surfcad-mcp 0.3.9 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +71 -50
- package/bin/surfcad-mcp.js +16 -8
- package/data/commands.json +6481 -5817
- package/data/helpers.json +243 -268
- package/package.json +10 -2
- package/src/cli.mjs +296 -23
- package/src/cliCall.mjs +221 -0
- package/src/errors.mjs +8 -5
- package/src/helpers.mjs +7 -5
- package/src/importFile.mjs +186 -0
- package/src/listen/bootstrap.mjs +87 -34
- package/src/listen/claudeCodeWake.mjs +74 -0
- package/src/listen/daemon.mjs +35 -0
- package/src/listen/listenCli.mjs +121 -30
- package/src/listen/listener.mjs +138 -8
- package/src/listen/owner.mjs +293 -0
- package/src/listen/waitCli.mjs +133 -0
- package/src/listen/wake.mjs +39 -19
- package/src/listen/wakeSetupText.mjs +23 -5
- package/src/pairWait.mjs +3 -3
- package/src/pairingCode.mjs +10 -0
- package/src/prompt/buildGuidance.mjs +9 -7
- package/src/prompt/chatFlow.mjs +15 -0
- package/src/prompt/errorHints.mjs +24 -10
- package/src/prompt/guide.mjs +27 -14
- package/src/prompt/promptSession.mjs +74 -10
- package/src/prompt/promptTools.mjs +10 -6
- package/src/prompt/replyConfirm.mjs +69 -0
- package/src/relayMessages.mjs +43 -1
- package/src/remote/config.mjs +17 -13
- package/src/remote/session.mjs +103 -5
- package/src/room/roomRuntime.mjs +186 -0
- package/src/room/roomServer.mjs +112 -0
- package/src/room/roomToolSchemas.mjs +228 -0
- package/src/room/seat.mjs +334 -0
- package/src/screenshotFile.mjs +9 -0
- package/src/server.mjs +155 -111
- package/src/stepUploadLimit.mjs +8 -0
- package/src/bridge/bridgePage.mjs +0 -132
- package/src/bridge/bridgePopup.mjs +0 -288
- package/src/bridge/relayHub.mjs +0 -556
- package/src/bridge/relayServer.mjs +0 -291
- package/src/nodeClient.mjs +0 -63
- package/src/relay.mjs +0 -419
|
@@ -52,7 +52,7 @@ export const BUILDING_STATUS_GUIDANCE = 'Call set_status { state: "building" } o
|
|
|
52
52
|
* Session presence. Kept short: it is part of the initialize instructions,
|
|
53
53
|
* which hosts truncate past 2 KB.
|
|
54
54
|
*/
|
|
55
|
-
export const SESSION_PRESENCE_GUIDANCE = 'Be interactive: post_progress while working, especially during long reasoning. A fresh process per tool call is normal and stays present. A long-lived process is optional, never required.
|
|
55
|
+
export const SESSION_PRESENCE_GUIDANCE = 'Be interactive: post_progress while working, especially during long reasoning. A fresh process per tool call is normal and stays present. A long-lived process is optional, never required. Never call close_session after a task.';
|
|
56
56
|
|
|
57
57
|
/**
|
|
58
58
|
* Short form of the in-viewer turn, for the initialize instructions (hosts
|
|
@@ -136,7 +136,7 @@ export function promptToolDefinitions() {
|
|
|
136
136
|
},
|
|
137
137
|
{
|
|
138
138
|
name: 'read_messages',
|
|
139
|
-
description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text.
|
|
139
|
+
description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text. An image the user attached (a screenshot of the model, or a photo from their camera or library) is the following image content block (image/png), not HTML and not part of the text. A message can carry up to four images: they follow it as consecutive image blocks in the order the user attached them, and the message says image_count when there is more than one. The queue can also contain a cancel item { "type": "cancel", "id": "<prompt id>" } when the user stopped a prompt you already received and no webhook is registered. Stop work on that id. Do not call reply_to_user or set_status for it. Every response includes recent: the last ${PROMPT_QUEUE_CAP} prompts this session received, oldest first, each { id, state } (queued, delivered, replied, or cancelled), held in memory only. A remote session returns that same recent list; an idle session that has not received a prompt has recent: []. acked is only the ids this call removed. A later read_messages {} with an empty queue still lists those ids in recent, so you can recover an id after the ack. status.last is only the newest id. ${USER_CONTENT} Do not render the text or the image as HTML. read_messages is a poll, not activity: with or without wait_ms it keeps the session connected but does not restart the stall window and does not change what the tab shows. When you finish the task from a prompt you received here, close that chat: ${CLOSING_REPLY_GUIDANCE} ${PROMPT_TURN_GUIDANCE}`,
|
|
140
140
|
inputSchema: {
|
|
141
141
|
type: 'object',
|
|
142
142
|
additionalProperties: false,
|
|
@@ -158,7 +158,7 @@ export function promptToolDefinitions() {
|
|
|
158
158
|
},
|
|
159
159
|
{
|
|
160
160
|
name: 'reply_to_user',
|
|
161
|
-
description: `${CLOSING_REPLY_GUIDANCE} The final reply is expected: it closes the task in the chat. Send a plain-text reply to
|
|
161
|
+
description: `${CLOSING_REPLY_GUIDANCE} The final reply is expected: it closes the task in the chat. Send a plain-text reply for a prompt id that belongs to this paired chat, including one read_messages returned in this process or in another (a wake run or a one-shot surfcad-mcp call). Several replies may share one id, including non-final replies and a final reply after read_messages has acked that prompt. Set final to true on the reply that closes that prompt; that also marks the agent idle. Omit in_reply_to to post one plain-text message to this paired session when no prompt is waiting. That note is not a prompt id, is limited to one per second, and does not close a prompt. The text is delivered as text, never rendered as HTML. This does not write the model or git. An in_reply_to that does not exist, or that belongs to someone else, is an error unknown_prompt and nothing is sent to the tab. A cancelled id returns { "ok": false, "error": "cancelled" } and is not delivered.`,
|
|
162
162
|
inputSchema: {
|
|
163
163
|
type: 'object',
|
|
164
164
|
additionalProperties: false,
|
|
@@ -166,7 +166,7 @@ export function promptToolDefinitions() {
|
|
|
166
166
|
properties: {
|
|
167
167
|
in_reply_to: {
|
|
168
168
|
type: 'string',
|
|
169
|
-
description: 'Prompt id this reply answers. Omit it to post a session message with no prompt. When set, it must
|
|
169
|
+
description: 'Prompt id this reply answers. Omit it to post a session message with no prompt. When set, it must belong to this paired chat: the id from read_messages, from the wake payload, or from an earlier session that read it. An id that does not exist, or that belongs to someone else, is unknown_prompt.',
|
|
170
170
|
},
|
|
171
171
|
text: {
|
|
172
172
|
type: 'string',
|
|
@@ -224,7 +224,7 @@ export function promptToolDefinitions() {
|
|
|
224
224
|
},
|
|
225
225
|
{
|
|
226
226
|
name: 'close_session',
|
|
227
|
-
description: '
|
|
227
|
+
description: 'Rarely needed: do not call it after a task, the user may answer minutes later. It shows the agent offline in the tab now instead of after 10 minutes with no activity. Chat messages waiting for you are kept for the next agent call, not dropped. Never call it on process exit, stdin end, or SIGTERM. A later tool call starts a new session.',
|
|
228
228
|
inputSchema: {
|
|
229
229
|
type: 'object',
|
|
230
230
|
additionalProperties: false,
|
|
@@ -255,7 +255,7 @@ export async function callPromptTool(prompts, name, args) {
|
|
|
255
255
|
}
|
|
256
256
|
if (wait > 0 && typeof prompts.waitForMessage === 'function') await prompts.waitForMessage(wait);
|
|
257
257
|
}
|
|
258
|
-
const { messages, images } = prompts.readMessages(args.max);
|
|
258
|
+
const { messages, images, extraImages } = prompts.readMessages(args.max);
|
|
259
259
|
const recent = typeof prompts.recentPrompts === 'function' ? prompts.recentPrompts() : [];
|
|
260
260
|
if (messages.length === 0) {
|
|
261
261
|
return {
|
|
@@ -270,6 +270,10 @@ export async function callPromptTool(prompts, name, args) {
|
|
|
270
270
|
content.push({ type: 'text', text: JSON.stringify(row, null, 2) });
|
|
271
271
|
const image = images[i];
|
|
272
272
|
if (image) content.push({ type: 'image', data: image.data, mimeType: image.mimeType });
|
|
273
|
+
// The message's other images, in the order the user attached them.
|
|
274
|
+
for (const extra of extraImages?.[i] || []) {
|
|
275
|
+
content.push({ type: 'image', data: extra.data, mimeType: extra.mimeType });
|
|
276
|
+
}
|
|
273
277
|
}
|
|
274
278
|
content.push({ type: 'text', text: JSON.stringify({ acked, recent }, null, 2) });
|
|
275
279
|
return { content };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The relay answers `agent.reply` with `agent.reply.result`. A new process
|
|
3
|
+
* does not know which prompt ids this chat has sent, so it waits for that
|
|
4
|
+
* answer instead of trusting the id's shape. An older relay that never
|
|
5
|
+
* answers is treated as success after a short wait: it still forwards the
|
|
6
|
+
* reply, which is what those servers do for every id.
|
|
7
|
+
*/
|
|
8
|
+
import { PAIR_MSG } from '../relayMessages.mjs';
|
|
9
|
+
|
|
10
|
+
export const REPLY_CONFIRM_MS = 800;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @param {Map<string, { resolve: () => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout> }>} waiters
|
|
14
|
+
* @param {object} payload
|
|
15
|
+
* @param {number} [timeoutMs]
|
|
16
|
+
* @returns {Promise<void> | null}
|
|
17
|
+
*/
|
|
18
|
+
export function armReplyConfirm(waiters, payload, timeoutMs = REPLY_CONFIRM_MS) {
|
|
19
|
+
if (!payload || payload.type !== PAIR_MSG.AGENT_REPLY || typeof payload.id !== 'string' || !payload.id) {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
const id = payload.id;
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
const timer = setTimeout(() => {
|
|
25
|
+
waiters.delete(id);
|
|
26
|
+
resolve();
|
|
27
|
+
}, timeoutMs);
|
|
28
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
29
|
+
waiters.set(id, { resolve, reject, timer });
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {Map<string, { resolve: () => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout> }>} waiters
|
|
35
|
+
* @param {object} msg
|
|
36
|
+
* @returns {boolean} true when this frame was a reply result (handled or ignored)
|
|
37
|
+
*/
|
|
38
|
+
export function settleReplyConfirm(waiters, msg) {
|
|
39
|
+
if (!msg || msg.type !== PAIR_MSG.AGENT_REPLY_RESULT) return false;
|
|
40
|
+
const id = typeof msg.id === 'string' ? msg.id : '';
|
|
41
|
+
if (!id) return true;
|
|
42
|
+
const waiter = waiters.get(id);
|
|
43
|
+
if (!waiter) return true;
|
|
44
|
+
waiters.delete(id);
|
|
45
|
+
clearTimeout(waiter.timer);
|
|
46
|
+
if (msg.ok === false) {
|
|
47
|
+
const code = typeof msg.error === 'string' && msg.error ? msg.error : 'unknown_prompt';
|
|
48
|
+
waiter.reject(Object.assign(new Error(
|
|
49
|
+
code === 'unknown_prompt'
|
|
50
|
+
? 'in_reply_to is not a prompt in this paired chat'
|
|
51
|
+
: 'Reply was refused',
|
|
52
|
+
), { code }));
|
|
53
|
+
} else {
|
|
54
|
+
waiter.resolve();
|
|
55
|
+
}
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param {Map<string, { resolve: () => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout> }>} waiters
|
|
61
|
+
* @param {Error} err
|
|
62
|
+
*/
|
|
63
|
+
export function failReplyConfirms(waiters, err) {
|
|
64
|
+
for (const waiter of waiters.values()) {
|
|
65
|
+
clearTimeout(waiter.timer);
|
|
66
|
+
waiter.reject(err);
|
|
67
|
+
}
|
|
68
|
+
waiters.clear();
|
|
69
|
+
}
|
package/src/relayMessages.mjs
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Wire message types for the SurfCAD M1 agent-bridge relay (browser tab ↔ local peer).
|
|
3
|
-
* Kept in sync with `src/agent/ws/
|
|
3
|
+
* Kept in sync with `src/agent/ws/relayMessages.js` in the SurfCAD monorepo.
|
|
4
4
|
*/
|
|
5
|
+
/** Largest agent.prompt frame the server will forward, in characters. */
|
|
6
|
+
export const DEFAULT_MAX_AGENT_PROMPT_FRAME_CHARS = 4 * 1024 * 1024;
|
|
7
|
+
|
|
5
8
|
export const PAIR_MSG = Object.freeze({
|
|
6
9
|
ERROR: 'error',
|
|
7
10
|
REGISTER_TAB: 'register_tab',
|
|
@@ -19,6 +22,12 @@ export const PAIR_MSG = Object.freeze({
|
|
|
19
22
|
AGENT_PROMPT_ACK: 'agent.prompt.ack',
|
|
20
23
|
/** Agent → page. Contract v:1. Several replies may share one prompt id. */
|
|
21
24
|
AGENT_REPLY: 'agent.reply',
|
|
25
|
+
/**
|
|
26
|
+
* Relay → agent. Contract v:1. `{ id, ok, error? }`. The reply was
|
|
27
|
+
* forwarded (`ok`) or refused (`unknown_prompt`) because the id is not
|
|
28
|
+
* in this paired chat. Not forwarded to the page.
|
|
29
|
+
*/
|
|
30
|
+
AGENT_REPLY_RESULT: 'agent.reply.result',
|
|
22
31
|
/** Agent → page. Contract v:1. A plain-text note for this paired session, with no prompt id. */
|
|
23
32
|
AGENT_MESSAGE: 'agent.message',
|
|
24
33
|
/** Agent → page. Contract v:1. */
|
|
@@ -40,3 +49,36 @@ export const PAIR_MSG = Object.freeze({
|
|
|
40
49
|
*/
|
|
41
50
|
AGENT_PROMPT_TAKEN: 'agent.prompt.taken',
|
|
42
51
|
});
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Newest prompt ids kept per paired chat. Older than this, a reply is
|
|
55
|
+
* `unknown_prompt`. The text is not stored. Lives in this file because the
|
|
56
|
+
* backend deploy already ships it (BE_SHARED); a new module would not.
|
|
57
|
+
*/
|
|
58
|
+
export const KNOWN_PROMPT_CAP = 2000;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* @param {Map<string, true> | null | undefined} ids
|
|
62
|
+
* @param {unknown} id
|
|
63
|
+
* @param {number} [cap]
|
|
64
|
+
* @returns {boolean}
|
|
65
|
+
*/
|
|
66
|
+
export function rememberPromptId(ids, id, cap = KNOWN_PROMPT_CAP) {
|
|
67
|
+
if (!(ids instanceof Map)) return false;
|
|
68
|
+
if (typeof id !== 'string' || !id || id.length > 80) return false;
|
|
69
|
+
ids.delete(id);
|
|
70
|
+
ids.set(id, true);
|
|
71
|
+
while (ids.size > cap) {
|
|
72
|
+
const oldest = ids.keys().next().value;
|
|
73
|
+
ids.delete(oldest);
|
|
74
|
+
}
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* @param {Map<string, true> | null | undefined} ids
|
|
80
|
+
* @param {unknown} id
|
|
81
|
+
*/
|
|
82
|
+
export function promptIdKnown(ids, id) {
|
|
83
|
+
return ids instanceof Map && typeof id === 'string' && id.length > 0 && ids.has(id);
|
|
84
|
+
}
|
package/src/remote/config.mjs
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Server relay address and agent name.
|
|
3
3
|
* The token never appears in these helpers.
|
|
4
|
+
*
|
|
5
|
+
* The loopback relay was removed in 0.4.0. `--local` and the old loopback
|
|
6
|
+
* env vars are refused so a saved config does not silently do nothing.
|
|
4
7
|
*/
|
|
5
8
|
|
|
6
9
|
import { homedir } from 'node:os';
|
|
@@ -150,29 +153,30 @@ function explicitLocalRelay(env) {
|
|
|
150
153
|
return false;
|
|
151
154
|
}
|
|
152
155
|
|
|
156
|
+
const LOCAL_RELAY_REMOVED = 'The local relay was removed in surfcad-mcp 0.4.0. Run npx surfcad-mcp login --code CODE.';
|
|
157
|
+
|
|
153
158
|
/**
|
|
154
|
-
*
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
* 3. an explicit loopback URL, port, or pairing code → local
|
|
158
|
-
* 4. a saved login → remote
|
|
159
|
-
* 5. local
|
|
159
|
+
* Stdio always uses the server relay. A saved login is required; the CLI
|
|
160
|
+
* reports a missing one. `--local` and the old loopback env vars are errors.
|
|
161
|
+
* `--remote` is accepted and changes nothing.
|
|
160
162
|
* @param {{
|
|
161
163
|
* remote?: boolean,
|
|
162
164
|
* local?: boolean,
|
|
163
165
|
* loggedIn?: boolean,
|
|
164
166
|
* env?: NodeJS.ProcessEnv,
|
|
165
167
|
* }} [options]
|
|
166
|
-
* @returns {{ ok: true, mode: '
|
|
168
|
+
* @returns {{ ok: true, mode: 'remote' } | { ok: false, error: string }}
|
|
167
169
|
*/
|
|
168
170
|
export function selectRelayMode(options = {}) {
|
|
169
171
|
const env = options.env || process.env;
|
|
170
172
|
if (options.remote && options.local) {
|
|
171
173
|
return { ok: false, error: 'Pass either --remote or --local, not both.' };
|
|
172
174
|
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
if (options.
|
|
177
|
-
|
|
175
|
+
const transport = typeof env.SURFCAD_MCP_TRANSPORT === 'string'
|
|
176
|
+
? env.SURFCAD_MCP_TRANSPORT.trim().toLowerCase()
|
|
177
|
+
: '';
|
|
178
|
+
if (options.local || transport === 'local' || explicitLocalRelay(env)) {
|
|
179
|
+
return { ok: false, error: LOCAL_RELAY_REMOVED };
|
|
180
|
+
}
|
|
181
|
+
return { ok: true, mode: 'remote' };
|
|
178
182
|
}
|
package/src/remote/session.mjs
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* The bearer token is never logged and is never placed in the URL.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
+
import { releaseOwner } from '../listen/owner.mjs';
|
|
7
8
|
import { randomUUID } from 'node:crypto';
|
|
8
9
|
import { WebSocket } from 'ws';
|
|
9
10
|
import {
|
|
@@ -21,12 +22,24 @@ import {
|
|
|
21
22
|
} from '../errors.mjs';
|
|
22
23
|
import { PAIR_MSG } from '../relayMessages.mjs';
|
|
23
24
|
import { createPromptSession } from '../prompt/promptSession.mjs';
|
|
25
|
+
import { armReplyConfirm, failReplyConfirms, settleReplyConfirm } from '../prompt/replyConfirm.mjs';
|
|
24
26
|
import { agentUrls, resolveAgentName } from './config.mjs';
|
|
25
27
|
import { callOverHttp, COMMAND_WAIT_MS, commandWaitTimeout, resultFromCommandResponse } from './httpFallback.mjs';
|
|
26
28
|
|
|
27
29
|
/** Server relay closes a revoked or expired token with this code. */
|
|
28
30
|
const TOKEN_CLOSE_CODE = 4001;
|
|
29
31
|
const HELLO_TIMEOUT_MS = 8000;
|
|
32
|
+
/**
|
|
33
|
+
* Incoming frame cap on this client. The server relay's cap is the one that
|
|
34
|
+
* drops a tab socket; this stays above it so a `list_edges` result the
|
|
35
|
+
* server accepted is not dropped here. `ws` defaults to 100 MB.
|
|
36
|
+
*/
|
|
37
|
+
const AGENT_WS_MAX_PAYLOAD = 64 * 1024 * 1024;
|
|
38
|
+
/**
|
|
39
|
+
* How long `close()` waits for frames on their way out (the "taken" report,
|
|
40
|
+
* the close handshake) before it drops the socket anyway.
|
|
41
|
+
*/
|
|
42
|
+
const CLOSE_FLUSH_MS = 3000;
|
|
30
43
|
|
|
31
44
|
/**
|
|
32
45
|
* @param {string} wsUrl
|
|
@@ -37,6 +50,7 @@ function openAuthorizedSocket(wsUrl, token) {
|
|
|
37
50
|
const ws = new WebSocket(wsUrl, {
|
|
38
51
|
headers: { Authorization: `Bearer ${token}` },
|
|
39
52
|
handshakeTimeout: HELLO_TIMEOUT_MS,
|
|
53
|
+
maxPayload: AGENT_WS_MAX_PAYLOAD,
|
|
40
54
|
});
|
|
41
55
|
let settled = false;
|
|
42
56
|
const fail = (err) => {
|
|
@@ -171,6 +185,14 @@ export class RemoteSession {
|
|
|
171
185
|
#promptAbort = null;
|
|
172
186
|
/** @type {Map<string, { resolve: (v: unknown) => void, reject: (e: Error) => void }>} */
|
|
173
187
|
#pending = new Map();
|
|
188
|
+
/** @type {Map<string, { resolve: () => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout> }>} */
|
|
189
|
+
#replyWaiters = new Map();
|
|
190
|
+
/**
|
|
191
|
+
* Sends nobody awaits (the "taken" report, a cancel result). `close()`
|
|
192
|
+
* waits for them, so a one-shot process does not exit with one unsent.
|
|
193
|
+
* @type {Set<Promise<void>>}
|
|
194
|
+
*/
|
|
195
|
+
#outbound = new Set();
|
|
174
196
|
#log;
|
|
175
197
|
#fetch;
|
|
176
198
|
#commandTimeoutMs;
|
|
@@ -205,11 +227,12 @@ export class RemoteSession {
|
|
|
205
227
|
: COMMAND_WAIT_MS;
|
|
206
228
|
this.#prompts = options.promptSession || createPromptSession({
|
|
207
229
|
send: (payload) => this.#sendToTab(payload),
|
|
230
|
+
confirmReplies: true,
|
|
208
231
|
// The server holds a tab prompt until a process reports it taken.
|
|
209
232
|
onTaken: (ids) => {
|
|
210
|
-
Promise.resolve()
|
|
233
|
+
this.#track(Promise.resolve()
|
|
211
234
|
.then(() => this.#sendToTab({ type: PAIR_MSG.AGENT_PROMPT_TAKEN, v: 1, ids }))
|
|
212
|
-
.catch(() => { /* advisory; the next hello or pull offers them again */ });
|
|
235
|
+
.catch(() => { /* advisory; the next hello or pull offers them again */ }));
|
|
213
236
|
},
|
|
214
237
|
onUnread: options.onUnread,
|
|
215
238
|
});
|
|
@@ -438,6 +461,7 @@ export class RemoteSession {
|
|
|
438
461
|
}));
|
|
439
462
|
return;
|
|
440
463
|
}
|
|
464
|
+
if (settleReplyConfirm(this.#replyWaiters, msg)) return;
|
|
441
465
|
if (this.#dispatchInbound(msg)) return;
|
|
442
466
|
const id = msg.id == null ? '' : String(msg.id);
|
|
443
467
|
const waiter = id ? this.#pending.get(id) : undefined;
|
|
@@ -500,13 +524,19 @@ export class RemoteSession {
|
|
|
500
524
|
* @returns {boolean} true when this frame was a prompt
|
|
501
525
|
*/
|
|
502
526
|
#dispatchInbound(msg) {
|
|
527
|
+
if (msg.type === 'agent.chat.reset') {
|
|
528
|
+
// The person deleted the chat history: this machine's chat owner lets
|
|
529
|
+
// go, and the next message starts a new session.
|
|
530
|
+
void releaseOwner(process.env).catch(() => {});
|
|
531
|
+
return true;
|
|
532
|
+
}
|
|
503
533
|
if (msg.type === PAIR_MSG.AGENT_PROMPT) {
|
|
504
534
|
void this.#prompts.acceptPrompt(msg);
|
|
505
535
|
return true;
|
|
506
536
|
}
|
|
507
537
|
if (msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL) {
|
|
508
538
|
const cancelId = typeof msg.id === 'string' ? msg.id : '';
|
|
509
|
-
|
|
539
|
+
this.#track(this.#prompts.cancel(cancelId).then((result) => (
|
|
510
540
|
Promise.resolve(this.#sendToTab({
|
|
511
541
|
type: PAIR_MSG.AGENT_PROMPT_CANCEL_RESULT,
|
|
512
542
|
v: 1,
|
|
@@ -514,8 +544,8 @@ export class RemoteSession {
|
|
|
514
544
|
state: result.state,
|
|
515
545
|
})).catch(() => {
|
|
516
546
|
/* socket closed before the result could be sent */
|
|
517
|
-
})
|
|
518
|
-
|
|
547
|
+
})
|
|
548
|
+
), () => {}));
|
|
519
549
|
return true;
|
|
520
550
|
}
|
|
521
551
|
return false;
|
|
@@ -597,6 +627,7 @@ export class RemoteSession {
|
|
|
597
627
|
#failPending(err) {
|
|
598
628
|
for (const waiter of this.#pending.values()) waiter.reject(err);
|
|
599
629
|
this.#pending.clear();
|
|
630
|
+
failReplyConfirms(this.#replyWaiters, err);
|
|
600
631
|
}
|
|
601
632
|
|
|
602
633
|
/**
|
|
@@ -609,7 +640,9 @@ export class RemoteSession {
|
|
|
609
640
|
async #sendToTab(payload) {
|
|
610
641
|
if (!this.isPaired()) await this.connect();
|
|
611
642
|
if (this.#transport === 'ws' && this.#ws && this.#ws.readyState === WebSocket.OPEN) {
|
|
643
|
+
const pending = armReplyConfirm(this.#replyWaiters, payload);
|
|
612
644
|
this.#ws.send(JSON.stringify(payload));
|
|
645
|
+
if (pending) await pending;
|
|
613
646
|
return;
|
|
614
647
|
}
|
|
615
648
|
if (this.#state === 'paired' && this.#transport === 'http') {
|
|
@@ -698,6 +731,71 @@ export class RemoteSession {
|
|
|
698
731
|
});
|
|
699
732
|
}
|
|
700
733
|
|
|
734
|
+
/**
|
|
735
|
+
* @param {Promise<unknown>} sending never rejects
|
|
736
|
+
*/
|
|
737
|
+
#track(sending) {
|
|
738
|
+
const entry = sending.then(() => {}, () => {});
|
|
739
|
+
this.#outbound.add(entry);
|
|
740
|
+
void entry.then(() => this.#outbound.delete(entry));
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/**
|
|
744
|
+
* Everything on its way to the server has arrived: the untracked sends
|
|
745
|
+
* have settled (over HTTPS that is the POST's answer), and on a websocket
|
|
746
|
+
* the closing handshake is done. `ws` writes the close frame after every
|
|
747
|
+
* queued frame and the server answers it after reading up to it, so its
|
|
748
|
+
* close is the receipt for all of them.
|
|
749
|
+
*/
|
|
750
|
+
async #flushOutbound() {
|
|
751
|
+
while (this.#outbound.size > 0) {
|
|
752
|
+
await Promise.all([...this.#outbound]);
|
|
753
|
+
}
|
|
754
|
+
const ws = this.#ws;
|
|
755
|
+
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
|
756
|
+
// This session is leaving: its own close handler would fall back to
|
|
757
|
+
// HTTPS and start a prompt pull.
|
|
758
|
+
ws.removeAllListeners('close');
|
|
759
|
+
await new Promise((resolve) => {
|
|
760
|
+
ws.once('close', () => resolve(undefined));
|
|
761
|
+
try {
|
|
762
|
+
ws.close(1000);
|
|
763
|
+
} catch {
|
|
764
|
+
resolve(undefined);
|
|
765
|
+
}
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* Leave without losing a frame. `disconnect()` alone terminates the
|
|
771
|
+
* socket, and a one-shot process (`surfcad-mcp call`) then exits: a
|
|
772
|
+
* "taken" report sent a moment earlier could be dropped, and the server
|
|
773
|
+
* offered the same prompt to the next process. This waits, up to
|
|
774
|
+
* `timeoutMs`, for the pending sends and the closing handshake, then
|
|
775
|
+
* disconnects (the hard close is the fallback).
|
|
776
|
+
* @param {{ timeoutMs?: number }} [options]
|
|
777
|
+
*/
|
|
778
|
+
async close(options = {}) {
|
|
779
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs >= 0
|
|
780
|
+
? options.timeoutMs
|
|
781
|
+
: CLOSE_FLUSH_MS;
|
|
782
|
+
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
|
783
|
+
let timer;
|
|
784
|
+
const expired = new Promise((resolve) => {
|
|
785
|
+
timer = setTimeout(() => resolve('timeout'), timeoutMs);
|
|
786
|
+
});
|
|
787
|
+
let flushed = false;
|
|
788
|
+
try {
|
|
789
|
+
flushed = (await Promise.race([this.#flushOutbound().then(() => 'flushed'), expired])) === 'flushed';
|
|
790
|
+
} catch {
|
|
791
|
+
/* the hard close below is the fallback */
|
|
792
|
+
} finally {
|
|
793
|
+
clearTimeout(timer);
|
|
794
|
+
this.disconnect();
|
|
795
|
+
}
|
|
796
|
+
return { flushed };
|
|
797
|
+
}
|
|
798
|
+
|
|
701
799
|
disconnect() {
|
|
702
800
|
this.#connecting = null;
|
|
703
801
|
this.#stopPromptPull();
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime loader and room-session connector for headless room mode
|
|
3
|
+
* (`surfcad-mcp room mcp` and `surfcad-mcp room call`).
|
|
4
|
+
*
|
|
5
|
+
* Dynamically imports the standalone `surfcad` package (`surfcad/room`), which
|
|
6
|
+
* ships the SurfCAD helper runtime, patched Manifold 3.0.1 WASM kernel,
|
|
7
|
+
* `--permission` sandbox runner, and headless room client.
|
|
8
|
+
*/
|
|
9
|
+
import WebSocket from 'ws';
|
|
10
|
+
import { resolveServerUrl } from '../remote/config.mjs';
|
|
11
|
+
import { readRoomSeat } from './seat.mjs';
|
|
12
|
+
|
|
13
|
+
const MIN_NODE_MAJOR = 22;
|
|
14
|
+
const MIN_NODE_MINOR = 15;
|
|
15
|
+
const DEFAULT_READY_TIMEOUT_MS = 20_000;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Node >= 22.15 is required for the `--permission` sandbox runner.
|
|
19
|
+
* @param {string} [version]
|
|
20
|
+
*/
|
|
21
|
+
export function checkRoomNodeVersion(version = process.versions?.node || '0.0.0') {
|
|
22
|
+
const [majStr = '0', minStr = '0'] = String(version).replace(/^v/, '').split('.');
|
|
23
|
+
const major = Number(majStr);
|
|
24
|
+
const minor = Number(minStr);
|
|
25
|
+
const ok = major > MIN_NODE_MAJOR || (major === MIN_NODE_MAJOR && minor >= MIN_NODE_MINOR);
|
|
26
|
+
if (!ok) {
|
|
27
|
+
throw Object.assign(
|
|
28
|
+
new Error(`Room mode requires Node.js >= ${MIN_NODE_MAJOR}.${MIN_NODE_MINOR}.0 for the build sandbox (found ${version}).`),
|
|
29
|
+
{ code: 'node_too_old' },
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Load `surfcad/room`, surfacing a clear install instruction if `surfcad` is not installed.
|
|
36
|
+
* @param {{ importRoom?: () => Promise<any> }} [opts]
|
|
37
|
+
*/
|
|
38
|
+
export async function loadSurfcadRoomModule(opts = {}) {
|
|
39
|
+
const loader = typeof opts.importRoom === 'function'
|
|
40
|
+
? opts.importRoom
|
|
41
|
+
: () => import('surfcad/room');
|
|
42
|
+
try {
|
|
43
|
+
const mod = await loader();
|
|
44
|
+
if (!mod || typeof mod.createHeadlessRoom !== 'function' || typeof mod.createBuildRunner !== 'function') {
|
|
45
|
+
throw Object.assign(
|
|
46
|
+
new Error('The installed "surfcad" package does not export surfcad/room. Update it with: npm i -g surfcad@latest'),
|
|
47
|
+
{ code: 'bad_surfcad' },
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
return mod;
|
|
51
|
+
} catch (err) {
|
|
52
|
+
if (err?.code === 'bad_surfcad') throw err;
|
|
53
|
+
const missing = err?.code === 'ERR_MODULE_NOT_FOUND'
|
|
54
|
+
|| err?.code === 'ERR_PACKAGE_PATH_NOT_EXPORTED'
|
|
55
|
+
|| /Cannot find package 'surfcad'/i.test(String(err?.message || ''));
|
|
56
|
+
if (missing) {
|
|
57
|
+
throw Object.assign(
|
|
58
|
+
new Error('Room mode needs the "surfcad" runtime package. Install it with: npm i -g surfcad (or run: npx -p surfcad -p surfcad-mcp surfcad-mcp room mcp)'),
|
|
59
|
+
{ code: 'missing_surfcad' },
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
throw err;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Connect to the room saved on this machine (`room-seat.json`) using the
|
|
68
|
+
* sandboxed `surfcad/room` headless client. Never logs or prints the seat token.
|
|
69
|
+
* @param {{
|
|
70
|
+
* env?: NodeJS.ProcessEnv,
|
|
71
|
+
* server?: string,
|
|
72
|
+
* importRoom?: () => Promise<any>,
|
|
73
|
+
* WebSocketImpl?: any,
|
|
74
|
+
* prewarm?: boolean,
|
|
75
|
+
* timeoutMs?: number,
|
|
76
|
+
* memoryMb?: number,
|
|
77
|
+
* readyTimeoutMs?: number,
|
|
78
|
+
* onRefused?: (status: number) => void,
|
|
79
|
+
* onMention?: (message: object) => void,
|
|
80
|
+
* report?: (what: string, detail?: unknown) => void,
|
|
81
|
+
* }} [opts]
|
|
82
|
+
*/
|
|
83
|
+
export async function connectRoomSession(opts = {}) {
|
|
84
|
+
checkRoomNodeVersion();
|
|
85
|
+
const env = opts.env || process.env;
|
|
86
|
+
const saved = await readRoomSeat(env);
|
|
87
|
+
if (!saved) {
|
|
88
|
+
throw Object.assign(
|
|
89
|
+
new Error('No room seat is saved on this machine. Run npx surfcad-mcp room join --room LINK first.'),
|
|
90
|
+
{ code: 'no_room_seat' },
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
if (saved.expiresAt > 0 && saved.expiresAt <= Date.now()) {
|
|
94
|
+
throw Object.assign(
|
|
95
|
+
new Error('The saved room seat has expired. Run npx surfcad-mcp room join --room LINK again.'),
|
|
96
|
+
{ code: 'seat_expired' },
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
const serverOrigin = opts.server || env.SURFCAD_AGENT_SERVER?.trim() || !saved.server
|
|
100
|
+
? resolveServerUrl({ flag: opts.server, env })
|
|
101
|
+
: saved.server;
|
|
102
|
+
|
|
103
|
+
const surfcadRoom = await loadSurfcadRoomModule({ importRoom: opts.importRoom });
|
|
104
|
+
const runner = surfcadRoom.createBuildRunner({
|
|
105
|
+
prewarm: opts.prewarm !== false,
|
|
106
|
+
...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}),
|
|
107
|
+
...(opts.memoryMb ? { memoryMb: opts.memoryMb } : {}),
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
let refusedStatus = 0;
|
|
111
|
+
let allowed = true;
|
|
112
|
+
const wsUrl = surfcadRoom.roomUrlFor(serverOrigin);
|
|
113
|
+
const createSocket = surfcadRoom.seatSocket({
|
|
114
|
+
WebSocketImpl: opts.WebSocketImpl || WebSocket,
|
|
115
|
+
token: saved.token,
|
|
116
|
+
onRefused: (status) => {
|
|
117
|
+
refusedStatus = status;
|
|
118
|
+
if (status === 401 || status === 403 || status === 409) allowed = false;
|
|
119
|
+
opts.onRefused?.(status);
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
const room = surfcadRoom.createHeadlessRoom({
|
|
124
|
+
roomKey: saved.room,
|
|
125
|
+
url: wsUrl,
|
|
126
|
+
createSocket,
|
|
127
|
+
build: (source, job) => runner.build(source, { mesh: true, ...(job?.importedModels ? { importedModels: job.importedModels } : {}) }),
|
|
128
|
+
stillAllowed: () => allowed,
|
|
129
|
+
onMention: opts.onMention || null,
|
|
130
|
+
report: opts.report || null,
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
room.start();
|
|
134
|
+
|
|
135
|
+
const waitReady = async (timeoutMs = opts.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS) => {
|
|
136
|
+
let timer = null;
|
|
137
|
+
try {
|
|
138
|
+
const ready = await Promise.race([
|
|
139
|
+
room.whenReady(),
|
|
140
|
+
new Promise((resolve) => {
|
|
141
|
+
timer = setTimeout(() => resolve('timeout'), timeoutMs);
|
|
142
|
+
}),
|
|
143
|
+
]);
|
|
144
|
+
if (ready === true) return { ok: true };
|
|
145
|
+
if (refusedStatus === 401) {
|
|
146
|
+
return { ok: false, code: 'seat_revoked', message: 'This room seat token was rejected or revoked. Run npx surfcad-mcp room join again.' };
|
|
147
|
+
}
|
|
148
|
+
if (refusedStatus === 409) {
|
|
149
|
+
return { ok: false, code: 'seat_in_use', message: 'This room seat is already connected from another process.' };
|
|
150
|
+
}
|
|
151
|
+
if (ready === 'timeout') {
|
|
152
|
+
return { ok: false, code: 'not_ready', message: 'Timed out waiting for the room state snapshot. Make sure the room host has the assembly open in SurfCAD.' };
|
|
153
|
+
}
|
|
154
|
+
const state = await room.call('room_state', {});
|
|
155
|
+
return { ok: false, code: 'not_ready', message: state?.waiting || state?.message || 'Could not sync room state.' };
|
|
156
|
+
} finally {
|
|
157
|
+
if (timer) clearTimeout(timer);
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
let closed = false;
|
|
162
|
+
const close = async () => {
|
|
163
|
+
if (closed) return;
|
|
164
|
+
closed = true;
|
|
165
|
+
try {
|
|
166
|
+
room.stop();
|
|
167
|
+
} catch { /* ignore */ }
|
|
168
|
+
await runner.close().catch(() => {});
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
return {
|
|
172
|
+
room,
|
|
173
|
+
runner,
|
|
174
|
+
surfcadRoom,
|
|
175
|
+
seat: {
|
|
176
|
+
room: saved.room,
|
|
177
|
+
server: serverOrigin,
|
|
178
|
+
label: saved.label,
|
|
179
|
+
machine: saved.machine,
|
|
180
|
+
expiresAt: saved.expiresAt,
|
|
181
|
+
},
|
|
182
|
+
waitReady,
|
|
183
|
+
callTool: (name, args = {}) => room.call(name, args),
|
|
184
|
+
close,
|
|
185
|
+
};
|
|
186
|
+
}
|