oh-my-opencode 5.1.81 → 5.1.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/dist/cli/index.js +443 -276
  2. package/dist/cli-node/index.js +443 -276
  3. package/dist/hooks/claude-code-hooks/handlers/empty-hook-config.fixture.d.ts +1 -0
  4. package/dist/index.js +650 -431
  5. package/dist/shared/opencode-message-dir.d.ts +1 -1
  6. package/dist/skills/browser/references/owned-engine/README.md +4 -2
  7. package/dist/skills/browser/references/owned-engine/frames-and-humans.md +9 -3
  8. package/dist/skills/browser/runtime/omowright/index.js +8 -8
  9. package/dist/skills/browser/runtime/omowright/manifest.json +4 -4
  10. package/dist/skills/frontend/SKILL.md +4 -2
  11. package/dist/skills/frontend/references/perfection/state-and-flow.md +120 -0
  12. package/dist/skills/visual-qa/AGENTS.md +2 -1
  13. package/dist/skills/visual-qa/SKILL.md +43 -11
  14. package/dist/skills/visual-qa/references/behaviour-evidence.md +189 -0
  15. package/dist/tui.js +15 -15
  16. package/package.json +15 -15
  17. package/packages/lsp-core/src/lsp/client-key.ts +14 -0
  18. package/packages/lsp-core/src/lsp/client-startup.ts +139 -0
  19. package/packages/lsp-core/src/lsp/client-wrapper.ts +4 -4
  20. package/packages/lsp-core/src/lsp/config-loader.ts +15 -0
  21. package/packages/lsp-core/src/lsp/directory-diagnostics-group-scan.test.ts +388 -0
  22. package/packages/lsp-core/src/lsp/directory-diagnostics-mixed-typescript.test.ts +124 -0
  23. package/packages/lsp-core/src/lsp/directory-diagnostics.test.ts +4 -4
  24. package/packages/lsp-core/src/lsp/directory-diagnostics.ts +38 -41
  25. package/packages/lsp-core/src/lsp/directory-group-scan.ts +124 -0
  26. package/packages/lsp-core/src/lsp/directory-server-groups.ts +84 -0
  27. package/packages/lsp-core/src/lsp/manager-acquisition.test.ts +115 -0
  28. package/packages/lsp-core/src/lsp/manager-lifecycle.test.ts +9 -9
  29. package/packages/lsp-core/src/lsp/manager-max-clients.test.ts +41 -16
  30. package/packages/lsp-core/src/lsp/manager-reaping.test.ts +119 -0
  31. package/packages/lsp-core/src/lsp/manager-test-support.ts +108 -0
  32. package/packages/lsp-core/src/lsp/manager.ts +80 -249
  33. package/packages/lsp-core/src/lsp/native-typescript.ts +88 -0
  34. package/packages/lsp-core/src/lsp/server-installation.ts +15 -7
  35. package/packages/lsp-core/src/lsp/server-resolution-typescript-native.test.ts +327 -0
  36. package/packages/lsp-core/src/lsp/server-resolution.ts +28 -2
  37. package/packages/lsp-core/src/lsp/timer-provider.ts +17 -0
  38. package/packages/lsp-core/src/lsp/typescript-project-test-support.ts +52 -0
  39. package/packages/lsp-daemon/dist/cli.js +486 -310
  40. package/packages/lsp-daemon/dist/client.js +472 -296
  41. package/packages/lsp-daemon/dist/index.js +476 -300
  42. package/packages/lsp-tools-mcp/dist/cli.js +467 -291
  43. package/packages/lsp-tools-mcp/dist/lsp/manager.js +160 -193
  44. package/packages/lsp-tools-mcp/dist/mcp.js +467 -291
  45. package/packages/lsp-tools-mcp/dist/tools.js +467 -291
  46. package/packages/omo-codex/plugin/.codex-plugin/plugin.json +1 -1
  47. package/packages/omo-codex/plugin/components/bootstrap/hooks/hooks.json +1 -1
  48. package/packages/omo-codex/plugin/components/bootstrap/package.json +1 -1
  49. package/packages/omo-codex/plugin/components/comment-checker/hooks/hooks.json +1 -1
  50. package/packages/omo-codex/plugin/components/comment-checker/package.json +1 -1
  51. package/packages/omo-codex/plugin/components/git-bash/hooks/hooks.json +2 -2
  52. package/packages/omo-codex/plugin/components/git-bash/package.json +1 -1
  53. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/hooks/hooks.json +1 -1
  54. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/package.json +1 -1
  55. package/packages/omo-codex/plugin/components/lsp/dist/.omo-runtime-manifest.json +3 -3
  56. package/packages/omo-codex/plugin/components/lsp/dist/cli.js +478 -313
  57. package/packages/omo-codex/plugin/components/lsp/hooks/hooks.json +2 -2
  58. package/packages/omo-codex/plugin/components/lsp/package.json +1 -1
  59. package/packages/omo-codex/plugin/components/rules/hooks/hooks.json +4 -4
  60. package/packages/omo-codex/plugin/components/rules/package.json +1 -1
  61. package/packages/omo-codex/plugin/components/teammode/hooks/hooks.json +1 -1
  62. package/packages/omo-codex/plugin/components/teammode/package.json +1 -1
  63. package/packages/omo-codex/plugin/components/telemetry/hooks/hooks.json +1 -1
  64. package/packages/omo-codex/plugin/components/telemetry/package.json +1 -1
  65. package/packages/omo-codex/plugin/components/ultrawork/hooks/hooks.json +1 -1
  66. package/packages/omo-codex/plugin/components/ultrawork/package.json +1 -1
  67. package/packages/omo-codex/plugin/components/ulw-execute-continuation/hooks/hooks.json +1 -1
  68. package/packages/omo-codex/plugin/components/ulw-execute-continuation/package.json +1 -1
  69. package/packages/omo-codex/plugin/components/ulw-loop/hooks/hooks.json +5 -5
  70. package/packages/omo-codex/plugin/components/ulw-loop/package.json +1 -1
  71. package/packages/omo-codex/plugin/hooks/post-compact-resetting-git-bash-mcp-reminder.json +1 -1
  72. package/packages/omo-codex/plugin/hooks/post-compact-resetting-lsp-diagnostics-cache.json +1 -1
  73. package/packages/omo-codex/plugin/hooks/post-compact-resetting-project-rule-cache.json +1 -1
  74. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-comments.json +1 -1
  75. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-lsp-diagnostics.json +1 -1
  76. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-thread-title-hygiene.json +1 -1
  77. package/packages/omo-codex/plugin/hooks/post-tool-use-matching-project-rules.json +1 -1
  78. package/packages/omo-codex/plugin/hooks/post-tool-use-recording-spawn-admission.json +1 -1
  79. package/packages/omo-codex/plugin/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json +1 -1
  80. package/packages/omo-codex/plugin/hooks/pre-tool-use-guarding-ulw-loop-spawns.json +1 -1
  81. package/packages/omo-codex/plugin/hooks/pre-tool-use-recommending-git-bash-mcp.json +1 -1
  82. package/packages/omo-codex/plugin/hooks/session-start-checking-auto-update.json +1 -1
  83. package/packages/omo-codex/plugin/hooks/session-start-checking-bootstrap-provisioning.json +1 -1
  84. package/packages/omo-codex/plugin/hooks/session-start-loading-project-rules.json +1 -1
  85. package/packages/omo-codex/plugin/hooks/session-start-recording-session-telemetry.json +1 -1
  86. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-execute-continuation.json +1 -1
  87. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-loop-resume.json +1 -1
  88. package/packages/omo-codex/plugin/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json +1 -1
  89. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ultrawork-trigger.json +1 -1
  90. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ulw-loop-steering.json +1 -1
  91. package/packages/omo-codex/plugin/hooks/user-prompt-submit-loading-project-rules.json +1 -1
  92. package/packages/omo-codex/plugin/package-lock.json +12 -12
  93. package/packages/omo-codex/plugin/package.json +1 -1
  94. package/packages/omo-codex/plugin/skills/browser/references/owned-engine/README.md +4 -2
  95. package/packages/omo-codex/plugin/skills/browser/references/owned-engine/frames-and-humans.md +9 -3
  96. package/packages/omo-codex/plugin/skills/browser/runtime/omowright/index.js +8 -8
  97. package/packages/omo-codex/plugin/skills/browser/runtime/omowright/manifest.json +4 -4
  98. package/packages/omo-codex/plugin/skills/frontend/SKILL.md +4 -2
  99. package/packages/omo-codex/plugin/skills/frontend/references/perfection/state-and-flow.md +120 -0
  100. package/packages/omo-codex/plugin/skills/visual-qa/AGENTS.md +2 -1
  101. package/packages/omo-codex/plugin/skills/visual-qa/SKILL.md +43 -11
  102. package/packages/omo-codex/plugin/skills/visual-qa/references/behaviour-evidence.md +189 -0
  103. package/packages/omo-codex/scripts/install-dist/install-local.mjs +2 -2
  104. package/packages/shared-skills/skills/browser/references/owned-engine/README.md +4 -2
  105. package/packages/shared-skills/skills/browser/references/owned-engine/frames-and-humans.md +9 -3
  106. package/packages/shared-skills/skills/browser/runtime/omowright/index.js +8 -8
  107. package/packages/shared-skills/skills/browser/runtime/omowright/manifest.json +4 -4
  108. package/packages/shared-skills/skills/frontend/SKILL.md +4 -2
  109. package/packages/shared-skills/skills/frontend/references/perfection/state-and-flow.md +120 -0
  110. package/packages/shared-skills/skills/visual-qa/AGENTS.md +2 -1
  111. package/packages/shared-skills/skills/visual-qa/SKILL.md +43 -11
  112. package/packages/shared-skills/skills/visual-qa/references/behaviour-evidence.md +189 -0
@@ -0,0 +1,108 @@
1
+ import { LspClient } from "./client.js"
2
+ import { ControlledClock } from "./controlled-clock-test-support.js"
3
+ import { LspManager } from "./manager.js"
4
+ import type { ResolvedServer } from "./types.js"
5
+
6
+ export const SERVER: ResolvedServer = { id: "typescript", command: ["fake-ts-ls"], extensions: [".ts"], priority: 1 }
7
+ export const IDLE_TIMEOUT_MS = 1_000
8
+ export const INIT_TIMEOUT_MS = 5_000
9
+ export const REAPER_INTERVAL_MS = 100
10
+
11
+ export interface Gate {
12
+ readonly promise: Promise<void>
13
+ open(): void
14
+ }
15
+
16
+ function gate(): Gate {
17
+ let resolvePromise: (() => void) | undefined
18
+ const promise = new Promise<void>((resolve) => {
19
+ resolvePromise = resolve
20
+ })
21
+ return { promise, open: () => resolvePromise?.() }
22
+ }
23
+
24
+ /** A client whose start finishes when `started` opens and whose stop finishes when `stopped` opens. */
25
+ class GatedClient extends LspClient {
26
+ readonly started = gate()
27
+ readonly stopped = gate()
28
+ stopCount = 0
29
+ private alive = true
30
+
31
+ constructor(root: string, holdStart: boolean, holdStop: boolean, server: ResolvedServer = SERVER) {
32
+ super(root, server)
33
+ if (!holdStart) this.started.open()
34
+ if (!holdStop) this.stopped.open()
35
+ }
36
+
37
+ override async start(): Promise<void> {
38
+ await this.started.promise
39
+ }
40
+
41
+ override async initialize(): Promise<void> {}
42
+
43
+ override async stop(): Promise<void> {
44
+ this.stopCount += 1
45
+ await this.stopped.promise
46
+ this.alive = false
47
+ }
48
+
49
+ override isAlive(): boolean {
50
+ return this.alive
51
+ }
52
+
53
+ running(): boolean {
54
+ return this.alive && this.stopCount === 0
55
+ }
56
+ }
57
+
58
+ export interface GatedManagerOptions {
59
+ readonly maxResidentClients?: number
60
+ /** Whether the start of the n-th spawned client (0-based) waits for its gate. */
61
+ readonly holdStart?: (index: number) => boolean
62
+ readonly holdStops?: boolean
63
+ }
64
+
65
+ /** A real LspManager over gated fake clients, on a virtual clock that also drives its reaper. */
66
+ export function gatedManager(options: GatedManagerOptions = {}) {
67
+ const clock = new ControlledClock()
68
+ const clients: GatedClient[] = []
69
+ const manager = new LspManager({
70
+ maxResidentClients: options.maxResidentClients ?? 6,
71
+ idleTimeoutMs: IDLE_TIMEOUT_MS,
72
+ initTimeoutMs: INIT_TIMEOUT_MS,
73
+ reaperIntervalMs: REAPER_INTERVAL_MS,
74
+ now: clock.now,
75
+ timers: clock,
76
+ clientFactory: (root) => {
77
+ const client = new GatedClient(root, options.holdStart?.(clients.length) ?? false, options.holdStops ?? false)
78
+ clients.push(client)
79
+ return client
80
+ },
81
+ })
82
+ return { manager, clients, clock }
83
+ }
84
+
85
+ /** Per pooled key: root, references, counted waiters, still starting. */
86
+ export function pool(manager: LspManager) {
87
+ return manager
88
+ .getSnapshot()
89
+ .map((entry) => [entry.root, entry.refCount, entry.pendingWaiters, entry.isInitializing] as const)
90
+ }
91
+
92
+ /**
93
+ * Runs `action` after `turns` microtask turns. Sweeping `turns` lands the action at every step of a
94
+ * promise chain (here: a start finishing and its waiters resuming) without timers or sleeps.
95
+ */
96
+ export async function afterMicrotasks(turns: number, action: () => void): Promise<void> {
97
+ for (let turn = 0; turn < turns; turn += 1) await Promise.resolve()
98
+ action()
99
+ }
100
+
101
+ export const MICROTASK_SWEEP = Array.from({ length: 12 }, (_, turns) => turns)
102
+
103
+ export function settle<T>(promise: Promise<T>): Promise<{ readonly value?: T; readonly error?: unknown }> {
104
+ return promise.then(
105
+ (value) => ({ value }),
106
+ (error: unknown) => ({ error }),
107
+ )
108
+ }
@@ -1,5 +1,7 @@
1
1
  import { reportBestEffortCleanupError } from "./cleanup-errors.js"
2
2
  import { LspClient } from "./client.js"
3
+ import { type ClientIdentity, lspClientKey } from "./client-key.js"
4
+ import { awaitWithSignal, ClientStartups, type ManagedClient } from "./client-startup.js"
3
5
  import {
4
6
  CLIENT_RESPAWN_COOLDOWN_MS,
5
7
  CLIENT_RESPAWN_RETRY_LIMIT,
@@ -10,18 +12,9 @@ import {
10
12
  } from "./constants.js"
11
13
  import { LspClientRespawnBudgetExceededError } from "./errors.js"
12
14
  import { installProcessSignalCleanup } from "./process-signal-cleanup.js"
15
+ import { realTimerProvider, repeatEvery, type TimerProvider } from "./timer-provider.js"
13
16
  import type { ResolvedServer } from "./types.js"
14
17
 
15
- interface ManagedClient {
16
- client: LspClient
17
- refCount: number
18
- pendingWaiters: number
19
- lastUsedAt: number
20
- initPromise: Promise<void> | null
21
- isInitializing: boolean
22
- initializingSince: number | null
23
- }
24
-
25
18
  interface RespawnBudget {
26
19
  deadGenerations: number
27
20
  exhaustedAt: number | null
@@ -45,6 +38,8 @@ export interface LspManagerOptions {
45
38
  reaperIntervalMs?: number
46
39
  clientFactory?: (root: string, server: ResolvedServer) => LspClient
47
40
  now?: () => number
41
+ /** Schedules the reaper. */
42
+ timers?: TimerProvider
48
43
  }
49
44
 
50
45
  async function stopClientBestEffort(client: LspClient): Promise<void> {
@@ -55,79 +50,35 @@ async function stopClientBestEffort(client: LspClient): Promise<void> {
55
50
  }
56
51
  }
57
52
 
58
- function awaitWithSignal<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
59
- if (!signal) return promise
60
- return new Promise<T>((resolve, reject) => {
61
- let settled = false
62
- const onAbort = () => {
63
- if (settled) return
64
- settled = true
65
- reject(new DOMException("Aborted", "AbortError"))
66
- }
67
- if (signal.aborted) {
68
- onAbort()
69
- return
70
- }
71
- signal.addEventListener("abort", onAbort, { once: true })
72
- promise.then(
73
- (value) => {
74
- if (settled) return
75
- settled = true
76
- signal.removeEventListener("abort", onAbort)
77
- resolve(value)
78
- },
79
- (err) => {
80
- if (settled) return
81
- settled = true
82
- signal.removeEventListener("abort", onAbort)
83
- reject(err)
84
- },
85
- )
86
- })
87
- }
88
-
89
53
  export class LspManager {
90
54
  private readonly clients = new Map<string, ManagedClient>()
91
55
  /** In-flight stops per key; getClient awaits these instead of spawning a duplicate client. */
92
56
  private readonly pendingStops = new Map<string, Promise<void>>()
93
57
  private readonly respawnBudgets = new Map<string, RespawnBudget>()
94
- private reaperHandle: NodeJS.Timeout | null = null
58
+ private readonly stopReaper: () => void
95
59
  private signalDisposer: (() => void) | null = null
96
60
  private disposed = false
97
61
 
98
62
  private readonly idleTimeoutMs: number
99
63
  private readonly initTimeoutMs: number
100
64
  private readonly maxResidentClients: number
101
- private readonly reaperIntervalMs: number
102
65
  private readonly clientFactory: (root: string, server: ResolvedServer) => LspClient
103
66
  private readonly now: () => number
67
+ private readonly startups: ClientStartups
104
68
 
105
69
  constructor(options: LspManagerOptions = {}) {
106
70
  this.idleTimeoutMs = options.idleTimeoutMs ?? IDLE_TIMEOUT_MS
107
71
  this.initTimeoutMs = options.initTimeoutMs ?? INIT_TIMEOUT_MS
108
72
  this.maxResidentClients = options.maxResidentClients ?? MAX_RESIDENT_CLIENTS
109
- this.reaperIntervalMs = options.reaperIntervalMs ?? REAPER_INTERVAL_MS
110
73
  this.clientFactory = options.clientFactory ?? ((root, server) => new LspClient(root, server))
111
74
  this.now = options.now ?? (() => Date.now())
75
+ this.startups = new ClientStartups(this.now, (managed) => this.discard(managed))
112
76
 
113
- this.startReaper()
77
+ const reaperIntervalMs = options.reaperIntervalMs ?? REAPER_INTERVAL_MS
78
+ this.stopReaper = repeatEvery(options.timers ?? realTimerProvider, reaperIntervalMs, () => this.reapStale())
114
79
  this.signalDisposer = installProcessSignalCleanup(() => this.stopAll())
115
80
  }
116
81
 
117
- private startReaper(): void {
118
- if (this.reaperHandle) return
119
- this.reaperHandle = setInterval(() => {
120
- this.reapStale()
121
- }, this.reaperIntervalMs)
122
- if (typeof this.reaperHandle.unref === "function") {
123
- this.reaperHandle.unref()
124
- }
125
- }
126
-
127
- private getKey(root: string, serverId: string): string {
128
- return `${root}::${serverId}`
129
- }
130
-
131
82
  /**
132
83
  * Deletes-then-stops with a tombstone: the pending stop is recorded so a concurrent getClient
133
84
  * for the same key awaits it instead of spawning a duplicate client while the old one lingers
@@ -172,28 +123,21 @@ export class LspManager {
172
123
  budget.exhaustedAt = null
173
124
  }
174
125
 
126
+ private startupExpired(managed: ManagedClient, t: number): boolean {
127
+ return (
128
+ managed.isInitializing && managed.initializingSince !== null && t - managed.initializingSince > this.initTimeoutMs
129
+ )
130
+ }
131
+
175
132
  private reapStale(): void {
176
133
  const t = this.now()
177
- for (const [key, managed] of this.clients) {
178
- if (
179
- managed.isInitializing &&
180
- managed.initializingSince !== null &&
181
- t - managed.initializingSince > this.initTimeoutMs
182
- ) {
183
- this.clients.delete(key)
184
- void this.tombstoneStop(key, managed.client)
185
- continue
186
- }
187
-
188
- if (
134
+ for (const managed of [...this.clients.values()]) {
135
+ const idle =
189
136
  !managed.isInitializing &&
190
137
  managed.refCount === 0 &&
191
138
  managed.pendingWaiters === 0 &&
192
139
  t - managed.lastUsedAt > this.idleTimeoutMs
193
- ) {
194
- this.clients.delete(key)
195
- void this.tombstoneStop(key, managed.client)
196
- }
140
+ if (idle || this.startupExpired(managed, t)) this.discard(managed)
197
141
  }
198
142
  }
199
143
 
@@ -207,177 +151,100 @@ export class LspManager {
207
151
  while (this.clients.size >= this.maxResidentClients) {
208
152
  const victim = this.leastRecentlyUsedIdleClient()
209
153
  if (!victim) return
210
- this.clients.delete(victim.key)
211
- void this.tombstoneStop(victim.key, victim.managed.client)
154
+ this.discard(victim)
212
155
  }
213
156
  }
214
157
 
215
- private leastRecentlyUsedIdleClient(): { readonly key: string; readonly managed: ManagedClient } | null {
216
- let candidate: { readonly key: string; readonly managed: ManagedClient } | null = null
217
- for (const [key, managed] of this.clients) {
158
+ private leastRecentlyUsedIdleClient(): ManagedClient | null {
159
+ let candidate: ManagedClient | null = null
160
+ for (const managed of this.clients.values()) {
218
161
  if (managed.refCount > 0 || managed.pendingWaiters > 0 || managed.isInitializing) continue
219
- if (candidate === null || managed.lastUsedAt < candidate.managed.lastUsedAt) {
220
- candidate = { key, managed }
221
- }
162
+ if (candidate === null || managed.lastUsedAt < candidate.lastUsedAt) candidate = managed
222
163
  }
223
164
  return candidate
224
165
  }
225
166
 
226
- private async tryDeleteIfOrphaned(key: string, managed: ManagedClient): Promise<void> {
227
- if (
228
- managed.refCount === 0 &&
229
- managed.pendingWaiters === 0 &&
230
- !managed.isInitializing &&
231
- this.clients.get(key) === managed
232
- ) {
233
- this.clients.delete(key)
234
- await this.tombstoneStop(key, managed.client)
235
- }
167
+ /** Drops `managed` from the pool and stops it as a tracked tombstone, once; nothing here awaits the stop. */
168
+ private discard(managed: ManagedClient): void {
169
+ if (this.clients.get(managed.key) !== managed) return
170
+ this.clients.delete(managed.key)
171
+ void this.tombstoneStop(managed.key, managed.client)
236
172
  }
237
173
 
174
+ /** Every await here happens before the acquisition counts or while it counts as a waiter (client-startup.ts). */
238
175
  async getClient(root: string, server: ResolvedServer, signal?: AbortSignal): Promise<LspClient> {
239
- if (this.disposed) {
240
- throw new Error("LspManager has been disposed")
241
- }
242
- signal?.throwIfAborted()
243
-
244
- const key = this.getKey(root, server.id)
176
+ const key = lspClientKey(root, server)
245
177
  for (;;) {
246
- const pendingStop = this.pendingStops.get(key)
247
- if (pendingStop === undefined) break
248
- await awaitWithSignal(pendingStop, signal)
178
+ if (this.disposed) {
179
+ throw new Error("LspManager has been disposed")
180
+ }
249
181
  signal?.throwIfAborted()
250
- }
251
- if (this.disposed) {
252
- throw new Error("LspManager has been disposed")
253
- }
254
-
255
- let managed = this.clients.get(key)
256
-
257
- if (managed) {
258
- const t = this.now()
259
- if (
260
- managed.isInitializing &&
261
- managed.initializingSince !== null &&
262
- t - managed.initializingSince > this.initTimeoutMs
263
- ) {
264
- this.clients.delete(key)
265
- await this.tombstoneStop(key, managed.client)
266
- managed = undefined
182
+ const pendingStop = this.pendingStops.get(key)
183
+ if (pendingStop !== undefined) {
184
+ await awaitWithSignal(pendingStop, signal)
185
+ continue
186
+ }
187
+ let managed = this.clients.get(key)
188
+ if (managed !== undefined && this.startupExpired(managed, this.now())) {
189
+ this.discard(managed)
190
+ continue
191
+ }
192
+ if (managed === undefined) {
193
+ this.evictForAdmission()
194
+ this.ensureRespawnAllowed(key, root, server.id)
195
+ managed = this.startClient(key, root, server, true)
267
196
  }
268
- }
269
197
 
270
- if (managed) {
271
- if (managed.initPromise) {
272
- managed.pendingWaiters++
273
- try {
274
- await awaitWithSignal(managed.initPromise, signal)
275
- } catch (err) {
276
- managed.pendingWaiters--
277
- await this.tryDeleteIfOrphaned(key, managed)
278
- throw err
198
+ const { initPromise } = managed
199
+ if (initPromise !== null) {
200
+ await this.startups.wait(managed, initPromise, signal)
201
+ if (signal?.aborted) {
202
+ this.startups.detach(managed)
203
+ signal.throwIfAborted()
279
204
  }
280
205
  managed.pendingWaiters--
281
206
  }
282
-
283
- if (signal?.aborted) {
284
- await this.tryDeleteIfOrphaned(key, managed)
285
- signal.throwIfAborted()
286
- }
287
-
207
+ // No await from the waiter's uncounting above to the reference below.
208
+ if (this.clients.get(key) !== managed) continue
288
209
  if (!managed.client.isAlive()) {
289
210
  this.recordDeadGeneration(key)
290
- if (this.clients.get(key) === managed) {
291
- this.clients.delete(key)
292
- }
293
- await this.tombstoneStop(key, managed.client)
294
- return this.getClient(root, server, signal)
211
+ this.discard(managed)
212
+ continue
295
213
  }
296
-
297
214
  this.markHealthyGeneration(key)
298
215
  managed.refCount++
299
216
  managed.lastUsedAt = this.now()
300
217
  return managed.client
301
218
  }
219
+ }
302
220
 
303
- this.evictForAdmission()
304
- this.ensureRespawnAllowed(key, root, server.id)
305
-
221
+ private startClient(key: string, root: string, server: ResolvedServer, heldByWaiters: boolean): ManagedClient {
306
222
  const client = this.clientFactory(root, server)
307
- const initStartedAt = this.now()
308
- const initPromise = (async () => {
309
- await client.start()
310
- await client.initialize()
311
- })()
312
-
313
- const newManaged: ManagedClient = {
314
- client,
315
- refCount: 0,
316
- pendingWaiters: 1,
317
- lastUsedAt: initStartedAt,
318
- initPromise,
319
- isInitializing: true,
320
- initializingSince: initStartedAt,
321
- }
322
- this.clients.set(key, newManaged)
323
-
324
- try {
325
- await awaitWithSignal(initPromise, signal)
326
- } catch (err) {
327
- newManaged.pendingWaiters--
328
- if (this.clients.get(key) === newManaged) {
329
- this.clients.delete(key)
330
- }
331
- await this.tombstoneStop(key, client)
332
- throw err
333
- }
334
-
335
- newManaged.pendingWaiters--
336
- newManaged.isInitializing = false
337
- newManaged.initializingSince = null
338
- newManaged.initPromise = null
339
-
340
- if (signal?.aborted) {
341
- await this.tryDeleteIfOrphaned(key, newManaged)
342
- signal.throwIfAborted()
343
- }
344
-
345
- if (!client.isAlive()) {
346
- this.recordDeadGeneration(key)
347
- if (this.clients.get(key) === newManaged) {
348
- this.clients.delete(key)
349
- }
350
- await this.tombstoneStop(key, client)
351
- return this.getClient(root, server, signal)
352
- }
353
-
354
- this.markHealthyGeneration(key)
355
- newManaged.refCount++
356
- newManaged.lastUsedAt = this.now()
357
- return client
223
+ const managed = this.startups.begin({ key, root, serverId: server.id, client, heldByWaiters })
224
+ this.clients.set(key, managed)
225
+ return managed
358
226
  }
359
227
 
360
- releaseClient(root: string, serverId: string): void {
361
- const key = this.getKey(root, serverId)
362
- const managed = this.clients.get(key)
228
+ /** Gives back the reference on `client`; a client no longer pooled for the key has none left to give back. */
229
+ releaseClient(root: string, server: ClientIdentity, client?: LspClient): void {
230
+ const managed = this.clients.get(lspClientKey(root, server))
231
+ if (client !== undefined && managed?.client !== client) return
363
232
  if (managed && managed.refCount > 0) {
364
233
  managed.refCount--
365
234
  managed.lastUsedAt = this.now()
366
235
  }
367
236
  }
368
237
 
369
- invalidateClient(root: string, serverId: string, client?: LspClient): void {
370
- const key = this.getKey(root, serverId)
371
- const managed = this.clients.get(key)
238
+ invalidateClient(root: string, server: ClientIdentity, client?: LspClient): void {
239
+ const managed = this.clients.get(lspClientKey(root, server))
372
240
  if (!managed) return
373
241
  if (client && managed.client !== client) return
374
- this.clients.delete(key)
375
- void this.tombstoneStop(key, managed.client)
242
+ this.discard(managed)
376
243
  }
377
244
 
378
245
  warmupClient(root: string, server: ResolvedServer): void {
379
246
  if (this.disposed) return
380
- const key = this.getKey(root, server.id)
247
+ const key = lspClientKey(root, server)
381
248
  if (this.clients.has(key) || this.pendingStops.has(key)) return
382
249
 
383
250
  this.evictForAdmission()
@@ -386,53 +253,20 @@ export class LspManager {
386
253
  } catch {
387
254
  return
388
255
  }
389
-
390
- const client = this.clientFactory(root, server)
391
- const initStartedAt = this.now()
392
- const initPromise = (async () => {
393
- await client.start()
394
- await client.initialize()
395
- })()
396
-
397
- const managed: ManagedClient = {
398
- client,
399
- refCount: 0,
400
- pendingWaiters: 0,
401
- lastUsedAt: initStartedAt,
402
- initPromise,
403
- isInitializing: true,
404
- initializingSince: initStartedAt,
405
- }
406
- this.clients.set(key, managed)
407
-
408
- initPromise.then(
409
- () => {
410
- managed.isInitializing = false
411
- managed.initializingSince = null
412
- managed.initPromise = null
413
- managed.lastUsedAt = this.now()
414
- },
415
- () => {
416
- if (this.clients.get(key) === managed) {
417
- this.clients.delete(key)
418
- }
419
- void this.tombstoneStop(key, client)
420
- },
421
- )
256
+ this.startClient(key, root, server, false)
422
257
  }
423
258
 
424
- isServerInitializing(root: string, serverId: string): boolean {
425
- const managed = this.clients.get(this.getKey(root, serverId))
259
+ isServerInitializing(root: string, server: ClientIdentity): boolean {
260
+ const managed = this.clients.get(lspClientKey(root, server))
426
261
  return managed?.isInitializing ?? false
427
262
  }
428
263
 
429
264
  getSnapshot(): ClientSnapshot[] {
430
265
  const snapshots: ClientSnapshot[] = []
431
- for (const [key, managed] of this.clients) {
432
- const [root, serverId] = key.split("::") as [string, string]
266
+ for (const managed of this.clients.values()) {
433
267
  snapshots.push({
434
- root,
435
- serverId,
268
+ root: managed.root,
269
+ serverId: managed.serverId,
436
270
  refCount: managed.refCount,
437
271
  pendingWaiters: managed.pendingWaiters,
438
272
  lastUsedAt: managed.lastUsedAt,
@@ -444,8 +278,8 @@ export class LspManager {
444
278
  return snapshots
445
279
  }
446
280
 
447
- hasClient(root: string, serverId: string): boolean {
448
- return this.clients.has(this.getKey(root, serverId))
281
+ hasClient(root: string, server: ClientIdentity): boolean {
282
+ return this.clients.has(lspClientKey(root, server))
449
283
  }
450
284
 
451
285
  clientCount(): number {
@@ -455,10 +289,7 @@ export class LspManager {
455
289
  async stopAll(): Promise<void> {
456
290
  this.disposed = true
457
291
 
458
- if (this.reaperHandle) {
459
- clearInterval(this.reaperHandle)
460
- this.reaperHandle = null
461
- }
292
+ this.stopReaper()
462
293
 
463
294
  if (this.signalDisposer) {
464
295
  this.signalDisposer()
@@ -0,0 +1,88 @@
1
+ import { existsSync, realpathSync, statSync } from "node:fs"
2
+ import { dirname, join, resolve } from "node:path"
3
+
4
+ import { canonicalizeExistingOrNearestAncestor, isPathInside } from "../request-context.js"
5
+ import type { ServerWithSource } from "./config-loader.js"
6
+ import {
7
+ executableSuffixes,
8
+ NODE_LOCAL_BIN_DIR,
9
+ NODE_PROJECT_MARKERS,
10
+ probe,
11
+ probeWithSuffixes,
12
+ } from "./server-installation.js"
13
+
14
+ /**
15
+ * Where the search for a project's TypeScript 7 compiler starts, as a real path. A target is judged by
16
+ * its real location: one that resolves (through any symlink) outside the real session directory keeps
17
+ * the session directory, so a link inside the session never lends it another project's compiler. A
18
+ * symlinked session root still works because both sides are canonicalized. Any error falls back to
19
+ * the session directory as given.
20
+ */
21
+ export function nativeTypescriptSearchDirectory(targetPath: string | undefined, workingDirectory: string): string {
22
+ try {
23
+ const session = realpathSync(workingDirectory)
24
+ if (targetPath === undefined) return session
25
+ const target = canonicalizeExistingOrNearestAncestor(resolve(workingDirectory, targetPath))
26
+ if (!isPathInside(session, target)) return session
27
+ return statSync(target, { throwIfNoEntry: false })?.isDirectory() === true ? target : dirname(target)
28
+ } catch {
29
+ return workingDirectory
30
+ }
31
+ }
32
+
33
+ /**
34
+ * TypeScript 7 serves LSP itself (`tsc --lsp --stdio`) and no longer ships the `lib/tsserver.js` that
35
+ * typescript-language-server wraps. Only the project's own `node_modules/.bin/tsc` decides, so a global
36
+ * compiler never changes the server. A command a config file named is never replaced, even one equal
37
+ * to the default. `searchDirectory` must be a real path (see nativeTypescriptSearchDirectory).
38
+ */
39
+ export function nativeTypescriptCommand(server: ServerWithSource, searchDirectory: string): string[] | null {
40
+ if (server.id !== "typescript" || !server.inheritsBuiltinCommand) return null
41
+ const found = findProjectTsc(searchDirectory)
42
+ if (found === null) return null
43
+ const speaksLsp = !existsSync(join(found.packageDir, "lib", "tsserver.js"))
44
+ return speaksLsp ? [found.tsc, "--lsp", "--stdio"] : null
45
+ }
46
+
47
+ /**
48
+ * Walks up from `searchDirectory` to the repository root (`.git`) and returns the nearest eligible
49
+ * `tsc`: one in the `node_modules/.bin` of a directory with a Node project marker, where that bin
50
+ * directory is real (see isRealDirectory) and a `typescript` package sits beside it. Unlike the generic
51
+ * local-bin walk, no `bin` or virtualenv directory is probed, so a `bin/tsc` of another ecosystem never
52
+ * shadows a hoisted compiler, and an ineligible candidate (such as a stale `tsc` shim left without its
53
+ * package) is passed over instead of ending the walk. Any installed TypeScript ends it, so a package on
54
+ * TypeScript 5 keeps typescript-language-server even below a hoisted TypeScript 7.
55
+ */
56
+ function findProjectTsc(searchDirectory: string): { readonly tsc: string; readonly packageDir: string } | null {
57
+ const suffixes = executableSuffixes(process.platform, undefined)
58
+ let current = searchDirectory
59
+ for (;;) {
60
+ if (NODE_PROJECT_MARKERS.some((marker) => probe(join(current, marker)))) {
61
+ const binDir = join(current, NODE_LOCAL_BIN_DIR)
62
+ const tsc = probeWithSuffixes(binDir, "tsc", suffixes)
63
+ const packageDir = join(binDir, "..", "typescript")
64
+ if (tsc !== null && isRealDirectory(binDir) && existsSync(join(packageDir, "package.json"))) {
65
+ return { tsc, packageDir }
66
+ }
67
+ }
68
+ if (probe(join(current, ".git"))) return null
69
+ const parent = dirname(current)
70
+ if (parent === current) return null
71
+ current = parent
72
+ }
73
+ }
74
+
75
+ /**
76
+ * npm, yarn, bun (hoisted and isolated) and pnpm (including its global virtual store) link the entries
77
+ * inside `node_modules`: `.bin/tsc` is a symlink or a shell shim, and `node_modules/typescript` may link
78
+ * into `.bun`, `.pnpm` or a store. None of them links `node_modules` or `node_modules/.bin` itself. So
79
+ * the bin directory the walk found must be a real directory at that place; when either level is a
80
+ * symlink, the compiler belongs to whatever the link points at and that candidate is not used.
81
+ */
82
+ function isRealDirectory(directory: string): boolean {
83
+ try {
84
+ return realpathSync(directory) === directory
85
+ } catch {
86
+ return false
87
+ }
88
+ }