@wonderwhy-er/desktop-commander 0.2.52 → 0.3.1-alpha.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/dist/command-manager.d.ts +7 -2
- package/dist/command-manager.js +16 -11
- package/dist/config-manager.d.ts +49 -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/handlers/filesystem-handlers.d.ts +1 -1
- package/dist/handlers/filesystem-handlers.js +26 -16
- 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 +2 -3
- package/dist/remote-device/broadcast-analytics.d.ts +28 -0
- package/dist/remote-device/broadcast-analytics.js +41 -0
- 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/mqtt-enrollment.d.ts +16 -0
- package/dist/remote-device/mqtt-enrollment.js +162 -0
- package/dist/remote-device/mqtt-transport.d.ts +44 -0
- package/dist/remote-device/mqtt-transport.js +197 -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 +106 -69
- package/dist/remote-device/transport-analytics.d.ts +29 -0
- package/dist/remote-device/transport-analytics.js +44 -0
- 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 +44 -11
- 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 +12 -4
- package/dist/tools/filesystem.d.ts +30 -6
- package/dist/tools/filesystem.js +246 -140
- package/dist/tools/improved-process-tools.d.ts +9 -3
- package/dist/tools/improved-process-tools.js +171 -68
- 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/schemas.d.ts +1 -1
- package/dist/tools/schemas.js +15 -6
- package/dist/tools/search.d.ts +32 -0
- package/dist/tools/search.js +202 -0
- package/dist/types.d.ts +1 -1
- package/dist/ui/config-editor/config-editor-runtime.js +6 -6
- package/dist/ui/config-editor/src/app.js +2 -15
- 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/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 +93 -33
- 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 +9 -7
- package/dist/utils/trackTools.js +2 -1
- 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 +8 -2
- 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,197 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { connect } from 'mqtt';
|
|
3
|
+
// Ids become literal topic segments; reject separators and MQTT wildcards.
|
|
4
|
+
const ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
5
|
+
const CONNECT_TIMEOUT_MS = 10000;
|
|
6
|
+
/**
|
|
7
|
+
* Read opt-in connector settings for RemoteChannel registration/restoration.
|
|
8
|
+
* Return null for legacy installs; only explicit loopback development may bypass mutual TLS.
|
|
9
|
+
*/
|
|
10
|
+
export function readMqttConfig(env = process.env, credentials) {
|
|
11
|
+
if (env.MQTT_TRANSPORT_ENABLED !== 'true')
|
|
12
|
+
return null;
|
|
13
|
+
let url;
|
|
14
|
+
try {
|
|
15
|
+
url = new URL(env.MQTT_BROKER_URL || '');
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
throw new Error('MQTT_BROKER_URL must be a valid MQTT URL');
|
|
19
|
+
}
|
|
20
|
+
if (url.username || url.password || url.search || url.hash || (url.pathname && url.pathname !== '/')) {
|
|
21
|
+
throw new Error('MQTT_BROKER_URL must not contain credentials, paths, or query parameters');
|
|
22
|
+
}
|
|
23
|
+
// MQTT 3.1.1 matches the local broker and AWS pilot. Clean sessions avoid broker
|
|
24
|
+
// backlog replay; each reconnect below must obtain a fresh SUBACK before admission.
|
|
25
|
+
const options = {
|
|
26
|
+
protocolVersion: 4,
|
|
27
|
+
clean: true,
|
|
28
|
+
keepalive: 30,
|
|
29
|
+
connectTimeout: CONNECT_TIMEOUT_MS,
|
|
30
|
+
// Spread reconnects between connector processes after a shared network outage.
|
|
31
|
+
reconnectPeriod: 1000 + Math.floor(Math.random() * 1500),
|
|
32
|
+
resubscribe: false,
|
|
33
|
+
queueQoSZero: false,
|
|
34
|
+
};
|
|
35
|
+
if (url.protocol === 'mqtt:') {
|
|
36
|
+
if (env.MQTT_ALLOW_INSECURE_LOCAL !== 'true' ||
|
|
37
|
+
!['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)) {
|
|
38
|
+
throw new Error('Plain MQTT requires MQTT_ALLOW_INSECURE_LOCAL=true and a loopback broker');
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
else if (url.protocol === 'mqtts:') {
|
|
42
|
+
if (!credentials && (!env.MQTT_CERT_FILE || !env.MQTT_KEY_FILE)) {
|
|
43
|
+
throw new Error('TLS MQTT requires MQTT_CERT_FILE and MQTT_KEY_FILE');
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
// Enrollment supplies the locally held key directly; manual file configuration remains valid.
|
|
47
|
+
options.cert = credentials?.cert ?? readFileSync(env.MQTT_CERT_FILE);
|
|
48
|
+
options.key = credentials?.key ?? readFileSync(env.MQTT_KEY_FILE);
|
|
49
|
+
if (env.MQTT_CA_FILE)
|
|
50
|
+
options.ca = readFileSync(env.MQTT_CA_FILE);
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
throw new Error('Unable to read MQTT TLS files');
|
|
54
|
+
}
|
|
55
|
+
options.rejectUnauthorized = true;
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
throw new Error('MQTT_BROKER_URL must use mqtts:// or explicit loopback mqtt://');
|
|
59
|
+
}
|
|
60
|
+
return { url: url.toString(), options };
|
|
61
|
+
}
|
|
62
|
+
/** Match the server publisher's exact device topic without granting wildcard subscriptions. */
|
|
63
|
+
export function mqttDoorbellTopic(userId, deviceId) {
|
|
64
|
+
if (!ID.test(userId) || !ID.test(deviceId))
|
|
65
|
+
throw new Error('Invalid MQTT device identity');
|
|
66
|
+
return `dc/mqtt/v1/users/${userId}/devices/${deviceId}/new_call`;
|
|
67
|
+
}
|
|
68
|
+
/** A per-device subscription; payload validation precedes all database access. */
|
|
69
|
+
export class MqttDoorbellReceiver {
|
|
70
|
+
/** Bind verified registration identity and RemoteChannel's delivery/readiness callbacks once. */
|
|
71
|
+
constructor(config, userId, deviceId, onDoorbell, onReady) {
|
|
72
|
+
this.config = config;
|
|
73
|
+
this.userId = userId;
|
|
74
|
+
this.deviceId = deviceId;
|
|
75
|
+
this.onDoorbell = onDoorbell;
|
|
76
|
+
this.onReady = onReady;
|
|
77
|
+
this.client = null;
|
|
78
|
+
this.stopped = false;
|
|
79
|
+
this.ready = false;
|
|
80
|
+
this.cancelStart = null;
|
|
81
|
+
this.topic = mqttDoorbellTopic(userId, deviceId);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Connect once and resolve after QoS 1 SUBACK plus the readiness callback.
|
|
85
|
+
* MQTT.js owns socket reconnects; this receiver owns resubscription and admission.
|
|
86
|
+
*/
|
|
87
|
+
async start() {
|
|
88
|
+
if (this.client || this.stopped)
|
|
89
|
+
throw new Error('MQTT receiver already started or stopped');
|
|
90
|
+
// Log only the hostname: credentials and raw broker errors must stay out of logs.
|
|
91
|
+
console.log('[MQTT] Connecting to broker:', new URL(this.config.url).hostname);
|
|
92
|
+
const client = connect(this.config.url, {
|
|
93
|
+
...this.config.options,
|
|
94
|
+
// Stable identity also lets an AWS policy restrict this certificate's Connect permission.
|
|
95
|
+
clientId: `dc-device-${this.deviceId}`,
|
|
96
|
+
});
|
|
97
|
+
this.client = client;
|
|
98
|
+
await new Promise((resolve, reject) => {
|
|
99
|
+
let settled = false;
|
|
100
|
+
// Startup has several competing exits; settle once and always cancel its timer.
|
|
101
|
+
const finish = (error) => {
|
|
102
|
+
if (settled)
|
|
103
|
+
return;
|
|
104
|
+
settled = true;
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
this.cancelStart = null;
|
|
107
|
+
if (error)
|
|
108
|
+
reject(error);
|
|
109
|
+
else
|
|
110
|
+
resolve();
|
|
111
|
+
};
|
|
112
|
+
// A connected socket without a granted subscription must not hang device startup.
|
|
113
|
+
const timer = setTimeout(() => {
|
|
114
|
+
finish(new Error('MQTT connection/subscription timed out'));
|
|
115
|
+
void this.stop().catch(() => { });
|
|
116
|
+
}, this.config.options.connectTimeout ?? CONNECT_TIMEOUT_MS);
|
|
117
|
+
this.cancelStart = () => finish(new Error('MQTT receiver stopped'));
|
|
118
|
+
client.on('connect', () => {
|
|
119
|
+
if (this.stopped)
|
|
120
|
+
return;
|
|
121
|
+
// Run after every connection: a TCP connection alone cannot receive commands.
|
|
122
|
+
client.subscribe(this.topic, { qos: 1 }, (error, granted) => {
|
|
123
|
+
if (this.stopped || !client.connected)
|
|
124
|
+
return;
|
|
125
|
+
if (error || granted?.length !== 1 || granted[0].topic !== this.topic || granted[0].qos !== 1) {
|
|
126
|
+
finish(new Error('MQTT device subscription refused'));
|
|
127
|
+
void this.stop().catch(() => { });
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
// Reject downgraded/foreign grants above, then let RemoteChannel persist capability.
|
|
131
|
+
// Recheck after that await so a stop/close cannot resolve stale startup as ready.
|
|
132
|
+
this.ready = true;
|
|
133
|
+
void this.onReady(true).then(() => {
|
|
134
|
+
if (!this.stopped && this.ready) {
|
|
135
|
+
// Report usable command delivery only after the broker grants the subscription.
|
|
136
|
+
console.log('[MQTT] Connected and subscribed; ready for tool calls');
|
|
137
|
+
finish();
|
|
138
|
+
}
|
|
139
|
+
}).catch(() => {
|
|
140
|
+
finish(new Error('MQTT readiness update failed'));
|
|
141
|
+
void this.stop().catch(() => { });
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
// Withdraw local admission immediately; RemoteChannel serializes the durable flag update.
|
|
146
|
+
client.on('close', () => {
|
|
147
|
+
if (this.ready && !this.stopped) {
|
|
148
|
+
console.warn('[MQTT] Disconnected; waiting for reconnection');
|
|
149
|
+
}
|
|
150
|
+
this.ready = false;
|
|
151
|
+
void this.onReady(false).catch(() => { });
|
|
152
|
+
});
|
|
153
|
+
// MQTT.js reconnects after network faults. Never print TLS/broker errors,
|
|
154
|
+
// which can include certificate paths or broker-provided sensitive text.
|
|
155
|
+
client.on('error', () => { });
|
|
156
|
+
// Treat broker input as untrusted before RemoteChannel performs any database read.
|
|
157
|
+
// Reject retained backlog and oversized data before parsing, then enforce exact identity.
|
|
158
|
+
client.on('message', (topic, bytes, packet) => {
|
|
159
|
+
if (this.stopped || !this.ready || topic !== this.topic || packet.retain || bytes.length > 1024)
|
|
160
|
+
return;
|
|
161
|
+
let payload;
|
|
162
|
+
try {
|
|
163
|
+
payload = JSON.parse(bytes.toString('utf8'));
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (!payload || typeof payload !== 'object' || Object.keys(payload).length !== 4 ||
|
|
169
|
+
typeof payload.call_id !== 'string' || !ID.test(payload.call_id) ||
|
|
170
|
+
payload.user_id !== this.userId || payload.device_id !== this.deviceId ||
|
|
171
|
+
typeof payload.expires_at !== 'string')
|
|
172
|
+
return;
|
|
173
|
+
// Canonical UTC and a live deadline reject malformed/stale notifications; the row's
|
|
174
|
+
// independently stored deadline is checked again after RemoteChannel fetches it.
|
|
175
|
+
const expires = Date.parse(payload.expires_at);
|
|
176
|
+
if (!Number.isFinite(expires) || new Date(expires).toISOString() !== payload.expires_at ||
|
|
177
|
+
expires <= Date.now())
|
|
178
|
+
return;
|
|
179
|
+
// EventEmitter cannot await handlers. RemoteChannel owns bounded admission and
|
|
180
|
+
// observes execution; a rejected callback must not kill the MQTT event loop.
|
|
181
|
+
void this.onDoorbell(payload).catch(() => { });
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
/** Stop reconnects, reject pending startup and withdraw readiness on sign-out/shutdown. */
|
|
186
|
+
async stop() {
|
|
187
|
+
if (this.stopped)
|
|
188
|
+
return;
|
|
189
|
+
this.stopped = true;
|
|
190
|
+
this.ready = false;
|
|
191
|
+
this.cancelStart?.();
|
|
192
|
+
// Force socket closure: teardown must not wait for broker acknowledgements.
|
|
193
|
+
this.client?.end(true);
|
|
194
|
+
this.client = null;
|
|
195
|
+
await this.onReady(false);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
@@ -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,
|
|
@@ -3,94 +3,131 @@
|
|
|
3
3
|
/**
|
|
4
4
|
* Blocking script to update device status to offline
|
|
5
5
|
* Runs synchronously during shutdown to ensure DB update completes
|
|
6
|
-
*
|
|
6
|
+
*
|
|
7
7
|
* Usage: node blocking-offline-update.js <deviceId> <supabaseUrl> <supabaseKey> <accessToken> [refreshToken]
|
|
8
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.
|
|
9
13
|
*/
|
|
10
14
|
|
|
11
15
|
import { createClient } from '@supabase/supabase-js';
|
|
12
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
|
+
|
|
13
31
|
// Parse command line arguments
|
|
14
32
|
const [deviceId, supabaseUrl, supabaseKey, accessToken, refreshToken] = process.argv.slice(2);
|
|
15
33
|
|
|
16
34
|
if (!deviceId || !supabaseUrl || !supabaseKey || !accessToken) {
|
|
17
35
|
console.error('❌ Missing required arguments');
|
|
18
36
|
console.error('Usage: node blocking-offline-update.js <deviceId> <supabaseUrl> <supabaseKey> <accessToken> [refreshToken]');
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
// Set timeout for entire operation
|
|
23
|
-
const TIMEOUT_MS = 3000;
|
|
24
|
-
const timeoutHandle = setTimeout(() => {
|
|
25
|
-
console.error('⏱️ Timeout: Update took too long');
|
|
26
|
-
process.exit(2); // Exit code 2 for timeout
|
|
27
|
-
}, TIMEOUT_MS);
|
|
28
|
-
|
|
29
|
-
const auth = { persistSession: false, autoRefreshToken: false };
|
|
30
|
-
|
|
31
|
-
// Update device status to offline, stamping the exact shutdown moment so
|
|
32
|
-
// "last seen X ago" is precise for clean shutdowns (the periodic
|
|
33
|
-
// bookkeeping write only runs on the slow capable cadence).
|
|
34
|
-
// The token goes straight to PostgREST as a Bearer header: setSession()
|
|
35
|
-
// would first spend a GoTrue round trip of the budget re-validating it.
|
|
36
|
-
const markOffline = (token) => createClient(supabaseUrl, supabaseKey, {
|
|
37
|
-
auth,
|
|
38
|
-
global: { headers: { Authorization: `Bearer ${token}` } }
|
|
39
|
-
})
|
|
40
|
-
.from('mcp_devices')
|
|
41
|
-
.update({ status: 'offline', last_seen: new Date().toISOString() })
|
|
42
|
-
.eq('id', deviceId);
|
|
43
|
-
|
|
44
|
-
function tokenLooksLive(token) {
|
|
45
|
-
try {
|
|
46
|
-
const { exp } = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'));
|
|
47
|
-
return typeof exp === 'number' && exp * 1000 > Date.now() + 5000;
|
|
48
|
-
} catch {
|
|
49
|
-
return false;
|
|
50
|
-
}
|
|
37
|
+
exitProcess(1);
|
|
38
|
+
} else {
|
|
39
|
+
await markDeviceOffline();
|
|
51
40
|
}
|
|
52
41
|
|
|
53
|
-
|
|
54
|
-
//
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
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
|
+
}
|
|
60
79
|
}
|
|
61
|
-
const client = createClient(supabaseUrl, supabaseKey, { auth });
|
|
62
|
-
const { data, error: authError } = await client.auth.refreshSession({ refresh_token: refreshToken });
|
|
63
80
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
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;
|
|
68
97
|
}
|
|
69
|
-
return data.session.access_token;
|
|
70
|
-
}
|
|
71
98
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
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
|
+
}
|
|
78
127
|
}
|
|
79
128
|
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
clearTimeout(timeoutHandle);
|
|
83
|
-
|
|
84
|
-
if (error) {
|
|
85
|
-
console.error('❌ DB update error:', error.message);
|
|
86
|
-
process.exit(4); // Exit code 4 for DB error
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
console.log('✓ Device marked as offline');
|
|
90
|
-
process.exit(0); // Success
|
|
91
|
-
|
|
92
|
-
} catch (error) {
|
|
129
|
+
const code = await update();
|
|
93
130
|
clearTimeout(timeoutHandle);
|
|
94
|
-
|
|
95
|
-
|
|
131
|
+
// After a timeout the exit code stays 2 (only exitProcess()'s first call counts)
|
|
132
|
+
exitProcess(code);
|
|
96
133
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
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
|
+
operation?: string;
|
|
11
|
+
operationId?: string;
|
|
12
|
+
};
|
|
13
|
+
/** Record a device transport checkpoint without affecting command handling. */
|
|
14
|
+
export declare function observeTransport(input: TransportObservation): {
|
|
15
|
+
observation_id: `${string}-${string}-${string}-${string}-${string}`;
|
|
16
|
+
source_process_id: `${string}-${string}-${string}-${string}-${string}`;
|
|
17
|
+
schema_version: number;
|
|
18
|
+
timestamp_utc: string;
|
|
19
|
+
monotonic_ms: number;
|
|
20
|
+
operation_id?: string | undefined;
|
|
21
|
+
operation?: string | undefined;
|
|
22
|
+
call_id: string;
|
|
23
|
+
device_id: string;
|
|
24
|
+
transport: string;
|
|
25
|
+
stage: string;
|
|
26
|
+
notification_id: string;
|
|
27
|
+
attempt_number: number;
|
|
28
|
+
} | null;
|
|
29
|
+
export {};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { capture } from '../utils/capture.js';
|
|
3
|
+
const ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
4
|
+
const PROCESS_ID = randomUUID();
|
|
5
|
+
/** Record a device transport checkpoint without affecting command handling. */
|
|
6
|
+
export function observeTransport(input) {
|
|
7
|
+
try {
|
|
8
|
+
const timestamp_utc = new Date().toISOString();
|
|
9
|
+
const monotonic_ms = performance.now();
|
|
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
|
+
const operationId = receipt ? undefined : input.operationId ??
|
|
21
|
+
(input.stage === 'operation_start' ? observationId : undefined);
|
|
22
|
+
const event = {
|
|
23
|
+
call_id: callId,
|
|
24
|
+
device_id: deviceId,
|
|
25
|
+
transport: 'broadcast',
|
|
26
|
+
stage: input.stage,
|
|
27
|
+
notification_id: `${callId}:broadcast:1`,
|
|
28
|
+
attempt_number: 1,
|
|
29
|
+
...(!receipt && input.operation ? { operation: input.operation } : {}),
|
|
30
|
+
...(operationId ? { operation_id: operationId } : {}),
|
|
31
|
+
observation_id: observationId,
|
|
32
|
+
source_process_id: PROCESS_ID,
|
|
33
|
+
schema_version: 1,
|
|
34
|
+
timestamp_utc,
|
|
35
|
+
monotonic_ms,
|
|
36
|
+
};
|
|
37
|
+
void capture(input.stage, event);
|
|
38
|
+
return event;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// Telemetry must never affect command handling.
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|