session-peer 0.3.6 → 0.4.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
@@ -1,4 +1,6 @@
1
1
  #!/usr/bin/env node
2
+ import { handoffCommand, handoffSend, prepareHandoff, privateMessage } from './handoff-operations.js';
3
+ import { canonicalId, closed, HANDOFF_LIMITS, HandoffBudget, parseStrictJson, parseWaitTimeout, safeInteger, systemClock } from './handoff.js';
2
4
  import { doctor } from './diagnostics.js';
3
5
  import { help } from './help.js';
4
6
  import { renderOutput } from './output.js';
@@ -13,8 +15,8 @@ import { envelope, host, reply, VERSION, VERSION_LINE } from './protocol.js';
13
15
  import { CHANNELS, checkUpdate, noticeText, refreshCache, refuseSelfUpdate, REFRESH_ARG, updateNotice, UpdateRefusal } from './updates.js';
14
16
  import { jumpOptions, sshConfig, sshJump, sshOptions } from './ssh.js';
15
17
  import { configuredHost, detectedHost, isSelf, probeReturnRoute, unsafeReturnHost, replyUri, returnHost, route, sender, tailnet } from './replies.js';
16
- const FLAGS = ['--json', '--all', '--dry-run', '--no-from', '--no-reply-to', '--no-update-notice', '--allow-inactive-codex-home', '--check-return-route', '--check'];
17
- 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'];
18
+ 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'];
19
+ 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'];
18
20
  // Repeated in order; every other value option is single.
19
21
  const REPEATED = ['--host', '--ssh-opt'];
20
22
  // Requested destinations, so a command-wide refusal can be attributed to each.
@@ -88,6 +90,24 @@ export function parse(args) {
88
90
  throw new Refusal('conflicting_output_options');
89
91
  if (!flags.has('--json') && !values.has('--output-format'))
90
92
  throw new Refusal('json_output_required');
93
+ const handoff = flags.has('--request-ack') || flags.has('--observe-delivery') || values.has('--correlation-id') || values.has('--wait-for') || values.has('--wait-timeout');
94
+ if (handoff) {
95
+ if (command !== 'send')
96
+ throw new Refusal('inapplicable_option');
97
+ if (values.has('--correlation-id') && !canonicalId(values.get('--correlation-id')))
98
+ throw new Refusal('invalid_correlation_id');
99
+ if (values.has('--wait-for') && !['delivered', 'acknowledged'].includes(values.get('--wait-for')))
100
+ throw new Refusal('invalid_wait_for');
101
+ if (values.has('--wait-timeout')) {
102
+ parseWaitTimeout(values.get('--wait-timeout'));
103
+ if (!values.has('--correlation-id') && !values.has('--wait-for') && !flags.has('--request-ack') && !flags.has('--observe-delivery'))
104
+ throw new Refusal('inapplicable_wait_timeout');
105
+ }
106
+ if (flags.has('--dry-run') && (flags.has('--request-ack') || flags.has('--observe-delivery') || values.has('--wait-for')))
107
+ throw new Refusal('incompatible_handoff_dry_run');
108
+ }
109
+ if (values.has('--message-file') && (command !== 'send' || values.has('--message')))
110
+ throw new Refusal('conflicting_message_sources');
91
111
  if (command === 'update') {
92
112
  if (values.has('--channel') && !CHANNELS.includes(values.get('--channel')))
93
113
  throw new Refusal('unsupported_update_channel');
@@ -143,6 +163,15 @@ export function parse(args) {
143
163
  values.set('--to', route.to);
144
164
  }
145
165
  }
166
+ if (handoff && hosts.length) {
167
+ if (hosts.length > HANDOFF_LIMITS.fanout)
168
+ throw new Refusal('handoff_fanout_too_large');
169
+ if (values.has('--correlation-id') && hosts.length > 1)
170
+ throw new Refusal('handoff_correlation_fanout_forbidden');
171
+ // Owned SSH descendant cleanup has only been qualified on POSIX origins.
172
+ if (process.platform === 'win32' || values.get('--remote-platform') === 'win32')
173
+ throw new Refusal('remote_handoff_unsupported', 1);
174
+ }
146
175
  if (command === 'send' && flags.has('--allow-inactive-codex-home')) {
147
176
  if (!values.get('--to').startsWith('codex:'))
148
177
  throw new Refusal('inapplicable_option');
@@ -201,21 +230,28 @@ export function parse(args) {
201
230
  }
202
231
  return { command, values, flags, hosts, ssh, ...(jump ? { jump } : {}), ...(address ? { address } : {}) };
203
232
  }
204
- async function input() {
233
+ async function input(limit = 4_100_000, preserveBOM = false, timeoutMs) {
205
234
  const chunks = [];
206
235
  let bytes = 0;
207
- for await (const chunk of process.stdin) {
208
- const part = Buffer.from(chunk);
209
- bytes += part.length;
210
- if (bytes > 4_100_000)
211
- throw new Refusal('input_too_large');
212
- chunks.push(part);
213
- }
236
+ const timer = timeoutMs === undefined ? undefined : setTimeout(() => process.stdin.destroy(new Refusal('deadline_before_effect', 1)), Math.max(1, timeoutMs));
214
237
  try {
215
- return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));
238
+ for await (const chunk of process.stdin) {
239
+ const part = Buffer.from(chunk);
240
+ bytes += part.length;
241
+ if (bytes > limit)
242
+ throw new Refusal('input_too_large');
243
+ chunks.push(part);
244
+ }
245
+ try {
246
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: preserveBOM }).decode(Buffer.concat(chunks));
247
+ }
248
+ catch {
249
+ throw new Refusal('invalid_utf8');
250
+ }
216
251
  }
217
- catch {
218
- throw new Refusal('invalid_utf8');
252
+ finally {
253
+ if (timer)
254
+ clearTimeout(timer);
219
255
  }
220
256
  }
221
257
  const quote = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
@@ -244,7 +280,7 @@ export function sshPreflightFailure(result, expected) {
244
280
  return 'ssh_preflight_failed';
245
281
  return undefined;
246
282
  }
247
- async function remote(options, ssh, target, resolved, message, returnTo) {
283
+ async function remote(options, ssh, target, resolved, message, returnTo, budget) {
248
284
  const { values, flags, command } = options;
249
285
  const binary = values.get('--remote-bin') ?? 'session-peer';
250
286
  const windows = values.get('--remote-platform') === 'win32';
@@ -262,7 +298,8 @@ async function remote(options, ssh, target, resolved, message, returnTo) {
262
298
  const base = ['-T', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'ConnectTimeout=10',
263
299
  ...(options.jump ? jumpOptions(ssh, options.jump) : []),
264
300
  ...(values.has('--ssh-control-path') ? ['-S', values.get('--ssh-control-path')] : []), ...resolved.options, ...options.ssh.args, '--', target];
265
- const preflight = await run(ssh, [...base, invoke('--version')], { timeout: 15000 });
301
+ budget?.beforeEffect();
302
+ const preflight = await run(ssh, [...base, invoke('--version')], { timeout: budget ? Math.max(1, Math.min(15000, budget.observationRemainingMs())) : 15000 });
266
303
  const preflightError = sshPreflightFailure(preflight, VERSION_LINE);
267
304
  if (preflightError)
268
305
  throw new Refusal(preflightError, 1);
@@ -281,15 +318,71 @@ async function remote(options, ssh, target, resolved, message, returnTo) {
281
318
  // The destination probes back to this machine; the request carries only the host.
282
319
  if (returnTo)
283
320
  args.push('--return-route-host', returnTo);
284
- const done = await run(ssh, [...base, invoke('--stdio-request')], {
285
- timeout: 90000, rawStdout: true, input: JSON.stringify({ schemaVersion: 1, args })
286
- });
321
+ const context = budget ? { correlationId: values.get('--correlation-id'), requestAck: flags.has('--request-ack'),
322
+ observeDelivery: flags.has('--observe-delivery'), waitFor: values.get('--wait-for') } : undefined;
323
+ if (context) {
324
+ for (const key of ['--correlation-id', '--wait-for', '--wait-timeout'])
325
+ if (values.has(key))
326
+ args.push(key, values.get(key));
327
+ for (const key of ['--request-ack', '--observe-delivery'])
328
+ if (flags.has(key))
329
+ args.push(key);
330
+ }
331
+ const execute = (requestArgs, preparation = false) => {
332
+ budget?.beforeEffect();
333
+ const remainingMs = budget ? Math.floor(budget.remainingMs()) : undefined;
334
+ if (remainingMs !== undefined && (remainingMs < 1 || remainingMs > 60000))
335
+ throw new Refusal('invalid_handoff_budget', 1);
336
+ return run(ssh, [...base, invoke(`--stdio-request${remainingMs === undefined ? '' : ` --handoff-remaining-ms=${remainingMs}`}`)], {
337
+ timeout: budget ? Math.max(1, budget.remainingMs() - 200) : 90000, rawStdout: true,
338
+ input: JSON.stringify({ schemaVersion: 1, args: requestArgs,
339
+ ...(remainingMs !== undefined ? { handoff: { schemaVersion: 1, remainingMs, ...(preparation ? { preparation: true } : {}) } } : {}) })
340
+ });
341
+ };
342
+ let prepared;
343
+ let destinationHost;
344
+ let boundTo = values.get('--to'), boundHome = values.get('--codex-home');
345
+ if (budget) {
346
+ // This round reserves a destination-owned intent and performs zero native
347
+ // submissions. An incomplete response is never replayed or guessed into send.
348
+ const preparation = await execute(args, true);
349
+ let checked;
350
+ try {
351
+ checked = responseOutcome(preparation, { command, to: boundTo, home: boundHome, dryRun: true,
352
+ allowInactive: flags.has('--allow-inactive-codex-home'), handoff: { ...context, preparation: true } });
353
+ }
354
+ catch {
355
+ throw new Refusal('remote_preparation_unverified', 1);
356
+ }
357
+ if (checked.value.ok === true && checked.exitCode !== 0)
358
+ throw new Refusal('remote_preparation_unverified', 1);
359
+ if (checked.exitCode !== 0 || checked.value.ok !== true)
360
+ return { value: { ...checked.value, host: resolved.canonical, sshHost: target }, exitCode: checked.exitCode || 1 };
361
+ const h = checked.value.handoff;
362
+ if (!h)
363
+ throw new Refusal('remote_preparation_unverified', 1);
364
+ prepared = { correlationId: h.correlationId, ledgerEpoch: h.ledgerEpoch, targetGeneration: h.targetGeneration };
365
+ destinationHost = checked.value.host;
366
+ const nativeTarget = checked.value.target;
367
+ boundTo = boundTo.startsWith('codex:') ? `codex:${nativeTarget.id}` : `claude:${nativeTarget.pid}`;
368
+ if (boundTo.startsWith('codex:'))
369
+ boundHome = checked.value.codexHome;
370
+ const replace = (key, value) => { const index = args.indexOf(key); if (index >= 0)
371
+ args[index + 1] = value;
372
+ else
373
+ args.push(key, value); };
374
+ replace('--to', boundTo);
375
+ replace('--correlation-id', h.correlationId);
376
+ if (boundHome !== undefined)
377
+ replace('--codex-home', boundHome);
378
+ }
379
+ const done = await execute(args);
287
380
  const uncertain = () => { if (command === 'send' && !flags.has('--dry-run') && done.spawned)
288
381
  throw new UnknownOutcome(); throw new Refusal('remote_response_unverified', 1); };
289
382
  let verified;
290
383
  try {
291
- verified = responseOutcome(done, { command, to: values.get('--to'), dryRun: flags.has('--dry-run'), returnTo,
292
- home: values.get('--codex-home'), allowInactive: flags.has('--allow-inactive-codex-home') });
384
+ verified = responseOutcome(done, { command, to: boundTo, dryRun: flags.has('--dry-run'), returnTo,
385
+ home: boundHome, allowInactive: flags.has('--allow-inactive-codex-home'), ...(context ? { handoff: { ...context, correlationId: prepared.correlationId, prepared, destinationHost } } : {}) });
293
386
  }
294
387
  catch {
295
388
  return uncertain();
@@ -311,13 +404,15 @@ function failure(error, command, where) {
311
404
  }
312
405
  // Destinations run in order, one attempt each. A failure or unknown outcome is
313
406
  // reported for that destination only; it is never retried or failed over.
314
- async function remotes(options, status, message, returnTo) {
407
+ async function remotes(options, status, message, returnTo, firstBudget) {
315
408
  const ssh = executable('ssh'), results = [];
316
409
  let exitCode = 0;
317
410
  for (const requestedHost of options.hosts) {
318
411
  const target = host(requestedHost);
319
412
  let outcome, user = {}, canonical = target;
320
413
  try {
414
+ const budget = firstBudget ? results.length === 0 ? firstBudget : new HandoffBudget(parseWaitTimeout(options.values.get('--wait-timeout') ?? '30')) : undefined;
415
+ budget?.beforeEffect();
321
416
  // A known offline or ambiguous tailnet peer is refused before any SSH process.
322
417
  const resolved = route(target, status);
323
418
  canonical = resolved.canonical;
@@ -336,7 +431,7 @@ async function remotes(options, status, message, returnTo) {
336
431
  user = { sshUser: null, sshUserSource: 'unknown' };
337
432
  }
338
433
  // Metadata never blocks or aborts a destination; earlier results are kept.
339
- outcome = await remote(options, ssh, target, { canonical, options: [...hostName, ...alias] }, message, returnTo);
434
+ outcome = await remote(options, ssh, target, { canonical, options: [...hostName, ...alias] }, message, returnTo, budget);
340
435
  }
341
436
  // One destination keeps the existing flat local-host failure shape.
342
437
  catch (error) {
@@ -351,6 +446,7 @@ async function remotes(options, status, message, returnTo) {
351
446
  let command = 'unknown';
352
447
  let format = 'json';
353
448
  let wire = false;
449
+ let wireWatchdog;
354
450
  try {
355
451
  const [major, minor] = process.versions.node.split('.').map(Number);
356
452
  if (!((major === 22 && minor >= 13) || major === 24))
@@ -363,25 +459,81 @@ try {
363
459
  else if (args.length === 1 && args[0] === '--version')
364
460
  console.log(VERSION_LINE);
365
461
  else if ((args.length === 1 && ['--help', '-h'].includes(args[0])) ||
366
- (args.length === 2 && ['list', 'send', 'doctor', 'update'].includes(args[0]) && ['--help', '-h'].includes(args[1])))
462
+ (args.length === 2 && ['list', 'send', 'doctor', 'update', 'handoff', 'ack'].includes(args[0]) && ['--help', '-h'].includes(args[1])))
367
463
  console.log(help(args.length === 2 ? args[0] : undefined));
464
+ else if (args[0] === 'handoff' || args[0] === 'ack') {
465
+ command = args[0];
466
+ const operation = await handoffCommand(args, limit => input(limit, true));
467
+ console.log(JSON.stringify({ schemaVersion: 1, host: hostname(), command, ok: operation.exitCode === 0, ...operation.value }));
468
+ process.exitCode = operation.exitCode;
469
+ }
368
470
  else {
369
- wire = args.length === 1 && args[0] === '--stdio-request';
471
+ wire = args[0] === '--stdio-request';
472
+ let wireContext;
473
+ let wireBudget;
474
+ let wireRemainingMs;
370
475
  if (wire) {
476
+ if (args.length !== 1) {
477
+ if (args.length !== 2 || !/^--handoff-remaining-ms=[1-9][0-9]{0,4}$/.test(args[1]))
478
+ throw new Refusal('invalid_remote_request');
479
+ wireRemainingMs = Number(args[1].slice('--handoff-remaining-ms='.length));
480
+ if (wireRemainingMs > 60000)
481
+ throw new Refusal('invalid_remote_request');
482
+ // Charge Node startup and imports before module execution. The same
483
+ // duration then covers input, preparation/effect and owned cleanup.
484
+ const wireStartedAt = systemClock.monotonic() - process.uptime() * 1000;
485
+ wireBudget = HandoffBudget.fromRemainingMs(wireRemainingMs, systemClock, wireStartedAt);
486
+ wireBudget.beforeEffect();
487
+ wireWatchdog = setTimeout(() => process.kill(process.pid, 'SIGTERM'), Math.max(1, wireBudget.remainingMs()));
488
+ }
371
489
  let request;
490
+ let raw;
372
491
  try {
373
- request = JSON.parse(await input());
492
+ raw = await input(4_100_000, false, wireBudget?.observationRemainingMs());
493
+ request = JSON.parse(raw);
374
494
  }
375
- catch {
495
+ catch (error) {
496
+ if (wireBudget && error instanceof Refusal && error.code === 'deadline_before_effect')
497
+ throw error;
376
498
  throw new Refusal('invalid_remote_request');
377
499
  }
378
500
  const record = request;
379
501
  if (!record || record.schemaVersion !== 1 || !Array.isArray(record.args) || record.args.some(a => typeof a !== 'string'))
380
502
  throw new Refusal('invalid_remote_request');
503
+ if (record.handoff !== undefined) {
504
+ try {
505
+ parseStrictJson(raw, { scope: 'outer', maxBytes: 4_100_000 });
506
+ closed(record, ['schemaVersion', 'args', 'handoff']);
507
+ const context = closed(record.handoff, ['schemaVersion', 'remainingMs'], ['preparation']);
508
+ if (context.schemaVersion !== 1 || !safeInteger(context.remainingMs) || context.remainingMs < 1 || context.remainingMs > 60000 ||
509
+ (context.preparation !== undefined && context.preparation !== true))
510
+ throw new Error('invalid');
511
+ wireContext = { remainingMs: context.remainingMs, ...(context.preparation ? { preparation: true } : {}) };
512
+ if (wireContext.remainingMs !== wireRemainingMs)
513
+ throw new Error('duration_mismatch');
514
+ }
515
+ catch {
516
+ throw new Refusal('invalid_remote_request');
517
+ }
518
+ }
381
519
  args = record.args;
382
520
  }
383
521
  command = ['list', 'send', 'doctor', 'update'].includes(args[0] ?? '') ? args[0] : 'unknown';
384
522
  const options = parse(args);
523
+ const handoffEnabled = 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');
524
+ if (wire && (handoffEnabled !== !!wireContext || handoffEnabled !== !!wireBudget))
525
+ throw new Refusal('remote_handoff_context_required', 1);
526
+ if (wireContext && (command !== 'send' || process.platform === 'win32'))
527
+ throw new Refusal('remote_handoff_unsupported', 1);
528
+ if (wireContext && wireContext.remainingMs > parseWaitTimeout(options.values.get('--wait-timeout') ?? '30') * 1000)
529
+ throw new Refusal('invalid_remote_request');
530
+ if (wireContext && !wireContext.preparation && !options.values.has('--correlation-id'))
531
+ throw new Refusal('remote_preparation_required', 1);
532
+ const handoffBudget = handoffEnabled ? wireContext ? wireBudget : new HandoffBudget(parseWaitTimeout(options.values.get('--wait-timeout') ?? '30')) : undefined;
533
+ if (wireContext && handoffBudget) {
534
+ handoffBudget.beforeEffect();
535
+ // The input-side watchdog remains installed; do not renew it here.
536
+ }
385
537
  format = !wire && options.values.get('--output-format') === 'text' ? 'text' : 'json';
386
538
  if (wire && options.values.get('--output-format') === 'text')
387
539
  throw new Refusal('remote_json_required');
@@ -398,15 +550,24 @@ try {
398
550
  queried = true;
399
551
  status = await tailnet();
400
552
  } return status; };
553
+ let rawMessage;
401
554
  let message, routing = {};
402
555
  if (command === 'send') {
403
- message = options.values.get('--message');
404
- if (message === undefined || message === '-') {
405
- if (wire)
406
- throw new Refusal('remote_message_required');
407
- message = await input();
556
+ if (options.values.has('--message-file')) {
557
+ // File contents are literal, including a single dash. Only the local
558
+ // command-line message source uses '-' as the stdin selector.
559
+ message = privateMessage(options.values.get('--message-file'));
560
+ }
561
+ else {
562
+ message = options.values.get('--message');
563
+ if (message === undefined || (!wire && message === '-')) {
564
+ if (wire)
565
+ throw new Refusal('remote_message_required');
566
+ message = await input(4_100_000, false, handoffBudget?.observationRemainingMs());
567
+ }
408
568
  }
409
569
  checkMessage(message);
570
+ rawMessage = message;
410
571
  const noFrom = options.flags.has('--no-from'), noReply = options.flags.has('--no-reply-to');
411
572
  if (options.address) {
412
573
  const resolution = { uri: options.address.uri, transport: options.address.transport };
@@ -472,9 +633,17 @@ try {
472
633
  let result = {}, exitCode, results;
473
634
  // Propagate the verified remote exit code so SSH and local refusals match.
474
635
  if (options.hosts.length)
475
- ({ value: results, exitCode } = await remotes(options, await tailnetStatus(), message, returnTo));
476
- else if (command === 'send')
477
- 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') });
636
+ ({ value: results, exitCode } = await remotes(options, await tailnetStatus(), message, returnTo, handoffBudget));
637
+ else if (command === 'send') {
638
+ 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') };
639
+ 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');
640
+ if (wireContext?.preparation)
641
+ ({ value: result, exitCode } = await prepareHandoff(settings, undefined, options.values.get('--correlation-id'), handoffBudget));
642
+ else if (enabled)
643
+ ({ value: result, exitCode } = await handoffSend(settings, { 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 }));
644
+ else
645
+ result = await send(settings);
646
+ }
478
647
  else if (command === 'update')
479
648
  result = options.flags.has('--check') ? await checkUpdate(options.values.get('--channel')) : refuseSelfUpdate(options.values.get('--channel'));
480
649
  else if (command === 'doctor') {
@@ -497,7 +666,7 @@ try {
497
666
  // Without a return host there is nothing to probe from the destination.
498
667
  if (command === 'doctor' && options.flags.has('--check-return-route') && !returnTo)
499
668
  results = results?.map(item => item.ok === false ? item : ({ ...item, returnRoute: { status: 'failed', transport: 'ssh', host: null, reason: 'return_host_unavailable' } }));
500
- const shape = (item) => ({ schemaVersion: 1, host: hostname(), command, ok: item.ok !== false, version: VERSION, referenceVersion: '1.0.2', ...item });
669
+ const shape = (item) => ({ schemaVersion: 1, host: hostname(), command, ok: item.ok !== false, version: VERSION, referenceVersion: '1.1.0', ...item });
501
670
  // Cached advisory notice, computed once per invocation by this client and never
502
671
  // in wire mode. JSON: additive `clientUpdate` on a flat (single-result) object
503
672
  // only; a repeated --host array keeps its exact element shape. Text: one stderr line.
@@ -512,7 +681,18 @@ try {
512
681
  }
513
682
  catch (error) {
514
683
  // A command-wide refusal before dispatch applies to every requested host.
515
- const { value, exitCode } = failure(error, command, hostname());
516
- console.log(renderOutput(!wire && requested.length > 1 ? requested.map(item => ({ ...value, host: item })) : value, format));
517
- process.exitCode = exitCode;
684
+ if (command === 'handoff' || command === 'ack') {
685
+ const failureCode = error instanceof Refusal ? error.code : 'handoff_operation_failed';
686
+ console.log(JSON.stringify({ schemaVersion: 1, host: hostname(), command, ok: false, error: failureCode }));
687
+ process.exitCode = error instanceof Refusal ? error.exitCode : 1;
688
+ }
689
+ else {
690
+ const { value, exitCode } = failure(error, command, hostname());
691
+ console.log(renderOutput(!wire && requested.length > 1 ? requested.map(item => ({ ...value, host: item })) : value, format));
692
+ process.exitCode = exitCode;
693
+ }
694
+ }
695
+ finally {
696
+ if (wireWatchdog)
697
+ clearTimeout(wireWatchdog);
518
698
  }
@@ -0,0 +1,103 @@
1
+ import type { MetadataQualification } from './metadata-observation.js';
2
+ import { HandoffBudget, type Clock, type Handoff, type WaitFor, type WaitReason, type WaitStatus } from './handoff.js';
3
+ export type HandoffBinding = Readonly<{
4
+ agent: 'claude' | 'codex';
5
+ destination: string;
6
+ target: string;
7
+ home?: string;
8
+ writerIdentity?: string;
9
+ generation: string | null;
10
+ payloadDigest: string;
11
+ }>;
12
+ export type PrepareOptions = {
13
+ correlationId?: string;
14
+ requestAck?: boolean;
15
+ observeDelivery?: boolean;
16
+ waitFor?: WaitFor;
17
+ budget?: HandoffBudget;
18
+ dryRun?: boolean;
19
+ channels?: {
20
+ delivery: boolean;
21
+ receipt?: boolean;
22
+ };
23
+ observationSupported?: boolean;
24
+ clientUserMessageId?: string;
25
+ observationQualification?: MetadataQualification;
26
+ };
27
+ export type ObservationContext = Readonly<{
28
+ binding: HandoffBinding;
29
+ clientUserMessageId: string;
30
+ qualification: MetadataQualification;
31
+ }>;
32
+ export type HandoffObservation = {
33
+ clientUserMessageId: string;
34
+ injectionObserved: boolean;
35
+ turn?: Handoff['observation']['turn'];
36
+ };
37
+ export type HandoffQueryError = {
38
+ schemaVersion: 1;
39
+ correlationId: string;
40
+ status: 'unknown';
41
+ context: 'ledger_missing' | 'ledger_corrupt' | 'id_unknown';
42
+ retry: {
43
+ allowed: false;
44
+ reason: 'history_unavailable';
45
+ };
46
+ };
47
+ export type HandoffStatus = {
48
+ handoff: Handoff;
49
+ } | {
50
+ reason: 'handoff_history_unavailable';
51
+ handoffQuery: HandoffQueryError;
52
+ };
53
+ export declare const payloadDigest: (payload: string | Uint8Array) => string;
54
+ export declare class HandoffLedger {
55
+ readonly path: string;
56
+ private readonly clock;
57
+ private readonly clockId;
58
+ constructor(path: string, options?: {
59
+ clock?: Clock;
60
+ });
61
+ private filename;
62
+ private key;
63
+ private protectDigest;
64
+ private revealDigest;
65
+ private lock;
66
+ private read;
67
+ private write;
68
+ init(): {
69
+ ledgerEpoch: string;
70
+ storage: 'private_posix';
71
+ cloneRollbackProtection: 'intact_retained_history_only';
72
+ };
73
+ private usable;
74
+ private snapshot;
75
+ status(id: string): HandoffStatus;
76
+ private selectWait;
77
+ private operationSnapshot;
78
+ operationStatus(id: string, operationId: string): Handoff;
79
+ observationContext(id: string): ObservationContext | undefined;
80
+ prepare(binding: HandoffBinding, options?: PrepareOptions): Handoff;
81
+ private configure;
82
+ commitEffect(id: string, binding: HandoffBinding, budget?: HandoffBudget): Handoff;
83
+ private refuse;
84
+ refusePrepared(id: string, binding: HandoffBinding, reason?: WaitReason): Handoff;
85
+ recordSubmission(id: string, status: 'submitted' | 'unknown' | 'refused'): Handoff;
86
+ recordObservation(id: string, observation: HandoffObservation, originalBinding: HandoffBinding): Handoff;
87
+ recordObservationFailure(id: string, originalBinding: HandoffBinding, status: 'unsupported' | 'failed', operationId?: string): Handoff;
88
+ private addWait;
89
+ beginWait(id: string, goal: Exclude<WaitFor, 'none'>, budget?: HandoffBudget, options?: {
90
+ observationSupported?: boolean;
91
+ }): Handoff;
92
+ recordWait(id: string, status: Exclude<WaitStatus, 'pending' | 'not_requested'>, reason?: WaitReason, operationId?: string): Handoff;
93
+ private commitAck;
94
+ confirm(raw: string | Uint8Array): Handoff;
95
+ mintCapability(id: string, bootstrap: {
96
+ privateConsumerValidated: true;
97
+ compatibleProducerValidated: true;
98
+ }): string;
99
+ acceptReceipt(raw: string | Uint8Array): Handoff;
100
+ revoke(id: string): void;
101
+ quarantine(): void;
102
+ prune(): void;
103
+ }