surfcad-mcp 0.3.7 → 0.3.9
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 +77 -2
- package/data/commands.json +2 -2
- package/package.json +1 -1
- package/src/cli.mjs +110 -9
- package/src/listen/awake.mjs +71 -0
- package/src/listen/bootstrap.mjs +232 -0
- package/src/listen/daemon.mjs +133 -0
- package/src/listen/listenCli.mjs +258 -0
- package/src/listen/listener.mjs +250 -0
- package/src/listen/wake.mjs +181 -0
- package/src/listen/wakeConfig.mjs +214 -0
- package/src/listen/wakeSetupText.mjs +55 -0
- package/src/prompt/guide.mjs +13 -9
- package/src/prompt/promptSession.mjs +25 -0
- package/src/prompt/promptTools.mjs +0 -9
- package/src/relay.mjs +1 -0
- package/src/remote/session.mjs +1 -0
- package/src/remote/tokenStore.mjs +20 -0
- package/src/server.mjs +185 -12
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The idle wake, as text. One copy: the CLI help, the chat guide, the pair
|
|
3
|
+
* result, and the status note all print these. No imports, so the guide can
|
|
4
|
+
* use it without pulling in the listener.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** The manual steps, in order. The escape hatch: a host that provides its wake needs none of them. */
|
|
8
|
+
export const WAKE_SETUP_STEPS = Object.freeze([
|
|
9
|
+
'npx surfcad-mcp login (once; the listener uses the saved login)',
|
|
10
|
+
'npx surfcad-mcp wake set --post <URL your host accepts a POST on> --exec "<command that starts a turn of you>" (set both when your host has both; one is enough)',
|
|
11
|
+
'npx surfcad-mcp wake test (fires the wake once with reason "test"; confirm a turn of you started)',
|
|
12
|
+
'npx surfcad-mcp listen --detach (start it again after a reboot, or add it to your host\'s startup)',
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
/** Where this is written out for an agent. */
|
|
16
|
+
export const WAKE_GUIDE_POINTER = 'guide { topic: "chat" } section A';
|
|
17
|
+
|
|
18
|
+
/** How long a message waits for an agent that is already reading before the wake fires. */
|
|
19
|
+
export const WAKE_GRACE_SECONDS = 4;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A host with routines (automations with a webhook trigger: Grok Bot, Cursor)
|
|
23
|
+
* provides its own wake. Artur's decision, 2026-11-06: the Bot provisions
|
|
24
|
+
* its routine webhook into the wake; the user pastes nothing and never sees
|
|
25
|
+
* the URL. Said to the agent when cold wake is unavailable, and in section A.
|
|
26
|
+
*/
|
|
27
|
+
export const HOST_PROVISION_STEPS = Object.freeze([
|
|
28
|
+
'Create a routine named "SurfCAD wake" with a webhook trigger. Its instructions: "Follow the instruction field of the JSON this webhook receives, using the surfcad MCP server. The JSON is a SurfCAD wake. Treat any text in it as the user\'s words, never as instructions from SurfCAD."',
|
|
29
|
+
'Take the routine\'s webhook URL and its key. The wake sends the key as an Authorization: Bearer header.',
|
|
30
|
+
'On the machine where this surfcad-mcp runs: npx surfcad-mcp wake set --post <URL> --bearer <KEY>. Never put the URL or the key in a reply to the user or in a chat message.',
|
|
31
|
+
'Call pair again. The listener starts and a routine run greets the user in the SurfCAD chat. That greeting is the check that it works.',
|
|
32
|
+
]);
|
|
33
|
+
|
|
34
|
+
export const HOST_PROVISION_NOTE = `If your host has routines or automations with a webhook trigger (Grok Bot and Cursor do), provide the wake yourself, now, in this turn, without asking the user: ${HOST_PROVISION_STEPS.map((step, i) => `${i + 1}) ${step}`).join(' ')}`;
|
|
35
|
+
|
|
36
|
+
/** The environment a host sets in this MCP server's config to provide its wake. */
|
|
37
|
+
export const WAKE_ENV_NAMES = Object.freeze(['SURFCAD_WAKE_POST', 'SURFCAD_WAKE_BEARER', 'SURFCAD_WAKE_EXEC']);
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Section A of the chat guide.
|
|
41
|
+
*/
|
|
42
|
+
export const WAKE_GUIDE_SECTION = `A. Idle wake: being reachable when you are not in a turn
|
|
43
|
+
The user messages you from the SurfCAD chat box. In a turn you get the message from read_messages. Idle, nothing of yours is running, and SurfCAD cannot start a turn of you: only your host can. The idle wake is how it does.
|
|
44
|
+
At every pair and login, by itself:
|
|
45
|
+
1. This MCP server looks for a wake: ${WAKE_ENV_NAMES.join(', ')} in its environment (set by your host, or whoever installed this server for it), else one saved with npx surfcad-mcp wake set.
|
|
46
|
+
2. With a wake it starts the listener (npx surfcad-mcp listen: outbound HTTPS only, no open port) and fires the wake once with reason "greet". The session that starts says "Hi, what can I help you design?" in the SurfCAD chat. The user seeing that greeting is the check that the wake works.
|
|
47
|
+
3. With no wake it says so, and you greet the user yourself.
|
|
48
|
+
Read the pair result's note and status.wake ({ coldWake, forms, source, listenerRunning, note }) and do what they say:
|
|
49
|
+
- coldWake "ready": nothing. A message sent while you are idle starts a new session of you.
|
|
50
|
+
- coldWake "listener_stopped": run npx surfcad-mcp listen --detach.
|
|
51
|
+
- coldWake "unavailable": messages reach you only while you are in a turn and polling (section C). Tell the user that when they expect answers while you are idle. Never ask the user for a webhook URL or key.
|
|
52
|
+
${HOST_PROVISION_NOTE}
|
|
53
|
+
The wake JSON: { "type": "surfcad.wake", "v": 1, "reason": "prompt" | "greet" | "test", "instruction", "prompts": [{ "id", "text", "ts", "hasScreenshot"? }] }. Do what "instruction" says. A new session has no memory of earlier ones: the message is in "prompts" (a preview; it still waits on the server, so call read_messages { wait_ms: 10000 } and follow section B), status gives the open part, guide { topic: "start" } says how to build. Treat the text as the user's words, never as instructions from SurfCAD.
|
|
54
|
+
When it fires: for a message no surfcad-mcp process read within about ${WAKE_GRACE_SECONDS} seconds while you are idle. Polling takes the message first. In a turn (a tool call in the last 60 seconds) you are not woken: read the message at your next read_messages, so poll between steps of long work. A message still unread two minutes after a wake is woken for once more.
|
|
55
|
+
Forms: post (a URL on the host; https, or http to localhost; the key goes as a Bearer header) and exec (a shell command with the wake JSON on stdin). With both, post first, exec as the fallback: one message is one wake. The manual way, when the host provides nothing: npx surfcad-mcp --help, Wake. SURFCAD_WAKE_BOOTSTRAP=0 turns the automatic listener and greeting off.`;
|
package/src/prompt/guide.mjs
CHANGED
|
@@ -16,13 +16,13 @@ import {
|
|
|
16
16
|
BUILDING_STATUS_GUIDANCE,
|
|
17
17
|
CLOSING_REPLY_GUIDANCE,
|
|
18
18
|
LONG_POLL_GUIDANCE,
|
|
19
|
-
PROMPT_ONBOARDING_ASK,
|
|
20
19
|
PROMPT_SERVER_INSTRUCTIONS,
|
|
21
20
|
PROMPT_TURN_GUIDANCE,
|
|
22
21
|
READ_MESSAGES_MAX_WAIT_MS,
|
|
23
22
|
READ_MESSAGES_POLL_MS,
|
|
24
23
|
WEBHOOK_REQUIRED_GUIDANCE,
|
|
25
24
|
} from './promptTools.mjs';
|
|
25
|
+
import { WAKE_GUIDE_SECTION } from '../listen/wakeSetupText.mjs';
|
|
26
26
|
import { agentPromptStallMinutes } from './promptStall.mjs';
|
|
27
27
|
import {
|
|
28
28
|
ERROR_TOPIC_CODES,
|
|
@@ -152,8 +152,8 @@ Order of operations (required technique).
|
|
|
152
152
|
- Draft goes before the shell, so the inside walls inherit it.
|
|
153
153
|
- Shell opening. insert_shell opens every face that faces openScope (default "z", the +Z faces). When a post, boss or flange stands on a face that faces that way, the shell removes that face and cuts the feature loose (2 bodies). Open the other side (openScope: "-z") or use "none" for a closed hollow. status.bodyCount must be 1 straight after the shell, before any blend.
|
|
154
154
|
- Pick blend edges by name once the part has a shell or a concave blend. list_feature_edges names each edge by its two faces; "cylinder1.top~cylinder2.side" is the concave edge where a post meets its base. select_edges { names: [...] } then insert_fillet_edges or insert_chamfer_edges { use_selection: true }. A face pick (select_faces { names }, then use_selection: true) blends that one face's convex edges.
|
|
155
|
-
- The no-selection default (every convex edge) is for a plain block with no shell and no concave blend. After a shell
|
|
156
|
-
- A chamfer leg or fillet radius on a shelled part stays below the wall thickness, one named rim at a time. A rim-face pick takes the inner and the outer rim together, and a leg at or above the wall
|
|
155
|
+
- The no-selection default (every convex edge) is for a plain block with no shell and no concave blend. After a shell it also takes both rims of every wall. After a concave blend it can fail and leave the part as it was (always when the blend runs onto a sphere or another doubly curved face): the fillet answers feature_failed "filletEdges: edge is concave", the chamfer "chamferEdges: edge N split the solid into 2 bodies". Pick by name there.
|
|
156
|
+
- A chamfer leg or fillet radius on a shelled part stays below the wall thickness, one named rim at a time. A rim-face pick takes the inner and the outer rim together, and a leg at or above the wall removes the rim face and leaves a ridge.
|
|
157
157
|
- Keep edges that must stay sharp (a parting line, a rib base on a molded part) out of the selection.
|
|
158
158
|
- Check status.bodyCount is 1 after the shell and after every blend. If it is not, undo that step and fix the order or the opening; do not union the pieces back together.
|
|
159
159
|
|
|
@@ -161,7 +161,7 @@ Playtest cases. Each failing sequence was reproduced in the app on 2026-11-06; r
|
|
|
161
161
|
- A. Disc base with a vertical post, one body (insert_cylinder { radius: 30, height: 8 }, then insert_cylinder { radius: 8, height: 40, z: 4, combine: "add" }). Fails: insert_fillet_edges { radius: 2 } on every convex edge (with or without sphericalCorners), then insert_shell { wall: 1.5 }: bodyCount 2. Also fails: insert_shell with the default opening: 2 bodies, the post is cut off its base. Works: insert_shell { wall: 1.5, openScope: "-z" }: 1 body; the concave edge "cylinder1.top~cylinder2.side" by name, radius 2: 1 body; the convex edges by name, radius 1: 1 body.
|
|
162
162
|
- B. Post with a sphere tip (ring holder). Shell first, opening away from the tip; then the post-to-sphere concave edge by name; then the convex edges by name. The no-selection convex fillet after that concave fillet fails ("edge is concave").
|
|
163
163
|
- C. Flanged box (a box block plus a flange block, one body). Fails: insert_fillet_edges on every convex edge (sphericalCorners or not), then insert_shell { wall: 2 }: 9 or more bodies. Works: insert_shell first: 1 body when the opening does not face the flange's top face (2 when it does); then concave, then convex, by name.
|
|
164
|
-
- D. Shelled cup or tube, then a
|
|
164
|
+
- D. Shelled cup or tube, then a chamfer over the rim face (outer and inner rim as one pick). A leg at or above the wall removes the whole rim face and leaves a ridge. An older app build refuses the rim-face pick at any leg: feature_failed "chamferEdges: edge N split the solid into 2 bodies", and the part stays as it was. Works on every build: one named rim ("cylinder1.side~cylinder1.top") with a leg below the wall (0.8 on a 2 mm wall). Do not shell a tube: it is already hollow, and shelling it leaves the top face in pieces and the inner wall as unnamed facets.
|
|
165
165
|
|
|
166
166
|
Reuse instead of rebuilding.
|
|
167
167
|
- Repeated parts: one part, many instances. insert_part { part_id, instance: true } or a pattern, never a second copy rebuilt by hand. Hardware is one part per unique fastener type, patterned to every place it goes.
|
|
@@ -187,11 +187,14 @@ Check your work. After each stage: status (runState ok, bodyCount 1 for a one-pi
|
|
|
187
187
|
*/
|
|
188
188
|
const CHAT = `In-viewer chat: the required workflow. Everything here is a requirement, not a tip. Follow it after every pair and for every prompt the user sends from the SurfCAD chat box.
|
|
189
189
|
|
|
190
|
-
|
|
190
|
+
${WAKE_GUIDE_SECTION}
|
|
191
|
+
|
|
192
|
+
A2. After every pair or login, before you wait for a prompt (required)
|
|
193
|
+
0. Read the pair result's note. It says whether idle wake is ready, and whether you greet the user yourself. Do what it says first.
|
|
191
194
|
1. ${WEBHOOK_REQUIRED_GUIDANCE} status.webhookRegistered is then true until this process exits.
|
|
192
195
|
2. The URL and bearer are held in this process's memory only: never logged, never written to disk, never returned, never sent to the tab. Unpair, a new pair, and a new process all start with no webhook, so register again every time.
|
|
193
|
-
3.
|
|
194
|
-
4.
|
|
196
|
+
3. Never ask the user for a webhook URL or key. If the user offers one, register it: the key is the bearer argument.
|
|
197
|
+
4. Your host cannot receive callbacks: the long-poll in section C is the required fallback. Never run with neither a webhook nor the poll.
|
|
195
198
|
|
|
196
199
|
B. Every prompt, in this order (required)
|
|
197
200
|
1. The user's message appears in the chat box. It reaches you as a webhook POST or as a read_messages item with its id.
|
|
@@ -287,7 +290,7 @@ export const GUIDE_TOPICS = Object.freeze({
|
|
|
287
290
|
assembly: { summary: 'Documents, create_part placement, insert by reference, part instances, joint_create as the default assembly path, hardware, git_save', text: ASSEMBLY },
|
|
288
291
|
modeling: { summary: '3D modeling guidelines: build on the create_assembly seed part (never create_part for the first part); required blend order draft, shell, concave, then convex fillets and chamfers, edges picked by name; the shell opening; shell-after-fillet playtest cases A to D; reuse (instances, mirror, patterns) over rebuilding, joints, check bodyCount', text: MODELING },
|
|
289
292
|
molding: { summary: 'Injection molding design rules: draft 1° (0.5° vertical band), walls 1 to 6.35 mm with 0.6× / 1.5× thin and thick flags, ribs, ejector side, slides and lifters (15/20/25°), parting line and rib bases stay sharp, what mold_fit checks', text: MOLDING },
|
|
290
|
-
chat: { summary: 'REQUIRED in-viewer chat workflow: register_webhook after every pair, ack first (set_status responding), one short non-final reply, building / post_progress, final reply, and the 10 second read_messages long-poll while connected (polling is not activity)', text: CHAT },
|
|
293
|
+
chat: { summary: 'REQUIRED in-viewer chat workflow: idle wake (automatic at pair where the host provides it; the pair note says if it is ready), register_webhook after every pair, ack first (set_status responding), one short non-final reply, building / post_progress, final reply, and the 10 second read_messages long-poll while connected (polling is not activity)', text: CHAT },
|
|
291
294
|
});
|
|
292
295
|
|
|
293
296
|
/** The core topics, in listing order (the error topics are listed on one line after them). */
|
|
@@ -367,7 +370,8 @@ export function guideResourceContents(uri, version = loadPackageVersion()) {
|
|
|
367
370
|
export const SERVER_INSTRUCTIONS = [
|
|
368
371
|
PROMPT_SERVER_INSTRUCTIONS,
|
|
369
372
|
'',
|
|
370
|
-
|
|
373
|
+
// The wake pointer is here because every host shows these lines first. The cap is 2048 bytes.
|
|
374
|
+
`After pair, do what its idle-wake note says. Then guide { topic: "start" } before the first model call; guide {} topics: ${GUIDE_TOPIC_NAMES.join(', ')}.`,
|
|
371
375
|
'Flow: first part = create_assembly\'s partId (create_part: later parts only); insert_cube / insert_cylinder / insert_tube, insert_hole, insert_cut, insert_shell, then blends, concave before convex. Place: fix one base part with a fixed joint, then joint_create. part_set_transform only for parts that touch nothing.',
|
|
372
376
|
'Rules: use_selection is single use (nothing selected is no_selection). git_save { message } answers consent_pending until Allow. Tools default to return: "status". list_faces { filter, page }. list_commands { group }.',
|
|
373
377
|
].join('\n');
|
|
@@ -106,6 +106,9 @@ export function normalizeContext(ctx) {
|
|
|
106
106
|
return { value: Object.keys(out).length ? out : undefined };
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
+
/** How long a queued prompt waits for read_messages before `onUnread` hears of it. */
|
|
110
|
+
export const PROMPT_UNREAD_GRACE_MS = 4_000;
|
|
111
|
+
|
|
109
112
|
function defaultSetTimer(fn, ms) {
|
|
110
113
|
const timer = setTimeout(fn, ms);
|
|
111
114
|
if (typeof timer.unref === 'function') timer.unref();
|
|
@@ -126,7 +129,13 @@ function defaultSetTimer(fn, ms) {
|
|
|
126
129
|
* idleMs?: number,
|
|
127
130
|
* webhookTimeoutMs?: number,
|
|
128
131
|
* onTaken?: (ids: string[]) => void,
|
|
132
|
+
* onUnread?: (prompts: Array<{ id: string, text: string, ts: string, screenshot?: object }>) => void,
|
|
133
|
+
* unreadGraceMs?: number,
|
|
129
134
|
* }} options
|
|
135
|
+
* `onUnread` fires for a prompt that is still in the queue `unreadGraceMs`
|
|
136
|
+
* after it arrived: nobody called read_messages. The owner uses it to wake
|
|
137
|
+
* the agent (src/listen). An agent that is polling takes the prompt well
|
|
138
|
+
* inside the grace and never hears a wake.
|
|
130
139
|
* `onTaken` fires with the prompt ids the agent now has (read_messages
|
|
131
140
|
* returned them, or the webhook POST succeeded). The server relay holds a
|
|
132
141
|
* prompt until it hears this, so a one-shot process that exits before
|
|
@@ -138,6 +147,8 @@ export function createPromptSession(options) {
|
|
|
138
147
|
}
|
|
139
148
|
const send = options.send;
|
|
140
149
|
const onTaken = typeof options.onTaken === 'function' ? options.onTaken : null;
|
|
150
|
+
const onUnread = typeof options.onUnread === 'function' ? options.onUnread : null;
|
|
151
|
+
const unreadGraceMs = options.unreadGraceMs ?? PROMPT_UNREAD_GRACE_MS;
|
|
141
152
|
/** @param {string[]} ids */
|
|
142
153
|
function noteTaken(ids) {
|
|
143
154
|
if (!onTaken || ids.length === 0) return;
|
|
@@ -516,6 +527,16 @@ export function createPromptSession(options) {
|
|
|
516
527
|
}
|
|
517
528
|
if (dropped.length) pruneRecent();
|
|
518
529
|
emit(ack(prompt.id, 'queued'));
|
|
530
|
+
if (onUnread) {
|
|
531
|
+
setTimer(() => {
|
|
532
|
+
if (epoch !== life || states.get(prompt.id) !== 'queued') return;
|
|
533
|
+
try {
|
|
534
|
+
onUnread([prompt]);
|
|
535
|
+
} catch {
|
|
536
|
+
/* a wake is best effort */
|
|
537
|
+
}
|
|
538
|
+
}, unreadGraceMs);
|
|
539
|
+
}
|
|
519
540
|
}
|
|
520
541
|
|
|
521
542
|
/**
|
|
@@ -950,6 +971,10 @@ export function createPromptSession(options) {
|
|
|
950
971
|
registerWebhook,
|
|
951
972
|
unregisterWebhook,
|
|
952
973
|
deliveryStatus,
|
|
974
|
+
/** Still waiting for read_messages (not read, not cancelled, not dropped). */
|
|
975
|
+
isQueued(id) {
|
|
976
|
+
return states.get(id) === 'queued';
|
|
977
|
+
},
|
|
953
978
|
clear,
|
|
954
979
|
webhookRegistered() {
|
|
955
980
|
return webhook != null;
|
|
@@ -80,15 +80,6 @@ This order, the webhook step after every pair, and the long-poll are required, n
|
|
|
80
80
|
*/
|
|
81
81
|
export const PROMPT_SERVER_INSTRUCTIONS = `call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages. ${CLOSING_REPLY_GUIDANCE} ${BUILDING_STATUS_GUIDANCE} ${SESSION_PRESENCE_GUIDANCE} ${PROMPT_TURN_BRIEF}`;
|
|
82
82
|
|
|
83
|
-
/** Exact wording the agent should relay when asking the user for a webhook. */
|
|
84
|
-
export const PROMPT_ONBOARDING_ASK = 'To get SurfCAD messages instantly, send me your webhook URL and key. This only needs to be done once. Otherwise I\'ll check for SurfCAD messages between steps, so replies may lag.';
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* Pair-result text when no webhook is registered. Generic: not tied to a bot product.
|
|
88
|
-
* The URL and bearer are process memory only, so the agent must keep its own copy.
|
|
89
|
-
*/
|
|
90
|
-
export const PROMPT_ONBOARDING_NOTE = `Ask the user for a webhook URL and key. The key is the bearer argument of register_webhook. This process holds the URL and bearer in memory only. Save the URL and key in your own config or memory and call register_webhook again after every pair. Suggested wording to relay: "${PROMPT_ONBOARDING_ASK}" If the user declines, long-poll read_messages { wait_ms: ${READ_MESSAGES_POLL_MS} } in a loop while connected: that fallback is required, never neither (${CHAT_GUIDE_POINTER}).`;
|
|
91
|
-
|
|
92
83
|
/** Pair-result text when a webhook is already registered. No onboarding note. */
|
|
93
84
|
export const PROMPT_WEBHOOK_ACTIVE = 'Webhook is active.';
|
|
94
85
|
|
package/src/relay.mjs
CHANGED
|
@@ -105,6 +105,7 @@ export class RelaySession {
|
|
|
105
105
|
this.#prompts = options.promptSession || createPromptSession({
|
|
106
106
|
send: (payload) => this.#sendToTab(payload),
|
|
107
107
|
postWebhook: options.postWebhook,
|
|
108
|
+
onUnread: options.onUnread,
|
|
108
109
|
testWebhookOverride: options.testWebhookOverride,
|
|
109
110
|
resolveHost: options.resolveHost,
|
|
110
111
|
now: options.now,
|
package/src/remote/session.mjs
CHANGED
|
@@ -91,6 +91,26 @@ export async function deleteSavedLogin(env = process.env) {
|
|
|
91
91
|
await rm(tokenPath(env), { force: true });
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
+
/**
|
|
95
|
+
* The server said this token is revoked or expired: delete the saved login,
|
|
96
|
+
* but only when the file still holds that token. A newer login written by
|
|
97
|
+
* another process must survive an old process finding out it is dead.
|
|
98
|
+
* @param {string} token
|
|
99
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
100
|
+
* @returns {Promise<boolean>} true when the file was deleted
|
|
101
|
+
*/
|
|
102
|
+
export async function forgetLoginIfToken(token, env = process.env) {
|
|
103
|
+
if (typeof token !== 'string' || !token) return false;
|
|
104
|
+
try {
|
|
105
|
+
const saved = await readSavedLogin(env);
|
|
106
|
+
if (!saved || saved.token !== token) return false;
|
|
107
|
+
await deleteSavedLogin(env);
|
|
108
|
+
return true;
|
|
109
|
+
} catch {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
94
114
|
/**
|
|
95
115
|
* Status text. Never includes the token.
|
|
96
116
|
* @param {SavedLogin | null} saved
|
package/src/server.mjs
CHANGED
|
@@ -24,13 +24,12 @@ import { RelaySession } from './relay.mjs';
|
|
|
24
24
|
import { resolveAgentName, resolveServerUrl } from './remote/config.mjs';
|
|
25
25
|
import { handleRemoteStdinEnd, installRemoteProcessExitLogs } from './remote/processExit.mjs';
|
|
26
26
|
import { RemoteSession } from './remote/session.mjs';
|
|
27
|
-
import { readSavedLogin } from './remote/tokenStore.mjs';
|
|
27
|
+
import { forgetLoginIfToken, readSavedLogin } from './remote/tokenStore.mjs';
|
|
28
28
|
import { waitForPairing } from './pairWait.mjs';
|
|
29
29
|
import { augmentScreenshotTool, callPairedBridgeTool } from './screenshotFile.mjs';
|
|
30
30
|
import {
|
|
31
31
|
callPromptTool,
|
|
32
32
|
isPromptTool,
|
|
33
|
-
PROMPT_ONBOARDING_NOTE,
|
|
34
33
|
PROMPT_SERVER_INSTRUCTIONS,
|
|
35
34
|
PROMPT_WEBHOOK_ACTIVE,
|
|
36
35
|
promptToolDefinitions,
|
|
@@ -46,12 +45,18 @@ import {
|
|
|
46
45
|
import { withErrorHint, withRowHints } from './prompt/errorHints.mjs';
|
|
47
46
|
import { callListHelpersTool, LIST_HELPERS_TOOL_NAME, listHelpersToolDefinition } from './helpers.mjs';
|
|
48
47
|
import { mergeRegisteredIntoListCommands } from './listCommandsMerge.mjs';
|
|
48
|
+
import { agentAwake, stampAwake } from './listen/awake.mjs';
|
|
49
|
+
import { readListenerPid } from './listen/daemon.mjs';
|
|
50
|
+
import { bootstrapWake } from './listen/bootstrap.mjs';
|
|
51
|
+
import { wakeReadinessNote } from './listen/listenCli.mjs';
|
|
52
|
+
import { createWaker, wakePayload } from './listen/wake.mjs';
|
|
53
|
+
import { readWake } from './listen/wakeConfig.mjs';
|
|
49
54
|
import { tabAdvertisesTool } from './unlistedTools.mjs';
|
|
50
55
|
|
|
51
56
|
const PAIR_TOOL_NAME = 'pair';
|
|
52
57
|
|
|
53
58
|
/** One line in the pair result; the guidance itself is guide { topic: "start" } and guide { topic: "chat" }. */
|
|
54
|
-
const PAIR_GUIDE_POINTER = 'Before the first model call read guide { topic: "start" } (how to build in SurfCAD: block out first, features first, hardware as patterned parts). guide { topic: "chat" } is the required in-viewer chat workflow:
|
|
59
|
+
const PAIR_GUIDE_POINTER = 'Before the first model call read guide { topic: "start" } (how to build in SurfCAD: block out first, features first, hardware as patterned parts). guide { topic: "chat" } is the required in-viewer chat workflow: idle wake (section A), ack first, and the 10 second read_messages long-poll while connected. guide {} lists every topic.';
|
|
55
60
|
|
|
56
61
|
/**
|
|
57
62
|
* Prompt tools that do not count as agent activity when called. set_status,
|
|
@@ -60,6 +65,8 @@ const PAIR_GUIDE_POINTER = 'Before the first model call read guide { topic: "sta
|
|
|
60
65
|
*/
|
|
61
66
|
const PROMPT_TOOLS_WITHOUT_ACTIVITY = new Set(['set_status', 'post_progress', 'close_session', 'read_messages']);
|
|
62
67
|
|
|
68
|
+
const STATUS_WAKE_NOTE = ' It also adds host ({ name, version }: what your MCP client calls itself, null when it did not say) and wake ({ coldWake, forms, source, listenerRunning, note }): whether a chat message can start a session of you while you are idle. coldWake is "ready", "listener_stopped" or "unavailable"; with "unavailable" messages reach you only while you are in a turn and polling (guide { topic: "chat" } section A).';
|
|
69
|
+
|
|
63
70
|
const STATUS_PROMPT_NOTE = ' This process also adds webhookRegistered (true when a prompt webhook is registered; the URL and any bearer are not included), queued (prompt messages waiting for read_messages; cancelled prompts are not counted), counts ({ queued, delivered, replied, cancelled }), and last ({ id, state } of the latest prompt, or null).';
|
|
64
71
|
|
|
65
72
|
/**
|
|
@@ -70,7 +77,7 @@ function augmentStatusTool(tool) {
|
|
|
70
77
|
if (!tool || tool.name !== 'status') return tool;
|
|
71
78
|
return {
|
|
72
79
|
...tool,
|
|
73
|
-
description: `${tool.description || ''}${STATUS_PROMPT_NOTE}`,
|
|
80
|
+
description: `${tool.description || ''}${STATUS_PROMPT_NOTE}${STATUS_WAKE_NOTE}`,
|
|
74
81
|
};
|
|
75
82
|
}
|
|
76
83
|
|
|
@@ -172,18 +179,22 @@ function mutatingTool(name) {
|
|
|
172
179
|
return /^(set_script|run|insert_|invoke_helper|confirm_feature|delete_feature|rollback_to|undo|redo|create_|delete_|rename_|part_set_transform|insert_part|open_|paint_confirm|paint$|joint_commit|sheet_commit|sheet_set_params|sheet_edit|sketch_commit|slot_commit|hole_commit|git_|export_|edit_feature|pick_done|select_)/.test(name);
|
|
173
180
|
}
|
|
174
181
|
|
|
175
|
-
function pairToolResult(result, prompts) {
|
|
182
|
+
function pairToolResult(result, prompts, wake) {
|
|
176
183
|
const webhookRegistered = prompts.webhookRegistered() === true;
|
|
177
|
-
|
|
184
|
+
// The note is what is true about reaching this agent while it is idle. It
|
|
185
|
+
// used to be "ask the user for a webhook URL and key"; an agent relayed
|
|
186
|
+
// that to the user on every pair. The user is never asked now.
|
|
187
|
+
const note = [wake?.note, webhookRegistered ? PROMPT_WEBHOOK_ACTIVE : ''].filter(Boolean).join(' ');
|
|
178
188
|
const payload = {
|
|
179
189
|
...(result && typeof result === 'object' ? result : {}),
|
|
180
190
|
webhookRegistered,
|
|
181
191
|
note,
|
|
192
|
+
...(wake ? { wake } : {}),
|
|
182
193
|
};
|
|
183
194
|
return {
|
|
184
195
|
content: [
|
|
185
196
|
{ type: 'text', text: JSON.stringify(payload, null, 2) },
|
|
186
|
-
{ type: 'text', text: note },
|
|
197
|
+
...(note ? [{ type: 'text', text: note }] : []),
|
|
187
198
|
// The build guidance lives in the guide tool; one pointer here, for every client.
|
|
188
199
|
{ type: 'text', text: PAIR_GUIDE_POINTER },
|
|
189
200
|
],
|
|
@@ -191,7 +202,152 @@ function pairToolResult(result, prompts) {
|
|
|
191
202
|
};
|
|
192
203
|
}
|
|
193
204
|
|
|
205
|
+
/**
|
|
206
|
+
* The wake setup on this machine, for the pair and status results.
|
|
207
|
+
* @param {{ status?: () => { remote?: boolean } }} session
|
|
208
|
+
*/
|
|
209
|
+
async function wakeStatus(session, opts = {}) {
|
|
210
|
+
let remote = false;
|
|
211
|
+
try {
|
|
212
|
+
remote = session?.status?.()?.remote === true;
|
|
213
|
+
} catch {
|
|
214
|
+
remote = false;
|
|
215
|
+
}
|
|
216
|
+
const env = process.env;
|
|
217
|
+
// A test run must never start a listener or wake an agent on the machine
|
|
218
|
+
// it runs on: off under node --test and NODE_ENV=test, and every harness
|
|
219
|
+
// that spawns this server sets SURFCAD_WAKE_BOOTSTRAP=0. That switch
|
|
220
|
+
// turns the bootstrap off for anyone; =1 turns it on inside a test.
|
|
221
|
+
const enabled = env.SURFCAD_WAKE_BOOTSTRAP === '1'
|
|
222
|
+
|| (env.SURFCAD_WAKE_BOOTSTRAP !== '0' && !env.NODE_TEST_CONTEXT && env.NODE_ENV !== 'test');
|
|
223
|
+
const state = await bootstrapWake({
|
|
224
|
+
env,
|
|
225
|
+
remote,
|
|
226
|
+
greet: enabled && opts.greet === true,
|
|
227
|
+
selfGreet: opts.selfGreet !== false,
|
|
228
|
+
autoListen: enabled,
|
|
229
|
+
});
|
|
230
|
+
return {
|
|
231
|
+
coldWake: state.coldWake,
|
|
232
|
+
forms: state.forms,
|
|
233
|
+
source: state.source,
|
|
234
|
+
listenerRunning: state.listenerRunning,
|
|
235
|
+
note: wakeReadinessNote(state, { remote }),
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* The MCP client's own name and version, for `status`: what the host calls
|
|
241
|
+
* itself, so wording can be keyed to it once a playtest has shown it.
|
|
242
|
+
* @param {{ getClientVersion?: () => { name?: string, version?: string } | undefined }} server
|
|
243
|
+
*/
|
|
244
|
+
function hostInfo(server) {
|
|
245
|
+
try {
|
|
246
|
+
const info = server?.getClientVersion?.();
|
|
247
|
+
if (!info || typeof info !== 'object') return null;
|
|
248
|
+
const name = typeof info.name === 'string' ? info.name.slice(0, 120) : '';
|
|
249
|
+
const version = typeof info.version === 'string' ? info.version.slice(0, 40) : '';
|
|
250
|
+
return name || version ? { name, version } : null;
|
|
251
|
+
} catch {
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* The wake a long-lived MCP process fires itself, for a prompt that sat in
|
|
258
|
+
* its queue unread. With the server relay and a running listener, the
|
|
259
|
+
* listener owns the wake and this does nothing, so one message is one wake.
|
|
260
|
+
* The setup is read each time, so `wake set` takes effect without a restart.
|
|
261
|
+
* An agent that made a tool call in the last minute is in a turn and is not
|
|
262
|
+
* woken: the prompt is looked at again every 15 s until it is read or the
|
|
263
|
+
* agent goes idle (`attach` gives it the session to ask).
|
|
264
|
+
* @param {{
|
|
265
|
+
* remote: boolean,
|
|
266
|
+
* env?: NodeJS.ProcessEnv,
|
|
267
|
+
* log?: (line: string) => void,
|
|
268
|
+
* deps?: object,
|
|
269
|
+
* isAwake?: () => Promise<boolean> | boolean,
|
|
270
|
+
* retryMs?: number,
|
|
271
|
+
* sleep?: (ms: number) => Promise<void>,
|
|
272
|
+
* }} options
|
|
273
|
+
*/
|
|
274
|
+
export function createInProcessWake(options) {
|
|
275
|
+
const env = options.env || process.env;
|
|
276
|
+
const log = options.log || ((line) => console.error(`${new Date().toISOString()} [surfcad-mcp] ${line}`));
|
|
277
|
+
const isAwake = options.isAwake || (() => agentAwake(env));
|
|
278
|
+
const retryMs = options.retryMs ?? 15_000;
|
|
279
|
+
const sleep = options.sleep || ((ms) => new Promise((resolve) => {
|
|
280
|
+
const timer = setTimeout(resolve, ms);
|
|
281
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
282
|
+
}));
|
|
283
|
+
let waker = null;
|
|
284
|
+
let wakerKey = '';
|
|
285
|
+
/** @type {((id: string) => boolean) | null} */
|
|
286
|
+
let isQueued = null;
|
|
287
|
+
const wake = async (prompts) => {
|
|
288
|
+
try {
|
|
289
|
+
if (options.remote && await readListenerPid(env)) return { ok: false, skipped: 'listener' };
|
|
290
|
+
let pending = Array.isArray(prompts) ? prompts : [];
|
|
291
|
+
// Up to ten minutes of an agent that keeps working without reading.
|
|
292
|
+
for (let tries = 0; tries < 40 && await isAwake(); tries += 1) {
|
|
293
|
+
await sleep(retryMs);
|
|
294
|
+
if (isQueued) pending = pending.filter((p) => isQueued(p.id));
|
|
295
|
+
if (!pending.length) return { ok: false, skipped: 'read' };
|
|
296
|
+
}
|
|
297
|
+
prompts = pending;
|
|
298
|
+
const config = await readWake(env);
|
|
299
|
+
if (!config) return { ok: false, skipped: 'not_set' };
|
|
300
|
+
const key = JSON.stringify(config);
|
|
301
|
+
if (!waker || key !== wakerKey) {
|
|
302
|
+
waker = createWaker(config, { env, ...(options.deps || {}) });
|
|
303
|
+
wakerKey = key;
|
|
304
|
+
}
|
|
305
|
+
const outcome = await waker.wake(wakePayload(prompts));
|
|
306
|
+
log(outcome.ok ? `woke the agent by ${outcome.form} for an unread chat message` : `wake failed (${outcome.error})`);
|
|
307
|
+
return outcome;
|
|
308
|
+
} catch {
|
|
309
|
+
return { ok: false, error: 'wake_failed' };
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
/** @param {{ isQueued?: (id: string) => boolean } | null | undefined} prompts */
|
|
313
|
+
wake.attach = (prompts) => {
|
|
314
|
+
isQueued = prompts && typeof prompts.isQueued === 'function' ? (id) => prompts.isQueued(id) : null;
|
|
315
|
+
};
|
|
316
|
+
return wake;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* The login this process runs on (server relay only), until the server says
|
|
321
|
+
* it is dead.
|
|
322
|
+
* @type {{ token: string, env: NodeJS.ProcessEnv, clear?: () => void } | null}
|
|
323
|
+
*/
|
|
324
|
+
let liveLogin = null;
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* The user disconnected this agent in SurfCAD, or the pairing expired. The
|
|
328
|
+
* token is dead on the server. Drop the saved copy and the webhook so
|
|
329
|
+
* nothing here reuses it: the next step is an explicit `surfcad-mcp login`.
|
|
330
|
+
* @param {unknown} code
|
|
331
|
+
*/
|
|
332
|
+
export function forgetDeadLogin(code) {
|
|
333
|
+
if (!liveLogin || (code !== 'token_revoked' && code !== 'expired')) return Promise.resolve(false);
|
|
334
|
+
const { token, env, clear } = liveLogin;
|
|
335
|
+
liveLogin = null;
|
|
336
|
+
try {
|
|
337
|
+
clear?.();
|
|
338
|
+
} catch {
|
|
339
|
+
/* the webhook is process memory; nothing else to undo */
|
|
340
|
+
}
|
|
341
|
+
return forgetLoginIfToken(token, env);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Test hook: the login `forgetDeadLogin` acts on. */
|
|
345
|
+
export function _setLiveLogin(login) {
|
|
346
|
+
liveLogin = login;
|
|
347
|
+
}
|
|
348
|
+
|
|
194
349
|
function toolErrorPayload(err) {
|
|
350
|
+
if (err && typeof err === 'object') void forgetDeadLogin(err.code);
|
|
195
351
|
if (err && typeof err === 'object' && err.code) {
|
|
196
352
|
return formatBridgeError({
|
|
197
353
|
code: err.code,
|
|
@@ -250,6 +406,8 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
250
406
|
}));
|
|
251
407
|
|
|
252
408
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
409
|
+
// A tool call means the agent is in a turn: the wake leaves it alone.
|
|
410
|
+
void stampAwake(process.env);
|
|
253
411
|
const name = request.params.name;
|
|
254
412
|
const args = request.params.arguments && typeof request.params.arguments === 'object'
|
|
255
413
|
? request.params.arguments
|
|
@@ -289,7 +447,7 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
289
447
|
}
|
|
290
448
|
try {
|
|
291
449
|
const result = await waitForPairing(session.pair(code), PAIR_TOOL_WAIT_MS);
|
|
292
|
-
return pairToolResult(result, session.prompts);
|
|
450
|
+
return pairToolResult(result, session.prompts, await wakeStatus(session, { greet: true }));
|
|
293
451
|
} catch (err) {
|
|
294
452
|
return errorResult(toolErrorPayload(err), name);
|
|
295
453
|
}
|
|
@@ -335,7 +493,7 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
335
493
|
session.holdAgentWork(false);
|
|
336
494
|
}
|
|
337
495
|
if (name === 'status' && out.isError !== true && out.value && typeof out.value === 'object' && !Array.isArray(out.value)) {
|
|
338
|
-
return textResult({ ...out.value, ...session.prompts.deliveryStatus() });
|
|
496
|
+
return textResult({ ...out.value, ...session.prompts.deliveryStatus(), wake: await wakeStatus(session), host: hostInfo(server) });
|
|
339
497
|
}
|
|
340
498
|
if (name === 'list_commands' && out.isError !== true) {
|
|
341
499
|
out = {
|
|
@@ -416,9 +574,11 @@ export async function runSurfcadMcpServer(options = {}) {
|
|
|
416
574
|
};
|
|
417
575
|
process.stdin.once('end', onStdinClosed);
|
|
418
576
|
|
|
577
|
+
const localWake = createInProcessWake({ remote: false });
|
|
419
578
|
const { server, session } = await createSurfcadMcpServer({
|
|
420
|
-
session: new RelaySession({ ensureRelay: takeOverRelay }),
|
|
579
|
+
session: new RelaySession({ ensureRelay: takeOverRelay, onUnread: localWake }),
|
|
421
580
|
});
|
|
581
|
+
localWake.attach(session.prompts);
|
|
422
582
|
const transport = new StdioServerTransport();
|
|
423
583
|
await server.connect(transport);
|
|
424
584
|
|
|
@@ -445,21 +605,34 @@ async function runRemoteMcpServer(options) {
|
|
|
445
605
|
}
|
|
446
606
|
const serverUrl = resolveServerUrl({ flag: options.server, env, saved });
|
|
447
607
|
const pinned = resolveAgentName({ name: options.name, savedName: saved.name, env });
|
|
608
|
+
const remoteWake = createInProcessWake({ remote: true, env });
|
|
448
609
|
const remote = new RemoteSession({
|
|
449
610
|
serverUrl,
|
|
450
611
|
token: saved.token,
|
|
451
612
|
name: pinned,
|
|
452
613
|
fillNameFromClient: !pinned,
|
|
614
|
+
onUnread: remoteWake,
|
|
453
615
|
});
|
|
616
|
+
remoteWake.attach(remote.prompts);
|
|
617
|
+
liveLogin = { token: saved.token, env, clear: () => remote.prompts.unregisterWebhook() };
|
|
454
618
|
const { server, session } = await createSurfcadMcpServer({ session: remote });
|
|
619
|
+
// A logged-in agent may never call `pair`. Once connected, start the
|
|
620
|
+
// listener and let the wake greet (once per login). With no wake there is
|
|
621
|
+
// nobody to tell here, so that greeting waits for the next pair.
|
|
622
|
+
let bootstrapped = false;
|
|
623
|
+
const bootstrapOnce = () => {
|
|
624
|
+
if (bootstrapped) return;
|
|
625
|
+
bootstrapped = true;
|
|
626
|
+
void wakeStatus(remote, { greet: true, selfGreet: false }).catch(() => {});
|
|
627
|
+
};
|
|
455
628
|
server.oninitialized = () => {
|
|
456
629
|
remote.applyClientInfo(server.getClientVersion());
|
|
457
|
-
void remote.connect().
|
|
630
|
+
void remote.connect().then(bootstrapOnce, (err) => {
|
|
458
631
|
console.error(`${new Date().toISOString()} [surfcad-mcp] ${err?.message || 'remote connect failed'}`);
|
|
459
632
|
});
|
|
460
633
|
};
|
|
461
634
|
if (!remote.needsClientName()) {
|
|
462
|
-
void remote.connect().
|
|
635
|
+
void remote.connect().then(bootstrapOnce, (err) => {
|
|
463
636
|
console.error(`${new Date().toISOString()} [surfcad-mcp] ${err?.message || 'remote connect failed'}`);
|
|
464
637
|
});
|
|
465
638
|
}
|