@wezzard/mcp-relay 0.0.0-stage → 0.14.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/.claude-plugin/marketplace.json +14 -0
- package/.claude-plugin/plugin.json +9 -0
- package/.mcp.json +10 -0
- package/LICENSE +21 -0
- package/README.md +421 -2
- package/agents/vm-relay-operator.md +39 -0
- package/commands/status.md +4 -0
- package/dist/NOTICE.txt +1 -0
- package/dist/build-info.json +982 -0
- package/dist/doctor.mjs +802 -0
- package/dist/integrity.json +6 -0
- package/dist/receiver.mjs +1341 -0
- package/dist/review-data.d.ts +68 -0
- package/dist/review-data.mjs +404 -0
- package/dist/server.mjs +30767 -0
- package/package.json +75 -4
- package/pi-mcp.json +1 -0
- package/pi-prompts/mcp-relay-status.md +4 -0
|
@@ -0,0 +1,1341 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// src/guest/receiver.ts
|
|
4
|
+
import { spawn, execFile } from "node:child_process";
|
|
5
|
+
import { createHash as createHash2, randomUUID } from "node:crypto";
|
|
6
|
+
import { mkdir as mkdir3, open, readFile as readFile2, rename as rename3, rm as rm2, stat as stat2, realpath } from "node:fs/promises";
|
|
7
|
+
import { dirname as dirname2, isAbsolute, join as join3, resolve } from "node:path";
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
9
|
+
|
|
10
|
+
// node_modules/@wezzard/relay-driver-remote-runtime/dist/src/capture-gate.js
|
|
11
|
+
function readinessOf(health) {
|
|
12
|
+
return health.ready ?? health.recording ?? false;
|
|
13
|
+
}
|
|
14
|
+
var DEFAULT_MAX_HEALTH_AGE_MS = 2e3;
|
|
15
|
+
var CaptureGate = class {
|
|
16
|
+
maxHealthAgeMs;
|
|
17
|
+
now;
|
|
18
|
+
health;
|
|
19
|
+
constructor(maxHealthAgeMs = DEFAULT_MAX_HEALTH_AGE_MS, now = () => Date.now()) {
|
|
20
|
+
this.maxHealthAgeMs = maxHealthAgeMs;
|
|
21
|
+
this.now = now;
|
|
22
|
+
}
|
|
23
|
+
/** Called by the capture integration (or its failure callback). */
|
|
24
|
+
update(health) {
|
|
25
|
+
this.health = health;
|
|
26
|
+
}
|
|
27
|
+
/** Called when capture capability loss is detected; disables input immediately. */
|
|
28
|
+
reportLoss(diagnostic) {
|
|
29
|
+
this.health = {
|
|
30
|
+
ready: false,
|
|
31
|
+
diagnostic,
|
|
32
|
+
observedAtMonotonic: this.now()
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Admission check before each operation. Returns a refusal diagnostic when
|
|
37
|
+
* input must not be dispatched; undefined when screenshot capability is ready.
|
|
38
|
+
*/
|
|
39
|
+
checkAdmission() {
|
|
40
|
+
const health = this.health;
|
|
41
|
+
if (!health)
|
|
42
|
+
return "capture health not yet observed";
|
|
43
|
+
const age = this.now() - health.observedAtMonotonic;
|
|
44
|
+
if (age > this.maxHealthAgeMs) {
|
|
45
|
+
return `capture health observation is stale (${age} ms old)`;
|
|
46
|
+
}
|
|
47
|
+
if (!readinessOf(health)) {
|
|
48
|
+
return `capture unavailable: ${health.diagnostic ?? "display screenshot capability not available"}`;
|
|
49
|
+
}
|
|
50
|
+
return void 0;
|
|
51
|
+
}
|
|
52
|
+
get currentSegmentId() {
|
|
53
|
+
return this.health && readinessOf(this.health) ? this.health.segmentId : void 0;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// node_modules/@wezzard/relay-driver-remote-runtime/dist/src/record-store.js
|
|
58
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
59
|
+
import { dirname, join } from "node:path";
|
|
60
|
+
|
|
61
|
+
// node_modules/@wezzard/relay-driver-core/dist/src/identity.js
|
|
62
|
+
var SUFFIX_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
63
|
+
function allocateSuffix(now = Date.now(), random = Math.random) {
|
|
64
|
+
const time = now.toString(36).padStart(9, "0");
|
|
65
|
+
let rand = "";
|
|
66
|
+
for (let i = 0; i < 8; i++) {
|
|
67
|
+
rand += SUFFIX_ALPHABET[Math.floor(random() * SUFFIX_ALPHABET.length)];
|
|
68
|
+
}
|
|
69
|
+
return `${time}${rand}`;
|
|
70
|
+
}
|
|
71
|
+
function allocateId(kind, now = Date.now(), random = Math.random) {
|
|
72
|
+
return { kind, suffix: allocateSuffix(now, random) };
|
|
73
|
+
}
|
|
74
|
+
function formatId(id) {
|
|
75
|
+
return `${id.kind}-${id.suffix}`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// node_modules/@wezzard/relay-driver-core/dist/src/journal.js
|
|
79
|
+
import { promises as fs } from "node:fs";
|
|
80
|
+
var JournalWriter = class _JournalWriter {
|
|
81
|
+
path;
|
|
82
|
+
seq = 0;
|
|
83
|
+
handle;
|
|
84
|
+
constructor(path) {
|
|
85
|
+
this.path = path;
|
|
86
|
+
}
|
|
87
|
+
static async create(path) {
|
|
88
|
+
const writer = new _JournalWriter(path);
|
|
89
|
+
writer.handle = await fs.open(path, "a");
|
|
90
|
+
const handle = writer.handle;
|
|
91
|
+
handle.unref?.();
|
|
92
|
+
return writer;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Append one record. `durable` fsyncs before returning (start records).
|
|
96
|
+
* The whole line is written or the call rejects; a rejected append may
|
|
97
|
+
* leave a partial line, which readers report as a damaged tail.
|
|
98
|
+
*/
|
|
99
|
+
async append(record, options = {}) {
|
|
100
|
+
if (!this.handle)
|
|
101
|
+
throw new Error("journal writer is closed");
|
|
102
|
+
const full = {
|
|
103
|
+
...record,
|
|
104
|
+
seq: this.seq++,
|
|
105
|
+
writtenAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
106
|
+
};
|
|
107
|
+
const line = Buffer.from(JSON.stringify(full) + "\n", "utf8");
|
|
108
|
+
let offset = 0;
|
|
109
|
+
while (offset < line.length) {
|
|
110
|
+
const { bytesWritten } = await this.handle.write(line, offset, line.length - offset, null);
|
|
111
|
+
if (!(bytesWritten > 0)) {
|
|
112
|
+
throw new Error(`journal write made no progress after ${offset} of ${line.length} bytes (seq ${full.seq})`);
|
|
113
|
+
}
|
|
114
|
+
offset += bytesWritten;
|
|
115
|
+
}
|
|
116
|
+
if (options.durable) {
|
|
117
|
+
await this.handle.sync();
|
|
118
|
+
}
|
|
119
|
+
return full;
|
|
120
|
+
}
|
|
121
|
+
async close() {
|
|
122
|
+
if (this.handle) {
|
|
123
|
+
await this.handle.sync();
|
|
124
|
+
await this.handle.close();
|
|
125
|
+
this.handle = void 0;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
async function readJournal(path, options = {}) {
|
|
130
|
+
let text2;
|
|
131
|
+
try {
|
|
132
|
+
text2 = await fs.readFile(path, "utf8");
|
|
133
|
+
} catch (err) {
|
|
134
|
+
if (err.code === "ENOENT") {
|
|
135
|
+
return { records: [] };
|
|
136
|
+
}
|
|
137
|
+
throw err;
|
|
138
|
+
}
|
|
139
|
+
const records = [];
|
|
140
|
+
let damagedTail;
|
|
141
|
+
const lines = text2.split("\n");
|
|
142
|
+
for (let i = 0; i < lines.length; i++) {
|
|
143
|
+
const line = lines[i];
|
|
144
|
+
if (line === "")
|
|
145
|
+
continue;
|
|
146
|
+
try {
|
|
147
|
+
records.push(JSON.parse(line));
|
|
148
|
+
} catch {
|
|
149
|
+
if (i === lines.length - 1) {
|
|
150
|
+
damagedTail = line;
|
|
151
|
+
} else {
|
|
152
|
+
damagedTail = damagedTail === void 0 ? line : damagedTail;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (options.limit && records.length >= options.limit)
|
|
156
|
+
break;
|
|
157
|
+
}
|
|
158
|
+
return { records, damagedTail };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// node_modules/@wezzard/relay-driver-remote-runtime/dist/src/record-store.js
|
|
162
|
+
var RecordStore = class _RecordStore {
|
|
163
|
+
rootDir;
|
|
164
|
+
journal;
|
|
165
|
+
constructor(rootDir) {
|
|
166
|
+
this.rootDir = rootDir;
|
|
167
|
+
}
|
|
168
|
+
static async create(rootDir) {
|
|
169
|
+
await mkdir(join(rootDir, "records"), { recursive: true });
|
|
170
|
+
await mkdir(join(rootDir, "journal"), { recursive: true });
|
|
171
|
+
const store = new _RecordStore(rootDir);
|
|
172
|
+
store.journal = await JournalWriter.create(join(rootDir, "journal", "events.jsonl"));
|
|
173
|
+
return store;
|
|
174
|
+
}
|
|
175
|
+
recordPath(kind, id) {
|
|
176
|
+
return join(this.rootDir, "records", kind, `${id}.json`);
|
|
177
|
+
}
|
|
178
|
+
async writeRecord(kind, id, record) {
|
|
179
|
+
const path = this.recordPath(kind, id);
|
|
180
|
+
await mkdir(dirname(path), { recursive: true });
|
|
181
|
+
const tmp = `${path}.tmp`;
|
|
182
|
+
await writeFile(tmp, JSON.stringify(record, null, 2), "utf8");
|
|
183
|
+
await rename(tmp, path);
|
|
184
|
+
}
|
|
185
|
+
async readRecord(kind, id) {
|
|
186
|
+
try {
|
|
187
|
+
return JSON.parse(await readFile(this.recordPath(kind, id), "utf8"));
|
|
188
|
+
} catch (err) {
|
|
189
|
+
if (err.code === "ENOENT")
|
|
190
|
+
return void 0;
|
|
191
|
+
throw err;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
async appendJournal(record, options = {}) {
|
|
195
|
+
if (!this.journal)
|
|
196
|
+
throw new Error("store is closed");
|
|
197
|
+
return this.journal.append(record, options);
|
|
198
|
+
}
|
|
199
|
+
// ---- sessions / attempts / executions ----
|
|
200
|
+
async putSession(session) {
|
|
201
|
+
await this.writeRecord("session", session.sessionId, session);
|
|
202
|
+
}
|
|
203
|
+
async getSession(sessionId) {
|
|
204
|
+
return this.readRecord("session", sessionId);
|
|
205
|
+
}
|
|
206
|
+
async putAttempt(attempt) {
|
|
207
|
+
await this.writeRecord("attempt", attempt.attemptId, attempt);
|
|
208
|
+
}
|
|
209
|
+
async getAttempt(attemptId) {
|
|
210
|
+
return this.readRecord("attempt", attemptId);
|
|
211
|
+
}
|
|
212
|
+
async putExecution(execution) {
|
|
213
|
+
await this.writeRecord("execution", execution.executionId, execution);
|
|
214
|
+
}
|
|
215
|
+
async getExecution(executionId) {
|
|
216
|
+
return this.readRecord("execution", executionId);
|
|
217
|
+
}
|
|
218
|
+
async putAction(action) {
|
|
219
|
+
await this.writeRecord("action", action.actionId, action);
|
|
220
|
+
}
|
|
221
|
+
async getAction(actionId) {
|
|
222
|
+
return this.readRecord("action", actionId);
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Durable start retention: the journal fsyncs the start record before the
|
|
226
|
+
* callable may be invoked. Returns after the record is on disk.
|
|
227
|
+
*/
|
|
228
|
+
async retainActionStart(params) {
|
|
229
|
+
const record = await this.getAction(params.actionId);
|
|
230
|
+
if (!record)
|
|
231
|
+
throw new Error(`unknown action ${params.actionId}`);
|
|
232
|
+
if (record.state !== "pending") {
|
|
233
|
+
throw new Error(`action ${params.actionId} is not pending (state: ${record.state})`);
|
|
234
|
+
}
|
|
235
|
+
const start = await this.appendJournal({
|
|
236
|
+
kind: "action-start",
|
|
237
|
+
sessionId: params.sessionId,
|
|
238
|
+
attemptId: params.attemptId,
|
|
239
|
+
stepId: params.stepId,
|
|
240
|
+
executionId: params.executionId,
|
|
241
|
+
actionId: params.actionId,
|
|
242
|
+
state: "admitted",
|
|
243
|
+
title: params.title,
|
|
244
|
+
inputMode: params.inputMode,
|
|
245
|
+
snapshotPlan: params.snapshots?.plan
|
|
246
|
+
}, { durable: true });
|
|
247
|
+
const updated = {
|
|
248
|
+
...record,
|
|
249
|
+
state: "admitted",
|
|
250
|
+
startRetainedAt: start.writtenAt
|
|
251
|
+
};
|
|
252
|
+
await this.putAction(updated);
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Retain the snapshot evidence references for one action (SNAP-02/03):
|
|
256
|
+
* hashes-at-capture, file names, provenance, and for coalescing groups
|
|
257
|
+
* the pair-citation layout. Journal record fsynced — snapshot references
|
|
258
|
+
* are durable evidence, not prose.
|
|
259
|
+
*/
|
|
260
|
+
async retainActionSnapshots(actionId, snapshots, plan) {
|
|
261
|
+
const record = await this.getAction(actionId);
|
|
262
|
+
if (!record)
|
|
263
|
+
throw new Error(`unknown action ${actionId}`);
|
|
264
|
+
await this.appendJournal({
|
|
265
|
+
kind: "snapshot-evidence",
|
|
266
|
+
sessionId: record.sessionId,
|
|
267
|
+
attemptId: record.attemptId,
|
|
268
|
+
actionId,
|
|
269
|
+
state: "recorded",
|
|
270
|
+
snapshots,
|
|
271
|
+
snapshotRole: plan.role,
|
|
272
|
+
groupId: plan.group?.groupId
|
|
273
|
+
});
|
|
274
|
+
await this.putAction({
|
|
275
|
+
...record,
|
|
276
|
+
snapshots,
|
|
277
|
+
snapshotRole: plan.role,
|
|
278
|
+
groupId: plan.group?.groupId
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
async retainActionCompletion(params) {
|
|
282
|
+
const record = await this.getAction(params.actionId);
|
|
283
|
+
if (!record)
|
|
284
|
+
throw new Error(`unknown action ${params.actionId}`);
|
|
285
|
+
if (record.state !== "admitted") {
|
|
286
|
+
throw new Error(`action ${params.actionId} is not admitted (state: ${record.state})`);
|
|
287
|
+
}
|
|
288
|
+
await this.appendJournal({
|
|
289
|
+
kind: "action-completion",
|
|
290
|
+
sessionId: record.sessionId,
|
|
291
|
+
attemptId: record.attemptId,
|
|
292
|
+
executionId: record.executionId,
|
|
293
|
+
actionId: record.actionId,
|
|
294
|
+
state: "recorded",
|
|
295
|
+
toolOutcome: params.toolOutcome
|
|
296
|
+
});
|
|
297
|
+
await this.putAction({
|
|
298
|
+
...record,
|
|
299
|
+
state: "recorded",
|
|
300
|
+
toolOutcome: params.toolOutcome,
|
|
301
|
+
evidenceStatus: "retained"
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Close an admitted action whose callable never ran (for example, the
|
|
306
|
+
* before-snapshot could not be captured after the durable start). The
|
|
307
|
+
* `action-refusal` record states that no input was dispatched; it is not a
|
|
308
|
+
* tool completion and carries no tool outcome (D26).
|
|
309
|
+
*/
|
|
310
|
+
async retainActionRefusal(params) {
|
|
311
|
+
const record = await this.getAction(params.actionId);
|
|
312
|
+
if (!record)
|
|
313
|
+
throw new Error(`unknown action ${params.actionId}`);
|
|
314
|
+
if (record.state !== "admitted") {
|
|
315
|
+
throw new Error(`action ${params.actionId} is not admitted (state: ${record.state})`);
|
|
316
|
+
}
|
|
317
|
+
await this.appendJournal({
|
|
318
|
+
kind: "action-refusal",
|
|
319
|
+
sessionId: record.sessionId,
|
|
320
|
+
attemptId: record.attemptId,
|
|
321
|
+
stepId: record.stepId,
|
|
322
|
+
executionId: record.executionId,
|
|
323
|
+
actionId: record.actionId,
|
|
324
|
+
state: "refused",
|
|
325
|
+
inputDispatched: false,
|
|
326
|
+
diagnostic: params.diagnostic
|
|
327
|
+
}, { durable: true });
|
|
328
|
+
await this.putAction({
|
|
329
|
+
...record,
|
|
330
|
+
state: "refused",
|
|
331
|
+
evidenceStatus: "not-applicable"
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Mark an admitted action uncertain (process/transport lost before
|
|
336
|
+
* completion). Never resolves the outcome; recovery may later find the
|
|
337
|
+
* original record.
|
|
338
|
+
*/
|
|
339
|
+
async markUncertain(actionId, diagnostic) {
|
|
340
|
+
const record = await this.getAction(actionId);
|
|
341
|
+
if (!record)
|
|
342
|
+
throw new Error(`unknown action ${actionId}`);
|
|
343
|
+
if (record.state !== "admitted")
|
|
344
|
+
return;
|
|
345
|
+
await this.appendJournal({
|
|
346
|
+
kind: "action-completion",
|
|
347
|
+
sessionId: record.sessionId,
|
|
348
|
+
attemptId: record.attemptId,
|
|
349
|
+
actionId: record.actionId,
|
|
350
|
+
state: "uncertain",
|
|
351
|
+
diagnostic
|
|
352
|
+
});
|
|
353
|
+
await this.putAction({
|
|
354
|
+
...record,
|
|
355
|
+
state: "uncertain",
|
|
356
|
+
evidenceStatus: "unconfirmed"
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
async journalHistory() {
|
|
360
|
+
return readJournal(join(this.rootDir, "journal", "events.jsonl"));
|
|
361
|
+
}
|
|
362
|
+
async close() {
|
|
363
|
+
await this.journal?.close();
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
// node_modules/@wezzard/relay-driver-remote-runtime/dist/src/snapshots.js
|
|
368
|
+
import { mkdir as mkdir2, stat, rename as rename2, rm } from "node:fs/promises";
|
|
369
|
+
import { createHash } from "node:crypto";
|
|
370
|
+
import { join as join2 } from "node:path";
|
|
371
|
+
function isoStamp(d) {
|
|
372
|
+
return d.toISOString().replace(/[-:]/g, "").replace(/\./g, ".").replace(/-$/, "Z");
|
|
373
|
+
}
|
|
374
|
+
var SnapshotCaptureError = class extends Error {
|
|
375
|
+
constructor(message2) {
|
|
376
|
+
super(message2);
|
|
377
|
+
this.name = "SnapshotCaptureError";
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
var SnapshotStore = class {
|
|
381
|
+
capture;
|
|
382
|
+
store;
|
|
383
|
+
rootDir;
|
|
384
|
+
seq = 0;
|
|
385
|
+
constructor(capture, store, rootDir) {
|
|
386
|
+
this.capture = capture;
|
|
387
|
+
this.store = store;
|
|
388
|
+
this.rootDir = rootDir;
|
|
389
|
+
}
|
|
390
|
+
get snapshotsDir() {
|
|
391
|
+
return join2(this.rootDir, "snapshots");
|
|
392
|
+
}
|
|
393
|
+
fileNameFor(identity, role, capturedAt) {
|
|
394
|
+
const seqPart = `a${String(identity.journalSeq).padStart(6, "0")}`;
|
|
395
|
+
const safeIdentity = identity.dispatchIdentity.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "event";
|
|
396
|
+
return `${seqPart}-${isoStamp(capturedAt)}-${role}-${safeIdentity}.png`;
|
|
397
|
+
}
|
|
398
|
+
/** Capture one snapshot with provenance; hashes the file at capture. */
|
|
399
|
+
async captureOne(identity, role, declared = {}) {
|
|
400
|
+
const dir = join2(this.snapshotsDir, identity.sessionId);
|
|
401
|
+
await mkdir2(dir, { recursive: true });
|
|
402
|
+
const captureStartedAtMonotonic = Date.now();
|
|
403
|
+
const capturedAt = new Date(captureStartedAtMonotonic);
|
|
404
|
+
const fileName = this.fileNameFor(identity, role, capturedAt);
|
|
405
|
+
const tmpPath = join2(dir, `.${fileName}.part`);
|
|
406
|
+
const finalPath = join2(dir, fileName);
|
|
407
|
+
try {
|
|
408
|
+
await this.capture(tmpPath);
|
|
409
|
+
await rename2(tmpPath, finalPath);
|
|
410
|
+
} catch (err) {
|
|
411
|
+
await rm(tmpPath, { force: true }).catch(() => {
|
|
412
|
+
});
|
|
413
|
+
throw new SnapshotCaptureError(`screenshot capture failed for ${role}-snapshot: ${err instanceof Error ? err.message : String(err)}`);
|
|
414
|
+
}
|
|
415
|
+
const statInfo = await stat(finalPath);
|
|
416
|
+
const sha256 = await hashFile(finalPath);
|
|
417
|
+
const captureCompletedAtMonotonic = Date.now();
|
|
418
|
+
return {
|
|
419
|
+
fileName,
|
|
420
|
+
sha256,
|
|
421
|
+
bytes: statInfo.size,
|
|
422
|
+
captureStartedAtMonotonic,
|
|
423
|
+
captureCompletedAtMonotonic,
|
|
424
|
+
capturedAt: capturedAt.toISOString(),
|
|
425
|
+
role,
|
|
426
|
+
declaredAfterIntervalMs: declared.afterIntervalMs,
|
|
427
|
+
actualWaitMs: declared.waitStartMonotonic !== void 0 ? captureStartedAtMonotonic - declared.waitStartMonotonic : void 0
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
/** Capture the before-snapshot for an event (journal seq must be pre-allocated). */
|
|
431
|
+
async before(identity) {
|
|
432
|
+
return this.captureOne(identity, "before");
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Wait exactly `afterIntervalMs` from `dispatchCompletedAtMonotonic`, then
|
|
436
|
+
* capture the after-snapshot. The wait is exact per contract: no polling,
|
|
437
|
+
* no stability detection.
|
|
438
|
+
*/
|
|
439
|
+
async after(identity, dispatchCompletedAtMonotonic, afterIntervalMs) {
|
|
440
|
+
const target = dispatchCompletedAtMonotonic + afterIntervalMs;
|
|
441
|
+
const waitStartMonotonic = dispatchCompletedAtMonotonic;
|
|
442
|
+
await waitUntil(target);
|
|
443
|
+
return this.captureOne(identity, "after", { afterIntervalMs, waitStartMonotonic });
|
|
444
|
+
}
|
|
445
|
+
nextSeq() {
|
|
446
|
+
return ++this.seq;
|
|
447
|
+
}
|
|
448
|
+
setSeq(value) {
|
|
449
|
+
this.seq = Math.max(this.seq, value);
|
|
450
|
+
}
|
|
451
|
+
async close() {
|
|
452
|
+
}
|
|
453
|
+
};
|
|
454
|
+
function waitUntil(targetMonotonic) {
|
|
455
|
+
return new Promise((resolve2) => {
|
|
456
|
+
const tick = () => {
|
|
457
|
+
const remaining = targetMonotonic - Date.now();
|
|
458
|
+
if (remaining <= 0)
|
|
459
|
+
resolve2();
|
|
460
|
+
else
|
|
461
|
+
setTimeout(tick, Math.min(remaining, 250));
|
|
462
|
+
};
|
|
463
|
+
tick();
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
async function hashFile(path) {
|
|
467
|
+
const { readFile: readFile3 } = await import("node:fs/promises");
|
|
468
|
+
return createHash("sha256").update(await readFile3(path)).digest("hex");
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// node_modules/@wezzard/relay-driver-remote-runtime/dist/src/admission.js
|
|
472
|
+
var AdmissionRefusedError = class extends Error {
|
|
473
|
+
constructor(message2) {
|
|
474
|
+
super(message2);
|
|
475
|
+
this.name = "AdmissionRefusedError";
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
var HandleAlreadyUsedError = class extends Error {
|
|
479
|
+
actionId;
|
|
480
|
+
constructor(actionId) {
|
|
481
|
+
super(`action handle ${actionId} was already invoked; use a new handle for a deliberate retry`);
|
|
482
|
+
this.actionId = actionId;
|
|
483
|
+
this.name = "HandleAlreadyUsedError";
|
|
484
|
+
}
|
|
485
|
+
};
|
|
486
|
+
var EvidenceWriteError = class extends Error {
|
|
487
|
+
actionId;
|
|
488
|
+
toolOutcome;
|
|
489
|
+
constructor(actionId, toolOutcome, cause) {
|
|
490
|
+
super(`evidence retention failed for action ${actionId}; input is disabled`, { cause });
|
|
491
|
+
this.actionId = actionId;
|
|
492
|
+
this.toolOutcome = toolOutcome;
|
|
493
|
+
this.name = "EvidenceWriteError";
|
|
494
|
+
}
|
|
495
|
+
};
|
|
496
|
+
var AdmissionEngine = class {
|
|
497
|
+
store;
|
|
498
|
+
capture;
|
|
499
|
+
ids;
|
|
500
|
+
snapshotStore;
|
|
501
|
+
/** Set when any evidence write fails; input stays disabled for the session. */
|
|
502
|
+
evidenceFailed = false;
|
|
503
|
+
evidenceFailureDiagnostic;
|
|
504
|
+
lastSnapshots;
|
|
505
|
+
constructor(store, capture, ids, snapshotStore) {
|
|
506
|
+
this.store = store;
|
|
507
|
+
this.capture = capture;
|
|
508
|
+
this.ids = ids;
|
|
509
|
+
this.snapshotStore = snapshotStore;
|
|
510
|
+
}
|
|
511
|
+
/** Why input is currently disabled, or undefined when admission is possible. */
|
|
512
|
+
refusalReason() {
|
|
513
|
+
if (this.evidenceFailed) {
|
|
514
|
+
return `evidence retention previously failed: ${this.evidenceFailureDiagnostic}`;
|
|
515
|
+
}
|
|
516
|
+
return this.capture.checkAdmission();
|
|
517
|
+
}
|
|
518
|
+
get evidenceFailure() {
|
|
519
|
+
return this.evidenceFailureDiagnostic;
|
|
520
|
+
}
|
|
521
|
+
/** Snapshot evidence captured during the most recent call(). */
|
|
522
|
+
get actionSnapshots() {
|
|
523
|
+
return this.lastSnapshots;
|
|
524
|
+
}
|
|
525
|
+
allocateAction(params) {
|
|
526
|
+
const id = allocateId("action");
|
|
527
|
+
const actionId = formatId(id);
|
|
528
|
+
return actionId;
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* The full call sequence for one backend invocation. The callable runs in
|
|
532
|
+
* the caller's process; admission and retention happen here.
|
|
533
|
+
*/
|
|
534
|
+
async call(params, callable) {
|
|
535
|
+
const actionId = this.allocateAction(params);
|
|
536
|
+
return this.callWithHandle(actionId, params, callable);
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Resolve the snapshot plan for the params, or undefined when the action
|
|
540
|
+
* carries no snapshot evidence. Throws AdmissionRefusedError on contract
|
|
541
|
+
* violations — a missing required interval is a usage refusal BEFORE any
|
|
542
|
+
* dispatch (never an uncertain run).
|
|
543
|
+
*/
|
|
544
|
+
resolveSnapshotPlan(params, actionId) {
|
|
545
|
+
const p = params.snapshots;
|
|
546
|
+
if (!p)
|
|
547
|
+
return void 0;
|
|
548
|
+
if (!this.snapshotStore) {
|
|
549
|
+
throw new AdmissionRefusedError("snapshots requested but this engine has no snapshot store configured");
|
|
550
|
+
}
|
|
551
|
+
const identity = this.dispatchIdentityOf(actionId, params);
|
|
552
|
+
if (p.group) {
|
|
553
|
+
const groupId = p.group.groupId;
|
|
554
|
+
if (!groupId) {
|
|
555
|
+
throw new AdmissionRefusedError("coalescing group declared without groupId");
|
|
556
|
+
}
|
|
557
|
+
switch (p.group.phase) {
|
|
558
|
+
case "first":
|
|
559
|
+
return { capturesBefore: true, capturesAfter: false, role: "first", group: { groupId } };
|
|
560
|
+
case "member":
|
|
561
|
+
return { capturesBefore: false, capturesAfter: false, role: "member", group: { groupId } };
|
|
562
|
+
case "last": {
|
|
563
|
+
const interval = p.group.afterIntervalMs ?? p.afterIntervalMs;
|
|
564
|
+
if (typeof interval !== "number" || !Number.isFinite(interval) || interval < 0) {
|
|
565
|
+
throw new AdmissionRefusedError(`coalescing group ${groupId}: after-snapshot interval is required on the last member (agent-supplied per the snapshot contract)`);
|
|
566
|
+
}
|
|
567
|
+
return {
|
|
568
|
+
capturesBefore: false,
|
|
569
|
+
capturesAfter: { afterIntervalMs: interval },
|
|
570
|
+
role: "last",
|
|
571
|
+
group: { groupId }
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
default:
|
|
575
|
+
throw new AdmissionRefusedError(`coalescing group phase must be first|member|last, got: ${String(p.group.phase)}`);
|
|
576
|
+
}
|
|
577
|
+
void identity;
|
|
578
|
+
}
|
|
579
|
+
if (typeof p.afterIntervalMs !== "number" || !Number.isFinite(p.afterIntervalMs) || p.afterIntervalMs < 0) {
|
|
580
|
+
throw new AdmissionRefusedError("after-snapshot interval is required: supply afterIntervalMs (agent-supplied per the snapshot contract; the runtime never guesses)");
|
|
581
|
+
}
|
|
582
|
+
return {
|
|
583
|
+
capturesBefore: true,
|
|
584
|
+
capturesAfter: { afterIntervalMs: p.afterIntervalMs },
|
|
585
|
+
role: "single"
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
dispatchIdentityOf(actionId, params) {
|
|
589
|
+
if (params.dispatchIdentity)
|
|
590
|
+
return params.dispatchIdentity;
|
|
591
|
+
if (params.title)
|
|
592
|
+
return params.title;
|
|
593
|
+
if (params.stepId)
|
|
594
|
+
return params.stepId;
|
|
595
|
+
return actionId;
|
|
596
|
+
}
|
|
597
|
+
/** Call sequence for an existing handle identity. */
|
|
598
|
+
async callWithHandle(actionId, params, callable) {
|
|
599
|
+
if (this.evidenceFailed) {
|
|
600
|
+
throw new AdmissionRefusedError(this.refusalReason());
|
|
601
|
+
}
|
|
602
|
+
const existing = await this.store.getAction(actionId);
|
|
603
|
+
if (existing && existing.state !== "pending") {
|
|
604
|
+
throw new HandleAlreadyUsedError(actionId);
|
|
605
|
+
}
|
|
606
|
+
const refusal = this.capture.checkAdmission();
|
|
607
|
+
if (refusal) {
|
|
608
|
+
await this.store.putAction({
|
|
609
|
+
actionId,
|
|
610
|
+
sessionId: this.ids.sessionId,
|
|
611
|
+
attemptId: this.ids.attemptId,
|
|
612
|
+
stepId: params.stepId,
|
|
613
|
+
state: "refused",
|
|
614
|
+
title: params.title,
|
|
615
|
+
inputMode: params.inputMode,
|
|
616
|
+
executionId: params.parentExecutionId,
|
|
617
|
+
evidenceStatus: "not-applicable"
|
|
618
|
+
});
|
|
619
|
+
await this.store.appendJournal({
|
|
620
|
+
kind: "action-refusal",
|
|
621
|
+
sessionId: this.ids.sessionId,
|
|
622
|
+
attemptId: this.ids.attemptId,
|
|
623
|
+
actionId,
|
|
624
|
+
state: "refused",
|
|
625
|
+
diagnostic: refusal
|
|
626
|
+
});
|
|
627
|
+
throw new AdmissionRefusedError(refusal);
|
|
628
|
+
}
|
|
629
|
+
let snapPlan;
|
|
630
|
+
try {
|
|
631
|
+
snapPlan = this.resolveSnapshotPlan(params, actionId);
|
|
632
|
+
} catch (err) {
|
|
633
|
+
if (err instanceof AdmissionRefusedError) {
|
|
634
|
+
await this.store.putAction({
|
|
635
|
+
actionId,
|
|
636
|
+
sessionId: this.ids.sessionId,
|
|
637
|
+
attemptId: this.ids.attemptId,
|
|
638
|
+
stepId: params.stepId,
|
|
639
|
+
state: "refused",
|
|
640
|
+
title: params.title,
|
|
641
|
+
inputMode: params.inputMode,
|
|
642
|
+
executionId: params.parentExecutionId,
|
|
643
|
+
evidenceStatus: "not-applicable"
|
|
644
|
+
});
|
|
645
|
+
await this.store.appendJournal({
|
|
646
|
+
kind: "action-refusal",
|
|
647
|
+
sessionId: this.ids.sessionId,
|
|
648
|
+
attemptId: this.ids.attemptId,
|
|
649
|
+
actionId,
|
|
650
|
+
state: "refused",
|
|
651
|
+
diagnostic: err.message
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
throw err;
|
|
655
|
+
}
|
|
656
|
+
this.lastSnapshots = void 0;
|
|
657
|
+
await this.store.putAction({
|
|
658
|
+
actionId,
|
|
659
|
+
sessionId: this.ids.sessionId,
|
|
660
|
+
attemptId: this.ids.attemptId,
|
|
661
|
+
stepId: params.stepId,
|
|
662
|
+
state: "pending",
|
|
663
|
+
title: params.title,
|
|
664
|
+
inputMode: params.inputMode,
|
|
665
|
+
executionId: params.parentExecutionId
|
|
666
|
+
});
|
|
667
|
+
let toolOutcome;
|
|
668
|
+
try {
|
|
669
|
+
await this.store.retainActionStart({
|
|
670
|
+
actionId,
|
|
671
|
+
sessionId: this.ids.sessionId,
|
|
672
|
+
attemptId: this.ids.attemptId,
|
|
673
|
+
stepId: params.stepId,
|
|
674
|
+
title: params.title,
|
|
675
|
+
inputMode: params.inputMode,
|
|
676
|
+
executionId: params.parentExecutionId,
|
|
677
|
+
snapshots: snapPlan ? { plan: snapPlan } : void 0
|
|
678
|
+
});
|
|
679
|
+
const snapshots = [];
|
|
680
|
+
if (snapPlan?.capturesBefore && this.snapshotStore) {
|
|
681
|
+
const identity = {
|
|
682
|
+
journalSeq: this.snapshotStore.nextSeq(),
|
|
683
|
+
dispatchIdentity: this.dispatchIdentityOf(actionId, params),
|
|
684
|
+
sessionId: this.ids.sessionId,
|
|
685
|
+
attemptId: this.ids.attemptId
|
|
686
|
+
};
|
|
687
|
+
let before;
|
|
688
|
+
try {
|
|
689
|
+
before = await this.snapshotStore.before(identity);
|
|
690
|
+
} catch (err) {
|
|
691
|
+
if (err instanceof SnapshotCaptureError) {
|
|
692
|
+
throw new AdmissionRefusedError(err.message);
|
|
693
|
+
}
|
|
694
|
+
throw err;
|
|
695
|
+
}
|
|
696
|
+
snapshots.push(before);
|
|
697
|
+
await this.store.appendJournal({
|
|
698
|
+
kind: "snapshot-captured",
|
|
699
|
+
sessionId: this.ids.sessionId,
|
|
700
|
+
attemptId: this.ids.attemptId,
|
|
701
|
+
actionId,
|
|
702
|
+
state: "recorded",
|
|
703
|
+
snapshot: before,
|
|
704
|
+
group: snapPlan.group?.groupId
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
let value;
|
|
708
|
+
try {
|
|
709
|
+
value = await callable();
|
|
710
|
+
toolOutcome = { kind: "success", value };
|
|
711
|
+
} catch (err) {
|
|
712
|
+
toolOutcome = { kind: "failure", error: err };
|
|
713
|
+
value = void 0;
|
|
714
|
+
}
|
|
715
|
+
const dispatchCompletedAtMonotonic = Date.now();
|
|
716
|
+
if (snapPlan?.capturesAfter && this.snapshotStore) {
|
|
717
|
+
const identity = {
|
|
718
|
+
journalSeq: this.snapshotStore.nextSeq(),
|
|
719
|
+
dispatchIdentity: this.dispatchIdentityOf(actionId, params),
|
|
720
|
+
sessionId: this.ids.sessionId,
|
|
721
|
+
attemptId: this.ids.attemptId
|
|
722
|
+
};
|
|
723
|
+
try {
|
|
724
|
+
const after = await this.snapshotStore.after(identity, dispatchCompletedAtMonotonic, snapPlan.capturesAfter.afterIntervalMs);
|
|
725
|
+
snapshots.push(after);
|
|
726
|
+
await this.store.appendJournal({
|
|
727
|
+
kind: "snapshot-captured",
|
|
728
|
+
sessionId: this.ids.sessionId,
|
|
729
|
+
attemptId: this.ids.attemptId,
|
|
730
|
+
actionId,
|
|
731
|
+
state: "recorded",
|
|
732
|
+
snapshot: after,
|
|
733
|
+
group: snapPlan.group?.groupId
|
|
734
|
+
});
|
|
735
|
+
} catch (err) {
|
|
736
|
+
if (err instanceof SnapshotCaptureError) {
|
|
737
|
+
const diag = err instanceof Error ? err.message : String(err);
|
|
738
|
+
await this.store.appendJournal({
|
|
739
|
+
kind: "capture-status",
|
|
740
|
+
sessionId: this.ids.sessionId,
|
|
741
|
+
attemptId: this.ids.attemptId,
|
|
742
|
+
actionId,
|
|
743
|
+
state: "incomplete",
|
|
744
|
+
diagnostic: diag
|
|
745
|
+
}).catch(() => {
|
|
746
|
+
});
|
|
747
|
+
} else {
|
|
748
|
+
throw err;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
if (snapPlan) {
|
|
753
|
+
this.lastSnapshots = snapshots;
|
|
754
|
+
await this.store.retainActionSnapshots(actionId, snapshots, snapPlan);
|
|
755
|
+
}
|
|
756
|
+
} catch (err) {
|
|
757
|
+
if (err instanceof AdmissionRefusedError) {
|
|
758
|
+
await this.retainRefusalAfterStart(actionId, err);
|
|
759
|
+
throw err;
|
|
760
|
+
}
|
|
761
|
+
if (err instanceof EvidenceWriteError) {
|
|
762
|
+
throw err;
|
|
763
|
+
}
|
|
764
|
+
toolOutcome = { kind: "failure", error: err };
|
|
765
|
+
}
|
|
766
|
+
try {
|
|
767
|
+
await this.store.retainActionCompletion({
|
|
768
|
+
actionId,
|
|
769
|
+
toolOutcome: serializeOutcome(toolOutcome)
|
|
770
|
+
});
|
|
771
|
+
} catch (err) {
|
|
772
|
+
this.evidenceFailed = true;
|
|
773
|
+
this.evidenceFailureDiagnostic = String(err);
|
|
774
|
+
await this.store.appendJournal({
|
|
775
|
+
kind: "evidence-failure",
|
|
776
|
+
sessionId: this.ids.sessionId,
|
|
777
|
+
attemptId: this.ids.attemptId,
|
|
778
|
+
actionId,
|
|
779
|
+
state: "incomplete",
|
|
780
|
+
diagnostic: String(err)
|
|
781
|
+
}).catch(() => {
|
|
782
|
+
});
|
|
783
|
+
throw new EvidenceWriteError(actionId, toolOutcome, err);
|
|
784
|
+
}
|
|
785
|
+
if (toolOutcome.kind === "failure") {
|
|
786
|
+
throw toolOutcome.error;
|
|
787
|
+
}
|
|
788
|
+
return toolOutcome.value;
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* Retain the refusal of an action whose start was already retained. A
|
|
792
|
+
* failure to retain it is an evidence failure: input is disabled (D17).
|
|
793
|
+
*/
|
|
794
|
+
async retainRefusalAfterStart(actionId, refusal) {
|
|
795
|
+
try {
|
|
796
|
+
await this.store.retainActionRefusal({ actionId, diagnostic: refusal.message });
|
|
797
|
+
} catch (err) {
|
|
798
|
+
this.evidenceFailed = true;
|
|
799
|
+
this.evidenceFailureDiagnostic = String(err);
|
|
800
|
+
await this.store.appendJournal({
|
|
801
|
+
kind: "evidence-failure",
|
|
802
|
+
sessionId: this.ids.sessionId,
|
|
803
|
+
attemptId: this.ids.attemptId,
|
|
804
|
+
actionId,
|
|
805
|
+
state: "incomplete",
|
|
806
|
+
diagnostic: String(err)
|
|
807
|
+
}).catch(() => {
|
|
808
|
+
});
|
|
809
|
+
throw new EvidenceWriteError(actionId, { kind: "refused", diagnostic: refusal.message }, err);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
};
|
|
813
|
+
function serializeOutcome(outcome) {
|
|
814
|
+
if (outcome && typeof outcome === "object" && "kind" in outcome) {
|
|
815
|
+
const o = outcome;
|
|
816
|
+
if (o.kind === "success")
|
|
817
|
+
return { kind: "success", value: describe(o.value) };
|
|
818
|
+
if (o.kind === "failure")
|
|
819
|
+
return { kind: "failure", error: describe(o.error) };
|
|
820
|
+
}
|
|
821
|
+
return describe(outcome);
|
|
822
|
+
}
|
|
823
|
+
function describe(value) {
|
|
824
|
+
if (value instanceof Error) {
|
|
825
|
+
return { errorName: value.name, message: value.message };
|
|
826
|
+
}
|
|
827
|
+
return value;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
// src/guest/image-evidence.ts
|
|
831
|
+
var safeId = (value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,159}$/.test(value);
|
|
832
|
+
function afterRequested(request) {
|
|
833
|
+
return !(request?.kind === "exec" && request.diagnostic === true) && request?.capture !== false && !["first", "member"].includes(request?.snapshots?.group?.phase ?? "");
|
|
834
|
+
}
|
|
835
|
+
function validateImageEvidence(value, request, authoritativeSnapshots) {
|
|
836
|
+
const fail = () => {
|
|
837
|
+
throw new Error("invalid image evidence");
|
|
838
|
+
};
|
|
839
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) fail();
|
|
840
|
+
const evidence = value;
|
|
841
|
+
if (!["available", "not-requested", "capture-failed", "capture-unknown"].includes(evidence.status) || !Array.isArray(evidence.snapshots) || evidence.snapshots.length > 2) fail();
|
|
842
|
+
const group = request.snapshots?.group;
|
|
843
|
+
const phases = /* @__PURE__ */ new Set();
|
|
844
|
+
let actionId;
|
|
845
|
+
for (const s of evidence.snapshots) {
|
|
846
|
+
if (!s || typeof s !== "object" || Array.isArray(s) || s.sessionId !== request.sessionId || s.attemptId !== request.attemptId || s.executionId !== request.executionId || !safeId(s.actionId) || s.stepId !== request.step?.id || s.groupId !== group?.groupId || !["before", "after"].includes(s.phase) || phases.has(s.phase) || actionId !== void 0 && actionId !== s.actionId || typeof s.capturedAt !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(s.capturedAt) || !Number.isFinite(Date.parse(s.capturedAt)) || typeof s.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(s.sha256) || !Number.isSafeInteger(s.bytes) || s.bytes < 1 || s.bytes > 64 * 1024 * 1024 || s.mimeType !== "image/png" || typeof s.fileName !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.-]*\.png$/.test(s.fileName) || s.fileName.length > 255 || request.diagnostic === true || request.capture === false || s.phase === "before" && group && group.phase !== "first" || s.phase === "after" && !afterRequested(request) || s.declaredAfterIntervalMs !== (s.phase === "after" ? group?.afterIntervalMs ?? request.snapshots?.afterIntervalMs : void 0)) fail();
|
|
847
|
+
phases.add(s.phase);
|
|
848
|
+
actionId = s.actionId;
|
|
849
|
+
}
|
|
850
|
+
if (evidence.status === "not-requested" !== !afterRequested(request) || evidence.status === "available" !== phases.has("after")) fail();
|
|
851
|
+
if (authoritativeSnapshots !== void 0) {
|
|
852
|
+
if (authoritativeSnapshots.length !== evidence.snapshots.length) fail();
|
|
853
|
+
const fields = ["sessionId", "attemptId", "executionId", "actionId", "stepId", "phase", "capturedAt", "sha256", "bytes", "mimeType", "declaredAfterIntervalMs", "fileName", "groupId"];
|
|
854
|
+
for (const s of evidence.snapshots) {
|
|
855
|
+
const original = authoritativeSnapshots.find((record) => record.phase === s.phase);
|
|
856
|
+
if (!original || fields.some((field) => original[field] !== s[field])) fail();
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
// src/guest/receiver.ts
|
|
862
|
+
var MAX_REQUEST_BYTES = 1024 * 1024;
|
|
863
|
+
var MAX_OUTPUT_BYTES = 64 * 1024;
|
|
864
|
+
var MAX_INTERVAL_MS = 3e5;
|
|
865
|
+
var MAX_TIMEOUT_MS = 36e5;
|
|
866
|
+
var MAX_SCRIPT_BYTES = 8 * 1024 * 1024;
|
|
867
|
+
var message = (error) => error instanceof Error ? error.message : String(error);
|
|
868
|
+
var hash = (bytes) => createHash2("sha256").update(bytes).digest("hex");
|
|
869
|
+
var text = (value) => typeof value === "string" && value.length > 0 && !value.includes("\0");
|
|
870
|
+
var bounded = (value = "") => {
|
|
871
|
+
const bytes = Buffer.from(value);
|
|
872
|
+
if (bytes.length <= MAX_OUTPUT_BYTES) return value;
|
|
873
|
+
return new TextDecoder().decode(bytes.subarray(0, MAX_OUTPUT_BYTES), { stream: true });
|
|
874
|
+
};
|
|
875
|
+
async function durableJson(path, data) {
|
|
876
|
+
await mkdir3(dirname2(path), { recursive: true });
|
|
877
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
878
|
+
const file = await open(temporary, "wx", 384);
|
|
879
|
+
try {
|
|
880
|
+
await file.writeFile(JSON.stringify(data));
|
|
881
|
+
await file.sync();
|
|
882
|
+
} finally {
|
|
883
|
+
await file.close();
|
|
884
|
+
}
|
|
885
|
+
await rename3(temporary, path);
|
|
886
|
+
const directory = await open(dirname2(path), "r");
|
|
887
|
+
try {
|
|
888
|
+
await directory.sync();
|
|
889
|
+
} finally {
|
|
890
|
+
await directory.close();
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
async function optionalJson(path) {
|
|
894
|
+
try {
|
|
895
|
+
return JSON.parse(await readFile2(path, "utf8"));
|
|
896
|
+
} catch (error) {
|
|
897
|
+
if (error.code === "ENOENT") return void 0;
|
|
898
|
+
throw error;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
function validate(request) {
|
|
902
|
+
if (!safeId(request.executionId) || !safeId(request.sessionId) || !safeId(request.attemptId)) throw new Error("safe executionId, sessionId and attemptId are required");
|
|
903
|
+
if (typeof request.because !== "string" || !request.because.trim() || request.because.length > 16384) throw new Error("nonblank because is required (maximum 16384 characters)");
|
|
904
|
+
if (!["exec", "script", "code"].includes(request.kind)) throw new Error("kind must be exec, script or code");
|
|
905
|
+
if (request.cwd !== void 0 && (!text(request.cwd) || !isAbsolute(request.cwd))) throw new Error("cwd must be an absolute path");
|
|
906
|
+
if (request.timeoutMs !== void 0 && (!Number.isInteger(request.timeoutMs) || request.timeoutMs < 1 || request.timeoutMs > MAX_TIMEOUT_MS)) throw new Error("timeoutMs must be an integer from 1 to 3600000");
|
|
907
|
+
if (request.diagnostic !== void 0 && (typeof request.diagnostic !== "boolean" || request.kind !== "exec")) throw new Error("diagnostic is allowed only for exec and must be boolean");
|
|
908
|
+
if (request.step !== void 0 && (!request.step || !safeId(request.step.id) || !text(request.step.title) || request.step.expected !== void 0 && typeof request.step.expected !== "string" || request.step.inputMode !== void 0 && !["ordinary", "accessibility"].includes(request.step.inputMode))) throw new Error("invalid step metadata");
|
|
909
|
+
const snapshots = request.snapshots;
|
|
910
|
+
if (!snapshots || typeof snapshots !== "object" || Array.isArray(snapshots)) throw new Error("snapshots are required; no implicit interval");
|
|
911
|
+
const interval = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0 && n <= MAX_INTERVAL_MS;
|
|
912
|
+
if (snapshots.afterIntervalMs !== void 0 && !interval(snapshots.afterIntervalMs)) throw new Error("invalid afterIntervalMs (0..300000 required)");
|
|
913
|
+
if (snapshots.group !== void 0) {
|
|
914
|
+
const group = snapshots.group;
|
|
915
|
+
if (!group || !safeId(group.groupId) || !["first", "member", "last"].includes(group.phase)) throw new Error("invalid coalescing group");
|
|
916
|
+
if (group.afterIntervalMs !== void 0 && !interval(group.afterIntervalMs)) throw new Error("invalid group afterIntervalMs");
|
|
917
|
+
if (group.phase === "last" && !interval(group.afterIntervalMs ?? snapshots.afterIntervalMs)) throw new Error("last group member requires afterIntervalMs");
|
|
918
|
+
} else if (!interval(snapshots.afterIntervalMs)) throw new Error("afterIntervalMs is required; no default");
|
|
919
|
+
if (request.kind !== "code" && (!Array.isArray(request.argv) || request.argv.length === 0 || request.argv.length > 256 || !request.argv.every((arg, index) => typeof arg === "string" && !arg.includes("\0") && (index > 0 || arg.length > 0)))) throw new Error("argv must be a nonempty string vector without NULs (maximum 256 entries)");
|
|
920
|
+
if (request.kind !== "exec" && !["javascript", "typescript", "python"].includes(request.language ?? "")) throw new Error("script/code language is required");
|
|
921
|
+
if (request.kind === "code" && (typeof request.code !== "string" || !/^[a-f0-9]{64}$/.test(request.codeSha256 ?? ""))) throw new Error("code and its SHA-256 are required");
|
|
922
|
+
if (request.capture !== void 0 && typeof request.capture !== "boolean") throw new Error("capture must be boolean");
|
|
923
|
+
if (request.kind === "script" && (!text(request.remotePath) || !isAbsolute(request.remotePath) || !/^[a-f0-9]{64}$/.test(request.scriptSha256 ?? ""))) throw new Error("absolute remotePath and script SHA-256 are required");
|
|
924
|
+
}
|
|
925
|
+
function groupAbsentFromProcessTable(group, table) {
|
|
926
|
+
const lines = table.split("\n").map((line) => line.trim()).filter(Boolean);
|
|
927
|
+
if (!lines.length) throw new Error("Empty process table cannot prove group absence");
|
|
928
|
+
const entries = lines.map((line) => {
|
|
929
|
+
const match = /^(\d+)\s+(\d+)\s+(\S+)$/.exec(line);
|
|
930
|
+
if (!match || Number(match[1]) < 0 || Number(match[2]) < 1) throw new Error("Malformed process table");
|
|
931
|
+
return { group: Number(match[1]), pid: Number(match[2]) };
|
|
932
|
+
});
|
|
933
|
+
if (!entries.some((entry) => entry.pid === process.pid)) throw new Error("Process table lacks receiver identity");
|
|
934
|
+
return !entries.some((entry) => entry.group === group);
|
|
935
|
+
}
|
|
936
|
+
async function darwinGroupAbsent(group) {
|
|
937
|
+
return new Promise((resolve2) => {
|
|
938
|
+
execFile("/bin/ps", ["-axo", "pgid=,pid=,stat="], { encoding: "utf8", timeout: 1e3, maxBuffer: 1024 * 1024 }, (error, stdout) => {
|
|
939
|
+
if (error) {
|
|
940
|
+
resolve2(void 0);
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
try {
|
|
944
|
+
resolve2(groupAbsentFromProcessTable(group, stdout));
|
|
945
|
+
} catch {
|
|
946
|
+
resolve2(void 0);
|
|
947
|
+
}
|
|
948
|
+
});
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
async function confirmProcessGroupExit(pid, options = {}) {
|
|
952
|
+
const clock = options.clock ?? (() => performance.now());
|
|
953
|
+
const pause = options.pause ?? ((ms) => new Promise((resolve2) => setTimeout(resolve2, ms)));
|
|
954
|
+
const probe = options.probe ?? ((group) => {
|
|
955
|
+
process.kill(-group, 0);
|
|
956
|
+
});
|
|
957
|
+
const deadline = clock() + (options.timeoutMs ?? 1e3);
|
|
958
|
+
for (; ; ) {
|
|
959
|
+
try {
|
|
960
|
+
probe(pid);
|
|
961
|
+
} catch (error) {
|
|
962
|
+
const code = error.code;
|
|
963
|
+
if (code === "ESRCH") return true;
|
|
964
|
+
const observer = options.permissionObserver ?? (process.platform === "darwin" ? darwinGroupAbsent : void 0);
|
|
965
|
+
if (code !== "EPERM" || !observer) return void 0;
|
|
966
|
+
const absent = await observer(pid);
|
|
967
|
+
if (absent !== false) return absent;
|
|
968
|
+
}
|
|
969
|
+
const remaining = deadline - clock();
|
|
970
|
+
if (remaining <= 0) return false;
|
|
971
|
+
await pause(Math.min(25, remaining));
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
async function runArgv(argv, options, onSpawn) {
|
|
975
|
+
return new Promise((done) => {
|
|
976
|
+
const child = spawn(argv[0], argv.slice(1), { cwd: options.cwd, env: options.env, shell: false, detached: true, stdio: ["ignore", "pipe", "pipe"] });
|
|
977
|
+
const chunks = { stdout: [], stderr: [] };
|
|
978
|
+
let bytes = 0, timedOut = false, outputTruncated = false, spawnError;
|
|
979
|
+
const stop = () => {
|
|
980
|
+
if (child.pid) {
|
|
981
|
+
try {
|
|
982
|
+
process.kill(-child.pid, "SIGKILL");
|
|
983
|
+
} catch {
|
|
984
|
+
child.kill("SIGKILL");
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
};
|
|
988
|
+
const collect = (stream, chunk) => {
|
|
989
|
+
const available = Math.max(0, MAX_OUTPUT_BYTES - bytes);
|
|
990
|
+
if (available) chunks[stream].push(chunk.subarray(0, available));
|
|
991
|
+
bytes += chunk.length;
|
|
992
|
+
if (bytes > MAX_OUTPUT_BYTES) {
|
|
993
|
+
outputTruncated = true;
|
|
994
|
+
stop();
|
|
995
|
+
}
|
|
996
|
+
};
|
|
997
|
+
const identityRetained = child.pid && onSpawn ? onSpawn(child.pid).catch((error) => {
|
|
998
|
+
spawnError = `process identity retention failed: ${message(error)}`;
|
|
999
|
+
stop();
|
|
1000
|
+
}) : Promise.resolve();
|
|
1001
|
+
child.stdout.on("data", (c) => collect("stdout", c));
|
|
1002
|
+
child.stderr.on("data", (c) => collect("stderr", c));
|
|
1003
|
+
const timer = setTimeout(() => {
|
|
1004
|
+
timedOut = true;
|
|
1005
|
+
stop();
|
|
1006
|
+
}, options.timeoutMs);
|
|
1007
|
+
child.on("error", (error) => {
|
|
1008
|
+
spawnError = message(error);
|
|
1009
|
+
});
|
|
1010
|
+
child.on("close", async (code, signal) => {
|
|
1011
|
+
clearTimeout(timer);
|
|
1012
|
+
await identityRetained;
|
|
1013
|
+
stop();
|
|
1014
|
+
let terminationConfirmed, terminationDiagnostic;
|
|
1015
|
+
if (child.pid) terminationConfirmed = await confirmProcessGroupExit(child.pid, { probe: (pid) => {
|
|
1016
|
+
try {
|
|
1017
|
+
process.kill(-pid, 0);
|
|
1018
|
+
} catch (error) {
|
|
1019
|
+
if (error.code !== "ESRCH") terminationDiagnostic = `process group ${pid}: ${error.code ?? message(error)}`;
|
|
1020
|
+
throw error;
|
|
1021
|
+
}
|
|
1022
|
+
} });
|
|
1023
|
+
else if (spawnError) terminationConfirmed = true;
|
|
1024
|
+
done({ terminationConfirmed, terminationDiagnostic, exitStatus: { code, signal }, stdout: Buffer.concat(chunks.stdout).toString("utf8"), stderr: Buffer.concat(chunks.stderr).toString("utf8"), timedOut, outputTruncated, spawnError });
|
|
1025
|
+
});
|
|
1026
|
+
});
|
|
1027
|
+
}
|
|
1028
|
+
async function captureWithDriver(outFile, driver, dispatch = runArgv) {
|
|
1029
|
+
const result = await dispatch([driver, "call", "get_desktop_state", "--json", JSON.stringify({ screenshot_out_file: outFile })], { env: process.env, timeoutMs: 6e4 });
|
|
1030
|
+
if (result.exitStatus.code !== 0 || result.timedOut || result.outputTruncated || result.spawnError || result.terminationConfirmed !== true) throw new Error(`display capture unavailable: ${JSON.stringify({ exitStatus: result.exitStatus, timedOut: result.timedOut, outputTruncated: result.outputTruncated, spawnError: result.spawnError, terminationConfirmed: result.terminationConfirmed, terminationDiagnostic: result.terminationDiagnostic, stdout: result.stdout?.slice(0, 1500), stderr: result.stderr?.slice(0, 1500) })}`);
|
|
1031
|
+
const value = JSON.parse(result.stdout ?? "");
|
|
1032
|
+
if (value.screenshot_file_path !== outFile) throw new Error("display capture returned a missing or mismatched screenshot_file_path");
|
|
1033
|
+
}
|
|
1034
|
+
async function receive(input, options = {}) {
|
|
1035
|
+
const request = input;
|
|
1036
|
+
const executionId = request && safeId(request.executionId) ? request.executionId : "unknown";
|
|
1037
|
+
const evidenceMode = request?.kind === "exec" && request.diagnostic === true ? "diagnostic" : void 0;
|
|
1038
|
+
const uncaptured = request?.capture === false;
|
|
1039
|
+
const timeoutMs = request?.timeoutMs ?? 12e4;
|
|
1040
|
+
let imageEvidence = { status: afterRequested(request) ? "capture-unknown" : "not-requested", snapshots: [] };
|
|
1041
|
+
const response = (kind, diagnostic) => ({ executionId, evidenceMode, timeoutMs, imageEvidence, outcome: { kind, diagnostic: bounded(diagnostic) } });
|
|
1042
|
+
let encoded;
|
|
1043
|
+
try {
|
|
1044
|
+
encoded = JSON.stringify(input);
|
|
1045
|
+
if (!encoded || Buffer.byteLength(encoded) > MAX_REQUEST_BYTES) return response("refused", "request exceeds maximum size or is not JSON");
|
|
1046
|
+
} catch {
|
|
1047
|
+
return response("refused", "request is not serializable JSON");
|
|
1048
|
+
}
|
|
1049
|
+
if (!request || !safeId(request.executionId) || !safeId(request.sessionId) || !safeId(request.attemptId)) return response("refused", "safe executionId, sessionId and attemptId are required");
|
|
1050
|
+
const root = resolve(options.root ?? process.env.RELAY_RUNTIME_ROOT ?? "/var/tmp/relay-driver-runtime");
|
|
1051
|
+
const state = join3(root, "state");
|
|
1052
|
+
const lock = join3(root, ".receiver-lock");
|
|
1053
|
+
const receiptPath = join3(state, "receiver", "receipts", `${executionId}.json`);
|
|
1054
|
+
const startedPath = join3(state, "receiver", "started", `${executionId}.json`);
|
|
1055
|
+
const groupPath = join3(state, "receiver", "groups.json");
|
|
1056
|
+
let store, ownsLock = false, keepLock = false;
|
|
1057
|
+
const ownerPath = join3(lock, "owner.json");
|
|
1058
|
+
const operationPids = [];
|
|
1059
|
+
let pendingSpawn = false;
|
|
1060
|
+
const markLock = (active, settled = false) => durableJson(ownerPath, { pid: process.pid, executionId, active, operationPids, pendingSpawn, settled });
|
|
1061
|
+
const runOwned = async (argv, dispatchOptions) => {
|
|
1062
|
+
pendingSpawn = true;
|
|
1063
|
+
await markLock(true);
|
|
1064
|
+
const result = await runArgv(argv, dispatchOptions, async (pid) => {
|
|
1065
|
+
operationPids.push(pid);
|
|
1066
|
+
pendingSpawn = false;
|
|
1067
|
+
await markLock(true);
|
|
1068
|
+
});
|
|
1069
|
+
if (result.terminationConfirmed === true) pendingSpawn = false;
|
|
1070
|
+
if (result.terminationConfirmed !== true) keepLock = true;
|
|
1071
|
+
if (!keepLock) await markLock(false);
|
|
1072
|
+
return result;
|
|
1073
|
+
};
|
|
1074
|
+
let reconcileGroup;
|
|
1075
|
+
let dispatchResult;
|
|
1076
|
+
const output = () => dispatchResult ? { stdout: bounded(dispatchResult.stdout), stderr: bounded(dispatchResult.stderr), timedOut: !!dispatchResult.timedOut, outputTruncated: !!dispatchResult.outputTruncated, terminationConfirmed: dispatchResult.terminationConfirmed } : {};
|
|
1077
|
+
try {
|
|
1078
|
+
await mkdir3(root, { recursive: true });
|
|
1079
|
+
const receipt = await optionalJson(receiptPath);
|
|
1080
|
+
if (receipt) return receipt;
|
|
1081
|
+
if (await optionalJson(startedPath)) return response("uncertain", "execution was already started; it will not be replayed");
|
|
1082
|
+
try {
|
|
1083
|
+
await mkdir3(lock);
|
|
1084
|
+
ownsLock = true;
|
|
1085
|
+
} catch (error) {
|
|
1086
|
+
if (error.code !== "EEXIST") throw error;
|
|
1087
|
+
const owner = await optionalJson(ownerPath);
|
|
1088
|
+
const absent = (pid, group2 = false) => {
|
|
1089
|
+
if (!Number.isInteger(pid) || !pid || pid < 1) return false;
|
|
1090
|
+
try {
|
|
1091
|
+
process.kill(group2 ? -pid : pid, 0);
|
|
1092
|
+
return false;
|
|
1093
|
+
} catch (error2) {
|
|
1094
|
+
return error2.code === "ESRCH";
|
|
1095
|
+
}
|
|
1096
|
+
};
|
|
1097
|
+
if (!owner || !absent(owner.pid) && owner.settled !== true || owner.active !== false && !(owner.pendingSpawn === false && Array.isArray(owner.operationPids) && owner.operationPids.length > 0 && owner.operationPids.every((pid) => absent(pid, true)))) return response("uncertain", "receiver lock ownership or active operation is unconfirmed; input is not replayed");
|
|
1098
|
+
try {
|
|
1099
|
+
await mkdir3(join3(lock, "recovery"));
|
|
1100
|
+
} catch {
|
|
1101
|
+
return response("uncertain", "receiver lock reconciliation is already in progress");
|
|
1102
|
+
}
|
|
1103
|
+
if (JSON.stringify(await optionalJson(ownerPath)) !== JSON.stringify(owner)) return response("uncertain", "receiver lock changed during reconciliation");
|
|
1104
|
+
await rename3(lock, join3(root, `.receiver-lock-retired-${randomUUID()}`));
|
|
1105
|
+
try {
|
|
1106
|
+
await mkdir3(lock);
|
|
1107
|
+
ownsLock = true;
|
|
1108
|
+
} catch {
|
|
1109
|
+
return response("uncertain", "receiver acquired by another operation during reconciliation");
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
await markLock(false);
|
|
1113
|
+
const recovered = await optionalJson(receiptPath);
|
|
1114
|
+
if (recovered) return recovered;
|
|
1115
|
+
if (await optionalJson(startedPath)) return response("uncertain", "execution was already started; it will not be replayed");
|
|
1116
|
+
store = await RecordStore.create(state);
|
|
1117
|
+
const history = await store.journalHistory();
|
|
1118
|
+
if (history.damagedTail) throw new Error("damaged journal; execution requires recording recovery without modifying prior evidence");
|
|
1119
|
+
await durableJson(startedPath, { executionId, requestSha256: hash(encoded) });
|
|
1120
|
+
const ids = { sessionId: request.sessionId, attemptId: request.attemptId };
|
|
1121
|
+
await store.appendJournal({ kind: "annotation", annotationType: "routing-decision", ...ids, executionId, state: "pending", because: request.because, step: request.step, evidenceMode, timeoutMs, ...uncaptured ? { capture: false } : {} }, { durable: true });
|
|
1122
|
+
const gate = new CaptureGate();
|
|
1123
|
+
let captureFailure;
|
|
1124
|
+
const capture = async (out) => {
|
|
1125
|
+
try {
|
|
1126
|
+
pendingSpawn = true;
|
|
1127
|
+
await markLock(true);
|
|
1128
|
+
await (options.capture ?? ((file2) => captureWithDriver(file2, options.cuaDriver ?? process.env.RELAY_CUA_DRIVER ?? (process.platform === "darwin" ? "/Applications/CuaDriver.app/Contents/MacOS/cua-driver" : "cua-driver"), runOwned)))(out);
|
|
1129
|
+
if (!keepLock) {
|
|
1130
|
+
pendingSpawn = false;
|
|
1131
|
+
await markLock(false);
|
|
1132
|
+
}
|
|
1133
|
+
const file = await stat2(out);
|
|
1134
|
+
if (!file.isFile() || file.size < 1 || file.size > 64 * 1024 * 1024) throw new Error("screenshot file missing, empty or oversized");
|
|
1135
|
+
} catch (error) {
|
|
1136
|
+
captureFailure = message(error);
|
|
1137
|
+
gate.reportLoss(captureFailure);
|
|
1138
|
+
throw error;
|
|
1139
|
+
}
|
|
1140
|
+
};
|
|
1141
|
+
const snapshots = new SnapshotStore(capture, store, state);
|
|
1142
|
+
snapshots.setSeq(history.records.length + 1);
|
|
1143
|
+
const engine = new AdmissionEngine(store, gate, ids, snapshots);
|
|
1144
|
+
const params = { parentExecutionId: executionId, stepId: request.step?.id, title: request.step?.title, inputMode: request.step?.inputMode ?? "ordinary", snapshots: evidenceMode || uncaptured ? void 0 : request.snapshots, dispatchIdentity: executionId };
|
|
1145
|
+
const actionId = engine.allocateAction(params);
|
|
1146
|
+
const retain = async (result) => {
|
|
1147
|
+
const retained = await store.journalHistory();
|
|
1148
|
+
const descriptors = [];
|
|
1149
|
+
if (!retained.damagedTail) {
|
|
1150
|
+
for (const record of retained.records) {
|
|
1151
|
+
if (record.kind !== "snapshot-captured" || record.actionId !== actionId) continue;
|
|
1152
|
+
const event = record;
|
|
1153
|
+
if (event.sessionId !== request.sessionId || event.attemptId !== request.attemptId) throw new Error("snapshot identity conflicts with request");
|
|
1154
|
+
const s = event.snapshot;
|
|
1155
|
+
descriptors.push({ sessionId: event.sessionId, attemptId: event.attemptId, executionId, actionId, stepId: request.step?.id, phase: s.role, capturedAt: s.capturedAt, sha256: s.sha256, bytes: s.bytes, mimeType: "image/png", declaredAfterIntervalMs: s.declaredAfterIntervalMs, fileName: s.fileName, groupId: event.group });
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
const candidate = {
|
|
1159
|
+
status: !afterRequested(request) ? "not-requested" : descriptors.some((s) => s.phase === "after") ? "available" : captureFailure ? "capture-failed" : "capture-unknown",
|
|
1160
|
+
snapshots: descriptors
|
|
1161
|
+
};
|
|
1162
|
+
validateImageEvidence(candidate, request);
|
|
1163
|
+
imageEvidence = candidate;
|
|
1164
|
+
result = JSON.parse(JSON.stringify({ ...result, imageEvidence, evidenceMode, timeoutMs, ...output() }));
|
|
1165
|
+
if (result.outcome.kind !== "completed" || result.outcome.exitStatus.code !== 0) await reconcileGroup?.("operation failed or incomplete");
|
|
1166
|
+
await store.putExecution({ executionId, ...ids, state: result.outcome.kind === "completed" ? "recorded" : result.outcome.kind, argv: request.argv, scriptId: request.scriptId, exitStatus: result.outcome.kind === "completed" ? result.outcome.exitStatus : void 0 });
|
|
1167
|
+
await store.appendJournal({ kind: "execution-completion", ...ids, executionId, state: result.outcome.kind === "completed" ? "recorded" : result.outcome.kind, response: result }, { durable: true });
|
|
1168
|
+
await durableJson(receiptPath, result);
|
|
1169
|
+
return result;
|
|
1170
|
+
};
|
|
1171
|
+
const refuse = async (diagnostic) => {
|
|
1172
|
+
gate.reportLoss(diagnostic);
|
|
1173
|
+
try {
|
|
1174
|
+
await engine.callWithHandle(actionId, params, () => {
|
|
1175
|
+
throw new Error("refused dispatch must never run");
|
|
1176
|
+
});
|
|
1177
|
+
} catch (error) {
|
|
1178
|
+
if (!(error instanceof AdmissionRefusedError)) throw error;
|
|
1179
|
+
}
|
|
1180
|
+
return retain(response("refused", diagnostic));
|
|
1181
|
+
};
|
|
1182
|
+
try {
|
|
1183
|
+
validate(request);
|
|
1184
|
+
} catch (error) {
|
|
1185
|
+
return await refuse(message(error));
|
|
1186
|
+
}
|
|
1187
|
+
const groups = await optionalJson(groupPath) ?? { used: [] };
|
|
1188
|
+
const group = evidenceMode || uncaptured ? void 0 : request.snapshots.group;
|
|
1189
|
+
const abandonGroup = async (diagnostic) => {
|
|
1190
|
+
if (!groups.active) return;
|
|
1191
|
+
await store.appendJournal({ kind: "annotation", annotationType: "group-incomplete", ...ids, executionId, groupId: groups.active.groupId, priorSessionId: groups.active.sessionId, priorAttemptId: groups.active.attemptId, diagnostic, state: "incomplete" }, { durable: true });
|
|
1192
|
+
delete groups.active;
|
|
1193
|
+
await durableJson(groupPath, groups);
|
|
1194
|
+
};
|
|
1195
|
+
if (evidenceMode) await abandonGroup("explicit diagnostic interrupted the visual group");
|
|
1196
|
+
if (groups.active && (!group || group.groupId !== groups.active.groupId || request.sessionId !== groups.active.sessionId || request.attemptId !== groups.active.attemptId || group.phase === "first")) return await refuse("coalescing group is open; unrelated input is forbidden until its last member");
|
|
1197
|
+
if (!groups.active && group && (group.phase !== "first" || groups.used.includes(group.groupId))) return await refuse("coalescing group must begin with a fresh first member; group IDs cannot be reused");
|
|
1198
|
+
reconcileGroup = abandonGroup;
|
|
1199
|
+
let argv = request.argv ?? [];
|
|
1200
|
+
try {
|
|
1201
|
+
if (request.kind === "script") {
|
|
1202
|
+
const info = await stat2(request.remotePath);
|
|
1203
|
+
if (!info.isFile() || info.size > MAX_SCRIPT_BYTES) throw new Error("script missing or exceeds size bound");
|
|
1204
|
+
if (hash(await readFile2(request.remotePath)) !== request.scriptSha256) throw new Error("script hash mismatch");
|
|
1205
|
+
const expected = request.language === "python" ? "python3" : request.language === "typescript" ? "tsx" : "node";
|
|
1206
|
+
if (argv.length !== 2 || argv[0].split("/").at(-1) !== expected || argv[1] !== request.remotePath) throw new Error("script argv must be [interpreter, verified remotePath]");
|
|
1207
|
+
if (request.language === "javascript") argv = [process.execPath, request.remotePath];
|
|
1208
|
+
} else if (request.kind === "code") {
|
|
1209
|
+
if (hash(request.code) !== request.codeSha256) throw new Error("streamed code hash mismatch");
|
|
1210
|
+
const extension = request.language === "python" ? "py" : request.language === "typescript" ? "ts" : "js";
|
|
1211
|
+
const path = join3(root, "streamed", `${executionId}.${extension}`);
|
|
1212
|
+
await mkdir3(dirname2(path), { recursive: true });
|
|
1213
|
+
const file = await open(path, "wx", 384);
|
|
1214
|
+
try {
|
|
1215
|
+
await file.writeFile(request.code);
|
|
1216
|
+
await file.sync();
|
|
1217
|
+
} finally {
|
|
1218
|
+
await file.close();
|
|
1219
|
+
}
|
|
1220
|
+
if (hash(await readFile2(path)) !== request.codeSha256) throw new Error("materialized streamed code hash mismatch");
|
|
1221
|
+
argv = [request.language === "python" ? "python3" : request.language === "typescript" ? "tsx" : process.execPath, path];
|
|
1222
|
+
}
|
|
1223
|
+
} catch (error) {
|
|
1224
|
+
return await refuse(message(error));
|
|
1225
|
+
}
|
|
1226
|
+
await store.appendJournal({ kind: "execution-start", ...ids, executionId, state: "admitted", argv, cwd: request.cwd, step: request.step, evidenceMode, timeoutMs, ...uncaptured ? { capture: false } : {}, scriptIdentity: request.kind === "exec" ? void 0 : { sha256: request.kind === "code" ? request.codeSha256 : request.scriptSha256, language: request.language, remotePath: argv.at(-1) } }, { durable: true });
|
|
1227
|
+
if (group?.phase === "first") {
|
|
1228
|
+
groups.active = { groupId: group.groupId, ...ids };
|
|
1229
|
+
groups.used.push(group.groupId);
|
|
1230
|
+
await durableJson(groupPath, groups);
|
|
1231
|
+
}
|
|
1232
|
+
if (group && group.phase !== "first") {
|
|
1233
|
+
const probe = join3(root, `.capture-probe-${executionId}.png`);
|
|
1234
|
+
try {
|
|
1235
|
+
await capture(probe);
|
|
1236
|
+
} catch (error) {
|
|
1237
|
+
return await refuse(message(error));
|
|
1238
|
+
} finally {
|
|
1239
|
+
await rm2(probe, { force: true });
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
gate.update({ ready: true, observedAtMonotonic: Date.now() });
|
|
1243
|
+
let dispatched = false;
|
|
1244
|
+
try {
|
|
1245
|
+
const outcome = await engine.callWithHandle(actionId, params, async () => {
|
|
1246
|
+
dispatched = true;
|
|
1247
|
+
pendingSpawn = true;
|
|
1248
|
+
await markLock(true);
|
|
1249
|
+
try {
|
|
1250
|
+
const dispatchOptions = { cwd: request.cwd, env: process.env, timeoutMs };
|
|
1251
|
+
dispatchResult = options.dispatch ? await options.dispatch(argv, dispatchOptions) : await runOwned(argv, dispatchOptions);
|
|
1252
|
+
return dispatchResult;
|
|
1253
|
+
} finally {
|
|
1254
|
+
if (dispatchResult && dispatchResult.terminationConfirmed !== false && !keepLock) {
|
|
1255
|
+
pendingSpawn = false;
|
|
1256
|
+
await markLock(false);
|
|
1257
|
+
} else keepLock = true;
|
|
1258
|
+
}
|
|
1259
|
+
});
|
|
1260
|
+
const expectedCount = !group ? 2 : group.phase === "member" ? 0 : 1;
|
|
1261
|
+
if (captureFailure || engine.evidenceFailure || !evidenceMode && !uncaptured && engine.actionSnapshots?.length !== expectedCount) {
|
|
1262
|
+
const diagnostic = captureFailure ?? engine.evidenceFailure ?? "missing required snapshot evidence";
|
|
1263
|
+
return await retain(response("uncertain", diagnostic));
|
|
1264
|
+
}
|
|
1265
|
+
const driver = options.cuaDriver ?? process.env.RELAY_CUA_DRIVER;
|
|
1266
|
+
if (request.kind === "exec" && driver && argv[0] === driver && argv[1] === "call" && outcome.exitStatus.code === 0) {
|
|
1267
|
+
let value;
|
|
1268
|
+
try {
|
|
1269
|
+
value = JSON.parse(outcome.stdout ?? "");
|
|
1270
|
+
} catch {
|
|
1271
|
+
}
|
|
1272
|
+
if (value && typeof value === "object" && (value.isError === true || value.error || typeof value.code === "string" && value.code.length > 0)) {
|
|
1273
|
+
const diagnostic = `CUA structured failure: ${JSON.stringify(value)}`;
|
|
1274
|
+
return await retain({ ...response(value.code === "desktop_escalation_required" ? "refused" : "uncertain", diagnostic), stdout: bounded(outcome.stdout), stderr: bounded(outcome.stderr) });
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
const result = outcome.spawnError || outcome.timedOut || outcome.outputTruncated ? response("uncertain", outcome.spawnError ?? (outcome.timedOut ? "execution timed out" : "execution exceeded output bound")) : { executionId, outcome: { kind: "completed", exitStatus: outcome.exitStatus } };
|
|
1278
|
+
if (group?.phase === "last" && result.outcome.kind === "completed" && result.outcome.exitStatus.code === 0) {
|
|
1279
|
+
delete groups.active;
|
|
1280
|
+
await durableJson(groupPath, groups);
|
|
1281
|
+
}
|
|
1282
|
+
return await retain({ ...result, stdout: bounded(outcome.stdout), stderr: bounded(outcome.stderr), timedOut: !!outcome.timedOut, outputTruncated: !!outcome.outputTruncated });
|
|
1283
|
+
} catch (error) {
|
|
1284
|
+
await reconcileGroup?.(message(error));
|
|
1285
|
+
await store.appendJournal({ kind: "evidence-failure", ...ids, executionId, actionId, state: dispatched ? "uncertain" : "refused", diagnostic: message(error) }, { durable: true });
|
|
1286
|
+
return await retain(response(dispatched ? "uncertain" : error instanceof AdmissionRefusedError ? "refused" : "uncertain", message(error)));
|
|
1287
|
+
}
|
|
1288
|
+
} catch (error) {
|
|
1289
|
+
if (ownsLock) await reconcileGroup?.(message(error)).catch(() => {
|
|
1290
|
+
});
|
|
1291
|
+
return { ...response("uncertain", `receiver error: ${message(error)}`), ...output() };
|
|
1292
|
+
} finally {
|
|
1293
|
+
try {
|
|
1294
|
+
await store?.close();
|
|
1295
|
+
} catch {
|
|
1296
|
+
keepLock = true;
|
|
1297
|
+
}
|
|
1298
|
+
if (ownsLock && !keepLock) await rm2(lock, { recursive: true, force: true }).catch(() => {
|
|
1299
|
+
});
|
|
1300
|
+
else if (ownsLock) await markLock(true, true).catch(() => {
|
|
1301
|
+
});
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
async function main() {
|
|
1305
|
+
let result;
|
|
1306
|
+
try {
|
|
1307
|
+
const path = process.argv[2];
|
|
1308
|
+
if (!path) throw new Error("usage: receiver REQUEST.json (file framing; stdin is not used)");
|
|
1309
|
+
const file = await open(path, "r");
|
|
1310
|
+
let bytes;
|
|
1311
|
+
try {
|
|
1312
|
+
if ((await file.stat()).size > MAX_REQUEST_BYTES) throw new Error("request file exceeds maximum size");
|
|
1313
|
+
bytes = Buffer.alloc(MAX_REQUEST_BYTES + 1);
|
|
1314
|
+
let length = 0;
|
|
1315
|
+
while (length < bytes.length) {
|
|
1316
|
+
const part = await file.read(bytes, length, bytes.length - length, null);
|
|
1317
|
+
if (!part.bytesRead) break;
|
|
1318
|
+
length += part.bytesRead;
|
|
1319
|
+
}
|
|
1320
|
+
if (length > MAX_REQUEST_BYTES) throw new Error("request file exceeds maximum size");
|
|
1321
|
+
bytes = bytes.subarray(0, length);
|
|
1322
|
+
} finally {
|
|
1323
|
+
await file.close();
|
|
1324
|
+
}
|
|
1325
|
+
result = await receive(JSON.parse(bytes.toString("utf8")));
|
|
1326
|
+
} catch (error) {
|
|
1327
|
+
result = { executionId: "unknown", imageEvidence: { status: "capture-unknown", snapshots: [] }, outcome: { kind: "refused", diagnostic: bounded(message(error)) } };
|
|
1328
|
+
}
|
|
1329
|
+
process.stdout.write(`${JSON.stringify(result)}
|
|
1330
|
+
`);
|
|
1331
|
+
}
|
|
1332
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(await realpath(resolve(process.argv[1]))).href) void main();
|
|
1333
|
+
export {
|
|
1334
|
+
MAX_OUTPUT_BYTES,
|
|
1335
|
+
MAX_REQUEST_BYTES,
|
|
1336
|
+
afterRequested,
|
|
1337
|
+
confirmProcessGroupExit,
|
|
1338
|
+
groupAbsentFromProcessTable,
|
|
1339
|
+
receive,
|
|
1340
|
+
validateImageEvidence
|
|
1341
|
+
};
|