@phnx-labs/agents-cli 1.20.27 → 1.20.29

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.
Files changed (101) hide show
  1. package/CHANGELOG.md +3 -0
  2. package/dist/commands/doctor.js +57 -4
  3. package/dist/commands/exec.d.ts +1 -1
  4. package/dist/commands/exec.js +198 -15
  5. package/dist/commands/hosts.d.ts +11 -0
  6. package/dist/commands/hosts.js +229 -0
  7. package/dist/commands/repo.d.ts +29 -0
  8. package/dist/commands/repo.js +174 -38
  9. package/dist/commands/secrets.d.ts +2 -7
  10. package/dist/commands/secrets.js +108 -29
  11. package/dist/commands/sessions.d.ts +2 -0
  12. package/dist/commands/sessions.js +8 -24
  13. package/dist/commands/ssh.d.ts +14 -0
  14. package/dist/commands/ssh.js +263 -0
  15. package/dist/commands/sync.d.ts +2 -0
  16. package/dist/commands/sync.js +22 -5
  17. package/dist/commands/view.js +27 -11
  18. package/dist/index.js +3 -1
  19. package/dist/lib/agents.d.ts +1 -0
  20. package/dist/lib/agents.js +44 -4
  21. package/dist/lib/browser/drivers/ssh.d.ts +47 -2
  22. package/dist/lib/browser/drivers/ssh.js +113 -24
  23. package/dist/lib/browser/profiles.js +28 -1
  24. package/dist/lib/browser/runtime-state.js +28 -8
  25. package/dist/lib/browser/types.d.ts +10 -1
  26. package/dist/lib/cli-resources.js +10 -1
  27. package/dist/lib/devices/connect.d.ts +34 -0
  28. package/dist/lib/devices/connect.js +101 -0
  29. package/dist/lib/devices/registry.d.ts +78 -0
  30. package/dist/lib/devices/registry.js +168 -0
  31. package/dist/lib/devices/ssh-config.d.ts +21 -0
  32. package/dist/lib/devices/ssh-config.js +33 -0
  33. package/dist/lib/devices/tailscale.d.ts +31 -0
  34. package/dist/lib/devices/tailscale.js +126 -0
  35. package/dist/lib/doctor-diff.d.ts +12 -0
  36. package/dist/lib/doctor-diff.js +89 -2
  37. package/dist/lib/exec.d.ts +27 -0
  38. package/dist/lib/exec.js +62 -19
  39. package/dist/lib/hooks.d.ts +17 -0
  40. package/dist/lib/hooks.js +127 -3
  41. package/dist/lib/hosts/dispatch.d.ts +26 -0
  42. package/dist/lib/hosts/dispatch.js +71 -0
  43. package/dist/lib/hosts/progress.d.ts +21 -0
  44. package/dist/lib/hosts/progress.js +49 -0
  45. package/dist/lib/hosts/providers/local.d.ts +17 -0
  46. package/dist/lib/hosts/providers/local.js +81 -0
  47. package/dist/lib/hosts/ready.d.ts +37 -0
  48. package/dist/lib/hosts/ready.js +88 -0
  49. package/dist/lib/hosts/registry.d.ts +22 -0
  50. package/dist/lib/hosts/registry.js +65 -0
  51. package/dist/lib/hosts/ssh-config.d.ts +37 -0
  52. package/dist/lib/hosts/ssh-config.js +157 -0
  53. package/dist/lib/hosts/tasks.d.ts +32 -0
  54. package/dist/lib/hosts/tasks.js +58 -0
  55. package/dist/lib/hosts/types.d.ts +51 -0
  56. package/dist/lib/hosts/types.js +21 -0
  57. package/dist/lib/loop.d.ts +9 -0
  58. package/dist/lib/loop.js +13 -1
  59. package/dist/lib/mcp.js +12 -3
  60. package/dist/lib/menubar/MenubarHelper.app/Contents/MacOS/MenubarHelper +0 -0
  61. package/dist/lib/migrate.js +9 -5
  62. package/dist/lib/platform/exec.d.ts +10 -0
  63. package/dist/lib/platform/exec.js +17 -0
  64. package/dist/lib/platform/index.d.ts +1 -0
  65. package/dist/lib/platform/index.js +1 -0
  66. package/dist/lib/platform/links.d.ts +15 -0
  67. package/dist/lib/platform/links.js +42 -0
  68. package/dist/lib/platform/paths.d.ts +18 -0
  69. package/dist/lib/platform/paths.js +22 -0
  70. package/dist/lib/platform/posixpath.d.ts +28 -0
  71. package/dist/lib/platform/posixpath.js +153 -0
  72. package/dist/lib/plugins.d.ts +10 -0
  73. package/dist/lib/plugins.js +1 -1
  74. package/dist/lib/project-launch.js +6 -3
  75. package/dist/lib/sandbox.js +5 -2
  76. package/dist/lib/secrets/remote.d.ts +67 -0
  77. package/dist/lib/secrets/remote.js +133 -0
  78. package/dist/lib/self-update.js +7 -2
  79. package/dist/lib/session/db.d.ts +24 -0
  80. package/dist/lib/session/db.js +80 -5
  81. package/dist/lib/session/discover.d.ts +28 -0
  82. package/dist/lib/session/discover.js +303 -4
  83. package/dist/lib/session/parse.d.ts +7 -0
  84. package/dist/lib/session/parse.js +110 -0
  85. package/dist/lib/session/relative-time.d.ts +7 -0
  86. package/dist/lib/session/relative-time.js +28 -0
  87. package/dist/lib/session/remote.d.ts +31 -3
  88. package/dist/lib/session/remote.js +121 -14
  89. package/dist/lib/session/types.d.ts +1 -1
  90. package/dist/lib/session/types.js +1 -1
  91. package/dist/lib/ssh-exec.d.ts +45 -0
  92. package/dist/lib/ssh-exec.js +61 -0
  93. package/dist/lib/startup/command-registry.d.ts +2 -0
  94. package/dist/lib/startup/command-registry.js +5 -0
  95. package/dist/lib/state.d.ts +2 -0
  96. package/dist/lib/state.js +2 -0
  97. package/dist/lib/types.d.ts +21 -0
  98. package/dist/lib/versions.d.ts +6 -2
  99. package/dist/lib/versions.js +8 -4
  100. package/package.json +1 -1
  101. package/scripts/postinstall.js +62 -0
@@ -4,11 +4,10 @@ import { CDPClient, discoverBrowserWsUrl, verifyBrowserIdentity } from '../cdp.j
4
4
  import { getPortOccupant } from '../chrome.js';
5
5
  import { parseEndpointUrl } from '../profiles.js';
6
6
  import { writeProfileRuntime, clearProfileRuntime } from '../runtime-state.js';
7
- export function shellQuote(s) {
8
- if (/^[A-Za-z0-9_./:=@%+-]+$/.test(s))
9
- return s;
10
- return "'" + s.replace(/'/g, "'\\''") + "'";
11
- }
7
+ // shellQuote lives in the shared ssh-exec helper (single choke point); re-export
8
+ // so existing importers of `shellQuote` from this module keep working.
9
+ import { shellQuote } from '../../ssh-exec.js';
10
+ export { shellQuote };
12
11
  export async function connectSSH(endpoint, profile) {
13
12
  const url = new URL(endpoint);
14
13
  if (url.protocol !== 'ssh:') {
@@ -24,6 +23,11 @@ export async function connectSSH(endpoint, profile) {
24
23
  }
25
24
  const host = parsed.host;
26
25
  const remotePort = parsed.port;
26
+ // `&os=windows` switches the remote-command dialect (cmd.exe launch via
27
+ // `start`, taskkill teardown). Anything else — including absent — is posix.
28
+ // The query param is the single source of truth so the driver never has to
29
+ // be threaded a separate per-profile field.
30
+ const remoteOs = (url.searchParams.get('os') || '').toLowerCase() === 'windows' ? 'windows' : 'posix';
27
31
  // Bind the tunnel to the SAME local port the user configured. Using an
28
32
  // allocated port instead made `status` print confusing rows like
29
33
  // `port 9200 (configured 10005)` and made it impossible to predict which
@@ -40,7 +44,7 @@ export async function connectSSH(endpoint, profile) {
40
44
  `Either kill that process (\`kill ${occupant.pid}\`) or change the profile's port.`);
41
45
  }
42
46
  try {
43
- await ensureRemoteBrowser(user, host, profile.browser, remotePort, profile.binary);
47
+ await ensureRemoteBrowser(user, host, profile.browser, remotePort, remoteOs, profile.binary);
44
48
  }
45
49
  catch {
46
50
  // Browser may already be running, continue
@@ -156,28 +160,100 @@ function tryConnect(port) {
156
160
  socket.on('error', reject);
157
161
  });
158
162
  }
159
- async function ensureRemoteBrowser(user, host, browserType, port, customBinary) {
160
- const browserPaths = {
161
- chrome: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
162
- comet: '/Applications/Comet.app/Contents/MacOS/Comet',
163
- chromium: '/Applications/Chromium.app/Contents/MacOS/Chromium',
164
- brave: '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
165
- edge: '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
166
- };
167
- let browserPath;
163
+ // macOS .app launchers the historical POSIX table.
164
+ const POSIX_BROWSER_PATHS = {
165
+ chrome: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
166
+ comet: '/Applications/Comet.app/Contents/MacOS/Comet',
167
+ chromium: '/Applications/Chromium.app/Contents/MacOS/Chromium',
168
+ brave: '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
169
+ edge: '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
170
+ };
171
+ // Windows App Paths registry keys per browser. CreateProcess (used by WMI
172
+ // Win32_Process.Create) does not honor App Paths the way ShellExecute/`start`
173
+ // does, so the launch script resolves the real `.exe` path from this registry
174
+ // key at runtime — covering both Program Files and Program Files (x86)
175
+ // installs without hardcoding (or guessing) the location.
176
+ const WIN_BROWSER_APPPATH = {
177
+ chrome: 'chrome.exe',
178
+ chromium: 'chrome.exe',
179
+ brave: 'brave.exe',
180
+ edge: 'msedge.exe',
181
+ };
182
+ /** Single-quote a string for embedding inside a PowerShell literal. */
183
+ function psSingleQuote(s) {
184
+ return "'" + s.replace(/'/g, "''") + "'";
185
+ }
186
+ /**
187
+ * Wrap a PowerShell script as a `-EncodedCommand` invocation. Base64 of the
188
+ * UTF-16LE bytes is a single quote-free token, so it rides through Node spawn
189
+ * → Windows sshd → cmd.exe with zero escaping hazards (hand-quoted
190
+ * `powershell -Command "…"` is fragile the moment a path or URL is involved).
191
+ */
192
+ export function encodePowerShell(script) {
193
+ const b64 = Buffer.from(script, 'utf16le').toString('base64');
194
+ return `powershell -NoProfile -EncodedCommand ${b64}`;
195
+ }
196
+ /**
197
+ * The PowerShell that launches the browser on a Windows remote. Two hard
198
+ * requirements shaped this:
199
+ * 1. The browser must OUTLIVE the ssh session. Windows OpenSSH terminates
200
+ * the session's job tree on disconnect, which reaps both `start /B` and
201
+ * `Start-Process` children (verified against a real box). WMI
202
+ * `Win32_Process.Create` spawns under the WMI provider service instead,
203
+ * so the process survives after we drop the ssh connection and reconnect
204
+ * over the CDP tunnel.
205
+ * 2. A distinct `--user-data-dir` so a fresh instance bound to the debugging
206
+ * port comes up even when the user already has Edge open.
207
+ * CreateProcess ignores App Paths, so we resolve the real `.exe` from the
208
+ * registry at runtime rather than relying on a bare `msedge` name.
209
+ */
210
+ export function buildWindowsLaunchScript(browserType, port, customBinary) {
211
+ let exeExpr;
168
212
  if (customBinary) {
169
- browserPath = customBinary;
213
+ exeExpr = psSingleQuote(customBinary);
170
214
  }
171
215
  else if (browserType === 'custom') {
172
216
  throw new Error('browser: custom requires a binary path in the profile');
173
217
  }
174
218
  else {
175
- browserPath = browserPaths[browserType];
176
- if (!browserPath) {
177
- throw new Error(`Unknown browser type: ${browserType}`);
219
+ const exeKey = WIN_BROWSER_APPPATH[browserType];
220
+ if (!exeKey)
221
+ throw new Error(`Unknown browser type for windows remote: ${browserType}`);
222
+ exeExpr =
223
+ `(Get-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\${exeKey}').'(default)'`;
224
+ }
225
+ // Keep the `--remote-allow-origins=http://127.0.0.1:${port}` literal in
226
+ // source — a test asserts CDP is never opened to `*`.
227
+ return [
228
+ `$exe = ${exeExpr}`,
229
+ `$cl = '"' + $exe + '" --remote-debugging-port=${port}` +
230
+ ` --remote-allow-origins=http://127.0.0.1:${port}` +
231
+ ` --disable-background-timer-throttling --user-data-dir="' + $env:TEMP + '\\agents-browser-${port}"'`,
232
+ `Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = $cl } | Out-Null`,
233
+ ].join('; ');
234
+ }
235
+ /** The PowerShell that kills whatever holds the CDP port on a Windows remote. */
236
+ export function buildWindowsKillScript(port) {
237
+ return (`Get-NetTCPConnection -LocalPort ${port} -State Listen -ErrorAction SilentlyContinue ` +
238
+ `| ForEach-Object { Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue }`);
239
+ }
240
+ /**
241
+ * Build the remote command that launches the browser detached with a CDP port.
242
+ * POSIX backgrounds the `.app` binary with `… &`; Windows resolves the exe and
243
+ * spawns it via WMI (encoded PowerShell) so it survives the ssh session.
244
+ */
245
+ export function buildLaunchCmd(remoteOs, browserType, port, customBinary) {
246
+ if (remoteOs === 'windows') {
247
+ return encodePowerShell(buildWindowsLaunchScript(browserType, port, customBinary));
248
+ }
249
+ const browserPath = customBinary ?? POSIX_BROWSER_PATHS[browserType];
250
+ if (!browserPath) {
251
+ if (browserType === 'custom') {
252
+ throw new Error('browser: custom requires a binary path in the profile');
178
253
  }
254
+ throw new Error(`Unknown browser type for posix remote: ${browserType}`);
179
255
  }
180
- const remoteCmd = [
256
+ return [
181
257
  shellQuote(browserPath),
182
258
  `--remote-debugging-port=${port}`,
183
259
  shellQuote(`--remote-allow-origins=http://127.0.0.1:${port}`),
@@ -185,6 +261,20 @@ async function ensureRemoteBrowser(user, host, browserType, port, customBinary)
185
261
  `--user-data-dir=/tmp/agents-browser-${port}`,
186
262
  '</dev/null >/dev/null 2>&1 &',
187
263
  ].join(' ');
264
+ }
265
+ /**
266
+ * Build the remote command that kills whatever holds the CDP port.
267
+ * POSIX uses `lsof`+`kill`; Windows uses encoded PowerShell
268
+ * (Get-NetTCPConnection → Stop-Process).
269
+ */
270
+ export function buildKillCmd(remoteOs, port) {
271
+ if (remoteOs === 'windows') {
272
+ return encodePowerShell(buildWindowsKillScript(port));
273
+ }
274
+ return `pids=$(lsof -ti ${shellQuote(`:${port}`)} 2>/dev/null); [ -z "$pids" ] || kill -9 $pids 2>/dev/null || true`;
275
+ }
276
+ async function ensureRemoteBrowser(user, host, browserType, port, remoteOs, customBinary) {
277
+ const remoteCmd = buildLaunchCmd(remoteOs, browserType, port, customBinary);
188
278
  return new Promise((resolve, reject) => {
189
279
  const child = spawn('ssh', [
190
280
  `${user}@${host}`,
@@ -200,12 +290,11 @@ async function ensureRemoteBrowser(user, host, browserType, port, customBinary)
200
290
  }, 2000);
201
291
  });
202
292
  }
203
- export async function restartRemoteBrowser(user, host, browserType, port, customBinary) {
293
+ export async function restartRemoteBrowser(user, host, browserType, port, remoteOs, customBinary) {
204
294
  // Kill any process using the remote debugging port
205
- const killCmd = `pids=$(lsof -ti ${shellQuote(`:${port}`)} 2>/dev/null); [ -z "$pids" ] || kill -9 $pids 2>/dev/null || true`;
206
- await runSSHCommand(user, host, killCmd);
295
+ await runSSHCommand(user, host, buildKillCmd(remoteOs, port));
207
296
  await sleep(500);
208
- await ensureRemoteBrowser(user, host, browserType, port, customBinary);
297
+ await ensureRemoteBrowser(user, host, browserType, port, remoteOs, customBinary);
209
298
  await sleep(1500);
210
299
  }
211
300
  function runSSHCommand(user, host, cmd) {
@@ -194,6 +194,27 @@ function hasSshEndpoint(endpoints) {
194
194
  }
195
195
  });
196
196
  }
197
+ /**
198
+ * True when any endpoint is an `ssh://…?os=windows` target — i.e. the browser
199
+ * lives on a remote Windows host. Such a profile's binary (`msedge.exe`) will
200
+ * never exist on this Mac, so create-time local-binary validation must be
201
+ * skipped; the binary is resolved on the remote at connect time instead.
202
+ */
203
+ function hasRemoteWindowsEndpoint(endpoints) {
204
+ const targets = Array.isArray(endpoints)
205
+ ? endpoints
206
+ : Object.values(endpoints).map((preset) => preset.target);
207
+ return targets.some((target) => {
208
+ try {
209
+ const url = new URL(target);
210
+ return (url.protocol === 'ssh:' &&
211
+ (url.searchParams.get('os') || '').toLowerCase() === 'windows');
212
+ }
213
+ catch {
214
+ return false;
215
+ }
216
+ });
217
+ }
197
218
  export async function createProfile(profile) {
198
219
  const meta = readMeta();
199
220
  if (meta.browser?.[profile.name]) {
@@ -220,7 +241,13 @@ export async function createProfile(profile) {
220
241
  // error ("Comet not installed at /Applications/Comet.app") rather than
221
242
  // deferring the failure to the first task. `findBrowserPath` short-circuits
222
243
  // for browser=custom without a binary by throwing — same outcome.
223
- findBrowserPath(profile.browser, profile.binary);
244
+ //
245
+ // Skip for remote-Windows profiles: the browser is `msedge.exe` on the
246
+ // remote box, never on this Mac, so a local lookup would always (wrongly)
247
+ // fail. The remote launcher resolves it at connect time via App Paths.
248
+ if (!hasRemoteWindowsEndpoint(profile.endpoints)) {
249
+ findBrowserPath(profile.browser, profile.binary);
250
+ }
224
251
  meta.browser = meta.browser ?? {};
225
252
  meta.browser[profile.name] = profileToConfig(profile);
226
253
  writeMeta(meta);
@@ -248,20 +248,40 @@ export function reapOrphanedProcesses() {
248
248
  return { reaped, details };
249
249
  }
250
250
  function matchesCommand(pid, expectedCommand) {
251
+ const out = liveProcessCommand(pid);
252
+ if (!out)
253
+ return false;
254
+ // Match on the basename only — `/Applications/Comet.app/Contents/MacOS/Comet`
255
+ // vs the recorded `Comet`, vs `Google\ Chrome`, vs Windows `chrome.exe`.
256
+ // Case-insensitive.
257
+ const live = path.basename(out).toLowerCase();
258
+ const want = path.basename(expectedCommand).toLowerCase();
259
+ return live === want || live.startsWith(want) || want.startsWith(live);
260
+ }
261
+ /**
262
+ * The executable/image name the live `pid` is running, or null if it can't be
263
+ * determined. The process-listing API differs per OS: Windows has no `ps`, so
264
+ * we query `tasklist` (CSV image name in column 1); POSIX uses `ps -o comm=`.
265
+ */
266
+ function liveProcessCommand(pid) {
251
267
  try {
268
+ if (process.platform === 'win32') {
269
+ const out = execFileSync('tasklist', ['/FI', `PID eq ${pid}`, '/NH', '/FO', 'CSV'], {
270
+ encoding: 'utf-8',
271
+ stdio: ['ignore', 'pipe', 'ignore'],
272
+ }).trim();
273
+ // Rows look like: "node.exe","1234","Console","1","12,345 K"
274
+ // A no-match prints an "INFO: No tasks..." line that won't match the regex.
275
+ const m = out.match(/^"([^"]+)"/);
276
+ return m ? m[1] : null;
277
+ }
252
278
  const out = execFileSync('ps', ['-p', String(pid), '-o', 'comm='], {
253
279
  encoding: 'utf-8',
254
280
  stdio: ['ignore', 'pipe', 'ignore'],
255
281
  }).trim();
256
- if (!out)
257
- return false;
258
- // Match on the basename only — `/Applications/Comet.app/Contents/MacOS/Comet`
259
- // vs the recorded `Comet`, vs `Google\ Chrome`. Case-insensitive.
260
- const live = path.basename(out).toLowerCase();
261
- const want = path.basename(expectedCommand).toLowerCase();
262
- return live === want || live.startsWith(want) || want.startsWith(live);
282
+ return out || null;
263
283
  }
264
284
  catch {
265
- return false;
285
+ return null;
266
286
  }
267
287
  }
@@ -7,7 +7,16 @@ export type BrowserType = 'chrome' | 'comet' | 'chromium' | 'brave' | 'edge' | '
7
7
  * Per-endpoint overrides take precedence over profile-level fields.
8
8
  */
9
9
  export interface EndpointPreset {
10
- /** CDP URL — `cdp://host:port` or `ssh://host?port=N` */
10
+ /**
11
+ * CDP URL — `cdp://host:port` or `ssh://host?port=N`.
12
+ *
13
+ * For an SSH target whose remote is Windows, append `&os=windows` (e.g.
14
+ * `ssh://user@host?port=9222&os=windows`). The driver then speaks the
15
+ * Windows dialect (launch via WMI Win32_Process.Create so the browser
16
+ * survives the ssh session, teardown via Get-NetTCPConnection/Stop-Process)
17
+ * instead of the POSIX default. The query param is the single source of
18
+ * truth for remote-OS selection.
19
+ */
11
20
  target: string;
12
21
  /** Override the profile-level binary (e.g. a remote host has no local binary). */
13
22
  binary?: string;
@@ -116,7 +116,16 @@ export function parseCheckSpec(raw, defaultName) {
116
116
  * decide whether to surface or swallow the error per file.
117
117
  */
118
118
  export function parseCliManifest(contents, opts) {
119
- const raw = yaml.parse(contents);
119
+ // Tolerant parse. A manifest may legitimately carry OS-specific strings — a
120
+ // Windows path like `C:\Users\...` embedded in a double-quoted YAML scalar
121
+ // trips YAML's escape rules (`\U` is an invalid escape) and makes the strict
122
+ // `yaml.parse` throw a parser error. That throw must NOT pre-empt the
123
+ // security validation below: the per-field allowlist checks (unsafe tokens,
124
+ // non-https URLs, path traversal) are the authoritative gate on a hostile
125
+ // manifest. parseDocument collects those escape errors instead of throwing
126
+ // and still recovers the scalar values, so the dangerous content reaches
127
+ // assertSafeCheckToken / assertNpmPackage and is rejected on its merits.
128
+ const raw = yaml.parseDocument(contents, { strict: false }).toJS();
120
129
  if (!raw || typeof raw !== 'object') {
121
130
  throw new Error('manifest must be a YAML object');
122
131
  }
@@ -0,0 +1,34 @@
1
+ import { type DeviceProfile } from './registry.js';
2
+ /** Env var the askpass shim reads to know which bundle holds the password. */
3
+ export declare const ASKPASS_BUNDLE_ENV = "AGENTS_SSH_BUNDLE";
4
+ /** Env var the askpass shim reads to know which key in the bundle is the password. */
5
+ export declare const ASKPASS_KEY_ENV = "AGENTS_SSH_KEY";
6
+ /**
7
+ * Build the `user@host` (or bare `host`) ssh target for a device and validate
8
+ * it against the shared injection guard. Throws if the device has no address.
9
+ */
10
+ export declare function sshTargetFor(device: DeviceProfile): string;
11
+ /**
12
+ * Wrap a remote command for the device's shell. Windows devices speak
13
+ * PowerShell, so a bare command is run through `powershell -NoProfile
14
+ * -Command`; POSIX devices get the command verbatim (the remote login shell
15
+ * parses it). Returns undefined when no command was given (interactive login).
16
+ */
17
+ export declare function wrapRemoteCommand(device: DeviceProfile, cmd: string[]): string | undefined;
18
+ /**
19
+ * Build the argv (after the `ssh` program name) and the environment overlay
20
+ * for connecting to a device. For password auth this points `SSH_ASKPASS` at
21
+ * the shim and disables pubkey + the host's interactive password prompt so the
22
+ * shim is the only auth path. Pure (no spawn) so it is unit-testable.
23
+ */
24
+ export declare function buildSshInvocation(device: DeviceProfile, cmd: string[], askpassShimPath: string): {
25
+ args: string[];
26
+ env: Record<string, string>;
27
+ };
28
+ /**
29
+ * Write (idempotently) the askpass shim — a tiny executable that re-invokes
30
+ * this CLI as `agents ssh __askpass`. ssh execs `SSH_ASKPASS` with no usable
31
+ * args, so the shim carries no secret itself; it only bridges ssh's askpass
32
+ * protocol back into the CLI, which then resolves the bundle.
33
+ */
34
+ export declare function writeAskpassShim(): string;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Connection layer for `agents ssh` — turn a device profile into a real ssh
3
+ * invocation, with platform-aware command wrapping and password-from-bundle
4
+ * auth.
5
+ *
6
+ * Auth is genuinely two first-class, non-interactive methods:
7
+ * - `key` — the system ssh agent / on-disk keys (BatchMode-friendly).
8
+ * - `password` — the secret is pulled from a Keychain-backed secrets bundle
9
+ * by an askpass shim. The wrapper points `SSH_ASKPASS` at the
10
+ * shim and forces its use; ssh calls the shim, the shim calls
11
+ * back into `agents ssh __askpass`, which resolves the bundle
12
+ * via the existing `readAndResolveBundleEnv` path and prints
13
+ * the password to ssh. The password never touches argv or an
14
+ * expect buffer.
15
+ */
16
+ import * as fs from 'fs';
17
+ import * as path from 'path';
18
+ import { assertValidSshTarget, shellQuote } from '../ssh-exec.js';
19
+ import { getCacheDir } from '../state.js';
20
+ import { hostNameFor } from './ssh-config.js';
21
+ /** Env var the askpass shim reads to know which bundle holds the password. */
22
+ export const ASKPASS_BUNDLE_ENV = 'AGENTS_SSH_BUNDLE';
23
+ /** Env var the askpass shim reads to know which key in the bundle is the password. */
24
+ export const ASKPASS_KEY_ENV = 'AGENTS_SSH_KEY';
25
+ /**
26
+ * Build the `user@host` (or bare `host`) ssh target for a device and validate
27
+ * it against the shared injection guard. Throws if the device has no address.
28
+ */
29
+ export function sshTargetFor(device) {
30
+ const host = hostNameFor(device);
31
+ if (!host) {
32
+ throw new Error(`Device '${device.name}' has no address (dnsName/ip). Run \`agents devices sync\` or \`agents devices add\`.`);
33
+ }
34
+ const target = device.user ? `${device.user}@${host}` : host;
35
+ assertValidSshTarget(target);
36
+ return target;
37
+ }
38
+ /**
39
+ * Wrap a remote command for the device's shell. Windows devices speak
40
+ * PowerShell, so a bare command is run through `powershell -NoProfile
41
+ * -Command`; POSIX devices get the command verbatim (the remote login shell
42
+ * parses it). Returns undefined when no command was given (interactive login).
43
+ */
44
+ export function wrapRemoteCommand(device, cmd) {
45
+ if (cmd.length === 0)
46
+ return undefined;
47
+ const joined = cmd.join(' ');
48
+ if (device.shell === 'powershell') {
49
+ return `powershell -NoProfile -Command ${shellQuote(joined)}`;
50
+ }
51
+ return joined;
52
+ }
53
+ /**
54
+ * Build the argv (after the `ssh` program name) and the environment overlay
55
+ * for connecting to a device. For password auth this points `SSH_ASKPASS` at
56
+ * the shim and disables pubkey + the host's interactive password prompt so the
57
+ * shim is the only auth path. Pure (no spawn) so it is unit-testable.
58
+ */
59
+ export function buildSshInvocation(device, cmd, askpassShimPath) {
60
+ const target = sshTargetFor(device);
61
+ const remote = wrapRemoteCommand(device, cmd);
62
+ const env = {};
63
+ const args = ['-o', 'StrictHostKeyChecking=accept-new', '-o', 'ConnectTimeout=10'];
64
+ if (device.auth.method === 'password') {
65
+ if (!device.auth.bundle) {
66
+ throw new Error(`Device '${device.name}' uses password auth but has no secrets bundle. Set one with \`agents devices set ${device.name} --bundle <name>\`.`);
67
+ }
68
+ env.SSH_ASKPASS = askpassShimPath;
69
+ env.SSH_ASKPASS_REQUIRE = 'force';
70
+ env[ASKPASS_BUNDLE_ENV] = device.auth.bundle;
71
+ env[ASKPASS_KEY_ENV] = device.auth.bundleKey ?? 'password';
72
+ args.push('-o', 'PreferredAuthentications=password', '-o', 'PubkeyAuthentication=no', '-o', 'NumberOfPasswordPrompts=1');
73
+ }
74
+ else {
75
+ args.push('-o', 'BatchMode=yes');
76
+ }
77
+ // An interactive login (no remote command) needs a real tty.
78
+ if (!remote)
79
+ args.push('-tt');
80
+ args.push(target);
81
+ if (remote)
82
+ args.push(remote);
83
+ return { args, env };
84
+ }
85
+ /**
86
+ * Write (idempotently) the askpass shim — a tiny executable that re-invokes
87
+ * this CLI as `agents ssh __askpass`. ssh execs `SSH_ASKPASS` with no usable
88
+ * args, so the shim carries no secret itself; it only bridges ssh's askpass
89
+ * protocol back into the CLI, which then resolves the bundle.
90
+ */
91
+ export function writeAskpassShim() {
92
+ const dir = path.join(getCacheDir(), 'devices');
93
+ fs.mkdirSync(dir, { recursive: true });
94
+ const shimPath = path.join(dir, 'askpass.sh');
95
+ // process.execPath = the node/bun binary; argv[1] = this CLI's entry script.
96
+ const node = process.execPath;
97
+ const entry = process.argv[1] ?? '';
98
+ const body = `#!/bin/sh\n# Generated by agents-cli — bridges ssh SSH_ASKPASS back into the CLI.\nexec ${shellQuote(node)} ${shellQuote(entry)} ssh __askpass\n`;
99
+ fs.writeFileSync(shimPath, body, { mode: 0o700 });
100
+ return shimPath;
101
+ }
@@ -0,0 +1,78 @@
1
+ /** Operating-system family of a device, used to pick the remote shell. */
2
+ export type DevicePlatform = 'windows' | 'linux' | 'macos' | 'unknown';
3
+ /** Remote shell dialect derived from the platform. */
4
+ export type DeviceShell = 'powershell' | 'posix';
5
+ /** How `agents ssh` authenticates to a device. Both are first-class, fully
6
+ * non-interactive: `key` uses the ssh agent / on-disk keys, `password` pulls
7
+ * the secret from a Keychain-backed secrets bundle via an askpass shim. */
8
+ export type DeviceAuthMethod = 'key' | 'password';
9
+ /** How to reach a device on the network. */
10
+ export interface DeviceAddress {
11
+ /** Where the address came from: a Tailscale node, or a manual entry. */
12
+ via: 'tailscale' | 'manual';
13
+ /** Fully-qualified DNS name (Tailscale MagicDNS), without a trailing dot. */
14
+ dnsName?: string;
15
+ /** Raw IP address (IPv4 preferred). */
16
+ ip?: string;
17
+ }
18
+ /** Authentication settings for a device. */
19
+ export interface DeviceAuth {
20
+ method: DeviceAuthMethod;
21
+ /** Secrets bundle holding the password (when method === 'password'). */
22
+ bundle?: string;
23
+ /** Key within the bundle whose value is the password. Defaults to 'password'. */
24
+ bundleKey?: string;
25
+ }
26
+ /** Last-known Tailscale reachability snapshot for a device. */
27
+ export interface DeviceTailscale {
28
+ online: boolean;
29
+ /** True when the last handshake was a direct (non-relayed) connection. */
30
+ direct: boolean;
31
+ /** DERP relay region code (e.g. 'sfo'); empty when direct. */
32
+ relay?: string;
33
+ lastSeen?: string;
34
+ }
35
+ /** A single registered device. */
36
+ export interface DeviceProfile {
37
+ name: string;
38
+ platform: DevicePlatform;
39
+ shell: DeviceShell;
40
+ user?: string;
41
+ address: DeviceAddress;
42
+ auth: DeviceAuth;
43
+ tailscale?: DeviceTailscale;
44
+ createdAt: string;
45
+ updatedAt: string;
46
+ }
47
+ /** Map of device name to profile. */
48
+ export type DeviceRegistry = Record<string, DeviceProfile>;
49
+ /** Throw if `name` is not usable as an ssh alias (no spaces, quotes, etc.). */
50
+ export declare function assertValidDeviceName(name: string): void;
51
+ /** Map a Tailscale `OS` field to our platform enum. */
52
+ export declare function platformFromOs(os: string | undefined): DevicePlatform;
53
+ /** The remote shell a platform speaks. */
54
+ export declare function shellForPlatform(platform: DevicePlatform): DeviceShell;
55
+ /**
56
+ * Load all devices from the registry file. Returns an empty object only when
57
+ * the file does not exist. A malformed file is a hard error — silently
58
+ * returning {} would let the next write wipe the user's device list.
59
+ */
60
+ export declare function loadDevices(): Promise<DeviceRegistry>;
61
+ /** Get a single device profile, or null if it is not registered. */
62
+ export declare function getDevice(name: string): Promise<DeviceProfile | null>;
63
+ /** Fields a caller may supply when creating or updating a device. */
64
+ export interface DeviceInput {
65
+ platform?: DevicePlatform;
66
+ user?: string;
67
+ address?: DeviceAddress;
68
+ auth?: DeviceAuth;
69
+ tailscale?: DeviceTailscale;
70
+ }
71
+ /**
72
+ * Create the device if absent, otherwise merge the supplied fields into the
73
+ * existing profile. `shell` is always re-derived from the (possibly new)
74
+ * platform so the two can never drift. Returns the resulting profile.
75
+ */
76
+ export declare function upsertDevice(name: string, input: DeviceInput): Promise<DeviceProfile>;
77
+ /** Remove a device. Returns false if it was not registered. */
78
+ export declare function removeDevice(name: string): Promise<boolean>;