feat(lsp): LSP capability seam, generic stdio provider, and lsp tool
Implements the LSP capability seam RFC as three packages: dsh-lsp (the ctx.lsp interface — provider registry by branded id + exclusive extension mapping, per-query order-independent selection, closed request/result vocabulary, LspError taxonomy), dsh-lsp-local (a generic stdio language-server provider — Content-Length JSON-RPC framing, per-(provider, workspace) process single-flight, transient didOpen/query/didClose, an abortable per-instance queue, UTF-16 negotiation, host-namespace source reads outside ctx.fs, and bounded shutdown/kill teardown), and dsh-tool-lsp (the model-facing lsp tool — four operations, one-based UTF-16 cursor conversion, workspace-grouped location rendering, hover capping, a required session workspace, and a timeout budget). Why: an agent had text search and file reads but no way to identify a program symbol — follow an alias, connect an interface to implementations, or read an inferred type — before changing code. Splitting model contract, seam, and local subprocess behavior keeps the four semantic queries stable across future remote or sandbox-native providers without leaking a JSON-RPC escape hatch.
This commit is contained in:
240
packages/lsp/lsp-local/src/connection.ts
Normal file
240
packages/lsp/lsp-local/src/connection.ts
Normal file
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* A JSON-RPC endpoint over one spawned language server's stdio. Owns id correlation, outbound
|
||||
* requests/notifications, and inbound server→client requests: it answers `workspace/configuration`
|
||||
* from static config, and rejects `workspace/applyEdit` (this host never applies edits or runs
|
||||
* commands). It caps stderr, surfaces framing/decoder failures as a fatal close, and exposes the
|
||||
* child handle so the instance owns process-signal teardown.
|
||||
* @module @deepseek-ai/dsh-lsp-local/connection
|
||||
*/
|
||||
|
||||
import type { ChildProcessByStdio } from 'node:child_process'
|
||||
import { spawn } from 'node:child_process'
|
||||
import type { Readable, Writable } from 'node:stream'
|
||||
import { encodeMessage, MessageDecoder } from './framing.ts'
|
||||
|
||||
/** How to launch the server and answer its config requests. */
|
||||
export interface ConnectionSpec {
|
||||
/** The resolved absolute executable path (no shell). */
|
||||
readonly command: string
|
||||
/** Arguments passed to the executable. */
|
||||
readonly args: readonly string[]
|
||||
/** The child's working directory (the canonical workspace). */
|
||||
readonly cwd: string
|
||||
/** The child's environment (credential-scrubbed, with overrides applied). */
|
||||
readonly env: Record<string, string>
|
||||
/** Largest single framed message accepted from the server. */
|
||||
readonly maxMessageBytes: number
|
||||
/** Largest stderr tail retained for diagnostics. */
|
||||
readonly maxStderrBytes: number
|
||||
/** Static answer to every `workspace/configuration` item. */
|
||||
readonly configuration: unknown
|
||||
}
|
||||
|
||||
interface Pending {
|
||||
resolve: (value: unknown) => void
|
||||
reject: (error: Error) => void
|
||||
}
|
||||
|
||||
/** A live JSON-RPC endpoint bound to one child process. */
|
||||
export class LspConnection {
|
||||
private readonly child: ChildProcessByStdio<Writable, Readable, Readable>
|
||||
private readonly decoder: MessageDecoder
|
||||
private readonly pending = new Map<number, Pending>()
|
||||
private nextId = 1
|
||||
private stderr = ''
|
||||
private closeReason: Error | undefined
|
||||
/** Set once the process has fully exited; the instance awaits it during teardown. */
|
||||
readonly closed: Promise<void>
|
||||
|
||||
/**
|
||||
* @param spec - how to launch the server and answer its config requests.
|
||||
* @param onServerRequest - answers a server→client request; rejects to send an error response.
|
||||
*/
|
||||
constructor(
|
||||
private readonly spec: ConnectionSpec,
|
||||
private readonly onServerRequest: (method: string, params: unknown) => Promise<unknown>,
|
||||
) {
|
||||
this.decoder = new MessageDecoder(spec.maxMessageBytes)
|
||||
this.child = spawn(spec.command, [...spec.args], {
|
||||
cwd: spec.cwd,
|
||||
env: spec.env,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
})
|
||||
this.closed = new Promise<void>((resolve) => {
|
||||
this.child.on('close', () => {
|
||||
const reason = this.closeReason ?? new Error('language server exited')
|
||||
// Record the reason so any request issued AFTER close rejects immediately instead of hanging
|
||||
// (a closed process sends no further responses).
|
||||
this.closeReason = reason
|
||||
this.failAll(reason)
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
this.child.on('error', (error) => { this.fail(error) })
|
||||
// A write to the child's stdin after it exits emits an async 'error'; swallow it so an EPIPE
|
||||
// during teardown does not crash the process. Pending requests fail via the 'close' handler.
|
||||
/* v8 ignore next -- the handler only fires on an async stdin write error during teardown. */
|
||||
this.child.stdin.on('error', () => { /* swallow */ })
|
||||
this.child.stdout.on('data', (chunk: Buffer) => { this.onStdout(chunk) })
|
||||
this.child.stderr.on('data', (chunk: Buffer) => { this.onStderr(chunk) })
|
||||
}
|
||||
|
||||
/** The child's pid, or `-1` when the spawn produced no pid (so signalling is a no-op). */
|
||||
get pid(): number {
|
||||
/* v8 ignore next -- the `-1` fallback only applies to a spawn that produced no pid; defensive. */
|
||||
return this.child.pid ?? -1
|
||||
}
|
||||
|
||||
/** The retained stderr tail, for diagnostics on a failed server. */
|
||||
get stderrTail(): string {
|
||||
return this.stderr
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a request and await its result.
|
||||
* @param method - the JSON-RPC method.
|
||||
* @param params - the request params.
|
||||
* @returns the response result; rejects on an error response, write failure, or close.
|
||||
*/
|
||||
request(method: string, params: unknown): Promise<unknown> {
|
||||
const id = this.nextId++
|
||||
const promise = new Promise<unknown>((resolve, reject) => {
|
||||
if (this.closeReason !== undefined) {
|
||||
reject(this.closeReason)
|
||||
return
|
||||
}
|
||||
this.pending.set(id, { resolve, reject })
|
||||
try {
|
||||
this.write({ jsonrpc: '2.0', id, method, params })
|
||||
} catch (error) {
|
||||
/* v8 ignore start -- a stdin write failure surfaces asynchronously via the swallowed
|
||||
'error' listener, so this synchronous catch is a defensive guard. */
|
||||
this.pending.delete(id)
|
||||
reject(asError(error))
|
||||
/* v8 ignore stop */
|
||||
}
|
||||
})
|
||||
// A caller that stops awaiting (e.g. an aborted query) can leave this promise to reject later
|
||||
// when the process closes; a benign no-op handler keeps that from surfacing as an unhandled
|
||||
// rejection. The returned promise still delivers the rejection to the caller's own await/catch.
|
||||
promise.catch(() => {})
|
||||
return promise
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a notification (no id, no response).
|
||||
* @param method - the JSON-RPC method.
|
||||
* @param params - the notification params.
|
||||
*/
|
||||
notify(method: string, params: unknown): void {
|
||||
this.write({ jsonrpc: '2.0', method, params })
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a `$/cancelRequest` for an in-flight request id (best-effort; ignores write failure).
|
||||
* @param requestId - the numeric id of the request to cancel.
|
||||
*/
|
||||
cancel(requestId: number): void {
|
||||
try {
|
||||
this.write({ jsonrpc: '2.0', method: '$/cancelRequest', params: { id: requestId } })
|
||||
} catch {
|
||||
// The server is already gone or unwritable; the pending request will fail on close.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The id the NEXT `request()` will use, so the instance can pre-arm a cancel.
|
||||
* @returns the numeric id the next request will be assigned.
|
||||
*/
|
||||
peekNextId(): number {
|
||||
return this.nextId
|
||||
}
|
||||
|
||||
/** Send SIGTERM to the child (idempotent-safe; a dead child ignores it). */
|
||||
terminate(): void {
|
||||
this.child.kill('SIGTERM')
|
||||
}
|
||||
|
||||
/** Send SIGKILL to the child. */
|
||||
kill(): void {
|
||||
this.child.kill('SIGKILL')
|
||||
}
|
||||
|
||||
private onStdout(chunk: Buffer): void {
|
||||
let messages: unknown[]
|
||||
try {
|
||||
messages = this.decoder.push(chunk)
|
||||
} catch (error) {
|
||||
// A framing/JSON failure corrupts the stream position irrecoverably: fail the instance.
|
||||
this.fail(asError(error))
|
||||
this.child.kill('SIGKILL')
|
||||
return
|
||||
}
|
||||
for (const message of messages) this.dispatch(message)
|
||||
}
|
||||
|
||||
private onStderr(chunk: Buffer): void {
|
||||
if (this.stderr.length >= this.spec.maxStderrBytes) return
|
||||
this.stderr = (this.stderr + chunk.toString('utf8')).slice(0, this.spec.maxStderrBytes)
|
||||
}
|
||||
|
||||
private dispatch(message: unknown): void {
|
||||
if (message === null || typeof message !== 'object') return
|
||||
const frame = message as Record<string, unknown>
|
||||
const id = frame.id
|
||||
const method = frame.method
|
||||
if (typeof method === 'string' && (typeof id === 'number' || typeof id === 'string')) {
|
||||
void this.handleServerRequest(id, method, frame.params)
|
||||
return
|
||||
}
|
||||
if (typeof method === 'string') {
|
||||
// A server→client notification (e.g. diagnostics, logs): ignored by this MVP host.
|
||||
return
|
||||
}
|
||||
if (typeof id === 'number') this.handleResponse(id, frame)
|
||||
}
|
||||
|
||||
private async handleServerRequest(id: number | string, method: string, params: unknown): Promise<void> {
|
||||
try {
|
||||
const result = await this.onServerRequest(method, params)
|
||||
this.write({ jsonrpc: '2.0', id, result })
|
||||
} catch (error) {
|
||||
this.write({ jsonrpc: '2.0', id, error: { code: -32601, message: asError(error).message } })
|
||||
}
|
||||
}
|
||||
|
||||
private handleResponse(id: number, frame: Record<string, unknown>): void {
|
||||
const pending = this.pending.get(id)
|
||||
if (!pending) return
|
||||
this.pending.delete(id)
|
||||
const error = frame.error
|
||||
if (error !== null && typeof error === 'object') {
|
||||
const record = error as Record<string, unknown>
|
||||
pending.reject(new Error(typeof record.message === 'string' ? record.message : 'LSP error response'))
|
||||
return
|
||||
}
|
||||
pending.resolve(frame.result)
|
||||
}
|
||||
|
||||
private write(message: unknown): void {
|
||||
this.child.stdin.write(encodeMessage(message))
|
||||
}
|
||||
|
||||
private fail(error: Error): void {
|
||||
/* v8 ignore next -- the second arm (closeReason already set) needs two fail() calls before close; defensive. */
|
||||
if (this.closeReason === undefined) this.closeReason = error
|
||||
this.failAll(error)
|
||||
}
|
||||
|
||||
private failAll(error: Error): void {
|
||||
const waiting = [...this.pending.values()]
|
||||
this.pending.clear()
|
||||
for (const pending of waiting) pending.reject(error)
|
||||
}
|
||||
}
|
||||
|
||||
/** Coerce an unknown thrown value to an `Error`. */
|
||||
function asError(value: unknown): Error {
|
||||
/* v8 ignore next -- the non-Error branch guards against a non-Error throw, which our paths never produce. */
|
||||
return value instanceof Error ? value : new Error(String(value))
|
||||
}
|
||||
99
packages/lsp/lsp-local/src/framing.ts
Normal file
99
packages/lsp/lsp-local/src/framing.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* LSP base-protocol framing: `Content-Length`-delimited JSON-RPC over a byte stream. The encoder
|
||||
* produces one framed buffer; the decoder buffers incoming bytes and yields complete message bodies,
|
||||
* bounding the header and total message size so a hostile or broken server cannot exhaust memory.
|
||||
* @module @deepseek-ai/dsh-lsp-local/framing
|
||||
*/
|
||||
|
||||
/** The header/body separator in the LSP base protocol. */
|
||||
const HEADER_SEPARATOR = '\r\n\r\n'
|
||||
|
||||
/** Cap on the header section so a server that never sends the separator cannot grow the buffer forever. */
|
||||
const MAX_HEADER_BYTES = 1 << 16
|
||||
|
||||
/**
|
||||
* Encode one JSON-RPC message as a framed LSP buffer (`Content-Length: N\r\n\r\n<utf-8 json>`).
|
||||
* @param message - the JSON-RPC message object to serialize.
|
||||
* @returns the framed bytes ready to write to the server's stdin.
|
||||
*/
|
||||
export function encodeMessage(message: unknown): Buffer {
|
||||
const body = Buffer.from(JSON.stringify(message), 'utf8')
|
||||
const header = Buffer.from(`Content-Length: ${body.length}\r\n\r\n`, 'ascii')
|
||||
return Buffer.concat([header, body])
|
||||
}
|
||||
|
||||
/**
|
||||
* A streaming decoder for `Content-Length`-framed JSON-RPC. Feed it stdout chunks; it returns any
|
||||
* whole message bodies that completed. It parses only the `Content-Length` header and ignores other
|
||||
* headers (e.g. `Content-Type`), matching the base protocol.
|
||||
*/
|
||||
export class MessageDecoder {
|
||||
private buffer: Buffer = Buffer.alloc(0)
|
||||
private readonly maxMessageBytes: number
|
||||
|
||||
/**
|
||||
* @param maxMessageBytes - reject any single framed body larger than this (guards memory).
|
||||
*/
|
||||
constructor(maxMessageBytes: number) {
|
||||
this.maxMessageBytes = maxMessageBytes
|
||||
}
|
||||
|
||||
/**
|
||||
* Append a chunk and return every message body that is now complete.
|
||||
* @param chunk - raw bytes from the server's stdout.
|
||||
* @returns the parsed JSON bodies, in arrival order (possibly empty).
|
||||
* @throws Error when a header is malformed or a body exceeds `maxMessageBytes`.
|
||||
*/
|
||||
push(chunk: Buffer): unknown[] {
|
||||
this.buffer = this.buffer.length === 0 ? chunk : Buffer.concat([this.buffer, chunk])
|
||||
const messages: unknown[] = []
|
||||
for (;;) {
|
||||
const step = this.next()
|
||||
if (!step.ready) break
|
||||
messages.push(step.message)
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
/** Parse and consume the next complete message, or report that more bytes are needed. */
|
||||
private next(): { ready: false } | { ready: true; message: unknown } {
|
||||
const separator = this.buffer.indexOf(HEADER_SEPARATOR)
|
||||
if (separator < 0) {
|
||||
if (this.buffer.length > MAX_HEADER_BYTES) {
|
||||
throw new Error(`LSP header exceeded ${MAX_HEADER_BYTES} bytes without a terminator`)
|
||||
}
|
||||
return { ready: false }
|
||||
}
|
||||
const headerText = this.buffer.toString('ascii', 0, separator)
|
||||
const contentLength = parseContentLength(headerText)
|
||||
if (contentLength > this.maxMessageBytes) {
|
||||
throw new Error(`LSP message length ${contentLength} exceeds the ${this.maxMessageBytes}-byte limit`)
|
||||
}
|
||||
const bodyStart = separator + HEADER_SEPARATOR.length
|
||||
const bodyEnd = bodyStart + contentLength
|
||||
if (this.buffer.length < bodyEnd) return { ready: false }
|
||||
const body = this.buffer.toString('utf8', bodyStart, bodyEnd)
|
||||
this.buffer = this.buffer.subarray(bodyEnd)
|
||||
try {
|
||||
return { ready: true, message: JSON.parse(body) }
|
||||
} catch (error) {
|
||||
/* v8 ignore next -- JSON.parse throws a SyntaxError (an Error); the String() fallback is defensive. */
|
||||
throw new Error(`LSP message body was not valid JSON: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Read the `Content-Length` header value (case-insensitive), rejecting a missing or non-numeric one. */
|
||||
function parseContentLength(headerText: string): number {
|
||||
for (const line of headerText.split('\r\n')) {
|
||||
const colon = line.indexOf(':')
|
||||
if (colon < 0) continue
|
||||
if (line.slice(0, colon).trim().toLowerCase() !== 'content-length') continue
|
||||
const value = Number(line.slice(colon + 1).trim())
|
||||
if (!Number.isInteger(value) || value < 0) {
|
||||
throw new Error(`invalid Content-Length header: ${JSON.stringify(line)}`)
|
||||
}
|
||||
return value
|
||||
}
|
||||
throw new Error(`LSP header block missing Content-Length: ${JSON.stringify(headerText)}`)
|
||||
}
|
||||
104
packages/lsp/lsp-local/src/host.ts
Normal file
104
packages/lsp/lsp-local/src/host.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Host-filesystem source access for the local provider, using Node APIs directly in the
|
||||
* subprocess's namespace (never `ctx.fs`): only the LSP result is model-visible, so a query does not
|
||||
* satisfy read-before-write policy and emits no `fs/observed`. Canonicalization derives target
|
||||
* identity from `realpath`, so symlink aliases share a workspace; a source is rejected before server
|
||||
* startup when it is missing, non-regular, non-UTF-8, oversized, or canonically outside the
|
||||
* workspace. External result locations are allowed, but an external path can never become a query
|
||||
* source.
|
||||
* @module @deepseek-ai/dsh-lsp-local/host
|
||||
*/
|
||||
|
||||
import { readFile, realpath, stat } from 'node:fs/promises'
|
||||
import { isAbsolute, resolve as resolvePath, sep } from 'node:path'
|
||||
|
||||
/** A validated source: its canonical absolute path and current UTF-8 text. */
|
||||
export interface HostSource {
|
||||
/** The canonical (realpath-resolved) absolute path, inside the canonical workspace. */
|
||||
readonly canonicalPath: string
|
||||
/** The file's current text, read as UTF-8. */
|
||||
readonly text: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonicalize a workspace root: it must exist and be a directory. The returned realpath supplies
|
||||
* process cwd, `rootUri`, the sole `workspaceFolders` entry, and pool identity, so symlinked roots
|
||||
* collapse to one instance.
|
||||
* @param workspaceRoot - the caller's workspace root (absolute).
|
||||
* @returns the canonical directory path.
|
||||
* @throws Error when the path is missing or not a directory.
|
||||
*/
|
||||
export async function canonicalizeWorkspace(workspaceRoot: string): Promise<string> {
|
||||
let canonical: string
|
||||
try {
|
||||
canonical = await realpath(workspaceRoot)
|
||||
} catch (error) {
|
||||
throw new Error(`workspace root "${workspaceRoot}" cannot be resolved: ${messageOf(error)}`)
|
||||
}
|
||||
const info = await stat(canonical)
|
||||
if (!info.isDirectory()) {
|
||||
throw new Error(`workspace root "${workspaceRoot}" is not a directory`)
|
||||
}
|
||||
return canonical
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve, canonicalize, validate, and read a query source in one pass. A relative `filePath`
|
||||
* resolves against `canonicalWorkspace`; an absolute one is taken directly. The canonical target
|
||||
* must be a regular UTF-8 file no larger than `maxDocumentBytes`, and must lie inside the canonical
|
||||
* workspace.
|
||||
* @param filePath - the model-supplied source path (relative or absolute).
|
||||
* @param canonicalWorkspace - the already-canonicalized workspace root.
|
||||
* @param maxDocumentBytes - the largest source this host will open.
|
||||
* @returns the canonical path and current UTF-8 text.
|
||||
* @throws Error when the source is missing, non-regular, oversized, non-UTF-8, or out of workspace.
|
||||
*/
|
||||
export async function readHostSource(
|
||||
filePath: string,
|
||||
canonicalWorkspace: string,
|
||||
maxDocumentBytes: number,
|
||||
): Promise<HostSource> {
|
||||
const requested = isAbsolute(filePath) ? filePath : resolvePath(canonicalWorkspace, filePath)
|
||||
let canonicalPath: string
|
||||
try {
|
||||
canonicalPath = await realpath(requested)
|
||||
} catch (error) {
|
||||
throw new Error(`source "${filePath}" cannot be resolved: ${messageOf(error)}`)
|
||||
}
|
||||
if (!isInside(canonicalWorkspace, canonicalPath)) {
|
||||
throw new Error(`source "${filePath}" resolves outside the workspace`)
|
||||
}
|
||||
const info = await stat(canonicalPath)
|
||||
if (!info.isFile()) {
|
||||
throw new Error(`source "${filePath}" is not a regular file`)
|
||||
}
|
||||
if (info.size > maxDocumentBytes) {
|
||||
throw new Error(`source "${filePath}" is ${info.size} bytes, over the ${maxDocumentBytes}-byte limit`)
|
||||
}
|
||||
const buffer = await readFile(canonicalPath)
|
||||
const text = decodeUtf8Strict(buffer, filePath)
|
||||
return { canonicalPath, text }
|
||||
}
|
||||
|
||||
/** Whether `child` is the workspace itself or a descendant of it (both already canonical). */
|
||||
function isInside(workspace: string, child: string): boolean {
|
||||
if (child === workspace) return true
|
||||
/* v8 ignore next -- a canonical non-root workspace never ends with a separator; the guard covers the filesystem root. */
|
||||
const base = workspace.endsWith(sep) ? workspace : workspace + sep
|
||||
return child.startsWith(base)
|
||||
}
|
||||
|
||||
/** Decode UTF-8 strictly (a replacement char means the source was not valid UTF-8 text). */
|
||||
function decodeUtf8Strict(buffer: Buffer, filePath: string): string {
|
||||
const text = buffer.toString('utf8')
|
||||
if (text.includes('<27>')) {
|
||||
throw new Error(`source "${filePath}" is not valid UTF-8 text`)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
/** Extract a message from an unknown thrown value without leaking `any`. */
|
||||
function messageOf(error: unknown): string {
|
||||
/* v8 ignore next -- Node fs rejections are always Error instances; the String() fallback is defensive. */
|
||||
return error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
255
packages/lsp/lsp-local/src/index.ts
Normal file
255
packages/lsp/lsp-local/src/index.ts
Normal file
@@ -0,0 +1,255 @@
|
||||
/**
|
||||
* Generic stdio language-server provider for `ctx.lsp`. One plugin instance configures one server
|
||||
* command and its extension→language-id map; load multiple instances for multiple servers. The
|
||||
* provider lazily single-flights one server process per `(provider id, canonical workspace
|
||||
* realpath)`, serves transient-open queries through it, and evicts a crashed process so a later
|
||||
* query can replace it. It reads sources through Node APIs in the host namespace (not `ctx.fs`) and
|
||||
* trusts its configured server — no sandbox confinement.
|
||||
*
|
||||
* Namespace plugin (named exports, no default export). Lifecycle is effect-scoped: disposal
|
||||
* unregisters from `ctx.lsp` and tears down every live server.
|
||||
* @module @deepseek-ai/dsh-lsp-local
|
||||
*/
|
||||
|
||||
import { accessSync, constants } from 'node:fs'
|
||||
import { delimiter, isAbsolute, join } from 'node:path'
|
||||
import type { Context } from 'cordis'
|
||||
import z from 'schemastery'
|
||||
import { LspProviderId } from '@deepseek-ai/dsh-lsp'
|
||||
import type {
|
||||
LspProvider,
|
||||
LspProviderQuery,
|
||||
LspQueryResult,
|
||||
} from '@deepseek-ai/dsh-lsp'
|
||||
// Side-effect type import: declaration-merges `ctx.lsp` onto Context.
|
||||
import type {} from '@deepseek-ai/dsh-lsp'
|
||||
import { canonicalizeWorkspace } from './host.ts'
|
||||
import { LspInstance } from './instance.ts'
|
||||
import type { InstanceSpec } from './instance.ts'
|
||||
|
||||
export { canonicalizeWorkspace, readHostSource } from './host.ts'
|
||||
export { encodeMessage, MessageDecoder } from './framing.ts'
|
||||
export {
|
||||
negotiatePositionEncoding,
|
||||
normalizeHover,
|
||||
normalizeLocations,
|
||||
requestMethod,
|
||||
supportsOperation,
|
||||
supportsTransientOpen,
|
||||
} from './translate.ts'
|
||||
export { LspInstance } from './instance.ts'
|
||||
export { LspConnection } from './connection.ts'
|
||||
|
||||
/** Cordis plugin name for loader diagnostics. */
|
||||
export const name = 'lsp-local'
|
||||
|
||||
/** Services required by this plugin. */
|
||||
export const inject = ['lsp']
|
||||
|
||||
/** Credential-shaped ambient env vars are NOT forwarded to the child by default. */
|
||||
const SENSITIVE_ENV_PATTERN = /KEY|SECRET|TOKEN/i
|
||||
|
||||
const DEFAULT_MAX_MESSAGE_BYTES = 16_000_000
|
||||
const DEFAULT_MAX_STDERR_BYTES = 1_000_000
|
||||
const DEFAULT_MAX_DOCUMENT_BYTES = 4_000_000
|
||||
const DEFAULT_SHUTDOWN_TIMEOUT_MS = 5_000
|
||||
const DEFAULT_KILL_GRACE_MS = 2_000
|
||||
|
||||
/** Plugin configuration: one server command plus its extension mapping and host bounds. */
|
||||
export interface Config {
|
||||
/** Stable provider id, reserved on `ctx.lsp` with the extensions. */
|
||||
providerId: string
|
||||
/** Executable to spawn (absolute, or resolved on PATH at load). */
|
||||
command: string
|
||||
/** Lowercase leading-dot extension → LSP language id (e.g. `{ '.ts': 'typescript' }`). */
|
||||
extensionToLanguage: Record<string, string>
|
||||
/** Arguments passed to the executable (no shell). Default `[]`. */
|
||||
args?: string[]
|
||||
/** Extra env vars merged on top of the scrubbed ambient env. Default `{}`. */
|
||||
env?: Record<string, string>
|
||||
/** Static `initialize` options forwarded to the server. Default `null`. */
|
||||
initializationOptions?: unknown
|
||||
/** Static answer to every `workspace/configuration` item. Default `null`. */
|
||||
configuration?: unknown
|
||||
/** Largest single framed message accepted from the server (bytes). Default 16000000. */
|
||||
maxMessageBytes?: number
|
||||
/** Largest stderr tail retained for diagnostics (bytes). Default 1000000. */
|
||||
maxStderrBytes?: number
|
||||
/** Largest source file this host will open (bytes). Default 4000000. */
|
||||
maxDocumentBytes?: number
|
||||
/** Graceful `shutdown`/`exit` budget before escalation (ms). Default 5000. */
|
||||
shutdownTimeoutMs?: number
|
||||
/** SIGTERM→SIGKILL grace after graceful shutdown fails (ms). Default 2000. */
|
||||
killGraceMs?: number
|
||||
}
|
||||
|
||||
/** The resolved config after schemastery fills every default; the provider reads this shape. */
|
||||
type ResolvedConfig = Required<Config>
|
||||
|
||||
export const Config: z<Config> = z.object({
|
||||
providerId: z.string().required(),
|
||||
command: z.string().required(),
|
||||
args: z.array(String).default([]),
|
||||
env: z.dict(String).default({}),
|
||||
extensionToLanguage: z.dict(String).required(),
|
||||
initializationOptions: z.any().default(null),
|
||||
configuration: z.any().default(null),
|
||||
maxMessageBytes: z.number().default(DEFAULT_MAX_MESSAGE_BYTES),
|
||||
maxStderrBytes: z.number().default(DEFAULT_MAX_STDERR_BYTES),
|
||||
maxDocumentBytes: z.number().default(DEFAULT_MAX_DOCUMENT_BYTES),
|
||||
shutdownTimeoutMs: z.number().default(DEFAULT_SHUTDOWN_TIMEOUT_MS),
|
||||
killGraceMs: z.number().default(DEFAULT_KILL_GRACE_MS),
|
||||
})
|
||||
|
||||
/**
|
||||
* Register a generic stdio LSP provider. Resolves the executable at load (after credential
|
||||
* scrubbing) and fails before registration when it is unavailable; the process itself launches
|
||||
* lazily on the first matching query.
|
||||
* @param ctx - the plugin context (must inject `lsp`).
|
||||
* @param config - the resolved plugin configuration (schemastery has filled every default).
|
||||
*/
|
||||
export function apply(ctx: Context, config: Config): void {
|
||||
const resolved = config as ResolvedConfig
|
||||
const childEnv = buildChildEnv(resolved.env)
|
||||
// Resolve the executable eagerly so a misconfigured command fails at load, not on first query.
|
||||
const executable = resolveExecutable(resolved.command, childEnv)
|
||||
|
||||
const provider = new LocalLspProvider(resolved, childEnv, executable)
|
||||
ctx.effect(() => {
|
||||
const dispose = ctx.lsp.registerProvider(provider)
|
||||
return async () => {
|
||||
dispose()
|
||||
await provider.disposeAll()
|
||||
}
|
||||
}, 'lsp-local.registerProvider')
|
||||
}
|
||||
|
||||
/** A pooled generic provider: one server process per canonical workspace, created on demand. */
|
||||
class LocalLspProvider implements LspProvider {
|
||||
readonly id: LspProviderId
|
||||
readonly extensionToLanguage: Readonly<Record<string, string>>
|
||||
/** Single-flight map: canonical workspace realpath → the (pending) instance for it. */
|
||||
private readonly instances = new Map<string, Promise<LspInstance>>()
|
||||
private disposed = false
|
||||
|
||||
constructor(
|
||||
private readonly config: ResolvedConfig,
|
||||
private readonly childEnv: Record<string, string>,
|
||||
private readonly executable: string,
|
||||
) {
|
||||
this.id = LspProviderId(config.providerId)
|
||||
this.extensionToLanguage = config.extensionToLanguage
|
||||
}
|
||||
|
||||
async query(request: LspProviderQuery, signal?: AbortSignal): Promise<LspQueryResult> {
|
||||
/* v8 ignore next -- the seam unregisters this provider on dispose, so a query never reaches a disposed provider; defensive. */
|
||||
if (this.disposed) throw new Error('lsp-local provider is disposed')
|
||||
const workspace = await canonicalizeWorkspace(request.workspaceRoot)
|
||||
const instance = await this.instanceFor(workspace)
|
||||
try {
|
||||
return await instance.query(request, signal)
|
||||
} finally {
|
||||
// A crashed/closed process must not be reused: drop its slot so the next query starts fresh,
|
||||
// but only if the slot still holds THIS instance (a concurrent replacement must survive).
|
||||
if (instance.dead) {
|
||||
const slot = this.instances.get(workspace)
|
||||
/* v8 ignore next -- the slot-undefined arm needs a concurrent eviction of the same slot; defensive. */
|
||||
if (slot !== undefined && (await settledInstance(slot)) === instance) {
|
||||
this.instances.delete(workspace)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Single-flight one instance per canonical workspace; a rejected creation clears the slot. */
|
||||
private instanceFor(workspace: string): Promise<LspInstance> {
|
||||
const existing = this.instances.get(workspace)
|
||||
if (existing !== undefined) return existing
|
||||
const created = Promise.resolve().then(() => this.createInstance(workspace))
|
||||
this.instances.set(workspace, created)
|
||||
/* v8 ignore next 3 -- createInstance (the LspInstance constructor) does not throw; spawn failures
|
||||
surface asynchronously through the instance, so this creation-rejection cleanup is defensive. */
|
||||
created.catch(() => {
|
||||
if (this.instances.get(workspace) === created) this.instances.delete(workspace)
|
||||
})
|
||||
return created
|
||||
}
|
||||
|
||||
private createInstance(workspace: string): LspInstance {
|
||||
const spec: InstanceSpec = {
|
||||
command: this.executable,
|
||||
args: this.config.args,
|
||||
cwd: workspace,
|
||||
env: this.childEnv,
|
||||
configuration: this.config.configuration,
|
||||
initializationOptions: this.config.initializationOptions,
|
||||
maxMessageBytes: this.config.maxMessageBytes,
|
||||
maxStderrBytes: this.config.maxStderrBytes,
|
||||
maxDocumentBytes: this.config.maxDocumentBytes,
|
||||
shutdownTimeoutMs: this.config.shutdownTimeoutMs,
|
||||
killGraceMs: this.config.killGraceMs,
|
||||
}
|
||||
return new LspInstance(spec)
|
||||
}
|
||||
|
||||
/** Dispose every live instance and block further queries. */
|
||||
async disposeAll(): Promise<void> {
|
||||
this.disposed = true
|
||||
const pending = [...this.instances.values()]
|
||||
this.instances.clear()
|
||||
await Promise.all(pending.map(async (entry) => {
|
||||
try {
|
||||
const instance = await entry
|
||||
await instance.dispose()
|
||||
} catch {
|
||||
// A never-initialized instance already rejected; nothing to tear down.
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve a slot promise to its instance for identity comparison, tolerating a pending rejection. */
|
||||
async function settledInstance(slot: Promise<LspInstance>): Promise<LspInstance | undefined> {
|
||||
try {
|
||||
return await slot
|
||||
} catch {
|
||||
/* v8 ignore next -- a slot promise only rejects if createInstance throws, which it never does; defensive. */
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** The ambient env minus credential-shaped vars, plus the config's explicit env. */
|
||||
function buildChildEnv(extra: Record<string, string>): Record<string, string> {
|
||||
const scrubbed = Object.entries(process.env).filter(
|
||||
([key, value]) => value !== undefined && !SENSITIVE_ENV_PATTERN.test(key),
|
||||
) as [string, string][]
|
||||
return { ...Object.fromEntries(scrubbed), ...extra }
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the server executable to an absolute path: an absolute command is verified directly; a
|
||||
* bare command is looked up on the child's PATH. Fails loudly when nothing is executable.
|
||||
*/
|
||||
function resolveExecutable(command: string, childEnv: Record<string, string>): string {
|
||||
if (isAbsolute(command)) {
|
||||
return command
|
||||
}
|
||||
/* v8 ignore next -- buildChildEnv always sets PATH from the ambient env; the further fallbacks are defensive. */
|
||||
const pathValue = childEnv.PATH ?? process.env.PATH ?? ''
|
||||
for (const dir of pathValue.split(delimiter)) {
|
||||
if (dir === '') continue
|
||||
const candidate = join(dir, command)
|
||||
if (isExecutableSync(candidate)) return candidate
|
||||
}
|
||||
throw new Error(`lsp-local: command "${command}" was not found on PATH`)
|
||||
}
|
||||
|
||||
/** Synchronous executable check used only at load-time resolution. */
|
||||
function isExecutableSync(path: string): boolean {
|
||||
try {
|
||||
accessSync(path, constants.X_OK)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
293
packages/lsp/lsp-local/src/instance.ts
Normal file
293
packages/lsp/lsp-local/src/instance.ts
Normal file
@@ -0,0 +1,293 @@
|
||||
/**
|
||||
* One language-server instance: a connection plus the initialize handshake, the serialized abortable
|
||||
* query queue, the transient `didOpen`→request→`didClose` lifecycle, and bounded teardown. One
|
||||
* instance owns one `(provider id, canonical workspace)` process. Queries serialize through a single
|
||||
* queue so a cancellation that fails to stop the server can terminate it without killing unrelated
|
||||
* work; distinct instances run in parallel.
|
||||
* @module @deepseek-ai/dsh-lsp-local/instance
|
||||
*/
|
||||
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import type {
|
||||
LspOperation,
|
||||
LspProviderQuery,
|
||||
LspQueryResult,
|
||||
} from '@deepseek-ai/dsh-lsp'
|
||||
import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout'
|
||||
import { LspConnection } from './connection.ts'
|
||||
import type { ConnectionSpec } from './connection.ts'
|
||||
import { readHostSource } from './host.ts'
|
||||
import type { WireInitializeResult, WireServerCapabilities } from './protocol.ts'
|
||||
import {
|
||||
negotiatePositionEncoding,
|
||||
normalizeHover,
|
||||
normalizeLocations,
|
||||
requestMethod,
|
||||
supportsOperation,
|
||||
supportsTransientOpen,
|
||||
} from './translate.ts'
|
||||
|
||||
/** Everything an instance needs beyond the connection spec. */
|
||||
export interface InstanceSpec extends ConnectionSpec {
|
||||
/** Static `initialize` options forwarded to the server. */
|
||||
readonly initializationOptions: unknown
|
||||
/** Largest source file this host will open (bytes). */
|
||||
readonly maxDocumentBytes: number
|
||||
/** Graceful `shutdown`/`exit` budget before escalation (ms). */
|
||||
readonly shutdownTimeoutMs: number
|
||||
/** SIGTERM→SIGKILL grace after graceful shutdown fails (ms). */
|
||||
readonly killGraceMs: number
|
||||
}
|
||||
|
||||
/**
|
||||
* A single initialized server process. Not exported as a provider — the provider single-flights and
|
||||
* pools these. `query()` serializes; `dispose()` rejects queued work and tears the process down.
|
||||
*/
|
||||
export class LspInstance {
|
||||
private readonly connection: LspConnection
|
||||
private capabilities: WireServerCapabilities | undefined
|
||||
/** The serialization tail: each query awaits the prior one, so lifecycles never interleave. */
|
||||
private queue: Promise<unknown> = Promise.resolve()
|
||||
private disposed = false
|
||||
/** Set once the process closes, so the pool can synchronously skip a dead instance. */
|
||||
private processClosed = false
|
||||
/** Populated once `initialize` succeeds; a failed handshake rejects every query. */
|
||||
private readonly ready: Promise<void>
|
||||
|
||||
/**
|
||||
* @param spec - the launch, initialize, and teardown parameters.
|
||||
*/
|
||||
constructor(private readonly spec: InstanceSpec) {
|
||||
this.connection = new LspConnection(spec, (method, params) => this.answerServerRequest(method, params))
|
||||
this.ready = this.initialize()
|
||||
// A handshake rejection must not surface as an unhandled rejection before the first query awaits
|
||||
// it; queries attach the real handler.
|
||||
this.ready.catch(() => {})
|
||||
void this.connection.closed.then(() => { this.processClosed = true })
|
||||
}
|
||||
|
||||
/** Synchronous liveness check: true once the process has closed or the instance was disposed. */
|
||||
get dead(): boolean {
|
||||
return this.processClosed || this.disposed
|
||||
}
|
||||
|
||||
/**
|
||||
* Run one query through the serialized queue.
|
||||
* @param request - the resolved provider query.
|
||||
* @param signal - optional cancellation for this query's full lifecycle.
|
||||
* @returns the normalized result.
|
||||
*/
|
||||
query(request: LspProviderQuery, signal?: AbortSignal): Promise<LspQueryResult> {
|
||||
const run = this.queue.then(() => this.runQuery(request, signal))
|
||||
// Keep the tail alive regardless of this query's outcome so the next caller still serializes.
|
||||
this.queue = run.then(() => undefined, () => undefined)
|
||||
return run
|
||||
}
|
||||
|
||||
private async initialize(): Promise<void> {
|
||||
const initializeResult = await this.connection.request('initialize', {
|
||||
processId: process.pid,
|
||||
rootUri: pathToFileURL(this.spec.cwd).href,
|
||||
workspaceFolders: [{ uri: pathToFileURL(this.spec.cwd).href, name: 'workspace' }],
|
||||
capabilities: CLIENT_CAPABILITIES,
|
||||
initializationOptions: this.spec.initializationOptions,
|
||||
}) as WireInitializeResult
|
||||
const capabilities = initializeResult.capabilities
|
||||
// An omitted encoding defaults to utf-16; any other value is a protocol error we reject here.
|
||||
negotiatePositionEncoding(capabilities.positionEncoding)
|
||||
this.capabilities = capabilities
|
||||
this.connection.notify('initialized', {})
|
||||
}
|
||||
|
||||
private async runQuery(request: LspProviderQuery, signal?: AbortSignal): Promise<LspQueryResult> {
|
||||
if (this.disposed) throw new Error('LSP instance was disposed')
|
||||
if (signal?.aborted) throw abortError(signal)
|
||||
await this.ready
|
||||
const capabilities = this.capabilities
|
||||
/* v8 ignore next -- `ready` resolves only after capabilities are set, else it rejects above; defensive. */
|
||||
if (capabilities === undefined) throw new Error('LSP instance is not initialized')
|
||||
if (!supportsOperation(capabilities, request.operation)) {
|
||||
throw new Error(`server does not support ${request.operation}`)
|
||||
}
|
||||
if (!supportsTransientOpen(capabilities.textDocumentSync)) {
|
||||
throw new Error('server does not support the transient textDocument/didOpen this host requires')
|
||||
}
|
||||
|
||||
const source = await readHostSource(request.filePath, this.spec.cwd, this.spec.maxDocumentBytes)
|
||||
const uri = pathToFileURL(source.canonicalPath).href
|
||||
let opened = false
|
||||
try {
|
||||
if (signal?.aborted) throw abortError(signal)
|
||||
this.connection.notify('textDocument/didOpen', {
|
||||
textDocument: { uri, languageId: request.languageId, version: 1, text: source.text },
|
||||
})
|
||||
opened = true
|
||||
const payload = await this.sendRequest(request.operation, uri, request.position, signal)
|
||||
return this.normalize(request.operation, payload)
|
||||
} finally {
|
||||
if (opened) {
|
||||
try {
|
||||
this.connection.notify('textDocument/didClose', { textDocument: { uri } })
|
||||
} catch (error) {
|
||||
/* v8 ignore start -- stdin write errors surface asynchronously via the swallowed 'error'
|
||||
listener, so a synchronous didClose write failure is a defensive path. */
|
||||
// A close-write failure does not replace the settled result/error, but the instance can no
|
||||
// longer be trusted: invalidate it and await bounded process termination.
|
||||
this.disposed = true
|
||||
void this.tearDown(error instanceof Error ? error : new Error(String(error)))
|
||||
/* v8 ignore stop */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async sendRequest(
|
||||
operation: LspOperation,
|
||||
uri: string,
|
||||
position: LspProviderQuery['position'],
|
||||
signal?: AbortSignal,
|
||||
): Promise<unknown> {
|
||||
const params = {
|
||||
textDocument: { uri },
|
||||
position: { line: position.line, character: position.character },
|
||||
// references always includes declarations: the caller gets no flag and impact analysis never
|
||||
// omits the defining site.
|
||||
...(operation === 'references' ? { context: { includeDeclaration: true } } : {}),
|
||||
}
|
||||
const requestId = this.connection.peekNextId()
|
||||
const send = this.connection.request(requestMethod(operation), params)
|
||||
if (signal === undefined) return send
|
||||
return this.raceAbort(send, requestId, signal)
|
||||
}
|
||||
|
||||
/** Race a pending request against abort; on abort, send `$/cancelRequest` and reject. */
|
||||
private async raceAbort(send: Promise<unknown>, requestId: number, signal: AbortSignal): Promise<unknown> {
|
||||
const abort = new Promise<never>((_, reject) => {
|
||||
const onAbort = (): void => { reject(abortError(signal)) }
|
||||
/* v8 ignore next -- runQuery checks signal.aborted before sending, so it is not yet aborted here; defensive. */
|
||||
if (signal.aborted) { onAbort(); return }
|
||||
signal.addEventListener('abort', onAbort, { once: true })
|
||||
// Remove the abort listener once the request settles either way; the finally-promise inherits
|
||||
// send's rejection, so catch it to avoid an unhandled rejection when abort already won.
|
||||
send.finally(() => { signal.removeEventListener('abort', onAbort) }).catch(() => {})
|
||||
})
|
||||
try {
|
||||
return await Promise.race([send, abort])
|
||||
} catch (error) {
|
||||
if (signal.aborted) this.connection.cancel(requestId)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private normalize(operation: LspOperation, payload: unknown): LspQueryResult {
|
||||
if (operation === 'hover') {
|
||||
return { kind: 'hover', hover: normalizeHover(payload) }
|
||||
}
|
||||
return { kind: 'locations', locations: normalizeLocations(payload) }
|
||||
}
|
||||
|
||||
private answerServerRequest(method: string, params: unknown): Promise<unknown> {
|
||||
if (method === 'workspace/configuration') {
|
||||
// Answer every requested item with the one static configuration value.
|
||||
const record = params as { items?: unknown[] } | null
|
||||
/* v8 ignore next -- a configuration request always carries an items array; the empty fallback is defensive. */
|
||||
const items = Array.isArray(record?.items) ? record.items : []
|
||||
return Promise.resolve(items.map(() => this.spec.configuration))
|
||||
}
|
||||
if (LIFECYCLE_NOOP_METHODS.has(method)) {
|
||||
// Accept lifecycle bookkeeping requests with an empty result; we register nothing dynamic.
|
||||
return Promise.resolve(null)
|
||||
}
|
||||
if (method === 'workspace/applyEdit') {
|
||||
// This host never applies edits or runs commands.
|
||||
return Promise.reject(new Error('workspace/applyEdit is not permitted by this host'))
|
||||
}
|
||||
return Promise.reject(new Error(`unsupported server request: ${method}`))
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject queued work, attempt graceful `shutdown`/`exit`, then escalate SIGTERM→SIGKILL, awaiting
|
||||
* process close so nothing outlives disposal.
|
||||
*/
|
||||
async dispose(): Promise<void> {
|
||||
if (this.disposed) {
|
||||
await this.connection.closed
|
||||
return
|
||||
}
|
||||
this.disposed = true
|
||||
await this.tearDown(new Error('LSP instance disposed'))
|
||||
}
|
||||
|
||||
private async tearDown(_reason: Error): Promise<void> {
|
||||
try {
|
||||
using shutdownDeadline = deadline(undefined, this.spec.shutdownTimeoutMs, 'LSP_SHUTDOWN')
|
||||
await this.gracefulShutdown(shutdownDeadline.signal)
|
||||
} catch {
|
||||
// Graceful shutdown failed or timed out: fall through to signal escalation.
|
||||
}
|
||||
await this.forceTerminate()
|
||||
}
|
||||
|
||||
/** Best-effort LSP `shutdown` request then `exit` notification, bounded by `signal`. */
|
||||
private async gracefulShutdown(signal: AbortSignal): Promise<void> {
|
||||
const shutdown = this.connection.request('shutdown', null)
|
||||
await Promise.race([
|
||||
shutdown,
|
||||
new Promise<never>((_, reject) => {
|
||||
/* v8 ignore next -- the shutdown deadline signal is freshly armed and not yet aborted here; defensive. */
|
||||
if (signal.aborted) { reject(abortError(signal)); return }
|
||||
signal.addEventListener('abort', () => { reject(abortError(signal)) }, { once: true })
|
||||
}),
|
||||
])
|
||||
this.connection.notify('exit', null)
|
||||
}
|
||||
|
||||
/** SIGTERM, wait `killGraceMs` for close, then SIGKILL; await full process close either way. */
|
||||
private async forceTerminate(): Promise<void> {
|
||||
this.connection.terminate()
|
||||
using graceDeadline = deadline(undefined, this.spec.killGraceMs, 'LSP_KILL_GRACE')
|
||||
const closedInTime = await Promise.race([
|
||||
this.connection.closed.then(() => true),
|
||||
new Promise<boolean>((resolve) => {
|
||||
/* v8 ignore next -- the kill-grace deadline signal is freshly armed and not yet aborted here; defensive. */
|
||||
if (graceDeadline.signal.aborted) { resolve(false); return }
|
||||
graceDeadline.signal.addEventListener('abort', () => { resolve(false) }, { once: true })
|
||||
}),
|
||||
])
|
||||
if (!closedInTime) this.connection.kill()
|
||||
await this.connection.closed
|
||||
}
|
||||
}
|
||||
|
||||
/** Server→client request methods this host acknowledges with an empty result (no dynamic registration). */
|
||||
const LIFECYCLE_NOOP_METHODS = new Set([
|
||||
'window/workDoneProgress/create',
|
||||
'client/registerCapability',
|
||||
'client/unregisterCapability',
|
||||
])
|
||||
|
||||
/** Build an abort Error carrying the signal's reason (preserving a timeout classification). */
|
||||
function abortError(signal: AbortSignal): Error {
|
||||
const timeout = timeoutOf(signal)
|
||||
if (timeout !== undefined) return timeout
|
||||
const reason: unknown = signal.reason
|
||||
if (reason instanceof Error) return reason
|
||||
return new Error('LSP query aborted')
|
||||
}
|
||||
|
||||
/**
|
||||
* The client capabilities advertised at `initialize`: UTF-16 positions, workspace folders and
|
||||
* configuration, markdown/plaintext hover, and link support for definition/implementation. No
|
||||
* dynamic registration; the server's returned capabilities are authoritative.
|
||||
*/
|
||||
const CLIENT_CAPABILITIES = {
|
||||
general: { positionEncodings: ['utf-16'] },
|
||||
workspace: { workspaceFolders: true, configuration: true },
|
||||
textDocument: {
|
||||
synchronization: { dynamicRegistration: false },
|
||||
hover: { contentFormat: ['markdown', 'plaintext'] },
|
||||
definition: { linkSupport: true },
|
||||
implementation: { linkSupport: true },
|
||||
references: {},
|
||||
},
|
||||
} as const
|
||||
80
packages/lsp/lsp-local/src/protocol.ts
Normal file
80
packages/lsp/lsp-local/src/protocol.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* The subset of LSP wire types this generic host reads and writes: initialize capabilities, the four
|
||||
* request results (`Location`, `LocationLink`, `Hover`), and the `textDocumentSync` shapes used to
|
||||
* decide transient-open support. Types only. Fields absent from a real server payload stay optional;
|
||||
* the translation layer normalizes them into the seam's closed unions.
|
||||
* @module @deepseek-ai/dsh-lsp-local/protocol
|
||||
*/
|
||||
|
||||
/** A zero-based UTF-16 position on the wire (the protocol's `Position`). */
|
||||
export interface WirePosition {
|
||||
readonly line: number
|
||||
readonly character: number
|
||||
}
|
||||
|
||||
/** A wire range (`Range`). */
|
||||
export interface WireRange {
|
||||
readonly start: WirePosition
|
||||
readonly end: WirePosition
|
||||
}
|
||||
|
||||
/** A `Location`: a document URI plus a range. */
|
||||
export interface WireLocation {
|
||||
readonly uri: string
|
||||
readonly range: WireRange
|
||||
}
|
||||
|
||||
/** A `LocationLink`: the target uri plus the selection range to focus. */
|
||||
export interface WireLocationLink {
|
||||
readonly targetUri: string
|
||||
readonly targetSelectionRange: WireRange
|
||||
readonly targetRange?: WireRange
|
||||
}
|
||||
|
||||
/** A `MarkupContent` hover body (`markdown` or `plaintext`). */
|
||||
export interface WireMarkupContent {
|
||||
readonly kind: 'markdown' | 'plaintext'
|
||||
readonly value: string
|
||||
}
|
||||
|
||||
/** A `MarkedString` object form (`{ language, value }`); the string form is a bare `string`. */
|
||||
export interface WireMarkedStringObject {
|
||||
readonly language: string
|
||||
readonly value: string
|
||||
}
|
||||
|
||||
/** One `MarkedString`: a raw string or a language-tagged code block. */
|
||||
export type WireMarkedString = string | WireMarkedStringObject
|
||||
|
||||
/** A `Hover`: contents in any of the protocol's three encodings, plus an optional range. */
|
||||
export interface WireHover {
|
||||
readonly contents: WireMarkupContent | WireMarkedString | readonly WireMarkedString[]
|
||||
readonly range?: WireRange
|
||||
}
|
||||
|
||||
/** The legacy enum form of `textDocumentSync` (`0` None, `1` Full, `2` Incremental). */
|
||||
export type WireTextDocumentSyncKind = 0 | 1 | 2
|
||||
|
||||
/** The options form of `textDocumentSync` (`{ openClose, change }`). */
|
||||
export interface WireTextDocumentSyncOptions {
|
||||
readonly openClose?: boolean
|
||||
readonly change?: WireTextDocumentSyncKind
|
||||
}
|
||||
|
||||
/** A `ServerCapabilities.provider` slot: a boolean or an options object (both mean "supported"). */
|
||||
export type WireProviderCapability = boolean | Record<string, unknown> | undefined
|
||||
|
||||
/** The `ServerCapabilities` fields this host inspects. */
|
||||
export interface WireServerCapabilities {
|
||||
readonly positionEncoding?: string
|
||||
readonly textDocumentSync?: WireTextDocumentSyncKind | WireTextDocumentSyncOptions
|
||||
readonly definitionProvider?: WireProviderCapability
|
||||
readonly referencesProvider?: WireProviderCapability
|
||||
readonly implementationProvider?: WireProviderCapability
|
||||
readonly hoverProvider?: WireProviderCapability
|
||||
}
|
||||
|
||||
/** The `initialize` result envelope. */
|
||||
export interface WireInitializeResult {
|
||||
readonly capabilities: WireServerCapabilities
|
||||
}
|
||||
210
packages/lsp/lsp-local/src/translate.ts
Normal file
210
packages/lsp/lsp-local/src/translate.ts
Normal file
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* Pure protocol translation for the local host: what the server's capabilities allow, and how its
|
||||
* `Location`/`LocationLink`/`Hover` payloads normalize into the seam's closed result unions. No I/O
|
||||
* or process state — every function here is a pure transform, which the fake-stdio tests pin exactly.
|
||||
* @module @deepseek-ai/dsh-lsp-local/translate
|
||||
*/
|
||||
|
||||
import type {
|
||||
LspHover,
|
||||
LspLocation,
|
||||
LspOperation,
|
||||
LspRange,
|
||||
} from '@deepseek-ai/dsh-lsp'
|
||||
import { assertNever } from '@deepseek-ai/dsh-llm'
|
||||
import type {
|
||||
WireHover,
|
||||
WireLocation,
|
||||
WireLocationLink,
|
||||
WireMarkedString,
|
||||
WireProviderCapability,
|
||||
WireRange,
|
||||
WireServerCapabilities,
|
||||
WireTextDocumentSyncKind,
|
||||
WireTextDocumentSyncOptions,
|
||||
} from './protocol.ts'
|
||||
|
||||
/**
|
||||
* The `textDocument/*` request method for each seam operation.
|
||||
* @param operation - the seam operation to map.
|
||||
* @returns the LSP request method name.
|
||||
*/
|
||||
export function requestMethod(operation: LspOperation): string {
|
||||
switch (operation) {
|
||||
case 'definition': return 'textDocument/definition'
|
||||
case 'references': return 'textDocument/references'
|
||||
case 'implementation': return 'textDocument/implementation'
|
||||
case 'hover': return 'textDocument/hover'
|
||||
/* v8 ignore next -- exhaustive over the closed LspOperation union; unreachable. */
|
||||
default: return assertNever(operation, 'requestMethod')
|
||||
}
|
||||
}
|
||||
|
||||
/** The `ServerCapabilities` provider field backing each operation. */
|
||||
function capabilityValue(capabilities: WireServerCapabilities, operation: LspOperation): WireProviderCapability {
|
||||
switch (operation) {
|
||||
case 'definition': return capabilities.definitionProvider
|
||||
case 'references': return capabilities.referencesProvider
|
||||
case 'implementation': return capabilities.implementationProvider
|
||||
case 'hover': return capabilities.hoverProvider
|
||||
/* v8 ignore next -- exhaustive over the closed LspOperation union; unreachable. */
|
||||
default: return assertNever(operation, 'capabilityValue')
|
||||
}
|
||||
}
|
||||
|
||||
/** A provider capability is present when the server sent `true` or an options object (not `false`/absent). */
|
||||
function supportsCapability(value: WireProviderCapability): boolean {
|
||||
if (value === undefined) return false
|
||||
if (typeof value === 'boolean') return value
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the server advertises the requested operation.
|
||||
* @param capabilities - the server's `initialize` capabilities.
|
||||
* @param operation - the seam operation to check.
|
||||
* @returns true when the corresponding provider capability is present.
|
||||
*/
|
||||
export function supportsOperation(capabilities: WireServerCapabilities, operation: LspOperation): boolean {
|
||||
return supportsCapability(capabilityValue(capabilities, operation))
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a `textDocumentSync` value permits the transient `didOpen`/`didClose` this host relies on.
|
||||
* @param sync - the server's advertised `textDocumentSync` capability.
|
||||
* @returns true when transient open/close is supported.
|
||||
*/
|
||||
export function supportsTransientOpen(sync: WireServerCapabilities['textDocumentSync']): boolean {
|
||||
if (sync === undefined) return false
|
||||
if (typeof sync === 'number') return isOpenCloseKind(sync)
|
||||
return sync.openClose === true || (sync.openClose === undefined && changeAllowsOpenClose(sync))
|
||||
}
|
||||
|
||||
/** Legacy enum: `Full` (1) or `Incremental` (2) imply open/close support; `None` (0) does not. */
|
||||
function isOpenCloseKind(kind: WireTextDocumentSyncKind): boolean {
|
||||
return kind === 1 || kind === 2
|
||||
}
|
||||
|
||||
/** Options without an explicit `openClose` fall back to the legacy `change` enum's implication. */
|
||||
function changeAllowsOpenClose(sync: WireTextDocumentSyncOptions): boolean {
|
||||
return sync.change !== undefined && isOpenCloseKind(sync.change)
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the negotiated position encoding. An omitted encoding defaults to `utf-16`; any value
|
||||
* other than `utf-16` is a protocol error this host does not support.
|
||||
* @param encoding - the server's advertised `positionEncoding`, if any.
|
||||
* @returns the string `'utf-16'`.
|
||||
* @throws Error for any non-`utf-16` encoding.
|
||||
*/
|
||||
export function negotiatePositionEncoding(encoding: string | undefined): 'utf-16' {
|
||||
if (encoding === undefined || encoding === 'utf-16') return 'utf-16'
|
||||
throw new Error(`server negotiated unsupported position encoding "${encoding}"; this host requires utf-16`)
|
||||
}
|
||||
|
||||
/** Convert a wire range to the seam's range (structurally identical, but re-shaped as `readonly`). */
|
||||
function toRange(range: WireRange): LspRange {
|
||||
return {
|
||||
start: { line: range.start.line, character: range.start.character },
|
||||
end: { line: range.end.line, character: range.end.character },
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a record is a `LocationLink` (has `targetUri` + `targetSelectionRange`). */
|
||||
function isLocationLink(value: Record<string, unknown>): boolean {
|
||||
return typeof value.targetUri === 'string' && isRange(value.targetSelectionRange)
|
||||
}
|
||||
|
||||
/** Whether a record is a `Location` (has string `uri` + a range). */
|
||||
function isLocation(value: Record<string, unknown>): boolean {
|
||||
return typeof value.uri === 'string' && isRange(value.range)
|
||||
}
|
||||
|
||||
/** Structural range guard used by both location shapes. */
|
||||
function isRange(value: unknown): value is WireRange {
|
||||
if (value === null || typeof value !== 'object') return false
|
||||
const range = value as Record<string, unknown>
|
||||
return isPosition(range.start) && isPosition(range.end)
|
||||
}
|
||||
|
||||
/** Structural position guard. */
|
||||
function isPosition(value: unknown): boolean {
|
||||
if (value === null || typeof value !== 'object') return false
|
||||
const position = value as Record<string, unknown>
|
||||
return typeof position.line === 'number' && typeof position.character === 'number'
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a navigation result (`Location`, `Location[]`, `LocationLink[]`, or `null`) to the seam's
|
||||
* locations. `Location` maps directly; `LocationLink` maps `targetUri` + `targetSelectionRange`.
|
||||
* @param payload - the raw `textDocument/definition|references|implementation` result.
|
||||
* @returns the normalized locations (empty for `null`/`[]`).
|
||||
* @throws Error when an element is neither a `Location` nor a `LocationLink`.
|
||||
*/
|
||||
export function normalizeLocations(payload: unknown): LspLocation[] {
|
||||
if (payload === null || payload === undefined) return []
|
||||
const elements = Array.isArray(payload) ? payload : [payload]
|
||||
const locations: LspLocation[] = []
|
||||
for (const element of elements) {
|
||||
if (element === null || typeof element !== 'object') {
|
||||
throw new Error('LSP navigation result contained a non-object entry')
|
||||
}
|
||||
const record = element as Record<string, unknown>
|
||||
if (isLocationLink(record)) {
|
||||
const link = record as unknown as WireLocationLink
|
||||
locations.push({ uri: link.targetUri, range: toRange(link.targetSelectionRange) })
|
||||
} else if (isLocation(record)) {
|
||||
const location = record as unknown as WireLocation
|
||||
locations.push({ uri: location.uri, range: toRange(location.range) })
|
||||
} else {
|
||||
throw new Error('LSP navigation result contained neither a Location nor a LocationLink')
|
||||
}
|
||||
}
|
||||
return locations
|
||||
}
|
||||
|
||||
/** Render one `MarkedString` (string form verbatim; object form as a language-tagged fenced block). */
|
||||
function renderMarkedString(value: WireMarkedString): string {
|
||||
if (typeof value === 'string') return value
|
||||
return `\`\`\`${value.language}\n${value.value}\n\`\`\``
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a `Hover` (or `null`) to the seam's hover. `MarkupContent` uses its `value`; a string
|
||||
* `MarkedString` is verbatim; a language-tagged `MarkedString` becomes a fenced code block; an array
|
||||
* joins its rendered parts with one blank line. `maxHoverChars` is NOT applied here — the tool caps.
|
||||
* @param payload - the raw `textDocument/hover` result.
|
||||
* @returns the normalized hover, or `null` when there is no content.
|
||||
* @throws Error when the payload is a non-null, non-object, or structurally invalid hover.
|
||||
*/
|
||||
export function normalizeHover(payload: unknown): LspHover | null {
|
||||
if (payload === null || payload === undefined) return null
|
||||
if (typeof payload !== 'object') throw new Error('LSP hover result was not an object')
|
||||
const hover = payload as unknown as WireHover
|
||||
const contents = renderHoverContents(hover.contents)
|
||||
if (contents === '') return null
|
||||
const range = hover.range
|
||||
return range !== undefined && isRange(range) ? { contents, range: toRange(range) } : { contents }
|
||||
}
|
||||
|
||||
/** Render the three `Hover.contents` encodings into one string (input is untrusted wire data). */
|
||||
function renderHoverContents(contents: unknown): string {
|
||||
if (contents === null || contents === undefined) {
|
||||
throw new Error('LSP hover result had no contents')
|
||||
}
|
||||
if (typeof contents === 'string') return contents
|
||||
if (Array.isArray(contents)) {
|
||||
return contents.map(renderMarkedString).join('\n\n')
|
||||
}
|
||||
if (typeof contents !== 'object') {
|
||||
throw new Error('LSP hover contents were not MarkupContent, MarkedString, or an array')
|
||||
}
|
||||
const record = contents as Record<string, unknown>
|
||||
if (record.kind === 'markdown' || record.kind === 'plaintext') {
|
||||
return typeof record.value === 'string' ? record.value : ''
|
||||
}
|
||||
if (typeof record.language === 'string' && typeof record.value === 'string') {
|
||||
return renderMarkedString({ language: record.language, value: record.value })
|
||||
}
|
||||
throw new Error('LSP hover contents were not MarkupContent, MarkedString, or an array')
|
||||
}
|
||||
Reference in New Issue
Block a user