session-peer 0.5.2 → 0.6.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.
Files changed (45) hide show
  1. package/CONTRIBUTING.md +11 -5
  2. package/PARITY.md +20 -5
  3. package/README.ja.md +8 -8
  4. package/README.ko.md +8 -8
  5. package/README.md +8 -8
  6. package/README.zh-CN.md +8 -8
  7. package/RELEASING.md +116 -0
  8. package/VALIDATION.md +137 -1
  9. package/dist/cli.js +54 -4
  10. package/dist/diagnostics.js +17 -98
  11. package/dist/discovery.d.ts +32 -0
  12. package/dist/discovery.js +405 -68
  13. package/dist/handoff-operations.js +88 -34
  14. package/dist/help.js +18 -2
  15. package/dist/macos-acl.d.ts +10 -0
  16. package/dist/macos-acl.js +75 -0
  17. package/dist/output.js +6 -1
  18. package/dist/protocol.d.ts +2 -2
  19. package/dist/protocol.js +1 -1
  20. package/dist/receipt-collector.d.ts +12 -0
  21. package/dist/receipt-collector.js +283 -0
  22. package/dist/receipt-command.d.ts +10 -0
  23. package/dist/receipt-command.js +246 -0
  24. package/dist/receipt-producer.d.ts +7 -0
  25. package/dist/receipt-producer.js +107 -0
  26. package/dist/receipt-protocol.d.ts +219 -0
  27. package/dist/receipt-protocol.js +374 -0
  28. package/dist/receipt-send.d.ts +26 -0
  29. package/dist/receipt-send.js +375 -0
  30. package/dist/receipt-state.d.ts +89 -0
  31. package/dist/receipt-state.js +503 -0
  32. package/dist/receipt-store.d.ts +32 -0
  33. package/dist/receipt-store.js +286 -0
  34. package/dist/replies.js +3 -1
  35. package/dist/send.d.ts +5 -2
  36. package/dist/send.js +34 -49
  37. package/dist/skill-metadata.js +5 -3
  38. package/docs/api.md +32 -7
  39. package/docs/design/typescript-skill-compatibility.md +48 -0
  40. package/docs/guide.ja.md +41 -15
  41. package/docs/guide.ko.md +43 -17
  42. package/docs/guide.md +42 -16
  43. package/docs/guide.zh-CN.md +41 -15
  44. package/docs/shorthand.md +1 -1
  45. package/package.json +3 -3
@@ -0,0 +1,286 @@
1
+ // Owner-private managed receipt storage. This module never launches a process,
2
+ // opens an agent inbox, interprets a supplied target path or repairs old history.
3
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from 'node:crypto';
4
+ import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, opendirSync, readSync, renameSync, writeSync } from 'node:fs';
5
+ import { isAbsolute, join, resolve } from 'node:path';
6
+ import { createRequire } from 'node:module';
7
+ import { canonicalId, closed, fail, HANDOFF_LIMITS, parseStrictJson, safeId } from './handoff.js';
8
+ import { inspectMacosAcls } from './macos-acl.js';
9
+ export const receiptDigest = (value) => createHash('sha256').update(value).digest('hex');
10
+ const flags = constants.O_NOFOLLOW | constants.O_NONBLOCK;
11
+ const identity = (s) => [s.dev, s.ino, s.uid, s.mode, s.nlink, s.size, s.mtimeNs, s.ctimeNs].join(':');
12
+ const directoryIdentity = (s) => [s.dev, s.ino, s.uid, s.mode].join(':');
13
+ // ACL changes update ctime. Cache only an inspected unchanged descriptor/path
14
+ // snapshot, and bound this process-local metadata cache independently of history.
15
+ const aclEvidence = new Map();
16
+ function privateStat(path, directory) {
17
+ const uid = process.getuid?.();
18
+ if (uid === undefined || process.platform === 'win32')
19
+ fail('receipt_storage_unsupported');
20
+ const s = lstatSync(path, { bigint: true });
21
+ if (s.isSymbolicLink() || (directory ? !s.isDirectory() : !s.isFile()) || s.uid !== BigInt(uid) ||
22
+ (s.mode & 511n) !== (directory ? 448n : 384n) || (!directory && s.nlink !== 1n))
23
+ fail('receipt_storage_untrusted');
24
+ if (process.platform === 'darwin' && aclEvidence.get(path) !== identity(s)) {
25
+ if (inspectMacosAcls([path]) !== 'clear' || identity(lstatSync(path, { bigint: true })) !== identity(s))
26
+ fail('receipt_storage_untrusted');
27
+ if (aclEvidence.size >= 256)
28
+ aclEvidence.clear();
29
+ aclEvidence.set(path, identity(s));
30
+ }
31
+ return s;
32
+ }
33
+ function writeAll(fd, data) {
34
+ let offset = 0;
35
+ while (offset < data.byteLength) {
36
+ const count = writeSync(fd, data, offset, data.byteLength - offset);
37
+ if (count <= 0)
38
+ fail('receipt_history_unavailable');
39
+ offset += count;
40
+ }
41
+ fsyncSync(fd);
42
+ }
43
+ function syncDirectory(path) {
44
+ const fd = openSync(path, constants.O_RDONLY | flags);
45
+ try {
46
+ fsyncSync(fd);
47
+ }
48
+ finally {
49
+ closeSync(fd);
50
+ }
51
+ }
52
+ function readPrivate(path, limit) {
53
+ const before = privateStat(path, false);
54
+ if (before.size > BigInt(limit))
55
+ fail('receipt_history_corrupt');
56
+ const fd = openSync(path, constants.O_RDONLY | flags);
57
+ try {
58
+ const opened = fstatSync(fd, { bigint: true });
59
+ if (identity(opened) !== identity(before))
60
+ fail('receipt_storage_untrusted');
61
+ const buffer = Buffer.alloc(Math.min(Number(opened.size) + 1, limit + 1));
62
+ let length = 0;
63
+ while (length < buffer.length) {
64
+ const count = readSync(fd, buffer, length, buffer.length - length, length);
65
+ if (!count)
66
+ break;
67
+ length += count;
68
+ }
69
+ if (length !== Number(opened.size) || identity(fstatSync(fd, { bigint: true })) !== identity(opened) ||
70
+ identity(privateStat(path, false)) !== identity(opened))
71
+ fail('receipt_storage_untrusted');
72
+ return { bytes: buffer.subarray(0, length), evidence: identity(opened) };
73
+ }
74
+ finally {
75
+ closeSync(fd);
76
+ }
77
+ }
78
+ function createPrivate(path, value) {
79
+ const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | flags, 0o600);
80
+ try {
81
+ writeAll(fd, value);
82
+ }
83
+ finally {
84
+ closeSync(fd);
85
+ }
86
+ }
87
+ const locks = () => createRequire(import.meta.url)('fs-ext-extra-prebuilt');
88
+ // A lifetime kernel lock, with every later read/write tied to its original inode.
89
+ // A missing/replaced key, marker, lock or state is not an invitation to recreate it.
90
+ export class ReceiptStore {
91
+ path;
92
+ marker;
93
+ fd;
94
+ lockEvidence;
95
+ directoryEvidence;
96
+ markerEvidence;
97
+ keyEvidence;
98
+ key;
99
+ stateEvidence = '';
100
+ poisoned = false;
101
+ constructor(path) {
102
+ if (!isAbsolute(path))
103
+ fail('receipt_storage_untrusted');
104
+ this.path = resolve(path);
105
+ this.directoryEvidence = directoryIdentity(privateStat(this.path, true));
106
+ const lockPath = join(this.path, 'collector.lock'), before = privateStat(lockPath, false);
107
+ const fd = openSync(lockPath, constants.O_RDWR | flags);
108
+ try {
109
+ if (identity(fstatSync(fd, { bigint: true })) !== identity(before))
110
+ fail('receipt_storage_untrusted');
111
+ try {
112
+ locks().flockSync(fd, 'exnb');
113
+ }
114
+ catch {
115
+ fail('receipt_collector_busy');
116
+ }
117
+ this.fd = fd;
118
+ this.lockEvidence = identity(before);
119
+ const marker = readPrivate(join(this.path, 'managed.json'), 16384);
120
+ const m = closed(parseStrictJson(marker.bytes, { maxBytes: 16384 }), ['version', 'ledgerEpoch', 'endpointSelector']);
121
+ if (m.version !== 2 || !canonicalId(m.ledgerEpoch) || !safeId(m.endpointSelector, 4096) || !isAbsolute(m.endpointSelector))
122
+ fail('receipt_history_corrupt');
123
+ this.marker = Object.freeze(m);
124
+ this.markerEvidence = marker.evidence;
125
+ const key = readPrivate(join(this.path, 'ledger.key'), 32);
126
+ if (key.bytes.length !== 32)
127
+ fail('receipt_history_corrupt');
128
+ this.key = Buffer.from(key.bytes);
129
+ this.keyEvidence = key.evidence;
130
+ this.assertOwner();
131
+ }
132
+ catch (error) {
133
+ if (this.fd !== undefined) {
134
+ try {
135
+ locks().flockSync(fd, 'un');
136
+ }
137
+ finally {
138
+ this.fd = undefined;
139
+ closeSync(fd);
140
+ }
141
+ }
142
+ else
143
+ closeSync(fd);
144
+ throw error;
145
+ }
146
+ }
147
+ static initialize(path, endpointSelector) {
148
+ if (!isAbsolute(path) || !safeId(endpointSelector, 4096) || !isAbsolute(endpointSelector))
149
+ fail('receipt_storage_untrusted');
150
+ if (process.platform === 'win32' || process.getuid?.() === undefined)
151
+ fail('receipt_storage_unsupported');
152
+ try {
153
+ mkdirSync(path, { mode: 0o700 });
154
+ }
155
+ catch (error) {
156
+ if (error.code !== 'EEXIST')
157
+ throw error;
158
+ }
159
+ privateStat(path, true);
160
+ // Even an old unmanaged ledger is left untouched. Partial initialization is
161
+ // retained as unavailable evidence, never automatically repaired or removed.
162
+ const entries = opendirSync(path);
163
+ try {
164
+ if (entries.readSync() !== null)
165
+ fail('receipt_state_exists');
166
+ }
167
+ finally {
168
+ entries.closeSync();
169
+ }
170
+ const lockPath = join(path, 'collector.lock');
171
+ let fd;
172
+ try {
173
+ fd = openSync(lockPath, constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | flags, 0o600);
174
+ }
175
+ catch {
176
+ fail('receipt_state_exists');
177
+ }
178
+ try {
179
+ locks().flockSync(fd, 'exnb');
180
+ fsyncSync(fd);
181
+ const key = randomBytes(32), epoch = randomUUID();
182
+ createPrivate(join(path, 'ledger.key'), key);
183
+ const data = { version: 2, epoch, keyId: receiptDigest(key), quarantined: false, records: {} };
184
+ createPrivate(join(path, 'ledger.json'), Buffer.from(JSON.stringify({ digest: receiptDigest(JSON.stringify(data)), data })));
185
+ createPrivate(join(path, 'managed.json'), Buffer.from(JSON.stringify({ version: 2, ledgerEpoch: epoch, endpointSelector })));
186
+ syncDirectory(path);
187
+ return { ledgerEpoch: epoch, storage: 'private_posix', managedVersion: 2 };
188
+ }
189
+ finally {
190
+ try {
191
+ locks().flockSync(fd, 'un');
192
+ }
193
+ finally {
194
+ closeSync(fd);
195
+ }
196
+ }
197
+ }
198
+ assertOwner() {
199
+ if (this.fd === undefined || this.poisoned)
200
+ fail('receipt_collector_closed');
201
+ if (directoryIdentity(privateStat(this.path, true)) !== this.directoryEvidence ||
202
+ identity(privateStat(join(this.path, 'collector.lock'), false)) !== this.lockEvidence ||
203
+ identity(fstatSync(this.fd, { bigint: true })) !== this.lockEvidence ||
204
+ identity(privateStat(join(this.path, 'managed.json'), false)) !== this.markerEvidence ||
205
+ identity(privateStat(join(this.path, 'ledger.key'), false)) !== this.keyEvidence)
206
+ fail('receipt_storage_untrusted');
207
+ }
208
+ read() {
209
+ this.assertOwner();
210
+ const content = readPrivate(join(this.path, 'ledger.json'), HANDOFF_LIMITS.journal);
211
+ try {
212
+ const wrapper = closed(parseStrictJson(content.bytes, { scope: 'outer', maxBytes: HANDOFF_LIMITS.journal }), ['digest', 'data']);
213
+ if (typeof wrapper.digest !== 'string' || wrapper.digest !== receiptDigest(JSON.stringify(wrapper.data)))
214
+ fail('receipt_history_corrupt');
215
+ const data = closed(wrapper.data, ['version', 'epoch', 'keyId', 'quarantined', 'records']);
216
+ if (data.version !== 2 || data.epoch !== this.marker.ledgerEpoch || data.keyId !== receiptDigest(this.key))
217
+ fail('receipt_history_corrupt');
218
+ this.stateEvidence = content.evidence;
219
+ return data;
220
+ }
221
+ catch {
222
+ fail('receipt_history_corrupt');
223
+ }
224
+ }
225
+ assertUnchanged() {
226
+ this.assertOwner();
227
+ if (!this.stateEvidence || identity(privateStat(join(this.path, 'ledger.json'), false)) !== this.stateEvidence)
228
+ fail('receipt_history_changed');
229
+ }
230
+ sealDigest(value, epoch, id) {
231
+ if (!/^[a-f0-9]{64}$/.test(value))
232
+ fail('receipt_history_corrupt');
233
+ const nonce = randomBytes(12), cipher = createCipheriv('aes-256-gcm', this.key, nonce);
234
+ cipher.setAAD(Buffer.from(JSON.stringify(['receipt-binding-v2', epoch, id])));
235
+ const bytes = Buffer.concat([cipher.update(Buffer.from(value, 'hex')), cipher.final()]);
236
+ return `sealed-v2:${nonce.toString('hex')}:${bytes.toString('hex')}:${cipher.getAuthTag().toString('hex')}`;
237
+ }
238
+ openDigest(value, epoch, id) {
239
+ try {
240
+ if (typeof value !== 'string' || !/^sealed-v2:[a-f0-9]{24}:[a-f0-9]{64}:[a-f0-9]{32}$/.test(value))
241
+ fail('receipt_history_corrupt');
242
+ const [, nonce, bytes, tag] = value.split(':');
243
+ const cipher = createDecipheriv('aes-256-gcm', this.key, Buffer.from(nonce, 'hex'));
244
+ cipher.setAAD(Buffer.from(JSON.stringify(['receipt-binding-v2', epoch, id])));
245
+ cipher.setAuthTag(Buffer.from(tag, 'hex'));
246
+ return Buffer.concat([cipher.update(Buffer.from(bytes, 'hex')), cipher.final()]).toString('hex');
247
+ }
248
+ catch {
249
+ fail('receipt_history_corrupt');
250
+ }
251
+ }
252
+ write(data) {
253
+ this.assertUnchanged();
254
+ const text = Buffer.from(JSON.stringify({ digest: receiptDigest(JSON.stringify(data)), data }));
255
+ if (text.byteLength > HANDOFF_LIMITS.journal)
256
+ fail('receipt_ledger_full');
257
+ const temporary = join(this.path, `.receipt-ledger-${randomUUID()}.tmp`);
258
+ try {
259
+ createPrivate(temporary, text);
260
+ this.assertUnchanged();
261
+ renameSync(temporary, join(this.path, 'ledger.json'));
262
+ syncDirectory(this.path);
263
+ this.stateEvidence = identity(privateStat(join(this.path, 'ledger.json'), false));
264
+ this.assertOwner();
265
+ }
266
+ catch (error) {
267
+ // A sync failure can follow rename; do not claim rollback or allow another
268
+ // command to extend authority from uncertain durable state in this owner.
269
+ this.poisoned = true;
270
+ throw error;
271
+ }
272
+ }
273
+ close() {
274
+ const fd = this.fd;
275
+ this.fd = undefined;
276
+ this.key.fill(0);
277
+ if (fd !== undefined) {
278
+ try {
279
+ locks().flockSync(fd, 'un');
280
+ }
281
+ finally {
282
+ closeSync(fd);
283
+ }
284
+ }
285
+ }
286
+ }
package/dist/replies.js CHANGED
@@ -20,7 +20,9 @@ export function sender() {
20
20
  const pid = /(\d+)\.sock$/.exec(socket)?.[1];
21
21
  let rows = [];
22
22
  try {
23
- rows = claude(true).sessions;
23
+ const found = claude(true);
24
+ if (found.discovery.claude.status === 'ok')
25
+ rows = found.sessions;
24
26
  }
25
27
  catch {
26
28
  rows = [];
package/dist/send.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type ClaudeReceiptProvenance } from './discovery.js';
1
2
  import { UnknownOutcome } from './process.js';
2
3
  import { type HomeResolution } from './writer.js';
3
4
  export type SendContext = {
@@ -15,8 +16,10 @@ export type CodexStorageGuard = {
15
16
  finalCheck: (ownedAppServer?: boolean) => void;
16
17
  };
17
18
  export type SendHooks = {
18
- resolved: (context: SendContext, snapshot: Record<string, unknown>) => Promise<string | void> | string | void;
19
+ resolved: (context: SendContext, snapshot: Record<string, unknown>, provenance?: ClaudeReceiptProvenance) => Promise<string | void> | string | void;
20
+ privateReceiptContext?: true;
19
21
  beforeEffect?: () => Promise<void> | void;
22
+ beforeWrite?: () => void;
20
23
  timeoutMs?: () => number;
21
24
  codexRoute?: () => 'ordinary' | 'owned_app_server';
22
25
  submitCodex?: (context: SendContext, message: string, storage: CodexStorageGuard) => Promise<{
@@ -39,5 +42,5 @@ export declare class CodexUnknownOutcome extends UnknownOutcome {
39
42
  }
40
43
  export declare function queueId(stdout: string, id: string): string | undefined;
41
44
  export declare function checkMessage(text: string, codex?: boolean): void;
42
- export declare function postSocket(path: string, text: string, timeout?: number): Promise<void>;
45
+ export declare function postSocket(path: string, text: string, timeout?: number, beforeWrite?: () => void): Promise<void>;
43
46
  export declare function send(options: SendOptions): Promise<Record<string, unknown>>;
package/dist/send.js CHANGED
@@ -1,10 +1,8 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { casefold } from './casefold.js';
3
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';
7
- import { claude, Refusal } from './discovery.js';
4
+ import { lstatSync } from 'node:fs';
5
+ import { claude, claudeSelectionIdentity, claudeReceiptProvenance, revalidateClaudeInventory, Refusal } from './discovery.js';
8
6
  import { classifyCodexStorage, codexConsumerCwd, codexConsumerSnapshotSync, codexStoragePin, codexWriterCwd, codexWriterStorage, storageDiagnostic } from './codex-storage.js';
9
7
  import { executable, run, UnknownOutcome } from './process.js';
10
8
  import { HomeRefusal, resolveWriter, revalidateWriter, uuid } from './writer.js';
@@ -27,7 +25,7 @@ export function checkMessage(text, codex = false) {
27
25
  (codex && Buffer.byteLength(text, 'utf8') > 32768))
28
26
  throw new Refusal('invalid_message', 2);
29
27
  }
30
- export async function postSocket(path, text, timeout) {
28
+ export async function postSocket(path, text, timeout, beforeWrite) {
31
29
  return new Promise((resolve, reject) => {
32
30
  let attempted = false, finished = false;
33
31
  const startedAt = performance.now();
@@ -40,12 +38,21 @@ export async function postSocket(path, text, timeout) {
40
38
  clearTimeout(timer);
41
39
  socket.destroy();
42
40
  if (error)
43
- reject(attempted ? new UnknownOutcome() : new Refusal('inbox_unreachable', 1));
41
+ reject(attempted ? new UnknownOutcome() : error instanceof Refusal ? error : new Refusal('inbox_unreachable', 1));
44
42
  else
45
43
  resolve();
46
44
  };
47
45
  socket.on('error', error => finish(error));
48
46
  socket.once('connect', () => {
47
+ if (finished)
48
+ return;
49
+ try {
50
+ beforeWrite?.();
51
+ }
52
+ catch (error) {
53
+ finish(error instanceof Error ? error : new Error('before_write_refused'));
54
+ return;
55
+ }
49
56
  attempted = true;
50
57
  socket.end(JSON.stringify({ type: 'user', message: { role: 'user', content: text } }) + '\n', () => {
51
58
  // Write completion is submission only, never consumption. Match Python's drain window.
@@ -57,41 +64,6 @@ export async function postSocket(path, text, timeout) {
57
64
  });
58
65
  });
59
66
  }
60
- // A private continuity fingerprint, not proof of a native incarnation. Do not
61
- // read or persist registry contents (which can include authentication material).
62
- function claudeBindingIdentity(row) {
63
- const stable = (s) => [s.dev, s.ino, s.uid, s.size, s.mtimeNs, s.ctimeNs, s.birthtimeNs].map(String);
64
- const same = (a, b) => JSON.stringify(stable(a)) === JSON.stringify(stable(b));
65
- const directory = process.env.CLAUDE_CONFIG_DIR || process.env.ANTHROPIC_CONFIG_DIR || join(homedir(), '.claude');
66
- const path = join(directory, 'sessions', String(row.pid) + '.json');
67
- try {
68
- const before = lstatSync(path, { bigint: true });
69
- if (!before.isFile() || before.size > 1024n * 1024n)
70
- throw new Error();
71
- const fd = openSync(path, constants.O_RDONLY | (process.platform === 'win32' ? 0 : constants.O_NOFOLLOW | constants.O_NONBLOCK));
72
- let metadata;
73
- try {
74
- const opened = fstatSync(fd, { bigint: true });
75
- if (!opened.isFile() || !same(before, opened) || !same(opened, lstatSync(path, { bigint: true })))
76
- throw new Error();
77
- metadata = stable(opened);
78
- }
79
- finally {
80
- closeSync(fd);
81
- }
82
- let socket = null;
83
- if (process.platform !== 'win32') {
84
- const file = lstatSync(String(row.socket), { bigint: true });
85
- if (!file.isSocket())
86
- throw new Error();
87
- socket = stable(file);
88
- }
89
- return createHash('sha256').update(JSON.stringify({ pid: row.pid, name: row.name, socketPath: row.socket, metadata, socket })).digest('hex');
90
- }
91
- catch {
92
- throw new Refusal('target_changed', 1);
93
- }
94
- }
95
67
  export async function send(options) {
96
68
  checkMessage(options.message, options.to.startsWith('codex:'));
97
69
  const base = { ok: true, submitted: !options.dryRun, consumptionConfirmed: false,
@@ -279,7 +251,10 @@ export async function send(options) {
279
251
  if (!target)
280
252
  throw new Refusal('no_reachable_target');
281
253
  const select = () => {
282
- const rows = claude(false).sessions;
254
+ const inventory = claude(false);
255
+ if (inventory.discovery.claude.status !== 'ok')
256
+ throw new Refusal('claude_discovery_incomplete', 1);
257
+ const rows = inventory.sessions;
283
258
  const matches = rows.filter(r => /^\d+$/.test(target) ? r.pid === Number(target) :
284
259
  typeof r.name === 'string' && casefold(r.name) === casefold(target));
285
260
  if (matches.length !== 1)
@@ -287,28 +262,38 @@ export async function send(options) {
287
262
  return matches[0];
288
263
  };
289
264
  const row = select();
290
- const identity = options.hooks ? claudeBindingIdentity(row) : undefined;
265
+ const identity = claudeSelectionIdentity(row);
291
266
  const result = { ...base, target: { agent: 'claude', pid: row.pid, name: row.name }, status: options.dryRun ? 'validated' : 'posted' };
292
267
  if (options.hooks) {
293
268
  // Existing POSIX Claude discovery proves PID/socket reachability, not a
294
269
  // restart-safe native incarnation. Do not manufacture a generation.
295
- const body = await options.hooks.resolved({ agent: 'claude', target: String(row.pid), generation: null, writerIdentity: identity }, result);
270
+ const body = await options.hooks.resolved({ agent: 'claude', target: String(row.pid), generation: null, writerIdentity: identity }, result, options.hooks.privateReceiptContext && process.platform !== 'win32' ? claudeReceiptProvenance(row) : undefined);
296
271
  if (body !== undefined) {
297
272
  checkMessage(body);
298
273
  options = { ...options, message: body };
299
274
  result.chars = [...body].length;
300
275
  }
301
276
  }
277
+ const finalCheck = () => {
278
+ const rechecked = select();
279
+ if (row.pid !== rechecked.pid || row.socket !== rechecked.socket ||
280
+ claudeSelectionIdentity(row) !== identity || claudeSelectionIdentity(rechecked) !== identity)
281
+ throw new Refusal('target_changed', 1);
282
+ revalidateClaudeInventory(row, rechecked);
283
+ };
284
+ finalCheck();
302
285
  if (options.dryRun)
303
286
  return result;
304
- const rechecked = select();
305
- if (row.pid !== rechecked.pid || row.socket !== rechecked.socket ||
306
- (identity !== undefined && claudeBindingIdentity(rechecked) !== identity))
307
- throw new Refusal('target_changed', 1);
308
287
  await options.hooks?.beforeEffect?.();
288
+ const remaining = options.hooks?.timeoutMs?.();
289
+ const cutoff = remaining === undefined ? undefined : performance.now() + remaining;
290
+ finalCheck();
291
+ const timeout = cutoff === undefined ? undefined : Math.floor(cutoff - performance.now());
292
+ if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 1))
293
+ throw new Refusal('deadline_before_effect', 1);
309
294
  if (process.platform === 'win32')
310
295
  await postWindowsPipe(String(row.socket), Number(row.pid), options.message);
311
296
  else
312
- await postSocket(String(row.socket), options.message, options.hooks?.timeoutMs?.());
297
+ await postSocket(String(row.socket), options.message, timeout, options.hooks?.beforeWrite);
313
298
  return result;
314
299
  }
@@ -9,8 +9,8 @@ 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.5.2 release row
13
- // carries forward only the four exact profiles accepted by public 0.5.1.
12
+ // Preserve each published runtime/profile result. The 0.6.1 preparation row
13
+ // carries forward only the four exact profiles accepted by public 0.6.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 = {
@@ -19,7 +19,9 @@ const matrix = {
19
19
  '0.4.0': ['0.1.0', '0.2.0', '0.2.1', '0.3.0'],
20
20
  '0.5.0': ['0.1.0', '0.2.0', '0.2.1', '0.3.0'],
21
21
  '0.5.1': ['0.1.0', '0.2.0', '0.2.1', '0.3.0'],
22
- '0.5.2': ['0.1.0', '0.2.0', '0.2.1', '0.3.0']
22
+ '0.5.2': ['0.1.0', '0.2.0', '0.2.1', '0.3.0'],
23
+ '0.6.0': ['0.1.0', '0.2.0', '0.2.1', '0.3.0'],
24
+ '0.6.1': ['0.1.0', '0.2.0', '0.2.1', '0.3.0']
23
25
  };
24
26
  const profiles = {
25
27
  '0.1.0': ['0.1.0', 'typescript', '0.1.0', '0.1.0', 'probe-help'],
package/docs/api.md CHANGED
@@ -1,18 +1,18 @@
1
1
  # API reference
2
2
 
3
- This reference describes source/package version **0.5.2**. Check registry availability and review the selected release before installation. Dated release evidence is recorded in [VALIDATION.md](../VALIDATION.md); before publication use a reviewed source artifact.
3
+ This reference describes source/package version **0.6.1**. Check registry availability and review the selected release before installation. Dated release evidence is recorded in [VALIDATION.md](../VALIDATION.md); before publication use a reviewed source artifact.
4
4
 
5
5
  [Back to README](../README.md) · [User guide](guide.md)
6
6
 
7
7
  The package exposes a small ESM API with TypeScript declarations. Install it
8
- locally with `npm install --ignore-scripts session-peer@0.5.2` before importing it.
8
+ locally with `npm install --ignore-scripts session-peer@0.6.1` before importing it.
9
9
  Importing the package does not execute the CLI or submit a message.
10
10
 
11
11
  ```js
12
12
  import { VERSION, VERSION_LINE, reply, envelope } from 'session-peer';
13
13
 
14
- console.log(VERSION); // 0.5.2
15
- console.log(VERSION_LINE); // session-peer 0.5.2 (typescript)
14
+ console.log(VERSION); // 0.6.1
15
+ console.log(VERSION_LINE); // session-peer 0.6.1 (typescript)
16
16
  const address = 'session-peer://v1/reply?agent=claude&session=12345&transport=local';
17
17
  console.log(reply(address)); // { to: '12345' }
18
18
  console.log(envelope('Please review and reply.', true, address));
@@ -214,7 +214,7 @@ message/transcript scan manufactures ACK. Ordinary generated Reply-To stays v1.
214
214
 
215
215
  POSIX opt-in `send --host HOST` performs an exact-version preflight and a
216
216
  no-effect preparation before one destination-side send. Both ends must contain
217
- the same reviewed 0.5.2 implementation. This workflow was introduced in
217
+ the same reviewed 0.6.1 implementation. This workflow was introduced in
218
218
  0.4.0; a 0.3.x banner does not establish the capability. Initialize the destination's private ledger explicitly; no command
219
219
  auto-installs a handler or initializes missing history. The origin does not
220
220
  create a local receipt collector. Reconcile with `handoff status`/`wait` on the
@@ -316,7 +316,7 @@ requested evidence goal. After any possible RPC write, no legacy fallback or
316
316
  second submission occurs.
317
317
 
318
318
  Selection is by the exact host platform/architecture and native version.
319
- The 0.5.2 source records a Linux arm64 Codex 0.162.1 candidate (pinned musl
319
+ The 0.6.1 source records a Linux arm64 Codex 0.162.1 candidate (pinned musl
320
320
  executable, procfs storage binding, `/proc/locks` writer-owner check) but does
321
321
  not activate it. Linux and any other unlisted platform/version have no
322
322
  profile, so required delivery refuses before effect and best-effort uses the
@@ -396,7 +396,7 @@ a completed milestone. Exact evidence and limits are in [VALIDATION](../VALIDATI
396
396
 
397
397
  ## 0.4.0 implementation scope
398
398
 
399
- The 0.5.2 source preserves this supported handoff scope; its Linux and Windows
399
+ The 0.6.1 source preserves this supported handoff scope; its Linux and Windows
400
400
  groundwork does not enable additional platform or ACK support.
401
401
 
402
402
  The 0.4.0 implementation includes the qualified macOS arm64 observer and explicit
@@ -407,3 +407,28 @@ voluntary receipt producer/authenticated collector bootstrap [#132](https://gith
407
407
  are future extensions. An automatic collector would still require an explicit
408
408
  receiver receipt; it must never infer ACK from messages or turn completion.
409
409
  Unsupported required goals refuse before effect; no post-attempt fallback or resend.
410
+
411
+ ## Explicit local receipt bootstrap (source implementation)
412
+
413
+ The `receipt` owner commands and `send --receipt-collector SOCKET` select a local, manually operated receipt route. They do not start services, discover alternate collectors, wake a session, answer an approval or resend a native message. Read the [operator guide](guide.md#explicit-local-receipts) before supplying private receipt input.
414
+
415
+ - `receipt init` creates a fresh managed format-2 store. Existing unmanaged format-1 history is not migrated or adopted. New legacy owner commands refuse a managed context; managed status and waits require the live collector.
416
+ - `receipt serve` is a foreground process with a single mutation and monotonic-clock owner. A second owner refuses. Unexpected state/key/endpoint replacement is not repaired. Cleanup may be unconfirmed; that does not authorize removal of an unrelated path.
417
+ - `receipt respond --receipt -` accepts only a bounded private receipt frame on stdin, through the explicitly selected private endpoint. A successful invocation records authenticated receipt evidence only; it cannot send a message. Never put capability data in argv, environment, URI, shell command text or public output.
418
+ - The generic CLI envelope stays `schemaVersion:1`. Codex's nested handoff/receipt stays v1 with the original non-null native generation. Claude uses a separate nested handoff/receipt v2 with `targetGeneration:null` and `receiptContext:{kind:"delegated_context",id:UUID}`. A v1 validator must reject that new scope rather than synthesizing a generation or downgrading it.
419
+ - `token_possession` means delegated receipt authority, not native/model identity, consumption, completion or responsibility acceptance. Existing `operator_confirmed` evidence remains a separate manual assurance. The intended recipient's native queue/history may retain delegated authority.
420
+ - Codex delegation uses only the qualified owned RPC route with private stdin. A token-bearing body is never passed through a native `--message` argument or a legacy queue fallback. Unsupported required ACK refuses before effect. Best-effort unsupported bootstrap can retain ordinary submission facts without minting an unused token.
421
+ - The original ACK operation is opened before the effect fence and uses the original total budget. A fast authenticated receipt can occupy one reserved candidate slot until positive native submission is recorded. Unknown/refused outcomes cannot be promoted by that receipt. ACK eligibility is classified through the collector's serialized transition; it never backdates an ACK or rewrites a terminal timeout.
422
+ - Each independent wait has its own immutable operation ID/deadline. Polling does not open another wait, extend authority or submit native input. A fresh collector cannot revive unused old-clock authority. Committed receipts and terminal waits are retained.
423
+
424
+ IPC is separately versioned and limited to the closed receipt operations described in the [reviewed design](https://github.com/abruption/session-peer-ts/blob/d922d6e20345f10b914ee9cf4da40476fd044f5d/docs/design/receipt-bootstrap.md). Request/response frames are at most 16,384 bytes including LF; each raw private receipt is at most 4,096 bytes. The collector admits at most 16 live connections, with finite per-read/write and total exchange budgets. Unknown post-attempt responses never authorize automatic retry. These bounds do not promise a deadline for arbitrary kernel-blocked filesystem I/O or protect against a hostile same-user writer.
425
+
426
+ Windows managed storage and reverse-SSH receipt collection remain unsupported. Existing native observation qualification remains unchanged. OS/IPC fixtures, synthetic native transports and actual live-agent receipts are separate evidence categories; this source description is not a release or live-model qualification claim.
427
+
428
+ ### Original-budget IPC 2 and retained-context limits
429
+
430
+ Private IPC 2 `hello.clockReferenceMs` is an opaque collector monotonic reference. A client captures its remaining total milliseconds after that reply and echoes the fixed reference/span in `wait-open`; the actor anchors the original cutoff to the earlier reference. Network, preparation and mint latency cannot start a renewed wait budget. This does not depend on clocks sharing an origin or on UTC comparisons. Public CLI/receipt/handoff version namespaces are unchanged by the private IPC revision.
431
+
432
+ Explicit revoke/quarantine rejects further receipt presentations, including duplicates, while owner status retains committed ACK evidence. TTL expiry alone does not erase the authenticated identical-receipt retrieval exception. A late flag refers to the first recorded wait; a later wait cannot renew it. Context limits apply jointly: the current conservative 64-KiB retained reservation can fill a 32-MiB store at about 511 small intents before the separate 10,000-record upper bound. There is no automatic retirement or deletion. A full-store refusal never authorizes dropping history or resending.
433
+
434
+ Before a managed intent is established, bootstrap refusal can have no handoff IDs; the client does not fabricate an epoch/correlation/operation for unavailable storage. Once an operation is established, its original verified IDs/deadline and independently known native facts are preserved on later failures without inventing a durable terminal result.
@@ -2,6 +2,54 @@
2
2
 
3
3
  This document retains the original TS source proposal and dated design review for [#118](https://github.com/abruption/session-peer-ts/issues/118), based on the companion [Draft #20 at `963c3d7`](https://github.com/abruption/session-peer-skill/blob/963c3d748a11b1164013ee26c9c0ef285c52b285/docs/typescript-compatibility.md). Companion [design acceptance at `699a325`](https://github.com/abruption/session-peer-skill/blob/699a3251830c30c62d0f812363faf4d0eb0c8e0c/docs/typescript-compatibility.md) records the full static review of the exact candidates below on 2026-10-09. This design-only acceptance does not authorize runtime merge/release, successor skill metadata/publication, installation or pin changes, content authenticity, or live delivery support.
4
4
 
5
+ ## 0.6.1 finite row — 2026-11-09 KST release preparation
6
+
7
+ The candidate explicitly carries forward the four exact profiles accepted by
8
+ public 0.6.0: skill 0.1.0, 0.2.0, 0.2.1 and 0.3.0 with unchanged metadata.
9
+ Compiled default, explicit `undefined`, explicit 0.6.1 and outer `inspectSkill`
10
+ use this finite row. Matching metadata remains exactly
11
+ `compatible / skill_contract_compatible / metadata_only`; changed profiles and
12
+ unreviewed runtime identities such as 0.6.2 or 0.7.0 remain incompatible.
13
+ Malformed 0.6.1-preview.1 and 00.6.1 remain
14
+ `unknown / skill_metadata_missing` with no `verification` property.
15
+
16
+ All historical rows, parser/reader behavior and immutable complete-skill
17
+ fixtures remain unchanged. This row does not publish/install a skill, change
18
+ its independent source pin, authenticate content or qualify native delivery,
19
+ receipt/ACK support or a platform. The dated 0.6.0 section below records its
20
+ then-unreviewed 0.6.1 rejection; that historical artifact is not rewritten.
21
+ A new helper accepting an explicit runtime string is not execution of an older
22
+ published CLI. This section records candidate preparation, not public 0.6.1.
23
+
24
+ ## 0.6.0 finite row — 2026-11-03 KST release preparation
25
+
26
+ The 0.6.0 source preparation adds one explicit runtime row accepting exactly the
27
+ four existing profiles: skill 0.1.0, 0.2.0, 0.2.1 and 0.3.0, with their existing
28
+ metadata values. Compiled default, explicit `undefined`, explicit 0.6.0 and outer
29
+ `inspectSkill` use this finite row. Matching metadata returns exactly
30
+ `compatible / skill_contract_compatible / metadata_only`; changed profiles and
31
+ unreviewed stable runtime identities such as 0.5.3, 0.6.1 and 0.7.0 remain
32
+ incompatible. Malformed identities, including 0.6.0-preview.1 and 00.6.0, remain
33
+ `unknown / skill_metadata_missing` with the `verification` property absent.
34
+ All historical matrix rows, exact profile values, grammar and bounded reader
35
+ behavior remain unchanged.
36
+
37
+ The installation guidance retains independently published skill 0.2.1 source
38
+ `0f494cabd05901c03161dc91792dcf89f8e96631`, 13,996 raw UTF-8 bytes, SHA-256
39
+ `8c3520f95e0d6807303be96bfa06df69887ddaf76be05f1905505d0a956820c3`.
40
+ This row neither publishes a new skill nor changes its installation pin, body,
41
+ minimum/full metadata or permissions. In particular it does not establish that
42
+ an older skill documents new runtime receipt operations. Optional operations
43
+ still require the selected runtime's help, platform and separately validated
44
+ route. Metadata compatibility is not content authentication, authorization,
45
+ recipient identity, delivery or ACK evidence.
46
+
47
+ This section records source preparation only, not publication or completed
48
+ receipt/native qualification. The dated 0.5.2 checkpoint below retains that
49
+ historical validator's rejection of then-unreviewed 0.6.0; supplying 0.6.0 to the
50
+ new helper is not execution of the old published 0.5.2 validator. No historical
51
+ artifact or immutable complete-skill fixture is rewritten.
52
+
5
53
  ## 0.5.2 finite row — 2026-10-30 KST release preparation
6
54
 
7
55
  The 0.5.2 source explicitly accepts exactly the four profiles accepted by public