@johnhenry/wsh 0.32.0 → 0.34.0

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/README.md CHANGED
@@ -63,7 +63,7 @@ Or via CDN:
63
63
  - **MCP bridge** -- discover and invoke remote MCP tools through the control channel
64
64
  - **Session recording** -- own JSON schema (asciicast-v2-shaped, not a playable asciicast file -- see note below) recording and playback with seek/pause/resume
65
65
  - **Key management** -- IndexedDB storage with OPFS encrypted backup (PBKDF2 + AES-256-GCM)
66
- - **98 message types** -- handshake, channel, gateway, guest sharing, compression negotiation, copilot, policy, authorized-key management, and more
66
+ - **99 message types** -- handshake, channel, gateway, guest sharing, compression negotiation, copilot, policy, authorized-key management, and more
67
67
 
68
68
  > **Session recording is asciicast-v2-shaped, but not an asciicast file.**
69
69
  > The JS `SessionRecorder.toJSON()` export borrows asciicast v2's vocabulary --
@@ -182,10 +182,14 @@ const { stdout } = await WshClient.exec(url, 'wc -c', { username, keyPair, stdin
182
182
  On an open exec session, `await session.write(data); await session.closeStdin()` sends EOF without closing the
183
183
  session: output keeps arriving and `onExit` / `onClose` fire as usual. Without `stdin`, `exec` never touches stdin.
184
184
 
185
- EOF is the end of the session's stdin data stream, so it needs a **stream-mode** host: `@johnhenry/wsh/server` (any
186
- version, nothing to upgrade server-side). The Rust `wsh-server` runs exec on a PTY with stdin carried as control
187
- messages (`data_mode: virtual`) and has no EOF message; `closeStdin()` throws there and `exec({ stdin })` rejects
188
- rather than silently hanging (tracked in #105).
185
+ EOF is either the end of the session's stdin data stream (a **stream-mode** host: `@johnhenry/wsh/server`, any
186
+ version) or, on a virtual-mode host, a zero-length `SessionData`. The Rust `wsh-server` from `rust-v0.5.0` supports the
187
+ second form: it advertises the `exec-pipes` feature, and a client that sees it opens the exec channel with
188
+ `stdio: 'pipes'` (`exec({ stdin })` does this by itself), so the command runs on plain pipes -- byte-exact input, no
189
+ echo, stderr kept apart (`session.onStderr`, and `stderr` in the `exec()` result) -- and `closeStdin()` works. Against
190
+ an older Rust server (no `exec-pipes`; its exec is a PTY) nothing is sent that it would reject, and `closeStdin()` /
191
+ `exec({ stdin })` fail with a clear error instead of hanging. `exec` without `stdin`, `pty` sessions and shells keep
192
+ the PTY.
189
193
 
190
194
  ## Node Server
191
195
 
@@ -602,6 +606,20 @@ await session.write('ls\n'); // and it is the same process
602
606
  only the owner re-attaches as a controller; everyone else needs the token.
603
607
  Sessions are in-memory: a server restart ends them all.
604
608
 
609
+ ### Cancelling transfers and tool calls
610
+
611
+ ```js
612
+ const ac = new AbortController();
613
+ const p = client.upload(bytes, 'big.bin', { signal: ac.signal });
614
+ ac.abort(); // p rejects with an AbortError and the file channel is closed
615
+ await client.download('big.bin', { signal });
616
+ await client.callTool('search', { q: 'x' }, { timeout: 30_000, signal });
617
+ const pty = client.getSession(client.listSessions()[0].channelId); // live session: write() / close()
618
+ ```
619
+
620
+ An aborted upload writes nothing (the server writes the file only when the last chunk arrives). An aborted `callTool`
621
+ also sends `McpCancel` to a host advertising `mcp-cancel`, so the tool handler's `ctx.signal` fires.
622
+
605
623
  ### MCP tools
606
624
 
607
625
  `createWshServer({ mcp })` answers `McpDiscover` and `McpCall`, so the stock
@@ -1029,7 +1047,7 @@ so options the platform gains later need no change here.
1029
1047
 
1030
1048
  | Export | Description |
1031
1049
  |--------|-------------|
1032
- | `MSG` | 98 message type constants (hex opcodes) |
1050
+ | `MSG` | 99 message type constants (hex opcodes) |
1033
1051
  | `CHANNEL_KIND` | Channel types: `pty`, `exec`, `meta`, `file`, `tcp`, `udp`, `job` |
1034
1052
  | `AUTH_METHOD` | Auth methods: `pubkey`, `password` |
1035
1053
  | `cborEncode` / `cborDecode` | CBOR codec (maps, arrays, strings, ints, bytes, bools, null, floats) |
@@ -1053,7 +1071,7 @@ instead of dragging its own toolchain and CI job into an unrelated
1053
1071
  browser-app repo. It was previously deleted from clawser by accident
1054
1072
  (2026-03-14) and restored (2026-07-05) before this move.
1055
1073
 
1056
- Four crates, workspace-versioned at `0.1.0`:
1074
+ Four crates, workspace-versioned (currently `0.5.0`):
1057
1075
 
1058
1076
  | Crate | Kind | Description |
1059
1077
  |-------|------|--------------|
@@ -1077,6 +1095,7 @@ than left to be found.
1077
1095
  | Install an authorized key | `WshClient.addAuthorizedKey()` | `wsh_client::WshClient::add_authorized_key()`, `wsh copy-id` | **Wire-unified** (wsh #59): `AuthorizedKeyAdd`/`AuthorizedKeyResult`, replacing a Rust-CLI-only shell command with a message every implementation can send |
1078
1096
  | Host identity / TOFU | `WshKnownHosts` (localStorage-backed) | `KnownHosts`/`HostStatus` (`~/.wsh/known_hosts`-backed) | **Record unified, policy is not** (wsh #59): both pin `ServerHello.host_fingerprint`, which `@johnhenry/wsh/server` populates (with a proof of possession, [Host key](#host-key-fingerprint--tofu)) but no Rust `wsh-server` release does yet (see [Security](#security-model)). *When* to trust, prompt, or persist is deliberately left per-implementation -- a browser and a CLI have different UX for "first time seeing this host" |
1079
1097
  | Typed RPC channels (`openRpc`, `rpc` sessions; `wsh-host`, `wsh-fs`, `mcp`) | `WshClient.openRpc()`, `RpcChannel` | Rust `wsh-server` (`rust-v0.4.0`+): `wsh-host`, and `wsh-fs` when `[rpc] fs_root` is set; no client yet in `wsh-client` | **No wire change**: `Open { kind: 'rpc', command: <protocol> }` plus `rpc*` `ServerHello` features, negotiated so it fails fast elsewhere; the Rust server serves it on WebSocket/QMux only |
1098
+ | Exec stdin + EOF, separate stderr | `exec({ stdin })`, `session.closeStdin()`, `session.onStderr` | none yet in `wsh-client` | **Wire-unified, negotiated** (#105): `Open.stdio = "pipes"` + `OpenOk.stderr_channel_id` + zero-length `SessionData` as EOF, offered by the `exec-pipes` `ServerHello` feature. `@johnhenry/wsh/server` needs none of it (stream-mode EOF); the Rust `wsh-server` (`rust-v0.5.0`+) runs such an exec on pipes, everything else on the PTY |
1080
1099
  | Interactive shell UI | none -- this SDK is a protocol client, not a terminal emulator; pair with xterm.js/ghostty-web | `wsh connect`, `wsh sftp` (line-oriented REPL) | **Deliberately not unified** -- a browser embeds a terminal widget the host page owns; a CLI process owns its own TTY |
1081
1100
  | Attach / resume | `attachSession()`, `resumeSession()`, `WshSession.seq` | `attach_session()`, `resume_session()` | **Wire-unified** (`Attach`/`Resume`/`Presence`); `seq` = cumulative output bytes. `@johnhenry/wsh/server` honours `last_seq` (bounded ring, gap errors) and answers Presence with `channel_id`/`seq`; the Rust `wsh-server` does the same (`rust-v0.2.0`+; fixed 256 KiB ring) |
1082
1101
  | Reverse-connect / relay peer | `connectReverse()`, `trustRelayPeer()`; `@johnhenry/wsh/server`: `relay` option and `createReverseHost()` | `wsh reverse`, `wsh agent` (persistent, with startup-unit install) | **Wire-unified** (registration, discovery, signed peer records); **daemonization is CLI-only** -- a browser tab cannot be a background OS service. The Node relay is default-deny and bridges one operator per peer unless `maxOperatorsPerPeer` is raised (`busy:` reasons say so); E2E and bridged feature gates need `rust-v0.3.0`+ on the Rust side; several operators per peer and the signed `KeyExchange` are JS-relay only for now |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/wsh",
3
- "version": "0.32.0",
3
+ "version": "0.34.0",
4
4
  "description": "Web Shell \u2014 browser-native remote command execution over WebTransport and WebSocket with Ed25519 authentication",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/client.mjs CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  attach as attachMsg, resume as resumeMsg, ping as pingMsg, pong as pongMsg,
17
17
  reverseRegister as reverseRegisterMsg, reverseList as reverseListMsg,
18
18
  reverseConnect as reverseConnectMsg, relayForward as relayForwardMsg,
19
- mcpDiscover as mcpDiscoverMsg, mcpCall as mcpCallMsg,
19
+ mcpDiscover as mcpDiscoverMsg, mcpCall as mcpCallMsg, mcpCancel as mcpCancelMsg,
20
20
  suspendSession as suspendSessionMsg, restartPty as restartPtyMsg,
21
21
  metricsRequest as metricsRequestMsg,
22
22
  guestInvite as guestInviteMsg, guestJoin as guestJoinMsg, guestRevoke as guestRevokeMsg,
@@ -75,12 +75,27 @@ const FS_RPC_OPS = new Set(['stat', 'list', 'read', 'write', 'mkdir', 'remove',
75
75
  */
76
76
  export const MCP_CALL_ID_FEATURE = 'mcp-call-id';
77
77
 
78
+ /**
79
+ * ServerHello feature advertising that the host understands `McpCancel` (stop an in-flight `McpCall`).
80
+ * Negotiated rather than assumed: McpCancelPayload is `deny_unknown_fields` on the Rust side, so an older
81
+ * server would reject it. Implies `mcp-call-id` (the cancel names a call by its id).
82
+ */
83
+ export const MCP_CANCEL_FEATURE = 'mcp-cancel';
84
+
85
+ /** An `AbortError` for `signal`, with the signal's reason as `cause`. */
86
+ function abortError(signal) {
87
+ const e = new DOMException('The operation was aborted', 'AbortError');
88
+ if (signal && 'reason' in signal && signal.reason !== undefined) e.cause = signal.reason;
89
+ return e;
90
+ }
91
+
78
92
  /**
79
93
  * ServerHello feature: the host discovers a client-opened exec data stream
80
94
  * on its own (the transport announces it), so the client must NOT write the
81
95
  * one-byte "primer" -- against such a host it would reach the process's stdin.
82
96
  */
83
97
  export const STREAM_ANNOUNCE_FEATURE = 'stream-announce';
98
+ export const EXEC_PIPES_FEATURE = 'exec-pipes';
84
99
 
85
100
  /**
86
101
  * Reject a missing argument that maps to a `required: true` wire field.
@@ -713,8 +728,17 @@ export class WshClient {
713
728
  * stream is bound, before any received byte can be delivered (`openRpc` uses it to set `onData`).
714
729
  * @returns {Promise<WshSession>}
715
730
  */
716
- async openSession({ type = 'pty', command, protocol, cols = 80, rows = 24, env, timeout = DEFAULT_OPEN_TIMEOUT, primer = true, attach } = {}) {
731
+ async openSession({ type = 'pty', command, protocol, cols = 80, rows = 24, env, timeout = DEFAULT_OPEN_TIMEOUT, primer = true, attach, stdio } = {}) {
717
732
  this.#assertAuthenticated('openSession');
733
+ if (stdio !== undefined && stdio !== 'pty' && stdio !== 'pipes') {
734
+ throw new TypeError('openSession: stdio must be "pty" or "pipes"');
735
+ }
736
+ if (stdio === 'pipes') {
737
+ if (type !== 'exec') throw new TypeError('openSession: stdio "pipes" is only for type "exec"');
738
+ if (!this.hasFeature(EXEC_PIPES_FEATURE)) {
739
+ throw new Error(`openSession: this host does not advertise "${EXEC_PIPES_FEATURE}" (exec on plain pipes with stdin EOF); it runs exec on a PTY, which cannot signal end of input`);
740
+ }
741
+ }
718
742
  if (type === 'rpc') {
719
743
  this.#assertRpcProtocol(protocol);
720
744
  command = protocol;
@@ -722,7 +746,7 @@ export class WshClient {
722
746
  const requestedChannelId = this._nextChannelId();
723
747
 
724
748
  await this.#transport.sendControl(
725
- openMsg({ kind: type, command, cols, rows, env })
749
+ openMsg({ kind: type, command, cols, rows, env, stdio: stdio === 'pipes' ? 'pipes' : undefined })
726
750
  );
727
751
 
728
752
  // Registered as a dedicated pending-open (not the generic
@@ -794,7 +818,7 @@ export class WshClient {
794
818
 
795
819
  /**
796
820
  * List locally tracked sessions with their current state.
797
- * @returns {Array<{channelId: number, kind: string, state: string}>}
821
+ * @returns {Array<{channelId: number, kind: string, state: string, sessionId?: string}>}
798
822
  */
799
823
  listSessions() {
800
824
  const result = [];
@@ -803,11 +827,30 @@ export class WshClient {
803
827
  channelId,
804
828
  kind: session.kind,
805
829
  state: session.state,
830
+ sessionId: session.sessionId,
806
831
  });
807
832
  }
808
833
  return result;
809
834
  }
810
835
 
836
+ /**
837
+ * The live {@link WshSession} this client opened, by `channelId` (as listed by
838
+ * {@link WshClient#listSessions}) or by the server `sessionId`. Unlike the plain objects
839
+ * `listSessions()` returns, it can `write()`, `resize()`, `closeStdin()` and `close()`.
840
+ * `undefined` when there is no such session (never opened, or already closed by the host).
841
+ *
842
+ * @param {number|string} id
843
+ * @returns {WshSession|undefined}
844
+ */
845
+ getSession(id) {
846
+ if (typeof id === 'number') return this.#sessions.get(id);
847
+ if (typeof id !== 'string' || !id) return undefined;
848
+ for (const session of this.#sessions.values()) {
849
+ if (session.sessionId === id) return session;
850
+ }
851
+ return undefined;
852
+ }
853
+
811
854
  /**
812
855
  * Attach to an existing remote session (collaborative or read-only).
813
856
  *
@@ -1038,21 +1081,32 @@ export class WshClient {
1038
1081
  * @param {boolean} [opts.primer=true] - See `openSession({ primer })`
1039
1082
  * @param {string|Uint8Array|ReadableStream|AsyncIterable|Iterable} [opts.stdin] - Input for the
1040
1083
  * command. It is written, then stdin is closed (EOF), so `cat`, `wc -c` and `sh -s` finish.
1041
- * Omitted: stdin is never touched (unchanged behaviour). Needs a stream-mode host.
1042
- * @returns {Promise<{stdout: Uint8Array, exitCode: number}>}
1043
- */
1044
- static async exec(url, command, { username, keyPair, signer, password, timeout = DEFAULT_EXEC_TIMEOUT, primer = true, stdin, ...hostKeyOpts } = {}) {
1084
+ * Omitted: stdin is never touched (unchanged behaviour). Needs a stream-mode host or a host
1085
+ * advertising `exec-pipes` (the Rust `wsh-server` from `rust-v0.5.0`); against any other
1086
+ * virtual-mode host it fails with a clear error rather than hanging.
1087
+ * @param {'pipes'|'pty'} [opts.stdio] - Where the command runs. Default: with `stdin`, plain pipes
1088
+ * when the host advertises `exec-pipes` (no echo, stderr kept apart, EOF), else the host's native
1089
+ * mode; without `stdin`, the host's native mode (a PTY on the Rust server), exactly as before.
1090
+ * `'pipes'` throws if the host does not advertise `exec-pipes`; `'pty'` never asks for pipes.
1091
+ * @returns {Promise<{stdout: Uint8Array, exitCode: number, stderr?: Uint8Array}>} `stderr` is present
1092
+ * only when the command ran on pipes.
1093
+ */
1094
+ static async exec(url, command, { username, keyPair, signer, password, timeout = DEFAULT_EXEC_TIMEOUT, primer = true, stdin, stdio, ...hostKeyOpts } = {}) {
1045
1095
  if (stdin !== undefined) assertStdinSource(stdin);
1096
+ if (stdio !== undefined && stdio !== 'pipes' && stdio !== 'pty') throw new TypeError('exec: stdio must be "pipes" or "pty"');
1046
1097
  const client = new WshClient();
1047
1098
  const chunks = [];
1099
+ const errChunks = [];
1048
1100
  let exitCode = -1;
1101
+ let piped = false;
1049
1102
 
1050
1103
  try {
1051
1104
  await client.connect(url, { username, keyPair, signer, password, ...hostKeyOpts });
1105
+ piped = stdio === 'pipes' || (stdio === undefined && stdin !== undefined && client.hasFeature(EXEC_PIPES_FEATURE));
1052
1106
 
1053
1107
  // The first stdin byte (or the EOF itself) announces the data stream to a
1054
1108
  // legacy host, so the primer byte is only needed when there is no stdin.
1055
- const session = await client.openSession({ type: 'exec', command, primer: stdin === undefined ? primer : false });
1109
+ const session = await client.openSession({ type: 'exec', command, primer: stdin === undefined ? primer : false, stdio: piped ? 'pipes' : undefined });
1056
1110
 
1057
1111
  await new Promise((resolve, reject) => {
1058
1112
  const timer = setTimeout(() => {
@@ -1063,6 +1117,10 @@ export class WshClient {
1063
1117
  chunks.push(data);
1064
1118
  };
1065
1119
 
1120
+ session.onStderr = (data) => {
1121
+ errChunks.push(data);
1122
+ };
1123
+
1066
1124
  session.onExit = (code) => {
1067
1125
  exitCode = code;
1068
1126
  };
@@ -1084,16 +1142,18 @@ export class WshClient {
1084
1142
  await client.disconnect().catch(() => {});
1085
1143
  }
1086
1144
 
1087
- // Concatenate output chunks.
1088
- const totalLength = chunks.reduce((sum, c) => sum + c.byteLength, 0);
1089
- const stdout = new Uint8Array(totalLength);
1090
- let offset = 0;
1091
- for (const chunk of chunks) {
1092
- stdout.set(chunk, offset);
1093
- offset += chunk.byteLength;
1094
- }
1145
+ const concat = (parts) => {
1146
+ const out = new Uint8Array(parts.reduce((sum, c) => sum + c.byteLength, 0));
1147
+ let offset = 0;
1148
+ for (const chunk of parts) {
1149
+ out.set(chunk, offset);
1150
+ offset += chunk.byteLength;
1151
+ }
1152
+ return out;
1153
+ };
1095
1154
 
1096
- return { stdout, exitCode };
1155
+ const stdout = concat(chunks);
1156
+ return piped ? { stdout, exitCode, stderr: concat(errChunks) } : { stdout, exitCode };
1097
1157
  }
1098
1158
 
1099
1159
  // ── Reverse mode ────────────────────────────────────────────────────
@@ -1393,42 +1453,86 @@ export class WshClient {
1393
1453
  * @param {string} remotePath - Destination path on the server
1394
1454
  * @param {object} [opts]
1395
1455
  * @param {function(number): void} [opts.onProgress] - Progress callback (bytes sent)
1456
+ * @param {AbortSignal} [opts.signal] - Abort the transfer. Rejects with an `AbortError` and closes the file
1457
+ * channel. An already-aborted signal opens nothing. The host buffers the upload and writes the file only once
1458
+ * the final chunk has arrived, so aborting before then leaves the destination untouched -- nothing partial is
1459
+ * ever on disk. If the abort lands after the final chunk was sent, the host may still complete the write
1460
+ * (the promise rejects regardless).
1396
1461
  */
1397
- async upload(blob, remotePath, { onProgress } = {}) {
1462
+ async upload(blob, remotePath, { onProgress, signal } = {}) {
1398
1463
  this.#assertAuthenticated('upload');
1399
- const session = await this.openSession({ type: 'file', command: `upload:${remotePath}` });
1464
+ if (signal?.aborted) throw abortError(signal);
1465
+ const session = await this.#openAbortable(signal, { type: 'file', command: `upload:${remotePath}` });
1466
+ const stop = () => { session.close().catch(() => {}); };
1467
+ signal?.addEventListener('abort', stop, { once: true });
1468
+ try {
1469
+ return await this.#uploadOn(session, blob, onProgress, signal);
1470
+ } catch (e) {
1471
+ if (signal?.aborted) throw abortError(signal);
1472
+ throw e;
1473
+ } finally {
1474
+ signal?.removeEventListener('abort', stop);
1475
+ await session.close().catch(() => {});
1476
+ }
1477
+ }
1478
+
1479
+ /**
1480
+ * openSession(), but a signal that fires while the host is still answering rejects at once and closes the
1481
+ * session when it does open (nothing is leaked).
1482
+ * @private
1483
+ */
1484
+ async #openAbortable(signal, opts) {
1485
+ if (!signal) return this.openSession(opts);
1486
+ const opening = this.openSession(opts);
1487
+ let onAbort;
1488
+ const aborted = new Promise((_, reject) => {
1489
+ onAbort = () => reject(abortError(signal));
1490
+ signal.addEventListener('abort', onAbort, { once: true });
1491
+ });
1492
+ try {
1493
+ return await Promise.race([opening, aborted]);
1494
+ } catch (e) {
1495
+ opening.then((s) => s.close(), () => {}).catch(() => {});
1496
+ throw e;
1497
+ } finally {
1498
+ signal.removeEventListener('abort', onAbort);
1499
+ }
1500
+ }
1501
+
1502
+ /** @private */
1503
+ async #uploadOn(session, blob, onProgress, signal) {
1400
1504
  const data = blob instanceof Blob
1401
1505
  ? new Uint8Array(await blob.arrayBuffer())
1402
1506
  : blob;
1403
1507
  const total = data.byteLength;
1404
1508
 
1405
- try {
1406
- let sent = 0;
1407
- do {
1408
- const end = Math.min(sent + FILE_CHUNK_SIZE, total);
1409
- await this.#transport.sendControl(fileChunkMsg({
1410
- channelId: session.channelId,
1411
- offset: sent,
1412
- data: data.subarray(sent, end),
1413
- isFinal: end >= total,
1414
- totalSize: total,
1415
- }));
1416
- sent = end;
1417
- onProgress?.(sent);
1418
- } while (sent < total);
1419
-
1420
- // The server confirms completion the same way an exec session
1421
- // signals it finished: Exit with a code, then Close. Resolve on
1422
- // whichever arrives first.
1423
- const code = await new Promise((resolve) => {
1424
- session.onExit = (c) => { session.onExit = null; resolve(c); };
1425
- session.onClose = () => resolve(null);
1426
- });
1427
- if (code !== 0) {
1428
- throw new Error(`Upload failed with exit code ${code ?? 'unknown'}`);
1429
- }
1430
- } finally {
1431
- await session.close().catch(() => {});
1509
+ let sent = 0;
1510
+ do {
1511
+ // Checked before every chunk: a closed channel must not be written to.
1512
+ if (signal?.aborted) throw abortError(signal);
1513
+ const end = Math.min(sent + FILE_CHUNK_SIZE, total);
1514
+ await this.#transport.sendControl(fileChunkMsg({
1515
+ channelId: session.channelId,
1516
+ offset: sent,
1517
+ data: data.subarray(sent, end),
1518
+ isFinal: end >= total,
1519
+ totalSize: total,
1520
+ }));
1521
+ sent = end;
1522
+ onProgress?.(sent);
1523
+ } while (sent < total);
1524
+ if (signal?.aborted) throw abortError(signal);
1525
+
1526
+ // The server confirms completion the same way an exec session
1527
+ // signals it finished: Exit with a code, then Close. Resolve on
1528
+ // whichever arrives first.
1529
+ const code = await new Promise((resolve) => {
1530
+ session.onExit = (c) => { session.onExit = null; resolve(c); };
1531
+ session.onClose = () => resolve(null);
1532
+ if (session.state === 'closed') resolve(null);
1533
+ });
1534
+ if (code !== 0) {
1535
+ throw new Error(`Upload failed with exit code ${code ?? 'unknown'}`);
1432
1536
  }
1433
1537
  }
1434
1538
 
@@ -1445,11 +1549,16 @@ export class WshClient {
1445
1549
  * @param {object} [opts]
1446
1550
  * @param {function({received: number, total: number}): void} [opts.onProgress]
1447
1551
  * @param {number} [opts.timeout=10000] - Timeout in ms waiting for the channel to open
1552
+ * @param {AbortSignal} [opts.signal] - Abort the transfer. Rejects with an `AbortError` and closes the file
1553
+ * channel (the host stops sending). An already-aborted signal opens nothing.
1448
1554
  * @returns {Promise<Uint8Array>} File contents
1449
1555
  */
1450
- async download(remotePath, { onProgress, timeout = DEFAULT_OPEN_TIMEOUT } = {}) {
1556
+ async download(remotePath, { onProgress, timeout = DEFAULT_OPEN_TIMEOUT, signal } = {}) {
1451
1557
  this.#assertAuthenticated('download');
1452
- const session = await this.openSession({ type: 'file', command: `download:${remotePath}`, timeout });
1558
+ if (signal?.aborted) throw abortError(signal);
1559
+ const session = await this.#openAbortable(signal, { type: 'file', command: `download:${remotePath}`, timeout });
1560
+ const stop = () => { session.close().catch(() => {}); };
1561
+ signal?.addEventListener('abort', stop, { once: true });
1453
1562
 
1454
1563
  try {
1455
1564
  let data = null;
@@ -1457,6 +1566,7 @@ export class WshClient {
1457
1566
 
1458
1567
  while (true) {
1459
1568
  const chunk = await session._readFileChunk();
1569
+ if (signal?.aborted) throw abortError(signal);
1460
1570
  if (chunk === null) {
1461
1571
  throw new Error('Download failed: connection closed before the transfer completed (truncated)');
1462
1572
  }
@@ -1474,7 +1584,11 @@ export class WshClient {
1474
1584
  return data;
1475
1585
  }
1476
1586
  }
1587
+ } catch (e) {
1588
+ if (signal?.aborted) throw abortError(signal);
1589
+ throw e;
1477
1590
  } finally {
1591
+ signal?.removeEventListener('abort', stop);
1478
1592
  await session.close().catch(() => {});
1479
1593
  }
1480
1594
  }
@@ -1514,31 +1628,47 @@ export class WshClient {
1514
1628
  * @param {object} [args={}] - Tool arguments. Defaults to `{}` rather
1515
1629
  * than being omitted: `McpCall.arguments` is a required wire field,
1516
1630
  * and a tool that takes no arguments is an ordinary thing to call.
1517
- * @param {number} [timeout=30000]
1631
+ * @param {number|{timeout?: number, signal?: AbortSignal}} [options=30000] - A timeout in ms, or
1632
+ * `{ timeout, signal }`. When `signal` fires the call rejects with an `AbortError`; against a host
1633
+ * advertising `mcp-cancel` (see {@link MCP_CANCEL_FEATURE}) it also sends `McpCancel`, so the tool
1634
+ * handler's own signal fires. An already-aborted signal sends nothing. Against an older host the
1635
+ * call is only abandoned locally and the tool runs to completion (its reply is discarded).
1518
1636
  * @returns {Promise<*>} Tool result
1519
1637
  */
1520
- async callTool(name, args = {}, timeout = 30_000) {
1638
+ async callTool(name, args = {}, options = 30_000) {
1521
1639
  this.#assertAuthenticated('callTool');
1522
1640
  requireArgs('callTool', { name });
1641
+ const { timeout = 30_000, signal } = typeof options === 'number' ? { timeout: options } : (options ?? {});
1642
+ if (signal?.aborted) throw abortError(signal);
1523
1643
 
1524
1644
  if (this.hasFeature(MCP_CALL_ID_FEATURE)) {
1525
- return this.#callToolCorrelated(name, args, timeout);
1645
+ return this.#callToolCorrelated(name, args, timeout, signal);
1526
1646
  }
1527
1647
  // No correlation available: serialise so a concurrent caller cannot be
1528
- // handed someone else's result.
1648
+ // handed someone else's result. An aborted call stops waiting at once, but
1649
+ // keeps its queue slot until its reply (or timeout): with no call_id on the
1650
+ // wire, that late reply would otherwise be handed to the next call.
1529
1651
  const run = this.#mcpQueue.then(
1530
- () => this.#callToolCorrelated(name, args, timeout),
1531
- () => this.#callToolCorrelated(name, args, timeout),
1652
+ () => this.#callToolCorrelated(name, args, timeout, undefined, signal),
1653
+ () => this.#callToolCorrelated(name, args, timeout, undefined, signal),
1532
1654
  );
1533
1655
  this.#mcpQueue = run.then(() => undefined, () => undefined);
1534
- return run;
1656
+ if (!signal) return run;
1657
+ let onAbort;
1658
+ const aborted = new Promise((_, reject) => {
1659
+ onAbort = () => reject(abortError(signal));
1660
+ signal.addEventListener('abort', onAbort, { once: true });
1661
+ });
1662
+ try { return await Promise.race([run, aborted]); } finally { signal.removeEventListener('abort', onAbort); }
1535
1663
  }
1536
1664
 
1537
1665
  /**
1538
1666
  * Send one McpCall and wait for the McpResult that answers it.
1667
+ * `signal` aborts the wait (correlated path); `skipIfAborted` is the queued path's start-gate.
1539
1668
  * @private
1540
1669
  */
1541
- async #callToolCorrelated(name, args, timeout) {
1670
+ async #callToolCorrelated(name, args, timeout, signal, skipIfAborted) {
1671
+ if (skipIfAborted?.aborted) throw abortError(skipIfAborted);
1542
1672
  const correlate = this.hasFeature(MCP_CALL_ID_FEATURE);
1543
1673
  // Only sent when the peer understands it: McpCallPayload is
1544
1674
  // deny_unknown_fields on the Rust side, so an unsolicited call_id would
@@ -1549,7 +1679,7 @@ export class WshClient {
1549
1679
  mcpCallMsg({ tool: name, arguments: args, callId })
1550
1680
  );
1551
1681
 
1552
- const response = await this.#waitForMessage(
1682
+ const wait = this.#waitForMessage(
1553
1683
  [MSG.MCP_RESULT],
1554
1684
  timeout,
1555
1685
  `Timed out waiting for MCP tool result (${name})`,
@@ -1558,9 +1688,18 @@ export class WshClient {
1558
1688
  callId === undefined
1559
1689
  ? undefined
1560
1690
  : (msg) => msg.call_id === undefined || msg.call_id === callId,
1691
+ signal,
1561
1692
  );
1562
-
1563
- return response.result;
1693
+ try {
1694
+ const response = await wait;
1695
+ return response.result;
1696
+ } catch (e) {
1697
+ if (signal?.aborted && e?.name === 'AbortError' && callId !== undefined && this.hasFeature(MCP_CANCEL_FEATURE)) {
1698
+ // Best effort: the caller has already given up.
1699
+ this.#transport.sendControl(mcpCancelMsg({ callId })).catch(() => {});
1700
+ }
1701
+ throw e;
1702
+ }
1564
1703
  }
1565
1704
 
1566
1705
  // ── Suspend / Restart ───────────────────────────────────────────────
@@ -2596,9 +2735,12 @@ export class WshClient {
2596
2735
  // different connection.
2597
2736
  sessionId: msg.session_id,
2598
2737
  resumeToken: msg.token,
2738
+ stderrChannelId: msg.stderr_channel_id,
2599
2739
  }
2600
2740
  );
2601
2741
  this.#sessions.set(serverChannelId, session);
2742
+ // stderr of a pipes session arrives on its own channel id; route it to the same session.
2743
+ if (session.stderrChannelId !== undefined) this.#sessions.set(session.stderrChannelId, session);
2602
2744
 
2603
2745
  if (dataMode === 'virtual') {
2604
2746
  session._activateVirtual((m) => this.sendRelayControl(m));
@@ -2705,6 +2847,7 @@ export class WshClient {
2705
2847
  // Remove session from tracking if it's closed.
2706
2848
  if (type === MSG.CLOSE) {
2707
2849
  this.#sessions.delete(channelId);
2850
+ if (session.stderrChannelId !== undefined) this.#sessions.delete(session.stderrChannelId);
2708
2851
  }
2709
2852
  return;
2710
2853
  }
@@ -2869,20 +3012,34 @@ export class WshClient {
2869
3012
  * @returns {Promise<object>}
2870
3013
  * @private
2871
3014
  */
2872
- #waitForMessage(types, timeout, timeoutMessage, match) {
3015
+ #waitForMessage(types, timeout, timeoutMessage, match, signal) {
2873
3016
  const typeArr = Array.isArray(types) ? types : [types];
2874
3017
 
2875
3018
  return new Promise((resolve, reject) => {
2876
3019
  const timer = setTimeout(() => {
2877
3020
  // Remove this waiter.
2878
3021
  this.#removeWaiter(key, waiter);
3022
+ signal?.removeEventListener('abort', onAbort);
2879
3023
  reject(new Error(timeoutMessage));
2880
3024
  }, timeout);
3025
+ const onAbort = () => {
3026
+ clearTimeout(timer);
3027
+ this.#removeWaiter(key, waiter);
3028
+ reject(abortError(signal));
3029
+ };
3030
+ if (signal) {
3031
+ if (signal.aborted) { clearTimeout(timer); reject(abortError(signal)); return; }
3032
+ signal.addEventListener('abort', onAbort, { once: true });
3033
+ }
2881
3034
 
2882
3035
  // `match` lets a waiter claim only the reply that belongs to it --
2883
3036
  // correlation, rather than "first waiter of this type wins". Waiters
2884
3037
  // without one match on type alone, as before.
2885
- const waiter = { resolve, reject, timer, types: typeArr, match };
3038
+ const waiter = {
3039
+ resolve: (v) => { signal?.removeEventListener('abort', onAbort); resolve(v); },
3040
+ reject: (e) => { signal?.removeEventListener('abort', onAbort); reject(e); },
3041
+ timer, types: typeArr, match,
3042
+ };
2886
3043
 
2887
3044
  // For multi-type waiting, use a synthetic key.
2888
3045
  const key = typeArr.length === 1
@@ -54,7 +54,7 @@ export class WshFileTransfer {
54
54
  * @param {number} [opts.timeout] - Timeout in ms for server responses
55
55
  * @returns {Promise<{ success: boolean, bytesTransferred: number }>}
56
56
  */
57
- async upload(data, remotePath, { onProgress, timeout = RESPONSE_TIMEOUT_MS } = {}) {
57
+ async upload(data, remotePath, { onProgress, timeout = RESPONSE_TIMEOUT_MS, signal } = {}) {
58
58
  if (typeof this.#client.upload !== 'function') {
59
59
  throw new Error('WshFileTransfer requires a client exposing upload() (e.g. WshClient)');
60
60
  }
@@ -68,6 +68,7 @@ export class WshFileTransfer {
68
68
  onProgress?.(value);
69
69
  },
70
70
  timeout,
71
+ signal,
71
72
  });
72
73
  const bytes = data instanceof Uint8Array ? data.byteLength : data.byteLength ?? data.length ?? 0;
73
74
  return { success: true, bytesTransferred: bytes };
@@ -87,11 +88,11 @@ export class WshFileTransfer {
87
88
  * @param {number} [opts.timeout] - Timeout in ms for server responses
88
89
  * @returns {Promise<Uint8Array>} File content
89
90
  */
90
- async download(remotePath, { onProgress, timeout = RESPONSE_TIMEOUT_MS } = {}) {
91
+ async download(remotePath, { onProgress, timeout = RESPONSE_TIMEOUT_MS, signal } = {}) {
91
92
  if (typeof this.#client.download !== 'function') {
92
93
  throw new Error('WshFileTransfer requires a client exposing download() (e.g. WshClient)');
93
94
  }
94
- return await this.#client.download(remotePath, { onProgress, timeout });
95
+ return await this.#client.download(remotePath, { onProgress, timeout, signal });
95
96
  }
96
97
 
97
98
  /**
package/src/index.d.ts CHANGED
@@ -238,12 +238,17 @@ export const PROTOCOL_VERSION: 'wsh-v1';
238
238
  */
239
239
  export const MCP_CALL_ID_FEATURE: 'mcp-call-id';
240
240
 
241
+ /** ServerHello feature: the host understands `McpCancel` (stop an in-flight `McpCall`). Implies `mcp-call-id`. */
242
+ export const MCP_CANCEL_FEATURE: 'mcp-cancel';
243
+
241
244
  /**
242
245
  * ServerHello feature: the host discovers a client-opened exec data stream
243
246
  * without help (the transport announces it), so the client writes no
244
247
  * one-byte primer against it.
245
248
  */
246
249
  export const STREAM_ANNOUNCE_FEATURE: 'stream-announce';
250
+ /** ServerHello feature: the host runs `exec` on plain pipes (stderr apart, stdin EOF) when asked with `stdio: 'pipes'`. */
251
+ export const EXEC_PIPES_FEATURE: 'exec-pipes';
247
252
 
248
253
  // ── Typed (object-mode) RPC channels -- wsh #85 ────────────────────────
249
254
 
@@ -557,6 +562,11 @@ export function mcpCall(opts?: {
557
562
  callId?: string;
558
563
  }): WshMessage;
559
564
 
565
+ export function mcpCancel(opts?: {
566
+ /** The `call_id` of the McpCall to stop. */
567
+ callId?: string;
568
+ }): WshMessage;
569
+
560
570
  export function mcpResult(opts?: {
561
571
  result?: unknown;
562
572
  /** Echoed verbatim from the McpCall this answers. */
@@ -1633,6 +1643,12 @@ export class WshSession {
1633
1643
  /** Called when stdout/stderr data arrives. */
1634
1644
  onData: ((data: Uint8Array) => void) | null;
1635
1645
 
1646
+ /** stderr of a `stdio: 'pipes'` exec session (the host keeps it apart from stdout). */
1647
+ onStderr: ((data: Uint8Array) => void) | null;
1648
+
1649
+ /** Channel id carrying stderr for a `stdio: 'pipes'` session, else undefined. */
1650
+ readonly stderrChannelId: number | undefined;
1651
+
1636
1652
  /** Called when the remote process exits. */
1637
1653
  onExit: ((code: number) => void) | null;
1638
1654
 
@@ -1849,6 +1865,12 @@ export interface WshOpenSessionOptions {
1849
1865
  * never sends it.
1850
1866
  */
1851
1867
  primer?: boolean;
1868
+ /**
1869
+ * `exec` only: `'pipes'` runs the command on plain pipes (no echo, stderr on
1870
+ * `session.onStderr`, `closeStdin()` works) and throws unless the host
1871
+ * advertises `exec-pipes`. `'pty'` or omitted: the host's native mode.
1872
+ */
1873
+ stdio?: 'pty' | 'pipes';
1852
1874
  }
1853
1875
 
1854
1876
  /**
@@ -1929,12 +1951,20 @@ export interface WshExecOptions extends WshHostKeyOptions {
1929
1951
  * stream-mode host (`@johnhenry/wsh/server`).
1930
1952
  */
1931
1953
  stdin?: string | Uint8Array | ReadableStream<Uint8Array | string> | AsyncIterable<Uint8Array | string> | Iterable<Uint8Array | string>;
1954
+ /**
1955
+ * Default: with `stdin`, plain pipes when the host advertises `exec-pipes`,
1956
+ * else the host's native mode; without `stdin`, the host's native mode.
1957
+ * `'pipes'` throws if the host lacks `exec-pipes`; `'pty'` never asks for pipes.
1958
+ */
1959
+ stdio?: 'pty' | 'pipes';
1932
1960
  }
1933
1961
 
1934
1962
  /** Result from WshClient.exec(). */
1935
1963
  export interface WshExecResult {
1936
1964
  stdout: Uint8Array;
1937
1965
  exitCode: number;
1966
+ /** Present only when the command ran on plain pipes (`exec-pipes`). */
1967
+ stderr?: Uint8Array;
1938
1968
  }
1939
1969
 
1940
1970
  /** Session list entry. */
@@ -1942,6 +1972,8 @@ export interface WshSessionInfo {
1942
1972
  channelId: number;
1943
1973
  kind: string;
1944
1974
  state: string;
1975
+ /** The server's session id, when the host assigned one (pty / exec). */
1976
+ sessionId?: string;
1945
1977
  }
1946
1978
 
1947
1979
  /** Peer information from reverse list. */
@@ -2147,6 +2179,12 @@ export class WshClient {
2147
2179
  */
2148
2180
  listSessions(): WshSessionInfo[];
2149
2181
 
2182
+ /**
2183
+ * The live session this client opened, by `channelId` or server `sessionId` -- one that can `write()`,
2184
+ * `resize()`, `closeStdin()` and `close()`. `undefined` when there is none.
2185
+ */
2186
+ getSession(id: number | string): WshSession | undefined;
2187
+
2150
2188
  /**
2151
2189
  * Attach to an existing remote session (collaborative or read-only).
2152
2190
  * Authorization is satisfied by EITHER `opts.token` OR the caller
@@ -2320,7 +2358,11 @@ export class WshClient {
2320
2358
  /**
2321
2359
  * Upload a blob to a remote path.
2322
2360
  */
2323
- upload(blob: Blob | Uint8Array, remotePath: string, opts?: { onProgress?: (bytesSent: number) => void }): Promise<void>;
2361
+ upload(blob: Blob | Uint8Array, remotePath: string, opts?: {
2362
+ onProgress?: (bytesSent: number) => void;
2363
+ /** Rejects with an `AbortError` and closes the file channel; an already-aborted signal opens nothing. */
2364
+ signal?: AbortSignal;
2365
+ }): Promise<void>;
2324
2366
 
2325
2367
  /**
2326
2368
  * Download a file from a remote path.
@@ -2330,6 +2372,8 @@ export class WshClient {
2330
2372
  opts?: {
2331
2373
  onProgress?: (progress: { received: number; total: number }) => void;
2332
2374
  timeout?: number;
2375
+ /** Rejects with an `AbortError` and closes the file channel; an already-aborted signal opens nothing. */
2376
+ signal?: AbortSignal;
2333
2377
  },
2334
2378
  ): Promise<Uint8Array>;
2335
2379
 
@@ -2341,7 +2385,12 @@ export class WshClient {
2341
2385
  /**
2342
2386
  * Call an MCP tool on the remote server.
2343
2387
  */
2344
- callTool(name: string, args: Record<string, unknown>, timeout?: number): Promise<unknown>;
2388
+ callTool(
2389
+ name: string,
2390
+ args?: Record<string, unknown>,
2391
+ /** A timeout in ms, or `{ timeout, signal }`. An aborted call rejects with an `AbortError`; against a host advertising `mcp-cancel` the tool handler's signal fires too. */
2392
+ options?: number | { timeout?: number; signal?: AbortSignal },
2393
+ ): Promise<unknown>;
2345
2394
 
2346
2395
  /**
2347
2396
  * Connect using an externally created transport.
@@ -2562,6 +2611,7 @@ export class WshFileTransfer {
2562
2611
  opts?: {
2563
2612
  onProgress?: (progress: WshFileUploadProgress) => void;
2564
2613
  timeout?: number;
2614
+ signal?: AbortSignal;
2565
2615
  },
2566
2616
  ): Promise<WshFileUploadResult>;
2567
2617
 
@@ -2573,6 +2623,7 @@ export class WshFileTransfer {
2573
2623
  opts?: {
2574
2624
  onProgress?: (progress: WshFileDownloadProgress) => void;
2575
2625
  timeout?: number;
2626
+ signal?: AbortSignal;
2576
2627
  },
2577
2628
  ): Promise<Uint8Array>;
2578
2629
 
package/src/index.mjs CHANGED
@@ -15,7 +15,7 @@ export {
15
15
  open, openOk, openFail, resize, signal, exit, close, sessionData, error, ping, pong,
16
16
  attach, resume, rename, idleWarning, shutdown, snapshot,
17
17
  presence, controlChanged, metrics,
18
- mcpDiscover, mcpTools, mcpCall, mcpResult,
18
+ mcpDiscover, mcpTools, mcpCall, mcpResult, mcpCancel,
19
19
  reverseRegister, reverseList, reversePeers, reverseConnect, reverseAccept, reverseReject,
20
20
  relayForward, reverseClose, RELAY_FORWARDABLE, isRelayForwardable,
21
21
  openTcp, openUdp, resolveDns, gatewayOk, gatewayFail, gatewayClose,
@@ -75,7 +75,7 @@ export {
75
75
  // Session + Client
76
76
  export { WshSession } from './session.mjs';
77
77
  export { WshVirtualSessionBackend, normalizeSessionData } from './virtual-session.mjs';
78
- export { WshClient, MCP_CALL_ID_FEATURE, STREAM_ANNOUNCE_FEATURE } from './client.mjs';
78
+ export { WshClient, MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE, STREAM_ANNOUNCE_FEATURE, EXEC_PIPES_FEATURE } from './client.mjs';
79
79
 
80
80
  // End-to-end key exchange (responder side, feature names, signed transcript) -- wsh #90
81
81
  export { E2E_FEATURE, E2E_SIGN_FEATURE, keyExchangeTranscript, verifyKeyExchangeSignature } from './e2e-exchange.mjs';
@@ -54,6 +54,7 @@ export const MSG = Object.freeze({
54
54
  MCP_TOOLS: 0x41,
55
55
  MCP_CALL: 0x42,
56
56
  MCP_RESULT: 0x43,
57
+ MCP_CANCEL: 0x44,
57
58
 
58
59
  // Reverse
59
60
  REVERSE_REGISTER: 0x50,
@@ -240,19 +241,21 @@ export function authFail({ reason } = {}) {
240
241
  };
241
242
  }
242
243
 
243
- export function open({ kind, command, cols, rows, env } = {}) {
244
+ export function open({ kind, command, cols, rows, env, stdio } = {}) {
244
245
  const msg = { type: MSG.OPEN, kind };
245
246
  if (command !== undefined) msg.command = command;
246
247
  if (cols !== undefined) msg.cols = cols;
247
248
  if (rows !== undefined) msg.rows = rows;
248
249
  if (env !== undefined) msg.env = env;
250
+ if (stdio !== undefined) msg.stdio = stdio;
249
251
  return msg;
250
252
  }
251
253
 
252
- export function openOk({ channelId, streamIds = [], dataMode = "stream", capabilities = [], sessionId, token } = {}) {
254
+ export function openOk({ channelId, streamIds = [], dataMode = "stream", capabilities = [], sessionId, token, stderrChannelId } = {}) {
253
255
  const msg = { type: MSG.OPEN_OK, channel_id: channelId, stream_ids: streamIds, data_mode: dataMode, capabilities };
254
256
  if (sessionId !== undefined) msg.session_id = sessionId;
255
257
  if (token !== undefined) msg.token = token;
258
+ if (stderrChannelId !== undefined) msg.stderr_channel_id = stderrChannelId;
256
259
  return msg;
257
260
  }
258
261
 
@@ -459,6 +462,13 @@ export function mcpResult({ result, callId } = {}) {
459
462
  return msg;
460
463
  }
461
464
 
465
+ export function mcpCancel({ callId } = {}) {
466
+ return {
467
+ type: MSG.MCP_CANCEL,
468
+ call_id: callId,
469
+ };
470
+ }
471
+
462
472
  export function reverseRegister({ username, capabilities = [], peerType = "host", shellBackend = "pty", supportsAttach = false, supportsReplay = false, supportsEcho = false, supportsTermSync = false, publicKey, seq, recordSignature } = {}) {
463
473
  return {
464
474
  type: MSG.REVERSE_REGISTER,
@@ -945,6 +955,7 @@ export const RELAY_FORWARDABLE = new Set([
945
955
  MSG.MCP_TOOLS,
946
956
  MSG.MCP_CALL,
947
957
  MSG.MCP_RESULT,
958
+ MSG.MCP_CANCEL,
948
959
  MSG.REVERSE_ACCEPT,
949
960
  MSG.REVERSE_REJECT,
950
961
  MSG.GUEST_JOIN,
@@ -24,7 +24,7 @@ import {
24
24
  generateNonce, verifyChallenge, fingerprint, importPublicKeyRaw,
25
25
  } from '../auth.mjs';
26
26
  import { FILE_CHUNK_BYTES, MAX_ATTACHMENTS } from './constants.mjs';
27
- import { MCP_CALL_ID_FEATURE } from '../client.mjs';
27
+ import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE } from '../client.mjs';
28
28
  import { RpcChannel, RPC_FEATURE, RPC_MAX_MESSAGE_PREFIX, rpcProtocolFeature } from '../rpc.mjs';
29
29
  import { sealFrame, openFrame, ROLE_TAGS } from '../e2e-frame.mjs';
30
30
  import { E2EResponder, E2E_FEATURE, E2E_SIGN_FEATURE } from '../e2e-exchange.mjs';
@@ -42,7 +42,7 @@ export const STREAM_ANNOUNCE = 'stream-announce';
42
42
  */
43
43
  export function hostFeatures(cfg, { dataStreams = true } = {}) {
44
44
  const features = dataStreams ? [STREAM_ANNOUNCE] : [];
45
- if (cfg.mcp) features.push(MCP_CALL_ID_FEATURE);
45
+ if (cfg.mcp) features.push(MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE);
46
46
  if (cfg.gateway) features.push('gateway');
47
47
  if (cfg.files) features.push('file-transfer', 'file-write', 'file-rename');
48
48
  // End-to-end encryption (#90) is the virtual-mode EncryptedFrame layer, so it is offered where there are no
@@ -117,6 +117,8 @@ export function createConnectionFactory(cfg) {
117
117
  const fileWrites = new Map();
118
118
  /** AbortControllers of in-flight MCP calls: aborted on disconnect, counted for the cap. */
119
119
  const mcpCalls = new Set();
120
+ /** call_id -> AbortController, for McpCancel. */
121
+ const mcpById = new Map();
120
122
  /** Channel ids awaiting their client-opened data stream, in OpenOk order. */
121
123
  const pendingStreams = [];
122
124
  const decoder = new FrameDecoder();
@@ -185,6 +187,7 @@ export function createConnectionFactory(cfg) {
185
187
  e2eSessions.clear();
186
188
  for (const c of mcpCalls) c.abort(new Error('connection closed'));
187
189
  mcpCalls.clear();
190
+ mcpById.clear();
188
191
  for (const w of fileWrites.values()) clearTimeout(w.timer);
189
192
  fileWrites.clear();
190
193
  try { qmux?.destroy(new Error(why)); } catch { /* already gone */ }
@@ -253,6 +256,7 @@ export function createConnectionFactory(cfg) {
253
256
  // Not awaited: the handler chain is serial, and a slow tool must not hold up
254
257
  // the next call (or a Close) behind it.
255
258
  case MSG.MCP_CALL: handleMcpCall(m); return;
259
+ case MSG.MCP_CANCEL: if (typeof m.call_id === 'string') mcpById.get(m.call_id)?.abort(new Error('cancelled by the caller')); return;
256
260
  default:
257
261
  if (typeof m.type === 'string' && Object.hasOwn(cfg.extensions ?? {}, m.type) && typeof cfg.extensions[m.type] === 'function') {
258
262
  try { await cfg.extensions[m.type](m, { username: state.username, fingerprint: state.fingerprint, send }); } catch (e) { log(`extension "${m.type}" threw: ${e.message}`); }
@@ -465,6 +469,7 @@ export function createConnectionFactory(cfg) {
465
469
 
466
470
  const abort = new AbortController();
467
471
  mcpCalls.add(abort);
472
+ if (callId !== undefined) mcpById.set(callId, abort);
468
473
  (async () => {
469
474
  const name = typeof m.tool === 'string' ? m.tool : '';
470
475
  const tool = name ? await cfg.mcp.find(name, state.username, principal()) : null;
@@ -493,7 +498,7 @@ export function createConnectionFactory(cfg) {
493
498
  }
494
499
  })()
495
500
  .catch((e) => log(`mcp call ${m.tool}: ${e.message}`))
496
- .finally(() => mcpCalls.delete(abort));
501
+ .finally(() => { mcpCalls.delete(abort); if (callId !== undefined && mcpById.get(callId) === abort) mcpById.delete(callId); });
497
502
  }
498
503
 
499
504
  // ── Open ──────────────────────────────────────────────────────────
@@ -881,10 +886,12 @@ export function createConnectionFactory(cfg) {
881
886
  if (direction === 'download') {
882
887
  let data;
883
888
  try { data = await cfg.files.readWhole(filePath); } catch (e) { return send(openFail({ reason: e.message })); }
884
- channels.set(channelId, { kill: () => channels.delete(channelId) });
889
+ let cancelled = false;
890
+ channels.set(channelId, { kill: () => { if (channels.delete(channelId)) { cancelled = true; log(`download ${filePath}: closed before completion`); } } });
885
891
  await send(openOk({ channelId, dataMode: 'virtual', capabilities: [] }));
886
892
  let off = 0;
887
893
  do {
894
+ if (cancelled) return;
888
895
  const end = Math.min(off + FILE_CHUNK_BYTES, data.byteLength);
889
896
  await send(fileChunk({ channelId, offset: off, data: data.subarray(off, end), isFinal: end >= data.byteLength, totalSize: data.byteLength }));
890
897
  off = end;
@@ -893,7 +900,9 @@ export function createConnectionFactory(cfg) {
893
900
  return;
894
901
  }
895
902
 
896
- const ch = { buf: null, kill: () => channels.delete(channelId) };
903
+ // Closed before the final chunk: the buffered bytes are dropped and nothing is written, so an
904
+ // aborted upload leaves the destination exactly as it was (the write itself is whole-file, see writeWhole).
905
+ const ch = { buf: null, kill: () => { if (channels.delete(channelId)) log(`upload ${filePath}: closed before completion, nothing written`); } };
897
906
  channels.set(channelId, ch);
898
907
  const done = async (code, why) => {
899
908
  if (why) log(`upload ${filePath}: ${why}`);
package/src/session.mjs CHANGED
@@ -173,6 +173,14 @@ export class WshSession {
173
173
  */
174
174
  onData = null;
175
175
 
176
+ /**
177
+ * Called when stderr data arrives, for a session opened with `stdio: 'pipes'`
178
+ * (a host advertising `exec-pipes` keeps stderr apart from stdout). Always
179
+ * null-safe to leave unset: it only ever fires for such sessions.
180
+ * @type {function(Uint8Array): void|null}
181
+ */
182
+ onStderr = null;
183
+
176
184
  /**
177
185
  * Called when the remote process exits.
178
186
  * @type {function(number): void|null}
@@ -246,10 +254,12 @@ export class WshSession {
246
254
  */
247
255
  constructor(
248
256
  transport, channelId, streamIds, kind,
249
- { dataMode = 'stream', capabilities = [], sessionId, resumeToken } = {}
257
+ { dataMode = 'stream', capabilities = [], sessionId, resumeToken, stderrChannelId } = {}
250
258
  ) {
251
259
  this.#transport = transport;
252
260
  this.channelId = channelId;
261
+ /** Channel id carrying stderr for a `stdio: 'pipes'` session, else undefined. */
262
+ this.stderrChannelId = Number.isSafeInteger(stderrChannelId) ? stderrChannelId : undefined;
253
263
  this.#streamIds = streamIds;
254
264
  this.kind = kind;
255
265
  this.id = String(channelId);
@@ -536,6 +546,12 @@ export class WshSession {
536
546
  if (this.#virtualBackend === null) {
537
547
  throw new Error('Session not yet activated — virtual backend unavailable');
538
548
  }
549
+ if (this.#stdinClosed) {
550
+ throw new Error('Cannot write to a session whose stdin is closed');
551
+ }
552
+ // A zero-length SessionData is the EOF signal on a pipes session; an empty
553
+ // write must never be mistaken for it.
554
+ if (this.#capabilities.includes('stdin-eof') && (typeof data === 'string' ? data.length === 0 : data.byteLength === 0)) return;
539
555
  if (this.#e2eKey !== null) {
540
556
  const bytes = typeof data === 'string' ? textEncoder.encode(data) : data;
541
557
  const counter = this.#e2eSendCounter++;
@@ -586,8 +602,21 @@ export class WshSession {
586
602
  async closeStdin() {
587
603
  if (this.#stdinClosed) return;
588
604
  if (this.#state === STATE_CLOSED) return;
605
+ if (this.#dataMode === 'virtual' && this.#capabilities.includes('stdin-eof')) {
606
+ // Pipes exec on a host that granted `stdio: 'pipes'`: a zero-length
607
+ // SessionData is the EOF (spec Open.stdio / OpenOk.stderr_channel_id).
608
+ if (this.#virtualBackend === null) {
609
+ throw new Error('Session not yet activated — virtual backend unavailable');
610
+ }
611
+ if (this.#e2eKey !== null) {
612
+ throw new Error('closeStdin() is not supported on an end-to-end encrypted virtual session');
613
+ }
614
+ this.#stdinClosed = true;
615
+ await this.#virtualBackend.write(new Uint8Array(0));
616
+ return;
617
+ }
589
618
  if (this.#dataMode !== 'stream') {
590
- throw new Error('closeStdin() needs a stream-mode session; this session\'s host carries stdin as control messages, which have no EOF');
619
+ throw new Error('closeStdin() needs a stream-mode session or a host advertising "exec-pipes"; this session\'s host carries stdin as control messages, which have no EOF');
591
620
  }
592
621
  if (this.#stdinWriter === null) {
593
622
  throw new Error('Session not yet bound — stdin writer unavailable');
@@ -715,6 +744,16 @@ export class WshSession {
715
744
  _handleControlMessage(msg) {
716
745
  switch (msg.type) {
717
746
  case MSG.SESSION_DATA: {
747
+ if (this.stderrChannelId !== undefined && msg.channel_id === this.stderrChannelId) {
748
+ if (msg.data && msg.data.byteLength > 0) {
749
+ try {
750
+ this.onStderr?.(msg.data);
751
+ } catch (err) {
752
+ console.error('[wsh:session] onStderr handler error:', err);
753
+ }
754
+ }
755
+ break;
756
+ }
718
757
  if (msg.data && msg.data.byteLength > 0) {
719
758
  this.#virtualBackend?.pushData(msg.data);
720
759
  try {