surfcad-mcp 0.3.8 → 0.4.0

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 (43) hide show
  1. package/README.md +102 -49
  2. package/bin/surfcad-mcp.js +4 -3
  3. package/data/commands.json +6481 -5817
  4. package/data/helpers.json +243 -268
  5. package/package.json +2 -2
  6. package/src/cli.mjs +234 -24
  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 +285 -0
  12. package/src/listen/claudeCodeWake.mjs +74 -0
  13. package/src/listen/daemon.mjs +40 -0
  14. package/src/listen/listenCli.mjs +157 -27
  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 +42 -8
  19. package/src/listen/wakeConfig.mjs +17 -2
  20. package/src/listen/wakeSetupText.mjs +53 -14
  21. package/src/pairWait.mjs +3 -3
  22. package/src/pairingCode.mjs +10 -0
  23. package/src/prompt/buildGuidance.mjs +9 -7
  24. package/src/prompt/chatFlow.mjs +15 -0
  25. package/src/prompt/errorHints.mjs +24 -10
  26. package/src/prompt/guide.mjs +31 -18
  27. package/src/prompt/promptSession.mjs +74 -10
  28. package/src/prompt/promptTools.mjs +10 -15
  29. package/src/prompt/replyConfirm.mjs +69 -0
  30. package/src/relayMessages.mjs +43 -1
  31. package/src/remote/config.mjs +17 -13
  32. package/src/remote/session.mjs +103 -5
  33. package/src/remote/tokenStore.mjs +20 -0
  34. package/src/room/seat.mjs +334 -0
  35. package/src/screenshotFile.mjs +9 -0
  36. package/src/server.mjs +241 -119
  37. package/src/stepUploadLimit.mjs +8 -0
  38. package/src/bridge/bridgePage.mjs +0 -132
  39. package/src/bridge/bridgePopup.mjs +0 -288
  40. package/src/bridge/relayHub.mjs +0 -556
  41. package/src/bridge/relayServer.mjs +0 -291
  42. package/src/nodeClient.mjs +0 -63
  43. package/src/relay.mjs +0 -419
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
+ }
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Wake bootstrap: after a pair or login the user can message the agent from
3
+ * SurfCAD with no further setup, where the host makes that possible.
4
+ *
5
+ * SurfCAD cannot make up a way to start a turn of an agent. That exists only
6
+ * on the agent's host. So the wake comes from one of two places, and the
7
+ * user is never asked to paste a URL:
8
+ *
9
+ * env The host (or whoever installs this MCP server for it) puts the
10
+ * wake in the server's environment: SURFCAD_WAKE_POST (with
11
+ * SURFCAD_WAKE_BEARER) and/or SURFCAD_WAKE_EXEC. This is the
12
+ * host-provided path: an MCP server config has an `env` block, and
13
+ * that is the one channel a host has to this process.
14
+ * saved `surfcad-mcp wake set` was run on this machine (the escape hatch).
15
+ *
16
+ * With a wake in hand the bootstrap starts the listener (server relay) and
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.
28
+ *
29
+ * With no wake, nothing is pretended: the state says cold wake is
30
+ * unavailable, and the pairing session tells the user once that the setup
31
+ * is still needed.
32
+ */
33
+
34
+ import { listenPaused } from './owner.mjs';
35
+ import { createHash } from 'node:crypto';
36
+ import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';
37
+ import { join } from 'node:path';
38
+ import { configDir } from '../remote/config.mjs';
39
+ import { readSavedLogin } from '../remote/tokenStore.mjs';
40
+ import {
41
+ readListenerLoginMark,
42
+ readListenerPid,
43
+ startDetachedListener,
44
+ stopListener,
45
+ writeListenerLoginMark,
46
+ } from './daemon.mjs';
47
+ import { createWaker, wakePayload } from './wake.mjs';
48
+ import {
49
+ normalizeWakeBearer,
50
+ normalizeWakeExec,
51
+ normalizeWakeUrl,
52
+ readWake,
53
+ saveWake,
54
+ wakeForms,
55
+ } from './wakeConfig.mjs';
56
+
57
+ /**
58
+ * The wake the host put in this server's environment, or null. A value that
59
+ * does not pass the `wake set` rules is left out and named in `problems`.
60
+ * @param {NodeJS.ProcessEnv} [env]
61
+ * @returns {{ config: import('./wakeConfig.mjs').WakeConfig | null, problems: string[] }}
62
+ */
63
+ export function wakeFromEnv(env = process.env) {
64
+ /** @type {import('./wakeConfig.mjs').WakeConfig} */
65
+ const config = {};
66
+ const problems = [];
67
+ const text = (name) => (typeof env[name] === 'string' ? env[name].trim() : '');
68
+ if (text('SURFCAD_WAKE_POST')) {
69
+ try {
70
+ const url = normalizeWakeUrl(text('SURFCAD_WAKE_POST'));
71
+ const bearer = normalizeWakeBearer(text('SURFCAD_WAKE_BEARER'));
72
+ config.post = bearer ? { url, bearer } : { url };
73
+ } catch (err) {
74
+ problems.push(`SURFCAD_WAKE_POST: ${err?.message || 'not a usable URL'}`);
75
+ }
76
+ }
77
+ if (text('SURFCAD_WAKE_EXEC')) {
78
+ try {
79
+ config.exec = normalizeWakeExec(text('SURFCAD_WAKE_EXEC'));
80
+ } catch (err) {
81
+ problems.push(`SURFCAD_WAKE_EXEC: ${err?.message || 'not a usable command'}`);
82
+ }
83
+ }
84
+ return { config: config.post || config.exec ? config : null, problems };
85
+ }
86
+
87
+ function sameWake(a, b) {
88
+ const norm = (c) => JSON.stringify({ post: c?.post ? { url: c.post.url, bearer: c.post.bearer || '' } : null, exec: c?.exec || '' });
89
+ return norm(a) === norm(b);
90
+ }
91
+
92
+ /**
93
+ * The wake for this machine and where it came from. The environment wins: it
94
+ * is what the host says now, and it is written to wake.json so the listener,
95
+ * a separate process, uses the same one.
96
+ * @param {NodeJS.ProcessEnv} [env]
97
+ * @returns {Promise<{ config: import('./wakeConfig.mjs').WakeConfig | null, source: 'env' | 'saved' | null, problems: string[] }>}
98
+ */
99
+ export async function provisionWake(env = process.env) {
100
+ const fromEnv = wakeFromEnv(env);
101
+ let saved = null;
102
+ try {
103
+ saved = await readWake(env);
104
+ } catch {
105
+ saved = null;
106
+ }
107
+ if (fromEnv.config) {
108
+ if (!sameWake(fromEnv.config, saved)) {
109
+ try {
110
+ saved = await saveWake(fromEnv.config, env);
111
+ } catch {
112
+ return { config: fromEnv.config, source: 'env', problems: [...fromEnv.problems, 'The wake could not be saved for the listener.'] };
113
+ }
114
+ }
115
+ return { config: saved || fromEnv.config, source: 'env', problems: fromEnv.problems };
116
+ }
117
+ return { config: saved, source: saved ? 'saved' : null, problems: fromEnv.problems };
118
+ }
119
+
120
+ /** @param {NodeJS.ProcessEnv} [env] */
121
+ export function wakeStatePath(env = process.env) {
122
+ return join(configDir(env), 'wake-state.json');
123
+ }
124
+
125
+ /** A short one-way mark of a login. Never the token. */
126
+ export function loginMark(token) {
127
+ return createHash('sha256').update(String(token || 'local')).digest('hex').slice(0, 16);
128
+ }
129
+
130
+ async function readState(env) {
131
+ try {
132
+ const parsed = JSON.parse(await readFile(wakeStatePath(env), 'utf8'));
133
+ return parsed && typeof parsed === 'object' ? parsed : {};
134
+ } catch {
135
+ return {};
136
+ }
137
+ }
138
+
139
+ async function writeState(state, env) {
140
+ try {
141
+ await mkdir(configDir(env), { recursive: true, mode: 0o700 });
142
+ await writeFile(wakeStatePath(env), `${JSON.stringify(state)}\n`, { mode: 0o600 });
143
+ await chmod(wakeStatePath(env), 0o600);
144
+ } catch {
145
+ /* a test wake fired twice is the worst that happens */
146
+ }
147
+ }
148
+
149
+ /**
150
+ * @typedef {{
151
+ * forms: string[],
152
+ * source: 'env' | 'saved' | null,
153
+ * listenerRunning: boolean,
154
+ * listenerStarted: boolean,
155
+ * coldWake: 'ready' | 'listener_stopped' | 'unavailable',
156
+ * wakeCheck: 'fired' | 'not_fired' | 'already_fired' | 'none',
157
+ * userNotice: 'tell_now' | 'later' | 'done' | 'not_needed',
158
+ * problems: string[],
159
+ * }} WakeBootstrap
160
+ */
161
+
162
+ /**
163
+ * Run after a successful pair or login.
164
+ * @param {{
165
+ * env?: NodeJS.ProcessEnv,
166
+ * remote: boolean,
167
+ * check?: boolean,
168
+ * tellUser?: boolean,
169
+ * autoListen?: boolean,
170
+ * spawn?: any,
171
+ * fetch?: typeof fetch,
172
+ * waker?: ReturnType<typeof createWaker>,
173
+ * startListener?: typeof startDetachedListener,
174
+ * stopListener?: typeof stopListener,
175
+ * listenerPid?: typeof readListenerPid,
176
+ * }} options
177
+ * `remote`: this process is on the server relay (a saved login exists), so
178
+ * the listener can run. `check: false` skips the test wake (a status read).
179
+ * `autoListen: false` reports the listener and does not start it.
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'`).
183
+ * @returns {Promise<WakeBootstrap>}
184
+ */
185
+ export async function bootstrapWake(options) {
186
+ const env = options.env || process.env;
187
+ const listenerPid = options.listenerPid || readListenerPid;
188
+ const { config, source, problems } = await provisionWake(env);
189
+ const forms = wakeForms(config);
190
+
191
+ let listenerRunning = false;
192
+ let listenerStarted = false;
193
+ let token = '';
194
+ if (options.remote) {
195
+ try {
196
+ token = (await readSavedLogin(env))?.token || '';
197
+ } catch {
198
+ token = '';
199
+ }
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
+ }
223
+ // A listener with no wake cannot start a turn, so it is not started.
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) {
228
+ try {
229
+ await (options.startListener || startDetachedListener)({ env, spawn: options.spawn });
230
+ listenerStarted = true;
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
+ }
239
+ } catch {
240
+ problems.push('The listener could not be started. Run: npx surfcad-mcp listen --detach');
241
+ }
242
+ }
243
+ }
244
+
245
+ // Cold wake: something can start a turn while no agent process is up.
246
+ // The local relay has no listener; there this process fires the wake, so
247
+ // it holds only while the host keeps the process running.
248
+ /** @type {WakeBootstrap['coldWake']} */
249
+ let coldWake = 'unavailable';
250
+ if (config) coldWake = !options.remote || listenerRunning ? 'ready' : 'listener_stopped';
251
+
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) {
260
+ const mark = loginMark(options.remote ? token : 'local');
261
+ const state = await readState(env);
262
+ if (config) {
263
+ if (state.checked !== mark) {
264
+ await writeState({ ...state, checked: mark, checkedAt: new Date().toISOString() }, env);
265
+ const waker = options.waker || createWaker(config, { env, fetch: options.fetch, spawn: options.spawn });
266
+ const outcome = await waker.wake(wakePayload([], { reason: 'test' }));
267
+ if (outcome.ok) {
268
+ wakeCheck = 'fired';
269
+ } else {
270
+ wakeCheck = 'not_fired';
271
+ problems.push(`The wake did not fire (${outcome.error}).`);
272
+ coldWake = 'unavailable';
273
+ }
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
+ }
282
+ }
283
+ }
284
+ return { forms, source, listenerRunning, listenerStarted, coldWake, wakeCheck, userNotice, problems };
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.
@@ -103,6 +138,11 @@ export async function startDetachedListener(options = {}) {
103
138
  windowsHide: true,
104
139
  });
105
140
  child.unref?.();
141
+ // The listener writes this itself once it is up. Writing it here too
142
+ // means "running" is true the moment --detach returns, with no gap in
143
+ // which a second start or a status read sees nothing. A child that dies
144
+ // at once leaves a dead pid, and readListenerPid removes those.
145
+ if (Number.isInteger(child.pid) && child.pid > 0) await writeListenerPid(child.pid, env);
106
146
  return { pid: child.pid, log };
107
147
  } finally {
108
148
  closeSync(fd);