@weave-os/router 0.2.14
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/LICENSE +90 -0
- package/README.md +172 -0
- package/bin.js +68 -0
- package/cc-statusline.sh +951 -0
- package/codex-skills/disable-routing/SKILL.md +22 -0
- package/codex-skills/fm/SKILL.md +15 -0
- package/codex-skills/fm/scripts/emit.sh +8 -0
- package/codex-skills/force-model/SKILL.md +15 -0
- package/codex-skills/force-model/scripts/emit.sh +9 -0
- package/codex-skills/rf/SKILL.md +15 -0
- package/codex-skills/rf/scripts/emit.sh +7 -0
- package/codex-skills/router-feedback/SKILL.md +15 -0
- package/codex-skills/router-feedback/scripts/emit.sh +9 -0
- package/codex-skills/router-models/SKILL.md +51 -0
- package/codex-skills/router-off/SKILL.md +22 -0
- package/codex-skills/router-on/SKILL.md +22 -0
- package/codex-skills/router-status/SKILL.md +19 -0
- package/codex-skills/ufm/SKILL.md +14 -0
- package/codex-skills/ufm/scripts/emit.sh +3 -0
- package/codex-skills/unforce-model/SKILL.md +14 -0
- package/codex-skills/unforce-model/scripts/emit.sh +4 -0
- package/codex-status.sh +378 -0
- package/commands/beta.md +5 -0
- package/commands/fm.md +6 -0
- package/commands/force-model.md +6 -0
- package/commands/models.md +46 -0
- package/commands/rf.md +6 -0
- package/commands/router-feedback.md +6 -0
- package/commands/router-models.md +46 -0
- package/commands/router-off.md +10 -0
- package/commands/router-on.md +10 -0
- package/commands/router-session.md +15 -0
- package/commands/router-status.md +10 -0
- package/commands/ufm.md +5 -0
- package/commands/unforce-model.md +5 -0
- package/directives.tsv +13 -0
- package/install.sh +5092 -0
- package/opencode-weave/README.md +78 -0
- package/opencode-weave/package.json +18 -0
- package/opencode-weave/src/index.ts +655 -0
- package/package.json +79 -0
- package/pi-router/README.md +123 -0
- package/pi-router/package.json +25 -0
- package/pi-router/skills/install-lsps/SKILL.md +75 -0
- package/pi-router/skills/lsp-guide/SKILL.md +63 -0
- package/pi-router/src/beta.ts +21 -0
- package/pi-router/src/compaction.ts +188 -0
- package/pi-router/src/config.ts +293 -0
- package/pi-router/src/context-window.ts +12 -0
- package/pi-router/src/dispatch.ts +377 -0
- package/pi-router/src/force-model.ts +126 -0
- package/pi-router/src/index.ts +62 -0
- package/pi-router/src/lsp-broker.ts +255 -0
- package/pi-router/src/lsp-client.ts +435 -0
- package/pi-router/src/lsp-format.ts +230 -0
- package/pi-router/src/lsp-install.ts +215 -0
- package/pi-router/src/lsp-protocol.ts +128 -0
- package/pi-router/src/lsp-servers.ts +361 -0
- package/pi-router/src/lsp.ts +529 -0
- package/pi-router/src/metadata.ts +32 -0
- package/pi-router/src/pricing.generated.ts +91 -0
- package/pi-router/src/provider.ts +64 -0
- package/pi-router/src/routed-model.ts +182 -0
- package/pi-router/src/safety.ts +66 -0
- package/pi-router/src/savings.ts +191 -0
- package/pi-router/src/ui.ts +91 -0
- package/pi-router/src/wooly.ts +408 -0
- package/registry.sh +102 -0
- package/uninstall.sh +788 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pi consumes slash commands locally, so expose the router's force-model
|
|
3
|
+
* directives as extension commands and forward one canonical user turn.
|
|
4
|
+
*
|
|
5
|
+
* The router remains authoritative for aliases, validation, canonical model
|
|
6
|
+
* ids, and pin persistence. UI state is reconstructed from command/response
|
|
7
|
+
* pairs on the reachable Pi branch; this is necessary because Pi records the
|
|
8
|
+
* selected model handle on assistant messages rather than the response model.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type {
|
|
12
|
+
ExtensionAPI,
|
|
13
|
+
ExtensionCommandContext,
|
|
14
|
+
SessionEntry,
|
|
15
|
+
} from "@mariozechner/pi-coding-agent";
|
|
16
|
+
|
|
17
|
+
export type ForceModelTransition =
|
|
18
|
+
| { kind: "applied"; model: string }
|
|
19
|
+
| { kind: "cleared" }
|
|
20
|
+
| { kind: "noop" };
|
|
21
|
+
|
|
22
|
+
type ForceModelDirective = "force" | "clear";
|
|
23
|
+
|
|
24
|
+
function messageText(message: unknown): string | undefined {
|
|
25
|
+
if (!message || typeof message !== "object" || !("content" in message)) return undefined;
|
|
26
|
+
const content = message.content;
|
|
27
|
+
if (typeof content === "string") return content;
|
|
28
|
+
if (!Array.isArray(content)) return undefined;
|
|
29
|
+
return content
|
|
30
|
+
.filter(
|
|
31
|
+
(block): block is { type: "text"; text: string } =>
|
|
32
|
+
Boolean(
|
|
33
|
+
block &&
|
|
34
|
+
typeof block === "object" &&
|
|
35
|
+
"type" in block &&
|
|
36
|
+
block.type === "text" &&
|
|
37
|
+
"text" in block &&
|
|
38
|
+
typeof block.text === "string",
|
|
39
|
+
),
|
|
40
|
+
)
|
|
41
|
+
.map((block) => block.text)
|
|
42
|
+
.join("\n");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function parseForceModelDirective(text: string): ForceModelDirective | undefined {
|
|
46
|
+
const command = text.trim();
|
|
47
|
+
if (/^\/(?:force-model|fm)\s+\S+/i.test(command)) return "force";
|
|
48
|
+
if (/^\/(?:unforce-model|ufm)$/i.test(command)) return "clear";
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function parseForceModelAcknowledgement(text: string): ForceModelTransition | undefined {
|
|
53
|
+
const applied = /force-model applied:\s+([^\s()]+)/i.exec(text);
|
|
54
|
+
if (applied) return { kind: "applied", model: applied[1] };
|
|
55
|
+
if (/force-model cleared/i.test(text)) return { kind: "cleared" };
|
|
56
|
+
if (/is(?:n't| not) a recognized model/i.test(text)) return { kind: "noop" };
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function isSyntheticPinClear(text: string): boolean {
|
|
61
|
+
return /^(?:✦ \*\*Weave Router\*\* →|Weave Router:)\s+(?:Tool-call|Repetition|No-progress) loop detected\b[\s\S]*\bclearing the session pin\b/i.test(
|
|
62
|
+
text.trim(),
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Reconstruct the effective router pin on the currently reachable branch. */
|
|
67
|
+
export function forcedModelFromBranch(entries: readonly SessionEntry[]): string | undefined {
|
|
68
|
+
let forcedModel: string | undefined;
|
|
69
|
+
let pendingDirective: ForceModelDirective | undefined;
|
|
70
|
+
|
|
71
|
+
for (const entry of entries) {
|
|
72
|
+
if (entry.type !== "message") continue;
|
|
73
|
+
if (entry.message.role === "user") {
|
|
74
|
+
pendingDirective = parseForceModelDirective(messageText(entry.message) ?? "");
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (entry.message.role !== "assistant") continue;
|
|
78
|
+
|
|
79
|
+
const text = messageText(entry.message) ?? "";
|
|
80
|
+
if (isSyntheticPinClear(text)) {
|
|
81
|
+
forcedModel = undefined;
|
|
82
|
+
pendingDirective = undefined;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (!pendingDirective) continue;
|
|
86
|
+
|
|
87
|
+
const transition = parseForceModelAcknowledgement(text);
|
|
88
|
+
if (transition?.kind === "applied" && pendingDirective === "force") forcedModel = transition.model;
|
|
89
|
+
else if (transition?.kind === "cleared" && pendingDirective === "clear") forcedModel = undefined;
|
|
90
|
+
// Rejected force-model commands intentionally retain the previous pin.
|
|
91
|
+
pendingDirective = undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return forcedModel;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function sendRouterCommand(pi: ExtensionAPI, command: string, ctx: ExtensionCommandContext): void {
|
|
98
|
+
pi.sendUserMessage(command, ctx.isIdle() ? undefined : { deliverAs: "followUp" });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function registerForceModelCommands(pi: ExtensionAPI): void {
|
|
102
|
+
const forceModel = async (args: string, ctx: ExtensionCommandContext): Promise<void> => {
|
|
103
|
+
const modelAndPrompt = args.trim();
|
|
104
|
+
if (!modelAndPrompt) {
|
|
105
|
+
ctx.ui.notify("Usage: /fm <model-id>", "warning");
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
sendRouterCommand(pi, `/force-model ${modelAndPrompt}`, ctx);
|
|
109
|
+
};
|
|
110
|
+
const clearForceModel = async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {
|
|
111
|
+
sendRouterCommand(pi, "/unforce-model", ctx);
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
for (const name of ["fm", "force-model"]) {
|
|
115
|
+
pi.registerCommand(name, {
|
|
116
|
+
description: "Pin this session to a specific model via the Weave Router",
|
|
117
|
+
handler: forceModel,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
for (const name of ["ufm", "unforce-model"]) {
|
|
121
|
+
pi.registerCommand(name, {
|
|
122
|
+
description: "Clear this session's forced Weave Router model",
|
|
123
|
+
handler: clearForceModel,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @weave-os/router — route the pi coding agent through the Weave Router.
|
|
3
|
+
*
|
|
4
|
+
* Wiring (all on the existing router surface — no router source change beyond
|
|
5
|
+
* the installer):
|
|
6
|
+
* - provider: register `weave` with per-process knob headers (quality on
|
|
7
|
+
* the main loop, speed/cheap in subagents).
|
|
8
|
+
* - metadata: stamp body.metadata.user_id for sticky sessions + subagent
|
|
9
|
+
* detection.
|
|
10
|
+
* - Loom UI: branded header, Wooly animation, actual route, and saved $.
|
|
11
|
+
* - safety: block catastrophic bash (unless WEAVE_NO_SAFETY=1).
|
|
12
|
+
* - compaction: protect long tool loops, then compact routed context.
|
|
13
|
+
* - dispatch: parallel, context-isolated subagents — top-level process
|
|
14
|
+
* only (no grandchildren).
|
|
15
|
+
* - lsp: code intelligence (definition/references/hover/symbols/
|
|
16
|
+
* diagnostics) over lazily spawned language servers, shared
|
|
17
|
+
* with subagents through a parent-side broker socket.
|
|
18
|
+
*
|
|
19
|
+
* The same module loads in dispatched children via `-e <self>`; WEAVE_PI_SUBAGENT
|
|
20
|
+
* flips the provider knobs and suppresses the dispatch tool so fan-out doesn't recurse.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { fileURLToPath } from "node:url";
|
|
24
|
+
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
|
|
25
|
+
import { registerBetaCommand } from "./beta.js";
|
|
26
|
+
import { isSubagent } from "./config.js";
|
|
27
|
+
import { registerCompaction } from "./compaction.js";
|
|
28
|
+
import { registerDispatch } from "./dispatch.js";
|
|
29
|
+
import { registerForceModelCommands } from "./force-model.js";
|
|
30
|
+
import { registerLsp } from "./lsp.js";
|
|
31
|
+
import { registerMetadata } from "./metadata.js";
|
|
32
|
+
import { registerRoutedModel } from "./routed-model.js";
|
|
33
|
+
import { registerSafety } from "./safety.js";
|
|
34
|
+
import { registerWeave } from "./provider.js";
|
|
35
|
+
|
|
36
|
+
const SELF_PATH = fileURLToPath(import.meta.url);
|
|
37
|
+
|
|
38
|
+
export default function (pi: ExtensionAPI): void {
|
|
39
|
+
// Register at load so the provider is available for `--list-models` and
|
|
40
|
+
// print mode (dispatched children), and again on session_start so the right
|
|
41
|
+
// knob headers survive `/reload` and new/resumed sessions.
|
|
42
|
+
registerWeave(pi);
|
|
43
|
+
pi.on("session_start", () => registerWeave(pi));
|
|
44
|
+
|
|
45
|
+
registerMetadata(pi);
|
|
46
|
+
registerBetaCommand(pi);
|
|
47
|
+
registerForceModelCommands(pi);
|
|
48
|
+
registerRoutedModel(pi);
|
|
49
|
+
registerCompaction(pi);
|
|
50
|
+
|
|
51
|
+
if (process.env.WEAVE_NO_SAFETY !== "1") registerSafety(pi);
|
|
52
|
+
|
|
53
|
+
// registerLsp picks its own role: the main process gets the pool-backed tool
|
|
54
|
+
// and returns the broker provider below; a child gets the broker-backed tool
|
|
55
|
+
// only when dispatch actually handed it a socket.
|
|
56
|
+
const lspBroker = process.env.WEAVE_PI_NO_LSP === "1" ? undefined : registerLsp(pi);
|
|
57
|
+
|
|
58
|
+
// Only the top-level process fans out. Children (WEAVE_PI_SUBAGENT=1) load
|
|
59
|
+
// this same extension but get no dispatch tool, so subagents can't spawn
|
|
60
|
+
// grandchildren.
|
|
61
|
+
if (!isSubagent()) registerDispatch(pi, SELF_PATH, lspBroker);
|
|
62
|
+
}
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subagent access to the parent's language servers.
|
|
3
|
+
*
|
|
4
|
+
* Dispatch children are the heaviest potential LSP users and the shortest-lived
|
|
5
|
+
* processes, so letting each spawn its own gopls would pay the indexing cost N
|
|
6
|
+
* times over and then throw the warm index away. Instead the parent exposes its
|
|
7
|
+
* pool over a local socket and children forward queries to it. The socket
|
|
8
|
+
* carries the same Content-Length framing as LSP stdio.
|
|
9
|
+
*
|
|
10
|
+
* The broker takes the orchestration core as a function, so it never reaches
|
|
11
|
+
* into the pool itself and is testable against a fake runner.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { randomBytes, timingSafeEqual } from "node:crypto";
|
|
15
|
+
import * as fs from "node:fs";
|
|
16
|
+
import * as net from "node:net";
|
|
17
|
+
import * as os from "node:os";
|
|
18
|
+
import * as path from "node:path";
|
|
19
|
+
import { createFrameParser, encodeFrame, type JsonRpcMessage, type LspOperationParams } from "./lsp-protocol.js";
|
|
20
|
+
|
|
21
|
+
const HELLO = "broker/hello";
|
|
22
|
+
const EXECUTE = "lsp/execute";
|
|
23
|
+
const CANCEL = "$/cancel";
|
|
24
|
+
const CONNECTION_LOST = "LSP broker connection lost";
|
|
25
|
+
|
|
26
|
+
export type LspRunner = (params: LspOperationParams, cwd: string, signal?: AbortSignal) => Promise<string>;
|
|
27
|
+
|
|
28
|
+
export interface LspBrokerHandle {
|
|
29
|
+
socketPath: string;
|
|
30
|
+
token: string;
|
|
31
|
+
close(): Promise<void>;
|
|
32
|
+
/** Synchronous socket removal for `process.on("exit")`, which cannot await `close()`. */
|
|
33
|
+
removeSocket(): void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface BrokerDeps {
|
|
37
|
+
makeSocketPath?(): { socketPath: string; cleanup(): void };
|
|
38
|
+
makeToken?(): string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function tokensMatch(expected: string, received: unknown): boolean {
|
|
42
|
+
if (typeof received !== "string" || received.length !== expected.length) return false;
|
|
43
|
+
return timingSafeEqual(Buffer.from(expected), Buffer.from(received));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function defaultSocketPath(): { socketPath: string; cleanup(): void } {
|
|
47
|
+
if (process.platform === "win32") {
|
|
48
|
+
// Named pipes live in the kernel namespace: nothing to create or unlink.
|
|
49
|
+
return { socketPath: `\\\\.\\pipe\\weave-pi-lsp-${process.pid}-${randomBytes(6).toString("hex")}`, cleanup: () => undefined };
|
|
50
|
+
}
|
|
51
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "weave-pi-lsp-"));
|
|
52
|
+
fs.chmodSync(dir, 0o700);
|
|
53
|
+
const socketPath = path.join(dir, "lsp.sock");
|
|
54
|
+
return {
|
|
55
|
+
socketPath,
|
|
56
|
+
cleanup: () => {
|
|
57
|
+
try {
|
|
58
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
59
|
+
} catch {
|
|
60
|
+
/* best effort */
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Listen for child connections. Started on demand (right before a fan-out), so
|
|
68
|
+
* a session that never dispatches never opens a socket.
|
|
69
|
+
*/
|
|
70
|
+
export async function startLspBroker(runner: LspRunner, deps: BrokerDeps = {}): Promise<LspBrokerHandle> {
|
|
71
|
+
const token = (deps.makeToken ?? (() => randomBytes(32).toString("hex")))();
|
|
72
|
+
const { socketPath, cleanup } = (deps.makeSocketPath ?? defaultSocketPath)();
|
|
73
|
+
const connections = new Set<net.Socket>();
|
|
74
|
+
|
|
75
|
+
const server = net.createServer((socket) => {
|
|
76
|
+
connections.add(socket);
|
|
77
|
+
socket.on("close", () => connections.delete(socket));
|
|
78
|
+
socket.on("error", () => socket.destroy());
|
|
79
|
+
|
|
80
|
+
let authenticated = false;
|
|
81
|
+
const inflight = new Map<number, AbortController>();
|
|
82
|
+
const reply = (message: JsonRpcMessage): void => {
|
|
83
|
+
if (!socket.destroyed) socket.write(encodeFrame(message));
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const parser = createFrameParser(
|
|
87
|
+
(message) => {
|
|
88
|
+
if (!authenticated) {
|
|
89
|
+
// Children share the user's privileges, so the token is not a
|
|
90
|
+
// privilege boundary — it keeps unrelated local processes out.
|
|
91
|
+
if (message.method !== HELLO || !tokensMatch(token, (message.params as { token?: unknown } | undefined)?.token)) {
|
|
92
|
+
socket.destroy();
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
authenticated = true;
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (message.method === CANCEL) {
|
|
100
|
+
const id = (message.params as { id?: unknown } | undefined)?.id;
|
|
101
|
+
if (typeof id === "number") inflight.get(id)?.abort();
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (message.method !== EXECUTE || typeof message.id !== "number") return;
|
|
105
|
+
|
|
106
|
+
const id = message.id;
|
|
107
|
+
const payload = message.params as { params?: LspOperationParams; cwd?: string } | undefined;
|
|
108
|
+
if (!payload?.params) {
|
|
109
|
+
reply({ id, error: { code: -32602, message: "missing lsp params" } });
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const controller = new AbortController();
|
|
113
|
+
inflight.set(id, controller);
|
|
114
|
+
runner(payload.params, payload.cwd || process.cwd(), controller.signal)
|
|
115
|
+
.then((text) => reply({ id, result: { text } }))
|
|
116
|
+
.catch((error: Error) => reply({ id, error: { code: -32000, message: error.message } }))
|
|
117
|
+
.finally(() => inflight.delete(id));
|
|
118
|
+
},
|
|
119
|
+
() => socket.destroy(),
|
|
120
|
+
);
|
|
121
|
+
|
|
122
|
+
socket.on("data", (chunk: Buffer) => parser.push(chunk));
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
await new Promise<void>((resolve, reject) => {
|
|
126
|
+
const onError = (error: Error): void => reject(error);
|
|
127
|
+
server.once("error", onError);
|
|
128
|
+
server.listen(socketPath, () => {
|
|
129
|
+
server.removeListener("error", onError);
|
|
130
|
+
resolve();
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
// The listener must never be the reason the parent process stays alive.
|
|
134
|
+
server.unref();
|
|
135
|
+
|
|
136
|
+
return {
|
|
137
|
+
socketPath,
|
|
138
|
+
token,
|
|
139
|
+
removeSocket: cleanup,
|
|
140
|
+
close(): Promise<void> {
|
|
141
|
+
for (const socket of connections) socket.destroy();
|
|
142
|
+
connections.clear();
|
|
143
|
+
return new Promise<void>((resolve) => {
|
|
144
|
+
server.close(() => {
|
|
145
|
+
cleanup();
|
|
146
|
+
resolve();
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
type ConnectFn = (socketPath: string) => net.Socket;
|
|
154
|
+
|
|
155
|
+
interface BrokerPending {
|
|
156
|
+
resolve(text: string): void;
|
|
157
|
+
reject(error: Error): void;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The child half: one lazy connection, shared by every `lsp` call in that process. */
|
|
161
|
+
export class LspBrokerClient {
|
|
162
|
+
private nextId = 1;
|
|
163
|
+
private readonly pending = new Map<number, BrokerPending>();
|
|
164
|
+
private connection?: Promise<net.Socket>;
|
|
165
|
+
|
|
166
|
+
constructor(
|
|
167
|
+
private readonly socketPath: string,
|
|
168
|
+
private readonly token: string,
|
|
169
|
+
private readonly timeoutMs: number,
|
|
170
|
+
private readonly connectFn: ConnectFn = (target) => net.connect(target),
|
|
171
|
+
) {}
|
|
172
|
+
|
|
173
|
+
async execute(params: LspOperationParams, cwd: string, signal?: AbortSignal): Promise<string> {
|
|
174
|
+
const socket = await this.connect();
|
|
175
|
+
const id = this.nextId++;
|
|
176
|
+
|
|
177
|
+
return new Promise<string>((resolve, reject) => {
|
|
178
|
+
let settled = false;
|
|
179
|
+
const cleanup = (): void => {
|
|
180
|
+
settled = true;
|
|
181
|
+
clearTimeout(timer);
|
|
182
|
+
signal?.removeEventListener("abort", onAbort);
|
|
183
|
+
this.pending.delete(id);
|
|
184
|
+
};
|
|
185
|
+
const onAbort = (): void => {
|
|
186
|
+
if (settled) return;
|
|
187
|
+
cleanup();
|
|
188
|
+
if (!socket.destroyed) socket.write(encodeFrame({ method: CANCEL, params: { id } }));
|
|
189
|
+
reject(new Error("aborted"));
|
|
190
|
+
};
|
|
191
|
+
const timer = setTimeout(() => {
|
|
192
|
+
if (settled) return;
|
|
193
|
+
cleanup();
|
|
194
|
+
if (!socket.destroyed) socket.write(encodeFrame({ method: CANCEL, params: { id } }));
|
|
195
|
+
reject(new Error("timed out waiting for the LSP broker"));
|
|
196
|
+
}, this.timeoutMs);
|
|
197
|
+
|
|
198
|
+
this.pending.set(id, {
|
|
199
|
+
resolve: (text) => {
|
|
200
|
+
if (settled) return;
|
|
201
|
+
cleanup();
|
|
202
|
+
resolve(text);
|
|
203
|
+
},
|
|
204
|
+
reject: (error) => {
|
|
205
|
+
if (settled) return;
|
|
206
|
+
cleanup();
|
|
207
|
+
reject(error);
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
211
|
+
socket.write(encodeFrame({ id, method: EXECUTE, params: { params, cwd } }));
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
close(): void {
|
|
216
|
+
const pending = this.connection;
|
|
217
|
+
this.connection = undefined;
|
|
218
|
+
void pending?.then((socket) => socket.destroy()).catch(() => undefined);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
private connect(): Promise<net.Socket> {
|
|
222
|
+
if (this.connection) return this.connection;
|
|
223
|
+
this.connection = new Promise<net.Socket>((resolve, reject) => {
|
|
224
|
+
const socket = this.connectFn(this.socketPath);
|
|
225
|
+
const parser = createFrameParser(
|
|
226
|
+
(message) => {
|
|
227
|
+
if (typeof message.id !== "number") return;
|
|
228
|
+
const entry = this.pending.get(message.id);
|
|
229
|
+
if (!entry) return;
|
|
230
|
+
if (message.error) entry.reject(new Error(message.error.message));
|
|
231
|
+
else entry.resolve(((message.result as { text?: string } | undefined)?.text) ?? "");
|
|
232
|
+
},
|
|
233
|
+
() => socket.destroy(),
|
|
234
|
+
);
|
|
235
|
+
|
|
236
|
+
const fail = (error: Error): void => {
|
|
237
|
+
// Drop the cached connection so a later call can retry a live parent.
|
|
238
|
+
this.connection = undefined;
|
|
239
|
+
for (const entry of [...this.pending.values()]) entry.reject(error);
|
|
240
|
+
this.pending.clear();
|
|
241
|
+
reject(error);
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
socket.on("data", (chunk: Buffer) => parser.push(chunk));
|
|
245
|
+
socket.on("error", (error: Error) => fail(error));
|
|
246
|
+
socket.on("close", () => fail(new Error(CONNECTION_LOST)));
|
|
247
|
+
socket.on("connect", () => {
|
|
248
|
+
socket.write(encodeFrame({ method: HELLO, params: { token: this.token } }));
|
|
249
|
+
resolve(socket);
|
|
250
|
+
});
|
|
251
|
+
socket.unref?.();
|
|
252
|
+
});
|
|
253
|
+
return this.connection;
|
|
254
|
+
}
|
|
255
|
+
}
|