session-peer 0.1.0 → 0.2.1
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/CONTRIBUTING.md +11 -1
- package/PARITY.md +416 -0
- package/README.ja.md +80 -91
- package/README.ko.md +81 -165
- package/README.md +80 -174
- package/README.zh-CN.md +76 -91
- package/RELEASING.md +130 -7
- package/SECURITY.md +3 -2
- package/UNICODE-LICENSE.txt +39 -0
- package/VALIDATION.md +251 -16
- package/dist/casefold.d.ts +2 -0
- package/dist/casefold.js +9 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +87 -30
- package/dist/diagnostics.d.ts +21 -0
- package/dist/diagnostics.js +231 -0
- package/dist/discovery.d.ts +22 -1
- package/dist/discovery.js +199 -50
- package/dist/help.d.ts +1 -0
- package/dist/help.js +50 -0
- package/dist/output.d.ts +2 -0
- package/dist/output.js +43 -0
- package/dist/process.d.ts +1 -0
- package/dist/process.js +14 -2
- package/dist/protocol.d.ts +2 -2
- package/dist/protocol.js +11 -2
- package/dist/send.d.ts +8 -0
- package/dist/send.js +38 -18
- package/dist/windows.d.ts +2 -0
- package/dist/windows.js +30 -3
- package/dist/writer.d.ts +34 -3
- package/dist/writer.js +140 -69
- package/docs/api.md +30 -0
- package/docs/guide.ja.md +208 -0
- package/docs/guide.ko.md +294 -0
- package/docs/guide.md +324 -0
- package/docs/guide.zh-CN.md +204 -0
- package/package.json +6 -3
package/dist/discovery.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
//
|
|
2
|
-
|
|
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;
|
|
@@ -12,6 +13,21 @@ export class Refusal extends Error {
|
|
|
12
13
|
this.exitCode = exitCode;
|
|
13
14
|
}
|
|
14
15
|
}
|
|
16
|
+
// Codex can relocate state_5.sqlite/queue_1.sqlite with `sqlite_home`; validation
|
|
17
|
+
// reads <home>/state_5.sqlite, so any configured relocation is unsupported.
|
|
18
|
+
export function sqliteHome(home) {
|
|
19
|
+
let text;
|
|
20
|
+
try {
|
|
21
|
+
const file = join(home, 'config.toml'), stat = statSync(file);
|
|
22
|
+
if (!stat.isFile() || stat.size > 1024 * 1024)
|
|
23
|
+
return 'unknown';
|
|
24
|
+
text = readFileSync(file, 'utf8');
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
return ['ENOENT', 'ENOTDIR'].includes(error.code ?? '') ? 'default' : 'unknown';
|
|
28
|
+
}
|
|
29
|
+
return /^[ \t]*["']?sqlite_home["']?[ \t]*=/m.test(text) ? 'configured' : 'default';
|
|
30
|
+
}
|
|
15
31
|
function missing(error) {
|
|
16
32
|
return ['ENOENT', 'ENOTDIR'].includes(error.code ?? '');
|
|
17
33
|
}
|
|
@@ -20,22 +36,38 @@ export function canonical(path) {
|
|
|
20
36
|
path = join(homedir(), path.slice(2));
|
|
21
37
|
else if (path.startsWith('~'))
|
|
22
38
|
throw new Refusal('unsupported_home_expansion');
|
|
23
|
-
|
|
39
|
+
return canonicalPath(resolve(path), new Set());
|
|
40
|
+
}
|
|
41
|
+
function canonicalPath(absolute, seen) {
|
|
42
|
+
if (seen.has(absolute))
|
|
43
|
+
throw new Refusal('home_resolution_failed', 1);
|
|
44
|
+
seen.add(absolute);
|
|
24
45
|
try {
|
|
25
46
|
return realpathSync(absolute);
|
|
26
47
|
}
|
|
27
48
|
catch (error) {
|
|
28
49
|
if (!missing(error))
|
|
29
50
|
throw new Refusal('home_resolution_failed', 1);
|
|
51
|
+
// realpath fails for dangling links. Resolve the link itself before falling
|
|
52
|
+
// back to its parent, so missing aliases still merge required source labels.
|
|
53
|
+
let target;
|
|
54
|
+
try {
|
|
55
|
+
if (lstatSync(absolute).isSymbolicLink())
|
|
56
|
+
target = readlinkSync(absolute);
|
|
57
|
+
}
|
|
58
|
+
catch (linkError) {
|
|
59
|
+
if (!missing(linkError))
|
|
60
|
+
throw new Refusal('home_resolution_failed', 1);
|
|
61
|
+
}
|
|
62
|
+
if (target !== undefined)
|
|
63
|
+
return canonicalPath(resolve(dirname(absolute), target), seen);
|
|
30
64
|
const parent = dirname(absolute);
|
|
31
|
-
return parent === absolute ? absolute : join(
|
|
65
|
+
return parent === absolute ? absolute : join(canonicalPath(parent, seen), absolute.slice(parent.length));
|
|
32
66
|
}
|
|
33
67
|
}
|
|
34
68
|
function alive(pid) {
|
|
35
69
|
if (pid <= 1)
|
|
36
70
|
return false;
|
|
37
|
-
if (process.platform === 'win32')
|
|
38
|
-
return windowsProcessStart(pid) !== undefined;
|
|
39
71
|
try {
|
|
40
72
|
process.kill(pid, 0);
|
|
41
73
|
return true;
|
|
@@ -74,8 +106,8 @@ export function claude(all) {
|
|
|
74
106
|
if (typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid > 2147483647)
|
|
75
107
|
continue;
|
|
76
108
|
const matches = pid === Number(entry.slice(0, -5));
|
|
77
|
-
let live = matches && alive(pid);
|
|
78
|
-
if (
|
|
109
|
+
let live = matches && process.platform !== 'win32' && alive(pid);
|
|
110
|
+
if (matches && process.platform === 'win32') {
|
|
79
111
|
const started = typeof record.startedAt === 'number' && Number.isSafeInteger(record.startedAt) && record.startedAt > 0 ? record.startedAt : NaN;
|
|
80
112
|
const ticks = windowsProcessStart(pid);
|
|
81
113
|
const actual = ticks === undefined ? NaN : Number((ticks - 116444736000000000n) / 10000n);
|
|
@@ -104,59 +136,176 @@ export function claude(all) {
|
|
|
104
136
|
}
|
|
105
137
|
return { sessions, discovery: { claude: { status: 'ok' } } };
|
|
106
138
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
const
|
|
111
|
-
|
|
112
|
-
|
|
139
|
+
// Shared bounded sources; listing accumulates diagnostics while writer inventory
|
|
140
|
+
// keeps its stricter, fail-closed policy. No recursive scan or credential reads.
|
|
141
|
+
export function configuredHomePaths() {
|
|
142
|
+
const value = process.env.SESSION_PEER_CODEX_HOMES;
|
|
143
|
+
if (value === undefined)
|
|
144
|
+
return [];
|
|
145
|
+
let paths;
|
|
113
146
|
try {
|
|
114
|
-
|
|
115
|
-
code = 'state_db_not_regular';
|
|
147
|
+
paths = JSON.parse(value);
|
|
116
148
|
}
|
|
117
|
-
catch
|
|
118
|
-
|
|
149
|
+
catch {
|
|
150
|
+
throw new Refusal('invalid_home_configuration', 1);
|
|
151
|
+
}
|
|
152
|
+
if (!Array.isArray(paths) || paths.some(p => typeof p !== 'string' || !p.trim() ||
|
|
153
|
+
p.includes('\0') || (!isAbsolute(p) && !p.startsWith('~/')))) {
|
|
154
|
+
throw new Refusal('invalid_home_configuration', 1);
|
|
119
155
|
}
|
|
120
|
-
|
|
156
|
+
return paths;
|
|
157
|
+
}
|
|
158
|
+
export function orcaHomePaths() {
|
|
159
|
+
const directory = join(homedir(), 'Library/Application Support/orca/codex-accounts');
|
|
160
|
+
return readdirSync(directory).sort(compareText).map(entry => join(directory, entry, 'home'));
|
|
161
|
+
}
|
|
162
|
+
function compareText(a, b) {
|
|
163
|
+
// Python sorts Unicode code points, independent of locale and UTF-16 ordering.
|
|
164
|
+
const left = [...a], right = [...b];
|
|
165
|
+
for (let i = 0; i < Math.min(left.length, right.length); i++) {
|
|
166
|
+
const diff = left[i].codePointAt(0) - right[i].codePointAt(0);
|
|
167
|
+
if (diff)
|
|
168
|
+
return diff;
|
|
169
|
+
}
|
|
170
|
+
return left.length - right.length;
|
|
171
|
+
}
|
|
172
|
+
export function listingCandidates(explicit) {
|
|
173
|
+
const candidates = new Map(), errors = [];
|
|
174
|
+
function add(path, source, required) {
|
|
175
|
+
let home;
|
|
121
176
|
try {
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
177
|
+
home = canonical(path);
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
errors.push({ source, path, code: 'home_resolution_failed', error: 'home_resolution_failed' });
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
const item = candidates.get(home) ?? { codexHome: home, stateDb: join(home, 'state_5.sqlite'), sources: [], required: false };
|
|
184
|
+
if (!item.sources.includes(source))
|
|
185
|
+
item.sources.push(source);
|
|
186
|
+
item.required ||= required;
|
|
187
|
+
candidates.set(home, item);
|
|
188
|
+
}
|
|
189
|
+
if (explicit !== undefined)
|
|
190
|
+
add(explicit, 'argument', true);
|
|
191
|
+
else {
|
|
192
|
+
add(join(homedir(), '.codex'), 'default', false);
|
|
193
|
+
if (process.env.CODEX_HOME)
|
|
194
|
+
add(process.env.CODEX_HOME, 'environment', true);
|
|
195
|
+
if (process.platform === 'darwin') {
|
|
125
196
|
try {
|
|
126
|
-
|
|
127
|
-
|
|
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
|
-
});
|
|
197
|
+
for (const home of orcaHomePaths())
|
|
198
|
+
add(home, 'orca', false);
|
|
145
199
|
}
|
|
146
|
-
|
|
147
|
-
|
|
200
|
+
catch (error) {
|
|
201
|
+
if (error.code !== 'ENOENT') {
|
|
202
|
+
errors.push({ source: 'orca', path: join(homedir(), 'Library/Application Support/orca/codex-accounts'),
|
|
203
|
+
code: 'candidate_enumeration_failed', error: 'candidate_enumeration_failed' });
|
|
204
|
+
}
|
|
148
205
|
}
|
|
149
206
|
}
|
|
207
|
+
try {
|
|
208
|
+
for (const home of configuredHomePaths())
|
|
209
|
+
add(home, 'configured', true);
|
|
210
|
+
}
|
|
150
211
|
catch {
|
|
151
|
-
code
|
|
152
|
-
sessions = [];
|
|
212
|
+
errors.push({ source: 'configured', code: 'invalid_home_configuration', error: 'invalid_home_configuration' });
|
|
153
213
|
}
|
|
154
214
|
}
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
215
|
+
return { homes: [...candidates.values()], errors };
|
|
216
|
+
}
|
|
217
|
+
async function readCodex(home, file, all) {
|
|
218
|
+
// Lazy import: Claude-only commands don't initialize experimental SQLite.
|
|
219
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
220
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
221
|
+
try {
|
|
222
|
+
db.exec('PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; PRAGMA busy_timeout=3000');
|
|
223
|
+
const columns = new Set(db.prepare('PRAGMA table_info(threads)').all().map(row => row.name));
|
|
224
|
+
const required = ['id', 'title', 'cwd', 'updated_at', 'archived', 'rollout_path'];
|
|
225
|
+
if (!required.every(name => columns.has(name)))
|
|
226
|
+
throw new Error('unsupported_schema');
|
|
227
|
+
const name = columns.has('name') ? "COALESCE(NULLIF(name, ''), NULLIF(title, ''), id)" : "COALESCE(NULLIF(title, ''), id)";
|
|
228
|
+
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();
|
|
229
|
+
return rows.map(row => {
|
|
230
|
+
if (typeof row.id !== 'string' || !row.id || typeof row.display_name !== 'string' ||
|
|
231
|
+
typeof row.updated_at !== 'number' || !Number.isSafeInteger(row.updated_at) ||
|
|
232
|
+
typeof row.archived !== 'number' || (row.cwd !== null && typeof row.cwd !== 'string')) {
|
|
233
|
+
throw new Error('unsupported_row');
|
|
234
|
+
}
|
|
235
|
+
const firstLine = row.display_name.split(/[\n\r\v\f\x1c-\x1e\x85\u2028\u2029]/u)[0] ?? '';
|
|
236
|
+
return { agent: 'codex', id: row.id, name: [...firstLine].slice(0, 120).join(''),
|
|
237
|
+
cwd: row.cwd, updatedAt: row.updated_at, archived: Boolean(row.archived),
|
|
238
|
+
codexHome: home, stateDb: file };
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
finally {
|
|
242
|
+
db.close();
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
export async function codex(path, all) {
|
|
246
|
+
const { homes, errors } = listingCandidates(path);
|
|
247
|
+
const sessions = [], diagnostics = [];
|
|
248
|
+
for (const { required, ...item } of homes) {
|
|
249
|
+
let code;
|
|
250
|
+
let absent = false;
|
|
251
|
+
try {
|
|
252
|
+
if (!statSync(item.stateDb).isFile())
|
|
253
|
+
code = 'state_db_not_regular';
|
|
254
|
+
}
|
|
255
|
+
catch (error) {
|
|
256
|
+
if (missing(error)) {
|
|
257
|
+
if (required)
|
|
258
|
+
code = 'state_db_missing';
|
|
259
|
+
else
|
|
260
|
+
absent = true;
|
|
261
|
+
}
|
|
262
|
+
else
|
|
263
|
+
code = ['EACCES', 'EPERM'].includes(error.code ?? '') ? 'permission_denied' : 'state_db_read_failed';
|
|
264
|
+
}
|
|
265
|
+
let rows = [];
|
|
266
|
+
if (!code && !absent) {
|
|
267
|
+
try {
|
|
268
|
+
rows = await readCodex(item.codexHome, item.stateDb, all);
|
|
269
|
+
}
|
|
270
|
+
catch (error) {
|
|
271
|
+
code = ['EACCES', 'EPERM'].includes(error.code ?? '') ? 'permission_denied' : 'state_db_read_failed';
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
sessions.push(...rows);
|
|
275
|
+
diagnostics.push({ ...item, ...(code ? { status: 'error', code, error: code } :
|
|
276
|
+
absent ? { status: 'absent', code: 'state_db_absent' } : { status: 'ok', sessionCount: rows.length }) });
|
|
277
|
+
}
|
|
278
|
+
sessions.sort((a, b) => Number(b.updatedAt) - Number(a.updatedAt) ||
|
|
279
|
+
compareText(String(a.codexHome), String(b.codexHome)) || compareText(String(a.id), String(b.id)));
|
|
280
|
+
const failed = errors.length > 0 || diagnostics.some(item => item.status === 'error');
|
|
281
|
+
const discovery = { status: failed ? 'error' : diagnostics.some(item => item.status === 'ok') ? 'ok' : 'not_installed', homes: diagnostics };
|
|
282
|
+
if (errors.length)
|
|
283
|
+
discovery.errors = errors;
|
|
158
284
|
if (failed)
|
|
159
285
|
discovery.error = 'Codex home discovery is incomplete; inspect homes and errors';
|
|
160
|
-
return { sessions,
|
|
286
|
+
return { sessions, discovery: { codex: discovery }, ok: !failed,
|
|
287
|
+
...(homes.length === 1 && !errors.length ? { codexHome: homes[0].codexHome } : {}),
|
|
161
288
|
...(failed ? { error: 'Discovery failed for: codex' } : {}) };
|
|
162
289
|
}
|
|
290
|
+
export async function listing(agent, home, all) {
|
|
291
|
+
const result = { sessions: [], discovery: {}, ok: true };
|
|
292
|
+
for (const name of agent ? [agent] : ['claude', 'codex']) {
|
|
293
|
+
try {
|
|
294
|
+
const found = name === 'claude' ? claude(all) : await codex(home, all);
|
|
295
|
+
result.sessions.push(...found.sessions);
|
|
296
|
+
Object.assign(result.discovery, found.discovery);
|
|
297
|
+
if (found.codexHome !== undefined)
|
|
298
|
+
result.codexHome = found.codexHome;
|
|
299
|
+
}
|
|
300
|
+
catch (error) {
|
|
301
|
+
const code = error instanceof Refusal ? error.code : 'discovery_failed';
|
|
302
|
+
result.discovery[name] = { status: 'error', error: code };
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
const failed = Object.keys(result.discovery).filter(name => result.discovery[name].status === 'error');
|
|
306
|
+
if (failed.length) {
|
|
307
|
+
result.ok = false;
|
|
308
|
+
result.error = 'Discovery failed for: ' + failed.join(', ');
|
|
309
|
+
}
|
|
310
|
+
return result;
|
|
311
|
+
}
|
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
|
+
}
|
package/dist/output.d.ts
ADDED
package/dist/output.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Escape terminal controls plus bidi/zero-width format characters in
|
|
2
|
+
// user-controlled names/paths; preserve other Unicode.
|
|
3
|
+
const safe = (value) => String(value ?? '').replace(/[\x00-\x1f\x7f-\x9f\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
|
4
|
+
export function renderOutput(value, format) {
|
|
5
|
+
if (format === 'json')
|
|
6
|
+
return JSON.stringify(value);
|
|
7
|
+
const lines = [];
|
|
8
|
+
if (value.command === 'list') {
|
|
9
|
+
const sessions = Array.isArray(value.sessions) ? value.sessions : [];
|
|
10
|
+
for (const row of sessions)
|
|
11
|
+
lines.push(`${safe(row.agent)}:${safe(row.pid ?? row.id)} ${safe(row.name)}${row.codexHome ? ` home=${safe(row.codexHome)}` : ''}`);
|
|
12
|
+
if (!sessions.length)
|
|
13
|
+
lines.push('No sessions found.');
|
|
14
|
+
if (value.discovery && typeof value.discovery === 'object') {
|
|
15
|
+
for (const [agent, diagnostic] of Object.entries(value.discovery))
|
|
16
|
+
lines.push(`Discovery ${safe(agent)}: ${safe(JSON.stringify(diagnostic))}`);
|
|
17
|
+
}
|
|
18
|
+
if (Array.isArray(value.errors))
|
|
19
|
+
for (const error of value.errors)
|
|
20
|
+
lines.push(`Discovery error: ${safe(JSON.stringify(error))}`);
|
|
21
|
+
}
|
|
22
|
+
else if (value.command === 'doctor') {
|
|
23
|
+
lines.push('Read-only diagnostics; readiness does not authorize submission.');
|
|
24
|
+
lines.push(`Ready: ${value.ready === true ? 'yes' : 'no'}`);
|
|
25
|
+
lines.push(`Agents: ${safe(JSON.stringify(value.agents ?? {}))}`);
|
|
26
|
+
lines.push(`Capabilities: ${safe(JSON.stringify(value.capabilities ?? {}))}`);
|
|
27
|
+
}
|
|
28
|
+
else if (value.ok === true) {
|
|
29
|
+
const target = value.target;
|
|
30
|
+
lines.push(`${safe(value.status)}: ${safe(target?.agent)}:${safe(target?.pid ?? target?.id)}`);
|
|
31
|
+
if (value.codexHome)
|
|
32
|
+
lines.push(`Codex home: ${safe(value.codexHome)}`);
|
|
33
|
+
if (value.queueId)
|
|
34
|
+
lines.push(`Queue ID: ${safe(value.queueId)}`);
|
|
35
|
+
lines.push(value.submitted === false ? 'Dry run: nothing submitted.' : 'Submitted; consumption/ACK is not confirmed.');
|
|
36
|
+
}
|
|
37
|
+
if (value.ok === false) {
|
|
38
|
+
lines.push(`Error: ${safe(value.error ?? 'operation_failed')}`);
|
|
39
|
+
if (value.command === 'send')
|
|
40
|
+
lines.push(value.submitted === null ? 'Submission outcome unknown. Do not retry automatically.' : 'Nothing submitted.');
|
|
41
|
+
}
|
|
42
|
+
return lines.join('\n');
|
|
43
|
+
}
|
package/dist/process.d.ts
CHANGED
package/dist/process.js
CHANGED
|
@@ -4,16 +4,28 @@ import { delimiter, isAbsolute, join } from 'node:path';
|
|
|
4
4
|
import { Refusal } from './discovery.js';
|
|
5
5
|
export class UnknownOutcome extends Error {
|
|
6
6
|
}
|
|
7
|
+
// Node refuses to spawn .cmd/.bat without a shell (CVE-2024-27980), and a shell
|
|
8
|
+
// would interpret the message argv, so Windows batch shims are unsupported.
|
|
9
|
+
export const batchShim = (path) => process.platform === 'win32' && /\.(?:cmd|bat)$/i.test(path);
|
|
7
10
|
export function executable(name) {
|
|
8
11
|
const windows = process.platform === 'win32';
|
|
9
12
|
const names = windows && !/\.(?:exe|cmd|bat)$/i.test(name) ? [name + '.exe', name + '.cmd', name] : [name];
|
|
10
13
|
const paths = isAbsolute(name) ? [name] : name.includes('/') || name.includes('\\') ? [] :
|
|
11
14
|
(process.env.PATH ?? '').split(delimiter).filter(Boolean).flatMap(p => names.map(n => join(p, n)));
|
|
12
15
|
for (const path of paths) {
|
|
16
|
+
let found = false;
|
|
13
17
|
try {
|
|
14
18
|
accessSync(path, constants.X_OK);
|
|
15
|
-
|
|
16
|
-
|
|
19
|
+
found = statSync(path).isFile();
|
|
20
|
+
}
|
|
21
|
+
catch { }
|
|
22
|
+
if (!found)
|
|
23
|
+
continue;
|
|
24
|
+
// Keep PATH precedence: a first-match shim is refused, not bypassed.
|
|
25
|
+
if (batchShim(path))
|
|
26
|
+
throw new Refusal('executable_unsupported', 1);
|
|
27
|
+
try {
|
|
28
|
+
return realpathSync(path);
|
|
17
29
|
}
|
|
18
30
|
catch { }
|
|
19
31
|
}
|
package/dist/protocol.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export declare const VERSION = "0.1
|
|
2
|
-
export declare const VERSION_LINE = "session-peer 0.1
|
|
1
|
+
export declare const VERSION = "0.2.1";
|
|
2
|
+
export declare const VERSION_LINE = "session-peer 0.2.1 (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
|
|
3
|
+
export const VERSION = '0.2.1';
|
|
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))
|
|
@@ -32,6 +32,9 @@ export function reply(value) {
|
|
|
32
32
|
throw new Refusal('invalid_reply_uri');
|
|
33
33
|
if (agent !== 'codex' && fields.has('codexHome'))
|
|
34
34
|
throw new Refusal('invalid_reply_uri');
|
|
35
|
+
// Match Python: a POSIX or Windows absolute path, never cwd- or ~-relative.
|
|
36
|
+
if (fields.has('codexHome') && !/^(?:\/|[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(fields.get('codexHome')))
|
|
37
|
+
throw new Refusal('invalid_reply_uri');
|
|
35
38
|
if (transport === 'local' && fields.has('host'))
|
|
36
39
|
throw new Refusal('invalid_reply_uri');
|
|
37
40
|
if (transport === 'ssh' && !fields.has('host'))
|
|
@@ -45,6 +48,12 @@ export function envelope(text, noFrom, address) {
|
|
|
45
48
|
const from = !noFrom && sender && uuid(sender) ? `From: codex:${sender}\n\n` : '';
|
|
46
49
|
if (address)
|
|
47
50
|
reply(address);
|
|
51
|
+
// Trim edge newlines by index: /\n+$/ is quadratic on long interior newline runs.
|
|
52
|
+
let start = 0, end = text.length;
|
|
53
|
+
while (start < end && text[start] === '\n')
|
|
54
|
+
start++;
|
|
55
|
+
while (end > start && text[end - 1] === '\n')
|
|
56
|
+
end--;
|
|
48
57
|
// No inferred identity/reverse route and no executable Reply command.
|
|
49
|
-
return from + text.
|
|
58
|
+
return from + text.slice(start, end) + (address ? `\n\n---\nReply-To: ${address}` : '');
|
|
50
59
|
}
|
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>>;
|
package/dist/send.js
CHANGED
|
@@ -1,8 +1,22 @@
|
|
|
1
|
+
import { casefold } from './casefold.js';
|
|
1
2
|
import { createConnection } from 'node:net';
|
|
2
|
-
import {
|
|
3
|
+
import { claude, Refusal, sqliteHome } 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,42 @@ 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)
|
|
47
|
-
throw new Refusal('
|
|
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
|
|
63
|
+
const selection = await resolveWriter(options.home, id, options.allowInactive);
|
|
64
|
+
const { home } = selection;
|
|
65
|
+
const storage = sqliteHome(home);
|
|
66
|
+
if (storage !== 'default')
|
|
67
|
+
throw new HomeRefusal(storage === 'configured' ? 'unsupported_codex_sqlite_home' : 'codex_config_unreadable', selection.resolution);
|
|
51
68
|
const result = { ...base, target: { agent: 'codex', id }, codexHome: home,
|
|
52
|
-
status: options.dryRun ? 'validated' : 'queued' };
|
|
69
|
+
status: options.dryRun ? 'validated' : 'queued', codexHomeResolution: selection.resolution };
|
|
53
70
|
if (options.dryRun)
|
|
54
71
|
return result;
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
72
|
+
await revalidateWriter(selection, options.home, id, options.allowInactive);
|
|
73
|
+
// `--message=` keeps a body starting with `-` from being parsed as an option.
|
|
74
|
+
// An inherited CODEX_SQLITE_HOME would queue outside the validated home.
|
|
75
|
+
// Windows environment names are case-insensitive.
|
|
76
|
+
const inherited = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.toUpperCase() !== 'CODEX_SQLITE_HOME'));
|
|
77
|
+
const done = await run(binary, ['queue', '--thread', id, `--message=${options.message}`], { env: { ...inherited, CODEX_HOME: home }, timeout: 30000 });
|
|
58
78
|
if (!done.spawned)
|
|
59
|
-
throw new
|
|
79
|
+
throw new HomeRefusal('native_spawn_failed', selection.resolution);
|
|
60
80
|
if (done.interrupted || done.code !== 0)
|
|
61
|
-
throw new
|
|
62
|
-
|
|
81
|
+
throw new CodexUnknownOutcome(selection.resolution);
|
|
82
|
+
const queuedId = queueId(done.stdout, id);
|
|
83
|
+
return { ...result, ...(queuedId === undefined ? {} : { queueId: queuedId }) };
|
|
63
84
|
}
|
|
64
85
|
if (options.to.includes(':') && !options.to.startsWith('claude:'))
|
|
65
86
|
throw new Refusal('unsupported_agent');
|
|
66
|
-
if (options.home || options.codexBin)
|
|
87
|
+
if (options.home || options.codexBin || options.allowInactive)
|
|
67
88
|
throw new Refusal('inapplicable_option');
|
|
68
89
|
const target = options.to.replace(/^claude:/, '');
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
throw new Refusal('use_pid_for_unicode_name');
|
|
90
|
+
if (!target)
|
|
91
|
+
throw new Refusal('no_reachable_target');
|
|
72
92
|
const select = () => {
|
|
73
93
|
const rows = claude(false).sessions;
|
|
74
94
|
const matches = rows.filter(r => /^\d+$/.test(target) ? r.pid === Number(target) :
|
|
75
|
-
typeof r.name === 'string' && r.name
|
|
95
|
+
typeof r.name === 'string' && casefold(r.name) === casefold(target));
|
|
76
96
|
if (matches.length !== 1)
|
|
77
97
|
throw new Refusal(matches.length ? 'ambiguous_target' : 'no_reachable_target', 2);
|
|
78
98
|
return matches[0];
|
package/dist/windows.d.ts
CHANGED
|
@@ -4,6 +4,8 @@ export type WindowsProcess = {
|
|
|
4
4
|
command: string;
|
|
5
5
|
start: string;
|
|
6
6
|
};
|
|
7
|
+
export declare const COMPILED_INSPECTION_TIMEOUT_MS = 20000;
|
|
8
|
+
export declare const START_PROBE_TIMEOUT_MS = 8000;
|
|
7
9
|
export declare function inspectWindows(mode: 'identity' | 'openers', value: string): WindowsProcess[];
|
|
8
10
|
export declare function windowsProcessStart(pid: number): bigint | undefined;
|
|
9
11
|
export declare function postWindowsPipe(pipe: string, pid: number, text: string): Promise<void>;
|