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,150 @@
1
+ // Linux procfs evidence for exact native profiles. These readers inspect only
2
+ // a supplied PID (an owned app-server child or the single lsof-reported lock
3
+ // owner) and the kernel lock table; they never scan /proc/<pid> inventories.
4
+ // All parsing is closed: an unrecognized row that names the inspected inode, a
5
+ // changed start time, a foreign UID or an unexpected executable refuses.
6
+ // Exact profile rows select this machinery (see native-profiles.ts); it is
7
+ // unit-tested with injected readers. Synchronous reads here run in the owned
8
+ // linux-native-probe worker under the caller's original deadline, or inside
9
+ // the already deadline-bounded writer-probe process.
10
+ import { readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs';
11
+ export const procfs = {
12
+ readFile: path => readFileSync(path, 'utf8'),
13
+ readdir: path => readdirSync(path),
14
+ readlink: path => readlinkSync(path),
15
+ stat: path => { const s = statSync(path, { bigint: true }); return { dev: s.dev, ino: s.ino }; },
16
+ };
17
+ export class ProcRefusal extends Error {
18
+ }
19
+ const refuse = () => { throw new ProcRefusal('procfs_evidence_unverified'); };
20
+ const gone = (error) => ['ENOENT', 'ESRCH'].includes(error.code ?? '');
21
+ const decimal = (value) => /^(?:0|[1-9]\d{0,18})$/.test(value ?? '') ? BigInt(value) : refuse();
22
+ // /proc/<pid>/stat: comm may contain spaces and ')' so split after the LAST ')'.
23
+ // Fields after comm start at field 3 (state); starttime is field 22.
24
+ export function parseProcStat(text) {
25
+ const end = text.lastIndexOf(')');
26
+ if (end < 0 || text[end + 1] !== ' ')
27
+ refuse();
28
+ const fields = text.slice(end + 2).replace(/\n$/, '').split(' ');
29
+ if (fields.length < 20 || !/^[A-Za-z]$/.test(fields[0]))
30
+ refuse();
31
+ return { state: fields[0], ppid: Number(decimal(fields[1])), pgrp: Number(decimal(fields[2])), starttime: decimal(fields[19]).toString() };
32
+ }
33
+ // Real, effective, saved and filesystem UIDs must all be the caller's UID.
34
+ export function parseProcStatusUid(text) {
35
+ const rows = text.split('\n').filter(line => line.startsWith('Uid:'));
36
+ const match = rows.length === 1 ? /^Uid:\t(\d+)\t(\d+)\t(\d+)\t(\d+)$/.exec(rows[0]) : null;
37
+ if (!match || new Set(match.slice(1)).size !== 1)
38
+ refuse();
39
+ return Number(decimal(match[1]));
40
+ }
41
+ // glibc gnu_dev_major/minor, matching libuv's makedev() for statx results.
42
+ export function devParts(dev) {
43
+ return { major: ((dev >> 8n) & 0xfffn) | ((dev >> 32n) & ~0xfffn), minor: (dev & 0xffn) | ((dev >> 12n) & ~0xffn) };
44
+ }
45
+ // fs/locks.c lock_get_status: "<id>: [-> ]<KIND> <MODE> <ACCESS> <pid> <maj>:<min>:<ino> <start> <end|EOF>".
46
+ // Rows for other inodes may use unknown kinds and are ignored only when they
47
+ // cannot name the inspected inode.
48
+ export function procLockHolders(text, target) {
49
+ const { major, minor } = devParts(target.dev), rows = [];
50
+ for (const line of text.split('\n')) {
51
+ if (!line)
52
+ continue;
53
+ const match = /^\d+: (?:\s*(->)\s+)?(\S+)\s+(\S+)\s+(\S+)\s+(-?\d+) ([0-9a-f]+):([0-9a-f]+):(\d+) \d+ (?:\d+|EOF)$/.exec(line);
54
+ if (!match) {
55
+ if (line.includes(':' + target.ino.toString() + ' '))
56
+ refuse();
57
+ continue;
58
+ }
59
+ const row = { blocked: match[1] === '->', kind: match[2], access: match[4], pid: Number(match[5]),
60
+ major: BigInt('0x' + match[6]), minor: BigInt('0x' + match[7]), ino: decimal(match[8]) };
61
+ if (row.ino === target.ino && row.major === major && row.minor === minor)
62
+ rows.push(row);
63
+ }
64
+ return rows;
65
+ }
66
+ // Exactly one granted exclusive flock(2) holder, as Rust std File::try_lock
67
+ // takes on Unix; POSIX/OFD/shared/lease rows or another holder are ambiguous.
68
+ export function procFlockOwner(path, reader = procfs) {
69
+ const target = reader.stat(path), rows = procLockHolders(reader.readFile('/proc/locks'), target);
70
+ const granted = rows.filter(row => !row.blocked);
71
+ if (rows.some(row => row.kind !== 'FLOCK') || granted.length !== 1 || granted[0].access !== 'WRITE' ||
72
+ !Number.isSafeInteger(granted[0].pid) || granted[0].pid <= 1)
73
+ refuse();
74
+ return granted[0].pid;
75
+ }
76
+ export function procOwner(pid, reader = procfs, executable = false) {
77
+ if (!Number.isSafeInteger(pid) || pid <= 1)
78
+ refuse();
79
+ try {
80
+ const stat = parseProcStat(reader.readFile(`/proc/${pid}/stat`)), uid = parseProcStatusUid(reader.readFile(`/proc/${pid}/status`));
81
+ if (['Z', 'X', 'x'].includes(stat.state))
82
+ refuse();
83
+ return { pid, ...stat, uid, ...(executable ? { exe: reader.stat(`/proc/${pid}/exe`) } : {}) };
84
+ }
85
+ catch (error) {
86
+ if (error instanceof ProcRefusal)
87
+ throw error;
88
+ return refuse();
89
+ }
90
+ }
91
+ export const sameOwner = (left, right) => left.pid === right.pid && left.ppid === right.ppid &&
92
+ left.pgrp === right.pgrp && left.starttime === right.starttime && left.uid === right.uid &&
93
+ left.exe?.dev === right.exe?.dev && left.exe?.ino === right.exe?.ino;
94
+ // Only regular absolute paths are retained; sockets, pipes and anon inodes are
95
+ // not storage. A descriptor closed during the walk is not opened state.
96
+ export function procOpenedFiles(pid, reader = procfs, limit = 4096) {
97
+ let entries;
98
+ try {
99
+ entries = reader.readdir(`/proc/${pid}/fd`);
100
+ }
101
+ catch {
102
+ return refuse();
103
+ }
104
+ if (entries.length > limit || entries.some(entry => !/^(?:0|[1-9]\d{0,9})$/.test(entry)))
105
+ refuse();
106
+ const files = [];
107
+ for (const fd of entries) {
108
+ let name, stat;
109
+ try {
110
+ name = reader.readlink(`/proc/${pid}/fd/${fd}`);
111
+ if (!name.startsWith('/'))
112
+ continue;
113
+ stat = reader.stat(`/proc/${pid}/fd/${fd}`);
114
+ }
115
+ catch (error) {
116
+ if (gone(error))
117
+ continue;
118
+ return refuse();
119
+ }
120
+ const deleted = name.endsWith(' (deleted)');
121
+ files.push({ name: deleted ? name.slice(0, -' (deleted)'.length) : name, dev: stat.dev, ino: stat.ino, deleted });
122
+ }
123
+ return files;
124
+ }
125
+ // Owned app-server binding: this process's direct child, its own detached
126
+ // group leader, same UID in all four slots, executing exactly the selected
127
+ // executable inode, unchanged (PID reuse/exec) across the descriptor walk.
128
+ export function procOwnedFiles(pid, parentPid, uid, executable, reader = procfs) {
129
+ const before = procOwner(pid, reader, true);
130
+ if (before.ppid !== parentPid || before.pgrp !== pid || before.uid !== uid ||
131
+ before.exe.dev !== executable.dev || before.exe.ino !== executable.ino)
132
+ refuse();
133
+ const files = procOpenedFiles(pid, reader);
134
+ if (!sameOwner(before, procOwner(pid, reader, true)))
135
+ refuse();
136
+ return files;
137
+ }
138
+ // Host-native 64-bit little-endian executable header: ELF on Linux, thin
139
+ // Mach-O on Darwin. The complete byte digest is the artifact identity.
140
+ const machines = { arm64: [183, 0x0100000c], x64: [62, 0x01000007] };
141
+ export function nativeExecutable(header, platform, arch) {
142
+ const machine = machines[arch];
143
+ if (!machine || header.length < 20)
144
+ return false;
145
+ if (platform === 'linux')
146
+ return header.readUInt32BE(0) === 0x7f454c46 && header[4] === 2 && header[5] === 1 &&
147
+ [2, 3].includes(header.readUInt16LE(16)) && header.readUInt16LE(18) === machine[0];
148
+ return platform === 'darwin' && header.readUInt32LE(0) === 0xfeedfacf && header.readUInt32LE(4) === machine[1] &&
149
+ header.readUInt32LE(12) === 2;
150
+ }
@@ -0,0 +1,49 @@
1
+ import { type NativeProfile } from './native-profiles.js';
2
+ export declare const METADATA_SOURCE: Readonly<{
3
+ version: "0.160.1";
4
+ commit: "d27764b82f7118f674371e6d6e76271d9d606edb";
5
+ database: "thread_history_1.sqlite";
6
+ recentUsers: 256;
7
+ maxCellBytes: number;
8
+ childMs: 1000;
9
+ }>;
10
+ export type MetadataScope = Readonly<{
11
+ home: string;
12
+ threadId: string;
13
+ generation: string | null;
14
+ }>;
15
+ export declare const METADATA_RESUME_QUALIFICATION: Readonly<{
16
+ version: "0.160.1";
17
+ commit: "d27764b82f7118f674371e6d6e76271d9d606edb";
18
+ platform: "darwin-arm64";
19
+ }>;
20
+ export type MetadataQualification = Readonly<{
21
+ version: string;
22
+ commit: string;
23
+ platform: string;
24
+ }>;
25
+ export declare function metadataQualification(version: string, platform?: string): MetadataQualification | undefined;
26
+ export type MetadataBudget = {
27
+ observationRemainingMs(): number;
28
+ };
29
+ export type VerifyMetadataOwner = (scope: MetadataScope, signal: AbortSignal) => boolean | Promise<boolean>;
30
+ export type MetadataReason = 'metadata_version_unsupported' | 'metadata_platform_unsupported' | 'metadata_scope_invalid' | 'metadata_storage_untrusted' | 'metadata_history_unavailable' | 'metadata_schema_unsupported' | 'metadata_owner_changed' | 'metadata_deadline' | 'metadata_probe_failed' | 'metadata_probe_stopped' | 'metadata_ambiguous';
31
+ export type MetadataCapability = {
32
+ supported: boolean;
33
+ reason?: MetadataReason;
34
+ };
35
+ export type MetadataObservation = MetadataCapability & {
36
+ injectionObserved: boolean;
37
+ clientUserMessageId?: string;
38
+ turn?: {
39
+ id: string;
40
+ status: 'running' | 'completed' | 'failed' | 'interrupted' | 'unknown';
41
+ };
42
+ };
43
+ export declare function metadataCapability(scope: MetadataScope, version: string, budget: MetadataBudget | undefined, verifyOwner: VerifyMetadataOwner, profiles?: readonly NativeProfile[]): Promise<MetadataCapability>;
44
+ export declare function observeMetadata(scope: MetadataScope & {
45
+ clientUserMessageId: string;
46
+ }, budget: MetadataBudget, verifyOwner: VerifyMetadataOwner): Promise<MetadataObservation>;
47
+ export declare function resumeMetadataObservation(scope: MetadataScope & {
48
+ clientUserMessageId: string;
49
+ }, qualification: MetadataQualification, budget: MetadataBudget, verifyOwner: VerifyMetadataOwner): Promise<MetadataObservation>;
@@ -0,0 +1,250 @@
1
+ // Opt-in, metadata-only observation for the exact qualified Codex store below.
2
+ // No transcript, native client, warming, migration or receipt bootstrap is used.
3
+ import childProcess from 'node:child_process';
4
+ import { isAbsolute, join, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { NATIVE_PROFILES, validateNativeProfiles } from './native-profiles.js';
7
+ export const METADATA_SOURCE = Object.freeze({ version: '0.160.1',
8
+ commit: 'd27764b82f7118f674371e6d6e76271d9d606edb',
9
+ database: 'thread_history_1.sqlite', recentUsers: 256, maxCellBytes: 256 * 1024, childMs: 1000 });
10
+ // Persist this private qualification only after the original native queue and
11
+ // metadata preflight have both selected this exact source. A version read from
12
+ // today's PATH, a caller-supplied flag or the metadata schema alone cannot
13
+ // establish how an older intent was submitted.
14
+ export const METADATA_RESUME_QUALIFICATION = Object.freeze({ version: METADATA_SOURCE.version,
15
+ commit: METADATA_SOURCE.commit, platform: 'darwin-arm64' });
16
+ // Exact native qualification is separate from POSIX structural-store fixtures.
17
+ // No version range, current PATH inference or schema-only upgrade is permitted.
18
+ // Rows are projected from the exact platform-aware native profile table.
19
+ const metadataQualifications = Object.freeze(NATIVE_PROFILES.map(row => row.platform === METADATA_RESUME_QUALIFICATION.platform && row.version === METADATA_RESUME_QUALIFICATION.version &&
20
+ row.commit === METADATA_RESUME_QUALIFICATION.commit ? METADATA_RESUME_QUALIFICATION :
21
+ Object.freeze({ version: row.version, commit: row.commit, platform: row.platform })));
22
+ // With a platform, selection is the exact (platform, version) row. Without one
23
+ // (structural store checks only) a version must name exactly one platform's row.
24
+ export function metadataQualification(version, platform) {
25
+ if (typeof version !== 'string' || (platform !== undefined && typeof platform !== 'string'))
26
+ return undefined;
27
+ const exact = version.startsWith('codex-cli ') ? version.slice('codex-cli '.length) : version;
28
+ const rows = metadataQualifications.filter(profile => profile.version === exact && (platform === undefined || profile.platform === platform));
29
+ return rows.length === 1 ? rows[0] : undefined;
30
+ }
31
+ const reasons = ['metadata_version_unsupported', 'metadata_platform_unsupported',
32
+ 'metadata_scope_invalid', 'metadata_storage_untrusted', 'metadata_history_unavailable', 'metadata_schema_unsupported',
33
+ 'metadata_owner_changed', 'metadata_deadline', 'metadata_probe_failed', 'metadata_probe_stopped', 'metadata_ambiguous'];
34
+ const safe = (value, limit) => typeof value === 'string' && value.length > 0 &&
35
+ Buffer.byteLength(value) <= limit && !/[\x00-\x1f\x7f-\x9f]/.test(value) &&
36
+ !/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value);
37
+ const uuid = (value) => /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(value);
38
+ const unsupported = (reason) => ({ supported: false, injectionObserved: false, reason });
39
+ function remaining(budget) {
40
+ const value = budget?.observationRemainingMs() ?? 3000;
41
+ return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
42
+ }
43
+ async function owner(scope, verify, budget) {
44
+ const duration = Math.min(METADATA_SOURCE.childMs, remaining(budget));
45
+ if (duration < 1)
46
+ return false;
47
+ const controller = new AbortController();
48
+ let timer;
49
+ try {
50
+ return await Promise.race([Promise.resolve().then(() => verify(scope, controller.signal)).then(value => value === true),
51
+ new Promise(resolve => { timer = setTimeout(() => { controller.abort(); resolve(false); }, duration); })]);
52
+ }
53
+ catch {
54
+ return false;
55
+ }
56
+ finally {
57
+ if (timer)
58
+ clearTimeout(timer);
59
+ controller.abort();
60
+ }
61
+ }
62
+ function probe(request, budget) {
63
+ const duration = Math.min(METADATA_SOURCE.childMs, remaining(budget));
64
+ if (duration < 1)
65
+ return Promise.resolve(unsupported('metadata_deadline'));
66
+ const extension = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
67
+ const worker = fileURLToPath(new URL('./handoff-observer-probe' + extension, import.meta.url));
68
+ return new Promise(resolve => {
69
+ let child;
70
+ try {
71
+ child = childProcess.spawn(process.execPath, [...(extension === '.ts' ? ['--experimental-strip-types'] : []), worker], {
72
+ detached: true, shell: false, stdio: ['pipe', 'pipe', 'pipe'],
73
+ env: { ...process.env, NODE_OPTIONS: undefined, NODE_PATH: undefined },
74
+ });
75
+ }
76
+ catch {
77
+ resolve(unsupported('metadata_probe_failed'));
78
+ return;
79
+ }
80
+ let finished = false, stopped = false, total = 0, output = '', stopReason = 'metadata_probe_failed';
81
+ let grace;
82
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
83
+ const handlers = new Map();
84
+ const reap = () => { if (child.pid)
85
+ try {
86
+ process.kill(-child.pid, 'SIGKILL');
87
+ }
88
+ catch { /* Already gone. */ } };
89
+ const finish = (result) => {
90
+ if (finished)
91
+ return;
92
+ finished = true;
93
+ clearTimeout(timer);
94
+ if (grace)
95
+ clearTimeout(grace);
96
+ for (const signal of signals)
97
+ process.removeListener(signal, handlers.get(signal));
98
+ resolve(result);
99
+ };
100
+ const stop = (reason) => {
101
+ if (stopped || finished)
102
+ return;
103
+ stopped = true;
104
+ stopReason = reason;
105
+ reap();
106
+ child.stdin.destroy();
107
+ child.stdout.destroy();
108
+ child.stderr.destroy();
109
+ // Cleanup grace stays inside the available original observation budget.
110
+ grace = setTimeout(() => finish(unsupported(reason)), Math.min(100, remaining(budget)));
111
+ };
112
+ const interrupted = (signal) => {
113
+ const sole = process.listenerCount(signal) === 1;
114
+ stop('metadata_probe_stopped');
115
+ if (sole) {
116
+ for (const name of signals)
117
+ process.removeListener(name, handlers.get(name));
118
+ process.kill(process.pid, signal);
119
+ }
120
+ };
121
+ const timer = setTimeout(() => stop('metadata_deadline'), duration);
122
+ for (const signal of signals) {
123
+ const handler = () => interrupted(signal);
124
+ handlers.set(signal, handler);
125
+ process.on(signal, handler);
126
+ }
127
+ child.stdin.on('error', () => { });
128
+ child.stdout.setEncoding('utf8');
129
+ child.stdout.on('data', (part) => { total += Buffer.byteLength(part); if (total > 4096)
130
+ stop('metadata_probe_failed');
131
+ else
132
+ output += part; });
133
+ // Drain without retaining or logging SQLite/native diagnostics.
134
+ child.stderr.on('data', (part) => { total += part.length; if (total > 8192)
135
+ stop('metadata_probe_failed'); });
136
+ child.once('error', () => stop('metadata_probe_failed'));
137
+ child.once('close', code => {
138
+ if (stopped) {
139
+ finish(unsupported(stopReason));
140
+ return;
141
+ }
142
+ if (code !== 0) {
143
+ finish(unsupported('metadata_probe_failed'));
144
+ return;
145
+ }
146
+ try {
147
+ const value = JSON.parse(output);
148
+ if (!value || typeof value.supported !== 'boolean' || typeof value.injectionObserved !== 'boolean' ||
149
+ Object.keys(value).some(key => !['supported', 'injectionObserved', 'reason', 'clientUserMessageId', 'turn', 'storageStamp'].includes(key)))
150
+ throw new Error();
151
+ if (!value.supported) {
152
+ if (value.injectionObserved || !reasons.includes(value.reason) || value.clientUserMessageId !== undefined ||
153
+ value.turn !== undefined || value.storageStamp !== undefined)
154
+ throw new Error();
155
+ }
156
+ else if (value.reason !== undefined || !/^[a-f0-9]{64}$/.test(value.storageStamp ?? '') ||
157
+ (request.expectedStorageStamp !== undefined && value.storageStamp !== request.expectedStorageStamp))
158
+ throw new Error();
159
+ if (value.injectionObserved) {
160
+ if (value.clientUserMessageId !== request.clientUserMessageId || !safe(value.clientUserMessageId, 128) || !value.turn ||
161
+ Object.keys(value.turn).some(key => !['id', 'status'].includes(key)) || !safe(value.turn.id, 128) ||
162
+ !['running', 'completed', 'failed', 'interrupted', 'unknown'].includes(value.turn.status))
163
+ throw new Error();
164
+ }
165
+ else if (value.clientUserMessageId !== undefined || value.turn !== undefined)
166
+ throw new Error();
167
+ finish(value);
168
+ }
169
+ catch {
170
+ finish(unsupported('metadata_probe_failed'));
171
+ }
172
+ });
173
+ child.stdin.end(JSON.stringify(request));
174
+ });
175
+ }
176
+ async function inspect(scope, mode, budget, verify, clientUserMessageId) {
177
+ if (!['darwin', 'linux'].includes(process.platform) || process.getuid?.() === undefined)
178
+ return unsupported('metadata_platform_unsupported');
179
+ if (!scope || !safe(scope.home, 2048) || !safe(scope.threadId, 128) || !uuid(scope.threadId) ||
180
+ !safe(scope.generation, 256) || (mode === 'observe' && !safe(clientUserMessageId, 128)))
181
+ return unsupported('metadata_scope_invalid');
182
+ const original = Object.freeze({ home: scope.home, threadId: scope.threadId, generation: scope.generation });
183
+ if (remaining(budget) < 1)
184
+ return unsupported('metadata_deadline');
185
+ // Filesystem calls can block on a disconnected volume. Every validation and
186
+ // inode comparison is performed inside a deadline-owned worker, never here.
187
+ const request = { database: join(original.home, METADATA_SOURCE.database), threadId: original.threadId.toLowerCase() };
188
+ const before = await probe({ ...request, mode: 'snapshot' }, budget);
189
+ if (!before.supported)
190
+ return before;
191
+ if (!(await owner(original, verify, budget)))
192
+ return unsupported(remaining(budget) < 1 ? 'metadata_deadline' : 'metadata_owner_changed');
193
+ const result = await probe({ ...request, mode, expectedStorageStamp: before.storageStamp,
194
+ ...(clientUserMessageId === undefined ? {} : { clientUserMessageId }) }, budget);
195
+ if (!result.supported)
196
+ return result;
197
+ if (!(await owner(original, verify, budget)))
198
+ return unsupported(remaining(budget) < 1 ? 'metadata_deadline' : 'metadata_owner_changed');
199
+ const after = await probe({ ...request, mode: 'snapshot', expectedStorageStamp: before.storageStamp }, budget);
200
+ if (!after.supported)
201
+ return after;
202
+ if (remaining(budget) < 1)
203
+ return unsupported('metadata_deadline');
204
+ const { storageStamp: _privateStamp, ...publicResult } = result;
205
+ return publicResult;
206
+ }
207
+ // `profiles` is a hermetic test hook (validated synthetic tables only).
208
+ export async function metadataCapability(scope, version, budget, verifyOwner, profiles = NATIVE_PROFILES) {
209
+ // Structural store check: any exact row's version. Platform selection is the
210
+ // caller's exact metadataQualification(version, platform), never inferred here.
211
+ const exact = typeof version === 'string' && version.startsWith('codex-cli ') ? version.slice('codex-cli '.length) : version;
212
+ if (!validateNativeProfiles(profiles).some(row => row.version === exact))
213
+ return { supported: false, reason: 'metadata_version_unsupported' };
214
+ const result = await inspect(scope, 'capability', budget, verifyOwner);
215
+ return { supported: result.supported, ...(result.reason === undefined ? {} : { reason: result.reason }) };
216
+ }
217
+ export function observeMetadata(scope, budget, verifyOwner) {
218
+ return inspect(scope, 'observe', budget, verifyOwner, scope.clientUserMessageId);
219
+ }
220
+ // Read-only reconciliation of a retained, positively submitted intent. The
221
+ // ledger caller supplies the ORIGINAL binding/qualification and must neither
222
+ // infer missing submission evidence nor replace the generation with today's
223
+ // owner. This API never finds or invokes Codex and never submits or warms data.
224
+ export function resumeMetadataObservation(scope, qualification, budget, verifyOwner) {
225
+ if (!qualification || typeof qualification !== 'object' || Array.isArray(qualification) ||
226
+ Object.keys(qualification).length !== 3 ||
227
+ Object.keys(qualification).some(key => !['version', 'commit', 'platform'].includes(key))) {
228
+ return Promise.resolve(unsupported('metadata_scope_invalid'));
229
+ }
230
+ // Retained records use the canonical native version, not a CLI banner. The
231
+ // exact retained (version, commit, platform) row is required; a same-version
232
+ // row for another platform is not inherited.
233
+ const versions = metadataQualifications.filter(row => row.version === qualification.version);
234
+ if (!versions.length) {
235
+ return Promise.resolve(unsupported('metadata_version_unsupported'));
236
+ }
237
+ const commits = versions.filter(row => row.commit === qualification.commit);
238
+ if (!commits.length) {
239
+ return Promise.resolve(unsupported('metadata_schema_unsupported'));
240
+ }
241
+ if (!commits.some(row => row.platform === qualification.platform) ||
242
+ qualification.platform !== `${process.platform}-${process.arch}`) {
243
+ return Promise.resolve(unsupported('metadata_platform_unsupported'));
244
+ }
245
+ if (!scope || !safe(scope.home, 2048) || !isAbsolute(scope.home) || resolve(scope.home) !== scope.home ||
246
+ typeof scope.generation !== 'string' || !/^[a-f0-9]{64}$/.test(scope.generation)) {
247
+ return Promise.resolve(unsupported('metadata_scope_invalid'));
248
+ }
249
+ return inspect(scope, 'observe', budget, verifyOwner, scope.clientUserMessageId);
250
+ }
@@ -0,0 +1,25 @@
1
+ export type NativeProfile = Readonly<{
2
+ platform: string;
3
+ version: string;
4
+ commit: string;
5
+ platformOs: 'macos' | 'linux';
6
+ storageBinding: 'darwin_lsof' | 'linux_procfs';
7
+ ownerInspection: 'lsof_ps' | 'lsof_ps_procfs_locks';
8
+ sshDestination: boolean;
9
+ artifact: Readonly<{
10
+ target: string;
11
+ sha256: string;
12
+ }> | null;
13
+ }>;
14
+ export type NativeProfileQuery = Readonly<{
15
+ platform: string;
16
+ version: string;
17
+ }>;
18
+ export type NativeProfileRefusal = 'version_unsupported' | 'platform_unsupported';
19
+ export declare function validateNativeProfiles(table: readonly NativeProfile[]): readonly NativeProfile[];
20
+ export declare const NATIVE_PROFILES: readonly NativeProfile[];
21
+ export declare const CANDIDATE_PROFILES: readonly NativeProfile[];
22
+ export declare const currentPlatform: () => string;
23
+ export declare function selectNativeProfile(query: NativeProfileQuery, table?: readonly NativeProfile[]): NativeProfile | undefined;
24
+ export declare function nativeProfileRefusal(query: NativeProfileQuery, table?: readonly NativeProfile[]): NativeProfileRefusal | undefined;
25
+ export declare const platformProfiled: (platform: string, table?: readonly NativeProfile[]) => boolean;
@@ -0,0 +1,62 @@
1
+ const kinds = {
2
+ darwin: { platformOs: 'macos', storageBinding: 'darwin_lsof', ownerInspection: 'lsof_ps', targets: { arm64: 'aarch64-apple-darwin' } },
3
+ linux: { platformOs: 'linux', storageBinding: 'linux_procfs', ownerInspection: 'lsof_ps_procfs_locks',
4
+ targets: { arm64: 'aarch64-unknown-linux-musl', x64: 'x86_64-unknown-linux-musl' } },
5
+ };
6
+ const historical = new Set(['darwin-arm64/0.160.1', 'darwin-arm64/0.162.1']);
7
+ // Validates the whole table, including test-supplied synthetic tables, so a
8
+ // malformed or ambiguous row cannot be selected by a looser comparison.
9
+ export function validateNativeProfiles(table) {
10
+ const keys = new Set();
11
+ for (const row of table) {
12
+ if (!row || typeof row !== 'object' || Object.keys(row).sort().join() !==
13
+ 'artifact,commit,ownerInspection,platform,platformOs,sshDestination,storageBinding,version')
14
+ throw new Error('invalid native profile');
15
+ const [os, arch, extra] = row.platform.split('-'), kind = kinds[os];
16
+ const target = kind?.targets[arch];
17
+ if (!kind || !target || extra !== undefined || !/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/.test(row.version) ||
18
+ !/^[0-9a-f]{40}$/.test(row.commit) || row.platformOs !== kind.platformOs || row.storageBinding !== kind.storageBinding ||
19
+ row.ownerInspection !== kind.ownerInspection || typeof row.sshDestination !== 'boolean' ||
20
+ (os === 'linux' && row.sshDestination))
21
+ throw new Error('invalid native profile');
22
+ const key = row.platform + '/' + row.version;
23
+ if (keys.has(key))
24
+ throw new Error('ambiguous native profile');
25
+ keys.add(key);
26
+ if (row.artifact === null ? !historical.has(key) : Object.keys(row.artifact).sort().join() !== 'sha256,target' ||
27
+ row.artifact.target !== target || !/^[0-9a-f]{64}$/.test(row.artifact.sha256))
28
+ throw new Error('invalid native artifact');
29
+ }
30
+ return Object.freeze(table.map(row => Object.freeze({ ...row, artifact: row.artifact && Object.freeze({ ...row.artifact }) })));
31
+ }
32
+ export const NATIVE_PROFILES = validateNativeProfiles([
33
+ { platform: 'darwin-arm64', version: '0.160.1', commit: 'd27764b82f7118f674371e6d6e76271d9d606edb',
34
+ platformOs: 'macos', storageBinding: 'darwin_lsof', ownerInspection: 'lsof_ps', sshDestination: true, artifact: null },
35
+ { platform: 'darwin-arm64', version: '0.162.1', commit: '092d3acd6bec3e3a14bdc7e7a2810ab628ab759d',
36
+ platformOs: 'macos', storageBinding: 'darwin_lsof', ownerInspection: 'lsof_ps', sshDestination: true, artifact: null },
37
+ ]);
38
+ // Recorded but NOT selectable. Linux arm64 test host, 2026-10-20: upstream
39
+ // rust-v0.162.1 musl artifact digest, Linux-generated schema/opt-out evidence
40
+ // and one dedicated-thread client-ID injection (linux-observation-native-
41
+ // evidence.json). Activation is withheld until the original TUI writer's
42
+ // executable is bound to this artifact and the writer's kernel identity is
43
+ // retained across send and independent wait (PARITY.md follow-up design).
44
+ export const CANDIDATE_PROFILES = validateNativeProfiles([
45
+ { platform: 'linux-arm64', version: '0.162.1', commit: '092d3acd6bec3e3a14bdc7e7a2810ab628ab759d',
46
+ platformOs: 'linux', storageBinding: 'linux_procfs', ownerInspection: 'lsof_ps_procfs_locks', sshDestination: false,
47
+ artifact: { target: 'aarch64-unknown-linux-musl', sha256: '071cbe8d821cf1b02b6d8ba6c8b7991b228fcb8519dcb68a37d31222bb8cabe5' } },
48
+ ]);
49
+ export const currentPlatform = () => `${process.platform}-${process.arch}`;
50
+ export function selectNativeProfile(query, table = NATIVE_PROFILES) {
51
+ if (!query || typeof query.platform !== 'string' || typeof query.version !== 'string')
52
+ return undefined;
53
+ return table.find(row => row.platform === query.platform && row.version === query.version);
54
+ }
55
+ // Version absence is reported before platform absence; neither is downgraded
56
+ // to a nearby row. An exact version on another platform is still unsupported.
57
+ export function nativeProfileRefusal(query, table = NATIVE_PROFILES) {
58
+ if (selectNativeProfile(query, table))
59
+ return undefined;
60
+ return table.some(row => row.version === query?.version) ? 'platform_unsupported' : 'version_unsupported';
61
+ }
62
+ export const platformProfiled = (platform, table = NATIVE_PROFILES) => table.some(row => row.platform === platform);
package/dist/output.js CHANGED
@@ -66,7 +66,13 @@ export function renderOutput(value, format) {
66
66
  if (value.command === 'update' && value.error === 'self_update_unsupported')
67
67
  lines.push(value.updateCommand ? `This installation is managed by ${safe(value.managedBy)}. Upgrade with: ${safe(value.updateCommand)}` : safe(value.guidance));
68
68
  if (value.command === 'send')
69
- lines.push(value.submitted === null ? 'Submission outcome unknown. Do not retry automatically.' : 'Nothing submitted.');
69
+ lines.push(value.submitted === true ? 'Submitted; the requested evidence goal was not established. Do not retry automatically.' : value.submitted === null ? 'Submission outcome unknown. Do not retry automatically.' : 'Nothing submitted.');
70
+ }
71
+ if (value.handoff && typeof value.handoff === 'object') {
72
+ const h = value.handoff;
73
+ lines.push(`Handoff: ${safe(h.correlationId)} (${safe(h.state)})`);
74
+ for (const key of ['observation', 'ack', 'wait'])
75
+ lines.push(`${key}: ${safe(JSON.stringify(h[key]))}`);
70
76
  }
71
77
  if (value.sshTransport && typeof value.sshTransport === 'object') {
72
78
  const transport = value.sshTransport;
package/dist/process.d.ts CHANGED
@@ -19,3 +19,31 @@ export declare function run(binary: string, args: string[], options?: {
19
19
  limit?: number;
20
20
  rawStdout?: boolean;
21
21
  }): Promise<Done>;
22
+ export type TreeCleanup = 'confirmed' | 'unconfirmed';
23
+ export type TreeReply = {
24
+ rows: Map<number, number>;
25
+ held: Map<number, {
26
+ start: bigint;
27
+ exit: bigint | null;
28
+ }>;
29
+ errors: Map<number, 'gone' | 'denied'>;
30
+ };
31
+ export type TreeHelper = {
32
+ pid?: number;
33
+ request(hold: number[], kill: number[]): Promise<TreeReply>;
34
+ close(): void;
35
+ };
36
+ export type TreeRoot = {
37
+ pid: number;
38
+ exited: () => boolean;
39
+ kill: () => void;
40
+ };
41
+ export declare function parseTreeReply(line: string): TreeReply;
42
+ export declare function windowsTreeHelper(): TreeHelper;
43
+ export declare const ROOT_HOLD_GRACE_MS = 2000;
44
+ export declare function reapWindowsTree(root: TreeRoot, deadline: () => number, options?: {
45
+ helper?: () => TreeHelper;
46
+ now?: () => number;
47
+ self?: number;
48
+ signal?: AbortSignal;
49
+ }): Promise<TreeCleanup>;