session-peer 0.5.1 → 0.6.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.
- package/CONTRIBUTING.md +26 -0
- package/PARITY.md +134 -4
- package/README.ja.md +12 -8
- package/README.ko.md +12 -8
- package/README.md +12 -8
- package/README.zh-CN.md +12 -8
- package/RELEASING.md +142 -0
- package/VALIDATION.md +154 -2
- package/dist/app-server.d.ts +10 -2
- package/dist/app-server.js +115 -53
- package/dist/cli.js +54 -4
- package/dist/codex-storage.d.ts +46 -0
- package/dist/codex-storage.js +447 -0
- package/dist/diagnostics.js +23 -102
- package/dist/discovery.d.ts +32 -1
- package/dist/discovery.js +405 -89
- package/dist/handoff-operations.js +40 -10
- package/dist/help.js +18 -2
- package/dist/macos-acl.d.ts +10 -0
- package/dist/macos-acl.js +75 -0
- package/dist/output.js +6 -1
- package/dist/process.d.ts +1 -0
- package/dist/process.js +1 -1
- package/dist/protocol.d.ts +2 -2
- package/dist/protocol.js +1 -1
- package/dist/receipt-collector.d.ts +12 -0
- package/dist/receipt-collector.js +283 -0
- package/dist/receipt-command.d.ts +10 -0
- package/dist/receipt-command.js +246 -0
- package/dist/receipt-producer.d.ts +7 -0
- package/dist/receipt-producer.js +107 -0
- package/dist/receipt-protocol.d.ts +219 -0
- package/dist/receipt-protocol.js +374 -0
- package/dist/receipt-send.d.ts +26 -0
- package/dist/receipt-send.js +375 -0
- package/dist/receipt-state.d.ts +89 -0
- package/dist/receipt-state.js +503 -0
- package/dist/receipt-store.d.ts +32 -0
- package/dist/receipt-store.js +286 -0
- package/dist/replies.js +3 -1
- package/dist/send.d.ts +14 -3
- package/dist/send.js +165 -63
- package/dist/skill-metadata.js +5 -3
- package/docs/api.md +155 -7
- package/docs/design/remote-deployment.md +8 -0
- package/docs/design/typescript-skill-compatibility.md +50 -0
- package/docs/guide.ja.md +47 -15
- package/docs/guide.ko.md +50 -19
- package/docs/guide.md +48 -16
- package/docs/guide.zh-CN.md +47 -15
- package/docs/shorthand.md +1 -1
- package/package.json +5 -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
|
-
|
|
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 = {
|
|
@@ -6,12 +7,22 @@ export type SendContext = {
|
|
|
6
7
|
home?: string;
|
|
7
8
|
generation: string | null;
|
|
8
9
|
writerIdentity?: string;
|
|
10
|
+
readonly binary?: string;
|
|
11
|
+
};
|
|
12
|
+
export type CodexStorageGuard = {
|
|
13
|
+
readonly binary: string;
|
|
14
|
+
readonly cwd: string;
|
|
15
|
+
revalidate: (ownedAppServer?: boolean) => Promise<void>;
|
|
16
|
+
finalCheck: (ownedAppServer?: boolean) => void;
|
|
9
17
|
};
|
|
10
18
|
export type SendHooks = {
|
|
11
|
-
resolved: (context: SendContext, snapshot: Record<string, unknown
|
|
19
|
+
resolved: (context: SendContext, snapshot: Record<string, unknown>, provenance?: ClaudeReceiptProvenance) => Promise<string | void> | string | void;
|
|
20
|
+
privateReceiptContext?: true;
|
|
12
21
|
beforeEffect?: () => Promise<void> | void;
|
|
22
|
+
beforeWrite?: () => void;
|
|
13
23
|
timeoutMs?: () => number;
|
|
14
|
-
|
|
24
|
+
codexRoute?: () => 'ordinary' | 'owned_app_server';
|
|
25
|
+
submitCodex?: (context: SendContext, message: string, storage: CodexStorageGuard) => Promise<{
|
|
15
26
|
queueId?: string;
|
|
16
27
|
clientUserMessageId: string;
|
|
17
28
|
}>;
|
|
@@ -31,5 +42,5 @@ export declare class CodexUnknownOutcome extends UnknownOutcome {
|
|
|
31
42
|
}
|
|
32
43
|
export declare function queueId(stdout: string, id: string): string | undefined;
|
|
33
44
|
export declare function checkMessage(text: string, codex?: boolean): void;
|
|
34
|
-
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>;
|
|
35
46
|
export declare function send(options: SendOptions): Promise<Record<string, unknown>>;
|
package/dist/send.js
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { casefold } from './casefold.js';
|
|
3
3
|
import { createConnection } from 'node:net';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { claude, Refusal, sqliteHome } from './discovery.js';
|
|
4
|
+
import { lstatSync } from 'node:fs';
|
|
5
|
+
import { claude, claudeSelectionIdentity, claudeReceiptProvenance, revalidateClaudeInventory, Refusal } from './discovery.js';
|
|
6
|
+
import { classifyCodexStorage, codexConsumerCwd, codexConsumerSnapshotSync, codexStoragePin, codexWriterCwd, codexWriterStorage, storageDiagnostic } from './codex-storage.js';
|
|
8
7
|
import { executable, run, UnknownOutcome } from './process.js';
|
|
9
8
|
import { HomeRefusal, resolveWriter, revalidateWriter, uuid } from './writer.js';
|
|
10
9
|
import { postWindowsPipe } from './windows.js';
|
|
@@ -26,7 +25,7 @@ export function checkMessage(text, codex = false) {
|
|
|
26
25
|
(codex && Buffer.byteLength(text, 'utf8') > 32768))
|
|
27
26
|
throw new Refusal('invalid_message', 2);
|
|
28
27
|
}
|
|
29
|
-
export async function postSocket(path, text, timeout) {
|
|
28
|
+
export async function postSocket(path, text, timeout, beforeWrite) {
|
|
30
29
|
return new Promise((resolve, reject) => {
|
|
31
30
|
let attempted = false, finished = false;
|
|
32
31
|
const startedAt = performance.now();
|
|
@@ -39,12 +38,21 @@ export async function postSocket(path, text, timeout) {
|
|
|
39
38
|
clearTimeout(timer);
|
|
40
39
|
socket.destroy();
|
|
41
40
|
if (error)
|
|
42
|
-
reject(attempted ? new UnknownOutcome() : new Refusal('inbox_unreachable', 1));
|
|
41
|
+
reject(attempted ? new UnknownOutcome() : error instanceof Refusal ? error : new Refusal('inbox_unreachable', 1));
|
|
43
42
|
else
|
|
44
43
|
resolve();
|
|
45
44
|
};
|
|
46
45
|
socket.on('error', error => finish(error));
|
|
47
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
|
+
}
|
|
48
56
|
attempted = true;
|
|
49
57
|
socket.end(JSON.stringify({ type: 'user', message: { role: 'user', content: text } }) + '\n', () => {
|
|
50
58
|
// Write completion is submission only, never consumption. Match Python's drain window.
|
|
@@ -56,41 +64,6 @@ export async function postSocket(path, text, timeout) {
|
|
|
56
64
|
});
|
|
57
65
|
});
|
|
58
66
|
}
|
|
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
|
-
}
|
|
94
67
|
export async function send(options) {
|
|
95
68
|
checkMessage(options.message, options.to.startsWith('codex:'));
|
|
96
69
|
const base = { ok: true, submitted: !options.dryRun, consumptionConfirmed: false,
|
|
@@ -100,13 +73,62 @@ export async function send(options) {
|
|
|
100
73
|
if (!uuid(id))
|
|
101
74
|
throw new Refusal('codex_uuid_required');
|
|
102
75
|
const binary = executable(options.codexBin ?? 'codex');
|
|
76
|
+
const executableEvidence = () => {
|
|
77
|
+
try {
|
|
78
|
+
const info = lstatSync(binary, { bigint: true });
|
|
79
|
+
if (!info.isFile())
|
|
80
|
+
throw new Error();
|
|
81
|
+
return [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(':');
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
throw new Refusal('codex_storage_loader_unverifiable', 1);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
const binaryEvidence = executableEvidence();
|
|
103
88
|
const selection = await resolveWriter(options.home, id, options.allowInactive);
|
|
104
89
|
const { home } = selection;
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
throw new HomeRefusal(
|
|
90
|
+
if (!['darwin', 'linux'].includes(process.platform)) {
|
|
91
|
+
const platformStorage = classifyCodexStorage({ home });
|
|
92
|
+
throw new HomeRefusal(platformStorage.code, selection.resolution);
|
|
93
|
+
}
|
|
94
|
+
const refuseStorage = (check) => {
|
|
95
|
+
if (check.status !== 'classified')
|
|
96
|
+
throw new HomeRefusal(check.code, selection.resolution);
|
|
97
|
+
return check;
|
|
98
|
+
};
|
|
99
|
+
let consumerCwd;
|
|
100
|
+
try {
|
|
101
|
+
consumerCwd = await codexConsumerCwd(home, id);
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
throw new HomeRefusal('codex_consumer_context_unverifiable', selection.resolution);
|
|
105
|
+
}
|
|
106
|
+
let writerPid, writerCwd, selectedDatabase;
|
|
107
|
+
try {
|
|
108
|
+
const proof = JSON.parse(selection.evidence);
|
|
109
|
+
const selected = proof.fingerprints.find(item => item.home === home);
|
|
110
|
+
selectedDatabase = selected.database;
|
|
111
|
+
if (codexConsumerSnapshotSync(home, id).database !== selectedDatabase)
|
|
112
|
+
throw new Error();
|
|
113
|
+
writerPid = JSON.parse(selected.writer).pid;
|
|
114
|
+
if (writerPid !== undefined) {
|
|
115
|
+
writerCwd = codexWriterCwd(writerPid);
|
|
116
|
+
codexWriterStorage(writerPid, home);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
throw new HomeRefusal('codex_consumer_context_unverifiable', selection.resolution);
|
|
121
|
+
}
|
|
122
|
+
const consumerCwds = [consumerCwd, ...(writerCwd ? [writerCwd] : [])];
|
|
123
|
+
const queueCwd = process.cwd();
|
|
124
|
+
// Hooks may choose an owned app-server; that path binds its opened SQLite
|
|
125
|
+
// descriptors independently. Its fallback must revalidate the ordinary plan.
|
|
126
|
+
const provisionalOwned = !options.dryRun && Boolean(options.hooks?.submitCodex);
|
|
127
|
+
let ownedAppServer = provisionalOwned;
|
|
128
|
+
let storage = refuseStorage(classifyCodexStorage({ home, queueCwd, consumerCwds, ownedAppServer }));
|
|
108
129
|
const result = { ...base, target: { agent: 'codex', id }, codexHome: home,
|
|
109
|
-
status: options.dryRun ? 'validated' : 'queued', codexHomeResolution: selection.resolution
|
|
130
|
+
status: options.dryRun ? 'validated' : 'queued', codexHomeResolution: selection.resolution,
|
|
131
|
+
storage: storageDiagnostic(storage) };
|
|
110
132
|
let context;
|
|
111
133
|
if (options.hooks) {
|
|
112
134
|
// Bind the identity already captured by selection, not a second sample
|
|
@@ -118,7 +140,7 @@ export async function send(options) {
|
|
|
118
140
|
if (!identity)
|
|
119
141
|
throw new HomeRefusal('active_writer_unverified', selection.resolution);
|
|
120
142
|
const generation = live ? createHash('sha256').update(identity).digest('hex') : null;
|
|
121
|
-
context = { agent: 'codex', target: id, home, generation,
|
|
143
|
+
context = { agent: 'codex', target: id, home, generation, binary,
|
|
122
144
|
// Inactive evidence still binds a prepared intent across invocations. This
|
|
123
145
|
// private fingerprint is not a native incarnation or public generation.
|
|
124
146
|
writerIdentity: generation ?? createHash('sha256').update(JSON.stringify(selected)).digest('hex') };
|
|
@@ -129,24 +151,91 @@ export async function send(options) {
|
|
|
129
151
|
result.chars = [...body].length;
|
|
130
152
|
}
|
|
131
153
|
}
|
|
154
|
+
// Recheck the provisional evidence after asynchronous resolution, then
|
|
155
|
+
// classify the route actually selected by the handoff. Dry-run has no
|
|
156
|
+
// owned process/FD proof and always uses the ordinary metadata policy.
|
|
157
|
+
const actualOwned = !options.dryRun && Boolean(options.hooks?.submitCodex) &&
|
|
158
|
+
(options.hooks?.codexRoute ? options.hooks.codexRoute() === 'owned_app_server' : true);
|
|
159
|
+
const continuity = classifyCodexStorage({ home, queueCwd, consumerCwds, ownedAppServer: provisionalOwned });
|
|
160
|
+
result.storage = storageDiagnostic(continuity);
|
|
161
|
+
refuseStorage(continuity);
|
|
162
|
+
if (continuity.fingerprint !== storage.fingerprint)
|
|
163
|
+
throw new HomeRefusal('codex_storage_changed_before_queue', selection.resolution);
|
|
164
|
+
const actualStorage = classifyCodexStorage({ home, queueCwd, consumerCwds, ownedAppServer: actualOwned });
|
|
165
|
+
result.storage = storageDiagnostic(actualStorage);
|
|
166
|
+
storage = refuseStorage(actualStorage);
|
|
167
|
+
ownedAppServer = actualOwned;
|
|
132
168
|
if (options.dryRun)
|
|
133
169
|
return result;
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
170
|
+
// Diagnostic probe only on an effectful send. Doctor and dry-run never
|
|
171
|
+
// execute an agent binary. Exact tags qualify loader semantics, not delivery.
|
|
172
|
+
const inherited = Object.fromEntries(Object.entries(process.env).filter(([key]) => !['CODEX_SQLITE_HOME', 'CODEX_HOME'].includes(key.toUpperCase())));
|
|
173
|
+
const env = { ...inherited, CODEX_HOME: home, PWD: storage.queueCwd };
|
|
174
|
+
const version = await run(binary, ['--version'], { env, cwd: storage.queueCwd, timeout: Math.min(3000, options.hooks?.timeoutMs?.() ?? 3000), limit: 4096 });
|
|
175
|
+
const nativeVersion = !version.interrupted && version.code === 0 && /^codex-cli \d+\.\d+\.\d+\s*$/.test(version.stdout) ? version.stdout.trim().slice(10) : '';
|
|
176
|
+
const qualified = refuseStorage(classifyCodexStorage({ home, queueCwd, consumerCwds, ownedAppServer, version: nativeVersion }));
|
|
177
|
+
if (qualified.fingerprint !== storage.fingerprint)
|
|
178
|
+
throw new HomeRefusal('codex_storage_changed_before_queue', selection.resolution);
|
|
179
|
+
result.storage = storageDiagnostic(qualified);
|
|
180
|
+
const guard = Object.freeze({ binary, cwd: qualified.queueCwd, async revalidate(owned = ownedAppServer) {
|
|
181
|
+
await revalidateWriter(selection, options.home, id, options.allowInactive);
|
|
182
|
+
try {
|
|
183
|
+
await codexConsumerCwd(home, id);
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
throw new HomeRefusal('codex_consumer_context_unverifiable', selection.resolution);
|
|
187
|
+
}
|
|
188
|
+
guard.finalCheck(owned);
|
|
189
|
+
}, finalCheck(owned = ownedAppServer) {
|
|
190
|
+
const checkConsumer = () => {
|
|
191
|
+
try {
|
|
192
|
+
const current = codexConsumerSnapshotSync(home, id);
|
|
193
|
+
if (current.database !== selectedDatabase || current.cwd !== consumerCwd)
|
|
194
|
+
throw new Error();
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
throw new HomeRefusal('codex_storage_changed_before_queue', selection.resolution);
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
checkConsumer();
|
|
201
|
+
if (writerPid !== undefined) {
|
|
202
|
+
try {
|
|
203
|
+
if (codexWriterCwd(writerPid) !== writerCwd)
|
|
204
|
+
throw new Error();
|
|
205
|
+
codexWriterStorage(writerPid, home);
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
throw new HomeRefusal('codex_consumer_context_unverifiable', selection.resolution);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const current = refuseStorage(classifyCodexStorage({ home, queueCwd, consumerCwds, ownedAppServer, version: nativeVersion }));
|
|
212
|
+
if (current.fingerprint !== qualified.fingerprint)
|
|
213
|
+
throw new HomeRefusal('codex_storage_changed_before_queue', selection.resolution);
|
|
214
|
+
if (owned !== ownedAppServer)
|
|
215
|
+
refuseStorage(classifyCodexStorage({ home, queueCwd, consumerCwds, ownedAppServer: owned, version: nativeVersion }));
|
|
216
|
+
checkConsumer();
|
|
217
|
+
if (executableEvidence() !== binaryEvidence)
|
|
218
|
+
throw new HomeRefusal('codex_storage_loader_changed', selection.resolution);
|
|
219
|
+
} });
|
|
220
|
+
await guard.revalidate();
|
|
140
221
|
// `--message=` keeps a body starting with `-` from being parsed as an option.
|
|
141
222
|
// An inherited CODEX_SQLITE_HOME would queue outside the validated home.
|
|
142
223
|
// Windows environment names are case-insensitive.
|
|
143
224
|
if (options.hooks?.submitCodex) {
|
|
144
|
-
const receipt = await options.hooks.submitCodex(context, options.message);
|
|
225
|
+
const receipt = await options.hooks.submitCodex(context, options.message, guard);
|
|
145
226
|
return { ...result, ...(receipt.queueId === undefined ? {} : { queueId: receipt.queueId }) };
|
|
146
227
|
}
|
|
147
|
-
const inherited = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.toUpperCase() !== 'CODEX_SQLITE_HOME'));
|
|
148
228
|
await options.hooks?.beforeEffect?.();
|
|
149
|
-
|
|
229
|
+
await guard.revalidate();
|
|
230
|
+
// Capture a caller's remaining budget once, then charge the final sync I/O
|
|
231
|
+
// to that absolute cutoff without another callback or asynchronous gap.
|
|
232
|
+
const remaining = options.hooks?.timeoutMs?.();
|
|
233
|
+
const cutoff = remaining === undefined ? undefined : performance.now() + remaining;
|
|
234
|
+
guard.finalCheck();
|
|
235
|
+
const timeout = cutoff === undefined ? 30000 : Math.floor(cutoff - performance.now());
|
|
236
|
+
if (!Number.isFinite(timeout) || timeout < 1)
|
|
237
|
+
throw new HomeRefusal('deadline_before_effect', selection.resolution);
|
|
238
|
+
const done = await run(binary, ['queue', '--thread', id, `--message=${options.message}`, '-c', codexStoragePin(home)], { env, cwd: guard.cwd, timeout });
|
|
150
239
|
if (!done.spawned)
|
|
151
240
|
throw new HomeRefusal('native_spawn_failed', selection.resolution);
|
|
152
241
|
if (done.interrupted || done.code !== 0)
|
|
@@ -162,7 +251,10 @@ export async function send(options) {
|
|
|
162
251
|
if (!target)
|
|
163
252
|
throw new Refusal('no_reachable_target');
|
|
164
253
|
const select = () => {
|
|
165
|
-
const
|
|
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;
|
|
166
258
|
const matches = rows.filter(r => /^\d+$/.test(target) ? r.pid === Number(target) :
|
|
167
259
|
typeof r.name === 'string' && casefold(r.name) === casefold(target));
|
|
168
260
|
if (matches.length !== 1)
|
|
@@ -170,28 +262,38 @@ export async function send(options) {
|
|
|
170
262
|
return matches[0];
|
|
171
263
|
};
|
|
172
264
|
const row = select();
|
|
173
|
-
const identity =
|
|
265
|
+
const identity = claudeSelectionIdentity(row);
|
|
174
266
|
const result = { ...base, target: { agent: 'claude', pid: row.pid, name: row.name }, status: options.dryRun ? 'validated' : 'posted' };
|
|
175
267
|
if (options.hooks) {
|
|
176
268
|
// Existing POSIX Claude discovery proves PID/socket reachability, not a
|
|
177
269
|
// 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);
|
|
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);
|
|
179
271
|
if (body !== undefined) {
|
|
180
272
|
checkMessage(body);
|
|
181
273
|
options = { ...options, message: body };
|
|
182
274
|
result.chars = [...body].length;
|
|
183
275
|
}
|
|
184
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();
|
|
185
285
|
if (options.dryRun)
|
|
186
286
|
return result;
|
|
187
|
-
const rechecked = select();
|
|
188
|
-
if (row.pid !== rechecked.pid || row.socket !== rechecked.socket ||
|
|
189
|
-
(identity !== undefined && claudeBindingIdentity(rechecked) !== identity))
|
|
190
|
-
throw new Refusal('target_changed', 1);
|
|
191
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);
|
|
192
294
|
if (process.platform === 'win32')
|
|
193
295
|
await postWindowsPipe(String(row.socket), Number(row.pid), options.message);
|
|
194
296
|
else
|
|
195
|
-
await postSocket(String(row.socket), options.message, options.hooks?.
|
|
297
|
+
await postSocket(String(row.socket), options.message, timeout, options.hooks?.beforeWrite);
|
|
196
298
|
return result;
|
|
197
299
|
}
|