session-peer 0.2.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/RELEASING.md CHANGED
@@ -7,7 +7,50 @@ remain independent. The npm Trusted Publisher for `abruption/session-peer-ts`,
7
7
  uses OIDC and no npm token. The protected GitHub environment requires a reviewer
8
8
  and permits deployments from `main` only.
9
9
 
10
- ## Public baseline checked 2026-09-28 KST
10
+ ## Current public release — 0.2.0
11
+
12
+ `session-peer@0.2.0` was published on 2026-09-28 KST. Public verification passed
13
+ with `latest=0.2.0` and unchanged `preview=0.1.0-preview.1`; see the
14
+ [dated 0.2.0 verification record](VALIDATION.md#public-020--2026-09-28-kst).
15
+ The 0.2.0 procedure below is completed history, not a repeatable dispatch.
16
+ A future release requires a new reviewed version and baseline preparation PR.
17
+
18
+ ## 0.2.1 stable release procedure
19
+
20
+ The reviewed stable target is 0.2.1, a reliability and hardening update
21
+ ([changes](PARITY.md#021-reliability-and-hardening)). Previous stable 0.2.0
22
+ integrity is pinned:
23
+ `sha512-wXUVn2GdF3fKAjJA9cUKIiBc9YVswnfBNALo2nxhXqmpCqC7/9N+AQJct/06RAU7stbcbrfY55JQ15PPESXwHw==`.
24
+ The preview integrity remains pinned as a preservation check. No existing tag is
25
+ removed.
26
+
27
+ 1. Merge the reviewed 0.2.1 preparation PR into main and require successful
28
+ exact-main CI (including Windows Node 22/24 and the release gate).
29
+ 2. Check npm environment reviewers and main-only deployment policy, package
30
+ ownership/2FA and stage-only Trusted Publisher mapping. Inspect pending stages
31
+ with authenticated `npm stage list session-peer`; stop on a conflicting stage.
32
+ 3. Require 0.2.1 absent, `latest=0.2.0`, `preview=0.1.0-preview.1`, and the 0.2.0
33
+ and preview integrity/provenance records unchanged. The script enforces these.
34
+ 4. Obtain final approval naming **exact main SHA**, **0.2.1**, **stable-stage** and
35
+ `latest` promotion to 0.2.1. Do not replay any historical approval.
36
+ 5. Dispatch `publish.yml` on main with `mode=stable-stage`, `version=0.2.1`,
37
+ `source_sha=<approved 40-character main SHA>`, and
38
+ `confirmation=session-peer@0.2.1 stable-stage`.
39
+ 6. Before approving the protected npm environment, download the prepare job's
40
+ `npm-release-<SHA>` artifact and apply the documentation gate below.
41
+ 7. Staging uses Node 24/npm 11.15.0 and OIDC with upload retries disabled. Record
42
+ the stage ID, compare the staged tarball with the retained artifact, and obtain
43
+ the separate final npm 2FA approval, which publishes 0.2.1 and promotes `latest`.
44
+ 8. After approval, run `node scripts/release.mjs artifact` and
45
+ `node scripts/release.mjs verify` on that exact source/artifact and append dated
46
+ public evidence to VALIDATION.md.
47
+
48
+ Release notes must list the stricter 0.2.1 refusals (option-name values,
49
+ SSH usage exit code 2, `sqlite_home`, Windows batch shims, relative Reply-To
50
+ `codexHome`). SSH requires the same version on both ends, so 0.2.0 and 0.2.1
51
+ hosts refuse each other at preflight; upgrade the endpoints together.
52
+
53
+ ## Historical pre-0.2.0 baseline checked 2026-09-28 KST
11
54
 
12
55
  `session-peer@0.1.0` is public. The registry records publication at
13
56
  `2026-09-27T11:23:51.466Z`; the 2026-09-28 KST recheck found
@@ -15,7 +58,7 @@ and permits deployments from `main` only.
15
58
  [dated stable verification record](VALIDATION.md#public-010--2026-09-27-kst)
16
59
  for source, staging run, artifact hashes, approvals and evidence limits.
17
60
 
18
- ## 0.2.0 stable release procedure
61
+ ## Completed 0.2.0 stable release procedure
19
62
 
20
63
  The reviewed stable target is 0.2.0. Previous stable 0.1.0 integrity is pinned:
21
64
  `sha512-/FtILLgUpIAgqf5FsdU5/x17IGeWO3ylmm47gbSyN3hHjD40pp5gtOeAXU3zqmye/cx7PE52Pp/oLa0ZgZyDQQ==`.
@@ -183,9 +226,9 @@ reviewed new version and its own approval.
183
226
 
184
227
  The first preview.0 used a bootstrap token, and the registry assigned both
185
228
  `preview` and `latest` to it despite `--tag preview`. That bootstrap path is
186
- closed in this workflow. The repository `NPM_TOKEN` secret and any remaining
187
- bootstrap credential should be removed through a separate owner-approved account
188
- operation; this PR neither reads nor changes those credentials.
229
+ closed in this workflow. On 2026-09-29 KST the owner revoked the bootstrap token
230
+ and deleted the repository `NPM_TOKEN` secret; the repository and `npm`
231
+ environment now hold no Actions secrets. Publishing relies only on OIDC.
189
232
 
190
233
  ## Sources
191
234
 
package/SECURITY.md CHANGED
@@ -14,6 +14,7 @@ homes, SQLite DBs, transcripts, browser profiles or .env files. Rotate exposed
14
14
  secrets with their provider; deleting a comment does not revoke a secret.
15
15
 
16
16
  Review is manual and best-effort, with no response or fix deadline. The project is
17
- an unpublished preview; reports on any commit are welcome but no stable support
18
- or backport promise exists. English and Korean reports are welcome. Disclosure
17
+ a published npm client, with 0.2.0 release evidence in [VALIDATION.md](VALIDATION.md#public-020--2026-09-28-kst).
18
+ Reports on published versions and source commits are welcome; no maintenance
19
+ window or backport promise exists. English and Korean reports are welcome. Disclosure
19
20
  is coordinated with the reporter; private reports are not automatically public.
package/VALIDATION.md CHANGED
@@ -1,11 +1,60 @@
1
1
  # Validation record — updated 2026-09-28 KST
2
2
 
3
- This dated record covers the 0.2.0 release source and historical 0.1.0 public
3
+ This dated record covers public 0.2.0 verification and historical 0.1.0 public
4
4
  verification, candidate checks and live-agent observations. Older sections
5
5
  describe their stated checkpoint rather than current feature availability.
6
6
  It does not claim complete Python parity.
7
7
  Python reference: v1.0.2, commit `47c23713d0a2a3c11ebde6186afd8c43489b8b65`.
8
8
 
9
+ ## 0.2.1 candidate checks — 2026-09-29 KST
10
+
11
+ Candidate source: main after #62, #63, #64 and #66 plus the 0.2.1 preparation PR.
12
+ Changes are listed in [PARITY.md](PARITY.md#021-reliability-and-hardening).
13
+ Local macOS arm64 Node 22.14.0 with the pinned Python reference: 77 tests, 73
14
+ passed, 4 Windows-only skipped; package smoke, repository checker, `npm audit`
15
+ (0 vulnerabilities), release `pack` and `artifact` validation passed. Each
16
+ included fix PR passed the full macOS/Linux/Windows Node 22/24 matrix, CodeQL and
17
+ the release gate on its head. These are fixture results, not live-TUI ACKs and not
18
+ public release evidence; 0.2.1 publication requires the procedure in
19
+ [RELEASING.md](RELEASING.md#021-stable-release-procedure) and a dated public record.
20
+
21
+ ## Public 0.2.0 — 2026-09-28 KST
22
+
23
+ `session-peer@0.2.0` is public. Registry publication time is
24
+ `2026-09-28T04:28:39.027Z` (13:28:39 KST). Verified `latest=0.2.0` and
25
+ unchanged `preview=0.1.0-preview.1`; authenticated pending-stage list is empty.
26
+
27
+ - Source: `2107c4c9f3a2ad9deca42f4e0dd9673d2e5fb3ce`, release PR #44.
28
+ - Exact-main CI: [36377144969](https://github.com/abruption/session-peer-ts/actions/runs/36377144969), successful.
29
+ - Staging run: [36377508658](https://github.com/abruption/session-peer-ts/actions/runs/36377508658), successful; Node 24 / npm 11.15.0.
30
+ - Stage: `479ce166-c252-4f71-88d6-9a9bda4c4e92`, tag `latest`, GitHub Actions trusted automation.
31
+ - Artifact: `session-peer-0.2.0.tgz`; SHA-256 `2def227c0e6d997b2fd292c1f7cfaec2d4330e654caf703fcb100eadafb418c2`.
32
+ - Registry integrity: `sha512-wXUVn2GdF3fKAjJA9cUKIiBc9YVswnfBNALo2nxhXqmpCqC7/9N+AQJct/06RAU7stbcbrfY55JQ15PPESXwHw==`.
33
+
34
+ The user approved the exact main SHA/stable-stage, separately approved the
35
+ protected GitHub npm environment, and reported final npm 2FA promotion complete.
36
+ Before dispatch, the npm UI showed the Trusted Publisher mapping to this repo,
37
+ `publish.yml`, environment `npm`, with `npm stage publish` permission only.
38
+ GitHub required reviewer and main-only environment policy were checked.
39
+ The existing package setting permitted 2FA or bypass-enabled automation tokens;
40
+ this release did not change that setting and used OIDC staging.
41
+
42
+ Codex reviewed the retained Actions artifact against the exact source: all four
43
+ READMEs plus PARITY, RELEASING and VALIDATION matched byte for byte. The tarball
44
+ downloaded from npm staging was byte-identical to that retained artifact.
45
+ After promotion, `release.mjs verify` passed registry integrity/tag/attestation
46
+ checks, npm signature audit, fresh version-specific installation, version banner,
47
+ isolated empty Claude listing and uninstall on macOS Node 22.14.0. Published
48
+ provenance names the exact source SHA and run above. The npm 0.2.0 page rendered
49
+ the version-specific README and install command correctly when inspected.
50
+
51
+ This public-package check does not add a new live-agent ACK or cross-device
52
+ submission claim. Platform fixture evidence remains the exact-main CI above;
53
+ historical live-agent observations below retain their original versions.
54
+ The immutable npm tarball contains the dated pre-publication checkpoint; this
55
+ post-publication record is a later GitHub documentation update. No republishing,
56
+ tag deletion, GitHub release/tag creation or fleet installation was performed.
57
+
9
58
  ## Source discovery for 0.2.0 — 2026-09-28 KST
10
59
 
11
60
  Issue #16 adds combined Claude/Codex listing and bounded multiple-home inventory.
@@ -27,7 +76,10 @@ Windows SSH fixture additionally executes actual PowerShell/.cmd and checks
27
76
  partial listing rows while a native writer is held, with no new queue call.
28
77
  Windows test files run serially so concurrent PowerShell compilation does not
29
78
  consume the native inspector's fixed timeout; assertions and production deadlines
30
- are unchanged. Each native subtest cleans its children even after assertion
79
+ are unchanged. Separately (#65), the compiling `Add-Type` owner inspection now has
80
+ a 20000 ms deadline after a slow runner exceeded 8000 ms on main (CI run
81
+ 36419550921, attempt 1); the compile-free creation-time probe keeps 8000 ms, and
82
+ timeouts still refuse. Each native subtest cleans its children even after assertion
31
83
  failure. Package smoke verifies unified empty discovery without executables on PATH.
32
84
  These are fixture contracts, not new live-TUI ACKs. CI evidence belongs to the
33
85
  issue's PR-head checks; publication requires separate release preparation.
package/dist/cli.js CHANGED
@@ -9,6 +9,8 @@ import { executable, run, UnknownOutcome } from './process.js';
9
9
  import { checkMessage, send, CodexUnknownOutcome } from './send.js';
10
10
  import { HomeRefusal } from './writer.js';
11
11
  import { envelope, host, reply, VERSION, VERSION_LINE } from './protocol.js';
12
+ const FLAGS = ['--json', '--all', '--dry-run', '--no-from', '--no-reply-to', '--no-update-notice', '--allow-inactive-codex-home'];
13
+ const VALUES = ['--agent', '--codex-home', '--codex-bin', '--output-format', '--to', '--message', '-m', '--host', '--remote-bin', '--remote-platform', '--ssh-control-path', '--reply-address'];
12
14
  export function parse(args) {
13
15
  const command = args[0];
14
16
  if (command !== 'list' && command !== 'send' && command !== 'doctor')
@@ -30,15 +32,18 @@ export function parse(args) {
30
32
  }
31
33
  const split = token.indexOf('=');
32
34
  const key = split > 0 ? token.slice(0, split) : token;
33
- if (['--json', '--all', '--dry-run', '--no-from', '--no-reply-to', '--no-update-notice', '--allow-inactive-codex-home'].includes(key)) {
35
+ if (FLAGS.includes(key)) {
34
36
  if (flags.has(key) || split > 0)
35
37
  throw new Refusal('invalid_option');
36
38
  flags.add(key);
37
39
  }
38
- else if (['--agent', '--codex-home', '--codex-bin', '--output-format', '--to', '--message', '-m', '--host', '--remote-bin', '--remote-platform', '--ssh-control-path', '--reply-address'].includes(key)) {
40
+ else if (VALUES.includes(key)) {
39
41
  const name = key === '-m' ? '--message' : key;
40
42
  const value = split > 0 ? token.slice(split + 1) : args[++i];
41
- if (value === undefined || values.has(name))
43
+ // A separate value that is itself an option name is a missing value, as in
44
+ // argparse; `--message=--dry-run` or stdin still send such text literally.
45
+ const option = split > 0 ? '' : (value ?? '').split('=')[0];
46
+ if (value === undefined || values.has(name) || [...FLAGS, ...VALUES, '--help', '-h', '--version', '--stdio-request'].includes(option))
42
47
  throw new Refusal('invalid_option');
43
48
  values.set(name, value);
44
49
  }
@@ -140,6 +145,9 @@ export function sshPreflightFailure(result, expected) {
140
145
  return 'ssh_preflight_timeout';
141
146
  if (!result.spawned)
142
147
  return 'ssh_unavailable';
148
+ // A verified version is success even when login scripts write to stderr.
149
+ if (result.code === 0 && result.stdout.trim() === expected)
150
+ return undefined;
143
151
  const detail = result.stderr;
144
152
  if (/host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED|no [^\n]*host key is known/i.test(detail))
145
153
  return 'ssh_host_key_untrusted';
@@ -163,7 +171,8 @@ async function remote(options, message) {
163
171
  const invoke = (flag) => {
164
172
  if (!windows)
165
173
  return `${quote(binary)} ${flag}`;
166
- const code = `& '${binary.replace(/'/g, "''")}' ${flag}`;
174
+ // PowerShell also closes single-quoted strings on U+2018-U+201B.
175
+ const code = `& '${binary.replace(/['\u2018-\u201b]/g, '$&$&')}' ${flag}`;
167
176
  return `powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(code, 'utf16le').toString('base64')}`;
168
177
  };
169
178
  const ssh = executable('ssh');
@@ -184,7 +193,7 @@ async function remote(options, message) {
184
193
  if (flags.has('--allow-inactive-codex-home'))
185
194
  args.push('--allow-inactive-codex-home');
186
195
  if (command === 'send')
187
- args.push('--message', message, '--no-from', '--no-reply-to');
196
+ args.push(`--message=${message}`, '--no-from', '--no-reply-to');
188
197
  const done = await run(ssh, [...base, invoke('--stdio-request')], {
189
198
  timeout: 90000, input: JSON.stringify({ schemaVersion: 1, args })
190
199
  });
@@ -209,7 +218,7 @@ async function remote(options, message) {
209
218
  (value.ok && (value.submitted !== !flags.has('--dry-run') || value.status !== expectedStatus)) ||
210
219
  (!value.ok && !((value.submitted === false && value.status === 'refused') || (value.submitted === null && value.status === 'unknown')))))
211
220
  return uncertain();
212
- return { ...value, host: target, sshHost: target };
221
+ return { value: { ...value, host: target, sshHost: target }, exitCode: done.code };
213
222
  }
214
223
  let command = 'unknown';
215
224
  let format = 'json';
@@ -259,9 +268,10 @@ try {
259
268
  message = envelope(message, options.flags.has('--no-from'), options.values.get('--reply-address'));
260
269
  checkMessage(message, options.values.get('--to').startsWith('codex:'));
261
270
  }
262
- let result;
271
+ let result, exitCode;
272
+ // Propagate the verified remote exit code so SSH and local refusals match.
263
273
  if (options.values.has('--host'))
264
- result = await remote(options, message);
274
+ ({ value: result, exitCode } = await remote(options, message));
265
275
  else if (command === 'send')
266
276
  result = await send({ to: options.values.get('--to'), home: options.values.get('--codex-home'), codexBin: options.values.get('--codex-bin'), message: message, dryRun: options.flags.has('--dry-run'), allowInactive: options.flags.has('--allow-inactive-codex-home') });
267
277
  else if (command === 'doctor')
@@ -269,7 +279,7 @@ try {
269
279
  else
270
280
  result = await listing(options.values.get('--agent'), options.values.get('--codex-home'), options.flags.has('--all'));
271
281
  console.log(renderOutput({ schemaVersion: 1, host: hostname(), command, ok: result.ok !== false, version: VERSION, referenceVersion: '1.0.2', ...result }, format));
272
- process.exitCode = result.ok === false ? 1 : 0;
282
+ process.exitCode = exitCode ?? (result.ok === false ? 1 : 0);
273
283
  }
274
284
  }
275
285
  catch (error) {
@@ -3,7 +3,8 @@
3
3
  import { accessSync, constants, readdirSync, readFileSync, statSync } from 'node:fs';
4
4
  import { homedir } from 'node:os';
5
5
  import { delimiter, isAbsolute, join } from 'node:path';
6
- import { canonical, listingCandidates } from './discovery.js';
6
+ import { canonical, listingCandidates, sqliteHome } from './discovery.js';
7
+ import { batchShim } from './process.js';
7
8
  import { windowsProcessStart } from './windows.js';
8
9
  const failure = (error, missing, unknown) => {
9
10
  const code = error.code;
@@ -25,6 +26,8 @@ function tool(name) {
25
26
  if (!statSync(path).isFile())
26
27
  continue;
27
28
  accessSync(path, constants.X_OK);
29
+ if (batchShim(path))
30
+ return { status: 'unsupported', code: 'executable_unsupported', path, executed: false };
28
31
  return { status: 'available', code: 'executable_found', path, executed: false };
29
32
  }
30
33
  catch (error) {
@@ -67,8 +70,11 @@ async function codexHome(file) {
67
70
  export async function diagnoseCodex(home, binary) {
68
71
  const inventory = listingCandidates(home);
69
72
  const homes = [];
70
- for (const item of inventory.homes)
71
- homes.push({ ...item, ...await codexHome(item.stateDb) });
73
+ for (const item of inventory.homes) {
74
+ const storage = sqliteHome(item.codexHome);
75
+ homes.push({ ...item, ...(storage === 'configured' ? { status: 'unsupported', code: 'unsupported_codex_sqlite_home' } :
76
+ storage === 'unknown' ? { status: 'unknown', code: 'codex_config_unreadable' } : await codexHome(item.stateDb)) });
77
+ }
72
78
  const agentTool = tool(binary ?? 'codex');
73
79
  const complete = inventory.errors.length === 0 && homes.every(item => item.status === 'available' || (!item.required && item.status === 'missing'));
74
80
  const ready = complete && homes.some(item => item.status === 'available') && agentTool.status === 'available';
@@ -4,6 +4,7 @@ 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';
7
8
  export declare function canonical(path: string): string;
8
9
  export declare function claude(all: boolean): Row;
9
10
  export declare function configuredHomePaths(): string[];
package/dist/discovery.js CHANGED
@@ -13,6 +13,21 @@ export class Refusal extends Error {
13
13
  this.exitCode = exitCode;
14
14
  }
15
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
+ }
16
31
  function missing(error) {
17
32
  return ['ENOENT', 'ENOTDIR'].includes(error.code ?? '');
18
33
  }
@@ -53,8 +68,6 @@ function canonicalPath(absolute, seen) {
53
68
  function alive(pid) {
54
69
  if (pid <= 1)
55
70
  return false;
56
- if (process.platform === 'win32')
57
- return windowsProcessStart(pid) !== undefined;
58
71
  try {
59
72
  process.kill(pid, 0);
60
73
  return true;
@@ -93,8 +106,8 @@ export function claude(all) {
93
106
  if (typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid > 2147483647)
94
107
  continue;
95
108
  const matches = pid === Number(entry.slice(0, -5));
96
- let live = matches && alive(pid);
97
- if (live && process.platform === 'win32') {
109
+ let live = matches && process.platform !== 'win32' && alive(pid);
110
+ if (matches && process.platform === 'win32') {
98
111
  const started = typeof record.startedAt === 'number' && Number.isSafeInteger(record.startedAt) && record.startedAt > 0 ? record.startedAt : NaN;
99
112
  const ticks = windowsProcessStart(pid);
100
113
  const actual = ticks === undefined ? NaN : Number((ticks - 116444736000000000n) / 10000n);
package/dist/output.js CHANGED
@@ -1,5 +1,6 @@
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')}`);
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')}`);
3
4
  export function renderOutput(value, format) {
4
5
  if (format === 'json')
5
6
  return JSON.stringify(value);
package/dist/process.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export declare class UnknownOutcome extends Error {
2
2
  }
3
+ export declare const batchShim: (path: string) => boolean;
3
4
  export declare function executable(name: string): string;
4
5
  export type Done = {
5
6
  code: number | null;
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
- if (statSync(path).isFile())
16
- return realpathSync(path);
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
  }
@@ -1,5 +1,5 @@
1
- export declare const VERSION = "0.2.0";
2
- export declare const VERSION_LINE = "session-peer 0.2.0 (typescript)";
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.2.0';
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.replace(/^\n+|\n+$/g, '') + (address ? `\n\n---\nReply-To: ${address}` : '');
58
+ return from + text.slice(start, end) + (address ? `\n\n---\nReply-To: ${address}` : '');
50
59
  }
package/dist/send.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { casefold } from './casefold.js';
2
2
  import { createConnection } from 'node:net';
3
- import { claude, Refusal } from './discovery.js';
3
+ import { claude, Refusal, sqliteHome } from './discovery.js';
4
4
  import { executable, run, UnknownOutcome } from './process.js';
5
5
  import { HomeRefusal, resolveWriter, revalidateWriter, uuid } from './writer.js';
6
6
  import { postWindowsPipe } from './windows.js';
@@ -62,12 +62,19 @@ export async function send(options) {
62
62
  const binary = executable(options.codexBin ?? 'codex');
63
63
  const selection = await resolveWriter(options.home, id, options.allowInactive);
64
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);
65
68
  const result = { ...base, target: { agent: 'codex', id }, codexHome: home,
66
69
  status: options.dryRun ? 'validated' : 'queued', codexHomeResolution: selection.resolution };
67
70
  if (options.dryRun)
68
71
  return result;
69
72
  await revalidateWriter(selection, options.home, id, options.allowInactive);
70
- const done = await run(binary, ['queue', '--thread', id, '--message', options.message], { env: { ...process.env, CODEX_HOME: home }, timeout: 30000 });
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 });
71
78
  if (!done.spawned)
72
79
  throw new HomeRefusal('native_spawn_failed', selection.resolution);
73
80
  if (done.interrupted || done.code !== 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>;
package/dist/windows.js CHANGED
@@ -70,6 +70,11 @@ function Openers([string]$location) {
70
70
  } finally { [void][Reader]::RmEndSession($session) }
71
71
  }
72
72
  `;
73
+ // Add-Type compiles the helper with csc on every inspectWindows call, which has
74
+ // exceeded 8 s on slow runners (#47, #65). Timeouts still fail closed. The
75
+ // compile-free creation-time probe keeps the shorter deadline.
76
+ export const COMPILED_INSPECTION_TIMEOUT_MS = 20000;
77
+ export const START_PROBE_TIMEOUT_MS = 8000;
73
78
  export function inspectWindows(mode, value) {
74
79
  if (process.platform !== 'win32')
75
80
  throw new Refusal('windows_inspection_unavailable', 1);
@@ -82,7 +87,7 @@ try {
82
87
  } catch { exit 1 }
83
88
  `;
84
89
  const done = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
85
- '$script = [Console]::In.ReadToEnd(); Invoke-Expression $script'], { input: code, encoding: 'utf8', timeout: 8000, maxBuffer: 65536, windowsHide: true });
90
+ '$script = [Console]::In.ReadToEnd(); Invoke-Expression $script'], { input: code, encoding: 'utf8', timeout: COMPILED_INSPECTION_TIMEOUT_MS, maxBuffer: 65536, windowsHide: true });
86
91
  if (done.status !== 0 || done.error)
87
92
  throw new Refusal('windows_owner_inspection_failed', 1);
88
93
  let rows;
@@ -101,9 +106,31 @@ try {
101
106
  return rows;
102
107
  }
103
108
  export function windowsProcessStart(pid) {
109
+ if (process.platform !== 'win32' || !Number.isSafeInteger(pid) || pid <= 1 || pid > 2147483647)
110
+ return undefined;
111
+ // Claude discovery only needs the creation time. Avoid compiling Reader and
112
+ // querying CIM/GetOwnerSid for every listed PID; Codex ownership still uses
113
+ // inspectWindows above. Dispose the native process handle on every path.
114
+ const code = `
115
+ $ErrorActionPreference = 'Stop'
116
+ try {
117
+ $item = [Diagnostics.Process]::GetProcessById(${pid})
118
+ try {
119
+ if ($item.HasExited) { exit 1 }
120
+ $ticks = $item.StartTime.ToUniversalTime().ToFileTimeUtc()
121
+ [Console]::Out.WriteLine($ticks.ToString([Globalization.CultureInfo]::InvariantCulture))
122
+ } finally { $item.Dispose() }
123
+ } catch { exit 1 }
124
+ `;
104
125
  try {
105
- const rows = inspectWindows('identity', String(pid));
106
- return rows.length === 1 ? BigInt(rows[0].start) : undefined;
126
+ const done = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', code], { encoding: 'utf8', timeout: START_PROBE_TIMEOUT_MS, maxBuffer: 65536, windowsHide: true });
127
+ if (done.status !== 0 || done.error)
128
+ return undefined;
129
+ const text = done.stdout.trim();
130
+ if (!/^[1-9][0-9]{0,18}$/.test(text))
131
+ return undefined;
132
+ const ticks = BigInt(text);
133
+ return ticks <= 9223372036854775807n ? ticks : undefined;
107
134
  }
108
135
  catch {
109
136
  return undefined;
package/docs/api.md ADDED
@@ -0,0 +1,30 @@
1
+ # API reference
2
+
3
+ [Back to README](../README.md) · [User guide](guide.md)
4
+
5
+ The package exposes a small ESM API with TypeScript declarations. Install it
6
+ locally with `npm install --ignore-scripts session-peer@0.2.1` before importing it.
7
+ Importing the package does not execute the CLI or submit a message.
8
+
9
+ ```js
10
+ import { VERSION, VERSION_LINE, reply, envelope } from 'session-peer';
11
+
12
+ console.log(VERSION); // 0.2.1
13
+ console.log(VERSION_LINE); // session-peer 0.2.1 (typescript)
14
+ const address = 'session-peer://v1/reply?agent=claude&session=12345&transport=local';
15
+ console.log(reply(address)); // { to: '12345' }
16
+ console.log(envelope('Please review and reply.', true, address));
17
+ ```
18
+
19
+ | Export | Contract |
20
+ | --- | --- |
21
+ | `VERSION` | Package version string. |
22
+ | `VERSION_LINE` | CLI version string including the TypeScript marker. |
23
+ | `reply(uri)` | Parse a supported Reply-To URI into `{ to, host?, home? }`; throw on invalid input. Parsing does not discover or authorize the destination. |
24
+ | `envelope(text, noFrom, address?)` | Trim leading/trailing newlines, optionally prepend valid Codex sender metadata from the environment, and append a validated Reply-To URI. Returns text only. |
25
+
26
+ The example uses a placeholder PID and performs no delivery. These helpers do
27
+ not verify a live writer, establish a return route, or confirm consumption.
28
+ Only the exports above form the public package API; internal `dist` modules are
29
+ not package subpath exports. Use the [CLI guide](guide.md#use) for sending and
30
+ [CONTRIBUTING.md](../CONTRIBUTING.md) for development and test setup.