@openagents-org/agent-launcher 0.2.133 → 0.2.134

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openagents-org/agent-launcher",
3
- "version": "0.2.133",
3
+ "version": "0.2.134",
4
4
  "description": "OpenAgents Launcher — install, configure, and run AI coding agents from your terminal",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -205,7 +205,13 @@ class CursorAdapter extends BaseAdapter {
205
205
  }
206
206
 
207
207
  // Tier 3: Common install locations
208
+ const localAppData = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
208
209
  const candidates = IS_WINDOWS ? [
210
+ // Windows native installer (install?win32=true) drops the CLI here.
211
+ path.join(localAppData, 'cursor-agent', 'cursor-agent.cmd'),
212
+ path.join(localAppData, 'cursor-agent', 'cursor-agent.exe'),
213
+ path.join(localAppData, 'cursor-agent', 'agent.cmd'),
214
+ path.join(localAppData, 'cursor-agent', 'agent.exe'),
209
215
  path.join(home, '.cursor', 'bin', 'cursor-agent.cmd'),
210
216
  path.join(home, '.cursor', 'bin', 'cursor-agent.exe'),
211
217
  path.join(home, '.cursor', 'bin', 'cursor-agent'),
@@ -195,6 +195,12 @@ class GeminiAdapter extends BaseAdapter {
195
195
 
196
196
  const cmd = [geminiBin, '-p', fullPrompt, '-y', '-o', 'stream-json'];
197
197
 
198
+ // Honor a user-configured model (e.g. when pointing at a relay/proxy whose
199
+ // channels don't match the CLI default). Set via GEMINI_MODEL in env_config.
200
+ const env = this.agentEnv || process.env;
201
+ const model = (env.GEMINI_MODEL || env.GOOGLE_GEMINI_MODEL || '').trim();
202
+ if (model) cmd.push('-m', model);
203
+
198
204
  const sessionId = this._channelSessions[channelName];
199
205
  if (sessionId && !skipResume) {
200
206
  cmd.push('-r', sessionId);
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Pure data helpers for the agent list, shared by the TUI (tui.js) and tests.
3
+ *
4
+ * Kept free of any UI/blessed dependency so the list-rendering logic — in
5
+ * particular the "(local)" labelling and Connect gating — can be unit-tested.
6
+ */
7
+
8
+ 'use strict';
9
+
10
+ /**
11
+ * Build one display row per configured agent from a connector.
12
+ *
13
+ * `workspace` holds the resolved workspace URL (or '' when the agent is not
14
+ * connected). `workspaceLabel` is what the WORKSPACE column shows: the URL when
15
+ * connected, otherwise "(local)" — matching `agn list` so local-only agents are
16
+ * always visible rather than rendered as a blank cell.
17
+ */
18
+ function loadAgentRows(connector) {
19
+ const config = connector.config.load();
20
+ const agents = config.agents || [];
21
+ const agentStatuses = connector.getDaemonStatus() || {};
22
+ const pid = connector.getDaemonPid();
23
+ const networks = config.networks || [];
24
+ return agents.map(agent => {
25
+ const info = agentStatuses[agent.name] || {};
26
+ const state = pid ? (info.state || 'stopped') : 'stopped';
27
+ let workspace = '';
28
+ if (agent.network) {
29
+ const net = networks.find(n => n.slug === agent.network || n.id === agent.network);
30
+ if (net) {
31
+ const slug = net.slug || net.id;
32
+ const isLocal = (net.endpoint || '').includes('localhost') || (net.endpoint || '').includes('127.0.0.1');
33
+ if (isLocal) workspace = `${net.endpoint}/${slug}`;
34
+ else workspace = `workspace.openagents.org/${slug}`;
35
+ } else {
36
+ workspace = agent.network;
37
+ }
38
+ }
39
+ let notReadyMsg = '';
40
+ let health = null;
41
+ try {
42
+ health = connector.healthCheck(agent.type || 'openclaw');
43
+ if (health && !health.ready) notReadyMsg = health.message || 'Not configured';
44
+ } catch {}
45
+
46
+ return {
47
+ name: agent.name,
48
+ type: agent.type || 'openclaw',
49
+ state,
50
+ workspace,
51
+ // "(local)" when there's no workspace connection; URL otherwise. `workspace`
52
+ // stays empty for local-only agents so Connect gating still treats them as
53
+ // connectable (see connectAvailable).
54
+ workspaceLabel: workspace || '(local)',
55
+ path: agent.path || '',
56
+ network: agent.network || '',
57
+ lastError: info.last_error || '',
58
+ notReadyMsg,
59
+ health,
60
+ configured: true,
61
+ };
62
+ });
63
+ }
64
+
65
+ /**
66
+ * An agent can be connected to a workspace when it's configured and not already
67
+ * bound to one. Mirrors the footer/menu gating so it can be unit-tested.
68
+ */
69
+ function connectAvailable(row) {
70
+ return !!(row && row.configured && !row.workspace);
71
+ }
72
+
73
+ module.exports = { loadAgentRows, connectAvailable };
package/src/cli.js CHANGED
@@ -123,7 +123,6 @@ async function cmdCreate(connector, flags, positional) {
123
123
 
124
124
  try {
125
125
  connector.addAgent({ name, type, role, path: flags.path || process.cwd() });
126
- print(`Agent '${name}' created (type: ${type})`);
127
126
 
128
127
  // Signal daemon to pick up the new agent
129
128
  try { connector.sendDaemonCommand('reload'); } catch {}
@@ -132,10 +131,14 @@ async function cmdCreate(connector, flags, positional) {
132
131
  // Without a workspace connection they will not appear in the Workspace Dashboard.
133
132
  const created = connector.config.getAgent(name);
134
133
  if (created && !created.network) {
134
+ print(`Created local agent: ${name} (type: ${type})`);
135
135
  print('');
136
- print(`Note: '${name}' is local-only and will not appear in the Workspace Dashboard.`);
137
- print(`To make it visible, connect it to a workspace:`);
136
+ print('This agent is local-only and will not appear in Workspace Dashboard yet.');
137
+ print('');
138
+ print('To connect it to a Workspace, run:');
138
139
  print(` agn connect ${name} <workspace-token>`);
140
+ } else {
141
+ print(`Agent '${name}' created (type: ${type})`);
139
142
  }
140
143
 
141
144
  if (!connector.isInstalled(type)) {
@@ -306,11 +309,10 @@ async function cmdConnect(connector, flags, positional) {
306
309
  // No token supplied and none in the environment. Never prompt — keep
307
310
  // CI / non-interactive environments from hanging. Print a helpful error
308
311
  // explaining why the agent stays invisible and how to fix it.
309
- print(`Error: no workspace token provided for '${name}'.`);
310
- print(`Without a token, '${name}' stays local-only and will not appear in the Workspace Dashboard.`);
311
- print('Provide a token in one of these ways:');
312
+ print('Workspace token is required.');
313
+ print('Local-only agents do not appear in Workspace Dashboard until connected.');
314
+ print('Run:');
312
315
  print(` agn connect ${name} <workspace-token>`);
313
- print(` OPENAGENTS_WORKSPACE_TOKEN=<workspace-token> agn connect ${name}`);
314
316
  process.exitCode = 1;
315
317
  return;
316
318
  }
package/src/installer.js CHANGED
@@ -414,31 +414,72 @@ class Installer {
414
414
  await this.installNodejs(onData);
415
415
  }
416
416
 
417
- // Resolve npm command
418
- let cmd = rawCmd;
417
+ const env = this._buildShellEnv();
418
+ const isWin = process.platform === 'win32';
419
+
420
+ // Build the spawn invocation. Three shapes:
421
+ // 1. npm install via bundled `node npm-cli.js` — argv array, no shell.
422
+ // Path-safe under non-ASCII home dirs on Windows (preferred).
423
+ // 2. npm install via legacy shell string (npm.cmd / npm) — fallback only
424
+ // when no node + npm-cli.js layout is found; OEM-codepage corruption
425
+ // means this breaks on non-ASCII paths, but still works for ASCII.
426
+ // 3. pip / curl / powershell — keep the legacy shell-string behaviour.
427
+ let spawnFile;
428
+ let spawnArgs = [];
429
+ let useShell;
430
+ let installCwd;
431
+ let displayCmd;
432
+
419
433
  if (rawCmd.startsWith('npm install')) {
420
434
  const prefixDir = getRuntimePrefix(agentType);
421
435
  fs.mkdirSync(prefixDir, { recursive: true });
422
- // Use --save so npm tracks the package in package.json (prevents pruning on next install)
423
- const args = rawCmd.replace('npm install', 'install --loglevel=verbose --save').replace(' -g ', ` --prefix "${prefixDir}" `);
424
- cmd = this._resolveNpmCommand(args);
425
- } else if (rawCmd.startsWith('pip install') || rawCmd.startsWith('pipx install')) {
426
- cmd = rawCmd; // pip commands stay as-is
436
+ installCwd = prefixDir;
437
+
438
+ // `npm install [-g] <pkg…>` → install --save --prefix <dir> <pkg…>
439
+ const pkgArgs = rawCmd
440
+ .replace(/^npm install\s*/, '')
441
+ .replace(/(^|\s)-g(\s|$)/, ' ')
442
+ .trim()
443
+ .split(/\s+/)
444
+ .filter(Boolean);
445
+ // Use --save so npm tracks the package in package.json (prevents pruning
446
+ // on next install).
447
+ const npmArgs = ['install', '--loglevel=verbose', '--save', '--prefix', prefixDir, ...pkgArgs];
448
+ displayCmd = `npm ${npmArgs.join(' ')}`;
449
+
450
+ const direct = this._resolveNodeNpmCli();
451
+ if (direct) {
452
+ spawnFile = direct.node;
453
+ spawnArgs = [direct.npmCli, ...npmArgs];
454
+ useShell = false;
455
+ // Ensure npm's own `node` child lookups (postinstall scripts) resolve
456
+ // to this same runtime by putting its dir first on PATH.
457
+ const pathKey = Object.keys(env).find(k => k.toLowerCase() === 'path') || 'PATH';
458
+ const nodeDir = path.dirname(direct.node);
459
+ if (!(env[pathKey] || '').includes(nodeDir)) {
460
+ env[pathKey] = nodeDir + (isWin ? ';' : ':') + (env[pathKey] || '');
461
+ }
462
+ } else {
463
+ // Legacy fallback: quoted prefix inside a shell string.
464
+ const args = `install --loglevel=verbose --save --prefix "${prefixDir}" ${pkgArgs.join(' ')}`;
465
+ spawnFile = this._wrapForWindowsShell(this._resolveNpmCommand(args));
466
+ useShell = isWin ? (env.ComSpec || 'C:\\Windows\\System32\\cmd.exe') : true;
467
+ displayCmd = spawnFile;
468
+ }
469
+ } else {
470
+ // pip / curl / powershell — unchanged shell-string behaviour.
471
+ spawnFile = this._wrapForWindowsShell(rawCmd);
472
+ useShell = isWin ? (env.ComSpec || 'C:\\Windows\\System32\\cmd.exe') : true;
473
+ // Set cwd outside System32 on Windows.
474
+ installCwd = os.homedir();
475
+ displayCmd = spawnFile;
427
476
  }
428
477
 
429
- cmd = this._wrapForWindowsShell(cmd);
430
-
431
- if (onData) onData(`$ ${cmd}\n\n`);
432
-
433
- const env = this._buildShellEnv();
434
- const shell = process.platform === 'win32'
435
- ? (process.env.ComSpec || 'C:\\Windows\\System32\\cmd.exe')
436
- : true;
437
- // Set cwd to runtime prefix dir (avoids running from System32 on Windows)
438
- const installCwd = rawCmd.startsWith('npm install') ? getRuntimePrefix(agentType) : os.homedir();
478
+ if (onData) onData(`$ ${displayCmd}\n\n`);
439
479
 
440
480
  return new Promise((resolve, reject) => {
441
- const proc = spawn(cmd, [], { shell, env, cwd: installCwd, stdio: ['ignore', 'pipe', 'pipe'] });
481
+ // windowsHide stops a console window from flashing up on every install.
482
+ const proc = spawn(spawnFile, spawnArgs, { shell: useShell, env, cwd: installCwd, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
442
483
 
443
484
  if (proc.stdout) proc.stdout.setEncoding('utf-8');
444
485
  if (proc.stderr) proc.stderr.setEncoding('utf-8');
@@ -458,7 +499,7 @@ class Installer {
458
499
  if (code === 0) {
459
500
  this._markInstalled(agentType);
460
501
  if (onData) onData(`\nDone! ${agentType} is now installed.\n`);
461
- resolve({ success: true, command: cmd });
502
+ resolve({ success: true, command: displayCmd });
462
503
  } else {
463
504
  // A partial install can leave a placeholder stub at
464
505
  // bin/<binary>.exe and npm-generated cmd-shims under
@@ -473,8 +514,8 @@ class Installer {
473
514
  } catch {}
474
515
  const tail = outputTail.trim();
475
516
  const msg = tail
476
- ? `Install failed with exit code ${code}\nCommand: ${cmd}\n\n${tail}`
477
- : `Install failed with exit code ${code}\nCommand: ${cmd}`;
517
+ ? `Install failed with exit code ${code}\nCommand: ${displayCmd}\n\n${tail}`
518
+ : `Install failed with exit code ${code}\nCommand: ${displayCmd}`;
478
519
  if (onData) onData(`\n${msg}\n`);
479
520
  reject(new Error(msg));
480
521
  }
@@ -599,7 +640,7 @@ class Installer {
599
640
  : true;
600
641
 
601
642
  return new Promise((resolve, reject) => {
602
- const proc = spawn(cmd, [], { shell, env, stdio: ['ignore', 'pipe', 'pipe'] });
643
+ const proc = spawn(cmd, [], { shell, env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
603
644
 
604
645
  if (proc.stdout) proc.stdout.setEncoding('utf-8');
605
646
  if (proc.stderr) proc.stderr.setEncoding('utf-8');
@@ -811,9 +852,14 @@ class Installer {
811
852
  } catch {}
812
853
  }
813
854
  }
855
+ // On Windows the spread above yields a "Path" key, not "PATH". Writing
856
+ // `env.PATH` would create a duplicate key holding only extraDirs and drop
857
+ // everything else; libuv then resolves spawned binaries against the wrong,
858
+ // truncated value. Update the existing case-insensitive key in place.
859
+ const pathKey = Object.keys(env).find(k => k.toLowerCase() === 'path') || 'PATH';
814
860
  for (const d of extraDirs) {
815
- if (d && !(env.PATH || '').includes(d)) {
816
- env.PATH = d + sep + (env.PATH || '');
861
+ if (d && !(env[pathKey] || '').includes(d)) {
862
+ env[pathKey] = d + sep + (env[pathKey] || '');
817
863
  }
818
864
  }
819
865
  return env;
@@ -918,7 +964,7 @@ class Installer {
918
964
  const proc = spawnProc('powershell', [
919
965
  '-NoProfile', '-Command',
920
966
  `Expand-Archive -Path '${zipPath}' -DestinationPath '${nodejsDir}' -Force`
921
- ], { stdio: ['ignore', 'pipe', 'pipe'] });
967
+ ], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
922
968
  if (proc.stdout) proc.stdout.on('data', (d) => { if (onData) onData(d.toString()); });
923
969
  if (proc.stderr) proc.stderr.on('data', (d) => { if (onData) onData(d.toString()); });
924
970
  proc.on('error', reject);
@@ -1039,6 +1085,54 @@ class Installer {
1039
1085
  });
1040
1086
  }
1041
1087
 
1088
+ /**
1089
+ * Locate a `node` binary plus its `npm-cli.js` so npm can be invoked as
1090
+ * `node npm-cli.js …` with argv passed array-style and NO shell. On Windows
1091
+ * that goes through CreateProcessW (UTF-16), so an install prefix under a
1092
+ * non-ASCII home dir (e.g. `C:\Users\用户名\.openagents\runtimes\…`) is
1093
+ * preserved exactly. The legacy `npm.cmd` shell shim instead has cmd.exe
1094
+ * decode the path bytes with the OEM code page (936/GBK on zh-CN), corrupting
1095
+ * it and silently breaking every install. Returns { node, npmCli } or null
1096
+ * when no usable layout is found (caller falls back to the legacy shell
1097
+ * command, which still works for ASCII paths).
1098
+ */
1099
+ _resolveNodeNpmCli() {
1100
+ const exists = (p) => { try { return fs.existsSync(p); } catch { return false; } };
1101
+ const isWin = process.platform === 'win32';
1102
+ const nodeName = isWin ? 'node.exe' : 'node';
1103
+
1104
+ const nodeCandidates = [];
1105
+ // Bundled portable node (~/.openagents/nodejs, plus nested node-* layouts)
1106
+ const bundledDir = path.join(this.configDir, 'nodejs');
1107
+ nodeCandidates.push(path.join(bundledDir, nodeName));
1108
+ nodeCandidates.push(path.join(bundledDir, 'bin', 'node'));
1109
+ try {
1110
+ for (const e of fs.readdirSync(bundledDir)) {
1111
+ if (e.startsWith('node-')) {
1112
+ nodeCandidates.push(path.join(bundledDir, e, nodeName));
1113
+ nodeCandidates.push(path.join(bundledDir, e, 'bin', 'node'));
1114
+ }
1115
+ }
1116
+ } catch {}
1117
+ // System node — its npm-cli.js lives next to (or one level above) it.
1118
+ try {
1119
+ const sys = whichBinary('node');
1120
+ if (sys) nodeCandidates.push(sys);
1121
+ } catch {}
1122
+
1123
+ for (const node of nodeCandidates) {
1124
+ if (!node || !exists(node)) continue;
1125
+ const dir = path.dirname(node);
1126
+ const npmCli = [
1127
+ path.join(dir, 'node_modules', 'npm', 'bin', 'npm-cli.js'),
1128
+ path.join(dir, 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
1129
+ path.join(dir, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
1130
+ ].find(exists);
1131
+ if (npmCli && this._canExecute(node)) return { node, npmCli };
1132
+ }
1133
+ return null;
1134
+ }
1135
+
1042
1136
  /**
1043
1137
  * Resolve the npm CLI command. Uses system npm if available.
1044
1138
  */
package/src/paths.js CHANGED
@@ -107,7 +107,13 @@ function getEnhancedEnv(baseEnv) {
107
107
  const env = { ...(baseEnv || process.env) };
108
108
  const extra = getExtraBinDirs();
109
109
  if (extra.length > 0) {
110
- env.PATH = extra.join(SEP) + SEP + (env.PATH || '');
110
+ // Spreading process.env on Windows yields a "Path" key (not "PATH"), so a
111
+ // bare `env.PATH = …` would create a SECOND key holding only the extra dirs
112
+ // — no System32 — and libuv picks that truncated one when resolving spawned
113
+ // executables (cmd.exe / where.exe become unfindable). Update the existing
114
+ // case-insensitive path key in place instead.
115
+ const pathKey = Object.keys(env).find((k) => k.toLowerCase() === 'path') || 'PATH';
116
+ env[pathKey] = extra.join(SEP) + SEP + (env[pathKey] || '');
111
117
  }
112
118
  if (IS_WINDOWS) {
113
119
  // Force UTF-8 output from child processes on non-English Windows locales
@@ -179,8 +185,16 @@ function _addWindowsPaths(dirs) {
179
185
  // Portable Node.js installed by OpenAgents Launcher
180
186
  _push(dirs, path.join(HOME, '.openagents', 'nodejs'));
181
187
 
182
- // Cursor CLI native installer
188
+ // Cursor CLI native installer.
189
+ // - ~/.cursor/bin : the curl|bash layout (also used by some setups)
190
+ // - %LOCALAPPDATA%\cursor-agent : where the Windows installer
191
+ // (irm 'https://cursor.com/install?win32=true' | iex) actually drops
192
+ // cursor-agent.cmd / agent.cmd. The installer edits the *registry* PATH,
193
+ // so an already-running launcher/daemon process never sees it via `where`
194
+ // unless we add the dir here explicitly.
183
195
  _push(dirs, path.join(HOME, '.cursor', 'bin'));
196
+ if (localAppData) _push(dirs, path.join(localAppData, 'cursor-agent'));
197
+ _push(dirs, path.join(HOME, '.local', 'bin'));
184
198
 
185
199
  // Node.js install
186
200
  _push(dirs, path.join(programFiles, 'nodejs'));
package/src/tui.js CHANGED
@@ -8,6 +8,7 @@
8
8
 
9
9
  const blessed = require('blessed');
10
10
  const { AgentConnector } = require('./index');
11
+ const { loadAgentRows, connectAvailable } = require('./agent-rows');
11
12
  const path = require('path');
12
13
  const fs = require('fs');
13
14
  const { spawn } = require('child_process');
@@ -64,49 +65,6 @@ function getConnector() {
64
65
  return new AgentConnector({ configDir });
65
66
  }
66
67
 
67
- function loadAgentRows(connector) {
68
- const config = connector.config.load();
69
- const agents = config.agents || [];
70
- const agentStatuses = connector.getDaemonStatus() || {};
71
- const pid = connector.getDaemonPid();
72
- const networks = config.networks || [];
73
- return agents.map(agent => {
74
- const info = agentStatuses[agent.name] || {};
75
- const state = pid ? (info.state || 'stopped') : 'stopped';
76
- let workspace = '';
77
- if (agent.network) {
78
- const net = networks.find(n => n.slug === agent.network || n.id === agent.network);
79
- if (net) {
80
- const slug = net.slug || net.id;
81
- const isLocal = (net.endpoint || '').includes('localhost') || (net.endpoint || '').includes('127.0.0.1');
82
- if (isLocal) workspace = `${net.endpoint}/${slug}`;
83
- else workspace = `workspace.openagents.org/${slug}`;
84
- } else {
85
- workspace = agent.network;
86
- }
87
- }
88
- let notReadyMsg = '';
89
- let health = null;
90
- try {
91
- health = connector.healthCheck(agent.type || 'openclaw');
92
- if (health && !health.ready) notReadyMsg = health.message || 'Not configured';
93
- } catch {}
94
-
95
- return {
96
- name: agent.name,
97
- type: agent.type || 'openclaw',
98
- state,
99
- workspace,
100
- path: agent.path || '',
101
- network: agent.network || '',
102
- lastError: info.last_error || '',
103
- notReadyMsg,
104
- health,
105
- configured: true,
106
- };
107
- });
108
- }
109
-
110
68
  function describeHealth(health) {
111
69
  if (!health) return '';
112
70
  if (!health.ready) return health.message || 'Not configured';
@@ -271,7 +229,7 @@ function createTUI() {
271
229
  const envFields = connector.registry.getEnvFields(agent.type);
272
230
  if (envFields && envFields.length > 0) items.push({ key: 'e', label: 'Configure' });
273
231
 
274
- if (!agent.workspace) items.push({ key: 'c', label: 'Connect' });
232
+ if (connectAvailable(agent)) items.push({ key: 'c', label: 'Connect' });
275
233
  if (agent.workspace) items.push({ key: 'd', label: 'Disconnect' });
276
234
  if (agent.workspace) items.push({ key: 'w', label: 'Workspace' });
277
235
 
@@ -322,7 +280,8 @@ function createTUI() {
322
280
  const items = [];
323
281
  for (const r of agentRows) {
324
282
  const state = stateMarkup(r.state, !!r.workspace);
325
- const ws = r.workspace || '';
283
+ // Local-only agents (no workspace) show a dimmed "(local)" marker.
284
+ const ws = r.workspace || `{gray-fg}${r.workspaceLabel}{/gray-fg}`;
326
285
  items.push(` ${r.name.padEnd(22)} ${r.type.padEnd(14)} ${state.padEnd(30)} ${ws}`);
327
286
  // Detail row: working dir + config warning
328
287
  const details = [];
@@ -418,7 +377,7 @@ function createTUI() {
418
377
  if (isStopped) actions.push({ label: 'Start', key: 'start' });
419
378
  if (isRunning) actions.push({ label: 'Stop', key: 'stop' });
420
379
  if (agent.workspace) actions.push({ label: 'Open Workspace', key: 'open_workspace' });
421
- if (!agent.workspace) actions.push({ label: 'Connect to Workspace', key: 'connect' });
380
+ if (connectAvailable(agent)) actions.push({ label: 'Connect to Workspace', key: 'connect' });
422
381
  if (agent.workspace) actions.push({ label: 'Disconnect from Workspace', key: 'disconnect' });
423
382
  actions.push({ label: 'Remove', key: 'remove' });
424
383
 
@@ -1403,7 +1362,7 @@ function createTUI() {
1403
1362
  Connect() {
1404
1363
  if (currentView !== 'main' || !selectedAgent()) return;
1405
1364
  const a = selectedAgent();
1406
- if (a.configured && !a.workspace) showConnectWorkspaceScreen(a.name);
1365
+ if (connectAvailable(a)) showConnectWorkspaceScreen(a.name);
1407
1366
  },
1408
1367
  Disconnect() {
1409
1368
  if (currentView !== 'main' || !selectedAgent()) return;
@@ -1492,4 +1451,4 @@ function createTUI() {
1492
1451
  }
1493
1452
 
1494
1453
  function run() { createTUI(); }
1495
- module.exports = { run };
1454
+ module.exports = { run, loadAgentRows, connectAvailable };
@@ -104,32 +104,75 @@ function detectInstallPrefix() {
104
104
  return null;
105
105
  }
106
106
 
107
- function findNpmBin() {
108
- const nodeDir = path.dirname(process.execPath);
109
- for (const name of ['npm', 'npm.cmd']) {
107
+ /**
108
+ * Locate the npm executable next to the running node binary, falling back to
109
+ * a PATH lookup. On Windows the runnable file is `npm.cmd`; the extensionless
110
+ * `npm` shipped alongside it is a Unix shell script that cmd.exe / PowerShell
111
+ * cannot execute, so it must be checked AFTER `npm.cmd`. The opts are injectable
112
+ * to keep this testable across platforms.
113
+ */
114
+ function findNpmBin(opts = {}) {
115
+ const platform = opts.platform || process.platform;
116
+ const nodeDir = opts.nodeDir || path.dirname(process.execPath);
117
+ const exists = opts.exists || fs.existsSync;
118
+ const names = platform === 'win32' ? ['npm.cmd', 'npm'] : ['npm'];
119
+ for (const name of names) {
110
120
  const candidate = path.join(nodeDir, name);
111
- if (fs.existsSync(candidate)) return candidate;
121
+ if (exists(candidate)) return candidate;
112
122
  }
113
- try {
114
- return execSync(process.platform === 'win32' ? 'where npm' : 'which npm', {
123
+ // PATH fallback (injectable so tests can exercise the hard fallback
124
+ // deterministically regardless of the host OS).
125
+ const lookup = opts.lookup || (() =>
126
+ execSync(platform === 'win32' ? 'where npm' : 'which npm', {
115
127
  encoding: 'utf-8', timeout: 3000,
116
- }).trim().split(/\r?\n/)[0];
117
- } catch { return 'npm'; }
128
+ }).trim().split(/\r?\n/)[0]);
129
+ try {
130
+ return lookup() || (platform === 'win32' ? 'npm.cmd' : 'npm');
131
+ } catch { return platform === 'win32' ? 'npm.cmd' : 'npm'; }
118
132
  }
119
133
 
120
134
  /**
121
135
  * Run npm install to update to the latest version. Blocking.
122
- * Returns true on success.
136
+ * Returns true on success. `opts` are injectable for testing.
123
137
  */
124
- function runUpdate() {
125
- const prefix = detectInstallPrefix();
126
- const npmBin = findNpmBin();
138
+ function runUpdate(opts = {}) {
139
+ const platform = opts.platform || process.platform;
140
+ const spawn = opts.spawn || spawnSync;
141
+ const npmBin = opts.npmBin || findNpmBin({ platform });
142
+ const prefix = opts.prefix !== undefined ? opts.prefix : detectInstallPrefix();
127
143
  const args = ['install', '--no-save', `${PKG_NAME}@latest`];
128
144
  if (prefix) args.push('--prefix', prefix);
129
145
  else args.push('-g');
146
+
147
+ // On Windows, npm.cmd is a batch file and must be invoked through cmd.exe.
148
+ // Passing the args via cmd.exe with shell:false lets Node quote paths that
149
+ // contain spaces (e.g. C:\Program Files\nodejs\npm.cmd) correctly.
150
+ let cmd, cmdArgs;
151
+ if (platform === 'win32') {
152
+ cmd = process.env.ComSpec || 'cmd.exe';
153
+ cmdArgs = ['/d', '/s', '/c', npmBin, ...args];
154
+ } else {
155
+ cmd = npmBin;
156
+ cmdArgs = args;
157
+ }
158
+
130
159
  process.stderr.write(`[launcher] Running: ${npmBin} ${args.join(' ')}\n`);
131
- const r = spawnSync(npmBin, args, { stdio: 'inherit' });
132
- return r.status === 0;
160
+ const r = spawn(cmd, cmdArgs, { stdio: 'inherit' });
161
+
162
+ // spawn failed to even start the process (ENOENT / EINVAL / EACCES ...).
163
+ if (r && r.error) {
164
+ process.stderr.write(`[launcher] Failed to run npm (${cmd}): ${r.error.message}\n`);
165
+ return false;
166
+ }
167
+ // npm started but exited non-zero. Its own stderr was already streamed via
168
+ // stdio:'inherit'; surface the exit code so the failure isn't silent.
169
+ if (!r || r.status !== 0) {
170
+ const code = r ? r.status : 'unknown';
171
+ const sig = r && r.signal ? ` (signal ${r.signal})` : '';
172
+ process.stderr.write(`[launcher] npm exited with code ${code}${sig}\n`);
173
+ return false;
174
+ }
175
+ return true;
133
176
  }
134
177
 
135
178
  /**
@@ -179,5 +222,6 @@ module.exports = {
179
222
  checkForUpdate,
180
223
  notifyAndMaybeUpdate,
181
224
  runUpdate,
225
+ findNpmBin,
182
226
  currentVersion,
183
227
  };