@wonderwhy-er/desktop-commander 0.2.48 → 0.2.51
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 +35 -13
- package/dist/config-manager.d.ts +25 -35
- package/dist/config-manager.js +196 -95
- package/dist/npm-scripts/remote.js +29 -1
- package/dist/remote-device/desktop-commander-integration.d.ts +26 -0
- package/dist/remote-device/desktop-commander-integration.js +95 -4
- package/dist/remote-device/device-authenticator.js +8 -3
- package/dist/remote-device/device.d.ts +24 -1
- package/dist/remote-device/device.js +129 -12
- package/dist/remote-device/remote-channel.d.ts +15 -13
- package/dist/remote-device/remote-channel.js +95 -85
- package/dist/remote-device/scripts/blocking-offline-update.js +50 -20
- package/dist/server.js +6 -4
- package/dist/terminal-manager.js +39 -0
- package/dist/tools/edit.js +13 -1
- package/dist/tools/process.d.ts +1 -1
- package/dist/tools/process.js +2 -2
- package/dist/uninstall-claude-server.js +0 -15
- package/dist/utils/files/text.d.ts +1 -0
- package/dist/utils/files/text.js +38 -8
- package/dist/utils/usageTracker.d.ts +0 -8
- package/dist/utils/usageTracker.js +52 -53
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +3 -1
|
@@ -48,8 +48,8 @@ const TOKEN_REFRESH_INTERVAL_MS = 45 * 60 * 1000;
|
|
|
48
48
|
// Below this, skew is noise — leave Date.now untouched. Above it, correct.
|
|
49
49
|
const CLOCK_SKEW_CORRECTION_THRESHOLD_MS = 5 * 60 * 1000;
|
|
50
50
|
// Failed recreates before withdrawing transport_broadcast_v1 — keeping it while
|
|
51
|
-
// unable to join
|
|
52
|
-
// half-open recovery legitimately costs 2.
|
|
51
|
+
// unable to join leaves the server dispatching calls this device can't
|
|
52
|
+
// receive. Not lower than 3: ordinary half-open recovery legitimately costs 2.
|
|
53
53
|
const TRANSPORT_WITHDRAW_AFTER_ATTEMPTS = 3;
|
|
54
54
|
// Cap on the withdrawal write; it runs in a catch block RECREATE_TIMEOUT_MS
|
|
55
55
|
// does not cover.
|
|
@@ -116,6 +116,8 @@ export class RemoteChannel {
|
|
|
116
116
|
this.statusWriteChain = Promise.resolve();
|
|
117
117
|
/** Tokens from the last setSession / TOKEN_REFRESHED, for setOffline(). */
|
|
118
118
|
this.lastKnownSession = null;
|
|
119
|
+
/** Notified when auth-js rotates the session; the device persists it. */
|
|
120
|
+
this.sessionRefreshedHandler = null;
|
|
119
121
|
/** Set by unsubscribe(): suppresses status/heartbeat writes so they can't
|
|
120
122
|
* land after setOffline()'s durable write. */
|
|
121
123
|
this.shuttingDown = false;
|
|
@@ -193,11 +195,21 @@ export class RemoteChannel {
|
|
|
193
195
|
catch { /* no onHeartbeat on this client version: staleness check stays inert */ }
|
|
194
196
|
}
|
|
195
197
|
}
|
|
198
|
+
/**
|
|
199
|
+
* Register a callback fired when auth-js rotates the session. auth-js
|
|
200
|
+
* rotates the refresh token on every refresh and the previous one is spent,
|
|
201
|
+
* so a config written once at startup replays a dead token on the next
|
|
202
|
+
* restart and the device demands browser authorization again.
|
|
203
|
+
*/
|
|
204
|
+
onSessionRefreshed(handler) {
|
|
205
|
+
this.sessionRefreshedHandler = handler;
|
|
206
|
+
}
|
|
196
207
|
async setSession(session) {
|
|
197
208
|
if (!this.client)
|
|
198
209
|
throw new Error('Client not initialized');
|
|
199
210
|
console.debug('[DEBUG] RemoteChannel.setSession() called, has refresh_token:', !!session.refresh_token);
|
|
200
|
-
|
|
211
|
+
// setSession() already fetches the user from GoTrue (or refreshes), so no getUser() after it.
|
|
212
|
+
const { data: { user }, error } = await this.client.auth.setSession({
|
|
201
213
|
access_token: session.access_token,
|
|
202
214
|
refresh_token: session.refresh_token || ''
|
|
203
215
|
});
|
|
@@ -206,13 +218,6 @@ export class RemoteChannel {
|
|
|
206
218
|
await captureRemote('remote_channel_set_session_error', { error });
|
|
207
219
|
return { error };
|
|
208
220
|
}
|
|
209
|
-
// Get user info
|
|
210
|
-
const { data: { user }, error: userError } = await this.client.auth.getUser();
|
|
211
|
-
if (userError) {
|
|
212
|
-
console.error('[DEBUG] Failed to get user:', userError.message);
|
|
213
|
-
await captureRemote('remote_channel_get_user_error', { error: userError });
|
|
214
|
-
throw userError;
|
|
215
|
-
}
|
|
216
221
|
if (!user) {
|
|
217
222
|
const noUserError = new Error('No user returned after setSession');
|
|
218
223
|
console.error('[DEBUG] No user returned:', noUserError.message);
|
|
@@ -242,6 +247,14 @@ export class RemoteChannel {
|
|
|
242
247
|
access_token: newSession.access_token,
|
|
243
248
|
refresh_token: newSession.refresh_token ?? this.lastKnownSession?.refresh_token ?? null,
|
|
244
249
|
};
|
|
250
|
+
// Memory alone is not enough: the token we just replaced is
|
|
251
|
+
// spent, so whatever is on disk is now unusable.
|
|
252
|
+
// Hand over the session we were just given. A listener that
|
|
253
|
+
// re-read it could find a sign-out instead and persist that.
|
|
254
|
+
this.sessionRefreshedHandler?.({
|
|
255
|
+
access_token: newSession.access_token,
|
|
256
|
+
refresh_token: newSession.refresh_token ?? null,
|
|
257
|
+
});
|
|
245
258
|
}
|
|
246
259
|
else if (event === 'SIGNED_OUT') {
|
|
247
260
|
void this.handleSignedOut();
|
|
@@ -436,7 +449,7 @@ export class RemoteChannel {
|
|
|
436
449
|
/**
|
|
437
450
|
* Publish presence, retrying a non-'ok' result — track() resolves with a
|
|
438
451
|
* status rather than rejecting, and absent presence reads as offline on the
|
|
439
|
-
*
|
|
452
|
+
* dashboard. `presenceTracked` lets the health check retry later.
|
|
440
453
|
*/
|
|
441
454
|
async trackPresenceWithRetry(recovered, attempts = 3) {
|
|
442
455
|
if (this.isTrackingPresence)
|
|
@@ -471,7 +484,7 @@ export class RemoteChannel {
|
|
|
471
484
|
// Reconnect attempts preceding this join (0 on a first join).
|
|
472
485
|
captureRemote('remote_channel_presence_tracked', { recoveredAfterAttempts: recovered }).catch(() => { });
|
|
473
486
|
// Proven end-to-end (joined AND presence published) — only now
|
|
474
|
-
//
|
|
487
|
+
// advertise the capability dispatch requires.
|
|
475
488
|
await this.setTransportCapable(true);
|
|
476
489
|
return;
|
|
477
490
|
}
|
|
@@ -482,9 +495,9 @@ export class RemoteChannel {
|
|
|
482
495
|
this.presenceTracked = false;
|
|
483
496
|
console.error('❌ Presence track failed after retries — withdrawing broadcast capability');
|
|
484
497
|
captureRemote('remote_channel_presence_track_error', { attempts }).catch(() => { });
|
|
485
|
-
// Withdraw: a
|
|
486
|
-
//
|
|
487
|
-
// accurate
|
|
498
|
+
// Withdraw: the dashboard reads a flagged device with no presence as
|
|
499
|
+
// offline. The faster heartbeat tier keeps the device's DB status
|
|
500
|
+
// accurate while it recovers.
|
|
488
501
|
await this.setTransportCapable(false);
|
|
489
502
|
}
|
|
490
503
|
/**
|
|
@@ -499,9 +512,8 @@ export class RemoteChannel {
|
|
|
499
512
|
}
|
|
500
513
|
/**
|
|
501
514
|
* Advertise (or withdraw) the broadcast capability. Only true while genuinely
|
|
502
|
-
* reachable that way — the server
|
|
503
|
-
*
|
|
504
|
-
* re-arm the heartbeat.
|
|
515
|
+
* reachable that way — the server fails dispatch fast without it and picks
|
|
516
|
+
* the offline-sweep tier from it, so every change must re-arm the heartbeat.
|
|
505
517
|
*/
|
|
506
518
|
async setTransportCapable(capable) {
|
|
507
519
|
if (!this.client || !this.deviceId)
|
|
@@ -538,7 +550,7 @@ export class RemoteChannel {
|
|
|
538
550
|
return new Promise((resolve, reject) => {
|
|
539
551
|
if (!this.client || !this.user?.id || !this.onToolCall || !this.deviceId) {
|
|
540
552
|
// deviceId is the presence KEY; a null key gets a random one and
|
|
541
|
-
// the
|
|
553
|
+
// the dashboard's lookup by device id silently misses.
|
|
542
554
|
console.debug('[DEBUG] createChannel() failed - missing prerequisites');
|
|
543
555
|
return reject(new Error('Client not initialized or missing subscription parameters'));
|
|
544
556
|
}
|
|
@@ -547,11 +559,8 @@ export class RemoteChannel {
|
|
|
547
559
|
const channelName = `user:${this.user.id}`;
|
|
548
560
|
console.debug(`[DEBUG] Creating channel: ${channelName}`);
|
|
549
561
|
this.channel = this.client.channel(channelName, {
|
|
550
|
-
// ack: true — without it send() resolves 'ok' once the frame hits
|
|
551
|
-
// the socket, making notifyResult's status check dead code.
|
|
552
562
|
config: {
|
|
553
563
|
private: true,
|
|
554
|
-
broadcast: { ack: true },
|
|
555
564
|
// Non-null: the guard above rejects when !deviceId.
|
|
556
565
|
presence: { key: this.deviceId, enabled: true }
|
|
557
566
|
}
|
|
@@ -572,9 +581,10 @@ export class RemoteChannel {
|
|
|
572
581
|
// Update device status on successful connection (queued, so
|
|
573
582
|
// it can't be overtaken by a teardown's status write).
|
|
574
583
|
this.queueStatusWrite('online');
|
|
575
|
-
//
|
|
576
|
-
//
|
|
577
|
-
// "Device ready" while still
|
|
584
|
+
// The capability flag dispatch requires is written only
|
|
585
|
+
// once presence lands, so resolve then — otherwise
|
|
586
|
+
// registerDevice() reports "Device ready" while still
|
|
587
|
+
// undispatchable.
|
|
578
588
|
this.trackPresenceWithRetry(recovered)
|
|
579
589
|
.catch(() => { })
|
|
580
590
|
.finally(() => resolve());
|
|
@@ -621,15 +631,15 @@ export class RemoteChannel {
|
|
|
621
631
|
}
|
|
622
632
|
}
|
|
623
633
|
/**
|
|
624
|
-
* Handle a 'new_call' doorbell. It carries ids only;
|
|
625
|
-
*
|
|
626
|
-
*
|
|
634
|
+
* Handle a 'new_call' doorbell. It carries ids only; one conditional update
|
|
635
|
+
* claims the row (pending -> executing) and returns it, and it is handed to
|
|
636
|
+
* device.ts marked as claimed.
|
|
627
637
|
*/
|
|
628
638
|
async onDoorbell(payload) {
|
|
629
639
|
const callId = payload?.call_id;
|
|
630
640
|
if (!callId)
|
|
631
641
|
return;
|
|
632
|
-
if (payload?.device_id
|
|
642
|
+
if (payload?.device_id !== this.deviceId) {
|
|
633
643
|
console.debug('[DEBUG] Ignoring doorbell for different device');
|
|
634
644
|
return;
|
|
635
645
|
}
|
|
@@ -639,70 +649,68 @@ export class RemoteChannel {
|
|
|
639
649
|
if (!this.client)
|
|
640
650
|
return;
|
|
641
651
|
// Retry on transient failures (a REST blip while the socket stays
|
|
642
|
-
// healthy).
|
|
652
|
+
// healthy). This claim is the only way we learn about a call,
|
|
643
653
|
// so a hiccup must not cost a 5-minute timeout.
|
|
644
654
|
let row = null;
|
|
645
|
-
let
|
|
655
|
+
let claimError = null;
|
|
646
656
|
for (const delayMs of [0, 500, 1500]) {
|
|
647
657
|
if (delayMs > 0)
|
|
648
658
|
await this.sleep(delayMs);
|
|
649
659
|
const { data, error } = await this.client
|
|
650
660
|
.from('mcp_remote_calls')
|
|
651
|
-
.
|
|
661
|
+
.update({ status: 'executing' })
|
|
652
662
|
.eq('id', callId)
|
|
653
|
-
.
|
|
663
|
+
.eq('device_id', this.deviceId)
|
|
664
|
+
.eq('status', 'pending')
|
|
665
|
+
.select('*');
|
|
654
666
|
if (!error) {
|
|
655
|
-
row = data;
|
|
656
|
-
lastError = null;
|
|
667
|
+
row = data?.[0] ?? null;
|
|
657
668
|
break;
|
|
658
669
|
}
|
|
659
|
-
|
|
660
|
-
|
|
670
|
+
// Left set on purpose: a later clean empty result may still mean our
|
|
671
|
+
// own attempt committed, so the read-back below must run.
|
|
672
|
+
claimError = error;
|
|
673
|
+
console.debug(`[DEBUG] Doorbell claim attempt failed for ${callId}: ${error.message} — retrying`);
|
|
661
674
|
}
|
|
662
|
-
if (
|
|
663
|
-
|
|
664
|
-
await captureRemote('remote_channel_doorbell_fetch_error', { error: lastError });
|
|
675
|
+
if (row) {
|
|
676
|
+
this.dispatchToolCall({ new: row, claimed: true });
|
|
665
677
|
return;
|
|
666
678
|
}
|
|
667
|
-
if (!
|
|
668
|
-
//
|
|
669
|
-
|
|
670
|
-
await captureRemote('
|
|
679
|
+
if (!claimError) {
|
|
680
|
+
// Claimed by a duplicate doorbell or another process, or cleaned up.
|
|
681
|
+
console.debug('[DEBUG] Doorbell call already claimed or gone:', callId);
|
|
682
|
+
await captureRemote('remote_channel_doorbell_claim_no_row', { call_id: callId });
|
|
671
683
|
return;
|
|
672
684
|
}
|
|
673
|
-
|
|
674
|
-
//
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
*/
|
|
686
|
-
async notifyResult(callId) {
|
|
687
|
-
if (!this.channel || this.channel.state !== 'joined') {
|
|
688
|
-
console.debug('[DEBUG] Result doorbell skipped — channel not joined (recovery poll covers)');
|
|
685
|
+
await captureRemote('remote_channel_mark_call_executing_error', { error: claimError });
|
|
686
|
+
// A failed claim may never have reached the database, so read the row
|
|
687
|
+
// back: still 'pending' means nobody holds it and it can be delivered.
|
|
688
|
+
const { data: current, error } = await this.client
|
|
689
|
+
.from('mcp_remote_calls')
|
|
690
|
+
.select('*')
|
|
691
|
+
.eq('id', callId)
|
|
692
|
+
.eq('device_id', this.deviceId)
|
|
693
|
+
.maybeSingle();
|
|
694
|
+
if (error) {
|
|
695
|
+
console.error(`[DEBUG] Doorbell row fetch failed for ${callId} after claim errors:`, error.message);
|
|
696
|
+
await captureRemote('remote_channel_doorbell_fetch_error', { error });
|
|
689
697
|
return;
|
|
690
698
|
}
|
|
691
|
-
|
|
692
|
-
//
|
|
693
|
-
|
|
694
|
-
const result = await this.channel.send({ type: 'broadcast', event: 'result', payload: { call_id: callId } });
|
|
695
|
-
if (result === 'ok') {
|
|
696
|
-
console.debug('[DEBUG] Result doorbell sent:', callId);
|
|
697
|
-
}
|
|
698
|
-
else {
|
|
699
|
-
console.debug(`[DEBUG] Result doorbell not acknowledged (${result}) — recovery poll covers:`, callId);
|
|
700
|
-
captureRemote('remote_channel_result_doorbell_send_failed', { result }).catch(() => { });
|
|
701
|
-
}
|
|
699
|
+
if (current?.status === 'pending') {
|
|
700
|
+
// No claim landed; device.ts claims it.
|
|
701
|
+
this.dispatchToolCall({ new: current });
|
|
702
702
|
}
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
703
|
+
else {
|
|
704
|
+
// 'executing' reads the same whether our own claim committed with its
|
|
705
|
+
// response lost or another process holding this device_id won it, and
|
|
706
|
+
// the row carries no claimant. Running it on that guess executes a
|
|
707
|
+
// side-effecting tool twice; skipping costs one call its timeout, which
|
|
708
|
+
// is what a failed doorbell read already cost before the claim path.
|
|
709
|
+
console.debug('[DEBUG] Doorbell call already claimed or gone:', callId);
|
|
710
|
+
await captureRemote('remote_channel_doorbell_claim_unresolved', {
|
|
711
|
+
call_id: callId,
|
|
712
|
+
status: current?.status ?? null,
|
|
713
|
+
});
|
|
706
714
|
}
|
|
707
715
|
}
|
|
708
716
|
/**
|
|
@@ -749,8 +757,10 @@ export class RemoteChannel {
|
|
|
749
757
|
}
|
|
750
758
|
}
|
|
751
759
|
// Self-heal a failed presence publish: the channel is up, so nothing
|
|
752
|
-
// else will ever retry (SUBSCRIBED won't fire again)
|
|
753
|
-
//
|
|
760
|
+
// else will ever retry (SUBSCRIBED won't fire again). Until it
|
|
761
|
+
// lands the dashboard shows this device offline, and if track()
|
|
762
|
+
// already failed its retries the capability is withdrawn too, so
|
|
763
|
+
// the server fails every dispatch to it fast.
|
|
754
764
|
if (!this.presenceTracked && this.deviceId && !this.isTrackingPresence) {
|
|
755
765
|
console.debug('[DEBUG] Channel joined but presence not tracked — retrying track()');
|
|
756
766
|
this.trackPresenceWithRetry(0, 1).catch(() => { });
|
|
@@ -896,9 +906,8 @@ export class RemoteChannel {
|
|
|
896
906
|
catch (err) {
|
|
897
907
|
captureRemote('remote_channel_recreate_error', { errMsg: err?.message, attempt: this.reconnectAttempt });
|
|
898
908
|
console.debug(`[DEBUG] Channel recreation failed: ${err?.message} — ${this.connState()}`);
|
|
899
|
-
// Sustained failure: stop promising a transport we can't deliver,
|
|
900
|
-
//
|
|
901
|
-
// authoritatively and overrides `status`.
|
|
909
|
+
// Sustained failure: stop promising a transport we can't deliver, so
|
|
910
|
+
// dispatch fails fast instead of every call waiting out the timeout.
|
|
902
911
|
if (this.reconnectAttempt >= TRANSPORT_WITHDRAW_AFTER_ATTEMPTS) {
|
|
903
912
|
// Bounded, in its own try: this catch block is outside
|
|
904
913
|
// RECREATE_TIMEOUT_MS, so a hanging PATCH would pin
|
|
@@ -1055,9 +1064,8 @@ export class RemoteChannel {
|
|
|
1055
1064
|
// Skip the write entirely when no transport is up. Bumping last_seen
|
|
1056
1065
|
// on a deaf device would keep its row perpetually young, so the
|
|
1057
1066
|
// server's staleness sweep could never age it out and correct a
|
|
1058
|
-
// stale 'online' — and
|
|
1059
|
-
//
|
|
1060
|
-
// falls back to. Staying silent lets the sweep do its job.
|
|
1067
|
+
// stale 'online' — and that row is what dispatch reads. Staying
|
|
1068
|
+
// silent lets the sweep do its job.
|
|
1061
1069
|
if (!this.isReachable()) {
|
|
1062
1070
|
console.debug('[DEBUG] Skipping heartbeat write — no transport joined; letting the row age out');
|
|
1063
1071
|
return;
|
|
@@ -1188,8 +1196,8 @@ export class RemoteChannel {
|
|
|
1188
1196
|
// timeout) and refreshes when the token is within ~90s of expiry,
|
|
1189
1197
|
// POSTing /token with its own ~30s retry budget. On a just-woken
|
|
1190
1198
|
// machine that outlasts device.ts's 5s force-exit, and then spawnSync
|
|
1191
|
-
// never runs and the offline write is lost. The subprocess
|
|
1192
|
-
//
|
|
1199
|
+
// never runs and the offline write is lost. The subprocess refreshes
|
|
1200
|
+
// an expired access_token itself, so a stale one is fine.
|
|
1193
1201
|
const live = await Promise.race([
|
|
1194
1202
|
this.client.auth.getSession().then((r) => r.data?.session ?? null),
|
|
1195
1203
|
this.sleep(OFFLINE_SESSION_TIMEOUT_MS).then(() => null),
|
|
@@ -1227,7 +1235,9 @@ export class RemoteChannel {
|
|
|
1227
1235
|
supabaseUrl,
|
|
1228
1236
|
supabaseKey,
|
|
1229
1237
|
session.access_token,
|
|
1230
|
-
session
|
|
1238
|
+
// A lost session's refresh token already failed to refresh;
|
|
1239
|
+
// presenting it again can trip GoTrue's reuse detection.
|
|
1240
|
+
this.sessionLost ? '' : session.refresh_token || ''
|
|
1231
1241
|
], {
|
|
1232
1242
|
timeout: 3000,
|
|
1233
1243
|
stdio: 'pipe', // Capture output to prevent blocking
|
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
* Blocking script to update device status to offline
|
|
5
5
|
* Runs synchronously during shutdown to ensure DB update completes
|
|
6
6
|
*
|
|
7
|
-
* Usage: node blocking-offline-update.js <deviceId> <supabaseUrl> <supabaseKey> <accessToken>
|
|
7
|
+
* Usage: node blocking-offline-update.js <deviceId> <supabaseUrl> <supabaseKey> <accessToken> [refreshToken]
|
|
8
|
+
* Without a refreshToken only a still-valid accessToken can be used.
|
|
8
9
|
*/
|
|
9
10
|
|
|
10
11
|
import { createClient } from '@supabase/supabase-js';
|
|
@@ -12,9 +13,9 @@ import { createClient } from '@supabase/supabase-js';
|
|
|
12
13
|
// Parse command line arguments
|
|
13
14
|
const [deviceId, supabaseUrl, supabaseKey, accessToken, refreshToken] = process.argv.slice(2);
|
|
14
15
|
|
|
15
|
-
if (!deviceId || !supabaseUrl || !supabaseKey || !accessToken
|
|
16
|
+
if (!deviceId || !supabaseUrl || !supabaseKey || !accessToken) {
|
|
16
17
|
console.error('❌ Missing required arguments');
|
|
17
|
-
console.error('Usage: node blocking-offline-update.js <deviceId> <supabaseUrl> <supabaseKey> <accessToken>
|
|
18
|
+
console.error('Usage: node blocking-offline-update.js <deviceId> <supabaseUrl> <supabaseKey> <accessToken> [refreshToken]');
|
|
18
19
|
process.exit(1);
|
|
19
20
|
}
|
|
20
21
|
|
|
@@ -25,29 +26,58 @@ const timeoutHandle = setTimeout(() => {
|
|
|
25
26
|
process.exit(2); // Exit code 2 for timeout
|
|
26
27
|
}, TIMEOUT_MS);
|
|
27
28
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
+
}
|
|
51
|
+
}
|
|
31
52
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
53
|
+
// refreshSession(), not setSession(): setSession() validates a token that
|
|
54
|
+
// looks live on this machine's clock via /user instead of refreshing it.
|
|
55
|
+
async function refreshedToken() {
|
|
56
|
+
if (!refreshToken) {
|
|
57
|
+
console.error('❌ Auth error: access token not usable and no refresh token');
|
|
58
|
+
clearTimeout(timeoutHandle);
|
|
59
|
+
process.exit(3); // Exit code 3 for auth error
|
|
60
|
+
}
|
|
61
|
+
const client = createClient(supabaseUrl, supabaseKey, { auth });
|
|
62
|
+
const { data, error: authError } = await client.auth.refreshSession({ refresh_token: refreshToken });
|
|
37
63
|
|
|
38
|
-
if (authError) {
|
|
39
|
-
console.error('❌ Auth error:', authError
|
|
64
|
+
if (authError || !data.session) {
|
|
65
|
+
console.error('❌ Auth error:', authError?.message ?? 'no session returned');
|
|
40
66
|
clearTimeout(timeoutHandle);
|
|
41
67
|
process.exit(3); // Exit code 3 for auth error
|
|
42
68
|
}
|
|
69
|
+
return data.session.access_token;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
try {
|
|
73
|
+
// An expired token (e.g. the machine just woke) is refreshed first. A 401
|
|
74
|
+
// means it only looked live on this machine's clock: refresh and retry once.
|
|
75
|
+
let result = tokenLooksLive(accessToken) ? await markOffline(accessToken) : null;
|
|
76
|
+
if (!result || result.status === 401) {
|
|
77
|
+
result = await markOffline(await refreshedToken());
|
|
78
|
+
}
|
|
43
79
|
|
|
44
|
-
|
|
45
|
-
// "last seen X ago" is precise for clean shutdowns (the periodic
|
|
46
|
-
// bookkeeping write only runs on the slow capable cadence).
|
|
47
|
-
const { error } = await client
|
|
48
|
-
.from('mcp_devices')
|
|
49
|
-
.update({ status: 'offline', last_seen: new Date().toISOString() })
|
|
50
|
-
.eq('id', deviceId);
|
|
80
|
+
const { error } = result;
|
|
51
81
|
|
|
52
82
|
clearTimeout(timeoutHandle);
|
|
53
83
|
|
package/dist/server.js
CHANGED
|
@@ -1051,16 +1051,18 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
|
1051
1051
|
{
|
|
1052
1052
|
name: "get_recent_tool_calls",
|
|
1053
1053
|
description: `
|
|
1054
|
-
Get recent tool call history with
|
|
1055
|
-
Returns chronological list of
|
|
1054
|
+
Get recent local tool call history with arguments and outputs.
|
|
1055
|
+
Returns a chronological list of recent calls loaded from the local history file.
|
|
1056
1056
|
|
|
1057
1057
|
Useful for:
|
|
1058
1058
|
- Onboarding new chats about work already done
|
|
1059
1059
|
- Recovering context after chat history loss
|
|
1060
1060
|
- Debugging tool call sequences
|
|
1061
1061
|
|
|
1062
|
-
Note: Does not track its own calls or
|
|
1063
|
-
History
|
|
1062
|
+
Note: Does not track its own calls or track_ui_event.
|
|
1063
|
+
History is persisted locally in tool-history.jsonl, keeps up to the last 1000
|
|
1064
|
+
calls in memory, and trims older on-disk history. Stored outputs over 4 KiB
|
|
1065
|
+
are replaced with an omission marker.
|
|
1064
1066
|
|
|
1065
1067
|
${CMD_PREFIX_DESCRIPTION}`,
|
|
1066
1068
|
inputSchema: zodToJsonSchema(GetRecentToolCallsArgsSchema),
|
package/dist/terminal-manager.js
CHANGED
|
@@ -203,6 +203,28 @@ export class TerminalManager {
|
|
|
203
203
|
// Spawn the process with appropriate arguments
|
|
204
204
|
const childProcess = spawn(spawnConfig.executable, spawnConfig.args, spawnOptions);
|
|
205
205
|
let output = '';
|
|
206
|
+
// spawn() reports failure asynchronously via an 'error' event; it does not
|
|
207
|
+
// throw. Node rethrows an 'error' that has no listener as an uncaught
|
|
208
|
+
// exception, and our process-level handler (src/index.ts) turns that into
|
|
209
|
+
// process.exit(1). So an unresolvable executable — e.g. shell: "/usr/bin/bash"
|
|
210
|
+
// on Windows — used to kill the entire MCP server one tick AFTER this
|
|
211
|
+
// function had already returned "Failed to get process ID", making the crash
|
|
212
|
+
// look unrelated to the command that caused it. Under `remote` the parent
|
|
213
|
+
// then kept accepting tool calls over a dead stdio pipe ("Not connected").
|
|
214
|
+
//
|
|
215
|
+
// Attach before any return path below, and keep it for the session lifetime
|
|
216
|
+
// so a later runtime error (EPIPE on a closed stdin, ...) can't crash us either.
|
|
217
|
+
let forwardProcessError = null;
|
|
218
|
+
let pendingProcessError = null;
|
|
219
|
+
childProcess.on('error', (err) => {
|
|
220
|
+
if (forwardProcessError) {
|
|
221
|
+
forwardProcessError(err);
|
|
222
|
+
}
|
|
223
|
+
else {
|
|
224
|
+
pendingProcessError = err;
|
|
225
|
+
console.error(`Process error for "${command}": ${err.message}`);
|
|
226
|
+
}
|
|
227
|
+
});
|
|
206
228
|
// Ensure childProcess.pid is defined before proceeding
|
|
207
229
|
if (!childProcess.pid) {
|
|
208
230
|
// Return a consistent error object instead of throwing
|
|
@@ -257,6 +279,23 @@ export class TerminalManager {
|
|
|
257
279
|
}
|
|
258
280
|
resolve(result);
|
|
259
281
|
};
|
|
282
|
+
// Now that resolveOnce exists, route process errors into it: an error after
|
|
283
|
+
// a successful spawn means the process is gone, so the caller must not sit
|
|
284
|
+
// waiting for output that will never arrive.
|
|
285
|
+
forwardProcessError = (err) => {
|
|
286
|
+
this.sessions.delete(childProcess.pid);
|
|
287
|
+
exitReason = 'process_exit';
|
|
288
|
+
resolveOnce({
|
|
289
|
+
pid: childProcess.pid,
|
|
290
|
+
output: output + `\nProcess error: ${err.message}`,
|
|
291
|
+
isBlocked: false
|
|
292
|
+
});
|
|
293
|
+
};
|
|
294
|
+
// An error emitted between spawn and here (the common case — spawn errors
|
|
295
|
+
// land on the next tick) is replayed rather than dropped.
|
|
296
|
+
if (pendingProcessError) {
|
|
297
|
+
forwardProcessError(pendingProcessError);
|
|
298
|
+
}
|
|
260
299
|
childProcess.stdout.on('data', (data) => {
|
|
261
300
|
const text = data.toString();
|
|
262
301
|
const now = Date.now();
|
package/dist/tools/edit.js
CHANGED
|
@@ -239,6 +239,19 @@ RECOMMENDATION: For large search/replace operations, consider breaking them into
|
|
|
239
239
|
// Log to file
|
|
240
240
|
await fuzzySearchLogger.log(logEntry);
|
|
241
241
|
// Combine all fuzzy search data for single capture
|
|
242
|
+
//
|
|
243
|
+
// character_codes (characterCodeData.report) is deliberately NOT sent.
|
|
244
|
+
// It is a frequency map of the characters in the diff between the
|
|
245
|
+
// search text and the file text, so for a short diff it is close to
|
|
246
|
+
// recoverable file content — and mcp-privacy-policy.md states that
|
|
247
|
+
// file contents are not collected. It was added as diagnostics for the
|
|
248
|
+
// CRLF/LF normalization work in #103 (May 2025) to show whether failed
|
|
249
|
+
// matches came from \r (13), \n (10) or non-breaking spaces; that
|
|
250
|
+
// question is long since answered.
|
|
251
|
+
//
|
|
252
|
+
// The scalars below are kept: they are counts and lengths, and carry
|
|
253
|
+
// no recoverable content. The full report still goes to the local
|
|
254
|
+
// fuzzy-search.log for anyone debugging on their own machine.
|
|
242
255
|
const fuzzySearchData = {
|
|
243
256
|
similarity: similarity,
|
|
244
257
|
execution_time_ms: executionTime,
|
|
@@ -246,7 +259,6 @@ RECOMMENDATION: For large search/replace operations, consider breaking them into
|
|
|
246
259
|
file_size: content.length,
|
|
247
260
|
threshold: FUZZY_THRESHOLD,
|
|
248
261
|
found_text_length: fuzzyResult.value.length,
|
|
249
|
-
character_codes: characterCodeData.report,
|
|
250
262
|
unique_character_count: characterCodeData.uniqueCount,
|
|
251
263
|
total_diff_length: characterCodeData.diffLength
|
|
252
264
|
};
|
package/dist/tools/process.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ProcessInfo, ServerResult } from '../types.js';
|
|
2
2
|
/**
|
|
3
|
-
* Parse `tasklist /
|
|
3
|
+
* Parse `tasklist /FO CSV /NH` output (#662). Fields per row, all quoted:
|
|
4
4
|
* [Image Name, PID, Session Name, Session#, Mem Usage]. CSV instead of the
|
|
5
5
|
* default table: image names can contain spaces and Mem Usage contains
|
|
6
6
|
* thousands separators, so positional whitespace splitting can't work.
|
package/dist/tools/process.js
CHANGED
|
@@ -4,7 +4,7 @@ import os from 'os';
|
|
|
4
4
|
import { KillProcessArgsSchema } from './schemas.js';
|
|
5
5
|
const execAsync = promisify(exec);
|
|
6
6
|
/**
|
|
7
|
-
* Parse `tasklist /
|
|
7
|
+
* Parse `tasklist /FO CSV /NH` output (#662). Fields per row, all quoted:
|
|
8
8
|
* [Image Name, PID, Session Name, Session#, Mem Usage]. CSV instead of the
|
|
9
9
|
* default table: image names can contain spaces and Mem Usage contains
|
|
10
10
|
* thousands separators, so positional whitespace splitting can't work.
|
|
@@ -46,7 +46,7 @@ export function parsePsAux(stdout) {
|
|
|
46
46
|
}
|
|
47
47
|
export async function listProcesses() {
|
|
48
48
|
const isWindows = os.platform() === 'win32';
|
|
49
|
-
const command = isWindows ? 'tasklist /
|
|
49
|
+
const command = isWindows ? 'tasklist /FO CSV /NH' : 'ps aux';
|
|
50
50
|
try {
|
|
51
51
|
const { stdout } = await execAsync(command);
|
|
52
52
|
const processes = isWindows ? parseWindowsTasklistCsv(stdout) : parsePsAux(stdout);
|
|
@@ -693,12 +693,6 @@ export default async function uninstall() {
|
|
|
693
693
|
logToFile('\nIf you want to reinstall later, you can run:');
|
|
694
694
|
logToFile('npx @wonderwhy-er/desktop-commander@latest setup');
|
|
695
695
|
|
|
696
|
-
logToFile('\n🎁 We\'re sorry to see you leaving, we’d love to understand your decision not to use Desktop Commander.')
|
|
697
|
-
logToFile('In return for a brief 30-minute call, we’ll send you a $20 Amazon gift card as a thank-you.');
|
|
698
|
-
logToFile('To get a gift card, please fill out this form:');
|
|
699
|
-
logToFile(' https://tally.so/r/w8lyRo');
|
|
700
|
-
|
|
701
|
-
|
|
702
696
|
logToFile('\nThank you for using Desktop Commander! 👋\n');
|
|
703
697
|
|
|
704
698
|
// Send final tracking event
|
|
@@ -712,11 +706,6 @@ export default async function uninstall() {
|
|
|
712
706
|
logToFile('You may need to manually remove Desktop Commander from Claude\'s configuration.');
|
|
713
707
|
logToFile(`Configuration file location: ${claudeConfigPath}\n`);
|
|
714
708
|
|
|
715
|
-
logToFile('\n🎁 We\'re sorry to see you leaving, we\'d love to understand your decision not to use Desktop Commander.')
|
|
716
|
-
logToFile('In return for a brief 30-minute call, we\'ll send you a $20 Amazon gift card as a thank-you.');
|
|
717
|
-
logToFile('To get a gift card, please fill out this form:');
|
|
718
|
-
logToFile(' https://tally.so/r/w8lyRo');
|
|
719
|
-
|
|
720
709
|
await ensureTrackingCompleted('uninstall_partial_failure');
|
|
721
710
|
|
|
722
711
|
return false;
|
|
@@ -735,10 +724,6 @@ export default async function uninstall() {
|
|
|
735
724
|
logToFile('You may need to manually remove Desktop Commander from Claude\'s configuration.');
|
|
736
725
|
logToFile(`Configuration file location: ${claudeConfigPath}\n`);
|
|
737
726
|
|
|
738
|
-
logToFile('\n🎁 We\'re sorry to see you leaving, we\'d love to understand your decision not to use Desktop Commander.')
|
|
739
|
-
logToFile('In return for a brief 30-minute call, we\'ll send you a $20 Amazon gift card as a thank-you.');
|
|
740
|
-
logToFile('To get a gift card, please fill out this form:');
|
|
741
|
-
logToFile('https://tally.so/r/w8lyRo');
|
|
742
727
|
return false;
|
|
743
728
|
}
|
|
744
729
|
}
|
|
@@ -19,6 +19,7 @@ import { FileHandler, ReadOptions, FileResult, FileInfo } from './base.js';
|
|
|
19
19
|
*/
|
|
20
20
|
export declare class TextFileHandler implements FileHandler {
|
|
21
21
|
canHandle(_path: string): boolean;
|
|
22
|
+
private detectTextEncoding;
|
|
22
23
|
read(filePath: string, options?: ReadOptions): Promise<FileResult>;
|
|
23
24
|
write(path: string, content: string, mode?: 'rewrite' | 'append'): Promise<void>;
|
|
24
25
|
getInfo(path: string): Promise<FileInfo>;
|