1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
|
/**
* Manager — lazy-spawn one client per (serverID, root); dedup concurrent
* spawns; track a broken set (no retry storm); status(cwd); shutdownAll().
*/
import { join } from "node:path";
import {
type ClientDeps,
type FileWatcher,
type FsAccess,
LanguageServerClient,
type SpawnProcess,
} from "./client.js";
import { configFingerprint, type ResolvedServer, resolveServers } from "./config.js";
import { findRoot } from "./root.js";
import type { LspServerState, LspServerStatus } from "./types.js";
export type Logger = {
readonly info: (msg: string, attrs?: Record<string, string | number | boolean | null>) => void;
readonly warn: (msg: string, attrs?: Record<string, string | number | boolean | null>) => void;
readonly error: (msg: string, attrs?: Record<string, unknown>) => void;
};
export interface ManagerDeps {
readonly spawn: SpawnProcess;
readonly fileWatcher: FileWatcher;
readonly fs: FsAccess;
readonly logger?: Logger | undefined;
/**
* Injected clock (epoch-ms) for bounded-backoff bookkeeping. Defaults to
* `Date.now`; injected in tests so backoff is deterministic.
*/
readonly now?: (() => number) | undefined;
}
type ClientEntry = {
readonly client: LanguageServerClient;
readonly server: ResolvedServer;
readonly promise: Promise<void>;
};
/**
* A failed server's recovery bookkeeping. `configFingerprint` is the resolved
* config captured at failure time: a config edit produces a different
* fingerprint (a discrete event → cannot storm) and the next `status()` clears
* the entry and re-spawns. `brokenAt` seeds a bounded backoff so transient
* failures (e.g. a not-yet-installed binary) also self-heal without a storm.
* `error` is the enriched failure reason surfaced while the server stays
* broken.
*/
type BrokenEntry = {
readonly configFingerprint: string;
readonly brokenAt: number;
readonly error: string;
};
/** Bounded backoff before a transient (config-unchanged) failure is retried. */
const BACKOFF_MS = 30_000;
export class LspManager {
private clients = new Map<string, ClientEntry>();
private broken = new Map<string, BrokenEntry>();
private spawning = new Map<string, Promise<void>>();
private shadowWarned = new Set<string>();
private readonly deps: ManagerDeps;
private readonly now: () => number;
constructor(deps: ManagerDeps) {
this.deps = deps;
this.now = deps.now ?? Date.now;
}
async status(cwd: string): Promise<readonly LspServerStatus[]> {
// Config is resolved PER cwd: a different conversation cwd (e.g. a Roblox
// project) gets its own .dispatch/lsp.json or opencode.json, not a global one.
const dispatchLspJson = await this.readOrNull(join(cwd, ".dispatch", "lsp.json"));
const opencodeJson = await this.readOrNull(join(cwd, "opencode.json"));
const { servers, shadowed } = await resolveServers({
cwd,
dispatchLspJson,
opencodeJson,
exists: this.deps.fs.exists,
});
// A present `.dispatch/lsp.json` silently shadows `opencode.json`'s lsp
// key — warn once per cwd so a broken shadow names itself (an agent
// running inside dispatch can only see `status()`, not the journal).
if (shadowed && !this.shadowWarned.has(cwd)) {
this.shadowWarned.add(cwd);
this.deps.logger?.warn(
`.dispatch/lsp.json is shadowing the opencode.json "lsp" config — its servers take precedence and the opencode.json lsp entry is ignored`,
{ cwd },
);
}
const results: LspServerStatus[] = [];
for (const server of servers) {
const root = await findRoot(cwd, cwd, server.rootMarkers, this.deps.fs.exists);
const key = `${server.id}:${root}`;
const brokenEntry = this.broken.get(key);
if (brokenEntry) {
// Recovery, storm-safe: a config change is a discrete event, so it
// cannot loop. Transient failures (config unchanged) are retried
// only after a bounded backoff — never in a tight loop.
const configChanged = configFingerprint(server) !== brokenEntry.configFingerprint;
const backoffElapsed = this.now() - brokenEntry.brokenAt >= BACKOFF_MS;
if (configChanged || backoffElapsed) {
this.broken.delete(key);
// Discard the stale client entry (and any leaked process) from
// the failed spawn so status() re-spawns fresh.
const stale = this.clients.get(key);
if (stale) {
this.clients.delete(key);
stale.client.shutdown();
}
// fall through to (re)spawn
} else {
results.push({
id: server.id,
name: server.name,
root,
extensions: server.extensions,
state: "error",
error: brokenEntry.error,
configSource: server.configSource,
});
continue;
}
}
const existing = this.clients.get(key);
if (existing) {
const state = existing.client.getState();
const stateError = existing.client.getStateError();
// A client that died or corrupted AFTER connecting flipped its
// own state to "error" (client.ts handleExit/markBroken). Spawn
// succeeded so there's no broken entry yet — seed one so the
// bounded-backoff path above re-spawns it, instead of reporting
// error forever (and so getDiagnostics' "connected" filter skips
// it, avoiding a per-edit hang on the corpse).
if (state === "error" && !this.broken.has(key)) {
this.broken.set(key, {
configFingerprint: configFingerprint(server),
brokenAt: this.now(),
error: enrichError(server, stateError ?? "server unavailable"),
});
}
const status: LspServerStatus = {
id: server.id,
name: server.name,
root,
extensions: server.extensions,
state: mapState(state),
configSource: server.configSource,
};
if (stateError !== undefined) {
(status as { error?: string }).error = enrichError(server, stateError);
}
results.push(status);
continue;
}
try {
await this.spawnClient(server, root, key);
const entry = this.clients.get(key);
if (entry) {
const state = entry.client.getState();
const stateError = entry.client.getStateError();
const status: LspServerStatus = {
id: server.id,
name: server.name,
root,
extensions: server.extensions,
state: mapState(state),
configSource: server.configSource,
};
if (stateError !== undefined) {
(status as { error?: string }).error = enrichError(server, stateError);
}
results.push(status);
}
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
this.broken.set(key, {
configFingerprint: configFingerprint(server),
brokenAt: this.now(),
error: enrichError(server, message),
});
results.push({
id: server.id,
name: server.name,
root,
extensions: server.extensions,
state: "error",
error: enrichError(server, message),
configSource: server.configSource,
});
}
}
return results;
}
getClient(serverId: string, root: string): LanguageServerClient | undefined {
const key = `${serverId}:${root}`;
return this.clients.get(key)?.client;
}
/** Read a config file's contents, or null if it is absent/unreadable. */
private async readOrNull(path: string): Promise<string | null> {
if (!(await this.deps.fs.exists(path))) return null;
try {
return await this.deps.fs.readText(path);
} catch {
return null;
}
}
private async spawnClient(server: ResolvedServer, root: string, key: string): Promise<void> {
const existingSpawn = this.spawning.get(key);
if (existingSpawn) return existingSpawn;
const spawnPromise = this.doSpawn(server, root, key);
this.spawning.set(key, spawnPromise);
try {
await spawnPromise;
} finally {
this.spawning.delete(key);
}
}
private async doSpawn(server: ResolvedServer, root: string, key: string): Promise<void> {
const clientDeps: ClientDeps = {
spawn: this.deps.spawn,
fileWatcher: this.deps.fileWatcher,
fs: this.deps.fs,
command: server.command,
root,
serverId: server.id,
};
if (server.env) {
(clientDeps as { env?: Readonly<Record<string, string>> }).env = server.env;
}
if (server.initialization) {
(clientDeps as { initialization?: Readonly<Record<string, unknown>> }).initialization =
server.initialization;
}
const client = new LanguageServerClient(clientDeps);
const entry: ClientEntry = {
client,
server,
promise: client.start(),
};
this.clients.set(key, entry);
await entry.promise;
if (client.getState() === "error") {
const message = client.getStateError() ?? "unknown";
this.broken.set(key, {
configFingerprint: configFingerprint(server),
brokenAt: this.now(),
error: enrichError(server, message),
});
this.deps.logger?.warn("LSP server failed to start", {
serverId: server.id,
root,
configSource: server.configSource ?? "unknown",
error: message,
});
} else {
this.deps.logger?.info("LSP server connected", {
serverId: server.id,
root,
});
}
}
shutdownAll(): void {
for (const [key, entry] of this.clients) {
entry.client.shutdown();
this.deps.logger?.info("LSP server shutdown", { key });
}
this.clients.clear();
this.broken.clear();
this.spawning.clear();
this.shadowWarned.clear();
}
}
function mapState(state: LspServerState): LspServerState {
return state;
}
/**
* Prefix a failure reason with the server id + its config source, so a broken
* config file names itself in the `status()` response (e.g.
* `ruby-lsp [from .dispatch/lsp.json]: spawn failed`).
*/
function enrichError(server: ResolvedServer, message: string): string {
const source = server.configSource ?? "unknown";
return `${server.id} [from ${source}]: ${message}`;
}
|