session-peer 0.1.0-preview.1 → 0.2.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.
package/dist/send.js CHANGED
@@ -1,8 +1,22 @@
1
+ import { casefold } from './casefold.js';
1
2
  import { createConnection } from 'node:net';
2
- import { canonical, claude, Refusal } from './discovery.js';
3
+ import { claude, Refusal } from './discovery.js';
3
4
  import { executable, run, UnknownOutcome } from './process.js';
4
- import { resolveWriter, uuid } from './writer.js';
5
+ import { HomeRefusal, resolveWriter, revalidateWriter, uuid } from './writer.js';
5
6
  import { postWindowsPipe } from './windows.js';
7
+ export class CodexUnknownOutcome extends UnknownOutcome {
8
+ codexHomeResolution;
9
+ constructor(codexHomeResolution) {
10
+ super();
11
+ this.codexHomeResolution = codexHomeResolution;
12
+ }
13
+ }
14
+ export function queueId(stdout, id) {
15
+ if (!uuid(id))
16
+ return undefined;
17
+ const matches = [...stdout.matchAll(new RegExp(`^Queued message ([A-Za-z0-9][A-Za-z0-9._:-]{0,127}) for thread ${id}\\.\\r?$`, 'gm'))];
18
+ return matches.length === 1 ? matches[0][1] : undefined;
19
+ }
6
20
  export function checkMessage(text, codex = false) {
7
21
  if (!text.trim() || text.includes('\0') || [...text].length > 1_000_000 ||
8
22
  (codex && Buffer.byteLength(text, 'utf8') > 32768))
@@ -43,36 +57,35 @@ export async function send(options) {
43
57
  dryRun: Boolean(options.dryRun), chars: [...options.message].length };
44
58
  if (options.to.startsWith('codex:')) {
45
59
  const id = options.to.slice(6).toLowerCase();
46
- if (!uuid(id) || !options.home)
47
- throw new Refusal('codex_uuid_and_explicit_home_required');
48
- const home = canonical(options.home);
60
+ if (!uuid(id))
61
+ throw new Refusal('codex_uuid_required');
49
62
  const binary = executable(options.codexBin ?? 'codex');
50
- const evidence = await resolveWriter(home, id);
63
+ const selection = await resolveWriter(options.home, id, options.allowInactive);
64
+ const { home } = selection;
51
65
  const result = { ...base, target: { agent: 'codex', id }, codexHome: home,
52
- status: options.dryRun ? 'validated' : 'queued' };
66
+ status: options.dryRun ? 'validated' : 'queued', codexHomeResolution: selection.resolution };
53
67
  if (options.dryRun)
54
68
  return result;
55
- if (await resolveWriter(home, id) !== evidence)
56
- throw new Refusal('writer_evidence_changed_before_queue', 1);
69
+ await revalidateWriter(selection, options.home, id, options.allowInactive);
57
70
  const done = await run(binary, ['queue', '--thread', id, '--message', options.message], { env: { ...process.env, CODEX_HOME: home }, timeout: 30000 });
58
71
  if (!done.spawned)
59
- throw new Refusal('native_spawn_failed', 1);
72
+ throw new HomeRefusal('native_spawn_failed', selection.resolution);
60
73
  if (done.interrupted || done.code !== 0)
61
- throw new UnknownOutcome();
62
- return result;
74
+ throw new CodexUnknownOutcome(selection.resolution);
75
+ const queuedId = queueId(done.stdout, id);
76
+ return { ...result, ...(queuedId === undefined ? {} : { queueId: queuedId }) };
63
77
  }
64
78
  if (options.to.includes(':') && !options.to.startsWith('claude:'))
65
79
  throw new Refusal('unsupported_agent');
66
- if (options.home || options.codexBin)
80
+ if (options.home || options.codexBin || options.allowInactive)
67
81
  throw new Refusal('inapplicable_option');
68
82
  const target = options.to.replace(/^claude:/, '');
69
- // ASCII name folding is explicit; Unicode names must use a PID until full casefold parity exists.
70
- if (!target || /[^\x20-\x7e]/.test(target))
71
- throw new Refusal('use_pid_for_unicode_name');
83
+ if (!target)
84
+ throw new Refusal('no_reachable_target');
72
85
  const select = () => {
73
86
  const rows = claude(false).sessions;
74
87
  const matches = rows.filter(r => /^\d+$/.test(target) ? r.pid === Number(target) :
75
- typeof r.name === 'string' && r.name.toLowerCase() === target.toLowerCase());
88
+ typeof r.name === 'string' && casefold(r.name) === casefold(target));
76
89
  if (matches.length !== 1)
77
90
  throw new Refusal(matches.length ? 'ambiguous_target' : 'no_reachable_target', 2);
78
91
  return matches[0];
package/dist/writer.d.ts CHANGED
@@ -1,8 +1,39 @@
1
+ import { Refusal } from './discovery.js';
1
2
  export declare const uuid: (value: string) => boolean;
2
3
  export declare function probeLock(path: string): Promise<'free' | 'held' | 'absent' | 'unknown'>;
3
4
  export declare function inspectWriter(home: string, id: string): Promise<{
4
- activity: string;
5
+ activity: "inactive";
6
+ writerLock: "absent" | "free";
7
+ identity: string;
8
+ } | {
9
+ activity: "live_writer";
10
+ writerLock: "held";
5
11
  identity: string;
6
12
  }>;
7
- export declare function homes(selected: string): string[];
8
- export declare function resolveWriter(selected: string, id: string): Promise<string>;
13
+ export type HomeCandidate = {
14
+ codexHome: string;
15
+ sources: string[];
16
+ savedThread: boolean | null;
17
+ writerLock: 'not_checked' | 'held' | 'free' | 'absent' | 'unknown';
18
+ activity?: 'inactive' | 'live_writer' | 'unknown';
19
+ reason: string;
20
+ };
21
+ export type HomeResolution = {
22
+ schemaVersion: 1;
23
+ status: 'selected' | 'explicit' | 'ambiguous' | 'unknown';
24
+ selected: string | null;
25
+ reason: string;
26
+ candidates: HomeCandidate[];
27
+ };
28
+ export declare class HomeRefusal extends Refusal {
29
+ readonly codexHomeResolution: HomeResolution;
30
+ constructor(code: string, codexHomeResolution: HomeResolution, exitCode?: number);
31
+ }
32
+ export declare function homes(selected?: string): string[];
33
+ export type WriterSelection = {
34
+ home: string;
35
+ evidence: string;
36
+ resolution: HomeResolution;
37
+ };
38
+ export declare function resolveWriter(selected: string | undefined, id: string, allowInactive?: boolean): Promise<WriterSelection>;
39
+ export declare function revalidateWriter(previous: WriterSelection, selected: string | undefined, id: string, allowInactive?: boolean): Promise<void>;
package/dist/writer.js CHANGED
@@ -1,8 +1,7 @@
1
- import { closeSync, constants, fstatSync, lstatSync, openSync, readdirSync, statSync } from 'node:fs';
2
- import { homedir } from 'node:os';
3
- import { isAbsolute, join } from 'node:path';
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
4
3
  import { setTimeout as delay } from 'node:timers/promises';
5
- import { canonical, Refusal } from './discovery.js';
4
+ import { listingCandidates, Refusal } from './discovery.js';
6
5
  import { executable, run } from './process.js';
7
6
  import { inspectWindows } from './windows.js';
8
7
  const missing = (error) => ['ENOENT', 'ENOTDIR'].includes(error.code ?? '');
@@ -54,7 +53,7 @@ export async function probeLock(path) {
54
53
  async function sample(path) {
55
54
  const state = await probeLock(path);
56
55
  if (state !== 'held')
57
- return { state, fingerprint: '', owners: [], valid: true };
56
+ return { state, fingerprint: state === 'free' ? snapshot(path) : '', owners: [], valid: true };
58
57
  const fingerprint = snapshot(path);
59
58
  if (process.platform === 'win32') {
60
59
  const owners = inspectWindows('openers', path);
@@ -87,7 +86,7 @@ export async function inspectWriter(home, id) {
87
86
  const path = join(home, 'thread-writer-locks', `${id}.lock`);
88
87
  const before = await sample(path);
89
88
  if (before.state === 'free' || before.state === 'absent')
90
- return { activity: 'inactive', identity: '' };
89
+ return { activity: 'inactive', writerLock: before.state, identity: JSON.stringify({ state: before.state, fingerprint: before.fingerprint }) };
91
90
  if (before.state !== 'held')
92
91
  throw new Refusal('active_writer_unverified', 1);
93
92
  await delay(250);
@@ -99,81 +98,153 @@ export async function inspectWriter(home, id) {
99
98
  !owner?.start || !ownId || owner.uid !== ownId || !/^codex(?:\.exe|-|$)/i.test(owner.command ?? '')) {
100
99
  throw new Refusal('active_writer_unverified', 1);
101
100
  }
102
- return { activity: 'live_writer', identity: JSON.stringify({ fingerprint: after.fingerprint, ...owner }) };
101
+ return { activity: 'live_writer', writerLock: 'held', identity: JSON.stringify({ fingerprint: after.fingerprint, ...owner }) };
103
102
  }
104
- export function homes(selected) {
105
- const result = new Set([canonical(selected)]);
106
- const addExisting = (home) => {
107
- try {
108
- if (!statSync(join(home, 'state_5.sqlite')).isFile())
109
- throw new Refusal('home_inventory_unreadable', 1);
110
- result.add(canonical(home));
111
- }
112
- catch (error) {
113
- if (!missing(error))
114
- throw new Refusal('home_inventory_unreadable', 1);
115
- }
116
- };
117
- addExisting(join(homedir(), '.codex'));
118
- if (process.env.CODEX_HOME)
119
- addExisting(process.env.CODEX_HOME);
120
- if (process.platform === 'darwin') {
121
- const directory = join(homedir(), 'Library/Application Support/orca/codex-accounts');
122
- let entries = [];
123
- try {
124
- entries = readdirSync(directory).sort();
125
- }
126
- catch (error) {
127
- if (!missing(error))
128
- throw new Refusal('home_inventory_unreadable', 1);
129
- }
130
- for (const entry of entries)
131
- addExisting(join(directory, entry, 'home'));
103
+ export class HomeRefusal extends Refusal {
104
+ codexHomeResolution;
105
+ constructor(code, codexHomeResolution, exitCode = 1) {
106
+ super(code, exitCode);
107
+ this.codexHomeResolution = codexHomeResolution;
132
108
  }
133
- if (process.env.SESSION_PEER_CODEX_HOMES) {
134
- let paths;
135
- try {
136
- paths = JSON.parse(process.env.SESSION_PEER_CODEX_HOMES);
137
- }
138
- catch {
139
- throw new Refusal('invalid_home_configuration', 1);
109
+ }
110
+ function resolution(status, selected, reason, candidates) {
111
+ return { schemaVersion: 1, status, selected, reason, candidates };
112
+ }
113
+ function inventory(selected) {
114
+ // Never pass selected as listing's pin: send must inventory competing homes.
115
+ const automatic = listingCandidates();
116
+ const explicit = selected === undefined ? undefined : listingCandidates(selected);
117
+ const items = [...(explicit?.homes ?? []), ...automatic.homes];
118
+ const merged = new Map();
119
+ for (const item of items) {
120
+ const old = merged.get(item.codexHome);
121
+ if (old) {
122
+ old.required ||= item.required;
123
+ old.sources = [...new Set([...old.sources, ...item.sources])];
140
124
  }
141
- if (!Array.isArray(paths) || paths.some(p => typeof p !== 'string' || (!isAbsolute(p) && !p.startsWith('~/'))))
142
- throw new Refusal('invalid_home_configuration', 1);
143
- for (const path of paths)
144
- result.add(canonical(path));
125
+ else
126
+ merged.set(item.codexHome, { ...item, sources: [...item.sources] });
127
+ }
128
+ const homes = [...merged.values()].sort((a, b) => a.codexHome < b.codexHome ? -1 : a.codexHome > b.codexHome ? 1 : 0);
129
+ const candidates = homes.map(item => ({ codexHome: item.codexHome, sources: item.sources,
130
+ savedThread: null, writerLock: 'not_checked', reason: 'not_inspected' }));
131
+ const errors = [...(explicit?.errors ?? []), ...automatic.errors];
132
+ if (errors.length) {
133
+ const reason = errors.some(e => e.code === 'invalid_home_configuration') ? 'invalid_home_configuration' :
134
+ errors.some(e => e.code === 'home_resolution_failed') ? 'home_resolution_failed' : 'home_inventory_unreadable';
135
+ throw new HomeRefusal(reason, resolution('unknown', null, reason, candidates));
145
136
  }
146
- return [...result].sort();
137
+ return { homes, candidates, explicit: explicit?.homes[0]?.codexHome };
147
138
  }
148
- export async function resolveWriter(selected, id) {
139
+ export function homes(selected) { return inventory(selected).homes.map(item => item.codexHome); }
140
+ export async function resolveWriter(selected, id, allowInactive = false) {
141
+ if (!uuid(id))
142
+ throw new HomeRefusal('codex_uuid_required', resolution('unknown', null, 'invalid_thread_id', []), 2);
143
+ if (selected !== undefined && !selected)
144
+ throw new HomeRefusal('invalid_codex_home', resolution('unknown', null, 'invalid_codex_home', []), 2);
145
+ if (allowInactive && !selected)
146
+ throw new HomeRefusal('inactive_opt_in_requires_explicit_home', resolution('unknown', null, 'inactive_opt_in_requires_explicit_home', []), 2);
147
+ const { homes: inventoryHomes, candidates, explicit } = inventory(selected);
149
148
  const { DatabaseSync } = await import('node:sqlite');
150
- const candidates = homes(selected);
151
- const matches = [];
152
- for (const home of candidates) {
153
- let saved = false;
149
+ const fingerprints = [];
150
+ for (const [index, item] of inventoryHomes.entries()) {
151
+ const candidate = candidates[index];
152
+ let dbFingerprint = 'absent';
153
+ let present = true;
154
154
  try {
155
- const db = new DatabaseSync(join(home, 'state_5.sqlite'), { readOnly: true });
156
155
  try {
157
- db.exec('PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=3000');
158
- saved = Boolean(db.prepare('SELECT 1 FROM threads WHERE id=? LIMIT 1').get(id));
156
+ if (!statSync(item.stateDb).isFile()) {
157
+ candidate.reason = 'state_db_not_regular';
158
+ throw new Error();
159
+ }
160
+ }
161
+ catch (error) {
162
+ if (!missing(error))
163
+ throw error;
164
+ present = false;
165
+ candidate.savedThread = false;
166
+ candidate.reason = item.required ? 'state_db_missing' : 'state_db_absent';
167
+ if (item.required)
168
+ throw new Error();
159
169
  }
160
- finally {
161
- db.close();
170
+ if (present) {
171
+ // Track file identity, not mtime: normal unrelated DB activity is allowed.
172
+ const before = statSync(item.stateDb, { bigint: true });
173
+ const db = new DatabaseSync(item.stateDb, { readOnly: true });
174
+ try {
175
+ db.exec('PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=3000');
176
+ candidate.savedThread = Boolean(db.prepare('SELECT 1 FROM threads WHERE id=? LIMIT 1').get(id));
177
+ }
178
+ finally {
179
+ db.close();
180
+ }
181
+ const after = statSync(item.stateDb, { bigint: true });
182
+ if (before.dev !== after.dev || before.ino !== after.ino) {
183
+ candidate.reason = 'state_db_changed';
184
+ throw new Error();
185
+ }
186
+ dbFingerprint = `${after.dev}:${after.ino}`;
187
+ candidate.reason = candidate.savedThread ? 'saved_thread' : 'thread_not_saved';
162
188
  }
163
189
  }
190
+ catch (error) {
191
+ if (candidate.reason === 'not_inspected')
192
+ candidate.reason =
193
+ ['EACCES', 'EPERM'].includes(error.code ?? '') ? 'permission_denied' : 'state_db_read_failed';
194
+ throw new HomeRefusal('home_inventory_unreadable', resolution('unknown', null, 'home_inventory_unreadable', candidates));
195
+ }
196
+ // Inspect this UUID even without a saved row: an unsaved competing first turn
197
+ // is not permission to queue elsewhere. Optional absent homes remain bounded.
198
+ try {
199
+ const writer = await inspectWriter(item.codexHome, id);
200
+ candidate.activity = writer.activity;
201
+ candidate.writerLock = writer.writerLock;
202
+ if (writer.activity === 'live_writer')
203
+ candidate.reason = 'stable_live_writer';
204
+ fingerprints.push({ home: item.codexHome, database: dbFingerprint, writer: writer.identity });
205
+ }
164
206
  catch {
165
- throw new Refusal('home_inventory_unreadable', 1);
207
+ candidate.activity = 'unknown';
208
+ candidate.writerLock = 'unknown';
209
+ candidate.reason = 'active_writer_unverified';
210
+ throw new HomeRefusal('active_writer_unverified', resolution('unknown', null, 'active_writer_unverified', candidates));
166
211
  }
167
- if (saved)
168
- matches.push({ home, ...await inspectWriter(home, id) });
169
212
  }
170
- const live = matches.filter(c => c.activity === 'live_writer');
171
- if (!matches.length)
172
- throw new Refusal('thread_not_saved_in_known_homes', 2);
173
- if (live.length !== 1)
174
- throw new Refusal(live.length ? 'multiple_live_writers' : 'inactive_writer', 1);
175
- if (live[0].home !== canonical(selected))
176
- throw new Refusal('explicit_home_conflicts_with_live_writer', 1);
177
- // Include inactive competitors and inventory in the pre-submit revalidation token.
178
- return JSON.stringify({ candidates, matches });
213
+ const refuse = (code, status = 'unknown', exitCode = 1, reason = code) => {
214
+ throw new HomeRefusal(code, resolution(status, null, reason, candidates), exitCode);
215
+ };
216
+ const live = candidates.filter(c => c.activity === 'live_writer');
217
+ if (live.length > 1)
218
+ refuse('multiple_live_writers', 'ambiguous');
219
+ let chosen;
220
+ let reason;
221
+ if (live.length === 1) {
222
+ chosen = live[0];
223
+ if (explicit !== undefined && chosen.codexHome !== explicit)
224
+ refuse('explicit_home_conflicts_with_live_writer', 'ambiguous');
225
+ if (!chosen.savedThread)
226
+ refuse('thread_not_yet_persisted', 'unknown', 2);
227
+ reason = explicit === undefined ? 'single_stable_live_writer' : 'explicit_live_writer';
228
+ }
229
+ else {
230
+ if (!candidates.some(c => c.savedThread))
231
+ refuse('thread_not_saved_in_known_homes', 'unknown', 2);
232
+ const pinned = candidates.find(c => c.codexHome === explicit);
233
+ if (explicit !== undefined && !pinned?.savedThread)
234
+ refuse('thread_not_saved_in_explicit_home', 'unknown', 2);
235
+ if (!allowInactive || !pinned)
236
+ refuse('inactive_writer', 'ambiguous', 1, 'inactive_queue_requires_opt_in');
237
+ chosen = pinned;
238
+ reason = 'explicit_inactive_opt_in';
239
+ }
240
+ const result = resolution(explicit === undefined ? 'selected' : 'explicit', chosen.codexHome, reason, candidates);
241
+ // Bind all candidates (including inactive, absent and unsaved competitors),
242
+ // saved-row presence, DB identity and native owner/file evidence to revalidation.
243
+ return { home: chosen.codexHome, resolution: result, evidence: JSON.stringify({ result, fingerprints }) };
244
+ }
245
+ export async function revalidateWriter(previous, selected, id, allowInactive = false) {
246
+ const current = await resolveWriter(selected, id, allowInactive);
247
+ if (current.evidence !== previous.evidence) {
248
+ throw new HomeRefusal('writer_evidence_changed_before_queue', resolution('unknown', null, 'writer_evidence_changed_before_queue', current.resolution.candidates));
249
+ }
179
250
  }
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "session-peer",
3
- "version": "0.1.0-preview.1",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "registry": "https://registry.npmjs.org/",
7
7
  "access": "public",
8
- "tag": "preview"
8
+ "tag": "latest"
9
9
  },
10
10
  "repository": { "type": "git", "url": "git+https://github.com/abruption/session-peer-ts.git" },
11
11
  "os": ["darwin", "linux", "win32"],
12
- "description": "Python-free local and SSH client for Claude Code and Codex sessions (preview)",
12
+ "description": "Python-free local and SSH client for Claude Code and Codex sessions",
13
13
  "type": "module",
14
14
  "types": "./dist/index.d.ts",
15
15
  "exports": {
@@ -31,13 +31,15 @@
31
31
  "CONTRIBUTING.md",
32
32
  "RELEASING.md",
33
33
  "SECURITY.md",
34
- "VALIDATION.md"
34
+ "VALIDATION.md",
35
+ "PARITY.md",
36
+ "UNICODE-LICENSE.txt"
35
37
  ],
36
38
  "scripts": {
37
39
  "build": "tsc -p tsconfig.json",
38
40
  "test": "npm run build && npm run test:types && node --experimental-strip-types --test test/*.test.ts",
39
41
  "test:types": "tsc -p tsconfig.test.json",
40
- "test:windows": "npm run build && npm run test:types && node --experimental-strip-types --test test/windows.test.ts",
42
+ "test:windows": "npm run build && npm run test:types && node --experimental-strip-types --test --test-concurrency=1 test/windows.test.ts test/windows-contract.test.ts test/input-boundaries.test.ts test/discovery.test.ts test/codex-homes.test.ts test/diagnostics.test.ts test/cli-usability.test.ts test/skill-guidance.test.ts",
41
43
  "test:package": "npm run build && node --experimental-strip-types test/package-smoke.ts"
42
44
  },
43
45
  "devDependencies": {