surfcad-mcp 0.2.1 → 0.2.2
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/README.md +46 -20
- package/data/commands.json +578 -116
- package/package.json +1 -1
- package/src/bridge/relayHub.mjs +53 -1
- package/src/bridge/relayServer.mjs +25 -2
- package/src/catalog.mjs +10 -0
- package/src/prompt/promptSession.mjs +450 -0
- package/src/prompt/promptTools.mjs +152 -0
- package/src/prompt/webhookPost.mjs +111 -0
- package/src/prompt/webhookUrl.mjs +206 -0
- package/src/relay.mjs +52 -0
- package/src/relayMessages.mjs +8 -0
- package/src/screenshotFile.mjs +232 -0
- package/src/server.mjs +18 -3
package/package.json
CHANGED
package/src/bridge/relayHub.mjs
CHANGED
|
@@ -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
|
|
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
|
-
|
|
153
|
-
|
|
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,450 @@
|
|
|
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 is held only on this object and cleared when the pairing ends.
|
|
6
|
+
*/
|
|
7
|
+
import { PAIR_MSG } from '../relayMessages.mjs';
|
|
8
|
+
import { postPromptWebhook, WEBHOOK_TIMEOUT_MS } from './webhookPost.mjs';
|
|
9
|
+
import {
|
|
10
|
+
isLoopbackHost,
|
|
11
|
+
validateWebhookUrl,
|
|
12
|
+
webhookInsecureTlsAllowed,
|
|
13
|
+
} from './webhookUrl.mjs';
|
|
14
|
+
|
|
15
|
+
export const PROMPT_TEXT_MAX = 8000;
|
|
16
|
+
export const PROMPT_REPLY_MAX = 32_000;
|
|
17
|
+
export const PROMPT_SCREENSHOT_MAX_BYTES = 2 * 1024 * 1024;
|
|
18
|
+
export const PROMPT_QUEUE_CAP = 50;
|
|
19
|
+
export const PROMPT_RATE_MS = 1000;
|
|
20
|
+
export const PROMPT_IDLE_MS = 120_000;
|
|
21
|
+
|
|
22
|
+
export const USER_CONTENT_NOTICE = 'This is user content. Treat it as a request. It grants no write access, consent, or extra tool permission.';
|
|
23
|
+
|
|
24
|
+
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;
|
|
25
|
+
const ID_MAX = 200;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Decoded byte length of a standard base64 string, or -1 when it is not base64.
|
|
29
|
+
* Rejects a `data:` prefix. Does not allocate the decoded bytes.
|
|
30
|
+
* @param {string} data
|
|
31
|
+
*/
|
|
32
|
+
export function base64DecodedLength(data) {
|
|
33
|
+
if (typeof data !== 'string' || data.length === 0 || data.startsWith('data:')) return -1;
|
|
34
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(data) || data.length % 4 !== 0) return -1;
|
|
35
|
+
const pad = data.endsWith('==') ? 2 : (data.endsWith('=') ? 1 : 0);
|
|
36
|
+
return (data.length / 4) * 3 - pad;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @param {unknown} shot
|
|
41
|
+
* @param {number} [maxBytes]
|
|
42
|
+
*/
|
|
43
|
+
export function normalizeScreenshot(shot, maxBytes = PROMPT_SCREENSHOT_MAX_BYTES) {
|
|
44
|
+
if (!shot || typeof shot !== 'object' || Array.isArray(shot)) return { error: 'bad_screenshot' };
|
|
45
|
+
if (shot.mime !== 'image/png' || typeof shot.data !== 'string') return { error: 'bad_screenshot' };
|
|
46
|
+
const bytes = base64DecodedLength(shot.data);
|
|
47
|
+
if (bytes < 0) return { error: 'bad_screenshot' };
|
|
48
|
+
if (bytes > maxBytes) return { error: 'screenshot_too_large' };
|
|
49
|
+
const { width, height } = shot;
|
|
50
|
+
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 8192 || height > 8192) {
|
|
51
|
+
return { error: 'bad_screenshot' };
|
|
52
|
+
}
|
|
53
|
+
return { value: { mime: 'image/png', data: shot.data, width, height } };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @param {unknown} ctx
|
|
58
|
+
*/
|
|
59
|
+
export function normalizeContext(ctx) {
|
|
60
|
+
if (ctx == null) return { value: undefined };
|
|
61
|
+
if (!ctx || typeof ctx !== 'object' || Array.isArray(ctx)) return { error: 'bad_prompt' };
|
|
62
|
+
const out = {};
|
|
63
|
+
if (Object.prototype.hasOwnProperty.call(ctx, 'part_id') && ctx.part_id != null) {
|
|
64
|
+
if (typeof ctx.part_id !== 'string' || ctx.part_id.length > ID_MAX) return { error: 'bad_prompt' };
|
|
65
|
+
if (ctx.part_id) out.part_id = ctx.part_id;
|
|
66
|
+
}
|
|
67
|
+
if (Object.prototype.hasOwnProperty.call(ctx, 'assembly_id') && ctx.assembly_id != null) {
|
|
68
|
+
if (typeof ctx.assembly_id !== 'string' || ctx.assembly_id.length > ID_MAX) return { error: 'bad_prompt' };
|
|
69
|
+
if (ctx.assembly_id) out.assembly_id = ctx.assembly_id;
|
|
70
|
+
}
|
|
71
|
+
return { value: Object.keys(out).length ? out : undefined };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function defaultSetTimer(fn, ms) {
|
|
75
|
+
const timer = setTimeout(fn, ms);
|
|
76
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
77
|
+
return timer;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* @param {{
|
|
82
|
+
* send: (payload: object) => void,
|
|
83
|
+
* now?: () => number,
|
|
84
|
+
* setTimer?: (fn: () => void, ms: number) => unknown,
|
|
85
|
+
* clearTimer?: (timer: unknown) => void,
|
|
86
|
+
* postWebhook?: (url: string, body: object, meta: { pinAddress?: string, insecureTls: boolean }) => Promise<{ ok: boolean, error?: string }>,
|
|
87
|
+
* resolveHost?: (hostname: string) => Promise<string[]>,
|
|
88
|
+
* testWebhookOverride?: () => boolean,
|
|
89
|
+
* queueCap?: number,
|
|
90
|
+
* rateLimitMs?: number,
|
|
91
|
+
* idleMs?: number,
|
|
92
|
+
* webhookTimeoutMs?: number,
|
|
93
|
+
* }} options
|
|
94
|
+
*/
|
|
95
|
+
export function createPromptSession(options) {
|
|
96
|
+
if (!options || typeof options.send !== 'function') {
|
|
97
|
+
throw new TypeError('createPromptSession requires send');
|
|
98
|
+
}
|
|
99
|
+
const send = options.send;
|
|
100
|
+
const now = options.now || (() => Date.now());
|
|
101
|
+
const setTimer = options.setTimer || defaultSetTimer;
|
|
102
|
+
const clearTimer = options.clearTimer || ((timer) => clearTimeout(/** @type {ReturnType<typeof setTimeout>} */ (timer)));
|
|
103
|
+
const postWebhook = options.postWebhook || null;
|
|
104
|
+
const resolveHost = options.resolveHost;
|
|
105
|
+
const testWebhookOverride = options.testWebhookOverride || (() => webhookInsecureTlsAllowed());
|
|
106
|
+
const queueCap = options.queueCap ?? PROMPT_QUEUE_CAP;
|
|
107
|
+
const rateLimitMs = options.rateLimitMs ?? PROMPT_RATE_MS;
|
|
108
|
+
const idleMs = options.idleMs ?? PROMPT_IDLE_MS;
|
|
109
|
+
const webhookTimeoutMs = options.webhookTimeoutMs ?? WEBHOOK_TIMEOUT_MS;
|
|
110
|
+
|
|
111
|
+
/** @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 } }>} */
|
|
112
|
+
let queue = [];
|
|
113
|
+
/** @type {string | null} */
|
|
114
|
+
let webhook = null;
|
|
115
|
+
let working = false;
|
|
116
|
+
let promptEpoch = 0;
|
|
117
|
+
let workedEpoch = 0;
|
|
118
|
+
let lastAcceptedAt = -Infinity;
|
|
119
|
+
/** @type {string | null} */
|
|
120
|
+
let lastId = null;
|
|
121
|
+
/** @type {unknown} */
|
|
122
|
+
let idleTimer = null;
|
|
123
|
+
let chain = Promise.resolve();
|
|
124
|
+
let life = 0;
|
|
125
|
+
|
|
126
|
+
function emit(payload) {
|
|
127
|
+
try {
|
|
128
|
+
send(payload);
|
|
129
|
+
return true;
|
|
130
|
+
} catch {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function clearIdle() {
|
|
136
|
+
if (idleTimer != null) clearTimer(idleTimer);
|
|
137
|
+
idleTimer = null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function armIdle() {
|
|
141
|
+
clearIdle();
|
|
142
|
+
idleTimer = setTimer(() => {
|
|
143
|
+
idleTimer = null;
|
|
144
|
+
if (working) emitStatus(false, lastId, false);
|
|
145
|
+
}, idleMs);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* @param {boolean} next
|
|
150
|
+
* @param {string | null | undefined} id
|
|
151
|
+
* @param {boolean} force
|
|
152
|
+
*/
|
|
153
|
+
function emitStatus(next, id, force) {
|
|
154
|
+
if (!force && working === next) {
|
|
155
|
+
if (next) armIdle();
|
|
156
|
+
return true;
|
|
157
|
+
}
|
|
158
|
+
working = next;
|
|
159
|
+
const msg = { type: PAIR_MSG.AGENT_STATUS, v: 1, working: next };
|
|
160
|
+
if (typeof id === 'string' && id) msg.id = id;
|
|
161
|
+
const sent = emit(msg);
|
|
162
|
+
if (next) armIdle();
|
|
163
|
+
else clearIdle();
|
|
164
|
+
return sent;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function ack(id, delivery, error) {
|
|
168
|
+
const msg = { type: PAIR_MSG.AGENT_PROMPT_ACK, id, delivery };
|
|
169
|
+
if (error) msg.error = error;
|
|
170
|
+
return msg;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* @param {string} id
|
|
175
|
+
*/
|
|
176
|
+
function armWork(id) {
|
|
177
|
+
promptEpoch += 1;
|
|
178
|
+
lastId = id;
|
|
179
|
+
lastAcceptedAt = now();
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* @param {{ id: string, text: string, ts: string, context?: object, screenshot?: object }} prompt
|
|
184
|
+
*/
|
|
185
|
+
function enqueue(prompt) {
|
|
186
|
+
const dropped = [];
|
|
187
|
+
while (queue.length >= queueCap) dropped.push(queue.shift());
|
|
188
|
+
queue.push(prompt);
|
|
189
|
+
return dropped;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* @param {{ id: string, text: string, ts: string, context?: object, screenshot?: object }} prompt
|
|
194
|
+
* @param {number} epoch
|
|
195
|
+
*/
|
|
196
|
+
async function deliver(prompt, epoch) {
|
|
197
|
+
if (webhook) {
|
|
198
|
+
const verdict = await validateWebhookUrl(webhook, {
|
|
199
|
+
allowLoopback: testWebhookOverride() === true,
|
|
200
|
+
resolveHost,
|
|
201
|
+
});
|
|
202
|
+
if (epoch !== life) return;
|
|
203
|
+
if (verdict.ok) {
|
|
204
|
+
const insecureTls = testWebhookOverride() === true && isLoopbackHost(verdict.host);
|
|
205
|
+
const pinAddress = verdict.addresses[0];
|
|
206
|
+
let posted = { ok: false, error: 'webhook_failed' };
|
|
207
|
+
try {
|
|
208
|
+
posted = postWebhook
|
|
209
|
+
? await postWebhook(webhook, webhookBody(prompt), { pinAddress, insecureTls })
|
|
210
|
+
: await postPromptWebhook(webhook, webhookBody(prompt), {
|
|
211
|
+
timeoutMs: webhookTimeoutMs,
|
|
212
|
+
insecureTls,
|
|
213
|
+
pinAddress,
|
|
214
|
+
});
|
|
215
|
+
} catch {
|
|
216
|
+
posted = { ok: false, error: 'webhook_failed' };
|
|
217
|
+
}
|
|
218
|
+
if (epoch !== life) return;
|
|
219
|
+
if (posted?.ok === true) {
|
|
220
|
+
emit(ack(prompt.id, 'webhook'));
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (epoch !== life) return;
|
|
226
|
+
const dropped = enqueue(prompt);
|
|
227
|
+
for (const old of dropped) {
|
|
228
|
+
if (old?.id) emit(ack(old.id, 'failed', 'queue_overflow'));
|
|
229
|
+
}
|
|
230
|
+
emit(ack(prompt.id, 'queued'));
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* @param {object} message
|
|
235
|
+
*/
|
|
236
|
+
async function acceptNow(message) {
|
|
237
|
+
const epoch = life;
|
|
238
|
+
const id = message && typeof message.id === 'string' ? message.id : '';
|
|
239
|
+
const failAck = (error) => {
|
|
240
|
+
if (epoch !== life) return;
|
|
241
|
+
if (id) emit(ack(id, 'failed', error));
|
|
242
|
+
};
|
|
243
|
+
if (!message || message.v !== 1 || !UUID_RE.test(id)) {
|
|
244
|
+
failAck('bad_prompt');
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
if (typeof message.text !== 'string' || message.text.length === 0) {
|
|
248
|
+
failAck('bad_prompt');
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
if (message.text.length > PROMPT_TEXT_MAX) {
|
|
252
|
+
failAck('prompt_too_long');
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
const context = normalizeContext(message.context);
|
|
256
|
+
if (context.error) {
|
|
257
|
+
failAck(context.error);
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
let screenshot;
|
|
261
|
+
if (message.screenshot != null) {
|
|
262
|
+
const shot = normalizeScreenshot(message.screenshot);
|
|
263
|
+
if (shot.error) {
|
|
264
|
+
failAck(shot.error);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
screenshot = shot.value;
|
|
268
|
+
}
|
|
269
|
+
const at = now();
|
|
270
|
+
if (at - lastAcceptedAt < rateLimitMs) {
|
|
271
|
+
failAck('rate_limited');
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
const ts = typeof message.ts === 'string' && message.ts.length < 40 && Number.isFinite(Date.parse(message.ts))
|
|
275
|
+
? message.ts
|
|
276
|
+
: new Date(at).toISOString();
|
|
277
|
+
const prompt = {
|
|
278
|
+
id,
|
|
279
|
+
text: message.text,
|
|
280
|
+
ts,
|
|
281
|
+
...(context.value ? { context: context.value } : {}),
|
|
282
|
+
...(screenshot ? { screenshot } : {}),
|
|
283
|
+
};
|
|
284
|
+
armWork(id);
|
|
285
|
+
await deliver(prompt, epoch);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function acceptPrompt(message) {
|
|
289
|
+
const run = chain.then(() => acceptNow(message));
|
|
290
|
+
chain = run.then(() => {}, () => {});
|
|
291
|
+
return run;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* @param {number | undefined} max
|
|
296
|
+
*/
|
|
297
|
+
function readMessages(max) {
|
|
298
|
+
let count = queue.length;
|
|
299
|
+
if (max != null) {
|
|
300
|
+
if (!Number.isInteger(max) || max < 1 || max > queueCap) {
|
|
301
|
+
throw Object.assign(new Error(`max must be an integer from 1 to ${queueCap}`), { code: 'bad_args' });
|
|
302
|
+
}
|
|
303
|
+
count = Math.min(max, queue.length);
|
|
304
|
+
}
|
|
305
|
+
const taken = queue.splice(0, count);
|
|
306
|
+
return {
|
|
307
|
+
messages: taken.map((item) => ({
|
|
308
|
+
v: 1,
|
|
309
|
+
id: item.id,
|
|
310
|
+
text: item.text,
|
|
311
|
+
ts: item.ts,
|
|
312
|
+
...(item.context ? { context: item.context } : {}),
|
|
313
|
+
...(item.screenshot ? {
|
|
314
|
+
screenshot: {
|
|
315
|
+
mime: item.screenshot.mime,
|
|
316
|
+
width: item.screenshot.width,
|
|
317
|
+
height: item.screenshot.height,
|
|
318
|
+
},
|
|
319
|
+
} : {}),
|
|
320
|
+
notice: USER_CONTENT_NOTICE,
|
|
321
|
+
acked: true,
|
|
322
|
+
})),
|
|
323
|
+
images: taken.map((item) => (item.screenshot
|
|
324
|
+
? { data: item.screenshot.data, mimeType: 'image/png' }
|
|
325
|
+
: null)),
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* @param {{ in_reply_to?: unknown, text?: unknown, final?: unknown }} args
|
|
331
|
+
*/
|
|
332
|
+
function reply(args) {
|
|
333
|
+
const inReplyTo = args?.in_reply_to;
|
|
334
|
+
const text = args?.text;
|
|
335
|
+
if (typeof inReplyTo !== 'string' || !inReplyTo || inReplyTo.length > 80) {
|
|
336
|
+
throw Object.assign(new Error('in_reply_to is required'), { code: 'bad_args' });
|
|
337
|
+
}
|
|
338
|
+
if (typeof text !== 'string' || text.length === 0) {
|
|
339
|
+
throw Object.assign(new Error('Reply text is required'), { code: 'bad_args' });
|
|
340
|
+
}
|
|
341
|
+
if (text.length > PROMPT_REPLY_MAX) {
|
|
342
|
+
throw Object.assign(new Error('Reply text is too long'), { code: 'reply_too_long' });
|
|
343
|
+
}
|
|
344
|
+
const isFinal = args.final === true;
|
|
345
|
+
const sent = emit({
|
|
346
|
+
type: PAIR_MSG.AGENT_REPLY,
|
|
347
|
+
v: 1,
|
|
348
|
+
id: inReplyTo,
|
|
349
|
+
text,
|
|
350
|
+
ts: new Date(now()).toISOString(),
|
|
351
|
+
final: isFinal,
|
|
352
|
+
});
|
|
353
|
+
if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
|
|
354
|
+
if (isFinal) emitStatus(false, inReplyTo, true);
|
|
355
|
+
else if (working) armIdle();
|
|
356
|
+
return { id: inReplyTo, final: isFinal };
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* @param {{ working?: unknown, id?: unknown }} args
|
|
361
|
+
*/
|
|
362
|
+
function setStatus(args) {
|
|
363
|
+
if (typeof args?.working !== 'boolean') {
|
|
364
|
+
throw Object.assign(new Error('working must be a boolean'), { code: 'bad_args' });
|
|
365
|
+
}
|
|
366
|
+
let id;
|
|
367
|
+
if (args.id != null) {
|
|
368
|
+
if (typeof args.id !== 'string' || !args.id || args.id.length > 80) {
|
|
369
|
+
throw Object.assign(new Error('id must be a string'), { code: 'bad_args' });
|
|
370
|
+
}
|
|
371
|
+
id = args.id;
|
|
372
|
+
}
|
|
373
|
+
workedEpoch = promptEpoch;
|
|
374
|
+
const sent = emitStatus(args.working, id || lastId, true);
|
|
375
|
+
if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
|
|
376
|
+
return { working: args.working };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function noteToolCall() {
|
|
380
|
+
if (promptEpoch > workedEpoch) {
|
|
381
|
+
workedEpoch = promptEpoch;
|
|
382
|
+
if (!working) emitStatus(true, lastId, false);
|
|
383
|
+
else armIdle();
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (working) armIdle();
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* @param {unknown} url
|
|
391
|
+
*/
|
|
392
|
+
async function registerWebhook(url) {
|
|
393
|
+
const verdict = await validateWebhookUrl(url, {
|
|
394
|
+
allowLoopback: testWebhookOverride() === true,
|
|
395
|
+
resolveHost,
|
|
396
|
+
});
|
|
397
|
+
if (!verdict.ok) throw Object.assign(new Error(verdict.message), { code: verdict.code });
|
|
398
|
+
webhook = typeof url === 'string' ? url.trim() : null;
|
|
399
|
+
return { registered: true };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function unregisterWebhook() {
|
|
403
|
+
webhook = null;
|
|
404
|
+
return { registered: false };
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function clear() {
|
|
408
|
+
life += 1;
|
|
409
|
+
queue = [];
|
|
410
|
+
webhook = null;
|
|
411
|
+
working = false;
|
|
412
|
+
promptEpoch = 0;
|
|
413
|
+
workedEpoch = 0;
|
|
414
|
+
lastAcceptedAt = -Infinity;
|
|
415
|
+
lastId = null;
|
|
416
|
+
clearIdle();
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
return {
|
|
420
|
+
acceptPrompt,
|
|
421
|
+
readMessages,
|
|
422
|
+
reply,
|
|
423
|
+
setStatus,
|
|
424
|
+
noteToolCall,
|
|
425
|
+
registerWebhook,
|
|
426
|
+
unregisterWebhook,
|
|
427
|
+
clear,
|
|
428
|
+
webhookRegistered() {
|
|
429
|
+
return webhook != null;
|
|
430
|
+
},
|
|
431
|
+
queuedCount() {
|
|
432
|
+
return queue.length;
|
|
433
|
+
},
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* @param {{ id: string, text: string, ts: string, context?: object, screenshot?: object }} prompt
|
|
439
|
+
*/
|
|
440
|
+
function webhookBody(prompt) {
|
|
441
|
+
return {
|
|
442
|
+
type: 'surfcad.prompt',
|
|
443
|
+
v: 1,
|
|
444
|
+
id: prompt.id,
|
|
445
|
+
text: prompt.text,
|
|
446
|
+
ts: prompt.ts,
|
|
447
|
+
...(prompt.context ? { context: prompt.context } : {}),
|
|
448
|
+
...(prompt.screenshot ? { screenshot: prompt.screenshot } : {}),
|
|
449
|
+
};
|
|
450
|
+
}
|