session-peer 0.2.0 → 0.3.0

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/dist/cli.js CHANGED
@@ -9,11 +9,35 @@ import { executable, run, UnknownOutcome } from './process.js';
9
9
  import { checkMessage, send, CodexUnknownOutcome } from './send.js';
10
10
  import { HomeRefusal } from './writer.js';
11
11
  import { envelope, host, reply, VERSION, VERSION_LINE } from './protocol.js';
12
+ import { CHANNELS, checkUpdate, noticeText, refreshCache, refuseSelfUpdate, REFRESH_ARG, updateNotice, UpdateRefusal } from './updates.js';
13
+ import { jumpOptions, sshConfig, sshJump, sshOptions } from './ssh.js';
14
+ import { configuredHost, detectedHost, isSelf, probeReturnRoute, unsafeReturnHost, replyUri, returnHost, route, sender, tailnet } from './replies.js';
15
+ const FLAGS = ['--json', '--all', '--dry-run', '--no-from', '--no-reply-to', '--no-update-notice', '--allow-inactive-codex-home', '--check-return-route', '--check'];
16
+ const VALUES = ['--agent', '--codex-home', '--codex-bin', '--output-format', '--to', '--message', '-m', '--host', '--remote-bin', '--remote-platform', '--ssh-control-path', '--reply-address', '--ssh-opt', '--ssh-jump', '--reply-to', '--return-route-host', '--channel'];
17
+ // Repeated in order; every other value option is single.
18
+ const REPEATED = ['--host', '--ssh-opt'];
19
+ // Requested destinations, so a command-wide refusal can be attributed to each.
20
+ let requested = [];
12
21
  export function parse(args) {
13
22
  const command = args[0];
14
- if (command !== 'list' && command !== 'send' && command !== 'doctor')
23
+ if (command !== 'list' && command !== 'send' && command !== 'doctor' && command !== 'update')
15
24
  throw new Refusal('unsupported_command');
16
- const values = new Map(), flags = new Set();
25
+ // Collect requested hosts before any other validation, so that even a syntax
26
+ // refusal with several --host values is attributed to each of them. Value
27
+ // options consume their next token, as in the loop below; `--` ends options.
28
+ requested = [];
29
+ for (let i = 1; i < args.length && args[i] !== '--'; i++) {
30
+ const token = args[i], key = token.split('=')[0];
31
+ if (key === '--host') {
32
+ const value = token.includes('=') ? token.slice(7) : args[++i];
33
+ if (value !== undefined)
34
+ requested.push(value);
35
+ }
36
+ else if (VALUES.includes(key) && !token.includes('='))
37
+ i++;
38
+ }
39
+ let address;
40
+ const values = new Map(), flags = new Set(), repeated = new Map(REPEATED.map(k => [k, []]));
17
41
  let positional;
18
42
  let terminated = false;
19
43
  for (let i = 1; i < args.length; i++) {
@@ -30,21 +54,28 @@ export function parse(args) {
30
54
  }
31
55
  const split = token.indexOf('=');
32
56
  const key = split > 0 ? token.slice(0, split) : token;
33
- if (['--json', '--all', '--dry-run', '--no-from', '--no-reply-to', '--no-update-notice', '--allow-inactive-codex-home'].includes(key)) {
57
+ if (FLAGS.includes(key)) {
34
58
  if (flags.has(key) || split > 0)
35
59
  throw new Refusal('invalid_option');
36
60
  flags.add(key);
37
61
  }
38
- else if (['--agent', '--codex-home', '--codex-bin', '--output-format', '--to', '--message', '-m', '--host', '--remote-bin', '--remote-platform', '--ssh-control-path', '--reply-address'].includes(key)) {
62
+ else if (VALUES.includes(key)) {
39
63
  const name = key === '-m' ? '--message' : key;
40
64
  const value = split > 0 ? token.slice(split + 1) : args[++i];
41
- if (value === undefined || values.has(name))
65
+ // A separate value that is itself an option name is a missing value, as in
66
+ // argparse; `--message=--dry-run` or stdin still send such text literally.
67
+ const option = split > 0 ? '' : (value ?? '').split('=')[0];
68
+ if (value === undefined || values.has(name) || [...FLAGS, ...VALUES, '--help', '-h', '--version', '--stdio-request'].includes(option))
42
69
  throw new Refusal('invalid_option');
43
- values.set(name, value);
70
+ if (REPEATED.includes(name))
71
+ repeated.get(name).push(value);
72
+ else
73
+ values.set(name, value);
44
74
  }
45
75
  else
46
76
  throw new Refusal('unsupported_option');
47
77
  }
78
+ let hosts = repeated.get('--host');
48
79
  if (positional !== undefined) {
49
80
  if (values.has('--message'))
50
81
  throw new Refusal('conflicting_message_sources');
@@ -56,6 +87,18 @@ export function parse(args) {
56
87
  throw new Refusal('conflicting_output_options');
57
88
  if (!flags.has('--json') && !values.has('--output-format'))
58
89
  throw new Refusal('json_output_required');
90
+ if (command === 'update') {
91
+ if (values.has('--channel') && !CHANNELS.includes(values.get('--channel')))
92
+ throw new Refusal('unsupported_update_channel');
93
+ // Local client only: remote hosts and other installations update through their own managers.
94
+ if ([...values.keys()].some(k => !['--output-format', '--channel'].includes(k)) || [...flags].some(k => !['--json', '--check', '--no-update-notice'].includes(k)))
95
+ throw new Refusal('inapplicable_option');
96
+ if (hosts.length || repeated.get('--ssh-opt').length)
97
+ throw new Refusal('inapplicable_option');
98
+ return { command, values, flags, hosts: [], ssh: { args: [] } };
99
+ }
100
+ if (flags.has('--check') || values.has('--channel'))
101
+ throw new Refusal('inapplicable_option');
59
102
  if (command === 'list' || command === 'doctor') {
60
103
  if (values.has('--agent') && !['claude', 'codex'].includes(values.get('--agent')))
61
104
  throw new Refusal('unsupported_agent');
@@ -63,24 +106,39 @@ export function parse(args) {
63
106
  throw new Refusal('invalid_codex_home');
64
107
  if (values.get('--agent') === 'claude' && values.has('--codex-home'))
65
108
  throw new Refusal('inapplicable_option');
66
- if (['--to', '--message', '--reply-address', ...(command === 'list' ? ['--codex-bin'] : [])].some(k => values.has(k)) || ['--dry-run', '--no-from', '--no-reply-to', '--allow-inactive-codex-home'].some(k => flags.has(k)))
109
+ if (['--to', '--message', '--reply-address', ...(command === 'list' ? ['--codex-bin', '--reply-to', '--return-route-host'] : [])].some(k => values.has(k)) || ['--dry-run', '--no-from', '--no-reply-to', '--allow-inactive-codex-home', ...(command === 'list' ? ['--check-return-route'] : [])].some(k => flags.has(k)))
67
110
  throw new Refusal('inapplicable_option');
68
111
  if (command === 'doctor' && (flags.has('--all') || (values.get('--agent') === 'claude' && values.has('--codex-bin'))))
69
112
  throw new Refusal('inapplicable_option');
113
+ // --reply-to names the return host to probe; the probe itself is opt-in.
114
+ if (command === 'doctor' && ((values.has('--reply-to') && !flags.has('--check-return-route')) || (values.has('--return-route-host') && flags.has('--check-return-route'))))
115
+ throw new Refusal('inapplicable_option');
116
+ for (const key of ['--reply-to', '--return-route-host'])
117
+ if (values.has(key))
118
+ returnHost(values.get(key));
70
119
  }
71
120
  else {
72
121
  if (!values.get('--to') || values.has('--agent') || flags.has('--all'))
73
122
  throw new Refusal('invalid_send_options');
74
- if (flags.has('--no-reply-to') && values.has('--reply-address'))
123
+ if (flags.has('--check-return-route') || values.has('--return-route-host'))
124
+ throw new Refusal('inapplicable_option');
125
+ if ([flags.has('--no-reply-to'), values.has('--reply-address'), values.has('--reply-to')].filter(Boolean).length > 1)
75
126
  throw new Refusal('conflicting_reply_options');
127
+ if (values.has('--reply-to'))
128
+ returnHost(values.get('--reply-to'));
76
129
  if (values.get('--to').startsWith('session-peer:')) {
77
130
  const route = reply(values.get('--to'));
78
- for (const [key, value] of [['--host', route.host], ['--codex-home', route.home]]) {
79
- if (values.has(key) && values.get(key) !== value)
80
- throw new Refusal('reply_route_conflict');
81
- if (value !== undefined)
82
- values.set(key, value);
83
- }
131
+ // Only a route taken from the URI alone may later normalize to local.
132
+ address = { uri: values.get('--to'), transport: route.host === undefined ? 'local' : 'ssh',
133
+ implicit: !hosts.length && !repeated.get('--ssh-opt').length && !['--remote-bin', '--remote-platform', '--ssh-control-path', '--ssh-jump'].some(k => values.has(k)) };
134
+ if (hosts.length && (hosts.length > 1 || host(hosts[0]) !== route.host))
135
+ throw new Refusal('reply_route_conflict');
136
+ if (route.host !== undefined)
137
+ hosts = [route.host];
138
+ if (values.has('--codex-home') && values.get('--codex-home') !== route.home)
139
+ throw new Refusal('reply_route_conflict');
140
+ if (route.home !== undefined)
141
+ values.set('--codex-home', route.home);
84
142
  values.set('--to', route.to);
85
143
  }
86
144
  }
@@ -92,10 +150,37 @@ export function parse(args) {
92
150
  }
93
151
  if (values.has('--codex-home') && !values.get('--codex-home'))
94
152
  throw new Refusal('invalid_codex_home');
95
- if (values.has('--host'))
96
- host(values.get('--host'));
153
+ // Validate every destination and option before any SSH process starts.
154
+ const destinations = new Set();
155
+ for (const item of hosts) {
156
+ const destination = host(item), at = destination.lastIndexOf('@');
157
+ // One attempt per destination: a repeated destination is refused, not sent twice.
158
+ const name = destination.slice(at + 1).toLowerCase(), key = destination.slice(0, at + 1) + (name.includes(':') ? new URL(`http://[${name}]`).hostname : name);
159
+ if (destinations.has(key))
160
+ throw new Refusal('duplicate_ssh_host');
161
+ destinations.add(key);
162
+ }
163
+ if (repeated.get('--ssh-opt').length && !hosts.length)
164
+ throw new Refusal('inapplicable_option');
165
+ const ssh = sshOptions(repeated.get('--ssh-opt'));
166
+ // `ssh -l` silently overrides USER@HOST, so both together are ambiguous.
167
+ if (ssh.user !== undefined && hosts.some(item => item.includes('@')))
168
+ throw new Refusal('conflicting_ssh_user');
169
+ let jump;
170
+ if (values.has('--ssh-jump')) {
171
+ if (!hosts.length)
172
+ throw new Refusal('inapplicable_option');
173
+ jump = sshJump(values.get('--ssh-jump'));
174
+ // An existing control master would bypass the hop entirely.
175
+ if (values.has('--ssh-control-path'))
176
+ throw new Refusal('conflicting_ssh_jump');
177
+ // Win32-OpenSSH starts ProxyCommand without a POSIX shell; not yet proven.
178
+ if (process.platform === 'win32')
179
+ throw new Refusal('ssh_jump_unsupported_platform');
180
+ }
97
181
  if (values.has('--ssh-control-path')) {
98
- if (!values.has('--host'))
182
+ // One control socket multiplexes one destination, never several.
183
+ if (hosts.length !== 1)
99
184
  throw new Refusal('inapplicable_option');
100
185
  try {
101
186
  if (!lstatSync(values.get('--ssh-control-path')).isSocket())
@@ -105,15 +190,15 @@ export function parse(args) {
105
190
  throw new Refusal('invalid_ssh_control_path');
106
191
  }
107
192
  }
108
- if (values.has('--remote-platform') && (!values.has('--host') || !['posix', 'win32'].includes(values.get('--remote-platform'))))
193
+ if (values.has('--remote-platform') && (!hosts.length || !['posix', 'win32'].includes(values.get('--remote-platform'))))
109
194
  throw new Refusal('invalid_remote_platform');
110
195
  if (values.has('--remote-bin')) {
111
196
  const binary = values.get('--remote-bin');
112
- if (!values.has('--host') || (values.get('--remote-platform') === 'win32' ?
197
+ if (!hosts.length || (values.get('--remote-platform') === 'win32' ?
113
198
  !/^[A-Za-z]:\\[^\r\n]+$/.test(binary) : !/^\/[\x20-\x7e]+$/.test(binary)))
114
199
  throw new Refusal('invalid_remote_bin');
115
200
  }
116
- return { command, values, flags };
201
+ return { command, values, flags, hosts, ssh, ...(jump ? { jump } : {}), ...(address ? { address } : {}) };
117
202
  }
118
203
  async function input() {
119
204
  const chunks = [];
@@ -140,6 +225,9 @@ export function sshPreflightFailure(result, expected) {
140
225
  return 'ssh_preflight_timeout';
141
226
  if (!result.spawned)
142
227
  return 'ssh_unavailable';
228
+ // A verified version is success even when login scripts write to stderr.
229
+ if (result.code === 0 && result.stdout.trim() === expected)
230
+ return undefined;
143
231
  const detail = result.stderr;
144
232
  if (/host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED|no [^\n]*host key is known/i.test(detail))
145
233
  return 'ssh_host_key_untrusted';
@@ -155,20 +243,22 @@ export function sshPreflightFailure(result, expected) {
155
243
  return 'ssh_preflight_failed';
156
244
  return undefined;
157
245
  }
158
- async function remote(options, message) {
246
+ async function remote(options, ssh, target, resolved, message, returnTo) {
159
247
  const { values, flags, command } = options;
160
- const target = host(values.get('--host'));
161
248
  const binary = values.get('--remote-bin') ?? 'session-peer';
162
249
  const windows = values.get('--remote-platform') === 'win32';
163
250
  const invoke = (flag) => {
164
251
  if (!windows)
165
252
  return `${quote(binary)} ${flag}`;
166
- const code = `& '${binary.replace(/'/g, "''")}' ${flag}`;
253
+ // PowerShell also closes single-quoted strings on U+2018-U+201B.
254
+ const code = `& '${binary.replace(/['\u2018-\u201b]/g, '$&$&')}' ${flag}`;
167
255
  return `powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(code, 'utf16le').toString('base64')}`;
168
256
  };
169
- const ssh = executable('ssh');
257
+ // OpenSSH keeps the first value obtained, so the fixed hardening options
258
+ // precede the allowlisted user options and cannot be overridden by them.
170
259
  const base = ['-T', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'ConnectTimeout=10',
171
- ...(values.has('--ssh-control-path') ? ['-S', values.get('--ssh-control-path')] : []), '--', target];
260
+ ...(options.jump ? jumpOptions(ssh, options.jump) : []),
261
+ ...(values.has('--ssh-control-path') ? ['-S', values.get('--ssh-control-path')] : []), ...resolved.options, ...options.ssh.args, '--', target];
172
262
  const preflight = await run(ssh, [...base, invoke('--version')], { timeout: 15000 });
173
263
  const preflightError = sshPreflightFailure(preflight, VERSION_LINE);
174
264
  if (preflightError)
@@ -184,7 +274,10 @@ async function remote(options, message) {
184
274
  if (flags.has('--allow-inactive-codex-home'))
185
275
  args.push('--allow-inactive-codex-home');
186
276
  if (command === 'send')
187
- args.push('--message', message, '--no-from', '--no-reply-to');
277
+ args.push(`--message=${message}`, '--no-from', '--no-reply-to');
278
+ // The destination probes back to this machine; the request carries only the host.
279
+ if (returnTo)
280
+ args.push('--return-route-host', returnTo);
188
281
  const done = await run(ssh, [...base, invoke('--stdio-request')], {
189
282
  timeout: 90000, input: JSON.stringify({ schemaVersion: 1, args })
190
283
  });
@@ -204,15 +297,70 @@ async function remote(options, message) {
204
297
  return uncertain();
205
298
  if (command === 'doctor' && value.ok && (value.diagnosticCompleted !== true || typeof value.ready !== 'boolean' || value.implementation !== 'typescript' || !value.agents || typeof value.agents !== 'object' || Array.isArray(value.agents)))
206
299
  return uncertain();
300
+ const probe = value.returnRoute;
301
+ if (command === 'doctor' && value.ok && returnTo && (!probe || typeof probe !== 'object' || !['verified', 'failed'].includes(probe.status) || !['local', 'ssh'].includes(probe.transport)))
302
+ return uncertain();
207
303
  const expectedStatus = flags.has('--dry-run') ? 'validated' : values.get('--to')?.startsWith('codex:') ? 'queued' : 'posted';
208
304
  if (command === 'send' && (value.consumptionConfirmed !== false ||
209
305
  (value.ok && (value.submitted !== !flags.has('--dry-run') || value.status !== expectedStatus)) ||
210
306
  (!value.ok && !((value.submitted === false && value.status === 'refused') || (value.submitted === null && value.status === 'unknown')))))
211
307
  return uncertain();
212
- return { ...value, host: target, sshHost: target };
308
+ // `clientUpdate` is client-local: a remote-supplied value is never trusted or shown.
309
+ delete value.clientUpdate;
310
+ return { value: { ...value, host: resolved.canonical, sshHost: target }, exitCode: done.code };
311
+ }
312
+ function failure(error, command, where) {
313
+ const unknown = error instanceof UnknownOutcome;
314
+ const refusal = error instanceof Refusal ? error : new Refusal('operation_failed', 1);
315
+ const homeResolution = error instanceof HomeRefusal || error instanceof CodexUnknownOutcome ? error.codexHomeResolution : undefined;
316
+ return { exitCode: unknown ? 1 : refusal.exitCode, value: { schemaVersion: 1, host: where, command, ok: false,
317
+ error: unknown ? 'outcome_unknown' : refusal.code, status: unknown ? 'unknown' : 'refused',
318
+ submitted: unknown ? null : false, consumptionConfirmed: false, retryAllowed: false,
319
+ ...(homeResolution === undefined ? {} : { codexHomeResolution: homeResolution }),
320
+ ...(error instanceof UpdateRefusal ? error.guidance : {}) } };
321
+ }
322
+ // Destinations run in order, one attempt each. A failure or unknown outcome is
323
+ // reported for that destination only; it is never retried or failed over.
324
+ async function remotes(options, status, message, returnTo) {
325
+ const ssh = executable('ssh'), results = [];
326
+ let exitCode = 0;
327
+ for (const requestedHost of options.hosts) {
328
+ const target = host(requestedHost);
329
+ let outcome, user = {}, canonical = target;
330
+ try {
331
+ // A known offline or ambiguous tailnet peer is refused before any SSH process.
332
+ const resolved = route(target, status);
333
+ canonical = resolved.canonical;
334
+ const hostName = resolved.hostName ? ['-o', `HostName=${resolved.hostName}`] : [];
335
+ // One `ssh -G` serves the user metadata and, for a resolved peer, shows
336
+ // whether ssh_config already pins a HostKeyAlias. Ours is added only when
337
+ // the configuration was read and has none; an unread one is never overridden.
338
+ let alias = [];
339
+ try {
340
+ const config = await sshConfig(ssh, target, { ...options.ssh, args: [...hostName, ...options.ssh.args] }, !!resolved.hostName);
341
+ user = config.user;
342
+ if (resolved.hostKeyAlias && config.read && !config.hostKeyAlias)
343
+ alias = ['-o', `HostKeyAlias=${resolved.hostKeyAlias}`];
344
+ }
345
+ catch {
346
+ user = { sshUser: null, sshUserSource: 'unknown' };
347
+ }
348
+ // Metadata never blocks or aborts a destination; earlier results are kept.
349
+ outcome = await remote(options, ssh, target, { canonical, options: [...hostName, ...alias] }, message, returnTo);
350
+ }
351
+ // One destination keeps the existing flat local-host failure shape.
352
+ catch (error) {
353
+ outcome = failure(error, options.command, options.hosts.length === 1 ? hostname() : canonical !== target ? canonical : requestedHost);
354
+ }
355
+ results.push({ ...outcome.value, ...(options.hosts.length > 1 && canonical === target ? { host: requestedHost } : {}), sshHost: target, ...user,
356
+ ...(options.jump ? { sshJump: options.jump.spec } : {}) });
357
+ exitCode = options.hosts.length === 1 ? outcome.exitCode : outcome.exitCode === 0 && exitCode === 0 ? 0 : 1;
358
+ }
359
+ return { value: results, exitCode };
213
360
  }
214
361
  let command = 'unknown';
215
362
  let format = 'json';
363
+ let wire = false;
216
364
  try {
217
365
  const [major, minor] = process.versions.node.split('.').map(Number);
218
366
  if (!((major === 22 && minor >= 13) || major === 24))
@@ -220,13 +368,15 @@ try {
220
368
  if (!['darwin', 'linux', 'win32'].includes(process.platform))
221
369
  throw new Refusal('unsupported_platform');
222
370
  let args = process.argv.slice(2);
223
- if (args.length === 1 && args[0] === '--version')
371
+ if (args.length === 1 && args[0] === REFRESH_ARG)
372
+ await refreshCache();
373
+ else if (args.length === 1 && args[0] === '--version')
224
374
  console.log(VERSION_LINE);
225
375
  else if ((args.length === 1 && ['--help', '-h'].includes(args[0])) ||
226
- (args.length === 2 && ['list', 'send', 'doctor'].includes(args[0]) && ['--help', '-h'].includes(args[1])))
376
+ (args.length === 2 && ['list', 'send', 'doctor', 'update'].includes(args[0]) && ['--help', '-h'].includes(args[1])))
227
377
  console.log(help(args.length === 2 ? args[0] : undefined));
228
378
  else {
229
- const wire = args.length === 1 && args[0] === '--stdio-request';
379
+ wire = args.length === 1 && args[0] === '--stdio-request';
230
380
  if (wire) {
231
381
  let request;
232
382
  try {
@@ -240,14 +390,25 @@ try {
240
390
  throw new Refusal('invalid_remote_request');
241
391
  args = record.args;
242
392
  }
243
- command = ['list', 'send', 'doctor'].includes(args[0] ?? '') ? args[0] : 'unknown';
393
+ command = ['list', 'send', 'doctor', 'update'].includes(args[0] ?? '') ? args[0] : 'unknown';
244
394
  const options = parse(args);
245
395
  format = !wire && options.values.get('--output-format') === 'text' ? 'text' : 'json';
246
396
  if (wire && options.values.get('--output-format') === 'text')
247
397
  throw new Refusal('remote_json_required');
248
- if (wire && (options.values.has('--host') || options.values.has('--remote-bin') || options.values.has('--remote-platform') || options.values.has('--ssh-control-path')))
398
+ if (wire && command === 'update')
399
+ throw new Refusal('remote_update_unsupported');
400
+ if (wire && (options.hosts.length || options.ssh.args.length || options.jump || options.values.has('--remote-bin') || options.values.has('--remote-platform') || options.values.has('--ssh-control-path') ||
401
+ options.values.has('--reply-to') || options.flags.has('--check-return-route')))
249
402
  throw new Refusal('nested_transport_forbidden');
250
- let message;
403
+ if (!wire && options.values.has('--return-route-host'))
404
+ throw new Refusal('unsupported_option');
405
+ // Tailscale status is queried at most once, and only when a route needs it.
406
+ let status, queried = false;
407
+ const tailnetStatus = async () => { if (!queried) {
408
+ queried = true;
409
+ status = await tailnet();
410
+ } return status; };
411
+ let message, routing = {};
251
412
  if (command === 'send') {
252
413
  message = options.values.get('--message');
253
414
  if (message === undefined || message === '-') {
@@ -256,29 +417,108 @@ try {
256
417
  message = await input();
257
418
  }
258
419
  checkMessage(message);
259
- message = envelope(message, options.flags.has('--no-from'), options.values.get('--reply-address'));
420
+ const noFrom = options.flags.has('--no-from'), noReply = options.flags.has('--no-reply-to');
421
+ if (options.address) {
422
+ const resolution = { uri: options.address.uri, transport: options.address.transport };
423
+ // A reply URI naming this user on this machine is delivered locally.
424
+ if (options.address.implicit && options.address.transport === 'ssh' && isSelf(host(options.hosts[0]), await tailnetStatus())) {
425
+ options.hosts = [];
426
+ requested = [];
427
+ Object.assign(resolution, { transport: 'local', normalizedFrom: 'ssh_self' });
428
+ }
429
+ routing.addressResolution = resolution;
430
+ }
431
+ const identity = wire || (noFrom && noReply) ? undefined : sender();
432
+ let address = options.values.get('--reply-address');
433
+ if (!address && !noReply && identity) {
434
+ const configured = configuredHost(options.values.get('--reply-to'));
435
+ let destination = configured ? route(returnHost(configured), await tailnetStatus()).canonical : undefined;
436
+ // Sent to another machine, a loopback or non-canonical numeric reply host could name the receiver.
437
+ if (destination && options.hosts.length && unsafeReturnHost(destination))
438
+ throw new Refusal('invalid_reply_host');
439
+ const local = !options.hosts.length && (!destination || isSelf(destination, await tailnetStatus()));
440
+ if (!local && !destination) {
441
+ const detected = detectedHost(await tailnetStatus());
442
+ try {
443
+ destination = detected ? returnHost(detected) : undefined;
444
+ }
445
+ catch {
446
+ destination = undefined;
447
+ }
448
+ }
449
+ // Generated routes are inert data; SSH routes stay unverified until doctor probes them.
450
+ try {
451
+ if (local) {
452
+ address = replyUri(identity);
453
+ routing.replyRoute = { uri: address, transport: 'local', status: 'verified', reason: 'same_machine_route' };
454
+ }
455
+ else if (destination) {
456
+ address = replyUri(identity, destination);
457
+ routing.replyRoute = { uri: address, transport: 'ssh', status: 'unverified', reason: 'reverse_ssh_not_checked' };
458
+ }
459
+ }
460
+ catch {
461
+ address = undefined;
462
+ delete routing.replyRoute;
463
+ }
464
+ }
465
+ message = envelope(message, noFrom, address, identity ?? null);
260
466
  checkMessage(message, options.values.get('--to').startsWith('codex:'));
261
467
  }
262
- let result;
263
- if (options.values.has('--host'))
264
- result = await remote(options, message);
468
+ let returnTo;
469
+ if (command === 'doctor' && options.flags.has('--check-return-route')) {
470
+ const configured = configuredHost(options.values.get('--reply-to')) ?? detectedHost(await tailnetStatus());
471
+ try {
472
+ returnTo = configured ? returnHost(configured) : undefined;
473
+ }
474
+ catch (error) {
475
+ if (options.values.has('--reply-to') || configuredHost())
476
+ throw error;
477
+ }
478
+ // A remote executor would read a loopback name as itself, not as this origin.
479
+ if (returnTo && options.hosts.length && unsafeReturnHost(returnTo))
480
+ throw new Refusal('invalid_return_route');
481
+ }
482
+ let result = {}, exitCode, results;
483
+ // Propagate the verified remote exit code so SSH and local refusals match.
484
+ if (options.hosts.length)
485
+ ({ value: results, exitCode } = await remotes(options, await tailnetStatus(), message, returnTo));
265
486
  else if (command === 'send')
266
487
  result = await send({ to: options.values.get('--to'), home: options.values.get('--codex-home'), codexBin: options.values.get('--codex-bin'), message: message, dryRun: options.flags.has('--dry-run'), allowInactive: options.flags.has('--allow-inactive-codex-home') });
267
- else if (command === 'doctor')
488
+ else if (command === 'update')
489
+ result = options.flags.has('--check') ? await checkUpdate(options.values.get('--channel')) : refuseSelfUpdate(options.values.get('--channel'));
490
+ else if (command === 'doctor') {
268
491
  result = await doctor(options.values.get('--agent'), options.values.get('--codex-home'), options.values.get('--codex-bin'));
492
+ // Opt-in reverse probe: locally, or on the destination when it arrives over the wire.
493
+ const probeTo = wire ? options.values.get('--return-route-host') : returnTo;
494
+ if (options.flags.has('--check-return-route') || probeTo)
495
+ result.returnRoute = await probeReturnRoute(probeTo && returnHost(probeTo), await tailnetStatus(), wire);
496
+ }
269
497
  else
270
498
  result = await listing(options.values.get('--agent'), options.values.get('--codex-home'), options.flags.has('--all'));
271
- console.log(renderOutput({ schemaVersion: 1, host: hostname(), command, ok: result.ok !== false, version: VERSION, referenceVersion: '1.0.2', ...result }, format));
272
- process.exitCode = result.ok === false ? 1 : 0;
499
+ if (command === 'send') {
500
+ results = results?.map(item => ({ ...item, ...routing }));
501
+ result = { ...result, ...routing };
502
+ }
503
+ // Without a return host there is nothing to probe from the destination.
504
+ if (command === 'doctor' && options.flags.has('--check-return-route') && !returnTo)
505
+ results = results?.map(item => item.ok === false ? item : ({ ...item, returnRoute: { status: 'failed', transport: 'ssh', host: null, reason: 'return_host_unavailable' } }));
506
+ const shape = (item) => ({ schemaVersion: 1, host: hostname(), command, ok: item.ok !== false, version: VERSION, referenceVersion: '1.0.2', ...item });
507
+ // Cached advisory notice, computed once per invocation by this client and never
508
+ // in wire mode. JSON: additive `clientUpdate` on a flat (single-result) object
509
+ // only; a repeated --host array keeps its exact element shape. Text: one stderr line.
510
+ const notice = wire || command === 'update' ? undefined : updateNotice(options.flags.has('--no-update-notice'));
511
+ const array = !!results && results.length > 1;
512
+ // One destination stays flat; repeated --host returns an ordered array.
513
+ console.log(renderOutput(array ? results.map(shape) : { ...shape(results?.[0] ?? result), ...(notice && format === 'json' ? { clientUpdate: notice } : {}) }, format));
514
+ if (notice && format === 'text')
515
+ console.error(noticeText(notice));
516
+ process.exitCode = exitCode ?? (result.ok === false ? 1 : 0);
273
517
  }
274
518
  }
275
519
  catch (error) {
276
- const unknown = error instanceof UnknownOutcome;
277
- const failure = error instanceof Refusal ? error : new Refusal('operation_failed', 1);
278
- const homeResolution = error instanceof HomeRefusal || error instanceof CodexUnknownOutcome ? error.codexHomeResolution : undefined;
279
- console.log(renderOutput({ schemaVersion: 1, host: hostname(), command, ok: false,
280
- error: unknown ? 'outcome_unknown' : failure.code, status: unknown ? 'unknown' : 'refused',
281
- submitted: unknown ? null : false, consumptionConfirmed: false, retryAllowed: false,
282
- ...(homeResolution === undefined ? {} : { codexHomeResolution: homeResolution }) }, format));
283
- process.exitCode = unknown ? 1 : failure.exitCode;
520
+ // A command-wide refusal before dispatch applies to every requested host.
521
+ const { value, exitCode } = failure(error, command, hostname());
522
+ console.log(renderOutput(!wire && requested.length > 1 ? requested.map(item => ({ ...value, host: item })) : value, format));
523
+ process.exitCode = exitCode;
284
524
  }
@@ -7,6 +7,8 @@ export declare const capabilities: {
7
7
  list: boolean;
8
8
  send: boolean;
9
9
  doctor: boolean;
10
+ updateCheck: boolean;
11
+ selfUpdate: boolean;
10
12
  wake: boolean;
11
13
  wait: boolean;
12
14
  ack: boolean;
@@ -3,7 +3,8 @@
3
3
  import { accessSync, constants, readdirSync, readFileSync, statSync } from 'node:fs';
4
4
  import { homedir } from 'node:os';
5
5
  import { delimiter, isAbsolute, join } from 'node:path';
6
- import { canonical, listingCandidates } from './discovery.js';
6
+ import { canonical, listingCandidates, sqliteHome } from './discovery.js';
7
+ import { batchShim } from './process.js';
7
8
  import { windowsProcessStart } from './windows.js';
8
9
  const failure = (error, missing, unknown) => {
9
10
  const code = error.code;
@@ -12,7 +13,7 @@ const failure = (error, missing, unknown) => {
12
13
  { status: 'unknown', code: unknown };
13
14
  };
14
15
  export const capabilities = {
15
- list: true, send: true, doctor: true, wake: false, wait: false, ack: false,
16
+ list: true, send: true, doctor: true, updateCheck: true, selfUpdate: false, wake: false, wait: false, ack: false,
16
17
  consumptionConfirmation: false, transports: ['local', 'ssh'], agents: ['claude', 'codex']
17
18
  };
18
19
  function tool(name) {
@@ -25,6 +26,8 @@ function tool(name) {
25
26
  if (!statSync(path).isFile())
26
27
  continue;
27
28
  accessSync(path, constants.X_OK);
29
+ if (batchShim(path))
30
+ return { status: 'unsupported', code: 'executable_unsupported', path, executed: false };
28
31
  return { status: 'available', code: 'executable_found', path, executed: false };
29
32
  }
30
33
  catch (error) {
@@ -67,8 +70,11 @@ async function codexHome(file) {
67
70
  export async function diagnoseCodex(home, binary) {
68
71
  const inventory = listingCandidates(home);
69
72
  const homes = [];
70
- for (const item of inventory.homes)
71
- homes.push({ ...item, ...await codexHome(item.stateDb) });
73
+ for (const item of inventory.homes) {
74
+ const storage = sqliteHome(item.codexHome);
75
+ homes.push({ ...item, ...(storage === 'configured' ? { status: 'unsupported', code: 'unsupported_codex_sqlite_home' } :
76
+ storage === 'unknown' ? { status: 'unknown', code: 'codex_config_unreadable' } : await codexHome(item.stateDb)) });
77
+ }
72
78
  const agentTool = tool(binary ?? 'codex');
73
79
  const complete = inventory.errors.length === 0 && homes.every(item => item.status === 'available' || (!item.required && item.status === 'missing'));
74
80
  const ready = complete && homes.some(item => item.status === 'available') && agentTool.status === 'available';
@@ -4,6 +4,7 @@ export declare class Refusal extends Error {
4
4
  readonly exitCode: number;
5
5
  constructor(code: string, exitCode?: number);
6
6
  }
7
+ export declare function sqliteHome(home: string): 'default' | 'configured' | 'unknown';
7
8
  export declare function canonical(path: string): string;
8
9
  export declare function claude(all: boolean): Row;
9
10
  export declare function configuredHomePaths(): string[];
package/dist/discovery.js CHANGED
@@ -13,6 +13,21 @@ export class Refusal extends Error {
13
13
  this.exitCode = exitCode;
14
14
  }
15
15
  }
16
+ // Codex can relocate state_5.sqlite/queue_1.sqlite with `sqlite_home`; validation
17
+ // reads <home>/state_5.sqlite, so any configured relocation is unsupported.
18
+ export function sqliteHome(home) {
19
+ let text;
20
+ try {
21
+ const file = join(home, 'config.toml'), stat = statSync(file);
22
+ if (!stat.isFile() || stat.size > 1024 * 1024)
23
+ return 'unknown';
24
+ text = readFileSync(file, 'utf8');
25
+ }
26
+ catch (error) {
27
+ return ['ENOENT', 'ENOTDIR'].includes(error.code ?? '') ? 'default' : 'unknown';
28
+ }
29
+ return /^[ \t]*["']?sqlite_home["']?[ \t]*=/m.test(text) ? 'configured' : 'default';
30
+ }
16
31
  function missing(error) {
17
32
  return ['ENOENT', 'ENOTDIR'].includes(error.code ?? '');
18
33
  }
@@ -53,8 +68,6 @@ function canonicalPath(absolute, seen) {
53
68
  function alive(pid) {
54
69
  if (pid <= 1)
55
70
  return false;
56
- if (process.platform === 'win32')
57
- return windowsProcessStart(pid) !== undefined;
58
71
  try {
59
72
  process.kill(pid, 0);
60
73
  return true;
@@ -93,8 +106,8 @@ export function claude(all) {
93
106
  if (typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid > 2147483647)
94
107
  continue;
95
108
  const matches = pid === Number(entry.slice(0, -5));
96
- let live = matches && alive(pid);
97
- if (live && process.platform === 'win32') {
109
+ let live = matches && process.platform !== 'win32' && alive(pid);
110
+ if (matches && process.platform === 'win32') {
98
111
  const started = typeof record.startedAt === 'number' && Number.isSafeInteger(record.startedAt) && record.startedAt > 0 ? record.startedAt : NaN;
99
112
  const ticks = windowsProcessStart(pid);
100
113
  const actual = ticks === undefined ? NaN : Number((ticks - 116444736000000000n) / 10000n);