dsh-zcode-cua 0.0.0-stage → 1.3.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/CHANGELOG.md +133 -0
- package/LICENSE +21 -0
- package/README.md +208 -2
- package/README.zh.md +209 -0
- package/client.js +209 -0
- package/cordis.patch.yml +43 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/preview.svg +51 -0
- package/icon.svg +28 -0
- package/index.js +226 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +73 -6
- package/server/access.js +94 -0
- package/server/helper-launcher.js +64 -0
- package/server/index.js +498 -0
- package/server/overlay/Overlay.cs +777 -0
- package/server/overlay/host.ps1 +130 -0
- package/server/overlay.js +374 -0
- package/server/paths.js +231 -0
- package/skills/zcode-computer-use/SKILL.md +304 -0
package/server/access.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-session opt-in for the Computer Use tool.
|
|
3
|
+
*
|
|
4
|
+
* ## Why this exists
|
|
5
|
+
*
|
|
6
|
+
* The `js` tool can drive the whole desktop: it clicks, types into whatever
|
|
7
|
+
* holds the keyboard, and reads any window's accessibility tree. That is the
|
|
8
|
+
* point of the plugin, and it is also far too much authority to hand a new
|
|
9
|
+
* session by default — the user starts a session to ask a question and gets an
|
|
10
|
+
* agent that may take the mouse. So the tool is DENIED until the user turns it
|
|
11
|
+
* on for that session, from a switch under the composer.
|
|
12
|
+
*
|
|
13
|
+
* ## Why the state lives here and not in the session log
|
|
14
|
+
*
|
|
15
|
+
* The Harness refuses a stored event whose `type` it does not know unless the
|
|
16
|
+
* envelope carries `ignorable: true`, and live `Session.append()` cannot set
|
|
17
|
+
* that marker. Writing an opt-in record into the log would therefore make the
|
|
18
|
+
* session refuse to reopen after a restart — a plugin that bricks the
|
|
19
|
+
* conversation it was installed for. So the switch is plugin-owned state kept
|
|
20
|
+
* in memory, keyed by session id, and the *denial* is what reaches the model
|
|
21
|
+
* (through the guard) rather than a stored permission record.
|
|
22
|
+
*
|
|
23
|
+
* The consequence, stated plainly because it is a real behaviour: the grant is
|
|
24
|
+
* per session and does not survive a Host restart. A restarted Host comes back
|
|
25
|
+
* with every session off, which is the safe direction for a capability that
|
|
26
|
+
* moves the user's mouse. The user turns it on again from the same switch.
|
|
27
|
+
*
|
|
28
|
+
* ## Why a guard and not `restrict`
|
|
29
|
+
*
|
|
30
|
+
* `ctx.tools.restrict()` removes a tool from the model's schema, which reads as
|
|
31
|
+
* "this plugin is not installed" and leaves the model with no way to tell the
|
|
32
|
+
* user what to do. A guard keeps the tool visible and answers a call with a
|
|
33
|
+
* message that names the switch, so the model can tell the user exactly how to
|
|
34
|
+
* proceed. Guards are also monotonic — once registered they cannot be lifted by
|
|
35
|
+
* a later registration — which is the property we want for a capability gate.
|
|
36
|
+
*
|
|
37
|
+
* @module dsh-zcode-cua/access
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
/** Tool name the MCP client registers for this server's `js` tool. */
|
|
41
|
+
export const CUA_TOOL_NAME = "mcp__zcode-cua__js";
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Sessions that have switched the tool on.
|
|
45
|
+
*
|
|
46
|
+
* A Set of session ids. Ids are opaque branded strings owned by the Harness; we
|
|
47
|
+
* never parse them, only compare them for equality.
|
|
48
|
+
*/
|
|
49
|
+
const granted = new Set();
|
|
50
|
+
|
|
51
|
+
/** Whether `sessionId` has opted in. */
|
|
52
|
+
export function isGranted(sessionId) {
|
|
53
|
+
return typeof sessionId === "string" && granted.has(sessionId);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Turn the tool on or off for one session. */
|
|
57
|
+
export function setGranted(sessionId, value) {
|
|
58
|
+
if (typeof sessionId !== "string" || sessionId === "") return;
|
|
59
|
+
if (value) granted.add(sessionId);
|
|
60
|
+
else granted.delete(sessionId);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Drop every grant. Called when the plugin unloads so a re-mount does not
|
|
65
|
+
* inherit authority granted to a previous generation of the plugin.
|
|
66
|
+
*/
|
|
67
|
+
export function clearGrants() {
|
|
68
|
+
granted.clear();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The guard body.
|
|
73
|
+
*
|
|
74
|
+
* Returns a denial for the Computer Use tool unless the calling session opted
|
|
75
|
+
* in, and `undefined` (allow) for every other tool — a guard that denies tools
|
|
76
|
+
* it does not own would silently break unrelated plugins.
|
|
77
|
+
*
|
|
78
|
+
* `execution.agent` is the calling Agent; its `id` is the SessionId. A call
|
|
79
|
+
* with no agent (a subagent or a host-initiated call with no session attached)
|
|
80
|
+
* cannot be matched to a grant and is denied: "no session" is not a session
|
|
81
|
+
* that said yes.
|
|
82
|
+
*/
|
|
83
|
+
export function guardBody(execution) {
|
|
84
|
+
if (execution?.name !== CUA_TOOL_NAME) return undefined;
|
|
85
|
+
const sessionId = execution.agent?.id;
|
|
86
|
+
if (isGranted(sessionId)) return undefined;
|
|
87
|
+
return {
|
|
88
|
+
reason:
|
|
89
|
+
"Computer control is off for this session. Ask the user to switch it on with the " +
|
|
90
|
+
"\"Computer control\" toggle under the message box, then call this tool again. " +
|
|
91
|
+
"Do not retry before they confirm: the toggle is theirs to flip.",
|
|
92
|
+
info: { name: "COMPUTER_USE_DISABLED", code: "COMPUTER_USE_DISABLED" },
|
|
93
|
+
};
|
|
94
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helper launcher: starts the ZCode native helper without its ghost cursor.
|
|
3
|
+
*
|
|
4
|
+
* Why this file exists
|
|
5
|
+
* --------------------
|
|
6
|
+
* The upstream `node-repl-host` starts the native helper itself, from the recipe
|
|
7
|
+
* this bridge hands it, and it appends `--ghost-cursor-overlay` unconditionally
|
|
8
|
+
* (`server.js:121868` — no setting, no env var, no way to say no). The helper
|
|
9
|
+
* then paints its own always-on pointer overlay on top of every screen.
|
|
10
|
+
*
|
|
11
|
+
* That overlay was useful while this plugin had no indicator of its own. It no
|
|
12
|
+
* longer is: `server/overlay.js` draws a banner, an edge glow and a cursor ring
|
|
13
|
+
* that Windows excludes from every screenshot, while the ZCode overlay is a
|
|
14
|
+
* plain top-level window that any full-screen capture picks up. Two indicators
|
|
15
|
+
* disagreeing about what is happening is worse than one.
|
|
16
|
+
*
|
|
17
|
+
* The recipe's `command` and `entryPath` are ours to choose, so the entry the
|
|
18
|
+
* upstream launches is this file, which drops the flag and then execs the real
|
|
19
|
+
* helper. Nothing upstream is modified, and `DSH_ZCODE_CUA_KEEP_GHOST_CURSOR=1`
|
|
20
|
+
* restores the stock behaviour.
|
|
21
|
+
*
|
|
22
|
+
* Argument layout received from the upstream:
|
|
23
|
+
* <this file> --socket <pipe> --parent-pid <pid> --ghost-cursor-overlay
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { spawn } from "node:child_process";
|
|
27
|
+
|
|
28
|
+
/** Env var the recipe uses to tell us which helper entry to actually run. */
|
|
29
|
+
const HELPER_ENTRY_ENV = "DSH_ZCODE_CUA_HELPER_ENTRY";
|
|
30
|
+
|
|
31
|
+
/** Opt back into the stock ghost cursor. */
|
|
32
|
+
const KEEP_ENV = "DSH_ZCODE_CUA_KEEP_GHOST_CURSOR";
|
|
33
|
+
|
|
34
|
+
const GHOST_FLAG = "--ghost-cursor-overlay";
|
|
35
|
+
|
|
36
|
+
const entry = process.env[HELPER_ENTRY_ENV]?.trim();
|
|
37
|
+
if (!entry) {
|
|
38
|
+
process.stderr.write(`[dsh-zcode-cua] ${HELPER_ENTRY_ENV} is not set; cannot locate the helper entry\n`);
|
|
39
|
+
process.exit(1);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const keepGhost = process.env[KEEP_ENV] === "1";
|
|
43
|
+
const forwarded = process.argv.slice(2).filter((arg) => keepGhost || arg !== GHOST_FLAG);
|
|
44
|
+
|
|
45
|
+
// The helper needs the native addon path, which the upstream already put in our
|
|
46
|
+
// environment (`ZCODE_CUA_HELPER_ADDON`), and `ELECTRON_RUN_AS_NODE=1`, which it
|
|
47
|
+
// also set. Both are inherited, so the child is launched with `process.env`.
|
|
48
|
+
const child = spawn(process.execPath, [entry, ...forwarded], {
|
|
49
|
+
cwd: process.env.ZCODE_CUA_HELPER_ROOT?.trim() || process.cwd(),
|
|
50
|
+
env: process.env,
|
|
51
|
+
detached: true,
|
|
52
|
+
stdio: "ignore",
|
|
53
|
+
windowsHide: true,
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
child.on("error", (error) => {
|
|
57
|
+
process.stderr.write(`[dsh-zcode-cua] helper launch failed: ${error.message}\n`);
|
|
58
|
+
process.exit(1);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
// Detach and leave: the upstream does not wait on this process, and the helper
|
|
62
|
+
// must outlive it.
|
|
63
|
+
child.unref();
|
|
64
|
+
process.exit(0);
|
package/server/index.js
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP server entry point.
|
|
3
|
+
*
|
|
4
|
+
* This is a thin, opinionated proxy in front of ZCode's own
|
|
5
|
+
* `node-repl-host` MCP server. The upstream owns the `js` tool and the whole
|
|
6
|
+
* Computer Use surface; this process exists for two reasons only:
|
|
7
|
+
*
|
|
8
|
+
* 1. It spawns the upstream with the four environment variables that switch
|
|
9
|
+
* Computer Use on. Without `ZCODE_CUA_PERMISSION_BROKER_SOCKET` and
|
|
10
|
+
* `ZCODE_CUA_WIN_HELPER_RECIPE` the upstream answers `tools/list` with a
|
|
11
|
+
* `js` tool that can never reach a desktop, and the failure is invisible
|
|
12
|
+
* from the model's side.
|
|
13
|
+
*
|
|
14
|
+
* 2. It supplies the request context the upstream validates on every
|
|
15
|
+
* `tools/call`.
|
|
16
|
+
*
|
|
17
|
+
* The upstream reads that context from `_meta["com.zcode/request-context"]` and
|
|
18
|
+
* rejects a call whose `session_id` or `turn_id` is empty, so this server mints
|
|
19
|
+
* a session id once and a turn id per call.
|
|
20
|
+
*
|
|
21
|
+
* @module dsh-zcode-cua/server
|
|
22
|
+
*/
|
|
23
|
+
import { spawn } from "node:child_process";
|
|
24
|
+
import { randomUUID } from "node:crypto";
|
|
25
|
+
import { dirname, join } from "node:path";
|
|
26
|
+
import { fileURLToPath } from "node:url";
|
|
27
|
+
import { resolveRuntime, describeRuntime, runtimeIsComplete } from "./paths.js";
|
|
28
|
+
import { createOverlay } from "./overlay.js";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Launcher the upstream runs instead of the helper entry.
|
|
32
|
+
*
|
|
33
|
+
* The upstream appends `--ghost-cursor-overlay` to whatever entry it launches
|
|
34
|
+
* and offers no way to opt out, so the entry it gets is this launcher: it drops
|
|
35
|
+
* the flag and execs the real helper. See `server/helper-launcher.js`.
|
|
36
|
+
*/
|
|
37
|
+
const HELPER_LAUNCHER = join(dirname(fileURLToPath(import.meta.url)), "helper-launcher.js");
|
|
38
|
+
|
|
39
|
+
/** Env var the launcher reads to find the real helper entry. */
|
|
40
|
+
const HELPER_ENTRY_ENV = "DSH_ZCODE_CUA_HELPER_ENTRY";
|
|
41
|
+
|
|
42
|
+
const KEY_PROTOCOL = "io.modelcontextprotocol/protocolVersion";
|
|
43
|
+
const KEY_CAPS = "io.modelcontextprotocol/clientCapabilities";
|
|
44
|
+
const KEY_INFO = "io.modelcontextprotocol/clientInfo";
|
|
45
|
+
const KEY_REQ_CTX = "com.zcode/request-context";
|
|
46
|
+
const MODERN_REVISION = "2026-07-28";
|
|
47
|
+
const SERVER_NAME = "zcode-cua";
|
|
48
|
+
const SERVER_VERSION = "1.0.0";
|
|
49
|
+
|
|
50
|
+
/** Result fields only modern MCP clients understand. */
|
|
51
|
+
const MODERN_ONLY_FIELDS = ["resultType", "ttlMs", "cacheScope"];
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* How long one forwarded request may wait for the upstream.
|
|
55
|
+
*
|
|
56
|
+
* Generous on purpose: a `js` call can legitimately run for two minutes
|
|
57
|
+
* (`node-repl-host` caps a cell at 120 s) and `toolCallTimeoutMs` in
|
|
58
|
+
* `cordis.patch.yml` is 180 s. This ceiling only exists to stop a *lost* answer
|
|
59
|
+
* from pinning a promise forever, so it sits above every legitimate duration
|
|
60
|
+
* rather than policing them.
|
|
61
|
+
*/
|
|
62
|
+
const REQUEST_TIMEOUT_MS = 240_000;
|
|
63
|
+
|
|
64
|
+
/** Set once a shutdown has begun, so an upstream exit is not read as a crash. */
|
|
65
|
+
let shuttingDown = false;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The "AI is driving this computer" indicator.
|
|
69
|
+
*
|
|
70
|
+
* Off with `DSH_ZCODE_CUA_NO_OVERLAY=1`. On by default because the point of the
|
|
71
|
+
* feature is that the user should never be surprised by a moving pointer; a
|
|
72
|
+
* silent default-off would only help people who already know the plugin does
|
|
73
|
+
* this. Failure is always non-fatal — see `server/overlay.js`.
|
|
74
|
+
*/
|
|
75
|
+
const overlay = createOverlay({
|
|
76
|
+
enabled: process.env.DSH_ZCODE_CUA_NO_OVERLAY !== "1",
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
const runtime = resolveRuntime();
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Stable identifiers for this process.
|
|
83
|
+
*
|
|
84
|
+
* `sessionId` groups every action of one DSH session under one identity; it is
|
|
85
|
+
* derived once so reconnects stay consistent. `turnId` must be fresh per tool
|
|
86
|
+
* call — reusing one would make consecutive actions indistinguishable upstream.
|
|
87
|
+
*/
|
|
88
|
+
const sessionId = process.env.ZCODE_BRIDGE_SESSION_ID?.trim() || `dsh-${randomUUID()}`;
|
|
89
|
+
const workspacePath = process.env.ZCODE_BRIDGE_WORKSPACE?.trim() || process.cwd();
|
|
90
|
+
const clientMode = process.env.ZCODE_BRIDGE_CLIENT_MODE?.trim() || "desktop-continuous";
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Launch the upstream MCP server.
|
|
94
|
+
*
|
|
95
|
+
* The helper recipe tells the upstream how to start the native helper and, via
|
|
96
|
+
* `hostPid`, which process should take it down. Pointing `hostPid` at this
|
|
97
|
+
* process is deliberate: when DSH disposes the MCP client, this process exits,
|
|
98
|
+
* the helper's liveness watchdog sees its parent go, and the helper shuts down
|
|
99
|
+
* instead of being left running in the background.
|
|
100
|
+
*/
|
|
101
|
+
function spawnUpstream() {
|
|
102
|
+
if (!runtime.upstream) {
|
|
103
|
+
throw new Error(
|
|
104
|
+
"ZCode's node-repl-host MCP server was not found. Install ZCode, or point " +
|
|
105
|
+
"ZCODE_BRIDGE_SERVER at its dist/mcp/server.js.",
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
const env = {
|
|
109
|
+
...process.env,
|
|
110
|
+
// The model's bootstrap imports `computer-use-client.mjs` through this root.
|
|
111
|
+
...(runtime.cuaPluginRoot ? { ZCODE_CUA_PLUGIN_ROOT: runtime.cuaPluginRoot } : {}),
|
|
112
|
+
...(runtime.cuaPluginRoot ? { ZCODE_PLUGIN_ROOT: runtime.cuaPluginRoot } : {}),
|
|
113
|
+
// Named pipe the helper listens on. The upstream refuses a path outside the
|
|
114
|
+
// `zcode-cua-helper-*` namespace, so the prefix is not cosmetic.
|
|
115
|
+
ZCODE_CUA_PERMISSION_BROKER_SOCKET:
|
|
116
|
+
process.env.ZCODE_CUA_PERMISSION_BROKER_SOCKET?.trim() ||
|
|
117
|
+
`\\\\.\\pipe\\zcode-cua-helper-${randomUUID().replace(/-/g, "").slice(0, 16)}`,
|
|
118
|
+
// How to start the native helper. `command` runs the helper's entry with
|
|
119
|
+
// Node; the upstream appends `--socket`, `--parent-pid` and, unconditionally,
|
|
120
|
+
// `--ghost-cursor-overlay`. That flag is why the entry below is our launcher
|
|
121
|
+
// rather than the helper itself: the launcher strips the flag and execs the
|
|
122
|
+
// real helper, so the stock pointer overlay never appears next to the banner
|
|
123
|
+
// this plugin draws. See `server/helper-launcher.js`.
|
|
124
|
+
...(runtime.helperEntry && runtime.helperAddon
|
|
125
|
+
? {
|
|
126
|
+
ZCODE_CUA_WIN_HELPER_RECIPE: JSON.stringify({
|
|
127
|
+
command: process.execPath,
|
|
128
|
+
entryPath: HELPER_LAUNCHER,
|
|
129
|
+
root: runtime.helperRoot,
|
|
130
|
+
addonPath: runtime.helperAddon,
|
|
131
|
+
commandEnv: { [HELPER_ENTRY_ENV]: runtime.helperEntry },
|
|
132
|
+
hostPid: process.pid,
|
|
133
|
+
}),
|
|
134
|
+
}
|
|
135
|
+
: {}),
|
|
136
|
+
};
|
|
137
|
+
return spawn(process.execPath, [runtime.upstream], {
|
|
138
|
+
env,
|
|
139
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
140
|
+
windowsHide: true,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
let upstream;
|
|
145
|
+
try {
|
|
146
|
+
upstream = spawnUpstream();
|
|
147
|
+
} catch (error) {
|
|
148
|
+
// A missing upstream is reported and then fatal: this process has no tools of
|
|
149
|
+
// its own, so staying alive would present an empty tool list with no reason.
|
|
150
|
+
process.stderr.write(`[dsh-zcode-cua] ${error instanceof Error ? error.message : String(error)}\n`);
|
|
151
|
+
process.exit(1);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// ── upstream connection ─────────────────────────────────────────────────────
|
|
155
|
+
const pending = new Map();
|
|
156
|
+
let nextId = 1;
|
|
157
|
+
|
|
158
|
+
function upstreamRequest(method, params) {
|
|
159
|
+
const id = nextId++;
|
|
160
|
+
const child = upstream;
|
|
161
|
+
return new Promise((resolve, reject) => {
|
|
162
|
+
if (!child || child.exitCode !== null || child.signalCode !== null) {
|
|
163
|
+
reject(new Error("upstream MCP server is not running"));
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
// A request whose answer never arrives must not pin a promise forever: the
|
|
167
|
+
// caller (a `tools/call`) would hang until DSH's own timeout, and the entry
|
|
168
|
+
// would keep the child's closure alive. Fail it on its own clock instead.
|
|
169
|
+
const timer = setTimeout(() => {
|
|
170
|
+
if (pending.delete(id)) reject(new Error(`upstream did not answer ${method} within ${REQUEST_TIMEOUT_MS}ms`));
|
|
171
|
+
}, REQUEST_TIMEOUT_MS);
|
|
172
|
+
timer.unref?.();
|
|
173
|
+
pending.set(id, {
|
|
174
|
+
resolve: (value) => {
|
|
175
|
+
clearTimeout(timer);
|
|
176
|
+
resolve(value);
|
|
177
|
+
},
|
|
178
|
+
reject: (error) => {
|
|
179
|
+
clearTimeout(timer);
|
|
180
|
+
reject(error);
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
try {
|
|
184
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
clearTimeout(timer);
|
|
187
|
+
pending.delete(id);
|
|
188
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
let upstreamBuffer = "";
|
|
194
|
+
upstream.stdout.on("data", (chunk) => {
|
|
195
|
+
upstreamBuffer += chunk.toString("utf8");
|
|
196
|
+
let newline;
|
|
197
|
+
while ((newline = upstreamBuffer.indexOf("\n")) >= 0) {
|
|
198
|
+
const line = upstreamBuffer.slice(0, newline);
|
|
199
|
+
upstreamBuffer = upstreamBuffer.slice(newline + 1);
|
|
200
|
+
if (!line.trim()) continue;
|
|
201
|
+
let message;
|
|
202
|
+
try {
|
|
203
|
+
message = JSON.parse(line);
|
|
204
|
+
} catch {
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
if (message.id === undefined) continue;
|
|
208
|
+
const entry = pending.get(message.id);
|
|
209
|
+
if (!entry) continue;
|
|
210
|
+
pending.delete(message.id);
|
|
211
|
+
if (message.error) {
|
|
212
|
+
entry.reject(Object.assign(new Error(message.error.message ?? "upstream error"), { rpcError: message.error }));
|
|
213
|
+
} else {
|
|
214
|
+
entry.resolve(message.result);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
upstream.stderr.on("data", (chunk) => process.stderr.write(chunk));
|
|
220
|
+
upstream.on("close", (code, signal) => {
|
|
221
|
+
// Every in-flight request would otherwise wait for its own timeout while the
|
|
222
|
+
// client has already been told nothing. Fail them now, with the reason.
|
|
223
|
+
const reason = new Error(
|
|
224
|
+
`upstream MCP server exited (code ${code}${signal ? `, signal ${signal}` : ""})`,
|
|
225
|
+
);
|
|
226
|
+
for (const [id, entry] of pending) {
|
|
227
|
+
pending.delete(id);
|
|
228
|
+
entry.reject(reason);
|
|
229
|
+
}
|
|
230
|
+
// The exit code alone cannot tell "DSH is shutting down" from "ZCode's server
|
|
231
|
+
// crashed": a child killed by a signal, or one that died on its own while the
|
|
232
|
+
// parent is still alive, is a crash. Exiting 0 in that case told DSH the MCP
|
|
233
|
+
// server had finished normally, so its `reconnect` policy never fired and the
|
|
234
|
+
// tools stayed missing until DSH restarted. Exit non-zero and let that policy
|
|
235
|
+
// do its job.
|
|
236
|
+
const crashed = signal !== null || !shuttingDown;
|
|
237
|
+
process.stderr.write(
|
|
238
|
+
`[dsh-zcode-cua] upstream exited (code ${code}${signal ? `, signal ${signal}` : ""})${crashed ? "; reporting a failure so the client may reconnect" : ""}\n`,
|
|
239
|
+
);
|
|
240
|
+
process.exit(crashed ? 1 : 0);
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
// ── client side ─────────────────────────────────────────────────────────────
|
|
244
|
+
const INSTRUCTIONS = [
|
|
245
|
+
"ZCode Computer Use, proxied for DeepSeek Harness.",
|
|
246
|
+
"",
|
|
247
|
+
"Every `js` call runs in a fresh Node.js kernel, so the runtime must be",
|
|
248
|
+
"bootstrapped inside each call before anything else:",
|
|
249
|
+
"",
|
|
250
|
+
" const root = process.env.ZCODE_CUA_PLUGIN_ROOT ?? process.env.ZCODE_PLUGIN_ROOT;",
|
|
251
|
+
' const { join } = await import("node:path");',
|
|
252
|
+
' const { pathToFileURL } = await import("node:url");',
|
|
253
|
+
" const { setupComputerUseRuntime } = await import(",
|
|
254
|
+
' pathToFileURL(join(root, "scripts", "computer-use-client.mjs")).href',
|
|
255
|
+
" );",
|
|
256
|
+
" await setupComputerUseRuntime({ globals: globalThis });",
|
|
257
|
+
"",
|
|
258
|
+
"Then drive the desktop through `agent.computerUse`.",
|
|
259
|
+
"",
|
|
260
|
+
"Runtime:",
|
|
261
|
+
describeRuntime(runtime),
|
|
262
|
+
].join("\n");
|
|
263
|
+
|
|
264
|
+
function envelope(extra) {
|
|
265
|
+
const base = {
|
|
266
|
+
[KEY_PROTOCOL]: MODERN_REVISION,
|
|
267
|
+
[KEY_CAPS]: {},
|
|
268
|
+
[KEY_INFO]: { name: "dsh-zcode-cua", version: SERVER_VERSION },
|
|
269
|
+
};
|
|
270
|
+
return extra ? { ...base, ...extra } : base;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* The request context the upstream validates.
|
|
275
|
+
*
|
|
276
|
+
* It rejects a `tools/call` whose `session_id` or `turn_id` is empty, so both
|
|
277
|
+
* are always supplied; the session id is stable for this process and the turn
|
|
278
|
+
* id is fresh per call.
|
|
279
|
+
*/
|
|
280
|
+
function requestContext(turnId) {
|
|
281
|
+
return {
|
|
282
|
+
session_id: sessionId,
|
|
283
|
+
turn_id: turnId,
|
|
284
|
+
workspace_path: workspacePath,
|
|
285
|
+
workspace_key: workspacePath,
|
|
286
|
+
client_mode: clientMode,
|
|
287
|
+
delivery_kind: clientMode,
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function write(message) {
|
|
292
|
+
process.stdout.write(`${JSON.stringify(message)}\n`);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function toLegacyResult(result) {
|
|
296
|
+
if (result === null || typeof result !== "object" || Array.isArray(result)) return result;
|
|
297
|
+
const copy = { ...result };
|
|
298
|
+
for (const key of MODERN_ONLY_FIELDS) delete copy[key];
|
|
299
|
+
return copy;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Attach a fresh turn id to one tools/call. */
|
|
303
|
+
function withRequestContext(method, params) {
|
|
304
|
+
if (method !== "tools/call") return params ?? {};
|
|
305
|
+
const incoming = params?._meta ?? {};
|
|
306
|
+
const context = requestContext(`turn-${randomUUID()}`);
|
|
307
|
+
return {
|
|
308
|
+
...params,
|
|
309
|
+
_meta: { ...envelope(incoming), [KEY_REQ_CTX]: context },
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
let clientIsModern = false;
|
|
314
|
+
let legacyHandshakeSeen = false;
|
|
315
|
+
|
|
316
|
+
async function forwardModern(message) {
|
|
317
|
+
const { id, method, params } = message;
|
|
318
|
+
if (method === "tools/call") {
|
|
319
|
+
await forwardToolCall(method, params, (result) => {
|
|
320
|
+
if (result instanceof Error) {
|
|
321
|
+
write({ jsonrpc: "2.0", id, error: result.rpcError ?? { code: -32603, message: String(result?.message ?? result) } });
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
write({ jsonrpc: "2.0", id, result });
|
|
325
|
+
});
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
const forwarded = { ...(params ?? {}), _meta: envelope(params?._meta) };
|
|
329
|
+
try {
|
|
330
|
+
write({ jsonrpc: "2.0", id, result: await upstreamRequest(method, forwarded) });
|
|
331
|
+
} catch (error) {
|
|
332
|
+
write({ jsonrpc: "2.0", id, error: error.rpcError ?? { code: -32603, message: String(error?.message ?? error) } });
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Forward one notification upstream, verbatim apart from the envelope.
|
|
338
|
+
*
|
|
339
|
+
* Notifications are fire-and-forget: the upstream answers nothing, so there is
|
|
340
|
+
* no request id to correlate and no reply to write back. A write failure is
|
|
341
|
+
* reported once and swallowed — losing a cancellation must not also take down
|
|
342
|
+
* the connection that is about to be told to stop.
|
|
343
|
+
*/
|
|
344
|
+
async function forwardNotification(message) {
|
|
345
|
+
const { method, params } = message;
|
|
346
|
+
try {
|
|
347
|
+
upstream.stdin.write(
|
|
348
|
+
`${JSON.stringify({ jsonrpc: "2.0", method, params: { ...(params ?? {}), _meta: envelope(params?._meta) } })}\n`,
|
|
349
|
+
);
|
|
350
|
+
} catch (error) {
|
|
351
|
+
process.stderr.write(
|
|
352
|
+
`[dsh-zcode-cua] could not forward ${method}: ${error instanceof Error ? error.message : String(error)}\n`,
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Forward one tools/call with the indicator raised for its duration.
|
|
359
|
+
*
|
|
360
|
+
* The indicator brackets the WHOLE call rather than each broker request: a `js`
|
|
361
|
+
* cell is one user-visible action even when it performs a dozen clicks, and
|
|
362
|
+
* flickering the border between them would read as a malfunction. `finally`
|
|
363
|
+
* covers all three endings — success, upstream error, and cancellation — because
|
|
364
|
+
* a stranded indicator would claim the AI is still driving after the user
|
|
365
|
+
* stopped it.
|
|
366
|
+
*/
|
|
367
|
+
async function forwardToolCall(method, params, respond) {
|
|
368
|
+
const name = typeof params?.name === "string" ? params.name : "";
|
|
369
|
+
const tracked = overlay.handlesTool(name);
|
|
370
|
+
// The `js` tool requires a `title`, and the model writes it as a short
|
|
371
|
+
// user-facing description of what the call is about to do. That is exactly
|
|
372
|
+
// the line the banner should show, so it is passed straight through.
|
|
373
|
+
const title = typeof params?.arguments?.title === "string" ? params.arguments.title : "";
|
|
374
|
+
if (tracked) overlay.enter(title);
|
|
375
|
+
try {
|
|
376
|
+
const forwarded = withRequestContext(method, params);
|
|
377
|
+
respond(await upstreamRequest(method, forwarded));
|
|
378
|
+
} catch (error) {
|
|
379
|
+
respond(error);
|
|
380
|
+
} finally {
|
|
381
|
+
if (tracked) overlay.leave();
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async function handleLegacy(message) {
|
|
386
|
+
const { id, method, params } = message;
|
|
387
|
+
|
|
388
|
+
if (method === "initialize") {
|
|
389
|
+
write({
|
|
390
|
+
jsonrpc: "2.0",
|
|
391
|
+
id,
|
|
392
|
+
result: {
|
|
393
|
+
protocolVersion: params?.protocolVersion ?? "2025-11-25",
|
|
394
|
+
capabilities: { tools: { listChanged: false } },
|
|
395
|
+
serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
|
|
396
|
+
instructions: INSTRUCTIONS,
|
|
397
|
+
},
|
|
398
|
+
});
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
if (method === "ping") {
|
|
403
|
+
write({ jsonrpc: "2.0", id, result: {} });
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
if (method === "tools/list") {
|
|
408
|
+
try {
|
|
409
|
+
write({ jsonrpc: "2.0", id, result: toLegacyResult(await upstreamRequest("tools/list", { _meta: envelope() })) });
|
|
410
|
+
} catch (error) {
|
|
411
|
+
write({ jsonrpc: "2.0", id, error: error.rpcError ?? { code: -32603, message: String(error?.message ?? error) } });
|
|
412
|
+
}
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
if (method === "tools/call") {
|
|
417
|
+
await forwardToolCall(method, params, (result) => {
|
|
418
|
+
if (result instanceof Error) {
|
|
419
|
+
write({ jsonrpc: "2.0", id, error: result.rpcError ?? { code: -32603, message: String(result?.message ?? result) } });
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
write({ jsonrpc: "2.0", id, result: toLegacyResult(result) });
|
|
423
|
+
});
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
write({ jsonrpc: "2.0", id, error: { code: -32601, message: `Method not found: ${method}` } });
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* Notifications that must reach the upstream even though they carry no `id`.
|
|
432
|
+
*
|
|
433
|
+
* `notifications/cancelled` is the one that matters: DSH cancels a tool call
|
|
434
|
+
* when the user interrupts, and the upstream turns that into an aborted `js`
|
|
435
|
+
* cell. Dropping it here — as a blanket "no id means nothing to forward" does —
|
|
436
|
+
* leaves the native action running after the user has stopped it: clicks keep
|
|
437
|
+
* landing and the ghost cursor keeps moving on a turn nobody is waiting for.
|
|
438
|
+
* The others are forwarded so the upstream's own state stays consistent.
|
|
439
|
+
*/
|
|
440
|
+
const FORWARDED_NOTIFICATIONS = new Set([
|
|
441
|
+
"notifications/cancelled",
|
|
442
|
+
"notifications/progress",
|
|
443
|
+
"notifications/roots/list_changed",
|
|
444
|
+
]);
|
|
445
|
+
|
|
446
|
+
function handleMessage(message) {
|
|
447
|
+
if (message.id === undefined) {
|
|
448
|
+
if (typeof message.method === "string" && FORWARDED_NOTIFICATIONS.has(message.method)) {
|
|
449
|
+
void forwardNotification(message);
|
|
450
|
+
}
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
if (!clientIsModern && !legacyHandshakeSeen && message.method !== "initialize") {
|
|
454
|
+
if (message.method === "server/discover" || message.params?._meta?.[KEY_PROTOCOL] !== undefined) {
|
|
455
|
+
clientIsModern = true;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
if (message.method === "initialize") legacyHandshakeSeen = true;
|
|
459
|
+
void (clientIsModern ? forwardModern(message) : handleLegacy(message)).catch((error) => {
|
|
460
|
+
write({ jsonrpc: "2.0", id: message.id, error: { code: -32603, message: String(error?.message ?? error) } });
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
let clientBuffer = "";
|
|
465
|
+
process.stdin.on("data", (chunk) => {
|
|
466
|
+
clientBuffer += chunk.toString("utf8");
|
|
467
|
+
let newline;
|
|
468
|
+
while ((newline = clientBuffer.indexOf("\n")) >= 0) {
|
|
469
|
+
const line = clientBuffer.slice(0, newline);
|
|
470
|
+
clientBuffer = clientBuffer.slice(newline + 1);
|
|
471
|
+
if (!line.trim()) continue;
|
|
472
|
+
let message;
|
|
473
|
+
try {
|
|
474
|
+
message = JSON.parse(line);
|
|
475
|
+
} catch {
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
handleMessage(message);
|
|
479
|
+
}
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
function shutdown(code = 0) {
|
|
483
|
+
shuttingDown = true;
|
|
484
|
+
overlay.dispose();
|
|
485
|
+
try {
|
|
486
|
+
upstream.kill();
|
|
487
|
+
} catch {
|
|
488
|
+
// The child may already be gone; nothing to do.
|
|
489
|
+
}
|
|
490
|
+
process.exit(code);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
process.stdin.on("end", () => shutdown(0));
|
|
494
|
+
for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => shutdown(0));
|
|
495
|
+
|
|
496
|
+
process.stderr.write(
|
|
497
|
+
`[dsh-zcode-cua] ready (runtime ${runtimeIsComplete(runtime) ? "complete" : "INCOMPLETE"})\n${describeRuntime(runtime)}\n`,
|
|
498
|
+
);
|