session-peer 0.3.6 → 0.5.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.
Files changed (52) hide show
  1. package/CONTRIBUTING.md +6 -4
  2. package/PARITY.md +431 -6
  3. package/README.ja.md +14 -8
  4. package/README.ko.md +14 -8
  5. package/README.md +14 -8
  6. package/README.zh-CN.md +14 -8
  7. package/RELEASING.md +109 -0
  8. package/VALIDATION.md +806 -1
  9. package/dist/app-server.d.ts +207 -0
  10. package/dist/app-server.js +1044 -0
  11. package/dist/cli.js +229 -39
  12. package/dist/handoff-ledger.d.ts +103 -0
  13. package/dist/handoff-ledger.js +791 -0
  14. package/dist/handoff-observer-probe.d.ts +1 -0
  15. package/dist/handoff-observer-probe.js +170 -0
  16. package/dist/handoff-operations.d.ts +29 -0
  17. package/dist/handoff-operations.js +496 -0
  18. package/dist/handoff-writer-probe.d.ts +1 -0
  19. package/dist/handoff-writer-probe.js +146 -0
  20. package/dist/handoff.d.ts +112 -0
  21. package/dist/handoff.js +261 -0
  22. package/dist/help.js +18 -0
  23. package/dist/linux-native-probe.d.ts +1 -0
  24. package/dist/linux-native-probe.js +51 -0
  25. package/dist/linux-proc.d.ts +55 -0
  26. package/dist/linux-proc.js +150 -0
  27. package/dist/metadata-observation.d.ts +49 -0
  28. package/dist/metadata-observation.js +250 -0
  29. package/dist/native-profiles.d.ts +25 -0
  30. package/dist/native-profiles.js +62 -0
  31. package/dist/output.js +7 -1
  32. package/dist/process.d.ts +28 -0
  33. package/dist/process.js +284 -2
  34. package/dist/protocol.d.ts +2 -2
  35. package/dist/protocol.js +1 -1
  36. package/dist/send.d.ts +18 -1
  37. package/dist/send.js +91 -6
  38. package/dist/skill-metadata.js +7 -4
  39. package/dist/ssh-response.d.ts +11 -0
  40. package/dist/ssh-response.js +78 -2
  41. package/dist/ssh.d.ts +2 -1
  42. package/dist/ssh.js +37 -2
  43. package/dist/windows.d.ts +28 -0
  44. package/dist/windows.js +149 -1
  45. package/docs/api.md +255 -4
  46. package/docs/design/typescript-skill-compatibility.md +55 -2
  47. package/docs/guide.ja.md +36 -16
  48. package/docs/guide.ko.md +39 -19
  49. package/docs/guide.md +46 -20
  50. package/docs/guide.zh-CN.md +36 -16
  51. package/docs/shorthand.md +1 -1
  52. package/package.json +2 -2
package/dist/process.js CHANGED
@@ -1,7 +1,8 @@
1
- import { spawn } from 'node:child_process';
1
+ import childProcess, { spawn } from 'node:child_process';
2
2
  import { accessSync, constants, realpathSync, statSync } from 'node:fs';
3
3
  import { delimiter, isAbsolute, join } from 'node:path';
4
4
  import { StringDecoder } from 'node:string_decoder';
5
+ import timers from 'node:timers/promises';
5
6
  import { Refusal } from './discovery.js';
6
7
  export class UnknownOutcome extends Error {
7
8
  }
@@ -37,7 +38,8 @@ export function executable(name) {
37
38
  // this CLI reaps that group, which includes descendants such as a jump
38
39
  // ProxyCommand, and nothing else; a descendant that calls setsid() itself has
39
40
  // left the group and is out of scope (there is no PID scanning). Windows has no
40
- // equivalent here: only the child is killed and descendants may linger.
41
+ // equivalent here: only the child is killed and descendants may linger; the
42
+ // tree backend below is a candidate that is deliberately not used (#131).
41
43
  const groups = new Set();
42
44
  const posix = process.platform !== 'win32';
43
45
  const reap = (pid) => { if (pid)
@@ -150,3 +152,283 @@ export function run(binary, args, options = {}) {
150
152
  child.stdin.end(options.input);
151
153
  });
152
154
  }
155
+ // Request: "<hold csv|-> <kill csv|->". Reply: "ok <rows> <held> <errors>"
156
+ // with rows pid:ppid, held pid:start:exit (exit empty while running) and errors
157
+ // pid:gone|denied. Get-CimInstance returns no command lines or arguments here.
158
+ const helperScript = String.raw `
159
+ $ErrorActionPreference = 'Stop'
160
+ $held = @{}
161
+ function Ids([string]$text) {
162
+ if ($text -eq '-') { return @() }
163
+ if ($text -notmatch '^[0-9]{1,10}(,[0-9]{1,10}){0,4095}$') { throw 'invalid_request' }
164
+ return @($text.Split(',') | ForEach-Object { [int]$_ })
165
+ }
166
+ function Field($list) { if ($list.Count) { return ($list -join ',') }; return '-' }
167
+ function Ticks([DateTime]$time) { return $time.ToUniversalTime().ToFileTimeUtc().ToString([Globalization.CultureInfo]::InvariantCulture) }
168
+ while ($null -ne ($line = [Console]::In.ReadLine())) {
169
+ try {
170
+ $parts = $line.Split(' ')
171
+ if ($parts.Count -ne 2) { throw 'invalid_request' }
172
+ $errors = @()
173
+ foreach ($id in (Ids $parts[0])) {
174
+ if ($held.ContainsKey($id)) { continue }
175
+ try {
176
+ $item = [Diagnostics.Process]::GetProcessById($id)
177
+ # Handle opens and caches one handle; StartTime, HasExited and Kill
178
+ # below all use it, so the identity checked is the identity killed.
179
+ $null = $item.Handle
180
+ $held[$id] = $item
181
+ } catch [ComponentModel.Win32Exception] {
182
+ $kind = 'gone'; if ($_.Exception.NativeErrorCode -eq 5) { $kind = 'denied' }
183
+ $errors += "$($id):$kind"
184
+ } catch { $errors += "$($id):gone" }
185
+ }
186
+ # Snapshot right after the holds and before any kill, so every candidate
187
+ # held here that is still running is listed with its own parent.
188
+ $rows = @(Get-CimInstance -ClassName Win32_Process -Property ProcessId,ParentProcessId | ForEach-Object { "$($_.ProcessId):$($_.ParentProcessId)" })
189
+ $kills = @(Ids $parts[1])
190
+ foreach ($id in $kills) { if ($held.ContainsKey($id)) { try { $held[$id].Kill() } catch {} } }
191
+ foreach ($id in $kills) { if ($held.ContainsKey($id)) { try { [void]$held[$id].WaitForExit(250) } catch {} } }
192
+ $states = @()
193
+ foreach ($id in @($held.Keys)) {
194
+ $item = $held[$id]
195
+ $exit = ''; if ($item.HasExited) { $exit = Ticks $item.ExitTime }
196
+ $states += "$($id):$(Ticks $item.StartTime):$exit"
197
+ }
198
+ [Console]::Out.WriteLine("ok $(Field $rows) $(Field $states) $(Field $errors)")
199
+ } catch { [Console]::Out.WriteLine('error') }
200
+ [Console]::Out.Flush()
201
+ }
202
+ `;
203
+ const csv = (values) => values.length ? values.join(',') : '-';
204
+ const ticks = (text) => { if (!/^[1-9][0-9]{0,18}$/.test(text))
205
+ throw new Error('tree_reply'); return BigInt(text); };
206
+ export function parseTreeReply(line) {
207
+ const parts = line.split(' ');
208
+ if (parts.length !== 4 || parts[0] !== 'ok')
209
+ throw new Error('tree_reply');
210
+ const list = (text) => text === '-' ? [] : text.split(',');
211
+ const id = (text) => { if (!/^[0-9]{1,10}$/.test(text))
212
+ throw new Error('tree_reply'); return Number(text); };
213
+ const reply = { rows: new Map(), held: new Map(), errors: new Map() };
214
+ for (const row of list(parts[1])) {
215
+ const [pid, ppid, extra] = row.split(':');
216
+ if (extra !== undefined)
217
+ throw new Error('tree_reply');
218
+ reply.rows.set(id(pid), id(ppid ?? ''));
219
+ }
220
+ for (const row of list(parts[2])) {
221
+ const [pid, start, exit, extra] = row.split(':');
222
+ if (extra !== undefined || exit === undefined)
223
+ throw new Error('tree_reply');
224
+ reply.held.set(id(pid), { start: ticks(start), exit: exit === '' ? null : ticks(exit) });
225
+ }
226
+ for (const row of list(parts[3])) {
227
+ const [pid, error, extra] = row.split(':');
228
+ if (extra !== undefined || (error !== 'gone' && error !== 'denied'))
229
+ throw new Error('tree_reply');
230
+ reply.errors.set(id(pid), error);
231
+ }
232
+ return reply;
233
+ }
234
+ // One helper per cleanup, started only after a stop (so after any Ctrl-C that
235
+ // caused it); it exits on stdin EOF. Not detached: PowerShell started with
236
+ // DETACHED_PROCESS reads EOF from its piped stdin and exits at once (measured
237
+ // on Windows 10 x64 / PowerShell 5.1). A further Ctrl-C during cleanup can end
238
+ // the helper; that cleanup then reports unconfirmed.
239
+ export function windowsTreeHelper() {
240
+ const helper = childProcess.spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand',
241
+ Buffer.from(helperScript, 'utf16le').toString('base64')], { shell: false, windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] });
242
+ let buffer = '', waiting, failed = false;
243
+ const fail = () => { failed = true; waiting?.reject(new Error('tree_helper')); waiting = undefined; };
244
+ helper.once('error', fail);
245
+ helper.once('exit', fail);
246
+ helper.stdin.on('error', fail);
247
+ helper.stdout.setEncoding('utf8');
248
+ helper.stdout.on('data', (part) => {
249
+ buffer += part;
250
+ if (buffer.length > 4 * 1024 * 1024) {
251
+ fail();
252
+ helper.kill();
253
+ return;
254
+ }
255
+ const end = buffer.indexOf('\n');
256
+ if (end < 0)
257
+ return;
258
+ const line = buffer.slice(0, end).replace(/\r$/, '');
259
+ buffer = buffer.slice(end + 1);
260
+ const pending = waiting;
261
+ waiting = undefined;
262
+ try {
263
+ pending?.resolve(parseTreeReply(line));
264
+ }
265
+ catch {
266
+ pending?.reject(new Error('tree_reply'));
267
+ }
268
+ });
269
+ return {
270
+ pid: helper.pid,
271
+ request(hold, kill) {
272
+ return new Promise((resolve, reject) => {
273
+ if (failed || waiting) {
274
+ reject(new Error('tree_helper'));
275
+ return;
276
+ }
277
+ waiting = { resolve, reject };
278
+ helper.stdin.write(`${csv(hold)} ${csv(kill)}\n`);
279
+ });
280
+ },
281
+ close() { try {
282
+ helper.stdin.destroy();
283
+ helper.stdout.destroy();
284
+ helper.kill();
285
+ }
286
+ catch { /* Already gone. */ } },
287
+ };
288
+ }
289
+ // A provisional classifier, not an ownership proof. It compares creation/exit
290
+ // times read through held handles; those are UTC wall-clock instants, so the
291
+ // ordering is known to be unsound under a clock rollback, which is why no
292
+ // production path selects this backend. The root is identified first: Node
293
+ // holds its handle until Node observes its exit, so a hold that completes
294
+ // before that holds the root itself (the root is terminated only after this
295
+ // and after its listed children are held, or after ROOT_HOLD_GRACE_MS if the
296
+ // helper is slow). A descendant C is accepted when its parent P was accepted
297
+ // and P.start <= C.start <= P.exit by those UTC times, P being held and so
298
+ // stable. Only accepted candidates are killed; anything else is held but not
299
+ // killed. When the root's identity, a candidate's identity or a candidate's
300
+ // parent cannot be established (root exited first, vanished, denied, unlisted),
301
+ // nothing under it is killed and the result is unconfirmed.
302
+ // A descendant whose own parent exited and was released before cleanup began
303
+ // is not linked to the root at all; it is neither killed nor detectable here.
304
+ // close() asks the helper to exit; it does not await its termination.
305
+ export const ROOT_HOLD_GRACE_MS = 2000;
306
+ export async function reapWindowsTree(root, deadline, options = {}) {
307
+ const now = options.now ?? (() => performance.now()), self = options.self ?? process.pid;
308
+ let helper;
309
+ const grace = setTimeout(() => root.kill(), Math.max(0, Math.min(ROOT_HOLD_GRACE_MS, deadline() - now())));
310
+ try {
311
+ helper = (options.helper ?? windowsTreeHelper)();
312
+ }
313
+ catch {
314
+ clearTimeout(grace);
315
+ root.kill();
316
+ return 'unconfirmed';
317
+ }
318
+ const owned = new Map(), foreign = new Set(), unknown = new Set();
319
+ const listed = new Map();
320
+ // An already observed exit means the root PID may be reused: no evidence.
321
+ let hold = root.exited() ? [] : [root.pid], kill = [];
322
+ let doubtful = !hold.length, rootPending = hold.length > 0;
323
+ const parentOwns = (ppid, start) => {
324
+ const parent = owned.get(ppid);
325
+ return !!parent && start >= parent.start && (parent.exit === null || start <= parent.exit);
326
+ };
327
+ const aborted = new Promise(resolve => {
328
+ if (options.signal?.aborted)
329
+ resolve(undefined);
330
+ else
331
+ options.signal?.addEventListener('abort', () => resolve(undefined), { once: true });
332
+ });
333
+ try {
334
+ for (;;) {
335
+ const remaining = deadline() - now();
336
+ if (remaining <= 0 || options.signal?.aborted)
337
+ return 'unconfirmed';
338
+ // A reply can confirm only if its snapshot followed every kill and the
339
+ // root's observed exit (the helper snapshots before a request's kills).
340
+ const settledBefore = !kill.length && root.exited();
341
+ const abort = new AbortController();
342
+ const reply = await Promise.race([helper.request(hold, kill), aborted,
343
+ timers.setTimeout(remaining, undefined, { signal: abort.signal }).catch(() => undefined)]).finally(() => abort.abort());
344
+ if (!reply)
345
+ return 'unconfirmed';
346
+ for (const [pid, state] of reply.held) {
347
+ const node = owned.get(pid);
348
+ if (node)
349
+ node.exit = state.exit;
350
+ }
351
+ for (const pid of hold) {
352
+ const state = reply.held.get(pid);
353
+ if (rootPending && pid === root.pid) {
354
+ // Still unobserved by Node now, so it was the root when opened.
355
+ rootPending = false;
356
+ // An identified root is terminated through the held handle once the
357
+ // visible tree is held (Node's own kill would let a Node child's job
358
+ // end them first, unheld); the grace timer stays as the backstop.
359
+ // An unidentified root is killed now (through Node's handle).
360
+ if (state && !root.exited())
361
+ owned.set(pid, { ...state });
362
+ else {
363
+ doubtful = true;
364
+ unknown.add(pid);
365
+ clearTimeout(grace);
366
+ root.kill();
367
+ }
368
+ continue;
369
+ }
370
+ if (!state) {
371
+ doubtful = true;
372
+ unknown.add(pid);
373
+ continue;
374
+ }
375
+ // Only this snapshot, taken after the hold, describes the held process.
376
+ // An earlier row may belong to a previous holder of the PID, and no
377
+ // wall-clock stamp can show otherwise: an unlisted (already exited)
378
+ // candidate stays unclassified, and nothing under it is killed.
379
+ const ppid = reply.rows.get(pid);
380
+ if (ppid === undefined) {
381
+ doubtful = true;
382
+ unknown.add(pid);
383
+ }
384
+ else if (ppid !== pid && parentOwns(ppid, state.start))
385
+ owned.set(pid, { ...state });
386
+ else {
387
+ // A changed parent means the listed process was replaced before the
388
+ // hold; whatever it started is no longer visible: doubtful.
389
+ if (ppid !== listed.get(pid))
390
+ doubtful = true;
391
+ foreign.add(pid);
392
+ }
393
+ }
394
+ hold = [];
395
+ kill = [];
396
+ for (const [pid, node] of owned)
397
+ if (node.exit === null)
398
+ kill.push(pid);
399
+ // An unidentified root already made the result doubtful; its PID is in unknown.
400
+ for (const [pid, ppid] of reply.rows) {
401
+ if (unknown.has(ppid))
402
+ doubtful = true;
403
+ if (pid <= 4 || pid === ppid || pid === self || pid === helper.pid || owned.has(pid) || foreign.has(pid) || unknown.has(pid))
404
+ continue;
405
+ if (owned.has(ppid)) {
406
+ hold.push(pid);
407
+ listed.set(pid, ppid);
408
+ }
409
+ }
410
+ // Hold the whole visible tree before killing anything: a dying Node
411
+ // parent's job ends its children, and an unheld one would then vanish
412
+ // unattributed. A tree that keeps growing is bounded by the deadline
413
+ // (the root by ROOT_HOLD_GRACE_MS).
414
+ if (hold.length)
415
+ kill = [];
416
+ if (!hold.length && !kill.length) {
417
+ if (root.exited() && settledBefore)
418
+ return doubtful ? 'unconfirmed' : 'confirmed';
419
+ if (root.exited())
420
+ continue;
421
+ // The root was asked to terminate; give Node a moment to observe it.
422
+ await Promise.race([timers.setTimeout(Math.max(0, Math.min(25, deadline() - now()))), aborted]);
423
+ }
424
+ }
425
+ }
426
+ catch {
427
+ return 'unconfirmed';
428
+ }
429
+ finally {
430
+ clearTimeout(grace);
431
+ root.kill();
432
+ helper.close();
433
+ }
434
+ }
@@ -1,5 +1,5 @@
1
- export declare const VERSION = "0.3.6";
2
- export declare const VERSION_LINE = "session-peer 0.3.6 (typescript)";
1
+ export declare const VERSION = "0.5.0";
2
+ export declare const VERSION_LINE = "session-peer 0.5.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.6';
4
+ export const VERSION = '0.5.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,18 +9,21 @@ 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 each published runtime/profile result. The 0.3.6 release candidate
13
- // carries forward the exact three profiles reviewed for published 0.3.5.
12
+ // Preserve each published runtime/profile result. The 0.5.0 release candidate
13
+ // carries forward only the four exact profiles accepted by public 0.4.0.
14
14
  // Metadata compatibility does not authenticate content or publish/install a skill.
15
15
  // Every later runtime/profile requires separate review; no version ranges.
16
16
  const matrix = {
17
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'],
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']
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
+ '0.5.0': ['0.1.0', '0.2.0', '0.2.1', '0.3.0']
19
21
  };
20
22
  const profiles = {
21
23
  '0.1.0': ['0.1.0', 'typescript', '0.1.0', '0.1.0', 'probe-help'],
22
24
  '0.2.0': ['0.2.0', 'typescript', '0.1.0', '0.3.2', 'probe-help'],
23
- '0.2.1': ['0.2.1', 'typescript', '0.1.0', '0.3.2', 'probe-help']
25
+ '0.2.1': ['0.2.1', 'typescript', '0.1.0', '0.3.2', 'probe-help'],
26
+ '0.3.0': ['0.3.0', 'typescript', '0.1.0', '0.4.0', 'probe-help']
24
27
  };
25
28
  // Deliberately not general YAML: plain ASCII tokens or unescaped quoted strings,
26
29
  // 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 };