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