glasspane-mcp 1.1.2 → 1.2.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/dist/dispatch.d.ts +1 -1
- package/dist/http-gateway-cli.d.ts +3 -0
- package/dist/http-gateway-cli.js +2744 -0
- package/dist/http-gateway.d.ts +39 -0
- package/dist/http-gateway.js +2626 -0
- package/dist/index.js +1 -1
- package/dist/tools.d.ts +30 -1
- package/package.json +19 -5
|
@@ -0,0 +1,2744 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/http-gateway-cli.ts
|
|
4
|
+
import process2 from "node:process";
|
|
5
|
+
|
|
6
|
+
// src/engine-client.ts
|
|
7
|
+
import net from "node:net";
|
|
8
|
+
import os from "node:os";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
|
|
13
|
+
// src/io.ts
|
|
14
|
+
var MAX_FRAME_BYTES = 4 * 1024 * 1024;
|
|
15
|
+
var OVERSIZE_PREFIX_BYTES = 512;
|
|
16
|
+
var LineReader = class {
|
|
17
|
+
constructor(sink) {
|
|
18
|
+
this.sink = sink;
|
|
19
|
+
}
|
|
20
|
+
sink;
|
|
21
|
+
buffer = "";
|
|
22
|
+
/** UTF-8 bytes seen for the line in progress (counted, not all retained). */
|
|
23
|
+
bytes = 0;
|
|
24
|
+
/** The line in progress already blew the cap; only the head is retained. */
|
|
25
|
+
discarding = false;
|
|
26
|
+
/** @param chunk UTF-8 text fragment received from the stream. */
|
|
27
|
+
push(chunk) {
|
|
28
|
+
let rest = chunk;
|
|
29
|
+
while (rest.length > 0) {
|
|
30
|
+
const nl = rest.indexOf("\n");
|
|
31
|
+
const closed = nl !== -1;
|
|
32
|
+
this.consume(closed ? rest.slice(0, nl) : rest);
|
|
33
|
+
rest = closed ? rest.slice(nl + 1) : "";
|
|
34
|
+
if (closed) {
|
|
35
|
+
this.deliver();
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/** Partial line so far; only the retained head while a line is discarded. */
|
|
40
|
+
pendingText() {
|
|
41
|
+
return this.buffer;
|
|
42
|
+
}
|
|
43
|
+
consume(segment) {
|
|
44
|
+
if (segment.length === 0) {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const segmentBytes = Buffer.byteLength(segment, "utf8");
|
|
48
|
+
if (this.discarding) {
|
|
49
|
+
this.bytes += segmentBytes;
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (this.bytes + segmentBytes > MAX_FRAME_BYTES) {
|
|
53
|
+
this.discarding = true;
|
|
54
|
+
this.buffer = this.buffer.length >= OVERSIZE_PREFIX_BYTES ? this.buffer.slice(0, OVERSIZE_PREFIX_BYTES) : (this.buffer + segment).slice(0, OVERSIZE_PREFIX_BYTES);
|
|
55
|
+
this.bytes += segmentBytes;
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
this.buffer += segment;
|
|
59
|
+
this.bytes += segmentBytes;
|
|
60
|
+
}
|
|
61
|
+
deliver() {
|
|
62
|
+
const line = this.buffer;
|
|
63
|
+
const bytes = this.bytes;
|
|
64
|
+
const oversize = this.discarding;
|
|
65
|
+
this.buffer = "";
|
|
66
|
+
this.bytes = 0;
|
|
67
|
+
this.discarding = false;
|
|
68
|
+
if (oversize) {
|
|
69
|
+
this.sink.onOversize(bytes, line);
|
|
70
|
+
} else {
|
|
71
|
+
this.sink.onLine(line);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
var OversizeFrameError = class extends Error {
|
|
76
|
+
bytes;
|
|
77
|
+
prefix;
|
|
78
|
+
constructor(bytes, prefix) {
|
|
79
|
+
super(`frame exceeds ${MAX_FRAME_BYTES} bytes (${bytes} received)`);
|
|
80
|
+
this.name = "OversizeFrameError";
|
|
81
|
+
this.bytes = bytes;
|
|
82
|
+
this.prefix = prefix;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
var FRAME_ID_PATTERN = /"id"\s*:\s*(?:"((?:[^"\\]|\\.)*)"|(-?\d+)(?=[\s,}]))/;
|
|
86
|
+
function recoverFrameId(prefix) {
|
|
87
|
+
const match = FRAME_ID_PATTERN.exec(prefix);
|
|
88
|
+
if (!match) {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
const quoted = match[1];
|
|
92
|
+
if (quoted !== void 0) {
|
|
93
|
+
try {
|
|
94
|
+
return JSON.parse(`"${quoted}"`);
|
|
95
|
+
} catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const digits = match[2];
|
|
100
|
+
if (digits === void 0) {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
const numeric = Number(digits);
|
|
104
|
+
return Number.isSafeInteger(numeric) ? numeric : digits;
|
|
105
|
+
}
|
|
106
|
+
var StreamLineIo = class {
|
|
107
|
+
constructor(input, output) {
|
|
108
|
+
this.input = input;
|
|
109
|
+
this.output = output;
|
|
110
|
+
this.reader = new LineReader({
|
|
111
|
+
onLine: (line) => this.messageHandler?.(line),
|
|
112
|
+
onOversize: (bytes, prefix) => this.errorHandler?.(new OversizeFrameError(bytes, prefix))
|
|
113
|
+
});
|
|
114
|
+
input.setEncoding("utf8");
|
|
115
|
+
input.on("data", (chunk) => this.reader.push(chunk));
|
|
116
|
+
input.on("close", () => this.closeHandler?.());
|
|
117
|
+
input.on("error", (error) => this.errorHandler?.(error));
|
|
118
|
+
}
|
|
119
|
+
input;
|
|
120
|
+
output;
|
|
121
|
+
reader;
|
|
122
|
+
messageHandler = null;
|
|
123
|
+
closeHandler = null;
|
|
124
|
+
errorHandler = null;
|
|
125
|
+
writeLine(line) {
|
|
126
|
+
this.output.write(line + "\n");
|
|
127
|
+
}
|
|
128
|
+
onMessage(handler) {
|
|
129
|
+
this.messageHandler = handler;
|
|
130
|
+
}
|
|
131
|
+
onClose(handler) {
|
|
132
|
+
this.closeHandler = handler;
|
|
133
|
+
}
|
|
134
|
+
onError(handler) {
|
|
135
|
+
this.errorHandler = handler;
|
|
136
|
+
}
|
|
137
|
+
close() {
|
|
138
|
+
this.input.destroy();
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
// src/errors.ts
|
|
143
|
+
var GP_E_ENGINE_UNREACHABLE = "GP_E_ENGINE_UNREACHABLE";
|
|
144
|
+
var GP_E_BAD_PARAMS = "GP_E_BAD_PARAMS";
|
|
145
|
+
var GP_E_NO_EVIDENCE = "GP_E_NO_EVIDENCE";
|
|
146
|
+
var GP_E_INTERNAL = "GP_E_INTERNAL";
|
|
147
|
+
var GP_E_PROJECT_LIMIT = "GP_E_PROJECT_LIMIT";
|
|
148
|
+
var GP_E_NOT_FOUND = "GP_E_NOT_FOUND";
|
|
149
|
+
var GP_E_ENGINE_TIMEOUT = "GP_E_ENGINE_TIMEOUT";
|
|
150
|
+
var GP_E_PAYLOAD_TOO_LARGE = "GP_E_PAYLOAD_TOO_LARGE";
|
|
151
|
+
function formatToolError(code, message, remedy) {
|
|
152
|
+
return `${code}: ${message} | remedy: ${remedy}`;
|
|
153
|
+
}
|
|
154
|
+
function formatToolErrorShape(error) {
|
|
155
|
+
return formatToolError(error.code, error.message, error.remedy);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// src/engine-client.ts
|
|
159
|
+
function daemonUnreachableRemedy() {
|
|
160
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
161
|
+
const installerCli = path.resolve(here, "..", "..", "installer", "cli.js");
|
|
162
|
+
if (fs.existsSync(installerCli)) {
|
|
163
|
+
return `run "node ${installerCli} --restore-launchd" (auto-restores and verifies the launchd-managed daemon), then retry`;
|
|
164
|
+
}
|
|
165
|
+
return "ensure the glasspane daemon is running (launchd job com.glasspane.daemon; in a repo checkout run `node installer/cli.js --restore-launchd`), then retry";
|
|
166
|
+
}
|
|
167
|
+
var ENGINE_SOCKET_ENV = "GLASSPANE_ENGINE_SOCK";
|
|
168
|
+
function defaultSocketPath() {
|
|
169
|
+
return process.env[ENGINE_SOCKET_ENV] ?? path.join(os.homedir(), ".glasspane", "engine.sock");
|
|
170
|
+
}
|
|
171
|
+
var ENGINE_TIMEOUT_MS = 1e4;
|
|
172
|
+
var ENGINE_DEADLINES_MS = {
|
|
173
|
+
hello: 15e3,
|
|
174
|
+
attach: 3e4,
|
|
175
|
+
act: 12e4,
|
|
176
|
+
observe: 45e3,
|
|
177
|
+
assert_element: 6e4,
|
|
178
|
+
diagnose: 3e4,
|
|
179
|
+
last_evidence: 6e4,
|
|
180
|
+
snapshot: 9e4,
|
|
181
|
+
probe_status: 15e3,
|
|
182
|
+
shutdown: 15e3
|
|
183
|
+
};
|
|
184
|
+
var RESTORE_BASE_DEADLINE_MS = 3e4;
|
|
185
|
+
var CALLER_VISIBLE_CEILING_MS = 5e4;
|
|
186
|
+
function callerDeadlineMs(method, params, ceilingMs = CALLER_VISIBLE_CEILING_MS) {
|
|
187
|
+
return Math.min(engineDeadlineMs(method, params), ceilingMs);
|
|
188
|
+
}
|
|
189
|
+
var REPLAY_UNSAFE_METHODS = /* @__PURE__ */ new Set(["act", "restore"]);
|
|
190
|
+
function engineDeadlineMs(method, params) {
|
|
191
|
+
if (method === "restore") {
|
|
192
|
+
const steps = params?.steps;
|
|
193
|
+
const count = Array.isArray(steps) ? steps.length : 0;
|
|
194
|
+
return RESTORE_BASE_DEADLINE_MS + count * ENGINE_DEADLINES_MS.act;
|
|
195
|
+
}
|
|
196
|
+
const known = ENGINE_DEADLINES_MS[method];
|
|
197
|
+
return known ?? ENGINE_TIMEOUT_MS * 3;
|
|
198
|
+
}
|
|
199
|
+
var ENGINE_PROTOCOL_VERSION = "0";
|
|
200
|
+
var EngineCallError = class extends Error {
|
|
201
|
+
code;
|
|
202
|
+
message;
|
|
203
|
+
remedy;
|
|
204
|
+
constructor(code, message, remedy) {
|
|
205
|
+
super(`${code}: ${message}`);
|
|
206
|
+
this.name = "EngineCallError";
|
|
207
|
+
this.code = code;
|
|
208
|
+
this.message = message;
|
|
209
|
+
this.remedy = remedy;
|
|
210
|
+
}
|
|
211
|
+
toBody() {
|
|
212
|
+
return { code: this.code, message: this.message, remedy: this.remedy };
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
function slowEngineRemedy(method) {
|
|
216
|
+
const poll = "confirm the daemon is alive with a cheap call instead \u2014 gp_probe_status goes out immediately while this request is still outstanding (the shell no longer queues one MCP request behind another) and is answered as soon as the daemon is free of it";
|
|
217
|
+
if (REPLAY_UNSAFE_METHODS.has(method)) {
|
|
218
|
+
return `${poll}. The daemon serves one request at a time and is still working on this one, so wait for it; do NOT re-issue ${method}, because the original action can still take effect on the user's screen \u2014 the original reply is written to this server's log (stderr) when it lands, which is where the answer is. Restart only if gp_probe_status times out too \u2014 then ${daemonUnreachableRemedy()}`;
|
|
219
|
+
}
|
|
220
|
+
return `${poll}. The daemon serves one request at a time and is still working on this one, so wait, then retry this read narrower (smaller maxDepth / a tighter selector); if gp_probe_status times out as well, ${daemonUnreachableRemedy()}`;
|
|
221
|
+
}
|
|
222
|
+
var LATE_REPLY_RETENTION = 16;
|
|
223
|
+
var LOG_BODY_CHARS = 64 * 1024;
|
|
224
|
+
var EngineJsonRpcClient = class {
|
|
225
|
+
constructor(io, timeoutMs, identity = null, callerCeilingMs = CALLER_VISIBLE_CEILING_MS) {
|
|
226
|
+
this.io = io;
|
|
227
|
+
this.timeoutMs = timeoutMs;
|
|
228
|
+
this.identity = identity;
|
|
229
|
+
this.callerCeilingMs = callerCeilingMs;
|
|
230
|
+
this.io.onMessage((line) => this.handleMessage(line));
|
|
231
|
+
this.io.onError((error) => {
|
|
232
|
+
if (error instanceof OversizeFrameError) {
|
|
233
|
+
this.failOversizedReply(error);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
this.teardown(new EngineCallError(
|
|
237
|
+
GP_E_ENGINE_UNREACHABLE,
|
|
238
|
+
`engine transport error: ${error.message}`,
|
|
239
|
+
daemonUnreachableRemedy()
|
|
240
|
+
));
|
|
241
|
+
});
|
|
242
|
+
this.io.onClose(() => this.teardown(new EngineCallError(
|
|
243
|
+
GP_E_ENGINE_UNREACHABLE,
|
|
244
|
+
"engine transport closed",
|
|
245
|
+
daemonUnreachableRemedy()
|
|
246
|
+
)));
|
|
247
|
+
this.io.onOpen?.(() => this.handshake());
|
|
248
|
+
}
|
|
249
|
+
io;
|
|
250
|
+
timeoutMs;
|
|
251
|
+
identity;
|
|
252
|
+
callerCeilingMs;
|
|
253
|
+
nextId = 0;
|
|
254
|
+
closed = false;
|
|
255
|
+
pending = /* @__PURE__ */ new Map();
|
|
256
|
+
noteHandler = null;
|
|
257
|
+
/**
|
|
258
|
+
* Sink for facts that cannot be attached to any request of the caller: a
|
|
259
|
+
* late reply, a frame with an id this client never issued, a daemon that
|
|
260
|
+
* fails its handshake. Without a sink these stay invisible, which is how
|
|
261
|
+
* "not measured" turns into a confident wrong story.
|
|
262
|
+
*/
|
|
263
|
+
onEngineNote(handler) {
|
|
264
|
+
this.noteHandler = handler;
|
|
265
|
+
}
|
|
266
|
+
/** Send a request and await its matching response frame. */
|
|
267
|
+
call(method, params) {
|
|
268
|
+
const id = this.nextId++;
|
|
269
|
+
const frame = { id, method, ...params === void 0 ? {} : { params } };
|
|
270
|
+
const methodDeadlineMs = this.timeoutMs ?? engineDeadlineMs(method, params);
|
|
271
|
+
const deadlineMs = this.timeoutMs ?? callerDeadlineMs(method, params, this.callerCeilingMs);
|
|
272
|
+
return new Promise((resolve, reject) => {
|
|
273
|
+
const entry = {
|
|
274
|
+
id,
|
|
275
|
+
method,
|
|
276
|
+
deadlineMs,
|
|
277
|
+
methodDeadlineMs,
|
|
278
|
+
timer: null,
|
|
279
|
+
settled: false,
|
|
280
|
+
deliver: resolve,
|
|
281
|
+
fail: reject
|
|
282
|
+
};
|
|
283
|
+
entry.timer = setTimeout(() => this.onDeadline(entry), deadlineMs);
|
|
284
|
+
this.pending.set(id, entry);
|
|
285
|
+
try {
|
|
286
|
+
this.io.writeLine(JSON.stringify(frame));
|
|
287
|
+
} catch (error) {
|
|
288
|
+
this.pending.delete(id);
|
|
289
|
+
this.reject(entry, new EngineCallError(
|
|
290
|
+
GP_E_ENGINE_UNREACHABLE,
|
|
291
|
+
`cannot send '${method}' to the engine daemon: ${error.message}`,
|
|
292
|
+
daemonUnreachableRemedy()
|
|
293
|
+
));
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
close() {
|
|
298
|
+
this.teardown(new EngineCallError(
|
|
299
|
+
GP_E_ENGINE_UNREACHABLE,
|
|
300
|
+
"engine client closed",
|
|
301
|
+
daemonUnreachableRemedy()
|
|
302
|
+
));
|
|
303
|
+
this.closed = true;
|
|
304
|
+
this.io.close();
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Timeout path: settle the caller with a *slow* diagnosis but keep the
|
|
308
|
+
* entry, so a reply landing afterwards is delivered instead of thrown away.
|
|
309
|
+
* Only the transport going away makes a request unrecoverable.
|
|
310
|
+
*/
|
|
311
|
+
onDeadline(entry) {
|
|
312
|
+
this.report(
|
|
313
|
+
`engine has not answered '${entry.method}' (id ${entry.id}) within ${entry.deadlineMs}ms \u2014 still in flight`
|
|
314
|
+
);
|
|
315
|
+
const capped = entry.methodDeadlineMs > entry.deadlineMs ? ` This shell stops waiting for an MCP client's sake at ${entry.deadlineMs}ms while the daemon gets up to ${entry.methodDeadlineMs}ms for '${entry.method}', because a client that is left hanging retries on its own and a retried '${entry.method}' runs twice.` : "";
|
|
316
|
+
this.reject(entry, new EngineCallError(
|
|
317
|
+
GP_E_ENGINE_TIMEOUT,
|
|
318
|
+
`engine is still working on '${entry.method}': no reply after ${entry.deadlineMs}ms. The request stays registered \u2014 a late reply is written to the server log \u2014 so this is a busy or slow daemon, not an unreachable one.` + capped,
|
|
319
|
+
slowEngineRemedy(entry.method)
|
|
320
|
+
));
|
|
321
|
+
this.retainForLateReply();
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* A settled-by-timeout entry is what makes a late reply attributable, so the
|
|
325
|
+
* retention is bounded oldest-first and the eviction is logged, not silent.
|
|
326
|
+
*/
|
|
327
|
+
retainForLateReply() {
|
|
328
|
+
const stale = [...this.pending.values()].filter((entry) => entry.settled);
|
|
329
|
+
if (stale.length < LATE_REPLY_RETENTION) {
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
const evicted = stale[0];
|
|
333
|
+
if (!evicted) {
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
this.pending.delete(evicted.id);
|
|
337
|
+
this.report(`dropped late-reply tracking for '${evicted.method}' (id ${evicted.id}): retention cap ${LATE_REPLY_RETENTION} reached`);
|
|
338
|
+
}
|
|
339
|
+
handleMessage(line) {
|
|
340
|
+
let frame;
|
|
341
|
+
try {
|
|
342
|
+
frame = JSON.parse(line);
|
|
343
|
+
} catch {
|
|
344
|
+
this.report(`engine sent a non-JSON frame, dropped: ${truncate(line)}`);
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
const id = frame.id;
|
|
348
|
+
if (typeof id === "number") {
|
|
349
|
+
const entry = this.pending.get(id);
|
|
350
|
+
if (!entry) {
|
|
351
|
+
this.report(`engine sent a frame for request id ${id}, which this client never issued (or already gave up on): ${truncate(line)}`);
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
this.pending.delete(id);
|
|
355
|
+
if (entry.settled) {
|
|
356
|
+
this.reportLateReply(entry, frame);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
this.settleFromFrame(entry, frame);
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
if (id === null || id === void 0) {
|
|
363
|
+
const target = this.oldestOpen();
|
|
364
|
+
if (frame.error && target) {
|
|
365
|
+
this.pending.delete(target.id);
|
|
366
|
+
this.reject(target, attribute(this.engineError(frame.error), target));
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
this.report(frame.error ? `engine reported ${this.engineError(frame.error).code} with no request in flight: ${truncate(line)}` : `engine sent an id-less frame with no request in flight: ${truncate(line)}`);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
this.report(`engine sent a frame with a non-numeric request id (${jsonOrString(id)}), which this client never issues: ${truncate(line)}`);
|
|
373
|
+
}
|
|
374
|
+
settleFromFrame(entry, frame) {
|
|
375
|
+
if (frame.error) {
|
|
376
|
+
this.reject(entry, this.engineError(frame.error));
|
|
377
|
+
} else {
|
|
378
|
+
this.resolve(entry, frame.result);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* A frame over the cap: attribute it to the request it belonged to — from
|
|
383
|
+
* the retained head when the daemon echoed an id, else by arrival order —
|
|
384
|
+
* and fail that one call only.
|
|
385
|
+
*/
|
|
386
|
+
failOversizedReply(error) {
|
|
387
|
+
const echoed = recoverFrameId(error.prefix);
|
|
388
|
+
let entry = typeof echoed === "number" ? this.pending.get(echoed) : void 0;
|
|
389
|
+
if (entry?.settled) {
|
|
390
|
+
this.pending.delete(entry.id);
|
|
391
|
+
this.report(`the engine's late reply to '${entry.method}' (id ${entry.id}) exceeded the ${MAX_FRAME_BYTES}-byte frame cap (${error.bytes} bytes), so its body could not be delivered even late`);
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
const inferred = entry === void 0;
|
|
395
|
+
if (!entry) {
|
|
396
|
+
entry = this.oldestOpen();
|
|
397
|
+
}
|
|
398
|
+
if (!entry) {
|
|
399
|
+
this.report(`engine sent an oversized frame (${error.bytes} bytes) with no request in flight \u2014 dropped, connection intact`);
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
this.pending.delete(entry.id);
|
|
403
|
+
this.reject(entry, attribute(new EngineCallError(
|
|
404
|
+
GP_E_PAYLOAD_TOO_LARGE,
|
|
405
|
+
`the engine's reply to '${entry.method}' exceeded the ${MAX_FRAME_BYTES}-byte frame cap (${error.bytes} bytes) and was dropped; the connection is intact and other requests are unaffected`,
|
|
406
|
+
"narrow this request: retry with a smaller maxDepth or a more specific selector (the daemon keeps answering other requests)"
|
|
407
|
+
), entry, inferred));
|
|
408
|
+
}
|
|
409
|
+
engineError(body) {
|
|
410
|
+
return new EngineCallError(
|
|
411
|
+
String(body.code ?? "GP_E_UNKNOWN"),
|
|
412
|
+
String(body.message ?? "the engine sent an error frame without a message"),
|
|
413
|
+
typeof body.remedy === "string" && body.remedy !== "" ? body.remedy : "the engine sent no remedy for this error code; check the daemon log (stderr) and retry"
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
/** Oldest request the caller is still waiting on (daemon FIFO order). */
|
|
417
|
+
oldestOpen() {
|
|
418
|
+
for (const entry of this.pending.values()) {
|
|
419
|
+
if (!entry.settled) {
|
|
420
|
+
return entry;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
return void 0;
|
|
424
|
+
}
|
|
425
|
+
reportLateReply(entry, frame) {
|
|
426
|
+
const body = frame.error ? `error ${JSON.stringify(frame.error)}` : truncate(jsonOrString(frame.result));
|
|
427
|
+
this.report(
|
|
428
|
+
`late engine reply for '${entry.method}' (id ${entry.id}), ${entry.deadlineMs}ms deadline already reported: ${body}`
|
|
429
|
+
);
|
|
430
|
+
}
|
|
431
|
+
resolve(entry, value) {
|
|
432
|
+
this.complete(entry);
|
|
433
|
+
entry.deliver(value);
|
|
434
|
+
}
|
|
435
|
+
reject(entry, reason) {
|
|
436
|
+
this.complete(entry);
|
|
437
|
+
entry.fail(reason);
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Single settle funnel: clears the deadline timer on every path and marks
|
|
441
|
+
* the entry settled. Callers delete the entry when the transport can no
|
|
442
|
+
* longer answer it, and keep it after a timeout for the late reply.
|
|
443
|
+
*/
|
|
444
|
+
complete(entry) {
|
|
445
|
+
if (entry.timer !== null) {
|
|
446
|
+
clearTimeout(entry.timer);
|
|
447
|
+
entry.timer = null;
|
|
448
|
+
}
|
|
449
|
+
entry.settled = true;
|
|
450
|
+
}
|
|
451
|
+
/** Reject everything outstanding and drop every handle. */
|
|
452
|
+
teardown(reason) {
|
|
453
|
+
const entries = [...this.pending.values()];
|
|
454
|
+
this.pending.clear();
|
|
455
|
+
for (const entry of entries) {
|
|
456
|
+
if (!entry.settled) {
|
|
457
|
+
this.reject(entry, reason);
|
|
458
|
+
} else if (entry.timer !== null) {
|
|
459
|
+
clearTimeout(entry.timer);
|
|
460
|
+
entry.timer = null;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
report(note) {
|
|
465
|
+
this.noteHandler?.(note);
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* R4-06: both sides self-report protocol/version and the repo keeps a single
|
|
469
|
+
* version line, yet nothing compared them at runtime — an old daemon under a
|
|
470
|
+
* new shell only surfaced as a mystery schema error later. Handshake once
|
|
471
|
+
* per (re)connection and report the measurement, including "unmeasured".
|
|
472
|
+
*/
|
|
473
|
+
handshake() {
|
|
474
|
+
if (this.closed) {
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
this.call("hello").then(
|
|
478
|
+
(result) => this.verifyIdentity(result),
|
|
479
|
+
(error) => this.report(
|
|
480
|
+
`engine did not answer the hello handshake on this connection: ${error.message}`
|
|
481
|
+
)
|
|
482
|
+
);
|
|
483
|
+
}
|
|
484
|
+
verifyIdentity(result) {
|
|
485
|
+
const expected = ENGINE_PROTOCOL_VERSION;
|
|
486
|
+
if (typeof result !== "object" || result === null) {
|
|
487
|
+
this.report("engine answered hello without an object result \u2014 protocol compatibility could not be measured");
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
const report = result;
|
|
491
|
+
const protocol = typeof report.protocolVersion === "string" ? report.protocolVersion : null;
|
|
492
|
+
if (protocol === null) {
|
|
493
|
+
this.report(`engine self-report has no protocolVersion (engine=${jsonOrString(report.engine)}); expected '${expected}' \u2014 compatibility unverified`);
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
if (protocol !== expected) {
|
|
497
|
+
this.report(`protocol mismatch: engine speaks '${protocol}', this shell speaks '${expected}' \u2014 upgrade or restart one side before trusting tool results`);
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
const version = typeof report.version === "string" ? report.version : null;
|
|
501
|
+
const wantVersion = this.identity?.version;
|
|
502
|
+
if (version !== null && wantVersion !== void 0 && version !== wantVersion) {
|
|
503
|
+
this.report(`version mismatch: engine self-reports '${version}', this MCP shell ships '${wantVersion}' (single version line) \u2014 one side is stale`);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
function attribute(error, entry, inferred = true) {
|
|
508
|
+
if (!inferred) {
|
|
509
|
+
return error;
|
|
510
|
+
}
|
|
511
|
+
return new EngineCallError(
|
|
512
|
+
error.code,
|
|
513
|
+
`${error.message} (the engine's frame carried no request id; this is the oldest request still in flight, and the daemon answers in the order it received them \u2014 method '${entry.method}')`,
|
|
514
|
+
error.remedy
|
|
515
|
+
);
|
|
516
|
+
}
|
|
517
|
+
function truncate(text) {
|
|
518
|
+
return text.length <= LOG_BODY_CHARS ? text : `${text.slice(0, LOG_BODY_CHARS)}\u2026 [+${text.length - LOG_BODY_CHARS} chars not logged]`;
|
|
519
|
+
}
|
|
520
|
+
function jsonOrString(value) {
|
|
521
|
+
return String(JSON.stringify(value));
|
|
522
|
+
}
|
|
523
|
+
var ReconnectingSocketIo = class {
|
|
524
|
+
constructor(socketPath, open) {
|
|
525
|
+
this.socketPath = socketPath;
|
|
526
|
+
this.open = open;
|
|
527
|
+
}
|
|
528
|
+
socketPath;
|
|
529
|
+
open;
|
|
530
|
+
inner = null;
|
|
531
|
+
closed = false;
|
|
532
|
+
messageHandler = null;
|
|
533
|
+
closeHandler = null;
|
|
534
|
+
errorHandler = null;
|
|
535
|
+
openHandler = null;
|
|
536
|
+
writeLine(line) {
|
|
537
|
+
this.connect().writeLine(line);
|
|
538
|
+
}
|
|
539
|
+
onMessage(handler) {
|
|
540
|
+
this.messageHandler = handler;
|
|
541
|
+
}
|
|
542
|
+
onClose(handler) {
|
|
543
|
+
this.closeHandler = handler;
|
|
544
|
+
}
|
|
545
|
+
onError(handler) {
|
|
546
|
+
this.errorHandler = handler;
|
|
547
|
+
}
|
|
548
|
+
onOpen(handler) {
|
|
549
|
+
this.openHandler = handler;
|
|
550
|
+
}
|
|
551
|
+
close() {
|
|
552
|
+
this.closed = true;
|
|
553
|
+
const inner = this.inner;
|
|
554
|
+
this.inner = null;
|
|
555
|
+
inner?.close();
|
|
556
|
+
}
|
|
557
|
+
connect() {
|
|
558
|
+
if (this.closed) {
|
|
559
|
+
throw new Error(`engine transport for ${this.socketPath} is closed`);
|
|
560
|
+
}
|
|
561
|
+
if (this.inner) {
|
|
562
|
+
return this.inner;
|
|
563
|
+
}
|
|
564
|
+
const socket = this.open(this.socketPath);
|
|
565
|
+
const io = new StreamLineIo(socket, socket);
|
|
566
|
+
io.onMessage((line) => this.messageHandler?.(line));
|
|
567
|
+
io.onError((error) => {
|
|
568
|
+
if (this.inner === io) {
|
|
569
|
+
this.inner = null;
|
|
570
|
+
io.close();
|
|
571
|
+
}
|
|
572
|
+
this.errorHandler?.(error);
|
|
573
|
+
});
|
|
574
|
+
io.onClose(() => {
|
|
575
|
+
if (this.inner === io) {
|
|
576
|
+
this.inner = null;
|
|
577
|
+
}
|
|
578
|
+
this.closeHandler?.();
|
|
579
|
+
});
|
|
580
|
+
socket.once("connect", () => {
|
|
581
|
+
if (this.inner === io) {
|
|
582
|
+
this.openHandler?.();
|
|
583
|
+
}
|
|
584
|
+
});
|
|
585
|
+
this.inner = io;
|
|
586
|
+
return io;
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
function unixSocketEngineClient(socketPath, options = {}) {
|
|
590
|
+
const open = options.open ?? ((target) => net.createConnection(target));
|
|
591
|
+
return new EngineJsonRpcClient(
|
|
592
|
+
new ReconnectingSocketIo(socketPath, open),
|
|
593
|
+
void 0,
|
|
594
|
+
options.identity ?? null,
|
|
595
|
+
options.callerCeilingMs ?? CALLER_VISIBLE_CEILING_MS
|
|
596
|
+
);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// src/http-gateway.ts
|
|
600
|
+
import http from "node:http";
|
|
601
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
602
|
+
import { URL } from "node:url";
|
|
603
|
+
|
|
604
|
+
// src/evidence-report.ts
|
|
605
|
+
var PLACEHOLDER = "\u2014";
|
|
606
|
+
function reportTitle(pack) {
|
|
607
|
+
return `${pack.operationId} \xB7 ${measureLabel(pack)} \xB7 ${levelLabel(pack.circuitBreaker.level)}`;
|
|
608
|
+
}
|
|
609
|
+
function evidenceSummaryLines(pack) {
|
|
610
|
+
const lines = [];
|
|
611
|
+
lines.push(`attribution: ${pack.attribution.level} | contaminated=${pack.attribution.contaminated}`);
|
|
612
|
+
const reason = pack.circuitBreaker.reason === void 0 ? "" : ` | reason: ${pack.circuitBreaker.reason}`;
|
|
613
|
+
lines.push(`circuitBreaker: level ${pack.circuitBreaker.level} (${levelLabel(pack.circuitBreaker.level)})${reason}`);
|
|
614
|
+
if (pack.assertion !== void 0 && pack.assertion !== null) {
|
|
615
|
+
const a = pack.assertion;
|
|
616
|
+
lines.push(
|
|
617
|
+
`assert ${a.property} on ${selectorText(a.selector)}: expected=${valueText(a.expected)} actual=${valueText(a.actual)} passed=${a.passed}`
|
|
618
|
+
);
|
|
619
|
+
}
|
|
620
|
+
const act = pack.signals.act;
|
|
621
|
+
lines.push(`act ${act.action} ${selectorText(act.selector)}: ${act.actConfirmed ? "confirmed" : "rejected"}`);
|
|
622
|
+
if (pack.signals.axEvent !== void 0 && pack.signals.axEvent !== null) {
|
|
623
|
+
const ax = pack.signals.axEvent;
|
|
624
|
+
lines.push(`axEvent: changed=${ax.axChanged} nodes=${ax.nodeCount} latencyMs=${doubleText(ax.latencyMs)}`);
|
|
625
|
+
} else {
|
|
626
|
+
lines.push(AX_EVENT_NOT_MEASURED);
|
|
627
|
+
}
|
|
628
|
+
lines.push(
|
|
629
|
+
pack.signals.handlerProbe !== void 0 && pack.signals.handlerProbe !== null ? handlerProbeText(pack.signals.handlerProbe) : HANDLER_PROBE_NOT_MEASURED
|
|
630
|
+
);
|
|
631
|
+
lines.push(
|
|
632
|
+
pack.signals.stateDiff !== void 0 && pack.signals.stateDiff !== null ? stateDiffText(pack.signals.stateDiff) : STATE_DIFF_NOT_MEASURED
|
|
633
|
+
);
|
|
634
|
+
if (pack.signals.pixelDiff !== void 0 && pack.signals.pixelDiff !== null) {
|
|
635
|
+
const px = pack.signals.pixelDiff;
|
|
636
|
+
let line = `pixelDiff: changedRatio=${doubleText(px.changedPixelRatio)} windowId=${px.windowId}`;
|
|
637
|
+
if (px.bounds !== null) {
|
|
638
|
+
const b = px.bounds;
|
|
639
|
+
line += ` bounds=${doubleText(b.x)},${doubleText(b.y)},${doubleText(b.width)},${doubleText(b.height)}`;
|
|
640
|
+
}
|
|
641
|
+
lines.push(line);
|
|
642
|
+
} else {
|
|
643
|
+
lines.push(PIXEL_DIFF_NOT_MEASURED);
|
|
644
|
+
}
|
|
645
|
+
if (pack.signals.responsiveness !== void 0 && pack.signals.responsiveness !== null) {
|
|
646
|
+
const r = pack.signals.responsiveness;
|
|
647
|
+
lines.push(`responsiveness: responsive=${r.responsive} pingMs=${doubleText(r.pingMs)}`);
|
|
648
|
+
} else {
|
|
649
|
+
lines.push(RESPONSIVENESS_NOT_MEASURED);
|
|
650
|
+
}
|
|
651
|
+
if (pack.signals.crash !== void 0 && pack.signals.crash !== null) {
|
|
652
|
+
const c = pack.signals.crash;
|
|
653
|
+
lines.push(`crash: aliveBefore=${c.processAliveBefore} aliveAfter=${c.processAliveAfter}`);
|
|
654
|
+
} else {
|
|
655
|
+
lines.push(CRASH_NOT_MEASURED);
|
|
656
|
+
}
|
|
657
|
+
return lines;
|
|
658
|
+
}
|
|
659
|
+
function renderMarkdown(pack, diagnostics) {
|
|
660
|
+
const out = [];
|
|
661
|
+
out.push(`# ${reportTitle(pack)}`);
|
|
662
|
+
out.push("");
|
|
663
|
+
out.push(`**operationId**: ${pack.operationId}`);
|
|
664
|
+
out.push(`**createdAt**: ${pack.createdAt}`);
|
|
665
|
+
out.push(`**schemaVersion**: ${pack.schemaVersion}`);
|
|
666
|
+
for (const line of evidenceSummaryLines(pack)) {
|
|
667
|
+
out.push(`* ${line}`);
|
|
668
|
+
}
|
|
669
|
+
out.push("");
|
|
670
|
+
for (const section of sections(pack, diagnostics)) {
|
|
671
|
+
out.push(`## ${section.title}`);
|
|
672
|
+
out.push("");
|
|
673
|
+
out.push(section.body);
|
|
674
|
+
out.push("");
|
|
675
|
+
}
|
|
676
|
+
return out.join("\n");
|
|
677
|
+
}
|
|
678
|
+
function renderHTML(pack, diagnostics) {
|
|
679
|
+
const out = [];
|
|
680
|
+
out.push(`<div class="gp-evidence" id="${escapeHTML(pack.operationId)}">`);
|
|
681
|
+
out.push(`<h1>${escapeHTML(reportTitle(pack))}</h1>`);
|
|
682
|
+
out.push(`<dl class="gp-summary">`);
|
|
683
|
+
out.push(`<dt>operationId</dt><dd>${escapeHTML(pack.operationId)}</dd>`);
|
|
684
|
+
out.push(`<dt>createdAt</dt><dd>${escapeHTML(pack.createdAt)}</dd>`);
|
|
685
|
+
out.push(`<dt>schemaVersion</dt><dd>${escapeHTML(pack.schemaVersion)}</dd>`);
|
|
686
|
+
for (const line of evidenceSummaryLines(pack)) {
|
|
687
|
+
out.push(`<dt class="gp-line">\xB7</dt><dd>${escapeHTML(line)}</dd>`);
|
|
688
|
+
}
|
|
689
|
+
out.push(`</dl>`);
|
|
690
|
+
for (const section of sections(pack, diagnostics)) {
|
|
691
|
+
out.push(`<section class="gp-section">`);
|
|
692
|
+
out.push(`<h2>${escapeHTML(section.title)}</h2>`);
|
|
693
|
+
if (section.preformatted) {
|
|
694
|
+
out.push(`<pre>${escapeHTML(section.body)}</pre>`);
|
|
695
|
+
} else {
|
|
696
|
+
out.push(`<p>${escapeHTML(section.body).replace(/\n/g, "<br>")}</p>`);
|
|
697
|
+
}
|
|
698
|
+
out.push(`</section>`);
|
|
699
|
+
}
|
|
700
|
+
out.push(`</div>`);
|
|
701
|
+
return out.join("\n");
|
|
702
|
+
}
|
|
703
|
+
function escapeHTML(value) {
|
|
704
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
705
|
+
}
|
|
706
|
+
var NO_DIAGNOSIS_TEXT = "\u2014 (no diagnosis recorded: this pack carries none; run gp_diagnose for this operationId, then gp_export_evidence again)";
|
|
707
|
+
var HANDLER_PROBE_NOT_MEASURED = "handlerProbe: not measured (no probe connection served this act window)";
|
|
708
|
+
var STATE_DIFF_NOT_MEASURED = "stateDiff: not measured (the probe reported no state channel)";
|
|
709
|
+
var AX_EVENT_NOT_MEASURED = "axEvent: not measured (this pack carries no AX tree digest)";
|
|
710
|
+
var PIXEL_DIFF_NOT_MEASURED = "pixelDiff: not measured (this pack carries no pixel comparison)";
|
|
711
|
+
var RESPONSIVENESS_NOT_MEASURED = "responsiveness: not measured (this pack carries no responsiveness round trip)";
|
|
712
|
+
var CRASH_NOT_MEASURED = "crash: not measured (this pack carries no process liveness sample)";
|
|
713
|
+
var MAX_HANDLERS_SHOWN = 8;
|
|
714
|
+
var MAX_ENTRIES_SHOWN = 8;
|
|
715
|
+
function sections(pack, diagnostics) {
|
|
716
|
+
const report = pack.diagnosis?.report;
|
|
717
|
+
const hasDiagnosticsText = diagnostics !== void 0 && diagnostics !== "";
|
|
718
|
+
const reportEvidence = nonEmpty(report?.evidence);
|
|
719
|
+
const absent = pack.diagnosis === null || pack.diagnosis === void 0 ? NO_DIAGNOSIS_TEXT : PLACEHOLDER;
|
|
720
|
+
return [
|
|
721
|
+
{ title: "PATH", body: nonEmpty(report?.path) ?? absent, preformatted: false },
|
|
722
|
+
{ title: "ANOMALY", body: nonEmpty(report?.anomaly) ?? absent, preformatted: false },
|
|
723
|
+
{
|
|
724
|
+
title: "EVIDENCE",
|
|
725
|
+
body: reportEvidence ?? (hasDiagnosticsText && diagnostics !== void 0 ? diagnostics : absent),
|
|
726
|
+
preformatted: reportEvidence === void 0 && hasDiagnosticsText
|
|
727
|
+
},
|
|
728
|
+
{ title: "NEXT", body: nonEmpty(report?.next) ?? absent, preformatted: false }
|
|
729
|
+
];
|
|
730
|
+
}
|
|
731
|
+
function handlerProbeText(handlerProbe) {
|
|
732
|
+
const refs = handlerProbe.handlers.slice(0, MAX_HANDLERS_SHOWN).map((ref) => `${ref.file}:${ref.line}`);
|
|
733
|
+
const hidden = handlerProbe.handlers.length - refs.length;
|
|
734
|
+
if (hidden > 0) {
|
|
735
|
+
refs.push(`+${hidden} more`);
|
|
736
|
+
}
|
|
737
|
+
const list = refs.length === 0 ? "no localized hits" : refs.join(", ");
|
|
738
|
+
return `handlerProbe: probeVersion=${handlerProbe.probeVersion} hitCount=${handlerProbe.hitCount} late=${handlerProbe.lateCount} handlers=[${list}]`;
|
|
739
|
+
}
|
|
740
|
+
function stateDiffText(stateDiff) {
|
|
741
|
+
const rendered = stateDiff.entries.slice(0, MAX_ENTRIES_SHOWN).map((entry) => `${entry.key} "${entry.before}" -> "${entry.after}"`);
|
|
742
|
+
const hidden = stateDiff.entries.length - rendered.length;
|
|
743
|
+
if (hidden > 0) {
|
|
744
|
+
rendered.push(`+${hidden} more`);
|
|
745
|
+
}
|
|
746
|
+
const list = rendered.length === 0 ? "no key changes" : rendered.join(", ");
|
|
747
|
+
return `stateDiff: source=${stateDiff.source} changed=${stateDiff.changed} entries=[${list}]`;
|
|
748
|
+
}
|
|
749
|
+
function nonEmpty(value) {
|
|
750
|
+
return value !== void 0 && value !== "" ? value : void 0;
|
|
751
|
+
}
|
|
752
|
+
function measureLabel(pack) {
|
|
753
|
+
if (pack.diagnosis !== null && pack.diagnosis !== void 0) {
|
|
754
|
+
return pack.diagnosis.class;
|
|
755
|
+
}
|
|
756
|
+
if (pack.assertion !== null && pack.assertion !== void 0) {
|
|
757
|
+
return pack.assertion.property;
|
|
758
|
+
}
|
|
759
|
+
return pack.signals.act.action;
|
|
760
|
+
}
|
|
761
|
+
function levelLabel(level) {
|
|
762
|
+
switch (level) {
|
|
763
|
+
case 0:
|
|
764
|
+
return "normal";
|
|
765
|
+
case 1:
|
|
766
|
+
return "degraded";
|
|
767
|
+
case 2:
|
|
768
|
+
return "act_failed_channel_alive";
|
|
769
|
+
case 3:
|
|
770
|
+
return "channel_fault";
|
|
771
|
+
default:
|
|
772
|
+
return String(level);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
function selectorText(selector) {
|
|
776
|
+
let text = selector.role;
|
|
777
|
+
if (selector.title !== void 0 && selector.title !== "") {
|
|
778
|
+
text += ` "${selector.title}"`;
|
|
779
|
+
}
|
|
780
|
+
if (selector.identifier !== void 0 && selector.identifier !== "") {
|
|
781
|
+
text += ` #${selector.identifier}`;
|
|
782
|
+
}
|
|
783
|
+
return text;
|
|
784
|
+
}
|
|
785
|
+
function valueText(value) {
|
|
786
|
+
return String(value);
|
|
787
|
+
}
|
|
788
|
+
function doubleText(value) {
|
|
789
|
+
if (Number.isNaN(value)) {
|
|
790
|
+
return "nan";
|
|
791
|
+
}
|
|
792
|
+
if (value === Number.POSITIVE_INFINITY) {
|
|
793
|
+
return "inf";
|
|
794
|
+
}
|
|
795
|
+
if (value === Number.NEGATIVE_INFINITY) {
|
|
796
|
+
return "-inf";
|
|
797
|
+
}
|
|
798
|
+
const exponential = value.toExponential(G_SIG_DIGITS - 1);
|
|
799
|
+
const marker = exponential.indexOf("e");
|
|
800
|
+
const mantissa = exponential.slice(0, marker);
|
|
801
|
+
const power = Number(exponential.slice(marker + 1));
|
|
802
|
+
const digits = mantissa.replace("-", "").replace(".", "");
|
|
803
|
+
const body = power >= -4 && power < G_SIG_DIGITS ? fixedFromDigits(digits, power) : exponentialFromDigits(digits, power);
|
|
804
|
+
return mantissa.startsWith("-") ? `-${body}` : body;
|
|
805
|
+
}
|
|
806
|
+
var G_SIG_DIGITS = 6;
|
|
807
|
+
function fixedFromDigits(digits, power) {
|
|
808
|
+
const point = power + 1;
|
|
809
|
+
const intPart = point <= 0 ? "0" : digits.slice(0, point);
|
|
810
|
+
const rawFraction = point <= 0 ? `${"0".repeat(-point)}${digits}` : digits.slice(point);
|
|
811
|
+
const fraction = rawFraction.replace(/0+$/, "");
|
|
812
|
+
return fraction === "" ? intPart : `${intPart}.${fraction}`;
|
|
813
|
+
}
|
|
814
|
+
function exponentialFromDigits(digits, power) {
|
|
815
|
+
const head = digits.slice(0, 1);
|
|
816
|
+
const tail = digits.slice(1).replace(/0+$/, "");
|
|
817
|
+
const mantissa = tail === "" ? head : `${head}.${tail}`;
|
|
818
|
+
return `${mantissa}e${power < 0 ? "-" : "+"}${String(Math.abs(power)).padStart(2, "0")}`;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
// src/tools.ts
|
|
822
|
+
import { z as z5 } from "zod";
|
|
823
|
+
|
|
824
|
+
// ../kernel/dist/schemas.js
|
|
825
|
+
import { createRequire } from "node:module";
|
|
826
|
+
var nodeRequire = createRequire(import.meta.url);
|
|
827
|
+
function loadSchema(relativePath) {
|
|
828
|
+
return nodeRequire(relativePath);
|
|
829
|
+
}
|
|
830
|
+
var EVIDENCE_PACK_JSON_SCHEMA = loadSchema("../schemas/evidence-pack.schema.json");
|
|
831
|
+
var DECISION_LOG_ENTRY_JSON_SCHEMA = loadSchema("../schemas/decision-log-entry.schema.json");
|
|
832
|
+
var RECIPE_CONFIG_JSON_SCHEMA = loadSchema("../schemas/recipe-config.schema.json");
|
|
833
|
+
|
|
834
|
+
// ../kernel/dist/evidence-pack.js
|
|
835
|
+
import { z } from "zod";
|
|
836
|
+
var OPERATION_ID_PATTERN = /^op_[0-9A-HJKMNP-TV-Z]{26}$/;
|
|
837
|
+
var ISO_MILLIS_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
838
|
+
var TREE_DIGEST_PATTERN = /^[0-9a-f]{32}$/;
|
|
839
|
+
var SELECTOR_MAX_LENGTH = 512;
|
|
840
|
+
var EVIDENCE_SCHEMA_VERSION = "glasspane.evidence/0.1";
|
|
841
|
+
var LEGACY_EVIDENCE_SCHEMA_VERSION = "glasspane.evidence/0.1-draft";
|
|
842
|
+
var AttributionLevelSchema = z.enum(["soft", "strong", "weak"]);
|
|
843
|
+
var CircuitBreakerLevelSchema = z.number().int().min(0).max(3);
|
|
844
|
+
var SelectorSchema = z.strictObject({
|
|
845
|
+
role: z.string().max(SELECTOR_MAX_LENGTH),
|
|
846
|
+
title: z.string().max(SELECTOR_MAX_LENGTH).optional(),
|
|
847
|
+
identifier: z.string().max(SELECTOR_MAX_LENGTH).optional()
|
|
848
|
+
});
|
|
849
|
+
var ActionSchema = z.enum([
|
|
850
|
+
"press",
|
|
851
|
+
"increment",
|
|
852
|
+
"decrement",
|
|
853
|
+
"showMenu",
|
|
854
|
+
"confirm",
|
|
855
|
+
"cancel",
|
|
856
|
+
"pick"
|
|
857
|
+
]);
|
|
858
|
+
var AssertionPropertySchema = z.enum([
|
|
859
|
+
"title",
|
|
860
|
+
"value",
|
|
861
|
+
"role",
|
|
862
|
+
"enabled",
|
|
863
|
+
"focused"
|
|
864
|
+
]);
|
|
865
|
+
var StringOrBoolSchema = z.union([z.string(), z.boolean()]);
|
|
866
|
+
var BoundsSchema = z.strictObject({
|
|
867
|
+
x: z.number(),
|
|
868
|
+
y: z.number(),
|
|
869
|
+
width: z.number(),
|
|
870
|
+
height: z.number()
|
|
871
|
+
});
|
|
872
|
+
var AxEventSignalSchema = z.strictObject({
|
|
873
|
+
treeDigestBefore: z.string().regex(TREE_DIGEST_PATTERN),
|
|
874
|
+
treeDigestAfter: z.string().regex(TREE_DIGEST_PATTERN),
|
|
875
|
+
nodeCount: z.number().int().min(0),
|
|
876
|
+
axChanged: z.boolean(),
|
|
877
|
+
latencyMs: z.number().min(0)
|
|
878
|
+
});
|
|
879
|
+
var PixelDiffSignalSchema = z.strictObject({
|
|
880
|
+
changedPixelRatio: z.number().min(0).max(1),
|
|
881
|
+
bounds: z.union([BoundsSchema, z.null()]),
|
|
882
|
+
windowId: z.number().int().min(0)
|
|
883
|
+
});
|
|
884
|
+
var ResponsivenessSignalSchema = z.strictObject({
|
|
885
|
+
responsive: z.boolean(),
|
|
886
|
+
pingMs: z.number().min(0)
|
|
887
|
+
});
|
|
888
|
+
var CrashSignalSchema = z.strictObject({
|
|
889
|
+
processAliveBefore: z.boolean(),
|
|
890
|
+
processAliveAfter: z.boolean()
|
|
891
|
+
});
|
|
892
|
+
var ActSignalSchema = z.strictObject({
|
|
893
|
+
selector: SelectorSchema,
|
|
894
|
+
action: ActionSchema,
|
|
895
|
+
actConfirmed: z.boolean()
|
|
896
|
+
});
|
|
897
|
+
var HandlerRefSchema = z.strictObject({
|
|
898
|
+
file: z.string().min(1).max(512),
|
|
899
|
+
line: z.number().int().min(0)
|
|
900
|
+
});
|
|
901
|
+
var HandlerProbeSignalSchema = z.strictObject({
|
|
902
|
+
probeVersion: z.string().min(1).max(64),
|
|
903
|
+
hitCount: z.number().int().min(0),
|
|
904
|
+
handlers: z.array(HandlerRefSchema).max(32),
|
|
905
|
+
lateCount: z.number().int().min(0)
|
|
906
|
+
});
|
|
907
|
+
var StateEntrySchema = z.strictObject({
|
|
908
|
+
key: z.string().min(1).max(512),
|
|
909
|
+
before: z.string().max(1024),
|
|
910
|
+
after: z.string().max(1024)
|
|
911
|
+
});
|
|
912
|
+
var StateDiffSignalSchema = z.strictObject({
|
|
913
|
+
source: z.enum(["z1-macro", "z2-mirror", "z3-kvc"]),
|
|
914
|
+
changed: z.boolean(),
|
|
915
|
+
entries: z.array(StateEntrySchema).max(64)
|
|
916
|
+
});
|
|
917
|
+
var SignalsSchema = z.strictObject({
|
|
918
|
+
act: ActSignalSchema,
|
|
919
|
+
axEvent: AxEventSignalSchema.optional(),
|
|
920
|
+
// Z5 channel has no in-process probes: explicit null is the honest boundary;
|
|
921
|
+
// P6 §3.1 opens the object alternative once a GlassPaneProbe connects.
|
|
922
|
+
handlerProbe: z.union([HandlerProbeSignalSchema, z.null()]),
|
|
923
|
+
stateDiff: z.union([StateDiffSignalSchema, z.null()]),
|
|
924
|
+
pixelDiff: PixelDiffSignalSchema.optional(),
|
|
925
|
+
responsiveness: ResponsivenessSignalSchema.optional(),
|
|
926
|
+
crash: CrashSignalSchema.optional()
|
|
927
|
+
});
|
|
928
|
+
var AttributionSchema = z.strictObject({
|
|
929
|
+
level: AttributionLevelSchema,
|
|
930
|
+
contaminated: z.boolean()
|
|
931
|
+
});
|
|
932
|
+
var CircuitBreakerSchema = z.strictObject({
|
|
933
|
+
level: CircuitBreakerLevelSchema,
|
|
934
|
+
reason: z.string().optional()
|
|
935
|
+
});
|
|
936
|
+
var AssertionSchema = z.strictObject({
|
|
937
|
+
kind: z.literal("element_property"),
|
|
938
|
+
selector: SelectorSchema,
|
|
939
|
+
property: AssertionPropertySchema,
|
|
940
|
+
expected: StringOrBoolSchema,
|
|
941
|
+
actual: StringOrBoolSchema,
|
|
942
|
+
passed: z.boolean()
|
|
943
|
+
});
|
|
944
|
+
var DiagnosisClassSchema = z.enum([
|
|
945
|
+
"T0",
|
|
946
|
+
"T1",
|
|
947
|
+
"T2",
|
|
948
|
+
"T3",
|
|
949
|
+
"T4",
|
|
950
|
+
"T5",
|
|
951
|
+
"T6",
|
|
952
|
+
"T7",
|
|
953
|
+
"T8",
|
|
954
|
+
"T9",
|
|
955
|
+
"NO_ANOMALY",
|
|
956
|
+
"INCONCLUSIVE"
|
|
957
|
+
]);
|
|
958
|
+
var DiagnosisReportSchema = z.strictObject({
|
|
959
|
+
path: z.string(),
|
|
960
|
+
anomaly: z.string(),
|
|
961
|
+
evidence: z.string(),
|
|
962
|
+
next: z.string()
|
|
963
|
+
});
|
|
964
|
+
var DiagnosisSchema = z.strictObject({
|
|
965
|
+
class: DiagnosisClassSchema,
|
|
966
|
+
report: DiagnosisReportSchema
|
|
967
|
+
});
|
|
968
|
+
var EvidencePackSchema = z.strictObject({
|
|
969
|
+
schemaVersion: z.literal(EVIDENCE_SCHEMA_VERSION),
|
|
970
|
+
operationId: z.string().regex(OPERATION_ID_PATTERN),
|
|
971
|
+
createdAt: z.string().regex(ISO_MILLIS_PATTERN),
|
|
972
|
+
attribution: AttributionSchema,
|
|
973
|
+
circuitBreaker: CircuitBreakerSchema,
|
|
974
|
+
signals: SignalsSchema,
|
|
975
|
+
assertion: z.union([AssertionSchema, z.null()]).optional(),
|
|
976
|
+
diagnosis: z.union([DiagnosisSchema, z.null()]).optional()
|
|
977
|
+
});
|
|
978
|
+
function isObjectRecord(value) {
|
|
979
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
980
|
+
}
|
|
981
|
+
function normalizeEvidencePackForRead(input) {
|
|
982
|
+
if (!isObjectRecord(input)) {
|
|
983
|
+
return input;
|
|
984
|
+
}
|
|
985
|
+
const foldsLegacyVersion = input.schemaVersion === LEGACY_EVIDENCE_SCHEMA_VERSION;
|
|
986
|
+
const signals = isObjectRecord(input.signals) ? input.signals : void 0;
|
|
987
|
+
const pixelDiff = signals === void 0 ? void 0 : signals.pixelDiff;
|
|
988
|
+
const fillsBounds = isObjectRecord(pixelDiff) && signals !== void 0 && !("bounds" in pixelDiff);
|
|
989
|
+
if (!foldsLegacyVersion && !fillsBounds) {
|
|
990
|
+
return input;
|
|
991
|
+
}
|
|
992
|
+
const next = { ...input };
|
|
993
|
+
if (foldsLegacyVersion) {
|
|
994
|
+
next.schemaVersion = EVIDENCE_SCHEMA_VERSION;
|
|
995
|
+
}
|
|
996
|
+
if (fillsBounds && signals !== void 0 && isObjectRecord(pixelDiff)) {
|
|
997
|
+
next.signals = { ...signals, pixelDiff: { ...pixelDiff, bounds: null } };
|
|
998
|
+
}
|
|
999
|
+
return next;
|
|
1000
|
+
}
|
|
1001
|
+
var EvidencePackReadSchema = z.preprocess(normalizeEvidencePackForRead, EvidencePackSchema);
|
|
1002
|
+
|
|
1003
|
+
// ../kernel/dist/decision-log-entry.js
|
|
1004
|
+
import { z as z2 } from "zod";
|
|
1005
|
+
var DECISION_ENTRY_ID_PATTERN = /^dl_[0-9A-HJKMNP-TV-Z]{26}$/;
|
|
1006
|
+
var PREV_ENTRY_HASH_PATTERN = /^([0-9a-f]{64})?$/;
|
|
1007
|
+
var SUMMARY_MAX_LENGTH = 2048;
|
|
1008
|
+
var DecisionOutcomeSchema = z2.enum(["pass", "fail", "blocked", "inconclusive"]);
|
|
1009
|
+
var DecisionLogEntrySchema = z2.strictObject({
|
|
1010
|
+
entryId: z2.string().regex(DECISION_ENTRY_ID_PATTERN),
|
|
1011
|
+
sequence: z2.number().int().min(0),
|
|
1012
|
+
prevEntryHash: z2.string().regex(PREV_ENTRY_HASH_PATTERN),
|
|
1013
|
+
operationId: z2.string().regex(OPERATION_ID_PATTERN).optional(),
|
|
1014
|
+
summary: z2.string().max(SUMMARY_MAX_LENGTH),
|
|
1015
|
+
outcome: DecisionOutcomeSchema,
|
|
1016
|
+
createdAt: z2.string().regex(ISO_MILLIS_PATTERN)
|
|
1017
|
+
});
|
|
1018
|
+
|
|
1019
|
+
// ../kernel/dist/recipe-config.js
|
|
1020
|
+
import { z as z3 } from "zod";
|
|
1021
|
+
var RECIPE_SCHEMA_VERSION = "glasspane.recipe/0.1-draft";
|
|
1022
|
+
var RECIPE_NAME_MAX_LENGTH = 256;
|
|
1023
|
+
var RECIPE_MIN_STEPS = 1;
|
|
1024
|
+
var RECIPE_MAX_STEPS = 64;
|
|
1025
|
+
var RecipeStepKindSchema = z3.enum(["act", "observe", "assert", "diagnose"]);
|
|
1026
|
+
var RecipeStepSchema = z3.strictObject({
|
|
1027
|
+
kind: RecipeStepKindSchema,
|
|
1028
|
+
params: z3.record(z3.unknown())
|
|
1029
|
+
});
|
|
1030
|
+
var RecipeConfigSchema = z3.strictObject({
|
|
1031
|
+
schemaVersion: z3.literal(RECIPE_SCHEMA_VERSION),
|
|
1032
|
+
name: z3.string().max(RECIPE_NAME_MAX_LENGTH),
|
|
1033
|
+
steps: z3.array(RecipeStepSchema).min(RECIPE_MIN_STEPS).max(RECIPE_MAX_STEPS)
|
|
1034
|
+
});
|
|
1035
|
+
|
|
1036
|
+
// ../kernel/dist/errors.js
|
|
1037
|
+
var KernelSchemaError = class extends Error {
|
|
1038
|
+
code = "KERNEL_E_SCHEMA";
|
|
1039
|
+
issues;
|
|
1040
|
+
constructor(label, issues) {
|
|
1041
|
+
const detail = issues.map((issue) => `${issue.path.length > 0 ? issue.path : "<root>"}: ${issue.message}`).join("; ");
|
|
1042
|
+
super(`invalid ${label}: ${detail}`);
|
|
1043
|
+
this.name = "KernelSchemaError";
|
|
1044
|
+
this.issues = issues;
|
|
1045
|
+
}
|
|
1046
|
+
};
|
|
1047
|
+
|
|
1048
|
+
// ../kernel/dist/parse.js
|
|
1049
|
+
function schemaError(label, error) {
|
|
1050
|
+
const issues = error.issues.map((issue) => ({
|
|
1051
|
+
path: issue.path.map((segment) => String(segment)).join("."),
|
|
1052
|
+
message: issue.message
|
|
1053
|
+
}));
|
|
1054
|
+
return new KernelSchemaError(label, issues);
|
|
1055
|
+
}
|
|
1056
|
+
function parseEvidencePackRead(input) {
|
|
1057
|
+
const result = EvidencePackReadSchema.safeParse(input);
|
|
1058
|
+
if (result.success) {
|
|
1059
|
+
return result.data;
|
|
1060
|
+
}
|
|
1061
|
+
throw schemaError("evidence pack", result.error);
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
// src/canonical.ts
|
|
1065
|
+
function canonicalJson(value) {
|
|
1066
|
+
return JSON.stringify(sortKeys(value));
|
|
1067
|
+
}
|
|
1068
|
+
function sortKeys(value) {
|
|
1069
|
+
if (Array.isArray(value)) {
|
|
1070
|
+
return value.map((entry) => sortKeys(entry));
|
|
1071
|
+
}
|
|
1072
|
+
if (value !== null && typeof value === "object") {
|
|
1073
|
+
const record = value;
|
|
1074
|
+
const sorted = {};
|
|
1075
|
+
for (const key of Object.keys(record).sort()) {
|
|
1076
|
+
sorted[key] = sortKeys(record[key]);
|
|
1077
|
+
}
|
|
1078
|
+
return sorted;
|
|
1079
|
+
}
|
|
1080
|
+
return value;
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
// src/project-registry.ts
|
|
1084
|
+
import fs2 from "node:fs";
|
|
1085
|
+
import os2 from "node:os";
|
|
1086
|
+
import path2 from "node:path";
|
|
1087
|
+
import { randomBytes } from "node:crypto";
|
|
1088
|
+
import { z as z4 } from "zod";
|
|
1089
|
+
var CROCKFORD_BODY_RE = "[0-9A-HJKMNP-TV-Z]{26}";
|
|
1090
|
+
var PROJECT_ID_RE = new RegExp(`^prj_${CROCKFORD_BODY_RE}$`);
|
|
1091
|
+
var MAX_PROJECTS = 128;
|
|
1092
|
+
var MAX_DISPLAY_NAME_LENGTH = 256;
|
|
1093
|
+
var MAX_FIELD_LENGTH = 1024;
|
|
1094
|
+
var PID_RANGE = [1, 2147483647];
|
|
1095
|
+
var PATH_FIELDS = [
|
|
1096
|
+
"recipeConfigPath",
|
|
1097
|
+
"calibrationAssetsPath",
|
|
1098
|
+
"evidenceStoragePath"
|
|
1099
|
+
];
|
|
1100
|
+
var PROTECTED_ROOTS = [
|
|
1101
|
+
"/",
|
|
1102
|
+
"/Applications",
|
|
1103
|
+
"/System",
|
|
1104
|
+
"/Library",
|
|
1105
|
+
"/Users",
|
|
1106
|
+
"/private",
|
|
1107
|
+
"/tmp",
|
|
1108
|
+
"/Volumes"
|
|
1109
|
+
];
|
|
1110
|
+
var PROTECTED_SUBTREES = [
|
|
1111
|
+
"/Applications",
|
|
1112
|
+
"/System",
|
|
1113
|
+
"/Library",
|
|
1114
|
+
"/private/etc",
|
|
1115
|
+
"/usr",
|
|
1116
|
+
"/bin",
|
|
1117
|
+
"/sbin",
|
|
1118
|
+
"/dev",
|
|
1119
|
+
"/tmp",
|
|
1120
|
+
"/private/tmp",
|
|
1121
|
+
"/private/var/tmp"
|
|
1122
|
+
];
|
|
1123
|
+
function daemonProjectsPath() {
|
|
1124
|
+
return path2.join(os2.homedir(), ".glasspane", "projects.json");
|
|
1125
|
+
}
|
|
1126
|
+
var FIRMLINK_PREFIX = "/System/Volumes/Data";
|
|
1127
|
+
var FORCE_OVERWRITE_ENV = "GLASSPANE_PROJECTS_FORCE_OVERWRITE";
|
|
1128
|
+
var PROJECTS_FILE_ENV = "GLASSPANE_PROJECTS_FILE";
|
|
1129
|
+
var ProjectListArgs = z4.strictObject({});
|
|
1130
|
+
var ProjectGetArgs = z4.strictObject({
|
|
1131
|
+
projectId: z4.string().regex(PROJECT_ID_RE, "projectId must match prj_ + 26 Crockford chars")
|
|
1132
|
+
});
|
|
1133
|
+
var ProjectSetArgs = z4.strictObject({
|
|
1134
|
+
projectId: z4.string().regex(PROJECT_ID_RE).optional(),
|
|
1135
|
+
displayName: z4.string().min(1).max(MAX_DISPLAY_NAME_LENGTH),
|
|
1136
|
+
// An optional field is *patch*-shaped (B-11): `undefined` keeps what is
|
|
1137
|
+
// stored, `null` clears it, a value replaces it. The exactly-one-of identity
|
|
1138
|
+
// rule deliberately is not a check on this object — it holds of the MERGED
|
|
1139
|
+
// entry, and an update that clears one field while setting the other only
|
|
1140
|
+
// becomes legal after the merge (`assertSingleIdentity`).
|
|
1141
|
+
bundleId: z4.string().max(256).nullish(),
|
|
1142
|
+
pid: z4.number().int().min(PID_RANGE[0]).max(PID_RANGE[1]).nullish(),
|
|
1143
|
+
recipeConfigPath: z4.string().max(MAX_FIELD_LENGTH).nullish(),
|
|
1144
|
+
calibrationAssetsPath: z4.string().max(MAX_FIELD_LENGTH).nullish(),
|
|
1145
|
+
evidenceStoragePath: z4.string().max(MAX_FIELD_LENGTH).nullish()
|
|
1146
|
+
});
|
|
1147
|
+
function projectsPath() {
|
|
1148
|
+
const envPath = process.env[PROJECTS_FILE_ENV];
|
|
1149
|
+
if (envPath) return envPath;
|
|
1150
|
+
return daemonProjectsPath();
|
|
1151
|
+
}
|
|
1152
|
+
function loadRegistry(filePath) {
|
|
1153
|
+
let raw;
|
|
1154
|
+
try {
|
|
1155
|
+
raw = fs2.readFileSync(filePath, "utf8");
|
|
1156
|
+
} catch (error) {
|
|
1157
|
+
if (nodeErrorCode(error) === "ENOENT") {
|
|
1158
|
+
return { projects: [], failure: null };
|
|
1159
|
+
}
|
|
1160
|
+
return { projects: [], failure: `cannot be read (${describeError(error)})` };
|
|
1161
|
+
}
|
|
1162
|
+
let parsed;
|
|
1163
|
+
try {
|
|
1164
|
+
parsed = JSON.parse(raw);
|
|
1165
|
+
} catch (error) {
|
|
1166
|
+
return { projects: [], failure: `is not valid JSON (${describeError(error)})` };
|
|
1167
|
+
}
|
|
1168
|
+
if (!Array.isArray(parsed)) {
|
|
1169
|
+
return { projects: [], failure: "is not a JSON array of projects" };
|
|
1170
|
+
}
|
|
1171
|
+
const projects = [];
|
|
1172
|
+
for (let i = 0; i < parsed.length; i++) {
|
|
1173
|
+
const problem = inspectStoredEntry(parsed[i], i);
|
|
1174
|
+
if (problem !== null) {
|
|
1175
|
+
return { projects: [], failure: problem };
|
|
1176
|
+
}
|
|
1177
|
+
projects.push(parsed[i]);
|
|
1178
|
+
}
|
|
1179
|
+
return { projects, failure: null };
|
|
1180
|
+
}
|
|
1181
|
+
function inspectStoredEntry(raw, index) {
|
|
1182
|
+
const at = `entry ${index}`;
|
|
1183
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
1184
|
+
return `${at} is not an object`;
|
|
1185
|
+
}
|
|
1186
|
+
const record = raw;
|
|
1187
|
+
const stringField = (key, required) => {
|
|
1188
|
+
const value = record[key];
|
|
1189
|
+
if (value === void 0 || value === null) {
|
|
1190
|
+
return required ? `${at} is missing '${key}'` : null;
|
|
1191
|
+
}
|
|
1192
|
+
return typeof value === "string" ? null : `${at} has a non-string '${key}'`;
|
|
1193
|
+
};
|
|
1194
|
+
const requiredStrings = ["projectId", "displayName", "createdAt"];
|
|
1195
|
+
for (const key of requiredStrings) {
|
|
1196
|
+
const problem = stringField(key, true);
|
|
1197
|
+
if (problem) return problem;
|
|
1198
|
+
}
|
|
1199
|
+
const optionalStrings = ["bundleId", ...PATH_FIELDS];
|
|
1200
|
+
for (const key of optionalStrings) {
|
|
1201
|
+
const problem = stringField(key, false);
|
|
1202
|
+
if (problem) return problem;
|
|
1203
|
+
}
|
|
1204
|
+
const pid = record.pid;
|
|
1205
|
+
if (pid !== void 0 && pid !== null) {
|
|
1206
|
+
if (typeof pid !== "number" || !Number.isInteger(pid)) {
|
|
1207
|
+
return `${at} has a non-integer 'pid'`;
|
|
1208
|
+
}
|
|
1209
|
+
if (pid < -2147483648 || pid > 2147483647) {
|
|
1210
|
+
return `${at} has a 'pid' outside the range the daemon can decode (Int32)`;
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
return null;
|
|
1214
|
+
}
|
|
1215
|
+
function requireUsableRegistry(filePath, snapshot) {
|
|
1216
|
+
if (snapshot.failure === null) {
|
|
1217
|
+
return { projects: snapshot.projects };
|
|
1218
|
+
}
|
|
1219
|
+
if (process.env[FORCE_OVERWRITE_ENV] !== "1") {
|
|
1220
|
+
throw new ProjectRegistryError(GP_E_INTERNAL, unreadableMessage(filePath, snapshot.failure));
|
|
1221
|
+
}
|
|
1222
|
+
const discarded = `${filePath}.unreadable-${uniqueToken()}`;
|
|
1223
|
+
try {
|
|
1224
|
+
fs2.renameSync(filePath, discarded);
|
|
1225
|
+
} catch (error) {
|
|
1226
|
+
throw new ProjectRegistryError(
|
|
1227
|
+
GP_E_INTERNAL,
|
|
1228
|
+
`projects.json at ${filePath} ${snapshot.failure}; ${FORCE_OVERWRITE_ENV}=1 asked to move it aside first, but that failed (${describeError(error)}), so nothing was overwritten`
|
|
1229
|
+
);
|
|
1230
|
+
}
|
|
1231
|
+
return { projects: [], discarded };
|
|
1232
|
+
}
|
|
1233
|
+
function unreadableMessage(filePath, failure) {
|
|
1234
|
+
return `projects.json at ${filePath} ${failure}. gp_project_set refused to write it: replacing an unreadable registry discards every registration in it. See the damage with \`python3 -m json.tool ${filePath}\` and repair that file, or set ${FORCE_OVERWRITE_ENV}=1 and retry to rebuild the registry from scratch \u2014 the unloadable file is moved aside as ${filePath}.unreadable-<id> rather than deleted, and every existing project entry is lost.`;
|
|
1235
|
+
}
|
|
1236
|
+
function readFailureMessage(filePath, failure) {
|
|
1237
|
+
return `projects.json at ${filePath} ${failure}. This is a read failure, not an empty registry: the entries that are registered cannot be listed. See the damage with \`python3 -m json.tool ${filePath}\`, then repair or replace that file. To rebuild the registry from scratch instead \u2014 which costs every existing entry \u2014 set ${FORCE_OVERWRITE_ENV}=1 and call gp_project_set again.`;
|
|
1238
|
+
}
|
|
1239
|
+
function saveProjects(filePath, entries) {
|
|
1240
|
+
const dir = path2.dirname(filePath);
|
|
1241
|
+
fs2.mkdirSync(dir, { recursive: true });
|
|
1242
|
+
const tmpPath = `${filePath}.tmp-${uniqueToken()}`;
|
|
1243
|
+
try {
|
|
1244
|
+
fs2.writeFileSync(tmpPath, JSON.stringify(entries, null, 2), "utf8");
|
|
1245
|
+
fs2.renameSync(tmpPath, filePath);
|
|
1246
|
+
} catch (error) {
|
|
1247
|
+
try {
|
|
1248
|
+
fs2.unlinkSync(tmpPath);
|
|
1249
|
+
} catch {
|
|
1250
|
+
}
|
|
1251
|
+
throw error;
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
var tokenCounter = 0;
|
|
1255
|
+
function uniqueToken() {
|
|
1256
|
+
tokenCounter += 1;
|
|
1257
|
+
return `${process.pid}-${Date.now().toString(36)}-${tokenCounter.toString(36)}-${randomBytes(4).toString("hex")}`;
|
|
1258
|
+
}
|
|
1259
|
+
function projectList() {
|
|
1260
|
+
const filePath = projectsPath();
|
|
1261
|
+
const snapshot = loadRegistry(filePath);
|
|
1262
|
+
if (snapshot.failure !== null) {
|
|
1263
|
+
throw new ProjectRegistryError(GP_E_INTERNAL, readFailureMessage(filePath, snapshot.failure));
|
|
1264
|
+
}
|
|
1265
|
+
return snapshot.projects;
|
|
1266
|
+
}
|
|
1267
|
+
function projectGet(projectId) {
|
|
1268
|
+
const projects = projectList();
|
|
1269
|
+
return projects.find((p) => p.projectId === projectId);
|
|
1270
|
+
}
|
|
1271
|
+
function projectSet(args) {
|
|
1272
|
+
const filePath = projectsPath();
|
|
1273
|
+
assertStorablePid(args.pid);
|
|
1274
|
+
const snapshot = loadRegistry(filePath);
|
|
1275
|
+
const { projects, discarded } = requireUsableRegistry(filePath, snapshot);
|
|
1276
|
+
let entry;
|
|
1277
|
+
const projectId = args.projectId;
|
|
1278
|
+
if (projectId) {
|
|
1279
|
+
const existing = projects.find((p) => p.projectId === projectId);
|
|
1280
|
+
if (existing === void 0) {
|
|
1281
|
+
throw new ProjectRegistryError(GP_E_NOT_FOUND, `unknown projectId ${projectId}`);
|
|
1282
|
+
}
|
|
1283
|
+
entry = applyPatch(existing, args);
|
|
1284
|
+
assertSingleIdentity(entry);
|
|
1285
|
+
projects[projects.indexOf(existing)] = entry;
|
|
1286
|
+
} else {
|
|
1287
|
+
if (projects.length >= MAX_PROJECTS) {
|
|
1288
|
+
throw new ProjectRegistryError(GP_E_PROJECT_LIMIT, `project limit reached (${MAX_PROJECTS})`);
|
|
1289
|
+
}
|
|
1290
|
+
entry = applyPatch(
|
|
1291
|
+
{
|
|
1292
|
+
projectId: generateProjectId(),
|
|
1293
|
+
displayName: args.displayName,
|
|
1294
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1295
|
+
},
|
|
1296
|
+
args
|
|
1297
|
+
);
|
|
1298
|
+
assertSingleIdentity(entry);
|
|
1299
|
+
projects.push(entry);
|
|
1300
|
+
}
|
|
1301
|
+
saveProjects(filePath, projects);
|
|
1302
|
+
return {
|
|
1303
|
+
...entry,
|
|
1304
|
+
requiresDaemonRestart: true,
|
|
1305
|
+
daemonRestartNotice: daemonRestartNotice(filePath),
|
|
1306
|
+
...discarded !== void 0 ? { discardedUnreadableFile: discarded } : {}
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
function applyPatch(base, args) {
|
|
1310
|
+
const next = { ...base, displayName: args.displayName };
|
|
1311
|
+
if (args.bundleId !== void 0) {
|
|
1312
|
+
if (args.bundleId === null) delete next.bundleId;
|
|
1313
|
+
else next.bundleId = args.bundleId;
|
|
1314
|
+
}
|
|
1315
|
+
if (args.pid !== void 0) {
|
|
1316
|
+
if (args.pid === null) delete next.pid;
|
|
1317
|
+
else next.pid = args.pid;
|
|
1318
|
+
}
|
|
1319
|
+
for (const field of PATH_FIELDS) {
|
|
1320
|
+
applyPathField(next, field, args[field]);
|
|
1321
|
+
}
|
|
1322
|
+
return next;
|
|
1323
|
+
}
|
|
1324
|
+
function applyPathField(target, field, value) {
|
|
1325
|
+
if (value === void 0) return;
|
|
1326
|
+
if (value === null) {
|
|
1327
|
+
delete target[field];
|
|
1328
|
+
return;
|
|
1329
|
+
}
|
|
1330
|
+
target[field] = checkAgentPath(field, value);
|
|
1331
|
+
}
|
|
1332
|
+
function assertSingleIdentity(entry) {
|
|
1333
|
+
const hasBundleId = entry.bundleId !== void 0;
|
|
1334
|
+
const hasPid = entry.pid !== void 0;
|
|
1335
|
+
if (hasBundleId && hasPid) {
|
|
1336
|
+
throw new ProjectRegistryError(
|
|
1337
|
+
GP_E_BAD_PARAMS,
|
|
1338
|
+
`bundleId (${entry.bundleId}) and pid (${entry.pid}) are both set on projectId ${entry.projectId} \u2014 exactly one of bundleId or pid may identify the app. Pass null for the one to drop (bundleId: null keeps pid, pid: null keeps bundleId); omitting a field keeps whatever is already stored.`
|
|
1339
|
+
);
|
|
1340
|
+
}
|
|
1341
|
+
if (!hasBundleId && !hasPid) {
|
|
1342
|
+
throw new ProjectRegistryError(
|
|
1343
|
+
GP_E_BAD_PARAMS,
|
|
1344
|
+
`projectId ${entry.projectId} would be left with neither bundleId nor pid \u2014 exactly one of bundleId or pid must identify the app (this call cleared the one that was stored). Set bundleId or pid instead of nulling it.`
|
|
1345
|
+
);
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
function daemonRestartNotice(filePath) {
|
|
1349
|
+
const daemonPath = daemonProjectsPath();
|
|
1350
|
+
if (path2.resolve(filePath) !== path2.resolve(daemonPath)) {
|
|
1351
|
+
return `Saved in ${filePath}, but the background service never reads that file: it loads ${daemonPath} once when it starts (${PROJECTS_FILE_ENV} is honoured by this MCP shell only, not by the daemon), so gp_attach will keep returning GP_E_NOT_FOUND for this projectId and restarting the service will not help. Repeat the registration against ${daemonPath} \u2014 unset ${PROJECTS_FILE_ENV} for the shell, or write the entry where the daemon looks \u2014 and only then restart the background service so it reloads: ${restartCommand()}`;
|
|
1352
|
+
}
|
|
1353
|
+
return `Saved in ${filePath}, but the running background service loaded that file once when it started, so gp_attach will keep returning GP_E_NOT_FOUND for this projectId until the service restarts: ${restartCommand()}`;
|
|
1354
|
+
}
|
|
1355
|
+
function restartCommand() {
|
|
1356
|
+
return `run \`launchctl kickstart -k gui/${currentUid()}/com.glasspane.daemon\` \u2014 if that reports the service was not found, the launchd job was never bootstrapped, so ${daemonUnreachableRemedy()}`;
|
|
1357
|
+
}
|
|
1358
|
+
function currentUid() {
|
|
1359
|
+
return typeof process.getuid === "function" ? process.getuid() : 0;
|
|
1360
|
+
}
|
|
1361
|
+
function assertStorablePid(pid) {
|
|
1362
|
+
if (pid === void 0 || pid === null) return;
|
|
1363
|
+
if (!Number.isInteger(pid) || pid < PID_RANGE[0] || pid > PID_RANGE[1]) {
|
|
1364
|
+
throw new ProjectRegistryError(
|
|
1365
|
+
GP_E_BAD_PARAMS,
|
|
1366
|
+
`pid must be an integer in ${PID_RANGE[0]}..${PID_RANGE[1]} (given: ${pid}) \u2014 the background service stores it as a 32-bit process id, and a value outside that range makes it discard every registration in projects.json`
|
|
1367
|
+
);
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
function checkAgentPath(field, value) {
|
|
1371
|
+
if (!value.startsWith("/")) {
|
|
1372
|
+
throw badPath(field, value, `must be an absolute path (got "${value}")`);
|
|
1373
|
+
}
|
|
1374
|
+
for (const component of value.split("/")) {
|
|
1375
|
+
if (component === "." || component === "..") {
|
|
1376
|
+
throw badPath(field, value, `must not contain "." or ".." components (got "${value}")`);
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
const logical = path2.posix.normalize(value);
|
|
1380
|
+
const given = stripFirmlink(logical);
|
|
1381
|
+
const resolved = stripFirmlink(resolveExistingAncestor(logical));
|
|
1382
|
+
const refusal = strongestRefusal(given === resolved ? [resolved] : [resolved, given], resolved);
|
|
1383
|
+
if (refusal !== null) {
|
|
1384
|
+
throw badPath(field, value, refusalPhrase(refusal, resolved));
|
|
1385
|
+
}
|
|
1386
|
+
return logical;
|
|
1387
|
+
}
|
|
1388
|
+
function strongestRefusal(targets, resolved) {
|
|
1389
|
+
let best = null;
|
|
1390
|
+
for (const target of targets) {
|
|
1391
|
+
const refusal = refuseCandidate(target);
|
|
1392
|
+
if (refusal === null) continue;
|
|
1393
|
+
const ranked = {
|
|
1394
|
+
target,
|
|
1395
|
+
reason: refusal.reason,
|
|
1396
|
+
rank: (refusal.source === "named" ? 2 : 0) + (target === resolved ? 1 : 0)
|
|
1397
|
+
};
|
|
1398
|
+
if (best === null || ranked.rank > best.rank) {
|
|
1399
|
+
best = ranked;
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
return best;
|
|
1403
|
+
}
|
|
1404
|
+
function refusalPhrase(refusal, resolved) {
|
|
1405
|
+
if (refusal.target === resolved) {
|
|
1406
|
+
return `resolves to ${resolved}, which is ${refusal.reason}`;
|
|
1407
|
+
}
|
|
1408
|
+
return `is ${refusal.target}, which is ${refusal.reason}; that path resolves to ${resolved}`;
|
|
1409
|
+
}
|
|
1410
|
+
function badPath(field, value, problem) {
|
|
1411
|
+
return new ProjectRegistryError(
|
|
1412
|
+
GP_E_BAD_PARAMS,
|
|
1413
|
+
`${field} ${problem}. ${PATH_SHAPE_HINT} (given: "${value}")`
|
|
1414
|
+
);
|
|
1415
|
+
}
|
|
1416
|
+
var PATH_SHAPE_HINT = `An acceptable value is a project-owned directory at least two levels deep, e.g. "/Users/you/work/notes-app/.glasspane/evidence": absolute, with no "." or ".." components, not world-writable, with its nearest existing directory owned by the user running this shell (never a shared tree such as /Users/Shared, another user's home, /private/tmp, or a top-level directory of the boot volume), and not the filesystem root, a mounted volume root, your home directory, anything under ~/Library, or a system-owned tree (${PROTECTED_SUBTREES.join(", ")}) \u2014 the daemon writes evidence into this directory and deletes expired entries from it`;
|
|
1417
|
+
function refuseCandidate(target) {
|
|
1418
|
+
const home = stripFirmlink(path2.posix.normalize(os2.homedir()));
|
|
1419
|
+
if (target === home) return named("the current user's home directory");
|
|
1420
|
+
if (isInside(`${home}/Library`, target)) return named("inside the current user's Library folder");
|
|
1421
|
+
if (isProtectedRoot(target)) return named("a protected system root");
|
|
1422
|
+
const components = target.split("/").filter((c) => c !== "");
|
|
1423
|
+
if (components.length === 0) return named("the filesystem root");
|
|
1424
|
+
if (components[0] === "Volumes" && components.length === 2) {
|
|
1425
|
+
return named("a top-level mounted volume root");
|
|
1426
|
+
}
|
|
1427
|
+
if (components.length === 1) return named("a top-level directory of the boot volume");
|
|
1428
|
+
for (const tree of PROTECTED_SUBTREES) {
|
|
1429
|
+
if (isInside(tree, target)) return named(`inside the system-owned tree ${tree}`);
|
|
1430
|
+
}
|
|
1431
|
+
const unowned = refuseUnownedTree(target);
|
|
1432
|
+
return unowned === null ? null : { source: "ownership", reason: unowned };
|
|
1433
|
+
}
|
|
1434
|
+
function named(reason) {
|
|
1435
|
+
return { source: "named", reason };
|
|
1436
|
+
}
|
|
1437
|
+
function refuseUnownedTree(target) {
|
|
1438
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : null;
|
|
1439
|
+
const ancestor = nearestExistingAncestor(target);
|
|
1440
|
+
if (uid === null) {
|
|
1441
|
+
return `on a platform where this shell has no user id to compare against, so the owner of its nearest existing directory ${ancestor} cannot be checked`;
|
|
1442
|
+
}
|
|
1443
|
+
let stat;
|
|
1444
|
+
try {
|
|
1445
|
+
stat = fs2.statSync(ancestor);
|
|
1446
|
+
} catch (error) {
|
|
1447
|
+
return `under a nearest existing directory ${ancestor} that cannot be inspected (${describeError(error)})`;
|
|
1448
|
+
}
|
|
1449
|
+
if (stat.uid !== uid) {
|
|
1450
|
+
return `not under a directory owned by the current user: its nearest existing directory ${ancestor} belongs to uid ${stat.uid}, not uid ${uid}`;
|
|
1451
|
+
}
|
|
1452
|
+
if ((stat.mode & 18) !== 0) {
|
|
1453
|
+
return `under the world-writable directory ${ancestor} (mode ${(stat.mode & 511).toString(8)}), where any user can place a file or a link that this archive would then be written into and pruned from`;
|
|
1454
|
+
}
|
|
1455
|
+
return null;
|
|
1456
|
+
}
|
|
1457
|
+
function nearestExistingAncestor(target) {
|
|
1458
|
+
let cursor = target;
|
|
1459
|
+
for (; ; ) {
|
|
1460
|
+
if (fs2.existsSync(cursor)) {
|
|
1461
|
+
return cursor;
|
|
1462
|
+
}
|
|
1463
|
+
const parent = path2.posix.dirname(cursor);
|
|
1464
|
+
if (parent === cursor) return parent;
|
|
1465
|
+
cursor = parent;
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
function isProtectedRoot(target) {
|
|
1469
|
+
return PROTECTED_ROOTS.includes(target);
|
|
1470
|
+
}
|
|
1471
|
+
function isInside(root, target) {
|
|
1472
|
+
return target === root || target.startsWith(`${root}/`);
|
|
1473
|
+
}
|
|
1474
|
+
function stripFirmlink(target) {
|
|
1475
|
+
if (target === FIRMLINK_PREFIX) return "/";
|
|
1476
|
+
return target.startsWith(`${FIRMLINK_PREFIX}/`) ? `/${target.slice(FIRMLINK_PREFIX.length + 1)}` : target;
|
|
1477
|
+
}
|
|
1478
|
+
function resolveExistingAncestor(target) {
|
|
1479
|
+
let cursor = target;
|
|
1480
|
+
const missingTail = [];
|
|
1481
|
+
for (; ; ) {
|
|
1482
|
+
try {
|
|
1483
|
+
const real = fs2.realpathSync(cursor);
|
|
1484
|
+
return missingTail.length === 0 ? real : path2.posix.join(real, ...missingTail);
|
|
1485
|
+
} catch {
|
|
1486
|
+
const parent = path2.posix.dirname(cursor);
|
|
1487
|
+
if (parent === cursor) return target;
|
|
1488
|
+
missingTail.unshift(path2.posix.basename(cursor));
|
|
1489
|
+
cursor = parent;
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
function generateProjectId() {
|
|
1494
|
+
const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
1495
|
+
const body = [];
|
|
1496
|
+
const bytes = new Uint8Array(26);
|
|
1497
|
+
if (typeof globalThis.crypto?.getRandomValues === "function") {
|
|
1498
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
1499
|
+
} else {
|
|
1500
|
+
for (let i = 0; i < 26; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
1501
|
+
}
|
|
1502
|
+
for (let i = 0; i < 26; i++) {
|
|
1503
|
+
const byte = bytes[i];
|
|
1504
|
+
body.push(CROCKFORD.charAt(byte % 32));
|
|
1505
|
+
}
|
|
1506
|
+
return `prj_${body.join("")}`;
|
|
1507
|
+
}
|
|
1508
|
+
function nodeErrorCode(error) {
|
|
1509
|
+
return error?.code;
|
|
1510
|
+
}
|
|
1511
|
+
function describeError(error) {
|
|
1512
|
+
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
1513
|
+
return String(error);
|
|
1514
|
+
}
|
|
1515
|
+
var ProjectRegistryError = class extends Error {
|
|
1516
|
+
code;
|
|
1517
|
+
constructor(code, message) {
|
|
1518
|
+
super(message);
|
|
1519
|
+
this.name = "ProjectRegistryError";
|
|
1520
|
+
this.code = code;
|
|
1521
|
+
}
|
|
1522
|
+
};
|
|
1523
|
+
|
|
1524
|
+
// src/tools.ts
|
|
1525
|
+
var PID_INT32_MAX = 2147483647;
|
|
1526
|
+
var OptionalPidSchema = z5.number().int().min(1).max(PID_INT32_MAX).optional();
|
|
1527
|
+
var OptionalDepthSchema = z5.number().int().min(1).max(10).optional();
|
|
1528
|
+
var OptionalRoleSchema = z5.string().max(128).optional();
|
|
1529
|
+
var OptionalBundleIdSchema = z5.string().max(256).optional();
|
|
1530
|
+
var OptionalOperationIdSchema = z5.string().regex(/^op_[0-9A-HJKMNP-TV-Z]{26}$/).optional();
|
|
1531
|
+
var OptionalProjectIdSchema = z5.string().regex(/^prj_[0-9A-HJKMNP-TV-Z]{26}$/).optional();
|
|
1532
|
+
var ExpectSchema = z5.union([z5.string().max(512), z5.boolean()]);
|
|
1533
|
+
var SnapshotIdSchema = z5.string().regex(/^snap_[0-9A-HJKMNP-TV-Z]{26}$/);
|
|
1534
|
+
var ActStepSchema = z5.strictObject({
|
|
1535
|
+
selector: SelectorSchema,
|
|
1536
|
+
action: ActionSchema
|
|
1537
|
+
});
|
|
1538
|
+
var RestoreStepsSchema = z5.array(ActStepSchema).min(1).max(64).optional();
|
|
1539
|
+
var RESTORE_MODES = [
|
|
1540
|
+
"compare",
|
|
1541
|
+
"ffwd",
|
|
1542
|
+
"restore_snapshot",
|
|
1543
|
+
"rollback_full"
|
|
1544
|
+
];
|
|
1545
|
+
var RestoreModeSchema = z5.enum(RESTORE_MODES).optional();
|
|
1546
|
+
var AttachArgs = z5.strictObject({
|
|
1547
|
+
bundleId: OptionalBundleIdSchema,
|
|
1548
|
+
pid: OptionalPidSchema,
|
|
1549
|
+
projectId: OptionalProjectIdSchema
|
|
1550
|
+
}).refine((v) => v.bundleId !== void 0 || v.pid !== void 0, {
|
|
1551
|
+
message: "attach requires either bundleId or pid"
|
|
1552
|
+
});
|
|
1553
|
+
var ObserveArgs = z5.strictObject({
|
|
1554
|
+
maxDepth: OptionalDepthSchema,
|
|
1555
|
+
role: OptionalRoleSchema
|
|
1556
|
+
});
|
|
1557
|
+
var OptionalHitTargetSchema = z5.number().min(1).max(400).optional();
|
|
1558
|
+
var OptionalScaleSchema = z5.number().min(0.1).max(1).optional();
|
|
1559
|
+
var CaptureViewArgs = z5.strictObject({
|
|
1560
|
+
scale: OptionalScaleSchema
|
|
1561
|
+
});
|
|
1562
|
+
var AuditUiArgs = z5.strictObject({
|
|
1563
|
+
maxDepth: OptionalDepthSchema,
|
|
1564
|
+
minHitTargetPt: OptionalHitTargetSchema
|
|
1565
|
+
});
|
|
1566
|
+
var ActArgs = z5.strictObject({
|
|
1567
|
+
selector: SelectorSchema,
|
|
1568
|
+
action: ActionSchema,
|
|
1569
|
+
degrade: z5.boolean().optional()
|
|
1570
|
+
});
|
|
1571
|
+
var AssertElementArgs = z5.strictObject({
|
|
1572
|
+
selector: SelectorSchema,
|
|
1573
|
+
property: AssertionPropertySchema,
|
|
1574
|
+
expected: ExpectSchema
|
|
1575
|
+
});
|
|
1576
|
+
var DiagnoseArgs = z5.strictObject({
|
|
1577
|
+
operationId: OptionalOperationIdSchema
|
|
1578
|
+
});
|
|
1579
|
+
var LastEvidenceArgs = z5.strictObject({
|
|
1580
|
+
operationId: OptionalOperationIdSchema
|
|
1581
|
+
});
|
|
1582
|
+
var SnapshotArgs = z5.strictObject({
|
|
1583
|
+
maxDepth: OptionalDepthSchema
|
|
1584
|
+
});
|
|
1585
|
+
var RestoreArgs = z5.strictObject({
|
|
1586
|
+
snapshotId: SnapshotIdSchema,
|
|
1587
|
+
steps: RestoreStepsSchema,
|
|
1588
|
+
mode: RestoreModeSchema
|
|
1589
|
+
});
|
|
1590
|
+
var ProbeStatusArgs = z5.strictObject({});
|
|
1591
|
+
var ReportFormatSchema = z5.enum(["html", "markdown"]).default("markdown");
|
|
1592
|
+
var ExportEvidenceArgs = z5.strictObject({
|
|
1593
|
+
operationId: z5.string().regex(/^op_[0-9A-HJKMNP-TV-Z]{26}$/),
|
|
1594
|
+
format: ReportFormatSchema
|
|
1595
|
+
});
|
|
1596
|
+
var RecentReportsArgs = z5.strictObject({
|
|
1597
|
+
limit: z5.number().int().min(1).max(20).default(5),
|
|
1598
|
+
format: ReportFormatSchema
|
|
1599
|
+
});
|
|
1600
|
+
function zodIssueText(error) {
|
|
1601
|
+
return error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
|
|
1602
|
+
}
|
|
1603
|
+
function zodBridge(schema) {
|
|
1604
|
+
return (raw) => {
|
|
1605
|
+
const parsed = schema.safeParse(raw);
|
|
1606
|
+
if (parsed.success) {
|
|
1607
|
+
return { ok: true, value: parsed.data };
|
|
1608
|
+
}
|
|
1609
|
+
return { ok: false, issues: zodIssueText(parsed.error) };
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
var selectorJsonSchema = {
|
|
1613
|
+
type: "object",
|
|
1614
|
+
additionalProperties: false,
|
|
1615
|
+
properties: {
|
|
1616
|
+
role: { type: "string", maxLength: 512 },
|
|
1617
|
+
title: { type: "string", maxLength: 512 },
|
|
1618
|
+
identifier: { type: "string", maxLength: 512 }
|
|
1619
|
+
},
|
|
1620
|
+
required: ["role"]
|
|
1621
|
+
};
|
|
1622
|
+
var TOOL_SPECS = [
|
|
1623
|
+
{
|
|
1624
|
+
name: "gp_attach",
|
|
1625
|
+
description: "Attach the engine to a running app by bundleId or pid.",
|
|
1626
|
+
engineMethod: "attach",
|
|
1627
|
+
inputSchema: {
|
|
1628
|
+
type: "object",
|
|
1629
|
+
additionalProperties: false,
|
|
1630
|
+
properties: {
|
|
1631
|
+
bundleId: { type: "string", maxLength: 256 },
|
|
1632
|
+
pid: { type: "integer", minimum: 1, maximum: PID_INT32_MAX },
|
|
1633
|
+
projectId: { type: "string", pattern: "^prj_[0-9A-HJKMNP-TV-Z]{26}$" }
|
|
1634
|
+
},
|
|
1635
|
+
oneOf: [
|
|
1636
|
+
{ required: ["bundleId"] },
|
|
1637
|
+
{ required: ["pid"] }
|
|
1638
|
+
]
|
|
1639
|
+
},
|
|
1640
|
+
validate: zodBridge(AttachArgs)
|
|
1641
|
+
},
|
|
1642
|
+
{
|
|
1643
|
+
name: "gp_observe",
|
|
1644
|
+
description: "Snapshot the attached app's accessibility tree.",
|
|
1645
|
+
engineMethod: "observe",
|
|
1646
|
+
inputSchema: {
|
|
1647
|
+
type: "object",
|
|
1648
|
+
additionalProperties: false,
|
|
1649
|
+
properties: {
|
|
1650
|
+
maxDepth: { type: "integer", minimum: 1, maximum: 10 },
|
|
1651
|
+
role: { type: "string", maxLength: 128 }
|
|
1652
|
+
}
|
|
1653
|
+
},
|
|
1654
|
+
validate: zodBridge(ObserveArgs)
|
|
1655
|
+
},
|
|
1656
|
+
{
|
|
1657
|
+
name: "gp_act",
|
|
1658
|
+
description: "Perform a UI action on the attached app and confirm it. If the daemon reports GP_E_BUSY_INPUT (real user input is contaminating the window), retry later, or set degrade: true to proceed immediately with the contamination recorded in evidence (attribution becomes weak + contaminated=true) \u2014 never silently clean. Prefer selector.identifier over selector.title to name the element: a title is not a stable handle (a measured case: every act against a title-keyed selector reported actConfirmed while the app's handler never ran, because the press resolved to something that was not the button). actConfirmed means the accessibility action was accepted \u2014 not that the intended element handled it; to prove the click itself, read the probe's handler hit or the state change, or assert_element against a value that the action is supposed to change.",
|
|
1659
|
+
engineMethod: "act",
|
|
1660
|
+
inputSchema: {
|
|
1661
|
+
type: "object",
|
|
1662
|
+
additionalProperties: false,
|
|
1663
|
+
properties: {
|
|
1664
|
+
selector: selectorJsonSchema,
|
|
1665
|
+
action: {
|
|
1666
|
+
type: "string",
|
|
1667
|
+
enum: ["press", "increment", "decrement", "showMenu", "confirm", "cancel", "pick"]
|
|
1668
|
+
},
|
|
1669
|
+
degrade: { type: "boolean" }
|
|
1670
|
+
},
|
|
1671
|
+
required: ["selector", "action"]
|
|
1672
|
+
},
|
|
1673
|
+
validate: zodBridge(ActArgs)
|
|
1674
|
+
},
|
|
1675
|
+
{
|
|
1676
|
+
name: "gp_assert_element",
|
|
1677
|
+
description: "Assert a property of an element in the attached app.",
|
|
1678
|
+
engineMethod: "assert_element",
|
|
1679
|
+
inputSchema: {
|
|
1680
|
+
type: "object",
|
|
1681
|
+
additionalProperties: false,
|
|
1682
|
+
properties: {
|
|
1683
|
+
selector: selectorJsonSchema,
|
|
1684
|
+
property: { type: "string", enum: ["title", "value", "role", "enabled", "focused"] },
|
|
1685
|
+
expected: { oneOf: [{ type: "string", maxLength: 512 }, { type: "boolean" }] }
|
|
1686
|
+
},
|
|
1687
|
+
required: ["selector", "property", "expected"]
|
|
1688
|
+
},
|
|
1689
|
+
validate: zodBridge(AssertElementArgs)
|
|
1690
|
+
},
|
|
1691
|
+
{
|
|
1692
|
+
name: "gp_audit_ui",
|
|
1693
|
+
description: "Audit the attached app's layout for operability: element geometry plus deterministic rules report zero-sized or out-of-window controls (blocking), undersized hit targets, clipped elements and frame overlaps (advisory). The verdict distinguishes pass from insufficient: unmeasured geometry never counts as a clean result. Read-only \u2014 it records no operation.",
|
|
1694
|
+
engineMethod: "audit_ui",
|
|
1695
|
+
inputSchema: {
|
|
1696
|
+
type: "object",
|
|
1697
|
+
additionalProperties: false,
|
|
1698
|
+
properties: {
|
|
1699
|
+
maxDepth: { type: "integer", minimum: 1, maximum: 10 },
|
|
1700
|
+
minHitTargetPt: { type: "number", minimum: 1, maximum: 400 }
|
|
1701
|
+
}
|
|
1702
|
+
},
|
|
1703
|
+
validate: zodBridge(AuditUiArgs)
|
|
1704
|
+
},
|
|
1705
|
+
{
|
|
1706
|
+
name: "gp_capture_view",
|
|
1707
|
+
description: "Send the attached app's current window to your model once, as a PNG, for visual review. This is the only tool that moves image pixels, and it is a pass-through: the engine encodes the capture and writes nothing to disk (the result says persisted: false). Use it for what measurements cannot judge \u2014 visual taste, layout that reads as wrong, content with no accessibility tree. For anything assertable, prefer gp_audit_ui / gp_assert_element: a measurement repeats, a visual impression does not. `scale` is a pixel-density factor applied to the captured image (window size is reported separately in points as pointSize), and the summary states both the requested scale and the appliedScale actually present in the image. WARNING: the image enters this conversation, so anything your model provider logs will retain whatever was on screen. Needs the daemon's Screen Recording grant; oversized windows are refused with a suggested scale rather than silently downsampled.",
|
|
1708
|
+
engineMethod: "capture_view",
|
|
1709
|
+
inputSchema: {
|
|
1710
|
+
type: "object",
|
|
1711
|
+
additionalProperties: false,
|
|
1712
|
+
properties: {
|
|
1713
|
+
scale: { type: "number", minimum: 0.1, maximum: 1 }
|
|
1714
|
+
}
|
|
1715
|
+
},
|
|
1716
|
+
validate: zodBridge(CaptureViewArgs),
|
|
1717
|
+
execute: captureView
|
|
1718
|
+
},
|
|
1719
|
+
{
|
|
1720
|
+
name: "gp_diagnose",
|
|
1721
|
+
description: "Diagnose the most recent (or the given) operation.",
|
|
1722
|
+
engineMethod: "diagnose",
|
|
1723
|
+
inputSchema: {
|
|
1724
|
+
type: "object",
|
|
1725
|
+
additionalProperties: false,
|
|
1726
|
+
properties: {
|
|
1727
|
+
operationId: { type: "string", pattern: "^op_[0-9A-HJKMNP-TV-Z]{26}$" }
|
|
1728
|
+
}
|
|
1729
|
+
},
|
|
1730
|
+
validate: zodBridge(DiagnoseArgs)
|
|
1731
|
+
},
|
|
1732
|
+
{
|
|
1733
|
+
name: "gp_last_evidence",
|
|
1734
|
+
description: "Return the full evidence pack for the most recent (or given) operation.",
|
|
1735
|
+
engineMethod: "last_evidence",
|
|
1736
|
+
inputSchema: {
|
|
1737
|
+
type: "object",
|
|
1738
|
+
additionalProperties: false,
|
|
1739
|
+
properties: {
|
|
1740
|
+
operationId: { type: "string", pattern: "^op_[0-9A-HJKMNP-TV-Z]{26}$" }
|
|
1741
|
+
}
|
|
1742
|
+
},
|
|
1743
|
+
validate: zodBridge(LastEvidenceArgs)
|
|
1744
|
+
},
|
|
1745
|
+
{
|
|
1746
|
+
name: "gp_snapshot",
|
|
1747
|
+
description: "Capture a digest-only baseline of the attached app's AX tree for later restore.",
|
|
1748
|
+
engineMethod: "snapshot",
|
|
1749
|
+
inputSchema: {
|
|
1750
|
+
type: "object",
|
|
1751
|
+
additionalProperties: false,
|
|
1752
|
+
properties: {
|
|
1753
|
+
maxDepth: { type: "integer", minimum: 1, maximum: 10 }
|
|
1754
|
+
}
|
|
1755
|
+
},
|
|
1756
|
+
validate: zodBridge(SnapshotArgs)
|
|
1757
|
+
},
|
|
1758
|
+
{
|
|
1759
|
+
name: "gp_restore",
|
|
1760
|
+
description: "Restore from a snapshot: replay act steps over the baseline (tier-2 ffwd), or compare the current tree against it when steps are omitted.",
|
|
1761
|
+
engineMethod: "restore",
|
|
1762
|
+
inputSchema: {
|
|
1763
|
+
type: "object",
|
|
1764
|
+
additionalProperties: false,
|
|
1765
|
+
properties: {
|
|
1766
|
+
snapshotId: { type: "string", pattern: "^snap_[0-9A-HJKMNP-TV-Z]{26}$" },
|
|
1767
|
+
steps: {
|
|
1768
|
+
type: "array",
|
|
1769
|
+
minItems: 1,
|
|
1770
|
+
maxItems: 64,
|
|
1771
|
+
items: {
|
|
1772
|
+
type: "object",
|
|
1773
|
+
additionalProperties: false,
|
|
1774
|
+
properties: {
|
|
1775
|
+
selector: selectorJsonSchema,
|
|
1776
|
+
action: {
|
|
1777
|
+
type: "string",
|
|
1778
|
+
enum: ["press", "increment", "decrement", "showMenu", "confirm", "cancel", "pick"]
|
|
1779
|
+
}
|
|
1780
|
+
},
|
|
1781
|
+
required: ["selector", "action"]
|
|
1782
|
+
}
|
|
1783
|
+
},
|
|
1784
|
+
mode: { type: "string", enum: [...RESTORE_MODES] }
|
|
1785
|
+
},
|
|
1786
|
+
required: ["snapshotId"]
|
|
1787
|
+
},
|
|
1788
|
+
validate: zodBridge(RestoreArgs)
|
|
1789
|
+
},
|
|
1790
|
+
{
|
|
1791
|
+
name: "gp_probe_status",
|
|
1792
|
+
description: "List GlassPaneProbe connections and whether the attached app has a live probe \u2014 probe presence is what makes T4/T5/T7/T8 verdicts and tier-1 checkpoint restores decidable. `attachedHasProbe` is that yes/no for the attached app; `probes` holds **live** registrations only (every row `connected: true`), so a probe that dropped is absent from it rather than flagged inside it: read `recentDisconnections` for that history (`pid`, `disconnectReason`, `disconnectedAt`, per-pid `drops`), and `disconnections` is just the total count since start. Each live row can also carry the frame-accounting that makes a zero verdict readable: `stateFramesUnmappedSource` (daemon-side, per pid), and `droppedEvents` / `droppedWrites` / `rejectedKeys` as the probe itself reported them \u2014 those are **absent when unreported**, which is not the same as zero, and `unmapableStateFrames` is the daemon-side total that survives a disconnect. The same reply is where the T9 degradation watch is readable without performing an action, under `degradation` (absent when this daemon runs without T9 wired): `tier` is `healthy` / `watch` / `degrading`, and `judged` says whether that tier is a measurement at all \u2014 `judged: false` with `tier: healthy` means the window was too thin or too short to read, **not** that the app is clean; `basis` spells out which of those it is with the numbers, alongside `samples`/`minimumSamples` and `spanSeconds`/`minimumSpanSeconds`. `longSession` marks the window spanning at least the long-session threshold; it is context for the trend, and it never changes `tier` by itself. `drivers` appears only when something is trending, and `slopes` carries only the channels that produced one (`pingMsPerSec`, `memoryBytesPerSec`, `handlesPerSec`) \u2014 a channel missing from `slopes` was never read, which is not a rate of zero.",
|
|
1793
|
+
engineMethod: "probe_status",
|
|
1794
|
+
inputSchema: {
|
|
1795
|
+
type: "object",
|
|
1796
|
+
additionalProperties: false,
|
|
1797
|
+
properties: {}
|
|
1798
|
+
},
|
|
1799
|
+
validate: zodBridge(ProbeStatusArgs)
|
|
1800
|
+
},
|
|
1801
|
+
{
|
|
1802
|
+
name: "gp_export_evidence",
|
|
1803
|
+
description: "Render one operation's evidence pack as a human-readable report (HTML or Markdown) for the developer audit view.",
|
|
1804
|
+
engineMethod: "export_evidence",
|
|
1805
|
+
inputSchema: {
|
|
1806
|
+
type: "object",
|
|
1807
|
+
additionalProperties: false,
|
|
1808
|
+
properties: {
|
|
1809
|
+
operationId: { type: "string", pattern: "^op_[0-9A-HJKMNP-TV-Z]{26}$" },
|
|
1810
|
+
format: { type: "string", enum: ["html", "markdown"] }
|
|
1811
|
+
},
|
|
1812
|
+
required: ["operationId"]
|
|
1813
|
+
},
|
|
1814
|
+
validate: zodBridge(ExportEvidenceArgs),
|
|
1815
|
+
execute: exportEvidence
|
|
1816
|
+
},
|
|
1817
|
+
{
|
|
1818
|
+
name: "gp_recent_reports",
|
|
1819
|
+
description: "Aggregate the most recent operations' four-section reports (HTML or Markdown) into one audit view.",
|
|
1820
|
+
engineMethod: "recent_reports",
|
|
1821
|
+
inputSchema: {
|
|
1822
|
+
type: "object",
|
|
1823
|
+
additionalProperties: false,
|
|
1824
|
+
properties: {
|
|
1825
|
+
limit: { type: "integer", minimum: 1, maximum: 20 },
|
|
1826
|
+
format: { type: "string", enum: ["html", "markdown"] }
|
|
1827
|
+
}
|
|
1828
|
+
},
|
|
1829
|
+
validate: zodBridge(RecentReportsArgs),
|
|
1830
|
+
execute: recentReports
|
|
1831
|
+
},
|
|
1832
|
+
{
|
|
1833
|
+
name: "gp_project_list",
|
|
1834
|
+
description: "List all registered GlassPane projects (P1 spec v1.4).",
|
|
1835
|
+
engineMethod: "project_list",
|
|
1836
|
+
inputSchema: {
|
|
1837
|
+
type: "object",
|
|
1838
|
+
additionalProperties: false,
|
|
1839
|
+
properties: {}
|
|
1840
|
+
},
|
|
1841
|
+
validate: zodBridge(ProjectListArgs),
|
|
1842
|
+
execute: projectListTool
|
|
1843
|
+
},
|
|
1844
|
+
{
|
|
1845
|
+
name: "gp_project_set",
|
|
1846
|
+
description: "Create or update a GlassPane project. Omit projectId to register a new project; include it to update an existing one. Exactly one of bundleId or pid identifies the app: passing both is refused, and on update omitting both keeps the stored identity. Passing null for bundleId, pid or a path field clears it; omitting a field leaves it as stored.",
|
|
1847
|
+
engineMethod: "project_set",
|
|
1848
|
+
inputSchema: {
|
|
1849
|
+
type: "object",
|
|
1850
|
+
additionalProperties: false,
|
|
1851
|
+
properties: {
|
|
1852
|
+
projectId: { type: "string", pattern: "^prj_[0-9A-HJKMNP-TV-Z]{26}$" },
|
|
1853
|
+
displayName: { type: "string", minLength: 1, maxLength: 256 },
|
|
1854
|
+
// `null` clears the field on update, so these mirror
|
|
1855
|
+
// ProjectSetArgs' `.nullish()` rather than the old optional-string form.
|
|
1856
|
+
bundleId: { type: ["string", "null"], maxLength: 256 },
|
|
1857
|
+
// Matches ProjectSetArgs.pid, which is bounded to the same Int32 domain
|
|
1858
|
+
// the daemon stores (an out-of-range pid made Swift fail to decode the
|
|
1859
|
+
// whole registry file, which then got rewritten as an empty table).
|
|
1860
|
+
pid: { type: ["integer", "null"], minimum: 1, maximum: PID_INT32_MAX },
|
|
1861
|
+
recipeConfigPath: { type: ["string", "null"], maxLength: 1024 },
|
|
1862
|
+
calibrationAssetsPath: { type: ["string", "null"], maxLength: 1024 },
|
|
1863
|
+
evidenceStoragePath: { type: ["string", "null"], maxLength: 1024 }
|
|
1864
|
+
},
|
|
1865
|
+
required: ["displayName"],
|
|
1866
|
+
// Exactly one of bundleId/pid must identify the app *after* an update is
|
|
1867
|
+
// merged with the stored entry, which a schema for one call cannot state
|
|
1868
|
+
// over a shared file: `projectId` alone means "keep the stored identity".
|
|
1869
|
+
// The authoritative rule runs on the merged entry in project-registry's
|
|
1870
|
+
// assertSingleIdentity, whose message names both fields.
|
|
1871
|
+
anyOf: [
|
|
1872
|
+
{ required: ["bundleId"] },
|
|
1873
|
+
{ required: ["pid"] },
|
|
1874
|
+
{ required: ["projectId"] }
|
|
1875
|
+
]
|
|
1876
|
+
},
|
|
1877
|
+
validate: zodBridge(ProjectSetArgs),
|
|
1878
|
+
execute: projectSetTool
|
|
1879
|
+
},
|
|
1880
|
+
{
|
|
1881
|
+
name: "gp_project_get",
|
|
1882
|
+
description: "Fetch one GlassPane project by its project ID.",
|
|
1883
|
+
engineMethod: "project_get",
|
|
1884
|
+
inputSchema: {
|
|
1885
|
+
type: "object",
|
|
1886
|
+
additionalProperties: false,
|
|
1887
|
+
properties: {
|
|
1888
|
+
projectId: { type: "string", pattern: "^prj_[0-9A-HJKMNP-TV-Z]{26}$" }
|
|
1889
|
+
},
|
|
1890
|
+
required: ["projectId"]
|
|
1891
|
+
},
|
|
1892
|
+
validate: zodBridge(ProjectGetArgs),
|
|
1893
|
+
execute: projectGetTool
|
|
1894
|
+
}
|
|
1895
|
+
];
|
|
1896
|
+
var TOOL_BY_NAME = new Map(
|
|
1897
|
+
TOOL_SPECS.map((spec) => [spec.name, spec])
|
|
1898
|
+
);
|
|
1899
|
+
async function readTrail(session, turn, limit) {
|
|
1900
|
+
await turn.acquire();
|
|
1901
|
+
try {
|
|
1902
|
+
return session.recentIds(limit);
|
|
1903
|
+
} finally {
|
|
1904
|
+
turn.release();
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
var EvidenceFrameShapeError = class extends Error {
|
|
1908
|
+
constructor(detail) {
|
|
1909
|
+
super(`engine returned a last_evidence frame without an evidencePack object: ${detail}`);
|
|
1910
|
+
this.name = "EvidenceFrameShapeError";
|
|
1911
|
+
}
|
|
1912
|
+
};
|
|
1913
|
+
function parseEvidenceFrame(raw) {
|
|
1914
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
1915
|
+
throw new EvidenceFrameShapeError("result frame is not an object");
|
|
1916
|
+
}
|
|
1917
|
+
const body = raw.evidencePack;
|
|
1918
|
+
if (body === void 0) {
|
|
1919
|
+
throw new EvidenceFrameShapeError("missing evidencePack field in last_evidence result");
|
|
1920
|
+
}
|
|
1921
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
1922
|
+
throw new EvidenceFrameShapeError("evidencePack field is not an object");
|
|
1923
|
+
}
|
|
1924
|
+
const pack = parseEvidencePackRead(body);
|
|
1925
|
+
const measured = body.schemaVersion;
|
|
1926
|
+
return {
|
|
1927
|
+
pack,
|
|
1928
|
+
measuredSchemaVersion: typeof measured === "string" ? measured : pack.schemaVersion
|
|
1929
|
+
};
|
|
1930
|
+
}
|
|
1931
|
+
function packForReport(pack, measuredSchemaVersion) {
|
|
1932
|
+
if (measuredSchemaVersion === pack.schemaVersion) {
|
|
1933
|
+
return pack;
|
|
1934
|
+
}
|
|
1935
|
+
return { ...pack, schemaVersion: `${measuredSchemaVersion} (read as ${pack.schemaVersion})` };
|
|
1936
|
+
}
|
|
1937
|
+
async function captureView(args, context) {
|
|
1938
|
+
try {
|
|
1939
|
+
const raw = await context.engine.call("capture_view", args);
|
|
1940
|
+
const body = raw ?? {};
|
|
1941
|
+
const png = body.pngBase64;
|
|
1942
|
+
if (typeof png !== "string" || png.length === 0) {
|
|
1943
|
+
return {
|
|
1944
|
+
content: [{ type: "text", text: formatToolError(
|
|
1945
|
+
GP_E_INTERNAL,
|
|
1946
|
+
"capture_view answered without a pngBase64 payload",
|
|
1947
|
+
"retry once; if it repeats, report this \u2014 the engine captured but the shell could not read the image"
|
|
1948
|
+
) }],
|
|
1949
|
+
isError: true
|
|
1950
|
+
};
|
|
1951
|
+
}
|
|
1952
|
+
if (body.persisted !== false) {
|
|
1953
|
+
return {
|
|
1954
|
+
content: [{ type: "text", text: formatToolError(
|
|
1955
|
+
GP_E_INTERNAL,
|
|
1956
|
+
`capture_view answered without persisted:false (got ${JSON.stringify(body.persisted ?? null)})`,
|
|
1957
|
+
"do not treat this image as unsaved: the engine did not say so. Retry once, then report the frame shape \u2014 the pass-through guarantee is a claim about the protocol, not a default the shell may fill in"
|
|
1958
|
+
) }],
|
|
1959
|
+
isError: true
|
|
1960
|
+
};
|
|
1961
|
+
}
|
|
1962
|
+
const mimeType = typeof body.mimeType === "string" && body.mimeType.length > 0 ? body.mimeType : "image/png";
|
|
1963
|
+
const summary = canonicalJson({
|
|
1964
|
+
mimeType,
|
|
1965
|
+
byteCount: body.byteCount,
|
|
1966
|
+
pixelWidth: body.pixelWidth,
|
|
1967
|
+
pixelHeight: body.pixelHeight,
|
|
1968
|
+
scale: body.scale,
|
|
1969
|
+
// 实际应用的倍率与请求值都给出:静默降采样失败时,"appliedScale" 才是
|
|
1970
|
+
// 模型该信的那个数(它决定自己看到的是不是缩过的版本)。
|
|
1971
|
+
appliedScale: body.appliedScale,
|
|
1972
|
+
windowId: body.windowId,
|
|
1973
|
+
pointSize: body.pointSize,
|
|
1974
|
+
persisted: body.persisted
|
|
1975
|
+
});
|
|
1976
|
+
return {
|
|
1977
|
+
content: [
|
|
1978
|
+
{ type: "image", data: png, mimeType },
|
|
1979
|
+
{ type: "text", text: summary }
|
|
1980
|
+
],
|
|
1981
|
+
isError: false
|
|
1982
|
+
};
|
|
1983
|
+
} catch (error) {
|
|
1984
|
+
if (error instanceof EngineCallError) {
|
|
1985
|
+
return {
|
|
1986
|
+
content: [{ type: "text", text: formatToolErrorShape(error.toBody()) }],
|
|
1987
|
+
isError: true
|
|
1988
|
+
};
|
|
1989
|
+
}
|
|
1990
|
+
return {
|
|
1991
|
+
content: [{ type: "text", text: formatToolError(
|
|
1992
|
+
GP_E_INTERNAL,
|
|
1993
|
+
`internal shell error: ${String(error)}`,
|
|
1994
|
+
"see the MCP server logs and retry"
|
|
1995
|
+
) }],
|
|
1996
|
+
isError: true
|
|
1997
|
+
};
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
function mapEvidenceReadError(error) {
|
|
2001
|
+
if (error instanceof EvidenceFrameShapeError) {
|
|
2002
|
+
return {
|
|
2003
|
+
content: [{ type: "text", text: formatToolError(
|
|
2004
|
+
GP_E_INTERNAL,
|
|
2005
|
+
error.message,
|
|
2006
|
+
`retry gp_last_evidence for the same operationId; if the answer still carries no evidencePack object then whatever is listening on this socket does not speak the engine contract \u2014 ${daemonUnreachableRemedy()}`
|
|
2007
|
+
) }],
|
|
2008
|
+
isError: true
|
|
2009
|
+
};
|
|
2010
|
+
}
|
|
2011
|
+
if (error instanceof KernelSchemaError) {
|
|
2012
|
+
return {
|
|
2013
|
+
content: [{ type: "text", text: formatToolError(
|
|
2014
|
+
GP_E_INTERNAL,
|
|
2015
|
+
`engine returned an invalid evidence pack: ${error.message}`,
|
|
2016
|
+
"engine and kernel schema drifted; fix the common fixtures (assertion C35)"
|
|
2017
|
+
) }],
|
|
2018
|
+
isError: true
|
|
2019
|
+
};
|
|
2020
|
+
}
|
|
2021
|
+
return void 0;
|
|
2022
|
+
}
|
|
2023
|
+
async function projectListTool() {
|
|
2024
|
+
try {
|
|
2025
|
+
const projects = projectList();
|
|
2026
|
+
return {
|
|
2027
|
+
content: [{ type: "text", text: canonicalJson({ projects }) }],
|
|
2028
|
+
isError: false
|
|
2029
|
+
};
|
|
2030
|
+
} catch (error) {
|
|
2031
|
+
return mapProjectError(error);
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
async function projectSetTool(args) {
|
|
2035
|
+
try {
|
|
2036
|
+
const entry = projectSet(args);
|
|
2037
|
+
return { content: [{ type: "text", text: canonicalJson({ project: entry }) }], isError: false };
|
|
2038
|
+
} catch (error) {
|
|
2039
|
+
return mapProjectError(error);
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
async function projectGetTool(args) {
|
|
2043
|
+
const argv = args;
|
|
2044
|
+
try {
|
|
2045
|
+
const entry = projectGet(argv.projectId);
|
|
2046
|
+
if (entry === void 0) {
|
|
2047
|
+
return {
|
|
2048
|
+
content: [{ type: "text", text: formatToolError(
|
|
2049
|
+
"GP_E_NOT_FOUND",
|
|
2050
|
+
`unknown project ${argv.projectId}`,
|
|
2051
|
+
"check the projectId; use gp_project_list to view available projects"
|
|
2052
|
+
) }],
|
|
2053
|
+
isError: true
|
|
2054
|
+
};
|
|
2055
|
+
}
|
|
2056
|
+
return { content: [{ type: "text", text: canonicalJson({ project: entry }) }], isError: false };
|
|
2057
|
+
} catch (error) {
|
|
2058
|
+
return mapProjectError(error);
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
function mapProjectError(error) {
|
|
2062
|
+
if (error instanceof ProjectRegistryError) {
|
|
2063
|
+
return {
|
|
2064
|
+
content: [{ type: "text", text: formatToolError(
|
|
2065
|
+
error.code,
|
|
2066
|
+
error.message,
|
|
2067
|
+
projectErrorRemedy(error.code)
|
|
2068
|
+
) }],
|
|
2069
|
+
isError: true
|
|
2070
|
+
};
|
|
2071
|
+
}
|
|
2072
|
+
return {
|
|
2073
|
+
content: [{ type: "text", text: formatToolError(
|
|
2074
|
+
GP_E_INTERNAL,
|
|
2075
|
+
`internal shell error in project registry: ${String(error)}`,
|
|
2076
|
+
projectErrorRemedy(GP_E_INTERNAL)
|
|
2077
|
+
) }],
|
|
2078
|
+
isError: true
|
|
2079
|
+
};
|
|
2080
|
+
}
|
|
2081
|
+
function projectErrorRemedy(code) {
|
|
2082
|
+
if (code === GP_E_PROJECT_LIMIT) {
|
|
2083
|
+
return "delete unused projects first (`glasspaned --list-projects` prints the registered set), then retry";
|
|
2084
|
+
}
|
|
2085
|
+
if (code === GP_E_NOT_FOUND) {
|
|
2086
|
+
return "check the projectId; use gp_project_list to view available projects";
|
|
2087
|
+
}
|
|
2088
|
+
if (code === GP_E_INTERNAL) {
|
|
2089
|
+
return `the projects file is the problem, not your arguments: the message above names its path, so read it with \`python3 -m json.tool <that path>\`, repair or restore the damaged entry, and retry \u2014 or set ${FORCE_OVERWRITE_ENV}=1 and call gp_project_set to rebuild the registry from scratch (the unloadable file is moved aside as <path>.unreadable-<id>, never deleted, and every entry still in it is lost). Do not retry the same read-only call unchanged: it will keep failing.`;
|
|
2090
|
+
}
|
|
2091
|
+
return "check the tool's input schema and retry";
|
|
2092
|
+
}
|
|
2093
|
+
async function exportEvidence(args, context) {
|
|
2094
|
+
const argv = args;
|
|
2095
|
+
const render2 = argv.format === "html" ? renderHTML : renderMarkdown;
|
|
2096
|
+
try {
|
|
2097
|
+
const raw = await context.engine.call("last_evidence", { operationId: argv.operationId });
|
|
2098
|
+
const { pack, measuredSchemaVersion } = parseEvidenceFrame(raw);
|
|
2099
|
+
await context.turn.acquire();
|
|
2100
|
+
try {
|
|
2101
|
+
context.session.record(raw);
|
|
2102
|
+
} finally {
|
|
2103
|
+
context.turn.release();
|
|
2104
|
+
}
|
|
2105
|
+
return { content: [{ type: "text", text: render2(packForReport(pack, measuredSchemaVersion), void 0) }], isError: false };
|
|
2106
|
+
} catch (error) {
|
|
2107
|
+
return mapAuditError(error);
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
async function recentReports(args, context) {
|
|
2111
|
+
const argv = args;
|
|
2112
|
+
const ids = await readTrail(context.session, context.turn, argv.limit);
|
|
2113
|
+
if (ids.length === 0) {
|
|
2114
|
+
return {
|
|
2115
|
+
content: [{ type: "text", text: formatToolError(
|
|
2116
|
+
GP_E_NO_EVIDENCE,
|
|
2117
|
+
"no operations recorded in this session",
|
|
2118
|
+
"run gp_act / gp_assert_element first, then retry gp_recent_reports"
|
|
2119
|
+
) }],
|
|
2120
|
+
isError: true
|
|
2121
|
+
};
|
|
2122
|
+
}
|
|
2123
|
+
const packs = [];
|
|
2124
|
+
const skipped = [];
|
|
2125
|
+
for (const id of ids) {
|
|
2126
|
+
try {
|
|
2127
|
+
const raw = await context.engine.call("last_evidence", { operationId: id });
|
|
2128
|
+
const parsed = parseEvidenceFrame(raw);
|
|
2129
|
+
packs.push({ id, pack: packForReport(parsed.pack, parsed.measuredSchemaVersion) });
|
|
2130
|
+
} catch (error) {
|
|
2131
|
+
if (error instanceof EngineCallError && error.code === GP_E_NO_EVIDENCE) {
|
|
2132
|
+
skipped.push(id);
|
|
2133
|
+
} else {
|
|
2134
|
+
return mapAuditError(error);
|
|
2135
|
+
}
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
if (packs.length === 0) {
|
|
2139
|
+
return {
|
|
2140
|
+
content: [{ type: "text", text: formatToolError(
|
|
2141
|
+
GP_E_NO_EVIDENCE,
|
|
2142
|
+
"no recent evidence is reachable in the daemon history",
|
|
2143
|
+
"the engine may have restarted; re-run gp_act / gp_assert_element to regenerate evidence"
|
|
2144
|
+
) }],
|
|
2145
|
+
isError: true
|
|
2146
|
+
};
|
|
2147
|
+
}
|
|
2148
|
+
const render2 = argv.format === "html" ? renderHTML : renderMarkdown;
|
|
2149
|
+
const header = argv.format === "html" ? `<h1>GlassPane recent reports (${packs.length})</h1>` : `# GlassPane recent reports (${packs.length})`;
|
|
2150
|
+
const skipNote = skipped.length === 0 ? "" : argv.format === "html" ? `<p class="gp-skipped">skipped ${skipped.length} unreachable ${skipped.length === 1 ? "entry" : "entries"}: ${escapeHTML(skipped.join(", "))}</p>` : `> skipped ${skipped.length} unreachable ${skipped.length === 1 ? "entry" : "entries"}: ${skipped.join(", ")}`;
|
|
2151
|
+
const separator = argv.format === "html" ? "\n<hr>\n" : "\n\n---\n";
|
|
2152
|
+
const body = packs.map(({ pack }) => render2(pack, void 0)).join(separator);
|
|
2153
|
+
const sections2 = [header];
|
|
2154
|
+
if (skipNote !== "") {
|
|
2155
|
+
sections2.push(skipNote);
|
|
2156
|
+
}
|
|
2157
|
+
sections2.push(body);
|
|
2158
|
+
return { content: [{ type: "text", text: sections2.join("\n") }], isError: false };
|
|
2159
|
+
}
|
|
2160
|
+
function mapAuditError(error) {
|
|
2161
|
+
if (error instanceof EngineCallError) {
|
|
2162
|
+
return {
|
|
2163
|
+
content: [{ type: "text", text: formatToolErrorShape(error.toBody()) }],
|
|
2164
|
+
isError: true
|
|
2165
|
+
};
|
|
2166
|
+
}
|
|
2167
|
+
const evidenceFailure = mapEvidenceReadError(error);
|
|
2168
|
+
if (evidenceFailure !== void 0) {
|
|
2169
|
+
return evidenceFailure;
|
|
2170
|
+
}
|
|
2171
|
+
return {
|
|
2172
|
+
content: [{ type: "text", text: formatToolError(
|
|
2173
|
+
GP_E_INTERNAL,
|
|
2174
|
+
`internal shell error: ${String(error)}`,
|
|
2175
|
+
"see the MCP server logs and retry"
|
|
2176
|
+
) }],
|
|
2177
|
+
isError: true
|
|
2178
|
+
};
|
|
2179
|
+
}
|
|
2180
|
+
|
|
2181
|
+
// src/http-gateway.ts
|
|
2182
|
+
var GLASSPANE_HTTP_TOKEN_ENV = "GLASSPANE_HTTP_TOKEN";
|
|
2183
|
+
var DEFAULT_GATEWAY_PORT = 8787;
|
|
2184
|
+
var DEFAULT_GATEWAY_HOST = "127.0.0.1";
|
|
2185
|
+
var MAX_REQUEST_BODY_BYTES = 256 * 1024;
|
|
2186
|
+
var MAX_EVIDENCE_IDS = 20;
|
|
2187
|
+
var OPERATION_ID_PATTERN2 = /^op_[0-9A-HJKMNP-TV-Z]{26}$/;
|
|
2188
|
+
var REPORT_FORMATS = ["html", "markdown"];
|
|
2189
|
+
function isReportFormat(value) {
|
|
2190
|
+
return REPORT_FORMATS.includes(value);
|
|
2191
|
+
}
|
|
2192
|
+
var HTTP_UNAUTHORIZED = "GP_HTTP_UNAUTHORIZED";
|
|
2193
|
+
var HTTP_NOT_FOUND = "GP_HTTP_NOT_FOUND";
|
|
2194
|
+
var HTTP_BAD_REQUEST = "GP_HTTP_BAD_REQUEST";
|
|
2195
|
+
var HTTP_PAYLOAD_TOO_LARGE = "GP_HTTP_PAYLOAD_TOO_LARGE";
|
|
2196
|
+
var HTTP_NOT_PROVIDED = "GP_HTTP_NOT_PROVIDED";
|
|
2197
|
+
var FORWARDABLE_TOOLS = new Map(
|
|
2198
|
+
TOOL_SPECS.filter((spec) => spec.execute === void 0).map((spec) => [spec.engineMethod, spec])
|
|
2199
|
+
);
|
|
2200
|
+
function createHttpGateway(options) {
|
|
2201
|
+
const port = options.port ?? DEFAULT_GATEWAY_PORT;
|
|
2202
|
+
const host = options.host ?? DEFAULT_GATEWAY_HOST;
|
|
2203
|
+
if (options.token === "") {
|
|
2204
|
+
throw new Error(
|
|
2205
|
+
`createHttpGateway requires a non-empty token (read ${GLASSPANE_HTTP_TOKEN_ENV}); refusing to start with an empty or defaulted token`
|
|
2206
|
+
);
|
|
2207
|
+
}
|
|
2208
|
+
const client = options.connectController !== void 0 ? options.connectController(options.socketPath) : unixSocketEngineClient(options.socketPath);
|
|
2209
|
+
const expectedToken = Buffer.from(options.token, "utf8");
|
|
2210
|
+
const server = http.createServer((req, res) => {
|
|
2211
|
+
handleHttp(req, res, client, expectedToken).catch((error) => {
|
|
2212
|
+
fail(res, 500, GP_E_INTERNAL, `internal gateway error: ${String(error)}`, "see the gateway log and retry");
|
|
2213
|
+
});
|
|
2214
|
+
});
|
|
2215
|
+
server.listen(port, host);
|
|
2216
|
+
const close = () => new Promise((resolve, reject) => {
|
|
2217
|
+
client.close?.();
|
|
2218
|
+
server.close((error) => {
|
|
2219
|
+
if (error) {
|
|
2220
|
+
reject(error);
|
|
2221
|
+
} else {
|
|
2222
|
+
resolve();
|
|
2223
|
+
}
|
|
2224
|
+
});
|
|
2225
|
+
forceCloseConnections(server);
|
|
2226
|
+
});
|
|
2227
|
+
return { server, close };
|
|
2228
|
+
}
|
|
2229
|
+
function forceCloseConnections(server) {
|
|
2230
|
+
const withCloseAll = server;
|
|
2231
|
+
if (typeof withCloseAll.closeAllConnections === "function") {
|
|
2232
|
+
withCloseAll.closeAllConnections();
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
async function handleHttp(req, res, client, expectedToken) {
|
|
2236
|
+
if (!authorized(req, expectedToken)) {
|
|
2237
|
+
fail(
|
|
2238
|
+
res,
|
|
2239
|
+
401,
|
|
2240
|
+
HTTP_UNAUTHORIZED,
|
|
2241
|
+
"missing or invalid Authorization: Bearer <token>",
|
|
2242
|
+
"set the Authorization header to `Bearer <token>` where <token> is the GLASSPANE_HTTP_TOKEN the gateway was launched with"
|
|
2243
|
+
);
|
|
2244
|
+
return;
|
|
2245
|
+
}
|
|
2246
|
+
const url = parseRequestUrl(req.url);
|
|
2247
|
+
if (url === null) {
|
|
2248
|
+
fail(res, 400, HTTP_BAD_REQUEST, "could not parse request URL", "send a well-formed request line");
|
|
2249
|
+
return;
|
|
2250
|
+
}
|
|
2251
|
+
const segments = url.pathname.split("/").filter((part) => part !== "");
|
|
2252
|
+
await dispatch(req, res, url, segments, client);
|
|
2253
|
+
}
|
|
2254
|
+
function parseRequestUrl(raw) {
|
|
2255
|
+
if (typeof raw !== "string" || raw === "") {
|
|
2256
|
+
return null;
|
|
2257
|
+
}
|
|
2258
|
+
try {
|
|
2259
|
+
return new URL(raw, `http://${DEFAULT_GATEWAY_HOST}`);
|
|
2260
|
+
} catch {
|
|
2261
|
+
return null;
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
2264
|
+
async function dispatch(req, res, url, segments, client) {
|
|
2265
|
+
const [v1, resource, id] = segments;
|
|
2266
|
+
if (v1 !== "v1") {
|
|
2267
|
+
NotFound(res, url.pathname);
|
|
2268
|
+
return;
|
|
2269
|
+
}
|
|
2270
|
+
if (req.method === "GET") {
|
|
2271
|
+
if (resource === "hello" && segments.length === 2) {
|
|
2272
|
+
await handleHello(client, res);
|
|
2273
|
+
return;
|
|
2274
|
+
}
|
|
2275
|
+
if (resource === "evidence" && segments.length === 2) {
|
|
2276
|
+
await handleEvidenceAggregate(url, client, res);
|
|
2277
|
+
return;
|
|
2278
|
+
}
|
|
2279
|
+
if (resource === "evidence" && segments.length === 3 && id !== void 0) {
|
|
2280
|
+
await handleEvidenceSingle(id, url, client, res);
|
|
2281
|
+
return;
|
|
2282
|
+
}
|
|
2283
|
+
if (resource === "stats" && segments.length === 2) {
|
|
2284
|
+
handleEvidenceStats(res);
|
|
2285
|
+
return;
|
|
2286
|
+
}
|
|
2287
|
+
} else if (req.method === "POST") {
|
|
2288
|
+
if (resource === "tools" && segments.length === 3 && id !== void 0) {
|
|
2289
|
+
await handleToolForward(id, req, client, res);
|
|
2290
|
+
return;
|
|
2291
|
+
}
|
|
2292
|
+
if (resource === "recipes" && id === "validate" && segments.length === 3) {
|
|
2293
|
+
await handleRecipeValidate(req, res);
|
|
2294
|
+
return;
|
|
2295
|
+
}
|
|
2296
|
+
}
|
|
2297
|
+
NotFound(res, url.pathname);
|
|
2298
|
+
}
|
|
2299
|
+
async function handleHello(client, res) {
|
|
2300
|
+
try {
|
|
2301
|
+
const result = await client.call("hello");
|
|
2302
|
+
ok(res, result);
|
|
2303
|
+
} catch (error) {
|
|
2304
|
+
failEngine(res, error);
|
|
2305
|
+
}
|
|
2306
|
+
}
|
|
2307
|
+
async function handleEvidenceSingle(rawId, url, client, res) {
|
|
2308
|
+
const operationId = parseOperationId(rawId);
|
|
2309
|
+
if (operationId === null) {
|
|
2310
|
+
fail(
|
|
2311
|
+
res,
|
|
2312
|
+
400,
|
|
2313
|
+
HTTP_BAD_REQUEST,
|
|
2314
|
+
`invalid operationId '${rawId}'`,
|
|
2315
|
+
"operationId must match `op_[0-9A-HJKMNP-TV-Z]{26}`"
|
|
2316
|
+
);
|
|
2317
|
+
return;
|
|
2318
|
+
}
|
|
2319
|
+
const format = parseFormat(url.searchParams.get("format"));
|
|
2320
|
+
if (format === null) {
|
|
2321
|
+
fail(res, 400, HTTP_BAD_REQUEST, "invalid format", "format must be 'html' or 'markdown'");
|
|
2322
|
+
return;
|
|
2323
|
+
}
|
|
2324
|
+
try {
|
|
2325
|
+
const raw = await client.call("last_evidence", { operationId });
|
|
2326
|
+
const { pack, measuredSchemaVersion } = parseEvidenceFrame(raw);
|
|
2327
|
+
const view = packForReport(pack, measuredSchemaVersion);
|
|
2328
|
+
ok(res, { operationId, format, report: render(view, format) });
|
|
2329
|
+
} catch (error) {
|
|
2330
|
+
failEngine(res, error);
|
|
2331
|
+
}
|
|
2332
|
+
}
|
|
2333
|
+
async function handleEvidenceAggregate(url, client, res) {
|
|
2334
|
+
const ids = parseOperationIdList(url.searchParams.get("ids"));
|
|
2335
|
+
if (ids === null) {
|
|
2336
|
+
fail(
|
|
2337
|
+
res,
|
|
2338
|
+
400,
|
|
2339
|
+
HTTP_BAD_REQUEST,
|
|
2340
|
+
"invalid or empty ids",
|
|
2341
|
+
"ids must be a comma-separated list of operationIds of form `op_[0-9A-HJKMNP-TV-Z]{26}`"
|
|
2342
|
+
);
|
|
2343
|
+
return;
|
|
2344
|
+
}
|
|
2345
|
+
if (ids.length > MAX_EVIDENCE_IDS) {
|
|
2346
|
+
fail(
|
|
2347
|
+
res,
|
|
2348
|
+
400,
|
|
2349
|
+
HTTP_BAD_REQUEST,
|
|
2350
|
+
`too many ids: ${ids.length} exceeds the ${MAX_EVIDENCE_IDS}-id ceiling`,
|
|
2351
|
+
`pass at most ${MAX_EVIDENCE_IDS} operationIds per request; split the batch`
|
|
2352
|
+
);
|
|
2353
|
+
return;
|
|
2354
|
+
}
|
|
2355
|
+
const format = parseFormat(url.searchParams.get("format"));
|
|
2356
|
+
if (format === null) {
|
|
2357
|
+
fail(res, 400, HTTP_BAD_REQUEST, "invalid format", "format must be 'html' or 'markdown'");
|
|
2358
|
+
return;
|
|
2359
|
+
}
|
|
2360
|
+
const blocks = [];
|
|
2361
|
+
const renderedIds = [];
|
|
2362
|
+
const skipped = [];
|
|
2363
|
+
for (const operationId of ids) {
|
|
2364
|
+
try {
|
|
2365
|
+
const raw = await client.call("last_evidence", { operationId });
|
|
2366
|
+
const { pack, measuredSchemaVersion } = parseEvidenceFrame(raw);
|
|
2367
|
+
blocks.push(render(packForReport(pack, measuredSchemaVersion), format));
|
|
2368
|
+
renderedIds.push(operationId);
|
|
2369
|
+
} catch (error) {
|
|
2370
|
+
if (error instanceof EngineCallError && error.code === GP_E_NO_EVIDENCE) {
|
|
2371
|
+
skipped.push(operationId);
|
|
2372
|
+
} else {
|
|
2373
|
+
await failEngine(res, error);
|
|
2374
|
+
return;
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
}
|
|
2378
|
+
if (blocks.length === 0) {
|
|
2379
|
+
fail(
|
|
2380
|
+
res,
|
|
2381
|
+
404,
|
|
2382
|
+
GP_E_NO_EVIDENCE,
|
|
2383
|
+
"none of the requested operations have evidence in the daemon history",
|
|
2384
|
+
"the engine may have restarted or those operationIds never produced evidence; re-run gp_act / gp_assert_element to regenerate"
|
|
2385
|
+
);
|
|
2386
|
+
return;
|
|
2387
|
+
}
|
|
2388
|
+
const header = format === "html" ? `<h1>GlassPane evidence reports (${blocks.length})</h1>` : `# GlassPane evidence reports (${blocks.length})`;
|
|
2389
|
+
const skipNote = makeSkipNote(skipped, format);
|
|
2390
|
+
const separator = format === "html" ? "\n<hr>\n" : "\n\n---\n";
|
|
2391
|
+
const sections2 = [header];
|
|
2392
|
+
if (skipNote !== "") {
|
|
2393
|
+
sections2.push(skipNote);
|
|
2394
|
+
}
|
|
2395
|
+
sections2.push(blocks.join(separator));
|
|
2396
|
+
ok(res, { format, renderedIds, skipped, report: sections2.join("\n") });
|
|
2397
|
+
}
|
|
2398
|
+
async function handleToolForward(name, req, client, res) {
|
|
2399
|
+
const spec = FORWARDABLE_TOOLS.get(name);
|
|
2400
|
+
if (spec === void 0) {
|
|
2401
|
+
fail(
|
|
2402
|
+
res,
|
|
2403
|
+
404,
|
|
2404
|
+
HTTP_NOT_FOUND,
|
|
2405
|
+
`unknown tool method '${name}'`,
|
|
2406
|
+
"the gateway only forwards the daemon methods an MCP-less caller can use; see TOOL_SPECS for the whitelist"
|
|
2407
|
+
);
|
|
2408
|
+
return;
|
|
2409
|
+
}
|
|
2410
|
+
let body;
|
|
2411
|
+
try {
|
|
2412
|
+
const text = await readBody(req, MAX_REQUEST_BODY_BYTES);
|
|
2413
|
+
body = JSON.parse(text);
|
|
2414
|
+
} catch (error) {
|
|
2415
|
+
if (error instanceof HTTPPayloadTooLargeError) {
|
|
2416
|
+
fail(
|
|
2417
|
+
res,
|
|
2418
|
+
400,
|
|
2419
|
+
HTTP_PAYLOAD_TOO_LARGE,
|
|
2420
|
+
`request body exceeds ${MAX_REQUEST_BODY_BYTES} bytes`,
|
|
2421
|
+
"shrink the request payload and retry"
|
|
2422
|
+
);
|
|
2423
|
+
return;
|
|
2424
|
+
}
|
|
2425
|
+
fail(
|
|
2426
|
+
res,
|
|
2427
|
+
400,
|
|
2428
|
+
HTTP_BAD_REQUEST,
|
|
2429
|
+
"request body must be a JSON object of tool params",
|
|
2430
|
+
"send a JSON object matching the tool's input schema"
|
|
2431
|
+
);
|
|
2432
|
+
return;
|
|
2433
|
+
}
|
|
2434
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
2435
|
+
fail(
|
|
2436
|
+
res,
|
|
2437
|
+
400,
|
|
2438
|
+
HTTP_BAD_REQUEST,
|
|
2439
|
+
"request body must be a JSON object of tool params",
|
|
2440
|
+
"send a JSON object matching the tool's input schema"
|
|
2441
|
+
);
|
|
2442
|
+
return;
|
|
2443
|
+
}
|
|
2444
|
+
const checked = spec.validate(body);
|
|
2445
|
+
if (!checked.ok) {
|
|
2446
|
+
fail(
|
|
2447
|
+
res,
|
|
2448
|
+
400,
|
|
2449
|
+
GP_E_BAD_PARAMS,
|
|
2450
|
+
`invalid arguments for '${name}'`,
|
|
2451
|
+
checked.issues
|
|
2452
|
+
);
|
|
2453
|
+
return;
|
|
2454
|
+
}
|
|
2455
|
+
try {
|
|
2456
|
+
const result = await client.call(spec.engineMethod, checked.value);
|
|
2457
|
+
if (spec.engineMethod === "last_evidence") {
|
|
2458
|
+
try {
|
|
2459
|
+
parseEvidenceFrame(result);
|
|
2460
|
+
} catch {
|
|
2461
|
+
fail(
|
|
2462
|
+
res,
|
|
2463
|
+
502,
|
|
2464
|
+
GP_E_INTERNAL,
|
|
2465
|
+
"the daemon returned a last_evidence frame that does not match the engine contract (no parseable evidencePack)",
|
|
2466
|
+
"reenact the operation so the daemon writes a fresh pack; if it still fails, the engine and kernel schemas have drifted (assertion C35)"
|
|
2467
|
+
);
|
|
2468
|
+
return;
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
ok(res, result);
|
|
2472
|
+
} catch (error) {
|
|
2473
|
+
await failEngine(res, error);
|
|
2474
|
+
}
|
|
2475
|
+
}
|
|
2476
|
+
function handleEvidenceStats(res) {
|
|
2477
|
+
fail(
|
|
2478
|
+
res,
|
|
2479
|
+
501,
|
|
2480
|
+
HTTP_NOT_PROVIDED,
|
|
2481
|
+
"evidence statistics are not exposed over this daemon's socket protocol in this build",
|
|
2482
|
+
"run `glasspaned --evidence-stats` against the same --state-dir this socket serves to get count/totalBytes/listFailure/dir"
|
|
2483
|
+
);
|
|
2484
|
+
}
|
|
2485
|
+
async function handleRecipeValidate(req, res) {
|
|
2486
|
+
try {
|
|
2487
|
+
await readBody(req, MAX_REQUEST_BODY_BYTES);
|
|
2488
|
+
} catch (error) {
|
|
2489
|
+
if (error instanceof HTTPPayloadTooLargeError) {
|
|
2490
|
+
fail(
|
|
2491
|
+
res,
|
|
2492
|
+
400,
|
|
2493
|
+
HTTP_PAYLOAD_TOO_LARGE,
|
|
2494
|
+
`request body exceeds ${MAX_REQUEST_BODY_BYTES} bytes`,
|
|
2495
|
+
"shrink the request payload and retry"
|
|
2496
|
+
);
|
|
2497
|
+
return;
|
|
2498
|
+
}
|
|
2499
|
+
fail(res, 400, HTTP_BAD_REQUEST, "could not read the request body", "resend the request");
|
|
2500
|
+
return;
|
|
2501
|
+
}
|
|
2502
|
+
fail(
|
|
2503
|
+
res,
|
|
2504
|
+
501,
|
|
2505
|
+
HTTP_NOT_PROVIDED,
|
|
2506
|
+
"recipe validation is not exposed over this daemon's socket protocol in this build",
|
|
2507
|
+
"run `glasspaned --recipe-validate <recipe.json-path>`; this build provides no socket method for it"
|
|
2508
|
+
);
|
|
2509
|
+
}
|
|
2510
|
+
function authorized(req, expected) {
|
|
2511
|
+
const header = req.headers.authorization;
|
|
2512
|
+
if (typeof header !== "string") {
|
|
2513
|
+
return false;
|
|
2514
|
+
}
|
|
2515
|
+
const match = /^Bearer\s+(.+)$/i.exec(header);
|
|
2516
|
+
if (match === null) {
|
|
2517
|
+
return false;
|
|
2518
|
+
}
|
|
2519
|
+
const bearer = match[1];
|
|
2520
|
+
if (bearer === void 0) {
|
|
2521
|
+
return false;
|
|
2522
|
+
}
|
|
2523
|
+
return tokenMatches(expected, bearer);
|
|
2524
|
+
}
|
|
2525
|
+
function tokenMatches(expected, received) {
|
|
2526
|
+
const expectedDigest = sha256(expected);
|
|
2527
|
+
const receivedDigest = sha256(Buffer.from(received, "utf8"));
|
|
2528
|
+
return timingSafeEqual(expectedDigest, receivedDigest);
|
|
2529
|
+
}
|
|
2530
|
+
function sha256(data) {
|
|
2531
|
+
return createHash("sha256").update(data).digest();
|
|
2532
|
+
}
|
|
2533
|
+
function parseOperationId(value) {
|
|
2534
|
+
if (typeof value !== "string") {
|
|
2535
|
+
return null;
|
|
2536
|
+
}
|
|
2537
|
+
return OPERATION_ID_PATTERN2.test(value) ? value : null;
|
|
2538
|
+
}
|
|
2539
|
+
function parseOperationIdList(raw) {
|
|
2540
|
+
if (raw === null) {
|
|
2541
|
+
return null;
|
|
2542
|
+
}
|
|
2543
|
+
const tokens = raw.split(",").map((token) => token.trim()).filter((token) => token !== "");
|
|
2544
|
+
if (tokens.length === 0) {
|
|
2545
|
+
return null;
|
|
2546
|
+
}
|
|
2547
|
+
for (const token of tokens) {
|
|
2548
|
+
if (parseOperationId(token) === null) {
|
|
2549
|
+
return null;
|
|
2550
|
+
}
|
|
2551
|
+
}
|
|
2552
|
+
return tokens;
|
|
2553
|
+
}
|
|
2554
|
+
function parseFormat(value) {
|
|
2555
|
+
if (value === null) {
|
|
2556
|
+
return "markdown";
|
|
2557
|
+
}
|
|
2558
|
+
return isReportFormat(value) ? value : null;
|
|
2559
|
+
}
|
|
2560
|
+
function render(view, format) {
|
|
2561
|
+
return format === "html" ? renderHTML(view, void 0) : renderMarkdown(view, void 0);
|
|
2562
|
+
}
|
|
2563
|
+
function makeSkipNote(skipped, format) {
|
|
2564
|
+
if (skipped.length === 0) {
|
|
2565
|
+
return "";
|
|
2566
|
+
}
|
|
2567
|
+
const label = skipped.length === 1 ? "entry" : "entries";
|
|
2568
|
+
return format === "html" ? `<p class="gp-skipped">skipped ${skipped.length} unreachable ${label}: ${escapeHTML(skipped.join(", "))}</p>` : `> skipped ${skipped.length} unreachable ${label}: ${skipped.join(", ")}`;
|
|
2569
|
+
}
|
|
2570
|
+
function ok(res, result) {
|
|
2571
|
+
writeJson(res, 200, { ok: true, result });
|
|
2572
|
+
}
|
|
2573
|
+
function fail(res, status, code, message, remedy) {
|
|
2574
|
+
writeJson(res, status, { ok: false, error: { code, message, remedy } });
|
|
2575
|
+
}
|
|
2576
|
+
function writeJson(res, status, body) {
|
|
2577
|
+
const text = JSON.stringify(body);
|
|
2578
|
+
res.writeHead(status, {
|
|
2579
|
+
"content-type": "application/json",
|
|
2580
|
+
"content-length": Buffer.byteLength(text),
|
|
2581
|
+
"cache-control": "no-store"
|
|
2582
|
+
});
|
|
2583
|
+
res.end(text);
|
|
2584
|
+
}
|
|
2585
|
+
function NotFound(res, pathname) {
|
|
2586
|
+
fail(
|
|
2587
|
+
res,
|
|
2588
|
+
404,
|
|
2589
|
+
HTTP_NOT_FOUND,
|
|
2590
|
+
`no route for ${pathname}`,
|
|
2591
|
+
"GET /v1/hello, GET /v1/evidence/:operationId, GET /v1/evidence?ids=a,b&format=html, POST /v1/tools/:name"
|
|
2592
|
+
);
|
|
2593
|
+
}
|
|
2594
|
+
async function failEngine(res, error) {
|
|
2595
|
+
if (error instanceof EngineCallError) {
|
|
2596
|
+
const status = error.code === GP_E_NO_EVIDENCE ? 404 : 502;
|
|
2597
|
+
fail(res, status, error.code, error.message, error.remedy);
|
|
2598
|
+
return;
|
|
2599
|
+
}
|
|
2600
|
+
fail(
|
|
2601
|
+
res,
|
|
2602
|
+
500,
|
|
2603
|
+
GP_E_INTERNAL,
|
|
2604
|
+
`engine transport error: ${String(error)}`,
|
|
2605
|
+
"ensure the glasspane daemon is running, then retry"
|
|
2606
|
+
);
|
|
2607
|
+
}
|
|
2608
|
+
var HTTPPayloadTooLargeError = class extends Error {
|
|
2609
|
+
constructor(limit) {
|
|
2610
|
+
super(`request body exceeds ${limit} bytes`);
|
|
2611
|
+
this.name = "HTTPPayloadTooLargeError";
|
|
2612
|
+
}
|
|
2613
|
+
};
|
|
2614
|
+
function readBody(req, limit) {
|
|
2615
|
+
return new Promise((resolve, reject) => {
|
|
2616
|
+
let size = 0;
|
|
2617
|
+
const chunks = [];
|
|
2618
|
+
req.on("data", (chunk) => {
|
|
2619
|
+
size += chunk.length;
|
|
2620
|
+
if (size > limit) {
|
|
2621
|
+
req.destroy();
|
|
2622
|
+
reject(new HTTPPayloadTooLargeError(limit));
|
|
2623
|
+
return;
|
|
2624
|
+
}
|
|
2625
|
+
chunks.push(chunk);
|
|
2626
|
+
});
|
|
2627
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
2628
|
+
req.on("error", (error) => reject(error));
|
|
2629
|
+
});
|
|
2630
|
+
}
|
|
2631
|
+
|
|
2632
|
+
// src/http-gateway-cli.ts
|
|
2633
|
+
var HOST = DEFAULT_GATEWAY_HOST;
|
|
2634
|
+
function parseArgs(argv) {
|
|
2635
|
+
const options = { socketPath: defaultSocketPath(), port: DEFAULT_GATEWAY_PORT, help: false };
|
|
2636
|
+
for (let i = 0; i < argv.length; i++) {
|
|
2637
|
+
const arg = argv[i];
|
|
2638
|
+
if (arg === "--help" || arg === "-h") {
|
|
2639
|
+
options.help = true;
|
|
2640
|
+
} else if (arg === "--socket-path" || arg === "-s") {
|
|
2641
|
+
const value = argv[i + 1];
|
|
2642
|
+
if (value === void 0) {
|
|
2643
|
+
throw new Error("--socket-path requires a value");
|
|
2644
|
+
}
|
|
2645
|
+
options.socketPath = value;
|
|
2646
|
+
i += 1;
|
|
2647
|
+
} else if (arg.startsWith("--socket-path=")) {
|
|
2648
|
+
options.socketPath = arg.slice("--socket-path=".length);
|
|
2649
|
+
} else if (arg === "--port" || arg === "-p") {
|
|
2650
|
+
const raw = argv[i + 1];
|
|
2651
|
+
const value = Number(raw);
|
|
2652
|
+
if (raw === void 0 || !Number.isInteger(value) || value < 0 || value > 65535) {
|
|
2653
|
+
throw new Error("--port requires an integer between 0 and 65535");
|
|
2654
|
+
}
|
|
2655
|
+
options.port = value;
|
|
2656
|
+
i += 1;
|
|
2657
|
+
} else if (arg.startsWith("--port=")) {
|
|
2658
|
+
options.port = Number(arg.slice("--port=".length));
|
|
2659
|
+
}
|
|
2660
|
+
}
|
|
2661
|
+
return options;
|
|
2662
|
+
}
|
|
2663
|
+
var USAGE = `usage: glasspane-http [--socket-path <path>] [--port <n>]
|
|
2664
|
+
|
|
2665
|
+
Exposes the GlassPane engine as an HTTP/REST gateway on ${HOST} only.
|
|
2666
|
+
|
|
2667
|
+
Lifetime and auth:
|
|
2668
|
+
- GLASSPANE_HTTP_TOKEN <token> is required and read from the environment;
|
|
2669
|
+
the gateway refuses to start without it (enforced, never defaulted).
|
|
2670
|
+
- SIGINT / SIGTERM shut the gateway down cleanly (close the engine client
|
|
2671
|
+
and the HTTP server, then exit 0).
|
|
2672
|
+
|
|
2673
|
+
Socket, in the order this process resolves it:
|
|
2674
|
+
1. --socket-path <path>
|
|
2675
|
+
2. GLASSPANE_ENGINE_SOCK=<path>
|
|
2676
|
+
3. $HOME/.glasspane/engine.sock (same guess policy as glasspane-mcp)
|
|
2677
|
+
`;
|
|
2678
|
+
function main() {
|
|
2679
|
+
let options;
|
|
2680
|
+
try {
|
|
2681
|
+
options = parseArgs(process2.argv.slice(2));
|
|
2682
|
+
} catch (error) {
|
|
2683
|
+
process2.stderr.write(String(error) + "\n\n" + USAGE);
|
|
2684
|
+
process2.exit(2);
|
|
2685
|
+
}
|
|
2686
|
+
if (options.help) {
|
|
2687
|
+
process2.stdout.write(USAGE);
|
|
2688
|
+
process2.exit(0);
|
|
2689
|
+
}
|
|
2690
|
+
const token = process2.env[GLASSPANE_HTTP_TOKEN_ENV];
|
|
2691
|
+
if (typeof token !== "string" || token === "") {
|
|
2692
|
+
process2.stderr.write(
|
|
2693
|
+
`${GLASSPANE_HTTP_TOKEN_ENV} is not set or is empty; refusing to start an unauthenticated gateway.
|
|
2694
|
+
|
|
2695
|
+
${USAGE}`
|
|
2696
|
+
);
|
|
2697
|
+
process2.exit(2);
|
|
2698
|
+
}
|
|
2699
|
+
let gateway;
|
|
2700
|
+
try {
|
|
2701
|
+
gateway = createHttpGateway({
|
|
2702
|
+
socketPath: options.socketPath,
|
|
2703
|
+
token,
|
|
2704
|
+
port: options.port,
|
|
2705
|
+
host: HOST
|
|
2706
|
+
});
|
|
2707
|
+
} catch (error) {
|
|
2708
|
+
process2.stderr.write(`failed to start the HTTP gateway: ${String(error)}
|
|
2709
|
+
`);
|
|
2710
|
+
process2.exit(2);
|
|
2711
|
+
}
|
|
2712
|
+
gateway.server.once("listening", () => {
|
|
2713
|
+
const address = gateway.server.address();
|
|
2714
|
+
const bound = typeof address === "object" && address !== null ? `${address.address}:${address.port}` : String(address);
|
|
2715
|
+
process2.stderr.write(`[glasspane-http] listening on http://${bound}
|
|
2716
|
+
`);
|
|
2717
|
+
process2.stderr.write(`[glasspane-http] bridging daemon socket ${options.socketPath}
|
|
2718
|
+
`);
|
|
2719
|
+
});
|
|
2720
|
+
gateway.server.on("error", (error) => {
|
|
2721
|
+
process2.stderr.write(`[glasspane-http] server error: ${String(error)}
|
|
2722
|
+
`);
|
|
2723
|
+
});
|
|
2724
|
+
let shuttingDown = false;
|
|
2725
|
+
const shutdown = (signal) => {
|
|
2726
|
+
if (shuttingDown) {
|
|
2727
|
+
return;
|
|
2728
|
+
}
|
|
2729
|
+
shuttingDown = true;
|
|
2730
|
+
process2.stderr.write(`[glasspane-http] received ${signal}; shutting down
|
|
2731
|
+
`);
|
|
2732
|
+
gateway.close().then(
|
|
2733
|
+
() => process2.exit(0),
|
|
2734
|
+
(error) => {
|
|
2735
|
+
process2.stderr.write(`[glasspane-http] error during shutdown: ${String(error)}
|
|
2736
|
+
`);
|
|
2737
|
+
process2.exit(1);
|
|
2738
|
+
}
|
|
2739
|
+
);
|
|
2740
|
+
};
|
|
2741
|
+
process2.on("SIGINT", () => shutdown("SIGINT"));
|
|
2742
|
+
process2.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
2743
|
+
}
|
|
2744
|
+
main();
|