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.
- package/README.md +44 -1
- package/data/commands.json +2 -2
- 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/guide.mjs +10 -6
- package/src/prompt/promptSession.mjs +25 -0
- package/src/relay.mjs +1 -0
- package/src/remote/session.mjs +1 -0
- package/src/server.mjs +101 -6
package/README.md
CHANGED
|
@@ -181,10 +181,53 @@ After `read_messages` returns a prompt, ack first with `set_status { state: "res
|
|
|
181
181
|
|
|
182
182
|
Stop in the prompt card sends `agent.prompt.cancel` (`v: 1`, the current prompt id) over the same paired connection. Each prompt is `queued`, `delivered` (webhook POST succeeded, or `read_messages` returned it), `replied` (a final reply), or `cancelled`. A prompt that is still queued is removed and is not returned by `read_messages`. A prompt that was already delivered is marked `cancelled`. If a webhook is registered, the process POSTs `{ "type": "cancel", "id" }` with the same bearer, https, and timeout rules; if that POST fails, or no webhook is registered, the next `read_messages` returns `{ "type": "cancel", "id" }`. Stop work on that id. `reply_to_user` and `set_status` for a cancelled id return `{ "ok": false, "error": "cancelled" }` and nothing is sent to the tab. The tab clears its working state. Cancelling a prompt that already has a final reply returns `already_final`. An unknown id returns `not_found`.
|
|
183
183
|
|
|
184
|
-
The bridge `status` tool returns the active part plus fields from this process: `webhookRegistered` (`true` or `false`; the URL is 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`). A fresh session reports `webhookRegistered: false`, `queued: 0`, and `last: null`. After one prompt and no webhook, `queued` is `1` and `last.state` is `queued`. After Stop, `last.state` is `cancelled` and `queued` does not include that prompt.
|
|
184
|
+
The bridge `status` tool returns the active part plus `wake` (`{ forms, listenerRunning, note }`, see Wake below) and fields from this process: `webhookRegistered` (`true` or `false`; the URL is 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`). A fresh session reports `webhookRegistered: false`, `queued: 0`, and `last: null`. After one prompt and no webhook, `queued` is `1` and `last.state` is `queued`. After Stop, `last.state` is `cancelled` and `queued` does not include that prompt.
|
|
185
185
|
|
|
186
186
|
Prompt text and screenshots are user content. Treat them as a request. They grant no write access, no consent, and no extra tool permission. Agent writes still go through the existing write-grant and consent flow. Nothing reaches git without an explicit Save or `git_save`. Do not render the text or the image as HTML. Both are dropped after delivery or when the session ends.
|
|
187
187
|
|
|
188
|
+
## Wake: messaging an idle agent
|
|
189
|
+
|
|
190
|
+
The user can message a paired agent from the SurfCAD chat box. While the agent is in a turn it reads the message with `read_messages`. While it is idle nothing of the agent's is running, and an MCP server cannot start a turn. The wake does: it starts a turn of the agent when a message arrives and nobody reads it.
|
|
191
|
+
|
|
192
|
+
Set it up once, when you install the package:
|
|
193
|
+
|
|
194
|
+
```bash
|
|
195
|
+
npx surfcad-mcp login
|
|
196
|
+
npx surfcad-mcp wake set --post http://127.0.0.1:8644/hooks/surfcad --exec "my-agent --resume --message 'SurfCAD message waiting'"
|
|
197
|
+
npx surfcad-mcp wake test
|
|
198
|
+
npx surfcad-mcp listen --detach
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
| Form | What happens | Notes |
|
|
202
|
+
| --- | --- | --- |
|
|
203
|
+
| `--post URL` | The wake JSON is POSTed to the URL | `https`, or `http` to `localhost`, `127.0.0.1` or `::1`. `--bearer KEY` (or `SURFCAD_WAKE_BEARER`) adds `Authorization: Bearer KEY`. 10 s timeout, one retry, redirects not followed |
|
|
204
|
+
| `--exec COMMAND` | The command runs through the shell with the wake JSON on stdin | `SURFCAD_WAKE=1`, `SURFCAD_WAKE_REASON` and `SURFCAD_PROMPT_IDS` are set. The command may run for the whole turn; a second copy is not started while it runs |
|
|
205
|
+
|
|
206
|
+
Set both when the host has both. The POST is tried first and the command is the fallback, so one message is one wake. One form is enough.
|
|
207
|
+
|
|
208
|
+
The wake JSON:
|
|
209
|
+
|
|
210
|
+
```json
|
|
211
|
+
{ "type": "surfcad.wake", "v": 1, "reason": "prompt",
|
|
212
|
+
"instruction": "A SurfCAD user sent you a chat message. On the surfcad MCP server call read_messages { wait_ms: 10000 }, then follow guide { topic: \"chat\" }: set_status responding first, then reply_to_user.",
|
|
213
|
+
"prompts": [{ "id": "…", "text": "make the boss taller", "ts": "…", "hasScreenshot": true }] }
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
The text is a preview. The message itself stays on the server until an agent process reads it with `read_messages`, so a wake never consumes a message. A screenshot is not in the wake; `read_messages` returns it.
|
|
217
|
+
|
|
218
|
+
How it works:
|
|
219
|
+
|
|
220
|
+
- `npx surfcad-mcp listen` long-polls the server relay (`GET /agent/prompts`) with the saved login. Outbound HTTPS only: no open port, it works behind NAT, and it works when the user is on a phone, because neither side has to reach the other.
|
|
221
|
+
- A message is not woken for at once. An agent that is already polling takes it within seconds. After 4 seconds the listener asks the server whether the message is still unread, and only then fires the wake. A message still unread two minutes after a wake is woken for once more.
|
|
222
|
+
- An agent in a turn is not woken. Every MCP tool call stamps a small file (`awake` in the config directory), and for 60 seconds after the last one the agent counts as in a turn: it reads the message at its next `read_messages`, and a wake on top of that would start a second turn beside the first. The message is looked at again every 15 seconds until the agent reads it or goes idle.
|
|
223
|
+
- A long-lived `surfcad-mcp` MCP process fires the same wake itself for a message that sits unread in its queue. That covers the local relay, which has no login. When a listener is running on the server relay, the listener owns the wake.
|
|
224
|
+
- `npx surfcad-mcp status` prints the saved wake and whether the listener is running. The MCP `status` tool returns the same as `wake: { forms, listenerRunning, note }`, and every `pair` result carries the note, so an agent sees a missing setup and the steps to fix it.
|
|
225
|
+
- `npx surfcad-mcp wake show | test | clear`, `npx surfcad-mcp listen --stop`. The listener logs to `listener.log` in the config directory. Start it again after a reboot, or add `npx surfcad-mcp listen` to the host's startup (a systemd user unit, launchd, pm2).
|
|
226
|
+
|
|
227
|
+
What is saved: `wake.json` next to the saved login, mode 0600. It is written only by `wake set` on this machine. Nothing a server, a tab or a chat message sends can change it. Message text reaches the command on stdin only, never in its arguments or environment. The bearer is never printed or logged.
|
|
228
|
+
|
|
229
|
+
`register_webhook` is still there for a host with a public HTTPS endpoint. It lives in one MCP process's memory, so it cannot wake an agent whose host starts a fresh process per tool call. The wake can.
|
|
230
|
+
|
|
188
231
|
## Safety and consent
|
|
189
232
|
|
|
190
233
|
- **Commerce:** Agents cannot place orders or drive checkout. Quote/cart/checkout controls are not exposed as MCP tools.
|
package/data/commands.json
CHANGED
|
@@ -5600,7 +5600,7 @@
|
|
|
5600
5600
|
},
|
|
5601
5601
|
{
|
|
5602
5602
|
"name": "insert_fillet_edges",
|
|
5603
|
-
"description": "Prefer this over freehand set_script. Insert this helper on the active part (set_active_part first) and run it. Numbers are finite and within ±1000000 mm (positions and deltas included); NaN and Infinity are bad_args. Working copy only; git_save commits. The result usedSelection says whether the viewport selection was used. A face pick is written into the script by name (facesNamed for a hole, edgesOf for a fillet or chamfer around that face) and is found again on the new mesh after every rebuild, so a second use_selection insert lands on the same face; an edge pick (select_edges { names }, pick sessions, a tap) is written as edgesNamed(part, \"faceA~faceB\"), the pair of stamped faces it lies between, which also survives edits. Every face has a name (helper roles, fillet1.round / chamfer2.bevel, import@1.f<k>, <block>.f<k> for freehand). Edge picks still clear with the rebuild (re-pick before the next insert), and use_selection: true with nothing selected is no_selection (nothing is written). Build in ribbon order: block out every part of the assembly as plain blocks first (within seconds of the prompt, then screenshot for the user), then Build and Shape, then Polish, then pattern and place; finish each stage across the whole assembly before the next. Features first: insert_code_snippet { gap, why, script } is the fallback for one operation no feature can do (its block starts with // FEATURE-GAP: <missing feature or option> | <why the existing feature did not work>); set_script only rewrites a whole part. Hardware is one part per unique fastener type, one instance patterned to every place it goes. Fix one base part with a fixed joint, then place every part that touches or attaches to another with joint_create (one call creates the joint and solves placement). Use part_set_transform only for parts that touch nothing. Block-out positions are rough; joints set final positions. If the geometry engine crashes under this part (out of memory, a wasm abort, or a run past its 30 s budget) the result is ok: false with crash { code: geometry_worker_crashed, reason: wasm_abort | out_of_memory | timeout | worker_lost, workerRestarted: true } and one failures row with the same code; status.runState is failed. The worker was already replaced and other parts kept building, so do not ask for a reload and do not retry the same script: simplify the part, lower segment counts, or split it into smaller parts, then run it again. When the run past the budget was inside one marked feature block, the part is rebuilt without that block instead: the result is ok: false with one failures row { code: feature_timeout, featureId, featureType, featureLabel, elapsedMs, budgetMs, detail }, status.runState is failed, the other features are built and shown, and status.featureMs (and feature_tree ms) say how long each block took; edit, delete, or undo that feature. Cost: fillets and chamfers are the slow features. Do them last, once the shape is final, on the smallest edge set that does the job (a face pick writes edgesOf for that face only; grouped edges from list_edges for less), because a blend over many edges, or on a swept or lofted body, can run past the 30 s block budget and come back as feature_timeout with the part rebuilt without it. Order (required): shell first, then concave fillets and chamfers, then convex ones. After a shell or a concave blend pick the edges by name (select_edges { names } or a face pick, then use_selection: true); the no-selection default is for a plain block and
|
|
5603
|
+
"description": "Prefer this over freehand set_script. Insert this helper on the active part (set_active_part first) and run it. Numbers are finite and within ±1000000 mm (positions and deltas included); NaN and Infinity are bad_args. Working copy only; git_save commits. The result usedSelection says whether the viewport selection was used. A face pick is written into the script by name (facesNamed for a hole, edgesOf for a fillet or chamfer around that face) and is found again on the new mesh after every rebuild, so a second use_selection insert lands on the same face; an edge pick (select_edges { names }, pick sessions, a tap) is written as edgesNamed(part, \"faceA~faceB\"), the pair of stamped faces it lies between, which also survives edits. Every face has a name (helper roles, fillet1.round / chamfer2.bevel, import@1.f<k>, <block>.f<k> for freehand). Edge picks still clear with the rebuild (re-pick before the next insert), and use_selection: true with nothing selected is no_selection (nothing is written). Build in ribbon order: block out every part of the assembly as plain blocks first (within seconds of the prompt, then screenshot for the user), then Build and Shape, then Polish, then pattern and place; finish each stage across the whole assembly before the next. Features first: insert_code_snippet { gap, why, script } is the fallback for one operation no feature can do (its block starts with // FEATURE-GAP: <missing feature or option> | <why the existing feature did not work>); set_script only rewrites a whole part. Hardware is one part per unique fastener type, one instance patterned to every place it goes. Fix one base part with a fixed joint, then place every part that touches or attaches to another with joint_create (one call creates the joint and solves placement). Use part_set_transform only for parts that touch nothing. Block-out positions are rough; joints set final positions. If the geometry engine crashes under this part (out of memory, a wasm abort, or a run past its 30 s budget) the result is ok: false with crash { code: geometry_worker_crashed, reason: wasm_abort | out_of_memory | timeout | worker_lost, workerRestarted: true } and one failures row with the same code; status.runState is failed. The worker was already replaced and other parts kept building, so do not ask for a reload and do not retry the same script: simplify the part, lower segment counts, or split it into smaller parts, then run it again. When the run past the budget was inside one marked feature block, the part is rebuilt without that block instead: the result is ok: false with one failures row { code: feature_timeout, featureId, featureType, featureLabel, elapsedMs, budgetMs, detail }, status.runState is failed, the other features are built and shown, and status.featureMs (and feature_tree ms) say how long each block took; edit, delete, or undo that feature. Cost: fillets and chamfers are the slow features. Do them last, once the shape is final, on the smallest edge set that does the job (a face pick writes edgesOf for that face only; grouped edges from list_edges for less), because a blend over many edges, or on a swept or lofted body, can run past the 30 s block budget and come back as feature_timeout with the part rebuilt without it. Order (required): shell first, then concave fillets and chamfers, then convex ones. After a shell or a concave blend pick the edges by name (select_edges { names } or a face pick, then use_selection: true); the no-selection default takes every convex edge, is for a plain block, and can fail there (guide { topic: \"modeling\" }). Writes (defaults): part = filletEdges(part, convexEdges(part), 3, { sphericalCorners: true }); Takes return: \"status\" | \"summary\" | \"full\" (MCP default \"status\": status.script is omitted; \"summary\" adds status.features; \"full\" echoes the script).",
|
|
5604
5604
|
"args": {
|
|
5605
5605
|
"type": "object",
|
|
5606
5606
|
"additionalProperties": false,
|
|
@@ -5893,7 +5893,7 @@
|
|
|
5893
5893
|
},
|
|
5894
5894
|
{
|
|
5895
5895
|
"name": "insert_chamfer_edges",
|
|
5896
|
-
"description": "Prefer this over freehand set_script. Insert this helper on the active part (set_active_part first) and run it. Numbers are finite and within ±1000000 mm (positions and deltas included); NaN and Infinity are bad_args. Working copy only; git_save commits. The result usedSelection says whether the viewport selection was used. A face pick is written into the script by name (facesNamed for a hole, edgesOf for a fillet or chamfer around that face) and is found again on the new mesh after every rebuild, so a second use_selection insert lands on the same face; an edge pick (select_edges { names }, pick sessions, a tap) is written as edgesNamed(part, \"faceA~faceB\"), the pair of stamped faces it lies between, which also survives edits. Every face has a name (helper roles, fillet1.round / chamfer2.bevel, import@1.f<k>, <block>.f<k> for freehand). Edge picks still clear with the rebuild (re-pick before the next insert), and use_selection: true with nothing selected is no_selection (nothing is written). Build in ribbon order: block out every part of the assembly as plain blocks first (within seconds of the prompt, then screenshot for the user), then Build and Shape, then Polish, then pattern and place; finish each stage across the whole assembly before the next. Features first: insert_code_snippet { gap, why, script } is the fallback for one operation no feature can do (its block starts with // FEATURE-GAP: <missing feature or option> | <why the existing feature did not work>); set_script only rewrites a whole part. Hardware is one part per unique fastener type, one instance patterned to every place it goes. Fix one base part with a fixed joint, then place every part that touches or attaches to another with joint_create (one call creates the joint and solves placement). Use part_set_transform only for parts that touch nothing. Block-out positions are rough; joints set final positions. If the geometry engine crashes under this part (out of memory, a wasm abort, or a run past its 30 s budget) the result is ok: false with crash { code: geometry_worker_crashed, reason: wasm_abort | out_of_memory | timeout | worker_lost, workerRestarted: true } and one failures row with the same code; status.runState is failed. The worker was already replaced and other parts kept building, so do not ask for a reload and do not retry the same script: simplify the part, lower segment counts, or split it into smaller parts, then run it again. When the run past the budget was inside one marked feature block, the part is rebuilt without that block instead: the result is ok: false with one failures row { code: feature_timeout, featureId, featureType, featureLabel, elapsedMs, budgetMs, detail }, status.runState is failed, the other features are built and shown, and status.featureMs (and feature_tree ms) say how long each block took; edit, delete, or undo that feature. Cost: fillets and chamfers are the slow features. Do them last, once the shape is final, on the smallest edge set that does the job (a face pick writes edgesOf for that face only; grouped edges from list_edges for less), because a blend over many edges, or on a swept or lofted body, can run past the 30 s block budget and come back as feature_timeout with the part rebuilt without it. Order (required): shell first, then concave fillets and chamfers, then convex ones. After a shell or a concave blend pick the edges by name (select_edges { names } or a face pick, then use_selection: true); the no-selection default is for a plain block and
|
|
5896
|
+
"description": "Prefer this over freehand set_script. Insert this helper on the active part (set_active_part first) and run it. Numbers are finite and within ±1000000 mm (positions and deltas included); NaN and Infinity are bad_args. Working copy only; git_save commits. The result usedSelection says whether the viewport selection was used. A face pick is written into the script by name (facesNamed for a hole, edgesOf for a fillet or chamfer around that face) and is found again on the new mesh after every rebuild, so a second use_selection insert lands on the same face; an edge pick (select_edges { names }, pick sessions, a tap) is written as edgesNamed(part, \"faceA~faceB\"), the pair of stamped faces it lies between, which also survives edits. Every face has a name (helper roles, fillet1.round / chamfer2.bevel, import@1.f<k>, <block>.f<k> for freehand). Edge picks still clear with the rebuild (re-pick before the next insert), and use_selection: true with nothing selected is no_selection (nothing is written). Build in ribbon order: block out every part of the assembly as plain blocks first (within seconds of the prompt, then screenshot for the user), then Build and Shape, then Polish, then pattern and place; finish each stage across the whole assembly before the next. Features first: insert_code_snippet { gap, why, script } is the fallback for one operation no feature can do (its block starts with // FEATURE-GAP: <missing feature or option> | <why the existing feature did not work>); set_script only rewrites a whole part. Hardware is one part per unique fastener type, one instance patterned to every place it goes. Fix one base part with a fixed joint, then place every part that touches or attaches to another with joint_create (one call creates the joint and solves placement). Use part_set_transform only for parts that touch nothing. Block-out positions are rough; joints set final positions. If the geometry engine crashes under this part (out of memory, a wasm abort, or a run past its 30 s budget) the result is ok: false with crash { code: geometry_worker_crashed, reason: wasm_abort | out_of_memory | timeout | worker_lost, workerRestarted: true } and one failures row with the same code; status.runState is failed. The worker was already replaced and other parts kept building, so do not ask for a reload and do not retry the same script: simplify the part, lower segment counts, or split it into smaller parts, then run it again. When the run past the budget was inside one marked feature block, the part is rebuilt without that block instead: the result is ok: false with one failures row { code: feature_timeout, featureId, featureType, featureLabel, elapsedMs, budgetMs, detail }, status.runState is failed, the other features are built and shown, and status.featureMs (and feature_tree ms) say how long each block took; edit, delete, or undo that feature. Cost: fillets and chamfers are the slow features. Do them last, once the shape is final, on the smallest edge set that does the job (a face pick writes edgesOf for that face only; grouped edges from list_edges for less), because a blend over many edges, or on a swept or lofted body, can run past the 30 s block budget and come back as feature_timeout with the part rebuilt without it. Order (required): shell first, then concave fillets and chamfers, then convex ones. After a shell or a concave blend pick the edges by name (select_edges { names } or a face pick, then use_selection: true); the no-selection default takes every convex edge, is for a plain block, and can fail there (guide { topic: \"modeling\" }). Writes (defaults): part = chamferEdges(part, convexEdges(part), 2); Takes return: \"status\" | \"summary\" | \"full\" (MCP default \"status\": status.script is omitted; \"summary\" adds status.features; \"full\" echoes the script).",
|
|
5897
5897
|
"args": {
|
|
5898
5898
|
"type": "object",
|
|
5899
5899
|
"additionalProperties": false,
|
package/package.json
CHANGED
package/src/cli.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `surfcad-mcp` argv. login / logout / status exit.
|
|
3
|
-
*
|
|
2
|
+
* `surfcad-mcp` argv. login / logout / status / wake exit. `listen` runs the
|
|
3
|
+
* wake listener until it is stopped. Anything else starts the stdio server.
|
|
4
|
+
* The token and the wake bearer are never written to stdout or stderr.
|
|
4
5
|
*/
|
|
5
6
|
|
|
6
7
|
import { hostname } from 'node:os';
|
|
@@ -8,6 +9,7 @@ import { resolveAgentName, resolveServerUrl, selectRelayMode } from './remote/co
|
|
|
8
9
|
import { loginDevice, loginWithCode } from './remote/login.mjs';
|
|
9
10
|
import { logoutDevice } from './remote/logout.mjs';
|
|
10
11
|
import { formatLoginStatus, readSavedLogin } from './remote/tokenStore.mjs';
|
|
12
|
+
import { runListenCommand, runWakeCommand, wakeStatusText, WAKE_SETUP_STEPS } from './listen/listenCli.mjs';
|
|
11
13
|
|
|
12
14
|
const HELP = `surfcad-mcp
|
|
13
15
|
|
|
@@ -23,6 +25,23 @@ const HELP = `surfcad-mcp
|
|
|
23
25
|
Revokes this machine's token on the server, then deletes the saved
|
|
24
26
|
file. If the server cannot be reached, the file is still deleted.
|
|
25
27
|
npx surfcad-mcp status
|
|
28
|
+
The saved login, the wake setup, and whether the listener is running.
|
|
29
|
+
|
|
30
|
+
Wake: start a turn of the agent when the user sends a chat message from
|
|
31
|
+
SurfCAD and no agent process is reading. Set it up once, at install:
|
|
32
|
+
${WAKE_SETUP_STEPS.map((step, i) => ` ${i + 1}. ${step}`).join('\n')}
|
|
33
|
+
npx surfcad-mcp wake set [--post URL [--bearer KEY]] [--exec COMMAND]
|
|
34
|
+
Save how to wake the agent on this machine. --post: the wake JSON is
|
|
35
|
+
POSTed there (https, or http to localhost). --exec: the command runs
|
|
36
|
+
with the wake JSON on stdin. With both, the POST is tried first and
|
|
37
|
+
the command is the fallback. The key can also come from
|
|
38
|
+
SURFCAD_WAKE_BEARER. It is saved on this machine and is not printed.
|
|
39
|
+
npx surfcad-mcp wake show | test | clear
|
|
40
|
+
npx surfcad-mcp listen [--detach] [--stop]
|
|
41
|
+
Watch the server relay for chat messages and fire the wake for one
|
|
42
|
+
that no agent process reads within a few seconds. Outbound HTTPS
|
|
43
|
+
only: no open port, works behind NAT. Needs a saved login and a saved
|
|
44
|
+
wake. --detach starts it in the background and returns. --stop ends it.
|
|
26
45
|
|
|
27
46
|
--remote Use the server relay. Requires a saved login.
|
|
28
47
|
--local Use the local relay even when a login is saved.
|
|
@@ -42,22 +61,64 @@ SURFCAD_AGENT_BRIDGE_WS_PORT, or a non-empty SURFCAD_PAIRING_CODE.
|
|
|
42
61
|
* @param {string[]} argv
|
|
43
62
|
*/
|
|
44
63
|
export function parseArgs(argv) {
|
|
45
|
-
/** @type {'serve' | 'login' | 'logout' | 'status' | 'help'} */
|
|
64
|
+
/** @type {'serve' | 'login' | 'logout' | 'status' | 'listen' | 'wake' | 'help'} */
|
|
46
65
|
let command = 'serve';
|
|
47
66
|
let name = '';
|
|
48
67
|
let server = '';
|
|
49
68
|
let code = '';
|
|
50
69
|
let remote = false;
|
|
51
70
|
let local = false;
|
|
71
|
+
let action = '';
|
|
72
|
+
let post = '';
|
|
73
|
+
let exec = '';
|
|
74
|
+
let bearer = '';
|
|
75
|
+
let detach = false;
|
|
76
|
+
let stop = false;
|
|
77
|
+
const valued = (arg, flag, i) => {
|
|
78
|
+
const value = arg === flag ? argv[i + 1] : arg.slice(flag.length + 1);
|
|
79
|
+
if (!value || (arg === flag && value.startsWith('--'))) {
|
|
80
|
+
throw Object.assign(new Error(`${flag} needs a value.`), { code: 'bad_args' });
|
|
81
|
+
}
|
|
82
|
+
return value;
|
|
83
|
+
};
|
|
52
84
|
for (let i = 0; i < argv.length; i += 1) {
|
|
53
85
|
const arg = argv[i];
|
|
54
|
-
if (arg === 'login' || arg === 'logout' || arg === 'status') {
|
|
86
|
+
if (arg === 'login' || arg === 'logout' || arg === 'status' || arg === 'listen' || arg === 'wake') {
|
|
55
87
|
if (command !== 'serve') {
|
|
56
|
-
throw Object.assign(new Error('Pass one command: login, logout, or
|
|
88
|
+
throw Object.assign(new Error('Pass one command: login, logout, status, wake, or listen.'), { code: 'bad_args' });
|
|
57
89
|
}
|
|
58
90
|
command = arg;
|
|
59
91
|
continue;
|
|
60
92
|
}
|
|
93
|
+
if (command === 'wake' && !action && (arg === 'set' || arg === 'show' || arg === 'test' || arg === 'clear')) {
|
|
94
|
+
action = arg;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (arg === '--detach') {
|
|
98
|
+
detach = true;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (arg === '--stop') {
|
|
102
|
+
stop = true;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (arg === '--post' || arg.startsWith('--post=')) {
|
|
106
|
+
post = valued(arg, '--post', i);
|
|
107
|
+
if (arg === '--post') i += 1;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (arg === '--exec' || arg.startsWith('--exec=')) {
|
|
111
|
+
// A command may start with "--" only in the = form.
|
|
112
|
+
exec = arg === '--exec' ? argv[i + 1] || '' : arg.slice('--exec='.length);
|
|
113
|
+
if (!exec) throw Object.assign(new Error('--exec needs a value.'), { code: 'bad_args' });
|
|
114
|
+
if (arg === '--exec') i += 1;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (arg === '--bearer' || arg.startsWith('--bearer=')) {
|
|
118
|
+
bearer = valued(arg, '--bearer', i);
|
|
119
|
+
if (arg === '--bearer') i += 1;
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
61
122
|
if (arg === '--help' || arg === '-h' || arg === 'help') {
|
|
62
123
|
command = 'help';
|
|
63
124
|
continue;
|
|
@@ -96,7 +157,16 @@ export function parseArgs(argv) {
|
|
|
96
157
|
}
|
|
97
158
|
throw Object.assign(new Error(`Unknown argument: ${arg}`), { code: 'bad_args' });
|
|
98
159
|
}
|
|
99
|
-
|
|
160
|
+
if (command !== 'wake' && (post || exec || bearer)) {
|
|
161
|
+
throw Object.assign(new Error('--post, --exec and --bearer go with: wake set.'), { code: 'bad_args' });
|
|
162
|
+
}
|
|
163
|
+
if (command !== 'listen' && (detach || stop)) {
|
|
164
|
+
throw Object.assign(new Error('--detach and --stop go with: listen.'), { code: 'bad_args' });
|
|
165
|
+
}
|
|
166
|
+
if (detach && stop) {
|
|
167
|
+
throw Object.assign(new Error('Pass --detach or --stop, not both.'), { code: 'bad_args' });
|
|
168
|
+
}
|
|
169
|
+
return { command, name, server, code, remote, local, action, post, exec, bearer, detach, stop };
|
|
100
170
|
}
|
|
101
171
|
|
|
102
172
|
/**
|
|
@@ -122,6 +192,9 @@ function flagsFromEnv(env, flags) {
|
|
|
122
192
|
* fetch?: typeof fetch,
|
|
123
193
|
* io?: { stdout: (text: string) => void, stderr: (text: string) => void },
|
|
124
194
|
* machine?: string,
|
|
195
|
+
* spawn?: any,
|
|
196
|
+
* signal?: AbortSignal,
|
|
197
|
+
* onSignals?: (stop: () => void) => void,
|
|
125
198
|
* }} [options]
|
|
126
199
|
* @returns {Promise<{ action: 'exit', code: number } | { action: 'serve', mode: 'local' | 'remote', server: string, name: string }>}
|
|
127
200
|
*/
|
|
@@ -143,9 +216,9 @@ export async function runCli(argv, options = {}) {
|
|
|
143
216
|
io.stdout(HELP);
|
|
144
217
|
return { action: 'exit', code: 0 };
|
|
145
218
|
}
|
|
146
|
-
if (parsed.command
|
|
219
|
+
if (parsed.command !== 'serve') {
|
|
147
220
|
if (parsed.remote || parsed.local) {
|
|
148
|
-
io.stderr(`login, logout, and
|
|
221
|
+
io.stderr(`login, logout, status, wake, and listen do not take --remote or --local.\n${HELP}`);
|
|
149
222
|
return { action: 'exit', code: 1 };
|
|
150
223
|
}
|
|
151
224
|
}
|
|
@@ -191,10 +264,26 @@ export async function runCli(argv, options = {}) {
|
|
|
191
264
|
const saved = await readSavedLogin(env);
|
|
192
265
|
const serverUrl = resolveServerUrl({ flag: parsed.server, env, saved });
|
|
193
266
|
io.stdout(formatLoginStatus(saved, serverUrl));
|
|
267
|
+
io.stdout(await wakeStatusText(env));
|
|
194
268
|
return { action: 'exit', code: 0 };
|
|
195
269
|
}
|
|
270
|
+
if (parsed.command === 'wake') {
|
|
271
|
+
const code = await runWakeCommand(parsed, { env, io, fetch: options.fetch, spawn: options.spawn });
|
|
272
|
+
return { action: 'exit', code };
|
|
273
|
+
}
|
|
274
|
+
if (parsed.command === 'listen') {
|
|
275
|
+
const code = await runListenCommand(parsed, {
|
|
276
|
+
env,
|
|
277
|
+
io,
|
|
278
|
+
fetch: options.fetch,
|
|
279
|
+
spawn: options.spawn,
|
|
280
|
+
signal: options.signal,
|
|
281
|
+
onSignals: options.onSignals,
|
|
282
|
+
});
|
|
283
|
+
return { action: 'exit', code };
|
|
284
|
+
}
|
|
196
285
|
} catch (err) {
|
|
197
|
-
const usage = err?.code === '
|
|
286
|
+
const usage = err?.code === 'bad_server' || (err?.code === 'bad_args' && parsed.command !== 'wake') ? HELP : '';
|
|
198
287
|
io.stderr(`${err?.message || 'Login failed'}\n${usage}`);
|
|
199
288
|
return { action: 'exit', code: 1 };
|
|
200
289
|
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* "The agent is in a turn right now": the time of its last MCP tool call,
|
|
3
|
+
* shared between surfcad-mcp processes on this machine through one small
|
|
4
|
+
* file. The MCP server stamps it on every tool call. The listener reads it
|
|
5
|
+
* before a wake.
|
|
6
|
+
*
|
|
7
|
+
* An agent in a turn is not woken. It reads the message at its next
|
|
8
|
+
* read_messages, as the chat guide requires, and a wake on top of that would
|
|
9
|
+
* start a second turn beside the first (with an exec wake, a second copy of
|
|
10
|
+
* the agent). Once it has made no tool call for AWAKE_MS it counts as idle,
|
|
11
|
+
* the same 60 s after which the tab shows it idle, and an unread message
|
|
12
|
+
* wakes it.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
import { configDir } from '../remote/config.mjs';
|
|
18
|
+
|
|
19
|
+
/** No tool call for this long: the agent is idle and may be woken. */
|
|
20
|
+
export const AWAKE_MS = 60_000;
|
|
21
|
+
/** The stamp is rewritten at most this often. */
|
|
22
|
+
const STAMP_EVERY_MS = 5_000;
|
|
23
|
+
|
|
24
|
+
/** @param {NodeJS.ProcessEnv} [env] */
|
|
25
|
+
export function awakePath(env = process.env) {
|
|
26
|
+
return join(configDir(env), 'awake');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
let lastStampAt = 0;
|
|
30
|
+
let lastStampPath = '';
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Record a tool call. Best effort and throttled: a failure to write must
|
|
34
|
+
* never fail the tool call.
|
|
35
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
36
|
+
* @param {number} [now]
|
|
37
|
+
*/
|
|
38
|
+
export async function stampAwake(env = process.env, now = Date.now()) {
|
|
39
|
+
const path = awakePath(env);
|
|
40
|
+
if (path === lastStampPath && now - lastStampAt < STAMP_EVERY_MS) return;
|
|
41
|
+
lastStampAt = now;
|
|
42
|
+
lastStampPath = path;
|
|
43
|
+
try {
|
|
44
|
+
await mkdir(configDir(env), { recursive: true, mode: 0o700 });
|
|
45
|
+
await writeFile(path, `${now}\n`, { mode: 0o600 });
|
|
46
|
+
} catch {
|
|
47
|
+
/* best effort */
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
53
|
+
* @returns {Promise<number>} ms timestamp of the last tool call, 0 when none is recorded
|
|
54
|
+
*/
|
|
55
|
+
export async function lastAwakeAt(env = process.env) {
|
|
56
|
+
try {
|
|
57
|
+
const at = Number.parseInt((await readFile(awakePath(env), 'utf8')).trim(), 10);
|
|
58
|
+
return Number.isFinite(at) && at > 0 ? at : 0;
|
|
59
|
+
} catch {
|
|
60
|
+
return 0;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
66
|
+
* @param {number} [now]
|
|
67
|
+
*/
|
|
68
|
+
export async function agentAwake(env = process.env, now = Date.now()) {
|
|
69
|
+
const at = await lastAwakeAt(env);
|
|
70
|
+
return at > 0 && now - at >= 0 && now - at < AWAKE_MS;
|
|
71
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One listener per config directory: a pid file, a log file, and a detached
|
|
3
|
+
* start for agents that set the listener up with one command and move on.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { spawn as nodeSpawn } from 'node:child_process';
|
|
7
|
+
import { closeSync, openSync } from 'node:fs';
|
|
8
|
+
import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { configDir } from '../remote/config.mjs';
|
|
12
|
+
|
|
13
|
+
/** @param {NodeJS.ProcessEnv} [env] */
|
|
14
|
+
export function listenerPidPath(env = process.env) {
|
|
15
|
+
return join(configDir(env), 'listener.pid');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** @param {NodeJS.ProcessEnv} [env] */
|
|
19
|
+
export function listenerLogPath(env = process.env) {
|
|
20
|
+
return join(configDir(env), 'listener.log');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param {number} pid
|
|
25
|
+
* @param {(pid: number, signal: number) => void} [kill]
|
|
26
|
+
*/
|
|
27
|
+
export function pidAlive(pid, kill = process.kill.bind(process)) {
|
|
28
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
29
|
+
try {
|
|
30
|
+
kill(pid, 0);
|
|
31
|
+
return true;
|
|
32
|
+
} catch (err) {
|
|
33
|
+
// EPERM: it exists and belongs to someone else. Still alive.
|
|
34
|
+
return Boolean(err && typeof err === 'object' && err.code === 'EPERM');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The pid of the running listener, or null. A pid file left by a listener
|
|
40
|
+
* that died is removed.
|
|
41
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
42
|
+
* @param {{ kill?: (pid: number, signal: number) => void }} [deps]
|
|
43
|
+
* @returns {Promise<number | null>}
|
|
44
|
+
*/
|
|
45
|
+
export async function readListenerPid(env = process.env, deps = {}) {
|
|
46
|
+
let text;
|
|
47
|
+
try {
|
|
48
|
+
text = await readFile(listenerPidPath(env), 'utf8');
|
|
49
|
+
} catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
const pid = Number.parseInt(text.trim(), 10);
|
|
53
|
+
if (pidAlive(pid, deps.kill)) return pid;
|
|
54
|
+
await rm(listenerPidPath(env), { force: true });
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {number} pid
|
|
60
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
61
|
+
*/
|
|
62
|
+
export async function writeListenerPid(pid, env = process.env) {
|
|
63
|
+
const dir = configDir(env);
|
|
64
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
65
|
+
await writeFile(listenerPidPath(env), `${pid}\n`, { mode: 0o600 });
|
|
66
|
+
await chmod(listenerPidPath(env), 0o600);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Remove the pid file if it still names `pid`.
|
|
71
|
+
* @param {number} pid
|
|
72
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
73
|
+
*/
|
|
74
|
+
export async function clearListenerPid(pid, env = process.env) {
|
|
75
|
+
try {
|
|
76
|
+
const text = await readFile(listenerPidPath(env), 'utf8');
|
|
77
|
+
if (Number.parseInt(text.trim(), 10) !== pid) return;
|
|
78
|
+
} catch {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
await rm(listenerPidPath(env), { force: true });
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Start `surfcad-mcp listen` as its own process group with its output in
|
|
86
|
+
* the log file, and return at once.
|
|
87
|
+
* @param {{ env?: NodeJS.ProcessEnv, spawn?: typeof nodeSpawn, bin?: string, args?: string[] }} [options]
|
|
88
|
+
* @returns {Promise<{ pid: number | undefined, log: string }>}
|
|
89
|
+
*/
|
|
90
|
+
export async function startDetachedListener(options = {}) {
|
|
91
|
+
const env = options.env || process.env;
|
|
92
|
+
const spawn = options.spawn || nodeSpawn;
|
|
93
|
+
const bin = options.bin || fileURLToPath(new URL('../../bin/surfcad-mcp.js', import.meta.url));
|
|
94
|
+
const dir = configDir(env);
|
|
95
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
96
|
+
const log = listenerLogPath(env);
|
|
97
|
+
const fd = openSync(log, 'a', 0o600);
|
|
98
|
+
try {
|
|
99
|
+
const child = spawn(process.execPath, [bin, 'listen', ...(options.args || [])], {
|
|
100
|
+
detached: true,
|
|
101
|
+
stdio: ['ignore', fd, fd],
|
|
102
|
+
env,
|
|
103
|
+
windowsHide: true,
|
|
104
|
+
});
|
|
105
|
+
child.unref?.();
|
|
106
|
+
return { pid: child.pid, log };
|
|
107
|
+
} finally {
|
|
108
|
+
closeSync(fd);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
114
|
+
* @param {{ kill?: (pid: number, signal: number | string) => void }} [deps]
|
|
115
|
+
* @returns {Promise<{ stopped: boolean, pid: number | null }>}
|
|
116
|
+
*/
|
|
117
|
+
export async function stopListener(env = process.env, deps = {}) {
|
|
118
|
+
const kill = deps.kill || process.kill.bind(process);
|
|
119
|
+
const pid = await readListenerPid(env, { kill });
|
|
120
|
+
if (!pid) return { stopped: false, pid: null };
|
|
121
|
+
try {
|
|
122
|
+
kill(pid, 'SIGTERM');
|
|
123
|
+
} catch {
|
|
124
|
+
/* gone between the check and the signal */
|
|
125
|
+
}
|
|
126
|
+
await rm(listenerPidPath(env), { force: true });
|
|
127
|
+
return { stopped: true, pid };
|
|
128
|
+
}
|