@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.
@@ -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> <refreshToken>
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 || !refreshToken) {
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> <refreshToken>');
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
- try {
29
- // Create Supabase client
30
- const client = createClient(supabaseUrl, supabaseKey);
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
- // Set session using access token and refresh token
33
- const { error: authError } = await client.auth.setSession({
34
- access_token: accessToken,
35
- refresh_token: refreshToken
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.message);
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
- // Update device status to offline, stamping the exact shutdown moment so
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
@@ -278,7 +278,7 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
278
278
  Read contents from files and URLs.
279
279
  Read PDF files and extract content as markdown and images.
280
280
 
281
- Prefer this over 'execute_command' with cat/type for viewing files.
281
+ Suitable for reading authorized local files directly without starting a shell command.
282
282
 
283
283
  Supports partial file reading with:
284
284
  - 'offset' (start line, default: 0)
@@ -790,47 +790,27 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
790
790
  {
791
791
  name: "start_process",
792
792
  description: `
793
- Start a new terminal process with intelligent state detection.
793
+ Start a terminal process on the authorized device with intelligent state detection.
794
794
 
795
- PRIMARY TOOL FOR FILE ANALYSIS AND DATA PROCESSING
796
- This is the ONLY correct tool for analyzing local files (CSV, JSON, logs, etc.).
797
- The analysis tool CANNOT access local files and WILL FAIL - always use processes for file-based work.
798
-
799
- CRITICAL RULE: For ANY local file work, ALWAYS use this tool + interact_with_process, NEVER use analysis/REPL tool.
795
+ Suitable for shell commands, interactive REPL sessions, data-processing scripts,
796
+ programmatic file analysis, and other long-running terminal work.
800
797
 
801
798
  ${OS_GUIDANCE}
802
799
 
803
- REQUIRED WORKFLOW FOR LOCAL FILES:
804
- 1. start_process("python3 -i") - Start Python REPL for data analysis
805
- 2. interact_with_process(pid, "import pandas as pd, numpy as np")
806
- 3. interact_with_process(pid, "df = pd.read_csv('/absolute/path/file.csv')")
807
- 4. interact_with_process(pid, "print(df.describe())")
808
- 5. Continue analysis with pandas, matplotlib, seaborn, etc.
809
-
810
- COMMON FILE ANALYSIS PATTERNS:
811
- • start_process("python3 -i") → Python REPL for data analysis (RECOMMENDED)
812
- • start_process("node -i") → Node.js REPL for JSON processing
813
- • start_process("node:local") → Node.js on MCP server (stateless, ES imports, all code in one call)
814
- • start_process("cut -d',' -f1 file.csv | sort | uniq -c") → Quick CSV analysis
815
- • start_process("wc -l /path/file.csv") → Line counting
816
- • start_process("head -10 /path/file.csv") → File preview
817
-
818
- BINARY FILE SUPPORT:
819
- For PDF, Excel, Word, archives, databases, and other binary formats, use process tools with appropriate libraries or command-line utilities.
820
-
821
- INTERACTIVE PROCESSES FOR DATA ANALYSIS:
822
- For code/calculations, use in this priority order:
823
- 1. start_process("python3 -i") - Python REPL (preferred)
824
- 2. start_process("node -i") - Node.js REPL (when Python unavailable)
825
- 3. start_process("node:local") - Node.js fallback (when node -i fails)
826
- 4. Use interact_with_process() to send commands
827
- 5. Use read_process_output() to get responses
828
- When Python is unavailable, prefer Node.js over shell for calculations.
829
- Node.js: Always use ES import syntax (import x from 'y'), not require().
800
+ Examples:
801
+ • start_process("python3 -i") → Start an interactive Python REPL
802
+ • start_process("node -i") → Start an interactive Node.js REPL
803
+ • start_process("node:local") → Run stateless Node.js code on the MCP server
804
+ • start_process("wc -l /path/file.csv") → Run a one-shot shell command
805
+
806
+ Interactive process sessions support follow-up input after they are started.
807
+ Long-running process sessions expose newly available output while they remain active.
808
+ Binary files can be processed with appropriate command-line tools or libraries available
809
+ in the selected process environment.
830
810
 
831
811
  SMART DETECTION:
832
812
  - Detects REPL prompts (>>>, >, $, etc.)
833
- - Identifies when process is waiting for input
813
+ - Identifies when a process is waiting for input
834
814
  - Recognizes process completion vs timeout
835
815
  - Early exit prevents unnecessary waiting
836
816
 
@@ -845,10 +825,6 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
845
825
  - Total duration and time to first output
846
826
  - Complete timeline of all output events with timestamps
847
827
  - Which detection mechanism triggered early exit
848
- Use this to identify missed optimization opportunities and improve detection patterns.
849
-
850
- ALWAYS USE FOR: Local file analysis, CSV processing, data exploration, system commands
851
- NEVER USE ANALYSIS TOOL FOR: Local file access (analysis tool is browser-only and WILL FAIL)
852
828
 
853
829
  ${PATH_GUIDANCE}
854
830
  ${CMD_PREFIX_DESCRIPTION}`,
@@ -904,60 +880,36 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
904
880
  {
905
881
  name: "interact_with_process",
906
882
  description: `
907
- Send input to a running process and automatically receive the response.
883
+ Send input to an existing terminal or REPL process and return newly available output.
908
884
 
909
- CRITICAL: THIS IS THE PRIMARY TOOL FOR ALL LOCAL FILE ANALYSIS
910
- For ANY local file analysis (CSV, JSON, data processing), ALWAYS use this instead of the analysis tool.
911
- The analysis tool CANNOT access local files and WILL FAIL - use processes for ALL file-based work.
885
+ Useful for interactive shells, Python/Node/R/Julia REPLs, database consoles,
886
+ and long-running commands started with start_process().
912
887
 
913
- FILE ANALYSIS PRIORITY ORDER (MANDATORY):
914
- 1. ALWAYS FIRST: Use this tool (start_process + interact_with_process) for local data analysis
915
- 2. ALTERNATIVE: Use command-line tools (cut, awk, grep) for quick processing
916
- 3. NEVER EVER: Use analysis tool for local file access (IT WILL FAIL)
917
-
918
- REQUIRED INTERACTIVE WORKFLOW FOR FILE ANALYSIS:
919
- 1. Start REPL: start_process("python3 -i")
920
- 2. Load libraries: interact_with_process(pid, "import pandas as pd, numpy as np")
921
- 3. Read file: interact_with_process(pid, "df = pd.read_csv('/absolute/path/file.csv')")
922
- 4. Analyze: interact_with_process(pid, "print(df.describe())")
923
- 5. Continue: interact_with_process(pid, "df.groupby('column').size()")
924
-
925
- BINARY FILE PROCESSING WORKFLOWS:
926
- Use appropriate Python libraries (PyPDF2, pandas, docx2txt, etc.) or command-line tools for binary file analysis.
888
+ Examples:
889
+ - Interactive Python REPL sessions can be started with \`python3 -i\`.
890
+ - Existing interactive sessions accept additional input such as imports or analysis commands.
891
+ - Interactive sessions can return newly available output while they remain active.
927
892
 
928
893
  SMART DETECTION:
929
- - Automatically waits for REPL prompt (>>>, >, etc.)
894
+ - Automatically waits for a recognized prompt when requested
930
895
  - Detects errors and completion states
931
- - Early exit prevents timeout delays
932
- - Clean output formatting (removes prompts)
933
-
934
- SUPPORTED REPLs:
935
- - Python: python3 -i (RECOMMENDED for data analysis)
936
- - Node.js: node -i
937
- - R: R
938
- - Julia: julia
939
- - Shell: bash, zsh
940
- - Database: mysql, postgres
896
+ - Early exit prevents unnecessary waiting
897
+ - Cleans common REPL prompt text from returned output
941
898
 
942
899
  PARAMETERS:
943
- - pid: Process ID from start_process
944
- - input: Code/command to execute
945
- - timeout_ms: Max wait (default: 8000ms)
946
- - wait_for_prompt: Auto-wait for response (default: true)
947
- - verbose_timing: Enable detailed performance telemetry (default: false)
900
+ - pid: Process ID returned by start_process
901
+ - input: Text or command to send to the process
902
+ - timeout_ms: Maximum wait time (default: 8000ms)
903
+ - wait_for_prompt: Whether to wait for a prompt before returning (default: true)
904
+ - verbose_timing: Include detailed timing telemetry (default: false)
948
905
 
949
906
  Returns execution result with status indicators.
950
907
 
951
908
  PERFORMANCE DEBUGGING (verbose_timing parameter):
952
- Set verbose_timing: true to get detailed timing information including:
953
- - Exit reason (early_exit_quick_pattern, early_exit_periodic_check, process_finished, timeout, no_wait)
909
+ When enabled, detailed timing includes:
910
+ - Exit reason
954
911
  - Total duration and time to first output
955
- - Complete timeline of all output events with timestamps
956
- - Which detection mechanism triggered early exit
957
- Use this to identify slow interactions and optimize detection patterns.
958
-
959
- ALWAYS USE FOR: CSV analysis, JSON processing, file statistics, data visualization prep, ANY local file work
960
- NEVER USE ANALYSIS TOOL FOR: Local file access (it cannot read files from disk and WILL FAIL)
912
+ - Timeline of output events
961
913
 
962
914
  ${CMD_PREFIX_DESCRIPTION}`,
963
915
  inputSchema: zodToJsonSchema(InteractWithProcessArgsSchema),
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.2.50";
1
+ export declare const VERSION = "0.2.52";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '0.2.50';
1
+ export const VERSION = '0.2.52';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wonderwhy-er/desktop-commander",
3
- "version": "0.2.50",
3
+ "version": "0.2.52",
4
4
  "description": "MCP server for terminal operations and file editing",
5
5
  "mcpName": "io.github.wonderwhy-er/desktop-commander",
6
6
  "license": "MIT",