@wonderwhy-er/desktop-commander 0.2.52 → 0.3.1-alpha.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/LICENSE +20 -20
- package/README.md +1152 -1152
- package/dist/bootstrap.js +0 -0
- package/dist/command-manager.d.ts +7 -2
- package/dist/command-manager.js +16 -11
- package/dist/config-field-definitions.js +0 -0
- package/dist/config-manager.d.ts +55 -3
- package/dist/config-manager.js +329 -87
- package/dist/config-recovery.d.ts +28 -0
- package/dist/config-recovery.js +81 -0
- package/dist/config.d.ts +1 -0
- package/dist/config.js +9 -0
- package/dist/custom-stdio.js +0 -0
- package/dist/data/onboarding-prompts.json +70 -70
- package/dist/error-handlers.js +0 -0
- package/dist/handlers/filesystem-handlers.d.ts +1 -1
- package/dist/handlers/filesystem-handlers.js +28 -18
- package/dist/handlers/search-answers.d.ts +58 -0
- package/dist/handlers/search-answers.js +172 -0
- package/dist/handlers/search-handlers.js +4 -92
- package/dist/index.js +14 -7
- package/dist/npm-scripts/remote.js +36 -22
- package/dist/remote-device/desktop-commander-integration.js +19 -25
- package/dist/remote-device/device.d.ts +14 -0
- package/dist/remote-device/device.js +137 -30
- package/dist/remote-device/diagnostics/device-log.d.ts +63 -0
- package/dist/remote-device/diagnostics/device-log.js +219 -0
- package/dist/remote-device/diagnostics/redact.d.ts +1 -0
- package/dist/remote-device/diagnostics/redact.js +76 -0
- package/dist/remote-device/diagnostics/report.d.ts +118 -0
- package/dist/remote-device/diagnostics/report.js +748 -0
- package/dist/remote-device/diagnostics/upload.d.ts +11 -0
- package/dist/remote-device/diagnostics/upload.js +59 -0
- package/dist/remote-device/remote-channel.d.ts +12 -0
- package/dist/remote-device/remote-channel.js +55 -8
- package/dist/remote-device/scripts/blocking-offline-update.js +133 -96
- package/dist/remote-device/transport-telemetry.d.ts +32 -0
- package/dist/remote-device/transport-telemetry.js +48 -0
- package/dist/search-manager.d.ts +239 -27
- package/dist/search-manager.js +746 -312
- package/dist/server.js +654 -621
- package/dist/setup-claude-server.js +942 -942
- package/dist/terminal-manager.d.ts +138 -21
- package/dist/terminal-manager.js +300 -215
- package/dist/tools/config.d.ts +1 -1
- package/dist/tools/config.js +21 -70
- package/dist/tools/edit.js +14 -6
- package/dist/tools/filesystem.d.ts +30 -6
- package/dist/tools/filesystem.js +246 -140
- package/dist/tools/fuzzySearch.js +9 -9
- package/dist/tools/improved-process-tools.d.ts +9 -3
- package/dist/tools/improved-process-tools.js +181 -78
- package/dist/tools/pdf/extract-images.d.ts +2 -0
- package/dist/tools/pdf/extract-images.js +4 -1
- package/dist/tools/pdf/index.d.ts +5 -3
- package/dist/tools/pdf/index.js +4 -3
- package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
- package/dist/tools/pdf/lib/pdf2md.js +12 -5
- package/dist/tools/pdf/manipulations.d.ts +12 -1
- package/dist/tools/pdf/manipulations.js +17 -4
- package/dist/tools/pdf/markdown.d.ts +96 -0
- package/dist/tools/pdf/markdown.js +485 -20
- package/dist/tools/pdf/utils.d.ts +2 -2
- package/dist/tools/pdf/utils.js +4 -4
- package/dist/tools/process.js +8 -5
- package/dist/tools/prompts.js +1 -1
- package/dist/tools/schemas.d.ts +1 -1
- package/dist/tools/schemas.js +15 -6
- package/dist/track-installation.js +387 -387
- package/dist/types.d.ts +1 -1
- package/dist/types.js +0 -0
- package/dist/ui/config-editor/config-editor-runtime.js +6 -6
- package/dist/ui/config-editor/index.html +13 -13
- package/dist/ui/config-editor/src/app.js +32 -45
- package/dist/ui/config-editor/src/array-modal.js +32 -32
- package/dist/ui/config-editor/styles.css +586 -586
- package/dist/ui/file-preview/index.html +16 -16
- package/dist/ui/file-preview/src/app.js +8 -8
- package/dist/ui/file-preview/src/document-layout.js +31 -31
- package/dist/ui/file-preview/src/document-outline.js +8 -8
- package/dist/ui/file-preview/src/markdown/conflict-dialog.js +33 -33
- package/dist/ui/file-preview/src/markdown/controller.js +9 -9
- package/dist/ui/file-preview/src/markdown/editor.js +31 -31
- package/dist/ui/file-preview/styles.css +1630 -1630
- package/dist/uninstall-claude-server.js +745 -745
- package/dist/utils/ab-test.js +27 -9
- package/dist/utils/atomic-write.d.ts +14 -0
- package/dist/utils/atomic-write.js +80 -0
- package/dist/utils/capture.d.ts +17 -1
- package/dist/utils/capture.js +177 -68
- package/dist/utils/exit-process.d.ts +24 -0
- package/dist/utils/exit-process.js +31 -0
- package/dist/utils/feature-flags.js +2 -1
- package/dist/utils/files/base.d.ts +3 -1
- package/dist/utils/files/binary.js +4 -4
- package/dist/utils/files/docx.d.ts +3 -0
- package/dist/utils/files/docx.js +24 -9
- package/dist/utils/files/excel.d.ts +10 -0
- package/dist/utils/files/excel.js +96 -36
- package/dist/utils/files/factory.d.ts +22 -1
- package/dist/utils/files/factory.js +59 -4
- package/dist/utils/files/image.d.ts +12 -4
- package/dist/utils/files/image.js +19 -8
- package/dist/utils/files/index.d.ts +5 -3
- package/dist/utils/files/index.js +4 -3
- package/dist/utils/files/pdf.js +18 -36
- package/dist/utils/files/text.d.ts +21 -5
- package/dist/utils/files/text.js +90 -86
- package/dist/utils/internal-facts.d.ts +3 -0
- package/dist/utils/internal-facts.js +23 -0
- package/dist/utils/lazy-package.d.ts +23 -0
- package/dist/utils/lazy-package.js +42 -0
- package/dist/utils/open-browser.js +2 -1
- package/dist/utils/process-detection.d.ts +24 -5
- package/dist/utils/process-detection.js +199 -89
- package/dist/utils/process-tree.d.ts +14 -0
- package/dist/utils/process-tree.js +223 -0
- package/dist/utils/rename.d.ts +9 -0
- package/dist/utils/rename.js +74 -0
- package/dist/utils/ripgrep-resolver.js +9 -14
- package/dist/utils/shell.d.ts +42 -0
- package/dist/utils/shell.js +187 -0
- package/dist/utils/system-info.js +99 -97
- package/dist/utils/trackTools.js +2 -1
- package/dist/utils/usageTracker.js +49 -49
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
- package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
- package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
- package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
- package/package.json +10 -3
- package/vendor/telemetry-contract/README.md +56 -0
- package/vendor/telemetry-contract/package.json +32 -0
- package/vendor/telemetry-contract/transport.d.ts +38 -0
- package/vendor/telemetry-contract/transport.js +164 -0
- package/vendor/telemetry-contract/transport.test.js +39 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** The signed-in user's id from ~/.desktop-commander-device/device.json, or null. */
|
|
2
|
+
export declare function savedUserId(home: string): string | null;
|
|
3
|
+
export interface UploadOptions {
|
|
4
|
+
/** From /api/mcp-info; null when the server names none, and then nothing is uploaded. */
|
|
5
|
+
diagnosticsUrl: string | null;
|
|
6
|
+
userId: string | null;
|
|
7
|
+
deviceId: string | null;
|
|
8
|
+
timeoutMs?: number;
|
|
9
|
+
}
|
|
10
|
+
/** POSTs the zip and resolves the report id; rejects with a short reason. */
|
|
11
|
+
export declare function uploadReport(zip: Buffer, options: UploadOptions): Promise<string>;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
/**
|
|
4
|
+
* Sends the diagnostics zip to Desktop Commander's diagnostics Worker, which
|
|
5
|
+
* stores it for 7 days and answers with a report id the user gives support.
|
|
6
|
+
*
|
|
7
|
+
* The address comes only from the server's /api/mcp-info `diagnosticsUrl`, so
|
|
8
|
+
* the Worker can move without a release. When the server names none, nothing
|
|
9
|
+
* is uploaded and the zip stays saved.
|
|
10
|
+
* The ids only sort the upload into a folder: the user id is the saved access
|
|
11
|
+
* token's `sub`, read locally like blocking-offline-update.js reads `exp`, and
|
|
12
|
+
* the device id is device.json's. Nothing is refreshed, nothing signs in, and
|
|
13
|
+
* device.json is only read.
|
|
14
|
+
*/
|
|
15
|
+
const UPLOAD_TIMEOUT_MS = 30000;
|
|
16
|
+
const ID_SHAPED = /^[A-Za-z0-9_-]{1,64}$/;
|
|
17
|
+
/** The longest piece of the Worker's error message that is shown. */
|
|
18
|
+
const MAX_MESSAGE_CHARS = 200;
|
|
19
|
+
/** The signed-in user's id from ~/.desktop-commander-device/device.json, or null. */
|
|
20
|
+
export function savedUserId(home) {
|
|
21
|
+
try {
|
|
22
|
+
const config = JSON.parse(fs.readFileSync(path.join(home, '.desktop-commander-device', 'device.json'), 'utf8'));
|
|
23
|
+
const token = config?.session?.access_token;
|
|
24
|
+
if (typeof token !== 'string')
|
|
25
|
+
return null;
|
|
26
|
+
const { sub } = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString('utf8'));
|
|
27
|
+
return typeof sub === 'string' && ID_SHAPED.test(sub) ? sub : null;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** POSTs the zip and resolves the report id; rejects with a short reason. */
|
|
34
|
+
export async function uploadReport(zip, options) {
|
|
35
|
+
const url = options.diagnosticsUrl;
|
|
36
|
+
if (!url)
|
|
37
|
+
throw new Error('the server named no upload address');
|
|
38
|
+
const headers = { 'Content-Type': 'application/zip' };
|
|
39
|
+
if (options.userId)
|
|
40
|
+
headers['X-DC-User-Id'] = options.userId;
|
|
41
|
+
if (options.deviceId)
|
|
42
|
+
headers['X-DC-Device-Id'] = options.deviceId;
|
|
43
|
+
const response = await fetch(url, {
|
|
44
|
+
method: 'POST',
|
|
45
|
+
headers,
|
|
46
|
+
body: new Uint8Array(zip),
|
|
47
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? UPLOAD_TIMEOUT_MS),
|
|
48
|
+
});
|
|
49
|
+
const body = await response.json().catch(() => null);
|
|
50
|
+
if (!response.ok) {
|
|
51
|
+
// The Worker answers errors as {code, message}: show its message, on one short line
|
|
52
|
+
const message = typeof body?.message === 'string' ? body.message.replace(/\s+/g, ' ').trim().slice(0, MAX_MESSAGE_CHARS) : '';
|
|
53
|
+
throw new Error(`the server answered ${response.status}${message ? `: ${message}` : ''}`);
|
|
54
|
+
}
|
|
55
|
+
const id = body?.id;
|
|
56
|
+
if (typeof id !== 'string' || !ID_SHAPED.test(id))
|
|
57
|
+
throw new Error('the server gave no report id');
|
|
58
|
+
return id;
|
|
59
|
+
}
|
|
@@ -65,6 +65,9 @@ export declare class RemoteChannel {
|
|
|
65
65
|
private presenceTracked;
|
|
66
66
|
/** Last capability value written (null = never), to avoid redundant writes. */
|
|
67
67
|
private transportCapableWritten;
|
|
68
|
+
/** Value of the last capability write still queued or in flight; null once the queue is idle. */
|
|
69
|
+
private transportCapableQueued;
|
|
70
|
+
private capabilityWriteChain;
|
|
68
71
|
/** Monotonic start of a Presence-only degradation while broadcast remains joined. */
|
|
69
72
|
private presenceFailureStartedAt;
|
|
70
73
|
/** Re-entrancy guard: on a wedged socket each track() buffers for the full
|
|
@@ -146,8 +149,17 @@ export declare class RemoteChannel {
|
|
|
146
149
|
* Advertise (or withdraw) the broadcast capability. Only true while genuinely
|
|
147
150
|
* reachable that way — the server fails dispatch fast without it and picks
|
|
148
151
|
* the offline-sweep tier from it, so every change must re-arm the heartbeat.
|
|
152
|
+
*
|
|
153
|
+
* Writes are queued, like the status writes. A withdrawal the recreate stops
|
|
154
|
+
* waiting for still lands: compared with the last landed value, a re-publish
|
|
155
|
+
* in the meantime looked redundant and was skipped, and the withdrawal then
|
|
156
|
+
* left a device that claims to be online without the flag. Resolves with
|
|
157
|
+
* whether the row holds `capable` once this write is done.
|
|
149
158
|
*/
|
|
150
159
|
private setTransportCapable;
|
|
160
|
+
private writeTransportCapable;
|
|
161
|
+
/** Aborts one write to this device's row after DEVICE_ROW_WRITE_TIMEOUT_MS (a method, so tests can shorten it). */
|
|
162
|
+
private deviceRowWriteSignal;
|
|
151
163
|
/** Create and subscribe the private channel (initial join and recreation). */
|
|
152
164
|
private createChannel;
|
|
153
165
|
/**
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createClient } from '@supabase/supabase-js';
|
|
2
2
|
import { captureRemote } from '../utils/capture.js';
|
|
3
|
+
import { observeTransport } from './transport-telemetry.js';
|
|
3
4
|
import { VERSION } from '../version.js';
|
|
4
5
|
const NUL_CHAR = String.fromCharCode(0);
|
|
5
6
|
const NUL_RE = new RegExp(NUL_CHAR, 'g');
|
|
@@ -79,6 +80,11 @@ const TRANSPORT_WITHDRAW_AFTER_ATTEMPTS = 3;
|
|
|
79
80
|
// Cap on the withdrawal write; it runs in a catch block RECREATE_TIMEOUT_MS
|
|
80
81
|
// does not cover.
|
|
81
82
|
const CAPABILITY_WRITE_TIMEOUT_MS = 5000;
|
|
83
|
+
// Cap on one write to this device's row (capability, status), after which it
|
|
84
|
+
// is aborted. A PATCH sent down a half-open connection is otherwise answered
|
|
85
|
+
// only by fetch's own 300 s headers timeout, and the write queue behind it,
|
|
86
|
+
// with the presence publish waiting on that queue, waits as long.
|
|
87
|
+
const DEVICE_ROW_WRITE_TIMEOUT_MS = 10000;
|
|
82
88
|
// Cap on the shutdown session fetch, which races device.ts's 5s force-exit.
|
|
83
89
|
const OFFLINE_SESSION_TIMEOUT_MS = 500;
|
|
84
90
|
// realtime-js parks in 'disconnecting' for ~100ms after a disconnect and
|
|
@@ -185,6 +191,10 @@ export class RemoteChannel {
|
|
|
185
191
|
this.presenceTracked = false;
|
|
186
192
|
/** Last capability value written (null = never), to avoid redundant writes. */
|
|
187
193
|
this.transportCapableWritten = null;
|
|
194
|
+
/** Value of the last capability write still queued or in flight; null once the queue is idle. */
|
|
195
|
+
this.transportCapableQueued = null;
|
|
196
|
+
// Single-slot queue keeping capability writes in order (see setTransportCapable).
|
|
197
|
+
this.capabilityWriteChain = Promise.resolve();
|
|
188
198
|
/** Monotonic start of a Presence-only degradation while broadcast remains joined. */
|
|
189
199
|
this.presenceFailureStartedAt = null;
|
|
190
200
|
/** Re-entrancy guard: on a wedged socket each track() buffers for the full
|
|
@@ -659,20 +669,44 @@ export class RemoteChannel {
|
|
|
659
669
|
* Advertise (or withdraw) the broadcast capability. Only true while genuinely
|
|
660
670
|
* reachable that way — the server fails dispatch fast without it and picks
|
|
661
671
|
* the offline-sweep tier from it, so every change must re-arm the heartbeat.
|
|
672
|
+
*
|
|
673
|
+
* Writes are queued, like the status writes. A withdrawal the recreate stops
|
|
674
|
+
* waiting for still lands: compared with the last landed value, a re-publish
|
|
675
|
+
* in the meantime looked redundant and was skipped, and the withdrawal then
|
|
676
|
+
* left a device that claims to be online without the flag. Resolves with
|
|
677
|
+
* whether the row holds `capable` once this write is done.
|
|
662
678
|
*/
|
|
663
|
-
|
|
679
|
+
setTransportCapable(capable) {
|
|
680
|
+
if (!this.client || !this.deviceId)
|
|
681
|
+
return Promise.resolve(false);
|
|
682
|
+
// What the row holds once the queue drains — no redundant writes.
|
|
683
|
+
if ((this.transportCapableQueued ?? this.transportCapableWritten) === capable) {
|
|
684
|
+
return this.capabilityWriteChain.then(() => this.transportCapableWritten === capable);
|
|
685
|
+
}
|
|
686
|
+
this.transportCapableQueued = capable;
|
|
687
|
+
const write = this.capabilityWriteChain.then(() => this.writeTransportCapable(capable));
|
|
688
|
+
this.capabilityWriteChain = write;
|
|
689
|
+
write.then(() => {
|
|
690
|
+
if (this.capabilityWriteChain === write)
|
|
691
|
+
this.transportCapableQueued = null;
|
|
692
|
+
});
|
|
693
|
+
return write;
|
|
694
|
+
}
|
|
695
|
+
async writeTransportCapable(capable) {
|
|
664
696
|
if (!this.client || !this.deviceId)
|
|
665
697
|
return false;
|
|
666
|
-
if (this.transportCapableWritten === capable)
|
|
667
|
-
return true; // no redundant writes
|
|
668
698
|
try {
|
|
669
699
|
const capabilities = this.capabilitiesPayload(capable);
|
|
670
700
|
const { error } = await this.client
|
|
671
701
|
.from('mcp_devices')
|
|
672
702
|
.update({ capabilities })
|
|
673
|
-
.eq('id', this.deviceId)
|
|
703
|
+
.eq('id', this.deviceId)
|
|
704
|
+
.abortSignal(this.deviceRowWriteSignal());
|
|
674
705
|
if (error) {
|
|
675
706
|
console.error('[DEBUG] Failed to update transport capability:', error.message);
|
|
707
|
+
// An aborted write may still land: what the row holds is
|
|
708
|
+
// unknown, so the next write of either value is not skipped.
|
|
709
|
+
this.transportCapableWritten = null;
|
|
676
710
|
return false;
|
|
677
711
|
}
|
|
678
712
|
this.transportCapableWritten = capable;
|
|
@@ -688,10 +722,15 @@ export class RemoteChannel {
|
|
|
688
722
|
}
|
|
689
723
|
catch (error) {
|
|
690
724
|
console.error('[DEBUG] Transport capability update threw:', error?.message);
|
|
725
|
+
this.transportCapableWritten = null;
|
|
691
726
|
return false;
|
|
692
727
|
}
|
|
693
728
|
return true;
|
|
694
729
|
}
|
|
730
|
+
/** Aborts one write to this device's row after DEVICE_ROW_WRITE_TIMEOUT_MS (a method, so tests can shorten it). */
|
|
731
|
+
deviceRowWriteSignal() {
|
|
732
|
+
return AbortSignal.timeout(DEVICE_ROW_WRITE_TIMEOUT_MS);
|
|
733
|
+
}
|
|
695
734
|
/** Create and subscribe the private channel (initial join and recreation). */
|
|
696
735
|
createChannel() {
|
|
697
736
|
return new Promise((resolve, reject) => {
|
|
@@ -713,6 +752,10 @@ export class RemoteChannel {
|
|
|
713
752
|
}
|
|
714
753
|
})
|
|
715
754
|
.on('broadcast', { event: 'new_call' }, ({ payload }) => {
|
|
755
|
+
if (!this.shuttingDown) {
|
|
756
|
+
observeTransport({ stage: 'received', payload, deviceId: this.deviceId,
|
|
757
|
+
userId: this.user?.id, transport: 'broadcast' });
|
|
758
|
+
}
|
|
716
759
|
this.onDoorbell(payload).catch((e) => {
|
|
717
760
|
console.error('[DEBUG] Doorbell handling failed:', e?.message);
|
|
718
761
|
});
|
|
@@ -1117,8 +1160,9 @@ export class RemoteChannel {
|
|
|
1117
1160
|
await this.withTimeout(() => this.setTransportCapable(false), CAPABILITY_WRITE_TIMEOUT_MS, 'withdrawTransportCapability');
|
|
1118
1161
|
}
|
|
1119
1162
|
catch (withdrawErr) {
|
|
1120
|
-
// The
|
|
1121
|
-
//
|
|
1163
|
+
// The write stays queued, in order with any re-publish after
|
|
1164
|
+
// it, and ends within DEVICE_ROW_WRITE_TIMEOUT_MS; the flag
|
|
1165
|
+
// only advances on a confirmed write.
|
|
1122
1166
|
console.debug(`[DEBUG] Capability withdrawal did not complete: ${withdrawErr?.message}`);
|
|
1123
1167
|
}
|
|
1124
1168
|
}
|
|
@@ -1391,7 +1435,8 @@ export class RemoteChannel {
|
|
|
1391
1435
|
const { error } = await this.client
|
|
1392
1436
|
.from('mcp_devices')
|
|
1393
1437
|
.update({ status: status, last_seen: new Date().toISOString() })
|
|
1394
|
-
.eq('id', deviceId)
|
|
1438
|
+
.eq('id', deviceId)
|
|
1439
|
+
.abortSignal(this.deviceRowWriteSignal());
|
|
1395
1440
|
if (error) {
|
|
1396
1441
|
console.error(`[DEBUG] Failed to set status ${status}:`, error.message);
|
|
1397
1442
|
if (status == "online") {
|
|
@@ -1451,7 +1496,9 @@ export class RemoteChannel {
|
|
|
1451
1496
|
const scriptPath = path.join(__dirname, 'scripts', 'blocking-offline-update.js');
|
|
1452
1497
|
console.debug('[DEBUG] Spawning blocking update script:', scriptPath);
|
|
1453
1498
|
console.debug('[DEBUG] Using node executable:', process.execPath);
|
|
1454
|
-
|
|
1499
|
+
// The node running this device, by its full path: a bare 'node' is
|
|
1500
|
+
// looked up in the working folder first on Windows
|
|
1501
|
+
const result = spawnSync(process.execPath, [
|
|
1455
1502
|
scriptPath,
|
|
1456
1503
|
deviceId,
|
|
1457
1504
|
supabaseUrl,
|
|
@@ -1,96 +1,133 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Blocking script to update device status to offline
|
|
5
|
-
* Runs synchronously during shutdown to ensure DB update completes
|
|
6
|
-
*
|
|
7
|
-
* Usage: node blocking-offline-update.js <deviceId> <supabaseUrl> <supabaseKey> <accessToken> [refreshToken]
|
|
8
|
-
* Without a refreshToken only a still-valid accessToken can be used.
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
//
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
//
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
try {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Blocking script to update device status to offline
|
|
5
|
+
* Runs synchronously during shutdown to ensure DB update completes
|
|
6
|
+
*
|
|
7
|
+
* Usage: node blocking-offline-update.js <deviceId> <supabaseUrl> <supabaseKey> <accessToken> [refreshToken]
|
|
8
|
+
* Without a refreshToken only a still-valid accessToken can be used.
|
|
9
|
+
*
|
|
10
|
+
* Ends through exitProcess(), never process.exit(): process.exit() right after
|
|
11
|
+
* the update's fetch() can abort Node on Windows with exit code 0xC0000409
|
|
12
|
+
* (see src/utils/exit-process.ts), and the parent then reports a failed update.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { createClient } from '@supabase/supabase-js';
|
|
16
|
+
|
|
17
|
+
// The build copies this script to dist/remote-device/scripts/, next to the
|
|
18
|
+
// compiled dist/utils/exit-process.js. Run from a source checkout (npm run
|
|
19
|
+
// device:start starts it with plain node, without tsx) it loads the checkout's
|
|
20
|
+
// build, dist/utils/exit-process.js (npm install builds it), which works on
|
|
21
|
+
// every Node version. Without a build it falls back to
|
|
22
|
+
// src/utils/exit-process.ts, which only Node 22.18+ loads (by stripping types).
|
|
23
|
+
const ifNotFound = (importNext) => (error) => {
|
|
24
|
+
if (error.code !== 'ERR_MODULE_NOT_FOUND') throw error;
|
|
25
|
+
return importNext();
|
|
26
|
+
};
|
|
27
|
+
const { exitProcess, EXIT_GRACE_MS } = await import('../../utils/exit-process.js')
|
|
28
|
+
.catch(ifNotFound(() => import('../../../dist/utils/exit-process.js')))
|
|
29
|
+
.catch(ifNotFound(() => import('../../utils/exit-process.ts')));
|
|
30
|
+
|
|
31
|
+
// Parse command line arguments
|
|
32
|
+
const [deviceId, supabaseUrl, supabaseKey, accessToken, refreshToken] = process.argv.slice(2);
|
|
33
|
+
|
|
34
|
+
if (!deviceId || !supabaseUrl || !supabaseKey || !accessToken) {
|
|
35
|
+
console.error('❌ Missing required arguments');
|
|
36
|
+
console.error('Usage: node blocking-offline-update.js <deviceId> <supabaseUrl> <supabaseKey> <accessToken> [refreshToken]');
|
|
37
|
+
exitProcess(1);
|
|
38
|
+
} else {
|
|
39
|
+
await markDeviceOffline();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function markDeviceOffline() {
|
|
43
|
+
// The parent (setOffline() in remote-channel.ts) kills this script 3000ms
|
|
44
|
+
// after starting it. The update gets that time, counted from the start of
|
|
45
|
+
// the process, minus what the process may need to end once it gives up.
|
|
46
|
+
const PARENT_TIMEOUT_MS = 3000;
|
|
47
|
+
const deadline = new AbortController();
|
|
48
|
+
const timeoutHandle = setTimeout(() => {
|
|
49
|
+
console.error('⏱️ Timeout: Update took too long');
|
|
50
|
+
exitProcess(2); // Exit code 2 for timeout
|
|
51
|
+
// Ends the requests still in flight, which would keep the process alive
|
|
52
|
+
deadline.abort();
|
|
53
|
+
}, PARENT_TIMEOUT_MS - EXIT_GRACE_MS - performance.now());
|
|
54
|
+
|
|
55
|
+
const auth = { persistSession: false, autoRefreshToken: false };
|
|
56
|
+
const fetchBeforeDeadline = (input, init) => fetch(input, { ...init, signal: deadline.signal });
|
|
57
|
+
|
|
58
|
+
// Update device status to offline, stamping the exact shutdown moment so
|
|
59
|
+
// "last seen X ago" is precise for clean shutdowns (the periodic
|
|
60
|
+
// bookkeeping write only runs on the slow capable cadence).
|
|
61
|
+
// The token goes straight to PostgREST as a Bearer header: setSession()
|
|
62
|
+
// would first spend a GoTrue round trip of the budget re-validating it.
|
|
63
|
+
const markOffline = (token) => createClient(supabaseUrl, supabaseKey, {
|
|
64
|
+
auth,
|
|
65
|
+
global: { headers: { Authorization: `Bearer ${token}` }, fetch: fetchBeforeDeadline }
|
|
66
|
+
})
|
|
67
|
+
.from('mcp_devices')
|
|
68
|
+
.update({ status: 'offline', last_seen: new Date().toISOString() })
|
|
69
|
+
.eq('id', deviceId);
|
|
70
|
+
|
|
71
|
+
function tokenLooksLive(token) {
|
|
72
|
+
try {
|
|
73
|
+
const { exp } = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'));
|
|
74
|
+
return typeof exp === 'number' && exp * 1000 > Date.now() + 5000;
|
|
75
|
+
} catch {
|
|
76
|
+
// Not a JWT we can read: treat it as expired and refresh the session
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// refreshSession(), not setSession(): setSession() validates a token that
|
|
82
|
+
// looks live on this machine's clock via /user instead of refreshing it.
|
|
83
|
+
// Resolves with the new access token, or undefined after reporting why there is none.
|
|
84
|
+
async function refreshedToken() {
|
|
85
|
+
if (!refreshToken) {
|
|
86
|
+
console.error('❌ Auth error: access token not usable and no refresh token');
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
const client = createClient(supabaseUrl, supabaseKey, { auth, global: { fetch: fetchBeforeDeadline } });
|
|
90
|
+
const { data, error: authError } = await client.auth.refreshSession({ refresh_token: refreshToken });
|
|
91
|
+
|
|
92
|
+
if (authError || !data.session) {
|
|
93
|
+
console.error('❌ Auth error:', authError?.message ?? 'no session returned');
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
return data.session.access_token;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Resolves with the exit code
|
|
100
|
+
async function update() {
|
|
101
|
+
try {
|
|
102
|
+
// An expired token (e.g. the machine just woke) is refreshed first. A 401
|
|
103
|
+
// means it only looked live on this machine's clock: refresh and retry once.
|
|
104
|
+
let result = tokenLooksLive(accessToken) ? await markOffline(accessToken) : null;
|
|
105
|
+
if (!result || result.status === 401) {
|
|
106
|
+
const token = await refreshedToken();
|
|
107
|
+
if (!token) {
|
|
108
|
+
return 3; // Exit code 3 for auth error
|
|
109
|
+
}
|
|
110
|
+
result = await markOffline(token);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const { error } = result;
|
|
114
|
+
|
|
115
|
+
if (error) {
|
|
116
|
+
console.error('❌ DB update error:', error.message);
|
|
117
|
+
return 4; // Exit code 4 for DB error
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
console.log('✓ Device marked as offline');
|
|
121
|
+
return 0; // Success
|
|
122
|
+
|
|
123
|
+
} catch (error) {
|
|
124
|
+
console.error('❌ Unexpected error:', error.message);
|
|
125
|
+
return 5; // Exit code 5 for unexpected error
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const code = await update();
|
|
130
|
+
clearTimeout(timeoutHandle);
|
|
131
|
+
// After a timeout the exit code stays 2 (only exitProcess()'s first call counts)
|
|
132
|
+
exitProcess(code);
|
|
133
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
type TransportObservation = ({
|
|
2
|
+
stage: 'received';
|
|
3
|
+
payload: any;
|
|
4
|
+
deviceId: string | null;
|
|
5
|
+
userId: string | undefined;
|
|
6
|
+
} | {
|
|
7
|
+
stage: string;
|
|
8
|
+
callId: string;
|
|
9
|
+
deviceId: string | null | undefined;
|
|
10
|
+
toolName?: string;
|
|
11
|
+
operation?: string;
|
|
12
|
+
operationId?: string;
|
|
13
|
+
}) & {
|
|
14
|
+
transport?: 'broadcast' | 'mqtt';
|
|
15
|
+
};
|
|
16
|
+
/** Record a device transport checkpoint without affecting command handling. */
|
|
17
|
+
export declare function observeTransport(input: TransportObservation): {
|
|
18
|
+
observation_id: `${string}-${string}-${string}-${string}-${string}`;
|
|
19
|
+
source_process_id: `${string}-${string}-${string}-${string}-${string}`;
|
|
20
|
+
schema_version: number;
|
|
21
|
+
timestamp_utc: string;
|
|
22
|
+
operation_id?: string | undefined;
|
|
23
|
+
operation?: string | undefined;
|
|
24
|
+
tool_name?: string | undefined;
|
|
25
|
+
notification_id?: string | undefined;
|
|
26
|
+
attempt_number?: number | undefined;
|
|
27
|
+
transport?: "broadcast" | "mqtt" | undefined;
|
|
28
|
+
call_id: string;
|
|
29
|
+
device_id: string;
|
|
30
|
+
stage: string;
|
|
31
|
+
} | null;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { sanitizeTransportEvent } from '@desktop-commander/telemetry-contract/transport';
|
|
3
|
+
import { captureTransport } from '../utils/capture.js';
|
|
4
|
+
const ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
5
|
+
const PROCESS_ID = randomUUID();
|
|
6
|
+
/** Record a device transport checkpoint without affecting command handling. */
|
|
7
|
+
export function observeTransport(input) {
|
|
8
|
+
try {
|
|
9
|
+
const timestamp_utc = new Date().toISOString();
|
|
10
|
+
const receipt = 'payload' in input;
|
|
11
|
+
const callId = receipt ? input.payload?.call_id : input.callId;
|
|
12
|
+
const deviceId = input.deviceId;
|
|
13
|
+
if (typeof callId !== 'string' || !ID.test(callId) ||
|
|
14
|
+
typeof deviceId !== 'string' || !ID.test(deviceId))
|
|
15
|
+
return null;
|
|
16
|
+
if (receipt && (input.payload.device_id !== deviceId || !input.userId ||
|
|
17
|
+
(input.payload.user_id !== undefined && input.payload.user_id !== input.userId)))
|
|
18
|
+
return null;
|
|
19
|
+
const observationId = randomUUID();
|
|
20
|
+
let operationId;
|
|
21
|
+
if (!receipt) {
|
|
22
|
+
operationId = input.stage === 'operation_start' ? observationId : input.operationId;
|
|
23
|
+
}
|
|
24
|
+
const event = {
|
|
25
|
+
call_id: callId,
|
|
26
|
+
device_id: deviceId,
|
|
27
|
+
stage: input.stage,
|
|
28
|
+
...(input.transport === 'broadcast' || input.transport === 'mqtt' ? { transport: input.transport } : {}),
|
|
29
|
+
...(input.transport === 'broadcast' ? {
|
|
30
|
+
notification_id: `${callId}:broadcast:1`, attempt_number: 1,
|
|
31
|
+
} : {}),
|
|
32
|
+
...(!receipt && typeof input.toolName === 'string' && input.toolName.length > 0 &&
|
|
33
|
+
input.toolName.length <= 128 ? { tool_name: input.toolName } : {}),
|
|
34
|
+
...(!receipt && input.operation ? { operation: input.operation } : {}),
|
|
35
|
+
...(operationId ? { operation_id: operationId } : {}),
|
|
36
|
+
observation_id: observationId,
|
|
37
|
+
source_process_id: PROCESS_ID,
|
|
38
|
+
schema_version: 1,
|
|
39
|
+
timestamp_utc,
|
|
40
|
+
};
|
|
41
|
+
void captureTransport(input.stage, sanitizeTransportEvent(input.stage, event));
|
|
42
|
+
return event;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
// Telemetry must never affect command handling.
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|