Skip to content

The one and only agent harness for complex codebases. Project memory, planning, execution, and verified completion inside Codex.

chore: sync Codex marketplace v4.18.1

github-actions[bot]098177c52a4f
diff --git a/plugins/omo/.codex-plugin/plugin.json b/plugins/omo/.codex-plugin/plugin.json
index 09ccc190..93a6d1b0 100644
--- a/plugins/omo/.codex-plugin/plugin.json
+++ b/plugins/omo/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "omo",
- "version": "4.18.0",
+ "version": "4.18.1",
"description": "One Codex plugin namespace for Yeongyu's local Codex components.",
"author": {
"name": "Yeongyu Kim",
diff --git a/plugins/omo/components/bootstrap/hooks/hooks.json b/plugins/omo/components/bootstrap/hooks/hooks.json
index d6c40efb..9e975dd5 100644
--- a/plugins/omo/components/bootstrap/hooks/hooks.json
+++ b/plugins/omo/components/bootstrap/hooks/hooks.json
@@ -8,7 +8,7 @@
"command": "node \"${PLUGIN_ROOT}/components/bootstrap/dist/cli.js\" hook session-start",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\bootstrap.ps1\"",
"timeout": 30,
- "statusMessage": "(OmO 4.18.0) Checking Bootstrap Provisioning"
+ "statusMessage": "(OmO 4.18.1) Checking Bootstrap Provisioning"
}
]
}
diff --git a/plugins/omo/components/bootstrap/package.json b/plugins/omo/components/bootstrap/package.json
index 1b1fd1ce..143fb0ac 100644
--- a/plugins/omo/components/bootstrap/package.json
+++ b/plugins/omo/components/bootstrap/package.json
@@ -1,6 +1,6 @@
{
"name": "@sisyphuslabs/codex-bootstrap",
- "version": "4.18.0",
+ "version": "4.18.1",
"description": "Codex SessionStart bootstrap component that provisions LazyCodex runtime dependencies from a detached worker.",
"type": "module",
"private": true,
diff --git a/plugins/omo/components/codegraph/package.json b/plugins/omo/components/codegraph/package.json
index 063b3daf..41a9c302 100644
--- a/plugins/omo/components/codegraph/package.json
+++ b/plugins/omo/components/codegraph/package.json
@@ -1,6 +1,6 @@
{
"name": "@sisyphuslabs/codex-codegraph",
- "version": "4.18.0",
+ "version": "4.18.1",
"description": "Codex plugin MCP wrapper for CodeGraph.",
"type": "module",
"private": true,
diff --git a/plugins/omo/components/comment-checker/hooks/hooks.json b/plugins/omo/components/comment-checker/hooks/hooks.json
index 08c7102e..518d6c07 100644
--- a/plugins/omo/components/comment-checker/hooks/hooks.json
+++ b/plugins/omo/components/comment-checker/hooks/hooks.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use",
"timeout": 30,
- "statusMessage": "(OmO 4.18.0) Checking Comments"
+ "statusMessage": "(OmO 4.18.1) Checking Comments"
}
]
}
diff --git a/plugins/omo/components/comment-checker/package.json b/plugins/omo/components/comment-checker/package.json
index dfd7f96e..b1426649 100644
--- a/plugins/omo/components/comment-checker/package.json
+++ b/plugins/omo/components/comment-checker/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-comment-checker",
- "version": "4.18.0",
+ "version": "4.18.1",
"description": "Codex plugin that runs comment-checker after edit-like PostToolUse hooks.",
"type": "module",
"packageManager": "[email protected]",
diff --git a/plugins/omo/components/git-bash/hooks/hooks.json b/plugins/omo/components/git-bash/hooks/hooks.json
index df99aee3..a4e874d6 100644
--- a/plugins/omo/components/git-bash/hooks/hooks.json
+++ b/plugins/omo/components/git-bash/hooks/hooks.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Recommending Git Bash MCP"
+ "statusMessage": "(OmO 4.18.1) Recommending Git Bash MCP"
}
]
}
@@ -20,7 +20,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Resetting Git Bash MCP Reminder"
+ "statusMessage": "(OmO 4.18.1) Resetting Git Bash MCP Reminder"
}
]
}
diff --git a/plugins/omo/components/git-bash/package.json b/plugins/omo/components/git-bash/package.json
index 7fcc10b0..0c4c0428 100644
--- a/plugins/omo/components/git-bash/package.json
+++ b/plugins/omo/components/git-bash/package.json
@@ -1,6 +1,6 @@
{
"name": "@sisyphuslabs/codex-git-bash-hook",
- "version": "4.18.0",
+ "version": "4.18.1",
"description": "Codex hook component that reminds Windows sessions to prefer the OMO git_bash MCP.",
"type": "module",
"private": true,
diff --git a/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json b/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json
index 347fd177..fcf815d8 100644
--- a/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json
+++ b/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/lazycodex-executor-verify/dist/cli.js\" hook subagent-stop",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Verifying LazyCodex Executor Evidence"
+ "statusMessage": "(OmO 4.18.1) Verifying LazyCodex Executor Evidence"
}
]
}
diff --git a/plugins/omo/components/lazycodex-executor-verify/package.json b/plugins/omo/components/lazycodex-executor-verify/package.json
index 78e01938..6e117d89 100644
--- a/plugins/omo/components/lazycodex-executor-verify/package.json
+++ b/plugins/omo/components/lazycodex-executor-verify/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-lazycodex-executor-verify",
- "version": "4.18.0",
+ "version": "4.18.1",
"description": "Codex SubagentStop evidence verifier for LazyCodex executor completions.",
"type": "module",
"packageManager": "[email protected]",
diff --git a/plugins/omo/components/lsp-daemon/dist/cli.js b/plugins/omo/components/lsp-daemon/dist/cli.js
index 0d53f640..8c4b148b 100644
--- a/plugins/omo/components/lsp-daemon/dist/cli.js
+++ b/plugins/omo/components/lsp-daemon/dist/cli.js
@@ -3,6 +3,10 @@
// src/cli.ts
import { argv, stderr } from "node:process";
+// src/proxy.ts
+import { existsSync as existsSync11, realpathSync as realpathSync4 } from "node:fs";
+import { basename as basename3, delimiter as delimiter4, dirname as dirname9, isAbsolute as isAbsolute4 } from "node:path";
+
// ../mcp-stdio-core/src/record.ts
function isPlainRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -17,9 +21,6 @@ function errorResponse(id, code, message, data) {
function jsonRpcId(value) {
return typeof value === "string" || typeof value === "number" || value === null ? value : null;
}
-function messageFromError(error) {
- return error instanceof Error ? error.message : String(error);
-}
// ../mcp-stdio-core/src/transport.ts
var HEADER_SEPARATOR = Buffer.from(`\r
\r
@@ -206,37 +207,187 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {
closed: () => isClosed
};
}
-// ../lsp-core/src/tools/diagnostics.ts
-import { resolve as resolve4 } from "node:path";
-
// ../lsp-core/src/lsp/client-wrapper.ts
-import { existsSync as existsSync5, statSync as statSync2 } from "node:fs";
-import { dirname as dirname2, join as join5, resolve as resolve2 } from "node:path";
+import { existsSync as existsSync9, statSync as statSync3 } from "node:fs";
+import { dirname as dirname6, join as join4, resolve as resolve7 } from "node:path";
// ../lsp-core/src/request-context.ts
import { AsyncLocalStorage } from "node:async_hooks";
+import { existsSync, realpathSync, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from "node:path";
+
+class LspRequestContextParseError extends Error {
+ code;
+ name = "LspRequestContextParseError";
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ }
+}
+
+class LspRequestContextUnavailableError extends Error {
+ name = "LspRequestContextUnavailableError";
+ constructor() {
+ super("LSP request context is required. Standalone MCP startup must install one with runWithRequestContext(createStandaloneMcpRequestContext()).");
+ }
+}
var storage = new AsyncLocalStorage;
+var CONTEXT_FIELDS = new Set(["cwd", "projectConfigPaths", "userConfigPath", "installDecisionsPath", "capabilities"]);
+var CAPABILITY_FIELDS = new Set(["installDecisionTool"]);
function runWithRequestContext(context, fn) {
return storage.run(context, fn);
}
+function lspRequestContext() {
+ const context = storage.getStore();
+ if (!context)
+ throw new LspRequestContextUnavailableError;
+ return context;
+}
function contextCwd() {
- return storage.getStore()?.cwd ?? process.cwd();
+ return lspRequestContext().cwd;
+}
+function createStandaloneMcpRequestContext(input = {}) {
+ const env = input.env ?? process.env;
+ const cwd = canonicalCwd(input.cwd ?? process.cwd());
+ const home = input.homeDir ?? homedir();
+ const projectConfigPaths = translateProjectConfigEnv(env["LSP_TOOLS_MCP_PROJECT_CONFIG"], cwd);
+ const userConfigPath = translateHomeConfigEnv(env["LSP_TOOLS_MCP_USER_CONFIG"], home, ".codex/lsp-client.json");
+ const installDecisionsPath = translateHomeConfigEnv(env["LSP_TOOLS_MCP_INSTALL_DECISIONS"], home, ".codex/lsp-install-decisions.json");
+ return parseLspRequestContext({
+ cwd,
+ projectConfigPaths,
+ userConfigPath,
+ installDecisionsPath,
+ capabilities: { installDecisionTool: true }
+ });
+}
+function parseLspRequestContext(value) {
+ if (!isRecord(value)) {
+ throw new LspRequestContextParseError("invalid_context", "LSP request context must be an object.");
+ }
+ rejectUnknownFields(value, CONTEXT_FIELDS, "context");
+ const cwd = stringField(value, "cwd");
+ const projectConfigPaths = stringArrayField(value, "projectConfigPaths");
+ const userConfigPath = stringField(value, "userConfigPath");
+ const installDecisionsPath = stringField(value, "installDecisionsPath");
+ const capabilities = capabilitiesField(value["capabilities"]);
+ const canonical = canonicalCwd(cwd);
+ for (const path of projectConfigPaths) {
+ requireAbsolutePath(path, "projectConfigPaths");
+ const projectPath = canonicalizeExistingOrNearestAncestor(path);
+ if (!isPathInside(canonical, projectPath)) {
+ throw new LspRequestContextParseError("project_config_outside_cwd", `Project LSP config path must be inside cwd: ${path}`);
+ }
+ }
+ requireAbsolutePath(userConfigPath, "userConfigPath");
+ requireAbsolutePath(installDecisionsPath, "installDecisionsPath");
+ return {
+ cwd: canonical,
+ projectConfigPaths: projectConfigPaths.map((path) => canonicalizeExistingOrNearestAncestor(path)),
+ userConfigPath,
+ installDecisionsPath,
+ capabilities
+ };
+}
+function translateProjectConfigEnv(value, cwd) {
+ if (value === undefined || value.length === 0)
+ return [join(cwd, ".codex", "lsp-client.json")];
+ return value.split(delimiter).filter((entry) => entry.length > 0).map((entry) => isAbsolute(entry) ? entry : join(cwd, entry));
+}
+function translateHomeConfigEnv(value, home, fallback) {
+ if (value === undefined || value.length === 0)
+ return join(home, fallback);
+ return isAbsolute(value) ? value : join(home, value);
+}
+function canonicalCwd(cwd) {
+ const resolved = resolve(cwd);
+ if (!existsSync(resolved) || !statSync(resolved).isDirectory()) {
+ throw new LspRequestContextParseError("invalid_cwd", `LSP request cwd must be an existing directory: ${cwd}`);
+ }
+ return realpathSync(resolved);
+}
+function canonicalizeExistingOrNearestAncestor(path) {
+ let current = resolve(path);
+ const suffix = [];
+ while (true) {
+ try {
+ const existing = realpathSync(current);
+ return suffix.length === 0 ? existing : join(existing, ...suffix);
+ } catch (error) {
+ if (!isMissingPathError(error))
+ throw error;
+ const parent = dirname(current);
+ if (parent === current)
+ throw error;
+ suffix.unshift(basename(current));
+ current = parent;
+ }
+ }
+}
+function capabilitiesField(value) {
+ if (!isRecord(value)) {
+ throw new LspRequestContextParseError("invalid_capabilities", "LSP request capabilities must be an object.");
+ }
+ rejectUnknownFields(value, CAPABILITY_FIELDS, "capabilities");
+ const installDecisionTool = value["installDecisionTool"];
+ if (typeof installDecisionTool !== "boolean") {
+ throw new LspRequestContextParseError("invalid_install_decision_capability", "LSP request capabilities.installDecisionTool must be a boolean.");
+ }
+ return { installDecisionTool };
+}
+function stringField(value, field) {
+ const fieldValue = value[field];
+ if (typeof fieldValue !== "string" || fieldValue.length === 0) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string.`);
+ }
+ return fieldValue;
+}
+function stringArrayField(value, field) {
+ const fieldValue = value[field];
+ if (!Array.isArray(fieldValue) || !fieldValue.every((item) => typeof item === "string" && item.length > 0)) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string array.`);
+ }
+ return fieldValue;
+}
+function requireAbsolutePath(path, field) {
+ if (!isAbsolute(path)) {
+ throw new LspRequestContextParseError("relative_path", `LSP request context.${field} must be absolute: ${path}`);
+ }
}
-function contextEnv(key) {
- const store = storage.getStore();
- if (store?.env)
- return store.env[key];
- return process.env[key];
+function isPathInside(parent, child) {
+ const childPath = resolve(child);
+ const relativePath = relative(parent, childPath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute(relativePath);
+}
+function isMissingPathError(error) {
+ const code = errorCode(error);
+ return code === "ENOENT" || code === "ENOTDIR";
+}
+function rejectUnknownFields(value, allowed, scope) {
+ const unknown = Object.keys(value).filter((key) => !allowed.has(key));
+ if (unknown.length > 0) {
+ throw new LspRequestContextParseError("unknown_field", `Unknown LSP request ${scope} field: ${unknown.join(", ")}`);
+ }
+}
+function isRecord(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function errorCode(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
}
// ../lsp-core/src/lsp/effective-extension.ts
-import { basename, extname } from "node:path";
+import { basename as basename2, extname } from "node:path";
var BASENAME_EXTENSIONS = {
Dockerfile: ".dockerfile",
Containerfile: ".dockerfile"
};
function effectiveExtension(filePath) {
- return BASENAME_EXTENSIONS[basename(filePath)] ?? extname(filePath);
+ return BASENAME_EXTENSIONS[basename2(filePath)] ?? extname(filePath);
}
// ../lsp-core/src/lsp/errors.ts
@@ -286,7 +437,12 @@ class LspInvalidPathError extends Error {
}
class LspServerLookupError extends Error {
+ lookup;
name = "LspServerLookupError";
+ constructor(message, lookup) {
+ super(message);
+ this.lookup = lookup;
+ }
}
class LspServerInitializingError extends Error {
@@ -306,17 +462,18 @@ function isLspDeadConnectionError(err) {
}
// ../lsp-core/src/lsp/cleanup-errors.ts
-function reportBestEffortCleanupError(operation, error) {
- if (process.env["CODEX_LSP_DEBUG_CLEANUP"] !== "1")
- return;
+function writeCleanupError(message) {
+ process.stderr.write(`${message}
+`);
+}
+function reportBestEffortCleanupError(operation, error, logger = writeCleanupError) {
const message = error instanceof Error ? error.message : String(error);
- console.error(`[codex-lsp] ignored ${operation} failure during cleanup: ${message}`);
+ logger(`[lsp] ignored ${operation} failure during cleanup: ${message}`);
}
// ../lsp-core/src/lsp/client.ts
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
-import { pathToFileURL as pathToFileURL2 } from "node:url";
+import { resolve as resolve6 } from "node:path";
+import { pathToFileURL as pathToFileURL3 } from "node:url";
// ../lsp-core/src/lsp/connection.ts
import { pathToFileURL } from "node:url";
@@ -380,28 +537,80 @@ class JsonRpcConnection {
onError(handler) {
this.errorHandlers.push(handler);
}
- async sendRequest(method, params) {
+ async sendRequest(method, params, options = {}) {
if (this.disposed)
throw new Error("JSON-RPC connection is disposed");
const id = this.nextRequestId;
this.nextRequestId += 1;
+ const key = String(id);
const message = params === undefined ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
- const responsePromise = new Promise((resolve, reject) => {
- this.pendingRequests.set(String(id), {
+ let requestWritten = false;
+ let cancelAfterWrite = false;
+ let settled = false;
+ const writeCancel = () => this.writeMessage({ jsonrpc: "2.0", method: "$/cancelRequest", params: { id } });
+ const responsePromise = new Promise((resolve2, reject) => {
+ const cleanup = () => {
+ options.signal?.removeEventListener("abort", onAbort);
+ };
+ const settleCancel = () => {
+ if (settled)
+ return;
+ settled = true;
+ this.pendingRequests.delete(key);
+ cleanup();
+ const rejectCancelled = () => reject(abortError(options.signal));
+ if (!requestWritten) {
+ cancelAfterWrite = true;
+ rejectCancelled();
+ return;
+ }
+ writeCancel().then(rejectCancelled, (error) => {
+ this.emitError(toError(error));
+ rejectCancelled();
+ });
+ };
+ const onAbort = () => settleCancel();
+ this.pendingRequests.set(key, {
resolve(result) {
- resolve(result);
+ settled = true;
+ cleanup();
+ resolve2(result);
+ },
+ reject(error) {
+ settled = true;
+ cleanup();
+ reject(error);
},
- reject
+ cleanup
});
+ if (options.signal?.aborted) {
+ settleCancel();
+ return;
+ }
+ options.signal?.addEventListener("abort", onAbort, { once: true });
});
+ if (settled)
+ return responsePromise;
try {
await this.writeMessage(message);
+ requestWritten = true;
+ if (cancelAfterWrite)
+ await writeCancel();
} catch (error) {
- this.pendingRequests.delete(String(id));
+ if (settled)
+ return responsePromise;
+ const pending = this.pendingRequests.get(key);
+ if (pending) {
+ pending.cleanup();
+ this.pendingRequests.delete(key);
+ }
throw error;
}
return responsePromise;
}
+ pendingRequestCount() {
+ return this.pendingRequests.size;
+ }
async sendNotification(method, params) {
if (this.disposed)
return;
@@ -418,6 +627,7 @@ class JsonRpcConnection {
this.reader.off("error", this.handleStreamError);
this.writer.off("error", this.handleStreamError);
for (const pending of this.pendingRequests.values()) {
+ pending.cleanup();
pending.reject(new Error("JSON-RPC connection disposed"));
}
this.pendingRequests.clear();
@@ -493,6 +703,7 @@ class JsonRpcConnection {
if (!pending)
return;
this.pendingRequests.delete(String(id));
+ pending.cleanup();
if ("error" in message) {
pending.reject(jsonRpcErrorToError(message["error"]));
return;
@@ -506,7 +717,11 @@ class JsonRpcConnection {
try {
handler(params);
} catch (error) {
- this.emitError(toError(error));
+ if (error instanceof Error) {
+ this.emitError(error);
+ return;
+ }
+ this.emitError(new Error(String(error)));
}
}
handleRequest(message) {
@@ -531,13 +746,13 @@ class JsonRpcConnection {
const payload = `Content-Length: ${Buffer.byteLength(body, "utf8")}\r
\r
${body}`;
- return new Promise((resolve, reject) => {
+ return new Promise((resolve2, reject) => {
this.writer.write(payload, (error) => {
if (error) {
reject(error);
return;
}
- resolve();
+ resolve2();
});
});
}
@@ -547,6 +762,14 @@ ${body}`;
}
}
}
+function abortError(signal) {
+ const reason = signal?.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "LSP request cancelled");
+ error.name = "AbortError";
+ return error;
+}
function parseContentLength2(headers) {
for (const line of headers.split(`\r
`)) {
@@ -586,8 +809,8 @@ function toError(error) {
// ../lsp-core/src/lsp/process.ts
import { spawn, spawnSync } from "node:child_process";
-import { existsSync, statSync } from "node:fs";
-import { delimiter, join } from "node:path";
+import { existsSync as existsSync2, statSync as statSync2 } from "node:fs";
+import { delimiter as delimiter2, join as join2 } from "node:path";
function isMissingProcessError(error) {
if (!(error instanceof Error) || !("code" in error))
return false;
@@ -600,10 +823,10 @@ function reportKillError(context, error) {
}
function validateCwd(cwd) {
try {
- if (!existsSync(cwd)) {
+ if (!existsSync2(cwd)) {
return { valid: false, error: `Working directory does not exist: ${cwd}` };
}
- const stats = statSync(cwd);
+ const stats = statSync2(cwd);
if (!stats.isDirectory()) {
return { valid: false, error: `Path is not a directory: ${cwd}` };
}
@@ -616,9 +839,9 @@ function validateCwd(cwd) {
}
}
function wrap(proc) {
- const exitedPromise = new Promise((resolve) => {
- proc.once("close", (code) => resolve(code ?? 0));
- proc.once("error", () => resolve(1));
+ const exitedPromise = new Promise((resolve2) => {
+ proc.once("close", (code) => resolve2(code ?? 0));
+ proc.once("error", () => resolve2(1));
});
if (!proc.stdin || !proc.stdout || !proc.stderr) {
throw new LspProcessSpawnError("Spawned process is missing one of stdin/stdout/stderr pipes");
@@ -672,7 +895,7 @@ function isWindowsShellShim(command) {
return lowerCommand.endsWith(".cmd") || lowerCommand.endsWith(".bat");
}
function splitPath(pathValue, platform) {
- const separator = platform === "win32" ? ";" : delimiter;
+ const separator = platform === "win32" ? ";" : delimiter2;
return pathValue.split(separator).filter(Boolean);
}
function getWindowsPathExtensions(env) {
@@ -687,8 +910,8 @@ function resolveWindowsCommand(command, env) {
const extensions = getWindowsPathExtensions(env);
for (const baseDirectory of baseDirectories) {
for (const extension of extensions) {
- const candidate = baseDirectory ? join(baseDirectory, `${command}${extension}`) : `${command}${extension}`;
- if (existsSync(candidate))
+ const candidate = baseDirectory ? join2(baseDirectory, `${command}${extension}`) : `${command}${extension}`;
+ if (existsSync2(candidate))
return candidate;
}
}
@@ -733,16 +956,16 @@ function spawnProcess(command, options) {
return wrap(proc);
}
-// ../lsp-core/src/lsp/transport.ts
-function isRecord(value) {
+// ../lsp-core/src/lsp/transport-protocol.ts
+function isRecord2(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function parseConfigurationItems(params) {
- if (!isRecord(params) || !Array.isArray(params["items"]))
+ if (!isRecord2(params) || !Array.isArray(params["items"]))
return [];
const items = [];
for (const item of params["items"]) {
- if (!isRecord(item))
+ if (!isRecord2(item))
continue;
const section = item["section"];
items.push(section === undefined || typeof section !== "string" ? {} : { section });
@@ -750,10 +973,35 @@ function parseConfigurationItems(params) {
return items;
}
function parseDiagnosticsParams(params) {
- if (!isRecord(params) || typeof params["uri"] !== "string")
+ if (!isRecord2(params) || typeof params["uri"] !== "string")
return null;
const diagnostics = Array.isArray(params["diagnostics"]) ? params["diagnostics"].filter(isDiagnostic) : [];
- return { uri: params["uri"], diagnostics };
+ const version = typeof params["version"] === "number" ? params["version"] : undefined;
+ return { uri: params["uri"], diagnostics, ...version === undefined ? {} : { version } };
+}
+function createLspSpawnEnv(_root, input) {
+ return { ...input };
+}
+function isDiagnostic(value) {
+ return isRecord2(value) && isRange(value["range"]) && typeof value["message"] === "string";
+}
+function isRange(value) {
+ return isRecord2(value) && isPosition(value["start"]) && isPosition(value["end"]);
+}
+function isPosition(value) {
+ return isRecord2(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+}
+
+// ../lsp-core/src/lsp/transport.ts
+class LspClientNotStartedError extends Error {
+ serverId;
+ root;
+ name = "LspClientNotStartedError";
+ constructor(serverId, root) {
+ super("LSP client not started");
+ this.serverId = serverId;
+ this.root = root;
+ }
}
class LspClientTransport {
@@ -766,6 +1014,8 @@ class LspClientTransport {
diagnosticsStore = new Map;
requestTimeoutMs;
initializeTimeoutMs;
+ workspaceApplyEditHandler = null;
+ diagnosticPullSupported = false;
constructor(root, server2, timeouts = {}) {
this.root = root;
this.server = server2;
@@ -778,6 +1028,21 @@ class LspClientTransport {
command() {
return [...this.server.command];
}
+ setWorkspaceApplyEditHandler(handler) {
+ this.workspaceApplyEditHandler = handler;
+ }
+ hasWorkspaceApplyEditHandler() {
+ return this.workspaceApplyEditHandler !== null;
+ }
+ setDiagnosticPullSupported(supported) {
+ this.diagnosticPullSupported = supported;
+ }
+ isDiagnosticPullSupported() {
+ return this.diagnosticPullSupported;
+ }
+ handlePublishDiagnostics(params) {
+ this.diagnosticsStore.set(params.uri, [...params.diagnostics]);
+ }
async start() {
const env = createLspSpawnEnv(this.root, {
...process.env,
@@ -788,7 +1053,6 @@ class LspClientTransport {
env
});
this.startStderrReading();
- await new Promise((resolve) => setTimeout(resolve, 100));
if (this.proc.exitCode !== null) {
const stderr = this.stderrBuffer.join(`
`);
@@ -798,7 +1062,7 @@ class LspClientTransport {
this.connection.onNotification("textDocument/publishDiagnostics", (params) => {
const diagnosticsParams = parseDiagnosticsParams(params);
if (diagnosticsParams?.uri) {
- this.diagnosticsStore.set(diagnosticsParams.uri, diagnosticsParams.diagnostics);
+ this.handlePublishDiagnostics(diagnosticsParams);
}
});
this.connection.onRequest("workspace/configuration", (params) => {
@@ -811,6 +1075,9 @@ class LspClientTransport {
});
this.connection.onRequest("client/registerCapability", () => null);
this.connection.onRequest("window/workDoneProgress/create", () => null);
+ if (this.workspaceApplyEditHandler) {
+ this.connection.onRequest("workspace/applyEdit", this.workspaceApplyEditHandler);
+ }
this.connection.onClose(() => {
this.processExited = true;
});
@@ -839,30 +1106,25 @@ class LspClientTransport {
}
async sendRequest(method, ...args) {
if (!this.connection)
- throw new Error("LSP client not started");
+ throw new LspClientNotStartedError(this.server.id, this.root);
if (this.processExited || this.proc && this.proc.exitCode !== null) {
const stderrTail = this.stderrBuffer.slice(-10).join(`
`);
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, stderrTail || undefined);
}
- const timeoutMs = args[1]?.timeoutMs ?? this.requestTimeoutMs;
- let timeoutHandle = null;
- const timeoutPromise = new Promise((_, reject) => {
- timeoutHandle = setTimeout(() => {
- const stderrTail = this.stderrBuffer.slice(-5).join(`
+ const options = args[1];
+ const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
+ const timeoutController = new AbortController;
+ const timeoutHandle = setTimeout(() => {
+ const stderrTail = this.stderrBuffer.slice(-5).join(`
`);
- reject(new LspRequestTimeoutError(method, stderrTail || undefined));
- }, timeoutMs);
- });
+ timeoutController.abort(new LspRequestTimeoutError(method, stderrTail || undefined));
+ }, timeoutMs);
+ const combinedSignal = combineAbortSignals(options?.signal, timeoutController.signal);
try {
- const requestPromise = args.length === 0 ? this.connection.sendRequest(method) : this.connection.sendRequest(method, args[0]);
- const result = await Promise.race([requestPromise, timeoutPromise]);
- if (timeoutHandle !== null)
- clearTimeout(timeoutHandle);
+ const result = args.length === 0 ? await this.connection.sendRequest(method, undefined, { signal: combinedSignal.signal }) : await this.connection.sendRequest(method, args[0], { signal: combinedSignal.signal });
return result;
} catch (error) {
- if (timeoutHandle !== null)
- clearTimeout(timeoutHandle);
if (this.processExited || this.proc && this.proc.exitCode !== null) {
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, this.stderrBuffer.slice(-10).join(`
`) || undefined);
@@ -871,6 +1133,9 @@ class LspClientTransport {
throw new LspConnectionClosedError(this.server.id, this.root, error.message);
}
throw error;
+ } finally {
+ clearTimeout(timeoutHandle);
+ combinedSignal.dispose();
}
}
async sendNotification(method, ...args) {
@@ -899,17 +1164,17 @@ class LspClientTransport {
try {
await this.sendRequest("shutdown");
} catch (error) {
- reportBestEffortCleanupError("shutdown request", error);
+ reportBestEffortCleanupError("shutdown request", error instanceof Error ? error : String(error));
}
try {
await this.sendNotification("exit");
} catch (error) {
- reportBestEffortCleanupError("exit notification", error);
+ reportBestEffortCleanupError("exit notification", error instanceof Error ? error : String(error));
}
try {
this.connection.dispose();
} catch (error) {
- reportBestEffortCleanupError("connection dispose", error);
+ reportBestEffortCleanupError("connection dispose", error instanceof Error ? error : String(error));
}
this.connection = null;
}
@@ -920,8 +1185,8 @@ class LspClientTransport {
try {
proc.kill();
let timeoutId;
- const timeoutPromise = new Promise((resolve) => {
- timeoutId = setTimeout(resolve, STOP_HARD_KILL_TIMEOUT_MS);
+ const timeoutPromise = new Promise((resolve2) => {
+ timeoutId = setTimeout(resolve2, STOP_HARD_KILL_TIMEOUT_MS);
});
await Promise.race([
proc.exited.then(() => {
@@ -937,14 +1202,14 @@ class LspClientTransport {
proc.kill("SIGKILL");
await Promise.race([
proc.exited,
- new Promise((resolve) => setTimeout(resolve, STOP_SIGKILL_GRACE_MS))
+ new Promise((resolve2) => setTimeout(resolve2, STOP_SIGKILL_GRACE_MS))
]);
} catch (error) {
- reportBestEffortCleanupError("hard process kill", error);
+ reportBestEffortCleanupError("hard process kill", error instanceof Error ? error : String(error));
}
}
} catch (error) {
- reportBestEffortCleanupError("process stop", error);
+ reportBestEffortCleanupError("process stop", error instanceof Error ? error : String(error));
}
}
this.processExited = true;
@@ -954,26 +1219,45 @@ class LspClientTransport {
return this.diagnosticsStore.get(uri) ?? [];
}
}
-function createLspSpawnEnv(_root, input) {
- return { ...input };
-}
-function isDiagnostic(value) {
- return isRecord(value) && isRange(value["range"]) && typeof value["message"] === "string";
-}
-function isRange(value) {
- return isRecord(value) && isPosition(value["start"]) && isPosition(value["end"]);
-}
-function isPosition(value) {
- return isRecord(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+function combineAbortSignals(primary, secondary) {
+ const controller = new AbortController;
+ const abortFrom = (signal) => {
+ if (!controller.signal.aborted)
+ controller.abort(signal.reason);
+ };
+ const onPrimaryAbort = () => {
+ if (primary)
+ abortFrom(primary);
+ };
+ const onSecondaryAbort = () => abortFrom(secondary);
+ if (primary?.aborted)
+ abortFrom(primary);
+ else
+ primary?.addEventListener("abort", onPrimaryAbort, { once: true });
+ if (secondary.aborted)
+ abortFrom(secondary);
+ else
+ secondary.addEventListener("abort", onSecondaryAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => {
+ primary?.removeEventListener("abort", onPrimaryAbort);
+ secondary.removeEventListener("abort", onSecondaryAbort);
+ }
+ };
}
// ../lsp-core/src/lsp/connection.ts
-var INITIALIZE_SETTLE_MS = 300;
+function supportsDiagnosticPull(capabilities) {
+ if (capabilities === undefined)
+ return false;
+ return Object.hasOwn(capabilities, "diagnosticProvider");
+}
class LspClientConnection extends LspClientTransport {
async initialize() {
const rootUri = pathToFileURL(this.root).href;
- await this.sendRequest("initialize", {
+ const result = await this.sendRequest("initialize", {
processId: process.pid,
rootUri,
rootPath: this.root,
@@ -987,8 +1271,7 @@ class LspClientConnection extends LspClientTransport {
publishDiagnostics: {},
rename: {
prepareSupport: true,
- prepareSupportDefaultBehavior: 1,
- honorsChangeAnnotations: true
+ prepareSupportDefaultBehavior: 1
},
codeAction: {
codeActionLiteralSupport: {
@@ -1017,22 +1300,28 @@ class LspClientConnection extends LspClientTransport {
symbol: {},
workspaceFolders: true,
configuration: true,
- applyEdit: true,
+ ...this.hasWorkspaceApplyEditHandler() ? { applyEdit: true } : {},
workspaceEdit: {
- documentChanges: true
+ documentChanges: true,
+ resourceOperations: ["create", "rename", "delete"]
}
}
},
initializationOptions: this.server.initialization
}, { timeoutMs: this.initializeTimeoutMs });
+ this.setDiagnosticPullSupported(supportsDiagnosticPull(result?.capabilities));
await this.sendNotification("initialized");
await this.sendNotification("workspace/didChangeConfiguration", {
settings: { json: { validate: { enable: true } } }
});
- await new Promise((r) => setTimeout(r, INITIALIZE_SETTLE_MS));
}
}
+// ../lsp-core/src/lsp/workspace-document-state.ts
+import { readFileSync, realpathSync as realpathSync2 } from "node:fs";
+import { relative as relative2, resolve as resolve2 } from "node:path";
+import { pathToFileURL as pathToFileURL2 } from "node:url";
+
// ../lsp-core/src/lsp/language-mappings.ts
var SYMBOL_KIND_MAP = {
1: "File",
@@ -1205,164 +1494,1635 @@ function getLanguageId(ext) {
return EXT_TO_LANG[ext] ?? "plaintext";
}
-// ../lsp-core/src/lsp/client.ts
-var POST_OPEN_DELAY_MS = 1000;
-var POST_DIAGNOSTICS_WAIT_MS = 500;
+// ../lsp-core/src/lsp/workspace-document-state.ts
+var WATCHED_FILE_BATCH_SIZE = 128;
+var DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
+function canonicalPath(filePath) {
+ const absolute = resolve2(filePath);
+ try {
+ return realpathSync2(absolute);
+ } catch {
+ return absolute;
+ }
+}
+function isSameOrDescendant(candidate, parent) {
+ const suffix = relative2(parent, candidate);
+ return suffix === "" || !suffix.startsWith("..") && suffix !== "..";
+}
+function movedPath(candidate, oldPath, newPath) {
+ const suffix = relative2(oldPath, candidate);
+ return suffix === "" ? newPath : resolve2(newPath, suffix);
+}
-class LspClient extends LspClientConnection {
- openedFiles = new Set;
- documentVersions = new Map;
- lastSyncedText = new Map;
- diagnosticPullErrors = [];
- getDiagnosticPullErrors() {
- return this.diagnosticPullErrors;
+class WorkspaceDocumentState {
+ sendNotification;
+ clearDiagnostics;
+ openDocuments = new Map;
+ openByUri = new Map;
+ openPromises = new Map;
+ now;
+ versionlessPublishQuiescenceMs;
+ constructor(sendNotification, clearDiagnostics, options = {}) {
+ this.sendNotification = sendNotification;
+ this.clearDiagnostics = clearDiagnostics;
+ this.now = options.now ?? (() => Date.now());
+ this.versionlessPublishQuiescenceMs = options.versionlessPublishQuiescenceMs ?? DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS;
}
async openFile(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- const uri = pathToFileURL2(absPath).href;
- const text = readFileSync(absPath, "utf-8");
- if (!this.openedFiles.has(absPath)) {
- const ext = effectiveExtension(absPath);
- const languageId = getLanguageId(ext);
- const version = 1;
- await this.sendNotification("textDocument/didOpen", {
- textDocument: {
- uri,
- languageId,
- version,
- text
- }
- });
- this.openedFiles.add(absPath);
- this.documentVersions.set(uri, version);
- this.lastSyncedText.set(uri, text);
- await new Promise((r) => setTimeout(r, POST_OPEN_DELAY_MS));
- return;
+ const path = canonicalPath(filePath);
+ const existingOpen = this.openPromises.get(path);
+ if (existingOpen) {
+ await existingOpen;
+ return this.openFile(path);
}
- const prevText = this.lastSyncedText.get(uri);
- if (prevText === text) {
+ const text = readFileSync(path, "utf-8");
+ const existing = this.openDocuments.get(path);
+ if (!existing)
+ return this.openDocumentSingleFlight(path, text);
+ if (existing.text === text)
return;
- }
- const nextVersion = (this.documentVersions.get(uri) ?? 1) + 1;
- this.documentVersions.set(uri, nextVersion);
- this.lastSyncedText.set(uri, text);
- await this.sendNotification("textDocument/didChange", {
- textDocument: { uri, version: nextVersion },
- contentChanges: [{ text }]
- });
- await this.sendNotification("textDocument/didSave", {
- textDocument: { uri },
- text
- });
+ await this.changeDocument(existing, text);
}
- async definition(filePath, line, character) {
- const absPath = resolve(contextCwd(), filePath);
- await this.openFile(absPath);
- return this.sendRequest("textDocument/definition", {
- textDocument: { uri: pathToFileURL2(absPath).href },
- position: { line: line - 1, character }
- });
+ getVersion(filePath) {
+ return this.openDocuments.get(canonicalPath(filePath))?.version;
}
- async references(filePath, line, character, includeDeclaration = true) {
- const absPath = resolve(contextCwd(), filePath);
- await this.openFile(absPath);
- return this.sendRequest("textDocument/references", {
- textDocument: { uri: pathToFileURL2(absPath).href },
- position: { line: line - 1, character },
- context: { includeDeclaration }
- });
+ getStoredDiagnostics(uri) {
+ const state = this.openByUri.get(uri);
+ if (!state)
+ return [];
+ return state.lastPublish?.diagnostics ?? state.pullCache?.diagnostics ?? [];
+ }
+ captureDiagnosticSnapshot(filePath) {
+ const state = this.openDocuments.get(canonicalPath(filePath));
+ if (!state)
+ return null;
+ return {
+ path: state.path,
+ uri: state.uri,
+ version: state.version,
+ documentGeneration: state.generation,
+ publishGeneration: state.publishGeneration
+ };
}
- async documentSymbols(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- await this.openFile(absPath);
- return this.sendRequest("textDocument/documentSymbol", {
- textDocument: { uri: pathToFileURL2(absPath).href }
- });
+ isCurrentSnapshot(snapshot) {
+ const state = this.openDocuments.get(snapshot.path);
+ return state !== undefined && state.uri === snapshot.uri && state.version === snapshot.version && state.generation === snapshot.documentGeneration;
}
- async workspaceSymbols(query) {
- return this.sendRequest("workspace/symbol", { query });
+ getPullCache(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.pullCache || state.pullCache.documentVersion !== snapshot.version)
+ return null;
+ return state.pullCache;
}
- isUnsupportedDiagnosticPullError(error) {
- if (!(error instanceof Error))
- return false;
- const code = "code" in error && typeof error.code === "number" ? error.code : undefined;
- if (code === -32601)
- return true;
- return /unsupported|not supported|method not found|unknown request/i.test(error.message);
+ recordPullDiagnostics(snapshot, report) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state)
+ return;
+ state.pullCache = {
+ documentVersion: snapshot.version,
+ diagnostics: [...report.diagnostics],
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ };
}
- async diagnostics(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- const uri = pathToFileURL2(absPath).href;
- await this.openFile(absPath);
- await new Promise((r) => setTimeout(r, POST_DIAGNOSTICS_WAIT_MS));
- try {
- const result = await this.sendRequest("textDocument/diagnostic", {
- textDocument: { uri }
- });
- if (result.items) {
- return { items: result.items };
+ recordPublishedDiagnostics(params) {
+ const state = this.openByUri.get(params.uri);
+ if (!state)
+ return;
+ state.publishGeneration += 1;
+ state.lastPublish = {
+ diagnostics: [...params.diagnostics],
+ publishGeneration: state.publishGeneration,
+ documentGenerationAtArrival: state.generation,
+ arrivedAt: this.now(),
+ ...params.version === undefined ? {} : { version: params.version }
+ };
+ this.notifyWaiters(state);
+ }
+ resolvePushDiagnostics(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.lastPublish)
+ return { status: "missing" };
+ const publish = state.lastPublish;
+ if (publish.version !== undefined) {
+ return publish.version === snapshot.version ? { status: "ready", diagnostics: publish.diagnostics } : { status: "missing" };
+ }
+ if (publish.documentGenerationAtArrival < snapshot.documentGeneration)
+ return { status: "missing" };
+ const readyAt = publish.arrivedAt + this.versionlessPublishQuiescenceMs;
+ const waitMs = Math.max(0, readyAt - this.now());
+ return waitMs === 0 ? { status: "ready", diagnostics: publish.diagnostics } : { status: "wait", waitMs };
+ }
+ waitForDiagnosticsActivity(snapshot, timeoutMs) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state || timeoutMs <= 0)
+ return Promise.resolve();
+ return new Promise((resolveActivity) => {
+ let settled = false;
+ const finish = () => {
+ if (settled)
+ return;
+ settled = true;
+ clearTimeout(timer);
+ state.waiters.delete(finish);
+ resolveActivity();
+ };
+ const timer = setTimeout(finish, timeoutMs);
+ if (typeof timer.unref === "function")
+ timer.unref();
+ state.waiters.add(finish);
+ });
+ }
+ validateVersions(operations) {
+ const versions = new Map([...this.openDocuments].map(([path, state]) => [path, state.version]));
+ for (const operation of operations) {
+ if (operation.kind === "text") {
+ const current = versions.get(operation.path);
+ if (operation.documentVersion !== null && current !== operation.documentVersion) {
+ const observed = current === undefined ? "closed document" : `open document version ${current}`;
+ return {
+ changeIndex: operation.changeIndex,
+ message: `document version ${operation.documentVersion} does not match ${observed} for ${operation.path}`
+ };
+ }
+ if (current !== undefined)
+ versions.set(operation.path, current + 1);
+ continue;
}
- } catch (error) {
- if (!this.isUnsupportedDiagnosticPullError(error)) {
- this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ if (operation.kind === "rename") {
+ const moved = [...versions].filter(([path]) => isSameOrDescendant(path, operation.oldPath));
+ for (const [path] of moved)
+ versions.delete(path);
+ for (const [path] of moved)
+ versions.set(movedPath(path, operation.oldPath, operation.newPath), 1);
+ continue;
+ }
+ if (operation.kind === "delete") {
+ for (const path of [...versions.keys()]) {
+ if (isSameOrDescendant(path, operation.path))
+ versions.delete(path);
+ }
+ continue;
+ }
+ if (operation.kind === "create" && operation.replaced && versions.has(operation.path)) {
+ versions.set(operation.path, 1);
}
}
- return { items: this.getStoredDiagnostics(uri) };
+ return null;
}
- async prepareRename(filePath, line, character) {
- const absPath = resolve(contextCwd(), filePath);
- await this.openFile(absPath);
- return this.sendRequest("textDocument/prepareRename", {
- textDocument: { uri: pathToFileURL2(absPath).href },
- position: { line: line - 1, character }
- });
+ async synchronize(delta) {
+ const watched = [];
+ for (const mutation of delta.operations)
+ await this.synchronizeMutation(mutation, watched);
+ for (let index = 0;index < watched.length; index += WATCHED_FILE_BATCH_SIZE) {
+ await this.sendNotification("workspace/didChangeWatchedFiles", {
+ changes: watched.slice(index, index + WATCHED_FILE_BATCH_SIZE)
+ });
+ }
}
- async rename(filePath, line, character, newName) {
- const absPath = resolve(contextCwd(), filePath);
- await this.openFile(absPath);
- return this.sendRequest("textDocument/rename", {
- textDocument: { uri: pathToFileURL2(absPath).href },
- position: { line: line - 1, character },
- newName
+ async synchronizeMutation(mutation, watched) {
+ if (mutation.kind === "text") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state)
+ await this.changeDocument(state, mutation.afterText);
+ else
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 2 });
+ return;
+ }
+ if (mutation.kind === "create") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state) {
+ await this.closeDocument(state);
+ await this.openDocumentSingleFlight(mutation.path, readFileSync(mutation.path, "utf-8"));
+ } else {
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: mutation.replaced ? 2 : 1 });
+ }
+ return;
+ }
+ if (mutation.kind === "rename") {
+ const moved = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.oldPath));
+ for (const state of moved)
+ await this.closeDocument(state);
+ for (const state of moved) {
+ const path = movedPath(state.path, mutation.oldPath, mutation.newPath);
+ await this.openDocumentSingleFlight(path, readFileSync(path, "utf-8"));
+ }
+ if (moved.length === 0) {
+ watched.push({ uri: pathToFileURL2(mutation.oldPath).href, type: 3 });
+ watched.push({ uri: pathToFileURL2(mutation.newPath).href, type: 1 });
+ }
+ return;
+ }
+ const removed = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.path));
+ for (const state of removed)
+ await this.closeDocument(state);
+ if (removed.length === 0)
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 3 });
+ }
+ async openDocumentSingleFlight(path, text) {
+ const existing = this.openPromises.get(path);
+ if (existing)
+ return existing;
+ const open = (async () => {
+ const state = {
+ path,
+ uri: pathToFileURL2(path).href,
+ languageId: getLanguageId(effectiveExtension(path)),
+ text,
+ version: 1,
+ generation: 1,
+ publishGeneration: 0,
+ waiters: new Set
+ };
+ this.openDocuments.set(path, state);
+ this.openByUri.set(state.uri, state);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didOpen", {
+ textDocument: { uri: state.uri, languageId: state.languageId, version: state.version, text }
+ });
+ })().finally(() => {
+ this.openPromises.delete(path);
+ });
+ this.openPromises.set(path, open);
+ return open;
+ }
+ async changeDocument(state, text) {
+ state.text = text;
+ state.version += 1;
+ state.generation += 1;
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didChange", {
+ textDocument: { uri: state.uri, version: state.version },
+ contentChanges: [{ text }]
});
+ await this.sendNotification("textDocument/didSave", { textDocument: { uri: state.uri }, text });
+ }
+ async closeDocument(state) {
+ this.openDocuments.delete(state.path);
+ this.openByUri.delete(state.uri);
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didClose", { textDocument: { uri: state.uri } });
+ }
+ notifyWaiters(state) {
+ for (const waiter of [...state.waiters])
+ waiter();
}
}
-// ../lsp-core/src/lsp/process-signal-cleanup.ts
-function installProcessSignalCleanup(cleanup) {
- const signals = process.platform === "win32" ? ["SIGINT", "SIGTERM", "SIGBREAK"] : ["SIGINT", "SIGTERM"];
- const handler = () => {
- cleanup().catch((error) => {
- reportBestEffortCleanupError("signal cleanup", error);
- });
- };
- for (const signal of signals) {
- process.on(signal, handler);
- }
- return () => {
- for (const signal of signals) {
- process.removeListener(signal, handler);
- }
- };
+// ../lsp-core/src/lsp/workspace-apply-edit-failure.ts
+var CONCURRENT_FAILURE_REASON_BY_PHASE = {
+ applying: "workspace/applyEdit is already in progress for this workspace mutation",
+ settled: "workspace/applyEdit was already handled for this workspace mutation"
+};
+function workspaceApplyEditConcurrentFailureReason(phase) {
+ return CONCURRENT_FAILURE_REASON_BY_PHASE[phase];
}
-// ../lsp-core/src/lsp/manager.ts
-async function stopClientBestEffort(client) {
+// ../lsp-core/src/lsp/workspace-edit-commit.ts
+import { existsSync as existsSync4, lstatSync as lstatSync2, renameSync, rmSync, writeFileSync } from "node:fs";
+
+// ../lsp-core/src/lsp/workspace-edit-path.ts
+import { existsSync as existsSync3, lstatSync, readFileSync as readFileSync2, readdirSync, realpathSync as realpathSync3 } from "node:fs";
+import { dirname as dirname2, isAbsolute as isAbsolute2, relative as relative3, resolve as resolve3 } from "node:path";
+import { fileURLToPath } from "node:url";
+
+class WorkspaceEditPathError extends Error {
+ path;
+ detail;
+ name = "WorkspaceEditPathError";
+ constructor(path, detail) {
+ super(`${detail}: ${path}`);
+ this.path = path;
+ this.detail = detail;
+ }
+}
+function isPathInsideWorkspace(filePath, workspaceRoot) {
+ const relativePath = relative3(workspaceRoot, filePath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute2(relativePath);
+}
+function canonicalizeMissingPath(filePath) {
+ let ancestor = filePath;
+ while (!existsSync3(ancestor)) {
+ const parent = dirname2(ancestor);
+ if (parent === ancestor)
+ throw new WorkspaceEditPathError(filePath, "no existing ancestor");
+ ancestor = parent;
+ }
+ return resolve3(realpathSync3(ancestor), relative3(ancestor, filePath));
+}
+function canonicalWorkspaceRoot(workspaceRoot) {
try {
- await client.stop();
+ const canonical = realpathSync3(resolve3(workspaceRoot));
+ if (!lstatSync(canonical).isDirectory()) {
+ return { success: false, error: `workspace root is not a directory: ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath: resolve3(workspaceRoot),
+ followedSymbolicLink: existsSync3(resolve3(workspaceRoot)) && lstatSync(resolve3(workspaceRoot)).isSymbolicLink()
+ };
} catch (error) {
- reportBestEffortCleanupError("client stop", error);
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `workspace root ${workspaceRoot}: ${detail}` };
}
}
-function awaitWithSignal(promise, signal) {
- if (!signal)
- return promise;
- return new Promise((resolve2, reject) => {
- let settled = false;
- const onAbort = () => {
- if (settled)
- return;
- settled = true;
+function uriToCanonicalWorkspacePath(uri, workspaceRoot) {
+ let requestedPath;
+ try {
+ const parsed = new URL(uri);
+ if (parsed.protocol !== "file:" || parsed.search !== "" || parsed.hash !== "") {
+ return { success: false, error: `non-file URI ${uri}` };
+ }
+ requestedPath = resolve3(fileURLToPath(parsed));
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `non-file URI ${uri}: ${detail}` };
+ }
+ try {
+ const canonical = existsSync3(requestedPath) ? realpathSync3(requestedPath) : canonicalizeMissingPath(requestedPath);
+ if (!isPathInsideWorkspace(canonical, workspaceRoot)) {
+ return { success: false, error: `${requestedPath}: outside workspace ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath,
+ followedSymbolicLink: existsSync3(requestedPath) && lstatSync(requestedPath).isSymbolicLink()
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `${requestedPath}: ${detail}` };
+ }
+}
+function snapshotPath(path, includeChildren) {
+ if (!existsSync3(path))
+ return { kind: "missing" };
+ const stats = lstatSync(path);
+ if (stats.isFile())
+ return { kind: "file", content: readFileSync2(path, "utf-8") };
+ if (stats.isDirectory()) {
+ return includeChildren ? { kind: "directory", children: readdirSync(path).sort() } : { kind: "directory" };
+ }
+ throw new WorkspaceEditPathError(path, "unsupported filesystem entry");
+}
+
+// ../lsp-core/src/lsp/workspace-edit-commit.ts
+var DEFAULT_IO = {
+ writeFile(path, content) {
+ writeFileSync(path, content, "utf-8");
+ },
+ rename(oldPath, newPath) {
+ renameSync(oldPath, newPath);
+ },
+ remove(path, recursive) {
+ rmSync(path, { recursive, force: false });
+ }
+};
+function snapshotsEqual(expected, actual) {
+ if (expected.kind !== actual.kind)
+ return false;
+ if (expected.kind === "file" && actual.kind === "file")
+ return expected.content === actual.content;
+ if (expected.kind === "directory" && actual.kind === "directory" && expected.children !== undefined) {
+ return JSON.stringify(expected.children) === JSON.stringify(actual.children);
+ }
+ return true;
+}
+function liveSnapshot(path, expected) {
+ return snapshotPath(path, expected.kind === "directory" && expected.children !== undefined);
+}
+function firstOperationIndex(plan) {
+ return plan.operations[0]?.changeIndex ?? 0;
+}
+function failedCommit(plan, failure) {
+ const { message, changeIndex, mutations = [], filesModified = [], totalEdits = 0, lateAbort = false } = failure;
+ return {
+ result: {
+ success: false,
+ filesModified,
+ totalEdits,
+ errors: [`change ${changeIndex}: ${message}`],
+ failedChange: changeIndex,
+ ...lateAbort ? { lateAbort: true } : {}
+ },
+ delta: mutationDelta(mutations),
+ fingerprint: plan.fingerprint
+ };
+}
+function verifySnapshots(plan) {
+ for (const [path, expected] of plan.snapshots) {
+ let actual;
+ try {
+ actual = liveSnapshot(path, expected);
+ } catch (error) {
+ const changeIndex = plan.firstChangeByPath.get(path) ?? firstOperationIndex(plan);
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, { message: `cannot verify snapshot for ${path}: ${detail}`, changeIndex });
+ }
+ if (!snapshotsEqual(expected, actual)) {
+ const changeIndex = plan.firstChangeByPath.get(path) ?? firstOperationIndex(plan);
+ return failedCommit(plan, { message: `workspace state changed before commit: ${path}`, changeIndex });
+ }
+ }
+ return null;
+}
+function addModifiedPath(paths, path) {
+ if (!paths.includes(path))
+ paths.push(path);
+}
+function reportedPath(plan, path) {
+ return plan.reportedPathByCanonical.get(path) ?? path;
+}
+function changedPathsForMutation(mutation) {
+ return mutation.kind === "rename" ? [mutation.oldPath, mutation.newPath] : [mutation.path];
+}
+function mutationDelta(operations) {
+ const changedPaths = new Set;
+ for (const operation of operations) {
+ for (const path of changedPathsForMutation(operation))
+ changedPaths.add(path);
+ }
+ return { operations, changedPaths: [...changedPaths].sort() };
+}
+function resolveIo(overrides) {
+ return {
+ writeFile: overrides?.writeFile ?? DEFAULT_IO.writeFile,
+ rename: overrides?.rename ?? DEFAULT_IO.rename,
+ remove: overrides?.remove ?? DEFAULT_IO.remove
+ };
+}
+function commitOperation(context, operation) {
+ const { plan, io, accumulator } = context;
+ if (operation.kind === "noop")
+ return;
+ if (operation.kind === "text") {
+ io.writeFile(operation.path, operation.afterText);
+ accumulator.mutations.push({
+ kind: "text",
+ path: operation.path,
+ beforeText: operation.beforeText,
+ afterText: operation.afterText
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ accumulator.totalEdits += operation.editCount;
+ return;
+ }
+ if (operation.kind === "create") {
+ io.writeFile(operation.path, "");
+ accumulator.mutations.push({ kind: "create", path: operation.path, replaced: operation.replaced });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ return;
+ }
+ if (operation.kind === "rename") {
+ if (operation.replaceDestination) {
+ const targetKind = existsSync4(operation.newPath) && lstatSync2(operation.newPath).isDirectory() ? "directory" : "file";
+ io.remove(operation.newPath, targetKind === "directory");
+ accumulator.mutations.push({ kind: "delete", path: operation.newPath, targetKind });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ }
+ io.rename(operation.oldPath, operation.newPath);
+ accumulator.mutations.push({
+ kind: "rename",
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: operation.sourceKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ return;
+ }
+ io.remove(operation.path, operation.recursive);
+ accumulator.mutations.push({
+ kind: "delete",
+ path: operation.path,
+ targetKind: operation.targetKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+}
+function commitWorkspaceEditPlan(plan, options = {}) {
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const stale = verifySnapshots(plan);
+ if (stale)
+ return stale;
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const io = resolveIo(options.io);
+ const accumulator = { mutations: [], filesModified: [], totalEdits: 0 };
+ const context = { plan, io, accumulator };
+ let lateAbort = false;
+ for (const operation of plan.operations) {
+ try {
+ commitOperation(context, operation);
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, {
+ message: `I/O failure during ${operation.kind}: ${detail}`,
+ changeIndex: operation.changeIndex,
+ mutations: accumulator.mutations,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ lateAbort: lateAbort || options.signal?.aborted === true
+ });
+ }
+ if (options.signal?.aborted)
+ lateAbort = true;
+ }
+ const result = {
+ success: true,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ errors: [],
+ ...lateAbort ? { lateAbort: true } : {}
+ };
+ return { result, delta: mutationDelta(accumulator.mutations), fingerprint: plan.fingerprint };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-fingerprint.ts
+import { createHash } from "node:crypto";
+function canonicalFingerprint(operations) {
+ const canonical = operations.map((operation) => {
+ switch (operation.kind) {
+ case "text":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ edits: operation.edits,
+ version: operation.version
+ };
+ case "rename":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "create":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "delete":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ recursive: operation.recursive,
+ ignoreIfNotExists: operation.ignoreIfNotExists
+ };
+ }
+ });
+ return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
+}
+
+// ../lsp-core/src/lsp/workspace-edit-types.ts
+class WorkspaceEditValidationError extends Error {
+ changeIndex;
+ detail;
+ name = "WorkspaceEditValidationError";
+ constructor(changeIndex, detail) {
+ super(`change ${changeIndex}: ${detail}`);
+ this.changeIndex = changeIndex;
+ this.detail = detail;
+ }
+}
+
+// ../lsp-core/src/lsp/workspace-edit-parse-helpers.ts
+function isRecord3(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function parsePosition(value) {
+ if (!isRecord3(value) || typeof value["line"] !== "number" || typeof value["character"] !== "number") {
+ return null;
+ }
+ return { line: value["line"], character: value["character"] };
+}
+function parseRange(value) {
+ if (!isRecord3(value))
+ return null;
+ const start = parsePosition(value["start"]);
+ const end = parsePosition(value["end"]);
+ return start && end ? { start, end } : null;
+}
+function parseTextEdits(value, changeIndex) {
+ if (!Array.isArray(value)) {
+ throw new WorkspaceEditValidationError(changeIndex, "text edits must be an array");
+ }
+ const edits = [];
+ for (const candidate of value) {
+ if (!isRecord3(candidate) || typeof candidate["newText"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "text edit requires range and newText");
+ }
+ if ("annotationId" in candidate) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated text edits are unsupported");
+ }
+ const range = parseRange(candidate["range"]);
+ if (!range)
+ throw new WorkspaceEditValidationError(changeIndex, "text edit range is malformed");
+ edits.push({ range, newText: candidate["newText"] });
+ }
+ return edits;
+}
+function parseBooleanOption(options, key, changeIndex) {
+ const value = options[key];
+ if (value === undefined)
+ return false;
+ if (typeof value !== "boolean") {
+ throw new WorkspaceEditValidationError(changeIndex, `${key} must be boolean`);
+ }
+ return value;
+}
+function parseOptions(value, allowed, changeIndex) {
+ if (value === undefined)
+ return {};
+ if (!isRecord3(value))
+ throw new WorkspaceEditValidationError(changeIndex, "resource options must be an object");
+ for (const key of Object.keys(value)) {
+ if (!allowed.includes(key))
+ throw new WorkspaceEditValidationError(changeIndex, `unsupported resource option ${key}`);
+ }
+ const parsed = {};
+ for (const key of allowed)
+ parsed[key] = parseBooleanOption(value, key, changeIndex);
+ return parsed;
+}
+
+// ../lsp-core/src/lsp/workspace-edit-resource-parser.ts
+function parseResourceChange(input) {
+ const kind = input.change["kind"];
+ if (kind === "create" || kind === "delete") {
+ parseSinglePathResource(input, kind);
+ return;
+ }
+ if (kind !== "rename") {
+ throw new WorkspaceEditValidationError(input.changeIndex, `unsupported resource operation ${String(kind)}`);
+ }
+ parseRename(input);
+}
+function parseSinglePathResource(input, kind) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["uri"] !== "string")
+ throw new WorkspaceEditValidationError(changeIndex, `${kind}.uri is required`);
+ const resolvedPath = uriToCanonicalWorkspacePath(change["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ if (kind === "create") {
+ const options2 = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ overwrite: options2["overwrite"] ?? false,
+ ignoreIfExists: options2["ignoreIfExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["recursive", "ignoreIfNotExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ recursive: options["recursive"] ?? false,
+ ignoreIfNotExists: options["ignoreIfNotExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+}
+function parseRename(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["oldUri"] !== "string" || typeof change["newUri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "rename requires oldUri and newUri");
+ }
+ const oldPath = uriToCanonicalWorkspacePath(change["oldUri"], workspaceRoot);
+ const newPath = uriToCanonicalWorkspacePath(change["newUri"], workspaceRoot);
+ if (!oldPath.success || !newPath.success) {
+ target.failures.push({
+ changeIndex,
+ message: !oldPath.success ? oldPath.error : !newPath.success ? newPath.error : "invalid rename path"
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind: "rename",
+ changeIndex,
+ oldPath: oldPath.path,
+ newPath: newPath.path,
+ reportedOldPath: oldPath.requestedPath,
+ reportedNewPath: newPath.requestedPath,
+ overwrite: options["overwrite"] ?? false,
+ ignoreIfExists: options["ignoreIfExists"] ?? false,
+ followedSymbolicLink: oldPath.followedSymbolicLink || newPath.followedSymbolicLink
+ });
+}
+
+// ../lsp-core/src/lsp/workspace-edit-parser.ts
+function failureResult(failures) {
+ const sorted = [...failures].sort((left, right) => left.changeIndex - right.changeIndex);
+ const first = sorted[0];
+ return {
+ success: false,
+ filesModified: [],
+ totalEdits: 0,
+ errors: sorted.map((failure) => `change ${failure.changeIndex}: ${failure.message}`),
+ ...first ? { failedChange: first.changeIndex } : {}
+ };
+}
+function parseWorkspaceEdit(edit, workspaceRoot) {
+ if (!isRecord3(edit))
+ return { operations: [], failures: [{ changeIndex: 0, message: "No edit provided" }] };
+ if (edit["changeAnnotations"] !== undefined) {
+ return { operations: [], failures: [{ changeIndex: 0, message: "change annotations are unsupported" }] };
+ }
+ const hasChanges = edit["changes"] !== undefined;
+ const hasDocumentChanges = edit["documentChanges"] !== undefined;
+ if (hasChanges && hasDocumentChanges) {
+ return {
+ operations: [],
+ failures: [{ changeIndex: 0, message: "changes and documentChanges cannot be combined" }]
+ };
+ }
+ const target = { operations: [], failures: [] };
+ if (hasChanges)
+ return parseChanges(edit["changes"], workspaceRoot, target);
+ return parseDocumentChanges(edit["documentChanges"], workspaceRoot, target);
+}
+function parseChanges(value, workspaceRoot, target) {
+ if (!isRecord3(value))
+ return { ...target, failures: [{ changeIndex: 0, message: "changes must be an object" }] };
+ const entries = Object.entries(value).sort(([left], [right]) => left.localeCompare(right));
+ for (const [changeIndex, [uri, rawEdits]] of entries.entries()) {
+ const resolvedPath = uriToCanonicalWorkspacePath(uri, workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ continue;
+ }
+ try {
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(rawEdits, changeIndex),
+ version: null
+ });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChanges(value, workspaceRoot, target) {
+ if (value === undefined)
+ return target;
+ if (!Array.isArray(value)) {
+ return { ...target, failures: [{ changeIndex: 0, message: "documentChanges must be an array" }] };
+ }
+ for (const [changeIndex, change] of value.entries()) {
+ try {
+ parseDocumentChange({ change, changeIndex, workspaceRoot, target });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChange(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (!isRecord3(change))
+ throw new WorkspaceEditValidationError(changeIndex, "document change must be an object");
+ if ("annotationId" in change) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated resource operations are unsupported");
+ }
+ if (typeof change["kind"] === "string") {
+ parseResourceChange({ change, changeIndex, workspaceRoot, target });
+ return;
+ }
+ const identifier = change["textDocument"];
+ if (!isRecord3(identifier) || typeof identifier["uri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "textDocument.uri is required");
+ }
+ const version = identifier["version"];
+ if (version !== null && (!Number.isInteger(version) || typeof version !== "number" || version < 0)) {
+ throw new WorkspaceEditValidationError(changeIndex, "document version must be null or a non-negative integer");
+ }
+ const resolvedPath = uriToCanonicalWorkspacePath(identifier["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(change["edits"], changeIndex),
+ version
+ });
+}
+
+// ../lsp-core/src/lsp/workspace-edit-simulation.ts
+import { dirname as dirname3, relative as relative4, resolve as resolve4 } from "node:path";
+
+// ../lsp-core/src/lsp/workspace-edit-text.ts
+function comparePosition(left, right) {
+ return left.line === right.line ? left.character - right.character : left.line - right.line;
+}
+function positionsEqual(left, right) {
+ return left.line === right.line && left.character === right.character;
+}
+function rangesEqual(left, right) {
+ return positionsEqual(left.start, right.start) && positionsEqual(left.end, right.end);
+}
+function isEmptyRange(range) {
+ return positionsEqual(range.start, range.end);
+}
+function formatRange(range) {
+ return `${range.start.line + 1}:${range.start.character + 1}-${range.end.line + 1}:${range.end.character + 1}`;
+}
+function validatePosition(position, label, context) {
+ const { lines, changeIndex } = context;
+ if (!Number.isInteger(position.line) || !Number.isInteger(position.character)) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position must use integer line and character`);
+ }
+ if (position.line < 0 || position.character < 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position cannot be negative`);
+ }
+ const line = lines[position.line];
+ if (line === undefined) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} line ${position.line} is outside the document`);
+ }
+ if (position.character > line.length) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} character ${position.character} is outside line ${position.line}`);
+ }
+}
+function validateRange(range, lines, changeIndex) {
+ const context = { lines, changeIndex };
+ validatePosition(range.start, "start", context);
+ validatePosition(range.end, "end", context);
+ if (comparePosition(range.start, range.end) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `range ${formatRange(range)} ends before it starts`);
+ }
+}
+function sortAndDeduplicate(edits) {
+ const sorted = edits.map((edit, index) => ({ edit, index })).sort((left, right) => {
+ const positionOrder = comparePosition(right.edit.range.start, left.edit.range.start);
+ return positionOrder === 0 ? right.index - left.index : positionOrder;
+ });
+ const unique = [];
+ for (const entry of sorted) {
+ const previous = unique.at(-1);
+ if (previous !== undefined && !isEmptyRange(entry.edit.range) && rangesEqual(previous.range, entry.edit.range) && previous.newText === entry.edit.newText) {
+ continue;
+ }
+ unique.push(entry.edit);
+ }
+ return unique;
+}
+function validateNoOverlap(edits, changeIndex) {
+ for (let index = 0;index < edits.length - 1; index += 1) {
+ const later = edits[index];
+ const earlier = edits[index + 1];
+ if (later === undefined || earlier === undefined)
+ continue;
+ if (comparePosition(earlier.range.end, later.range.start) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `overlapping edits ${formatRange(earlier.range)} and ${formatRange(later.range)}`);
+ }
+ }
+}
+function applyNormalizedTextEdits(content, edits) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ const { start, end } = edit.range;
+ const startLine = lines[start.line];
+ const endLine = lines[end.line];
+ if (startLine === undefined || endLine === undefined)
+ continue;
+ const replacement = startLine.slice(0, start.character) + edit.newText + endLine.slice(end.character);
+ lines.splice(start.line, end.line - start.line + 1, ...replacement.split(`
+`));
+ }
+ return lines.join(`
+`);
+}
+function normalizeTextEdits(content, edits, changeIndex) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ validateRange(edit.range, lines, changeIndex);
+ }
+ const normalized = sortAndDeduplicate(edits);
+ validateNoOverlap(normalized, changeIndex);
+ return { edits: normalized, text: applyNormalizedTextEdits(content, normalized) };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-simulation.ts
+function isSameOrDescendant2(candidate, parent) {
+ const relativePath = relative4(parent, candidate);
+ return relativePath === "" || !relativePath.startsWith("..") && relativePath !== "..";
+}
+function removeVirtualSubtree(virtual, path) {
+ for (const candidate of [...virtual.keys()]) {
+ if (isSameOrDescendant2(candidate, path))
+ virtual.delete(candidate);
+ }
+ virtual.set(path, { kind: "missing" });
+}
+function moveVirtualSubtree(virtual, oldPath, newPath) {
+ const moved = [...virtual.entries()].filter(([candidate]) => isSameOrDescendant2(candidate, oldPath));
+ removeVirtualSubtree(virtual, oldPath);
+ removeVirtualSubtree(virtual, newPath);
+ for (const [candidate, entry] of moved) {
+ const suffix = relative4(oldPath, candidate);
+ virtual.set(suffix === "" ? newPath : resolve4(newPath, suffix), entry);
+ }
+}
+function virtualDirectoryHasChildren(virtual, path) {
+ for (const [candidate, entry] of virtual) {
+ if (candidate !== path && entry.kind !== "missing" && isSameOrDescendant2(candidate, path))
+ return true;
+ }
+ return false;
+}
+function requireVirtualParent(virtual, path, changeIndex) {
+ if (virtual.get(dirname3(path))?.kind !== "directory") {
+ throw new WorkspaceEditValidationError(changeIndex, `parent directory does not exist for ${path}`);
+ }
+}
+function simulateOperations(parsed, snapshots) {
+ const virtual = new Map(snapshots);
+ const planned = [];
+ const failures = [];
+ for (const operation of parsed) {
+ try {
+ planned.push(simulateOperation(operation, virtual));
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ failures.push({ changeIndex: operation.changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return { operations: planned, failures };
+}
+function simulateOperation(operation, virtual) {
+ switch (operation.kind) {
+ case "text":
+ return simulateText(operation, virtual);
+ case "create":
+ return simulateCreate(operation, virtual);
+ case "rename":
+ return simulateRename(operation, virtual);
+ case "delete":
+ return simulateDelete(operation, virtual);
+ }
+}
+function rejectSymbolicLink(operation) {
+ if (operation.followedSymbolicLink) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "resource operations through symbolic links are unsupported");
+ }
+}
+function simulateText(operation, virtual) {
+ const entry = virtual.get(operation.path);
+ if (entry?.kind !== "file")
+ throw new WorkspaceEditValidationError(operation.changeIndex, `${operation.path} is not a file`);
+ const normalized = normalizeTextEdits(entry.content, operation.edits, operation.changeIndex);
+ virtual.set(operation.path, { kind: "file", content: normalized.text });
+ return {
+ kind: "text",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ beforeText: entry.content,
+ afterText: normalized.text,
+ editCount: normalized.edits.length,
+ documentVersion: operation.version
+ };
+}
+function simulateCreate(operation, virtual) {
+ rejectSymbolicLink(operation);
+ requireVirtualParent(virtual, operation.path, operation.changeIndex);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind !== "missing") {
+ if (operation.overwrite && target.kind === "file") {
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: true };
+ }
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `create target already exists: ${operation.path}`);
+ }
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: false };
+}
+function simulateRename(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const source = virtual.get(operation.oldPath) ?? { kind: "missing" };
+ if (source.kind === "missing") {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename source does not exist: ${operation.oldPath}`);
+ }
+ if (operation.oldPath === operation.newPath)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ if (isSameOrDescendant2(operation.newPath, operation.oldPath)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "cannot rename a path into its own subtree");
+ }
+ requireVirtualParent(virtual, operation.newPath, operation.changeIndex);
+ const destination = virtual.get(operation.newPath) ?? { kind: "missing" };
+ if (destination.kind !== "missing" && !operation.overwrite) {
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename target already exists: ${operation.newPath}`);
+ }
+ moveVirtualSubtree(virtual, operation.oldPath, operation.newPath);
+ return {
+ kind: "rename",
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: source.kind,
+ replaceDestination: destination.kind !== "missing"
+ };
+}
+function simulateDelete(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind === "missing") {
+ if (operation.ignoreIfNotExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `delete target does not exist: ${operation.path}`);
+ }
+ if (target.kind === "directory" && !operation.recursive && virtualDirectoryHasChildren(virtual, operation.path)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `directory is not empty: ${operation.path}`);
+ }
+ removeVirtualSubtree(virtual, operation.path);
+ return {
+ kind: "delete",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ targetKind: target.kind,
+ recursive: operation.recursive
+ };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-snapshot.ts
+import { existsSync as existsSync5, lstatSync as lstatSync3, readdirSync as readdirSync2 } from "node:fs";
+import { dirname as dirname4, resolve as resolve5 } from "node:path";
+class WorkspaceSnapshotBuilder {
+ workspaceRoot;
+ snapshots = new Map;
+ constructor(workspaceRoot) {
+ this.workspaceRoot = workspaceRoot;
+ }
+ build(operations) {
+ this.add(this.workspaceRoot, false);
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, true);
+ this.add(operation.newPath, true);
+ break;
+ case "delete":
+ this.add(operation.path, true);
+ break;
+ case "text":
+ case "create":
+ this.add(operation.path, false);
+ break;
+ }
+ }
+ return this.snapshots;
+ }
+ add(path, includeChildren) {
+ let candidate = path;
+ while (true) {
+ const existing = this.snapshots.get(candidate);
+ if (existing === undefined || includeChildren && existing.kind === "directory" && existing.children === undefined) {
+ this.snapshots.set(candidate, snapshotPath(candidate, includeChildren && candidate === path));
+ }
+ if (candidate === this.workspaceRoot)
+ break;
+ candidate = dirname4(candidate);
+ }
+ if (!includeChildren || !existsSync5(path) || !lstatSync3(path).isDirectory())
+ return;
+ for (const child of readdirSync2(path))
+ this.add(resolve5(path, child), true);
+ }
+}
+function snapshotOperations(operations, workspaceRoot) {
+ return new WorkspaceSnapshotBuilder(workspaceRoot).build(operations);
+}
+
+// ../lsp-core/src/lsp/workspace-edit-plan.ts
+class PlanPathIndex {
+ firstChangeByPath = new Map;
+ reportedPathByCanonical = new Map;
+ build(operations) {
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, operation.reportedOldPath, operation.changeIndex);
+ this.add(operation.newPath, operation.reportedNewPath, operation.changeIndex);
+ break;
+ case "text":
+ case "create":
+ case "delete":
+ this.add(operation.path, operation.reportedPath, operation.changeIndex);
+ break;
+ }
+ }
+ }
+ add(path, reportedPath2, changeIndex) {
+ if (!this.firstChangeByPath.has(path))
+ this.firstChangeByPath.set(path, changeIndex);
+ if (!this.reportedPathByCanonical.has(path))
+ this.reportedPathByCanonical.set(path, reportedPath2);
+ }
+}
+function fingerprintWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ return { success: true, fingerprint: canonicalFingerprint(parsed.operations) };
+}
+function planWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ let snapshots;
+ try {
+ snapshots = snapshotOperations(parsed.operations, root.path);
+ } catch (error) {
+ return {
+ success: false,
+ result: failureResult([{ changeIndex: 0, message: error instanceof Error ? error.message : String(error) }])
+ };
+ }
+ const simulated = simulateOperations(parsed.operations, snapshots);
+ if (simulated.failures.length > 0)
+ return { success: false, result: failureResult(simulated.failures) };
+ const paths = new PlanPathIndex;
+ paths.build(parsed.operations);
+ const plan = {
+ workspaceRoot: root.path,
+ operations: simulated.operations,
+ snapshots,
+ firstChangeByPath: paths.firstChangeByPath,
+ reportedPathByCanonical: paths.reportedPathByCanonical,
+ fingerprint: canonicalFingerprint(parsed.operations)
+ };
+ return { success: true, plan };
+}
+
+// ../lsp-core/src/lsp/workspace-mutation-controller.ts
+function failure(message, failedChange, base) {
+ return {
+ success: false,
+ filesModified: base?.filesModified ?? [],
+ totalEdits: base?.totalEdits ?? 0,
+ errors: [message],
+ ...failedChange === undefined ? {} : { failedChange },
+ ...base?.lateAbort ? { lateAbort: true } : {}
+ };
+}
+function responseFor(result) {
+ if (result.success)
+ return { applied: true };
+ return {
+ applied: false,
+ failureReason: result.errors[0] ?? "workspace edit failed",
+ ...result.failedChange === undefined ? {} : { failedChange: result.failedChange }
+ };
+}
+function isRecord4(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+class WorkspaceMutationController {
+ workspaceRoot;
+ documents;
+ activeLease = null;
+ nextLeaseId = 1;
+ io;
+ constructor(workspaceRoot, documents) {
+ this.workspaceRoot = workspaceRoot;
+ this.documents = documents;
+ }
+ setIo(io) {
+ this.io = io;
+ }
+ acquire(signal) {
+ if (this.activeLease)
+ return { success: false, result: failure("workspace mutation is already in progress") };
+ if (signal?.aborted)
+ return { success: false, result: failure("cancelled before mutating request") };
+ const lease = {
+ id: this.nextLeaseId,
+ phase: "idle",
+ ...signal === undefined ? {} : { signal }
+ };
+ this.nextLeaseId += 1;
+ this.activeLease = lease;
+ return { success: true, lease };
+ }
+ release(lease) {
+ if (this.activeLease?.id !== lease.id)
+ return;
+ this.activeLease.phase = "sealed";
+ this.activeLease = null;
+ }
+ isBeforeCommit(lease) {
+ return this.activeLease?.id === lease.id && this.activeLease.phase === "idle";
+ }
+ async handleApplyEdit(params) {
+ const lease = this.activeLease;
+ if (!lease)
+ return { applied: false, failureReason: "workspace/applyEdit requires an active workspace mutation" };
+ if (lease.phase !== "idle") {
+ return {
+ applied: false,
+ failureReason: workspaceApplyEditConcurrentFailureReason(lease.phase === "applying" ? "applying" : "settled")
+ };
+ }
+ lease.phase = "applying";
+ lease.applyCompletion = new Promise((resolve6) => {
+ lease.resolveApply = resolve6;
+ });
+ const edit = isRecord4(params) ? params["edit"] : undefined;
+ const record2 = edit === undefined ? { fingerprint: null, result: failure("workspace/applyEdit params.edit is required", 0) } : await this.applyEdit(edit, lease);
+ lease.serverApply = record2;
+ lease.phase = "settled";
+ lease.resolveApply?.();
+ return responseFor(record2.result);
+ }
+ async reconcileRename(leaseToken, edit) {
+ const lease = this.requireActiveLease(leaseToken);
+ if (!lease)
+ return { edit, apply: failure("workspace mutation lease ended before rename reconciliation") };
+ if (lease.phase === "applying")
+ await lease.applyCompletion;
+ if (lease.serverApply)
+ return this.reconcileServerApply(lease.serverApply, edit);
+ lease.phase = "sealed";
+ if (!edit)
+ return { edit, apply: failure("No edit provided") };
+ const applied = await this.applyEdit(edit, lease);
+ return { edit, apply: applied.result };
+ }
+ reconcileServerApply(record2, edit) {
+ if (!edit)
+ return { edit, apply: record2.result };
+ const fingerprint = fingerprintWorkspaceEdit(edit, this.workspaceRoot);
+ if (fingerprint.success && record2.fingerprint !== null && fingerprint.fingerprint === record2.fingerprint) {
+ return { edit, apply: record2.result };
+ }
+ return {
+ edit,
+ apply: failure("rename result conflicts with server-applied workspace edit", 0, record2.result)
+ };
+ }
+ async applyEdit(edit, lease) {
+ const planned = planWorkspaceEdit(edit, this.workspaceRoot);
+ if (!planned.success)
+ return { fingerprint: null, result: planned.result };
+ const versionFailure = this.documents.validateVersions(planned.plan.operations);
+ if (versionFailure) {
+ return {
+ fingerprint: planned.plan.fingerprint,
+ result: failure(versionFailure.message, versionFailure.changeIndex)
+ };
+ }
+ const commit = commitWorkspaceEditPlan(planned.plan, {
+ ...lease.signal === undefined ? {} : { signal: lease.signal },
+ ...this.io === undefined ? {} : { io: this.io }
+ });
+ let result = commit.result;
+ if (commit.delta.operations.length > 0) {
+ try {
+ await this.documents.synchronize(commit.delta);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ result = failure(`document synchronization failed after filesystem commit: ${message}`, undefined, result);
+ }
+ }
+ if (lease.signal?.aborted && !result.lateAbort)
+ result = { ...result, lateAbort: true };
+ return { fingerprint: planned.plan.fingerprint, result };
+ }
+ requireActiveLease(lease) {
+ return this.activeLease?.id === lease.id ? this.activeLease : null;
+ }
+}
+
+// ../lsp-core/src/lsp/client.ts
+var DIAGNOSTICS_FRESHNESS_TIMEOUT_MS = 3000;
+var VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
+
+class LspClient extends LspClientConnection {
+ diagnosticPullErrors = [];
+ documents;
+ workspaceMutations;
+ diagnosticsFreshnessTimeoutMs;
+ constructor(root, server2, options = {}) {
+ super(root, server2, options);
+ this.diagnosticsFreshnessTimeoutMs = options.diagnosticsFreshnessTimeoutMs ?? DIAGNOSTICS_FRESHNESS_TIMEOUT_MS;
+ this.documents = new WorkspaceDocumentState((method, params) => this.sendNotification(method, params), (uri) => this.diagnosticsStore.delete(uri), {
+ versionlessPublishQuiescenceMs: options.versionlessPublishQuiescenceMs ?? VERSIONLESS_PUBLISH_QUIESCENCE_MS
+ });
+ this.workspaceMutations = new WorkspaceMutationController(root, this.documents);
+ this.setWorkspaceApplyEditHandler((params) => this.workspaceMutations.handleApplyEdit(params));
+ }
+ getDiagnosticPullErrors() {
+ return this.diagnosticPullErrors;
+ }
+ async openFile(filePath) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.documents.openFile(absPath);
+ }
+ getOpenDocumentVersion(filePath) {
+ return this.documents.getVersion(this.resolveWorkspacePath(filePath));
+ }
+ getStoredDiagnostics(uri) {
+ return [...this.documents.getStoredDiagnostics(uri)];
+ }
+ setWorkspaceEditIo(io) {
+ this.workspaceMutations.setIo(io);
+ }
+ handlePublishDiagnostics(params) {
+ super.handlePublishDiagnostics(params);
+ this.documents.recordPublishedDiagnostics(params);
+ }
+ async definition(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("textDocument/definition", {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character }
+ }, options);
+ }
+ async references(filePath, line, character, includeDeclaration = true, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("textDocument/references", {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character },
+ context: { includeDeclaration }
+ }, options);
+ }
+ async documentSymbols(filePath, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("textDocument/documentSymbol", {
+ textDocument: { uri: pathToFileURL3(absPath).href }
+ }, options);
+ }
+ async workspaceSymbols(query, signal) {
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("workspace/symbol", { query }, options);
+ }
+ isUnsupportedDiagnosticPullError(error) {
+ if (!(error instanceof Error))
+ return false;
+ const code = "code" in error && typeof error.code === "number" ? error.code : undefined;
+ if (code === -32601)
+ return true;
+ return /unsupported|not supported|method not found|unknown request/i.test(error.message);
+ }
+ freshnessTimeout(absPath) {
+ return {
+ items: [],
+ transientError: {
+ kind: "freshness_timeout",
+ message: `Timed out waiting for fresh diagnostics for ${absPath} within ${this.diagnosticsFreshnessTimeoutMs}ms.`
+ }
+ };
+ }
+ parseDiagnosticPullReport(value) {
+ if (value.kind === "unchanged") {
+ return {
+ type: "unchanged",
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ return {
+ type: "full",
+ diagnostics: value.items ?? [],
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ async diagnostics(filePath, signal) {
+ signal?.throwIfAborted();
+ const absPath = this.resolveWorkspacePath(filePath);
+ const uri = pathToFileURL3(absPath).href;
+ await this.openFile(absPath);
+ const deadlineAt = Date.now() + this.diagnosticsFreshnessTimeoutMs;
+ for (;; ) {
+ signal?.throwIfAborted();
+ const snapshot = this.documents.captureDiagnosticSnapshot(absPath);
+ if (!snapshot)
+ return this.freshnessTimeout(absPath);
+ const push = this.documents.resolvePushDiagnostics(snapshot);
+ if (push.status === "ready")
+ return { items: [...push.diagnostics] };
+ let pushFallbackOnly = !this.isDiagnosticPullSupported();
+ if (!pushFallbackOnly) {
+ const cached = this.documents.getPullCache(snapshot);
+ try {
+ const remainingMs2 = deadlineAt - Date.now();
+ if (remainingMs2 <= 0)
+ return this.freshnessTimeout(absPath);
+ const result = await this.sendRequest("textDocument/diagnostic", {
+ textDocument: { uri },
+ ...cached?.resultId === undefined ? {} : { previousResultId: cached.resultId }
+ }, { timeoutMs: remainingMs2, ...signal === undefined ? {} : { signal } });
+ if (!this.documents.isCurrentSnapshot(snapshot))
+ continue;
+ const report = this.parseDiagnosticPullReport(result);
+ if (report.type === "full") {
+ this.documents.recordPullDiagnostics(snapshot, {
+ kind: "full",
+ diagnostics: report.diagnostics,
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ });
+ return { items: [...report.diagnostics] };
+ }
+ if (cached !== null && cached.documentVersion === snapshot.version && cached.resultId === report.resultId) {
+ return { items: [...cached.diagnostics] };
+ }
+ } catch (error) {
+ if (this.isUnsupportedDiagnosticPullError(error)) {
+ this.setDiagnosticPullSupported(false);
+ pushFallbackOnly = true;
+ } else if (error instanceof LspRequestTimeoutError) {
+ pushFallbackOnly = true;
+ } else {
+ this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ throw error;
+ }
+ }
+ }
+ if (!pushFallbackOnly)
+ continue;
+ const remainingMs = deadlineAt - Date.now();
+ if (remainingMs <= 0)
+ return this.freshnessTimeout(absPath);
+ const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;
+ await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);
+ }
+ }
+ async prepareRename(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("textDocument/prepareRename", {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character }
+ }, options);
+ }
+ async rename(filePath, line, character, newName, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const acquired = this.workspaceMutations.acquire(signal);
+ if (!acquired.success)
+ return { edit: null, apply: acquired.result };
+ const preCommitSignal = createPreCommitAbortSignal(signal, () => this.workspaceMutations.isBeforeCommit(acquired.lease));
+ try {
+ const renameParams = {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character },
+ newName
+ };
+ const edit = preCommitSignal === undefined ? await this.sendRequest("textDocument/rename", renameParams) : await this.sendRequest("textDocument/rename", renameParams, {
+ signal: preCommitSignal.signal
+ });
+ return await this.workspaceMutations.reconcileRename(acquired.lease, edit);
+ } finally {
+ preCommitSignal?.dispose();
+ this.workspaceMutations.release(acquired.lease);
+ }
+ }
+ resolveWorkspacePath(filePath) {
+ return resolve6(this.root, filePath);
+ }
+}
+function waitForDiagnosticsActivity(wait, signal) {
+ if (!signal)
+ return wait;
+ if (signal.aborted)
+ return Promise.reject(abortError2(signal));
+ return new Promise((resolve7, reject) => {
+ const onAbort = () => {
+ signal.removeEventListener("abort", onAbort);
+ reject(abortError2(signal));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ wait.then(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve7();
+ }, (error) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(error);
+ });
+ });
+}
+function createPreCommitAbortSignal(source, isBeforeCommit) {
+ if (!source)
+ return;
+ const controller = new AbortController;
+ const onAbort = () => {
+ if (isBeforeCommit() && !controller.signal.aborted)
+ controller.abort(preCommitAbortReason(source));
+ };
+ if (source.aborted)
+ onAbort();
+ else
+ source.addEventListener("abort", onAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => source.removeEventListener("abort", onAbort)
+ };
+}
+function preCommitAbortReason(source) {
+ const reason = source.reason;
+ if (reason instanceof Error && reason.name !== "AbortError")
+ return reason;
+ return new Error("LSP request cancelled before workspace edit commit");
+}
+function abortError2(signal) {
+ const reason = signal.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "operation cancelled");
+ error.name = "AbortError";
+ return error;
+}
+
+// ../lsp-core/src/lsp/process-signal-cleanup.ts
+function installProcessSignalCleanup(cleanup) {
+ const signals = process.platform === "win32" ? ["SIGINT", "SIGTERM", "SIGBREAK"] : ["SIGINT", "SIGTERM"];
+ const handler = () => {
+ cleanup().catch((error) => {
+ reportBestEffortCleanupError("signal cleanup", error);
+ });
+ };
+ for (const signal of signals) {
+ process.on(signal, handler);
+ }
+ return () => {
+ for (const signal of signals) {
+ process.removeListener(signal, handler);
+ }
+ };
+}
+
+// ../lsp-core/src/lsp/manager.ts
+async function stopClientBestEffort(client) {
+ try {
+ await client.stop();
+ } catch (error) {
+ reportBestEffortCleanupError("client stop", error);
+ }
+}
+function awaitWithSignal(promise, signal) {
+ if (!signal)
+ return promise;
+ return new Promise((resolve7, reject) => {
+ let settled = false;
+ const onAbort = () => {
+ if (settled)
+ return;
+ settled = true;
reject(new DOMException("Aborted", "AbortError"));
};
if (signal.aborted) {
@@ -1375,7 +3135,7 @@ function awaitWithSignal(promise, signal) {
return;
settled = true;
signal.removeEventListener("abort", onAbort);
- resolve2(value);
+ resolve7(value);
}, (err) => {
if (settled)
return;
@@ -1629,21 +3389,17 @@ async function disposeDefaultLspManager() {
}
// ../lsp-core/src/lsp/server-install-state.ts
-import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
-import { homedir } from "node:os";
-import { dirname, isAbsolute, join as join2 } from "node:path";
+import { existsSync as existsSync6, mkdirSync, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
+import { dirname as dirname5 } from "node:path";
function getInstallDecisionsPath() {
- const override = contextEnv("LSP_TOOLS_MCP_INSTALL_DECISIONS");
- if (!override)
- return join2(homedir(), ".codex", "lsp-install-decisions.json");
- return isAbsolute(override) ? override : join2(homedir(), override);
+ return lspRequestContext().installDecisionsPath;
}
function loadInstallDecisions() {
const path = getInstallDecisionsPath();
- if (!existsSync2(path))
+ if (!existsSync6(path))
return {};
try {
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
+ const parsed = JSON.parse(readFileSync3(path, "utf8"));
return isInstallDecisions(parsed) ? parsed : {};
} catch {
return {};
@@ -1662,28 +3418,26 @@ function isInstallDecision(value) {
}
function writeInstallDecisions(decisions) {
const path = getInstallDecisionsPath();
- mkdirSync(dirname(path), { recursive: true });
+ mkdirSync(dirname5(path), { recursive: true });
const tmpPath = `${path}.tmp`;
- writeFileSync(tmpPath, `${JSON.stringify(decisions, null, 2)}
+ writeFileSync2(tmpPath, `${JSON.stringify(decisions, null, 2)}
`, "utf8");
- renameSync(tmpPath, path);
+ renameSync2(tmpPath, path);
}
function isInstallDecisions(value) {
- return isRecord2(value) && Object.values(value).every(isInstallDecisionRecord);
+ return isRecord5(value) && Object.values(value).every(isInstallDecisionRecord);
}
function isInstallDecisionRecord(value) {
- if (!isRecord2(value))
+ if (!isRecord5(value))
return false;
return isInstallDecision(value["decision"]) && typeof value["decidedAt"] === "string";
}
-function isRecord2(value) {
+function isRecord5(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
// ../lsp-core/src/lsp/config-loader.ts
-import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
-import { homedir as homedir2 } from "node:os";
-import { delimiter as delimiter2, isAbsolute as isAbsolute2, join as join3 } from "node:path";
+import { existsSync as existsSync7, readFileSync as readFileSync4 } from "node:fs";
// ../lsp-core/src/lsp/server-definitions.ts
var LSP_INSTALL_HINTS = {
@@ -1833,27 +3587,17 @@ var BUILTIN_SERVERS = {
};
// ../lsp-core/src/lsp/config-loader.ts
-function resolveProjectConfigPath(path) {
- return isAbsolute2(path) ? path : join3(contextCwd(), path);
-}
function getProjectConfigPaths() {
- const projectOverride = contextEnv("LSP_TOOLS_MCP_PROJECT_CONFIG");
- if (projectOverride) {
- return projectOverride.split(delimiter2).filter(Boolean).map(resolveProjectConfigPath);
- }
- return [join3(contextCwd(), ".codex", "lsp-client.json")];
+ return lspRequestContext().projectConfigPaths;
}
function getUserConfigPath() {
- const userOverride = contextEnv("LSP_TOOLS_MCP_USER_CONFIG");
- if (!userOverride)
- return join3(homedir2(), ".codex", "lsp-client.json");
- return isAbsolute2(userOverride) ? userOverride : join3(homedir2(), userOverride);
+ return lspRequestContext().userConfigPath;
}
function loadJsonFile(path) {
- if (!existsSync3(path))
+ if (!existsSync7(path))
return null;
try {
- const parsed = JSON.parse(readFileSync3(path, "utf-8"));
+ const parsed = JSON.parse(readFileSync4(path, "utf-8"));
return isConfigJson(parsed) ? parsed : null;
} catch {
return null;
@@ -1992,16 +3736,16 @@ function applyOptionalServerFields(server2, entry) {
}
}
function isConfigJson(value) {
- if (!isRecord3(value))
+ if (!isRecord6(value))
return false;
const lsp = value["lsp"];
- return lsp === undefined || isRecord3(lsp);
+ return lsp === undefined || isRecord6(lsp);
}
function parseLspEntry(value) {
return isLspEntry(value) ? value : null;
}
function isLspEntry(value) {
- if (!isRecord3(value))
+ if (!isRecord6(value))
return false;
const disabled = value["disabled"];
const command = value["command"];
@@ -2009,15 +3753,15 @@ function isLspEntry(value) {
const priority = value["priority"];
const env = value["env"];
const initialization = value["initialization"];
- return (disabled === undefined || typeof disabled === "boolean") && (command === undefined || isStringArray(command)) && (extensions === undefined || isStringArray(extensions)) && (priority === undefined || typeof priority === "number") && (env === undefined || isStringRecord(env)) && (initialization === undefined || isRecord3(initialization));
+ return (disabled === undefined || typeof disabled === "boolean") && (command === undefined || isStringArray(command)) && (extensions === undefined || isStringArray(extensions)) && (priority === undefined || typeof priority === "number") && (env === undefined || isStringRecord(env)) && (initialization === undefined || isRecord6(initialization));
}
function isStringArray(value) {
return Array.isArray(value) && value.every((item) => typeof item === "string");
}
function isStringRecord(value) {
- return isRecord3(value) && Object.values(value).every((item) => typeof item === "string");
+ return isRecord6(value) && Object.values(value).every((item) => typeof item === "string");
}
-function isRecord3(value) {
+function isRecord6(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function getDisabledServerIds() {
@@ -2038,8 +3782,8 @@ function getDisabledServerIds() {
}
// ../lsp-core/src/lsp/server-installation.ts
-import { existsSync as existsSync4 } from "node:fs";
-import { delimiter as delimiter3, join as join4 } from "node:path";
+import { existsSync as existsSync8 } from "node:fs";
+import { delimiter as delimiter3, join as join3 } from "node:path";
function isServerInstalled(command, _workingDirectory) {
if (command.length === 0)
return false;
@@ -2047,7 +3791,7 @@ function isServerInstalled(command, _workingDirectory) {
if (!cmd)
return false;
if (cmd.includes("/") || cmd.includes("\\")) {
- if (existsSync4(cmd))
+ if (existsSync8(cmd))
return true;
}
const isWindows = process.platform === "win32";
@@ -2068,7 +3812,7 @@ function isServerInstalled(command, _workingDirectory) {
const paths = pathEnv.split(delimiter3);
for (const p of paths) {
for (const suffix of exts) {
- if (existsSync4(join4(p, cmd + suffix))) {
+ if (existsSync8(join3(p, cmd + suffix))) {
return true;
}
}
@@ -2167,39 +3911,50 @@ function getAllServers() {
var WORKSPACE_MARKERS = [".git", "package.json", "pyproject.toml", "Cargo.toml", "go.mod", "pom.xml", "build.gradle"];
function isDirectoryPath(filePath) {
try {
- return statSync2(filePath).isDirectory();
+ return statSync3(filePath).isDirectory();
} catch {
return false;
}
}
function findWorkspaceRoot(filePath) {
- const abs = resolve2(contextCwd(), filePath);
+ const abs = resolvePathInsideContext(filePath);
let dir = abs;
if (!isDirectoryPath(dir)) {
- dir = dirname2(dir);
+ dir = dirname6(dir);
}
let prevDir = "";
while (dir !== prevDir) {
for (const marker of WORKSPACE_MARKERS) {
- if (existsSync5(join5(dir, marker))) {
+ if (existsSync9(join4(dir, marker))) {
return dir;
}
}
prevDir = dir;
- dir = dirname2(dir);
+ dir = dirname6(dir);
}
- return dirname2(abs);
+ return dirname6(abs);
+}
+function resolvePathInsideContext(filePath) {
+ const cwd = contextCwd();
+ const abs = resolve7(cwd, filePath);
+ const canonical = canonicalizeExistingOrNearestAncestor(abs);
+ if (!isPathInside(cwd, canonical)) {
+ throw new LspInvalidPathError(`LSP file path must be inside request cwd: ${filePath}`);
+ }
+ return canonical;
}
function formatServerLookupError(result) {
if (result.status === "not_installed") {
return formatNotInstalled(result);
}
+ const context = lspRequestContext();
+ const firstProjectConfigPath = context.projectConfigPaths[0] ?? "<project lsp config>";
return [
`No LSP server configured for extension: ${result.extension}`,
"",
`Available servers: ${result.availableServers.slice(0, 10).join(", ")}${result.availableServers.length > 10 ? "..." : ""}`,
"",
- "Configure a custom server in '.codex/lsp-client.json':",
+ `Configure a custom server in '${firstProjectConfigPath}' or '${context.userConfigPath}':`,
" {",
' "lsp": {',
' "my-server": {',
@@ -2215,6 +3970,7 @@ function formatNotInstalled(result) {
const { server: server2, installHint } = result;
const extensions = server2.extensions.join(", ");
const decision = loadInstallDecision(server2.id)?.decision;
+ const context = lspRequestContext();
if (decision === "declined") {
return `LSP server '${server2.id}' (${extensions}) is NOT INSTALLED; user previously declined installation — proceed without LSP.`;
}
@@ -2230,6 +3986,17 @@ function formatNotInstalled(result) {
"The user has pre-authorized LSP installation. Run the install command, then retry this tool:",
` ${installHint}`
].join(`
+`);
+ }
+ if (!context.capabilities.installDecisionTool) {
+ return [
+ ...header,
+ "To install, run:",
+ ` ${installHint}`,
+ "",
+ "ACTION REQUIRED — ASK THE USER whether to install this LSP server.",
+ "Install-decision recording is unavailable in this harness; proceed without LSP if the user declines."
+ ].join(`
`);
}
return [
@@ -2241,6 +4008,7 @@ function formatNotInstalled(result) {
"- If the user agrees: run the install command above, then retry this tool.",
"- If the user declines, OR has NOT explicitly asked for LSP installation:",
` call lsp_install_decision { server_id: "${server2.id}", decision: "declined" },`,
+ ` which writes to ${context.installDecisionsPath},`,
" then ignore this message and proceed WITHOUT LSP."
].join(`
`);
@@ -2254,14 +4022,14 @@ var READ_ONLY_RETRY_TOOLS = new Set([
"prepareRename"
]);
async function withLspClient(filePath, fn, toolName, options = {}) {
- const absPath = resolve2(contextCwd(), filePath);
+ const absPath = resolvePathInsideContext(filePath);
if (isDirectoryPath(absPath)) {
throw new LspInvalidPathError("Directory paths are not supported by this LSP tool. " + "Use lsp.diagnostics with a directory path for directory diagnostics.");
}
const ext = effectiveExtension(absPath);
const result = findServerForExtension(ext);
if (result.status !== "found") {
- throw new LspServerLookupError(formatServerLookupError(result));
+ throw new LspServerLookupError(formatServerLookupError(result), result);
}
const server2 = result.server;
const root = findWorkspaceRoot(absPath);
@@ -2289,11 +4057,11 @@ async function withLspClient(filePath, fn, toolName, options = {}) {
}
// ../lsp-core/src/lsp/directory-diagnostics.ts
-import { existsSync as existsSync6, lstatSync, readdirSync } from "node:fs";
-import { join as join6, resolve as resolve3 } from "node:path";
+import { existsSync as existsSync10, lstatSync as lstatSync4, readdirSync as readdirSync3 } from "node:fs";
+import { join as join5, resolve as resolve8 } from "node:path";
// ../lsp-core/src/lsp/formatters.ts
-import { fileURLToPath } from "node:url";
+import { fileURLToPath as fileURLToPath2 } from "node:url";
var DIAGNOSTIC_SEVERITY_FILTERS = {
error: 1,
warning: 2,
@@ -2301,7 +4069,7 @@ var DIAGNOSTIC_SEVERITY_FILTERS = {
hint: 4
};
function uriToPath(uri) {
- return fileURLToPath(uri);
+ return fileURLToPath2(uri);
}
function formatLocation(loc) {
if ("targetUri" in loc) {
@@ -2387,6 +4155,9 @@ function formatApplyResult(result) {
for (const file of result.filesModified) {
lines.push(` - ${file}`);
}
+ if (result.lateAbort) {
+ lines.push("Cancellation arrived after the filesystem commit began; the committed edit completed.");
+ }
} else {
lines.push("Failed to apply some changes:");
for (const err of result.errors) {
@@ -2402,6 +4173,7 @@ function formatApplyResult(result) {
// ../lsp-core/src/lsp/directory-diagnostics.ts
var SKIP_DIRECTORIES = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
+var DIRECTORY_DIAGNOSTICS_MAX_CONCURRENCY = 4;
function collectFilesWithExtension(dir, extension, maxFiles) {
const files = [];
function walk(currentDir) {
@@ -2409,17 +4181,17 @@ function collectFilesWithExtension(dir, extension, maxFiles) {
return;
let entries = [];
try {
- entries = readdirSync(currentDir);
+ entries = readdirSync3(currentDir);
} catch {
return;
}
for (const entry of entries) {
if (files.length >= maxFiles)
return;
- const fullPath = join6(currentDir, entry);
+ const fullPath = join5(currentDir, entry);
let stat;
try {
- stat = lstatSync(fullPath);
+ stat = lstatSync4(fullPath);
} catch {
continue;
}
@@ -2437,52 +4209,65 @@ function collectFilesWithExtension(dir, extension, maxFiles) {
walk(dir);
return files;
}
-async function aggregateDiagnosticsForDirectory(directory, extension, severity, maxFiles = DEFAULT_MAX_DIRECTORY_FILES) {
+async function aggregateDiagnosticsForDirectory(directory, extension, severity, maxFiles = DEFAULT_MAX_DIRECTORY_FILES, options = {}) {
if (!extension.startsWith(".")) {
throw new LspInvalidPathError(`Extension must start with a dot (e.g., ".ts", not "${extension}"). Use ".${extension}" instead.`);
}
- const absDir = resolve3(contextCwd(), directory);
- if (!existsSync6(absDir)) {
+ const absDir = resolve8(options.workspaceRoot ?? contextCwd(), directory);
+ if (!existsSync10(absDir)) {
throw new LspInvalidPathError(`Directory does not exist: ${absDir}`);
}
- const serverResult = findServerForExtension(extension);
+ const serverResult = options.server === undefined ? findServerForExtension(extension) : { status: "found", server: options.server };
if (serverResult.status !== "found") {
throw new LspServerLookupError(formatServerLookupError(serverResult));
}
const server2 = serverResult.server;
- const allFiles = collectFilesWithExtension(absDir, extension, maxFiles + 1);
+ const allFiles = (options.listFiles ?? collectFilesWithExtension)(absDir, extension, maxFiles + 1);
const wasCapped = allFiles.length > maxFiles;
const filesToProcess = allFiles.slice(0, maxFiles);
if (filesToProcess.length === 0) {
- return [
+ const output = [
`Directory: ${absDir}`,
`Extension: ${extension}`,
"Files scanned: 0",
`No files found with extension "${extension}".`
].join(`
`);
+ return { output, totalDiagnostics: 0, fileFailures: [] };
}
- const root = findWorkspaceRoot(absDir);
- const manager = getLspManager();
+ const root = options.workspaceRoot ?? findWorkspaceRoot(absDir);
+ const manager = options.manager ?? getLspManager();
const allDiagnostics = [];
const fileErrors = [];
+ const maxConcurrency = Math.max(1, options.maxConcurrency ?? DIRECTORY_DIAGNOSTICS_MAX_CONCURRENCY);
+ options.signal?.throwIfAborted();
const client = await manager.getClient(root, server2);
try {
- for (const file of filesToProcess) {
- try {
- const result = await client.diagnostics(file);
- const filtered = filterDiagnosticsBySeverity(result.items, severity);
- allDiagnostics.push(...filtered.map((diagnostic) => ({
- filePath: file,
- diagnostic
- })));
- } catch (e) {
- fileErrors.push({
- file,
- error: e instanceof Error ? e.message : String(e)
- });
+ let nextIndex = 0;
+ const workers = Array.from({ length: Math.min(maxConcurrency, filesToProcess.length) }, async () => {
+ for (;; ) {
+ if (options.signal?.aborted)
+ return;
+ const file = filesToProcess[nextIndex];
+ nextIndex += 1;
+ if (file === undefined)
+ return;
+ try {
+ const result = await client.diagnostics(file, options.signal);
+ const filtered = filterDiagnosticsBySeverity(result.items, severity);
+ allDiagnostics.push(...filtered.map((diagnostic) => ({
+ filePath: file,
+ diagnostic
+ })));
+ } catch (e) {
+ fileErrors.push({
+ file,
+ error: e instanceof Error ? e.message : String(e)
+ });
+ }
}
- }
+ });
+ await Promise.all(workers);
} finally {
manager.releaseClient(root, server2.id);
}
@@ -2510,13 +4295,13 @@ async function aggregateDiagnosticsForDirectory(directory, extension, severity,
lines.push("", `... (${allDiagnostics.length - DEFAULT_MAX_DIAGNOSTICS} more diagnostics not shown)`);
}
}
- return lines.join(`
-`);
+ return { output: lines.join(`
+`), totalDiagnostics: allDiagnostics.length, fileFailures: fileErrors };
}
// ../lsp-core/src/lsp/infer-extension.ts
-import { lstatSync as lstatSync2, readdirSync as readdirSync2 } from "node:fs";
-import { join as join7 } from "node:path";
+import { lstatSync as lstatSync5, readdirSync as readdirSync4 } from "node:fs";
+import { join as join6 } from "node:path";
var SKIP_DIRECTORIES2 = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
var MAX_SCAN_ENTRIES = 500;
function inferExtensionFromDirectory(directory) {
@@ -2527,17 +4312,17 @@ function inferExtensionFromDirectory(directory) {
return;
let entries;
try {
- entries = readdirSync2(dir);
+ entries = readdirSync4(dir);
} catch {
return;
}
for (const entry of entries) {
if (scanned >= MAX_SCAN_ENTRIES)
return;
- const fullPath = join7(dir, entry);
+ const fullPath = join6(dir, entry);
let stat;
try {
- stat = lstatSync2(fullPath);
+ stat = lstatSync5(fullPath);
} catch {
continue;
}
@@ -2611,13 +4396,48 @@ function missingDependencyResult(error, details) {
details: {
...details,
error: message,
- errorKind: "missing_dependency"
+ errorKind: "missing_dependency",
+ ...availabilityDetails(error)
}
};
}
+function availabilityDetails(error) {
+ const availability = missingDependencyAvailability(error);
+ return availability === null ? {} : { availability };
+}
+function missingDependencyAvailability(error) {
+ if (!(error instanceof LspServerLookupError) || error.lookup === undefined)
+ return null;
+ const context = lspRequestContext();
+ switch (error.lookup.status) {
+ case "not_configured":
+ return {
+ kind: "not_configured",
+ extension: error.lookup.extension,
+ availableServers: [...error.lookup.availableServers],
+ projectConfigPaths: [...context.projectConfigPaths],
+ userConfigPath: context.userConfigPath,
+ installDecisionTool: context.capabilities.installDecisionTool
+ };
+ case "not_installed":
+ return {
+ kind: "not_installed",
+ serverId: error.lookup.server.id,
+ command: [...error.lookup.server.command],
+ extensions: [...error.lookup.server.extensions],
+ installHint: error.lookup.installHint,
+ installDecisionTool: context.capabilities.installDecisionTool,
+ installDecisionsPath: context.installDecisionsPath
+ };
+ default: {
+ const exhaustive = error.lookup;
+ return exhaustive;
+ }
+ }
+}
// ../lsp-core/src/tools/parameters.ts
-function isRecord4(value) {
+function isRecord7(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function requireString(params, key) {
@@ -2674,7 +4494,7 @@ async function executeLspDiagnostics(params, signal) {
const filePath = requireString(params, "filePath");
const severity = severityFilter(params);
try {
- const absPath = resolve4(contextCwd(), filePath);
+ const absPath = resolvePathInsideContext(filePath);
if (isDirectoryPath(absPath)) {
const extension = inferExtensionFromDirectory(absPath);
if (!extension) {
@@ -2691,18 +4511,33 @@ async function executeLspDiagnostics(params, signal) {
};
return text(message, details3);
}
- const output2 = await aggregateDiagnosticsForDirectory(absPath, extension, severity);
+ const output2 = await aggregateDiagnosticsForDirectory(absPath, extension, severity, undefined, signal === undefined ? {} : { signal });
const details2 = {
filePath,
severity,
mode: "directory",
diagnostics: [],
+ totalDiagnostics: output2.totalDiagnostics,
+ truncated: false,
+ fileFailures: [...output2.fileFailures]
+ };
+ return text(output2.output, details2);
+ }
+ const result = await withLspClient(filePath, async (client) => client.diagnostics(filePath, signal), "diagnostics", clientOptions(signal));
+ if (result.transientError) {
+ const message = result.transientError.message;
+ const details2 = {
+ filePath,
+ severity,
+ mode: "file",
+ diagnostics: [],
totalDiagnostics: 0,
- truncated: false
+ truncated: false,
+ error: message,
+ errorKind: result.transientError.kind
};
- return text(output2, details2);
+ return text(message, details2, true);
}
- const result = await withLspClient(filePath, async (client) => client.diagnostics(filePath), "diagnostics", clientOptions(signal));
const diagnostics = filterDiagnosticsBySeverity(asDiagnosticArray(result), severity);
const total = diagnostics.length;
const truncated = total > DEFAULT_MAX_DIAGNOSTICS;
@@ -2763,7 +4598,7 @@ async function executeLspGotoDefinition(params, signal) {
const line = requireNumber(params, "line");
const character = requireNumber(params, "character");
try {
- const result = await withLspClient(filePath, async (client) => client.definition(filePath, line, character), "definition", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.definition(filePath, line, character, signal), "definition", clientOptions(signal));
const locations = !result ? [] : Array.isArray(result) ? result : [result];
const details = { filePath, line, character, locations };
if (locations.length === 0)
@@ -2788,7 +4623,7 @@ async function executeLspFindReferences(params, signal) {
const character = requireNumber(params, "character");
const includeDeclaration = optionalBoolean(params, "includeDeclaration") ?? true;
try {
- const result = await withLspClient(filePath, async (client) => client.references(filePath, line, character, includeDeclaration), "references", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.references(filePath, line, character, includeDeclaration, signal), "references", clientOptions(signal));
const references = Array.isArray(result) ? result : [];
const total = references.length;
const truncated = total > DEFAULT_MAX_REFERENCES;
@@ -2824,181 +4659,13 @@ async function executeLspFindReferences(params, signal) {
}
}
-// ../lsp-core/src/lsp/workspace-edit.ts
-import { existsSync as existsSync7, readFileSync as readFileSync4, realpathSync, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
-import { dirname as dirname3, isAbsolute as isAbsolute3, relative, resolve as resolve5 } from "node:path";
-import { fileURLToPath as fileURLToPath2 } from "node:url";
-function errorMessage2(error) {
- return error instanceof Error ? error.message : String(error);
-}
-function isPathInsideWorkspace(filePath, workspaceRoot) {
- const relativePath = relative(workspaceRoot, filePath);
- return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute3(relativePath);
-}
-function realpathForValidation(filePath) {
- if (existsSync7(filePath))
- return realpathSync(filePath);
- const parent = dirname3(filePath);
- return resolve5(realpathSync(parent), relative(parent, filePath));
-}
-function uriToWorkspacePath(uri, workspaceRoot) {
- let filePath;
- try {
- filePath = fileURLToPath2(uri);
- } catch (error) {
- return { success: false, error: `non-file URI ${uri}: ${errorMessage2(error)}` };
- }
- let validatedPath;
- try {
- validatedPath = realpathForValidation(filePath);
- } catch (error) {
- return { success: false, error: `${filePath}: ${errorMessage2(error)}` };
- }
- if (!isPathInsideWorkspace(validatedPath, workspaceRoot)) {
- return { success: false, error: `${filePath}: outside workspace ${workspaceRoot}` };
- }
- return { success: true, path: filePath };
-}
-function applyTextEditsToFile(filePath, edits) {
- try {
- const content = readFileSync4(filePath, "utf-8");
- const lines = content.split(`
-`);
- const sortedEdits = [...edits].sort((a, b) => {
- if (b.range.start.line !== a.range.start.line) {
- return b.range.start.line - a.range.start.line;
- }
- return b.range.start.character - a.range.start.character;
- });
- for (const edit of sortedEdits) {
- const startLine = edit.range.start.line;
- const startChar = edit.range.start.character;
- const endLine = edit.range.end.line;
- const endChar = edit.range.end.character;
- if (startLine === endLine) {
- const line = lines[startLine] ?? "";
- lines[startLine] = line.substring(0, startChar) + edit.newText + line.substring(endChar);
- } else {
- const firstLine = lines[startLine] ?? "";
- const lastLine = lines[endLine] ?? "";
- const newContent = firstLine.substring(0, startChar) + edit.newText + lastLine.substring(endChar);
- lines.splice(startLine, endLine - startLine + 1, ...newContent.split(`
-`));
- }
- }
- writeFileSync2(filePath, lines.join(`
-`), "utf-8");
- return { success: true, editCount: edits.length };
- } catch (err) {
- return {
- success: false,
- editCount: 0,
- error: err instanceof Error ? err.message : String(err)
- };
- }
-}
-function applyWorkspaceEdit(edit, options = {}) {
- if (!edit) {
- return { success: false, filesModified: [], totalEdits: 0, errors: ["No edit provided"] };
- }
- const result = { success: true, filesModified: [], totalEdits: 0, errors: [] };
- const workspaceRoot = realpathSync(options.workspaceRoot ?? contextCwd());
- if (edit.changes) {
- for (const [uri, edits] of Object.entries(edit.changes)) {
- const validatedPath = uriToWorkspacePath(uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(validatedPath.error);
- continue;
- }
- const applyResult = applyTextEditsToFile(validatedPath.path, edits);
- if (applyResult.success) {
- result.filesModified.push(validatedPath.path);
- result.totalEdits += applyResult.editCount;
- } else {
- result.success = false;
- result.errors.push(`${validatedPath.path}: ${applyResult.error}`);
- }
- }
- }
- if (edit.documentChanges) {
- for (const change of edit.documentChanges) {
- if (!("kind" in change)) {
- const validatedPath = uriToWorkspacePath(change.textDocument.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(validatedPath.error);
- continue;
- }
- const applyResult = applyTextEditsToFile(validatedPath.path, change.edits);
- if (applyResult.success) {
- result.filesModified.push(validatedPath.path);
- result.totalEdits += applyResult.editCount;
- } else {
- result.success = false;
- result.errors.push(`${validatedPath.path}: ${applyResult.error}`);
- }
- continue;
- }
- if (change.kind === "create") {
- try {
- const validatedPath = uriToWorkspacePath(change.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(`Create ${change.uri}: ${validatedPath.error}`);
- continue;
- }
- writeFileSync2(validatedPath.path, "", "utf-8");
- result.filesModified.push(validatedPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Create ${change.uri}: ${String(err)}`);
- }
- } else if (change.kind === "rename") {
- try {
- const oldPath = uriToWorkspacePath(change.oldUri, workspaceRoot);
- const newPath = uriToWorkspacePath(change.newUri, workspaceRoot);
- if (!oldPath.success || !newPath.success) {
- const error = oldPath.success ? newPath.success ? "invalid URI" : newPath.error : oldPath.error;
- result.success = false;
- result.errors.push(`Rename ${change.oldUri}: ${error}`);
- continue;
- }
- const content = readFileSync4(oldPath.path, "utf-8");
- writeFileSync2(newPath.path, content, "utf-8");
- unlinkSync(oldPath.path);
- result.filesModified.push(newPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Rename ${change.oldUri}: ${String(err)}`);
- }
- } else if (change.kind === "delete") {
- try {
- const validatedPath = uriToWorkspacePath(change.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(`Delete ${change.uri}: ${validatedPath.error}`);
- continue;
- }
- unlinkSync(validatedPath.path);
- result.filesModified.push(validatedPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Delete ${change.uri}: ${String(err)}`);
- }
- }
- }
- }
- return result;
-}
-
// ../lsp-core/src/tools/rename.ts
async function executeLspPrepareRename(params, signal) {
const filePath = requireString(params, "filePath");
const line = requireNumber(params, "line");
const character = requireNumber(params, "character");
try {
- const result = await withLspClient(filePath, async (client) => client.prepareRename(filePath, line, character), "prepareRename", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.prepareRename(filePath, line, character, signal), "prepareRename", clientOptions(signal));
const details = { filePath, line, character, result };
return text(formatPrepareRenameResult(result), details);
} catch (error) {
@@ -3019,13 +4686,9 @@ async function executeLspRename(params, signal) {
const character = requireNumber(params, "character");
const newName = requireString(params, "newName");
try {
- const edit = await withLspClient(filePath, async (client, workspaceRoot) => ({
- edit: await client.rename(filePath, line, character, newName),
- workspaceRoot
- }), "rename", clientOptions(signal));
- const apply = applyWorkspaceEdit(edit.edit, { workspaceRoot: edit.workspaceRoot });
- const details = { filePath, line, character, newName, apply, edit: edit.edit };
- return text(formatApplyResult(apply), details, !apply.success);
+ const result = await withLspClient(filePath, async (client) => client.rename(filePath, line, character, newName, signal), "rename", clientOptions(signal));
+ const details = { filePath, line, character, newName, apply: result.apply, edit: result.edit };
+ return text(formatApplyResult(result.apply), details, !result.apply.success);
} catch (error) {
const missingDependency = missingDependencyResult(error, {
filePath,
@@ -3100,10 +4763,10 @@ async function executeLspSymbols(params, signal) {
errorKind: "missing_query"
});
}
- const symbols2 = await withLspClient(filePath, async (client) => client.workspaceSymbols(query), "workspaceSymbols", clientOptions(signal));
+ const symbols2 = await withLspClient(filePath, async (client) => client.workspaceSymbols(query, signal), "workspaceSymbols", clientOptions(signal));
return formatSymbolsResult(filePath, scope, symbols2, limit, query);
}
- const symbols = await withLspClient(filePath, async (client) => client.documentSymbols(filePath), "documentSymbols", clientOptions(signal));
+ const symbols = await withLspClient(filePath, async (client) => client.documentSymbols(filePath, signal), "documentSymbols", clientOptions(signal));
return formatSymbolsResult(filePath, scope, symbols, limit);
} catch (error) {
const query = optionalString(params, "query");
@@ -3269,12 +4932,12 @@ function matchesToolName(tool, name) {
return tool.name === name || (tool.aliases?.includes(name) ?? false);
}
function coerceToolArguments(value) {
- return isRecord4(value) ? value : {};
+ return isRecord7(value) ? value : {};
}
// ../lsp-core/src/mcp.ts
var SERVER_NAME = "lsp";
var SERVER_VERSION = "0.1.0";
-async function handleLspMcpRequest(input) {
+async function handleLspMcpRequest(input, options = {}) {
if (!isPlainRecord(input)) {
return errorResponse(null, -32600, "Invalid Request");
}
@@ -3296,24 +4959,27 @@ async function handleLspMcpRequest(input) {
return successResponse(id, { tools: LSP_MCP_TOOLS.map(describeTool) });
}
if (method === "tools/call") {
- return handleToolCall(id, input["params"]);
+ return handleToolCall(id, input["params"], options.signal);
}
return errorResponse(id, -32601, `Method not found: ${String(method)}`);
}
-async function handleToolCall(id, params) {
+async function handleToolCall(id, params, signal) {
if (!isPlainRecord(params) || typeof params["name"] !== "string") {
return errorResponse(id, -32602, "tools/call requires params.name");
}
try {
- const result = await executeLspTool(params["name"], coerceToolArguments(params["arguments"]));
+ const result = await executeLspTool(params["name"], coerceToolArguments(params["arguments"]), signal);
return successResponse(id, {
content: result.content,
isError: result.isError ?? false,
details: result.details
});
} catch (error) {
+ if (!(error instanceof Error)) {
+ throw error;
+ }
return successResponse(id, {
- content: [{ type: "text", text: messageFromError(error) }],
+ content: [{ type: "text", text: error.message }],
isError: true
});
}
@@ -3334,78 +5000,409 @@ function requestedProtocolVersion(params) {
// src/daemon-client.ts
import { connect as connect2 } from "node:net";
+import { homedir as homedir3 } from "node:os";
+import { join as join7 } from "node:path";
// src/ensure-daemon.ts
import { spawn as spawn2 } from "node:child_process";
-import { closeSync as closeSync2, existsSync as existsSync8, mkdirSync as mkdirSync3, openSync as openSync2 } from "node:fs";
+import { closeSync as closeSync2, mkdirSync as mkdirSync3, openSync as openSync2 } from "node:fs";
import { connect } from "node:net";
-import { dirname as dirname5 } from "node:path";
+import { dirname as dirname8 } from "node:path";
import { execPath } from "node:process";
-import { fileURLToPath as fileURLToPath3 } from "node:url";
-// src/lock.ts
-import { closeSync, mkdirSync as mkdirSync2, openSync, readFileSync as readFileSync5, unlinkSync as unlinkSync2, writeSync } from "node:fs";
-import { dirname as dirname4 } from "node:path";
-function isProcessAlive(pid) {
- if (!Number.isInteger(pid) || pid <= 0)
- return false;
+// src/ipc-protocol.ts
+import { randomBytes, timingSafeEqual } from "node:crypto";
+import {
+ chmodSync,
+ closeSync,
+ constants,
+ fchmodSync,
+ fstatSync,
+ lstatSync as lstatSync6,
+ mkdirSync as mkdirSync2,
+ openSync,
+ readFileSync as readFileSync5,
+ unlinkSync,
+ writeSync
+} from "node:fs";
+import { dirname as dirname7 } from "node:path";
+var OMO_DAEMON_PROTOCOL_VERSION = 1;
+var AUTH_ERROR_CODE = -32001;
+var PROTOCOL_ERROR_CODE = -32002;
+var AUTH_TOKEN_BYTES = 32;
+
+class UnsafePrivateDirectoryError extends Error {
+ path;
+ reason;
+ name = "UnsafePrivateDirectoryError";
+ code = "unsafe_private_directory";
+ constructor(path, reason) {
+ super(`unsafe private directory ${path}: ${reason}`);
+ this.path = path;
+ this.reason = reason;
+ }
+}
+function authEnvelope(token) {
+ return { protocolVersion: OMO_DAEMON_PROTOCOL_VERSION, token };
+}
+function readAuthToken(paths) {
try {
- process.kill(pid, 0);
- return true;
+ const token = readFileSync5(paths.auth, "utf8").trim();
+ return token.length > 0 ? token : null;
} catch (error) {
- return error.code === "EPERM";
+ if (error instanceof Error)
+ return null;
+ throw error;
}
}
-function readLockPid(lockPath) {
+function readOrCreateAuthToken(paths) {
+ const existing = readAuthToken(paths);
+ if (existing)
+ return existing;
+ return createAuthToken(paths);
+}
+function rotateAuthToken(paths) {
try {
- const pid = Number.parseInt(readFileSync5(lockPath, "utf8").trim(), 10);
- return Number.isInteger(pid) ? pid : null;
- } catch {
- return null;
+ unlinkSync(paths.auth);
+ } catch (error) {
+ if (!(error instanceof Error))
+ throw error;
}
+ return createAuthToken(paths);
}
-function tryAcquireLock(lockPath, ownerPid = process.pid) {
- mkdirSync2(dirname4(lockPath), { recursive: true });
- for (let attempt = 0;attempt < 2; attempt += 1) {
- const handle = writeLockFile(lockPath, ownerPid);
- if (handle)
- return handle;
- if (!reapStaleLock(lockPath))
- return null;
+function authenticateMessage(raw, expectedToken) {
+ const id = jsonRpcId2(raw);
+ if (!isPlainRecord(raw))
+ return authError(id);
+ const params = raw["params"];
+ if (!isPlainRecord(params))
+ return authError(id);
+ const envelope = params["_omo"];
+ if (!isPlainRecord(envelope))
+ return authError(id);
+ const protocolVersion = envelope["protocolVersion"];
+ if (protocolVersion !== OMO_DAEMON_PROTOCOL_VERSION)
+ return protocolError(id);
+ const token = envelope["token"];
+ if (typeof token !== "string" || !tokenMatches(token, expectedToken))
+ return authError(id);
+ const cleanParams = { ...params };
+ delete cleanParams["_omo"];
+ return { input: { ...raw, params: cleanParams }, id, method: typeof raw["method"] === "string" ? raw["method"] : undefined };
+}
+function isAuthErrorResponse(message) {
+ if (!isPlainRecord(message))
+ return false;
+ const error = message["error"];
+ if (!isPlainRecord(error))
+ return false;
+ const data = error["data"];
+ return error["code"] === AUTH_ERROR_CODE && isPlainRecord(data) && data["code"] === "daemon_authentication_failed";
+}
+function writePrivateFile(path, data) {
+ const fd = openSync(path, "w", 384);
+ try {
+ writeSync(fd, data);
+ } finally {
+ closeSync(fd);
}
- return null;
+ setPrivateFileMode(path);
}
-function writeLockFile(lockPath, ownerPid) {
+function ensurePrivateDirectory(path, options = {}) {
try {
- const fd = openSync(lockPath, "wx");
- writeSync(fd, `${ownerPid}
-`);
+ mkdirSync2(path, { recursive: true, mode: 448 });
+ } catch (error) {
+ if (errorCode2(error) !== "EEXIST")
+ throw error;
+ }
+ if (process.platform === "win32")
+ return;
+ const before = validatePrivateDirectory(path, options);
+ const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
+ try {
+ fchmodSync(fd, 448);
+ const after = validatePrivateDirectory(path, options);
+ const openStats = fstatSync(fd);
+ if (!sameDirectory(before, after) || !sameDirectory(before, openStats)) {
+ throw new UnsafePrivateDirectoryError(path, "changed_during_chmod");
+ }
+ } finally {
closeSync(fd);
- return { release: () => unlinkQuietly(lockPath) };
+ }
+}
+function setPrivateFileMode(path) {
+ if (process.platform !== "win32")
+ chmodSync(path, 384);
+}
+function createAuthToken(paths) {
+ ensurePrivateDirectory(dirname7(paths.auth));
+ const token = randomBytes(AUTH_TOKEN_BYTES).toString("base64url");
+ let fd;
+ try {
+ fd = openSync(paths.auth, "wx", 384);
} catch (error) {
- if (error.code === "EEXIST")
- return null;
+ if (errorCode2(error) === "EEXIST") {
+ const existing = readAuthToken(paths);
+ if (existing)
+ return existing;
+ }
throw error;
}
+ try {
+ writeSync(fd, `${token}
+`);
+ } finally {
+ closeSync(fd);
+ }
+ setPrivateFileMode(paths.auth);
+ return token;
}
-function reapStaleLock(lockPath) {
- const pid = readLockPid(lockPath);
- if (pid !== null && isProcessAlive(pid))
- return false;
- unlinkQuietly(lockPath);
- return true;
+function errorCode2(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
+}
+function validatePrivateDirectory(path, options) {
+ const stats = options.lstat ? options.lstat(path) : lstatPrivateDirectory(path);
+ if (stats.isSymbolicLink())
+ throw new UnsafePrivateDirectoryError(path, "symlink");
+ if (!stats.isDirectory())
+ throw new UnsafePrivateDirectoryError(path, "not_directory");
+ const currentUid = options.currentUid ? options.currentUid() : process.getuid?.();
+ if (currentUid !== undefined && stats.uid !== currentUid) {
+ throw new UnsafePrivateDirectoryError(path, "wrong_owner");
+ }
+ return stats;
+}
+function lstatPrivateDirectory(path) {
+ return lstatSync6(path);
+}
+function sameDirectory(a, b) {
+ return a.dev === b.dev && a.ino === b.ino;
+}
+function tokenMatches(candidate, expected) {
+ const candidateBytes = Buffer.from(candidate);
+ const expectedBytes = Buffer.from(expected);
+ return candidateBytes.length === expectedBytes.length && timingSafeEqual(candidateBytes, expectedBytes);
+}
+function jsonRpcId2(raw) {
+ if (!isPlainRecord(raw))
+ return null;
+ const id = raw["id"];
+ return typeof id === "string" || typeof id === "number" || id === null ? id : null;
+}
+function authError(id) {
+ return {
+ jsonrpc: "2.0",
+ id,
+ error: { code: AUTH_ERROR_CODE, message: "daemon authentication failed", data: { code: "daemon_authentication_failed" } }
+ };
+}
+function protocolError(id) {
+ return {
+ jsonrpc: "2.0",
+ id,
+ error: { code: PROTOCOL_ERROR_CODE, message: "daemon protocol mismatch", data: { code: "daemon_protocol_mismatch" } }
+ };
}
-function unlinkQuietly(path) {
+
+// src/paths.ts
+import { createHash as createHash2 } from "node:crypto";
+import { createRequire } from "node:module";
+import { homedir as homedir2, tmpdir, userInfo } from "node:os";
+import * as path from "node:path";
+import { fileURLToPath as fileURLToPath3 } from "node:url";
+
+// src/runtime-contract.ts
+import { statSync as statSync4 } from "node:fs";
+import { isAbsolute as isAbsolute3 } from "node:path";
+var OMO_LSP_DAEMON_DIR = "OMO_LSP_DAEMON_DIR";
+var OMO_LSP_DAEMON_CLI = "OMO_LSP_DAEMON_CLI";
+var OMO_LSP_DAEMON_VERSION = "OMO_LSP_DAEMON_VERSION";
+var DAEMON_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
+
+class InvalidRuntimeOverrideError extends Error {
+ code = "invalid_runtime_override";
+ reason;
+ constructor(reason, message) {
+ super(message);
+ this.name = "InvalidRuntimeOverrideError";
+ this.reason = reason;
+ }
+}
+
+class InvalidDaemonVersionError extends Error {
+ code = "invalid_daemon_version";
+ version;
+ constructor(version) {
+ super("LSP daemon version must match [A-Za-z0-9][A-Za-z0-9._+-]{0,127}");
+ this.name = "InvalidDaemonVersionError";
+ this.version = version;
+ }
+}
+function validateDaemonVersion(version) {
+ if (!DAEMON_VERSION_PATTERN.test(version))
+ throw new InvalidDaemonVersionError(version);
+ return version;
+}
+function resolveDaemonRuntime(env, defaults) {
+ const cliOverride = env[OMO_LSP_DAEMON_CLI];
+ const versionOverride = env[OMO_LSP_DAEMON_VERSION];
+ const hasCliOverride = cliOverride !== undefined;
+ const hasVersionOverride = versionOverride !== undefined;
+ if (hasCliOverride !== hasVersionOverride) {
+ throw new InvalidRuntimeOverrideError("paired_values_required", `${OMO_LSP_DAEMON_CLI} and ${OMO_LSP_DAEMON_VERSION} must be set together`);
+ }
+ if (!hasCliOverride || !hasVersionOverride) {
+ if (!isAbsolute3(defaults.cliPath)) {
+ throw new InvalidRuntimeOverrideError("packaged_cli_must_be_absolute", "Packaged LSP daemon CLI path must be absolute");
+ }
+ return { cliPath: defaults.cliPath, version: validateDaemonVersion(defaults.version) };
+ }
+ if (!isAbsolute3(cliOverride)) {
+ throw new InvalidRuntimeOverrideError("cli_must_be_absolute", `${OMO_LSP_DAEMON_CLI} must be an absolute path to an existing regular file`);
+ }
+ let cliStats;
try {
- unlinkSync2(path);
- } catch (error) {}
+ cliStats = statSync4(cliOverride);
+ } catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ throw new InvalidRuntimeOverrideError("cli_not_found", `${OMO_LSP_DAEMON_CLI} must name an existing regular file`);
+ }
+ if (!cliStats.isFile()) {
+ throw new InvalidRuntimeOverrideError("cli_not_file", `${OMO_LSP_DAEMON_CLI} must name an existing regular file`);
+ }
+ return { cliPath: cliOverride, version: validateDaemonVersion(versionOverride) };
+}
+
+// src/paths.ts
+var requireFromHere = createRequire(import.meta.url);
+var MAX_SOCKET_PATH_LENGTH = 100;
+
+class InvalidDaemonDirectoryError extends Error {
+ code = "invalid_daemon_directory";
+ directory;
+ constructor(directory) {
+ super(`${OMO_LSP_DAEMON_DIR} must be an absolute path`);
+ this.name = "InvalidDaemonDirectoryError";
+ this.directory = directory;
+ }
+}
+function resolveDaemonVersion(requireFn = requireFromHere) {
+ for (const candidate of ["./package.json", "../package.json"]) {
+ let loaded;
+ try {
+ loaded = requireFn(candidate);
+ } catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ continue;
+ }
+ if (typeof loaded === "object" && loaded !== null && "version" in loaded) {
+ const version = Reflect.get(loaded, "version");
+ if (typeof version === "string")
+ return validateDaemonVersion(version);
+ }
+ }
+ return "0";
+}
+function packagedRuntimeDefaults() {
+ return {
+ cliPath: fileURLToPath3(new URL("./cli.js", import.meta.url)),
+ version: resolveDaemonVersion()
+ };
+}
+function daemonBaseDir(env = process.env, platform = defaultDaemonPlatform()) {
+ const override = env[OMO_LSP_DAEMON_DIR];
+ if (override !== undefined) {
+ if (!platform.path.isAbsolute(override))
+ throw new InvalidDaemonDirectoryError(override);
+ return platform.path.resolve(override);
+ }
+ return platform.path.resolve(platform.path.join(platform.homedir(), ".omo", "lsp-daemon"));
+}
+function daemonPaths(env = process.env, runtimeDefaults = packagedRuntimeDefaults(), platform = defaultDaemonPlatform()) {
+ const runtime = resolveDaemonRuntime(env, runtimeDefaults);
+ const baseDir = daemonBaseDir(env, platform);
+ const dir = platform.path.resolve(platform.path.join(baseDir, `v${runtime.version}`));
+ return {
+ version: runtime.version,
+ cliPath: runtime.cliPath,
+ dir,
+ socket: resolveSocketPath(dir, runtime.version, platform),
+ lock: platform.path.join(dir, "daemon.lock"),
+ pid: platform.path.join(dir, "daemon.pid"),
+ auth: platform.path.join(dir, "daemon.auth"),
+ endpoint: platform.path.join(dir, "daemon.endpoint"),
+ owner: platform.path.join(dir, "daemon.owner"),
+ log: platform.path.join(dir, "daemon.log")
+ };
+}
+function defaultDaemonPlatform() {
+ return {
+ platform: process.platform,
+ homedir: homedir2,
+ tmpdir,
+ getuid: () => typeof process.getuid === "function" ? process.getuid() : undefined,
+ username: () => userInfo().username,
+ path
+ };
+}
+function resolveSocketPath(dir, version, platform) {
+ const canonicalVersionDir = platform.path.resolve(dir);
+ if (platform.platform === "win32") {
+ const currentUserDiscriminator = `${platform.getuid() ?? "win"}:${platform.username()}:${platform.path.resolve(platform.homedir())}`;
+ const digest = shortDigest(`${canonicalVersionDir}\x00${currentUserDiscriminator}`);
+ return `\\\\.\\pipe\\omo-lsp-${version}-${digest}`;
+ }
+ const natural = platform.path.join(canonicalVersionDir, "daemon.sock");
+ if (natural.length < MAX_SOCKET_PATH_LENGTH)
+ return natural;
+ return platform.path.join(platform.tmpdir(), `omo-lsp-${version}-${shortDigest(canonicalVersionDir)}`, "daemon.sock");
+}
+function shortDigest(value) {
+ return createHash2("sha256").update(value).digest("hex").slice(0, 16);
+}
+
+// src/socket-jsonrpc.ts
+function encodeJsonLine(message) {
+ return `${JSON.stringify(message)}
+`;
+}
+function createLineDecoder(onMessage, onParseError) {
+ let buffer = "";
+ return {
+ push(chunk) {
+ buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ let index = buffer.indexOf(`
+`);
+ while (index !== -1) {
+ const raw = buffer.slice(0, index).trim();
+ buffer = buffer.slice(index + 1);
+ if (raw.length > 0) {
+ try {
+ onMessage(JSON.parse(raw));
+ } catch (error) {
+ if (error instanceof Error) {
+ onParseError?.(raw, error);
+ } else {
+ throw error;
+ }
+ }
+ }
+ index = buffer.indexOf(`
+`);
+ }
+ }
+ };
}
// src/ensure-daemon.ts
var PROBE_TIMEOUT_MS = 500;
var DEFAULT_READY_TIMEOUT_MS = 5000;
var DEFAULT_POLL_INTERVAL_MS = 100;
-var CODEX_LSP_DAEMON_CLI_ENV = "CODEX_LSP_DAEMON_CLI";
class DaemonUnreachableError extends Error {
constructor(socketPath) {
@@ -3416,58 +5413,59 @@ class DaemonUnreachableError extends Error {
async function ensureDaemonRunning(paths, deps = defaultEnsureDaemonDeps(), options = {}) {
const readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
- if (await deps.probe(paths.socket))
- return;
- const lock = deps.acquireLock(paths.lock);
- if (!lock) {
- await waitUntilReachable(paths.socket, deps, readyTimeoutMs, pollIntervalMs);
+ if (await deps.probe(paths))
return;
- }
- try {
- if (await deps.probe(paths.socket))
- return;
- deps.cleanupStaleSocket(paths.socket);
- deps.spawnDaemon(paths);
- await waitUntilReachable(paths.socket, deps, readyTimeoutMs, pollIntervalMs);
- } finally {
- lock.release();
- }
+ deps.spawnDaemon(paths);
+ await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs);
}
-async function waitUntilReachable(socketPath, deps, readyTimeoutMs, pollIntervalMs) {
+async function waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs) {
const deadline = deps.now() + readyTimeoutMs;
for (;; ) {
- if (await deps.probe(socketPath))
+ if (await deps.probe(paths))
return;
if (deps.now() >= deadline)
- throw new DaemonUnreachableError(socketPath);
+ throw new DaemonUnreachableError(paths.socket);
await deps.sleep(pollIntervalMs);
}
}
-function probeSocket(socketPath, timeoutMs = PROBE_TIMEOUT_MS) {
- return new Promise((resolve6) => {
- const socket = connect(socketPath);
- const finish = (ok) => {
+async function probeDaemon(paths, timeoutMs = PROBE_TIMEOUT_MS) {
+ const token = readAuthToken(paths);
+ if (!token)
+ return false;
+ return await pingDaemon(paths, token, timeoutMs) !== null;
+}
+function pingDaemon(paths, token, timeoutMs = PROBE_TIMEOUT_MS) {
+ return new Promise((resolve9) => {
+ const socket = connect(paths.socket);
+ let settled = false;
+ const finish = (value) => {
+ if (settled)
+ return;
+ settled = true;
socket.destroy();
- resolve6(ok);
+ resolve9(value);
};
- const timer = setTimeout(() => finish(false), timeoutMs);
+ const timer = setTimeout(() => finish(null), timeoutMs);
timer.unref?.();
- socket.once("connect", () => {
+ const decoder = createLineDecoder((message) => {
clearTimeout(timer);
- finish(true);
+ finish(parsePingResponse(message));
+ });
+ socket.once("connect", () => {
+ socket.write(encodeJsonLine({ jsonrpc: "2.0", id: 1, method: "omo/ping", params: { _omo: authEnvelope(token) } }));
});
+ socket.on("data", (chunk) => decoder.push(chunk));
socket.once("error", () => {
clearTimeout(timer);
- finish(false);
+ finish(null);
});
});
}
function spawnDaemonProcess(paths) {
- mkdirSync3(dirname5(paths.log), { recursive: true });
+ mkdirSync3(dirname8(paths.log), { recursive: true });
const logFd = openSync2(paths.log, "a");
try {
- const cliPath = resolveDaemonCliPath();
- const child = spawn2(execPath, [cliPath, "daemon"], {
+ const child = spawn2(execPath, [paths.cliPath, "daemon"], {
detached: true,
stdio: ["ignore", logFd, logFd]
});
@@ -3476,156 +5474,133 @@ function spawnDaemonProcess(paths) {
closeSync2(logFd);
}
}
-function resolveDaemonCliPath(env = process.env) {
- const override = env[CODEX_LSP_DAEMON_CLI_ENV]?.trim();
- if (override)
- return override;
- return fileURLToPath3(new URL("./cli.js", import.meta.url));
-}
function defaultEnsureDaemonDeps() {
return {
- probe: (socketPath) => probeSocket(socketPath),
- acquireLock: (lockPath) => tryAcquireLock(lockPath),
- cleanupStaleSocket: (socketPath) => {
- if (existsSync8(socketPath))
- unlinkQuietly(socketPath);
- },
+ probe: (paths) => probeDaemon(paths),
spawnDaemon: (paths) => spawnDaemonProcess(paths),
- sleep: (ms) => new Promise((resolve6) => {
- setTimeout(resolve6, ms);
+ sleep: (ms) => new Promise((resolve9) => {
+ setTimeout(resolve9, ms);
}),
now: () => Date.now()
};
}
-
-// src/paths.ts
-import { createHash } from "node:crypto";
-import { createRequire } from "node:module";
-import { homedir as homedir3, tmpdir } from "node:os";
-import { join as join8 } from "node:path";
-var requireFromHere = createRequire(import.meta.url);
-var MAX_SOCKET_PATH_LENGTH = 100;
-var CODEX_LSP_DAEMON_VERSION_ENV = "CODEX_LSP_DAEMON_VERSION";
-function resolveDaemonVersion(requireFn = requireFromHere) {
- for (const candidate of ["./package.json", "../package.json"]) {
- try {
- const pkg = requireFn(candidate);
- if (typeof pkg.version === "string" && pkg.version.length > 0)
- return pkg.version;
- } catch {}
- }
- return "0";
-}
-function daemonBaseDir(env = process.env) {
- const explicit = env["CODEX_LSP_DAEMON_DIR"]?.trim();
- if (explicit)
- return explicit;
- const pluginData = env["PLUGIN_DATA"]?.trim();
- if (pluginData)
- return join8(pluginData, "daemon");
- const codexHome = env["CODEX_HOME"]?.trim();
- const home = codexHome && codexHome.length > 0 ? codexHome : join8(homedir3(), ".codex");
- return join8(home, "codex-lsp", "daemon");
-}
-function daemonPaths(env = process.env, version = resolveDaemonVersionFromEnv(env) ?? resolveDaemonVersion()) {
- const dir = join8(daemonBaseDir(env), `v${version}`);
- return {
- version,
- dir,
- socket: resolveSocketPath(dir, version),
- lock: join8(dir, "daemon.lock"),
- pid: join8(dir, "daemon.pid"),
- log: join8(dir, "daemon.log")
- };
-}
-function resolveDaemonVersionFromEnv(env = process.env) {
- const version = env[CODEX_LSP_DAEMON_VERSION_ENV]?.trim();
- return version && version.length > 0 ? version : null;
-}
-function resolveSocketPath(dir, version) {
- const digest = createHash("sha256").update(dir).digest("hex").slice(0, 16);
- if (process.platform === "win32") {
- return `\\\\.\\pipe\\omo-lsp-${version}-${digest}`;
+function parsePingResponse(message) {
+ if (!message || typeof message !== "object" || Array.isArray(message))
+ return null;
+ const result = Reflect.get(message, "result");
+ if (!result || typeof result !== "object" || Array.isArray(result))
+ return null;
+ const pid = Reflect.get(result, "pid");
+ const nonce = Reflect.get(result, "nonce");
+ const startedAt = Reflect.get(result, "startedAt");
+ const endpoint = Reflect.get(result, "endpoint");
+ if (typeof pid !== "number" || typeof nonce !== "string" || typeof startedAt !== "string")
+ return null;
+ if (!endpoint || typeof endpoint !== "object" || Array.isArray(endpoint))
+ return null;
+ const path2 = Reflect.get(endpoint, "path");
+ const kind = Reflect.get(endpoint, "kind");
+ if (typeof path2 !== "string")
+ return null;
+ if (kind === "windows")
+ return { pid, nonce, startedAt, endpoint: { kind, path: path2 } };
+ if (kind === "missing")
+ return { pid, nonce, startedAt, endpoint: { kind, path: path2 } };
+ const dev = Reflect.get(endpoint, "dev");
+ const ino = Reflect.get(endpoint, "ino");
+ if (kind === "unix" && typeof dev === "number" && typeof ino === "number") {
+ return { pid, nonce, startedAt, endpoint: { kind, path: path2, dev, ino } };
}
- const natural = join8(dir, "daemon.sock");
- if (natural.length < MAX_SOCKET_PATH_LENGTH)
- return natural;
- return join8(tmpdir(), `omo-lsp-${version}-${digest}.sock`);
+ return null;
}
// src/request-routing.ts
var CONTEXT_KEY = "_context";
+
+class InvalidDaemonRequestError extends Error {
+ name = "InvalidDaemonRequestError";
+}
function extractRequestContext(raw) {
if (!isPlainRecord(raw) || raw["method"] !== "tools/call")
return { input: raw, context: undefined };
const params = raw["params"];
if (!isPlainRecord(params))
- return { input: raw, context: undefined };
+ throw new InvalidDaemonRequestError("Daemon tools/call params must be an object.");
const args = params["arguments"];
if (!isPlainRecord(args))
- return { input: raw, context: undefined };
+ throw new InvalidDaemonRequestError("Daemon tools/call arguments must be an object.");
+ if (!Object.hasOwn(args, CONTEXT_KEY)) {
+ throw new InvalidDaemonRequestError("Daemon tools/call arguments must include _context.");
+ }
const context = parseContext(args[CONTEXT_KEY]);
- if (!context)
- return { input: raw, context: undefined };
const cleanedArgs = { ...args };
delete cleanedArgs[CONTEXT_KEY];
const cleaned = { ...raw, params: { ...params, arguments: cleanedArgs } };
return { input: cleaned, context };
}
-function handleDaemonMessage(raw) {
- const { input, context } = extractRequestContext(raw);
- if (context)
- return runWithRequestContext(context, () => handleLspMcpRequest(input));
- return handleLspMcpRequest(input);
-}
-function parseContext(value) {
- if (!isPlainRecord(value))
- return;
- const context = {};
- const cwd = value["cwd"];
- if (typeof cwd === "string")
- context.cwd = cwd;
- const env = value["env"];
- if (isStringRecord2(env))
- context.env = env;
- return context.cwd === undefined && context.env === undefined ? undefined : context;
+function handleDaemonMessage(raw, state) {
+ const authenticated = authenticateMessage(raw, state.token);
+ if ("error" in authenticated)
+ return Promise.resolve(authenticated);
+ if (authenticated.method === "omo/ping") {
+ return Promise.resolve({
+ jsonrpc: "2.0",
+ id: authenticated.id,
+ result: { protocolVersion: OMO_DAEMON_PROTOCOL_VERSION, ...state.owner }
+ });
+ }
+ if (authenticated.method === "$/cancelRequest") {
+ const targetId = cancellationTargetId(authenticated.input);
+ if (targetId !== undefined)
+ state.activeRequests?.get(String(targetId))?.abort();
+ return Promise.resolve(undefined);
+ }
+ let routed;
+ try {
+ routed = extractRequestContext(authenticated.input);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "invalid daemon request";
+ return Promise.resolve({
+ jsonrpc: "2.0",
+ id: authenticated.id,
+ error: { code: -32602, message, data: { code: "invalid_daemon_request" } }
+ });
+ }
+ const { input, context } = routed;
+ const key = routeRequestKey(authenticated.id);
+ if (key === undefined || !state.activeRequests) {
+ if (context)
+ return runWithRequestContext(context, () => handleLspMcpRequest(input));
+ return handleLspMcpRequest(input);
+ }
+ const controller = new AbortController;
+ state.activeRequests.set(key, controller);
+ const options = { signal: controller.signal };
+ const run = context ? runWithRequestContext(context, () => handleLspMcpRequest(input, options)) : handleLspMcpRequest(input, options);
+ return run.finally(() => {
+ if (state.activeRequests?.get(key) === controller)
+ state.activeRequests.delete(key);
+ });
}
-function isStringRecord2(value) {
- return isPlainRecord(value) && Object.values(value).every((item) => typeof item === "string");
+function routeRequestKey(id) {
+ return typeof id === "string" || typeof id === "number" ? String(id) : undefined;
}
-
-// src/socket-jsonrpc.ts
-function encodeJsonLine(message) {
- return `${JSON.stringify(message)}
-`;
+function cancellationTargetId(input) {
+ const params = input["params"];
+ if (!isPlainRecord(params))
+ return;
+ const id = params["id"];
+ return typeof id === "string" || typeof id === "number" ? id : undefined;
}
-function createLineDecoder(onMessage, onParseError) {
- let buffer = "";
- return {
- push(chunk) {
- buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
- let index = buffer.indexOf(`
-`);
- while (index !== -1) {
- const raw = buffer.slice(0, index).trim();
- buffer = buffer.slice(index + 1);
- if (raw.length > 0) {
- try {
- onMessage(JSON.parse(raw));
- } catch (error) {
- onParseError?.(raw, error);
- }
- }
- index = buffer.indexOf(`
-`);
- }
- }
- };
+function parseContext(value) {
+ if (!isPlainRecord(value))
+ throw new InvalidDaemonRequestError("LSP request _context must be an object.");
+ return parseLspRequestContext(value);
}
// src/daemon-client.ts
var DEFAULT_REQUEST_TIMEOUT_MS = 30000;
-var REQUEST_ID = 1;
+var nextProxyRequestId = 1;
class DaemonRequestError extends Error {
requestWritten;
@@ -3635,44 +5610,70 @@ class DaemonRequestError extends Error {
this.requestWritten = requestWritten;
}
}
-async function callToolViaDaemon(name, args, options = {}) {
+
+class DaemonAuthenticationRejectedError extends DaemonRequestError {
+ constructor() {
+ super("daemon authentication failed before dispatch", true);
+ this.name = "DaemonAuthenticationRejectedError";
+ }
+}
+
+class DaemonRequestCancelledError extends DaemonRequestError {
+ constructor(requestWritten) {
+ super("daemon request cancelled", requestWritten);
+ this.name = "DaemonRequestCancelledError";
+ }
+}
+async function callToolViaDaemon(name, args, options) {
+ const context = requireContext(options.context);
const paths = options.paths ?? daemonPaths();
const ensure = options.ensure ?? ensureDaemonRunning;
const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
- const requestArgs = withContext(args, options.context);
+ const requestArgs = withContext(args, context);
let lastError;
- for (let attempt = 0;attempt < 2; attempt += 1) {
+ let authRefreshUsed = false;
+ for (let attempt = 0;attempt < 3; attempt += 1) {
try {
await ensure(paths);
- return await sendToolCall(paths.socket, name, requestArgs, timeoutMs);
+ const token = readAuthToken(paths);
+ if (!token)
+ throw new DaemonRequestError("daemon auth token missing", false);
+ const sendOptions = options.signal === undefined ? { timeoutMs } : { timeoutMs, signal: options.signal };
+ return await sendToolCall(paths, token, name, requestArgs, sendOptions);
} catch (error) {
lastError = error;
- if (error instanceof DaemonRequestError && error.requestWritten)
+ if (error instanceof DaemonAuthenticationRejectedError && !authRefreshUsed) {
+ authRefreshUsed = true;
+ continue;
+ }
+ if (error instanceof DaemonRequestCancelledError)
+ break;
+ if (error instanceof DaemonRequestError && (error.requestWritten || !isRetryableTool(name)))
break;
}
}
return daemonUnreachableResult(paths, lastError);
}
-function callDiagnosticsViaDaemon(filePath, options = {}) {
+function callDiagnosticsViaDaemon(filePath, options) {
return callToolViaDaemon("diagnostics", { filePath, severity: "error" }, options);
}
-var FORWARDED_ENV_KEYS = [
- "LSP_TOOLS_MCP_PROJECT_CONFIG",
- "LSP_TOOLS_MCP_USER_CONFIG",
- "LSP_TOOLS_MCP_INSTALL_DECISIONS"
-];
function currentRequestContext(env = process.env) {
- const forwarded = {};
- for (const key of FORWARDED_ENV_KEYS) {
- const value = env[key];
- if (value !== undefined)
- forwarded[key] = value;
- }
- return { cwd: process.cwd(), env: forwarded };
+ const cwd = process.cwd();
+ const home = env["HOME"] ?? homedir3();
+ return parseLspRequestContext({
+ cwd,
+ projectConfigPaths: [join7(cwd, ".codex", "lsp-client.json")],
+ userConfigPath: join7(home, ".codex", "lsp-client.json"),
+ installDecisionsPath: join7(home, ".codex", "lsp-install-decisions.json"),
+ capabilities: { installDecisionTool: true }
+ });
+}
+function requireContext(context) {
+ if (!context)
+ throw new DaemonRequestError("daemon tool context is required", false);
+ return parseLspRequestContext(context);
}
function withContext(args, context) {
- if (!context || context.cwd === undefined && context.env === undefined)
- return args;
return { ...args, [CONTEXT_KEY]: context };
}
function daemonUnreachableResult(paths, error) {
@@ -3686,39 +5687,84 @@ function daemonUnreachableResult(paths, error) {
`);
return { content: [{ type: "text", text: text2 }], isError: true };
}
-function sendToolCall(socketPath, name, args, timeoutMs) {
- return new Promise((resolve6, reject) => {
- const socket = connect2(socketPath);
+function sendToolCall(paths, token, name, args, options) {
+ return new Promise((resolve9, reject) => {
+ const socket = connect2(paths.socket);
+ const requestId = allocateProxyRequestId();
let settled = false;
let requestWritten = false;
+ let cancelAfterWrite = false;
+ const cancelPayload = () => encodeJsonLine({
+ jsonrpc: "2.0",
+ method: "$/cancelRequest",
+ params: { _omo: authEnvelope(token), id: requestId }
+ });
const finish = (run) => {
if (settled)
return;
settled = true;
clearTimeout(timer);
- socket.destroy();
+ options.signal?.removeEventListener("abort", onAbort);
+ destroyAfterCancel();
run();
};
- const timer = setTimeout(() => finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten))), timeoutMs);
+ const sendCancel = () => {
+ if (!requestWritten) {
+ cancelAfterWrite = true;
+ return;
+ }
+ if (!socket.writable)
+ return;
+ socket.write(cancelPayload());
+ };
+ const destroyAfterCancel = () => {
+ socket.destroy();
+ };
+ const onAbort = () => {
+ sendCancel();
+ finish(() => reject(new DaemonRequestCancelledError(requestWritten)));
+ };
+ const timer = setTimeout(() => {
+ sendCancel();
+ finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten)));
+ }, options.timeoutMs);
timer.unref();
+ if (options.signal?.aborted) {
+ onAbort();
+ return;
+ }
+ options.signal?.addEventListener("abort", onAbort, { once: true });
const decoder = createLineDecoder((message) => {
- const result = toToolResult(message);
+ if (isAuthErrorResponse(message)) {
+ finish(() => reject(new DaemonAuthenticationRejectedError));
+ return;
+ }
+ const result = toToolResult(message, requestId);
if (result)
- finish(() => resolve6(result));
+ finish(() => resolve9(result));
else
finish(() => reject(new DaemonRequestError("invalid daemon response", requestWritten)));
});
socket.once("connect", () => {
- requestWritten = true;
- socket.write(encodeJsonLine({ jsonrpc: "2.0", id: REQUEST_ID, method: "tools/call", params: { name, arguments: args } }));
+ const payload = encodeJsonLine({
+ jsonrpc: "2.0",
+ id: requestId,
+ method: "tools/call",
+ params: { _omo: authEnvelope(token), name, arguments: args }
+ });
+ socket.write(payload, () => {
+ requestWritten = true;
+ if (cancelAfterWrite && socket.writable)
+ socket.write(cancelPayload());
+ });
});
socket.on("data", (chunk) => decoder.push(chunk));
socket.once("error", (error) => finish(() => reject(new DaemonRequestError(error.message, requestWritten))));
socket.once("close", () => finish(() => reject(new DaemonRequestError("daemon connection closed", requestWritten))));
});
}
-function toToolResult(message) {
- if (!isPlainRecord(message) || message["id"] !== REQUEST_ID)
+function toToolResult(message, requestId) {
+ if (!isPlainRecord(message) || message["id"] !== requestId)
return null;
const result = message["result"];
if (!isPlainRecord(result) || !Array.isArray(result["content"]))
@@ -3729,6 +5775,16 @@ function toToolResult(message) {
details: result["details"]
};
}
+function allocateProxyRequestId() {
+ const id = nextProxyRequestId;
+ nextProxyRequestId += 1;
+ if (nextProxyRequestId > Number.MAX_SAFE_INTEGER)
+ nextProxyRequestId = 1;
+ return id;
+}
+function isRetryableTool(name) {
+ return name !== "rename" && name !== "lsp_rename";
+}
function errorText(error) {
return error instanceof Error ? error.message : String(error);
}
@@ -3738,13 +5794,21 @@ async function runMcpStdioProxy(options = {}) {
const input = options.input ?? process.stdin;
const output = options.output ?? process.stdout;
const paths = options.paths ?? daemonPaths();
- const context = options.context ?? currentRequestContext();
+ const env = options.env ?? process.env;
+ const cwd = options.cwd ?? inferOpenCodeProjectCwd(env["LSP_TOOLS_MCP_PROJECT_CONFIG"]);
+ const contextEnv = cwd === undefined ? env : canonicalizeContextEnv(env);
+ const contextInput = {
+ env: contextEnv,
+ ...cwd === undefined ? {} : { cwd },
+ ...options.homeDir === undefined ? {} : { homeDir: options.homeDir }
+ };
+ const context = options.context ?? createStandaloneMcpRequestContext(contextInput);
const callOptions = { paths, context, ...options.ensure ? { ensure: options.ensure } : {} };
await runJsonRpcStdioServer({
input,
output,
idleTimeoutMs: 0,
- handler: handleProxyRequest,
+ handler: (request, requestOptions) => runWithRequestContext(context, () => handleProxyRequest(request, requestOptions)),
handlerOptions: callOptions,
onHandlerError: (error) => {
process.stderr.write(`[lsp-daemon] proxy error: ${error instanceof Error ? error.message : String(error)}
@@ -3768,43 +5832,332 @@ function asToolCall(parsed) {
const args = params["arguments"];
return { id: jsonRpcId(parsed["id"]), name: params["name"], args: isPlainRecord(args) ? args : {} };
}
+function inferOpenCodeProjectCwd(projectConfigEnv) {
+ if (!projectConfigEnv)
+ return;
+ for (const entry of projectConfigEnv.split(delimiter4)) {
+ const projectRoot = projectRootFromOpenCodeConfigPath(entry);
+ if (projectRoot)
+ return projectRoot;
+ }
+ return;
+}
+function canonicalizeContextEnv(env) {
+ return {
+ ...env,
+ LSP_TOOLS_MCP_PROJECT_CONFIG: canonicalizePathList(env["LSP_TOOLS_MCP_PROJECT_CONFIG"]),
+ LSP_TOOLS_MCP_USER_CONFIG: canonicalizePath(env["LSP_TOOLS_MCP_USER_CONFIG"]),
+ LSP_TOOLS_MCP_INSTALL_DECISIONS: canonicalizePath(env["LSP_TOOLS_MCP_INSTALL_DECISIONS"])
+ };
+}
+function canonicalizePathList(value) {
+ if (value === undefined)
+ return;
+ return value.split(delimiter4).map((entry) => canonicalizePath(entry) ?? entry).join(delimiter4);
+}
+function canonicalizePath(value) {
+ if (value === undefined || !isAbsolute4(value) || !existsSync11(value))
+ return value;
+ return realpathSync4(value);
+}
+function projectRootFromOpenCodeConfigPath(path2) {
+ if (basename3(path2) !== "lsp.json" && basename3(path2) !== "lsp-client.json")
+ return;
+ const configDir = dirname9(path2);
+ const configDirName = basename3(configDir);
+ if (configDirName !== ".opencode" && configDirName !== ".omo")
+ return;
+ return dirname9(configDir);
+}
// src/daemon-server.ts
-import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync3 } from "node:fs";
+import { chmodSync as chmodSync2 } from "node:fs";
import { createServer as createServer2 } from "node:net";
-import { join as join9 } from "node:path";
+
+// src/ownership.ts
+import { randomUUID } from "node:crypto";
+import { existsSync as existsSync12, lstatSync as lstatSync7, readFileSync as readFileSync7, statSync as statSync5, unlinkSync as unlinkSync3 } from "node:fs";
+import { dirname as dirname11 } from "node:path";
+
+// src/lock.ts
+import { closeSync as closeSync3, mkdirSync as mkdirSync4, openSync as openSync3, readFileSync as readFileSync6, unlinkSync as unlinkSync2, writeSync as writeSync2 } from "node:fs";
+import { dirname as dirname10 } from "node:path";
+function isProcessAlive(pid) {
+ if (!Number.isInteger(pid) || pid <= 0)
+ return false;
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ if (error instanceof Error)
+ return errorCode3(error) === "EPERM";
+ throw error;
+ }
+}
+function readLockPid(lockPath) {
+ try {
+ const pid = Number.parseInt(readFileSync6(lockPath, "utf8").trim(), 10);
+ return Number.isInteger(pid) ? pid : null;
+ } catch {
+ return null;
+ }
+}
+function tryAcquireLock(lockPath, ownerPid = process.pid) {
+ mkdirSync4(dirname10(lockPath), { recursive: true });
+ for (let attempt = 0;attempt < 2; attempt += 1) {
+ const handle = writeLockFile(lockPath, ownerPid);
+ if (handle)
+ return handle;
+ if (!reapStaleLock(lockPath))
+ return null;
+ }
+ return null;
+}
+function writeLockFile(lockPath, ownerPid) {
+ try {
+ const fd = openSync3(lockPath, "wx", 384);
+ writeSync2(fd, `${ownerPid}
+`);
+ closeSync3(fd);
+ return { release: () => unlinkQuietly(lockPath) };
+ } catch (error) {
+ if (errorCode3(error) === "EEXIST")
+ return null;
+ throw error;
+ }
+}
+function reapStaleLock(lockPath) {
+ const pid = readLockPid(lockPath);
+ if (pid !== null && isProcessAlive(pid))
+ return false;
+ unlinkQuietly(lockPath);
+ return true;
+}
+function unlinkQuietly(path2) {
+ try {
+ unlinkSync2(path2);
+ } catch (error) {
+ if (error instanceof Error)
+ return;
+ throw error;
+ }
+}
+function errorCode3(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
+}
+
+// src/ownership.ts
+class DaemonAlreadyRunningError extends Error {
+ name = "DaemonAlreadyRunningError";
+ code = "daemon_already_running";
+}
+
+class DaemonStartupDeferredError extends Error {
+ reason;
+ name = "DaemonStartupDeferredError";
+ code = "daemon_startup_deferred";
+ constructor(reason) {
+ super(`LSP daemon startup deferred: ${reason}`);
+ this.reason = reason;
+ }
+}
+async function acquireStartupLease(paths, pingOwner) {
+ ensureDaemonDirectories(paths);
+ const lock = tryAcquireLock(paths.lock);
+ if (!lock) {
+ const token = readAuthToken(paths);
+ if (token && await pingOwner(token))
+ throw new DaemonAlreadyRunningError("LSP daemon already running");
+ throw new DaemonStartupDeferredError("startup_lock_busy");
+ }
+ try {
+ const token = await validateExistingOwner(paths, pingOwner);
+ return { lock, token, owner: newOwner(paths) };
+ } catch (error) {
+ lock.release();
+ throw error;
+ }
+}
+function ensureDaemonDirectories(paths) {
+ ensurePrivateDirectory(paths.dir);
+ if (process.platform !== "win32")
+ ensurePrivateDirectory(dirname11(paths.socket));
+}
+function readDaemonOwner(paths) {
+ try {
+ return parseOwner(JSON.parse(readFileSync7(paths.owner, "utf8")));
+ } catch (error) {
+ if (error instanceof Error)
+ return null;
+ throw error;
+ }
+}
+function writeDaemonOwner(paths, owner) {
+ writePrivateFile(paths.pid, `${owner.pid}
+`);
+ writePrivateFile(paths.endpoint, owner.endpoint.path);
+ writePrivateFile(paths.owner, `${JSON.stringify(owner)}
+`);
+}
+function removeDaemonMetadataForOwner(paths, owner) {
+ const current = readDaemonOwner(paths);
+ if (!current || !sameOwner(current, owner))
+ return;
+ unlinkQuietly(paths.socket);
+ unlinkQuietly(paths.pid);
+ unlinkQuietly(paths.endpoint);
+ unlinkQuietly(paths.owner);
+}
+function endpointIdentity(endpointPath) {
+ if (process.platform === "win32")
+ return { kind: "windows", path: endpointPath };
+ try {
+ const stats = statSync5(endpointPath);
+ return { kind: "unix", path: endpointPath, dev: stats.dev, ino: stats.ino };
+ } catch (error) {
+ if (error instanceof Error)
+ return { kind: "missing", path: endpointPath };
+ throw error;
+ }
+}
+function sameEndpoint(a, b) {
+ if (a.kind !== b.kind || a.path !== b.path)
+ return false;
+ switch (a.kind) {
+ case "unix":
+ return b.kind === "unix" && a.dev === b.dev && a.ino === b.ino;
+ case "windows":
+ return true;
+ case "missing":
+ return true;
+ }
+}
+function sameOwner(a, b) {
+ return a.pid === b.pid && a.nonce === b.nonce && sameEndpoint(a.endpoint, b.endpoint);
+}
+async function validateExistingOwner(paths, pingOwner) {
+ let token = readOrCreateAuthToken(paths);
+ for (let attempt = 0;attempt < 2; attempt += 1) {
+ const owner = readDaemonOwner(paths);
+ if (!owner)
+ return token;
+ const ping = await pingOwner(token);
+ if (ping && owner.nonce === ping.nonce && sameEndpoint(owner.endpoint, ping.endpoint)) {
+ throw new DaemonAlreadyRunningError("LSP daemon already running");
+ }
+ if (ping)
+ continue;
+ if (isProcessAlive(owner.pid))
+ throw new DaemonStartupDeferredError("owner_pid_live_unreachable");
+ const reread = readDaemonOwner(paths);
+ const endpoint = endpointIdentity(owner.endpoint.path);
+ if (!reread || reread.nonce !== owner.nonce || !sameEndpoint(endpoint, owner.endpoint)) {
+ throw new DaemonStartupDeferredError("owner_changed_during_cleanup");
+ }
+ cleanupDeadOwner(paths, owner);
+ token = rotateAuthToken(paths);
+ return token;
+ }
+ throw new DaemonStartupDeferredError("reachable_owner_mismatch");
+}
+function cleanupDeadOwner(paths, owner) {
+ if (process.platform !== "win32" && existsSync12(owner.endpoint.path)) {
+ const stat = lstatSync7(owner.endpoint.path);
+ if (stat.isSocket())
+ unlinkSync3(owner.endpoint.path);
+ }
+ unlinkQuietly(paths.pid);
+ unlinkQuietly(paths.endpoint);
+ unlinkQuietly(paths.owner);
+}
+function newOwner(paths) {
+ return {
+ pid: process.pid,
+ nonce: randomUUID(),
+ startedAt: new Date().toISOString(),
+ endpoint: endpointIdentity(paths.socket)
+ };
+}
+function parseOwner(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value))
+ return null;
+ const pid = Reflect.get(value, "pid");
+ const nonce = Reflect.get(value, "nonce");
+ const startedAt = Reflect.get(value, "startedAt");
+ const endpoint = parseEndpoint(Reflect.get(value, "endpoint"));
+ if (typeof pid !== "number" || typeof nonce !== "string" || typeof startedAt !== "string" || !endpoint)
+ return null;
+ return { pid, nonce, startedAt, endpoint };
+}
+function parseEndpoint(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value))
+ return null;
+ const kind = Reflect.get(value, "kind");
+ const path2 = Reflect.get(value, "path");
+ if (typeof path2 !== "string")
+ return null;
+ if (kind === undefined)
+ return endpointIdentity(path2);
+ if (kind === "windows")
+ return { kind, path: path2 };
+ if (kind === "missing")
+ return { kind, path: path2 };
+ const dev = Reflect.get(value, "dev");
+ const ino = Reflect.get(value, "ino");
+ if (kind === "unix" && typeof dev === "number" && typeof ino === "number")
+ return { kind, path: path2, dev, ino };
+ return null;
+}
+
+// src/daemon-server.ts
var DEFAULT_IDLE_SHUTDOWN_MS = 30 * 60000;
var DEFAULT_IDLE_CHECK_INTERVAL_MS = 60000;
async function startDaemonServer(paths, options = {}) {
const idleShutdownMs = options.idleShutdownMs ?? DEFAULT_IDLE_SHUTDOWN_MS;
const idleCheckIntervalMs = options.idleCheckIntervalMs ?? DEFAULT_IDLE_CHECK_INTERVAL_MS;
- mkdirSync4(paths.dir, { recursive: true });
- unlinkQuietly(paths.socket);
+ const lease = await acquireStartupLease(paths, (token) => pingDaemon(paths, token));
const connections = new Set;
let lastActiveAt = Date.now();
const touch = () => {
lastActiveAt = Date.now();
};
+ let routeOwner = lease.owner;
const server2 = createServer2((socket) => {
connections.add(socket);
+ const activeRequests = new Map;
touch();
const decoder = createLineDecoder((message) => {
touch();
- respond(socket, message);
+ respond(socket, message, lease.token, routeOwner, activeRequests);
});
socket.on("data", (chunk) => decoder.push(chunk));
socket.on("error", () => socket.destroy());
socket.on("close", () => {
+ for (const controller of activeRequests.values())
+ controller.abort();
+ activeRequests.clear();
connections.delete(socket);
touch();
});
});
server2.on("error", (error) => logServerError(error));
- const endpointPath = join9(paths.dir, "daemon.endpoint");
- await listen(server2, paths.socket);
- writeFileSync3(paths.pid, `${process.pid}
-`);
- writeFileSync3(endpointPath, paths.socket);
+ let owner;
+ try {
+ await listen(server2, paths.socket);
+ if (process.platform !== "win32")
+ chmodSync2(paths.socket, 384);
+ owner = { ...lease.owner, endpoint: endpointIdentity(paths.socket) };
+ routeOwner = owner;
+ writeDaemonOwner(paths, owner);
+ await assertSelfProbe(paths, lease.token, owner);
+ } catch (error) {
+ lease.lock.release();
+ throw error;
+ }
+ lease.lock.release();
let closed = false;
const close = async () => {
if (closed)
@@ -3815,9 +6168,7 @@ async function startDaemonServer(paths, options = {}) {
socket.destroy();
connections.clear();
await closeServer(server2);
- unlinkQuietly(paths.socket);
- unlinkQuietly(paths.pid);
- unlinkQuietly(endpointPath);
+ removeDaemonMetadataForOwner(paths, owner);
await disposeDefaultLspManager();
};
const idleTimer = setInterval(() => {
@@ -3839,27 +6190,37 @@ async function startDaemonServer(paths, options = {}) {
installSignalHandlers(close);
return { server: server2, close };
}
-async function respond(socket, message) {
+async function respond(socket, message, token, owner, activeRequests) {
try {
- const response = await handleDaemonMessage(message);
+ const response = await handleDaemonMessage(message, { token, owner, activeRequests });
if (response && socket.writable)
socket.write(encodeJsonLine(response));
} catch (error) {
+ if (!(error instanceof Error))
+ throw error;
logServerError(error);
}
}
+async function assertSelfProbe(paths, token, owner) {
+ setPrivateFileMode(paths.pid);
+ setPrivateFileMode(paths.endpoint);
+ setPrivateFileMode(paths.owner);
+ const ping = await pingDaemon(paths, token);
+ if (!ping || ping.nonce !== owner.nonce)
+ throw new DaemonStartupDeferredError("self_probe_failed");
+}
function listen(server2, socketPath) {
- return new Promise((resolve6, reject) => {
+ return new Promise((resolve9, reject) => {
const onError = (error) => reject(error);
server2.once("error", onError);
server2.listen(socketPath, () => {
server2.removeListener("error", onError);
- resolve6();
+ resolve9();
});
});
}
function closeServer(server2) {
- return new Promise((resolve6) => server2.close(() => resolve6()));
+ return new Promise((resolve9) => server2.close(() => resolve9()));
}
function installSignalHandlers(close) {
const handler = () => {
@@ -3878,7 +6239,13 @@ function logServerError(error) {
async function runDaemon() {
process.on("uncaughtException", (error) => logNonFatal("uncaughtException", error));
process.on("unhandledRejection", (reason) => logNonFatal("unhandledRejection", reason));
- await startDaemonServer(daemonPaths());
+ try {
+ await startDaemonServer(daemonPaths());
+ } catch (error) {
+ if (error instanceof DaemonAlreadyRunningError)
+ return;
+ throw error;
+ }
}
function logNonFatal(kind, error) {
const message = error instanceof Error ? error.stack ?? error.message : String(error);
diff --git a/plugins/omo/components/lsp-daemon/dist/client.d.ts b/plugins/omo/components/lsp-daemon/dist/client.d.ts
new file mode 100644
index 00000000..8726feb3
--- /dev/null
+++ b/plugins/omo/components/lsp-daemon/dist/client.d.ts
@@ -0,0 +1,105 @@
+export declare const OMO_LSP_DAEMON_DIR = "OMO_LSP_DAEMON_DIR";
+export declare const OMO_LSP_DAEMON_CLI = "OMO_LSP_DAEMON_CLI";
+export declare const OMO_LSP_DAEMON_VERSION = "OMO_LSP_DAEMON_VERSION";
+export type DaemonRuntime = {
+ readonly cliPath: string;
+ readonly version: string;
+};
+export type DaemonRuntimeDefaults = DaemonRuntime;
+export type InvalidRuntimeOverrideReason = "paired_values_required" | "cli_must_be_absolute" | "cli_not_found" | "cli_not_file" | "packaged_cli_must_be_absolute";
+export declare class InvalidRuntimeOverrideError extends Error {
+ readonly code = "invalid_runtime_override";
+ readonly reason: InvalidRuntimeOverrideReason;
+ constructor(reason: InvalidRuntimeOverrideReason, message: string);
+}
+export declare function validateDaemonVersion(version: string): string;
+export declare function resolveDaemonRuntime(env: Record<string, string | undefined>, defaults: DaemonRuntimeDefaults): DaemonRuntime;
+export type LspRequestCapabilities = {
+ readonly installDecisionTool: boolean;
+};
+export type LspRequestContext = {
+ readonly cwd: string;
+ readonly projectConfigPaths: readonly string[];
+ readonly userConfigPath: string;
+ readonly installDecisionsPath: string;
+ readonly capabilities: LspRequestCapabilities;
+};
+export type DaemonToolContext = LspRequestContext;
+export type CallToolOptions = {
+ readonly context: DaemonToolContext;
+ readonly requestTimeoutMs?: number;
+ readonly signal?: AbortSignal;
+};
+export type TextContent = {
+ readonly type: "text";
+ readonly text: string;
+};
+export type ToolExecutionResult = {
+ readonly content: readonly TextContent[];
+ readonly isError?: boolean;
+ readonly details?: unknown;
+};
+export type SeverityFilter = "error" | "warning" | "information" | "hint" | "all";
+export type LspDiagnosticsDetails = {
+ readonly filePath: string;
+ readonly severity: SeverityFilter;
+ readonly mode: "file" | "directory";
+ readonly diagnostics: readonly unknown[];
+ readonly totalDiagnostics: number;
+ readonly truncated: boolean;
+ readonly error?: string;
+ readonly errorKind?: "freshness_timeout" | "missing_dependency" | "no_files" | "invalid_path";
+ readonly fileFailures?: readonly {
+ readonly file: string;
+ readonly error: string;
+ }[];
+};
+export type LspGotoDefinitionDetails = {
+ readonly filePath: string;
+ readonly line: number;
+ readonly character: number;
+ readonly locations: readonly unknown[];
+ readonly error?: string;
+ readonly errorKind?: "missing_dependency";
+};
+export type LspFindReferencesDetails = {
+ readonly filePath: string;
+ readonly line: number;
+ readonly character: number;
+ readonly references: readonly unknown[];
+ readonly totalReferences: number;
+ readonly truncated: boolean;
+ readonly error?: string;
+ readonly errorKind?: "missing_dependency";
+};
+export type LspSymbolsDetails = {
+ readonly filePath: string;
+ readonly scope: "document" | "workspace";
+ readonly query?: string;
+ readonly symbols: readonly unknown[];
+ readonly totalSymbols: number;
+ readonly truncated: boolean;
+ readonly error?: string;
+ readonly errorKind?: "missing_dependency" | "missing_query";
+};
+export type LspPrepareRenameDetails = {
+ readonly filePath: string;
+ readonly line: number;
+ readonly character: number;
+ readonly result: unknown;
+ readonly error?: string;
+ readonly errorKind?: "missing_dependency";
+};
+export type LspRenameDetails = {
+ readonly filePath: string;
+ readonly line: number;
+ readonly character: number;
+ readonly newName: string;
+ readonly apply: unknown;
+ readonly edit: unknown;
+ readonly error?: string;
+ readonly errorKind?: "missing_dependency";
+};
+export declare function callToolViaDaemon(name: string, args: Record<string, unknown>, options: CallToolOptions): Promise<ToolExecutionResult>;
+export declare function callDiagnosticsViaDaemon(filePath: string, options: CallToolOptions): Promise<ToolExecutionResult>;
+export declare function currentRequestContext(env?: Record<string, string | undefined>): DaemonToolContext;
diff --git a/plugins/omo/components/lsp-daemon/dist/client.js b/plugins/omo/components/lsp-daemon/dist/client.js
new file mode 100644
index 00000000..62e8261f
--- /dev/null
+++ b/plugins/omo/components/lsp-daemon/dist/client.js
@@ -0,0 +1,5851 @@
+// src/daemon-client.ts
+import { connect as connect2 } from "node:net";
+import { homedir as homedir3 } from "node:os";
+import { join as join7 } from "node:path";
+
+// ../lsp-core/src/request-context.ts
+import { AsyncLocalStorage } from "node:async_hooks";
+import { existsSync, realpathSync, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from "node:path";
+
+class LspRequestContextParseError extends Error {
+ code;
+ name = "LspRequestContextParseError";
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ }
+}
+
+class LspRequestContextUnavailableError extends Error {
+ name = "LspRequestContextUnavailableError";
+ constructor() {
+ super("LSP request context is required. Standalone MCP startup must install one with runWithRequestContext(createStandaloneMcpRequestContext()).");
+ }
+}
+var storage = new AsyncLocalStorage;
+var CONTEXT_FIELDS = new Set(["cwd", "projectConfigPaths", "userConfigPath", "installDecisionsPath", "capabilities"]);
+var CAPABILITY_FIELDS = new Set(["installDecisionTool"]);
+function runWithRequestContext(context, fn) {
+ return storage.run(context, fn);
+}
+function lspRequestContext() {
+ const context = storage.getStore();
+ if (!context)
+ throw new LspRequestContextUnavailableError;
+ return context;
+}
+function contextCwd() {
+ return lspRequestContext().cwd;
+}
+function createStandaloneMcpRequestContext(input = {}) {
+ const env = input.env ?? process.env;
+ const cwd = canonicalCwd(input.cwd ?? process.cwd());
+ const home = input.homeDir ?? homedir();
+ const projectConfigPaths = translateProjectConfigEnv(env["LSP_TOOLS_MCP_PROJECT_CONFIG"], cwd);
+ const userConfigPath = translateHomeConfigEnv(env["LSP_TOOLS_MCP_USER_CONFIG"], home, ".codex/lsp-client.json");
+ const installDecisionsPath = translateHomeConfigEnv(env["LSP_TOOLS_MCP_INSTALL_DECISIONS"], home, ".codex/lsp-install-decisions.json");
+ return parseLspRequestContext({
+ cwd,
+ projectConfigPaths,
+ userConfigPath,
+ installDecisionsPath,
+ capabilities: { installDecisionTool: true }
+ });
+}
+function parseLspRequestContext(value) {
+ if (!isRecord(value)) {
+ throw new LspRequestContextParseError("invalid_context", "LSP request context must be an object.");
+ }
+ rejectUnknownFields(value, CONTEXT_FIELDS, "context");
+ const cwd = stringField(value, "cwd");
+ const projectConfigPaths = stringArrayField(value, "projectConfigPaths");
+ const userConfigPath = stringField(value, "userConfigPath");
+ const installDecisionsPath = stringField(value, "installDecisionsPath");
+ const capabilities = capabilitiesField(value["capabilities"]);
+ const canonical = canonicalCwd(cwd);
+ for (const path of projectConfigPaths) {
+ requireAbsolutePath(path, "projectConfigPaths");
+ const projectPath = canonicalizeExistingOrNearestAncestor(path);
+ if (!isPathInside(canonical, projectPath)) {
+ throw new LspRequestContextParseError("project_config_outside_cwd", `Project LSP config path must be inside cwd: ${path}`);
+ }
+ }
+ requireAbsolutePath(userConfigPath, "userConfigPath");
+ requireAbsolutePath(installDecisionsPath, "installDecisionsPath");
+ return {
+ cwd: canonical,
+ projectConfigPaths: projectConfigPaths.map((path) => canonicalizeExistingOrNearestAncestor(path)),
+ userConfigPath,
+ installDecisionsPath,
+ capabilities
+ };
+}
+function translateProjectConfigEnv(value, cwd) {
+ if (value === undefined || value.length === 0)
+ return [join(cwd, ".codex", "lsp-client.json")];
+ return value.split(delimiter).filter((entry) => entry.length > 0).map((entry) => isAbsolute(entry) ? entry : join(cwd, entry));
+}
+function translateHomeConfigEnv(value, home, fallback) {
+ if (value === undefined || value.length === 0)
+ return join(home, fallback);
+ return isAbsolute(value) ? value : join(home, value);
+}
+function canonicalCwd(cwd) {
+ const resolved = resolve(cwd);
+ if (!existsSync(resolved) || !statSync(resolved).isDirectory()) {
+ throw new LspRequestContextParseError("invalid_cwd", `LSP request cwd must be an existing directory: ${cwd}`);
+ }
+ return realpathSync(resolved);
+}
+function canonicalizeExistingOrNearestAncestor(path) {
+ let current = resolve(path);
+ const suffix = [];
+ while (true) {
+ try {
+ const existing = realpathSync(current);
+ return suffix.length === 0 ? existing : join(existing, ...suffix);
+ } catch (error) {
+ if (!isMissingPathError(error))
+ throw error;
+ const parent = dirname(current);
+ if (parent === current)
+ throw error;
+ suffix.unshift(basename(current));
+ current = parent;
+ }
+ }
+}
+function capabilitiesField(value) {
+ if (!isRecord(value)) {
+ throw new LspRequestContextParseError("invalid_capabilities", "LSP request capabilities must be an object.");
+ }
+ rejectUnknownFields(value, CAPABILITY_FIELDS, "capabilities");
+ const installDecisionTool = value["installDecisionTool"];
+ if (typeof installDecisionTool !== "boolean") {
+ throw new LspRequestContextParseError("invalid_install_decision_capability", "LSP request capabilities.installDecisionTool must be a boolean.");
+ }
+ return { installDecisionTool };
+}
+function stringField(value, field) {
+ const fieldValue = value[field];
+ if (typeof fieldValue !== "string" || fieldValue.length === 0) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string.`);
+ }
+ return fieldValue;
+}
+function stringArrayField(value, field) {
+ const fieldValue = value[field];
+ if (!Array.isArray(fieldValue) || !fieldValue.every((item) => typeof item === "string" && item.length > 0)) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string array.`);
+ }
+ return fieldValue;
+}
+function requireAbsolutePath(path, field) {
+ if (!isAbsolute(path)) {
+ throw new LspRequestContextParseError("relative_path", `LSP request context.${field} must be absolute: ${path}`);
+ }
+}
+function isPathInside(parent, child) {
+ const childPath = resolve(child);
+ const relativePath = relative(parent, childPath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute(relativePath);
+}
+function isMissingPathError(error) {
+ const code = errorCode(error);
+ return code === "ENOENT" || code === "ENOTDIR";
+}
+function rejectUnknownFields(value, allowed, scope) {
+ const unknown = Object.keys(value).filter((key) => !allowed.has(key));
+ if (unknown.length > 0) {
+ throw new LspRequestContextParseError("unknown_field", `Unknown LSP request ${scope} field: ${unknown.join(", ")}`);
+ }
+}
+function isRecord(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function errorCode(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
+}
+
+// ../mcp-stdio-core/src/record.ts
+function isPlainRecord(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+// src/ensure-daemon.ts
+import { spawn } from "node:child_process";
+import { closeSync as closeSync2, mkdirSync as mkdirSync2, openSync as openSync2 } from "node:fs";
+import { connect } from "node:net";
+import { dirname as dirname3 } from "node:path";
+import { execPath } from "node:process";
+
+// src/ipc-protocol.ts
+import { randomBytes, timingSafeEqual } from "node:crypto";
+import {
+ chmodSync,
+ closeSync,
+ constants,
+ fchmodSync,
+ fstatSync,
+ lstatSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ unlinkSync,
+ writeSync
+} from "node:fs";
+import { dirname as dirname2 } from "node:path";
+var OMO_DAEMON_PROTOCOL_VERSION = 1;
+var AUTH_ERROR_CODE = -32001;
+var PROTOCOL_ERROR_CODE = -32002;
+var AUTH_TOKEN_BYTES = 32;
+
+class UnsafePrivateDirectoryError extends Error {
+ path;
+ reason;
+ name = "UnsafePrivateDirectoryError";
+ code = "unsafe_private_directory";
+ constructor(path, reason) {
+ super(`unsafe private directory ${path}: ${reason}`);
+ this.path = path;
+ this.reason = reason;
+ }
+}
+function authEnvelope(token) {
+ return { protocolVersion: OMO_DAEMON_PROTOCOL_VERSION, token };
+}
+function readAuthToken(paths) {
+ try {
+ const token = readFileSync(paths.auth, "utf8").trim();
+ return token.length > 0 ? token : null;
+ } catch (error) {
+ if (error instanceof Error)
+ return null;
+ throw error;
+ }
+}
+function readOrCreateAuthToken(paths) {
+ const existing = readAuthToken(paths);
+ if (existing)
+ return existing;
+ return createAuthToken(paths);
+}
+function rotateAuthToken(paths) {
+ try {
+ unlinkSync(paths.auth);
+ } catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ }
+ return createAuthToken(paths);
+}
+function authenticateMessage(raw, expectedToken) {
+ const id = jsonRpcId(raw);
+ if (!isPlainRecord(raw))
+ return authError(id);
+ const params = raw["params"];
+ if (!isPlainRecord(params))
+ return authError(id);
+ const envelope = params["_omo"];
+ if (!isPlainRecord(envelope))
+ return authError(id);
+ const protocolVersion = envelope["protocolVersion"];
+ if (protocolVersion !== OMO_DAEMON_PROTOCOL_VERSION)
+ return protocolError(id);
+ const token = envelope["token"];
+ if (typeof token !== "string" || !tokenMatches(token, expectedToken))
+ return authError(id);
+ const cleanParams = { ...params };
+ delete cleanParams["_omo"];
+ return { input: { ...raw, params: cleanParams }, id, method: typeof raw["method"] === "string" ? raw["method"] : undefined };
+}
+function isAuthErrorResponse(message) {
+ if (!isPlainRecord(message))
+ return false;
+ const error = message["error"];
+ if (!isPlainRecord(error))
+ return false;
+ const data = error["data"];
+ return error["code"] === AUTH_ERROR_CODE && isPlainRecord(data) && data["code"] === "daemon_authentication_failed";
+}
+function writePrivateFile(path, data) {
+ const fd = openSync(path, "w", 384);
+ try {
+ writeSync(fd, data);
+ } finally {
+ closeSync(fd);
+ }
+ setPrivateFileMode(path);
+}
+function ensurePrivateDirectory(path, options = {}) {
+ try {
+ mkdirSync(path, { recursive: true, mode: 448 });
+ } catch (error) {
+ if (errorCode2(error) !== "EEXIST")
+ throw error;
+ }
+ if (process.platform === "win32")
+ return;
+ const before = validatePrivateDirectory(path, options);
+ const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
+ try {
+ fchmodSync(fd, 448);
+ const after = validatePrivateDirectory(path, options);
+ const openStats = fstatSync(fd);
+ if (!sameDirectory(before, after) || !sameDirectory(before, openStats)) {
+ throw new UnsafePrivateDirectoryError(path, "changed_during_chmod");
+ }
+ } finally {
+ closeSync(fd);
+ }
+}
+function setPrivateFileMode(path) {
+ if (process.platform !== "win32")
+ chmodSync(path, 384);
+}
+function createAuthToken(paths) {
+ ensurePrivateDirectory(dirname2(paths.auth));
+ const token = randomBytes(AUTH_TOKEN_BYTES).toString("base64url");
+ let fd;
+ try {
+ fd = openSync(paths.auth, "wx", 384);
+ } catch (error) {
+ if (errorCode2(error) === "EEXIST") {
+ const existing = readAuthToken(paths);
+ if (existing)
+ return existing;
+ }
+ throw error;
+ }
+ try {
+ writeSync(fd, `${token}
+`);
+ } finally {
+ closeSync(fd);
+ }
+ setPrivateFileMode(paths.auth);
+ return token;
+}
+function errorCode2(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
+}
+function validatePrivateDirectory(path, options) {
+ const stats = options.lstat ? options.lstat(path) : lstatPrivateDirectory(path);
+ if (stats.isSymbolicLink())
+ throw new UnsafePrivateDirectoryError(path, "symlink");
+ if (!stats.isDirectory())
+ throw new UnsafePrivateDirectoryError(path, "not_directory");
+ const currentUid = options.currentUid ? options.currentUid() : process.getuid?.();
+ if (currentUid !== undefined && stats.uid !== currentUid) {
+ throw new UnsafePrivateDirectoryError(path, "wrong_owner");
+ }
+ return stats;
+}
+function lstatPrivateDirectory(path) {
+ return lstatSync(path);
+}
+function sameDirectory(a, b) {
+ return a.dev === b.dev && a.ino === b.ino;
+}
+function tokenMatches(candidate, expected) {
+ const candidateBytes = Buffer.from(candidate);
+ const expectedBytes = Buffer.from(expected);
+ return candidateBytes.length === expectedBytes.length && timingSafeEqual(candidateBytes, expectedBytes);
+}
+function jsonRpcId(raw) {
+ if (!isPlainRecord(raw))
+ return null;
+ const id = raw["id"];
+ return typeof id === "string" || typeof id === "number" || id === null ? id : null;
+}
+function authError(id) {
+ return {
+ jsonrpc: "2.0",
+ id,
+ error: { code: AUTH_ERROR_CODE, message: "daemon authentication failed", data: { code: "daemon_authentication_failed" } }
+ };
+}
+function protocolError(id) {
+ return {
+ jsonrpc: "2.0",
+ id,
+ error: { code: PROTOCOL_ERROR_CODE, message: "daemon protocol mismatch", data: { code: "daemon_protocol_mismatch" } }
+ };
+}
+
+// src/paths.ts
+import { createHash } from "node:crypto";
+import { createRequire } from "node:module";
+import { homedir as homedir2, tmpdir, userInfo } from "node:os";
+import * as path from "node:path";
+import { fileURLToPath } from "node:url";
+
+// src/runtime-contract.ts
+import { statSync as statSync2 } from "node:fs";
+import { isAbsolute as isAbsolute2 } from "node:path";
+var OMO_LSP_DAEMON_DIR = "OMO_LSP_DAEMON_DIR";
+var OMO_LSP_DAEMON_CLI = "OMO_LSP_DAEMON_CLI";
+var OMO_LSP_DAEMON_VERSION = "OMO_LSP_DAEMON_VERSION";
+var DAEMON_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
+
+class InvalidRuntimeOverrideError extends Error {
+ code = "invalid_runtime_override";
+ reason;
+ constructor(reason, message) {
+ super(message);
+ this.name = "InvalidRuntimeOverrideError";
+ this.reason = reason;
+ }
+}
+
+class InvalidDaemonVersionError extends Error {
+ code = "invalid_daemon_version";
+ version;
+ constructor(version) {
+ super("LSP daemon version must match [A-Za-z0-9][A-Za-z0-9._+-]{0,127}");
+ this.name = "InvalidDaemonVersionError";
+ this.version = version;
+ }
+}
+function validateDaemonVersion(version) {
+ if (!DAEMON_VERSION_PATTERN.test(version))
+ throw new InvalidDaemonVersionError(version);
+ return version;
+}
+function resolveDaemonRuntime(env, defaults) {
+ const cliOverride = env[OMO_LSP_DAEMON_CLI];
+ const versionOverride = env[OMO_LSP_DAEMON_VERSION];
+ const hasCliOverride = cliOverride !== undefined;
+ const hasVersionOverride = versionOverride !== undefined;
+ if (hasCliOverride !== hasVersionOverride) {
+ throw new InvalidRuntimeOverrideError("paired_values_required", `${OMO_LSP_DAEMON_CLI} and ${OMO_LSP_DAEMON_VERSION} must be set together`);
+ }
+ if (!hasCliOverride || !hasVersionOverride) {
+ if (!isAbsolute2(defaults.cliPath)) {
+ throw new InvalidRuntimeOverrideError("packaged_cli_must_be_absolute", "Packaged LSP daemon CLI path must be absolute");
+ }
+ return { cliPath: defaults.cliPath, version: validateDaemonVersion(defaults.version) };
+ }
+ if (!isAbsolute2(cliOverride)) {
+ throw new InvalidRuntimeOverrideError("cli_must_be_absolute", `${OMO_LSP_DAEMON_CLI} must be an absolute path to an existing regular file`);
+ }
+ let cliStats;
+ try {
+ cliStats = statSync2(cliOverride);
+ } catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ throw new InvalidRuntimeOverrideError("cli_not_found", `${OMO_LSP_DAEMON_CLI} must name an existing regular file`);
+ }
+ if (!cliStats.isFile()) {
+ throw new InvalidRuntimeOverrideError("cli_not_file", `${OMO_LSP_DAEMON_CLI} must name an existing regular file`);
+ }
+ return { cliPath: cliOverride, version: validateDaemonVersion(versionOverride) };
+}
+
+// src/paths.ts
+var requireFromHere = createRequire(import.meta.url);
+var MAX_SOCKET_PATH_LENGTH = 100;
+
+class InvalidDaemonDirectoryError extends Error {
+ code = "invalid_daemon_directory";
+ directory;
+ constructor(directory) {
+ super(`${OMO_LSP_DAEMON_DIR} must be an absolute path`);
+ this.name = "InvalidDaemonDirectoryError";
+ this.directory = directory;
+ }
+}
+function resolveDaemonVersion(requireFn = requireFromHere) {
+ for (const candidate of ["./package.json", "../package.json"]) {
+ let loaded;
+ try {
+ loaded = requireFn(candidate);
+ } catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ continue;
+ }
+ if (typeof loaded === "object" && loaded !== null && "version" in loaded) {
+ const version = Reflect.get(loaded, "version");
+ if (typeof version === "string")
+ return validateDaemonVersion(version);
+ }
+ }
+ return "0";
+}
+function packagedRuntimeDefaults() {
+ return {
+ cliPath: fileURLToPath(new URL("./cli.js", import.meta.url)),
+ version: resolveDaemonVersion()
+ };
+}
+function daemonBaseDir(env = process.env, platform = defaultDaemonPlatform()) {
+ const override = env[OMO_LSP_DAEMON_DIR];
+ if (override !== undefined) {
+ if (!platform.path.isAbsolute(override))
+ throw new InvalidDaemonDirectoryError(override);
+ return platform.path.resolve(override);
+ }
+ return platform.path.resolve(platform.path.join(platform.homedir(), ".omo", "lsp-daemon"));
+}
+function daemonPaths(env = process.env, runtimeDefaults = packagedRuntimeDefaults(), platform = defaultDaemonPlatform()) {
+ const runtime = resolveDaemonRuntime(env, runtimeDefaults);
+ const baseDir = daemonBaseDir(env, platform);
+ const dir = platform.path.resolve(platform.path.join(baseDir, `v${runtime.version}`));
+ return {
+ version: runtime.version,
+ cliPath: runtime.cliPath,
+ dir,
+ socket: resolveSocketPath(dir, runtime.version, platform),
+ lock: platform.path.join(dir, "daemon.lock"),
+ pid: platform.path.join(dir, "daemon.pid"),
+ auth: platform.path.join(dir, "daemon.auth"),
+ endpoint: platform.path.join(dir, "daemon.endpoint"),
+ owner: platform.path.join(dir, "daemon.owner"),
+ log: platform.path.join(dir, "daemon.log")
+ };
+}
+function defaultDaemonPlatform() {
+ return {
+ platform: process.platform,
+ homedir: homedir2,
+ tmpdir,
+ getuid: () => typeof process.getuid === "function" ? process.getuid() : undefined,
+ username: () => userInfo().username,
+ path
+ };
+}
+function resolveSocketPath(dir, version, platform) {
+ const canonicalVersionDir = platform.path.resolve(dir);
+ if (platform.platform === "win32") {
+ const currentUserDiscriminator = `${platform.getuid() ?? "win"}:${platform.username()}:${platform.path.resolve(platform.homedir())}`;
+ const digest = shortDigest(`${canonicalVersionDir}\x00${currentUserDiscriminator}`);
+ return `\\\\.\\pipe\\omo-lsp-${version}-${digest}`;
+ }
+ const natural = platform.path.join(canonicalVersionDir, "daemon.sock");
+ if (natural.length < MAX_SOCKET_PATH_LENGTH)
+ return natural;
+ return platform.path.join(platform.tmpdir(), `omo-lsp-${version}-${shortDigest(canonicalVersionDir)}`, "daemon.sock");
+}
+function shortDigest(value) {
+ return createHash("sha256").update(value).digest("hex").slice(0, 16);
+}
+
+// src/socket-jsonrpc.ts
+function encodeJsonLine(message) {
+ return `${JSON.stringify(message)}
+`;
+}
+function createLineDecoder(onMessage, onParseError) {
+ let buffer = "";
+ return {
+ push(chunk) {
+ buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ let index = buffer.indexOf(`
+`);
+ while (index !== -1) {
+ const raw = buffer.slice(0, index).trim();
+ buffer = buffer.slice(index + 1);
+ if (raw.length > 0) {
+ try {
+ onMessage(JSON.parse(raw));
+ } catch (error) {
+ if (error instanceof Error) {
+ onParseError?.(raw, error);
+ } else {
+ throw error;
+ }
+ }
+ }
+ index = buffer.indexOf(`
+`);
+ }
+ }
+ };
+}
+
+// src/ensure-daemon.ts
+var PROBE_TIMEOUT_MS = 500;
+var DEFAULT_READY_TIMEOUT_MS = 5000;
+var DEFAULT_POLL_INTERVAL_MS = 100;
+
+class DaemonUnreachableError extends Error {
+ constructor(socketPath) {
+ super(`LSP daemon did not become reachable at ${socketPath}`);
+ this.name = "DaemonUnreachableError";
+ }
+}
+async function ensureDaemonRunning(paths, deps = defaultEnsureDaemonDeps(), options = {}) {
+ const readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
+ const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
+ if (await deps.probe(paths))
+ return;
+ deps.spawnDaemon(paths);
+ await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs);
+}
+async function waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs) {
+ const deadline = deps.now() + readyTimeoutMs;
+ for (;; ) {
+ if (await deps.probe(paths))
+ return;
+ if (deps.now() >= deadline)
+ throw new DaemonUnreachableError(paths.socket);
+ await deps.sleep(pollIntervalMs);
+ }
+}
+async function probeDaemon(paths, timeoutMs = PROBE_TIMEOUT_MS) {
+ const token = readAuthToken(paths);
+ if (!token)
+ return false;
+ return await pingDaemon(paths, token, timeoutMs) !== null;
+}
+function pingDaemon(paths, token, timeoutMs = PROBE_TIMEOUT_MS) {
+ return new Promise((resolve2) => {
+ const socket = connect(paths.socket);
+ let settled = false;
+ const finish = (value) => {
+ if (settled)
+ return;
+ settled = true;
+ socket.destroy();
+ resolve2(value);
+ };
+ const timer = setTimeout(() => finish(null), timeoutMs);
+ timer.unref?.();
+ const decoder = createLineDecoder((message) => {
+ clearTimeout(timer);
+ finish(parsePingResponse(message));
+ });
+ socket.once("connect", () => {
+ socket.write(encodeJsonLine({ jsonrpc: "2.0", id: 1, method: "omo/ping", params: { _omo: authEnvelope(token) } }));
+ });
+ socket.on("data", (chunk) => decoder.push(chunk));
+ socket.once("error", () => {
+ clearTimeout(timer);
+ finish(null);
+ });
+ });
+}
+function spawnDaemonProcess(paths) {
+ mkdirSync2(dirname3(paths.log), { recursive: true });
+ const logFd = openSync2(paths.log, "a");
+ try {
+ const child = spawn(execPath, [paths.cliPath, "daemon"], {
+ detached: true,
+ stdio: ["ignore", logFd, logFd]
+ });
+ child.unref();
+ } finally {
+ closeSync2(logFd);
+ }
+}
+function defaultEnsureDaemonDeps() {
+ return {
+ probe: (paths) => probeDaemon(paths),
+ spawnDaemon: (paths) => spawnDaemonProcess(paths),
+ sleep: (ms) => new Promise((resolve2) => {
+ setTimeout(resolve2, ms);
+ }),
+ now: () => Date.now()
+ };
+}
+function parsePingResponse(message) {
+ if (!message || typeof message !== "object" || Array.isArray(message))
+ return null;
+ const result = Reflect.get(message, "result");
+ if (!result || typeof result !== "object" || Array.isArray(result))
+ return null;
+ const pid = Reflect.get(result, "pid");
+ const nonce = Reflect.get(result, "nonce");
+ const startedAt = Reflect.get(result, "startedAt");
+ const endpoint = Reflect.get(result, "endpoint");
+ if (typeof pid !== "number" || typeof nonce !== "string" || typeof startedAt !== "string")
+ return null;
+ if (!endpoint || typeof endpoint !== "object" || Array.isArray(endpoint))
+ return null;
+ const path2 = Reflect.get(endpoint, "path");
+ const kind = Reflect.get(endpoint, "kind");
+ if (typeof path2 !== "string")
+ return null;
+ if (kind === "windows")
+ return { pid, nonce, startedAt, endpoint: { kind, path: path2 } };
+ if (kind === "missing")
+ return { pid, nonce, startedAt, endpoint: { kind, path: path2 } };
+ const dev = Reflect.get(endpoint, "dev");
+ const ino = Reflect.get(endpoint, "ino");
+ if (kind === "unix" && typeof dev === "number" && typeof ino === "number") {
+ return { pid, nonce, startedAt, endpoint: { kind, path: path2, dev, ino } };
+ }
+ return null;
+}
+// ../mcp-stdio-core/src/responses.ts
+function successResponse(id, result) {
+ return { jsonrpc: "2.0", id, result };
+}
+function errorResponse(id, code, message, data) {
+ return { jsonrpc: "2.0", id, error: data === undefined ? { code, message } : { code, message, data } };
+}
+function jsonRpcId2(value) {
+ return typeof value === "string" || typeof value === "number" || value === null ? value : null;
+}
+// ../mcp-stdio-core/src/transport.ts
+var HEADER_SEPARATOR = Buffer.from(`\r
+\r
+`);
+async function* readStdioJsonRpcMessages(input) {
+ let buffer = Buffer.alloc(0);
+ for await (const chunk of input) {
+ buffer = Buffer.concat([buffer, bufferFromChunk(chunk)]);
+ while (true) {
+ const result = readNextMessage(buffer);
+ if (result.kind === "incomplete")
+ break;
+ buffer = result.remaining;
+ if (result.message)
+ yield result.message;
+ }
+ }
+ const trailing = buffer.toString("utf8").trim();
+ if (trailing.length > 0) {
+ yield parseJsonPayload(trailing, "line");
+ }
+}
+function writeStdioJsonRpcResponse(output, response, responseMode) {
+ const body = JSON.stringify(response);
+ if (responseMode === "framed") {
+ output.write(`Content-Length: ${Buffer.byteLength(body, "utf8")}\r
+\r
+${body}`);
+ return;
+ }
+ output.write(`${body}
+`);
+}
+function readNextMessage(buffer) {
+ if (buffer.length === 0)
+ return { kind: "incomplete" };
+ return startsWithContentLength(buffer) ? readFramedMessage(buffer) : readLineMessage(buffer);
+}
+function readLineMessage(buffer) {
+ const newlineIndex = buffer.indexOf(10);
+ if (newlineIndex === -1)
+ return { kind: "incomplete" };
+ const line = buffer.subarray(0, newlineIndex).toString("utf8").replace(/\r$/, "");
+ if (line.trim().length === 0) {
+ return { kind: "complete", remaining: buffer.subarray(newlineIndex + 1) };
+ }
+ return {
+ kind: "complete",
+ message: parseJsonPayload(line, "line"),
+ remaining: buffer.subarray(newlineIndex + 1)
+ };
+}
+function readFramedMessage(buffer) {
+ const separatorIndex = buffer.indexOf(HEADER_SEPARATOR);
+ if (separatorIndex === -1)
+ return { kind: "incomplete" };
+ const headers = buffer.subarray(0, separatorIndex).toString("ascii");
+ const contentLength = parseContentLength(headers);
+ const bodyStart = separatorIndex + HEADER_SEPARATOR.length;
+ if (contentLength === undefined) {
+ return {
+ kind: "complete",
+ message: {
+ kind: "parse_error",
+ message: "Missing or invalid Content-Length header",
+ responseMode: "framed"
+ },
+ remaining: buffer.subarray(bodyStart)
+ };
+ }
+ const bodyEnd = bodyStart + contentLength;
+ if (buffer.length < bodyEnd)
+ return { kind: "incomplete" };
+ const body = buffer.subarray(bodyStart, bodyEnd).toString("utf8");
+ return {
+ kind: "complete",
+ message: parseJsonPayload(body, "framed"),
+ remaining: buffer.subarray(bodyEnd)
+ };
+}
+function startsWithContentLength(buffer) {
+ const prefix = buffer.subarray(0, "content-length:".length).toString("ascii").toLowerCase();
+ return prefix === "content-length:";
+}
+function parseContentLength(headers) {
+ for (const line of headers.split(`\r
+`)) {
+ const match = /^content-length:\s*(\d+)$/i.exec(line);
+ if (match === null)
+ continue;
+ const value = match[1];
+ if (value === undefined)
+ return;
+ return Number(value);
+ }
+ return;
+}
+function parseJsonPayload(payload, responseMode) {
+ try {
+ return { kind: "request", payload: JSON.parse(payload), responseMode };
+ } catch (error) {
+ return { kind: "parse_error", message: error instanceof Error ? error.message : String(error), responseMode };
+ }
+}
+function bufferFromChunk(chunk) {
+ if (Buffer.isBuffer(chunk))
+ return chunk;
+ if (typeof chunk === "string")
+ return Buffer.from(chunk);
+ throw new TypeError(`Unsupported stdio chunk type: ${typeof chunk}`);
+}
+
+// ../mcp-stdio-core/src/server.ts
+var DEFAULT_IDLE_TIMEOUT_MS = 10 * 60000;
+var noopLog = () => {};
+async function runJsonRpcStdioServer(config) {
+ const log = config.log ?? noopLog;
+ const idleTimeoutMs = config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
+ const idleTimer = createIdleTimer(idleTimeoutMs, log, config.onIdleTimeout);
+ log("stdio_started", { cwd: process.cwd(), idle_timeout_ms: idleTimeoutMs });
+ idleTimer.arm();
+ try {
+ for await (const message of readStdioJsonRpcMessages(config.input)) {
+ if (idleTimer.closed())
+ break;
+ idleTimer.arm();
+ if (message.kind === "parse_error") {
+ handleParseError(message, config, log);
+ continue;
+ }
+ await handleRequest(message, config, log);
+ }
+ } finally {
+ idleTimer.clear();
+ log("stdio_stopped");
+ }
+}
+function handleParseError(message, config, log) {
+ log("parse_error", { message: message.message });
+ const response = config.parseErrorResponse?.(message.message) ?? errorResponse(null, -32700, "Parse error", message.message);
+ if (response !== undefined) {
+ writeStdioJsonRpcResponse(config.output, response, message.responseMode);
+ }
+}
+async function handleRequest(message, config, log) {
+ const parsed = message.payload;
+ const id = isPlainRecord(parsed) ? jsonRpcId2(parsed["id"]) : null;
+ const method = isPlainRecord(parsed) && typeof parsed["method"] === "string" ? parsed["method"] : null;
+ log("request", { id: id === null ? null : String(id), method });
+ try {
+ const response = await config.handler(parsed, config.handlerOptions);
+ if (response === undefined)
+ return;
+ writeStdioJsonRpcResponse(config.output, response, message.responseMode);
+ log("response", { id: String(response.id), method, is_error: response.error !== undefined });
+ } catch (error) {
+ if (config.onHandlerError === undefined)
+ throw error;
+ config.onHandlerError(error);
+ }
+}
+function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {
+ let timer = null;
+ let isClosed = false;
+ return {
+ arm: () => {
+ if (timer !== null)
+ clearTimeout(timer);
+ if (idleTimeoutMs <= 0)
+ return;
+ timer = setTimeout(() => {
+ isClosed = true;
+ log("idle_timeout", { idle_timeout_ms: idleTimeoutMs });
+ onIdleTimeout?.();
+ }, idleTimeoutMs);
+ timer.unref();
+ },
+ clear: () => {
+ if (timer === null)
+ return;
+ clearTimeout(timer);
+ timer = null;
+ },
+ closed: () => isClosed
+ };
+}
+// ../lsp-core/src/lsp/client-wrapper.ts
+import { existsSync as existsSync9, statSync as statSync4 } from "node:fs";
+import { dirname as dirname8, join as join4, resolve as resolve7 } from "node:path";
+
+// ../lsp-core/src/lsp/effective-extension.ts
+import { basename as basename2, extname } from "node:path";
+var BASENAME_EXTENSIONS = {
+ Dockerfile: ".dockerfile",
+ Containerfile: ".dockerfile"
+};
+function effectiveExtension(filePath) {
+ return BASENAME_EXTENSIONS[basename2(filePath)] ?? extname(filePath);
+}
+
+// ../lsp-core/src/lsp/errors.ts
+class LspConnectionClosedError extends Error {
+ serverId;
+ root;
+ name = "LspConnectionClosedError";
+ constructor(serverId, root, message) {
+ super(message ?? `LSP connection closed for ${serverId} at ${root}`);
+ this.serverId = serverId;
+ this.root = root;
+ }
+}
+
+class LspProcessExitedError extends Error {
+ serverId;
+ root;
+ exitCode;
+ stderrTail;
+ name = "LspProcessExitedError";
+ constructor(serverId, root, exitCode, stderrTail) {
+ const stderrSuffix = stderrTail ? `
+stderr tail: ${stderrTail}` : "";
+ super(`LSP server ${serverId} at ${root} exited with code ${exitCode ?? "null"}${stderrSuffix}`);
+ this.serverId = serverId;
+ this.root = root;
+ this.exitCode = exitCode;
+ this.stderrTail = stderrTail;
+ }
+}
+
+class LspRequestTimeoutError extends Error {
+ method;
+ stderrTail;
+ name = "LspRequestTimeoutError";
+ constructor(method, stderrTail) {
+ const stderrSuffix = stderrTail ? `
+recent stderr: ${stderrTail}` : "";
+ super(`LSP request timeout (method: ${method})${stderrSuffix}`);
+ this.method = method;
+ this.stderrTail = stderrTail;
+ }
+}
+
+class LspInvalidPathError extends Error {
+ name = "LspInvalidPathError";
+}
+
+class LspServerLookupError extends Error {
+ lookup;
+ name = "LspServerLookupError";
+ constructor(message, lookup) {
+ super(message);
+ this.lookup = lookup;
+ }
+}
+
+class LspServerInitializingError extends Error {
+ originalError;
+ name = "LspServerInitializingError";
+ constructor(originalError) {
+ super(`LSP server is still initializing. Please retry in a few seconds. Original error: ${originalError.message}`);
+ this.originalError = originalError;
+ }
+}
+
+class LspProcessSpawnError extends Error {
+ name = "LspProcessSpawnError";
+}
+function isLspDeadConnectionError(err) {
+ return err instanceof LspConnectionClosedError || err instanceof LspProcessExitedError;
+}
+
+// ../lsp-core/src/lsp/cleanup-errors.ts
+function writeCleanupError(message) {
+ process.stderr.write(`${message}
+`);
+}
+function reportBestEffortCleanupError(operation, error, logger = writeCleanupError) {
+ const message = error instanceof Error ? error.message : String(error);
+ logger(`[lsp] ignored ${operation} failure during cleanup: ${message}`);
+}
+
+// ../lsp-core/src/lsp/client.ts
+import { resolve as resolve6 } from "node:path";
+import { pathToFileURL as pathToFileURL3 } from "node:url";
+
+// ../lsp-core/src/lsp/connection.ts
+import { pathToFileURL } from "node:url";
+
+// ../lsp-core/src/lsp/constants.ts
+var DEFAULT_MAX_REFERENCES = 200;
+var DEFAULT_MAX_SYMBOLS = 200;
+var DEFAULT_MAX_DIAGNOSTICS = 200;
+var DEFAULT_MAX_DIRECTORY_FILES = 50;
+var REQUEST_TIMEOUT_MS = 15000;
+var INIT_TIMEOUT_MS = 60000;
+var IDLE_TIMEOUT_MS = 5 * 60000;
+var REAPER_INTERVAL_MS = 60000;
+var STOP_HARD_KILL_TIMEOUT_MS = 5000;
+var STOP_SIGKILL_GRACE_MS = 1000;
+
+// ../lsp-core/src/lsp/json-rpc-connection.ts
+var HEADER_SEPARATOR2 = `\r
+\r
+`;
+var PARSE_ERROR = -32700;
+var INVALID_REQUEST = -32600;
+var METHOD_NOT_FOUND = -32601;
+var INTERNAL_ERROR = -32603;
+
+class JsonRpcConnection {
+ reader;
+ writer;
+ pendingRequests = new Map;
+ notificationHandlers = new Map;
+ requestHandlers = new Map;
+ closeHandlers = [];
+ errorHandlers = [];
+ inputBuffer = Buffer.alloc(0);
+ nextRequestId = 1;
+ listening = false;
+ disposed = false;
+ constructor(reader, writer) {
+ this.reader = reader;
+ this.writer = writer;
+ }
+ listen() {
+ if (this.listening)
+ return;
+ this.listening = true;
+ this.reader.on("data", this.handleData);
+ this.reader.on("close", this.handleClose);
+ this.reader.on("end", this.handleClose);
+ this.reader.on("error", this.handleStreamError);
+ this.writer.on("error", this.handleStreamError);
+ }
+ onNotification(method, handler) {
+ this.notificationHandlers.set(method, handler);
+ }
+ onRequest(method, handler) {
+ this.requestHandlers.set(method, handler);
+ }
+ onClose(handler) {
+ this.closeHandlers.push(handler);
+ }
+ onError(handler) {
+ this.errorHandlers.push(handler);
+ }
+ async sendRequest(method, params, options = {}) {
+ if (this.disposed)
+ throw new Error("JSON-RPC connection is disposed");
+ const id = this.nextRequestId;
+ this.nextRequestId += 1;
+ const key = String(id);
+ const message = params === undefined ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
+ let requestWritten = false;
+ let cancelAfterWrite = false;
+ let settled = false;
+ const writeCancel = () => this.writeMessage({ jsonrpc: "2.0", method: "$/cancelRequest", params: { id } });
+ const responsePromise = new Promise((resolve2, reject) => {
+ const cleanup = () => {
+ options.signal?.removeEventListener("abort", onAbort);
+ };
+ const settleCancel = () => {
+ if (settled)
+ return;
+ settled = true;
+ this.pendingRequests.delete(key);
+ cleanup();
+ const rejectCancelled = () => reject(abortError(options.signal));
+ if (!requestWritten) {
+ cancelAfterWrite = true;
+ rejectCancelled();
+ return;
+ }
+ writeCancel().then(rejectCancelled, (error) => {
+ this.emitError(toError(error));
+ rejectCancelled();
+ });
+ };
+ const onAbort = () => settleCancel();
+ this.pendingRequests.set(key, {
+ resolve(result) {
+ settled = true;
+ cleanup();
+ resolve2(result);
+ },
+ reject(error) {
+ settled = true;
+ cleanup();
+ reject(error);
+ },
+ cleanup
+ });
+ if (options.signal?.aborted) {
+ settleCancel();
+ return;
+ }
+ options.signal?.addEventListener("abort", onAbort, { once: true });
+ });
+ if (settled)
+ return responsePromise;
+ try {
+ await this.writeMessage(message);
+ requestWritten = true;
+ if (cancelAfterWrite)
+ await writeCancel();
+ } catch (error) {
+ if (settled)
+ return responsePromise;
+ const pending = this.pendingRequests.get(key);
+ if (pending) {
+ pending.cleanup();
+ this.pendingRequests.delete(key);
+ }
+ throw error;
+ }
+ return responsePromise;
+ }
+ pendingRequestCount() {
+ return this.pendingRequests.size;
+ }
+ async sendNotification(method, params) {
+ if (this.disposed)
+ return;
+ const message = params === undefined ? { jsonrpc: "2.0", method } : { jsonrpc: "2.0", method, params };
+ await this.writeMessage(message);
+ }
+ dispose() {
+ if (this.disposed)
+ return;
+ this.disposed = true;
+ this.reader.off("data", this.handleData);
+ this.reader.off("close", this.handleClose);
+ this.reader.off("end", this.handleClose);
+ this.reader.off("error", this.handleStreamError);
+ this.writer.off("error", this.handleStreamError);
+ for (const pending of this.pendingRequests.values()) {
+ pending.cleanup();
+ pending.reject(new Error("JSON-RPC connection disposed"));
+ }
+ this.pendingRequests.clear();
+ this.notificationHandlers.clear();
+ this.requestHandlers.clear();
+ }
+ handleData = (chunk) => {
+ const chunkBuffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8");
+ this.inputBuffer = Buffer.concat([this.inputBuffer, chunkBuffer]);
+ this.drainInputBuffer();
+ };
+ handleClose = () => {
+ for (const handler of this.closeHandlers) {
+ handler();
+ }
+ };
+ handleStreamError = (error) => {
+ this.emitError(error);
+ };
+ drainInputBuffer() {
+ while (true) {
+ const headerEnd = this.inputBuffer.indexOf(HEADER_SEPARATOR2);
+ if (headerEnd === -1)
+ return;
+ const headers = this.inputBuffer.subarray(0, headerEnd).toString("ascii");
+ const contentLength = parseContentLength2(headers);
+ if (contentLength === null) {
+ this.inputBuffer = Buffer.alloc(0);
+ this.emitError(new Error("JSON-RPC message is missing Content-Length header"));
+ return;
+ }
+ const bodyStart = headerEnd + Buffer.byteLength(HEADER_SEPARATOR2);
+ const bodyEnd = bodyStart + contentLength;
+ if (this.inputBuffer.length < bodyEnd)
+ return;
+ const body = this.inputBuffer.subarray(bodyStart, bodyEnd).toString("utf8");
+ this.inputBuffer = this.inputBuffer.subarray(bodyEnd);
+ this.dispatchBody(body);
+ }
+ }
+ dispatchBody(body) {
+ let parsed;
+ try {
+ parsed = JSON.parse(body);
+ } catch (error) {
+ this.writeError(null, PARSE_ERROR, error instanceof Error ? error.message : "Parse error").catch((writeError) => this.emitError(toError(writeError)));
+ return;
+ }
+ if (!isJsonRpcObject(parsed)) {
+ this.writeError(null, INVALID_REQUEST, "Invalid JSON-RPC message").catch((error) => this.emitError(toError(error)));
+ return;
+ }
+ if ("id" in parsed && (("result" in parsed) || ("error" in parsed))) {
+ this.handleResponse(parsed);
+ return;
+ }
+ if (typeof parsed["method"] !== "string") {
+ const id = getMessageId(parsed) ?? null;
+ this.writeError(id, INVALID_REQUEST, "Invalid JSON-RPC method").catch((error) => this.emitError(toError(error)));
+ return;
+ }
+ if ("id" in parsed) {
+ this.handleRequest(parsed);
+ return;
+ }
+ this.handleNotification(parsed["method"], parsed["params"]);
+ }
+ handleResponse(message) {
+ const id = getMessageId(message);
+ if (id === undefined)
+ return;
+ const pending = this.pendingRequests.get(String(id));
+ if (!pending)
+ return;
+ this.pendingRequests.delete(String(id));
+ pending.cleanup();
+ if ("error" in message) {
+ pending.reject(jsonRpcErrorToError(message["error"]));
+ return;
+ }
+ pending.resolve(message["result"]);
+ }
+ handleNotification(method, params) {
+ const handler = this.notificationHandlers.get(method);
+ if (!handler)
+ return;
+ try {
+ handler(params);
+ } catch (error) {
+ if (error instanceof Error) {
+ this.emitError(error);
+ return;
+ }
+ this.emitError(new Error(String(error)));
+ }
+ }
+ handleRequest(message) {
+ const id = getMessageId(message);
+ if (id === undefined) {
+ this.writeError(null, INVALID_REQUEST, "Invalid JSON-RPC id").catch((error) => this.emitError(toError(error)));
+ return;
+ }
+ const method = typeof message["method"] === "string" ? message["method"] : "";
+ const handler = this.requestHandlers.get(method);
+ if (!handler) {
+ this.writeError(id, METHOD_NOT_FOUND, `Method not found: ${method}`).catch((error) => this.emitError(toError(error)));
+ return;
+ }
+ Promise.resolve().then(() => handler(message["params"])).then((result) => this.writeMessage({ jsonrpc: "2.0", id, result }), (error) => this.writeError(id, INTERNAL_ERROR, toError(error).message)).catch((error) => this.emitError(toError(error)));
+ }
+ async writeError(id, code, message) {
+ await this.writeMessage({ jsonrpc: "2.0", id, error: { code, message } });
+ }
+ writeMessage(message) {
+ const body = JSON.stringify(message);
+ const payload = `Content-Length: ${Buffer.byteLength(body, "utf8")}\r
+\r
+${body}`;
+ return new Promise((resolve2, reject) => {
+ this.writer.write(payload, (error) => {
+ if (error) {
+ reject(error);
+ return;
+ }
+ resolve2();
+ });
+ });
+ }
+ emitError(error) {
+ for (const handler of this.errorHandlers) {
+ handler(error);
+ }
+ }
+}
+function abortError(signal) {
+ const reason = signal?.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "LSP request cancelled");
+ error.name = "AbortError";
+ return error;
+}
+function parseContentLength2(headers) {
+ for (const line of headers.split(`\r
+`)) {
+ const separatorIndex = line.indexOf(":");
+ if (separatorIndex === -1)
+ continue;
+ const name = line.slice(0, separatorIndex).trim().toLowerCase();
+ if (name !== "content-length")
+ continue;
+ const value = Number.parseInt(line.slice(separatorIndex + 1).trim(), 10);
+ return Number.isFinite(value) && value >= 0 ? value : null;
+ }
+ return null;
+}
+function isJsonRpcObject(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function getMessageId(message) {
+ const id = message["id"];
+ if (typeof id === "number" || typeof id === "string" || id === null)
+ return id;
+ return;
+}
+function jsonRpcErrorToError(value) {
+ if (!isJsonRpcObject(value))
+ return new Error("JSON-RPC request failed");
+ const message = typeof value["message"] === "string" ? value["message"] : "JSON-RPC request failed";
+ const error = new Error(message);
+ if (typeof value["code"] === "number") {
+ error.name = `JsonRpcError(${value["code"]})`;
+ }
+ return error;
+}
+function toError(error) {
+ return error instanceof Error ? error : new Error(String(error));
+}
+
+// ../lsp-core/src/lsp/process.ts
+import { spawn as spawn2, spawnSync } from "node:child_process";
+import { existsSync as existsSync2, statSync as statSync3 } from "node:fs";
+import { delimiter as delimiter2, join as join2 } from "node:path";
+function isMissingProcessError(error) {
+ if (!(error instanceof Error) || !("code" in error))
+ return false;
+ return error.code === "ESRCH";
+}
+function reportKillError(context, error) {
+ if (!isMissingProcessError(error)) {
+ reportBestEffortCleanupError(context, error);
+ }
+}
+function validateCwd(cwd) {
+ try {
+ if (!existsSync2(cwd)) {
+ return { valid: false, error: `Working directory does not exist: ${cwd}` };
+ }
+ const stats = statSync3(cwd);
+ if (!stats.isDirectory()) {
+ return { valid: false, error: `Path is not a directory: ${cwd}` };
+ }
+ return { valid: true };
+ } catch (err) {
+ return {
+ valid: false,
+ error: `Cannot access working directory: ${cwd} (${err instanceof Error ? err.message : String(err)})`
+ };
+ }
+}
+function wrap(proc) {
+ const exitedPromise = new Promise((resolve2) => {
+ proc.once("close", (code) => resolve2(code ?? 0));
+ proc.once("error", () => resolve2(1));
+ });
+ if (!proc.stdin || !proc.stdout || !proc.stderr) {
+ throw new LspProcessSpawnError("Spawned process is missing one of stdin/stdout/stderr pipes");
+ }
+ return {
+ stdin: proc.stdin,
+ stdout: proc.stdout,
+ stderr: proc.stderr,
+ get pid() {
+ return proc.pid ?? undefined;
+ },
+ get exitCode() {
+ return proc.exitCode;
+ },
+ get killed() {
+ return proc.killed;
+ },
+ exited: exitedPromise,
+ kill(signal) {
+ killProcessTree(proc, signal ?? "SIGTERM");
+ }
+ };
+}
+function killProcessTree(proc, signal) {
+ if (process.platform === "win32" && proc.pid) {
+ const result = spawnSync("taskkill", ["/pid", String(proc.pid), "/f", "/t"], {
+ stdio: "ignore",
+ windowsHide: true
+ });
+ if (!result.error && result.status === 0)
+ return;
+ if (result.error)
+ reportKillError("windows process tree kill", result.error);
+ }
+ if (process.platform !== "win32" && proc.pid) {
+ try {
+ process.kill(-proc.pid, signal);
+ return;
+ } catch (error) {
+ reportKillError("process group kill", error);
+ }
+ }
+ try {
+ proc.kill(signal);
+ } catch (error) {
+ reportKillError("process kill", error);
+ }
+}
+function isWindowsShellShim(command) {
+ const lowerCommand = command.toLowerCase();
+ return lowerCommand.endsWith(".cmd") || lowerCommand.endsWith(".bat");
+}
+function splitPath(pathValue, platform) {
+ const separator = platform === "win32" ? ";" : delimiter2;
+ return pathValue.split(separator).filter(Boolean);
+}
+function getWindowsPathExtensions(env) {
+ const rawExtensions = env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD";
+ const extensions = rawExtensions.split(";").map((extension) => extension.trim()).filter(Boolean).map((extension) => extension.startsWith(".") ? extension : `.${extension}`);
+ return [...new Set([...extensions, ".exe", ".cmd", ".bat", ""])];
+}
+function resolveWindowsCommand(command, env) {
+ const hasPathSeparator = command.includes("/") || command.includes("\\");
+ const pathValue = env["PATH"] ?? env["Path"] ?? "";
+ const baseDirectories = hasPathSeparator ? [""] : splitPath(pathValue, "win32");
+ const extensions = getWindowsPathExtensions(env);
+ for (const baseDirectory of baseDirectories) {
+ for (const extension of extensions) {
+ const candidate = baseDirectory ? join2(baseDirectory, `${command}${extension}`) : `${command}${extension}`;
+ if (existsSync2(candidate))
+ return candidate;
+ }
+ }
+ return command;
+}
+function createSpawnCommand(command, platform = process.platform, commandProcessor = process.env["ComSpec"] ?? "cmd.exe", env = process.env) {
+ const [cmd, ...args] = command;
+ if (!cmd) {
+ throw new LspProcessSpawnError("[lsp] empty command");
+ }
+ if (platform !== "win32") {
+ return { command: cmd, args, shell: false };
+ }
+ const resolvedCommand = resolveWindowsCommand(cmd, env);
+ if (!isWindowsShellShim(resolvedCommand)) {
+ return { command: resolvedCommand, args, shell: false };
+ }
+ return {
+ command: commandProcessor,
+ args: ["/d", "/s", "/c", resolvedCommand, ...args],
+ shell: false
+ };
+}
+function spawnProcess(command, options) {
+ const cwdValidation = validateCwd(options.cwd);
+ if (!cwdValidation.valid) {
+ throw new LspInvalidPathError(`[lsp] ${cwdValidation.error}`);
+ }
+ const [cmd] = command;
+ if (!cmd) {
+ throw new LspProcessSpawnError("[lsp] empty command");
+ }
+ const preparedCommand = createSpawnCommand(command, process.platform, process.env["ComSpec"] ?? "cmd.exe", options.env);
+ const proc = spawn2(preparedCommand.command, preparedCommand.args, {
+ cwd: options.cwd,
+ env: options.env,
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+ shell: preparedCommand.shell,
+ detached: process.platform !== "win32"
+ });
+ return wrap(proc);
+}
+
+// ../lsp-core/src/lsp/transport-protocol.ts
+function isRecord2(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function parseConfigurationItems(params) {
+ if (!isRecord2(params) || !Array.isArray(params["items"]))
+ return [];
+ const items = [];
+ for (const item of params["items"]) {
+ if (!isRecord2(item))
+ continue;
+ const section = item["section"];
+ items.push(section === undefined || typeof section !== "string" ? {} : { section });
+ }
+ return items;
+}
+function parseDiagnosticsParams(params) {
+ if (!isRecord2(params) || typeof params["uri"] !== "string")
+ return null;
+ const diagnostics = Array.isArray(params["diagnostics"]) ? params["diagnostics"].filter(isDiagnostic) : [];
+ const version = typeof params["version"] === "number" ? params["version"] : undefined;
+ return { uri: params["uri"], diagnostics, ...version === undefined ? {} : { version } };
+}
+function createLspSpawnEnv(_root, input) {
+ return { ...input };
+}
+function isDiagnostic(value) {
+ return isRecord2(value) && isRange(value["range"]) && typeof value["message"] === "string";
+}
+function isRange(value) {
+ return isRecord2(value) && isPosition(value["start"]) && isPosition(value["end"]);
+}
+function isPosition(value) {
+ return isRecord2(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+}
+
+// ../lsp-core/src/lsp/transport.ts
+class LspClientNotStartedError extends Error {
+ serverId;
+ root;
+ name = "LspClientNotStartedError";
+ constructor(serverId, root) {
+ super("LSP client not started");
+ this.serverId = serverId;
+ this.root = root;
+ }
+}
+
+class LspClientTransport {
+ root;
+ server;
+ proc = null;
+ connection = null;
+ stderrBuffer = [];
+ processExited = false;
+ diagnosticsStore = new Map;
+ requestTimeoutMs;
+ initializeTimeoutMs;
+ workspaceApplyEditHandler = null;
+ diagnosticPullSupported = false;
+ constructor(root, server2, timeouts = {}) {
+ this.root = root;
+ this.server = server2;
+ this.requestTimeoutMs = timeouts.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
+ this.initializeTimeoutMs = timeouts.initializeTimeoutMs ?? INIT_TIMEOUT_MS;
+ }
+ pid() {
+ return this.proc?.pid;
+ }
+ command() {
+ return [...this.server.command];
+ }
+ setWorkspaceApplyEditHandler(handler) {
+ this.workspaceApplyEditHandler = handler;
+ }
+ hasWorkspaceApplyEditHandler() {
+ return this.workspaceApplyEditHandler !== null;
+ }
+ setDiagnosticPullSupported(supported) {
+ this.diagnosticPullSupported = supported;
+ }
+ isDiagnosticPullSupported() {
+ return this.diagnosticPullSupported;
+ }
+ handlePublishDiagnostics(params) {
+ this.diagnosticsStore.set(params.uri, [...params.diagnostics]);
+ }
+ async start() {
+ const env = createLspSpawnEnv(this.root, {
+ ...process.env,
+ ...this.server.env
+ });
+ this.proc = spawnProcess(this.server.command, {
+ cwd: this.root,
+ env
+ });
+ this.startStderrReading();
+ if (this.proc.exitCode !== null) {
+ const stderr = this.stderrBuffer.join(`
+`);
+ throw new LspProcessExitedError(this.server.id, this.root, this.proc.exitCode, stderr.slice(-2000));
+ }
+ this.connection = new JsonRpcConnection(this.proc.stdout, this.proc.stdin);
+ this.connection.onNotification("textDocument/publishDiagnostics", (params) => {
+ const diagnosticsParams = parseDiagnosticsParams(params);
+ if (diagnosticsParams?.uri) {
+ this.handlePublishDiagnostics(diagnosticsParams);
+ }
+ });
+ this.connection.onRequest("workspace/configuration", (params) => {
+ const items = parseConfigurationItems(params);
+ return items.map((item) => {
+ if (item.section === "json")
+ return { validate: { enable: true } };
+ return {};
+ });
+ });
+ this.connection.onRequest("client/registerCapability", () => null);
+ this.connection.onRequest("window/workDoneProgress/create", () => null);
+ if (this.workspaceApplyEditHandler) {
+ this.connection.onRequest("workspace/applyEdit", this.workspaceApplyEditHandler);
+ }
+ this.connection.onClose(() => {
+ this.processExited = true;
+ });
+ this.connection.onError((error) => {
+ reportBestEffortCleanupError("connection error notification", error);
+ });
+ this.connection.listen();
+ }
+ startStderrReading() {
+ if (!this.proc)
+ return;
+ this.proc.stderr.setEncoding("utf-8");
+ this.proc.stderr.on("data", (chunk) => {
+ this.stderrBuffer.push(chunk);
+ if (this.stderrBuffer.length > 100) {
+ this.stderrBuffer.shift();
+ }
+ });
+ }
+ isConnectionClosedError(error) {
+ if (!(error instanceof Error)) {
+ return false;
+ }
+ const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
+ return code === "ERR_STREAM_DESTROYED" || /connection closed|connection is disposed|stream was destroyed/i.test(error.message);
+ }
+ async sendRequest(method, ...args) {
+ if (!this.connection)
+ throw new LspClientNotStartedError(this.server.id, this.root);
+ if (this.processExited || this.proc && this.proc.exitCode !== null) {
+ const stderrTail = this.stderrBuffer.slice(-10).join(`
+`);
+ throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, stderrTail || undefined);
+ }
+ const options = args[1];
+ const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
+ const timeoutController = new AbortController;
+ const timeoutHandle = setTimeout(() => {
+ const stderrTail = this.stderrBuffer.slice(-5).join(`
+`);
+ timeoutController.abort(new LspRequestTimeoutError(method, stderrTail || undefined));
+ }, timeoutMs);
+ const combinedSignal = combineAbortSignals(options?.signal, timeoutController.signal);
+ try {
+ const result = args.length === 0 ? await this.connection.sendRequest(method, undefined, { signal: combinedSignal.signal }) : await this.connection.sendRequest(method, args[0], { signal: combinedSignal.signal });
+ return result;
+ } catch (error) {
+ if (this.processExited || this.proc && this.proc.exitCode !== null) {
+ throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, this.stderrBuffer.slice(-10).join(`
+`) || undefined);
+ }
+ if (this.isConnectionClosedError(error)) {
+ throw new LspConnectionClosedError(this.server.id, this.root, error.message);
+ }
+ throw error;
+ } finally {
+ clearTimeout(timeoutHandle);
+ combinedSignal.dispose();
+ }
+ }
+ async sendNotification(method, ...args) {
+ if (!this.connection)
+ return;
+ if (this.processExited || this.proc && this.proc.exitCode !== null)
+ return;
+ try {
+ if (args.length === 0) {
+ await this.connection.sendNotification(method);
+ } else {
+ await this.connection.sendNotification(method, args[0]);
+ }
+ } catch (error) {
+ if (this.isConnectionClosedError(error)) {
+ throw new LspConnectionClosedError(this.server.id, this.root, error.message);
+ }
+ throw error;
+ }
+ }
+ isAlive() {
+ return this.proc !== null && !this.processExited && this.proc.exitCode === null;
+ }
+ async stop() {
+ if (this.connection) {
+ try {
+ await this.sendRequest("shutdown");
+ } catch (error) {
+ reportBestEffortCleanupError("shutdown request", error instanceof Error ? error : String(error));
+ }
+ try {
+ await this.sendNotification("exit");
+ } catch (error) {
+ reportBestEffortCleanupError("exit notification", error instanceof Error ? error : String(error));
+ }
+ try {
+ this.connection.dispose();
+ } catch (error) {
+ reportBestEffortCleanupError("connection dispose", error instanceof Error ? error : String(error));
+ }
+ this.connection = null;
+ }
+ const proc = this.proc;
+ if (proc) {
+ this.proc = null;
+ let exitedBeforeTimeout = false;
+ try {
+ proc.kill();
+ let timeoutId;
+ const timeoutPromise = new Promise((resolve2) => {
+ timeoutId = setTimeout(resolve2, STOP_HARD_KILL_TIMEOUT_MS);
+ });
+ await Promise.race([
+ proc.exited.then(() => {
+ exitedBeforeTimeout = true;
+ }).finally(() => {
+ if (timeoutId)
+ clearTimeout(timeoutId);
+ }),
+ timeoutPromise
+ ]);
+ if (!exitedBeforeTimeout) {
+ try {
+ proc.kill("SIGKILL");
+ await Promise.race([
+ proc.exited,
+ new Promise((resolve2) => setTimeout(resolve2, STOP_SIGKILL_GRACE_MS))
+ ]);
+ } catch (error) {
+ reportBestEffortCleanupError("hard process kill", error instanceof Error ? error : String(error));
+ }
+ }
+ } catch (error) {
+ reportBestEffortCleanupError("process stop", error instanceof Error ? error : String(error));
+ }
+ }
+ this.processExited = true;
+ this.diagnosticsStore.clear();
+ }
+ getStoredDiagnostics(uri) {
+ return this.diagnosticsStore.get(uri) ?? [];
+ }
+}
+function combineAbortSignals(primary, secondary) {
+ const controller = new AbortController;
+ const abortFrom = (signal) => {
+ if (!controller.signal.aborted)
+ controller.abort(signal.reason);
+ };
+ const onPrimaryAbort = () => {
+ if (primary)
+ abortFrom(primary);
+ };
+ const onSecondaryAbort = () => abortFrom(secondary);
+ if (primary?.aborted)
+ abortFrom(primary);
+ else
+ primary?.addEventListener("abort", onPrimaryAbort, { once: true });
+ if (secondary.aborted)
+ abortFrom(secondary);
+ else
+ secondary.addEventListener("abort", onSecondaryAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => {
+ primary?.removeEventListener("abort", onPrimaryAbort);
+ secondary.removeEventListener("abort", onSecondaryAbort);
+ }
+ };
+}
+
+// ../lsp-core/src/lsp/connection.ts
+function supportsDiagnosticPull(capabilities) {
+ if (capabilities === undefined)
+ return false;
+ return Object.hasOwn(capabilities, "diagnosticProvider");
+}
+
+class LspClientConnection extends LspClientTransport {
+ async initialize() {
+ const rootUri = pathToFileURL(this.root).href;
+ const result = await this.sendRequest("initialize", {
+ processId: process.pid,
+ rootUri,
+ rootPath: this.root,
+ workspaceFolders: [{ uri: rootUri, name: "workspace" }],
+ capabilities: {
+ textDocument: {
+ hover: { contentFormat: ["markdown", "plaintext"] },
+ definition: { linkSupport: true },
+ references: {},
+ documentSymbol: { hierarchicalDocumentSymbolSupport: true },
+ publishDiagnostics: {},
+ rename: {
+ prepareSupport: true,
+ prepareSupportDefaultBehavior: 1
+ },
+ codeAction: {
+ codeActionLiteralSupport: {
+ codeActionKind: {
+ valueSet: [
+ "quickfix",
+ "refactor",
+ "refactor.extract",
+ "refactor.inline",
+ "refactor.rewrite",
+ "source",
+ "source.organizeImports",
+ "source.fixAll"
+ ]
+ }
+ },
+ isPreferredSupport: true,
+ disabledSupport: true,
+ dataSupport: true,
+ resolveSupport: {
+ properties: ["edit", "command"]
+ }
+ }
+ },
+ workspace: {
+ symbol: {},
+ workspaceFolders: true,
+ configuration: true,
+ ...this.hasWorkspaceApplyEditHandler() ? { applyEdit: true } : {},
+ workspaceEdit: {
+ documentChanges: true,
+ resourceOperations: ["create", "rename", "delete"]
+ }
+ }
+ },
+ initializationOptions: this.server.initialization
+ }, { timeoutMs: this.initializeTimeoutMs });
+ this.setDiagnosticPullSupported(supportsDiagnosticPull(result?.capabilities));
+ await this.sendNotification("initialized");
+ await this.sendNotification("workspace/didChangeConfiguration", {
+ settings: { json: { validate: { enable: true } } }
+ });
+ }
+}
+
+// ../lsp-core/src/lsp/workspace-document-state.ts
+import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
+import { relative as relative2, resolve as resolve2 } from "node:path";
+import { pathToFileURL as pathToFileURL2 } from "node:url";
+
+// ../lsp-core/src/lsp/language-mappings.ts
+var SYMBOL_KIND_MAP = {
+ 1: "File",
+ 2: "Module",
+ 3: "Namespace",
+ 4: "Package",
+ 5: "Class",
+ 6: "Method",
+ 7: "Property",
+ 8: "Field",
+ 9: "Constructor",
+ 10: "Enum",
+ 11: "Interface",
+ 12: "Function",
+ 13: "Variable",
+ 14: "Constant",
+ 15: "String",
+ 16: "Number",
+ 17: "Boolean",
+ 18: "Array",
+ 19: "Object",
+ 20: "Key",
+ 21: "Null",
+ 22: "EnumMember",
+ 23: "Struct",
+ 24: "Event",
+ 25: "Operator",
+ 26: "TypeParameter"
+};
+var SEVERITY_MAP = {
+ 1: "error",
+ 2: "warning",
+ 3: "information",
+ 4: "hint"
+};
+var EXT_TO_LANG = {
+ ".abap": "abap",
+ ".bat": "bat",
+ ".bib": "bibtex",
+ ".bibtex": "bibtex",
+ ".clj": "clojure",
+ ".cljs": "clojure",
+ ".cljc": "clojure",
+ ".edn": "clojure",
+ ".coffee": "coffeescript",
+ ".c": "c",
+ ".cpp": "cpp",
+ ".cxx": "cpp",
+ ".cc": "cpp",
+ ".c++": "cpp",
+ ".cs": "csharp",
+ ".css": "css",
+ ".d": "d",
+ ".pas": "pascal",
+ ".pascal": "pascal",
+ ".diff": "diff",
+ ".patch": "diff",
+ ".dart": "dart",
+ ".dockerfile": "dockerfile",
+ ".ex": "elixir",
+ ".exs": "elixir",
+ ".erl": "erlang",
+ ".hrl": "erlang",
+ ".fs": "fsharp",
+ ".fsi": "fsharp",
+ ".fsx": "fsharp",
+ ".fsscript": "fsharp",
+ ".gitcommit": "git-commit",
+ ".gitrebase": "git-rebase",
+ ".go": "go",
+ ".groovy": "groovy",
+ ".gleam": "gleam",
+ ".hbs": "handlebars",
+ ".handlebars": "handlebars",
+ ".hs": "haskell",
+ ".html": "html",
+ ".htm": "html",
+ ".ini": "ini",
+ ".java": "java",
+ ".jl": "julia",
+ ".js": "javascript",
+ ".jsx": "javascriptreact",
+ ".json": "json",
+ ".jsonc": "jsonc",
+ ".tex": "latex",
+ ".latex": "latex",
+ ".less": "less",
+ ".lua": "lua",
+ ".makefile": "makefile",
+ makefile: "makefile",
+ ".md": "markdown",
+ ".markdown": "markdown",
+ ".m": "objective-c",
+ ".mm": "objective-cpp",
+ ".pl": "perl",
+ ".pm": "perl",
+ ".pm6": "perl6",
+ ".php": "php",
+ ".ps1": "powershell",
+ ".psm1": "powershell",
+ ".pug": "jade",
+ ".jade": "jade",
+ ".py": "python",
+ ".pyi": "python",
+ ".r": "r",
+ ".cshtml": "razor",
+ ".razor": "razor",
+ ".rb": "ruby",
+ ".rake": "ruby",
+ ".gemspec": "ruby",
+ ".ru": "ruby",
+ ".erb": "erb",
+ ".html.erb": "erb",
+ ".js.erb": "erb",
+ ".css.erb": "erb",
+ ".json.erb": "erb",
+ ".rs": "rust",
+ ".scss": "scss",
+ ".sass": "sass",
+ ".scala": "scala",
+ ".shader": "shaderlab",
+ ".sh": "shellscript",
+ ".bash": "shellscript",
+ ".zsh": "shellscript",
+ ".ksh": "shellscript",
+ ".sql": "sql",
+ ".svelte": "svelte",
+ ".swift": "swift",
+ ".ts": "typescript",
+ ".tsx": "typescriptreact",
+ ".mts": "typescript",
+ ".cts": "typescript",
+ ".mtsx": "typescriptreact",
+ ".ctsx": "typescriptreact",
+ ".xml": "xml",
+ ".xsl": "xsl",
+ ".yaml": "yaml",
+ ".yml": "yaml",
+ ".mjs": "javascript",
+ ".cjs": "javascript",
+ ".vue": "vue",
+ ".zig": "zig",
+ ".zon": "zig",
+ ".astro": "astro",
+ ".ml": "ocaml",
+ ".mli": "ocaml",
+ ".tf": "terraform",
+ ".tfvars": "terraform-vars",
+ ".hcl": "hcl",
+ ".nix": "nix",
+ ".typ": "typst",
+ ".typc": "typst",
+ ".ets": "typescript",
+ ".lhs": "haskell",
+ ".kt": "kotlin",
+ ".kts": "kotlin",
+ ".prisma": "prisma",
+ ".h": "c",
+ ".hpp": "cpp",
+ ".hh": "cpp",
+ ".hxx": "cpp",
+ ".h++": "cpp",
+ ".objc": "objective-c",
+ ".objcpp": "objective-cpp",
+ ".fish": "fish",
+ ".graphql": "graphql",
+ ".gql": "graphql"
+};
+function getLanguageId(ext) {
+ return EXT_TO_LANG[ext] ?? "plaintext";
+}
+
+// ../lsp-core/src/lsp/workspace-document-state.ts
+var WATCHED_FILE_BATCH_SIZE = 128;
+var DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
+function canonicalPath(filePath) {
+ const absolute = resolve2(filePath);
+ try {
+ return realpathSync2(absolute);
+ } catch {
+ return absolute;
+ }
+}
+function isSameOrDescendant(candidate, parent) {
+ const suffix = relative2(parent, candidate);
+ return suffix === "" || !suffix.startsWith("..") && suffix !== "..";
+}
+function movedPath(candidate, oldPath, newPath) {
+ const suffix = relative2(oldPath, candidate);
+ return suffix === "" ? newPath : resolve2(newPath, suffix);
+}
+
+class WorkspaceDocumentState {
+ sendNotification;
+ clearDiagnostics;
+ openDocuments = new Map;
+ openByUri = new Map;
+ openPromises = new Map;
+ now;
+ versionlessPublishQuiescenceMs;
+ constructor(sendNotification, clearDiagnostics, options = {}) {
+ this.sendNotification = sendNotification;
+ this.clearDiagnostics = clearDiagnostics;
+ this.now = options.now ?? (() => Date.now());
+ this.versionlessPublishQuiescenceMs = options.versionlessPublishQuiescenceMs ?? DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS;
+ }
+ async openFile(filePath) {
+ const path2 = canonicalPath(filePath);
+ const existingOpen = this.openPromises.get(path2);
+ if (existingOpen) {
+ await existingOpen;
+ return this.openFile(path2);
+ }
+ const text = readFileSync2(path2, "utf-8");
+ const existing = this.openDocuments.get(path2);
+ if (!existing)
+ return this.openDocumentSingleFlight(path2, text);
+ if (existing.text === text)
+ return;
+ await this.changeDocument(existing, text);
+ }
+ getVersion(filePath) {
+ return this.openDocuments.get(canonicalPath(filePath))?.version;
+ }
+ getStoredDiagnostics(uri) {
+ const state = this.openByUri.get(uri);
+ if (!state)
+ return [];
+ return state.lastPublish?.diagnostics ?? state.pullCache?.diagnostics ?? [];
+ }
+ captureDiagnosticSnapshot(filePath) {
+ const state = this.openDocuments.get(canonicalPath(filePath));
+ if (!state)
+ return null;
+ return {
+ path: state.path,
+ uri: state.uri,
+ version: state.version,
+ documentGeneration: state.generation,
+ publishGeneration: state.publishGeneration
+ };
+ }
+ isCurrentSnapshot(snapshot) {
+ const state = this.openDocuments.get(snapshot.path);
+ return state !== undefined && state.uri === snapshot.uri && state.version === snapshot.version && state.generation === snapshot.documentGeneration;
+ }
+ getPullCache(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.pullCache || state.pullCache.documentVersion !== snapshot.version)
+ return null;
+ return state.pullCache;
+ }
+ recordPullDiagnostics(snapshot, report) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state)
+ return;
+ state.pullCache = {
+ documentVersion: snapshot.version,
+ diagnostics: [...report.diagnostics],
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ };
+ }
+ recordPublishedDiagnostics(params) {
+ const state = this.openByUri.get(params.uri);
+ if (!state)
+ return;
+ state.publishGeneration += 1;
+ state.lastPublish = {
+ diagnostics: [...params.diagnostics],
+ publishGeneration: state.publishGeneration,
+ documentGenerationAtArrival: state.generation,
+ arrivedAt: this.now(),
+ ...params.version === undefined ? {} : { version: params.version }
+ };
+ this.notifyWaiters(state);
+ }
+ resolvePushDiagnostics(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.lastPublish)
+ return { status: "missing" };
+ const publish = state.lastPublish;
+ if (publish.version !== undefined) {
+ return publish.version === snapshot.version ? { status: "ready", diagnostics: publish.diagnostics } : { status: "missing" };
+ }
+ if (publish.documentGenerationAtArrival < snapshot.documentGeneration)
+ return { status: "missing" };
+ const readyAt = publish.arrivedAt + this.versionlessPublishQuiescenceMs;
+ const waitMs = Math.max(0, readyAt - this.now());
+ return waitMs === 0 ? { status: "ready", diagnostics: publish.diagnostics } : { status: "wait", waitMs };
+ }
+ waitForDiagnosticsActivity(snapshot, timeoutMs) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state || timeoutMs <= 0)
+ return Promise.resolve();
+ return new Promise((resolveActivity) => {
+ let settled = false;
+ const finish = () => {
+ if (settled)
+ return;
+ settled = true;
+ clearTimeout(timer);
+ state.waiters.delete(finish);
+ resolveActivity();
+ };
+ const timer = setTimeout(finish, timeoutMs);
+ if (typeof timer.unref === "function")
+ timer.unref();
+ state.waiters.add(finish);
+ });
+ }
+ validateVersions(operations) {
+ const versions = new Map([...this.openDocuments].map(([path2, state]) => [path2, state.version]));
+ for (const operation of operations) {
+ if (operation.kind === "text") {
+ const current = versions.get(operation.path);
+ if (operation.documentVersion !== null && current !== operation.documentVersion) {
+ const observed = current === undefined ? "closed document" : `open document version ${current}`;
+ return {
+ changeIndex: operation.changeIndex,
+ message: `document version ${operation.documentVersion} does not match ${observed} for ${operation.path}`
+ };
+ }
+ if (current !== undefined)
+ versions.set(operation.path, current + 1);
+ continue;
+ }
+ if (operation.kind === "rename") {
+ const moved = [...versions].filter(([path2]) => isSameOrDescendant(path2, operation.oldPath));
+ for (const [path2] of moved)
+ versions.delete(path2);
+ for (const [path2] of moved)
+ versions.set(movedPath(path2, operation.oldPath, operation.newPath), 1);
+ continue;
+ }
+ if (operation.kind === "delete") {
+ for (const path2 of [...versions.keys()]) {
+ if (isSameOrDescendant(path2, operation.path))
+ versions.delete(path2);
+ }
+ continue;
+ }
+ if (operation.kind === "create" && operation.replaced && versions.has(operation.path)) {
+ versions.set(operation.path, 1);
+ }
+ }
+ return null;
+ }
+ async synchronize(delta) {
+ const watched = [];
+ for (const mutation of delta.operations)
+ await this.synchronizeMutation(mutation, watched);
+ for (let index = 0;index < watched.length; index += WATCHED_FILE_BATCH_SIZE) {
+ await this.sendNotification("workspace/didChangeWatchedFiles", {
+ changes: watched.slice(index, index + WATCHED_FILE_BATCH_SIZE)
+ });
+ }
+ }
+ async synchronizeMutation(mutation, watched) {
+ if (mutation.kind === "text") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state)
+ await this.changeDocument(state, mutation.afterText);
+ else
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 2 });
+ return;
+ }
+ if (mutation.kind === "create") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state) {
+ await this.closeDocument(state);
+ await this.openDocumentSingleFlight(mutation.path, readFileSync2(mutation.path, "utf-8"));
+ } else {
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: mutation.replaced ? 2 : 1 });
+ }
+ return;
+ }
+ if (mutation.kind === "rename") {
+ const moved = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.oldPath));
+ for (const state of moved)
+ await this.closeDocument(state);
+ for (const state of moved) {
+ const path2 = movedPath(state.path, mutation.oldPath, mutation.newPath);
+ await this.openDocumentSingleFlight(path2, readFileSync2(path2, "utf-8"));
+ }
+ if (moved.length === 0) {
+ watched.push({ uri: pathToFileURL2(mutation.oldPath).href, type: 3 });
+ watched.push({ uri: pathToFileURL2(mutation.newPath).href, type: 1 });
+ }
+ return;
+ }
+ const removed = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.path));
+ for (const state of removed)
+ await this.closeDocument(state);
+ if (removed.length === 0)
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 3 });
+ }
+ async openDocumentSingleFlight(path2, text) {
+ const existing = this.openPromises.get(path2);
+ if (existing)
+ return existing;
+ const open = (async () => {
+ const state = {
+ path: path2,
+ uri: pathToFileURL2(path2).href,
+ languageId: getLanguageId(effectiveExtension(path2)),
+ text,
+ version: 1,
+ generation: 1,
+ publishGeneration: 0,
+ waiters: new Set
+ };
+ this.openDocuments.set(path2, state);
+ this.openByUri.set(state.uri, state);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didOpen", {
+ textDocument: { uri: state.uri, languageId: state.languageId, version: state.version, text }
+ });
+ })().finally(() => {
+ this.openPromises.delete(path2);
+ });
+ this.openPromises.set(path2, open);
+ return open;
+ }
+ async changeDocument(state, text) {
+ state.text = text;
+ state.version += 1;
+ state.generation += 1;
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didChange", {
+ textDocument: { uri: state.uri, version: state.version },
+ contentChanges: [{ text }]
+ });
+ await this.sendNotification("textDocument/didSave", { textDocument: { uri: state.uri }, text });
+ }
+ async closeDocument(state) {
+ this.openDocuments.delete(state.path);
+ this.openByUri.delete(state.uri);
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didClose", { textDocument: { uri: state.uri } });
+ }
+ notifyWaiters(state) {
+ for (const waiter of [...state.waiters])
+ waiter();
+ }
+}
+
+// ../lsp-core/src/lsp/workspace-apply-edit-failure.ts
+var CONCURRENT_FAILURE_REASON_BY_PHASE = {
+ applying: "workspace/applyEdit is already in progress for this workspace mutation",
+ settled: "workspace/applyEdit was already handled for this workspace mutation"
+};
+function workspaceApplyEditConcurrentFailureReason(phase) {
+ return CONCURRENT_FAILURE_REASON_BY_PHASE[phase];
+}
+
+// ../lsp-core/src/lsp/workspace-edit-commit.ts
+import { existsSync as existsSync4, lstatSync as lstatSync3, renameSync, rmSync, writeFileSync } from "node:fs";
+
+// ../lsp-core/src/lsp/workspace-edit-path.ts
+import { existsSync as existsSync3, lstatSync as lstatSync2, readFileSync as readFileSync3, readdirSync, realpathSync as realpathSync3 } from "node:fs";
+import { dirname as dirname4, isAbsolute as isAbsolute3, relative as relative3, resolve as resolve3 } from "node:path";
+import { fileURLToPath as fileURLToPath2 } from "node:url";
+
+class WorkspaceEditPathError extends Error {
+ path;
+ detail;
+ name = "WorkspaceEditPathError";
+ constructor(path2, detail) {
+ super(`${detail}: ${path2}`);
+ this.path = path2;
+ this.detail = detail;
+ }
+}
+function isPathInsideWorkspace(filePath, workspaceRoot) {
+ const relativePath = relative3(workspaceRoot, filePath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute3(relativePath);
+}
+function canonicalizeMissingPath(filePath) {
+ let ancestor = filePath;
+ while (!existsSync3(ancestor)) {
+ const parent = dirname4(ancestor);
+ if (parent === ancestor)
+ throw new WorkspaceEditPathError(filePath, "no existing ancestor");
+ ancestor = parent;
+ }
+ return resolve3(realpathSync3(ancestor), relative3(ancestor, filePath));
+}
+function canonicalWorkspaceRoot(workspaceRoot) {
+ try {
+ const canonical = realpathSync3(resolve3(workspaceRoot));
+ if (!lstatSync2(canonical).isDirectory()) {
+ return { success: false, error: `workspace root is not a directory: ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath: resolve3(workspaceRoot),
+ followedSymbolicLink: existsSync3(resolve3(workspaceRoot)) && lstatSync2(resolve3(workspaceRoot)).isSymbolicLink()
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `workspace root ${workspaceRoot}: ${detail}` };
+ }
+}
+function uriToCanonicalWorkspacePath(uri, workspaceRoot) {
+ let requestedPath;
+ try {
+ const parsed = new URL(uri);
+ if (parsed.protocol !== "file:" || parsed.search !== "" || parsed.hash !== "") {
+ return { success: false, error: `non-file URI ${uri}` };
+ }
+ requestedPath = resolve3(fileURLToPath2(parsed));
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `non-file URI ${uri}: ${detail}` };
+ }
+ try {
+ const canonical = existsSync3(requestedPath) ? realpathSync3(requestedPath) : canonicalizeMissingPath(requestedPath);
+ if (!isPathInsideWorkspace(canonical, workspaceRoot)) {
+ return { success: false, error: `${requestedPath}: outside workspace ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath,
+ followedSymbolicLink: existsSync3(requestedPath) && lstatSync2(requestedPath).isSymbolicLink()
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `${requestedPath}: ${detail}` };
+ }
+}
+function snapshotPath(path2, includeChildren) {
+ if (!existsSync3(path2))
+ return { kind: "missing" };
+ const stats = lstatSync2(path2);
+ if (stats.isFile())
+ return { kind: "file", content: readFileSync3(path2, "utf-8") };
+ if (stats.isDirectory()) {
+ return includeChildren ? { kind: "directory", children: readdirSync(path2).sort() } : { kind: "directory" };
+ }
+ throw new WorkspaceEditPathError(path2, "unsupported filesystem entry");
+}
+
+// ../lsp-core/src/lsp/workspace-edit-commit.ts
+var DEFAULT_IO = {
+ writeFile(path2, content) {
+ writeFileSync(path2, content, "utf-8");
+ },
+ rename(oldPath, newPath) {
+ renameSync(oldPath, newPath);
+ },
+ remove(path2, recursive) {
+ rmSync(path2, { recursive, force: false });
+ }
+};
+function snapshotsEqual(expected, actual) {
+ if (expected.kind !== actual.kind)
+ return false;
+ if (expected.kind === "file" && actual.kind === "file")
+ return expected.content === actual.content;
+ if (expected.kind === "directory" && actual.kind === "directory" && expected.children !== undefined) {
+ return JSON.stringify(expected.children) === JSON.stringify(actual.children);
+ }
+ return true;
+}
+function liveSnapshot(path2, expected) {
+ return snapshotPath(path2, expected.kind === "directory" && expected.children !== undefined);
+}
+function firstOperationIndex(plan) {
+ return plan.operations[0]?.changeIndex ?? 0;
+}
+function failedCommit(plan, failure) {
+ const { message, changeIndex, mutations = [], filesModified = [], totalEdits = 0, lateAbort = false } = failure;
+ return {
+ result: {
+ success: false,
+ filesModified,
+ totalEdits,
+ errors: [`change ${changeIndex}: ${message}`],
+ failedChange: changeIndex,
+ ...lateAbort ? { lateAbort: true } : {}
+ },
+ delta: mutationDelta(mutations),
+ fingerprint: plan.fingerprint
+ };
+}
+function verifySnapshots(plan) {
+ for (const [path2, expected] of plan.snapshots) {
+ let actual;
+ try {
+ actual = liveSnapshot(path2, expected);
+ } catch (error) {
+ const changeIndex = plan.firstChangeByPath.get(path2) ?? firstOperationIndex(plan);
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, { message: `cannot verify snapshot for ${path2}: ${detail}`, changeIndex });
+ }
+ if (!snapshotsEqual(expected, actual)) {
+ const changeIndex = plan.firstChangeByPath.get(path2) ?? firstOperationIndex(plan);
+ return failedCommit(plan, { message: `workspace state changed before commit: ${path2}`, changeIndex });
+ }
+ }
+ return null;
+}
+function addModifiedPath(paths, path2) {
+ if (!paths.includes(path2))
+ paths.push(path2);
+}
+function reportedPath(plan, path2) {
+ return plan.reportedPathByCanonical.get(path2) ?? path2;
+}
+function changedPathsForMutation(mutation) {
+ return mutation.kind === "rename" ? [mutation.oldPath, mutation.newPath] : [mutation.path];
+}
+function mutationDelta(operations) {
+ const changedPaths = new Set;
+ for (const operation of operations) {
+ for (const path2 of changedPathsForMutation(operation))
+ changedPaths.add(path2);
+ }
+ return { operations, changedPaths: [...changedPaths].sort() };
+}
+function resolveIo(overrides) {
+ return {
+ writeFile: overrides?.writeFile ?? DEFAULT_IO.writeFile,
+ rename: overrides?.rename ?? DEFAULT_IO.rename,
+ remove: overrides?.remove ?? DEFAULT_IO.remove
+ };
+}
+function commitOperation(context, operation) {
+ const { plan, io, accumulator } = context;
+ if (operation.kind === "noop")
+ return;
+ if (operation.kind === "text") {
+ io.writeFile(operation.path, operation.afterText);
+ accumulator.mutations.push({
+ kind: "text",
+ path: operation.path,
+ beforeText: operation.beforeText,
+ afterText: operation.afterText
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ accumulator.totalEdits += operation.editCount;
+ return;
+ }
+ if (operation.kind === "create") {
+ io.writeFile(operation.path, "");
+ accumulator.mutations.push({ kind: "create", path: operation.path, replaced: operation.replaced });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ return;
+ }
+ if (operation.kind === "rename") {
+ if (operation.replaceDestination) {
+ const targetKind = existsSync4(operation.newPath) && lstatSync3(operation.newPath).isDirectory() ? "directory" : "file";
+ io.remove(operation.newPath, targetKind === "directory");
+ accumulator.mutations.push({ kind: "delete", path: operation.newPath, targetKind });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ }
+ io.rename(operation.oldPath, operation.newPath);
+ accumulator.mutations.push({
+ kind: "rename",
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: operation.sourceKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ return;
+ }
+ io.remove(operation.path, operation.recursive);
+ accumulator.mutations.push({
+ kind: "delete",
+ path: operation.path,
+ targetKind: operation.targetKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+}
+function commitWorkspaceEditPlan(plan, options = {}) {
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const stale = verifySnapshots(plan);
+ if (stale)
+ return stale;
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const io = resolveIo(options.io);
+ const accumulator = { mutations: [], filesModified: [], totalEdits: 0 };
+ const context = { plan, io, accumulator };
+ let lateAbort = false;
+ for (const operation of plan.operations) {
+ try {
+ commitOperation(context, operation);
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, {
+ message: `I/O failure during ${operation.kind}: ${detail}`,
+ changeIndex: operation.changeIndex,
+ mutations: accumulator.mutations,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ lateAbort: lateAbort || options.signal?.aborted === true
+ });
+ }
+ if (options.signal?.aborted)
+ lateAbort = true;
+ }
+ const result = {
+ success: true,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ errors: [],
+ ...lateAbort ? { lateAbort: true } : {}
+ };
+ return { result, delta: mutationDelta(accumulator.mutations), fingerprint: plan.fingerprint };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-fingerprint.ts
+import { createHash as createHash2 } from "node:crypto";
+function canonicalFingerprint(operations) {
+ const canonical = operations.map((operation) => {
+ switch (operation.kind) {
+ case "text":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ edits: operation.edits,
+ version: operation.version
+ };
+ case "rename":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "create":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "delete":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ recursive: operation.recursive,
+ ignoreIfNotExists: operation.ignoreIfNotExists
+ };
+ }
+ });
+ return createHash2("sha256").update(JSON.stringify(canonical)).digest("hex");
+}
+
+// ../lsp-core/src/lsp/workspace-edit-types.ts
+class WorkspaceEditValidationError extends Error {
+ changeIndex;
+ detail;
+ name = "WorkspaceEditValidationError";
+ constructor(changeIndex, detail) {
+ super(`change ${changeIndex}: ${detail}`);
+ this.changeIndex = changeIndex;
+ this.detail = detail;
+ }
+}
+
+// ../lsp-core/src/lsp/workspace-edit-parse-helpers.ts
+function isRecord3(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function parsePosition(value) {
+ if (!isRecord3(value) || typeof value["line"] !== "number" || typeof value["character"] !== "number") {
+ return null;
+ }
+ return { line: value["line"], character: value["character"] };
+}
+function parseRange(value) {
+ if (!isRecord3(value))
+ return null;
+ const start = parsePosition(value["start"]);
+ const end = parsePosition(value["end"]);
+ return start && end ? { start, end } : null;
+}
+function parseTextEdits(value, changeIndex) {
+ if (!Array.isArray(value)) {
+ throw new WorkspaceEditValidationError(changeIndex, "text edits must be an array");
+ }
+ const edits = [];
+ for (const candidate of value) {
+ if (!isRecord3(candidate) || typeof candidate["newText"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "text edit requires range and newText");
+ }
+ if ("annotationId" in candidate) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated text edits are unsupported");
+ }
+ const range = parseRange(candidate["range"]);
+ if (!range)
+ throw new WorkspaceEditValidationError(changeIndex, "text edit range is malformed");
+ edits.push({ range, newText: candidate["newText"] });
+ }
+ return edits;
+}
+function parseBooleanOption(options, key, changeIndex) {
+ const value = options[key];
+ if (value === undefined)
+ return false;
+ if (typeof value !== "boolean") {
+ throw new WorkspaceEditValidationError(changeIndex, `${key} must be boolean`);
+ }
+ return value;
+}
+function parseOptions(value, allowed, changeIndex) {
+ if (value === undefined)
+ return {};
+ if (!isRecord3(value))
+ throw new WorkspaceEditValidationError(changeIndex, "resource options must be an object");
+ for (const key of Object.keys(value)) {
+ if (!allowed.includes(key))
+ throw new WorkspaceEditValidationError(changeIndex, `unsupported resource option ${key}`);
+ }
+ const parsed = {};
+ for (const key of allowed)
+ parsed[key] = parseBooleanOption(value, key, changeIndex);
+ return parsed;
+}
+
+// ../lsp-core/src/lsp/workspace-edit-resource-parser.ts
+function parseResourceChange(input) {
+ const kind = input.change["kind"];
+ if (kind === "create" || kind === "delete") {
+ parseSinglePathResource(input, kind);
+ return;
+ }
+ if (kind !== "rename") {
+ throw new WorkspaceEditValidationError(input.changeIndex, `unsupported resource operation ${String(kind)}`);
+ }
+ parseRename(input);
+}
+function parseSinglePathResource(input, kind) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["uri"] !== "string")
+ throw new WorkspaceEditValidationError(changeIndex, `${kind}.uri is required`);
+ const resolvedPath = uriToCanonicalWorkspacePath(change["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ if (kind === "create") {
+ const options2 = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ overwrite: options2["overwrite"] ?? false,
+ ignoreIfExists: options2["ignoreIfExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["recursive", "ignoreIfNotExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ recursive: options["recursive"] ?? false,
+ ignoreIfNotExists: options["ignoreIfNotExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+}
+function parseRename(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["oldUri"] !== "string" || typeof change["newUri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "rename requires oldUri and newUri");
+ }
+ const oldPath = uriToCanonicalWorkspacePath(change["oldUri"], workspaceRoot);
+ const newPath = uriToCanonicalWorkspacePath(change["newUri"], workspaceRoot);
+ if (!oldPath.success || !newPath.success) {
+ target.failures.push({
+ changeIndex,
+ message: !oldPath.success ? oldPath.error : !newPath.success ? newPath.error : "invalid rename path"
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind: "rename",
+ changeIndex,
+ oldPath: oldPath.path,
+ newPath: newPath.path,
+ reportedOldPath: oldPath.requestedPath,
+ reportedNewPath: newPath.requestedPath,
+ overwrite: options["overwrite"] ?? false,
+ ignoreIfExists: options["ignoreIfExists"] ?? false,
+ followedSymbolicLink: oldPath.followedSymbolicLink || newPath.followedSymbolicLink
+ });
+}
+
+// ../lsp-core/src/lsp/workspace-edit-parser.ts
+function failureResult(failures) {
+ const sorted = [...failures].sort((left, right) => left.changeIndex - right.changeIndex);
+ const first = sorted[0];
+ return {
+ success: false,
+ filesModified: [],
+ totalEdits: 0,
+ errors: sorted.map((failure) => `change ${failure.changeIndex}: ${failure.message}`),
+ ...first ? { failedChange: first.changeIndex } : {}
+ };
+}
+function parseWorkspaceEdit(edit, workspaceRoot) {
+ if (!isRecord3(edit))
+ return { operations: [], failures: [{ changeIndex: 0, message: "No edit provided" }] };
+ if (edit["changeAnnotations"] !== undefined) {
+ return { operations: [], failures: [{ changeIndex: 0, message: "change annotations are unsupported" }] };
+ }
+ const hasChanges = edit["changes"] !== undefined;
+ const hasDocumentChanges = edit["documentChanges"] !== undefined;
+ if (hasChanges && hasDocumentChanges) {
+ return {
+ operations: [],
+ failures: [{ changeIndex: 0, message: "changes and documentChanges cannot be combined" }]
+ };
+ }
+ const target = { operations: [], failures: [] };
+ if (hasChanges)
+ return parseChanges(edit["changes"], workspaceRoot, target);
+ return parseDocumentChanges(edit["documentChanges"], workspaceRoot, target);
+}
+function parseChanges(value, workspaceRoot, target) {
+ if (!isRecord3(value))
+ return { ...target, failures: [{ changeIndex: 0, message: "changes must be an object" }] };
+ const entries = Object.entries(value).sort(([left], [right]) => left.localeCompare(right));
+ for (const [changeIndex, [uri, rawEdits]] of entries.entries()) {
+ const resolvedPath = uriToCanonicalWorkspacePath(uri, workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ continue;
+ }
+ try {
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(rawEdits, changeIndex),
+ version: null
+ });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChanges(value, workspaceRoot, target) {
+ if (value === undefined)
+ return target;
+ if (!Array.isArray(value)) {
+ return { ...target, failures: [{ changeIndex: 0, message: "documentChanges must be an array" }] };
+ }
+ for (const [changeIndex, change] of value.entries()) {
+ try {
+ parseDocumentChange({ change, changeIndex, workspaceRoot, target });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChange(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (!isRecord3(change))
+ throw new WorkspaceEditValidationError(changeIndex, "document change must be an object");
+ if ("annotationId" in change) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated resource operations are unsupported");
+ }
+ if (typeof change["kind"] === "string") {
+ parseResourceChange({ change, changeIndex, workspaceRoot, target });
+ return;
+ }
+ const identifier = change["textDocument"];
+ if (!isRecord3(identifier) || typeof identifier["uri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "textDocument.uri is required");
+ }
+ const version = identifier["version"];
+ if (version !== null && (!Number.isInteger(version) || typeof version !== "number" || version < 0)) {
+ throw new WorkspaceEditValidationError(changeIndex, "document version must be null or a non-negative integer");
+ }
+ const resolvedPath = uriToCanonicalWorkspacePath(identifier["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(change["edits"], changeIndex),
+ version
+ });
+}
+
+// ../lsp-core/src/lsp/workspace-edit-simulation.ts
+import { dirname as dirname5, relative as relative4, resolve as resolve4 } from "node:path";
+
+// ../lsp-core/src/lsp/workspace-edit-text.ts
+function comparePosition(left, right) {
+ return left.line === right.line ? left.character - right.character : left.line - right.line;
+}
+function positionsEqual(left, right) {
+ return left.line === right.line && left.character === right.character;
+}
+function rangesEqual(left, right) {
+ return positionsEqual(left.start, right.start) && positionsEqual(left.end, right.end);
+}
+function isEmptyRange(range) {
+ return positionsEqual(range.start, range.end);
+}
+function formatRange(range) {
+ return `${range.start.line + 1}:${range.start.character + 1}-${range.end.line + 1}:${range.end.character + 1}`;
+}
+function validatePosition(position, label, context) {
+ const { lines, changeIndex } = context;
+ if (!Number.isInteger(position.line) || !Number.isInteger(position.character)) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position must use integer line and character`);
+ }
+ if (position.line < 0 || position.character < 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position cannot be negative`);
+ }
+ const line = lines[position.line];
+ if (line === undefined) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} line ${position.line} is outside the document`);
+ }
+ if (position.character > line.length) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} character ${position.character} is outside line ${position.line}`);
+ }
+}
+function validateRange(range, lines, changeIndex) {
+ const context = { lines, changeIndex };
+ validatePosition(range.start, "start", context);
+ validatePosition(range.end, "end", context);
+ if (comparePosition(range.start, range.end) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `range ${formatRange(range)} ends before it starts`);
+ }
+}
+function sortAndDeduplicate(edits) {
+ const sorted = edits.map((edit, index) => ({ edit, index })).sort((left, right) => {
+ const positionOrder = comparePosition(right.edit.range.start, left.edit.range.start);
+ return positionOrder === 0 ? right.index - left.index : positionOrder;
+ });
+ const unique = [];
+ for (const entry of sorted) {
+ const previous = unique.at(-1);
+ if (previous !== undefined && !isEmptyRange(entry.edit.range) && rangesEqual(previous.range, entry.edit.range) && previous.newText === entry.edit.newText) {
+ continue;
+ }
+ unique.push(entry.edit);
+ }
+ return unique;
+}
+function validateNoOverlap(edits, changeIndex) {
+ for (let index = 0;index < edits.length - 1; index += 1) {
+ const later = edits[index];
+ const earlier = edits[index + 1];
+ if (later === undefined || earlier === undefined)
+ continue;
+ if (comparePosition(earlier.range.end, later.range.start) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `overlapping edits ${formatRange(earlier.range)} and ${formatRange(later.range)}`);
+ }
+ }
+}
+function applyNormalizedTextEdits(content, edits) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ const { start, end } = edit.range;
+ const startLine = lines[start.line];
+ const endLine = lines[end.line];
+ if (startLine === undefined || endLine === undefined)
+ continue;
+ const replacement = startLine.slice(0, start.character) + edit.newText + endLine.slice(end.character);
+ lines.splice(start.line, end.line - start.line + 1, ...replacement.split(`
+`));
+ }
+ return lines.join(`
+`);
+}
+function normalizeTextEdits(content, edits, changeIndex) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ validateRange(edit.range, lines, changeIndex);
+ }
+ const normalized = sortAndDeduplicate(edits);
+ validateNoOverlap(normalized, changeIndex);
+ return { edits: normalized, text: applyNormalizedTextEdits(content, normalized) };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-simulation.ts
+function isSameOrDescendant2(candidate, parent) {
+ const relativePath = relative4(parent, candidate);
+ return relativePath === "" || !relativePath.startsWith("..") && relativePath !== "..";
+}
+function removeVirtualSubtree(virtual, path2) {
+ for (const candidate of [...virtual.keys()]) {
+ if (isSameOrDescendant2(candidate, path2))
+ virtual.delete(candidate);
+ }
+ virtual.set(path2, { kind: "missing" });
+}
+function moveVirtualSubtree(virtual, oldPath, newPath) {
+ const moved = [...virtual.entries()].filter(([candidate]) => isSameOrDescendant2(candidate, oldPath));
+ removeVirtualSubtree(virtual, oldPath);
+ removeVirtualSubtree(virtual, newPath);
+ for (const [candidate, entry] of moved) {
+ const suffix = relative4(oldPath, candidate);
+ virtual.set(suffix === "" ? newPath : resolve4(newPath, suffix), entry);
+ }
+}
+function virtualDirectoryHasChildren(virtual, path2) {
+ for (const [candidate, entry] of virtual) {
+ if (candidate !== path2 && entry.kind !== "missing" && isSameOrDescendant2(candidate, path2))
+ return true;
+ }
+ return false;
+}
+function requireVirtualParent(virtual, path2, changeIndex) {
+ if (virtual.get(dirname5(path2))?.kind !== "directory") {
+ throw new WorkspaceEditValidationError(changeIndex, `parent directory does not exist for ${path2}`);
+ }
+}
+function simulateOperations(parsed, snapshots) {
+ const virtual = new Map(snapshots);
+ const planned = [];
+ const failures = [];
+ for (const operation of parsed) {
+ try {
+ planned.push(simulateOperation(operation, virtual));
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ failures.push({ changeIndex: operation.changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return { operations: planned, failures };
+}
+function simulateOperation(operation, virtual) {
+ switch (operation.kind) {
+ case "text":
+ return simulateText(operation, virtual);
+ case "create":
+ return simulateCreate(operation, virtual);
+ case "rename":
+ return simulateRename(operation, virtual);
+ case "delete":
+ return simulateDelete(operation, virtual);
+ }
+}
+function rejectSymbolicLink(operation) {
+ if (operation.followedSymbolicLink) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "resource operations through symbolic links are unsupported");
+ }
+}
+function simulateText(operation, virtual) {
+ const entry = virtual.get(operation.path);
+ if (entry?.kind !== "file")
+ throw new WorkspaceEditValidationError(operation.changeIndex, `${operation.path} is not a file`);
+ const normalized = normalizeTextEdits(entry.content, operation.edits, operation.changeIndex);
+ virtual.set(operation.path, { kind: "file", content: normalized.text });
+ return {
+ kind: "text",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ beforeText: entry.content,
+ afterText: normalized.text,
+ editCount: normalized.edits.length,
+ documentVersion: operation.version
+ };
+}
+function simulateCreate(operation, virtual) {
+ rejectSymbolicLink(operation);
+ requireVirtualParent(virtual, operation.path, operation.changeIndex);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind !== "missing") {
+ if (operation.overwrite && target.kind === "file") {
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: true };
+ }
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `create target already exists: ${operation.path}`);
+ }
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: false };
+}
+function simulateRename(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const source = virtual.get(operation.oldPath) ?? { kind: "missing" };
+ if (source.kind === "missing") {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename source does not exist: ${operation.oldPath}`);
+ }
+ if (operation.oldPath === operation.newPath)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ if (isSameOrDescendant2(operation.newPath, operation.oldPath)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "cannot rename a path into its own subtree");
+ }
+ requireVirtualParent(virtual, operation.newPath, operation.changeIndex);
+ const destination = virtual.get(operation.newPath) ?? { kind: "missing" };
+ if (destination.kind !== "missing" && !operation.overwrite) {
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename target already exists: ${operation.newPath}`);
+ }
+ moveVirtualSubtree(virtual, operation.oldPath, operation.newPath);
+ return {
+ kind: "rename",
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: source.kind,
+ replaceDestination: destination.kind !== "missing"
+ };
+}
+function simulateDelete(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind === "missing") {
+ if (operation.ignoreIfNotExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `delete target does not exist: ${operation.path}`);
+ }
+ if (target.kind === "directory" && !operation.recursive && virtualDirectoryHasChildren(virtual, operation.path)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `directory is not empty: ${operation.path}`);
+ }
+ removeVirtualSubtree(virtual, operation.path);
+ return {
+ kind: "delete",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ targetKind: target.kind,
+ recursive: operation.recursive
+ };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-snapshot.ts
+import { existsSync as existsSync5, lstatSync as lstatSync4, readdirSync as readdirSync2 } from "node:fs";
+import { dirname as dirname6, resolve as resolve5 } from "node:path";
+class WorkspaceSnapshotBuilder {
+ workspaceRoot;
+ snapshots = new Map;
+ constructor(workspaceRoot) {
+ this.workspaceRoot = workspaceRoot;
+ }
+ build(operations) {
+ this.add(this.workspaceRoot, false);
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, true);
+ this.add(operation.newPath, true);
+ break;
+ case "delete":
+ this.add(operation.path, true);
+ break;
+ case "text":
+ case "create":
+ this.add(operation.path, false);
+ break;
+ }
+ }
+ return this.snapshots;
+ }
+ add(path2, includeChildren) {
+ let candidate = path2;
+ while (true) {
+ const existing = this.snapshots.get(candidate);
+ if (existing === undefined || includeChildren && existing.kind === "directory" && existing.children === undefined) {
+ this.snapshots.set(candidate, snapshotPath(candidate, includeChildren && candidate === path2));
+ }
+ if (candidate === this.workspaceRoot)
+ break;
+ candidate = dirname6(candidate);
+ }
+ if (!includeChildren || !existsSync5(path2) || !lstatSync4(path2).isDirectory())
+ return;
+ for (const child of readdirSync2(path2))
+ this.add(resolve5(path2, child), true);
+ }
+}
+function snapshotOperations(operations, workspaceRoot) {
+ return new WorkspaceSnapshotBuilder(workspaceRoot).build(operations);
+}
+
+// ../lsp-core/src/lsp/workspace-edit-plan.ts
+class PlanPathIndex {
+ firstChangeByPath = new Map;
+ reportedPathByCanonical = new Map;
+ build(operations) {
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, operation.reportedOldPath, operation.changeIndex);
+ this.add(operation.newPath, operation.reportedNewPath, operation.changeIndex);
+ break;
+ case "text":
+ case "create":
+ case "delete":
+ this.add(operation.path, operation.reportedPath, operation.changeIndex);
+ break;
+ }
+ }
+ }
+ add(path2, reportedPath2, changeIndex) {
+ if (!this.firstChangeByPath.has(path2))
+ this.firstChangeByPath.set(path2, changeIndex);
+ if (!this.reportedPathByCanonical.has(path2))
+ this.reportedPathByCanonical.set(path2, reportedPath2);
+ }
+}
+function fingerprintWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ return { success: true, fingerprint: canonicalFingerprint(parsed.operations) };
+}
+function planWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ let snapshots;
+ try {
+ snapshots = snapshotOperations(parsed.operations, root.path);
+ } catch (error) {
+ return {
+ success: false,
+ result: failureResult([{ changeIndex: 0, message: error instanceof Error ? error.message : String(error) }])
+ };
+ }
+ const simulated = simulateOperations(parsed.operations, snapshots);
+ if (simulated.failures.length > 0)
+ return { success: false, result: failureResult(simulated.failures) };
+ const paths = new PlanPathIndex;
+ paths.build(parsed.operations);
+ const plan = {
+ workspaceRoot: root.path,
+ operations: simulated.operations,
+ snapshots,
+ firstChangeByPath: paths.firstChangeByPath,
+ reportedPathByCanonical: paths.reportedPathByCanonical,
+ fingerprint: canonicalFingerprint(parsed.operations)
+ };
+ return { success: true, plan };
+}
+
+// ../lsp-core/src/lsp/workspace-mutation-controller.ts
+function failure(message, failedChange, base) {
+ return {
+ success: false,
+ filesModified: base?.filesModified ?? [],
+ totalEdits: base?.totalEdits ?? 0,
+ errors: [message],
+ ...failedChange === undefined ? {} : { failedChange },
+ ...base?.lateAbort ? { lateAbort: true } : {}
+ };
+}
+function responseFor(result) {
+ if (result.success)
+ return { applied: true };
+ return {
+ applied: false,
+ failureReason: result.errors[0] ?? "workspace edit failed",
+ ...result.failedChange === undefined ? {} : { failedChange: result.failedChange }
+ };
+}
+function isRecord4(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+class WorkspaceMutationController {
+ workspaceRoot;
+ documents;
+ activeLease = null;
+ nextLeaseId = 1;
+ io;
+ constructor(workspaceRoot, documents) {
+ this.workspaceRoot = workspaceRoot;
+ this.documents = documents;
+ }
+ setIo(io) {
+ this.io = io;
+ }
+ acquire(signal) {
+ if (this.activeLease)
+ return { success: false, result: failure("workspace mutation is already in progress") };
+ if (signal?.aborted)
+ return { success: false, result: failure("cancelled before mutating request") };
+ const lease = {
+ id: this.nextLeaseId,
+ phase: "idle",
+ ...signal === undefined ? {} : { signal }
+ };
+ this.nextLeaseId += 1;
+ this.activeLease = lease;
+ return { success: true, lease };
+ }
+ release(lease) {
+ if (this.activeLease?.id !== lease.id)
+ return;
+ this.activeLease.phase = "sealed";
+ this.activeLease = null;
+ }
+ isBeforeCommit(lease) {
+ return this.activeLease?.id === lease.id && this.activeLease.phase === "idle";
+ }
+ async handleApplyEdit(params) {
+ const lease = this.activeLease;
+ if (!lease)
+ return { applied: false, failureReason: "workspace/applyEdit requires an active workspace mutation" };
+ if (lease.phase !== "idle") {
+ return {
+ applied: false,
+ failureReason: workspaceApplyEditConcurrentFailureReason(lease.phase === "applying" ? "applying" : "settled")
+ };
+ }
+ lease.phase = "applying";
+ lease.applyCompletion = new Promise((resolve6) => {
+ lease.resolveApply = resolve6;
+ });
+ const edit = isRecord4(params) ? params["edit"] : undefined;
+ const record2 = edit === undefined ? { fingerprint: null, result: failure("workspace/applyEdit params.edit is required", 0) } : await this.applyEdit(edit, lease);
+ lease.serverApply = record2;
+ lease.phase = "settled";
+ lease.resolveApply?.();
+ return responseFor(record2.result);
+ }
+ async reconcileRename(leaseToken, edit) {
+ const lease = this.requireActiveLease(leaseToken);
+ if (!lease)
+ return { edit, apply: failure("workspace mutation lease ended before rename reconciliation") };
+ if (lease.phase === "applying")
+ await lease.applyCompletion;
+ if (lease.serverApply)
+ return this.reconcileServerApply(lease.serverApply, edit);
+ lease.phase = "sealed";
+ if (!edit)
+ return { edit, apply: failure("No edit provided") };
+ const applied = await this.applyEdit(edit, lease);
+ return { edit, apply: applied.result };
+ }
+ reconcileServerApply(record2, edit) {
+ if (!edit)
+ return { edit, apply: record2.result };
+ const fingerprint = fingerprintWorkspaceEdit(edit, this.workspaceRoot);
+ if (fingerprint.success && record2.fingerprint !== null && fingerprint.fingerprint === record2.fingerprint) {
+ return { edit, apply: record2.result };
+ }
+ return {
+ edit,
+ apply: failure("rename result conflicts with server-applied workspace edit", 0, record2.result)
+ };
+ }
+ async applyEdit(edit, lease) {
+ const planned = planWorkspaceEdit(edit, this.workspaceRoot);
+ if (!planned.success)
+ return { fingerprint: null, result: planned.result };
+ const versionFailure = this.documents.validateVersions(planned.plan.operations);
+ if (versionFailure) {
+ return {
+ fingerprint: planned.plan.fingerprint,
+ result: failure(versionFailure.message, versionFailure.changeIndex)
+ };
+ }
+ const commit = commitWorkspaceEditPlan(planned.plan, {
+ ...lease.signal === undefined ? {} : { signal: lease.signal },
+ ...this.io === undefined ? {} : { io: this.io }
+ });
+ let result = commit.result;
+ if (commit.delta.operations.length > 0) {
+ try {
+ await this.documents.synchronize(commit.delta);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ result = failure(`document synchronization failed after filesystem commit: ${message}`, undefined, result);
+ }
+ }
+ if (lease.signal?.aborted && !result.lateAbort)
+ result = { ...result, lateAbort: true };
+ return { fingerprint: planned.plan.fingerprint, result };
+ }
+ requireActiveLease(lease) {
+ return this.activeLease?.id === lease.id ? this.activeLease : null;
+ }
+}
+
+// ../lsp-core/src/lsp/client.ts
+var DIAGNOSTICS_FRESHNESS_TIMEOUT_MS = 3000;
+var VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
+
+class LspClient extends LspClientConnection {
+ diagnosticPullErrors = [];
+ documents;
+ workspaceMutations;
+ diagnosticsFreshnessTimeoutMs;
+ constructor(root, server2, options = {}) {
+ super(root, server2, options);
+ this.diagnosticsFreshnessTimeoutMs = options.diagnosticsFreshnessTimeoutMs ?? DIAGNOSTICS_FRESHNESS_TIMEOUT_MS;
+ this.documents = new WorkspaceDocumentState((method, params) => this.sendNotification(method, params), (uri) => this.diagnosticsStore.delete(uri), {
+ versionlessPublishQuiescenceMs: options.versionlessPublishQuiescenceMs ?? VERSIONLESS_PUBLISH_QUIESCENCE_MS
+ });
+ this.workspaceMutations = new WorkspaceMutationController(root, this.documents);
+ this.setWorkspaceApplyEditHandler((params) => this.workspaceMutations.handleApplyEdit(params));
+ }
+ getDiagnosticPullErrors() {
+ return this.diagnosticPullErrors;
+ }
+ async openFile(filePath) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.documents.openFile(absPath);
+ }
+ getOpenDocumentVersion(filePath) {
+ return this.documents.getVersion(this.resolveWorkspacePath(filePath));
+ }
+ getStoredDiagnostics(uri) {
+ return [...this.documents.getStoredDiagnostics(uri)];
+ }
+ setWorkspaceEditIo(io) {
+ this.workspaceMutations.setIo(io);
+ }
+ handlePublishDiagnostics(params) {
+ super.handlePublishDiagnostics(params);
+ this.documents.recordPublishedDiagnostics(params);
+ }
+ async definition(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("textDocument/definition", {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character }
+ }, options);
+ }
+ async references(filePath, line, character, includeDeclaration = true, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("textDocument/references", {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character },
+ context: { includeDeclaration }
+ }, options);
+ }
+ async documentSymbols(filePath, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("textDocument/documentSymbol", {
+ textDocument: { uri: pathToFileURL3(absPath).href }
+ }, options);
+ }
+ async workspaceSymbols(query, signal) {
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("workspace/symbol", { query }, options);
+ }
+ isUnsupportedDiagnosticPullError(error) {
+ if (!(error instanceof Error))
+ return false;
+ const code = "code" in error && typeof error.code === "number" ? error.code : undefined;
+ if (code === -32601)
+ return true;
+ return /unsupported|not supported|method not found|unknown request/i.test(error.message);
+ }
+ freshnessTimeout(absPath) {
+ return {
+ items: [],
+ transientError: {
+ kind: "freshness_timeout",
+ message: `Timed out waiting for fresh diagnostics for ${absPath} within ${this.diagnosticsFreshnessTimeoutMs}ms.`
+ }
+ };
+ }
+ parseDiagnosticPullReport(value) {
+ if (value.kind === "unchanged") {
+ return {
+ type: "unchanged",
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ return {
+ type: "full",
+ diagnostics: value.items ?? [],
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ async diagnostics(filePath, signal) {
+ signal?.throwIfAborted();
+ const absPath = this.resolveWorkspacePath(filePath);
+ const uri = pathToFileURL3(absPath).href;
+ await this.openFile(absPath);
+ const deadlineAt = Date.now() + this.diagnosticsFreshnessTimeoutMs;
+ for (;; ) {
+ signal?.throwIfAborted();
+ const snapshot = this.documents.captureDiagnosticSnapshot(absPath);
+ if (!snapshot)
+ return this.freshnessTimeout(absPath);
+ const push = this.documents.resolvePushDiagnostics(snapshot);
+ if (push.status === "ready")
+ return { items: [...push.diagnostics] };
+ let pushFallbackOnly = !this.isDiagnosticPullSupported();
+ if (!pushFallbackOnly) {
+ const cached = this.documents.getPullCache(snapshot);
+ try {
+ const remainingMs2 = deadlineAt - Date.now();
+ if (remainingMs2 <= 0)
+ return this.freshnessTimeout(absPath);
+ const result = await this.sendRequest("textDocument/diagnostic", {
+ textDocument: { uri },
+ ...cached?.resultId === undefined ? {} : { previousResultId: cached.resultId }
+ }, { timeoutMs: remainingMs2, ...signal === undefined ? {} : { signal } });
+ if (!this.documents.isCurrentSnapshot(snapshot))
+ continue;
+ const report = this.parseDiagnosticPullReport(result);
+ if (report.type === "full") {
+ this.documents.recordPullDiagnostics(snapshot, {
+ kind: "full",
+ diagnostics: report.diagnostics,
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ });
+ return { items: [...report.diagnostics] };
+ }
+ if (cached !== null && cached.documentVersion === snapshot.version && cached.resultId === report.resultId) {
+ return { items: [...cached.diagnostics] };
+ }
+ } catch (error) {
+ if (this.isUnsupportedDiagnosticPullError(error)) {
+ this.setDiagnosticPullSupported(false);
+ pushFallbackOnly = true;
+ } else if (error instanceof LspRequestTimeoutError) {
+ pushFallbackOnly = true;
+ } else {
+ this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ throw error;
+ }
+ }
+ }
+ if (!pushFallbackOnly)
+ continue;
+ const remainingMs = deadlineAt - Date.now();
+ if (remainingMs <= 0)
+ return this.freshnessTimeout(absPath);
+ const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;
+ await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);
+ }
+ }
+ async prepareRename(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("textDocument/prepareRename", {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character }
+ }, options);
+ }
+ async rename(filePath, line, character, newName, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const acquired = this.workspaceMutations.acquire(signal);
+ if (!acquired.success)
+ return { edit: null, apply: acquired.result };
+ const preCommitSignal = createPreCommitAbortSignal(signal, () => this.workspaceMutations.isBeforeCommit(acquired.lease));
+ try {
+ const renameParams = {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character },
+ newName
+ };
+ const edit = preCommitSignal === undefined ? await this.sendRequest("textDocument/rename", renameParams) : await this.sendRequest("textDocument/rename", renameParams, {
+ signal: preCommitSignal.signal
+ });
+ return await this.workspaceMutations.reconcileRename(acquired.lease, edit);
+ } finally {
+ preCommitSignal?.dispose();
+ this.workspaceMutations.release(acquired.lease);
+ }
+ }
+ resolveWorkspacePath(filePath) {
+ return resolve6(this.root, filePath);
+ }
+}
+function waitForDiagnosticsActivity(wait, signal) {
+ if (!signal)
+ return wait;
+ if (signal.aborted)
+ return Promise.reject(abortError2(signal));
+ return new Promise((resolve7, reject) => {
+ const onAbort = () => {
+ signal.removeEventListener("abort", onAbort);
+ reject(abortError2(signal));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ wait.then(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve7();
+ }, (error) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(error);
+ });
+ });
+}
+function createPreCommitAbortSignal(source, isBeforeCommit) {
+ if (!source)
+ return;
+ const controller = new AbortController;
+ const onAbort = () => {
+ if (isBeforeCommit() && !controller.signal.aborted)
+ controller.abort(preCommitAbortReason(source));
+ };
+ if (source.aborted)
+ onAbort();
+ else
+ source.addEventListener("abort", onAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => source.removeEventListener("abort", onAbort)
+ };
+}
+function preCommitAbortReason(source) {
+ const reason = source.reason;
+ if (reason instanceof Error && reason.name !== "AbortError")
+ return reason;
+ return new Error("LSP request cancelled before workspace edit commit");
+}
+function abortError2(signal) {
+ const reason = signal.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "operation cancelled");
+ error.name = "AbortError";
+ return error;
+}
+
+// ../lsp-core/src/lsp/process-signal-cleanup.ts
+function installProcessSignalCleanup(cleanup) {
+ const signals = process.platform === "win32" ? ["SIGINT", "SIGTERM", "SIGBREAK"] : ["SIGINT", "SIGTERM"];
+ const handler = () => {
+ cleanup().catch((error) => {
+ reportBestEffortCleanupError("signal cleanup", error);
+ });
+ };
+ for (const signal of signals) {
+ process.on(signal, handler);
+ }
+ return () => {
+ for (const signal of signals) {
+ process.removeListener(signal, handler);
+ }
+ };
+}
+
+// ../lsp-core/src/lsp/manager.ts
+async function stopClientBestEffort(client) {
+ try {
+ await client.stop();
+ } catch (error) {
+ reportBestEffortCleanupError("client stop", error);
+ }
+}
+function awaitWithSignal(promise, signal) {
+ if (!signal)
+ return promise;
+ return new Promise((resolve7, reject) => {
+ let settled = false;
+ const onAbort = () => {
+ if (settled)
+ return;
+ settled = true;
+ reject(new DOMException("Aborted", "AbortError"));
+ };
+ if (signal.aborted) {
+ onAbort();
+ return;
+ }
+ signal.addEventListener("abort", onAbort, { once: true });
+ promise.then((value) => {
+ if (settled)
+ return;
+ settled = true;
+ signal.removeEventListener("abort", onAbort);
+ resolve7(value);
+ }, (err) => {
+ if (settled)
+ return;
+ settled = true;
+ signal.removeEventListener("abort", onAbort);
+ reject(err);
+ });
+ });
+}
+
+class LspManager {
+ clients = new Map;
+ reaperHandle = null;
+ signalDisposer = null;
+ disposed = false;
+ idleTimeoutMs;
+ initTimeoutMs;
+ reaperIntervalMs;
+ clientFactory;
+ now;
+ constructor(options = {}) {
+ this.idleTimeoutMs = options.idleTimeoutMs ?? IDLE_TIMEOUT_MS;
+ this.initTimeoutMs = options.initTimeoutMs ?? INIT_TIMEOUT_MS;
+ this.reaperIntervalMs = options.reaperIntervalMs ?? REAPER_INTERVAL_MS;
+ this.clientFactory = options.clientFactory ?? ((root, server2) => new LspClient(root, server2));
+ this.now = options.now ?? (() => Date.now());
+ this.startReaper();
+ this.signalDisposer = installProcessSignalCleanup(() => this.stopAll());
+ }
+ startReaper() {
+ if (this.reaperHandle)
+ return;
+ this.reaperHandle = setInterval(() => {
+ this.reapStale();
+ }, this.reaperIntervalMs);
+ if (typeof this.reaperHandle.unref === "function") {
+ this.reaperHandle.unref();
+ }
+ }
+ getKey(root, serverId) {
+ return `${root}::${serverId}`;
+ }
+ reapStale() {
+ const t = this.now();
+ for (const [key, managed] of this.clients) {
+ if (managed.isInitializing && managed.initializingSince !== null && t - managed.initializingSince > this.initTimeoutMs) {
+ stopClientBestEffort(managed.client);
+ this.clients.delete(key);
+ continue;
+ }
+ if (!managed.isInitializing && managed.refCount === 0 && managed.pendingWaiters === 0 && t - managed.lastUsedAt > this.idleTimeoutMs) {
+ stopClientBestEffort(managed.client);
+ this.clients.delete(key);
+ }
+ }
+ }
+ async tryDeleteIfOrphaned(key, managed) {
+ if (managed.refCount === 0 && managed.pendingWaiters === 0 && !managed.isInitializing && this.clients.get(key) === managed) {
+ this.clients.delete(key);
+ await stopClientBestEffort(managed.client);
+ }
+ }
+ async getClient(root, server2, signal) {
+ if (this.disposed) {
+ throw new Error("LspManager has been disposed");
+ }
+ signal?.throwIfAborted();
+ const key = this.getKey(root, server2.id);
+ let managed = this.clients.get(key);
+ if (managed) {
+ const t = this.now();
+ if (managed.isInitializing && managed.initializingSince !== null && t - managed.initializingSince > this.initTimeoutMs) {
+ await stopClientBestEffort(managed.client);
+ this.clients.delete(key);
+ managed = undefined;
+ }
+ }
+ if (managed) {
+ if (managed.initPromise) {
+ managed.pendingWaiters++;
+ try {
+ await awaitWithSignal(managed.initPromise, signal);
+ } catch (err) {
+ managed.pendingWaiters--;
+ await this.tryDeleteIfOrphaned(key, managed);
+ throw err;
+ }
+ managed.pendingWaiters--;
+ }
+ if (signal?.aborted) {
+ await this.tryDeleteIfOrphaned(key, managed);
+ signal.throwIfAborted();
+ }
+ if (!managed.client.isAlive()) {
+ await stopClientBestEffort(managed.client);
+ this.clients.delete(key);
+ return this.getClient(root, server2, signal);
+ }
+ managed.refCount++;
+ managed.lastUsedAt = this.now();
+ return managed.client;
+ }
+ const client = this.clientFactory(root, server2);
+ const initStartedAt = this.now();
+ const initPromise = (async () => {
+ await client.start();
+ await client.initialize();
+ })();
+ const newManaged = {
+ client,
+ refCount: 0,
+ pendingWaiters: 1,
+ lastUsedAt: initStartedAt,
+ initPromise,
+ isInitializing: true,
+ initializingSince: initStartedAt
+ };
+ this.clients.set(key, newManaged);
+ try {
+ await awaitWithSignal(initPromise, signal);
+ } catch (err) {
+ newManaged.pendingWaiters--;
+ if (this.clients.get(key) === newManaged) {
+ this.clients.delete(key);
+ }
+ await stopClientBestEffort(client);
+ throw err;
+ }
+ newManaged.pendingWaiters--;
+ newManaged.isInitializing = false;
+ newManaged.initializingSince = null;
+ newManaged.initPromise = null;
+ if (signal?.aborted) {
+ await this.tryDeleteIfOrphaned(key, newManaged);
+ signal.throwIfAborted();
+ }
+ newManaged.refCount++;
+ newManaged.lastUsedAt = this.now();
+ return client;
+ }
+ releaseClient(root, serverId) {
+ const key = this.getKey(root, serverId);
+ const managed = this.clients.get(key);
+ if (managed && managed.refCount > 0) {
+ managed.refCount--;
+ managed.lastUsedAt = this.now();
+ }
+ }
+ invalidateClient(root, serverId, client) {
+ const key = this.getKey(root, serverId);
+ const managed = this.clients.get(key);
+ if (!managed)
+ return;
+ if (client && managed.client !== client)
+ return;
+ this.clients.delete(key);
+ stopClientBestEffort(managed.client);
+ }
+ warmupClient(root, server2) {
+ if (this.disposed)
+ return;
+ const key = this.getKey(root, server2.id);
+ if (this.clients.has(key))
+ return;
+ const client = this.clientFactory(root, server2);
+ const initStartedAt = this.now();
+ const initPromise = (async () => {
+ await client.start();
+ await client.initialize();
+ })();
+ const managed = {
+ client,
+ refCount: 0,
+ pendingWaiters: 0,
+ lastUsedAt: initStartedAt,
+ initPromise,
+ isInitializing: true,
+ initializingSince: initStartedAt
+ };
+ this.clients.set(key, managed);
+ initPromise.then(() => {
+ managed.isInitializing = false;
+ managed.initializingSince = null;
+ managed.initPromise = null;
+ managed.lastUsedAt = this.now();
+ }, () => {
+ if (this.clients.get(key) === managed) {
+ this.clients.delete(key);
+ }
+ stopClientBestEffort(client);
+ });
+ }
+ isServerInitializing(root, serverId) {
+ const managed = this.clients.get(this.getKey(root, serverId));
+ return managed?.isInitializing ?? false;
+ }
+ getSnapshot() {
+ const snapshots = [];
+ for (const [key, managed] of this.clients) {
+ const [root, serverId] = key.split("::");
+ snapshots.push({
+ root,
+ serverId,
+ refCount: managed.refCount,
+ pendingWaiters: managed.pendingWaiters,
+ lastUsedAt: managed.lastUsedAt,
+ isInitializing: managed.isInitializing,
+ alive: managed.client.isAlive(),
+ command: managed.client.command()
+ });
+ }
+ return snapshots;
+ }
+ hasClient(root, serverId) {
+ return this.clients.has(this.getKey(root, serverId));
+ }
+ clientCount() {
+ return this.clients.size;
+ }
+ async stopAll() {
+ this.disposed = true;
+ if (this.reaperHandle) {
+ clearInterval(this.reaperHandle);
+ this.reaperHandle = null;
+ }
+ if (this.signalDisposer) {
+ this.signalDisposer();
+ this.signalDisposer = null;
+ }
+ const stopPromises = [];
+ for (const managed of this.clients.values()) {
+ stopPromises.push(stopClientBestEffort(managed.client));
+ }
+ this.clients.clear();
+ await Promise.allSettled(stopPromises);
+ }
+}
+var _defaultInstance = null;
+function getLspManager() {
+ if (!_defaultInstance) {
+ _defaultInstance = new LspManager;
+ }
+ return _defaultInstance;
+}
+async function disposeDefaultLspManager() {
+ if (_defaultInstance) {
+ const m = _defaultInstance;
+ _defaultInstance = null;
+ await m.stopAll();
+ }
+}
+
+// ../lsp-core/src/lsp/server-install-state.ts
+import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
+import { dirname as dirname7 } from "node:path";
+function getInstallDecisionsPath() {
+ return lspRequestContext().installDecisionsPath;
+}
+function loadInstallDecisions() {
+ const path2 = getInstallDecisionsPath();
+ if (!existsSync6(path2))
+ return {};
+ try {
+ const parsed = JSON.parse(readFileSync4(path2, "utf8"));
+ return isInstallDecisions(parsed) ? parsed : {};
+ } catch {
+ return {};
+ }
+}
+function loadInstallDecision(serverId) {
+ return loadInstallDecisions()[serverId];
+}
+function recordInstallDecision(serverId, decision, decidedAt = new Date().toISOString()) {
+ const decisions = loadInstallDecisions();
+ decisions[serverId] = { decision, decidedAt };
+ writeInstallDecisions(decisions);
+}
+function isInstallDecision(value) {
+ return value === "declined" || value === "allowed";
+}
+function writeInstallDecisions(decisions) {
+ const path2 = getInstallDecisionsPath();
+ mkdirSync3(dirname7(path2), { recursive: true });
+ const tmpPath = `${path2}.tmp`;
+ writeFileSync2(tmpPath, `${JSON.stringify(decisions, null, 2)}
+`, "utf8");
+ renameSync2(tmpPath, path2);
+}
+function isInstallDecisions(value) {
+ return isRecord5(value) && Object.values(value).every(isInstallDecisionRecord);
+}
+function isInstallDecisionRecord(value) {
+ if (!isRecord5(value))
+ return false;
+ return isInstallDecision(value["decision"]) && typeof value["decidedAt"] === "string";
+}
+function isRecord5(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+// ../lsp-core/src/lsp/config-loader.ts
+import { existsSync as existsSync7, readFileSync as readFileSync5 } from "node:fs";
+
+// ../lsp-core/src/lsp/server-definitions.ts
+var LSP_INSTALL_HINTS = {
+ typescript: "npm install -g typescript-language-server typescript",
+ deno: "Install Deno from https://deno.land",
+ vue: "npm install -g @vue/language-server",
+ eslint: "npm install -g vscode-langservers-extracted",
+ oxlint: "npm install -g oxlint",
+ biome: "npm install -g @biomejs/biome",
+ gopls: "go install golang.org/x/tools/gopls@latest",
+ "ruby-lsp": "gem install ruby-lsp",
+ basedpyright: "pip install basedpyright",
+ pyright: "pip install pyright",
+ ty: "pip install ty",
+ ruff: "pip install ruff",
+ "elixir-ls": "See https://github.com/elixir-lsp/elixir-ls",
+ zls: "See https://github.com/zigtools/zls",
+ csharp: "dotnet tool install -g csharp-ls",
+ fsharp: "dotnet tool install -g fsautocomplete",
+ "sourcekit-lsp": "Included with Xcode or Swift toolchain",
+ rust: "Install rust-analyzer and ensure it is in PATH. If using rustup: rustup component add rust-analyzer. " + "If rust-analyzer exits while loading rust-src: rustup component remove rust-src && rustup component add rust-src.",
+ clangd: "See https://clangd.llvm.org/installation",
+ svelte: "npm install -g svelte-language-server",
+ astro: "npm install -g @astrojs/language-server",
+ "bash-ls": "npm install -g bash-language-server",
+ jdtls: "See https://github.com/eclipse-jdtls/eclipse.jdt.ls",
+ "yaml-ls": "npm install -g yaml-language-server",
+ "lua-ls": "See https://github.com/LuaLS/lua-language-server",
+ php: "npm install -g intelephense",
+ dart: "Included with Dart SDK",
+ "terraform-ls": "See https://github.com/hashicorp/terraform-ls",
+ terraform: "See https://github.com/hashicorp/terraform-ls",
+ prisma: "npm install -g prisma",
+ "ocaml-lsp": "opam install ocaml-lsp-server",
+ texlab: "See https://github.com/latex-lsp/texlab",
+ dockerfile: "npm install -g dockerfile-language-server-nodejs",
+ gleam: "See https://gleam.run/getting-started/installing/",
+ "clojure-lsp": "See https://clojure-lsp.io/installation/",
+ nixd: "nix profile install nixpkgs#nixd",
+ tinymist: "See https://github.com/Myriad-Dreamin/tinymist",
+ "haskell-language-server": "ghcup install hls",
+ bash: "npm install -g bash-language-server",
+ "kotlin-ls": "See https://github.com/Kotlin/kotlin-lsp",
+ julials: `julia -e 'using Pkg; Pkg.add("LanguageServer")'`,
+ razor: "Razor runs through the Roslyn language server (cohosting). " + "Install: dotnet tool install -g roslyn-language-server --prerelease (requires v5.8.0+). See https://github.com/dotnet/razor"
+};
+var BUILTIN_SERVERS = {
+ typescript: {
+ command: ["typescript-language-server", "--stdio"],
+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"]
+ },
+ deno: { command: ["deno", "lsp"], extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"] },
+ vue: { command: ["vue-language-server", "--stdio"], extensions: [".vue"] },
+ eslint: {
+ command: ["vscode-eslint-language-server", "--stdio"],
+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".vue"]
+ },
+ oxlint: {
+ command: ["oxlint", "--lsp"],
+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".vue", ".astro", ".svelte"]
+ },
+ biome: {
+ command: ["biome", "lsp-proxy", "--stdio"],
+ extensions: [
+ ".ts",
+ ".tsx",
+ ".js",
+ ".jsx",
+ ".mjs",
+ ".cjs",
+ ".mts",
+ ".cts",
+ ".json",
+ ".jsonc",
+ ".vue",
+ ".astro",
+ ".svelte",
+ ".css",
+ ".graphql",
+ ".gql",
+ ".html"
+ ]
+ },
+ gopls: { command: ["gopls"], extensions: [".go"] },
+ "ruby-lsp": {
+ command: ["rubocop", "--lsp"],
+ extensions: [".rb", ".rake", ".gemspec", ".ru"]
+ },
+ basedpyright: {
+ command: ["basedpyright-langserver", "--stdio"],
+ extensions: [".py", ".pyi"]
+ },
+ pyright: { command: ["pyright-langserver", "--stdio"], extensions: [".py", ".pyi"] },
+ ty: { command: ["ty", "server"], extensions: [".py", ".pyi"] },
+ ruff: { command: ["ruff", "server"], extensions: [".py", ".pyi"] },
+ "elixir-ls": { command: ["elixir-ls"], extensions: [".ex", ".exs"] },
+ zls: { command: ["zls"], extensions: [".zig", ".zon"] },
+ csharp: { command: ["csharp-ls"], extensions: [".cs"] },
+ fsharp: { command: ["fsautocomplete"], extensions: [".fs", ".fsi", ".fsx", ".fsscript"] },
+ "sourcekit-lsp": { command: ["sourcekit-lsp"], extensions: [".swift", ".m", ".mm"] },
+ rust: { command: ["rust-analyzer"], extensions: [".rs"] },
+ clangd: {
+ command: ["clangd", "--background-index", "--clang-tidy"],
+ extensions: [".c", ".cpp", ".cc", ".cxx", ".c++", ".h", ".hpp", ".hh", ".hxx", ".h++"]
+ },
+ svelte: { command: ["svelteserver", "--stdio"], extensions: [".svelte"] },
+ astro: { command: ["astro-ls", "--stdio"], extensions: [".astro"] },
+ bash: {
+ command: ["bash-language-server", "start"],
+ extensions: [".sh", ".bash", ".zsh", ".ksh"]
+ },
+ "bash-ls": {
+ command: ["bash-language-server", "start"],
+ extensions: [".sh", ".bash", ".zsh", ".ksh"]
+ },
+ jdtls: { command: ["jdtls"], extensions: [".java"] },
+ "yaml-ls": { command: ["yaml-language-server", "--stdio"], extensions: [".yaml", ".yml"] },
+ "lua-ls": { command: ["lua-language-server"], extensions: [".lua"] },
+ php: { command: ["intelephense", "--stdio"], extensions: [".php"] },
+ dart: { command: ["dart", "language-server", "--lsp"], extensions: [".dart"] },
+ terraform: { command: ["terraform-ls", "serve"], extensions: [".tf", ".tfvars"] },
+ "terraform-ls": { command: ["terraform-ls", "serve"], extensions: [".tf", ".tfvars"] },
+ prisma: { command: ["prisma", "language-server"], extensions: [".prisma"] },
+ "ocaml-lsp": { command: ["ocamllsp"], extensions: [".ml", ".mli"] },
+ texlab: { command: ["texlab"], extensions: [".tex", ".bib"] },
+ dockerfile: { command: ["docker-langserver", "--stdio"], extensions: [".dockerfile"] },
+ gleam: { command: ["gleam", "lsp"], extensions: [".gleam"] },
+ "clojure-lsp": {
+ command: ["clojure-lsp", "listen"],
+ extensions: [".clj", ".cljs", ".cljc", ".edn"]
+ },
+ nixd: { command: ["nixd"], extensions: [".nix"] },
+ tinymist: { command: ["tinymist"], extensions: [".typ", ".typc"] },
+ "haskell-language-server": {
+ command: ["haskell-language-server-wrapper", "--lsp"],
+ extensions: [".hs", ".lhs"]
+ },
+ "kotlin-ls": { command: ["kotlin-lsp", "--stdio"], extensions: [".kt", ".kts"] },
+ julials: {
+ command: ["julia", "--startup-file=no", "--history-file=no", "-e", "using LanguageServer; runserver()"],
+ extensions: [".jl"]
+ },
+ razor: {
+ command: ["roslyn-language-server", "--stdio"],
+ extensions: [".razor", ".cshtml"]
+ }
+};
+
+// ../lsp-core/src/lsp/config-loader.ts
+function getProjectConfigPaths() {
+ return lspRequestContext().projectConfigPaths;
+}
+function getUserConfigPath() {
+ return lspRequestContext().userConfigPath;
+}
+function loadJsonFile(path2) {
+ if (!existsSync7(path2))
+ return null;
+ try {
+ const parsed = JSON.parse(readFileSync5(path2, "utf-8"));
+ return isConfigJson(parsed) ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+function loadAllConfigs() {
+ const configs = new Map;
+ const project = loadFirstJsonFile(getProjectConfigPaths());
+ if (project)
+ configs.set("project", project);
+ const user = loadJsonFile(getUserConfigPath());
+ if (user)
+ configs.set("user", user);
+ return configs;
+}
+function loadFirstJsonFile(paths) {
+ for (const path2 of paths) {
+ const config = loadJsonFile(path2);
+ if (config)
+ return config;
+ }
+ return null;
+}
+function getMergedServers() {
+ const configs = loadAllConfigs();
+ const servers = [];
+ const disabled = new Set;
+ const seen = new Set;
+ const sources = ["project", "user"];
+ for (const source of sources) {
+ const config = configs.get(source);
+ if (!config?.lsp)
+ continue;
+ for (const [id, rawEntry] of Object.entries(config.lsp)) {
+ const entry = parseLspEntry(rawEntry);
+ if (!entry)
+ continue;
+ if (entry.disabled) {
+ disabled.add(id);
+ continue;
+ }
+ if (seen.has(id))
+ continue;
+ const server2 = createServerFromEntry(id, entry, source);
+ if (!server2)
+ continue;
+ servers.push(server2);
+ seen.add(id);
+ }
+ }
+ for (const [id, config] of Object.entries(BUILTIN_SERVERS)) {
+ if (disabled.has(id) || seen.has(id))
+ continue;
+ servers.push({
+ id,
+ command: config.command,
+ extensions: config.extensions,
+ priority: -100,
+ source: "builtin"
+ });
+ }
+ return servers.sort((a, b) => {
+ if (a.source !== b.source) {
+ const order = {
+ project: 0,
+ user: 1,
+ builtin: 2
+ };
+ return order[a.source] - order[b.source];
+ }
+ return b.priority - a.priority;
+ });
+}
+function createServerFromEntry(id, entry, source) {
+ const builtin = BUILTIN_SERVERS[id];
+ if (source === "project") {
+ if (!builtin)
+ return null;
+ const server3 = createServer({
+ id,
+ command: builtin.command,
+ extensions: entry.extensions ?? builtin.extensions,
+ priority: entry.priority ?? 0,
+ source
+ });
+ if (entry.initialization !== undefined) {
+ server3.initialization = entry.initialization;
+ }
+ return server3;
+ }
+ if (entry.command && entry.extensions) {
+ const server3 = createServer({
+ id,
+ command: entry.command,
+ extensions: entry.extensions,
+ priority: entry.priority ?? 0,
+ source
+ });
+ applyOptionalServerFields(server3, entry);
+ return server3;
+ }
+ if (!builtin)
+ return null;
+ const server2 = createServer({
+ id,
+ command: entry.command ?? builtin.command,
+ extensions: entry.extensions ?? builtin.extensions,
+ priority: entry.priority ?? 0,
+ source
+ });
+ applyOptionalServerFields(server2, entry);
+ return server2;
+}
+function createServer(input) {
+ const server2 = {
+ id: input.id,
+ command: input.command,
+ extensions: input.extensions,
+ priority: input.priority,
+ source: input.source
+ };
+ if (input.env !== undefined) {
+ server2.env = input.env;
+ }
+ if (input.initialization !== undefined) {
+ server2.initialization = input.initialization;
+ }
+ return server2;
+}
+function applyOptionalServerFields(server2, entry) {
+ if (entry.env !== undefined) {
+ server2.env = entry.env;
+ }
+ if (entry.initialization !== undefined) {
+ server2.initialization = entry.initialization;
+ }
+}
+function isConfigJson(value) {
+ if (!isRecord6(value))
+ return false;
+ const lsp = value["lsp"];
+ return lsp === undefined || isRecord6(lsp);
+}
+function parseLspEntry(value) {
+ return isLspEntry(value) ? value : null;
+}
+function isLspEntry(value) {
+ if (!isRecord6(value))
+ return false;
+ const disabled = value["disabled"];
+ const command = value["command"];
+ const extensions = value["extensions"];
+ const priority = value["priority"];
+ const env = value["env"];
+ const initialization = value["initialization"];
+ return (disabled === undefined || typeof disabled === "boolean") && (command === undefined || isStringArray(command)) && (extensions === undefined || isStringArray(extensions)) && (priority === undefined || typeof priority === "number") && (env === undefined || isStringRecord(env)) && (initialization === undefined || isRecord6(initialization));
+}
+function isStringArray(value) {
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
+}
+function isStringRecord(value) {
+ return isRecord6(value) && Object.values(value).every((item) => typeof item === "string");
+}
+function isRecord6(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function getDisabledServerIds() {
+ const configs = loadAllConfigs();
+ const disabled = new Set;
+ for (const config of configs.values()) {
+ if (!config.lsp)
+ continue;
+ for (const [id, rawEntry] of Object.entries(config.lsp)) {
+ const entry = parseLspEntry(rawEntry);
+ if (!entry)
+ continue;
+ if (entry.disabled)
+ disabled.add(id);
+ }
+ }
+ return disabled;
+}
+
+// ../lsp-core/src/lsp/server-installation.ts
+import { existsSync as existsSync8 } from "node:fs";
+import { delimiter as delimiter3, join as join3 } from "node:path";
+function isServerInstalled(command, _workingDirectory) {
+ if (command.length === 0)
+ return false;
+ const [cmd] = command;
+ if (!cmd)
+ return false;
+ if (cmd.includes("/") || cmd.includes("\\")) {
+ if (existsSync8(cmd))
+ return true;
+ }
+ const isWindows = process.platform === "win32";
+ let exts = [""];
+ if (isWindows) {
+ const pathExt = process.env["PATHEXT"] ?? "";
+ if (pathExt) {
+ const systemExts = pathExt.split(";").filter(Boolean);
+ exts = [...new Set([...exts, ...systemExts, ".exe", ".cmd", ".bat", ".ps1"])];
+ } else {
+ exts = ["", ".exe", ".cmd", ".bat", ".ps1"];
+ }
+ }
+ let pathEnv = process.env["PATH"] ?? "";
+ if (isWindows && !pathEnv) {
+ pathEnv = process.env["Path"] ?? "";
+ }
+ const paths = pathEnv.split(delimiter3);
+ for (const p of paths) {
+ for (const suffix of exts) {
+ if (existsSync8(join3(p, cmd + suffix))) {
+ return true;
+ }
+ }
+ }
+ if (cmd === "node")
+ return true;
+ return false;
+}
+
+// ../lsp-core/src/lsp/server-resolution.ts
+function findServerForExtension(ext) {
+ const servers = getMergedServers();
+ for (const server2 of servers) {
+ if (server2.extensions.includes(ext) && isServerInstalled(server2.command)) {
+ const resolvedServer = {
+ id: server2.id,
+ command: server2.command,
+ extensions: server2.extensions,
+ priority: server2.priority
+ };
+ if (server2.env !== undefined) {
+ return {
+ status: "found",
+ server: {
+ ...resolvedServer,
+ env: server2.env,
+ ...server2.initialization === undefined ? {} : { initialization: server2.initialization }
+ }
+ };
+ }
+ return {
+ status: "found",
+ server: {
+ ...resolvedServer,
+ ...server2.initialization === undefined ? {} : { initialization: server2.initialization }
+ }
+ };
+ }
+ }
+ for (const server2 of servers) {
+ if (server2.extensions.includes(ext)) {
+ const installHint = LSP_INSTALL_HINTS[server2.id] ?? `Install '${server2.command[0]}' and ensure it's in your PATH`;
+ return {
+ status: "not_installed",
+ server: {
+ id: server2.id,
+ command: server2.command,
+ extensions: server2.extensions
+ },
+ installHint
+ };
+ }
+ }
+ const availableServers = [...new Set(servers.map((s) => s.id))];
+ return {
+ status: "not_configured",
+ extension: ext,
+ availableServers
+ };
+}
+function getAllServers() {
+ const servers = getMergedServers();
+ const disabled = getDisabledServerIds();
+ const result = [];
+ const seen = new Set;
+ for (const server2 of servers) {
+ if (seen.has(server2.id))
+ continue;
+ result.push({
+ id: server2.id,
+ installed: isServerInstalled(server2.command),
+ extensions: server2.extensions,
+ disabled: false,
+ source: server2.source,
+ priority: server2.priority
+ });
+ seen.add(server2.id);
+ }
+ for (const id of disabled) {
+ if (seen.has(id))
+ continue;
+ const builtin = BUILTIN_SERVERS[id];
+ result.push({
+ id,
+ installed: builtin ? isServerInstalled(builtin.command) : false,
+ extensions: builtin?.extensions ?? [],
+ disabled: true,
+ source: "disabled",
+ priority: 0
+ });
+ }
+ return result;
+}
+
+// ../lsp-core/src/lsp/client-wrapper.ts
+var WORKSPACE_MARKERS = [".git", "package.json", "pyproject.toml", "Cargo.toml", "go.mod", "pom.xml", "build.gradle"];
+function isDirectoryPath(filePath) {
+ try {
+ return statSync4(filePath).isDirectory();
+ } catch {
+ return false;
+ }
+}
+function findWorkspaceRoot(filePath) {
+ const abs = resolvePathInsideContext(filePath);
+ let dir = abs;
+ if (!isDirectoryPath(dir)) {
+ dir = dirname8(dir);
+ }
+ let prevDir = "";
+ while (dir !== prevDir) {
+ for (const marker of WORKSPACE_MARKERS) {
+ if (existsSync9(join4(dir, marker))) {
+ return dir;
+ }
+ }
+ prevDir = dir;
+ dir = dirname8(dir);
+ }
+ return dirname8(abs);
+}
+function resolvePathInsideContext(filePath) {
+ const cwd = contextCwd();
+ const abs = resolve7(cwd, filePath);
+ const canonical = canonicalizeExistingOrNearestAncestor(abs);
+ if (!isPathInside(cwd, canonical)) {
+ throw new LspInvalidPathError(`LSP file path must be inside request cwd: ${filePath}`);
+ }
+ return canonical;
+}
+function formatServerLookupError(result) {
+ if (result.status === "not_installed") {
+ return formatNotInstalled(result);
+ }
+ const context = lspRequestContext();
+ const firstProjectConfigPath = context.projectConfigPaths[0] ?? "<project lsp config>";
+ return [
+ `No LSP server configured for extension: ${result.extension}`,
+ "",
+ `Available servers: ${result.availableServers.slice(0, 10).join(", ")}${result.availableServers.length > 10 ? "..." : ""}`,
+ "",
+ `Configure a custom server in '${firstProjectConfigPath}' or '${context.userConfigPath}':`,
+ " {",
+ ' "lsp": {',
+ ' "my-server": {',
+ ' "command": ["my-lsp", "--stdio"],',
+ ` "extensions": ["${result.extension}"]`,
+ " }",
+ " }",
+ " }"
+ ].join(`
+`);
+}
+function formatNotInstalled(result) {
+ const { server: server2, installHint } = result;
+ const extensions = server2.extensions.join(", ");
+ const decision = loadInstallDecision(server2.id)?.decision;
+ const context = lspRequestContext();
+ if (decision === "declined") {
+ return `LSP server '${server2.id}' (${extensions}) is NOT INSTALLED; user previously declined installation — proceed without LSP.`;
+ }
+ const header = [
+ `LSP server '${server2.id}' for ${extensions} is NOT INSTALLED.`,
+ "",
+ `Command not found: ${server2.command[0]}`,
+ ""
+ ];
+ if (decision === "allowed") {
+ return [
+ ...header,
+ "The user has pre-authorized LSP installation. Run the install command, then retry this tool:",
+ ` ${installHint}`
+ ].join(`
+`);
+ }
+ if (!context.capabilities.installDecisionTool) {
+ return [
+ ...header,
+ "To install, run:",
+ ` ${installHint}`,
+ "",
+ "ACTION REQUIRED — ASK THE USER whether to install this LSP server.",
+ "Install-decision recording is unavailable in this harness; proceed without LSP if the user declines."
+ ].join(`
+`);
+ }
+ return [
+ ...header,
+ "To install, run:",
+ ` ${installHint}`,
+ "",
+ "ACTION REQUIRED — ASK THE USER whether to install this LSP server.",
+ "- If the user agrees: run the install command above, then retry this tool.",
+ "- If the user declines, OR has NOT explicitly asked for LSP installation:",
+ ` call lsp_install_decision { server_id: "${server2.id}", decision: "declined" },`,
+ ` which writes to ${context.installDecisionsPath},`,
+ " then ignore this message and proceed WITHOUT LSP."
+ ].join(`
+`);
+}
+var READ_ONLY_RETRY_TOOLS = new Set([
+ "diagnostics",
+ "definition",
+ "references",
+ "documentSymbols",
+ "workspaceSymbols",
+ "prepareRename"
+]);
+async function withLspClient(filePath, fn, toolName, options = {}) {
+ const absPath = resolvePathInsideContext(filePath);
+ if (isDirectoryPath(absPath)) {
+ throw new LspInvalidPathError("Directory paths are not supported by this LSP tool. " + "Use lsp.diagnostics with a directory path for directory diagnostics.");
+ }
+ const ext = effectiveExtension(absPath);
+ const result = findServerForExtension(ext);
+ if (result.status !== "found") {
+ throw new LspServerLookupError(formatServerLookupError(result), result);
+ }
+ const server2 = result.server;
+ const root = findWorkspaceRoot(absPath);
+ const manager = options.manager ?? getLspManager();
+ const acquireAndCall = async (allowRetry) => {
+ const client = await manager.getClient(root, server2, options.signal);
+ try {
+ return await fn(client, root);
+ } catch (err) {
+ if (allowRetry && READ_ONLY_RETRY_TOOLS.has(toolName) && isLspDeadConnectionError(err)) {
+ manager.invalidateClient(root, server2.id, client);
+ return acquireAndCall(false);
+ }
+ if (err instanceof LspRequestTimeoutError) {
+ if (manager.isServerInitializing(root, server2.id)) {
+ throw new LspServerInitializingError(err);
+ }
+ }
+ throw err;
+ } finally {
+ manager.releaseClient(root, server2.id);
+ }
+ };
+ return acquireAndCall(true);
+}
+
+// ../lsp-core/src/lsp/directory-diagnostics.ts
+import { existsSync as existsSync10, lstatSync as lstatSync5, readdirSync as readdirSync3 } from "node:fs";
+import { join as join5, resolve as resolve8 } from "node:path";
+
+// ../lsp-core/src/lsp/formatters.ts
+import { fileURLToPath as fileURLToPath3 } from "node:url";
+var DIAGNOSTIC_SEVERITY_FILTERS = {
+ error: 1,
+ warning: 2,
+ information: 3,
+ hint: 4
+};
+function uriToPath(uri) {
+ return fileURLToPath3(uri);
+}
+function formatLocation(loc) {
+ if ("targetUri" in loc) {
+ const uri2 = uriToPath(loc.targetUri);
+ const line2 = loc.targetRange.start.line + 1;
+ const char2 = loc.targetRange.start.character;
+ return `${uri2}:${line2}:${char2}`;
+ }
+ const uri = uriToPath(loc.uri);
+ const line = loc.range.start.line + 1;
+ const char = loc.range.start.character;
+ return `${uri}:${line}:${char}`;
+}
+function formatSymbolKind(kind) {
+ return SYMBOL_KIND_MAP[kind] ?? `Unknown(${kind})`;
+}
+function formatSeverity(severity) {
+ if (!severity)
+ return "unknown";
+ return SEVERITY_MAP[severity] ?? `unknown(${severity})`;
+}
+function formatDocumentSymbol(symbol, indent = 0) {
+ const prefix = " ".repeat(indent);
+ const kind = formatSymbolKind(symbol.kind);
+ const line = symbol.range.start.line + 1;
+ let result = `${prefix}${symbol.name} (${kind}) - line ${line}`;
+ if (symbol.children && symbol.children.length > 0) {
+ for (const child of symbol.children) {
+ result += `
+${formatDocumentSymbol(child, indent + 1)}`;
+ }
+ }
+ return result;
+}
+function formatSymbolInfo(symbol) {
+ const kind = formatSymbolKind(symbol.kind);
+ const loc = formatLocation(symbol.location);
+ const container = symbol.containerName ? ` (in ${symbol.containerName})` : "";
+ return `${symbol.name} (${kind})${container} - ${loc}`;
+}
+function formatDiagnostic(diag) {
+ const severity = formatSeverity(diag.severity);
+ const line = diag.range.start.line + 1;
+ const char = diag.range.start.character;
+ const source = diag.source ? `[${diag.source}]` : "";
+ const code = diag.code ? ` (${diag.code})` : "";
+ return `${severity}${source}${code} at ${line}:${char}: ${diag.message}`;
+}
+function filterDiagnosticsBySeverity(diagnostics, severityFilter) {
+ if (!severityFilter || severityFilter === "all") {
+ return diagnostics;
+ }
+ const targetSeverity = DIAGNOSTIC_SEVERITY_FILTERS[severityFilter];
+ return diagnostics.filter((d) => d.severity === targetSeverity);
+}
+function formatPrepareRenameResult(result) {
+ if (!result)
+ return "Cannot rename at this position";
+ if ("defaultBehavior" in result) {
+ return result.defaultBehavior ? "Rename supported (using default behavior)" : "Cannot rename at this position";
+ }
+ if ("range" in result && result.range) {
+ const startLine = result.range.start.line + 1;
+ const startChar = result.range.start.character;
+ const endLine = result.range.end.line + 1;
+ const endChar = result.range.end.character;
+ const placeholder = result.placeholder ? ` (current: "${result.placeholder}")` : "";
+ return `Rename available at ${startLine}:${startChar}-${endLine}:${endChar}${placeholder}`;
+ }
+ if ("start" in result && "end" in result) {
+ const startLine = result.start.line + 1;
+ const startChar = result.start.character;
+ const endLine = result.end.line + 1;
+ const endChar = result.end.character;
+ return `Rename available at ${startLine}:${startChar}-${endLine}:${endChar}`;
+ }
+ return "Cannot rename at this position";
+}
+function formatApplyResult(result) {
+ const lines = [];
+ if (result.success) {
+ lines.push(`Applied ${result.totalEdits} edit(s) to ${result.filesModified.length} file(s):`);
+ for (const file of result.filesModified) {
+ lines.push(` - ${file}`);
+ }
+ if (result.lateAbort) {
+ lines.push("Cancellation arrived after the filesystem commit began; the committed edit completed.");
+ }
+ } else {
+ lines.push("Failed to apply some changes:");
+ for (const err of result.errors) {
+ lines.push(` Error: ${err}`);
+ }
+ if (result.filesModified.length > 0) {
+ lines.push(`Successfully modified: ${result.filesModified.join(", ")}`);
+ }
+ }
+ return lines.join(`
+`);
+}
+
+// ../lsp-core/src/lsp/directory-diagnostics.ts
+var SKIP_DIRECTORIES = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
+var DIRECTORY_DIAGNOSTICS_MAX_CONCURRENCY = 4;
+function collectFilesWithExtension(dir, extension, maxFiles) {
+ const files = [];
+ function walk(currentDir) {
+ if (files.length >= maxFiles)
+ return;
+ let entries = [];
+ try {
+ entries = readdirSync3(currentDir);
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (files.length >= maxFiles)
+ return;
+ const fullPath = join5(currentDir, entry);
+ let stat;
+ try {
+ stat = lstatSync5(fullPath);
+ } catch {
+ continue;
+ }
+ if (!stat || stat.isSymbolicLink())
+ continue;
+ if (stat.isDirectory()) {
+ if (!SKIP_DIRECTORIES.has(entry)) {
+ walk(fullPath);
+ }
+ } else if (stat.isFile() && effectiveExtension(fullPath) === extension) {
+ files.push(fullPath);
+ }
+ }
+ }
+ walk(dir);
+ return files;
+}
+async function aggregateDiagnosticsForDirectory(directory, extension, severity, maxFiles = DEFAULT_MAX_DIRECTORY_FILES, options = {}) {
+ if (!extension.startsWith(".")) {
+ throw new LspInvalidPathError(`Extension must start with a dot (e.g., ".ts", not "${extension}"). Use ".${extension}" instead.`);
+ }
+ const absDir = resolve8(options.workspaceRoot ?? contextCwd(), directory);
+ if (!existsSync10(absDir)) {
+ throw new LspInvalidPathError(`Directory does not exist: ${absDir}`);
+ }
+ const serverResult = options.server === undefined ? findServerForExtension(extension) : { status: "found", server: options.server };
+ if (serverResult.status !== "found") {
+ throw new LspServerLookupError(formatServerLookupError(serverResult));
+ }
+ const server2 = serverResult.server;
+ const allFiles = (options.listFiles ?? collectFilesWithExtension)(absDir, extension, maxFiles + 1);
+ const wasCapped = allFiles.length > maxFiles;
+ const filesToProcess = allFiles.slice(0, maxFiles);
+ if (filesToProcess.length === 0) {
+ const output = [
+ `Directory: ${absDir}`,
+ `Extension: ${extension}`,
+ "Files scanned: 0",
+ `No files found with extension "${extension}".`
+ ].join(`
+`);
+ return { output, totalDiagnostics: 0, fileFailures: [] };
+ }
+ const root = options.workspaceRoot ?? findWorkspaceRoot(absDir);
+ const manager = options.manager ?? getLspManager();
+ const allDiagnostics = [];
+ const fileErrors = [];
+ const maxConcurrency = Math.max(1, options.maxConcurrency ?? DIRECTORY_DIAGNOSTICS_MAX_CONCURRENCY);
+ options.signal?.throwIfAborted();
+ const client = await manager.getClient(root, server2);
+ try {
+ let nextIndex = 0;
+ const workers = Array.from({ length: Math.min(maxConcurrency, filesToProcess.length) }, async () => {
+ for (;; ) {
+ if (options.signal?.aborted)
+ return;
+ const file = filesToProcess[nextIndex];
+ nextIndex += 1;
+ if (file === undefined)
+ return;
+ try {
+ const result = await client.diagnostics(file, options.signal);
+ const filtered = filterDiagnosticsBySeverity(result.items, severity);
+ allDiagnostics.push(...filtered.map((diagnostic) => ({
+ filePath: file,
+ diagnostic
+ })));
+ } catch (e) {
+ fileErrors.push({
+ file,
+ error: e instanceof Error ? e.message : String(e)
+ });
+ }
+ }
+ });
+ await Promise.all(workers);
+ } finally {
+ manager.releaseClient(root, server2.id);
+ }
+ const displayDiagnostics = allDiagnostics.slice(0, DEFAULT_MAX_DIAGNOSTICS);
+ const wasDiagCapped = allDiagnostics.length > DEFAULT_MAX_DIAGNOSTICS;
+ const lines = [
+ `Directory: ${absDir}`,
+ `Extension: ${extension}`,
+ `Files scanned: ${filesToProcess.length}${wasCapped ? ` (capped at ${maxFiles})` : ""}`,
+ `Files with errors: ${fileErrors.length}`,
+ `Total diagnostics: ${allDiagnostics.length}`
+ ];
+ if (fileErrors.length > 0) {
+ lines.push("", "File processing errors:");
+ for (const { file, error } of fileErrors) {
+ lines.push(` ${file}: ${error}`);
+ }
+ }
+ if (displayDiagnostics.length > 0) {
+ lines.push("");
+ for (const { filePath, diagnostic } of displayDiagnostics) {
+ lines.push(`${filePath}: ${formatDiagnostic(diagnostic)}`);
+ }
+ if (wasDiagCapped) {
+ lines.push("", `... (${allDiagnostics.length - DEFAULT_MAX_DIAGNOSTICS} more diagnostics not shown)`);
+ }
+ }
+ return { output: lines.join(`
+`), totalDiagnostics: allDiagnostics.length, fileFailures: fileErrors };
+}
+
+// ../lsp-core/src/lsp/infer-extension.ts
+import { lstatSync as lstatSync6, readdirSync as readdirSync4 } from "node:fs";
+import { join as join6 } from "node:path";
+var SKIP_DIRECTORIES2 = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
+var MAX_SCAN_ENTRIES = 500;
+function inferExtensionFromDirectory(directory) {
+ const extensionCounts = new Map;
+ let scanned = 0;
+ function walk(dir) {
+ if (scanned >= MAX_SCAN_ENTRIES)
+ return;
+ let entries;
+ try {
+ entries = readdirSync4(dir);
+ } catch {
+ return;
+ }
+ for (const entry of entries) {
+ if (scanned >= MAX_SCAN_ENTRIES)
+ return;
+ const fullPath = join6(dir, entry);
+ let stat;
+ try {
+ stat = lstatSync6(fullPath);
+ } catch {
+ continue;
+ }
+ if (stat.isSymbolicLink())
+ continue;
+ scanned++;
+ if (stat.isDirectory()) {
+ if (!SKIP_DIRECTORIES2.has(entry)) {
+ walk(fullPath);
+ }
+ } else if (stat.isFile()) {
+ const ext = effectiveExtension(fullPath);
+ if (ext && ext in EXT_TO_LANG) {
+ extensionCounts.set(ext, (extensionCounts.get(ext) ?? 0) + 1);
+ }
+ }
+ }
+ }
+ walk(directory);
+ if (extensionCounts.size === 0)
+ return null;
+ let maxExt = "";
+ let maxCount = 0;
+ for (const [ext, count] of extensionCounts) {
+ if (count > maxCount) {
+ maxCount = count;
+ maxExt = ext;
+ }
+ }
+ return maxExt || null;
+}
+
+// ../lsp-core/src/lsp/utils.ts
+var RUST_SRC_REPAIR_MESSAGE = [
+ "rust-analyzer exited while loading Rust standard library sources.",
+ "",
+ "Repair rust-src for the active toolchain:",
+ " rustup component remove rust-src",
+ " rustup component add rust-src"
+];
+function errorMessage(error) {
+ return error instanceof Error ? error.message : String(error);
+}
+function formatKnownLspStartupFailure(error) {
+ if (!(error instanceof LspProcessExitedError))
+ return null;
+ if (error.serverId !== "rust")
+ return null;
+ const details = error.stderrTail ?? error.message;
+ const lowerDetails = details.toLowerCase();
+ const isRustSrcFailure = lowerDetails.includes("rust-src") && (lowerDetails.includes("failed to install component") || lowerDetails.includes("detected conflict") || lowerDetails.includes("can't load standard library") || lowerDetails.includes("try installing") || lowerDetails.includes("sysroot"));
+ if (!isRustSrcFailure)
+ return null;
+ return [...RUST_SRC_REPAIR_MESSAGE, "", "Original stderr tail:", details].join(`
+`);
+}
+function handleMissingDependencyError(error) {
+ const knownStartupFailure = formatKnownLspStartupFailure(error);
+ if (knownStartupFailure)
+ return knownStartupFailure;
+ const message = errorMessage(error);
+ return message.includes("NOT INSTALLED") || message.includes("No LSP server configured") ? message : null;
+}
+// ../lsp-core/src/missing-dependency-result.ts
+function missingDependencyResult(error, details) {
+ const message = handleMissingDependencyError(error);
+ if (!message)
+ return null;
+ return {
+ content: [{ type: "text", text: message }],
+ details: {
+ ...details,
+ error: message,
+ errorKind: "missing_dependency",
+ ...availabilityDetails(error)
+ }
+ };
+}
+function availabilityDetails(error) {
+ const availability = missingDependencyAvailability(error);
+ return availability === null ? {} : { availability };
+}
+function missingDependencyAvailability(error) {
+ if (!(error instanceof LspServerLookupError) || error.lookup === undefined)
+ return null;
+ const context = lspRequestContext();
+ switch (error.lookup.status) {
+ case "not_configured":
+ return {
+ kind: "not_configured",
+ extension: error.lookup.extension,
+ availableServers: [...error.lookup.availableServers],
+ projectConfigPaths: [...context.projectConfigPaths],
+ userConfigPath: context.userConfigPath,
+ installDecisionTool: context.capabilities.installDecisionTool
+ };
+ case "not_installed":
+ return {
+ kind: "not_installed",
+ serverId: error.lookup.server.id,
+ command: [...error.lookup.server.command],
+ extensions: [...error.lookup.server.extensions],
+ installHint: error.lookup.installHint,
+ installDecisionTool: context.capabilities.installDecisionTool,
+ installDecisionsPath: context.installDecisionsPath
+ };
+ default: {
+ const exhaustive = error.lookup;
+ return exhaustive;
+ }
+ }
+}
+
+// ../lsp-core/src/tools/parameters.ts
+function isRecord7(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function requireString(params, key) {
+ const value = params[key];
+ if (typeof value !== "string" || value.length === 0) {
+ throw new Error(`Missing required string parameter '${key}'`);
+ }
+ return value;
+}
+function optionalString(params, key) {
+ const value = params[key];
+ return typeof value === "string" ? value : undefined;
+}
+function requireNumber(params, key) {
+ const value = params[key];
+ if (typeof value !== "number" || !Number.isFinite(value)) {
+ throw new Error(`Missing required number parameter '${key}'`);
+ }
+ return value;
+}
+function optionalNumber(params, key) {
+ const value = params[key];
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
+}
+function optionalBoolean(params, key) {
+ const value = params[key];
+ return typeof value === "boolean" ? value : undefined;
+}
+function severityFilter(params) {
+ const value = params["severity"];
+ if (value === "error" || value === "warning" || value === "information" || value === "hint" || value === "all") {
+ return value;
+ }
+ return "all";
+}
+function clientOptions(signal) {
+ return signal === undefined ? {} : { signal };
+}
+
+// ../lsp-core/src/tools/result.ts
+function text(text2, details, isError = false) {
+ return { content: [{ type: "text", text: text2 }], details, isError };
+}
+
+// ../lsp-core/src/tools/diagnostics.ts
+function asDiagnosticArray(result) {
+ if (!result)
+ return [];
+ if (Array.isArray(result))
+ return result;
+ return result.items ?? [];
+}
+async function executeLspDiagnostics(params, signal) {
+ const filePath = requireString(params, "filePath");
+ const severity = severityFilter(params);
+ try {
+ const absPath = resolvePathInsideContext(filePath);
+ if (isDirectoryPath(absPath)) {
+ const extension = inferExtensionFromDirectory(absPath);
+ if (!extension) {
+ const message = `No supported source files found in directory: ${absPath}`;
+ const details3 = {
+ filePath,
+ severity,
+ mode: "directory",
+ diagnostics: [],
+ totalDiagnostics: 0,
+ truncated: false,
+ error: message,
+ errorKind: "no_files"
+ };
+ return text(message, details3);
+ }
+ const output2 = await aggregateDiagnosticsForDirectory(absPath, extension, severity, undefined, signal === undefined ? {} : { signal });
+ const details2 = {
+ filePath,
+ severity,
+ mode: "directory",
+ diagnostics: [],
+ totalDiagnostics: output2.totalDiagnostics,
+ truncated: false,
+ fileFailures: [...output2.fileFailures]
+ };
+ return text(output2.output, details2);
+ }
+ const result = await withLspClient(filePath, async (client) => client.diagnostics(filePath, signal), "diagnostics", clientOptions(signal));
+ if (result.transientError) {
+ const message = result.transientError.message;
+ const details2 = {
+ filePath,
+ severity,
+ mode: "file",
+ diagnostics: [],
+ totalDiagnostics: 0,
+ truncated: false,
+ error: message,
+ errorKind: result.transientError.kind
+ };
+ return text(message, details2, true);
+ }
+ const diagnostics = filterDiagnosticsBySeverity(asDiagnosticArray(result), severity);
+ const total = diagnostics.length;
+ const truncated = total > DEFAULT_MAX_DIAGNOSTICS;
+ const limited = truncated ? diagnostics.slice(0, DEFAULT_MAX_DIAGNOSTICS) : diagnostics;
+ const output = total === 0 ? "No diagnostics found" : [
+ ...truncated ? [`Found ${total} diagnostics (showing first ${DEFAULT_MAX_DIAGNOSTICS}):`] : [],
+ ...limited.map(formatDiagnostic)
+ ].join(`
+`);
+ const details = {
+ filePath,
+ severity,
+ mode: "file",
+ diagnostics: diagnostics.map((diagnostic) => ({ file: absPath, diagnostic })),
+ totalDiagnostics: total,
+ truncated
+ };
+ return text(output, details);
+ } catch (error) {
+ const missingDependency = missingDependencyResult(error, {
+ filePath,
+ severity,
+ mode: "file",
+ diagnostics: [],
+ totalDiagnostics: 0,
+ truncated: false
+ });
+ if (missingDependency)
+ return missingDependency;
+ throw error;
+ }
+}
+// ../lsp-core/src/tools/install-decision.ts
+async function executeLspInstallDecision(params) {
+ const serverId = requireString(params, "server_id");
+ const decision = params["decision"];
+ if (!isInstallDecision(decision)) {
+ return text(`Invalid decision '${String(decision)}'. Expected "declined" or "allowed".`, { serverId, errorKind: "invalid_decision" }, true);
+ }
+ const serverIds = [...new Set(getMergedServers().map((server2) => server2.id))];
+ if (!serverIds.includes(serverId)) {
+ const preview = serverIds.slice(0, 20).join(", ");
+ return text(`Unknown LSP server '${serverId}'. Known servers: ${preview}${serverIds.length > 20 ? "..." : ""}`, { serverId, errorKind: "unknown_server" }, true);
+ }
+ recordInstallDecision(serverId, decision);
+ return text(`Recorded install decision for '${serverId}': ${decision}. ${decisionFollowUp(decision)}`, {
+ serverId,
+ decision
+ });
+}
+function decisionFollowUp(decision) {
+ return decision === "declined" ? "Future LSP lookups for this server stay quiet; proceed without LSP." : "Future LSP lookups keep install instructions without asking the user.";
+}
+
+// ../lsp-core/src/tools/navigation.ts
+async function executeLspGotoDefinition(params, signal) {
+ const filePath = requireString(params, "filePath");
+ const line = requireNumber(params, "line");
+ const character = requireNumber(params, "character");
+ try {
+ const result = await withLspClient(filePath, async (client) => client.definition(filePath, line, character, signal), "definition", clientOptions(signal));
+ const locations = !result ? [] : Array.isArray(result) ? result : [result];
+ const details = { filePath, line, character, locations };
+ if (locations.length === 0)
+ return text("No definition found", details);
+ return text(locations.map(formatLocation).join(`
+`), details);
+ } catch (error) {
+ const missingDependency = missingDependencyResult(error, {
+ filePath,
+ line,
+ character,
+ locations: []
+ });
+ if (missingDependency)
+ return missingDependency;
+ throw error;
+ }
+}
+async function executeLspFindReferences(params, signal) {
+ const filePath = requireString(params, "filePath");
+ const line = requireNumber(params, "line");
+ const character = requireNumber(params, "character");
+ const includeDeclaration = optionalBoolean(params, "includeDeclaration") ?? true;
+ try {
+ const result = await withLspClient(filePath, async (client) => client.references(filePath, line, character, includeDeclaration, signal), "references", clientOptions(signal));
+ const references = Array.isArray(result) ? result : [];
+ const total = references.length;
+ const truncated = total > DEFAULT_MAX_REFERENCES;
+ const limited = truncated ? references.slice(0, DEFAULT_MAX_REFERENCES) : references;
+ const details = {
+ filePath,
+ line,
+ character,
+ references,
+ totalReferences: total,
+ truncated
+ };
+ if (total === 0)
+ return text("No references found", details);
+ const output = [
+ ...truncated ? [`Found ${total} references (showing first ${DEFAULT_MAX_REFERENCES}):`] : [],
+ ...limited.map(formatLocation)
+ ].join(`
+`);
+ return text(output, details);
+ } catch (error) {
+ const missingDependency = missingDependencyResult(error, {
+ filePath,
+ line,
+ character,
+ references: [],
+ totalReferences: 0,
+ truncated: false
+ });
+ if (missingDependency)
+ return missingDependency;
+ throw error;
+ }
+}
+
+// ../lsp-core/src/tools/rename.ts
+async function executeLspPrepareRename(params, signal) {
+ const filePath = requireString(params, "filePath");
+ const line = requireNumber(params, "line");
+ const character = requireNumber(params, "character");
+ try {
+ const result = await withLspClient(filePath, async (client) => client.prepareRename(filePath, line, character, signal), "prepareRename", clientOptions(signal));
+ const details = { filePath, line, character, result };
+ return text(formatPrepareRenameResult(result), details);
+ } catch (error) {
+ const missingDependency = missingDependencyResult(error, {
+ filePath,
+ line,
+ character,
+ result: null
+ });
+ if (missingDependency)
+ return missingDependency;
+ throw error;
+ }
+}
+async function executeLspRename(params, signal) {
+ const filePath = requireString(params, "filePath");
+ const line = requireNumber(params, "line");
+ const character = requireNumber(params, "character");
+ const newName = requireString(params, "newName");
+ try {
+ const result = await withLspClient(filePath, async (client) => client.rename(filePath, line, character, newName, signal), "rename", clientOptions(signal));
+ const details = { filePath, line, character, newName, apply: result.apply, edit: result.edit };
+ return text(formatApplyResult(result.apply), details, !result.apply.success);
+ } catch (error) {
+ const missingDependency = missingDependencyResult(error, {
+ filePath,
+ line,
+ character,
+ newName,
+ apply: null,
+ edit: null
+ });
+ if (missingDependency)
+ return missingDependency;
+ throw error;
+ }
+}
+
+// ../lsp-core/src/tools/schema.ts
+function objectSchema(properties, required = []) {
+ return {
+ type: "object",
+ properties,
+ required
+ };
+}
+
+// ../lsp-core/src/tools/status.ts
+async function executeLspStatus() {
+ const servers = getAllServers();
+ const snapshots = getLspManager().getSnapshot();
+ const installed = servers.filter((server2) => server2.installed && !server2.disabled);
+ const configuredLines = servers.map((server2) => {
+ const state = server2.disabled ? "disabled" : server2.installed ? "installed" : "missing";
+ return `- ${server2.id}: ${state}; source=${server2.source}; extensions=${server2.extensions.join(", ")}`;
+ });
+ const activeLines = snapshots.map((snapshot) => {
+ const state = snapshot.alive ? snapshot.isInitializing ? "initializing" : "alive" : "dead";
+ return `- ${snapshot.serverId}: ${state}; root=${snapshot.root}; refs=${snapshot.refCount}`;
+ });
+ const lines = [
+ `Configured LSP servers: ${servers.length}`,
+ `Installed LSP servers: ${installed.length}`,
+ "",
+ ...configuredLines,
+ "",
+ `Active LSP clients: ${snapshots.length}`,
+ ...activeLines
+ ];
+ return text(lines.join(`
+`), { servers, snapshots });
+}
+
+// ../lsp-core/src/tools/symbols.ts
+function isDocumentSymbol(symbol) {
+ return "range" in symbol;
+}
+async function executeLspSymbols(params, signal) {
+ const filePath = requireString(params, "filePath");
+ const rawScope = optionalString(params, "scope") ?? "document";
+ const scope = rawScope === "workspace" ? "workspace" : "document";
+ const limit = Math.min(optionalNumber(params, "limit") ?? DEFAULT_MAX_SYMBOLS, DEFAULT_MAX_SYMBOLS);
+ try {
+ if (scope === "workspace") {
+ const query = optionalString(params, "query");
+ if (!query) {
+ const message = "Error: 'query' is required for workspace scope";
+ return text(message, {
+ filePath,
+ scope,
+ symbols: [],
+ totalSymbols: 0,
+ truncated: false,
+ error: message,
+ errorKind: "missing_query"
+ });
+ }
+ const symbols2 = await withLspClient(filePath, async (client) => client.workspaceSymbols(query, signal), "workspaceSymbols", clientOptions(signal));
+ return formatSymbolsResult(filePath, scope, symbols2, limit, query);
+ }
+ const symbols = await withLspClient(filePath, async (client) => client.documentSymbols(filePath, signal), "documentSymbols", clientOptions(signal));
+ return formatSymbolsResult(filePath, scope, symbols, limit);
+ } catch (error) {
+ const query = optionalString(params, "query");
+ const missingDependency = missingDependencyResult(error, {
+ filePath,
+ scope,
+ symbols: [],
+ totalSymbols: 0,
+ truncated: false,
+ ...query === undefined ? {} : { query }
+ });
+ if (missingDependency)
+ return missingDependency;
+ throw error;
+ }
+}
+function formatSymbolsResult(filePath, scope, symbols, limit, query) {
+ const total = symbols.length;
+ const truncated = total > limit;
+ const limited = truncated ? symbols.slice(0, limit) : symbols;
+ const details = {
+ filePath,
+ scope,
+ symbols,
+ totalSymbols: total,
+ truncated,
+ ...query === undefined ? {} : { query }
+ };
+ if (total === 0)
+ return text("No symbols found", details);
+ const lines = [];
+ if (truncated)
+ lines.push(`Found ${total} symbols (showing first ${limit}):`);
+ const documentSymbols = limited.filter(isDocumentSymbol);
+ if (documentSymbols.length === limited.length) {
+ lines.push(...documentSymbols.map((symbol) => formatDocumentSymbol(symbol)));
+ } else {
+ lines.push(...limited.filter((symbol) => !isDocumentSymbol(symbol)).map(formatSymbolInfo));
+ }
+ return text(lines.join(`
+`), details);
+}
+
+// ../lsp-core/src/tools/definitions.ts
+var LSP_MCP_TOOLS = [
+ {
+ name: "status",
+ aliases: ["lsp_status"],
+ title: "LSP Status",
+ description: "List configured and active LSP servers without starting a new language server.",
+ inputSchema: objectSchema({}),
+ execute: executeLspStatus
+ },
+ {
+ name: "diagnostics",
+ aliases: ["lsp_diagnostics"],
+ title: "LSP Diagnostics",
+ description: "Get errors, warnings, and hints for a source file or directory.",
+ inputSchema: objectSchema({
+ filePath: { type: "string", description: "File or directory path to check." },
+ severity: {
+ type: "string",
+ enum: ["error", "warning", "information", "hint", "all"],
+ description: "Severity filter. Defaults to all."
+ }
+ }, ["filePath"]),
+ execute: executeLspDiagnostics
+ },
+ {
+ name: "goto_definition",
+ aliases: ["lsp_goto_definition"],
+ title: "LSP Goto Definition",
+ description: "Find where a symbol is defined.",
+ inputSchema: objectSchema({
+ filePath: { type: "string", description: "Source file containing the symbol." },
+ line: { type: "number", description: "1-based line number." },
+ character: { type: "number", description: "0-based column." }
+ }, ["filePath", "line", "character"]),
+ execute: executeLspGotoDefinition
+ },
+ {
+ name: "find_references",
+ aliases: ["lsp_find_references"],
+ title: "LSP Find References",
+ description: "Find references of a symbol across the workspace.",
+ inputSchema: objectSchema({
+ filePath: { type: "string", description: "Source file containing the symbol." },
+ line: { type: "number", description: "1-based line number." },
+ character: { type: "number", description: "0-based column." },
+ includeDeclaration: { type: "boolean", description: "Include the declaration. Defaults to true." }
+ }, ["filePath", "line", "character"]),
+ execute: executeLspFindReferences
+ },
+ {
+ name: "symbols",
+ aliases: ["lsp_symbols"],
+ title: "LSP Symbols",
+ description: "List document symbols or search workspace symbols.",
+ inputSchema: objectSchema({
+ filePath: { type: "string", description: "File path used as LSP context." },
+ scope: {
+ type: "string",
+ enum: ["document", "workspace"],
+ description: "Use document for file outline or workspace for project-wide search."
+ },
+ query: { type: "string", description: "Workspace symbol query." },
+ limit: { type: "number", description: "Maximum number of symbols to return." }
+ }, ["filePath", "scope"]),
+ execute: executeLspSymbols
+ },
+ {
+ name: "prepare_rename",
+ aliases: ["lsp_prepare_rename"],
+ title: "LSP Prepare Rename",
+ description: "Check whether a symbol can be renamed at a position.",
+ inputSchema: objectSchema({
+ filePath: { type: "string", description: "Source file path." },
+ line: { type: "number", description: "1-based line number." },
+ character: { type: "number", description: "0-based column." }
+ }, ["filePath", "line", "character"]),
+ execute: executeLspPrepareRename
+ },
+ {
+ name: "rename",
+ aliases: ["lsp_rename"],
+ title: "LSP Rename",
+ description: "Rename a symbol across the workspace and apply the returned workspace edit.",
+ inputSchema: objectSchema({
+ filePath: { type: "string", description: "Source file path." },
+ line: { type: "number", description: "1-based line number." },
+ character: { type: "number", description: "0-based column." },
+ newName: { type: "string", description: "New symbol name." }
+ }, ["filePath", "line", "character", "newName"]),
+ execute: executeLspRename
+ },
+ {
+ name: "install_decision",
+ aliases: ["lsp_install_decision"],
+ title: "LSP Install Decision",
+ description: "Record whether the user allowed or declined installing a missing LSP server. Record 'declined' when the user declines, or has not explicitly asked for LSP installation, to silence future prompts.",
+ inputSchema: objectSchema({
+ server_id: {
+ type: "string",
+ description: "The LSP server id from the not-installed message (e.g. 'rust')."
+ },
+ decision: {
+ type: "string",
+ enum: ["declined", "allowed"],
+ description: "'declined' silences future prompts; 'allowed' pre-authorizes installation."
+ }
+ }, ["server_id", "decision"]),
+ execute: executeLspInstallDecision
+ }
+];
+// ../lsp-core/src/tools/runtime.ts
+async function executeLspTool(name, params, signal) {
+ const tool = LSP_MCP_TOOLS.find((candidate) => matchesToolName(candidate, name));
+ if (!tool)
+ throw new Error(`Unknown LSP tool: ${name}`);
+ return tool.execute(params, signal);
+}
+function matchesToolName(tool, name) {
+ return tool.name === name || (tool.aliases?.includes(name) ?? false);
+}
+function coerceToolArguments(value) {
+ return isRecord7(value) ? value : {};
+}
+// ../lsp-core/src/mcp.ts
+var SERVER_NAME = "lsp";
+var SERVER_VERSION = "0.1.0";
+async function handleLspMcpRequest(input, options = {}) {
+ if (!isPlainRecord(input)) {
+ return errorResponse(null, -32600, "Invalid Request");
+ }
+ const id = jsonRpcId2(input["id"]);
+ const method = input["method"];
+ if (method === "notifications/initialized")
+ return;
+ if (method === "ping")
+ return successResponse(id, {});
+ if (method === "initialize") {
+ const protocolVersion = requestedProtocolVersion(input["params"]);
+ return successResponse(id, {
+ capabilities: { tools: { listChanged: false } },
+ serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
+ protocolVersion
+ });
+ }
+ if (method === "tools/list") {
+ return successResponse(id, { tools: LSP_MCP_TOOLS.map(describeTool) });
+ }
+ if (method === "tools/call") {
+ return handleToolCall(id, input["params"], options.signal);
+ }
+ return errorResponse(id, -32601, `Method not found: ${String(method)}`);
+}
+async function handleToolCall(id, params, signal) {
+ if (!isPlainRecord(params) || typeof params["name"] !== "string") {
+ return errorResponse(id, -32602, "tools/call requires params.name");
+ }
+ try {
+ const result = await executeLspTool(params["name"], coerceToolArguments(params["arguments"]), signal);
+ return successResponse(id, {
+ content: result.content,
+ isError: result.isError ?? false,
+ details: result.details
+ });
+ } catch (error) {
+ if (!(error instanceof Error)) {
+ throw error;
+ }
+ return successResponse(id, {
+ content: [{ type: "text", text: error.message }],
+ isError: true
+ });
+ }
+}
+function describeTool(tool) {
+ return {
+ name: tool.name,
+ title: tool.title,
+ description: tool.description,
+ inputSchema: tool.inputSchema
+ };
+}
+function requestedProtocolVersion(params) {
+ if (!isPlainRecord(params) || typeof params["protocolVersion"] !== "string")
+ return "2024-11-05";
+ return params["protocolVersion"];
+}
+
+// src/request-routing.ts
+var CONTEXT_KEY = "_context";
+
+class InvalidDaemonRequestError extends Error {
+ name = "InvalidDaemonRequestError";
+}
+function extractRequestContext(raw) {
+ if (!isPlainRecord(raw) || raw["method"] !== "tools/call")
+ return { input: raw, context: undefined };
+ const params = raw["params"];
+ if (!isPlainRecord(params))
+ throw new InvalidDaemonRequestError("Daemon tools/call params must be an object.");
+ const args = params["arguments"];
+ if (!isPlainRecord(args))
+ throw new InvalidDaemonRequestError("Daemon tools/call arguments must be an object.");
+ if (!Object.hasOwn(args, CONTEXT_KEY)) {
+ throw new InvalidDaemonRequestError("Daemon tools/call arguments must include _context.");
+ }
+ const context = parseContext(args[CONTEXT_KEY]);
+ const cleanedArgs = { ...args };
+ delete cleanedArgs[CONTEXT_KEY];
+ const cleaned = { ...raw, params: { ...params, arguments: cleanedArgs } };
+ return { input: cleaned, context };
+}
+function handleDaemonMessage(raw, state) {
+ const authenticated = authenticateMessage(raw, state.token);
+ if ("error" in authenticated)
+ return Promise.resolve(authenticated);
+ if (authenticated.method === "omo/ping") {
+ return Promise.resolve({
+ jsonrpc: "2.0",
+ id: authenticated.id,
+ result: { protocolVersion: OMO_DAEMON_PROTOCOL_VERSION, ...state.owner }
+ });
+ }
+ if (authenticated.method === "$/cancelRequest") {
+ const targetId = cancellationTargetId(authenticated.input);
+ if (targetId !== undefined)
+ state.activeRequests?.get(String(targetId))?.abort();
+ return Promise.resolve(undefined);
+ }
+ let routed;
+ try {
+ routed = extractRequestContext(authenticated.input);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "invalid daemon request";
+ return Promise.resolve({
+ jsonrpc: "2.0",
+ id: authenticated.id,
+ error: { code: -32602, message, data: { code: "invalid_daemon_request" } }
+ });
+ }
+ const { input, context } = routed;
+ const key = routeRequestKey(authenticated.id);
+ if (key === undefined || !state.activeRequests) {
+ if (context)
+ return runWithRequestContext(context, () => handleLspMcpRequest(input));
+ return handleLspMcpRequest(input);
+ }
+ const controller = new AbortController;
+ state.activeRequests.set(key, controller);
+ const options = { signal: controller.signal };
+ const run = context ? runWithRequestContext(context, () => handleLspMcpRequest(input, options)) : handleLspMcpRequest(input, options);
+ return run.finally(() => {
+ if (state.activeRequests?.get(key) === controller)
+ state.activeRequests.delete(key);
+ });
+}
+function routeRequestKey(id) {
+ return typeof id === "string" || typeof id === "number" ? String(id) : undefined;
+}
+function cancellationTargetId(input) {
+ const params = input["params"];
+ if (!isPlainRecord(params))
+ return;
+ const id = params["id"];
+ return typeof id === "string" || typeof id === "number" ? id : undefined;
+}
+function parseContext(value) {
+ if (!isPlainRecord(value))
+ throw new InvalidDaemonRequestError("LSP request _context must be an object.");
+ return parseLspRequestContext(value);
+}
+
+// src/daemon-client.ts
+var DEFAULT_REQUEST_TIMEOUT_MS = 30000;
+var nextProxyRequestId = 1;
+
+class DaemonRequestError extends Error {
+ requestWritten;
+ constructor(message, requestWritten) {
+ super(message);
+ this.name = "DaemonRequestError";
+ this.requestWritten = requestWritten;
+ }
+}
+
+class DaemonAuthenticationRejectedError extends DaemonRequestError {
+ constructor() {
+ super("daemon authentication failed before dispatch", true);
+ this.name = "DaemonAuthenticationRejectedError";
+ }
+}
+
+class DaemonRequestCancelledError extends DaemonRequestError {
+ constructor(requestWritten) {
+ super("daemon request cancelled", requestWritten);
+ this.name = "DaemonRequestCancelledError";
+ }
+}
+async function callToolViaDaemon(name, args, options) {
+ const context = requireContext(options.context);
+ const paths = options.paths ?? daemonPaths();
+ const ensure = options.ensure ?? ensureDaemonRunning;
+ const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
+ const requestArgs = withContext(args, context);
+ let lastError;
+ let authRefreshUsed = false;
+ for (let attempt = 0;attempt < 3; attempt += 1) {
+ try {
+ await ensure(paths);
+ const token = readAuthToken(paths);
+ if (!token)
+ throw new DaemonRequestError("daemon auth token missing", false);
+ const sendOptions = options.signal === undefined ? { timeoutMs } : { timeoutMs, signal: options.signal };
+ return await sendToolCall(paths, token, name, requestArgs, sendOptions);
+ } catch (error) {
+ lastError = error;
+ if (error instanceof DaemonAuthenticationRejectedError && !authRefreshUsed) {
+ authRefreshUsed = true;
+ continue;
+ }
+ if (error instanceof DaemonRequestCancelledError)
+ break;
+ if (error instanceof DaemonRequestError && (error.requestWritten || !isRetryableTool(name)))
+ break;
+ }
+ }
+ return daemonUnreachableResult(paths, lastError);
+}
+function callDiagnosticsViaDaemon(filePath, options) {
+ return callToolViaDaemon("diagnostics", { filePath, severity: "error" }, options);
+}
+function currentRequestContext(env = process.env) {
+ const cwd = process.cwd();
+ const home = env["HOME"] ?? homedir3();
+ return parseLspRequestContext({
+ cwd,
+ projectConfigPaths: [join7(cwd, ".codex", "lsp-client.json")],
+ userConfigPath: join7(home, ".codex", "lsp-client.json"),
+ installDecisionsPath: join7(home, ".codex", "lsp-install-decisions.json"),
+ capabilities: { installDecisionTool: true }
+ });
+}
+function requireContext(context) {
+ if (!context)
+ throw new DaemonRequestError("daemon tool context is required", false);
+ return parseLspRequestContext(context);
+}
+function withContext(args, context) {
+ return { ...args, [CONTEXT_KEY]: context };
+}
+function daemonUnreachableResult(paths, error) {
+ const text2 = [
+ `LSP daemon unreachable: ${errorText(error)}.`,
+ "The MCP server is a thin proxy and never runs language servers in-process.",
+ `Socket: ${paths.socket}`,
+ `Logs: ${paths.log}`,
+ "The daemon is auto-started on demand and will be retried on the next request."
+ ].join(`
+`);
+ return { content: [{ type: "text", text: text2 }], isError: true };
+}
+function sendToolCall(paths, token, name, args, options) {
+ return new Promise((resolve9, reject) => {
+ const socket = connect2(paths.socket);
+ const requestId = allocateProxyRequestId();
+ let settled = false;
+ let requestWritten = false;
+ let cancelAfterWrite = false;
+ const cancelPayload = () => encodeJsonLine({
+ jsonrpc: "2.0",
+ method: "$/cancelRequest",
+ params: { _omo: authEnvelope(token), id: requestId }
+ });
+ const finish = (run) => {
+ if (settled)
+ return;
+ settled = true;
+ clearTimeout(timer);
+ options.signal?.removeEventListener("abort", onAbort);
+ destroyAfterCancel();
+ run();
+ };
+ const sendCancel = () => {
+ if (!requestWritten) {
+ cancelAfterWrite = true;
+ return;
+ }
+ if (!socket.writable)
+ return;
+ socket.write(cancelPayload());
+ };
+ const destroyAfterCancel = () => {
+ socket.destroy();
+ };
+ const onAbort = () => {
+ sendCancel();
+ finish(() => reject(new DaemonRequestCancelledError(requestWritten)));
+ };
+ const timer = setTimeout(() => {
+ sendCancel();
+ finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten)));
+ }, options.timeoutMs);
+ timer.unref();
+ if (options.signal?.aborted) {
+ onAbort();
+ return;
+ }
+ options.signal?.addEventListener("abort", onAbort, { once: true });
+ const decoder = createLineDecoder((message) => {
+ if (isAuthErrorResponse(message)) {
+ finish(() => reject(new DaemonAuthenticationRejectedError));
+ return;
+ }
+ const result = toToolResult(message, requestId);
+ if (result)
+ finish(() => resolve9(result));
+ else
+ finish(() => reject(new DaemonRequestError("invalid daemon response", requestWritten)));
+ });
+ socket.once("connect", () => {
+ const payload = encodeJsonLine({
+ jsonrpc: "2.0",
+ id: requestId,
+ method: "tools/call",
+ params: { _omo: authEnvelope(token), name, arguments: args }
+ });
+ socket.write(payload, () => {
+ requestWritten = true;
+ if (cancelAfterWrite && socket.writable)
+ socket.write(cancelPayload());
+ });
+ });
+ socket.on("data", (chunk) => decoder.push(chunk));
+ socket.once("error", (error) => finish(() => reject(new DaemonRequestError(error.message, requestWritten))));
+ socket.once("close", () => finish(() => reject(new DaemonRequestError("daemon connection closed", requestWritten))));
+ });
+}
+function toToolResult(message, requestId) {
+ if (!isPlainRecord(message) || message["id"] !== requestId)
+ return null;
+ const result = message["result"];
+ if (!isPlainRecord(result) || !Array.isArray(result["content"]))
+ return null;
+ return {
+ content: result["content"],
+ isError: result["isError"] === true,
+ details: result["details"]
+ };
+}
+function allocateProxyRequestId() {
+ const id = nextProxyRequestId;
+ nextProxyRequestId += 1;
+ if (nextProxyRequestId > Number.MAX_SAFE_INTEGER)
+ nextProxyRequestId = 1;
+ return id;
+}
+function isRetryableTool(name) {
+ return name !== "rename" && name !== "lsp_rename";
+}
+function errorText(error) {
+ return error instanceof Error ? error.message : String(error);
+}
+
+// src/client.ts
+import { statSync as statSync5 } from "node:fs";
+import { isAbsolute as isAbsolute4 } from "node:path";
+var OMO_LSP_DAEMON_DIR2 = "OMO_LSP_DAEMON_DIR";
+var OMO_LSP_DAEMON_CLI2 = "OMO_LSP_DAEMON_CLI";
+var OMO_LSP_DAEMON_VERSION2 = "OMO_LSP_DAEMON_VERSION";
+var DAEMON_VERSION_PATTERN2 = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
+
+class InvalidRuntimeOverrideError2 extends Error {
+ code = "invalid_runtime_override";
+ reason;
+ constructor(reason, message) {
+ super(message);
+ this.name = "InvalidRuntimeOverrideError";
+ this.reason = reason;
+ }
+}
+function validateDaemonVersion2(version) {
+ if (!DAEMON_VERSION_PATTERN2.test(version)) {
+ throw new Error("LSP daemon version must match [A-Za-z0-9][A-Za-z0-9._+-]{0,127}");
+ }
+ return version;
+}
+function resolveDaemonRuntime2(env, defaults) {
+ const cliOverride = env[OMO_LSP_DAEMON_CLI2];
+ const versionOverride = env[OMO_LSP_DAEMON_VERSION2];
+ const hasCliOverride = cliOverride !== undefined;
+ const hasVersionOverride = versionOverride !== undefined;
+ if (hasCliOverride !== hasVersionOverride) {
+ throw new InvalidRuntimeOverrideError2("paired_values_required", `${OMO_LSP_DAEMON_CLI2} and ${OMO_LSP_DAEMON_VERSION2} must be set together`);
+ }
+ if (!hasCliOverride || !hasVersionOverride) {
+ if (!isAbsolute4(defaults.cliPath)) {
+ throw new InvalidRuntimeOverrideError2("packaged_cli_must_be_absolute", "Packaged LSP daemon CLI path must be absolute");
+ }
+ return { cliPath: defaults.cliPath, version: validateDaemonVersion2(defaults.version) };
+ }
+ if (!isAbsolute4(cliOverride)) {
+ throw new InvalidRuntimeOverrideError2("cli_must_be_absolute", `${OMO_LSP_DAEMON_CLI2} must be an absolute path to an existing regular file`);
+ }
+ const stat = statSync5(cliOverride, { throwIfNoEntry: false });
+ if (!stat) {
+ throw new InvalidRuntimeOverrideError2("cli_not_found", `${OMO_LSP_DAEMON_CLI2} points to a missing file`);
+ }
+ if (!stat.isFile()) {
+ throw new InvalidRuntimeOverrideError2("cli_not_file", `${OMO_LSP_DAEMON_CLI2} must point to a regular file`);
+ }
+ return { cliPath: cliOverride, version: validateDaemonVersion2(versionOverride) };
+}
+function callToolViaDaemon2(name, args, options) {
+ return callToolViaDaemon(name, args, options);
+}
+function callDiagnosticsViaDaemon2(filePath, options) {
+ return callDiagnosticsViaDaemon(filePath, options);
+}
+function currentRequestContext2(env = process.env) {
+ return currentRequestContext(env);
+}
+export {
+ validateDaemonVersion2 as validateDaemonVersion,
+ resolveDaemonRuntime2 as resolveDaemonRuntime,
+ currentRequestContext2 as currentRequestContext,
+ callToolViaDaemon2 as callToolViaDaemon,
+ callDiagnosticsViaDaemon2 as callDiagnosticsViaDaemon,
+ OMO_LSP_DAEMON_VERSION2 as OMO_LSP_DAEMON_VERSION,
+ OMO_LSP_DAEMON_DIR2 as OMO_LSP_DAEMON_DIR,
+ OMO_LSP_DAEMON_CLI2 as OMO_LSP_DAEMON_CLI,
+ InvalidRuntimeOverrideError2 as InvalidRuntimeOverrideError
+};
diff --git a/plugins/omo/components/lsp-daemon/dist/daemon-client.d.ts b/plugins/omo/components/lsp-daemon/dist/daemon-client.d.ts
index 8710ac1f..af1e0582 100644
--- a/plugins/omo/components/lsp-daemon/dist/daemon-client.d.ts
+++ b/plugins/omo/components/lsp-daemon/dist/daemon-client.d.ts
@@ -1,19 +1,24 @@
import type { ToolExecutionResult } from "@oh-my-opencode/lsp-core/tools";
+import { type LspRequestContext } from "@oh-my-opencode/lsp-core/request-context";
import { type DaemonPaths } from "./paths.js";
export declare class DaemonRequestError extends Error {
readonly requestWritten: boolean;
constructor(message: string, requestWritten: boolean);
}
-export interface DaemonToolContext {
- cwd?: string;
- env?: Record<string, string>;
+export declare class DaemonAuthenticationRejectedError extends DaemonRequestError {
+ constructor();
}
+export declare class DaemonRequestCancelledError extends DaemonRequestError {
+ constructor(requestWritten: boolean);
+}
+export type DaemonToolContext = LspRequestContext;
export interface CallToolOptions {
- context?: DaemonToolContext;
+ context: DaemonToolContext;
paths?: DaemonPaths;
requestTimeoutMs?: number;
+ signal?: AbortSignal;
ensure?: (paths: DaemonPaths) => Promise<void>;
}
-export declare function callToolViaDaemon(name: string, args: Record<string, unknown>, options?: CallToolOptions): Promise<ToolExecutionResult>;
-export declare function callDiagnosticsViaDaemon(filePath: string, options?: CallToolOptions): Promise<ToolExecutionResult>;
+export declare function callToolViaDaemon(name: string, args: Record<string, unknown>, options: CallToolOptions): Promise<ToolExecutionResult>;
+export declare function callDiagnosticsViaDaemon(filePath: string, options: CallToolOptions): Promise<ToolExecutionResult>;
export declare function currentRequestContext(env?: NodeJS.ProcessEnv): DaemonToolContext;
diff --git a/plugins/omo/components/lsp-daemon/dist/daemon-client.js b/plugins/omo/components/lsp-daemon/dist/daemon-client.js
index fbc885f3..f9ce012e 100644
--- a/plugins/omo/components/lsp-daemon/dist/daemon-client.js
+++ b/plugins/omo/components/lsp-daemon/dist/daemon-client.js
@@ -1,11 +1,15 @@
import { connect } from "node:net";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { parseLspRequestContext } from "@oh-my-opencode/lsp-core/request-context";
import { isPlainRecord } from "@oh-my-opencode/mcp-stdio-core/record";
import { ensureDaemonRunning } from "./ensure-daemon.js";
+import { authEnvelope, isAuthErrorResponse, readAuthToken } from "./ipc-protocol.js";
import { daemonPaths } from "./paths.js";
import { CONTEXT_KEY } from "./request-routing.js";
import { createLineDecoder, encodeJsonLine } from "./socket-jsonrpc.js";
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
-const REQUEST_ID = 1;
+let nextProxyRequestId = 1;
export class DaemonRequestError extends Error {
constructor(message, requestWritten) {
super(message);
@@ -13,45 +17,69 @@ export class DaemonRequestError extends Error {
this.requestWritten = requestWritten;
}
}
-export async function callToolViaDaemon(name, args, options = {}) {
+export class DaemonAuthenticationRejectedError extends DaemonRequestError {
+ constructor() {
+ super("daemon authentication failed before dispatch", true);
+ this.name = "DaemonAuthenticationRejectedError";
+ }
+}
+export class DaemonRequestCancelledError extends DaemonRequestError {
+ constructor(requestWritten) {
+ super("daemon request cancelled", requestWritten);
+ this.name = "DaemonRequestCancelledError";
+ }
+}
+export async function callToolViaDaemon(name, args, options) {
+ const context = requireContext(options.context);
const paths = options.paths ?? daemonPaths();
const ensure = options.ensure ?? ensureDaemonRunning;
const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
- const requestArgs = withContext(args, options.context);
+ const requestArgs = withContext(args, context);
let lastError;
- for (let attempt = 0; attempt < 2; attempt += 1) {
+ let authRefreshUsed = false;
+ for (let attempt = 0; attempt < 3; attempt += 1) {
try {
await ensure(paths);
- return await sendToolCall(paths.socket, name, requestArgs, timeoutMs);
+ const token = readAuthToken(paths);
+ if (!token)
+ throw new DaemonRequestError("daemon auth token missing", false);
+ const sendOptions = options.signal === undefined ? { timeoutMs } : { timeoutMs, signal: options.signal };
+ return await sendToolCall(paths, token, name, requestArgs, sendOptions);
}
catch (error) {
lastError = error;
- if (error instanceof DaemonRequestError && error.requestWritten)
+ if (error instanceof DaemonAuthenticationRejectedError && !authRefreshUsed) {
+ authRefreshUsed = true;
+ continue;
+ }
+ if (error instanceof DaemonRequestCancelledError)
+ break;
+ if (error instanceof DaemonRequestError && (error.requestWritten || !isRetryableTool(name)))
break;
}
}
return daemonUnreachableResult(paths, lastError);
}
-export function callDiagnosticsViaDaemon(filePath, options = {}) {
+export function callDiagnosticsViaDaemon(filePath, options) {
return callToolViaDaemon("diagnostics", { filePath, severity: "error" }, options);
}
-const FORWARDED_ENV_KEYS = [
- "LSP_TOOLS_MCP_PROJECT_CONFIG",
- "LSP_TOOLS_MCP_USER_CONFIG",
- "LSP_TOOLS_MCP_INSTALL_DECISIONS",
-];
export function currentRequestContext(env = process.env) {
- const forwarded = {};
- for (const key of FORWARDED_ENV_KEYS) {
- const value = env[key];
- if (value !== undefined)
- forwarded[key] = value;
- }
- return { cwd: process.cwd(), env: forwarded };
+ const cwd = process.cwd();
+ const home = env["HOME"] ?? homedir();
+ return parseLspRequestContext({
+ cwd,
+ projectConfigPaths: [join(cwd, ".codex", "lsp-client.json")],
+ userConfigPath: join(home, ".codex", "lsp-client.json"),
+ installDecisionsPath: join(home, ".codex", "lsp-install-decisions.json"),
+ capabilities: { installDecisionTool: true },
+ });
+}
+function requireContext(context) {
+ if (!context)
+ throw new DaemonRequestError("daemon tool context is required", false);
+ return parseLspRequestContext(context);
}
function withContext(args, context) {
- if (!context || (context.cwd === undefined && context.env === undefined))
- return args;
return { ...args, [CONTEXT_KEY]: context };
}
function daemonUnreachableResult(paths, error) {
@@ -64,39 +92,84 @@ function daemonUnreachableResult(paths, error) {
].join("\n");
return { content: [{ type: "text", text }], isError: true };
}
-function sendToolCall(socketPath, name, args, timeoutMs) {
+function sendToolCall(paths, token, name, args, options) {
return new Promise((resolve, reject) => {
- const socket = connect(socketPath);
+ const socket = connect(paths.socket);
+ const requestId = allocateProxyRequestId();
let settled = false;
let requestWritten = false;
+ let cancelAfterWrite = false;
+ const cancelPayload = () => encodeJsonLine({
+ jsonrpc: "2.0",
+ method: "$/cancelRequest",
+ params: { _omo: authEnvelope(token), id: requestId },
+ });
const finish = (run) => {
if (settled)
return;
settled = true;
clearTimeout(timer);
- socket.destroy();
+ options.signal?.removeEventListener("abort", onAbort);
+ destroyAfterCancel();
run();
};
- const timer = setTimeout(() => finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten))), timeoutMs);
+ const sendCancel = () => {
+ if (!requestWritten) {
+ cancelAfterWrite = true;
+ return;
+ }
+ if (!socket.writable)
+ return;
+ socket.write(cancelPayload());
+ };
+ const destroyAfterCancel = () => {
+ socket.destroy();
+ };
+ const onAbort = () => {
+ sendCancel();
+ finish(() => reject(new DaemonRequestCancelledError(requestWritten)));
+ };
+ const timer = setTimeout(() => {
+ sendCancel();
+ finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten)));
+ }, options.timeoutMs);
timer.unref();
+ if (options.signal?.aborted) {
+ onAbort();
+ return;
+ }
+ options.signal?.addEventListener("abort", onAbort, { once: true });
const decoder = createLineDecoder((message) => {
- const result = toToolResult(message);
+ if (isAuthErrorResponse(message)) {
+ finish(() => reject(new DaemonAuthenticationRejectedError()));
+ return;
+ }
+ const result = toToolResult(message, requestId);
if (result)
finish(() => resolve(result));
else
finish(() => reject(new DaemonRequestError("invalid daemon response", requestWritten)));
});
socket.once("connect", () => {
- requestWritten = true;
- socket.write(encodeJsonLine({ jsonrpc: "2.0", id: REQUEST_ID, method: "tools/call", params: { name, arguments: args } }));
+ const payload = encodeJsonLine({
+ jsonrpc: "2.0",
+ id: requestId,
+ method: "tools/call",
+ params: { _omo: authEnvelope(token), name, arguments: args },
+ });
+ socket.write(payload, () => {
+ requestWritten = true;
+ if (cancelAfterWrite && socket.writable)
+ socket.write(cancelPayload());
+ });
});
socket.on("data", (chunk) => decoder.push(chunk));
socket.once("error", (error) => finish(() => reject(new DaemonRequestError(error.message, requestWritten))));
socket.once("close", () => finish(() => reject(new DaemonRequestError("daemon connection closed", requestWritten))));
});
}
-function toToolResult(message) {
- if (!isPlainRecord(message) || message["id"] !== REQUEST_ID)
+function toToolResult(message, requestId) {
+ if (!isPlainRecord(message) || message["id"] !== requestId)
return null;
const result = message["result"];
if (!isPlainRecord(result) || !Array.isArray(result["content"]))
@@ -107,6 +180,16 @@ function toToolResult(message) {
details: result["details"],
};
}
+function allocateProxyRequestId() {
+ const id = nextProxyRequestId;
+ nextProxyRequestId += 1;
+ if (nextProxyRequestId > Number.MAX_SAFE_INTEGER)
+ nextProxyRequestId = 1;
+ return id;
+}
+function isRetryableTool(name) {
+ return name !== "rename" && name !== "lsp_rename";
+}
function errorText(error) {
return error instanceof Error ? error.message : String(error);
}
diff --git a/plugins/omo/components/lsp-daemon/dist/daemon-server.d.ts b/plugins/omo/components/lsp-daemon/dist/daemon-server.d.ts
index 9766143a..2f2daba6 100644
--- a/plugins/omo/components/lsp-daemon/dist/daemon-server.d.ts
+++ b/plugins/omo/components/lsp-daemon/dist/daemon-server.d.ts
@@ -1,5 +1,6 @@
import { type Server } from "node:net";
import type { DaemonPaths } from "./paths.js";
+export { DaemonAlreadyRunningError, DaemonStartupDeferredError } from "./ownership.js";
export interface DaemonServerOptions {
idleShutdownMs?: number;
idleCheckIntervalMs?: number;
diff --git a/plugins/omo/components/lsp-daemon/dist/daemon-server.js b/plugins/omo/components/lsp-daemon/dist/daemon-server.js
index ef0783d1..820ceb6c 100644
--- a/plugins/omo/components/lsp-daemon/dist/daemon-server.js
+++ b/plugins/omo/components/lsp-daemon/dist/daemon-server.js
@@ -1,41 +1,58 @@
-import { mkdirSync, writeFileSync } from "node:fs";
+import { chmodSync } from "node:fs";
import { createServer } from "node:net";
-import { join } from "node:path";
import { disposeDefaultLspManager, getLspManager } from "@oh-my-opencode/lsp-core/lsp/manager";
-import { unlinkQuietly } from "./lock.js";
+import { setPrivateFileMode } from "./ipc-protocol.js";
+import { pingDaemon } from "./ensure-daemon.js";
+import { acquireStartupLease, DaemonStartupDeferredError, endpointIdentity, removeDaemonMetadataForOwner, writeDaemonOwner, } from "./ownership.js";
import { handleDaemonMessage } from "./request-routing.js";
import { createLineDecoder, encodeJsonLine } from "./socket-jsonrpc.js";
+export { DaemonAlreadyRunningError, DaemonStartupDeferredError } from "./ownership.js";
const DEFAULT_IDLE_SHUTDOWN_MS = 30 * 60_000;
const DEFAULT_IDLE_CHECK_INTERVAL_MS = 60_000;
export async function startDaemonServer(paths, options = {}) {
const idleShutdownMs = options.idleShutdownMs ?? DEFAULT_IDLE_SHUTDOWN_MS;
const idleCheckIntervalMs = options.idleCheckIntervalMs ?? DEFAULT_IDLE_CHECK_INTERVAL_MS;
- mkdirSync(paths.dir, { recursive: true });
- unlinkQuietly(paths.socket);
+ const lease = await acquireStartupLease(paths, (token) => pingDaemon(paths, token));
const connections = new Set();
let lastActiveAt = Date.now();
const touch = () => {
lastActiveAt = Date.now();
};
+ let routeOwner = lease.owner;
const server = createServer((socket) => {
connections.add(socket);
+ const activeRequests = new Map();
touch();
const decoder = createLineDecoder((message) => {
touch();
- void respond(socket, message);
+ void respond(socket, message, lease.token, routeOwner, activeRequests);
});
socket.on("data", (chunk) => decoder.push(chunk));
socket.on("error", () => socket.destroy());
socket.on("close", () => {
+ for (const controller of activeRequests.values())
+ controller.abort();
+ activeRequests.clear();
connections.delete(socket);
touch();
});
});
server.on("error", (error) => logServerError(error));
- const endpointPath = join(paths.dir, "daemon.endpoint");
- await listen(server, paths.socket);
- writeFileSync(paths.pid, `${process.pid}\n`);
- writeFileSync(endpointPath, paths.socket);
+ let owner;
+ try {
+ await listen(server, paths.socket);
+ if (process.platform !== "win32")
+ chmodSync(paths.socket, 0o600);
+ owner = { ...lease.owner, endpoint: endpointIdentity(paths.socket) };
+ routeOwner = owner;
+ writeDaemonOwner(paths, owner);
+ await assertSelfProbe(paths, lease.token, owner);
+ }
+ catch (error) {
+ lease.lock.release();
+ throw error;
+ }
+ lease.lock.release();
let closed = false;
const close = async () => {
if (closed)
@@ -46,9 +63,7 @@ export async function startDaemonServer(paths, options = {}) {
socket.destroy();
connections.clear();
await closeServer(server);
- unlinkQuietly(paths.socket);
- unlinkQuietly(paths.pid);
- unlinkQuietly(endpointPath);
+ removeDaemonMetadataForOwner(paths, owner);
await disposeDefaultLspManager();
};
const idleTimer = setInterval(() => {
@@ -70,16 +85,26 @@ export async function startDaemonServer(paths, options = {}) {
installSignalHandlers(close);
return { server, close };
}
-async function respond(socket, message) {
+async function respond(socket, message, token, owner, activeRequests) {
try {
- const response = await handleDaemonMessage(message);
+ const response = await handleDaemonMessage(message, { token, owner, activeRequests });
if (response && socket.writable)
socket.write(encodeJsonLine(response));
}
catch (error) {
+ if (!(error instanceof Error))
+ throw error;
logServerError(error);
}
}
+async function assertSelfProbe(paths, token, owner) {
+ setPrivateFileMode(paths.pid);
+ setPrivateFileMode(paths.endpoint);
+ setPrivateFileMode(paths.owner);
+ const ping = await pingDaemon(paths, token);
+ if (!ping || ping.nonce !== owner.nonce)
+ throw new DaemonStartupDeferredError("self_probe_failed");
+}
function listen(server, socketPath) {
return new Promise((resolve, reject) => {
const onError = (error) => reject(error);
diff --git a/plugins/omo/components/lsp-daemon/dist/ensure-daemon.d.ts b/plugins/omo/components/lsp-daemon/dist/ensure-daemon.d.ts
index ca79ce30..4c5c73f5 100644
--- a/plugins/omo/components/lsp-daemon/dist/ensure-daemon.d.ts
+++ b/plugins/omo/components/lsp-daemon/dist/ensure-daemon.d.ts
@@ -1,12 +1,12 @@
-import { type LockHandle } from "./lock.js";
-import type { DaemonPaths } from "./paths.js";
+import type { OwnerPing } from "./ownership.js";
+import { type DaemonPaths } from "./paths.js";
+import { type DaemonRuntimeDefaults } from "./runtime-contract.js";
+export { InvalidRuntimeOverrideError, OMO_LSP_DAEMON_CLI, resolveDaemonRuntime } from "./runtime-contract.js";
export declare class DaemonUnreachableError extends Error {
constructor(socketPath: string);
}
export interface EnsureDaemonDeps {
- probe(socketPath: string): Promise<boolean>;
- acquireLock(lockPath: string): LockHandle | null;
- cleanupStaleSocket(socketPath: string): void;
+ probe(paths: DaemonPaths): Promise<boolean>;
spawnDaemon(paths: DaemonPaths): void;
sleep(ms: number): Promise<void>;
now(): number;
@@ -16,7 +16,8 @@ export interface EnsureDaemonOptions {
pollIntervalMs?: number;
}
export declare function ensureDaemonRunning(paths: DaemonPaths, deps?: EnsureDaemonDeps, options?: EnsureDaemonOptions): Promise<void>;
-export declare function probeSocket(socketPath: string, timeoutMs?: number): Promise<boolean>;
+export declare function probeDaemon(paths: DaemonPaths, timeoutMs?: number): Promise<boolean>;
+export declare function pingDaemon(paths: DaemonPaths, token: string, timeoutMs?: number): Promise<OwnerPing | null>;
export declare function spawnDaemonProcess(paths: DaemonPaths): void;
-export declare function resolveDaemonCliPath(env?: NodeJS.ProcessEnv): string;
+export declare function resolveDaemonCliPath(env?: NodeJS.ProcessEnv, defaults?: DaemonRuntimeDefaults): string;
export declare function defaultEnsureDaemonDeps(): EnsureDaemonDeps;
diff --git a/plugins/omo/components/lsp-daemon/dist/ensure-daemon.js b/plugins/omo/components/lsp-daemon/dist/ensure-daemon.js
index 4a7374d2..d90c9b51 100644
--- a/plugins/omo/components/lsp-daemon/dist/ensure-daemon.js
+++ b/plugins/omo/components/lsp-daemon/dist/ensure-daemon.js
@@ -1,14 +1,16 @@
import { spawn } from "node:child_process";
-import { closeSync, existsSync, mkdirSync, openSync } from "node:fs";
+import { closeSync, mkdirSync, openSync } from "node:fs";
import { connect } from "node:net";
import { dirname } from "node:path";
import { execPath } from "node:process";
-import { fileURLToPath } from "node:url";
-import { tryAcquireLock, unlinkQuietly } from "./lock.js";
+import { authEnvelope, readAuthToken } from "./ipc-protocol.js";
+import { packagedRuntimeDefaults } from "./paths.js";
+import { resolveDaemonRuntime } from "./runtime-contract.js";
+import { createLineDecoder, encodeJsonLine } from "./socket-jsonrpc.js";
+export { InvalidRuntimeOverrideError, OMO_LSP_DAEMON_CLI, resolveDaemonRuntime } from "./runtime-contract.js";
const PROBE_TIMEOUT_MS = 500;
const DEFAULT_READY_TIMEOUT_MS = 5_000;
const DEFAULT_POLL_INTERVAL_MS = 100;
-const CODEX_LSP_DAEMON_CLI_ENV = "CODEX_LSP_DAEMON_CLI";
export class DaemonUnreachableError extends Error {
constructor(socketPath) {
super(`LSP daemon did not become reachable at ${socketPath}`);
@@ -18,50 +20,51 @@ export class DaemonUnreachableError extends Error {
export async function ensureDaemonRunning(paths, deps = defaultEnsureDaemonDeps(), options = {}) {
const readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
- if (await deps.probe(paths.socket))
+ if (await deps.probe(paths))
return;
- const lock = deps.acquireLock(paths.lock);
- if (!lock) {
- await waitUntilReachable(paths.socket, deps, readyTimeoutMs, pollIntervalMs);
- return;
- }
- try {
- if (await deps.probe(paths.socket))
- return;
- deps.cleanupStaleSocket(paths.socket);
- deps.spawnDaemon(paths);
- await waitUntilReachable(paths.socket, deps, readyTimeoutMs, pollIntervalMs);
- }
- finally {
- lock.release();
- }
+ deps.spawnDaemon(paths);
+ await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs);
}
-async function waitUntilReachable(socketPath, deps, readyTimeoutMs, pollIntervalMs) {
+async function waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs) {
const deadline = deps.now() + readyTimeoutMs;
for (;;) {
- if (await deps.probe(socketPath))
+ if (await deps.probe(paths))
return;
if (deps.now() >= deadline)
- throw new DaemonUnreachableError(socketPath);
+ throw new DaemonUnreachableError(paths.socket);
await deps.sleep(pollIntervalMs);
}
}
-export function probeSocket(socketPath, timeoutMs = PROBE_TIMEOUT_MS) {
+export async function probeDaemon(paths, timeoutMs = PROBE_TIMEOUT_MS) {
+ const token = readAuthToken(paths);
+ if (!token)
+ return false;
+ return (await pingDaemon(paths, token, timeoutMs)) !== null;
+}
+export function pingDaemon(paths, token, timeoutMs = PROBE_TIMEOUT_MS) {
return new Promise((resolve) => {
- const socket = connect(socketPath);
- const finish = (ok) => {
+ const socket = connect(paths.socket);
+ let settled = false;
+ const finish = (value) => {
+ if (settled)
+ return;
+ settled = true;
socket.destroy();
- resolve(ok);
+ resolve(value);
};
- const timer = setTimeout(() => finish(false), timeoutMs);
+ const timer = setTimeout(() => finish(null), timeoutMs);
timer.unref?.();
- socket.once("connect", () => {
+ const decoder = createLineDecoder((message) => {
clearTimeout(timer);
- finish(true);
+ finish(parsePingResponse(message));
+ });
+ socket.once("connect", () => {
+ socket.write(encodeJsonLine({ jsonrpc: "2.0", id: 1, method: "omo/ping", params: { _omo: authEnvelope(token) } }));
});
+ socket.on("data", (chunk) => decoder.push(chunk));
socket.once("error", () => {
clearTimeout(timer);
- finish(false);
+ finish(null);
});
});
}
@@ -69,8 +72,7 @@ export function spawnDaemonProcess(paths) {
mkdirSync(dirname(paths.log), { recursive: true });
const logFd = openSync(paths.log, "a");
try {
- const cliPath = resolveDaemonCliPath();
- const child = spawn(execPath, [cliPath, "daemon"], {
+ const child = spawn(execPath, [paths.cliPath, "daemon"], {
detached: true,
stdio: ["ignore", logFd, logFd],
});
@@ -80,20 +82,12 @@ export function spawnDaemonProcess(paths) {
closeSync(logFd);
}
}
-export function resolveDaemonCliPath(env = process.env) {
- const override = env[CODEX_LSP_DAEMON_CLI_ENV]?.trim();
- if (override)
- return override;
- return fileURLToPath(new URL("./cli.js", import.meta.url));
+export function resolveDaemonCliPath(env = process.env, defaults = packagedRuntimeDefaults()) {
+ return resolveDaemonRuntime(env, defaults).cliPath;
}
export function defaultEnsureDaemonDeps() {
return {
- probe: (socketPath) => probeSocket(socketPath),
- acquireLock: (lockPath) => tryAcquireLock(lockPath),
- cleanupStaleSocket: (socketPath) => {
- if (existsSync(socketPath))
- unlinkQuietly(socketPath);
- },
+ probe: (paths) => probeDaemon(paths),
spawnDaemon: (paths) => spawnDaemonProcess(paths),
sleep: (ms) => new Promise((resolve) => {
setTimeout(resolve, ms);
@@ -101,3 +95,32 @@ export function defaultEnsureDaemonDeps() {
now: () => Date.now(),
};
}
+function parsePingResponse(message) {
+ if (!message || typeof message !== "object" || Array.isArray(message))
+ return null;
+ const result = Reflect.get(message, "result");
+ if (!result || typeof result !== "object" || Array.isArray(result))
+ return null;
+ const pid = Reflect.get(result, "pid");
+ const nonce = Reflect.get(result, "nonce");
+ const startedAt = Reflect.get(result, "startedAt");
+ const endpoint = Reflect.get(result, "endpoint");
+ if (typeof pid !== "number" || typeof nonce !== "string" || typeof startedAt !== "string")
+ return null;
+ if (!endpoint || typeof endpoint !== "object" || Array.isArray(endpoint))
+ return null;
+ const path = Reflect.get(endpoint, "path");
+ const kind = Reflect.get(endpoint, "kind");
+ if (typeof path !== "string")
+ return null;
+ if (kind === "windows")
+ return { pid, nonce, startedAt, endpoint: { kind, path } };
+ if (kind === "missing")
+ return { pid, nonce, startedAt, endpoint: { kind, path } };
+ const dev = Reflect.get(endpoint, "dev");
+ const ino = Reflect.get(endpoint, "ino");
+ if (kind === "unix" && typeof dev === "number" && typeof ino === "number") {
+ return { pid, nonce, startedAt, endpoint: { kind, path, dev, ino } };
+ }
+ return null;
+}
diff --git a/plugins/omo/components/lsp-daemon/dist/index.d.ts b/plugins/omo/components/lsp-daemon/dist/index.d.ts
index b6aee6e3..a0320dd3 100644
--- a/plugins/omo/components/lsp-daemon/dist/index.d.ts
+++ b/plugins/omo/components/lsp-daemon/dist/index.d.ts
@@ -1,5 +1,5 @@
export { disposeDefaultLspManager } from "@oh-my-opencode/lsp-core/lsp/manager";
export { type CallToolOptions, callDiagnosticsViaDaemon, callToolViaDaemon, currentRequestContext, type DaemonToolContext, } from "./daemon-client.js";
-export { ensureDaemonRunning } from "./ensure-daemon.js";
-export { type DaemonPaths, daemonPaths } from "./paths.js";
+export { ensureDaemonRunning, InvalidRuntimeOverrideError, OMO_LSP_DAEMON_CLI, probeDaemon, resolveDaemonRuntime, } from "./ensure-daemon.js";
+export { type DaemonPaths, daemonPaths, InvalidDaemonDirectoryError, InvalidDaemonVersionError, OMO_LSP_DAEMON_DIR, OMO_LSP_DAEMON_VERSION, validateDaemonVersion, } from "./paths.js";
export { runMcpStdioProxy } from "./proxy.js";
diff --git a/plugins/omo/components/lsp-daemon/dist/index.js b/plugins/omo/components/lsp-daemon/dist/index.js
index 0bdbbc23..46dcc098 100644
--- a/plugins/omo/components/lsp-daemon/dist/index.js
+++ b/plugins/omo/components/lsp-daemon/dist/index.js
@@ -1,31 +1,16 @@
// ../lsp-core/src/lsp/cleanup-errors.ts
-function reportBestEffortCleanupError(operation, error) {
- if (process.env["CODEX_LSP_DEBUG_CLEANUP"] !== "1")
- return;
+function writeCleanupError(message) {
+ process.stderr.write(`${message}
+`);
+}
+function reportBestEffortCleanupError(operation, error, logger = writeCleanupError) {
const message = error instanceof Error ? error.message : String(error);
- console.error(`[codex-lsp] ignored ${operation} failure during cleanup: ${message}`);
+ logger(`[lsp] ignored ${operation} failure during cleanup: ${message}`);
}
// ../lsp-core/src/lsp/client.ts
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
-import { pathToFileURL as pathToFileURL2 } from "node:url";
-
-// ../lsp-core/src/request-context.ts
-import { AsyncLocalStorage } from "node:async_hooks";
-var storage = new AsyncLocalStorage;
-function runWithRequestContext(context, fn) {
- return storage.run(context, fn);
-}
-function contextCwd() {
- return storage.getStore()?.cwd ?? process.cwd();
-}
-function contextEnv(key) {
- const store = storage.getStore();
- if (store?.env)
- return store.env[key];
- return process.env[key];
-}
+import { resolve as resolve5 } from "node:path";
+import { pathToFileURL as pathToFileURL3 } from "node:url";
// ../lsp-core/src/lsp/connection.ts
import { pathToFileURL } from "node:url";
@@ -89,7 +74,12 @@ class LspInvalidPathError extends Error {
}
class LspServerLookupError extends Error {
+ lookup;
name = "LspServerLookupError";
+ constructor(message, lookup) {
+ super(message);
+ this.lookup = lookup;
+ }
}
class LspServerInitializingError extends Error {
@@ -155,28 +145,80 @@ class JsonRpcConnection {
onError(handler) {
this.errorHandlers.push(handler);
}
- async sendRequest(method, params) {
+ async sendRequest(method, params, options = {}) {
if (this.disposed)
throw new Error("JSON-RPC connection is disposed");
const id = this.nextRequestId;
this.nextRequestId += 1;
+ const key = String(id);
const message = params === undefined ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
+ let requestWritten = false;
+ let cancelAfterWrite = false;
+ let settled = false;
+ const writeCancel = () => this.writeMessage({ jsonrpc: "2.0", method: "$/cancelRequest", params: { id } });
const responsePromise = new Promise((resolve, reject) => {
- this.pendingRequests.set(String(id), {
+ const cleanup = () => {
+ options.signal?.removeEventListener("abort", onAbort);
+ };
+ const settleCancel = () => {
+ if (settled)
+ return;
+ settled = true;
+ this.pendingRequests.delete(key);
+ cleanup();
+ const rejectCancelled = () => reject(abortError(options.signal));
+ if (!requestWritten) {
+ cancelAfterWrite = true;
+ rejectCancelled();
+ return;
+ }
+ writeCancel().then(rejectCancelled, (error) => {
+ this.emitError(toError(error));
+ rejectCancelled();
+ });
+ };
+ const onAbort = () => settleCancel();
+ this.pendingRequests.set(key, {
resolve(result) {
+ settled = true;
+ cleanup();
resolve(result);
},
- reject
+ reject(error) {
+ settled = true;
+ cleanup();
+ reject(error);
+ },
+ cleanup
});
+ if (options.signal?.aborted) {
+ settleCancel();
+ return;
+ }
+ options.signal?.addEventListener("abort", onAbort, { once: true });
});
+ if (settled)
+ return responsePromise;
try {
await this.writeMessage(message);
+ requestWritten = true;
+ if (cancelAfterWrite)
+ await writeCancel();
} catch (error) {
- this.pendingRequests.delete(String(id));
+ if (settled)
+ return responsePromise;
+ const pending = this.pendingRequests.get(key);
+ if (pending) {
+ pending.cleanup();
+ this.pendingRequests.delete(key);
+ }
throw error;
}
return responsePromise;
}
+ pendingRequestCount() {
+ return this.pendingRequests.size;
+ }
async sendNotification(method, params) {
if (this.disposed)
return;
@@ -193,6 +235,7 @@ class JsonRpcConnection {
this.reader.off("error", this.handleStreamError);
this.writer.off("error", this.handleStreamError);
for (const pending of this.pendingRequests.values()) {
+ pending.cleanup();
pending.reject(new Error("JSON-RPC connection disposed"));
}
this.pendingRequests.clear();
@@ -268,6 +311,7 @@ class JsonRpcConnection {
if (!pending)
return;
this.pendingRequests.delete(String(id));
+ pending.cleanup();
if ("error" in message) {
pending.reject(jsonRpcErrorToError(message["error"]));
return;
@@ -281,7 +325,11 @@ class JsonRpcConnection {
try {
handler(params);
} catch (error) {
- this.emitError(toError(error));
+ if (error instanceof Error) {
+ this.emitError(error);
+ return;
+ }
+ this.emitError(new Error(String(error)));
}
}
handleRequest(message) {
@@ -322,6 +370,14 @@ ${body}`;
}
}
}
+function abortError(signal) {
+ const reason = signal?.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "LSP request cancelled");
+ error.name = "AbortError";
+ return error;
+}
function parseContentLength(headers) {
for (const line of headers.split(`\r
`)) {
@@ -508,7 +564,7 @@ function spawnProcess(command, options) {
return wrap(proc);
}
-// ../lsp-core/src/lsp/transport.ts
+// ../lsp-core/src/lsp/transport-protocol.ts
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
@@ -528,7 +584,32 @@ function parseDiagnosticsParams(params) {
if (!isRecord(params) || typeof params["uri"] !== "string")
return null;
const diagnostics = Array.isArray(params["diagnostics"]) ? params["diagnostics"].filter(isDiagnostic) : [];
- return { uri: params["uri"], diagnostics };
+ const version = typeof params["version"] === "number" ? params["version"] : undefined;
+ return { uri: params["uri"], diagnostics, ...version === undefined ? {} : { version } };
+}
+function createLspSpawnEnv(_root, input) {
+ return { ...input };
+}
+function isDiagnostic(value) {
+ return isRecord(value) && isRange(value["range"]) && typeof value["message"] === "string";
+}
+function isRange(value) {
+ return isRecord(value) && isPosition(value["start"]) && isPosition(value["end"]);
+}
+function isPosition(value) {
+ return isRecord(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+}
+
+// ../lsp-core/src/lsp/transport.ts
+class LspClientNotStartedError extends Error {
+ serverId;
+ root;
+ name = "LspClientNotStartedError";
+ constructor(serverId, root) {
+ super("LSP client not started");
+ this.serverId = serverId;
+ this.root = root;
+ }
}
class LspClientTransport {
@@ -541,6 +622,8 @@ class LspClientTransport {
diagnosticsStore = new Map;
requestTimeoutMs;
initializeTimeoutMs;
+ workspaceApplyEditHandler = null;
+ diagnosticPullSupported = false;
constructor(root, server, timeouts = {}) {
this.root = root;
this.server = server;
@@ -553,6 +636,21 @@ class LspClientTransport {
command() {
return [...this.server.command];
}
+ setWorkspaceApplyEditHandler(handler) {
+ this.workspaceApplyEditHandler = handler;
+ }
+ hasWorkspaceApplyEditHandler() {
+ return this.workspaceApplyEditHandler !== null;
+ }
+ setDiagnosticPullSupported(supported) {
+ this.diagnosticPullSupported = supported;
+ }
+ isDiagnosticPullSupported() {
+ return this.diagnosticPullSupported;
+ }
+ handlePublishDiagnostics(params) {
+ this.diagnosticsStore.set(params.uri, [...params.diagnostics]);
+ }
async start() {
const env = createLspSpawnEnv(this.root, {
...process.env,
@@ -563,7 +661,6 @@ class LspClientTransport {
env
});
this.startStderrReading();
- await new Promise((resolve) => setTimeout(resolve, 100));
if (this.proc.exitCode !== null) {
const stderr = this.stderrBuffer.join(`
`);
@@ -573,7 +670,7 @@ class LspClientTransport {
this.connection.onNotification("textDocument/publishDiagnostics", (params) => {
const diagnosticsParams = parseDiagnosticsParams(params);
if (diagnosticsParams?.uri) {
- this.diagnosticsStore.set(diagnosticsParams.uri, diagnosticsParams.diagnostics);
+ this.handlePublishDiagnostics(diagnosticsParams);
}
});
this.connection.onRequest("workspace/configuration", (params) => {
@@ -586,6 +683,9 @@ class LspClientTransport {
});
this.connection.onRequest("client/registerCapability", () => null);
this.connection.onRequest("window/workDoneProgress/create", () => null);
+ if (this.workspaceApplyEditHandler) {
+ this.connection.onRequest("workspace/applyEdit", this.workspaceApplyEditHandler);
+ }
this.connection.onClose(() => {
this.processExited = true;
});
@@ -614,30 +714,25 @@ class LspClientTransport {
}
async sendRequest(method, ...args) {
if (!this.connection)
- throw new Error("LSP client not started");
+ throw new LspClientNotStartedError(this.server.id, this.root);
if (this.processExited || this.proc && this.proc.exitCode !== null) {
const stderrTail = this.stderrBuffer.slice(-10).join(`
`);
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, stderrTail || undefined);
}
- const timeoutMs = args[1]?.timeoutMs ?? this.requestTimeoutMs;
- let timeoutHandle = null;
- const timeoutPromise = new Promise((_, reject) => {
- timeoutHandle = setTimeout(() => {
- const stderrTail = this.stderrBuffer.slice(-5).join(`
+ const options = args[1];
+ const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
+ const timeoutController = new AbortController;
+ const timeoutHandle = setTimeout(() => {
+ const stderrTail = this.stderrBuffer.slice(-5).join(`
`);
- reject(new LspRequestTimeoutError(method, stderrTail || undefined));
- }, timeoutMs);
- });
+ timeoutController.abort(new LspRequestTimeoutError(method, stderrTail || undefined));
+ }, timeoutMs);
+ const combinedSignal = combineAbortSignals(options?.signal, timeoutController.signal);
try {
- const requestPromise = args.length === 0 ? this.connection.sendRequest(method) : this.connection.sendRequest(method, args[0]);
- const result = await Promise.race([requestPromise, timeoutPromise]);
- if (timeoutHandle !== null)
- clearTimeout(timeoutHandle);
+ const result = args.length === 0 ? await this.connection.sendRequest(method, undefined, { signal: combinedSignal.signal }) : await this.connection.sendRequest(method, args[0], { signal: combinedSignal.signal });
return result;
} catch (error) {
- if (timeoutHandle !== null)
- clearTimeout(timeoutHandle);
if (this.processExited || this.proc && this.proc.exitCode !== null) {
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, this.stderrBuffer.slice(-10).join(`
`) || undefined);
@@ -646,6 +741,9 @@ class LspClientTransport {
throw new LspConnectionClosedError(this.server.id, this.root, error.message);
}
throw error;
+ } finally {
+ clearTimeout(timeoutHandle);
+ combinedSignal.dispose();
}
}
async sendNotification(method, ...args) {
@@ -674,17 +772,17 @@ class LspClientTransport {
try {
await this.sendRequest("shutdown");
} catch (error) {
- reportBestEffortCleanupError("shutdown request", error);
+ reportBestEffortCleanupError("shutdown request", error instanceof Error ? error : String(error));
}
try {
await this.sendNotification("exit");
} catch (error) {
- reportBestEffortCleanupError("exit notification", error);
+ reportBestEffortCleanupError("exit notification", error instanceof Error ? error : String(error));
}
try {
this.connection.dispose();
} catch (error) {
- reportBestEffortCleanupError("connection dispose", error);
+ reportBestEffortCleanupError("connection dispose", error instanceof Error ? error : String(error));
}
this.connection = null;
}
@@ -715,11 +813,11 @@ class LspClientTransport {
new Promise((resolve) => setTimeout(resolve, STOP_SIGKILL_GRACE_MS))
]);
} catch (error) {
- reportBestEffortCleanupError("hard process kill", error);
+ reportBestEffortCleanupError("hard process kill", error instanceof Error ? error : String(error));
}
}
} catch (error) {
- reportBestEffortCleanupError("process stop", error);
+ reportBestEffortCleanupError("process stop", error instanceof Error ? error : String(error));
}
}
this.processExited = true;
@@ -729,26 +827,45 @@ class LspClientTransport {
return this.diagnosticsStore.get(uri) ?? [];
}
}
-function createLspSpawnEnv(_root, input) {
- return { ...input };
-}
-function isDiagnostic(value) {
- return isRecord(value) && isRange(value["range"]) && typeof value["message"] === "string";
-}
-function isRange(value) {
- return isRecord(value) && isPosition(value["start"]) && isPosition(value["end"]);
-}
-function isPosition(value) {
- return isRecord(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+function combineAbortSignals(primary, secondary) {
+ const controller = new AbortController;
+ const abortFrom = (signal) => {
+ if (!controller.signal.aborted)
+ controller.abort(signal.reason);
+ };
+ const onPrimaryAbort = () => {
+ if (primary)
+ abortFrom(primary);
+ };
+ const onSecondaryAbort = () => abortFrom(secondary);
+ if (primary?.aborted)
+ abortFrom(primary);
+ else
+ primary?.addEventListener("abort", onPrimaryAbort, { once: true });
+ if (secondary.aborted)
+ abortFrom(secondary);
+ else
+ secondary.addEventListener("abort", onSecondaryAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => {
+ primary?.removeEventListener("abort", onPrimaryAbort);
+ secondary.removeEventListener("abort", onSecondaryAbort);
+ }
+ };
}
// ../lsp-core/src/lsp/connection.ts
-var INITIALIZE_SETTLE_MS = 300;
+function supportsDiagnosticPull(capabilities) {
+ if (capabilities === undefined)
+ return false;
+ return Object.hasOwn(capabilities, "diagnosticProvider");
+}
class LspClientConnection extends LspClientTransport {
async initialize() {
const rootUri = pathToFileURL(this.root).href;
- await this.sendRequest("initialize", {
+ const result = await this.sendRequest("initialize", {
processId: process.pid,
rootUri,
rootPath: this.root,
@@ -762,8 +879,7 @@ class LspClientConnection extends LspClientTransport {
publishDiagnostics: {},
rename: {
prepareSupport: true,
- prepareSupportDefaultBehavior: 1,
- honorsChangeAnnotations: true
+ prepareSupportDefaultBehavior: 1
},
codeAction: {
codeActionLiteralSupport: {
@@ -792,22 +908,28 @@ class LspClientConnection extends LspClientTransport {
symbol: {},
workspaceFolders: true,
configuration: true,
- applyEdit: true,
+ ...this.hasWorkspaceApplyEditHandler() ? { applyEdit: true } : {},
workspaceEdit: {
- documentChanges: true
+ documentChanges: true,
+ resourceOperations: ["create", "rename", "delete"]
}
}
},
initializationOptions: this.server.initialization
}, { timeoutMs: this.initializeTimeoutMs });
+ this.setDiagnosticPullSupported(supportsDiagnosticPull(result?.capabilities));
await this.sendNotification("initialized");
await this.sendNotification("workspace/didChangeConfiguration", {
settings: { json: { validate: { enable: true } } }
});
- await new Promise((r) => setTimeout(r, INITIALIZE_SETTLE_MS));
}
}
+// ../lsp-core/src/lsp/workspace-document-state.ts
+import { readFileSync, realpathSync } from "node:fs";
+import { relative, resolve } from "node:path";
+import { pathToFileURL as pathToFileURL2 } from "node:url";
+
// ../lsp-core/src/lsp/effective-extension.ts
import { basename, extname } from "node:path";
var BASENAME_EXTENSIONS = {
@@ -990,191 +1112,1662 @@ function getLanguageId(ext) {
return EXT_TO_LANG[ext] ?? "plaintext";
}
-// ../lsp-core/src/lsp/client.ts
-var POST_OPEN_DELAY_MS = 1000;
-var POST_DIAGNOSTICS_WAIT_MS = 500;
+// ../lsp-core/src/lsp/workspace-document-state.ts
+var WATCHED_FILE_BATCH_SIZE = 128;
+var DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
+function canonicalPath(filePath) {
+ const absolute = resolve(filePath);
+ try {
+ return realpathSync(absolute);
+ } catch {
+ return absolute;
+ }
+}
+function isSameOrDescendant(candidate, parent) {
+ const suffix = relative(parent, candidate);
+ return suffix === "" || !suffix.startsWith("..") && suffix !== "..";
+}
+function movedPath(candidate, oldPath, newPath) {
+ const suffix = relative(oldPath, candidate);
+ return suffix === "" ? newPath : resolve(newPath, suffix);
+}
-class LspClient extends LspClientConnection {
- openedFiles = new Set;
- documentVersions = new Map;
- lastSyncedText = new Map;
- diagnosticPullErrors = [];
- getDiagnosticPullErrors() {
- return this.diagnosticPullErrors;
+class WorkspaceDocumentState {
+ sendNotification;
+ clearDiagnostics;
+ openDocuments = new Map;
+ openByUri = new Map;
+ openPromises = new Map;
+ now;
+ versionlessPublishQuiescenceMs;
+ constructor(sendNotification, clearDiagnostics, options = {}) {
+ this.sendNotification = sendNotification;
+ this.clearDiagnostics = clearDiagnostics;
+ this.now = options.now ?? (() => Date.now());
+ this.versionlessPublishQuiescenceMs = options.versionlessPublishQuiescenceMs ?? DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS;
}
async openFile(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- const uri = pathToFileURL2(absPath).href;
- const text = readFileSync(absPath, "utf-8");
- if (!this.openedFiles.has(absPath)) {
- const ext = effectiveExtension(absPath);
- const languageId = getLanguageId(ext);
- const version = 1;
- await this.sendNotification("textDocument/didOpen", {
- textDocument: {
- uri,
- languageId,
- version,
- text
- }
- });
- this.openedFiles.add(absPath);
- this.documentVersions.set(uri, version);
- this.lastSyncedText.set(uri, text);
- await new Promise((r) => setTimeout(r, POST_OPEN_DELAY_MS));
- return;
+ const path = canonicalPath(filePath);
+ const existingOpen = this.openPromises.get(path);
+ if (existingOpen) {
+ await existingOpen;
+ return this.openFile(path);
}
- const prevText = this.lastSyncedText.get(uri);
- if (prevText === text) {
+ const text = readFileSync(path, "utf-8");
+ const existing = this.openDocuments.get(path);
+ if (!existing)
+ return this.openDocumentSingleFlight(path, text);
+ if (existing.text === text)
return;
- }
- const nextVersion = (this.documentVersions.get(uri) ?? 1) + 1;
- this.documentVersions.set(uri, nextVersion);
- this.lastSyncedText.set(uri, text);
- await this.sendNotification("textDocument/didChange", {
- textDocument: { uri, version: nextVersion },
- contentChanges: [{ text }]
- });
- await this.sendNotification("textDocument/didSave", {
- textDocument: { uri },
- text
- });
+ await this.changeDocument(existing, text);
}
- async definition(filePath, line, character) {
- const absPath = resolve(contextCwd(), filePath);
- await this.openFile(absPath);
- return this.sendRequest("textDocument/definition", {
- textDocument: { uri: pathToFileURL2(absPath).href },
- position: { line: line - 1, character }
- });
+ getVersion(filePath) {
+ return this.openDocuments.get(canonicalPath(filePath))?.version;
}
- async references(filePath, line, character, includeDeclaration = true) {
- const absPath = resolve(contextCwd(), filePath);
- await this.openFile(absPath);
- return this.sendRequest("textDocument/references", {
- textDocument: { uri: pathToFileURL2(absPath).href },
- position: { line: line - 1, character },
- context: { includeDeclaration }
- });
+ getStoredDiagnostics(uri) {
+ const state = this.openByUri.get(uri);
+ if (!state)
+ return [];
+ return state.lastPublish?.diagnostics ?? state.pullCache?.diagnostics ?? [];
+ }
+ captureDiagnosticSnapshot(filePath) {
+ const state = this.openDocuments.get(canonicalPath(filePath));
+ if (!state)
+ return null;
+ return {
+ path: state.path,
+ uri: state.uri,
+ version: state.version,
+ documentGeneration: state.generation,
+ publishGeneration: state.publishGeneration
+ };
}
- async documentSymbols(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- await this.openFile(absPath);
- return this.sendRequest("textDocument/documentSymbol", {
- textDocument: { uri: pathToFileURL2(absPath).href }
- });
+ isCurrentSnapshot(snapshot) {
+ const state = this.openDocuments.get(snapshot.path);
+ return state !== undefined && state.uri === snapshot.uri && state.version === snapshot.version && state.generation === snapshot.documentGeneration;
}
- async workspaceSymbols(query) {
- return this.sendRequest("workspace/symbol", { query });
+ getPullCache(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.pullCache || state.pullCache.documentVersion !== snapshot.version)
+ return null;
+ return state.pullCache;
}
- isUnsupportedDiagnosticPullError(error) {
- if (!(error instanceof Error))
- return false;
- const code = "code" in error && typeof error.code === "number" ? error.code : undefined;
- if (code === -32601)
- return true;
- return /unsupported|not supported|method not found|unknown request/i.test(error.message);
+ recordPullDiagnostics(snapshot, report) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state)
+ return;
+ state.pullCache = {
+ documentVersion: snapshot.version,
+ diagnostics: [...report.diagnostics],
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ };
}
- async diagnostics(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- const uri = pathToFileURL2(absPath).href;
- await this.openFile(absPath);
- await new Promise((r) => setTimeout(r, POST_DIAGNOSTICS_WAIT_MS));
- try {
- const result = await this.sendRequest("textDocument/diagnostic", {
- textDocument: { uri }
- });
- if (result.items) {
- return { items: result.items };
+ recordPublishedDiagnostics(params) {
+ const state = this.openByUri.get(params.uri);
+ if (!state)
+ return;
+ state.publishGeneration += 1;
+ state.lastPublish = {
+ diagnostics: [...params.diagnostics],
+ publishGeneration: state.publishGeneration,
+ documentGenerationAtArrival: state.generation,
+ arrivedAt: this.now(),
+ ...params.version === undefined ? {} : { version: params.version }
+ };
+ this.notifyWaiters(state);
+ }
+ resolvePushDiagnostics(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.lastPublish)
+ return { status: "missing" };
+ const publish = state.lastPublish;
+ if (publish.version !== undefined) {
+ return publish.version === snapshot.version ? { status: "ready", diagnostics: publish.diagnostics } : { status: "missing" };
+ }
+ if (publish.documentGenerationAtArrival < snapshot.documentGeneration)
+ return { status: "missing" };
+ const readyAt = publish.arrivedAt + this.versionlessPublishQuiescenceMs;
+ const waitMs = Math.max(0, readyAt - this.now());
+ return waitMs === 0 ? { status: "ready", diagnostics: publish.diagnostics } : { status: "wait", waitMs };
+ }
+ waitForDiagnosticsActivity(snapshot, timeoutMs) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state || timeoutMs <= 0)
+ return Promise.resolve();
+ return new Promise((resolveActivity) => {
+ let settled = false;
+ const finish = () => {
+ if (settled)
+ return;
+ settled = true;
+ clearTimeout(timer);
+ state.waiters.delete(finish);
+ resolveActivity();
+ };
+ const timer = setTimeout(finish, timeoutMs);
+ if (typeof timer.unref === "function")
+ timer.unref();
+ state.waiters.add(finish);
+ });
+ }
+ validateVersions(operations) {
+ const versions = new Map([...this.openDocuments].map(([path, state]) => [path, state.version]));
+ for (const operation of operations) {
+ if (operation.kind === "text") {
+ const current = versions.get(operation.path);
+ if (operation.documentVersion !== null && current !== operation.documentVersion) {
+ const observed = current === undefined ? "closed document" : `open document version ${current}`;
+ return {
+ changeIndex: operation.changeIndex,
+ message: `document version ${operation.documentVersion} does not match ${observed} for ${operation.path}`
+ };
+ }
+ if (current !== undefined)
+ versions.set(operation.path, current + 1);
+ continue;
}
- } catch (error) {
- if (!this.isUnsupportedDiagnosticPullError(error)) {
- this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ if (operation.kind === "rename") {
+ const moved = [...versions].filter(([path]) => isSameOrDescendant(path, operation.oldPath));
+ for (const [path] of moved)
+ versions.delete(path);
+ for (const [path] of moved)
+ versions.set(movedPath(path, operation.oldPath, operation.newPath), 1);
+ continue;
+ }
+ if (operation.kind === "delete") {
+ for (const path of [...versions.keys()]) {
+ if (isSameOrDescendant(path, operation.path))
+ versions.delete(path);
+ }
+ continue;
+ }
+ if (operation.kind === "create" && operation.replaced && versions.has(operation.path)) {
+ versions.set(operation.path, 1);
}
}
- return { items: this.getStoredDiagnostics(uri) };
+ return null;
}
- async prepareRename(filePath, line, character) {
- const absPath = resolve(contextCwd(), filePath);
- await this.openFile(absPath);
- return this.sendRequest("textDocument/prepareRename", {
- textDocument: { uri: pathToFileURL2(absPath).href },
- position: { line: line - 1, character }
- });
+ async synchronize(delta) {
+ const watched = [];
+ for (const mutation of delta.operations)
+ await this.synchronizeMutation(mutation, watched);
+ for (let index = 0;index < watched.length; index += WATCHED_FILE_BATCH_SIZE) {
+ await this.sendNotification("workspace/didChangeWatchedFiles", {
+ changes: watched.slice(index, index + WATCHED_FILE_BATCH_SIZE)
+ });
+ }
}
- async rename(filePath, line, character, newName) {
- const absPath = resolve(contextCwd(), filePath);
- await this.openFile(absPath);
- return this.sendRequest("textDocument/rename", {
- textDocument: { uri: pathToFileURL2(absPath).href },
- position: { line: line - 1, character },
- newName
+ async synchronizeMutation(mutation, watched) {
+ if (mutation.kind === "text") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state)
+ await this.changeDocument(state, mutation.afterText);
+ else
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 2 });
+ return;
+ }
+ if (mutation.kind === "create") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state) {
+ await this.closeDocument(state);
+ await this.openDocumentSingleFlight(mutation.path, readFileSync(mutation.path, "utf-8"));
+ } else {
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: mutation.replaced ? 2 : 1 });
+ }
+ return;
+ }
+ if (mutation.kind === "rename") {
+ const moved = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.oldPath));
+ for (const state of moved)
+ await this.closeDocument(state);
+ for (const state of moved) {
+ const path = movedPath(state.path, mutation.oldPath, mutation.newPath);
+ await this.openDocumentSingleFlight(path, readFileSync(path, "utf-8"));
+ }
+ if (moved.length === 0) {
+ watched.push({ uri: pathToFileURL2(mutation.oldPath).href, type: 3 });
+ watched.push({ uri: pathToFileURL2(mutation.newPath).href, type: 1 });
+ }
+ return;
+ }
+ const removed = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.path));
+ for (const state of removed)
+ await this.closeDocument(state);
+ if (removed.length === 0)
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 3 });
+ }
+ async openDocumentSingleFlight(path, text) {
+ const existing = this.openPromises.get(path);
+ if (existing)
+ return existing;
+ const open = (async () => {
+ const state = {
+ path,
+ uri: pathToFileURL2(path).href,
+ languageId: getLanguageId(effectiveExtension(path)),
+ text,
+ version: 1,
+ generation: 1,
+ publishGeneration: 0,
+ waiters: new Set
+ };
+ this.openDocuments.set(path, state);
+ this.openByUri.set(state.uri, state);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didOpen", {
+ textDocument: { uri: state.uri, languageId: state.languageId, version: state.version, text }
+ });
+ })().finally(() => {
+ this.openPromises.delete(path);
});
+ this.openPromises.set(path, open);
+ return open;
+ }
+ async changeDocument(state, text) {
+ state.text = text;
+ state.version += 1;
+ state.generation += 1;
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didChange", {
+ textDocument: { uri: state.uri, version: state.version },
+ contentChanges: [{ text }]
+ });
+ await this.sendNotification("textDocument/didSave", { textDocument: { uri: state.uri }, text });
+ }
+ async closeDocument(state) {
+ this.openDocuments.delete(state.path);
+ this.openByUri.delete(state.uri);
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didClose", { textDocument: { uri: state.uri } });
+ }
+ notifyWaiters(state) {
+ for (const waiter of [...state.waiters])
+ waiter();
}
}
-// ../lsp-core/src/lsp/process-signal-cleanup.ts
-function installProcessSignalCleanup(cleanup) {
- const signals = process.platform === "win32" ? ["SIGINT", "SIGTERM", "SIGBREAK"] : ["SIGINT", "SIGTERM"];
- const handler = () => {
- cleanup().catch((error) => {
- reportBestEffortCleanupError("signal cleanup", error);
- });
- };
- for (const signal of signals) {
- process.on(signal, handler);
- }
- return () => {
- for (const signal of signals) {
- process.removeListener(signal, handler);
- }
- };
+// ../lsp-core/src/lsp/workspace-apply-edit-failure.ts
+var CONCURRENT_FAILURE_REASON_BY_PHASE = {
+ applying: "workspace/applyEdit is already in progress for this workspace mutation",
+ settled: "workspace/applyEdit was already handled for this workspace mutation"
+};
+function workspaceApplyEditConcurrentFailureReason(phase) {
+ return CONCURRENT_FAILURE_REASON_BY_PHASE[phase];
}
-// ../lsp-core/src/lsp/manager.ts
-async function stopClientBestEffort(client) {
+// ../lsp-core/src/lsp/workspace-edit-commit.ts
+import { existsSync as existsSync3, lstatSync as lstatSync2, renameSync, rmSync, writeFileSync } from "node:fs";
+
+// ../lsp-core/src/lsp/workspace-edit-path.ts
+import { existsSync as existsSync2, lstatSync, readFileSync as readFileSync2, readdirSync, realpathSync as realpathSync2 } from "node:fs";
+import { dirname, isAbsolute, relative as relative2, resolve as resolve2 } from "node:path";
+import { fileURLToPath } from "node:url";
+
+class WorkspaceEditPathError extends Error {
+ path;
+ detail;
+ name = "WorkspaceEditPathError";
+ constructor(path, detail) {
+ super(`${detail}: ${path}`);
+ this.path = path;
+ this.detail = detail;
+ }
+}
+function isPathInsideWorkspace(filePath, workspaceRoot) {
+ const relativePath = relative2(workspaceRoot, filePath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute(relativePath);
+}
+function canonicalizeMissingPath(filePath) {
+ let ancestor = filePath;
+ while (!existsSync2(ancestor)) {
+ const parent = dirname(ancestor);
+ if (parent === ancestor)
+ throw new WorkspaceEditPathError(filePath, "no existing ancestor");
+ ancestor = parent;
+ }
+ return resolve2(realpathSync2(ancestor), relative2(ancestor, filePath));
+}
+function canonicalWorkspaceRoot(workspaceRoot) {
try {
- await client.stop();
+ const canonical = realpathSync2(resolve2(workspaceRoot));
+ if (!lstatSync(canonical).isDirectory()) {
+ return { success: false, error: `workspace root is not a directory: ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath: resolve2(workspaceRoot),
+ followedSymbolicLink: existsSync2(resolve2(workspaceRoot)) && lstatSync(resolve2(workspaceRoot)).isSymbolicLink()
+ };
} catch (error) {
- reportBestEffortCleanupError("client stop", error);
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `workspace root ${workspaceRoot}: ${detail}` };
}
}
-function awaitWithSignal(promise, signal) {
- if (!signal)
- return promise;
- return new Promise((resolve2, reject) => {
- let settled = false;
- const onAbort = () => {
- if (settled)
- return;
- settled = true;
- reject(new DOMException("Aborted", "AbortError"));
- };
- if (signal.aborted) {
- onAbort();
- return;
+function uriToCanonicalWorkspacePath(uri, workspaceRoot) {
+ let requestedPath;
+ try {
+ const parsed = new URL(uri);
+ if (parsed.protocol !== "file:" || parsed.search !== "" || parsed.hash !== "") {
+ return { success: false, error: `non-file URI ${uri}` };
}
- signal.addEventListener("abort", onAbort, { once: true });
- promise.then((value) => {
- if (settled)
- return;
- settled = true;
- signal.removeEventListener("abort", onAbort);
- resolve2(value);
- }, (err) => {
- if (settled)
- return;
- settled = true;
- signal.removeEventListener("abort", onAbort);
- reject(err);
- });
- });
+ requestedPath = resolve2(fileURLToPath(parsed));
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `non-file URI ${uri}: ${detail}` };
+ }
+ try {
+ const canonical = existsSync2(requestedPath) ? realpathSync2(requestedPath) : canonicalizeMissingPath(requestedPath);
+ if (!isPathInsideWorkspace(canonical, workspaceRoot)) {
+ return { success: false, error: `${requestedPath}: outside workspace ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath,
+ followedSymbolicLink: existsSync2(requestedPath) && lstatSync(requestedPath).isSymbolicLink()
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `${requestedPath}: ${detail}` };
+ }
+}
+function snapshotPath(path, includeChildren) {
+ if (!existsSync2(path))
+ return { kind: "missing" };
+ const stats = lstatSync(path);
+ if (stats.isFile())
+ return { kind: "file", content: readFileSync2(path, "utf-8") };
+ if (stats.isDirectory()) {
+ return includeChildren ? { kind: "directory", children: readdirSync(path).sort() } : { kind: "directory" };
+ }
+ throw new WorkspaceEditPathError(path, "unsupported filesystem entry");
}
-class LspManager {
- clients = new Map;
- reaperHandle = null;
- signalDisposer = null;
+// ../lsp-core/src/lsp/workspace-edit-commit.ts
+var DEFAULT_IO = {
+ writeFile(path, content) {
+ writeFileSync(path, content, "utf-8");
+ },
+ rename(oldPath, newPath) {
+ renameSync(oldPath, newPath);
+ },
+ remove(path, recursive) {
+ rmSync(path, { recursive, force: false });
+ }
+};
+function snapshotsEqual(expected, actual) {
+ if (expected.kind !== actual.kind)
+ return false;
+ if (expected.kind === "file" && actual.kind === "file")
+ return expected.content === actual.content;
+ if (expected.kind === "directory" && actual.kind === "directory" && expected.children !== undefined) {
+ return JSON.stringify(expected.children) === JSON.stringify(actual.children);
+ }
+ return true;
+}
+function liveSnapshot(path, expected) {
+ return snapshotPath(path, expected.kind === "directory" && expected.children !== undefined);
+}
+function firstOperationIndex(plan) {
+ return plan.operations[0]?.changeIndex ?? 0;
+}
+function failedCommit(plan, failure) {
+ const { message, changeIndex, mutations = [], filesModified = [], totalEdits = 0, lateAbort = false } = failure;
+ return {
+ result: {
+ success: false,
+ filesModified,
+ totalEdits,
+ errors: [`change ${changeIndex}: ${message}`],
+ failedChange: changeIndex,
+ ...lateAbort ? { lateAbort: true } : {}
+ },
+ delta: mutationDelta(mutations),
+ fingerprint: plan.fingerprint
+ };
+}
+function verifySnapshots(plan) {
+ for (const [path, expected] of plan.snapshots) {
+ let actual;
+ try {
+ actual = liveSnapshot(path, expected);
+ } catch (error) {
+ const changeIndex = plan.firstChangeByPath.get(path) ?? firstOperationIndex(plan);
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, { message: `cannot verify snapshot for ${path}: ${detail}`, changeIndex });
+ }
+ if (!snapshotsEqual(expected, actual)) {
+ const changeIndex = plan.firstChangeByPath.get(path) ?? firstOperationIndex(plan);
+ return failedCommit(plan, { message: `workspace state changed before commit: ${path}`, changeIndex });
+ }
+ }
+ return null;
+}
+function addModifiedPath(paths, path) {
+ if (!paths.includes(path))
+ paths.push(path);
+}
+function reportedPath(plan, path) {
+ return plan.reportedPathByCanonical.get(path) ?? path;
+}
+function changedPathsForMutation(mutation) {
+ return mutation.kind === "rename" ? [mutation.oldPath, mutation.newPath] : [mutation.path];
+}
+function mutationDelta(operations) {
+ const changedPaths = new Set;
+ for (const operation of operations) {
+ for (const path of changedPathsForMutation(operation))
+ changedPaths.add(path);
+ }
+ return { operations, changedPaths: [...changedPaths].sort() };
+}
+function resolveIo(overrides) {
+ return {
+ writeFile: overrides?.writeFile ?? DEFAULT_IO.writeFile,
+ rename: overrides?.rename ?? DEFAULT_IO.rename,
+ remove: overrides?.remove ?? DEFAULT_IO.remove
+ };
+}
+function commitOperation(context, operation) {
+ const { plan, io, accumulator } = context;
+ if (operation.kind === "noop")
+ return;
+ if (operation.kind === "text") {
+ io.writeFile(operation.path, operation.afterText);
+ accumulator.mutations.push({
+ kind: "text",
+ path: operation.path,
+ beforeText: operation.beforeText,
+ afterText: operation.afterText
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ accumulator.totalEdits += operation.editCount;
+ return;
+ }
+ if (operation.kind === "create") {
+ io.writeFile(operation.path, "");
+ accumulator.mutations.push({ kind: "create", path: operation.path, replaced: operation.replaced });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ return;
+ }
+ if (operation.kind === "rename") {
+ if (operation.replaceDestination) {
+ const targetKind = existsSync3(operation.newPath) && lstatSync2(operation.newPath).isDirectory() ? "directory" : "file";
+ io.remove(operation.newPath, targetKind === "directory");
+ accumulator.mutations.push({ kind: "delete", path: operation.newPath, targetKind });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ }
+ io.rename(operation.oldPath, operation.newPath);
+ accumulator.mutations.push({
+ kind: "rename",
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: operation.sourceKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ return;
+ }
+ io.remove(operation.path, operation.recursive);
+ accumulator.mutations.push({
+ kind: "delete",
+ path: operation.path,
+ targetKind: operation.targetKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+}
+function commitWorkspaceEditPlan(plan, options = {}) {
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const stale = verifySnapshots(plan);
+ if (stale)
+ return stale;
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const io = resolveIo(options.io);
+ const accumulator = { mutations: [], filesModified: [], totalEdits: 0 };
+ const context = { plan, io, accumulator };
+ let lateAbort = false;
+ for (const operation of plan.operations) {
+ try {
+ commitOperation(context, operation);
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, {
+ message: `I/O failure during ${operation.kind}: ${detail}`,
+ changeIndex: operation.changeIndex,
+ mutations: accumulator.mutations,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ lateAbort: lateAbort || options.signal?.aborted === true
+ });
+ }
+ if (options.signal?.aborted)
+ lateAbort = true;
+ }
+ const result = {
+ success: true,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ errors: [],
+ ...lateAbort ? { lateAbort: true } : {}
+ };
+ return { result, delta: mutationDelta(accumulator.mutations), fingerprint: plan.fingerprint };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-fingerprint.ts
+import { createHash } from "node:crypto";
+function canonicalFingerprint(operations) {
+ const canonical = operations.map((operation) => {
+ switch (operation.kind) {
+ case "text":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ edits: operation.edits,
+ version: operation.version
+ };
+ case "rename":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "create":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "delete":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ recursive: operation.recursive,
+ ignoreIfNotExists: operation.ignoreIfNotExists
+ };
+ }
+ });
+ return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
+}
+
+// ../lsp-core/src/lsp/workspace-edit-types.ts
+class WorkspaceEditValidationError extends Error {
+ changeIndex;
+ detail;
+ name = "WorkspaceEditValidationError";
+ constructor(changeIndex, detail) {
+ super(`change ${changeIndex}: ${detail}`);
+ this.changeIndex = changeIndex;
+ this.detail = detail;
+ }
+}
+
+// ../lsp-core/src/lsp/workspace-edit-parse-helpers.ts
+function isRecord2(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function parsePosition(value) {
+ if (!isRecord2(value) || typeof value["line"] !== "number" || typeof value["character"] !== "number") {
+ return null;
+ }
+ return { line: value["line"], character: value["character"] };
+}
+function parseRange(value) {
+ if (!isRecord2(value))
+ return null;
+ const start = parsePosition(value["start"]);
+ const end = parsePosition(value["end"]);
+ return start && end ? { start, end } : null;
+}
+function parseTextEdits(value, changeIndex) {
+ if (!Array.isArray(value)) {
+ throw new WorkspaceEditValidationError(changeIndex, "text edits must be an array");
+ }
+ const edits = [];
+ for (const candidate of value) {
+ if (!isRecord2(candidate) || typeof candidate["newText"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "text edit requires range and newText");
+ }
+ if ("annotationId" in candidate) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated text edits are unsupported");
+ }
+ const range = parseRange(candidate["range"]);
+ if (!range)
+ throw new WorkspaceEditValidationError(changeIndex, "text edit range is malformed");
+ edits.push({ range, newText: candidate["newText"] });
+ }
+ return edits;
+}
+function parseBooleanOption(options, key, changeIndex) {
+ const value = options[key];
+ if (value === undefined)
+ return false;
+ if (typeof value !== "boolean") {
+ throw new WorkspaceEditValidationError(changeIndex, `${key} must be boolean`);
+ }
+ return value;
+}
+function parseOptions(value, allowed, changeIndex) {
+ if (value === undefined)
+ return {};
+ if (!isRecord2(value))
+ throw new WorkspaceEditValidationError(changeIndex, "resource options must be an object");
+ for (const key of Object.keys(value)) {
+ if (!allowed.includes(key))
+ throw new WorkspaceEditValidationError(changeIndex, `unsupported resource option ${key}`);
+ }
+ const parsed = {};
+ for (const key of allowed)
+ parsed[key] = parseBooleanOption(value, key, changeIndex);
+ return parsed;
+}
+
+// ../lsp-core/src/lsp/workspace-edit-resource-parser.ts
+function parseResourceChange(input) {
+ const kind = input.change["kind"];
+ if (kind === "create" || kind === "delete") {
+ parseSinglePathResource(input, kind);
+ return;
+ }
+ if (kind !== "rename") {
+ throw new WorkspaceEditValidationError(input.changeIndex, `unsupported resource operation ${String(kind)}`);
+ }
+ parseRename(input);
+}
+function parseSinglePathResource(input, kind) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["uri"] !== "string")
+ throw new WorkspaceEditValidationError(changeIndex, `${kind}.uri is required`);
+ const resolvedPath = uriToCanonicalWorkspacePath(change["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ if (kind === "create") {
+ const options2 = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ overwrite: options2["overwrite"] ?? false,
+ ignoreIfExists: options2["ignoreIfExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["recursive", "ignoreIfNotExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ recursive: options["recursive"] ?? false,
+ ignoreIfNotExists: options["ignoreIfNotExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+}
+function parseRename(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["oldUri"] !== "string" || typeof change["newUri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "rename requires oldUri and newUri");
+ }
+ const oldPath = uriToCanonicalWorkspacePath(change["oldUri"], workspaceRoot);
+ const newPath = uriToCanonicalWorkspacePath(change["newUri"], workspaceRoot);
+ if (!oldPath.success || !newPath.success) {
+ target.failures.push({
+ changeIndex,
+ message: !oldPath.success ? oldPath.error : !newPath.success ? newPath.error : "invalid rename path"
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind: "rename",
+ changeIndex,
+ oldPath: oldPath.path,
+ newPath: newPath.path,
+ reportedOldPath: oldPath.requestedPath,
+ reportedNewPath: newPath.requestedPath,
+ overwrite: options["overwrite"] ?? false,
+ ignoreIfExists: options["ignoreIfExists"] ?? false,
+ followedSymbolicLink: oldPath.followedSymbolicLink || newPath.followedSymbolicLink
+ });
+}
+
+// ../lsp-core/src/lsp/workspace-edit-parser.ts
+function failureResult(failures) {
+ const sorted = [...failures].sort((left, right) => left.changeIndex - right.changeIndex);
+ const first = sorted[0];
+ return {
+ success: false,
+ filesModified: [],
+ totalEdits: 0,
+ errors: sorted.map((failure) => `change ${failure.changeIndex}: ${failure.message}`),
+ ...first ? { failedChange: first.changeIndex } : {}
+ };
+}
+function parseWorkspaceEdit(edit, workspaceRoot) {
+ if (!isRecord2(edit))
+ return { operations: [], failures: [{ changeIndex: 0, message: "No edit provided" }] };
+ if (edit["changeAnnotations"] !== undefined) {
+ return { operations: [], failures: [{ changeIndex: 0, message: "change annotations are unsupported" }] };
+ }
+ const hasChanges = edit["changes"] !== undefined;
+ const hasDocumentChanges = edit["documentChanges"] !== undefined;
+ if (hasChanges && hasDocumentChanges) {
+ return {
+ operations: [],
+ failures: [{ changeIndex: 0, message: "changes and documentChanges cannot be combined" }]
+ };
+ }
+ const target = { operations: [], failures: [] };
+ if (hasChanges)
+ return parseChanges(edit["changes"], workspaceRoot, target);
+ return parseDocumentChanges(edit["documentChanges"], workspaceRoot, target);
+}
+function parseChanges(value, workspaceRoot, target) {
+ if (!isRecord2(value))
+ return { ...target, failures: [{ changeIndex: 0, message: "changes must be an object" }] };
+ const entries = Object.entries(value).sort(([left], [right]) => left.localeCompare(right));
+ for (const [changeIndex, [uri, rawEdits]] of entries.entries()) {
+ const resolvedPath = uriToCanonicalWorkspacePath(uri, workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ continue;
+ }
+ try {
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(rawEdits, changeIndex),
+ version: null
+ });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChanges(value, workspaceRoot, target) {
+ if (value === undefined)
+ return target;
+ if (!Array.isArray(value)) {
+ return { ...target, failures: [{ changeIndex: 0, message: "documentChanges must be an array" }] };
+ }
+ for (const [changeIndex, change] of value.entries()) {
+ try {
+ parseDocumentChange({ change, changeIndex, workspaceRoot, target });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChange(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (!isRecord2(change))
+ throw new WorkspaceEditValidationError(changeIndex, "document change must be an object");
+ if ("annotationId" in change) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated resource operations are unsupported");
+ }
+ if (typeof change["kind"] === "string") {
+ parseResourceChange({ change, changeIndex, workspaceRoot, target });
+ return;
+ }
+ const identifier = change["textDocument"];
+ if (!isRecord2(identifier) || typeof identifier["uri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "textDocument.uri is required");
+ }
+ const version = identifier["version"];
+ if (version !== null && (!Number.isInteger(version) || typeof version !== "number" || version < 0)) {
+ throw new WorkspaceEditValidationError(changeIndex, "document version must be null or a non-negative integer");
+ }
+ const resolvedPath = uriToCanonicalWorkspacePath(identifier["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(change["edits"], changeIndex),
+ version
+ });
+}
+
+// ../lsp-core/src/lsp/workspace-edit-simulation.ts
+import { dirname as dirname2, relative as relative3, resolve as resolve3 } from "node:path";
+
+// ../lsp-core/src/lsp/workspace-edit-text.ts
+function comparePosition(left, right) {
+ return left.line === right.line ? left.character - right.character : left.line - right.line;
+}
+function positionsEqual(left, right) {
+ return left.line === right.line && left.character === right.character;
+}
+function rangesEqual(left, right) {
+ return positionsEqual(left.start, right.start) && positionsEqual(left.end, right.end);
+}
+function isEmptyRange(range) {
+ return positionsEqual(range.start, range.end);
+}
+function formatRange(range) {
+ return `${range.start.line + 1}:${range.start.character + 1}-${range.end.line + 1}:${range.end.character + 1}`;
+}
+function validatePosition(position, label, context) {
+ const { lines, changeIndex } = context;
+ if (!Number.isInteger(position.line) || !Number.isInteger(position.character)) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position must use integer line and character`);
+ }
+ if (position.line < 0 || position.character < 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position cannot be negative`);
+ }
+ const line = lines[position.line];
+ if (line === undefined) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} line ${position.line} is outside the document`);
+ }
+ if (position.character > line.length) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} character ${position.character} is outside line ${position.line}`);
+ }
+}
+function validateRange(range, lines, changeIndex) {
+ const context = { lines, changeIndex };
+ validatePosition(range.start, "start", context);
+ validatePosition(range.end, "end", context);
+ if (comparePosition(range.start, range.end) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `range ${formatRange(range)} ends before it starts`);
+ }
+}
+function sortAndDeduplicate(edits) {
+ const sorted = edits.map((edit, index) => ({ edit, index })).sort((left, right) => {
+ const positionOrder = comparePosition(right.edit.range.start, left.edit.range.start);
+ return positionOrder === 0 ? right.index - left.index : positionOrder;
+ });
+ const unique = [];
+ for (const entry of sorted) {
+ const previous = unique.at(-1);
+ if (previous !== undefined && !isEmptyRange(entry.edit.range) && rangesEqual(previous.range, entry.edit.range) && previous.newText === entry.edit.newText) {
+ continue;
+ }
+ unique.push(entry.edit);
+ }
+ return unique;
+}
+function validateNoOverlap(edits, changeIndex) {
+ for (let index = 0;index < edits.length - 1; index += 1) {
+ const later = edits[index];
+ const earlier = edits[index + 1];
+ if (later === undefined || earlier === undefined)
+ continue;
+ if (comparePosition(earlier.range.end, later.range.start) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `overlapping edits ${formatRange(earlier.range)} and ${formatRange(later.range)}`);
+ }
+ }
+}
+function applyNormalizedTextEdits(content, edits) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ const { start, end } = edit.range;
+ const startLine = lines[start.line];
+ const endLine = lines[end.line];
+ if (startLine === undefined || endLine === undefined)
+ continue;
+ const replacement = startLine.slice(0, start.character) + edit.newText + endLine.slice(end.character);
+ lines.splice(start.line, end.line - start.line + 1, ...replacement.split(`
+`));
+ }
+ return lines.join(`
+`);
+}
+function normalizeTextEdits(content, edits, changeIndex) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ validateRange(edit.range, lines, changeIndex);
+ }
+ const normalized = sortAndDeduplicate(edits);
+ validateNoOverlap(normalized, changeIndex);
+ return { edits: normalized, text: applyNormalizedTextEdits(content, normalized) };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-simulation.ts
+function isSameOrDescendant2(candidate, parent) {
+ const relativePath = relative3(parent, candidate);
+ return relativePath === "" || !relativePath.startsWith("..") && relativePath !== "..";
+}
+function removeVirtualSubtree(virtual, path) {
+ for (const candidate of [...virtual.keys()]) {
+ if (isSameOrDescendant2(candidate, path))
+ virtual.delete(candidate);
+ }
+ virtual.set(path, { kind: "missing" });
+}
+function moveVirtualSubtree(virtual, oldPath, newPath) {
+ const moved = [...virtual.entries()].filter(([candidate]) => isSameOrDescendant2(candidate, oldPath));
+ removeVirtualSubtree(virtual, oldPath);
+ removeVirtualSubtree(virtual, newPath);
+ for (const [candidate, entry] of moved) {
+ const suffix = relative3(oldPath, candidate);
+ virtual.set(suffix === "" ? newPath : resolve3(newPath, suffix), entry);
+ }
+}
+function virtualDirectoryHasChildren(virtual, path) {
+ for (const [candidate, entry] of virtual) {
+ if (candidate !== path && entry.kind !== "missing" && isSameOrDescendant2(candidate, path))
+ return true;
+ }
+ return false;
+}
+function requireVirtualParent(virtual, path, changeIndex) {
+ if (virtual.get(dirname2(path))?.kind !== "directory") {
+ throw new WorkspaceEditValidationError(changeIndex, `parent directory does not exist for ${path}`);
+ }
+}
+function simulateOperations(parsed, snapshots) {
+ const virtual = new Map(snapshots);
+ const planned = [];
+ const failures = [];
+ for (const operation of parsed) {
+ try {
+ planned.push(simulateOperation(operation, virtual));
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ failures.push({ changeIndex: operation.changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return { operations: planned, failures };
+}
+function simulateOperation(operation, virtual) {
+ switch (operation.kind) {
+ case "text":
+ return simulateText(operation, virtual);
+ case "create":
+ return simulateCreate(operation, virtual);
+ case "rename":
+ return simulateRename(operation, virtual);
+ case "delete":
+ return simulateDelete(operation, virtual);
+ }
+}
+function rejectSymbolicLink(operation) {
+ if (operation.followedSymbolicLink) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "resource operations through symbolic links are unsupported");
+ }
+}
+function simulateText(operation, virtual) {
+ const entry = virtual.get(operation.path);
+ if (entry?.kind !== "file")
+ throw new WorkspaceEditValidationError(operation.changeIndex, `${operation.path} is not a file`);
+ const normalized = normalizeTextEdits(entry.content, operation.edits, operation.changeIndex);
+ virtual.set(operation.path, { kind: "file", content: normalized.text });
+ return {
+ kind: "text",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ beforeText: entry.content,
+ afterText: normalized.text,
+ editCount: normalized.edits.length,
+ documentVersion: operation.version
+ };
+}
+function simulateCreate(operation, virtual) {
+ rejectSymbolicLink(operation);
+ requireVirtualParent(virtual, operation.path, operation.changeIndex);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind !== "missing") {
+ if (operation.overwrite && target.kind === "file") {
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: true };
+ }
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `create target already exists: ${operation.path}`);
+ }
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: false };
+}
+function simulateRename(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const source = virtual.get(operation.oldPath) ?? { kind: "missing" };
+ if (source.kind === "missing") {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename source does not exist: ${operation.oldPath}`);
+ }
+ if (operation.oldPath === operation.newPath)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ if (isSameOrDescendant2(operation.newPath, operation.oldPath)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "cannot rename a path into its own subtree");
+ }
+ requireVirtualParent(virtual, operation.newPath, operation.changeIndex);
+ const destination = virtual.get(operation.newPath) ?? { kind: "missing" };
+ if (destination.kind !== "missing" && !operation.overwrite) {
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename target already exists: ${operation.newPath}`);
+ }
+ moveVirtualSubtree(virtual, operation.oldPath, operation.newPath);
+ return {
+ kind: "rename",
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: source.kind,
+ replaceDestination: destination.kind !== "missing"
+ };
+}
+function simulateDelete(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind === "missing") {
+ if (operation.ignoreIfNotExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `delete target does not exist: ${operation.path}`);
+ }
+ if (target.kind === "directory" && !operation.recursive && virtualDirectoryHasChildren(virtual, operation.path)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `directory is not empty: ${operation.path}`);
+ }
+ removeVirtualSubtree(virtual, operation.path);
+ return {
+ kind: "delete",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ targetKind: target.kind,
+ recursive: operation.recursive
+ };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-snapshot.ts
+import { existsSync as existsSync4, lstatSync as lstatSync3, readdirSync as readdirSync2 } from "node:fs";
+import { dirname as dirname3, resolve as resolve4 } from "node:path";
+class WorkspaceSnapshotBuilder {
+ workspaceRoot;
+ snapshots = new Map;
+ constructor(workspaceRoot) {
+ this.workspaceRoot = workspaceRoot;
+ }
+ build(operations) {
+ this.add(this.workspaceRoot, false);
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, true);
+ this.add(operation.newPath, true);
+ break;
+ case "delete":
+ this.add(operation.path, true);
+ break;
+ case "text":
+ case "create":
+ this.add(operation.path, false);
+ break;
+ }
+ }
+ return this.snapshots;
+ }
+ add(path, includeChildren) {
+ let candidate = path;
+ while (true) {
+ const existing = this.snapshots.get(candidate);
+ if (existing === undefined || includeChildren && existing.kind === "directory" && existing.children === undefined) {
+ this.snapshots.set(candidate, snapshotPath(candidate, includeChildren && candidate === path));
+ }
+ if (candidate === this.workspaceRoot)
+ break;
+ candidate = dirname3(candidate);
+ }
+ if (!includeChildren || !existsSync4(path) || !lstatSync3(path).isDirectory())
+ return;
+ for (const child of readdirSync2(path))
+ this.add(resolve4(path, child), true);
+ }
+}
+function snapshotOperations(operations, workspaceRoot) {
+ return new WorkspaceSnapshotBuilder(workspaceRoot).build(operations);
+}
+
+// ../lsp-core/src/lsp/workspace-edit-plan.ts
+class PlanPathIndex {
+ firstChangeByPath = new Map;
+ reportedPathByCanonical = new Map;
+ build(operations) {
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, operation.reportedOldPath, operation.changeIndex);
+ this.add(operation.newPath, operation.reportedNewPath, operation.changeIndex);
+ break;
+ case "text":
+ case "create":
+ case "delete":
+ this.add(operation.path, operation.reportedPath, operation.changeIndex);
+ break;
+ }
+ }
+ }
+ add(path, reportedPath2, changeIndex) {
+ if (!this.firstChangeByPath.has(path))
+ this.firstChangeByPath.set(path, changeIndex);
+ if (!this.reportedPathByCanonical.has(path))
+ this.reportedPathByCanonical.set(path, reportedPath2);
+ }
+}
+function fingerprintWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ return { success: true, fingerprint: canonicalFingerprint(parsed.operations) };
+}
+function planWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ let snapshots;
+ try {
+ snapshots = snapshotOperations(parsed.operations, root.path);
+ } catch (error) {
+ return {
+ success: false,
+ result: failureResult([{ changeIndex: 0, message: error instanceof Error ? error.message : String(error) }])
+ };
+ }
+ const simulated = simulateOperations(parsed.operations, snapshots);
+ if (simulated.failures.length > 0)
+ return { success: false, result: failureResult(simulated.failures) };
+ const paths = new PlanPathIndex;
+ paths.build(parsed.operations);
+ const plan = {
+ workspaceRoot: root.path,
+ operations: simulated.operations,
+ snapshots,
+ firstChangeByPath: paths.firstChangeByPath,
+ reportedPathByCanonical: paths.reportedPathByCanonical,
+ fingerprint: canonicalFingerprint(parsed.operations)
+ };
+ return { success: true, plan };
+}
+
+// ../lsp-core/src/lsp/workspace-mutation-controller.ts
+function failure(message, failedChange, base) {
+ return {
+ success: false,
+ filesModified: base?.filesModified ?? [],
+ totalEdits: base?.totalEdits ?? 0,
+ errors: [message],
+ ...failedChange === undefined ? {} : { failedChange },
+ ...base?.lateAbort ? { lateAbort: true } : {}
+ };
+}
+function responseFor(result) {
+ if (result.success)
+ return { applied: true };
+ return {
+ applied: false,
+ failureReason: result.errors[0] ?? "workspace edit failed",
+ ...result.failedChange === undefined ? {} : { failedChange: result.failedChange }
+ };
+}
+function isRecord3(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+class WorkspaceMutationController {
+ workspaceRoot;
+ documents;
+ activeLease = null;
+ nextLeaseId = 1;
+ io;
+ constructor(workspaceRoot, documents) {
+ this.workspaceRoot = workspaceRoot;
+ this.documents = documents;
+ }
+ setIo(io) {
+ this.io = io;
+ }
+ acquire(signal) {
+ if (this.activeLease)
+ return { success: false, result: failure("workspace mutation is already in progress") };
+ if (signal?.aborted)
+ return { success: false, result: failure("cancelled before mutating request") };
+ const lease = {
+ id: this.nextLeaseId,
+ phase: "idle",
+ ...signal === undefined ? {} : { signal }
+ };
+ this.nextLeaseId += 1;
+ this.activeLease = lease;
+ return { success: true, lease };
+ }
+ release(lease) {
+ if (this.activeLease?.id !== lease.id)
+ return;
+ this.activeLease.phase = "sealed";
+ this.activeLease = null;
+ }
+ isBeforeCommit(lease) {
+ return this.activeLease?.id === lease.id && this.activeLease.phase === "idle";
+ }
+ async handleApplyEdit(params) {
+ const lease = this.activeLease;
+ if (!lease)
+ return { applied: false, failureReason: "workspace/applyEdit requires an active workspace mutation" };
+ if (lease.phase !== "idle") {
+ return {
+ applied: false,
+ failureReason: workspaceApplyEditConcurrentFailureReason(lease.phase === "applying" ? "applying" : "settled")
+ };
+ }
+ lease.phase = "applying";
+ lease.applyCompletion = new Promise((resolve5) => {
+ lease.resolveApply = resolve5;
+ });
+ const edit = isRecord3(params) ? params["edit"] : undefined;
+ const record = edit === undefined ? { fingerprint: null, result: failure("workspace/applyEdit params.edit is required", 0) } : await this.applyEdit(edit, lease);
+ lease.serverApply = record;
+ lease.phase = "settled";
+ lease.resolveApply?.();
+ return responseFor(record.result);
+ }
+ async reconcileRename(leaseToken, edit) {
+ const lease = this.requireActiveLease(leaseToken);
+ if (!lease)
+ return { edit, apply: failure("workspace mutation lease ended before rename reconciliation") };
+ if (lease.phase === "applying")
+ await lease.applyCompletion;
+ if (lease.serverApply)
+ return this.reconcileServerApply(lease.serverApply, edit);
+ lease.phase = "sealed";
+ if (!edit)
+ return { edit, apply: failure("No edit provided") };
+ const applied = await this.applyEdit(edit, lease);
+ return { edit, apply: applied.result };
+ }
+ reconcileServerApply(record, edit) {
+ if (!edit)
+ return { edit, apply: record.result };
+ const fingerprint = fingerprintWorkspaceEdit(edit, this.workspaceRoot);
+ if (fingerprint.success && record.fingerprint !== null && fingerprint.fingerprint === record.fingerprint) {
+ return { edit, apply: record.result };
+ }
+ return {
+ edit,
+ apply: failure("rename result conflicts with server-applied workspace edit", 0, record.result)
+ };
+ }
+ async applyEdit(edit, lease) {
+ const planned = planWorkspaceEdit(edit, this.workspaceRoot);
+ if (!planned.success)
+ return { fingerprint: null, result: planned.result };
+ const versionFailure = this.documents.validateVersions(planned.plan.operations);
+ if (versionFailure) {
+ return {
+ fingerprint: planned.plan.fingerprint,
+ result: failure(versionFailure.message, versionFailure.changeIndex)
+ };
+ }
+ const commit = commitWorkspaceEditPlan(planned.plan, {
+ ...lease.signal === undefined ? {} : { signal: lease.signal },
+ ...this.io === undefined ? {} : { io: this.io }
+ });
+ let result = commit.result;
+ if (commit.delta.operations.length > 0) {
+ try {
+ await this.documents.synchronize(commit.delta);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ result = failure(`document synchronization failed after filesystem commit: ${message}`, undefined, result);
+ }
+ }
+ if (lease.signal?.aborted && !result.lateAbort)
+ result = { ...result, lateAbort: true };
+ return { fingerprint: planned.plan.fingerprint, result };
+ }
+ requireActiveLease(lease) {
+ return this.activeLease?.id === lease.id ? this.activeLease : null;
+ }
+}
+
+// ../lsp-core/src/lsp/client.ts
+var DIAGNOSTICS_FRESHNESS_TIMEOUT_MS = 3000;
+var VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
+
+class LspClient extends LspClientConnection {
+ diagnosticPullErrors = [];
+ documents;
+ workspaceMutations;
+ diagnosticsFreshnessTimeoutMs;
+ constructor(root, server, options = {}) {
+ super(root, server, options);
+ this.diagnosticsFreshnessTimeoutMs = options.diagnosticsFreshnessTimeoutMs ?? DIAGNOSTICS_FRESHNESS_TIMEOUT_MS;
+ this.documents = new WorkspaceDocumentState((method, params) => this.sendNotification(method, params), (uri) => this.diagnosticsStore.delete(uri), {
+ versionlessPublishQuiescenceMs: options.versionlessPublishQuiescenceMs ?? VERSIONLESS_PUBLISH_QUIESCENCE_MS
+ });
+ this.workspaceMutations = new WorkspaceMutationController(root, this.documents);
+ this.setWorkspaceApplyEditHandler((params) => this.workspaceMutations.handleApplyEdit(params));
+ }
+ getDiagnosticPullErrors() {
+ return this.diagnosticPullErrors;
+ }
+ async openFile(filePath) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.documents.openFile(absPath);
+ }
+ getOpenDocumentVersion(filePath) {
+ return this.documents.getVersion(this.resolveWorkspacePath(filePath));
+ }
+ getStoredDiagnostics(uri) {
+ return [...this.documents.getStoredDiagnostics(uri)];
+ }
+ setWorkspaceEditIo(io) {
+ this.workspaceMutations.setIo(io);
+ }
+ handlePublishDiagnostics(params) {
+ super.handlePublishDiagnostics(params);
+ this.documents.recordPublishedDiagnostics(params);
+ }
+ async definition(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("textDocument/definition", {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character }
+ }, options);
+ }
+ async references(filePath, line, character, includeDeclaration = true, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("textDocument/references", {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character },
+ context: { includeDeclaration }
+ }, options);
+ }
+ async documentSymbols(filePath, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("textDocument/documentSymbol", {
+ textDocument: { uri: pathToFileURL3(absPath).href }
+ }, options);
+ }
+ async workspaceSymbols(query, signal) {
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("workspace/symbol", { query }, options);
+ }
+ isUnsupportedDiagnosticPullError(error) {
+ if (!(error instanceof Error))
+ return false;
+ const code = "code" in error && typeof error.code === "number" ? error.code : undefined;
+ if (code === -32601)
+ return true;
+ return /unsupported|not supported|method not found|unknown request/i.test(error.message);
+ }
+ freshnessTimeout(absPath) {
+ return {
+ items: [],
+ transientError: {
+ kind: "freshness_timeout",
+ message: `Timed out waiting for fresh diagnostics for ${absPath} within ${this.diagnosticsFreshnessTimeoutMs}ms.`
+ }
+ };
+ }
+ parseDiagnosticPullReport(value) {
+ if (value.kind === "unchanged") {
+ return {
+ type: "unchanged",
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ return {
+ type: "full",
+ diagnostics: value.items ?? [],
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ async diagnostics(filePath, signal) {
+ signal?.throwIfAborted();
+ const absPath = this.resolveWorkspacePath(filePath);
+ const uri = pathToFileURL3(absPath).href;
+ await this.openFile(absPath);
+ const deadlineAt = Date.now() + this.diagnosticsFreshnessTimeoutMs;
+ for (;; ) {
+ signal?.throwIfAborted();
+ const snapshot = this.documents.captureDiagnosticSnapshot(absPath);
+ if (!snapshot)
+ return this.freshnessTimeout(absPath);
+ const push = this.documents.resolvePushDiagnostics(snapshot);
+ if (push.status === "ready")
+ return { items: [...push.diagnostics] };
+ let pushFallbackOnly = !this.isDiagnosticPullSupported();
+ if (!pushFallbackOnly) {
+ const cached = this.documents.getPullCache(snapshot);
+ try {
+ const remainingMs2 = deadlineAt - Date.now();
+ if (remainingMs2 <= 0)
+ return this.freshnessTimeout(absPath);
+ const result = await this.sendRequest("textDocument/diagnostic", {
+ textDocument: { uri },
+ ...cached?.resultId === undefined ? {} : { previousResultId: cached.resultId }
+ }, { timeoutMs: remainingMs2, ...signal === undefined ? {} : { signal } });
+ if (!this.documents.isCurrentSnapshot(snapshot))
+ continue;
+ const report = this.parseDiagnosticPullReport(result);
+ if (report.type === "full") {
+ this.documents.recordPullDiagnostics(snapshot, {
+ kind: "full",
+ diagnostics: report.diagnostics,
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ });
+ return { items: [...report.diagnostics] };
+ }
+ if (cached !== null && cached.documentVersion === snapshot.version && cached.resultId === report.resultId) {
+ return { items: [...cached.diagnostics] };
+ }
+ } catch (error) {
+ if (this.isUnsupportedDiagnosticPullError(error)) {
+ this.setDiagnosticPullSupported(false);
+ pushFallbackOnly = true;
+ } else if (error instanceof LspRequestTimeoutError) {
+ pushFallbackOnly = true;
+ } else {
+ this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ throw error;
+ }
+ }
+ }
+ if (!pushFallbackOnly)
+ continue;
+ const remainingMs = deadlineAt - Date.now();
+ if (remainingMs <= 0)
+ return this.freshnessTimeout(absPath);
+ const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;
+ await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);
+ }
+ }
+ async prepareRename(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("textDocument/prepareRename", {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character }
+ }, options);
+ }
+ async rename(filePath, line, character, newName, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.openFile(absPath);
+ const acquired = this.workspaceMutations.acquire(signal);
+ if (!acquired.success)
+ return { edit: null, apply: acquired.result };
+ const preCommitSignal = createPreCommitAbortSignal(signal, () => this.workspaceMutations.isBeforeCommit(acquired.lease));
+ try {
+ const renameParams = {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character },
+ newName
+ };
+ const edit = preCommitSignal === undefined ? await this.sendRequest("textDocument/rename", renameParams) : await this.sendRequest("textDocument/rename", renameParams, {
+ signal: preCommitSignal.signal
+ });
+ return await this.workspaceMutations.reconcileRename(acquired.lease, edit);
+ } finally {
+ preCommitSignal?.dispose();
+ this.workspaceMutations.release(acquired.lease);
+ }
+ }
+ resolveWorkspacePath(filePath) {
+ return resolve5(this.root, filePath);
+ }
+}
+function waitForDiagnosticsActivity(wait, signal) {
+ if (!signal)
+ return wait;
+ if (signal.aborted)
+ return Promise.reject(abortError2(signal));
+ return new Promise((resolve6, reject) => {
+ const onAbort = () => {
+ signal.removeEventListener("abort", onAbort);
+ reject(abortError2(signal));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ wait.then(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve6();
+ }, (error) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(error);
+ });
+ });
+}
+function createPreCommitAbortSignal(source, isBeforeCommit) {
+ if (!source)
+ return;
+ const controller = new AbortController;
+ const onAbort = () => {
+ if (isBeforeCommit() && !controller.signal.aborted)
+ controller.abort(preCommitAbortReason(source));
+ };
+ if (source.aborted)
+ onAbort();
+ else
+ source.addEventListener("abort", onAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => source.removeEventListener("abort", onAbort)
+ };
+}
+function preCommitAbortReason(source) {
+ const reason = source.reason;
+ if (reason instanceof Error && reason.name !== "AbortError")
+ return reason;
+ return new Error("LSP request cancelled before workspace edit commit");
+}
+function abortError2(signal) {
+ const reason = signal.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "operation cancelled");
+ error.name = "AbortError";
+ return error;
+}
+
+// ../lsp-core/src/lsp/process-signal-cleanup.ts
+function installProcessSignalCleanup(cleanup) {
+ const signals = process.platform === "win32" ? ["SIGINT", "SIGTERM", "SIGBREAK"] : ["SIGINT", "SIGTERM"];
+ const handler = () => {
+ cleanup().catch((error) => {
+ reportBestEffortCleanupError("signal cleanup", error);
+ });
+ };
+ for (const signal of signals) {
+ process.on(signal, handler);
+ }
+ return () => {
+ for (const signal of signals) {
+ process.removeListener(signal, handler);
+ }
+ };
+}
+
+// ../lsp-core/src/lsp/manager.ts
+async function stopClientBestEffort(client) {
+ try {
+ await client.stop();
+ } catch (error) {
+ reportBestEffortCleanupError("client stop", error);
+ }
+}
+function awaitWithSignal(promise, signal) {
+ if (!signal)
+ return promise;
+ return new Promise((resolve6, reject) => {
+ let settled = false;
+ const onAbort = () => {
+ if (settled)
+ return;
+ settled = true;
+ reject(new DOMException("Aborted", "AbortError"));
+ };
+ if (signal.aborted) {
+ onAbort();
+ return;
+ }
+ signal.addEventListener("abort", onAbort, { once: true });
+ promise.then((value) => {
+ if (settled)
+ return;
+ settled = true;
+ signal.removeEventListener("abort", onAbort);
+ resolve6(value);
+ }, (err) => {
+ if (settled)
+ return;
+ settled = true;
+ signal.removeEventListener("abort", onAbort);
+ reject(err);
+ });
+ });
+}
+
+class LspManager {
+ clients = new Map;
+ reaperHandle = null;
+ signalDisposer = null;
disposed = false;
idleTimeoutMs;
initTimeoutMs;
@@ -1414,6 +3007,177 @@ async function disposeDefaultLspManager() {
}
// src/daemon-client.ts
import { connect as connect2 } from "node:net";
+import { homedir as homedir3 } from "node:os";
+import { join as join7 } from "node:path";
+
+// ../lsp-core/src/request-context.ts
+import { AsyncLocalStorage } from "node:async_hooks";
+import { existsSync as existsSync5, realpathSync as realpathSync3, statSync as statSync2 } from "node:fs";
+import { homedir } from "node:os";
+import { basename as basename2, delimiter as delimiter2, dirname as dirname4, isAbsolute as isAbsolute2, join as join2, relative as relative4, resolve as resolve6 } from "node:path";
+
+class LspRequestContextParseError extends Error {
+ code;
+ name = "LspRequestContextParseError";
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ }
+}
+
+class LspRequestContextUnavailableError extends Error {
+ name = "LspRequestContextUnavailableError";
+ constructor() {
+ super("LSP request context is required. Standalone MCP startup must install one with runWithRequestContext(createStandaloneMcpRequestContext()).");
+ }
+}
+var storage = new AsyncLocalStorage;
+var CONTEXT_FIELDS = new Set(["cwd", "projectConfigPaths", "userConfigPath", "installDecisionsPath", "capabilities"]);
+var CAPABILITY_FIELDS = new Set(["installDecisionTool"]);
+function runWithRequestContext(context, fn) {
+ return storage.run(context, fn);
+}
+function lspRequestContext() {
+ const context = storage.getStore();
+ if (!context)
+ throw new LspRequestContextUnavailableError;
+ return context;
+}
+function contextCwd() {
+ return lspRequestContext().cwd;
+}
+function createStandaloneMcpRequestContext(input = {}) {
+ const env = input.env ?? process.env;
+ const cwd = canonicalCwd(input.cwd ?? process.cwd());
+ const home = input.homeDir ?? homedir();
+ const projectConfigPaths = translateProjectConfigEnv(env["LSP_TOOLS_MCP_PROJECT_CONFIG"], cwd);
+ const userConfigPath = translateHomeConfigEnv(env["LSP_TOOLS_MCP_USER_CONFIG"], home, ".codex/lsp-client.json");
+ const installDecisionsPath = translateHomeConfigEnv(env["LSP_TOOLS_MCP_INSTALL_DECISIONS"], home, ".codex/lsp-install-decisions.json");
+ return parseLspRequestContext({
+ cwd,
+ projectConfigPaths,
+ userConfigPath,
+ installDecisionsPath,
+ capabilities: { installDecisionTool: true }
+ });
+}
+function parseLspRequestContext(value) {
+ if (!isRecord4(value)) {
+ throw new LspRequestContextParseError("invalid_context", "LSP request context must be an object.");
+ }
+ rejectUnknownFields(value, CONTEXT_FIELDS, "context");
+ const cwd = stringField(value, "cwd");
+ const projectConfigPaths = stringArrayField(value, "projectConfigPaths");
+ const userConfigPath = stringField(value, "userConfigPath");
+ const installDecisionsPath = stringField(value, "installDecisionsPath");
+ const capabilities = capabilitiesField(value["capabilities"]);
+ const canonical = canonicalCwd(cwd);
+ for (const path of projectConfigPaths) {
+ requireAbsolutePath(path, "projectConfigPaths");
+ const projectPath = canonicalizeExistingOrNearestAncestor(path);
+ if (!isPathInside(canonical, projectPath)) {
+ throw new LspRequestContextParseError("project_config_outside_cwd", `Project LSP config path must be inside cwd: ${path}`);
+ }
+ }
+ requireAbsolutePath(userConfigPath, "userConfigPath");
+ requireAbsolutePath(installDecisionsPath, "installDecisionsPath");
+ return {
+ cwd: canonical,
+ projectConfigPaths: projectConfigPaths.map((path) => canonicalizeExistingOrNearestAncestor(path)),
+ userConfigPath,
+ installDecisionsPath,
+ capabilities
+ };
+}
+function translateProjectConfigEnv(value, cwd) {
+ if (value === undefined || value.length === 0)
+ return [join2(cwd, ".codex", "lsp-client.json")];
+ return value.split(delimiter2).filter((entry) => entry.length > 0).map((entry) => isAbsolute2(entry) ? entry : join2(cwd, entry));
+}
+function translateHomeConfigEnv(value, home, fallback) {
+ if (value === undefined || value.length === 0)
+ return join2(home, fallback);
+ return isAbsolute2(value) ? value : join2(home, value);
+}
+function canonicalCwd(cwd) {
+ const resolved = resolve6(cwd);
+ if (!existsSync5(resolved) || !statSync2(resolved).isDirectory()) {
+ throw new LspRequestContextParseError("invalid_cwd", `LSP request cwd must be an existing directory: ${cwd}`);
+ }
+ return realpathSync3(resolved);
+}
+function canonicalizeExistingOrNearestAncestor(path) {
+ let current = resolve6(path);
+ const suffix = [];
+ while (true) {
+ try {
+ const existing = realpathSync3(current);
+ return suffix.length === 0 ? existing : join2(existing, ...suffix);
+ } catch (error) {
+ if (!isMissingPathError(error))
+ throw error;
+ const parent = dirname4(current);
+ if (parent === current)
+ throw error;
+ suffix.unshift(basename2(current));
+ current = parent;
+ }
+ }
+}
+function capabilitiesField(value) {
+ if (!isRecord4(value)) {
+ throw new LspRequestContextParseError("invalid_capabilities", "LSP request capabilities must be an object.");
+ }
+ rejectUnknownFields(value, CAPABILITY_FIELDS, "capabilities");
+ const installDecisionTool = value["installDecisionTool"];
+ if (typeof installDecisionTool !== "boolean") {
+ throw new LspRequestContextParseError("invalid_install_decision_capability", "LSP request capabilities.installDecisionTool must be a boolean.");
+ }
+ return { installDecisionTool };
+}
+function stringField(value, field) {
+ const fieldValue = value[field];
+ if (typeof fieldValue !== "string" || fieldValue.length === 0) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string.`);
+ }
+ return fieldValue;
+}
+function stringArrayField(value, field) {
+ const fieldValue = value[field];
+ if (!Array.isArray(fieldValue) || !fieldValue.every((item) => typeof item === "string" && item.length > 0)) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string array.`);
+ }
+ return fieldValue;
+}
+function requireAbsolutePath(path, field) {
+ if (!isAbsolute2(path)) {
+ throw new LspRequestContextParseError("relative_path", `LSP request context.${field} must be absolute: ${path}`);
+ }
+}
+function isPathInside(parent, child) {
+ const childPath = resolve6(child);
+ const relativePath = relative4(parent, childPath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute2(relativePath);
+}
+function isMissingPathError(error) {
+ const code = errorCode(error);
+ return code === "ENOENT" || code === "ENOTDIR";
+}
+function rejectUnknownFields(value, allowed, scope) {
+ const unknown = Object.keys(value).filter((key) => !allowed.has(key));
+ if (unknown.length > 0) {
+ throw new LspRequestContextParseError("unknown_field", `Unknown LSP request ${scope} field: ${unknown.join(", ")}`);
+ }
+}
+function isRecord4(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function errorCode(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
+}
// ../mcp-stdio-core/src/record.ts
function isPlainRecord(value) {
@@ -1422,75 +3186,404 @@ function isPlainRecord(value) {
// src/ensure-daemon.ts
import { spawn as spawn2 } from "node:child_process";
-import { closeSync as closeSync2, existsSync as existsSync2, mkdirSync as mkdirSync2, openSync as openSync2 } from "node:fs";
+import { closeSync as closeSync2, mkdirSync as mkdirSync2, openSync as openSync2 } from "node:fs";
import { connect } from "node:net";
-import { dirname as dirname2 } from "node:path";
+import { dirname as dirname6 } from "node:path";
import { execPath } from "node:process";
-import { fileURLToPath } from "node:url";
-// src/lock.ts
-import { closeSync, mkdirSync, openSync, readFileSync as readFileSync2, unlinkSync, writeSync } from "node:fs";
-import { dirname } from "node:path";
-function isProcessAlive(pid) {
- if (!Number.isInteger(pid) || pid <= 0)
- return false;
+// src/ipc-protocol.ts
+import { randomBytes, timingSafeEqual } from "node:crypto";
+import {
+ chmodSync,
+ closeSync,
+ constants,
+ fchmodSync,
+ fstatSync,
+ lstatSync as lstatSync4,
+ mkdirSync,
+ openSync,
+ readFileSync as readFileSync3,
+ unlinkSync,
+ writeSync
+} from "node:fs";
+import { dirname as dirname5 } from "node:path";
+var OMO_DAEMON_PROTOCOL_VERSION = 1;
+var AUTH_ERROR_CODE = -32001;
+var PROTOCOL_ERROR_CODE = -32002;
+var AUTH_TOKEN_BYTES = 32;
+
+class UnsafePrivateDirectoryError extends Error {
+ path;
+ reason;
+ name = "UnsafePrivateDirectoryError";
+ code = "unsafe_private_directory";
+ constructor(path, reason) {
+ super(`unsafe private directory ${path}: ${reason}`);
+ this.path = path;
+ this.reason = reason;
+ }
+}
+function authEnvelope(token) {
+ return { protocolVersion: OMO_DAEMON_PROTOCOL_VERSION, token };
+}
+function readAuthToken(paths) {
try {
- process.kill(pid, 0);
- return true;
+ const token = readFileSync3(paths.auth, "utf8").trim();
+ return token.length > 0 ? token : null;
} catch (error) {
- return error.code === "EPERM";
+ if (error instanceof Error)
+ return null;
+ throw error;
}
}
-function readLockPid(lockPath) {
+function readOrCreateAuthToken(paths) {
+ const existing = readAuthToken(paths);
+ if (existing)
+ return existing;
+ return createAuthToken(paths);
+}
+function rotateAuthToken(paths) {
try {
- const pid = Number.parseInt(readFileSync2(lockPath, "utf8").trim(), 10);
- return Number.isInteger(pid) ? pid : null;
- } catch {
- return null;
+ unlinkSync(paths.auth);
+ } catch (error) {
+ if (!(error instanceof Error))
+ throw error;
}
+ return createAuthToken(paths);
}
-function tryAcquireLock(lockPath, ownerPid = process.pid) {
- mkdirSync(dirname(lockPath), { recursive: true });
- for (let attempt = 0;attempt < 2; attempt += 1) {
- const handle = writeLockFile(lockPath, ownerPid);
- if (handle)
- return handle;
- if (!reapStaleLock(lockPath))
- return null;
+function authenticateMessage(raw, expectedToken) {
+ const id = jsonRpcId(raw);
+ if (!isPlainRecord(raw))
+ return authError(id);
+ const params = raw["params"];
+ if (!isPlainRecord(params))
+ return authError(id);
+ const envelope = params["_omo"];
+ if (!isPlainRecord(envelope))
+ return authError(id);
+ const protocolVersion = envelope["protocolVersion"];
+ if (protocolVersion !== OMO_DAEMON_PROTOCOL_VERSION)
+ return protocolError(id);
+ const token = envelope["token"];
+ if (typeof token !== "string" || !tokenMatches(token, expectedToken))
+ return authError(id);
+ const cleanParams = { ...params };
+ delete cleanParams["_omo"];
+ return { input: { ...raw, params: cleanParams }, id, method: typeof raw["method"] === "string" ? raw["method"] : undefined };
+}
+function isAuthErrorResponse(message) {
+ if (!isPlainRecord(message))
+ return false;
+ const error = message["error"];
+ if (!isPlainRecord(error))
+ return false;
+ const data = error["data"];
+ return error["code"] === AUTH_ERROR_CODE && isPlainRecord(data) && data["code"] === "daemon_authentication_failed";
+}
+function writePrivateFile(path, data) {
+ const fd = openSync(path, "w", 384);
+ try {
+ writeSync(fd, data);
+ } finally {
+ closeSync(fd);
}
- return null;
+ setPrivateFileMode(path);
}
-function writeLockFile(lockPath, ownerPid) {
+function ensurePrivateDirectory(path, options = {}) {
try {
- const fd = openSync(lockPath, "wx");
- writeSync(fd, `${ownerPid}
-`);
+ mkdirSync(path, { recursive: true, mode: 448 });
+ } catch (error) {
+ if (errorCode2(error) !== "EEXIST")
+ throw error;
+ }
+ if (process.platform === "win32")
+ return;
+ const before = validatePrivateDirectory(path, options);
+ const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
+ try {
+ fchmodSync(fd, 448);
+ const after = validatePrivateDirectory(path, options);
+ const openStats = fstatSync(fd);
+ if (!sameDirectory(before, after) || !sameDirectory(before, openStats)) {
+ throw new UnsafePrivateDirectoryError(path, "changed_during_chmod");
+ }
+ } finally {
closeSync(fd);
- return { release: () => unlinkQuietly(lockPath) };
+ }
+}
+function setPrivateFileMode(path) {
+ if (process.platform !== "win32")
+ chmodSync(path, 384);
+}
+function createAuthToken(paths) {
+ ensurePrivateDirectory(dirname5(paths.auth));
+ const token = randomBytes(AUTH_TOKEN_BYTES).toString("base64url");
+ let fd;
+ try {
+ fd = openSync(paths.auth, "wx", 384);
} catch (error) {
- if (error.code === "EEXIST")
- return null;
+ if (errorCode2(error) === "EEXIST") {
+ const existing = readAuthToken(paths);
+ if (existing)
+ return existing;
+ }
throw error;
}
+ try {
+ writeSync(fd, `${token}
+`);
+ } finally {
+ closeSync(fd);
+ }
+ setPrivateFileMode(paths.auth);
+ return token;
}
-function reapStaleLock(lockPath) {
- const pid = readLockPid(lockPath);
- if (pid !== null && isProcessAlive(pid))
- return false;
- unlinkQuietly(lockPath);
- return true;
+function errorCode2(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
+}
+function validatePrivateDirectory(path, options) {
+ const stats = options.lstat ? options.lstat(path) : lstatPrivateDirectory(path);
+ if (stats.isSymbolicLink())
+ throw new UnsafePrivateDirectoryError(path, "symlink");
+ if (!stats.isDirectory())
+ throw new UnsafePrivateDirectoryError(path, "not_directory");
+ const currentUid = options.currentUid ? options.currentUid() : process.getuid?.();
+ if (currentUid !== undefined && stats.uid !== currentUid) {
+ throw new UnsafePrivateDirectoryError(path, "wrong_owner");
+ }
+ return stats;
+}
+function lstatPrivateDirectory(path) {
+ return lstatSync4(path);
+}
+function sameDirectory(a, b) {
+ return a.dev === b.dev && a.ino === b.ino;
+}
+function tokenMatches(candidate, expected) {
+ const candidateBytes = Buffer.from(candidate);
+ const expectedBytes = Buffer.from(expected);
+ return candidateBytes.length === expectedBytes.length && timingSafeEqual(candidateBytes, expectedBytes);
+}
+function jsonRpcId(raw) {
+ if (!isPlainRecord(raw))
+ return null;
+ const id = raw["id"];
+ return typeof id === "string" || typeof id === "number" || id === null ? id : null;
+}
+function authError(id) {
+ return {
+ jsonrpc: "2.0",
+ id,
+ error: { code: AUTH_ERROR_CODE, message: "daemon authentication failed", data: { code: "daemon_authentication_failed" } }
+ };
+}
+function protocolError(id) {
+ return {
+ jsonrpc: "2.0",
+ id,
+ error: { code: PROTOCOL_ERROR_CODE, message: "daemon protocol mismatch", data: { code: "daemon_protocol_mismatch" } }
+ };
+}
+
+// src/paths.ts
+import { createHash as createHash2 } from "node:crypto";
+import { createRequire } from "node:module";
+import { homedir as homedir2, tmpdir, userInfo } from "node:os";
+import * as path from "node:path";
+import { fileURLToPath as fileURLToPath2 } from "node:url";
+
+// src/runtime-contract.ts
+import { statSync as statSync3 } from "node:fs";
+import { isAbsolute as isAbsolute3 } from "node:path";
+var OMO_LSP_DAEMON_DIR = "OMO_LSP_DAEMON_DIR";
+var OMO_LSP_DAEMON_CLI = "OMO_LSP_DAEMON_CLI";
+var OMO_LSP_DAEMON_VERSION = "OMO_LSP_DAEMON_VERSION";
+var DAEMON_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
+
+class InvalidRuntimeOverrideError extends Error {
+ code = "invalid_runtime_override";
+ reason;
+ constructor(reason, message) {
+ super(message);
+ this.name = "InvalidRuntimeOverrideError";
+ this.reason = reason;
+ }
}
-function unlinkQuietly(path) {
+
+class InvalidDaemonVersionError extends Error {
+ code = "invalid_daemon_version";
+ version;
+ constructor(version) {
+ super("LSP daemon version must match [A-Za-z0-9][A-Za-z0-9._+-]{0,127}");
+ this.name = "InvalidDaemonVersionError";
+ this.version = version;
+ }
+}
+function validateDaemonVersion(version) {
+ if (!DAEMON_VERSION_PATTERN.test(version))
+ throw new InvalidDaemonVersionError(version);
+ return version;
+}
+function resolveDaemonRuntime(env, defaults) {
+ const cliOverride = env[OMO_LSP_DAEMON_CLI];
+ const versionOverride = env[OMO_LSP_DAEMON_VERSION];
+ const hasCliOverride = cliOverride !== undefined;
+ const hasVersionOverride = versionOverride !== undefined;
+ if (hasCliOverride !== hasVersionOverride) {
+ throw new InvalidRuntimeOverrideError("paired_values_required", `${OMO_LSP_DAEMON_CLI} and ${OMO_LSP_DAEMON_VERSION} must be set together`);
+ }
+ if (!hasCliOverride || !hasVersionOverride) {
+ if (!isAbsolute3(defaults.cliPath)) {
+ throw new InvalidRuntimeOverrideError("packaged_cli_must_be_absolute", "Packaged LSP daemon CLI path must be absolute");
+ }
+ return { cliPath: defaults.cliPath, version: validateDaemonVersion(defaults.version) };
+ }
+ if (!isAbsolute3(cliOverride)) {
+ throw new InvalidRuntimeOverrideError("cli_must_be_absolute", `${OMO_LSP_DAEMON_CLI} must be an absolute path to an existing regular file`);
+ }
+ let cliStats;
try {
- unlinkSync(path);
- } catch (error) {}
+ cliStats = statSync3(cliOverride);
+ } catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ throw new InvalidRuntimeOverrideError("cli_not_found", `${OMO_LSP_DAEMON_CLI} must name an existing regular file`);
+ }
+ if (!cliStats.isFile()) {
+ throw new InvalidRuntimeOverrideError("cli_not_file", `${OMO_LSP_DAEMON_CLI} must name an existing regular file`);
+ }
+ return { cliPath: cliOverride, version: validateDaemonVersion(versionOverride) };
+}
+
+// src/paths.ts
+var requireFromHere = createRequire(import.meta.url);
+var MAX_SOCKET_PATH_LENGTH = 100;
+
+class InvalidDaemonDirectoryError extends Error {
+ code = "invalid_daemon_directory";
+ directory;
+ constructor(directory) {
+ super(`${OMO_LSP_DAEMON_DIR} must be an absolute path`);
+ this.name = "InvalidDaemonDirectoryError";
+ this.directory = directory;
+ }
+}
+function resolveDaemonVersion(requireFn = requireFromHere) {
+ for (const candidate of ["./package.json", "../package.json"]) {
+ let loaded;
+ try {
+ loaded = requireFn(candidate);
+ } catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ continue;
+ }
+ if (typeof loaded === "object" && loaded !== null && "version" in loaded) {
+ const version = Reflect.get(loaded, "version");
+ if (typeof version === "string")
+ return validateDaemonVersion(version);
+ }
+ }
+ return "0";
+}
+function packagedRuntimeDefaults() {
+ return {
+ cliPath: fileURLToPath2(new URL("./cli.js", import.meta.url)),
+ version: resolveDaemonVersion()
+ };
+}
+function daemonBaseDir(env = process.env, platform = defaultDaemonPlatform()) {
+ const override = env[OMO_LSP_DAEMON_DIR];
+ if (override !== undefined) {
+ if (!platform.path.isAbsolute(override))
+ throw new InvalidDaemonDirectoryError(override);
+ return platform.path.resolve(override);
+ }
+ return platform.path.resolve(platform.path.join(platform.homedir(), ".omo", "lsp-daemon"));
+}
+function daemonPaths(env = process.env, runtimeDefaults = packagedRuntimeDefaults(), platform = defaultDaemonPlatform()) {
+ const runtime = resolveDaemonRuntime(env, runtimeDefaults);
+ const baseDir = daemonBaseDir(env, platform);
+ const dir = platform.path.resolve(platform.path.join(baseDir, `v${runtime.version}`));
+ return {
+ version: runtime.version,
+ cliPath: runtime.cliPath,
+ dir,
+ socket: resolveSocketPath(dir, runtime.version, platform),
+ lock: platform.path.join(dir, "daemon.lock"),
+ pid: platform.path.join(dir, "daemon.pid"),
+ auth: platform.path.join(dir, "daemon.auth"),
+ endpoint: platform.path.join(dir, "daemon.endpoint"),
+ owner: platform.path.join(dir, "daemon.owner"),
+ log: platform.path.join(dir, "daemon.log")
+ };
+}
+function defaultDaemonPlatform() {
+ return {
+ platform: process.platform,
+ homedir: homedir2,
+ tmpdir,
+ getuid: () => typeof process.getuid === "function" ? process.getuid() : undefined,
+ username: () => userInfo().username,
+ path
+ };
+}
+function resolveSocketPath(dir, version, platform) {
+ const canonicalVersionDir = platform.path.resolve(dir);
+ if (platform.platform === "win32") {
+ const currentUserDiscriminator = `${platform.getuid() ?? "win"}:${platform.username()}:${platform.path.resolve(platform.homedir())}`;
+ const digest = shortDigest(`${canonicalVersionDir}\x00${currentUserDiscriminator}`);
+ return `\\\\.\\pipe\\omo-lsp-${version}-${digest}`;
+ }
+ const natural = platform.path.join(canonicalVersionDir, "daemon.sock");
+ if (natural.length < MAX_SOCKET_PATH_LENGTH)
+ return natural;
+ return platform.path.join(platform.tmpdir(), `omo-lsp-${version}-${shortDigest(canonicalVersionDir)}`, "daemon.sock");
+}
+function shortDigest(value) {
+ return createHash2("sha256").update(value).digest("hex").slice(0, 16);
+}
+
+// src/socket-jsonrpc.ts
+function encodeJsonLine(message) {
+ return `${JSON.stringify(message)}
+`;
+}
+function createLineDecoder(onMessage, onParseError) {
+ let buffer = "";
+ return {
+ push(chunk) {
+ buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ let index = buffer.indexOf(`
+`);
+ while (index !== -1) {
+ const raw = buffer.slice(0, index).trim();
+ buffer = buffer.slice(index + 1);
+ if (raw.length > 0) {
+ try {
+ onMessage(JSON.parse(raw));
+ } catch (error) {
+ if (error instanceof Error) {
+ onParseError?.(raw, error);
+ } else {
+ throw error;
+ }
+ }
+ }
+ index = buffer.indexOf(`
+`);
+ }
+ }
+ };
}
// src/ensure-daemon.ts
var PROBE_TIMEOUT_MS = 500;
var DEFAULT_READY_TIMEOUT_MS = 5000;
var DEFAULT_POLL_INTERVAL_MS = 100;
-var CODEX_LSP_DAEMON_CLI_ENV = "CODEX_LSP_DAEMON_CLI";
class DaemonUnreachableError extends Error {
constructor(socketPath) {
@@ -1498,61 +3591,62 @@ class DaemonUnreachableError extends Error {
this.name = "DaemonUnreachableError";
}
}
-async function ensureDaemonRunning(paths, deps = defaultEnsureDaemonDeps(), options = {}) {
- const readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
- const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
- if (await deps.probe(paths.socket))
- return;
- const lock = deps.acquireLock(paths.lock);
- if (!lock) {
- await waitUntilReachable(paths.socket, deps, readyTimeoutMs, pollIntervalMs);
- return;
- }
- try {
- if (await deps.probe(paths.socket))
- return;
- deps.cleanupStaleSocket(paths.socket);
- deps.spawnDaemon(paths);
- await waitUntilReachable(paths.socket, deps, readyTimeoutMs, pollIntervalMs);
- } finally {
- lock.release();
- }
-}
-async function waitUntilReachable(socketPath, deps, readyTimeoutMs, pollIntervalMs) {
+async function ensureDaemonRunning(paths, deps = defaultEnsureDaemonDeps(), options = {}) {
+ const readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
+ const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
+ if (await deps.probe(paths))
+ return;
+ deps.spawnDaemon(paths);
+ await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs);
+}
+async function waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs) {
const deadline = deps.now() + readyTimeoutMs;
for (;; ) {
- if (await deps.probe(socketPath))
+ if (await deps.probe(paths))
return;
if (deps.now() >= deadline)
- throw new DaemonUnreachableError(socketPath);
+ throw new DaemonUnreachableError(paths.socket);
await deps.sleep(pollIntervalMs);
}
}
-function probeSocket(socketPath, timeoutMs = PROBE_TIMEOUT_MS) {
- return new Promise((resolve2) => {
- const socket = connect(socketPath);
- const finish = (ok) => {
+async function probeDaemon(paths, timeoutMs = PROBE_TIMEOUT_MS) {
+ const token = readAuthToken(paths);
+ if (!token)
+ return false;
+ return await pingDaemon(paths, token, timeoutMs) !== null;
+}
+function pingDaemon(paths, token, timeoutMs = PROBE_TIMEOUT_MS) {
+ return new Promise((resolve7) => {
+ const socket = connect(paths.socket);
+ let settled = false;
+ const finish = (value) => {
+ if (settled)
+ return;
+ settled = true;
socket.destroy();
- resolve2(ok);
+ resolve7(value);
};
- const timer = setTimeout(() => finish(false), timeoutMs);
+ const timer = setTimeout(() => finish(null), timeoutMs);
timer.unref?.();
- socket.once("connect", () => {
+ const decoder = createLineDecoder((message) => {
clearTimeout(timer);
- finish(true);
+ finish(parsePingResponse(message));
+ });
+ socket.once("connect", () => {
+ socket.write(encodeJsonLine({ jsonrpc: "2.0", id: 1, method: "omo/ping", params: { _omo: authEnvelope(token) } }));
});
+ socket.on("data", (chunk) => decoder.push(chunk));
socket.once("error", () => {
clearTimeout(timer);
- finish(false);
+ finish(null);
});
});
}
function spawnDaemonProcess(paths) {
- mkdirSync2(dirname2(paths.log), { recursive: true });
+ mkdirSync2(dirname6(paths.log), { recursive: true });
const logFd = openSync2(paths.log, "a");
try {
- const cliPath = resolveDaemonCliPath();
- const child = spawn2(execPath, [cliPath, "daemon"], {
+ const child = spawn2(execPath, [paths.cliPath, "daemon"], {
detached: true,
stdio: ["ignore", logFd, logFd]
});
@@ -1561,81 +3655,44 @@ function spawnDaemonProcess(paths) {
closeSync2(logFd);
}
}
-function resolveDaemonCliPath(env = process.env) {
- const override = env[CODEX_LSP_DAEMON_CLI_ENV]?.trim();
- if (override)
- return override;
- return fileURLToPath(new URL("./cli.js", import.meta.url));
-}
function defaultEnsureDaemonDeps() {
return {
- probe: (socketPath) => probeSocket(socketPath),
- acquireLock: (lockPath) => tryAcquireLock(lockPath),
- cleanupStaleSocket: (socketPath) => {
- if (existsSync2(socketPath))
- unlinkQuietly(socketPath);
- },
+ probe: (paths) => probeDaemon(paths),
spawnDaemon: (paths) => spawnDaemonProcess(paths),
- sleep: (ms) => new Promise((resolve2) => {
- setTimeout(resolve2, ms);
+ sleep: (ms) => new Promise((resolve7) => {
+ setTimeout(resolve7, ms);
}),
now: () => Date.now()
};
}
-
-// src/paths.ts
-import { createHash } from "node:crypto";
-import { createRequire } from "node:module";
-import { homedir, tmpdir } from "node:os";
-import { join as join2 } from "node:path";
-var requireFromHere = createRequire(import.meta.url);
-var MAX_SOCKET_PATH_LENGTH = 100;
-var CODEX_LSP_DAEMON_VERSION_ENV = "CODEX_LSP_DAEMON_VERSION";
-function resolveDaemonVersion(requireFn = requireFromHere) {
- for (const candidate of ["./package.json", "../package.json"]) {
- try {
- const pkg = requireFn(candidate);
- if (typeof pkg.version === "string" && pkg.version.length > 0)
- return pkg.version;
- } catch {}
- }
- return "0";
-}
-function daemonBaseDir(env = process.env) {
- const explicit = env["CODEX_LSP_DAEMON_DIR"]?.trim();
- if (explicit)
- return explicit;
- const pluginData = env["PLUGIN_DATA"]?.trim();
- if (pluginData)
- return join2(pluginData, "daemon");
- const codexHome = env["CODEX_HOME"]?.trim();
- const home = codexHome && codexHome.length > 0 ? codexHome : join2(homedir(), ".codex");
- return join2(home, "codex-lsp", "daemon");
-}
-function daemonPaths(env = process.env, version = resolveDaemonVersionFromEnv(env) ?? resolveDaemonVersion()) {
- const dir = join2(daemonBaseDir(env), `v${version}`);
- return {
- version,
- dir,
- socket: resolveSocketPath(dir, version),
- lock: join2(dir, "daemon.lock"),
- pid: join2(dir, "daemon.pid"),
- log: join2(dir, "daemon.log")
- };
-}
-function resolveDaemonVersionFromEnv(env = process.env) {
- const version = env[CODEX_LSP_DAEMON_VERSION_ENV]?.trim();
- return version && version.length > 0 ? version : null;
-}
-function resolveSocketPath(dir, version) {
- const digest = createHash("sha256").update(dir).digest("hex").slice(0, 16);
- if (process.platform === "win32") {
- return `\\\\.\\pipe\\omo-lsp-${version}-${digest}`;
+function parsePingResponse(message) {
+ if (!message || typeof message !== "object" || Array.isArray(message))
+ return null;
+ const result = Reflect.get(message, "result");
+ if (!result || typeof result !== "object" || Array.isArray(result))
+ return null;
+ const pid = Reflect.get(result, "pid");
+ const nonce = Reflect.get(result, "nonce");
+ const startedAt = Reflect.get(result, "startedAt");
+ const endpoint = Reflect.get(result, "endpoint");
+ if (typeof pid !== "number" || typeof nonce !== "string" || typeof startedAt !== "string")
+ return null;
+ if (!endpoint || typeof endpoint !== "object" || Array.isArray(endpoint))
+ return null;
+ const path2 = Reflect.get(endpoint, "path");
+ const kind = Reflect.get(endpoint, "kind");
+ if (typeof path2 !== "string")
+ return null;
+ if (kind === "windows")
+ return { pid, nonce, startedAt, endpoint: { kind, path: path2 } };
+ if (kind === "missing")
+ return { pid, nonce, startedAt, endpoint: { kind, path: path2 } };
+ const dev = Reflect.get(endpoint, "dev");
+ const ino = Reflect.get(endpoint, "ino");
+ if (kind === "unix" && typeof dev === "number" && typeof ino === "number") {
+ return { pid, nonce, startedAt, endpoint: { kind, path: path2, dev, ino } };
}
- const natural = join2(dir, "daemon.sock");
- if (natural.length < MAX_SOCKET_PATH_LENGTH)
- return natural;
- return join2(tmpdir(), `omo-lsp-${version}-${digest}.sock`);
+ return null;
}
// ../mcp-stdio-core/src/responses.ts
function successResponse(id, result) {
@@ -1644,12 +3701,9 @@ function successResponse(id, result) {
function errorResponse(id, code, message, data) {
return { jsonrpc: "2.0", id, error: data === undefined ? { code, message } : { code, message, data } };
}
-function jsonRpcId(value) {
+function jsonRpcId2(value) {
return typeof value === "string" || typeof value === "number" || value === null ? value : null;
}
-function messageFromError(error) {
- return error instanceof Error ? error.message : String(error);
-}
// ../mcp-stdio-core/src/transport.ts
var HEADER_SEPARATOR2 = Buffer.from(`\r
\r
@@ -1796,7 +3850,7 @@ function handleParseError(message, config, log) {
}
async function handleRequest(message, config, log) {
const parsed = message.payload;
- const id = isPlainRecord(parsed) ? jsonRpcId(parsed["id"]) : null;
+ const id = isPlainRecord(parsed) ? jsonRpcId2(parsed["id"]) : null;
const method = isPlainRecord(parsed) && typeof parsed["method"] === "string" ? parsed["method"] : null;
log("request", { id: id === null ? null : String(id), method });
try {
@@ -1836,29 +3890,22 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {
closed: () => isClosed
};
}
-// ../lsp-core/src/tools/diagnostics.ts
-import { resolve as resolve4 } from "node:path";
-
// ../lsp-core/src/lsp/client-wrapper.ts
-import { existsSync as existsSync6, statSync as statSync2 } from "node:fs";
-import { dirname as dirname4, join as join6, resolve as resolve2 } from "node:path";
+import { existsSync as existsSync9, statSync as statSync4 } from "node:fs";
+import { dirname as dirname8, join as join4, resolve as resolve7 } from "node:path";
// ../lsp-core/src/lsp/server-install-state.ts
-import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync, writeFileSync } from "node:fs";
-import { homedir as homedir2 } from "node:os";
-import { dirname as dirname3, isAbsolute, join as join3 } from "node:path";
+import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
+import { dirname as dirname7 } from "node:path";
function getInstallDecisionsPath() {
- const override = contextEnv("LSP_TOOLS_MCP_INSTALL_DECISIONS");
- if (!override)
- return join3(homedir2(), ".codex", "lsp-install-decisions.json");
- return isAbsolute(override) ? override : join3(homedir2(), override);
+ return lspRequestContext().installDecisionsPath;
}
function loadInstallDecisions() {
- const path = getInstallDecisionsPath();
- if (!existsSync3(path))
+ const path2 = getInstallDecisionsPath();
+ if (!existsSync6(path2))
return {};
try {
- const parsed = JSON.parse(readFileSync3(path, "utf8"));
+ const parsed = JSON.parse(readFileSync4(path2, "utf8"));
return isInstallDecisions(parsed) ? parsed : {};
} catch {
return {};
@@ -1876,29 +3923,27 @@ function isInstallDecision(value) {
return value === "declined" || value === "allowed";
}
function writeInstallDecisions(decisions) {
- const path = getInstallDecisionsPath();
- mkdirSync3(dirname3(path), { recursive: true });
- const tmpPath = `${path}.tmp`;
- writeFileSync(tmpPath, `${JSON.stringify(decisions, null, 2)}
+ const path2 = getInstallDecisionsPath();
+ mkdirSync3(dirname7(path2), { recursive: true });
+ const tmpPath = `${path2}.tmp`;
+ writeFileSync2(tmpPath, `${JSON.stringify(decisions, null, 2)}
`, "utf8");
- renameSync(tmpPath, path);
+ renameSync2(tmpPath, path2);
}
function isInstallDecisions(value) {
- return isRecord2(value) && Object.values(value).every(isInstallDecisionRecord);
+ return isRecord5(value) && Object.values(value).every(isInstallDecisionRecord);
}
function isInstallDecisionRecord(value) {
- if (!isRecord2(value))
+ if (!isRecord5(value))
return false;
return isInstallDecision(value["decision"]) && typeof value["decidedAt"] === "string";
}
-function isRecord2(value) {
+function isRecord5(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
// ../lsp-core/src/lsp/config-loader.ts
-import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
-import { homedir as homedir3 } from "node:os";
-import { delimiter as delimiter2, isAbsolute as isAbsolute2, join as join4 } from "node:path";
+import { existsSync as existsSync7, readFileSync as readFileSync5 } from "node:fs";
// ../lsp-core/src/lsp/server-definitions.ts
var LSP_INSTALL_HINTS = {
@@ -2048,27 +4093,17 @@ var BUILTIN_SERVERS = {
};
// ../lsp-core/src/lsp/config-loader.ts
-function resolveProjectConfigPath(path) {
- return isAbsolute2(path) ? path : join4(contextCwd(), path);
-}
function getProjectConfigPaths() {
- const projectOverride = contextEnv("LSP_TOOLS_MCP_PROJECT_CONFIG");
- if (projectOverride) {
- return projectOverride.split(delimiter2).filter(Boolean).map(resolveProjectConfigPath);
- }
- return [join4(contextCwd(), ".codex", "lsp-client.json")];
+ return lspRequestContext().projectConfigPaths;
}
function getUserConfigPath() {
- const userOverride = contextEnv("LSP_TOOLS_MCP_USER_CONFIG");
- if (!userOverride)
- return join4(homedir3(), ".codex", "lsp-client.json");
- return isAbsolute2(userOverride) ? userOverride : join4(homedir3(), userOverride);
+ return lspRequestContext().userConfigPath;
}
-function loadJsonFile(path) {
- if (!existsSync4(path))
+function loadJsonFile(path2) {
+ if (!existsSync7(path2))
return null;
try {
- const parsed = JSON.parse(readFileSync4(path, "utf-8"));
+ const parsed = JSON.parse(readFileSync5(path2, "utf-8"));
return isConfigJson(parsed) ? parsed : null;
} catch {
return null;
@@ -2085,8 +4120,8 @@ function loadAllConfigs() {
return configs;
}
function loadFirstJsonFile(paths) {
- for (const path of paths) {
- const config = loadJsonFile(path);
+ for (const path2 of paths) {
+ const config = loadJsonFile(path2);
if (config)
return config;
}
@@ -2207,16 +4242,16 @@ function applyOptionalServerFields(server2, entry) {
}
}
function isConfigJson(value) {
- if (!isRecord3(value))
+ if (!isRecord6(value))
return false;
const lsp = value["lsp"];
- return lsp === undefined || isRecord3(lsp);
+ return lsp === undefined || isRecord6(lsp);
}
function parseLspEntry(value) {
return isLspEntry(value) ? value : null;
}
function isLspEntry(value) {
- if (!isRecord3(value))
+ if (!isRecord6(value))
return false;
const disabled = value["disabled"];
const command = value["command"];
@@ -2224,15 +4259,15 @@ function isLspEntry(value) {
const priority = value["priority"];
const env = value["env"];
const initialization = value["initialization"];
- return (disabled === undefined || typeof disabled === "boolean") && (command === undefined || isStringArray(command)) && (extensions === undefined || isStringArray(extensions)) && (priority === undefined || typeof priority === "number") && (env === undefined || isStringRecord(env)) && (initialization === undefined || isRecord3(initialization));
+ return (disabled === undefined || typeof disabled === "boolean") && (command === undefined || isStringArray(command)) && (extensions === undefined || isStringArray(extensions)) && (priority === undefined || typeof priority === "number") && (env === undefined || isStringRecord(env)) && (initialization === undefined || isRecord6(initialization));
}
function isStringArray(value) {
return Array.isArray(value) && value.every((item) => typeof item === "string");
}
function isStringRecord(value) {
- return isRecord3(value) && Object.values(value).every((item) => typeof item === "string");
+ return isRecord6(value) && Object.values(value).every((item) => typeof item === "string");
}
-function isRecord3(value) {
+function isRecord6(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function getDisabledServerIds() {
@@ -2253,8 +4288,8 @@ function getDisabledServerIds() {
}
// ../lsp-core/src/lsp/server-installation.ts
-import { existsSync as existsSync5 } from "node:fs";
-import { delimiter as delimiter3, join as join5 } from "node:path";
+import { existsSync as existsSync8 } from "node:fs";
+import { delimiter as delimiter3, join as join3 } from "node:path";
function isServerInstalled(command, _workingDirectory) {
if (command.length === 0)
return false;
@@ -2262,7 +4297,7 @@ function isServerInstalled(command, _workingDirectory) {
if (!cmd)
return false;
if (cmd.includes("/") || cmd.includes("\\")) {
- if (existsSync5(cmd))
+ if (existsSync8(cmd))
return true;
}
const isWindows = process.platform === "win32";
@@ -2283,7 +4318,7 @@ function isServerInstalled(command, _workingDirectory) {
const paths = pathEnv.split(delimiter3);
for (const p of paths) {
for (const suffix of exts) {
- if (existsSync5(join5(p, cmd + suffix))) {
+ if (existsSync8(join3(p, cmd + suffix))) {
return true;
}
}
@@ -2382,39 +4417,50 @@ function getAllServers() {
var WORKSPACE_MARKERS = [".git", "package.json", "pyproject.toml", "Cargo.toml", "go.mod", "pom.xml", "build.gradle"];
function isDirectoryPath(filePath) {
try {
- return statSync2(filePath).isDirectory();
+ return statSync4(filePath).isDirectory();
} catch {
return false;
}
}
function findWorkspaceRoot(filePath) {
- const abs = resolve2(contextCwd(), filePath);
+ const abs = resolvePathInsideContext(filePath);
let dir = abs;
if (!isDirectoryPath(dir)) {
- dir = dirname4(dir);
+ dir = dirname8(dir);
}
let prevDir = "";
while (dir !== prevDir) {
for (const marker of WORKSPACE_MARKERS) {
- if (existsSync6(join6(dir, marker))) {
+ if (existsSync9(join4(dir, marker))) {
return dir;
}
}
prevDir = dir;
- dir = dirname4(dir);
+ dir = dirname8(dir);
+ }
+ return dirname8(abs);
+}
+function resolvePathInsideContext(filePath) {
+ const cwd = contextCwd();
+ const abs = resolve7(cwd, filePath);
+ const canonical = canonicalizeExistingOrNearestAncestor(abs);
+ if (!isPathInside(cwd, canonical)) {
+ throw new LspInvalidPathError(`LSP file path must be inside request cwd: ${filePath}`);
}
- return dirname4(abs);
+ return canonical;
}
function formatServerLookupError(result) {
if (result.status === "not_installed") {
return formatNotInstalled(result);
}
+ const context = lspRequestContext();
+ const firstProjectConfigPath = context.projectConfigPaths[0] ?? "<project lsp config>";
return [
`No LSP server configured for extension: ${result.extension}`,
"",
`Available servers: ${result.availableServers.slice(0, 10).join(", ")}${result.availableServers.length > 10 ? "..." : ""}`,
"",
- "Configure a custom server in '.codex/lsp-client.json':",
+ `Configure a custom server in '${firstProjectConfigPath}' or '${context.userConfigPath}':`,
" {",
' "lsp": {',
' "my-server": {',
@@ -2430,6 +4476,7 @@ function formatNotInstalled(result) {
const { server: server2, installHint } = result;
const extensions = server2.extensions.join(", ");
const decision = loadInstallDecision(server2.id)?.decision;
+ const context = lspRequestContext();
if (decision === "declined") {
return `LSP server '${server2.id}' (${extensions}) is NOT INSTALLED; user previously declined installation — proceed without LSP.`;
}
@@ -2445,6 +4492,17 @@ function formatNotInstalled(result) {
"The user has pre-authorized LSP installation. Run the install command, then retry this tool:",
` ${installHint}`
].join(`
+`);
+ }
+ if (!context.capabilities.installDecisionTool) {
+ return [
+ ...header,
+ "To install, run:",
+ ` ${installHint}`,
+ "",
+ "ACTION REQUIRED — ASK THE USER whether to install this LSP server.",
+ "Install-decision recording is unavailable in this harness; proceed without LSP if the user declines."
+ ].join(`
`);
}
return [
@@ -2456,6 +4514,7 @@ function formatNotInstalled(result) {
"- If the user agrees: run the install command above, then retry this tool.",
"- If the user declines, OR has NOT explicitly asked for LSP installation:",
` call lsp_install_decision { server_id: "${server2.id}", decision: "declined" },`,
+ ` which writes to ${context.installDecisionsPath},`,
" then ignore this message and proceed WITHOUT LSP."
].join(`
`);
@@ -2469,14 +4528,14 @@ var READ_ONLY_RETRY_TOOLS = new Set([
"prepareRename"
]);
async function withLspClient(filePath, fn, toolName, options = {}) {
- const absPath = resolve2(contextCwd(), filePath);
+ const absPath = resolvePathInsideContext(filePath);
if (isDirectoryPath(absPath)) {
throw new LspInvalidPathError("Directory paths are not supported by this LSP tool. " + "Use lsp.diagnostics with a directory path for directory diagnostics.");
}
const ext = effectiveExtension(absPath);
const result = findServerForExtension(ext);
if (result.status !== "found") {
- throw new LspServerLookupError(formatServerLookupError(result));
+ throw new LspServerLookupError(formatServerLookupError(result), result);
}
const server2 = result.server;
const root = findWorkspaceRoot(absPath);
@@ -2504,11 +4563,11 @@ async function withLspClient(filePath, fn, toolName, options = {}) {
}
// ../lsp-core/src/lsp/directory-diagnostics.ts
-import { existsSync as existsSync7, lstatSync, readdirSync } from "node:fs";
-import { join as join7, resolve as resolve3 } from "node:path";
+import { existsSync as existsSync10, lstatSync as lstatSync5, readdirSync as readdirSync3 } from "node:fs";
+import { join as join5, resolve as resolve8 } from "node:path";
// ../lsp-core/src/lsp/formatters.ts
-import { fileURLToPath as fileURLToPath2 } from "node:url";
+import { fileURLToPath as fileURLToPath3 } from "node:url";
var DIAGNOSTIC_SEVERITY_FILTERS = {
error: 1,
warning: 2,
@@ -2516,7 +4575,7 @@ var DIAGNOSTIC_SEVERITY_FILTERS = {
hint: 4
};
function uriToPath(uri) {
- return fileURLToPath2(uri);
+ return fileURLToPath3(uri);
}
function formatLocation(loc) {
if ("targetUri" in loc) {
@@ -2602,6 +4661,9 @@ function formatApplyResult(result) {
for (const file of result.filesModified) {
lines.push(` - ${file}`);
}
+ if (result.lateAbort) {
+ lines.push("Cancellation arrived after the filesystem commit began; the committed edit completed.");
+ }
} else {
lines.push("Failed to apply some changes:");
for (const err of result.errors) {
@@ -2617,6 +4679,7 @@ function formatApplyResult(result) {
// ../lsp-core/src/lsp/directory-diagnostics.ts
var SKIP_DIRECTORIES = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
+var DIRECTORY_DIAGNOSTICS_MAX_CONCURRENCY = 4;
function collectFilesWithExtension(dir, extension, maxFiles) {
const files = [];
function walk(currentDir) {
@@ -2624,17 +4687,17 @@ function collectFilesWithExtension(dir, extension, maxFiles) {
return;
let entries = [];
try {
- entries = readdirSync(currentDir);
+ entries = readdirSync3(currentDir);
} catch {
return;
}
for (const entry of entries) {
if (files.length >= maxFiles)
return;
- const fullPath = join7(currentDir, entry);
+ const fullPath = join5(currentDir, entry);
let stat;
try {
- stat = lstatSync(fullPath);
+ stat = lstatSync5(fullPath);
} catch {
continue;
}
@@ -2652,52 +4715,65 @@ function collectFilesWithExtension(dir, extension, maxFiles) {
walk(dir);
return files;
}
-async function aggregateDiagnosticsForDirectory(directory, extension, severity, maxFiles = DEFAULT_MAX_DIRECTORY_FILES) {
+async function aggregateDiagnosticsForDirectory(directory, extension, severity, maxFiles = DEFAULT_MAX_DIRECTORY_FILES, options = {}) {
if (!extension.startsWith(".")) {
throw new LspInvalidPathError(`Extension must start with a dot (e.g., ".ts", not "${extension}"). Use ".${extension}" instead.`);
}
- const absDir = resolve3(contextCwd(), directory);
- if (!existsSync7(absDir)) {
+ const absDir = resolve8(options.workspaceRoot ?? contextCwd(), directory);
+ if (!existsSync10(absDir)) {
throw new LspInvalidPathError(`Directory does not exist: ${absDir}`);
}
- const serverResult = findServerForExtension(extension);
+ const serverResult = options.server === undefined ? findServerForExtension(extension) : { status: "found", server: options.server };
if (serverResult.status !== "found") {
throw new LspServerLookupError(formatServerLookupError(serverResult));
}
const server2 = serverResult.server;
- const allFiles = collectFilesWithExtension(absDir, extension, maxFiles + 1);
+ const allFiles = (options.listFiles ?? collectFilesWithExtension)(absDir, extension, maxFiles + 1);
const wasCapped = allFiles.length > maxFiles;
const filesToProcess = allFiles.slice(0, maxFiles);
if (filesToProcess.length === 0) {
- return [
+ const output = [
`Directory: ${absDir}`,
`Extension: ${extension}`,
"Files scanned: 0",
`No files found with extension "${extension}".`
].join(`
`);
+ return { output, totalDiagnostics: 0, fileFailures: [] };
}
- const root = findWorkspaceRoot(absDir);
- const manager = getLspManager();
+ const root = options.workspaceRoot ?? findWorkspaceRoot(absDir);
+ const manager = options.manager ?? getLspManager();
const allDiagnostics = [];
const fileErrors = [];
+ const maxConcurrency = Math.max(1, options.maxConcurrency ?? DIRECTORY_DIAGNOSTICS_MAX_CONCURRENCY);
+ options.signal?.throwIfAborted();
const client = await manager.getClient(root, server2);
try {
- for (const file of filesToProcess) {
- try {
- const result = await client.diagnostics(file);
- const filtered = filterDiagnosticsBySeverity(result.items, severity);
- allDiagnostics.push(...filtered.map((diagnostic) => ({
- filePath: file,
- diagnostic
- })));
- } catch (e) {
- fileErrors.push({
- file,
- error: e instanceof Error ? e.message : String(e)
- });
+ let nextIndex = 0;
+ const workers = Array.from({ length: Math.min(maxConcurrency, filesToProcess.length) }, async () => {
+ for (;; ) {
+ if (options.signal?.aborted)
+ return;
+ const file = filesToProcess[nextIndex];
+ nextIndex += 1;
+ if (file === undefined)
+ return;
+ try {
+ const result = await client.diagnostics(file, options.signal);
+ const filtered = filterDiagnosticsBySeverity(result.items, severity);
+ allDiagnostics.push(...filtered.map((diagnostic) => ({
+ filePath: file,
+ diagnostic
+ })));
+ } catch (e) {
+ fileErrors.push({
+ file,
+ error: e instanceof Error ? e.message : String(e)
+ });
+ }
}
- }
+ });
+ await Promise.all(workers);
} finally {
manager.releaseClient(root, server2.id);
}
@@ -2725,13 +4801,13 @@ async function aggregateDiagnosticsForDirectory(directory, extension, severity,
lines.push("", `... (${allDiagnostics.length - DEFAULT_MAX_DIAGNOSTICS} more diagnostics not shown)`);
}
}
- return lines.join(`
-`);
+ return { output: lines.join(`
+`), totalDiagnostics: allDiagnostics.length, fileFailures: fileErrors };
}
// ../lsp-core/src/lsp/infer-extension.ts
-import { lstatSync as lstatSync2, readdirSync as readdirSync2 } from "node:fs";
-import { join as join8 } from "node:path";
+import { lstatSync as lstatSync6, readdirSync as readdirSync4 } from "node:fs";
+import { join as join6 } from "node:path";
var SKIP_DIRECTORIES2 = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
var MAX_SCAN_ENTRIES = 500;
function inferExtensionFromDirectory(directory) {
@@ -2742,17 +4818,17 @@ function inferExtensionFromDirectory(directory) {
return;
let entries;
try {
- entries = readdirSync2(dir);
+ entries = readdirSync4(dir);
} catch {
return;
}
for (const entry of entries) {
if (scanned >= MAX_SCAN_ENTRIES)
return;
- const fullPath = join8(dir, entry);
+ const fullPath = join6(dir, entry);
let stat;
try {
- stat = lstatSync2(fullPath);
+ stat = lstatSync6(fullPath);
} catch {
continue;
}
@@ -2826,13 +4902,48 @@ function missingDependencyResult(error, details) {
details: {
...details,
error: message,
- errorKind: "missing_dependency"
+ errorKind: "missing_dependency",
+ ...availabilityDetails(error)
}
};
}
+function availabilityDetails(error) {
+ const availability = missingDependencyAvailability(error);
+ return availability === null ? {} : { availability };
+}
+function missingDependencyAvailability(error) {
+ if (!(error instanceof LspServerLookupError) || error.lookup === undefined)
+ return null;
+ const context = lspRequestContext();
+ switch (error.lookup.status) {
+ case "not_configured":
+ return {
+ kind: "not_configured",
+ extension: error.lookup.extension,
+ availableServers: [...error.lookup.availableServers],
+ projectConfigPaths: [...context.projectConfigPaths],
+ userConfigPath: context.userConfigPath,
+ installDecisionTool: context.capabilities.installDecisionTool
+ };
+ case "not_installed":
+ return {
+ kind: "not_installed",
+ serverId: error.lookup.server.id,
+ command: [...error.lookup.server.command],
+ extensions: [...error.lookup.server.extensions],
+ installHint: error.lookup.installHint,
+ installDecisionTool: context.capabilities.installDecisionTool,
+ installDecisionsPath: context.installDecisionsPath
+ };
+ default: {
+ const exhaustive = error.lookup;
+ return exhaustive;
+ }
+ }
+}
// ../lsp-core/src/tools/parameters.ts
-function isRecord4(value) {
+function isRecord7(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function requireString(params, key) {
@@ -2889,7 +5000,7 @@ async function executeLspDiagnostics(params, signal) {
const filePath = requireString(params, "filePath");
const severity = severityFilter(params);
try {
- const absPath = resolve4(contextCwd(), filePath);
+ const absPath = resolvePathInsideContext(filePath);
if (isDirectoryPath(absPath)) {
const extension = inferExtensionFromDirectory(absPath);
if (!extension) {
@@ -2906,18 +5017,33 @@ async function executeLspDiagnostics(params, signal) {
};
return text(message, details3);
}
- const output2 = await aggregateDiagnosticsForDirectory(absPath, extension, severity);
+ const output2 = await aggregateDiagnosticsForDirectory(absPath, extension, severity, undefined, signal === undefined ? {} : { signal });
const details2 = {
filePath,
severity,
mode: "directory",
diagnostics: [],
+ totalDiagnostics: output2.totalDiagnostics,
+ truncated: false,
+ fileFailures: [...output2.fileFailures]
+ };
+ return text(output2.output, details2);
+ }
+ const result = await withLspClient(filePath, async (client) => client.diagnostics(filePath, signal), "diagnostics", clientOptions(signal));
+ if (result.transientError) {
+ const message = result.transientError.message;
+ const details2 = {
+ filePath,
+ severity,
+ mode: "file",
+ diagnostics: [],
totalDiagnostics: 0,
- truncated: false
+ truncated: false,
+ error: message,
+ errorKind: result.transientError.kind
};
- return text(output2, details2);
+ return text(message, details2, true);
}
- const result = await withLspClient(filePath, async (client) => client.diagnostics(filePath), "diagnostics", clientOptions(signal));
const diagnostics = filterDiagnosticsBySeverity(asDiagnosticArray(result), severity);
const total = diagnostics.length;
const truncated = total > DEFAULT_MAX_DIAGNOSTICS;
@@ -2978,7 +5104,7 @@ async function executeLspGotoDefinition(params, signal) {
const line = requireNumber(params, "line");
const character = requireNumber(params, "character");
try {
- const result = await withLspClient(filePath, async (client) => client.definition(filePath, line, character), "definition", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.definition(filePath, line, character, signal), "definition", clientOptions(signal));
const locations = !result ? [] : Array.isArray(result) ? result : [result];
const details = { filePath, line, character, locations };
if (locations.length === 0)
@@ -3003,7 +5129,7 @@ async function executeLspFindReferences(params, signal) {
const character = requireNumber(params, "character");
const includeDeclaration = optionalBoolean(params, "includeDeclaration") ?? true;
try {
- const result = await withLspClient(filePath, async (client) => client.references(filePath, line, character, includeDeclaration), "references", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.references(filePath, line, character, includeDeclaration, signal), "references", clientOptions(signal));
const references = Array.isArray(result) ? result : [];
const total = references.length;
const truncated = total > DEFAULT_MAX_REFERENCES;
@@ -3039,181 +5165,13 @@ async function executeLspFindReferences(params, signal) {
}
}
-// ../lsp-core/src/lsp/workspace-edit.ts
-import { existsSync as existsSync8, readFileSync as readFileSync5, realpathSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
-import { dirname as dirname5, isAbsolute as isAbsolute3, relative, resolve as resolve5 } from "node:path";
-import { fileURLToPath as fileURLToPath3 } from "node:url";
-function errorMessage2(error) {
- return error instanceof Error ? error.message : String(error);
-}
-function isPathInsideWorkspace(filePath, workspaceRoot) {
- const relativePath = relative(workspaceRoot, filePath);
- return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute3(relativePath);
-}
-function realpathForValidation(filePath) {
- if (existsSync8(filePath))
- return realpathSync(filePath);
- const parent = dirname5(filePath);
- return resolve5(realpathSync(parent), relative(parent, filePath));
-}
-function uriToWorkspacePath(uri, workspaceRoot) {
- let filePath;
- try {
- filePath = fileURLToPath3(uri);
- } catch (error) {
- return { success: false, error: `non-file URI ${uri}: ${errorMessage2(error)}` };
- }
- let validatedPath;
- try {
- validatedPath = realpathForValidation(filePath);
- } catch (error) {
- return { success: false, error: `${filePath}: ${errorMessage2(error)}` };
- }
- if (!isPathInsideWorkspace(validatedPath, workspaceRoot)) {
- return { success: false, error: `${filePath}: outside workspace ${workspaceRoot}` };
- }
- return { success: true, path: filePath };
-}
-function applyTextEditsToFile(filePath, edits) {
- try {
- const content = readFileSync5(filePath, "utf-8");
- const lines = content.split(`
-`);
- const sortedEdits = [...edits].sort((a, b) => {
- if (b.range.start.line !== a.range.start.line) {
- return b.range.start.line - a.range.start.line;
- }
- return b.range.start.character - a.range.start.character;
- });
- for (const edit of sortedEdits) {
- const startLine = edit.range.start.line;
- const startChar = edit.range.start.character;
- const endLine = edit.range.end.line;
- const endChar = edit.range.end.character;
- if (startLine === endLine) {
- const line = lines[startLine] ?? "";
- lines[startLine] = line.substring(0, startChar) + edit.newText + line.substring(endChar);
- } else {
- const firstLine = lines[startLine] ?? "";
- const lastLine = lines[endLine] ?? "";
- const newContent = firstLine.substring(0, startChar) + edit.newText + lastLine.substring(endChar);
- lines.splice(startLine, endLine - startLine + 1, ...newContent.split(`
-`));
- }
- }
- writeFileSync2(filePath, lines.join(`
-`), "utf-8");
- return { success: true, editCount: edits.length };
- } catch (err) {
- return {
- success: false,
- editCount: 0,
- error: err instanceof Error ? err.message : String(err)
- };
- }
-}
-function applyWorkspaceEdit(edit, options = {}) {
- if (!edit) {
- return { success: false, filesModified: [], totalEdits: 0, errors: ["No edit provided"] };
- }
- const result = { success: true, filesModified: [], totalEdits: 0, errors: [] };
- const workspaceRoot = realpathSync(options.workspaceRoot ?? contextCwd());
- if (edit.changes) {
- for (const [uri, edits] of Object.entries(edit.changes)) {
- const validatedPath = uriToWorkspacePath(uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(validatedPath.error);
- continue;
- }
- const applyResult = applyTextEditsToFile(validatedPath.path, edits);
- if (applyResult.success) {
- result.filesModified.push(validatedPath.path);
- result.totalEdits += applyResult.editCount;
- } else {
- result.success = false;
- result.errors.push(`${validatedPath.path}: ${applyResult.error}`);
- }
- }
- }
- if (edit.documentChanges) {
- for (const change of edit.documentChanges) {
- if (!("kind" in change)) {
- const validatedPath = uriToWorkspacePath(change.textDocument.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(validatedPath.error);
- continue;
- }
- const applyResult = applyTextEditsToFile(validatedPath.path, change.edits);
- if (applyResult.success) {
- result.filesModified.push(validatedPath.path);
- result.totalEdits += applyResult.editCount;
- } else {
- result.success = false;
- result.errors.push(`${validatedPath.path}: ${applyResult.error}`);
- }
- continue;
- }
- if (change.kind === "create") {
- try {
- const validatedPath = uriToWorkspacePath(change.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(`Create ${change.uri}: ${validatedPath.error}`);
- continue;
- }
- writeFileSync2(validatedPath.path, "", "utf-8");
- result.filesModified.push(validatedPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Create ${change.uri}: ${String(err)}`);
- }
- } else if (change.kind === "rename") {
- try {
- const oldPath = uriToWorkspacePath(change.oldUri, workspaceRoot);
- const newPath = uriToWorkspacePath(change.newUri, workspaceRoot);
- if (!oldPath.success || !newPath.success) {
- const error = oldPath.success ? newPath.success ? "invalid URI" : newPath.error : oldPath.error;
- result.success = false;
- result.errors.push(`Rename ${change.oldUri}: ${error}`);
- continue;
- }
- const content = readFileSync5(oldPath.path, "utf-8");
- writeFileSync2(newPath.path, content, "utf-8");
- unlinkSync2(oldPath.path);
- result.filesModified.push(newPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Rename ${change.oldUri}: ${String(err)}`);
- }
- } else if (change.kind === "delete") {
- try {
- const validatedPath = uriToWorkspacePath(change.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(`Delete ${change.uri}: ${validatedPath.error}`);
- continue;
- }
- unlinkSync2(validatedPath.path);
- result.filesModified.push(validatedPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Delete ${change.uri}: ${String(err)}`);
- }
- }
- }
- }
- return result;
-}
-
// ../lsp-core/src/tools/rename.ts
async function executeLspPrepareRename(params, signal) {
const filePath = requireString(params, "filePath");
const line = requireNumber(params, "line");
const character = requireNumber(params, "character");
try {
- const result = await withLspClient(filePath, async (client) => client.prepareRename(filePath, line, character), "prepareRename", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.prepareRename(filePath, line, character, signal), "prepareRename", clientOptions(signal));
const details = { filePath, line, character, result };
return text(formatPrepareRenameResult(result), details);
} catch (error) {
@@ -3234,13 +5192,9 @@ async function executeLspRename(params, signal) {
const character = requireNumber(params, "character");
const newName = requireString(params, "newName");
try {
- const edit = await withLspClient(filePath, async (client, workspaceRoot) => ({
- edit: await client.rename(filePath, line, character, newName),
- workspaceRoot
- }), "rename", clientOptions(signal));
- const apply = applyWorkspaceEdit(edit.edit, { workspaceRoot: edit.workspaceRoot });
- const details = { filePath, line, character, newName, apply, edit: edit.edit };
- return text(formatApplyResult(apply), details, !apply.success);
+ const result = await withLspClient(filePath, async (client) => client.rename(filePath, line, character, newName, signal), "rename", clientOptions(signal));
+ const details = { filePath, line, character, newName, apply: result.apply, edit: result.edit };
+ return text(formatApplyResult(result.apply), details, !result.apply.success);
} catch (error) {
const missingDependency = missingDependencyResult(error, {
filePath,
@@ -3315,10 +5269,10 @@ async function executeLspSymbols(params, signal) {
errorKind: "missing_query"
});
}
- const symbols2 = await withLspClient(filePath, async (client) => client.workspaceSymbols(query), "workspaceSymbols", clientOptions(signal));
+ const symbols2 = await withLspClient(filePath, async (client) => client.workspaceSymbols(query, signal), "workspaceSymbols", clientOptions(signal));
return formatSymbolsResult(filePath, scope, symbols2, limit, query);
}
- const symbols = await withLspClient(filePath, async (client) => client.documentSymbols(filePath), "documentSymbols", clientOptions(signal));
+ const symbols = await withLspClient(filePath, async (client) => client.documentSymbols(filePath, signal), "documentSymbols", clientOptions(signal));
return formatSymbolsResult(filePath, scope, symbols, limit);
} catch (error) {
const query = optionalString(params, "query");
@@ -3484,16 +5438,16 @@ function matchesToolName(tool, name) {
return tool.name === name || (tool.aliases?.includes(name) ?? false);
}
function coerceToolArguments(value) {
- return isRecord4(value) ? value : {};
+ return isRecord7(value) ? value : {};
}
// ../lsp-core/src/mcp.ts
var SERVER_NAME = "lsp";
var SERVER_VERSION = "0.1.0";
-async function handleLspMcpRequest(input) {
+async function handleLspMcpRequest(input, options = {}) {
if (!isPlainRecord(input)) {
return errorResponse(null, -32600, "Invalid Request");
}
- const id = jsonRpcId(input["id"]);
+ const id = jsonRpcId2(input["id"]);
const method = input["method"];
if (method === "notifications/initialized")
return;
@@ -3511,24 +5465,27 @@ async function handleLspMcpRequest(input) {
return successResponse(id, { tools: LSP_MCP_TOOLS.map(describeTool) });
}
if (method === "tools/call") {
- return handleToolCall(id, input["params"]);
+ return handleToolCall(id, input["params"], options.signal);
}
return errorResponse(id, -32601, `Method not found: ${String(method)}`);
}
-async function handleToolCall(id, params) {
+async function handleToolCall(id, params, signal) {
if (!isPlainRecord(params) || typeof params["name"] !== "string") {
return errorResponse(id, -32602, "tools/call requires params.name");
}
try {
- const result = await executeLspTool(params["name"], coerceToolArguments(params["arguments"]));
+ const result = await executeLspTool(params["name"], coerceToolArguments(params["arguments"]), signal);
return successResponse(id, {
content: result.content,
isError: result.isError ?? false,
details: result.details
});
} catch (error) {
+ if (!(error instanceof Error)) {
+ throw error;
+ }
return successResponse(id, {
- content: [{ type: "text", text: messageFromError(error) }],
+ content: [{ type: "text", text: error.message }],
isError: true
});
}
@@ -3549,77 +5506,91 @@ function requestedProtocolVersion(params) {
// src/request-routing.ts
var CONTEXT_KEY = "_context";
+
+class InvalidDaemonRequestError extends Error {
+ name = "InvalidDaemonRequestError";
+}
function extractRequestContext(raw) {
if (!isPlainRecord(raw) || raw["method"] !== "tools/call")
return { input: raw, context: undefined };
const params = raw["params"];
if (!isPlainRecord(params))
- return { input: raw, context: undefined };
+ throw new InvalidDaemonRequestError("Daemon tools/call params must be an object.");
const args = params["arguments"];
if (!isPlainRecord(args))
- return { input: raw, context: undefined };
+ throw new InvalidDaemonRequestError("Daemon tools/call arguments must be an object.");
+ if (!Object.hasOwn(args, CONTEXT_KEY)) {
+ throw new InvalidDaemonRequestError("Daemon tools/call arguments must include _context.");
+ }
const context = parseContext(args[CONTEXT_KEY]);
- if (!context)
- return { input: raw, context: undefined };
const cleanedArgs = { ...args };
delete cleanedArgs[CONTEXT_KEY];
const cleaned = { ...raw, params: { ...params, arguments: cleanedArgs } };
return { input: cleaned, context };
}
-function handleDaemonMessage(raw) {
- const { input, context } = extractRequestContext(raw);
- if (context)
- return runWithRequestContext(context, () => handleLspMcpRequest(input));
- return handleLspMcpRequest(input);
-}
-function parseContext(value) {
- if (!isPlainRecord(value))
- return;
- const context = {};
- const cwd = value["cwd"];
- if (typeof cwd === "string")
- context.cwd = cwd;
- const env = value["env"];
- if (isStringRecord2(env))
- context.env = env;
- return context.cwd === undefined && context.env === undefined ? undefined : context;
+function handleDaemonMessage(raw, state) {
+ const authenticated = authenticateMessage(raw, state.token);
+ if ("error" in authenticated)
+ return Promise.resolve(authenticated);
+ if (authenticated.method === "omo/ping") {
+ return Promise.resolve({
+ jsonrpc: "2.0",
+ id: authenticated.id,
+ result: { protocolVersion: OMO_DAEMON_PROTOCOL_VERSION, ...state.owner }
+ });
+ }
+ if (authenticated.method === "$/cancelRequest") {
+ const targetId = cancellationTargetId(authenticated.input);
+ if (targetId !== undefined)
+ state.activeRequests?.get(String(targetId))?.abort();
+ return Promise.resolve(undefined);
+ }
+ let routed;
+ try {
+ routed = extractRequestContext(authenticated.input);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "invalid daemon request";
+ return Promise.resolve({
+ jsonrpc: "2.0",
+ id: authenticated.id,
+ error: { code: -32602, message, data: { code: "invalid_daemon_request" } }
+ });
+ }
+ const { input, context } = routed;
+ const key = routeRequestKey(authenticated.id);
+ if (key === undefined || !state.activeRequests) {
+ if (context)
+ return runWithRequestContext(context, () => handleLspMcpRequest(input));
+ return handleLspMcpRequest(input);
+ }
+ const controller = new AbortController;
+ state.activeRequests.set(key, controller);
+ const options = { signal: controller.signal };
+ const run = context ? runWithRequestContext(context, () => handleLspMcpRequest(input, options)) : handleLspMcpRequest(input, options);
+ return run.finally(() => {
+ if (state.activeRequests?.get(key) === controller)
+ state.activeRequests.delete(key);
+ });
}
-function isStringRecord2(value) {
- return isPlainRecord(value) && Object.values(value).every((item) => typeof item === "string");
+function routeRequestKey(id) {
+ return typeof id === "string" || typeof id === "number" ? String(id) : undefined;
}
-
-// src/socket-jsonrpc.ts
-function encodeJsonLine(message) {
- return `${JSON.stringify(message)}
-`;
+function cancellationTargetId(input) {
+ const params = input["params"];
+ if (!isPlainRecord(params))
+ return;
+ const id = params["id"];
+ return typeof id === "string" || typeof id === "number" ? id : undefined;
}
-function createLineDecoder(onMessage, onParseError) {
- let buffer = "";
- return {
- push(chunk) {
- buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
- let index = buffer.indexOf(`
-`);
- while (index !== -1) {
- const raw = buffer.slice(0, index).trim();
- buffer = buffer.slice(index + 1);
- if (raw.length > 0) {
- try {
- onMessage(JSON.parse(raw));
- } catch (error) {
- onParseError?.(raw, error);
- }
- }
- index = buffer.indexOf(`
-`);
- }
- }
- };
+function parseContext(value) {
+ if (!isPlainRecord(value))
+ throw new InvalidDaemonRequestError("LSP request _context must be an object.");
+ return parseLspRequestContext(value);
}
// src/daemon-client.ts
var DEFAULT_REQUEST_TIMEOUT_MS = 30000;
-var REQUEST_ID = 1;
+var nextProxyRequestId = 1;
class DaemonRequestError extends Error {
requestWritten;
@@ -3629,44 +5600,70 @@ class DaemonRequestError extends Error {
this.requestWritten = requestWritten;
}
}
-async function callToolViaDaemon(name, args, options = {}) {
+
+class DaemonAuthenticationRejectedError extends DaemonRequestError {
+ constructor() {
+ super("daemon authentication failed before dispatch", true);
+ this.name = "DaemonAuthenticationRejectedError";
+ }
+}
+
+class DaemonRequestCancelledError extends DaemonRequestError {
+ constructor(requestWritten) {
+ super("daemon request cancelled", requestWritten);
+ this.name = "DaemonRequestCancelledError";
+ }
+}
+async function callToolViaDaemon(name, args, options) {
+ const context = requireContext(options.context);
const paths = options.paths ?? daemonPaths();
const ensure = options.ensure ?? ensureDaemonRunning;
const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
- const requestArgs = withContext(args, options.context);
+ const requestArgs = withContext(args, context);
let lastError;
- for (let attempt = 0;attempt < 2; attempt += 1) {
+ let authRefreshUsed = false;
+ for (let attempt = 0;attempt < 3; attempt += 1) {
try {
await ensure(paths);
- return await sendToolCall(paths.socket, name, requestArgs, timeoutMs);
+ const token = readAuthToken(paths);
+ if (!token)
+ throw new DaemonRequestError("daemon auth token missing", false);
+ const sendOptions = options.signal === undefined ? { timeoutMs } : { timeoutMs, signal: options.signal };
+ return await sendToolCall(paths, token, name, requestArgs, sendOptions);
} catch (error) {
lastError = error;
- if (error instanceof DaemonRequestError && error.requestWritten)
+ if (error instanceof DaemonAuthenticationRejectedError && !authRefreshUsed) {
+ authRefreshUsed = true;
+ continue;
+ }
+ if (error instanceof DaemonRequestCancelledError)
+ break;
+ if (error instanceof DaemonRequestError && (error.requestWritten || !isRetryableTool(name)))
break;
}
}
return daemonUnreachableResult(paths, lastError);
}
-function callDiagnosticsViaDaemon(filePath, options = {}) {
+function callDiagnosticsViaDaemon(filePath, options) {
return callToolViaDaemon("diagnostics", { filePath, severity: "error" }, options);
}
-var FORWARDED_ENV_KEYS = [
- "LSP_TOOLS_MCP_PROJECT_CONFIG",
- "LSP_TOOLS_MCP_USER_CONFIG",
- "LSP_TOOLS_MCP_INSTALL_DECISIONS"
-];
function currentRequestContext(env = process.env) {
- const forwarded = {};
- for (const key of FORWARDED_ENV_KEYS) {
- const value = env[key];
- if (value !== undefined)
- forwarded[key] = value;
- }
- return { cwd: process.cwd(), env: forwarded };
+ const cwd = process.cwd();
+ const home = env["HOME"] ?? homedir3();
+ return parseLspRequestContext({
+ cwd,
+ projectConfigPaths: [join7(cwd, ".codex", "lsp-client.json")],
+ userConfigPath: join7(home, ".codex", "lsp-client.json"),
+ installDecisionsPath: join7(home, ".codex", "lsp-install-decisions.json"),
+ capabilities: { installDecisionTool: true }
+ });
+}
+function requireContext(context) {
+ if (!context)
+ throw new DaemonRequestError("daemon tool context is required", false);
+ return parseLspRequestContext(context);
}
function withContext(args, context) {
- if (!context || context.cwd === undefined && context.env === undefined)
- return args;
return { ...args, [CONTEXT_KEY]: context };
}
function daemonUnreachableResult(paths, error) {
@@ -3680,39 +5677,84 @@ function daemonUnreachableResult(paths, error) {
`);
return { content: [{ type: "text", text: text2 }], isError: true };
}
-function sendToolCall(socketPath, name, args, timeoutMs) {
- return new Promise((resolve6, reject) => {
- const socket = connect2(socketPath);
+function sendToolCall(paths, token, name, args, options) {
+ return new Promise((resolve9, reject) => {
+ const socket = connect2(paths.socket);
+ const requestId = allocateProxyRequestId();
let settled = false;
let requestWritten = false;
+ let cancelAfterWrite = false;
+ const cancelPayload = () => encodeJsonLine({
+ jsonrpc: "2.0",
+ method: "$/cancelRequest",
+ params: { _omo: authEnvelope(token), id: requestId }
+ });
const finish = (run) => {
if (settled)
return;
settled = true;
clearTimeout(timer);
- socket.destroy();
+ options.signal?.removeEventListener("abort", onAbort);
+ destroyAfterCancel();
run();
};
- const timer = setTimeout(() => finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten))), timeoutMs);
+ const sendCancel = () => {
+ if (!requestWritten) {
+ cancelAfterWrite = true;
+ return;
+ }
+ if (!socket.writable)
+ return;
+ socket.write(cancelPayload());
+ };
+ const destroyAfterCancel = () => {
+ socket.destroy();
+ };
+ const onAbort = () => {
+ sendCancel();
+ finish(() => reject(new DaemonRequestCancelledError(requestWritten)));
+ };
+ const timer = setTimeout(() => {
+ sendCancel();
+ finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten)));
+ }, options.timeoutMs);
timer.unref();
+ if (options.signal?.aborted) {
+ onAbort();
+ return;
+ }
+ options.signal?.addEventListener("abort", onAbort, { once: true });
const decoder = createLineDecoder((message) => {
- const result = toToolResult(message);
+ if (isAuthErrorResponse(message)) {
+ finish(() => reject(new DaemonAuthenticationRejectedError));
+ return;
+ }
+ const result = toToolResult(message, requestId);
if (result)
- finish(() => resolve6(result));
+ finish(() => resolve9(result));
else
finish(() => reject(new DaemonRequestError("invalid daemon response", requestWritten)));
});
socket.once("connect", () => {
- requestWritten = true;
- socket.write(encodeJsonLine({ jsonrpc: "2.0", id: REQUEST_ID, method: "tools/call", params: { name, arguments: args } }));
+ const payload = encodeJsonLine({
+ jsonrpc: "2.0",
+ id: requestId,
+ method: "tools/call",
+ params: { _omo: authEnvelope(token), name, arguments: args }
+ });
+ socket.write(payload, () => {
+ requestWritten = true;
+ if (cancelAfterWrite && socket.writable)
+ socket.write(cancelPayload());
+ });
});
socket.on("data", (chunk) => decoder.push(chunk));
socket.once("error", (error) => finish(() => reject(new DaemonRequestError(error.message, requestWritten))));
socket.once("close", () => finish(() => reject(new DaemonRequestError("daemon connection closed", requestWritten))));
});
}
-function toToolResult(message) {
- if (!isPlainRecord(message) || message["id"] !== REQUEST_ID)
+function toToolResult(message, requestId) {
+ if (!isPlainRecord(message) || message["id"] !== requestId)
return null;
const result = message["result"];
if (!isPlainRecord(result) || !Array.isArray(result["content"]))
@@ -3723,21 +5765,41 @@ function toToolResult(message) {
details: result["details"]
};
}
+function allocateProxyRequestId() {
+ const id = nextProxyRequestId;
+ nextProxyRequestId += 1;
+ if (nextProxyRequestId > Number.MAX_SAFE_INTEGER)
+ nextProxyRequestId = 1;
+ return id;
+}
+function isRetryableTool(name) {
+ return name !== "rename" && name !== "lsp_rename";
+}
function errorText(error) {
return error instanceof Error ? error.message : String(error);
}
// src/proxy.ts
+import { existsSync as existsSync11, realpathSync as realpathSync4 } from "node:fs";
+import { basename as basename3, delimiter as delimiter4, dirname as dirname9, isAbsolute as isAbsolute4 } from "node:path";
async function runMcpStdioProxy(options = {}) {
const input = options.input ?? process.stdin;
const output = options.output ?? process.stdout;
const paths = options.paths ?? daemonPaths();
- const context = options.context ?? currentRequestContext();
+ const env = options.env ?? process.env;
+ const cwd = options.cwd ?? inferOpenCodeProjectCwd(env["LSP_TOOLS_MCP_PROJECT_CONFIG"]);
+ const contextEnv = cwd === undefined ? env : canonicalizeContextEnv(env);
+ const contextInput = {
+ env: contextEnv,
+ ...cwd === undefined ? {} : { cwd },
+ ...options.homeDir === undefined ? {} : { homeDir: options.homeDir }
+ };
+ const context = options.context ?? createStandaloneMcpRequestContext(contextInput);
const callOptions = { paths, context, ...options.ensure ? { ensure: options.ensure } : {} };
await runJsonRpcStdioServer({
input,
output,
idleTimeoutMs: 0,
- handler: handleProxyRequest,
+ handler: (request, requestOptions) => runWithRequestContext(context, () => handleProxyRequest(request, requestOptions)),
handlerOptions: callOptions,
onHandlerError: (error) => {
process.stderr.write(`[lsp-daemon] proxy error: ${error instanceof Error ? error.message : String(error)}
@@ -3759,14 +5821,60 @@ function asToolCall(parsed) {
if (!isPlainRecord(params) || typeof params["name"] !== "string")
return null;
const args = params["arguments"];
- return { id: jsonRpcId(parsed["id"]), name: params["name"], args: isPlainRecord(args) ? args : {} };
+ return { id: jsonRpcId2(parsed["id"]), name: params["name"], args: isPlainRecord(args) ? args : {} };
+}
+function inferOpenCodeProjectCwd(projectConfigEnv) {
+ if (!projectConfigEnv)
+ return;
+ for (const entry of projectConfigEnv.split(delimiter4)) {
+ const projectRoot = projectRootFromOpenCodeConfigPath(entry);
+ if (projectRoot)
+ return projectRoot;
+ }
+ return;
+}
+function canonicalizeContextEnv(env) {
+ return {
+ ...env,
+ LSP_TOOLS_MCP_PROJECT_CONFIG: canonicalizePathList(env["LSP_TOOLS_MCP_PROJECT_CONFIG"]),
+ LSP_TOOLS_MCP_USER_CONFIG: canonicalizePath(env["LSP_TOOLS_MCP_USER_CONFIG"]),
+ LSP_TOOLS_MCP_INSTALL_DECISIONS: canonicalizePath(env["LSP_TOOLS_MCP_INSTALL_DECISIONS"])
+ };
+}
+function canonicalizePathList(value) {
+ if (value === undefined)
+ return;
+ return value.split(delimiter4).map((entry) => canonicalizePath(entry) ?? entry).join(delimiter4);
+}
+function canonicalizePath(value) {
+ if (value === undefined || !isAbsolute4(value) || !existsSync11(value))
+ return value;
+ return realpathSync4(value);
+}
+function projectRootFromOpenCodeConfigPath(path2) {
+ if (basename3(path2) !== "lsp.json" && basename3(path2) !== "lsp-client.json")
+ return;
+ const configDir = dirname9(path2);
+ const configDirName = basename3(configDir);
+ if (configDirName !== ".opencode" && configDirName !== ".omo")
+ return;
+ return dirname9(configDir);
}
export {
+ validateDaemonVersion,
runMcpStdioProxy,
+ resolveDaemonRuntime,
+ probeDaemon,
ensureDaemonRunning,
disposeDefaultLspManager,
daemonPaths,
currentRequestContext,
callToolViaDaemon,
- callDiagnosticsViaDaemon
+ callDiagnosticsViaDaemon,
+ OMO_LSP_DAEMON_VERSION,
+ OMO_LSP_DAEMON_DIR,
+ OMO_LSP_DAEMON_CLI,
+ InvalidRuntimeOverrideError,
+ InvalidDaemonVersionError,
+ InvalidDaemonDirectoryError
};
diff --git a/plugins/omo/components/lsp-daemon/dist/ipc-protocol.d.ts b/plugins/omo/components/lsp-daemon/dist/ipc-protocol.d.ts
new file mode 100644
index 00000000..fb2b73a0
--- /dev/null
+++ b/plugins/omo/components/lsp-daemon/dist/ipc-protocol.d.ts
@@ -0,0 +1,46 @@
+import { type Stats } from "node:fs";
+import type { DaemonPaths } from "./paths.js";
+export declare const OMO_DAEMON_PROTOCOL_VERSION = 1;
+export declare const AUTH_ERROR_CODE = -32001;
+export declare const PROTOCOL_ERROR_CODE = -32002;
+export type DaemonAuthEnvelope = {
+ readonly protocolVersion: typeof OMO_DAEMON_PROTOCOL_VERSION;
+ readonly token: string;
+};
+export type JsonRpcErrorResponse = {
+ readonly jsonrpc: "2.0";
+ readonly id: string | number | null;
+ readonly error: {
+ readonly code: number;
+ readonly message: string;
+ readonly data: {
+ readonly code: string;
+ };
+ };
+};
+export type AuthenticatedMessage = {
+ readonly input: Record<string, unknown>;
+ readonly id: string | number | null;
+ readonly method: string | undefined;
+};
+export type PrivateDirectoryStats = Pick<Stats, "dev" | "ino" | "uid" | "isDirectory" | "isSymbolicLink">;
+export interface PrivateDirectoryOptions {
+ readonly currentUid?: () => number | undefined;
+ readonly lstat?: (path: string) => PrivateDirectoryStats;
+}
+export declare class UnsafePrivateDirectoryError extends Error {
+ readonly path: string;
+ readonly reason: "changed_during_chmod" | "not_directory" | "symlink" | "wrong_owner";
+ readonly name = "UnsafePrivateDirectoryError";
+ readonly code = "unsafe_private_directory";
+ constructor(path: string, reason: "changed_during_chmod" | "not_directory" | "symlink" | "wrong_owner");
+}
+export declare function authEnvelope(token: string): DaemonAuthEnvelope;
+export declare function readAuthToken(paths: DaemonPaths): string | null;
+export declare function readOrCreateAuthToken(paths: DaemonPaths): string;
+export declare function rotateAuthToken(paths: DaemonPaths): string;
+export declare function authenticateMessage(raw: unknown, expectedToken: string): AuthenticatedMessage | JsonRpcErrorResponse;
+export declare function isAuthErrorResponse(message: unknown): boolean;
+export declare function writePrivateFile(path: string, data: string): void;
+export declare function ensurePrivateDirectory(path: string, options?: PrivateDirectoryOptions): void;
+export declare function setPrivateFileMode(path: string): void;
diff --git a/plugins/omo/components/lsp-daemon/dist/ipc-protocol.js b/plugins/omo/components/lsp-daemon/dist/ipc-protocol.js
new file mode 100644
index 00000000..41dd7f34
--- /dev/null
+++ b/plugins/omo/components/lsp-daemon/dist/ipc-protocol.js
@@ -0,0 +1,187 @@
+import { randomBytes, timingSafeEqual } from "node:crypto";
+import { chmodSync, closeSync, constants, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, unlinkSync, writeSync, } from "node:fs";
+import { dirname } from "node:path";
+import { isPlainRecord } from "@oh-my-opencode/mcp-stdio-core/record";
+export const OMO_DAEMON_PROTOCOL_VERSION = 1;
+export const AUTH_ERROR_CODE = -32001;
+export const PROTOCOL_ERROR_CODE = -32002;
+const AUTH_TOKEN_BYTES = 32;
+export class UnsafePrivateDirectoryError extends Error {
+ constructor(path, reason) {
+ super(`unsafe private directory ${path}: ${reason}`);
+ this.path = path;
+ this.reason = reason;
+ this.name = "UnsafePrivateDirectoryError";
+ this.code = "unsafe_private_directory";
+ }
+}
+export function authEnvelope(token) {
+ return { protocolVersion: OMO_DAEMON_PROTOCOL_VERSION, token };
+}
+export function readAuthToken(paths) {
+ try {
+ const token = readFileSync(paths.auth, "utf8").trim();
+ return token.length > 0 ? token : null;
+ }
+ catch (error) {
+ if (error instanceof Error)
+ return null;
+ throw error;
+ }
+}
+export function readOrCreateAuthToken(paths) {
+ const existing = readAuthToken(paths);
+ if (existing)
+ return existing;
+ return createAuthToken(paths);
+}
+export function rotateAuthToken(paths) {
+ try {
+ unlinkSync(paths.auth);
+ }
+ catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ }
+ return createAuthToken(paths);
+}
+export function authenticateMessage(raw, expectedToken) {
+ const id = jsonRpcId(raw);
+ if (!isPlainRecord(raw))
+ return authError(id);
+ const params = raw["params"];
+ if (!isPlainRecord(params))
+ return authError(id);
+ const envelope = params["_omo"];
+ if (!isPlainRecord(envelope))
+ return authError(id);
+ const protocolVersion = envelope["protocolVersion"];
+ if (protocolVersion !== OMO_DAEMON_PROTOCOL_VERSION)
+ return protocolError(id);
+ const token = envelope["token"];
+ if (typeof token !== "string" || !tokenMatches(token, expectedToken))
+ return authError(id);
+ const cleanParams = { ...params };
+ delete cleanParams["_omo"];
+ return { input: { ...raw, params: cleanParams }, id, method: typeof raw["method"] === "string" ? raw["method"] : undefined };
+}
+export function isAuthErrorResponse(message) {
+ if (!isPlainRecord(message))
+ return false;
+ const error = message["error"];
+ if (!isPlainRecord(error))
+ return false;
+ const data = error["data"];
+ return error["code"] === AUTH_ERROR_CODE && isPlainRecord(data) && data["code"] === "daemon_authentication_failed";
+}
+export function writePrivateFile(path, data) {
+ const fd = openSync(path, "w", 0o600);
+ try {
+ writeSync(fd, data);
+ }
+ finally {
+ closeSync(fd);
+ }
+ setPrivateFileMode(path);
+}
+export function ensurePrivateDirectory(path, options = {}) {
+ try {
+ mkdirSync(path, { recursive: true, mode: 0o700 });
+ }
+ catch (error) {
+ if (errorCode(error) !== "EEXIST")
+ throw error;
+ }
+ if (process.platform === "win32")
+ return;
+ const before = validatePrivateDirectory(path, options);
+ const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
+ try {
+ fchmodSync(fd, 0o700);
+ const after = validatePrivateDirectory(path, options);
+ const openStats = fstatSync(fd);
+ if (!sameDirectory(before, after) || !sameDirectory(before, openStats)) {
+ throw new UnsafePrivateDirectoryError(path, "changed_during_chmod");
+ }
+ }
+ finally {
+ closeSync(fd);
+ }
+}
+export function setPrivateFileMode(path) {
+ if (process.platform !== "win32")
+ chmodSync(path, 0o600);
+}
+function createAuthToken(paths) {
+ ensurePrivateDirectory(dirname(paths.auth));
+ const token = randomBytes(AUTH_TOKEN_BYTES).toString("base64url");
+ let fd;
+ try {
+ fd = openSync(paths.auth, "wx", 0o600);
+ }
+ catch (error) {
+ if (errorCode(error) === "EEXIST") {
+ const existing = readAuthToken(paths);
+ if (existing)
+ return existing;
+ }
+ throw error;
+ }
+ try {
+ writeSync(fd, `${token}\n`);
+ }
+ finally {
+ closeSync(fd);
+ }
+ setPrivateFileMode(paths.auth);
+ return token;
+}
+function errorCode(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return undefined;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
+}
+function validatePrivateDirectory(path, options) {
+ const stats = options.lstat ? options.lstat(path) : lstatPrivateDirectory(path);
+ if (stats.isSymbolicLink())
+ throw new UnsafePrivateDirectoryError(path, "symlink");
+ if (!stats.isDirectory())
+ throw new UnsafePrivateDirectoryError(path, "not_directory");
+ const currentUid = options.currentUid ? options.currentUid() : process.getuid?.();
+ if (currentUid !== undefined && stats.uid !== currentUid) {
+ throw new UnsafePrivateDirectoryError(path, "wrong_owner");
+ }
+ return stats;
+}
+function lstatPrivateDirectory(path) {
+ return lstatSync(path);
+}
+function sameDirectory(a, b) {
+ return a.dev === b.dev && a.ino === b.ino;
+}
+function tokenMatches(candidate, expected) {
+ const candidateBytes = Buffer.from(candidate);
+ const expectedBytes = Buffer.from(expected);
+ return candidateBytes.length === expectedBytes.length && timingSafeEqual(candidateBytes, expectedBytes);
+}
+function jsonRpcId(raw) {
+ if (!isPlainRecord(raw))
+ return null;
+ const id = raw["id"];
+ return typeof id === "string" || typeof id === "number" || id === null ? id : null;
+}
+function authError(id) {
+ return {
+ jsonrpc: "2.0",
+ id,
+ error: { code: AUTH_ERROR_CODE, message: "daemon authentication failed", data: { code: "daemon_authentication_failed" } },
+ };
+}
+function protocolError(id) {
+ return {
+ jsonrpc: "2.0",
+ id,
+ error: { code: PROTOCOL_ERROR_CODE, message: "daemon protocol mismatch", data: { code: "daemon_protocol_mismatch" } },
+ };
+}
diff --git a/plugins/omo/components/lsp-daemon/dist/lock.js b/plugins/omo/components/lsp-daemon/dist/lock.js
index df7dd6ba..958e0abb 100644
--- a/plugins/omo/components/lsp-daemon/dist/lock.js
+++ b/plugins/omo/components/lsp-daemon/dist/lock.js
@@ -8,7 +8,9 @@ export function isProcessAlive(pid) {
return true;
}
catch (error) {
- return error.code === "EPERM";
+ if (error instanceof Error)
+ return errorCode(error) === "EPERM";
+ throw error;
}
}
export function readLockPid(lockPath) {
@@ -33,13 +35,13 @@ export function tryAcquireLock(lockPath, ownerPid = process.pid) {
}
function writeLockFile(lockPath, ownerPid) {
try {
- const fd = openSync(lockPath, "wx");
+ const fd = openSync(lockPath, "wx", 0o600);
writeSync(fd, `${ownerPid}\n`);
closeSync(fd);
return { release: () => unlinkQuietly(lockPath) };
}
catch (error) {
- if (error.code === "EEXIST")
+ if (errorCode(error) === "EEXIST")
return null;
throw error;
}
@@ -56,6 +58,14 @@ export function unlinkQuietly(path) {
unlinkSync(path);
}
catch (error) {
- void error;
+ if (error instanceof Error)
+ return;
+ throw error;
}
}
+function errorCode(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return undefined;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
+}
diff --git a/plugins/omo/components/lsp-daemon/dist/ownership.d.ts b/plugins/omo/components/lsp-daemon/dist/ownership.d.ts
new file mode 100644
index 00000000..fc11d58d
--- /dev/null
+++ b/plugins/omo/components/lsp-daemon/dist/ownership.d.ts
@@ -0,0 +1,49 @@
+import { type LockHandle } from "./lock.js";
+import type { DaemonPaths } from "./paths.js";
+export type EndpointIdentity = {
+ readonly kind: "unix";
+ readonly path: string;
+ readonly dev: number;
+ readonly ino: number;
+} | {
+ readonly kind: "windows";
+ readonly path: string;
+} | {
+ readonly kind: "missing";
+ readonly path: string;
+};
+export type DaemonOwner = {
+ readonly pid: number;
+ readonly nonce: string;
+ readonly startedAt: string;
+ readonly endpoint: EndpointIdentity;
+};
+export type StartupLease = {
+ readonly lock: LockHandle;
+ readonly token: string;
+ readonly owner: DaemonOwner;
+};
+export declare class DaemonAlreadyRunningError extends Error {
+ readonly name = "DaemonAlreadyRunningError";
+ readonly code = "daemon_already_running";
+}
+export declare class DaemonStartupDeferredError extends Error {
+ readonly reason: string;
+ readonly name = "DaemonStartupDeferredError";
+ readonly code = "daemon_startup_deferred";
+ constructor(reason: string);
+}
+export type OwnerPing = {
+ readonly pid: number;
+ readonly nonce: string;
+ readonly startedAt: string;
+ readonly endpoint: EndpointIdentity;
+};
+export declare function acquireStartupLease(paths: DaemonPaths, pingOwner: (token: string) => Promise<OwnerPing | null>): Promise<StartupLease>;
+export declare function ensureDaemonDirectories(paths: DaemonPaths): void;
+export declare function readDaemonOwner(paths: DaemonPaths): DaemonOwner | null;
+export declare function writeDaemonOwner(paths: DaemonPaths, owner: DaemonOwner): void;
+export declare function removeDaemonMetadataForOwner(paths: DaemonPaths, owner: DaemonOwner): void;
+export declare function endpointIdentity(endpointPath: string): EndpointIdentity;
+export declare function sameEndpoint(a: EndpointIdentity, b: EndpointIdentity): boolean;
+export declare function sameOwner(a: DaemonOwner, b: DaemonOwner): boolean;
diff --git a/plugins/omo/components/lsp-daemon/dist/ownership.js b/plugins/omo/components/lsp-daemon/dist/ownership.js
new file mode 100644
index 00000000..3901518a
--- /dev/null
+++ b/plugins/omo/components/lsp-daemon/dist/ownership.js
@@ -0,0 +1,168 @@
+import { randomUUID } from "node:crypto";
+import { existsSync, lstatSync, readFileSync, statSync, unlinkSync } from "node:fs";
+import { dirname } from "node:path";
+import { tryAcquireLock, isProcessAlive, unlinkQuietly } from "./lock.js";
+import { ensurePrivateDirectory, readAuthToken, readOrCreateAuthToken, rotateAuthToken, writePrivateFile, } from "./ipc-protocol.js";
+export class DaemonAlreadyRunningError extends Error {
+ constructor() {
+ super(...arguments);
+ this.name = "DaemonAlreadyRunningError";
+ this.code = "daemon_already_running";
+ }
+}
+export class DaemonStartupDeferredError extends Error {
+ constructor(reason) {
+ super(`LSP daemon startup deferred: ${reason}`);
+ this.reason = reason;
+ this.name = "DaemonStartupDeferredError";
+ this.code = "daemon_startup_deferred";
+ }
+}
+export async function acquireStartupLease(paths, pingOwner) {
+ ensureDaemonDirectories(paths);
+ const lock = tryAcquireLock(paths.lock);
+ if (!lock) {
+ const token = readAuthToken(paths);
+ if (token && (await pingOwner(token)))
+ throw new DaemonAlreadyRunningError("LSP daemon already running");
+ throw new DaemonStartupDeferredError("startup_lock_busy");
+ }
+ try {
+ const token = await validateExistingOwner(paths, pingOwner);
+ return { lock, token, owner: newOwner(paths) };
+ }
+ catch (error) {
+ lock.release();
+ throw error;
+ }
+}
+export function ensureDaemonDirectories(paths) {
+ ensurePrivateDirectory(paths.dir);
+ if (process.platform !== "win32")
+ ensurePrivateDirectory(dirname(paths.socket));
+}
+export function readDaemonOwner(paths) {
+ try {
+ return parseOwner(JSON.parse(readFileSync(paths.owner, "utf8")));
+ }
+ catch (error) {
+ if (error instanceof Error)
+ return null;
+ throw error;
+ }
+}
+export function writeDaemonOwner(paths, owner) {
+ writePrivateFile(paths.pid, `${owner.pid}\n`);
+ writePrivateFile(paths.endpoint, owner.endpoint.path);
+ writePrivateFile(paths.owner, `${JSON.stringify(owner)}\n`);
+}
+export function removeDaemonMetadataForOwner(paths, owner) {
+ const current = readDaemonOwner(paths);
+ if (!current || !sameOwner(current, owner))
+ return;
+ unlinkQuietly(paths.socket);
+ unlinkQuietly(paths.pid);
+ unlinkQuietly(paths.endpoint);
+ unlinkQuietly(paths.owner);
+}
+export function endpointIdentity(endpointPath) {
+ if (process.platform === "win32")
+ return { kind: "windows", path: endpointPath };
+ try {
+ const stats = statSync(endpointPath);
+ return { kind: "unix", path: endpointPath, dev: stats.dev, ino: stats.ino };
+ }
+ catch (error) {
+ if (error instanceof Error)
+ return { kind: "missing", path: endpointPath };
+ throw error;
+ }
+}
+export function sameEndpoint(a, b) {
+ if (a.kind !== b.kind || a.path !== b.path)
+ return false;
+ switch (a.kind) {
+ case "unix":
+ return b.kind === "unix" && a.dev === b.dev && a.ino === b.ino;
+ case "windows":
+ return true;
+ case "missing":
+ return true;
+ }
+}
+export function sameOwner(a, b) {
+ return a.pid === b.pid && a.nonce === b.nonce && sameEndpoint(a.endpoint, b.endpoint);
+}
+async function validateExistingOwner(paths, pingOwner) {
+ let token = readOrCreateAuthToken(paths);
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ const owner = readDaemonOwner(paths);
+ if (!owner)
+ return token;
+ const ping = await pingOwner(token);
+ if (ping && owner.nonce === ping.nonce && sameEndpoint(owner.endpoint, ping.endpoint)) {
+ throw new DaemonAlreadyRunningError("LSP daemon already running");
+ }
+ if (ping)
+ continue;
+ if (isProcessAlive(owner.pid))
+ throw new DaemonStartupDeferredError("owner_pid_live_unreachable");
+ const reread = readDaemonOwner(paths);
+ const endpoint = endpointIdentity(owner.endpoint.path);
+ if (!reread || reread.nonce !== owner.nonce || !sameEndpoint(endpoint, owner.endpoint)) {
+ throw new DaemonStartupDeferredError("owner_changed_during_cleanup");
+ }
+ cleanupDeadOwner(paths, owner);
+ token = rotateAuthToken(paths);
+ return token;
+ }
+ throw new DaemonStartupDeferredError("reachable_owner_mismatch");
+}
+function cleanupDeadOwner(paths, owner) {
+ if (process.platform !== "win32" && existsSync(owner.endpoint.path)) {
+ const stat = lstatSync(owner.endpoint.path);
+ if (stat.isSocket())
+ unlinkSync(owner.endpoint.path);
+ }
+ unlinkQuietly(paths.pid);
+ unlinkQuietly(paths.endpoint);
+ unlinkQuietly(paths.owner);
+}
+function newOwner(paths) {
+ return {
+ pid: process.pid,
+ nonce: randomUUID(),
+ startedAt: new Date().toISOString(),
+ endpoint: endpointIdentity(paths.socket),
+ };
+}
+function parseOwner(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value))
+ return null;
+ const pid = Reflect.get(value, "pid");
+ const nonce = Reflect.get(value, "nonce");
+ const startedAt = Reflect.get(value, "startedAt");
+ const endpoint = parseEndpoint(Reflect.get(value, "endpoint"));
+ if (typeof pid !== "number" || typeof nonce !== "string" || typeof startedAt !== "string" || !endpoint)
+ return null;
+ return { pid, nonce, startedAt, endpoint };
+}
+function parseEndpoint(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value))
+ return null;
+ const kind = Reflect.get(value, "kind");
+ const path = Reflect.get(value, "path");
+ if (typeof path !== "string")
+ return null;
+ if (kind === undefined)
+ return endpointIdentity(path);
+ if (kind === "windows")
+ return { kind, path };
+ if (kind === "missing")
+ return { kind, path };
+ const dev = Reflect.get(value, "dev");
+ const ino = Reflect.get(value, "ino");
+ if (kind === "unix" && typeof dev === "number" && typeof ino === "number")
+ return { kind, path, dev, ino };
+ return null;
+}
diff --git a/plugins/omo/components/lsp-daemon/dist/paths.d.ts b/plugins/omo/components/lsp-daemon/dist/paths.d.ts
index 4bcbec52..7e47f0bf 100644
--- a/plugins/omo/components/lsp-daemon/dist/paths.d.ts
+++ b/plugins/omo/components/lsp-daemon/dist/paths.d.ts
@@ -1,12 +1,36 @@
+import { type DaemonRuntimeDefaults } from "./runtime-contract.js";
+export { InvalidDaemonVersionError, OMO_LSP_DAEMON_DIR, OMO_LSP_DAEMON_VERSION, validateDaemonVersion, } from "./runtime-contract.js";
+export interface DaemonPathOperations {
+ readonly isAbsolute: (value: string) => boolean;
+ readonly join: (...parts: string[]) => string;
+ readonly resolve: (...parts: string[]) => string;
+}
+export interface DaemonPlatform {
+ readonly platform: NodeJS.Platform;
+ readonly homedir: () => string;
+ readonly tmpdir: () => string;
+ readonly getuid: () => number | undefined;
+ readonly username: () => string;
+ readonly path: DaemonPathOperations;
+}
+export declare class InvalidDaemonDirectoryError extends Error {
+ readonly code = "invalid_daemon_directory";
+ readonly directory: string;
+ constructor(directory: string);
+}
export interface DaemonPaths {
- version: string;
- dir: string;
- socket: string;
- lock: string;
- pid: string;
- log: string;
+ readonly version: string;
+ readonly cliPath: string;
+ readonly dir: string;
+ readonly socket: string;
+ readonly lock: string;
+ readonly pid: string;
+ readonly auth: string;
+ readonly endpoint: string;
+ readonly owner: string;
+ readonly log: string;
}
export declare function resolveDaemonVersion(requireFn?: (id: string) => unknown): string;
-export declare function daemonBaseDir(env?: NodeJS.ProcessEnv): string;
-export declare function daemonPaths(env?: NodeJS.ProcessEnv, version?: string): DaemonPaths;
-export declare function resolveDaemonVersionFromEnv(env?: NodeJS.ProcessEnv): string | null;
+export declare function packagedRuntimeDefaults(): DaemonRuntimeDefaults;
+export declare function daemonBaseDir(env?: NodeJS.ProcessEnv, platform?: DaemonPlatform): string;
+export declare function daemonPaths(env?: NodeJS.ProcessEnv, runtimeDefaults?: DaemonRuntimeDefaults, platform?: DaemonPlatform): DaemonPaths;
diff --git a/plugins/omo/components/lsp-daemon/dist/paths.js b/plugins/omo/components/lsp-daemon/dist/paths.js
index 4d57305f..2985b649 100644
--- a/plugins/omo/components/lsp-daemon/dist/paths.js
+++ b/plugins/omo/components/lsp-daemon/dist/paths.js
@@ -1,54 +1,93 @@
import { createHash } from "node:crypto";
import { createRequire } from "node:module";
-import { homedir, tmpdir } from "node:os";
-import { join } from "node:path";
+import { homedir, tmpdir, userInfo } from "node:os";
+import * as path from "node:path";
+import { fileURLToPath } from "node:url";
+import { OMO_LSP_DAEMON_DIR, resolveDaemonRuntime, validateDaemonVersion, } from "./runtime-contract.js";
+export { InvalidDaemonVersionError, OMO_LSP_DAEMON_DIR, OMO_LSP_DAEMON_VERSION, validateDaemonVersion, } from "./runtime-contract.js";
const requireFromHere = createRequire(import.meta.url);
const MAX_SOCKET_PATH_LENGTH = 100;
-const CODEX_LSP_DAEMON_VERSION_ENV = "CODEX_LSP_DAEMON_VERSION";
+export class InvalidDaemonDirectoryError extends Error {
+ constructor(directory) {
+ super(`${OMO_LSP_DAEMON_DIR} must be an absolute path`);
+ this.code = "invalid_daemon_directory";
+ this.name = "InvalidDaemonDirectoryError";
+ this.directory = directory;
+ }
+}
export function resolveDaemonVersion(requireFn = requireFromHere) {
for (const candidate of ["./package.json", "../package.json"]) {
+ let loaded;
try {
- const pkg = requireFn(candidate);
- if (typeof pkg.version === "string" && pkg.version.length > 0)
- return pkg.version;
+ loaded = requireFn(candidate);
+ }
+ catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ continue;
+ }
+ if (typeof loaded === "object" && loaded !== null && "version" in loaded) {
+ const version = Reflect.get(loaded, "version");
+ if (typeof version === "string")
+ return validateDaemonVersion(version);
}
- catch { }
}
return "0";
}
-export function daemonBaseDir(env = process.env) {
- const explicit = env["CODEX_LSP_DAEMON_DIR"]?.trim();
- if (explicit)
- return explicit;
- const pluginData = env["PLUGIN_DATA"]?.trim();
- if (pluginData)
- return join(pluginData, "daemon");
- const codexHome = env["CODEX_HOME"]?.trim();
- const home = codexHome && codexHome.length > 0 ? codexHome : join(homedir(), ".codex");
- return join(home, "codex-lsp", "daemon");
-}
-export function daemonPaths(env = process.env, version = resolveDaemonVersionFromEnv(env) ?? resolveDaemonVersion()) {
- const dir = join(daemonBaseDir(env), `v${version}`);
+export function packagedRuntimeDefaults() {
+ return {
+ cliPath: fileURLToPath(new URL("./cli.js", import.meta.url)),
+ version: resolveDaemonVersion(),
+ };
+}
+export function daemonBaseDir(env = process.env, platform = defaultDaemonPlatform()) {
+ const override = env[OMO_LSP_DAEMON_DIR];
+ if (override !== undefined) {
+ if (!platform.path.isAbsolute(override))
+ throw new InvalidDaemonDirectoryError(override);
+ return platform.path.resolve(override);
+ }
+ return platform.path.resolve(platform.path.join(platform.homedir(), ".omo", "lsp-daemon"));
+}
+export function daemonPaths(env = process.env, runtimeDefaults = packagedRuntimeDefaults(), platform = defaultDaemonPlatform()) {
+ const runtime = resolveDaemonRuntime(env, runtimeDefaults);
+ const baseDir = daemonBaseDir(env, platform);
+ const dir = platform.path.resolve(platform.path.join(baseDir, `v${runtime.version}`));
return {
- version,
+ version: runtime.version,
+ cliPath: runtime.cliPath,
dir,
- socket: resolveSocketPath(dir, version),
- lock: join(dir, "daemon.lock"),
- pid: join(dir, "daemon.pid"),
- log: join(dir, "daemon.log"),
+ socket: resolveSocketPath(dir, runtime.version, platform),
+ lock: platform.path.join(dir, "daemon.lock"),
+ pid: platform.path.join(dir, "daemon.pid"),
+ auth: platform.path.join(dir, "daemon.auth"),
+ endpoint: platform.path.join(dir, "daemon.endpoint"),
+ owner: platform.path.join(dir, "daemon.owner"),
+ log: platform.path.join(dir, "daemon.log"),
};
}
-export function resolveDaemonVersionFromEnv(env = process.env) {
- const version = env[CODEX_LSP_DAEMON_VERSION_ENV]?.trim();
- return version && version.length > 0 ? version : null;
+function defaultDaemonPlatform() {
+ return {
+ platform: process.platform,
+ homedir,
+ tmpdir,
+ getuid: () => (typeof process.getuid === "function" ? process.getuid() : undefined),
+ username: () => userInfo().username,
+ path,
+ };
}
-function resolveSocketPath(dir, version) {
- const digest = createHash("sha256").update(dir).digest("hex").slice(0, 16);
- if (process.platform === "win32") {
+function resolveSocketPath(dir, version, platform) {
+ const canonicalVersionDir = platform.path.resolve(dir);
+ if (platform.platform === "win32") {
+ const currentUserDiscriminator = `${platform.getuid() ?? "win"}:${platform.username()}:${platform.path.resolve(platform.homedir())}`;
+ const digest = shortDigest(`${canonicalVersionDir}\0${currentUserDiscriminator}`);
return `\\\\.\\pipe\\omo-lsp-${version}-${digest}`;
}
- const natural = join(dir, "daemon.sock");
+ const natural = platform.path.join(canonicalVersionDir, "daemon.sock");
if (natural.length < MAX_SOCKET_PATH_LENGTH)
return natural;
- return join(tmpdir(), `omo-lsp-${version}-${digest}.sock`);
+ return platform.path.join(platform.tmpdir(), `omo-lsp-${version}-${shortDigest(canonicalVersionDir)}`, "daemon.sock");
+}
+function shortDigest(value) {
+ return createHash("sha256").update(value).digest("hex").slice(0, 16);
}
diff --git a/plugins/omo/components/lsp-daemon/dist/proxy.d.ts b/plugins/omo/components/lsp-daemon/dist/proxy.d.ts
index 257e0d5e..3a6fe01e 100644
--- a/plugins/omo/components/lsp-daemon/dist/proxy.d.ts
+++ b/plugins/omo/components/lsp-daemon/dist/proxy.d.ts
@@ -6,6 +6,9 @@ export interface ProxyOptions {
output?: Writable;
paths?: DaemonPaths;
context?: DaemonToolContext;
+ cwd?: string;
+ env?: Record<string, string | undefined>;
+ homeDir?: string;
ensure?: CallToolOptions["ensure"];
}
export declare function runMcpStdioProxy(options?: ProxyOptions): Promise<void>;
diff --git a/plugins/omo/components/lsp-daemon/dist/proxy.js b/plugins/omo/components/lsp-daemon/dist/proxy.js
index 76cc1f95..32d31866 100644
--- a/plugins/omo/components/lsp-daemon/dist/proxy.js
+++ b/plugins/omo/components/lsp-daemon/dist/proxy.js
@@ -1,19 +1,30 @@
+import { existsSync, realpathSync } from "node:fs";
+import { basename, delimiter, dirname, isAbsolute } from "node:path";
import { jsonRpcId, runJsonRpcStdioServer, successResponse } from "@oh-my-opencode/mcp-stdio-core";
import { isPlainRecord } from "@oh-my-opencode/mcp-stdio-core/record";
import { handleLspMcpRequest } from "@oh-my-opencode/lsp-core/mcp";
-import { callToolViaDaemon, currentRequestContext, } from "./daemon-client.js";
+import { createStandaloneMcpRequestContext, runWithRequestContext } from "@oh-my-opencode/lsp-core/request-context";
+import { callToolViaDaemon } from "./daemon-client.js";
import { daemonPaths } from "./paths.js";
export async function runMcpStdioProxy(options = {}) {
const input = options.input ?? process.stdin;
const output = options.output ?? process.stdout;
const paths = options.paths ?? daemonPaths();
- const context = options.context ?? currentRequestContext();
+ const env = options.env ?? process.env;
+ const cwd = options.cwd ?? inferOpenCodeProjectCwd(env["LSP_TOOLS_MCP_PROJECT_CONFIG"]);
+ const contextEnv = cwd === undefined ? env : canonicalizeContextEnv(env);
+ const contextInput = {
+ env: contextEnv,
+ ...(cwd === undefined ? {} : { cwd }),
+ ...(options.homeDir === undefined ? {} : { homeDir: options.homeDir }),
+ };
+ const context = options.context ?? createStandaloneMcpRequestContext(contextInput);
const callOptions = { paths, context, ...(options.ensure ? { ensure: options.ensure } : {}) };
await runJsonRpcStdioServer({
input,
output,
idleTimeoutMs: 0,
- handler: handleProxyRequest,
+ handler: (request, requestOptions) => runWithRequestContext(context, () => handleProxyRequest(request, requestOptions)),
handlerOptions: callOptions,
onHandlerError: (error) => {
process.stderr.write(`[lsp-daemon] proxy error: ${error instanceof Error ? error.message : String(error)}\n`);
@@ -36,3 +47,43 @@ function asToolCall(parsed) {
const args = params["arguments"];
return { id: jsonRpcId(parsed["id"]), name: params["name"], args: isPlainRecord(args) ? args : {} };
}
+function inferOpenCodeProjectCwd(projectConfigEnv) {
+ if (!projectConfigEnv)
+ return undefined;
+ for (const entry of projectConfigEnv.split(delimiter)) {
+ const projectRoot = projectRootFromOpenCodeConfigPath(entry);
+ if (projectRoot)
+ return projectRoot;
+ }
+ return undefined;
+}
+function canonicalizeContextEnv(env) {
+ return {
+ ...env,
+ LSP_TOOLS_MCP_PROJECT_CONFIG: canonicalizePathList(env["LSP_TOOLS_MCP_PROJECT_CONFIG"]),
+ LSP_TOOLS_MCP_USER_CONFIG: canonicalizePath(env["LSP_TOOLS_MCP_USER_CONFIG"]),
+ LSP_TOOLS_MCP_INSTALL_DECISIONS: canonicalizePath(env["LSP_TOOLS_MCP_INSTALL_DECISIONS"]),
+ };
+}
+function canonicalizePathList(value) {
+ if (value === undefined)
+ return undefined;
+ return value
+ .split(delimiter)
+ .map((entry) => canonicalizePath(entry) ?? entry)
+ .join(delimiter);
+}
+function canonicalizePath(value) {
+ if (value === undefined || !isAbsolute(value) || !existsSync(value))
+ return value;
+ return realpathSync(value);
+}
+function projectRootFromOpenCodeConfigPath(path) {
+ if (basename(path) !== "lsp.json" && basename(path) !== "lsp-client.json")
+ return undefined;
+ const configDir = dirname(path);
+ const configDirName = basename(configDir);
+ if (configDirName !== ".opencode" && configDirName !== ".omo")
+ return undefined;
+ return dirname(configDir);
+}
diff --git a/plugins/omo/components/lsp-daemon/dist/request-routing.d.ts b/plugins/omo/components/lsp-daemon/dist/request-routing.d.ts
index eb39b28d..9f3f620c 100644
--- a/plugins/omo/components/lsp-daemon/dist/request-routing.d.ts
+++ b/plugins/omo/components/lsp-daemon/dist/request-routing.d.ts
@@ -1,9 +1,14 @@
-import { type JsonRpcResponse } from "@oh-my-opencode/lsp-core/mcp";
import { type RequestContext } from "@oh-my-opencode/lsp-core/request-context";
+import type { DaemonOwner } from "./ownership.js";
export declare const CONTEXT_KEY = "_context";
export interface RoutedRequest {
input: unknown;
context: RequestContext | undefined;
}
export declare function extractRequestContext(raw: unknown): RoutedRequest;
-export declare function handleDaemonMessage(raw: unknown): Promise<JsonRpcResponse | undefined>;
+export type DaemonRouteState = {
+ readonly token: string;
+ readonly owner: DaemonOwner;
+ readonly activeRequests?: Map<string, AbortController>;
+};
+export declare function handleDaemonMessage(raw: unknown, state: DaemonRouteState): Promise<unknown>;
diff --git a/plugins/omo/components/lsp-daemon/dist/request-routing.js b/plugins/omo/components/lsp-daemon/dist/request-routing.js
index bda778ef..8d6eee6a 100644
--- a/plugins/omo/components/lsp-daemon/dist/request-routing.js
+++ b/plugins/omo/components/lsp-daemon/dist/request-routing.js
@@ -1,42 +1,91 @@
import { handleLspMcpRequest } from "@oh-my-opencode/lsp-core/mcp";
-import { runWithRequestContext } from "@oh-my-opencode/lsp-core/request-context";
+import { parseLspRequestContext, runWithRequestContext } from "@oh-my-opencode/lsp-core/request-context";
import { isPlainRecord } from "@oh-my-opencode/mcp-stdio-core/record";
+import { authenticateMessage, OMO_DAEMON_PROTOCOL_VERSION } from "./ipc-protocol.js";
export const CONTEXT_KEY = "_context";
+class InvalidDaemonRequestError extends Error {
+ constructor() {
+ super(...arguments);
+ this.name = "InvalidDaemonRequestError";
+ }
+}
export function extractRequestContext(raw) {
if (!isPlainRecord(raw) || raw["method"] !== "tools/call")
return { input: raw, context: undefined };
const params = raw["params"];
if (!isPlainRecord(params))
- return { input: raw, context: undefined };
+ throw new InvalidDaemonRequestError("Daemon tools/call params must be an object.");
const args = params["arguments"];
if (!isPlainRecord(args))
- return { input: raw, context: undefined };
+ throw new InvalidDaemonRequestError("Daemon tools/call arguments must be an object.");
+ if (!Object.hasOwn(args, CONTEXT_KEY)) {
+ throw new InvalidDaemonRequestError("Daemon tools/call arguments must include _context.");
+ }
const context = parseContext(args[CONTEXT_KEY]);
- if (!context)
- return { input: raw, context: undefined };
const cleanedArgs = { ...args };
delete cleanedArgs[CONTEXT_KEY];
const cleaned = { ...raw, params: { ...params, arguments: cleanedArgs } };
return { input: cleaned, context };
}
-export function handleDaemonMessage(raw) {
- const { input, context } = extractRequestContext(raw);
- if (context)
- return runWithRequestContext(context, () => handleLspMcpRequest(input));
- return handleLspMcpRequest(input);
+export function handleDaemonMessage(raw, state) {
+ const authenticated = authenticateMessage(raw, state.token);
+ if ("error" in authenticated)
+ return Promise.resolve(authenticated);
+ if (authenticated.method === "omo/ping") {
+ return Promise.resolve({
+ jsonrpc: "2.0",
+ id: authenticated.id,
+ result: { protocolVersion: OMO_DAEMON_PROTOCOL_VERSION, ...state.owner },
+ });
+ }
+ if (authenticated.method === "$/cancelRequest") {
+ const targetId = cancellationTargetId(authenticated.input);
+ if (targetId !== undefined)
+ state.activeRequests?.get(String(targetId))?.abort();
+ return Promise.resolve(undefined);
+ }
+ let routed;
+ try {
+ routed = extractRequestContext(authenticated.input);
+ }
+ catch (error) {
+ const message = error instanceof Error ? error.message : "invalid daemon request";
+ return Promise.resolve({
+ jsonrpc: "2.0",
+ id: authenticated.id,
+ error: { code: -32602, message, data: { code: "invalid_daemon_request" } },
+ });
+ }
+ const { input, context } = routed;
+ const key = routeRequestKey(authenticated.id);
+ if (key === undefined || !state.activeRequests) {
+ if (context)
+ return runWithRequestContext(context, () => handleLspMcpRequest(input));
+ return handleLspMcpRequest(input);
+ }
+ const controller = new AbortController();
+ state.activeRequests.set(key, controller);
+ const options = { signal: controller.signal };
+ const run = context
+ ? runWithRequestContext(context, () => handleLspMcpRequest(input, options))
+ : handleLspMcpRequest(input, options);
+ return run.finally(() => {
+ if (state.activeRequests?.get(key) === controller)
+ state.activeRequests.delete(key);
+ });
}
-function parseContext(value) {
- if (!isPlainRecord(value))
+function routeRequestKey(id) {
+ return typeof id === "string" || typeof id === "number" ? String(id) : undefined;
+}
+function cancellationTargetId(input) {
+ const params = input["params"];
+ if (!isPlainRecord(params))
return undefined;
- const context = {};
- const cwd = value["cwd"];
- if (typeof cwd === "string")
- context.cwd = cwd;
- const env = value["env"];
- if (isStringRecord(env))
- context.env = env;
- return context.cwd === undefined && context.env === undefined ? undefined : context;
+ const id = params["id"];
+ return typeof id === "string" || typeof id === "number" ? id : undefined;
}
-function isStringRecord(value) {
- return isPlainRecord(value) && Object.values(value).every((item) => typeof item === "string");
+function parseContext(value) {
+ if (!isPlainRecord(value))
+ throw new InvalidDaemonRequestError("LSP request _context must be an object.");
+ return parseLspRequestContext(value);
}
diff --git a/plugins/omo/components/lsp-daemon/dist/run-daemon.js b/plugins/omo/components/lsp-daemon/dist/run-daemon.js
index 5006157d..d109b0f4 100644
--- a/plugins/omo/components/lsp-daemon/dist/run-daemon.js
+++ b/plugins/omo/components/lsp-daemon/dist/run-daemon.js
@@ -1,9 +1,16 @@
-import { startDaemonServer } from "./daemon-server.js";
+import { DaemonAlreadyRunningError, startDaemonServer } from "./daemon-server.js";
import { daemonPaths } from "./paths.js";
export async function runDaemon() {
process.on("uncaughtException", (error) => logNonFatal("uncaughtException", error));
process.on("unhandledRejection", (reason) => logNonFatal("unhandledRejection", reason));
- await startDaemonServer(daemonPaths());
+ try {
+ await startDaemonServer(daemonPaths());
+ }
+ catch (error) {
+ if (error instanceof DaemonAlreadyRunningError)
+ return;
+ throw error;
+ }
}
function logNonFatal(kind, error) {
const message = error instanceof Error ? (error.stack ?? error.message) : String(error);
diff --git a/plugins/omo/components/lsp-daemon/dist/runtime-contract.d.ts b/plugins/omo/components/lsp-daemon/dist/runtime-contract.d.ts
new file mode 100644
index 00000000..af8af6c1
--- /dev/null
+++ b/plugins/omo/components/lsp-daemon/dist/runtime-contract.d.ts
@@ -0,0 +1,21 @@
+export declare const OMO_LSP_DAEMON_DIR = "OMO_LSP_DAEMON_DIR";
+export declare const OMO_LSP_DAEMON_CLI = "OMO_LSP_DAEMON_CLI";
+export declare const OMO_LSP_DAEMON_VERSION = "OMO_LSP_DAEMON_VERSION";
+export interface DaemonRuntime {
+ readonly cliPath: string;
+ readonly version: string;
+}
+export type DaemonRuntimeDefaults = DaemonRuntime;
+export type InvalidRuntimeOverrideReason = "paired_values_required" | "cli_must_be_absolute" | "cli_not_found" | "cli_not_file" | "packaged_cli_must_be_absolute";
+export declare class InvalidRuntimeOverrideError extends Error {
+ readonly code = "invalid_runtime_override";
+ readonly reason: InvalidRuntimeOverrideReason;
+ constructor(reason: InvalidRuntimeOverrideReason, message: string);
+}
+export declare class InvalidDaemonVersionError extends Error {
+ readonly code = "invalid_daemon_version";
+ readonly version: string;
+ constructor(version: string);
+}
+export declare function validateDaemonVersion(version: string): string;
+export declare function resolveDaemonRuntime(env: NodeJS.ProcessEnv, defaults: DaemonRuntimeDefaults): DaemonRuntime;
diff --git a/plugins/omo/components/lsp-daemon/dist/runtime-contract.js b/plugins/omo/components/lsp-daemon/dist/runtime-contract.js
new file mode 100644
index 00000000..8526280c
--- /dev/null
+++ b/plugins/omo/components/lsp-daemon/dist/runtime-contract.js
@@ -0,0 +1,58 @@
+import { statSync } from "node:fs";
+import { isAbsolute } from "node:path";
+export const OMO_LSP_DAEMON_DIR = "OMO_LSP_DAEMON_DIR";
+export const OMO_LSP_DAEMON_CLI = "OMO_LSP_DAEMON_CLI";
+export const OMO_LSP_DAEMON_VERSION = "OMO_LSP_DAEMON_VERSION";
+const DAEMON_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
+export class InvalidRuntimeOverrideError extends Error {
+ constructor(reason, message) {
+ super(message);
+ this.code = "invalid_runtime_override";
+ this.name = "InvalidRuntimeOverrideError";
+ this.reason = reason;
+ }
+}
+export class InvalidDaemonVersionError extends Error {
+ constructor(version) {
+ super("LSP daemon version must match [A-Za-z0-9][A-Za-z0-9._+-]{0,127}");
+ this.code = "invalid_daemon_version";
+ this.name = "InvalidDaemonVersionError";
+ this.version = version;
+ }
+}
+export function validateDaemonVersion(version) {
+ if (!DAEMON_VERSION_PATTERN.test(version))
+ throw new InvalidDaemonVersionError(version);
+ return version;
+}
+export function resolveDaemonRuntime(env, defaults) {
+ const cliOverride = env[OMO_LSP_DAEMON_CLI];
+ const versionOverride = env[OMO_LSP_DAEMON_VERSION];
+ const hasCliOverride = cliOverride !== undefined;
+ const hasVersionOverride = versionOverride !== undefined;
+ if (hasCliOverride !== hasVersionOverride) {
+ throw new InvalidRuntimeOverrideError("paired_values_required", `${OMO_LSP_DAEMON_CLI} and ${OMO_LSP_DAEMON_VERSION} must be set together`);
+ }
+ if (!hasCliOverride || !hasVersionOverride) {
+ if (!isAbsolute(defaults.cliPath)) {
+ throw new InvalidRuntimeOverrideError("packaged_cli_must_be_absolute", "Packaged LSP daemon CLI path must be absolute");
+ }
+ return { cliPath: defaults.cliPath, version: validateDaemonVersion(defaults.version) };
+ }
+ if (!isAbsolute(cliOverride)) {
+ throw new InvalidRuntimeOverrideError("cli_must_be_absolute", `${OMO_LSP_DAEMON_CLI} must be an absolute path to an existing regular file`);
+ }
+ let cliStats;
+ try {
+ cliStats = statSync(cliOverride);
+ }
+ catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ throw new InvalidRuntimeOverrideError("cli_not_found", `${OMO_LSP_DAEMON_CLI} must name an existing regular file`);
+ }
+ if (!cliStats.isFile()) {
+ throw new InvalidRuntimeOverrideError("cli_not_file", `${OMO_LSP_DAEMON_CLI} must name an existing regular file`);
+ }
+ return { cliPath: cliOverride, version: validateDaemonVersion(versionOverride) };
+}
diff --git a/plugins/omo/components/lsp-daemon/dist/socket-jsonrpc.js b/plugins/omo/components/lsp-daemon/dist/socket-jsonrpc.js
index 7b8c8417..bb2d9291 100644
--- a/plugins/omo/components/lsp-daemon/dist/socket-jsonrpc.js
+++ b/plugins/omo/components/lsp-daemon/dist/socket-jsonrpc.js
@@ -15,7 +15,12 @@ export function createLineDecoder(onMessage, onParseError) {
onMessage(JSON.parse(raw));
}
catch (error) {
- onParseError?.(raw, error);
+ if (error instanceof Error) {
+ onParseError?.(raw, error);
+ }
+ else {
+ throw error;
+ }
}
}
index = buffer.indexOf("\n");
diff --git a/plugins/omo/components/lsp-tools-mcp/dist/cli.js b/plugins/omo/components/lsp-tools-mcp/dist/cli.js
index 523f43b5..2c59d346 100755
--- a/plugins/omo/components/lsp-tools-mcp/dist/cli.js
+++ b/plugins/omo/components/lsp-tools-mcp/dist/cli.js
@@ -1,33 +1,18 @@
#!/usr/bin/env node
// ../lsp-core/src/lsp/cleanup-errors.ts
-function reportBestEffortCleanupError(operation, error) {
- if (process.env["CODEX_LSP_DEBUG_CLEANUP"] !== "1")
- return;
+function writeCleanupError(message) {
+ process.stderr.write(`${message}
+`);
+}
+function reportBestEffortCleanupError(operation, error, logger = writeCleanupError) {
const message = error instanceof Error ? error.message : String(error);
- console.error(`[codex-lsp] ignored ${operation} failure during cleanup: ${message}`);
+ logger(`[lsp] ignored ${operation} failure during cleanup: ${message}`);
}
// ../lsp-core/src/lsp/client.ts
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
-import { pathToFileURL as pathToFileURL2 } from "node:url";
-
-// ../lsp-core/src/request-context.ts
-import { AsyncLocalStorage } from "node:async_hooks";
-var storage = new AsyncLocalStorage;
-function runWithRequestContext(context, fn) {
- return storage.run(context, fn);
-}
-function contextCwd() {
- return storage.getStore()?.cwd ?? process.cwd();
-}
-function contextEnv(key) {
- const store = storage.getStore();
- if (store?.env)
- return store.env[key];
- return process.env[key];
-}
+import { resolve as resolve5 } from "node:path";
+import { pathToFileURL as pathToFileURL3 } from "node:url";
// ../lsp-core/src/lsp/connection.ts
import { pathToFileURL } from "node:url";
@@ -91,7 +76,12 @@ class LspInvalidPathError extends Error {
}
class LspServerLookupError extends Error {
+ lookup;
name = "LspServerLookupError";
+ constructor(message, lookup) {
+ super(message);
+ this.lookup = lookup;
+ }
}
class LspServerInitializingError extends Error {
@@ -157,28 +147,80 @@ class JsonRpcConnection {
onError(handler) {
this.errorHandlers.push(handler);
}
- async sendRequest(method, params) {
+ async sendRequest(method, params, options = {}) {
if (this.disposed)
throw new Error("JSON-RPC connection is disposed");
const id = this.nextRequestId;
this.nextRequestId += 1;
+ const key = String(id);
const message = params === undefined ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
+ let requestWritten = false;
+ let cancelAfterWrite = false;
+ let settled = false;
+ const writeCancel = () => this.writeMessage({ jsonrpc: "2.0", method: "$/cancelRequest", params: { id } });
const responsePromise = new Promise((resolve, reject) => {
- this.pendingRequests.set(String(id), {
+ const cleanup = () => {
+ options.signal?.removeEventListener("abort", onAbort);
+ };
+ const settleCancel = () => {
+ if (settled)
+ return;
+ settled = true;
+ this.pendingRequests.delete(key);
+ cleanup();
+ const rejectCancelled = () => reject(abortError(options.signal));
+ if (!requestWritten) {
+ cancelAfterWrite = true;
+ rejectCancelled();
+ return;
+ }
+ writeCancel().then(rejectCancelled, (error) => {
+ this.emitError(toError(error));
+ rejectCancelled();
+ });
+ };
+ const onAbort = () => settleCancel();
+ this.pendingRequests.set(key, {
resolve(result) {
+ settled = true;
+ cleanup();
resolve(result);
},
- reject
+ reject(error) {
+ settled = true;
+ cleanup();
+ reject(error);
+ },
+ cleanup
});
+ if (options.signal?.aborted) {
+ settleCancel();
+ return;
+ }
+ options.signal?.addEventListener("abort", onAbort, { once: true });
});
+ if (settled)
+ return responsePromise;
try {
await this.writeMessage(message);
+ requestWritten = true;
+ if (cancelAfterWrite)
+ await writeCancel();
} catch (error) {
- this.pendingRequests.delete(String(id));
+ if (settled)
+ return responsePromise;
+ const pending = this.pendingRequests.get(key);
+ if (pending) {
+ pending.cleanup();
+ this.pendingRequests.delete(key);
+ }
throw error;
}
return responsePromise;
}
+ pendingRequestCount() {
+ return this.pendingRequests.size;
+ }
async sendNotification(method, params) {
if (this.disposed)
return;
@@ -195,6 +237,7 @@ class JsonRpcConnection {
this.reader.off("error", this.handleStreamError);
this.writer.off("error", this.handleStreamError);
for (const pending of this.pendingRequests.values()) {
+ pending.cleanup();
pending.reject(new Error("JSON-RPC connection disposed"));
}
this.pendingRequests.clear();
@@ -270,6 +313,7 @@ class JsonRpcConnection {
if (!pending)
return;
this.pendingRequests.delete(String(id));
+ pending.cleanup();
if ("error" in message) {
pending.reject(jsonRpcErrorToError(message["error"]));
return;
@@ -283,7 +327,11 @@ class JsonRpcConnection {
try {
handler(params);
} catch (error) {
- this.emitError(toError(error));
+ if (error instanceof Error) {
+ this.emitError(error);
+ return;
+ }
+ this.emitError(new Error(String(error)));
}
}
handleRequest(message) {
@@ -324,6 +372,14 @@ ${body}`;
}
}
}
+function abortError(signal) {
+ const reason = signal?.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "LSP request cancelled");
+ error.name = "AbortError";
+ return error;
+}
function parseContentLength(headers) {
for (const line of headers.split(`\r
`)) {
@@ -510,7 +566,7 @@ function spawnProcess(command, options) {
return wrap(proc);
}
-// ../lsp-core/src/lsp/transport.ts
+// ../lsp-core/src/lsp/transport-protocol.ts
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
@@ -530,7 +586,32 @@ function parseDiagnosticsParams(params) {
if (!isRecord(params) || typeof params["uri"] !== "string")
return null;
const diagnostics = Array.isArray(params["diagnostics"]) ? params["diagnostics"].filter(isDiagnostic) : [];
- return { uri: params["uri"], diagnostics };
+ const version = typeof params["version"] === "number" ? params["version"] : undefined;
+ return { uri: params["uri"], diagnostics, ...version === undefined ? {} : { version } };
+}
+function createLspSpawnEnv(_root, input) {
+ return { ...input };
+}
+function isDiagnostic(value) {
+ return isRecord(value) && isRange(value["range"]) && typeof value["message"] === "string";
+}
+function isRange(value) {
+ return isRecord(value) && isPosition(value["start"]) && isPosition(value["end"]);
+}
+function isPosition(value) {
+ return isRecord(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+}
+
+// ../lsp-core/src/lsp/transport.ts
+class LspClientNotStartedError extends Error {
+ serverId;
+ root;
+ name = "LspClientNotStartedError";
+ constructor(serverId, root) {
+ super("LSP client not started");
+ this.serverId = serverId;
+ this.root = root;
+ }
}
class LspClientTransport {
@@ -543,6 +624,8 @@ class LspClientTransport {
diagnosticsStore = new Map;
requestTimeoutMs;
initializeTimeoutMs;
+ workspaceApplyEditHandler = null;
+ diagnosticPullSupported = false;
constructor(root, server, timeouts = {}) {
this.root = root;
this.server = server;
@@ -555,6 +638,21 @@ class LspClientTransport {
command() {
return [...this.server.command];
}
+ setWorkspaceApplyEditHandler(handler) {
+ this.workspaceApplyEditHandler = handler;
+ }
+ hasWorkspaceApplyEditHandler() {
+ return this.workspaceApplyEditHandler !== null;
+ }
+ setDiagnosticPullSupported(supported) {
+ this.diagnosticPullSupported = supported;
+ }
+ isDiagnosticPullSupported() {
+ return this.diagnosticPullSupported;
+ }
+ handlePublishDiagnostics(params) {
+ this.diagnosticsStore.set(params.uri, [...params.diagnostics]);
+ }
async start() {
const env = createLspSpawnEnv(this.root, {
...process.env,
@@ -565,7 +663,6 @@ class LspClientTransport {
env
});
this.startStderrReading();
- await new Promise((resolve) => setTimeout(resolve, 100));
if (this.proc.exitCode !== null) {
const stderr = this.stderrBuffer.join(`
`);
@@ -575,7 +672,7 @@ class LspClientTransport {
this.connection.onNotification("textDocument/publishDiagnostics", (params) => {
const diagnosticsParams = parseDiagnosticsParams(params);
if (diagnosticsParams?.uri) {
- this.diagnosticsStore.set(diagnosticsParams.uri, diagnosticsParams.diagnostics);
+ this.handlePublishDiagnostics(diagnosticsParams);
}
});
this.connection.onRequest("workspace/configuration", (params) => {
@@ -588,6 +685,9 @@ class LspClientTransport {
});
this.connection.onRequest("client/registerCapability", () => null);
this.connection.onRequest("window/workDoneProgress/create", () => null);
+ if (this.workspaceApplyEditHandler) {
+ this.connection.onRequest("workspace/applyEdit", this.workspaceApplyEditHandler);
+ }
this.connection.onClose(() => {
this.processExited = true;
});
@@ -616,30 +716,25 @@ class LspClientTransport {
}
async sendRequest(method, ...args) {
if (!this.connection)
- throw new Error("LSP client not started");
+ throw new LspClientNotStartedError(this.server.id, this.root);
if (this.processExited || this.proc && this.proc.exitCode !== null) {
const stderrTail = this.stderrBuffer.slice(-10).join(`
`);
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, stderrTail || undefined);
}
- const timeoutMs = args[1]?.timeoutMs ?? this.requestTimeoutMs;
- let timeoutHandle = null;
- const timeoutPromise = new Promise((_, reject) => {
- timeoutHandle = setTimeout(() => {
- const stderrTail = this.stderrBuffer.slice(-5).join(`
+ const options = args[1];
+ const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
+ const timeoutController = new AbortController;
+ const timeoutHandle = setTimeout(() => {
+ const stderrTail = this.stderrBuffer.slice(-5).join(`
`);
- reject(new LspRequestTimeoutError(method, stderrTail || undefined));
- }, timeoutMs);
- });
+ timeoutController.abort(new LspRequestTimeoutError(method, stderrTail || undefined));
+ }, timeoutMs);
+ const combinedSignal = combineAbortSignals(options?.signal, timeoutController.signal);
try {
- const requestPromise = args.length === 0 ? this.connection.sendRequest(method) : this.connection.sendRequest(method, args[0]);
- const result = await Promise.race([requestPromise, timeoutPromise]);
- if (timeoutHandle !== null)
- clearTimeout(timeoutHandle);
+ const result = args.length === 0 ? await this.connection.sendRequest(method, undefined, { signal: combinedSignal.signal }) : await this.connection.sendRequest(method, args[0], { signal: combinedSignal.signal });
return result;
} catch (error) {
- if (timeoutHandle !== null)
- clearTimeout(timeoutHandle);
if (this.processExited || this.proc && this.proc.exitCode !== null) {
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, this.stderrBuffer.slice(-10).join(`
`) || undefined);
@@ -648,6 +743,9 @@ class LspClientTransport {
throw new LspConnectionClosedError(this.server.id, this.root, error.message);
}
throw error;
+ } finally {
+ clearTimeout(timeoutHandle);
+ combinedSignal.dispose();
}
}
async sendNotification(method, ...args) {
@@ -676,17 +774,17 @@ class LspClientTransport {
try {
await this.sendRequest("shutdown");
} catch (error) {
- reportBestEffortCleanupError("shutdown request", error);
+ reportBestEffortCleanupError("shutdown request", error instanceof Error ? error : String(error));
}
try {
await this.sendNotification("exit");
} catch (error) {
- reportBestEffortCleanupError("exit notification", error);
+ reportBestEffortCleanupError("exit notification", error instanceof Error ? error : String(error));
}
try {
this.connection.dispose();
} catch (error) {
- reportBestEffortCleanupError("connection dispose", error);
+ reportBestEffortCleanupError("connection dispose", error instanceof Error ? error : String(error));
}
this.connection = null;
}
@@ -717,11 +815,11 @@ class LspClientTransport {
new Promise((resolve) => setTimeout(resolve, STOP_SIGKILL_GRACE_MS))
]);
} catch (error) {
- reportBestEffortCleanupError("hard process kill", error);
+ reportBestEffortCleanupError("hard process kill", error instanceof Error ? error : String(error));
}
}
} catch (error) {
- reportBestEffortCleanupError("process stop", error);
+ reportBestEffortCleanupError("process stop", error instanceof Error ? error : String(error));
}
}
this.processExited = true;
@@ -731,26 +829,45 @@ class LspClientTransport {
return this.diagnosticsStore.get(uri) ?? [];
}
}
-function createLspSpawnEnv(_root, input) {
- return { ...input };
-}
-function isDiagnostic(value) {
- return isRecord(value) && isRange(value["range"]) && typeof value["message"] === "string";
-}
-function isRange(value) {
- return isRecord(value) && isPosition(value["start"]) && isPosition(value["end"]);
-}
-function isPosition(value) {
- return isRecord(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+function combineAbortSignals(primary, secondary) {
+ const controller = new AbortController;
+ const abortFrom = (signal) => {
+ if (!controller.signal.aborted)
+ controller.abort(signal.reason);
+ };
+ const onPrimaryAbort = () => {
+ if (primary)
+ abortFrom(primary);
+ };
+ const onSecondaryAbort = () => abortFrom(secondary);
+ if (primary?.aborted)
+ abortFrom(primary);
+ else
+ primary?.addEventListener("abort", onPrimaryAbort, { once: true });
+ if (secondary.aborted)
+ abortFrom(secondary);
+ else
+ secondary.addEventListener("abort", onSecondaryAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => {
+ primary?.removeEventListener("abort", onPrimaryAbort);
+ secondary.removeEventListener("abort", onSecondaryAbort);
+ }
+ };
}
// ../lsp-core/src/lsp/connection.ts
-var INITIALIZE_SETTLE_MS = 300;
+function supportsDiagnosticPull(capabilities) {
+ if (capabilities === undefined)
+ return false;
+ return Object.hasOwn(capabilities, "diagnosticProvider");
+}
class LspClientConnection extends LspClientTransport {
async initialize() {
const rootUri = pathToFileURL(this.root).href;
- await this.sendRequest("initialize", {
+ const result = await this.sendRequest("initialize", {
processId: process.pid,
rootUri,
rootPath: this.root,
@@ -764,8 +881,7 @@ class LspClientConnection extends LspClientTransport {
publishDiagnostics: {},
rename: {
prepareSupport: true,
- prepareSupportDefaultBehavior: 1,
- honorsChangeAnnotations: true
+ prepareSupportDefaultBehavior: 1
},
codeAction: {
codeActionLiteralSupport: {
@@ -794,22 +910,28 @@ class LspClientConnection extends LspClientTransport {
symbol: {},
workspaceFolders: true,
configuration: true,
- applyEdit: true,
+ ...this.hasWorkspaceApplyEditHandler() ? { applyEdit: true } : {},
workspaceEdit: {
- documentChanges: true
+ documentChanges: true,
+ resourceOperations: ["create", "rename", "delete"]
}
}
},
initializationOptions: this.server.initialization
}, { timeoutMs: this.initializeTimeoutMs });
+ this.setDiagnosticPullSupported(supportsDiagnosticPull(result?.capabilities));
await this.sendNotification("initialized");
await this.sendNotification("workspace/didChangeConfiguration", {
settings: { json: { validate: { enable: true } } }
});
- await new Promise((r) => setTimeout(r, INITIALIZE_SETTLE_MS));
}
}
+// ../lsp-core/src/lsp/workspace-document-state.ts
+import { readFileSync, realpathSync } from "node:fs";
+import { relative, resolve } from "node:path";
+import { pathToFileURL as pathToFileURL2 } from "node:url";
+
// ../lsp-core/src/lsp/effective-extension.ts
import { basename, extname } from "node:path";
var BASENAME_EXTENSIONS = {
@@ -992,82 +1114,1422 @@ function getLanguageId(ext) {
return EXT_TO_LANG[ext] ?? "plaintext";
}
+// ../lsp-core/src/lsp/workspace-document-state.ts
+var WATCHED_FILE_BATCH_SIZE = 128;
+var DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
+function canonicalPath(filePath) {
+ const absolute = resolve(filePath);
+ try {
+ return realpathSync(absolute);
+ } catch {
+ return absolute;
+ }
+}
+function isSameOrDescendant(candidate, parent) {
+ const suffix = relative(parent, candidate);
+ return suffix === "" || !suffix.startsWith("..") && suffix !== "..";
+}
+function movedPath(candidate, oldPath, newPath) {
+ const suffix = relative(oldPath, candidate);
+ return suffix === "" ? newPath : resolve(newPath, suffix);
+}
+
+class WorkspaceDocumentState {
+ sendNotification;
+ clearDiagnostics;
+ openDocuments = new Map;
+ openByUri = new Map;
+ openPromises = new Map;
+ now;
+ versionlessPublishQuiescenceMs;
+ constructor(sendNotification, clearDiagnostics, options = {}) {
+ this.sendNotification = sendNotification;
+ this.clearDiagnostics = clearDiagnostics;
+ this.now = options.now ?? (() => Date.now());
+ this.versionlessPublishQuiescenceMs = options.versionlessPublishQuiescenceMs ?? DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS;
+ }
+ async openFile(filePath) {
+ const path = canonicalPath(filePath);
+ const existingOpen = this.openPromises.get(path);
+ if (existingOpen) {
+ await existingOpen;
+ return this.openFile(path);
+ }
+ const text = readFileSync(path, "utf-8");
+ const existing = this.openDocuments.get(path);
+ if (!existing)
+ return this.openDocumentSingleFlight(path, text);
+ if (existing.text === text)
+ return;
+ await this.changeDocument(existing, text);
+ }
+ getVersion(filePath) {
+ return this.openDocuments.get(canonicalPath(filePath))?.version;
+ }
+ getStoredDiagnostics(uri) {
+ const state = this.openByUri.get(uri);
+ if (!state)
+ return [];
+ return state.lastPublish?.diagnostics ?? state.pullCache?.diagnostics ?? [];
+ }
+ captureDiagnosticSnapshot(filePath) {
+ const state = this.openDocuments.get(canonicalPath(filePath));
+ if (!state)
+ return null;
+ return {
+ path: state.path,
+ uri: state.uri,
+ version: state.version,
+ documentGeneration: state.generation,
+ publishGeneration: state.publishGeneration
+ };
+ }
+ isCurrentSnapshot(snapshot) {
+ const state = this.openDocuments.get(snapshot.path);
+ return state !== undefined && state.uri === snapshot.uri && state.version === snapshot.version && state.generation === snapshot.documentGeneration;
+ }
+ getPullCache(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.pullCache || state.pullCache.documentVersion !== snapshot.version)
+ return null;
+ return state.pullCache;
+ }
+ recordPullDiagnostics(snapshot, report) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state)
+ return;
+ state.pullCache = {
+ documentVersion: snapshot.version,
+ diagnostics: [...report.diagnostics],
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ };
+ }
+ recordPublishedDiagnostics(params) {
+ const state = this.openByUri.get(params.uri);
+ if (!state)
+ return;
+ state.publishGeneration += 1;
+ state.lastPublish = {
+ diagnostics: [...params.diagnostics],
+ publishGeneration: state.publishGeneration,
+ documentGenerationAtArrival: state.generation,
+ arrivedAt: this.now(),
+ ...params.version === undefined ? {} : { version: params.version }
+ };
+ this.notifyWaiters(state);
+ }
+ resolvePushDiagnostics(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.lastPublish)
+ return { status: "missing" };
+ const publish = state.lastPublish;
+ if (publish.version !== undefined) {
+ return publish.version === snapshot.version ? { status: "ready", diagnostics: publish.diagnostics } : { status: "missing" };
+ }
+ if (publish.documentGenerationAtArrival < snapshot.documentGeneration)
+ return { status: "missing" };
+ const readyAt = publish.arrivedAt + this.versionlessPublishQuiescenceMs;
+ const waitMs = Math.max(0, readyAt - this.now());
+ return waitMs === 0 ? { status: "ready", diagnostics: publish.diagnostics } : { status: "wait", waitMs };
+ }
+ waitForDiagnosticsActivity(snapshot, timeoutMs) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state || timeoutMs <= 0)
+ return Promise.resolve();
+ return new Promise((resolveActivity) => {
+ let settled = false;
+ const finish = () => {
+ if (settled)
+ return;
+ settled = true;
+ clearTimeout(timer);
+ state.waiters.delete(finish);
+ resolveActivity();
+ };
+ const timer = setTimeout(finish, timeoutMs);
+ if (typeof timer.unref === "function")
+ timer.unref();
+ state.waiters.add(finish);
+ });
+ }
+ validateVersions(operations) {
+ const versions = new Map([...this.openDocuments].map(([path, state]) => [path, state.version]));
+ for (const operation of operations) {
+ if (operation.kind === "text") {
+ const current = versions.get(operation.path);
+ if (operation.documentVersion !== null && current !== operation.documentVersion) {
+ const observed = current === undefined ? "closed document" : `open document version ${current}`;
+ return {
+ changeIndex: operation.changeIndex,
+ message: `document version ${operation.documentVersion} does not match ${observed} for ${operation.path}`
+ };
+ }
+ if (current !== undefined)
+ versions.set(operation.path, current + 1);
+ continue;
+ }
+ if (operation.kind === "rename") {
+ const moved = [...versions].filter(([path]) => isSameOrDescendant(path, operation.oldPath));
+ for (const [path] of moved)
+ versions.delete(path);
+ for (const [path] of moved)
+ versions.set(movedPath(path, operation.oldPath, operation.newPath), 1);
+ continue;
+ }
+ if (operation.kind === "delete") {
+ for (const path of [...versions.keys()]) {
+ if (isSameOrDescendant(path, operation.path))
+ versions.delete(path);
+ }
+ continue;
+ }
+ if (operation.kind === "create" && operation.replaced && versions.has(operation.path)) {
+ versions.set(operation.path, 1);
+ }
+ }
+ return null;
+ }
+ async synchronize(delta) {
+ const watched = [];
+ for (const mutation of delta.operations)
+ await this.synchronizeMutation(mutation, watched);
+ for (let index = 0;index < watched.length; index += WATCHED_FILE_BATCH_SIZE) {
+ await this.sendNotification("workspace/didChangeWatchedFiles", {
+ changes: watched.slice(index, index + WATCHED_FILE_BATCH_SIZE)
+ });
+ }
+ }
+ async synchronizeMutation(mutation, watched) {
+ if (mutation.kind === "text") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state)
+ await this.changeDocument(state, mutation.afterText);
+ else
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 2 });
+ return;
+ }
+ if (mutation.kind === "create") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state) {
+ await this.closeDocument(state);
+ await this.openDocumentSingleFlight(mutation.path, readFileSync(mutation.path, "utf-8"));
+ } else {
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: mutation.replaced ? 2 : 1 });
+ }
+ return;
+ }
+ if (mutation.kind === "rename") {
+ const moved = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.oldPath));
+ for (const state of moved)
+ await this.closeDocument(state);
+ for (const state of moved) {
+ const path = movedPath(state.path, mutation.oldPath, mutation.newPath);
+ await this.openDocumentSingleFlight(path, readFileSync(path, "utf-8"));
+ }
+ if (moved.length === 0) {
+ watched.push({ uri: pathToFileURL2(mutation.oldPath).href, type: 3 });
+ watched.push({ uri: pathToFileURL2(mutation.newPath).href, type: 1 });
+ }
+ return;
+ }
+ const removed = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.path));
+ for (const state of removed)
+ await this.closeDocument(state);
+ if (removed.length === 0)
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 3 });
+ }
+ async openDocumentSingleFlight(path, text) {
+ const existing = this.openPromises.get(path);
+ if (existing)
+ return existing;
+ const open = (async () => {
+ const state = {
+ path,
+ uri: pathToFileURL2(path).href,
+ languageId: getLanguageId(effectiveExtension(path)),
+ text,
+ version: 1,
+ generation: 1,
+ publishGeneration: 0,
+ waiters: new Set
+ };
+ this.openDocuments.set(path, state);
+ this.openByUri.set(state.uri, state);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didOpen", {
+ textDocument: { uri: state.uri, languageId: state.languageId, version: state.version, text }
+ });
+ })().finally(() => {
+ this.openPromises.delete(path);
+ });
+ this.openPromises.set(path, open);
+ return open;
+ }
+ async changeDocument(state, text) {
+ state.text = text;
+ state.version += 1;
+ state.generation += 1;
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didChange", {
+ textDocument: { uri: state.uri, version: state.version },
+ contentChanges: [{ text }]
+ });
+ await this.sendNotification("textDocument/didSave", { textDocument: { uri: state.uri }, text });
+ }
+ async closeDocument(state) {
+ this.openDocuments.delete(state.path);
+ this.openByUri.delete(state.uri);
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didClose", { textDocument: { uri: state.uri } });
+ }
+ notifyWaiters(state) {
+ for (const waiter of [...state.waiters])
+ waiter();
+ }
+}
+
+// ../lsp-core/src/lsp/workspace-apply-edit-failure.ts
+var CONCURRENT_FAILURE_REASON_BY_PHASE = {
+ applying: "workspace/applyEdit is already in progress for this workspace mutation",
+ settled: "workspace/applyEdit was already handled for this workspace mutation"
+};
+function workspaceApplyEditConcurrentFailureReason(phase) {
+ return CONCURRENT_FAILURE_REASON_BY_PHASE[phase];
+}
+
+// ../lsp-core/src/lsp/workspace-edit-commit.ts
+import { existsSync as existsSync3, lstatSync as lstatSync2, renameSync, rmSync, writeFileSync } from "node:fs";
+
+// ../lsp-core/src/lsp/workspace-edit-path.ts
+import { existsSync as existsSync2, lstatSync, readFileSync as readFileSync2, readdirSync, realpathSync as realpathSync2 } from "node:fs";
+import { dirname, isAbsolute, relative as relative2, resolve as resolve2 } from "node:path";
+import { fileURLToPath } from "node:url";
+
+class WorkspaceEditPathError extends Error {
+ path;
+ detail;
+ name = "WorkspaceEditPathError";
+ constructor(path, detail) {
+ super(`${detail}: ${path}`);
+ this.path = path;
+ this.detail = detail;
+ }
+}
+function isPathInsideWorkspace(filePath, workspaceRoot) {
+ const relativePath = relative2(workspaceRoot, filePath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute(relativePath);
+}
+function canonicalizeMissingPath(filePath) {
+ let ancestor = filePath;
+ while (!existsSync2(ancestor)) {
+ const parent = dirname(ancestor);
+ if (parent === ancestor)
+ throw new WorkspaceEditPathError(filePath, "no existing ancestor");
+ ancestor = parent;
+ }
+ return resolve2(realpathSync2(ancestor), relative2(ancestor, filePath));
+}
+function canonicalWorkspaceRoot(workspaceRoot) {
+ try {
+ const canonical = realpathSync2(resolve2(workspaceRoot));
+ if (!lstatSync(canonical).isDirectory()) {
+ return { success: false, error: `workspace root is not a directory: ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath: resolve2(workspaceRoot),
+ followedSymbolicLink: existsSync2(resolve2(workspaceRoot)) && lstatSync(resolve2(workspaceRoot)).isSymbolicLink()
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `workspace root ${workspaceRoot}: ${detail}` };
+ }
+}
+function uriToCanonicalWorkspacePath(uri, workspaceRoot) {
+ let requestedPath;
+ try {
+ const parsed = new URL(uri);
+ if (parsed.protocol !== "file:" || parsed.search !== "" || parsed.hash !== "") {
+ return { success: false, error: `non-file URI ${uri}` };
+ }
+ requestedPath = resolve2(fileURLToPath(parsed));
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `non-file URI ${uri}: ${detail}` };
+ }
+ try {
+ const canonical = existsSync2(requestedPath) ? realpathSync2(requestedPath) : canonicalizeMissingPath(requestedPath);
+ if (!isPathInsideWorkspace(canonical, workspaceRoot)) {
+ return { success: false, error: `${requestedPath}: outside workspace ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath,
+ followedSymbolicLink: existsSync2(requestedPath) && lstatSync(requestedPath).isSymbolicLink()
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `${requestedPath}: ${detail}` };
+ }
+}
+function snapshotPath(path, includeChildren) {
+ if (!existsSync2(path))
+ return { kind: "missing" };
+ const stats = lstatSync(path);
+ if (stats.isFile())
+ return { kind: "file", content: readFileSync2(path, "utf-8") };
+ if (stats.isDirectory()) {
+ return includeChildren ? { kind: "directory", children: readdirSync(path).sort() } : { kind: "directory" };
+ }
+ throw new WorkspaceEditPathError(path, "unsupported filesystem entry");
+}
+
+// ../lsp-core/src/lsp/workspace-edit-commit.ts
+var DEFAULT_IO = {
+ writeFile(path, content) {
+ writeFileSync(path, content, "utf-8");
+ },
+ rename(oldPath, newPath) {
+ renameSync(oldPath, newPath);
+ },
+ remove(path, recursive) {
+ rmSync(path, { recursive, force: false });
+ }
+};
+function snapshotsEqual(expected, actual) {
+ if (expected.kind !== actual.kind)
+ return false;
+ if (expected.kind === "file" && actual.kind === "file")
+ return expected.content === actual.content;
+ if (expected.kind === "directory" && actual.kind === "directory" && expected.children !== undefined) {
+ return JSON.stringify(expected.children) === JSON.stringify(actual.children);
+ }
+ return true;
+}
+function liveSnapshot(path, expected) {
+ return snapshotPath(path, expected.kind === "directory" && expected.children !== undefined);
+}
+function firstOperationIndex(plan) {
+ return plan.operations[0]?.changeIndex ?? 0;
+}
+function failedCommit(plan, failure) {
+ const { message, changeIndex, mutations = [], filesModified = [], totalEdits = 0, lateAbort = false } = failure;
+ return {
+ result: {
+ success: false,
+ filesModified,
+ totalEdits,
+ errors: [`change ${changeIndex}: ${message}`],
+ failedChange: changeIndex,
+ ...lateAbort ? { lateAbort: true } : {}
+ },
+ delta: mutationDelta(mutations),
+ fingerprint: plan.fingerprint
+ };
+}
+function verifySnapshots(plan) {
+ for (const [path, expected] of plan.snapshots) {
+ let actual;
+ try {
+ actual = liveSnapshot(path, expected);
+ } catch (error) {
+ const changeIndex = plan.firstChangeByPath.get(path) ?? firstOperationIndex(plan);
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, { message: `cannot verify snapshot for ${path}: ${detail}`, changeIndex });
+ }
+ if (!snapshotsEqual(expected, actual)) {
+ const changeIndex = plan.firstChangeByPath.get(path) ?? firstOperationIndex(plan);
+ return failedCommit(plan, { message: `workspace state changed before commit: ${path}`, changeIndex });
+ }
+ }
+ return null;
+}
+function addModifiedPath(paths, path) {
+ if (!paths.includes(path))
+ paths.push(path);
+}
+function reportedPath(plan, path) {
+ return plan.reportedPathByCanonical.get(path) ?? path;
+}
+function changedPathsForMutation(mutation) {
+ return mutation.kind === "rename" ? [mutation.oldPath, mutation.newPath] : [mutation.path];
+}
+function mutationDelta(operations) {
+ const changedPaths = new Set;
+ for (const operation of operations) {
+ for (const path of changedPathsForMutation(operation))
+ changedPaths.add(path);
+ }
+ return { operations, changedPaths: [...changedPaths].sort() };
+}
+function resolveIo(overrides) {
+ return {
+ writeFile: overrides?.writeFile ?? DEFAULT_IO.writeFile,
+ rename: overrides?.rename ?? DEFAULT_IO.rename,
+ remove: overrides?.remove ?? DEFAULT_IO.remove
+ };
+}
+function commitOperation(context, operation) {
+ const { plan, io, accumulator } = context;
+ if (operation.kind === "noop")
+ return;
+ if (operation.kind === "text") {
+ io.writeFile(operation.path, operation.afterText);
+ accumulator.mutations.push({
+ kind: "text",
+ path: operation.path,
+ beforeText: operation.beforeText,
+ afterText: operation.afterText
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ accumulator.totalEdits += operation.editCount;
+ return;
+ }
+ if (operation.kind === "create") {
+ io.writeFile(operation.path, "");
+ accumulator.mutations.push({ kind: "create", path: operation.path, replaced: operation.replaced });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ return;
+ }
+ if (operation.kind === "rename") {
+ if (operation.replaceDestination) {
+ const targetKind = existsSync3(operation.newPath) && lstatSync2(operation.newPath).isDirectory() ? "directory" : "file";
+ io.remove(operation.newPath, targetKind === "directory");
+ accumulator.mutations.push({ kind: "delete", path: operation.newPath, targetKind });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ }
+ io.rename(operation.oldPath, operation.newPath);
+ accumulator.mutations.push({
+ kind: "rename",
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: operation.sourceKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ return;
+ }
+ io.remove(operation.path, operation.recursive);
+ accumulator.mutations.push({
+ kind: "delete",
+ path: operation.path,
+ targetKind: operation.targetKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+}
+function commitWorkspaceEditPlan(plan, options = {}) {
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const stale = verifySnapshots(plan);
+ if (stale)
+ return stale;
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const io = resolveIo(options.io);
+ const accumulator = { mutations: [], filesModified: [], totalEdits: 0 };
+ const context = { plan, io, accumulator };
+ let lateAbort = false;
+ for (const operation of plan.operations) {
+ try {
+ commitOperation(context, operation);
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, {
+ message: `I/O failure during ${operation.kind}: ${detail}`,
+ changeIndex: operation.changeIndex,
+ mutations: accumulator.mutations,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ lateAbort: lateAbort || options.signal?.aborted === true
+ });
+ }
+ if (options.signal?.aborted)
+ lateAbort = true;
+ }
+ const result = {
+ success: true,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ errors: [],
+ ...lateAbort ? { lateAbort: true } : {}
+ };
+ return { result, delta: mutationDelta(accumulator.mutations), fingerprint: plan.fingerprint };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-fingerprint.ts
+import { createHash } from "node:crypto";
+function canonicalFingerprint(operations) {
+ const canonical = operations.map((operation) => {
+ switch (operation.kind) {
+ case "text":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ edits: operation.edits,
+ version: operation.version
+ };
+ case "rename":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "create":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "delete":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ recursive: operation.recursive,
+ ignoreIfNotExists: operation.ignoreIfNotExists
+ };
+ }
+ });
+ return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
+}
+
+// ../lsp-core/src/lsp/workspace-edit-types.ts
+class WorkspaceEditValidationError extends Error {
+ changeIndex;
+ detail;
+ name = "WorkspaceEditValidationError";
+ constructor(changeIndex, detail) {
+ super(`change ${changeIndex}: ${detail}`);
+ this.changeIndex = changeIndex;
+ this.detail = detail;
+ }
+}
+
+// ../lsp-core/src/lsp/workspace-edit-parse-helpers.ts
+function isRecord2(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function parsePosition(value) {
+ if (!isRecord2(value) || typeof value["line"] !== "number" || typeof value["character"] !== "number") {
+ return null;
+ }
+ return { line: value["line"], character: value["character"] };
+}
+function parseRange(value) {
+ if (!isRecord2(value))
+ return null;
+ const start = parsePosition(value["start"]);
+ const end = parsePosition(value["end"]);
+ return start && end ? { start, end } : null;
+}
+function parseTextEdits(value, changeIndex) {
+ if (!Array.isArray(value)) {
+ throw new WorkspaceEditValidationError(changeIndex, "text edits must be an array");
+ }
+ const edits = [];
+ for (const candidate of value) {
+ if (!isRecord2(candidate) || typeof candidate["newText"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "text edit requires range and newText");
+ }
+ if ("annotationId" in candidate) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated text edits are unsupported");
+ }
+ const range = parseRange(candidate["range"]);
+ if (!range)
+ throw new WorkspaceEditValidationError(changeIndex, "text edit range is malformed");
+ edits.push({ range, newText: candidate["newText"] });
+ }
+ return edits;
+}
+function parseBooleanOption(options, key, changeIndex) {
+ const value = options[key];
+ if (value === undefined)
+ return false;
+ if (typeof value !== "boolean") {
+ throw new WorkspaceEditValidationError(changeIndex, `${key} must be boolean`);
+ }
+ return value;
+}
+function parseOptions(value, allowed, changeIndex) {
+ if (value === undefined)
+ return {};
+ if (!isRecord2(value))
+ throw new WorkspaceEditValidationError(changeIndex, "resource options must be an object");
+ for (const key of Object.keys(value)) {
+ if (!allowed.includes(key))
+ throw new WorkspaceEditValidationError(changeIndex, `unsupported resource option ${key}`);
+ }
+ const parsed = {};
+ for (const key of allowed)
+ parsed[key] = parseBooleanOption(value, key, changeIndex);
+ return parsed;
+}
+
+// ../lsp-core/src/lsp/workspace-edit-resource-parser.ts
+function parseResourceChange(input) {
+ const kind = input.change["kind"];
+ if (kind === "create" || kind === "delete") {
+ parseSinglePathResource(input, kind);
+ return;
+ }
+ if (kind !== "rename") {
+ throw new WorkspaceEditValidationError(input.changeIndex, `unsupported resource operation ${String(kind)}`);
+ }
+ parseRename(input);
+}
+function parseSinglePathResource(input, kind) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["uri"] !== "string")
+ throw new WorkspaceEditValidationError(changeIndex, `${kind}.uri is required`);
+ const resolvedPath = uriToCanonicalWorkspacePath(change["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ if (kind === "create") {
+ const options2 = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ overwrite: options2["overwrite"] ?? false,
+ ignoreIfExists: options2["ignoreIfExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["recursive", "ignoreIfNotExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ recursive: options["recursive"] ?? false,
+ ignoreIfNotExists: options["ignoreIfNotExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+}
+function parseRename(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["oldUri"] !== "string" || typeof change["newUri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "rename requires oldUri and newUri");
+ }
+ const oldPath = uriToCanonicalWorkspacePath(change["oldUri"], workspaceRoot);
+ const newPath = uriToCanonicalWorkspacePath(change["newUri"], workspaceRoot);
+ if (!oldPath.success || !newPath.success) {
+ target.failures.push({
+ changeIndex,
+ message: !oldPath.success ? oldPath.error : !newPath.success ? newPath.error : "invalid rename path"
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind: "rename",
+ changeIndex,
+ oldPath: oldPath.path,
+ newPath: newPath.path,
+ reportedOldPath: oldPath.requestedPath,
+ reportedNewPath: newPath.requestedPath,
+ overwrite: options["overwrite"] ?? false,
+ ignoreIfExists: options["ignoreIfExists"] ?? false,
+ followedSymbolicLink: oldPath.followedSymbolicLink || newPath.followedSymbolicLink
+ });
+}
+
+// ../lsp-core/src/lsp/workspace-edit-parser.ts
+function failureResult(failures) {
+ const sorted = [...failures].sort((left, right) => left.changeIndex - right.changeIndex);
+ const first = sorted[0];
+ return {
+ success: false,
+ filesModified: [],
+ totalEdits: 0,
+ errors: sorted.map((failure) => `change ${failure.changeIndex}: ${failure.message}`),
+ ...first ? { failedChange: first.changeIndex } : {}
+ };
+}
+function parseWorkspaceEdit(edit, workspaceRoot) {
+ if (!isRecord2(edit))
+ return { operations: [], failures: [{ changeIndex: 0, message: "No edit provided" }] };
+ if (edit["changeAnnotations"] !== undefined) {
+ return { operations: [], failures: [{ changeIndex: 0, message: "change annotations are unsupported" }] };
+ }
+ const hasChanges = edit["changes"] !== undefined;
+ const hasDocumentChanges = edit["documentChanges"] !== undefined;
+ if (hasChanges && hasDocumentChanges) {
+ return {
+ operations: [],
+ failures: [{ changeIndex: 0, message: "changes and documentChanges cannot be combined" }]
+ };
+ }
+ const target = { operations: [], failures: [] };
+ if (hasChanges)
+ return parseChanges(edit["changes"], workspaceRoot, target);
+ return parseDocumentChanges(edit["documentChanges"], workspaceRoot, target);
+}
+function parseChanges(value, workspaceRoot, target) {
+ if (!isRecord2(value))
+ return { ...target, failures: [{ changeIndex: 0, message: "changes must be an object" }] };
+ const entries = Object.entries(value).sort(([left], [right]) => left.localeCompare(right));
+ for (const [changeIndex, [uri, rawEdits]] of entries.entries()) {
+ const resolvedPath = uriToCanonicalWorkspacePath(uri, workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ continue;
+ }
+ try {
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(rawEdits, changeIndex),
+ version: null
+ });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChanges(value, workspaceRoot, target) {
+ if (value === undefined)
+ return target;
+ if (!Array.isArray(value)) {
+ return { ...target, failures: [{ changeIndex: 0, message: "documentChanges must be an array" }] };
+ }
+ for (const [changeIndex, change] of value.entries()) {
+ try {
+ parseDocumentChange({ change, changeIndex, workspaceRoot, target });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChange(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (!isRecord2(change))
+ throw new WorkspaceEditValidationError(changeIndex, "document change must be an object");
+ if ("annotationId" in change) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated resource operations are unsupported");
+ }
+ if (typeof change["kind"] === "string") {
+ parseResourceChange({ change, changeIndex, workspaceRoot, target });
+ return;
+ }
+ const identifier = change["textDocument"];
+ if (!isRecord2(identifier) || typeof identifier["uri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "textDocument.uri is required");
+ }
+ const version = identifier["version"];
+ if (version !== null && (!Number.isInteger(version) || typeof version !== "number" || version < 0)) {
+ throw new WorkspaceEditValidationError(changeIndex, "document version must be null or a non-negative integer");
+ }
+ const resolvedPath = uriToCanonicalWorkspacePath(identifier["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(change["edits"], changeIndex),
+ version
+ });
+}
+
+// ../lsp-core/src/lsp/workspace-edit-simulation.ts
+import { dirname as dirname2, relative as relative3, resolve as resolve3 } from "node:path";
+
+// ../lsp-core/src/lsp/workspace-edit-text.ts
+function comparePosition(left, right) {
+ return left.line === right.line ? left.character - right.character : left.line - right.line;
+}
+function positionsEqual(left, right) {
+ return left.line === right.line && left.character === right.character;
+}
+function rangesEqual(left, right) {
+ return positionsEqual(left.start, right.start) && positionsEqual(left.end, right.end);
+}
+function isEmptyRange(range) {
+ return positionsEqual(range.start, range.end);
+}
+function formatRange(range) {
+ return `${range.start.line + 1}:${range.start.character + 1}-${range.end.line + 1}:${range.end.character + 1}`;
+}
+function validatePosition(position, label, context) {
+ const { lines, changeIndex } = context;
+ if (!Number.isInteger(position.line) || !Number.isInteger(position.character)) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position must use integer line and character`);
+ }
+ if (position.line < 0 || position.character < 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position cannot be negative`);
+ }
+ const line = lines[position.line];
+ if (line === undefined) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} line ${position.line} is outside the document`);
+ }
+ if (position.character > line.length) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} character ${position.character} is outside line ${position.line}`);
+ }
+}
+function validateRange(range, lines, changeIndex) {
+ const context = { lines, changeIndex };
+ validatePosition(range.start, "start", context);
+ validatePosition(range.end, "end", context);
+ if (comparePosition(range.start, range.end) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `range ${formatRange(range)} ends before it starts`);
+ }
+}
+function sortAndDeduplicate(edits) {
+ const sorted = edits.map((edit, index) => ({ edit, index })).sort((left, right) => {
+ const positionOrder = comparePosition(right.edit.range.start, left.edit.range.start);
+ return positionOrder === 0 ? right.index - left.index : positionOrder;
+ });
+ const unique = [];
+ for (const entry of sorted) {
+ const previous = unique.at(-1);
+ if (previous !== undefined && !isEmptyRange(entry.edit.range) && rangesEqual(previous.range, entry.edit.range) && previous.newText === entry.edit.newText) {
+ continue;
+ }
+ unique.push(entry.edit);
+ }
+ return unique;
+}
+function validateNoOverlap(edits, changeIndex) {
+ for (let index = 0;index < edits.length - 1; index += 1) {
+ const later = edits[index];
+ const earlier = edits[index + 1];
+ if (later === undefined || earlier === undefined)
+ continue;
+ if (comparePosition(earlier.range.end, later.range.start) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `overlapping edits ${formatRange(earlier.range)} and ${formatRange(later.range)}`);
+ }
+ }
+}
+function applyNormalizedTextEdits(content, edits) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ const { start, end } = edit.range;
+ const startLine = lines[start.line];
+ const endLine = lines[end.line];
+ if (startLine === undefined || endLine === undefined)
+ continue;
+ const replacement = startLine.slice(0, start.character) + edit.newText + endLine.slice(end.character);
+ lines.splice(start.line, end.line - start.line + 1, ...replacement.split(`
+`));
+ }
+ return lines.join(`
+`);
+}
+function normalizeTextEdits(content, edits, changeIndex) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ validateRange(edit.range, lines, changeIndex);
+ }
+ const normalized = sortAndDeduplicate(edits);
+ validateNoOverlap(normalized, changeIndex);
+ return { edits: normalized, text: applyNormalizedTextEdits(content, normalized) };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-simulation.ts
+function isSameOrDescendant2(candidate, parent) {
+ const relativePath = relative3(parent, candidate);
+ return relativePath === "" || !relativePath.startsWith("..") && relativePath !== "..";
+}
+function removeVirtualSubtree(virtual, path) {
+ for (const candidate of [...virtual.keys()]) {
+ if (isSameOrDescendant2(candidate, path))
+ virtual.delete(candidate);
+ }
+ virtual.set(path, { kind: "missing" });
+}
+function moveVirtualSubtree(virtual, oldPath, newPath) {
+ const moved = [...virtual.entries()].filter(([candidate]) => isSameOrDescendant2(candidate, oldPath));
+ removeVirtualSubtree(virtual, oldPath);
+ removeVirtualSubtree(virtual, newPath);
+ for (const [candidate, entry] of moved) {
+ const suffix = relative3(oldPath, candidate);
+ virtual.set(suffix === "" ? newPath : resolve3(newPath, suffix), entry);
+ }
+}
+function virtualDirectoryHasChildren(virtual, path) {
+ for (const [candidate, entry] of virtual) {
+ if (candidate !== path && entry.kind !== "missing" && isSameOrDescendant2(candidate, path))
+ return true;
+ }
+ return false;
+}
+function requireVirtualParent(virtual, path, changeIndex) {
+ if (virtual.get(dirname2(path))?.kind !== "directory") {
+ throw new WorkspaceEditValidationError(changeIndex, `parent directory does not exist for ${path}`);
+ }
+}
+function simulateOperations(parsed, snapshots) {
+ const virtual = new Map(snapshots);
+ const planned = [];
+ const failures = [];
+ for (const operation of parsed) {
+ try {
+ planned.push(simulateOperation(operation, virtual));
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ failures.push({ changeIndex: operation.changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return { operations: planned, failures };
+}
+function simulateOperation(operation, virtual) {
+ switch (operation.kind) {
+ case "text":
+ return simulateText(operation, virtual);
+ case "create":
+ return simulateCreate(operation, virtual);
+ case "rename":
+ return simulateRename(operation, virtual);
+ case "delete":
+ return simulateDelete(operation, virtual);
+ }
+}
+function rejectSymbolicLink(operation) {
+ if (operation.followedSymbolicLink) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "resource operations through symbolic links are unsupported");
+ }
+}
+function simulateText(operation, virtual) {
+ const entry = virtual.get(operation.path);
+ if (entry?.kind !== "file")
+ throw new WorkspaceEditValidationError(operation.changeIndex, `${operation.path} is not a file`);
+ const normalized = normalizeTextEdits(entry.content, operation.edits, operation.changeIndex);
+ virtual.set(operation.path, { kind: "file", content: normalized.text });
+ return {
+ kind: "text",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ beforeText: entry.content,
+ afterText: normalized.text,
+ editCount: normalized.edits.length,
+ documentVersion: operation.version
+ };
+}
+function simulateCreate(operation, virtual) {
+ rejectSymbolicLink(operation);
+ requireVirtualParent(virtual, operation.path, operation.changeIndex);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind !== "missing") {
+ if (operation.overwrite && target.kind === "file") {
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: true };
+ }
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `create target already exists: ${operation.path}`);
+ }
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: false };
+}
+function simulateRename(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const source = virtual.get(operation.oldPath) ?? { kind: "missing" };
+ if (source.kind === "missing") {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename source does not exist: ${operation.oldPath}`);
+ }
+ if (operation.oldPath === operation.newPath)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ if (isSameOrDescendant2(operation.newPath, operation.oldPath)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "cannot rename a path into its own subtree");
+ }
+ requireVirtualParent(virtual, operation.newPath, operation.changeIndex);
+ const destination = virtual.get(operation.newPath) ?? { kind: "missing" };
+ if (destination.kind !== "missing" && !operation.overwrite) {
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename target already exists: ${operation.newPath}`);
+ }
+ moveVirtualSubtree(virtual, operation.oldPath, operation.newPath);
+ return {
+ kind: "rename",
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: source.kind,
+ replaceDestination: destination.kind !== "missing"
+ };
+}
+function simulateDelete(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind === "missing") {
+ if (operation.ignoreIfNotExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `delete target does not exist: ${operation.path}`);
+ }
+ if (target.kind === "directory" && !operation.recursive && virtualDirectoryHasChildren(virtual, operation.path)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `directory is not empty: ${operation.path}`);
+ }
+ removeVirtualSubtree(virtual, operation.path);
+ return {
+ kind: "delete",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ targetKind: target.kind,
+ recursive: operation.recursive
+ };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-snapshot.ts
+import { existsSync as existsSync4, lstatSync as lstatSync3, readdirSync as readdirSync2 } from "node:fs";
+import { dirname as dirname3, resolve as resolve4 } from "node:path";
+class WorkspaceSnapshotBuilder {
+ workspaceRoot;
+ snapshots = new Map;
+ constructor(workspaceRoot) {
+ this.workspaceRoot = workspaceRoot;
+ }
+ build(operations) {
+ this.add(this.workspaceRoot, false);
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, true);
+ this.add(operation.newPath, true);
+ break;
+ case "delete":
+ this.add(operation.path, true);
+ break;
+ case "text":
+ case "create":
+ this.add(operation.path, false);
+ break;
+ }
+ }
+ return this.snapshots;
+ }
+ add(path, includeChildren) {
+ let candidate = path;
+ while (true) {
+ const existing = this.snapshots.get(candidate);
+ if (existing === undefined || includeChildren && existing.kind === "directory" && existing.children === undefined) {
+ this.snapshots.set(candidate, snapshotPath(candidate, includeChildren && candidate === path));
+ }
+ if (candidate === this.workspaceRoot)
+ break;
+ candidate = dirname3(candidate);
+ }
+ if (!includeChildren || !existsSync4(path) || !lstatSync3(path).isDirectory())
+ return;
+ for (const child of readdirSync2(path))
+ this.add(resolve4(path, child), true);
+ }
+}
+function snapshotOperations(operations, workspaceRoot) {
+ return new WorkspaceSnapshotBuilder(workspaceRoot).build(operations);
+}
+
+// ../lsp-core/src/lsp/workspace-edit-plan.ts
+class PlanPathIndex {
+ firstChangeByPath = new Map;
+ reportedPathByCanonical = new Map;
+ build(operations) {
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, operation.reportedOldPath, operation.changeIndex);
+ this.add(operation.newPath, operation.reportedNewPath, operation.changeIndex);
+ break;
+ case "text":
+ case "create":
+ case "delete":
+ this.add(operation.path, operation.reportedPath, operation.changeIndex);
+ break;
+ }
+ }
+ }
+ add(path, reportedPath2, changeIndex) {
+ if (!this.firstChangeByPath.has(path))
+ this.firstChangeByPath.set(path, changeIndex);
+ if (!this.reportedPathByCanonical.has(path))
+ this.reportedPathByCanonical.set(path, reportedPath2);
+ }
+}
+function fingerprintWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ return { success: true, fingerprint: canonicalFingerprint(parsed.operations) };
+}
+function planWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ let snapshots;
+ try {
+ snapshots = snapshotOperations(parsed.operations, root.path);
+ } catch (error) {
+ return {
+ success: false,
+ result: failureResult([{ changeIndex: 0, message: error instanceof Error ? error.message : String(error) }])
+ };
+ }
+ const simulated = simulateOperations(parsed.operations, snapshots);
+ if (simulated.failures.length > 0)
+ return { success: false, result: failureResult(simulated.failures) };
+ const paths = new PlanPathIndex;
+ paths.build(parsed.operations);
+ const plan = {
+ workspaceRoot: root.path,
+ operations: simulated.operations,
+ snapshots,
+ firstChangeByPath: paths.firstChangeByPath,
+ reportedPathByCanonical: paths.reportedPathByCanonical,
+ fingerprint: canonicalFingerprint(parsed.operations)
+ };
+ return { success: true, plan };
+}
+
+// ../lsp-core/src/lsp/workspace-mutation-controller.ts
+function failure(message, failedChange, base) {
+ return {
+ success: false,
+ filesModified: base?.filesModified ?? [],
+ totalEdits: base?.totalEdits ?? 0,
+ errors: [message],
+ ...failedChange === undefined ? {} : { failedChange },
+ ...base?.lateAbort ? { lateAbort: true } : {}
+ };
+}
+function responseFor(result) {
+ if (result.success)
+ return { applied: true };
+ return {
+ applied: false,
+ failureReason: result.errors[0] ?? "workspace edit failed",
+ ...result.failedChange === undefined ? {} : { failedChange: result.failedChange }
+ };
+}
+function isRecord3(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+class WorkspaceMutationController {
+ workspaceRoot;
+ documents;
+ activeLease = null;
+ nextLeaseId = 1;
+ io;
+ constructor(workspaceRoot, documents) {
+ this.workspaceRoot = workspaceRoot;
+ this.documents = documents;
+ }
+ setIo(io) {
+ this.io = io;
+ }
+ acquire(signal) {
+ if (this.activeLease)
+ return { success: false, result: failure("workspace mutation is already in progress") };
+ if (signal?.aborted)
+ return { success: false, result: failure("cancelled before mutating request") };
+ const lease = {
+ id: this.nextLeaseId,
+ phase: "idle",
+ ...signal === undefined ? {} : { signal }
+ };
+ this.nextLeaseId += 1;
+ this.activeLease = lease;
+ return { success: true, lease };
+ }
+ release(lease) {
+ if (this.activeLease?.id !== lease.id)
+ return;
+ this.activeLease.phase = "sealed";
+ this.activeLease = null;
+ }
+ isBeforeCommit(lease) {
+ return this.activeLease?.id === lease.id && this.activeLease.phase === "idle";
+ }
+ async handleApplyEdit(params) {
+ const lease = this.activeLease;
+ if (!lease)
+ return { applied: false, failureReason: "workspace/applyEdit requires an active workspace mutation" };
+ if (lease.phase !== "idle") {
+ return {
+ applied: false,
+ failureReason: workspaceApplyEditConcurrentFailureReason(lease.phase === "applying" ? "applying" : "settled")
+ };
+ }
+ lease.phase = "applying";
+ lease.applyCompletion = new Promise((resolve5) => {
+ lease.resolveApply = resolve5;
+ });
+ const edit = isRecord3(params) ? params["edit"] : undefined;
+ const record = edit === undefined ? { fingerprint: null, result: failure("workspace/applyEdit params.edit is required", 0) } : await this.applyEdit(edit, lease);
+ lease.serverApply = record;
+ lease.phase = "settled";
+ lease.resolveApply?.();
+ return responseFor(record.result);
+ }
+ async reconcileRename(leaseToken, edit) {
+ const lease = this.requireActiveLease(leaseToken);
+ if (!lease)
+ return { edit, apply: failure("workspace mutation lease ended before rename reconciliation") };
+ if (lease.phase === "applying")
+ await lease.applyCompletion;
+ if (lease.serverApply)
+ return this.reconcileServerApply(lease.serverApply, edit);
+ lease.phase = "sealed";
+ if (!edit)
+ return { edit, apply: failure("No edit provided") };
+ const applied = await this.applyEdit(edit, lease);
+ return { edit, apply: applied.result };
+ }
+ reconcileServerApply(record, edit) {
+ if (!edit)
+ return { edit, apply: record.result };
+ const fingerprint = fingerprintWorkspaceEdit(edit, this.workspaceRoot);
+ if (fingerprint.success && record.fingerprint !== null && fingerprint.fingerprint === record.fingerprint) {
+ return { edit, apply: record.result };
+ }
+ return {
+ edit,
+ apply: failure("rename result conflicts with server-applied workspace edit", 0, record.result)
+ };
+ }
+ async applyEdit(edit, lease) {
+ const planned = planWorkspaceEdit(edit, this.workspaceRoot);
+ if (!planned.success)
+ return { fingerprint: null, result: planned.result };
+ const versionFailure = this.documents.validateVersions(planned.plan.operations);
+ if (versionFailure) {
+ return {
+ fingerprint: planned.plan.fingerprint,
+ result: failure(versionFailure.message, versionFailure.changeIndex)
+ };
+ }
+ const commit = commitWorkspaceEditPlan(planned.plan, {
+ ...lease.signal === undefined ? {} : { signal: lease.signal },
+ ...this.io === undefined ? {} : { io: this.io }
+ });
+ let result = commit.result;
+ if (commit.delta.operations.length > 0) {
+ try {
+ await this.documents.synchronize(commit.delta);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ result = failure(`document synchronization failed after filesystem commit: ${message}`, undefined, result);
+ }
+ }
+ if (lease.signal?.aborted && !result.lateAbort)
+ result = { ...result, lateAbort: true };
+ return { fingerprint: planned.plan.fingerprint, result };
+ }
+ requireActiveLease(lease) {
+ return this.activeLease?.id === lease.id ? this.activeLease : null;
+ }
+}
+
// ../lsp-core/src/lsp/client.ts
-var POST_OPEN_DELAY_MS = 1000;
-var POST_DIAGNOSTICS_WAIT_MS = 500;
+var DIAGNOSTICS_FRESHNESS_TIMEOUT_MS = 3000;
+var VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
class LspClient extends LspClientConnection {
- openedFiles = new Set;
- documentVersions = new Map;
- lastSyncedText = new Map;
diagnosticPullErrors = [];
+ documents;
+ workspaceMutations;
+ diagnosticsFreshnessTimeoutMs;
+ constructor(root, server, options = {}) {
+ super(root, server, options);
+ this.diagnosticsFreshnessTimeoutMs = options.diagnosticsFreshnessTimeoutMs ?? DIAGNOSTICS_FRESHNESS_TIMEOUT_MS;
+ this.documents = new WorkspaceDocumentState((method, params) => this.sendNotification(method, params), (uri) => this.diagnosticsStore.delete(uri), {
+ versionlessPublishQuiescenceMs: options.versionlessPublishQuiescenceMs ?? VERSIONLESS_PUBLISH_QUIESCENCE_MS
+ });
+ this.workspaceMutations = new WorkspaceMutationController(root, this.documents);
+ this.setWorkspaceApplyEditHandler((params) => this.workspaceMutations.handleApplyEdit(params));
+ }
getDiagnosticPullErrors() {
return this.diagnosticPullErrors;
}
async openFile(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- const uri = pathToFileURL2(absPath).href;
- const text = readFileSync(absPath, "utf-8");
- if (!this.openedFiles.has(absPath)) {
- const ext = effectiveExtension(absPath);
- const languageId = getLanguageId(ext);
- const version = 1;
- await this.sendNotification("textDocument/didOpen", {
- textDocument: {
- uri,
- languageId,
- version,
- text
- }
- });
- this.openedFiles.add(absPath);
- this.documentVersions.set(uri, version);
- this.lastSyncedText.set(uri, text);
- await new Promise((r) => setTimeout(r, POST_OPEN_DELAY_MS));
- return;
- }
- const prevText = this.lastSyncedText.get(uri);
- if (prevText === text) {
- return;
- }
- const nextVersion = (this.documentVersions.get(uri) ?? 1) + 1;
- this.documentVersions.set(uri, nextVersion);
- this.lastSyncedText.set(uri, text);
- await this.sendNotification("textDocument/didChange", {
- textDocument: { uri, version: nextVersion },
- contentChanges: [{ text }]
- });
- await this.sendNotification("textDocument/didSave", {
- textDocument: { uri },
- text
- });
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.documents.openFile(absPath);
+ }
+ getOpenDocumentVersion(filePath) {
+ return this.documents.getVersion(this.resolveWorkspacePath(filePath));
+ }
+ getStoredDiagnostics(uri) {
+ return [...this.documents.getStoredDiagnostics(uri)];
}
- async definition(filePath, line, character) {
- const absPath = resolve(contextCwd(), filePath);
+ setWorkspaceEditIo(io) {
+ this.workspaceMutations.setIo(io);
+ }
+ handlePublishDiagnostics(params) {
+ super.handlePublishDiagnostics(params);
+ this.documents.recordPublishedDiagnostics(params);
+ }
+ async definition(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/definition", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character }
- });
+ }, options);
}
- async references(filePath, line, character, includeDeclaration = true) {
- const absPath = resolve(contextCwd(), filePath);
+ async references(filePath, line, character, includeDeclaration = true, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/references", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character },
context: { includeDeclaration }
- });
+ }, options);
}
- async documentSymbols(filePath) {
- const absPath = resolve(contextCwd(), filePath);
+ async documentSymbols(filePath, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/documentSymbol", {
- textDocument: { uri: pathToFileURL2(absPath).href }
- });
+ textDocument: { uri: pathToFileURL3(absPath).href }
+ }, options);
}
- async workspaceSymbols(query) {
- return this.sendRequest("workspace/symbol", { query });
+ async workspaceSymbols(query, signal) {
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("workspace/symbol", { query }, options);
}
isUnsupportedDiagnosticPullError(error) {
if (!(error instanceof Error))
@@ -1077,43 +2539,174 @@ class LspClient extends LspClientConnection {
return true;
return /unsupported|not supported|method not found|unknown request/i.test(error.message);
}
- async diagnostics(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- const uri = pathToFileURL2(absPath).href;
- await this.openFile(absPath);
- await new Promise((r) => setTimeout(r, POST_DIAGNOSTICS_WAIT_MS));
- try {
- const result = await this.sendRequest("textDocument/diagnostic", {
- textDocument: { uri }
- });
- if (result.items) {
- return { items: result.items };
+ freshnessTimeout(absPath) {
+ return {
+ items: [],
+ transientError: {
+ kind: "freshness_timeout",
+ message: `Timed out waiting for fresh diagnostics for ${absPath} within ${this.diagnosticsFreshnessTimeoutMs}ms.`
}
- } catch (error) {
- if (!this.isUnsupportedDiagnosticPullError(error)) {
- this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ };
+ }
+ parseDiagnosticPullReport(value) {
+ if (value.kind === "unchanged") {
+ return {
+ type: "unchanged",
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ return {
+ type: "full",
+ diagnostics: value.items ?? [],
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ async diagnostics(filePath, signal) {
+ signal?.throwIfAborted();
+ const absPath = this.resolveWorkspacePath(filePath);
+ const uri = pathToFileURL3(absPath).href;
+ await this.openFile(absPath);
+ const deadlineAt = Date.now() + this.diagnosticsFreshnessTimeoutMs;
+ for (;; ) {
+ signal?.throwIfAborted();
+ const snapshot = this.documents.captureDiagnosticSnapshot(absPath);
+ if (!snapshot)
+ return this.freshnessTimeout(absPath);
+ const push = this.documents.resolvePushDiagnostics(snapshot);
+ if (push.status === "ready")
+ return { items: [...push.diagnostics] };
+ let pushFallbackOnly = !this.isDiagnosticPullSupported();
+ if (!pushFallbackOnly) {
+ const cached = this.documents.getPullCache(snapshot);
+ try {
+ const remainingMs2 = deadlineAt - Date.now();
+ if (remainingMs2 <= 0)
+ return this.freshnessTimeout(absPath);
+ const result = await this.sendRequest("textDocument/diagnostic", {
+ textDocument: { uri },
+ ...cached?.resultId === undefined ? {} : { previousResultId: cached.resultId }
+ }, { timeoutMs: remainingMs2, ...signal === undefined ? {} : { signal } });
+ if (!this.documents.isCurrentSnapshot(snapshot))
+ continue;
+ const report = this.parseDiagnosticPullReport(result);
+ if (report.type === "full") {
+ this.documents.recordPullDiagnostics(snapshot, {
+ kind: "full",
+ diagnostics: report.diagnostics,
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ });
+ return { items: [...report.diagnostics] };
+ }
+ if (cached !== null && cached.documentVersion === snapshot.version && cached.resultId === report.resultId) {
+ return { items: [...cached.diagnostics] };
+ }
+ } catch (error) {
+ if (this.isUnsupportedDiagnosticPullError(error)) {
+ this.setDiagnosticPullSupported(false);
+ pushFallbackOnly = true;
+ } else if (error instanceof LspRequestTimeoutError) {
+ pushFallbackOnly = true;
+ } else {
+ this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ throw error;
+ }
+ }
}
+ if (!pushFallbackOnly)
+ continue;
+ const remainingMs = deadlineAt - Date.now();
+ if (remainingMs <= 0)
+ return this.freshnessTimeout(absPath);
+ const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;
+ await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);
}
- return { items: this.getStoredDiagnostics(uri) };
}
- async prepareRename(filePath, line, character) {
- const absPath = resolve(contextCwd(), filePath);
+ async prepareRename(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/prepareRename", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character }
- });
+ }, options);
}
- async rename(filePath, line, character, newName) {
- const absPath = resolve(contextCwd(), filePath);
+ async rename(filePath, line, character, newName, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
- return this.sendRequest("textDocument/rename", {
- textDocument: { uri: pathToFileURL2(absPath).href },
- position: { line: line - 1, character },
- newName
- });
+ const acquired = this.workspaceMutations.acquire(signal);
+ if (!acquired.success)
+ return { edit: null, apply: acquired.result };
+ const preCommitSignal = createPreCommitAbortSignal(signal, () => this.workspaceMutations.isBeforeCommit(acquired.lease));
+ try {
+ const renameParams = {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character },
+ newName
+ };
+ const edit = preCommitSignal === undefined ? await this.sendRequest("textDocument/rename", renameParams) : await this.sendRequest("textDocument/rename", renameParams, {
+ signal: preCommitSignal.signal
+ });
+ return await this.workspaceMutations.reconcileRename(acquired.lease, edit);
+ } finally {
+ preCommitSignal?.dispose();
+ this.workspaceMutations.release(acquired.lease);
+ }
+ }
+ resolveWorkspacePath(filePath) {
+ return resolve5(this.root, filePath);
}
}
+function waitForDiagnosticsActivity(wait, signal) {
+ if (!signal)
+ return wait;
+ if (signal.aborted)
+ return Promise.reject(abortError2(signal));
+ return new Promise((resolve6, reject) => {
+ const onAbort = () => {
+ signal.removeEventListener("abort", onAbort);
+ reject(abortError2(signal));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ wait.then(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve6();
+ }, (error) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(error);
+ });
+ });
+}
+function createPreCommitAbortSignal(source, isBeforeCommit) {
+ if (!source)
+ return;
+ const controller = new AbortController;
+ const onAbort = () => {
+ if (isBeforeCommit() && !controller.signal.aborted)
+ controller.abort(preCommitAbortReason(source));
+ };
+ if (source.aborted)
+ onAbort();
+ else
+ source.addEventListener("abort", onAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => source.removeEventListener("abort", onAbort)
+ };
+}
+function preCommitAbortReason(source) {
+ const reason = source.reason;
+ if (reason instanceof Error && reason.name !== "AbortError")
+ return reason;
+ return new Error("LSP request cancelled before workspace edit commit");
+}
+function abortError2(signal) {
+ const reason = signal.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "operation cancelled");
+ error.name = "AbortError";
+ return error;
+}
// ../lsp-core/src/lsp/process-signal-cleanup.ts
function installProcessSignalCleanup(cleanup) {
@@ -1144,7 +2737,7 @@ async function stopClientBestEffort(client) {
function awaitWithSignal(promise, signal) {
if (!signal)
return promise;
- return new Promise((resolve2, reject) => {
+ return new Promise((resolve6, reject) => {
let settled = false;
const onAbort = () => {
if (settled)
@@ -1162,7 +2755,7 @@ function awaitWithSignal(promise, signal) {
return;
settled = true;
signal.removeEventListener("abort", onAbort);
- resolve2(value);
+ resolve6(value);
}, (err) => {
if (settled)
return;
@@ -1428,9 +3021,6 @@ function errorResponse(id, code, message, data) {
function jsonRpcId(value) {
return typeof value === "string" || typeof value === "number" || value === null ? value : null;
}
-function messageFromError(error) {
- return error instanceof Error ? error.message : String(error);
-}
// ../mcp-stdio-core/src/transport.ts
var HEADER_SEPARATOR2 = Buffer.from(`\r
\r
@@ -1617,29 +3207,201 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {
closed: () => isClosed
};
}
-// ../lsp-core/src/tools/diagnostics.ts
-import { resolve as resolve4 } from "node:path";
-
// ../lsp-core/src/lsp/client-wrapper.ts
-import { existsSync as existsSync5, statSync as statSync2 } from "node:fs";
-import { dirname as dirname2, join as join5, resolve as resolve2 } from "node:path";
+import { existsSync as existsSync9, statSync as statSync3 } from "node:fs";
+import { dirname as dirname6, join as join4, resolve as resolve7 } from "node:path";
-// ../lsp-core/src/lsp/server-install-state.ts
-import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
+// ../lsp-core/src/request-context.ts
+import { AsyncLocalStorage } from "node:async_hooks";
+import { existsSync as existsSync5, realpathSync as realpathSync3, statSync as statSync2 } from "node:fs";
import { homedir } from "node:os";
-import { dirname, isAbsolute, join as join2 } from "node:path";
+import { basename as basename2, delimiter as delimiter2, dirname as dirname4, isAbsolute as isAbsolute2, join as join2, relative as relative4, resolve as resolve6 } from "node:path";
+
+class LspRequestContextParseError extends Error {
+ code;
+ name = "LspRequestContextParseError";
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ }
+}
+
+class LspRequestContextUnavailableError extends Error {
+ name = "LspRequestContextUnavailableError";
+ constructor() {
+ super("LSP request context is required. Standalone MCP startup must install one with runWithRequestContext(createStandaloneMcpRequestContext()).");
+ }
+}
+var storage = new AsyncLocalStorage;
+var CONTEXT_FIELDS = new Set(["cwd", "projectConfigPaths", "userConfigPath", "installDecisionsPath", "capabilities"]);
+var CAPABILITY_FIELDS = new Set(["installDecisionTool"]);
+function runWithRequestContext(context, fn) {
+ return storage.run(context, fn);
+}
+function lspRequestContext() {
+ const context = storage.getStore();
+ if (!context)
+ throw new LspRequestContextUnavailableError;
+ return context;
+}
+function contextCwd() {
+ return lspRequestContext().cwd;
+}
+function contextEnv(key) {
+ const context = lspRequestContext();
+ if (key === "LSP_TOOLS_MCP_PROJECT_CONFIG")
+ return context.projectConfigPaths.join(delimiter2);
+ if (key === "LSP_TOOLS_MCP_USER_CONFIG")
+ return context.userConfigPath;
+ if (key === "LSP_TOOLS_MCP_INSTALL_DECISIONS")
+ return context.installDecisionsPath;
+ return;
+}
+function createStandaloneMcpRequestContext(input = {}) {
+ const env = input.env ?? process.env;
+ const cwd = canonicalCwd(input.cwd ?? process.cwd());
+ const home = input.homeDir ?? homedir();
+ const projectConfigPaths = translateProjectConfigEnv(env["LSP_TOOLS_MCP_PROJECT_CONFIG"], cwd);
+ const userConfigPath = translateHomeConfigEnv(env["LSP_TOOLS_MCP_USER_CONFIG"], home, ".codex/lsp-client.json");
+ const installDecisionsPath = translateHomeConfigEnv(env["LSP_TOOLS_MCP_INSTALL_DECISIONS"], home, ".codex/lsp-install-decisions.json");
+ return parseLspRequestContext({
+ cwd,
+ projectConfigPaths,
+ userConfigPath,
+ installDecisionsPath,
+ capabilities: { installDecisionTool: true }
+ });
+}
+function parseLspRequestContext(value) {
+ if (!isRecord4(value)) {
+ throw new LspRequestContextParseError("invalid_context", "LSP request context must be an object.");
+ }
+ rejectUnknownFields(value, CONTEXT_FIELDS, "context");
+ const cwd = stringField(value, "cwd");
+ const projectConfigPaths = stringArrayField(value, "projectConfigPaths");
+ const userConfigPath = stringField(value, "userConfigPath");
+ const installDecisionsPath = stringField(value, "installDecisionsPath");
+ const capabilities = capabilitiesField(value["capabilities"]);
+ const canonical = canonicalCwd(cwd);
+ for (const path of projectConfigPaths) {
+ requireAbsolutePath(path, "projectConfigPaths");
+ const projectPath = canonicalizeExistingOrNearestAncestor(path);
+ if (!isPathInside(canonical, projectPath)) {
+ throw new LspRequestContextParseError("project_config_outside_cwd", `Project LSP config path must be inside cwd: ${path}`);
+ }
+ }
+ requireAbsolutePath(userConfigPath, "userConfigPath");
+ requireAbsolutePath(installDecisionsPath, "installDecisionsPath");
+ return {
+ cwd: canonical,
+ projectConfigPaths: projectConfigPaths.map((path) => canonicalizeExistingOrNearestAncestor(path)),
+ userConfigPath,
+ installDecisionsPath,
+ capabilities
+ };
+}
+function translateProjectConfigEnv(value, cwd) {
+ if (value === undefined || value.length === 0)
+ return [join2(cwd, ".codex", "lsp-client.json")];
+ return value.split(delimiter2).filter((entry) => entry.length > 0).map((entry) => isAbsolute2(entry) ? entry : join2(cwd, entry));
+}
+function translateHomeConfigEnv(value, home, fallback) {
+ if (value === undefined || value.length === 0)
+ return join2(home, fallback);
+ return isAbsolute2(value) ? value : join2(home, value);
+}
+function canonicalCwd(cwd) {
+ const resolved = resolve6(cwd);
+ if (!existsSync5(resolved) || !statSync2(resolved).isDirectory()) {
+ throw new LspRequestContextParseError("invalid_cwd", `LSP request cwd must be an existing directory: ${cwd}`);
+ }
+ return realpathSync3(resolved);
+}
+function canonicalizeExistingOrNearestAncestor(path) {
+ let current = resolve6(path);
+ const suffix = [];
+ while (true) {
+ try {
+ const existing = realpathSync3(current);
+ return suffix.length === 0 ? existing : join2(existing, ...suffix);
+ } catch (error) {
+ if (!isMissingPathError(error))
+ throw error;
+ const parent = dirname4(current);
+ if (parent === current)
+ throw error;
+ suffix.unshift(basename2(current));
+ current = parent;
+ }
+ }
+}
+function capabilitiesField(value) {
+ if (!isRecord4(value)) {
+ throw new LspRequestContextParseError("invalid_capabilities", "LSP request capabilities must be an object.");
+ }
+ rejectUnknownFields(value, CAPABILITY_FIELDS, "capabilities");
+ const installDecisionTool = value["installDecisionTool"];
+ if (typeof installDecisionTool !== "boolean") {
+ throw new LspRequestContextParseError("invalid_install_decision_capability", "LSP request capabilities.installDecisionTool must be a boolean.");
+ }
+ return { installDecisionTool };
+}
+function stringField(value, field) {
+ const fieldValue = value[field];
+ if (typeof fieldValue !== "string" || fieldValue.length === 0) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string.`);
+ }
+ return fieldValue;
+}
+function stringArrayField(value, field) {
+ const fieldValue = value[field];
+ if (!Array.isArray(fieldValue) || !fieldValue.every((item) => typeof item === "string" && item.length > 0)) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string array.`);
+ }
+ return fieldValue;
+}
+function requireAbsolutePath(path, field) {
+ if (!isAbsolute2(path)) {
+ throw new LspRequestContextParseError("relative_path", `LSP request context.${field} must be absolute: ${path}`);
+ }
+}
+function isPathInside(parent, child) {
+ const childPath = resolve6(child);
+ const relativePath = relative4(parent, childPath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute2(relativePath);
+}
+function isMissingPathError(error) {
+ const code = errorCode(error);
+ return code === "ENOENT" || code === "ENOTDIR";
+}
+function rejectUnknownFields(value, allowed, scope) {
+ const unknown = Object.keys(value).filter((key) => !allowed.has(key));
+ if (unknown.length > 0) {
+ throw new LspRequestContextParseError("unknown_field", `Unknown LSP request ${scope} field: ${unknown.join(", ")}`);
+ }
+}
+function isRecord4(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function errorCode(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
+}
+
+// ../lsp-core/src/lsp/server-install-state.ts
+import { existsSync as existsSync6, mkdirSync, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
+import { dirname as dirname5 } from "node:path";
function getInstallDecisionsPath() {
- const override = contextEnv("LSP_TOOLS_MCP_INSTALL_DECISIONS");
- if (!override)
- return join2(homedir(), ".codex", "lsp-install-decisions.json");
- return isAbsolute(override) ? override : join2(homedir(), override);
+ return lspRequestContext().installDecisionsPath;
}
function loadInstallDecisions() {
const path = getInstallDecisionsPath();
- if (!existsSync2(path))
+ if (!existsSync6(path))
return {};
try {
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
+ const parsed = JSON.parse(readFileSync3(path, "utf8"));
return isInstallDecisions(parsed) ? parsed : {};
} catch {
return {};
@@ -1658,28 +3420,26 @@ function isInstallDecision(value) {
}
function writeInstallDecisions(decisions) {
const path = getInstallDecisionsPath();
- mkdirSync(dirname(path), { recursive: true });
+ mkdirSync(dirname5(path), { recursive: true });
const tmpPath = `${path}.tmp`;
- writeFileSync(tmpPath, `${JSON.stringify(decisions, null, 2)}
+ writeFileSync2(tmpPath, `${JSON.stringify(decisions, null, 2)}
`, "utf8");
- renameSync(tmpPath, path);
+ renameSync2(tmpPath, path);
}
function isInstallDecisions(value) {
- return isRecord2(value) && Object.values(value).every(isInstallDecisionRecord);
+ return isRecord5(value) && Object.values(value).every(isInstallDecisionRecord);
}
function isInstallDecisionRecord(value) {
- if (!isRecord2(value))
+ if (!isRecord5(value))
return false;
return isInstallDecision(value["decision"]) && typeof value["decidedAt"] === "string";
}
-function isRecord2(value) {
+function isRecord5(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
// ../lsp-core/src/lsp/config-loader.ts
-import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
-import { homedir as homedir2 } from "node:os";
-import { delimiter as delimiter2, isAbsolute as isAbsolute2, join as join3 } from "node:path";
+import { existsSync as existsSync7, readFileSync as readFileSync4 } from "node:fs";
// ../lsp-core/src/lsp/server-definitions.ts
var LSP_INSTALL_HINTS = {
@@ -1829,27 +3589,17 @@ var BUILTIN_SERVERS = {
};
// ../lsp-core/src/lsp/config-loader.ts
-function resolveProjectConfigPath(path) {
- return isAbsolute2(path) ? path : join3(contextCwd(), path);
-}
function getProjectConfigPaths() {
- const projectOverride = contextEnv("LSP_TOOLS_MCP_PROJECT_CONFIG");
- if (projectOverride) {
- return projectOverride.split(delimiter2).filter(Boolean).map(resolveProjectConfigPath);
- }
- return [join3(contextCwd(), ".codex", "lsp-client.json")];
+ return lspRequestContext().projectConfigPaths;
}
function getUserConfigPath() {
- const userOverride = contextEnv("LSP_TOOLS_MCP_USER_CONFIG");
- if (!userOverride)
- return join3(homedir2(), ".codex", "lsp-client.json");
- return isAbsolute2(userOverride) ? userOverride : join3(homedir2(), userOverride);
+ return lspRequestContext().userConfigPath;
}
function loadJsonFile(path) {
- if (!existsSync3(path))
+ if (!existsSync7(path))
return null;
try {
- const parsed = JSON.parse(readFileSync3(path, "utf-8"));
+ const parsed = JSON.parse(readFileSync4(path, "utf-8"));
return isConfigJson(parsed) ? parsed : null;
} catch {
return null;
@@ -1988,16 +3738,16 @@ function applyOptionalServerFields(server2, entry) {
}
}
function isConfigJson(value) {
- if (!isRecord3(value))
+ if (!isRecord6(value))
return false;
const lsp = value["lsp"];
- return lsp === undefined || isRecord3(lsp);
+ return lsp === undefined || isRecord6(lsp);
}
function parseLspEntry(value) {
return isLspEntry(value) ? value : null;
}
function isLspEntry(value) {
- if (!isRecord3(value))
+ if (!isRecord6(value))
return false;
const disabled = value["disabled"];
const command = value["command"];
@@ -2005,15 +3755,15 @@ function isLspEntry(value) {
const priority = value["priority"];
const env = value["env"];
const initialization = value["initialization"];
- return (disabled === undefined || typeof disabled === "boolean") && (command === undefined || isStringArray(command)) && (extensions === undefined || isStringArray(extensions)) && (priority === undefined || typeof priority === "number") && (env === undefined || isStringRecord(env)) && (initialization === undefined || isRecord3(initialization));
+ return (disabled === undefined || typeof disabled === "boolean") && (command === undefined || isStringArray(command)) && (extensions === undefined || isStringArray(extensions)) && (priority === undefined || typeof priority === "number") && (env === undefined || isStringRecord(env)) && (initialization === undefined || isRecord6(initialization));
}
function isStringArray(value) {
return Array.isArray(value) && value.every((item) => typeof item === "string");
}
function isStringRecord(value) {
- return isRecord3(value) && Object.values(value).every((item) => typeof item === "string");
+ return isRecord6(value) && Object.values(value).every((item) => typeof item === "string");
}
-function isRecord3(value) {
+function isRecord6(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function getDisabledServerIds() {
@@ -2034,8 +3784,8 @@ function getDisabledServerIds() {
}
// ../lsp-core/src/lsp/server-installation.ts
-import { existsSync as existsSync4 } from "node:fs";
-import { delimiter as delimiter3, join as join4 } from "node:path";
+import { existsSync as existsSync8 } from "node:fs";
+import { delimiter as delimiter3, join as join3 } from "node:path";
function isServerInstalled(command, _workingDirectory) {
if (command.length === 0)
return false;
@@ -2043,7 +3793,7 @@ function isServerInstalled(command, _workingDirectory) {
if (!cmd)
return false;
if (cmd.includes("/") || cmd.includes("\\")) {
- if (existsSync4(cmd))
+ if (existsSync8(cmd))
return true;
}
const isWindows = process.platform === "win32";
@@ -2064,7 +3814,7 @@ function isServerInstalled(command, _workingDirectory) {
const paths = pathEnv.split(delimiter3);
for (const p of paths) {
for (const suffix of exts) {
- if (existsSync4(join4(p, cmd + suffix))) {
+ if (existsSync8(join3(p, cmd + suffix))) {
return true;
}
}
@@ -2163,39 +3913,50 @@ function getAllServers() {
var WORKSPACE_MARKERS = [".git", "package.json", "pyproject.toml", "Cargo.toml", "go.mod", "pom.xml", "build.gradle"];
function isDirectoryPath(filePath) {
try {
- return statSync2(filePath).isDirectory();
+ return statSync3(filePath).isDirectory();
} catch {
return false;
}
}
function findWorkspaceRoot(filePath) {
- const abs = resolve2(contextCwd(), filePath);
+ const abs = resolvePathInsideContext(filePath);
let dir = abs;
if (!isDirectoryPath(dir)) {
- dir = dirname2(dir);
+ dir = dirname6(dir);
}
let prevDir = "";
while (dir !== prevDir) {
for (const marker of WORKSPACE_MARKERS) {
- if (existsSync5(join5(dir, marker))) {
+ if (existsSync9(join4(dir, marker))) {
return dir;
}
}
prevDir = dir;
- dir = dirname2(dir);
+ dir = dirname6(dir);
+ }
+ return dirname6(abs);
+}
+function resolvePathInsideContext(filePath) {
+ const cwd = contextCwd();
+ const abs = resolve7(cwd, filePath);
+ const canonical = canonicalizeExistingOrNearestAncestor(abs);
+ if (!isPathInside(cwd, canonical)) {
+ throw new LspInvalidPathError(`LSP file path must be inside request cwd: ${filePath}`);
}
- return dirname2(abs);
+ return canonical;
}
function formatServerLookupError(result) {
if (result.status === "not_installed") {
return formatNotInstalled(result);
}
+ const context = lspRequestContext();
+ const firstProjectConfigPath = context.projectConfigPaths[0] ?? "<project lsp config>";
return [
`No LSP server configured for extension: ${result.extension}`,
"",
`Available servers: ${result.availableServers.slice(0, 10).join(", ")}${result.availableServers.length > 10 ? "..." : ""}`,
"",
- "Configure a custom server in '.codex/lsp-client.json':",
+ `Configure a custom server in '${firstProjectConfigPath}' or '${context.userConfigPath}':`,
" {",
' "lsp": {',
' "my-server": {',
@@ -2211,6 +3972,7 @@ function formatNotInstalled(result) {
const { server: server2, installHint } = result;
const extensions = server2.extensions.join(", ");
const decision = loadInstallDecision(server2.id)?.decision;
+ const context = lspRequestContext();
if (decision === "declined") {
return `LSP server '${server2.id}' (${extensions}) is NOT INSTALLED; user previously declined installation — proceed without LSP.`;
}
@@ -2226,6 +3988,17 @@ function formatNotInstalled(result) {
"The user has pre-authorized LSP installation. Run the install command, then retry this tool:",
` ${installHint}`
].join(`
+`);
+ }
+ if (!context.capabilities.installDecisionTool) {
+ return [
+ ...header,
+ "To install, run:",
+ ` ${installHint}`,
+ "",
+ "ACTION REQUIRED — ASK THE USER whether to install this LSP server.",
+ "Install-decision recording is unavailable in this harness; proceed without LSP if the user declines."
+ ].join(`
`);
}
return [
@@ -2237,6 +4010,7 @@ function formatNotInstalled(result) {
"- If the user agrees: run the install command above, then retry this tool.",
"- If the user declines, OR has NOT explicitly asked for LSP installation:",
` call lsp_install_decision { server_id: "${server2.id}", decision: "declined" },`,
+ ` which writes to ${context.installDecisionsPath},`,
" then ignore this message and proceed WITHOUT LSP."
].join(`
`);
@@ -2250,14 +4024,14 @@ var READ_ONLY_RETRY_TOOLS = new Set([
"prepareRename"
]);
async function withLspClient(filePath, fn, toolName, options = {}) {
- const absPath = resolve2(contextCwd(), filePath);
+ const absPath = resolvePathInsideContext(filePath);
if (isDirectoryPath(absPath)) {
throw new LspInvalidPathError("Directory paths are not supported by this LSP tool. " + "Use lsp.diagnostics with a directory path for directory diagnostics.");
}
const ext = effectiveExtension(absPath);
const result = findServerForExtension(ext);
if (result.status !== "found") {
- throw new LspServerLookupError(formatServerLookupError(result));
+ throw new LspServerLookupError(formatServerLookupError(result), result);
}
const server2 = result.server;
const root = findWorkspaceRoot(absPath);
@@ -2285,11 +4059,11 @@ async function withLspClient(filePath, fn, toolName, options = {}) {
}
// ../lsp-core/src/lsp/directory-diagnostics.ts
-import { existsSync as existsSync6, lstatSync, readdirSync } from "node:fs";
-import { join as join6, resolve as resolve3 } from "node:path";
+import { existsSync as existsSync10, lstatSync as lstatSync4, readdirSync as readdirSync3 } from "node:fs";
+import { join as join5, resolve as resolve8 } from "node:path";
// ../lsp-core/src/lsp/formatters.ts
-import { fileURLToPath } from "node:url";
+import { fileURLToPath as fileURLToPath2 } from "node:url";
var DIAGNOSTIC_SEVERITY_FILTERS = {
error: 1,
warning: 2,
@@ -2297,7 +4071,7 @@ var DIAGNOSTIC_SEVERITY_FILTERS = {
hint: 4
};
function uriToPath(uri) {
- return fileURLToPath(uri);
+ return fileURLToPath2(uri);
}
function formatLocation(loc) {
if ("targetUri" in loc) {
@@ -2383,6 +4157,9 @@ function formatApplyResult(result) {
for (const file of result.filesModified) {
lines.push(` - ${file}`);
}
+ if (result.lateAbort) {
+ lines.push("Cancellation arrived after the filesystem commit began; the committed edit completed.");
+ }
} else {
lines.push("Failed to apply some changes:");
for (const err of result.errors) {
@@ -2398,6 +4175,7 @@ function formatApplyResult(result) {
// ../lsp-core/src/lsp/directory-diagnostics.ts
var SKIP_DIRECTORIES = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
+var DIRECTORY_DIAGNOSTICS_MAX_CONCURRENCY = 4;
function collectFilesWithExtension(dir, extension, maxFiles) {
const files = [];
function walk(currentDir) {
@@ -2405,17 +4183,17 @@ function collectFilesWithExtension(dir, extension, maxFiles) {
return;
let entries = [];
try {
- entries = readdirSync(currentDir);
+ entries = readdirSync3(currentDir);
} catch {
return;
}
for (const entry of entries) {
if (files.length >= maxFiles)
return;
- const fullPath = join6(currentDir, entry);
+ const fullPath = join5(currentDir, entry);
let stat;
try {
- stat = lstatSync(fullPath);
+ stat = lstatSync4(fullPath);
} catch {
continue;
}
@@ -2433,52 +4211,65 @@ function collectFilesWithExtension(dir, extension, maxFiles) {
walk(dir);
return files;
}
-async function aggregateDiagnosticsForDirectory(directory, extension, severity, maxFiles = DEFAULT_MAX_DIRECTORY_FILES) {
+async function aggregateDiagnosticsForDirectory(directory, extension, severity, maxFiles = DEFAULT_MAX_DIRECTORY_FILES, options = {}) {
if (!extension.startsWith(".")) {
throw new LspInvalidPathError(`Extension must start with a dot (e.g., ".ts", not "${extension}"). Use ".${extension}" instead.`);
}
- const absDir = resolve3(contextCwd(), directory);
- if (!existsSync6(absDir)) {
+ const absDir = resolve8(options.workspaceRoot ?? contextCwd(), directory);
+ if (!existsSync10(absDir)) {
throw new LspInvalidPathError(`Directory does not exist: ${absDir}`);
}
- const serverResult = findServerForExtension(extension);
+ const serverResult = options.server === undefined ? findServerForExtension(extension) : { status: "found", server: options.server };
if (serverResult.status !== "found") {
throw new LspServerLookupError(formatServerLookupError(serverResult));
}
const server2 = serverResult.server;
- const allFiles = collectFilesWithExtension(absDir, extension, maxFiles + 1);
+ const allFiles = (options.listFiles ?? collectFilesWithExtension)(absDir, extension, maxFiles + 1);
const wasCapped = allFiles.length > maxFiles;
const filesToProcess = allFiles.slice(0, maxFiles);
if (filesToProcess.length === 0) {
- return [
+ const output = [
`Directory: ${absDir}`,
`Extension: ${extension}`,
"Files scanned: 0",
`No files found with extension "${extension}".`
].join(`
`);
+ return { output, totalDiagnostics: 0, fileFailures: [] };
}
- const root = findWorkspaceRoot(absDir);
- const manager2 = getLspManager();
+ const root = options.workspaceRoot ?? findWorkspaceRoot(absDir);
+ const manager2 = options.manager ?? getLspManager();
const allDiagnostics = [];
const fileErrors = [];
+ const maxConcurrency = Math.max(1, options.maxConcurrency ?? DIRECTORY_DIAGNOSTICS_MAX_CONCURRENCY);
+ options.signal?.throwIfAborted();
const client = await manager2.getClient(root, server2);
try {
- for (const file of filesToProcess) {
- try {
- const result = await client.diagnostics(file);
- const filtered = filterDiagnosticsBySeverity(result.items, severity);
- allDiagnostics.push(...filtered.map((diagnostic) => ({
- filePath: file,
- diagnostic
- })));
- } catch (e) {
- fileErrors.push({
- file,
- error: e instanceof Error ? e.message : String(e)
- });
+ let nextIndex = 0;
+ const workers = Array.from({ length: Math.min(maxConcurrency, filesToProcess.length) }, async () => {
+ for (;; ) {
+ if (options.signal?.aborted)
+ return;
+ const file = filesToProcess[nextIndex];
+ nextIndex += 1;
+ if (file === undefined)
+ return;
+ try {
+ const result = await client.diagnostics(file, options.signal);
+ const filtered = filterDiagnosticsBySeverity(result.items, severity);
+ allDiagnostics.push(...filtered.map((diagnostic) => ({
+ filePath: file,
+ diagnostic
+ })));
+ } catch (e) {
+ fileErrors.push({
+ file,
+ error: e instanceof Error ? e.message : String(e)
+ });
+ }
}
- }
+ });
+ await Promise.all(workers);
} finally {
manager2.releaseClient(root, server2.id);
}
@@ -2506,13 +4297,13 @@ async function aggregateDiagnosticsForDirectory(directory, extension, severity,
lines.push("", `... (${allDiagnostics.length - DEFAULT_MAX_DIAGNOSTICS} more diagnostics not shown)`);
}
}
- return lines.join(`
-`);
+ return { output: lines.join(`
+`), totalDiagnostics: allDiagnostics.length, fileFailures: fileErrors };
}
// ../lsp-core/src/lsp/infer-extension.ts
-import { lstatSync as lstatSync2, readdirSync as readdirSync2 } from "node:fs";
-import { join as join7 } from "node:path";
+import { lstatSync as lstatSync5, readdirSync as readdirSync4 } from "node:fs";
+import { join as join6 } from "node:path";
var SKIP_DIRECTORIES2 = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
var MAX_SCAN_ENTRIES = 500;
function inferExtensionFromDirectory(directory) {
@@ -2523,17 +4314,17 @@ function inferExtensionFromDirectory(directory) {
return;
let entries;
try {
- entries = readdirSync2(dir);
+ entries = readdirSync4(dir);
} catch {
return;
}
for (const entry of entries) {
if (scanned >= MAX_SCAN_ENTRIES)
return;
- const fullPath = join7(dir, entry);
+ const fullPath = join6(dir, entry);
let stat;
try {
- stat = lstatSync2(fullPath);
+ stat = lstatSync5(fullPath);
} catch {
continue;
}
@@ -2607,13 +4398,48 @@ function missingDependencyResult(error, details) {
details: {
...details,
error: message,
- errorKind: "missing_dependency"
+ errorKind: "missing_dependency",
+ ...availabilityDetails(error)
}
};
}
+function availabilityDetails(error) {
+ const availability = missingDependencyAvailability(error);
+ return availability === null ? {} : { availability };
+}
+function missingDependencyAvailability(error) {
+ if (!(error instanceof LspServerLookupError) || error.lookup === undefined)
+ return null;
+ const context = lspRequestContext();
+ switch (error.lookup.status) {
+ case "not_configured":
+ return {
+ kind: "not_configured",
+ extension: error.lookup.extension,
+ availableServers: [...error.lookup.availableServers],
+ projectConfigPaths: [...context.projectConfigPaths],
+ userConfigPath: context.userConfigPath,
+ installDecisionTool: context.capabilities.installDecisionTool
+ };
+ case "not_installed":
+ return {
+ kind: "not_installed",
+ serverId: error.lookup.server.id,
+ command: [...error.lookup.server.command],
+ extensions: [...error.lookup.server.extensions],
+ installHint: error.lookup.installHint,
+ installDecisionTool: context.capabilities.installDecisionTool,
+ installDecisionsPath: context.installDecisionsPath
+ };
+ default: {
+ const exhaustive = error.lookup;
+ return exhaustive;
+ }
+ }
+}
// ../lsp-core/src/tools/parameters.ts
-function isRecord4(value) {
+function isRecord7(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function requireString(params, key) {
@@ -2670,7 +4496,7 @@ async function executeLspDiagnostics(params, signal) {
const filePath = requireString(params, "filePath");
const severity = severityFilter(params);
try {
- const absPath = resolve4(contextCwd(), filePath);
+ const absPath = resolvePathInsideContext(filePath);
if (isDirectoryPath(absPath)) {
const extension = inferExtensionFromDirectory(absPath);
if (!extension) {
@@ -2687,18 +4513,33 @@ async function executeLspDiagnostics(params, signal) {
};
return text(message, details3);
}
- const output2 = await aggregateDiagnosticsForDirectory(absPath, extension, severity);
+ const output2 = await aggregateDiagnosticsForDirectory(absPath, extension, severity, undefined, signal === undefined ? {} : { signal });
const details2 = {
filePath,
severity,
mode: "directory",
diagnostics: [],
+ totalDiagnostics: output2.totalDiagnostics,
+ truncated: false,
+ fileFailures: [...output2.fileFailures]
+ };
+ return text(output2.output, details2);
+ }
+ const result = await withLspClient(filePath, async (client) => client.diagnostics(filePath, signal), "diagnostics", clientOptions(signal));
+ if (result.transientError) {
+ const message = result.transientError.message;
+ const details2 = {
+ filePath,
+ severity,
+ mode: "file",
+ diagnostics: [],
totalDiagnostics: 0,
- truncated: false
+ truncated: false,
+ error: message,
+ errorKind: result.transientError.kind
};
- return text(output2, details2);
+ return text(message, details2, true);
}
- const result = await withLspClient(filePath, async (client) => client.diagnostics(filePath), "diagnostics", clientOptions(signal));
const diagnostics = filterDiagnosticsBySeverity(asDiagnosticArray(result), severity);
const total = diagnostics.length;
const truncated = total > DEFAULT_MAX_DIAGNOSTICS;
@@ -2759,7 +4600,7 @@ async function executeLspGotoDefinition(params, signal) {
const line = requireNumber(params, "line");
const character = requireNumber(params, "character");
try {
- const result = await withLspClient(filePath, async (client) => client.definition(filePath, line, character), "definition", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.definition(filePath, line, character, signal), "definition", clientOptions(signal));
const locations = !result ? [] : Array.isArray(result) ? result : [result];
const details = { filePath, line, character, locations };
if (locations.length === 0)
@@ -2784,7 +4625,7 @@ async function executeLspFindReferences(params, signal) {
const character = requireNumber(params, "character");
const includeDeclaration = optionalBoolean(params, "includeDeclaration") ?? true;
try {
- const result = await withLspClient(filePath, async (client) => client.references(filePath, line, character, includeDeclaration), "references", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.references(filePath, line, character, includeDeclaration, signal), "references", clientOptions(signal));
const references = Array.isArray(result) ? result : [];
const total = references.length;
const truncated = total > DEFAULT_MAX_REFERENCES;
@@ -2820,181 +4661,13 @@ async function executeLspFindReferences(params, signal) {
}
}
-// ../lsp-core/src/lsp/workspace-edit.ts
-import { existsSync as existsSync7, readFileSync as readFileSync4, realpathSync, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
-import { dirname as dirname3, isAbsolute as isAbsolute3, relative, resolve as resolve5 } from "node:path";
-import { fileURLToPath as fileURLToPath2 } from "node:url";
-function errorMessage2(error) {
- return error instanceof Error ? error.message : String(error);
-}
-function isPathInsideWorkspace(filePath, workspaceRoot) {
- const relativePath = relative(workspaceRoot, filePath);
- return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute3(relativePath);
-}
-function realpathForValidation(filePath) {
- if (existsSync7(filePath))
- return realpathSync(filePath);
- const parent = dirname3(filePath);
- return resolve5(realpathSync(parent), relative(parent, filePath));
-}
-function uriToWorkspacePath(uri, workspaceRoot) {
- let filePath;
- try {
- filePath = fileURLToPath2(uri);
- } catch (error) {
- return { success: false, error: `non-file URI ${uri}: ${errorMessage2(error)}` };
- }
- let validatedPath;
- try {
- validatedPath = realpathForValidation(filePath);
- } catch (error) {
- return { success: false, error: `${filePath}: ${errorMessage2(error)}` };
- }
- if (!isPathInsideWorkspace(validatedPath, workspaceRoot)) {
- return { success: false, error: `${filePath}: outside workspace ${workspaceRoot}` };
- }
- return { success: true, path: filePath };
-}
-function applyTextEditsToFile(filePath, edits) {
- try {
- const content = readFileSync4(filePath, "utf-8");
- const lines = content.split(`
-`);
- const sortedEdits = [...edits].sort((a, b) => {
- if (b.range.start.line !== a.range.start.line) {
- return b.range.start.line - a.range.start.line;
- }
- return b.range.start.character - a.range.start.character;
- });
- for (const edit of sortedEdits) {
- const startLine = edit.range.start.line;
- const startChar = edit.range.start.character;
- const endLine = edit.range.end.line;
- const endChar = edit.range.end.character;
- if (startLine === endLine) {
- const line = lines[startLine] ?? "";
- lines[startLine] = line.substring(0, startChar) + edit.newText + line.substring(endChar);
- } else {
- const firstLine = lines[startLine] ?? "";
- const lastLine = lines[endLine] ?? "";
- const newContent = firstLine.substring(0, startChar) + edit.newText + lastLine.substring(endChar);
- lines.splice(startLine, endLine - startLine + 1, ...newContent.split(`
-`));
- }
- }
- writeFileSync2(filePath, lines.join(`
-`), "utf-8");
- return { success: true, editCount: edits.length };
- } catch (err) {
- return {
- success: false,
- editCount: 0,
- error: err instanceof Error ? err.message : String(err)
- };
- }
-}
-function applyWorkspaceEdit(edit, options = {}) {
- if (!edit) {
- return { success: false, filesModified: [], totalEdits: 0, errors: ["No edit provided"] };
- }
- const result = { success: true, filesModified: [], totalEdits: 0, errors: [] };
- const workspaceRoot = realpathSync(options.workspaceRoot ?? contextCwd());
- if (edit.changes) {
- for (const [uri, edits] of Object.entries(edit.changes)) {
- const validatedPath = uriToWorkspacePath(uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(validatedPath.error);
- continue;
- }
- const applyResult = applyTextEditsToFile(validatedPath.path, edits);
- if (applyResult.success) {
- result.filesModified.push(validatedPath.path);
- result.totalEdits += applyResult.editCount;
- } else {
- result.success = false;
- result.errors.push(`${validatedPath.path}: ${applyResult.error}`);
- }
- }
- }
- if (edit.documentChanges) {
- for (const change of edit.documentChanges) {
- if (!("kind" in change)) {
- const validatedPath = uriToWorkspacePath(change.textDocument.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(validatedPath.error);
- continue;
- }
- const applyResult = applyTextEditsToFile(validatedPath.path, change.edits);
- if (applyResult.success) {
- result.filesModified.push(validatedPath.path);
- result.totalEdits += applyResult.editCount;
- } else {
- result.success = false;
- result.errors.push(`${validatedPath.path}: ${applyResult.error}`);
- }
- continue;
- }
- if (change.kind === "create") {
- try {
- const validatedPath = uriToWorkspacePath(change.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(`Create ${change.uri}: ${validatedPath.error}`);
- continue;
- }
- writeFileSync2(validatedPath.path, "", "utf-8");
- result.filesModified.push(validatedPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Create ${change.uri}: ${String(err)}`);
- }
- } else if (change.kind === "rename") {
- try {
- const oldPath = uriToWorkspacePath(change.oldUri, workspaceRoot);
- const newPath = uriToWorkspacePath(change.newUri, workspaceRoot);
- if (!oldPath.success || !newPath.success) {
- const error = oldPath.success ? newPath.success ? "invalid URI" : newPath.error : oldPath.error;
- result.success = false;
- result.errors.push(`Rename ${change.oldUri}: ${error}`);
- continue;
- }
- const content = readFileSync4(oldPath.path, "utf-8");
- writeFileSync2(newPath.path, content, "utf-8");
- unlinkSync(oldPath.path);
- result.filesModified.push(newPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Rename ${change.oldUri}: ${String(err)}`);
- }
- } else if (change.kind === "delete") {
- try {
- const validatedPath = uriToWorkspacePath(change.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(`Delete ${change.uri}: ${validatedPath.error}`);
- continue;
- }
- unlinkSync(validatedPath.path);
- result.filesModified.push(validatedPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Delete ${change.uri}: ${String(err)}`);
- }
- }
- }
- }
- return result;
-}
-
// ../lsp-core/src/tools/rename.ts
async function executeLspPrepareRename(params, signal) {
const filePath = requireString(params, "filePath");
const line = requireNumber(params, "line");
const character = requireNumber(params, "character");
try {
- const result = await withLspClient(filePath, async (client) => client.prepareRename(filePath, line, character), "prepareRename", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.prepareRename(filePath, line, character, signal), "prepareRename", clientOptions(signal));
const details = { filePath, line, character, result };
return text(formatPrepareRenameResult(result), details);
} catch (error) {
@@ -3015,13 +4688,9 @@ async function executeLspRename(params, signal) {
const character = requireNumber(params, "character");
const newName = requireString(params, "newName");
try {
- const edit = await withLspClient(filePath, async (client, workspaceRoot) => ({
- edit: await client.rename(filePath, line, character, newName),
- workspaceRoot
- }), "rename", clientOptions(signal));
- const apply = applyWorkspaceEdit(edit.edit, { workspaceRoot: edit.workspaceRoot });
- const details = { filePath, line, character, newName, apply, edit: edit.edit };
- return text(formatApplyResult(apply), details, !apply.success);
+ const result = await withLspClient(filePath, async (client) => client.rename(filePath, line, character, newName, signal), "rename", clientOptions(signal));
+ const details = { filePath, line, character, newName, apply: result.apply, edit: result.edit };
+ return text(formatApplyResult(result.apply), details, !result.apply.success);
} catch (error) {
const missingDependency = missingDependencyResult(error, {
filePath,
@@ -3096,10 +4765,10 @@ async function executeLspSymbols(params, signal) {
errorKind: "missing_query"
});
}
- const symbols2 = await withLspClient(filePath, async (client) => client.workspaceSymbols(query), "workspaceSymbols", clientOptions(signal));
+ const symbols2 = await withLspClient(filePath, async (client) => client.workspaceSymbols(query, signal), "workspaceSymbols", clientOptions(signal));
return formatSymbolsResult(filePath, scope, symbols2, limit, query);
}
- const symbols = await withLspClient(filePath, async (client) => client.documentSymbols(filePath), "documentSymbols", clientOptions(signal));
+ const symbols = await withLspClient(filePath, async (client) => client.documentSymbols(filePath, signal), "documentSymbols", clientOptions(signal));
return formatSymbolsResult(filePath, scope, symbols, limit);
} catch (error) {
const query = optionalString(params, "query");
@@ -3265,12 +4934,12 @@ function matchesToolName(tool, name) {
return tool.name === name || (tool.aliases?.includes(name) ?? false);
}
function coerceToolArguments(value) {
- return isRecord4(value) ? value : {};
+ return isRecord7(value) ? value : {};
}
// ../lsp-core/src/mcp.ts
var SERVER_NAME = "lsp";
var SERVER_VERSION = "0.1.0";
-async function handleLspMcpRequest(input) {
+async function handleLspMcpRequest(input, options = {}) {
if (!isPlainRecord(input)) {
return errorResponse(null, -32600, "Invalid Request");
}
@@ -3292,33 +4961,37 @@ async function handleLspMcpRequest(input) {
return successResponse(id, { tools: LSP_MCP_TOOLS.map(describeTool) });
}
if (method === "tools/call") {
- return handleToolCall(id, input["params"]);
+ return handleToolCall(id, input["params"], options.signal);
}
return errorResponse(id, -32601, `Method not found: ${String(method)}`);
}
async function runMcpStdioServer(input = process.stdin, output = process.stdout) {
+ const requestContext = createStandaloneMcpRequestContext();
await runJsonRpcStdioServer({
input,
output,
idleTimeoutMs: 0,
- handler: handleLspMcpRequest,
+ handler: (request) => runWithRequestContext(requestContext, () => handleLspMcpRequest(request)),
handlerOptions: undefined
});
}
-async function handleToolCall(id, params) {
+async function handleToolCall(id, params, signal) {
if (!isPlainRecord(params) || typeof params["name"] !== "string") {
return errorResponse(id, -32602, "tools/call requires params.name");
}
try {
- const result = await executeLspTool(params["name"], coerceToolArguments(params["arguments"]));
+ const result = await executeLspTool(params["name"], coerceToolArguments(params["arguments"]), signal);
return successResponse(id, {
content: result.content,
isError: result.isError ?? false,
details: result.details
});
} catch (error) {
+ if (!(error instanceof Error)) {
+ throw error;
+ }
return successResponse(id, {
- content: [{ type: "text", text: messageFromError(error) }],
+ content: [{ type: "text", text: error.message }],
isError: true
});
}
diff --git a/plugins/omo/components/lsp-tools-mcp/dist/lsp/manager.js b/plugins/omo/components/lsp-tools-mcp/dist/lsp/manager.js
index 9c41305f..e0354e4f 100644
--- a/plugins/omo/components/lsp-tools-mcp/dist/lsp/manager.js
+++ b/plugins/omo/components/lsp-tools-mcp/dist/lsp/manager.js
@@ -1,31 +1,16 @@
// ../lsp-core/src/lsp/cleanup-errors.ts
-function reportBestEffortCleanupError(operation, error) {
- if (process.env["CODEX_LSP_DEBUG_CLEANUP"] !== "1")
- return;
+function writeCleanupError(message) {
+ process.stderr.write(`${message}
+`);
+}
+function reportBestEffortCleanupError(operation, error, logger = writeCleanupError) {
const message = error instanceof Error ? error.message : String(error);
- console.error(`[codex-lsp] ignored ${operation} failure during cleanup: ${message}`);
+ logger(`[lsp] ignored ${operation} failure during cleanup: ${message}`);
}
// ../lsp-core/src/lsp/client.ts
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
-import { pathToFileURL as pathToFileURL2 } from "node:url";
-
-// ../lsp-core/src/request-context.ts
-import { AsyncLocalStorage } from "node:async_hooks";
-var storage = new AsyncLocalStorage;
-function runWithRequestContext(context, fn) {
- return storage.run(context, fn);
-}
-function contextCwd() {
- return storage.getStore()?.cwd ?? process.cwd();
-}
-function contextEnv(key) {
- const store = storage.getStore();
- if (store?.env)
- return store.env[key];
- return process.env[key];
-}
+import { resolve as resolve5 } from "node:path";
+import { pathToFileURL as pathToFileURL3 } from "node:url";
// ../lsp-core/src/lsp/connection.ts
import { pathToFileURL } from "node:url";
@@ -89,7 +74,12 @@ class LspInvalidPathError extends Error {
}
class LspServerLookupError extends Error {
+ lookup;
name = "LspServerLookupError";
+ constructor(message, lookup) {
+ super(message);
+ this.lookup = lookup;
+ }
}
class LspServerInitializingError extends Error {
@@ -155,28 +145,80 @@ class JsonRpcConnection {
onError(handler) {
this.errorHandlers.push(handler);
}
- async sendRequest(method, params) {
+ async sendRequest(method, params, options = {}) {
if (this.disposed)
throw new Error("JSON-RPC connection is disposed");
const id = this.nextRequestId;
this.nextRequestId += 1;
+ const key = String(id);
const message = params === undefined ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
+ let requestWritten = false;
+ let cancelAfterWrite = false;
+ let settled = false;
+ const writeCancel = () => this.writeMessage({ jsonrpc: "2.0", method: "$/cancelRequest", params: { id } });
const responsePromise = new Promise((resolve, reject) => {
- this.pendingRequests.set(String(id), {
+ const cleanup = () => {
+ options.signal?.removeEventListener("abort", onAbort);
+ };
+ const settleCancel = () => {
+ if (settled)
+ return;
+ settled = true;
+ this.pendingRequests.delete(key);
+ cleanup();
+ const rejectCancelled = () => reject(abortError(options.signal));
+ if (!requestWritten) {
+ cancelAfterWrite = true;
+ rejectCancelled();
+ return;
+ }
+ writeCancel().then(rejectCancelled, (error) => {
+ this.emitError(toError(error));
+ rejectCancelled();
+ });
+ };
+ const onAbort = () => settleCancel();
+ this.pendingRequests.set(key, {
resolve(result) {
+ settled = true;
+ cleanup();
resolve(result);
},
- reject
+ reject(error) {
+ settled = true;
+ cleanup();
+ reject(error);
+ },
+ cleanup
});
+ if (options.signal?.aborted) {
+ settleCancel();
+ return;
+ }
+ options.signal?.addEventListener("abort", onAbort, { once: true });
});
+ if (settled)
+ return responsePromise;
try {
await this.writeMessage(message);
+ requestWritten = true;
+ if (cancelAfterWrite)
+ await writeCancel();
} catch (error) {
- this.pendingRequests.delete(String(id));
+ if (settled)
+ return responsePromise;
+ const pending = this.pendingRequests.get(key);
+ if (pending) {
+ pending.cleanup();
+ this.pendingRequests.delete(key);
+ }
throw error;
}
return responsePromise;
}
+ pendingRequestCount() {
+ return this.pendingRequests.size;
+ }
async sendNotification(method, params) {
if (this.disposed)
return;
@@ -193,6 +235,7 @@ class JsonRpcConnection {
this.reader.off("error", this.handleStreamError);
this.writer.off("error", this.handleStreamError);
for (const pending of this.pendingRequests.values()) {
+ pending.cleanup();
pending.reject(new Error("JSON-RPC connection disposed"));
}
this.pendingRequests.clear();
@@ -268,6 +311,7 @@ class JsonRpcConnection {
if (!pending)
return;
this.pendingRequests.delete(String(id));
+ pending.cleanup();
if ("error" in message) {
pending.reject(jsonRpcErrorToError(message["error"]));
return;
@@ -281,7 +325,11 @@ class JsonRpcConnection {
try {
handler(params);
} catch (error) {
- this.emitError(toError(error));
+ if (error instanceof Error) {
+ this.emitError(error);
+ return;
+ }
+ this.emitError(new Error(String(error)));
}
}
handleRequest(message) {
@@ -322,6 +370,14 @@ ${body}`;
}
}
}
+function abortError(signal) {
+ const reason = signal?.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "LSP request cancelled");
+ error.name = "AbortError";
+ return error;
+}
function parseContentLength(headers) {
for (const line of headers.split(`\r
`)) {
@@ -508,7 +564,7 @@ function spawnProcess(command, options) {
return wrap(proc);
}
-// ../lsp-core/src/lsp/transport.ts
+// ../lsp-core/src/lsp/transport-protocol.ts
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
@@ -528,7 +584,32 @@ function parseDiagnosticsParams(params) {
if (!isRecord(params) || typeof params["uri"] !== "string")
return null;
const diagnostics = Array.isArray(params["diagnostics"]) ? params["diagnostics"].filter(isDiagnostic) : [];
- return { uri: params["uri"], diagnostics };
+ const version = typeof params["version"] === "number" ? params["version"] : undefined;
+ return { uri: params["uri"], diagnostics, ...version === undefined ? {} : { version } };
+}
+function createLspSpawnEnv(_root, input) {
+ return { ...input };
+}
+function isDiagnostic(value) {
+ return isRecord(value) && isRange(value["range"]) && typeof value["message"] === "string";
+}
+function isRange(value) {
+ return isRecord(value) && isPosition(value["start"]) && isPosition(value["end"]);
+}
+function isPosition(value) {
+ return isRecord(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+}
+
+// ../lsp-core/src/lsp/transport.ts
+class LspClientNotStartedError extends Error {
+ serverId;
+ root;
+ name = "LspClientNotStartedError";
+ constructor(serverId, root) {
+ super("LSP client not started");
+ this.serverId = serverId;
+ this.root = root;
+ }
}
class LspClientTransport {
@@ -541,6 +622,8 @@ class LspClientTransport {
diagnosticsStore = new Map;
requestTimeoutMs;
initializeTimeoutMs;
+ workspaceApplyEditHandler = null;
+ diagnosticPullSupported = false;
constructor(root, server, timeouts = {}) {
this.root = root;
this.server = server;
@@ -553,6 +636,21 @@ class LspClientTransport {
command() {
return [...this.server.command];
}
+ setWorkspaceApplyEditHandler(handler) {
+ this.workspaceApplyEditHandler = handler;
+ }
+ hasWorkspaceApplyEditHandler() {
+ return this.workspaceApplyEditHandler !== null;
+ }
+ setDiagnosticPullSupported(supported) {
+ this.diagnosticPullSupported = supported;
+ }
+ isDiagnosticPullSupported() {
+ return this.diagnosticPullSupported;
+ }
+ handlePublishDiagnostics(params) {
+ this.diagnosticsStore.set(params.uri, [...params.diagnostics]);
+ }
async start() {
const env = createLspSpawnEnv(this.root, {
...process.env,
@@ -563,7 +661,6 @@ class LspClientTransport {
env
});
this.startStderrReading();
- await new Promise((resolve) => setTimeout(resolve, 100));
if (this.proc.exitCode !== null) {
const stderr = this.stderrBuffer.join(`
`);
@@ -573,7 +670,7 @@ class LspClientTransport {
this.connection.onNotification("textDocument/publishDiagnostics", (params) => {
const diagnosticsParams = parseDiagnosticsParams(params);
if (diagnosticsParams?.uri) {
- this.diagnosticsStore.set(diagnosticsParams.uri, diagnosticsParams.diagnostics);
+ this.handlePublishDiagnostics(diagnosticsParams);
}
});
this.connection.onRequest("workspace/configuration", (params) => {
@@ -586,6 +683,9 @@ class LspClientTransport {
});
this.connection.onRequest("client/registerCapability", () => null);
this.connection.onRequest("window/workDoneProgress/create", () => null);
+ if (this.workspaceApplyEditHandler) {
+ this.connection.onRequest("workspace/applyEdit", this.workspaceApplyEditHandler);
+ }
this.connection.onClose(() => {
this.processExited = true;
});
@@ -614,30 +714,25 @@ class LspClientTransport {
}
async sendRequest(method, ...args) {
if (!this.connection)
- throw new Error("LSP client not started");
+ throw new LspClientNotStartedError(this.server.id, this.root);
if (this.processExited || this.proc && this.proc.exitCode !== null) {
const stderrTail = this.stderrBuffer.slice(-10).join(`
`);
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, stderrTail || undefined);
}
- const timeoutMs = args[1]?.timeoutMs ?? this.requestTimeoutMs;
- let timeoutHandle = null;
- const timeoutPromise = new Promise((_, reject) => {
- timeoutHandle = setTimeout(() => {
- const stderrTail = this.stderrBuffer.slice(-5).join(`
+ const options = args[1];
+ const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
+ const timeoutController = new AbortController;
+ const timeoutHandle = setTimeout(() => {
+ const stderrTail = this.stderrBuffer.slice(-5).join(`
`);
- reject(new LspRequestTimeoutError(method, stderrTail || undefined));
- }, timeoutMs);
- });
+ timeoutController.abort(new LspRequestTimeoutError(method, stderrTail || undefined));
+ }, timeoutMs);
+ const combinedSignal = combineAbortSignals(options?.signal, timeoutController.signal);
try {
- const requestPromise = args.length === 0 ? this.connection.sendRequest(method) : this.connection.sendRequest(method, args[0]);
- const result = await Promise.race([requestPromise, timeoutPromise]);
- if (timeoutHandle !== null)
- clearTimeout(timeoutHandle);
+ const result = args.length === 0 ? await this.connection.sendRequest(method, undefined, { signal: combinedSignal.signal }) : await this.connection.sendRequest(method, args[0], { signal: combinedSignal.signal });
return result;
} catch (error) {
- if (timeoutHandle !== null)
- clearTimeout(timeoutHandle);
if (this.processExited || this.proc && this.proc.exitCode !== null) {
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, this.stderrBuffer.slice(-10).join(`
`) || undefined);
@@ -646,6 +741,9 @@ class LspClientTransport {
throw new LspConnectionClosedError(this.server.id, this.root, error.message);
}
throw error;
+ } finally {
+ clearTimeout(timeoutHandle);
+ combinedSignal.dispose();
}
}
async sendNotification(method, ...args) {
@@ -674,17 +772,17 @@ class LspClientTransport {
try {
await this.sendRequest("shutdown");
} catch (error) {
- reportBestEffortCleanupError("shutdown request", error);
+ reportBestEffortCleanupError("shutdown request", error instanceof Error ? error : String(error));
}
try {
await this.sendNotification("exit");
} catch (error) {
- reportBestEffortCleanupError("exit notification", error);
+ reportBestEffortCleanupError("exit notification", error instanceof Error ? error : String(error));
}
try {
this.connection.dispose();
} catch (error) {
- reportBestEffortCleanupError("connection dispose", error);
+ reportBestEffortCleanupError("connection dispose", error instanceof Error ? error : String(error));
}
this.connection = null;
}
@@ -715,11 +813,11 @@ class LspClientTransport {
new Promise((resolve) => setTimeout(resolve, STOP_SIGKILL_GRACE_MS))
]);
} catch (error) {
- reportBestEffortCleanupError("hard process kill", error);
+ reportBestEffortCleanupError("hard process kill", error instanceof Error ? error : String(error));
}
}
} catch (error) {
- reportBestEffortCleanupError("process stop", error);
+ reportBestEffortCleanupError("process stop", error instanceof Error ? error : String(error));
}
}
this.processExited = true;
@@ -729,26 +827,45 @@ class LspClientTransport {
return this.diagnosticsStore.get(uri) ?? [];
}
}
-function createLspSpawnEnv(_root, input) {
- return { ...input };
-}
-function isDiagnostic(value) {
- return isRecord(value) && isRange(value["range"]) && typeof value["message"] === "string";
-}
-function isRange(value) {
- return isRecord(value) && isPosition(value["start"]) && isPosition(value["end"]);
-}
-function isPosition(value) {
- return isRecord(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+function combineAbortSignals(primary, secondary) {
+ const controller = new AbortController;
+ const abortFrom = (signal) => {
+ if (!controller.signal.aborted)
+ controller.abort(signal.reason);
+ };
+ const onPrimaryAbort = () => {
+ if (primary)
+ abortFrom(primary);
+ };
+ const onSecondaryAbort = () => abortFrom(secondary);
+ if (primary?.aborted)
+ abortFrom(primary);
+ else
+ primary?.addEventListener("abort", onPrimaryAbort, { once: true });
+ if (secondary.aborted)
+ abortFrom(secondary);
+ else
+ secondary.addEventListener("abort", onSecondaryAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => {
+ primary?.removeEventListener("abort", onPrimaryAbort);
+ secondary.removeEventListener("abort", onSecondaryAbort);
+ }
+ };
}
// ../lsp-core/src/lsp/connection.ts
-var INITIALIZE_SETTLE_MS = 300;
+function supportsDiagnosticPull(capabilities) {
+ if (capabilities === undefined)
+ return false;
+ return Object.hasOwn(capabilities, "diagnosticProvider");
+}
class LspClientConnection extends LspClientTransport {
async initialize() {
const rootUri = pathToFileURL(this.root).href;
- await this.sendRequest("initialize", {
+ const result = await this.sendRequest("initialize", {
processId: process.pid,
rootUri,
rootPath: this.root,
@@ -762,8 +879,7 @@ class LspClientConnection extends LspClientTransport {
publishDiagnostics: {},
rename: {
prepareSupport: true,
- prepareSupportDefaultBehavior: 1,
- honorsChangeAnnotations: true
+ prepareSupportDefaultBehavior: 1
},
codeAction: {
codeActionLiteralSupport: {
@@ -792,22 +908,28 @@ class LspClientConnection extends LspClientTransport {
symbol: {},
workspaceFolders: true,
configuration: true,
- applyEdit: true,
+ ...this.hasWorkspaceApplyEditHandler() ? { applyEdit: true } : {},
workspaceEdit: {
- documentChanges: true
+ documentChanges: true,
+ resourceOperations: ["create", "rename", "delete"]
}
}
},
initializationOptions: this.server.initialization
}, { timeoutMs: this.initializeTimeoutMs });
+ this.setDiagnosticPullSupported(supportsDiagnosticPull(result?.capabilities));
await this.sendNotification("initialized");
await this.sendNotification("workspace/didChangeConfiguration", {
settings: { json: { validate: { enable: true } } }
});
- await new Promise((r) => setTimeout(r, INITIALIZE_SETTLE_MS));
}
}
+// ../lsp-core/src/lsp/workspace-document-state.ts
+import { readFileSync, realpathSync } from "node:fs";
+import { relative, resolve } from "node:path";
+import { pathToFileURL as pathToFileURL2 } from "node:url";
+
// ../lsp-core/src/lsp/effective-extension.ts
import { basename, extname } from "node:path";
var BASENAME_EXTENSIONS = {
@@ -990,82 +1112,1422 @@ function getLanguageId(ext) {
return EXT_TO_LANG[ext] ?? "plaintext";
}
-// ../lsp-core/src/lsp/client.ts
-var POST_OPEN_DELAY_MS = 1000;
-var POST_DIAGNOSTICS_WAIT_MS = 500;
+// ../lsp-core/src/lsp/workspace-document-state.ts
+var WATCHED_FILE_BATCH_SIZE = 128;
+var DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
+function canonicalPath(filePath) {
+ const absolute = resolve(filePath);
+ try {
+ return realpathSync(absolute);
+ } catch {
+ return absolute;
+ }
+}
+function isSameOrDescendant(candidate, parent) {
+ const suffix = relative(parent, candidate);
+ return suffix === "" || !suffix.startsWith("..") && suffix !== "..";
+}
+function movedPath(candidate, oldPath, newPath) {
+ const suffix = relative(oldPath, candidate);
+ return suffix === "" ? newPath : resolve(newPath, suffix);
+}
-class LspClient extends LspClientConnection {
- openedFiles = new Set;
- documentVersions = new Map;
- lastSyncedText = new Map;
- diagnosticPullErrors = [];
- getDiagnosticPullErrors() {
- return this.diagnosticPullErrors;
+class WorkspaceDocumentState {
+ sendNotification;
+ clearDiagnostics;
+ openDocuments = new Map;
+ openByUri = new Map;
+ openPromises = new Map;
+ now;
+ versionlessPublishQuiescenceMs;
+ constructor(sendNotification, clearDiagnostics, options = {}) {
+ this.sendNotification = sendNotification;
+ this.clearDiagnostics = clearDiagnostics;
+ this.now = options.now ?? (() => Date.now());
+ this.versionlessPublishQuiescenceMs = options.versionlessPublishQuiescenceMs ?? DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS;
}
async openFile(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- const uri = pathToFileURL2(absPath).href;
- const text = readFileSync(absPath, "utf-8");
- if (!this.openedFiles.has(absPath)) {
- const ext = effectiveExtension(absPath);
- const languageId = getLanguageId(ext);
- const version = 1;
- await this.sendNotification("textDocument/didOpen", {
- textDocument: {
- uri,
- languageId,
- version,
- text
+ const path = canonicalPath(filePath);
+ const existingOpen = this.openPromises.get(path);
+ if (existingOpen) {
+ await existingOpen;
+ return this.openFile(path);
+ }
+ const text = readFileSync(path, "utf-8");
+ const existing = this.openDocuments.get(path);
+ if (!existing)
+ return this.openDocumentSingleFlight(path, text);
+ if (existing.text === text)
+ return;
+ await this.changeDocument(existing, text);
+ }
+ getVersion(filePath) {
+ return this.openDocuments.get(canonicalPath(filePath))?.version;
+ }
+ getStoredDiagnostics(uri) {
+ const state = this.openByUri.get(uri);
+ if (!state)
+ return [];
+ return state.lastPublish?.diagnostics ?? state.pullCache?.diagnostics ?? [];
+ }
+ captureDiagnosticSnapshot(filePath) {
+ const state = this.openDocuments.get(canonicalPath(filePath));
+ if (!state)
+ return null;
+ return {
+ path: state.path,
+ uri: state.uri,
+ version: state.version,
+ documentGeneration: state.generation,
+ publishGeneration: state.publishGeneration
+ };
+ }
+ isCurrentSnapshot(snapshot) {
+ const state = this.openDocuments.get(snapshot.path);
+ return state !== undefined && state.uri === snapshot.uri && state.version === snapshot.version && state.generation === snapshot.documentGeneration;
+ }
+ getPullCache(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.pullCache || state.pullCache.documentVersion !== snapshot.version)
+ return null;
+ return state.pullCache;
+ }
+ recordPullDiagnostics(snapshot, report) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state)
+ return;
+ state.pullCache = {
+ documentVersion: snapshot.version,
+ diagnostics: [...report.diagnostics],
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ };
+ }
+ recordPublishedDiagnostics(params) {
+ const state = this.openByUri.get(params.uri);
+ if (!state)
+ return;
+ state.publishGeneration += 1;
+ state.lastPublish = {
+ diagnostics: [...params.diagnostics],
+ publishGeneration: state.publishGeneration,
+ documentGenerationAtArrival: state.generation,
+ arrivedAt: this.now(),
+ ...params.version === undefined ? {} : { version: params.version }
+ };
+ this.notifyWaiters(state);
+ }
+ resolvePushDiagnostics(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.lastPublish)
+ return { status: "missing" };
+ const publish = state.lastPublish;
+ if (publish.version !== undefined) {
+ return publish.version === snapshot.version ? { status: "ready", diagnostics: publish.diagnostics } : { status: "missing" };
+ }
+ if (publish.documentGenerationAtArrival < snapshot.documentGeneration)
+ return { status: "missing" };
+ const readyAt = publish.arrivedAt + this.versionlessPublishQuiescenceMs;
+ const waitMs = Math.max(0, readyAt - this.now());
+ return waitMs === 0 ? { status: "ready", diagnostics: publish.diagnostics } : { status: "wait", waitMs };
+ }
+ waitForDiagnosticsActivity(snapshot, timeoutMs) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state || timeoutMs <= 0)
+ return Promise.resolve();
+ return new Promise((resolveActivity) => {
+ let settled = false;
+ const finish = () => {
+ if (settled)
+ return;
+ settled = true;
+ clearTimeout(timer);
+ state.waiters.delete(finish);
+ resolveActivity();
+ };
+ const timer = setTimeout(finish, timeoutMs);
+ if (typeof timer.unref === "function")
+ timer.unref();
+ state.waiters.add(finish);
+ });
+ }
+ validateVersions(operations) {
+ const versions = new Map([...this.openDocuments].map(([path, state]) => [path, state.version]));
+ for (const operation of operations) {
+ if (operation.kind === "text") {
+ const current = versions.get(operation.path);
+ if (operation.documentVersion !== null && current !== operation.documentVersion) {
+ const observed = current === undefined ? "closed document" : `open document version ${current}`;
+ return {
+ changeIndex: operation.changeIndex,
+ message: `document version ${operation.documentVersion} does not match ${observed} for ${operation.path}`
+ };
+ }
+ if (current !== undefined)
+ versions.set(operation.path, current + 1);
+ continue;
+ }
+ if (operation.kind === "rename") {
+ const moved = [...versions].filter(([path]) => isSameOrDescendant(path, operation.oldPath));
+ for (const [path] of moved)
+ versions.delete(path);
+ for (const [path] of moved)
+ versions.set(movedPath(path, operation.oldPath, operation.newPath), 1);
+ continue;
+ }
+ if (operation.kind === "delete") {
+ for (const path of [...versions.keys()]) {
+ if (isSameOrDescendant(path, operation.path))
+ versions.delete(path);
}
+ continue;
+ }
+ if (operation.kind === "create" && operation.replaced && versions.has(operation.path)) {
+ versions.set(operation.path, 1);
+ }
+ }
+ return null;
+ }
+ async synchronize(delta) {
+ const watched = [];
+ for (const mutation of delta.operations)
+ await this.synchronizeMutation(mutation, watched);
+ for (let index = 0;index < watched.length; index += WATCHED_FILE_BATCH_SIZE) {
+ await this.sendNotification("workspace/didChangeWatchedFiles", {
+ changes: watched.slice(index, index + WATCHED_FILE_BATCH_SIZE)
});
- this.openedFiles.add(absPath);
- this.documentVersions.set(uri, version);
- this.lastSyncedText.set(uri, text);
- await new Promise((r) => setTimeout(r, POST_OPEN_DELAY_MS));
+ }
+ }
+ async synchronizeMutation(mutation, watched) {
+ if (mutation.kind === "text") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state)
+ await this.changeDocument(state, mutation.afterText);
+ else
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 2 });
return;
}
- const prevText = this.lastSyncedText.get(uri);
- if (prevText === text) {
+ if (mutation.kind === "create") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state) {
+ await this.closeDocument(state);
+ await this.openDocumentSingleFlight(mutation.path, readFileSync(mutation.path, "utf-8"));
+ } else {
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: mutation.replaced ? 2 : 1 });
+ }
return;
}
- const nextVersion = (this.documentVersions.get(uri) ?? 1) + 1;
- this.documentVersions.set(uri, nextVersion);
- this.lastSyncedText.set(uri, text);
+ if (mutation.kind === "rename") {
+ const moved = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.oldPath));
+ for (const state of moved)
+ await this.closeDocument(state);
+ for (const state of moved) {
+ const path = movedPath(state.path, mutation.oldPath, mutation.newPath);
+ await this.openDocumentSingleFlight(path, readFileSync(path, "utf-8"));
+ }
+ if (moved.length === 0) {
+ watched.push({ uri: pathToFileURL2(mutation.oldPath).href, type: 3 });
+ watched.push({ uri: pathToFileURL2(mutation.newPath).href, type: 1 });
+ }
+ return;
+ }
+ const removed = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.path));
+ for (const state of removed)
+ await this.closeDocument(state);
+ if (removed.length === 0)
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 3 });
+ }
+ async openDocumentSingleFlight(path, text) {
+ const existing = this.openPromises.get(path);
+ if (existing)
+ return existing;
+ const open = (async () => {
+ const state = {
+ path,
+ uri: pathToFileURL2(path).href,
+ languageId: getLanguageId(effectiveExtension(path)),
+ text,
+ version: 1,
+ generation: 1,
+ publishGeneration: 0,
+ waiters: new Set
+ };
+ this.openDocuments.set(path, state);
+ this.openByUri.set(state.uri, state);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didOpen", {
+ textDocument: { uri: state.uri, languageId: state.languageId, version: state.version, text }
+ });
+ })().finally(() => {
+ this.openPromises.delete(path);
+ });
+ this.openPromises.set(path, open);
+ return open;
+ }
+ async changeDocument(state, text) {
+ state.text = text;
+ state.version += 1;
+ state.generation += 1;
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
await this.sendNotification("textDocument/didChange", {
- textDocument: { uri, version: nextVersion },
+ textDocument: { uri: state.uri, version: state.version },
contentChanges: [{ text }]
});
- await this.sendNotification("textDocument/didSave", {
- textDocument: { uri },
- text
+ await this.sendNotification("textDocument/didSave", { textDocument: { uri: state.uri }, text });
+ }
+ async closeDocument(state) {
+ this.openDocuments.delete(state.path);
+ this.openByUri.delete(state.uri);
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didClose", { textDocument: { uri: state.uri } });
+ }
+ notifyWaiters(state) {
+ for (const waiter of [...state.waiters])
+ waiter();
+ }
+}
+
+// ../lsp-core/src/lsp/workspace-apply-edit-failure.ts
+var CONCURRENT_FAILURE_REASON_BY_PHASE = {
+ applying: "workspace/applyEdit is already in progress for this workspace mutation",
+ settled: "workspace/applyEdit was already handled for this workspace mutation"
+};
+function workspaceApplyEditConcurrentFailureReason(phase) {
+ return CONCURRENT_FAILURE_REASON_BY_PHASE[phase];
+}
+
+// ../lsp-core/src/lsp/workspace-edit-commit.ts
+import { existsSync as existsSync3, lstatSync as lstatSync2, renameSync, rmSync, writeFileSync } from "node:fs";
+
+// ../lsp-core/src/lsp/workspace-edit-path.ts
+import { existsSync as existsSync2, lstatSync, readFileSync as readFileSync2, readdirSync, realpathSync as realpathSync2 } from "node:fs";
+import { dirname, isAbsolute, relative as relative2, resolve as resolve2 } from "node:path";
+import { fileURLToPath } from "node:url";
+
+class WorkspaceEditPathError extends Error {
+ path;
+ detail;
+ name = "WorkspaceEditPathError";
+ constructor(path, detail) {
+ super(`${detail}: ${path}`);
+ this.path = path;
+ this.detail = detail;
+ }
+}
+function isPathInsideWorkspace(filePath, workspaceRoot) {
+ const relativePath = relative2(workspaceRoot, filePath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute(relativePath);
+}
+function canonicalizeMissingPath(filePath) {
+ let ancestor = filePath;
+ while (!existsSync2(ancestor)) {
+ const parent = dirname(ancestor);
+ if (parent === ancestor)
+ throw new WorkspaceEditPathError(filePath, "no existing ancestor");
+ ancestor = parent;
+ }
+ return resolve2(realpathSync2(ancestor), relative2(ancestor, filePath));
+}
+function canonicalWorkspaceRoot(workspaceRoot) {
+ try {
+ const canonical = realpathSync2(resolve2(workspaceRoot));
+ if (!lstatSync(canonical).isDirectory()) {
+ return { success: false, error: `workspace root is not a directory: ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath: resolve2(workspaceRoot),
+ followedSymbolicLink: existsSync2(resolve2(workspaceRoot)) && lstatSync(resolve2(workspaceRoot)).isSymbolicLink()
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `workspace root ${workspaceRoot}: ${detail}` };
+ }
+}
+function uriToCanonicalWorkspacePath(uri, workspaceRoot) {
+ let requestedPath;
+ try {
+ const parsed = new URL(uri);
+ if (parsed.protocol !== "file:" || parsed.search !== "" || parsed.hash !== "") {
+ return { success: false, error: `non-file URI ${uri}` };
+ }
+ requestedPath = resolve2(fileURLToPath(parsed));
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `non-file URI ${uri}: ${detail}` };
+ }
+ try {
+ const canonical = existsSync2(requestedPath) ? realpathSync2(requestedPath) : canonicalizeMissingPath(requestedPath);
+ if (!isPathInsideWorkspace(canonical, workspaceRoot)) {
+ return { success: false, error: `${requestedPath}: outside workspace ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath,
+ followedSymbolicLink: existsSync2(requestedPath) && lstatSync(requestedPath).isSymbolicLink()
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `${requestedPath}: ${detail}` };
+ }
+}
+function snapshotPath(path, includeChildren) {
+ if (!existsSync2(path))
+ return { kind: "missing" };
+ const stats = lstatSync(path);
+ if (stats.isFile())
+ return { kind: "file", content: readFileSync2(path, "utf-8") };
+ if (stats.isDirectory()) {
+ return includeChildren ? { kind: "directory", children: readdirSync(path).sort() } : { kind: "directory" };
+ }
+ throw new WorkspaceEditPathError(path, "unsupported filesystem entry");
+}
+
+// ../lsp-core/src/lsp/workspace-edit-commit.ts
+var DEFAULT_IO = {
+ writeFile(path, content) {
+ writeFileSync(path, content, "utf-8");
+ },
+ rename(oldPath, newPath) {
+ renameSync(oldPath, newPath);
+ },
+ remove(path, recursive) {
+ rmSync(path, { recursive, force: false });
+ }
+};
+function snapshotsEqual(expected, actual) {
+ if (expected.kind !== actual.kind)
+ return false;
+ if (expected.kind === "file" && actual.kind === "file")
+ return expected.content === actual.content;
+ if (expected.kind === "directory" && actual.kind === "directory" && expected.children !== undefined) {
+ return JSON.stringify(expected.children) === JSON.stringify(actual.children);
+ }
+ return true;
+}
+function liveSnapshot(path, expected) {
+ return snapshotPath(path, expected.kind === "directory" && expected.children !== undefined);
+}
+function firstOperationIndex(plan) {
+ return plan.operations[0]?.changeIndex ?? 0;
+}
+function failedCommit(plan, failure) {
+ const { message, changeIndex, mutations = [], filesModified = [], totalEdits = 0, lateAbort = false } = failure;
+ return {
+ result: {
+ success: false,
+ filesModified,
+ totalEdits,
+ errors: [`change ${changeIndex}: ${message}`],
+ failedChange: changeIndex,
+ ...lateAbort ? { lateAbort: true } : {}
+ },
+ delta: mutationDelta(mutations),
+ fingerprint: plan.fingerprint
+ };
+}
+function verifySnapshots(plan) {
+ for (const [path, expected] of plan.snapshots) {
+ let actual;
+ try {
+ actual = liveSnapshot(path, expected);
+ } catch (error) {
+ const changeIndex = plan.firstChangeByPath.get(path) ?? firstOperationIndex(plan);
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, { message: `cannot verify snapshot for ${path}: ${detail}`, changeIndex });
+ }
+ if (!snapshotsEqual(expected, actual)) {
+ const changeIndex = plan.firstChangeByPath.get(path) ?? firstOperationIndex(plan);
+ return failedCommit(plan, { message: `workspace state changed before commit: ${path}`, changeIndex });
+ }
+ }
+ return null;
+}
+function addModifiedPath(paths, path) {
+ if (!paths.includes(path))
+ paths.push(path);
+}
+function reportedPath(plan, path) {
+ return plan.reportedPathByCanonical.get(path) ?? path;
+}
+function changedPathsForMutation(mutation) {
+ return mutation.kind === "rename" ? [mutation.oldPath, mutation.newPath] : [mutation.path];
+}
+function mutationDelta(operations) {
+ const changedPaths = new Set;
+ for (const operation of operations) {
+ for (const path of changedPathsForMutation(operation))
+ changedPaths.add(path);
+ }
+ return { operations, changedPaths: [...changedPaths].sort() };
+}
+function resolveIo(overrides) {
+ return {
+ writeFile: overrides?.writeFile ?? DEFAULT_IO.writeFile,
+ rename: overrides?.rename ?? DEFAULT_IO.rename,
+ remove: overrides?.remove ?? DEFAULT_IO.remove
+ };
+}
+function commitOperation(context, operation) {
+ const { plan, io, accumulator } = context;
+ if (operation.kind === "noop")
+ return;
+ if (operation.kind === "text") {
+ io.writeFile(operation.path, operation.afterText);
+ accumulator.mutations.push({
+ kind: "text",
+ path: operation.path,
+ beforeText: operation.beforeText,
+ afterText: operation.afterText
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ accumulator.totalEdits += operation.editCount;
+ return;
+ }
+ if (operation.kind === "create") {
+ io.writeFile(operation.path, "");
+ accumulator.mutations.push({ kind: "create", path: operation.path, replaced: operation.replaced });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ return;
+ }
+ if (operation.kind === "rename") {
+ if (operation.replaceDestination) {
+ const targetKind = existsSync3(operation.newPath) && lstatSync2(operation.newPath).isDirectory() ? "directory" : "file";
+ io.remove(operation.newPath, targetKind === "directory");
+ accumulator.mutations.push({ kind: "delete", path: operation.newPath, targetKind });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ }
+ io.rename(operation.oldPath, operation.newPath);
+ accumulator.mutations.push({
+ kind: "rename",
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: operation.sourceKind
});
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ return;
+ }
+ io.remove(operation.path, operation.recursive);
+ accumulator.mutations.push({
+ kind: "delete",
+ path: operation.path,
+ targetKind: operation.targetKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+}
+function commitWorkspaceEditPlan(plan, options = {}) {
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const stale = verifySnapshots(plan);
+ if (stale)
+ return stale;
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const io = resolveIo(options.io);
+ const accumulator = { mutations: [], filesModified: [], totalEdits: 0 };
+ const context = { plan, io, accumulator };
+ let lateAbort = false;
+ for (const operation of plan.operations) {
+ try {
+ commitOperation(context, operation);
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, {
+ message: `I/O failure during ${operation.kind}: ${detail}`,
+ changeIndex: operation.changeIndex,
+ mutations: accumulator.mutations,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ lateAbort: lateAbort || options.signal?.aborted === true
+ });
+ }
+ if (options.signal?.aborted)
+ lateAbort = true;
+ }
+ const result = {
+ success: true,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ errors: [],
+ ...lateAbort ? { lateAbort: true } : {}
+ };
+ return { result, delta: mutationDelta(accumulator.mutations), fingerprint: plan.fingerprint };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-fingerprint.ts
+import { createHash } from "node:crypto";
+function canonicalFingerprint(operations) {
+ const canonical = operations.map((operation) => {
+ switch (operation.kind) {
+ case "text":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ edits: operation.edits,
+ version: operation.version
+ };
+ case "rename":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "create":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "delete":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ recursive: operation.recursive,
+ ignoreIfNotExists: operation.ignoreIfNotExists
+ };
+ }
+ });
+ return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
+}
+
+// ../lsp-core/src/lsp/workspace-edit-types.ts
+class WorkspaceEditValidationError extends Error {
+ changeIndex;
+ detail;
+ name = "WorkspaceEditValidationError";
+ constructor(changeIndex, detail) {
+ super(`change ${changeIndex}: ${detail}`);
+ this.changeIndex = changeIndex;
+ this.detail = detail;
}
- async definition(filePath, line, character) {
- const absPath = resolve(contextCwd(), filePath);
+}
+
+// ../lsp-core/src/lsp/workspace-edit-parse-helpers.ts
+function isRecord2(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function parsePosition(value) {
+ if (!isRecord2(value) || typeof value["line"] !== "number" || typeof value["character"] !== "number") {
+ return null;
+ }
+ return { line: value["line"], character: value["character"] };
+}
+function parseRange(value) {
+ if (!isRecord2(value))
+ return null;
+ const start = parsePosition(value["start"]);
+ const end = parsePosition(value["end"]);
+ return start && end ? { start, end } : null;
+}
+function parseTextEdits(value, changeIndex) {
+ if (!Array.isArray(value)) {
+ throw new WorkspaceEditValidationError(changeIndex, "text edits must be an array");
+ }
+ const edits = [];
+ for (const candidate of value) {
+ if (!isRecord2(candidate) || typeof candidate["newText"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "text edit requires range and newText");
+ }
+ if ("annotationId" in candidate) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated text edits are unsupported");
+ }
+ const range = parseRange(candidate["range"]);
+ if (!range)
+ throw new WorkspaceEditValidationError(changeIndex, "text edit range is malformed");
+ edits.push({ range, newText: candidate["newText"] });
+ }
+ return edits;
+}
+function parseBooleanOption(options, key, changeIndex) {
+ const value = options[key];
+ if (value === undefined)
+ return false;
+ if (typeof value !== "boolean") {
+ throw new WorkspaceEditValidationError(changeIndex, `${key} must be boolean`);
+ }
+ return value;
+}
+function parseOptions(value, allowed, changeIndex) {
+ if (value === undefined)
+ return {};
+ if (!isRecord2(value))
+ throw new WorkspaceEditValidationError(changeIndex, "resource options must be an object");
+ for (const key of Object.keys(value)) {
+ if (!allowed.includes(key))
+ throw new WorkspaceEditValidationError(changeIndex, `unsupported resource option ${key}`);
+ }
+ const parsed = {};
+ for (const key of allowed)
+ parsed[key] = parseBooleanOption(value, key, changeIndex);
+ return parsed;
+}
+
+// ../lsp-core/src/lsp/workspace-edit-resource-parser.ts
+function parseResourceChange(input) {
+ const kind = input.change["kind"];
+ if (kind === "create" || kind === "delete") {
+ parseSinglePathResource(input, kind);
+ return;
+ }
+ if (kind !== "rename") {
+ throw new WorkspaceEditValidationError(input.changeIndex, `unsupported resource operation ${String(kind)}`);
+ }
+ parseRename(input);
+}
+function parseSinglePathResource(input, kind) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["uri"] !== "string")
+ throw new WorkspaceEditValidationError(changeIndex, `${kind}.uri is required`);
+ const resolvedPath = uriToCanonicalWorkspacePath(change["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ if (kind === "create") {
+ const options2 = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ overwrite: options2["overwrite"] ?? false,
+ ignoreIfExists: options2["ignoreIfExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["recursive", "ignoreIfNotExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ recursive: options["recursive"] ?? false,
+ ignoreIfNotExists: options["ignoreIfNotExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+}
+function parseRename(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["oldUri"] !== "string" || typeof change["newUri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "rename requires oldUri and newUri");
+ }
+ const oldPath = uriToCanonicalWorkspacePath(change["oldUri"], workspaceRoot);
+ const newPath = uriToCanonicalWorkspacePath(change["newUri"], workspaceRoot);
+ if (!oldPath.success || !newPath.success) {
+ target.failures.push({
+ changeIndex,
+ message: !oldPath.success ? oldPath.error : !newPath.success ? newPath.error : "invalid rename path"
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind: "rename",
+ changeIndex,
+ oldPath: oldPath.path,
+ newPath: newPath.path,
+ reportedOldPath: oldPath.requestedPath,
+ reportedNewPath: newPath.requestedPath,
+ overwrite: options["overwrite"] ?? false,
+ ignoreIfExists: options["ignoreIfExists"] ?? false,
+ followedSymbolicLink: oldPath.followedSymbolicLink || newPath.followedSymbolicLink
+ });
+}
+
+// ../lsp-core/src/lsp/workspace-edit-parser.ts
+function failureResult(failures) {
+ const sorted = [...failures].sort((left, right) => left.changeIndex - right.changeIndex);
+ const first = sorted[0];
+ return {
+ success: false,
+ filesModified: [],
+ totalEdits: 0,
+ errors: sorted.map((failure) => `change ${failure.changeIndex}: ${failure.message}`),
+ ...first ? { failedChange: first.changeIndex } : {}
+ };
+}
+function parseWorkspaceEdit(edit, workspaceRoot) {
+ if (!isRecord2(edit))
+ return { operations: [], failures: [{ changeIndex: 0, message: "No edit provided" }] };
+ if (edit["changeAnnotations"] !== undefined) {
+ return { operations: [], failures: [{ changeIndex: 0, message: "change annotations are unsupported" }] };
+ }
+ const hasChanges = edit["changes"] !== undefined;
+ const hasDocumentChanges = edit["documentChanges"] !== undefined;
+ if (hasChanges && hasDocumentChanges) {
+ return {
+ operations: [],
+ failures: [{ changeIndex: 0, message: "changes and documentChanges cannot be combined" }]
+ };
+ }
+ const target = { operations: [], failures: [] };
+ if (hasChanges)
+ return parseChanges(edit["changes"], workspaceRoot, target);
+ return parseDocumentChanges(edit["documentChanges"], workspaceRoot, target);
+}
+function parseChanges(value, workspaceRoot, target) {
+ if (!isRecord2(value))
+ return { ...target, failures: [{ changeIndex: 0, message: "changes must be an object" }] };
+ const entries = Object.entries(value).sort(([left], [right]) => left.localeCompare(right));
+ for (const [changeIndex, [uri, rawEdits]] of entries.entries()) {
+ const resolvedPath = uriToCanonicalWorkspacePath(uri, workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ continue;
+ }
+ try {
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(rawEdits, changeIndex),
+ version: null
+ });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChanges(value, workspaceRoot, target) {
+ if (value === undefined)
+ return target;
+ if (!Array.isArray(value)) {
+ return { ...target, failures: [{ changeIndex: 0, message: "documentChanges must be an array" }] };
+ }
+ for (const [changeIndex, change] of value.entries()) {
+ try {
+ parseDocumentChange({ change, changeIndex, workspaceRoot, target });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChange(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (!isRecord2(change))
+ throw new WorkspaceEditValidationError(changeIndex, "document change must be an object");
+ if ("annotationId" in change) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated resource operations are unsupported");
+ }
+ if (typeof change["kind"] === "string") {
+ parseResourceChange({ change, changeIndex, workspaceRoot, target });
+ return;
+ }
+ const identifier = change["textDocument"];
+ if (!isRecord2(identifier) || typeof identifier["uri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "textDocument.uri is required");
+ }
+ const version = identifier["version"];
+ if (version !== null && (!Number.isInteger(version) || typeof version !== "number" || version < 0)) {
+ throw new WorkspaceEditValidationError(changeIndex, "document version must be null or a non-negative integer");
+ }
+ const resolvedPath = uriToCanonicalWorkspacePath(identifier["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(change["edits"], changeIndex),
+ version
+ });
+}
+
+// ../lsp-core/src/lsp/workspace-edit-simulation.ts
+import { dirname as dirname2, relative as relative3, resolve as resolve3 } from "node:path";
+
+// ../lsp-core/src/lsp/workspace-edit-text.ts
+function comparePosition(left, right) {
+ return left.line === right.line ? left.character - right.character : left.line - right.line;
+}
+function positionsEqual(left, right) {
+ return left.line === right.line && left.character === right.character;
+}
+function rangesEqual(left, right) {
+ return positionsEqual(left.start, right.start) && positionsEqual(left.end, right.end);
+}
+function isEmptyRange(range) {
+ return positionsEqual(range.start, range.end);
+}
+function formatRange(range) {
+ return `${range.start.line + 1}:${range.start.character + 1}-${range.end.line + 1}:${range.end.character + 1}`;
+}
+function validatePosition(position, label, context) {
+ const { lines, changeIndex } = context;
+ if (!Number.isInteger(position.line) || !Number.isInteger(position.character)) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position must use integer line and character`);
+ }
+ if (position.line < 0 || position.character < 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position cannot be negative`);
+ }
+ const line = lines[position.line];
+ if (line === undefined) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} line ${position.line} is outside the document`);
+ }
+ if (position.character > line.length) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} character ${position.character} is outside line ${position.line}`);
+ }
+}
+function validateRange(range, lines, changeIndex) {
+ const context = { lines, changeIndex };
+ validatePosition(range.start, "start", context);
+ validatePosition(range.end, "end", context);
+ if (comparePosition(range.start, range.end) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `range ${formatRange(range)} ends before it starts`);
+ }
+}
+function sortAndDeduplicate(edits) {
+ const sorted = edits.map((edit, index) => ({ edit, index })).sort((left, right) => {
+ const positionOrder = comparePosition(right.edit.range.start, left.edit.range.start);
+ return positionOrder === 0 ? right.index - left.index : positionOrder;
+ });
+ const unique = [];
+ for (const entry of sorted) {
+ const previous = unique.at(-1);
+ if (previous !== undefined && !isEmptyRange(entry.edit.range) && rangesEqual(previous.range, entry.edit.range) && previous.newText === entry.edit.newText) {
+ continue;
+ }
+ unique.push(entry.edit);
+ }
+ return unique;
+}
+function validateNoOverlap(edits, changeIndex) {
+ for (let index = 0;index < edits.length - 1; index += 1) {
+ const later = edits[index];
+ const earlier = edits[index + 1];
+ if (later === undefined || earlier === undefined)
+ continue;
+ if (comparePosition(earlier.range.end, later.range.start) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `overlapping edits ${formatRange(earlier.range)} and ${formatRange(later.range)}`);
+ }
+ }
+}
+function applyNormalizedTextEdits(content, edits) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ const { start, end } = edit.range;
+ const startLine = lines[start.line];
+ const endLine = lines[end.line];
+ if (startLine === undefined || endLine === undefined)
+ continue;
+ const replacement = startLine.slice(0, start.character) + edit.newText + endLine.slice(end.character);
+ lines.splice(start.line, end.line - start.line + 1, ...replacement.split(`
+`));
+ }
+ return lines.join(`
+`);
+}
+function normalizeTextEdits(content, edits, changeIndex) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ validateRange(edit.range, lines, changeIndex);
+ }
+ const normalized = sortAndDeduplicate(edits);
+ validateNoOverlap(normalized, changeIndex);
+ return { edits: normalized, text: applyNormalizedTextEdits(content, normalized) };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-simulation.ts
+function isSameOrDescendant2(candidate, parent) {
+ const relativePath = relative3(parent, candidate);
+ return relativePath === "" || !relativePath.startsWith("..") && relativePath !== "..";
+}
+function removeVirtualSubtree(virtual, path) {
+ for (const candidate of [...virtual.keys()]) {
+ if (isSameOrDescendant2(candidate, path))
+ virtual.delete(candidate);
+ }
+ virtual.set(path, { kind: "missing" });
+}
+function moveVirtualSubtree(virtual, oldPath, newPath) {
+ const moved = [...virtual.entries()].filter(([candidate]) => isSameOrDescendant2(candidate, oldPath));
+ removeVirtualSubtree(virtual, oldPath);
+ removeVirtualSubtree(virtual, newPath);
+ for (const [candidate, entry] of moved) {
+ const suffix = relative3(oldPath, candidate);
+ virtual.set(suffix === "" ? newPath : resolve3(newPath, suffix), entry);
+ }
+}
+function virtualDirectoryHasChildren(virtual, path) {
+ for (const [candidate, entry] of virtual) {
+ if (candidate !== path && entry.kind !== "missing" && isSameOrDescendant2(candidate, path))
+ return true;
+ }
+ return false;
+}
+function requireVirtualParent(virtual, path, changeIndex) {
+ if (virtual.get(dirname2(path))?.kind !== "directory") {
+ throw new WorkspaceEditValidationError(changeIndex, `parent directory does not exist for ${path}`);
+ }
+}
+function simulateOperations(parsed, snapshots) {
+ const virtual = new Map(snapshots);
+ const planned = [];
+ const failures = [];
+ for (const operation of parsed) {
+ try {
+ planned.push(simulateOperation(operation, virtual));
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ failures.push({ changeIndex: operation.changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return { operations: planned, failures };
+}
+function simulateOperation(operation, virtual) {
+ switch (operation.kind) {
+ case "text":
+ return simulateText(operation, virtual);
+ case "create":
+ return simulateCreate(operation, virtual);
+ case "rename":
+ return simulateRename(operation, virtual);
+ case "delete":
+ return simulateDelete(operation, virtual);
+ }
+}
+function rejectSymbolicLink(operation) {
+ if (operation.followedSymbolicLink) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "resource operations through symbolic links are unsupported");
+ }
+}
+function simulateText(operation, virtual) {
+ const entry = virtual.get(operation.path);
+ if (entry?.kind !== "file")
+ throw new WorkspaceEditValidationError(operation.changeIndex, `${operation.path} is not a file`);
+ const normalized = normalizeTextEdits(entry.content, operation.edits, operation.changeIndex);
+ virtual.set(operation.path, { kind: "file", content: normalized.text });
+ return {
+ kind: "text",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ beforeText: entry.content,
+ afterText: normalized.text,
+ editCount: normalized.edits.length,
+ documentVersion: operation.version
+ };
+}
+function simulateCreate(operation, virtual) {
+ rejectSymbolicLink(operation);
+ requireVirtualParent(virtual, operation.path, operation.changeIndex);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind !== "missing") {
+ if (operation.overwrite && target.kind === "file") {
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: true };
+ }
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `create target already exists: ${operation.path}`);
+ }
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: false };
+}
+function simulateRename(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const source = virtual.get(operation.oldPath) ?? { kind: "missing" };
+ if (source.kind === "missing") {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename source does not exist: ${operation.oldPath}`);
+ }
+ if (operation.oldPath === operation.newPath)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ if (isSameOrDescendant2(operation.newPath, operation.oldPath)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "cannot rename a path into its own subtree");
+ }
+ requireVirtualParent(virtual, operation.newPath, operation.changeIndex);
+ const destination = virtual.get(operation.newPath) ?? { kind: "missing" };
+ if (destination.kind !== "missing" && !operation.overwrite) {
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename target already exists: ${operation.newPath}`);
+ }
+ moveVirtualSubtree(virtual, operation.oldPath, operation.newPath);
+ return {
+ kind: "rename",
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: source.kind,
+ replaceDestination: destination.kind !== "missing"
+ };
+}
+function simulateDelete(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind === "missing") {
+ if (operation.ignoreIfNotExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `delete target does not exist: ${operation.path}`);
+ }
+ if (target.kind === "directory" && !operation.recursive && virtualDirectoryHasChildren(virtual, operation.path)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `directory is not empty: ${operation.path}`);
+ }
+ removeVirtualSubtree(virtual, operation.path);
+ return {
+ kind: "delete",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ targetKind: target.kind,
+ recursive: operation.recursive
+ };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-snapshot.ts
+import { existsSync as existsSync4, lstatSync as lstatSync3, readdirSync as readdirSync2 } from "node:fs";
+import { dirname as dirname3, resolve as resolve4 } from "node:path";
+class WorkspaceSnapshotBuilder {
+ workspaceRoot;
+ snapshots = new Map;
+ constructor(workspaceRoot) {
+ this.workspaceRoot = workspaceRoot;
+ }
+ build(operations) {
+ this.add(this.workspaceRoot, false);
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, true);
+ this.add(operation.newPath, true);
+ break;
+ case "delete":
+ this.add(operation.path, true);
+ break;
+ case "text":
+ case "create":
+ this.add(operation.path, false);
+ break;
+ }
+ }
+ return this.snapshots;
+ }
+ add(path, includeChildren) {
+ let candidate = path;
+ while (true) {
+ const existing = this.snapshots.get(candidate);
+ if (existing === undefined || includeChildren && existing.kind === "directory" && existing.children === undefined) {
+ this.snapshots.set(candidate, snapshotPath(candidate, includeChildren && candidate === path));
+ }
+ if (candidate === this.workspaceRoot)
+ break;
+ candidate = dirname3(candidate);
+ }
+ if (!includeChildren || !existsSync4(path) || !lstatSync3(path).isDirectory())
+ return;
+ for (const child of readdirSync2(path))
+ this.add(resolve4(path, child), true);
+ }
+}
+function snapshotOperations(operations, workspaceRoot) {
+ return new WorkspaceSnapshotBuilder(workspaceRoot).build(operations);
+}
+
+// ../lsp-core/src/lsp/workspace-edit-plan.ts
+class PlanPathIndex {
+ firstChangeByPath = new Map;
+ reportedPathByCanonical = new Map;
+ build(operations) {
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, operation.reportedOldPath, operation.changeIndex);
+ this.add(operation.newPath, operation.reportedNewPath, operation.changeIndex);
+ break;
+ case "text":
+ case "create":
+ case "delete":
+ this.add(operation.path, operation.reportedPath, operation.changeIndex);
+ break;
+ }
+ }
+ }
+ add(path, reportedPath2, changeIndex) {
+ if (!this.firstChangeByPath.has(path))
+ this.firstChangeByPath.set(path, changeIndex);
+ if (!this.reportedPathByCanonical.has(path))
+ this.reportedPathByCanonical.set(path, reportedPath2);
+ }
+}
+function fingerprintWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ return { success: true, fingerprint: canonicalFingerprint(parsed.operations) };
+}
+function planWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ let snapshots;
+ try {
+ snapshots = snapshotOperations(parsed.operations, root.path);
+ } catch (error) {
+ return {
+ success: false,
+ result: failureResult([{ changeIndex: 0, message: error instanceof Error ? error.message : String(error) }])
+ };
+ }
+ const simulated = simulateOperations(parsed.operations, snapshots);
+ if (simulated.failures.length > 0)
+ return { success: false, result: failureResult(simulated.failures) };
+ const paths = new PlanPathIndex;
+ paths.build(parsed.operations);
+ const plan = {
+ workspaceRoot: root.path,
+ operations: simulated.operations,
+ snapshots,
+ firstChangeByPath: paths.firstChangeByPath,
+ reportedPathByCanonical: paths.reportedPathByCanonical,
+ fingerprint: canonicalFingerprint(parsed.operations)
+ };
+ return { success: true, plan };
+}
+
+// ../lsp-core/src/lsp/workspace-mutation-controller.ts
+function failure(message, failedChange, base) {
+ return {
+ success: false,
+ filesModified: base?.filesModified ?? [],
+ totalEdits: base?.totalEdits ?? 0,
+ errors: [message],
+ ...failedChange === undefined ? {} : { failedChange },
+ ...base?.lateAbort ? { lateAbort: true } : {}
+ };
+}
+function responseFor(result) {
+ if (result.success)
+ return { applied: true };
+ return {
+ applied: false,
+ failureReason: result.errors[0] ?? "workspace edit failed",
+ ...result.failedChange === undefined ? {} : { failedChange: result.failedChange }
+ };
+}
+function isRecord3(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+class WorkspaceMutationController {
+ workspaceRoot;
+ documents;
+ activeLease = null;
+ nextLeaseId = 1;
+ io;
+ constructor(workspaceRoot, documents) {
+ this.workspaceRoot = workspaceRoot;
+ this.documents = documents;
+ }
+ setIo(io) {
+ this.io = io;
+ }
+ acquire(signal) {
+ if (this.activeLease)
+ return { success: false, result: failure("workspace mutation is already in progress") };
+ if (signal?.aborted)
+ return { success: false, result: failure("cancelled before mutating request") };
+ const lease = {
+ id: this.nextLeaseId,
+ phase: "idle",
+ ...signal === undefined ? {} : { signal }
+ };
+ this.nextLeaseId += 1;
+ this.activeLease = lease;
+ return { success: true, lease };
+ }
+ release(lease) {
+ if (this.activeLease?.id !== lease.id)
+ return;
+ this.activeLease.phase = "sealed";
+ this.activeLease = null;
+ }
+ isBeforeCommit(lease) {
+ return this.activeLease?.id === lease.id && this.activeLease.phase === "idle";
+ }
+ async handleApplyEdit(params) {
+ const lease = this.activeLease;
+ if (!lease)
+ return { applied: false, failureReason: "workspace/applyEdit requires an active workspace mutation" };
+ if (lease.phase !== "idle") {
+ return {
+ applied: false,
+ failureReason: workspaceApplyEditConcurrentFailureReason(lease.phase === "applying" ? "applying" : "settled")
+ };
+ }
+ lease.phase = "applying";
+ lease.applyCompletion = new Promise((resolve5) => {
+ lease.resolveApply = resolve5;
+ });
+ const edit = isRecord3(params) ? params["edit"] : undefined;
+ const record = edit === undefined ? { fingerprint: null, result: failure("workspace/applyEdit params.edit is required", 0) } : await this.applyEdit(edit, lease);
+ lease.serverApply = record;
+ lease.phase = "settled";
+ lease.resolveApply?.();
+ return responseFor(record.result);
+ }
+ async reconcileRename(leaseToken, edit) {
+ const lease = this.requireActiveLease(leaseToken);
+ if (!lease)
+ return { edit, apply: failure("workspace mutation lease ended before rename reconciliation") };
+ if (lease.phase === "applying")
+ await lease.applyCompletion;
+ if (lease.serverApply)
+ return this.reconcileServerApply(lease.serverApply, edit);
+ lease.phase = "sealed";
+ if (!edit)
+ return { edit, apply: failure("No edit provided") };
+ const applied = await this.applyEdit(edit, lease);
+ return { edit, apply: applied.result };
+ }
+ reconcileServerApply(record, edit) {
+ if (!edit)
+ return { edit, apply: record.result };
+ const fingerprint = fingerprintWorkspaceEdit(edit, this.workspaceRoot);
+ if (fingerprint.success && record.fingerprint !== null && fingerprint.fingerprint === record.fingerprint) {
+ return { edit, apply: record.result };
+ }
+ return {
+ edit,
+ apply: failure("rename result conflicts with server-applied workspace edit", 0, record.result)
+ };
+ }
+ async applyEdit(edit, lease) {
+ const planned = planWorkspaceEdit(edit, this.workspaceRoot);
+ if (!planned.success)
+ return { fingerprint: null, result: planned.result };
+ const versionFailure = this.documents.validateVersions(planned.plan.operations);
+ if (versionFailure) {
+ return {
+ fingerprint: planned.plan.fingerprint,
+ result: failure(versionFailure.message, versionFailure.changeIndex)
+ };
+ }
+ const commit = commitWorkspaceEditPlan(planned.plan, {
+ ...lease.signal === undefined ? {} : { signal: lease.signal },
+ ...this.io === undefined ? {} : { io: this.io }
+ });
+ let result = commit.result;
+ if (commit.delta.operations.length > 0) {
+ try {
+ await this.documents.synchronize(commit.delta);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ result = failure(`document synchronization failed after filesystem commit: ${message}`, undefined, result);
+ }
+ }
+ if (lease.signal?.aborted && !result.lateAbort)
+ result = { ...result, lateAbort: true };
+ return { fingerprint: planned.plan.fingerprint, result };
+ }
+ requireActiveLease(lease) {
+ return this.activeLease?.id === lease.id ? this.activeLease : null;
+ }
+}
+
+// ../lsp-core/src/lsp/client.ts
+var DIAGNOSTICS_FRESHNESS_TIMEOUT_MS = 3000;
+var VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
+
+class LspClient extends LspClientConnection {
+ diagnosticPullErrors = [];
+ documents;
+ workspaceMutations;
+ diagnosticsFreshnessTimeoutMs;
+ constructor(root, server, options = {}) {
+ super(root, server, options);
+ this.diagnosticsFreshnessTimeoutMs = options.diagnosticsFreshnessTimeoutMs ?? DIAGNOSTICS_FRESHNESS_TIMEOUT_MS;
+ this.documents = new WorkspaceDocumentState((method, params) => this.sendNotification(method, params), (uri) => this.diagnosticsStore.delete(uri), {
+ versionlessPublishQuiescenceMs: options.versionlessPublishQuiescenceMs ?? VERSIONLESS_PUBLISH_QUIESCENCE_MS
+ });
+ this.workspaceMutations = new WorkspaceMutationController(root, this.documents);
+ this.setWorkspaceApplyEditHandler((params) => this.workspaceMutations.handleApplyEdit(params));
+ }
+ getDiagnosticPullErrors() {
+ return this.diagnosticPullErrors;
+ }
+ async openFile(filePath) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.documents.openFile(absPath);
+ }
+ getOpenDocumentVersion(filePath) {
+ return this.documents.getVersion(this.resolveWorkspacePath(filePath));
+ }
+ getStoredDiagnostics(uri) {
+ return [...this.documents.getStoredDiagnostics(uri)];
+ }
+ setWorkspaceEditIo(io) {
+ this.workspaceMutations.setIo(io);
+ }
+ handlePublishDiagnostics(params) {
+ super.handlePublishDiagnostics(params);
+ this.documents.recordPublishedDiagnostics(params);
+ }
+ async definition(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/definition", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character }
- });
+ }, options);
}
- async references(filePath, line, character, includeDeclaration = true) {
- const absPath = resolve(contextCwd(), filePath);
+ async references(filePath, line, character, includeDeclaration = true, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/references", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character },
context: { includeDeclaration }
- });
+ }, options);
}
- async documentSymbols(filePath) {
- const absPath = resolve(contextCwd(), filePath);
+ async documentSymbols(filePath, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/documentSymbol", {
- textDocument: { uri: pathToFileURL2(absPath).href }
- });
+ textDocument: { uri: pathToFileURL3(absPath).href }
+ }, options);
}
- async workspaceSymbols(query) {
- return this.sendRequest("workspace/symbol", { query });
+ async workspaceSymbols(query, signal) {
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("workspace/symbol", { query }, options);
}
isUnsupportedDiagnosticPullError(error) {
if (!(error instanceof Error))
@@ -1075,42 +2537,173 @@ class LspClient extends LspClientConnection {
return true;
return /unsupported|not supported|method not found|unknown request/i.test(error.message);
}
- async diagnostics(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- const uri = pathToFileURL2(absPath).href;
- await this.openFile(absPath);
- await new Promise((r) => setTimeout(r, POST_DIAGNOSTICS_WAIT_MS));
- try {
- const result = await this.sendRequest("textDocument/diagnostic", {
- textDocument: { uri }
- });
- if (result.items) {
- return { items: result.items };
+ freshnessTimeout(absPath) {
+ return {
+ items: [],
+ transientError: {
+ kind: "freshness_timeout",
+ message: `Timed out waiting for fresh diagnostics for ${absPath} within ${this.diagnosticsFreshnessTimeoutMs}ms.`
}
- } catch (error) {
- if (!this.isUnsupportedDiagnosticPullError(error)) {
- this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ };
+ }
+ parseDiagnosticPullReport(value) {
+ if (value.kind === "unchanged") {
+ return {
+ type: "unchanged",
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ return {
+ type: "full",
+ diagnostics: value.items ?? [],
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ async diagnostics(filePath, signal) {
+ signal?.throwIfAborted();
+ const absPath = this.resolveWorkspacePath(filePath);
+ const uri = pathToFileURL3(absPath).href;
+ await this.openFile(absPath);
+ const deadlineAt = Date.now() + this.diagnosticsFreshnessTimeoutMs;
+ for (;; ) {
+ signal?.throwIfAborted();
+ const snapshot = this.documents.captureDiagnosticSnapshot(absPath);
+ if (!snapshot)
+ return this.freshnessTimeout(absPath);
+ const push = this.documents.resolvePushDiagnostics(snapshot);
+ if (push.status === "ready")
+ return { items: [...push.diagnostics] };
+ let pushFallbackOnly = !this.isDiagnosticPullSupported();
+ if (!pushFallbackOnly) {
+ const cached = this.documents.getPullCache(snapshot);
+ try {
+ const remainingMs2 = deadlineAt - Date.now();
+ if (remainingMs2 <= 0)
+ return this.freshnessTimeout(absPath);
+ const result = await this.sendRequest("textDocument/diagnostic", {
+ textDocument: { uri },
+ ...cached?.resultId === undefined ? {} : { previousResultId: cached.resultId }
+ }, { timeoutMs: remainingMs2, ...signal === undefined ? {} : { signal } });
+ if (!this.documents.isCurrentSnapshot(snapshot))
+ continue;
+ const report = this.parseDiagnosticPullReport(result);
+ if (report.type === "full") {
+ this.documents.recordPullDiagnostics(snapshot, {
+ kind: "full",
+ diagnostics: report.diagnostics,
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ });
+ return { items: [...report.diagnostics] };
+ }
+ if (cached !== null && cached.documentVersion === snapshot.version && cached.resultId === report.resultId) {
+ return { items: [...cached.diagnostics] };
+ }
+ } catch (error) {
+ if (this.isUnsupportedDiagnosticPullError(error)) {
+ this.setDiagnosticPullSupported(false);
+ pushFallbackOnly = true;
+ } else if (error instanceof LspRequestTimeoutError) {
+ pushFallbackOnly = true;
+ } else {
+ this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ throw error;
+ }
+ }
}
+ if (!pushFallbackOnly)
+ continue;
+ const remainingMs = deadlineAt - Date.now();
+ if (remainingMs <= 0)
+ return this.freshnessTimeout(absPath);
+ const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;
+ await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);
}
- return { items: this.getStoredDiagnostics(uri) };
}
- async prepareRename(filePath, line, character) {
- const absPath = resolve(contextCwd(), filePath);
+ async prepareRename(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/prepareRename", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character }
- });
+ }, options);
}
- async rename(filePath, line, character, newName) {
- const absPath = resolve(contextCwd(), filePath);
+ async rename(filePath, line, character, newName, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
- return this.sendRequest("textDocument/rename", {
- textDocument: { uri: pathToFileURL2(absPath).href },
- position: { line: line - 1, character },
- newName
- });
+ const acquired = this.workspaceMutations.acquire(signal);
+ if (!acquired.success)
+ return { edit: null, apply: acquired.result };
+ const preCommitSignal = createPreCommitAbortSignal(signal, () => this.workspaceMutations.isBeforeCommit(acquired.lease));
+ try {
+ const renameParams = {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character },
+ newName
+ };
+ const edit = preCommitSignal === undefined ? await this.sendRequest("textDocument/rename", renameParams) : await this.sendRequest("textDocument/rename", renameParams, {
+ signal: preCommitSignal.signal
+ });
+ return await this.workspaceMutations.reconcileRename(acquired.lease, edit);
+ } finally {
+ preCommitSignal?.dispose();
+ this.workspaceMutations.release(acquired.lease);
+ }
}
+ resolveWorkspacePath(filePath) {
+ return resolve5(this.root, filePath);
+ }
+}
+function waitForDiagnosticsActivity(wait, signal) {
+ if (!signal)
+ return wait;
+ if (signal.aborted)
+ return Promise.reject(abortError2(signal));
+ return new Promise((resolve6, reject) => {
+ const onAbort = () => {
+ signal.removeEventListener("abort", onAbort);
+ reject(abortError2(signal));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ wait.then(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve6();
+ }, (error) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(error);
+ });
+ });
+}
+function createPreCommitAbortSignal(source, isBeforeCommit) {
+ if (!source)
+ return;
+ const controller = new AbortController;
+ const onAbort = () => {
+ if (isBeforeCommit() && !controller.signal.aborted)
+ controller.abort(preCommitAbortReason(source));
+ };
+ if (source.aborted)
+ onAbort();
+ else
+ source.addEventListener("abort", onAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => source.removeEventListener("abort", onAbort)
+ };
+}
+function preCommitAbortReason(source) {
+ const reason = source.reason;
+ if (reason instanceof Error && reason.name !== "AbortError")
+ return reason;
+ return new Error("LSP request cancelled before workspace edit commit");
+}
+function abortError2(signal) {
+ const reason = signal.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "operation cancelled");
+ error.name = "AbortError";
+ return error;
}
// ../lsp-core/src/lsp/process-signal-cleanup.ts
@@ -1142,7 +2735,7 @@ async function stopClientBestEffort(client) {
function awaitWithSignal(promise, signal) {
if (!signal)
return promise;
- return new Promise((resolve2, reject) => {
+ return new Promise((resolve6, reject) => {
let settled = false;
const onAbort = () => {
if (settled)
@@ -1160,7 +2753,7 @@ function awaitWithSignal(promise, signal) {
return;
settled = true;
signal.removeEventListener("abort", onAbort);
- resolve2(value);
+ resolve6(value);
}, (err) => {
if (settled)
return;
diff --git a/plugins/omo/components/lsp-tools-mcp/dist/mcp.js b/plugins/omo/components/lsp-tools-mcp/dist/mcp.js
index e08b3506..0b9dc2cc 100644
--- a/plugins/omo/components/lsp-tools-mcp/dist/mcp.js
+++ b/plugins/omo/components/lsp-tools-mcp/dist/mcp.js
@@ -12,9 +12,6 @@ function errorResponse(id, code, message, data) {
function jsonRpcId(value) {
return typeof value === "string" || typeof value === "number" || value === null ? value : null;
}
-function messageFromError(error) {
- return error instanceof Error ? error.message : String(error);
-}
// ../mcp-stdio-core/src/transport.ts
var HEADER_SEPARATOR = Buffer.from(`\r
\r
@@ -201,37 +198,197 @@ function createIdleTimer(idleTimeoutMs, log, onIdleTimeout) {
closed: () => isClosed
};
}
-// ../lsp-core/src/tools/diagnostics.ts
-import { resolve as resolve4 } from "node:path";
-
// ../lsp-core/src/lsp/client-wrapper.ts
-import { existsSync as existsSync5, statSync as statSync2 } from "node:fs";
-import { dirname as dirname2, join as join5, resolve as resolve2 } from "node:path";
+import { existsSync as existsSync9, statSync as statSync3 } from "node:fs";
+import { dirname as dirname6, join as join4, resolve as resolve7 } from "node:path";
// ../lsp-core/src/request-context.ts
import { AsyncLocalStorage } from "node:async_hooks";
+import { existsSync, realpathSync, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from "node:path";
+
+class LspRequestContextParseError extends Error {
+ code;
+ name = "LspRequestContextParseError";
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ }
+}
+
+class LspRequestContextUnavailableError extends Error {
+ name = "LspRequestContextUnavailableError";
+ constructor() {
+ super("LSP request context is required. Standalone MCP startup must install one with runWithRequestContext(createStandaloneMcpRequestContext()).");
+ }
+}
var storage = new AsyncLocalStorage;
+var CONTEXT_FIELDS = new Set(["cwd", "projectConfigPaths", "userConfigPath", "installDecisionsPath", "capabilities"]);
+var CAPABILITY_FIELDS = new Set(["installDecisionTool"]);
function runWithRequestContext(context, fn) {
return storage.run(context, fn);
}
+function lspRequestContext() {
+ const context = storage.getStore();
+ if (!context)
+ throw new LspRequestContextUnavailableError;
+ return context;
+}
function contextCwd() {
- return storage.getStore()?.cwd ?? process.cwd();
+ return lspRequestContext().cwd;
}
function contextEnv(key) {
- const store = storage.getStore();
- if (store?.env)
- return store.env[key];
- return process.env[key];
+ const context = lspRequestContext();
+ if (key === "LSP_TOOLS_MCP_PROJECT_CONFIG")
+ return context.projectConfigPaths.join(delimiter);
+ if (key === "LSP_TOOLS_MCP_USER_CONFIG")
+ return context.userConfigPath;
+ if (key === "LSP_TOOLS_MCP_INSTALL_DECISIONS")
+ return context.installDecisionsPath;
+ return;
+}
+function createStandaloneMcpRequestContext(input = {}) {
+ const env = input.env ?? process.env;
+ const cwd = canonicalCwd(input.cwd ?? process.cwd());
+ const home = input.homeDir ?? homedir();
+ const projectConfigPaths = translateProjectConfigEnv(env["LSP_TOOLS_MCP_PROJECT_CONFIG"], cwd);
+ const userConfigPath = translateHomeConfigEnv(env["LSP_TOOLS_MCP_USER_CONFIG"], home, ".codex/lsp-client.json");
+ const installDecisionsPath = translateHomeConfigEnv(env["LSP_TOOLS_MCP_INSTALL_DECISIONS"], home, ".codex/lsp-install-decisions.json");
+ return parseLspRequestContext({
+ cwd,
+ projectConfigPaths,
+ userConfigPath,
+ installDecisionsPath,
+ capabilities: { installDecisionTool: true }
+ });
+}
+function parseLspRequestContext(value) {
+ if (!isRecord(value)) {
+ throw new LspRequestContextParseError("invalid_context", "LSP request context must be an object.");
+ }
+ rejectUnknownFields(value, CONTEXT_FIELDS, "context");
+ const cwd = stringField(value, "cwd");
+ const projectConfigPaths = stringArrayField(value, "projectConfigPaths");
+ const userConfigPath = stringField(value, "userConfigPath");
+ const installDecisionsPath = stringField(value, "installDecisionsPath");
+ const capabilities = capabilitiesField(value["capabilities"]);
+ const canonical = canonicalCwd(cwd);
+ for (const path of projectConfigPaths) {
+ requireAbsolutePath(path, "projectConfigPaths");
+ const projectPath = canonicalizeExistingOrNearestAncestor(path);
+ if (!isPathInside(canonical, projectPath)) {
+ throw new LspRequestContextParseError("project_config_outside_cwd", `Project LSP config path must be inside cwd: ${path}`);
+ }
+ }
+ requireAbsolutePath(userConfigPath, "userConfigPath");
+ requireAbsolutePath(installDecisionsPath, "installDecisionsPath");
+ return {
+ cwd: canonical,
+ projectConfigPaths: projectConfigPaths.map((path) => canonicalizeExistingOrNearestAncestor(path)),
+ userConfigPath,
+ installDecisionsPath,
+ capabilities
+ };
+}
+function translateProjectConfigEnv(value, cwd) {
+ if (value === undefined || value.length === 0)
+ return [join(cwd, ".codex", "lsp-client.json")];
+ return value.split(delimiter).filter((entry) => entry.length > 0).map((entry) => isAbsolute(entry) ? entry : join(cwd, entry));
+}
+function translateHomeConfigEnv(value, home, fallback) {
+ if (value === undefined || value.length === 0)
+ return join(home, fallback);
+ return isAbsolute(value) ? value : join(home, value);
+}
+function canonicalCwd(cwd) {
+ const resolved = resolve(cwd);
+ if (!existsSync(resolved) || !statSync(resolved).isDirectory()) {
+ throw new LspRequestContextParseError("invalid_cwd", `LSP request cwd must be an existing directory: ${cwd}`);
+ }
+ return realpathSync(resolved);
+}
+function canonicalizeExistingOrNearestAncestor(path) {
+ let current = resolve(path);
+ const suffix = [];
+ while (true) {
+ try {
+ const existing = realpathSync(current);
+ return suffix.length === 0 ? existing : join(existing, ...suffix);
+ } catch (error) {
+ if (!isMissingPathError(error))
+ throw error;
+ const parent = dirname(current);
+ if (parent === current)
+ throw error;
+ suffix.unshift(basename(current));
+ current = parent;
+ }
+ }
+}
+function capabilitiesField(value) {
+ if (!isRecord(value)) {
+ throw new LspRequestContextParseError("invalid_capabilities", "LSP request capabilities must be an object.");
+ }
+ rejectUnknownFields(value, CAPABILITY_FIELDS, "capabilities");
+ const installDecisionTool = value["installDecisionTool"];
+ if (typeof installDecisionTool !== "boolean") {
+ throw new LspRequestContextParseError("invalid_install_decision_capability", "LSP request capabilities.installDecisionTool must be a boolean.");
+ }
+ return { installDecisionTool };
+}
+function stringField(value, field) {
+ const fieldValue = value[field];
+ if (typeof fieldValue !== "string" || fieldValue.length === 0) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string.`);
+ }
+ return fieldValue;
+}
+function stringArrayField(value, field) {
+ const fieldValue = value[field];
+ if (!Array.isArray(fieldValue) || !fieldValue.every((item) => typeof item === "string" && item.length > 0)) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string array.`);
+ }
+ return fieldValue;
+}
+function requireAbsolutePath(path, field) {
+ if (!isAbsolute(path)) {
+ throw new LspRequestContextParseError("relative_path", `LSP request context.${field} must be absolute: ${path}`);
+ }
+}
+function isPathInside(parent, child) {
+ const childPath = resolve(child);
+ const relativePath = relative(parent, childPath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute(relativePath);
+}
+function isMissingPathError(error) {
+ const code = errorCode(error);
+ return code === "ENOENT" || code === "ENOTDIR";
+}
+function rejectUnknownFields(value, allowed, scope) {
+ const unknown = Object.keys(value).filter((key) => !allowed.has(key));
+ if (unknown.length > 0) {
+ throw new LspRequestContextParseError("unknown_field", `Unknown LSP request ${scope} field: ${unknown.join(", ")}`);
+ }
+}
+function isRecord(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function errorCode(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
}
// ../lsp-core/src/lsp/effective-extension.ts
-import { basename, extname } from "node:path";
+import { basename as basename2, extname } from "node:path";
var BASENAME_EXTENSIONS = {
Dockerfile: ".dockerfile",
Containerfile: ".dockerfile"
};
function effectiveExtension(filePath) {
- return BASENAME_EXTENSIONS[basename(filePath)] ?? extname(filePath);
+ return BASENAME_EXTENSIONS[basename2(filePath)] ?? extname(filePath);
}
// ../lsp-core/src/lsp/errors.ts
@@ -281,7 +438,12 @@ class LspInvalidPathError extends Error {
}
class LspServerLookupError extends Error {
+ lookup;
name = "LspServerLookupError";
+ constructor(message, lookup) {
+ super(message);
+ this.lookup = lookup;
+ }
}
class LspServerInitializingError extends Error {
@@ -301,17 +463,18 @@ function isLspDeadConnectionError(err) {
}
// ../lsp-core/src/lsp/cleanup-errors.ts
-function reportBestEffortCleanupError(operation, error) {
- if (process.env["CODEX_LSP_DEBUG_CLEANUP"] !== "1")
- return;
+function writeCleanupError(message) {
+ process.stderr.write(`${message}
+`);
+}
+function reportBestEffortCleanupError(operation, error, logger = writeCleanupError) {
const message = error instanceof Error ? error.message : String(error);
- console.error(`[codex-lsp] ignored ${operation} failure during cleanup: ${message}`);
+ logger(`[lsp] ignored ${operation} failure during cleanup: ${message}`);
}
// ../lsp-core/src/lsp/client.ts
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
-import { pathToFileURL as pathToFileURL2 } from "node:url";
+import { resolve as resolve6 } from "node:path";
+import { pathToFileURL as pathToFileURL3 } from "node:url";
// ../lsp-core/src/lsp/connection.ts
import { pathToFileURL } from "node:url";
@@ -375,28 +538,80 @@ class JsonRpcConnection {
onError(handler) {
this.errorHandlers.push(handler);
}
- async sendRequest(method, params) {
+ async sendRequest(method, params, options = {}) {
if (this.disposed)
throw new Error("JSON-RPC connection is disposed");
const id = this.nextRequestId;
this.nextRequestId += 1;
+ const key = String(id);
const message = params === undefined ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
- const responsePromise = new Promise((resolve, reject) => {
- this.pendingRequests.set(String(id), {
+ let requestWritten = false;
+ let cancelAfterWrite = false;
+ let settled = false;
+ const writeCancel = () => this.writeMessage({ jsonrpc: "2.0", method: "$/cancelRequest", params: { id } });
+ const responsePromise = new Promise((resolve2, reject) => {
+ const cleanup = () => {
+ options.signal?.removeEventListener("abort", onAbort);
+ };
+ const settleCancel = () => {
+ if (settled)
+ return;
+ settled = true;
+ this.pendingRequests.delete(key);
+ cleanup();
+ const rejectCancelled = () => reject(abortError(options.signal));
+ if (!requestWritten) {
+ cancelAfterWrite = true;
+ rejectCancelled();
+ return;
+ }
+ writeCancel().then(rejectCancelled, (error) => {
+ this.emitError(toError(error));
+ rejectCancelled();
+ });
+ };
+ const onAbort = () => settleCancel();
+ this.pendingRequests.set(key, {
resolve(result) {
- resolve(result);
+ settled = true;
+ cleanup();
+ resolve2(result);
+ },
+ reject(error) {
+ settled = true;
+ cleanup();
+ reject(error);
},
- reject
+ cleanup
});
+ if (options.signal?.aborted) {
+ settleCancel();
+ return;
+ }
+ options.signal?.addEventListener("abort", onAbort, { once: true });
});
+ if (settled)
+ return responsePromise;
try {
await this.writeMessage(message);
+ requestWritten = true;
+ if (cancelAfterWrite)
+ await writeCancel();
} catch (error) {
- this.pendingRequests.delete(String(id));
+ if (settled)
+ return responsePromise;
+ const pending = this.pendingRequests.get(key);
+ if (pending) {
+ pending.cleanup();
+ this.pendingRequests.delete(key);
+ }
throw error;
}
return responsePromise;
}
+ pendingRequestCount() {
+ return this.pendingRequests.size;
+ }
async sendNotification(method, params) {
if (this.disposed)
return;
@@ -413,6 +628,7 @@ class JsonRpcConnection {
this.reader.off("error", this.handleStreamError);
this.writer.off("error", this.handleStreamError);
for (const pending of this.pendingRequests.values()) {
+ pending.cleanup();
pending.reject(new Error("JSON-RPC connection disposed"));
}
this.pendingRequests.clear();
@@ -488,6 +704,7 @@ class JsonRpcConnection {
if (!pending)
return;
this.pendingRequests.delete(String(id));
+ pending.cleanup();
if ("error" in message) {
pending.reject(jsonRpcErrorToError(message["error"]));
return;
@@ -501,7 +718,11 @@ class JsonRpcConnection {
try {
handler(params);
} catch (error) {
- this.emitError(toError(error));
+ if (error instanceof Error) {
+ this.emitError(error);
+ return;
+ }
+ this.emitError(new Error(String(error)));
}
}
handleRequest(message) {
@@ -526,13 +747,13 @@ class JsonRpcConnection {
const payload = `Content-Length: ${Buffer.byteLength(body, "utf8")}\r
\r
${body}`;
- return new Promise((resolve, reject) => {
+ return new Promise((resolve2, reject) => {
this.writer.write(payload, (error) => {
if (error) {
reject(error);
return;
}
- resolve();
+ resolve2();
});
});
}
@@ -542,6 +763,14 @@ ${body}`;
}
}
}
+function abortError(signal) {
+ const reason = signal?.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "LSP request cancelled");
+ error.name = "AbortError";
+ return error;
+}
function parseContentLength2(headers) {
for (const line of headers.split(`\r
`)) {
@@ -581,8 +810,8 @@ function toError(error) {
// ../lsp-core/src/lsp/process.ts
import { spawn, spawnSync } from "node:child_process";
-import { existsSync, statSync } from "node:fs";
-import { delimiter, join } from "node:path";
+import { existsSync as existsSync2, statSync as statSync2 } from "node:fs";
+import { delimiter as delimiter2, join as join2 } from "node:path";
function isMissingProcessError(error) {
if (!(error instanceof Error) || !("code" in error))
return false;
@@ -595,10 +824,10 @@ function reportKillError(context, error) {
}
function validateCwd(cwd) {
try {
- if (!existsSync(cwd)) {
+ if (!existsSync2(cwd)) {
return { valid: false, error: `Working directory does not exist: ${cwd}` };
}
- const stats = statSync(cwd);
+ const stats = statSync2(cwd);
if (!stats.isDirectory()) {
return { valid: false, error: `Path is not a directory: ${cwd}` };
}
@@ -611,9 +840,9 @@ function validateCwd(cwd) {
}
}
function wrap(proc) {
- const exitedPromise = new Promise((resolve) => {
- proc.once("close", (code) => resolve(code ?? 0));
- proc.once("error", () => resolve(1));
+ const exitedPromise = new Promise((resolve2) => {
+ proc.once("close", (code) => resolve2(code ?? 0));
+ proc.once("error", () => resolve2(1));
});
if (!proc.stdin || !proc.stdout || !proc.stderr) {
throw new LspProcessSpawnError("Spawned process is missing one of stdin/stdout/stderr pipes");
@@ -667,7 +896,7 @@ function isWindowsShellShim(command) {
return lowerCommand.endsWith(".cmd") || lowerCommand.endsWith(".bat");
}
function splitPath(pathValue, platform) {
- const separator = platform === "win32" ? ";" : delimiter;
+ const separator = platform === "win32" ? ";" : delimiter2;
return pathValue.split(separator).filter(Boolean);
}
function getWindowsPathExtensions(env) {
@@ -682,8 +911,8 @@ function resolveWindowsCommand(command, env) {
const extensions = getWindowsPathExtensions(env);
for (const baseDirectory of baseDirectories) {
for (const extension of extensions) {
- const candidate = baseDirectory ? join(baseDirectory, `${command}${extension}`) : `${command}${extension}`;
- if (existsSync(candidate))
+ const candidate = baseDirectory ? join2(baseDirectory, `${command}${extension}`) : `${command}${extension}`;
+ if (existsSync2(candidate))
return candidate;
}
}
@@ -728,16 +957,16 @@ function spawnProcess(command, options) {
return wrap(proc);
}
-// ../lsp-core/src/lsp/transport.ts
-function isRecord(value) {
+// ../lsp-core/src/lsp/transport-protocol.ts
+function isRecord2(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function parseConfigurationItems(params) {
- if (!isRecord(params) || !Array.isArray(params["items"]))
+ if (!isRecord2(params) || !Array.isArray(params["items"]))
return [];
const items = [];
for (const item of params["items"]) {
- if (!isRecord(item))
+ if (!isRecord2(item))
continue;
const section = item["section"];
items.push(section === undefined || typeof section !== "string" ? {} : { section });
@@ -745,10 +974,35 @@ function parseConfigurationItems(params) {
return items;
}
function parseDiagnosticsParams(params) {
- if (!isRecord(params) || typeof params["uri"] !== "string")
+ if (!isRecord2(params) || typeof params["uri"] !== "string")
return null;
const diagnostics = Array.isArray(params["diagnostics"]) ? params["diagnostics"].filter(isDiagnostic) : [];
- return { uri: params["uri"], diagnostics };
+ const version = typeof params["version"] === "number" ? params["version"] : undefined;
+ return { uri: params["uri"], diagnostics, ...version === undefined ? {} : { version } };
+}
+function createLspSpawnEnv(_root, input) {
+ return { ...input };
+}
+function isDiagnostic(value) {
+ return isRecord2(value) && isRange(value["range"]) && typeof value["message"] === "string";
+}
+function isRange(value) {
+ return isRecord2(value) && isPosition(value["start"]) && isPosition(value["end"]);
+}
+function isPosition(value) {
+ return isRecord2(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+}
+
+// ../lsp-core/src/lsp/transport.ts
+class LspClientNotStartedError extends Error {
+ serverId;
+ root;
+ name = "LspClientNotStartedError";
+ constructor(serverId, root) {
+ super("LSP client not started");
+ this.serverId = serverId;
+ this.root = root;
+ }
}
class LspClientTransport {
@@ -761,6 +1015,8 @@ class LspClientTransport {
diagnosticsStore = new Map;
requestTimeoutMs;
initializeTimeoutMs;
+ workspaceApplyEditHandler = null;
+ diagnosticPullSupported = false;
constructor(root, server2, timeouts = {}) {
this.root = root;
this.server = server2;
@@ -773,6 +1029,21 @@ class LspClientTransport {
command() {
return [...this.server.command];
}
+ setWorkspaceApplyEditHandler(handler) {
+ this.workspaceApplyEditHandler = handler;
+ }
+ hasWorkspaceApplyEditHandler() {
+ return this.workspaceApplyEditHandler !== null;
+ }
+ setDiagnosticPullSupported(supported) {
+ this.diagnosticPullSupported = supported;
+ }
+ isDiagnosticPullSupported() {
+ return this.diagnosticPullSupported;
+ }
+ handlePublishDiagnostics(params) {
+ this.diagnosticsStore.set(params.uri, [...params.diagnostics]);
+ }
async start() {
const env = createLspSpawnEnv(this.root, {
...process.env,
@@ -783,7 +1054,6 @@ class LspClientTransport {
env
});
this.startStderrReading();
- await new Promise((resolve) => setTimeout(resolve, 100));
if (this.proc.exitCode !== null) {
const stderr = this.stderrBuffer.join(`
`);
@@ -793,7 +1063,7 @@ class LspClientTransport {
this.connection.onNotification("textDocument/publishDiagnostics", (params) => {
const diagnosticsParams = parseDiagnosticsParams(params);
if (diagnosticsParams?.uri) {
- this.diagnosticsStore.set(diagnosticsParams.uri, diagnosticsParams.diagnostics);
+ this.handlePublishDiagnostics(diagnosticsParams);
}
});
this.connection.onRequest("workspace/configuration", (params) => {
@@ -806,6 +1076,9 @@ class LspClientTransport {
});
this.connection.onRequest("client/registerCapability", () => null);
this.connection.onRequest("window/workDoneProgress/create", () => null);
+ if (this.workspaceApplyEditHandler) {
+ this.connection.onRequest("workspace/applyEdit", this.workspaceApplyEditHandler);
+ }
this.connection.onClose(() => {
this.processExited = true;
});
@@ -834,30 +1107,25 @@ class LspClientTransport {
}
async sendRequest(method, ...args) {
if (!this.connection)
- throw new Error("LSP client not started");
+ throw new LspClientNotStartedError(this.server.id, this.root);
if (this.processExited || this.proc && this.proc.exitCode !== null) {
const stderrTail = this.stderrBuffer.slice(-10).join(`
`);
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, stderrTail || undefined);
}
- const timeoutMs = args[1]?.timeoutMs ?? this.requestTimeoutMs;
- let timeoutHandle = null;
- const timeoutPromise = new Promise((_, reject) => {
- timeoutHandle = setTimeout(() => {
- const stderrTail = this.stderrBuffer.slice(-5).join(`
+ const options = args[1];
+ const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
+ const timeoutController = new AbortController;
+ const timeoutHandle = setTimeout(() => {
+ const stderrTail = this.stderrBuffer.slice(-5).join(`
`);
- reject(new LspRequestTimeoutError(method, stderrTail || undefined));
- }, timeoutMs);
- });
+ timeoutController.abort(new LspRequestTimeoutError(method, stderrTail || undefined));
+ }, timeoutMs);
+ const combinedSignal = combineAbortSignals(options?.signal, timeoutController.signal);
try {
- const requestPromise = args.length === 0 ? this.connection.sendRequest(method) : this.connection.sendRequest(method, args[0]);
- const result = await Promise.race([requestPromise, timeoutPromise]);
- if (timeoutHandle !== null)
- clearTimeout(timeoutHandle);
+ const result = args.length === 0 ? await this.connection.sendRequest(method, undefined, { signal: combinedSignal.signal }) : await this.connection.sendRequest(method, args[0], { signal: combinedSignal.signal });
return result;
} catch (error) {
- if (timeoutHandle !== null)
- clearTimeout(timeoutHandle);
if (this.processExited || this.proc && this.proc.exitCode !== null) {
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, this.stderrBuffer.slice(-10).join(`
`) || undefined);
@@ -866,6 +1134,9 @@ class LspClientTransport {
throw new LspConnectionClosedError(this.server.id, this.root, error.message);
}
throw error;
+ } finally {
+ clearTimeout(timeoutHandle);
+ combinedSignal.dispose();
}
}
async sendNotification(method, ...args) {
@@ -894,17 +1165,17 @@ class LspClientTransport {
try {
await this.sendRequest("shutdown");
} catch (error) {
- reportBestEffortCleanupError("shutdown request", error);
+ reportBestEffortCleanupError("shutdown request", error instanceof Error ? error : String(error));
}
try {
await this.sendNotification("exit");
} catch (error) {
- reportBestEffortCleanupError("exit notification", error);
+ reportBestEffortCleanupError("exit notification", error instanceof Error ? error : String(error));
}
try {
this.connection.dispose();
} catch (error) {
- reportBestEffortCleanupError("connection dispose", error);
+ reportBestEffortCleanupError("connection dispose", error instanceof Error ? error : String(error));
}
this.connection = null;
}
@@ -915,8 +1186,8 @@ class LspClientTransport {
try {
proc.kill();
let timeoutId;
- const timeoutPromise = new Promise((resolve) => {
- timeoutId = setTimeout(resolve, STOP_HARD_KILL_TIMEOUT_MS);
+ const timeoutPromise = new Promise((resolve2) => {
+ timeoutId = setTimeout(resolve2, STOP_HARD_KILL_TIMEOUT_MS);
});
await Promise.race([
proc.exited.then(() => {
@@ -932,14 +1203,14 @@ class LspClientTransport {
proc.kill("SIGKILL");
await Promise.race([
proc.exited,
- new Promise((resolve) => setTimeout(resolve, STOP_SIGKILL_GRACE_MS))
+ new Promise((resolve2) => setTimeout(resolve2, STOP_SIGKILL_GRACE_MS))
]);
} catch (error) {
- reportBestEffortCleanupError("hard process kill", error);
+ reportBestEffortCleanupError("hard process kill", error instanceof Error ? error : String(error));
}
}
} catch (error) {
- reportBestEffortCleanupError("process stop", error);
+ reportBestEffortCleanupError("process stop", error instanceof Error ? error : String(error));
}
}
this.processExited = true;
@@ -949,26 +1220,45 @@ class LspClientTransport {
return this.diagnosticsStore.get(uri) ?? [];
}
}
-function createLspSpawnEnv(_root, input) {
- return { ...input };
-}
-function isDiagnostic(value) {
- return isRecord(value) && isRange(value["range"]) && typeof value["message"] === "string";
-}
-function isRange(value) {
- return isRecord(value) && isPosition(value["start"]) && isPosition(value["end"]);
-}
-function isPosition(value) {
- return isRecord(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+function combineAbortSignals(primary, secondary) {
+ const controller = new AbortController;
+ const abortFrom = (signal) => {
+ if (!controller.signal.aborted)
+ controller.abort(signal.reason);
+ };
+ const onPrimaryAbort = () => {
+ if (primary)
+ abortFrom(primary);
+ };
+ const onSecondaryAbort = () => abortFrom(secondary);
+ if (primary?.aborted)
+ abortFrom(primary);
+ else
+ primary?.addEventListener("abort", onPrimaryAbort, { once: true });
+ if (secondary.aborted)
+ abortFrom(secondary);
+ else
+ secondary.addEventListener("abort", onSecondaryAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => {
+ primary?.removeEventListener("abort", onPrimaryAbort);
+ secondary.removeEventListener("abort", onSecondaryAbort);
+ }
+ };
}
// ../lsp-core/src/lsp/connection.ts
-var INITIALIZE_SETTLE_MS = 300;
+function supportsDiagnosticPull(capabilities) {
+ if (capabilities === undefined)
+ return false;
+ return Object.hasOwn(capabilities, "diagnosticProvider");
+}
class LspClientConnection extends LspClientTransport {
async initialize() {
const rootUri = pathToFileURL(this.root).href;
- await this.sendRequest("initialize", {
+ const result = await this.sendRequest("initialize", {
processId: process.pid,
rootUri,
rootPath: this.root,
@@ -982,8 +1272,7 @@ class LspClientConnection extends LspClientTransport {
publishDiagnostics: {},
rename: {
prepareSupport: true,
- prepareSupportDefaultBehavior: 1,
- honorsChangeAnnotations: true
+ prepareSupportDefaultBehavior: 1
},
codeAction: {
codeActionLiteralSupport: {
@@ -1012,22 +1301,28 @@ class LspClientConnection extends LspClientTransport {
symbol: {},
workspaceFolders: true,
configuration: true,
- applyEdit: true,
+ ...this.hasWorkspaceApplyEditHandler() ? { applyEdit: true } : {},
workspaceEdit: {
- documentChanges: true
+ documentChanges: true,
+ resourceOperations: ["create", "rename", "delete"]
}
}
},
initializationOptions: this.server.initialization
}, { timeoutMs: this.initializeTimeoutMs });
+ this.setDiagnosticPullSupported(supportsDiagnosticPull(result?.capabilities));
await this.sendNotification("initialized");
await this.sendNotification("workspace/didChangeConfiguration", {
settings: { json: { validate: { enable: true } } }
});
- await new Promise((r) => setTimeout(r, INITIALIZE_SETTLE_MS));
}
}
+// ../lsp-core/src/lsp/workspace-document-state.ts
+import { readFileSync, realpathSync as realpathSync2 } from "node:fs";
+import { relative as relative2, resolve as resolve2 } from "node:path";
+import { pathToFileURL as pathToFileURL2 } from "node:url";
+
// ../lsp-core/src/lsp/language-mappings.ts
var SYMBOL_KIND_MAP = {
1: "File",
@@ -1200,82 +1495,1422 @@ function getLanguageId(ext) {
return EXT_TO_LANG[ext] ?? "plaintext";
}
+// ../lsp-core/src/lsp/workspace-document-state.ts
+var WATCHED_FILE_BATCH_SIZE = 128;
+var DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
+function canonicalPath(filePath) {
+ const absolute = resolve2(filePath);
+ try {
+ return realpathSync2(absolute);
+ } catch {
+ return absolute;
+ }
+}
+function isSameOrDescendant(candidate, parent) {
+ const suffix = relative2(parent, candidate);
+ return suffix === "" || !suffix.startsWith("..") && suffix !== "..";
+}
+function movedPath(candidate, oldPath, newPath) {
+ const suffix = relative2(oldPath, candidate);
+ return suffix === "" ? newPath : resolve2(newPath, suffix);
+}
+
+class WorkspaceDocumentState {
+ sendNotification;
+ clearDiagnostics;
+ openDocuments = new Map;
+ openByUri = new Map;
+ openPromises = new Map;
+ now;
+ versionlessPublishQuiescenceMs;
+ constructor(sendNotification, clearDiagnostics, options = {}) {
+ this.sendNotification = sendNotification;
+ this.clearDiagnostics = clearDiagnostics;
+ this.now = options.now ?? (() => Date.now());
+ this.versionlessPublishQuiescenceMs = options.versionlessPublishQuiescenceMs ?? DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS;
+ }
+ async openFile(filePath) {
+ const path = canonicalPath(filePath);
+ const existingOpen = this.openPromises.get(path);
+ if (existingOpen) {
+ await existingOpen;
+ return this.openFile(path);
+ }
+ const text = readFileSync(path, "utf-8");
+ const existing = this.openDocuments.get(path);
+ if (!existing)
+ return this.openDocumentSingleFlight(path, text);
+ if (existing.text === text)
+ return;
+ await this.changeDocument(existing, text);
+ }
+ getVersion(filePath) {
+ return this.openDocuments.get(canonicalPath(filePath))?.version;
+ }
+ getStoredDiagnostics(uri) {
+ const state = this.openByUri.get(uri);
+ if (!state)
+ return [];
+ return state.lastPublish?.diagnostics ?? state.pullCache?.diagnostics ?? [];
+ }
+ captureDiagnosticSnapshot(filePath) {
+ const state = this.openDocuments.get(canonicalPath(filePath));
+ if (!state)
+ return null;
+ return {
+ path: state.path,
+ uri: state.uri,
+ version: state.version,
+ documentGeneration: state.generation,
+ publishGeneration: state.publishGeneration
+ };
+ }
+ isCurrentSnapshot(snapshot) {
+ const state = this.openDocuments.get(snapshot.path);
+ return state !== undefined && state.uri === snapshot.uri && state.version === snapshot.version && state.generation === snapshot.documentGeneration;
+ }
+ getPullCache(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.pullCache || state.pullCache.documentVersion !== snapshot.version)
+ return null;
+ return state.pullCache;
+ }
+ recordPullDiagnostics(snapshot, report) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state)
+ return;
+ state.pullCache = {
+ documentVersion: snapshot.version,
+ diagnostics: [...report.diagnostics],
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ };
+ }
+ recordPublishedDiagnostics(params) {
+ const state = this.openByUri.get(params.uri);
+ if (!state)
+ return;
+ state.publishGeneration += 1;
+ state.lastPublish = {
+ diagnostics: [...params.diagnostics],
+ publishGeneration: state.publishGeneration,
+ documentGenerationAtArrival: state.generation,
+ arrivedAt: this.now(),
+ ...params.version === undefined ? {} : { version: params.version }
+ };
+ this.notifyWaiters(state);
+ }
+ resolvePushDiagnostics(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.lastPublish)
+ return { status: "missing" };
+ const publish = state.lastPublish;
+ if (publish.version !== undefined) {
+ return publish.version === snapshot.version ? { status: "ready", diagnostics: publish.diagnostics } : { status: "missing" };
+ }
+ if (publish.documentGenerationAtArrival < snapshot.documentGeneration)
+ return { status: "missing" };
+ const readyAt = publish.arrivedAt + this.versionlessPublishQuiescenceMs;
+ const waitMs = Math.max(0, readyAt - this.now());
+ return waitMs === 0 ? { status: "ready", diagnostics: publish.diagnostics } : { status: "wait", waitMs };
+ }
+ waitForDiagnosticsActivity(snapshot, timeoutMs) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state || timeoutMs <= 0)
+ return Promise.resolve();
+ return new Promise((resolveActivity) => {
+ let settled = false;
+ const finish = () => {
+ if (settled)
+ return;
+ settled = true;
+ clearTimeout(timer);
+ state.waiters.delete(finish);
+ resolveActivity();
+ };
+ const timer = setTimeout(finish, timeoutMs);
+ if (typeof timer.unref === "function")
+ timer.unref();
+ state.waiters.add(finish);
+ });
+ }
+ validateVersions(operations) {
+ const versions = new Map([...this.openDocuments].map(([path, state]) => [path, state.version]));
+ for (const operation of operations) {
+ if (operation.kind === "text") {
+ const current = versions.get(operation.path);
+ if (operation.documentVersion !== null && current !== operation.documentVersion) {
+ const observed = current === undefined ? "closed document" : `open document version ${current}`;
+ return {
+ changeIndex: operation.changeIndex,
+ message: `document version ${operation.documentVersion} does not match ${observed} for ${operation.path}`
+ };
+ }
+ if (current !== undefined)
+ versions.set(operation.path, current + 1);
+ continue;
+ }
+ if (operation.kind === "rename") {
+ const moved = [...versions].filter(([path]) => isSameOrDescendant(path, operation.oldPath));
+ for (const [path] of moved)
+ versions.delete(path);
+ for (const [path] of moved)
+ versions.set(movedPath(path, operation.oldPath, operation.newPath), 1);
+ continue;
+ }
+ if (operation.kind === "delete") {
+ for (const path of [...versions.keys()]) {
+ if (isSameOrDescendant(path, operation.path))
+ versions.delete(path);
+ }
+ continue;
+ }
+ if (operation.kind === "create" && operation.replaced && versions.has(operation.path)) {
+ versions.set(operation.path, 1);
+ }
+ }
+ return null;
+ }
+ async synchronize(delta) {
+ const watched = [];
+ for (const mutation of delta.operations)
+ await this.synchronizeMutation(mutation, watched);
+ for (let index = 0;index < watched.length; index += WATCHED_FILE_BATCH_SIZE) {
+ await this.sendNotification("workspace/didChangeWatchedFiles", {
+ changes: watched.slice(index, index + WATCHED_FILE_BATCH_SIZE)
+ });
+ }
+ }
+ async synchronizeMutation(mutation, watched) {
+ if (mutation.kind === "text") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state)
+ await this.changeDocument(state, mutation.afterText);
+ else
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 2 });
+ return;
+ }
+ if (mutation.kind === "create") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state) {
+ await this.closeDocument(state);
+ await this.openDocumentSingleFlight(mutation.path, readFileSync(mutation.path, "utf-8"));
+ } else {
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: mutation.replaced ? 2 : 1 });
+ }
+ return;
+ }
+ if (mutation.kind === "rename") {
+ const moved = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.oldPath));
+ for (const state of moved)
+ await this.closeDocument(state);
+ for (const state of moved) {
+ const path = movedPath(state.path, mutation.oldPath, mutation.newPath);
+ await this.openDocumentSingleFlight(path, readFileSync(path, "utf-8"));
+ }
+ if (moved.length === 0) {
+ watched.push({ uri: pathToFileURL2(mutation.oldPath).href, type: 3 });
+ watched.push({ uri: pathToFileURL2(mutation.newPath).href, type: 1 });
+ }
+ return;
+ }
+ const removed = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.path));
+ for (const state of removed)
+ await this.closeDocument(state);
+ if (removed.length === 0)
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 3 });
+ }
+ async openDocumentSingleFlight(path, text) {
+ const existing = this.openPromises.get(path);
+ if (existing)
+ return existing;
+ const open = (async () => {
+ const state = {
+ path,
+ uri: pathToFileURL2(path).href,
+ languageId: getLanguageId(effectiveExtension(path)),
+ text,
+ version: 1,
+ generation: 1,
+ publishGeneration: 0,
+ waiters: new Set
+ };
+ this.openDocuments.set(path, state);
+ this.openByUri.set(state.uri, state);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didOpen", {
+ textDocument: { uri: state.uri, languageId: state.languageId, version: state.version, text }
+ });
+ })().finally(() => {
+ this.openPromises.delete(path);
+ });
+ this.openPromises.set(path, open);
+ return open;
+ }
+ async changeDocument(state, text) {
+ state.text = text;
+ state.version += 1;
+ state.generation += 1;
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didChange", {
+ textDocument: { uri: state.uri, version: state.version },
+ contentChanges: [{ text }]
+ });
+ await this.sendNotification("textDocument/didSave", { textDocument: { uri: state.uri }, text });
+ }
+ async closeDocument(state) {
+ this.openDocuments.delete(state.path);
+ this.openByUri.delete(state.uri);
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didClose", { textDocument: { uri: state.uri } });
+ }
+ notifyWaiters(state) {
+ for (const waiter of [...state.waiters])
+ waiter();
+ }
+}
+
+// ../lsp-core/src/lsp/workspace-apply-edit-failure.ts
+var CONCURRENT_FAILURE_REASON_BY_PHASE = {
+ applying: "workspace/applyEdit is already in progress for this workspace mutation",
+ settled: "workspace/applyEdit was already handled for this workspace mutation"
+};
+function workspaceApplyEditConcurrentFailureReason(phase) {
+ return CONCURRENT_FAILURE_REASON_BY_PHASE[phase];
+}
+
+// ../lsp-core/src/lsp/workspace-edit-commit.ts
+import { existsSync as existsSync4, lstatSync as lstatSync2, renameSync, rmSync, writeFileSync } from "node:fs";
+
+// ../lsp-core/src/lsp/workspace-edit-path.ts
+import { existsSync as existsSync3, lstatSync, readFileSync as readFileSync2, readdirSync, realpathSync as realpathSync3 } from "node:fs";
+import { dirname as dirname2, isAbsolute as isAbsolute2, relative as relative3, resolve as resolve3 } from "node:path";
+import { fileURLToPath } from "node:url";
+
+class WorkspaceEditPathError extends Error {
+ path;
+ detail;
+ name = "WorkspaceEditPathError";
+ constructor(path, detail) {
+ super(`${detail}: ${path}`);
+ this.path = path;
+ this.detail = detail;
+ }
+}
+function isPathInsideWorkspace(filePath, workspaceRoot) {
+ const relativePath = relative3(workspaceRoot, filePath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute2(relativePath);
+}
+function canonicalizeMissingPath(filePath) {
+ let ancestor = filePath;
+ while (!existsSync3(ancestor)) {
+ const parent = dirname2(ancestor);
+ if (parent === ancestor)
+ throw new WorkspaceEditPathError(filePath, "no existing ancestor");
+ ancestor = parent;
+ }
+ return resolve3(realpathSync3(ancestor), relative3(ancestor, filePath));
+}
+function canonicalWorkspaceRoot(workspaceRoot) {
+ try {
+ const canonical = realpathSync3(resolve3(workspaceRoot));
+ if (!lstatSync(canonical).isDirectory()) {
+ return { success: false, error: `workspace root is not a directory: ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath: resolve3(workspaceRoot),
+ followedSymbolicLink: existsSync3(resolve3(workspaceRoot)) && lstatSync(resolve3(workspaceRoot)).isSymbolicLink()
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `workspace root ${workspaceRoot}: ${detail}` };
+ }
+}
+function uriToCanonicalWorkspacePath(uri, workspaceRoot) {
+ let requestedPath;
+ try {
+ const parsed = new URL(uri);
+ if (parsed.protocol !== "file:" || parsed.search !== "" || parsed.hash !== "") {
+ return { success: false, error: `non-file URI ${uri}` };
+ }
+ requestedPath = resolve3(fileURLToPath(parsed));
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `non-file URI ${uri}: ${detail}` };
+ }
+ try {
+ const canonical = existsSync3(requestedPath) ? realpathSync3(requestedPath) : canonicalizeMissingPath(requestedPath);
+ if (!isPathInsideWorkspace(canonical, workspaceRoot)) {
+ return { success: false, error: `${requestedPath}: outside workspace ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath,
+ followedSymbolicLink: existsSync3(requestedPath) && lstatSync(requestedPath).isSymbolicLink()
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `${requestedPath}: ${detail}` };
+ }
+}
+function snapshotPath(path, includeChildren) {
+ if (!existsSync3(path))
+ return { kind: "missing" };
+ const stats = lstatSync(path);
+ if (stats.isFile())
+ return { kind: "file", content: readFileSync2(path, "utf-8") };
+ if (stats.isDirectory()) {
+ return includeChildren ? { kind: "directory", children: readdirSync(path).sort() } : { kind: "directory" };
+ }
+ throw new WorkspaceEditPathError(path, "unsupported filesystem entry");
+}
+
+// ../lsp-core/src/lsp/workspace-edit-commit.ts
+var DEFAULT_IO = {
+ writeFile(path, content) {
+ writeFileSync(path, content, "utf-8");
+ },
+ rename(oldPath, newPath) {
+ renameSync(oldPath, newPath);
+ },
+ remove(path, recursive) {
+ rmSync(path, { recursive, force: false });
+ }
+};
+function snapshotsEqual(expected, actual) {
+ if (expected.kind !== actual.kind)
+ return false;
+ if (expected.kind === "file" && actual.kind === "file")
+ return expected.content === actual.content;
+ if (expected.kind === "directory" && actual.kind === "directory" && expected.children !== undefined) {
+ return JSON.stringify(expected.children) === JSON.stringify(actual.children);
+ }
+ return true;
+}
+function liveSnapshot(path, expected) {
+ return snapshotPath(path, expected.kind === "directory" && expected.children !== undefined);
+}
+function firstOperationIndex(plan) {
+ return plan.operations[0]?.changeIndex ?? 0;
+}
+function failedCommit(plan, failure) {
+ const { message, changeIndex, mutations = [], filesModified = [], totalEdits = 0, lateAbort = false } = failure;
+ return {
+ result: {
+ success: false,
+ filesModified,
+ totalEdits,
+ errors: [`change ${changeIndex}: ${message}`],
+ failedChange: changeIndex,
+ ...lateAbort ? { lateAbort: true } : {}
+ },
+ delta: mutationDelta(mutations),
+ fingerprint: plan.fingerprint
+ };
+}
+function verifySnapshots(plan) {
+ for (const [path, expected] of plan.snapshots) {
+ let actual;
+ try {
+ actual = liveSnapshot(path, expected);
+ } catch (error) {
+ const changeIndex = plan.firstChangeByPath.get(path) ?? firstOperationIndex(plan);
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, { message: `cannot verify snapshot for ${path}: ${detail}`, changeIndex });
+ }
+ if (!snapshotsEqual(expected, actual)) {
+ const changeIndex = plan.firstChangeByPath.get(path) ?? firstOperationIndex(plan);
+ return failedCommit(plan, { message: `workspace state changed before commit: ${path}`, changeIndex });
+ }
+ }
+ return null;
+}
+function addModifiedPath(paths, path) {
+ if (!paths.includes(path))
+ paths.push(path);
+}
+function reportedPath(plan, path) {
+ return plan.reportedPathByCanonical.get(path) ?? path;
+}
+function changedPathsForMutation(mutation) {
+ return mutation.kind === "rename" ? [mutation.oldPath, mutation.newPath] : [mutation.path];
+}
+function mutationDelta(operations) {
+ const changedPaths = new Set;
+ for (const operation of operations) {
+ for (const path of changedPathsForMutation(operation))
+ changedPaths.add(path);
+ }
+ return { operations, changedPaths: [...changedPaths].sort() };
+}
+function resolveIo(overrides) {
+ return {
+ writeFile: overrides?.writeFile ?? DEFAULT_IO.writeFile,
+ rename: overrides?.rename ?? DEFAULT_IO.rename,
+ remove: overrides?.remove ?? DEFAULT_IO.remove
+ };
+}
+function commitOperation(context, operation) {
+ const { plan, io, accumulator } = context;
+ if (operation.kind === "noop")
+ return;
+ if (operation.kind === "text") {
+ io.writeFile(operation.path, operation.afterText);
+ accumulator.mutations.push({
+ kind: "text",
+ path: operation.path,
+ beforeText: operation.beforeText,
+ afterText: operation.afterText
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ accumulator.totalEdits += operation.editCount;
+ return;
+ }
+ if (operation.kind === "create") {
+ io.writeFile(operation.path, "");
+ accumulator.mutations.push({ kind: "create", path: operation.path, replaced: operation.replaced });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ return;
+ }
+ if (operation.kind === "rename") {
+ if (operation.replaceDestination) {
+ const targetKind = existsSync4(operation.newPath) && lstatSync2(operation.newPath).isDirectory() ? "directory" : "file";
+ io.remove(operation.newPath, targetKind === "directory");
+ accumulator.mutations.push({ kind: "delete", path: operation.newPath, targetKind });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ }
+ io.rename(operation.oldPath, operation.newPath);
+ accumulator.mutations.push({
+ kind: "rename",
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: operation.sourceKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ return;
+ }
+ io.remove(operation.path, operation.recursive);
+ accumulator.mutations.push({
+ kind: "delete",
+ path: operation.path,
+ targetKind: operation.targetKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+}
+function commitWorkspaceEditPlan(plan, options = {}) {
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const stale = verifySnapshots(plan);
+ if (stale)
+ return stale;
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const io = resolveIo(options.io);
+ const accumulator = { mutations: [], filesModified: [], totalEdits: 0 };
+ const context = { plan, io, accumulator };
+ let lateAbort = false;
+ for (const operation of plan.operations) {
+ try {
+ commitOperation(context, operation);
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, {
+ message: `I/O failure during ${operation.kind}: ${detail}`,
+ changeIndex: operation.changeIndex,
+ mutations: accumulator.mutations,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ lateAbort: lateAbort || options.signal?.aborted === true
+ });
+ }
+ if (options.signal?.aborted)
+ lateAbort = true;
+ }
+ const result = {
+ success: true,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ errors: [],
+ ...lateAbort ? { lateAbort: true } : {}
+ };
+ return { result, delta: mutationDelta(accumulator.mutations), fingerprint: plan.fingerprint };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-fingerprint.ts
+import { createHash } from "node:crypto";
+function canonicalFingerprint(operations) {
+ const canonical = operations.map((operation) => {
+ switch (operation.kind) {
+ case "text":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ edits: operation.edits,
+ version: operation.version
+ };
+ case "rename":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "create":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "delete":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ recursive: operation.recursive,
+ ignoreIfNotExists: operation.ignoreIfNotExists
+ };
+ }
+ });
+ return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
+}
+
+// ../lsp-core/src/lsp/workspace-edit-types.ts
+class WorkspaceEditValidationError extends Error {
+ changeIndex;
+ detail;
+ name = "WorkspaceEditValidationError";
+ constructor(changeIndex, detail) {
+ super(`change ${changeIndex}: ${detail}`);
+ this.changeIndex = changeIndex;
+ this.detail = detail;
+ }
+}
+
+// ../lsp-core/src/lsp/workspace-edit-parse-helpers.ts
+function isRecord3(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function parsePosition(value) {
+ if (!isRecord3(value) || typeof value["line"] !== "number" || typeof value["character"] !== "number") {
+ return null;
+ }
+ return { line: value["line"], character: value["character"] };
+}
+function parseRange(value) {
+ if (!isRecord3(value))
+ return null;
+ const start = parsePosition(value["start"]);
+ const end = parsePosition(value["end"]);
+ return start && end ? { start, end } : null;
+}
+function parseTextEdits(value, changeIndex) {
+ if (!Array.isArray(value)) {
+ throw new WorkspaceEditValidationError(changeIndex, "text edits must be an array");
+ }
+ const edits = [];
+ for (const candidate of value) {
+ if (!isRecord3(candidate) || typeof candidate["newText"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "text edit requires range and newText");
+ }
+ if ("annotationId" in candidate) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated text edits are unsupported");
+ }
+ const range = parseRange(candidate["range"]);
+ if (!range)
+ throw new WorkspaceEditValidationError(changeIndex, "text edit range is malformed");
+ edits.push({ range, newText: candidate["newText"] });
+ }
+ return edits;
+}
+function parseBooleanOption(options, key, changeIndex) {
+ const value = options[key];
+ if (value === undefined)
+ return false;
+ if (typeof value !== "boolean") {
+ throw new WorkspaceEditValidationError(changeIndex, `${key} must be boolean`);
+ }
+ return value;
+}
+function parseOptions(value, allowed, changeIndex) {
+ if (value === undefined)
+ return {};
+ if (!isRecord3(value))
+ throw new WorkspaceEditValidationError(changeIndex, "resource options must be an object");
+ for (const key of Object.keys(value)) {
+ if (!allowed.includes(key))
+ throw new WorkspaceEditValidationError(changeIndex, `unsupported resource option ${key}`);
+ }
+ const parsed = {};
+ for (const key of allowed)
+ parsed[key] = parseBooleanOption(value, key, changeIndex);
+ return parsed;
+}
+
+// ../lsp-core/src/lsp/workspace-edit-resource-parser.ts
+function parseResourceChange(input) {
+ const kind = input.change["kind"];
+ if (kind === "create" || kind === "delete") {
+ parseSinglePathResource(input, kind);
+ return;
+ }
+ if (kind !== "rename") {
+ throw new WorkspaceEditValidationError(input.changeIndex, `unsupported resource operation ${String(kind)}`);
+ }
+ parseRename(input);
+}
+function parseSinglePathResource(input, kind) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["uri"] !== "string")
+ throw new WorkspaceEditValidationError(changeIndex, `${kind}.uri is required`);
+ const resolvedPath = uriToCanonicalWorkspacePath(change["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ if (kind === "create") {
+ const options2 = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ overwrite: options2["overwrite"] ?? false,
+ ignoreIfExists: options2["ignoreIfExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["recursive", "ignoreIfNotExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ recursive: options["recursive"] ?? false,
+ ignoreIfNotExists: options["ignoreIfNotExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+}
+function parseRename(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["oldUri"] !== "string" || typeof change["newUri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "rename requires oldUri and newUri");
+ }
+ const oldPath = uriToCanonicalWorkspacePath(change["oldUri"], workspaceRoot);
+ const newPath = uriToCanonicalWorkspacePath(change["newUri"], workspaceRoot);
+ if (!oldPath.success || !newPath.success) {
+ target.failures.push({
+ changeIndex,
+ message: !oldPath.success ? oldPath.error : !newPath.success ? newPath.error : "invalid rename path"
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind: "rename",
+ changeIndex,
+ oldPath: oldPath.path,
+ newPath: newPath.path,
+ reportedOldPath: oldPath.requestedPath,
+ reportedNewPath: newPath.requestedPath,
+ overwrite: options["overwrite"] ?? false,
+ ignoreIfExists: options["ignoreIfExists"] ?? false,
+ followedSymbolicLink: oldPath.followedSymbolicLink || newPath.followedSymbolicLink
+ });
+}
+
+// ../lsp-core/src/lsp/workspace-edit-parser.ts
+function failureResult(failures) {
+ const sorted = [...failures].sort((left, right) => left.changeIndex - right.changeIndex);
+ const first = sorted[0];
+ return {
+ success: false,
+ filesModified: [],
+ totalEdits: 0,
+ errors: sorted.map((failure) => `change ${failure.changeIndex}: ${failure.message}`),
+ ...first ? { failedChange: first.changeIndex } : {}
+ };
+}
+function parseWorkspaceEdit(edit, workspaceRoot) {
+ if (!isRecord3(edit))
+ return { operations: [], failures: [{ changeIndex: 0, message: "No edit provided" }] };
+ if (edit["changeAnnotations"] !== undefined) {
+ return { operations: [], failures: [{ changeIndex: 0, message: "change annotations are unsupported" }] };
+ }
+ const hasChanges = edit["changes"] !== undefined;
+ const hasDocumentChanges = edit["documentChanges"] !== undefined;
+ if (hasChanges && hasDocumentChanges) {
+ return {
+ operations: [],
+ failures: [{ changeIndex: 0, message: "changes and documentChanges cannot be combined" }]
+ };
+ }
+ const target = { operations: [], failures: [] };
+ if (hasChanges)
+ return parseChanges(edit["changes"], workspaceRoot, target);
+ return parseDocumentChanges(edit["documentChanges"], workspaceRoot, target);
+}
+function parseChanges(value, workspaceRoot, target) {
+ if (!isRecord3(value))
+ return { ...target, failures: [{ changeIndex: 0, message: "changes must be an object" }] };
+ const entries = Object.entries(value).sort(([left], [right]) => left.localeCompare(right));
+ for (const [changeIndex, [uri, rawEdits]] of entries.entries()) {
+ const resolvedPath = uriToCanonicalWorkspacePath(uri, workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ continue;
+ }
+ try {
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(rawEdits, changeIndex),
+ version: null
+ });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChanges(value, workspaceRoot, target) {
+ if (value === undefined)
+ return target;
+ if (!Array.isArray(value)) {
+ return { ...target, failures: [{ changeIndex: 0, message: "documentChanges must be an array" }] };
+ }
+ for (const [changeIndex, change] of value.entries()) {
+ try {
+ parseDocumentChange({ change, changeIndex, workspaceRoot, target });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChange(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (!isRecord3(change))
+ throw new WorkspaceEditValidationError(changeIndex, "document change must be an object");
+ if ("annotationId" in change) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated resource operations are unsupported");
+ }
+ if (typeof change["kind"] === "string") {
+ parseResourceChange({ change, changeIndex, workspaceRoot, target });
+ return;
+ }
+ const identifier = change["textDocument"];
+ if (!isRecord3(identifier) || typeof identifier["uri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "textDocument.uri is required");
+ }
+ const version = identifier["version"];
+ if (version !== null && (!Number.isInteger(version) || typeof version !== "number" || version < 0)) {
+ throw new WorkspaceEditValidationError(changeIndex, "document version must be null or a non-negative integer");
+ }
+ const resolvedPath = uriToCanonicalWorkspacePath(identifier["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(change["edits"], changeIndex),
+ version
+ });
+}
+
+// ../lsp-core/src/lsp/workspace-edit-simulation.ts
+import { dirname as dirname3, relative as relative4, resolve as resolve4 } from "node:path";
+
+// ../lsp-core/src/lsp/workspace-edit-text.ts
+function comparePosition(left, right) {
+ return left.line === right.line ? left.character - right.character : left.line - right.line;
+}
+function positionsEqual(left, right) {
+ return left.line === right.line && left.character === right.character;
+}
+function rangesEqual(left, right) {
+ return positionsEqual(left.start, right.start) && positionsEqual(left.end, right.end);
+}
+function isEmptyRange(range) {
+ return positionsEqual(range.start, range.end);
+}
+function formatRange(range) {
+ return `${range.start.line + 1}:${range.start.character + 1}-${range.end.line + 1}:${range.end.character + 1}`;
+}
+function validatePosition(position, label, context) {
+ const { lines, changeIndex } = context;
+ if (!Number.isInteger(position.line) || !Number.isInteger(position.character)) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position must use integer line and character`);
+ }
+ if (position.line < 0 || position.character < 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position cannot be negative`);
+ }
+ const line = lines[position.line];
+ if (line === undefined) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} line ${position.line} is outside the document`);
+ }
+ if (position.character > line.length) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} character ${position.character} is outside line ${position.line}`);
+ }
+}
+function validateRange(range, lines, changeIndex) {
+ const context = { lines, changeIndex };
+ validatePosition(range.start, "start", context);
+ validatePosition(range.end, "end", context);
+ if (comparePosition(range.start, range.end) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `range ${formatRange(range)} ends before it starts`);
+ }
+}
+function sortAndDeduplicate(edits) {
+ const sorted = edits.map((edit, index) => ({ edit, index })).sort((left, right) => {
+ const positionOrder = comparePosition(right.edit.range.start, left.edit.range.start);
+ return positionOrder === 0 ? right.index - left.index : positionOrder;
+ });
+ const unique = [];
+ for (const entry of sorted) {
+ const previous = unique.at(-1);
+ if (previous !== undefined && !isEmptyRange(entry.edit.range) && rangesEqual(previous.range, entry.edit.range) && previous.newText === entry.edit.newText) {
+ continue;
+ }
+ unique.push(entry.edit);
+ }
+ return unique;
+}
+function validateNoOverlap(edits, changeIndex) {
+ for (let index = 0;index < edits.length - 1; index += 1) {
+ const later = edits[index];
+ const earlier = edits[index + 1];
+ if (later === undefined || earlier === undefined)
+ continue;
+ if (comparePosition(earlier.range.end, later.range.start) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `overlapping edits ${formatRange(earlier.range)} and ${formatRange(later.range)}`);
+ }
+ }
+}
+function applyNormalizedTextEdits(content, edits) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ const { start, end } = edit.range;
+ const startLine = lines[start.line];
+ const endLine = lines[end.line];
+ if (startLine === undefined || endLine === undefined)
+ continue;
+ const replacement = startLine.slice(0, start.character) + edit.newText + endLine.slice(end.character);
+ lines.splice(start.line, end.line - start.line + 1, ...replacement.split(`
+`));
+ }
+ return lines.join(`
+`);
+}
+function normalizeTextEdits(content, edits, changeIndex) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ validateRange(edit.range, lines, changeIndex);
+ }
+ const normalized = sortAndDeduplicate(edits);
+ validateNoOverlap(normalized, changeIndex);
+ return { edits: normalized, text: applyNormalizedTextEdits(content, normalized) };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-simulation.ts
+function isSameOrDescendant2(candidate, parent) {
+ const relativePath = relative4(parent, candidate);
+ return relativePath === "" || !relativePath.startsWith("..") && relativePath !== "..";
+}
+function removeVirtualSubtree(virtual, path) {
+ for (const candidate of [...virtual.keys()]) {
+ if (isSameOrDescendant2(candidate, path))
+ virtual.delete(candidate);
+ }
+ virtual.set(path, { kind: "missing" });
+}
+function moveVirtualSubtree(virtual, oldPath, newPath) {
+ const moved = [...virtual.entries()].filter(([candidate]) => isSameOrDescendant2(candidate, oldPath));
+ removeVirtualSubtree(virtual, oldPath);
+ removeVirtualSubtree(virtual, newPath);
+ for (const [candidate, entry] of moved) {
+ const suffix = relative4(oldPath, candidate);
+ virtual.set(suffix === "" ? newPath : resolve4(newPath, suffix), entry);
+ }
+}
+function virtualDirectoryHasChildren(virtual, path) {
+ for (const [candidate, entry] of virtual) {
+ if (candidate !== path && entry.kind !== "missing" && isSameOrDescendant2(candidate, path))
+ return true;
+ }
+ return false;
+}
+function requireVirtualParent(virtual, path, changeIndex) {
+ if (virtual.get(dirname3(path))?.kind !== "directory") {
+ throw new WorkspaceEditValidationError(changeIndex, `parent directory does not exist for ${path}`);
+ }
+}
+function simulateOperations(parsed, snapshots) {
+ const virtual = new Map(snapshots);
+ const planned = [];
+ const failures = [];
+ for (const operation of parsed) {
+ try {
+ planned.push(simulateOperation(operation, virtual));
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ failures.push({ changeIndex: operation.changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return { operations: planned, failures };
+}
+function simulateOperation(operation, virtual) {
+ switch (operation.kind) {
+ case "text":
+ return simulateText(operation, virtual);
+ case "create":
+ return simulateCreate(operation, virtual);
+ case "rename":
+ return simulateRename(operation, virtual);
+ case "delete":
+ return simulateDelete(operation, virtual);
+ }
+}
+function rejectSymbolicLink(operation) {
+ if (operation.followedSymbolicLink) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "resource operations through symbolic links are unsupported");
+ }
+}
+function simulateText(operation, virtual) {
+ const entry = virtual.get(operation.path);
+ if (entry?.kind !== "file")
+ throw new WorkspaceEditValidationError(operation.changeIndex, `${operation.path} is not a file`);
+ const normalized = normalizeTextEdits(entry.content, operation.edits, operation.changeIndex);
+ virtual.set(operation.path, { kind: "file", content: normalized.text });
+ return {
+ kind: "text",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ beforeText: entry.content,
+ afterText: normalized.text,
+ editCount: normalized.edits.length,
+ documentVersion: operation.version
+ };
+}
+function simulateCreate(operation, virtual) {
+ rejectSymbolicLink(operation);
+ requireVirtualParent(virtual, operation.path, operation.changeIndex);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind !== "missing") {
+ if (operation.overwrite && target.kind === "file") {
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: true };
+ }
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `create target already exists: ${operation.path}`);
+ }
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: false };
+}
+function simulateRename(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const source = virtual.get(operation.oldPath) ?? { kind: "missing" };
+ if (source.kind === "missing") {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename source does not exist: ${operation.oldPath}`);
+ }
+ if (operation.oldPath === operation.newPath)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ if (isSameOrDescendant2(operation.newPath, operation.oldPath)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "cannot rename a path into its own subtree");
+ }
+ requireVirtualParent(virtual, operation.newPath, operation.changeIndex);
+ const destination = virtual.get(operation.newPath) ?? { kind: "missing" };
+ if (destination.kind !== "missing" && !operation.overwrite) {
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename target already exists: ${operation.newPath}`);
+ }
+ moveVirtualSubtree(virtual, operation.oldPath, operation.newPath);
+ return {
+ kind: "rename",
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: source.kind,
+ replaceDestination: destination.kind !== "missing"
+ };
+}
+function simulateDelete(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind === "missing") {
+ if (operation.ignoreIfNotExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `delete target does not exist: ${operation.path}`);
+ }
+ if (target.kind === "directory" && !operation.recursive && virtualDirectoryHasChildren(virtual, operation.path)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `directory is not empty: ${operation.path}`);
+ }
+ removeVirtualSubtree(virtual, operation.path);
+ return {
+ kind: "delete",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ targetKind: target.kind,
+ recursive: operation.recursive
+ };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-snapshot.ts
+import { existsSync as existsSync5, lstatSync as lstatSync3, readdirSync as readdirSync2 } from "node:fs";
+import { dirname as dirname4, resolve as resolve5 } from "node:path";
+class WorkspaceSnapshotBuilder {
+ workspaceRoot;
+ snapshots = new Map;
+ constructor(workspaceRoot) {
+ this.workspaceRoot = workspaceRoot;
+ }
+ build(operations) {
+ this.add(this.workspaceRoot, false);
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, true);
+ this.add(operation.newPath, true);
+ break;
+ case "delete":
+ this.add(operation.path, true);
+ break;
+ case "text":
+ case "create":
+ this.add(operation.path, false);
+ break;
+ }
+ }
+ return this.snapshots;
+ }
+ add(path, includeChildren) {
+ let candidate = path;
+ while (true) {
+ const existing = this.snapshots.get(candidate);
+ if (existing === undefined || includeChildren && existing.kind === "directory" && existing.children === undefined) {
+ this.snapshots.set(candidate, snapshotPath(candidate, includeChildren && candidate === path));
+ }
+ if (candidate === this.workspaceRoot)
+ break;
+ candidate = dirname4(candidate);
+ }
+ if (!includeChildren || !existsSync5(path) || !lstatSync3(path).isDirectory())
+ return;
+ for (const child of readdirSync2(path))
+ this.add(resolve5(path, child), true);
+ }
+}
+function snapshotOperations(operations, workspaceRoot) {
+ return new WorkspaceSnapshotBuilder(workspaceRoot).build(operations);
+}
+
+// ../lsp-core/src/lsp/workspace-edit-plan.ts
+class PlanPathIndex {
+ firstChangeByPath = new Map;
+ reportedPathByCanonical = new Map;
+ build(operations) {
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, operation.reportedOldPath, operation.changeIndex);
+ this.add(operation.newPath, operation.reportedNewPath, operation.changeIndex);
+ break;
+ case "text":
+ case "create":
+ case "delete":
+ this.add(operation.path, operation.reportedPath, operation.changeIndex);
+ break;
+ }
+ }
+ }
+ add(path, reportedPath2, changeIndex) {
+ if (!this.firstChangeByPath.has(path))
+ this.firstChangeByPath.set(path, changeIndex);
+ if (!this.reportedPathByCanonical.has(path))
+ this.reportedPathByCanonical.set(path, reportedPath2);
+ }
+}
+function fingerprintWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ return { success: true, fingerprint: canonicalFingerprint(parsed.operations) };
+}
+function planWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ let snapshots;
+ try {
+ snapshots = snapshotOperations(parsed.operations, root.path);
+ } catch (error) {
+ return {
+ success: false,
+ result: failureResult([{ changeIndex: 0, message: error instanceof Error ? error.message : String(error) }])
+ };
+ }
+ const simulated = simulateOperations(parsed.operations, snapshots);
+ if (simulated.failures.length > 0)
+ return { success: false, result: failureResult(simulated.failures) };
+ const paths = new PlanPathIndex;
+ paths.build(parsed.operations);
+ const plan = {
+ workspaceRoot: root.path,
+ operations: simulated.operations,
+ snapshots,
+ firstChangeByPath: paths.firstChangeByPath,
+ reportedPathByCanonical: paths.reportedPathByCanonical,
+ fingerprint: canonicalFingerprint(parsed.operations)
+ };
+ return { success: true, plan };
+}
+
+// ../lsp-core/src/lsp/workspace-mutation-controller.ts
+function failure(message, failedChange, base) {
+ return {
+ success: false,
+ filesModified: base?.filesModified ?? [],
+ totalEdits: base?.totalEdits ?? 0,
+ errors: [message],
+ ...failedChange === undefined ? {} : { failedChange },
+ ...base?.lateAbort ? { lateAbort: true } : {}
+ };
+}
+function responseFor(result) {
+ if (result.success)
+ return { applied: true };
+ return {
+ applied: false,
+ failureReason: result.errors[0] ?? "workspace edit failed",
+ ...result.failedChange === undefined ? {} : { failedChange: result.failedChange }
+ };
+}
+function isRecord4(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+class WorkspaceMutationController {
+ workspaceRoot;
+ documents;
+ activeLease = null;
+ nextLeaseId = 1;
+ io;
+ constructor(workspaceRoot, documents) {
+ this.workspaceRoot = workspaceRoot;
+ this.documents = documents;
+ }
+ setIo(io) {
+ this.io = io;
+ }
+ acquire(signal) {
+ if (this.activeLease)
+ return { success: false, result: failure("workspace mutation is already in progress") };
+ if (signal?.aborted)
+ return { success: false, result: failure("cancelled before mutating request") };
+ const lease = {
+ id: this.nextLeaseId,
+ phase: "idle",
+ ...signal === undefined ? {} : { signal }
+ };
+ this.nextLeaseId += 1;
+ this.activeLease = lease;
+ return { success: true, lease };
+ }
+ release(lease) {
+ if (this.activeLease?.id !== lease.id)
+ return;
+ this.activeLease.phase = "sealed";
+ this.activeLease = null;
+ }
+ isBeforeCommit(lease) {
+ return this.activeLease?.id === lease.id && this.activeLease.phase === "idle";
+ }
+ async handleApplyEdit(params) {
+ const lease = this.activeLease;
+ if (!lease)
+ return { applied: false, failureReason: "workspace/applyEdit requires an active workspace mutation" };
+ if (lease.phase !== "idle") {
+ return {
+ applied: false,
+ failureReason: workspaceApplyEditConcurrentFailureReason(lease.phase === "applying" ? "applying" : "settled")
+ };
+ }
+ lease.phase = "applying";
+ lease.applyCompletion = new Promise((resolve6) => {
+ lease.resolveApply = resolve6;
+ });
+ const edit = isRecord4(params) ? params["edit"] : undefined;
+ const record2 = edit === undefined ? { fingerprint: null, result: failure("workspace/applyEdit params.edit is required", 0) } : await this.applyEdit(edit, lease);
+ lease.serverApply = record2;
+ lease.phase = "settled";
+ lease.resolveApply?.();
+ return responseFor(record2.result);
+ }
+ async reconcileRename(leaseToken, edit) {
+ const lease = this.requireActiveLease(leaseToken);
+ if (!lease)
+ return { edit, apply: failure("workspace mutation lease ended before rename reconciliation") };
+ if (lease.phase === "applying")
+ await lease.applyCompletion;
+ if (lease.serverApply)
+ return this.reconcileServerApply(lease.serverApply, edit);
+ lease.phase = "sealed";
+ if (!edit)
+ return { edit, apply: failure("No edit provided") };
+ const applied = await this.applyEdit(edit, lease);
+ return { edit, apply: applied.result };
+ }
+ reconcileServerApply(record2, edit) {
+ if (!edit)
+ return { edit, apply: record2.result };
+ const fingerprint = fingerprintWorkspaceEdit(edit, this.workspaceRoot);
+ if (fingerprint.success && record2.fingerprint !== null && fingerprint.fingerprint === record2.fingerprint) {
+ return { edit, apply: record2.result };
+ }
+ return {
+ edit,
+ apply: failure("rename result conflicts with server-applied workspace edit", 0, record2.result)
+ };
+ }
+ async applyEdit(edit, lease) {
+ const planned = planWorkspaceEdit(edit, this.workspaceRoot);
+ if (!planned.success)
+ return { fingerprint: null, result: planned.result };
+ const versionFailure = this.documents.validateVersions(planned.plan.operations);
+ if (versionFailure) {
+ return {
+ fingerprint: planned.plan.fingerprint,
+ result: failure(versionFailure.message, versionFailure.changeIndex)
+ };
+ }
+ const commit = commitWorkspaceEditPlan(planned.plan, {
+ ...lease.signal === undefined ? {} : { signal: lease.signal },
+ ...this.io === undefined ? {} : { io: this.io }
+ });
+ let result = commit.result;
+ if (commit.delta.operations.length > 0) {
+ try {
+ await this.documents.synchronize(commit.delta);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ result = failure(`document synchronization failed after filesystem commit: ${message}`, undefined, result);
+ }
+ }
+ if (lease.signal?.aborted && !result.lateAbort)
+ result = { ...result, lateAbort: true };
+ return { fingerprint: planned.plan.fingerprint, result };
+ }
+ requireActiveLease(lease) {
+ return this.activeLease?.id === lease.id ? this.activeLease : null;
+ }
+}
+
// ../lsp-core/src/lsp/client.ts
-var POST_OPEN_DELAY_MS = 1000;
-var POST_DIAGNOSTICS_WAIT_MS = 500;
+var DIAGNOSTICS_FRESHNESS_TIMEOUT_MS = 3000;
+var VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
class LspClient extends LspClientConnection {
- openedFiles = new Set;
- documentVersions = new Map;
- lastSyncedText = new Map;
diagnosticPullErrors = [];
+ documents;
+ workspaceMutations;
+ diagnosticsFreshnessTimeoutMs;
+ constructor(root, server2, options = {}) {
+ super(root, server2, options);
+ this.diagnosticsFreshnessTimeoutMs = options.diagnosticsFreshnessTimeoutMs ?? DIAGNOSTICS_FRESHNESS_TIMEOUT_MS;
+ this.documents = new WorkspaceDocumentState((method, params) => this.sendNotification(method, params), (uri) => this.diagnosticsStore.delete(uri), {
+ versionlessPublishQuiescenceMs: options.versionlessPublishQuiescenceMs ?? VERSIONLESS_PUBLISH_QUIESCENCE_MS
+ });
+ this.workspaceMutations = new WorkspaceMutationController(root, this.documents);
+ this.setWorkspaceApplyEditHandler((params) => this.workspaceMutations.handleApplyEdit(params));
+ }
getDiagnosticPullErrors() {
return this.diagnosticPullErrors;
}
async openFile(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- const uri = pathToFileURL2(absPath).href;
- const text = readFileSync(absPath, "utf-8");
- if (!this.openedFiles.has(absPath)) {
- const ext = effectiveExtension(absPath);
- const languageId = getLanguageId(ext);
- const version = 1;
- await this.sendNotification("textDocument/didOpen", {
- textDocument: {
- uri,
- languageId,
- version,
- text
- }
- });
- this.openedFiles.add(absPath);
- this.documentVersions.set(uri, version);
- this.lastSyncedText.set(uri, text);
- await new Promise((r) => setTimeout(r, POST_OPEN_DELAY_MS));
- return;
- }
- const prevText = this.lastSyncedText.get(uri);
- if (prevText === text) {
- return;
- }
- const nextVersion = (this.documentVersions.get(uri) ?? 1) + 1;
- this.documentVersions.set(uri, nextVersion);
- this.lastSyncedText.set(uri, text);
- await this.sendNotification("textDocument/didChange", {
- textDocument: { uri, version: nextVersion },
- contentChanges: [{ text }]
- });
- await this.sendNotification("textDocument/didSave", {
- textDocument: { uri },
- text
- });
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.documents.openFile(absPath);
+ }
+ getOpenDocumentVersion(filePath) {
+ return this.documents.getVersion(this.resolveWorkspacePath(filePath));
+ }
+ getStoredDiagnostics(uri) {
+ return [...this.documents.getStoredDiagnostics(uri)];
+ }
+ setWorkspaceEditIo(io) {
+ this.workspaceMutations.setIo(io);
}
- async definition(filePath, line, character) {
- const absPath = resolve(contextCwd(), filePath);
+ handlePublishDiagnostics(params) {
+ super.handlePublishDiagnostics(params);
+ this.documents.recordPublishedDiagnostics(params);
+ }
+ async definition(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/definition", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character }
- });
+ }, options);
}
- async references(filePath, line, character, includeDeclaration = true) {
- const absPath = resolve(contextCwd(), filePath);
+ async references(filePath, line, character, includeDeclaration = true, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/references", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character },
context: { includeDeclaration }
- });
+ }, options);
}
- async documentSymbols(filePath) {
- const absPath = resolve(contextCwd(), filePath);
+ async documentSymbols(filePath, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/documentSymbol", {
- textDocument: { uri: pathToFileURL2(absPath).href }
- });
+ textDocument: { uri: pathToFileURL3(absPath).href }
+ }, options);
}
- async workspaceSymbols(query) {
- return this.sendRequest("workspace/symbol", { query });
+ async workspaceSymbols(query, signal) {
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("workspace/symbol", { query }, options);
}
isUnsupportedDiagnosticPullError(error) {
if (!(error instanceof Error))
@@ -1285,42 +2920,173 @@ class LspClient extends LspClientConnection {
return true;
return /unsupported|not supported|method not found|unknown request/i.test(error.message);
}
- async diagnostics(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- const uri = pathToFileURL2(absPath).href;
- await this.openFile(absPath);
- await new Promise((r) => setTimeout(r, POST_DIAGNOSTICS_WAIT_MS));
- try {
- const result = await this.sendRequest("textDocument/diagnostic", {
- textDocument: { uri }
- });
- if (result.items) {
- return { items: result.items };
+ freshnessTimeout(absPath) {
+ return {
+ items: [],
+ transientError: {
+ kind: "freshness_timeout",
+ message: `Timed out waiting for fresh diagnostics for ${absPath} within ${this.diagnosticsFreshnessTimeoutMs}ms.`
}
- } catch (error) {
- if (!this.isUnsupportedDiagnosticPullError(error)) {
- this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ };
+ }
+ parseDiagnosticPullReport(value) {
+ if (value.kind === "unchanged") {
+ return {
+ type: "unchanged",
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ return {
+ type: "full",
+ diagnostics: value.items ?? [],
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ async diagnostics(filePath, signal) {
+ signal?.throwIfAborted();
+ const absPath = this.resolveWorkspacePath(filePath);
+ const uri = pathToFileURL3(absPath).href;
+ await this.openFile(absPath);
+ const deadlineAt = Date.now() + this.diagnosticsFreshnessTimeoutMs;
+ for (;; ) {
+ signal?.throwIfAborted();
+ const snapshot = this.documents.captureDiagnosticSnapshot(absPath);
+ if (!snapshot)
+ return this.freshnessTimeout(absPath);
+ const push = this.documents.resolvePushDiagnostics(snapshot);
+ if (push.status === "ready")
+ return { items: [...push.diagnostics] };
+ let pushFallbackOnly = !this.isDiagnosticPullSupported();
+ if (!pushFallbackOnly) {
+ const cached = this.documents.getPullCache(snapshot);
+ try {
+ const remainingMs2 = deadlineAt - Date.now();
+ if (remainingMs2 <= 0)
+ return this.freshnessTimeout(absPath);
+ const result = await this.sendRequest("textDocument/diagnostic", {
+ textDocument: { uri },
+ ...cached?.resultId === undefined ? {} : { previousResultId: cached.resultId }
+ }, { timeoutMs: remainingMs2, ...signal === undefined ? {} : { signal } });
+ if (!this.documents.isCurrentSnapshot(snapshot))
+ continue;
+ const report = this.parseDiagnosticPullReport(result);
+ if (report.type === "full") {
+ this.documents.recordPullDiagnostics(snapshot, {
+ kind: "full",
+ diagnostics: report.diagnostics,
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ });
+ return { items: [...report.diagnostics] };
+ }
+ if (cached !== null && cached.documentVersion === snapshot.version && cached.resultId === report.resultId) {
+ return { items: [...cached.diagnostics] };
+ }
+ } catch (error) {
+ if (this.isUnsupportedDiagnosticPullError(error)) {
+ this.setDiagnosticPullSupported(false);
+ pushFallbackOnly = true;
+ } else if (error instanceof LspRequestTimeoutError) {
+ pushFallbackOnly = true;
+ } else {
+ this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ throw error;
+ }
+ }
}
+ if (!pushFallbackOnly)
+ continue;
+ const remainingMs = deadlineAt - Date.now();
+ if (remainingMs <= 0)
+ return this.freshnessTimeout(absPath);
+ const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;
+ await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);
}
- return { items: this.getStoredDiagnostics(uri) };
}
- async prepareRename(filePath, line, character) {
- const absPath = resolve(contextCwd(), filePath);
+ async prepareRename(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/prepareRename", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character }
- });
+ }, options);
}
- async rename(filePath, line, character, newName) {
- const absPath = resolve(contextCwd(), filePath);
+ async rename(filePath, line, character, newName, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
- return this.sendRequest("textDocument/rename", {
- textDocument: { uri: pathToFileURL2(absPath).href },
- position: { line: line - 1, character },
- newName
- });
+ const acquired = this.workspaceMutations.acquire(signal);
+ if (!acquired.success)
+ return { edit: null, apply: acquired.result };
+ const preCommitSignal = createPreCommitAbortSignal(signal, () => this.workspaceMutations.isBeforeCommit(acquired.lease));
+ try {
+ const renameParams = {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character },
+ newName
+ };
+ const edit = preCommitSignal === undefined ? await this.sendRequest("textDocument/rename", renameParams) : await this.sendRequest("textDocument/rename", renameParams, {
+ signal: preCommitSignal.signal
+ });
+ return await this.workspaceMutations.reconcileRename(acquired.lease, edit);
+ } finally {
+ preCommitSignal?.dispose();
+ this.workspaceMutations.release(acquired.lease);
+ }
}
+ resolveWorkspacePath(filePath) {
+ return resolve6(this.root, filePath);
+ }
+}
+function waitForDiagnosticsActivity(wait, signal) {
+ if (!signal)
+ return wait;
+ if (signal.aborted)
+ return Promise.reject(abortError2(signal));
+ return new Promise((resolve7, reject) => {
+ const onAbort = () => {
+ signal.removeEventListener("abort", onAbort);
+ reject(abortError2(signal));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ wait.then(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve7();
+ }, (error) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(error);
+ });
+ });
+}
+function createPreCommitAbortSignal(source, isBeforeCommit) {
+ if (!source)
+ return;
+ const controller = new AbortController;
+ const onAbort = () => {
+ if (isBeforeCommit() && !controller.signal.aborted)
+ controller.abort(preCommitAbortReason(source));
+ };
+ if (source.aborted)
+ onAbort();
+ else
+ source.addEventListener("abort", onAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => source.removeEventListener("abort", onAbort)
+ };
+}
+function preCommitAbortReason(source) {
+ const reason = source.reason;
+ if (reason instanceof Error && reason.name !== "AbortError")
+ return reason;
+ return new Error("LSP request cancelled before workspace edit commit");
+}
+function abortError2(signal) {
+ const reason = signal.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "operation cancelled");
+ error.name = "AbortError";
+ return error;
}
// ../lsp-core/src/lsp/process-signal-cleanup.ts
@@ -1352,7 +3118,7 @@ async function stopClientBestEffort(client) {
function awaitWithSignal(promise, signal) {
if (!signal)
return promise;
- return new Promise((resolve2, reject) => {
+ return new Promise((resolve7, reject) => {
let settled = false;
const onAbort = () => {
if (settled)
@@ -1370,7 +3136,7 @@ function awaitWithSignal(promise, signal) {
return;
settled = true;
signal.removeEventListener("abort", onAbort);
- resolve2(value);
+ resolve7(value);
}, (err) => {
if (settled)
return;
@@ -1624,21 +3390,17 @@ async function disposeDefaultLspManager() {
}
// ../lsp-core/src/lsp/server-install-state.ts
-import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
-import { homedir } from "node:os";
-import { dirname, isAbsolute, join as join2 } from "node:path";
+import { existsSync as existsSync6, mkdirSync, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
+import { dirname as dirname5 } from "node:path";
function getInstallDecisionsPath() {
- const override = contextEnv("LSP_TOOLS_MCP_INSTALL_DECISIONS");
- if (!override)
- return join2(homedir(), ".codex", "lsp-install-decisions.json");
- return isAbsolute(override) ? override : join2(homedir(), override);
+ return lspRequestContext().installDecisionsPath;
}
function loadInstallDecisions() {
const path = getInstallDecisionsPath();
- if (!existsSync2(path))
+ if (!existsSync6(path))
return {};
try {
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
+ const parsed = JSON.parse(readFileSync3(path, "utf8"));
return isInstallDecisions(parsed) ? parsed : {};
} catch {
return {};
@@ -1657,28 +3419,26 @@ function isInstallDecision(value) {
}
function writeInstallDecisions(decisions) {
const path = getInstallDecisionsPath();
- mkdirSync(dirname(path), { recursive: true });
+ mkdirSync(dirname5(path), { recursive: true });
const tmpPath = `${path}.tmp`;
- writeFileSync(tmpPath, `${JSON.stringify(decisions, null, 2)}
+ writeFileSync2(tmpPath, `${JSON.stringify(decisions, null, 2)}
`, "utf8");
- renameSync(tmpPath, path);
+ renameSync2(tmpPath, path);
}
function isInstallDecisions(value) {
- return isRecord2(value) && Object.values(value).every(isInstallDecisionRecord);
+ return isRecord5(value) && Object.values(value).every(isInstallDecisionRecord);
}
function isInstallDecisionRecord(value) {
- if (!isRecord2(value))
+ if (!isRecord5(value))
return false;
return isInstallDecision(value["decision"]) && typeof value["decidedAt"] === "string";
}
-function isRecord2(value) {
+function isRecord5(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
// ../lsp-core/src/lsp/config-loader.ts
-import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
-import { homedir as homedir2 } from "node:os";
-import { delimiter as delimiter2, isAbsolute as isAbsolute2, join as join3 } from "node:path";
+import { existsSync as existsSync7, readFileSync as readFileSync4 } from "node:fs";
// ../lsp-core/src/lsp/server-definitions.ts
var LSP_INSTALL_HINTS = {
@@ -1828,27 +3588,17 @@ var BUILTIN_SERVERS = {
};
// ../lsp-core/src/lsp/config-loader.ts
-function resolveProjectConfigPath(path) {
- return isAbsolute2(path) ? path : join3(contextCwd(), path);
-}
function getProjectConfigPaths() {
- const projectOverride = contextEnv("LSP_TOOLS_MCP_PROJECT_CONFIG");
- if (projectOverride) {
- return projectOverride.split(delimiter2).filter(Boolean).map(resolveProjectConfigPath);
- }
- return [join3(contextCwd(), ".codex", "lsp-client.json")];
+ return lspRequestContext().projectConfigPaths;
}
function getUserConfigPath() {
- const userOverride = contextEnv("LSP_TOOLS_MCP_USER_CONFIG");
- if (!userOverride)
- return join3(homedir2(), ".codex", "lsp-client.json");
- return isAbsolute2(userOverride) ? userOverride : join3(homedir2(), userOverride);
+ return lspRequestContext().userConfigPath;
}
function loadJsonFile(path) {
- if (!existsSync3(path))
+ if (!existsSync7(path))
return null;
try {
- const parsed = JSON.parse(readFileSync3(path, "utf-8"));
+ const parsed = JSON.parse(readFileSync4(path, "utf-8"));
return isConfigJson(parsed) ? parsed : null;
} catch {
return null;
@@ -1987,16 +3737,16 @@ function applyOptionalServerFields(server2, entry) {
}
}
function isConfigJson(value) {
- if (!isRecord3(value))
+ if (!isRecord6(value))
return false;
const lsp = value["lsp"];
- return lsp === undefined || isRecord3(lsp);
+ return lsp === undefined || isRecord6(lsp);
}
function parseLspEntry(value) {
return isLspEntry(value) ? value : null;
}
function isLspEntry(value) {
- if (!isRecord3(value))
+ if (!isRecord6(value))
return false;
const disabled = value["disabled"];
const command = value["command"];
@@ -2004,15 +3754,15 @@ function isLspEntry(value) {
const priority = value["priority"];
const env = value["env"];
const initialization = value["initialization"];
- return (disabled === undefined || typeof disabled === "boolean") && (command === undefined || isStringArray(command)) && (extensions === undefined || isStringArray(extensions)) && (priority === undefined || typeof priority === "number") && (env === undefined || isStringRecord(env)) && (initialization === undefined || isRecord3(initialization));
+ return (disabled === undefined || typeof disabled === "boolean") && (command === undefined || isStringArray(command)) && (extensions === undefined || isStringArray(extensions)) && (priority === undefined || typeof priority === "number") && (env === undefined || isStringRecord(env)) && (initialization === undefined || isRecord6(initialization));
}
function isStringArray(value) {
return Array.isArray(value) && value.every((item) => typeof item === "string");
}
function isStringRecord(value) {
- return isRecord3(value) && Object.values(value).every((item) => typeof item === "string");
+ return isRecord6(value) && Object.values(value).every((item) => typeof item === "string");
}
-function isRecord3(value) {
+function isRecord6(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function getDisabledServerIds() {
@@ -2033,8 +3783,8 @@ function getDisabledServerIds() {
}
// ../lsp-core/src/lsp/server-installation.ts
-import { existsSync as existsSync4 } from "node:fs";
-import { delimiter as delimiter3, join as join4 } from "node:path";
+import { existsSync as existsSync8 } from "node:fs";
+import { delimiter as delimiter3, join as join3 } from "node:path";
function isServerInstalled(command, _workingDirectory) {
if (command.length === 0)
return false;
@@ -2042,7 +3792,7 @@ function isServerInstalled(command, _workingDirectory) {
if (!cmd)
return false;
if (cmd.includes("/") || cmd.includes("\\")) {
- if (existsSync4(cmd))
+ if (existsSync8(cmd))
return true;
}
const isWindows = process.platform === "win32";
@@ -2063,7 +3813,7 @@ function isServerInstalled(command, _workingDirectory) {
const paths = pathEnv.split(delimiter3);
for (const p of paths) {
for (const suffix of exts) {
- if (existsSync4(join4(p, cmd + suffix))) {
+ if (existsSync8(join3(p, cmd + suffix))) {
return true;
}
}
@@ -2162,39 +3912,50 @@ function getAllServers() {
var WORKSPACE_MARKERS = [".git", "package.json", "pyproject.toml", "Cargo.toml", "go.mod", "pom.xml", "build.gradle"];
function isDirectoryPath(filePath) {
try {
- return statSync2(filePath).isDirectory();
+ return statSync3(filePath).isDirectory();
} catch {
return false;
}
}
function findWorkspaceRoot(filePath) {
- const abs = resolve2(contextCwd(), filePath);
+ const abs = resolvePathInsideContext(filePath);
let dir = abs;
if (!isDirectoryPath(dir)) {
- dir = dirname2(dir);
+ dir = dirname6(dir);
}
let prevDir = "";
while (dir !== prevDir) {
for (const marker of WORKSPACE_MARKERS) {
- if (existsSync5(join5(dir, marker))) {
+ if (existsSync9(join4(dir, marker))) {
return dir;
}
}
prevDir = dir;
- dir = dirname2(dir);
+ dir = dirname6(dir);
+ }
+ return dirname6(abs);
+}
+function resolvePathInsideContext(filePath) {
+ const cwd = contextCwd();
+ const abs = resolve7(cwd, filePath);
+ const canonical = canonicalizeExistingOrNearestAncestor(abs);
+ if (!isPathInside(cwd, canonical)) {
+ throw new LspInvalidPathError(`LSP file path must be inside request cwd: ${filePath}`);
}
- return dirname2(abs);
+ return canonical;
}
function formatServerLookupError(result) {
if (result.status === "not_installed") {
return formatNotInstalled(result);
}
+ const context = lspRequestContext();
+ const firstProjectConfigPath = context.projectConfigPaths[0] ?? "<project lsp config>";
return [
`No LSP server configured for extension: ${result.extension}`,
"",
`Available servers: ${result.availableServers.slice(0, 10).join(", ")}${result.availableServers.length > 10 ? "..." : ""}`,
"",
- "Configure a custom server in '.codex/lsp-client.json':",
+ `Configure a custom server in '${firstProjectConfigPath}' or '${context.userConfigPath}':`,
" {",
' "lsp": {',
' "my-server": {',
@@ -2210,6 +3971,7 @@ function formatNotInstalled(result) {
const { server: server2, installHint } = result;
const extensions = server2.extensions.join(", ");
const decision = loadInstallDecision(server2.id)?.decision;
+ const context = lspRequestContext();
if (decision === "declined") {
return `LSP server '${server2.id}' (${extensions}) is NOT INSTALLED; user previously declined installation — proceed without LSP.`;
}
@@ -2225,6 +3987,17 @@ function formatNotInstalled(result) {
"The user has pre-authorized LSP installation. Run the install command, then retry this tool:",
` ${installHint}`
].join(`
+`);
+ }
+ if (!context.capabilities.installDecisionTool) {
+ return [
+ ...header,
+ "To install, run:",
+ ` ${installHint}`,
+ "",
+ "ACTION REQUIRED — ASK THE USER whether to install this LSP server.",
+ "Install-decision recording is unavailable in this harness; proceed without LSP if the user declines."
+ ].join(`
`);
}
return [
@@ -2236,6 +4009,7 @@ function formatNotInstalled(result) {
"- If the user agrees: run the install command above, then retry this tool.",
"- If the user declines, OR has NOT explicitly asked for LSP installation:",
` call lsp_install_decision { server_id: "${server2.id}", decision: "declined" },`,
+ ` which writes to ${context.installDecisionsPath},`,
" then ignore this message and proceed WITHOUT LSP."
].join(`
`);
@@ -2249,14 +4023,14 @@ var READ_ONLY_RETRY_TOOLS = new Set([
"prepareRename"
]);
async function withLspClient(filePath, fn, toolName, options = {}) {
- const absPath = resolve2(contextCwd(), filePath);
+ const absPath = resolvePathInsideContext(filePath);
if (isDirectoryPath(absPath)) {
throw new LspInvalidPathError("Directory paths are not supported by this LSP tool. " + "Use lsp.diagnostics with a directory path for directory diagnostics.");
}
const ext = effectiveExtension(absPath);
const result = findServerForExtension(ext);
if (result.status !== "found") {
- throw new LspServerLookupError(formatServerLookupError(result));
+ throw new LspServerLookupError(formatServerLookupError(result), result);
}
const server2 = result.server;
const root = findWorkspaceRoot(absPath);
@@ -2284,11 +4058,11 @@ async function withLspClient(filePath, fn, toolName, options = {}) {
}
// ../lsp-core/src/lsp/directory-diagnostics.ts
-import { existsSync as existsSync6, lstatSync, readdirSync } from "node:fs";
-import { join as join6, resolve as resolve3 } from "node:path";
+import { existsSync as existsSync10, lstatSync as lstatSync4, readdirSync as readdirSync3 } from "node:fs";
+import { join as join5, resolve as resolve8 } from "node:path";
// ../lsp-core/src/lsp/formatters.ts
-import { fileURLToPath } from "node:url";
+import { fileURLToPath as fileURLToPath2 } from "node:url";
var DIAGNOSTIC_SEVERITY_FILTERS = {
error: 1,
warning: 2,
@@ -2296,7 +4070,7 @@ var DIAGNOSTIC_SEVERITY_FILTERS = {
hint: 4
};
function uriToPath(uri) {
- return fileURLToPath(uri);
+ return fileURLToPath2(uri);
}
function formatLocation(loc) {
if ("targetUri" in loc) {
@@ -2382,6 +4156,9 @@ function formatApplyResult(result) {
for (const file of result.filesModified) {
lines.push(` - ${file}`);
}
+ if (result.lateAbort) {
+ lines.push("Cancellation arrived after the filesystem commit began; the committed edit completed.");
+ }
} else {
lines.push("Failed to apply some changes:");
for (const err of result.errors) {
@@ -2397,6 +4174,7 @@ function formatApplyResult(result) {
// ../lsp-core/src/lsp/directory-diagnostics.ts
var SKIP_DIRECTORIES = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
+var DIRECTORY_DIAGNOSTICS_MAX_CONCURRENCY = 4;
function collectFilesWithExtension(dir, extension, maxFiles) {
const files = [];
function walk(currentDir) {
@@ -2404,17 +4182,17 @@ function collectFilesWithExtension(dir, extension, maxFiles) {
return;
let entries = [];
try {
- entries = readdirSync(currentDir);
+ entries = readdirSync3(currentDir);
} catch {
return;
}
for (const entry of entries) {
if (files.length >= maxFiles)
return;
- const fullPath = join6(currentDir, entry);
+ const fullPath = join5(currentDir, entry);
let stat;
try {
- stat = lstatSync(fullPath);
+ stat = lstatSync4(fullPath);
} catch {
continue;
}
@@ -2432,52 +4210,65 @@ function collectFilesWithExtension(dir, extension, maxFiles) {
walk(dir);
return files;
}
-async function aggregateDiagnosticsForDirectory(directory, extension, severity, maxFiles = DEFAULT_MAX_DIRECTORY_FILES) {
+async function aggregateDiagnosticsForDirectory(directory, extension, severity, maxFiles = DEFAULT_MAX_DIRECTORY_FILES, options = {}) {
if (!extension.startsWith(".")) {
throw new LspInvalidPathError(`Extension must start with a dot (e.g., ".ts", not "${extension}"). Use ".${extension}" instead.`);
}
- const absDir = resolve3(contextCwd(), directory);
- if (!existsSync6(absDir)) {
+ const absDir = resolve8(options.workspaceRoot ?? contextCwd(), directory);
+ if (!existsSync10(absDir)) {
throw new LspInvalidPathError(`Directory does not exist: ${absDir}`);
}
- const serverResult = findServerForExtension(extension);
+ const serverResult = options.server === undefined ? findServerForExtension(extension) : { status: "found", server: options.server };
if (serverResult.status !== "found") {
throw new LspServerLookupError(formatServerLookupError(serverResult));
}
const server2 = serverResult.server;
- const allFiles = collectFilesWithExtension(absDir, extension, maxFiles + 1);
+ const allFiles = (options.listFiles ?? collectFilesWithExtension)(absDir, extension, maxFiles + 1);
const wasCapped = allFiles.length > maxFiles;
const filesToProcess = allFiles.slice(0, maxFiles);
if (filesToProcess.length === 0) {
- return [
+ const output = [
`Directory: ${absDir}`,
`Extension: ${extension}`,
"Files scanned: 0",
`No files found with extension "${extension}".`
].join(`
`);
+ return { output, totalDiagnostics: 0, fileFailures: [] };
}
- const root = findWorkspaceRoot(absDir);
- const manager = getLspManager();
+ const root = options.workspaceRoot ?? findWorkspaceRoot(absDir);
+ const manager = options.manager ?? getLspManager();
const allDiagnostics = [];
const fileErrors = [];
+ const maxConcurrency = Math.max(1, options.maxConcurrency ?? DIRECTORY_DIAGNOSTICS_MAX_CONCURRENCY);
+ options.signal?.throwIfAborted();
const client = await manager.getClient(root, server2);
try {
- for (const file of filesToProcess) {
- try {
- const result = await client.diagnostics(file);
- const filtered = filterDiagnosticsBySeverity(result.items, severity);
- allDiagnostics.push(...filtered.map((diagnostic) => ({
- filePath: file,
- diagnostic
- })));
- } catch (e) {
- fileErrors.push({
- file,
- error: e instanceof Error ? e.message : String(e)
- });
+ let nextIndex = 0;
+ const workers = Array.from({ length: Math.min(maxConcurrency, filesToProcess.length) }, async () => {
+ for (;; ) {
+ if (options.signal?.aborted)
+ return;
+ const file = filesToProcess[nextIndex];
+ nextIndex += 1;
+ if (file === undefined)
+ return;
+ try {
+ const result = await client.diagnostics(file, options.signal);
+ const filtered = filterDiagnosticsBySeverity(result.items, severity);
+ allDiagnostics.push(...filtered.map((diagnostic) => ({
+ filePath: file,
+ diagnostic
+ })));
+ } catch (e) {
+ fileErrors.push({
+ file,
+ error: e instanceof Error ? e.message : String(e)
+ });
+ }
}
- }
+ });
+ await Promise.all(workers);
} finally {
manager.releaseClient(root, server2.id);
}
@@ -2505,13 +4296,13 @@ async function aggregateDiagnosticsForDirectory(directory, extension, severity,
lines.push("", `... (${allDiagnostics.length - DEFAULT_MAX_DIAGNOSTICS} more diagnostics not shown)`);
}
}
- return lines.join(`
-`);
+ return { output: lines.join(`
+`), totalDiagnostics: allDiagnostics.length, fileFailures: fileErrors };
}
// ../lsp-core/src/lsp/infer-extension.ts
-import { lstatSync as lstatSync2, readdirSync as readdirSync2 } from "node:fs";
-import { join as join7 } from "node:path";
+import { lstatSync as lstatSync5, readdirSync as readdirSync4 } from "node:fs";
+import { join as join6 } from "node:path";
var SKIP_DIRECTORIES2 = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
var MAX_SCAN_ENTRIES = 500;
function inferExtensionFromDirectory(directory) {
@@ -2522,17 +4313,17 @@ function inferExtensionFromDirectory(directory) {
return;
let entries;
try {
- entries = readdirSync2(dir);
+ entries = readdirSync4(dir);
} catch {
return;
}
for (const entry of entries) {
if (scanned >= MAX_SCAN_ENTRIES)
return;
- const fullPath = join7(dir, entry);
+ const fullPath = join6(dir, entry);
let stat;
try {
- stat = lstatSync2(fullPath);
+ stat = lstatSync5(fullPath);
} catch {
continue;
}
@@ -2606,13 +4397,48 @@ function missingDependencyResult(error, details) {
details: {
...details,
error: message,
- errorKind: "missing_dependency"
+ errorKind: "missing_dependency",
+ ...availabilityDetails(error)
}
};
}
+function availabilityDetails(error) {
+ const availability = missingDependencyAvailability(error);
+ return availability === null ? {} : { availability };
+}
+function missingDependencyAvailability(error) {
+ if (!(error instanceof LspServerLookupError) || error.lookup === undefined)
+ return null;
+ const context = lspRequestContext();
+ switch (error.lookup.status) {
+ case "not_configured":
+ return {
+ kind: "not_configured",
+ extension: error.lookup.extension,
+ availableServers: [...error.lookup.availableServers],
+ projectConfigPaths: [...context.projectConfigPaths],
+ userConfigPath: context.userConfigPath,
+ installDecisionTool: context.capabilities.installDecisionTool
+ };
+ case "not_installed":
+ return {
+ kind: "not_installed",
+ serverId: error.lookup.server.id,
+ command: [...error.lookup.server.command],
+ extensions: [...error.lookup.server.extensions],
+ installHint: error.lookup.installHint,
+ installDecisionTool: context.capabilities.installDecisionTool,
+ installDecisionsPath: context.installDecisionsPath
+ };
+ default: {
+ const exhaustive = error.lookup;
+ return exhaustive;
+ }
+ }
+}
// ../lsp-core/src/tools/parameters.ts
-function isRecord4(value) {
+function isRecord7(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function requireString(params, key) {
@@ -2669,7 +4495,7 @@ async function executeLspDiagnostics(params, signal) {
const filePath = requireString(params, "filePath");
const severity = severityFilter(params);
try {
- const absPath = resolve4(contextCwd(), filePath);
+ const absPath = resolvePathInsideContext(filePath);
if (isDirectoryPath(absPath)) {
const extension = inferExtensionFromDirectory(absPath);
if (!extension) {
@@ -2686,18 +4512,33 @@ async function executeLspDiagnostics(params, signal) {
};
return text(message, details3);
}
- const output2 = await aggregateDiagnosticsForDirectory(absPath, extension, severity);
+ const output2 = await aggregateDiagnosticsForDirectory(absPath, extension, severity, undefined, signal === undefined ? {} : { signal });
const details2 = {
filePath,
severity,
mode: "directory",
diagnostics: [],
+ totalDiagnostics: output2.totalDiagnostics,
+ truncated: false,
+ fileFailures: [...output2.fileFailures]
+ };
+ return text(output2.output, details2);
+ }
+ const result = await withLspClient(filePath, async (client) => client.diagnostics(filePath, signal), "diagnostics", clientOptions(signal));
+ if (result.transientError) {
+ const message = result.transientError.message;
+ const details2 = {
+ filePath,
+ severity,
+ mode: "file",
+ diagnostics: [],
totalDiagnostics: 0,
- truncated: false
+ truncated: false,
+ error: message,
+ errorKind: result.transientError.kind
};
- return text(output2, details2);
+ return text(message, details2, true);
}
- const result = await withLspClient(filePath, async (client) => client.diagnostics(filePath), "diagnostics", clientOptions(signal));
const diagnostics = filterDiagnosticsBySeverity(asDiagnosticArray(result), severity);
const total = diagnostics.length;
const truncated = total > DEFAULT_MAX_DIAGNOSTICS;
@@ -2758,7 +4599,7 @@ async function executeLspGotoDefinition(params, signal) {
const line = requireNumber(params, "line");
const character = requireNumber(params, "character");
try {
- const result = await withLspClient(filePath, async (client) => client.definition(filePath, line, character), "definition", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.definition(filePath, line, character, signal), "definition", clientOptions(signal));
const locations = !result ? [] : Array.isArray(result) ? result : [result];
const details = { filePath, line, character, locations };
if (locations.length === 0)
@@ -2783,7 +4624,7 @@ async function executeLspFindReferences(params, signal) {
const character = requireNumber(params, "character");
const includeDeclaration = optionalBoolean(params, "includeDeclaration") ?? true;
try {
- const result = await withLspClient(filePath, async (client) => client.references(filePath, line, character, includeDeclaration), "references", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.references(filePath, line, character, includeDeclaration, signal), "references", clientOptions(signal));
const references = Array.isArray(result) ? result : [];
const total = references.length;
const truncated = total > DEFAULT_MAX_REFERENCES;
@@ -2819,181 +4660,13 @@ async function executeLspFindReferences(params, signal) {
}
}
-// ../lsp-core/src/lsp/workspace-edit.ts
-import { existsSync as existsSync7, readFileSync as readFileSync4, realpathSync, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
-import { dirname as dirname3, isAbsolute as isAbsolute3, relative, resolve as resolve5 } from "node:path";
-import { fileURLToPath as fileURLToPath2 } from "node:url";
-function errorMessage2(error) {
- return error instanceof Error ? error.message : String(error);
-}
-function isPathInsideWorkspace(filePath, workspaceRoot) {
- const relativePath = relative(workspaceRoot, filePath);
- return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute3(relativePath);
-}
-function realpathForValidation(filePath) {
- if (existsSync7(filePath))
- return realpathSync(filePath);
- const parent = dirname3(filePath);
- return resolve5(realpathSync(parent), relative(parent, filePath));
-}
-function uriToWorkspacePath(uri, workspaceRoot) {
- let filePath;
- try {
- filePath = fileURLToPath2(uri);
- } catch (error) {
- return { success: false, error: `non-file URI ${uri}: ${errorMessage2(error)}` };
- }
- let validatedPath;
- try {
- validatedPath = realpathForValidation(filePath);
- } catch (error) {
- return { success: false, error: `${filePath}: ${errorMessage2(error)}` };
- }
- if (!isPathInsideWorkspace(validatedPath, workspaceRoot)) {
- return { success: false, error: `${filePath}: outside workspace ${workspaceRoot}` };
- }
- return { success: true, path: filePath };
-}
-function applyTextEditsToFile(filePath, edits) {
- try {
- const content = readFileSync4(filePath, "utf-8");
- const lines = content.split(`
-`);
- const sortedEdits = [...edits].sort((a, b) => {
- if (b.range.start.line !== a.range.start.line) {
- return b.range.start.line - a.range.start.line;
- }
- return b.range.start.character - a.range.start.character;
- });
- for (const edit of sortedEdits) {
- const startLine = edit.range.start.line;
- const startChar = edit.range.start.character;
- const endLine = edit.range.end.line;
- const endChar = edit.range.end.character;
- if (startLine === endLine) {
- const line = lines[startLine] ?? "";
- lines[startLine] = line.substring(0, startChar) + edit.newText + line.substring(endChar);
- } else {
- const firstLine = lines[startLine] ?? "";
- const lastLine = lines[endLine] ?? "";
- const newContent = firstLine.substring(0, startChar) + edit.newText + lastLine.substring(endChar);
- lines.splice(startLine, endLine - startLine + 1, ...newContent.split(`
-`));
- }
- }
- writeFileSync2(filePath, lines.join(`
-`), "utf-8");
- return { success: true, editCount: edits.length };
- } catch (err) {
- return {
- success: false,
- editCount: 0,
- error: err instanceof Error ? err.message : String(err)
- };
- }
-}
-function applyWorkspaceEdit(edit, options = {}) {
- if (!edit) {
- return { success: false, filesModified: [], totalEdits: 0, errors: ["No edit provided"] };
- }
- const result = { success: true, filesModified: [], totalEdits: 0, errors: [] };
- const workspaceRoot = realpathSync(options.workspaceRoot ?? contextCwd());
- if (edit.changes) {
- for (const [uri, edits] of Object.entries(edit.changes)) {
- const validatedPath = uriToWorkspacePath(uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(validatedPath.error);
- continue;
- }
- const applyResult = applyTextEditsToFile(validatedPath.path, edits);
- if (applyResult.success) {
- result.filesModified.push(validatedPath.path);
- result.totalEdits += applyResult.editCount;
- } else {
- result.success = false;
- result.errors.push(`${validatedPath.path}: ${applyResult.error}`);
- }
- }
- }
- if (edit.documentChanges) {
- for (const change of edit.documentChanges) {
- if (!("kind" in change)) {
- const validatedPath = uriToWorkspacePath(change.textDocument.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(validatedPath.error);
- continue;
- }
- const applyResult = applyTextEditsToFile(validatedPath.path, change.edits);
- if (applyResult.success) {
- result.filesModified.push(validatedPath.path);
- result.totalEdits += applyResult.editCount;
- } else {
- result.success = false;
- result.errors.push(`${validatedPath.path}: ${applyResult.error}`);
- }
- continue;
- }
- if (change.kind === "create") {
- try {
- const validatedPath = uriToWorkspacePath(change.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(`Create ${change.uri}: ${validatedPath.error}`);
- continue;
- }
- writeFileSync2(validatedPath.path, "", "utf-8");
- result.filesModified.push(validatedPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Create ${change.uri}: ${String(err)}`);
- }
- } else if (change.kind === "rename") {
- try {
- const oldPath = uriToWorkspacePath(change.oldUri, workspaceRoot);
- const newPath = uriToWorkspacePath(change.newUri, workspaceRoot);
- if (!oldPath.success || !newPath.success) {
- const error = oldPath.success ? newPath.success ? "invalid URI" : newPath.error : oldPath.error;
- result.success = false;
- result.errors.push(`Rename ${change.oldUri}: ${error}`);
- continue;
- }
- const content = readFileSync4(oldPath.path, "utf-8");
- writeFileSync2(newPath.path, content, "utf-8");
- unlinkSync(oldPath.path);
- result.filesModified.push(newPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Rename ${change.oldUri}: ${String(err)}`);
- }
- } else if (change.kind === "delete") {
- try {
- const validatedPath = uriToWorkspacePath(change.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(`Delete ${change.uri}: ${validatedPath.error}`);
- continue;
- }
- unlinkSync(validatedPath.path);
- result.filesModified.push(validatedPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Delete ${change.uri}: ${String(err)}`);
- }
- }
- }
- }
- return result;
-}
-
// ../lsp-core/src/tools/rename.ts
async function executeLspPrepareRename(params, signal) {
const filePath = requireString(params, "filePath");
const line = requireNumber(params, "line");
const character = requireNumber(params, "character");
try {
- const result = await withLspClient(filePath, async (client) => client.prepareRename(filePath, line, character), "prepareRename", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.prepareRename(filePath, line, character, signal), "prepareRename", clientOptions(signal));
const details = { filePath, line, character, result };
return text(formatPrepareRenameResult(result), details);
} catch (error) {
@@ -3014,13 +4687,9 @@ async function executeLspRename(params, signal) {
const character = requireNumber(params, "character");
const newName = requireString(params, "newName");
try {
- const edit = await withLspClient(filePath, async (client, workspaceRoot) => ({
- edit: await client.rename(filePath, line, character, newName),
- workspaceRoot
- }), "rename", clientOptions(signal));
- const apply = applyWorkspaceEdit(edit.edit, { workspaceRoot: edit.workspaceRoot });
- const details = { filePath, line, character, newName, apply, edit: edit.edit };
- return text(formatApplyResult(apply), details, !apply.success);
+ const result = await withLspClient(filePath, async (client) => client.rename(filePath, line, character, newName, signal), "rename", clientOptions(signal));
+ const details = { filePath, line, character, newName, apply: result.apply, edit: result.edit };
+ return text(formatApplyResult(result.apply), details, !result.apply.success);
} catch (error) {
const missingDependency = missingDependencyResult(error, {
filePath,
@@ -3095,10 +4764,10 @@ async function executeLspSymbols(params, signal) {
errorKind: "missing_query"
});
}
- const symbols2 = await withLspClient(filePath, async (client) => client.workspaceSymbols(query), "workspaceSymbols", clientOptions(signal));
+ const symbols2 = await withLspClient(filePath, async (client) => client.workspaceSymbols(query, signal), "workspaceSymbols", clientOptions(signal));
return formatSymbolsResult(filePath, scope, symbols2, limit, query);
}
- const symbols = await withLspClient(filePath, async (client) => client.documentSymbols(filePath), "documentSymbols", clientOptions(signal));
+ const symbols = await withLspClient(filePath, async (client) => client.documentSymbols(filePath, signal), "documentSymbols", clientOptions(signal));
return formatSymbolsResult(filePath, scope, symbols, limit);
} catch (error) {
const query = optionalString(params, "query");
@@ -3264,12 +4933,12 @@ function matchesToolName(tool, name) {
return tool.name === name || (tool.aliases?.includes(name) ?? false);
}
function coerceToolArguments(value) {
- return isRecord4(value) ? value : {};
+ return isRecord7(value) ? value : {};
}
// ../lsp-core/src/mcp.ts
var SERVER_NAME = "lsp";
var SERVER_VERSION = "0.1.0";
-async function handleLspMcpRequest(input) {
+async function handleLspMcpRequest(input, options = {}) {
if (!isPlainRecord(input)) {
return errorResponse(null, -32600, "Invalid Request");
}
@@ -3291,33 +4960,37 @@ async function handleLspMcpRequest(input) {
return successResponse(id, { tools: LSP_MCP_TOOLS.map(describeTool) });
}
if (method === "tools/call") {
- return handleToolCall(id, input["params"]);
+ return handleToolCall(id, input["params"], options.signal);
}
return errorResponse(id, -32601, `Method not found: ${String(method)}`);
}
async function runMcpStdioServer(input = process.stdin, output = process.stdout) {
+ const requestContext = createStandaloneMcpRequestContext();
await runJsonRpcStdioServer({
input,
output,
idleTimeoutMs: 0,
- handler: handleLspMcpRequest,
+ handler: (request) => runWithRequestContext(requestContext, () => handleLspMcpRequest(request)),
handlerOptions: undefined
});
}
-async function handleToolCall(id, params) {
+async function handleToolCall(id, params, signal) {
if (!isPlainRecord(params) || typeof params["name"] !== "string") {
return errorResponse(id, -32602, "tools/call requires params.name");
}
try {
- const result = await executeLspTool(params["name"], coerceToolArguments(params["arguments"]));
+ const result = await executeLspTool(params["name"], coerceToolArguments(params["arguments"]), signal);
return successResponse(id, {
content: result.content,
isError: result.isError ?? false,
details: result.details
});
} catch (error) {
+ if (!(error instanceof Error)) {
+ throw error;
+ }
return successResponse(id, {
- content: [{ type: "text", text: messageFromError(error) }],
+ content: [{ type: "text", text: error.message }],
isError: true
});
}
diff --git a/plugins/omo/components/lsp-tools-mcp/dist/request-context.js b/plugins/omo/components/lsp-tools-mcp/dist/request-context.js
index 48a464e2..77715f38 100644
--- a/plugins/omo/components/lsp-tools-mcp/dist/request-context.js
+++ b/plugins/omo/components/lsp-tools-mcp/dist/request-context.js
@@ -1,20 +1,190 @@
// ../lsp-core/src/request-context.ts
import { AsyncLocalStorage } from "node:async_hooks";
+import { existsSync, realpathSync, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from "node:path";
+
+class LspRequestContextParseError extends Error {
+ code;
+ name = "LspRequestContextParseError";
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ }
+}
+
+class LspRequestContextUnavailableError extends Error {
+ name = "LspRequestContextUnavailableError";
+ constructor() {
+ super("LSP request context is required. Standalone MCP startup must install one with runWithRequestContext(createStandaloneMcpRequestContext()).");
+ }
+}
var storage = new AsyncLocalStorage;
+var CONTEXT_FIELDS = new Set(["cwd", "projectConfigPaths", "userConfigPath", "installDecisionsPath", "capabilities"]);
+var CAPABILITY_FIELDS = new Set(["installDecisionTool"]);
function runWithRequestContext(context, fn) {
return storage.run(context, fn);
}
+function lspRequestContext() {
+ const context = storage.getStore();
+ if (!context)
+ throw new LspRequestContextUnavailableError;
+ return context;
+}
function contextCwd() {
- return storage.getStore()?.cwd ?? process.cwd();
+ return lspRequestContext().cwd;
}
function contextEnv(key) {
- const store = storage.getStore();
- if (store?.env)
- return store.env[key];
- return process.env[key];
+ const context = lspRequestContext();
+ if (key === "LSP_TOOLS_MCP_PROJECT_CONFIG")
+ return context.projectConfigPaths.join(delimiter);
+ if (key === "LSP_TOOLS_MCP_USER_CONFIG")
+ return context.userConfigPath;
+ if (key === "LSP_TOOLS_MCP_INSTALL_DECISIONS")
+ return context.installDecisionsPath;
+ return;
+}
+function createStandaloneMcpRequestContext(input = {}) {
+ const env = input.env ?? process.env;
+ const cwd = canonicalCwd(input.cwd ?? process.cwd());
+ const home = input.homeDir ?? homedir();
+ const projectConfigPaths = translateProjectConfigEnv(env["LSP_TOOLS_MCP_PROJECT_CONFIG"], cwd);
+ const userConfigPath = translateHomeConfigEnv(env["LSP_TOOLS_MCP_USER_CONFIG"], home, ".codex/lsp-client.json");
+ const installDecisionsPath = translateHomeConfigEnv(env["LSP_TOOLS_MCP_INSTALL_DECISIONS"], home, ".codex/lsp-install-decisions.json");
+ return parseLspRequestContext({
+ cwd,
+ projectConfigPaths,
+ userConfigPath,
+ installDecisionsPath,
+ capabilities: { installDecisionTool: true }
+ });
+}
+function parseLspRequestContext(value) {
+ if (!isRecord(value)) {
+ throw new LspRequestContextParseError("invalid_context", "LSP request context must be an object.");
+ }
+ rejectUnknownFields(value, CONTEXT_FIELDS, "context");
+ const cwd = stringField(value, "cwd");
+ const projectConfigPaths = stringArrayField(value, "projectConfigPaths");
+ const userConfigPath = stringField(value, "userConfigPath");
+ const installDecisionsPath = stringField(value, "installDecisionsPath");
+ const capabilities = capabilitiesField(value["capabilities"]);
+ const canonical = canonicalCwd(cwd);
+ for (const path of projectConfigPaths) {
+ requireAbsolutePath(path, "projectConfigPaths");
+ const projectPath = canonicalizeExistingOrNearestAncestor(path);
+ if (!isPathInside(canonical, projectPath)) {
+ throw new LspRequestContextParseError("project_config_outside_cwd", `Project LSP config path must be inside cwd: ${path}`);
+ }
+ }
+ requireAbsolutePath(userConfigPath, "userConfigPath");
+ requireAbsolutePath(installDecisionsPath, "installDecisionsPath");
+ return {
+ cwd: canonical,
+ projectConfigPaths: projectConfigPaths.map((path) => canonicalizeExistingOrNearestAncestor(path)),
+ userConfigPath,
+ installDecisionsPath,
+ capabilities
+ };
+}
+function translateProjectConfigEnv(value, cwd) {
+ if (value === undefined || value.length === 0)
+ return [join(cwd, ".codex", "lsp-client.json")];
+ return value.split(delimiter).filter((entry) => entry.length > 0).map((entry) => isAbsolute(entry) ? entry : join(cwd, entry));
+}
+function translateHomeConfigEnv(value, home, fallback) {
+ if (value === undefined || value.length === 0)
+ return join(home, fallback);
+ return isAbsolute(value) ? value : join(home, value);
+}
+function canonicalCwd(cwd) {
+ const resolved = resolve(cwd);
+ if (!existsSync(resolved) || !statSync(resolved).isDirectory()) {
+ throw new LspRequestContextParseError("invalid_cwd", `LSP request cwd must be an existing directory: ${cwd}`);
+ }
+ return realpathSync(resolved);
+}
+function canonicalizeExistingOrNearestAncestor(path) {
+ let current = resolve(path);
+ const suffix = [];
+ while (true) {
+ try {
+ const existing = realpathSync(current);
+ return suffix.length === 0 ? existing : join(existing, ...suffix);
+ } catch (error) {
+ if (!isMissingPathError(error))
+ throw error;
+ const parent = dirname(current);
+ if (parent === current)
+ throw error;
+ suffix.unshift(basename(current));
+ current = parent;
+ }
+ }
+}
+function capabilitiesField(value) {
+ if (!isRecord(value)) {
+ throw new LspRequestContextParseError("invalid_capabilities", "LSP request capabilities must be an object.");
+ }
+ rejectUnknownFields(value, CAPABILITY_FIELDS, "capabilities");
+ const installDecisionTool = value["installDecisionTool"];
+ if (typeof installDecisionTool !== "boolean") {
+ throw new LspRequestContextParseError("invalid_install_decision_capability", "LSP request capabilities.installDecisionTool must be a boolean.");
+ }
+ return { installDecisionTool };
+}
+function stringField(value, field) {
+ const fieldValue = value[field];
+ if (typeof fieldValue !== "string" || fieldValue.length === 0) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string.`);
+ }
+ return fieldValue;
+}
+function stringArrayField(value, field) {
+ const fieldValue = value[field];
+ if (!Array.isArray(fieldValue) || !fieldValue.every((item) => typeof item === "string" && item.length > 0)) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string array.`);
+ }
+ return fieldValue;
+}
+function requireAbsolutePath(path, field) {
+ if (!isAbsolute(path)) {
+ throw new LspRequestContextParseError("relative_path", `LSP request context.${field} must be absolute: ${path}`);
+ }
+}
+function isPathInside(parent, child) {
+ const childPath = resolve(child);
+ const relativePath = relative(parent, childPath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute(relativePath);
+}
+function isMissingPathError(error) {
+ const code = errorCode(error);
+ return code === "ENOENT" || code === "ENOTDIR";
+}
+function rejectUnknownFields(value, allowed, scope) {
+ const unknown = Object.keys(value).filter((key) => !allowed.has(key));
+ if (unknown.length > 0) {
+ throw new LspRequestContextParseError("unknown_field", `Unknown LSP request ${scope} field: ${unknown.join(", ")}`);
+ }
+}
+function isRecord(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function errorCode(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
}
export {
runWithRequestContext,
+ parseLspRequestContext,
+ lspRequestContext,
+ isPathInside,
+ createStandaloneMcpRequestContext,
contextEnv,
- contextCwd
+ contextCwd,
+ canonicalizeExistingOrNearestAncestor,
+ LspRequestContextUnavailableError,
+ LspRequestContextParseError
};
diff --git a/plugins/omo/components/lsp-tools-mcp/dist/tools.js b/plugins/omo/components/lsp-tools-mcp/dist/tools.js
index 4f3f9c5a..7e7d37bf 100644
--- a/plugins/omo/components/lsp-tools-mcp/dist/tools.js
+++ b/plugins/omo/components/lsp-tools-mcp/dist/tools.js
@@ -1,34 +1,194 @@
-// ../lsp-core/src/tools/diagnostics.ts
-import { resolve as resolve4 } from "node:path";
-
// ../lsp-core/src/lsp/client-wrapper.ts
-import { existsSync as existsSync5, statSync as statSync2 } from "node:fs";
-import { dirname as dirname2, join as join5, resolve as resolve2 } from "node:path";
+import { existsSync as existsSync9, statSync as statSync3 } from "node:fs";
+import { dirname as dirname6, join as join4, resolve as resolve7 } from "node:path";
// ../lsp-core/src/request-context.ts
import { AsyncLocalStorage } from "node:async_hooks";
+import { existsSync, realpathSync, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from "node:path";
+
+class LspRequestContextParseError extends Error {
+ code;
+ name = "LspRequestContextParseError";
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ }
+}
+
+class LspRequestContextUnavailableError extends Error {
+ name = "LspRequestContextUnavailableError";
+ constructor() {
+ super("LSP request context is required. Standalone MCP startup must install one with runWithRequestContext(createStandaloneMcpRequestContext()).");
+ }
+}
var storage = new AsyncLocalStorage;
+var CONTEXT_FIELDS = new Set(["cwd", "projectConfigPaths", "userConfigPath", "installDecisionsPath", "capabilities"]);
+var CAPABILITY_FIELDS = new Set(["installDecisionTool"]);
function runWithRequestContext(context, fn) {
return storage.run(context, fn);
}
+function lspRequestContext() {
+ const context = storage.getStore();
+ if (!context)
+ throw new LspRequestContextUnavailableError;
+ return context;
+}
function contextCwd() {
- return storage.getStore()?.cwd ?? process.cwd();
+ return lspRequestContext().cwd;
}
function contextEnv(key) {
- const store = storage.getStore();
- if (store?.env)
- return store.env[key];
- return process.env[key];
+ const context = lspRequestContext();
+ if (key === "LSP_TOOLS_MCP_PROJECT_CONFIG")
+ return context.projectConfigPaths.join(delimiter);
+ if (key === "LSP_TOOLS_MCP_USER_CONFIG")
+ return context.userConfigPath;
+ if (key === "LSP_TOOLS_MCP_INSTALL_DECISIONS")
+ return context.installDecisionsPath;
+ return;
+}
+function createStandaloneMcpRequestContext(input = {}) {
+ const env = input.env ?? process.env;
+ const cwd = canonicalCwd(input.cwd ?? process.cwd());
+ const home = input.homeDir ?? homedir();
+ const projectConfigPaths = translateProjectConfigEnv(env["LSP_TOOLS_MCP_PROJECT_CONFIG"], cwd);
+ const userConfigPath = translateHomeConfigEnv(env["LSP_TOOLS_MCP_USER_CONFIG"], home, ".codex/lsp-client.json");
+ const installDecisionsPath = translateHomeConfigEnv(env["LSP_TOOLS_MCP_INSTALL_DECISIONS"], home, ".codex/lsp-install-decisions.json");
+ return parseLspRequestContext({
+ cwd,
+ projectConfigPaths,
+ userConfigPath,
+ installDecisionsPath,
+ capabilities: { installDecisionTool: true }
+ });
+}
+function parseLspRequestContext(value) {
+ if (!isRecord(value)) {
+ throw new LspRequestContextParseError("invalid_context", "LSP request context must be an object.");
+ }
+ rejectUnknownFields(value, CONTEXT_FIELDS, "context");
+ const cwd = stringField(value, "cwd");
+ const projectConfigPaths = stringArrayField(value, "projectConfigPaths");
+ const userConfigPath = stringField(value, "userConfigPath");
+ const installDecisionsPath = stringField(value, "installDecisionsPath");
+ const capabilities = capabilitiesField(value["capabilities"]);
+ const canonical = canonicalCwd(cwd);
+ for (const path of projectConfigPaths) {
+ requireAbsolutePath(path, "projectConfigPaths");
+ const projectPath = canonicalizeExistingOrNearestAncestor(path);
+ if (!isPathInside(canonical, projectPath)) {
+ throw new LspRequestContextParseError("project_config_outside_cwd", `Project LSP config path must be inside cwd: ${path}`);
+ }
+ }
+ requireAbsolutePath(userConfigPath, "userConfigPath");
+ requireAbsolutePath(installDecisionsPath, "installDecisionsPath");
+ return {
+ cwd: canonical,
+ projectConfigPaths: projectConfigPaths.map((path) => canonicalizeExistingOrNearestAncestor(path)),
+ userConfigPath,
+ installDecisionsPath,
+ capabilities
+ };
+}
+function translateProjectConfigEnv(value, cwd) {
+ if (value === undefined || value.length === 0)
+ return [join(cwd, ".codex", "lsp-client.json")];
+ return value.split(delimiter).filter((entry) => entry.length > 0).map((entry) => isAbsolute(entry) ? entry : join(cwd, entry));
+}
+function translateHomeConfigEnv(value, home, fallback) {
+ if (value === undefined || value.length === 0)
+ return join(home, fallback);
+ return isAbsolute(value) ? value : join(home, value);
+}
+function canonicalCwd(cwd) {
+ const resolved = resolve(cwd);
+ if (!existsSync(resolved) || !statSync(resolved).isDirectory()) {
+ throw new LspRequestContextParseError("invalid_cwd", `LSP request cwd must be an existing directory: ${cwd}`);
+ }
+ return realpathSync(resolved);
+}
+function canonicalizeExistingOrNearestAncestor(path) {
+ let current = resolve(path);
+ const suffix = [];
+ while (true) {
+ try {
+ const existing = realpathSync(current);
+ return suffix.length === 0 ? existing : join(existing, ...suffix);
+ } catch (error) {
+ if (!isMissingPathError(error))
+ throw error;
+ const parent = dirname(current);
+ if (parent === current)
+ throw error;
+ suffix.unshift(basename(current));
+ current = parent;
+ }
+ }
+}
+function capabilitiesField(value) {
+ if (!isRecord(value)) {
+ throw new LspRequestContextParseError("invalid_capabilities", "LSP request capabilities must be an object.");
+ }
+ rejectUnknownFields(value, CAPABILITY_FIELDS, "capabilities");
+ const installDecisionTool = value["installDecisionTool"];
+ if (typeof installDecisionTool !== "boolean") {
+ throw new LspRequestContextParseError("invalid_install_decision_capability", "LSP request capabilities.installDecisionTool must be a boolean.");
+ }
+ return { installDecisionTool };
+}
+function stringField(value, field) {
+ const fieldValue = value[field];
+ if (typeof fieldValue !== "string" || fieldValue.length === 0) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string.`);
+ }
+ return fieldValue;
+}
+function stringArrayField(value, field) {
+ const fieldValue = value[field];
+ if (!Array.isArray(fieldValue) || !fieldValue.every((item) => typeof item === "string" && item.length > 0)) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string array.`);
+ }
+ return fieldValue;
+}
+function requireAbsolutePath(path, field) {
+ if (!isAbsolute(path)) {
+ throw new LspRequestContextParseError("relative_path", `LSP request context.${field} must be absolute: ${path}`);
+ }
+}
+function isPathInside(parent, child) {
+ const childPath = resolve(child);
+ const relativePath = relative(parent, childPath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute(relativePath);
+}
+function isMissingPathError(error) {
+ const code = errorCode(error);
+ return code === "ENOENT" || code === "ENOTDIR";
+}
+function rejectUnknownFields(value, allowed, scope) {
+ const unknown = Object.keys(value).filter((key) => !allowed.has(key));
+ if (unknown.length > 0) {
+ throw new LspRequestContextParseError("unknown_field", `Unknown LSP request ${scope} field: ${unknown.join(", ")}`);
+ }
+}
+function isRecord(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function errorCode(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
}
// ../lsp-core/src/lsp/effective-extension.ts
-import { basename, extname } from "node:path";
+import { basename as basename2, extname } from "node:path";
var BASENAME_EXTENSIONS = {
Dockerfile: ".dockerfile",
Containerfile: ".dockerfile"
};
function effectiveExtension(filePath) {
- return BASENAME_EXTENSIONS[basename(filePath)] ?? extname(filePath);
+ return BASENAME_EXTENSIONS[basename2(filePath)] ?? extname(filePath);
}
// ../lsp-core/src/lsp/errors.ts
@@ -78,7 +238,12 @@ class LspInvalidPathError extends Error {
}
class LspServerLookupError extends Error {
+ lookup;
name = "LspServerLookupError";
+ constructor(message, lookup) {
+ super(message);
+ this.lookup = lookup;
+ }
}
class LspServerInitializingError extends Error {
@@ -98,17 +263,18 @@ function isLspDeadConnectionError(err) {
}
// ../lsp-core/src/lsp/cleanup-errors.ts
-function reportBestEffortCleanupError(operation, error) {
- if (process.env["CODEX_LSP_DEBUG_CLEANUP"] !== "1")
- return;
+function writeCleanupError(message) {
+ process.stderr.write(`${message}
+`);
+}
+function reportBestEffortCleanupError(operation, error, logger = writeCleanupError) {
const message = error instanceof Error ? error.message : String(error);
- console.error(`[codex-lsp] ignored ${operation} failure during cleanup: ${message}`);
+ logger(`[lsp] ignored ${operation} failure during cleanup: ${message}`);
}
// ../lsp-core/src/lsp/client.ts
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
-import { pathToFileURL as pathToFileURL2 } from "node:url";
+import { resolve as resolve6 } from "node:path";
+import { pathToFileURL as pathToFileURL3 } from "node:url";
// ../lsp-core/src/lsp/connection.ts
import { pathToFileURL } from "node:url";
@@ -172,28 +338,80 @@ class JsonRpcConnection {
onError(handler) {
this.errorHandlers.push(handler);
}
- async sendRequest(method, params) {
+ async sendRequest(method, params, options = {}) {
if (this.disposed)
throw new Error("JSON-RPC connection is disposed");
const id = this.nextRequestId;
this.nextRequestId += 1;
+ const key = String(id);
const message = params === undefined ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
- const responsePromise = new Promise((resolve, reject) => {
- this.pendingRequests.set(String(id), {
+ let requestWritten = false;
+ let cancelAfterWrite = false;
+ let settled = false;
+ const writeCancel = () => this.writeMessage({ jsonrpc: "2.0", method: "$/cancelRequest", params: { id } });
+ const responsePromise = new Promise((resolve2, reject) => {
+ const cleanup = () => {
+ options.signal?.removeEventListener("abort", onAbort);
+ };
+ const settleCancel = () => {
+ if (settled)
+ return;
+ settled = true;
+ this.pendingRequests.delete(key);
+ cleanup();
+ const rejectCancelled = () => reject(abortError(options.signal));
+ if (!requestWritten) {
+ cancelAfterWrite = true;
+ rejectCancelled();
+ return;
+ }
+ writeCancel().then(rejectCancelled, (error) => {
+ this.emitError(toError(error));
+ rejectCancelled();
+ });
+ };
+ const onAbort = () => settleCancel();
+ this.pendingRequests.set(key, {
resolve(result) {
- resolve(result);
+ settled = true;
+ cleanup();
+ resolve2(result);
},
- reject
+ reject(error) {
+ settled = true;
+ cleanup();
+ reject(error);
+ },
+ cleanup
});
+ if (options.signal?.aborted) {
+ settleCancel();
+ return;
+ }
+ options.signal?.addEventListener("abort", onAbort, { once: true });
});
+ if (settled)
+ return responsePromise;
try {
await this.writeMessage(message);
+ requestWritten = true;
+ if (cancelAfterWrite)
+ await writeCancel();
} catch (error) {
- this.pendingRequests.delete(String(id));
+ if (settled)
+ return responsePromise;
+ const pending = this.pendingRequests.get(key);
+ if (pending) {
+ pending.cleanup();
+ this.pendingRequests.delete(key);
+ }
throw error;
}
return responsePromise;
}
+ pendingRequestCount() {
+ return this.pendingRequests.size;
+ }
async sendNotification(method, params) {
if (this.disposed)
return;
@@ -210,6 +428,7 @@ class JsonRpcConnection {
this.reader.off("error", this.handleStreamError);
this.writer.off("error", this.handleStreamError);
for (const pending of this.pendingRequests.values()) {
+ pending.cleanup();
pending.reject(new Error("JSON-RPC connection disposed"));
}
this.pendingRequests.clear();
@@ -285,6 +504,7 @@ class JsonRpcConnection {
if (!pending)
return;
this.pendingRequests.delete(String(id));
+ pending.cleanup();
if ("error" in message) {
pending.reject(jsonRpcErrorToError(message["error"]));
return;
@@ -298,7 +518,11 @@ class JsonRpcConnection {
try {
handler(params);
} catch (error) {
- this.emitError(toError(error));
+ if (error instanceof Error) {
+ this.emitError(error);
+ return;
+ }
+ this.emitError(new Error(String(error)));
}
}
handleRequest(message) {
@@ -323,13 +547,13 @@ class JsonRpcConnection {
const payload = `Content-Length: ${Buffer.byteLength(body, "utf8")}\r
\r
${body}`;
- return new Promise((resolve, reject) => {
+ return new Promise((resolve2, reject) => {
this.writer.write(payload, (error) => {
if (error) {
reject(error);
return;
}
- resolve();
+ resolve2();
});
});
}
@@ -339,6 +563,14 @@ ${body}`;
}
}
}
+function abortError(signal) {
+ const reason = signal?.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "LSP request cancelled");
+ error.name = "AbortError";
+ return error;
+}
function parseContentLength(headers) {
for (const line of headers.split(`\r
`)) {
@@ -378,8 +610,8 @@ function toError(error) {
// ../lsp-core/src/lsp/process.ts
import { spawn, spawnSync } from "node:child_process";
-import { existsSync, statSync } from "node:fs";
-import { delimiter, join } from "node:path";
+import { existsSync as existsSync2, statSync as statSync2 } from "node:fs";
+import { delimiter as delimiter2, join as join2 } from "node:path";
function isMissingProcessError(error) {
if (!(error instanceof Error) || !("code" in error))
return false;
@@ -392,10 +624,10 @@ function reportKillError(context, error) {
}
function validateCwd(cwd) {
try {
- if (!existsSync(cwd)) {
+ if (!existsSync2(cwd)) {
return { valid: false, error: `Working directory does not exist: ${cwd}` };
}
- const stats = statSync(cwd);
+ const stats = statSync2(cwd);
if (!stats.isDirectory()) {
return { valid: false, error: `Path is not a directory: ${cwd}` };
}
@@ -408,9 +640,9 @@ function validateCwd(cwd) {
}
}
function wrap(proc) {
- const exitedPromise = new Promise((resolve) => {
- proc.once("close", (code) => resolve(code ?? 0));
- proc.once("error", () => resolve(1));
+ const exitedPromise = new Promise((resolve2) => {
+ proc.once("close", (code) => resolve2(code ?? 0));
+ proc.once("error", () => resolve2(1));
});
if (!proc.stdin || !proc.stdout || !proc.stderr) {
throw new LspProcessSpawnError("Spawned process is missing one of stdin/stdout/stderr pipes");
@@ -464,7 +696,7 @@ function isWindowsShellShim(command) {
return lowerCommand.endsWith(".cmd") || lowerCommand.endsWith(".bat");
}
function splitPath(pathValue, platform) {
- const separator = platform === "win32" ? ";" : delimiter;
+ const separator = platform === "win32" ? ";" : delimiter2;
return pathValue.split(separator).filter(Boolean);
}
function getWindowsPathExtensions(env) {
@@ -479,8 +711,8 @@ function resolveWindowsCommand(command, env) {
const extensions = getWindowsPathExtensions(env);
for (const baseDirectory of baseDirectories) {
for (const extension of extensions) {
- const candidate = baseDirectory ? join(baseDirectory, `${command}${extension}`) : `${command}${extension}`;
- if (existsSync(candidate))
+ const candidate = baseDirectory ? join2(baseDirectory, `${command}${extension}`) : `${command}${extension}`;
+ if (existsSync2(candidate))
return candidate;
}
}
@@ -525,16 +757,16 @@ function spawnProcess(command, options) {
return wrap(proc);
}
-// ../lsp-core/src/lsp/transport.ts
-function isRecord(value) {
+// ../lsp-core/src/lsp/transport-protocol.ts
+function isRecord2(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function parseConfigurationItems(params) {
- if (!isRecord(params) || !Array.isArray(params["items"]))
+ if (!isRecord2(params) || !Array.isArray(params["items"]))
return [];
const items = [];
for (const item of params["items"]) {
- if (!isRecord(item))
+ if (!isRecord2(item))
continue;
const section = item["section"];
items.push(section === undefined || typeof section !== "string" ? {} : { section });
@@ -542,10 +774,35 @@ function parseConfigurationItems(params) {
return items;
}
function parseDiagnosticsParams(params) {
- if (!isRecord(params) || typeof params["uri"] !== "string")
+ if (!isRecord2(params) || typeof params["uri"] !== "string")
return null;
const diagnostics = Array.isArray(params["diagnostics"]) ? params["diagnostics"].filter(isDiagnostic) : [];
- return { uri: params["uri"], diagnostics };
+ const version = typeof params["version"] === "number" ? params["version"] : undefined;
+ return { uri: params["uri"], diagnostics, ...version === undefined ? {} : { version } };
+}
+function createLspSpawnEnv(_root, input) {
+ return { ...input };
+}
+function isDiagnostic(value) {
+ return isRecord2(value) && isRange(value["range"]) && typeof value["message"] === "string";
+}
+function isRange(value) {
+ return isRecord2(value) && isPosition(value["start"]) && isPosition(value["end"]);
+}
+function isPosition(value) {
+ return isRecord2(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+}
+
+// ../lsp-core/src/lsp/transport.ts
+class LspClientNotStartedError extends Error {
+ serverId;
+ root;
+ name = "LspClientNotStartedError";
+ constructor(serverId, root) {
+ super("LSP client not started");
+ this.serverId = serverId;
+ this.root = root;
+ }
}
class LspClientTransport {
@@ -558,6 +815,8 @@ class LspClientTransport {
diagnosticsStore = new Map;
requestTimeoutMs;
initializeTimeoutMs;
+ workspaceApplyEditHandler = null;
+ diagnosticPullSupported = false;
constructor(root, server, timeouts = {}) {
this.root = root;
this.server = server;
@@ -570,6 +829,21 @@ class LspClientTransport {
command() {
return [...this.server.command];
}
+ setWorkspaceApplyEditHandler(handler) {
+ this.workspaceApplyEditHandler = handler;
+ }
+ hasWorkspaceApplyEditHandler() {
+ return this.workspaceApplyEditHandler !== null;
+ }
+ setDiagnosticPullSupported(supported) {
+ this.diagnosticPullSupported = supported;
+ }
+ isDiagnosticPullSupported() {
+ return this.diagnosticPullSupported;
+ }
+ handlePublishDiagnostics(params) {
+ this.diagnosticsStore.set(params.uri, [...params.diagnostics]);
+ }
async start() {
const env = createLspSpawnEnv(this.root, {
...process.env,
@@ -580,7 +854,6 @@ class LspClientTransport {
env
});
this.startStderrReading();
- await new Promise((resolve) => setTimeout(resolve, 100));
if (this.proc.exitCode !== null) {
const stderr = this.stderrBuffer.join(`
`);
@@ -590,7 +863,7 @@ class LspClientTransport {
this.connection.onNotification("textDocument/publishDiagnostics", (params) => {
const diagnosticsParams = parseDiagnosticsParams(params);
if (diagnosticsParams?.uri) {
- this.diagnosticsStore.set(diagnosticsParams.uri, diagnosticsParams.diagnostics);
+ this.handlePublishDiagnostics(diagnosticsParams);
}
});
this.connection.onRequest("workspace/configuration", (params) => {
@@ -603,6 +876,9 @@ class LspClientTransport {
});
this.connection.onRequest("client/registerCapability", () => null);
this.connection.onRequest("window/workDoneProgress/create", () => null);
+ if (this.workspaceApplyEditHandler) {
+ this.connection.onRequest("workspace/applyEdit", this.workspaceApplyEditHandler);
+ }
this.connection.onClose(() => {
this.processExited = true;
});
@@ -631,30 +907,25 @@ class LspClientTransport {
}
async sendRequest(method, ...args) {
if (!this.connection)
- throw new Error("LSP client not started");
+ throw new LspClientNotStartedError(this.server.id, this.root);
if (this.processExited || this.proc && this.proc.exitCode !== null) {
const stderrTail = this.stderrBuffer.slice(-10).join(`
`);
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, stderrTail || undefined);
}
- const timeoutMs = args[1]?.timeoutMs ?? this.requestTimeoutMs;
- let timeoutHandle = null;
- const timeoutPromise = new Promise((_, reject) => {
- timeoutHandle = setTimeout(() => {
- const stderrTail = this.stderrBuffer.slice(-5).join(`
+ const options = args[1];
+ const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
+ const timeoutController = new AbortController;
+ const timeoutHandle = setTimeout(() => {
+ const stderrTail = this.stderrBuffer.slice(-5).join(`
`);
- reject(new LspRequestTimeoutError(method, stderrTail || undefined));
- }, timeoutMs);
- });
+ timeoutController.abort(new LspRequestTimeoutError(method, stderrTail || undefined));
+ }, timeoutMs);
+ const combinedSignal = combineAbortSignals(options?.signal, timeoutController.signal);
try {
- const requestPromise = args.length === 0 ? this.connection.sendRequest(method) : this.connection.sendRequest(method, args[0]);
- const result = await Promise.race([requestPromise, timeoutPromise]);
- if (timeoutHandle !== null)
- clearTimeout(timeoutHandle);
+ const result = args.length === 0 ? await this.connection.sendRequest(method, undefined, { signal: combinedSignal.signal }) : await this.connection.sendRequest(method, args[0], { signal: combinedSignal.signal });
return result;
} catch (error) {
- if (timeoutHandle !== null)
- clearTimeout(timeoutHandle);
if (this.processExited || this.proc && this.proc.exitCode !== null) {
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, this.stderrBuffer.slice(-10).join(`
`) || undefined);
@@ -663,6 +934,9 @@ class LspClientTransport {
throw new LspConnectionClosedError(this.server.id, this.root, error.message);
}
throw error;
+ } finally {
+ clearTimeout(timeoutHandle);
+ combinedSignal.dispose();
}
}
async sendNotification(method, ...args) {
@@ -691,17 +965,17 @@ class LspClientTransport {
try {
await this.sendRequest("shutdown");
} catch (error) {
- reportBestEffortCleanupError("shutdown request", error);
+ reportBestEffortCleanupError("shutdown request", error instanceof Error ? error : String(error));
}
try {
await this.sendNotification("exit");
} catch (error) {
- reportBestEffortCleanupError("exit notification", error);
+ reportBestEffortCleanupError("exit notification", error instanceof Error ? error : String(error));
}
try {
this.connection.dispose();
} catch (error) {
- reportBestEffortCleanupError("connection dispose", error);
+ reportBestEffortCleanupError("connection dispose", error instanceof Error ? error : String(error));
}
this.connection = null;
}
@@ -712,8 +986,8 @@ class LspClientTransport {
try {
proc.kill();
let timeoutId;
- const timeoutPromise = new Promise((resolve) => {
- timeoutId = setTimeout(resolve, STOP_HARD_KILL_TIMEOUT_MS);
+ const timeoutPromise = new Promise((resolve2) => {
+ timeoutId = setTimeout(resolve2, STOP_HARD_KILL_TIMEOUT_MS);
});
await Promise.race([
proc.exited.then(() => {
@@ -729,14 +1003,14 @@ class LspClientTransport {
proc.kill("SIGKILL");
await Promise.race([
proc.exited,
- new Promise((resolve) => setTimeout(resolve, STOP_SIGKILL_GRACE_MS))
+ new Promise((resolve2) => setTimeout(resolve2, STOP_SIGKILL_GRACE_MS))
]);
} catch (error) {
- reportBestEffortCleanupError("hard process kill", error);
+ reportBestEffortCleanupError("hard process kill", error instanceof Error ? error : String(error));
}
}
} catch (error) {
- reportBestEffortCleanupError("process stop", error);
+ reportBestEffortCleanupError("process stop", error instanceof Error ? error : String(error));
}
}
this.processExited = true;
@@ -746,26 +1020,45 @@ class LspClientTransport {
return this.diagnosticsStore.get(uri) ?? [];
}
}
-function createLspSpawnEnv(_root, input) {
- return { ...input };
-}
-function isDiagnostic(value) {
- return isRecord(value) && isRange(value["range"]) && typeof value["message"] === "string";
-}
-function isRange(value) {
- return isRecord(value) && isPosition(value["start"]) && isPosition(value["end"]);
-}
-function isPosition(value) {
- return isRecord(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+function combineAbortSignals(primary, secondary) {
+ const controller = new AbortController;
+ const abortFrom = (signal) => {
+ if (!controller.signal.aborted)
+ controller.abort(signal.reason);
+ };
+ const onPrimaryAbort = () => {
+ if (primary)
+ abortFrom(primary);
+ };
+ const onSecondaryAbort = () => abortFrom(secondary);
+ if (primary?.aborted)
+ abortFrom(primary);
+ else
+ primary?.addEventListener("abort", onPrimaryAbort, { once: true });
+ if (secondary.aborted)
+ abortFrom(secondary);
+ else
+ secondary.addEventListener("abort", onSecondaryAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => {
+ primary?.removeEventListener("abort", onPrimaryAbort);
+ secondary.removeEventListener("abort", onSecondaryAbort);
+ }
+ };
}
// ../lsp-core/src/lsp/connection.ts
-var INITIALIZE_SETTLE_MS = 300;
+function supportsDiagnosticPull(capabilities) {
+ if (capabilities === undefined)
+ return false;
+ return Object.hasOwn(capabilities, "diagnosticProvider");
+}
class LspClientConnection extends LspClientTransport {
async initialize() {
const rootUri = pathToFileURL(this.root).href;
- await this.sendRequest("initialize", {
+ const result = await this.sendRequest("initialize", {
processId: process.pid,
rootUri,
rootPath: this.root,
@@ -779,8 +1072,7 @@ class LspClientConnection extends LspClientTransport {
publishDiagnostics: {},
rename: {
prepareSupport: true,
- prepareSupportDefaultBehavior: 1,
- honorsChangeAnnotations: true
+ prepareSupportDefaultBehavior: 1
},
codeAction: {
codeActionLiteralSupport: {
@@ -809,22 +1101,28 @@ class LspClientConnection extends LspClientTransport {
symbol: {},
workspaceFolders: true,
configuration: true,
- applyEdit: true,
+ ...this.hasWorkspaceApplyEditHandler() ? { applyEdit: true } : {},
workspaceEdit: {
- documentChanges: true
+ documentChanges: true,
+ resourceOperations: ["create", "rename", "delete"]
}
}
},
initializationOptions: this.server.initialization
}, { timeoutMs: this.initializeTimeoutMs });
+ this.setDiagnosticPullSupported(supportsDiagnosticPull(result?.capabilities));
await this.sendNotification("initialized");
await this.sendNotification("workspace/didChangeConfiguration", {
settings: { json: { validate: { enable: true } } }
});
- await new Promise((r) => setTimeout(r, INITIALIZE_SETTLE_MS));
}
}
+// ../lsp-core/src/lsp/workspace-document-state.ts
+import { readFileSync, realpathSync as realpathSync2 } from "node:fs";
+import { relative as relative2, resolve as resolve2 } from "node:path";
+import { pathToFileURL as pathToFileURL2 } from "node:url";
+
// ../lsp-core/src/lsp/language-mappings.ts
var SYMBOL_KIND_MAP = {
1: "File",
@@ -997,82 +1295,1422 @@ function getLanguageId(ext) {
return EXT_TO_LANG[ext] ?? "plaintext";
}
+// ../lsp-core/src/lsp/workspace-document-state.ts
+var WATCHED_FILE_BATCH_SIZE = 128;
+var DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
+function canonicalPath(filePath) {
+ const absolute = resolve2(filePath);
+ try {
+ return realpathSync2(absolute);
+ } catch {
+ return absolute;
+ }
+}
+function isSameOrDescendant(candidate, parent) {
+ const suffix = relative2(parent, candidate);
+ return suffix === "" || !suffix.startsWith("..") && suffix !== "..";
+}
+function movedPath(candidate, oldPath, newPath) {
+ const suffix = relative2(oldPath, candidate);
+ return suffix === "" ? newPath : resolve2(newPath, suffix);
+}
+
+class WorkspaceDocumentState {
+ sendNotification;
+ clearDiagnostics;
+ openDocuments = new Map;
+ openByUri = new Map;
+ openPromises = new Map;
+ now;
+ versionlessPublishQuiescenceMs;
+ constructor(sendNotification, clearDiagnostics, options = {}) {
+ this.sendNotification = sendNotification;
+ this.clearDiagnostics = clearDiagnostics;
+ this.now = options.now ?? (() => Date.now());
+ this.versionlessPublishQuiescenceMs = options.versionlessPublishQuiescenceMs ?? DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS;
+ }
+ async openFile(filePath) {
+ const path = canonicalPath(filePath);
+ const existingOpen = this.openPromises.get(path);
+ if (existingOpen) {
+ await existingOpen;
+ return this.openFile(path);
+ }
+ const text = readFileSync(path, "utf-8");
+ const existing = this.openDocuments.get(path);
+ if (!existing)
+ return this.openDocumentSingleFlight(path, text);
+ if (existing.text === text)
+ return;
+ await this.changeDocument(existing, text);
+ }
+ getVersion(filePath) {
+ return this.openDocuments.get(canonicalPath(filePath))?.version;
+ }
+ getStoredDiagnostics(uri) {
+ const state = this.openByUri.get(uri);
+ if (!state)
+ return [];
+ return state.lastPublish?.diagnostics ?? state.pullCache?.diagnostics ?? [];
+ }
+ captureDiagnosticSnapshot(filePath) {
+ const state = this.openDocuments.get(canonicalPath(filePath));
+ if (!state)
+ return null;
+ return {
+ path: state.path,
+ uri: state.uri,
+ version: state.version,
+ documentGeneration: state.generation,
+ publishGeneration: state.publishGeneration
+ };
+ }
+ isCurrentSnapshot(snapshot) {
+ const state = this.openDocuments.get(snapshot.path);
+ return state !== undefined && state.uri === snapshot.uri && state.version === snapshot.version && state.generation === snapshot.documentGeneration;
+ }
+ getPullCache(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.pullCache || state.pullCache.documentVersion !== snapshot.version)
+ return null;
+ return state.pullCache;
+ }
+ recordPullDiagnostics(snapshot, report) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state)
+ return;
+ state.pullCache = {
+ documentVersion: snapshot.version,
+ diagnostics: [...report.diagnostics],
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ };
+ }
+ recordPublishedDiagnostics(params) {
+ const state = this.openByUri.get(params.uri);
+ if (!state)
+ return;
+ state.publishGeneration += 1;
+ state.lastPublish = {
+ diagnostics: [...params.diagnostics],
+ publishGeneration: state.publishGeneration,
+ documentGenerationAtArrival: state.generation,
+ arrivedAt: this.now(),
+ ...params.version === undefined ? {} : { version: params.version }
+ };
+ this.notifyWaiters(state);
+ }
+ resolvePushDiagnostics(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.lastPublish)
+ return { status: "missing" };
+ const publish = state.lastPublish;
+ if (publish.version !== undefined) {
+ return publish.version === snapshot.version ? { status: "ready", diagnostics: publish.diagnostics } : { status: "missing" };
+ }
+ if (publish.documentGenerationAtArrival < snapshot.documentGeneration)
+ return { status: "missing" };
+ const readyAt = publish.arrivedAt + this.versionlessPublishQuiescenceMs;
+ const waitMs = Math.max(0, readyAt - this.now());
+ return waitMs === 0 ? { status: "ready", diagnostics: publish.diagnostics } : { status: "wait", waitMs };
+ }
+ waitForDiagnosticsActivity(snapshot, timeoutMs) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state || timeoutMs <= 0)
+ return Promise.resolve();
+ return new Promise((resolveActivity) => {
+ let settled = false;
+ const finish = () => {
+ if (settled)
+ return;
+ settled = true;
+ clearTimeout(timer);
+ state.waiters.delete(finish);
+ resolveActivity();
+ };
+ const timer = setTimeout(finish, timeoutMs);
+ if (typeof timer.unref === "function")
+ timer.unref();
+ state.waiters.add(finish);
+ });
+ }
+ validateVersions(operations) {
+ const versions = new Map([...this.openDocuments].map(([path, state]) => [path, state.version]));
+ for (const operation of operations) {
+ if (operation.kind === "text") {
+ const current = versions.get(operation.path);
+ if (operation.documentVersion !== null && current !== operation.documentVersion) {
+ const observed = current === undefined ? "closed document" : `open document version ${current}`;
+ return {
+ changeIndex: operation.changeIndex,
+ message: `document version ${operation.documentVersion} does not match ${observed} for ${operation.path}`
+ };
+ }
+ if (current !== undefined)
+ versions.set(operation.path, current + 1);
+ continue;
+ }
+ if (operation.kind === "rename") {
+ const moved = [...versions].filter(([path]) => isSameOrDescendant(path, operation.oldPath));
+ for (const [path] of moved)
+ versions.delete(path);
+ for (const [path] of moved)
+ versions.set(movedPath(path, operation.oldPath, operation.newPath), 1);
+ continue;
+ }
+ if (operation.kind === "delete") {
+ for (const path of [...versions.keys()]) {
+ if (isSameOrDescendant(path, operation.path))
+ versions.delete(path);
+ }
+ continue;
+ }
+ if (operation.kind === "create" && operation.replaced && versions.has(operation.path)) {
+ versions.set(operation.path, 1);
+ }
+ }
+ return null;
+ }
+ async synchronize(delta) {
+ const watched = [];
+ for (const mutation of delta.operations)
+ await this.synchronizeMutation(mutation, watched);
+ for (let index = 0;index < watched.length; index += WATCHED_FILE_BATCH_SIZE) {
+ await this.sendNotification("workspace/didChangeWatchedFiles", {
+ changes: watched.slice(index, index + WATCHED_FILE_BATCH_SIZE)
+ });
+ }
+ }
+ async synchronizeMutation(mutation, watched) {
+ if (mutation.kind === "text") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state)
+ await this.changeDocument(state, mutation.afterText);
+ else
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 2 });
+ return;
+ }
+ if (mutation.kind === "create") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state) {
+ await this.closeDocument(state);
+ await this.openDocumentSingleFlight(mutation.path, readFileSync(mutation.path, "utf-8"));
+ } else {
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: mutation.replaced ? 2 : 1 });
+ }
+ return;
+ }
+ if (mutation.kind === "rename") {
+ const moved = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.oldPath));
+ for (const state of moved)
+ await this.closeDocument(state);
+ for (const state of moved) {
+ const path = movedPath(state.path, mutation.oldPath, mutation.newPath);
+ await this.openDocumentSingleFlight(path, readFileSync(path, "utf-8"));
+ }
+ if (moved.length === 0) {
+ watched.push({ uri: pathToFileURL2(mutation.oldPath).href, type: 3 });
+ watched.push({ uri: pathToFileURL2(mutation.newPath).href, type: 1 });
+ }
+ return;
+ }
+ const removed = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.path));
+ for (const state of removed)
+ await this.closeDocument(state);
+ if (removed.length === 0)
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 3 });
+ }
+ async openDocumentSingleFlight(path, text) {
+ const existing = this.openPromises.get(path);
+ if (existing)
+ return existing;
+ const open = (async () => {
+ const state = {
+ path,
+ uri: pathToFileURL2(path).href,
+ languageId: getLanguageId(effectiveExtension(path)),
+ text,
+ version: 1,
+ generation: 1,
+ publishGeneration: 0,
+ waiters: new Set
+ };
+ this.openDocuments.set(path, state);
+ this.openByUri.set(state.uri, state);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didOpen", {
+ textDocument: { uri: state.uri, languageId: state.languageId, version: state.version, text }
+ });
+ })().finally(() => {
+ this.openPromises.delete(path);
+ });
+ this.openPromises.set(path, open);
+ return open;
+ }
+ async changeDocument(state, text) {
+ state.text = text;
+ state.version += 1;
+ state.generation += 1;
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didChange", {
+ textDocument: { uri: state.uri, version: state.version },
+ contentChanges: [{ text }]
+ });
+ await this.sendNotification("textDocument/didSave", { textDocument: { uri: state.uri }, text });
+ }
+ async closeDocument(state) {
+ this.openDocuments.delete(state.path);
+ this.openByUri.delete(state.uri);
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didClose", { textDocument: { uri: state.uri } });
+ }
+ notifyWaiters(state) {
+ for (const waiter of [...state.waiters])
+ waiter();
+ }
+}
+
+// ../lsp-core/src/lsp/workspace-apply-edit-failure.ts
+var CONCURRENT_FAILURE_REASON_BY_PHASE = {
+ applying: "workspace/applyEdit is already in progress for this workspace mutation",
+ settled: "workspace/applyEdit was already handled for this workspace mutation"
+};
+function workspaceApplyEditConcurrentFailureReason(phase) {
+ return CONCURRENT_FAILURE_REASON_BY_PHASE[phase];
+}
+
+// ../lsp-core/src/lsp/workspace-edit-commit.ts
+import { existsSync as existsSync4, lstatSync as lstatSync2, renameSync, rmSync, writeFileSync } from "node:fs";
+
+// ../lsp-core/src/lsp/workspace-edit-path.ts
+import { existsSync as existsSync3, lstatSync, readFileSync as readFileSync2, readdirSync, realpathSync as realpathSync3 } from "node:fs";
+import { dirname as dirname2, isAbsolute as isAbsolute2, relative as relative3, resolve as resolve3 } from "node:path";
+import { fileURLToPath } from "node:url";
+
+class WorkspaceEditPathError extends Error {
+ path;
+ detail;
+ name = "WorkspaceEditPathError";
+ constructor(path, detail) {
+ super(`${detail}: ${path}`);
+ this.path = path;
+ this.detail = detail;
+ }
+}
+function isPathInsideWorkspace(filePath, workspaceRoot) {
+ const relativePath = relative3(workspaceRoot, filePath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute2(relativePath);
+}
+function canonicalizeMissingPath(filePath) {
+ let ancestor = filePath;
+ while (!existsSync3(ancestor)) {
+ const parent = dirname2(ancestor);
+ if (parent === ancestor)
+ throw new WorkspaceEditPathError(filePath, "no existing ancestor");
+ ancestor = parent;
+ }
+ return resolve3(realpathSync3(ancestor), relative3(ancestor, filePath));
+}
+function canonicalWorkspaceRoot(workspaceRoot) {
+ try {
+ const canonical = realpathSync3(resolve3(workspaceRoot));
+ if (!lstatSync(canonical).isDirectory()) {
+ return { success: false, error: `workspace root is not a directory: ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath: resolve3(workspaceRoot),
+ followedSymbolicLink: existsSync3(resolve3(workspaceRoot)) && lstatSync(resolve3(workspaceRoot)).isSymbolicLink()
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `workspace root ${workspaceRoot}: ${detail}` };
+ }
+}
+function uriToCanonicalWorkspacePath(uri, workspaceRoot) {
+ let requestedPath;
+ try {
+ const parsed = new URL(uri);
+ if (parsed.protocol !== "file:" || parsed.search !== "" || parsed.hash !== "") {
+ return { success: false, error: `non-file URI ${uri}` };
+ }
+ requestedPath = resolve3(fileURLToPath(parsed));
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `non-file URI ${uri}: ${detail}` };
+ }
+ try {
+ const canonical = existsSync3(requestedPath) ? realpathSync3(requestedPath) : canonicalizeMissingPath(requestedPath);
+ if (!isPathInsideWorkspace(canonical, workspaceRoot)) {
+ return { success: false, error: `${requestedPath}: outside workspace ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath,
+ followedSymbolicLink: existsSync3(requestedPath) && lstatSync(requestedPath).isSymbolicLink()
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `${requestedPath}: ${detail}` };
+ }
+}
+function snapshotPath(path, includeChildren) {
+ if (!existsSync3(path))
+ return { kind: "missing" };
+ const stats = lstatSync(path);
+ if (stats.isFile())
+ return { kind: "file", content: readFileSync2(path, "utf-8") };
+ if (stats.isDirectory()) {
+ return includeChildren ? { kind: "directory", children: readdirSync(path).sort() } : { kind: "directory" };
+ }
+ throw new WorkspaceEditPathError(path, "unsupported filesystem entry");
+}
+
+// ../lsp-core/src/lsp/workspace-edit-commit.ts
+var DEFAULT_IO = {
+ writeFile(path, content) {
+ writeFileSync(path, content, "utf-8");
+ },
+ rename(oldPath, newPath) {
+ renameSync(oldPath, newPath);
+ },
+ remove(path, recursive) {
+ rmSync(path, { recursive, force: false });
+ }
+};
+function snapshotsEqual(expected, actual) {
+ if (expected.kind !== actual.kind)
+ return false;
+ if (expected.kind === "file" && actual.kind === "file")
+ return expected.content === actual.content;
+ if (expected.kind === "directory" && actual.kind === "directory" && expected.children !== undefined) {
+ return JSON.stringify(expected.children) === JSON.stringify(actual.children);
+ }
+ return true;
+}
+function liveSnapshot(path, expected) {
+ return snapshotPath(path, expected.kind === "directory" && expected.children !== undefined);
+}
+function firstOperationIndex(plan) {
+ return plan.operations[0]?.changeIndex ?? 0;
+}
+function failedCommit(plan, failure) {
+ const { message, changeIndex, mutations = [], filesModified = [], totalEdits = 0, lateAbort = false } = failure;
+ return {
+ result: {
+ success: false,
+ filesModified,
+ totalEdits,
+ errors: [`change ${changeIndex}: ${message}`],
+ failedChange: changeIndex,
+ ...lateAbort ? { lateAbort: true } : {}
+ },
+ delta: mutationDelta(mutations),
+ fingerprint: plan.fingerprint
+ };
+}
+function verifySnapshots(plan) {
+ for (const [path, expected] of plan.snapshots) {
+ let actual;
+ try {
+ actual = liveSnapshot(path, expected);
+ } catch (error) {
+ const changeIndex = plan.firstChangeByPath.get(path) ?? firstOperationIndex(plan);
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, { message: `cannot verify snapshot for ${path}: ${detail}`, changeIndex });
+ }
+ if (!snapshotsEqual(expected, actual)) {
+ const changeIndex = plan.firstChangeByPath.get(path) ?? firstOperationIndex(plan);
+ return failedCommit(plan, { message: `workspace state changed before commit: ${path}`, changeIndex });
+ }
+ }
+ return null;
+}
+function addModifiedPath(paths, path) {
+ if (!paths.includes(path))
+ paths.push(path);
+}
+function reportedPath(plan, path) {
+ return plan.reportedPathByCanonical.get(path) ?? path;
+}
+function changedPathsForMutation(mutation) {
+ return mutation.kind === "rename" ? [mutation.oldPath, mutation.newPath] : [mutation.path];
+}
+function mutationDelta(operations) {
+ const changedPaths = new Set;
+ for (const operation of operations) {
+ for (const path of changedPathsForMutation(operation))
+ changedPaths.add(path);
+ }
+ return { operations, changedPaths: [...changedPaths].sort() };
+}
+function resolveIo(overrides) {
+ return {
+ writeFile: overrides?.writeFile ?? DEFAULT_IO.writeFile,
+ rename: overrides?.rename ?? DEFAULT_IO.rename,
+ remove: overrides?.remove ?? DEFAULT_IO.remove
+ };
+}
+function commitOperation(context, operation) {
+ const { plan, io, accumulator } = context;
+ if (operation.kind === "noop")
+ return;
+ if (operation.kind === "text") {
+ io.writeFile(operation.path, operation.afterText);
+ accumulator.mutations.push({
+ kind: "text",
+ path: operation.path,
+ beforeText: operation.beforeText,
+ afterText: operation.afterText
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ accumulator.totalEdits += operation.editCount;
+ return;
+ }
+ if (operation.kind === "create") {
+ io.writeFile(operation.path, "");
+ accumulator.mutations.push({ kind: "create", path: operation.path, replaced: operation.replaced });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ return;
+ }
+ if (operation.kind === "rename") {
+ if (operation.replaceDestination) {
+ const targetKind = existsSync4(operation.newPath) && lstatSync2(operation.newPath).isDirectory() ? "directory" : "file";
+ io.remove(operation.newPath, targetKind === "directory");
+ accumulator.mutations.push({ kind: "delete", path: operation.newPath, targetKind });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ }
+ io.rename(operation.oldPath, operation.newPath);
+ accumulator.mutations.push({
+ kind: "rename",
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: operation.sourceKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ return;
+ }
+ io.remove(operation.path, operation.recursive);
+ accumulator.mutations.push({
+ kind: "delete",
+ path: operation.path,
+ targetKind: operation.targetKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+}
+function commitWorkspaceEditPlan(plan, options = {}) {
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const stale = verifySnapshots(plan);
+ if (stale)
+ return stale;
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const io = resolveIo(options.io);
+ const accumulator = { mutations: [], filesModified: [], totalEdits: 0 };
+ const context = { plan, io, accumulator };
+ let lateAbort = false;
+ for (const operation of plan.operations) {
+ try {
+ commitOperation(context, operation);
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, {
+ message: `I/O failure during ${operation.kind}: ${detail}`,
+ changeIndex: operation.changeIndex,
+ mutations: accumulator.mutations,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ lateAbort: lateAbort || options.signal?.aborted === true
+ });
+ }
+ if (options.signal?.aborted)
+ lateAbort = true;
+ }
+ const result = {
+ success: true,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ errors: [],
+ ...lateAbort ? { lateAbort: true } : {}
+ };
+ return { result, delta: mutationDelta(accumulator.mutations), fingerprint: plan.fingerprint };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-fingerprint.ts
+import { createHash } from "node:crypto";
+function canonicalFingerprint(operations) {
+ const canonical = operations.map((operation) => {
+ switch (operation.kind) {
+ case "text":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ edits: operation.edits,
+ version: operation.version
+ };
+ case "rename":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "create":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "delete":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ recursive: operation.recursive,
+ ignoreIfNotExists: operation.ignoreIfNotExists
+ };
+ }
+ });
+ return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
+}
+
+// ../lsp-core/src/lsp/workspace-edit-types.ts
+class WorkspaceEditValidationError extends Error {
+ changeIndex;
+ detail;
+ name = "WorkspaceEditValidationError";
+ constructor(changeIndex, detail) {
+ super(`change ${changeIndex}: ${detail}`);
+ this.changeIndex = changeIndex;
+ this.detail = detail;
+ }
+}
+
+// ../lsp-core/src/lsp/workspace-edit-parse-helpers.ts
+function isRecord3(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function parsePosition(value) {
+ if (!isRecord3(value) || typeof value["line"] !== "number" || typeof value["character"] !== "number") {
+ return null;
+ }
+ return { line: value["line"], character: value["character"] };
+}
+function parseRange(value) {
+ if (!isRecord3(value))
+ return null;
+ const start = parsePosition(value["start"]);
+ const end = parsePosition(value["end"]);
+ return start && end ? { start, end } : null;
+}
+function parseTextEdits(value, changeIndex) {
+ if (!Array.isArray(value)) {
+ throw new WorkspaceEditValidationError(changeIndex, "text edits must be an array");
+ }
+ const edits = [];
+ for (const candidate of value) {
+ if (!isRecord3(candidate) || typeof candidate["newText"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "text edit requires range and newText");
+ }
+ if ("annotationId" in candidate) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated text edits are unsupported");
+ }
+ const range = parseRange(candidate["range"]);
+ if (!range)
+ throw new WorkspaceEditValidationError(changeIndex, "text edit range is malformed");
+ edits.push({ range, newText: candidate["newText"] });
+ }
+ return edits;
+}
+function parseBooleanOption(options, key, changeIndex) {
+ const value = options[key];
+ if (value === undefined)
+ return false;
+ if (typeof value !== "boolean") {
+ throw new WorkspaceEditValidationError(changeIndex, `${key} must be boolean`);
+ }
+ return value;
+}
+function parseOptions(value, allowed, changeIndex) {
+ if (value === undefined)
+ return {};
+ if (!isRecord3(value))
+ throw new WorkspaceEditValidationError(changeIndex, "resource options must be an object");
+ for (const key of Object.keys(value)) {
+ if (!allowed.includes(key))
+ throw new WorkspaceEditValidationError(changeIndex, `unsupported resource option ${key}`);
+ }
+ const parsed = {};
+ for (const key of allowed)
+ parsed[key] = parseBooleanOption(value, key, changeIndex);
+ return parsed;
+}
+
+// ../lsp-core/src/lsp/workspace-edit-resource-parser.ts
+function parseResourceChange(input) {
+ const kind = input.change["kind"];
+ if (kind === "create" || kind === "delete") {
+ parseSinglePathResource(input, kind);
+ return;
+ }
+ if (kind !== "rename") {
+ throw new WorkspaceEditValidationError(input.changeIndex, `unsupported resource operation ${String(kind)}`);
+ }
+ parseRename(input);
+}
+function parseSinglePathResource(input, kind) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["uri"] !== "string")
+ throw new WorkspaceEditValidationError(changeIndex, `${kind}.uri is required`);
+ const resolvedPath = uriToCanonicalWorkspacePath(change["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ if (kind === "create") {
+ const options2 = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ overwrite: options2["overwrite"] ?? false,
+ ignoreIfExists: options2["ignoreIfExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["recursive", "ignoreIfNotExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ recursive: options["recursive"] ?? false,
+ ignoreIfNotExists: options["ignoreIfNotExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+}
+function parseRename(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["oldUri"] !== "string" || typeof change["newUri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "rename requires oldUri and newUri");
+ }
+ const oldPath = uriToCanonicalWorkspacePath(change["oldUri"], workspaceRoot);
+ const newPath = uriToCanonicalWorkspacePath(change["newUri"], workspaceRoot);
+ if (!oldPath.success || !newPath.success) {
+ target.failures.push({
+ changeIndex,
+ message: !oldPath.success ? oldPath.error : !newPath.success ? newPath.error : "invalid rename path"
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind: "rename",
+ changeIndex,
+ oldPath: oldPath.path,
+ newPath: newPath.path,
+ reportedOldPath: oldPath.requestedPath,
+ reportedNewPath: newPath.requestedPath,
+ overwrite: options["overwrite"] ?? false,
+ ignoreIfExists: options["ignoreIfExists"] ?? false,
+ followedSymbolicLink: oldPath.followedSymbolicLink || newPath.followedSymbolicLink
+ });
+}
+
+// ../lsp-core/src/lsp/workspace-edit-parser.ts
+function failureResult(failures) {
+ const sorted = [...failures].sort((left, right) => left.changeIndex - right.changeIndex);
+ const first = sorted[0];
+ return {
+ success: false,
+ filesModified: [],
+ totalEdits: 0,
+ errors: sorted.map((failure) => `change ${failure.changeIndex}: ${failure.message}`),
+ ...first ? { failedChange: first.changeIndex } : {}
+ };
+}
+function parseWorkspaceEdit(edit, workspaceRoot) {
+ if (!isRecord3(edit))
+ return { operations: [], failures: [{ changeIndex: 0, message: "No edit provided" }] };
+ if (edit["changeAnnotations"] !== undefined) {
+ return { operations: [], failures: [{ changeIndex: 0, message: "change annotations are unsupported" }] };
+ }
+ const hasChanges = edit["changes"] !== undefined;
+ const hasDocumentChanges = edit["documentChanges"] !== undefined;
+ if (hasChanges && hasDocumentChanges) {
+ return {
+ operations: [],
+ failures: [{ changeIndex: 0, message: "changes and documentChanges cannot be combined" }]
+ };
+ }
+ const target = { operations: [], failures: [] };
+ if (hasChanges)
+ return parseChanges(edit["changes"], workspaceRoot, target);
+ return parseDocumentChanges(edit["documentChanges"], workspaceRoot, target);
+}
+function parseChanges(value, workspaceRoot, target) {
+ if (!isRecord3(value))
+ return { ...target, failures: [{ changeIndex: 0, message: "changes must be an object" }] };
+ const entries = Object.entries(value).sort(([left], [right]) => left.localeCompare(right));
+ for (const [changeIndex, [uri, rawEdits]] of entries.entries()) {
+ const resolvedPath = uriToCanonicalWorkspacePath(uri, workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ continue;
+ }
+ try {
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(rawEdits, changeIndex),
+ version: null
+ });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChanges(value, workspaceRoot, target) {
+ if (value === undefined)
+ return target;
+ if (!Array.isArray(value)) {
+ return { ...target, failures: [{ changeIndex: 0, message: "documentChanges must be an array" }] };
+ }
+ for (const [changeIndex, change] of value.entries()) {
+ try {
+ parseDocumentChange({ change, changeIndex, workspaceRoot, target });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChange(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (!isRecord3(change))
+ throw new WorkspaceEditValidationError(changeIndex, "document change must be an object");
+ if ("annotationId" in change) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated resource operations are unsupported");
+ }
+ if (typeof change["kind"] === "string") {
+ parseResourceChange({ change, changeIndex, workspaceRoot, target });
+ return;
+ }
+ const identifier = change["textDocument"];
+ if (!isRecord3(identifier) || typeof identifier["uri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "textDocument.uri is required");
+ }
+ const version = identifier["version"];
+ if (version !== null && (!Number.isInteger(version) || typeof version !== "number" || version < 0)) {
+ throw new WorkspaceEditValidationError(changeIndex, "document version must be null or a non-negative integer");
+ }
+ const resolvedPath = uriToCanonicalWorkspacePath(identifier["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(change["edits"], changeIndex),
+ version
+ });
+}
+
+// ../lsp-core/src/lsp/workspace-edit-simulation.ts
+import { dirname as dirname3, relative as relative4, resolve as resolve4 } from "node:path";
+
+// ../lsp-core/src/lsp/workspace-edit-text.ts
+function comparePosition(left, right) {
+ return left.line === right.line ? left.character - right.character : left.line - right.line;
+}
+function positionsEqual(left, right) {
+ return left.line === right.line && left.character === right.character;
+}
+function rangesEqual(left, right) {
+ return positionsEqual(left.start, right.start) && positionsEqual(left.end, right.end);
+}
+function isEmptyRange(range) {
+ return positionsEqual(range.start, range.end);
+}
+function formatRange(range) {
+ return `${range.start.line + 1}:${range.start.character + 1}-${range.end.line + 1}:${range.end.character + 1}`;
+}
+function validatePosition(position, label, context) {
+ const { lines, changeIndex } = context;
+ if (!Number.isInteger(position.line) || !Number.isInteger(position.character)) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position must use integer line and character`);
+ }
+ if (position.line < 0 || position.character < 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position cannot be negative`);
+ }
+ const line = lines[position.line];
+ if (line === undefined) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} line ${position.line} is outside the document`);
+ }
+ if (position.character > line.length) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} character ${position.character} is outside line ${position.line}`);
+ }
+}
+function validateRange(range, lines, changeIndex) {
+ const context = { lines, changeIndex };
+ validatePosition(range.start, "start", context);
+ validatePosition(range.end, "end", context);
+ if (comparePosition(range.start, range.end) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `range ${formatRange(range)} ends before it starts`);
+ }
+}
+function sortAndDeduplicate(edits) {
+ const sorted = edits.map((edit, index) => ({ edit, index })).sort((left, right) => {
+ const positionOrder = comparePosition(right.edit.range.start, left.edit.range.start);
+ return positionOrder === 0 ? right.index - left.index : positionOrder;
+ });
+ const unique = [];
+ for (const entry of sorted) {
+ const previous = unique.at(-1);
+ if (previous !== undefined && !isEmptyRange(entry.edit.range) && rangesEqual(previous.range, entry.edit.range) && previous.newText === entry.edit.newText) {
+ continue;
+ }
+ unique.push(entry.edit);
+ }
+ return unique;
+}
+function validateNoOverlap(edits, changeIndex) {
+ for (let index = 0;index < edits.length - 1; index += 1) {
+ const later = edits[index];
+ const earlier = edits[index + 1];
+ if (later === undefined || earlier === undefined)
+ continue;
+ if (comparePosition(earlier.range.end, later.range.start) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `overlapping edits ${formatRange(earlier.range)} and ${formatRange(later.range)}`);
+ }
+ }
+}
+function applyNormalizedTextEdits(content, edits) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ const { start, end } = edit.range;
+ const startLine = lines[start.line];
+ const endLine = lines[end.line];
+ if (startLine === undefined || endLine === undefined)
+ continue;
+ const replacement = startLine.slice(0, start.character) + edit.newText + endLine.slice(end.character);
+ lines.splice(start.line, end.line - start.line + 1, ...replacement.split(`
+`));
+ }
+ return lines.join(`
+`);
+}
+function normalizeTextEdits(content, edits, changeIndex) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ validateRange(edit.range, lines, changeIndex);
+ }
+ const normalized = sortAndDeduplicate(edits);
+ validateNoOverlap(normalized, changeIndex);
+ return { edits: normalized, text: applyNormalizedTextEdits(content, normalized) };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-simulation.ts
+function isSameOrDescendant2(candidate, parent) {
+ const relativePath = relative4(parent, candidate);
+ return relativePath === "" || !relativePath.startsWith("..") && relativePath !== "..";
+}
+function removeVirtualSubtree(virtual, path) {
+ for (const candidate of [...virtual.keys()]) {
+ if (isSameOrDescendant2(candidate, path))
+ virtual.delete(candidate);
+ }
+ virtual.set(path, { kind: "missing" });
+}
+function moveVirtualSubtree(virtual, oldPath, newPath) {
+ const moved = [...virtual.entries()].filter(([candidate]) => isSameOrDescendant2(candidate, oldPath));
+ removeVirtualSubtree(virtual, oldPath);
+ removeVirtualSubtree(virtual, newPath);
+ for (const [candidate, entry] of moved) {
+ const suffix = relative4(oldPath, candidate);
+ virtual.set(suffix === "" ? newPath : resolve4(newPath, suffix), entry);
+ }
+}
+function virtualDirectoryHasChildren(virtual, path) {
+ for (const [candidate, entry] of virtual) {
+ if (candidate !== path && entry.kind !== "missing" && isSameOrDescendant2(candidate, path))
+ return true;
+ }
+ return false;
+}
+function requireVirtualParent(virtual, path, changeIndex) {
+ if (virtual.get(dirname3(path))?.kind !== "directory") {
+ throw new WorkspaceEditValidationError(changeIndex, `parent directory does not exist for ${path}`);
+ }
+}
+function simulateOperations(parsed, snapshots) {
+ const virtual = new Map(snapshots);
+ const planned = [];
+ const failures = [];
+ for (const operation of parsed) {
+ try {
+ planned.push(simulateOperation(operation, virtual));
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ failures.push({ changeIndex: operation.changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return { operations: planned, failures };
+}
+function simulateOperation(operation, virtual) {
+ switch (operation.kind) {
+ case "text":
+ return simulateText(operation, virtual);
+ case "create":
+ return simulateCreate(operation, virtual);
+ case "rename":
+ return simulateRename(operation, virtual);
+ case "delete":
+ return simulateDelete(operation, virtual);
+ }
+}
+function rejectSymbolicLink(operation) {
+ if (operation.followedSymbolicLink) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "resource operations through symbolic links are unsupported");
+ }
+}
+function simulateText(operation, virtual) {
+ const entry = virtual.get(operation.path);
+ if (entry?.kind !== "file")
+ throw new WorkspaceEditValidationError(operation.changeIndex, `${operation.path} is not a file`);
+ const normalized = normalizeTextEdits(entry.content, operation.edits, operation.changeIndex);
+ virtual.set(operation.path, { kind: "file", content: normalized.text });
+ return {
+ kind: "text",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ beforeText: entry.content,
+ afterText: normalized.text,
+ editCount: normalized.edits.length,
+ documentVersion: operation.version
+ };
+}
+function simulateCreate(operation, virtual) {
+ rejectSymbolicLink(operation);
+ requireVirtualParent(virtual, operation.path, operation.changeIndex);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind !== "missing") {
+ if (operation.overwrite && target.kind === "file") {
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: true };
+ }
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `create target already exists: ${operation.path}`);
+ }
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: false };
+}
+function simulateRename(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const source = virtual.get(operation.oldPath) ?? { kind: "missing" };
+ if (source.kind === "missing") {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename source does not exist: ${operation.oldPath}`);
+ }
+ if (operation.oldPath === operation.newPath)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ if (isSameOrDescendant2(operation.newPath, operation.oldPath)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "cannot rename a path into its own subtree");
+ }
+ requireVirtualParent(virtual, operation.newPath, operation.changeIndex);
+ const destination = virtual.get(operation.newPath) ?? { kind: "missing" };
+ if (destination.kind !== "missing" && !operation.overwrite) {
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename target already exists: ${operation.newPath}`);
+ }
+ moveVirtualSubtree(virtual, operation.oldPath, operation.newPath);
+ return {
+ kind: "rename",
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: source.kind,
+ replaceDestination: destination.kind !== "missing"
+ };
+}
+function simulateDelete(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind === "missing") {
+ if (operation.ignoreIfNotExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `delete target does not exist: ${operation.path}`);
+ }
+ if (target.kind === "directory" && !operation.recursive && virtualDirectoryHasChildren(virtual, operation.path)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `directory is not empty: ${operation.path}`);
+ }
+ removeVirtualSubtree(virtual, operation.path);
+ return {
+ kind: "delete",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ targetKind: target.kind,
+ recursive: operation.recursive
+ };
+}
+
+// ../lsp-core/src/lsp/workspace-edit-snapshot.ts
+import { existsSync as existsSync5, lstatSync as lstatSync3, readdirSync as readdirSync2 } from "node:fs";
+import { dirname as dirname4, resolve as resolve5 } from "node:path";
+class WorkspaceSnapshotBuilder {
+ workspaceRoot;
+ snapshots = new Map;
+ constructor(workspaceRoot) {
+ this.workspaceRoot = workspaceRoot;
+ }
+ build(operations) {
+ this.add(this.workspaceRoot, false);
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, true);
+ this.add(operation.newPath, true);
+ break;
+ case "delete":
+ this.add(operation.path, true);
+ break;
+ case "text":
+ case "create":
+ this.add(operation.path, false);
+ break;
+ }
+ }
+ return this.snapshots;
+ }
+ add(path, includeChildren) {
+ let candidate = path;
+ while (true) {
+ const existing = this.snapshots.get(candidate);
+ if (existing === undefined || includeChildren && existing.kind === "directory" && existing.children === undefined) {
+ this.snapshots.set(candidate, snapshotPath(candidate, includeChildren && candidate === path));
+ }
+ if (candidate === this.workspaceRoot)
+ break;
+ candidate = dirname4(candidate);
+ }
+ if (!includeChildren || !existsSync5(path) || !lstatSync3(path).isDirectory())
+ return;
+ for (const child of readdirSync2(path))
+ this.add(resolve5(path, child), true);
+ }
+}
+function snapshotOperations(operations, workspaceRoot) {
+ return new WorkspaceSnapshotBuilder(workspaceRoot).build(operations);
+}
+
+// ../lsp-core/src/lsp/workspace-edit-plan.ts
+class PlanPathIndex {
+ firstChangeByPath = new Map;
+ reportedPathByCanonical = new Map;
+ build(operations) {
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, operation.reportedOldPath, operation.changeIndex);
+ this.add(operation.newPath, operation.reportedNewPath, operation.changeIndex);
+ break;
+ case "text":
+ case "create":
+ case "delete":
+ this.add(operation.path, operation.reportedPath, operation.changeIndex);
+ break;
+ }
+ }
+ }
+ add(path, reportedPath2, changeIndex) {
+ if (!this.firstChangeByPath.has(path))
+ this.firstChangeByPath.set(path, changeIndex);
+ if (!this.reportedPathByCanonical.has(path))
+ this.reportedPathByCanonical.set(path, reportedPath2);
+ }
+}
+function fingerprintWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ return { success: true, fingerprint: canonicalFingerprint(parsed.operations) };
+}
+function planWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ let snapshots;
+ try {
+ snapshots = snapshotOperations(parsed.operations, root.path);
+ } catch (error) {
+ return {
+ success: false,
+ result: failureResult([{ changeIndex: 0, message: error instanceof Error ? error.message : String(error) }])
+ };
+ }
+ const simulated = simulateOperations(parsed.operations, snapshots);
+ if (simulated.failures.length > 0)
+ return { success: false, result: failureResult(simulated.failures) };
+ const paths = new PlanPathIndex;
+ paths.build(parsed.operations);
+ const plan = {
+ workspaceRoot: root.path,
+ operations: simulated.operations,
+ snapshots,
+ firstChangeByPath: paths.firstChangeByPath,
+ reportedPathByCanonical: paths.reportedPathByCanonical,
+ fingerprint: canonicalFingerprint(parsed.operations)
+ };
+ return { success: true, plan };
+}
+
+// ../lsp-core/src/lsp/workspace-mutation-controller.ts
+function failure(message, failedChange, base) {
+ return {
+ success: false,
+ filesModified: base?.filesModified ?? [],
+ totalEdits: base?.totalEdits ?? 0,
+ errors: [message],
+ ...failedChange === undefined ? {} : { failedChange },
+ ...base?.lateAbort ? { lateAbort: true } : {}
+ };
+}
+function responseFor(result) {
+ if (result.success)
+ return { applied: true };
+ return {
+ applied: false,
+ failureReason: result.errors[0] ?? "workspace edit failed",
+ ...result.failedChange === undefined ? {} : { failedChange: result.failedChange }
+ };
+}
+function isRecord4(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+class WorkspaceMutationController {
+ workspaceRoot;
+ documents;
+ activeLease = null;
+ nextLeaseId = 1;
+ io;
+ constructor(workspaceRoot, documents) {
+ this.workspaceRoot = workspaceRoot;
+ this.documents = documents;
+ }
+ setIo(io) {
+ this.io = io;
+ }
+ acquire(signal) {
+ if (this.activeLease)
+ return { success: false, result: failure("workspace mutation is already in progress") };
+ if (signal?.aborted)
+ return { success: false, result: failure("cancelled before mutating request") };
+ const lease = {
+ id: this.nextLeaseId,
+ phase: "idle",
+ ...signal === undefined ? {} : { signal }
+ };
+ this.nextLeaseId += 1;
+ this.activeLease = lease;
+ return { success: true, lease };
+ }
+ release(lease) {
+ if (this.activeLease?.id !== lease.id)
+ return;
+ this.activeLease.phase = "sealed";
+ this.activeLease = null;
+ }
+ isBeforeCommit(lease) {
+ return this.activeLease?.id === lease.id && this.activeLease.phase === "idle";
+ }
+ async handleApplyEdit(params) {
+ const lease = this.activeLease;
+ if (!lease)
+ return { applied: false, failureReason: "workspace/applyEdit requires an active workspace mutation" };
+ if (lease.phase !== "idle") {
+ return {
+ applied: false,
+ failureReason: workspaceApplyEditConcurrentFailureReason(lease.phase === "applying" ? "applying" : "settled")
+ };
+ }
+ lease.phase = "applying";
+ lease.applyCompletion = new Promise((resolve6) => {
+ lease.resolveApply = resolve6;
+ });
+ const edit = isRecord4(params) ? params["edit"] : undefined;
+ const record = edit === undefined ? { fingerprint: null, result: failure("workspace/applyEdit params.edit is required", 0) } : await this.applyEdit(edit, lease);
+ lease.serverApply = record;
+ lease.phase = "settled";
+ lease.resolveApply?.();
+ return responseFor(record.result);
+ }
+ async reconcileRename(leaseToken, edit) {
+ const lease = this.requireActiveLease(leaseToken);
+ if (!lease)
+ return { edit, apply: failure("workspace mutation lease ended before rename reconciliation") };
+ if (lease.phase === "applying")
+ await lease.applyCompletion;
+ if (lease.serverApply)
+ return this.reconcileServerApply(lease.serverApply, edit);
+ lease.phase = "sealed";
+ if (!edit)
+ return { edit, apply: failure("No edit provided") };
+ const applied = await this.applyEdit(edit, lease);
+ return { edit, apply: applied.result };
+ }
+ reconcileServerApply(record, edit) {
+ if (!edit)
+ return { edit, apply: record.result };
+ const fingerprint = fingerprintWorkspaceEdit(edit, this.workspaceRoot);
+ if (fingerprint.success && record.fingerprint !== null && fingerprint.fingerprint === record.fingerprint) {
+ return { edit, apply: record.result };
+ }
+ return {
+ edit,
+ apply: failure("rename result conflicts with server-applied workspace edit", 0, record.result)
+ };
+ }
+ async applyEdit(edit, lease) {
+ const planned = planWorkspaceEdit(edit, this.workspaceRoot);
+ if (!planned.success)
+ return { fingerprint: null, result: planned.result };
+ const versionFailure = this.documents.validateVersions(planned.plan.operations);
+ if (versionFailure) {
+ return {
+ fingerprint: planned.plan.fingerprint,
+ result: failure(versionFailure.message, versionFailure.changeIndex)
+ };
+ }
+ const commit = commitWorkspaceEditPlan(planned.plan, {
+ ...lease.signal === undefined ? {} : { signal: lease.signal },
+ ...this.io === undefined ? {} : { io: this.io }
+ });
+ let result = commit.result;
+ if (commit.delta.operations.length > 0) {
+ try {
+ await this.documents.synchronize(commit.delta);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ result = failure(`document synchronization failed after filesystem commit: ${message}`, undefined, result);
+ }
+ }
+ if (lease.signal?.aborted && !result.lateAbort)
+ result = { ...result, lateAbort: true };
+ return { fingerprint: planned.plan.fingerprint, result };
+ }
+ requireActiveLease(lease) {
+ return this.activeLease?.id === lease.id ? this.activeLease : null;
+ }
+}
+
// ../lsp-core/src/lsp/client.ts
-var POST_OPEN_DELAY_MS = 1000;
-var POST_DIAGNOSTICS_WAIT_MS = 500;
+var DIAGNOSTICS_FRESHNESS_TIMEOUT_MS = 3000;
+var VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
class LspClient extends LspClientConnection {
- openedFiles = new Set;
- documentVersions = new Map;
- lastSyncedText = new Map;
diagnosticPullErrors = [];
+ documents;
+ workspaceMutations;
+ diagnosticsFreshnessTimeoutMs;
+ constructor(root, server, options = {}) {
+ super(root, server, options);
+ this.diagnosticsFreshnessTimeoutMs = options.diagnosticsFreshnessTimeoutMs ?? DIAGNOSTICS_FRESHNESS_TIMEOUT_MS;
+ this.documents = new WorkspaceDocumentState((method, params) => this.sendNotification(method, params), (uri) => this.diagnosticsStore.delete(uri), {
+ versionlessPublishQuiescenceMs: options.versionlessPublishQuiescenceMs ?? VERSIONLESS_PUBLISH_QUIESCENCE_MS
+ });
+ this.workspaceMutations = new WorkspaceMutationController(root, this.documents);
+ this.setWorkspaceApplyEditHandler((params) => this.workspaceMutations.handleApplyEdit(params));
+ }
getDiagnosticPullErrors() {
return this.diagnosticPullErrors;
}
async openFile(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- const uri = pathToFileURL2(absPath).href;
- const text = readFileSync(absPath, "utf-8");
- if (!this.openedFiles.has(absPath)) {
- const ext = effectiveExtension(absPath);
- const languageId = getLanguageId(ext);
- const version = 1;
- await this.sendNotification("textDocument/didOpen", {
- textDocument: {
- uri,
- languageId,
- version,
- text
- }
- });
- this.openedFiles.add(absPath);
- this.documentVersions.set(uri, version);
- this.lastSyncedText.set(uri, text);
- await new Promise((r) => setTimeout(r, POST_OPEN_DELAY_MS));
- return;
- }
- const prevText = this.lastSyncedText.get(uri);
- if (prevText === text) {
- return;
- }
- const nextVersion = (this.documentVersions.get(uri) ?? 1) + 1;
- this.documentVersions.set(uri, nextVersion);
- this.lastSyncedText.set(uri, text);
- await this.sendNotification("textDocument/didChange", {
- textDocument: { uri, version: nextVersion },
- contentChanges: [{ text }]
- });
- await this.sendNotification("textDocument/didSave", {
- textDocument: { uri },
- text
- });
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.documents.openFile(absPath);
+ }
+ getOpenDocumentVersion(filePath) {
+ return this.documents.getVersion(this.resolveWorkspacePath(filePath));
+ }
+ getStoredDiagnostics(uri) {
+ return [...this.documents.getStoredDiagnostics(uri)];
}
- async definition(filePath, line, character) {
- const absPath = resolve(contextCwd(), filePath);
+ setWorkspaceEditIo(io) {
+ this.workspaceMutations.setIo(io);
+ }
+ handlePublishDiagnostics(params) {
+ super.handlePublishDiagnostics(params);
+ this.documents.recordPublishedDiagnostics(params);
+ }
+ async definition(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/definition", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character }
- });
+ }, options);
}
- async references(filePath, line, character, includeDeclaration = true) {
- const absPath = resolve(contextCwd(), filePath);
+ async references(filePath, line, character, includeDeclaration = true, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/references", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character },
context: { includeDeclaration }
- });
+ }, options);
}
- async documentSymbols(filePath) {
- const absPath = resolve(contextCwd(), filePath);
+ async documentSymbols(filePath, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/documentSymbol", {
- textDocument: { uri: pathToFileURL2(absPath).href }
- });
+ textDocument: { uri: pathToFileURL3(absPath).href }
+ }, options);
}
- async workspaceSymbols(query) {
- return this.sendRequest("workspace/symbol", { query });
+ async workspaceSymbols(query, signal) {
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("workspace/symbol", { query }, options);
}
isUnsupportedDiagnosticPullError(error) {
if (!(error instanceof Error))
@@ -1082,43 +2720,174 @@ class LspClient extends LspClientConnection {
return true;
return /unsupported|not supported|method not found|unknown request/i.test(error.message);
}
- async diagnostics(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- const uri = pathToFileURL2(absPath).href;
- await this.openFile(absPath);
- await new Promise((r) => setTimeout(r, POST_DIAGNOSTICS_WAIT_MS));
- try {
- const result = await this.sendRequest("textDocument/diagnostic", {
- textDocument: { uri }
- });
- if (result.items) {
- return { items: result.items };
+ freshnessTimeout(absPath) {
+ return {
+ items: [],
+ transientError: {
+ kind: "freshness_timeout",
+ message: `Timed out waiting for fresh diagnostics for ${absPath} within ${this.diagnosticsFreshnessTimeoutMs}ms.`
}
- } catch (error) {
- if (!this.isUnsupportedDiagnosticPullError(error)) {
- this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ };
+ }
+ parseDiagnosticPullReport(value) {
+ if (value.kind === "unchanged") {
+ return {
+ type: "unchanged",
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ return {
+ type: "full",
+ diagnostics: value.items ?? [],
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ async diagnostics(filePath, signal) {
+ signal?.throwIfAborted();
+ const absPath = this.resolveWorkspacePath(filePath);
+ const uri = pathToFileURL3(absPath).href;
+ await this.openFile(absPath);
+ const deadlineAt = Date.now() + this.diagnosticsFreshnessTimeoutMs;
+ for (;; ) {
+ signal?.throwIfAborted();
+ const snapshot = this.documents.captureDiagnosticSnapshot(absPath);
+ if (!snapshot)
+ return this.freshnessTimeout(absPath);
+ const push = this.documents.resolvePushDiagnostics(snapshot);
+ if (push.status === "ready")
+ return { items: [...push.diagnostics] };
+ let pushFallbackOnly = !this.isDiagnosticPullSupported();
+ if (!pushFallbackOnly) {
+ const cached = this.documents.getPullCache(snapshot);
+ try {
+ const remainingMs2 = deadlineAt - Date.now();
+ if (remainingMs2 <= 0)
+ return this.freshnessTimeout(absPath);
+ const result = await this.sendRequest("textDocument/diagnostic", {
+ textDocument: { uri },
+ ...cached?.resultId === undefined ? {} : { previousResultId: cached.resultId }
+ }, { timeoutMs: remainingMs2, ...signal === undefined ? {} : { signal } });
+ if (!this.documents.isCurrentSnapshot(snapshot))
+ continue;
+ const report = this.parseDiagnosticPullReport(result);
+ if (report.type === "full") {
+ this.documents.recordPullDiagnostics(snapshot, {
+ kind: "full",
+ diagnostics: report.diagnostics,
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ });
+ return { items: [...report.diagnostics] };
+ }
+ if (cached !== null && cached.documentVersion === snapshot.version && cached.resultId === report.resultId) {
+ return { items: [...cached.diagnostics] };
+ }
+ } catch (error) {
+ if (this.isUnsupportedDiagnosticPullError(error)) {
+ this.setDiagnosticPullSupported(false);
+ pushFallbackOnly = true;
+ } else if (error instanceof LspRequestTimeoutError) {
+ pushFallbackOnly = true;
+ } else {
+ this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ throw error;
+ }
+ }
}
+ if (!pushFallbackOnly)
+ continue;
+ const remainingMs = deadlineAt - Date.now();
+ if (remainingMs <= 0)
+ return this.freshnessTimeout(absPath);
+ const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;
+ await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);
}
- return { items: this.getStoredDiagnostics(uri) };
}
- async prepareRename(filePath, line, character) {
- const absPath = resolve(contextCwd(), filePath);
+ async prepareRename(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/prepareRename", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character }
- });
+ }, options);
}
- async rename(filePath, line, character, newName) {
- const absPath = resolve(contextCwd(), filePath);
+ async rename(filePath, line, character, newName, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
- return this.sendRequest("textDocument/rename", {
- textDocument: { uri: pathToFileURL2(absPath).href },
- position: { line: line - 1, character },
- newName
- });
+ const acquired = this.workspaceMutations.acquire(signal);
+ if (!acquired.success)
+ return { edit: null, apply: acquired.result };
+ const preCommitSignal = createPreCommitAbortSignal(signal, () => this.workspaceMutations.isBeforeCommit(acquired.lease));
+ try {
+ const renameParams = {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character },
+ newName
+ };
+ const edit = preCommitSignal === undefined ? await this.sendRequest("textDocument/rename", renameParams) : await this.sendRequest("textDocument/rename", renameParams, {
+ signal: preCommitSignal.signal
+ });
+ return await this.workspaceMutations.reconcileRename(acquired.lease, edit);
+ } finally {
+ preCommitSignal?.dispose();
+ this.workspaceMutations.release(acquired.lease);
+ }
+ }
+ resolveWorkspacePath(filePath) {
+ return resolve6(this.root, filePath);
}
}
+function waitForDiagnosticsActivity(wait, signal) {
+ if (!signal)
+ return wait;
+ if (signal.aborted)
+ return Promise.reject(abortError2(signal));
+ return new Promise((resolve7, reject) => {
+ const onAbort = () => {
+ signal.removeEventListener("abort", onAbort);
+ reject(abortError2(signal));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ wait.then(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve7();
+ }, (error) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(error);
+ });
+ });
+}
+function createPreCommitAbortSignal(source, isBeforeCommit) {
+ if (!source)
+ return;
+ const controller = new AbortController;
+ const onAbort = () => {
+ if (isBeforeCommit() && !controller.signal.aborted)
+ controller.abort(preCommitAbortReason(source));
+ };
+ if (source.aborted)
+ onAbort();
+ else
+ source.addEventListener("abort", onAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => source.removeEventListener("abort", onAbort)
+ };
+}
+function preCommitAbortReason(source) {
+ const reason = source.reason;
+ if (reason instanceof Error && reason.name !== "AbortError")
+ return reason;
+ return new Error("LSP request cancelled before workspace edit commit");
+}
+function abortError2(signal) {
+ const reason = signal.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "operation cancelled");
+ error.name = "AbortError";
+ return error;
+}
// ../lsp-core/src/lsp/process-signal-cleanup.ts
function installProcessSignalCleanup(cleanup) {
@@ -1149,7 +2918,7 @@ async function stopClientBestEffort(client) {
function awaitWithSignal(promise, signal) {
if (!signal)
return promise;
- return new Promise((resolve2, reject) => {
+ return new Promise((resolve7, reject) => {
let settled = false;
const onAbort = () => {
if (settled)
@@ -1167,7 +2936,7 @@ function awaitWithSignal(promise, signal) {
return;
settled = true;
signal.removeEventListener("abort", onAbort);
- resolve2(value);
+ resolve7(value);
}, (err) => {
if (settled)
return;
@@ -1421,21 +3190,17 @@ async function disposeDefaultLspManager() {
}
// ../lsp-core/src/lsp/server-install-state.ts
-import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
-import { homedir } from "node:os";
-import { dirname, isAbsolute, join as join2 } from "node:path";
+import { existsSync as existsSync6, mkdirSync, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
+import { dirname as dirname5 } from "node:path";
function getInstallDecisionsPath() {
- const override = contextEnv("LSP_TOOLS_MCP_INSTALL_DECISIONS");
- if (!override)
- return join2(homedir(), ".codex", "lsp-install-decisions.json");
- return isAbsolute(override) ? override : join2(homedir(), override);
+ return lspRequestContext().installDecisionsPath;
}
function loadInstallDecisions() {
const path = getInstallDecisionsPath();
- if (!existsSync2(path))
+ if (!existsSync6(path))
return {};
try {
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
+ const parsed = JSON.parse(readFileSync3(path, "utf8"));
return isInstallDecisions(parsed) ? parsed : {};
} catch {
return {};
@@ -1454,28 +3219,26 @@ function isInstallDecision(value) {
}
function writeInstallDecisions(decisions) {
const path = getInstallDecisionsPath();
- mkdirSync(dirname(path), { recursive: true });
+ mkdirSync(dirname5(path), { recursive: true });
const tmpPath = `${path}.tmp`;
- writeFileSync(tmpPath, `${JSON.stringify(decisions, null, 2)}
+ writeFileSync2(tmpPath, `${JSON.stringify(decisions, null, 2)}
`, "utf8");
- renameSync(tmpPath, path);
+ renameSync2(tmpPath, path);
}
function isInstallDecisions(value) {
- return isRecord2(value) && Object.values(value).every(isInstallDecisionRecord);
+ return isRecord5(value) && Object.values(value).every(isInstallDecisionRecord);
}
function isInstallDecisionRecord(value) {
- if (!isRecord2(value))
+ if (!isRecord5(value))
return false;
return isInstallDecision(value["decision"]) && typeof value["decidedAt"] === "string";
}
-function isRecord2(value) {
+function isRecord5(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
// ../lsp-core/src/lsp/config-loader.ts
-import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
-import { homedir as homedir2 } from "node:os";
-import { delimiter as delimiter2, isAbsolute as isAbsolute2, join as join3 } from "node:path";
+import { existsSync as existsSync7, readFileSync as readFileSync4 } from "node:fs";
// ../lsp-core/src/lsp/server-definitions.ts
var LSP_INSTALL_HINTS = {
@@ -1625,27 +3388,17 @@ var BUILTIN_SERVERS = {
};
// ../lsp-core/src/lsp/config-loader.ts
-function resolveProjectConfigPath(path) {
- return isAbsolute2(path) ? path : join3(contextCwd(), path);
-}
function getProjectConfigPaths() {
- const projectOverride = contextEnv("LSP_TOOLS_MCP_PROJECT_CONFIG");
- if (projectOverride) {
- return projectOverride.split(delimiter2).filter(Boolean).map(resolveProjectConfigPath);
- }
- return [join3(contextCwd(), ".codex", "lsp-client.json")];
+ return lspRequestContext().projectConfigPaths;
}
function getUserConfigPath() {
- const userOverride = contextEnv("LSP_TOOLS_MCP_USER_CONFIG");
- if (!userOverride)
- return join3(homedir2(), ".codex", "lsp-client.json");
- return isAbsolute2(userOverride) ? userOverride : join3(homedir2(), userOverride);
+ return lspRequestContext().userConfigPath;
}
function loadJsonFile(path) {
- if (!existsSync3(path))
+ if (!existsSync7(path))
return null;
try {
- const parsed = JSON.parse(readFileSync3(path, "utf-8"));
+ const parsed = JSON.parse(readFileSync4(path, "utf-8"));
return isConfigJson(parsed) ? parsed : null;
} catch {
return null;
@@ -1784,16 +3537,16 @@ function applyOptionalServerFields(server, entry) {
}
}
function isConfigJson(value) {
- if (!isRecord3(value))
+ if (!isRecord6(value))
return false;
const lsp = value["lsp"];
- return lsp === undefined || isRecord3(lsp);
+ return lsp === undefined || isRecord6(lsp);
}
function parseLspEntry(value) {
return isLspEntry(value) ? value : null;
}
function isLspEntry(value) {
- if (!isRecord3(value))
+ if (!isRecord6(value))
return false;
const disabled = value["disabled"];
const command = value["command"];
@@ -1801,15 +3554,15 @@ function isLspEntry(value) {
const priority = value["priority"];
const env = value["env"];
const initialization = value["initialization"];
- return (disabled === undefined || typeof disabled === "boolean") && (command === undefined || isStringArray(command)) && (extensions === undefined || isStringArray(extensions)) && (priority === undefined || typeof priority === "number") && (env === undefined || isStringRecord(env)) && (initialization === undefined || isRecord3(initialization));
+ return (disabled === undefined || typeof disabled === "boolean") && (command === undefined || isStringArray(command)) && (extensions === undefined || isStringArray(extensions)) && (priority === undefined || typeof priority === "number") && (env === undefined || isStringRecord(env)) && (initialization === undefined || isRecord6(initialization));
}
function isStringArray(value) {
return Array.isArray(value) && value.every((item) => typeof item === "string");
}
function isStringRecord(value) {
- return isRecord3(value) && Object.values(value).every((item) => typeof item === "string");
+ return isRecord6(value) && Object.values(value).every((item) => typeof item === "string");
}
-function isRecord3(value) {
+function isRecord6(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function getDisabledServerIds() {
@@ -1830,8 +3583,8 @@ function getDisabledServerIds() {
}
// ../lsp-core/src/lsp/server-installation.ts
-import { existsSync as existsSync4 } from "node:fs";
-import { delimiter as delimiter3, join as join4 } from "node:path";
+import { existsSync as existsSync8 } from "node:fs";
+import { delimiter as delimiter3, join as join3 } from "node:path";
function isServerInstalled(command, _workingDirectory) {
if (command.length === 0)
return false;
@@ -1839,7 +3592,7 @@ function isServerInstalled(command, _workingDirectory) {
if (!cmd)
return false;
if (cmd.includes("/") || cmd.includes("\\")) {
- if (existsSync4(cmd))
+ if (existsSync8(cmd))
return true;
}
const isWindows = process.platform === "win32";
@@ -1860,7 +3613,7 @@ function isServerInstalled(command, _workingDirectory) {
const paths = pathEnv.split(delimiter3);
for (const p of paths) {
for (const suffix of exts) {
- if (existsSync4(join4(p, cmd + suffix))) {
+ if (existsSync8(join3(p, cmd + suffix))) {
return true;
}
}
@@ -1959,39 +3712,50 @@ function getAllServers() {
var WORKSPACE_MARKERS = [".git", "package.json", "pyproject.toml", "Cargo.toml", "go.mod", "pom.xml", "build.gradle"];
function isDirectoryPath(filePath) {
try {
- return statSync2(filePath).isDirectory();
+ return statSync3(filePath).isDirectory();
} catch {
return false;
}
}
function findWorkspaceRoot(filePath) {
- const abs = resolve2(contextCwd(), filePath);
+ const abs = resolvePathInsideContext(filePath);
let dir = abs;
if (!isDirectoryPath(dir)) {
- dir = dirname2(dir);
+ dir = dirname6(dir);
}
let prevDir = "";
while (dir !== prevDir) {
for (const marker of WORKSPACE_MARKERS) {
- if (existsSync5(join5(dir, marker))) {
+ if (existsSync9(join4(dir, marker))) {
return dir;
}
}
prevDir = dir;
- dir = dirname2(dir);
+ dir = dirname6(dir);
+ }
+ return dirname6(abs);
+}
+function resolvePathInsideContext(filePath) {
+ const cwd = contextCwd();
+ const abs = resolve7(cwd, filePath);
+ const canonical = canonicalizeExistingOrNearestAncestor(abs);
+ if (!isPathInside(cwd, canonical)) {
+ throw new LspInvalidPathError(`LSP file path must be inside request cwd: ${filePath}`);
}
- return dirname2(abs);
+ return canonical;
}
function formatServerLookupError(result) {
if (result.status === "not_installed") {
return formatNotInstalled(result);
}
+ const context = lspRequestContext();
+ const firstProjectConfigPath = context.projectConfigPaths[0] ?? "<project lsp config>";
return [
`No LSP server configured for extension: ${result.extension}`,
"",
`Available servers: ${result.availableServers.slice(0, 10).join(", ")}${result.availableServers.length > 10 ? "..." : ""}`,
"",
- "Configure a custom server in '.codex/lsp-client.json':",
+ `Configure a custom server in '${firstProjectConfigPath}' or '${context.userConfigPath}':`,
" {",
' "lsp": {',
' "my-server": {',
@@ -2007,6 +3771,7 @@ function formatNotInstalled(result) {
const { server, installHint } = result;
const extensions = server.extensions.join(", ");
const decision = loadInstallDecision(server.id)?.decision;
+ const context = lspRequestContext();
if (decision === "declined") {
return `LSP server '${server.id}' (${extensions}) is NOT INSTALLED; user previously declined installation — proceed without LSP.`;
}
@@ -2022,6 +3787,17 @@ function formatNotInstalled(result) {
"The user has pre-authorized LSP installation. Run the install command, then retry this tool:",
` ${installHint}`
].join(`
+`);
+ }
+ if (!context.capabilities.installDecisionTool) {
+ return [
+ ...header,
+ "To install, run:",
+ ` ${installHint}`,
+ "",
+ "ACTION REQUIRED — ASK THE USER whether to install this LSP server.",
+ "Install-decision recording is unavailable in this harness; proceed without LSP if the user declines."
+ ].join(`
`);
}
return [
@@ -2033,6 +3809,7 @@ function formatNotInstalled(result) {
"- If the user agrees: run the install command above, then retry this tool.",
"- If the user declines, OR has NOT explicitly asked for LSP installation:",
` call lsp_install_decision { server_id: "${server.id}", decision: "declined" },`,
+ ` which writes to ${context.installDecisionsPath},`,
" then ignore this message and proceed WITHOUT LSP."
].join(`
`);
@@ -2046,14 +3823,14 @@ var READ_ONLY_RETRY_TOOLS = new Set([
"prepareRename"
]);
async function withLspClient(filePath, fn, toolName, options = {}) {
- const absPath = resolve2(contextCwd(), filePath);
+ const absPath = resolvePathInsideContext(filePath);
if (isDirectoryPath(absPath)) {
throw new LspInvalidPathError("Directory paths are not supported by this LSP tool. " + "Use lsp.diagnostics with a directory path for directory diagnostics.");
}
const ext = effectiveExtension(absPath);
const result = findServerForExtension(ext);
if (result.status !== "found") {
- throw new LspServerLookupError(formatServerLookupError(result));
+ throw new LspServerLookupError(formatServerLookupError(result), result);
}
const server = result.server;
const root = findWorkspaceRoot(absPath);
@@ -2081,11 +3858,11 @@ async function withLspClient(filePath, fn, toolName, options = {}) {
}
// ../lsp-core/src/lsp/directory-diagnostics.ts
-import { existsSync as existsSync6, lstatSync, readdirSync } from "node:fs";
-import { join as join6, resolve as resolve3 } from "node:path";
+import { existsSync as existsSync10, lstatSync as lstatSync4, readdirSync as readdirSync3 } from "node:fs";
+import { join as join5, resolve as resolve8 } from "node:path";
// ../lsp-core/src/lsp/formatters.ts
-import { fileURLToPath } from "node:url";
+import { fileURLToPath as fileURLToPath2 } from "node:url";
var DIAGNOSTIC_SEVERITY_FILTERS = {
error: 1,
warning: 2,
@@ -2093,7 +3870,7 @@ var DIAGNOSTIC_SEVERITY_FILTERS = {
hint: 4
};
function uriToPath(uri) {
- return fileURLToPath(uri);
+ return fileURLToPath2(uri);
}
function formatLocation(loc) {
if ("targetUri" in loc) {
@@ -2179,6 +3956,9 @@ function formatApplyResult(result) {
for (const file of result.filesModified) {
lines.push(` - ${file}`);
}
+ if (result.lateAbort) {
+ lines.push("Cancellation arrived after the filesystem commit began; the committed edit completed.");
+ }
} else {
lines.push("Failed to apply some changes:");
for (const err of result.errors) {
@@ -2194,6 +3974,7 @@ function formatApplyResult(result) {
// ../lsp-core/src/lsp/directory-diagnostics.ts
var SKIP_DIRECTORIES = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
+var DIRECTORY_DIAGNOSTICS_MAX_CONCURRENCY = 4;
function collectFilesWithExtension(dir, extension, maxFiles) {
const files = [];
function walk(currentDir) {
@@ -2201,17 +3982,17 @@ function collectFilesWithExtension(dir, extension, maxFiles) {
return;
let entries = [];
try {
- entries = readdirSync(currentDir);
+ entries = readdirSync3(currentDir);
} catch {
return;
}
for (const entry of entries) {
if (files.length >= maxFiles)
return;
- const fullPath = join6(currentDir, entry);
+ const fullPath = join5(currentDir, entry);
let stat;
try {
- stat = lstatSync(fullPath);
+ stat = lstatSync4(fullPath);
} catch {
continue;
}
@@ -2229,52 +4010,65 @@ function collectFilesWithExtension(dir, extension, maxFiles) {
walk(dir);
return files;
}
-async function aggregateDiagnosticsForDirectory(directory, extension, severity, maxFiles = DEFAULT_MAX_DIRECTORY_FILES) {
+async function aggregateDiagnosticsForDirectory(directory, extension, severity, maxFiles = DEFAULT_MAX_DIRECTORY_FILES, options = {}) {
if (!extension.startsWith(".")) {
throw new LspInvalidPathError(`Extension must start with a dot (e.g., ".ts", not "${extension}"). Use ".${extension}" instead.`);
}
- const absDir = resolve3(contextCwd(), directory);
- if (!existsSync6(absDir)) {
+ const absDir = resolve8(options.workspaceRoot ?? contextCwd(), directory);
+ if (!existsSync10(absDir)) {
throw new LspInvalidPathError(`Directory does not exist: ${absDir}`);
}
- const serverResult = findServerForExtension(extension);
+ const serverResult = options.server === undefined ? findServerForExtension(extension) : { status: "found", server: options.server };
if (serverResult.status !== "found") {
throw new LspServerLookupError(formatServerLookupError(serverResult));
}
const server = serverResult.server;
- const allFiles = collectFilesWithExtension(absDir, extension, maxFiles + 1);
+ const allFiles = (options.listFiles ?? collectFilesWithExtension)(absDir, extension, maxFiles + 1);
const wasCapped = allFiles.length > maxFiles;
const filesToProcess = allFiles.slice(0, maxFiles);
if (filesToProcess.length === 0) {
- return [
+ const output = [
`Directory: ${absDir}`,
`Extension: ${extension}`,
"Files scanned: 0",
`No files found with extension "${extension}".`
].join(`
`);
+ return { output, totalDiagnostics: 0, fileFailures: [] };
}
- const root = findWorkspaceRoot(absDir);
- const manager = getLspManager();
+ const root = options.workspaceRoot ?? findWorkspaceRoot(absDir);
+ const manager = options.manager ?? getLspManager();
const allDiagnostics = [];
const fileErrors = [];
+ const maxConcurrency = Math.max(1, options.maxConcurrency ?? DIRECTORY_DIAGNOSTICS_MAX_CONCURRENCY);
+ options.signal?.throwIfAborted();
const client = await manager.getClient(root, server);
try {
- for (const file of filesToProcess) {
- try {
- const result = await client.diagnostics(file);
- const filtered = filterDiagnosticsBySeverity(result.items, severity);
- allDiagnostics.push(...filtered.map((diagnostic) => ({
- filePath: file,
- diagnostic
- })));
- } catch (e) {
- fileErrors.push({
- file,
- error: e instanceof Error ? e.message : String(e)
- });
+ let nextIndex = 0;
+ const workers = Array.from({ length: Math.min(maxConcurrency, filesToProcess.length) }, async () => {
+ for (;; ) {
+ if (options.signal?.aborted)
+ return;
+ const file = filesToProcess[nextIndex];
+ nextIndex += 1;
+ if (file === undefined)
+ return;
+ try {
+ const result = await client.diagnostics(file, options.signal);
+ const filtered = filterDiagnosticsBySeverity(result.items, severity);
+ allDiagnostics.push(...filtered.map((diagnostic) => ({
+ filePath: file,
+ diagnostic
+ })));
+ } catch (e) {
+ fileErrors.push({
+ file,
+ error: e instanceof Error ? e.message : String(e)
+ });
+ }
}
- }
+ });
+ await Promise.all(workers);
} finally {
manager.releaseClient(root, server.id);
}
@@ -2302,13 +4096,13 @@ async function aggregateDiagnosticsForDirectory(directory, extension, severity,
lines.push("", `... (${allDiagnostics.length - DEFAULT_MAX_DIAGNOSTICS} more diagnostics not shown)`);
}
}
- return lines.join(`
-`);
+ return { output: lines.join(`
+`), totalDiagnostics: allDiagnostics.length, fileFailures: fileErrors };
}
// ../lsp-core/src/lsp/infer-extension.ts
-import { lstatSync as lstatSync2, readdirSync as readdirSync2 } from "node:fs";
-import { join as join7 } from "node:path";
+import { lstatSync as lstatSync5, readdirSync as readdirSync4 } from "node:fs";
+import { join as join6 } from "node:path";
var SKIP_DIRECTORIES2 = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
var MAX_SCAN_ENTRIES = 500;
function inferExtensionFromDirectory(directory) {
@@ -2319,17 +4113,17 @@ function inferExtensionFromDirectory(directory) {
return;
let entries;
try {
- entries = readdirSync2(dir);
+ entries = readdirSync4(dir);
} catch {
return;
}
for (const entry of entries) {
if (scanned >= MAX_SCAN_ENTRIES)
return;
- const fullPath = join7(dir, entry);
+ const fullPath = join6(dir, entry);
let stat;
try {
- stat = lstatSync2(fullPath);
+ stat = lstatSync5(fullPath);
} catch {
continue;
}
@@ -2403,13 +4197,48 @@ function missingDependencyResult(error, details) {
details: {
...details,
error: message,
- errorKind: "missing_dependency"
+ errorKind: "missing_dependency",
+ ...availabilityDetails(error)
}
};
}
+function availabilityDetails(error) {
+ const availability = missingDependencyAvailability(error);
+ return availability === null ? {} : { availability };
+}
+function missingDependencyAvailability(error) {
+ if (!(error instanceof LspServerLookupError) || error.lookup === undefined)
+ return null;
+ const context = lspRequestContext();
+ switch (error.lookup.status) {
+ case "not_configured":
+ return {
+ kind: "not_configured",
+ extension: error.lookup.extension,
+ availableServers: [...error.lookup.availableServers],
+ projectConfigPaths: [...context.projectConfigPaths],
+ userConfigPath: context.userConfigPath,
+ installDecisionTool: context.capabilities.installDecisionTool
+ };
+ case "not_installed":
+ return {
+ kind: "not_installed",
+ serverId: error.lookup.server.id,
+ command: [...error.lookup.server.command],
+ extensions: [...error.lookup.server.extensions],
+ installHint: error.lookup.installHint,
+ installDecisionTool: context.capabilities.installDecisionTool,
+ installDecisionsPath: context.installDecisionsPath
+ };
+ default: {
+ const exhaustive = error.lookup;
+ return exhaustive;
+ }
+ }
+}
// ../lsp-core/src/tools/parameters.ts
-function isRecord4(value) {
+function isRecord7(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function requireString(params, key) {
@@ -2466,7 +4295,7 @@ async function executeLspDiagnostics(params, signal) {
const filePath = requireString(params, "filePath");
const severity = severityFilter(params);
try {
- const absPath = resolve4(contextCwd(), filePath);
+ const absPath = resolvePathInsideContext(filePath);
if (isDirectoryPath(absPath)) {
const extension = inferExtensionFromDirectory(absPath);
if (!extension) {
@@ -2483,18 +4312,33 @@ async function executeLspDiagnostics(params, signal) {
};
return text(message, details3);
}
- const output2 = await aggregateDiagnosticsForDirectory(absPath, extension, severity);
+ const output2 = await aggregateDiagnosticsForDirectory(absPath, extension, severity, undefined, signal === undefined ? {} : { signal });
const details2 = {
filePath,
severity,
mode: "directory",
diagnostics: [],
+ totalDiagnostics: output2.totalDiagnostics,
+ truncated: false,
+ fileFailures: [...output2.fileFailures]
+ };
+ return text(output2.output, details2);
+ }
+ const result = await withLspClient(filePath, async (client) => client.diagnostics(filePath, signal), "diagnostics", clientOptions(signal));
+ if (result.transientError) {
+ const message = result.transientError.message;
+ const details2 = {
+ filePath,
+ severity,
+ mode: "file",
+ diagnostics: [],
totalDiagnostics: 0,
- truncated: false
+ truncated: false,
+ error: message,
+ errorKind: result.transientError.kind
};
- return text(output2, details2);
+ return text(message, details2, true);
}
- const result = await withLspClient(filePath, async (client) => client.diagnostics(filePath), "diagnostics", clientOptions(signal));
const diagnostics = filterDiagnosticsBySeverity(asDiagnosticArray(result), severity);
const total = diagnostics.length;
const truncated = total > DEFAULT_MAX_DIAGNOSTICS;
@@ -2555,7 +4399,7 @@ async function executeLspGotoDefinition(params, signal) {
const line = requireNumber(params, "line");
const character = requireNumber(params, "character");
try {
- const result = await withLspClient(filePath, async (client) => client.definition(filePath, line, character), "definition", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.definition(filePath, line, character, signal), "definition", clientOptions(signal));
const locations = !result ? [] : Array.isArray(result) ? result : [result];
const details = { filePath, line, character, locations };
if (locations.length === 0)
@@ -2580,7 +4424,7 @@ async function executeLspFindReferences(params, signal) {
const character = requireNumber(params, "character");
const includeDeclaration = optionalBoolean(params, "includeDeclaration") ?? true;
try {
- const result = await withLspClient(filePath, async (client) => client.references(filePath, line, character, includeDeclaration), "references", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.references(filePath, line, character, includeDeclaration, signal), "references", clientOptions(signal));
const references = Array.isArray(result) ? result : [];
const total = references.length;
const truncated = total > DEFAULT_MAX_REFERENCES;
@@ -2616,181 +4460,13 @@ async function executeLspFindReferences(params, signal) {
}
}
-// ../lsp-core/src/lsp/workspace-edit.ts
-import { existsSync as existsSync7, readFileSync as readFileSync4, realpathSync, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
-import { dirname as dirname3, isAbsolute as isAbsolute3, relative, resolve as resolve5 } from "node:path";
-import { fileURLToPath as fileURLToPath2 } from "node:url";
-function errorMessage2(error) {
- return error instanceof Error ? error.message : String(error);
-}
-function isPathInsideWorkspace(filePath, workspaceRoot) {
- const relativePath = relative(workspaceRoot, filePath);
- return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute3(relativePath);
-}
-function realpathForValidation(filePath) {
- if (existsSync7(filePath))
- return realpathSync(filePath);
- const parent = dirname3(filePath);
- return resolve5(realpathSync(parent), relative(parent, filePath));
-}
-function uriToWorkspacePath(uri, workspaceRoot) {
- let filePath;
- try {
- filePath = fileURLToPath2(uri);
- } catch (error) {
- return { success: false, error: `non-file URI ${uri}: ${errorMessage2(error)}` };
- }
- let validatedPath;
- try {
- validatedPath = realpathForValidation(filePath);
- } catch (error) {
- return { success: false, error: `${filePath}: ${errorMessage2(error)}` };
- }
- if (!isPathInsideWorkspace(validatedPath, workspaceRoot)) {
- return { success: false, error: `${filePath}: outside workspace ${workspaceRoot}` };
- }
- return { success: true, path: filePath };
-}
-function applyTextEditsToFile(filePath, edits) {
- try {
- const content = readFileSync4(filePath, "utf-8");
- const lines = content.split(`
-`);
- const sortedEdits = [...edits].sort((a, b) => {
- if (b.range.start.line !== a.range.start.line) {
- return b.range.start.line - a.range.start.line;
- }
- return b.range.start.character - a.range.start.character;
- });
- for (const edit of sortedEdits) {
- const startLine = edit.range.start.line;
- const startChar = edit.range.start.character;
- const endLine = edit.range.end.line;
- const endChar = edit.range.end.character;
- if (startLine === endLine) {
- const line = lines[startLine] ?? "";
- lines[startLine] = line.substring(0, startChar) + edit.newText + line.substring(endChar);
- } else {
- const firstLine = lines[startLine] ?? "";
- const lastLine = lines[endLine] ?? "";
- const newContent = firstLine.substring(0, startChar) + edit.newText + lastLine.substring(endChar);
- lines.splice(startLine, endLine - startLine + 1, ...newContent.split(`
-`));
- }
- }
- writeFileSync2(filePath, lines.join(`
-`), "utf-8");
- return { success: true, editCount: edits.length };
- } catch (err) {
- return {
- success: false,
- editCount: 0,
- error: err instanceof Error ? err.message : String(err)
- };
- }
-}
-function applyWorkspaceEdit(edit, options = {}) {
- if (!edit) {
- return { success: false, filesModified: [], totalEdits: 0, errors: ["No edit provided"] };
- }
- const result = { success: true, filesModified: [], totalEdits: 0, errors: [] };
- const workspaceRoot = realpathSync(options.workspaceRoot ?? contextCwd());
- if (edit.changes) {
- for (const [uri, edits] of Object.entries(edit.changes)) {
- const validatedPath = uriToWorkspacePath(uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(validatedPath.error);
- continue;
- }
- const applyResult = applyTextEditsToFile(validatedPath.path, edits);
- if (applyResult.success) {
- result.filesModified.push(validatedPath.path);
- result.totalEdits += applyResult.editCount;
- } else {
- result.success = false;
- result.errors.push(`${validatedPath.path}: ${applyResult.error}`);
- }
- }
- }
- if (edit.documentChanges) {
- for (const change of edit.documentChanges) {
- if (!("kind" in change)) {
- const validatedPath = uriToWorkspacePath(change.textDocument.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(validatedPath.error);
- continue;
- }
- const applyResult = applyTextEditsToFile(validatedPath.path, change.edits);
- if (applyResult.success) {
- result.filesModified.push(validatedPath.path);
- result.totalEdits += applyResult.editCount;
- } else {
- result.success = false;
- result.errors.push(`${validatedPath.path}: ${applyResult.error}`);
- }
- continue;
- }
- if (change.kind === "create") {
- try {
- const validatedPath = uriToWorkspacePath(change.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(`Create ${change.uri}: ${validatedPath.error}`);
- continue;
- }
- writeFileSync2(validatedPath.path, "", "utf-8");
- result.filesModified.push(validatedPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Create ${change.uri}: ${String(err)}`);
- }
- } else if (change.kind === "rename") {
- try {
- const oldPath = uriToWorkspacePath(change.oldUri, workspaceRoot);
- const newPath = uriToWorkspacePath(change.newUri, workspaceRoot);
- if (!oldPath.success || !newPath.success) {
- const error = oldPath.success ? newPath.success ? "invalid URI" : newPath.error : oldPath.error;
- result.success = false;
- result.errors.push(`Rename ${change.oldUri}: ${error}`);
- continue;
- }
- const content = readFileSync4(oldPath.path, "utf-8");
- writeFileSync2(newPath.path, content, "utf-8");
- unlinkSync(oldPath.path);
- result.filesModified.push(newPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Rename ${change.oldUri}: ${String(err)}`);
- }
- } else if (change.kind === "delete") {
- try {
- const validatedPath = uriToWorkspacePath(change.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(`Delete ${change.uri}: ${validatedPath.error}`);
- continue;
- }
- unlinkSync(validatedPath.path);
- result.filesModified.push(validatedPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Delete ${change.uri}: ${String(err)}`);
- }
- }
- }
- }
- return result;
-}
-
// ../lsp-core/src/tools/rename.ts
async function executeLspPrepareRename(params, signal) {
const filePath = requireString(params, "filePath");
const line = requireNumber(params, "line");
const character = requireNumber(params, "character");
try {
- const result = await withLspClient(filePath, async (client) => client.prepareRename(filePath, line, character), "prepareRename", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.prepareRename(filePath, line, character, signal), "prepareRename", clientOptions(signal));
const details = { filePath, line, character, result };
return text(formatPrepareRenameResult(result), details);
} catch (error) {
@@ -2811,13 +4487,9 @@ async function executeLspRename(params, signal) {
const character = requireNumber(params, "character");
const newName = requireString(params, "newName");
try {
- const edit = await withLspClient(filePath, async (client, workspaceRoot) => ({
- edit: await client.rename(filePath, line, character, newName),
- workspaceRoot
- }), "rename", clientOptions(signal));
- const apply = applyWorkspaceEdit(edit.edit, { workspaceRoot: edit.workspaceRoot });
- const details = { filePath, line, character, newName, apply, edit: edit.edit };
- return text(formatApplyResult(apply), details, !apply.success);
+ const result = await withLspClient(filePath, async (client) => client.rename(filePath, line, character, newName, signal), "rename", clientOptions(signal));
+ const details = { filePath, line, character, newName, apply: result.apply, edit: result.edit };
+ return text(formatApplyResult(result.apply), details, !result.apply.success);
} catch (error) {
const missingDependency = missingDependencyResult(error, {
filePath,
@@ -2892,10 +4564,10 @@ async function executeLspSymbols(params, signal) {
errorKind: "missing_query"
});
}
- const symbols2 = await withLspClient(filePath, async (client) => client.workspaceSymbols(query), "workspaceSymbols", clientOptions(signal));
+ const symbols2 = await withLspClient(filePath, async (client) => client.workspaceSymbols(query, signal), "workspaceSymbols", clientOptions(signal));
return formatSymbolsResult(filePath, scope, symbols2, limit, query);
}
- const symbols = await withLspClient(filePath, async (client) => client.documentSymbols(filePath), "documentSymbols", clientOptions(signal));
+ const symbols = await withLspClient(filePath, async (client) => client.documentSymbols(filePath, signal), "documentSymbols", clientOptions(signal));
return formatSymbolsResult(filePath, scope, symbols, limit);
} catch (error) {
const query = optionalString(params, "query");
@@ -3061,10 +4733,10 @@ function matchesToolName(tool, name) {
return tool.name === name || (tool.aliases?.includes(name) ?? false);
}
function coerceToolArguments(value) {
- return isRecord4(value) ? value : {};
+ return isRecord7(value) ? value : {};
}
export {
- isRecord4 as isRecord,
+ isRecord7 as isRecord,
executeLspTool,
executeLspSymbols,
executeLspStatus,
diff --git a/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json b/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json
new file mode 100644
index 00000000..c6511023
--- /dev/null
+++ b/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json
@@ -0,0 +1,55 @@
+{
+ "schemaVersion": 1,
+ "version": "4.18.1",
+ "inputDigest": "sha256:ce104d23ca60e4a61242e99e54232a9fc82078b6471381511abc3187f8489842",
+ "outputs": [
+ {
+ "path": "cli.d.ts",
+ "sha256": "43e818adf60173644896298637f47b01d5819b17eda46eaa32d0c7d64724d012"
+ },
+ {
+ "path": "cli.js",
+ "sha256": "84e00d94acd6c757613daaf8dde1e9425861ab6aa16923daaebd207934bc8ca1"
+ },
+ {
+ "path": "codex-hook-cli.d.ts",
+ "sha256": "bd48e303e97da1d606dff5fa073090d494ed489f9d4f51a5ff566e97b708d34b"
+ },
+ {
+ "path": "codex-hook-cli.js",
+ "sha256": "bc83ec2045b69fc7ecff052262c675757dbb2a66168b40eae7541214736c4fd3"
+ },
+ {
+ "path": "codex-hook.d.ts",
+ "sha256": "70537f67c91bb7b72242396831d4441ead673336537e1f07d94df055d887aeac"
+ },
+ {
+ "path": "codex-hook.js",
+ "sha256": "9a4f53b980521752f603c9a46de8001294c1b964a31f7945eb48ecdae4bf12ac"
+ },
+ {
+ "path": "daemon-cli-path.d.ts",
+ "sha256": "a44c2c2a0edbfa5489a094d875a2cf2a282f1c089bbc315fe70f205a0d7dd526"
+ },
+ {
+ "path": "daemon-cli-path.js",
+ "sha256": "5c34353638e95d4a98664c8d23516475e850983e81900aa40e03752946162830"
+ },
+ {
+ "path": "lsp-session-state.d.ts",
+ "sha256": "403a805ef4c42eae0954c9f39432d0d132b65b6ab066e345aee1dbd383b524e0"
+ },
+ {
+ "path": "lsp-session-state.js",
+ "sha256": "d9c1f4bbace5a8a1fad3d0c3d225e4019700946b2391d1d5ae4d2362ca2e495f"
+ },
+ {
+ "path": "mutated-file-paths.d.ts",
+ "sha256": "a049a783e853964aa88b5a604441540acb56ec91f7b7c5c728cce28d86a6942f"
+ },
+ {
+ "path": "mutated-file-paths.js",
+ "sha256": "bf9d07872875bb1581d5e446b565b903cc24800836bd1dfdfdab8d3efadd963f"
+ }
+ ]
+}
diff --git a/plugins/omo/components/lsp/dist/cli.js b/plugins/omo/components/lsp/dist/cli.js
index 79213565..02e08abe 100644
--- a/plugins/omo/components/lsp/dist/cli.js
+++ b/plugins/omo/components/lsp/dist/cli.js
@@ -1,80 +1,542 @@
#!/usr/bin/env node
-// components/lsp/src/cli.ts
+// src/cli.ts
import { spawn as spawn3 } from "node:child_process";
import { argv, execPath as execPath2, stderr } from "node:process";
-// components/lsp/src/codex-hook-cli.ts
+// src/codex-hook-cli.ts
import { stdin as processStdin } from "node:process";
-// ../../lsp-daemon/dist/index.js
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
-import { pathToFileURL as pathToFileURL2 } from "node:url";
-import { AsyncLocalStorage } from "node:async_hooks";
-import { pathToFileURL } from "node:url";
-import { spawn, spawnSync } from "node:child_process";
-import { existsSync, statSync } from "node:fs";
-import { delimiter, join } from "node:path";
-import { basename, extname } from "node:path";
+// src/codex-hook.ts
+import { readFileSync as readFileSync9, realpathSync as realpathSync6 } from "node:fs";
+import { homedir as homedir3 } from "node:os";
+import { join as join11, resolve as resolve11 } from "node:path";
+
+// ../../../../lsp-daemon/dist/client.js
import { connect as connect2 } from "node:net";
-import { spawn as spawn2 } from "node:child_process";
-import { closeSync as closeSync2, existsSync as existsSync2, mkdirSync as mkdirSync2, openSync as openSync2 } from "node:fs";
+import { AsyncLocalStorage } from "node:async_hooks";
+import { existsSync, realpathSync, statSync } from "node:fs";
+import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from "node:path";
+import { spawn } from "node:child_process";
+import { closeSync as closeSync2, mkdirSync as mkdirSync2, openSync as openSync2 } from "node:fs";
import { connect } from "node:net";
-import { dirname as dirname2 } from "node:path";
+import { dirname as dirname3 } from "node:path";
import { execPath } from "node:process";
-import { fileURLToPath } from "node:url";
-import { closeSync, mkdirSync, openSync, readFileSync as readFileSync2, unlinkSync, writeSync } from "node:fs";
-import { dirname } from "node:path";
+import {
+ chmodSync,
+ closeSync,
+ constants,
+ fchmodSync,
+ fstatSync,
+ lstatSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ unlinkSync,
+ writeSync
+} from "node:fs";
import { createHash } from "node:crypto";
import { createRequire } from "node:module";
-import { homedir, tmpdir } from "node:os";
-import { join as join2 } from "node:path";
-import { resolve as resolve4 } from "node:path";
-import { existsSync as existsSync6, statSync as statSync2 } from "node:fs";
-import { dirname as dirname4, join as join6, resolve as resolve2 } from "node:path";
-import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync, writeFileSync } from "node:fs";
-import { homedir as homedir2 } from "node:os";
-import { dirname as dirname3, isAbsolute, join as join3 } from "node:path";
-import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
-import { homedir as homedir3 } from "node:os";
-import { delimiter as delimiter2, isAbsolute as isAbsolute2, join as join4 } from "node:path";
-import { existsSync as existsSync5 } from "node:fs";
-import { delimiter as delimiter3, join as join5 } from "node:path";
-import { existsSync as existsSync7, lstatSync, readdirSync } from "node:fs";
-import { join as join7, resolve as resolve3 } from "node:path";
+import { homedir as homedir2, tmpdir, userInfo } from "node:os";
+import * as path from "node:path";
+import { fileURLToPath } from "node:url";
+import { statSync as statSync2 } from "node:fs";
+import { isAbsolute as isAbsolute2 } from "node:path";
+import { existsSync as existsSync9, statSync as statSync4 } from "node:fs";
+import { dirname as dirname8, join as join4, resolve as resolve7 } from "node:path";
+import { basename as basename2, extname } from "node:path";
+import { resolve as resolve6 } from "node:path";
+import { pathToFileURL as pathToFileURL3 } from "node:url";
+import { pathToFileURL } from "node:url";
+import { spawn as spawn2, spawnSync } from "node:child_process";
+import { existsSync as existsSync2, statSync as statSync3 } from "node:fs";
+import { delimiter as delimiter2, join as join2 } from "node:path";
+import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
+import { relative as relative2, resolve as resolve2 } from "node:path";
+import { pathToFileURL as pathToFileURL2 } from "node:url";
+import { existsSync as existsSync4, lstatSync as lstatSync3, renameSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync as existsSync3, lstatSync as lstatSync2, readFileSync as readFileSync3, readdirSync, realpathSync as realpathSync3 } from "node:fs";
+import { dirname as dirname4, isAbsolute as isAbsolute3, relative as relative3, resolve as resolve3 } from "node:path";
import { fileURLToPath as fileURLToPath2 } from "node:url";
-import { lstatSync as lstatSync2, readdirSync as readdirSync2 } from "node:fs";
-import { join as join8 } from "node:path";
-import { existsSync as existsSync8, readFileSync as readFileSync5, realpathSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
-import { dirname as dirname5, isAbsolute as isAbsolute3, relative, resolve as resolve5 } from "node:path";
+import { createHash as createHash2 } from "node:crypto";
+import { dirname as dirname5, relative as relative4, resolve as resolve4 } from "node:path";
+import { existsSync as existsSync5, lstatSync as lstatSync4, readdirSync as readdirSync2 } from "node:fs";
+import { dirname as dirname6, resolve as resolve5 } from "node:path";
+import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
+import { dirname as dirname7 } from "node:path";
+import { existsSync as existsSync7, readFileSync as readFileSync5 } from "node:fs";
+import { existsSync as existsSync8 } from "node:fs";
+import { delimiter as delimiter3, join as join3 } from "node:path";
+import { existsSync as existsSync10, lstatSync as lstatSync5, readdirSync as readdirSync3 } from "node:fs";
+import { join as join5, resolve as resolve8 } from "node:path";
import { fileURLToPath as fileURLToPath3 } from "node:url";
-function reportBestEffortCleanupError(operation, error) {
- if (process.env["CODEX_LSP_DEBUG_CLEANUP"] !== "1")
- return;
- const message = error instanceof Error ? error.message : String(error);
- console.error(`[codex-lsp] ignored ${operation} failure during cleanup: ${message}`);
+import { lstatSync as lstatSync6, readdirSync as readdirSync4 } from "node:fs";
+import { join as join6 } from "node:path";
+import { statSync as statSync5 } from "node:fs";
+import { isAbsolute as isAbsolute4 } from "node:path";
+
+class LspRequestContextParseError extends Error {
+ code;
+ name = "LspRequestContextParseError";
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ }
+}
+
+class LspRequestContextUnavailableError extends Error {
+ name = "LspRequestContextUnavailableError";
+ constructor() {
+ super("LSP request context is required. Standalone MCP startup must install one with runWithRequestContext(createStandaloneMcpRequestContext()).");
+ }
}
var storage = new AsyncLocalStorage;
+var CONTEXT_FIELDS = new Set(["cwd", "projectConfigPaths", "userConfigPath", "installDecisionsPath", "capabilities"]);
+var CAPABILITY_FIELDS = new Set(["installDecisionTool"]);
+function lspRequestContext() {
+ const context = storage.getStore();
+ if (!context)
+ throw new LspRequestContextUnavailableError;
+ return context;
+}
function contextCwd() {
- return storage.getStore()?.cwd ?? process.cwd();
+ return lspRequestContext().cwd;
+}
+function parseLspRequestContext(value) {
+ if (!isRecord(value)) {
+ throw new LspRequestContextParseError("invalid_context", "LSP request context must be an object.");
+ }
+ rejectUnknownFields(value, CONTEXT_FIELDS, "context");
+ const cwd = stringField(value, "cwd");
+ const projectConfigPaths = stringArrayField(value, "projectConfigPaths");
+ const userConfigPath = stringField(value, "userConfigPath");
+ const installDecisionsPath = stringField(value, "installDecisionsPath");
+ const capabilities = capabilitiesField(value["capabilities"]);
+ const canonical = canonicalCwd(cwd);
+ for (const path2 of projectConfigPaths) {
+ requireAbsolutePath(path2, "projectConfigPaths");
+ const projectPath = canonicalizeExistingOrNearestAncestor(path2);
+ if (!isPathInside(canonical, projectPath)) {
+ throw new LspRequestContextParseError("project_config_outside_cwd", `Project LSP config path must be inside cwd: ${path2}`);
+ }
+ }
+ requireAbsolutePath(userConfigPath, "userConfigPath");
+ requireAbsolutePath(installDecisionsPath, "installDecisionsPath");
+ return {
+ cwd: canonical,
+ projectConfigPaths: projectConfigPaths.map((path2) => canonicalizeExistingOrNearestAncestor(path2)),
+ userConfigPath,
+ installDecisionsPath,
+ capabilities
+ };
}
-function contextEnv(key) {
- const store = storage.getStore();
- if (store?.env)
- return store.env[key];
- return process.env[key];
+function canonicalCwd(cwd) {
+ const resolved = resolve(cwd);
+ if (!existsSync(resolved) || !statSync(resolved).isDirectory()) {
+ throw new LspRequestContextParseError("invalid_cwd", `LSP request cwd must be an existing directory: ${cwd}`);
+ }
+ return realpathSync(resolved);
+}
+function canonicalizeExistingOrNearestAncestor(path2) {
+ let current = resolve(path2);
+ const suffix = [];
+ while (true) {
+ try {
+ const existing = realpathSync(current);
+ return suffix.length === 0 ? existing : join(existing, ...suffix);
+ } catch (error) {
+ if (!isMissingPathError(error))
+ throw error;
+ const parent = dirname(current);
+ if (parent === current)
+ throw error;
+ suffix.unshift(basename(current));
+ current = parent;
+ }
+ }
+}
+function capabilitiesField(value) {
+ if (!isRecord(value)) {
+ throw new LspRequestContextParseError("invalid_capabilities", "LSP request capabilities must be an object.");
+ }
+ rejectUnknownFields(value, CAPABILITY_FIELDS, "capabilities");
+ const installDecisionTool = value["installDecisionTool"];
+ if (typeof installDecisionTool !== "boolean") {
+ throw new LspRequestContextParseError("invalid_install_decision_capability", "LSP request capabilities.installDecisionTool must be a boolean.");
+ }
+ return { installDecisionTool };
+}
+function stringField(value, field) {
+ const fieldValue = value[field];
+ if (typeof fieldValue !== "string" || fieldValue.length === 0) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string.`);
+ }
+ return fieldValue;
+}
+function stringArrayField(value, field) {
+ const fieldValue = value[field];
+ if (!Array.isArray(fieldValue) || !fieldValue.every((item) => typeof item === "string" && item.length > 0)) {
+ throw new LspRequestContextParseError("invalid_field", `LSP request context.${field} must be a non-empty string array.`);
+ }
+ return fieldValue;
+}
+function requireAbsolutePath(path2, field) {
+ if (!isAbsolute(path2)) {
+ throw new LspRequestContextParseError("relative_path", `LSP request context.${field} must be absolute: ${path2}`);
+ }
+}
+function isPathInside(parent, child) {
+ const childPath = resolve(child);
+ const relativePath = relative(parent, childPath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute(relativePath);
+}
+function isMissingPathError(error) {
+ const code = errorCode(error);
+ return code === "ENOENT" || code === "ENOTDIR";
+}
+function rejectUnknownFields(value, allowed, scope) {
+ const unknown = Object.keys(value).filter((key) => !allowed.has(key));
+ if (unknown.length > 0) {
+ throw new LspRequestContextParseError("unknown_field", `Unknown LSP request ${scope} field: ${unknown.join(", ")}`);
+ }
+}
+function isRecord(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function errorCode(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
+}
+function isPlainRecord(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+var OMO_DAEMON_PROTOCOL_VERSION = 1;
+var AUTH_ERROR_CODE = -32001;
+function authEnvelope(token) {
+ return { protocolVersion: OMO_DAEMON_PROTOCOL_VERSION, token };
+}
+function readAuthToken(paths) {
+ try {
+ const token = readFileSync(paths.auth, "utf8").trim();
+ return token.length > 0 ? token : null;
+ } catch (error) {
+ if (error instanceof Error)
+ return null;
+ throw error;
+ }
+}
+function isAuthErrorResponse(message) {
+ if (!isPlainRecord(message))
+ return false;
+ const error = message["error"];
+ if (!isPlainRecord(error))
+ return false;
+ const data = error["data"];
+ return error["code"] === AUTH_ERROR_CODE && isPlainRecord(data) && data["code"] === "daemon_authentication_failed";
+}
+var OMO_LSP_DAEMON_DIR = "OMO_LSP_DAEMON_DIR";
+var OMO_LSP_DAEMON_CLI = "OMO_LSP_DAEMON_CLI";
+var OMO_LSP_DAEMON_VERSION = "OMO_LSP_DAEMON_VERSION";
+var DAEMON_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
+
+class InvalidRuntimeOverrideError extends Error {
+ code = "invalid_runtime_override";
+ reason;
+ constructor(reason, message) {
+ super(message);
+ this.name = "InvalidRuntimeOverrideError";
+ this.reason = reason;
+ }
+}
+
+class InvalidDaemonVersionError extends Error {
+ code = "invalid_daemon_version";
+ version;
+ constructor(version) {
+ super("LSP daemon version must match [A-Za-z0-9][A-Za-z0-9._+-]{0,127}");
+ this.name = "InvalidDaemonVersionError";
+ this.version = version;
+ }
+}
+function validateDaemonVersion(version) {
+ if (!DAEMON_VERSION_PATTERN.test(version))
+ throw new InvalidDaemonVersionError(version);
+ return version;
+}
+function resolveDaemonRuntime(env, defaults) {
+ const cliOverride = env[OMO_LSP_DAEMON_CLI];
+ const versionOverride = env[OMO_LSP_DAEMON_VERSION];
+ const hasCliOverride = cliOverride !== undefined;
+ const hasVersionOverride = versionOverride !== undefined;
+ if (hasCliOverride !== hasVersionOverride) {
+ throw new InvalidRuntimeOverrideError("paired_values_required", `${OMO_LSP_DAEMON_CLI} and ${OMO_LSP_DAEMON_VERSION} must be set together`);
+ }
+ if (!hasCliOverride || !hasVersionOverride) {
+ if (!isAbsolute2(defaults.cliPath)) {
+ throw new InvalidRuntimeOverrideError("packaged_cli_must_be_absolute", "Packaged LSP daemon CLI path must be absolute");
+ }
+ return { cliPath: defaults.cliPath, version: validateDaemonVersion(defaults.version) };
+ }
+ if (!isAbsolute2(cliOverride)) {
+ throw new InvalidRuntimeOverrideError("cli_must_be_absolute", `${OMO_LSP_DAEMON_CLI} must be an absolute path to an existing regular file`);
+ }
+ let cliStats;
+ try {
+ cliStats = statSync2(cliOverride);
+ } catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ throw new InvalidRuntimeOverrideError("cli_not_found", `${OMO_LSP_DAEMON_CLI} must name an existing regular file`);
+ }
+ if (!cliStats.isFile()) {
+ throw new InvalidRuntimeOverrideError("cli_not_file", `${OMO_LSP_DAEMON_CLI} must name an existing regular file`);
+ }
+ return { cliPath: cliOverride, version: validateDaemonVersion(versionOverride) };
+}
+var requireFromHere = createRequire(import.meta.url);
+var MAX_SOCKET_PATH_LENGTH = 100;
+
+class InvalidDaemonDirectoryError extends Error {
+ code = "invalid_daemon_directory";
+ directory;
+ constructor(directory) {
+ super(`${OMO_LSP_DAEMON_DIR} must be an absolute path`);
+ this.name = "InvalidDaemonDirectoryError";
+ this.directory = directory;
+ }
+}
+function resolveDaemonVersion(requireFn = requireFromHere) {
+ for (const candidate of ["./package.json", "../package.json"]) {
+ let loaded;
+ try {
+ loaded = requireFn(candidate);
+ } catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ continue;
+ }
+ if (typeof loaded === "object" && loaded !== null && "version" in loaded) {
+ const version = Reflect.get(loaded, "version");
+ if (typeof version === "string")
+ return validateDaemonVersion(version);
+ }
+ }
+ return "0";
+}
+function packagedRuntimeDefaults() {
+ return {
+ cliPath: fileURLToPath(new URL("./cli.js", import.meta.url)),
+ version: resolveDaemonVersion()
+ };
+}
+function daemonBaseDir(env = process.env, platform = defaultDaemonPlatform()) {
+ const override = env[OMO_LSP_DAEMON_DIR];
+ if (override !== undefined) {
+ if (!platform.path.isAbsolute(override))
+ throw new InvalidDaemonDirectoryError(override);
+ return platform.path.resolve(override);
+ }
+ return platform.path.resolve(platform.path.join(platform.homedir(), ".omo", "lsp-daemon"));
+}
+function daemonPaths(env = process.env, runtimeDefaults = packagedRuntimeDefaults(), platform = defaultDaemonPlatform()) {
+ const runtime = resolveDaemonRuntime(env, runtimeDefaults);
+ const baseDir = daemonBaseDir(env, platform);
+ const dir = platform.path.resolve(platform.path.join(baseDir, `v${runtime.version}`));
+ return {
+ version: runtime.version,
+ cliPath: runtime.cliPath,
+ dir,
+ socket: resolveSocketPath(dir, runtime.version, platform),
+ lock: platform.path.join(dir, "daemon.lock"),
+ pid: platform.path.join(dir, "daemon.pid"),
+ auth: platform.path.join(dir, "daemon.auth"),
+ endpoint: platform.path.join(dir, "daemon.endpoint"),
+ owner: platform.path.join(dir, "daemon.owner"),
+ log: platform.path.join(dir, "daemon.log")
+ };
+}
+function defaultDaemonPlatform() {
+ return {
+ platform: process.platform,
+ homedir: homedir2,
+ tmpdir,
+ getuid: () => typeof process.getuid === "function" ? process.getuid() : undefined,
+ username: () => userInfo().username,
+ path
+ };
+}
+function resolveSocketPath(dir, version, platform) {
+ const canonicalVersionDir = platform.path.resolve(dir);
+ if (platform.platform === "win32") {
+ const currentUserDiscriminator = `${platform.getuid() ?? "win"}:${platform.username()}:${platform.path.resolve(platform.homedir())}`;
+ const digest = shortDigest(`${canonicalVersionDir}\x00${currentUserDiscriminator}`);
+ return `\\\\.\\pipe\\omo-lsp-${version}-${digest}`;
+ }
+ const natural = platform.path.join(canonicalVersionDir, "daemon.sock");
+ if (natural.length < MAX_SOCKET_PATH_LENGTH)
+ return natural;
+ return platform.path.join(platform.tmpdir(), `omo-lsp-${version}-${shortDigest(canonicalVersionDir)}`, "daemon.sock");
+}
+function shortDigest(value) {
+ return createHash("sha256").update(value).digest("hex").slice(0, 16);
+}
+function encodeJsonLine(message) {
+ return `${JSON.stringify(message)}
+`;
+}
+function createLineDecoder(onMessage, onParseError) {
+ let buffer = "";
+ return {
+ push(chunk) {
+ buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
+ let index = buffer.indexOf(`
+`);
+ while (index !== -1) {
+ const raw = buffer.slice(0, index).trim();
+ buffer = buffer.slice(index + 1);
+ if (raw.length > 0) {
+ try {
+ onMessage(JSON.parse(raw));
+ } catch (error) {
+ if (error instanceof Error) {
+ onParseError?.(raw, error);
+ } else {
+ throw error;
+ }
+ }
+ }
+ index = buffer.indexOf(`
+`);
+ }
+ }
+ };
+}
+var PROBE_TIMEOUT_MS = 500;
+var DEFAULT_READY_TIMEOUT_MS = 5000;
+var DEFAULT_POLL_INTERVAL_MS = 100;
+
+class DaemonUnreachableError extends Error {
+ constructor(socketPath) {
+ super(`LSP daemon did not become reachable at ${socketPath}`);
+ this.name = "DaemonUnreachableError";
+ }
+}
+async function ensureDaemonRunning(paths, deps = defaultEnsureDaemonDeps(), options = {}) {
+ const readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
+ const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
+ if (await deps.probe(paths))
+ return;
+ deps.spawnDaemon(paths);
+ await waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs);
+}
+async function waitUntilReachable(paths, deps, readyTimeoutMs, pollIntervalMs) {
+ const deadline = deps.now() + readyTimeoutMs;
+ for (;; ) {
+ if (await deps.probe(paths))
+ return;
+ if (deps.now() >= deadline)
+ throw new DaemonUnreachableError(paths.socket);
+ await deps.sleep(pollIntervalMs);
+ }
+}
+async function probeDaemon(paths, timeoutMs = PROBE_TIMEOUT_MS) {
+ const token = readAuthToken(paths);
+ if (!token)
+ return false;
+ return await pingDaemon(paths, token, timeoutMs) !== null;
+}
+function pingDaemon(paths, token, timeoutMs = PROBE_TIMEOUT_MS) {
+ return new Promise((resolve22) => {
+ const socket = connect(paths.socket);
+ let settled = false;
+ const finish = (value) => {
+ if (settled)
+ return;
+ settled = true;
+ socket.destroy();
+ resolve22(value);
+ };
+ const timer = setTimeout(() => finish(null), timeoutMs);
+ timer.unref?.();
+ const decoder = createLineDecoder((message) => {
+ clearTimeout(timer);
+ finish(parsePingResponse(message));
+ });
+ socket.once("connect", () => {
+ socket.write(encodeJsonLine({ jsonrpc: "2.0", id: 1, method: "omo/ping", params: { _omo: authEnvelope(token) } }));
+ });
+ socket.on("data", (chunk) => decoder.push(chunk));
+ socket.once("error", () => {
+ clearTimeout(timer);
+ finish(null);
+ });
+ });
+}
+function spawnDaemonProcess(paths) {
+ mkdirSync2(dirname3(paths.log), { recursive: true });
+ const logFd = openSync2(paths.log, "a");
+ try {
+ const child = spawn(execPath, [paths.cliPath, "daemon"], {
+ detached: true,
+ stdio: ["ignore", logFd, logFd]
+ });
+ child.unref();
+ } finally {
+ closeSync2(logFd);
+ }
+}
+function defaultEnsureDaemonDeps() {
+ return {
+ probe: (paths) => probeDaemon(paths),
+ spawnDaemon: (paths) => spawnDaemonProcess(paths),
+ sleep: (ms) => new Promise((resolve22) => {
+ setTimeout(resolve22, ms);
+ }),
+ now: () => Date.now()
+ };
+}
+function parsePingResponse(message) {
+ if (!message || typeof message !== "object" || Array.isArray(message))
+ return null;
+ const result = Reflect.get(message, "result");
+ if (!result || typeof result !== "object" || Array.isArray(result))
+ return null;
+ const pid = Reflect.get(result, "pid");
+ const nonce = Reflect.get(result, "nonce");
+ const startedAt = Reflect.get(result, "startedAt");
+ const endpoint = Reflect.get(result, "endpoint");
+ if (typeof pid !== "number" || typeof nonce !== "string" || typeof startedAt !== "string")
+ return null;
+ if (!endpoint || typeof endpoint !== "object" || Array.isArray(endpoint))
+ return null;
+ const path2 = Reflect.get(endpoint, "path");
+ const kind = Reflect.get(endpoint, "kind");
+ if (typeof path2 !== "string")
+ return null;
+ if (kind === "windows")
+ return { pid, nonce, startedAt, endpoint: { kind, path: path2 } };
+ if (kind === "missing")
+ return { pid, nonce, startedAt, endpoint: { kind, path: path2 } };
+ const dev = Reflect.get(endpoint, "dev");
+ const ino = Reflect.get(endpoint, "ino");
+ if (kind === "unix" && typeof dev === "number" && typeof ino === "number") {
+ return { pid, nonce, startedAt, endpoint: { kind, path: path2, dev, ino } };
+ }
+ return null;
+}
+var HEADER_SEPARATOR = Buffer.from(`\r
+\r
+`);
+var DEFAULT_IDLE_TIMEOUT_MS = 10 * 60000;
+var BASENAME_EXTENSIONS = {
+ Dockerfile: ".dockerfile",
+ Containerfile: ".dockerfile"
+};
+function effectiveExtension(filePath) {
+ return BASENAME_EXTENSIONS[basename2(filePath)] ?? extname(filePath);
}
-var DEFAULT_MAX_REFERENCES = 200;
-var DEFAULT_MAX_SYMBOLS = 200;
-var DEFAULT_MAX_DIAGNOSTICS = 200;
-var DEFAULT_MAX_DIRECTORY_FILES = 50;
-var REQUEST_TIMEOUT_MS = 15000;
-var INIT_TIMEOUT_MS = 60000;
-var IDLE_TIMEOUT_MS = 5 * 60000;
-var REAPER_INTERVAL_MS = 60000;
-var STOP_HARD_KILL_TIMEOUT_MS = 5000;
-var STOP_SIGKILL_GRACE_MS = 1000;
class LspConnectionClosedError extends Error {
serverId;
@@ -122,7 +584,12 @@ class LspInvalidPathError extends Error {
}
class LspServerLookupError extends Error {
+ lookup;
name = "LspServerLookupError";
+ constructor(message, lookup) {
+ super(message);
+ this.lookup = lookup;
+ }
}
class LspServerInitializingError extends Error {
@@ -140,7 +607,25 @@ class LspProcessSpawnError extends Error {
function isLspDeadConnectionError(err) {
return err instanceof LspConnectionClosedError || err instanceof LspProcessExitedError;
}
-var HEADER_SEPARATOR = `\r
+function writeCleanupError(message) {
+ process.stderr.write(`${message}
+`);
+}
+function reportBestEffortCleanupError(operation, error, logger = writeCleanupError) {
+ const message = error instanceof Error ? error.message : String(error);
+ logger(`[lsp] ignored ${operation} failure during cleanup: ${message}`);
+}
+var DEFAULT_MAX_REFERENCES = 200;
+var DEFAULT_MAX_SYMBOLS = 200;
+var DEFAULT_MAX_DIAGNOSTICS = 200;
+var DEFAULT_MAX_DIRECTORY_FILES = 50;
+var REQUEST_TIMEOUT_MS = 15000;
+var INIT_TIMEOUT_MS = 60000;
+var IDLE_TIMEOUT_MS = 5 * 60000;
+var REAPER_INTERVAL_MS = 60000;
+var STOP_HARD_KILL_TIMEOUT_MS = 5000;
+var STOP_SIGKILL_GRACE_MS = 1000;
+var HEADER_SEPARATOR2 = `\r
\r
`;
var PARSE_ERROR = -32700;
@@ -186,28 +671,80 @@ class JsonRpcConnection {
onError(handler) {
this.errorHandlers.push(handler);
}
- async sendRequest(method, params) {
+ async sendRequest(method, params, options = {}) {
if (this.disposed)
throw new Error("JSON-RPC connection is disposed");
const id = this.nextRequestId;
this.nextRequestId += 1;
+ const key = String(id);
const message = params === undefined ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
- const responsePromise = new Promise((resolve6, reject) => {
- this.pendingRequests.set(String(id), {
+ let requestWritten = false;
+ let cancelAfterWrite = false;
+ let settled = false;
+ const writeCancel = () => this.writeMessage({ jsonrpc: "2.0", method: "$/cancelRequest", params: { id } });
+ const responsePromise = new Promise((resolve22, reject) => {
+ const cleanup = () => {
+ options.signal?.removeEventListener("abort", onAbort);
+ };
+ const settleCancel = () => {
+ if (settled)
+ return;
+ settled = true;
+ this.pendingRequests.delete(key);
+ cleanup();
+ const rejectCancelled = () => reject(abortError(options.signal));
+ if (!requestWritten) {
+ cancelAfterWrite = true;
+ rejectCancelled();
+ return;
+ }
+ writeCancel().then(rejectCancelled, (error) => {
+ this.emitError(toError(error));
+ rejectCancelled();
+ });
+ };
+ const onAbort = () => settleCancel();
+ this.pendingRequests.set(key, {
resolve(result) {
- resolve6(result);
+ settled = true;
+ cleanup();
+ resolve22(result);
},
- reject
+ reject(error) {
+ settled = true;
+ cleanup();
+ reject(error);
+ },
+ cleanup
});
+ if (options.signal?.aborted) {
+ settleCancel();
+ return;
+ }
+ options.signal?.addEventListener("abort", onAbort, { once: true });
});
+ if (settled)
+ return responsePromise;
try {
await this.writeMessage(message);
+ requestWritten = true;
+ if (cancelAfterWrite)
+ await writeCancel();
} catch (error) {
- this.pendingRequests.delete(String(id));
+ if (settled)
+ return responsePromise;
+ const pending = this.pendingRequests.get(key);
+ if (pending) {
+ pending.cleanup();
+ this.pendingRequests.delete(key);
+ }
throw error;
}
return responsePromise;
}
+ pendingRequestCount() {
+ return this.pendingRequests.size;
+ }
async sendNotification(method, params) {
if (this.disposed)
return;
@@ -224,6 +761,7 @@ class JsonRpcConnection {
this.reader.off("error", this.handleStreamError);
this.writer.off("error", this.handleStreamError);
for (const pending of this.pendingRequests.values()) {
+ pending.cleanup();
pending.reject(new Error("JSON-RPC connection disposed"));
}
this.pendingRequests.clear();
@@ -245,17 +783,17 @@ class JsonRpcConnection {
};
drainInputBuffer() {
while (true) {
- const headerEnd = this.inputBuffer.indexOf(HEADER_SEPARATOR);
+ const headerEnd = this.inputBuffer.indexOf(HEADER_SEPARATOR2);
if (headerEnd === -1)
return;
const headers = this.inputBuffer.subarray(0, headerEnd).toString("ascii");
- const contentLength = parseContentLength(headers);
+ const contentLength = parseContentLength2(headers);
if (contentLength === null) {
this.inputBuffer = Buffer.alloc(0);
this.emitError(new Error("JSON-RPC message is missing Content-Length header"));
return;
}
- const bodyStart = headerEnd + Buffer.byteLength(HEADER_SEPARATOR);
+ const bodyStart = headerEnd + Buffer.byteLength(HEADER_SEPARATOR2);
const bodyEnd = bodyStart + contentLength;
if (this.inputBuffer.length < bodyEnd)
return;
@@ -299,6 +837,7 @@ class JsonRpcConnection {
if (!pending)
return;
this.pendingRequests.delete(String(id));
+ pending.cleanup();
if ("error" in message) {
pending.reject(jsonRpcErrorToError(message["error"]));
return;
@@ -312,7 +851,11 @@ class JsonRpcConnection {
try {
handler(params);
} catch (error) {
- this.emitError(toError(error));
+ if (error instanceof Error) {
+ this.emitError(error);
+ return;
+ }
+ this.emitError(new Error(String(error)));
}
}
handleRequest(message) {
@@ -337,13 +880,13 @@ class JsonRpcConnection {
const payload = `Content-Length: ${Buffer.byteLength(body, "utf8")}\r
\r
${body}`;
- return new Promise((resolve6, reject) => {
+ return new Promise((resolve22, reject) => {
this.writer.write(payload, (error) => {
if (error) {
reject(error);
return;
}
- resolve6();
+ resolve22();
});
});
}
@@ -353,7 +896,15 @@ ${body}`;
}
}
}
-function parseContentLength(headers) {
+function abortError(signal) {
+ const reason = signal?.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "LSP request cancelled");
+ error.name = "AbortError";
+ return error;
+}
+function parseContentLength2(headers) {
for (const line of headers.split(`\r
`)) {
const separatorIndex = line.indexOf(":");
@@ -401,10 +952,10 @@ function reportKillError(context, error) {
}
function validateCwd(cwd) {
try {
- if (!existsSync(cwd)) {
+ if (!existsSync2(cwd)) {
return { valid: false, error: `Working directory does not exist: ${cwd}` };
}
- const stats = statSync(cwd);
+ const stats = statSync3(cwd);
if (!stats.isDirectory()) {
return { valid: false, error: `Path is not a directory: ${cwd}` };
}
@@ -417,9 +968,9 @@ function validateCwd(cwd) {
}
}
function wrap(proc) {
- const exitedPromise = new Promise((resolve6) => {
- proc.once("close", (code) => resolve6(code ?? 0));
- proc.once("error", () => resolve6(1));
+ const exitedPromise = new Promise((resolve22) => {
+ proc.once("close", (code) => resolve22(code ?? 0));
+ proc.once("error", () => resolve22(1));
});
if (!proc.stdin || !proc.stdout || !proc.stderr) {
throw new LspProcessSpawnError("Spawned process is missing one of stdin/stdout/stderr pipes");
@@ -473,7 +1024,7 @@ function isWindowsShellShim(command) {
return lowerCommand.endsWith(".cmd") || lowerCommand.endsWith(".bat");
}
function splitPath(pathValue, platform) {
- const separator = platform === "win32" ? ";" : delimiter;
+ const separator = platform === "win32" ? ";" : delimiter2;
return pathValue.split(separator).filter(Boolean);
}
function getWindowsPathExtensions(env) {
@@ -488,8 +1039,8 @@ function resolveWindowsCommand(command, env) {
const extensions = getWindowsPathExtensions(env);
for (const baseDirectory of baseDirectories) {
for (const extension of extensions) {
- const candidate = baseDirectory ? join(baseDirectory, `${command}${extension}`) : `${command}${extension}`;
- if (existsSync(candidate))
+ const candidate = baseDirectory ? join2(baseDirectory, `${command}${extension}`) : `${command}${extension}`;
+ if (existsSync2(candidate))
return candidate;
}
}
@@ -523,7 +1074,7 @@ function spawnProcess(command, options) {
throw new LspProcessSpawnError("[lsp] empty command");
}
const preparedCommand = createSpawnCommand(command, process.platform, process.env["ComSpec"] ?? "cmd.exe", options.env);
- const proc = spawn(preparedCommand.command, preparedCommand.args, {
+ const proc = spawn2(preparedCommand.command, preparedCommand.args, {
cwd: options.cwd,
env: options.env,
stdio: ["pipe", "pipe", "pipe"],
@@ -533,15 +1084,15 @@ function spawnProcess(command, options) {
});
return wrap(proc);
}
-function isRecord(value) {
+function isRecord2(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function parseConfigurationItems(params) {
- if (!isRecord(params) || !Array.isArray(params["items"]))
+ if (!isRecord2(params) || !Array.isArray(params["items"]))
return [];
const items = [];
for (const item of params["items"]) {
- if (!isRecord(item))
+ if (!isRecord2(item))
continue;
const section = item["section"];
items.push(section === undefined || typeof section !== "string" ? {} : { section });
@@ -549,10 +1100,34 @@ function parseConfigurationItems(params) {
return items;
}
function parseDiagnosticsParams(params) {
- if (!isRecord(params) || typeof params["uri"] !== "string")
+ if (!isRecord2(params) || typeof params["uri"] !== "string")
return null;
const diagnostics = Array.isArray(params["diagnostics"]) ? params["diagnostics"].filter(isDiagnostic) : [];
- return { uri: params["uri"], diagnostics };
+ const version = typeof params["version"] === "number" ? params["version"] : undefined;
+ return { uri: params["uri"], diagnostics, ...version === undefined ? {} : { version } };
+}
+function createLspSpawnEnv(_root, input) {
+ return { ...input };
+}
+function isDiagnostic(value) {
+ return isRecord2(value) && isRange(value["range"]) && typeof value["message"] === "string";
+}
+function isRange(value) {
+ return isRecord2(value) && isPosition(value["start"]) && isPosition(value["end"]);
+}
+function isPosition(value) {
+ return isRecord2(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+}
+
+class LspClientNotStartedError extends Error {
+ serverId;
+ root;
+ name = "LspClientNotStartedError";
+ constructor(serverId, root) {
+ super("LSP client not started");
+ this.serverId = serverId;
+ this.root = root;
+ }
}
class LspClientTransport {
@@ -565,9 +1140,11 @@ class LspClientTransport {
diagnosticsStore = new Map;
requestTimeoutMs;
initializeTimeoutMs;
- constructor(root, server, timeouts = {}) {
+ workspaceApplyEditHandler = null;
+ diagnosticPullSupported = false;
+ constructor(root, server2, timeouts = {}) {
this.root = root;
- this.server = server;
+ this.server = server2;
this.requestTimeoutMs = timeouts.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
this.initializeTimeoutMs = timeouts.initializeTimeoutMs ?? INIT_TIMEOUT_MS;
}
@@ -577,6 +1154,21 @@ class LspClientTransport {
command() {
return [...this.server.command];
}
+ setWorkspaceApplyEditHandler(handler) {
+ this.workspaceApplyEditHandler = handler;
+ }
+ hasWorkspaceApplyEditHandler() {
+ return this.workspaceApplyEditHandler !== null;
+ }
+ setDiagnosticPullSupported(supported) {
+ this.diagnosticPullSupported = supported;
+ }
+ isDiagnosticPullSupported() {
+ return this.diagnosticPullSupported;
+ }
+ handlePublishDiagnostics(params) {
+ this.diagnosticsStore.set(params.uri, [...params.diagnostics]);
+ }
async start() {
const env = createLspSpawnEnv(this.root, {
...process.env,
@@ -587,7 +1179,6 @@ class LspClientTransport {
env
});
this.startStderrReading();
- await new Promise((resolve6) => setTimeout(resolve6, 100));
if (this.proc.exitCode !== null) {
const stderr = this.stderrBuffer.join(`
`);
@@ -597,7 +1188,7 @@ class LspClientTransport {
this.connection.onNotification("textDocument/publishDiagnostics", (params) => {
const diagnosticsParams = parseDiagnosticsParams(params);
if (diagnosticsParams?.uri) {
- this.diagnosticsStore.set(diagnosticsParams.uri, diagnosticsParams.diagnostics);
+ this.handlePublishDiagnostics(diagnosticsParams);
}
});
this.connection.onRequest("workspace/configuration", (params) => {
@@ -610,6 +1201,9 @@ class LspClientTransport {
});
this.connection.onRequest("client/registerCapability", () => null);
this.connection.onRequest("window/workDoneProgress/create", () => null);
+ if (this.workspaceApplyEditHandler) {
+ this.connection.onRequest("workspace/applyEdit", this.workspaceApplyEditHandler);
+ }
this.connection.onClose(() => {
this.processExited = true;
});
@@ -638,30 +1232,25 @@ class LspClientTransport {
}
async sendRequest(method, ...args) {
if (!this.connection)
- throw new Error("LSP client not started");
+ throw new LspClientNotStartedError(this.server.id, this.root);
if (this.processExited || this.proc && this.proc.exitCode !== null) {
const stderrTail = this.stderrBuffer.slice(-10).join(`
`);
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, stderrTail || undefined);
}
- const timeoutMs = args[1]?.timeoutMs ?? this.requestTimeoutMs;
- let timeoutHandle = null;
- const timeoutPromise = new Promise((_, reject) => {
- timeoutHandle = setTimeout(() => {
- const stderrTail = this.stderrBuffer.slice(-5).join(`
+ const options = args[1];
+ const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
+ const timeoutController = new AbortController;
+ const timeoutHandle = setTimeout(() => {
+ const stderrTail = this.stderrBuffer.slice(-5).join(`
`);
- reject(new LspRequestTimeoutError(method, stderrTail || undefined));
- }, timeoutMs);
- });
+ timeoutController.abort(new LspRequestTimeoutError(method, stderrTail || undefined));
+ }, timeoutMs);
+ const combinedSignal = combineAbortSignals(options?.signal, timeoutController.signal);
try {
- const requestPromise = args.length === 0 ? this.connection.sendRequest(method) : this.connection.sendRequest(method, args[0]);
- const result = await Promise.race([requestPromise, timeoutPromise]);
- if (timeoutHandle !== null)
- clearTimeout(timeoutHandle);
+ const result = args.length === 0 ? await this.connection.sendRequest(method, undefined, { signal: combinedSignal.signal }) : await this.connection.sendRequest(method, args[0], { signal: combinedSignal.signal });
return result;
} catch (error) {
- if (timeoutHandle !== null)
- clearTimeout(timeoutHandle);
if (this.processExited || this.proc && this.proc.exitCode !== null) {
throw new LspProcessExitedError(this.server.id, this.root, this.proc?.exitCode ?? null, this.stderrBuffer.slice(-10).join(`
`) || undefined);
@@ -670,6 +1259,9 @@ class LspClientTransport {
throw new LspConnectionClosedError(this.server.id, this.root, error.message);
}
throw error;
+ } finally {
+ clearTimeout(timeoutHandle);
+ combinedSignal.dispose();
}
}
async sendNotification(method, ...args) {
@@ -698,17 +1290,17 @@ class LspClientTransport {
try {
await this.sendRequest("shutdown");
} catch (error) {
- reportBestEffortCleanupError("shutdown request", error);
+ reportBestEffortCleanupError("shutdown request", error instanceof Error ? error : String(error));
}
try {
await this.sendNotification("exit");
} catch (error) {
- reportBestEffortCleanupError("exit notification", error);
+ reportBestEffortCleanupError("exit notification", error instanceof Error ? error : String(error));
}
try {
this.connection.dispose();
} catch (error) {
- reportBestEffortCleanupError("connection dispose", error);
+ reportBestEffortCleanupError("connection dispose", error instanceof Error ? error : String(error));
}
this.connection = null;
}
@@ -719,8 +1311,8 @@ class LspClientTransport {
try {
proc.kill();
let timeoutId;
- const timeoutPromise = new Promise((resolve6) => {
- timeoutId = setTimeout(resolve6, STOP_HARD_KILL_TIMEOUT_MS);
+ const timeoutPromise = new Promise((resolve22) => {
+ timeoutId = setTimeout(resolve22, STOP_HARD_KILL_TIMEOUT_MS);
});
await Promise.race([
proc.exited.then(() => {
@@ -736,14 +1328,14 @@ class LspClientTransport {
proc.kill("SIGKILL");
await Promise.race([
proc.exited,
- new Promise((resolve6) => setTimeout(resolve6, STOP_SIGKILL_GRACE_MS))
+ new Promise((resolve22) => setTimeout(resolve22, STOP_SIGKILL_GRACE_MS))
]);
} catch (error) {
- reportBestEffortCleanupError("hard process kill", error);
+ reportBestEffortCleanupError("hard process kill", error instanceof Error ? error : String(error));
}
}
} catch (error) {
- reportBestEffortCleanupError("process stop", error);
+ reportBestEffortCleanupError("process stop", error instanceof Error ? error : String(error));
}
}
this.processExited = true;
@@ -753,24 +1345,43 @@ class LspClientTransport {
return this.diagnosticsStore.get(uri) ?? [];
}
}
-function createLspSpawnEnv(_root, input) {
- return { ...input };
-}
-function isDiagnostic(value) {
- return isRecord(value) && isRange(value["range"]) && typeof value["message"] === "string";
-}
-function isRange(value) {
- return isRecord(value) && isPosition(value["start"]) && isPosition(value["end"]);
+function combineAbortSignals(primary, secondary) {
+ const controller = new AbortController;
+ const abortFrom = (signal) => {
+ if (!controller.signal.aborted)
+ controller.abort(signal.reason);
+ };
+ const onPrimaryAbort = () => {
+ if (primary)
+ abortFrom(primary);
+ };
+ const onSecondaryAbort = () => abortFrom(secondary);
+ if (primary?.aborted)
+ abortFrom(primary);
+ else
+ primary?.addEventListener("abort", onPrimaryAbort, { once: true });
+ if (secondary.aborted)
+ abortFrom(secondary);
+ else
+ secondary.addEventListener("abort", onSecondaryAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => {
+ primary?.removeEventListener("abort", onPrimaryAbort);
+ secondary.removeEventListener("abort", onSecondaryAbort);
+ }
+ };
}
-function isPosition(value) {
- return isRecord(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+function supportsDiagnosticPull(capabilities) {
+ if (capabilities === undefined)
+ return false;
+ return Object.hasOwn(capabilities, "diagnosticProvider");
}
-var INITIALIZE_SETTLE_MS = 300;
class LspClientConnection extends LspClientTransport {
async initialize() {
const rootUri = pathToFileURL(this.root).href;
- await this.sendRequest("initialize", {
+ const result = await this.sendRequest("initialize", {
processId: process.pid,
rootUri,
rootPath: this.root,
@@ -784,8 +1395,7 @@ class LspClientConnection extends LspClientTransport {
publishDiagnostics: {},
rename: {
prepareSupport: true,
- prepareSupportDefaultBehavior: 1,
- honorsChangeAnnotations: true
+ prepareSupportDefaultBehavior: 1
},
codeAction: {
codeActionLiteralSupport: {
@@ -814,28 +1424,22 @@ class LspClientConnection extends LspClientTransport {
symbol: {},
workspaceFolders: true,
configuration: true,
- applyEdit: true,
+ ...this.hasWorkspaceApplyEditHandler() ? { applyEdit: true } : {},
workspaceEdit: {
- documentChanges: true
+ documentChanges: true,
+ resourceOperations: ["create", "rename", "delete"]
}
}
},
initializationOptions: this.server.initialization
}, { timeoutMs: this.initializeTimeoutMs });
+ this.setDiagnosticPullSupported(supportsDiagnosticPull(result?.capabilities));
await this.sendNotification("initialized");
await this.sendNotification("workspace/didChangeConfiguration", {
settings: { json: { validate: { enable: true } } }
});
- await new Promise((r) => setTimeout(r, INITIALIZE_SETTLE_MS));
}
}
-var BASENAME_EXTENSIONS = {
- Dockerfile: ".dockerfile",
- Containerfile: ".dockerfile"
-};
-function effectiveExtension(filePath) {
- return BASENAME_EXTENSIONS[basename(filePath)] ?? extname(filePath);
-}
var SYMBOL_KIND_MAP = {
1: "File",
2: "Module",
@@ -1006,81 +1610,1384 @@ var EXT_TO_LANG = {
function getLanguageId(ext) {
return EXT_TO_LANG[ext] ?? "plaintext";
}
-var POST_OPEN_DELAY_MS = 1000;
-var POST_DIAGNOSTICS_WAIT_MS = 500;
+var WATCHED_FILE_BATCH_SIZE = 128;
+var DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
+function canonicalPath(filePath) {
+ const absolute = resolve2(filePath);
+ try {
+ return realpathSync2(absolute);
+ } catch {
+ return absolute;
+ }
+}
+function isSameOrDescendant(candidate, parent) {
+ const suffix = relative2(parent, candidate);
+ return suffix === "" || !suffix.startsWith("..") && suffix !== "..";
+}
+function movedPath(candidate, oldPath, newPath) {
+ const suffix = relative2(oldPath, candidate);
+ return suffix === "" ? newPath : resolve2(newPath, suffix);
+}
-class LspClient extends LspClientConnection {
- openedFiles = new Set;
- documentVersions = new Map;
- lastSyncedText = new Map;
- diagnosticPullErrors = [];
- getDiagnosticPullErrors() {
- return this.diagnosticPullErrors;
+class WorkspaceDocumentState {
+ sendNotification;
+ clearDiagnostics;
+ openDocuments = new Map;
+ openByUri = new Map;
+ openPromises = new Map;
+ now;
+ versionlessPublishQuiescenceMs;
+ constructor(sendNotification, clearDiagnostics, options = {}) {
+ this.sendNotification = sendNotification;
+ this.clearDiagnostics = clearDiagnostics;
+ this.now = options.now ?? (() => Date.now());
+ this.versionlessPublishQuiescenceMs = options.versionlessPublishQuiescenceMs ?? DEFAULT_VERSIONLESS_PUBLISH_QUIESCENCE_MS;
}
async openFile(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- const uri = pathToFileURL2(absPath).href;
- const text = readFileSync(absPath, "utf-8");
- if (!this.openedFiles.has(absPath)) {
- const ext = effectiveExtension(absPath);
- const languageId = getLanguageId(ext);
- const version = 1;
- await this.sendNotification("textDocument/didOpen", {
- textDocument: {
- uri,
- languageId,
- version,
- text
+ const path2 = canonicalPath(filePath);
+ const existingOpen = this.openPromises.get(path2);
+ if (existingOpen) {
+ await existingOpen;
+ return this.openFile(path2);
+ }
+ const text = readFileSync2(path2, "utf-8");
+ const existing = this.openDocuments.get(path2);
+ if (!existing)
+ return this.openDocumentSingleFlight(path2, text);
+ if (existing.text === text)
+ return;
+ await this.changeDocument(existing, text);
+ }
+ getVersion(filePath) {
+ return this.openDocuments.get(canonicalPath(filePath))?.version;
+ }
+ getStoredDiagnostics(uri) {
+ const state = this.openByUri.get(uri);
+ if (!state)
+ return [];
+ return state.lastPublish?.diagnostics ?? state.pullCache?.diagnostics ?? [];
+ }
+ captureDiagnosticSnapshot(filePath) {
+ const state = this.openDocuments.get(canonicalPath(filePath));
+ if (!state)
+ return null;
+ return {
+ path: state.path,
+ uri: state.uri,
+ version: state.version,
+ documentGeneration: state.generation,
+ publishGeneration: state.publishGeneration
+ };
+ }
+ isCurrentSnapshot(snapshot) {
+ const state = this.openDocuments.get(snapshot.path);
+ return state !== undefined && state.uri === snapshot.uri && state.version === snapshot.version && state.generation === snapshot.documentGeneration;
+ }
+ getPullCache(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.pullCache || state.pullCache.documentVersion !== snapshot.version)
+ return null;
+ return state.pullCache;
+ }
+ recordPullDiagnostics(snapshot, report) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state)
+ return;
+ state.pullCache = {
+ documentVersion: snapshot.version,
+ diagnostics: [...report.diagnostics],
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ };
+ }
+ recordPublishedDiagnostics(params) {
+ const state = this.openByUri.get(params.uri);
+ if (!state)
+ return;
+ state.publishGeneration += 1;
+ state.lastPublish = {
+ diagnostics: [...params.diagnostics],
+ publishGeneration: state.publishGeneration,
+ documentGenerationAtArrival: state.generation,
+ arrivedAt: this.now(),
+ ...params.version === undefined ? {} : { version: params.version }
+ };
+ this.notifyWaiters(state);
+ }
+ resolvePushDiagnostics(snapshot) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state?.lastPublish)
+ return { status: "missing" };
+ const publish = state.lastPublish;
+ if (publish.version !== undefined) {
+ return publish.version === snapshot.version ? { status: "ready", diagnostics: publish.diagnostics } : { status: "missing" };
+ }
+ if (publish.documentGenerationAtArrival < snapshot.documentGeneration)
+ return { status: "missing" };
+ const readyAt = publish.arrivedAt + this.versionlessPublishQuiescenceMs;
+ const waitMs = Math.max(0, readyAt - this.now());
+ return waitMs === 0 ? { status: "ready", diagnostics: publish.diagnostics } : { status: "wait", waitMs };
+ }
+ waitForDiagnosticsActivity(snapshot, timeoutMs) {
+ const state = this.openByUri.get(snapshot.uri);
+ if (!state || timeoutMs <= 0)
+ return Promise.resolve();
+ return new Promise((resolveActivity) => {
+ let settled = false;
+ const finish = () => {
+ if (settled)
+ return;
+ settled = true;
+ clearTimeout(timer);
+ state.waiters.delete(finish);
+ resolveActivity();
+ };
+ const timer = setTimeout(finish, timeoutMs);
+ if (typeof timer.unref === "function")
+ timer.unref();
+ state.waiters.add(finish);
+ });
+ }
+ validateVersions(operations) {
+ const versions = new Map([...this.openDocuments].map(([path2, state]) => [path2, state.version]));
+ for (const operation of operations) {
+ if (operation.kind === "text") {
+ const current = versions.get(operation.path);
+ if (operation.documentVersion !== null && current !== operation.documentVersion) {
+ const observed = current === undefined ? "closed document" : `open document version ${current}`;
+ return {
+ changeIndex: operation.changeIndex,
+ message: `document version ${operation.documentVersion} does not match ${observed} for ${operation.path}`
+ };
+ }
+ if (current !== undefined)
+ versions.set(operation.path, current + 1);
+ continue;
+ }
+ if (operation.kind === "rename") {
+ const moved = [...versions].filter(([path2]) => isSameOrDescendant(path2, operation.oldPath));
+ for (const [path2] of moved)
+ versions.delete(path2);
+ for (const [path2] of moved)
+ versions.set(movedPath(path2, operation.oldPath, operation.newPath), 1);
+ continue;
+ }
+ if (operation.kind === "delete") {
+ for (const path2 of [...versions.keys()]) {
+ if (isSameOrDescendant(path2, operation.path))
+ versions.delete(path2);
}
+ continue;
+ }
+ if (operation.kind === "create" && operation.replaced && versions.has(operation.path)) {
+ versions.set(operation.path, 1);
+ }
+ }
+ return null;
+ }
+ async synchronize(delta) {
+ const watched = [];
+ for (const mutation of delta.operations)
+ await this.synchronizeMutation(mutation, watched);
+ for (let index = 0;index < watched.length; index += WATCHED_FILE_BATCH_SIZE) {
+ await this.sendNotification("workspace/didChangeWatchedFiles", {
+ changes: watched.slice(index, index + WATCHED_FILE_BATCH_SIZE)
});
- this.openedFiles.add(absPath);
- this.documentVersions.set(uri, version);
- this.lastSyncedText.set(uri, text);
- await new Promise((r) => setTimeout(r, POST_OPEN_DELAY_MS));
+ }
+ }
+ async synchronizeMutation(mutation, watched) {
+ if (mutation.kind === "text") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state)
+ await this.changeDocument(state, mutation.afterText);
+ else
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 2 });
return;
}
- const prevText = this.lastSyncedText.get(uri);
- if (prevText === text) {
+ if (mutation.kind === "create") {
+ const state = this.openDocuments.get(mutation.path);
+ if (state) {
+ await this.closeDocument(state);
+ await this.openDocumentSingleFlight(mutation.path, readFileSync2(mutation.path, "utf-8"));
+ } else {
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: mutation.replaced ? 2 : 1 });
+ }
return;
}
- const nextVersion = (this.documentVersions.get(uri) ?? 1) + 1;
- this.documentVersions.set(uri, nextVersion);
- this.lastSyncedText.set(uri, text);
+ if (mutation.kind === "rename") {
+ const moved = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.oldPath));
+ for (const state of moved)
+ await this.closeDocument(state);
+ for (const state of moved) {
+ const path2 = movedPath(state.path, mutation.oldPath, mutation.newPath);
+ await this.openDocumentSingleFlight(path2, readFileSync2(path2, "utf-8"));
+ }
+ if (moved.length === 0) {
+ watched.push({ uri: pathToFileURL2(mutation.oldPath).href, type: 3 });
+ watched.push({ uri: pathToFileURL2(mutation.newPath).href, type: 1 });
+ }
+ return;
+ }
+ const removed = [...this.openDocuments.values()].filter((state) => isSameOrDescendant(state.path, mutation.path));
+ for (const state of removed)
+ await this.closeDocument(state);
+ if (removed.length === 0)
+ watched.push({ uri: pathToFileURL2(mutation.path).href, type: 3 });
+ }
+ async openDocumentSingleFlight(path2, text) {
+ const existing = this.openPromises.get(path2);
+ if (existing)
+ return existing;
+ const open = (async () => {
+ const state = {
+ path: path2,
+ uri: pathToFileURL2(path2).href,
+ languageId: getLanguageId(effectiveExtension(path2)),
+ text,
+ version: 1,
+ generation: 1,
+ publishGeneration: 0,
+ waiters: new Set
+ };
+ this.openDocuments.set(path2, state);
+ this.openByUri.set(state.uri, state);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didOpen", {
+ textDocument: { uri: state.uri, languageId: state.languageId, version: state.version, text }
+ });
+ })().finally(() => {
+ this.openPromises.delete(path2);
+ });
+ this.openPromises.set(path2, open);
+ return open;
+ }
+ async changeDocument(state, text) {
+ state.text = text;
+ state.version += 1;
+ state.generation += 1;
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
await this.sendNotification("textDocument/didChange", {
- textDocument: { uri, version: nextVersion },
+ textDocument: { uri: state.uri, version: state.version },
contentChanges: [{ text }]
});
- await this.sendNotification("textDocument/didSave", {
- textDocument: { uri },
- text
+ await this.sendNotification("textDocument/didSave", { textDocument: { uri: state.uri }, text });
+ }
+ async closeDocument(state) {
+ this.openDocuments.delete(state.path);
+ this.openByUri.delete(state.uri);
+ this.clearDiagnostics(state.uri);
+ this.notifyWaiters(state);
+ await this.sendNotification("textDocument/didClose", { textDocument: { uri: state.uri } });
+ }
+ notifyWaiters(state) {
+ for (const waiter of [...state.waiters])
+ waiter();
+ }
+}
+var CONCURRENT_FAILURE_REASON_BY_PHASE = {
+ applying: "workspace/applyEdit is already in progress for this workspace mutation",
+ settled: "workspace/applyEdit was already handled for this workspace mutation"
+};
+function workspaceApplyEditConcurrentFailureReason(phase) {
+ return CONCURRENT_FAILURE_REASON_BY_PHASE[phase];
+}
+
+class WorkspaceEditPathError extends Error {
+ path;
+ detail;
+ name = "WorkspaceEditPathError";
+ constructor(path2, detail) {
+ super(`${detail}: ${path2}`);
+ this.path = path2;
+ this.detail = detail;
+ }
+}
+function isPathInsideWorkspace(filePath, workspaceRoot) {
+ const relativePath = relative3(workspaceRoot, filePath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute3(relativePath);
+}
+function canonicalizeMissingPath(filePath) {
+ let ancestor = filePath;
+ while (!existsSync3(ancestor)) {
+ const parent = dirname4(ancestor);
+ if (parent === ancestor)
+ throw new WorkspaceEditPathError(filePath, "no existing ancestor");
+ ancestor = parent;
+ }
+ return resolve3(realpathSync3(ancestor), relative3(ancestor, filePath));
+}
+function canonicalWorkspaceRoot(workspaceRoot) {
+ try {
+ const canonical = realpathSync3(resolve3(workspaceRoot));
+ if (!lstatSync2(canonical).isDirectory()) {
+ return { success: false, error: `workspace root is not a directory: ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath: resolve3(workspaceRoot),
+ followedSymbolicLink: existsSync3(resolve3(workspaceRoot)) && lstatSync2(resolve3(workspaceRoot)).isSymbolicLink()
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `workspace root ${workspaceRoot}: ${detail}` };
+ }
+}
+function uriToCanonicalWorkspacePath(uri, workspaceRoot) {
+ let requestedPath;
+ try {
+ const parsed = new URL(uri);
+ if (parsed.protocol !== "file:" || parsed.search !== "" || parsed.hash !== "") {
+ return { success: false, error: `non-file URI ${uri}` };
+ }
+ requestedPath = resolve3(fileURLToPath2(parsed));
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `non-file URI ${uri}: ${detail}` };
+ }
+ try {
+ const canonical = existsSync3(requestedPath) ? realpathSync3(requestedPath) : canonicalizeMissingPath(requestedPath);
+ if (!isPathInsideWorkspace(canonical, workspaceRoot)) {
+ return { success: false, error: `${requestedPath}: outside workspace ${workspaceRoot}` };
+ }
+ return {
+ success: true,
+ path: canonical,
+ requestedPath,
+ followedSymbolicLink: existsSync3(requestedPath) && lstatSync2(requestedPath).isSymbolicLink()
+ };
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return { success: false, error: `${requestedPath}: ${detail}` };
+ }
+}
+function snapshotPath(path2, includeChildren) {
+ if (!existsSync3(path2))
+ return { kind: "missing" };
+ const stats = lstatSync2(path2);
+ if (stats.isFile())
+ return { kind: "file", content: readFileSync3(path2, "utf-8") };
+ if (stats.isDirectory()) {
+ return includeChildren ? { kind: "directory", children: readdirSync(path2).sort() } : { kind: "directory" };
+ }
+ throw new WorkspaceEditPathError(path2, "unsupported filesystem entry");
+}
+var DEFAULT_IO = {
+ writeFile(path2, content) {
+ writeFileSync(path2, content, "utf-8");
+ },
+ rename(oldPath, newPath) {
+ renameSync(oldPath, newPath);
+ },
+ remove(path2, recursive) {
+ rmSync(path2, { recursive, force: false });
+ }
+};
+function snapshotsEqual(expected, actual) {
+ if (expected.kind !== actual.kind)
+ return false;
+ if (expected.kind === "file" && actual.kind === "file")
+ return expected.content === actual.content;
+ if (expected.kind === "directory" && actual.kind === "directory" && expected.children !== undefined) {
+ return JSON.stringify(expected.children) === JSON.stringify(actual.children);
+ }
+ return true;
+}
+function liveSnapshot(path2, expected) {
+ return snapshotPath(path2, expected.kind === "directory" && expected.children !== undefined);
+}
+function firstOperationIndex(plan) {
+ return plan.operations[0]?.changeIndex ?? 0;
+}
+function failedCommit(plan, failure) {
+ const { message, changeIndex, mutations = [], filesModified = [], totalEdits = 0, lateAbort = false } = failure;
+ return {
+ result: {
+ success: false,
+ filesModified,
+ totalEdits,
+ errors: [`change ${changeIndex}: ${message}`],
+ failedChange: changeIndex,
+ ...lateAbort ? { lateAbort: true } : {}
+ },
+ delta: mutationDelta(mutations),
+ fingerprint: plan.fingerprint
+ };
+}
+function verifySnapshots(plan) {
+ for (const [path2, expected] of plan.snapshots) {
+ let actual;
+ try {
+ actual = liveSnapshot(path2, expected);
+ } catch (error) {
+ const changeIndex = plan.firstChangeByPath.get(path2) ?? firstOperationIndex(plan);
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, { message: `cannot verify snapshot for ${path2}: ${detail}`, changeIndex });
+ }
+ if (!snapshotsEqual(expected, actual)) {
+ const changeIndex = plan.firstChangeByPath.get(path2) ?? firstOperationIndex(plan);
+ return failedCommit(plan, { message: `workspace state changed before commit: ${path2}`, changeIndex });
+ }
+ }
+ return null;
+}
+function addModifiedPath(paths, path2) {
+ if (!paths.includes(path2))
+ paths.push(path2);
+}
+function reportedPath(plan, path2) {
+ return plan.reportedPathByCanonical.get(path2) ?? path2;
+}
+function changedPathsForMutation(mutation) {
+ return mutation.kind === "rename" ? [mutation.oldPath, mutation.newPath] : [mutation.path];
+}
+function mutationDelta(operations) {
+ const changedPaths = new Set;
+ for (const operation of operations) {
+ for (const path2 of changedPathsForMutation(operation))
+ changedPaths.add(path2);
+ }
+ return { operations, changedPaths: [...changedPaths].sort() };
+}
+function resolveIo(overrides) {
+ return {
+ writeFile: overrides?.writeFile ?? DEFAULT_IO.writeFile,
+ rename: overrides?.rename ?? DEFAULT_IO.rename,
+ remove: overrides?.remove ?? DEFAULT_IO.remove
+ };
+}
+function commitOperation(context, operation) {
+ const { plan, io, accumulator } = context;
+ if (operation.kind === "noop")
+ return;
+ if (operation.kind === "text") {
+ io.writeFile(operation.path, operation.afterText);
+ accumulator.mutations.push({
+ kind: "text",
+ path: operation.path,
+ beforeText: operation.beforeText,
+ afterText: operation.afterText
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ accumulator.totalEdits += operation.editCount;
+ return;
+ }
+ if (operation.kind === "create") {
+ io.writeFile(operation.path, "");
+ accumulator.mutations.push({ kind: "create", path: operation.path, replaced: operation.replaced });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+ return;
+ }
+ if (operation.kind === "rename") {
+ if (operation.replaceDestination) {
+ const targetKind = existsSync4(operation.newPath) && lstatSync3(operation.newPath).isDirectory() ? "directory" : "file";
+ io.remove(operation.newPath, targetKind === "directory");
+ accumulator.mutations.push({ kind: "delete", path: operation.newPath, targetKind });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ }
+ io.rename(operation.oldPath, operation.newPath);
+ accumulator.mutations.push({
+ kind: "rename",
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: operation.sourceKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.newPath));
+ return;
+ }
+ io.remove(operation.path, operation.recursive);
+ accumulator.mutations.push({
+ kind: "delete",
+ path: operation.path,
+ targetKind: operation.targetKind
+ });
+ addModifiedPath(accumulator.filesModified, reportedPath(plan, operation.path));
+}
+function commitWorkspaceEditPlan(plan, options = {}) {
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const stale = verifySnapshots(plan);
+ if (stale)
+ return stale;
+ if (options.signal?.aborted) {
+ return failedCommit(plan, { message: "cancelled before commit", changeIndex: firstOperationIndex(plan) });
+ }
+ const io = resolveIo(options.io);
+ const accumulator = { mutations: [], filesModified: [], totalEdits: 0 };
+ const context = { plan, io, accumulator };
+ let lateAbort = false;
+ for (const operation of plan.operations) {
+ try {
+ commitOperation(context, operation);
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ return failedCommit(plan, {
+ message: `I/O failure during ${operation.kind}: ${detail}`,
+ changeIndex: operation.changeIndex,
+ mutations: accumulator.mutations,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ lateAbort: lateAbort || options.signal?.aborted === true
+ });
+ }
+ if (options.signal?.aborted)
+ lateAbort = true;
+ }
+ const result = {
+ success: true,
+ filesModified: accumulator.filesModified,
+ totalEdits: accumulator.totalEdits,
+ errors: [],
+ ...lateAbort ? { lateAbort: true } : {}
+ };
+ return { result, delta: mutationDelta(accumulator.mutations), fingerprint: plan.fingerprint };
+}
+function canonicalFingerprint(operations) {
+ const canonical = operations.map((operation) => {
+ switch (operation.kind) {
+ case "text":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ edits: operation.edits,
+ version: operation.version
+ };
+ case "rename":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "create":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ overwrite: operation.overwrite,
+ ignoreIfExists: operation.ignoreIfExists
+ };
+ case "delete":
+ return {
+ kind: operation.kind,
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ recursive: operation.recursive,
+ ignoreIfNotExists: operation.ignoreIfNotExists
+ };
+ }
+ });
+ return createHash2("sha256").update(JSON.stringify(canonical)).digest("hex");
+}
+
+class WorkspaceEditValidationError extends Error {
+ changeIndex;
+ detail;
+ name = "WorkspaceEditValidationError";
+ constructor(changeIndex, detail) {
+ super(`change ${changeIndex}: ${detail}`);
+ this.changeIndex = changeIndex;
+ this.detail = detail;
+ }
+}
+function isRecord3(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function parsePosition(value) {
+ if (!isRecord3(value) || typeof value["line"] !== "number" || typeof value["character"] !== "number") {
+ return null;
+ }
+ return { line: value["line"], character: value["character"] };
+}
+function parseRange(value) {
+ if (!isRecord3(value))
+ return null;
+ const start = parsePosition(value["start"]);
+ const end = parsePosition(value["end"]);
+ return start && end ? { start, end } : null;
+}
+function parseTextEdits(value, changeIndex) {
+ if (!Array.isArray(value)) {
+ throw new WorkspaceEditValidationError(changeIndex, "text edits must be an array");
+ }
+ const edits = [];
+ for (const candidate of value) {
+ if (!isRecord3(candidate) || typeof candidate["newText"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "text edit requires range and newText");
+ }
+ if ("annotationId" in candidate) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated text edits are unsupported");
+ }
+ const range = parseRange(candidate["range"]);
+ if (!range)
+ throw new WorkspaceEditValidationError(changeIndex, "text edit range is malformed");
+ edits.push({ range, newText: candidate["newText"] });
+ }
+ return edits;
+}
+function parseBooleanOption(options, key, changeIndex) {
+ const value = options[key];
+ if (value === undefined)
+ return false;
+ if (typeof value !== "boolean") {
+ throw new WorkspaceEditValidationError(changeIndex, `${key} must be boolean`);
+ }
+ return value;
+}
+function parseOptions(value, allowed, changeIndex) {
+ if (value === undefined)
+ return {};
+ if (!isRecord3(value))
+ throw new WorkspaceEditValidationError(changeIndex, "resource options must be an object");
+ for (const key of Object.keys(value)) {
+ if (!allowed.includes(key))
+ throw new WorkspaceEditValidationError(changeIndex, `unsupported resource option ${key}`);
+ }
+ const parsed = {};
+ for (const key of allowed)
+ parsed[key] = parseBooleanOption(value, key, changeIndex);
+ return parsed;
+}
+function parseResourceChange(input) {
+ const kind = input.change["kind"];
+ if (kind === "create" || kind === "delete") {
+ parseSinglePathResource(input, kind);
+ return;
+ }
+ if (kind !== "rename") {
+ throw new WorkspaceEditValidationError(input.changeIndex, `unsupported resource operation ${String(kind)}`);
+ }
+ parseRename(input);
+}
+function parseSinglePathResource(input, kind) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["uri"] !== "string")
+ throw new WorkspaceEditValidationError(changeIndex, `${kind}.uri is required`);
+ const resolvedPath = uriToCanonicalWorkspacePath(change["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ if (kind === "create") {
+ const options2 = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ overwrite: options2["overwrite"] ?? false,
+ ignoreIfExists: options2["ignoreIfExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["recursive", "ignoreIfNotExists"], changeIndex);
+ target.operations.push({
+ kind,
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ recursive: options["recursive"] ?? false,
+ ignoreIfNotExists: options["ignoreIfNotExists"] ?? false,
+ followedSymbolicLink: resolvedPath.followedSymbolicLink
+ });
+}
+function parseRename(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (typeof change["oldUri"] !== "string" || typeof change["newUri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "rename requires oldUri and newUri");
+ }
+ const oldPath = uriToCanonicalWorkspacePath(change["oldUri"], workspaceRoot);
+ const newPath = uriToCanonicalWorkspacePath(change["newUri"], workspaceRoot);
+ if (!oldPath.success || !newPath.success) {
+ target.failures.push({
+ changeIndex,
+ message: !oldPath.success ? oldPath.error : !newPath.success ? newPath.error : "invalid rename path"
+ });
+ return;
+ }
+ const options = parseOptions(change["options"], ["overwrite", "ignoreIfExists"], changeIndex);
+ target.operations.push({
+ kind: "rename",
+ changeIndex,
+ oldPath: oldPath.path,
+ newPath: newPath.path,
+ reportedOldPath: oldPath.requestedPath,
+ reportedNewPath: newPath.requestedPath,
+ overwrite: options["overwrite"] ?? false,
+ ignoreIfExists: options["ignoreIfExists"] ?? false,
+ followedSymbolicLink: oldPath.followedSymbolicLink || newPath.followedSymbolicLink
+ });
+}
+function failureResult(failures) {
+ const sorted = [...failures].sort((left, right) => left.changeIndex - right.changeIndex);
+ const first = sorted[0];
+ return {
+ success: false,
+ filesModified: [],
+ totalEdits: 0,
+ errors: sorted.map((failure) => `change ${failure.changeIndex}: ${failure.message}`),
+ ...first ? { failedChange: first.changeIndex } : {}
+ };
+}
+function parseWorkspaceEdit(edit, workspaceRoot) {
+ if (!isRecord3(edit))
+ return { operations: [], failures: [{ changeIndex: 0, message: "No edit provided" }] };
+ if (edit["changeAnnotations"] !== undefined) {
+ return { operations: [], failures: [{ changeIndex: 0, message: "change annotations are unsupported" }] };
+ }
+ const hasChanges = edit["changes"] !== undefined;
+ const hasDocumentChanges = edit["documentChanges"] !== undefined;
+ if (hasChanges && hasDocumentChanges) {
+ return {
+ operations: [],
+ failures: [{ changeIndex: 0, message: "changes and documentChanges cannot be combined" }]
+ };
+ }
+ const target = { operations: [], failures: [] };
+ if (hasChanges)
+ return parseChanges(edit["changes"], workspaceRoot, target);
+ return parseDocumentChanges(edit["documentChanges"], workspaceRoot, target);
+}
+function parseChanges(value, workspaceRoot, target) {
+ if (!isRecord3(value))
+ return { ...target, failures: [{ changeIndex: 0, message: "changes must be an object" }] };
+ const entries = Object.entries(value).sort(([left], [right]) => left.localeCompare(right));
+ for (const [changeIndex, [uri, rawEdits]] of entries.entries()) {
+ const resolvedPath = uriToCanonicalWorkspacePath(uri, workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ continue;
+ }
+ try {
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(rawEdits, changeIndex),
+ version: null
+ });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChanges(value, workspaceRoot, target) {
+ if (value === undefined)
+ return target;
+ if (!Array.isArray(value)) {
+ return { ...target, failures: [{ changeIndex: 0, message: "documentChanges must be an array" }] };
+ }
+ for (const [changeIndex, change] of value.entries()) {
+ try {
+ parseDocumentChange({ change, changeIndex, workspaceRoot, target });
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ target.failures.push({ changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return target;
+}
+function parseDocumentChange(input) {
+ const { change, changeIndex, workspaceRoot, target } = input;
+ if (!isRecord3(change))
+ throw new WorkspaceEditValidationError(changeIndex, "document change must be an object");
+ if ("annotationId" in change) {
+ throw new WorkspaceEditValidationError(changeIndex, "annotated resource operations are unsupported");
+ }
+ if (typeof change["kind"] === "string") {
+ parseResourceChange({ change, changeIndex, workspaceRoot, target });
+ return;
+ }
+ const identifier = change["textDocument"];
+ if (!isRecord3(identifier) || typeof identifier["uri"] !== "string") {
+ throw new WorkspaceEditValidationError(changeIndex, "textDocument.uri is required");
+ }
+ const version = identifier["version"];
+ if (version !== null && (!Number.isInteger(version) || typeof version !== "number" || version < 0)) {
+ throw new WorkspaceEditValidationError(changeIndex, "document version must be null or a non-negative integer");
+ }
+ const resolvedPath = uriToCanonicalWorkspacePath(identifier["uri"], workspaceRoot);
+ if (!resolvedPath.success) {
+ target.failures.push({ changeIndex, message: resolvedPath.error });
+ return;
+ }
+ target.operations.push({
+ kind: "text",
+ changeIndex,
+ path: resolvedPath.path,
+ reportedPath: resolvedPath.requestedPath,
+ edits: parseTextEdits(change["edits"], changeIndex),
+ version
+ });
+}
+function comparePosition(left, right) {
+ return left.line === right.line ? left.character - right.character : left.line - right.line;
+}
+function positionsEqual(left, right) {
+ return left.line === right.line && left.character === right.character;
+}
+function rangesEqual(left, right) {
+ return positionsEqual(left.start, right.start) && positionsEqual(left.end, right.end);
+}
+function isEmptyRange(range) {
+ return positionsEqual(range.start, range.end);
+}
+function formatRange(range) {
+ return `${range.start.line + 1}:${range.start.character + 1}-${range.end.line + 1}:${range.end.character + 1}`;
+}
+function validatePosition(position, label, context) {
+ const { lines, changeIndex } = context;
+ if (!Number.isInteger(position.line) || !Number.isInteger(position.character)) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position must use integer line and character`);
+ }
+ if (position.line < 0 || position.character < 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} position cannot be negative`);
+ }
+ const line = lines[position.line];
+ if (line === undefined) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} line ${position.line} is outside the document`);
+ }
+ if (position.character > line.length) {
+ throw new WorkspaceEditValidationError(changeIndex, `${label} character ${position.character} is outside line ${position.line}`);
+ }
+}
+function validateRange(range, lines, changeIndex) {
+ const context = { lines, changeIndex };
+ validatePosition(range.start, "start", context);
+ validatePosition(range.end, "end", context);
+ if (comparePosition(range.start, range.end) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `range ${formatRange(range)} ends before it starts`);
+ }
+}
+function sortAndDeduplicate(edits) {
+ const sorted = edits.map((edit, index) => ({ edit, index })).sort((left, right) => {
+ const positionOrder = comparePosition(right.edit.range.start, left.edit.range.start);
+ return positionOrder === 0 ? right.index - left.index : positionOrder;
+ });
+ const unique = [];
+ for (const entry of sorted) {
+ const previous = unique.at(-1);
+ if (previous !== undefined && !isEmptyRange(entry.edit.range) && rangesEqual(previous.range, entry.edit.range) && previous.newText === entry.edit.newText) {
+ continue;
+ }
+ unique.push(entry.edit);
+ }
+ return unique;
+}
+function validateNoOverlap(edits, changeIndex) {
+ for (let index = 0;index < edits.length - 1; index += 1) {
+ const later = edits[index];
+ const earlier = edits[index + 1];
+ if (later === undefined || earlier === undefined)
+ continue;
+ if (comparePosition(earlier.range.end, later.range.start) > 0) {
+ throw new WorkspaceEditValidationError(changeIndex, `overlapping edits ${formatRange(earlier.range)} and ${formatRange(later.range)}`);
+ }
+ }
+}
+function applyNormalizedTextEdits(content, edits) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ const { start, end } = edit.range;
+ const startLine = lines[start.line];
+ const endLine = lines[end.line];
+ if (startLine === undefined || endLine === undefined)
+ continue;
+ const replacement = startLine.slice(0, start.character) + edit.newText + endLine.slice(end.character);
+ lines.splice(start.line, end.line - start.line + 1, ...replacement.split(`
+`));
+ }
+ return lines.join(`
+`);
+}
+function normalizeTextEdits(content, edits, changeIndex) {
+ const lines = content.split(`
+`);
+ for (const edit of edits) {
+ validateRange(edit.range, lines, changeIndex);
+ }
+ const normalized = sortAndDeduplicate(edits);
+ validateNoOverlap(normalized, changeIndex);
+ return { edits: normalized, text: applyNormalizedTextEdits(content, normalized) };
+}
+function isSameOrDescendant2(candidate, parent) {
+ const relativePath = relative4(parent, candidate);
+ return relativePath === "" || !relativePath.startsWith("..") && relativePath !== "..";
+}
+function removeVirtualSubtree(virtual, path2) {
+ for (const candidate of [...virtual.keys()]) {
+ if (isSameOrDescendant2(candidate, path2))
+ virtual.delete(candidate);
+ }
+ virtual.set(path2, { kind: "missing" });
+}
+function moveVirtualSubtree(virtual, oldPath, newPath) {
+ const moved = [...virtual.entries()].filter(([candidate]) => isSameOrDescendant2(candidate, oldPath));
+ removeVirtualSubtree(virtual, oldPath);
+ removeVirtualSubtree(virtual, newPath);
+ for (const [candidate, entry] of moved) {
+ const suffix = relative4(oldPath, candidate);
+ virtual.set(suffix === "" ? newPath : resolve4(newPath, suffix), entry);
+ }
+}
+function virtualDirectoryHasChildren(virtual, path2) {
+ for (const [candidate, entry] of virtual) {
+ if (candidate !== path2 && entry.kind !== "missing" && isSameOrDescendant2(candidate, path2))
+ return true;
+ }
+ return false;
+}
+function requireVirtualParent(virtual, path2, changeIndex) {
+ if (virtual.get(dirname5(path2))?.kind !== "directory") {
+ throw new WorkspaceEditValidationError(changeIndex, `parent directory does not exist for ${path2}`);
+ }
+}
+function simulateOperations(parsed, snapshots) {
+ const virtual = new Map(snapshots);
+ const planned = [];
+ const failures = [];
+ for (const operation of parsed) {
+ try {
+ planned.push(simulateOperation(operation, virtual));
+ } catch (error) {
+ if (error instanceof WorkspaceEditValidationError) {
+ failures.push({ changeIndex: operation.changeIndex, message: error.detail });
+ continue;
+ }
+ throw error;
+ }
+ }
+ return { operations: planned, failures };
+}
+function simulateOperation(operation, virtual) {
+ switch (operation.kind) {
+ case "text":
+ return simulateText(operation, virtual);
+ case "create":
+ return simulateCreate(operation, virtual);
+ case "rename":
+ return simulateRename(operation, virtual);
+ case "delete":
+ return simulateDelete(operation, virtual);
+ }
+}
+function rejectSymbolicLink(operation) {
+ if (operation.followedSymbolicLink) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "resource operations through symbolic links are unsupported");
+ }
+}
+function simulateText(operation, virtual) {
+ const entry = virtual.get(operation.path);
+ if (entry?.kind !== "file")
+ throw new WorkspaceEditValidationError(operation.changeIndex, `${operation.path} is not a file`);
+ const normalized = normalizeTextEdits(entry.content, operation.edits, operation.changeIndex);
+ virtual.set(operation.path, { kind: "file", content: normalized.text });
+ return {
+ kind: "text",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ beforeText: entry.content,
+ afterText: normalized.text,
+ editCount: normalized.edits.length,
+ documentVersion: operation.version
+ };
+}
+function simulateCreate(operation, virtual) {
+ rejectSymbolicLink(operation);
+ requireVirtualParent(virtual, operation.path, operation.changeIndex);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind !== "missing") {
+ if (operation.overwrite && target.kind === "file") {
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: true };
+ }
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `create target already exists: ${operation.path}`);
+ }
+ virtual.set(operation.path, { kind: "file", content: "" });
+ return { kind: "create", changeIndex: operation.changeIndex, path: operation.path, replaced: false };
+}
+function simulateRename(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const source = virtual.get(operation.oldPath) ?? { kind: "missing" };
+ if (source.kind === "missing") {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename source does not exist: ${operation.oldPath}`);
+ }
+ if (operation.oldPath === operation.newPath)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ if (isSameOrDescendant2(operation.newPath, operation.oldPath)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, "cannot rename a path into its own subtree");
+ }
+ requireVirtualParent(virtual, operation.newPath, operation.changeIndex);
+ const destination = virtual.get(operation.newPath) ?? { kind: "missing" };
+ if (destination.kind !== "missing" && !operation.overwrite) {
+ if (operation.ignoreIfExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `rename target already exists: ${operation.newPath}`);
+ }
+ moveVirtualSubtree(virtual, operation.oldPath, operation.newPath);
+ return {
+ kind: "rename",
+ changeIndex: operation.changeIndex,
+ oldPath: operation.oldPath,
+ newPath: operation.newPath,
+ sourceKind: source.kind,
+ replaceDestination: destination.kind !== "missing"
+ };
+}
+function simulateDelete(operation, virtual) {
+ rejectSymbolicLink(operation);
+ const target = virtual.get(operation.path) ?? { kind: "missing" };
+ if (target.kind === "missing") {
+ if (operation.ignoreIfNotExists)
+ return { kind: "noop", changeIndex: operation.changeIndex };
+ throw new WorkspaceEditValidationError(operation.changeIndex, `delete target does not exist: ${operation.path}`);
+ }
+ if (target.kind === "directory" && !operation.recursive && virtualDirectoryHasChildren(virtual, operation.path)) {
+ throw new WorkspaceEditValidationError(operation.changeIndex, `directory is not empty: ${operation.path}`);
+ }
+ removeVirtualSubtree(virtual, operation.path);
+ return {
+ kind: "delete",
+ changeIndex: operation.changeIndex,
+ path: operation.path,
+ targetKind: target.kind,
+ recursive: operation.recursive
+ };
+}
+
+class WorkspaceSnapshotBuilder {
+ workspaceRoot;
+ snapshots = new Map;
+ constructor(workspaceRoot) {
+ this.workspaceRoot = workspaceRoot;
+ }
+ build(operations) {
+ this.add(this.workspaceRoot, false);
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, true);
+ this.add(operation.newPath, true);
+ break;
+ case "delete":
+ this.add(operation.path, true);
+ break;
+ case "text":
+ case "create":
+ this.add(operation.path, false);
+ break;
+ }
+ }
+ return this.snapshots;
+ }
+ add(path2, includeChildren) {
+ let candidate = path2;
+ while (true) {
+ const existing = this.snapshots.get(candidate);
+ if (existing === undefined || includeChildren && existing.kind === "directory" && existing.children === undefined) {
+ this.snapshots.set(candidate, snapshotPath(candidate, includeChildren && candidate === path2));
+ }
+ if (candidate === this.workspaceRoot)
+ break;
+ candidate = dirname6(candidate);
+ }
+ if (!includeChildren || !existsSync5(path2) || !lstatSync4(path2).isDirectory())
+ return;
+ for (const child of readdirSync2(path2))
+ this.add(resolve5(path2, child), true);
+ }
+}
+function snapshotOperations(operations, workspaceRoot) {
+ return new WorkspaceSnapshotBuilder(workspaceRoot).build(operations);
+}
+
+class PlanPathIndex {
+ firstChangeByPath = new Map;
+ reportedPathByCanonical = new Map;
+ build(operations) {
+ for (const operation of operations) {
+ switch (operation.kind) {
+ case "rename":
+ this.add(operation.oldPath, operation.reportedOldPath, operation.changeIndex);
+ this.add(operation.newPath, operation.reportedNewPath, operation.changeIndex);
+ break;
+ case "text":
+ case "create":
+ case "delete":
+ this.add(operation.path, operation.reportedPath, operation.changeIndex);
+ break;
+ }
+ }
+ }
+ add(path2, reportedPath2, changeIndex) {
+ if (!this.firstChangeByPath.has(path2))
+ this.firstChangeByPath.set(path2, changeIndex);
+ if (!this.reportedPathByCanonical.has(path2))
+ this.reportedPathByCanonical.set(path2, reportedPath2);
+ }
+}
+function fingerprintWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ return { success: true, fingerprint: canonicalFingerprint(parsed.operations) };
+}
+function planWorkspaceEdit(edit, workspaceRoot) {
+ const root = canonicalWorkspaceRoot(workspaceRoot);
+ if (!root.success)
+ return { success: false, result: failureResult([{ changeIndex: 0, message: root.error }]) };
+ const parsed = parseWorkspaceEdit(edit, root.path);
+ if (parsed.failures.length > 0)
+ return { success: false, result: failureResult(parsed.failures) };
+ let snapshots;
+ try {
+ snapshots = snapshotOperations(parsed.operations, root.path);
+ } catch (error) {
+ return {
+ success: false,
+ result: failureResult([{ changeIndex: 0, message: error instanceof Error ? error.message : String(error) }])
+ };
+ }
+ const simulated = simulateOperations(parsed.operations, snapshots);
+ if (simulated.failures.length > 0)
+ return { success: false, result: failureResult(simulated.failures) };
+ const paths = new PlanPathIndex;
+ paths.build(parsed.operations);
+ const plan = {
+ workspaceRoot: root.path,
+ operations: simulated.operations,
+ snapshots,
+ firstChangeByPath: paths.firstChangeByPath,
+ reportedPathByCanonical: paths.reportedPathByCanonical,
+ fingerprint: canonicalFingerprint(parsed.operations)
+ };
+ return { success: true, plan };
+}
+function failure(message, failedChange, base) {
+ return {
+ success: false,
+ filesModified: base?.filesModified ?? [],
+ totalEdits: base?.totalEdits ?? 0,
+ errors: [message],
+ ...failedChange === undefined ? {} : { failedChange },
+ ...base?.lateAbort ? { lateAbort: true } : {}
+ };
+}
+function responseFor(result) {
+ if (result.success)
+ return { applied: true };
+ return {
+ applied: false,
+ failureReason: result.errors[0] ?? "workspace edit failed",
+ ...result.failedChange === undefined ? {} : { failedChange: result.failedChange }
+ };
+}
+function isRecord4(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+class WorkspaceMutationController {
+ workspaceRoot;
+ documents;
+ activeLease = null;
+ nextLeaseId = 1;
+ io;
+ constructor(workspaceRoot, documents) {
+ this.workspaceRoot = workspaceRoot;
+ this.documents = documents;
+ }
+ setIo(io) {
+ this.io = io;
+ }
+ acquire(signal) {
+ if (this.activeLease)
+ return { success: false, result: failure("workspace mutation is already in progress") };
+ if (signal?.aborted)
+ return { success: false, result: failure("cancelled before mutating request") };
+ const lease = {
+ id: this.nextLeaseId,
+ phase: "idle",
+ ...signal === undefined ? {} : { signal }
+ };
+ this.nextLeaseId += 1;
+ this.activeLease = lease;
+ return { success: true, lease };
+ }
+ release(lease) {
+ if (this.activeLease?.id !== lease.id)
+ return;
+ this.activeLease.phase = "sealed";
+ this.activeLease = null;
+ }
+ isBeforeCommit(lease) {
+ return this.activeLease?.id === lease.id && this.activeLease.phase === "idle";
+ }
+ async handleApplyEdit(params) {
+ const lease = this.activeLease;
+ if (!lease)
+ return { applied: false, failureReason: "workspace/applyEdit requires an active workspace mutation" };
+ if (lease.phase !== "idle") {
+ return {
+ applied: false,
+ failureReason: workspaceApplyEditConcurrentFailureReason(lease.phase === "applying" ? "applying" : "settled")
+ };
+ }
+ lease.phase = "applying";
+ lease.applyCompletion = new Promise((resolve62) => {
+ lease.resolveApply = resolve62;
+ });
+ const edit = isRecord4(params) ? params["edit"] : undefined;
+ const record2 = edit === undefined ? { fingerprint: null, result: failure("workspace/applyEdit params.edit is required", 0) } : await this.applyEdit(edit, lease);
+ lease.serverApply = record2;
+ lease.phase = "settled";
+ lease.resolveApply?.();
+ return responseFor(record2.result);
+ }
+ async reconcileRename(leaseToken, edit) {
+ const lease = this.requireActiveLease(leaseToken);
+ if (!lease)
+ return { edit, apply: failure("workspace mutation lease ended before rename reconciliation") };
+ if (lease.phase === "applying")
+ await lease.applyCompletion;
+ if (lease.serverApply)
+ return this.reconcileServerApply(lease.serverApply, edit);
+ lease.phase = "sealed";
+ if (!edit)
+ return { edit, apply: failure("No edit provided") };
+ const applied = await this.applyEdit(edit, lease);
+ return { edit, apply: applied.result };
+ }
+ reconcileServerApply(record2, edit) {
+ if (!edit)
+ return { edit, apply: record2.result };
+ const fingerprint = fingerprintWorkspaceEdit(edit, this.workspaceRoot);
+ if (fingerprint.success && record2.fingerprint !== null && fingerprint.fingerprint === record2.fingerprint) {
+ return { edit, apply: record2.result };
+ }
+ return {
+ edit,
+ apply: failure("rename result conflicts with server-applied workspace edit", 0, record2.result)
+ };
+ }
+ async applyEdit(edit, lease) {
+ const planned = planWorkspaceEdit(edit, this.workspaceRoot);
+ if (!planned.success)
+ return { fingerprint: null, result: planned.result };
+ const versionFailure = this.documents.validateVersions(planned.plan.operations);
+ if (versionFailure) {
+ return {
+ fingerprint: planned.plan.fingerprint,
+ result: failure(versionFailure.message, versionFailure.changeIndex)
+ };
+ }
+ const commit = commitWorkspaceEditPlan(planned.plan, {
+ ...lease.signal === undefined ? {} : { signal: lease.signal },
+ ...this.io === undefined ? {} : { io: this.io }
});
+ let result = commit.result;
+ if (commit.delta.operations.length > 0) {
+ try {
+ await this.documents.synchronize(commit.delta);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ result = failure(`document synchronization failed after filesystem commit: ${message}`, undefined, result);
+ }
+ }
+ if (lease.signal?.aborted && !result.lateAbort)
+ result = { ...result, lateAbort: true };
+ return { fingerprint: planned.plan.fingerprint, result };
+ }
+ requireActiveLease(lease) {
+ return this.activeLease?.id === lease.id ? this.activeLease : null;
+ }
+}
+var DIAGNOSTICS_FRESHNESS_TIMEOUT_MS = 3000;
+var VERSIONLESS_PUBLISH_QUIESCENCE_MS = 250;
+
+class LspClient extends LspClientConnection {
+ diagnosticPullErrors = [];
+ documents;
+ workspaceMutations;
+ diagnosticsFreshnessTimeoutMs;
+ constructor(root, server2, options = {}) {
+ super(root, server2, options);
+ this.diagnosticsFreshnessTimeoutMs = options.diagnosticsFreshnessTimeoutMs ?? DIAGNOSTICS_FRESHNESS_TIMEOUT_MS;
+ this.documents = new WorkspaceDocumentState((method, params) => this.sendNotification(method, params), (uri) => this.diagnosticsStore.delete(uri), {
+ versionlessPublishQuiescenceMs: options.versionlessPublishQuiescenceMs ?? VERSIONLESS_PUBLISH_QUIESCENCE_MS
+ });
+ this.workspaceMutations = new WorkspaceMutationController(root, this.documents);
+ this.setWorkspaceApplyEditHandler((params) => this.workspaceMutations.handleApplyEdit(params));
+ }
+ getDiagnosticPullErrors() {
+ return this.diagnosticPullErrors;
}
- async definition(filePath, line, character) {
- const absPath = resolve(contextCwd(), filePath);
+ async openFile(filePath) {
+ const absPath = this.resolveWorkspacePath(filePath);
+ await this.documents.openFile(absPath);
+ }
+ getOpenDocumentVersion(filePath) {
+ return this.documents.getVersion(this.resolveWorkspacePath(filePath));
+ }
+ getStoredDiagnostics(uri) {
+ return [...this.documents.getStoredDiagnostics(uri)];
+ }
+ setWorkspaceEditIo(io) {
+ this.workspaceMutations.setIo(io);
+ }
+ handlePublishDiagnostics(params) {
+ super.handlePublishDiagnostics(params);
+ this.documents.recordPublishedDiagnostics(params);
+ }
+ async definition(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/definition", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character }
- });
+ }, options);
}
- async references(filePath, line, character, includeDeclaration = true) {
- const absPath = resolve(contextCwd(), filePath);
+ async references(filePath, line, character, includeDeclaration = true, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/references", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character },
context: { includeDeclaration }
- });
+ }, options);
}
- async documentSymbols(filePath) {
- const absPath = resolve(contextCwd(), filePath);
+ async documentSymbols(filePath, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/documentSymbol", {
- textDocument: { uri: pathToFileURL2(absPath).href }
- });
+ textDocument: { uri: pathToFileURL3(absPath).href }
+ }, options);
}
- async workspaceSymbols(query) {
- return this.sendRequest("workspace/symbol", { query });
+ async workspaceSymbols(query, signal) {
+ const options = signal === undefined ? {} : { signal };
+ return this.sendRequest("workspace/symbol", { query }, options);
}
isUnsupportedDiagnosticPullError(error) {
if (!(error instanceof Error))
@@ -1090,42 +2997,173 @@ class LspClient extends LspClientConnection {
return true;
return /unsupported|not supported|method not found|unknown request/i.test(error.message);
}
- async diagnostics(filePath) {
- const absPath = resolve(contextCwd(), filePath);
- const uri = pathToFileURL2(absPath).href;
- await this.openFile(absPath);
- await new Promise((r) => setTimeout(r, POST_DIAGNOSTICS_WAIT_MS));
- try {
- const result = await this.sendRequest("textDocument/diagnostic", {
- textDocument: { uri }
- });
- if (result.items) {
- return { items: result.items };
+ freshnessTimeout(absPath) {
+ return {
+ items: [],
+ transientError: {
+ kind: "freshness_timeout",
+ message: `Timed out waiting for fresh diagnostics for ${absPath} within ${this.diagnosticsFreshnessTimeoutMs}ms.`
}
- } catch (error) {
- if (!this.isUnsupportedDiagnosticPullError(error)) {
- this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ };
+ }
+ parseDiagnosticPullReport(value) {
+ if (value.kind === "unchanged") {
+ return {
+ type: "unchanged",
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ return {
+ type: "full",
+ diagnostics: value.items ?? [],
+ ...value.resultId === undefined ? {} : { resultId: value.resultId }
+ };
+ }
+ async diagnostics(filePath, signal) {
+ signal?.throwIfAborted();
+ const absPath = this.resolveWorkspacePath(filePath);
+ const uri = pathToFileURL3(absPath).href;
+ await this.openFile(absPath);
+ const deadlineAt = Date.now() + this.diagnosticsFreshnessTimeoutMs;
+ for (;; ) {
+ signal?.throwIfAborted();
+ const snapshot = this.documents.captureDiagnosticSnapshot(absPath);
+ if (!snapshot)
+ return this.freshnessTimeout(absPath);
+ const push = this.documents.resolvePushDiagnostics(snapshot);
+ if (push.status === "ready")
+ return { items: [...push.diagnostics] };
+ let pushFallbackOnly = !this.isDiagnosticPullSupported();
+ if (!pushFallbackOnly) {
+ const cached = this.documents.getPullCache(snapshot);
+ try {
+ const remainingMs2 = deadlineAt - Date.now();
+ if (remainingMs2 <= 0)
+ return this.freshnessTimeout(absPath);
+ const result = await this.sendRequest("textDocument/diagnostic", {
+ textDocument: { uri },
+ ...cached?.resultId === undefined ? {} : { previousResultId: cached.resultId }
+ }, { timeoutMs: remainingMs2, ...signal === undefined ? {} : { signal } });
+ if (!this.documents.isCurrentSnapshot(snapshot))
+ continue;
+ const report = this.parseDiagnosticPullReport(result);
+ if (report.type === "full") {
+ this.documents.recordPullDiagnostics(snapshot, {
+ kind: "full",
+ diagnostics: report.diagnostics,
+ ...report.resultId === undefined ? {} : { resultId: report.resultId }
+ });
+ return { items: [...report.diagnostics] };
+ }
+ if (cached !== null && cached.documentVersion === snapshot.version && cached.resultId === report.resultId) {
+ return { items: [...cached.diagnostics] };
+ }
+ } catch (error) {
+ if (this.isUnsupportedDiagnosticPullError(error)) {
+ this.setDiagnosticPullSupported(false);
+ pushFallbackOnly = true;
+ } else if (error instanceof LspRequestTimeoutError) {
+ pushFallbackOnly = true;
+ } else {
+ this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ throw error;
+ }
+ }
}
+ if (!pushFallbackOnly)
+ continue;
+ const remainingMs = deadlineAt - Date.now();
+ if (remainingMs <= 0)
+ return this.freshnessTimeout(absPath);
+ const waitMs = push.status === "wait" ? Math.min(push.waitMs, remainingMs) : remainingMs;
+ await waitForDiagnosticsActivity(this.documents.waitForDiagnosticsActivity(snapshot, waitMs), signal);
}
- return { items: this.getStoredDiagnostics(uri) };
}
- async prepareRename(filePath, line, character) {
- const absPath = resolve(contextCwd(), filePath);
+ async prepareRename(filePath, line, character, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
+ const options = signal === undefined ? {} : { signal };
return this.sendRequest("textDocument/prepareRename", {
- textDocument: { uri: pathToFileURL2(absPath).href },
+ textDocument: { uri: pathToFileURL3(absPath).href },
position: { line: line - 1, character }
- });
+ }, options);
}
- async rename(filePath, line, character, newName) {
- const absPath = resolve(contextCwd(), filePath);
+ async rename(filePath, line, character, newName, signal) {
+ const absPath = this.resolveWorkspacePath(filePath);
await this.openFile(absPath);
- return this.sendRequest("textDocument/rename", {
- textDocument: { uri: pathToFileURL2(absPath).href },
- position: { line: line - 1, character },
- newName
- });
+ const acquired = this.workspaceMutations.acquire(signal);
+ if (!acquired.success)
+ return { edit: null, apply: acquired.result };
+ const preCommitSignal = createPreCommitAbortSignal(signal, () => this.workspaceMutations.isBeforeCommit(acquired.lease));
+ try {
+ const renameParams = {
+ textDocument: { uri: pathToFileURL3(absPath).href },
+ position: { line: line - 1, character },
+ newName
+ };
+ const edit = preCommitSignal === undefined ? await this.sendRequest("textDocument/rename", renameParams) : await this.sendRequest("textDocument/rename", renameParams, {
+ signal: preCommitSignal.signal
+ });
+ return await this.workspaceMutations.reconcileRename(acquired.lease, edit);
+ } finally {
+ preCommitSignal?.dispose();
+ this.workspaceMutations.release(acquired.lease);
+ }
}
+ resolveWorkspacePath(filePath) {
+ return resolve6(this.root, filePath);
+ }
+}
+function waitForDiagnosticsActivity(wait, signal) {
+ if (!signal)
+ return wait;
+ if (signal.aborted)
+ return Promise.reject(abortError2(signal));
+ return new Promise((resolve72, reject) => {
+ const onAbort = () => {
+ signal.removeEventListener("abort", onAbort);
+ reject(abortError2(signal));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ wait.then(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve72();
+ }, (error) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(error);
+ });
+ });
+}
+function createPreCommitAbortSignal(source, isBeforeCommit) {
+ if (!source)
+ return;
+ const controller = new AbortController;
+ const onAbort = () => {
+ if (isBeforeCommit() && !controller.signal.aborted)
+ controller.abort(preCommitAbortReason(source));
+ };
+ if (source.aborted)
+ onAbort();
+ else
+ source.addEventListener("abort", onAbort, { once: true });
+ return {
+ signal: controller.signal,
+ dispose: () => source.removeEventListener("abort", onAbort)
+ };
+}
+function preCommitAbortReason(source) {
+ const reason = source.reason;
+ if (reason instanceof Error && reason.name !== "AbortError")
+ return reason;
+ return new Error("LSP request cancelled before workspace edit commit");
+}
+function abortError2(signal) {
+ const reason = signal.reason;
+ if (reason instanceof Error)
+ return reason;
+ const error = new Error(typeof reason === "string" ? reason : "operation cancelled");
+ error.name = "AbortError";
+ return error;
}
function installProcessSignalCleanup(cleanup) {
const signals = process.platform === "win32" ? ["SIGINT", "SIGTERM", "SIGBREAK"] : ["SIGINT", "SIGTERM"];
@@ -1153,7 +3191,7 @@ async function stopClientBestEffort(client) {
function awaitWithSignal(promise, signal) {
if (!signal)
return promise;
- return new Promise((resolve22, reject) => {
+ return new Promise((resolve72, reject) => {
let settled = false;
const onAbort = () => {
if (settled)
@@ -1171,7 +3209,7 @@ function awaitWithSignal(promise, signal) {
return;
settled = true;
signal.removeEventListener("abort", onAbort);
- resolve22(value);
+ resolve72(value);
}, (err) => {
if (settled)
return;
@@ -1196,7 +3234,7 @@ class LspManager {
this.idleTimeoutMs = options.idleTimeoutMs ?? IDLE_TIMEOUT_MS;
this.initTimeoutMs = options.initTimeoutMs ?? INIT_TIMEOUT_MS;
this.reaperIntervalMs = options.reaperIntervalMs ?? REAPER_INTERVAL_MS;
- this.clientFactory = options.clientFactory ?? ((root, server) => new LspClient(root, server));
+ this.clientFactory = options.clientFactory ?? ((root, server2) => new LspClient(root, server2));
this.now = options.now ?? (() => Date.now());
this.startReaper();
this.signalDisposer = installProcessSignalCleanup(() => this.stopAll());
@@ -1234,12 +3272,12 @@ class LspManager {
await stopClientBestEffort(managed.client);
}
}
- async getClient(root, server, signal) {
+ async getClient(root, server2, signal) {
if (this.disposed) {
throw new Error("LspManager has been disposed");
}
signal?.throwIfAborted();
- const key = this.getKey(root, server.id);
+ const key = this.getKey(root, server2.id);
let managed = this.clients.get(key);
if (managed) {
const t = this.now();
@@ -1268,13 +3306,13 @@ class LspManager {
if (!managed.client.isAlive()) {
await stopClientBestEffort(managed.client);
this.clients.delete(key);
- return this.getClient(root, server, signal);
+ return this.getClient(root, server2, signal);
}
managed.refCount++;
managed.lastUsedAt = this.now();
return managed.client;
}
- const client = this.clientFactory(root, server);
+ const client = this.clientFactory(root, server2);
const initStartedAt = this.now();
const initPromise = (async () => {
await client.start();
@@ -1330,13 +3368,13 @@ class LspManager {
this.clients.delete(key);
stopClientBestEffort(managed.client);
}
- warmupClient(root, server) {
+ warmupClient(root, server2) {
if (this.disposed)
return;
- const key = this.getKey(root, server.id);
+ const key = this.getKey(root, server2.id);
if (this.clients.has(key))
return;
- const client = this.clientFactory(root, server);
+ const client = this.clientFactory(root, server2);
const initStartedAt = this.now();
const initPromise = (async () => {
await client.start();
@@ -1416,230 +3454,15 @@ function getLspManager() {
}
return _defaultInstance;
}
-async function disposeDefaultLspManager() {
- if (_defaultInstance) {
- const m = _defaultInstance;
- _defaultInstance = null;
- await m.stopAll();
- }
-}
-function isPlainRecord(value) {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-function isProcessAlive(pid) {
- if (!Number.isInteger(pid) || pid <= 0)
- return false;
- try {
- process.kill(pid, 0);
- return true;
- } catch (error) {
- return error.code === "EPERM";
- }
-}
-function readLockPid(lockPath) {
- try {
- const pid = Number.parseInt(readFileSync2(lockPath, "utf8").trim(), 10);
- return Number.isInteger(pid) ? pid : null;
- } catch {
- return null;
- }
-}
-function tryAcquireLock(lockPath, ownerPid = process.pid) {
- mkdirSync(dirname(lockPath), { recursive: true });
- for (let attempt = 0;attempt < 2; attempt += 1) {
- const handle = writeLockFile(lockPath, ownerPid);
- if (handle)
- return handle;
- if (!reapStaleLock(lockPath))
- return null;
- }
- return null;
-}
-function writeLockFile(lockPath, ownerPid) {
- try {
- const fd = openSync(lockPath, "wx");
- writeSync(fd, `${ownerPid}
-`);
- closeSync(fd);
- return { release: () => unlinkQuietly(lockPath) };
- } catch (error) {
- if (error.code === "EEXIST")
- return null;
- throw error;
- }
-}
-function reapStaleLock(lockPath) {
- const pid = readLockPid(lockPath);
- if (pid !== null && isProcessAlive(pid))
- return false;
- unlinkQuietly(lockPath);
- return true;
-}
-function unlinkQuietly(path) {
- try {
- unlinkSync(path);
- } catch (error) {}
-}
-var PROBE_TIMEOUT_MS = 500;
-var DEFAULT_READY_TIMEOUT_MS = 5000;
-var DEFAULT_POLL_INTERVAL_MS = 100;
-var CODEX_LSP_DAEMON_CLI_ENV = "CODEX_LSP_DAEMON_CLI";
-
-class DaemonUnreachableError extends Error {
- constructor(socketPath) {
- super(`LSP daemon did not become reachable at ${socketPath}`);
- this.name = "DaemonUnreachableError";
- }
-}
-async function ensureDaemonRunning(paths, deps = defaultEnsureDaemonDeps(), options = {}) {
- const readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
- const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
- if (await deps.probe(paths.socket))
- return;
- const lock = deps.acquireLock(paths.lock);
- if (!lock) {
- await waitUntilReachable(paths.socket, deps, readyTimeoutMs, pollIntervalMs);
- return;
- }
- try {
- if (await deps.probe(paths.socket))
- return;
- deps.cleanupStaleSocket(paths.socket);
- deps.spawnDaemon(paths);
- await waitUntilReachable(paths.socket, deps, readyTimeoutMs, pollIntervalMs);
- } finally {
- lock.release();
- }
-}
-async function waitUntilReachable(socketPath, deps, readyTimeoutMs, pollIntervalMs) {
- const deadline = deps.now() + readyTimeoutMs;
- for (;; ) {
- if (await deps.probe(socketPath))
- return;
- if (deps.now() >= deadline)
- throw new DaemonUnreachableError(socketPath);
- await deps.sleep(pollIntervalMs);
- }
-}
-function probeSocket(socketPath, timeoutMs = PROBE_TIMEOUT_MS) {
- return new Promise((resolve22) => {
- const socket = connect(socketPath);
- const finish = (ok) => {
- socket.destroy();
- resolve22(ok);
- };
- const timer = setTimeout(() => finish(false), timeoutMs);
- timer.unref?.();
- socket.once("connect", () => {
- clearTimeout(timer);
- finish(true);
- });
- socket.once("error", () => {
- clearTimeout(timer);
- finish(false);
- });
- });
-}
-function spawnDaemonProcess(paths) {
- mkdirSync2(dirname2(paths.log), { recursive: true });
- const logFd = openSync2(paths.log, "a");
- try {
- const cliPath = resolveDaemonCliPath();
- const child = spawn2(execPath, [cliPath, "daemon"], {
- detached: true,
- stdio: ["ignore", logFd, logFd]
- });
- child.unref();
- } finally {
- closeSync2(logFd);
- }
-}
-function resolveDaemonCliPath(env = process.env) {
- const override = env[CODEX_LSP_DAEMON_CLI_ENV]?.trim();
- if (override)
- return override;
- return fileURLToPath(new URL("./cli.js", import.meta.url));
-}
-function defaultEnsureDaemonDeps() {
- return {
- probe: (socketPath) => probeSocket(socketPath),
- acquireLock: (lockPath) => tryAcquireLock(lockPath),
- cleanupStaleSocket: (socketPath) => {
- if (existsSync2(socketPath))
- unlinkQuietly(socketPath);
- },
- spawnDaemon: (paths) => spawnDaemonProcess(paths),
- sleep: (ms) => new Promise((resolve22) => {
- setTimeout(resolve22, ms);
- }),
- now: () => Date.now()
- };
-}
-var requireFromHere = createRequire(import.meta.url);
-var MAX_SOCKET_PATH_LENGTH = 100;
-var CODEX_LSP_DAEMON_VERSION_ENV = "CODEX_LSP_DAEMON_VERSION";
-function resolveDaemonVersion(requireFn = requireFromHere) {
- for (const candidate of ["./package.json", "../package.json"]) {
- try {
- const pkg = requireFn(candidate);
- if (typeof pkg.version === "string" && pkg.version.length > 0)
- return pkg.version;
- } catch {}
- }
- return "0";
-}
-function daemonBaseDir(env = process.env) {
- const explicit = env["CODEX_LSP_DAEMON_DIR"]?.trim();
- if (explicit)
- return explicit;
- const pluginData = env["PLUGIN_DATA"]?.trim();
- if (pluginData)
- return join2(pluginData, "daemon");
- const codexHome = env["CODEX_HOME"]?.trim();
- const home = codexHome && codexHome.length > 0 ? codexHome : join2(homedir(), ".codex");
- return join2(home, "codex-lsp", "daemon");
-}
-function daemonPaths(env = process.env, version = resolveDaemonVersionFromEnv(env) ?? resolveDaemonVersion()) {
- const dir = join2(daemonBaseDir(env), `v${version}`);
- return {
- version,
- dir,
- socket: resolveSocketPath(dir, version),
- lock: join2(dir, "daemon.lock"),
- pid: join2(dir, "daemon.pid"),
- log: join2(dir, "daemon.log")
- };
-}
-function resolveDaemonVersionFromEnv(env = process.env) {
- const version = env[CODEX_LSP_DAEMON_VERSION_ENV]?.trim();
- return version && version.length > 0 ? version : null;
-}
-function resolveSocketPath(dir, version) {
- const digest = createHash("sha256").update(dir).digest("hex").slice(0, 16);
- if (process.platform === "win32") {
- return `\\\\.\\pipe\\omo-lsp-${version}-${digest}`;
- }
- const natural = join2(dir, "daemon.sock");
- if (natural.length < MAX_SOCKET_PATH_LENGTH)
- return natural;
- return join2(tmpdir(), `omo-lsp-${version}-${digest}.sock`);
-}
-var HEADER_SEPARATOR2 = Buffer.from(`\r
-\r
-`);
-var DEFAULT_IDLE_TIMEOUT_MS = 10 * 60000;
function getInstallDecisionsPath() {
- const override = contextEnv("LSP_TOOLS_MCP_INSTALL_DECISIONS");
- if (!override)
- return join3(homedir2(), ".codex", "lsp-install-decisions.json");
- return isAbsolute(override) ? override : join3(homedir2(), override);
+ return lspRequestContext().installDecisionsPath;
}
function loadInstallDecisions() {
- const path = getInstallDecisionsPath();
- if (!existsSync3(path))
+ const path2 = getInstallDecisionsPath();
+ if (!existsSync6(path2))
return {};
try {
- const parsed = JSON.parse(readFileSync3(path, "utf8"));
+ const parsed = JSON.parse(readFileSync4(path2, "utf8"));
return isInstallDecisions(parsed) ? parsed : {};
} catch {
return {};
@@ -1657,22 +3480,22 @@ function isInstallDecision(value) {
return value === "declined" || value === "allowed";
}
function writeInstallDecisions(decisions) {
- const path = getInstallDecisionsPath();
- mkdirSync3(dirname3(path), { recursive: true });
- const tmpPath = `${path}.tmp`;
- writeFileSync(tmpPath, `${JSON.stringify(decisions, null, 2)}
+ const path2 = getInstallDecisionsPath();
+ mkdirSync3(dirname7(path2), { recursive: true });
+ const tmpPath = `${path2}.tmp`;
+ writeFileSync2(tmpPath, `${JSON.stringify(decisions, null, 2)}
`, "utf8");
- renameSync(tmpPath, path);
+ renameSync2(tmpPath, path2);
}
function isInstallDecisions(value) {
- return isRecord2(value) && Object.values(value).every(isInstallDecisionRecord);
+ return isRecord5(value) && Object.values(value).every(isInstallDecisionRecord);
}
function isInstallDecisionRecord(value) {
- if (!isRecord2(value))
+ if (!isRecord5(value))
return false;
return isInstallDecision(value["decision"]) && typeof value["decidedAt"] === "string";
}
-function isRecord2(value) {
+function isRecord5(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
var LSP_INSTALL_HINTS = {
@@ -1820,27 +3643,17 @@ var BUILTIN_SERVERS = {
extensions: [".razor", ".cshtml"]
}
};
-function resolveProjectConfigPath(path) {
- return isAbsolute2(path) ? path : join4(contextCwd(), path);
-}
function getProjectConfigPaths() {
- const projectOverride = contextEnv("LSP_TOOLS_MCP_PROJECT_CONFIG");
- if (projectOverride) {
- return projectOverride.split(delimiter2).filter(Boolean).map(resolveProjectConfigPath);
- }
- return [join4(contextCwd(), ".codex", "lsp-client.json")];
+ return lspRequestContext().projectConfigPaths;
}
function getUserConfigPath() {
- const userOverride = contextEnv("LSP_TOOLS_MCP_USER_CONFIG");
- if (!userOverride)
- return join4(homedir3(), ".codex", "lsp-client.json");
- return isAbsolute2(userOverride) ? userOverride : join4(homedir3(), userOverride);
+ return lspRequestContext().userConfigPath;
}
-function loadJsonFile(path) {
- if (!existsSync4(path))
+function loadJsonFile(path2) {
+ if (!existsSync7(path2))
return null;
try {
- const parsed = JSON.parse(readFileSync4(path, "utf-8"));
+ const parsed = JSON.parse(readFileSync5(path2, "utf-8"));
return isConfigJson(parsed) ? parsed : null;
} catch {
return null;
@@ -1857,8 +3670,8 @@ function loadAllConfigs() {
return configs;
}
function loadFirstJsonFile(paths) {
- for (const path of paths) {
- const config = loadJsonFile(path);
+ for (const path2 of paths) {
+ const config = loadJsonFile(path2);
if (config)
return config;
}
@@ -1979,16 +3792,16 @@ function applyOptionalServerFields(server2, entry) {
}
}
function isConfigJson(value) {
- if (!isRecord3(value))
+ if (!isRecord6(value))
return false;
const lsp = value["lsp"];
- return lsp === undefined || isRecord3(lsp);
+ return lsp === undefined || isRecord6(lsp);
}
function parseLspEntry(value) {
return isLspEntry(value) ? value : null;
}
function isLspEntry(value) {
- if (!isRecord3(value))
+ if (!isRecord6(value))
return false;
const disabled = value["disabled"];
const command = value["command"];
@@ -1996,15 +3809,15 @@ function isLspEntry(value) {
const priority = value["priority"];
const env = value["env"];
const initialization = value["initialization"];
- return (disabled === undefined || typeof disabled === "boolean") && (command === undefined || isStringArray(command)) && (extensions === undefined || isStringArray(extensions)) && (priority === undefined || typeof priority === "number") && (env === undefined || isStringRecord(env)) && (initialization === undefined || isRecord3(initialization));
+ return (disabled === undefined || typeof disabled === "boolean") && (command === undefined || isStringArray(command)) && (extensions === undefined || isStringArray(extensions)) && (priority === undefined || typeof priority === "number") && (env === undefined || isStringRecord(env)) && (initialization === undefined || isRecord6(initialization));
}
function isStringArray(value) {
return Array.isArray(value) && value.every((item) => typeof item === "string");
}
function isStringRecord(value) {
- return isRecord3(value) && Object.values(value).every((item) => typeof item === "string");
+ return isRecord6(value) && Object.values(value).every((item) => typeof item === "string");
}
-function isRecord3(value) {
+function isRecord6(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function getDisabledServerIds() {
@@ -2030,7 +3843,7 @@ function isServerInstalled(command, _workingDirectory) {
if (!cmd)
return false;
if (cmd.includes("/") || cmd.includes("\\")) {
- if (existsSync5(cmd))
+ if (existsSync8(cmd))
return true;
}
const isWindows = process.platform === "win32";
@@ -2051,7 +3864,7 @@ function isServerInstalled(command, _workingDirectory) {
const paths = pathEnv.split(delimiter3);
for (const p of paths) {
for (const suffix of exts) {
- if (existsSync5(join5(p, cmd + suffix))) {
+ if (existsSync8(join3(p, cmd + suffix))) {
return true;
}
}
@@ -2146,39 +3959,50 @@ function getAllServers() {
var WORKSPACE_MARKERS = [".git", "package.json", "pyproject.toml", "Cargo.toml", "go.mod", "pom.xml", "build.gradle"];
function isDirectoryPath(filePath) {
try {
- return statSync2(filePath).isDirectory();
+ return statSync4(filePath).isDirectory();
} catch {
return false;
}
}
function findWorkspaceRoot(filePath) {
- const abs = resolve2(contextCwd(), filePath);
+ const abs = resolvePathInsideContext(filePath);
let dir = abs;
if (!isDirectoryPath(dir)) {
- dir = dirname4(dir);
+ dir = dirname8(dir);
}
let prevDir = "";
while (dir !== prevDir) {
for (const marker of WORKSPACE_MARKERS) {
- if (existsSync6(join6(dir, marker))) {
+ if (existsSync9(join4(dir, marker))) {
return dir;
}
}
prevDir = dir;
- dir = dirname4(dir);
+ dir = dirname8(dir);
}
- return dirname4(abs);
+ return dirname8(abs);
+}
+function resolvePathInsideContext(filePath) {
+ const cwd = contextCwd();
+ const abs = resolve7(cwd, filePath);
+ const canonical = canonicalizeExistingOrNearestAncestor(abs);
+ if (!isPathInside(cwd, canonical)) {
+ throw new LspInvalidPathError(`LSP file path must be inside request cwd: ${filePath}`);
+ }
+ return canonical;
}
function formatServerLookupError(result) {
if (result.status === "not_installed") {
return formatNotInstalled(result);
}
+ const context = lspRequestContext();
+ const firstProjectConfigPath = context.projectConfigPaths[0] ?? "<project lsp config>";
return [
`No LSP server configured for extension: ${result.extension}`,
"",
`Available servers: ${result.availableServers.slice(0, 10).join(", ")}${result.availableServers.length > 10 ? "..." : ""}`,
"",
- "Configure a custom server in '.codex/lsp-client.json':",
+ `Configure a custom server in '${firstProjectConfigPath}' or '${context.userConfigPath}':`,
" {",
' "lsp": {',
' "my-server": {',
@@ -2194,6 +4018,7 @@ function formatNotInstalled(result) {
const { server: server2, installHint } = result;
const extensions = server2.extensions.join(", ");
const decision = loadInstallDecision(server2.id)?.decision;
+ const context = lspRequestContext();
if (decision === "declined") {
return `LSP server '${server2.id}' (${extensions}) is NOT INSTALLED; user previously declined installation — proceed without LSP.`;
}
@@ -2209,6 +4034,17 @@ function formatNotInstalled(result) {
"The user has pre-authorized LSP installation. Run the install command, then retry this tool:",
` ${installHint}`
].join(`
+`);
+ }
+ if (!context.capabilities.installDecisionTool) {
+ return [
+ ...header,
+ "To install, run:",
+ ` ${installHint}`,
+ "",
+ "ACTION REQUIRED — ASK THE USER whether to install this LSP server.",
+ "Install-decision recording is unavailable in this harness; proceed without LSP if the user declines."
+ ].join(`
`);
}
return [
@@ -2220,6 +4056,7 @@ function formatNotInstalled(result) {
"- If the user agrees: run the install command above, then retry this tool.",
"- If the user declines, OR has NOT explicitly asked for LSP installation:",
` call lsp_install_decision { server_id: "${server2.id}", decision: "declined" },`,
+ ` which writes to ${context.installDecisionsPath},`,
" then ignore this message and proceed WITHOUT LSP."
].join(`
`);
@@ -2233,14 +4070,14 @@ var READ_ONLY_RETRY_TOOLS = new Set([
"prepareRename"
]);
async function withLspClient(filePath, fn, toolName, options = {}) {
- const absPath = resolve2(contextCwd(), filePath);
+ const absPath = resolvePathInsideContext(filePath);
if (isDirectoryPath(absPath)) {
throw new LspInvalidPathError("Directory paths are not supported by this LSP tool. " + "Use lsp.diagnostics with a directory path for directory diagnostics.");
}
const ext = effectiveExtension(absPath);
const result = findServerForExtension(ext);
if (result.status !== "found") {
- throw new LspServerLookupError(formatServerLookupError(result));
+ throw new LspServerLookupError(formatServerLookupError(result), result);
}
const server2 = result.server;
const root = findWorkspaceRoot(absPath);
@@ -2273,7 +4110,7 @@ var DIAGNOSTIC_SEVERITY_FILTERS = {
hint: 4
};
function uriToPath(uri) {
- return fileURLToPath2(uri);
+ return fileURLToPath3(uri);
}
function formatLocation(loc) {
if ("targetUri" in loc) {
@@ -2359,6 +4196,9 @@ function formatApplyResult(result) {
for (const file of result.filesModified) {
lines.push(` - ${file}`);
}
+ if (result.lateAbort) {
+ lines.push("Cancellation arrived after the filesystem commit began; the committed edit completed.");
+ }
} else {
lines.push("Failed to apply some changes:");
for (const err of result.errors) {
@@ -2372,6 +4212,7 @@ function formatApplyResult(result) {
`);
}
var SKIP_DIRECTORIES = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
+var DIRECTORY_DIAGNOSTICS_MAX_CONCURRENCY = 4;
function collectFilesWithExtension(dir, extension, maxFiles) {
const files = [];
function walk(currentDir) {
@@ -2379,17 +4220,17 @@ function collectFilesWithExtension(dir, extension, maxFiles) {
return;
let entries = [];
try {
- entries = readdirSync(currentDir);
+ entries = readdirSync3(currentDir);
} catch {
return;
}
for (const entry of entries) {
if (files.length >= maxFiles)
return;
- const fullPath = join7(currentDir, entry);
+ const fullPath = join5(currentDir, entry);
let stat;
try {
- stat = lstatSync(fullPath);
+ stat = lstatSync5(fullPath);
} catch {
continue;
}
@@ -2407,52 +4248,65 @@ function collectFilesWithExtension(dir, extension, maxFiles) {
walk(dir);
return files;
}
-async function aggregateDiagnosticsForDirectory(directory, extension, severity, maxFiles = DEFAULT_MAX_DIRECTORY_FILES) {
+async function aggregateDiagnosticsForDirectory(directory, extension, severity, maxFiles = DEFAULT_MAX_DIRECTORY_FILES, options = {}) {
if (!extension.startsWith(".")) {
throw new LspInvalidPathError(`Extension must start with a dot (e.g., ".ts", not "${extension}"). Use ".${extension}" instead.`);
}
- const absDir = resolve3(contextCwd(), directory);
- if (!existsSync7(absDir)) {
+ const absDir = resolve8(options.workspaceRoot ?? contextCwd(), directory);
+ if (!existsSync10(absDir)) {
throw new LspInvalidPathError(`Directory does not exist: ${absDir}`);
}
- const serverResult = findServerForExtension(extension);
+ const serverResult = options.server === undefined ? findServerForExtension(extension) : { status: "found", server: options.server };
if (serverResult.status !== "found") {
throw new LspServerLookupError(formatServerLookupError(serverResult));
}
const server2 = serverResult.server;
- const allFiles = collectFilesWithExtension(absDir, extension, maxFiles + 1);
+ const allFiles = (options.listFiles ?? collectFilesWithExtension)(absDir, extension, maxFiles + 1);
const wasCapped = allFiles.length > maxFiles;
const filesToProcess = allFiles.slice(0, maxFiles);
if (filesToProcess.length === 0) {
- return [
+ const output = [
`Directory: ${absDir}`,
`Extension: ${extension}`,
"Files scanned: 0",
`No files found with extension "${extension}".`
].join(`
`);
+ return { output, totalDiagnostics: 0, fileFailures: [] };
}
- const root = findWorkspaceRoot(absDir);
- const manager = getLspManager();
+ const root = options.workspaceRoot ?? findWorkspaceRoot(absDir);
+ const manager = options.manager ?? getLspManager();
const allDiagnostics = [];
const fileErrors = [];
+ const maxConcurrency = Math.max(1, options.maxConcurrency ?? DIRECTORY_DIAGNOSTICS_MAX_CONCURRENCY);
+ options.signal?.throwIfAborted();
const client = await manager.getClient(root, server2);
try {
- for (const file of filesToProcess) {
- try {
- const result = await client.diagnostics(file);
- const filtered = filterDiagnosticsBySeverity(result.items, severity);
- allDiagnostics.push(...filtered.map((diagnostic) => ({
- filePath: file,
- diagnostic
- })));
- } catch (e) {
- fileErrors.push({
- file,
- error: e instanceof Error ? e.message : String(e)
- });
+ let nextIndex = 0;
+ const workers = Array.from({ length: Math.min(maxConcurrency, filesToProcess.length) }, async () => {
+ for (;; ) {
+ if (options.signal?.aborted)
+ return;
+ const file = filesToProcess[nextIndex];
+ nextIndex += 1;
+ if (file === undefined)
+ return;
+ try {
+ const result = await client.diagnostics(file, options.signal);
+ const filtered = filterDiagnosticsBySeverity(result.items, severity);
+ allDiagnostics.push(...filtered.map((diagnostic) => ({
+ filePath: file,
+ diagnostic
+ })));
+ } catch (e) {
+ fileErrors.push({
+ file,
+ error: e instanceof Error ? e.message : String(e)
+ });
+ }
}
- }
+ });
+ await Promise.all(workers);
} finally {
manager.releaseClient(root, server2.id);
}
@@ -2480,8 +4334,8 @@ async function aggregateDiagnosticsForDirectory(directory, extension, severity,
lines.push("", `... (${allDiagnostics.length - DEFAULT_MAX_DIAGNOSTICS} more diagnostics not shown)`);
}
}
- return lines.join(`
-`);
+ return { output: lines.join(`
+`), totalDiagnostics: allDiagnostics.length, fileFailures: fileErrors };
}
var SKIP_DIRECTORIES2 = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
var MAX_SCAN_ENTRIES = 500;
@@ -2493,17 +4347,17 @@ function inferExtensionFromDirectory(directory) {
return;
let entries;
try {
- entries = readdirSync2(dir);
+ entries = readdirSync4(dir);
} catch {
return;
}
for (const entry of entries) {
if (scanned >= MAX_SCAN_ENTRIES)
return;
- const fullPath = join8(dir, entry);
+ const fullPath = join6(dir, entry);
let stat;
try {
- stat = lstatSync2(fullPath);
+ stat = lstatSync6(fullPath);
} catch {
continue;
}
@@ -2574,10 +4428,45 @@ function missingDependencyResult(error, details) {
details: {
...details,
error: message,
- errorKind: "missing_dependency"
+ errorKind: "missing_dependency",
+ ...availabilityDetails(error)
}
};
}
+function availabilityDetails(error) {
+ const availability = missingDependencyAvailability(error);
+ return availability === null ? {} : { availability };
+}
+function missingDependencyAvailability(error) {
+ if (!(error instanceof LspServerLookupError) || error.lookup === undefined)
+ return null;
+ const context = lspRequestContext();
+ switch (error.lookup.status) {
+ case "not_configured":
+ return {
+ kind: "not_configured",
+ extension: error.lookup.extension,
+ availableServers: [...error.lookup.availableServers],
+ projectConfigPaths: [...context.projectConfigPaths],
+ userConfigPath: context.userConfigPath,
+ installDecisionTool: context.capabilities.installDecisionTool
+ };
+ case "not_installed":
+ return {
+ kind: "not_installed",
+ serverId: error.lookup.server.id,
+ command: [...error.lookup.server.command],
+ extensions: [...error.lookup.server.extensions],
+ installHint: error.lookup.installHint,
+ installDecisionTool: context.capabilities.installDecisionTool,
+ installDecisionsPath: context.installDecisionsPath
+ };
+ default: {
+ const exhaustive = error.lookup;
+ return exhaustive;
+ }
+ }
+}
function requireString(params, key) {
const value = params[key];
if (typeof value !== "string" || value.length === 0) {
@@ -2628,7 +4517,7 @@ async function executeLspDiagnostics(params, signal) {
const filePath = requireString(params, "filePath");
const severity = severityFilter(params);
try {
- const absPath = resolve4(contextCwd(), filePath);
+ const absPath = resolvePathInsideContext(filePath);
if (isDirectoryPath(absPath)) {
const extension = inferExtensionFromDirectory(absPath);
if (!extension) {
@@ -2645,18 +4534,33 @@ async function executeLspDiagnostics(params, signal) {
};
return text(message, details3);
}
- const output2 = await aggregateDiagnosticsForDirectory(absPath, extension, severity);
+ const output2 = await aggregateDiagnosticsForDirectory(absPath, extension, severity, undefined, signal === undefined ? {} : { signal });
const details2 = {
filePath,
severity,
mode: "directory",
diagnostics: [],
+ totalDiagnostics: output2.totalDiagnostics,
+ truncated: false,
+ fileFailures: [...output2.fileFailures]
+ };
+ return text(output2.output, details2);
+ }
+ const result = await withLspClient(filePath, async (client) => client.diagnostics(filePath, signal), "diagnostics", clientOptions(signal));
+ if (result.transientError) {
+ const message = result.transientError.message;
+ const details2 = {
+ filePath,
+ severity,
+ mode: "file",
+ diagnostics: [],
totalDiagnostics: 0,
- truncated: false
+ truncated: false,
+ error: message,
+ errorKind: result.transientError.kind
};
- return text(output2, details2);
+ return text(message, details2, true);
}
- const result = await withLspClient(filePath, async (client) => client.diagnostics(filePath), "diagnostics", clientOptions(signal));
const diagnostics = filterDiagnosticsBySeverity(asDiagnosticArray(result), severity);
const total = diagnostics.length;
const truncated = total > DEFAULT_MAX_DIAGNOSTICS;
@@ -2714,7 +4618,7 @@ async function executeLspGotoDefinition(params, signal) {
const line = requireNumber(params, "line");
const character = requireNumber(params, "character");
try {
- const result = await withLspClient(filePath, async (client) => client.definition(filePath, line, character), "definition", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.definition(filePath, line, character, signal), "definition", clientOptions(signal));
const locations = !result ? [] : Array.isArray(result) ? result : [result];
const details = { filePath, line, character, locations };
if (locations.length === 0)
@@ -2733,216 +4637,53 @@ async function executeLspGotoDefinition(params, signal) {
throw error;
}
}
-async function executeLspFindReferences(params, signal) {
- const filePath = requireString(params, "filePath");
- const line = requireNumber(params, "line");
- const character = requireNumber(params, "character");
- const includeDeclaration = optionalBoolean(params, "includeDeclaration") ?? true;
- try {
- const result = await withLspClient(filePath, async (client) => client.references(filePath, line, character, includeDeclaration), "references", clientOptions(signal));
- const references = Array.isArray(result) ? result : [];
- const total = references.length;
- const truncated = total > DEFAULT_MAX_REFERENCES;
- const limited = truncated ? references.slice(0, DEFAULT_MAX_REFERENCES) : references;
- const details = {
- filePath,
- line,
- character,
- references,
- totalReferences: total,
- truncated
- };
- if (total === 0)
- return text("No references found", details);
- const output = [
- ...truncated ? [`Found ${total} references (showing first ${DEFAULT_MAX_REFERENCES}):`] : [],
- ...limited.map(formatLocation)
- ].join(`
-`);
- return text(output, details);
- } catch (error) {
- const missingDependency = missingDependencyResult(error, {
- filePath,
- line,
- character,
- references: [],
- totalReferences: 0,
- truncated: false
- });
- if (missingDependency)
- return missingDependency;
- throw error;
- }
-}
-function errorMessage2(error) {
- return error instanceof Error ? error.message : String(error);
-}
-function isPathInsideWorkspace(filePath, workspaceRoot) {
- const relativePath = relative(workspaceRoot, filePath);
- return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute3(relativePath);
-}
-function realpathForValidation(filePath) {
- if (existsSync8(filePath))
- return realpathSync(filePath);
- const parent = dirname5(filePath);
- return resolve5(realpathSync(parent), relative(parent, filePath));
-}
-function uriToWorkspacePath(uri, workspaceRoot) {
- let filePath;
- try {
- filePath = fileURLToPath3(uri);
- } catch (error) {
- return { success: false, error: `non-file URI ${uri}: ${errorMessage2(error)}` };
- }
- let validatedPath;
- try {
- validatedPath = realpathForValidation(filePath);
- } catch (error) {
- return { success: false, error: `${filePath}: ${errorMessage2(error)}` };
- }
- if (!isPathInsideWorkspace(validatedPath, workspaceRoot)) {
- return { success: false, error: `${filePath}: outside workspace ${workspaceRoot}` };
- }
- return { success: true, path: filePath };
-}
-function applyTextEditsToFile(filePath, edits) {
- try {
- const content = readFileSync5(filePath, "utf-8");
- const lines = content.split(`
-`);
- const sortedEdits = [...edits].sort((a, b) => {
- if (b.range.start.line !== a.range.start.line) {
- return b.range.start.line - a.range.start.line;
- }
- return b.range.start.character - a.range.start.character;
- });
- for (const edit of sortedEdits) {
- const startLine = edit.range.start.line;
- const startChar = edit.range.start.character;
- const endLine = edit.range.end.line;
- const endChar = edit.range.end.character;
- if (startLine === endLine) {
- const line = lines[startLine] ?? "";
- lines[startLine] = line.substring(0, startChar) + edit.newText + line.substring(endChar);
- } else {
- const firstLine = lines[startLine] ?? "";
- const lastLine = lines[endLine] ?? "";
- const newContent = firstLine.substring(0, startChar) + edit.newText + lastLine.substring(endChar);
- lines.splice(startLine, endLine - startLine + 1, ...newContent.split(`
-`));
- }
- }
- writeFileSync2(filePath, lines.join(`
-`), "utf-8");
- return { success: true, editCount: edits.length };
- } catch (err) {
- return {
- success: false,
- editCount: 0,
- error: err instanceof Error ? err.message : String(err)
- };
- }
-}
-function applyWorkspaceEdit(edit, options = {}) {
- if (!edit) {
- return { success: false, filesModified: [], totalEdits: 0, errors: ["No edit provided"] };
- }
- const result = { success: true, filesModified: [], totalEdits: 0, errors: [] };
- const workspaceRoot = realpathSync(options.workspaceRoot ?? contextCwd());
- if (edit.changes) {
- for (const [uri, edits] of Object.entries(edit.changes)) {
- const validatedPath = uriToWorkspacePath(uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(validatedPath.error);
- continue;
- }
- const applyResult = applyTextEditsToFile(validatedPath.path, edits);
- if (applyResult.success) {
- result.filesModified.push(validatedPath.path);
- result.totalEdits += applyResult.editCount;
- } else {
- result.success = false;
- result.errors.push(`${validatedPath.path}: ${applyResult.error}`);
- }
- }
- }
- if (edit.documentChanges) {
- for (const change of edit.documentChanges) {
- if (!("kind" in change)) {
- const validatedPath = uriToWorkspacePath(change.textDocument.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(validatedPath.error);
- continue;
- }
- const applyResult = applyTextEditsToFile(validatedPath.path, change.edits);
- if (applyResult.success) {
- result.filesModified.push(validatedPath.path);
- result.totalEdits += applyResult.editCount;
- } else {
- result.success = false;
- result.errors.push(`${validatedPath.path}: ${applyResult.error}`);
- }
- continue;
- }
- if (change.kind === "create") {
- try {
- const validatedPath = uriToWorkspacePath(change.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(`Create ${change.uri}: ${validatedPath.error}`);
- continue;
- }
- writeFileSync2(validatedPath.path, "", "utf-8");
- result.filesModified.push(validatedPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Create ${change.uri}: ${String(err)}`);
- }
- } else if (change.kind === "rename") {
- try {
- const oldPath = uriToWorkspacePath(change.oldUri, workspaceRoot);
- const newPath = uriToWorkspacePath(change.newUri, workspaceRoot);
- if (!oldPath.success || !newPath.success) {
- const error = oldPath.success ? newPath.success ? "invalid URI" : newPath.error : oldPath.error;
- result.success = false;
- result.errors.push(`Rename ${change.oldUri}: ${error}`);
- continue;
- }
- const content = readFileSync5(oldPath.path, "utf-8");
- writeFileSync2(newPath.path, content, "utf-8");
- unlinkSync2(oldPath.path);
- result.filesModified.push(newPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Rename ${change.oldUri}: ${String(err)}`);
- }
- } else if (change.kind === "delete") {
- try {
- const validatedPath = uriToWorkspacePath(change.uri, workspaceRoot);
- if (!validatedPath.success) {
- result.success = false;
- result.errors.push(`Delete ${change.uri}: ${validatedPath.error}`);
- continue;
- }
- unlinkSync2(validatedPath.path);
- result.filesModified.push(validatedPath.path);
- } catch (err) {
- result.success = false;
- result.errors.push(`Delete ${change.uri}: ${String(err)}`);
- }
- }
- }
+async function executeLspFindReferences(params, signal) {
+ const filePath = requireString(params, "filePath");
+ const line = requireNumber(params, "line");
+ const character = requireNumber(params, "character");
+ const includeDeclaration = optionalBoolean(params, "includeDeclaration") ?? true;
+ try {
+ const result = await withLspClient(filePath, async (client) => client.references(filePath, line, character, includeDeclaration, signal), "references", clientOptions(signal));
+ const references = Array.isArray(result) ? result : [];
+ const total = references.length;
+ const truncated = total > DEFAULT_MAX_REFERENCES;
+ const limited = truncated ? references.slice(0, DEFAULT_MAX_REFERENCES) : references;
+ const details = {
+ filePath,
+ line,
+ character,
+ references,
+ totalReferences: total,
+ truncated
+ };
+ if (total === 0)
+ return text("No references found", details);
+ const output = [
+ ...truncated ? [`Found ${total} references (showing first ${DEFAULT_MAX_REFERENCES}):`] : [],
+ ...limited.map(formatLocation)
+ ].join(`
+`);
+ return text(output, details);
+ } catch (error) {
+ const missingDependency = missingDependencyResult(error, {
+ filePath,
+ line,
+ character,
+ references: [],
+ totalReferences: 0,
+ truncated: false
+ });
+ if (missingDependency)
+ return missingDependency;
+ throw error;
}
- return result;
}
async function executeLspPrepareRename(params, signal) {
const filePath = requireString(params, "filePath");
const line = requireNumber(params, "line");
const character = requireNumber(params, "character");
try {
- const result = await withLspClient(filePath, async (client) => client.prepareRename(filePath, line, character), "prepareRename", clientOptions(signal));
+ const result = await withLspClient(filePath, async (client) => client.prepareRename(filePath, line, character, signal), "prepareRename", clientOptions(signal));
const details = { filePath, line, character, result };
return text(formatPrepareRenameResult(result), details);
} catch (error) {
@@ -2963,13 +4704,9 @@ async function executeLspRename(params, signal) {
const character = requireNumber(params, "character");
const newName = requireString(params, "newName");
try {
- const edit = await withLspClient(filePath, async (client, workspaceRoot) => ({
- edit: await client.rename(filePath, line, character, newName),
- workspaceRoot
- }), "rename", clientOptions(signal));
- const apply = applyWorkspaceEdit(edit.edit, { workspaceRoot: edit.workspaceRoot });
- const details = { filePath, line, character, newName, apply, edit: edit.edit };
- return text(formatApplyResult(apply), details, !apply.success);
+ const result = await withLspClient(filePath, async (client) => client.rename(filePath, line, character, newName, signal), "rename", clientOptions(signal));
+ const details = { filePath, line, character, newName, apply: result.apply, edit: result.edit };
+ return text(formatApplyResult(result.apply), details, !result.apply.success);
} catch (error) {
const missingDependency = missingDependencyResult(error, {
filePath,
@@ -3038,10 +4775,10 @@ async function executeLspSymbols(params, signal) {
errorKind: "missing_query"
});
}
- const symbols2 = await withLspClient(filePath, async (client) => client.workspaceSymbols(query), "workspaceSymbols", clientOptions(signal));
+ const symbols2 = await withLspClient(filePath, async (client) => client.workspaceSymbols(query, signal), "workspaceSymbols", clientOptions(signal));
return formatSymbolsResult(filePath, scope, symbols2, limit, query);
}
- const symbols = await withLspClient(filePath, async (client) => client.documentSymbols(filePath), "documentSymbols", clientOptions(signal));
+ const symbols = await withLspClient(filePath, async (client) => client.documentSymbols(filePath, signal), "documentSymbols", clientOptions(signal));
return formatSymbolsResult(filePath, scope, symbols, limit);
} catch (error) {
const query = optionalString(params, "query");
@@ -3195,35 +4932,8 @@ var LSP_MCP_TOOLS = [
}
];
var CONTEXT_KEY = "_context";
-function encodeJsonLine(message) {
- return `${JSON.stringify(message)}
-`;
-}
-function createLineDecoder(onMessage, onParseError) {
- let buffer = "";
- return {
- push(chunk) {
- buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
- let index = buffer.indexOf(`
-`);
- while (index !== -1) {
- const raw = buffer.slice(0, index).trim();
- buffer = buffer.slice(index + 1);
- if (raw.length > 0) {
- try {
- onMessage(JSON.parse(raw));
- } catch (error) {
- onParseError?.(raw, error);
- }
- }
- index = buffer.indexOf(`
-`);
- }
- }
- };
-}
var DEFAULT_REQUEST_TIMEOUT_MS = 30000;
-var REQUEST_ID = 1;
+var nextProxyRequestId = 1;
class DaemonRequestError extends Error {
requestWritten;
@@ -3233,44 +4943,59 @@ class DaemonRequestError extends Error {
this.requestWritten = requestWritten;
}
}
-async function callToolViaDaemon(name, args, options = {}) {
+
+class DaemonAuthenticationRejectedError extends DaemonRequestError {
+ constructor() {
+ super("daemon authentication failed before dispatch", true);
+ this.name = "DaemonAuthenticationRejectedError";
+ }
+}
+
+class DaemonRequestCancelledError extends DaemonRequestError {
+ constructor(requestWritten) {
+ super("daemon request cancelled", requestWritten);
+ this.name = "DaemonRequestCancelledError";
+ }
+}
+async function callToolViaDaemon(name, args, options) {
+ const context = requireContext(options.context);
const paths = options.paths ?? daemonPaths();
const ensure = options.ensure ?? ensureDaemonRunning;
const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
- const requestArgs = withContext(args, options.context);
+ const requestArgs = withContext(args, context);
let lastError;
- for (let attempt = 0;attempt < 2; attempt += 1) {
+ let authRefreshUsed = false;
+ for (let attempt = 0;attempt < 3; attempt += 1) {
try {
await ensure(paths);
- return await sendToolCall(paths.socket, name, requestArgs, timeoutMs);
+ const token = readAuthToken(paths);
+ if (!token)
+ throw new DaemonRequestError("daemon auth token missing", false);
+ const sendOptions = options.signal === undefined ? { timeoutMs } : { timeoutMs, signal: options.signal };
+ return await sendToolCall(paths, token, name, requestArgs, sendOptions);
} catch (error) {
lastError = error;
- if (error instanceof DaemonRequestError && error.requestWritten)
+ if (error instanceof DaemonAuthenticationRejectedError && !authRefreshUsed) {
+ authRefreshUsed = true;
+ continue;
+ }
+ if (error instanceof DaemonRequestCancelledError)
+ break;
+ if (error instanceof DaemonRequestError && (error.requestWritten || !isRetryableTool(name)))
break;
}
}
return daemonUnreachableResult(paths, lastError);
}
-function callDiagnosticsViaDaemon(filePath, options = {}) {
+function callDiagnosticsViaDaemon(filePath, options) {
return callToolViaDaemon("diagnostics", { filePath, severity: "error" }, options);
}
-var FORWARDED_ENV_KEYS = [
- "LSP_TOOLS_MCP_PROJECT_CONFIG",
- "LSP_TOOLS_MCP_USER_CONFIG",
- "LSP_TOOLS_MCP_INSTALL_DECISIONS"
-];
-function currentRequestContext(env = process.env) {
- const forwarded = {};
- for (const key of FORWARDED_ENV_KEYS) {
- const value = env[key];
- if (value !== undefined)
- forwarded[key] = value;
- }
- return { cwd: process.cwd(), env: forwarded };
+function requireContext(context) {
+ if (!context)
+ throw new DaemonRequestError("daemon tool context is required", false);
+ return parseLspRequestContext(context);
}
function withContext(args, context) {
- if (!context || context.cwd === undefined && context.env === undefined)
- return args;
return { ...args, [CONTEXT_KEY]: context };
}
function daemonUnreachableResult(paths, error) {
@@ -3284,39 +5009,84 @@ function daemonUnreachableResult(paths, error) {
`);
return { content: [{ type: "text", text: text2 }], isError: true };
}
-function sendToolCall(socketPath, name, args, timeoutMs) {
- return new Promise((resolve6, reject) => {
- const socket = connect2(socketPath);
+function sendToolCall(paths, token, name, args, options) {
+ return new Promise((resolve9, reject) => {
+ const socket = connect2(paths.socket);
+ const requestId = allocateProxyRequestId();
let settled = false;
let requestWritten = false;
+ let cancelAfterWrite = false;
+ const cancelPayload = () => encodeJsonLine({
+ jsonrpc: "2.0",
+ method: "$/cancelRequest",
+ params: { _omo: authEnvelope(token), id: requestId }
+ });
const finish = (run) => {
if (settled)
return;
settled = true;
clearTimeout(timer);
- socket.destroy();
+ options.signal?.removeEventListener("abort", onAbort);
+ destroyAfterCancel();
run();
};
- const timer = setTimeout(() => finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten))), timeoutMs);
+ const sendCancel = () => {
+ if (!requestWritten) {
+ cancelAfterWrite = true;
+ return;
+ }
+ if (!socket.writable)
+ return;
+ socket.write(cancelPayload());
+ };
+ const destroyAfterCancel = () => {
+ socket.destroy();
+ };
+ const onAbort = () => {
+ sendCancel();
+ finish(() => reject(new DaemonRequestCancelledError(requestWritten)));
+ };
+ const timer = setTimeout(() => {
+ sendCancel();
+ finish(() => reject(new DaemonRequestError("daemon request timed out", requestWritten)));
+ }, options.timeoutMs);
timer.unref();
+ if (options.signal?.aborted) {
+ onAbort();
+ return;
+ }
+ options.signal?.addEventListener("abort", onAbort, { once: true });
const decoder = createLineDecoder((message) => {
- const result = toToolResult(message);
+ if (isAuthErrorResponse(message)) {
+ finish(() => reject(new DaemonAuthenticationRejectedError));
+ return;
+ }
+ const result = toToolResult(message, requestId);
if (result)
- finish(() => resolve6(result));
+ finish(() => resolve9(result));
else
finish(() => reject(new DaemonRequestError("invalid daemon response", requestWritten)));
});
socket.once("connect", () => {
- requestWritten = true;
- socket.write(encodeJsonLine({ jsonrpc: "2.0", id: REQUEST_ID, method: "tools/call", params: { name, arguments: args } }));
+ const payload = encodeJsonLine({
+ jsonrpc: "2.0",
+ id: requestId,
+ method: "tools/call",
+ params: { _omo: authEnvelope(token), name, arguments: args }
+ });
+ socket.write(payload, () => {
+ requestWritten = true;
+ if (cancelAfterWrite && socket.writable)
+ socket.write(cancelPayload());
+ });
});
socket.on("data", (chunk) => decoder.push(chunk));
socket.once("error", (error) => finish(() => reject(new DaemonRequestError(error.message, requestWritten))));
socket.once("close", () => finish(() => reject(new DaemonRequestError("daemon connection closed", requestWritten))));
});
}
-function toToolResult(message) {
- if (!isPlainRecord(message) || message["id"] !== REQUEST_ID)
+function toToolResult(message, requestId) {
+ if (!isPlainRecord(message) || message["id"] !== requestId)
return null;
const result = message["result"];
if (!isPlainRecord(result) || !Array.isArray(result["content"]))
@@ -3327,167 +5097,436 @@ function toToolResult(message) {
details: result["details"]
};
}
+function allocateProxyRequestId() {
+ const id = nextProxyRequestId;
+ nextProxyRequestId += 1;
+ if (nextProxyRequestId > Number.MAX_SAFE_INTEGER)
+ nextProxyRequestId = 1;
+ return id;
+}
+function isRetryableTool(name) {
+ return name !== "rename" && name !== "lsp_rename";
+}
function errorText(error) {
return error instanceof Error ? error.message : String(error);
}
+var OMO_LSP_DAEMON_CLI2 = "OMO_LSP_DAEMON_CLI";
+var OMO_LSP_DAEMON_VERSION2 = "OMO_LSP_DAEMON_VERSION";
+var DAEMON_VERSION_PATTERN2 = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
+
+class InvalidRuntimeOverrideError2 extends Error {
+ code = "invalid_runtime_override";
+ reason;
+ constructor(reason, message) {
+ super(message);
+ this.name = "InvalidRuntimeOverrideError";
+ this.reason = reason;
+ }
+}
+function validateDaemonVersion2(version) {
+ if (!DAEMON_VERSION_PATTERN2.test(version)) {
+ throw new Error("LSP daemon version must match [A-Za-z0-9][A-Za-z0-9._+-]{0,127}");
+ }
+ return version;
+}
+function resolveDaemonRuntime2(env, defaults) {
+ const cliOverride = env[OMO_LSP_DAEMON_CLI2];
+ const versionOverride = env[OMO_LSP_DAEMON_VERSION2];
+ const hasCliOverride = cliOverride !== undefined;
+ const hasVersionOverride = versionOverride !== undefined;
+ if (hasCliOverride !== hasVersionOverride) {
+ throw new InvalidRuntimeOverrideError2("paired_values_required", `${OMO_LSP_DAEMON_CLI2} and ${OMO_LSP_DAEMON_VERSION2} must be set together`);
+ }
+ if (!hasCliOverride || !hasVersionOverride) {
+ if (!isAbsolute4(defaults.cliPath)) {
+ throw new InvalidRuntimeOverrideError2("packaged_cli_must_be_absolute", "Packaged LSP daemon CLI path must be absolute");
+ }
+ return { cliPath: defaults.cliPath, version: validateDaemonVersion2(defaults.version) };
+ }
+ if (!isAbsolute4(cliOverride)) {
+ throw new InvalidRuntimeOverrideError2("cli_must_be_absolute", `${OMO_LSP_DAEMON_CLI2} must be an absolute path to an existing regular file`);
+ }
+ const stat = statSync5(cliOverride, { throwIfNoEntry: false });
+ if (!stat) {
+ throw new InvalidRuntimeOverrideError2("cli_not_found", `${OMO_LSP_DAEMON_CLI2} points to a missing file`);
+ }
+ if (!stat.isFile()) {
+ throw new InvalidRuntimeOverrideError2("cli_not_file", `${OMO_LSP_DAEMON_CLI2} must point to a regular file`);
+ }
+ return { cliPath: cliOverride, version: validateDaemonVersion2(versionOverride) };
+}
+function callDiagnosticsViaDaemon2(filePath, options) {
+ return callDiagnosticsViaDaemon(filePath, options);
+}
+
+// ../../../../lsp-core/src/post-edit/orchestration.ts
+import { extname as extname2 } from "node:path";
+var DEFAULT_MAX_CONCURRENCY = 4;
+var CLEAN_DIAGNOSTICS_TEXT = "No diagnostics found";
+function createPostEditNotConfiguredCache() {
+ return { notConfiguredExtensions: new Set };
+}
+async function collectPostEditDiagnostics(input) {
+ const cache = input.cache === undefined ? createPostEditNotConfiguredCache() : input.cache;
+ const filePaths = firstSeenDiagnosticTargets(input.filePaths, cache);
+ const results = await runBoundedDiagnostics(filePaths, input.runDiagnostics, input.maxConcurrency);
+ const blocks = [];
+ const observations = [];
+ for (const result of results) {
+ const classification = classifyDiagnostics(result.outcome);
+ switch (classification.kind) {
+ case "clean":
+ observations.push({ filePath: result.filePath, kind: "clean" });
+ break;
+ case "not_configured":
+ cache.notConfiguredExtensions.add(classification.extension);
+ observations.push({ filePath: result.filePath, kind: "not_configured" });
+ break;
+ case "block":
+ blocks.push({ filePath: result.filePath, diagnostics: classification.diagnostics });
+ observations.push({ filePath: result.filePath, kind: "block" });
+ break;
+ default: {
+ const exhaustive = classification;
+ return exhaustive;
+ }
+ }
+ }
+ return { blocks, observations };
+}
+function firstSeenDiagnosticTargets(filePaths, cache) {
+ const seen = new Set;
+ const targets = [];
+ for (const filePath of filePaths) {
+ if (filePath.length === 0 || seen.has(filePath))
+ continue;
+ seen.add(filePath);
+ const extension = extensionKey(filePath);
+ if (extension !== undefined && cache.notConfiguredExtensions.has(extension))
+ continue;
+ targets.push({ index: targets.length, filePath });
+ }
+ return targets;
+}
+async function runBoundedDiagnostics(filePaths, runDiagnostics, maxConcurrency) {
+ const results = [];
+ const workerCount = Math.min(Math.max(1, maxConcurrency ?? DEFAULT_MAX_CONCURRENCY), filePaths.length);
+ let nextIndex = 0;
+ async function worker() {
+ for (;; ) {
+ const target = filePaths[nextIndex];
+ nextIndex += 1;
+ if (target === undefined)
+ return;
+ results[target.index] = {
+ index: target.index,
+ filePath: target.filePath,
+ outcome: await collectFileDiagnostics(target.filePath, runDiagnostics)
+ };
+ }
+ }
+ await Promise.all(Array.from({ length: workerCount }, () => worker()));
+ return results.filter((result) => result !== undefined);
+}
+async function collectFileDiagnostics(filePath, runDiagnostics) {
+ try {
+ return normalizeDiagnosticsOutcome(await runDiagnostics(filePath));
+ } catch (error) {
+ if (error instanceof Error)
+ return formatDiagnosticsError(error);
+ return normalizeDiagnosticsText(String(error));
+ }
+}
+function normalizeDiagnosticsOutcome(outcome) {
+ if (typeof outcome === "string")
+ return normalizeDiagnosticsText(outcome);
+ return outcome;
+}
+function normalizeDiagnosticsText(text2) {
+ return text2.trim();
+}
+function formatDiagnosticsError(error) {
+ const message = normalizeDiagnosticsText(error.message);
+ return message.length > 0 ? message : normalizeDiagnosticsText(String(error));
+}
+function classifyDiagnostics(outcome) {
+ if (typeof outcome !== "string") {
+ return { kind: "not_configured", extension: outcome.extension };
+ }
+ const diagnostics = outcome;
+ if (diagnostics.length === 0 || diagnostics === CLEAN_DIAGNOSTICS_TEXT)
+ return { kind: "clean" };
+ return { kind: "block", diagnostics };
+}
+function extensionKey(filePath) {
+ const extension = extname2(filePath).toLowerCase();
+ return extension.length === 0 ? undefined : extension;
+}
+// ../../../../lsp-core/src/request-context.ts
+import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
+import { existsSync as existsSync11, realpathSync as realpathSync4, statSync as statSync6 } from "node:fs";
+import { basename as basename3, delimiter as delimiter4, dirname as dirname2, isAbsolute as isAbsolute5, join as join7, relative as relative5, resolve as resolve9 } from "node:path";
-// components/lsp/src/codex-hook.ts
-import { readFileSync as readFileSync9 } from "node:fs";
+class LspRequestContextParseError2 extends Error {
+ code;
+ name = "LspRequestContextParseError";
+ constructor(code, message) {
+ super(message);
+ this.code = code;
+ }
+}
+var storage2 = new AsyncLocalStorage2;
+var CONTEXT_FIELDS2 = new Set(["cwd", "projectConfigPaths", "userConfigPath", "installDecisionsPath", "capabilities"]);
+var CAPABILITY_FIELDS2 = new Set(["installDecisionTool"]);
+function parseLspRequestContext2(value) {
+ if (!isRecord7(value)) {
+ throw new LspRequestContextParseError2("invalid_context", "LSP request context must be an object.");
+ }
+ rejectUnknownFields2(value, CONTEXT_FIELDS2, "context");
+ const cwd = stringField2(value, "cwd");
+ const projectConfigPaths = stringArrayField2(value, "projectConfigPaths");
+ const userConfigPath = stringField2(value, "userConfigPath");
+ const installDecisionsPath = stringField2(value, "installDecisionsPath");
+ const capabilities = capabilitiesField2(value["capabilities"]);
+ const canonical = canonicalCwd2(cwd);
+ for (const path2 of projectConfigPaths) {
+ requireAbsolutePath2(path2, "projectConfigPaths");
+ const projectPath = canonicalizeExistingOrNearestAncestor2(path2);
+ if (!isPathInside2(canonical, projectPath)) {
+ throw new LspRequestContextParseError2("project_config_outside_cwd", `Project LSP config path must be inside cwd: ${path2}`);
+ }
+ }
+ requireAbsolutePath2(userConfigPath, "userConfigPath");
+ requireAbsolutePath2(installDecisionsPath, "installDecisionsPath");
+ return {
+ cwd: canonical,
+ projectConfigPaths: projectConfigPaths.map((path2) => canonicalizeExistingOrNearestAncestor2(path2)),
+ userConfigPath,
+ installDecisionsPath,
+ capabilities
+ };
+}
+function canonicalCwd2(cwd) {
+ const resolved = resolve9(cwd);
+ if (!existsSync11(resolved) || !statSync6(resolved).isDirectory()) {
+ throw new LspRequestContextParseError2("invalid_cwd", `LSP request cwd must be an existing directory: ${cwd}`);
+ }
+ return realpathSync4(resolved);
+}
+function canonicalizeExistingOrNearestAncestor2(path2) {
+ let current = resolve9(path2);
+ const suffix = [];
+ while (true) {
+ try {
+ const existing = realpathSync4(current);
+ return suffix.length === 0 ? existing : join7(existing, ...suffix);
+ } catch (error) {
+ if (!isMissingPathError2(error))
+ throw error;
+ const parent = dirname2(current);
+ if (parent === current)
+ throw error;
+ suffix.unshift(basename3(current));
+ current = parent;
+ }
+ }
+}
+function capabilitiesField2(value) {
+ if (!isRecord7(value)) {
+ throw new LspRequestContextParseError2("invalid_capabilities", "LSP request capabilities must be an object.");
+ }
+ rejectUnknownFields2(value, CAPABILITY_FIELDS2, "capabilities");
+ const installDecisionTool = value["installDecisionTool"];
+ if (typeof installDecisionTool !== "boolean") {
+ throw new LspRequestContextParseError2("invalid_install_decision_capability", "LSP request capabilities.installDecisionTool must be a boolean.");
+ }
+ return { installDecisionTool };
+}
+function stringField2(value, field) {
+ const fieldValue = value[field];
+ if (typeof fieldValue !== "string" || fieldValue.length === 0) {
+ throw new LspRequestContextParseError2("invalid_field", `LSP request context.${field} must be a non-empty string.`);
+ }
+ return fieldValue;
+}
+function stringArrayField2(value, field) {
+ const fieldValue = value[field];
+ if (!Array.isArray(fieldValue) || !fieldValue.every((item) => typeof item === "string" && item.length > 0)) {
+ throw new LspRequestContextParseError2("invalid_field", `LSP request context.${field} must be a non-empty string array.`);
+ }
+ return fieldValue;
+}
+function requireAbsolutePath2(path2, field) {
+ if (!isAbsolute5(path2)) {
+ throw new LspRequestContextParseError2("relative_path", `LSP request context.${field} must be absolute: ${path2}`);
+ }
+}
+function isPathInside2(parent, child) {
+ const childPath = resolve9(child);
+ const relativePath = relative5(parent, childPath);
+ return relativePath === "" || !relativePath.startsWith("..") && !isAbsolute5(relativePath);
+}
+function isMissingPathError2(error) {
+ const code = errorCode2(error);
+ return code === "ENOENT" || code === "ENOTDIR";
+}
+function rejectUnknownFields2(value, allowed, scope) {
+ const unknown = Object.keys(value).filter((key) => !allowed.has(key));
+ if (unknown.length > 0) {
+ throw new LspRequestContextParseError2("unknown_field", `Unknown LSP request ${scope} field: ${unknown.join(", ")}`);
+ }
+}
+function isRecord7(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function errorCode2(error) {
+ if (!error || typeof error !== "object" || !("code" in error))
+ return;
+ const code = Reflect.get(error, "code");
+ return typeof code === "string" ? code : undefined;
+}
-// components/lsp/src/daemon-cli-path.ts
-import { existsSync as existsSync9, readFileSync as readFileSync6 } from "node:fs";
+// src/daemon-cli-path.ts
+import { existsSync as existsSync13, readFileSync as readFileSync6 } from "node:fs";
import { createRequire as createRequire2 } from "node:module";
-import { dirname as dirname6, join as join9 } from "node:path";
+import { dirname as dirname9, join as join9 } from "node:path";
import { fileURLToPath as fileURLToPath4 } from "node:url";
var requireFromHere2 = createRequire2(import.meta.url);
-var PACKAGE_LSP_DAEMON_CLI = "@code-yeongyu/lsp-daemon/dist/cli.js";
-var CODEX_LSP_DAEMON_CLI_ENV2 = "CODEX_LSP_DAEMON_CLI";
-var CODEX_LSP_DAEMON_VERSION_ENV2 = "CODEX_LSP_DAEMON_VERSION";
+var PACKAGE_LSP_DAEMON_CLI = "@code-yeongyu/lsp-daemon/cli";
function ensureLspDaemonCliEnv(env = process.env) {
- const configuredCli = env[CODEX_LSP_DAEMON_CLI_ENV2]?.trim();
- const resolution = configuredCli ? resolveConfiguredLspDaemonCli(configuredCli) : resolveLspDaemonCli();
- if (!configuredCli)
- env[CODEX_LSP_DAEMON_CLI_ENV2] = resolution.cliPath;
- if (!env[CODEX_LSP_DAEMON_VERSION_ENV2]?.trim() && resolution.version !== null) {
- env[CODEX_LSP_DAEMON_VERSION_ENV2] = resolution.version;
- }
-}
-function resolveLspDaemonCliPath() {
- return resolveLspDaemonCli().cliPath;
+ const runtime = resolveDaemonRuntime2(env, resolveLspDaemonCli());
+ env[OMO_LSP_DAEMON_CLI2] = runtime.cliPath;
+ env[OMO_LSP_DAEMON_VERSION2] = runtime.version;
+}
+function resolveLspDaemonCliPath(env = process.env) {
+ const runtime = resolveDaemonRuntime2(env, resolveLspDaemonCli());
+ if (env[OMO_LSP_DAEMON_CLI2] === undefined)
+ env[OMO_LSP_DAEMON_CLI2] = runtime.cliPath;
+ if (env[OMO_LSP_DAEMON_VERSION2] === undefined)
+ env[OMO_LSP_DAEMON_VERSION2] = runtime.version;
+ return runtime.cliPath;
}
function resolveLspDaemonCli() {
const packageCli = resolvePackageLspDaemonCliPath();
if (packageCli !== null)
return resolveConfiguredLspDaemonCli(packageCli);
const bundledCli = fileURLToPath4(new URL("../../lsp-daemon/dist/cli.js", import.meta.url));
- if (existsSync9(bundledCli))
+ if (existsSync13(bundledCli))
return resolveConfiguredLspDaemonCli(bundledCli);
return resolveConfiguredLspDaemonCli(bundledCli);
}
function resolvePackageLspDaemonCliPath() {
try {
return requireFromHere2.resolve(PACKAGE_LSP_DAEMON_CLI);
- } catch {
+ } catch (error) {
+ if (!(error instanceof Error))
+ throw error;
return null;
}
}
function resolveConfiguredLspDaemonCli(cliPath) {
+ const version = readDaemonPackageVersion(cliPath);
+ if (version === null) {
+ throw new Error(`Unable to determine packaged LSP daemon version beside ${cliPath}`);
+ }
return {
cliPath,
- version: readDaemonPackageVersion(cliPath)
+ version
};
}
function readDaemonPackageVersion(cliPath) {
try {
- const parsed = JSON.parse(readFileSync6(join9(dirname6(cliPath), "package.json"), "utf8"));
- if (isRecord4(parsed) && typeof parsed["version"] === "string" && parsed["version"].length > 0) {
+ const parsed = JSON.parse(readFileSync6(join9(dirname9(cliPath), "package.json"), "utf8"));
+ if (isRecord9(parsed) && typeof parsed["version"] === "string" && parsed["version"].length > 0) {
return parsed["version"];
}
- } catch {}
+ } catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ }
return null;
}
-function isRecord4(value) {
+function isRecord9(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
-// components/lsp/src/lsp-session-state.ts
+// src/lsp-session-state.ts
import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "node:fs";
-import { homedir as homedir4 } from "node:os";
-import { dirname as dirname8, extname as extname2, join as join11 } from "node:path";
+import { homedir } from "node:os";
+import { dirname as dirname11, join as join10 } from "node:path";
function sessionIdFrom(input) {
return typeof input.session_id === "string" && input.session_id.length > 0 ? input.session_id : undefined;
}
-function shouldSkipUnavailableLspDiagnostics(filePath, sessionId) {
+function readLspPostEditCache(sessionId) {
if (sessionId === undefined)
- return false;
- const state = readSessionState(sessionStatePath(sessionId));
- const extension = extensionKey(filePath);
- return extension !== undefined && state.postCompactProbePending !== true && state.unavailableExtensions.includes(extension);
-}
-function recordLspDiagnosticsObservations(sessionId, observations) {
- if (sessionId === undefined || observations.length === 0)
- return;
+ return { notConfiguredExtensions: new Set };
const state = readSessionState(sessionStatePath(sessionId));
- const unavailableExtensions = new Set(state.unavailableExtensions);
- for (const observation of observations) {
- const extension = extensionKey(observation.filePath);
- if (extension === undefined)
- continue;
- if (observation.unavailable) {
- unavailableExtensions.add(extension);
- } else {
- unavailableExtensions.delete(extension);
- }
- }
- writeSessionState(sessionStatePath(sessionId), { unavailableExtensions: [...unavailableExtensions].sort() });
+ return { notConfiguredExtensions: new Set(state.notConfiguredExtensions) };
}
-function markLspSessionCompacted(sessionId) {
+function writeLspPostEditCache(sessionId, cache) {
if (sessionId === undefined)
return;
- const state = readSessionState(sessionStatePath(sessionId));
- if (state.unavailableExtensions.length === 0)
- return;
writeSessionState(sessionStatePath(sessionId), {
- unavailableExtensions: state.unavailableExtensions,
- postCompactProbePending: true
+ notConfiguredExtensions: [...cache.notConfiguredExtensions].sort()
});
}
-function isUnavailableLspDiagnostics(diagnostics) {
- const normalized = diagnostics.trim();
- return normalized.includes("LSP request timeout (method: initialize)") || normalized.includes("LSP server is still initializing") || normalized.includes("NOT INSTALLED") || normalized.includes("Command not found:");
+function markLspSessionCompacted(sessionId) {
+ if (sessionId === undefined)
+ return;
+ writeSessionState(sessionStatePath(sessionId), emptyState());
}
function isLspDaemonUnreachableDiagnostics(diagnostics) {
return diagnostics.includes("LSP daemon unreachable");
}
function sessionStatePath(sessionId) {
- const root = process.env["PLUGIN_DATA"] ?? join11(homedir4(), ".codex", "codex-lsp");
- return join11(root, "sessions", `${safePathSegment(sessionId)}.json`);
+ const root = process.env["PLUGIN_DATA"] ?? join10(homedir(), ".codex", "codex-lsp");
+ return join10(root, "sessions", `${safePathSegment(sessionId)}.json`);
}
-function readSessionState(path) {
+function readSessionState(path2) {
try {
- const parsed = JSON.parse(readFileSync8(path, "utf8"));
- if (isLspSessionState(parsed))
- return parsed;
+ const parsed = JSON.parse(readFileSync8(path2, "utf8"));
+ if (isRecord10(parsed) && isLspSessionState(parsed))
+ return normalizeSessionState(parsed);
return emptyState();
} catch (error) {
- if (error instanceof SyntaxError || isRecord6(error) && error["code"] === "ENOENT")
+ if (error instanceof SyntaxError || isRecord10(error) && error["code"] === "ENOENT")
return emptyState();
throw error;
}
}
-function writeSessionState(path, state) {
- mkdirSync4(dirname8(path), { recursive: true });
- writeFileSync3(path, `${JSON.stringify(state)}
+function writeSessionState(path2, state) {
+ mkdirSync4(dirname11(path2), { recursive: true });
+ writeFileSync3(path2, `${JSON.stringify(state)}
`);
}
function emptyState() {
- return { unavailableExtensions: [] };
-}
-function extensionKey(filePath) {
- const extension = extname2(filePath).toLowerCase();
- return extension.length === 0 ? undefined : extension;
+ return { notConfiguredExtensions: [] };
}
function safePathSegment(value) {
return value.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 120) || "unknown-session";
}
function isLspSessionState(value) {
- if (!isRecord6(value) || !Array.isArray(value["unavailableExtensions"]))
- return false;
- const postCompactProbePending = value["postCompactProbePending"];
- return value["unavailableExtensions"].every((item) => typeof item === "string") && (postCompactProbePending === undefined || typeof postCompactProbePending === "boolean");
+ const notConfiguredExtensions = value["notConfiguredExtensions"] ?? value["unavailableExtensions"];
+ return Array.isArray(notConfiguredExtensions) && notConfiguredExtensions.every((item) => typeof item === "string");
}
-function isRecord6(value) {
+function normalizeSessionState(value) {
+ const notConfiguredExtensions = value["notConfiguredExtensions"] ?? value["unavailableExtensions"];
+ return {
+ notConfiguredExtensions: Array.isArray(notConfiguredExtensions) ? notConfiguredExtensions.filter((item) => typeof item === "string").sort() : []
+ };
+}
+function isRecord10(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
-// components/lsp/src/mutated-file-paths.ts
+// src/mutated-file-paths.ts
var MUTATION_TOOL_NAMES = new Set(["apply_patch", "write", "edit", "multiedit", "multi_edit"]);
function extractMutatedFilePaths(input) {
if (!isMutationTool(input.tool_name))
return [];
if (isFailedToolResponse(input.tool_response))
return [];
- const toolInput = isRecord7(input.tool_input) ? input.tool_input : {};
+ const toolInput = isRecord11(input.tool_input) ? input.tool_input : {};
const paths = new Set;
addStringValue(paths, toolInput["path"]);
addStringValue(paths, toolInput["filePath"]);
@@ -3506,7 +5545,7 @@ function isMutationTool(value) {
return MUTATION_TOOL_NAMES.has(value.toLowerCase());
}
function isFailedToolResponse(value) {
- if (!isRecord7(value))
+ if (!isRecord11(value))
return false;
return value["isError"] === true || value["is_error"] === true || value["error"] === true || value["status"] === "error";
}
@@ -3532,9 +5571,9 @@ function addPatchInput(paths, value) {
return;
for (const line of value.split(`
`)) {
- const path = extractPatchHeaderPath(line);
- if (path !== undefined)
- paths.add(path);
+ const path2 = extractPatchHeaderPath(line);
+ if (path2 !== undefined)
+ paths.add(path2);
}
}
function extractPatchHeaderPath(line) {
@@ -3549,7 +5588,7 @@ function addPatchFiles(paths, value) {
if (!Array.isArray(value))
return;
for (const item of value) {
- if (!isRecord7(item))
+ if (!isRecord11(item))
continue;
addStringValue(paths, item["path"]);
addStringValue(paths, item["filePath"]);
@@ -3558,18 +5597,15 @@ function addPatchFiles(paths, value) {
addStringValue(paths, item["move_path"]);
}
}
-function isRecord7(value) {
+function isRecord11(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
-// components/lsp/src/codex-hook.ts
-var CLEAN_DIAGNOSTICS_TEXT = "No diagnostics found";
-var UNSUPPORTED_EXTENSION_TEXT = "No LSP server configured for extension:";
+// src/codex-hook.ts
var DIAGNOSTIC_START_PATTERN = /(?:error|warning|information|hint)\[[^\]\r\n]+\] \(\d+\) at \d+:\d+:/g;
var DIAGNOSTIC_CHUNK_PATTERN = /^(?:error|warning|information|hint)\[[^\]\r\n]+\] \(\d+\) at \d+:\d+:/;
var DEFAULT_MAX_HOOK_FEEDBACK_CHARS = 8000;
var CONTEXT_PRESSURE_MAX_HOOK_FEEDBACK_CHARS = 1200;
-var MAX_CONCURRENT_DIAGNOSTICS = 4;
var CONTEXT_PRESSURE_MARKERS = [
"context compacted",
"context_length_exceeded",
@@ -3581,29 +5617,47 @@ var CONTEXT_PRESSURE_MARKERS = [
];
async function runLspDiagnosticsText(filePath) {
ensureLspDaemonCliEnv();
- const result = await callDiagnosticsViaDaemon(filePath, { context: currentRequestContext() });
+ const result = await callDiagnosticsViaDaemon2(filePath, { context: codexLspRequestContext() });
+ return postEditOutcomeFromDaemonResult(result);
+}
+function postEditOutcomeFromDaemonResult(result) {
+ const availability = notConfiguredAvailability(result.details);
+ if (availability !== undefined)
+ return { kind: "not_configured", extension: availability.extension };
return result.content.map((block) => block.text).join(`
`);
}
+function notConfiguredAvailability(details) {
+ if (!isRecord12(details))
+ return;
+ const availability = details["availability"];
+ if (!isRecord12(availability))
+ return;
+ if (availability["kind"] !== "not_configured")
+ return;
+ const extension = availability["extension"];
+ return typeof extension === "string" && extension.length > 0 ? { extension } : undefined;
+}
+function codexLspRequestContext(env = process.env, cwd = process.cwd()) {
+ const canonicalCwd3 = realpathSync6(resolve11(cwd));
+ const codexHome = resolve11(env["CODEX_HOME"]?.trim() || join11(homedir3(), ".codex"));
+ return parseLspRequestContext2({
+ cwd: canonicalCwd3,
+ projectConfigPaths: [join11(canonicalCwd3, ".codex", "lsp-client.json")],
+ userConfigPath: join11(codexHome, "lsp-client.json"),
+ installDecisionsPath: join11(codexHome, "lsp-install-decisions.json"),
+ capabilities: { installDecisionTool: true }
+ });
+}
async function runLspPostToolUseHook(input, runDiagnostics = runLspDiagnosticsText) {
const sessionId = sessionIdFrom(input);
- const filePaths = extractMutatedFilePaths(input).filter((filePath) => !shouldSkipUnavailableLspDiagnostics(filePath, sessionId));
+ const filePaths = extractMutatedFilePaths(input);
if (filePaths.length === 0)
return "";
- const blocks = [];
- const observations = [];
- for (const { filePath, diagnostics } of await collectDiagnostics(filePaths, runDiagnostics)) {
- if (isLspDaemonUnreachableDiagnostics(diagnostics))
- continue;
- const unavailable = isUnavailableLspDiagnostics(diagnostics);
- observations.push({ filePath, unavailable });
- if (isCleanDiagnostics(diagnostics))
- continue;
- if (unavailable)
- continue;
- blocks.push({ filePath, diagnostics });
- }
- recordLspDiagnosticsObservations(sessionId, observations);
+ const cache = readLspPostEditCache(sessionId);
+ const result = await collectPostEditDiagnostics({ filePaths, runDiagnostics, cache });
+ writeLspPostEditCache(sessionId, cache);
+ const blocks = result.blocks.filter(({ diagnostics }) => !isLspDaemonUnreachableDiagnostics(diagnostics));
if (blocks.length === 0)
return "";
const rawReason = blocks.map(formatDiagnosticBlock).join(`
@@ -3625,38 +5679,6 @@ async function runLspPostCompactHook(input) {
markLspSessionCompacted(sessionIdFrom(input));
return "";
}
-async function collectDiagnostics(filePaths, runDiagnostics) {
- const results = [];
- let nextIndex = 0;
- const workerCount = Math.min(MAX_CONCURRENT_DIAGNOSTICS, filePaths.length);
- async function worker() {
- for (;; ) {
- const index = nextIndex;
- nextIndex += 1;
- const filePath = filePaths[index];
- if (filePath === undefined)
- return;
- results[index] = { filePath, diagnostics: await collectFileDiagnostics(filePath, runDiagnostics) };
- }
- }
- await Promise.all(Array.from({ length: workerCount }, () => worker()));
- return results;
-}
-async function collectFileDiagnostics(filePath, runDiagnostics) {
- try {
- return (await runDiagnostics(filePath)).trim();
- } catch (error) {
- return formatDiagnosticsError(error);
- }
-}
-function formatDiagnosticsError(error) {
- if (error instanceof Error) {
- const message = error.message.trim();
- if (message.length > 0)
- return message;
- }
- return String(error).trim();
-}
function formatDiagnosticBlock({ filePath, diagnostics }) {
return `LSP diagnostics after editing ${filePath}:
@@ -3739,14 +5761,11 @@ function limitHookText(text2, maxChars) {
const head = text2.slice(0, maxChars - marker.length).replace(/[ \t\r\n]+$/, "");
return `${head}${marker}`;
}
-function isCleanDiagnostics(diagnostics) {
- return diagnostics.length === 0 || diagnostics === CLEAN_DIAGNOSTICS_TEXT || diagnostics.startsWith(UNSUPPORTED_EXTENSION_TEXT);
-}
-function isRecord8(value) {
+function isRecord12(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
-// components/lsp/src/codex-hook-cli.ts
+// src/codex-hook-cli.ts
async function runPostToolUseHookCli(stdin = processStdin) {
await runHookCli((input) => runLspPostToolUseHook(input), stdin);
}
@@ -3759,16 +5778,12 @@ async function runHookCli(runHook, stdin) {
if (!raw.trim())
return;
const parsed = JSON.parse(raw);
- const input = isRecord8(parsed) ? parsed : {};
+ const input = isRecord12(parsed) ? parsed : {};
const output = await runHook(input);
if (output)
process.stdout.write(output);
} catch {
return;
- } finally {
- await disposeDefaultLspManager().catch(() => {
- return;
- });
}
}
async function readStdin(stdin) {
@@ -3780,7 +5795,7 @@ async function readStdin(stdin) {
return raw;
}
-// components/lsp/src/cli.ts
+// src/cli.ts
async function main() {
const [command = "mcp", subcommand = ""] = argv.slice(2);
if (command === "hook" && subcommand === "post-tool-use") {
@@ -3807,14 +5822,14 @@ main().catch((error) => {
async function runPackageLspMcpCli() {
const cliPath = resolveLspDaemonCliPath();
const child = spawn3(execPath2, [cliPath, "mcp"], { stdio: "inherit" });
- await new Promise((resolve6, reject) => {
+ await new Promise((resolve10, reject) => {
child.once("error", reject);
child.once("exit", (code, signal) => {
if (code !== null && code !== 0)
process.exitCode = code;
if (code === null && signal !== null)
process.exitCode = 1;
- resolve6();
+ resolve10();
});
});
}
diff --git a/plugins/omo/components/lsp/dist/codex-hook-cli.js b/plugins/omo/components/lsp/dist/codex-hook-cli.js
index 57b88c40..7386687c 100644
--- a/plugins/omo/components/lsp/dist/codex-hook-cli.js
+++ b/plugins/omo/components/lsp/dist/codex-hook-cli.js
@@ -1,5 +1,4 @@
import { stdin as processStdin } from "node:process";
-import { disposeDefaultLspManager } from "@code-yeongyu/lsp-daemon";
import { isRecord, runLspPostCompactHook, runLspPostToolUseHook } from "./codex-hook.js";
export async function runPostToolUseHookCli(stdin = processStdin) {
await runHookCli((input) => runLspPostToolUseHook(input), stdin);
@@ -22,9 +21,6 @@ async function runHookCli(runHook, stdin) {
// LSP feedback is best-effort: stderr or a non-zero exit here surfaces as harness noise on every edit.
return;
}
- finally {
- await disposeDefaultLspManager().catch(() => undefined);
- }
}
async function readStdin(stdin) {
stdin.setEncoding("utf8");
diff --git a/plugins/omo/components/lsp/dist/codex-hook.d.ts b/plugins/omo/components/lsp/dist/codex-hook.d.ts
index 5da31a2b..cd3a48f2 100644
--- a/plugins/omo/components/lsp/dist/codex-hook.d.ts
+++ b/plugins/omo/components/lsp/dist/codex-hook.d.ts
@@ -1,5 +1,7 @@
+import { type PostEditDiagnosticsOutcome } from "@oh-my-opencode/lsp-core/post-edit";
+import { type LspRequestContext } from "@oh-my-opencode/lsp-core/request-context";
export { extractMutatedFilePaths } from "./mutated-file-paths.js";
-export type DiagnosticsRunner = (filePath: string) => Promise<string>;
+export type DiagnosticsRunner = (filePath: string) => Promise<PostEditDiagnosticsOutcome>;
export interface CodexPostToolUseInput {
session_id?: unknown;
tool_name?: unknown;
@@ -10,7 +12,8 @@ export interface CodexPostToolUseInput {
export interface CodexPostCompactInput {
session_id?: unknown;
}
-export declare function runLspDiagnosticsText(filePath: string): Promise<string>;
+export declare function runLspDiagnosticsText(filePath: string): Promise<PostEditDiagnosticsOutcome>;
+export declare function codexLspRequestContext(env?: Record<string, string | undefined>, cwd?: string): LspRequestContext;
export declare function runLspPostToolUseHook(input: CodexPostToolUseInput, runDiagnostics?: DiagnosticsRunner): Promise<string>;
export declare function runLspPostCompactHook(input: CodexPostCompactInput): Promise<string>;
export declare function isRecord(value: unknown): value is Record<string, unknown>;
diff --git a/plugins/omo/components/lsp/dist/codex-hook.js b/plugins/omo/components/lsp/dist/codex-hook.js
index 509bc2da..f5fdc2ee 100644
--- a/plugins/omo/components/lsp/dist/codex-hook.js
+++ b/plugins/omo/components/lsp/dist/codex-hook.js
@@ -1,16 +1,17 @@
-import { readFileSync } from "node:fs";
-import { callDiagnosticsViaDaemon, currentRequestContext } from "@code-yeongyu/lsp-daemon";
+import { readFileSync, realpathSync } from "node:fs";
+import { homedir } from "node:os";
+import { join, resolve } from "node:path";
+import { callDiagnosticsViaDaemon } from "@code-yeongyu/lsp-daemon/client";
+import { collectPostEditDiagnostics } from "@oh-my-opencode/lsp-core/post-edit";
+import { parseLspRequestContext } from "@oh-my-opencode/lsp-core/request-context";
import { ensureLspDaemonCliEnv } from "./daemon-cli-path.js";
-import { isLspDaemonUnreachableDiagnostics, isUnavailableLspDiagnostics, markLspSessionCompacted, recordLspDiagnosticsObservations, sessionIdFrom, shouldSkipUnavailableLspDiagnostics, } from "./lsp-session-state.js";
+import { isLspDaemonUnreachableDiagnostics, markLspSessionCompacted, readLspPostEditCache, sessionIdFrom, writeLspPostEditCache, } from "./lsp-session-state.js";
import { extractMutatedFilePaths } from "./mutated-file-paths.js";
export { extractMutatedFilePaths } from "./mutated-file-paths.js";
-const CLEAN_DIAGNOSTICS_TEXT = "No diagnostics found";
-const UNSUPPORTED_EXTENSION_TEXT = "No LSP server configured for extension:";
const DIAGNOSTIC_START_PATTERN = /(?:error|warning|information|hint)\[[^\]\r\n]+\] \(\d+\) at \d+:\d+:/g;
const DIAGNOSTIC_CHUNK_PATTERN = /^(?:error|warning|information|hint)\[[^\]\r\n]+\] \(\d+\) at \d+:\d+:/;
const DEFAULT_MAX_HOOK_FEEDBACK_CHARS = 8000;
const CONTEXT_PRESSURE_MAX_HOOK_FEEDBACK_CHARS = 1200;
-const MAX_CONCURRENT_DIAGNOSTICS = 4;
const CONTEXT_PRESSURE_MARKERS = [
"context compacted",
"context_length_exceeded",
@@ -22,30 +23,46 @@ const CONTEXT_PRESSURE_MARKERS = [
];
export async function runLspDiagnosticsText(filePath) {
ensureLspDaemonCliEnv();
- const result = await callDiagnosticsViaDaemon(filePath, { context: currentRequestContext() });
+ const result = await callDiagnosticsViaDaemon(filePath, { context: codexLspRequestContext() });
+ return postEditOutcomeFromDaemonResult(result);
+}
+function postEditOutcomeFromDaemonResult(result) {
+ const availability = notConfiguredAvailability(result.details);
+ if (availability !== undefined)
+ return { kind: "not_configured", extension: availability.extension };
return result.content.map((block) => block.text).join("\n");
}
+function notConfiguredAvailability(details) {
+ if (!isRecord(details))
+ return undefined;
+ const availability = details["availability"];
+ if (!isRecord(availability))
+ return undefined;
+ if (availability["kind"] !== "not_configured")
+ return undefined;
+ const extension = availability["extension"];
+ return typeof extension === "string" && extension.length > 0 ? { extension } : undefined;
+}
+export function codexLspRequestContext(env = process.env, cwd = process.cwd()) {
+ const canonicalCwd = realpathSync(resolve(cwd));
+ const codexHome = resolve(env["CODEX_HOME"]?.trim() || join(homedir(), ".codex"));
+ return parseLspRequestContext({
+ cwd: canonicalCwd,
+ projectConfigPaths: [join(canonicalCwd, ".codex", "lsp-client.json")],
+ userConfigPath: join(codexHome, "lsp-client.json"),
+ installDecisionsPath: join(codexHome, "lsp-install-decisions.json"),
+ capabilities: { installDecisionTool: true },
+ });
+}
export async function runLspPostToolUseHook(input, runDiagnostics = runLspDiagnosticsText) {
const sessionId = sessionIdFrom(input);
- const filePaths = extractMutatedFilePaths(input).filter((filePath) => !shouldSkipUnavailableLspDiagnostics(filePath, sessionId));
+ const filePaths = extractMutatedFilePaths(input);
if (filePaths.length === 0)
return "";
- const blocks = [];
- const observations = [];
- for (const { filePath, diagnostics } of await collectDiagnostics(filePaths, runDiagnostics)) {
- // A daemon outage is transient (connect-or-spawn retries on the next request);
- // recording it would silence this extension for the rest of the session.
- if (isLspDaemonUnreachableDiagnostics(diagnostics))
- continue;
- const unavailable = isUnavailableLspDiagnostics(diagnostics);
- observations.push({ filePath, unavailable });
- if (isCleanDiagnostics(diagnostics))
- continue;
- if (unavailable)
- continue;
- blocks.push({ filePath, diagnostics });
- }
- recordLspDiagnosticsObservations(sessionId, observations);
+ const cache = readLspPostEditCache(sessionId);
+ const result = await collectPostEditDiagnostics({ filePaths, runDiagnostics, cache });
+ writeLspPostEditCache(sessionId, cache);
+ const blocks = result.blocks.filter(({ diagnostics }) => !isLspDaemonUnreachableDiagnostics(diagnostics));
if (blocks.length === 0)
return "";
const rawReason = blocks.map(formatDiagnosticBlock).join("\n\n");
@@ -64,39 +81,6 @@ export async function runLspPostCompactHook(input) {
markLspSessionCompacted(sessionIdFrom(input));
return "";
}
-async function collectDiagnostics(filePaths, runDiagnostics) {
- const results = [];
- let nextIndex = 0;
- const workerCount = Math.min(MAX_CONCURRENT_DIAGNOSTICS, filePaths.length);
- async function worker() {
- for (;;) {
- const index = nextIndex;
- nextIndex += 1;
- const filePath = filePaths[index];
- if (filePath === undefined)
- return;
- results[index] = { filePath, diagnostics: await collectFileDiagnostics(filePath, runDiagnostics) };
- }
- }
- await Promise.all(Array.from({ length: workerCount }, () => worker()));
- return results;
-}
-async function collectFileDiagnostics(filePath, runDiagnostics) {
- try {
- return (await runDiagnostics(filePath)).trim();
- }
- catch (error) {
- return formatDiagnosticsError(error);
- }
-}
-function formatDiagnosticsError(error) {
- if (error instanceof Error) {
- const message = error.message.trim();
- if (message.length > 0)
- return message;
- }
- return String(error).trim();
-}
function formatDiagnosticBlock({ filePath, diagnostics }) {
return `LSP diagnostics after editing ${filePath}:\n\n${formatDiagnosticsForDisplay(diagnostics)}`;
}
@@ -172,11 +156,6 @@ function limitHookText(text, maxChars) {
const head = text.slice(0, maxChars - marker.length).replace(/[ \t\r\n]+$/, "");
return `${head}${marker}`;
}
-function isCleanDiagnostics(diagnostics) {
- return (diagnostics.length === 0 ||
- diagnostics === CLEAN_DIAGNOSTICS_TEXT ||
- diagnostics.startsWith(UNSUPPORTED_EXTENSION_TEXT));
-}
export function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
diff --git a/plugins/omo/components/lsp/dist/daemon-cli-path.d.ts b/plugins/omo/components/lsp/dist/daemon-cli-path.d.ts
index e11de5fd..3a0748a9 100644
--- a/plugins/omo/components/lsp/dist/daemon-cli-path.d.ts
+++ b/plugins/omo/components/lsp/dist/daemon-cli-path.d.ts
@@ -1,2 +1,2 @@
export declare function ensureLspDaemonCliEnv(env?: NodeJS.ProcessEnv): void;
-export declare function resolveLspDaemonCliPath(): string;
+export declare function resolveLspDaemonCliPath(env?: NodeJS.ProcessEnv): string;
diff --git a/plugins/omo/components/lsp/dist/daemon-cli-path.js b/plugins/omo/components/lsp/dist/daemon-cli-path.js
index dae8dcc1..f42a3adc 100644
--- a/plugins/omo/components/lsp/dist/daemon-cli-path.js
+++ b/plugins/omo/components/lsp/dist/daemon-cli-path.js
@@ -2,21 +2,21 @@ import { existsSync, readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
+import { OMO_LSP_DAEMON_CLI, OMO_LSP_DAEMON_VERSION, resolveDaemonRuntime, } from "@code-yeongyu/lsp-daemon/client";
const requireFromHere = createRequire(import.meta.url);
-const PACKAGE_LSP_DAEMON_CLI = "@code-yeongyu/lsp-daemon/dist/cli.js";
-const CODEX_LSP_DAEMON_CLI_ENV = "CODEX_LSP_DAEMON_CLI";
-const CODEX_LSP_DAEMON_VERSION_ENV = "CODEX_LSP_DAEMON_VERSION";
+const PACKAGE_LSP_DAEMON_CLI = "@code-yeongyu/lsp-daemon/cli";
export function ensureLspDaemonCliEnv(env = process.env) {
- const configuredCli = env[CODEX_LSP_DAEMON_CLI_ENV]?.trim();
- const resolution = configuredCli ? resolveConfiguredLspDaemonCli(configuredCli) : resolveLspDaemonCli();
- if (!configuredCli)
- env[CODEX_LSP_DAEMON_CLI_ENV] = resolution.cliPath;
- if (!env[CODEX_LSP_DAEMON_VERSION_ENV]?.trim() && resolution.version !== null) {
- env[CODEX_LSP_DAEMON_VERSION_ENV] = resolution.version;
- }
+ const runtime = resolveDaemonRuntime(env, resolveLspDaemonCli());
+ env[OMO_LSP_DAEMON_CLI] = runtime.cliPath;
+ env[OMO_LSP_DAEMON_VERSION] = runtime.version;
}
-export function resolveLspDaemonCliPath() {
- return resolveLspDaemonCli().cliPath;
+export function resolveLspDaemonCliPath(env = process.env) {
+ const runtime = resolveDaemonRuntime(env, resolveLspDaemonCli());
+ if (env[OMO_LSP_DAEMON_CLI] === undefined)
+ env[OMO_LSP_DAEMON_CLI] = runtime.cliPath;
+ if (env[OMO_LSP_DAEMON_VERSION] === undefined)
+ env[OMO_LSP_DAEMON_VERSION] = runtime.version;
+ return runtime.cliPath;
}
function resolveLspDaemonCli() {
const packageCli = resolvePackageLspDaemonCliPath();
@@ -31,14 +31,20 @@ function resolvePackageLspDaemonCliPath() {
try {
return requireFromHere.resolve(PACKAGE_LSP_DAEMON_CLI);
}
- catch {
+ catch (error) {
+ if (!(error instanceof Error))
+ throw error;
return null;
}
}
function resolveConfiguredLspDaemonCli(cliPath) {
+ const version = readDaemonPackageVersion(cliPath);
+ if (version === null) {
+ throw new Error(`Unable to determine packaged LSP daemon version beside ${cliPath}`);
+ }
return {
cliPath,
- version: readDaemonPackageVersion(cliPath),
+ version,
};
}
function readDaemonPackageVersion(cliPath) {
@@ -48,7 +54,10 @@ function readDaemonPackageVersion(cliPath) {
return parsed["version"];
}
}
- catch { }
+ catch (error) {
+ if (!(error instanceof Error))
+ throw error;
+ }
return null;
}
function isRecord(value) {
diff --git a/plugins/omo/components/lsp/dist/lsp-session-state.d.ts b/plugins/omo/components/lsp/dist/lsp-session-state.d.ts
index 8ad926d9..9718ef6b 100644
--- a/plugins/omo/components/lsp/dist/lsp-session-state.d.ts
+++ b/plugins/omo/components/lsp/dist/lsp-session-state.d.ts
@@ -1,12 +1,8 @@
-export interface DiagnosticsObservation {
- readonly filePath: string;
- readonly unavailable: boolean;
-}
+import type { PostEditNotConfiguredCache } from "@oh-my-opencode/lsp-core/post-edit";
export declare function sessionIdFrom(input: {
readonly session_id?: unknown;
}): string | undefined;
-export declare function shouldSkipUnavailableLspDiagnostics(filePath: string, sessionId: string | undefined): boolean;
-export declare function recordLspDiagnosticsObservations(sessionId: string | undefined, observations: readonly DiagnosticsObservation[]): void;
+export declare function readLspPostEditCache(sessionId: string | undefined): PostEditNotConfiguredCache;
+export declare function writeLspPostEditCache(sessionId: string | undefined, cache: PostEditNotConfiguredCache): void;
export declare function markLspSessionCompacted(sessionId: string | undefined): void;
-export declare function isUnavailableLspDiagnostics(diagnostics: string): boolean;
export declare function isLspDaemonUnreachableDiagnostics(diagnostics: string): boolean;
diff --git a/plugins/omo/components/lsp/dist/lsp-session-state.js b/plugins/omo/components/lsp/dist/lsp-session-state.js
index 98bcb6a2..c3ec1bd1 100644
--- a/plugins/omo/components/lsp/dist/lsp-session-state.js
+++ b/plugins/omo/components/lsp/dist/lsp-session-state.js
@@ -1,53 +1,26 @@
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
-import { dirname, extname, join } from "node:path";
+import { dirname, join } from "node:path";
export function sessionIdFrom(input) {
return typeof input.session_id === "string" && input.session_id.length > 0 ? input.session_id : undefined;
}
-export function shouldSkipUnavailableLspDiagnostics(filePath, sessionId) {
+export function readLspPostEditCache(sessionId) {
if (sessionId === undefined)
- return false;
+ return { notConfiguredExtensions: new Set() };
const state = readSessionState(sessionStatePath(sessionId));
- const extension = extensionKey(filePath);
- return (extension !== undefined &&
- state.postCompactProbePending !== true &&
- state.unavailableExtensions.includes(extension));
+ return { notConfiguredExtensions: new Set(state.notConfiguredExtensions) };
}
-export function recordLspDiagnosticsObservations(sessionId, observations) {
- if (sessionId === undefined || observations.length === 0)
- return;
- const state = readSessionState(sessionStatePath(sessionId));
- const unavailableExtensions = new Set(state.unavailableExtensions);
- for (const observation of observations) {
- const extension = extensionKey(observation.filePath);
- if (extension === undefined)
- continue;
- if (observation.unavailable) {
- unavailableExtensions.add(extension);
- }
- else {
- unavailableExtensions.delete(extension);
- }
- }
- writeSessionState(sessionStatePath(sessionId), { unavailableExtensions: [...unavailableExtensions].sort() });
-}
-export function markLspSessionCompacted(sessionId) {
+export function writeLspPostEditCache(sessionId, cache) {
if (sessionId === undefined)
return;
- const state = readSessionState(sessionStatePath(sessionId));
- if (state.unavailableExtensions.length === 0)
- return;
writeSessionState(sessionStatePath(sessionId), {
- unavailableExtensions: state.unavailableExtensions,
- postCompactProbePending: true,
+ notConfiguredExtensions: [...cache.notConfiguredExtensions].sort(),
});
}
-export function isUnavailableLspDiagnostics(diagnostics) {
- const normalized = diagnostics.trim();
- return (normalized.includes("LSP request timeout (method: initialize)") ||
- normalized.includes("LSP server is still initializing") ||
- normalized.includes("NOT INSTALLED") ||
- normalized.includes("Command not found:"));
+export function markLspSessionCompacted(sessionId) {
+ if (sessionId === undefined)
+ return;
+ writeSessionState(sessionStatePath(sessionId), emptyState());
}
export function isLspDaemonUnreachableDiagnostics(diagnostics) {
return diagnostics.includes("LSP daemon unreachable");
@@ -59,8 +32,8 @@ function sessionStatePath(sessionId) {
function readSessionState(path) {
try {
const parsed = JSON.parse(readFileSync(path, "utf8"));
- if (isLspSessionState(parsed))
- return parsed;
+ if (isRecord(parsed) && isLspSessionState(parsed))
+ return normalizeSessionState(parsed);
return emptyState();
}
catch (error) {
@@ -74,21 +47,22 @@ function writeSessionState(path, state) {
writeFileSync(path, `${JSON.stringify(state)}\n`);
}
function emptyState() {
- return { unavailableExtensions: [] };
-}
-function extensionKey(filePath) {
- const extension = extname(filePath).toLowerCase();
- return extension.length === 0 ? undefined : extension;
+ return { notConfiguredExtensions: [] };
}
function safePathSegment(value) {
return value.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 120) || "unknown-session";
}
function isLspSessionState(value) {
- if (!isRecord(value) || !Array.isArray(value["unavailableExtensions"]))
- return false;
- const postCompactProbePending = value["postCompactProbePending"];
- return (value["unavailableExtensions"].every((item) => typeof item === "string") &&
- (postCompactProbePending === undefined || typeof postCompactProbePending === "boolean"));
+ const notConfiguredExtensions = value["notConfiguredExtensions"] ?? value["unavailableExtensions"];
+ return Array.isArray(notConfiguredExtensions) && notConfiguredExtensions.every((item) => typeof item === "string");
+}
+function normalizeSessionState(value) {
+ const notConfiguredExtensions = value["notConfiguredExtensions"] ?? value["unavailableExtensions"];
+ return {
+ notConfiguredExtensions: Array.isArray(notConfiguredExtensions)
+ ? notConfiguredExtensions.filter((item) => typeof item === "string").sort()
+ : [],
+ };
}
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
diff --git a/plugins/omo/components/lsp/hooks/hooks.json b/plugins/omo/components/lsp/hooks/hooks.json
index 677a74b0..0abe0dfc 100644
--- a/plugins/omo/components/lsp/hooks/hooks.json
+++ b/plugins/omo/components/lsp/hooks/hooks.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use",
"timeout": 60,
- "statusMessage": "(OmO 4.18.0) Checking LSP Diagnostics"
+ "statusMessage": "(OmO 4.18.1) Checking LSP Diagnostics"
}
]
}
@@ -21,7 +21,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Resetting LSP Diagnostics Cache"
+ "statusMessage": "(OmO 4.18.1) Resetting LSP Diagnostics Cache"
}
]
}
diff --git a/plugins/omo/components/lsp/package.json b/plugins/omo/components/lsp/package.json
index 074c36a8..080cf9c5 100644
--- a/plugins/omo/components/lsp/package.json
+++ b/plugins/omo/components/lsp/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-lsp",
- "version": "4.18.0",
+ "version": "4.18.1",
"description": "Codex plugin that exposes Language Server Protocol tools and post-edit diagnostics.",
"type": "module",
"packageManager": "[email protected]",
@@ -38,7 +38,7 @@
"scripts": {
"bootstrap": "node scripts/build-lsp-tools.mjs && node scripts/build-lsp-daemon.mjs",
"prebuild": "node scripts/build-lsp-tools.mjs && node scripts/build-lsp-daemon.mjs",
- "build": "node scripts/clean-dist.mjs && tsc -p tsconfig.build.json",
+ "build": "node scripts/build-runtime.mjs",
"pretest": "npm run build --silent",
"test": "node scripts/test.mjs",
"test:watch": "vitest",
@@ -50,6 +50,7 @@
"check": "tsc --noEmit && biome check src test && tsc -p tsconfig.build.json"
},
"dependencies": {
+ "@oh-my-opencode/lsp-core": "file:../../../../lsp-core",
"@code-yeongyu/lsp-daemon": "file:../../../../lsp-daemon"
},
"devDependencies": {
diff --git a/plugins/omo/components/lsp/scripts/build-lsp-daemon.mjs b/plugins/omo/components/lsp/scripts/build-lsp-daemon.mjs
index 7725dae2..4a277011 100644
--- a/plugins/omo/components/lsp/scripts/build-lsp-daemon.mjs
+++ b/plugins/omo/components/lsp/scripts/build-lsp-daemon.mjs
@@ -1,10 +1,11 @@
#!/usr/bin/env node
import { execSync } from "node:child_process";
-import { existsSync, statSync } from "node:fs";
+import { existsSync, lstatSync, mkdirSync, realpathSync, rmSync, statSync, symlinkSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
+const componentRoot = join(here, "..");
const force = process.argv.includes("--force");
// Ordered candidate list:
@@ -18,6 +19,8 @@ const candidates = [
function requiredOutputs(dir) {
return [
join(dir, "dist", "cli.js"),
+ join(dir, "dist", "client.js"),
+ join(dir, "dist", "client.d.ts"),
join(dir, "dist", "index.js"),
join(dir, "dist", "index.d.ts"),
];
@@ -30,12 +33,14 @@ for (const dir of candidates) {
if (existsSync(packageJson)) {
const outputs = requiredOutputs(dir);
if (!force && isBuildFresh(packageJson, outputs)) {
+ ensureComponentPackageLink(dir);
process.exit(0);
}
console.log("Installing repository lsp-daemon dependencies...");
execSync("npm ci", { cwd: dir, stdio: "inherit" });
console.log("Building repository lsp-daemon...");
execSync("npm run build", { cwd: dir, stdio: "inherit" });
+ ensureComponentPackageLink(dir);
console.log("Done.");
process.exit(0);
}
@@ -46,6 +51,7 @@ for (const dir of candidates) {
for (const dir of candidates) {
const outputs = requiredOutputs(dir);
if (outputs.every((p) => existsSync(p))) {
+ ensureComponentPackageLink(dir);
console.log(`Using bundled lsp-daemon dist at ${dir}.`);
process.exit(0);
}
@@ -66,3 +72,27 @@ function isBuildFresh(inputPath, outputPaths) {
const inputMtime = statSync(inputPath).mtimeMs;
return outputPaths.every((path) => statSync(path).mtimeMs >= inputMtime);
}
+
+function ensureComponentPackageLink(packageDir) {
+ const scopeDir = join(componentRoot, "node_modules", "@code-yeongyu");
+ const linkPath = join(scopeDir, "lsp-daemon");
+ mkdirSync(scopeDir, { recursive: true });
+ if (isSymlinkToUsablePackage(linkPath, packageDir)) return;
+ rmSync(linkPath, { recursive: true, force: true });
+ symlinkSync(packageDir, linkPath, "junction");
+}
+
+function isSymlinkToUsablePackage(linkPath, packageDir) {
+ try {
+ const stat = lstatSync(linkPath);
+ return (
+ stat.isSymbolicLink() &&
+ existsSync(packageDir) &&
+ realpathSync(linkPath) === realpathSync(packageDir) &&
+ requiredOutputs(linkPath).every((path) => existsSync(path))
+ );
+ } catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
+ throw error;
+ }
+}
diff --git a/plugins/omo/components/lsp/scripts/build-lsp-daemon.test.mjs b/plugins/omo/components/lsp/scripts/build-lsp-daemon.test.mjs
new file mode 100644
index 00000000..b19ce23c
--- /dev/null
+++ b/plugins/omo/components/lsp/scripts/build-lsp-daemon.test.mjs
@@ -0,0 +1,76 @@
+import assert from "node:assert/strict";
+import { chmod, copyFile, lstat, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { delimiter, join } from "node:path";
+import { spawnSync } from "node:child_process";
+import test from "node:test";
+
+async function makeFixture() {
+ const root = await mkdtemp(join(tmpdir(), "codex-lsp-daemon-build-"));
+ const componentRoot = join(root, "packages", "omo-codex", "plugin", "components", "lsp");
+ const packageDir = join(root, "packages", "lsp-daemon");
+ const script = join(componentRoot, "scripts", "build-lsp-daemon.mjs");
+ await mkdir(join(componentRoot, "scripts"), { recursive: true });
+ await mkdir(join(packageDir, "dist"), { recursive: true });
+ await copyFile(new URL("./build-lsp-daemon.mjs", import.meta.url), script);
+ await writeFile(join(packageDir, "package.json"), "{}\n");
+ await writeDaemonOutputs(packageDir);
+ return { root, componentRoot, packageDir, script };
+}
+
+async function writeDaemonOutputs(packageDir) {
+ for (const output of ["cli.js", "client.js", "client.d.ts", "index.js", "index.d.ts"]) {
+ await writeFile(join(packageDir, "dist", output), `${output}\n`);
+ }
+}
+
+function runScript(script, fakeBin, args = []) {
+ return spawnSync(process.execPath, [script, ...args], {
+ encoding: "utf8",
+ env: { ...process.env, PATH: fakeBin ? `${fakeBin}${delimiter}${process.env.PATH ?? ""}` : process.env.PATH },
+ });
+}
+
+test("#given fresh daemon dist #when bootstrapping component #then local package link is created", async () => {
+ // given
+ const fixture = await makeFixture();
+ const link = join(fixture.componentRoot, "node_modules", "@code-yeongyu", "lsp-daemon");
+
+ // when
+ const result = runScript(fixture.script);
+
+ // then
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal((await lstat(link)).isSymbolicLink(), true);
+ assert.equal(await realpath(link), await realpath(fixture.packageDir));
+});
+
+test("#given client outputs are missing #when bootstrapping component #then daemon rebuild runs before linking", async () => {
+ // given
+ const fixture = await makeFixture();
+ await rm(join(fixture.packageDir, "dist", "client.d.ts"));
+ const fakeBin = join(fixture.root, "bin");
+ const npmLog = join(fixture.root, "npm.log");
+ await mkdir(fakeBin, { recursive: true });
+ await writeFile(
+ join(fakeBin, "npm.js"),
+ `const { appendFileSync, mkdirSync, writeFileSync } = require("node:fs");\n` +
+ `const { join } = require("node:path");\n` +
+ `appendFileSync(${JSON.stringify(npmLog)}, process.argv.slice(2).join(" ") + "\\n");\n` +
+ `if (process.argv.slice(2).join(" ") === "run build") {\n` +
+ ` const dist = join(process.cwd(), "dist");\n` +
+ ` mkdirSync(dist, { recursive: true });\n` +
+ ` for (const name of ["cli.js", "client.js", "client.d.ts", "index.js", "index.d.ts"]) writeFileSync(join(dist, name), name + "\\n");\n` +
+ `}\n`,
+ );
+ await writeFile(join(fakeBin, "npm"), "#!/usr/bin/env node\nrequire('./npm.js');\n");
+ await chmod(join(fakeBin, "npm"), 0o755);
+
+ // when
+ const result = runScript(fixture.script, fakeBin);
+
+ // then
+ assert.equal(result.status, 0, result.stderr);
+ assert.match(await readFile(npmLog, "utf8"), /ci\nrun build\n/u);
+ assert.equal(await realpath(join(fixture.componentRoot, "node_modules", "@code-yeongyu", "lsp-daemon")), await realpath(fixture.packageDir));
+});
diff --git a/plugins/omo/components/lsp/scripts/build-runtime.mjs b/plugins/omo/components/lsp/scripts/build-runtime.mjs
new file mode 100644
index 00000000..846ff2bf
--- /dev/null
+++ b/plugins/omo/components/lsp/scripts/build-runtime.mjs
@@ -0,0 +1,201 @@
+#!/usr/bin/env node
+import { createHash } from "node:crypto";
+import { spawnSync } from "node:child_process";
+import { builtinModules } from "node:module";
+import {
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ readdirSync,
+ renameSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { dirname, join, relative } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const SCHEMA_VERSION = 1;
+const componentRoot = dirname(dirname(fileURLToPath(import.meta.url)));
+const distDir = join(componentRoot, "dist");
+const manifestPath = join(distDir, ".omo-runtime-manifest.json");
+const builtinSpecifiers = new Set([
+ ...builtinModules,
+ ...builtinModules.map((name) => `node:${name}`),
+]);
+
+if (!existsSync(join(componentRoot, "src"))) {
+ validateDistOnlyManifest();
+ process.exit(0);
+}
+
+if (isManifestFresh()) {
+ process.exit(0);
+}
+
+rmSync(distDir, { recursive: true, force: true });
+mkdirSync(distDir, { recursive: true });
+run("tsc", ["-p", "tsconfig.build.json"]);
+run("bun", [
+ "build",
+ "src/cli.ts",
+ "--target",
+ "node",
+ "--format",
+ "esm",
+ "--outfile",
+ "dist/cli.js",
+]);
+assertBuiltinOnlyCli();
+writeManifest();
+validateManifest({ requireFreshInputs: true });
+
+function run(command, args) {
+ const result = spawnSync(command, args, {
+ cwd: componentRoot,
+ shell: process.platform === "win32",
+ stdio: "inherit",
+ });
+ if (result.error !== undefined) throw result.error;
+ if (result.status !== 0) process.exit(result.status ?? 1);
+}
+
+function isManifestFresh() {
+ try {
+ validateManifest({ requireFreshInputs: true });
+ return true;
+ } catch (error) {
+ if (error instanceof Error) return false;
+ throw error;
+ }
+}
+
+function validateDistOnlyManifest() {
+ try {
+ validateManifest({ requireFreshInputs: false });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ console.error(`Invalid installed codex-lsp runtime manifest: ${message}`);
+ process.exit(1);
+ }
+}
+
+function validateManifest({ requireFreshInputs }) {
+ const manifest = readManifest();
+ if (manifest.schemaVersion !== SCHEMA_VERSION) throw new Error("unsupported manifest schemaVersion");
+ if (manifest.version !== packageVersion()) throw new Error("manifest version is stale");
+ if (requireFreshInputs && manifest.inputDigest !== inputDigest()) throw new Error("manifest inputDigest is stale");
+ const outputs = [...manifest.outputs].sort((left, right) => left.path.localeCompare(right.path));
+ if (JSON.stringify(outputs) !== JSON.stringify(manifest.outputs)) throw new Error("manifest outputs are not sorted");
+ for (const output of outputs) {
+ const outputPath = join(distDir, output.path);
+ if (!existsSync(outputPath)) throw new Error(`manifest output is missing: ${output.path}`);
+ if (sha256File(outputPath) !== output.sha256) throw new Error(`manifest output hash mismatch: ${output.path}`);
+ }
+}
+
+function readManifest() {
+ if (!existsSync(manifestPath)) throw new Error("manifest is missing");
+ const parsed = JSON.parse(readFileSync(manifestPath, "utf8"));
+ if (!isRecord(parsed)) throw new Error("manifest must be an object");
+ if (parsed.schemaVersion !== SCHEMA_VERSION) throw new Error("manifest schemaVersion must be 1");
+ if (typeof parsed.version !== "string") throw new Error("manifest version must be a string");
+ if (typeof parsed.inputDigest !== "string" || !/^sha256:[0-9a-f]{64}$/.test(parsed.inputDigest)) {
+ throw new Error("manifest inputDigest must be sha256:<64hex>");
+ }
+ if (!Array.isArray(parsed.outputs) || !parsed.outputs.every(isManifestOutput)) {
+ throw new Error("manifest outputs are malformed");
+ }
+ return parsed;
+}
+
+function isManifestOutput(value) {
+ return (
+ isRecord(value) &&
+ typeof value.path === "string" &&
+ value.path.length > 0 &&
+ !value.path.includes("..") &&
+ typeof value.sha256 === "string" &&
+ /^[0-9a-f]{64}$/.test(value.sha256)
+ );
+}
+
+function writeManifest() {
+ const manifest = {
+ schemaVersion: SCHEMA_VERSION,
+ version: packageVersion(),
+ inputDigest: inputDigest(),
+ outputs: outputFiles().map((path) => ({ path, sha256: sha256File(join(distDir, path)) })),
+ };
+ manifest.outputs.sort((left, right) => left.path.localeCompare(right.path));
+ const tempPath = join(distDir, `.omo-runtime-manifest.${process.pid}.tmp`);
+ writeFileSync(tempPath, `${JSON.stringify(manifest, null, 2)}\n`);
+ renameSync(tempPath, manifestPath);
+}
+
+function inputDigest() {
+ const hash = createHash("sha256");
+ for (const path of inputFiles()) {
+ hash.update(path);
+ hash.update("\0");
+ hash.update(sha256File(join(componentRoot, path)));
+ hash.update("\0");
+ }
+ return `sha256:${hash.digest("hex")}`;
+}
+
+function inputFiles() {
+ return [
+ "package.json",
+ "tsconfig.json",
+ "tsconfig.build.json",
+ "scripts/build-runtime.mjs",
+ ...walk(join(componentRoot, "src")).map((path) => relative(componentRoot, path)),
+ ].sort();
+}
+
+function outputFiles() {
+ return walk(distDir)
+ .map((path) => relative(distDir, path))
+ .filter((path) => path !== ".omo-runtime-manifest.json")
+ .sort();
+}
+
+function walk(root) {
+ const entries = [];
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
+ const path = join(root, entry.name);
+ if (entry.isDirectory()) {
+ entries.push(...walk(path));
+ } else if (entry.isFile()) {
+ entries.push(path);
+ }
+ }
+ return entries;
+}
+
+function assertBuiltinOnlyCli() {
+ const source = readFileSync(join(distDir, "cli.js"), "utf8");
+ const specifiers = [
+ ...source.matchAll(/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+)["']/g),
+ ...source.matchAll(/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g),
+ ].map((match) => match[1]);
+ const invalid = specifiers.filter((specifier) => !builtinSpecifiers.has(specifier));
+ if (invalid.length > 0) {
+ throw new Error(`dist/cli.js has non-builtin runtime imports: ${invalid.join(", ")}`);
+ }
+}
+
+function packageVersion() {
+ const parsed = JSON.parse(readFileSync(join(componentRoot, "package.json"), "utf8"));
+ if (!isRecord(parsed) || typeof parsed.version !== "string") throw new Error("package.json version is missing");
+ return parsed.version;
+}
+
+function sha256File(path) {
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
+}
+
+function isRecord(value) {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/plugins/omo/components/lsp/scripts/build-runtime.test.mjs b/plugins/omo/components/lsp/scripts/build-runtime.test.mjs
new file mode 100644
index 00000000..09633a80
--- /dev/null
+++ b/plugins/omo/components/lsp/scripts/build-runtime.test.mjs
@@ -0,0 +1,55 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+
+const SCRIPT_URL = new URL("./build-runtime.mjs", import.meta.url);
+
+test("#given a built component runtime #when the manifest is inspected #then it pins sorted output hashes", async () => {
+ const manifest = JSON.parse(await readFile(new URL("../dist/.omo-runtime-manifest.json", import.meta.url), "utf8"));
+ assert.equal(manifest.schemaVersion, 1);
+ assert.match(manifest.inputDigest, /^sha256:[0-9a-f]{64}$/u);
+ assert.deepEqual(
+ manifest.outputs.map((output) => output.path),
+ [...manifest.outputs.map((output) => output.path)].sort(),
+ );
+ assert(manifest.outputs.some((output) => output.path === "cli.js"));
+ assert(manifest.outputs.every((output) => /^[0-9a-f]{64}$/u.test(output.sha256)));
+});
+
+test("#given a dist-only installed component #when output bytes are tampered #then validation fails actionably", async () => {
+ const root = await mkdtemp(join(tmpdir(), "codex-lsp-dist-only-"));
+ try {
+ const componentRoot = join(root, "component");
+ await mkdir(join(componentRoot, "scripts"), { recursive: true });
+ await copyFile(SCRIPT_URL, join(componentRoot, "scripts", "build-runtime.mjs"));
+ await writeFile(join(componentRoot, "package.json"), JSON.stringify({ version: "4.17.0" }));
+ await mkdir(join(componentRoot, "dist"), { recursive: true });
+ await writeFile(join(componentRoot, "dist", "cli.js"), "console.log('tampered')\n");
+ await writeFile(
+ join(componentRoot, "dist", ".omo-runtime-manifest.json"),
+ JSON.stringify(
+ {
+ schemaVersion: 1,
+ version: "4.17.0",
+ inputDigest: `sha256:${"0".repeat(64)}`,
+ outputs: [{ path: "cli.js", sha256: "1".repeat(64) }],
+ },
+ null,
+ 2,
+ ),
+ );
+
+ const result = spawnSync(process.execPath, [join(componentRoot, "scripts", "build-runtime.mjs")], {
+ encoding: "utf8",
+ });
+
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr, /Invalid installed codex-lsp runtime manifest/u);
+ assert.match(result.stderr, /hash mismatch/u);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/omo/components/lsp/src/codex-hook-cli.ts b/plugins/omo/components/lsp/src/codex-hook-cli.ts
index 3325b83e..c0a336cb 100644
--- a/plugins/omo/components/lsp/src/codex-hook-cli.ts
+++ b/plugins/omo/components/lsp/src/codex-hook-cli.ts
@@ -1,7 +1,5 @@
import { stdin as processStdin } from "node:process";
-import { disposeDefaultLspManager } from "@code-yeongyu/lsp-daemon";
-
import { isRecord, runLspPostCompactHook, runLspPostToolUseHook } from "./codex-hook.js";
export async function runPostToolUseHookCli(stdin: NodeJS.ReadStream = processStdin): Promise<void> {
@@ -26,8 +24,6 @@ async function runHookCli(
} catch {
// LSP feedback is best-effort: stderr or a non-zero exit here surfaces as harness noise on every edit.
return;
- } finally {
- await disposeDefaultLspManager().catch(() => undefined);
}
}
diff --git a/plugins/omo/components/lsp/src/codex-hook.ts b/plugins/omo/components/lsp/src/codex-hook.ts
index 5408c4d0..e0d21099 100644
--- a/plugins/omo/components/lsp/src/codex-hook.ts
+++ b/plugins/omo/components/lsp/src/codex-hook.ts
@@ -1,21 +1,24 @@
-import { readFileSync } from "node:fs";
+import { readFileSync, realpathSync } from "node:fs";
+import { homedir } from "node:os";
+import { join, resolve } from "node:path";
-import { callDiagnosticsViaDaemon, currentRequestContext } from "@code-yeongyu/lsp-daemon";
+import { callDiagnosticsViaDaemon } from "@code-yeongyu/lsp-daemon/client";
+import { collectPostEditDiagnostics, type PostEditDiagnosticsOutcome } from "@oh-my-opencode/lsp-core/post-edit";
+import { parseLspRequestContext, type LspRequestContext } from "@oh-my-opencode/lsp-core/request-context";
import { ensureLspDaemonCliEnv } from "./daemon-cli-path.js";
import {
isLspDaemonUnreachableDiagnostics,
- isUnavailableLspDiagnostics,
markLspSessionCompacted,
- recordLspDiagnosticsObservations,
+ readLspPostEditCache,
sessionIdFrom,
- shouldSkipUnavailableLspDiagnostics,
+ writeLspPostEditCache,
} from "./lsp-session-state.js";
import { extractMutatedFilePaths } from "./mutated-file-paths.js";
export { extractMutatedFilePaths } from "./mutated-file-paths.js";
-export type DiagnosticsRunner = (filePath: string) => Promise<string>;
+export type DiagnosticsRunner = (filePath: string) => Promise<PostEditDiagnosticsOutcome>;
export interface CodexPostToolUseInput {
session_id?: unknown;
@@ -43,13 +46,10 @@ interface PostToolUseHookOutput {
};
}
-const CLEAN_DIAGNOSTICS_TEXT = "No diagnostics found";
-const UNSUPPORTED_EXTENSION_TEXT = "No LSP server configured for extension:";
const DIAGNOSTIC_START_PATTERN = /(?:error|warning|information|hint)\[[^\]\r\n]+\] \(\d+\) at \d+:\d+:/g;
const DIAGNOSTIC_CHUNK_PATTERN = /^(?:error|warning|information|hint)\[[^\]\r\n]+\] \(\d+\) at \d+:\d+:/;
const DEFAULT_MAX_HOOK_FEEDBACK_CHARS = 8000;
const CONTEXT_PRESSURE_MAX_HOOK_FEEDBACK_CHARS = 1200;
-const MAX_CONCURRENT_DIAGNOSTICS = 4;
const CONTEXT_PRESSURE_MARKERS = [
"context compacted",
"context_length_exceeded",
@@ -60,35 +60,57 @@ const CONTEXT_PRESSURE_MARKERS = [
"long threads and multiple compactions",
] as const;
-export async function runLspDiagnosticsText(filePath: string): Promise<string> {
+export async function runLspDiagnosticsText(filePath: string): Promise<PostEditDiagnosticsOutcome> {
ensureLspDaemonCliEnv();
- const result = await callDiagnosticsViaDaemon(filePath, { context: currentRequestContext() });
+ const result = await callDiagnosticsViaDaemon(filePath, { context: codexLspRequestContext() });
+ return postEditOutcomeFromDaemonResult(result);
+}
+
+function postEditOutcomeFromDaemonResult(result: {
+ readonly content: readonly { readonly type: string; readonly text?: string }[];
+ readonly details?: unknown;
+}): PostEditDiagnosticsOutcome {
+ const availability = notConfiguredAvailability(result.details);
+ if (availability !== undefined) return { kind: "not_configured", extension: availability.extension };
return result.content.map((block) => block.text).join("\n");
}
+function notConfiguredAvailability(details: unknown): { readonly extension: string } | undefined {
+ if (!isRecord(details)) return undefined;
+ const availability = details["availability"];
+ if (!isRecord(availability)) return undefined;
+ if (availability["kind"] !== "not_configured") return undefined;
+ const extension = availability["extension"];
+ return typeof extension === "string" && extension.length > 0 ? { extension } : undefined;
+}
+
+export function codexLspRequestContext(
+ env: Record<string, string | undefined> = process.env,
+ cwd: string = process.cwd(),
+): LspRequestContext {
+ const canonicalCwd = realpathSync(resolve(cwd));
+ const codexHome = resolve(env["CODEX_HOME"]?.trim() || join(homedir(), ".codex"));
+ return parseLspRequestContext({
+ cwd: canonicalCwd,
+ projectConfigPaths: [join(canonicalCwd, ".codex", "lsp-client.json")],
+ userConfigPath: join(codexHome, "lsp-client.json"),
+ installDecisionsPath: join(codexHome, "lsp-install-decisions.json"),
+ capabilities: { installDecisionTool: true },
+ });
+}
+
export async function runLspPostToolUseHook(
input: CodexPostToolUseInput,
runDiagnostics: DiagnosticsRunner = runLspDiagnosticsText,
): Promise<string> {
const sessionId = sessionIdFrom(input);
- const filePaths = extractMutatedFilePaths(input).filter(
- (filePath) => !shouldSkipUnavailableLspDiagnostics(filePath, sessionId),
- );
+ const filePaths = extractMutatedFilePaths(input);
if (filePaths.length === 0) return "";
- const blocks: DiagnosticBlock[] = [];
- const observations: Array<{ filePath: string; unavailable: boolean }> = [];
- for (const { filePath, diagnostics } of await collectDiagnostics(filePaths, runDiagnostics)) {
- // A daemon outage is transient (connect-or-spawn retries on the next request);
- // recording it would silence this extension for the rest of the session.
- if (isLspDaemonUnreachableDiagnostics(diagnostics)) continue;
- const unavailable = isUnavailableLspDiagnostics(diagnostics);
- observations.push({ filePath, unavailable });
- if (isCleanDiagnostics(diagnostics)) continue;
- if (unavailable) continue;
- blocks.push({ filePath, diagnostics });
- }
- recordLspDiagnosticsObservations(sessionId, observations);
+ const cache = readLspPostEditCache(sessionId);
+ const result = await collectPostEditDiagnostics({ filePaths, runDiagnostics, cache });
+ writeLspPostEditCache(sessionId, cache);
+ const blocks = result.blocks.filter(({ diagnostics }) => !isLspDaemonUnreachableDiagnostics(diagnostics));
if (blocks.length === 0) return "";
@@ -110,42 +132,6 @@ export async function runLspPostCompactHook(input: CodexPostCompactInput): Promi
return "";
}
-async function collectDiagnostics(
- filePaths: readonly string[],
- runDiagnostics: DiagnosticsRunner,
-): Promise<DiagnosticBlock[]> {
- const results: DiagnosticBlock[] = [];
- let nextIndex = 0;
- const workerCount = Math.min(MAX_CONCURRENT_DIAGNOSTICS, filePaths.length);
- async function worker(): Promise<void> {
- for (;;) {
- const index = nextIndex;
- nextIndex += 1;
- const filePath = filePaths[index];
- if (filePath === undefined) return;
- results[index] = { filePath, diagnostics: await collectFileDiagnostics(filePath, runDiagnostics) };
- }
- }
- await Promise.all(Array.from({ length: workerCount }, () => worker()));
- return results;
-}
-
-async function collectFileDiagnostics(filePath: string, runDiagnostics: DiagnosticsRunner): Promise<string> {
- try {
- return (await runDiagnostics(filePath)).trim();
- } catch (error) {
- return formatDiagnosticsError(error);
- }
-}
-
-function formatDiagnosticsError(error: unknown): string {
- if (error instanceof Error) {
- const message = error.message.trim();
- if (message.length > 0) return message;
- }
- return String(error).trim();
-}
-
function formatDiagnosticBlock({ filePath, diagnostics }: DiagnosticBlock): string {
return `LSP diagnostics after editing ${filePath}:\n\n${formatDiagnosticsForDisplay(diagnostics)}`;
}
@@ -221,14 +207,6 @@ function limitHookText(text: string, maxChars: number): string {
return `${head}${marker}`;
}
-function isCleanDiagnostics(diagnostics: string): boolean {
- return (
- diagnostics.length === 0 ||
- diagnostics === CLEAN_DIAGNOSTICS_TEXT ||
- diagnostics.startsWith(UNSUPPORTED_EXTENSION_TEXT)
- );
-}
-
export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
diff --git a/plugins/omo/components/lsp/src/daemon-cli-path.ts b/plugins/omo/components/lsp/src/daemon-cli-path.ts
index 806f6a49..2c04599e 100644
--- a/plugins/omo/components/lsp/src/daemon-cli-path.ts
+++ b/plugins/omo/components/lsp/src/daemon-cli-path.ts
@@ -3,28 +3,32 @@ import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
+import {
+ OMO_LSP_DAEMON_CLI,
+ OMO_LSP_DAEMON_VERSION,
+ resolveDaemonRuntime,
+} from "@code-yeongyu/lsp-daemon/client";
+
const requireFromHere = createRequire(import.meta.url);
-const PACKAGE_LSP_DAEMON_CLI = "@code-yeongyu/lsp-daemon/dist/cli.js";
-const CODEX_LSP_DAEMON_CLI_ENV = "CODEX_LSP_DAEMON_CLI";
-const CODEX_LSP_DAEMON_VERSION_ENV = "CODEX_LSP_DAEMON_VERSION";
+const PACKAGE_LSP_DAEMON_CLI = "@code-yeongyu/lsp-daemon/cli";
interface LspDaemonCliResolution {
cliPath: string;
- version: string | null;
+ version: string;
}
export function ensureLspDaemonCliEnv(env: NodeJS.ProcessEnv = process.env): void {
- const configuredCli = env[CODEX_LSP_DAEMON_CLI_ENV]?.trim();
- const resolution = configuredCli ? resolveConfiguredLspDaemonCli(configuredCli) : resolveLspDaemonCli();
- if (!configuredCli) env[CODEX_LSP_DAEMON_CLI_ENV] = resolution.cliPath;
- if (!env[CODEX_LSP_DAEMON_VERSION_ENV]?.trim() && resolution.version !== null) {
- env[CODEX_LSP_DAEMON_VERSION_ENV] = resolution.version;
- }
+ const runtime = resolveDaemonRuntime(env, resolveLspDaemonCli());
+ env[OMO_LSP_DAEMON_CLI] = runtime.cliPath;
+ env[OMO_LSP_DAEMON_VERSION] = runtime.version;
}
-export function resolveLspDaemonCliPath(): string {
- return resolveLspDaemonCli().cliPath;
+export function resolveLspDaemonCliPath(env: NodeJS.ProcessEnv = process.env): string {
+ const runtime = resolveDaemonRuntime(env, resolveLspDaemonCli());
+ if (env[OMO_LSP_DAEMON_CLI] === undefined) env[OMO_LSP_DAEMON_CLI] = runtime.cliPath;
+ if (env[OMO_LSP_DAEMON_VERSION] === undefined) env[OMO_LSP_DAEMON_VERSION] = runtime.version;
+ return runtime.cliPath;
}
function resolveLspDaemonCli(): LspDaemonCliResolution {
@@ -38,15 +42,20 @@ function resolveLspDaemonCli(): LspDaemonCliResolution {
function resolvePackageLspDaemonCliPath(): string | null {
try {
return requireFromHere.resolve(PACKAGE_LSP_DAEMON_CLI);
- } catch {
+ } catch (error) {
+ if (!(error instanceof Error)) throw error;
return null;
}
}
function resolveConfiguredLspDaemonCli(cliPath: string): LspDaemonCliResolution {
+ const version = readDaemonPackageVersion(cliPath);
+ if (version === null) {
+ throw new Error(`Unable to determine packaged LSP daemon version beside ${cliPath}`);
+ }
return {
cliPath,
- version: readDaemonPackageVersion(cliPath),
+ version,
};
}
@@ -56,7 +65,9 @@ function readDaemonPackageVersion(cliPath: string): string | null {
if (isRecord(parsed) && typeof parsed["version"] === "string" && parsed["version"].length > 0) {
return parsed["version"];
}
- } catch {}
+ } catch (error) {
+ if (!(error instanceof Error)) throw error;
+ }
return null;
}
diff --git a/plugins/omo/components/lsp/src/lsp-session-state.ts b/plugins/omo/components/lsp/src/lsp-session-state.ts
index 7c547d44..a31822ab 100644
--- a/plugins/omo/components/lsp/src/lsp-session-state.ts
+++ b/plugins/omo/components/lsp/src/lsp-session-state.ts
@@ -1,71 +1,33 @@
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
-import { dirname, extname, join } from "node:path";
+import { dirname, join } from "node:path";
-interface LspSessionState {
- readonly unavailableExtensions: readonly string[];
- readonly postCompactProbePending?: boolean;
-}
+import type { PostEditNotConfiguredCache } from "@oh-my-opencode/lsp-core/post-edit";
-export interface DiagnosticsObservation {
- readonly filePath: string;
- readonly unavailable: boolean;
+interface LspSessionState {
+ readonly notConfiguredExtensions: readonly string[];
}
export function sessionIdFrom(input: { readonly session_id?: unknown }): string | undefined {
return typeof input.session_id === "string" && input.session_id.length > 0 ? input.session_id : undefined;
}
-export function shouldSkipUnavailableLspDiagnostics(filePath: string, sessionId: string | undefined): boolean {
- if (sessionId === undefined) return false;
+export function readLspPostEditCache(sessionId: string | undefined): PostEditNotConfiguredCache {
+ if (sessionId === undefined) return { notConfiguredExtensions: new Set() };
const state = readSessionState(sessionStatePath(sessionId));
- const extension = extensionKey(filePath);
- return (
- extension !== undefined &&
- state.postCompactProbePending !== true &&
- state.unavailableExtensions.includes(extension)
- );
-}
-
-export function recordLspDiagnosticsObservations(
- sessionId: string | undefined,
- observations: readonly DiagnosticsObservation[],
-): void {
- if (sessionId === undefined || observations.length === 0) return;
- const state = readSessionState(sessionStatePath(sessionId));
- const unavailableExtensions = new Set(state.unavailableExtensions);
-
- for (const observation of observations) {
- const extension = extensionKey(observation.filePath);
- if (extension === undefined) continue;
- if (observation.unavailable) {
- unavailableExtensions.add(extension);
- } else {
- unavailableExtensions.delete(extension);
- }
- }
-
- writeSessionState(sessionStatePath(sessionId), { unavailableExtensions: [...unavailableExtensions].sort() });
+ return { notConfiguredExtensions: new Set(state.notConfiguredExtensions) };
}
-export function markLspSessionCompacted(sessionId: string | undefined): void {
+export function writeLspPostEditCache(sessionId: string | undefined, cache: PostEditNotConfiguredCache): void {
if (sessionId === undefined) return;
- const state = readSessionState(sessionStatePath(sessionId));
- if (state.unavailableExtensions.length === 0) return;
writeSessionState(sessionStatePath(sessionId), {
- unavailableExtensions: state.unavailableExtensions,
- postCompactProbePending: true,
+ notConfiguredExtensions: [...cache.notConfiguredExtensions].sort(),
});
}
-export function isUnavailableLspDiagnostics(diagnostics: string): boolean {
- const normalized = diagnostics.trim();
- return (
- normalized.includes("LSP request timeout (method: initialize)") ||
- normalized.includes("LSP server is still initializing") ||
- normalized.includes("NOT INSTALLED") ||
- normalized.includes("Command not found:")
- );
+export function markLspSessionCompacted(sessionId: string | undefined): void {
+ if (sessionId === undefined) return;
+ writeSessionState(sessionStatePath(sessionId), emptyState());
}
export function isLspDaemonUnreachableDiagnostics(diagnostics: string): boolean {
@@ -80,7 +42,7 @@ function sessionStatePath(sessionId: string): string {
function readSessionState(path: string): LspSessionState {
try {
const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
- if (isLspSessionState(parsed)) return parsed;
+ if (isRecord(parsed) && isLspSessionState(parsed)) return normalizeSessionState(parsed);
return emptyState();
} catch (error) {
if (error instanceof SyntaxError || (isRecord(error) && error["code"] === "ENOENT")) return emptyState();
@@ -94,25 +56,25 @@ function writeSessionState(path: string, state: LspSessionState): void {
}
function emptyState(): LspSessionState {
- return { unavailableExtensions: [] };
-}
-
-function extensionKey(filePath: string): string | undefined {
- const extension = extname(filePath).toLowerCase();
- return extension.length === 0 ? undefined : extension;
+ return { notConfiguredExtensions: [] };
}
function safePathSegment(value: string): string {
return value.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 120) || "unknown-session";
}
-function isLspSessionState(value: unknown): value is LspSessionState {
- if (!isRecord(value) || !Array.isArray(value["unavailableExtensions"])) return false;
- const postCompactProbePending = value["postCompactProbePending"];
- return (
- value["unavailableExtensions"].every((item) => typeof item === "string") &&
- (postCompactProbePending === undefined || typeof postCompactProbePending === "boolean")
- );
+function isLspSessionState(value: Record<string, unknown>): boolean {
+ const notConfiguredExtensions = value["notConfiguredExtensions"] ?? value["unavailableExtensions"];
+ return Array.isArray(notConfiguredExtensions) && notConfiguredExtensions.every((item) => typeof item === "string");
+}
+
+function normalizeSessionState(value: Record<string, unknown>): LspSessionState {
+ const notConfiguredExtensions = value["notConfiguredExtensions"] ?? value["unavailableExtensions"];
+ return {
+ notConfiguredExtensions: Array.isArray(notConfiguredExtensions)
+ ? notConfiguredExtensions.filter((item) => typeof item === "string").sort()
+ : [],
+ };
}
function isRecord(value: unknown): value is Record<string, unknown> {
diff --git a/plugins/omo/components/lsp/test/codex-hook-unavailable.test.ts b/plugins/omo/components/lsp/test/codex-hook-unavailable.test.ts
index cf9dfde1..16b74c12 100644
--- a/plugins/omo/components/lsp/test/codex-hook-unavailable.test.ts
+++ b/plugins/omo/components/lsp/test/codex-hook-unavailable.test.ts
@@ -3,15 +3,10 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
+import type { PostEditDiagnosticsOutcome } from "@oh-my-opencode/lsp-core/post-edit";
import { runLspPostCompactHook, runLspPostToolUseHook } from "../src/codex-hook.js";
-const MARKSMAN_INITIALIZE_TIMEOUT = [
- "LSP request timeout (method: initialize)",
- 'recent stderr: [01:16:41 INF] <LSP Entry> Starting Marksman LSP server: {"arch":"Arm64"}',
- '[01:16:41 INF] <Folder> Loading folder documents: {"uri":"file:///repo"}',
-].join("\n");
-
const DAEMON_UNREACHABLE = [
"LSP daemon unreachable: daemon did not become reachable.",
"The MCP server is a thin proxy and never runs language servers in-process.",
@@ -37,7 +32,7 @@ describe("codex PostToolUse unavailable LSP suppression", () => {
// when
const firstOutput = await runLspPostToolUseHook(input, async () => {
calls += 1;
- return MARKSMAN_INITIALIZE_TIMEOUT;
+ return markdownNotConfigured();
});
const secondOutput = await runLspPostToolUseHook(input, async () => {
calls += 1;
@@ -60,7 +55,7 @@ describe("codex PostToolUse unavailable LSP suppression", () => {
await withPluginData(pluginData, async () => {
await runLspPostToolUseHook(input, async () => {
calls += 1;
- return MARKSMAN_INITIALIZE_TIMEOUT;
+ return markdownNotConfigured();
});
await runLspPostToolUseHook(input, async () => {
calls += 1;
@@ -80,7 +75,7 @@ describe("codex PostToolUse unavailable LSP suppression", () => {
const compactOutput = await runLspPostCompactHook(compactInput);
const afterCompactOutput = await runLspPostToolUseHook(input, async () => {
calls += 1;
- return MARKSMAN_INITIALIZE_TIMEOUT;
+ return markdownNotConfigured();
});
await runLspPostToolUseHook(input, async () => {
calls += 1;
@@ -103,7 +98,7 @@ describe("codex PostToolUse unavailable LSP suppression", () => {
await withPluginData(pluginData, async () => {
await runLspPostToolUseHook(input, async () => {
calls += 1;
- return MARKSMAN_INITIALIZE_TIMEOUT;
+ return markdownNotConfigured();
});
await runLspPostCompactHook({ session_id: "session-compact-clean" });
@@ -154,11 +149,11 @@ describe("codex PostToolUse unavailable LSP suppression", () => {
const input = postToolUseInput("session-daemon-down-probe", ".omo/ulw-loop/evidence/note.md");
let calls = 0;
- await withPluginData(pluginData, async () => {
- await runLspPostToolUseHook(input, async () => {
- calls += 1;
- return MARKSMAN_INITIALIZE_TIMEOUT;
- });
+ await withPluginData(pluginData, async () => {
+ await runLspPostToolUseHook(input, async () => {
+ calls += 1;
+ return markdownNotConfigured();
+ });
await runLspPostToolUseHook(input, async () => {
calls += 1;
return "error[markdown] (1000) at 1:1: cached call should have been skipped.";
@@ -172,7 +167,7 @@ describe("codex PostToolUse unavailable LSP suppression", () => {
});
const retriedProbeOutput = await runLspPostToolUseHook(input, async () => {
calls += 1;
- return MARKSMAN_INITIALIZE_TIMEOUT;
+ return markdownNotConfigured();
});
await runLspPostToolUseHook(input, async () => {
calls += 1;
@@ -193,7 +188,7 @@ describe("codex PostToolUse unavailable LSP suppression", () => {
const typescriptInput = postToolUseInput("session-real-diagnostics", "src/broken.ts");
await withPluginData(pluginData, async () => {
- await runLspPostToolUseHook(markdownInput, async () => MARKSMAN_INITIALIZE_TIMEOUT);
+ await runLspPostToolUseHook(markdownInput, async () => markdownNotConfigured());
// when
const output = await runLspPostToolUseHook(
@@ -248,6 +243,10 @@ function tempPluginData(): string {
return dir;
}
+function markdownNotConfigured(): PostEditDiagnosticsOutcome {
+ return { kind: "not_configured", extension: ".md" };
+}
+
interface PostToolUseHookOutput {
readonly decision: "block";
readonly reason: string;
diff --git a/plugins/omo/components/lsp/test/codex-hook.test.ts b/plugins/omo/components/lsp/test/codex-hook.test.ts
index 0b34e163..cab0a505 100644
--- a/plugins/omo/components/lsp/test/codex-hook.test.ts
+++ b/plugins/omo/components/lsp/test/codex-hook.test.ts
@@ -1,10 +1,11 @@
-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
+import type { PostEditDiagnosticsOutcome } from "@oh-my-opencode/lsp-core/post-edit";
-import { extractMutatedFilePaths, runLspPostToolUseHook } from "../src/codex-hook.js";
+import { codexLspRequestContext, extractMutatedFilePaths, runLspPostToolUseHook } from "../src/codex-hook.js";
const tempDirs: string[] = [];
@@ -15,6 +16,21 @@ afterEach(() => {
});
describe("codex PostToolUse hook", () => {
+ it("#given CODEX_HOME #when building the daemon request context #then Codex config paths are exact and capability is enabled", () => {
+ const cwd = tempDir("codex-lsp-cwd-");
+ const codexHome = tempDir("codex-lsp-home-");
+
+ const context = codexLspRequestContext({ CODEX_HOME: codexHome }, cwd);
+
+ expect(context).toEqual({
+ cwd: realpathSync(cwd),
+ projectConfigPaths: [path.join(realpathSync(cwd), ".codex", "lsp-client.json")],
+ userConfigPath: path.join(codexHome, "lsp-client.json"),
+ installDecisionsPath: path.join(codexHome, "lsp-install-decisions.json"),
+ capabilities: { installDecisionTool: true },
+ });
+ });
+
it("extracts files from Codex apply_patch command payloads", () => {
const paths = extractMutatedFilePaths({
tool_name: "apply_patch",
@@ -174,7 +190,7 @@ describe("codex PostToolUse hook", () => {
return "error[typescript] (2322) at 1:7: Type 'number' is not assignable to type 'string'.";
}
if (filePath === "README.md") {
- return "No LSP server configured for extension: .md";
+ return markdownNotConfigured();
}
return "No diagnostics found";
},
@@ -286,7 +302,7 @@ describe("codex PostToolUse hook", () => {
},
tool_response: "Success. Updated files.",
},
- async () => "No LSP server configured for extension: .md",
+ async () => markdownNotConfigured(),
);
expect(output).toBe("");
@@ -356,3 +372,13 @@ function isPostToolUseHookOutput(value: unknown): value is PostToolUseHookOutput
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+
+function tempDir(prefix: string): string {
+ const dir = mkdtempSync(path.join(tmpdir(), prefix));
+ tempDirs.push(dir);
+ return dir;
+}
+
+function markdownNotConfigured(): PostEditDiagnosticsOutcome {
+ return { kind: "not_configured", extension: ".md" };
+}
diff --git a/plugins/omo/components/lsp/test/package-smoke.test.ts b/plugins/omo/components/lsp/test/package-smoke.test.ts
index d1ff7d6f..c56657e1 100644
--- a/plugins/omo/components/lsp/test/package-smoke.test.ts
+++ b/plugins/omo/components/lsp/test/package-smoke.test.ts
@@ -31,11 +31,12 @@ describe("plugin package metadata", () => {
expect(packageJson.type).toBe("module");
expect(packageJson.packageManager).toBe("[email protected]");
expect(packageJson.dependencies).toEqual({
+ "@oh-my-opencode/lsp-core": "file:../../../../lsp-core",
"@code-yeongyu/lsp-daemon": "file:../../../../lsp-daemon",
});
expect(packageJson.bin["omo-lsp"]).toBe("./dist/cli.js");
expect(packageJson.bin["codex-lsp"]).toBeUndefined();
- expect(scripts["build"]).toBe("node scripts/clean-dist.mjs && tsc -p tsconfig.build.json");
+ expect(scripts["build"]).toBe("node scripts/build-runtime.mjs");
expect(scripts["pretest"]).toBe("npm run build --silent");
expect(cliSource.startsWith("#!/usr/bin/env node")).toBe(true);
expect(cliSource).toContain("Usage: omo-lsp [mcp | hook post-tool-use | hook post-compact]");
@@ -45,15 +46,28 @@ describe("plugin package metadata", () => {
expect(lspServer?.args).toEqual(["../../../../lsp-daemon/dist/cli.js", "mcp"]);
expect(cliSource).not.toContain("./lazy-lsp-mcp.js");
expect(cliSource).toContain("resolveLspDaemonCliPath");
- expect(daemonCliPathSource).toContain("@code-yeongyu/lsp-daemon/dist/cli.js");
+ expect(daemonCliPathSource).toContain("@code-yeongyu/lsp-daemon/cli");
expect(daemonCliPathSource).toContain("../../lsp-daemon/dist/cli.js");
- expect(daemonCliPathSource).toContain("CODEX_LSP_DAEMON_VERSION");
+ expect(daemonCliPathSource).toContain("OMO_LSP_DAEMON_VERSION");
expect(cliSource).not.toContain("../../../../../lsp-daemon/dist/cli.js");
expect(codexHookSource).toContain("ensureLspDaemonCliEnv");
- expect(codexHookCliSource).toContain("@code-yeongyu/lsp-daemon");
- expect(codexHookSource).toContain("@code-yeongyu/lsp-daemon");
+ expect(codexHookCliSource).not.toContain("@code-yeongyu/lsp-daemon");
+ expect(codexHookSource).toContain("@code-yeongyu/lsp-daemon/client");
+ expect(codexHookSource).toContain("@oh-my-opencode/lsp-core/post-edit");
+ expect(codexHookSource).toContain("CODEX_HOME");
expect(codexHookCliSource).not.toContain("../../../../../lsp-daemon");
expect(codexHookSource).not.toContain("../../../../../lsp-daemon");
expect(sourceFiles.filter((name) => name.startsWith("lazy-mcp") || name === "lazy-lsp-mcp.ts")).toEqual([]);
});
+
+ it("#given built component CLI #when runtime imports are inspected #then it is self-contained except Node builtins", () => {
+ const cliSource = readTextFile("dist/cli.js");
+ const imports = [
+ ...cliSource.matchAll(/\bimport\s+(?:[^'";]+?\s+from\s+)?["']([^"']+)["']/g),
+ ...cliSource.matchAll(/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g),
+ ].flatMap((match) => (match[1] === undefined ? [] : [match[1]]));
+ expect(imports.filter((specifier) => !specifier.startsWith("node:"))).toEqual([]);
+ expect(cliSource).not.toContain("@code-yeongyu/lsp-daemon/client");
+ expect(cliSource).not.toContain("@oh-my-opencode/lsp-core");
+ });
});
diff --git a/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-5.5.md b/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-5.5.md
index 0a68e90f..11b7ac0f 100644
--- a/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-5.5.md
+++ b/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-5.5.md
@@ -74,7 +74,7 @@ Diagnostics catch type errors, not logic bugs; tests cover only what their autho
# Global Review and Debugging Gate
-Run `review-work` plus a `debugging` runtime audit only before a PR handoff or when the user asks for a review; lane pass/fail semantics live in those skills. For everything else, the gate above is the whole gate: once you have personally observed the artifact working, report your evidence. Redact secrets, tokens, and PII from ledgers, PR bodies, and handoffs.
+Run `review-work` plus a `debugging` runtime audit only before a PR handoff or when the user asks for a review; lane pass/fail semantics live in those skills. A passing review lane binds to the exact commit SHA it reviewed: NEVER re-run a lane at a SHA where that same lane already passed this task; every lane that has not passed at the current SHA still runs. For everything else, the gate above is the whole gate: once you have personally observed the artifact working, report your evidence. Redact secrets, tokens, and PII from ledgers, PR bodies, and handoffs.
# Failure Recovery
diff --git a/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-5.6.md b/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-5.6.md
index da661ca9..ebda5ce8 100644
--- a/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-5.6.md
+++ b/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-5.6.md
@@ -52,7 +52,7 @@ Diagnostics catch type errors, not logic bugs; tests cover only what their autho
"This should work" from reading source does not pass. A defect found in usage is yours to fix this turn.
-Run `review-work` plus a `debugging` runtime audit only before a PR handoff or when the user asks for a review; lane pass/fail semantics live in those skills. For everything else, the gate above is the whole gate: once you have personally observed the artifact working, report your evidence. Redact secrets, tokens, and PII from ledgers, PR bodies, and handoffs.
+Run `review-work` plus a `debugging` runtime audit only before a PR handoff or when the user asks for a review; lane pass/fail semantics live in those skills. A passing review lane binds to the exact commit SHA it reviewed: NEVER re-run a lane at a SHA where that same lane already passed this task; every lane that has not passed at the current SHA still runs. For everything else, the gate above is the whole gate: once you have personally observed the artifact working, report your evidence. Redact secrets, tokens, and PII from ledgers, PR bodies, and handoffs.
# Failure Recovery
diff --git a/plugins/omo/components/rules/hooks/hooks.json b/plugins/omo/components/rules/hooks/hooks.json
index ab8a0a1e..67d737d2 100644
--- a/plugins/omo/components/rules/hooks/hooks.json
+++ b/plugins/omo/components/rules/hooks/hooks.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Loading Project Rules"
+ "statusMessage": "(OmO 4.18.1) Loading Project Rules"
}
]
}
@@ -19,7 +19,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Loading Project Rules"
+ "statusMessage": "(OmO 4.18.1) Loading Project Rules"
}
]
}
@@ -32,7 +32,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Matching Project Rules"
+ "statusMessage": "(OmO 4.18.1) Matching Project Rules"
}
]
}
@@ -45,7 +45,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Resetting Project Rule Cache"
+ "statusMessage": "(OmO 4.18.1) Resetting Project Rule Cache"
}
]
}
diff --git a/plugins/omo/components/rules/package.json b/plugins/omo/components/rules/package.json
index b41a94c1..8255deba 100644
--- a/plugins/omo/components/rules/package.json
+++ b/plugins/omo/components/rules/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-rules",
- "version": "4.18.0",
+ "version": "4.18.1",
"description": "Codex plugin that injects project rule files into model context through lifecycle hooks.",
"type": "module",
"packageManager": "[email protected]",
diff --git a/plugins/omo/components/start-work-continuation/directive.md b/plugins/omo/components/start-work-continuation/directive.md
index 1baead5a..d24b9325 100644
--- a/plugins/omo/components/start-work-continuation/directive.md
+++ b/plugins/omo/components/start-work-continuation/directive.md
@@ -40,7 +40,7 @@ You are mid-flight on a Prometheus work plan; this turn is an automatic continua
# Final gate
-Before completion, run `review-work` and a `debugging` runtime audit; inconclusive lanes fail. Do not create a PR, PR handoff, branch handoff, merge, or final completion answer until this gate passes. For PR/branch work, stay in the task-owned worktree: create/update the PR, wait for CI/review/Cubic gates, merge by default unless explicitly opted out, then clean up. Redact secrets, tokens, credentials, auth headers, cookies, env dumps, logs, and PII.
+Before completion, run `review-work` and a `debugging` runtime audit; inconclusive lanes fail. The gate's pass binds to the commit SHA it reviewed — never re-run it on an already-passed SHA; re-run only when new commits land. Do not create a PR, PR handoff, branch handoff, merge, or final completion answer until this gate passes. For PR/branch work, stay in the task-owned worktree: create/update the PR, wait for CI/review/Cubic gates, merge by default unless explicitly opted out, then clean up. Redact secrets, tokens, credentials, auth headers, cookies, env dumps, logs, and PII.
# Stop conditions for THIS turn
diff --git a/plugins/omo/components/start-work-continuation/hooks/hooks.json b/plugins/omo/components/start-work-continuation/hooks/hooks.json
index 20d5df9e..3fa77314 100644
--- a/plugins/omo/components/start-work-continuation/hooks/hooks.json
+++ b/plugins/omo/components/start-work-continuation/hooks/hooks.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook stop",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Checking Start-Work Continuation"
+ "statusMessage": "(OmO 4.18.1) Checking Start-Work Continuation"
}
]
}
@@ -19,7 +19,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook subagent-stop",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Checking Start-Work Continuation"
+ "statusMessage": "(OmO 4.18.1) Checking Start-Work Continuation"
}
]
}
diff --git a/plugins/omo/components/start-work-continuation/package.json b/plugins/omo/components/start-work-continuation/package.json
index 9133bd9d..ffa9ab6a 100644
--- a/plugins/omo/components/start-work-continuation/package.json
+++ b/plugins/omo/components/start-work-continuation/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-start-work-continuation",
- "version": "4.18.0",
+ "version": "4.18.1",
"description": "Codex Stop hook continuation injector for omo-codex start-work plans.",
"type": "module",
"packageManager": "[email protected]",
diff --git a/plugins/omo/components/teammode/hooks/hooks.json b/plugins/omo/components/teammode/hooks/hooks.json
index 28fb230e..2ccbdafa 100644
--- a/plugins/omo/components/teammode/hooks/hooks.json
+++ b/plugins/omo/components/teammode/hooks/hooks.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Checking Thread Title Hygiene"
+ "statusMessage": "(OmO 4.18.1) Checking Thread Title Hygiene"
}
]
}
diff --git a/plugins/omo/components/teammode/package.json b/plugins/omo/components/teammode/package.json
index 98c0ee7f..9f904923 100644
--- a/plugins/omo/components/teammode/package.json
+++ b/plugins/omo/components/teammode/package.json
@@ -1,6 +1,6 @@
{
"name": "@sisyphuslabs/codex-teammode",
- "version": "4.18.0",
+ "version": "4.18.1",
"description": "Codex team-mode hook component that keeps background thread titles descriptive after create_thread.",
"type": "module",
"private": true,
diff --git a/plugins/omo/components/telemetry/hooks/hooks.json b/plugins/omo/components/telemetry/hooks/hooks.json
index afdb0b2b..5c4bedbb 100644
--- a/plugins/omo/components/telemetry/hooks/hooks.json
+++ b/plugins/omo/components/telemetry/hooks/hooks.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Recording Session Telemetry"
+ "statusMessage": "(OmO 4.18.1) Recording Session Telemetry"
}
]
}
diff --git a/plugins/omo/components/telemetry/package.json b/plugins/omo/components/telemetry/package.json
index cf1ec03a..d961a029 100644
--- a/plugins/omo/components/telemetry/package.json
+++ b/plugins/omo/components/telemetry/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-telemetry",
- "version": "4.18.0",
+ "version": "4.18.1",
"description": "Codex plugin component that emits omo-codex anonymous daily-active telemetry on SessionStart.",
"type": "module",
"packageManager": "[email protected]",
diff --git a/plugins/omo/components/ultrawork/hooks/hooks.json b/plugins/omo/components/ultrawork/hooks/hooks.json
index 09e2d27d..a6b8e3f2 100644
--- a/plugins/omo/components/ultrawork/hooks/hooks.json
+++ b/plugins/omo/components/ultrawork/hooks/hooks.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Checking Ultrawork Trigger"
+ "statusMessage": "(OmO 4.18.1) Checking Ultrawork Trigger"
}
]
}
diff --git a/plugins/omo/components/ultrawork/package.json b/plugins/omo/components/ultrawork/package.json
index a9497a22..9c683ca0 100644
--- a/plugins/omo/components/ultrawork/package.json
+++ b/plugins/omo/components/ultrawork/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-ultrawork",
- "version": "4.18.0",
+ "version": "4.18.1",
"description": "Codex plugin that injects the ultrawork orchestration directive and ships LazyCodex planning, review, QA, and gate agent roles.",
"type": "module",
"packageManager": "[email protected]",
diff --git a/plugins/omo/components/ulw-loop/hooks/hooks.json b/plugins/omo/components/ulw-loop/hooks/hooks.json
index 59ce08a7..1ba2155e 100644
--- a/plugins/omo/components/ulw-loop/hooks/hooks.json
+++ b/plugins/omo/components/ulw-loop/hooks/hooks.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit --with-ultrawork",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Checking Ulw-Loop Steering"
+ "statusMessage": "(OmO 4.18.1) Checking Ulw-Loop Steering"
}
]
}
@@ -20,7 +20,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Enforcing Unlimited Ulw-Loop Budget"
+ "statusMessage": "(OmO 4.18.1) Enforcing Unlimited Ulw-Loop Budget"
}
]
},
@@ -31,7 +31,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use-spawn",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Guarding Ulw-Loop Spawns"
+ "statusMessage": "(OmO 4.18.1) Guarding Ulw-Loop Spawns"
}
]
}
@@ -43,7 +43,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook stop",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Checking Ulw-Loop Resume"
+ "statusMessage": "(OmO 4.18.1) Checking Ulw-Loop Resume"
}
]
}
diff --git a/plugins/omo/components/ulw-loop/package.json b/plugins/omo/components/ulw-loop/package.json
index 5a6cbadc..3753cd01 100644
--- a/plugins/omo/components/ulw-loop/package.json
+++ b/plugins/omo/components/ulw-loop/package.json
@@ -1,6 +1,6 @@
{
"name": "@code-yeongyu/codex-ulw-loop",
- "version": "4.18.0",
+ "version": "4.18.1",
"description": "Codex plugin: durable repo-native multi-goal orchestration with embedded success criteria and observable evidence audit.",
"type": "module",
"packageManager": "[email protected]",
diff --git a/plugins/omo/components/ulw-loop/skills/ulw-loop/SKILL.md b/plugins/omo/components/ulw-loop/skills/ulw-loop/SKILL.md
index 29b36dfa..d78cfcd8 100644
--- a/plugins/omo/components/ulw-loop/skills/ulw-loop/SKILL.md
+++ b/plugins/omo/components/ulw-loop/skills/ulw-loop/SKILL.md
@@ -23,7 +23,7 @@ This skill is intentionally compact. The full workflow lives in `references/full
- After any compaction or context loss, re-read brief + goals + ledger FIRST plus `omo ulw-loop status --json`, then resume; never re-plan from scratch.
- If `omo ulw-loop create-goals` says the existing aggregate is already complete, start unrelated new work with a fresh `--session-id <new-id>` instead of steering or forcing the completed default state. Use `--force` only to intentionally overwrite completed evidence.
- Every success criterion needs observable evidence from a real surface: a channel (terminal/TUI via the xterm.js web terminal, HTTP, browser, computer-use) or, for CLI- or data-shaped criteria, an auxiliary surface (CLI stdout, DB diff, parsed config dump).
-- Evidence is bound to its capture commit; a later fix, rebase, or merge makes it stale — re-run at the current HEAD and re-record, never relabel or regenerate. Record only after cleanup receipts exist.
+- Evidence is bound to the tree it was captured at (`git rev-parse --short "HEAD^{tree}"`); it goes stale only when tracked content changes — a rebase or amend that keeps the tree identical keeps it valid. When the tree differs, re-run at the current HEAD and re-record, never relabel or regenerate. Record only after cleanup receipts exist.
- Delegate code edits, test writes, fixes, and QA execution to right-sized Codex subagents when the workflow requires it.
- Every `spawn_agent` message starts with `TASK:`, then names `DELIVERABLE`, `SCOPE`, and `VERIFY`; put role and specialty instructions inside `message`; use `fork_turns: "none"` (v1: `fork_context: false`) unless full history is truly required.
- Plan and reviewer agents may run for a long time; spawn them in the background and keep doing independent root work. Between `wait_agent` calls, back off — double the timeout up to ~5 minutes — instead of spinning short cycles.
diff --git a/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.md b/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.md
index 9d4972fa..1ba6a194 100644
--- a/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.md
+++ b/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.md
@@ -165,9 +165,9 @@ Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures a
5. EXECUTE-AS-SCENARIO: ACTUALLY run the Manual-QA scenario the criterion named (channel table above). Run it yourself for the orchestrator check; for heavier flows dispatch a dedicated QA execution worker (`lazycodex-worker-medium` by default; `lazycodex-worker-high` when the QA flow itself is hard) whose ONLY job is to drive the channel and write the artifact to the named evidence path. If the scenario FAILS, respawn the implementing worker with the captured failure — do not hand-patch around it.
6. CAPTURE: collect the observable artifact path: transcript, stdout, screenshot, assertion, status+body, diff, or parsed dump. No artifact written at the evidence path — not done; record BLOCKED and respawn QA.
7. CLEAN (PAIRED, NEVER SKIP): tear down every runtime artifact step 5 spawned BEFORE recording — server PIDs (`kill`, verify `kill -0` fails), `tmux` sessions (`tmux kill-session -t ulw-qa-<criterion>`; confirm `tmux ls`), browser / Playwright contexts (`.close()`), containers (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env vars, AND close every finished worker (v1 `close_agent`; on V2 finished workers end on their own — `interrupt_agent` any still running). Register each teardown as its own todo the moment the QA spawns the resource (scripts, tmux assets, browsers / agent-browser sessions, PIDs, ports) so none is forgotten. Embed a one-line cleanup receipt in the evidence string, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo; rm -rf /tmp/ulw.aB12cD; interrupt_agent w-3`. Missing receipt → record BLOCKED, not PASS.
-8. RECORD one result immediately from the artifact you just wrote — never from memory or a later turn — stamping the capture commit `$(git rev-parse --short HEAD)` into the evidence:
- - PASS: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status pass --evidence "<observable> @<short-sha> | <cleanup receipt>" --json`
- - FAIL: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status fail --evidence "<observable> @<short-sha> | <cleanup receipt>" --notes "<diagnosis>" --json`
+8. RECORD one result immediately from the artifact you just wrote — never from memory or a later turn — stamping the capture tree `$(git rev-parse --short "HEAD^{tree}")` into the evidence:
+ - PASS: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status pass --evidence "<observable> @tree:<short-tree> | <cleanup receipt>" --json`
+ - FAIL: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status fail --evidence "<observable> @tree:<short-tree> | <cleanup receipt>" --notes "<diagnosis>" --json`
- BLOCKED: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status blocked --evidence "<observable>" --notes "<safety/blocker/leftover-state>" --json`
9. If actual does not match expected, diagnose, respawn the right-sized worker with the failure context to fix minimally, and rerun the SAME criterion (including a fresh cleanup).
10. After 3 same-criterion failures, exit the goal with diagnosis.
@@ -184,9 +184,10 @@ Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures a
## Final Quality Gate
Trigger only for the final aggregate goal after every criterion in every goal is `pass`.
1. Run targeted verification for changed behavior.
-2. FREEZE first — no more edits or rebases. At the frozen `git rev-parse HEAD`, re-run Manual-QA for any PASS criterion whose stamped commit is not HEAD, so every criterion is proven at HEAD; each artifact exists and is non-empty.
+2. FREEZE first — no more edits or rebases. At the frozen HEAD, re-run Manual-QA for any PASS criterion whose stamped tree differs from `git rev-parse --short "HEAD^{tree}"`, so every criterion is proven on the frozen tree; each artifact exists and is non-empty.
3a. Spawn lazycodex-code-reviewer and lazycodex-qa-executor in parallel (`fork_context: false` on v1; `fork_turns: "none"` on v2) with brief, goals, desired outcome, diff, evidence; wait for BOTH and confirm their report artifacts exist on disk.
3b. Only then spawn lazycodex-gate-reviewer with those artifact paths.
+3c. The gate's approval binds to the frozen tree and covers its three lanes — code quality, hands-on QA, and goal verification. A later rebase or amend that keeps the tree identical keeps the approval; changed content needs fresh review of the delta.
4. Treat timeout, missing deliverable, ack-only, `BLOCKED:`, or inconclusive review as a blocker. Any fix restarts the freeze at the new HEAD: re-run ONLY the proofs it invalidated and stamp the fresh output — never regenerate all evidence or relabel stale output to HEAD — re-review the delta at most TWICE; then record-review-blockers (step 5) and surface to the user.
5. If review remains blocked, run `omo ulw-loop record-review-blockers --goal-id <id> --title "<...>" --objective "<...>" --evidence "<review findings>" --codex-goal-json <snapshot> --json`.
6. If clean, checkpoint final completion:
@@ -224,7 +225,7 @@ Structured prompt directives accepted: `OMO_ULW_LOOP_STEER: { ... }`, `omo.ulw-l
## Constraints
1. NEVER call `update_goal` mid-aggregate; only on final story after the quality gate passes.
2. NEVER call `create_goal` when `get_goal` shows a different active goal.
-3. Evidence is bound to the commit it was captured at; a later fix, rebase, or merge invalidates it — re-run the QA at the current HEAD and re-record. NEVER mark PASS from memory, and NEVER relabel, pin, refresh, or regenerate prior output to a moved HEAD.
+3. Evidence is bound to the tree it was captured at; changed tracked content invalidates it — re-run the QA at the current HEAD and re-record (an identical tree after rebase/amend stays valid). NEVER mark PASS from memory, and NEVER relabel, pin, refresh, or regenerate prior output to a moved HEAD.
4. NEVER bypass the criteria gate: non-final aggregate completion requires all essential criteria; final aggregate completion requires all criteria across the whole plan.
5. Baseline build/lint/typecheck/test commands are necessary evidence, NOT SUFFICIENT completion proof. Criteria coverage with observable evidence is the gate.
6. Treat `.omo/ulw-loop/ledger.jsonl` as the durable audit trail; checkpoint after every success or failure.
diff --git a/plugins/omo/dist/cli-node/index.js b/plugins/omo/dist/cli-node/index.js
index 85c09268..2fca9678 100755
--- a/plugins/omo/dist/cli-node/index.js
+++ b/plugins/omo/dist/cli-node/index.js
@@ -2146,7 +2146,7 @@ var package_default;
var init_package = __esm(() => {
package_default = {
name: "oh-my-opencode",
- version: "4.18.0",
+ version: "4.18.1",
description: "The Best AI Agent Harness - Batteries-Included OpenCode Plugin with Multi-Model Orchestration, Parallel Background Agents, and Crafted LSP/AST Tools",
main: "./dist/index.js",
types: "dist/index.d.ts",
@@ -2255,7 +2255,8 @@ var init_package = __esm(() => {
"build:codex-install": "bun run script/build-codex-install.ts",
"install:codex-dev": "bun run script/build-codex-install.ts && bun run script/install-codex-dev.ts",
"build:codex-plugin": "npm --prefix packages/omo-codex/plugin ci && bun run --cwd packages/omo-codex/plugin build",
- "build:senpi-plugin": "node packages/omo-senpi/plugin/scripts/build-extension.mjs && node packages/omo-senpi/plugin/scripts/sync-skills.mjs && node packages/omo-senpi/plugin/scripts/embed-directive.mjs --check",
+ "build:senpi-plugin": "bun run build:lsp-daemon && bun run build:senpi-plugin:stage",
+ "build:senpi-plugin:stage": "node packages/omo-senpi/plugin/scripts/stage-lsp-daemon-runtime.mjs && node packages/omo-senpi/plugin/scripts/build-extension.mjs && node packages/omo-senpi/plugin/scripts/sync-skills.mjs && node packages/omo-senpi/plugin/scripts/embed-directive.mjs --check && node packages/omo-senpi/plugin/scripts/build-install.mjs",
"build:materialize-frontend": "node packages/omo-codex/plugin/scripts/materialize-shared-upstreams.mjs --strict",
"build:shared-skills-assets": "bun run build:materialize-frontend && rm -rf dist/skills && cp -R packages/shared-skills/skills dist/skills",
"build:lsp-tools-mcp": "npm --prefix packages/lsp-tools-mcp ci && npm --prefix packages/lsp-tools-mcp run build",
@@ -2277,7 +2278,7 @@ var init_package = __esm(() => {
"typecheck:script": "tsgo --noEmit -p script/tsconfig.json",
test: "bun test",
"test:codex": "bun run build:codex-install && bun run build:git-bash-mcp && bun run build:lsp-tools-mcp && bun run build:lsp-daemon && npm --prefix packages/lsp-tools-mcp test && npm --prefix packages/omo-codex/plugin ci && npm --prefix packages/omo-codex/plugin/components/ulw-loop test && bun run --cwd packages/omo-codex/plugin build && npm --prefix packages/omo-codex/plugin/components/codegraph run typecheck && npm --prefix packages/omo-codex/plugin/components/codegraph test && node scripts/check-third-party-notices.mjs --ship && bun test packages/omo-opencode/src/cli/cli-installer.platform.test.ts packages/omo-codex/src/install/codex-cache.test.ts packages/omo-codex/src/install/codex-cleanup.test.ts packages/omo-codex/src/install/codex-config-agent-cleanup.test.ts packages/omo-codex/src/install/codex-config-autonomous-features.test.ts packages/omo-codex/src/install/codex-config-reasoning.test.ts packages/omo-codex/src/install/codex-config-toml.test.ts packages/omo-codex/src/install/codex-project-local-cleanup.test.ts packages/omo-codex/src/install/install-codex-project-local-cleanup.test.ts packages/omo-codex/src/install/install-codex.test.ts packages/omo-codex/src/install/install-codex-packaged.test.ts packages/omo-codex/src/install/link-cached-plugin-agents.test.ts packages/omo-codex/src/**/*.test.ts packages/utils/src/jsonc-parser.test.ts packages/utils/src/frontmatter.test.ts packages/hashline-core/src/hash-computation.test.ts packages/hashline-core/src/smoke-untested-modules.test.ts packages/rules-engine/src/index.test.ts packages/rules-engine/src/security-boundary.test.ts packages/agents-md-core/src/injector.test.ts packages/omo-codex/plugin/components/lsp/test/package-smoke.test.ts && node --test packages/omo-codex/plugin/test/*.test.mjs packages/omo-codex/scripts/install-cache-copy.test.mjs packages/omo-codex/scripts/install-cli-args.test.mjs packages/omo-codex/scripts/install-delegated-command.test.mjs packages/omo-codex/scripts/install-config-autonomous-features.test.mjs packages/omo-codex/scripts/install-config-autonomous.test.mjs packages/omo-codex/scripts/install-config-reasoning.test.mjs packages/omo-codex/scripts/install-config.test.mjs packages/omo-codex/scripts/install-hook-targets.test.mjs packages/omo-codex/scripts/install-project-local-cleanup.test.mjs packages/omo-codex/scripts/install-lazycodex-version-stamp.test.mjs packages/omo-codex/scripts/install-local-entrypoint.test.mjs packages/omo-codex/scripts/install-local-git-bash-preflight.test.mjs packages/omo-codex/scripts/install-local.test.mjs packages/omo-codex/scripts/install-marketplace-cache.test.mjs packages/omo-codex/scripts/install-mcp-context7-runtime.test.mjs packages/omo-codex/scripts/install-mcp-runtime.test.mjs packages/omo-codex/scripts/install-packaged-local.test.mjs packages/omo-codex/scripts/install-generated-bundle.test.mjs packages/omo-codex/scripts/install-agent-links.test.mjs packages/omo-codex/scripts/install-bin-links.test.mjs",
- "test:senpi": "node packages/omo-senpi/plugin/scripts/build-extension.mjs && node packages/omo-senpi/plugin/scripts/sync-skills.mjs && node packages/omo-senpi/plugin/scripts/embed-directive.mjs --check && bun test packages/omo-senpi",
+ "test:senpi": "bun run build:senpi-plugin && tsgo --noEmit -p packages/omo-senpi/tsconfig.json && bun test packages/omo-senpi",
"test:windows-codex": "bun run test:codex",
"build:git-bash-mcp": "bun run --cwd packages/git-bash-mcp build"
},
@@ -2317,7 +2318,6 @@ var init_package = __esm(() => {
picocolors: "^1.1.1",
picomatch: "^4.0.4",
"posthog-node": "^5.34.3",
- "vscode-jsonrpc": "^8.2.1",
zod: "^4.4.3"
},
devDependencies: {
@@ -2358,18 +2358,18 @@ var init_package = __esm(() => {
typescript: "^6.0.3"
},
optionalDependencies: {
- "oh-my-opencode-darwin-arm64": "4.18.0",
- "oh-my-opencode-darwin-x64": "4.18.0",
- "oh-my-opencode-darwin-x64-baseline": "4.18.0",
- "oh-my-opencode-linux-arm64": "4.18.0",
- "oh-my-opencode-linux-arm64-musl": "4.18.0",
- "oh-my-opencode-linux-x64": "4.18.0",
- "oh-my-opencode-linux-x64-baseline": "4.18.0",
- "oh-my-opencode-linux-x64-musl": "4.18.0",
- "oh-my-opencode-linux-x64-musl-baseline": "4.18.0",
- "oh-my-opencode-windows-arm64": "4.18.0",
- "oh-my-opencode-windows-x64": "4.18.0",
- "oh-my-opencode-windows-x64-baseline": "4.18.0"
+ "oh-my-opencode-darwin-arm64": "4.18.1",
+ "oh-my-opencode-darwin-x64": "4.18.1",
+ "oh-my-opencode-darwin-x64-baseline": "4.18.1",
+ "oh-my-opencode-linux-arm64": "4.18.1",
+ "oh-my-opencode-linux-arm64-musl": "4.18.1",
+ "oh-my-opencode-linux-x64": "4.18.1",
+ "oh-my-opencode-linux-x64-baseline": "4.18.1",
+ "oh-my-opencode-linux-x64-musl": "4.18.1",
+ "oh-my-opencode-linux-x64-musl-baseline": "4.18.1",
+ "oh-my-opencode-windows-arm64": "4.18.1",
+ "oh-my-opencode-windows-x64": "4.18.1",
+ "oh-my-opencode-windows-x64-baseline": "4.18.1"
},
overrides: {
"@earendil-works/pi-agent-core": "0.80.3",
@@ -66851,14 +66851,14 @@ var init_config_manager = __esm(() => {
// packages/telemetry-core/src/activity-state.ts
import { existsSync as existsSync28, mkdirSync as mkdirSync8, readFileSync as readFileSync14 } from "node:fs";
-import { basename as basename10, join as join53 } from "node:path";
+import { basename as basename11, join as join53 } from "node:path";
function resolveTelemetryStateDir(product, options = {}) {
const dataDir = resolveXdgDataDir(product.cacheDirName, {
env: options.env,
osProvider: options.osProvider
});
const xdgStateDir = options.env?.XDG_DATA_HOME === undefined ? undefined : join53(options.env.XDG_DATA_HOME, product.cacheDirName);
- if (dataDir === xdgStateDir || xdgStateDir === undefined && basename10(dataDir) === product.cacheDirName) {
+ if (dataDir === xdgStateDir || xdgStateDir === undefined && basename11(dataDir) === product.cacheDirName) {
return dataDir;
}
return join53(dataDir, product.cacheDirName);
@@ -67092,18 +67092,18 @@ var init_env2 = __esm(() => {
});
// packages/telemetry-core/src/machine-id.ts
-import { createHash as createHash3 } from "node:crypto";
+import { createHash as createHash4 } from "node:crypto";
import os4 from "node:os";
function getDefaultTelemetryOsProvider() {
return os4;
}
function getTelemetryDistinctId(machineIdPrefix, osProvider = getDefaultTelemetryOsProvider()) {
- return createHash3("sha256").update(`${machineIdPrefix}${osProvider.hostname()}`).digest("hex");
+ return createHash4("sha256").update(`${machineIdPrefix}${osProvider.hostname()}`).digest("hex");
}
var init_machine_id = () => {};
// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
-import { dirname as dirname18, posix as posix2, sep as sep7 } from "path";
+import { dirname as dirname18, posix as posix3, sep as sep7 } from "path";
function createModulerModifier() {
const getModuleFromFileName = createGetModuleFromFilename();
return async (frames) => {
@@ -67118,7 +67118,7 @@ function createGetModuleFromFilename(basePath = process.argv[1] ? dirname18(proc
if (!filename)
return;
const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;
- let { dir, base: file2, ext } = posix2.parse(normalizedFilename);
+ let { dir, base: file2, ext } = posix3.parse(normalizedFilename);
if (ext === ".js" || ext === ".mjs" || ext === ".cjs")
file2 = file2.slice(0, -1 * ext.length);
const decodedFile = decodeURIComponent(file2);
@@ -72658,7 +72658,7 @@ var package_default2;
var init_package2 = __esm(() => {
package_default2 = {
name: "@oh-my-opencode/omo-codex",
- version: "4.18.0",
+ version: "4.18.1",
type: "module",
private: true,
description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",
@@ -73477,18 +73477,18 @@ function removeFromTextBunLock(lockPath, packageNames) {
try {
const content = fs12.readFileSync(lockPath, "utf-8");
const lock = JSON.parse(stripTrailingCommas(content));
- let removed = false;
+ let removed2 = false;
for (const packageName of packageNames) {
if (lock.packages?.[packageName]) {
delete lock.packages[packageName];
log2(`[auto-update-checker] Removed from bun.lock: ${packageName}`);
- removed = true;
+ removed2 = true;
}
}
- if (removed) {
+ if (removed2) {
fs12.writeFileSync(lockPath, JSON.stringify(lock, null, 2));
}
- return removed;
+ return removed2;
} catch (error51) {
if (!(error51 instanceof Error)) {
throw error51;
@@ -73528,7 +73528,7 @@ function getInvalidationPackageNames(packageName, defaultPackageName, acceptedPa
function removeSpecifierRootDirs(cacheDir, packageNames) {
const parentDirs = [cacheDir, path13.join(cacheDir, "packages")];
const prefixes = packageNames.map((packageName) => `${packageName}@`);
- let removed = false;
+ let removed2 = false;
for (const parentDir of parentDirs) {
if (!fs12.existsSync(parentDir)) {
continue;
@@ -73540,10 +73540,10 @@ function removeSpecifierRootDirs(cacheDir, packageNames) {
const specifierDir = path13.join(parentDir, entry.name);
fs12.rmSync(specifierDir, { recursive: true, force: true });
log2(`[auto-update-checker] Specifier cache removed: ${specifierDir}`);
- removed = true;
+ removed2 = true;
}
}
- return removed;
+ return removed2;
}
function invalidatePackage(packageName, options = {}) {
try {
@@ -77843,65 +77843,297 @@ function formatUnknownError(error) {
}
// packages/omo-codex/src/install/lsp-daemon-reaper.ts
-import { readFile as readFile18, readdir as readdir9, rm as rm10 } from "node:fs/promises";
+import { createHash as createHash3 } from "node:crypto";
+import { lstat as lstat11, readFile as readFile19, readdir as readdir10, rm as rm10 } from "node:fs/promises";
+import { tmpdir as tmpdir3 } from "node:os";
+import { join as join48, posix as posix2 } from "node:path";
+
+// packages/omo-codex/src/install/lsp-daemon-reaper-attestation.ts
+import { execFile as execFile2 } from "node:child_process";
+import { readFile as readFile18, readdir as readdir9, readlink as readlink5 } from "node:fs/promises";
import { connect } from "node:net";
-import { join as join48 } from "node:path";
-async function reapLspDaemons(codexHome, deps = {}) {
- const killProcess = deps.killProcess ?? sendSigterm;
- const isDaemonLive = deps.isDaemonLive ?? probeSocketLive;
- const daemonRoot = join48(codexHome, "codex-lsp", "daemon");
- const reaped = [];
- let entries;
+import { basename as basename10 } from "node:path";
+var PROBE_TIMEOUT_MS = 500;
+async function probeLegacyJsonRpcEndpoint(endpoint, timeoutMs = PROBE_TIMEOUT_MS) {
+ return await new Promise((resolve14) => {
+ const socket = connect(endpoint);
+ let settled = false;
+ let buffer = "";
+ const finish = (value) => {
+ if (settled)
+ return;
+ settled = true;
+ clearTimeout(timer);
+ socket.destroy();
+ resolve14(value);
+ };
+ const timer = setTimeout(() => finish(false), timeoutMs);
+ timer.unref?.();
+ socket.once("connect", () => {
+ socket.write(`${JSON.stringify(legacyStatusRequest())}
+`);
+ });
+ socket.on("data", (chunk) => {
+ buffer += chunk.toString("utf8");
+ const newlineIndex = buffer.indexOf(`
+`);
+ if (newlineIndex < 0)
+ return;
+ finish(isJsonRpcResponse(buffer.slice(0, newlineIndex).trim()));
+ });
+ socket.once("error", () => finish(false));
+ });
+}
+async function attestLegacyDaemonOwnership(input, deps = {}) {
+ if (input.platform === "linux")
+ return await attestLinuxOwnership(input, deps);
+ if (input.platform === "darwin")
+ return await attestMacOwnership(input, deps);
+ return false;
+}
+async function attestLinuxOwnership(input, deps) {
+ const readFileImpl = deps.readFile ?? readFile18;
+ const readDirImpl = deps.readDir ?? readdir9;
+ const readLinkImpl = deps.readLink ?? readlink5;
+ const procNetUnix = await readText(readFileImpl, "/proc/net/unix");
+ if (procNetUnix === null)
+ return false;
+ const inode = inodeForEndpoint(procNetUnix, input.endpoint);
+ if (inode === null)
+ return false;
+ const fdEntries = await readDirImpl(`/proc/${input.pid}/fd`).catch(() => null);
+ if (fdEntries === null)
+ return false;
+ let ownsEndpoint = false;
+ for (const fdEntry of fdEntries) {
+ const target = await readLinkImpl(`/proc/${input.pid}/fd/${fdEntry}`).catch(() => null);
+ if (target !== `socket:[${inode}]`)
+ continue;
+ ownsEndpoint = true;
+ break;
+ }
+ if (!ownsEndpoint)
+ return false;
+ const cmdline = await readBinary(readFileImpl, `/proc/${input.pid}/cmdline`);
+ if (cmdline === null)
+ return false;
+ return isNodeCliDaemonArgv(splitCmdline(cmdline));
+}
+async function attestMacOwnership(input, deps) {
+ const executeFileImpl = deps.executeFile ?? execFile2;
+ const filteredLsofOutput = await executeForStdout(executeFileImpl, "/usr/sbin/lsof", [
+ "-a",
+ "-n",
+ "-P",
+ "-p",
+ String(input.pid),
+ "-U",
+ "-Fn",
+ "--",
+ input.endpoint
+ ]);
+ const lsofOutput = filteredLsofOutput ?? await executeForStdout(executeFileImpl, "/usr/sbin/lsof", [
+ "-a",
+ "-n",
+ "-P",
+ "-p",
+ String(input.pid),
+ "-U",
+ "-Fn"
+ ]);
+ if (lsofOutput === null || !lsofShowsUnixEndpoint(lsofOutput, input.pid, input.endpoint))
+ return false;
+ const commandOutput = await executeForStdout(executeFileImpl, "/bin/ps", ["-p", String(input.pid), "-o", "command="]);
+ if (commandOutput === null)
+ return false;
+ return isNodeCliDaemonCommand(commandOutput.trim());
+}
+function legacyStatusRequest() {
+ return {
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: { name: "status", arguments: {} }
+ };
+}
+function isJsonRpcResponse(line) {
+ if (line.length === 0)
+ return false;
try {
- entries = await readdir9(daemonRoot);
+ const parsed = JSON.parse(line);
+ return parsed.jsonrpc === "2.0" && parsed.id === 1 && (Object.hasOwn(parsed, "result") || Object.hasOwn(parsed, "error"));
} catch {
- return reaped;
+ return false;
}
- for (const entry of entries) {
- const versionDir = join48(daemonRoot, entry);
- const pid = await readPidFile(join48(versionDir, "daemon.pid"));
- const socketPath = await readEndpointFile(join48(versionDir, "daemon.endpoint"));
- if (pid !== null && socketPath !== null && await isDaemonLive(socketPath) && killProcess(pid)) {
- reaped.push(pid);
+}
+function inodeForEndpoint(procNetUnix, endpoint) {
+ for (const line of procNetUnix.split(/\r?\n/)) {
+ const trimmed = line.trim();
+ if (trimmed.length === 0 || trimmed.startsWith("Num"))
+ continue;
+ const fields = trimmed.split(/\s+/);
+ if (fields.length < 8 || fields[7] !== endpoint)
+ continue;
+ return fields[6] ?? null;
+ }
+ return null;
+}
+function splitCmdline(buffer) {
+ return buffer.toString("utf8").split("\x00").filter((value) => value.length > 0);
+}
+function isNodeCliDaemonArgv(argv) {
+ if (argv.length < 2 || !argv.includes("daemon"))
+ return false;
+ const executable = basename10(argv[0] ?? "");
+ if (!/^node(?:\.exe)?$/i.test(executable))
+ return false;
+ return argv.some((value) => value === "cli.js" || value.endsWith("/cli.js") || value.endsWith("\\cli.js"));
+}
+function lsofShowsUnixEndpoint(output, pid, endpoint) {
+ const lines = output.split(/\r?\n/).filter((line) => line.length > 0);
+ const endpointName = basename10(endpoint);
+ return lines.includes(`p${pid}`) && lines.some((line) => line === `n${endpoint}` || line === `n${endpointName}`);
+}
+function isNodeCliDaemonCommand(command) {
+ return /\bnode(?:\.exe)?\b/i.test(command) && /\bcli\.js\b/.test(command) && /\bdaemon\b/.test(command);
+}
+async function executeForStdout(executeFileImpl, file2, args) {
+ return await new Promise((resolve14) => {
+ executeFileImpl(file2, [...args], { encoding: "utf8", maxBuffer: 1024 * 1024, timeout: 1000 }, (error, stdout) => {
+ if (error !== null) {
+ resolve14(null);
+ return;
+ }
+ resolve14(stdout);
+ });
+ });
+}
+async function readText(readFileImpl, path7) {
+ return await readFileImpl(path7, "utf8").catch(() => null);
+}
+async function readBinary(readFileImpl, path7) {
+ return await readFileImpl(path7).catch(() => null);
+}
+
+// packages/omo-codex/src/install/lsp-daemon-reaper.ts
+var LEGACY_EXIT_WAIT_TIMEOUT_MS = 5000;
+var LEGACY_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
+async function reapLspDaemons(codexHome, deps = {}) {
+ const daemonRoot = join48(codexHome, "codex-lsp", "daemon");
+ const platform = deps.platform ?? process.platform;
+ const tmpDir = deps.tmpDir ?? tmpdir3();
+ const probe2 = deps.probeLegacyJsonRpc ?? probeLegacyJsonRpcEndpoint;
+ const attest = deps.attestLegacyDaemonOwnership ?? ((input) => attestLegacyDaemonOwnership(input));
+ const killProcess = deps.killProcess ?? sendSigterm;
+ const waitForProcessExit = deps.waitForProcessExit ?? defaultWaitForProcessExit;
+ const entries = await readdir10(daemonRoot, { withFileTypes: true }).catch(() => []);
+ const results = [];
+ for (const entry of [...entries].sort((left, right) => left.name.localeCompare(right.name))) {
+ const versionPath = join48(daemonRoot, entry.name);
+ const parsedVersion = parseVersionEntry(entry.name);
+ if (parsedVersion === null || !entry.isDirectory()) {
+ await removeVersionDir(versionPath);
+ results.push(removed(entry.name, "removed invalid legacy version entry"));
+ continue;
+ }
+ const metadata = await readLegacyMetadata({ versionPath, version: parsedVersion, codexHome, platform, tmpDir });
+ if (metadata.kind === "remove") {
+ await removeVersionDir(versionPath);
+ results.push(removed(parsedVersion, metadata.reason));
+ continue;
+ }
+ if (!await probe2(metadata.endpoint)) {
+ await removeVersionDir(versionPath);
+ results.push(removed(parsedVersion, "removed stale legacy daemon state"));
+ continue;
+ }
+ if (platform === "win32") {
+ results.push(deferred(parsedVersion, "legacy named pipe responded but Windows cannot prove pid ownership safely"));
+ continue;
}
- await rm10(versionDir, { recursive: true, force: true });
+ const owned = await attest({ pid: metadata.pid, endpoint: metadata.endpoint, platform });
+ if (!owned) {
+ results.push(deferred(parsedVersion, "legacy endpoint responded but pid ownership was not proven"));
+ continue;
+ }
+ if (!killProcess(metadata.pid)) {
+ await removeVersionDir(versionPath);
+ results.push(removed(parsedVersion, "removed stale legacy daemon state"));
+ continue;
+ }
+ if (!await waitForProcessExit(metadata.pid, LEGACY_EXIT_WAIT_TIMEOUT_MS)) {
+ results.push(deferred(parsedVersion, `timed out waiting ${LEGACY_EXIT_WAIT_TIMEOUT_MS}ms for the proven legacy daemon to exit`));
+ continue;
+ }
+ await removeVersionDir(versionPath);
+ results.push(terminated(parsedVersion, "terminated proven owned legacy daemon"));
}
- return reaped;
+ return results;
}
-async function readEndpointFile(path7) {
- try {
- const content = (await readFile18(path7, "utf8")).trim();
- return content.length > 0 ? content : null;
- } catch {
+function parseVersionEntry(entryName) {
+ if (!entryName.startsWith("v"))
return null;
+ const version = entryName.slice(1);
+ return LEGACY_VERSION_PATTERN.test(version) ? version : null;
+}
+async function readLegacyMetadata(input) {
+ const pidText = await readRegularTrimmedFile(join48(input.versionPath, "daemon.pid"));
+ if (pidText === "non_regular")
+ return { kind: "remove", reason: "removed non-regular legacy daemon metadata" };
+ if (pidText === null)
+ return { kind: "remove", reason: "removed malformed legacy daemon metadata" };
+ const pid = Number.parseInt(pidText, 10);
+ if (!Number.isInteger(pid) || pid <= 0)
+ return { kind: "remove", reason: "removed malformed legacy daemon metadata" };
+ const endpointText = await readRegularTrimmedFile(join48(input.versionPath, "daemon.endpoint"));
+ if (endpointText === "non_regular")
+ return { kind: "remove", reason: "removed non-regular legacy daemon metadata" };
+ if (endpointText === null)
+ return { kind: "remove", reason: "removed malformed legacy daemon metadata" };
+ const allowedEndpoints = legacyEndpointCandidates({
+ version: input.version,
+ versionPath: input.versionPath,
+ platform: input.platform,
+ tmpDir: input.tmpDir
+ });
+ if (!allowedEndpoints.includes(endpointText)) {
+ return { kind: "remove", reason: "removed legacy daemon state with an endpoint outside the frozen vectors" };
}
+ return { kind: "valid", pid, endpoint: endpointText };
}
-async function readPidFile(path7) {
- try {
- const pid = Number.parseInt((await readFile18(path7, "utf8")).trim(), 10);
- return Number.isInteger(pid) && pid > 0 ? pid : null;
- } catch {
- return null;
+function legacyEndpointCandidates(input) {
+ if (input.platform === "win32") {
+ const normalizedVersionPath = input.versionPath.replaceAll("/", "\\");
+ const digest = shortDigest(normalizedVersionPath);
+ return [`\\\\.\\pipe\\omo-lsp-${input.version}-${digest}`];
}
+ const natural = posix2.join(input.versionPath, "daemon.sock");
+ const hashed = posix2.join(input.tmpDir, `omo-lsp-${input.version}-${shortDigest(input.versionPath)}.sock`);
+ return [natural, hashed];
}
-function probeSocketLive(socketPath, timeoutMs = 500) {
- return new Promise((resolve14) => {
- const socket = connect(socketPath);
- const done = (ok) => {
- socket.destroy();
- resolve14(ok);
- };
- const timer = setTimeout(() => done(false), timeoutMs);
- timer.unref();
- socket.once("connect", () => {
- clearTimeout(timer);
- done(true);
- });
- socket.once("error", () => {
- clearTimeout(timer);
- done(false);
- });
- });
+async function readRegularTrimmedFile(path7) {
+ const stats = await lstat11(path7).catch(() => null);
+ if (stats === null)
+ return null;
+ if (!stats.isFile())
+ return "non_regular";
+ const content = (await readFile19(path7, "utf8")).trim();
+ return content.length > 0 ? content : null;
+}
+function shortDigest(value) {
+ return createHash3("sha256").update(value).digest("hex").slice(0, 16);
+}
+async function removeVersionDir(path7) {
+ await rm10(path7, { recursive: true, force: true });
+}
+function removed(version, reason) {
+ return { version, status: "removed", reason };
+}
+function terminated(version, reason) {
+ return { version, status: "terminated", reason };
+}
+function deferred(version, reason) {
+ return { version, status: "deferred", reason };
}
function sendSigterm(pid) {
try {
@@ -77911,6 +78143,24 @@ function sendSigterm(pid) {
return false;
}
}
+async function defaultWaitForProcessExit(pid, timeoutMs) {
+ const deadline = Date.now() + timeoutMs;
+ for (;; ) {
+ if (!processIsRunning(pid))
+ return true;
+ if (Date.now() >= deadline)
+ return false;
+ await new Promise((resolve14) => setTimeout(resolve14, 100));
+ }
+}
+function processIsRunning(pid) {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
// packages/omo-codex/src/install/codex-installer-bin-dir.ts
import { homedir as homedir5 } from "node:os";
@@ -77928,7 +78178,7 @@ function resolveCodexInstallerBinDir(input) {
}
// packages/omo-codex/src/install/codex-git-bash-hooks.ts
-import { readFile as readFile19, writeFile as writeFile11 } from "node:fs/promises";
+import { readFile as readFile20, writeFile as writeFile11 } from "node:fs/promises";
import { join as join50 } from "node:path";
var WINDOWS_ONLY_GIT_BASH_HOOKS = new Set([
"./hooks/pre-tool-use-recommending-git-bash-mcp.json",
@@ -77938,7 +78188,7 @@ async function removeGitBashHooksOffWindows(input) {
if (input.platform === "win32")
return;
const manifestPath = join50(input.pluginRoot, ".codex-plugin", "plugin.json");
- const parsed = JSON.parse(await readFile19(manifestPath, "utf8"));
+ const parsed = JSON.parse(await readFile20(manifestPath, "utf8"));
if (!isPlainRecord3(parsed) || !Array.isArray(parsed.hooks))
return;
const hooks = parsed.hooks.filter((hook) => typeof hook !== "string" || !WINDOWS_ONLY_GIT_BASH_HOOKS.has(hook));
@@ -78132,7 +78382,16 @@ async function runCodexInstaller(options = {}) {
pluginNames: marketplace.plugins.map((plugin) => plugin.name)
});
}
- await reapLspDaemons(codexHome).catch(() => []);
+ const legacyDaemonCleanup = await reapLspDaemons(codexHome).catch((error) => {
+ const message = error instanceof Error ? error.message : String(error);
+ log4(`Warning: skipped legacy Codex LSP daemon cleanup: ${message}`);
+ return [];
+ });
+ for (const cleanup of legacyDaemonCleanup) {
+ if (cleanup.status !== "deferred")
+ continue;
+ log4(`Warning: deferred legacy Codex LSP daemon cleanup for v${cleanup.version}: ${cleanup.reason}`);
+ }
const marketplaceRoot = join55(codexHome, "plugins", "cache", marketplace.name);
await writeCachedMarketplaceManifest({
marketplaceName: marketplace.name,
@@ -78224,10 +78483,10 @@ function codexMarketplaceSource(marketplaceRoot) {
}
// packages/omo-codex/src/install/codex-installation-detection.ts
init_bun_which_shim();
-import { execFile as execFile2 } from "node:child_process";
+import { execFile as execFile3 } from "node:child_process";
import { existsSync as existsSync31 } from "node:fs";
import { homedir as homedir7 } from "node:os";
-import { posix as posix3, win32 as win323 } from "node:path";
+import { posix as posix4, win32 as win323 } from "node:path";
var CODEX_PATH_CHECK_LABEL = "codex (PATH)";
var WINDOWS_START_APPS_ARGS = [
"-NoProfile",
@@ -78304,11 +78563,11 @@ async function findWindowsCodexStartApp(runCommand) {
}
}
function macCodexAppPaths(homeDir) {
- return ["/Applications/Codex.app", posix3.join(homeDir, "Applications", "Codex.app")];
+ return ["/Applications/Codex.app", posix4.join(homeDir, "Applications", "Codex.app")];
}
function macCodexDmgPaths(homeDir) {
- const downloads = posix3.join(homeDir, "Downloads");
- return [posix3.join(downloads, "codex.dmg"), posix3.join(downloads, "Codex.dmg")];
+ const downloads = posix4.join(homeDir, "Downloads");
+ return [posix4.join(downloads, "codex.dmg"), posix4.join(downloads, "Codex.dmg")];
}
function windowsCodexCliPaths(env3) {
const candidates = [];
@@ -78346,18 +78605,18 @@ function dedupe(values) {
}
function defaultRunCommand2(command, args) {
return new Promise((resolve16) => {
- execFile2(command, [...args], { encoding: "utf8", windowsHide: true }, (error, stdout) => {
+ execFile3(command, [...args], { encoding: "utf8", windowsHide: true }, (error, stdout) => {
resolve16({ success: error === null, stdout });
});
});
}
// packages/omo-codex/src/install/codex-cleanup.ts
-import { lstat as lstat12, readFile as readFile21, readdir as readdir10, rm as rm11, rmdir } from "node:fs/promises";
+import { lstat as lstat13, readFile as readFile22, readdir as readdir11, rm as rm11, rmdir } from "node:fs/promises";
import { homedir as homedir8 } from "node:os";
import { isAbsolute as isAbsolute11, join as join57, relative as relative7, resolve as resolve17 } from "node:path";
// packages/omo-codex/src/install/codex-cleanup-config.ts
-import { lstat as lstat11, mkdir as mkdir8, readFile as readFile20, writeFile as writeFile12 } from "node:fs/promises";
+import { lstat as lstat12, mkdir as mkdir8, readFile as readFile21, writeFile as writeFile12 } from "node:fs/promises";
import { dirname as dirname19 } from "node:path";
var MANAGED_MARKETPLACES = ["sisyphuslabs", "lazycodex", "code-yeongyu-codex-plugins"];
var LEGACY_MANAGED_CODEX_AGENT_NAMES_TO_PURGE2 = ["codex-ultrawork-reviewer"];
@@ -78390,7 +78649,7 @@ function cleanupCodexLightConfigText(config) {
async function cleanupCodexConfig(configPath, now) {
if (!await configExists(configPath))
return { changed: false };
- const original = await readFile20(configPath, "utf8");
+ const original = await readFile21(configPath, "utf8");
const next = cleanupCodexLightConfigText(original);
if (next === original)
return { changed: false };
@@ -78459,7 +78718,7 @@ function formatBackupTimestamp2(date) {
}
async function configExists(path7) {
try {
- await lstat11(path7);
+ await lstat12(path7);
return true;
} catch (error) {
if (nodeErrorCode5(error) === "ENOENT")
@@ -78577,7 +78836,7 @@ async function collectBootstrapDataDirsByGlob(codexHome) {
async function walkForManagedBootstrapDirs(directory, depth, results) {
if (depth > BOOTSTRAP_DATA_GLOB_MAX_DEPTH)
return;
- const entries = await readdir10(directory, { withFileTypes: true }).catch(() => null);
+ const entries = await readdir11(directory, { withFileTypes: true }).catch(() => null);
if (entries === null)
return;
for (const entry of entries) {
@@ -78609,7 +78868,7 @@ async function removeManagedPathBestEffort(path7, seams) {
}
async function attemptRemove(path7) {
try {
- if (await lstat12(path7).catch(() => null) === null)
+ if (await lstat13(path7).catch(() => null) === null)
return false;
await rm11(path7, { recursive: true, force: true });
return true;
@@ -78635,7 +78894,7 @@ async function collectInstalledAgentPaths(codexHome, configPath) {
];
const versionRoot = join57(codexHome, "plugins", "cache", "sisyphuslabs", "omo");
if (await exists6(versionRoot)) {
- const entries = await readdir10(versionRoot, { withFileTypes: true });
+ const entries = await readdir11(versionRoot, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory())
manifestPaths.push(join57(versionRoot, entry.name, INSTALLED_AGENTS_MANIFEST));
@@ -78655,20 +78914,20 @@ async function collectInstalledAgentPaths(codexHome, configPath) {
async function readManagedAgentPathsFromConfig(codexHome, configPath) {
if (!await exists6(configPath))
return [];
- const config = await readFile21(configPath, "utf8");
+ const config = await readFile22(configPath, "utf8");
return MANAGED_CODEX_AGENT_NAMES2.filter((agentName) => config.includes(`config_file = ${JSON.stringify(`./agents/${agentName}.toml`)}`)).map((agentName) => join57(codexHome, "agents", `${agentName}.toml`));
}
async function readInstalledAgentManifest(manifestPath) {
if (!await exists6(manifestPath))
return [];
- const parsed = JSON.parse(await readFile21(manifestPath, "utf8"));
+ const parsed = JSON.parse(await readFile22(manifestPath, "utf8"));
if (!isPlainRecord3(parsed) || !Array.isArray(parsed.agents))
return [];
return parsed.agents.filter((path7) => typeof path7 === "string");
}
async function removeManifestListedAgentLinks(codexHome, paths) {
const agentsDir = join57(codexHome, "agents");
- const removed = [];
+ const removed2 = [];
const skipped2 = [];
for (const path7 of paths) {
if (!isSafeManagedAgentPath(agentsDir, path7)) {
@@ -78683,9 +78942,9 @@ async function removeManifestListedAgentLinks(codexHome, paths) {
continue;
}
await rm11(path7, { force: true });
- removed.push(path7);
+ removed2.push(path7);
}
- return { removed, skipped: skipped2 };
+ return { removed: removed2, skipped: skipped2 };
}
function isSafeManagedAgentPath(agentsDir, path7) {
if (!isAbsolute11(path7))
@@ -78703,7 +78962,7 @@ async function exists6(path7) {
}
async function maybeLstat2(path7) {
try {
- return await lstat12(path7);
+ return await lstat13(path7);
} catch (error) {
if (nodeErrorCode6(error) === "ENOENT")
return null;
@@ -78718,18 +78977,26 @@ function nodeErrorCode6(error) {
// packages/omo-codex/src/install/codex-git-bash-mcp-env.ts
var CODEGRAPH_RELATIVE_ARGS2 = new Set(["components/codegraph/dist/serve.js", "./components/codegraph/dist/serve.js"]);
// packages/omo-senpi/src/install/install-senpi.ts
-import { execFile as execFile3 } from "node:child_process";
+import { execFile as execFile4 } from "node:child_process";
import { constants as constants7, existsSync as existsSync32 } from "node:fs";
-import { access, copyFile as copyFile3, mkdir as mkdir9, readFile as readFile22, rename as rename5, writeFile as writeFile13 } from "node:fs/promises";
+import { access, copyFile as copyFile3, mkdir as mkdir9, readFile as readFile23, rename as rename5, writeFile as writeFile13 } from "node:fs/promises";
import { homedir as homedir9 } from "node:os";
import { dirname as dirname21, join as join58, resolve as resolve18 } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify as promisify2 } from "node:util";
-var execFileAsync2 = promisify2(execFile3);
+var execFileAsync2 = promisify2(execFile4);
var REQUIRED_PLUGIN_ARTIFACTS = [
join58("extensions", "omo.js"),
join58("skills", "ultrawork", "SKILL.md"),
- join58("skills", "ulw-loop", "SKILL.md")
+ join58("skills", "ulw-loop", "SKILL.md"),
+ join58("runtime", "lsp-daemon", "dist", "cli.js"),
+ join58("runtime", "lsp-daemon", "dist", "index.js"),
+ join58("runtime", "lsp-daemon", "dist", "index.d.ts"),
+ join58("runtime", "lsp-daemon", "dist", "daemon-client.js"),
+ join58("runtime", "lsp-daemon", "dist", "daemon-client.d.ts"),
+ join58("runtime", "lsp-daemon", "dist", "package.json"),
+ join58("runtime", "lsp-daemon", "dist", ".omo-runtime-manifest.json"),
+ join58("scripts", "install.mjs")
];
async function runSenpiInstaller(options = {}) {
const context = resolveInstallContext(options);
@@ -78753,7 +79020,8 @@ async function runSenpiInstaller(options = {}) {
}
function resolveInstallContext(options) {
const env3 = options.env ?? process.env;
- const repoRoot = resolve18(options.repoRoot ?? findRepoRoot2(dirname21(fileURLToPath(import.meta.url))));
+ const allowBuild = options.pluginPath === undefined;
+ const repoRoot = resolve18(options.repoRoot ?? (allowBuild ? findRepoRoot2(dirname21(fileURLToPath(import.meta.url))) : dirname21(resolve18(options.pluginPath))));
const agentDir = resolve18(options.agentDir ?? env3.SENPI_CODING_AGENT_DIR ?? join58(homedir9(), ".senpi", "agent"));
const pluginPath = resolve18(options.pluginPath ?? join58(repoRoot, "packages", "omo-senpi", "plugin"));
return {
@@ -78762,6 +79030,7 @@ function resolveInstallContext(options) {
agentDir,
settingsPath: join58(agentDir, "settings.json"),
pluginPath,
+ allowBuild,
runCommand: options.runCommand ?? defaultRunCommand3
};
}
@@ -78769,8 +79038,13 @@ async function ensurePluginArtifacts(context) {
const missing = await hasMissingPluginArtifact(context.pluginPath);
if (!missing)
return;
+ if (!context.allowBuild) {
+ throw new Error(`Packed omo-senpi plugin is missing required runtime artifacts at ${context.pluginPath}`);
+ }
await context.runCommand("node", [join58(context.pluginPath, "scripts", "build-extension.mjs")], { cwd: context.repoRoot });
await context.runCommand("node", [join58(context.pluginPath, "scripts", "sync-skills.mjs")], { cwd: context.repoRoot });
+ await context.runCommand("node", [join58(context.pluginPath, "scripts", "build-install.mjs")], { cwd: context.repoRoot });
+ await context.runCommand("node", [join58(context.pluginPath, "scripts", "stage-lsp-daemon-runtime.mjs")], { cwd: context.repoRoot });
}
async function hasMissingPluginArtifact(pluginPath) {
for (const artifact of REQUIRED_PLUGIN_ARTIFACTS) {
@@ -78789,7 +79063,7 @@ async function defaultRunCommand3(command, args, options) {
async function readSettings(settingsPath) {
let raw;
try {
- raw = await readFile22(settingsPath, "utf8");
+ raw = await readFile23(settingsPath, "utf8");
} catch (error) {
if (isErrno(error, "ENOENT"))
return {};
@@ -78868,7 +79142,7 @@ function isErrno(error, code) {
return error instanceof Error && "code" in error && error.code === code;
}
// packages/omo-opencode/src/cli/star-request.ts
-import { execFile as execFile4 } from "node:child_process";
+import { execFile as execFile5 } from "node:child_process";
import { promisify as promisify3 } from "node:util";
var STAR_REPOSITORIES = [
"code-yeongyu/oh-my-openagent",
@@ -78880,7 +79154,7 @@ var PLATFORM_REPOSITORIES = {
both: STAR_REPOSITORIES,
senpi: STAR_REPOSITORIES
};
-var execFileAsync3 = promisify3(execFile4);
+var execFileAsync3 = promisify3(execFile5);
async function runGitHubStarCommand(repository) {
await execFileAsync3("gh", ["api", "--silent", "--method", "PUT", `/user/starred/${repository}`]);
}
@@ -97250,7 +97524,7 @@ var import_picocolors11 = __toESM(require_picocolors(), 1);
// packages/omo-opencode/src/cli/run/opencode-binary-resolver.ts
init_bun_which_shim();
init_spawn_with_windows_hide();
-import { delimiter as delimiter2, dirname as dirname23, posix as posix4, win32 as win324 } from "node:path";
+import { delimiter as delimiter2, dirname as dirname23, posix as posix5, win32 as win324 } from "node:path";
var OPENCODE_COMMANDS = ["opencode", "opencode-desktop"];
var WINDOWS_SUFFIXES = ["", ".exe", ".cmd", ".bat", ".ps1"];
function getCommandCandidates(platform) {
@@ -97261,7 +97535,7 @@ function getCommandCandidates(platform) {
function getPathTools(platform) {
if (platform === "win32")
return win324;
- return posix4;
+ return posix5;
}
function collectCandidateBinaryPaths(pathEnv, which2 = bunWhich, platform = process.platform) {
const seen = new Set;
@@ -100420,12 +100694,12 @@ import { dirname as dirname30, join as join79 } from "node:path";
// packages/omo-opencode/src/hooks/comment-checker/downloader.ts
import { join as join78 } from "path";
-import { homedir as homedir18, tmpdir as tmpdir3 } from "os";
+import { homedir as homedir18, tmpdir as tmpdir4 } from "os";
init_binary_downloader();
init_logger2();
init_plugin_identity();
var DEBUG = process.env.COMMENT_CHECKER_DEBUG === "1";
-var DEBUG_FILE = join78(tmpdir3(), "comment-checker-debug.log");
+var DEBUG_FILE = join78(tmpdir4(), "comment-checker-debug.log");
function getCacheDir2() {
if (process.platform === "win32") {
const localAppData = process.env.LOCALAPPDATA || process.env.APPDATA;
@@ -100662,13 +100936,14 @@ async function getGhCliInfo(dependencies = {}) {
}
// packages/omo-opencode/src/cli/doctor/checks/tools-lsp.ts
-import { readFileSync as readFileSync38 } from "node:fs";
+import { readFileSync as readFileSync39 } from "node:fs";
import { join as join80 } from "node:path";
// packages/omo-opencode/src/mcp/lsp.ts
-import { existsSync as existsSync56 } from "node:fs";
+import { existsSync as existsSync56, readFileSync as readFileSync38 } from "node:fs";
import { delimiter as delimiter3, dirname as dirname31, resolve as resolve21 } from "node:path";
import { fileURLToPath as fileURLToPath7 } from "node:url";
+init_opencode_config_dir();
// packages/omo-opencode/src/mcp/cli-suffix.ts
function normalizeCliPath(path14) {
@@ -100680,7 +100955,7 @@ function hasCliSuffix(candidatePath, suffix) {
// packages/omo-opencode/src/mcp/runtime-executable.ts
init_bun_which_shim();
-import { basename as basename12 } from "node:path";
+import { basename as basename13 } from "node:path";
var NODE_EXECUTABLE_NAMES = new Set(["node", "node.exe"]);
function isUnsafeCommandName2(commandName) {
if (commandName.length === 0)
@@ -100696,7 +100971,7 @@ function isUnsafeCommandName2(commandName) {
return false;
}
function isNodeExecPath(execPath) {
- return NODE_EXECUTABLE_NAMES.has(basename12(execPath).toLowerCase());
+ return NODE_EXECUTABLE_NAMES.has(basename13(execPath).toLowerCase());
}
function resolveRuntimeExecutable(commandName, options = {}) {
if (isUnsafeCommandName2(commandName)) {
@@ -100766,8 +101041,15 @@ var LSP_TOOLS_PACKAGE_REL = "packages/lsp-tools-mcp";
var DIST_CLI_REL = "dist/cli.js";
var SOURCE_CLI_REL = "src/cli.ts";
var PROJECT_LSP_CONFIGS = [".opencode/lsp.json", ".omo/lsp.json", ".omo/lsp-client.json"];
+var DAEMON_PACKAGE_NAME = "@code-yeongyu/lsp-daemon";
+var OMO_LSP_DAEMON_CLI = "OMO_LSP_DAEMON_CLI";
+var OMO_LSP_DAEMON_VERSION = "OMO_LSP_DAEMON_VERSION";
+var DaemonPackageSchema = exports_external.object({
+ version: exports_external.string().min(1)
+});
var LSP_BOOTSTRAP_SCRIPT = [
"const { existsSync } = require('node:fs')",
+ "const { createRequire } = require('node:module')",
"const { join } = require('node:path')",
"const { spawnSync } = require('node:child_process')",
"const root = process.argv[1]",
@@ -100776,16 +101058,18 @@ var LSP_BOOTSTRAP_SCRIPT = [
`const toolsPackage = join(root, '${LSP_TOOLS_PACKAGE_REL}')`,
`const daemonPackage = join(root, '${PACKAGE_REL}')`,
"const toolsDist = join(toolsPackage, 'dist/cli.js')",
- "const daemonDist = join(daemonPackage, 'dist/cli.js')",
+ "const daemonPackageJson = join(daemonPackage, 'package.json')",
"const daemonSource = join(daemonPackage, 'src/cli.ts')",
"const run = (command, args, stdio) => spawnSync(command, args, { cwd: root, env: process.env, stdio })",
"const finish = (result) => { if (result.error) { console.error(result.error.message); process.exit(1) } process.exit(result.status ?? 1) }",
"const runIfAvailable = (command, args) => { const result = run(command, args, 'inherit'); if (result.error) return false; finish(result); return true }",
- "if (existsSync(daemonDist)) finish(run(process.execPath, [daemonDist, 'mcp'], 'inherit'))",
- "if (existsSync(daemonSource) && existsSync(toolsDist)) runIfAvailable(bun, [daemonSource, 'mcp'])",
+ `const resolveDaemonCli = () => { try { return createRequire(daemonPackageJson).resolve('${DAEMON_PACKAGE_NAME}/cli') } catch (error) { if (error instanceof Error) return null; throw error } }`,
+ "const daemonCli = existsSync(daemonPackageJson) ? resolveDaemonCli() : null",
+ "if (daemonCli) finish(run(process.execPath, [daemonCli, 'mcp'], 'inherit'))",
+ `if (existsSync(daemonSource) && existsSync(toolsDist)) { const pkg = require(daemonPackageJson); process.env.${OMO_LSP_DAEMON_CLI} = daemonSource; process.env.${OMO_LSP_DAEMON_VERSION} = pkg.version; runIfAvailable(bun, [daemonSource, 'mcp']) }`,
"const steps = [[npm, ['--prefix', toolsPackage, 'install', '--no-package-lock', '--no-audit', '--no-fund']], [npm, ['--prefix', toolsPackage, 'run', 'build']], [npm, ['--prefix', daemonPackage, 'install', '--no-package-lock', '--no-audit', '--no-fund']], [npm, ['--prefix', daemonPackage, 'run', 'build']]]",
"for (const [command, args] of steps) { const result = run(command, args, ['ignore', 'ignore', 'inherit']); if (result.error || result.status !== 0) finish(result) }",
- "finish(run(process.execPath, [daemonDist, 'mcp'], 'inherit'))"
+ "finish(run(process.execPath, [resolveDaemonCli(), 'mcp'], 'inherit'))"
].join(";");
function getModuleDirectory(moduleUrl) {
try {
@@ -100799,6 +101083,16 @@ function getModuleDirectory(moduleUrl) {
function findBootstrapRoot(candidates, pathExists) {
return candidates.find((candidate) => pathExists(resolve21(candidate.root, "package.json")))?.root ?? process.cwd();
}
+function readDaemonPackageVersion(root) {
+ try {
+ const packageJson = JSON.parse(readFileSync38(resolve21(root, PACKAGE_REL, "package.json"), "utf-8"));
+ return DaemonPackageSchema.parse(packageJson).version;
+ } catch (error51) {
+ if (!(error51 instanceof Error))
+ throw error51;
+ return null;
+ }
+}
function createBootstrapCandidate(root, pathExists, resolveExecutable) {
const runtime5 = resolveJavaScriptRuntime(resolveExecutable);
const bun = resolveExecutable("bun");
@@ -100823,7 +101117,7 @@ function resolveLspCommand(options = {}) {
sourceCliRel: SOURCE_CLI_REL,
pathExists,
resolveExecutable,
- isSourceCandidateAvailable: ({ root }) => pathExists(resolve21(root, LSP_TOOLS_PACKAGE_REL, DIST_CLI_REL))
+ isSourceCandidateAvailable: ({ root }) => pathExists(resolve21(root, LSP_TOOLS_PACKAGE_REL, DIST_CLI_REL)) && readDaemonPackageVersion(root) !== null
}) : [];
const distCandidate = candidates.find((candidate) => hasCliSuffix(candidate.path, DIST_CLI_REL) && candidate.exists);
if (distCandidate) {
@@ -100837,12 +101131,21 @@ function resolveLspCommand(options = {}) {
}
function createLspMcpConfig(options = {}) {
const resolvedCommand = resolveLspCommand(options);
+ const cwd = resolve21(options.cwd ?? process.cwd());
+ const configDir = getOpenCodeConfigDir({ binary: "opencode" });
+ const sourceVersion = hasCliSuffix(resolvedCommand.path, SOURCE_CLI_REL) ? readDaemonPackageVersion(resolvedCommand.root) : null;
return {
type: "local",
command: resolvedCommand.command,
enabled: resolvedCommand.exists,
environment: {
- LSP_TOOLS_MCP_PROJECT_CONFIG: PROJECT_LSP_CONFIGS.join(delimiter3)
+ LSP_TOOLS_MCP_PROJECT_CONFIG: PROJECT_LSP_CONFIGS.map((configPath) => resolve21(cwd, configPath)).join(delimiter3),
+ LSP_TOOLS_MCP_USER_CONFIG: resolve21(configDir, "lsp.json"),
+ LSP_TOOLS_MCP_INSTALL_DECISIONS: resolve21(configDir, "lsp-install-decisions.json"),
+ ...sourceVersion ? {
+ [OMO_LSP_DAEMON_CLI]: resolvedCommand.path,
+ [OMO_LSP_DAEMON_VERSION]: sourceVersion
+ } : {}
}
};
}
@@ -100859,7 +101162,7 @@ function readOmoConfig(configDirectory) {
return null;
}
try {
- const content = readFileSync38(detected.path, "utf-8");
+ const content = readFileSync39(detected.path, "utf-8");
return parseJsonc(content);
} catch (error51) {
if (!(error51 instanceof Error)) {
@@ -100889,7 +101192,7 @@ function getInstalledLspServers(options = {}) {
// packages/omo-opencode/src/cli/doctor/checks/tools-mcp.ts
init_shared();
-import { existsSync as existsSync57, readFileSync as readFileSync39 } from "node:fs";
+import { existsSync as existsSync57, readFileSync as readFileSync40 } from "node:fs";
import { homedir as homedir20 } from "node:os";
import { join as join81 } from "node:path";
var BUILTIN_MCP_SERVERS = ["websearch", "context7", "grep_app", "lsp"];
@@ -100906,7 +101209,7 @@ function loadUserMcpConfig() {
if (!existsSync57(configPath))
continue;
try {
- const content = readFileSync39(configPath, "utf-8");
+ const content = readFileSync40(configPath, "utf-8");
const config3 = parseJsonc(content);
if (config3.mcpServers) {
Object.assign(servers, config3.mcpServers);
@@ -101041,7 +101344,7 @@ async function checkTools() {
// packages/omo-opencode/src/cli/doctor/checks/telemetry.ts
init_src4();
-import { existsSync as existsSync58, readFileSync as readFileSync40 } from "node:fs";
+import { existsSync as existsSync58, readFileSync as readFileSync41 } from "node:fs";
function isTelemetryState(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
@@ -101051,7 +101354,7 @@ function readLastActiveDay(stateFilePath) {
}
let parsed;
try {
- parsed = JSON.parse(readFileSync40(stateFilePath, "utf-8"));
+ parsed = JSON.parse(readFileSync41(stateFilePath, "utf-8"));
} catch (error51) {
if (error51 instanceof Error) {
return "unreadable";
@@ -101126,7 +101429,7 @@ function expandHomeDirectory(directoryPath) {
// packages/omo-opencode/src/cli/doctor/checks/team-mode.ts
init_shared();
init_plugin_identity();
-import { readFileSync as readFileSync41, promises as fs13 } from "node:fs";
+import { readFileSync as readFileSync42, promises as fs13 } from "node:fs";
import path15 from "node:path";
async function checkTeamMode() {
const config3 = loadTeamModeConfig();
@@ -101163,7 +101466,7 @@ function loadTeamModeConfig() {
if (!configPath)
return { team_mode: undefined };
try {
- return parseJsonc(readFileSync41(configPath, "utf-8"));
+ return parseJsonc(readFileSync42(configPath, "utf-8"));
} catch (error51) {
if (error51 instanceof Error) {
return { team_mode: undefined };
@@ -101197,9 +101500,9 @@ async function pathExists(dir) {
// packages/omo-opencode/src/cli/doctor/checks/codex.ts
init_src();
import { existsSync as existsSync59 } from "node:fs";
-import { lstat as lstat13, readdir as readdir11, readFile as readFile23 } from "node:fs/promises";
+import { lstat as lstat14, readdir as readdir12, readFile as readFile24 } from "node:fs/promises";
import { homedir as homedir22 } from "node:os";
-import { basename as basename13, join as join82, resolve as resolve22 } from "node:path";
+import { basename as basename14, join as join82, resolve as resolve22 } from "node:path";
// packages/omo-opencode/package.json
var package_default3 = {
name: "@oh-my-opencode/omo-opencode",
@@ -101388,7 +101691,7 @@ async function resolveInstalledPluginRoot(codexHome) {
const pluginRoot = join82(codexHome, "plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME2);
if (!existsSync59(pluginRoot))
return null;
- const versions2 = await readdir11(pluginRoot, { withFileTypes: true });
+ const versions2 = await readdir12(pluginRoot, { withFileTypes: true });
const candidates = versions2.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(compareVersionsDescending);
return candidates.length === 0 ? null : join82(pluginRoot, candidates[0] ?? DEFAULT_PLUGIN_VERSION);
}
@@ -101404,7 +101707,7 @@ async function readCodexConfigSummary(configPath) {
companionLifecycleHookStateEvents: []
};
}
- const content = await readFile23(configPath, "utf8");
+ const content = await readFile24(configPath, "utf8");
return {
exists: true,
marketplaceConfigured: content.includes("[marketplaces.sisyphuslabs]"),
@@ -101427,12 +101730,12 @@ async function readLinkedAgents(codexHome) {
const agentsDir = join82(codexHome, "agents");
if (!existsSync59(agentsDir))
return [];
- const entries = await readdir11(agentsDir, { withFileTypes: true });
- return entries.filter((entry) => entry.isFile() || entry.isSymbolicLink()).map((entry) => basename13(entry.name, ".toml")).sort();
+ const entries = await readdir12(agentsDir, { withFileTypes: true });
+ return entries.filter((entry) => entry.isFile() || entry.isSymbolicLink()).map((entry) => basename14(entry.name, ".toml")).sort();
}
async function readJson(path16) {
try {
- const parsed = JSON.parse(await readFile23(path16, "utf8"));
+ const parsed = JSON.parse(await readFile24(path16, "utf8"));
return isPlainRecord(parsed) ? parsed : null;
} catch (error51) {
if (error51 instanceof Error)
@@ -101527,7 +101830,7 @@ function compareVersionsDescending(left, right) {
}
async function pathExists2(path16) {
try {
- await lstat13(path16);
+ await lstat14(path16);
return true;
} catch (error51) {
if (error51 instanceof Error)
@@ -101538,7 +101841,7 @@ async function pathExists2(path16) {
// packages/omo-opencode/src/cli/doctor/checks/codex-components.ts
init_src();
-import { readdir as readdir12, readFile as readFile24, stat as stat6 } from "node:fs/promises";
+import { readdir as readdir13, readFile as readFile25, stat as stat6 } from "node:fs/promises";
import { homedir as homedir23 } from "node:os";
import { dirname as dirname32, isAbsolute as isAbsolute13, join as join83, relative as relative10, resolve as resolve23, sep as sep9 } from "node:path";
var CODEX_COMPONENTS_CHECK_ID = "codex-components";
@@ -101679,7 +101982,7 @@ async function findHookManifestPaths(root) {
async function findManifestPaths(root, manifestName) {
let entries;
try {
- entries = await readdir12(root, { withFileTypes: true });
+ entries = await readdir13(root, { withFileTypes: true });
} catch {
return [];
}
@@ -101791,7 +102094,7 @@ function degradedDetailLines(entries) {
}
async function readJson2(path16) {
try {
- const parsed = JSON.parse(await readFile24(path16, "utf8"));
+ const parsed = JSON.parse(await readFile25(path16, "utf8"));
return isRecord6(parsed) ? parsed : null;
} catch (error51) {
if (error51 instanceof Error)
@@ -101819,7 +102122,7 @@ function isRecord6(value) {
// packages/omo-opencode/src/cli/doctor/checks/codex-runtime-wrapper.ts
import { existsSync as existsSync60 } from "node:fs";
-import { readFile as readFile25 } from "node:fs/promises";
+import { readFile as readFile26 } from "node:fs/promises";
import { homedir as homedir24 } from "node:os";
import { join as join84, resolve as resolve24 } from "node:path";
var RUNTIME_WRAPPER_MARKER2 = "OMO_GENERATED_RUNTIME_WRAPPER";
@@ -101854,7 +102157,7 @@ async function checkCodexRuntimeWrapper(deps = {}) {
}
async function readRuntimeWrapper(path16) {
try {
- return await readFile25(path16, "utf8");
+ return await readFile26(path16, "utf8");
} catch (error51) {
if (error51 instanceof Error)
return null;
@@ -102330,18 +102633,18 @@ Doctor failed unexpectedly: ${message}`];
}
// packages/mcp-client-core/src/mcp-oauth/storage.ts
-import { createHash as createHash4 } from "node:crypto";
+import { createHash as createHash5 } from "node:crypto";
import {
chmodSync as chmodSync4,
existsSync as existsSync63,
mkdirSync as mkdirSync14,
readdirSync as readdirSync9,
- readFileSync as readFileSync43,
+ readFileSync as readFileSync44,
renameSync as renameSync7,
unlinkSync as unlinkSync8,
writeFileSync as writeFileSync11
} from "node:fs";
-import { basename as basename14, dirname as dirname33, join as join87 } from "node:path";
+import { basename as basename15, dirname as dirname33, join as join87 } from "node:path";
// packages/mcp-client-core/src/config-dir.ts
import { existsSync as existsSync61, realpathSync as realpathSync8 } from "node:fs";
@@ -102369,7 +102672,7 @@ function getOpenCodeCliConfigDir(env3 = process.env) {
}
// packages/mcp-client-core/src/mcp-oauth/storage-index.ts
-import { chmodSync as chmodSync3, existsSync as existsSync62, readFileSync as readFileSync42, renameSync as renameSync6, writeFileSync as writeFileSync10 } from "node:fs";
+import { chmodSync as chmodSync3, existsSync as existsSync62, readFileSync as readFileSync43, renameSync as renameSync6, writeFileSync as writeFileSync10 } from "node:fs";
import { join as join86 } from "node:path";
var INDEX_FILE_NAME = "index.json";
function isTokenIndex(value) {
@@ -102385,7 +102688,7 @@ function readTokenIndex(storageDir) {
if (!existsSync62(indexPath))
return {};
try {
- const parsed = JSON.parse(readFileSync42(indexPath, "utf-8"));
+ const parsed = JSON.parse(readFileSync43(indexPath, "utf-8"));
return isTokenIndex(parsed) ? parsed : {};
} catch (readError) {
if (!(readError instanceof Error))
@@ -102425,7 +102728,7 @@ function getMcpOauthStorageDir() {
return join87(getOpenCodeCliConfigDir(), STORAGE_DIR_NAME);
}
function getMcpOauthServerHash(serverHost, resource) {
- return createHash4("sha256").update(buildKey(serverHost, resource)).digest("hex").slice(0, 32);
+ return createHash5("sha256").update(buildKey(serverHost, resource)).digest("hex").slice(0, 32);
}
function getMcpOauthStoragePath(serverHost, resource) {
return join87(getMcpOauthStorageDir(), `${getMcpOauthServerHash(serverHost, resource)}.json`);
@@ -102495,7 +102798,7 @@ function readTokenFile(filePath) {
if (!existsSync63(filePath))
return null;
try {
- const parsed = JSON.parse(readFileSync43(filePath, "utf-8"));
+ const parsed = JSON.parse(readFileSync44(filePath, "utf-8"));
return isOAuthTokenData(parsed) ? parsed : null;
} catch (readError) {
if (!(readError instanceof Error))
@@ -102508,7 +102811,7 @@ function readLegacyStore() {
if (!existsSync63(filePath))
return null;
try {
- const parsed = JSON.parse(readFileSync43(filePath, "utf-8"));
+ const parsed = JSON.parse(readFileSync44(filePath, "utf-8"));
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
return null;
const result = {};
@@ -102626,7 +102929,7 @@ function listAllTokens() {
if (!entry.isFile() || !entry.name.endsWith(".json") || entry.name === "index.json")
continue;
const token = readTokenFile(join87(dir, entry.name));
- const hash2 = basename14(entry.name, ".json");
+ const hash2 = basename15(entry.name, ".json");
if (token)
result[index[hash2] ?? hash2] = token;
}
@@ -102799,13 +103102,13 @@ async function findAvailablePort2(startPort = DEFAULT_PORT) {
// packages/mcp-client-core/src/mcp-oauth/oauth-authorization-flow.ts
import { spawn as spawn4 } from "node:child_process";
-import { createHash as createHash5, randomBytes as randomBytes2 } from "node:crypto";
+import { createHash as createHash6, randomBytes as randomBytes2 } from "node:crypto";
import { createServer as createServer2 } from "node:http";
function generateCodeVerifier() {
return randomBytes2(32).toString("base64url");
}
function generateCodeChallenge(verifier) {
- return createHash5("sha256").update(verifier).digest("base64url");
+ return createHash6("sha256").update(verifier).digest("base64url");
}
function buildAuthorizationUrl(authorizationEndpoint, options) {
const url2 = new URL(authorizationEndpoint);
@@ -103349,7 +103652,7 @@ async function boulder(options) {
}
// packages/omo-opencode/src/cli/codex-ulw-loop.ts
import { spawn as spawn5 } from "node:child_process";
-import { existsSync as existsSync65, readFileSync as readFileSync44, realpathSync as realpathSync9 } from "node:fs";
+import { existsSync as existsSync65, readFileSync as readFileSync45, realpathSync as realpathSync9 } from "node:fs";
import { homedir as homedir26 } from "node:os";
var ULW_LOOP_DELEGATION_SENTINEL = "OMO_ULW_LOOP_DELEGATED";
function resolveCodexUlwLoopCommand(input = {}) {
@@ -103399,7 +103702,7 @@ function resolveLegacyLocalOmoBin(env3, homeDir, currentExecutablePaths) {
}
function isGeneratedRuntimeWrapper(candidate) {
try {
- return readFileSync44(candidate, "utf8").includes(RUNTIME_WRAPPER_MARKER);
+ return readFileSync45(candidate, "utf8").includes(RUNTIME_WRAPPER_MARKER);
} catch (error51) {
if (error51 instanceof Error)
return false;
diff --git a/plugins/omo/dist/cli/index.js b/plugins/omo/dist/cli/index.js
index b893cf01..77906fdf 100755
--- a/plugins/omo/dist/cli/index.js
+++ b/plugins/omo/dist/cli/index.js
@@ -2145,7 +2145,7 @@ var package_default;
var init_package = __esm(() => {
package_default = {
name: "oh-my-opencode",
- version: "4.18.0",
+ version: "4.18.1",
description: "The Best AI Agent Harness - Batteries-Included OpenCode Plugin with Multi-Model Orchestration, Parallel Background Agents, and Crafted LSP/AST Tools",
main: "./dist/index.js",
types: "dist/index.d.ts",
@@ -2254,7 +2254,8 @@ var init_package = __esm(() => {
"build:codex-install": "bun run script/build-codex-install.ts",
"install:codex-dev": "bun run script/build-codex-install.ts && bun run script/install-codex-dev.ts",
"build:codex-plugin": "npm --prefix packages/omo-codex/plugin ci && bun run --cwd packages/omo-codex/plugin build",
- "build:senpi-plugin": "node packages/omo-senpi/plugin/scripts/build-extension.mjs && node packages/omo-senpi/plugin/scripts/sync-skills.mjs && node packages/omo-senpi/plugin/scripts/embed-directive.mjs --check",
+ "build:senpi-plugin": "bun run build:lsp-daemon && bun run build:senpi-plugin:stage",
+ "build:senpi-plugin:stage": "node packages/omo-senpi/plugin/scripts/stage-lsp-daemon-runtime.mjs && node packages/omo-senpi/plugin/scripts/build-extension.mjs && node packages/omo-senpi/plugin/scripts/sync-skills.mjs && node packages/omo-senpi/plugin/scripts/embed-directive.mjs --check && node packages/omo-senpi/plugin/scripts/build-install.mjs",
"build:materialize-frontend": "node packages/omo-codex/plugin/scripts/materialize-shared-upstreams.mjs --strict",
"build:shared-skills-assets": "bun run build:materialize-frontend && rm -rf dist/skills && cp -R packages/shared-skills/skills dist/skills",
"build:lsp-tools-mcp": "npm --prefix packages/lsp-tools-mcp ci && npm --prefix packages/lsp-tools-mcp run build",
@@ -2276,7 +2277,7 @@ var init_package = __esm(() => {
"typecheck:script": "tsgo --noEmit -p script/tsconfig.json",
test: "bun test",
"test:codex": "bun run build:codex-install && bun run build:git-bash-mcp && bun run build:lsp-tools-mcp && bun run build:lsp-daemon && npm --prefix packages/lsp-tools-mcp test && npm --prefix packages/omo-codex/plugin ci && npm --prefix packages/omo-codex/plugin/components/ulw-loop test && bun run --cwd packages/omo-codex/plugin build && npm --prefix packages/omo-codex/plugin/components/codegraph run typecheck && npm --prefix packages/omo-codex/plugin/components/codegraph test && node scripts/check-third-party-notices.mjs --ship && bun test packages/omo-opencode/src/cli/cli-installer.platform.test.ts packages/omo-codex/src/install/codex-cache.test.ts packages/omo-codex/src/install/codex-cleanup.test.ts packages/omo-codex/src/install/codex-config-agent-cleanup.test.ts packages/omo-codex/src/install/codex-config-autonomous-features.test.ts packages/omo-codex/src/install/codex-config-reasoning.test.ts packages/omo-codex/src/install/codex-config-toml.test.ts packages/omo-codex/src/install/codex-project-local-cleanup.test.ts packages/omo-codex/src/install/install-codex-project-local-cleanup.test.ts packages/omo-codex/src/install/install-codex.test.ts packages/omo-codex/src/install/install-codex-packaged.test.ts packages/omo-codex/src/install/link-cached-plugin-agents.test.ts packages/omo-codex/src/**/*.test.ts packages/utils/src/jsonc-parser.test.ts packages/utils/src/frontmatter.test.ts packages/hashline-core/src/hash-computation.test.ts packages/hashline-core/src/smoke-untested-modules.test.ts packages/rules-engine/src/index.test.ts packages/rules-engine/src/security-boundary.test.ts packages/agents-md-core/src/injector.test.ts packages/omo-codex/plugin/components/lsp/test/package-smoke.test.ts && node --test packages/omo-codex/plugin/test/*.test.mjs packages/omo-codex/scripts/install-cache-copy.test.mjs packages/omo-codex/scripts/install-cli-args.test.mjs packages/omo-codex/scripts/install-delegated-command.test.mjs packages/omo-codex/scripts/install-config-autonomous-features.test.mjs packages/omo-codex/scripts/install-config-autonomous.test.mjs packages/omo-codex/scripts/install-config-reasoning.test.mjs packages/omo-codex/scripts/install-config.test.mjs packages/omo-codex/scripts/install-hook-targets.test.mjs packages/omo-codex/scripts/install-project-local-cleanup.test.mjs packages/omo-codex/scripts/install-lazycodex-version-stamp.test.mjs packages/omo-codex/scripts/install-local-entrypoint.test.mjs packages/omo-codex/scripts/install-local-git-bash-preflight.test.mjs packages/omo-codex/scripts/install-local.test.mjs packages/omo-codex/scripts/install-marketplace-cache.test.mjs packages/omo-codex/scripts/install-mcp-context7-runtime.test.mjs packages/omo-codex/scripts/install-mcp-runtime.test.mjs packages/omo-codex/scripts/install-packaged-local.test.mjs packages/omo-codex/scripts/install-generated-bundle.test.mjs packages/omo-codex/scripts/install-agent-links.test.mjs packages/omo-codex/scripts/install-bin-links.test.mjs",
- "test:senpi": "node packages/omo-senpi/plugin/scripts/build-extension.mjs && node packages/omo-senpi/plugin/scripts/sync-skills.mjs && node packages/omo-senpi/plugin/scripts/embed-directive.mjs --check && bun test packages/omo-senpi",
+ "test:senpi": "bun run build:senpi-plugin && tsgo --noEmit -p packages/omo-senpi/tsconfig.json && bun test packages/omo-senpi",
"test:windows-codex": "bun run test:codex",
"build:git-bash-mcp": "bun run --cwd packages/git-bash-mcp build"
},
@@ -2316,7 +2317,6 @@ var init_package = __esm(() => {
picocolors: "^1.1.1",
picomatch: "^4.0.4",
"posthog-node": "^5.34.3",
- "vscode-jsonrpc": "^8.2.1",
zod: "^4.4.3"
},
devDependencies: {
@@ -2357,18 +2357,18 @@ var init_package = __esm(() => {
typescript: "^6.0.3"
},
optionalDependencies: {
- "oh-my-opencode-darwin-arm64": "4.18.0",
- "oh-my-opencode-darwin-x64": "4.18.0",
- "oh-my-opencode-darwin-x64-baseline": "4.18.0",
- "oh-my-opencode-linux-arm64": "4.18.0",
- "oh-my-opencode-linux-arm64-musl": "4.18.0",
- "oh-my-opencode-linux-x64": "4.18.0",
- "oh-my-opencode-linux-x64-baseline": "4.18.0",
- "oh-my-opencode-linux-x64-musl": "4.18.0",
- "oh-my-opencode-linux-x64-musl-baseline": "4.18.0",
- "oh-my-opencode-windows-arm64": "4.18.0",
- "oh-my-opencode-windows-x64": "4.18.0",
- "oh-my-opencode-windows-x64-baseline": "4.18.0"
+ "oh-my-opencode-darwin-arm64": "4.18.1",
+ "oh-my-opencode-darwin-x64": "4.18.1",
+ "oh-my-opencode-darwin-x64-baseline": "4.18.1",
+ "oh-my-opencode-linux-arm64": "4.18.1",
+ "oh-my-opencode-linux-arm64-musl": "4.18.1",
+ "oh-my-opencode-linux-x64": "4.18.1",
+ "oh-my-opencode-linux-x64-baseline": "4.18.1",
+ "oh-my-opencode-linux-x64-musl": "4.18.1",
+ "oh-my-opencode-linux-x64-musl-baseline": "4.18.1",
+ "oh-my-opencode-windows-arm64": "4.18.1",
+ "oh-my-opencode-windows-x64": "4.18.1",
+ "oh-my-opencode-windows-x64-baseline": "4.18.1"
},
overrides: {
"@earendil-works/pi-agent-core": "0.80.3",
@@ -66795,14 +66795,14 @@ var init_config_manager = __esm(() => {
// packages/telemetry-core/src/activity-state.ts
import { existsSync as existsSync28, mkdirSync as mkdirSync8, readFileSync as readFileSync14 } from "fs";
-import { basename as basename10, join as join53 } from "path";
+import { basename as basename11, join as join53 } from "path";
function resolveTelemetryStateDir(product, options = {}) {
const dataDir = resolveXdgDataDir(product.cacheDirName, {
env: options.env,
osProvider: options.osProvider
});
const xdgStateDir = options.env?.XDG_DATA_HOME === undefined ? undefined : join53(options.env.XDG_DATA_HOME, product.cacheDirName);
- if (dataDir === xdgStateDir || xdgStateDir === undefined && basename10(dataDir) === product.cacheDirName) {
+ if (dataDir === xdgStateDir || xdgStateDir === undefined && basename11(dataDir) === product.cacheDirName) {
return dataDir;
}
return join53(dataDir, product.cacheDirName);
@@ -67036,18 +67036,18 @@ var init_env2 = __esm(() => {
});
// packages/telemetry-core/src/machine-id.ts
-import { createHash as createHash3 } from "crypto";
+import { createHash as createHash4 } from "crypto";
import os4 from "os";
function getDefaultTelemetryOsProvider() {
return os4;
}
function getTelemetryDistinctId(machineIdPrefix, osProvider = getDefaultTelemetryOsProvider()) {
- return createHash3("sha256").update(`${machineIdPrefix}${osProvider.hostname()}`).digest("hex");
+ return createHash4("sha256").update(`${machineIdPrefix}${osProvider.hostname()}`).digest("hex");
}
var init_machine_id = () => {};
// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
-import { dirname as dirname18, posix as posix2, sep as sep7 } from "path";
+import { dirname as dirname18, posix as posix3, sep as sep7 } from "path";
function createModulerModifier() {
const getModuleFromFileName = createGetModuleFromFilename();
return async (frames) => {
@@ -67062,7 +67062,7 @@ function createGetModuleFromFilename(basePath = process.argv[1] ? dirname18(proc
if (!filename)
return;
const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;
- let { dir, base: file2, ext } = posix2.parse(normalizedFilename);
+ let { dir, base: file2, ext } = posix3.parse(normalizedFilename);
if (ext === ".js" || ext === ".mjs" || ext === ".cjs")
file2 = file2.slice(0, -1 * ext.length);
const decodedFile = decodeURIComponent(file2);
@@ -72602,7 +72602,7 @@ var package_default2;
var init_package2 = __esm(() => {
package_default2 = {
name: "@oh-my-opencode/omo-codex",
- version: "4.18.0",
+ version: "4.18.1",
type: "module",
private: true,
description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",
@@ -73421,18 +73421,18 @@ function removeFromTextBunLock(lockPath, packageNames) {
try {
const content = fs12.readFileSync(lockPath, "utf-8");
const lock = JSON.parse(stripTrailingCommas(content));
- let removed = false;
+ let removed2 = false;
for (const packageName of packageNames) {
if (lock.packages?.[packageName]) {
delete lock.packages[packageName];
log2(`[auto-update-checker] Removed from bun.lock: ${packageName}`);
- removed = true;
+ removed2 = true;
}
}
- if (removed) {
+ if (removed2) {
fs12.writeFileSync(lockPath, JSON.stringify(lock, null, 2));
}
- return removed;
+ return removed2;
} catch (error51) {
if (!(error51 instanceof Error)) {
throw error51;
@@ -73472,7 +73472,7 @@ function getInvalidationPackageNames(packageName, defaultPackageName, acceptedPa
function removeSpecifierRootDirs(cacheDir, packageNames) {
const parentDirs = [cacheDir, path13.join(cacheDir, "packages")];
const prefixes = packageNames.map((packageName) => `${packageName}@`);
- let removed = false;
+ let removed2 = false;
for (const parentDir of parentDirs) {
if (!fs12.existsSync(parentDir)) {
continue;
@@ -73484,10 +73484,10 @@ function removeSpecifierRootDirs(cacheDir, packageNames) {
const specifierDir = path13.join(parentDir, entry.name);
fs12.rmSync(specifierDir, { recursive: true, force: true });
log2(`[auto-update-checker] Specifier cache removed: ${specifierDir}`);
- removed = true;
+ removed2 = true;
}
}
- return removed;
+ return removed2;
}
function invalidatePackage(packageName, options = {}) {
try {
@@ -77787,65 +77787,297 @@ function formatUnknownError(error) {
}
// packages/omo-codex/src/install/lsp-daemon-reaper.ts
-import { readFile as readFile18, readdir as readdir9, rm as rm10 } from "fs/promises";
+import { createHash as createHash3 } from "crypto";
+import { lstat as lstat11, readFile as readFile19, readdir as readdir10, rm as rm10 } from "fs/promises";
+import { tmpdir as tmpdir3 } from "os";
+import { join as join48, posix as posix2 } from "path";
+
+// packages/omo-codex/src/install/lsp-daemon-reaper-attestation.ts
+import { execFile as execFile2 } from "child_process";
+import { readFile as readFile18, readdir as readdir9, readlink as readlink5 } from "fs/promises";
import { connect } from "net";
-import { join as join48 } from "path";
-async function reapLspDaemons(codexHome, deps = {}) {
- const killProcess = deps.killProcess ?? sendSigterm;
- const isDaemonLive = deps.isDaemonLive ?? probeSocketLive;
- const daemonRoot = join48(codexHome, "codex-lsp", "daemon");
- const reaped = [];
- let entries;
+import { basename as basename10 } from "path";
+var PROBE_TIMEOUT_MS = 500;
+async function probeLegacyJsonRpcEndpoint(endpoint, timeoutMs = PROBE_TIMEOUT_MS) {
+ return await new Promise((resolve14) => {
+ const socket = connect(endpoint);
+ let settled = false;
+ let buffer = "";
+ const finish = (value) => {
+ if (settled)
+ return;
+ settled = true;
+ clearTimeout(timer);
+ socket.destroy();
+ resolve14(value);
+ };
+ const timer = setTimeout(() => finish(false), timeoutMs);
+ timer.unref?.();
+ socket.once("connect", () => {
+ socket.write(`${JSON.stringify(legacyStatusRequest())}
+`);
+ });
+ socket.on("data", (chunk) => {
+ buffer += chunk.toString("utf8");
+ const newlineIndex = buffer.indexOf(`
+`);
+ if (newlineIndex < 0)
+ return;
+ finish(isJsonRpcResponse(buffer.slice(0, newlineIndex).trim()));
+ });
+ socket.once("error", () => finish(false));
+ });
+}
+async function attestLegacyDaemonOwnership(input, deps = {}) {
+ if (input.platform === "linux")
+ return await attestLinuxOwnership(input, deps);
+ if (input.platform === "darwin")
+ return await attestMacOwnership(input, deps);
+ return false;
+}
+async function attestLinuxOwnership(input, deps) {
+ const readFileImpl = deps.readFile ?? readFile18;
+ const readDirImpl = deps.readDir ?? readdir9;
+ const readLinkImpl = deps.readLink ?? readlink5;
+ const procNetUnix = await readText(readFileImpl, "/proc/net/unix");
+ if (procNetUnix === null)
+ return false;
+ const inode = inodeForEndpoint(procNetUnix, input.endpoint);
+ if (inode === null)
+ return false;
+ const fdEntries = await readDirImpl(`/proc/${input.pid}/fd`).catch(() => null);
+ if (fdEntries === null)
+ return false;
+ let ownsEndpoint = false;
+ for (const fdEntry of fdEntries) {
+ const target = await readLinkImpl(`/proc/${input.pid}/fd/${fdEntry}`).catch(() => null);
+ if (target !== `socket:[${inode}]`)
+ continue;
+ ownsEndpoint = true;
+ break;
+ }
+ if (!ownsEndpoint)
+ return false;
+ const cmdline = await readBinary(readFileImpl, `/proc/${input.pid}/cmdline`);
+ if (cmdline === null)
+ return false;
+ return isNodeCliDaemonArgv(splitCmdline(cmdline));
+}
+async function attestMacOwnership(input, deps) {
+ const executeFileImpl = deps.executeFile ?? execFile2;
+ const filteredLsofOutput = await executeForStdout(executeFileImpl, "/usr/sbin/lsof", [
+ "-a",
+ "-n",
+ "-P",
+ "-p",
+ String(input.pid),
+ "-U",
+ "-Fn",
+ "--",
+ input.endpoint
+ ]);
+ const lsofOutput = filteredLsofOutput ?? await executeForStdout(executeFileImpl, "/usr/sbin/lsof", [
+ "-a",
+ "-n",
+ "-P",
+ "-p",
+ String(input.pid),
+ "-U",
+ "-Fn"
+ ]);
+ if (lsofOutput === null || !lsofShowsUnixEndpoint(lsofOutput, input.pid, input.endpoint))
+ return false;
+ const commandOutput = await executeForStdout(executeFileImpl, "/bin/ps", ["-p", String(input.pid), "-o", "command="]);
+ if (commandOutput === null)
+ return false;
+ return isNodeCliDaemonCommand(commandOutput.trim());
+}
+function legacyStatusRequest() {
+ return {
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: { name: "status", arguments: {} }
+ };
+}
+function isJsonRpcResponse(line) {
+ if (line.length === 0)
+ return false;
try {
- entries = await readdir9(daemonRoot);
+ const parsed = JSON.parse(line);
+ return parsed.jsonrpc === "2.0" && parsed.id === 1 && (Object.hasOwn(parsed, "result") || Object.hasOwn(parsed, "error"));
} catch {
- return reaped;
+ return false;
}
- for (const entry of entries) {
- const versionDir = join48(daemonRoot, entry);
- const pid = await readPidFile(join48(versionDir, "daemon.pid"));
- const socketPath = await readEndpointFile(join48(versionDir, "daemon.endpoint"));
- if (pid !== null && socketPath !== null && await isDaemonLive(socketPath) && killProcess(pid)) {
- reaped.push(pid);
+}
+function inodeForEndpoint(procNetUnix, endpoint) {
+ for (const line of procNetUnix.split(/\r?\n/)) {
+ const trimmed = line.trim();
+ if (trimmed.length === 0 || trimmed.startsWith("Num"))
+ continue;
+ const fields = trimmed.split(/\s+/);
+ if (fields.length < 8 || fields[7] !== endpoint)
+ continue;
+ return fields[6] ?? null;
+ }
+ return null;
+}
+function splitCmdline(buffer) {
+ return buffer.toString("utf8").split("\x00").filter((value) => value.length > 0);
+}
+function isNodeCliDaemonArgv(argv) {
+ if (argv.length < 2 || !argv.includes("daemon"))
+ return false;
+ const executable = basename10(argv[0] ?? "");
+ if (!/^node(?:\.exe)?$/i.test(executable))
+ return false;
+ return argv.some((value) => value === "cli.js" || value.endsWith("/cli.js") || value.endsWith("\\cli.js"));
+}
+function lsofShowsUnixEndpoint(output, pid, endpoint) {
+ const lines = output.split(/\r?\n/).filter((line) => line.length > 0);
+ const endpointName = basename10(endpoint);
+ return lines.includes(`p${pid}`) && lines.some((line) => line === `n${endpoint}` || line === `n${endpointName}`);
+}
+function isNodeCliDaemonCommand(command) {
+ return /\bnode(?:\.exe)?\b/i.test(command) && /\bcli\.js\b/.test(command) && /\bdaemon\b/.test(command);
+}
+async function executeForStdout(executeFileImpl, file2, args) {
+ return await new Promise((resolve14) => {
+ executeFileImpl(file2, [...args], { encoding: "utf8", maxBuffer: 1024 * 1024, timeout: 1000 }, (error, stdout) => {
+ if (error !== null) {
+ resolve14(null);
+ return;
+ }
+ resolve14(stdout);
+ });
+ });
+}
+async function readText(readFileImpl, path7) {
+ return await readFileImpl(path7, "utf8").catch(() => null);
+}
+async function readBinary(readFileImpl, path7) {
+ return await readFileImpl(path7).catch(() => null);
+}
+
+// packages/omo-codex/src/install/lsp-daemon-reaper.ts
+var LEGACY_EXIT_WAIT_TIMEOUT_MS = 5000;
+var LEGACY_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;
+async function reapLspDaemons(codexHome, deps = {}) {
+ const daemonRoot = join48(codexHome, "codex-lsp", "daemon");
+ const platform = deps.platform ?? process.platform;
+ const tmpDir = deps.tmpDir ?? tmpdir3();
+ const probe2 = deps.probeLegacyJsonRpc ?? probeLegacyJsonRpcEndpoint;
+ const attest = deps.attestLegacyDaemonOwnership ?? ((input) => attestLegacyDaemonOwnership(input));
+ const killProcess = deps.killProcess ?? sendSigterm;
+ const waitForProcessExit = deps.waitForProcessExit ?? defaultWaitForProcessExit;
+ const entries = await readdir10(daemonRoot, { withFileTypes: true }).catch(() => []);
+ const results = [];
+ for (const entry of [...entries].sort((left, right) => left.name.localeCompare(right.name))) {
+ const versionPath = join48(daemonRoot, entry.name);
+ const parsedVersion = parseVersionEntry(entry.name);
+ if (parsedVersion === null || !entry.isDirectory()) {
+ await removeVersionDir(versionPath);
+ results.push(removed(entry.name, "removed invalid legacy version entry"));
+ continue;
+ }
+ const metadata = await readLegacyMetadata({ versionPath, version: parsedVersion, codexHome, platform, tmpDir });
+ if (metadata.kind === "remove") {
+ await removeVersionDir(versionPath);
+ results.push(removed(parsedVersion, metadata.reason));
+ continue;
+ }
+ if (!await probe2(metadata.endpoint)) {
+ await removeVersionDir(versionPath);
+ results.push(removed(parsedVersion, "removed stale legacy daemon state"));
+ continue;
+ }
+ if (platform === "win32") {
+ results.push(deferred(parsedVersion, "legacy named pipe responded but Windows cannot prove pid ownership safely"));
+ continue;
}
- await rm10(versionDir, { recursive: true, force: true });
+ const owned = await attest({ pid: metadata.pid, endpoint: metadata.endpoint, platform });
+ if (!owned) {
+ results.push(deferred(parsedVersion, "legacy endpoint responded but pid ownership was not proven"));
+ continue;
+ }
+ if (!killProcess(metadata.pid)) {
+ await removeVersionDir(versionPath);
+ results.push(removed(parsedVersion, "removed stale legacy daemon state"));
+ continue;
+ }
+ if (!await waitForProcessExit(metadata.pid, LEGACY_EXIT_WAIT_TIMEOUT_MS)) {
+ results.push(deferred(parsedVersion, `timed out waiting ${LEGACY_EXIT_WAIT_TIMEOUT_MS}ms for the proven legacy daemon to exit`));
+ continue;
+ }
+ await removeVersionDir(versionPath);
+ results.push(terminated(parsedVersion, "terminated proven owned legacy daemon"));
}
- return reaped;
+ return results;
}
-async function readEndpointFile(path7) {
- try {
- const content = (await readFile18(path7, "utf8")).trim();
- return content.length > 0 ? content : null;
- } catch {
+function parseVersionEntry(entryName) {
+ if (!entryName.startsWith("v"))
return null;
+ const version = entryName.slice(1);
+ return LEGACY_VERSION_PATTERN.test(version) ? version : null;
+}
+async function readLegacyMetadata(input) {
+ const pidText = await readRegularTrimmedFile(join48(input.versionPath, "daemon.pid"));
+ if (pidText === "non_regular")
+ return { kind: "remove", reason: "removed non-regular legacy daemon metadata" };
+ if (pidText === null)
+ return { kind: "remove", reason: "removed malformed legacy daemon metadata" };
+ const pid = Number.parseInt(pidText, 10);
+ if (!Number.isInteger(pid) || pid <= 0)
+ return { kind: "remove", reason: "removed malformed legacy daemon metadata" };
+ const endpointText = await readRegularTrimmedFile(join48(input.versionPath, "daemon.endpoint"));
+ if (endpointText === "non_regular")
+ return { kind: "remove", reason: "removed non-regular legacy daemon metadata" };
+ if (endpointText === null)
+ return { kind: "remove", reason: "removed malformed legacy daemon metadata" };
+ const allowedEndpoints = legacyEndpointCandidates({
+ version: input.version,
+ versionPath: input.versionPath,
+ platform: input.platform,
+ tmpDir: input.tmpDir
+ });
+ if (!allowedEndpoints.includes(endpointText)) {
+ return { kind: "remove", reason: "removed legacy daemon state with an endpoint outside the frozen vectors" };
}
+ return { kind: "valid", pid, endpoint: endpointText };
}
-async function readPidFile(path7) {
- try {
- const pid = Number.parseInt((await readFile18(path7, "utf8")).trim(), 10);
- return Number.isInteger(pid) && pid > 0 ? pid : null;
- } catch {
- return null;
+function legacyEndpointCandidates(input) {
+ if (input.platform === "win32") {
+ const normalizedVersionPath = input.versionPath.replaceAll("/", "\\");
+ const digest = shortDigest(normalizedVersionPath);
+ return [`\\\\.\\pipe\\omo-lsp-${input.version}-${digest}`];
}
+ const natural = posix2.join(input.versionPath, "daemon.sock");
+ const hashed = posix2.join(input.tmpDir, `omo-lsp-${input.version}-${shortDigest(input.versionPath)}.sock`);
+ return [natural, hashed];
}
-function probeSocketLive(socketPath, timeoutMs = 500) {
- return new Promise((resolve14) => {
- const socket = connect(socketPath);
- const done = (ok) => {
- socket.destroy();
- resolve14(ok);
- };
- const timer = setTimeout(() => done(false), timeoutMs);
- timer.unref();
- socket.once("connect", () => {
- clearTimeout(timer);
- done(true);
- });
- socket.once("error", () => {
- clearTimeout(timer);
- done(false);
- });
- });
+async function readRegularTrimmedFile(path7) {
+ const stats = await lstat11(path7).catch(() => null);
+ if (stats === null)
+ return null;
+ if (!stats.isFile())
+ return "non_regular";
+ const content = (await readFile19(path7, "utf8")).trim();
+ return content.length > 0 ? content : null;
+}
+function shortDigest(value) {
+ return createHash3("sha256").update(value).digest("hex").slice(0, 16);
+}
+async function removeVersionDir(path7) {
+ await rm10(path7, { recursive: true, force: true });
+}
+function removed(version, reason) {
+ return { version, status: "removed", reason };
+}
+function terminated(version, reason) {
+ return { version, status: "terminated", reason };
+}
+function deferred(version, reason) {
+ return { version, status: "deferred", reason };
}
function sendSigterm(pid) {
try {
@@ -77855,6 +78087,24 @@ function sendSigterm(pid) {
return false;
}
}
+async function defaultWaitForProcessExit(pid, timeoutMs) {
+ const deadline = Date.now() + timeoutMs;
+ for (;; ) {
+ if (!processIsRunning(pid))
+ return true;
+ if (Date.now() >= deadline)
+ return false;
+ await new Promise((resolve14) => setTimeout(resolve14, 100));
+ }
+}
+function processIsRunning(pid) {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
// packages/omo-codex/src/install/codex-installer-bin-dir.ts
import { homedir as homedir5 } from "os";
@@ -77872,7 +78122,7 @@ function resolveCodexInstallerBinDir(input) {
}
// packages/omo-codex/src/install/codex-git-bash-hooks.ts
-import { readFile as readFile19, writeFile as writeFile11 } from "fs/promises";
+import { readFile as readFile20, writeFile as writeFile11 } from "fs/promises";
import { join as join50 } from "path";
var WINDOWS_ONLY_GIT_BASH_HOOKS = new Set([
"./hooks/pre-tool-use-recommending-git-bash-mcp.json",
@@ -77882,7 +78132,7 @@ async function removeGitBashHooksOffWindows(input) {
if (input.platform === "win32")
return;
const manifestPath = join50(input.pluginRoot, ".codex-plugin", "plugin.json");
- const parsed = JSON.parse(await readFile19(manifestPath, "utf8"));
+ const parsed = JSON.parse(await readFile20(manifestPath, "utf8"));
if (!isPlainRecord3(parsed) || !Array.isArray(parsed.hooks))
return;
const hooks = parsed.hooks.filter((hook) => typeof hook !== "string" || !WINDOWS_ONLY_GIT_BASH_HOOKS.has(hook));
@@ -78076,7 +78326,16 @@ async function runCodexInstaller(options = {}) {
pluginNames: marketplace.plugins.map((plugin) => plugin.name)
});
}
- await reapLspDaemons(codexHome).catch(() => []);
+ const legacyDaemonCleanup = await reapLspDaemons(codexHome).catch((error) => {
+ const message = error instanceof Error ? error.message : String(error);
+ log4(`Warning: skipped legacy Codex LSP daemon cleanup: ${message}`);
+ return [];
+ });
+ for (const cleanup of legacyDaemonCleanup) {
+ if (cleanup.status !== "deferred")
+ continue;
+ log4(`Warning: deferred legacy Codex LSP daemon cleanup for v${cleanup.version}: ${cleanup.reason}`);
+ }
const marketplaceRoot = join55(codexHome, "plugins", "cache", marketplace.name);
await writeCachedMarketplaceManifest({
marketplaceName: marketplace.name,
@@ -78168,10 +78427,10 @@ function codexMarketplaceSource(marketplaceRoot) {
}
// packages/omo-codex/src/install/codex-installation-detection.ts
init_bun_which_shim();
-import { execFile as execFile2 } from "child_process";
+import { execFile as execFile3 } from "child_process";
import { existsSync as existsSync31 } from "fs";
import { homedir as homedir7 } from "os";
-import { posix as posix3, win32 as win323 } from "path";
+import { posix as posix4, win32 as win323 } from "path";
var CODEX_PATH_CHECK_LABEL = "codex (PATH)";
var WINDOWS_START_APPS_ARGS = [
"-NoProfile",
@@ -78248,11 +78507,11 @@ async function findWindowsCodexStartApp(runCommand) {
}
}
function macCodexAppPaths(homeDir) {
- return ["/Applications/Codex.app", posix3.join(homeDir, "Applications", "Codex.app")];
+ return ["/Applications/Codex.app", posix4.join(homeDir, "Applications", "Codex.app")];
}
function macCodexDmgPaths(homeDir) {
- const downloads = posix3.join(homeDir, "Downloads");
- return [posix3.join(downloads, "codex.dmg"), posix3.join(downloads, "Codex.dmg")];
+ const downloads = posix4.join(homeDir, "Downloads");
+ return [posix4.join(downloads, "codex.dmg"), posix4.join(downloads, "Codex.dmg")];
}
function windowsCodexCliPaths(env3) {
const candidates = [];
@@ -78290,18 +78549,18 @@ function dedupe(values) {
}
function defaultRunCommand2(command, args) {
return new Promise((resolve16) => {
- execFile2(command, [...args], { encoding: "utf8", windowsHide: true }, (error, stdout) => {
+ execFile3(command, [...args], { encoding: "utf8", windowsHide: true }, (error, stdout) => {
resolve16({ success: error === null, stdout });
});
});
}
// packages/omo-codex/src/install/codex-cleanup.ts
-import { lstat as lstat12, readFile as readFile21, readdir as readdir10, rm as rm11, rmdir } from "fs/promises";
+import { lstat as lstat13, readFile as readFile22, readdir as readdir11, rm as rm11, rmdir } from "fs/promises";
import { homedir as homedir8 } from "os";
import { isAbsolute as isAbsolute11, join as join57, relative as relative7, resolve as resolve17 } from "path";
// packages/omo-codex/src/install/codex-cleanup-config.ts
-import { lstat as lstat11, mkdir as mkdir8, readFile as readFile20, writeFile as writeFile12 } from "fs/promises";
+import { lstat as lstat12, mkdir as mkdir8, readFile as readFile21, writeFile as writeFile12 } from "fs/promises";
import { dirname as dirname19 } from "path";
var MANAGED_MARKETPLACES = ["sisyphuslabs", "lazycodex", "code-yeongyu-codex-plugins"];
var LEGACY_MANAGED_CODEX_AGENT_NAMES_TO_PURGE2 = ["codex-ultrawork-reviewer"];
@@ -78334,7 +78593,7 @@ function cleanupCodexLightConfigText(config) {
async function cleanupCodexConfig(configPath, now) {
if (!await configExists(configPath))
return { changed: false };
- const original = await readFile20(configPath, "utf8");
+ const original = await readFile21(configPath, "utf8");
const next = cleanupCodexLightConfigText(original);
if (next === original)
return { changed: false };
@@ -78403,7 +78662,7 @@ function formatBackupTimestamp2(date) {
}
async function configExists(path7) {
try {
- await lstat11(path7);
+ await lstat12(path7);
return true;
} catch (error) {
if (nodeErrorCode5(error) === "ENOENT")
@@ -78521,7 +78780,7 @@ async function collectBootstrapDataDirsByGlob(codexHome) {
async function walkForManagedBootstrapDirs(directory, depth, results) {
if (depth > BOOTSTRAP_DATA_GLOB_MAX_DEPTH)
return;
- const entries = await readdir10(directory, { withFileTypes: true }).catch(() => null);
+ const entries = await readdir11(directory, { withFileTypes: true }).catch(() => null);
if (entries === null)
return;
for (const entry of entries) {
@@ -78553,7 +78812,7 @@ async function removeManagedPathBestEffort(path7, seams) {
}
async function attemptRemove(path7) {
try {
- if (await lstat12(path7).catch(() => null) === null)
+ if (await lstat13(path7).catch(() => null) === null)
return false;
await rm11(path7, { recursive: true, force: true });
return true;
@@ -78579,7 +78838,7 @@ async function collectInstalledAgentPaths(codexHome, configPath) {
];
const versionRoot = join57(codexHome, "plugins", "cache", "sisyphuslabs", "omo");
if (await exists6(versionRoot)) {
- const entries = await readdir10(versionRoot, { withFileTypes: true });
+ const entries = await readdir11(versionRoot, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory())
manifestPaths.push(join57(versionRoot, entry.name, INSTALLED_AGENTS_MANIFEST));
@@ -78599,20 +78858,20 @@ async function collectInstalledAgentPaths(codexHome, configPath) {
async function readManagedAgentPathsFromConfig(codexHome, configPath) {
if (!await exists6(configPath))
return [];
- const config = await readFile21(configPath, "utf8");
+ const config = await readFile22(configPath, "utf8");
return MANAGED_CODEX_AGENT_NAMES2.filter((agentName) => config.includes(`config_file = ${JSON.stringify(`./agents/${agentName}.toml`)}`)).map((agentName) => join57(codexHome, "agents", `${agentName}.toml`));
}
async function readInstalledAgentManifest(manifestPath) {
if (!await exists6(manifestPath))
return [];
- const parsed = JSON.parse(await readFile21(manifestPath, "utf8"));
+ const parsed = JSON.parse(await readFile22(manifestPath, "utf8"));
if (!isPlainRecord3(parsed) || !Array.isArray(parsed.agents))
return [];
return parsed.agents.filter((path7) => typeof path7 === "string");
}
async function removeManifestListedAgentLinks(codexHome, paths) {
const agentsDir = join57(codexHome, "agents");
- const removed = [];
+ const removed2 = [];
const skipped2 = [];
for (const path7 of paths) {
if (!isSafeManagedAgentPath(agentsDir, path7)) {
@@ -78627,9 +78886,9 @@ async function removeManifestListedAgentLinks(codexHome, paths) {
continue;
}
await rm11(path7, { force: true });
- removed.push(path7);
+ removed2.push(path7);
}
- return { removed, skipped: skipped2 };
+ return { removed: removed2, skipped: skipped2 };
}
function isSafeManagedAgentPath(agentsDir, path7) {
if (!isAbsolute11(path7))
@@ -78647,7 +78906,7 @@ async function exists6(path7) {
}
async function maybeLstat2(path7) {
try {
- return await lstat12(path7);
+ return await lstat13(path7);
} catch (error) {
if (nodeErrorCode6(error) === "ENOENT")
return null;
@@ -78662,18 +78921,26 @@ function nodeErrorCode6(error) {
// packages/omo-codex/src/install/codex-git-bash-mcp-env.ts
var CODEGRAPH_RELATIVE_ARGS2 = new Set(["components/codegraph/dist/serve.js", "./components/codegraph/dist/serve.js"]);
// packages/omo-senpi/src/install/install-senpi.ts
-import { execFile as execFile3 } from "child_process";
+import { execFile as execFile4 } from "child_process";
import { constants as constants7, existsSync as existsSync32 } from "fs";
-import { access, copyFile as copyFile3, mkdir as mkdir9, readFile as readFile22, rename as rename5, writeFile as writeFile13 } from "fs/promises";
+import { access, copyFile as copyFile3, mkdir as mkdir9, readFile as readFile23, rename as rename5, writeFile as writeFile13 } from "fs/promises";
import { homedir as homedir9 } from "os";
import { dirname as dirname21, join as join58, resolve as resolve18 } from "path";
import { fileURLToPath } from "url";
import { promisify as promisify2 } from "util";
-var execFileAsync2 = promisify2(execFile3);
+var execFileAsync2 = promisify2(execFile4);
var REQUIRED_PLUGIN_ARTIFACTS = [
join58("extensions", "omo.js"),
join58("skills", "ultrawork", "SKILL.md"),
- join58("skills", "ulw-loop", "SKILL.md")
+ join58("skills", "ulw-loop", "SKILL.md"),
+ join58("runtime", "lsp-daemon", "dist", "cli.js"),
+ join58("runtime", "lsp-daemon", "dist", "index.js"),
+ join58("runtime", "lsp-daemon", "dist", "index.d.ts"),
+ join58("runtime", "lsp-daemon", "dist", "daemon-client.js"),
+ join58("runtime", "lsp-daemon", "dist", "daemon-client.d.ts"),
+ join58("runtime", "lsp-daemon", "dist", "package.json"),
+ join58("runtime", "lsp-daemon", "dist", ".omo-runtime-manifest.json"),
+ join58("scripts", "install.mjs")
];
async function runSenpiInstaller(options = {}) {
const context = resolveInstallContext(options);
@@ -78697,7 +78964,8 @@ async function runSenpiInstaller(options = {}) {
}
function resolveInstallContext(options) {
const env3 = options.env ?? process.env;
- const repoRoot = resolve18(options.repoRoot ?? findRepoRoot2(dirname21(fileURLToPath(import.meta.url))));
+ const allowBuild = options.pluginPath === undefined;
+ const repoRoot = resolve18(options.repoRoot ?? (allowBuild ? findRepoRoot2(dirname21(fileURLToPath(import.meta.url))) : dirname21(resolve18(options.pluginPath))));
const agentDir = resolve18(options.agentDir ?? env3.SENPI_CODING_AGENT_DIR ?? join58(homedir9(), ".senpi", "agent"));
const pluginPath = resolve18(options.pluginPath ?? join58(repoRoot, "packages", "omo-senpi", "plugin"));
return {
@@ -78706,6 +78974,7 @@ function resolveInstallContext(options) {
agentDir,
settingsPath: join58(agentDir, "settings.json"),
pluginPath,
+ allowBuild,
runCommand: options.runCommand ?? defaultRunCommand3
};
}
@@ -78713,8 +78982,13 @@ async function ensurePluginArtifacts(context) {
const missing = await hasMissingPluginArtifact(context.pluginPath);
if (!missing)
return;
+ if (!context.allowBuild) {
+ throw new Error(`Packed omo-senpi plugin is missing required runtime artifacts at ${context.pluginPath}`);
+ }
await context.runCommand("node", [join58(context.pluginPath, "scripts", "build-extension.mjs")], { cwd: context.repoRoot });
await context.runCommand("node", [join58(context.pluginPath, "scripts", "sync-skills.mjs")], { cwd: context.repoRoot });
+ await context.runCommand("node", [join58(context.pluginPath, "scripts", "build-install.mjs")], { cwd: context.repoRoot });
+ await context.runCommand("node", [join58(context.pluginPath, "scripts", "stage-lsp-daemon-runtime.mjs")], { cwd: context.repoRoot });
}
async function hasMissingPluginArtifact(pluginPath) {
for (const artifact of REQUIRED_PLUGIN_ARTIFACTS) {
@@ -78733,7 +79007,7 @@ async function defaultRunCommand3(command, args, options) {
async function readSettings(settingsPath) {
let raw;
try {
- raw = await readFile22(settingsPath, "utf8");
+ raw = await readFile23(settingsPath, "utf8");
} catch (error) {
if (isErrno(error, "ENOENT"))
return {};
@@ -78812,7 +79086,7 @@ function isErrno(error, code) {
return error instanceof Error && "code" in error && error.code === code;
}
// packages/omo-opencode/src/cli/star-request.ts
-import { execFile as execFile4 } from "child_process";
+import { execFile as execFile5 } from "child_process";
import { promisify as promisify3 } from "util";
var STAR_REPOSITORIES = [
"code-yeongyu/oh-my-openagent",
@@ -78824,7 +79098,7 @@ var PLATFORM_REPOSITORIES = {
both: STAR_REPOSITORIES,
senpi: STAR_REPOSITORIES
};
-var execFileAsync3 = promisify3(execFile4);
+var execFileAsync3 = promisify3(execFile5);
async function runGitHubStarCommand(repository) {
await execFileAsync3("gh", ["api", "--silent", "--method", "PUT", `/user/starred/${repository}`]);
}
@@ -97194,7 +97468,7 @@ var import_picocolors11 = __toESM(require_picocolors(), 1);
// packages/omo-opencode/src/cli/run/opencode-binary-resolver.ts
init_bun_which_shim();
init_spawn_with_windows_hide();
-import { delimiter as delimiter2, dirname as dirname23, posix as posix4, win32 as win324 } from "path";
+import { delimiter as delimiter2, dirname as dirname23, posix as posix5, win32 as win324 } from "path";
var OPENCODE_COMMANDS = ["opencode", "opencode-desktop"];
var WINDOWS_SUFFIXES = ["", ".exe", ".cmd", ".bat", ".ps1"];
function getCommandCandidates(platform) {
@@ -97205,7 +97479,7 @@ function getCommandCandidates(platform) {
function getPathTools(platform) {
if (platform === "win32")
return win324;
- return posix4;
+ return posix5;
}
function collectCandidateBinaryPaths(pathEnv, which2 = bunWhich, platform = process.platform) {
const seen = new Set;
@@ -100364,12 +100638,12 @@ import { dirname as dirname30, join as join79 } from "path";
// packages/omo-opencode/src/hooks/comment-checker/downloader.ts
import { join as join78 } from "path";
-import { homedir as homedir18, tmpdir as tmpdir3 } from "os";
+import { homedir as homedir18, tmpdir as tmpdir4 } from "os";
init_binary_downloader();
init_logger2();
init_plugin_identity();
var DEBUG = process.env.COMMENT_CHECKER_DEBUG === "1";
-var DEBUG_FILE = join78(tmpdir3(), "comment-checker-debug.log");
+var DEBUG_FILE = join78(tmpdir4(), "comment-checker-debug.log");
function getCacheDir2() {
if (process.platform === "win32") {
const localAppData = process.env.LOCALAPPDATA || process.env.APPDATA;
@@ -100606,13 +100880,14 @@ async function getGhCliInfo(dependencies = {}) {
}
// packages/omo-opencode/src/cli/doctor/checks/tools-lsp.ts
-import { readFileSync as readFileSync38 } from "fs";
+import { readFileSync as readFileSync39 } from "fs";
import { join as join80 } from "path";
// packages/omo-opencode/src/mcp/lsp.ts
-import { existsSync as existsSync56 } from "fs";
+import { existsSync as existsSync56, readFileSync as readFileSync38 } from "fs";
import { delimiter as delimiter3, dirname as dirname31, resolve as resolve21 } from "path";
import { fileURLToPath as fileURLToPath7 } from "url";
+init_opencode_config_dir();
// packages/omo-opencode/src/mcp/cli-suffix.ts
function normalizeCliPath(path14) {
@@ -100624,7 +100899,7 @@ function hasCliSuffix(candidatePath, suffix) {
// packages/omo-opencode/src/mcp/runtime-executable.ts
init_bun_which_shim();
-import { basename as basename12 } from "path";
+import { basename as basename13 } from "path";
var NODE_EXECUTABLE_NAMES = new Set(["node", "node.exe"]);
function isUnsafeCommandName2(commandName) {
if (commandName.length === 0)
@@ -100640,7 +100915,7 @@ function isUnsafeCommandName2(commandName) {
return false;
}
function isNodeExecPath(execPath) {
- return NODE_EXECUTABLE_NAMES.has(basename12(execPath).toLowerCase());
+ return NODE_EXECUTABLE_NAMES.has(basename13(execPath).toLowerCase());
}
function resolveRuntimeExecutable(commandName, options = {}) {
if (isUnsafeCommandName2(commandName)) {
@@ -100710,8 +100985,15 @@ var LSP_TOOLS_PACKAGE_REL = "packages/lsp-tools-mcp";
var DIST_CLI_REL = "dist/cli.js";
var SOURCE_CLI_REL = "src/cli.ts";
var PROJECT_LSP_CONFIGS = [".opencode/lsp.json", ".omo/lsp.json", ".omo/lsp-client.json"];
+var DAEMON_PACKAGE_NAME = "@code-yeongyu/lsp-daemon";
+var OMO_LSP_DAEMON_CLI = "OMO_LSP_DAEMON_CLI";
+var OMO_LSP_DAEMON_VERSION = "OMO_LSP_DAEMON_VERSION";
+var DaemonPackageSchema = exports_external.object({
+ version: exports_external.string().min(1)
+});
var LSP_BOOTSTRAP_SCRIPT = [
"const { existsSync } = require('node:fs')",
+ "const { createRequire } = require('node:module')",
"const { join } = require('node:path')",
"const { spawnSync } = require('node:child_process')",
"const root = process.argv[1]",
@@ -100720,16 +101002,18 @@ var LSP_BOOTSTRAP_SCRIPT = [
`const toolsPackage = join(root, '${LSP_TOOLS_PACKAGE_REL}')`,
`const daemonPackage = join(root, '${PACKAGE_REL}')`,
"const toolsDist = join(toolsPackage, 'dist/cli.js')",
- "const daemonDist = join(daemonPackage, 'dist/cli.js')",
+ "const daemonPackageJson = join(daemonPackage, 'package.json')",
"const daemonSource = join(daemonPackage, 'src/cli.ts')",
"const run = (command, args, stdio) => spawnSync(command, args, { cwd: root, env: process.env, stdio })",
"const finish = (result) => { if (result.error) { console.error(result.error.message); process.exit(1) } process.exit(result.status ?? 1) }",
"const runIfAvailable = (command, args) => { const result = run(command, args, 'inherit'); if (result.error) return false; finish(result); return true }",
- "if (existsSync(daemonDist)) finish(run(process.execPath, [daemonDist, 'mcp'], 'inherit'))",
- "if (existsSync(daemonSource) && existsSync(toolsDist)) runIfAvailable(bun, [daemonSource, 'mcp'])",
+ `const resolveDaemonCli = () => { try { return createRequire(daemonPackageJson).resolve('${DAEMON_PACKAGE_NAME}/cli') } catch (error) { if (error instanceof Error) return null; throw error } }`,
+ "const daemonCli = existsSync(daemonPackageJson) ? resolveDaemonCli() : null",
+ "if (daemonCli) finish(run(process.execPath, [daemonCli, 'mcp'], 'inherit'))",
+ `if (existsSync(daemonSource) && existsSync(toolsDist)) { const pkg = require(daemonPackageJson); process.env.${OMO_LSP_DAEMON_CLI} = daemonSource; process.env.${OMO_LSP_DAEMON_VERSION} = pkg.version; runIfAvailable(bun, [daemonSource, 'mcp']) }`,
"const steps = [[npm, ['--prefix', toolsPackage, 'install', '--no-package-lock', '--no-audit', '--no-fund']], [npm, ['--prefix', toolsPackage, 'run', 'build']], [npm, ['--prefix', daemonPackage, 'install', '--no-package-lock', '--no-audit', '--no-fund']], [npm, ['--prefix', daemonPackage, 'run', 'build']]]",
"for (const [command, args] of steps) { const result = run(command, args, ['ignore', 'ignore', 'inherit']); if (result.error || result.status !== 0) finish(result) }",
- "finish(run(process.execPath, [daemonDist, 'mcp'], 'inherit'))"
+ "finish(run(process.execPath, [resolveDaemonCli(), 'mcp'], 'inherit'))"
].join(";");
function getModuleDirectory(moduleUrl) {
try {
@@ -100743,6 +101027,16 @@ function getModuleDirectory(moduleUrl) {
function findBootstrapRoot(candidates, pathExists) {
return candidates.find((candidate) => pathExists(resolve21(candidate.root, "package.json")))?.root ?? process.cwd();
}
+function readDaemonPackageVersion(root) {
+ try {
+ const packageJson = JSON.parse(readFileSync38(resolve21(root, PACKAGE_REL, "package.json"), "utf-8"));
+ return DaemonPackageSchema.parse(packageJson).version;
+ } catch (error51) {
+ if (!(error51 instanceof Error))
+ throw error51;
+ return null;
+ }
+}
function createBootstrapCandidate(root, pathExists, resolveExecutable) {
const runtime5 = resolveJavaScriptRuntime(resolveExecutable);
const bun = resolveExecutable("bun");
@@ -100767,7 +101061,7 @@ function resolveLspCommand(options = {}) {
sourceCliRel: SOURCE_CLI_REL,
pathExists,
resolveExecutable,
- isSourceCandidateAvailable: ({ root }) => pathExists(resolve21(root, LSP_TOOLS_PACKAGE_REL, DIST_CLI_REL))
+ isSourceCandidateAvailable: ({ root }) => pathExists(resolve21(root, LSP_TOOLS_PACKAGE_REL, DIST_CLI_REL)) && readDaemonPackageVersion(root) !== null
}) : [];
const distCandidate = candidates.find((candidate) => hasCliSuffix(candidate.path, DIST_CLI_REL) && candidate.exists);
if (distCandidate) {
@@ -100781,12 +101075,21 @@ function resolveLspCommand(options = {}) {
}
function createLspMcpConfig(options = {}) {
const resolvedCommand = resolveLspCommand(options);
+ const cwd = resolve21(options.cwd ?? process.cwd());
+ const configDir = getOpenCodeConfigDir({ binary: "opencode" });
+ const sourceVersion = hasCliSuffix(resolvedCommand.path, SOURCE_CLI_REL) ? readDaemonPackageVersion(resolvedCommand.root) : null;
return {
type: "local",
command: resolvedCommand.command,
enabled: resolvedCommand.exists,
environment: {
- LSP_TOOLS_MCP_PROJECT_CONFIG: PROJECT_LSP_CONFIGS.join(delimiter3)
+ LSP_TOOLS_MCP_PROJECT_CONFIG: PROJECT_LSP_CONFIGS.map((configPath) => resolve21(cwd, configPath)).join(delimiter3),
+ LSP_TOOLS_MCP_USER_CONFIG: resolve21(configDir, "lsp.json"),
+ LSP_TOOLS_MCP_INSTALL_DECISIONS: resolve21(configDir, "lsp-install-decisions.json"),
+ ...sourceVersion ? {
+ [OMO_LSP_DAEMON_CLI]: resolvedCommand.path,
+ [OMO_LSP_DAEMON_VERSION]: sourceVersion
+ } : {}
}
};
}
@@ -100803,7 +101106,7 @@ function readOmoConfig(configDirectory) {
return null;
}
try {
- const content = readFileSync38(detected.path, "utf-8");
+ const content = readFileSync39(detected.path, "utf-8");
return parseJsonc(content);
} catch (error51) {
if (!(error51 instanceof Error)) {
@@ -100833,7 +101136,7 @@ function getInstalledLspServers(options = {}) {
// packages/omo-opencode/src/cli/doctor/checks/tools-mcp.ts
init_shared();
-import { existsSync as existsSync57, readFileSync as readFileSync39 } from "fs";
+import { existsSync as existsSync57, readFileSync as readFileSync40 } from "fs";
import { homedir as homedir20 } from "os";
import { join as join81 } from "path";
var BUILTIN_MCP_SERVERS = ["websearch", "context7", "grep_app", "lsp"];
@@ -100850,7 +101153,7 @@ function loadUserMcpConfig() {
if (!existsSync57(configPath))
continue;
try {
- const content = readFileSync39(configPath, "utf-8");
+ const content = readFileSync40(configPath, "utf-8");
const config3 = parseJsonc(content);
if (config3.mcpServers) {
Object.assign(servers, config3.mcpServers);
@@ -100985,7 +101288,7 @@ async function checkTools() {
// packages/omo-opencode/src/cli/doctor/checks/telemetry.ts
init_src4();
-import { existsSync as existsSync58, readFileSync as readFileSync40 } from "fs";
+import { existsSync as existsSync58, readFileSync as readFileSync41 } from "fs";
function isTelemetryState(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
@@ -100995,7 +101298,7 @@ function readLastActiveDay(stateFilePath) {
}
let parsed;
try {
- parsed = JSON.parse(readFileSync40(stateFilePath, "utf-8"));
+ parsed = JSON.parse(readFileSync41(stateFilePath, "utf-8"));
} catch (error51) {
if (error51 instanceof Error) {
return "unreadable";
@@ -101070,7 +101373,7 @@ function expandHomeDirectory(directoryPath) {
// packages/omo-opencode/src/cli/doctor/checks/team-mode.ts
init_shared();
init_plugin_identity();
-import { readFileSync as readFileSync41, promises as fs13 } from "fs";
+import { readFileSync as readFileSync42, promises as fs13 } from "fs";
import path15 from "path";
async function checkTeamMode() {
const config3 = loadTeamModeConfig();
@@ -101107,7 +101410,7 @@ function loadTeamModeConfig() {
if (!configPath)
return { team_mode: undefined };
try {
- return parseJsonc(readFileSync41(configPath, "utf-8"));
+ return parseJsonc(readFileSync42(configPath, "utf-8"));
} catch (error51) {
if (error51 instanceof Error) {
return { team_mode: undefined };
@@ -101141,9 +101444,9 @@ async function pathExists(dir) {
// packages/omo-opencode/src/cli/doctor/checks/codex.ts
init_src();
import { existsSync as existsSync59 } from "fs";
-import { lstat as lstat13, readdir as readdir11, readFile as readFile23 } from "fs/promises";
+import { lstat as lstat14, readdir as readdir12, readFile as readFile24 } from "fs/promises";
import { homedir as homedir22 } from "os";
-import { basename as basename13, join as join82, resolve as resolve22 } from "path";
+import { basename as basename14, join as join82, resolve as resolve22 } from "path";
// packages/omo-opencode/package.json
var package_default3 = {
name: "@oh-my-opencode/omo-opencode",
@@ -101332,7 +101635,7 @@ async function resolveInstalledPluginRoot(codexHome) {
const pluginRoot = join82(codexHome, "plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME2);
if (!existsSync59(pluginRoot))
return null;
- const versions2 = await readdir11(pluginRoot, { withFileTypes: true });
+ const versions2 = await readdir12(pluginRoot, { withFileTypes: true });
const candidates = versions2.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(compareVersionsDescending);
return candidates.length === 0 ? null : join82(pluginRoot, candidates[0] ?? DEFAULT_PLUGIN_VERSION);
}
@@ -101348,7 +101651,7 @@ async function readCodexConfigSummary(configPath) {
companionLifecycleHookStateEvents: []
};
}
- const content = await readFile23(configPath, "utf8");
+ const content = await readFile24(configPath, "utf8");
return {
exists: true,
marketplaceConfigured: content.includes("[marketplaces.sisyphuslabs]"),
@@ -101371,12 +101674,12 @@ async function readLinkedAgents(codexHome) {
const agentsDir = join82(codexHome, "agents");
if (!existsSync59(agentsDir))
return [];
- const entries = await readdir11(agentsDir, { withFileTypes: true });
- return entries.filter((entry) => entry.isFile() || entry.isSymbolicLink()).map((entry) => basename13(entry.name, ".toml")).sort();
+ const entries = await readdir12(agentsDir, { withFileTypes: true });
+ return entries.filter((entry) => entry.isFile() || entry.isSymbolicLink()).map((entry) => basename14(entry.name, ".toml")).sort();
}
async function readJson(path16) {
try {
- const parsed = JSON.parse(await readFile23(path16, "utf8"));
+ const parsed = JSON.parse(await readFile24(path16, "utf8"));
return isPlainRecord(parsed) ? parsed : null;
} catch (error51) {
if (error51 instanceof Error)
@@ -101471,7 +101774,7 @@ function compareVersionsDescending(left, right) {
}
async function pathExists2(path16) {
try {
- await lstat13(path16);
+ await lstat14(path16);
return true;
} catch (error51) {
if (error51 instanceof Error)
@@ -101482,7 +101785,7 @@ async function pathExists2(path16) {
// packages/omo-opencode/src/cli/doctor/checks/codex-components.ts
init_src();
-import { readdir as readdir12, readFile as readFile24, stat as stat6 } from "fs/promises";
+import { readdir as readdir13, readFile as readFile25, stat as stat6 } from "fs/promises";
import { homedir as homedir23 } from "os";
import { dirname as dirname32, isAbsolute as isAbsolute13, join as join83, relative as relative10, resolve as resolve23, sep as sep9 } from "path";
var CODEX_COMPONENTS_CHECK_ID = "codex-components";
@@ -101623,7 +101926,7 @@ async function findHookManifestPaths(root) {
async function findManifestPaths(root, manifestName) {
let entries;
try {
- entries = await readdir12(root, { withFileTypes: true });
+ entries = await readdir13(root, { withFileTypes: true });
} catch {
return [];
}
@@ -101735,7 +102038,7 @@ function degradedDetailLines(entries) {
}
async function readJson2(path16) {
try {
- const parsed = JSON.parse(await readFile24(path16, "utf8"));
+ const parsed = JSON.parse(await readFile25(path16, "utf8"));
return isRecord6(parsed) ? parsed : null;
} catch (error51) {
if (error51 instanceof Error)
@@ -101763,7 +102066,7 @@ function isRecord6(value) {
// packages/omo-opencode/src/cli/doctor/checks/codex-runtime-wrapper.ts
import { existsSync as existsSync60 } from "fs";
-import { readFile as readFile25 } from "fs/promises";
+import { readFile as readFile26 } from "fs/promises";
import { homedir as homedir24 } from "os";
import { join as join84, resolve as resolve24 } from "path";
var RUNTIME_WRAPPER_MARKER2 = "OMO_GENERATED_RUNTIME_WRAPPER";
@@ -101798,7 +102101,7 @@ async function checkCodexRuntimeWrapper(deps = {}) {
}
async function readRuntimeWrapper(path16) {
try {
- return await readFile25(path16, "utf8");
+ return await readFile26(path16, "utf8");
} catch (error51) {
if (error51 instanceof Error)
return null;
@@ -102274,18 +102577,18 @@ Doctor failed unexpectedly: ${message}`];
}
// packages/mcp-client-core/src/mcp-oauth/storage.ts
-import { createHash as createHash4 } from "crypto";
+import { createHash as createHash5 } from "crypto";
import {
chmodSync as chmodSync4,
existsSync as existsSync63,
mkdirSync as mkdirSync14,
readdirSync as readdirSync9,
- readFileSync as readFileSync43,
+ readFileSync as readFileSync44,
renameSync as renameSync7,
unlinkSync as unlinkSync8,
writeFileSync as writeFileSync11
} from "fs";
-import { basename as basename14, dirname as dirname33, join as join87 } from "path";
+import { basename as basename15, dirname as dirname33, join as join87 } from "path";
// packages/mcp-client-core/src/config-dir.ts
import { existsSync as existsSync61, realpathSync as realpathSync8 } from "fs";
@@ -102313,7 +102616,7 @@ function getOpenCodeCliConfigDir(env3 = process.env) {
}
// packages/mcp-client-core/src/mcp-oauth/storage-index.ts
-import { chmodSync as chmodSync3, existsSync as existsSync62, readFileSync as readFileSync42, renameSync as renameSync6, writeFileSync as writeFileSync10 } from "fs";
+import { chmodSync as chmodSync3, existsSync as existsSync62, readFileSync as readFileSync43, renameSync as renameSync6, writeFileSync as writeFileSync10 } from "fs";
import { join as join86 } from "path";
var INDEX_FILE_NAME = "index.json";
function isTokenIndex(value) {
@@ -102329,7 +102632,7 @@ function readTokenIndex(storageDir) {
if (!existsSync62(indexPath))
return {};
try {
- const parsed = JSON.parse(readFileSync42(indexPath, "utf-8"));
+ const parsed = JSON.parse(readFileSync43(indexPath, "utf-8"));
return isTokenIndex(parsed) ? parsed : {};
} catch (readError) {
if (!(readError instanceof Error))
@@ -102369,7 +102672,7 @@ function getMcpOauthStorageDir() {
return join87(getOpenCodeCliConfigDir(), STORAGE_DIR_NAME);
}
function getMcpOauthServerHash(serverHost, resource) {
- return createHash4("sha256").update(buildKey(serverHost, resource)).digest("hex").slice(0, 32);
+ return createHash5("sha256").update(buildKey(serverHost, resource)).digest("hex").slice(0, 32);
}
function getMcpOauthStoragePath(serverHost, resource) {
return join87(getMcpOauthStorageDir(), `${getMcpOauthServerHash(serverHost, resource)}.json`);
@@ -102439,7 +102742,7 @@ function readTokenFile(filePath) {
if (!existsSync63(filePath))
return null;
try {
- const parsed = JSON.parse(readFileSync43(filePath, "utf-8"));
+ const parsed = JSON.parse(readFileSync44(filePath, "utf-8"));
return isOAuthTokenData(parsed) ? parsed : null;
} catch (readError) {
if (!(readError instanceof Error))
@@ -102452,7 +102755,7 @@ function readLegacyStore() {
if (!existsSync63(filePath))
return null;
try {
- const parsed = JSON.parse(readFileSync43(filePath, "utf-8"));
+ const parsed = JSON.parse(readFileSync44(filePath, "utf-8"));
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
return null;
const result = {};
@@ -102570,7 +102873,7 @@ function listAllTokens() {
if (!entry.isFile() || !entry.name.endsWith(".json") || entry.name === "index.json")
continue;
const token = readTokenFile(join87(dir, entry.name));
- const hash2 = basename14(entry.name, ".json");
+ const hash2 = basename15(entry.name, ".json");
if (token)
result[index[hash2] ?? hash2] = token;
}
@@ -102743,13 +103046,13 @@ async function findAvailablePort2(startPort = DEFAULT_PORT) {
// packages/mcp-client-core/src/mcp-oauth/oauth-authorization-flow.ts
import { spawn as spawn4 } from "child_process";
-import { createHash as createHash5, randomBytes as randomBytes2 } from "crypto";
+import { createHash as createHash6, randomBytes as randomBytes2 } from "crypto";
import { createServer as createServer2 } from "http";
function generateCodeVerifier() {
return randomBytes2(32).toString("base64url");
}
function generateCodeChallenge(verifier) {
- return createHash5("sha256").update(verifier).digest("base64url");
+ return createHash6("sha256").update(verifier).digest("base64url");
}
function buildAuthorizationUrl(authorizationEndpoint, options) {
const url2 = new URL(authorizationEndpoint);
@@ -103293,7 +103596,7 @@ async function boulder(options) {
}
// packages/omo-opencode/src/cli/codex-ulw-loop.ts
import { spawn as spawn5 } from "child_process";
-import { existsSync as existsSync65, readFileSync as readFileSync44, realpathSync as realpathSync9 } from "fs";
+import { existsSync as existsSync65, readFileSync as readFileSync45, realpathSync as realpathSync9 } from "fs";
import { homedir as homedir26 } from "os";
var ULW_LOOP_DELEGATION_SENTINEL = "OMO_ULW_LOOP_DELEGATED";
function resolveCodexUlwLoopCommand(input = {}) {
@@ -103343,7 +103646,7 @@ function resolveLegacyLocalOmoBin(env3, homeDir, currentExecutablePaths) {
}
function isGeneratedRuntimeWrapper(candidate) {
try {
- return readFileSync44(candidate, "utf8").includes(RUNTIME_WRAPPER_MARKER);
+ return readFileSync45(candidate, "utf8").includes(RUNTIME_WRAPPER_MARKER);
} catch (error51) {
if (error51 instanceof Error)
return false;
diff --git a/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json b/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json
index 1fd10006..8ccc9fc9 100644
--- a/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json
+++ b/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/git-bash/dist/cli.js\" hook post-compact",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Resetting Git Bash MCP Reminder",
+ "statusMessage": "(OmO 4.18.1) Resetting Git Bash MCP Reminder",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\git-bash\\dist\\cli.js\" hook post-compact"
}
],
diff --git a/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json b/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json
index 480b9ded..93c60f7b 100644
--- a/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json
+++ b/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-compact",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Resetting LSP Diagnostics Cache",
+ "statusMessage": "(OmO 4.18.1) Resetting LSP Diagnostics Cache",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lsp\\dist\\cli.js\" hook post-compact"
}
],
diff --git a/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json b/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json
index 9e2e304e..7873de9b 100644
--- a/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json
+++ b/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-compact",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Resetting Project Rule Cache",
+ "statusMessage": "(OmO 4.18.1) Resetting Project Rule Cache",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook post-compact"
}
],
diff --git a/plugins/omo/hooks/post-tool-use-checking-codegraph-init-guidance.json b/plugins/omo/hooks/post-tool-use-checking-codegraph-init-guidance.json
index 710fe8c2..7dc31e8a 100644
--- a/plugins/omo/hooks/post-tool-use-checking-codegraph-init-guidance.json
+++ b/plugins/omo/hooks/post-tool-use-checking-codegraph-init-guidance.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/codegraph/dist/cli.js\" hook post-tool-use",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Checking CodeGraph Init Guidance",
+ "statusMessage": "(OmO 4.18.1) Checking CodeGraph Init Guidance",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\codegraph\\dist\\cli.js\" hook post-tool-use"
}
],
diff --git a/plugins/omo/hooks/post-tool-use-checking-comments.json b/plugins/omo/hooks/post-tool-use-checking-comments.json
index b3e2ce72..92c06b84 100644
--- a/plugins/omo/hooks/post-tool-use-checking-comments.json
+++ b/plugins/omo/hooks/post-tool-use-checking-comments.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/comment-checker/dist/cli.js\" hook post-tool-use",
"timeout": 30,
- "statusMessage": "(OmO 4.18.0) Checking Comments",
+ "statusMessage": "(OmO 4.18.1) Checking Comments",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\comment-checker\\dist\\cli.js\" hook post-tool-use"
}
],
diff --git a/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json b/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json
index 8a35e5a0..c2336d4b 100644
--- a/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json
+++ b/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-tool-use",
"timeout": 60,
- "statusMessage": "(OmO 4.18.0) Checking LSP Diagnostics",
+ "statusMessage": "(OmO 4.18.1) Checking LSP Diagnostics",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lsp\\dist\\cli.js\" hook post-tool-use"
}
],
diff --git a/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json b/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json
index d0d00076..385331e7 100644
--- a/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json
+++ b/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/teammode/dist/cli.js\" hook post-tool-use",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Checking Thread Title Hygiene",
+ "statusMessage": "(OmO 4.18.1) Checking Thread Title Hygiene",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\teammode\\dist\\cli.js\" hook post-tool-use"
}
]
diff --git a/plugins/omo/hooks/post-tool-use-matching-project-rules.json b/plugins/omo/hooks/post-tool-use-matching-project-rules.json
index e73630a6..1d9fec2d 100644
--- a/plugins/omo/hooks/post-tool-use-matching-project-rules.json
+++ b/plugins/omo/hooks/post-tool-use-matching-project-rules.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-tool-use",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Matching Project Rules",
+ "statusMessage": "(OmO 4.18.1) Matching Project Rules",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook post-tool-use"
}
],
diff --git a/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json b/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json
index 0a11bed3..6dccce0d 100644
--- a/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json
+++ b/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook pre-tool-use",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Enforcing Unlimited Goal Budget",
+ "statusMessage": "(OmO 4.18.1) Enforcing Unlimited Goal Budget",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook pre-tool-use"
}
],
diff --git a/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json b/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json
index 353d01fb..290ff8d6 100644
--- a/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json
+++ b/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json
@@ -8,7 +8,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook pre-tool-use-spawn",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Guarding Ulw-Loop Spawns",
+ "statusMessage": "(OmO 4.18.1) Guarding Ulw-Loop Spawns",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook pre-tool-use-spawn"
}
]
diff --git a/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json b/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json
index debd1f87..f93adad1 100644
--- a/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json
+++ b/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/git-bash/dist/cli.js\" hook pre-tool-use",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Recommending Git Bash MCP",
+ "statusMessage": "(OmO 4.18.1) Recommending Git Bash MCP",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\git-bash\\dist\\cli.js\" hook pre-tool-use"
}
],
diff --git a/plugins/omo/hooks/session-start-checking-auto-update.json b/plugins/omo/hooks/session-start-checking-auto-update.json
index 59e213be..8d56d79c 100644
--- a/plugins/omo/hooks/session-start-checking-auto-update.json
+++ b/plugins/omo/hooks/session-start-checking-auto-update.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/scripts/auto-update.mjs\" hook session-start",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Checking Auto Update",
+ "statusMessage": "(OmO 4.18.1) Checking Auto Update",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\scripts\\auto-update.mjs\" hook session-start"
}
],
diff --git a/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json b/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json
index d6c40efb..9e975dd5 100644
--- a/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json
+++ b/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json
@@ -8,7 +8,7 @@
"command": "node \"${PLUGIN_ROOT}/components/bootstrap/dist/cli.js\" hook session-start",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\bootstrap.ps1\"",
"timeout": 30,
- "statusMessage": "(OmO 4.18.0) Checking Bootstrap Provisioning"
+ "statusMessage": "(OmO 4.18.1) Checking Bootstrap Provisioning"
}
]
}
diff --git a/plugins/omo/hooks/session-start-checking-codegraph-bootstrap.json b/plugins/omo/hooks/session-start-checking-codegraph-bootstrap.json
index bdd9e804..5d38aba8 100644
--- a/plugins/omo/hooks/session-start-checking-codegraph-bootstrap.json
+++ b/plugins/omo/hooks/session-start-checking-codegraph-bootstrap.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/codegraph/dist/cli.js\" hook session-start",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Checking CodeGraph Bootstrap",
+ "statusMessage": "(OmO 4.18.1) Checking CodeGraph Bootstrap",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\codegraph\\dist\\cli.js\" hook session-start"
}
]
diff --git a/plugins/omo/hooks/session-start-loading-project-rules.json b/plugins/omo/hooks/session-start-loading-project-rules.json
index 7b65e6c6..3f8d79e9 100644
--- a/plugins/omo/hooks/session-start-loading-project-rules.json
+++ b/plugins/omo/hooks/session-start-loading-project-rules.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook session-start",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Loading Project Rules",
+ "statusMessage": "(OmO 4.18.1) Loading Project Rules",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook session-start"
}
]
diff --git a/plugins/omo/hooks/session-start-recording-session-telemetry.json b/plugins/omo/hooks/session-start-recording-session-telemetry.json
index 67c47b43..26ee921b 100644
--- a/plugins/omo/hooks/session-start-recording-session-telemetry.json
+++ b/plugins/omo/hooks/session-start-recording-session-telemetry.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/telemetry/dist/cli.js\" hook session-start",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Recording Session Telemetry",
+ "statusMessage": "(OmO 4.18.1) Recording Session Telemetry",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\telemetry\\dist\\cli.js\" hook session-start"
}
]
diff --git a/plugins/omo/hooks/stop-checking-start-work-continuation.json b/plugins/omo/hooks/stop-checking-start-work-continuation.json
index 7319b58e..dc7573b0 100644
--- a/plugins/omo/hooks/stop-checking-start-work-continuation.json
+++ b/plugins/omo/hooks/stop-checking-start-work-continuation.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook stop",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Checking Start-Work Continuation",
+ "statusMessage": "(OmO 4.18.1) Checking Start-Work Continuation",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\start-work-continuation\\dist\\cli.js\" hook stop"
}
]
diff --git a/plugins/omo/hooks/stop-checking-ulw-loop-resume.json b/plugins/omo/hooks/stop-checking-ulw-loop-resume.json
index 8620f26b..9345ae6f 100644
--- a/plugins/omo/hooks/stop-checking-ulw-loop-resume.json
+++ b/plugins/omo/hooks/stop-checking-ulw-loop-resume.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook stop",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Checking Ulw-Loop Resume",
+ "statusMessage": "(OmO 4.18.1) Checking Ulw-Loop Resume",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook stop"
}
]
diff --git a/plugins/omo/hooks/subagent-stop-checking-start-work-continuation.json b/plugins/omo/hooks/subagent-stop-checking-start-work-continuation.json
index da2680f3..ddb37f79 100644
--- a/plugins/omo/hooks/subagent-stop-checking-start-work-continuation.json
+++ b/plugins/omo/hooks/subagent-stop-checking-start-work-continuation.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook subagent-stop",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Checking Start-Work Continuation",
+ "statusMessage": "(OmO 4.18.1) Checking Start-Work Continuation",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\start-work-continuation\\dist\\cli.js\" hook subagent-stop"
}
]
diff --git a/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json b/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json
index eec4e41c..3eff92d7 100644
--- a/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json
+++ b/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/lazycodex-executor-verify/dist/cli.js\" hook subagent-stop",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Verifying LazyCodex Executor Evidence",
+ "statusMessage": "(OmO 4.18.1) Verifying LazyCodex Executor Evidence",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lazycodex-executor-verify\\dist\\cli.js\" hook subagent-stop"
}
],
diff --git a/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json b/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json
index 29682b2a..d33e02ce 100644
--- a/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json
+++ b/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ultrawork/dist/cli.js\" hook user-prompt-submit",
"timeout": 5,
- "statusMessage": "(OmO 4.18.0) Checking Ultrawork Trigger",
+ "statusMessage": "(OmO 4.18.1) Checking Ultrawork Trigger",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ultrawork\\dist\\cli.js\" hook user-prompt-submit"
}
]
diff --git a/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json b/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json
index 8cc5cf0c..63a5cdb1 100644
--- a/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json
+++ b/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook user-prompt-submit",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Checking Ulw-Loop Steering",
+ "statusMessage": "(OmO 4.18.1) Checking Ulw-Loop Steering",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook user-prompt-submit"
}
]
diff --git a/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json b/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json
index 3a7f2165..40cd142d 100644
--- a/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json
+++ b/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json
@@ -7,7 +7,7 @@
"type": "command",
"command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook user-prompt-submit",
"timeout": 10,
- "statusMessage": "(OmO 4.18.0) Loading Project Rules",
+ "statusMessage": "(OmO 4.18.1) Loading Project Rules",
"commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook user-prompt-submit"
}
]
diff --git a/plugins/omo/package-lock.json b/plugins/omo/package-lock.json
index 0d361815..318cb149 100644
--- a/plugins/omo/package-lock.json
+++ b/plugins/omo/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@sisyphuslabs/omo-codex-plugin",
- "version": "4.18.0",
+ "version": "4.18.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@sisyphuslabs/omo-codex-plugin",
- "version": "4.18.0",
+ "version": "4.18.1",
"workspaces": [
"components/codegraph",
"components/comment-checker",
@@ -32,6 +32,13 @@
"@oh-my-opencode/utils": "workspace:*"
}
},
+ "../../lsp-core": {
+ "name": "@oh-my-opencode/lsp-core",
+ "version": "0.1.0",
+ "dependencies": {
+ "@oh-my-opencode/mcp-stdio-core": "workspace:*"
+ }
+ },
"../../lsp-daemon": {
"name": "@code-yeongyu/lsp-daemon",
"version": "0.1.0",
@@ -93,7 +100,7 @@
},
"components/codegraph": {
"name": "@sisyphuslabs/codex-codegraph",
- "version": "4.18.0",
+ "version": "4.18.1",
"bin": {
"omo-codegraph": "dist/cli.js"
},
@@ -112,7 +119,7 @@
},
"components/comment-checker": {
"name": "@code-yeongyu/codex-comment-checker",
- "version": "4.18.0",
+ "version": "4.18.1",
"license": "MIT",
"bin": {
"omo-comment-checker": "dist/cli.js"
@@ -133,7 +140,7 @@
},
"components/git-bash": {
"name": "@sisyphuslabs/codex-git-bash-hook",
- "version": "4.18.0",
+ "version": "4.18.1",
"bin": {
"omo-git-bash-hook": "dist/cli.js"
},
@@ -148,7 +155,7 @@
},
"components/lazycodex-executor-verify": {
"name": "@code-yeongyu/codex-lazycodex-executor-verify",
- "version": "4.18.0",
+ "version": "4.18.1",
"license": "MIT",
"bin": {
"lazycodex-executor-verify": "dist/cli.js"
@@ -165,10 +172,11 @@
},
"components/lsp": {
"name": "@code-yeongyu/codex-lsp",
- "version": "4.18.0",
+ "version": "4.18.1",
"license": "MIT",
"dependencies": {
- "@code-yeongyu/lsp-daemon": "file:../../../../lsp-daemon"
+ "@code-yeongyu/lsp-daemon": "file:../../../../lsp-daemon",
+ "@oh-my-opencode/lsp-core": "file:../../../../lsp-core"
},
"bin": {
"omo-lsp": "dist/cli.js"
@@ -185,7 +193,7 @@
},
"components/rules": {
"name": "@code-yeongyu/codex-rules",
- "version": "4.18.0",
+ "version": "4.18.1",
"license": "MIT",
"dependencies": {
"picomatch": "^4.0.3"
@@ -207,7 +215,7 @@
},
"components/start-work-continuation": {
"name": "@code-yeongyu/codex-start-work-continuation",
- "version": "4.18.0",
+ "version": "4.18.1",
"license": "MIT",
"bin": {
"omo-start-work-continuation": "dist/cli.js"
@@ -224,7 +232,7 @@
},
"components/teammode": {
"name": "@sisyphuslabs/codex-teammode",
- "version": "4.18.0",
+ "version": "4.18.1",
"devDependencies": {
"@types/node": "^25.9.3",
"bun-types": "^1.3.1",
@@ -237,7 +245,7 @@
},
"components/telemetry": {
"name": "@code-yeongyu/codex-telemetry",
- "version": "4.18.0",
+ "version": "4.18.1",
"license": "MIT",
"bin": {
"omo-telemetry": "dist/cli.js"
@@ -255,7 +263,7 @@
},
"components/ultrawork": {
"name": "@code-yeongyu/codex-ultrawork",
- "version": "4.18.0",
+ "version": "4.18.1",
"license": "MIT",
"bin": {
"omo-ultrawork": "dist/cli.js"
@@ -273,7 +281,7 @@
},
"components/ulw-loop": {
"name": "@code-yeongyu/codex-ulw-loop",
- "version": "4.18.0",
+ "version": "4.18.1",
"license": "MIT",
"bin": {
"omo-ulw-loop": "dist/cli.js",
@@ -663,6 +671,10 @@
"resolved": "../../comment-checker-core",
"link": true
},
+ "node_modules/@oh-my-opencode/lsp-core": {
+ "resolved": "../../lsp-core",
+ "link": true
+ },
"node_modules/@oh-my-opencode/prompts-core": {
"resolved": "../../prompts-core",
"link": true
diff --git a/plugins/omo/package.json b/plugins/omo/package.json
index a3aef734..2d4fde29 100644
--- a/plugins/omo/package.json
+++ b/plugins/omo/package.json
@@ -1,6 +1,6 @@
{
"name": "@sisyphuslabs/omo-codex-plugin",
- "version": "4.18.0",
+ "version": "4.18.1",
"description": "Aggregate Codex plugin root for OMO components.",
"type": "module",
"packageManager": "[email protected]",
diff --git a/plugins/omo/scripts/build-bundled-mcp-runtimes.mjs b/plugins/omo/scripts/build-bundled-mcp-runtimes.mjs
index fd6bdea0..f9c5140f 100644
--- a/plugins/omo/scripts/build-bundled-mcp-runtimes.mjs
+++ b/plugins/omo/scripts/build-bundled-mcp-runtimes.mjs
@@ -16,8 +16,7 @@ const runtimes = [
{
label: "lsp-daemon",
packageRoot: join(repoPackagesRoot, "lsp-daemon"),
- requiredOutputs: ["dist/cli.js", "dist/index.js", "dist/index.d.ts"],
- install: true,
+ requiredOutputs: ["dist/cli.js", "dist/client.js", "dist/client.d.ts", "dist/index.js", "dist/index.d.ts"],
},
{
label: "git-bash-mcp",
@@ -42,7 +41,7 @@ function buildRuntime(runtime) {
return;
}
- if (runtime.install === true && !existsSync(join(runtime.packageRoot, "node_modules"))) {
+ if (existsSync(join(runtime.packageRoot, "package-lock.json")) && !existsSync(join(runtime.packageRoot, "node_modules"))) {
const install = spawnSync("npm", ["ci"], {
cwd: runtime.packageRoot,
shell: process.platform === "win32",
diff --git a/plugins/omo/scripts/build-components.mjs b/plugins/omo/scripts/build-components.mjs
index 0f260c5a..448f2238 100644
--- a/plugins/omo/scripts/build-components.mjs
+++ b/plugins/omo/scripts/build-components.mjs
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import { spawn } from "node:child_process";
import { availableParallelism } from "node:os";
-import { readdir, readFile, writeFile } from "node:fs/promises";
+import { readdir, readFile, stat, writeFile } from "node:fs/promises";
import { builtinModules } from "node:module";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -55,6 +55,7 @@ async function runTasksWithConcurrency(items, limit) {
async function buildComponent(task) {
await runCaptured(task.buildCommand, task.buildArgs, task.buildCwd, `Building ${task.componentPath}`);
+ if (await hasComponentOwnedBundle(task.componentPath)) return;
await bundleCli(task.componentPath);
}
@@ -84,6 +85,17 @@ async function bundleCli(workspace) {
await normalizeBuiltinImports(output);
}
+async function hasComponentOwnedBundle(workspace) {
+ try {
+ const manifest = JSON.parse(await readFile(join(root, workspace, "dist", ".omo-runtime-manifest.json"), "utf8"));
+ const cli = await stat(join(root, workspace, "dist", "cli.js"));
+ return manifest?.schemaVersion === 1 && cli.isFile() && cli.size > 0;
+ } catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;
+ throw error;
+ }
+}
+
// Buffers each child's stdout/stderr and flushes it as one contiguous block so
// concurrent builds never interleave, keeping a failing component's output readable.
function runCaptured(command, args, cwd, label) {
diff --git a/plugins/omo/scripts/sync-skills.mjs b/plugins/omo/scripts/sync-skills.mjs
index 5f12d3b6..aea24486 100644
--- a/plugins/omo/scripts/sync-skills.mjs
+++ b/plugins/omo/scripts/sync-skills.mjs
@@ -132,7 +132,7 @@ const startWorkOriginalCompletion = `When all top-level checkboxes in \`## TODOs
const startWorkCodexCompletion = `When all top-level checkboxes in \`## TODOs\` and \`## Final Verification Wave\` are complete:
1. Run the plan's final verification commands.
-2. Complete the **Global Review and Debugging Gate** before any completion claim, PR creation, PR handoff, branch handoff, or merge:
+2. Complete the **Global Review and Debugging Gate** before any completion claim, PR creation, PR handoff, branch handoff, or merge. The gate's pass binds to the commit SHA it reviewed and covers every later checkpoint at that same SHA — never re-run it on an already-passed SHA; re-run only when new commits land:
- Invoke the \`review-work\` skill with the final diff, changed files, user goal, constraints, run command, and verification evidence. All five review lanes must return PASS. A timeout, missing deliverable, ack-only child, \`BLOCKED:\`, or inconclusive lane is a gate failure, not approval.
- Run a debugging-oriented runtime audit even when the review passes: name at least three plausible failure hypotheses for the changed surface, run the distinguishing checks against the actual artifact, and append the ruled-out or confirmed result to \`.omo/start-work/ledger.jsonl\`.
- If any review lane or debugging hypothesis fails, invoke the \`debugging\` skill, confirm root cause with runtime evidence, add the minimal failing test or reproduction, fix it, rerun the affected verification, then rerun the Global Review and Debugging Gate.
diff --git a/plugins/omo/skills/start-work/SKILL.md b/plugins/omo/skills/start-work/SKILL.md
index 013d5a39..85f5d941 100644
--- a/plugins/omo/skills/start-work/SKILL.md
+++ b/plugins/omo/skills/start-work/SKILL.md
@@ -176,7 +176,7 @@ Only after verification passes:
When all top-level checkboxes in `## TODOs` and `## Final Verification Wave` are complete:
1. Run the plan's final verification commands.
-2. Complete the **Global Review and Debugging Gate** before any completion claim, PR creation, PR handoff, branch handoff, or merge:
+2. Complete the **Global Review and Debugging Gate** before any completion claim, PR creation, PR handoff, branch handoff, or merge. The gate's pass binds to the commit SHA it reviewed and covers every later checkpoint at that same SHA — never re-run it on an already-passed SHA; re-run only when new commits land:
- Invoke the `review-work` skill with the final diff, changed files, user goal, constraints, run command, and verification evidence. All five review lanes must return PASS. A timeout, missing deliverable, ack-only child, `BLOCKED:`, or inconclusive lane is a gate failure, not approval.
- Run a debugging-oriented runtime audit even when the review passes: name at least three plausible failure hypotheses for the changed surface, run the distinguishing checks against the actual artifact, and append the ruled-out or confirmed result to `.omo/start-work/ledger.jsonl`.
- If any review lane or debugging hypothesis fails, invoke the `debugging` skill, confirm root cause with runtime evidence, add the minimal failing test or reproduction, fix it, rerun the affected verification, then rerun the Global Review and Debugging Gate.
diff --git a/plugins/omo/skills/ulw-loop/SKILL.md b/plugins/omo/skills/ulw-loop/SKILL.md
index 29b36dfa..d78cfcd8 100644
--- a/plugins/omo/skills/ulw-loop/SKILL.md
+++ b/plugins/omo/skills/ulw-loop/SKILL.md
@@ -23,7 +23,7 @@ This skill is intentionally compact. The full workflow lives in `references/full
- After any compaction or context loss, re-read brief + goals + ledger FIRST plus `omo ulw-loop status --json`, then resume; never re-plan from scratch.
- If `omo ulw-loop create-goals` says the existing aggregate is already complete, start unrelated new work with a fresh `--session-id <new-id>` instead of steering or forcing the completed default state. Use `--force` only to intentionally overwrite completed evidence.
- Every success criterion needs observable evidence from a real surface: a channel (terminal/TUI via the xterm.js web terminal, HTTP, browser, computer-use) or, for CLI- or data-shaped criteria, an auxiliary surface (CLI stdout, DB diff, parsed config dump).
-- Evidence is bound to its capture commit; a later fix, rebase, or merge makes it stale — re-run at the current HEAD and re-record, never relabel or regenerate. Record only after cleanup receipts exist.
+- Evidence is bound to the tree it was captured at (`git rev-parse --short "HEAD^{tree}"`); it goes stale only when tracked content changes — a rebase or amend that keeps the tree identical keeps it valid. When the tree differs, re-run at the current HEAD and re-record, never relabel or regenerate. Record only after cleanup receipts exist.
- Delegate code edits, test writes, fixes, and QA execution to right-sized Codex subagents when the workflow requires it.
- Every `spawn_agent` message starts with `TASK:`, then names `DELIVERABLE`, `SCOPE`, and `VERIFY`; put role and specialty instructions inside `message`; use `fork_turns: "none"` (v1: `fork_context: false`) unless full history is truly required.
- Plan and reviewer agents may run for a long time; spawn them in the background and keep doing independent root work. Between `wait_agent` calls, back off — double the timeout up to ~5 minutes — instead of spinning short cycles.
diff --git a/plugins/omo/skills/ulw-loop/references/full-workflow.md b/plugins/omo/skills/ulw-loop/references/full-workflow.md
index 9d4972fa..1ba6a194 100644
--- a/plugins/omo/skills/ulw-loop/references/full-workflow.md
+++ b/plugins/omo/skills/ulw-loop/references/full-workflow.md
@@ -165,9 +165,9 @@ Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures a
5. EXECUTE-AS-SCENARIO: ACTUALLY run the Manual-QA scenario the criterion named (channel table above). Run it yourself for the orchestrator check; for heavier flows dispatch a dedicated QA execution worker (`lazycodex-worker-medium` by default; `lazycodex-worker-high` when the QA flow itself is hard) whose ONLY job is to drive the channel and write the artifact to the named evidence path. If the scenario FAILS, respawn the implementing worker with the captured failure — do not hand-patch around it.
6. CAPTURE: collect the observable artifact path: transcript, stdout, screenshot, assertion, status+body, diff, or parsed dump. No artifact written at the evidence path — not done; record BLOCKED and respawn QA.
7. CLEAN (PAIRED, NEVER SKIP): tear down every runtime artifact step 5 spawned BEFORE recording — server PIDs (`kill`, verify `kill -0` fails), `tmux` sessions (`tmux kill-session -t ulw-qa-<criterion>`; confirm `tmux ls`), browser / Playwright contexts (`.close()`), containers (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env vars, AND close every finished worker (v1 `close_agent`; on V2 finished workers end on their own — `interrupt_agent` any still running). Register each teardown as its own todo the moment the QA spawns the resource (scripts, tmux assets, browsers / agent-browser sessions, PIDs, ports) so none is forgotten. Embed a one-line cleanup receipt in the evidence string, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo; rm -rf /tmp/ulw.aB12cD; interrupt_agent w-3`. Missing receipt → record BLOCKED, not PASS.
-8. RECORD one result immediately from the artifact you just wrote — never from memory or a later turn — stamping the capture commit `$(git rev-parse --short HEAD)` into the evidence:
- - PASS: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status pass --evidence "<observable> @<short-sha> | <cleanup receipt>" --json`
- - FAIL: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status fail --evidence "<observable> @<short-sha> | <cleanup receipt>" --notes "<diagnosis>" --json`
+8. RECORD one result immediately from the artifact you just wrote — never from memory or a later turn — stamping the capture tree `$(git rev-parse --short "HEAD^{tree}")` into the evidence:
+ - PASS: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status pass --evidence "<observable> @tree:<short-tree> | <cleanup receipt>" --json`
+ - FAIL: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status fail --evidence "<observable> @tree:<short-tree> | <cleanup receipt>" --notes "<diagnosis>" --json`
- BLOCKED: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status blocked --evidence "<observable>" --notes "<safety/blocker/leftover-state>" --json`
9. If actual does not match expected, diagnose, respawn the right-sized worker with the failure context to fix minimally, and rerun the SAME criterion (including a fresh cleanup).
10. After 3 same-criterion failures, exit the goal with diagnosis.
@@ -184,9 +184,10 @@ Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures a
## Final Quality Gate
Trigger only for the final aggregate goal after every criterion in every goal is `pass`.
1. Run targeted verification for changed behavior.
-2. FREEZE first — no more edits or rebases. At the frozen `git rev-parse HEAD`, re-run Manual-QA for any PASS criterion whose stamped commit is not HEAD, so every criterion is proven at HEAD; each artifact exists and is non-empty.
+2. FREEZE first — no more edits or rebases. At the frozen HEAD, re-run Manual-QA for any PASS criterion whose stamped tree differs from `git rev-parse --short "HEAD^{tree}"`, so every criterion is proven on the frozen tree; each artifact exists and is non-empty.
3a. Spawn lazycodex-code-reviewer and lazycodex-qa-executor in parallel (`fork_context: false` on v1; `fork_turns: "none"` on v2) with brief, goals, desired outcome, diff, evidence; wait for BOTH and confirm their report artifacts exist on disk.
3b. Only then spawn lazycodex-gate-reviewer with those artifact paths.
+3c. The gate's approval binds to the frozen tree and covers its three lanes — code quality, hands-on QA, and goal verification. A later rebase or amend that keeps the tree identical keeps the approval; changed content needs fresh review of the delta.
4. Treat timeout, missing deliverable, ack-only, `BLOCKED:`, or inconclusive review as a blocker. Any fix restarts the freeze at the new HEAD: re-run ONLY the proofs it invalidated and stamp the fresh output — never regenerate all evidence or relabel stale output to HEAD — re-review the delta at most TWICE; then record-review-blockers (step 5) and surface to the user.
5. If review remains blocked, run `omo ulw-loop record-review-blockers --goal-id <id> --title "<...>" --objective "<...>" --evidence "<review findings>" --codex-goal-json <snapshot> --json`.
6. If clean, checkpoint final completion:
@@ -224,7 +225,7 @@ Structured prompt directives accepted: `OMO_ULW_LOOP_STEER: { ... }`, `omo.ulw-l
## Constraints
1. NEVER call `update_goal` mid-aggregate; only on final story after the quality gate passes.
2. NEVER call `create_goal` when `get_goal` shows a different active goal.
-3. Evidence is bound to the commit it was captured at; a later fix, rebase, or merge invalidates it — re-run the QA at the current HEAD and re-record. NEVER mark PASS from memory, and NEVER relabel, pin, refresh, or regenerate prior output to a moved HEAD.
+3. Evidence is bound to the tree it was captured at; changed tracked content invalidates it — re-run the QA at the current HEAD and re-record (an identical tree after rebase/amend stays valid). NEVER mark PASS from memory, and NEVER relabel, pin, refresh, or regenerate prior output to a moved HEAD.
4. NEVER bypass the criteria gate: non-final aggregate completion requires all essential criteria; final aggregate completion requires all criteria across the whole plan.
5. Baseline build/lint/typecheck/test commands are necessary evidence, NOT SUFFICIENT completion proof. Criteria coverage with observable evidence is the gate.
6. Treat `.omo/ulw-loop/ledger.jsonl` as the durable audit trail; checkpoint after every success or failure.
diff --git a/plugins/omo/test/aggregate-build.test.mjs b/plugins/omo/test/aggregate-build.test.mjs
index 3c1c0e33..f7ba7685 100644
--- a/plugins/omo/test/aggregate-build.test.mjs
+++ b/plugins/omo/test/aggregate-build.test.mjs
@@ -36,3 +36,11 @@ test("#given omo-codex package build script #when inspected #then delegates to t
// then
assert.equal(buildPluginScript, "bun run --cwd plugin build");
});
+
+test("#given a component-owned runtime manifest #when aggregate component build script is inspected #then it preserves bundled bytes", async () => {
+ const buildScript = await readFile(join(root, "scripts", "build-components.mjs"), "utf8");
+
+ assert.match(buildScript, /hasComponentOwnedBundle/u);
+ assert.match(buildScript, /"dist", "\.omo-runtime-manifest\.json"/u);
+ assert.match(buildScript, /if \(await hasComponentOwnedBundle\(task\.componentPath\)\) return/u);
+});
diff --git a/plugins/omo/test/component-bundled-cli.test.mjs b/plugins/omo/test/component-bundled-cli.test.mjs
index b2955053..dbadcd08 100644
--- a/plugins/omo/test/component-bundled-cli.test.mjs
+++ b/plugins/omo/test/component-bundled-cli.test.mjs
@@ -1,5 +1,15 @@
import assert from "node:assert/strict";
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import {
+ chmodSync,
+ cpSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
import { readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -23,6 +33,7 @@ const HOOK_EVENTS_BY_COMPONENT = {
};
const MCP_ONLY_COMPONENTS = new Set(["codegraph"]);
const HOOK_CLI_TEST_TIMEOUT_MS = 45_000;
+const DAEMON_EXIT_TIMEOUT_MS = 5_000;
test("#given required component CLI contracts #when workspaces are inspected #then every contract component is covered", async () => {
// given
@@ -125,29 +136,84 @@ test("#given representative component hook payloads #when executed through dist
}
});
-test("#given bundled LSP hook CLI in installed layout #when diagnostics run #then it spawns sibling daemon target", () => {
+test("#given bundled LSP hook CLI in installed layout #when diagnostics run #then it spawns sibling daemon target", async () => {
const tempRoot = mkdtempSync(join(tmpdir(), "omo-codex-lsp-installed-"));
try {
const lspDist = join(tempRoot, "components", "lsp", "dist");
const daemonDist = join(tempRoot, "components", "lsp-daemon", "dist");
const daemonDir = join(tempRoot, "daemon");
- const invocationLog = join(tempRoot, "fake-daemon-invocations.jsonl");
mkdirSync(lspDist, { recursive: true });
mkdirSync(daemonDist, { recursive: true });
mkdirSync(join(tempRoot, "src"), { recursive: true });
writeFileSync(join(tempRoot, "package.json"), JSON.stringify({ type: "module" }));
writeFileSync(join(lspDist, "cli.js"), readFileSync(componentCliPath("lsp"), "utf8"));
- writeFileSync(join(daemonDist, "package.json"), JSON.stringify({ type: "module", version: "0.1.0" }));
- writeFakeLspDaemonCli(join(daemonDist, "cli.js"));
- const editedFile = join(tempRoot, "src", "broken.c");
- writeFileSync(editedFile, "int main(void) { return missing_symbol; }\n");
+ cpSync(join(root, "..", "..", "lsp-daemon", "dist"), daemonDist, { recursive: true });
+ const editedFile = join(tempRoot, "src", "broken.ts");
+ const scenarioPath = join(tempRoot, "scenario.json");
+ const eventsPath = join(tempRoot, "lsp-events.jsonl");
+ const codexHome = join(tempRoot, "codex-home");
+ mkdirSync(codexHome, { recursive: true });
+ writeFileSync(editedFile, "const value: string = 1;\n");
+ writeFileSync(eventsPath, "");
+ writeFileSync(
+ scenarioPath,
+ JSON.stringify({
+ publishDiagnostics: [
+ {
+ trigger: "didOpen",
+ version: 1,
+ diagnostics: [
+ {
+ range: { start: { line: 0, character: 6 }, end: { line: 0, character: 11 } },
+ severity: 1,
+ code: "fake",
+ source: "fake",
+ message: "Missing fake symbol.",
+ },
+ ],
+ },
+ ],
+ diagnosticResponses: [
+ {
+ report: {
+ items: [
+ {
+ range: { start: { line: 0, character: 6 }, end: { line: 0, character: 11 } },
+ severity: 1,
+ code: "fake",
+ source: "fake",
+ message: "Missing fake symbol.",
+ },
+ ],
+ },
+ },
+ ],
+ }),
+ );
+ writeFileSync(
+ join(codexHome, "lsp-client.json"),
+ JSON.stringify({
+ lsp: {
+ typescript: {
+ command: [
+ process.execPath,
+ join(root, "..", "..", "lsp-core", "src", "lsp", "fixtures", "workspace-edit-server.mjs"),
+ scenarioPath,
+ eventsPath,
+ ],
+ extensions: [".ts"],
+ },
+ },
+ }),
+ );
const result = spawnSync(process.execPath, [join(lspDist, "cli.js"), "hook", "post-tool-use"], {
cwd: tempRoot,
encoding: "utf8",
env: hookEnv(tempRoot, {
- CODEX_LSP_DAEMON_DIR: daemonDir,
- FAKE_LSP_DAEMON_LOG: invocationLog,
+ CODEX_HOME: codexHome,
+ OMO_LSP_DAEMON_DIR: daemonDir,
+ NODE_PATH: "",
}),
input: JSON.stringify({
session_id: "bundled-lsp-hook",
@@ -158,17 +224,17 @@ test("#given bundled LSP hook CLI in installed layout #when diagnostics run #the
timeout: HOOK_CLI_TEST_TIMEOUT_MS,
});
- const daemonInvocations = existsSync(invocationLog) ? readFileSync(invocationLog, "utf8") : "";
- const failureContext = `stdout: ${result.stdout}\nstderr: ${result.stderr}\ndaemon log: ${daemonInvocations}`;
+ const failureContext = `stdout: ${result.stdout}\nstderr: ${result.stderr}`;
assert.equal(result.status, 0, failureContext);
assert.equal(result.stderr, "", failureContext);
assert.notEqual(result.stdout, "", failureContext);
const parsed = JSON.parse(result.stdout);
assert.equal(parsed.decision, "block");
- assert.match(parsed.reason, /error\[fake\] \(1\) at 1:1: Missing fake symbol\./);
- assert.deepEqual(daemonInvocations.trim().split("\n").map(JSON.parse), [["daemon"]]);
- assert.equal(existsSync(join(daemonDir, "v0.1.0", "daemon.log")), true);
+ assert.match(parsed.reason, /Missing fake symbol\./);
+ assert.match(readFileSync(eventsPath, "utf8"), /textDocument\/publishDiagnostics/);
+ assert.equal(existsSync(join(daemonDir, `v${JSON.parse(readFileSync(join(daemonDist, "package.json"), "utf8")).version}`, "daemon.log")), true);
} finally {
+ await stopTestDaemons(join(tempRoot, "daemon"));
rmSync(tempRoot, { recursive: true, force: true });
}
});
@@ -336,7 +402,7 @@ function writeFakeLspDaemonCli(path) {
'import { createServer } from "node:net";',
"",
"appendFileSync(process.env.FAKE_LSP_DAEMON_LOG, `${JSON.stringify(process.argv.slice(2))}\\n`);",
- "const baseDir = process.env.CODEX_LSP_DAEMON_DIR;",
+ "const baseDir = process.env.OMO_LSP_DAEMON_DIR;",
'const versionDirName = readdirSync(baseDir).find((entry) => entry.startsWith("v")) ?? "v0";',
"const version = versionDirName.slice(1);",
"const dir = join(baseDir, versionDirName);",
@@ -374,6 +440,53 @@ function writeFakeLspDaemonCli(path) {
);
}
+async function stopTestDaemons(daemonRoot) {
+ if (!existsSync(daemonRoot)) return;
+ for (const versionDir of readdirSync(daemonRoot)) {
+ const pidPath = join(daemonRoot, versionDir, "daemon.pid");
+ if (!existsSync(pidPath)) continue;
+ const pid = Number(readFileSync(pidPath, "utf8").trim());
+ if (!Number.isInteger(pid) || pid <= 0) continue;
+ if (process.platform === "win32") {
+ const result = spawnSync("taskkill", ["/pid", String(pid), "/f", "/t"], {
+ encoding: "utf8",
+ windowsHide: true,
+ });
+ if (result.error) throw result.error;
+ if (result.status !== 0 && processIsRunning(pid)) {
+ throw new Error(
+ `taskkill failed for test daemon ${pid}: exit=${result.status} stderr=${result.stderr.trim()}`,
+ );
+ }
+ } else {
+ try {
+ process.kill(pid, "SIGTERM");
+ } catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "ESRCH") continue;
+ throw error;
+ }
+ }
+ await waitForProcessExit(pid);
+ }
+}
+
+async function waitForProcessExit(pid) {
+ const deadline = Date.now() + DAEMON_EXIT_TIMEOUT_MS;
+ while (processIsRunning(pid)) {
+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for test daemon ${pid} to exit`);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+}
+
+function processIsRunning(pid) {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
function hookEnv(tempRoot, extraEnv = {}) {
return {
...process.env,
diff --git a/plugins/omo/test/install-time-build-runtime.test.mjs b/plugins/omo/test/install-time-build-runtime.test.mjs
index 526bdf67..ce340929 100644
--- a/plugins/omo/test/install-time-build-runtime.test.mjs
+++ b/plugins/omo/test/install-time-build-runtime.test.mjs
@@ -31,3 +31,13 @@ test("#given aggregate build scripts #when inspected #then npm subprocesses reso
assert.match(installTimeBuildScripts, /shell: process\.platform === "win32"/);
assert.doesNotMatch(installTimeBuildScripts, /npm\.cmd/);
});
+
+test("#given bundled MCP runtime builds #when a locked runtime has no node_modules #then npm ci bootstraps it before build", async () => {
+ // given
+ const buildBundledMcpRuntimesScript = await readFile(join(root, "scripts", "build-bundled-mcp-runtimes.mjs"), "utf8");
+
+ // then
+ assert.match(buildBundledMcpRuntimesScript, /package-lock\.json/);
+ assert.match(buildBundledMcpRuntimesScript, /spawnSync\("npm", \["ci"\]/);
+ assert.match(buildBundledMcpRuntimesScript, /!existsSync\(join\(runtime\.packageRoot, "node_modules"\)\)/);
+});
diff --git a/plugins/omo/test/lsp-prebuild-layouts.test.mjs b/plugins/omo/test/lsp-prebuild-layouts.test.mjs
index 37c6cc5d..996f7c48 100644
--- a/plugins/omo/test/lsp-prebuild-layouts.test.mjs
+++ b/plugins/omo/test/lsp-prebuild-layouts.test.mjs
@@ -64,6 +64,8 @@ test("#given the installed cache layout #when running build-lsp-daemon #then use
await mkdir(join(root, "components", "lsp-daemon", "dist"), { recursive: true });
await writeFile(join(root, "components", "lsp-daemon", "dist", "cli.js"), "");
+ await writeFile(join(root, "components", "lsp-daemon", "dist", "client.js"), "");
+ await writeFile(join(root, "components", "lsp-daemon", "dist", "client.d.ts"), "");
await writeFile(join(root, "components", "lsp-daemon", "dist", "index.js"), "");
await writeFile(join(root, "components", "lsp-daemon", "dist", "index.d.ts"), "");
diff --git a/plugins/omo/test/sync-skills-test-support.mjs b/plugins/omo/test/sync-skills-test-support.mjs
index 06502577..b22def5a 100644
--- a/plugins/omo/test/sync-skills-test-support.mjs
+++ b/plugins/omo/test/sync-skills-test-support.mjs
@@ -77,7 +77,7 @@ const startWorkOriginalCompletion = `When all top-level checkboxes in \`## TODOs
const startWorkCodexCompletion = `When all top-level checkboxes in \`## TODOs\` and \`## Final Verification Wave\` are complete:
1. Run the plan's final verification commands.
-2. Complete the **Global Review and Debugging Gate** before any completion claim, PR creation, PR handoff, branch handoff, or merge:
+2. Complete the **Global Review and Debugging Gate** before any completion claim, PR creation, PR handoff, branch handoff, or merge. The gate's pass binds to the commit SHA it reviewed and covers every later checkpoint at that same SHA — never re-run it on an already-passed SHA; re-run only when new commits land:
- Invoke the \`review-work\` skill with the final diff, changed files, user goal, constraints, run command, and verification evidence. All five review lanes must return PASS. A timeout, missing deliverable, ack-only child, \`BLOCKED:\`, or inconclusive lane is a gate failure, not approval.
- Run a debugging-oriented runtime audit even when the review passes: name at least three plausible failure hypotheses for the changed surface, run the distinguishing checks against the actual artifact, and append the ruled-out or confirmed result to \`.omo/start-work/ledger.jsonl\`.
- If any review lane or debugging hypothesis fails, invoke the \`debugging\` skill, confirm root cause with runtime evidence, add the minimal failing test or reproduction, fix it, rerun the affected verification, then rerun the Global Review and Debugging Gate.