session-peer 0.2.1 → 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,13 +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
- const FLAGS = ['--json', '--all', '--dry-run', '--no-from', '--no-reply-to', '--no-update-notice', '--allow-inactive-codex-home'];
13
- const VALUES = ['--agent', '--codex-home', '--codex-bin', '--output-format', '--to', '--message', '-m', '--host', '--remote-bin', '--remote-platform', '--ssh-control-path', '--reply-address'];
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 = [];
14
21
  export function parse(args) {
15
22
  const command = args[0];
16
- if (command !== 'list' && command !== 'send' && command !== 'doctor')
23
+ if (command !== 'list' && command !== 'send' && command !== 'doctor' && command !== 'update')
17
24
  throw new Refusal('unsupported_command');
18
- 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, []]));
19
41
  let positional;
20
42
  let terminated = false;
21
43
  for (let i = 1; i < args.length; i++) {
@@ -45,11 +67,15 @@ export function parse(args) {
45
67
  const option = split > 0 ? '' : (value ?? '').split('=')[0];
46
68
  if (value === undefined || values.has(name) || [...FLAGS, ...VALUES, '--help', '-h', '--version', '--stdio-request'].includes(option))
47
69
  throw new Refusal('invalid_option');
48
- values.set(name, value);
70
+ if (REPEATED.includes(name))
71
+ repeated.get(name).push(value);
72
+ else
73
+ values.set(name, value);
49
74
  }
50
75
  else
51
76
  throw new Refusal('unsupported_option');
52
77
  }
78
+ let hosts = repeated.get('--host');
53
79
  if (positional !== undefined) {
54
80
  if (values.has('--message'))
55
81
  throw new Refusal('conflicting_message_sources');
@@ -61,6 +87,18 @@ export function parse(args) {
61
87
  throw new Refusal('conflicting_output_options');
62
88
  if (!flags.has('--json') && !values.has('--output-format'))
63
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');
64
102
  if (command === 'list' || command === 'doctor') {
65
103
  if (values.has('--agent') && !['claude', 'codex'].includes(values.get('--agent')))
66
104
  throw new Refusal('unsupported_agent');
@@ -68,24 +106,39 @@ export function parse(args) {
68
106
  throw new Refusal('invalid_codex_home');
69
107
  if (values.get('--agent') === 'claude' && values.has('--codex-home'))
70
108
  throw new Refusal('inapplicable_option');
71
- 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)))
72
110
  throw new Refusal('inapplicable_option');
73
111
  if (command === 'doctor' && (flags.has('--all') || (values.get('--agent') === 'claude' && values.has('--codex-bin'))))
74
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));
75
119
  }
76
120
  else {
77
121
  if (!values.get('--to') || values.has('--agent') || flags.has('--all'))
78
122
  throw new Refusal('invalid_send_options');
79
- 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)
80
126
  throw new Refusal('conflicting_reply_options');
127
+ if (values.has('--reply-to'))
128
+ returnHost(values.get('--reply-to'));
81
129
  if (values.get('--to').startsWith('session-peer:')) {
82
130
  const route = reply(values.get('--to'));
83
- for (const [key, value] of [['--host', route.host], ['--codex-home', route.home]]) {
84
- if (values.has(key) && values.get(key) !== value)
85
- throw new Refusal('reply_route_conflict');
86
- if (value !== undefined)
87
- values.set(key, value);
88
- }
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);
89
142
  values.set('--to', route.to);
90
143
  }
91
144
  }
@@ -97,10 +150,37 @@ export function parse(args) {
97
150
  }
98
151
  if (values.has('--codex-home') && !values.get('--codex-home'))
99
152
  throw new Refusal('invalid_codex_home');
100
- if (values.has('--host'))
101
- 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
+ }
102
181
  if (values.has('--ssh-control-path')) {
103
- if (!values.has('--host'))
182
+ // One control socket multiplexes one destination, never several.
183
+ if (hosts.length !== 1)
104
184
  throw new Refusal('inapplicable_option');
105
185
  try {
106
186
  if (!lstatSync(values.get('--ssh-control-path')).isSocket())
@@ -110,15 +190,15 @@ export function parse(args) {
110
190
  throw new Refusal('invalid_ssh_control_path');
111
191
  }
112
192
  }
113
- 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'))))
114
194
  throw new Refusal('invalid_remote_platform');
115
195
  if (values.has('--remote-bin')) {
116
196
  const binary = values.get('--remote-bin');
117
- if (!values.has('--host') || (values.get('--remote-platform') === 'win32' ?
197
+ if (!hosts.length || (values.get('--remote-platform') === 'win32' ?
118
198
  !/^[A-Za-z]:\\[^\r\n]+$/.test(binary) : !/^\/[\x20-\x7e]+$/.test(binary)))
119
199
  throw new Refusal('invalid_remote_bin');
120
200
  }
121
- return { command, values, flags };
201
+ return { command, values, flags, hosts, ssh, ...(jump ? { jump } : {}), ...(address ? { address } : {}) };
122
202
  }
123
203
  async function input() {
124
204
  const chunks = [];
@@ -163,9 +243,8 @@ export function sshPreflightFailure(result, expected) {
163
243
  return 'ssh_preflight_failed';
164
244
  return undefined;
165
245
  }
166
- async function remote(options, message) {
246
+ async function remote(options, ssh, target, resolved, message, returnTo) {
167
247
  const { values, flags, command } = options;
168
- const target = host(values.get('--host'));
169
248
  const binary = values.get('--remote-bin') ?? 'session-peer';
170
249
  const windows = values.get('--remote-platform') === 'win32';
171
250
  const invoke = (flag) => {
@@ -175,9 +254,11 @@ async function remote(options, message) {
175
254
  const code = `& '${binary.replace(/['\u2018-\u201b]/g, '$&$&')}' ${flag}`;
176
255
  return `powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(code, 'utf16le').toString('base64')}`;
177
256
  };
178
- 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.
179
259
  const base = ['-T', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'ConnectTimeout=10',
180
- ...(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];
181
262
  const preflight = await run(ssh, [...base, invoke('--version')], { timeout: 15000 });
182
263
  const preflightError = sshPreflightFailure(preflight, VERSION_LINE);
183
264
  if (preflightError)
@@ -194,6 +275,9 @@ async function remote(options, message) {
194
275
  args.push('--allow-inactive-codex-home');
195
276
  if (command === 'send')
196
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);
197
281
  const done = await run(ssh, [...base, invoke('--stdio-request')], {
198
282
  timeout: 90000, input: JSON.stringify({ schemaVersion: 1, args })
199
283
  });
@@ -213,15 +297,70 @@ async function remote(options, message) {
213
297
  return uncertain();
214
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)))
215
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();
216
303
  const expectedStatus = flags.has('--dry-run') ? 'validated' : values.get('--to')?.startsWith('codex:') ? 'queued' : 'posted';
217
304
  if (command === 'send' && (value.consumptionConfirmed !== false ||
218
305
  (value.ok && (value.submitted !== !flags.has('--dry-run') || value.status !== expectedStatus)) ||
219
306
  (!value.ok && !((value.submitted === false && value.status === 'refused') || (value.submitted === null && value.status === 'unknown')))))
220
307
  return uncertain();
221
- return { value: { ...value, host: target, sshHost: target }, exitCode: done.code };
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 };
222
360
  }
223
361
  let command = 'unknown';
224
362
  let format = 'json';
363
+ let wire = false;
225
364
  try {
226
365
  const [major, minor] = process.versions.node.split('.').map(Number);
227
366
  if (!((major === 22 && minor >= 13) || major === 24))
@@ -229,13 +368,15 @@ try {
229
368
  if (!['darwin', 'linux', 'win32'].includes(process.platform))
230
369
  throw new Refusal('unsupported_platform');
231
370
  let args = process.argv.slice(2);
232
- 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')
233
374
  console.log(VERSION_LINE);
234
375
  else if ((args.length === 1 && ['--help', '-h'].includes(args[0])) ||
235
- (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])))
236
377
  console.log(help(args.length === 2 ? args[0] : undefined));
237
378
  else {
238
- const wire = args.length === 1 && args[0] === '--stdio-request';
379
+ wire = args.length === 1 && args[0] === '--stdio-request';
239
380
  if (wire) {
240
381
  let request;
241
382
  try {
@@ -249,14 +390,25 @@ try {
249
390
  throw new Refusal('invalid_remote_request');
250
391
  args = record.args;
251
392
  }
252
- command = ['list', 'send', 'doctor'].includes(args[0] ?? '') ? args[0] : 'unknown';
393
+ command = ['list', 'send', 'doctor', 'update'].includes(args[0] ?? '') ? args[0] : 'unknown';
253
394
  const options = parse(args);
254
395
  format = !wire && options.values.get('--output-format') === 'text' ? 'text' : 'json';
255
396
  if (wire && options.values.get('--output-format') === 'text')
256
397
  throw new Refusal('remote_json_required');
257
- 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')))
258
402
  throw new Refusal('nested_transport_forbidden');
259
- 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 = {};
260
412
  if (command === 'send') {
261
413
  message = options.values.get('--message');
262
414
  if (message === undefined || message === '-') {
@@ -265,30 +417,108 @@ try {
265
417
  message = await input();
266
418
  }
267
419
  checkMessage(message);
268
- 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);
269
466
  checkMessage(message, options.values.get('--to').startsWith('codex:'));
270
467
  }
271
- let result, exitCode;
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;
272
483
  // Propagate the verified remote exit code so SSH and local refusals match.
273
- if (options.values.has('--host'))
274
- ({ value: result, exitCode } = await remote(options, message));
484
+ if (options.hosts.length)
485
+ ({ value: results, exitCode } = await remotes(options, await tailnetStatus(), message, returnTo));
275
486
  else if (command === 'send')
276
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') });
277
- 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') {
278
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
+ }
279
497
  else
280
498
  result = await listing(options.values.get('--agent'), options.values.get('--codex-home'), options.flags.has('--all'));
281
- console.log(renderOutput({ schemaVersion: 1, host: hostname(), command, ok: result.ok !== false, version: VERSION, referenceVersion: '1.0.2', ...result }, format));
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));
282
516
  process.exitCode = exitCode ?? (result.ok === false ? 1 : 0);
283
517
  }
284
518
  }
285
519
  catch (error) {
286
- const unknown = error instanceof UnknownOutcome;
287
- const failure = error instanceof Refusal ? error : new Refusal('operation_failed', 1);
288
- const homeResolution = error instanceof HomeRefusal || error instanceof CodexUnknownOutcome ? error.codexHomeResolution : undefined;
289
- console.log(renderOutput({ schemaVersion: 1, host: hostname(), command, ok: false,
290
- error: unknown ? 'outcome_unknown' : failure.code, status: unknown ? 'unknown' : 'refused',
291
- submitted: unknown ? null : false, consumptionConfirmed: false, retryAllowed: false,
292
- ...(homeResolution === undefined ? {} : { codexHomeResolution: homeResolution }) }, format));
293
- 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;
294
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;
@@ -13,7 +13,7 @@ const failure = (error, missing, unknown) => {
13
13
  { status: 'unknown', code: unknown };
14
14
  };
15
15
  export const capabilities = {
16
- 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,
17
17
  consumptionConfirmation: false, transports: ['local', 'ssh'], agents: ['claude', 'codex']
18
18
  };
19
19
  function tool(name) {
package/dist/help.js CHANGED
@@ -3,11 +3,19 @@ export function help(command) {
3
3
  const common = `Output (required for operations; no default):
4
4
  --json | --output-format json|text JSON stays one machine-readable object
5
5
  Transport:
6
- --host HOST SSH destination (no nested transports)
6
+ --host [USER@]HOST SSH destination; repeat for ordered per-host results
7
+ (IPv6: 2001:db8::1 or [2001:db8::1]; no nested transports)
8
+ --ssh-opt OPT Allowlisted ssh option, repeatable: -p PORT, -l USER,
9
+ -i IDENTITY_FILE, -o Port|User|IdentityFile|IdentitiesOnly=VALUE,
10
+ -4, -6. Other options (ProxyJump, ProxyCommand, -F...) are refused
11
+ --ssh-jump USER@HOST[:PORT] One hardened jump host for every --host (POSIX clients;
12
+ fixed ProxyCommand with BatchMode/StrictHostKeyChecking)
7
13
  --remote-bin ABSOLUTE_PATH Remote session-peer executable
8
14
  --remote-platform posix|win32 Remote shell platform
9
- --ssh-control-path SOCKET Existing SSH control socket
10
- --no-update-notice Accepted compatibility flag
15
+ --ssh-control-path SOCKET Existing SSH control socket (one --host only)
16
+ Tailscale status is a routing hint only (SESSION_PEER_TAILSCALE=off skips it):
17
+ known online peers use their MagicDNS name, known offline peers are refused.
18
+ --no-update-notice Suppress the opt-in cached update notice
11
19
  -h, --help Show command help`;
12
20
  if (command === 'list')
13
21
  return `Usage: session-peer list [options]
@@ -23,7 +31,21 @@ Successful diagnostics exit 0 even when ready=false. Check readiness separately.
23
31
  --agent claude|codex Filter one agent (default: both)
24
32
  --codex-home HOME Pin Codex metadata inspection
25
33
  --codex-bin PATH Inspect executable availability; never execute it
34
+ --check-return-route Probe noninteractive SSH back to the return host
35
+ --reply-to USER@HOST Return host to probe (default: reply-host env or tailnet)
36
+ Forward reachability never implies a working return route.
26
37
  ${common}`;
38
+ if (command === 'update')
39
+ return `Usage: session-peer update --check [options]
40
+ Check the npm registry for a newer session-peer. Never installs or replaces files.
41
+ Without --check, refuses (self_update_unsupported) and names the owning manager's command.
42
+ --check Read the npm dist-tag (one request, 3 s timeout)
43
+ --channel latest|preview npm dist-tag to compare (default: latest)
44
+ Output (required; no default):
45
+ --json | --output-format json|text JSON stays one machine-readable object
46
+ -h, --help Show command help
47
+ Skills, Python installations and remote hosts are updated separately.
48
+ Notices on other commands are opt-in: SESSION_PEER_UPDATE_NOTICE=1.`;
27
49
  if (command === 'send')
28
50
  return `Usage: session-peer send --to TARGET [MESSAGE | --message TEXT | -m TEXT] [options]
29
51
  TARGET: Claude name/PID, claude:NAME/PID, codex:UUID, or session-peer reply URI.
@@ -33,9 +55,13 @@ Unicode names use exact Unicode 14.0.0 default casefold; collisions require PID.
33
55
  --codex-home HOME Explicit Codex home; otherwise select unique live writer
34
56
  --codex-bin PATH Native Codex executable
35
57
  --allow-inactive-codex-home Queue only with explicit verified inactive home
36
- --no-from Omit sender envelope
58
+ --no-from Omit detected Claude/Codex sender (From)
37
59
  --no-reply-to Do not add a reply route
38
- --reply-address URI Explicit reply route (conflicts with --no-reply-to)
60
+ --reply-address URI Explicit reply route
61
+ --reply-to HOST Return host for the generated route; precedence:
62
+ --reply-to, SESSION_PEER_REPLY_HOST, CC_PEER_REPLY_HOST,
63
+ tailnet address. The three reply options are exclusive.
64
+ Sender and Reply-To are inert metadata, never authentication.
39
65
  Queued/posted is not ACK. Unknown outcomes must not be retried automatically.
40
66
  ${common}`;
41
67
  return `session-peer ${VERSION} (TypeScript)
@@ -43,6 +69,7 @@ Usage: session-peer <command> [options]
43
69
  list List Claude/Codex sessions
44
70
  send Submit one guarded message
45
71
  doctor Inspect read-only metadata and capabilities
72
+ update --check Check npm for a newer version (no self-update)
46
73
  --version Print exact runtime version
47
74
  --help, -h Show help; <command> --help for details
48
75
  ${common}
package/dist/output.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export type OutputFormat = 'json' | 'text';
2
- export declare function renderOutput(value: Record<string, unknown>, format: OutputFormat): string;
2
+ export declare function renderOutput(value: Record<string, unknown> | Record<string, unknown>[], format: OutputFormat): string;
package/dist/output.js CHANGED
@@ -4,6 +4,8 @@ const safe = (value) => String(value ?? '').replace(/[\x00-\x1f\x7f-\x9f\u061c\u
4
4
  export function renderOutput(value, format) {
5
5
  if (format === 'json')
6
6
  return JSON.stringify(value);
7
+ if (Array.isArray(value))
8
+ return value.map(item => `Host: ${safe(item.host)}\n${renderOutput(item, format)}`).join('\n\n');
7
9
  const lines = [];
8
10
  if (value.command === 'list') {
9
11
  const sessions = Array.isArray(value.sessions) ? value.sessions : [];
@@ -24,6 +26,17 @@ export function renderOutput(value, format) {
24
26
  lines.push(`Ready: ${value.ready === true ? 'yes' : 'no'}`);
25
27
  lines.push(`Agents: ${safe(JSON.stringify(value.agents ?? {}))}`);
26
28
  lines.push(`Capabilities: ${safe(JSON.stringify(value.capabilities ?? {}))}`);
29
+ const route = value.returnRoute;
30
+ lines.push(route ? `Return route: ${safe(route.status)} via ${safe(route.transport)} (${safe(route.reason)})` : 'Return route: not checked (use --check-return-route)');
31
+ }
32
+ else if (value.command === 'update' && value.ok === true) {
33
+ lines.push(`session-peer ${safe(value.current)} (typescript): ${value.status === 'update_available' ? `${safe(value.latest)} available` :
34
+ value.status === 'ahead' ? `newer than ${safe(value.latest)}` : 'up to date'} on npm dist-tag ${safe(value.distTag)}.`);
35
+ if (value.outdated === true)
36
+ lines.push(value.updateCommand ? `Upgrade with: ${safe(value.updateCommand)}` : safe(value.guidance));
37
+ if (value.cache === 'skipped_stale_lock')
38
+ lines.push('Update cache not written: a stale npm-update.lock remains; delete it while no session-peer process runs.');
39
+ lines.push('Skills, Python installations and remote hosts are updated separately.');
27
40
  }
28
41
  else if (value.ok === true) {
29
42
  const target = value.target;
@@ -36,6 +49,8 @@ export function renderOutput(value, format) {
36
49
  }
37
50
  if (value.ok === false) {
38
51
  lines.push(`Error: ${safe(value.error ?? 'operation_failed')}`);
52
+ if (value.command === 'update' && value.error === 'self_update_unsupported')
53
+ lines.push(value.updateCommand ? `This installation is managed by ${safe(value.managedBy)}. Upgrade with: ${safe(value.updateCommand)}` : safe(value.guidance));
39
54
  if (value.command === 'send')
40
55
  lines.push(value.submitted === null ? 'Submission outcome unknown. Do not retry automatically.' : 'Nothing submitted.');
41
56
  }