session-peer 0.4.0 → 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.
@@ -13,6 +13,9 @@ import { basename, isAbsolute, join } from 'node:path';
13
13
  import { performance } from 'node:perf_hooks';
14
14
  import { TextDecoder } from 'node:util';
15
15
  import { run } from './process.js';
16
+ import { CANDIDATE_PROFILES, NATIVE_PROFILES, platformProfiled, selectNativeProfile, validateNativeProfiles } from './native-profiles.js';
17
+ import { procOwnedFiles } from './linux-proc.js';
18
+ import { fileURLToPath } from 'node:url';
16
19
  export const APP_SERVER_EVIDENCE = Object.freeze({
17
20
  version: '0.160.1', inspectedPlatform: 'darwin-arm64',
18
21
  officialSourceCommit: 'd27764b82f7118f674371e6d6e76271d9d606edb',
@@ -22,9 +25,12 @@ export const APP_SERVER_EVIDENCE = Object.freeze({
22
25
  itemStartedSha256: '7574788d2a352747f50d44be3ef649011cb8de8069da4c655faff14d0aee32c4',
23
26
  turnCompletedSha256: '016870158603b0f84bd9f8f65f927161c9fd5128e5ec632087616462dc44e085',
24
27
  });
25
- // Each entry qualifies queue-only mechanics on this exact native version and
26
- // platform. Neither generated schemas nor isolated unloaded-thread fixtures
27
- // qualify a live writer endpoint, metadata-only observer or delivery/ACK.
28
+ // Darwin entries qualify queue-only mechanics on that exact native version and
29
+ // platform. The linux-arm64 entry is generated-schema data for the
30
+ // non-selectable candidate only; it is consumed by profile selection and tests
31
+ // and qualifies nothing while no Linux row is selectable. Neither generated
32
+ // schemas nor isolated unloaded-thread fixtures qualify a live writer
33
+ // endpoint, metadata-only observer or delivery/ACK.
28
34
  export const APP_SERVER_QUEUE_EVIDENCE = Object.freeze([
29
35
  APP_SERVER_EVIDENCE,
30
36
  Object.freeze({
@@ -36,16 +42,34 @@ export const APP_SERVER_QUEUE_EVIDENCE = Object.freeze([
36
42
  itemStartedSha256: '692c5876f44a4c12a9b9211912860ceddb65d34497ab4fe9aa46cbebe1a63166',
37
43
  turnCompletedSha256: '69413578ec3ecd02691424bdeb9d640c7244b4ca4c5c3ef26f69a2efe7c37db8',
38
44
  }),
45
+ // Generated on the Linux arm64 host from the exact pinned musl artifact with
46
+ // an isolated CODEX_HOME; byte-identical to the darwin-arm64 0.162.1 schemas.
47
+ // Schema evidence only: no linux-arm64 profile row is selectable yet.
48
+ Object.freeze({
49
+ version: '0.162.1', inspectedPlatform: 'linux-arm64',
50
+ officialSourceCommit: '092d3acd6bec3e3a14bdc7e7a2810ab628ab759d',
51
+ scope: 'generated_schema_only',
52
+ queueAddParamsSha256: '60f25b7d3e3357c215bef9d2fe7047200f545e030dca9e00527ac0620cd0c88f',
53
+ queueAddResponseSha256: 'c11b9772788427b19c9f9decf0765e2b41cbdead1aa9c3d39f42fdd70b339314',
54
+ itemStartedSha256: '692c5876f44a4c12a9b9211912860ceddb65d34497ab4fe9aa46cbebe1a63166',
55
+ turnCompletedSha256: '69413578ec3ecd02691424bdeb9d640c7244b4ca4c5c3ef26f69a2efe7c37db8',
56
+ }),
39
57
  ]);
40
- function queueEvidence(version) { return APP_SERVER_QUEUE_EVIDENCE.find(profile => profile.version === version); }
58
+ // Exact (version, platform) schema evidence; another platform's row is never inherited.
59
+ function queueEvidence(version, platform) {
60
+ return APP_SERVER_QUEUE_EVIDENCE.find(profile => profile.version === version && profile.inspectedPlatform === platform);
61
+ }
62
+ // Every production or candidate profile row must carry its own exact schema evidence row.
63
+ if ([...NATIVE_PROFILES, ...CANDIDATE_PROFILES].some(row => !queueEvidence(row.version, row.platform)))
64
+ throw new Error('native profile lacks queue evidence');
41
65
  export const APP_SERVER_LIMITS = Object.freeze({
42
66
  frameBytes: 65536, receivedBytes: 1024 * 1024, sentBytes: 256 * 1024,
43
67
  frames: 512, notifications: 256, requests: 16, observations: 64, messageBytes: 32768,
44
68
  lifetimeMs: 60000, cleanupMs: 250,
45
69
  });
46
70
  export function appServerCapability(context) {
47
- const profile = queueEvidence(context.version);
48
- const qualified = profile !== undefined && profile.inspectedPlatform === context.platform;
71
+ const qualified = selectNativeProfile({ platform: context.platform, version: context.version }) !== undefined &&
72
+ queueEvidence(context.version, context.platform) !== undefined;
49
73
  return { supported: false, schema: qualified ? 'version_qualified' : 'version_unqualified', route: 'route_unsupported',
50
74
  reason: qualified ? 'metadata_only_owner_route_unvalidated' : 'version_unqualified', attempted: false, queueSupported: qualified };
51
75
  }
@@ -298,13 +322,15 @@ export class BoundedAppServerClient {
298
322
  }
299
323
  // Hermetic test hook for the exact native RPC profile. It does not qualify a
300
324
  // binary, platform or writer. Production callers use nativeQueueOnce instead.
301
- static async connectNativeQueueFixture(scope, transport, deadlineMs, verifyOwner, beforeEffect, nativeVersion = APP_SERVER_EVIDENCE.version) {
302
- return this.connectWire(scope, transport, deadlineMs, verifyOwner, true, beforeEffect, nativeVersion);
325
+ // The profile table defaults to the frozen production rows; a hermetic test
326
+ // may supply a validated synthetic table, which never qualifies production.
327
+ static async connectNativeQueueFixture(scope, transport, deadlineMs, verifyOwner, beforeEffect, nativeVersion = APP_SERVER_EVIDENCE.version, platform = APP_SERVER_EVIDENCE.inspectedPlatform, profiles = NATIVE_PROFILES) {
328
+ return this.connectWire(scope, transport, deadlineMs, verifyOwner, true, beforeEffect, selectNativeProfile({ platform, version: nativeVersion }, validateNativeProfiles(profiles)));
303
329
  }
304
- static async connectNativeQueueWire(scope, transport, deadlineMs, verifyOwner, beforeEffect, nativeVersion = APP_SERVER_EVIDENCE.version) {
305
- return this.connectWire(scope, transport, deadlineMs, verifyOwner, true, beforeEffect, nativeVersion);
330
+ static async connectNativeQueueWire(scope, transport, deadlineMs, verifyOwner, beforeEffect, profile) {
331
+ return this.connectWire(scope, transport, deadlineMs, verifyOwner, true, beforeEffect, profile);
306
332
  }
307
- static async connectWire(scope, transport, deadlineMs, verifyOwner, nativeQueue, beforeEffect = async () => { }, nativeVersion = APP_SERVER_EVIDENCE.version) {
333
+ static async connectWire(scope, transport, deadlineMs, verifyOwner, nativeQueue, beforeEffect = async () => { }, profile) {
308
334
  let original;
309
335
  try {
310
336
  original = scopeValue(scope);
@@ -326,12 +352,14 @@ export class BoundedAppServerClient {
326
352
  try {
327
353
  await client.owner();
328
354
  if (nativeQueue) {
329
- const notifications = nativeNotifications(nativeVersion);
355
+ if (!profile)
356
+ throw new AppServerFault('unsupported_version', false);
357
+ const nativeVersion = profile.version, notifications = nativeNotifications(nativeVersion);
330
358
  const hello = object(await client.request('initialize', {
331
359
  clientInfo: { name: 'session-peer-native-queue', version: '1' },
332
360
  capabilities: { experimentalApi: true, optOutNotificationMethods: [...notifications] },
333
361
  }), ['codexHome', 'platformFamily', 'platformOs', 'userAgent']);
334
- if (hello.codexHome !== original.codexHome || hello.platformFamily !== 'unix' || hello.platformOs !== 'macos' ||
362
+ if (hello.codexHome !== original.codexHome || hello.platformFamily !== 'unix' || hello.platformOs !== profile.platformOs ||
335
363
  !safeId(hello.userAgent, 4096))
336
364
  throw new AppServerFault('owner_changed', false);
337
365
  // The queue process itself reports its compiled build; the earlier
@@ -640,6 +668,9 @@ async function beforeDeadline(deadlineMs, operation, code) {
640
668
  async function verifyOwnedSqliteBinding(pid, home, deadlineMs) {
641
669
  if (!pid || pid < 2 || performance.now() >= deadlineMs)
642
670
  throw new AppServerFault('storage_binding_unverified', false);
671
+ verifyOpenedSqlite(await darwinOpenedFiles(pid, deadlineMs), home);
672
+ }
673
+ async function darwinOpenedFiles(pid, deadlineMs) {
643
674
  // Only the owned app-server PID is queried, never a session inventory/PID scan.
644
675
  // An exact managed requirement can override both env and CLI sqlite_home.
645
676
  // initialize.codexHome does not attest to effective SQLite storage; require
@@ -655,7 +686,6 @@ async function verifyOwnedSqliteBinding(pid, home, deadlineMs) {
655
686
  throw new AppServerFault('deadline', false);
656
687
  if (result.code !== 0 || result.interrupted)
657
688
  throw new AppServerFault('storage_binding_unverified', false);
658
- const required = ['state_5.sqlite', 'queue_1.sqlite'];
659
689
  const files = [];
660
690
  let current;
661
691
  for (const raw of result.stdout.split('\0')) {
@@ -671,13 +701,19 @@ async function verifyOwnedSqliteBinding(pid, home, deadlineMs) {
671
701
  else if (current && /^i[0-9]+$/.test(field))
672
702
  current.ino = BigInt(field.slice(1));
673
703
  }
704
+ return files;
705
+ }
706
+ // Exact canonical state/queue paths (and only their own WAL/SHM sidecars) must
707
+ // be opened by the owned PID with the inode now at that canonical path.
708
+ function verifyOpenedSqlite(files, home) {
709
+ const required = ['state_5.sqlite', 'queue_1.sqlite'];
674
710
  for (const file of required) {
675
711
  const expected = join(home, file);
676
712
  const opened = files.filter(row => row.name && [file, file + '-wal', file + '-shm'].includes(basename(row.name)));
677
713
  if (!opened.some(row => row.name === expected))
678
714
  throw new AppServerFault('storage_binding_unverified', false);
679
715
  for (const row of opened) {
680
- if (![expected, expected + '-wal', expected + '-shm'].includes(row.name))
716
+ if (row.deleted || ![expected, expected + '-wal', expected + '-shm'].includes(row.name))
681
717
  throw new AppServerFault('storage_binding_unverified', false);
682
718
  try {
683
719
  const canonical = lstatSync(row.name, { bigint: true });
@@ -690,6 +726,79 @@ async function verifyOwnedSqliteBinding(pid, home, deadlineMs) {
690
726
  }
691
727
  }
692
728
  }
729
+ // Synchronous native-profile I/O (executable digest, procfs walk) runs in an
730
+ // owned worker. Supervisor refusal boundary for that worker only: run()
731
+ // requests termination of its group (SIGKILL) at the original remaining
732
+ // budget and beforeDeadline() refuses at that deadline; actual reaping of a
733
+ // worker blocked in uninterruptible kernel I/O may occur later. Caller-side realpath/stat/lstat (executable identity,
734
+ // canonical SQLite paths) stay synchronous here, as on Darwin, and are only
735
+ // followed by deadline checks; they have no execution-time bound.
736
+ async function nativeWorker(args, deadlineMs) {
737
+ const extension = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
738
+ const worker = fileURLToPath(new URL('./linux-native-probe' + extension, import.meta.url));
739
+ return beforeDeadline(deadlineMs, async () => {
740
+ const result = await run(process.execPath, [...(extension === '.ts' ? ['--experimental-strip-types'] : []), worker, ...args], {
741
+ timeout: Math.max(1, deadlineMs - performance.now()), limit: 1024 * 1024,
742
+ env: { PATH: '/usr/bin:/bin', LC_ALL: 'C', LANG: 'C' }
743
+ });
744
+ if (result.code !== 0 || result.interrupted)
745
+ return undefined;
746
+ const value = JSON.parse(result.stdout);
747
+ return value && value.ok === true ? value : undefined;
748
+ }, 'unsupported_version');
749
+ }
750
+ // Complete pinned-executable digest within the original deadline.
751
+ export async function artifactDigest(path, deadlineMs, maxBytes = 512 * 1024 * 1024) {
752
+ const value = await nativeWorker(['digest', path, process.platform, process.arch, String(maxBytes)], deadlineMs);
753
+ if (performance.now() >= deadlineMs)
754
+ throw new AppServerFault('deadline', false);
755
+ if (typeof value?.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(value.sha256))
756
+ throw new AppServerFault('unsupported_version', false);
757
+ return value.sha256;
758
+ }
759
+ // Linux: read only the owned child's /proc entries. The executable inode is the
760
+ // selected native artifact, so a script/npm shim whose exe is an interpreter is
761
+ // refused rather than trusted to have exec'd the right storage owner. An
762
+ // injected reader (hermetic tests) runs in-process; production uses the worker.
763
+ export async function verifyProcfsSqliteBinding(pid, home, deadlineMs, binary, reader) {
764
+ if (!pid || pid < 2 || performance.now() >= deadlineMs)
765
+ throw new AppServerFault('storage_binding_unverified', false);
766
+ let files;
767
+ const uid = process.getuid?.();
768
+ if (uid === undefined)
769
+ throw new AppServerFault('storage_binding_unverified', false);
770
+ if (reader) {
771
+ try {
772
+ const exe = statSync(realpathSync(binary), { bigint: true });
773
+ files = procOwnedFiles(pid, process.pid, uid, { dev: exe.dev, ino: exe.ino }, reader);
774
+ }
775
+ catch {
776
+ throw new AppServerFault('storage_binding_unverified', false);
777
+ }
778
+ }
779
+ else {
780
+ let value;
781
+ try {
782
+ value = await nativeWorker(['bind', String(pid), String(process.pid), String(uid), binary], deadlineMs);
783
+ }
784
+ catch (error) {
785
+ throw error instanceof AppServerFault && error.code === 'deadline' ? error : new AppServerFault('storage_binding_unverified', false);
786
+ }
787
+ if (!Array.isArray(value?.files))
788
+ throw new AppServerFault('storage_binding_unverified', false);
789
+ try {
790
+ files = value.files.map(file => ({
791
+ name: file.name, dev: BigInt(file.dev), ino: BigInt(file.ino), deleted: file.deleted === true
792
+ }));
793
+ }
794
+ catch {
795
+ throw new AppServerFault('storage_binding_unverified', false);
796
+ }
797
+ }
798
+ if (performance.now() >= deadlineMs)
799
+ throw new AppServerFault('deadline', false);
800
+ verifyOpenedSqlite(files, home);
801
+ }
693
802
  // lsof field output escapes backslashes and non-ASCII bytes even with NUL field
694
803
  // delimiters. Decode the protected system tool's filename representation, then
695
804
  // compare exact canonical paths; never accept a prefix/substring match.
@@ -740,9 +849,14 @@ function verifyExecutableIdentity(binary, expected) {
740
849
  // in a network-denied synthetic home. This is not a live delivery/ACK claim.
741
850
  // Root integration owns generation, canonical home, storage and writer guards.
742
851
  // This function never invokes thread start/resume/read/list or a model turn.
743
- export async function nativeQueueOnce(options) {
744
- const platform = `${process.platform}-${process.arch}`;
745
- if (platform !== APP_SERVER_EVIDENCE.inspectedPlatform)
852
+ export function nativeQueueOnce(options) {
853
+ return nativeQueueOnceWithProfiles(options, NATIVE_PROFILES);
854
+ }
855
+ // Hermetic test hook: a synthetic, validated profile table exercises another
856
+ // platform's selection and binding path. Production uses only NATIVE_PROFILES.
857
+ export async function nativeQueueOnceWithProfiles(options, table) {
858
+ const profiles = validateNativeProfiles(table), platform = `${process.platform}-${process.arch}`;
859
+ if (!platformProfiled(platform, profiles))
746
860
  throw new AppServerFault('unsupported_transport', false);
747
861
  let original;
748
862
  try {
@@ -775,12 +889,32 @@ export async function nativeQueueOnce(options) {
775
889
  if (performance.now() >= options.deadlineMs)
776
890
  throw new AppServerFault('deadline', false);
777
891
  const nativeVersion = version.stdout.trim().slice('codex-cli '.length);
778
- if (version.interrupted || version.code !== 0 || !queueEvidence(nativeVersion) || version.stdout.trim() !== `codex-cli ${nativeVersion}`) {
892
+ const profile = selectNativeProfile({ platform, version: nativeVersion }, profiles);
893
+ if (version.interrupted || version.code !== 0 || !profile || version.stdout.trim() !== `codex-cli ${nativeVersion}`) {
779
894
  throw new AppServerFault('unsupported_version', false);
780
895
  }
781
896
  verifyExecutableIdentity(options.binary, binaryIdentity);
782
897
  if (performance.now() >= options.deadlineMs)
783
898
  throw new AppServerFault('deadline', false);
899
+ if (profile.artifact) {
900
+ // Pinned executable bytes, hashed within the original deadline; the stable
901
+ // identity check below proves the hashed inode is the one spawned next.
902
+ let digest;
903
+ try {
904
+ digest = await artifactDigest(realpathSync(options.binary), options.deadlineMs);
905
+ }
906
+ catch {
907
+ throw new AppServerFault(performance.now() >= options.deadlineMs ? 'deadline' : 'unsupported_version', false);
908
+ }
909
+ if (digest !== profile.artifact.sha256)
910
+ throw new AppServerFault('unsupported_version', false);
911
+ verifyExecutableIdentity(options.binary, binaryIdentity);
912
+ if (performance.now() >= options.deadlineMs)
913
+ throw new AppServerFault('deadline', false);
914
+ }
915
+ const bind = async (pid) => profile.storageBinding === 'linux_procfs' ?
916
+ verifyProcfsSqliteBinding(pid, original.codexHome, options.deadlineMs, options.binary) :
917
+ verifyOwnedSqliteBinding(pid, original.codexHome, options.deadlineMs);
784
918
  const transport = { qualification: 'native_queue_only_stdio',
785
919
  ...spawnOwnedStdio(options.binary, ['app-server', '--stdio', '-c', 'analytics.enabled=false',
786
920
  '-c', `sqlite_home=${JSON.stringify(original.codexHome)}`], env, original.codexHome) };
@@ -794,11 +928,11 @@ export async function nativeQueueOnce(options) {
794
928
  // Run after the LAST asynchronous owner verification. The durable guard
795
929
  // and owner probe can both await I/O and change canonical file bindings.
796
930
  verifyExecutableIdentity(options.binary, binaryIdentity);
797
- await verifyOwnedSqliteBinding(transport.pid, original.codexHome, options.deadlineMs);
931
+ await bind(transport.pid);
798
932
  }
799
933
  return valid;
800
- }, async () => { await options.beforeEffect(); effectGuarded = true; }, nativeVersion);
801
- await verifyOwnedSqliteBinding(transport.pid, original.codexHome, options.deadlineMs);
934
+ }, async () => { await options.beforeEffect(); effectGuarded = true; }, profile);
935
+ await bind(transport.pid);
802
936
  return await client.queueOnce({ clientUserMessageId: options.clientUserMessageId, message: options.message });
803
937
  }
804
938
  finally {
@@ -841,8 +975,9 @@ function releaseOwned(pid) {
841
975
  process.removeListener(name, terminateOwned);
842
976
  process.removeListener('exit', processExit);
843
977
  }
844
- // POSIX groups reap owned descendants. Only darwin-arm64 has native queue
845
- // mechanics qualification; Windows resource cleanup remains unqualified.
978
+ // POSIX groups reap owned descendants. Only darwin-arm64 rows are selectable;
979
+ // Linux uses the same owned group in hermetic and candidate checks. Windows
980
+ // resource cleanup remains unqualified.
846
981
  function spawnOwnedStdio(binary, args, env, cwd) {
847
982
  if (process.platform === 'win32')
848
983
  throw new AppServerFault('unsupported_transport', false);
package/dist/cli.js CHANGED
@@ -204,7 +204,17 @@ export function parse(args) {
204
204
  // An existing control master would bypass the hop entirely.
205
205
  if (values.has('--ssh-control-path'))
206
206
  throw new Refusal('conflicting_ssh_jump');
207
- // Win32-OpenSSH starts ProxyCommand without a POSIX shell; not yet proven.
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.
208
218
  if (process.platform === 'win32')
209
219
  throw new Refusal('ssh_jump_unsupported_platform');
210
220
  }
@@ -640,7 +650,7 @@ try {
640
650
  if (wireContext?.preparation)
641
651
  ({ value: result, exitCode } = await prepareHandoff(settings, undefined, options.values.get('--correlation-id'), handoffBudget));
642
652
  else if (enabled)
643
- ({ value: result, exitCode } = await handoffSend(settings, { correlationId: options.values.get('--correlation-id'), requestAck: options.flags.has('--request-ack'), observeDelivery: options.flags.has('--observe-delivery'), waitFor: options.values.get('--wait-for'), seconds: parseWaitTimeout(options.values.get('--wait-timeout') ?? '30'), payload: rawMessage, budget: handoffBudget, resultOverhead: Buffer.byteLength(JSON.stringify(routing)) + 1024 }));
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 }));
644
654
  else
645
655
  result = await send(settings);
646
656
  }
@@ -1,6 +1,10 @@
1
1
  // Private POSIX ledger. No native submission or transcript access occurs here.
2
2
  // Fencing assumes intact retained history: unmarked clones/rollbacks cannot be
3
- // detected by a local-only ledger. Windows ACL/bootstrap support is not claimed.
3
+ // detected by a local-only ledger. Windows ACL/bootstrap support is not claimed:
4
+ // src/windows.ts has a candidate owner-SID/protected-DACL/reparse guard, not
5
+ // connected here and not sufficient on its own; LockFileEx fencing, replace-over-open, durability and
6
+ // crash recovery have no native evidence, so every Windows ledger operation
7
+ // still fails closed (handoff_storage_unsupported) before touching storage.
4
8
  import { randomBytes, randomUUID, createHash, timingSafeEqual, createCipheriv, createDecipheriv } from 'node:crypto';
5
9
  import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
6
10
  import { isAbsolute, join, resolve } from 'node:path';
@@ -1,10 +1,13 @@
1
1
  import { HandoffLedger } from './handoff-ledger.js';
2
2
  import { HandoffBudget, type WaitFor } from './handoff.js';
3
+ import { type MetadataQualification } from './metadata-observation.js';
3
4
  import { type SendOptions } from './send.js';
5
+ import { type NativeProfile } from './native-profiles.js';
4
6
  export type HandoffOptions = {
5
7
  correlationId?: string;
6
8
  requestAck?: boolean;
7
9
  observeDelivery?: boolean;
10
+ remote?: boolean;
8
11
  waitFor?: Exclude<WaitFor, 'none'>;
9
12
  seconds?: number;
10
13
  ledgerPath?: string;
@@ -19,6 +22,7 @@ export type OperationResult = {
19
22
  export declare function ledgerPath(): string;
20
23
  export declare function privateMessage(path: string): string;
21
24
  export declare function correlationEnvelope(message: string, id: string): string;
25
+ export declare function observationQualification(nativeVersion: string, platform: string, remote: boolean, table?: readonly NativeProfile[]): MetadataQualification | undefined;
22
26
  export declare function prepareHandoff(options: SendOptions, path?: string, correlationId?: string, budget?: HandoffBudget): Promise<OperationResult>;
23
27
  export declare function handoffSend(options: SendOptions, handoffOptions: HandoffOptions): Promise<OperationResult>;
24
28
  export declare function waitForHandoff(ledger: HandoffLedger, id: string, goal: 'delivered' | 'acknowledged', budget: HandoffBudget): Promise<OperationResult>;
@@ -12,6 +12,7 @@ import { checkMessage, queueId, send } from './send.js';
12
12
  import { Refusal } from './discovery.js';
13
13
  import { HomeRefusal } from './writer.js';
14
14
  import { executable, run, UnknownOutcome } from './process.js';
15
+ import { currentPlatform, selectNativeProfile, validateNativeProfiles } from './native-profiles.js';
15
16
  export function ledgerPath() {
16
17
  const path = process.env.SESSION_PEER_HANDOFF_HOME ?? join(homedir(), '.local', 'state', 'session-peer-ts', 'handoff');
17
18
  if (!isAbsolute(path))
@@ -62,6 +63,27 @@ export function correlationEnvelope(message, id) {
62
63
  // A dedicated inert metadata line, not an executable Reply-To extension.
63
64
  return message + '\n\n---\nHandoff: ' + JSON.stringify({ schemaVersion: 1, correlationId: id });
64
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
+ }
65
87
  // Nonblocking ledger locks can contend across independent waiters. Retry only
66
88
  // within the caller's existing total budget; never replay a native operation.
67
89
  async function persistWithinBudget(budget, action) {
@@ -100,7 +122,7 @@ export async function handoffSend(options, handoffOptions) {
100
122
  const budget = handoffOptions.budget ?? new HandoffBudget(handoffOptions.seconds ?? 30);
101
123
  let handoff, snapshot;
102
124
  let scope, queueScope, deliverySupported = false, stopped = false, operationId;
103
- let qualification;
125
+ let qualification, ownerArgs = [];
104
126
  let original, fenced = false, knownNative;
105
127
  const ownWait = () => {
106
128
  if (handoff && operationId) {
@@ -130,7 +152,7 @@ export async function handoffSend(options, handoffOptions) {
130
152
  if (stopped || signal?.aborted || budget.observationRemainingMs() < 1)
131
153
  return false;
132
154
  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 } });
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 } });
134
156
  if (signal?.aborted || stopped || result.code !== 0 || result.interrupted)
135
157
  return false;
136
158
  try {
@@ -159,7 +181,9 @@ export async function handoffSend(options, handoffOptions) {
159
181
  queueScope = { codexHome: context.home, threadId: context.target, generation: context.generation, ownerIdentity: context.writerIdentity };
160
182
  const version = await run(executable(options.codexBin ?? 'codex'), ['--version'], { timeout: Math.min(1000, budget.observationRemainingMs()), limit: 4096 });
161
183
  const nativeVersion = !version.interrupted && version.code === 0 ? version.stdout.trim().replace(/^codex-cli /, '') : '';
162
- qualification = metadataQualification(nativeVersion);
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);
163
187
  if (qualification && nativeQueueCapability({ version: nativeVersion, platform: `${process.platform}-${process.arch}`, scope: queueScope }).queueSupported)
164
188
  deliverySupported = (await metadataCapability(scope, nativeVersion, budget, verifyOwner)).supported;
165
189
  }
@@ -315,11 +339,12 @@ export async function waitForHandoff(ledger, id, goal, budget) {
315
339
  const persist = (action) => persistWithinBudget(budget, action);
316
340
  const ownWait = () => { if (operationId)
317
341
  handoff = ledger.operationStatus(id, operationId); };
342
+ const ownerArgs = ownerProbeArgs(context?.qualification);
318
343
  const verifyOwner = async (scope, signal) => {
319
344
  if (stopped || signal.aborted || budget.observationRemainingMs() < 1)
320
345
  return false;
321
346
  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 } });
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 } });
323
348
  if (stopped || signal.aborted || result.code !== 0 || result.interrupted)
324
349
  return false;
325
350
  try {
@@ -4,6 +4,15 @@
4
4
  // separate groups and defeat the supervisor's cleanup.
5
5
  // Keep the sample/identity algorithm aligned with writer.ts inspectWriter.
6
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.
7
16
  import { spawn } from 'node:child_process';
8
17
  import { createHash } from 'node:crypto';
9
18
  import { lstatSync, realpathSync } from 'node:fs';
@@ -58,8 +67,10 @@ async function main(args) {
58
67
  const refusal = (error) => ({ schemaVersion: 1, ok: false, error });
59
68
  if (!['darwin', 'linux'].includes(process.platform) || process.getuid?.() === undefined)
60
69
  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 ||
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 ||
63
74
  !/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(rawId))
64
75
  return refusal('writer_probe_invalid');
65
76
  try {
@@ -68,10 +79,20 @@ async function main(args) {
68
79
  return refusal('writer_probe_unverified');
69
80
  // Dynamic import keeps dependency failures inside the sanitized boundary.
70
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
+ };
71
92
  async function sample() {
72
93
  const state = await probeLock(path);
73
94
  if (state !== 'held')
74
- return { state, fingerprint: state === 'free' ? fingerprint(path) : '', owners: [], valid: true };
95
+ return { state, fingerprint: state === 'free' ? fingerprint(path) : '', owners: [], valid: true, kernel: undefined };
75
96
  const stamp = fingerprint(path);
76
97
  const listed = await command('lsof', ['-nP', '-F0pcu', '--', path]);
77
98
  const owners = [];
@@ -93,7 +114,7 @@ async function main(args) {
93
114
  }
94
115
  // Ambiguous owners need no further tools and cannot produce a generation.
95
116
  if (owners.length !== 1)
96
- return { state, fingerprint: stamp, owners, valid: false };
117
+ return { state, fingerprint: stamp, owners, valid: false, kernel: undefined };
97
118
  for (const owner of owners) {
98
119
  if (!Number.isSafeInteger(owner.pid) || owner.pid <= 1)
99
120
  continue;
@@ -101,7 +122,7 @@ async function main(args) {
101
122
  if (started.valid)
102
123
  owner.start = started.stdout.trim();
103
124
  }
104
- return { state, fingerprint: stamp, owners, valid: listed.valid };
125
+ return { state, fingerprint: stamp, owners, valid: listed.valid, kernel: inspect(owners[0].pid) };
105
126
  }
106
127
  const before = await sample();
107
128
  if (before.state !== 'held')
@@ -111,7 +132,9 @@ async function main(args) {
111
132
  if (!before.valid || !after.valid || before.state !== after.state || before.fingerprint !== after.fingerprint ||
112
133
  before.owners.length !== 1 || after.owners.length !== 1 || JSON.stringify(before.owners) !== JSON.stringify(after.owners) ||
113
134
  !owner?.start || !safe(owner.start, 256) || uid === undefined || owner.uid !== uid ||
114
- !/^codex(?:\.exe|-|$)/i.test(owner.command ?? '') || !owned(path, false))
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)))
115
138
  return refusal('writer_probe_unverified');
116
139
  const identity = JSON.stringify({ fingerprint: after.fingerprint, ...owner });
117
140
  return { schemaVersion: 1, ok: true, generation: createHash('sha256').update(identity).digest('hex') };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,51 @@
1
+ // Owned one-shot worker for synchronous native-profile I/O: the complete
2
+ // executable digest and the Linux owned-child procfs/canonical-path binding.
3
+ // The caller runs it with process.run() under the ORIGINAL remaining budget;
4
+ // at that deadline it requests termination of the worker's process group and
5
+ // the caller refuses the effect. Actual reaping of a process blocked in
6
+ // uninterruptible kernel I/O may occur later, when the kernel returns; the
7
+ // caller's effect decision never waits on it beyond its own deadline check. Output is closed JSON returned only to the
8
+ // caller (opened paths stay in memory, never in CLI output or logs).
9
+ import { createHash } from 'node:crypto';
10
+ import { closeSync, openSync, readSync, realpathSync, statSync } from 'node:fs';
11
+ import { isAbsolute } from 'node:path';
12
+ import { nativeExecutable, procOwnedFiles } from './linux-proc.js';
13
+ const integer = (value) => /^[1-9]\d{0,9}$/.test(value ?? '') ? Number(value) : NaN;
14
+ function digest(path, platform, arch, maxBytes) {
15
+ const fd = openSync(path, 'r');
16
+ try {
17
+ const header = Buffer.alloc(20);
18
+ if (readSync(fd, header, 0, 20, 0) !== 20 || !nativeExecutable(header, platform, arch))
19
+ throw new Error('format');
20
+ const hash = createHash('sha256'), chunk = Buffer.alloc(1024 * 1024);
21
+ let total = 0;
22
+ for (let read; (read = readSync(fd, chunk, 0, chunk.length, null)) > 0;) {
23
+ total += read;
24
+ if (total > maxBytes)
25
+ throw new Error('size');
26
+ hash.update(chunk.subarray(0, read));
27
+ }
28
+ return hash.digest('hex');
29
+ }
30
+ finally {
31
+ closeSync(fd);
32
+ }
33
+ }
34
+ function main(args) {
35
+ try {
36
+ if (args[0] === 'digest' && args.length === 5 && isAbsolute(args[1])) {
37
+ return { ok: true, sha256: digest(args[1], args[2], args[3], integer(args[4])) };
38
+ }
39
+ if (args[0] === 'bind' && args.length === 5 && isAbsolute(args[4])) {
40
+ const [pid, parent, uid] = [integer(args[1]), integer(args[2]), Number(args[3])];
41
+ if (!Number.isSafeInteger(uid) || uid < 0 || uid !== process.getuid?.())
42
+ throw new Error('uid');
43
+ const exe = statSync(realpathSync(args[4]), { bigint: true });
44
+ const files = procOwnedFiles(pid, parent, uid, { dev: exe.dev, ino: exe.ino });
45
+ return { ok: true, files: files.map(file => ({ name: file.name, dev: file.dev.toString(), ino: file.ino.toString(), deleted: file.deleted })) };
46
+ }
47
+ }
48
+ catch { /* Closed refusal below; no path or native diagnostic is returned. */ }
49
+ return { ok: false };
50
+ }
51
+ process.stdout.write(JSON.stringify(main(process.argv.slice(2))) + '\n');
@@ -0,0 +1,55 @@
1
+ export type ProcStat = {
2
+ dev: bigint;
3
+ ino: bigint;
4
+ };
5
+ export type ProcReader = {
6
+ readFile(path: string): string;
7
+ readdir(path: string): string[];
8
+ readlink(path: string): string;
9
+ stat(path: string): ProcStat;
10
+ };
11
+ export declare const procfs: ProcReader;
12
+ export declare class ProcRefusal extends Error {
13
+ }
14
+ export declare function parseProcStat(text: string): {
15
+ state: string;
16
+ ppid: number;
17
+ pgrp: number;
18
+ starttime: string;
19
+ };
20
+ export declare function parseProcStatusUid(text: string): number;
21
+ export declare function devParts(dev: bigint): {
22
+ major: bigint;
23
+ minor: bigint;
24
+ };
25
+ export type ProcLock = {
26
+ blocked: boolean;
27
+ kind: string;
28
+ access: string;
29
+ pid: number;
30
+ major: bigint;
31
+ minor: bigint;
32
+ ino: bigint;
33
+ };
34
+ export declare function procLockHolders(text: string, target: ProcStat): ProcLock[];
35
+ export declare function procFlockOwner(path: string, reader?: ProcReader): number;
36
+ export type ProcOwner = {
37
+ pid: number;
38
+ ppid: number;
39
+ pgrp: number;
40
+ state: string;
41
+ starttime: string;
42
+ uid: number;
43
+ exe?: ProcStat;
44
+ };
45
+ export declare function procOwner(pid: number, reader?: ProcReader, executable?: boolean): ProcOwner;
46
+ export declare const sameOwner: (left: ProcOwner, right: ProcOwner) => boolean;
47
+ export type OpenedFile = {
48
+ name: string;
49
+ dev: bigint;
50
+ ino: bigint;
51
+ deleted: boolean;
52
+ };
53
+ export declare function procOpenedFiles(pid: number, reader?: ProcReader, limit?: number): OpenedFile[];
54
+ export declare function procOwnedFiles(pid: number, parentPid: number, uid: number, executable: ProcStat, reader?: ProcReader): OpenedFile[];
55
+ export declare function nativeExecutable(header: Buffer, platform: string, arch: string): boolean;