session-peer 0.6.2 → 0.7.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/PARITY.md +1 -1
- package/README.ja.md +40 -33
- package/README.ko.md +16 -22
- package/README.md +10 -16
- package/README.zh-CN.md +38 -30
- package/RELEASING.md +20 -0
- package/dist/cli.d.ts +1 -17
- package/dist/cli.js +38 -211
- package/dist/execution.d.ts +60 -0
- package/dist/execution.js +215 -0
- package/dist/process.d.ts +2 -0
- package/dist/process.js +21 -3
- package/dist/protocol.d.ts +2 -2
- package/dist/protocol.js +1 -1
- package/dist/skill-metadata.js +4 -3
- package/docs/api.md +18 -15
- package/docs/design/execution-and-mcp.md +84 -0
- package/docs/design/typescript-skill-compatibility.md +7 -0
- package/docs/guide.ja.md +55 -53
- package/docs/guide.ko.md +52 -48
- package/docs/guide.md +81 -77
- package/docs/guide.zh-CN.md +54 -51
- package/docs/shorthand.md +9 -10
- package/package.json +2 -1
package/dist/cli.js
CHANGED
|
@@ -3,35 +3,27 @@ import { handoffCommand, handoffSend, prepareHandoff, privateMessage } from './h
|
|
|
3
3
|
import { receiptCommand } from './receipt-command.js';
|
|
4
4
|
import { managedReceiptSend } from './receipt-send.js';
|
|
5
5
|
import { canonicalId, closed, HANDOFF_LIMITS, HandoffBudget, parseStrictJson, parseWaitTimeout, safeInteger, systemClock } from './handoff.js';
|
|
6
|
-
import {
|
|
6
|
+
import { executeLocal, executeSsh, failure } from './execution.js';
|
|
7
7
|
import { help } from './help.js';
|
|
8
8
|
import { renderOutput } from './output.js';
|
|
9
9
|
import { hostname } from 'node:os';
|
|
10
10
|
import { lstatSync } from 'node:fs';
|
|
11
11
|
import { isAbsolute } from 'node:path';
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import { HomeRefusal } from './writer.js';
|
|
16
|
-
import { responseOutcome } from './ssh-response.js';
|
|
12
|
+
import { Refusal } from './discovery.js';
|
|
13
|
+
import { checkMessage } from './send.js';
|
|
14
|
+
import { enableCliSignalForwarding, stopCliChildren } from './process.js';
|
|
17
15
|
import { envelope, host, reply, VERSION, VERSION_LINE } from './protocol.js';
|
|
18
|
-
import { CHANNELS, checkUpdate, noticeText, refreshCache, refuseSelfUpdate, REFRESH_ARG, updateNotice
|
|
19
|
-
import {
|
|
16
|
+
import { CHANNELS, checkUpdate, noticeText, refreshCache, refuseSelfUpdate, REFRESH_ARG, updateNotice } from './updates.js';
|
|
17
|
+
import { sshJump, sshOptions } from './ssh.js';
|
|
20
18
|
import { configuredHost, detectedHost, isSelf, probeReturnRoute, unsafeReturnHost, replyUri, returnHost, route, sender, tailnet } from './replies.js';
|
|
21
19
|
const FLAGS = ['--json', '--all', '--dry-run', '--no-from', '--no-reply-to', '--no-update-notice', '--allow-inactive-codex-home', '--check-return-route', '--check', '--request-ack', '--observe-delivery'];
|
|
22
20
|
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', '--correlation-id', '--wait-for', '--wait-timeout', '--message-file', '--receipt-collector'];
|
|
23
21
|
// Repeated in order; every other value option is single.
|
|
24
22
|
const REPEATED = ['--host', '--ssh-opt'];
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
const
|
|
29
|
-
if (command !== 'list' && command !== 'send' && command !== 'doctor' && command !== 'update')
|
|
30
|
-
throw new Refusal('unsupported_command');
|
|
31
|
-
// Collect requested hosts before any other validation, so that even a syntax
|
|
32
|
-
// refusal with several --host values is attributed to each of them. Value
|
|
33
|
-
// options consume their next token, as in the loop below; `--` ends options.
|
|
34
|
-
requested = [];
|
|
23
|
+
function requestedHosts(args) {
|
|
24
|
+
// Collect hosts before option validation so a command-wide refusal can be
|
|
25
|
+
// attributed to each of them. A value option consumes its following token.
|
|
26
|
+
const requested = [];
|
|
35
27
|
for (let i = 1; i < args.length && args[i] !== '--'; i++) {
|
|
36
28
|
const token = args[i], key = token.split('=')[0];
|
|
37
29
|
if (key === '--host') {
|
|
@@ -42,6 +34,12 @@ export function parse(args) {
|
|
|
42
34
|
else if (VALUES.includes(key) && !token.includes('='))
|
|
43
35
|
i++;
|
|
44
36
|
}
|
|
37
|
+
return requested;
|
|
38
|
+
}
|
|
39
|
+
export function parse(args) {
|
|
40
|
+
const command = args[0];
|
|
41
|
+
if (command !== 'list' && command !== 'send' && command !== 'doctor' && command !== 'update')
|
|
42
|
+
throw new Refusal('unsupported_command');
|
|
45
43
|
let address;
|
|
46
44
|
const values = new Map(), flags = new Set(), repeated = new Map(REPEATED.map(k => [k, []]));
|
|
47
45
|
let positional;
|
|
@@ -279,196 +277,16 @@ async function input(limit = 4_100_000, preserveBOM = false, timeoutMs) {
|
|
|
279
277
|
clearTimeout(timer);
|
|
280
278
|
}
|
|
281
279
|
}
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
if (
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
return 'ssh_unavailable';
|
|
290
|
-
// A verified version is success even when login scripts write to stderr.
|
|
291
|
-
if (result.code === 0 && result.stdout.trim() === expected)
|
|
292
|
-
return undefined;
|
|
293
|
-
const detail = result.stderr;
|
|
294
|
-
if (/host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED|no [^\n]*host key is known/i.test(detail))
|
|
295
|
-
return 'ssh_host_key_untrusted';
|
|
296
|
-
if (/permission denied \(|authentication failed|too many authentication failures|tailnet policy does not permit/i.test(detail))
|
|
297
|
-
return 'ssh_authentication_refused';
|
|
298
|
-
if (/could not resolve hostname|name or service not known|network is unreachable|no route to host|connection timed out|connection refused|operation timed out/i.test(detail))
|
|
299
|
-
return 'ssh_unreachable';
|
|
300
|
-
if (result.code === 127 && /not found|no such file|not recognized/i.test(detail))
|
|
301
|
-
return 'remote_cli_missing';
|
|
302
|
-
if (result.code === 0 && result.stdout.trim() !== expected)
|
|
303
|
-
return 'remote_version_mismatch';
|
|
304
|
-
if (result.code !== 0)
|
|
305
|
-
return 'ssh_preflight_failed';
|
|
306
|
-
return undefined;
|
|
307
|
-
}
|
|
308
|
-
async function remote(options, ssh, target, resolved, message, returnTo, budget) {
|
|
309
|
-
const { values, flags, command } = options;
|
|
310
|
-
const binary = values.get('--remote-bin') ?? 'session-peer';
|
|
311
|
-
const windows = values.get('--remote-platform') === 'win32';
|
|
312
|
-
const invoke = (flag) => {
|
|
313
|
-
if (!windows)
|
|
314
|
-
return `${quote(binary)} ${flag}`;
|
|
315
|
-
// PowerShell also closes single-quoted strings on U+2018-U+201B.
|
|
316
|
-
// PowerShell otherwise maps every native nonzero exit to 1. A failed
|
|
317
|
-
// invocation has no native exit code and must not accidentally exit 0.
|
|
318
|
-
const code = `& '${binary.replace(/['\u2018-\u201b]/g, '$&$&')}' ${flag}; if ($null -eq $LASTEXITCODE) { exit 1 }; exit $LASTEXITCODE`;
|
|
319
|
-
return `powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(code, 'utf16le').toString('base64')}`;
|
|
320
|
-
};
|
|
321
|
-
// OpenSSH keeps the first value obtained, so the fixed hardening options
|
|
322
|
-
// precede the allowlisted user options and cannot be overridden by them.
|
|
323
|
-
const base = ['-T', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'ConnectTimeout=10',
|
|
324
|
-
...(options.jump ? jumpOptions(ssh, options.jump) : []),
|
|
325
|
-
...(values.has('--ssh-control-path') ? ['-S', values.get('--ssh-control-path')] : []), ...resolved.options, ...options.ssh.args, '--', target];
|
|
326
|
-
budget?.beforeEffect();
|
|
327
|
-
const preflight = await run(ssh, [...base, invoke('--version')], { timeout: budget ? Math.max(1, Math.min(15000, budget.observationRemainingMs())) : 15000 });
|
|
328
|
-
const preflightError = sshPreflightFailure(preflight, VERSION_LINE);
|
|
329
|
-
if (preflightError)
|
|
330
|
-
throw new Refusal(preflightError, 1);
|
|
331
|
-
const args = [command, '--json'];
|
|
332
|
-
for (const [key, value] of values)
|
|
333
|
-
if (['--agent', '--codex-home', '--codex-bin', '--to'].includes(key))
|
|
334
|
-
args.push(key, value);
|
|
335
|
-
if (flags.has('--all'))
|
|
336
|
-
args.push('--all');
|
|
337
|
-
if (flags.has('--dry-run'))
|
|
338
|
-
args.push('--dry-run');
|
|
339
|
-
if (flags.has('--allow-inactive-codex-home'))
|
|
340
|
-
args.push('--allow-inactive-codex-home');
|
|
341
|
-
if (command === 'send')
|
|
342
|
-
args.push(`--message=${message}`, '--no-from', '--no-reply-to');
|
|
343
|
-
// The destination probes back to this machine; the request carries only the host.
|
|
344
|
-
if (returnTo)
|
|
345
|
-
args.push('--return-route-host', returnTo);
|
|
346
|
-
const context = budget ? { correlationId: values.get('--correlation-id'), requestAck: flags.has('--request-ack'),
|
|
347
|
-
observeDelivery: flags.has('--observe-delivery'), waitFor: values.get('--wait-for') } : undefined;
|
|
348
|
-
if (context) {
|
|
349
|
-
for (const key of ['--correlation-id', '--wait-for', '--wait-timeout'])
|
|
350
|
-
if (values.has(key))
|
|
351
|
-
args.push(key, values.get(key));
|
|
352
|
-
for (const key of ['--request-ack', '--observe-delivery'])
|
|
353
|
-
if (flags.has(key))
|
|
354
|
-
args.push(key);
|
|
355
|
-
}
|
|
356
|
-
const execute = (requestArgs, preparation = false) => {
|
|
357
|
-
budget?.beforeEffect();
|
|
358
|
-
const remainingMs = budget ? Math.floor(budget.remainingMs()) : undefined;
|
|
359
|
-
if (remainingMs !== undefined && (remainingMs < 1 || remainingMs > 60000))
|
|
360
|
-
throw new Refusal('invalid_handoff_budget', 1);
|
|
361
|
-
return run(ssh, [...base, invoke(`--stdio-request${remainingMs === undefined ? '' : ` --handoff-remaining-ms=${remainingMs}`}`)], {
|
|
362
|
-
timeout: budget ? Math.max(1, budget.remainingMs() - 200) : 90000, rawStdout: true,
|
|
363
|
-
input: JSON.stringify({ schemaVersion: 1, args: requestArgs,
|
|
364
|
-
...(remainingMs !== undefined ? { handoff: { schemaVersion: 1, remainingMs, ...(preparation ? { preparation: true } : {}) } } : {}) })
|
|
365
|
-
});
|
|
366
|
-
};
|
|
367
|
-
let prepared;
|
|
368
|
-
let destinationHost;
|
|
369
|
-
let boundTo = values.get('--to'), boundHome = values.get('--codex-home');
|
|
370
|
-
if (budget) {
|
|
371
|
-
// This round reserves a destination-owned intent and performs zero native
|
|
372
|
-
// submissions. An incomplete response is never replayed or guessed into send.
|
|
373
|
-
const preparation = await execute(args, true);
|
|
374
|
-
let checked;
|
|
375
|
-
try {
|
|
376
|
-
checked = responseOutcome(preparation, { command, to: boundTo, home: boundHome, dryRun: true,
|
|
377
|
-
allowInactive: flags.has('--allow-inactive-codex-home'), handoff: { ...context, preparation: true } });
|
|
378
|
-
}
|
|
379
|
-
catch {
|
|
380
|
-
throw new Refusal('remote_preparation_unverified', 1);
|
|
381
|
-
}
|
|
382
|
-
if (checked.value.ok === true && checked.exitCode !== 0)
|
|
383
|
-
throw new Refusal('remote_preparation_unverified', 1);
|
|
384
|
-
if (checked.exitCode !== 0 || checked.value.ok !== true)
|
|
385
|
-
return { value: { ...checked.value, host: resolved.canonical, sshHost: target }, exitCode: checked.exitCode || 1 };
|
|
386
|
-
const h = checked.value.handoff;
|
|
387
|
-
if (!h)
|
|
388
|
-
throw new Refusal('remote_preparation_unverified', 1);
|
|
389
|
-
prepared = { correlationId: h.correlationId, ledgerEpoch: h.ledgerEpoch, targetGeneration: h.targetGeneration };
|
|
390
|
-
destinationHost = checked.value.host;
|
|
391
|
-
const nativeTarget = checked.value.target;
|
|
392
|
-
boundTo = boundTo.startsWith('codex:') ? `codex:${nativeTarget.id}` : `claude:${nativeTarget.pid}`;
|
|
393
|
-
if (boundTo.startsWith('codex:'))
|
|
394
|
-
boundHome = checked.value.codexHome;
|
|
395
|
-
const replace = (key, value) => { const index = args.indexOf(key); if (index >= 0)
|
|
396
|
-
args[index + 1] = value;
|
|
397
|
-
else
|
|
398
|
-
args.push(key, value); };
|
|
399
|
-
replace('--to', boundTo);
|
|
400
|
-
replace('--correlation-id', h.correlationId);
|
|
401
|
-
if (boundHome !== undefined)
|
|
402
|
-
replace('--codex-home', boundHome);
|
|
403
|
-
}
|
|
404
|
-
const done = await execute(args);
|
|
405
|
-
const uncertain = () => { if (command === 'send' && !flags.has('--dry-run') && done.spawned)
|
|
406
|
-
throw new UnknownOutcome(); throw new Refusal('remote_response_unverified', 1); };
|
|
407
|
-
let verified;
|
|
408
|
-
try {
|
|
409
|
-
verified = responseOutcome(done, { command, to: boundTo, dryRun: flags.has('--dry-run'), returnTo,
|
|
410
|
-
home: boundHome, allowInactive: flags.has('--allow-inactive-codex-home'), ...(context ? { handoff: { ...context, correlationId: prepared.correlationId, prepared, destinationHost } } : {}) });
|
|
411
|
-
}
|
|
412
|
-
catch {
|
|
413
|
-
return uncertain();
|
|
414
|
-
}
|
|
415
|
-
const { value } = verified;
|
|
416
|
-
// `clientUpdate` is client-local: a remote-supplied value is never trusted or shown.
|
|
417
|
-
delete value.clientUpdate;
|
|
418
|
-
return { value: { ...value, host: resolved.canonical, sshHost: target }, exitCode: verified.exitCode };
|
|
419
|
-
}
|
|
420
|
-
function failure(error, command, where) {
|
|
421
|
-
const unknown = error instanceof UnknownOutcome;
|
|
422
|
-
const refusal = error instanceof Refusal ? error : new Refusal('operation_failed', 1);
|
|
423
|
-
const homeResolution = error instanceof HomeRefusal || error instanceof CodexUnknownOutcome ? error.codexHomeResolution : undefined;
|
|
424
|
-
return { exitCode: unknown ? 1 : refusal.exitCode, value: { schemaVersion: 1, host: where, command, ok: false,
|
|
425
|
-
error: unknown ? 'outcome_unknown' : refusal.code, status: unknown ? 'unknown' : 'refused',
|
|
426
|
-
submitted: unknown ? null : false, consumptionConfirmed: false, retryAllowed: false,
|
|
427
|
-
...(homeResolution === undefined ? {} : { codexHomeResolution: homeResolution }),
|
|
428
|
-
...(error instanceof UpdateRefusal ? error.guidance : {}) } };
|
|
429
|
-
}
|
|
430
|
-
// Destinations run in order, one attempt each. A failure or unknown outcome is
|
|
431
|
-
// reported for that destination only; it is never retried or failed over.
|
|
432
|
-
async function remotes(options, status, message, returnTo, firstBudget) {
|
|
433
|
-
const ssh = executable('ssh'), results = [];
|
|
434
|
-
let exitCode = 0;
|
|
435
|
-
for (const requestedHost of options.hosts) {
|
|
436
|
-
const target = host(requestedHost);
|
|
437
|
-
let outcome, user = {}, canonical = target;
|
|
438
|
-
try {
|
|
439
|
-
const budget = firstBudget ? results.length === 0 ? firstBudget : new HandoffBudget(parseWaitTimeout(options.values.get('--wait-timeout') ?? '30')) : undefined;
|
|
440
|
-
budget?.beforeEffect();
|
|
441
|
-
// A known offline or ambiguous tailnet peer is refused before any SSH process.
|
|
442
|
-
const resolved = route(target, status);
|
|
443
|
-
canonical = resolved.canonical;
|
|
444
|
-
const hostName = resolved.hostName ? ['-o', `HostName=${resolved.hostName}`] : [];
|
|
445
|
-
// One `ssh -G` serves the user metadata and, for a resolved peer, shows
|
|
446
|
-
// whether ssh_config already pins a HostKeyAlias. Ours is added only when
|
|
447
|
-
// the configuration was read and has none; an unread one is never overridden.
|
|
448
|
-
let alias = [];
|
|
449
|
-
try {
|
|
450
|
-
const config = await sshConfig(ssh, target, { ...options.ssh, args: [...hostName, ...options.ssh.args] }, !!resolved.hostName);
|
|
451
|
-
user = config.user;
|
|
452
|
-
if (resolved.hostKeyAlias && config.read && !config.hostKeyAlias)
|
|
453
|
-
alias = ['-o', `HostKeyAlias=${resolved.hostKeyAlias}`];
|
|
454
|
-
}
|
|
455
|
-
catch {
|
|
456
|
-
user = { sshUser: null, sshUserSource: 'unknown' };
|
|
457
|
-
}
|
|
458
|
-
// Metadata never blocks or aborts a destination; earlier results are kept.
|
|
459
|
-
outcome = await remote(options, ssh, target, { canonical, options: [...hostName, ...alias] }, message, returnTo, budget);
|
|
460
|
-
}
|
|
461
|
-
// One destination keeps the existing flat local-host failure shape.
|
|
462
|
-
catch (error) {
|
|
463
|
-
outcome = failure(error, options.command, options.hosts.length === 1 ? hostname() : canonical !== target ? canonical : requestedHost);
|
|
464
|
-
}
|
|
465
|
-
results.push({ ...outcome.value, ...(options.hosts.length > 1 && canonical === target ? { host: requestedHost } : {}), sshHost: target, ...user,
|
|
466
|
-
...(options.jump ? { sshJump: options.jump.spec } : {}) });
|
|
467
|
-
exitCode = options.hosts.length === 1 ? outcome.exitCode : outcome.exitCode === 0 && exitCode === 0 ? 0 : 1;
|
|
468
|
-
}
|
|
469
|
-
return { value: results, exitCode };
|
|
280
|
+
enableCliSignalForwarding();
|
|
281
|
+
const mcpWorker = Boolean(process.send) && process.env.SESSION_PEER_MCP_WORKER === '1';
|
|
282
|
+
const stopMcpWorker = () => { stopCliChildren(); process.exit(130); };
|
|
283
|
+
if (mcpWorker) {
|
|
284
|
+
process.on('message', message => { if (message === 'session-peer:cancel')
|
|
285
|
+
stopMcpWorker(); });
|
|
286
|
+
process.once('disconnect', stopMcpWorker);
|
|
470
287
|
}
|
|
471
288
|
let command = 'unknown';
|
|
289
|
+
let requested = [];
|
|
472
290
|
let format = 'json';
|
|
473
291
|
let wire = false;
|
|
474
292
|
let wireWatchdog;
|
|
@@ -571,6 +389,8 @@ try {
|
|
|
571
389
|
args = record.args;
|
|
572
390
|
}
|
|
573
391
|
command = ['list', 'send', 'doctor', 'update'].includes(args[0] ?? '') ? args[0] : 'unknown';
|
|
392
|
+
if (command !== 'unknown')
|
|
393
|
+
requested = requestedHosts(args);
|
|
574
394
|
const options = parse(args);
|
|
575
395
|
if (wire && options.values.has('--receipt-collector'))
|
|
576
396
|
throw new Refusal('remote_receipt_unsupported', 1);
|
|
@@ -617,9 +437,11 @@ try {
|
|
|
617
437
|
if (message === undefined || (!wire && message === '-')) {
|
|
618
438
|
if (wire)
|
|
619
439
|
throw new Refusal('remote_message_required');
|
|
620
|
-
message = await input(4_100_000,
|
|
440
|
+
message = await input(4_100_000, mcpWorker, handoffBudget?.observationRemainingMs());
|
|
621
441
|
}
|
|
622
442
|
}
|
|
443
|
+
if (mcpWorker && process.env.SESSION_PEER_MCP_BODY_BYTES !== String(Buffer.byteLength(message, 'utf8')))
|
|
444
|
+
throw new Refusal('worker_input_incomplete');
|
|
623
445
|
checkMessage(message);
|
|
624
446
|
rawMessage = message;
|
|
625
447
|
const noFrom = options.flags.has('--no-from'), noReply = options.flags.has('--no-reply-to');
|
|
@@ -687,7 +509,7 @@ try {
|
|
|
687
509
|
let result = {}, exitCode, results;
|
|
688
510
|
// Propagate the verified remote exit code so SSH and local refusals match.
|
|
689
511
|
if (options.hosts.length)
|
|
690
|
-
({ value: results, exitCode } = await
|
|
512
|
+
({ value: results, exitCode } = await executeSsh({ options, context: { tailnet: await tailnetStatus(), returnTo, budget: handoffBudget }, message }));
|
|
691
513
|
else if (command === 'send') {
|
|
692
514
|
const settings = { 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') };
|
|
693
515
|
const enabled = options.flags.has('--request-ack') || options.flags.has('--observe-delivery') || options.values.has('--correlation-id') || options.values.has('--wait-for') || options.values.has('--wait-timeout');
|
|
@@ -702,19 +524,19 @@ try {
|
|
|
702
524
|
else if (enabled)
|
|
703
525
|
({ value: result, exitCode } = await handoffSend(settings, { remote: wireContext !== undefined, correlationId: options.values.get('--correlation-id'), requestAck: options.flags.has('--request-ack'), observeDelivery: options.flags.has('--observe-delivery'), waitFor: options.values.get('--wait-for'), seconds: parseWaitTimeout(options.values.get('--wait-timeout') ?? '30'), payload: rawMessage, budget: handoffBudget, resultOverhead: Buffer.byteLength(JSON.stringify(routing)) + 1024 }));
|
|
704
526
|
else
|
|
705
|
-
result = await send
|
|
527
|
+
result = await executeLocal({ command: 'send', settings });
|
|
706
528
|
}
|
|
707
529
|
else if (command === 'update')
|
|
708
530
|
result = options.flags.has('--check') ? await checkUpdate(options.values.get('--channel')) : refuseSelfUpdate(options.values.get('--channel'));
|
|
709
531
|
else if (command === 'doctor') {
|
|
710
|
-
result = await doctor
|
|
532
|
+
result = await executeLocal({ command: 'doctor', agent: options.values.get('--agent'), home: options.values.get('--codex-home'), binary: options.values.get('--codex-bin') });
|
|
711
533
|
// Opt-in reverse probe: locally, or on the destination when it arrives over the wire.
|
|
712
534
|
const probeTo = wire ? options.values.get('--return-route-host') : returnTo;
|
|
713
535
|
if (options.flags.has('--check-return-route') || probeTo)
|
|
714
536
|
result.returnRoute = await probeReturnRoute(probeTo && returnHost(probeTo), await tailnetStatus(), wire);
|
|
715
537
|
}
|
|
716
538
|
else
|
|
717
|
-
result = await
|
|
539
|
+
result = await executeLocal({ command: 'list', agent: options.values.get('--agent'), home: options.values.get('--codex-home'), all: options.flags.has('--all') });
|
|
718
540
|
if (command === 'send') {
|
|
719
541
|
results = results?.map(item => ({ ...item, ...routing }));
|
|
720
542
|
result = { ...result, ...routing };
|
|
@@ -755,4 +577,9 @@ catch (error) {
|
|
|
755
577
|
finally {
|
|
756
578
|
if (wireWatchdog)
|
|
757
579
|
clearTimeout(wireWatchdog);
|
|
580
|
+
if (mcpWorker) {
|
|
581
|
+
stopCliChildren();
|
|
582
|
+
process.removeListener('disconnect', stopMcpWorker);
|
|
583
|
+
process.disconnect?.();
|
|
584
|
+
}
|
|
758
585
|
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { doctor } from './diagnostics.js';
|
|
2
|
+
import { listing } from './discovery.js';
|
|
3
|
+
import { HandoffBudget } from './handoff.js';
|
|
4
|
+
import { type Done } from './process.js';
|
|
5
|
+
import { type Tailnet } from './replies.js';
|
|
6
|
+
import { send, type SendOptions } from './send.js';
|
|
7
|
+
import { type SshJump, type SshOptions } from './ssh.js';
|
|
8
|
+
export type ParsedOptions = {
|
|
9
|
+
command: 'list' | 'send' | 'doctor' | 'update';
|
|
10
|
+
values: Map<string, string>;
|
|
11
|
+
flags: Set<string>;
|
|
12
|
+
hosts: string[];
|
|
13
|
+
ssh: SshOptions;
|
|
14
|
+
jump?: SshJump;
|
|
15
|
+
address?: {
|
|
16
|
+
uri: string;
|
|
17
|
+
transport: 'local' | 'ssh';
|
|
18
|
+
implicit: boolean;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
export type Agent = 'claude' | 'codex';
|
|
22
|
+
type AgentSelection = {
|
|
23
|
+
agent?: Agent;
|
|
24
|
+
home?: string;
|
|
25
|
+
};
|
|
26
|
+
export type LocalOperation = (AgentSelection & {
|
|
27
|
+
command: 'list';
|
|
28
|
+
all: boolean;
|
|
29
|
+
}) | (AgentSelection & {
|
|
30
|
+
command: 'doctor';
|
|
31
|
+
binary?: string;
|
|
32
|
+
}) | {
|
|
33
|
+
command: 'send';
|
|
34
|
+
settings: SendOptions;
|
|
35
|
+
};
|
|
36
|
+
type LocalAdapters = {
|
|
37
|
+
list: typeof listing;
|
|
38
|
+
doctor: typeof doctor;
|
|
39
|
+
send: typeof send;
|
|
40
|
+
};
|
|
41
|
+
export declare function executeLocal(operation: LocalOperation, adapters?: LocalAdapters): Promise<Record<string, unknown>>;
|
|
42
|
+
type SshOperation = {
|
|
43
|
+
options: ParsedOptions;
|
|
44
|
+
context: {
|
|
45
|
+
tailnet?: Tailnet;
|
|
46
|
+
returnTo?: string;
|
|
47
|
+
budget?: HandoffBudget;
|
|
48
|
+
};
|
|
49
|
+
message?: string;
|
|
50
|
+
};
|
|
51
|
+
export declare function executeSsh({ options, context, message }: SshOperation): Promise<{
|
|
52
|
+
value: Record<string, unknown>[];
|
|
53
|
+
exitCode: number;
|
|
54
|
+
}>;
|
|
55
|
+
export declare function sshPreflightFailure(result: Done, expected: string): string | undefined;
|
|
56
|
+
export declare function failure(error: unknown, command: string, where: string): {
|
|
57
|
+
value: Record<string, unknown>;
|
|
58
|
+
exitCode: number;
|
|
59
|
+
};
|
|
60
|
+
export {};
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { hostname } from 'node:os';
|
|
2
|
+
import { doctor } from './diagnostics.js';
|
|
3
|
+
import { listing, Refusal } from './discovery.js';
|
|
4
|
+
import { HandoffBudget, parseWaitTimeout } from './handoff.js';
|
|
5
|
+
import { executable, run, UnknownOutcome } from './process.js';
|
|
6
|
+
import { host, VERSION_LINE } from './protocol.js';
|
|
7
|
+
import { route } from './replies.js';
|
|
8
|
+
import { send, CodexUnknownOutcome } from './send.js';
|
|
9
|
+
import { responseOutcome } from './ssh-response.js';
|
|
10
|
+
import { jumpOptions, sshConfig } from './ssh.js';
|
|
11
|
+
import { UpdateRefusal } from './updates.js';
|
|
12
|
+
import { HomeRefusal } from './writer.js';
|
|
13
|
+
const localAdapters = { list: listing, doctor, send };
|
|
14
|
+
export async function executeLocal(operation, adapters = localAdapters) {
|
|
15
|
+
switch (operation.command) {
|
|
16
|
+
case 'list':
|
|
17
|
+
return adapters.list(operation.agent, operation.home, operation.all);
|
|
18
|
+
case 'doctor':
|
|
19
|
+
return adapters.doctor(operation.agent, operation.home, operation.binary);
|
|
20
|
+
case 'send':
|
|
21
|
+
return adapters.send(operation.settings);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export async function executeSsh({ options, context, message }) {
|
|
25
|
+
return remotes(options, context.tailnet, message, context.returnTo, context.budget);
|
|
26
|
+
}
|
|
27
|
+
const quote = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
|
|
28
|
+
// Classify only the no-message version preflight. Never expose SSH stderr,
|
|
29
|
+
// which can contain user paths or agent output.
|
|
30
|
+
export function sshPreflightFailure(result, expected) {
|
|
31
|
+
if (result.interrupted)
|
|
32
|
+
return 'ssh_preflight_timeout';
|
|
33
|
+
if (!result.spawned)
|
|
34
|
+
return 'ssh_unavailable';
|
|
35
|
+
// A verified version is success even when login scripts write to stderr.
|
|
36
|
+
if (result.code === 0 && result.stdout.trim() === expected)
|
|
37
|
+
return undefined;
|
|
38
|
+
const detail = result.stderr;
|
|
39
|
+
if (/host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED|no [^\n]*host key is known/i.test(detail))
|
|
40
|
+
return 'ssh_host_key_untrusted';
|
|
41
|
+
if (/permission denied \(|authentication failed|too many authentication failures|tailnet policy does not permit/i.test(detail))
|
|
42
|
+
return 'ssh_authentication_refused';
|
|
43
|
+
if (/could not resolve hostname|name or service not known|network is unreachable|no route to host|connection timed out|connection refused|operation timed out/i.test(detail))
|
|
44
|
+
return 'ssh_unreachable';
|
|
45
|
+
if (result.code === 127 && /not found|no such file|not recognized/i.test(detail))
|
|
46
|
+
return 'remote_cli_missing';
|
|
47
|
+
if (result.code === 0 && result.stdout.trim() !== expected)
|
|
48
|
+
return 'remote_version_mismatch';
|
|
49
|
+
if (result.code !== 0)
|
|
50
|
+
return 'ssh_preflight_failed';
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
async function remote(options, ssh, target, resolved, message, returnTo, budget) {
|
|
54
|
+
const { values, flags, command } = options;
|
|
55
|
+
const binary = values.get('--remote-bin') ?? 'session-peer';
|
|
56
|
+
const windows = values.get('--remote-platform') === 'win32';
|
|
57
|
+
const invoke = (flag) => {
|
|
58
|
+
if (!windows)
|
|
59
|
+
return `${quote(binary)} ${flag}`;
|
|
60
|
+
// PowerShell also closes single-quoted strings on U+2018-U+201B.
|
|
61
|
+
// PowerShell otherwise maps every native nonzero exit to 1. A failed
|
|
62
|
+
// invocation has no native exit code and must not accidentally exit 0.
|
|
63
|
+
const code = `& '${binary.replace(/['\u2018-\u201b]/g, '$&$&')}' ${flag}; if ($null -eq $LASTEXITCODE) { exit 1 }; exit $LASTEXITCODE`;
|
|
64
|
+
return `powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(code, 'utf16le').toString('base64')}`;
|
|
65
|
+
};
|
|
66
|
+
// OpenSSH keeps the first value obtained, so the fixed hardening options
|
|
67
|
+
// precede the allowlisted user options and cannot be overridden by them.
|
|
68
|
+
const base = ['-T', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'ConnectTimeout=10',
|
|
69
|
+
...(options.jump ? jumpOptions(ssh, options.jump) : []),
|
|
70
|
+
...(values.has('--ssh-control-path') ? ['-S', values.get('--ssh-control-path')] : []), ...resolved.options, ...options.ssh.args, '--', target];
|
|
71
|
+
budget?.beforeEffect();
|
|
72
|
+
const preflight = await run(ssh, [...base, invoke('--version')], { timeout: budget ? Math.max(1, Math.min(15000, budget.observationRemainingMs())) : 15000 });
|
|
73
|
+
const preflightError = sshPreflightFailure(preflight, VERSION_LINE);
|
|
74
|
+
if (preflightError)
|
|
75
|
+
throw new Refusal(preflightError, 1);
|
|
76
|
+
const args = [command, '--json'];
|
|
77
|
+
for (const [key, value] of values)
|
|
78
|
+
if (['--agent', '--codex-home', '--codex-bin', '--to'].includes(key))
|
|
79
|
+
args.push(key, value);
|
|
80
|
+
if (flags.has('--all'))
|
|
81
|
+
args.push('--all');
|
|
82
|
+
if (flags.has('--dry-run'))
|
|
83
|
+
args.push('--dry-run');
|
|
84
|
+
if (flags.has('--allow-inactive-codex-home'))
|
|
85
|
+
args.push('--allow-inactive-codex-home');
|
|
86
|
+
if (command === 'send')
|
|
87
|
+
args.push(`--message=${message}`, '--no-from', '--no-reply-to');
|
|
88
|
+
// The destination probes back to this machine; the request carries only the host.
|
|
89
|
+
if (returnTo)
|
|
90
|
+
args.push('--return-route-host', returnTo);
|
|
91
|
+
const context = budget ? { correlationId: values.get('--correlation-id'), requestAck: flags.has('--request-ack'),
|
|
92
|
+
observeDelivery: flags.has('--observe-delivery'), waitFor: values.get('--wait-for') } : undefined;
|
|
93
|
+
if (context) {
|
|
94
|
+
for (const key of ['--correlation-id', '--wait-for', '--wait-timeout'])
|
|
95
|
+
if (values.has(key))
|
|
96
|
+
args.push(key, values.get(key));
|
|
97
|
+
for (const key of ['--request-ack', '--observe-delivery'])
|
|
98
|
+
if (flags.has(key))
|
|
99
|
+
args.push(key);
|
|
100
|
+
}
|
|
101
|
+
const execute = (requestArgs, preparation = false) => {
|
|
102
|
+
budget?.beforeEffect();
|
|
103
|
+
const remainingMs = budget ? Math.floor(budget.remainingMs()) : undefined;
|
|
104
|
+
if (remainingMs !== undefined && (remainingMs < 1 || remainingMs > 60000))
|
|
105
|
+
throw new Refusal('invalid_handoff_budget', 1);
|
|
106
|
+
return run(ssh, [...base, invoke(`--stdio-request${remainingMs === undefined ? '' : ` --handoff-remaining-ms=${remainingMs}`}`)], {
|
|
107
|
+
timeout: budget ? Math.max(1, budget.remainingMs() - 200) : 90000, rawStdout: true,
|
|
108
|
+
input: JSON.stringify({ schemaVersion: 1, args: requestArgs,
|
|
109
|
+
...(remainingMs !== undefined ? { handoff: { schemaVersion: 1, remainingMs, ...(preparation ? { preparation: true } : {}) } } : {}) })
|
|
110
|
+
});
|
|
111
|
+
};
|
|
112
|
+
let prepared;
|
|
113
|
+
let destinationHost;
|
|
114
|
+
let boundTo = values.get('--to'), boundHome = values.get('--codex-home');
|
|
115
|
+
if (budget) {
|
|
116
|
+
// This round reserves a destination-owned intent and performs zero native
|
|
117
|
+
// submissions. An incomplete response is never replayed or guessed into send.
|
|
118
|
+
const preparation = await execute(args, true);
|
|
119
|
+
let checked;
|
|
120
|
+
try {
|
|
121
|
+
checked = responseOutcome(preparation, { command, to: boundTo, home: boundHome, dryRun: true,
|
|
122
|
+
allowInactive: flags.has('--allow-inactive-codex-home'), handoff: { ...context, preparation: true } });
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
throw new Refusal('remote_preparation_unverified', 1);
|
|
126
|
+
}
|
|
127
|
+
if (checked.value.ok === true && checked.exitCode !== 0)
|
|
128
|
+
throw new Refusal('remote_preparation_unverified', 1);
|
|
129
|
+
if (checked.exitCode !== 0 || checked.value.ok !== true)
|
|
130
|
+
return { value: { ...checked.value, host: resolved.canonical, sshHost: target }, exitCode: checked.exitCode || 1 };
|
|
131
|
+
const h = checked.value.handoff;
|
|
132
|
+
if (!h)
|
|
133
|
+
throw new Refusal('remote_preparation_unverified', 1);
|
|
134
|
+
prepared = { correlationId: h.correlationId, ledgerEpoch: h.ledgerEpoch, targetGeneration: h.targetGeneration };
|
|
135
|
+
destinationHost = checked.value.host;
|
|
136
|
+
const nativeTarget = checked.value.target;
|
|
137
|
+
boundTo = boundTo.startsWith('codex:') ? `codex:${nativeTarget.id}` : `claude:${nativeTarget.pid}`;
|
|
138
|
+
if (boundTo.startsWith('codex:'))
|
|
139
|
+
boundHome = checked.value.codexHome;
|
|
140
|
+
const replace = (key, value) => { const index = args.indexOf(key); if (index >= 0)
|
|
141
|
+
args[index + 1] = value;
|
|
142
|
+
else
|
|
143
|
+
args.push(key, value); };
|
|
144
|
+
replace('--to', boundTo);
|
|
145
|
+
replace('--correlation-id', h.correlationId);
|
|
146
|
+
if (boundHome !== undefined)
|
|
147
|
+
replace('--codex-home', boundHome);
|
|
148
|
+
}
|
|
149
|
+
const done = await execute(args);
|
|
150
|
+
const uncertain = () => { if (command === 'send' && !flags.has('--dry-run') && done.spawned)
|
|
151
|
+
throw new UnknownOutcome(); throw new Refusal('remote_response_unverified', 1); };
|
|
152
|
+
let verified;
|
|
153
|
+
try {
|
|
154
|
+
verified = responseOutcome(done, { command, to: boundTo, dryRun: flags.has('--dry-run'), returnTo,
|
|
155
|
+
home: boundHome, allowInactive: flags.has('--allow-inactive-codex-home'), ...(context ? { handoff: { ...context, correlationId: prepared.correlationId, prepared, destinationHost } } : {}) });
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
return uncertain();
|
|
159
|
+
}
|
|
160
|
+
const { value } = verified;
|
|
161
|
+
// `clientUpdate` is client-local: a remote-supplied value is never trusted or shown.
|
|
162
|
+
delete value.clientUpdate;
|
|
163
|
+
return { value: { ...value, host: resolved.canonical, sshHost: target }, exitCode: verified.exitCode };
|
|
164
|
+
}
|
|
165
|
+
export function failure(error, command, where) {
|
|
166
|
+
const unknown = error instanceof UnknownOutcome;
|
|
167
|
+
const refusal = error instanceof Refusal ? error : new Refusal('operation_failed', 1);
|
|
168
|
+
const homeResolution = error instanceof HomeRefusal || error instanceof CodexUnknownOutcome ? error.codexHomeResolution : undefined;
|
|
169
|
+
return { exitCode: unknown ? 1 : refusal.exitCode, value: { schemaVersion: 1, host: where, command, ok: false,
|
|
170
|
+
error: unknown ? 'outcome_unknown' : refusal.code, status: unknown ? 'unknown' : 'refused',
|
|
171
|
+
submitted: unknown ? null : false, consumptionConfirmed: false, retryAllowed: false,
|
|
172
|
+
...(homeResolution === undefined ? {} : { codexHomeResolution: homeResolution }),
|
|
173
|
+
...(error instanceof UpdateRefusal ? error.guidance : {}) } };
|
|
174
|
+
}
|
|
175
|
+
// Destinations run in order, one attempt each. A failure or unknown outcome is
|
|
176
|
+
// reported for that destination only; it is never retried or failed over.
|
|
177
|
+
async function remotes(options, status, message, returnTo, firstBudget) {
|
|
178
|
+
const ssh = executable('ssh'), results = [];
|
|
179
|
+
let exitCode = 0;
|
|
180
|
+
for (const requestedHost of options.hosts) {
|
|
181
|
+
const target = host(requestedHost);
|
|
182
|
+
let outcome, user = {}, canonical = target;
|
|
183
|
+
try {
|
|
184
|
+
const budget = firstBudget ? results.length === 0 ? firstBudget : new HandoffBudget(parseWaitTimeout(options.values.get('--wait-timeout') ?? '30')) : undefined;
|
|
185
|
+
budget?.beforeEffect();
|
|
186
|
+
// A known offline or ambiguous tailnet peer is refused before any SSH process.
|
|
187
|
+
const resolved = route(target, status);
|
|
188
|
+
canonical = resolved.canonical;
|
|
189
|
+
const hostName = resolved.hostName ? ['-o', `HostName=${resolved.hostName}`] : [];
|
|
190
|
+
// One `ssh -G` serves the user metadata and, for a resolved peer, shows
|
|
191
|
+
// whether ssh_config already pins a HostKeyAlias. Ours is added only when
|
|
192
|
+
// the configuration was read and has none; an unread one is never overridden.
|
|
193
|
+
let alias = [];
|
|
194
|
+
try {
|
|
195
|
+
const config = await sshConfig(ssh, target, { ...options.ssh, args: [...hostName, ...options.ssh.args] }, !!resolved.hostName);
|
|
196
|
+
user = config.user;
|
|
197
|
+
if (resolved.hostKeyAlias && config.read && !config.hostKeyAlias)
|
|
198
|
+
alias = ['-o', `HostKeyAlias=${resolved.hostKeyAlias}`];
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
user = { sshUser: null, sshUserSource: 'unknown' };
|
|
202
|
+
}
|
|
203
|
+
// Metadata never blocks or aborts a destination; earlier results are kept.
|
|
204
|
+
outcome = await remote(options, ssh, target, { canonical, options: [...hostName, ...alias] }, message, returnTo, budget);
|
|
205
|
+
}
|
|
206
|
+
// One destination keeps the existing flat local-host failure shape.
|
|
207
|
+
catch (error) {
|
|
208
|
+
outcome = failure(error, options.command, options.hosts.length === 1 ? hostname() : canonical !== target ? canonical : requestedHost);
|
|
209
|
+
}
|
|
210
|
+
results.push({ ...outcome.value, ...(options.hosts.length > 1 && canonical === target ? { host: requestedHost } : {}), sshHost: target, ...user,
|
|
211
|
+
...(options.jump ? { sshJump: options.jump.spec } : {}) });
|
|
212
|
+
exitCode = options.hosts.length === 1 ? outcome.exitCode : outcome.exitCode === 0 && exitCode === 0 ? 0 : 1;
|
|
213
|
+
}
|
|
214
|
+
return { value: results, exitCode };
|
|
215
|
+
}
|
package/dist/process.d.ts
CHANGED
|
@@ -12,6 +12,8 @@ export type Done = {
|
|
|
12
12
|
stdoutBytes?: Buffer;
|
|
13
13
|
stopReason?: StopReason;
|
|
14
14
|
};
|
|
15
|
+
export declare function enableCliSignalForwarding(): void;
|
|
16
|
+
export declare function stopCliChildren(): void;
|
|
15
17
|
export declare function run(binary: string, args: string[], options?: {
|
|
16
18
|
env?: NodeJS.ProcessEnv;
|
|
17
19
|
cwd?: string;
|