dsh-windows-parallel-mcp 0.0.1 → 0.1.1

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/lib/engine.js ADDED
@@ -0,0 +1,225 @@
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
+ */
45
+ export function resolvePowerShell(explicitPath, env = process.env) {
46
+ if (explicitPath && existsSync(explicitPath)) return explicitPath;
47
+ const win = env.SystemRoot ? join(env.SystemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe') : '';
48
+ if (win && existsSync(win)) return win;
49
+ return 'powershell.exe';
50
+ }
51
+
52
+ /**
53
+ * A refusing-or-answering client for one worker process.
54
+ *
55
+ * Deliberately not an EventEmitter: there is exactly one consumer (the tool), and a second listener
56
+ * surface would make "who restarts the worker" ambiguous.
57
+ */
58
+ export class WorkerClient {
59
+ /**
60
+ * @param {object} options
61
+ * @param {string} [options.powershellPath]
62
+ * @param {string} [options.script]
63
+ * @param {number} [options.requestTimeoutMs]
64
+ * @param {(line: string) => void} [options.onStderr]
65
+ * @param {(info: {restarted: boolean, code: number|null, signal: string|null}) => void} [options.onExit]
66
+ */
67
+ constructor(options = {}) {
68
+ this.powershellPath = resolvePowerShell(options.powershellPath);
69
+ this.script = options.script ?? workerScript();
70
+ this.requestTimeoutMs = options.requestTimeoutMs ?? 20000;
71
+ this.onStderr = options.onStderr ?? (() => {});
72
+ this.onExit = options.onExit ?? (() => {});
73
+
74
+ /** @type {import('node:child_process').ChildProcess | null} */
75
+ this.child = null;
76
+ /** Pending requests keyed by id. Every entry owns its own timer. */
77
+ this.pending = new Map();
78
+ this.seq = 0;
79
+ /** Set once the worker has been started, so a restart is distinguishable from a first start. */
80
+ this.started = false;
81
+ this.restarts = 0;
82
+ /** Last stderr lines, kept because a worker that dies usually explains itself there. */
83
+ this.stderrTail = [];
84
+ this.buffer = '';
85
+ }
86
+
87
+ get alive() {
88
+ return this.child !== null && this.child.exitCode === null && !this.child.killed;
89
+ }
90
+
91
+ /**
92
+ * Start the worker if it is not running. Costs one PowerShell launch on first call; a no-op
93
+ * afterwards. Throws if the script is missing, because a missing engine is a broken install and
94
+ * pretending otherwise would surface as a confusing refusal later.
95
+ */
96
+ start() {
97
+ if (this.alive) return this;
98
+ if (!existsSync(this.script)) {
99
+ throw new Error(`dsh-windows-parallel-mcp: engine worker not found at ${this.script}`);
100
+ }
101
+ const args = [
102
+ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-STA',
103
+ '-File', this.script,
104
+ ];
105
+ const child = spawn(this.powershellPath, args, {
106
+ windowsHide: true,
107
+ stdio: ['pipe', 'pipe', 'pipe'],
108
+ });
109
+ this.child = child;
110
+ this.buffer = '';
111
+ this.stderrTail = [];
112
+
113
+ child.stdout.setEncoding('utf8');
114
+ child.stdout.on('data', (chunk) => this.#onStdout(chunk));
115
+ child.stderr.setEncoding('utf8');
116
+ child.stderr.on('data', (chunk) => {
117
+ for (const line of chunk.split(/\r?\n/)) {
118
+ if (!line.trim()) continue;
119
+ this.stderrTail.push(line);
120
+ if (this.stderrTail.length > 40) this.stderrTail.shift();
121
+ this.onStderr(line);
122
+ }
123
+ });
124
+ child.on('error', (err) => this.#failAll(`worker failed to start: ${err.message}`));
125
+ child.on('exit', (code, signal) => {
126
+ const wasStarted = this.started;
127
+ this.child = null;
128
+ // An exit with outstanding requests is a crash from the caller's point of view, and each of
129
+ // those callers is told so with the worker's own last words attached -- a bare 'worker
130
+ // exited' would send the reader looking in the wrong place.
131
+ this.#failAll(this.#exitMessage(code, signal));
132
+ if (wasStarted) {
133
+ this.restarts += 1;
134
+ this.onExit({ restarted: true, code, signal });
135
+ }
136
+ });
137
+ this.started = true;
138
+ return this;
139
+ }
140
+
141
+ #exitMessage(code, signal) {
142
+ const tail = this.stderrTail.length ? ` :: ${this.stderrTail.slice(-3).join(' | ')}` : '';
143
+ return `engine worker exited (code=${code ?? 'null'} signal=${signal ?? 'null'})${tail}`;
144
+ }
145
+
146
+ #onStdout(chunk) {
147
+ this.buffer += chunk;
148
+ let idx;
149
+ // Only complete lines are protocol. A partial line stays buffered: JSON split across chunks is
150
+ // normal, and parsing the fragment would produce a spurious malformed-response error.
151
+ while ((idx = this.buffer.indexOf('\n')) >= 0) {
152
+ const raw = this.buffer.slice(0, idx).replace(/\r$/, '');
153
+ this.buffer = this.buffer.slice(idx + 1);
154
+ if (!raw.trim()) continue;
155
+ let msg;
156
+ try {
157
+ msg = JSON.parse(raw);
158
+ } catch {
159
+ // Not protocol. Keep it as a diagnostic instead of teaching the caller a fake failure.
160
+ this.stderrTail.push(`[unparsed stdout] ${raw}`);
161
+ continue;
162
+ }
163
+ if (!msg || typeof msg !== 'object' || !('id' in msg)) {
164
+ this.stderrTail.push(`[stdout without id] ${raw}`);
165
+ continue;
166
+ }
167
+ const entry = this.pending.get(String(msg.id));
168
+ if (!entry) continue; // a late answer for a request that already timed out
169
+ this.pending.delete(String(msg.id));
170
+ clearTimeout(entry.timer);
171
+ entry.resolve(msg);
172
+ }
173
+ }
174
+
175
+ #failAll(reason) {
176
+ for (const [id, entry] of this.pending) {
177
+ clearTimeout(entry.timer);
178
+ entry.reject(new Error(reason));
179
+ this.pending.delete(id);
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Send one request and await its response object. Resolves with the whole envelope, so the caller
185
+ * decides what a refusal means; this layer never turns a refusal into an exception.
186
+ */
187
+ request(payload) {
188
+ this.start();
189
+ const id = String(++this.seq);
190
+ const line = JSON.stringify({ id, ...payload }) + '\n';
191
+ const child = this.child;
192
+ return new Promise((resolvePromise, rejectPromise) => {
193
+ const timer = setTimeout(() => {
194
+ this.pending.delete(id);
195
+ // The worker is presumed wedged. It is killed rather than left running: a wedged STA thread
196
+ // inside a cross-process wait will not recover, and the next call deserves a clean process.
197
+ // Restart is bounded by the `restarts` counter read by the tool layer.
198
+ rejectPromise(new Error(
199
+ `engine worker did not answer within ${this.requestTimeoutMs} ms (action=${payload.action}); the worker was killed and will be restarted on the next call`,
200
+ ));
201
+ try { child.kill(); } catch { /* already gone */ }
202
+ }, this.requestTimeoutMs);
203
+ this.pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer });
204
+ child.stdin.write(line, 'utf8', (err) => {
205
+ if (!err) return;
206
+ this.pending.delete(id);
207
+ clearTimeout(timer);
208
+ rejectPromise(new Error(`could not write to the engine worker: ${err.message}`));
209
+ });
210
+ });
211
+ }
212
+
213
+ /** Clean shutdown: close stdin (the worker exits its read loop), then make sure it is gone. */
214
+ async dispose() {
215
+ const child = this.child;
216
+ this.child = null;
217
+ this.#failAll('engine worker disposed');
218
+ if (!child) return;
219
+ try { child.stdin.end(); } catch { }
220
+ await new Promise((done) => {
221
+ const t = setTimeout(() => { try { child.kill(); } catch { } done(); }, 1500);
222
+ child.once('exit', () => { clearTimeout(t); done(); });
223
+ });
224
+ }
225
+ }
@@ -0,0 +1,138 @@
1
+ // host-tools.js — the one host-provided helper this plugin needs, with a fallback that is not a lie.
2
+ //
3
+ // WHY A FALLBACK AT ALL. `defineTool` lives in `@deepseek-ai/dsh-tools`, a peer the host provides.
4
+ // Peer resolution for a plugin loaded out of the profile's node_modules is the host's business, not
5
+ // the plugin's, and it is not something this package can verify from inside itself: a static import
6
+ // turns "the host resolves peers differently than I assumed" into "the plugin fails to load, with no
7
+ // tool and no message". So the import is dynamic, and when it fails the local shim takes over.
8
+ //
9
+ // WHAT THE SHIM IS AND IS NOT. It is NOT a reimplementation of the host's tool runtime: it builds the
10
+ // same registry-ready shape from the same simplified parameter spec (per-field `type` / `description`
11
+ // / `enum` / `required: true`, exactly the shape dsh-bash-terminal-ts passes) and validates arguments
12
+ // against it, because a schema that nothing validates is a description, not a contract. What it does
13
+ // not do is the host's own error branding and presentation hooks; those are additive.
14
+ //
15
+ // REFUSALS ARE NOT ERRORS HERE. The engine answers refusals as normal results carrying a code
16
+ // (decide.ps1's closed set). This layer must not convert them into thrown exceptions -- a thrown
17
+ // error would reach the model as a tool failure, and the whole point of the refusal vocabulary is
18
+ // that the caller can branch on the code and read the next step.
19
+ export const TOOL_NAME = 'wpm';
20
+
21
+ /** The five actions, in the order the contract lists them. */
22
+ export const ACTIONS = ['windows', 'click', 'type', 'focus', 'status'];
23
+
24
+ /** Simplified parameter spec — the same shape the host's `defineTool` consumes. */
25
+ export const PARAMETERS = {
26
+ action: {
27
+ type: 'string',
28
+ enum: ACTIONS,
29
+ required: true,
30
+ description:
31
+ 'windows: list live windows that can be driven (hwnd, title, class, pid, rect). '
32
+ + 'status: read the focus table (foreground window, focused control, last human input age, paused flag). '
33
+ + 'click: click at a screen coordinate inside the target. type: write text into the target. '
34
+ + 'focus: move keyboard focus to a named control inside the target.',
35
+ },
36
+ hwnd: {
37
+ type: 'string',
38
+ description: 'Target top-level window handle from action=windows. Required by click, type and focus.',
39
+ },
40
+ x: { type: 'number', description: 'Screen X coordinate (click only). Must resolve to a child of the target, or the action is refused.' },
41
+ y: { type: 'number', description: 'Screen Y coordinate (click only).' },
42
+ text: { type: 'string', description: 'Text to write (type only). The message tier inserts at the control\'s caret (position 0 when it was never focused); replace:true rewrites the whole value instead. An empty string is refused: it cannot be distinguished from a channel that silently did nothing.' },
43
+ elementName: {
44
+ type: 'string',
45
+ description:
46
+ 'UIA Name or AutomationId of the control to address (type/focus). Naming an element forces the UIA tier, '
47
+ + 'because a window message cannot address "the control called X".',
48
+ },
49
+ replace: { type: 'boolean', description: 'Replace the existing value instead of appending (type only).' },
50
+ settleMs: { type: 'number', description: 'How long to let the app commit its state before the effect is judged (0-2000, default 350).' },
51
+ };
52
+
53
+ /**
54
+ * Build a JSON Schema from the simplified spec.
55
+ *
56
+ * Kept separate and exported so test/schema-test.mjs can compare the shape this plugin registers
57
+ * against src/schema/tools.json: the contract file is the source of truth, and a divergence between
58
+ * "what the model is told" and "what the registry accepts" is invisible until a call is rejected.
59
+ */
60
+ export function parametersToJsonSchema(spec = PARAMETERS) {
61
+ const properties = {};
62
+ const required = [];
63
+ for (const [name, field] of Object.entries(spec)) {
64
+ const { required: isRequired, ...rest } = field;
65
+ properties[name] = rest;
66
+ if (isRequired) required.push(name);
67
+ }
68
+ return { type: 'object', properties, required, additionalProperties: false };
69
+ }
70
+
71
+ /** Minimal argument validation. Returns a list of human-readable violations, empty when valid. */
72
+ export function validateArguments(schema, args) {
73
+ const problems = [];
74
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) return ['arguments must be an object'];
75
+ for (const name of schema.required ?? []) {
76
+ if (args[name] === undefined || args[name] === null) problems.push(`missing required argument '${name}'`);
77
+ }
78
+ for (const [name, value] of Object.entries(args)) {
79
+ const field = schema.properties?.[name];
80
+ if (!field) {
81
+ problems.push(`unknown argument '${name}'`);
82
+ continue;
83
+ }
84
+ if (value === undefined || value === null) continue;
85
+ if (field.type === 'string' && typeof value !== 'string') problems.push(`'${name}' must be a string`);
86
+ if (field.type === 'number' && typeof value !== 'number') problems.push(`'${name}' must be a number`);
87
+ if (field.type === 'boolean' && typeof value !== 'boolean') problems.push(`'${name}' must be a boolean`);
88
+ if (Array.isArray(field.enum) && !field.enum.includes(value)) {
89
+ problems.push(`'${name}' must be one of ${field.enum.join(', ')}`);
90
+ }
91
+ }
92
+ return problems;
93
+ }
94
+
95
+ /** The local shim: same input, same registry-ready output shape. */
96
+ export function localDefineTool(options) {
97
+ const parameters = parametersToJsonSchema(options.parameters);
98
+ const userExecute = options.execute;
99
+ return {
100
+ name: options.name,
101
+ description: options.description,
102
+ parameters,
103
+ output: {
104
+ schema: options.output.schema,
105
+ render: options.output.render,
106
+ },
107
+ async execute(args) {
108
+ const problems = validateArguments(parameters, args);
109
+ if (problems.length) {
110
+ const err = new Error(`${options.name}: ${problems.join('; ')}`);
111
+ err.name = 'ToolArgsError';
112
+ throw err;
113
+ }
114
+ return userExecute(args);
115
+ },
116
+ };
117
+ }
118
+
119
+ /**
120
+ * Resolve the host's `defineTool`, falling back to the local shim.
121
+ * Returns `{ defineTool, source }` so the plugin can log which one it got -- a silent fallback is how
122
+ * "runs on my machine" diverges from "runs on the host".
123
+ */
124
+ export async function resolveDefineTool() {
125
+ // The peer is reached through ./peers-tools.js with a STATIC import -- the host's loader resolves
126
+ // the bare specifier there, while a dynamic `import('@deepseek-ai/dsh-tools')` from a
127
+ // `link:`-installed package resolves upward from the link target and never reaches the profile's
128
+ // node_modules. peers-tools.js throwing means dsh-tools genuinely is not installed (this desktop
129
+ // profile: it is not): the shim takes over and `source` says so. See peers-schemastery.js for why
130
+ // the two peers have separate bridges.
131
+ try {
132
+ const mod = await import('./peers-tools.js');
133
+ if (mod && typeof mod.defineTool === 'function') return { defineTool: mod.defineTool, source: '@deepseek-ai/dsh-tools' };
134
+ } catch {
135
+ // Documented fallback, reported via `source`.
136
+ }
137
+ return { defineTool: localDefineTool, source: 'local-shim' };
138
+ }