surfcad-mcp 0.3.6 → 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.
- package/README.md +53 -8
- package/data/commands.json +48 -12
- package/data/helpers.json +1 -1
- package/package.json +1 -1
- package/src/cli.mjs +98 -9
- package/src/listen/awake.mjs +71 -0
- package/src/listen/daemon.mjs +128 -0
- package/src/listen/listenCli.mjs +219 -0
- package/src/listen/listener.mjs +250 -0
- package/src/listen/wake.mjs +167 -0
- package/src/listen/wakeConfig.mjs +199 -0
- package/src/listen/wakeSetupText.mjs +34 -0
- package/src/prompt/buildGuidance.mjs +2 -2
- package/src/prompt/errorHints.mjs +2 -1
- package/src/prompt/guide.mjs +83 -19
- package/src/prompt/promptSession.mjs +40 -7
- package/src/prompt/promptStall.mjs +3 -2
- package/src/prompt/promptTools.mjs +50 -7
- package/src/relay.mjs +1 -0
- package/src/remote/session.mjs +1 -0
- package/src/server.mjs +113 -8
|
@@ -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;
|
|
@@ -264,9 +275,10 @@ export function createPromptSession(options) {
|
|
|
264
275
|
}
|
|
265
276
|
|
|
266
277
|
/**
|
|
267
|
-
* The agent did something that is not a state change (another
|
|
268
|
-
* a
|
|
269
|
-
* own deadline restarts too. A stall notice is replaced by the
|
|
278
|
+
* The agent did something that is not a state change (another bridge
|
|
279
|
+
* tool call, a partial reply). Restart the idle window and tell the tab,
|
|
280
|
+
* so its own deadline restarts too. A stall notice is replaced by the
|
|
281
|
+
* live state. A read_messages poll never comes here.
|
|
270
282
|
*/
|
|
271
283
|
function noteActivity() {
|
|
272
284
|
if (lastId && states.get(lastId) === 'cancelled') return;
|
|
@@ -515,6 +527,16 @@ export function createPromptSession(options) {
|
|
|
515
527
|
}
|
|
516
528
|
if (dropped.length) pruneRecent();
|
|
517
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
|
+
}
|
|
518
540
|
}
|
|
519
541
|
|
|
520
542
|
/**
|
|
@@ -666,7 +688,9 @@ export function createPromptSession(options) {
|
|
|
666
688
|
? { data: item.screenshot.data, mimeType: 'image/png' }
|
|
667
689
|
: null);
|
|
668
690
|
}
|
|
669
|
-
|
|
691
|
+
// A poll is not activity. read_messages (with or without wait_ms) must
|
|
692
|
+
// not restart the stall window or tell the tab the agent is active: an
|
|
693
|
+
// agent that only long-polls would otherwise never stall.
|
|
670
694
|
noteTaken(takenIds);
|
|
671
695
|
return { messages, images };
|
|
672
696
|
}
|
|
@@ -828,10 +852,15 @@ export function createPromptSession(options) {
|
|
|
828
852
|
throw Object.assign(new Error('text must be at most 500 characters'), { code: 'bad_args' });
|
|
829
853
|
}
|
|
830
854
|
const sent = emit({ type: PAIR_MSG.AGENT_PROGRESS, v: 1, working: true }, { required: true });
|
|
831
|
-
|
|
832
|
-
|
|
855
|
+
// Progress is the agent saying it is still at work: with a phase open
|
|
856
|
+
// it restarts the stall window, like a tool call or a partial reply.
|
|
857
|
+
const finish = () => {
|
|
858
|
+
noteActivity();
|
|
859
|
+
return { ok: true, working: true };
|
|
860
|
+
};
|
|
861
|
+
if (sent && typeof sent.then === 'function') return sent.then(finish);
|
|
833
862
|
if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
|
|
834
|
-
return
|
|
863
|
+
return finish();
|
|
835
864
|
}
|
|
836
865
|
|
|
837
866
|
/**
|
|
@@ -942,6 +971,10 @@ export function createPromptSession(options) {
|
|
|
942
971
|
registerWebhook,
|
|
943
972
|
unregisterWebhook,
|
|
944
973
|
deliveryStatus,
|
|
974
|
+
/** Still waiting for read_messages (not read, not cancelled, not dropped). */
|
|
975
|
+
isQueued(id) {
|
|
976
|
+
return states.get(id) === 'queued';
|
|
977
|
+
},
|
|
945
978
|
clear,
|
|
946
979
|
webhookRegistered() {
|
|
947
980
|
return webhook != null;
|
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* No agent activity for this long is a stall, not a silent return to idle.
|
|
3
3
|
* The in-viewer prompt and the MCP prompt session share this one window.
|
|
4
4
|
* It applies to both typing (the pane is responding) and working (the
|
|
5
|
-
* agent is building). Relayed tool calls, status,
|
|
6
|
-
*
|
|
5
|
+
* agent is building). Relayed tool calls, status, post_progress, and
|
|
6
|
+
* replies start it over. A read_messages poll does not: an agent that only
|
|
7
|
+
* long-polls is waiting, not working.
|
|
7
8
|
*/
|
|
8
9
|
export const AGENT_PROMPT_STALL_MS = 15 * 60 * 1000;
|
|
9
10
|
|
|
@@ -11,6 +11,29 @@ const USER_CONTENT = `${USER_CONTENT_NOTICE} Agent writes still go through the e
|
|
|
11
11
|
/** read_messages { wait_ms } cap: long enough to skip idle polls, short enough for a host tool timeout. */
|
|
12
12
|
export const READ_MESSAGES_MAX_WAIT_MS = 25_000;
|
|
13
13
|
|
|
14
|
+
/**
|
|
15
|
+
* The required long-poll cycle while connected: read_messages { wait_ms }
|
|
16
|
+
* with this value, called again as soon as it returns. Under the cap above,
|
|
17
|
+
* so a host with a short tool timeout can still run it.
|
|
18
|
+
*/
|
|
19
|
+
export const READ_MESSAGES_POLL_MS = 10_000;
|
|
20
|
+
|
|
21
|
+
/** Where the whole required in-viewer chat workflow lives. */
|
|
22
|
+
export const CHAT_GUIDE_POINTER = 'guide { topic: "chat" }';
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The required fallback (and safety net) while connected. Shared by the
|
|
26
|
+
* turn guidance, the chat topic, and the read_messages and
|
|
27
|
+
* register_webhook descriptions.
|
|
28
|
+
*/
|
|
29
|
+
export const LONG_POLL_GUIDANCE = `While connected, long-poll read_messages { wait_ms: ${READ_MESSAGES_POLL_MS} } in a loop (call it again as soon as it returns): required whenever no webhook wakes you, and the safety net when one is registered. Polling is not activity: it does not restart the stall window or the tab's working state.`;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Webhook mode is a requirement, not a hint. The URL and bearer are process
|
|
33
|
+
* memory only, so every pair (and every fresh process) starts without one.
|
|
34
|
+
*/
|
|
35
|
+
export const WEBHOOK_REQUIRED_GUIDANCE = 'Required when your host can receive HTTPS callbacks: call register_webhook right after every successful pair or login, before you wait for a prompt, and again in every new process (a fresh surfcad-mcp per tool call starts with no webhook). Keep the URL and bearer in your host config.';
|
|
36
|
+
|
|
14
37
|
/**
|
|
15
38
|
* Closing reply for a task that started in the in-viewer prompt pane.
|
|
16
39
|
* The same sentence is the second sentence of the MCP initialize
|
|
@@ -31,11 +54,31 @@ export const BUILDING_STATUS_GUIDANCE = 'Call set_status { state: "building" } o
|
|
|
31
54
|
*/
|
|
32
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. Call close_session when done, never on exit.';
|
|
33
56
|
|
|
57
|
+
/**
|
|
58
|
+
* Short form of the in-viewer turn, for the initialize instructions (hosts
|
|
59
|
+
* truncate past 2 KB). The full order is PROMPT_TURN_GUIDANCE.
|
|
60
|
+
*/
|
|
61
|
+
export const PROMPT_TURN_BRIEF = `Required after every in-viewer prompt (full order: ${CHAT_GUIDE_POINTER}): ack first with set_status { state: "responding", id: <prompt id> } before any other tool (bouncing dots), then one short reply_to_user { in_reply_to, final: false }. The tab holds that reply for 10 seconds, then folds the chat and shows the working spinner. Required after every pair: register_webhook again (process memory only). No webhook: loop read_messages { wait_ms: ${READ_MESSAGES_POLL_MS} } while connected; polling is not activity. An empty immediate read does not mean the user never sent.`;
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Required order after read_messages returns a prompt. set_status responding
|
|
65
|
+
* is the ack. There is no separate ack tool. The 10 second hold is the tab's
|
|
66
|
+
* timer, not the agent's.
|
|
67
|
+
*/
|
|
68
|
+
export const PROMPT_TURN_GUIDANCE = `In-viewer prompt — required order after read_messages returns a user prompt:
|
|
69
|
+
1. Ack immediately: set_status { state: "responding", id: <prompt id> }. That shows the bouncing dots. Do this before any other tool. set_status responding is the ack; there is no separate ack tool.
|
|
70
|
+
2. Reply once, non-final: reply_to_user { in_reply_to: <id>, text: "Got it — starting on <one-line plan>.", final: false }. Keep that reply short. The tab holds that reply visible for 10 seconds.
|
|
71
|
+
3. Only when you are about to create or edit geometry: set_status { state: "building", id }. After the 10 second hold the tab folds the chat and shows the working spinner (on a phone, the Bot button). A building, post_progress, or model-changing call during the hold waits until it ends. Do not call building for list, status, or read_messages.
|
|
72
|
+
4. While modeling, call post_progress occasionally so the session stays present.
|
|
73
|
+
5. When done or failed: reply_to_user { in_reply_to: <id>, text: <what changed, what failed, what remains>, final: true }. That stops the spinner, reopens the chat with the confirmation, and idles.
|
|
74
|
+
${LONG_POLL_GUIDANCE} A per-call process catches prompts the server is holding the same way. register_webhook after every pair when your host can receive callbacks. An empty immediate read does not mean the user never sent.
|
|
75
|
+
This order, the webhook step after every pair, and the long-poll are required, not tips: ${CHAT_GUIDE_POINTER} is the whole workflow.`;
|
|
76
|
+
|
|
34
77
|
/**
|
|
35
78
|
* First paragraph of the MCP initialize `instructions`.
|
|
36
79
|
* Goldens pin the webhook sentence as the prefix.
|
|
37
80
|
*/
|
|
38
|
-
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}`;
|
|
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}`;
|
|
39
82
|
|
|
40
83
|
/** Exact wording the agent should relay when asking the user for a webhook. */
|
|
41
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.';
|
|
@@ -44,7 +87,7 @@ export const PROMPT_ONBOARDING_ASK = 'To get SurfCAD messages instantly, send me
|
|
|
44
87
|
* Pair-result text when no webhook is registered. Generic: not tied to a bot product.
|
|
45
88
|
* The URL and bearer are process memory only, so the agent must keep its own copy.
|
|
46
89
|
*/
|
|
47
|
-
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, poll read_messages.`;
|
|
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}).`;
|
|
48
91
|
|
|
49
92
|
/** Pair-result text when a webhook is already registered. No onboarding note. */
|
|
50
93
|
export const PROMPT_WEBHOOK_ACTIVE = 'Webhook is active.';
|
|
@@ -72,7 +115,7 @@ export function promptToolDefinitions() {
|
|
|
72
115
|
return [
|
|
73
116
|
{
|
|
74
117
|
name: 'register_webhook',
|
|
75
|
-
description: `Register an https webhook that receives user prompts from the paired SurfCAD tab. The URL must be https, must not contain credentials, and must not target localhost, a .local name, or a private, loopback, or link-local address. Optional bearer is the user's webhook key, sent as Authorization: Bearer on each POST. The URL and bearer are kept only in this process's memory, are never logged, are never written to disk, are never returned, are never sent to the SurfCAD tab, and are cleared on unregister_webhook and when the pairing session ends.
|
|
118
|
+
description: `Register an https webhook that receives user prompts from the paired SurfCAD tab. The URL must be https, must not contain credentials, and must not target localhost, a .local name, or a private, loopback, or link-local address. Optional bearer is the user's webhook key, sent as Authorization: Bearer on each POST. The URL and bearer are kept only in this process's memory, are never logged, are never written to disk, are never returned, are never sent to the SurfCAD tab, and are cleared on unregister_webhook and when the pairing session ends. ${WEBHOOK_REQUIRED_GUIDANCE} If the user declines a webhook, the required fallback is the long-poll, not silence. ${LONG_POLL_GUIDANCE} When a webhook is registered, each prompt is POSTed as JSON { "type": "surfcad.prompt", ... } and times out after 10 seconds with one retry. If the POST fails, the prompt is queued instead. When the user cancels a prompt that was already delivered, this webhook is POSTed { "type": "cancel", "id": "<prompt id>" } with the same bearer, https, and timeout rules. Stop work on that id. Do not call reply_to_user or set_status for it. ${USER_CONTENT}`,
|
|
76
119
|
inputSchema: {
|
|
77
120
|
type: 'object',
|
|
78
121
|
additionalProperties: false,
|
|
@@ -102,7 +145,7 @@ export function promptToolDefinitions() {
|
|
|
102
145
|
},
|
|
103
146
|
{
|
|
104
147
|
name: 'read_messages',
|
|
105
|
-
description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text. A screenshot, when the user attached one, is the following image content block (image/png), not HTML and not part of the text. 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. When you finish the task from a prompt you received here, close that chat: ${CLOSING_REPLY_GUIDANCE}`,
|
|
148
|
+
description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text. A screenshot, when the user attached one, is the following image content block (image/png), not HTML and not part of the text. 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}`,
|
|
106
149
|
inputSchema: {
|
|
107
150
|
type: 'object',
|
|
108
151
|
additionalProperties: false,
|
|
@@ -117,7 +160,7 @@ export function promptToolDefinitions() {
|
|
|
117
160
|
type: 'integer',
|
|
118
161
|
minimum: 0,
|
|
119
162
|
maximum: READ_MESSAGES_MAX_WAIT_MS,
|
|
120
|
-
description: `Long-poll: when the queue is empty, wait up to this many milliseconds (at most ${READ_MESSAGES_MAX_WAIT_MS}) for a prompt or cancel to arrive before answering, instead of returning an empty list at once.
|
|
163
|
+
description: `Long-poll: when the queue is empty, wait up to this many milliseconds (at most ${READ_MESSAGES_MAX_WAIT_MS}) for a prompt or cancel to arrive before answering, instead of returning an empty list at once. The required cycle while connected is ${READ_MESSAGES_POLL_MS}, called again as soon as it returns (or register_webhook, with this loop as the safety net). An empty immediate read does not mean the user never sent. Omit or 0 to return immediately.`,
|
|
121
164
|
},
|
|
122
165
|
},
|
|
123
166
|
},
|
|
@@ -147,7 +190,7 @@ export function promptToolDefinitions() {
|
|
|
147
190
|
},
|
|
148
191
|
{
|
|
149
192
|
name: 'set_status',
|
|
150
|
-
description: `Tell the SurfCAD tab which phase the user's prompt is in. responding (alias typing):
|
|
193
|
+
description: `Tell the SurfCAD tab which phase the user's prompt is in. responding (alias typing) is the ack: call set_status { state: "responding", id } first after read_messages returns a prompt, before any other tool. The chat stays open with bouncing dots. Then one short non-final reply_to_user. The tab holds that reply for 10 seconds. building (alias working): you are creating or editing geometry. A building call, post_progress, or model-changing tool during that hold waits, then the chat folds and the field shows "Agent is working..." (on a phone, the Bot button spins). ${BUILDING_STATUS_GUIDANCE} Do not call building to list parts, faces, edges, or transforms, or for status or read_messages. A model-changing tool also enters building if you skip this call. A read never does. set_status is for progress and does not close the task. A partial reply does not leave building; the final reply, Stop, or a disconnect does. reply_to_user { final: true } stops the spinner, reopens the chat, and idles. No activity for ${agentPromptStallMinutes()} minutes, while responding or building, shows the stall notice and leaves Stop up. set_status, a model-changing tool, post_progress, and reply_to_user are activity; a read_messages poll is not. The result state is the tab value (responding and typing are typing; building and working are working). Without id it targets the latest prompt. With no prompt at all (a build you started yourself, or a prompt an earlier one-shot process read) the tab still shows the state: it keeps a session-level state fed by this call, by every model-changing tool you call, and by post_progress, and it returns to idle 60 s after the last of those. A cancelled id returns { ok: false, error: cancelled }. ${CLOSING_REPLY_GUIDANCE}`,
|
|
151
194
|
inputSchema: {
|
|
152
195
|
type: 'object',
|
|
153
196
|
additionalProperties: false,
|
|
@@ -175,7 +218,7 @@ export function promptToolDefinitions() {
|
|
|
175
218
|
},
|
|
176
219
|
{
|
|
177
220
|
name: 'post_progress',
|
|
178
|
-
description: 'Tell SurfCAD you are working, without showing thinking text. Call it while you work, especially during long reasoning, so the
|
|
221
|
+
description: 'Tell SurfCAD you are working, without showing thinking text. Call it while you work, especially during long reasoning, so the chat folds and the spinner shows (on a phone, the Bot button). A non-final ack reply stays visible for 10 seconds first; a post_progress during that hold waits until it ends. Optional text is accepted and discarded; it is never shown. This also keeps the session present. It does not close the task.',
|
|
179
222
|
inputSchema: {
|
|
180
223
|
type: 'object',
|
|
181
224
|
additionalProperties: false,
|
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
package/src/server.mjs
CHANGED
|
@@ -46,12 +46,26 @@ 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
|
-
/** One line in the pair result; the guidance itself is guide { topic: "start" }. */
|
|
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)
|
|
58
|
+
/** One line in the pair result; the guidance itself is guide { topic: "start" } and guide { topic: "chat" }. */
|
|
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.';
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Prompt tools that do not count as agent activity when called. set_status,
|
|
63
|
+
* post_progress, and close_session send their own frame; read_messages is a
|
|
64
|
+
* poll and must not restart the stall window.
|
|
65
|
+
*/
|
|
66
|
+
const PROMPT_TOOLS_WITHOUT_ACTIVITY = new Set(['set_status', 'post_progress', 'close_session', 'read_messages']);
|
|
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).';
|
|
55
69
|
|
|
56
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).';
|
|
57
71
|
|
|
@@ -63,7 +77,7 @@ function augmentStatusTool(tool) {
|
|
|
63
77
|
if (!tool || tool.name !== 'status') return tool;
|
|
64
78
|
return {
|
|
65
79
|
...tool,
|
|
66
|
-
description: `${tool.description || ''}${STATUS_PROMPT_NOTE}`,
|
|
80
|
+
description: `${tool.description || ''}${STATUS_PROMPT_NOTE}${STATUS_WAKE_NOTE}`,
|
|
67
81
|
};
|
|
68
82
|
}
|
|
69
83
|
|
|
@@ -165,18 +179,21 @@ function mutatingTool(name) {
|
|
|
165
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);
|
|
166
180
|
}
|
|
167
181
|
|
|
168
|
-
function pairToolResult(result, prompts) {
|
|
182
|
+
function pairToolResult(result, prompts, wake) {
|
|
169
183
|
const webhookRegistered = prompts.webhookRegistered() === true;
|
|
170
184
|
const note = webhookRegistered ? PROMPT_WEBHOOK_ACTIVE : PROMPT_ONBOARDING_NOTE;
|
|
171
185
|
const payload = {
|
|
172
186
|
...(result && typeof result === 'object' ? result : {}),
|
|
173
187
|
webhookRegistered,
|
|
174
188
|
note,
|
|
189
|
+
...(wake ? { wake } : {}),
|
|
175
190
|
};
|
|
176
191
|
return {
|
|
177
192
|
content: [
|
|
178
193
|
{ type: 'text', text: JSON.stringify(payload, null, 2) },
|
|
179
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 }] : []),
|
|
180
197
|
// The build guidance lives in the guide tool; one pointer here, for every client.
|
|
181
198
|
{ type: 'text', text: PAIR_GUIDE_POINTER },
|
|
182
199
|
],
|
|
@@ -184,6 +201,84 @@ function pairToolResult(result, prompts) {
|
|
|
184
201
|
};
|
|
185
202
|
}
|
|
186
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
|
+
|
|
187
282
|
function toolErrorPayload(err) {
|
|
188
283
|
if (err && typeof err === 'object' && err.code) {
|
|
189
284
|
return formatBridgeError({
|
|
@@ -243,6 +338,8 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
243
338
|
}));
|
|
244
339
|
|
|
245
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);
|
|
246
343
|
const name = request.params.name;
|
|
247
344
|
const args = request.params.arguments && typeof request.params.arguments === 'object'
|
|
248
345
|
? request.params.arguments
|
|
@@ -257,7 +354,10 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
257
354
|
}
|
|
258
355
|
|
|
259
356
|
if (isPromptTool(name)) {
|
|
260
|
-
|
|
357
|
+
// set_status, post_progress, and replies drive the tab state themselves.
|
|
358
|
+
// read_messages is a poll: it is not agent activity, so it must not
|
|
359
|
+
// restart the stall window (a long-poll loop would otherwise hide a stall).
|
|
360
|
+
if (!PROMPT_TOOLS_WITHOUT_ACTIVITY.has(name)) session.noteAgentToolCall();
|
|
261
361
|
try {
|
|
262
362
|
const out = await callPromptTool(session.prompts, name, args);
|
|
263
363
|
if (out.isError) return errorResult(out.error, name);
|
|
@@ -279,7 +379,7 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
279
379
|
}
|
|
280
380
|
try {
|
|
281
381
|
const result = await waitForPairing(session.pair(code), PAIR_TOOL_WAIT_MS);
|
|
282
|
-
return pairToolResult(result, session.prompts);
|
|
382
|
+
return pairToolResult(result, session.prompts, await wakeStatus(session));
|
|
283
383
|
} catch (err) {
|
|
284
384
|
return errorResult(toolErrorPayload(err), name);
|
|
285
385
|
}
|
|
@@ -325,7 +425,7 @@ export async function createSurfcadMcpServer(options = {}) {
|
|
|
325
425
|
session.holdAgentWork(false);
|
|
326
426
|
}
|
|
327
427
|
if (name === 'status' && out.isError !== true && out.value && typeof out.value === 'object' && !Array.isArray(out.value)) {
|
|
328
|
-
return textResult({ ...out.value, ...session.prompts.deliveryStatus() });
|
|
428
|
+
return textResult({ ...out.value, ...session.prompts.deliveryStatus(), wake: await wakeStatus(session) });
|
|
329
429
|
}
|
|
330
430
|
if (name === 'list_commands' && out.isError !== true) {
|
|
331
431
|
out = {
|
|
@@ -406,9 +506,11 @@ export async function runSurfcadMcpServer(options = {}) {
|
|
|
406
506
|
};
|
|
407
507
|
process.stdin.once('end', onStdinClosed);
|
|
408
508
|
|
|
509
|
+
const localWake = createInProcessWake({ remote: false });
|
|
409
510
|
const { server, session } = await createSurfcadMcpServer({
|
|
410
|
-
session: new RelaySession({ ensureRelay: takeOverRelay }),
|
|
511
|
+
session: new RelaySession({ ensureRelay: takeOverRelay, onUnread: localWake }),
|
|
411
512
|
});
|
|
513
|
+
localWake.attach(session.prompts);
|
|
412
514
|
const transport = new StdioServerTransport();
|
|
413
515
|
await server.connect(transport);
|
|
414
516
|
|
|
@@ -435,12 +537,15 @@ async function runRemoteMcpServer(options) {
|
|
|
435
537
|
}
|
|
436
538
|
const serverUrl = resolveServerUrl({ flag: options.server, env, saved });
|
|
437
539
|
const pinned = resolveAgentName({ name: options.name, savedName: saved.name, env });
|
|
540
|
+
const remoteWake = createInProcessWake({ remote: true, env });
|
|
438
541
|
const remote = new RemoteSession({
|
|
439
542
|
serverUrl,
|
|
440
543
|
token: saved.token,
|
|
441
544
|
name: pinned,
|
|
442
545
|
fillNameFromClient: !pinned,
|
|
546
|
+
onUnread: remoteWake,
|
|
443
547
|
});
|
|
548
|
+
remoteWake.attach(remote.prompts);
|
|
444
549
|
const { server, session } = await createSurfcadMcpServer({ session: remote });
|
|
445
550
|
server.oninitialized = () => {
|
|
446
551
|
remote.applyClientInfo(server.getClientVersion());
|