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.
@@ -0,0 +1,225 @@
1
+ // Diagnostics inspect bounded metadata only. Never probe/connect to an inbox,
2
+ // acquire a writer lock, execute an agent binary, or write configuration.
3
+ import { accessSync, constants, readdirSync, readFileSync, statSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { delimiter, isAbsolute, join } from 'node:path';
6
+ import { canonical, listingCandidates } from './discovery.js';
7
+ import { windowsProcessStart } from './windows.js';
8
+ const failure = (error, missing, unknown) => {
9
+ const code = error.code;
10
+ return code === 'ENOENT' || code === 'ENOTDIR' ? { status: 'missing', code: missing } :
11
+ code === 'EACCES' || code === 'EPERM' ? { status: 'permission_denied', code: 'permission_denied' } :
12
+ { status: 'unknown', code: unknown };
13
+ };
14
+ export const capabilities = {
15
+ list: true, send: true, doctor: true, wake: false, wait: false, ack: false,
16
+ consumptionConfirmation: false, transports: ['local', 'ssh'], agents: ['claude', 'codex']
17
+ };
18
+ function tool(name) {
19
+ const names = process.platform === 'win32' && !/\.(?:exe|cmd|bat)$/i.test(name) ? [name + '.exe', name + '.cmd', name] : [name];
20
+ const paths = isAbsolute(name) ? [name] : name.includes('/') || name.includes('\\') ? [] :
21
+ (process.env.PATH ?? '').split(delimiter).filter(Boolean).flatMap(path => names.map(base => join(path, base)));
22
+ let diagnostic = { status: 'missing', code: 'executable_unavailable', executed: false };
23
+ for (const path of paths) {
24
+ try {
25
+ if (!statSync(path).isFile())
26
+ continue;
27
+ accessSync(path, constants.X_OK);
28
+ return { status: 'available', code: 'executable_found', path, executed: false };
29
+ }
30
+ catch (error) {
31
+ const found = failure(error, 'executable_unavailable', 'executable_inspection_unknown');
32
+ if (found.status !== 'missing')
33
+ diagnostic = { ...found, executed: false };
34
+ }
35
+ }
36
+ return diagnostic;
37
+ }
38
+ async function codexHome(file) {
39
+ try {
40
+ if (!statSync(file).isFile())
41
+ return { status: 'unsupported', code: 'state_db_not_regular' };
42
+ accessSync(file, constants.R_OK);
43
+ }
44
+ catch (error) {
45
+ return failure(error, 'state_db_missing', 'state_db_unreadable');
46
+ }
47
+ try {
48
+ const { DatabaseSync } = await import('node:sqlite');
49
+ const db = new DatabaseSync(file, { readOnly: true });
50
+ try {
51
+ db.exec('PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=3000');
52
+ const columns = new Set(db.prepare('PRAGMA table_info(threads)').all().map(row => row.name));
53
+ const missingColumns = ['id', 'title', 'cwd', 'updated_at', 'archived', 'rollout_path'].filter(name => !columns.has(name));
54
+ if (missingColumns.length)
55
+ return { status: 'unsupported', code: 'unsupported_threads_schema', missingColumns };
56
+ const count = db.prepare('SELECT COUNT(*) AS count FROM threads').get().count;
57
+ return { status: 'available', code: 'state_db_readable', sessionCount: count };
58
+ }
59
+ finally {
60
+ db.close();
61
+ }
62
+ }
63
+ catch (error) {
64
+ return failure(error, 'state_db_missing', 'state_db_unreadable');
65
+ }
66
+ }
67
+ export async function diagnoseCodex(home, binary) {
68
+ const inventory = listingCandidates(home);
69
+ const homes = [];
70
+ for (const item of inventory.homes)
71
+ homes.push({ ...item, ...await codexHome(item.stateDb) });
72
+ const agentTool = tool(binary ?? 'codex');
73
+ const complete = inventory.errors.length === 0 && homes.every(item => item.status === 'available' || (!item.required && item.status === 'missing'));
74
+ const ready = complete && homes.some(item => item.status === 'available') && agentTool.status === 'available';
75
+ return { ready, status: ready ? 'available' : 'unavailable', tool: agentTool, homes,
76
+ errors: inventory.errors, verification: 'read_only_metadata', writerVerified: false,
77
+ sendAuthorized: false };
78
+ }
79
+ export function diagnoseClaude() {
80
+ const directory = join(process.env.CLAUDE_CONFIG_DIR || process.env.ANTHROPIC_CONFIG_DIR || join(homedir(), '.claude'), 'sessions');
81
+ const result = { sessionsDir: directory, records: 0, invalidRecords: 0, aliveSessions: 0,
82
+ availableInboxes: 0, staleRecords: 0, unknownInspections: 0, permissionFailures: 0 };
83
+ let entries;
84
+ try {
85
+ if (!statSync(directory).isDirectory())
86
+ return { ...result, ready: false, status: 'unsupported', code: 'sessions_path_not_directory' };
87
+ entries = readdirSync(directory).sort();
88
+ }
89
+ catch (error) {
90
+ return { ...result, ready: false, ...failure(error, 'sessions_dir_missing', 'sessions_dir_unreadable') };
91
+ }
92
+ for (const entry of entries) {
93
+ if (!/^[0-9]+\.json$/.test(entry))
94
+ continue;
95
+ let record;
96
+ try {
97
+ const path = join(directory, entry), info = statSync(path);
98
+ if (!info.isFile() || info.size > 65536) {
99
+ result.invalidRecords++;
100
+ continue;
101
+ }
102
+ const value = JSON.parse(readFileSync(path, 'utf8'));
103
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
104
+ result.invalidRecords++;
105
+ continue;
106
+ }
107
+ record = value;
108
+ }
109
+ catch (error) {
110
+ if (['EACCES', 'EPERM'].includes(error.code ?? ''))
111
+ result.permissionFailures++;
112
+ else if (error instanceof SyntaxError)
113
+ result.invalidRecords++;
114
+ else
115
+ result.unknownInspections++;
116
+ continue;
117
+ }
118
+ const pid = record.pid;
119
+ if (typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid <= 1 || pid > 2147483647) {
120
+ result.invalidRecords++;
121
+ continue;
122
+ }
123
+ result.records++;
124
+ if (pid !== Number(entry.slice(0, -5))) {
125
+ result.staleRecords++;
126
+ continue;
127
+ }
128
+ let live = false;
129
+ if (process.platform === 'win32') {
130
+ const ticks = windowsProcessStart(pid);
131
+ if (ticks === undefined || typeof record.startedAt !== 'number' || !Number.isSafeInteger(record.startedAt) || record.startedAt <= 0) {
132
+ result.unknownInspections++;
133
+ continue;
134
+ }
135
+ live = Number((ticks - 116444736000000000n) / 10000n) <= record.startedAt + 2000;
136
+ }
137
+ else {
138
+ try {
139
+ process.kill(pid, 0);
140
+ live = true;
141
+ }
142
+ catch (error) {
143
+ if (error.code !== 'ESRCH') {
144
+ result.unknownInspections++;
145
+ continue;
146
+ }
147
+ }
148
+ }
149
+ if (!live) {
150
+ result.staleRecords++;
151
+ continue;
152
+ }
153
+ result.aliveSessions++;
154
+ const socket = typeof record.messagingSocketPath === 'string' ? record.messagingSocketPath : '';
155
+ if (process.platform === 'win32') {
156
+ // A named pipe advertisement is not proof that the pipe exists or accepts connections.
157
+ if (/^\\\\\.\\pipe\\[^\r\n]+$/i.test(socket))
158
+ result.availableInboxes++;
159
+ }
160
+ else if (socket) {
161
+ try {
162
+ if (statSync(socket).isSocket())
163
+ result.availableInboxes++;
164
+ }
165
+ catch (error) {
166
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code ?? '')) {
167
+ result.unknownInspections++;
168
+ if (['EACCES', 'EPERM'].includes(error.code ?? ''))
169
+ result.permissionFailures++;
170
+ }
171
+ }
172
+ }
173
+ }
174
+ const ready = result.availableInboxes > 0 && result.permissionFailures === 0 && result.unknownInspections === 0;
175
+ const code = result.permissionFailures ? 'permission_denied' : result.unknownInspections ? 'inspection_unknown' :
176
+ result.availableInboxes ? 'inbox_advertised' : result.aliveSessions ? 'inbox_unavailable' : 'no_live_sessions';
177
+ return { ...result, ready, status: ready ? 'available' : 'unavailable', code,
178
+ verification: process.platform === 'win32' ? 'process_and_pipe_advertisement' : 'process_and_filesystem',
179
+ inboxConnected: false, sendAuthorized: false };
180
+ }
181
+ export async function doctor(agent, home, binary) {
182
+ const agents = {};
183
+ if (!agent || agent === 'claude')
184
+ agents.claude = diagnoseClaude();
185
+ if (!agent || agent === 'codex')
186
+ agents.codex = await diagnoseCodex(home, binary);
187
+ return { ok: true, ready: Object.values(agents).every(item => item.ready === true), agents,
188
+ implementation: 'typescript', skills: inspectSkills(home), capabilities, diagnosticCompleted: true, consumptionConfirmed: false };
189
+ }
190
+ // Inspect only named skill entrypoints; interpret frontmatter, never instructions or references.
191
+ export function inspectSkills(home) {
192
+ const paths = new Set([join(homedir(), '.agents/skills/session-peer-ts/SKILL.md'),
193
+ join(home || process.env.CODEX_HOME || join(homedir(), '.codex'), 'skills/session-peer-ts/SKILL.md')]);
194
+ return [...paths].map(path => {
195
+ try {
196
+ path = canonical(path);
197
+ if (!statSync(path).isFile() || statSync(path).size > 65536)
198
+ return { path, status: 'unknown', code: 'skill_metadata_unreadable' };
199
+ const text = readFileSync(path, 'utf8');
200
+ const front = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text)?.[1];
201
+ if (!front)
202
+ return { path, status: 'unknown', code: 'skill_metadata_missing' };
203
+ const lines = front.split(/\r?\n/);
204
+ const sections = lines.map((line, index) => /^metadata: *(?:#.*)?$/.test(line) ? index : -1).filter(index => index >= 0);
205
+ if (sections.length !== 1)
206
+ return { path, status: 'unknown', code: 'skill_metadata_missing' };
207
+ const start = sections[0] + 1;
208
+ let end = start;
209
+ while (end < lines.length && (/^ /.test(lines[end]) || /^ *(?:#.*)?$/.test(lines[end])))
210
+ end++;
211
+ const fields = lines.slice(start, end).map(line => /^ ([a-z-]+): *(?:"([^"\r\n]*)"|'([^'\r\n]*)'|([^#"'\r\n]*?)) *(?:#.*)?$/.exec(line));
212
+ const field = (key) => {
213
+ const values = fields.filter(match => match?.[1] === key).map(match => (match[2] ?? match[3] ?? match[4]).trim());
214
+ return values.length === 1 ? values[0] : undefined;
215
+ };
216
+ const implementation = field('runtime-implementation'), minimum = field('runtime-min-version');
217
+ const policy = field('runtime-capability-policy');
218
+ const compatible = implementation === 'typescript' && minimum === '0.1.0' && policy === 'probe-help' && field('version') === '0.1.0' && field('runtime-full-version') === '0.1.0';
219
+ return { path, status: compatible ? 'compatible' : 'incompatible', code: compatible ? 'skill_contract_compatible' : 'skill_contract_mismatch', verification: 'metadata_only' };
220
+ }
221
+ catch (error) {
222
+ return { path, ...failure(error, 'skill_missing', 'skill_metadata_unreadable') };
223
+ }
224
+ });
225
+ }
@@ -6,5 +6,25 @@ export declare class Refusal extends Error {
6
6
  }
7
7
  export declare function canonical(path: string): string;
8
8
  export declare function claude(all: boolean): Row;
9
- export declare function codex(path: string, all: boolean): Promise<Row>;
9
+ export declare function configuredHomePaths(): string[];
10
+ export declare function orcaHomePaths(): string[];
11
+ type Candidate = {
12
+ codexHome: string;
13
+ stateDb: string;
14
+ sources: string[];
15
+ required: boolean;
16
+ };
17
+ type Listing = {
18
+ sessions: Row[];
19
+ discovery: Record<string, Row>;
20
+ ok?: boolean;
21
+ codexHome?: string;
22
+ error?: string;
23
+ };
24
+ export declare function listingCandidates(explicit?: string): {
25
+ homes: Candidate[];
26
+ errors: Row[];
27
+ };
28
+ export declare function codex(path: string | undefined, all: boolean): Promise<Listing>;
29
+ export declare function listing(agent: 'claude' | 'codex' | undefined, home: string | undefined, all: boolean): Promise<Listing>;
10
30
  export {};
package/dist/discovery.js CHANGED
@@ -1,7 +1,8 @@
1
- // Deliberately read-only: no subprocess, network, socket connection or DB writes.
2
- import { readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
1
+ // Read-only discovery: no inbox connections, writer selection, queue or DB writes.
2
+ // Windows Claude metadata uses native process inspection.
3
+ import { lstatSync, readFileSync, readlinkSync, readdirSync, realpathSync, statSync } from 'node:fs';
3
4
  import { homedir } from 'node:os';
4
- import { dirname, join, resolve } from 'node:path';
5
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
5
6
  import { windowsProcessStart } from './windows.js';
6
7
  export class Refusal extends Error {
7
8
  code;
@@ -20,15 +21,33 @@ export function canonical(path) {
20
21
  path = join(homedir(), path.slice(2));
21
22
  else if (path.startsWith('~'))
22
23
  throw new Refusal('unsupported_home_expansion');
23
- const absolute = resolve(path);
24
+ return canonicalPath(resolve(path), new Set());
25
+ }
26
+ function canonicalPath(absolute, seen) {
27
+ if (seen.has(absolute))
28
+ throw new Refusal('home_resolution_failed', 1);
29
+ seen.add(absolute);
24
30
  try {
25
31
  return realpathSync(absolute);
26
32
  }
27
33
  catch (error) {
28
34
  if (!missing(error))
29
35
  throw new Refusal('home_resolution_failed', 1);
36
+ // realpath fails for dangling links. Resolve the link itself before falling
37
+ // back to its parent, so missing aliases still merge required source labels.
38
+ let target;
39
+ try {
40
+ if (lstatSync(absolute).isSymbolicLink())
41
+ target = readlinkSync(absolute);
42
+ }
43
+ catch (linkError) {
44
+ if (!missing(linkError))
45
+ throw new Refusal('home_resolution_failed', 1);
46
+ }
47
+ if (target !== undefined)
48
+ return canonicalPath(resolve(dirname(absolute), target), seen);
30
49
  const parent = dirname(absolute);
31
- return parent === absolute ? absolute : join(canonical(parent), absolute.slice(parent.length));
50
+ return parent === absolute ? absolute : join(canonicalPath(parent, seen), absolute.slice(parent.length));
32
51
  }
33
52
  }
34
53
  function alive(pid) {
@@ -104,59 +123,176 @@ export function claude(all) {
104
123
  }
105
124
  return { sessions, discovery: { claude: { status: 'ok' } } };
106
125
  }
107
- export async function codex(path, all) {
108
- const home = canonical(path);
109
- const file = join(home, 'state_5.sqlite');
110
- const item = { codexHome: home, stateDb: file, sources: ['argument'] };
111
- let sessions = [];
112
- let code;
126
+ // Shared bounded sources; listing accumulates diagnostics while writer inventory
127
+ // keeps its stricter, fail-closed policy. No recursive scan or credential reads.
128
+ export function configuredHomePaths() {
129
+ const value = process.env.SESSION_PEER_CODEX_HOMES;
130
+ if (value === undefined)
131
+ return [];
132
+ let paths;
113
133
  try {
114
- if (!statSync(file).isFile())
115
- code = 'state_db_not_regular';
134
+ paths = JSON.parse(value);
116
135
  }
117
- catch (error) {
118
- code = missing(error) ? 'state_db_missing' : 'state_db_read_failed';
136
+ catch {
137
+ throw new Refusal('invalid_home_configuration', 1);
119
138
  }
120
- if (!code) {
139
+ if (!Array.isArray(paths) || paths.some(p => typeof p !== 'string' || !p.trim() ||
140
+ p.includes('\0') || (!isAbsolute(p) && !p.startsWith('~/')))) {
141
+ throw new Refusal('invalid_home_configuration', 1);
142
+ }
143
+ return paths;
144
+ }
145
+ export function orcaHomePaths() {
146
+ const directory = join(homedir(), 'Library/Application Support/orca/codex-accounts');
147
+ return readdirSync(directory).sort(compareText).map(entry => join(directory, entry, 'home'));
148
+ }
149
+ function compareText(a, b) {
150
+ // Python sorts Unicode code points, independent of locale and UTF-16 ordering.
151
+ const left = [...a], right = [...b];
152
+ for (let i = 0; i < Math.min(left.length, right.length); i++) {
153
+ const diff = left[i].codePointAt(0) - right[i].codePointAt(0);
154
+ if (diff)
155
+ return diff;
156
+ }
157
+ return left.length - right.length;
158
+ }
159
+ export function listingCandidates(explicit) {
160
+ const candidates = new Map(), errors = [];
161
+ function add(path, source, required) {
162
+ let home;
121
163
  try {
122
- // Lazy import: Claude-only commands don't initialize experimental SQLite.
123
- const { DatabaseSync } = await import('node:sqlite');
124
- const db = new DatabaseSync(file, { readOnly: true });
164
+ home = canonical(path);
165
+ }
166
+ catch {
167
+ errors.push({ source, path, code: 'home_resolution_failed', error: 'home_resolution_failed' });
168
+ return;
169
+ }
170
+ const item = candidates.get(home) ?? { codexHome: home, stateDb: join(home, 'state_5.sqlite'), sources: [], required: false };
171
+ if (!item.sources.includes(source))
172
+ item.sources.push(source);
173
+ item.required ||= required;
174
+ candidates.set(home, item);
175
+ }
176
+ if (explicit !== undefined)
177
+ add(explicit, 'argument', true);
178
+ else {
179
+ add(join(homedir(), '.codex'), 'default', false);
180
+ if (process.env.CODEX_HOME)
181
+ add(process.env.CODEX_HOME, 'environment', true);
182
+ if (process.platform === 'darwin') {
125
183
  try {
126
- db.exec('PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=3000');
127
- const columns = new Set(db.prepare('PRAGMA table_info(threads)').all().map(row => row.name));
128
- const required = ['id', 'title', 'cwd', 'updated_at', 'archived', 'rollout_path'];
129
- if (!required.every(name => columns.has(name)))
130
- throw new Error('unsupported_schema');
131
- const name = columns.has('name') ? "COALESCE(NULLIF(name, ''), NULLIF(title, ''), id)" : "COALESCE(NULLIF(title, ''), id)";
132
- const rows = db.prepare(`SELECT id, ${name} AS display_name, cwd, updated_at, archived FROM threads ${all ? '' : 'WHERE archived = 0'} ORDER BY updated_at DESC, id ASC`).all();
133
- sessions = rows.map(row => {
134
- if (typeof row.id !== 'string' || !row.id || typeof row.display_name !== 'string' ||
135
- typeof row.updated_at !== 'number' || !Number.isSafeInteger(row.updated_at) ||
136
- typeof row.archived !== 'number' || (row.cwd !== null && typeof row.cwd !== 'string')) {
137
- throw new Error('unsupported_row');
138
- }
139
- // Python slicing counts Unicode code points, not JS UTF-16 units.
140
- const firstLine = row.display_name.split(/[\n\r\v\f\x1c-\x1e\x85\u2028\u2029]/u)[0] ?? '';
141
- return { agent: 'codex', id: row.id, name: [...firstLine].slice(0, 120).join(''),
142
- cwd: row.cwd, updatedAt: row.updated_at, archived: Boolean(row.archived),
143
- codexHome: home, stateDb: file };
144
- });
184
+ for (const home of orcaHomePaths())
185
+ add(home, 'orca', false);
145
186
  }
146
- finally {
147
- db.close();
187
+ catch (error) {
188
+ if (error.code !== 'ENOENT') {
189
+ errors.push({ source: 'orca', path: join(homedir(), 'Library/Application Support/orca/codex-accounts'),
190
+ code: 'candidate_enumeration_failed', error: 'candidate_enumeration_failed' });
191
+ }
148
192
  }
149
193
  }
194
+ try {
195
+ for (const home of configuredHomePaths())
196
+ add(home, 'configured', true);
197
+ }
150
198
  catch {
151
- code = 'state_db_read_failed';
152
- sessions = [];
199
+ errors.push({ source: 'configured', code: 'invalid_home_configuration', error: 'invalid_home_configuration' });
153
200
  }
154
201
  }
155
- const failed = Boolean(code);
156
- Object.assign(item, failed ? { status: 'error', code, error: code } : { status: 'ok', sessionCount: sessions.length });
157
- const discovery = { status: failed ? 'error' : 'ok', homes: [item] };
202
+ return { homes: [...candidates.values()], errors };
203
+ }
204
+ async function readCodex(home, file, all) {
205
+ // Lazy import: Claude-only commands don't initialize experimental SQLite.
206
+ const { DatabaseSync } = await import('node:sqlite');
207
+ const db = new DatabaseSync(file, { readOnly: true });
208
+ try {
209
+ db.exec('PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=3000');
210
+ const columns = new Set(db.prepare('PRAGMA table_info(threads)').all().map(row => row.name));
211
+ const required = ['id', 'title', 'cwd', 'updated_at', 'archived', 'rollout_path'];
212
+ if (!required.every(name => columns.has(name)))
213
+ throw new Error('unsupported_schema');
214
+ const name = columns.has('name') ? "COALESCE(NULLIF(name, ''), NULLIF(title, ''), id)" : "COALESCE(NULLIF(title, ''), id)";
215
+ const rows = db.prepare(`SELECT id, ${name} AS display_name, cwd, updated_at, archived FROM threads ${all ? '' : 'WHERE archived = 0'} ORDER BY updated_at DESC, id ASC`).all();
216
+ return rows.map(row => {
217
+ if (typeof row.id !== 'string' || !row.id || typeof row.display_name !== 'string' ||
218
+ typeof row.updated_at !== 'number' || !Number.isSafeInteger(row.updated_at) ||
219
+ typeof row.archived !== 'number' || (row.cwd !== null && typeof row.cwd !== 'string')) {
220
+ throw new Error('unsupported_row');
221
+ }
222
+ const firstLine = row.display_name.split(/[\n\r\v\f\x1c-\x1e\x85\u2028\u2029]/u)[0] ?? '';
223
+ return { agent: 'codex', id: row.id, name: [...firstLine].slice(0, 120).join(''),
224
+ cwd: row.cwd, updatedAt: row.updated_at, archived: Boolean(row.archived),
225
+ codexHome: home, stateDb: file };
226
+ });
227
+ }
228
+ finally {
229
+ db.close();
230
+ }
231
+ }
232
+ export async function codex(path, all) {
233
+ const { homes, errors } = listingCandidates(path);
234
+ const sessions = [], diagnostics = [];
235
+ for (const { required, ...item } of homes) {
236
+ let code;
237
+ let absent = false;
238
+ try {
239
+ if (!statSync(item.stateDb).isFile())
240
+ code = 'state_db_not_regular';
241
+ }
242
+ catch (error) {
243
+ if (missing(error)) {
244
+ if (required)
245
+ code = 'state_db_missing';
246
+ else
247
+ absent = true;
248
+ }
249
+ else
250
+ code = ['EACCES', 'EPERM'].includes(error.code ?? '') ? 'permission_denied' : 'state_db_read_failed';
251
+ }
252
+ let rows = [];
253
+ if (!code && !absent) {
254
+ try {
255
+ rows = await readCodex(item.codexHome, item.stateDb, all);
256
+ }
257
+ catch (error) {
258
+ code = ['EACCES', 'EPERM'].includes(error.code ?? '') ? 'permission_denied' : 'state_db_read_failed';
259
+ }
260
+ }
261
+ sessions.push(...rows);
262
+ diagnostics.push({ ...item, ...(code ? { status: 'error', code, error: code } :
263
+ absent ? { status: 'absent', code: 'state_db_absent' } : { status: 'ok', sessionCount: rows.length }) });
264
+ }
265
+ sessions.sort((a, b) => Number(b.updatedAt) - Number(a.updatedAt) ||
266
+ compareText(String(a.codexHome), String(b.codexHome)) || compareText(String(a.id), String(b.id)));
267
+ const failed = errors.length > 0 || diagnostics.some(item => item.status === 'error');
268
+ const discovery = { status: failed ? 'error' : diagnostics.some(item => item.status === 'ok') ? 'ok' : 'not_installed', homes: diagnostics };
269
+ if (errors.length)
270
+ discovery.errors = errors;
158
271
  if (failed)
159
272
  discovery.error = 'Codex home discovery is incomplete; inspect homes and errors';
160
- return { sessions, codexHome: home, discovery: { codex: discovery }, ok: !failed,
273
+ return { sessions, discovery: { codex: discovery }, ok: !failed,
274
+ ...(homes.length === 1 && !errors.length ? { codexHome: homes[0].codexHome } : {}),
161
275
  ...(failed ? { error: 'Discovery failed for: codex' } : {}) };
162
276
  }
277
+ export async function listing(agent, home, all) {
278
+ const result = { sessions: [], discovery: {}, ok: true };
279
+ for (const name of agent ? [agent] : ['claude', 'codex']) {
280
+ try {
281
+ const found = name === 'claude' ? claude(all) : await codex(home, all);
282
+ result.sessions.push(...found.sessions);
283
+ Object.assign(result.discovery, found.discovery);
284
+ if (found.codexHome !== undefined)
285
+ result.codexHome = found.codexHome;
286
+ }
287
+ catch (error) {
288
+ const code = error instanceof Refusal ? error.code : 'discovery_failed';
289
+ result.discovery[name] = { status: 'error', error: code };
290
+ }
291
+ }
292
+ const failed = Object.keys(result.discovery).filter(name => result.discovery[name].status === 'error');
293
+ if (failed.length) {
294
+ result.ok = false;
295
+ result.error = 'Discovery failed for: ' + failed.join(', ');
296
+ }
297
+ return result;
298
+ }
package/dist/help.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function help(command?: string): string;
package/dist/help.js ADDED
@@ -0,0 +1,50 @@
1
+ import { VERSION } from './protocol.js';
2
+ export function help(command) {
3
+ const common = `Output (required for operations; no default):
4
+ --json | --output-format json|text JSON stays one machine-readable object
5
+ Transport:
6
+ --host HOST SSH destination (no nested transports)
7
+ --remote-bin ABSOLUTE_PATH Remote session-peer executable
8
+ --remote-platform posix|win32 Remote shell platform
9
+ --ssh-control-path SOCKET Existing SSH control socket
10
+ --no-update-notice Accepted compatibility flag
11
+ -h, --help Show command help`;
12
+ if (command === 'list')
13
+ return `Usage: session-peer list [options]
14
+ List reachable Claude and saved Codex sessions. Listing is not send authorization.
15
+ --agent claude|codex Filter one agent (default: both)
16
+ --codex-home HOME Pin Codex listing to one home
17
+ --all Include stale Claude/archived Codex rows
18
+ ${common}`;
19
+ if (command === 'doctor')
20
+ return `Usage: session-peer doctor [options]
21
+ Read-only metadata/capability diagnostics; does not send, wake or authorize a send.
22
+ Successful diagnostics exit 0 even when ready=false. Check readiness separately.
23
+ --agent claude|codex Filter one agent (default: both)
24
+ --codex-home HOME Pin Codex metadata inspection
25
+ --codex-bin PATH Inspect executable availability; never execute it
26
+ ${common}`;
27
+ if (command === 'send')
28
+ return `Usage: session-peer send --to TARGET [MESSAGE | --message TEXT | -m TEXT] [options]
29
+ TARGET: Claude name/PID, claude:NAME/PID, codex:UUID, or session-peer reply URI.
30
+ Omit the body or use - for UTF-8 stdin. Only one body source is permitted.
31
+ Unicode names use exact Unicode 14.0.0 default casefold; collisions require PID.
32
+ --dry-run Validate without submission
33
+ --codex-home HOME Explicit Codex home; otherwise select unique live writer
34
+ --codex-bin PATH Native Codex executable
35
+ --allow-inactive-codex-home Queue only with explicit verified inactive home
36
+ --no-from Omit sender envelope
37
+ --no-reply-to Do not add a reply route
38
+ --reply-address URI Explicit reply route (conflicts with --no-reply-to)
39
+ Queued/posted is not ACK. Unknown outcomes must not be retried automatically.
40
+ ${common}`;
41
+ return `session-peer ${VERSION} (TypeScript)
42
+ Usage: session-peer <command> [options]
43
+ list List Claude/Codex sessions
44
+ send Submit one guarded message
45
+ doctor Inspect read-only metadata and capabilities
46
+ --version Print exact runtime version
47
+ --help, -h Show help; <command> --help for details
48
+ ${common}
49
+ No Relay server, MCP, wake, wait or automatic ACK support.`;
50
+ }
@@ -0,0 +1,2 @@
1
+ export type OutputFormat = 'json' | 'text';
2
+ export declare function renderOutput(value: Record<string, unknown>, format: OutputFormat): string;
package/dist/output.js ADDED
@@ -0,0 +1,42 @@
1
+ // Escape terminal control characters in user-controlled names/paths; preserve Unicode.
2
+ const safe = (value) => String(value ?? '').replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
3
+ export function renderOutput(value, format) {
4
+ if (format === 'json')
5
+ return JSON.stringify(value);
6
+ const lines = [];
7
+ if (value.command === 'list') {
8
+ const sessions = Array.isArray(value.sessions) ? value.sessions : [];
9
+ for (const row of sessions)
10
+ lines.push(`${safe(row.agent)}:${safe(row.pid ?? row.id)} ${safe(row.name)}${row.codexHome ? ` home=${safe(row.codexHome)}` : ''}`);
11
+ if (!sessions.length)
12
+ lines.push('No sessions found.');
13
+ if (value.discovery && typeof value.discovery === 'object') {
14
+ for (const [agent, diagnostic] of Object.entries(value.discovery))
15
+ lines.push(`Discovery ${safe(agent)}: ${safe(JSON.stringify(diagnostic))}`);
16
+ }
17
+ if (Array.isArray(value.errors))
18
+ for (const error of value.errors)
19
+ lines.push(`Discovery error: ${safe(JSON.stringify(error))}`);
20
+ }
21
+ else if (value.command === 'doctor') {
22
+ lines.push('Read-only diagnostics; readiness does not authorize submission.');
23
+ lines.push(`Ready: ${value.ready === true ? 'yes' : 'no'}`);
24
+ lines.push(`Agents: ${safe(JSON.stringify(value.agents ?? {}))}`);
25
+ lines.push(`Capabilities: ${safe(JSON.stringify(value.capabilities ?? {}))}`);
26
+ }
27
+ else if (value.ok === true) {
28
+ const target = value.target;
29
+ lines.push(`${safe(value.status)}: ${safe(target?.agent)}:${safe(target?.pid ?? target?.id)}`);
30
+ if (value.codexHome)
31
+ lines.push(`Codex home: ${safe(value.codexHome)}`);
32
+ if (value.queueId)
33
+ lines.push(`Queue ID: ${safe(value.queueId)}`);
34
+ lines.push(value.submitted === false ? 'Dry run: nothing submitted.' : 'Submitted; consumption/ACK is not confirmed.');
35
+ }
36
+ if (value.ok === false) {
37
+ lines.push(`Error: ${safe(value.error ?? 'operation_failed')}`);
38
+ if (value.command === 'send')
39
+ lines.push(value.submitted === null ? 'Submission outcome unknown. Do not retry automatically.' : 'Nothing submitted.');
40
+ }
41
+ return lines.join('\n');
42
+ }
@@ -1,5 +1,5 @@
1
- export declare const VERSION = "0.1.0-preview.1";
2
- export declare const VERSION_LINE = "session-peer 0.1.0-preview.1 (typescript)";
1
+ export declare const VERSION = "0.2.0";
2
+ export declare const VERSION_LINE = "session-peer 0.2.0 (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,6 +1,6 @@
1
1
  import { Refusal } from './discovery.js';
2
2
  import { uuid } from './writer.js';
3
- export const VERSION = '0.1.0-preview.1';
3
+ export const VERSION = '0.2.0';
4
4
  export const VERSION_LINE = `session-peer ${VERSION} (typescript)`;
5
5
  export function host(value) {
6
6
  if (value.length > 255 || !/^(?:[A-Za-z0-9_][A-Za-z0-9_.-]*@)?[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(value))
package/dist/send.d.ts CHANGED
@@ -1,10 +1,18 @@
1
+ import { UnknownOutcome } from './process.js';
2
+ import { type HomeResolution } from './writer.js';
1
3
  export type SendOptions = {
2
4
  to: string;
3
5
  home?: string;
4
6
  codexBin?: string;
5
7
  message: string;
6
8
  dryRun?: boolean;
9
+ allowInactive?: boolean;
7
10
  };
11
+ export declare class CodexUnknownOutcome extends UnknownOutcome {
12
+ readonly codexHomeResolution: HomeResolution;
13
+ constructor(codexHomeResolution: HomeResolution);
14
+ }
15
+ export declare function queueId(stdout: string, id: string): string | undefined;
8
16
  export declare function checkMessage(text: string, codex?: boolean): void;
9
17
  export declare function postSocket(path: string, text: string): Promise<void>;
10
18
  export declare function send(options: SendOptions): Promise<Record<string, unknown>>;