@johnhenry/wsh 0.33.0 → 0.34.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/README.md +16 -2
- package/package.json +1 -1
- package/src/client.mjs +172 -46
- package/src/file-transfer.mjs +4 -3
- package/src/index.d.ts +32 -3
- package/src/index.mjs +2 -2
- package/src/mcp-bridge.mjs +45 -9
- package/src/messages.gen.mjs +9 -0
- package/src/server/connection.mjs +14 -5
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
|
-
- **
|
|
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 --
|
|
@@ -606,6 +606,20 @@ await session.write('ls\n'); // and it is the same process
|
|
|
606
606
|
only the owner re-attaches as a controller; everyone else needs the token.
|
|
607
607
|
Sessions are in-memory: a server restart ends them all.
|
|
608
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
|
+
|
|
609
623
|
### MCP tools
|
|
610
624
|
|
|
611
625
|
`createWshServer({ mcp })` answers `McpDiscover` and `McpCall`, so the stock
|
|
@@ -1033,7 +1047,7 @@ so options the platform gains later need no change here.
|
|
|
1033
1047
|
|
|
1034
1048
|
| Export | Description |
|
|
1035
1049
|
|--------|-------------|
|
|
1036
|
-
| `MSG` |
|
|
1050
|
+
| `MSG` | 99 message type constants (hex opcodes) |
|
|
1037
1051
|
| `CHANNEL_KIND` | Channel types: `pty`, `exec`, `meta`, `file`, `tcp`, `udp`, `job` |
|
|
1038
1052
|
| `AUTH_METHOD` | Auth methods: `pubkey`, `password` |
|
|
1039
1053
|
| `cborEncode` / `cborDecode` | CBOR codec (maps, arrays, strings, ints, bytes, bools, null, floats) |
|
package/package.json
CHANGED
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,6 +75,20 @@ 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
|
|
@@ -804,7 +818,7 @@ export class WshClient {
|
|
|
804
818
|
|
|
805
819
|
/**
|
|
806
820
|
* List locally tracked sessions with their current state.
|
|
807
|
-
* @returns {Array<{channelId: number, kind: string, state: string}>}
|
|
821
|
+
* @returns {Array<{channelId: number, kind: string, state: string, sessionId?: string}>}
|
|
808
822
|
*/
|
|
809
823
|
listSessions() {
|
|
810
824
|
const result = [];
|
|
@@ -813,11 +827,30 @@ export class WshClient {
|
|
|
813
827
|
channelId,
|
|
814
828
|
kind: session.kind,
|
|
815
829
|
state: session.state,
|
|
830
|
+
sessionId: session.sessionId,
|
|
816
831
|
});
|
|
817
832
|
}
|
|
818
833
|
return result;
|
|
819
834
|
}
|
|
820
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
|
+
|
|
821
854
|
/**
|
|
822
855
|
* Attach to an existing remote session (collaborative or read-only).
|
|
823
856
|
*
|
|
@@ -1420,42 +1453,86 @@ export class WshClient {
|
|
|
1420
1453
|
* @param {string} remotePath - Destination path on the server
|
|
1421
1454
|
* @param {object} [opts]
|
|
1422
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).
|
|
1423
1461
|
*/
|
|
1424
|
-
async upload(blob, remotePath, { onProgress } = {}) {
|
|
1462
|
+
async upload(blob, remotePath, { onProgress, signal } = {}) {
|
|
1425
1463
|
this.#assertAuthenticated('upload');
|
|
1426
|
-
|
|
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) {
|
|
1427
1504
|
const data = blob instanceof Blob
|
|
1428
1505
|
? new Uint8Array(await blob.arrayBuffer())
|
|
1429
1506
|
: blob;
|
|
1430
1507
|
const total = data.byteLength;
|
|
1431
1508
|
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
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'}`);
|
|
1459
1536
|
}
|
|
1460
1537
|
}
|
|
1461
1538
|
|
|
@@ -1472,11 +1549,16 @@ export class WshClient {
|
|
|
1472
1549
|
* @param {object} [opts]
|
|
1473
1550
|
* @param {function({received: number, total: number}): void} [opts.onProgress]
|
|
1474
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.
|
|
1475
1554
|
* @returns {Promise<Uint8Array>} File contents
|
|
1476
1555
|
*/
|
|
1477
|
-
async download(remotePath, { onProgress, timeout = DEFAULT_OPEN_TIMEOUT } = {}) {
|
|
1556
|
+
async download(remotePath, { onProgress, timeout = DEFAULT_OPEN_TIMEOUT, signal } = {}) {
|
|
1478
1557
|
this.#assertAuthenticated('download');
|
|
1479
|
-
|
|
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 });
|
|
1480
1562
|
|
|
1481
1563
|
try {
|
|
1482
1564
|
let data = null;
|
|
@@ -1484,6 +1566,7 @@ export class WshClient {
|
|
|
1484
1566
|
|
|
1485
1567
|
while (true) {
|
|
1486
1568
|
const chunk = await session._readFileChunk();
|
|
1569
|
+
if (signal?.aborted) throw abortError(signal);
|
|
1487
1570
|
if (chunk === null) {
|
|
1488
1571
|
throw new Error('Download failed: connection closed before the transfer completed (truncated)');
|
|
1489
1572
|
}
|
|
@@ -1501,7 +1584,11 @@ export class WshClient {
|
|
|
1501
1584
|
return data;
|
|
1502
1585
|
}
|
|
1503
1586
|
}
|
|
1587
|
+
} catch (e) {
|
|
1588
|
+
if (signal?.aborted) throw abortError(signal);
|
|
1589
|
+
throw e;
|
|
1504
1590
|
} finally {
|
|
1591
|
+
signal?.removeEventListener('abort', stop);
|
|
1505
1592
|
await session.close().catch(() => {});
|
|
1506
1593
|
}
|
|
1507
1594
|
}
|
|
@@ -1541,31 +1628,47 @@ export class WshClient {
|
|
|
1541
1628
|
* @param {object} [args={}] - Tool arguments. Defaults to `{}` rather
|
|
1542
1629
|
* than being omitted: `McpCall.arguments` is a required wire field,
|
|
1543
1630
|
* and a tool that takes no arguments is an ordinary thing to call.
|
|
1544
|
-
* @param {number} [
|
|
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).
|
|
1545
1636
|
* @returns {Promise<*>} Tool result
|
|
1546
1637
|
*/
|
|
1547
|
-
async callTool(name, args = {},
|
|
1638
|
+
async callTool(name, args = {}, options = 30_000) {
|
|
1548
1639
|
this.#assertAuthenticated('callTool');
|
|
1549
1640
|
requireArgs('callTool', { name });
|
|
1641
|
+
const { timeout = 30_000, signal } = typeof options === 'number' ? { timeout: options } : (options ?? {});
|
|
1642
|
+
if (signal?.aborted) throw abortError(signal);
|
|
1550
1643
|
|
|
1551
1644
|
if (this.hasFeature(MCP_CALL_ID_FEATURE)) {
|
|
1552
|
-
return this.#callToolCorrelated(name, args, timeout);
|
|
1645
|
+
return this.#callToolCorrelated(name, args, timeout, signal);
|
|
1553
1646
|
}
|
|
1554
1647
|
// No correlation available: serialise so a concurrent caller cannot be
|
|
1555
|
-
// 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.
|
|
1556
1651
|
const run = this.#mcpQueue.then(
|
|
1557
|
-
() => this.#callToolCorrelated(name, args, timeout),
|
|
1558
|
-
() => this.#callToolCorrelated(name, args, timeout),
|
|
1652
|
+
() => this.#callToolCorrelated(name, args, timeout, undefined, signal),
|
|
1653
|
+
() => this.#callToolCorrelated(name, args, timeout, undefined, signal),
|
|
1559
1654
|
);
|
|
1560
1655
|
this.#mcpQueue = run.then(() => undefined, () => undefined);
|
|
1561
|
-
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); }
|
|
1562
1663
|
}
|
|
1563
1664
|
|
|
1564
1665
|
/**
|
|
1565
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.
|
|
1566
1668
|
* @private
|
|
1567
1669
|
*/
|
|
1568
|
-
async #callToolCorrelated(name, args, timeout) {
|
|
1670
|
+
async #callToolCorrelated(name, args, timeout, signal, skipIfAborted) {
|
|
1671
|
+
if (skipIfAborted?.aborted) throw abortError(skipIfAborted);
|
|
1569
1672
|
const correlate = this.hasFeature(MCP_CALL_ID_FEATURE);
|
|
1570
1673
|
// Only sent when the peer understands it: McpCallPayload is
|
|
1571
1674
|
// deny_unknown_fields on the Rust side, so an unsolicited call_id would
|
|
@@ -1576,7 +1679,7 @@ export class WshClient {
|
|
|
1576
1679
|
mcpCallMsg({ tool: name, arguments: args, callId })
|
|
1577
1680
|
);
|
|
1578
1681
|
|
|
1579
|
-
const
|
|
1682
|
+
const wait = this.#waitForMessage(
|
|
1580
1683
|
[MSG.MCP_RESULT],
|
|
1581
1684
|
timeout,
|
|
1582
1685
|
`Timed out waiting for MCP tool result (${name})`,
|
|
@@ -1585,9 +1688,18 @@ export class WshClient {
|
|
|
1585
1688
|
callId === undefined
|
|
1586
1689
|
? undefined
|
|
1587
1690
|
: (msg) => msg.call_id === undefined || msg.call_id === callId,
|
|
1691
|
+
signal,
|
|
1588
1692
|
);
|
|
1589
|
-
|
|
1590
|
-
|
|
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
|
+
}
|
|
1591
1703
|
}
|
|
1592
1704
|
|
|
1593
1705
|
// ── Suspend / Restart ───────────────────────────────────────────────
|
|
@@ -2900,20 +3012,34 @@ export class WshClient {
|
|
|
2900
3012
|
* @returns {Promise<object>}
|
|
2901
3013
|
* @private
|
|
2902
3014
|
*/
|
|
2903
|
-
#waitForMessage(types, timeout, timeoutMessage, match) {
|
|
3015
|
+
#waitForMessage(types, timeout, timeoutMessage, match, signal) {
|
|
2904
3016
|
const typeArr = Array.isArray(types) ? types : [types];
|
|
2905
3017
|
|
|
2906
3018
|
return new Promise((resolve, reject) => {
|
|
2907
3019
|
const timer = setTimeout(() => {
|
|
2908
3020
|
// Remove this waiter.
|
|
2909
3021
|
this.#removeWaiter(key, waiter);
|
|
3022
|
+
signal?.removeEventListener('abort', onAbort);
|
|
2910
3023
|
reject(new Error(timeoutMessage));
|
|
2911
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
|
+
}
|
|
2912
3034
|
|
|
2913
3035
|
// `match` lets a waiter claim only the reply that belongs to it --
|
|
2914
3036
|
// correlation, rather than "first waiter of this type wins". Waiters
|
|
2915
3037
|
// without one match on type alone, as before.
|
|
2916
|
-
const waiter = {
|
|
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
|
+
};
|
|
2917
3043
|
|
|
2918
3044
|
// For multi-type waiting, use a synthetic key.
|
|
2919
3045
|
const key = typeArr.length === 1
|
package/src/file-transfer.mjs
CHANGED
|
@@ -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,6 +238,9 @@ 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
|
|
@@ -559,6 +562,11 @@ export function mcpCall(opts?: {
|
|
|
559
562
|
callId?: string;
|
|
560
563
|
}): WshMessage;
|
|
561
564
|
|
|
565
|
+
export function mcpCancel(opts?: {
|
|
566
|
+
/** The `call_id` of the McpCall to stop. */
|
|
567
|
+
callId?: string;
|
|
568
|
+
}): WshMessage;
|
|
569
|
+
|
|
562
570
|
export function mcpResult(opts?: {
|
|
563
571
|
result?: unknown;
|
|
564
572
|
/** Echoed verbatim from the McpCall this answers. */
|
|
@@ -1964,6 +1972,8 @@ export interface WshSessionInfo {
|
|
|
1964
1972
|
channelId: number;
|
|
1965
1973
|
kind: string;
|
|
1966
1974
|
state: string;
|
|
1975
|
+
/** The server's session id, when the host assigned one (pty / exec). */
|
|
1976
|
+
sessionId?: string;
|
|
1967
1977
|
}
|
|
1968
1978
|
|
|
1969
1979
|
/** Peer information from reverse list. */
|
|
@@ -2169,6 +2179,12 @@ export class WshClient {
|
|
|
2169
2179
|
*/
|
|
2170
2180
|
listSessions(): WshSessionInfo[];
|
|
2171
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
|
+
|
|
2172
2188
|
/**
|
|
2173
2189
|
* Attach to an existing remote session (collaborative or read-only).
|
|
2174
2190
|
* Authorization is satisfied by EITHER `opts.token` OR the caller
|
|
@@ -2342,7 +2358,11 @@ export class WshClient {
|
|
|
2342
2358
|
/**
|
|
2343
2359
|
* Upload a blob to a remote path.
|
|
2344
2360
|
*/
|
|
2345
|
-
upload(blob: Blob | Uint8Array, remotePath: string, opts?: {
|
|
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>;
|
|
2346
2366
|
|
|
2347
2367
|
/**
|
|
2348
2368
|
* Download a file from a remote path.
|
|
@@ -2352,6 +2372,8 @@ export class WshClient {
|
|
|
2352
2372
|
opts?: {
|
|
2353
2373
|
onProgress?: (progress: { received: number; total: number }) => void;
|
|
2354
2374
|
timeout?: number;
|
|
2375
|
+
/** Rejects with an `AbortError` and closes the file channel; an already-aborted signal opens nothing. */
|
|
2376
|
+
signal?: AbortSignal;
|
|
2355
2377
|
},
|
|
2356
2378
|
): Promise<Uint8Array>;
|
|
2357
2379
|
|
|
@@ -2363,7 +2385,12 @@ export class WshClient {
|
|
|
2363
2385
|
/**
|
|
2364
2386
|
* Call an MCP tool on the remote server.
|
|
2365
2387
|
*/
|
|
2366
|
-
callTool(
|
|
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>;
|
|
2367
2394
|
|
|
2368
2395
|
/**
|
|
2369
2396
|
* Connect using an externally created transport.
|
|
@@ -2584,6 +2611,7 @@ export class WshFileTransfer {
|
|
|
2584
2611
|
opts?: {
|
|
2585
2612
|
onProgress?: (progress: WshFileUploadProgress) => void;
|
|
2586
2613
|
timeout?: number;
|
|
2614
|
+
signal?: AbortSignal;
|
|
2587
2615
|
},
|
|
2588
2616
|
): Promise<WshFileUploadResult>;
|
|
2589
2617
|
|
|
@@ -2595,6 +2623,7 @@ export class WshFileTransfer {
|
|
|
2595
2623
|
opts?: {
|
|
2596
2624
|
onProgress?: (progress: WshFileDownloadProgress) => void;
|
|
2597
2625
|
timeout?: number;
|
|
2626
|
+
signal?: AbortSignal;
|
|
2598
2627
|
},
|
|
2599
2628
|
): Promise<Uint8Array>;
|
|
2600
2629
|
|
|
@@ -2754,7 +2783,7 @@ export class WshMcpBridge {
|
|
|
2754
2783
|
call(
|
|
2755
2784
|
toolName: string,
|
|
2756
2785
|
args?: Record<string, unknown>,
|
|
2757
|
-
opts?: { timeout?: number },
|
|
2786
|
+
opts?: { timeout?: number; signal?: AbortSignal },
|
|
2758
2787
|
): Promise<WshMcpCallResult>;
|
|
2759
2788
|
|
|
2760
2789
|
/**
|
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, EXEC_PIPES_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';
|
package/src/mcp-bridge.mjs
CHANGED
|
@@ -6,13 +6,32 @@
|
|
|
6
6
|
* remote server. Tool specs are cached after discovery for efficient reuse.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import { MSG, mcpDiscover, mcpCall } from './messages.mjs';
|
|
9
|
+
import { MSG, mcpDiscover, mcpCall, mcpCancel } from './messages.mjs';
|
|
10
10
|
import { waitForControlMessage } from './control-listener.mjs';
|
|
11
|
-
import { MCP_CALL_ID_FEATURE } from './client.mjs';
|
|
11
|
+
import { MCP_CALL_ID_FEATURE, MCP_CANCEL_FEATURE } from './client.mjs';
|
|
12
12
|
|
|
13
13
|
/** Default timeout for MCP operations (15 seconds). */
|
|
14
14
|
const MCP_TIMEOUT_MS = 15_000;
|
|
15
15
|
|
|
16
|
+
function abortError(signal) {
|
|
17
|
+
const e = new DOMException('The operation was aborted', 'AbortError');
|
|
18
|
+
if (signal.reason !== undefined) e.cause = signal.reason;
|
|
19
|
+
return e;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Settle with `promise`, or reject with an AbortError the moment `signal` fires. */
|
|
23
|
+
function raceAbort(signal, promise) {
|
|
24
|
+
if (signal.aborted) return Promise.reject(abortError(signal));
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const onAbort = () => reject(abortError(signal));
|
|
27
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
28
|
+
promise.then(
|
|
29
|
+
(v) => { signal.removeEventListener('abort', onAbort); resolve(v); },
|
|
30
|
+
(e) => { signal.removeEventListener('abort', onAbort); reject(e); },
|
|
31
|
+
);
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
16
35
|
export class WshMcpBridge {
|
|
17
36
|
/** @type {object} WshClient reference. */
|
|
18
37
|
#client;
|
|
@@ -107,9 +126,12 @@ export class WshMcpBridge {
|
|
|
107
126
|
* @param {object} [args={}] - Arguments to pass to the tool
|
|
108
127
|
* @param {object} [opts]
|
|
109
128
|
* @param {number} [opts.timeout] - Timeout in ms (default 15s)
|
|
129
|
+
* @param {AbortSignal} [opts.signal] - Abort the call. Rejects with an `AbortError`; against a host advertising
|
|
130
|
+
* `mcp-cancel` the tool is told to stop too. An already-aborted signal sends nothing.
|
|
110
131
|
* @returns {Promise<{ success: boolean, output: *, error?: string }>}
|
|
111
132
|
*/
|
|
112
|
-
async call(toolName, args = {}, { timeout = MCP_TIMEOUT_MS } = {}) {
|
|
133
|
+
async call(toolName, args = {}, { timeout = MCP_TIMEOUT_MS, signal } = {}) {
|
|
134
|
+
if (signal?.aborted) throw abortError(signal);
|
|
113
135
|
if (!toolName || typeof toolName !== 'string') {
|
|
114
136
|
throw new Error('toolName is required');
|
|
115
137
|
}
|
|
@@ -121,14 +143,16 @@ export class WshMcpBridge {
|
|
|
121
143
|
);
|
|
122
144
|
}
|
|
123
145
|
|
|
124
|
-
if (this.#correlates()) return this.#callOnce(toolName, args, timeout);
|
|
146
|
+
if (this.#correlates()) return this.#callOnce(toolName, args, timeout, signal);
|
|
125
147
|
|
|
148
|
+
// Uncorrelated: an aborted caller stops waiting, but keeps its queue slot until the reply (or timeout) so the
|
|
149
|
+
// late reply cannot be handed to the next call.
|
|
126
150
|
const run = this.#queue.then(
|
|
127
|
-
() => this.#callOnce(toolName, args, timeout),
|
|
128
|
-
() => this.#callOnce(toolName, args, timeout),
|
|
151
|
+
() => (signal?.aborted ? Promise.reject(abortError(signal)) : this.#callOnce(toolName, args, timeout)),
|
|
152
|
+
() => (signal?.aborted ? Promise.reject(abortError(signal)) : this.#callOnce(toolName, args, timeout)),
|
|
129
153
|
);
|
|
130
154
|
this.#queue = run.then(() => undefined, () => undefined);
|
|
131
|
-
return run;
|
|
155
|
+
return signal ? raceAbort(signal, run) : run;
|
|
132
156
|
}
|
|
133
157
|
|
|
134
158
|
/** True when the connected server echoes call_id. @private */
|
|
@@ -137,7 +161,7 @@ export class WshMcpBridge {
|
|
|
137
161
|
}
|
|
138
162
|
|
|
139
163
|
/** @private */
|
|
140
|
-
async #callOnce(toolName, args, timeout) {
|
|
164
|
+
async #callOnce(toolName, args, timeout, signal) {
|
|
141
165
|
const callId = this.#correlates()
|
|
142
166
|
? `bridge-${++this.#callCounter}-${Date.now()}`
|
|
143
167
|
: undefined;
|
|
@@ -146,7 +170,7 @@ export class WshMcpBridge {
|
|
|
146
170
|
mcpCall({ tool: toolName, arguments: args, callId })
|
|
147
171
|
);
|
|
148
172
|
|
|
149
|
-
const
|
|
173
|
+
const waiting = this._waitForMessage(
|
|
150
174
|
(msg) => {
|
|
151
175
|
// ERROR carries no call_id and cannot be attributed to one call;
|
|
152
176
|
// it is taken by whichever call is waiting.
|
|
@@ -157,6 +181,18 @@ export class WshMcpBridge {
|
|
|
157
181
|
},
|
|
158
182
|
timeout
|
|
159
183
|
);
|
|
184
|
+
let response;
|
|
185
|
+
try {
|
|
186
|
+
response = signal ? await raceAbort(signal, waiting) : await waiting;
|
|
187
|
+
} catch (e) {
|
|
188
|
+
if (signal?.aborted && e?.name === 'AbortError') {
|
|
189
|
+
waiting.catch(() => {}); // its own timeout still fires; nobody is listening
|
|
190
|
+
if (callId !== undefined && this.#client?.hasFeature?.(MCP_CANCEL_FEATURE) === true) {
|
|
191
|
+
Promise.resolve(this.#client.sendControl(mcpCancel({ callId }))).catch(() => {});
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
throw e;
|
|
195
|
+
}
|
|
160
196
|
|
|
161
197
|
if (response.type === MSG.ERROR) {
|
|
162
198
|
return {
|
package/src/messages.gen.mjs
CHANGED
|
@@ -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,
|
|
@@ -461,6 +462,13 @@ export function mcpResult({ result, callId } = {}) {
|
|
|
461
462
|
return msg;
|
|
462
463
|
}
|
|
463
464
|
|
|
465
|
+
export function mcpCancel({ callId } = {}) {
|
|
466
|
+
return {
|
|
467
|
+
type: MSG.MCP_CANCEL,
|
|
468
|
+
call_id: callId,
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
|
|
464
472
|
export function reverseRegister({ username, capabilities = [], peerType = "host", shellBackend = "pty", supportsAttach = false, supportsReplay = false, supportsEcho = false, supportsTermSync = false, publicKey, seq, recordSignature } = {}) {
|
|
465
473
|
return {
|
|
466
474
|
type: MSG.REVERSE_REGISTER,
|
|
@@ -947,6 +955,7 @@ export const RELAY_FORWARDABLE = new Set([
|
|
|
947
955
|
MSG.MCP_TOOLS,
|
|
948
956
|
MSG.MCP_CALL,
|
|
949
957
|
MSG.MCP_RESULT,
|
|
958
|
+
MSG.MCP_CANCEL,
|
|
950
959
|
MSG.REVERSE_ACCEPT,
|
|
951
960
|
MSG.REVERSE_REJECT,
|
|
952
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
|
-
|
|
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
|
-
|
|
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}`);
|