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.
- package/CONTRIBUTING.md +11 -5
- package/PARITY.md +20 -5
- package/README.ja.md +8 -8
- package/README.ko.md +8 -8
- package/README.md +8 -8
- package/README.zh-CN.md +8 -8
- package/RELEASING.md +116 -0
- package/VALIDATION.md +137 -1
- package/dist/cli.js +54 -4
- package/dist/diagnostics.js +17 -98
- package/dist/discovery.d.ts +32 -0
- package/dist/discovery.js +405 -68
- package/dist/handoff-operations.js +88 -34
- 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/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 +5 -2
- package/dist/send.js +34 -49
- package/dist/skill-metadata.js +5 -3
- package/docs/api.md +32 -7
- package/docs/design/typescript-skill-compatibility.md +48 -0
- package/docs/guide.ja.md +41 -15
- package/docs/guide.ko.md +43 -17
- package/docs/guide.md +42 -16
- package/docs/guide.zh-CN.md +41 -15
- package/docs/shorthand.md +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
// Explicit local receipt delegation. No import-time IO, collector startup or replay.
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { lstatSync, realpathSync } from 'node:fs';
|
|
4
|
+
import { hostname } from 'node:os';
|
|
5
|
+
import { dirname } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
8
|
+
import { nativeQueueCapability, nativeQueueOnce, AppServerFault } from './app-server.js';
|
|
9
|
+
import { Refusal } from './discovery.js';
|
|
10
|
+
import { HandoffBudget } from './handoff.js';
|
|
11
|
+
import { inspectMacosAcls } from './macos-acl.js';
|
|
12
|
+
import { currentPlatform, selectNativeProfile } from './native-profiles.js';
|
|
13
|
+
import { run, UnknownOutcome } from './process.js';
|
|
14
|
+
import { receiptEndpoint, receiptExchange } from './receipt-collector.js';
|
|
15
|
+
import { validateReceiptProducer } from './receipt-producer.js';
|
|
16
|
+
import { RECEIPT_PAIRS, validateReceiptBinding, validateManagedHandoff } from './receipt-protocol.js';
|
|
17
|
+
import { checkMessage, send } from './send.js';
|
|
18
|
+
class Unsupported extends Refusal {
|
|
19
|
+
constructor() { super('receipt_bootstrap_unsupported', 1); }
|
|
20
|
+
}
|
|
21
|
+
const digest = (value) => createHash('sha256').update(value).digest('hex');
|
|
22
|
+
const identity = (s) => [s.dev, s.ino, s.uid, s.mode, s.size, s.mtimeMs, s.ctimeMs, s.birthtimeMs].join(':');
|
|
23
|
+
function claudeAdmission(proof) {
|
|
24
|
+
const paths = [proof.registryDirectory, proof.registryRecordPath];
|
|
25
|
+
const inspect = () => {
|
|
26
|
+
const directory = lstatSync(paths[0]), record = lstatSync(paths[1]);
|
|
27
|
+
if (directory.isSymbolicLink() || !directory.isDirectory() || record.isSymbolicLink() || !record.isFile() ||
|
|
28
|
+
directory.uid !== process.getuid?.() || record.uid !== process.getuid?.() ||
|
|
29
|
+
((directory.mode | record.mode) & 0o022) !== 0 || realpathSync(paths[0]) !== paths[0] ||
|
|
30
|
+
realpathSync(paths[1]) !== paths[1] || dirname(paths[1]) !== paths[0] || digest(identity(record)) !== proof.registryIdentity)
|
|
31
|
+
throw new Refusal('receipt_registry_untrusted', 1);
|
|
32
|
+
return [identity(directory), identity(record)].join('/');
|
|
33
|
+
};
|
|
34
|
+
try {
|
|
35
|
+
const pinned = inspect();
|
|
36
|
+
const revalidate = () => {
|
|
37
|
+
if (inspect() !== pinned || (process.platform === 'darwin' && inspectMacosAcls(paths) !== 'clear') || inspect() !== pinned)
|
|
38
|
+
throw new Refusal('receipt_registry_untrusted', 1);
|
|
39
|
+
};
|
|
40
|
+
revalidate();
|
|
41
|
+
return revalidate;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
throw new Refusal('receipt_registry_untrusted', 1);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export async function managedReceiptSend(options, config, deps = {}) {
|
|
48
|
+
if ((config.requestAck !== undefined && typeof config.requestAck !== 'boolean') ||
|
|
49
|
+
(config.waitFor !== undefined && config.waitFor !== 'acknowledged'))
|
|
50
|
+
throw new Refusal('receipt_opt_in_required', 2);
|
|
51
|
+
if (!options.dryRun && config.requestAck !== true && config.waitFor !== 'acknowledged')
|
|
52
|
+
throw new Refusal('receipt_opt_in_required', 2);
|
|
53
|
+
const sourceSend = deps.send ?? send;
|
|
54
|
+
if (options.dryRun)
|
|
55
|
+
return { value: { ...await sourceSend({ ...options, hooks: undefined }), receiptBootstrap: { status: 'not_checked' } }, exitCode: 0 };
|
|
56
|
+
const budget = config.budget ?? new HandoffBudget(config.seconds ?? 30), exchange = deps.exchange ?? receiptExchange;
|
|
57
|
+
const endpoint = deps.endpoint ?? receiptEndpoint, probe = deps.run ?? run;
|
|
58
|
+
const required = config.waitFor === 'acknowledged';
|
|
59
|
+
let contextId = null, endpointIdentity, original;
|
|
60
|
+
let handoff, handle, operationId, operationDeadline;
|
|
61
|
+
let snapshot, knownNative;
|
|
62
|
+
let firstContext;
|
|
63
|
+
let waitBudget;
|
|
64
|
+
let prepared = false, fenced = false, stopped = false, stopSent = false;
|
|
65
|
+
let producer, revalidateTarget = () => { };
|
|
66
|
+
let queueScope, ownerArgs = [];
|
|
67
|
+
const timeout = () => { const remaining = Math.floor(budget.remainingMs()); if (remaining < 1)
|
|
68
|
+
throw new Refusal('deadline_before_effect', 1); return remaining; };
|
|
69
|
+
const rpc = async (op, body) => {
|
|
70
|
+
if (endpointIdentity !== undefined && endpoint(config.collector) !== endpointIdentity)
|
|
71
|
+
throw new Refusal('receipt_endpoint_changed', 1);
|
|
72
|
+
const response = await exchange(config.collector, contextId, op, body, timeout());
|
|
73
|
+
if (contextId !== null && response.collectorContextId !== contextId)
|
|
74
|
+
throw new Refusal('receipt_context_mismatch', 1);
|
|
75
|
+
if (!response.ok)
|
|
76
|
+
throw new Refusal(response.error, 1);
|
|
77
|
+
if ('handoff' in response.body) {
|
|
78
|
+
const h = validateManagedHandoff(response.body.handoff);
|
|
79
|
+
if (handle && (h.ledgerEpoch !== handle.ledgerEpoch || h.correlationId !== handle.correlationId ||
|
|
80
|
+
h.schemaVersion !== (handle.receiptContextId === null ? 1 : 2) ||
|
|
81
|
+
(h.schemaVersion === 2 && h.receiptContext.id !== handle.receiptContextId) || h.targetGeneration !== original?.generation))
|
|
82
|
+
throw new Refusal('receipt_context_mismatch', 1);
|
|
83
|
+
if (operationId && (op === 'wait-status' || op === 'wait-stop') &&
|
|
84
|
+
(h.wait.operationId !== operationId || h.wait.deadlineAtUtcMs !== operationDeadline))
|
|
85
|
+
throw new Refusal('receipt_wait_unknown', 1);
|
|
86
|
+
}
|
|
87
|
+
return response;
|
|
88
|
+
};
|
|
89
|
+
const update = (response) => {
|
|
90
|
+
if (!response.ok || !('handoff' in response.body))
|
|
91
|
+
throw new Refusal('invalid_receipt_protocol', 1);
|
|
92
|
+
const incoming = validateManagedHandoff(response.body.handoff);
|
|
93
|
+
if (operationId && incoming.wait.operationId === operationId && incoming.wait.deadlineAtUtcMs !== operationDeadline)
|
|
94
|
+
throw new Refusal('receipt_wait_unknown', 1);
|
|
95
|
+
// A general actor response may expose a concurrent owner's latest wait.
|
|
96
|
+
// Only an explicit original-operation query can replace our wait evidence.
|
|
97
|
+
handoff = !required ? { ...incoming, wait: { for: 'none', status: 'not_requested' }, nextActions: ['reconcile'] } :
|
|
98
|
+
operationId && incoming.wait.operationId !== operationId && handoff ?
|
|
99
|
+
{ ...incoming, wait: handoff.wait, nextActions: ['reconcile'] } : incoming;
|
|
100
|
+
};
|
|
101
|
+
const selector = () => ({ ledgerEpoch: handle.ledgerEpoch, correlationId: handle.correlationId });
|
|
102
|
+
const ownWait = async () => { if (operationId)
|
|
103
|
+
update(await rpc('wait-status', { ...selector(), operationId })); };
|
|
104
|
+
const stopWait = async () => {
|
|
105
|
+
stopSent = true;
|
|
106
|
+
try {
|
|
107
|
+
update(await rpc('wait-stop', { ...selector(), operationId: operationId }));
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (budget.remainingMs() <= 0)
|
|
111
|
+
throw error;
|
|
112
|
+
await ownWait(); // One read of the original operation; a terminal result wins.
|
|
113
|
+
if (handoff?.wait.status === 'pending')
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
const authorize = async () => {
|
|
118
|
+
if (fenced)
|
|
119
|
+
throw new Refusal('receipt_already_attempted', 1);
|
|
120
|
+
if (stopped)
|
|
121
|
+
throw new Refusal('stopped_by_operator', 130);
|
|
122
|
+
budget.beforeEffect();
|
|
123
|
+
producer.revalidate();
|
|
124
|
+
revalidateTarget();
|
|
125
|
+
if (endpoint(config.collector) !== endpointIdentity)
|
|
126
|
+
throw new Refusal('receipt_endpoint_changed', 1);
|
|
127
|
+
budget.beforeEffect();
|
|
128
|
+
update(await rpc('fence', { ...handle, binding: original }));
|
|
129
|
+
fenced = true;
|
|
130
|
+
if (stopped)
|
|
131
|
+
throw new Refusal('stopped_by_operator', 130);
|
|
132
|
+
producer.revalidate();
|
|
133
|
+
revalidateTarget();
|
|
134
|
+
budget.beforeEffect();
|
|
135
|
+
};
|
|
136
|
+
const verifyOwner = async (scope) => {
|
|
137
|
+
if (stopped || budget.observationRemainingMs() < 1)
|
|
138
|
+
return false;
|
|
139
|
+
const result = await probe(process.execPath, [fileURLToPath(new URL('./handoff-writer-probe.js', import.meta.url)), scope.codexHome, scope.threadId, ...ownerArgs], { timeout: Math.min(800, budget.observationRemainingMs()), limit: 4096, env: { ...process.env, NODE_OPTIONS: undefined, NODE_PATH: undefined } });
|
|
140
|
+
if (stopped || result.interrupted || result.code !== 0)
|
|
141
|
+
return false;
|
|
142
|
+
try {
|
|
143
|
+
const row = JSON.parse(result.stdout);
|
|
144
|
+
return row.schemaVersion === 1 && row.ok === true && row.generation === scope.generation && Object.keys(row).every(k => ['schemaVersion', 'ok', 'generation'].includes(k));
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
const stop = () => { stopped = true; };
|
|
151
|
+
const finish = (value, exitCode) => ({ value: { ...value, receiptBootstrap: { status: prepared ? 'supported' : 'unsupported' }, ...(handoff ? { handoff } : {}) }, exitCode });
|
|
152
|
+
if (required)
|
|
153
|
+
process.on('SIGINT', stop);
|
|
154
|
+
try {
|
|
155
|
+
const value = await sourceSend({ ...options, hooks: { privateReceiptContext: true,
|
|
156
|
+
async resolved(context, native, provenance) {
|
|
157
|
+
firstContext = { ...context };
|
|
158
|
+
snapshot = { ...native };
|
|
159
|
+
budget.beforeEffect();
|
|
160
|
+
const pair = RECEIPT_PAIRS.find(p => p.agent === context.agent);
|
|
161
|
+
if (!['linux', 'darwin'].includes(process.platform))
|
|
162
|
+
throw new Unsupported();
|
|
163
|
+
if (context.agent === 'claude') {
|
|
164
|
+
if (!provenance || context.generation !== null)
|
|
165
|
+
throw new Unsupported();
|
|
166
|
+
if (provenance.routeIdentity !== context.writerIdentity)
|
|
167
|
+
throw new Refusal('receipt_registry_untrusted', 1);
|
|
168
|
+
revalidateTarget = claudeAdmission(provenance);
|
|
169
|
+
original = validateReceiptBinding({ agent: 'claude', destination: hostname(), target: context.target, ...provenance, generation: null, payloadDigest: digest(config.payload ?? options.message) });
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
if (!context.home || !context.writerIdentity || !context.generation || !context.binary)
|
|
173
|
+
throw new Unsupported();
|
|
174
|
+
original = validateReceiptBinding({ agent: 'codex', destination: hostname(), target: context.target, home: context.home, writerIdentity: context.writerIdentity, generation: context.generation, payloadDigest: digest(config.payload ?? options.message) });
|
|
175
|
+
queueScope = { codexHome: context.home, threadId: context.target, generation: context.generation, ownerIdentity: context.writerIdentity };
|
|
176
|
+
const result = await probe(context.binary, ['--version'], { timeout: Math.min(1000, timeout()), limit: 4096 });
|
|
177
|
+
const version = !result.interrupted && result.code === 0 && /^codex-cli \d+\.\d+\.\d+\s*$/.test(result.stdout) ? result.stdout.trim().slice(10) : '';
|
|
178
|
+
const profile = selectNativeProfile({ platform: currentPlatform(), version });
|
|
179
|
+
if (!profile || !nativeQueueCapability({ version, platform: currentPlatform(), scope: queueScope }).queueSupported)
|
|
180
|
+
throw new Unsupported();
|
|
181
|
+
ownerArgs = profile.ownerInspection === 'lsof_ps_procfs_locks' ? ['--procfs-owner'] : [];
|
|
182
|
+
if (!await verifyOwner(queueScope))
|
|
183
|
+
throw new Unsupported();
|
|
184
|
+
}
|
|
185
|
+
endpointIdentity = endpoint(config.collector);
|
|
186
|
+
const hello = await rpc('hello', {});
|
|
187
|
+
const remainingMs = Math.floor(budget.remainingMs());
|
|
188
|
+
contextId = hello.collectorContextId;
|
|
189
|
+
if (!hello.ok || !('receiptSchemas' in hello.body))
|
|
190
|
+
throw new Refusal('invalid_receipt_protocol', 1);
|
|
191
|
+
if (remainingMs < 1)
|
|
192
|
+
throw new Refusal('deadline_before_effect', 1);
|
|
193
|
+
waitBudget = { clockReferenceMs: hello.body.clockReferenceMs, remainingMs };
|
|
194
|
+
if (hello.body.endpointOwner.uid !== process.getuid?.())
|
|
195
|
+
throw new Refusal('receipt_endpoint_untrusted', 1);
|
|
196
|
+
if (!hello.body.receiptSchemas.some(p => p.agent === pair.agent && p.receiptSchemaVersion === pair.receiptSchemaVersion && p.receiptScope === pair.receiptScope))
|
|
197
|
+
throw new Unsupported();
|
|
198
|
+
producer = await (deps.producer ?? validateReceiptProducer)(pair, { timeoutMs: timeout() });
|
|
199
|
+
revalidateTarget();
|
|
200
|
+
budget.beforeEffect();
|
|
201
|
+
// Account for the whole inert recipient envelope before allocating authority.
|
|
202
|
+
const placeholder = { schemaVersion: pair.receiptSchemaVersion, kind: 'receipt', ledgerEpoch: randomUUID(), correlationId: randomUUID(),
|
|
203
|
+
...(pair.agent === 'codex' ? { targetGeneration: context.generation } : { receiptScope: 'delegated_context', receiptContextId: randomUUID() }), receiptId: randomUUID(), capability: 'x'.repeat(43) };
|
|
204
|
+
checkMessage(options.message + '\nCorrelation-Id: ' + placeholder.correlationId + '\nReceipt-Only: ' + JSON.stringify({ collector: config.collector, receipt: placeholder }), context.agent === 'codex');
|
|
205
|
+
// Once prepare is attempted, no ordinary fallback is allowed even on an ambiguous response.
|
|
206
|
+
prepared = true;
|
|
207
|
+
const response = await rpc('prepare', { binding: original, receiptSchemaVersion: pair.receiptSchemaVersion, receiptScope: pair.receiptScope, producerEvidence: producer.evidence });
|
|
208
|
+
if (!response.ok || !('ledgerEpoch' in response.body) || !('receiptContextId' in response.body) || !('handoff' in response.body))
|
|
209
|
+
throw new Refusal('invalid_receipt_protocol', 1);
|
|
210
|
+
handle = { ledgerEpoch: response.body.ledgerEpoch, correlationId: response.body.correlationId, receiptContextId: response.body.receiptContextId };
|
|
211
|
+
const h = validateManagedHandoff(response.body.handoff);
|
|
212
|
+
if (h.schemaVersion !== pair.receiptSchemaVersion || h.targetGeneration !== context.generation || h.ledgerEpoch !== handle.ledgerEpoch || h.correlationId !== handle.correlationId ||
|
|
213
|
+
(pair.agent === 'codex' ? handle.receiptContextId !== null : h.schemaVersion !== 2 || h.receiptContext.id !== handle.receiptContextId))
|
|
214
|
+
throw new Refusal('receipt_context_mismatch', 1);
|
|
215
|
+
handoff = h;
|
|
216
|
+
const minted = await rpc('mint', { ...handle, producerProtocolVersion: 1 });
|
|
217
|
+
if (!minted.ok || !('capability' in minted.body))
|
|
218
|
+
throw new Refusal('invalid_receipt_protocol', 1);
|
|
219
|
+
if (required) {
|
|
220
|
+
update(await rpc('wait-open', { ...selector(), goal: 'acknowledged', timeoutSeconds: budget.seconds, ...waitBudget }));
|
|
221
|
+
operationId = handoff.wait.operationId;
|
|
222
|
+
operationDeadline = handoff.wait.deadlineAtUtcMs;
|
|
223
|
+
if (!operationId || handoff.wait.status !== 'pending')
|
|
224
|
+
throw new Refusal(handoff.wait.reason ?? 'receipt_bootstrap_unsupported', 1);
|
|
225
|
+
}
|
|
226
|
+
const frame = { ...placeholder, ledgerEpoch: handle.ledgerEpoch, correlationId: handle.correlationId,
|
|
227
|
+
...(pair.agent === 'claude' ? { receiptContextId: handle.receiptContextId } : {}), capability: minted.body.capability };
|
|
228
|
+
return options.message + '\nCorrelation-Id: ' + handle.correlationId + '\nReceipt-Only: ' + JSON.stringify({ collector: config.collector, receipt: frame });
|
|
229
|
+
}, beforeEffect: authorize, beforeWrite: () => { if (stopped)
|
|
230
|
+
throw new Refusal('stopped_by_operator', 130); budget.beforeEffect(); }, codexRoute: () => 'owned_app_server',
|
|
231
|
+
async submitCodex(_context, message, storage) {
|
|
232
|
+
if (!queueScope || !handle)
|
|
233
|
+
throw new Unsupported();
|
|
234
|
+
// The native adapter deliberately wraps callback failures. Retain only
|
|
235
|
+
// our own pre-effect Refusal so wrapping cannot erase stop/deadline facts.
|
|
236
|
+
let guardedRefusal;
|
|
237
|
+
const beforeEffect = async () => {
|
|
238
|
+
try {
|
|
239
|
+
await authorize();
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
if (error instanceof Refusal)
|
|
243
|
+
guardedRefusal = error;
|
|
244
|
+
throw error;
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
const verifyStorageSync = () => {
|
|
248
|
+
try {
|
|
249
|
+
if (stopped)
|
|
250
|
+
throw new Refusal('stopped_by_operator', 130);
|
|
251
|
+
budget.beforeEffect();
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
if (error instanceof Refusal)
|
|
255
|
+
guardedRefusal = error;
|
|
256
|
+
throw error;
|
|
257
|
+
}
|
|
258
|
+
storage.finalCheck(true);
|
|
259
|
+
};
|
|
260
|
+
try {
|
|
261
|
+
return await (deps.nativeQueue ?? nativeQueueOnce)({ binary: storage.binary, scope: queueScope, message, clientUserMessageId: handle.correlationId,
|
|
262
|
+
deadlineMs: budget.cutoff, verifyOwner, beforeEffect, verifyStorage: () => storage.revalidate(true), verifyStorageSync });
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
if (error instanceof AppServerFault) {
|
|
266
|
+
if (error.attempted)
|
|
267
|
+
throw new UnknownOutcome();
|
|
268
|
+
if (guardedRefusal)
|
|
269
|
+
throw guardedRefusal;
|
|
270
|
+
if (stopped)
|
|
271
|
+
throw new Refusal('stopped_by_operator', 130);
|
|
272
|
+
throw new Refusal('receipt_bootstrap_unsupported', 1);
|
|
273
|
+
}
|
|
274
|
+
throw error;
|
|
275
|
+
}
|
|
276
|
+
}, timeoutMs: () => { if (stopped)
|
|
277
|
+
throw new Refusal('stopped_by_operator', 130); budget.beforeEffect(); return Math.max(1, Math.floor(budget.observationRemainingMs())); } } });
|
|
278
|
+
knownNative = { ...value };
|
|
279
|
+
update(await rpc('submission', { ...handle, status: 'submitted' }));
|
|
280
|
+
await ownWait();
|
|
281
|
+
while (required && handoff.wait.status === 'pending' && !stopped && budget.observationRemainingMs() > 0) {
|
|
282
|
+
await delay(Math.min(100, budget.observationRemainingMs()));
|
|
283
|
+
if (stopped)
|
|
284
|
+
break;
|
|
285
|
+
await ownWait();
|
|
286
|
+
}
|
|
287
|
+
if (required && handoff.wait.status === 'pending') {
|
|
288
|
+
if (stopped && !stopSent) {
|
|
289
|
+
await stopWait();
|
|
290
|
+
}
|
|
291
|
+
else if (!stopped) {
|
|
292
|
+
await delay(Math.min(25, budget.remainingMs()));
|
|
293
|
+
if (stopped && !stopSent)
|
|
294
|
+
await stopWait();
|
|
295
|
+
else
|
|
296
|
+
await ownWait();
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
if (required && handoff.wait.status !== 'satisfied') {
|
|
300
|
+
const interrupted = handoff.wait.status === 'stopped' && handoff.wait.reason === 'stopped_by_operator';
|
|
301
|
+
return finish({ ...value, ok: false, error: handoff.wait.reason ?? 'timed_out_unknown', retryAllowed: false }, interrupted ? 130 : 1);
|
|
302
|
+
}
|
|
303
|
+
return finish(value, 0);
|
|
304
|
+
}
|
|
305
|
+
catch (error) {
|
|
306
|
+
if (!prepared && !required && firstContext && error instanceof Refusal && ['receipt_bootstrap_unsupported', 'receipt_collector_unavailable'].includes(error.code)) {
|
|
307
|
+
try {
|
|
308
|
+
const value = await sourceSend({ ...options, hooks: {
|
|
309
|
+
resolved(context) {
|
|
310
|
+
const fields = ['agent', 'target', 'home', 'generation', 'writerIdentity', 'binary'];
|
|
311
|
+
if (fields.some(field => context[field] !== firstContext[field]))
|
|
312
|
+
throw new Refusal('target_changed', 1);
|
|
313
|
+
budget.beforeEffect();
|
|
314
|
+
},
|
|
315
|
+
beforeEffect() { budget.beforeEffect(); },
|
|
316
|
+
timeoutMs() { budget.beforeEffect(); return Math.max(1, Math.floor(budget.observationRemainingMs())); }
|
|
317
|
+
} });
|
|
318
|
+
return { value: { ...value, receiptBootstrap: { status: 'unsupported' }, retryAllowed: false }, exitCode: 0 };
|
|
319
|
+
}
|
|
320
|
+
catch (fallbackError) {
|
|
321
|
+
error = fallbackError;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (!snapshot)
|
|
325
|
+
throw error;
|
|
326
|
+
let warning = false;
|
|
327
|
+
const uncertain = error instanceof UnknownOutcome || (fenced && !(error instanceof Refusal));
|
|
328
|
+
let stopError;
|
|
329
|
+
// Preserve an explicit stop before revoke/submission terminalizes this wait.
|
|
330
|
+
if (stopped && operationId && handoff?.wait.status === 'pending' && !stopSent) {
|
|
331
|
+
try {
|
|
332
|
+
await stopWait();
|
|
333
|
+
}
|
|
334
|
+
catch (failure) {
|
|
335
|
+
stopError = failure;
|
|
336
|
+
warning = true;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (knownNative) {
|
|
340
|
+
// A receipt/IPC failure cannot erase independently positive native acceptance.
|
|
341
|
+
if (handoff)
|
|
342
|
+
handoff = { ...handoff, state: handoff.ack.status === 'acknowledged' ? 'acknowledged' : 'submitted', submission: { status: 'submitted' }, nextActions: ['reconcile'] };
|
|
343
|
+
if (required && stopSent && handoff && handoff.wait.status !== 'pending') {
|
|
344
|
+
if (handoff.wait.status === 'satisfied')
|
|
345
|
+
return finish(knownNative, 0);
|
|
346
|
+
const confirmedStop = handoff.wait.status === 'stopped' && handoff.wait.reason === 'stopped_by_operator';
|
|
347
|
+
return finish({ ...knownNative, ok: false, error: handoff.wait.reason ?? 'timed_out_unknown', retryAllowed: false }, confirmedStop ? 130 : 1);
|
|
348
|
+
}
|
|
349
|
+
return finish({ ...knownNative, ...(required ? { ok: false, error: stopSent ? 'stop_unconfirmed' : 'receipt_persistence_failed' } : {}), handoffWarning: 'persistence_failed', retryAllowed: false }, required ? 1 : 0);
|
|
350
|
+
}
|
|
351
|
+
if (handle) {
|
|
352
|
+
try {
|
|
353
|
+
if (fenced)
|
|
354
|
+
update(await rpc('submission', { ...handle, status: uncertain ? 'unknown' : 'refused' }));
|
|
355
|
+
else
|
|
356
|
+
update(await rpc('revoke', selector()));
|
|
357
|
+
await ownWait();
|
|
358
|
+
}
|
|
359
|
+
catch {
|
|
360
|
+
warning = true;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
if (error instanceof Refusal && error.code === 'stopped_by_operator' &&
|
|
364
|
+
!(handoff?.wait.status === 'stopped' && handoff.wait.reason === 'stopped_by_operator'))
|
|
365
|
+
error = handoff?.wait.status === 'timed_out_unknown' ? new Refusal('timed_out_unknown', 1) :
|
|
366
|
+
handoff?.wait.status === 'failed' && handoff.wait.reason ? new Refusal(handoff.wait.reason, 1) :
|
|
367
|
+
stopError instanceof Refusal ? stopError : new Refusal('stop_unconfirmed', 1);
|
|
368
|
+
return finish({ ...snapshot, ok: false, status: uncertain ? 'unknown' : 'refused', submitted: uncertain ? null : false, consumptionConfirmed: false,
|
|
369
|
+
error: error instanceof Refusal ? error.code : uncertain ? 'outcome_unknown' : 'receipt_operation_failed', retryAllowed: false, ...(warning ? { handoffWarning: 'persistence_failed' } : {}) }, handoff?.wait.status === 'stopped' && handoff.wait.reason === 'stopped_by_operator' ? 130 : error instanceof Refusal && error.exitCode !== 130 ? error.exitCode : 1);
|
|
370
|
+
}
|
|
371
|
+
finally {
|
|
372
|
+
if (required)
|
|
373
|
+
process.removeListener('SIGINT', stop);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { type Clock } from './handoff.js';
|
|
2
|
+
import { type ReceiptBinding, type ProducerEvidence, type ManagedHandoff, type ReceiptScope } from './receipt-protocol.js';
|
|
3
|
+
type Handle = {
|
|
4
|
+
ledgerEpoch: string;
|
|
5
|
+
correlationId: string;
|
|
6
|
+
receiptContextId: string | null;
|
|
7
|
+
};
|
|
8
|
+
type Selector = Pick<Handle, 'ledgerEpoch' | 'correlationId'>;
|
|
9
|
+
export type ReceiptPreparation = {
|
|
10
|
+
binding: ReceiptBinding;
|
|
11
|
+
receiptSchemaVersion: 1 | 2;
|
|
12
|
+
receiptScope: ReceiptScope;
|
|
13
|
+
producerEvidence: ProducerEvidence;
|
|
14
|
+
};
|
|
15
|
+
export type PreparedReceipt = Handle & {
|
|
16
|
+
handoff: ManagedHandoff;
|
|
17
|
+
};
|
|
18
|
+
export type MintedReceipt = Handle & {
|
|
19
|
+
capability: string;
|
|
20
|
+
receiptSchemaVersion: 1 | 2;
|
|
21
|
+
receiptScope: ReceiptScope;
|
|
22
|
+
targetGeneration: string | null;
|
|
23
|
+
};
|
|
24
|
+
export type ReceiptAcceptance = {
|
|
25
|
+
status: 'awaiting_submission' | 'acknowledged';
|
|
26
|
+
receiptId: string;
|
|
27
|
+
handoff: ManagedHandoff;
|
|
28
|
+
};
|
|
29
|
+
export declare class ReceiptState {
|
|
30
|
+
readonly path: string;
|
|
31
|
+
readonly collectorContextId: `${string}-${string}-${string}-${string}-${string}`;
|
|
32
|
+
private readonly clock;
|
|
33
|
+
private store?;
|
|
34
|
+
private data?;
|
|
35
|
+
private busy;
|
|
36
|
+
private stopped;
|
|
37
|
+
private lastMono?;
|
|
38
|
+
constructor(path: string, options?: {
|
|
39
|
+
clock?: Clock;
|
|
40
|
+
});
|
|
41
|
+
static initialize(path: string, endpointSelector: string): {
|
|
42
|
+
ledgerEpoch: string;
|
|
43
|
+
storage: "private_posix";
|
|
44
|
+
managedVersion: 2;
|
|
45
|
+
};
|
|
46
|
+
get endpointSelector(): string;
|
|
47
|
+
get ledgerEpoch(): string;
|
|
48
|
+
assertOpen(): void;
|
|
49
|
+
open(): this;
|
|
50
|
+
close(): void;
|
|
51
|
+
private now;
|
|
52
|
+
clockReference(): number;
|
|
53
|
+
private utc;
|
|
54
|
+
private transact;
|
|
55
|
+
private validate;
|
|
56
|
+
private item;
|
|
57
|
+
private handle;
|
|
58
|
+
private authority;
|
|
59
|
+
private classify;
|
|
60
|
+
private snapshot;
|
|
61
|
+
prepare(input: ReceiptPreparation): PreparedReceipt;
|
|
62
|
+
mint(input: Handle & {
|
|
63
|
+
producerProtocolVersion: number;
|
|
64
|
+
}): MintedReceipt;
|
|
65
|
+
fence(input: Handle & {
|
|
66
|
+
binding: ReceiptBinding;
|
|
67
|
+
}): ManagedHandoff;
|
|
68
|
+
submission(input: Handle & {
|
|
69
|
+
status: 'submitted' | 'refused' | 'unknown';
|
|
70
|
+
}): ManagedHandoff;
|
|
71
|
+
status(input: Selector): ManagedHandoff;
|
|
72
|
+
waitOpen(input: Selector & {
|
|
73
|
+
goal: 'acknowledged';
|
|
74
|
+
timeoutSeconds: number;
|
|
75
|
+
clockReferenceMs?: number;
|
|
76
|
+
remainingMs?: number;
|
|
77
|
+
}): ManagedHandoff;
|
|
78
|
+
private selectWait;
|
|
79
|
+
waitStatus(input: Selector & {
|
|
80
|
+
operationId: string;
|
|
81
|
+
}): ManagedHandoff;
|
|
82
|
+
waitStop(input: Selector & {
|
|
83
|
+
operationId: string;
|
|
84
|
+
}): ManagedHandoff;
|
|
85
|
+
revoke(input: Selector): ManagedHandoff;
|
|
86
|
+
private commitAck;
|
|
87
|
+
receipt(raw: string): ReceiptAcceptance;
|
|
88
|
+
}
|
|
89
|
+
export {};
|