dsh-windows-parallel-mcp 0.8.2 → 0.9.0-rc.2
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/CHANGELOG.de.md +444 -419
- package/CHANGELOG.es.md +444 -419
- package/CHANGELOG.fr.md +444 -419
- package/CHANGELOG.it.md +444 -419
- package/CHANGELOG.ja.md +444 -419
- package/CHANGELOG.ko.md +444 -419
- package/CHANGELOG.md +965 -940
- package/CHANGELOG.pt.md +444 -419
- package/CHANGELOG.ru.md +444 -419
- package/CHANGELOG.zh.md +444 -419
- package/INSTALL.de.md +126 -126
- package/INSTALL.es.md +126 -126
- package/INSTALL.fr.md +126 -126
- package/INSTALL.it.md +126 -126
- package/INSTALL.ja.md +126 -126
- package/INSTALL.ko.md +126 -126
- package/INSTALL.md +122 -122
- package/INSTALL.pt.md +126 -126
- package/INSTALL.ru.md +126 -126
- package/INSTALL.zh.md +126 -126
- package/README.de.md +684 -684
- package/README.es.md +684 -684
- package/README.fr.md +684 -684
- package/README.it.md +684 -684
- package/README.ja.md +684 -684
- package/README.ko.md +684 -684
- package/README.md +680 -680
- package/README.pt.md +684 -684
- package/README.ru.md +684 -684
- package/README.zh.md +684 -684
- package/cordis.patch.yml +15 -15
- package/docs/refusals.md +90 -90
- package/docs/takeover.md +128 -128
- package/dsh.plugin.json +18 -18
- package/lib/config.js +275 -275
- package/lib/engine.js +252 -252
- package/lib/host-tools.js +365 -338
- package/lib/index.js +1275 -1249
- package/lib/peers-schemastery.js +23 -23
- package/lib/peers-tools.js +15 -15
- package/lib/proof-window.mjs +427 -427
- package/package.json +122 -122
- package/server.json +110 -110
- package/src/engine/decide.ps1 +356 -356
- package/src/engine/engine.ps1 +1208 -1208
- package/src/engine/hud.ps1 +411 -411
- package/src/engine/input-inject.ps1 +176 -176
- package/src/engine/overlay.ps1 +389 -389
- package/src/engine/takeover.ps1 +144 -144
- package/src/engine/win.ps1 +1881 -1881
- package/src/engine/worker.ps1 +310 -310
- package/src/schema/tools.json +533 -533
- package/types/index.d.ts +190 -187
package/lib/engine.js
CHANGED
|
@@ -1,252 +1,252 @@
|
|
|
1
|
-
// engine.js — the sidecar client: one long-lived PowerShell worker, driven over JSON lines.
|
|
2
|
-
//
|
|
3
|
-
// WHY THE WORKER EXISTS AT ALL. The engine (src/engine/*.ps1) is PowerShell because the OS APIs it
|
|
4
|
-
// needs -- UIA COM, GetGUIThreadInfo, AttachThreadInput -- are cheapest there and cost zero install
|
|
5
|
-
// (findings.md TS-1). But UIA wants an STA apartment and a PowerShell process cannot both host that
|
|
6
|
-
// apartment and stay responsive while blocking on stdin. So the worker owns the apartment and the
|
|
7
|
-
// line protocol, and this file owns the process lifetime. Same division the sibling competitor
|
|
8
|
-
// measured to work.
|
|
9
|
-
//
|
|
10
|
-
// WHAT THIS FILE IS RESPONSIBLE FOR, and each one is a failure already seen in this repo or in the
|
|
11
|
-
// ecosystem:
|
|
12
|
-
// * LAZY START. Spawning PowerShell + Add-Type + assembly load on plugin load would put that cost
|
|
13
|
-
// in the host's boot path for a tool nobody has called yet. First call pays; nobody else does.
|
|
14
|
-
// * ONE RESTART, THEN AN HONEST ERROR. A crashed worker must not become a permanently-dead tool
|
|
15
|
-
// that reports nothing, and it must not become an infinite respawn loop either.
|
|
16
|
-
// * NO SILENT STALL. Every request has a deadline. A worker that stops answering (STA thread
|
|
17
|
-
// wedged inside a cross-process SendMessage is the realistic case) would otherwise leave the
|
|
18
|
-
// model waiting forever with no diagnostic.
|
|
19
|
-
// * STDOUT IS THE PROTOCOL AND NOTHING ELSE. A stray line means a broken parse; the reader
|
|
20
|
-
// therefore keeps only lines that parse as an object with an `id`, and preserves everything else
|
|
21
|
-
// as diagnostics rather than throwing it away.
|
|
22
|
-
import { spawn } from 'node:child_process';
|
|
23
|
-
import { existsSync } from 'node:fs';
|
|
24
|
-
import { dirname, join, resolve } from 'node:path';
|
|
25
|
-
import { fileURLToPath } from 'node:url';
|
|
26
|
-
|
|
27
|
-
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
28
|
-
|
|
29
|
-
/** Absolute path of the engine directory shipped inside the package. */
|
|
30
|
-
export function engineRoot(from = HERE) {
|
|
31
|
-
return resolve(from, '..', 'src', 'engine');
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/** Resolve the worker script for this package. */
|
|
35
|
-
export function workerScript(from = HERE) {
|
|
36
|
-
return join(engineRoot(from), 'worker.ps1');
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Locate a PowerShell executable. Windows PowerShell 5.1 is the floor: it ships with Windows, it has
|
|
41
|
-
* UIAutomationClient, and it needs no installation — which is the project's only citable difference
|
|
42
|
-
* against competitors that require uv/Python or an MSVC runtime (findings.md TS-1). pwsh is accepted
|
|
43
|
-
* when the operator points at it, because it is a superset for these calls.
|
|
44
|
-
* @param {string} [explicitPath]
|
|
45
|
-
* @param {Record<string, string|undefined>} [env]
|
|
46
|
-
* @returns {string}
|
|
47
|
-
*/
|
|
48
|
-
export function resolvePowerShell(explicitPath, env = process.env) {
|
|
49
|
-
if (explicitPath && existsSync(explicitPath)) return explicitPath;
|
|
50
|
-
const win = env.SystemRoot ? join(env.SystemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe') : '';
|
|
51
|
-
if (win && existsSync(win)) return win;
|
|
52
|
-
return 'powershell.exe';
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* A refusing-or-answering client for one worker process.
|
|
57
|
-
*
|
|
58
|
-
* Deliberately not an EventEmitter: there is exactly one consumer (the tool), and a second listener
|
|
59
|
-
* surface would make "who restarts the worker" ambiguous.
|
|
60
|
-
*/
|
|
61
|
-
export class WorkerClient {
|
|
62
|
-
/**
|
|
63
|
-
* @param {object} options
|
|
64
|
-
* @param {string} [options.powershellPath]
|
|
65
|
-
* @param {string} [options.script]
|
|
66
|
-
* @param {number} [options.requestTimeoutMs]
|
|
67
|
-
* @param {(line: string) => void} [options.onStderr]
|
|
68
|
-
* @param {(info: {restarted: boolean, code: number|null, signal: string|null}) => void} [options.onExit]
|
|
69
|
-
*/
|
|
70
|
-
constructor(options = {}) {
|
|
71
|
-
this.powershellPath = resolvePowerShell(options.powershellPath);
|
|
72
|
-
this.script = options.script ?? workerScript();
|
|
73
|
-
this.requestTimeoutMs = options.requestTimeoutMs ?? 20000;
|
|
74
|
-
this.onStderr = options.onStderr ?? (() => {});
|
|
75
|
-
this.onExit = options.onExit ?? (() => {});
|
|
76
|
-
|
|
77
|
-
/** @type {import('node:child_process').ChildProcess | null} */
|
|
78
|
-
this.child = null;
|
|
79
|
-
/** Pending requests keyed by id. Every entry owns its own timer. */
|
|
80
|
-
this.pending = new Map();
|
|
81
|
-
this.seq = 0;
|
|
82
|
-
/** Set once the worker has been started, so a restart is distinguishable from a first start. */
|
|
83
|
-
this.started = false;
|
|
84
|
-
this.restarts = 0;
|
|
85
|
-
/** Last stderr lines, kept because a worker that dies usually explains itself there. */
|
|
86
|
-
/** @type {string[]} */
|
|
87
|
-
this.stderrTail = [];
|
|
88
|
-
this.buffer = '';
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
get alive() {
|
|
92
|
-
return this.child !== null && this.child.exitCode === null && !this.child.killed;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
* Start the worker if it is not running. Costs one PowerShell launch on first call; a no-op
|
|
97
|
-
* afterwards. Throws if the script is missing, because a missing engine is a broken install and
|
|
98
|
-
* pretending otherwise would surface as a confusing refusal later.
|
|
99
|
-
*/
|
|
100
|
-
start() {
|
|
101
|
-
if (this.alive) return this;
|
|
102
|
-
if (!existsSync(this.script)) {
|
|
103
|
-
throw new Error(`dsh-windows-parallel-mcp: engine worker not found at ${this.script}`);
|
|
104
|
-
}
|
|
105
|
-
const args = [
|
|
106
|
-
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-STA',
|
|
107
|
-
'-File', this.script,
|
|
108
|
-
];
|
|
109
|
-
const child = spawn(this.powershellPath, args, {
|
|
110
|
-
windowsHide: true,
|
|
111
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
112
|
-
});
|
|
113
|
-
this.child = child;
|
|
114
|
-
this.buffer = '';
|
|
115
|
-
this.stderrTail = [];
|
|
116
|
-
|
|
117
|
-
child.stdout.setEncoding('utf8');
|
|
118
|
-
child.stdout.on('data', (chunk) => this.#onStdout(chunk));
|
|
119
|
-
child.stderr.setEncoding('utf8');
|
|
120
|
-
child.stderr.on('data', (chunk) => {
|
|
121
|
-
for (const line of chunk.split(/\r?\n/)) {
|
|
122
|
-
if (!line.trim()) continue;
|
|
123
|
-
this.stderrTail.push(line);
|
|
124
|
-
if (this.stderrTail.length > 40) this.stderrTail.shift();
|
|
125
|
-
this.onStderr(line);
|
|
126
|
-
}
|
|
127
|
-
});
|
|
128
|
-
child.on('error', (err) => this.#failAll(`worker failed to start: ${err.message}`));
|
|
129
|
-
child.on('exit', (code, signal) => {
|
|
130
|
-
const wasStarted = this.started;
|
|
131
|
-
this.child = null;
|
|
132
|
-
// An exit with outstanding requests is a crash from the caller's point of view, and each of
|
|
133
|
-
// those callers is told so with the worker's own last words attached -- a bare 'worker
|
|
134
|
-
// exited' would send the reader looking in the wrong place.
|
|
135
|
-
this.#failAll(this.#exitMessage(code, signal));
|
|
136
|
-
if (wasStarted) {
|
|
137
|
-
this.restarts += 1;
|
|
138
|
-
this.onExit({ restarted: true, code, signal });
|
|
139
|
-
}
|
|
140
|
-
});
|
|
141
|
-
this.started = true;
|
|
142
|
-
return this;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* @param {number|null} code
|
|
147
|
-
* @param {string|null} signal
|
|
148
|
-
* @returns {string}
|
|
149
|
-
*/
|
|
150
|
-
#exitMessage(code, signal) {
|
|
151
|
-
const tail = this.stderrTail.length ? ` :: ${this.stderrTail.slice(-3).join(' | ')}` : '';
|
|
152
|
-
return `engine worker exited (code=${code ?? 'null'} signal=${signal ?? 'null'})${tail}`;
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/** @param {string} chunk */
|
|
156
|
-
#onStdout(chunk) {
|
|
157
|
-
this.buffer += chunk;
|
|
158
|
-
let idx;
|
|
159
|
-
// Only complete lines are protocol. A partial line stays buffered: JSON split across chunks is
|
|
160
|
-
// normal, and parsing the fragment would produce a spurious malformed-response error.
|
|
161
|
-
while ((idx = this.buffer.indexOf('\n')) >= 0) {
|
|
162
|
-
const raw = this.buffer.slice(0, idx).replace(/\r$/, '');
|
|
163
|
-
this.buffer = this.buffer.slice(idx + 1);
|
|
164
|
-
if (!raw.trim()) continue;
|
|
165
|
-
let msg;
|
|
166
|
-
try {
|
|
167
|
-
msg = JSON.parse(raw);
|
|
168
|
-
} catch {
|
|
169
|
-
// Not protocol. Keep it as a diagnostic instead of teaching the caller a fake failure.
|
|
170
|
-
this.stderrTail.push(`[unparsed stdout] ${raw}`);
|
|
171
|
-
continue;
|
|
172
|
-
}
|
|
173
|
-
if (!msg || typeof msg !== 'object' || !('id' in msg)) {
|
|
174
|
-
this.stderrTail.push(`[stdout without id] ${raw}`);
|
|
175
|
-
continue;
|
|
176
|
-
}
|
|
177
|
-
const entry = this.pending.get(String(msg.id));
|
|
178
|
-
if (!entry) continue; // a late answer for a request that already timed out
|
|
179
|
-
this.pending.delete(String(msg.id));
|
|
180
|
-
clearTimeout(entry.timer);
|
|
181
|
-
entry.resolve(msg);
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
/** @param {string} reason */
|
|
186
|
-
#failAll(reason) {
|
|
187
|
-
for (const [id, entry] of this.pending) {
|
|
188
|
-
clearTimeout(entry.timer);
|
|
189
|
-
entry.reject(new Error(reason));
|
|
190
|
-
this.pending.delete(id);
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* Send one request and await its response object. Resolves with the whole envelope, so the caller
|
|
196
|
-
* decides what a refusal means; this layer never turns a refusal into an exception.
|
|
197
|
-
* @param {any} payload
|
|
198
|
-
* @returns {Promise<any>}
|
|
199
|
-
*/
|
|
200
|
-
request(payload) {
|
|
201
|
-
this.start();
|
|
202
|
-
const id = String(++this.seq);
|
|
203
|
-
const line = JSON.stringify({ id, ...payload }) + '\n';
|
|
204
|
-
// `start()` above either established a live child or threw, so this cast states a fact the
|
|
205
|
-
// method just enforced rather than suppressing an unknown. The same holds for `stdin`: this
|
|
206
|
-
// class spawns with stdio 'pipe', and narrowing it here keeps the runtime path byte-identical
|
|
207
|
-
// (a defensive `if (!stdin) throw` would add a branch that can never run).
|
|
208
|
-
const child = /** @type {import('node:child_process').ChildProcess} */ (this.child);
|
|
209
|
-
return new Promise((resolvePromise, rejectPromise) => {
|
|
210
|
-
const timer = setTimeout(() => {
|
|
211
|
-
this.pending.delete(id);
|
|
212
|
-
// The worker is presumed wedged. It is killed rather than left running: a wedged STA thread
|
|
213
|
-
// inside a cross-process wait will not recover, and the next call deserves a clean process.
|
|
214
|
-
// Restart is bounded by the `restarts` counter read by the tool layer.
|
|
215
|
-
rejectPromise(new Error(
|
|
216
|
-
`engine worker did not answer within ${this.requestTimeoutMs} ms (action=${payload.action}); the worker was killed and will be restarted on the next call`,
|
|
217
|
-
));
|
|
218
|
-
try { child.kill(); } catch { /* already gone */ }
|
|
219
|
-
}, this.requestTimeoutMs);
|
|
220
|
-
this.pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer });
|
|
221
|
-
// The cast sits at the call site rather than in a `const stdin = ...` line so the emitted
|
|
222
|
-
// JavaScript keeps exactly the statements it had: this file's shape is reviewed as a document,
|
|
223
|
-
// and a typing exercise is not allowed to restructure it. `stdin` is `Writable | null` upstream
|
|
224
|
-
// but this class always spawns with stdio 'pipe'.
|
|
225
|
-
/** @type {import('node:stream').Writable} */ (child.stdin).write(line, 'utf8', (err) => {
|
|
226
|
-
if (!err) return;
|
|
227
|
-
this.pending.delete(id);
|
|
228
|
-
clearTimeout(timer);
|
|
229
|
-
rejectPromise(new Error(`could not write to the engine worker: ${err.message}`));
|
|
230
|
-
});
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
/** Clean shutdown: close stdin (the worker exits its read loop), then make sure it is gone. */
|
|
235
|
-
async dispose() {
|
|
236
|
-
const child = this.child;
|
|
237
|
-
this.child = null;
|
|
238
|
-
this.#failAll('engine worker disposed');
|
|
239
|
-
if (!child) return;
|
|
240
|
-
// Cast at the call site, not into a `const`: same reason as in request() -- the statements here
|
|
241
|
-
// must stay exactly what they are. `stdin` is `Writable | null` upstream; this class always
|
|
242
|
-
// spawns with stdio 'pipe', so the cast states the invariant instead of adding a dead branch.
|
|
243
|
-
try { /** @type {import('node:stream').Writable} */ (child.stdin).end(); } catch { }
|
|
244
|
-
// The `@param` hint is what TS2810 asks for under checkJs: it wants "this resolve may be called
|
|
245
|
-
// with no argument" stated, because the promise never carries a value. Documentation only -- the
|
|
246
|
-
// emitted JavaScript is byte-identical to the unhinted form.
|
|
247
|
-
await new Promise(/** @param {(value?: void) => void} done */ (done) => {
|
|
248
|
-
const t = setTimeout(() => { try { child.kill(); } catch { } done(); }, 1500);
|
|
249
|
-
child.once('exit', () => { clearTimeout(t); done(); });
|
|
250
|
-
});
|
|
251
|
-
}
|
|
252
|
-
}
|
|
1
|
+
// engine.js — the sidecar client: one long-lived PowerShell worker, driven over JSON lines.
|
|
2
|
+
//
|
|
3
|
+
// WHY THE WORKER EXISTS AT ALL. The engine (src/engine/*.ps1) is PowerShell because the OS APIs it
|
|
4
|
+
// needs -- UIA COM, GetGUIThreadInfo, AttachThreadInput -- are cheapest there and cost zero install
|
|
5
|
+
// (findings.md TS-1). But UIA wants an STA apartment and a PowerShell process cannot both host that
|
|
6
|
+
// apartment and stay responsive while blocking on stdin. So the worker owns the apartment and the
|
|
7
|
+
// line protocol, and this file owns the process lifetime. Same division the sibling competitor
|
|
8
|
+
// measured to work.
|
|
9
|
+
//
|
|
10
|
+
// WHAT THIS FILE IS RESPONSIBLE FOR, and each one is a failure already seen in this repo or in the
|
|
11
|
+
// ecosystem:
|
|
12
|
+
// * LAZY START. Spawning PowerShell + Add-Type + assembly load on plugin load would put that cost
|
|
13
|
+
// in the host's boot path for a tool nobody has called yet. First call pays; nobody else does.
|
|
14
|
+
// * ONE RESTART, THEN AN HONEST ERROR. A crashed worker must not become a permanently-dead tool
|
|
15
|
+
// that reports nothing, and it must not become an infinite respawn loop either.
|
|
16
|
+
// * NO SILENT STALL. Every request has a deadline. A worker that stops answering (STA thread
|
|
17
|
+
// wedged inside a cross-process SendMessage is the realistic case) would otherwise leave the
|
|
18
|
+
// model waiting forever with no diagnostic.
|
|
19
|
+
// * STDOUT IS THE PROTOCOL AND NOTHING ELSE. A stray line means a broken parse; the reader
|
|
20
|
+
// therefore keeps only lines that parse as an object with an `id`, and preserves everything else
|
|
21
|
+
// as diagnostics rather than throwing it away.
|
|
22
|
+
import { spawn } from 'node:child_process';
|
|
23
|
+
import { existsSync } from 'node:fs';
|
|
24
|
+
import { dirname, join, resolve } from 'node:path';
|
|
25
|
+
import { fileURLToPath } from 'node:url';
|
|
26
|
+
|
|
27
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
28
|
+
|
|
29
|
+
/** Absolute path of the engine directory shipped inside the package. */
|
|
30
|
+
export function engineRoot(from = HERE) {
|
|
31
|
+
return resolve(from, '..', 'src', 'engine');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Resolve the worker script for this package. */
|
|
35
|
+
export function workerScript(from = HERE) {
|
|
36
|
+
return join(engineRoot(from), 'worker.ps1');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Locate a PowerShell executable. Windows PowerShell 5.1 is the floor: it ships with Windows, it has
|
|
41
|
+
* UIAutomationClient, and it needs no installation — which is the project's only citable difference
|
|
42
|
+
* against competitors that require uv/Python or an MSVC runtime (findings.md TS-1). pwsh is accepted
|
|
43
|
+
* when the operator points at it, because it is a superset for these calls.
|
|
44
|
+
* @param {string} [explicitPath]
|
|
45
|
+
* @param {Record<string, string|undefined>} [env]
|
|
46
|
+
* @returns {string}
|
|
47
|
+
*/
|
|
48
|
+
export function resolvePowerShell(explicitPath, env = process.env) {
|
|
49
|
+
if (explicitPath && existsSync(explicitPath)) return explicitPath;
|
|
50
|
+
const win = env.SystemRoot ? join(env.SystemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe') : '';
|
|
51
|
+
if (win && existsSync(win)) return win;
|
|
52
|
+
return 'powershell.exe';
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* A refusing-or-answering client for one worker process.
|
|
57
|
+
*
|
|
58
|
+
* Deliberately not an EventEmitter: there is exactly one consumer (the tool), and a second listener
|
|
59
|
+
* surface would make "who restarts the worker" ambiguous.
|
|
60
|
+
*/
|
|
61
|
+
export class WorkerClient {
|
|
62
|
+
/**
|
|
63
|
+
* @param {object} options
|
|
64
|
+
* @param {string} [options.powershellPath]
|
|
65
|
+
* @param {string} [options.script]
|
|
66
|
+
* @param {number} [options.requestTimeoutMs]
|
|
67
|
+
* @param {(line: string) => void} [options.onStderr]
|
|
68
|
+
* @param {(info: {restarted: boolean, code: number|null, signal: string|null}) => void} [options.onExit]
|
|
69
|
+
*/
|
|
70
|
+
constructor(options = {}) {
|
|
71
|
+
this.powershellPath = resolvePowerShell(options.powershellPath);
|
|
72
|
+
this.script = options.script ?? workerScript();
|
|
73
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? 20000;
|
|
74
|
+
this.onStderr = options.onStderr ?? (() => {});
|
|
75
|
+
this.onExit = options.onExit ?? (() => {});
|
|
76
|
+
|
|
77
|
+
/** @type {import('node:child_process').ChildProcess | null} */
|
|
78
|
+
this.child = null;
|
|
79
|
+
/** Pending requests keyed by id. Every entry owns its own timer. */
|
|
80
|
+
this.pending = new Map();
|
|
81
|
+
this.seq = 0;
|
|
82
|
+
/** Set once the worker has been started, so a restart is distinguishable from a first start. */
|
|
83
|
+
this.started = false;
|
|
84
|
+
this.restarts = 0;
|
|
85
|
+
/** Last stderr lines, kept because a worker that dies usually explains itself there. */
|
|
86
|
+
/** @type {string[]} */
|
|
87
|
+
this.stderrTail = [];
|
|
88
|
+
this.buffer = '';
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
get alive() {
|
|
92
|
+
return this.child !== null && this.child.exitCode === null && !this.child.killed;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Start the worker if it is not running. Costs one PowerShell launch on first call; a no-op
|
|
97
|
+
* afterwards. Throws if the script is missing, because a missing engine is a broken install and
|
|
98
|
+
* pretending otherwise would surface as a confusing refusal later.
|
|
99
|
+
*/
|
|
100
|
+
start() {
|
|
101
|
+
if (this.alive) return this;
|
|
102
|
+
if (!existsSync(this.script)) {
|
|
103
|
+
throw new Error(`dsh-windows-parallel-mcp: engine worker not found at ${this.script}`);
|
|
104
|
+
}
|
|
105
|
+
const args = [
|
|
106
|
+
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-STA',
|
|
107
|
+
'-File', this.script,
|
|
108
|
+
];
|
|
109
|
+
const child = spawn(this.powershellPath, args, {
|
|
110
|
+
windowsHide: true,
|
|
111
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
112
|
+
});
|
|
113
|
+
this.child = child;
|
|
114
|
+
this.buffer = '';
|
|
115
|
+
this.stderrTail = [];
|
|
116
|
+
|
|
117
|
+
child.stdout.setEncoding('utf8');
|
|
118
|
+
child.stdout.on('data', (chunk) => this.#onStdout(chunk));
|
|
119
|
+
child.stderr.setEncoding('utf8');
|
|
120
|
+
child.stderr.on('data', (chunk) => {
|
|
121
|
+
for (const line of chunk.split(/\r?\n/)) {
|
|
122
|
+
if (!line.trim()) continue;
|
|
123
|
+
this.stderrTail.push(line);
|
|
124
|
+
if (this.stderrTail.length > 40) this.stderrTail.shift();
|
|
125
|
+
this.onStderr(line);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
child.on('error', (err) => this.#failAll(`worker failed to start: ${err.message}`));
|
|
129
|
+
child.on('exit', (code, signal) => {
|
|
130
|
+
const wasStarted = this.started;
|
|
131
|
+
this.child = null;
|
|
132
|
+
// An exit with outstanding requests is a crash from the caller's point of view, and each of
|
|
133
|
+
// those callers is told so with the worker's own last words attached -- a bare 'worker
|
|
134
|
+
// exited' would send the reader looking in the wrong place.
|
|
135
|
+
this.#failAll(this.#exitMessage(code, signal));
|
|
136
|
+
if (wasStarted) {
|
|
137
|
+
this.restarts += 1;
|
|
138
|
+
this.onExit({ restarted: true, code, signal });
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
this.started = true;
|
|
142
|
+
return this;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* @param {number|null} code
|
|
147
|
+
* @param {string|null} signal
|
|
148
|
+
* @returns {string}
|
|
149
|
+
*/
|
|
150
|
+
#exitMessage(code, signal) {
|
|
151
|
+
const tail = this.stderrTail.length ? ` :: ${this.stderrTail.slice(-3).join(' | ')}` : '';
|
|
152
|
+
return `engine worker exited (code=${code ?? 'null'} signal=${signal ?? 'null'})${tail}`;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** @param {string} chunk */
|
|
156
|
+
#onStdout(chunk) {
|
|
157
|
+
this.buffer += chunk;
|
|
158
|
+
let idx;
|
|
159
|
+
// Only complete lines are protocol. A partial line stays buffered: JSON split across chunks is
|
|
160
|
+
// normal, and parsing the fragment would produce a spurious malformed-response error.
|
|
161
|
+
while ((idx = this.buffer.indexOf('\n')) >= 0) {
|
|
162
|
+
const raw = this.buffer.slice(0, idx).replace(/\r$/, '');
|
|
163
|
+
this.buffer = this.buffer.slice(idx + 1);
|
|
164
|
+
if (!raw.trim()) continue;
|
|
165
|
+
let msg;
|
|
166
|
+
try {
|
|
167
|
+
msg = JSON.parse(raw);
|
|
168
|
+
} catch {
|
|
169
|
+
// Not protocol. Keep it as a diagnostic instead of teaching the caller a fake failure.
|
|
170
|
+
this.stderrTail.push(`[unparsed stdout] ${raw}`);
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (!msg || typeof msg !== 'object' || !('id' in msg)) {
|
|
174
|
+
this.stderrTail.push(`[stdout without id] ${raw}`);
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
const entry = this.pending.get(String(msg.id));
|
|
178
|
+
if (!entry) continue; // a late answer for a request that already timed out
|
|
179
|
+
this.pending.delete(String(msg.id));
|
|
180
|
+
clearTimeout(entry.timer);
|
|
181
|
+
entry.resolve(msg);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** @param {string} reason */
|
|
186
|
+
#failAll(reason) {
|
|
187
|
+
for (const [id, entry] of this.pending) {
|
|
188
|
+
clearTimeout(entry.timer);
|
|
189
|
+
entry.reject(new Error(reason));
|
|
190
|
+
this.pending.delete(id);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Send one request and await its response object. Resolves with the whole envelope, so the caller
|
|
196
|
+
* decides what a refusal means; this layer never turns a refusal into an exception.
|
|
197
|
+
* @param {any} payload
|
|
198
|
+
* @returns {Promise<any>}
|
|
199
|
+
*/
|
|
200
|
+
request(payload) {
|
|
201
|
+
this.start();
|
|
202
|
+
const id = String(++this.seq);
|
|
203
|
+
const line = JSON.stringify({ id, ...payload }) + '\n';
|
|
204
|
+
// `start()` above either established a live child or threw, so this cast states a fact the
|
|
205
|
+
// method just enforced rather than suppressing an unknown. The same holds for `stdin`: this
|
|
206
|
+
// class spawns with stdio 'pipe', and narrowing it here keeps the runtime path byte-identical
|
|
207
|
+
// (a defensive `if (!stdin) throw` would add a branch that can never run).
|
|
208
|
+
const child = /** @type {import('node:child_process').ChildProcess} */ (this.child);
|
|
209
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
210
|
+
const timer = setTimeout(() => {
|
|
211
|
+
this.pending.delete(id);
|
|
212
|
+
// The worker is presumed wedged. It is killed rather than left running: a wedged STA thread
|
|
213
|
+
// inside a cross-process wait will not recover, and the next call deserves a clean process.
|
|
214
|
+
// Restart is bounded by the `restarts` counter read by the tool layer.
|
|
215
|
+
rejectPromise(new Error(
|
|
216
|
+
`engine worker did not answer within ${this.requestTimeoutMs} ms (action=${payload.action}); the worker was killed and will be restarted on the next call`,
|
|
217
|
+
));
|
|
218
|
+
try { child.kill(); } catch { /* already gone */ }
|
|
219
|
+
}, this.requestTimeoutMs);
|
|
220
|
+
this.pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer });
|
|
221
|
+
// The cast sits at the call site rather than in a `const stdin = ...` line so the emitted
|
|
222
|
+
// JavaScript keeps exactly the statements it had: this file's shape is reviewed as a document,
|
|
223
|
+
// and a typing exercise is not allowed to restructure it. `stdin` is `Writable | null` upstream
|
|
224
|
+
// but this class always spawns with stdio 'pipe'.
|
|
225
|
+
/** @type {import('node:stream').Writable} */ (child.stdin).write(line, 'utf8', (err) => {
|
|
226
|
+
if (!err) return;
|
|
227
|
+
this.pending.delete(id);
|
|
228
|
+
clearTimeout(timer);
|
|
229
|
+
rejectPromise(new Error(`could not write to the engine worker: ${err.message}`));
|
|
230
|
+
});
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Clean shutdown: close stdin (the worker exits its read loop), then make sure it is gone. */
|
|
235
|
+
async dispose() {
|
|
236
|
+
const child = this.child;
|
|
237
|
+
this.child = null;
|
|
238
|
+
this.#failAll('engine worker disposed');
|
|
239
|
+
if (!child) return;
|
|
240
|
+
// Cast at the call site, not into a `const`: same reason as in request() -- the statements here
|
|
241
|
+
// must stay exactly what they are. `stdin` is `Writable | null` upstream; this class always
|
|
242
|
+
// spawns with stdio 'pipe', so the cast states the invariant instead of adding a dead branch.
|
|
243
|
+
try { /** @type {import('node:stream').Writable} */ (child.stdin).end(); } catch { }
|
|
244
|
+
// The `@param` hint is what TS2810 asks for under checkJs: it wants "this resolve may be called
|
|
245
|
+
// with no argument" stated, because the promise never carries a value. Documentation only -- the
|
|
246
|
+
// emitted JavaScript is byte-identical to the unhinted form.
|
|
247
|
+
await new Promise(/** @param {(value?: void) => void} done */ (done) => {
|
|
248
|
+
const t = setTimeout(() => { try { child.kill(); } catch { } done(); }, 1500);
|
|
249
|
+
child.once('exit', () => { clearTimeout(t); done(); });
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
}
|