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 CHANGED
@@ -53,7 +53,7 @@ On Safari, iOS, or a phone-width page, SurfCAD shows a join code. `login --code
53
53
 
54
54
  `login` without `--code` runs device-code pairing against `https://surfcad.com/agent`. It generates 32 random bytes, sends only their SHA-256, prints an `ABCD-EFGH` code and the approval URL (`https://surfcad.com/agent`), then polls with the secret until you approve, deny, or the code expires. The token is written to the config directory at mode 0600 (the directory is 0700). It is not printed and it is not logged. `status` shows the server, name, machine, and saved time, never the token. `logout` calls `DELETE /agent/tokens/self` with that token, then deletes the file. If the server cannot be reached, the file is still deleted and the command says the login may stay valid until it expires.
55
55
 
56
- Sign in on the approval page and enter the code. Leave the SurfCAD tab open. The client connects out over WebSocket (`wss://surfcad.com/agent`) with `Authorization: Bearer`. The first frame is `{ "type": "hello", "v": 1 }`. If WebSocket is blocked, commands fall back to `POST /agent/commands` and then Server-Sent Events, or a long-poll `GET` if the event stream fails. In-viewer prompts travel on the WebSocket.
56
+ Sign in on the approval page and enter the code. Leave the SurfCAD tab open. The client connects out over WebSocket (`wss://surfcad.com/agent`) with `Authorization: Bearer`. The first frame is `{ "type": "hello", "v": 1 }`. If WebSocket is blocked, commands fall back to `POST /agent/commands` and then Server-Sent Events, or a long-poll `GET` if the event stream fails. A finished command's result stays readable by the token that submitted it for 2 minutes (`RESULT_RETENTION_MS` on the server), so that poll still finds a result the failed stream had already been sent; it used to answer `not_found` ("That command is no longer waiting") for a command the tab had run. In-viewer prompts travel on the WebSocket.
57
57
 
58
58
  `--server https://staging.example` or `SURFCAD_AGENT_SERVER` overrides the origin for dev and staging. https becomes `wss://`. `http://` and `ws://` are accepted only for localhost, 127.0.0.1, and ::1.
59
59
 
@@ -77,9 +77,9 @@ Clear failures:
77
77
  3. Add `surfcad-mcp` to your MCP client (`npx surfcad-mcp`), set `SURFCAD_PAIRING_CODE` to that code, or call the MCP **`pair`** tool with `{ "code": "BCDFGHJK" }`.
78
78
  4. Click **Allow** (the green check) in SurfCAD when prompted.
79
79
 
80
- The MCP server instructions start with `call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages.` The next sentence tells the agent: when you finish a task started from the SurfCAD in-viewer prompt pane, send a closing reply with `reply_to_user` (`final: true`) summarising what was done, so the user gets confirmation. On failure or partial completion, say what was done, what failed and why, and what is left. The instructions continue with a quick-start (under 2 KB) that points at the `guide` tool. `guide { topic: "start" }` repeats that closing-reply rule.
80
+ The MCP server instructions start with `call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages.` The next sentence tells the agent: when you finish a task started from the SurfCAD in-viewer prompt pane, send a closing reply with `reply_to_user` (`final: true`) summarising what was done, so the user gets confirmation. On failure or partial completion, say what was done, what failed and why, and what is left. The instructions continue with a quick-start (under 2 KB) that points at the `guide` tool. `guide { topic: "start" }` repeats that closing-reply rule. `guide { topic: "chat" }` is the required in-viewer chat workflow (`register_webhook` after every pair, ack first, the 10 second long-poll while connected); the instructions, the `pair` result, and `start` all point at it.
81
81
 
82
- A successful `pair`, when no webhook is registered yet, returns an onboarding note as text content (a `type: "text"` block, not only `structuredContent` or `_meta`). The note asks the agent to request a webhook URL and key from the user. The key is the `bearer` argument. Suggested wording to relay: "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." If the user declines, the agent polls `read_messages`. This process holds the URL and bearer in memory only, so the agent should save them in its own config or memory and call `register_webhook` again after every pair. If a webhook is already registered when `pair` succeeds, the result omits that note and says the webhook is active.
82
+ A successful `pair`, when no webhook is registered yet, returns an onboarding note as text content (a `type: "text"` block, not only `structuredContent` or `_meta`). The note asks the agent to request a webhook URL and key from the user. The key is the `bearer` argument. Suggested wording to relay: "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." If the user declines, the agent must long-poll `read_messages { wait_ms: 10000 }` in a loop while connected (never neither a webhook nor the poll). This process holds the URL and bearer in memory only, so the agent should save them in its own config or memory and call `register_webhook` again after every pair. If a webhook is already registered when `pair` succeeds, the result omits that note and says the webhook is active.
83
83
 
84
84
  Nothing pairs without your approval.
85
85
 
@@ -111,7 +111,7 @@ In Cursor, add the same block under **Settings → MCP** or your project `.curso
111
111
  claude mcp add surfcad -- npx surfcad-mcp
112
112
  ```
113
113
 
114
- `read_messages { wait_ms }` (up to 25,000 ms) long-polls so an idle agent makes one call every 25 s instead of spinning. A local CLI session usually has no public https endpoint, so polling `read_messages` is the normal path there. Webhooks apply when the user runs a receiver that can take https POSTs. The key they send is the `bearer` argument of `register_webhook`.
114
+ `read_messages { wait_ms }` (up to 25,000 ms) long-polls. The required cycle while connected is `wait_ms: 10000`, called again as soon as it returns: the fallback when no webhook wakes the agent, and the safety net when one is registered. A poll is not activity: it keeps the session connected but does not restart the stall window. A local CLI session usually has no public https endpoint, so polling `read_messages` is the normal path there. Webhooks apply when the user runs a receiver that can take https POSTs. The key they send is the `bearer` argument of `register_webhook`.
115
115
 
116
116
  ## How to build
117
117
 
@@ -165,24 +165,69 @@ These five tools stay inside the local `surfcad-mcp` process. They are not SurfC
165
165
 
166
166
  | Tool | Args | What it does |
167
167
  | --- | --- | --- |
168
- | `register_webhook` | `{ url, bearer? }` | Remember an https URL that receives each user prompt as `POST` JSON `{ "type": "surfcad.prompt", ... }`. Optional `bearer` is sent as `Authorization: Bearer <bearer>` (non-empty, at most 4096 characters, no CR or LF). Rejects `http`, credentials in the URL, localhost, `.local` names, and private or loopback addresses. The URL and bearer are held only in memory, are never logged, are never written to disk, are never returned or put in status, are never sent to the SurfCAD tab, and are cleared on `unregister_webhook` and when the pairing session ends. A cancel of a prompt that was already delivered is POSTed as `{ "type": "cancel", "id" }` with the same bearer and timeout. Stop work on that id. |
168
+ | `register_webhook` | `{ url, bearer? }` | Remember an https URL that receives each user prompt as `POST` JSON `{ "type": "surfcad.prompt", ... }`. Optional `bearer` is sent as `Authorization: Bearer <bearer>` (non-empty, at most 4096 characters, no CR or LF). Rejects `http`, credentials in the URL, localhost, `.local` names, and private or loopback addresses. The URL and bearer are held only in memory, are never logged, are never written to disk, are never returned or put in status, are never sent to the SurfCAD tab, and are cleared on `unregister_webhook` and when the pairing session ends. Required when the host can receive HTTPS callbacks: call it right after every successful pair or login, before waiting for a prompt, and again in every new process. A cancel of a prompt that was already delivered is POSTed as `{ "type": "cancel", "id" }` with the same bearer and timeout. Stop work on that id. |
169
169
  | `unregister_webhook` | `{}` | Drop that URL and bearer. Later prompts are queued. |
170
- | `read_messages` | `{ max?, wait_ms? }` | Return queued prompts, oldest first, and remove them. A screenshot is the next MCP image content block (`image/png`), not part of the text. A cancel item `{ "type": "cancel", "id" }` means the user stopped a prompt you already received and no webhook is registered. Stop work on that id. Every response includes `recent`: the last 50 prompts this session received, oldest first, each `{ id, state }`, in memory only, including on a remote session. 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, so you can recover one after the ack. `status.last` is only the newest. When you finish the task from a prompt you received, close that chat with `reply_to_user`. |
170
+ | `read_messages` | `{ max?, wait_ms? }` | Return queued prompts, oldest first, and remove them. A screenshot is the next MCP image content block (`image/png`), not part of the text. A cancel item `{ "type": "cancel", "id" }` means the user stopped a prompt you already received and no webhook is registered. Stop work on that id. Every response includes `recent`: the last 50 prompts this session received, oldest first, each `{ id, state }`, in memory only, including on a remote session. 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, so you can recover one after the ack. `status.last` is only the newest. `read_messages` is a poll, not activity: with or without `wait_ms` it sends the tab nothing and does not restart the stall window. When you finish the task from a prompt you received, close that chat with `reply_to_user`. |
171
171
  | `reply_to_user` | `{ text, in_reply_to?, final? }` | Plain-text reply for a prompt id this session received. The final reply is expected and closes the task: when you finish a task started from the in-viewer prompt pane, send `reply_to_user` with `final: true` summarising what was done, so the user gets confirmation. On failure or partial completion, say what was done, what failed and why, and what is left. Several replies may share one id, including after `read_messages` has acked it, and the id may come from an earlier process (a fresh `surfcad-mcp` per tool call). `final: true` marks the agent idle. Omit `in_reply_to` to post one plain-text message on this paired session when no prompt is waiting. That note is not a prompt id, is limited to one per second, does not close a prompt, and is shown as text, not HTML. An `in_reply_to` that is not a prompt id is `unknown_prompt` and nothing is sent to the tab. A cancelled id returns `{ "ok": false, "error": "cancelled" }` and is not shown in the tab. |
172
- | `set_status` | `{ state, label?, id? }` | Progress only. It does not close the task; a closing `reply_to_user` does. `state: "responding"` (alias `typing`) keeps the chat open with bouncing dots. `state: "building"` (alias `working`) means you are creating or editing geometry: the chat collapses and the field shows "Agent is working...". Call `building` only once you have everything you need and are actually modeling. Listing parts, faces, edges, or transforms, `status`, and `read_messages` must not use `building`. The legacy boolean `working: true` is `building`. A model-changing tool also enters building if you skip the call. Building stays until the final reply, Stop, or disconnect. No activity for 15 minutes, while responding or building, shows the stall notice and leaves Stop up. With no prompt in flight the tab still shows it: the page keeps a session-level state fed by `set_status`, every model-changing tool call, and `post_progress`, and goes idle 60 s after the last one. A cancelled id returns `{ "ok": false, "error": "cancelled" }`. |
172
+ | `set_status` | `{ state, label?, id? }` | Progress only. It does not close the task; a closing `reply_to_user` does. `state: "responding"` (alias `typing`) is the ack after `read_messages`: call it first, before any other tool, and the chat stays open with bouncing dots. A non-final reply stays visible for 10 seconds. `state: "building"` (alias `working`) means you are creating or editing geometry: after that hold the chat folds and the field shows "Agent is working...". Call `building` only once you have everything you need and are actually modeling. Listing parts, faces, edges, or transforms, `status`, and `read_messages` must not use `building`. The legacy boolean `working: true` is `building`. A model-changing tool also enters building if you skip the call. Building stays until the final reply, Stop, or disconnect. No activity for 15 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. With no prompt in flight the tab still shows it: the page keeps a session-level state fed by `set_status`, every model-changing tool call, and `post_progress`, and goes idle 60 s after the last one. A cancelled id returns `{ "ok": false, "error": "cancelled" }`. |
173
173
 
174
174
  A paired SurfCAD tab sends `agent.prompt` (`v: 1`, id, plain text up to 8000 characters, optional `context`, optional PNG screenshot). On a remote login the same frame arrives on the agent WebSocket, or, when that socket is blocked, from `GET /agent/prompts` (bearer, long-poll). Both paths are accepted the same way. While the agent is present the server holds a prompt until a process reports it taken (`agent.prompt.taken`, sent when `read_messages` returns it or the webhook POST succeeds), offering it to each new socket after hello and once to each pull session (`GET /agent/prompts?session=<id>`), so a one-shot process per tool call does not lose it; the tab hears `queued` at once when no socket is open. A prompt that arrives twice in one process is kept once. One prompt per second. A screenshot over 2 MB is rejected. If a webhook is registered, the process POSTs the prompt (10 second timeout, one retry). When `bearer` was set, that POST includes `Authorization: Bearer <bearer>`. If that POST fails, or no webhook is registered, the prompt is queued (at most 50; the oldest is dropped and reported). The tab gets `agent.prompt.ack` with `delivery` `webhook`, `queued`, or `failed`. Replies and working state go back as `agent.reply` and `agent.status`.
175
175
 
176
176
  When you finish a task started from the in-viewer prompt pane, send a closing reply with `reply_to_user` (`final: true`) summarising what was done, so the user gets confirmation. On failure or partial completion, say what was done, what failed and why, and what is left. `set_status` is for progress and does not close the task. Call `set_status { state: "building" }` only once you have everything you need and are actually creating or editing geometry. Reads stay on responding.
177
177
 
178
+ After `read_messages` returns a prompt, ack first with `set_status { state: "responding", id: <prompt id> }` before any other tool (the bouncing dots; there is no separate ack tool), then one short `reply_to_user` with `final: false`. The tab holds that reply for 10 seconds. Building, `post_progress`, or a model change during the hold waits, then the chat folds and the spinner shows. `final: true` stops the spinner, reopens the chat, and idles. While connected, long-poll `read_messages { wait_ms: 10000 }` in a loop (required with no webhook, the safety net with one), and call `register_webhook` again after every pair. An empty immediate read does not mean the user never sent. `guide { topic: "chat" }` is the whole required workflow.
179
+
178
180
  `reply_to_user` accepts an `in_reply_to` that this process received (queued, delivered by webhook or `read_messages`, or already replied) or a prompt id from an earlier process. Anything that is not a prompt id is an error `unknown_prompt` and no `agent.reply` is sent. Omit `in_reply_to` to post one plain-text `agent.message` on this paired session (no prompt id, one per second). The page drops a reply whose id is not a prompt the user sent, and it draws a session note as text, not HTML. `read_messages` includes `recent`, the last 50 prompts in this session (`{ id, state }`, oldest first, memory only), on a local or remote session. An idle session has `recent: []`. That list stays after the ack, including when the queue is empty. `status.last` is only the newest id.
179
181
 
180
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`.
181
183
 
182
- 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.
183
185
 
184
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.
185
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
+
186
231
  ## Safety and consent
187
232
 
188
233
  - **Commerce:** Agents cannot place orders or drive checkout. Quote/cart/checkout controls are not exposed as MCP tools.
@@ -2,7 +2,7 @@
2
2
  "version": 1,
3
3
  "bridgeVersion": 1,
4
4
  "generatedBy": "npm run export:agent",
5
- "count": 212,
5
+ "count": 213,
6
6
  "$defs": {
7
7
  "status": {
8
8
  "type": "object",
@@ -2534,7 +2534,7 @@
2534
2534
  },
2535
2535
  {
2536
2536
  "name": "mold_fit",
2537
- "description": "Read-only moldability fit for one part mesh, in the part local frame (the same frame as list_faces). Searches bounding-box axes, large planar normals, and an icosphere (about 80 directions, deduped within 5°, d and -d are one axis). The chosen pull has the least occluded undercut area. Scores within max(2% of the part area, 25 mm²) of that best are tied; box axes and large planar normals win the tie over an icosphere sample, and drafted area breaks the rest. Fit is still good (0 undercut regions), fixable (1 to 4), or not_a_fit (5 or more), plus undercutCount, undercutArea, draftedArea, pull, and pullSource. Pass pull [x, y, z] to score that axis instead and keep its sign. The same result includes wall: a local thickness per triangle, nominal (mode, or the median when no thickness dominates the interior band), max, min, mean, median, and thin and thick regions. Thickness below 0.6× nominal is thin and above 1.5× nominal is thick. Wall thickness follows the geometric normal of each triangle. A stamp only flips that side when it points the other way, so one stamp on a curved face does not steer every facet. A triangle whose own normal is within 0.5° of perpendicular to the pull is not an undercut, and an undercut needs another triangle covering that point. A geometric check for later molding slices, not a supplier DFM. parting on the same result classifies every face as core or cavity by complete visibility (core along +pull, cavity along -pull). A wall within 0.5° of vertical takes the role of the labelled neighbour it can reach. There is no zero-draft class. One outer parting loop is kept. Stamped edges keep their names. On the same result, sideActions lists each block: a slide, a lifter, or an unresolved undercut. A block is one piece of steel that forms a connected set of trapped faces and withdraws along one direction. Every trapped feature that shares a direction on one connected surface is one block, whatever the gap between the features, so two holes on one wall are one slide. Each block carries pull (its withdraw direction, never the main pull axis), area (the block face it forms, which includes untrapped surface inside its window), trappedArea, window, span along the main pull, features (the stamped blocks it carries) and frees (the stamped faces it forms). A slide withdraws in the parting plane. A lifter withdraws tilted 15° to 25° into the core, and only when that tilt leaves the part without entering material. An unresolved undercut has no straight direction that frees it (a slot whose ends narrow toward the outer face); it needs a modelling change or a special mechanism. count is every block, slides, lifters and unresolved undercuts, and is what the report prices. A wall within 0.5° of vertical is not a side action. Undercuts are first refined to analysis cells of about 1.5 mm so a trapped footprint is the shadow of the feature, not the whole modelling triangle. count, slideCount, lifterCount and unresolvedCount are the numbers the mold report reads. moldDraft on the same result classifies every face, including fillets, by signed draft against that pull. The angle is the geometric normal of each triangle, so a stamp on a curved face does not drop it. Positive draft means the face normal points along the pull (the inside walls of a tray, the flange top). Negative draft means it points against the pull (the outside walls of a tray, the bottom). A face drafted at exactly the threshold passes (0.01° tolerance), and a planar stamped face takes one angle for the whole face. At the default 1° threshold each face is positive, negative, or below. Classified area is the whole mesh. below keeps a positive or negative sign. A vertical wall is below and its sign stays positive. There is no zero-draft class. It does not edit CAD draft. Molding rules: guide { topic: \"molding\" }.",
2537
+ "description": "Read-only moldability fit for one part mesh, in the part local frame (the same frame as list_faces). Searches bounding-box axes, large planar normals, and an icosphere (about 80 directions, deduped within 5°, d and -d are one axis). The chosen pull has the least occluded undercut area. Scores within max(2% of the part area, 25 mm²) of that best are tied; box axes and large planar normals win the tie over an icosphere sample, and drafted area breaks the rest. Fit is still good (0 undercut regions), fixable (1 to 4), or not_a_fit (5 or more), plus undercutCount, undercutArea, draftedArea, pull, and pullSource. Pass pull [x, y, z] to score that axis instead and keep its sign. The same result includes wall: a local thickness per triangle, nominal (mode, or the median when no thickness dominates the interior band), max, min, mean, median, and thin and thick regions. Thickness below 0.6× nominal is thin and above 1.5× nominal is thick. Wall thickness follows the geometric normal of each triangle. A stamp only flips that side when it points the other way, so one stamp on a curved face does not steer every facet. A triangle whose own normal is within 0.5° of perpendicular to the pull is not an undercut, and an undercut needs another triangle covering that point. A geometric check for later molding slices, not a supplier DFM. parting on the same result classifies every face as core or cavity by complete visibility (core along +pull, cavity along -pull). A wall within 0.5° of vertical takes the role of the labelled neighbour it can reach. There is no zero-draft class. One outer parting loop is kept. Stamped edges keep their names. On the same result, sideActions lists each block: a slide, a lifter, or an unresolved undercut. A block is one piece of steel that forms a connected set of trapped faces and withdraws along one direction. Every trapped feature that shares a direction on one connected surface is one block, whatever the gap between the features, so two holes on one wall are one slide. Each block carries pull (its withdraw direction, never the main pull axis), area (the block face it forms, which includes untrapped surface inside its window), trappedArea, window, span along the main pull, features (the stamped blocks it carries) and frees (the stamped faces it forms). A slide withdraws in the parting plane. A lifter withdraws tilted 15° to 25° into the core, and only when that tilt leaves the part without entering material. An unresolved undercut has no straight direction that frees it (a slot whose ends narrow toward the outer face); it needs a modelling change or a special mechanism. count is every block, slides, lifters and unresolved undercuts, and is what the report prices. A wall within 0.5° of vertical is not a side action. Undercuts are first refined to analysis cells of about 1.5 mm so a trapped footprint is the shadow of the feature, not the whole modelling triangle. count, slideCount, lifterCount and unresolvedCount are the numbers the mold report reads. moldDraft on the same result classifies every face, including fillets, by signed draft against that pull. The angle is the geometric normal of each triangle, so a stamp on a curved face does not drop it. Positive draft means the face normal points along the pull (the inside walls of a tray, the flange top). Negative draft means it points against the pull (the outside walls of a tray, the bottom). A face drafted at exactly the threshold passes (0.01° tolerance), and a planar stamped face takes one angle for the whole face. At the default 1° threshold each face is positive, negative, or below. Classified area is the whole mesh. below keeps a positive or negative sign. A vertical wall is below and its sign stays positive. There is no zero-draft class. It does not edit CAD draft. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2538
2538
  "args": {
2539
2539
  "type": "object",
2540
2540
  "additionalProperties": false,
@@ -2577,9 +2577,45 @@
2577
2577
  ]
2578
2578
  }
2579
2579
  },
2580
+ {
2581
+ "name": "mold_status",
2582
+ "description": "The next heartbeat or the final result of a mold_* analysis that answered { status: \"running\", jobId }. It waits up to about 30 s for the analysis, then answers either the result the original call would have returned (plus jobId) or another heartbeat { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec?, message }. A heartbeat is not a result: it has no fit, wall, or report fields. Call it again until status is not running. The analysis keeps running in the tab between calls and is never restarted; keep the SurfCAD tab in the foreground. Read-only and immediate. unknown_job: no analysis with that id ran past the budget in this tab (a mold_* call answers its result directly when it finishes in time), or it finished more than 10 minutes ago.",
2583
+ "args": {
2584
+ "type": "object",
2585
+ "additionalProperties": false,
2586
+ "required": [
2587
+ "job_id"
2588
+ ],
2589
+ "properties": {
2590
+ "job_id": {
2591
+ "type": "string",
2592
+ "description": "jobId from a mold_* call that answered status running"
2593
+ }
2594
+ }
2595
+ },
2596
+ "result": {
2597
+ "type": "object",
2598
+ "additionalProperties": true
2599
+ },
2600
+ "errors": [
2601
+ "bad_args",
2602
+ "unknown_job",
2603
+ "no_mesh",
2604
+ "internal"
2605
+ ],
2606
+ "mutates": false,
2607
+ "destructive": false,
2608
+ "confirm": false,
2609
+ "group": "measure",
2610
+ "immediate": true,
2611
+ "uiEntry": null,
2612
+ "example": {
2613
+ "job_id": "mold-1-abc"
2614
+ }
2615
+ },
2580
2616
  {
2581
2617
  "name": "mold_pull",
2582
- "description": "Set the shared pull reference used by core/cavity (including side actions) and mold draft. mode auto searches icosphere and planar candidates, minimizing occluded undercut area and then maximizing drafted area. mode plane uses Top (+Z), Front (+Y), or Right (+X). mode face uses normal [x, y, z] in the part local frame and keeps its sign. Changing it recomputes those from the same pull. Read-only. It does not edit CAD draft. Molding rules: guide { topic: \"molding\" }.",
2618
+ "description": "Set the shared pull reference used by core/cavity (including side actions) and mold draft. mode auto searches icosphere and planar candidates, minimizing occluded undercut area and then maximizing drafted area. mode plane uses Top (+Z), Front (+Y), or Right (+X). mode face uses normal [x, y, z] in the part local frame and keeps its sign. Changing it recomputes those from the same pull. Read-only. It does not edit CAD draft. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2583
2619
  "args": {
2584
2620
  "type": "object",
2585
2621
  "additionalProperties": false,
@@ -2645,7 +2681,7 @@
2645
2681
  },
2646
2682
  {
2647
2683
  "name": "mold_wall_map",
2648
- "description": "Show or hide the wall-thickness heatmap on the active part, in the part local frame. on true paints each triangle with the viridis ramp from thin (0.6× nominal) through nominal to thick (1.5× nominal) and shows that legend. on false removes the skin so face paint and the part colour show again. Omit on to toggle. Read-only. A geometric view of the mold-analysis wall field, not a stress plot and not a quote. Molding rules: guide { topic: \"molding\" }.",
2684
+ "description": "Show or hide the wall-thickness heatmap on the active part, in the part local frame. on true paints each triangle with the viridis ramp from thin (0.6× nominal) through nominal to thick (1.5× nominal) and shows that legend. on false removes the skin so face paint and the part colour show again. Omit on to toggle. Read-only. A geometric view of the mold-analysis wall field, not a stress plot and not a quote. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2649
2685
  "args": {
2650
2686
  "type": "object",
2651
2687
  "additionalProperties": false,
@@ -2676,7 +2712,7 @@
2676
2712
  },
2677
2713
  {
2678
2714
  "name": "mold_parting",
2679
- "description": "Show or hide the core, cavity, and side-action colours on the active part, in the part local frame. on true classifies every face from the mold-analysis pull by complete visibility (core along +pull, cavity along -pull) and paints a true undercut as a side action. A wall within 0.5° of vertical is still core or cavity: it takes the role of the labelled neighbour it can reach, so an inner pocket wall joins the core and an outer wall joins the cavity. There is no separate zero-draft colour. The outer parting loop is a polyline. Stamped faces keep their edge names on that loop. sideActions lists each block: a slide, a lifter, or an unresolved undercut. A block is one piece of steel that forms a connected set of trapped faces and withdraws along one direction. Every trapped feature that shares a direction on one connected surface is one block, whatever the gap between the features, so two holes on one wall are one slide. Each block carries pull (its withdraw direction, never the main pull axis), area (the block face it forms, which includes untrapped surface inside its window), trappedArea, window, span along the main pull, features (the stamped blocks it carries) and frees (the stamped faces it forms). A slide withdraws in the parting plane. A lifter withdraws tilted 15° to 25° into the core, and only when that tilt leaves the part without entering material. An unresolved undercut has no straight direction that frees it (a slot whose ends narrow toward the outer face); it needs a modelling change or a special mechanism. count is every block, slides, lifters and unresolved undercuts, and is what the report prices. group highlights one block. on false removes the skin so face paint and the part colour show again. Omit on to toggle. Read-only. Not a CAD draft edit and not a quote. Molding rules: guide { topic: \"molding\" }.",
2715
+ "description": "Show or hide the core, cavity, and side-action colours on the active part, in the part local frame. on true classifies every face from the mold-analysis pull by complete visibility (core along +pull, cavity along -pull) and paints a true undercut as a side action. A wall within 0.5° of vertical is still core or cavity: it takes the role of the labelled neighbour it can reach, so an inner pocket wall joins the core and an outer wall joins the cavity. There is no separate zero-draft colour. The outer parting loop is a polyline. Stamped faces keep their edge names on that loop. sideActions lists each block: a slide, a lifter, or an unresolved undercut. A block is one piece of steel that forms a connected set of trapped faces and withdraws along one direction. Every trapped feature that shares a direction on one connected surface is one block, whatever the gap between the features, so two holes on one wall are one slide. Each block carries pull (its withdraw direction, never the main pull axis), area (the block face it forms, which includes untrapped surface inside its window), trappedArea, window, span along the main pull, features (the stamped blocks it carries) and frees (the stamped faces it forms). A slide withdraws in the parting plane. A lifter withdraws tilted 15° to 25° into the core, and only when that tilt leaves the part without entering material. An unresolved undercut has no straight direction that frees it (a slot whose ends narrow toward the outer face); it needs a modelling change or a special mechanism. count is every block, slides, lifters and unresolved undercuts, and is what the report prices. group highlights one block. on false removes the skin so face paint and the part colour show again. Omit on to toggle. Read-only. Not a CAD draft edit and not a quote. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2680
2716
  "args": {
2681
2717
  "type": "object",
2682
2718
  "additionalProperties": false,
@@ -2716,7 +2752,7 @@
2716
2752
  },
2717
2753
  {
2718
2754
  "name": "mold_side_actions",
2719
- "description": "Alias of mold_parting for side actions. on true, or omit on, opens the core and cavity colouring and returns the same block list and counts (slides, lifters, unresolved undercuts), each with its withdraw direction and face area. replacedBy is mold_parting. on false does not hide that colouring; the message names mold_parting { on: false }. A wall within 0.5° of vertical is not a side action. The withdraw direction is never the pull axis. group highlights one block. Read-only. Not mold CAD and not a quote. Molding rules: guide { topic: \"molding\" }.",
2755
+ "description": "Alias of mold_parting for side actions. on true, or omit on, opens the core and cavity colouring and returns the same block list and counts (slides, lifters, unresolved undercuts), each with its withdraw direction and face area. replacedBy is mold_parting. on false does not hide that colouring; the message names mold_parting { on: false }. A wall within 0.5° of vertical is not a side action. The withdraw direction is never the pull axis. group highlights one block. Read-only. Not mold CAD and not a quote. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2720
2756
  "args": {
2721
2757
  "type": "object",
2722
2758
  "additionalProperties": false,
@@ -2754,7 +2790,7 @@
2754
2790
  },
2755
2791
  {
2756
2792
  "name": "mold_draft",
2757
- "description": "Show or hide signed mold draft on the active part, in the part local frame. on true classifies every face, including fillets and blend faces, against the mold-analysis pull. The angle is the geometric normal of that triangle. A stamped face normal is one average and does not drop the face. Positive draft means the face normal points along the pull (the inside walls of a tray, the flange top). Negative draft means it points against the pull (the outside walls of a tray, the bottom); the sign is asin(n · pull), not which mould half forms the face. A planar stamped face takes one angle for the whole face, and a wall drafted at exactly the threshold passes (0.01° tolerance). threshold is degrees in (0, 90]; the pane offers 0.5, 1, 2, 3, and 5, and 1 is the default. A face at or above the threshold is positive when the sign is positive, and negative when the sign is negative. Tops and bottoms are classified with the same three classes. Classified area is the whole mesh. Absolute draft below the threshold is below, and that bucket still splits positive and negative so a locked-steel check can see the sign. A vertical wall is below and its sign stays positive. There is no zero-draft class. Positive at or above the threshold uses the cavity colour. Negative at or above the threshold uses the core colour. Below the threshold is a red hatch. The result reports positive, negative, and below, each with count and area. below.positive and below.negative are the sign split. violations is the below count. Changing threshold rebuckets the stored field and does not measure the mesh again. on false removes the skin so face paint and the part colour show again. Omit on to toggle. Pass threshold without on to show at that threshold. Read-only. Not CAD draft mode, not an automatic draft fix, and not a quote. Molding rules: guide { topic: \"molding\" }.",
2793
+ "description": "Show or hide signed mold draft on the active part, in the part local frame. on true classifies every face, including fillets and blend faces, against the mold-analysis pull. The angle is the geometric normal of that triangle. A stamped face normal is one average and does not drop the face. Positive draft means the face normal points along the pull (the inside walls of a tray, the flange top). Negative draft means it points against the pull (the outside walls of a tray, the bottom); the sign is asin(n · pull), not which mould half forms the face. A planar stamped face takes one angle for the whole face, and a wall drafted at exactly the threshold passes (0.01° tolerance). threshold is degrees in (0, 90]; the pane offers 0.5, 1, 2, 3, and 5, and 1 is the default. A face at or above the threshold is positive when the sign is positive, and negative when the sign is negative. Tops and bottoms are classified with the same three classes. Classified area is the whole mesh. Absolute draft below the threshold is below, and that bucket still splits positive and negative so a locked-steel check can see the sign. A vertical wall is below and its sign stays positive. There is no zero-draft class. Positive at or above the threshold uses the cavity colour. Negative at or above the threshold uses the core colour. Below the threshold is a red hatch. The result reports positive, negative, and below, each with count and area. below.positive and below.negative are the sign split. violations is the below count. Changing threshold rebuckets the stored field and does not measure the mesh again. on false removes the skin so face paint and the part colour show again. Omit on to toggle. Pass threshold without on to show at that threshold. Read-only. Not CAD draft mode, not an automatic draft fix, and not a quote. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2758
2794
  "args": {
2759
2795
  "type": "object",
2760
2796
  "additionalProperties": false,
@@ -2794,7 +2830,7 @@
2794
2830
  },
2795
2831
  {
2796
2832
  "name": "mold_dfm",
2797
- "description": "Show or hide the mold report for the active part, in the part local frame. on true measures volume, projected area along the pull, and the side-action count, then returns part mass, press tonnage, tooling, and part price for grade and quantity. Mass is volume times the published resin density. Tooling is the published rate card: a base mold cost scaled by projected area, plus a per-side-action adder. Part price is material cost plus press time at the card machine rate plus tooling divided by quantity. assumptions lists the rates, sources, as-of dates, and formulas. A grade with no density or price, or a part with no wall or projected area, is flagged and not guessed. A priced catalog, when one is passed in, still prices from that catalog. The same function fills the pane and the spreadsheet. The resin default is PC/ABS. Press tonnage is the required tonnage of the measured projected area. The report says Mold report and Budgetary, not binding. It does not paint a skin. Opening it clears the other molding tools. on false closes the panel. Omit on to toggle. Read-only. Molding rules: guide { topic: \"molding\" }.",
2833
+ "description": "Show or hide the mold report for the active part, in the part local frame. on true measures volume, projected area along the pull, and the side-action count, then returns part mass, press tonnage, tooling, and part price for grade and quantity. Mass is volume times the published resin density. Tooling is the published rate card: a base mold cost scaled by projected area, plus a per-side-action adder. Part price is material cost plus press time at the card machine rate plus tooling divided by quantity. assumptions lists the rates, sources, as-of dates, and formulas. A grade with no density or price, or a part with no wall or projected area, is flagged and not guessed. A priced catalog, when one is passed in, still prices from that catalog. The same function fills the pane and the spreadsheet. The resin default is PC/ABS. Press tonnage is the required tonnage of the measured projected area. The report says Mold report and Budgetary, not binding. It does not paint a skin. Opening it clears the other molding tools. on false closes the panel. Omit on to toggle. Read-only. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2798
2834
  "args": {
2799
2835
  "type": "object",
2800
2836
  "additionalProperties": false,
@@ -2836,7 +2872,7 @@
2836
2872
  },
2837
2873
  {
2838
2874
  "name": "mold_quote",
2839
- "description": "Show or hide the mold report for the active part. This is the same report as mold_dfm, including part mass, the published tooling estimate, part price, and assumptions (rates, sources, as-of dates, and formulas). on true measures the mesh and returns volume, projected area, side-action count, and those estimates for grade, quantity, and cavityCount. Part price is material cost plus press time plus tooling divided by quantity. cavityCount stays in the costing call and does not scale the published rate card. It is not a control in the pane. A missing density, price, area, or wall is flagged and not guessed. A priced catalog, when one is passed in, still prices from that catalog. on false closes the panel. Omit on to toggle. It does not paint a skin and it does not place an order. Read-only. Molding rules: guide { topic: \"molding\" }.",
2875
+ "description": "Show or hide the mold report for the active part. This is the same report as mold_dfm, including part mass, the published tooling estimate, part price, and assumptions (rates, sources, as-of dates, and formulas). on true measures the mesh and returns volume, projected area, side-action count, and those estimates for grade, quantity, and cavityCount. Part price is material cost plus press time plus tooling divided by quantity. cavityCount stays in the costing call and does not scale the published rate card. It is not a control in the pane. A missing density, price, area, or wall is flagged and not guessed. A priced catalog, when one is passed in, still prices from that catalog. on false closes the panel. Omit on to toggle. It does not paint a skin and it does not place an order. Read-only. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2840
2876
  "args": {
2841
2877
  "type": "object",
2842
2878
  "additionalProperties": false,
@@ -5564,7 +5600,7 @@
5564
5600
  },
5565
5601
  {
5566
5602
  "name": "insert_fillet_edges",
5567
- "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: shell first, then concave fillets, then convex fillets (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).",
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).",
5568
5604
  "args": {
5569
5605
  "type": "object",
5570
5606
  "additionalProperties": false,
@@ -5857,7 +5893,7 @@
5857
5893
  },
5858
5894
  {
5859
5895
  "name": "insert_chamfer_edges",
5860
- "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. 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).",
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).",
5861
5897
  "args": {
5862
5898
  "type": "object",
5863
5899
  "additionalProperties": false,
@@ -8856,7 +8892,7 @@
8856
8892
  },
8857
8893
  {
8858
8894
  "name": "insert_shell",
8859
- "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. Order: shell first, then concave fillets, then convex fillets (guide { topic: \"modeling\" }). Writes (defaults): part = hollow(part, 2.5, 'z'); Takes return: \"status\" | \"summary\" | \"full\" (MCP default \"status\": status.script is omitted; \"summary\" adds status.features; \"full\" echoes the script).",
8895
+ "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. Order (required): shell before any fillet or chamfer; blending every convex edge first leaves several bodies. openScope opens every face that faces that way (default \"z\"): when a post, boss or flange stands on such a face, open the other side (\"-z\") or use \"none\". status.bodyCount must be 1 straight after the shell (guide { topic: \"modeling\" }). Writes (defaults): part = hollow(part, 2.5, 'z'); Takes return: \"status\" | \"summary\" | \"full\" (MCP default \"status\": status.script is omitted; \"summary\" adds status.features; \"full\" echoes the script).",
8860
8896
  "args": {
8861
8897
  "type": "object",
8862
8898
  "additionalProperties": false,
package/data/helpers.json CHANGED
@@ -1103,7 +1103,7 @@
1103
1103
  }
1104
1104
  ],
1105
1105
  "description": "chamferEdges(part, edges, c) — equal-leg 45° chamfer c on a SET of straight convex edges. ",
1106
- "doc": "chamferEdges(part, edges, c) — equal-leg 45° chamfer c on a SET of straight\nconvex edges. Edges = objects from c4MeshData/convexEdges, or a plain\n[{va, vb, n0, n1}] array. n0/n1 (outward normals of the two adjacent faces\nat that edge) are REQUIRED for hand-built edges, but are AUTO-DERIVED from\nthe current mesh when the edge object carries {faces: [i0, i1]} (as all\nc4MeshData-based selectors do: convexEdges, edgesByOrientation,\nedgesByNormal, planarFaceAt-derived selections) — no more\n\"Cannot read properties of undefined (reading '0')\" when mixing selectors\nwith chamferEdges.\n\nConstruction (verified, C2 pilot + C4): per edge, cutter = hull of the two\nedge endpoints plus four corner points pulled c into each adjacent face\ninterior. c IS THE LEG LENGTH along each adjacent face (CAD \"C2\" = 2 mm\non both legs), NOT the perpendicular face offset — the perpendicular\noffset is derived from the face-to-face angle (offset = c·tan(θ/2), θ =\nangle between n0/n1; at a 90° corner they coincide, at a 120° hex-nut\ncorner C2 → 1.155 mm offset / 2 mm legs). CUTTERS ARE APPLIED SEQUENTIALLY (one difference per edge) and\neach intermediate result is checked: a single degenerate cutter (e.g. at\na triple-junction rib-base edge where the two \"adjacent faces\" are coplanar\nor the cutter self-intersects) must not be allowed to wedge the batch\nunion into a wasm out-of-bounds trap (observed: chamfering ALL convex\nedges of a ribbed plate — one subset crashes the kernel while the rest\nbuild fine). The first bad edge throws a named, actionable error instead.\nCost: n differences instead of 1 — fine for the edge counts these parts\nactually use (≤ ~30); the C8 timeout guard catches anything pathological.\nA chamfer that splits the solid into more bodies than it started with\nthrows. The pieces are not returned.",
1106
+ "doc": "chamferEdges(part, edges, c) — equal-leg 45° chamfer c on a SET of straight\nconvex edges. Edges = objects from c4MeshData/convexEdges, or a plain\n[{va, vb, n0, n1}] array. n0/n1 (outward normals of the two adjacent faces\nat that edge) are REQUIRED for hand-built edges, but are AUTO-DERIVED from\nthe current mesh when the edge object carries {faces: [i0, i1]} (as all\nc4MeshData-based selectors do: convexEdges, edgesByOrientation,\nedgesByNormal, planarFaceAt-derived selections) — no more\n\"Cannot read properties of undefined (reading '0')\" when mixing selectors\nwith chamferEdges.\n\nConstruction (verified, C2 pilot + C4): per edge, cutter = hull of the two\nedge endpoints plus four corner points pulled c into each adjacent face\ninterior. c IS THE LEG LENGTH along each adjacent face (CAD \"C2\" = 2 mm\non both legs), NOT the perpendicular face offset — the perpendicular\noffset is derived from the face-to-face angle (offset = c·tan(θ/2), θ =\nangle between n0/n1; at a 90° corner they coincide, at a 120° hex-nut\ncorner C2 → 1.155 mm offset / 2 mm legs). CUTTERS ARE APPLIED SEQUENTIALLY (one difference per edge) and\neach intermediate result is checked: a single degenerate cutter (e.g. at\na triple-junction rib-base edge where the two \"adjacent faces\" are coplanar\nor the cutter self-intersects) must not be allowed to wedge the batch\nunion into a wasm out-of-bounds trap (observed: chamfering ALL convex\nedges of a ribbed plate — one subset crashes the kernel while the rest\nbuild fine). The first bad edge throws a named, actionable error instead.\nCost: n differences instead of 1 — fine for the edge counts these parts\nactually use (≤ ~30); the C8 timeout guard catches anything pathological.\nA chamfer that splits the solid into more bodies than it started with\nthrows. The pieces are not returned. A component with no volume\n(`_SEAM_DUST_MM3`) is seam dust, not a body: it is dropped and not counted.",
1107
1107
  "examples": [
1108
1108
  "part = chamferEdges(part, convexEdges(part), 2);"
1109
1109
  ]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "surfcad-mcp",
3
- "version": "0.3.6",
3
+ "version": "0.3.8",
4
4
  "description": "SurfCAD agent bridge MCP server (stdio) — pairs to a browser tab via the local WebSocket relay, or a saved remote login",
5
5
  "license": "Apache-2.0",
6
6
  "author": "artur0x0",
package/src/cli.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  /**
2
- * `surfcad-mcp` argv. login / logout / status exit. Anything else starts
3
- * the stdio server. The token is never written to stdout or stderr.
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 status.'), { code: 'bad_args' });
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
- return { command, name, server, code, remote, local };
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 === 'login' || parsed.command === 'logout' || parsed.command === 'status') {
219
+ if (parsed.command !== 'serve') {
147
220
  if (parsed.remote || parsed.local) {
148
- io.stderr(`login, logout, and status do not take --remote or --local.\n${HELP}`);
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 === 'bad_args' || err?.code === 'bad_server' ? HELP : '';
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
  }