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.
@@ -0,0 +1,471 @@
1
+ // Opt-in integration only. Default CLI imports this without opening storage or
2
+ // starting an observer/collector. Production receipt bootstrap is unqualified.
3
+ import { homedir, hostname } from 'node:os';
4
+ import { dirname, isAbsolute, join, parse, resolve } from 'node:path';
5
+ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readSync, realpathSync } from 'node:fs';
6
+ import { HandoffLedger, payloadDigest } from './handoff-ledger.js';
7
+ import { canonicalId, HANDOFF_LIMITS, HandoffBudget, parseWaitTimeout } from './handoff.js';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { nativeQueueCapability, nativeQueueOnce, AppServerFault } from './app-server.js';
10
+ import { metadataCapability, observeMetadata, resumeMetadataObservation, metadataQualification } from './metadata-observation.js';
11
+ import { checkMessage, queueId, send } from './send.js';
12
+ import { Refusal } from './discovery.js';
13
+ import { HomeRefusal } from './writer.js';
14
+ import { executable, run, UnknownOutcome } from './process.js';
15
+ export function ledgerPath() {
16
+ const path = process.env.SESSION_PEER_HANDOFF_HOME ?? join(homedir(), '.local', 'state', 'session-peer-ts', 'handoff');
17
+ if (!isAbsolute(path))
18
+ throw new Refusal('invalid_handoff_ledger', 2);
19
+ return resolve(path);
20
+ }
21
+ export function privateMessage(path) {
22
+ const before = lstatSync(path);
23
+ if (!before.isFile() || before.isSymbolicLink() || before.size > 4_100_000 ||
24
+ (process.platform !== 'win32' && (before.uid !== process.getuid?.() || (before.mode & 0o777) !== 0o600)))
25
+ throw new Refusal('private_message_file_untrusted', 2);
26
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
27
+ try {
28
+ const actual = fstatSync(fd);
29
+ if (!actual.isFile() || actual.ino !== before.ino || actual.dev !== before.dev || actual.size !== before.size)
30
+ throw new Refusal('private_message_file_untrusted', 2);
31
+ const buffer = Buffer.alloc(4_100_001);
32
+ let length = 0;
33
+ while (length < buffer.length) {
34
+ const count = readSync(fd, buffer, length, buffer.length - length, null);
35
+ if (!count)
36
+ break;
37
+ length += count;
38
+ }
39
+ const bytes = buffer.subarray(0, length);
40
+ if (bytes.length > 4_100_000)
41
+ throw new Refusal('input_too_large');
42
+ const after = fstatSync(fd);
43
+ if (after.size !== actual.size || after.mtimeMs !== actual.mtimeMs || length !== actual.size)
44
+ throw new Refusal('private_message_file_changed', 1);
45
+ try {
46
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
47
+ }
48
+ catch {
49
+ throw new Refusal('invalid_utf8');
50
+ }
51
+ }
52
+ finally {
53
+ closeSync(fd);
54
+ }
55
+ }
56
+ function binding(context, message, destination = hostname()) {
57
+ return { ...context, destination, payloadDigest: payloadDigest(message) };
58
+ }
59
+ export function correlationEnvelope(message, id) {
60
+ if (!canonicalId(id))
61
+ throw new Refusal('invalid_correlation_id', 2);
62
+ // A dedicated inert metadata line, not an executable Reply-To extension.
63
+ return message + '\n\n---\nHandoff: ' + JSON.stringify({ schemaVersion: 1, correlationId: id });
64
+ }
65
+ // Nonblocking ledger locks can contend across independent waiters. Retry only
66
+ // within the caller's existing total budget; never replay a native operation.
67
+ async function persistWithinBudget(budget, action) {
68
+ for (;;) {
69
+ try {
70
+ return action();
71
+ }
72
+ catch (error) {
73
+ if (!(error instanceof Refusal) || error.code !== 'handoff_ledger_busy' || budget.remainingMs() < 1)
74
+ throw error;
75
+ await new Promise(resolve => setTimeout(resolve, Math.min(20, budget.remainingMs())));
76
+ }
77
+ }
78
+ }
79
+ // Probes stop when less than one millisecond remains, but a durable timeout
80
+ // still requires reaching the exact monotonic cutoff. Charge this fractional
81
+ // tail to the existing budget, never label an early wake as expiry.
82
+ async function settleCutoffEdge(budget) {
83
+ while (budget.observationRemainingMs() > 0 && budget.observationRemainingMs() < 1) {
84
+ await new Promise(resolve => setTimeout(resolve, 1));
85
+ }
86
+ }
87
+ class BeforeEffectRefused extends Error {
88
+ }
89
+ export async function prepareHandoff(options, path = ledgerPath(), correlationId, budget) {
90
+ const ledger = new HandoffLedger(path);
91
+ let handoff;
92
+ const value = await send({ ...options, dryRun: true, hooks: { resolved(context) {
93
+ budget?.beforeEffect();
94
+ handoff = ledger.prepare(binding(context, options.message), { correlationId });
95
+ } } });
96
+ return { value: { ...value, handoff }, exitCode: 0 };
97
+ }
98
+ export async function handoffSend(options, handoffOptions) {
99
+ const ledger = new HandoffLedger(handoffOptions.ledgerPath ?? ledgerPath());
100
+ const budget = handoffOptions.budget ?? new HandoffBudget(handoffOptions.seconds ?? 30);
101
+ let handoff, snapshot;
102
+ let scope, queueScope, deliverySupported = false, stopped = false, operationId;
103
+ let qualification;
104
+ let original, fenced = false, knownNative;
105
+ const ownWait = () => {
106
+ if (handoff && operationId) {
107
+ const operation = ledger.operationStatus(handoff.correlationId, operationId);
108
+ // Keep independently known native facts, while projecting actions and the
109
+ // exact originating wait rather than the ledger's most recently added wait.
110
+ handoff = { ...handoff, wait: operation.wait, nextActions: operation.nextActions };
111
+ }
112
+ else if (handoff)
113
+ handoff = { ...handoff, wait: { for: 'none', status: 'not_requested' }, nextActions: ['reconcile'] };
114
+ };
115
+ const stop = () => {
116
+ stopped = true;
117
+ try {
118
+ ownWait();
119
+ if (handoff?.wait.status === 'pending')
120
+ handoff = ledger.recordWait(handoff.correlationId, 'stopped', 'stopped_by_operator', operationId);
121
+ ownWait();
122
+ }
123
+ catch { /* No fabricated terminal evidence after persistence failure. */ }
124
+ };
125
+ const persist = (action) => persistWithinBudget(budget, action);
126
+ const authorize = async () => { if (stopped)
127
+ throw new Refusal('stopped_by_operator', 130); budget.beforeEffect(); handoff = await persist(() => { if (stopped)
128
+ throw new Refusal('stopped_by_operator', 130); return ledger.commitEffect(handoff.correlationId, original, budget); }); fenced = true; ownWait(); };
129
+ const verifyOwner = async (target, signal) => {
130
+ if (stopped || signal?.aborted || budget.observationRemainingMs() < 1)
131
+ return false;
132
+ const worker = fileURLToPath(new URL('./handoff-writer-probe.js', import.meta.url));
133
+ const result = await run(process.execPath, [worker, target.home, target.threadId], { timeout: Math.min(800, budget.observationRemainingMs()), limit: 4096, env: { ...process.env, NODE_OPTIONS: undefined, NODE_PATH: undefined } });
134
+ if (signal?.aborted || stopped || result.code !== 0 || result.interrupted)
135
+ return false;
136
+ try {
137
+ const value = JSON.parse(result.stdout);
138
+ return value.schemaVersion === 1 && value.ok === true && Object.keys(value).every(key => ['schemaVersion', 'ok', 'generation'].includes(key)) && /^[0-9a-f]{64}$/.test(value.generation) && value.generation === target.generation;
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ };
144
+ const finish = (value, exitCode) => ({ value: { ...value, ...(handoff ? { handoff } : {}) }, exitCode });
145
+ if (handoffOptions.waitFor)
146
+ process.on('SIGINT', stop);
147
+ try {
148
+ const value = await send({ ...options, hooks: {
149
+ async resolved(context, native) {
150
+ snapshot = native;
151
+ original = binding(context, handoffOptions.payload ?? options.message);
152
+ if (Buffer.byteLength(JSON.stringify(native)) + HANDOFF_LIMITS.publicFrame + (handoffOptions.resultOverhead ?? 1024) > HANDOFF_LIMITS.outerFrame)
153
+ throw new Refusal('handoff_result_too_large', 1);
154
+ // Account for the fixed correlation envelope before allocating an intent.
155
+ checkMessage(correlationEnvelope(options.message, '00000000-0000-4000-8000-000000000000'), context.agent === 'codex');
156
+ const wantsDelivery = handoffOptions.observeDelivery || handoffOptions.waitFor === 'delivered';
157
+ if (wantsDelivery && context.agent === 'codex' && context.home && context.generation && budget.observationRemainingMs() > 0) {
158
+ scope = { home: context.home, threadId: context.target, generation: context.generation };
159
+ queueScope = { codexHome: context.home, threadId: context.target, generation: context.generation, ownerIdentity: context.writerIdentity };
160
+ const version = await run(executable(options.codexBin ?? 'codex'), ['--version'], { timeout: Math.min(1000, budget.observationRemainingMs()), limit: 4096 });
161
+ const nativeVersion = !version.interrupted && version.code === 0 ? version.stdout.trim().replace(/^codex-cli /, '') : '';
162
+ qualification = metadataQualification(nativeVersion);
163
+ if (qualification && nativeQueueCapability({ version: nativeVersion, platform: `${process.platform}-${process.arch}`, scope: queueScope }).queueSupported)
164
+ deliverySupported = (await metadataCapability(scope, nativeVersion, budget, verifyOwner)).supported;
165
+ }
166
+ handoff = await persist(() => ledger.prepare(original, { correlationId: handoffOptions.correlationId,
167
+ requestAck: handoffOptions.requestAck || handoffOptions.waitFor === 'acknowledged',
168
+ observeDelivery: handoffOptions.observeDelivery || handoffOptions.waitFor === 'delivered',
169
+ waitFor: handoffOptions.waitFor ?? 'none', budget, dryRun: options.dryRun, observationSupported: deliverySupported,
170
+ ...(deliverySupported ? { observationQualification: qualification } : {}) }));
171
+ operationId = handoff.wait.operationId;
172
+ if (handoff.state === 'refused')
173
+ throw new BeforeEffectRefused();
174
+ return correlationEnvelope(options.message, handoff.correlationId);
175
+ },
176
+ beforeEffect: authorize,
177
+ async submitCodex(context, message) {
178
+ if (!deliverySupported) {
179
+ // Best-effort unsupported is chosen before ANY app-server attempt.
180
+ await authorize();
181
+ const inherited = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.toUpperCase() !== 'CODEX_SQLITE_HOME'));
182
+ const done = await run(executable(options.codexBin ?? 'codex'), ['queue', '--thread', context.target, `--message=${message}`], { env: { ...inherited, CODEX_HOME: context.home }, timeout: Math.max(1, budget.observationRemainingMs()) });
183
+ if (!done.spawned)
184
+ throw new Refusal('native_spawn_failed', 1);
185
+ if (done.interrupted || done.code !== 0)
186
+ throw new UnknownOutcome();
187
+ const receipt = queueId(done.stdout, context.target);
188
+ return { queueId: receipt, clientUserMessageId: handoff.correlationId };
189
+ }
190
+ try {
191
+ return await nativeQueueOnce({ binary: executable(options.codexBin ?? 'codex'), scope: queueScope, message, clientUserMessageId: handoff.correlationId, deadlineMs: budget.cutoff, verifyOwner: async () => verifyOwner(scope), beforeEffect: authorize });
192
+ }
193
+ catch (error) {
194
+ if (error instanceof AppServerFault && error.attempted)
195
+ throw new UnknownOutcome();
196
+ if (error instanceof AppServerFault)
197
+ throw new Refusal(`app_server_${error.code}`, 1);
198
+ throw error;
199
+ }
200
+ },
201
+ timeoutMs() { budget.beforeEffect(); return Math.max(1, Math.floor(budget.observationRemainingMs())); },
202
+ } });
203
+ knownNative = value;
204
+ if (!options.dryRun) {
205
+ handoff = await persist(() => ledger.recordSubmission(handoff.correlationId, 'submitted'));
206
+ ownWait();
207
+ }
208
+ if (!options.dryRun && deliverySupported && scope && handoff) {
209
+ do {
210
+ if (stopped)
211
+ break;
212
+ const observed = await observeMetadata({ ...scope, clientUserMessageId: handoff.correlationId }, budget, verifyOwner);
213
+ if (!observed.supported) {
214
+ if (budget.observationRemainingMs() < 1)
215
+ break;
216
+ if (['metadata_deadline', 'metadata_probe_failed'].includes(observed.reason)) {
217
+ await new Promise(resolve => setTimeout(resolve, Math.min(100, budget.observationRemainingMs())));
218
+ continue;
219
+ }
220
+ handoff = await persist(() => ledger.recordObservationFailure(handoff.correlationId, original, observed.reason === 'metadata_owner_changed' ? 'unsupported' : 'failed', operationId));
221
+ ownWait();
222
+ break;
223
+ }
224
+ if (observed.injectionObserved) {
225
+ handoff = await persist(() => ledger.recordObservation(handoff.correlationId, { clientUserMessageId: observed.clientUserMessageId, injectionObserved: true, ...(observed.turn ? { turn: observed.turn } : {}) }, original));
226
+ ownWait();
227
+ break;
228
+ }
229
+ if (!handoffOptions.waitFor)
230
+ break;
231
+ await new Promise(resolve => setTimeout(resolve, Math.min(100, budget.observationRemainingMs())));
232
+ } while (budget.observationRemainingMs() > 0);
233
+ if (handoffOptions.waitFor && handoff.wait.status === 'pending') {
234
+ if (!stopped)
235
+ await settleCutoffEdge(budget);
236
+ handoff = await persist(() => stopped ? ledger.recordWait(handoff.correlationId, 'stopped', 'stopped_by_operator', operationId) : ledger.recordWait(handoff.correlationId, 'timed_out_unknown', undefined, operationId));
237
+ }
238
+ ownWait();
239
+ if (handoffOptions.waitFor && handoff.wait.status !== 'satisfied')
240
+ return finish({ ...value, ok: false, error: handoff.wait.reason ?? 'timed_out_unknown', retryAllowed: false }, handoff.wait.status === 'stopped' && handoff.wait.reason === 'stopped_by_operator' ? 130 : 1);
241
+ }
242
+ return finish(value, 0);
243
+ }
244
+ catch (error) {
245
+ if (!handoff || !snapshot)
246
+ throw error;
247
+ try {
248
+ ownWait();
249
+ }
250
+ catch { /* Preserve the last verified original operation. */ }
251
+ if (knownNative) {
252
+ // An I/O failure after positive native acceptance cannot erase that fact.
253
+ handoff = { ...handoff, state: handoff.ack.status === 'acknowledged' ? 'acknowledged' : handoff.observation.injectionObserved ? 'delivered' : 'submitted', submission: { status: 'submitted' }, nextActions: ['reconcile'] };
254
+ if (handoffOptions.waitFor) {
255
+ // Preserve the last verified operation; a failed write cannot create
256
+ // a durable terminal wait in the returned evidence.
257
+ const interrupted = handoff.wait.status === 'stopped' && handoff.wait.reason === 'stopped_by_operator';
258
+ return finish({ ...knownNative, ok: false, error: interrupted ? 'stopped_by_operator' : 'handoff_persistence_failed', handoffWarning: 'persistence_failed', retryAllowed: false }, interrupted ? 130 : 1);
259
+ }
260
+ return finish({ ...knownNative, handoffWarning: 'persistence_failed', retryAllowed: false }, 0);
261
+ }
262
+ const uncertain = error instanceof UnknownOutcome;
263
+ if (fenced) {
264
+ try {
265
+ handoff = ledger.recordSubmission(handoff.correlationId, uncertain ? 'unknown' : 'refused');
266
+ ownWait();
267
+ }
268
+ catch {
269
+ try {
270
+ const state = operationId ? { handoff: ledger.operationStatus(handoff.correlationId, operationId) } : ledger.status(handoff.correlationId);
271
+ if ('handoff' in state)
272
+ handoff = state.handoff;
273
+ ownWait();
274
+ }
275
+ catch { /* Keep the last verified original wait, never another operation's terminal outcome. */ }
276
+ }
277
+ }
278
+ try {
279
+ ownWait();
280
+ }
281
+ catch { /* A latest-operation snapshot is never proof of this wait's terminal outcome. */ }
282
+ if (handoffOptions.waitFor && handoff.wait.status === 'pending') {
283
+ try {
284
+ handoff = ledger.recordWait(handoff.correlationId, budget.observationRemainingMs() <= 0 ? 'timed_out_unknown' : 'failed', budget.observationRemainingMs() <= 0 ? undefined : 'evidence_failed', operationId);
285
+ ownWait();
286
+ }
287
+ catch {
288
+ handoff.wait = { ...handoff.wait, status: 'failed', reason: 'evidence_failed' };
289
+ }
290
+ }
291
+ if (!fenced && original && handoff.state !== 'refused') {
292
+ try {
293
+ handoff = ledger.refusePrepared(handoff.correlationId, original);
294
+ ownWait();
295
+ }
296
+ catch { /* Keep the last verified facts; never retry. */ }
297
+ }
298
+ const code = error instanceof BeforeEffectRefused ? handoff.wait.reason ?? 'evidence_unsupported' : error instanceof Refusal ? error.code : uncertain ? 'outcome_unknown' : 'handoff_operation_failed';
299
+ return finish({ ...snapshot, ok: false, error: code, status: uncertain ? 'unknown' : 'refused', submitted: uncertain ? null : false,
300
+ consumptionConfirmed: false, retryAllowed: false, ...(error instanceof HomeRefusal ? { codexHomeResolution: error.codexHomeResolution } : {}) }, handoffOptions.waitFor && handoff.wait.status === 'stopped' && handoff.wait.reason === 'stopped_by_operator' ? 130 : error instanceof Refusal && error.exitCode !== 130 ? error.exitCode : 1);
301
+ }
302
+ finally {
303
+ process.removeListener('SIGINT', stop);
304
+ }
305
+ }
306
+ // Start a new read-only operation on retained original submission evidence.
307
+ // Never reopen a queue client, adopt a successor owner or reset an old deadline.
308
+ export async function waitForHandoff(ledger, id, goal, budget) {
309
+ const retained = goal === 'delivered' ? ledger.observationContext(id) : undefined;
310
+ const context = retained?.binding.destination === hostname() ? retained : undefined;
311
+ // Register before the first durable wait write; the signal handler only marks
312
+ // intent. Persistence remains serialized in this operation, never its callback.
313
+ let stopped = false, handoff, operationId;
314
+ const stop = () => { stopped = true; };
315
+ const persist = (action) => persistWithinBudget(budget, action);
316
+ const ownWait = () => { if (operationId)
317
+ handoff = ledger.operationStatus(id, operationId); };
318
+ const verifyOwner = async (scope, signal) => {
319
+ if (stopped || signal.aborted || budget.observationRemainingMs() < 1)
320
+ return false;
321
+ const worker = fileURLToPath(new URL('./handoff-writer-probe.js', import.meta.url));
322
+ const result = await run(process.execPath, [worker, scope.home, scope.threadId], { timeout: Math.min(800, budget.observationRemainingMs()), limit: 4096, env: { ...process.env, NODE_OPTIONS: undefined, NODE_PATH: undefined } });
323
+ if (stopped || signal.aborted || result.code !== 0 || result.interrupted)
324
+ return false;
325
+ try {
326
+ const value = JSON.parse(result.stdout);
327
+ return value.schemaVersion === 1 && value.ok === true && Object.keys(value).every(key => ['schemaVersion', 'ok', 'generation'].includes(key)) &&
328
+ /^[0-9a-f]{64}$/.test(value.generation) && value.generation === scope.generation;
329
+ }
330
+ catch {
331
+ return false;
332
+ }
333
+ };
334
+ process.on('SIGINT', stop);
335
+ try {
336
+ handoff = await persist(() => ledger.beginWait(id, goal, budget, { observationSupported: context !== undefined }));
337
+ operationId = handoff.wait.operationId;
338
+ while (context && handoff.wait.status === 'pending' && !stopped && budget.observationRemainingMs() >= 1) {
339
+ const observed = await resumeMetadataObservation({ home: context.binding.home, threadId: context.binding.target,
340
+ generation: context.binding.generation, clientUserMessageId: context.clientUserMessageId }, context.qualification, budget, verifyOwner);
341
+ ownWait();
342
+ if (stopped || handoff.wait.status !== 'pending')
343
+ break;
344
+ if (!observed.supported) {
345
+ if (budget.observationRemainingMs() < 1)
346
+ break;
347
+ if (!['metadata_deadline', 'metadata_probe_failed'].includes(observed.reason)) {
348
+ handoff = await persist(() => ledger.recordObservationFailure(id, context.binding, ['metadata_owner_changed', 'metadata_version_unsupported', 'metadata_platform_unsupported'].includes(observed.reason) ? 'unsupported' : 'failed', operationId));
349
+ break;
350
+ }
351
+ }
352
+ else if (observed.injectionObserved) {
353
+ await persist(() => ledger.recordObservation(id, { clientUserMessageId: observed.clientUserMessageId, injectionObserved: true,
354
+ ...(observed.turn ? { turn: observed.turn } : {}) }, context.binding));
355
+ ownWait();
356
+ break;
357
+ }
358
+ await new Promise(resolve => setTimeout(resolve, Math.min(100, budget.observationRemainingMs())));
359
+ ownWait();
360
+ }
361
+ ownWait();
362
+ if (handoff.wait.status === 'pending') {
363
+ if (!stopped)
364
+ await settleCutoffEdge(budget);
365
+ handoff = await persist(() => stopped ? ledger.recordWait(id, 'stopped', 'stopped_by_operator', operationId) :
366
+ budget.observationRemainingMs() < 1 ? ledger.recordWait(id, 'timed_out_unknown', undefined, operationId) :
367
+ ledger.recordWait(id, 'unsupported', 'evidence_unsupported', operationId));
368
+ }
369
+ const success = handoff.wait.status === 'satisfied', interrupted = handoff.wait.status === 'stopped' && handoff.wait.reason === 'stopped_by_operator';
370
+ return { value: { handoff, ok: success }, exitCode: success ? 0 : interrupted ? 130 : 1 };
371
+ }
372
+ catch (error) {
373
+ if (!handoff)
374
+ throw error;
375
+ // Failure to write is not a committed terminal result. Keep the last valid
376
+ // original-operation snapshot and its known submission/injection evidence.
377
+ try {
378
+ ownWait();
379
+ }
380
+ catch { /* Retain independently verified facts. */ }
381
+ const interrupted = handoff.wait.status === 'stopped' && handoff.wait.reason === 'stopped_by_operator';
382
+ return { value: { handoff, ok: false, error: 'handoff_persistence_failed', handoffWarning: 'persistence_failed', retryAllowed: false }, exitCode: interrupted ? 130 : 1 };
383
+ }
384
+ finally {
385
+ process.removeListener('SIGINT', stop);
386
+ }
387
+ }
388
+ // New commands are local owner operations; forwarding them through native send
389
+ // or interpreting a receipt as a model prompt is never allowed.
390
+ export async function handoffCommand(args, readInput) {
391
+ const ack = args[0] === 'ack', operation = ack ? 'ack' : args[1];
392
+ if (!operation || !['init', 'prepare', 'status', 'wait', 'confirm', 'ack'].includes(operation))
393
+ throw new Refusal('unsupported_handoff_command');
394
+ const values = new Map();
395
+ const flags = new Set();
396
+ const names = ['--correlation-id', '--wait-for', '--wait-timeout', '--receipt', '--to', '--message-file', '--codex-home', '--codex-bin', '--output-format'];
397
+ for (let i = ack ? 1 : 2; i < args.length; i++) {
398
+ const token = args[i], equal = token.indexOf('='), name = equal < 0 ? token : token.slice(0, equal);
399
+ if (['--json', '--no-update-notice', '--allow-inactive-codex-home'].includes(name)) {
400
+ if (equal >= 0 || flags.has(name))
401
+ throw new Refusal('invalid_option');
402
+ flags.add(name);
403
+ continue;
404
+ }
405
+ if (!names.includes(name) || values.has(name))
406
+ throw new Refusal('unsupported_option');
407
+ const value = equal < 0 ? args[++i] : token.slice(equal + 1);
408
+ if (value === undefined || (equal < 0 && value.startsWith('--')))
409
+ throw new Refusal('invalid_option');
410
+ values.set(name, value);
411
+ }
412
+ if (!flags.has('--json') && values.get('--output-format') !== 'json')
413
+ throw new Refusal('json_output_required');
414
+ if (values.has('--output-format') && values.get('--output-format') !== 'json')
415
+ throw new Refusal('unsupported_output_format');
416
+ const permitted = { init: [], prepare: ['--to', '--message-file', '--codex-home', '--codex-bin'],
417
+ status: ['--correlation-id'], wait: ['--correlation-id', '--wait-for', '--wait-timeout'], confirm: ['--receipt'], ack: ['--receipt'] };
418
+ if ([...values.keys()].some(k => k !== '--output-format' && !permitted[operation].includes(k)) ||
419
+ (flags.has('--allow-inactive-codex-home') && operation !== 'prepare'))
420
+ throw new Refusal('inapplicable_option');
421
+ const path = ledgerPath(), ledger = new HandoffLedger(path);
422
+ if (operation === 'init') {
423
+ if (process.platform === 'win32')
424
+ throw new Refusal('handoff_platform_unsupported', 1);
425
+ const parent = dirname(path);
426
+ // Initialization is explicit; never follow a symlinked state prefix.
427
+ let current = parse(parent).root;
428
+ for (const component of parent.slice(current.length).split('/').filter(Boolean)) {
429
+ current = join(current, component);
430
+ try {
431
+ const stat = lstatSync(current);
432
+ if (!stat.isDirectory() || stat.isSymbolicLink())
433
+ throw new Refusal('handoff_storage_untrusted', 1);
434
+ }
435
+ catch (error) {
436
+ if (error.code !== 'ENOENT')
437
+ throw error;
438
+ mkdirSync(current, { mode: 0o700 });
439
+ }
440
+ }
441
+ if (realpathSync(parent) !== parent)
442
+ throw new Refusal('handoff_storage_untrusted', 1);
443
+ return { value: ledger.init(), exitCode: 0 };
444
+ }
445
+ if (operation === 'prepare') {
446
+ if (!values.get('--to') || !values.get('--message-file'))
447
+ throw new Refusal('invalid_send_options');
448
+ const value = await prepareHandoff({ to: values.get('--to'), message: privateMessage(values.get('--message-file')),
449
+ home: values.get('--codex-home'), codexBin: values.get('--codex-bin'), allowInactive: flags.has('--allow-inactive-codex-home') }, path);
450
+ return { value: { handoff: value.value.handoff }, exitCode: 0 };
451
+ }
452
+ if (operation === 'confirm' || operation === 'ack') {
453
+ if (values.get('--receipt') !== '-')
454
+ throw new Refusal('private_receipt_stdin_required', 2);
455
+ const raw = await readInput(4096);
456
+ return { value: { handoff: operation === 'confirm' ? ledger.confirm(raw) : ledger.acceptReceipt(raw) }, exitCode: 0 };
457
+ }
458
+ const id = values.get('--correlation-id');
459
+ if (!canonicalId(id))
460
+ throw new Refusal('invalid_correlation_id', 2);
461
+ const budget = operation === 'wait' ? new HandoffBudget(parseWaitTimeout(values.get('--wait-timeout') ?? '30')) : undefined;
462
+ const result = ledger.status(id);
463
+ if ('handoffQuery' in result)
464
+ return { value: { ok: false, ...result }, exitCode: 1 };
465
+ if (operation === 'status')
466
+ return { value: result, exitCode: 0 };
467
+ const goal = values.get('--wait-for');
468
+ if (!['delivered', 'acknowledged'].includes(goal ?? ''))
469
+ throw new Refusal('invalid_wait_for', 2);
470
+ return waitForHandoff(ledger, id, goal, budget);
471
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,123 @@
1
+ // Private owner verifier entry point. The caller MUST spawn this in an owned
2
+ // POSIX process group and enforce the original remaining deadline (at most 1s).
3
+ // lsof/ps inherit that group; using process.run() here would detach them into
4
+ // separate groups and defeat the supervisor's cleanup.
5
+ // Keep the sample/identity algorithm aligned with writer.ts inspectWriter.
6
+ // Its byte-for-byte identity SHA is covered by a real-lock synthetic fixture.
7
+ import { spawn } from 'node:child_process';
8
+ import { createHash } from 'node:crypto';
9
+ import { lstatSync, realpathSync } from 'node:fs';
10
+ import { isAbsolute, join, resolve } from 'node:path';
11
+ import { setTimeout as delay } from 'node:timers/promises';
12
+ const safe = (value, bytes) => typeof value === 'string' && value.length > 0 &&
13
+ Buffer.byteLength(value) <= bytes && !/[\x00-\x1f\x7f-\x9f]/.test(value) &&
14
+ !/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value);
15
+ function fingerprint(path) {
16
+ const s = lstatSync(path, { bigint: true });
17
+ return [s.dev, s.ino, s.size, s.mtimeNs].join(':');
18
+ }
19
+ function owned(path, directory) {
20
+ const s = lstatSync(path);
21
+ return !s.isSymbolicLink() && (directory ? s.isDirectory() : s.isFile() && s.nlink === 1) &&
22
+ s.uid === process.getuid?.() && !(s.mode & 0o022);
23
+ }
24
+ function command(binary, args, env = process.env) {
25
+ return new Promise(resolve => {
26
+ let child;
27
+ try {
28
+ child = spawn(binary, args, { shell: false, detached: false, stdio: ['ignore', 'pipe', 'pipe'],
29
+ env: { ...env, NODE_OPTIONS: undefined, NODE_PATH: undefined } });
30
+ }
31
+ catch {
32
+ resolve({ valid: false, stdout: '' });
33
+ return;
34
+ }
35
+ let bytes = 0, output = '', overflow = false, failed = false;
36
+ child.stdout.setEncoding('utf8');
37
+ child.stdout.on('data', (part) => {
38
+ bytes += Buffer.byteLength(part);
39
+ if (bytes > 4096) {
40
+ overflow = true;
41
+ output = '';
42
+ }
43
+ else if (!overflow)
44
+ output += part;
45
+ });
46
+ // Drain metadata tool errors without retaining paths, command text or bodies.
47
+ child.stderr.on('data', (part) => { bytes += part.length; if (bytes > 8192) {
48
+ overflow = true;
49
+ output = '';
50
+ } });
51
+ child.once('error', () => { failed = true; });
52
+ // Do not return while a command still runs. A hung/overflowing command and
53
+ // all its inherited-group descendants are killed by the owning supervisor.
54
+ child.once('close', code => resolve({ valid: code === 0 && !failed && !overflow, stdout: overflow ? '' : output }));
55
+ });
56
+ }
57
+ async function main(args) {
58
+ const refusal = (error) => ({ schemaVersion: 1, ok: false, error });
59
+ if (!['darwin', 'linux'].includes(process.platform) || process.getuid?.() === undefined)
60
+ return refusal('writer_probe_unsupported');
61
+ const [home, rawId] = args;
62
+ if (args.length !== 2 || !safe(home, 2048) || !safe(rawId, 128) || !isAbsolute(home) || resolve(home) !== home ||
63
+ !/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(rawId))
64
+ return refusal('writer_probe_invalid');
65
+ try {
66
+ const id = rawId.toLowerCase(), directory = join(home, 'thread-writer-locks'), path = join(directory, id + '.lock');
67
+ if (realpathSync(home) !== home || !owned(home, true) || !owned(directory, true) || !owned(path, false))
68
+ return refusal('writer_probe_unverified');
69
+ // Dynamic import keeps dependency failures inside the sanitized boundary.
70
+ const { probeLock } = await import('./writer.js');
71
+ async function sample() {
72
+ const state = await probeLock(path);
73
+ if (state !== 'held')
74
+ return { state, fingerprint: state === 'free' ? fingerprint(path) : '', owners: [], valid: true };
75
+ const stamp = fingerprint(path);
76
+ const listed = await command('lsof', ['-nP', '-F0pcu', '--', path]);
77
+ const owners = [];
78
+ let current;
79
+ // Preserve assignment order: inspectWriter's original JSON serialization
80
+ // is the generation source, not a newly canonicalized owner object.
81
+ for (const token of listed.stdout.split(/[\0\n]/)) {
82
+ const value = token.slice(1).trim();
83
+ if (token[0] === 'p') {
84
+ current = { pid: Number(value) };
85
+ owners.push(current);
86
+ }
87
+ if (current && token[0] === 'u') {
88
+ const uid = /^\d+$/.test(value) ? Number(value) : NaN;
89
+ current.uid = Number.isSafeInteger(uid) ? uid : undefined;
90
+ }
91
+ if (current && token[0] === 'c')
92
+ current.command = value;
93
+ }
94
+ // Ambiguous owners need no further tools and cannot produce a generation.
95
+ if (owners.length !== 1)
96
+ return { state, fingerprint: stamp, owners, valid: false };
97
+ for (const owner of owners) {
98
+ if (!Number.isSafeInteger(owner.pid) || owner.pid <= 1)
99
+ continue;
100
+ const started = await command('ps', ['-p', String(owner.pid), '-o', 'lstart='], { ...process.env, LC_ALL: 'C' });
101
+ if (started.valid)
102
+ owner.start = started.stdout.trim();
103
+ }
104
+ return { state, fingerprint: stamp, owners, valid: listed.valid };
105
+ }
106
+ const before = await sample();
107
+ if (before.state !== 'held')
108
+ return refusal('writer_probe_unverified');
109
+ await delay(250);
110
+ const after = await sample(), owner = after.owners[0], uid = process.getuid?.();
111
+ if (!before.valid || !after.valid || before.state !== after.state || before.fingerprint !== after.fingerprint ||
112
+ before.owners.length !== 1 || after.owners.length !== 1 || JSON.stringify(before.owners) !== JSON.stringify(after.owners) ||
113
+ !owner?.start || !safe(owner.start, 256) || uid === undefined || owner.uid !== uid ||
114
+ !/^codex(?:\.exe|-|$)/i.test(owner.command ?? '') || !owned(path, false))
115
+ return refusal('writer_probe_unverified');
116
+ const identity = JSON.stringify({ fingerprint: after.fingerprint, ...owner });
117
+ return { schemaVersion: 1, ok: true, generation: createHash('sha256').update(identity).digest('hex') };
118
+ }
119
+ catch {
120
+ return refusal('writer_probe_unverified');
121
+ }
122
+ }
123
+ void main(process.argv.slice(2)).then(result => { process.stdout.write(JSON.stringify(result) + '\n'); }, () => { process.stdout.write('{"schemaVersion":1,"ok":false,"error":"writer_probe_unverified"}\n'); });