session-peer 0.3.5 → 0.4.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,239 @@
1
+ // Opt-in, metadata-only observation for the exact qualified Codex store below.
2
+ // No transcript, native client, warming, migration or receipt bootstrap is used.
3
+ import childProcess from 'node:child_process';
4
+ import { isAbsolute, join, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ export const METADATA_SOURCE = Object.freeze({ version: '0.160.1',
7
+ commit: 'd27764b82f7118f674371e6d6e76271d9d606edb',
8
+ database: 'thread_history_1.sqlite', recentUsers: 256, maxCellBytes: 256 * 1024, childMs: 1000 });
9
+ // Persist this private qualification only after the original native queue and
10
+ // metadata preflight have both selected this exact source. A version read from
11
+ // today's PATH, a caller-supplied flag or the metadata schema alone cannot
12
+ // establish how an older intent was submitted.
13
+ export const METADATA_RESUME_QUALIFICATION = Object.freeze({ version: METADATA_SOURCE.version,
14
+ commit: METADATA_SOURCE.commit, platform: 'darwin-arm64' });
15
+ // Exact native qualification is separate from POSIX structural-store fixtures.
16
+ // No version range, current PATH inference or schema-only upgrade is permitted.
17
+ const metadataQualifications = Object.freeze([
18
+ METADATA_RESUME_QUALIFICATION,
19
+ Object.freeze({ version: '0.162.1', commit: '092d3acd6bec3e3a14bdc7e7a2810ab628ab759d', platform: 'darwin-arm64' }),
20
+ ]);
21
+ export function metadataQualification(version) {
22
+ if (typeof version !== 'string')
23
+ return undefined;
24
+ const exact = version.startsWith('codex-cli ') ? version.slice('codex-cli '.length) : version;
25
+ return metadataQualifications.find(profile => profile.version === exact);
26
+ }
27
+ const reasons = ['metadata_version_unsupported', 'metadata_platform_unsupported',
28
+ 'metadata_scope_invalid', 'metadata_storage_untrusted', 'metadata_history_unavailable', 'metadata_schema_unsupported',
29
+ 'metadata_owner_changed', 'metadata_deadline', 'metadata_probe_failed', 'metadata_probe_stopped', 'metadata_ambiguous'];
30
+ const safe = (value, limit) => typeof value === 'string' && value.length > 0 &&
31
+ Buffer.byteLength(value) <= limit && !/[\x00-\x1f\x7f-\x9f]/.test(value) &&
32
+ !/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value);
33
+ const uuid = (value) => /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(value);
34
+ const unsupported = (reason) => ({ supported: false, injectionObserved: false, reason });
35
+ function remaining(budget) {
36
+ const value = budget?.observationRemainingMs() ?? 3000;
37
+ return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
38
+ }
39
+ async function owner(scope, verify, budget) {
40
+ const duration = Math.min(METADATA_SOURCE.childMs, remaining(budget));
41
+ if (duration < 1)
42
+ return false;
43
+ const controller = new AbortController();
44
+ let timer;
45
+ try {
46
+ return await Promise.race([Promise.resolve().then(() => verify(scope, controller.signal)).then(value => value === true),
47
+ new Promise(resolve => { timer = setTimeout(() => { controller.abort(); resolve(false); }, duration); })]);
48
+ }
49
+ catch {
50
+ return false;
51
+ }
52
+ finally {
53
+ if (timer)
54
+ clearTimeout(timer);
55
+ controller.abort();
56
+ }
57
+ }
58
+ function probe(request, budget) {
59
+ const duration = Math.min(METADATA_SOURCE.childMs, remaining(budget));
60
+ if (duration < 1)
61
+ return Promise.resolve(unsupported('metadata_deadline'));
62
+ const extension = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
63
+ const worker = fileURLToPath(new URL('./handoff-observer-probe' + extension, import.meta.url));
64
+ return new Promise(resolve => {
65
+ let child;
66
+ try {
67
+ child = childProcess.spawn(process.execPath, [...(extension === '.ts' ? ['--experimental-strip-types'] : []), worker], {
68
+ detached: true, shell: false, stdio: ['pipe', 'pipe', 'pipe'],
69
+ env: { ...process.env, NODE_OPTIONS: undefined, NODE_PATH: undefined },
70
+ });
71
+ }
72
+ catch {
73
+ resolve(unsupported('metadata_probe_failed'));
74
+ return;
75
+ }
76
+ let finished = false, stopped = false, total = 0, output = '', stopReason = 'metadata_probe_failed';
77
+ let grace;
78
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
79
+ const handlers = new Map();
80
+ const reap = () => { if (child.pid)
81
+ try {
82
+ process.kill(-child.pid, 'SIGKILL');
83
+ }
84
+ catch { /* Already gone. */ } };
85
+ const finish = (result) => {
86
+ if (finished)
87
+ return;
88
+ finished = true;
89
+ clearTimeout(timer);
90
+ if (grace)
91
+ clearTimeout(grace);
92
+ for (const signal of signals)
93
+ process.removeListener(signal, handlers.get(signal));
94
+ resolve(result);
95
+ };
96
+ const stop = (reason) => {
97
+ if (stopped || finished)
98
+ return;
99
+ stopped = true;
100
+ stopReason = reason;
101
+ reap();
102
+ child.stdin.destroy();
103
+ child.stdout.destroy();
104
+ child.stderr.destroy();
105
+ // Cleanup grace stays inside the available original observation budget.
106
+ grace = setTimeout(() => finish(unsupported(reason)), Math.min(100, remaining(budget)));
107
+ };
108
+ const interrupted = (signal) => {
109
+ const sole = process.listenerCount(signal) === 1;
110
+ stop('metadata_probe_stopped');
111
+ if (sole) {
112
+ for (const name of signals)
113
+ process.removeListener(name, handlers.get(name));
114
+ process.kill(process.pid, signal);
115
+ }
116
+ };
117
+ const timer = setTimeout(() => stop('metadata_deadline'), duration);
118
+ for (const signal of signals) {
119
+ const handler = () => interrupted(signal);
120
+ handlers.set(signal, handler);
121
+ process.on(signal, handler);
122
+ }
123
+ child.stdin.on('error', () => { });
124
+ child.stdout.setEncoding('utf8');
125
+ child.stdout.on('data', (part) => { total += Buffer.byteLength(part); if (total > 4096)
126
+ stop('metadata_probe_failed');
127
+ else
128
+ output += part; });
129
+ // Drain without retaining or logging SQLite/native diagnostics.
130
+ child.stderr.on('data', (part) => { total += part.length; if (total > 8192)
131
+ stop('metadata_probe_failed'); });
132
+ child.once('error', () => stop('metadata_probe_failed'));
133
+ child.once('close', code => {
134
+ if (stopped) {
135
+ finish(unsupported(stopReason));
136
+ return;
137
+ }
138
+ if (code !== 0) {
139
+ finish(unsupported('metadata_probe_failed'));
140
+ return;
141
+ }
142
+ try {
143
+ const value = JSON.parse(output);
144
+ if (!value || typeof value.supported !== 'boolean' || typeof value.injectionObserved !== 'boolean' ||
145
+ Object.keys(value).some(key => !['supported', 'injectionObserved', 'reason', 'clientUserMessageId', 'turn', 'storageStamp'].includes(key)))
146
+ throw new Error();
147
+ if (!value.supported) {
148
+ if (value.injectionObserved || !reasons.includes(value.reason) || value.clientUserMessageId !== undefined ||
149
+ value.turn !== undefined || value.storageStamp !== undefined)
150
+ throw new Error();
151
+ }
152
+ else if (value.reason !== undefined || !/^[a-f0-9]{64}$/.test(value.storageStamp ?? '') ||
153
+ (request.expectedStorageStamp !== undefined && value.storageStamp !== request.expectedStorageStamp))
154
+ throw new Error();
155
+ if (value.injectionObserved) {
156
+ if (value.clientUserMessageId !== request.clientUserMessageId || !safe(value.clientUserMessageId, 128) || !value.turn ||
157
+ Object.keys(value.turn).some(key => !['id', 'status'].includes(key)) || !safe(value.turn.id, 128) ||
158
+ !['running', 'completed', 'failed', 'interrupted', 'unknown'].includes(value.turn.status))
159
+ throw new Error();
160
+ }
161
+ else if (value.clientUserMessageId !== undefined || value.turn !== undefined)
162
+ throw new Error();
163
+ finish(value);
164
+ }
165
+ catch {
166
+ finish(unsupported('metadata_probe_failed'));
167
+ }
168
+ });
169
+ child.stdin.end(JSON.stringify(request));
170
+ });
171
+ }
172
+ async function inspect(scope, mode, budget, verify, clientUserMessageId) {
173
+ if (!['darwin', 'linux'].includes(process.platform) || process.getuid?.() === undefined)
174
+ return unsupported('metadata_platform_unsupported');
175
+ if (!scope || !safe(scope.home, 2048) || !safe(scope.threadId, 128) || !uuid(scope.threadId) ||
176
+ !safe(scope.generation, 256) || (mode === 'observe' && !safe(clientUserMessageId, 128)))
177
+ return unsupported('metadata_scope_invalid');
178
+ const original = Object.freeze({ home: scope.home, threadId: scope.threadId, generation: scope.generation });
179
+ if (remaining(budget) < 1)
180
+ return unsupported('metadata_deadline');
181
+ // Filesystem calls can block on a disconnected volume. Every validation and
182
+ // inode comparison is performed inside a deadline-owned worker, never here.
183
+ const request = { database: join(original.home, METADATA_SOURCE.database), threadId: original.threadId.toLowerCase() };
184
+ const before = await probe({ ...request, mode: 'snapshot' }, budget);
185
+ if (!before.supported)
186
+ return before;
187
+ if (!(await owner(original, verify, budget)))
188
+ return unsupported(remaining(budget) < 1 ? 'metadata_deadline' : 'metadata_owner_changed');
189
+ const result = await probe({ ...request, mode, expectedStorageStamp: before.storageStamp,
190
+ ...(clientUserMessageId === undefined ? {} : { clientUserMessageId }) }, budget);
191
+ if (!result.supported)
192
+ return result;
193
+ if (!(await owner(original, verify, budget)))
194
+ return unsupported(remaining(budget) < 1 ? 'metadata_deadline' : 'metadata_owner_changed');
195
+ const after = await probe({ ...request, mode: 'snapshot', expectedStorageStamp: before.storageStamp }, budget);
196
+ if (!after.supported)
197
+ return after;
198
+ if (remaining(budget) < 1)
199
+ return unsupported('metadata_deadline');
200
+ const { storageStamp: _privateStamp, ...publicResult } = result;
201
+ return publicResult;
202
+ }
203
+ export async function metadataCapability(scope, version, budget, verifyOwner) {
204
+ if (!metadataQualification(version))
205
+ return { supported: false, reason: 'metadata_version_unsupported' };
206
+ const result = await inspect(scope, 'capability', budget, verifyOwner);
207
+ return { supported: result.supported, ...(result.reason === undefined ? {} : { reason: result.reason }) };
208
+ }
209
+ export function observeMetadata(scope, budget, verifyOwner) {
210
+ return inspect(scope, 'observe', budget, verifyOwner, scope.clientUserMessageId);
211
+ }
212
+ // Read-only reconciliation of a retained, positively submitted intent. The
213
+ // ledger caller supplies the ORIGINAL binding/qualification and must neither
214
+ // infer missing submission evidence nor replace the generation with today's
215
+ // owner. This API never finds or invokes Codex and never submits or warms data.
216
+ export function resumeMetadataObservation(scope, qualification, budget, verifyOwner) {
217
+ if (!qualification || typeof qualification !== 'object' || Array.isArray(qualification) ||
218
+ Object.keys(qualification).length !== 3 ||
219
+ Object.keys(qualification).some(key => !['version', 'commit', 'platform'].includes(key))) {
220
+ return Promise.resolve(unsupported('metadata_scope_invalid'));
221
+ }
222
+ const expected = metadataQualification(qualification.version);
223
+ // Retained records use the canonical native version, not a CLI banner.
224
+ if (!expected || qualification.version !== expected.version) {
225
+ return Promise.resolve(unsupported('metadata_version_unsupported'));
226
+ }
227
+ if (qualification.commit !== expected.commit) {
228
+ return Promise.resolve(unsupported('metadata_schema_unsupported'));
229
+ }
230
+ if (qualification.platform !== expected.platform ||
231
+ qualification.platform !== `${process.platform}-${process.arch}`) {
232
+ return Promise.resolve(unsupported('metadata_platform_unsupported'));
233
+ }
234
+ if (!scope || !safe(scope.home, 2048) || !isAbsolute(scope.home) || resolve(scope.home) !== scope.home ||
235
+ typeof scope.generation !== 'string' || !/^[a-f0-9]{64}$/.test(scope.generation)) {
236
+ return Promise.resolve(unsupported('metadata_scope_invalid'));
237
+ }
238
+ return inspect(scope, 'observe', budget, verifyOwner, scope.clientUserMessageId);
239
+ }
package/dist/output.js CHANGED
@@ -66,7 +66,13 @@ export function renderOutput(value, format) {
66
66
  if (value.command === 'update' && value.error === 'self_update_unsupported')
67
67
  lines.push(value.updateCommand ? `This installation is managed by ${safe(value.managedBy)}. Upgrade with: ${safe(value.updateCommand)}` : safe(value.guidance));
68
68
  if (value.command === 'send')
69
- lines.push(value.submitted === null ? 'Submission outcome unknown. Do not retry automatically.' : 'Nothing submitted.');
69
+ lines.push(value.submitted === true ? 'Submitted; the requested evidence goal was not established. Do not retry automatically.' : value.submitted === null ? 'Submission outcome unknown. Do not retry automatically.' : 'Nothing submitted.');
70
+ }
71
+ if (value.handoff && typeof value.handoff === 'object') {
72
+ const h = value.handoff;
73
+ lines.push(`Handoff: ${safe(h.correlationId)} (${safe(h.state)})`);
74
+ for (const key of ['observation', 'ack', 'wait'])
75
+ lines.push(`${key}: ${safe(JSON.stringify(h[key]))}`);
70
76
  }
71
77
  if (value.sshTransport && typeof value.sshTransport === 'object') {
72
78
  const transport = value.sshTransport;
@@ -1,5 +1,5 @@
1
- export declare const VERSION = "0.3.5";
2
- export declare const VERSION_LINE = "session-peer 0.3.5 (typescript)";
1
+ export declare const VERSION = "0.4.0";
2
+ export declare const VERSION_LINE = "session-peer 0.4.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,7 +1,7 @@
1
1
  import { isIPv6 } from 'node:net';
2
2
  import { Refusal } from './discovery.js';
3
3
  import { uuid } from './writer.js';
4
- export const VERSION = '0.3.5';
4
+ export const VERSION = '0.4.0';
5
5
  export const VERSION_LINE = `session-peer ${VERSION} (typescript)`;
6
6
  // Return the OpenSSH destination: [user@]name, or an IPv6 literal with any
7
7
  // brackets removed (`ssh` does not strip `[...]` outside ssh:// URIs). Zone IDs
package/dist/send.d.ts CHANGED
@@ -1,5 +1,21 @@
1
1
  import { UnknownOutcome } from './process.js';
2
2
  import { type HomeResolution } from './writer.js';
3
+ export type SendContext = {
4
+ agent: 'claude' | 'codex';
5
+ target: string;
6
+ home?: string;
7
+ generation: string | null;
8
+ writerIdentity?: string;
9
+ };
10
+ export type SendHooks = {
11
+ resolved: (context: SendContext, snapshot: Record<string, unknown>) => Promise<string | void> | string | void;
12
+ beforeEffect?: () => Promise<void> | void;
13
+ timeoutMs?: () => number;
14
+ submitCodex?: (context: SendContext, message: string) => Promise<{
15
+ queueId?: string;
16
+ clientUserMessageId: string;
17
+ }>;
18
+ };
3
19
  export type SendOptions = {
4
20
  to: string;
5
21
  home?: string;
@@ -7,6 +23,7 @@ export type SendOptions = {
7
23
  message: string;
8
24
  dryRun?: boolean;
9
25
  allowInactive?: boolean;
26
+ hooks?: SendHooks;
10
27
  };
11
28
  export declare class CodexUnknownOutcome extends UnknownOutcome {
12
29
  readonly codexHomeResolution: HomeResolution;
@@ -14,5 +31,5 @@ export declare class CodexUnknownOutcome extends UnknownOutcome {
14
31
  }
15
32
  export declare function queueId(stdout: string, id: string): string | undefined;
16
33
  export declare function checkMessage(text: string, codex?: boolean): void;
17
- export declare function postSocket(path: string, text: string): Promise<void>;
34
+ export declare function postSocket(path: string, text: string, timeout?: number): Promise<void>;
18
35
  export declare function send(options: SendOptions): Promise<Record<string, unknown>>;
package/dist/send.js CHANGED
@@ -1,5 +1,9 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { casefold } from './casefold.js';
2
3
  import { createConnection } from 'node:net';
4
+ import { closeSync, constants, fstatSync, lstatSync, openSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { join } from 'node:path';
3
7
  import { claude, Refusal, sqliteHome } from './discovery.js';
4
8
  import { executable, run, UnknownOutcome } from './process.js';
5
9
  import { HomeRefusal, resolveWriter, revalidateWriter, uuid } from './writer.js';
@@ -22,11 +26,12 @@ export function checkMessage(text, codex = false) {
22
26
  (codex && Buffer.byteLength(text, 'utf8') > 32768))
23
27
  throw new Refusal('invalid_message', 2);
24
28
  }
25
- export async function postSocket(path, text) {
29
+ export async function postSocket(path, text, timeout) {
26
30
  return new Promise((resolve, reject) => {
27
31
  let attempted = false, finished = false;
32
+ const startedAt = performance.now();
28
33
  const socket = createConnection(path);
29
- const timer = setTimeout(() => finish(new Error('timeout')), 10000);
34
+ const timer = setTimeout(() => finish(new Error('timeout')), timeout ?? 10000);
30
35
  const finish = (error) => {
31
36
  if (finished)
32
37
  return;
@@ -44,13 +49,48 @@ export async function postSocket(path, text) {
44
49
  socket.end(JSON.stringify({ type: 'user', message: { role: 'user', content: text } }) + '\n', () => {
45
50
  // Write completion is submission only, never consumption. Match Python's drain window.
46
51
  clearTimeout(timer);
47
- const drain = setTimeout(() => finish(), 2000);
52
+ const drain = setTimeout(() => finish(), timeout === undefined ? 2000 : Math.min(2000, Math.max(0, timeout - (performance.now() - startedAt))));
48
53
  socket.once('close', () => { clearTimeout(drain); finish(); });
49
54
  socket.once('data', () => { clearTimeout(drain); finish(); });
50
55
  });
51
56
  });
52
57
  });
53
58
  }
59
+ // A private continuity fingerprint, not proof of a native incarnation. Do not
60
+ // read or persist registry contents (which can include authentication material).
61
+ function claudeBindingIdentity(row) {
62
+ const stable = (s) => [s.dev, s.ino, s.uid, s.size, s.mtimeNs, s.ctimeNs, s.birthtimeNs].map(String);
63
+ const same = (a, b) => JSON.stringify(stable(a)) === JSON.stringify(stable(b));
64
+ const directory = process.env.CLAUDE_CONFIG_DIR || process.env.ANTHROPIC_CONFIG_DIR || join(homedir(), '.claude');
65
+ const path = join(directory, 'sessions', String(row.pid) + '.json');
66
+ try {
67
+ const before = lstatSync(path, { bigint: true });
68
+ if (!before.isFile() || before.size > 1024n * 1024n)
69
+ throw new Error();
70
+ const fd = openSync(path, constants.O_RDONLY | (process.platform === 'win32' ? 0 : constants.O_NOFOLLOW | constants.O_NONBLOCK));
71
+ let metadata;
72
+ try {
73
+ const opened = fstatSync(fd, { bigint: true });
74
+ if (!opened.isFile() || !same(before, opened) || !same(opened, lstatSync(path, { bigint: true })))
75
+ throw new Error();
76
+ metadata = stable(opened);
77
+ }
78
+ finally {
79
+ closeSync(fd);
80
+ }
81
+ let socket = null;
82
+ if (process.platform !== 'win32') {
83
+ const file = lstatSync(String(row.socket), { bigint: true });
84
+ if (!file.isSocket())
85
+ throw new Error();
86
+ socket = stable(file);
87
+ }
88
+ return createHash('sha256').update(JSON.stringify({ pid: row.pid, name: row.name, socketPath: row.socket, metadata, socket })).digest('hex');
89
+ }
90
+ catch {
91
+ throw new Refusal('target_changed', 1);
92
+ }
93
+ }
54
94
  export async function send(options) {
55
95
  checkMessage(options.message, options.to.startsWith('codex:'));
56
96
  const base = { ok: true, submitted: !options.dryRun, consumptionConfirmed: false,
@@ -67,14 +107,46 @@ export async function send(options) {
67
107
  throw new HomeRefusal(storage === 'configured' ? 'unsupported_codex_sqlite_home' : 'codex_config_unreadable', selection.resolution);
68
108
  const result = { ...base, target: { agent: 'codex', id }, codexHome: home,
69
109
  status: options.dryRun ? 'validated' : 'queued', codexHomeResolution: selection.resolution };
110
+ let context;
111
+ if (options.hooks) {
112
+ // Bind the identity already captured by selection, not a second sample
113
+ // which could belong to a different incarnation between A -> B -> A.
114
+ const proof = JSON.parse(selection.evidence);
115
+ const selected = proof.fingerprints.find(item => item.home === home);
116
+ const identity = selected?.writer;
117
+ const live = selection.resolution.candidates.find(item => item.codexHome === home)?.activity === 'live_writer';
118
+ if (!identity)
119
+ throw new HomeRefusal('active_writer_unverified', selection.resolution);
120
+ const generation = live ? createHash('sha256').update(identity).digest('hex') : null;
121
+ context = { agent: 'codex', target: id, home, generation,
122
+ // Inactive evidence still binds a prepared intent across invocations. This
123
+ // private fingerprint is not a native incarnation or public generation.
124
+ writerIdentity: generation ?? createHash('sha256').update(JSON.stringify(selected)).digest('hex') };
125
+ const body = await options.hooks.resolved(context, result);
126
+ if (body !== undefined) {
127
+ checkMessage(body, true);
128
+ options = { ...options, message: body };
129
+ result.chars = [...body].length;
130
+ }
131
+ }
70
132
  if (options.dryRun)
71
133
  return result;
72
134
  await revalidateWriter(selection, options.home, id, options.allowInactive);
135
+ if (options.hooks) {
136
+ const currentStorage = sqliteHome(home);
137
+ if (currentStorage !== 'default')
138
+ throw new HomeRefusal(currentStorage === 'configured' ? 'unsupported_codex_sqlite_home' : 'codex_config_unreadable', selection.resolution);
139
+ }
73
140
  // `--message=` keeps a body starting with `-` from being parsed as an option.
74
141
  // An inherited CODEX_SQLITE_HOME would queue outside the validated home.
75
142
  // Windows environment names are case-insensitive.
143
+ if (options.hooks?.submitCodex) {
144
+ const receipt = await options.hooks.submitCodex(context, options.message);
145
+ return { ...result, ...(receipt.queueId === undefined ? {} : { queueId: receipt.queueId }) };
146
+ }
76
147
  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 });
148
+ await options.hooks?.beforeEffect?.();
149
+ const done = await run(binary, ['queue', '--thread', id, `--message=${options.message}`], { env: { ...inherited, CODEX_HOME: home }, timeout: options.hooks?.timeoutMs?.() ?? 30000 });
78
150
  if (!done.spawned)
79
151
  throw new HomeRefusal('native_spawn_failed', selection.resolution);
80
152
  if (done.interrupted || done.code !== 0)
@@ -98,15 +170,28 @@ export async function send(options) {
98
170
  return matches[0];
99
171
  };
100
172
  const row = select();
173
+ const identity = options.hooks ? claudeBindingIdentity(row) : undefined;
101
174
  const result = { ...base, target: { agent: 'claude', pid: row.pid, name: row.name }, status: options.dryRun ? 'validated' : 'posted' };
175
+ if (options.hooks) {
176
+ // Existing POSIX Claude discovery proves PID/socket reachability, not a
177
+ // restart-safe native incarnation. Do not manufacture a generation.
178
+ const body = await options.hooks.resolved({ agent: 'claude', target: String(row.pid), generation: null, writerIdentity: identity }, result);
179
+ if (body !== undefined) {
180
+ checkMessage(body);
181
+ options = { ...options, message: body };
182
+ result.chars = [...body].length;
183
+ }
184
+ }
102
185
  if (options.dryRun)
103
186
  return result;
104
187
  const rechecked = select();
105
- if (row.pid !== rechecked.pid || row.socket !== rechecked.socket)
188
+ if (row.pid !== rechecked.pid || row.socket !== rechecked.socket ||
189
+ (identity !== undefined && claudeBindingIdentity(rechecked) !== identity))
106
190
  throw new Refusal('target_changed', 1);
191
+ await options.hooks?.beforeEffect?.();
107
192
  if (process.platform === 'win32')
108
193
  await postWindowsPipe(String(row.socket), Number(row.pid), options.message);
109
194
  else
110
- await postSocket(String(row.socket), options.message);
195
+ await postSocket(String(row.socket), options.message, options.hooks?.timeoutMs?.());
111
196
  return result;
112
197
  }
@@ -9,19 +9,20 @@ const verdict = (compatible) => ({ status: compatible ? 'compatible' : 'incompat
9
9
  code: compatible ? 'skill_contract_compatible' : 'skill_contract_mismatch', verification: 'metadata_only' });
10
10
  export const SKILL_METADATA_LIMIT = 65536;
11
11
  const keys = ['version', 'runtime-implementation', 'runtime-min-version', 'runtime-full-version', 'runtime-capability-policy'];
12
- // Preserve published 0.3.2/0.3.3/0.3.4 results. The 0.3.5 / skill 0.2.1
13
- // row is the #139 proposal activated by this 0.3.5 release candidate, not a
14
- // published companion profile. Candidate VERSION accepts this finite row;
15
- // this does not publish a companion skill or authenticate its content.
12
+ // Preserve each published runtime/profile result. The 0.4.0 release candidate
13
+ // preserves the three published profiles and adds one exact reviewed successor.
14
+ // Metadata compatibility does not authenticate content or publish/install a skill.
16
15
  // Every later runtime/profile requires separate review; no version ranges.
17
16
  const matrix = {
18
17
  '0.3.2': ['0.1.0'], '0.3.3': ['0.1.0', '0.2.0'], '0.3.4': ['0.1.0', '0.2.0'],
19
- '0.3.5': ['0.1.0', '0.2.0', '0.2.1']
18
+ '0.3.5': ['0.1.0', '0.2.0', '0.2.1'], '0.3.6': ['0.1.0', '0.2.0', '0.2.1'],
19
+ '0.4.0': ['0.1.0', '0.2.0', '0.2.1', '0.3.0']
20
20
  };
21
21
  const profiles = {
22
22
  '0.1.0': ['0.1.0', 'typescript', '0.1.0', '0.1.0', 'probe-help'],
23
23
  '0.2.0': ['0.2.0', 'typescript', '0.1.0', '0.3.2', 'probe-help'],
24
- '0.2.1': ['0.2.1', 'typescript', '0.1.0', '0.3.2', 'probe-help']
24
+ '0.2.1': ['0.2.1', 'typescript', '0.1.0', '0.3.2', 'probe-help'],
25
+ '0.3.0': ['0.3.0', 'typescript', '0.1.0', '0.4.0', 'probe-help']
25
26
  };
26
27
  // Deliberately not general YAML: plain ASCII tokens or unescaped quoted strings,
27
28
  // followed by an optional comment. YAML tags, aliases, maps and sequences fail.
@@ -1,8 +1,10 @@
1
1
  import type { Done } from './process.js';
2
+ import { type Handoff } from './handoff.js';
2
3
  export declare const RESPONSE_BYTES: number;
3
4
  export declare const RESPONSE_DEPTH = 64;
4
5
  export declare const RESPONSE_NODES = 65536;
5
6
  export declare function parseResponse(bytes: Uint8Array): Record<string, unknown>;
7
+ export type PreparedResponse = Pick<Handoff, 'correlationId' | 'ledgerEpoch' | 'targetGeneration'>;
6
8
  export type ResponseRequest = {
7
9
  command: string;
8
10
  to?: string;
@@ -10,6 +12,15 @@ export type ResponseRequest = {
10
12
  returnTo?: string;
11
13
  home?: string;
12
14
  allowInactive?: boolean;
15
+ handoff?: {
16
+ preparation?: boolean;
17
+ correlationId?: string;
18
+ requestAck?: boolean;
19
+ observeDelivery?: boolean;
20
+ waitFor?: 'delivered' | 'acknowledged';
21
+ prepared?: PreparedResponse;
22
+ destinationHost?: string;
23
+ };
13
24
  };
14
25
  export declare function validateResponse(value: Record<string, unknown>, request: ResponseRequest): void;
15
26
  export declare function responseOutcome(done: Done, request: ResponseRequest): {
@@ -1,6 +1,7 @@
1
1
  // Ordinary SSH response protocol. Internal helpers, not a package-root API.
2
2
  import { casefold } from './casefold.js';
3
3
  import { uuid } from './writer.js';
4
+ import { parseStrictJson, validateHandoff } from './handoff.js';
4
5
  export const RESPONSE_BYTES = 1024 * 1024;
5
6
  export const RESPONSE_DEPTH = 64;
6
7
  export const RESPONSE_NODES = 65536;
@@ -183,13 +184,88 @@ export function validateResponse(value, request) {
183
184
  export function responseOutcome(done, request) {
184
185
  if (!done.spawned || done.stopReason === 'output_limit' || !done.stdoutBytes)
185
186
  return invalid();
186
- const value = parseResponse(done.stdoutBytes);
187
- validateResponse(value, request);
187
+ const value = parseResponse(done.stdoutBytes), context = request.handoff;
188
+ if (context?.destinationHost !== undefined && value.host !== context.destinationHost)
189
+ invalid();
190
+ // The native profile is selected by the caller, never by returned metadata.
191
+ // Validate a positive native snapshot independently of a failed explicit wait.
192
+ const positive = request.command === 'send' && !request.dryRun && value.submitted === true;
193
+ const waitException = context?.waitFor !== undefined && positive && value.ok === false;
194
+ const native = waitException ? { ...value, ok: true } : value;
195
+ if (waitException)
196
+ delete native.error;
197
+ validateResponse(native, request);
198
+ let accepted;
199
+ if (context) {
200
+ try {
201
+ // The independently valid positive native snapshot does not make a
202
+ // malformed failed-wait envelope valid. Reject only its handoff evidence.
203
+ if (waitException && typeof value.error !== 'string')
204
+ invalid();
205
+ // The outer scanner preserved native facts; this second parser applies
206
+ // integer lexemes only to protocol subtrees before any lossy JSON values.
207
+ parseStrictJson(done.stdoutBytes, { scope: 'outer' });
208
+ const h = validateHandoff(value.handoff);
209
+ if (context.correlationId !== undefined && h.correlationId !== context.correlationId)
210
+ invalid();
211
+ if (context.preparation) {
212
+ if (!request.dryRun || !value.ok || h.state !== 'validated' || h.submission.status !== 'not_attempted' ||
213
+ h.wait.for !== 'none' || h.ack.status !== 'not_requested' || h.observation.status !== 'not_requested')
214
+ invalid();
215
+ }
216
+ else {
217
+ const expected = context.prepared;
218
+ if (!expected || (context.destinationHost !== undefined && value.host !== context.destinationHost) || h.correlationId !== expected.correlationId || h.ledgerEpoch !== expected.ledgerEpoch || h.targetGeneration !== expected.targetGeneration ||
219
+ h.wait.for !== (context.waitFor ?? 'none') || h.ack.status !== (context.requestAck || context.waitFor === 'acknowledged' ? 'unsupported' : 'not_requested') ||
220
+ (h.observation.injectionObserved && h.observation.clientUserMessageId !== expected.correlationId))
221
+ invalid();
222
+ if (positive && h.submission.status !== 'submitted')
223
+ invalid();
224
+ if (request.dryRun && h.submission.status !== 'not_attempted')
225
+ invalid();
226
+ if (!positive && !request.dryRun && h.submission.status !== (value.submitted === null ? 'unknown' : 'refused'))
227
+ invalid();
228
+ if (context.waitFor) {
229
+ const success = h.wait.status === 'satisfied';
230
+ const pendingPersistence = positive && h.wait.status === 'pending' &&
231
+ value.error === 'handoff_persistence_failed' && value.handoffWarning === 'persistence_failed';
232
+ if (value.ok !== success || (!success && !pendingPersistence && !['timed_out_unknown', 'unsupported', 'failed', 'stopped'].includes(h.wait.status)) ||
233
+ (h.wait.status === 'stopped' && (h.wait.reason !== 'stopped_by_operator' || done.interrupted || done.code !== 130)))
234
+ invalid();
235
+ }
236
+ }
237
+ accepted = h;
238
+ }
239
+ catch { /* Retain the separately validated native snapshot below. */ }
240
+ }
241
+ const persistenceWarning = value.handoffWarning === 'persistence_failed';
242
+ delete value.handoff;
243
+ delete value.handoffQuery;
244
+ delete value.handoffWarning;
245
+ if (accepted) {
246
+ value.handoff = accepted;
247
+ if (persistenceWarning)
248
+ value.handoffWarning = 'persistence_failed';
249
+ }
250
+ else if (context && positive) {
251
+ value.handoffWarning = 'invalid_handoff';
252
+ if (context.waitFor) {
253
+ value.ok = false;
254
+ value.error = 'invalid_handoff';
255
+ }
256
+ }
188
257
  // Reserved client-owned diagnosis; retain unrelated additive native fields.
189
258
  delete value.sshTransport;
190
259
  delete value.requestedCodexHome;
191
260
  const ordinary = !done.interrupted && [0, 1, 2].includes(done.code ?? -1);
261
+ const stopped = accepted?.wait.status === 'stopped' && !!context?.waitFor && positive && value.ok === false;
262
+ if (!done.interrupted && done.code === 130 && stopped)
263
+ return { value, exitCode: 130 };
192
264
  if (ordinary) {
265
+ if (context && !accepted && positive && context.waitFor)
266
+ return { value, exitCode: 1 };
267
+ if (accepted?.wait.status === 'stopped')
268
+ return invalid();
193
269
  if (value.ok !== (done.code === 0))
194
270
  return invalid();
195
271
  return { value, exitCode: done.code };