surfcad-mcp 0.2.1 → 0.2.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "surfcad-mcp",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "SurfCAD agent bridge MCP server (stdio) — pairs to a browser tab via the local WebSocket relay",
5
5
  "license": "Apache-2.0",
6
6
  "author": "artur0x0",
@@ -26,6 +26,11 @@ const SECRET_RE = /^[A-Za-z0-9_-]{16,128}$/;
26
26
  export const DEFAULT_TAB_RESERVATION_TTL_MS = 24 * 60 * 60 * 1000;
27
27
  /** How often expired reservations are swept from the Map (unref'd timer). */
28
28
  export const DEFAULT_TAB_RESERVATION_SWEEP_MS = 60 * 1000;
29
+ /**
30
+ * A 2 MiB PNG is about 2.8 MB of base64 plus a short JSON envelope.
31
+ * Larger prompt frames are refused before they are forwarded.
32
+ */
33
+ export const DEFAULT_MAX_AGENT_PROMPT_FRAME_CHARS = 4 * 1024 * 1024;
29
34
 
30
35
  function sendJson(socket, payload) {
31
36
  try {
@@ -81,6 +86,7 @@ function refuse(socket, code, message) {
81
86
  * onLog?: (line: string, level: RelayLogLevel) => void,
82
87
  * reservationTtlMs?: number,
83
88
  * reservationSweepMs?: number,
89
+ * maxPromptFrameChars?: number,
84
90
  * }} [opts]
85
91
  */
86
92
  export function createAgentBridgeRelayHub(opts = {}) {
@@ -88,6 +94,7 @@ export function createAgentBridgeRelayHub(opts = {}) {
88
94
  const log = (line, level = 'info') => { opts.onLog?.(line, level); };
89
95
  const reservationTtlMs = opts.reservationTtlMs ?? DEFAULT_TAB_RESERVATION_TTL_MS;
90
96
  const reservationSweepMs = opts.reservationSweepMs ?? DEFAULT_TAB_RESERVATION_SWEEP_MS;
97
+ const maxPromptFrameChars = opts.maxPromptFrameChars ?? DEFAULT_MAX_AGENT_PROMPT_FRAME_CHARS;
91
98
 
92
99
  /**
93
100
  * @type {Map<string, {
@@ -209,7 +216,8 @@ export function createAgentBridgeRelayHub(opts = {}) {
209
216
 
210
217
  socket.on('message', (raw) => {
211
218
  live.alive = true;
212
- const msg = parseMessage(typeof raw === 'string' ? raw : String(raw));
219
+ const rawText = typeof raw === 'string' ? raw : String(raw);
220
+ const msg = parseMessage(rawText);
213
221
  if (!msg || typeof msg !== 'object') {
214
222
  refuse(socket, 'bad_message', 'Expected JSON object');
215
223
  return;
@@ -352,6 +360,50 @@ export function createAgentBridgeRelayHub(opts = {}) {
352
360
  return;
353
361
  }
354
362
 
363
+ if (msg.type === PAIR_MSG.AGENT_PROMPT || msg.type === PAIR_MSG.AGENT_PROMPT_ACK
364
+ || msg.type === PAIR_MSG.AGENT_REPLY || msg.type === PAIR_MSG.AGENT_STATUS) {
365
+ if (msg.type === PAIR_MSG.AGENT_PROMPT) {
366
+ if (meta.role !== 'tab') {
367
+ sendJson(socket, { type: PAIR_MSG.ERROR, code: 'forbidden', message: 'Only the paired tab sends prompts' });
368
+ return;
369
+ }
370
+ const promptId = typeof msg.id === 'string' ? msg.id : undefined;
371
+ if (rawText.length > maxPromptFrameChars) {
372
+ sendJson(socket, {
373
+ type: PAIR_MSG.AGENT_PROMPT_ACK,
374
+ id: promptId,
375
+ delivery: 'failed',
376
+ error: 'screenshot_too_large',
377
+ });
378
+ return;
379
+ }
380
+ if (tab.pairedPeer == null) {
381
+ sendJson(socket, {
382
+ type: PAIR_MSG.AGENT_PROMPT_ACK,
383
+ id: promptId,
384
+ delivery: 'failed',
385
+ error: 'not_paired',
386
+ });
387
+ return;
388
+ }
389
+ sendJson(tab.pairedPeer, msg);
390
+ return;
391
+ }
392
+ if (meta.role !== 'peer' || tab.pairedPeer !== socket || tab.socket == null) {
393
+ const wrongRole = meta.role !== 'peer';
394
+ sendJson(socket, {
395
+ type: PAIR_MSG.ERROR,
396
+ code: wrongRole ? 'forbidden' : 'not_paired',
397
+ message: wrongRole
398
+ ? 'Only the paired agent sends replies and status'
399
+ : 'Pair before sending agent messages',
400
+ });
401
+ return;
402
+ }
403
+ sendJson(tab.socket, msg);
404
+ return;
405
+ }
406
+
355
407
  if (typeof msg.command === 'string' && msg.type !== PAIR_MSG.PAIR) {
356
408
  if (meta.role !== 'peer' || tab.pairedPeer !== socket) {
357
409
  refuse(socket, 'not_paired', 'Pair before sending bridge commands');
@@ -10,6 +10,7 @@ import { WebSocket, WebSocketServer } from 'ws';
10
10
  import { createAgentBridgeRelayHub } from './relayHub.mjs';
11
11
  import { extraAllowedOrigins, isAllowedHttpOrigin, isLoopbackAddress } from './localAddress.mjs';
12
12
  import { handleBridgeRequest } from './bridgePage.mjs';
13
+ import { loadCommandsCatalog, toolsCatalogPayload } from '../catalog.mjs';
13
14
 
14
15
  export const DEFAULT_RELAY_PORT = 17341;
15
16
 
@@ -127,6 +128,24 @@ export function startAgentBridgeRelay(options = {}) {
127
128
  return;
128
129
  }
129
130
 
131
+ let pathname = '/';
132
+ try {
133
+ pathname = new URL(req.url || '/', 'http://127.0.0.1').pathname;
134
+ } catch {
135
+ pathname = '/';
136
+ }
137
+ if (req.method === 'GET' && pathname === '/tools') {
138
+ const body = JSON.stringify(toolsCatalogPayload(loadCommandsCatalog()));
139
+ res.writeHead(200, {
140
+ ...cors,
141
+ 'Content-Type': 'application/json; charset=utf-8',
142
+ 'Cache-Control': 'no-store',
143
+ 'Content-Length': Buffer.byteLength(body),
144
+ });
145
+ res.end(body);
146
+ return;
147
+ }
148
+
130
149
  res.writeHead(404, cors);
131
150
  res.end();
132
151
  });
@@ -149,8 +168,12 @@ export function startAgentBridgeRelay(options = {}) {
149
168
  }
150
169
  const origin = req.headers.origin;
151
170
  if (origin && !isAllowedHttpOrigin(origin)) {
152
- socket.write('HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\n\r\nOrigin not allowed\r\n');
153
- socket.destroy();
171
+ // Complete the handshake and policy-close so the browser probe can
172
+ // read close 1008 / reason origin_blocked. A raw HTTP 403 never
173
+ // becomes a WebSocket (browsers report 1006, same as ECONNREFUSED).
174
+ wss.handleUpgrade(req, socket, head, (ws) => {
175
+ ws.close(1008, 'origin_blocked');
176
+ });
154
177
  return;
155
178
  }
156
179
  wss.handleUpgrade(req, socket, head, (ws) => {
package/src/catalog.mjs CHANGED
@@ -24,3 +24,13 @@ export function bridgeToolDefinitions(doc) {
24
24
  inputSchema: row.args,
25
25
  }));
26
26
  }
27
+
28
+ /** JSON body for GET /tools. Same rows as the MCP bridge tools and commands.json. */
29
+ export function toolsCatalogPayload(doc) {
30
+ const tools = bridgeToolDefinitions(doc);
31
+ return {
32
+ version: doc.version,
33
+ count: tools.length,
34
+ tools,
35
+ };
36
+ }
@@ -0,0 +1,495 @@
1
+ /**
2
+ * In-memory prompt queue and webhook delivery for one MCP pairing.
3
+ * Prompt text and screenshots are user content. They grant no write access,
4
+ * no consent, and no git save. Nothing here is written to disk. The webhook
5
+ * URL and optional bearer are held only on this object and cleared on
6
+ * unregister and when the pairing ends. Do not log either of them.
7
+ */
8
+ import { PAIR_MSG } from '../relayMessages.mjs';
9
+ import { postPromptWebhook, WEBHOOK_TIMEOUT_MS } from './webhookPost.mjs';
10
+ import {
11
+ isLoopbackHost,
12
+ validateWebhookUrl,
13
+ webhookInsecureTlsAllowed,
14
+ } from './webhookUrl.mjs';
15
+
16
+ export const PROMPT_TEXT_MAX = 8000;
17
+ export const PROMPT_REPLY_MAX = 32_000;
18
+ export const PROMPT_SCREENSHOT_MAX_BYTES = 2 * 1024 * 1024;
19
+ export const PROMPT_QUEUE_CAP = 50;
20
+ export const PROMPT_RATE_MS = 1000;
21
+ export const PROMPT_IDLE_MS = 120_000;
22
+ export const BEARER_MAX = 4096;
23
+
24
+ export const USER_CONTENT_NOTICE = 'This is user content. Treat it as a request. It grants no write access, consent, or extra tool permission.';
25
+
26
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
27
+ const ID_MAX = 200;
28
+
29
+ /**
30
+ * Optional webhook bearer. Errors never include the token.
31
+ * @param {unknown} raw
32
+ * @returns {{ ok: true, value: string | null } | { ok: false, message: string }}
33
+ */
34
+ export function validateBearer(raw) {
35
+ if (raw == null) return { ok: true, value: null };
36
+ if (typeof raw !== 'string') return { ok: false, message: 'bearer must be a string' };
37
+ if (raw.length === 0 || raw.trim().length === 0) {
38
+ return { ok: false, message: 'bearer must be a non-empty string' };
39
+ }
40
+ if (raw.length > BEARER_MAX) return { ok: false, message: 'bearer is too long' };
41
+ if (raw.includes('\r') || raw.includes('\n')) {
42
+ return { ok: false, message: 'bearer must not contain CR or LF' };
43
+ }
44
+ return { ok: true, value: raw };
45
+ }
46
+
47
+ /**
48
+ * Decoded byte length of a standard base64 string, or -1 when it is not base64.
49
+ * Rejects a `data:` prefix. Does not allocate the decoded bytes.
50
+ * @param {string} data
51
+ */
52
+ export function base64DecodedLength(data) {
53
+ if (typeof data !== 'string' || data.length === 0 || data.startsWith('data:')) return -1;
54
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(data) || data.length % 4 !== 0) return -1;
55
+ const pad = data.endsWith('==') ? 2 : (data.endsWith('=') ? 1 : 0);
56
+ return (data.length / 4) * 3 - pad;
57
+ }
58
+
59
+ /**
60
+ * @param {unknown} shot
61
+ * @param {number} [maxBytes]
62
+ */
63
+ export function normalizeScreenshot(shot, maxBytes = PROMPT_SCREENSHOT_MAX_BYTES) {
64
+ if (!shot || typeof shot !== 'object' || Array.isArray(shot)) return { error: 'bad_screenshot' };
65
+ if (shot.mime !== 'image/png' || typeof shot.data !== 'string') return { error: 'bad_screenshot' };
66
+ const bytes = base64DecodedLength(shot.data);
67
+ if (bytes < 0) return { error: 'bad_screenshot' };
68
+ if (bytes > maxBytes) return { error: 'screenshot_too_large' };
69
+ const { width, height } = shot;
70
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 8192 || height > 8192) {
71
+ return { error: 'bad_screenshot' };
72
+ }
73
+ return { value: { mime: 'image/png', data: shot.data, width, height } };
74
+ }
75
+
76
+ /**
77
+ * @param {unknown} ctx
78
+ */
79
+ export function normalizeContext(ctx) {
80
+ if (ctx == null) return { value: undefined };
81
+ if (!ctx || typeof ctx !== 'object' || Array.isArray(ctx)) return { error: 'bad_prompt' };
82
+ const out = {};
83
+ if (Object.prototype.hasOwnProperty.call(ctx, 'part_id') && ctx.part_id != null) {
84
+ if (typeof ctx.part_id !== 'string' || ctx.part_id.length > ID_MAX) return { error: 'bad_prompt' };
85
+ if (ctx.part_id) out.part_id = ctx.part_id;
86
+ }
87
+ if (Object.prototype.hasOwnProperty.call(ctx, 'assembly_id') && ctx.assembly_id != null) {
88
+ if (typeof ctx.assembly_id !== 'string' || ctx.assembly_id.length > ID_MAX) return { error: 'bad_prompt' };
89
+ if (ctx.assembly_id) out.assembly_id = ctx.assembly_id;
90
+ }
91
+ return { value: Object.keys(out).length ? out : undefined };
92
+ }
93
+
94
+ function defaultSetTimer(fn, ms) {
95
+ const timer = setTimeout(fn, ms);
96
+ if (typeof timer.unref === 'function') timer.unref();
97
+ return timer;
98
+ }
99
+
100
+ /**
101
+ * @param {{
102
+ * send: (payload: object) => void,
103
+ * now?: () => number,
104
+ * setTimer?: (fn: () => void, ms: number) => unknown,
105
+ * clearTimer?: (timer: unknown) => void,
106
+ * postWebhook?: (url: string, body: object, meta: { pinAddress?: string, insecureTls: boolean, authorization?: string }) => Promise<{ ok: boolean, error?: string }>,
107
+ * resolveHost?: (hostname: string) => Promise<string[]>,
108
+ * testWebhookOverride?: () => boolean,
109
+ * queueCap?: number,
110
+ * rateLimitMs?: number,
111
+ * idleMs?: number,
112
+ * webhookTimeoutMs?: number,
113
+ * }} options
114
+ */
115
+ export function createPromptSession(options) {
116
+ if (!options || typeof options.send !== 'function') {
117
+ throw new TypeError('createPromptSession requires send');
118
+ }
119
+ const send = options.send;
120
+ const now = options.now || (() => Date.now());
121
+ const setTimer = options.setTimer || defaultSetTimer;
122
+ const clearTimer = options.clearTimer || ((timer) => clearTimeout(/** @type {ReturnType<typeof setTimeout>} */ (timer)));
123
+ const postWebhook = options.postWebhook || null;
124
+ const resolveHost = options.resolveHost;
125
+ const testWebhookOverride = options.testWebhookOverride || (() => webhookInsecureTlsAllowed());
126
+ const queueCap = options.queueCap ?? PROMPT_QUEUE_CAP;
127
+ const rateLimitMs = options.rateLimitMs ?? PROMPT_RATE_MS;
128
+ const idleMs = options.idleMs ?? PROMPT_IDLE_MS;
129
+ const webhookTimeoutMs = options.webhookTimeoutMs ?? WEBHOOK_TIMEOUT_MS;
130
+
131
+ /** @type {Array<{ id: string, text: string, ts: string, context?: { part_id?: string, assembly_id?: string }, screenshot?: { mime: 'image/png', data: string, width: number, height: number } }>} */
132
+ let queue = [];
133
+ /** @type {string | null} */
134
+ let webhook = null;
135
+ /** @type {string | null} Bearer token. Process memory only. Never log or return it. */
136
+ let webhookBearer = null;
137
+ let working = false;
138
+ let promptEpoch = 0;
139
+ let workedEpoch = 0;
140
+ let lastAcceptedAt = -Infinity;
141
+ /** @type {string | null} */
142
+ let lastId = null;
143
+ /** @type {unknown} */
144
+ let idleTimer = null;
145
+ let chain = Promise.resolve();
146
+ let life = 0;
147
+
148
+ function emit(payload) {
149
+ try {
150
+ send(payload);
151
+ return true;
152
+ } catch {
153
+ return false;
154
+ }
155
+ }
156
+
157
+ function clearIdle() {
158
+ if (idleTimer != null) clearTimer(idleTimer);
159
+ idleTimer = null;
160
+ }
161
+
162
+ function armIdle() {
163
+ clearIdle();
164
+ idleTimer = setTimer(() => {
165
+ idleTimer = null;
166
+ if (working) emitStatus(false, lastId, false);
167
+ }, idleMs);
168
+ }
169
+
170
+ /**
171
+ * @param {boolean} next
172
+ * @param {string | null | undefined} id
173
+ * @param {boolean} force
174
+ */
175
+ function emitStatus(next, id, force) {
176
+ if (!force && working === next) {
177
+ if (next) armIdle();
178
+ return true;
179
+ }
180
+ working = next;
181
+ const msg = { type: PAIR_MSG.AGENT_STATUS, v: 1, working: next };
182
+ if (typeof id === 'string' && id) msg.id = id;
183
+ const sent = emit(msg);
184
+ if (next) armIdle();
185
+ else clearIdle();
186
+ return sent;
187
+ }
188
+
189
+ function ack(id, delivery, error) {
190
+ const msg = { type: PAIR_MSG.AGENT_PROMPT_ACK, id, delivery };
191
+ if (error) msg.error = error;
192
+ return msg;
193
+ }
194
+
195
+ /**
196
+ * @param {string} id
197
+ */
198
+ function armWork(id) {
199
+ promptEpoch += 1;
200
+ lastId = id;
201
+ lastAcceptedAt = now();
202
+ }
203
+
204
+ /**
205
+ * @param {{ id: string, text: string, ts: string, context?: object, screenshot?: object }} prompt
206
+ */
207
+ function enqueue(prompt) {
208
+ const dropped = [];
209
+ while (queue.length >= queueCap) dropped.push(queue.shift());
210
+ queue.push(prompt);
211
+ return dropped;
212
+ }
213
+
214
+ /**
215
+ * @param {{ id: string, text: string, ts: string, context?: object, screenshot?: object }} prompt
216
+ * @param {number} epoch
217
+ */
218
+ async function deliver(prompt, epoch) {
219
+ const target = webhook;
220
+ if (target) {
221
+ const verdict = await validateWebhookUrl(target, {
222
+ allowLoopback: testWebhookOverride() === true,
223
+ resolveHost,
224
+ });
225
+ if (epoch !== life) return;
226
+ // A unregister or a different URL landed during DNS. Do not POST the old target.
227
+ if (verdict.ok && webhook === target) {
228
+ const insecureTls = testWebhookOverride() === true && isLoopbackHost(verdict.host);
229
+ const pinAddress = verdict.addresses[0];
230
+ const bearer = webhookBearer;
231
+ const authorization = bearer ? `Bearer ${bearer}` : undefined;
232
+ let posted = { ok: false, error: 'webhook_failed' };
233
+ try {
234
+ posted = postWebhook
235
+ ? await postWebhook(target, webhookBody(prompt), {
236
+ pinAddress,
237
+ insecureTls,
238
+ ...(authorization ? { authorization } : {}),
239
+ })
240
+ : await postPromptWebhook(target, webhookBody(prompt), {
241
+ timeoutMs: webhookTimeoutMs,
242
+ insecureTls,
243
+ pinAddress,
244
+ ...(bearer ? { bearer } : {}),
245
+ });
246
+ } catch {
247
+ posted = { ok: false, error: 'webhook_failed' };
248
+ }
249
+ if (epoch !== life) return;
250
+ if (posted?.ok === true) {
251
+ emit(ack(prompt.id, 'webhook'));
252
+ return;
253
+ }
254
+ }
255
+ }
256
+ if (epoch !== life) return;
257
+ const dropped = enqueue(prompt);
258
+ for (const old of dropped) {
259
+ if (old?.id) emit(ack(old.id, 'failed', 'queue_overflow'));
260
+ }
261
+ emit(ack(prompt.id, 'queued'));
262
+ }
263
+
264
+ /**
265
+ * @param {object} message
266
+ */
267
+ async function acceptNow(message) {
268
+ const epoch = life;
269
+ const id = message && typeof message.id === 'string' ? message.id : '';
270
+ const failAck = (error) => {
271
+ if (epoch !== life) return;
272
+ if (id) emit(ack(id, 'failed', error));
273
+ };
274
+ if (!message || message.v !== 1 || !UUID_RE.test(id)) {
275
+ failAck('bad_prompt');
276
+ return;
277
+ }
278
+ if (typeof message.text !== 'string' || message.text.length === 0) {
279
+ failAck('bad_prompt');
280
+ return;
281
+ }
282
+ if (message.text.length > PROMPT_TEXT_MAX) {
283
+ failAck('prompt_too_long');
284
+ return;
285
+ }
286
+ const context = normalizeContext(message.context);
287
+ if (context.error) {
288
+ failAck(context.error);
289
+ return;
290
+ }
291
+ let screenshot;
292
+ if (message.screenshot != null) {
293
+ const shot = normalizeScreenshot(message.screenshot);
294
+ if (shot.error) {
295
+ failAck(shot.error);
296
+ return;
297
+ }
298
+ screenshot = shot.value;
299
+ }
300
+ const at = now();
301
+ if (at - lastAcceptedAt < rateLimitMs) {
302
+ failAck('rate_limited');
303
+ return;
304
+ }
305
+ const ts = typeof message.ts === 'string' && message.ts.length < 40 && Number.isFinite(Date.parse(message.ts))
306
+ ? message.ts
307
+ : new Date(at).toISOString();
308
+ const prompt = {
309
+ id,
310
+ text: message.text,
311
+ ts,
312
+ ...(context.value ? { context: context.value } : {}),
313
+ ...(screenshot ? { screenshot } : {}),
314
+ };
315
+ armWork(id);
316
+ await deliver(prompt, epoch);
317
+ }
318
+
319
+ function acceptPrompt(message) {
320
+ const run = chain.then(() => acceptNow(message));
321
+ chain = run.then(() => {}, () => {});
322
+ return run;
323
+ }
324
+
325
+ /**
326
+ * @param {number | undefined} max
327
+ */
328
+ function readMessages(max) {
329
+ let count = queue.length;
330
+ if (max != null) {
331
+ if (!Number.isInteger(max) || max < 1 || max > queueCap) {
332
+ throw Object.assign(new Error(`max must be an integer from 1 to ${queueCap}`), { code: 'bad_args' });
333
+ }
334
+ count = Math.min(max, queue.length);
335
+ }
336
+ const taken = queue.splice(0, count);
337
+ return {
338
+ messages: taken.map((item) => ({
339
+ v: 1,
340
+ id: item.id,
341
+ text: item.text,
342
+ ts: item.ts,
343
+ ...(item.context ? { context: item.context } : {}),
344
+ ...(item.screenshot ? {
345
+ screenshot: {
346
+ mime: item.screenshot.mime,
347
+ width: item.screenshot.width,
348
+ height: item.screenshot.height,
349
+ },
350
+ } : {}),
351
+ notice: USER_CONTENT_NOTICE,
352
+ acked: true,
353
+ })),
354
+ images: taken.map((item) => (item.screenshot
355
+ ? { data: item.screenshot.data, mimeType: 'image/png' }
356
+ : null)),
357
+ };
358
+ }
359
+
360
+ /**
361
+ * @param {{ in_reply_to?: unknown, text?: unknown, final?: unknown }} args
362
+ */
363
+ function reply(args) {
364
+ const inReplyTo = args?.in_reply_to;
365
+ const text = args?.text;
366
+ if (typeof inReplyTo !== 'string' || !inReplyTo || inReplyTo.length > 80) {
367
+ throw Object.assign(new Error('in_reply_to is required'), { code: 'bad_args' });
368
+ }
369
+ if (typeof text !== 'string' || text.length === 0) {
370
+ throw Object.assign(new Error('Reply text is required'), { code: 'bad_args' });
371
+ }
372
+ if (text.length > PROMPT_REPLY_MAX) {
373
+ throw Object.assign(new Error('Reply text is too long'), { code: 'reply_too_long' });
374
+ }
375
+ const isFinal = args.final === true;
376
+ const sent = emit({
377
+ type: PAIR_MSG.AGENT_REPLY,
378
+ v: 1,
379
+ id: inReplyTo,
380
+ text,
381
+ ts: new Date(now()).toISOString(),
382
+ final: isFinal,
383
+ });
384
+ if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
385
+ if (isFinal) emitStatus(false, inReplyTo, true);
386
+ else if (working) armIdle();
387
+ return { id: inReplyTo, final: isFinal };
388
+ }
389
+
390
+ /**
391
+ * @param {{ working?: unknown, id?: unknown }} args
392
+ */
393
+ function setStatus(args) {
394
+ if (typeof args?.working !== 'boolean') {
395
+ throw Object.assign(new Error('working must be a boolean'), { code: 'bad_args' });
396
+ }
397
+ let id;
398
+ if (args.id != null) {
399
+ if (typeof args.id !== 'string' || !args.id || args.id.length > 80) {
400
+ throw Object.assign(new Error('id must be a string'), { code: 'bad_args' });
401
+ }
402
+ id = args.id;
403
+ }
404
+ workedEpoch = promptEpoch;
405
+ const sent = emitStatus(args.working, id || lastId, true);
406
+ if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
407
+ return { working: args.working };
408
+ }
409
+
410
+ function noteToolCall() {
411
+ if (promptEpoch > workedEpoch) {
412
+ workedEpoch = promptEpoch;
413
+ if (!working) emitStatus(true, lastId, false);
414
+ else armIdle();
415
+ return;
416
+ }
417
+ if (working) armIdle();
418
+ }
419
+
420
+ /**
421
+ * @param {unknown} url
422
+ * @param {unknown} [bearer]
423
+ */
424
+ async function registerWebhook(url, bearer) {
425
+ const token = validateBearer(bearer);
426
+ if (!token.ok) throw Object.assign(new Error(token.message), { code: 'bad_args' });
427
+ const verdict = await validateWebhookUrl(url, {
428
+ allowLoopback: testWebhookOverride() === true,
429
+ resolveHost,
430
+ });
431
+ if (!verdict.ok) throw Object.assign(new Error(verdict.message), { code: verdict.code });
432
+ webhook = typeof url === 'string' ? url.trim() : null;
433
+ webhookBearer = token.value;
434
+ return { registered: true };
435
+ }
436
+
437
+ function unregisterWebhook() {
438
+ webhook = null;
439
+ webhookBearer = null;
440
+ return { registered: false };
441
+ }
442
+
443
+ function deliveryStatus() {
444
+ return {
445
+ webhookRegistered: webhook != null,
446
+ queued: queue.length,
447
+ };
448
+ }
449
+
450
+ function clear() {
451
+ life += 1;
452
+ queue = [];
453
+ webhook = null;
454
+ webhookBearer = null;
455
+ working = false;
456
+ promptEpoch = 0;
457
+ workedEpoch = 0;
458
+ lastAcceptedAt = -Infinity;
459
+ lastId = null;
460
+ clearIdle();
461
+ }
462
+
463
+ return {
464
+ acceptPrompt,
465
+ readMessages,
466
+ reply,
467
+ setStatus,
468
+ noteToolCall,
469
+ registerWebhook,
470
+ unregisterWebhook,
471
+ deliveryStatus,
472
+ clear,
473
+ webhookRegistered() {
474
+ return webhook != null;
475
+ },
476
+ queuedCount() {
477
+ return queue.length;
478
+ },
479
+ };
480
+ }
481
+
482
+ /**
483
+ * @param {{ id: string, text: string, ts: string, context?: object, screenshot?: object }} prompt
484
+ */
485
+ function webhookBody(prompt) {
486
+ return {
487
+ type: 'surfcad.prompt',
488
+ v: 1,
489
+ id: prompt.id,
490
+ text: prompt.text,
491
+ ts: prompt.ts,
492
+ ...(prompt.context ? { context: prompt.context } : {}),
493
+ ...(prompt.screenshot ? { screenshot: prompt.screenshot } : {}),
494
+ };
495
+ }