session-peer 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,447 @@
1
+ // Source-qualified LOCAL loader layers, independent of observation profiles.
2
+ // See docs: rust-v0.160.1, rust-v0.162.1 and rust-v0.165.0 config/src/loader.
3
+ // Never return TOML, preference values, native diagnostics or configuration paths.
4
+ import { createHash } from 'node:crypto';
5
+ import { execFileSync } from 'node:child_process';
6
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readlinkSync, readSync, realpathSync, statSync } from 'node:fs';
7
+ import { basename, dirname, isAbsolute, join } from 'node:path';
8
+ import { TextDecoder } from 'node:util';
9
+ import { parse } from 'smol-toml';
10
+ export const STORAGE_LOADER_VERSIONS = ['0.160.1', '0.162.1', '0.165.0'];
11
+ // JSON string escapes are TOML-compatible except raw DEL, which TOML forbids.
12
+ // C0 characters are escaped by JSON.stringify; escape DEL explicitly so Rust's
13
+ // override parser never falls back to a literal containing doubled slashes.
14
+ export function codexStoragePin(home) {
15
+ return `sqlite_home=${JSON.stringify(home).replace(/\u007f/g, '\\u007f')}`;
16
+ }
17
+ const LIMIT = 1024 * 1024;
18
+ const absent = (e) => e.code === 'ENOENT';
19
+ class Invalid extends Error {
20
+ layer;
21
+ configured;
22
+ constructor(layer, configured = false) {
23
+ super();
24
+ this.layer = layer;
25
+ this.configured = configured;
26
+ }
27
+ }
28
+ function metadata(s) {
29
+ return [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].join(':');
30
+ }
31
+ // Never follow a config symlink or open a special file; a racing FIFO cannot
32
+ // block this read. Missing parents that are not directories are unclassifiable.
33
+ function bytes(path, layer) {
34
+ let before;
35
+ try {
36
+ before = lstatSync(path, { bigint: true });
37
+ }
38
+ catch (e) {
39
+ if (absent(e))
40
+ return;
41
+ throw new Invalid(layer);
42
+ }
43
+ let fd;
44
+ try {
45
+ if (!before.isFile() || before.size > BigInt(LIMIT))
46
+ throw new Error();
47
+ fd = openSync(path, constants.O_RDONLY | (process.platform === 'win32' ? 0 : constants.O_NOFOLLOW | constants.O_NONBLOCK));
48
+ const opened = fstatSync(fd, { bigint: true });
49
+ if (!opened.isFile() || metadata(opened) !== metadata(before))
50
+ throw new Error();
51
+ const out = Buffer.alloc(LIMIT + 1);
52
+ let length = 0;
53
+ while (length < out.length) {
54
+ const n = readSync(fd, out, length, out.length - length, length);
55
+ if (!n)
56
+ break;
57
+ length += n;
58
+ }
59
+ const after = fstatSync(fd, { bigint: true }), named = lstatSync(path, { bigint: true });
60
+ if (length > LIMIT || BigInt(length) !== opened.size || !after.isFile() || !named.isFile() ||
61
+ metadata(after) !== metadata(before) || metadata(named) !== metadata(before))
62
+ throw new Error();
63
+ return out.subarray(0, length);
64
+ }
65
+ catch {
66
+ throw new Invalid(layer);
67
+ }
68
+ finally {
69
+ if (fd !== undefined)
70
+ closeSync(fd);
71
+ }
72
+ }
73
+ // Both 0.160.1 and 0.162.1 (also 0.165.0) require forced values, before AND
74
+ // after CopyAppValue. Do not import the older Python wake-version policy.
75
+ export function managedStoragePreferences() {
76
+ const script = `ObjC.import('CoreFoundation');
77
+ var domain=$('com.openai.codex');
78
+ if (!$.CFPreferencesAppSynchronize(domain)) throw Error('unavailable');
79
+ var out=[];
80
+ ['config_toml_base64','requirements_toml_base64'].forEach(function(name){
81
+ var key=$(name); if (!$.CFPreferencesAppValueIsForced(key,domain)) return;
82
+ var raw=$.CFPreferencesCopyAppValue(key,domain);
83
+ if (!$.CFPreferencesAppValueIsForced(key,domain)) return;
84
+ var value=ObjC.deepUnwrap(raw);
85
+ if(typeof value !== 'string' || value.length>2097152) throw Error('invalid');
86
+ out.push({forced:true,value:value});
87
+ }); JSON.stringify(out);`;
88
+ try {
89
+ const value = JSON.parse(execFileSync('/usr/bin/osascript', ['-l', 'JavaScript', '-e', script], { encoding: 'utf8', timeout: 3000, maxBuffer: 5 * LIMIT, stdio: ['ignore', 'pipe', 'pipe'] }));
90
+ if (!Array.isArray(value) || value.length > 2)
91
+ throw new Error();
92
+ return value;
93
+ }
94
+ catch {
95
+ throw new Invalid('preferences');
96
+ }
97
+ }
98
+ export function storageDiagnostic(check) {
99
+ const { fingerprint: _private, queueCwd: _cwd, ...diagnostic } = check;
100
+ return diagnostic;
101
+ }
102
+ export function classifyCodexStorage(options) {
103
+ const platform = options.platform ?? process.platform;
104
+ const layers = new Set(), evidence = [];
105
+ const qualified = platform === 'darwin' || platform === 'linux';
106
+ const versionOK = options.version === undefined || STORAGE_LOADER_VERSIONS.includes(options.version);
107
+ let queueCwd, total = 0;
108
+ let cloudConfiguration = 'unclassified';
109
+ const result = (status, code) => ({ status, code,
110
+ verification: 'local_loader_layers', loaderVersion: options.version ?? null,
111
+ loaderVersionVerified: options.version !== undefined && versionOK, localLoaderPlatformSupported: qualified,
112
+ layers: [...layers], consumerContext: options.consumerCwds?.length ? 'inspected' : 'not_provided',
113
+ cloudConfiguration,
114
+ fingerprint: createHash('sha256').update(JSON.stringify(evidence)).digest('hex'), ...(queueCwd ? { queueCwd } : {}) });
115
+ if (!qualified)
116
+ return result('unsupported', 'codex_storage_platform_unqualified');
117
+ if (!versionOK)
118
+ return result('unsupported', 'codex_storage_loader_unsupported');
119
+ try {
120
+ const environment = options.environment ?? process.env;
121
+ const remoteMarkers = ['CODEX_EXEC_SERVER_URL', 'CODEX_EXEC_SERVER_NOISE_REGISTRY_URL',
122
+ 'CODEX_EXEC_SERVER_NOISE_ENVIRONMENT_ID', 'CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN', 'CODEX_EXEC_SERVER_NOISE_CHATGPT_ACCOUNT_ID'];
123
+ if (remoteMarkers.some(name => Boolean(environment[name]?.trim())))
124
+ throw new Invalid('context');
125
+ try {
126
+ lstatSync(join(options.home, 'environments.toml'));
127
+ throw new Invalid('context');
128
+ }
129
+ catch (e) {
130
+ if (!absent(e))
131
+ throw e instanceof Invalid ? e : new Invalid('context');
132
+ }
133
+ let customMarkers = false, nonFileAuthStore = false, configServer = false;
134
+ const config = (data, layer) => {
135
+ total += data.length;
136
+ if (total > 8 * LIMIT)
137
+ throw new Invalid(layer);
138
+ let value;
139
+ try {
140
+ value = parse(new TextDecoder('utf-8', { fatal: true }).decode(data));
141
+ }
142
+ catch {
143
+ throw new Invalid(layer);
144
+ }
145
+ if (Object.hasOwn(value, 'sqlite_home'))
146
+ throw new Invalid(layer, true);
147
+ customMarkers ||= Object.hasOwn(value, 'project_root_markers');
148
+ // Native auth storage is a root selector. This deliberately conservative
149
+ // superset also refuses selectors in inactive/nested tables; it does not
150
+ // claim the native loader applies those nested selectors.
151
+ const pending = [value];
152
+ let count = 0;
153
+ while (pending.length) {
154
+ if (++count > 65536)
155
+ throw new Invalid(layer);
156
+ const item = pending.pop();
157
+ if (!item || typeof item !== 'object')
158
+ continue;
159
+ configServer ||= Object.hasOwn(item, 'config_server');
160
+ if (Object.hasOwn(item, 'cli_auth_credentials_store') &&
161
+ item.cli_auth_credentials_store !== 'file' &&
162
+ item.cli_auth_credentials_store !== 'ephemeral')
163
+ nonFileAuthStore = true;
164
+ pending.push(...Object.values(item));
165
+ }
166
+ };
167
+ const visited = new Set();
168
+ const inspect = (path, layer) => {
169
+ if (visited.has(path))
170
+ return;
171
+ visited.add(path);
172
+ layers.add(layer);
173
+ const data = bytes(path, layer);
174
+ evidence.push([layer, path, data ? createHash('sha256').update(data).digest('hex') : null,
175
+ data ? metadata(lstatSync(path, { bigint: true })) : null]);
176
+ if (data)
177
+ config(data, layer);
178
+ };
179
+ inspect(join(options.home, 'config.toml'), 'home');
180
+ const base = options.systemBase ?? '/etc/codex';
181
+ for (const [name, layer] of [['config.toml', 'system'], ['requirements.toml', 'requirements'], ['managed_config.toml', 'legacy']])
182
+ inspect(join(base, name), layer);
183
+ if (platform === 'darwin') {
184
+ layers.add('preferences');
185
+ const values = (options.preferences ?? managedStoragePreferences)();
186
+ if (!Array.isArray(values) || values.length > 2)
187
+ throw new Invalid('preferences');
188
+ for (const entry of values) {
189
+ if (!entry || typeof entry.forced !== 'boolean')
190
+ throw new Invalid('preferences');
191
+ if (!entry.forced)
192
+ continue;
193
+ if (typeof entry.value !== 'string' || entry.value.length > 2 * LIMIT)
194
+ throw new Invalid('preferences');
195
+ const encoded = entry.value.trim();
196
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded))
197
+ throw new Invalid('preferences');
198
+ const data = Buffer.from(encoded, 'base64');
199
+ if (data.length > LIMIT)
200
+ throw new Invalid('preferences');
201
+ evidence.push(['preferences', createHash('sha256').update(data).digest('hex')]);
202
+ config(data, 'preferences');
203
+ }
204
+ evidence.push(['preferences_end']);
205
+ }
206
+ layers.add('cloud');
207
+ // Source: cloud-config/service.rs only loads bundles for eligible backend
208
+ // auth; cache absence alone is insufficient because it fetches on a miss.
209
+ // Default auth storage is File (config/types.rs). Never read auth.json or
210
+ // keychain contents: possible auth/cache/keyring/external identity instead
211
+ // requires the owned process's actual opened-SQLite binding, or refusal.
212
+ let authMetadataPresent = false;
213
+ for (const name of ['auth.json', 'cloud-config-bundle-cache.json']) {
214
+ try {
215
+ const info = lstatSync(join(options.home, name), { bigint: true });
216
+ authMetadataPresent = true;
217
+ if (!options.ownedAppServer)
218
+ evidence.push(['cloud_metadata', name, metadata(info)]);
219
+ }
220
+ catch (e) {
221
+ if (!absent(e))
222
+ throw new Invalid('cloud');
223
+ if (!options.ownedAppServer)
224
+ evidence.push(['cloud_metadata', name, null]);
225
+ }
226
+ }
227
+ const externalAuth = ['CODEX_ACCESS_TOKEN', 'OPENAI_FEDERATION_RULE_ID', 'OPENAI_IDENTITY_TOKEN_FILE', 'OPENAI_WORKLOAD_IDENTITY_CONTEXT']
228
+ .some(name => Object.hasOwn(environment, name));
229
+ evidence.push(['external_auth_marker', externalAuth]);
230
+ const possibleCloud = () => authMetadataPresent || nonFileAuthStore || externalAuth || configServer;
231
+ const physical = (cwd) => {
232
+ try {
233
+ if (!isAbsolute(cwd))
234
+ throw new Error();
235
+ const path = realpathSync(cwd);
236
+ if (!statSync(path).isDirectory())
237
+ throw new Error();
238
+ return path;
239
+ }
240
+ catch {
241
+ throw new Invalid('context');
242
+ }
243
+ };
244
+ queueCwd = physical(options.queueCwd ?? process.cwd());
245
+ const scanAllAncestors = customMarkers || possibleCloud();
246
+ const contexts = [queueCwd, ...(options.consumerCwds ?? []).map(physical)];
247
+ const inspectContexts = (scanAllAncestors) => {
248
+ for (const cwd of new Set(contexts)) {
249
+ layers.add('context');
250
+ evidence.push(['cwd', cwd]);
251
+ const directories = [];
252
+ let dir = cwd;
253
+ for (;;) {
254
+ if (directories.length >= 256)
255
+ throw new Invalid('context');
256
+ directories.push(dir);
257
+ if (!scanAllAncestors) {
258
+ try {
259
+ const marker = lstatSync(join(dir, '.git'));
260
+ if (marker.isSymbolicLink())
261
+ throw new Invalid('project');
262
+ if (!marker.isDirectory())
263
+ break;
264
+ try {
265
+ statSync(join(dir, '.git', 'HEAD'));
266
+ break;
267
+ }
268
+ catch (e) {
269
+ if (!absent(e))
270
+ throw new Invalid('project');
271
+ }
272
+ }
273
+ catch (e) {
274
+ if (!absent(e))
275
+ throw e instanceof Invalid ? e : new Invalid('project');
276
+ }
277
+ }
278
+ const parent = dirname(dir);
279
+ if (dir === parent) {
280
+ if (!scanAllAncestors)
281
+ directories.splice(1);
282
+ break;
283
+ }
284
+ dir = parent;
285
+ }
286
+ evidence.push(['project_roots', directories]);
287
+ for (const directory of directories)
288
+ inspect(join(directory, '.codex', 'config.toml'), 'project');
289
+ }
290
+ };
291
+ inspectContexts(scanAllAncestors);
292
+ if (!scanAllAncestors && possibleCloud())
293
+ inspectContexts(true);
294
+ cloudConfiguration = possibleCloud() ? 'requires_owned_storage_binding' : 'ineligible_by_metadata';
295
+ evidence.push(['cloud_gate', possibleCloud()]);
296
+ if (possibleCloud() && !options.ownedAppServer) {
297
+ cloudConfiguration = 'unclassified';
298
+ throw new Invalid('cloud');
299
+ }
300
+ // A reused daemon retains its startup QueueStore. Disk config/read cannot
301
+ // attest to it; owned stdio has a separate opened-FD binding guard.
302
+ if (!options.ownedAppServer) {
303
+ layers.add('daemon');
304
+ try {
305
+ lstatSync(join(options.home, 'app-server-control', 'app-server-control.sock'));
306
+ throw new Invalid('daemon');
307
+ }
308
+ catch (e) {
309
+ if (!absent(e))
310
+ throw e instanceof Invalid ? e : new Invalid('daemon');
311
+ }
312
+ evidence.push(['daemon', 'absent']);
313
+ }
314
+ return result('classified', 'codex_local_storage_classified');
315
+ }
316
+ catch (e) {
317
+ const error = e instanceof Invalid ? e : new Invalid('context');
318
+ layers.add(error.layer);
319
+ return result(error.configured ? 'unsupported' : 'unknown', error.configured ? 'unsupported_codex_sqlite_home' :
320
+ error.layer === 'home' ? 'codex_config_unreadable' : error.layer === 'daemon' ? 'codex_daemon_storage_unverified' :
321
+ error.layer === 'cloud' ? 'codex_cloud_storage_unverified' : 'codex_storage_config_unverifiable');
322
+ }
323
+ }
324
+ // Only the saved thread's cwd column is inspected: never transcripts, accounts,
325
+ // credentials, preference files or arbitrary environment variables.
326
+ let sqlite;
327
+ export function codexStateIdentity(home) {
328
+ const info = lstatSync(join(home, 'state_5.sqlite'), { bigint: true });
329
+ if (!info.isFile())
330
+ throw new Error('codex_consumer_context_unverifiable');
331
+ return `${info.dev}:${info.ino}`;
332
+ }
333
+ // Initialized lazily by the first Codex-only read. The final dispatch barrier
334
+ // then queries metadata synchronously, without importing SQLite for Claude.
335
+ export function codexConsumerSnapshotSync(home, threadId) {
336
+ try {
337
+ if (!sqlite)
338
+ throw new Error();
339
+ const database = codexStateIdentity(home);
340
+ const db = new sqlite.DatabaseSync(join(home, 'state_5.sqlite'), { readOnly: true });
341
+ try {
342
+ db.exec('PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=3000');
343
+ const row = db.prepare('SELECT cwd FROM threads WHERE id=? LIMIT 1').get(threadId);
344
+ if (typeof row?.cwd !== 'string' || row.cwd.length > 32768 || !isAbsolute(row.cwd))
345
+ throw new Error();
346
+ if (codexStateIdentity(home) !== database)
347
+ throw new Error();
348
+ return { cwd: row.cwd, database };
349
+ }
350
+ finally {
351
+ db.close();
352
+ }
353
+ }
354
+ catch {
355
+ throw new Error('codex_consumer_context_unverifiable');
356
+ }
357
+ }
358
+ export async function codexConsumerCwd(home, threadId) {
359
+ sqlite ??= await import('node:sqlite');
360
+ return codexConsumerSnapshotSync(home, threadId).cwd;
361
+ }
362
+ // Optional live consumer context complements the persisted thread cwd. A PID
363
+ // comes only from the already retained writer evidence, never from discovery.
364
+ export function codexWriterCwd(pid) {
365
+ try {
366
+ if (!Number.isSafeInteger(pid) || pid < 2)
367
+ throw new Error();
368
+ if (process.platform === 'linux')
369
+ return realpathSync(readlinkSync(`/proc/${pid}/cwd`));
370
+ if (process.platform !== 'darwin')
371
+ throw new Error();
372
+ const output = execFileSync('/usr/sbin/lsof', ['-a', '-p', String(pid), '-d', 'cwd', '-Fn0'], { encoding: 'utf8', timeout: 3000, maxBuffer: 65536, stdio: ['ignore', 'pipe', 'pipe'] });
373
+ const paths = output.split(/[\0\n]/).filter(item => item.startsWith('n')).map(item => item.slice(1));
374
+ if (paths.length !== 1 || !isAbsolute(paths[0]))
375
+ throw new Error();
376
+ return realpathSync(decodeLsofFilename(paths[0]));
377
+ }
378
+ catch {
379
+ throw new Error('codex_consumer_context_unverifiable');
380
+ }
381
+ }
382
+ export function decodeLsofFilename(raw) {
383
+ const bytes = [];
384
+ for (let i = 0; i < raw.length; i++) {
385
+ if (raw[i] !== '\\') {
386
+ const char = String.fromCodePoint(raw.codePointAt(i));
387
+ bytes.push(...Buffer.from(char));
388
+ i += char.length - 1;
389
+ continue;
390
+ }
391
+ const next = raw[++i];
392
+ if (next === '\\') {
393
+ bytes.push(92);
394
+ continue;
395
+ }
396
+ if (next === 'x' && /^[0-9a-f]{2}$/i.test(raw.slice(i + 1, i + 3))) {
397
+ bytes.push(parseInt(raw.slice(i + 1, i + 3), 16));
398
+ i += 2;
399
+ continue;
400
+ }
401
+ throw new Error('codex_storage_binding_unverifiable');
402
+ }
403
+ return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.from(bytes));
404
+ }
405
+ // A sender version never qualifies a running consumer's environment/loader.
406
+ // Instead bind the retained writer PID's CURRENT opened state database inode.
407
+ // Observe metadata only; no process environment, DB contents or executable run.
408
+ // Queue descriptors, when present, must agree as well. Missing state evidence
409
+ // or another SQLite namespace is unclassifiable and refuses submission.
410
+ export function codexWriterStorage(pid, home) {
411
+ try {
412
+ if (!Number.isSafeInteger(pid) || pid < 2 || !['darwin', 'linux'].includes(process.platform))
413
+ throw new Error();
414
+ const binary = process.platform === 'darwin' ? '/usr/sbin/lsof' : '/usr/bin/lsof';
415
+ const out = execFileSync(binary, ['-a', '-p', String(pid), '-F0fDin'], { encoding: 'utf8', timeout: 3000, maxBuffer: 65536, stdio: ['ignore', 'pipe', 'pipe'],
416
+ env: { PATH: '/usr/bin:/bin:/usr/sbin:/sbin', LC_ALL: 'C', LANG: 'C' } });
417
+ const files = [];
418
+ let current;
419
+ for (const raw of out.split('\0')) {
420
+ const field = raw.replace(/^\n/, '');
421
+ if (field.startsWith('f')) {
422
+ current = {};
423
+ files.push(current);
424
+ }
425
+ else if (current && field.startsWith('n'))
426
+ current.name = decodeLsofFilename(field.slice(1));
427
+ else if (current && /^D0x[0-9a-f]+$/i.test(field))
428
+ current.dev = BigInt(field.slice(1));
429
+ else if (current && /^i[0-9]+$/.test(field))
430
+ current.ino = BigInt(field.slice(1));
431
+ }
432
+ if (!files.some(file => file.name === join(home, 'state_5.sqlite')))
433
+ throw new Error();
434
+ for (const file of files) {
435
+ if (!file.name || !/^(?:state_5|queue_1)\.sqlite(?:-(?:wal|shm))?(?: \(deleted\))?$/.test(basename(file.name)))
436
+ continue;
437
+ if (file.name !== join(home, basename(file.name)) || file.name.endsWith(' (deleted)'))
438
+ throw new Error();
439
+ const info = lstatSync(file.name, { bigint: true });
440
+ if (!info.isFile() || info.dev !== file.dev || info.ino !== file.ino)
441
+ throw new Error();
442
+ }
443
+ }
444
+ catch {
445
+ throw new Error('codex_consumer_storage_unverifiable');
446
+ }
447
+ }
@@ -1,9 +1,11 @@
1
- // Diagnostics inspect bounded metadata only. Never probe/connect to an inbox,
1
+ // Diagnostics read bounded configuration and metadata, returning sanitized checks.
2
+ // Never probe/connect to an inbox,
2
3
  // acquire a writer lock, execute an agent binary, or write configuration.
3
4
  import { accessSync, constants, readdirSync, readFileSync, statSync } from 'node:fs';
4
5
  import { homedir } from 'node:os';
5
6
  import { delimiter, isAbsolute, join } from 'node:path';
6
- import { listingCandidates, sqliteHome } from './discovery.js';
7
+ import { listingCandidates } from './discovery.js';
8
+ import { classifyCodexStorage, storageDiagnostic } from './codex-storage.js';
7
9
  import { inspectSkill } from './skill-metadata.js';
8
10
  import { batchShim } from './process.js';
9
11
  import { windowsProcessStart } from './windows.js';
@@ -72,9 +74,9 @@ export async function diagnoseCodex(home, binary) {
72
74
  const inventory = listingCandidates(home);
73
75
  const homes = [];
74
76
  for (const item of inventory.homes) {
75
- const storage = sqliteHome(item.codexHome);
76
- homes.push({ ...item, ...(storage === 'configured' ? { status: 'unsupported', code: 'unsupported_codex_sqlite_home' } :
77
- storage === 'unknown' ? { status: 'unknown', code: 'codex_config_unreadable' } : await codexHome(item.stateDb)) });
77
+ const storage = classifyCodexStorage({ home: item.codexHome });
78
+ homes.push({ ...item, storage: storageDiagnostic(storage), ...(storage.status !== 'classified' ?
79
+ { status: storage.status, code: storage.code } : await codexHome(item.stateDb)) });
78
80
  }
79
81
  const agentTool = tool(binary ?? 'codex');
80
82
  const complete = inventory.errors.length === 0 && homes.every(item => item.status === 'available' || (!item.required && item.status === 'missing'));
@@ -4,7 +4,6 @@ export declare class Refusal extends Error {
4
4
  readonly exitCode: number;
5
5
  constructor(code: string, exitCode?: number);
6
6
  }
7
- export declare function sqliteHome(home: string): 'default' | 'configured' | 'unknown';
8
7
  export declare function canonical(path: string): string;
9
8
  export declare function claude(all: boolean): Row;
10
9
  export declare function configuredHomePaths(): string[];
package/dist/discovery.js CHANGED
@@ -1,9 +1,8 @@
1
1
  // Read-only discovery: no inbox connections, writer selection, queue or DB writes.
2
2
  // Windows Claude metadata uses native process inspection.
3
- import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readlinkSync, readSync, readdirSync, realpathSync, statSync } from 'node:fs';
3
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readlinkSync, readSync, readdirSync, realpathSync, statSync } from 'node:fs';
4
4
  import { homedir } from 'node:os';
5
5
  import { dirname, isAbsolute, join, resolve } from 'node:path';
6
- import { parse as parseTOML } from 'smol-toml';
7
6
  import { windowsProcessStart } from './windows.js';
8
7
  export class Refusal extends Error {
9
8
  code;
@@ -14,26 +13,6 @@ export class Refusal extends Error {
14
13
  this.exitCode = exitCode;
15
14
  }
16
15
  }
17
- // Codex can relocate state_5.sqlite/queue_1.sqlite with `sqlite_home`; validation
18
- // reads <home>/state_5.sqlite, so any configured relocation is unsupported.
19
- export function sqliteHome(home) {
20
- let text;
21
- try {
22
- const file = join(home, 'config.toml'), stat = statSync(file);
23
- if (!stat.isFile() || stat.size > 1024 * 1024)
24
- return 'unknown';
25
- text = readFileSync(file, 'utf8');
26
- }
27
- catch (error) {
28
- return ['ENOENT', 'ENOTDIR'].includes(error.code ?? '') ? 'default' : 'unknown';
29
- }
30
- try {
31
- return Object.hasOwn(parseTOML(text), 'sqlite_home') ? 'configured' : 'default';
32
- }
33
- catch {
34
- return 'unknown';
35
- }
36
- }
37
16
  function missing(error) {
38
17
  return ['ENOENT', 'ENOTDIR'].includes(error.code ?? '');
39
18
  }
@@ -11,8 +11,9 @@ import { metadataCapability, observeMetadata, resumeMetadataObservation, metadat
11
11
  import { checkMessage, queueId, send } from './send.js';
12
12
  import { Refusal } from './discovery.js';
13
13
  import { HomeRefusal } from './writer.js';
14
- import { executable, run, UnknownOutcome } from './process.js';
14
+ import { run, UnknownOutcome } from './process.js';
15
15
  import { currentPlatform, selectNativeProfile, validateNativeProfiles } from './native-profiles.js';
16
+ import { codexStoragePin } from './codex-storage.js';
16
17
  export function ledgerPath() {
17
18
  const path = process.env.SESSION_PEER_HANDOFF_HOME ?? join(homedir(), '.local', 'state', 'session-peer-ts', 'handoff');
18
19
  if (!isAbsolute(path))
@@ -55,7 +56,8 @@ export function privateMessage(path) {
55
56
  }
56
57
  }
57
58
  function binding(context, message, destination = hostname()) {
58
- return { ...context, destination, payloadDigest: payloadDigest(message) };
59
+ const { binary: _privateBinary, ...retained } = context;
60
+ return { ...retained, destination, payloadDigest: payloadDigest(message) };
59
61
  }
60
62
  export function correlationEnvelope(message, id) {
61
63
  if (!canonicalId(id))
@@ -176,10 +178,12 @@ export async function handoffSend(options, handoffOptions) {
176
178
  // Account for the fixed correlation envelope before allocating an intent.
177
179
  checkMessage(correlationEnvelope(options.message, '00000000-0000-4000-8000-000000000000'), context.agent === 'codex');
178
180
  const wantsDelivery = handoffOptions.observeDelivery || handoffOptions.waitFor === 'delivered';
179
- if (wantsDelivery && context.agent === 'codex' && context.home && context.generation && budget.observationRemainingMs() > 0) {
181
+ if (!options.dryRun && wantsDelivery && context.agent === 'codex' && context.home && context.generation && budget.observationRemainingMs() > 0) {
180
182
  scope = { home: context.home, threadId: context.target, generation: context.generation };
181
183
  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 });
184
+ if (!context.binary)
185
+ throw new Refusal('codex_storage_loader_unverifiable', 1);
186
+ const version = await run(context.binary, ['--version'], { timeout: Math.min(1000, budget.observationRemainingMs()), limit: 4096 });
183
187
  const nativeVersion = !version.interrupted && version.code === 0 ? version.stdout.trim().replace(/^codex-cli /, '') : '';
184
188
  // Exact host platform and native version select one profile row, or none.
185
189
  qualification = observationQualification(nativeVersion, currentPlatform(), handoffOptions.remote === true);
@@ -198,12 +202,18 @@ export async function handoffSend(options, handoffOptions) {
198
202
  return correlationEnvelope(options.message, handoff.correlationId);
199
203
  },
200
204
  beforeEffect: authorize,
201
- async submitCodex(context, message) {
205
+ codexRoute: () => deliverySupported ? 'owned_app_server' : 'ordinary',
206
+ async submitCodex(context, message, storage) {
202
207
  if (!deliverySupported) {
203
208
  // Best-effort unsupported is chosen before ANY app-server attempt.
209
+ await storage.revalidate(false);
204
210
  await authorize();
211
+ await storage.revalidate(false);
205
212
  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()) });
213
+ storage.finalCheck(false);
214
+ const timeout = Math.max(1, budget.observationRemainingMs());
215
+ budget.beforeEffect();
216
+ const done = await run(storage.binary, ['queue', '--thread', context.target, `--message=${message}`, '-c', codexStoragePin(context.home)], { env: { ...inherited, CODEX_HOME: context.home, PWD: storage.cwd }, cwd: storage.cwd, timeout });
207
217
  if (!done.spawned)
208
218
  throw new Refusal('native_spawn_failed', 1);
209
219
  if (done.interrupted || done.code !== 0)
@@ -212,7 +222,7 @@ export async function handoffSend(options, handoffOptions) {
212
222
  return { queueId: receipt, clientUserMessageId: handoff.correlationId };
213
223
  }
214
224
  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 });
225
+ return await nativeQueueOnce({ binary: storage.binary, scope: queueScope, message, clientUserMessageId: handoff.correlationId, deadlineMs: budget.cutoff, verifyOwner: async () => verifyOwner(scope), beforeEffect: authorize, verifyStorage: () => storage.revalidate(true), verifyStorageSync: () => storage.finalCheck(true) });
216
226
  }
217
227
  catch (error) {
218
228
  if (error instanceof AppServerFault && error.attempted)
package/dist/process.d.ts CHANGED
@@ -14,6 +14,7 @@ export type Done = {
14
14
  };
15
15
  export declare function run(binary: string, args: string[], options?: {
16
16
  env?: NodeJS.ProcessEnv;
17
+ cwd?: string;
17
18
  input?: string;
18
19
  timeout?: number;
19
20
  limit?: number;
package/dist/process.js CHANGED
@@ -63,7 +63,7 @@ export function run(binary, args, options = {}) {
63
63
  let stdout = '', stderr = '', bytes = 0, stderrBytes = 0, spawned = false, interrupted = false, finished = false, stopped = false;
64
64
  let stopReason;
65
65
  const chunks = [], outputDecoder = new StringDecoder('utf8'), diagnosticDecoder = new StringDecoder('utf8');
66
- const child = spawn(binary, args, { shell: false, env: options.env ?? process.env, stdio: ['pipe', 'pipe', 'pipe'], detached: posix });
66
+ const child = spawn(binary, args, { shell: false, env: options.env ?? process.env, cwd: options.cwd, stdio: ['pipe', 'pipe', 'pipe'], detached: posix });
67
67
  const release = () => {
68
68
  if (child.pid === undefined || !groups.delete(child.pid) || groups.size)
69
69
  return;
@@ -1,5 +1,5 @@
1
- export declare const VERSION = "0.5.1";
2
- export declare const VERSION_LINE = "session-peer 0.5.1 (typescript)";
1
+ export declare const VERSION = "0.5.2";
2
+ export declare const VERSION_LINE = "session-peer 0.5.2 (typescript)";
3
3
  export declare function host(value: string): string;
4
4
  export declare function reply(value: string): {
5
5
  to: string;
package/dist/protocol.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { isIPv6 } from 'node:net';
2
2
  import { Refusal } from './discovery.js';
3
3
  import { uuid } from './writer.js';
4
- export const VERSION = '0.5.1';
4
+ export const VERSION = '0.5.2';
5
5
  export const VERSION_LINE = `session-peer ${VERSION} (typescript)`;
6
6
  // Return the OpenSSH destination: [user@]name, or an IPv6 literal with any
7
7
  // brackets removed (`ssh` does not strip `[...]` outside ssh:// URIs). Zone IDs
package/dist/send.d.ts CHANGED
@@ -6,12 +6,20 @@ export type SendContext = {
6
6
  home?: string;
7
7
  generation: string | null;
8
8
  writerIdentity?: string;
9
+ readonly binary?: string;
10
+ };
11
+ export type CodexStorageGuard = {
12
+ readonly binary: string;
13
+ readonly cwd: string;
14
+ revalidate: (ownedAppServer?: boolean) => Promise<void>;
15
+ finalCheck: (ownedAppServer?: boolean) => void;
9
16
  };
10
17
  export type SendHooks = {
11
18
  resolved: (context: SendContext, snapshot: Record<string, unknown>) => Promise<string | void> | string | void;
12
19
  beforeEffect?: () => Promise<void> | void;
13
20
  timeoutMs?: () => number;
14
- submitCodex?: (context: SendContext, message: string) => Promise<{
21
+ codexRoute?: () => 'ordinary' | 'owned_app_server';
22
+ submitCodex?: (context: SendContext, message: string, storage: CodexStorageGuard) => Promise<{
15
23
  queueId?: string;
16
24
  clientUserMessageId: string;
17
25
  }>;