surfcad-mcp 0.3.7 → 0.3.8

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.
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Saved wake actions: how this machine starts an agent turn when the user
3
+ * sends a chat message from SurfCAD and no agent process is reading.
4
+ *
5
+ * Two forms, either or both:
6
+ * post POST the wake JSON to a URL the agent's host listens on.
7
+ * exec run a local command with the wake JSON on stdin.
8
+ *
9
+ * The file sits next to the saved login, mode 0600 in a 0700 directory. It
10
+ * is written only by `surfcad-mcp wake set` on this machine. Nothing a
11
+ * server, a tab, or a chat message sends can change it, and no part of a
12
+ * message is ever put into the command line.
13
+ */
14
+
15
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
16
+ import { join } from 'node:path';
17
+ import { configDir } from '../remote/config.mjs';
18
+
19
+ export const WAKE_EXEC_MAX_CHARS = 4000;
20
+ export const WAKE_BEARER_MAX_CHARS = 512;
21
+
22
+ /**
23
+ * @typedef {{ url: string, bearer?: string }} WakePost
24
+ * @typedef {{ post?: WakePost, exec?: string, savedAt?: string }} WakeConfig
25
+ */
26
+
27
+ /**
28
+ * @param {NodeJS.ProcessEnv} [env]
29
+ */
30
+ export function wakePath(env = process.env) {
31
+ return join(configDir(env), 'wake.json');
32
+ }
33
+
34
+ /**
35
+ * @param {string} hostname
36
+ */
37
+ export function isLoopbackHost(hostname) {
38
+ const host = String(hostname || '').toLowerCase().replace(/^\[|\]$/g, '');
39
+ if (host === 'localhost' || host === '::1') return true;
40
+ return /^127(?:\.\d{1,3}){3}$/.test(host);
41
+ }
42
+
43
+ function bad(message) {
44
+ return Object.assign(new Error(message), { code: 'bad_args' });
45
+ }
46
+
47
+ /**
48
+ * A wake URL is https, or cleartext http to this machine only. The listener
49
+ * runs beside the agent's host, so localhost is the common case; that is
50
+ * the difference from register_webhook, which refuses it.
51
+ * @param {unknown} input
52
+ * @returns {string}
53
+ */
54
+ export function normalizeWakeUrl(input) {
55
+ const text = typeof input === 'string' ? input.trim() : '';
56
+ if (!text) throw bad('--post needs a URL.');
57
+ /** @type {URL} */
58
+ let url;
59
+ try {
60
+ url = new URL(text);
61
+ } catch {
62
+ throw bad('--post needs a full URL, for example http://127.0.0.1:8644/wake.');
63
+ }
64
+ if (url.username || url.password) {
65
+ throw bad('Do not put a user name or password in the wake URL. Use --bearer.');
66
+ }
67
+ if (url.protocol === 'https:') return url.toString();
68
+ if (url.protocol === 'http:' && isLoopbackHost(url.hostname)) return url.toString();
69
+ throw bad('The wake URL must be https, or http to localhost, 127.0.0.1 or ::1.');
70
+ }
71
+
72
+ /**
73
+ * @param {unknown} input
74
+ * @returns {string}
75
+ */
76
+ export function normalizeWakeBearer(input) {
77
+ const text = typeof input === 'string' ? input.trim() : '';
78
+ if (!text) return '';
79
+ if (text.length > WAKE_BEARER_MAX_CHARS || /[\r\n]/.test(text)) {
80
+ throw bad(`--bearer must be one line of at most ${WAKE_BEARER_MAX_CHARS} characters.`);
81
+ }
82
+ return text;
83
+ }
84
+
85
+ /**
86
+ * @param {unknown} input
87
+ * @returns {string}
88
+ */
89
+ export function normalizeWakeExec(input) {
90
+ const text = typeof input === 'string' ? input.trim() : '';
91
+ if (!text) throw bad('--exec needs a command.');
92
+ if (text.length > WAKE_EXEC_MAX_CHARS || text.includes('\0')) {
93
+ throw bad(`--exec must be at most ${WAKE_EXEC_MAX_CHARS} characters.`);
94
+ }
95
+ return text;
96
+ }
97
+
98
+ /**
99
+ * @param {unknown} raw
100
+ * @returns {WakeConfig | null} null when no usable form is in it
101
+ */
102
+ export function normalizeWake(raw) {
103
+ if (!raw || typeof raw !== 'object') return null;
104
+ const record = /** @type {Record<string, any>} */ (raw);
105
+ /** @type {WakeConfig} */
106
+ const out = {};
107
+ if (record.post && typeof record.post === 'object' && typeof record.post.url === 'string') {
108
+ try {
109
+ const url = normalizeWakeUrl(record.post.url);
110
+ const bearer = normalizeWakeBearer(record.post.bearer);
111
+ out.post = bearer ? { url, bearer } : { url };
112
+ } catch {
113
+ /* a hand-edited bad URL is no wake, not a crash */
114
+ }
115
+ }
116
+ if (typeof record.exec === 'string') {
117
+ try {
118
+ out.exec = normalizeWakeExec(record.exec);
119
+ } catch {
120
+ /* same */
121
+ }
122
+ }
123
+ if (!out.post && !out.exec) return null;
124
+ if (typeof record.savedAt === 'string') out.savedAt = record.savedAt;
125
+ return out;
126
+ }
127
+
128
+ /**
129
+ * @param {NodeJS.ProcessEnv} [env]
130
+ * @returns {Promise<WakeConfig | null>}
131
+ */
132
+ export async function readWake(env = process.env) {
133
+ /** @type {string} */
134
+ let text;
135
+ try {
136
+ text = await readFile(wakePath(env), 'utf8');
137
+ } catch (err) {
138
+ if (err && typeof err === 'object' && err.code === 'ENOENT') return null;
139
+ throw Object.assign(new Error('The saved wake setup could not be read.'), { code: 'bad_wake_file' });
140
+ }
141
+ try {
142
+ return normalizeWake(JSON.parse(text));
143
+ } catch {
144
+ throw Object.assign(new Error('The saved wake setup could not be read.'), { code: 'bad_wake_file' });
145
+ }
146
+ }
147
+
148
+ /**
149
+ * @param {WakeConfig} config
150
+ * @param {NodeJS.ProcessEnv} [env]
151
+ * @returns {Promise<WakeConfig>}
152
+ */
153
+ export async function saveWake(config, env = process.env) {
154
+ const clean = normalizeWake(config);
155
+ if (!clean) throw bad('Pass --post URL, --exec COMMAND, or both.');
156
+ clean.savedAt = new Date().toISOString();
157
+ const dir = configDir(env);
158
+ await mkdir(dir, { recursive: true, mode: 0o700 });
159
+ await chmod(dir, 0o700);
160
+ const path = wakePath(env);
161
+ const tmp = join(dir, `.wake-${process.pid}-${Date.now()}.tmp`);
162
+ try {
163
+ await writeFile(tmp, `${JSON.stringify(clean)}\n`, { mode: 0o600, flag: 'wx' });
164
+ await chmod(tmp, 0o600);
165
+ await rename(tmp, path);
166
+ await chmod(path, 0o600);
167
+ } catch {
168
+ await rm(tmp, { force: true });
169
+ throw Object.assign(new Error('Could not save the wake setup.'), { code: 'save_failed' });
170
+ }
171
+ return clean;
172
+ }
173
+
174
+ /**
175
+ * @param {NodeJS.ProcessEnv} [env]
176
+ */
177
+ export async function clearWake(env = process.env) {
178
+ await rm(wakePath(env), { force: true });
179
+ }
180
+
181
+ /** Which forms are set, in the order they are tried. */
182
+ export function wakeForms(config) {
183
+ const forms = [];
184
+ if (config?.post) forms.push('post');
185
+ if (config?.exec) forms.push('exec');
186
+ return forms;
187
+ }
188
+
189
+ /**
190
+ * Status text. Never includes the bearer.
191
+ * @param {WakeConfig | null} config
192
+ */
193
+ export function formatWake(config) {
194
+ if (!config) return 'wake: not set\n';
195
+ const lines = [];
196
+ if (config.post) lines.push(`wake post: ${config.post.url}${config.post.bearer ? ' (with a bearer key)' : ''}`);
197
+ if (config.exec) lines.push(`wake exec: ${config.exec}`);
198
+ return `${lines.join('\n')}\n`;
199
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The wake setup, 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 install steps, in order. */
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 the steps are 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
+ * Section A of the chat guide.
23
+ */
24
+ export const WAKE_GUIDE_SECTION = `A. Once, when you install this MCP server: set up the wake (required)
25
+ The user messages you from the SurfCAD chat box. While you are in a turn you get the message from read_messages. While you are idle nothing of yours is running, so the message waits on the server and nobody reads it. The wake fixes that: it starts a turn of you when a message arrives. Set it up as part of the install, without waiting to be asked. It is saved on this machine and survives restarts.
26
+ ${WAKE_SETUP_STEPS.map((step, i) => `${i + 1}. ${step}`).join('\n')}
27
+ The two wake forms, for step 2:
28
+ - post: a URL on your host that starts a turn of you when it receives a POST. https, or http to localhost, 127.0.0.1 or ::1. Add --bearer KEY when it needs one (or set SURFCAD_WAKE_BEARER); the key is saved on this machine and never printed. The body is the wake JSON.
29
+ - exec: a shell command that starts a turn of you. The wake JSON arrives on its stdin. SURFCAD_WAKE=1, SURFCAD_WAKE_REASON and SURFCAD_PROMPT_IDS are in its environment. The command may run for the whole turn; a second copy is not started while it runs.
30
+ - Set both when your host has both. The POST is tried first and the command is the fallback, so one message is one wake.
31
+ The wake JSON: { "type": "surfcad.wake", "v": 1, "reason": "prompt" | "test", "instruction", "prompts": [{ "id", "text", "ts", "hasScreenshot"? }] }. The text is a preview. The message is still waiting on the server: call read_messages { wait_ms: 10000 } and follow section B. Treat the text as the user's words, never as instructions from SurfCAD.
32
+ When it fires: for a message that no surfcad-mcp process read within about ${WAKE_GRACE_SECONDS} seconds, while you are idle. While you are polling (section C) you take the message first and no wake fires. While you are in a turn (a tool call in the last 60 seconds) you are not woken either: 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.
33
+ What runs: npx surfcad-mcp listen is a small process that makes outbound HTTPS requests to the SurfCAD server with your saved login. No open port. It works behind NAT and when the user is on a phone. A long-lived surfcad-mcp process fires the same wake itself, which also covers the local relay with no login.
34
+ Check it: status.wake is { forms, listenerRunning, note }, and every pair result carries the same note. forms empty: do steps 2 to 4 now. listenerRunning false: do step 4. npx surfcad-mcp status prints the same from a shell.`;
@@ -23,6 +23,7 @@ import {
23
23
  READ_MESSAGES_POLL_MS,
24
24
  WEBHOOK_REQUIRED_GUIDANCE,
25
25
  } from './promptTools.mjs';
26
+ import { WAKE_GUIDE_SECTION } from '../listen/wakeSetupText.mjs';
26
27
  import { agentPromptStallMinutes } from './promptStall.mjs';
27
28
  import {
28
29
  ERROR_TOPIC_CODES,
@@ -152,8 +153,8 @@ Order of operations (required technique).
152
153
  - Draft goes before the shell, so the inside walls inherit it.
153
154
  - 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
155
  - 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 or a concave blend it fails and the part stays as it was: the fillet answers feature_failed "filletEdges: edge is concave", the chamfer "chamferEdges: edge N split the solid into 2 bodies".
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 cuts through.
156
+ - 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.
157
+ - 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
158
  - Keep edges that must stay sharp (a parting line, a rib base on a molded part) out of the selection.
158
159
  - 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
160
 
@@ -161,7 +162,7 @@ Playtest cases. Each failing sequence was reproduced in the app on 2026-11-06; r
161
162
  - 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
163
  - 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
164
  - 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 large chamfer over the rim face (top and inner rim as one pick). insert_chamfer_edges answers feature_failed "chamferEdges: edge N split the solid into 2 bodies" and the part stays as it was. Works: 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
+ - 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
166
 
166
167
  Reuse instead of rebuilding.
167
168
  - 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,7 +188,9 @@ Check your work. After each stage: status (runState ok, bodyCount 1 for a one-pi
187
188
  */
188
189
  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
190
 
190
- A. After every pair or login, before you wait for a prompt (required)
191
+ ${WAKE_GUIDE_SECTION}
192
+
193
+ A2. After every pair or login, before you wait for a prompt (required)
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
196
  3. No webhook URL yet: ask the user once, in these words: "${PROMPT_ONBOARDING_ASK}"
@@ -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: the wake setup at install (so the user can message you while you are idle), 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
- `SurfCAD quick start. Pair, then call guide { topic: "start" } before the first model call; guide {} lists the topics (${GUIDE_TOPIC_NAMES.join(', ')}).`,
373
+ // The wake pointer is here because every host shows these lines first. The cap is 2048 bytes.
374
+ `Install: set up the wake, guide chat A. Pair, 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;
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,
@@ -211,6 +211,7 @@ export class RemoteSession {
211
211
  .then(() => this.#sendToTab({ type: PAIR_MSG.AGENT_PROMPT_TAKEN, v: 1, ids }))
212
212
  .catch(() => { /* advisory; the next hello or pull offers them again */ });
213
213
  },
214
+ onUnread: options.onUnread,
214
215
  });
215
216
  }
216
217
 
package/src/server.mjs CHANGED
@@ -46,12 +46,17 @@ import {
46
46
  import { withErrorHint, withRowHints } from './prompt/errorHints.mjs';
47
47
  import { callListHelpersTool, LIST_HELPERS_TOOL_NAME, listHelpersToolDefinition } from './helpers.mjs';
48
48
  import { mergeRegisteredIntoListCommands } from './listCommandsMerge.mjs';
49
+ import { agentAwake, stampAwake } from './listen/awake.mjs';
50
+ import { readListenerPid } from './listen/daemon.mjs';
51
+ import { wakeSetupNote, wakeSetupState } 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: register_webhook after every pair, ack first, and the 10 second read_messages long-poll while connected. guide {} lists every topic.';
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: the wake setup at install, 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 wake ({ forms, listenerRunning, note }): how this machine starts a turn of you when the user sends a chat message while you are idle. forms is empty until you run the wake setup (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,21 @@ 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
  const note = webhookRegistered ? PROMPT_WEBHOOK_ACTIVE : PROMPT_ONBOARDING_NOTE;
178
185
  const payload = {
179
186
  ...(result && typeof result === 'object' ? result : {}),
180
187
  webhookRegistered,
181
188
  note,
189
+ ...(wake ? { wake } : {}),
182
190
  };
183
191
  return {
184
192
  content: [
185
193
  { type: 'text', text: JSON.stringify(payload, null, 2) },
186
194
  { type: 'text', text: note },
195
+ // The install step an agent must not skip: without it the user cannot reach an idle agent.
196
+ ...(wake?.note ? [{ type: 'text', text: wake.note }] : []),
187
197
  // The build guidance lives in the guide tool; one pointer here, for every client.
188
198
  { type: 'text', text: PAIR_GUIDE_POINTER },
189
199
  ],
@@ -191,6 +201,84 @@ function pairToolResult(result, prompts) {
191
201
  };
192
202
  }
193
203
 
204
+ /**
205
+ * The wake setup on this machine, for the pair and status results.
206
+ * @param {{ status?: () => { remote?: boolean } }} session
207
+ */
208
+ async function wakeStatus(session) {
209
+ const state = await wakeSetupState(process.env);
210
+ let remote = false;
211
+ try {
212
+ remote = session?.status?.()?.remote === true;
213
+ } catch {
214
+ remote = false;
215
+ }
216
+ return { ...state, note: wakeSetupNote(state, { remote }) };
217
+ }
218
+
219
+ /**
220
+ * The wake a long-lived MCP process fires itself, for a prompt that sat in
221
+ * its queue unread. With the server relay and a running listener, the
222
+ * listener owns the wake and this does nothing, so one message is one wake.
223
+ * The setup is read each time, so `wake set` takes effect without a restart.
224
+ * An agent that made a tool call in the last minute is in a turn and is not
225
+ * woken: the prompt is looked at again every 15 s until it is read or the
226
+ * agent goes idle (`attach` gives it the session to ask).
227
+ * @param {{
228
+ * remote: boolean,
229
+ * env?: NodeJS.ProcessEnv,
230
+ * log?: (line: string) => void,
231
+ * deps?: object,
232
+ * isAwake?: () => Promise<boolean> | boolean,
233
+ * retryMs?: number,
234
+ * sleep?: (ms: number) => Promise<void>,
235
+ * }} options
236
+ */
237
+ export function createInProcessWake(options) {
238
+ const env = options.env || process.env;
239
+ const log = options.log || ((line) => console.error(`${new Date().toISOString()} [surfcad-mcp] ${line}`));
240
+ const isAwake = options.isAwake || (() => agentAwake(env));
241
+ const retryMs = options.retryMs ?? 15_000;
242
+ const sleep = options.sleep || ((ms) => new Promise((resolve) => {
243
+ const timer = setTimeout(resolve, ms);
244
+ if (typeof timer.unref === 'function') timer.unref();
245
+ }));
246
+ let waker = null;
247
+ let wakerKey = '';
248
+ /** @type {((id: string) => boolean) | null} */
249
+ let isQueued = null;
250
+ const wake = async (prompts) => {
251
+ try {
252
+ if (options.remote && await readListenerPid(env)) return { ok: false, skipped: 'listener' };
253
+ let pending = Array.isArray(prompts) ? prompts : [];
254
+ // Up to ten minutes of an agent that keeps working without reading.
255
+ for (let tries = 0; tries < 40 && await isAwake(); tries += 1) {
256
+ await sleep(retryMs);
257
+ if (isQueued) pending = pending.filter((p) => isQueued(p.id));
258
+ if (!pending.length) return { ok: false, skipped: 'read' };
259
+ }
260
+ prompts = pending;
261
+ const config = await readWake(env);
262
+ if (!config) return { ok: false, skipped: 'not_set' };
263
+ const key = JSON.stringify(config);
264
+ if (!waker || key !== wakerKey) {
265
+ waker = createWaker(config, { env, ...(options.deps || {}) });
266
+ wakerKey = key;
267
+ }
268
+ const outcome = await waker.wake(wakePayload(prompts));
269
+ log(outcome.ok ? `woke the agent by ${outcome.form} for an unread chat message` : `wake failed (${outcome.error})`);
270
+ return outcome;
271
+ } catch {
272
+ return { ok: false, error: 'wake_failed' };
273
+ }
274
+ };
275
+ /** @param {{ isQueued?: (id: string) => boolean } | null | undefined} prompts */
276
+ wake.attach = (prompts) => {
277
+ isQueued = prompts && typeof prompts.isQueued === 'function' ? (id) => prompts.isQueued(id) : null;
278
+ };
279
+ return wake;
280
+ }
281
+
194
282
  function toolErrorPayload(err) {
195
283
  if (err && typeof err === 'object' && err.code) {
196
284
  return formatBridgeError({
@@ -250,6 +338,8 @@ export async function createSurfcadMcpServer(options = {}) {
250
338
  }));
251
339
 
252
340
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
341
+ // A tool call means the agent is in a turn: the wake leaves it alone.
342
+ void stampAwake(process.env);
253
343
  const name = request.params.name;
254
344
  const args = request.params.arguments && typeof request.params.arguments === 'object'
255
345
  ? request.params.arguments
@@ -289,7 +379,7 @@ export async function createSurfcadMcpServer(options = {}) {
289
379
  }
290
380
  try {
291
381
  const result = await waitForPairing(session.pair(code), PAIR_TOOL_WAIT_MS);
292
- return pairToolResult(result, session.prompts);
382
+ return pairToolResult(result, session.prompts, await wakeStatus(session));
293
383
  } catch (err) {
294
384
  return errorResult(toolErrorPayload(err), name);
295
385
  }
@@ -335,7 +425,7 @@ export async function createSurfcadMcpServer(options = {}) {
335
425
  session.holdAgentWork(false);
336
426
  }
337
427
  if (name === 'status' && out.isError !== true && out.value && typeof out.value === 'object' && !Array.isArray(out.value)) {
338
- return textResult({ ...out.value, ...session.prompts.deliveryStatus() });
428
+ return textResult({ ...out.value, ...session.prompts.deliveryStatus(), wake: await wakeStatus(session) });
339
429
  }
340
430
  if (name === 'list_commands' && out.isError !== true) {
341
431
  out = {
@@ -416,9 +506,11 @@ export async function runSurfcadMcpServer(options = {}) {
416
506
  };
417
507
  process.stdin.once('end', onStdinClosed);
418
508
 
509
+ const localWake = createInProcessWake({ remote: false });
419
510
  const { server, session } = await createSurfcadMcpServer({
420
- session: new RelaySession({ ensureRelay: takeOverRelay }),
511
+ session: new RelaySession({ ensureRelay: takeOverRelay, onUnread: localWake }),
421
512
  });
513
+ localWake.attach(session.prompts);
422
514
  const transport = new StdioServerTransport();
423
515
  await server.connect(transport);
424
516
 
@@ -445,12 +537,15 @@ async function runRemoteMcpServer(options) {
445
537
  }
446
538
  const serverUrl = resolveServerUrl({ flag: options.server, env, saved });
447
539
  const pinned = resolveAgentName({ name: options.name, savedName: saved.name, env });
540
+ const remoteWake = createInProcessWake({ remote: true, env });
448
541
  const remote = new RemoteSession({
449
542
  serverUrl,
450
543
  token: saved.token,
451
544
  name: pinned,
452
545
  fillNameFromClient: !pinned,
546
+ onUnread: remoteWake,
453
547
  });
548
+ remoteWake.attach(remote.prompts);
454
549
  const { server, session } = await createSurfcadMcpServer({ session: remote });
455
550
  server.oninitialized = () => {
456
551
  remote.applyClientInfo(server.getClientVersion());