@pal-code/core 0.0.20 → 0.0.22
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.
- package/package.json +1 -1
- package/src/agent/scope.ts +12 -1
- package/src/agent/turn.ts +17 -4
- package/src/app-config.ts +19 -1
- package/src/config.ts +2 -1
- package/src/diagnostics-checks.ts +19 -0
- package/src/index.ts +16 -0
- package/src/lsp/client.ts +361 -0
- package/src/lsp/diagnostics-map.ts +138 -0
- package/src/lsp/fixtures/fake-lsp-server.ts +110 -0
- package/src/lsp/framing.ts +93 -0
- package/src/lsp/servers.ts +125 -0
- package/src/tools/definitions.ts +57 -39
- package/src/tools/edit-match.ts +201 -0
- package/src/tools/executor.ts +517 -92
- package/src/tools/json-schema.ts +341 -0
- package/src/tools/lazy.ts +191 -0
package/package.json
CHANGED
package/src/agent/scope.ts
CHANGED
|
@@ -12,11 +12,18 @@
|
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
14
|
import {getTodos, restoreTodos, type Todo} from './todos.js';
|
|
15
|
-
import {getShellCwd, setShellCwd} from '../tools/executor.js';
|
|
15
|
+
import {getShellCwd, getShellRoot, setShellCwd, setShellRoot} from '../tools/executor.js';
|
|
16
16
|
|
|
17
17
|
export interface RunScope {
|
|
18
18
|
todos: Todo[];
|
|
19
19
|
shellCwd: string;
|
|
20
|
+
/**
|
|
21
|
+
* The containment root in force. Restored alongside the cwd so a delegated
|
|
22
|
+
* child can never leave the parent's sandbox wider — or narrower — than it
|
|
23
|
+
* found it. A child that ran `setShellRoot(undefined)` would otherwise hand the
|
|
24
|
+
* parent an unconfined shell for the rest of its turn.
|
|
25
|
+
*/
|
|
26
|
+
shellRoot: string | undefined;
|
|
20
27
|
}
|
|
21
28
|
|
|
22
29
|
/** Capture the state a nested run must not leak into its parent. */
|
|
@@ -24,11 +31,15 @@ export function captureRunScope(): RunScope {
|
|
|
24
31
|
return {
|
|
25
32
|
todos: getTodos().map((t) => ({...t})),
|
|
26
33
|
shellCwd: getShellCwd(),
|
|
34
|
+
shellRoot: getShellRoot(),
|
|
27
35
|
};
|
|
28
36
|
}
|
|
29
37
|
|
|
30
38
|
/** Restore a scope captured by `captureRunScope`. Safe to call in a `finally`. */
|
|
31
39
|
export function restoreRunScope(scope: RunScope): void {
|
|
32
40
|
restoreTodos(scope.todos);
|
|
41
|
+
// Root first: `setShellCwd` is independent, but restoring the root clears or
|
|
42
|
+
// re-pins the boundary the cwd is then checked against.
|
|
43
|
+
setShellRoot(scope.shellRoot);
|
|
33
44
|
setShellCwd(scope.shellCwd);
|
|
34
45
|
}
|
package/src/agent/turn.ts
CHANGED
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
import type {ToolDef} from '../tools/definitions.js';
|
|
24
24
|
import {executeTool, registerExtensionHandlers} from '../tools/executor.js';
|
|
25
25
|
import type {ToolResult} from '../tools/executor.js';
|
|
26
|
+
import {projectTools} from '../tools/lazy.js';
|
|
26
27
|
import {clearFileRolesCache} from './file-roles.js';
|
|
27
28
|
import {runWithFallback, shortModel} from './fallback.js';
|
|
28
29
|
import {buildRolesPrompt, defaultPrimaryName, listPrimaries, resolvePrimary} from './roles.js';
|
|
@@ -252,13 +253,25 @@ function extensionPromptsFor(primary: {
|
|
|
252
253
|
return prompts.join('\n\n');
|
|
253
254
|
}
|
|
254
255
|
|
|
255
|
-
/**
|
|
256
|
+
/**
|
|
257
|
+
* Tools the turn may use, narrowed to the primary agent's set when it declares
|
|
258
|
+
* one, and projected to what the model should actually be told about.
|
|
259
|
+
*
|
|
260
|
+
* `getWireTools` is the lazy-schema projection: with `PAL_LAZY_TOOLS` unset it
|
|
261
|
+
* returns exactly `getAllTools()`, so this stays byte-for-byte the previous
|
|
262
|
+
* behaviour. Narrowing happens first so a primary that excludes a tool never
|
|
263
|
+
* pays for its stub either.
|
|
264
|
+
*/
|
|
256
265
|
export function toolsForPrimary(primaryName?: string): ToolDef[] {
|
|
257
266
|
const all = getAllTools();
|
|
258
267
|
const primary = primaryName ? resolvePrimary(primaryName) : null;
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
268
|
+
const narrowed = !primary?.tools
|
|
269
|
+
? all
|
|
270
|
+
: (() => {
|
|
271
|
+
const allowed = new Set(primary.tools);
|
|
272
|
+
return all.filter((t) => allowed.has(t.function.name));
|
|
273
|
+
})();
|
|
274
|
+
return projectTools(narrowed);
|
|
262
275
|
}
|
|
263
276
|
|
|
264
277
|
/**
|
package/src/app-config.ts
CHANGED
|
@@ -24,6 +24,23 @@ export interface Config {
|
|
|
24
24
|
modelRotation: boolean;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/**
|
|
28
|
+
* Platform-specific shell guidance.
|
|
29
|
+
*
|
|
30
|
+
* This MUST be derived from the host, not hardcoded: the previous version
|
|
31
|
+
* hardcoded the Windows text, so a Linux/macOS user was told their shell was
|
|
32
|
+
* cmd.exe and that `ls`/`cat` did not exist. Interactive sessions never
|
|
33
|
+
* noticed because the model worked around it; a headless task run on Windows
|
|
34
|
+
* burned its whole round budget retrying POSIX commands that the prompt had
|
|
35
|
+
* not warned it about.
|
|
36
|
+
*/
|
|
37
|
+
function shellGuidance(): string {
|
|
38
|
+
if (process.platform === 'win32') {
|
|
39
|
+
return 'Windows shell: the bash tool ALREADY runs inside cmd.exe. Write native commands directly (`dir`, `type`, `findstr`, `where`) and NEVER prefix them with `cmd /c`. Unix commands (`ls`, `cat`, `grep`, `head`, `rm`) do not exist here. Keep commands to a single line without `&&` chains when possible. Be concise; show code only when asked.';
|
|
40
|
+
}
|
|
41
|
+
return 'POSIX shell: the bash tool ALREADY runs inside /bin/sh. Write commands directly (`ls`, `cat`, `grep`, `find`, `rg`) and NEVER prefix them with `bash -c` or `sh -c`. Keep commands to a single line; prefer `&&` over separate calls only when the steps are genuinely dependent. Be concise; show code only when asked.';
|
|
42
|
+
}
|
|
43
|
+
|
|
27
44
|
const DEFAULT_SYSTEM_PROMPT = [
|
|
28
45
|
"pal — a terminal coding agent working in the user's project.",
|
|
29
46
|
'TOOLS: Never guess about files — read them. Batch independent tool calls in one response.',
|
|
@@ -32,7 +49,8 @@ const DEFAULT_SYSTEM_PROMPT = [
|
|
|
32
49
|
"DON'T LOOP: Never repeat a tool call with identical arguments — it cannot give a different result. If something fails twice, change approach or report the blocker.",
|
|
33
50
|
'STOP: Once every todo item is done and the request is satisfied, stop calling tools and reply. Do not re-read files you already have.',
|
|
34
51
|
'DELEGATE: For broad multi-file exploration, use `delegate` to keep your own context small.',
|
|
35
|
-
'
|
|
52
|
+
'EXPLORE: Before editing, locate the exact file and symbol. One `glob` or `grep_search`, then `read` the file — do not spend rounds listing directories.',
|
|
53
|
+
shellGuidance(),
|
|
36
54
|
].join('\n');
|
|
37
55
|
|
|
38
56
|
const EFFORTS = ['low', 'medium', 'high'] as const;
|
package/src/config.ts
CHANGED
|
@@ -10,6 +10,7 @@ import {readFileSync, statSync} from 'fs';
|
|
|
10
10
|
import {resolve, relative, isAbsolute, basename} from 'path';
|
|
11
11
|
import {minimatch} from 'minimatch';
|
|
12
12
|
import {TOOL_NAME_ALIASES} from './tools/definitions.js';
|
|
13
|
+
import type {ChildProviderConfig} from './agent/run.js';
|
|
13
14
|
|
|
14
15
|
/** Config file schema. */
|
|
15
16
|
export interface ToolConfig {
|
|
@@ -41,7 +42,7 @@ export interface ToolConfig {
|
|
|
41
42
|
name: string,
|
|
42
43
|
args: string,
|
|
43
44
|
id: string,
|
|
44
|
-
providerConfig:
|
|
45
|
+
providerConfig: ChildProviderConfig,
|
|
45
46
|
signal?: AbortSignal,
|
|
46
47
|
) => Promise<{content: string; error?: boolean}>;
|
|
47
48
|
};
|
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
|
|
10
10
|
import {extname, relative, resolve} from 'path';
|
|
11
11
|
import {log} from './logger.js';
|
|
12
|
+
import {runLspChecks} from './lsp/client.js';
|
|
13
|
+
import {isLspEnabled, serverForBatch} from './lsp/servers.js';
|
|
12
14
|
import type {DiagnosticError} from './diagnostics.js';
|
|
13
15
|
|
|
14
16
|
const BIOME_EXTS = new Set([
|
|
@@ -38,6 +40,23 @@ export async function runChecks(
|
|
|
38
40
|
// tests exercise the flow through an injected checker instead.
|
|
39
41
|
if (process.env.NODE_ENV === 'test') return null;
|
|
40
42
|
|
|
43
|
+
// LSP first, but only opt-in and only when a server actually claims these
|
|
44
|
+
// files. A `null` answer means "no opinion" and falls through to biome/tsc,
|
|
45
|
+
// so enabling PAL_LSP can never make diagnostics *worse* than they are today —
|
|
46
|
+
// it can only add coverage for files biome and tsc do not understand.
|
|
47
|
+
if (isLspEnabled()) {
|
|
48
|
+
const batch = serverForBatch(files);
|
|
49
|
+
if (batch !== null) {
|
|
50
|
+
const lsp = await runLspChecks({
|
|
51
|
+
spec: batch.spec,
|
|
52
|
+
files: batch.covered,
|
|
53
|
+
cwd: ctx.cwd,
|
|
54
|
+
budgetMs: ctx.budgetMs,
|
|
55
|
+
});
|
|
56
|
+
if (lsp !== null) return lsp;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
41
60
|
const biomeFiles = files.filter((f) => BIOME_EXTS.has(extname(f).toLowerCase()));
|
|
42
61
|
const needsTsc = files.some((f) => TS_EXTS.has(extname(f).toLowerCase()));
|
|
43
62
|
if (biomeFiles.length === 0 && !needsTsc) return null;
|
package/src/index.ts
CHANGED
|
@@ -139,16 +139,32 @@ export {
|
|
|
139
139
|
CORE_TOOLS,
|
|
140
140
|
TOOL_NAME_ALIASES,
|
|
141
141
|
getAllTools,
|
|
142
|
+
getWireTools,
|
|
142
143
|
registerExtensionTools,
|
|
143
144
|
validateRequiredArgs,
|
|
144
145
|
clearExtensionTools,
|
|
145
146
|
getExtensionTools,
|
|
146
147
|
} from './tools/definitions.js';
|
|
147
148
|
export type {ToolDef} from './tools/definitions.js';
|
|
149
|
+
export {
|
|
150
|
+
isLazyToolsEnabled,
|
|
151
|
+
isDeferred,
|
|
152
|
+
deferrableTools,
|
|
153
|
+
projectTools,
|
|
154
|
+
expandTools,
|
|
155
|
+
resetExpanded,
|
|
156
|
+
expandedTools,
|
|
157
|
+
DEFAULT_DEFERRABLE,
|
|
158
|
+
LAZY_ENV,
|
|
159
|
+
} from './tools/lazy.js';
|
|
148
160
|
export {
|
|
149
161
|
executeTool,
|
|
150
162
|
registerExtensionHandlers,
|
|
151
163
|
resetShell,
|
|
164
|
+
getShellCwd,
|
|
165
|
+
setShellCwd,
|
|
166
|
+
getShellRoot,
|
|
167
|
+
setShellRoot,
|
|
152
168
|
isMutatingToolset,
|
|
153
169
|
registerMutatingTools,
|
|
154
170
|
registerHistoryProvider,
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal stdio LSP client (roadmap #2).
|
|
3
|
+
*
|
|
4
|
+
* Scope check: this is not a general LSP implementation. It does exactly one
|
|
5
|
+
* job — start a server, open the files that were just edited, collect the
|
|
6
|
+
* diagnostics the server publishes for them, shut down. No completion, no
|
|
7
|
+
* hover, no workspace symbols, no multi-workspace, no `workspace/configuration`
|
|
8
|
+
* fan-out. Every one of those would be another few hundred lines of state that
|
|
9
|
+
* nothing in pal calls.
|
|
10
|
+
*
|
|
11
|
+
* The hard requirement is the one from `diagnostics.ts`: `noteEditedFile()` is
|
|
12
|
+
* fire-and-forget and the tool handler must never wait longer than its budget.
|
|
13
|
+
* So every await here races a deadline, and the client resolves to `null` on
|
|
14
|
+
* *any* trouble. A missing binary, a server that never initialises, a server
|
|
15
|
+
* that publishes nothing — all the same outcome, and the caller falls back to
|
|
16
|
+
* biome/tsc.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import {readFileSync} from 'fs';
|
|
20
|
+
import {log} from '../logger.js';
|
|
21
|
+
import {FrameDecoder, encodeMessage} from './framing.js';
|
|
22
|
+
import {type LspDiagnostic, mapDiagnostics} from './diagnostics-map.js';
|
|
23
|
+
import {fallbackWorkspaceConfig} from './diagnostics-map.js';
|
|
24
|
+
import type {ServerSpec} from './servers.js';
|
|
25
|
+
import type {DiagnosticError} from '../diagnostics.js';
|
|
26
|
+
|
|
27
|
+
/** JSON-RPC ids for requests this client sends. Server ids are echoed back. */
|
|
28
|
+
const INIT_REQUEST = 1;
|
|
29
|
+
const SHUTDOWN_REQUEST = 999_999;
|
|
30
|
+
|
|
31
|
+
interface PendingRequest {
|
|
32
|
+
resolve: (value: unknown) => void;
|
|
33
|
+
reject: (err: Error) => void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface LspRunOptions {
|
|
37
|
+
spec: ServerSpec;
|
|
38
|
+
files: readonly string[];
|
|
39
|
+
cwd: string;
|
|
40
|
+
budgetMs: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Start a server, collect diagnostics for `files`, stop it.
|
|
45
|
+
*
|
|
46
|
+
* Returns `null` for "no opinion" — the signal that the caller should fall back.
|
|
47
|
+
* Returns `[]` only when a server actually answered and said the files are clean.
|
|
48
|
+
*/
|
|
49
|
+
export async function runLspChecks(opts: LspRunOptions): Promise<DiagnosticError[] | null> {
|
|
50
|
+
const deadline = Date.now() + opts.budgetMs;
|
|
51
|
+
const remaining = () => Math.max(0, deadline - Date.now());
|
|
52
|
+
|
|
53
|
+
const client = new LspClient(opts);
|
|
54
|
+
try {
|
|
55
|
+
const started = await client.start(remaining());
|
|
56
|
+
if (!started) return null;
|
|
57
|
+
|
|
58
|
+
const published = await client.collect(remaining());
|
|
59
|
+
if (published === null) return null;
|
|
60
|
+
|
|
61
|
+
const mapped = mapDiagnostics(published, opts.files, opts.cwd);
|
|
62
|
+
return mapped.map((m) => ({path: m.path, line: m.line, message: m.message}));
|
|
63
|
+
} catch (err) {
|
|
64
|
+
// Never reach the model, never break the edit.
|
|
65
|
+
log('lsp-run-failed', {
|
|
66
|
+
command: opts.spec.command,
|
|
67
|
+
message: err instanceof Error ? err.message : String(err),
|
|
68
|
+
});
|
|
69
|
+
return null;
|
|
70
|
+
} finally {
|
|
71
|
+
await client.stop();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
class LspClient {
|
|
76
|
+
private proc: ReturnType<typeof Bun.spawn> | null = null;
|
|
77
|
+
private readonly decoder = new FrameDecoder();
|
|
78
|
+
private readonly pending = new Map<number, PendingRequest>();
|
|
79
|
+
/** Latest `publishDiagnostics` payload per URI — servers resend whole files. */
|
|
80
|
+
private readonly published = new Map<string, LspDiagnostic[]>();
|
|
81
|
+
private nextId = 10;
|
|
82
|
+
private exited = false;
|
|
83
|
+
private sawDiagnostics = false;
|
|
84
|
+
private lastPublishAt = 0;
|
|
85
|
+
|
|
86
|
+
constructor(private readonly opts: LspRunOptions) {}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Spawn + `initialize` + `initialized` + `didOpen` for every file.
|
|
90
|
+
*
|
|
91
|
+
* Returns false — not throws — when the server cannot be brought up, because
|
|
92
|
+
* "binary vanished between `isAvailable` and here" is a race, not a bug.
|
|
93
|
+
*/
|
|
94
|
+
async start(budgetMs: number): Promise<boolean> {
|
|
95
|
+
const bin = this.resolveBinary();
|
|
96
|
+
if (bin === null) return false;
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
this.proc = Bun.spawn([bin, ...this.opts.spec.args], {
|
|
100
|
+
stdin: 'pipe',
|
|
101
|
+
stdout: 'pipe',
|
|
102
|
+
stderr: 'pipe',
|
|
103
|
+
cwd: this.opts.cwd,
|
|
104
|
+
});
|
|
105
|
+
} catch (err) {
|
|
106
|
+
log('lsp-spawn-failed', {
|
|
107
|
+
command: this.opts.spec.command,
|
|
108
|
+
message: err instanceof Error ? err.message : String(err),
|
|
109
|
+
});
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
this.pumpStdout();
|
|
114
|
+
// stderr is drained but ignored: servers log chat to it constantly, and
|
|
115
|
+
// letting the pipe fill would block the server mid-initialise.
|
|
116
|
+
this.drainStderr();
|
|
117
|
+
this.watchExit();
|
|
118
|
+
|
|
119
|
+
const initResult = await this.request(
|
|
120
|
+
'initialize',
|
|
121
|
+
{
|
|
122
|
+
processId: process.pid,
|
|
123
|
+
rootUri: null,
|
|
124
|
+
capabilities: {
|
|
125
|
+
// Only diagnostics are wanted; declaring less keeps servers from
|
|
126
|
+
// sending things this client would ignore anyway.
|
|
127
|
+
textDocument: {synchronization: {didSave: false, dynamicRegistration: false}},
|
|
128
|
+
workspace: {configuration: false, workspaceFolders: false},
|
|
129
|
+
},
|
|
130
|
+
...(fallbackWorkspaceConfig(this.opts.spec.languageId) ?? {}),
|
|
131
|
+
},
|
|
132
|
+
budgetMs,
|
|
133
|
+
);
|
|
134
|
+
if (initResult === null) return false;
|
|
135
|
+
|
|
136
|
+
this.send({jsonrpc: '2.0', method: 'initialized', params: {}});
|
|
137
|
+
for (const file of this.opts.files) this.didOpen(file);
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Wait for the server to publish diagnostics, bounded by the budget.
|
|
143
|
+
*
|
|
144
|
+
* Servers are asynchronous and give no "I'm done analysing" signal in the base
|
|
145
|
+
* protocol. Two ways out: a publish arrives, then a short quiet period passes
|
|
146
|
+
* with no further publish (a server that reports 40 errors sends them as
|
|
147
|
+
* several publishes, and stopping at the first would under-report); or a
|
|
148
|
+
* `didOpen`-driven publish arrives and the server goes quiet. If nothing at all
|
|
149
|
+
* arrives, resolve `null` rather than pretending the files are clean — an empty
|
|
150
|
+
* result would tell the model "your edit is fine", which is exactly the
|
|
151
|
+
* false-negative that makes auto-diagnostics untrustworthy.
|
|
152
|
+
*/
|
|
153
|
+
async collect(budgetMs: number): Promise<Map<string, LspDiagnostic[]> | null> {
|
|
154
|
+
const hardDeadline = Date.now() + budgetMs;
|
|
155
|
+
|
|
156
|
+
while (Date.now() < hardDeadline) {
|
|
157
|
+
if (this.exited && !this.sawDiagnostics) return null;
|
|
158
|
+
if (this.sawDiagnostics && this.quietFor(150)) return this.published;
|
|
159
|
+
await sleep(25);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return this.sawDiagnostics ? this.published : null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
private quietFor(ms: number): boolean {
|
|
166
|
+
return Date.now() - this.lastPublishAt >= ms;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** `shutdown` → `exit` → SIGKILL if it lingers. Never throws. */
|
|
170
|
+
async stop(): Promise<void> {
|
|
171
|
+
const proc = this.proc;
|
|
172
|
+
if (proc === null) return;
|
|
173
|
+
this.proc = null;
|
|
174
|
+
|
|
175
|
+
try {
|
|
176
|
+
if (!this.exited) {
|
|
177
|
+
this.send({jsonrpc: '2.0', id: SHUTDOWN_REQUEST, method: 'shutdown', params: null});
|
|
178
|
+
this.send({jsonrpc: '2.0', method: 'exit', params: null});
|
|
179
|
+
}
|
|
180
|
+
// Give it a moment to exit on its own; a wedged server must not outlive
|
|
181
|
+
// the edit, so SIGKILL is the fallback rather than an indefinite wait.
|
|
182
|
+
const timer = setTimeout(() => {
|
|
183
|
+
try {
|
|
184
|
+
proc.kill(9);
|
|
185
|
+
} catch {
|
|
186
|
+
/* already gone */
|
|
187
|
+
}
|
|
188
|
+
}, 200);
|
|
189
|
+
try {
|
|
190
|
+
await Promise.race([proc.exited, sleep(300)]);
|
|
191
|
+
} finally {
|
|
192
|
+
clearTimeout(timer);
|
|
193
|
+
}
|
|
194
|
+
try {
|
|
195
|
+
proc.kill(9);
|
|
196
|
+
} catch {
|
|
197
|
+
/* already gone */
|
|
198
|
+
}
|
|
199
|
+
} catch {
|
|
200
|
+
/* shutting down is best-effort */
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ---- internals -----------------------------------------------------------
|
|
205
|
+
|
|
206
|
+
private resolveBinary(): string | null {
|
|
207
|
+
try {
|
|
208
|
+
return Bun.which(this.opts.spec.command) ?? null;
|
|
209
|
+
} catch {
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
private request(method: string, params: unknown, budgetMs: number): Promise<unknown | null> {
|
|
215
|
+
const id = this.nextId++;
|
|
216
|
+
const promise = new Promise<unknown>((resolve, reject) => {
|
|
217
|
+
this.pending.set(id, {resolve, reject});
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
this.send({jsonrpc: '2.0', id, method, params});
|
|
221
|
+
|
|
222
|
+
return Promise.race([
|
|
223
|
+
promise.then((v) => v).catch(() => null),
|
|
224
|
+
sleep(budgetMs).then(() => null),
|
|
225
|
+
]);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
private send(payload: unknown): void {
|
|
229
|
+
const proc = this.proc;
|
|
230
|
+
if (proc === null || this.exited) return;
|
|
231
|
+
try {
|
|
232
|
+
const stdin = proc.stdin as {write?: (chunk: string) => void} | undefined;
|
|
233
|
+
stdin?.write?.(encodeMessage(payload));
|
|
234
|
+
} catch {
|
|
235
|
+
/* stdin closed — the exit handler will surface it */
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
private didOpen(file: string): void {
|
|
240
|
+
const abs = file;
|
|
241
|
+
let text: string;
|
|
242
|
+
try {
|
|
243
|
+
text = readFileSync(abs, 'utf8');
|
|
244
|
+
} catch {
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
this.send({
|
|
248
|
+
jsonrpc: '2.0',
|
|
249
|
+
method: 'textDocument/didOpen',
|
|
250
|
+
params: {
|
|
251
|
+
textDocument: {
|
|
252
|
+
uri: pathToUri(abs),
|
|
253
|
+
languageId: this.opts.spec.languageId,
|
|
254
|
+
version: 1,
|
|
255
|
+
text,
|
|
256
|
+
},
|
|
257
|
+
},
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
private pumpStdout(): void {
|
|
262
|
+
const proc = this.proc;
|
|
263
|
+
const stdout = proc?.stdout as ReadableStream<Uint8Array> | undefined;
|
|
264
|
+
if (!stdout) return;
|
|
265
|
+
|
|
266
|
+
void (async () => {
|
|
267
|
+
const reader = stdout.getReader();
|
|
268
|
+
try {
|
|
269
|
+
for (;;) {
|
|
270
|
+
const {done, value} = await reader.read();
|
|
271
|
+
if (done) return;
|
|
272
|
+
if (!value) continue;
|
|
273
|
+
for (const frame of this.decoder.push(value)) {
|
|
274
|
+
if (frame.parseError) {
|
|
275
|
+
log('lsp-bad-frame', {error: frame.parseError});
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
this.handle(frame.body);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
} catch {
|
|
282
|
+
/* stream torn down with the process */
|
|
283
|
+
}
|
|
284
|
+
})();
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
private drainStderr(): void {
|
|
288
|
+
const stderr = this.proc?.stderr as ReadableStream<Uint8Array> | undefined;
|
|
289
|
+
if (!stderr) return;
|
|
290
|
+
void (async () => {
|
|
291
|
+
try {
|
|
292
|
+
const reader = stderr.getReader();
|
|
293
|
+
for (;;) {
|
|
294
|
+
const {done} = await reader.read();
|
|
295
|
+
if (done) return;
|
|
296
|
+
}
|
|
297
|
+
} catch {
|
|
298
|
+
/* ignored on purpose */
|
|
299
|
+
}
|
|
300
|
+
})();
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
private watchExit(): void {
|
|
304
|
+
const proc = this.proc;
|
|
305
|
+
if (!proc) return;
|
|
306
|
+
void Promise.resolve(proc.exited).then(() => {
|
|
307
|
+
this.exited = true;
|
|
308
|
+
for (const [, pending] of this.pending) pending.reject(new Error('lsp exited'));
|
|
309
|
+
this.pending.clear();
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
private handle(body: unknown): void {
|
|
314
|
+
if (typeof body !== 'object' || body === null) return;
|
|
315
|
+
const msg = body as {
|
|
316
|
+
id?: number;
|
|
317
|
+
method?: string;
|
|
318
|
+
result?: unknown;
|
|
319
|
+
params?: {uri?: string; diagnostics?: LspDiagnostic[]};
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
// Response to one of our requests.
|
|
323
|
+
if (typeof msg.id === 'number' && msg.method === undefined) {
|
|
324
|
+
const pending = this.pending.get(msg.id);
|
|
325
|
+
if (pending) {
|
|
326
|
+
this.pending.delete(msg.id);
|
|
327
|
+
pending.resolve(msg.result);
|
|
328
|
+
}
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
if (msg.method === 'textDocument/publishDiagnostics' && msg.params?.uri) {
|
|
333
|
+
this.published.set(msg.params.uri, msg.params.diagnostics ?? []);
|
|
334
|
+
this.lastPublishAt = Date.now();
|
|
335
|
+
this.sawDiagnostics = true;
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Server → client requests. Answering `null`/`null` keeps every server we
|
|
340
|
+
// target happy without implementing any of them; silence would stall it.
|
|
341
|
+
if (typeof msg.id === 'number' && msg.method !== undefined) {
|
|
342
|
+
if (msg.method === 'workspace/configuration') {
|
|
343
|
+
const items = (msg.params as unknown as {items?: unknown[]})?.items ?? [];
|
|
344
|
+
this.send({jsonrpc: '2.0', id: msg.id, result: items.map(() => null)});
|
|
345
|
+
} else {
|
|
346
|
+
this.send({jsonrpc: '2.0', id: msg.id, result: null});
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** `C:\x\y.ts` → `file:///C:/x/y.ts`, POSIX → `file:///x/y.ts`. */
|
|
353
|
+
export function pathToUri(abs: string): string {
|
|
354
|
+
const slashed = abs.replace(/\\/g, '/');
|
|
355
|
+
const prefixed = slashed.startsWith('/') ? slashed : `/${slashed}`;
|
|
356
|
+
return `file://${encodeURI(prefixed).replace(/#/g, '%23').replace(/\?/g, '%3F')}`;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function sleep(ms: number): Promise<boolean> {
|
|
360
|
+
return new Promise((resolve) => setTimeout(() => resolve(true), Math.max(0, ms)));
|
|
361
|
+
}
|