session-peer 0.3.6 → 0.5.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/CONTRIBUTING.md +6 -4
- package/PARITY.md +431 -6
- package/README.ja.md +14 -8
- package/README.ko.md +14 -8
- package/README.md +14 -8
- package/README.zh-CN.md +14 -8
- package/RELEASING.md +109 -0
- package/VALIDATION.md +806 -1
- package/dist/app-server.d.ts +207 -0
- package/dist/app-server.js +1044 -0
- package/dist/cli.js +229 -39
- package/dist/handoff-ledger.d.ts +103 -0
- package/dist/handoff-ledger.js +791 -0
- package/dist/handoff-observer-probe.d.ts +1 -0
- package/dist/handoff-observer-probe.js +170 -0
- package/dist/handoff-operations.d.ts +29 -0
- package/dist/handoff-operations.js +496 -0
- package/dist/handoff-writer-probe.d.ts +1 -0
- package/dist/handoff-writer-probe.js +146 -0
- package/dist/handoff.d.ts +112 -0
- package/dist/handoff.js +261 -0
- package/dist/help.js +18 -0
- package/dist/linux-native-probe.d.ts +1 -0
- package/dist/linux-native-probe.js +51 -0
- package/dist/linux-proc.d.ts +55 -0
- package/dist/linux-proc.js +150 -0
- package/dist/metadata-observation.d.ts +49 -0
- package/dist/metadata-observation.js +250 -0
- package/dist/native-profiles.d.ts +25 -0
- package/dist/native-profiles.js +62 -0
- package/dist/output.js +7 -1
- package/dist/process.d.ts +28 -0
- package/dist/process.js +284 -2
- package/dist/protocol.d.ts +2 -2
- package/dist/protocol.js +1 -1
- package/dist/send.d.ts +18 -1
- package/dist/send.js +91 -6
- package/dist/skill-metadata.js +7 -4
- package/dist/ssh-response.d.ts +11 -0
- package/dist/ssh-response.js +78 -2
- package/dist/ssh.d.ts +2 -1
- package/dist/ssh.js +37 -2
- package/dist/windows.d.ts +28 -0
- package/dist/windows.js +149 -1
- package/docs/api.md +255 -4
- package/docs/design/typescript-skill-compatibility.md +55 -2
- package/docs/guide.ja.md +36 -16
- package/docs/guide.ko.md +39 -19
- package/docs/guide.md +46 -20
- package/docs/guide.zh-CN.md +36 -16
- package/docs/shorthand.md +1 -1
- package/package.json +2 -2
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');
|
|
@@ -175,7 +204,17 @@ export function parse(args) {
|
|
|
175
204
|
// An existing control master would bypass the hop entirely.
|
|
176
205
|
if (values.has('--ssh-control-path'))
|
|
177
206
|
throw new Refusal('conflicting_ssh_jump');
|
|
178
|
-
// Win32-OpenSSH starts ProxyCommand without a POSIX shell
|
|
207
|
+
// Win32-OpenSSH starts ProxyCommand without a POSIX shell. windowsProxyCommand's
|
|
208
|
+
// quoting matched an isolated no-connection 9.5p1 probe; a connected hop and
|
|
209
|
+
// cleanup are unverified. Enabling also needs: an analysis of real ssh.exe not
|
|
210
|
+
// exiting with pipe stdin in a non-interactive session (run() uses pipe stdin);
|
|
211
|
+
// the same absolute, resolved ssh.exe from executable() as the outer binary and
|
|
212
|
+
// the ProxyCommand program; owned-process-tree cleanup on Windows: run() kills
|
|
213
|
+
// only the direct child, so a ProxyCommand ssh.exe may outlive a timeout, an
|
|
214
|
+
// overflow or an interrupt (#131 keeps tree cleanup as an unselected candidate
|
|
215
|
+
// backend, whose native tests use a PowerShell -> PING stand-in, never this
|
|
216
|
+
// ssh.exe -> ProxyCommand ssh.exe shape); any such stop stays an unknown effect
|
|
217
|
+
// with no resend; and the builder called here, before ssh -G.
|
|
179
218
|
if (process.platform === 'win32')
|
|
180
219
|
throw new Refusal('ssh_jump_unsupported_platform');
|
|
181
220
|
}
|
|
@@ -201,21 +240,28 @@ export function parse(args) {
|
|
|
201
240
|
}
|
|
202
241
|
return { command, values, flags, hosts, ssh, ...(jump ? { jump } : {}), ...(address ? { address } : {}) };
|
|
203
242
|
}
|
|
204
|
-
async function input() {
|
|
243
|
+
async function input(limit = 4_100_000, preserveBOM = false, timeoutMs) {
|
|
205
244
|
const chunks = [];
|
|
206
245
|
let bytes = 0;
|
|
207
|
-
|
|
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
|
-
}
|
|
246
|
+
const timer = timeoutMs === undefined ? undefined : setTimeout(() => process.stdin.destroy(new Refusal('deadline_before_effect', 1)), Math.max(1, timeoutMs));
|
|
214
247
|
try {
|
|
215
|
-
|
|
248
|
+
for await (const chunk of process.stdin) {
|
|
249
|
+
const part = Buffer.from(chunk);
|
|
250
|
+
bytes += part.length;
|
|
251
|
+
if (bytes > limit)
|
|
252
|
+
throw new Refusal('input_too_large');
|
|
253
|
+
chunks.push(part);
|
|
254
|
+
}
|
|
255
|
+
try {
|
|
256
|
+
return new TextDecoder('utf-8', { fatal: true, ignoreBOM: preserveBOM }).decode(Buffer.concat(chunks));
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
throw new Refusal('invalid_utf8');
|
|
260
|
+
}
|
|
216
261
|
}
|
|
217
|
-
|
|
218
|
-
|
|
262
|
+
finally {
|
|
263
|
+
if (timer)
|
|
264
|
+
clearTimeout(timer);
|
|
219
265
|
}
|
|
220
266
|
}
|
|
221
267
|
const quote = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
|
|
@@ -244,7 +290,7 @@ export function sshPreflightFailure(result, expected) {
|
|
|
244
290
|
return 'ssh_preflight_failed';
|
|
245
291
|
return undefined;
|
|
246
292
|
}
|
|
247
|
-
async function remote(options, ssh, target, resolved, message, returnTo) {
|
|
293
|
+
async function remote(options, ssh, target, resolved, message, returnTo, budget) {
|
|
248
294
|
const { values, flags, command } = options;
|
|
249
295
|
const binary = values.get('--remote-bin') ?? 'session-peer';
|
|
250
296
|
const windows = values.get('--remote-platform') === 'win32';
|
|
@@ -262,7 +308,8 @@ async function remote(options, ssh, target, resolved, message, returnTo) {
|
|
|
262
308
|
const base = ['-T', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'ConnectTimeout=10',
|
|
263
309
|
...(options.jump ? jumpOptions(ssh, options.jump) : []),
|
|
264
310
|
...(values.has('--ssh-control-path') ? ['-S', values.get('--ssh-control-path')] : []), ...resolved.options, ...options.ssh.args, '--', target];
|
|
265
|
-
|
|
311
|
+
budget?.beforeEffect();
|
|
312
|
+
const preflight = await run(ssh, [...base, invoke('--version')], { timeout: budget ? Math.max(1, Math.min(15000, budget.observationRemainingMs())) : 15000 });
|
|
266
313
|
const preflightError = sshPreflightFailure(preflight, VERSION_LINE);
|
|
267
314
|
if (preflightError)
|
|
268
315
|
throw new Refusal(preflightError, 1);
|
|
@@ -281,15 +328,71 @@ async function remote(options, ssh, target, resolved, message, returnTo) {
|
|
|
281
328
|
// The destination probes back to this machine; the request carries only the host.
|
|
282
329
|
if (returnTo)
|
|
283
330
|
args.push('--return-route-host', returnTo);
|
|
284
|
-
const
|
|
285
|
-
|
|
286
|
-
|
|
331
|
+
const context = budget ? { correlationId: values.get('--correlation-id'), requestAck: flags.has('--request-ack'),
|
|
332
|
+
observeDelivery: flags.has('--observe-delivery'), waitFor: values.get('--wait-for') } : undefined;
|
|
333
|
+
if (context) {
|
|
334
|
+
for (const key of ['--correlation-id', '--wait-for', '--wait-timeout'])
|
|
335
|
+
if (values.has(key))
|
|
336
|
+
args.push(key, values.get(key));
|
|
337
|
+
for (const key of ['--request-ack', '--observe-delivery'])
|
|
338
|
+
if (flags.has(key))
|
|
339
|
+
args.push(key);
|
|
340
|
+
}
|
|
341
|
+
const execute = (requestArgs, preparation = false) => {
|
|
342
|
+
budget?.beforeEffect();
|
|
343
|
+
const remainingMs = budget ? Math.floor(budget.remainingMs()) : undefined;
|
|
344
|
+
if (remainingMs !== undefined && (remainingMs < 1 || remainingMs > 60000))
|
|
345
|
+
throw new Refusal('invalid_handoff_budget', 1);
|
|
346
|
+
return run(ssh, [...base, invoke(`--stdio-request${remainingMs === undefined ? '' : ` --handoff-remaining-ms=${remainingMs}`}`)], {
|
|
347
|
+
timeout: budget ? Math.max(1, budget.remainingMs() - 200) : 90000, rawStdout: true,
|
|
348
|
+
input: JSON.stringify({ schemaVersion: 1, args: requestArgs,
|
|
349
|
+
...(remainingMs !== undefined ? { handoff: { schemaVersion: 1, remainingMs, ...(preparation ? { preparation: true } : {}) } } : {}) })
|
|
350
|
+
});
|
|
351
|
+
};
|
|
352
|
+
let prepared;
|
|
353
|
+
let destinationHost;
|
|
354
|
+
let boundTo = values.get('--to'), boundHome = values.get('--codex-home');
|
|
355
|
+
if (budget) {
|
|
356
|
+
// This round reserves a destination-owned intent and performs zero native
|
|
357
|
+
// submissions. An incomplete response is never replayed or guessed into send.
|
|
358
|
+
const preparation = await execute(args, true);
|
|
359
|
+
let checked;
|
|
360
|
+
try {
|
|
361
|
+
checked = responseOutcome(preparation, { command, to: boundTo, home: boundHome, dryRun: true,
|
|
362
|
+
allowInactive: flags.has('--allow-inactive-codex-home'), handoff: { ...context, preparation: true } });
|
|
363
|
+
}
|
|
364
|
+
catch {
|
|
365
|
+
throw new Refusal('remote_preparation_unverified', 1);
|
|
366
|
+
}
|
|
367
|
+
if (checked.value.ok === true && checked.exitCode !== 0)
|
|
368
|
+
throw new Refusal('remote_preparation_unverified', 1);
|
|
369
|
+
if (checked.exitCode !== 0 || checked.value.ok !== true)
|
|
370
|
+
return { value: { ...checked.value, host: resolved.canonical, sshHost: target }, exitCode: checked.exitCode || 1 };
|
|
371
|
+
const h = checked.value.handoff;
|
|
372
|
+
if (!h)
|
|
373
|
+
throw new Refusal('remote_preparation_unverified', 1);
|
|
374
|
+
prepared = { correlationId: h.correlationId, ledgerEpoch: h.ledgerEpoch, targetGeneration: h.targetGeneration };
|
|
375
|
+
destinationHost = checked.value.host;
|
|
376
|
+
const nativeTarget = checked.value.target;
|
|
377
|
+
boundTo = boundTo.startsWith('codex:') ? `codex:${nativeTarget.id}` : `claude:${nativeTarget.pid}`;
|
|
378
|
+
if (boundTo.startsWith('codex:'))
|
|
379
|
+
boundHome = checked.value.codexHome;
|
|
380
|
+
const replace = (key, value) => { const index = args.indexOf(key); if (index >= 0)
|
|
381
|
+
args[index + 1] = value;
|
|
382
|
+
else
|
|
383
|
+
args.push(key, value); };
|
|
384
|
+
replace('--to', boundTo);
|
|
385
|
+
replace('--correlation-id', h.correlationId);
|
|
386
|
+
if (boundHome !== undefined)
|
|
387
|
+
replace('--codex-home', boundHome);
|
|
388
|
+
}
|
|
389
|
+
const done = await execute(args);
|
|
287
390
|
const uncertain = () => { if (command === 'send' && !flags.has('--dry-run') && done.spawned)
|
|
288
391
|
throw new UnknownOutcome(); throw new Refusal('remote_response_unverified', 1); };
|
|
289
392
|
let verified;
|
|
290
393
|
try {
|
|
291
|
-
verified = responseOutcome(done, { command, to:
|
|
292
|
-
home:
|
|
394
|
+
verified = responseOutcome(done, { command, to: boundTo, dryRun: flags.has('--dry-run'), returnTo,
|
|
395
|
+
home: boundHome, allowInactive: flags.has('--allow-inactive-codex-home'), ...(context ? { handoff: { ...context, correlationId: prepared.correlationId, prepared, destinationHost } } : {}) });
|
|
293
396
|
}
|
|
294
397
|
catch {
|
|
295
398
|
return uncertain();
|
|
@@ -311,13 +414,15 @@ function failure(error, command, where) {
|
|
|
311
414
|
}
|
|
312
415
|
// Destinations run in order, one attempt each. A failure or unknown outcome is
|
|
313
416
|
// reported for that destination only; it is never retried or failed over.
|
|
314
|
-
async function remotes(options, status, message, returnTo) {
|
|
417
|
+
async function remotes(options, status, message, returnTo, firstBudget) {
|
|
315
418
|
const ssh = executable('ssh'), results = [];
|
|
316
419
|
let exitCode = 0;
|
|
317
420
|
for (const requestedHost of options.hosts) {
|
|
318
421
|
const target = host(requestedHost);
|
|
319
422
|
let outcome, user = {}, canonical = target;
|
|
320
423
|
try {
|
|
424
|
+
const budget = firstBudget ? results.length === 0 ? firstBudget : new HandoffBudget(parseWaitTimeout(options.values.get('--wait-timeout') ?? '30')) : undefined;
|
|
425
|
+
budget?.beforeEffect();
|
|
321
426
|
// A known offline or ambiguous tailnet peer is refused before any SSH process.
|
|
322
427
|
const resolved = route(target, status);
|
|
323
428
|
canonical = resolved.canonical;
|
|
@@ -336,7 +441,7 @@ async function remotes(options, status, message, returnTo) {
|
|
|
336
441
|
user = { sshUser: null, sshUserSource: 'unknown' };
|
|
337
442
|
}
|
|
338
443
|
// Metadata never blocks or aborts a destination; earlier results are kept.
|
|
339
|
-
outcome = await remote(options, ssh, target, { canonical, options: [...hostName, ...alias] }, message, returnTo);
|
|
444
|
+
outcome = await remote(options, ssh, target, { canonical, options: [...hostName, ...alias] }, message, returnTo, budget);
|
|
340
445
|
}
|
|
341
446
|
// One destination keeps the existing flat local-host failure shape.
|
|
342
447
|
catch (error) {
|
|
@@ -351,6 +456,7 @@ async function remotes(options, status, message, returnTo) {
|
|
|
351
456
|
let command = 'unknown';
|
|
352
457
|
let format = 'json';
|
|
353
458
|
let wire = false;
|
|
459
|
+
let wireWatchdog;
|
|
354
460
|
try {
|
|
355
461
|
const [major, minor] = process.versions.node.split('.').map(Number);
|
|
356
462
|
if (!((major === 22 && minor >= 13) || major === 24))
|
|
@@ -363,25 +469,81 @@ try {
|
|
|
363
469
|
else if (args.length === 1 && args[0] === '--version')
|
|
364
470
|
console.log(VERSION_LINE);
|
|
365
471
|
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])))
|
|
472
|
+
(args.length === 2 && ['list', 'send', 'doctor', 'update', 'handoff', 'ack'].includes(args[0]) && ['--help', '-h'].includes(args[1])))
|
|
367
473
|
console.log(help(args.length === 2 ? args[0] : undefined));
|
|
474
|
+
else if (args[0] === 'handoff' || args[0] === 'ack') {
|
|
475
|
+
command = args[0];
|
|
476
|
+
const operation = await handoffCommand(args, limit => input(limit, true));
|
|
477
|
+
console.log(JSON.stringify({ schemaVersion: 1, host: hostname(), command, ok: operation.exitCode === 0, ...operation.value }));
|
|
478
|
+
process.exitCode = operation.exitCode;
|
|
479
|
+
}
|
|
368
480
|
else {
|
|
369
|
-
wire = args
|
|
481
|
+
wire = args[0] === '--stdio-request';
|
|
482
|
+
let wireContext;
|
|
483
|
+
let wireBudget;
|
|
484
|
+
let wireRemainingMs;
|
|
370
485
|
if (wire) {
|
|
486
|
+
if (args.length !== 1) {
|
|
487
|
+
if (args.length !== 2 || !/^--handoff-remaining-ms=[1-9][0-9]{0,4}$/.test(args[1]))
|
|
488
|
+
throw new Refusal('invalid_remote_request');
|
|
489
|
+
wireRemainingMs = Number(args[1].slice('--handoff-remaining-ms='.length));
|
|
490
|
+
if (wireRemainingMs > 60000)
|
|
491
|
+
throw new Refusal('invalid_remote_request');
|
|
492
|
+
// Charge Node startup and imports before module execution. The same
|
|
493
|
+
// duration then covers input, preparation/effect and owned cleanup.
|
|
494
|
+
const wireStartedAt = systemClock.monotonic() - process.uptime() * 1000;
|
|
495
|
+
wireBudget = HandoffBudget.fromRemainingMs(wireRemainingMs, systemClock, wireStartedAt);
|
|
496
|
+
wireBudget.beforeEffect();
|
|
497
|
+
wireWatchdog = setTimeout(() => process.kill(process.pid, 'SIGTERM'), Math.max(1, wireBudget.remainingMs()));
|
|
498
|
+
}
|
|
371
499
|
let request;
|
|
500
|
+
let raw;
|
|
372
501
|
try {
|
|
373
|
-
|
|
502
|
+
raw = await input(4_100_000, false, wireBudget?.observationRemainingMs());
|
|
503
|
+
request = JSON.parse(raw);
|
|
374
504
|
}
|
|
375
|
-
catch {
|
|
505
|
+
catch (error) {
|
|
506
|
+
if (wireBudget && error instanceof Refusal && error.code === 'deadline_before_effect')
|
|
507
|
+
throw error;
|
|
376
508
|
throw new Refusal('invalid_remote_request');
|
|
377
509
|
}
|
|
378
510
|
const record = request;
|
|
379
511
|
if (!record || record.schemaVersion !== 1 || !Array.isArray(record.args) || record.args.some(a => typeof a !== 'string'))
|
|
380
512
|
throw new Refusal('invalid_remote_request');
|
|
513
|
+
if (record.handoff !== undefined) {
|
|
514
|
+
try {
|
|
515
|
+
parseStrictJson(raw, { scope: 'outer', maxBytes: 4_100_000 });
|
|
516
|
+
closed(record, ['schemaVersion', 'args', 'handoff']);
|
|
517
|
+
const context = closed(record.handoff, ['schemaVersion', 'remainingMs'], ['preparation']);
|
|
518
|
+
if (context.schemaVersion !== 1 || !safeInteger(context.remainingMs) || context.remainingMs < 1 || context.remainingMs > 60000 ||
|
|
519
|
+
(context.preparation !== undefined && context.preparation !== true))
|
|
520
|
+
throw new Error('invalid');
|
|
521
|
+
wireContext = { remainingMs: context.remainingMs, ...(context.preparation ? { preparation: true } : {}) };
|
|
522
|
+
if (wireContext.remainingMs !== wireRemainingMs)
|
|
523
|
+
throw new Error('duration_mismatch');
|
|
524
|
+
}
|
|
525
|
+
catch {
|
|
526
|
+
throw new Refusal('invalid_remote_request');
|
|
527
|
+
}
|
|
528
|
+
}
|
|
381
529
|
args = record.args;
|
|
382
530
|
}
|
|
383
531
|
command = ['list', 'send', 'doctor', 'update'].includes(args[0] ?? '') ? args[0] : 'unknown';
|
|
384
532
|
const options = parse(args);
|
|
533
|
+
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');
|
|
534
|
+
if (wire && (handoffEnabled !== !!wireContext || handoffEnabled !== !!wireBudget))
|
|
535
|
+
throw new Refusal('remote_handoff_context_required', 1);
|
|
536
|
+
if (wireContext && (command !== 'send' || process.platform === 'win32'))
|
|
537
|
+
throw new Refusal('remote_handoff_unsupported', 1);
|
|
538
|
+
if (wireContext && wireContext.remainingMs > parseWaitTimeout(options.values.get('--wait-timeout') ?? '30') * 1000)
|
|
539
|
+
throw new Refusal('invalid_remote_request');
|
|
540
|
+
if (wireContext && !wireContext.preparation && !options.values.has('--correlation-id'))
|
|
541
|
+
throw new Refusal('remote_preparation_required', 1);
|
|
542
|
+
const handoffBudget = handoffEnabled ? wireContext ? wireBudget : new HandoffBudget(parseWaitTimeout(options.values.get('--wait-timeout') ?? '30')) : undefined;
|
|
543
|
+
if (wireContext && handoffBudget) {
|
|
544
|
+
handoffBudget.beforeEffect();
|
|
545
|
+
// The input-side watchdog remains installed; do not renew it here.
|
|
546
|
+
}
|
|
385
547
|
format = !wire && options.values.get('--output-format') === 'text' ? 'text' : 'json';
|
|
386
548
|
if (wire && options.values.get('--output-format') === 'text')
|
|
387
549
|
throw new Refusal('remote_json_required');
|
|
@@ -398,15 +560,24 @@ try {
|
|
|
398
560
|
queried = true;
|
|
399
561
|
status = await tailnet();
|
|
400
562
|
} return status; };
|
|
563
|
+
let rawMessage;
|
|
401
564
|
let message, routing = {};
|
|
402
565
|
if (command === 'send') {
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
566
|
+
if (options.values.has('--message-file')) {
|
|
567
|
+
// File contents are literal, including a single dash. Only the local
|
|
568
|
+
// command-line message source uses '-' as the stdin selector.
|
|
569
|
+
message = privateMessage(options.values.get('--message-file'));
|
|
570
|
+
}
|
|
571
|
+
else {
|
|
572
|
+
message = options.values.get('--message');
|
|
573
|
+
if (message === undefined || (!wire && message === '-')) {
|
|
574
|
+
if (wire)
|
|
575
|
+
throw new Refusal('remote_message_required');
|
|
576
|
+
message = await input(4_100_000, false, handoffBudget?.observationRemainingMs());
|
|
577
|
+
}
|
|
408
578
|
}
|
|
409
579
|
checkMessage(message);
|
|
580
|
+
rawMessage = message;
|
|
410
581
|
const noFrom = options.flags.has('--no-from'), noReply = options.flags.has('--no-reply-to');
|
|
411
582
|
if (options.address) {
|
|
412
583
|
const resolution = { uri: options.address.uri, transport: options.address.transport };
|
|
@@ -472,9 +643,17 @@ try {
|
|
|
472
643
|
let result = {}, exitCode, results;
|
|
473
644
|
// Propagate the verified remote exit code so SSH and local refusals match.
|
|
474
645
|
if (options.hosts.length)
|
|
475
|
-
({ value: results, exitCode } = await remotes(options, await tailnetStatus(), message, returnTo));
|
|
476
|
-
else if (command === 'send')
|
|
477
|
-
|
|
646
|
+
({ value: results, exitCode } = await remotes(options, await tailnetStatus(), message, returnTo, handoffBudget));
|
|
647
|
+
else if (command === 'send') {
|
|
648
|
+
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') };
|
|
649
|
+
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');
|
|
650
|
+
if (wireContext?.preparation)
|
|
651
|
+
({ value: result, exitCode } = await prepareHandoff(settings, undefined, options.values.get('--correlation-id'), handoffBudget));
|
|
652
|
+
else if (enabled)
|
|
653
|
+
({ 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 }));
|
|
654
|
+
else
|
|
655
|
+
result = await send(settings);
|
|
656
|
+
}
|
|
478
657
|
else if (command === 'update')
|
|
479
658
|
result = options.flags.has('--check') ? await checkUpdate(options.values.get('--channel')) : refuseSelfUpdate(options.values.get('--channel'));
|
|
480
659
|
else if (command === 'doctor') {
|
|
@@ -497,7 +676,7 @@ try {
|
|
|
497
676
|
// Without a return host there is nothing to probe from the destination.
|
|
498
677
|
if (command === 'doctor' && options.flags.has('--check-return-route') && !returnTo)
|
|
499
678
|
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
|
|
679
|
+
const shape = (item) => ({ schemaVersion: 1, host: hostname(), command, ok: item.ok !== false, version: VERSION, referenceVersion: '1.1.0', ...item });
|
|
501
680
|
// Cached advisory notice, computed once per invocation by this client and never
|
|
502
681
|
// in wire mode. JSON: additive `clientUpdate` on a flat (single-result) object
|
|
503
682
|
// only; a repeated --host array keeps its exact element shape. Text: one stderr line.
|
|
@@ -512,7 +691,18 @@ try {
|
|
|
512
691
|
}
|
|
513
692
|
catch (error) {
|
|
514
693
|
// A command-wide refusal before dispatch applies to every requested host.
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
694
|
+
if (command === 'handoff' || command === 'ack') {
|
|
695
|
+
const failureCode = error instanceof Refusal ? error.code : 'handoff_operation_failed';
|
|
696
|
+
console.log(JSON.stringify({ schemaVersion: 1, host: hostname(), command, ok: false, error: failureCode }));
|
|
697
|
+
process.exitCode = error instanceof Refusal ? error.exitCode : 1;
|
|
698
|
+
}
|
|
699
|
+
else {
|
|
700
|
+
const { value, exitCode } = failure(error, command, hostname());
|
|
701
|
+
console.log(renderOutput(!wire && requested.length > 1 ? requested.map(item => ({ ...value, host: item })) : value, format));
|
|
702
|
+
process.exitCode = exitCode;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
finally {
|
|
706
|
+
if (wireWatchdog)
|
|
707
|
+
clearTimeout(wireWatchdog);
|
|
518
708
|
}
|
|
@@ -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
|
+
}
|