surfcad-mcp 0.3.9 → 0.4.1

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.
Files changed (44) hide show
  1. package/README.md +71 -50
  2. package/bin/surfcad-mcp.js +16 -8
  3. package/data/commands.json +6481 -5817
  4. package/data/helpers.json +243 -268
  5. package/package.json +10 -2
  6. package/src/cli.mjs +296 -23
  7. package/src/cliCall.mjs +221 -0
  8. package/src/errors.mjs +8 -5
  9. package/src/helpers.mjs +7 -5
  10. package/src/importFile.mjs +186 -0
  11. package/src/listen/bootstrap.mjs +87 -34
  12. package/src/listen/claudeCodeWake.mjs +74 -0
  13. package/src/listen/daemon.mjs +35 -0
  14. package/src/listen/listenCli.mjs +121 -30
  15. package/src/listen/listener.mjs +138 -8
  16. package/src/listen/owner.mjs +293 -0
  17. package/src/listen/waitCli.mjs +133 -0
  18. package/src/listen/wake.mjs +39 -19
  19. package/src/listen/wakeSetupText.mjs +23 -5
  20. package/src/pairWait.mjs +3 -3
  21. package/src/pairingCode.mjs +10 -0
  22. package/src/prompt/buildGuidance.mjs +9 -7
  23. package/src/prompt/chatFlow.mjs +15 -0
  24. package/src/prompt/errorHints.mjs +24 -10
  25. package/src/prompt/guide.mjs +27 -14
  26. package/src/prompt/promptSession.mjs +74 -10
  27. package/src/prompt/promptTools.mjs +10 -6
  28. package/src/prompt/replyConfirm.mjs +69 -0
  29. package/src/relayMessages.mjs +43 -1
  30. package/src/remote/config.mjs +17 -13
  31. package/src/remote/session.mjs +103 -5
  32. package/src/room/roomRuntime.mjs +186 -0
  33. package/src/room/roomServer.mjs +112 -0
  34. package/src/room/roomToolSchemas.mjs +228 -0
  35. package/src/room/seat.mjs +334 -0
  36. package/src/screenshotFile.mjs +9 -0
  37. package/src/server.mjs +155 -111
  38. package/src/stepUploadLimit.mjs +8 -0
  39. package/src/bridge/bridgePage.mjs +0 -132
  40. package/src/bridge/bridgePopup.mjs +0 -288
  41. package/src/bridge/relayHub.mjs +0 -556
  42. package/src/bridge/relayServer.mjs +0 -291
  43. package/src/nodeClient.mjs +0 -63
  44. package/src/relay.mjs +0 -419
package/src/errors.mjs CHANGED
@@ -20,7 +20,7 @@ export function formatBridgeError(err) {
20
20
  export function notPairedError() {
21
21
  return {
22
22
  code: 'not_paired',
23
- message: 'Not paired to a SurfCAD tab. Set SURFCAD_PAIRING_CODE or call the pair tool and click Allow, or run npx surfcad-mcp login --code with the join code.',
23
+ message: 'Not paired to a SurfCAD tab. Run npx surfcad-mcp login --code with the join code from Connect Agent, then call pair {}.',
24
24
  hint: pairingEnvHint(),
25
25
  };
26
26
  }
@@ -38,13 +38,13 @@ export function pairingLostError(reason) {
38
38
 
39
39
  export function pairPendingError() {
40
40
  return Object.assign(
41
- new Error('Waiting for Allow in SurfCAD. Click Allow in the app, then retry.'),
42
- { code: 'pair_pending', hint: 'The pairing request is still open in the SurfCAD tab.', retryable: true },
41
+ new Error('The saved login is still connecting. Keep the SurfCAD tab open, then retry pair {}.'),
42
+ { code: 'pair_pending', hint: 'The saved login is still connecting. Keep the SurfCAD tab open, then retry pair {}.', retryable: true },
43
43
  );
44
44
  }
45
45
 
46
46
  export function pairingEnvHint() {
47
- return 'Copy the 8-character code from SurfCAD → Local agent → Show pairing code, or run npx surfcad-mcp login --code with the join code.';
47
+ return 'Run npx surfcad-mcp login --code with the join code from Connect Agent (ABCD-EFGH; the hyphen is optional), then call pair {}.';
48
48
  }
49
49
 
50
50
  export function tabAsleepError() {
@@ -138,7 +138,7 @@ export function asRemoteError(error) {
138
138
  ) return error;
139
139
  }
140
140
  const record = error && typeof error === 'object'
141
- ? /** @type {{ code?: unknown, message?: unknown }} */ (error)
141
+ ? /** @type {{ code?: unknown, message?: unknown, details?: unknown, hint?: unknown, retryable?: unknown }} */ (error)
142
142
  : {};
143
143
  const code = typeof record.code === 'string' ? record.code : (typeof error === 'string' ? error : '');
144
144
  const message = typeof record.message === 'string'
@@ -162,5 +162,8 @@ export function asRemoteError(error) {
162
162
  if (error instanceof Error) return error;
163
163
  return Object.assign(new Error(message || 'Bridge call failed'), {
164
164
  code: code || 'bridge_error',
165
+ ...(record.details !== undefined ? { details: record.details } : {}),
166
+ ...(typeof record.hint === 'string' ? { hint: record.hint } : {}),
167
+ ...(record.retryable !== undefined ? { retryable: record.retryable } : {}),
165
168
  });
166
169
  }
package/src/helpers.mjs CHANGED
@@ -21,11 +21,11 @@ export const LIST_HELPERS_TOOL_NAME = 'list_helpers';
21
21
  */
22
22
  export const HELPER_GROUPS = Object.freeze({
23
23
  blocks: ['roundedBox', 'tube', 'rectTube', 'hexPrism', 'sheetMetalSolid'],
24
- shapes: ['makeCrossSection', 'solveContour', 'profileCircle', 'profileRectangle', 'profilePolygon', 'makeExtrude', 'makeRevolve', 'makeLoft', 'loft', 'sweep', 'sweepPoints', 'makeSweepPath', 'rotateContour', 'offsetPlaneFrame'],
25
- build: ['cut', 'hollow', 'shell', 'hole', 'holeSpan', 'cboreHole', 'cskHole', 'clearanceHole', 'tapDrillHole', 'screwBoss', 'holePattern', 'holesOnContour', 'booleanBodies', 'externalBody', 'addDraft', 'draftFaces', 'moveFace', 'deleteFace'],
26
- polish: ['filletEdges', 'chamferEdges', 'filletAlongPath', 'edgesNamed', 'convexEdges', 'concaveEdges', 'signedFeatureEdges', 'edge', 'edgesBetween', 'boundaryEdges'],
24
+ shapes: ['makeCrossSection', 'solveContour', 'profileCircle', 'profileRectangle', 'profilePolygon', 'makeExtrude', 'makeRevolve', 'remapSketchRings', 'makeLoft', 'loft', 'sweep', 'sweepPoints', 'makeSweepPath', 'rotateContour', 'offsetPlaneFrame', 'circleSegments', 'convertEdges', 'offsetContour'],
25
+ build: ['cut', 'hollow', 'shell', 'holeSpan', 'screwBoss', 'bossesOnContour', 'holesOnContour', 'booleanBodies', 'externalBody', 'addDraft', 'draftFaces', 'moveFace', 'deleteFace', 'weld'],
26
+ polish: ['filletEdges', 'chamferEdges', 'filletAlongPath', 'edgesNamed', 'edgeCurves', 'convexEdges', 'concaveEdges', 'signedFeatureEdges', 'edge', 'edgesBetween', 'boundaryEdges'],
27
27
  place: ['move', 'rotateAbout', 'center', 'align', 'mirror', 'array3D', 'polarArray', 'patternOnPoints', 'getDimensions'],
28
- faces: ['faceNames', 'facesNamed', 'edgesOf', 'surfaceOf', 'facesByNormal', 'planarFaceAt', 'edgesByOrientation', 'workplaneFromFace', 'placeInFrame', 'transformByFrame', 'placeOnFace'],
28
+ faces: ['faceNames', 'facesNamed', 'bodyFeatures', 'edgesOf', 'surfaceOf', 'facesByNormal', 'planarFaceAt', 'edgesByOrientation', 'workplaneFromFace', 'placeInFrame', 'transformByFrame', 'placeOnFace'],
29
29
  fasteners: ['fastenerClearanceDia', 'fastenerTapDrillDia', 'fastenerMajorDia', 'listFastenerSizes', 'resolveFastenerSize'],
30
30
  vectors: ['vecAdd', 'vecSub', 'vecMul', 'vecDot', 'vecCross', 'vecNorm', 'vecNormalize', 'sumSqDist'],
31
31
  legacy: ['getScaleRatio'],
@@ -81,7 +81,9 @@ export function shortDescription(helper) {
81
81
  return text;
82
82
  }
83
83
 
84
- const DIALECT_INTRO = `The SurfCAD dialect. A part's script is plain JavaScript over the Manifold kernel plus the helpers below, which the runtime passes in as function parameters (so their names are reserved: never declare them with const, let, class or function). The script sets and returns part; numbers are mm; insert_* tools write one marker block each (see guide features) and their descriptions quote the code they write with default arguments. list_helpers { names: [...] } returns a helper's full doc and examples; list_helpers { group } or { match } lists a slice.`;
84
+ // Under the 1,500-word cap on the dialect topic: every new helper line needs
85
+ // a trim here or in its first doc sentence.
86
+ const DIALECT_INTRO = `The SurfCAD dialect: JavaScript over the Manifold kernel plus these helpers (never declare their names). Scripts set and return part, in mm; insert_* tools write marker blocks; list_helpers { names } has full docs.`;
85
87
 
86
88
  /**
87
89
  * The dialect topic text, rendered from the registry: one signature line per
@@ -0,0 +1,186 @@
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import { basename, resolve } from 'node:path';
3
+ import { STEP_UPLOAD_MAX_BYTES, STEP_UPLOAD_TOO_LARGE } from './stepUploadLimit.mjs';
4
+
5
+ /** Raw bytes per bridge call: 96 KiB is 131072 base64 characters. */
6
+ export const IMPORT_CHUNK_BYTES = 96 * 1024;
7
+ /** STL, OBJ, and 3MF. STEP and STP use STEP_UPLOAD_MAX_BYTES. */
8
+ export const IMPORT_MAX_BYTES = 32 * 1024 * 1024;
9
+ const EXTENSIONS = ['.step', '.stp', '.stl', '.obj', '.3mf'];
10
+
11
+ function isStepName(name) {
12
+ return /\.(step|stp)$/i.test(String(name || ''));
13
+ }
14
+
15
+ /** `limits` is a test hook so a case can stub the byte cap. */
16
+ export function importPathTooLarge(name, size, limits) {
17
+ const step = isStepName(name);
18
+ const limit = step
19
+ ? (limits?.stepMax ?? STEP_UPLOAD_MAX_BYTES)
20
+ : (limits?.meshMax ?? IMPORT_MAX_BYTES);
21
+ if (size > limit) {
22
+ return fail('too_large', step ? STEP_UPLOAD_TOO_LARGE : 'The file is over 32 MiB.');
23
+ }
24
+ return null;
25
+ }
26
+
27
+ function fail(code, message) {
28
+ return { value: { code, message }, isError: true };
29
+ }
30
+
31
+ /**
32
+ * Add the MCP-only `path` option to import_model. The browser catalog does
33
+ * not list it; the file is read on the MCP host and sent in chunks.
34
+ * @param {{ name: string, description?: string, inputSchema?: object }} tool
35
+ */
36
+ export function augmentImportTool(tool) {
37
+ if (!tool || tool.name !== 'import_model') return tool;
38
+ const inputSchema = JSON.parse(JSON.stringify(tool.inputSchema || {
39
+ type: 'object',
40
+ additionalProperties: false,
41
+ properties: {},
42
+ }));
43
+ inputSchema.properties = {
44
+ ...(inputSchema.properties || {}),
45
+ path: {
46
+ type: 'string',
47
+ description: 'A model file on the MCP host (.step or .stp up to 200 MB, .stl, .obj, or .3mf up to 32 MiB). The server reads it and uploads it in chunks, so data, total, index and upload_id are not needed. Never sent to the browser.',
48
+ },
49
+ };
50
+ inputSchema.required = (inputSchema.required || []).filter((key) => key !== 'data');
51
+ return {
52
+ ...tool,
53
+ description: `${tool.description || 'Upload a model file as a new part.'} On the MCP host, prefer { path }: the server reads the file and sends the chunks for you, and the answer is the final { partId, name, script, run }.`,
54
+ inputSchema,
55
+ };
56
+ }
57
+
58
+ /**
59
+ * import_model with `path`: read the file here and send it chunk by chunk.
60
+ * Returns null when the call has no `path`, so the caller forwards it as is.
61
+ * @param {{ call: (name: string, args: object) => Promise<unknown> }} session
62
+ * @param {Record<string, unknown>} args
63
+ */
64
+ export async function callImportFromPath(session, args, limits) {
65
+ const src = args && typeof args === 'object' ? args : {};
66
+ if (!Object.prototype.hasOwnProperty.call(src, 'path')) return null;
67
+ if (typeof src.path !== 'string' || !src.path.trim() || src.path.includes('\0')) {
68
+ return fail('bad_args', 'import_model path must be a file path on the MCP host');
69
+ }
70
+ if (src.data != null || src.upload_id != null) {
71
+ return fail('bad_args', 'import_model takes path or data, not both');
72
+ }
73
+ const file = resolve(src.path.trim());
74
+ const name = typeof src.name === 'string' && src.name.trim() ? src.name.trim() : basename(file);
75
+ if (!EXTENSIONS.some((ext) => name.toLowerCase().endsWith(ext))) {
76
+ return fail('bad_args', `import_model reads ${EXTENSIONS.join(', ')} files`);
77
+ }
78
+ let info;
79
+ try {
80
+ info = await stat(file);
81
+ } catch {
82
+ return fail('not_found', `No file at ${file} on the MCP host`);
83
+ }
84
+ if (!info.isFile()) return fail('bad_args', `${file} is not a file`);
85
+ if (info.size === 0) return fail('bad_args', `${file} is empty`);
86
+ const over = importPathTooLarge(name, info.size, limits);
87
+ if (over) return over;
88
+
89
+ const bytes = await readFile(file);
90
+ const total = Math.ceil(bytes.length / IMPORT_CHUNK_BYTES);
91
+ const extra = {};
92
+ if (src.deflection != null) extra.deflection = src.deflection;
93
+ if (src.return != null) extra.return = src.return;
94
+ let uploadId = null;
95
+ let result = null;
96
+ for (let index = 0; index < total; index += 1) {
97
+ const data = bytes.subarray(index * IMPORT_CHUNK_BYTES, (index + 1) * IMPORT_CHUNK_BYTES).toString('base64');
98
+ const call = index === 0
99
+ ? { name, total, index, data, ...extra }
100
+ : { upload_id: uploadId, index, data, ...(src.return != null ? { return: src.return } : {}) };
101
+ result = await session.call('import_model', call);
102
+ if (index < total - 1) {
103
+ uploadId = result?.upload_id;
104
+ if (typeof uploadId !== 'string' || !uploadId) {
105
+ // The tab refused the chunk; its answer is the error to report.
106
+ return { value: result, isError: false };
107
+ }
108
+ }
109
+ }
110
+ return { value: result, isError: false };
111
+ }
112
+
113
+ const IMAGE_EXTENSIONS = { '.png': 'png', '.jpg': 'jpeg', '.jpeg': 'jpeg' };
114
+ export const BENCH_IMAGE_MAX_BYTES = 8 * 1024 * 1024;
115
+
116
+ /**
117
+ * Add the MCP-only `image_path` option to bench_show: a PNG or JPEG on the
118
+ * MCP host, read here and sent to the tab in chunks.
119
+ * @param {{ name: string, description?: string, inputSchema?: object }} tool
120
+ */
121
+ export function augmentBenchShowTool(tool) {
122
+ if (!tool || tool.name !== 'bench_show') return tool;
123
+ const inputSchema = JSON.parse(JSON.stringify(tool.inputSchema || {
124
+ type: 'object',
125
+ additionalProperties: false,
126
+ properties: {},
127
+ }));
128
+ inputSchema.properties = {
129
+ ...(inputSchema.properties || {}),
130
+ image_path: {
131
+ type: 'string',
132
+ description: 'A PNG or JPEG on the MCP host (up to 8 MiB), for example the fixture drawing. The server reads it and sends the chunks, so image, total, index and upload_id are not needed. Never sent to the browser.',
133
+ },
134
+ };
135
+ return {
136
+ ...tool,
137
+ description: `${tool.description || 'Show the fixture you are on.'} On the MCP host, prefer { image_path } for the image.`,
138
+ inputSchema,
139
+ };
140
+ }
141
+
142
+ /**
143
+ * bench_show with `image_path`: read the image here and send it chunk by
144
+ * chunk. Returns null when the call has no `image_path`.
145
+ * @param {{ call: (name: string, args: object) => Promise<unknown> }} session
146
+ * @param {Record<string, unknown>} args
147
+ */
148
+ export async function callBenchShowFromPath(session, args) {
149
+ const src = args && typeof args === 'object' ? args : {};
150
+ if (!Object.prototype.hasOwnProperty.call(src, 'image_path')) return null;
151
+ if (typeof src.image_path !== 'string' || !src.image_path.trim() || src.image_path.includes('\0')) {
152
+ return fail('bad_args', 'bench_show image_path must be a file path on the MCP host');
153
+ }
154
+ if (src.image != null || src.upload_id != null) {
155
+ return fail('bad_args', 'bench_show takes image_path or image, not both');
156
+ }
157
+ const file = resolve(src.image_path.trim());
158
+ const type = IMAGE_EXTENSIONS[file.slice(file.lastIndexOf('.')).toLowerCase()];
159
+ if (!type) return fail('bad_args', 'bench_show image_path reads .png, .jpg and .jpeg files');
160
+ let info;
161
+ try {
162
+ info = await stat(file);
163
+ } catch {
164
+ return fail('not_found', `No file at ${file} on the MCP host`);
165
+ }
166
+ if (!info.isFile() || info.size === 0) return fail('bad_args', `${file} is not an image file`);
167
+ if (info.size > BENCH_IMAGE_MAX_BYTES) return fail('too_large', 'The image is over 8 MiB.');
168
+
169
+ const bytes = await readFile(file);
170
+ const total = Math.ceil(bytes.length / IMPORT_CHUNK_BYTES);
171
+ const { image_path: _path, ...fields } = src;
172
+ let uploadId = null;
173
+ let result = null;
174
+ for (let index = 0; index < total; index += 1) {
175
+ const image = bytes.subarray(index * IMPORT_CHUNK_BYTES, (index + 1) * IMPORT_CHUNK_BYTES).toString('base64');
176
+ const call = index === 0
177
+ ? { ...fields, image, image_type: type, total, index }
178
+ : { upload_id: uploadId, index, image };
179
+ result = await session.call('bench_show', call);
180
+ if (index < total - 1) {
181
+ uploadId = result?.upload_id;
182
+ if (typeof uploadId !== 'string' || !uploadId) return { value: result, isError: false };
183
+ }
184
+ }
185
+ return { value: result, isError: false };
186
+ }
@@ -14,21 +14,36 @@
14
14
  * saved `surfcad-mcp wake set` was run on this machine (the escape hatch).
15
15
  *
16
16
  * With a wake in hand the bootstrap starts the listener (server relay) and
17
- * greets: it fires the wake once per login with reason "greet", and the
18
- * session that starts says hello in the SurfCAD chat. That greeting is the
19
- * validation. It proves the whole path, wake to host to MCP to tab, with
20
- * something the user can see.
17
+ * checks the wake: it fires it once per login with reason "test". The
18
+ * session that starts calls status once and ends; the user sees nothing.
19
+ * That is the check that the path works, wake to host to MCP.
20
+ *
21
+ * The greeting is not part of this. The SurfCAD tab greets the user itself
22
+ * the moment the pairing lands (src/agent/agentGreeting.js). Until
23
+ * 2026-11-07 the check was a "greet" wake whose session said hello, and a
24
+ * failed or slow POST was not marked done, so every message's fresh session
25
+ * was told to greet again (Artur's phone bug 3: a greeting after every
26
+ * message, two with a picture). The check is marked done before it fires,
27
+ * so it never repeats for a login, whatever the outcome.
21
28
  *
22
29
  * With no wake, nothing is pretended: the state says cold wake is
23
- * unavailable, and the session that paired greets the user itself.
30
+ * unavailable, and the pairing session tells the user once that the setup
31
+ * is still needed.
24
32
  */
25
33
 
34
+ import { listenPaused } from './owner.mjs';
26
35
  import { createHash } from 'node:crypto';
27
36
  import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';
28
37
  import { join } from 'node:path';
29
38
  import { configDir } from '../remote/config.mjs';
30
39
  import { readSavedLogin } from '../remote/tokenStore.mjs';
31
- import { readListenerPid, startDetachedListener } from './daemon.mjs';
40
+ import {
41
+ readListenerLoginMark,
42
+ readListenerPid,
43
+ startDetachedListener,
44
+ stopListener,
45
+ writeListenerLoginMark,
46
+ } from './daemon.mjs';
32
47
  import { createWaker, wakePayload } from './wake.mjs';
33
48
  import {
34
49
  normalizeWakeBearer,
@@ -108,7 +123,7 @@ export function wakeStatePath(env = process.env) {
108
123
  }
109
124
 
110
125
  /** A short one-way mark of a login. Never the token. */
111
- function loginMark(token) {
126
+ export function loginMark(token) {
112
127
  return createHash('sha256').update(String(token || 'local')).digest('hex').slice(0, 16);
113
128
  }
114
129
 
@@ -127,7 +142,7 @@ async function writeState(state, env) {
127
142
  await writeFile(wakeStatePath(env), `${JSON.stringify(state)}\n`, { mode: 0o600 });
128
143
  await chmod(wakeStatePath(env), 0o600);
129
144
  } catch {
130
- /* a greeting sent twice is the worst that happens */
145
+ /* a test wake fired twice is the worst that happens */
131
146
  }
132
147
  }
133
148
 
@@ -138,7 +153,8 @@ async function writeState(state, env) {
138
153
  * listenerRunning: boolean,
139
154
  * listenerStarted: boolean,
140
155
  * coldWake: 'ready' | 'listener_stopped' | 'unavailable',
141
- * greeting: 'sent_by_wake' | 'send_it_yourself' | 'already_sent' | 'wake_failed',
156
+ * wakeCheck: 'fired' | 'not_fired' | 'already_fired' | 'none',
157
+ * userNotice: 'tell_now' | 'later' | 'done' | 'not_needed',
142
158
  * problems: string[],
143
159
  * }} WakeBootstrap
144
160
  */
@@ -148,20 +164,22 @@ async function writeState(state, env) {
148
164
  * @param {{
149
165
  * env?: NodeJS.ProcessEnv,
150
166
  * remote: boolean,
151
- * greet?: boolean,
152
- * selfGreet?: boolean,
167
+ * check?: boolean,
168
+ * tellUser?: boolean,
153
169
  * autoListen?: boolean,
154
170
  * spawn?: any,
155
171
  * fetch?: typeof fetch,
156
172
  * waker?: ReturnType<typeof createWaker>,
157
173
  * startListener?: typeof startDetachedListener,
174
+ * stopListener?: typeof stopListener,
158
175
  * listenerPid?: typeof readListenerPid,
159
176
  * }} options
160
177
  * `remote`: this process is on the server relay (a saved login exists), so
161
- * the listener can run. `greet: false` skips the greeting (a status read).
178
+ * the listener can run. `check: false` skips the test wake (a status read).
162
179
  * `autoListen: false` reports the listener and does not start it.
163
- * `selfGreet: false`: the caller cannot tell a session to greet (the CLI, a
164
- * server start), so with no wake the greeting is left for the next pair.
180
+ * `tellUser: false`: the caller cannot tell a session to say anything (the
181
+ * CLI, a server start), so the one-time "setup still needed" notice is left
182
+ * for the next pair (`userNotice: 'later'`).
165
183
  * @returns {Promise<WakeBootstrap>}
166
184
  */
167
185
  export async function bootstrapWake(options) {
@@ -180,12 +198,44 @@ export async function bootstrapWake(options) {
180
198
  token = '';
181
199
  }
182
200
  listenerRunning = (await listenerPid(env)) != null;
201
+ // A new login revokes the previous token. A listener still running was
202
+ // started with that token (or with none recorded). Leave it and it dies
203
+ // on the next poll, and nothing wakes. Stop it and start one that reads
204
+ // the login just saved. The same login is not restarted.
205
+ if (config && token && listenerRunning && options.autoListen !== false) {
206
+ const mark = await readListenerLoginMark(env);
207
+ if (mark !== loginMark(token)) {
208
+ try {
209
+ await (options.stopListener || stopListener)(env);
210
+ } catch {
211
+ /* a pid that is still alive is reported below */
212
+ }
213
+ try {
214
+ listenerRunning = (await listenerPid(env)) != null;
215
+ } catch {
216
+ listenerRunning = false;
217
+ }
218
+ if (listenerRunning) {
219
+ problems.push('The listener is still on an older login. Run: npx surfcad-mcp listen --stop, then npx surfcad-mcp listen --detach');
220
+ }
221
+ }
222
+ }
183
223
  // A listener with no wake cannot start a turn, so it is not started.
184
- if (config && token && !listenerRunning && options.autoListen !== false) {
224
+ // A paused listener (listen --pause) stays down until listen --resume.
225
+ const paused = await listenPaused(env);
226
+ if (paused) problems.push('The listener is paused (npx surfcad-mcp listen --pause). Run npx surfcad-mcp listen --resume to start it again.');
227
+ if (config && token && !listenerRunning && !paused && options.autoListen !== false) {
185
228
  try {
186
229
  await (options.startListener || startDetachedListener)({ env, spawn: options.spawn });
187
230
  listenerStarted = true;
188
231
  listenerRunning = (await listenerPid(env)) != null;
232
+ if (listenerRunning) {
233
+ try {
234
+ await writeListenerLoginMark(loginMark(token), env);
235
+ } catch {
236
+ /* the listener records its own mark once it is up */
237
+ }
238
+ }
189
239
  } catch {
190
240
  problems.push('The listener could not be started. Run: npx surfcad-mcp listen --detach');
191
241
  }
@@ -199,34 +249,37 @@ export async function bootstrapWake(options) {
199
249
  let coldWake = 'unavailable';
200
250
  if (config) coldWake = !options.remote || listenerRunning ? 'ready' : 'listener_stopped';
201
251
 
202
- // One greeting per login: by the wake when there is one (that is the
203
- // check that it works), else by the session that just paired.
204
- /** @type {WakeBootstrap['greeting']} */
205
- let greeting = 'already_sent';
206
- if (options.greet !== false) {
252
+ // One test wake per login, marked done before it fires so it never
253
+ // repeats whatever the outcome. With no wake there is nothing to check;
254
+ // the pairing session tells the user once that the setup is needed.
255
+ /** @type {WakeBootstrap['wakeCheck']} */
256
+ let wakeCheck = config ? 'already_fired' : 'none';
257
+ /** @type {WakeBootstrap['userNotice']} */
258
+ let userNotice = config ? 'not_needed' : 'done';
259
+ if (options.check !== false) {
207
260
  const mark = loginMark(options.remote ? token : 'local');
208
261
  const state = await readState(env);
209
- if (state.greeted !== mark) {
210
- const done = () => writeState({ ...state, greeted: mark, greetedAt: new Date().toISOString() }, env);
211
- if (!config) {
212
- if (options.selfGreet !== false) {
213
- greeting = 'send_it_yourself';
214
- await done();
215
- }
216
- } else {
262
+ if (config) {
263
+ if (state.checked !== mark) {
264
+ await writeState({ ...state, checked: mark, checkedAt: new Date().toISOString() }, env);
217
265
  const waker = options.waker || createWaker(config, { env, fetch: options.fetch, spawn: options.spawn });
218
- const outcome = await waker.wake(wakePayload([], { reason: 'greet' }));
266
+ const outcome = await waker.wake(wakePayload([], { reason: 'test' }));
219
267
  if (outcome.ok) {
220
- greeting = 'sent_by_wake';
221
- await done();
268
+ wakeCheck = 'fired';
222
269
  } else {
223
- // Not marked: the next pair tries the wake again.
224
- greeting = 'wake_failed';
270
+ wakeCheck = 'not_fired';
225
271
  problems.push(`The wake did not fire (${outcome.error}).`);
226
272
  coldWake = 'unavailable';
227
273
  }
228
274
  }
275
+ } else if (state.toldUnavailable !== mark) {
276
+ if (options.tellUser === false) {
277
+ userNotice = 'later';
278
+ } else {
279
+ userNotice = 'tell_now';
280
+ await writeState({ ...state, toldUnavailable: mark, toldUnavailableAt: new Date().toISOString() }, env);
281
+ }
229
282
  }
230
283
  }
231
- return { forms, source, listenerRunning, listenerStarted, coldWake, greeting, problems };
284
+ return { forms, source, listenerRunning, listenerStarted, coldWake, wakeCheck, userNotice, problems };
232
285
  }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * `surfcad-mcp wake claude-code`: the wake command for Claude Code.
3
+ *
4
+ * Save it once: npx surfcad-mcp wake set --exec "npx -y surfcad-mcp@latest wake claude-code"
5
+ *
6
+ * A wake runs it with the wake JSON on stdin and SURFCAD_WAKE_ACTION /
7
+ * SURFCAD_WAKE_SESSION / SURFCAD_WAKE_CWD in the environment (wake.mjs). It
8
+ * starts one Claude Code turn with the conversation that should answer:
9
+ * resume the chat's owner, whose process is gone: claude -p --resume <id>
10
+ * fork the owner is open but idle: --resume <id> --fork-session, so two
11
+ * processes never write one session; the fork then owns the chat
12
+ * fresh nobody owns the chat: a new session, started from $HOME (inside
13
+ * a repo checkout npx would run that checkout's surfcad-mcp)
14
+ *
15
+ * Optional: CLAUDE_BIN (default claude), SURFCAD_WAKE_ALLOWED_TOOLS (tools
16
+ * the woken turn may use without asking; default the surfcad MCP tools).
17
+ */
18
+ import { spawn as nodeSpawn } from 'node:child_process';
19
+ import { existsSync } from 'node:fs';
20
+ import { homedir } from 'node:os';
21
+
22
+ export const CLAUDE_WAKE_PROMPT = 'A SurfCAD user sent a chat message while you were not reading the chat. The wake JSON is on stdin. Follow its instruction field with the surfcad MCP tools: read_messages first, then answer. This machine is already logged in: do not call pair.';
23
+
24
+ /**
25
+ * @param {NodeJS.ProcessEnv} env
26
+ * @param {{ exists?: (path: string) => boolean, home?: string }} [deps]
27
+ * @returns {{ command: string, args: string[], cwd: string, action: string }}
28
+ */
29
+ export function claudeWakeArgs(env, deps = {}) {
30
+ const exists = deps.exists || existsSync;
31
+ const home = deps.home || env.HOME || homedir();
32
+ const command = (env.CLAUDE_BIN || '').trim() || 'claude';
33
+ const allowed = (env.SURFCAD_WAKE_ALLOWED_TOOLS || '').trim() || 'mcp__surfcad';
34
+ const session = (env.SURFCAD_WAKE_SESSION || '').trim();
35
+ const wanted = (env.SURFCAD_WAKE_ACTION || '').trim();
36
+ const action = (wanted === 'resume' || wanted === 'fork') && /^[A-Za-z0-9-]{8,80}$/.test(session) ? wanted : 'fresh';
37
+ const cwdWanted = (env.SURFCAD_WAKE_CWD || '').trim();
38
+ const cwd = action !== 'fresh' && cwdWanted && exists(cwdWanted) ? cwdWanted : home;
39
+ // `--allowedTools` and `--mcp-config` take several values, so a prompt
40
+ // after them is read as one more value: the prompt goes right after -p.
41
+ if (action === 'resume') {
42
+ return { command, action, cwd, args: ['-p', CLAUDE_WAKE_PROMPT, '--resume', session, '--allowedTools', allowed] };
43
+ }
44
+ if (action === 'fork') {
45
+ return { command, action, cwd, args: ['-p', CLAUDE_WAKE_PROMPT, '--resume', session, '--fork-session', '--allowedTools', allowed] };
46
+ }
47
+ const mcp = JSON.stringify({ mcpServers: { surfcad: { command: 'npx', args: ['-y', 'surfcad-mcp@latest'] } } });
48
+ return { command, action, cwd, args: ['-p', CLAUDE_WAKE_PROMPT, '--mcp-config', mcp, '--allowedTools', allowed] };
49
+ }
50
+
51
+ /**
52
+ * Run the turn. stdin (the wake JSON) is passed through to claude.
53
+ * @param {{ env: NodeJS.ProcessEnv, io: { stderr: (s: string) => void }, spawn?: typeof nodeSpawn }} ctx
54
+ * @returns {Promise<number>} exit code
55
+ */
56
+ export function runClaudeCodeWake(ctx) {
57
+ const plan = claudeWakeArgs(ctx.env);
58
+ const spawn = ctx.spawn || nodeSpawn;
59
+ return new Promise((resolve) => {
60
+ let child;
61
+ try {
62
+ child = spawn(plan.command, plan.args, { cwd: plan.cwd, stdio: 'inherit', env: ctx.env });
63
+ } catch {
64
+ ctx.io.stderr(`could not start ${plan.command}\n`);
65
+ resolve(1);
66
+ return;
67
+ }
68
+ child.once('error', () => {
69
+ ctx.io.stderr(`could not start ${plan.command}\n`);
70
+ resolve(1);
71
+ });
72
+ child.once('exit', (code) => resolve(typeof code === 'number' ? code : 1));
73
+ });
74
+ }
@@ -81,6 +81,41 @@ export async function clearListenerPid(pid, env = process.env) {
81
81
  await rm(listenerPidPath(env), { force: true });
82
82
  }
83
83
 
84
+ /** A login mark, not the token. Mode 0600, same directory as the pid file. */
85
+ const LOGIN_MARK = /^[a-f0-9]{16}$/;
86
+
87
+ /** @param {NodeJS.ProcessEnv} [env] */
88
+ export function listenerLoginPath(env = process.env) {
89
+ return join(configDir(env), 'listener.login');
90
+ }
91
+
92
+ /**
93
+ * The login the running listener was started with, or '' when nothing was
94
+ * recorded. Never a token.
95
+ * @param {NodeJS.ProcessEnv} [env]
96
+ * @returns {Promise<string>}
97
+ */
98
+ export async function readListenerLoginMark(env = process.env) {
99
+ try {
100
+ const mark = (await readFile(listenerLoginPath(env), 'utf8')).trim();
101
+ return LOGIN_MARK.test(mark) ? mark : '';
102
+ } catch {
103
+ return '';
104
+ }
105
+ }
106
+
107
+ /**
108
+ * @param {string} mark 16 hex characters, a hash of the login, never the token
109
+ * @param {NodeJS.ProcessEnv} [env]
110
+ */
111
+ export async function writeListenerLoginMark(mark, env = process.env) {
112
+ if (typeof mark !== 'string' || !LOGIN_MARK.test(mark)) return;
113
+ const dir = configDir(env);
114
+ await mkdir(dir, { recursive: true, mode: 0o700 });
115
+ await writeFile(listenerLoginPath(env), `${mark}\n`, { mode: 0o600 });
116
+ await chmod(listenerLoginPath(env), 0o600);
117
+ }
118
+
84
119
  /**
85
120
  * Start `surfcad-mcp listen` as its own process group with its output in
86
121
  * the log file, and return at once.