@wonderwhy-er/desktop-commander 0.2.50 → 0.2.52
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 +14 -24
- package/dist/npm-scripts/remote.js +30 -1
- package/dist/remote-device/desktop-commander-integration.d.ts +20 -0
- package/dist/remote-device/desktop-commander-integration.js +121 -17
- package/dist/remote-device/device-authenticator.d.ts +13 -1
- package/dist/remote-device/device-authenticator.js +95 -50
- package/dist/remote-device/device.d.ts +14 -1
- package/dist/remote-device/device.js +162 -31
- package/dist/remote-device/remote-channel.d.ts +67 -16
- package/dist/remote-device/remote-channel.js +348 -116
- package/dist/remote-device/scripts/blocking-offline-update.js +50 -20
- package/dist/server.js +33 -81
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { RemoteChannel } from './remote-channel.js';
|
|
2
|
+
import { ChannelUnreachableError, RemoteChannel, observeServerDate } from './remote-channel.js';
|
|
3
3
|
import { DeviceAuthenticator } from './device-authenticator.js';
|
|
4
4
|
import { DesktopCommanderIntegration } from './desktop-commander-integration.js';
|
|
5
5
|
import { fileURLToPath } from 'url';
|
|
@@ -17,11 +17,24 @@ import { captureRemote } from '../utils/capture.js';
|
|
|
17
17
|
const SEEN_CALL_IDS_MAX = 100;
|
|
18
18
|
const PERSISTED_DEVICE_LOOKUP_ATTEMPTS = 3;
|
|
19
19
|
const PERSISTED_DEVICE_LOOKUP_RETRY_MS = 250;
|
|
20
|
+
/**
|
|
21
|
+
* Floor between recovery attempts. ensureReady()'s own backoff covers a child
|
|
22
|
+
* that fails to start; this covers one that starts and then fails verification,
|
|
23
|
+
* where no restart backoff was armed and the loop would otherwise spin.
|
|
24
|
+
*/
|
|
25
|
+
const RECOVERY_MIN_DELAY_MS = 1000;
|
|
20
26
|
export function getRemoteDeviceConfigPath() {
|
|
21
27
|
return path.join(os.homedir(), '.desktop-commander-device', 'device.json');
|
|
22
28
|
}
|
|
23
29
|
export class MCPDevice {
|
|
24
30
|
constructor(options = {}) {
|
|
31
|
+
/**
|
|
32
|
+
* Serialises config writes. Rotations are 45 minutes apart in normal
|
|
33
|
+
* running, but a save that stalls must not land after a newer one and
|
|
34
|
+
* persist a token that is already spent. Shutdown awaits this to drain
|
|
35
|
+
* whatever is still in flight.
|
|
36
|
+
*/
|
|
37
|
+
this.configWriteChain = Promise.resolve();
|
|
25
38
|
/** Call ids already handled by THIS process (insertion-ordered, bounded). */
|
|
26
39
|
this.seenCallIds = new Set();
|
|
27
40
|
this.baseServerUrl = process.env.MCP_SERVER_URL || 'https://mcp.desktopcommander.app';
|
|
@@ -34,8 +47,17 @@ export class MCPDevice {
|
|
|
34
47
|
// refresh-token families get replayed, trip GoTrue's reuse detection, and
|
|
35
48
|
// take the whole family down including the token a healthy connector holds.
|
|
36
49
|
this.persistSession = options.persistSession ?? true;
|
|
50
|
+
// The session refreshes every 45 minutes and auth-js rotates the refresh
|
|
51
|
+
// token each time. Without this the config keeps whichever token the
|
|
52
|
+
// process started with, and a restart hours later replays a spent one -
|
|
53
|
+
// GoTrue refuses it and an unattended device waits for a browser.
|
|
54
|
+
this.remoteChannel.onSessionRefreshed((session) => void this.savePersistedConfig(session));
|
|
37
55
|
// Initialize desktop integration
|
|
38
56
|
this.desktop = new DesktopCommanderIntegration();
|
|
57
|
+
// Readiness is a claim about executing, so it has to consult the local
|
|
58
|
+
// executor too. Read through a probe rather than a cached flag: there
|
|
59
|
+
// is then no state to keep in step, and `desktop` can be replaced.
|
|
60
|
+
this.remoteChannel.setLocalExecutorProbe(() => this.desktop.ready);
|
|
39
61
|
// Graceful shutdown handlers (only set once)
|
|
40
62
|
this.setupShutdownHandlers();
|
|
41
63
|
}
|
|
@@ -99,6 +121,10 @@ export class MCPDevice {
|
|
|
99
121
|
this.remoteChannel.initialize(supabaseUrl, anonKey);
|
|
100
122
|
// Load persisted configuration (deviceId, session)
|
|
101
123
|
let session = await this.loadPersistedConfig();
|
|
124
|
+
await captureRemote('remote_device_session_state', {
|
|
125
|
+
has_persisted_session: Boolean(session),
|
|
126
|
+
has_persisted_device_id: Boolean(this.deviceId),
|
|
127
|
+
});
|
|
102
128
|
// 2. Set Session or Authenticate
|
|
103
129
|
if (session) {
|
|
104
130
|
const { error } = await this.remoteChannel.setSession(session);
|
|
@@ -108,7 +134,6 @@ export class MCPDevice {
|
|
|
108
134
|
}
|
|
109
135
|
else {
|
|
110
136
|
console.log(' - ✅ Session restored');
|
|
111
|
-
console.log(' - ℹ️ To log out locally: npx @wonderwhy-er/desktop-commander@latest remote --logout');
|
|
112
137
|
// Revoking a device removes its server-side mcp_devices row, but the
|
|
113
138
|
// local config can still hold a valid user session + the now-deleted
|
|
114
139
|
// device ID. Do not silently recreate the revoked device with that
|
|
@@ -125,6 +150,7 @@ export class MCPDevice {
|
|
|
125
150
|
}
|
|
126
151
|
}
|
|
127
152
|
if (!session) {
|
|
153
|
+
await captureRemote('remote_device_auth_flow_started');
|
|
128
154
|
console.log('\n🔐 Authenticating with Remote MCP server...');
|
|
129
155
|
const authenticator = new DeviceAuthenticator(this.baseServerUrl);
|
|
130
156
|
session = await authenticator.authenticate(this.deviceId);
|
|
@@ -157,12 +183,60 @@ export class MCPDevice {
|
|
|
157
183
|
// Force save the current session immediately to ensure it's persisted
|
|
158
184
|
await this.savePersistedConfig();
|
|
159
185
|
const deviceName = os.hostname();
|
|
160
|
-
// Register as device
|
|
161
|
-
|
|
162
|
-
|
|
186
|
+
// Register as device. registerDevice() resolves only once the
|
|
187
|
+
// realtime channel is joined and presence is published, which is
|
|
188
|
+
// exactly what the hosted service needs to deliver a call — so a
|
|
189
|
+
// rejection means "running, but nothing can reach this device", and
|
|
190
|
+
// that has to be said instead of "Device ready".
|
|
191
|
+
//
|
|
192
|
+
// Deliberately not fatal, and deliberately not rethrown into the
|
|
193
|
+
// outer catch, which exits the process: the socket watchdog keeps
|
|
194
|
+
// retrying and announces "✅ Channel subscribed" when it gets
|
|
195
|
+
// through, so quitting here would remove the only way back.
|
|
196
|
+
let reachable = true;
|
|
197
|
+
try {
|
|
198
|
+
await this.remoteChannel.registerDevice(await this.desktop.listClientTools(), this.deviceId, deviceName, (payload) => this.handleNewToolCall(payload));
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
// Only a channel fault is recoverable here. A failed lookup or a
|
|
202
|
+
// missing device row happens before registerDevice() stores the
|
|
203
|
+
// recreation parameters, and both checkConnectionHealth() and
|
|
204
|
+
// recreateChannel() return early without them — so nothing in
|
|
205
|
+
// this process could repair it, and swallowing it would promise
|
|
206
|
+
// a retry that can never happen. Those stay fatal, as before.
|
|
207
|
+
if (!(error instanceof ChannelUnreachableError))
|
|
208
|
+
throw error;
|
|
209
|
+
reachable = false;
|
|
210
|
+
console.error(` - ❌ Realtime channel is not open: ${error.message}`);
|
|
211
|
+
await captureRemote('remote_device_registered_unreachable', { error });
|
|
212
|
+
}
|
|
213
|
+
console.log(reachable
|
|
214
|
+
? '✅ Device ready:'
|
|
215
|
+
: '⚠️ Device registered, but NOT reachable — no command can arrive yet:');
|
|
163
216
|
console.log(` - User: ${this.remoteChannel.user.email}`);
|
|
164
217
|
console.log(` - Device ID: ${this.deviceId}`);
|
|
165
218
|
console.log(` - Device Name: ${deviceName}`);
|
|
219
|
+
if (!reachable) {
|
|
220
|
+
console.log(' - Retrying in the background; commands start working once you see "✅ Channel subscribed".');
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
console.log('');
|
|
224
|
+
console.log('✅ Desktop Commander Remote is connected');
|
|
225
|
+
console.log('');
|
|
226
|
+
console.log(` Device: ${deviceName}`);
|
|
227
|
+
console.log(' Status: Online');
|
|
228
|
+
console.log('');
|
|
229
|
+
console.log('┌─ Next');
|
|
230
|
+
console.log('│ Return to ChatGPT or Claude and continue your conversation.');
|
|
231
|
+
console.log('│ Keep this Terminal running. You can minimize it.');
|
|
232
|
+
console.log('└─ Press Ctrl+C to disconnect.');
|
|
233
|
+
console.log('');
|
|
234
|
+
console.log('┌─ Commands');
|
|
235
|
+
console.log('│ Help: npx @wonderwhy-er/desktop-commander@latest remote --help');
|
|
236
|
+
console.log('│ Log out: npx @wonderwhy-er/desktop-commander@latest remote --logout');
|
|
237
|
+
console.log('└─ Run these in a new Terminal, or after disconnecting.');
|
|
238
|
+
console.log('');
|
|
239
|
+
}
|
|
166
240
|
// Keep process alive
|
|
167
241
|
this.remoteChannel.startHeartbeat(this.deviceId);
|
|
168
242
|
}
|
|
@@ -240,11 +314,28 @@ export class MCPDevice {
|
|
|
240
314
|
await captureRemote('remote_device_config_clear_error', { error });
|
|
241
315
|
}
|
|
242
316
|
}
|
|
243
|
-
|
|
317
|
+
/**
|
|
318
|
+
* Queue a config write. Returns the queued write, so a caller that must not
|
|
319
|
+
* outlive it - shutdown() - can await it.
|
|
320
|
+
*/
|
|
321
|
+
async savePersistedConfig(rotated) {
|
|
322
|
+
this.configWriteChain = this.configWriteChain.then(() => this.writePersistedConfig(rotated));
|
|
323
|
+
return this.configWriteChain;
|
|
324
|
+
}
|
|
325
|
+
async writePersistedConfig(rotated) {
|
|
244
326
|
try {
|
|
245
327
|
console.debug('[DEBUG] Saving persisted config, persistSession:', this.persistSession);
|
|
246
|
-
|
|
247
|
-
|
|
328
|
+
// Prefer the session TOKEN_REFRESHED handed us over re-reading it. A
|
|
329
|
+
// sign-out landing in that gap answers null, and the write below would
|
|
330
|
+
// replace a usable refresh token with nothing.
|
|
331
|
+
const session = rotated ?? (await this.remoteChannel.getSession()).data.session;
|
|
332
|
+
// Never trade a good token for an empty one. Deliberate clearing is
|
|
333
|
+
// what clearPersistedConfig() is for; --no-persist-session still
|
|
334
|
+
// writes null below, because persistSession is false there.
|
|
335
|
+
if (this.persistSession && !session?.refresh_token) {
|
|
336
|
+
console.debug('[DEBUG] Skipping config save - nothing to persist');
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
248
339
|
const config = {
|
|
249
340
|
deviceId: this.deviceId,
|
|
250
341
|
// Only save session if --persist-session flag is set
|
|
@@ -256,7 +347,16 @@ export class MCPDevice {
|
|
|
256
347
|
// Ensure the config directory exists
|
|
257
348
|
console.debug('[DEBUG] Creating config directory:', path.dirname(this.configPath));
|
|
258
349
|
await fs.mkdir(path.dirname(this.configPath), { recursive: true });
|
|
259
|
-
|
|
350
|
+
// Write then rename: the rename is the commit boundary, so a write
|
|
351
|
+
// cut short leaves the previous complete session rather than a
|
|
352
|
+
// truncated file. loadPersistedConfig() answers a JSON.parse
|
|
353
|
+
// failure with null, which costs a full browser reauthorization.
|
|
354
|
+
// Same shape as ConfigManager's atomic save; the pid keeps two
|
|
355
|
+
// processes off each other's temp file, and configWriteChain keeps
|
|
356
|
+
// this one off its own.
|
|
357
|
+
const tempPath = `${this.configPath}.${process.pid}.tmp`;
|
|
358
|
+
await fs.writeFile(tempPath, JSON.stringify(config, null, 2), { mode: 0o600 });
|
|
359
|
+
await fs.rename(tempPath, this.configPath);
|
|
260
360
|
console.debug('[DEBUG] Config saved to:', this.configPath);
|
|
261
361
|
}
|
|
262
362
|
catch (error) {
|
|
@@ -269,6 +369,11 @@ export class MCPDevice {
|
|
|
269
369
|
// No auth header needed for this public endpoint
|
|
270
370
|
console.debug('[DEBUG] Fetching Supabase config from:', `${this.baseServerUrl}/api/mcp-info`);
|
|
271
371
|
const response = await fetch(`${this.baseServerUrl}/api/mcp-info`);
|
|
372
|
+
// First request of the run, and it already states the server's time.
|
|
373
|
+
// auth-js judges the session handed to setSession() against this
|
|
374
|
+
// device's Date.now() with no skew tolerance, so the clock has to be
|
|
375
|
+
// right BEFORE that call - clockAwareFetch only corrects it afterwards.
|
|
376
|
+
observeServerDate(response.headers.get('date'));
|
|
272
377
|
if (!response.ok) {
|
|
273
378
|
console.debug('[DEBUG] Supabase config fetch failed, status:', response.status, response.statusText);
|
|
274
379
|
throw new Error(`Failed to fetch Supabase config: ${response.statusText}`);
|
|
@@ -288,23 +393,47 @@ export class MCPDevice {
|
|
|
288
393
|
* connected" until someone restarted the process by hand.
|
|
289
394
|
*/
|
|
290
395
|
async handleLocalMcpLoss(reason) {
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
//
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
396
|
+
// Through the predicate and its queue, not a direct write: the probe
|
|
397
|
+
// already reads false by the time this runs, and a direct write can be
|
|
398
|
+
// overtaken by an 'online' still sitting in the queue — which would put
|
|
399
|
+
// a device with a dead executor back into the server's selection pool.
|
|
400
|
+
await this.remoteChannel.syncReachabilityStatus()
|
|
401
|
+
.catch((e) => console.error('Failed to mark device offline:', e.message));
|
|
402
|
+
// Keep trying, rather than attempting once. The lazy restart in
|
|
403
|
+
// ensureReady() fires on an incoming tool call, and this device is now
|
|
404
|
+
// offline — the hosted service answers a call for an offline device
|
|
405
|
+
// with "No devices available" (confirmed live on 0.2.50), so no call
|
|
406
|
+
// will ever arrive to trigger it. One failed attempt used to mean the
|
|
407
|
+
// device stayed dead until a human restarted the connector.
|
|
408
|
+
let reported = false;
|
|
409
|
+
while (!this.isShuttingDown) {
|
|
410
|
+
try {
|
|
411
|
+
// ensureReady() only reports success once the child has served a
|
|
412
|
+
// request, so reaching here is proof of execution, not just of a
|
|
413
|
+
// completed handshake.
|
|
414
|
+
await this.desktop.ensureReady();
|
|
415
|
+
// Not setOnlineStatus('online'): the executor recovering says
|
|
416
|
+
// nothing about the channel. Let the predicate decide, or this
|
|
417
|
+
// repeats the one-sided claim this whole change removes.
|
|
418
|
+
this.remoteChannel.syncReachabilityStatus();
|
|
419
|
+
console.log('♻️ Local Desktop Commander MCP restarted; device is online again');
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
console.error(`❌ Could not restart local Desktop Commander MCP: ${error.message}`);
|
|
424
|
+
// Once per outage, not once per attempt: a device that never
|
|
425
|
+
// recovers would otherwise emit this every backoff window for
|
|
426
|
+
// as long as it runs.
|
|
427
|
+
if (!reported) {
|
|
428
|
+
reported = true;
|
|
429
|
+
await captureRemote('remote_device_local_mcp_restart_failed', { error, reason });
|
|
430
|
+
}
|
|
431
|
+
// ensureReady() refuses inside its backoff window; wait it out.
|
|
432
|
+
// The floor covers a child that starts but fails verification,
|
|
433
|
+
// where no restart backoff was armed.
|
|
434
|
+
const waitMs = Math.max(this.desktop.msUntilRestartAllowed, RECOVERY_MIN_DELAY_MS);
|
|
435
|
+
await new Promise((resolve) => setTimeout(resolve, waitMs));
|
|
302
436
|
}
|
|
303
|
-
console.log('♻️ Local Desktop Commander MCP restarted; device is online again');
|
|
304
|
-
}
|
|
305
|
-
catch (error) {
|
|
306
|
-
console.error(`❌ Could not restart local Desktop Commander MCP: ${error.message}`);
|
|
307
|
-
await captureRemote('remote_device_local_mcp_restart_failed', { error, reason });
|
|
308
437
|
}
|
|
309
438
|
}
|
|
310
439
|
/** Record a handled call id, evicting the oldest once the cap is reached. */
|
|
@@ -343,8 +472,9 @@ export class MCPDevice {
|
|
|
343
472
|
// DB claim second — keeps the row state machine honest, gives
|
|
344
473
|
// cross-restart/cross-process protection, and is observable. It may
|
|
345
474
|
// fail open (returns true on a transient write error); the local
|
|
346
|
-
// guard above is what makes execution exactly-once.
|
|
347
|
-
|
|
475
|
+
// guard above is what makes execution exactly-once. The doorbell
|
|
476
|
+
// path claims before dispatch and marks the payload `claimed`.
|
|
477
|
+
const claimed = payload.claimed === true || await this.remoteChannel.markCallExecuting(call_id);
|
|
348
478
|
if (!claimed) {
|
|
349
479
|
// markCallExecuting already logged the duplicate-delivery skip.
|
|
350
480
|
return;
|
|
@@ -378,10 +508,8 @@ export class MCPDevice {
|
|
|
378
508
|
result = await this.desktop.callClientTool(tool_name, tool_args, metadata);
|
|
379
509
|
}
|
|
380
510
|
console.log(`✅ Tool call ${tool_name} completed:\r\n ${JSON.stringify(result)}`);
|
|
381
|
-
//
|
|
382
|
-
// fetches the row by id on the doorbell, so the write must land first.
|
|
511
|
+
// The result write itself notifies the server (a DB trigger).
|
|
383
512
|
await this.remoteChannel.updateCallResult(call_id, 'completed', result);
|
|
384
|
-
await this.remoteChannel.notifyResult(call_id);
|
|
385
513
|
}
|
|
386
514
|
catch (error) {
|
|
387
515
|
console.error(`❌ Tool call ${tool_name} failed:`, error.message);
|
|
@@ -391,7 +519,6 @@ export class MCPDevice {
|
|
|
391
519
|
try {
|
|
392
520
|
await captureRemote('remote_device_tool_call_failed', { error, tool_name });
|
|
393
521
|
await this.remoteChannel.updateCallResult(call_id, 'failed', null, error.message);
|
|
394
|
-
await this.remoteChannel.notifyResult(call_id);
|
|
395
522
|
}
|
|
396
523
|
catch (reportError) {
|
|
397
524
|
console.error(`❌ Could not report failure for ${call_id}:`, reportError?.message);
|
|
@@ -420,6 +547,10 @@ export class MCPDevice {
|
|
|
420
547
|
console.log(' → Marking device offline...');
|
|
421
548
|
console.debug('[DEBUG] Calling setOffline() with deviceId:', this.deviceId);
|
|
422
549
|
await this.remoteChannel.setOffline(this.deviceId);
|
|
550
|
+
// Drain any config write still in flight - a rotation can land as
|
|
551
|
+
// teardown begins, and losing it costs the next start a browser.
|
|
552
|
+
console.debug('[DEBUG] Draining pending config writes');
|
|
553
|
+
await this.configWriteChain;
|
|
423
554
|
// Shutdown desktop integration
|
|
424
555
|
console.log(' → Shutting down desktop integration...');
|
|
425
556
|
console.debug('[DEBUG] Calling desktop.shutdown()');
|
|
@@ -10,6 +10,16 @@ export interface AuthSession {
|
|
|
10
10
|
refresh_token: string | null;
|
|
11
11
|
device_id?: string;
|
|
12
12
|
}
|
|
13
|
+
/**
|
|
14
|
+
* The device registered, but its realtime channel is not usable — the join
|
|
15
|
+
* failed, or presence was never acknowledged. Distinct from every other
|
|
16
|
+
* registration failure on purpose: this one the socket watchdog can repair, so
|
|
17
|
+
* the caller keeps the process alive, while a failed lookup or a missing row
|
|
18
|
+
* happens before the recreation parameters are stored and nothing can repair it.
|
|
19
|
+
*/
|
|
20
|
+
export declare class ChannelUnreachableError extends Error {
|
|
21
|
+
constructor(message: string);
|
|
22
|
+
}
|
|
13
23
|
interface DeviceData {
|
|
14
24
|
user_id: string;
|
|
15
25
|
device_name: string;
|
|
@@ -17,6 +27,10 @@ interface DeviceData {
|
|
|
17
27
|
status: string;
|
|
18
28
|
last_seen: string;
|
|
19
29
|
}
|
|
30
|
+
/** Jittered version of realtime-js's default 1s/2s/5s/10s stepped backoff. */
|
|
31
|
+
export declare function realtimeReconnectDelayMs(tries: number, random?: () => number): number;
|
|
32
|
+
/** Preserve Presence's existing 500ms-per-attempt retry shape, but desynchronize it. */
|
|
33
|
+
export declare function presenceRetryDelayMs(failedAttempt: number, random?: () => number): number;
|
|
20
34
|
export declare function observeServerDate(dateHeader: string | null): void;
|
|
21
35
|
export declare class RemoteChannel {
|
|
22
36
|
private client;
|
|
@@ -26,8 +40,16 @@ export declare class RemoteChannel {
|
|
|
26
40
|
/** Device the heartbeat timer maintains; null = stopped, so re-arm is inert. */
|
|
27
41
|
private heartbeatDeviceId;
|
|
28
42
|
private statusWriteChain;
|
|
43
|
+
/**
|
|
44
|
+
* Answers whether the local execution child is alive. Default yes, so a
|
|
45
|
+
* RemoteChannel used without a device (tests, other callers) behaves as
|
|
46
|
+
* before; MCPDevice installs the real probe.
|
|
47
|
+
*/
|
|
48
|
+
private localExecutorProbe;
|
|
29
49
|
/** Tokens from the last setSession / TOKEN_REFRESHED, for setOffline(). */
|
|
30
50
|
private lastKnownSession;
|
|
51
|
+
/** Notified when auth-js rotates the session; the device persists it. */
|
|
52
|
+
private sessionRefreshedHandler;
|
|
31
53
|
/** Set by unsubscribe(): suppresses status/heartbeat writes so they can't
|
|
32
54
|
* land after setOffline()'s durable write. */
|
|
33
55
|
private shuttingDown;
|
|
@@ -43,6 +65,8 @@ export declare class RemoteChannel {
|
|
|
43
65
|
private presenceTracked;
|
|
44
66
|
/** Last capability value written (null = never), to avoid redundant writes. */
|
|
45
67
|
private transportCapableWritten;
|
|
68
|
+
/** Monotonic start of a Presence-only degradation while broadcast remains joined. */
|
|
69
|
+
private presenceFailureStartedAt;
|
|
46
70
|
/** Re-entrancy guard: on a wedged socket each track() buffers for the full
|
|
47
71
|
* 10s push timeout, so 10s health ticks would stack pushes. */
|
|
48
72
|
private isTrackingPresence;
|
|
@@ -63,6 +87,19 @@ export declare class RemoteChannel {
|
|
|
63
87
|
private _user;
|
|
64
88
|
get user(): User | null;
|
|
65
89
|
initialize(url: string, key: string): void;
|
|
90
|
+
/**
|
|
91
|
+
* Teach the channel how to ask whether the local executor is alive.
|
|
92
|
+
* `status` is a claim that this device will run a tool call right now, and
|
|
93
|
+
* a joined channel alone cannot support that claim - issue #4.
|
|
94
|
+
*/
|
|
95
|
+
setLocalExecutorProbe(probe: () => boolean): void;
|
|
96
|
+
/**
|
|
97
|
+
* Register a callback fired when auth-js rotates the session. auth-js
|
|
98
|
+
* rotates the refresh token on every refresh and the previous one is spent,
|
|
99
|
+
* so a config written once at startup replays a dead token on the next
|
|
100
|
+
* restart and the device demands browser authorization again.
|
|
101
|
+
*/
|
|
102
|
+
onSessionRefreshed(handler: (session: AuthSession) => void): void;
|
|
66
103
|
setSession(session: AuthSession): Promise<{
|
|
67
104
|
error: any;
|
|
68
105
|
}>;
|
|
@@ -96,7 +133,7 @@ export declare class RemoteChannel {
|
|
|
96
133
|
/**
|
|
97
134
|
* Publish presence, retrying a non-'ok' result — track() resolves with a
|
|
98
135
|
* status rather than rejecting, and absent presence reads as offline on the
|
|
99
|
-
*
|
|
136
|
+
* dashboard. `presenceTracked` lets the health check retry later.
|
|
100
137
|
*/
|
|
101
138
|
private trackPresenceWithRetry;
|
|
102
139
|
private trackPresenceInner;
|
|
@@ -107,28 +144,30 @@ export declare class RemoteChannel {
|
|
|
107
144
|
private capabilitiesPayload;
|
|
108
145
|
/**
|
|
109
146
|
* Advertise (or withdraw) the broadcast capability. Only true while genuinely
|
|
110
|
-
* reachable that way — the server
|
|
111
|
-
*
|
|
112
|
-
* re-arm the heartbeat.
|
|
147
|
+
* reachable that way — the server fails dispatch fast without it and picks
|
|
148
|
+
* the offline-sweep tier from it, so every change must re-arm the heartbeat.
|
|
113
149
|
*/
|
|
114
150
|
private setTransportCapable;
|
|
115
151
|
/** Create and subscribe the private channel (initial join and recreation). */
|
|
116
152
|
private createChannel;
|
|
153
|
+
/**
|
|
154
|
+
* Recover calls whose Realtime doorbell was missed while this device was
|
|
155
|
+
* disconnected. Broadcast provides the fast path; the DB row is the source
|
|
156
|
+
* of truth. Only still-live pending rows for this device are considered.
|
|
157
|
+
*
|
|
158
|
+
* The follow-up onDoorbell() call performs the existing conditional claim,
|
|
159
|
+
* which makes this safe against a doorbell arriving at the same time.
|
|
160
|
+
*/
|
|
161
|
+
private recoverPendingCalls;
|
|
117
162
|
/** Hand a call to device.ts, observing the rejection — the handler is async
|
|
118
163
|
* and an unhandled rejection terminates the process. */
|
|
119
164
|
private dispatchToolCall;
|
|
120
165
|
/**
|
|
121
|
-
* Handle a 'new_call' doorbell. It carries ids only;
|
|
122
|
-
*
|
|
123
|
-
*
|
|
166
|
+
* Handle a 'new_call' doorbell. It carries ids only; one conditional update
|
|
167
|
+
* claims the row (pending -> executing) and returns it, and it is handed to
|
|
168
|
+
* device.ts marked as claimed.
|
|
124
169
|
*/
|
|
125
170
|
private onDoorbell;
|
|
126
|
-
/**
|
|
127
|
-
* Tell the server a result row is written. Fire-and-forget: a failed send
|
|
128
|
-
* just falls back to the server's 10s recovery poll. MUST run only after
|
|
129
|
-
* updateCallResult() resolves, so the server's fetch-by-id sees a terminal row.
|
|
130
|
-
*/
|
|
131
|
-
notifyResult(callId: string): Promise<void>;
|
|
132
171
|
/**
|
|
133
172
|
* Compact connection state for logs — e.g. "socket=open(1) ch=errored attempt=3".
|
|
134
173
|
* readyState 1=OPEN (a 1 while joins keep failing = a half-open socket being reused),
|
|
@@ -167,15 +206,26 @@ export declare class RemoteChannel {
|
|
|
167
206
|
*/
|
|
168
207
|
markCallExecuting(callId: string): Promise<boolean>;
|
|
169
208
|
updateCallResult(callId: string, status: string, result?: any, errorMessage?: string | null): Promise<void>;
|
|
170
|
-
/**
|
|
209
|
+
/**
|
|
210
|
+
* Reachable means all of it is true at once: the private channel is
|
|
211
|
+
* joined, this device has published its presence, and the local executor
|
|
212
|
+
* answers. The server needs the first two before it will dispatch, and a
|
|
213
|
+
* healthy channel on a device whose executor is dead is the false-online
|
|
214
|
+
* state issue #4 was opened for. Gates the heartbeat and `status`.
|
|
215
|
+
*/
|
|
171
216
|
private isReachable;
|
|
172
217
|
/**
|
|
173
218
|
* Set `status` from actual reachability. `status` is transport-agnostic (the
|
|
174
219
|
* server filters on it), so it must not follow one channel's health — the
|
|
175
220
|
* private channel's error path re-fires on every rejoin and would oscillate
|
|
176
221
|
* the row against the heartbeat. Same predicate as the heartbeat gate.
|
|
222
|
+
*
|
|
223
|
+
* Every transition belongs here rather than calling setOnlineStatus(), which
|
|
224
|
+
* is the write and not the decision. Public so the device can route its
|
|
225
|
+
* recovery transition through the predicate too.
|
|
177
226
|
*/
|
|
178
|
-
|
|
227
|
+
/** Resolves with whether the row actually took the write. */
|
|
228
|
+
syncReachabilityStatus(): Promise<boolean>;
|
|
179
229
|
/**
|
|
180
230
|
* Serialize the channel-callback status writes. They fire from un-awaited
|
|
181
231
|
* callbacks, and inside recreateChannel() a teardown's 'offline' and the
|
|
@@ -200,7 +250,8 @@ export declare class RemoteChannel {
|
|
|
200
250
|
/** Arm (or re-arm) the last_seen timer at the current tier's cadence. */
|
|
201
251
|
private scheduleHeartbeat;
|
|
202
252
|
stopHeartbeat(): void;
|
|
203
|
-
|
|
253
|
+
/** @returns whether the row actually took the write. */
|
|
254
|
+
setOnlineStatus(deviceId: string, status: 'online' | 'offline'): Promise<boolean>;
|
|
204
255
|
setOffline(deviceId: string | undefined): Promise<void>;
|
|
205
256
|
unsubscribe(): Promise<void>;
|
|
206
257
|
}
|