surfcad-mcp 0.3.7 → 0.3.9

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.
@@ -0,0 +1,250 @@
1
+ /**
2
+ * `surfcad-mcp listen`: the process that stays up between agent turns.
3
+ *
4
+ * An MCP server cannot start an agent turn, and a host that starts a fresh
5
+ * `surfcad-mcp` per tool call has nothing running while the agent is idle.
6
+ * A message the user sends from the SurfCAD chat box then waits on the
7
+ * server with nobody to read it. This loop watches for it and fires the
8
+ * saved wake action, so the agent starts a turn and reads the message.
9
+ *
10
+ * It uses the server relay's HTTPS pull (GET /agent/prompts), outbound only,
11
+ * so it works behind NAT and for a tab on a phone: neither side has to be
12
+ * reachable. The pull has the semantics a watcher needs and a socket does
13
+ * not:
14
+ * - a prompt offered to a pull session stays held on the server until an
15
+ * agent process reports it taken, so watching never consumes a message;
16
+ * - each poll renews presence, so the server keeps holding prompts for an
17
+ * idle agent and the tab shows the message as queued, not failed;
18
+ * - a cancel is answered by the server, with no socket here to answer it.
19
+ *
20
+ * A prompt is not a reason to wake by itself. An agent that is already in a
21
+ * turn long-polls read_messages and takes it within seconds, and a wake then
22
+ * would start a second turn. So each new prompt waits `graceMs`, and is
23
+ * then looked for again from a fresh pull session: the server offers every
24
+ * prompt it still holds to a session that has not seen it. Still there
25
+ * means nobody took it, and that is when the wake fires.
26
+ *
27
+ * One more case: the agent is in a turn but between polls. It made a tool
28
+ * call in the last minute (./awake.mjs), so it is not woken; the prompt is
29
+ * looked at again every 15 s until the agent reads it or goes idle.
30
+ */
31
+
32
+ import { randomUUID } from 'node:crypto';
33
+ import { agentUrls } from '../remote/config.mjs';
34
+ import { createWaker, wakePayload } from './wake.mjs';
35
+
36
+ export const LISTEN_POLL_MS = 25_000;
37
+ export const LISTEN_GRACE_MS = 4_000;
38
+ /** A prompt that was woken for and is still unread is woken for once more after this. */
39
+ export const LISTEN_REWAKE_MS = 120_000;
40
+ /** While the wake command of an earlier message still runs, look again this often. */
41
+ export const LISTEN_BUSY_RETRY_MS = 15_000;
42
+ export const LISTEN_BACKOFF_MS = Object.freeze([1_000, 2_000, 5_000, 10_000, 30_000]);
43
+ const SEEN_CAP = 500;
44
+
45
+ function newSession() {
46
+ return randomUUID().replace(/-/g, '');
47
+ }
48
+
49
+ /**
50
+ * @param {unknown} frame
51
+ * @returns {{ id: string, text?: string, ts?: string, screenshot?: unknown } | null}
52
+ */
53
+ export function promptFromFrame(frame) {
54
+ if (!frame || typeof frame !== 'object') return null;
55
+ const f = /** @type {Record<string, any>} */ (frame);
56
+ if (f.type !== 'agent.prompt' || typeof f.id !== 'string' || !f.id) return null;
57
+ return {
58
+ id: f.id,
59
+ ...(typeof f.text === 'string' ? { text: f.text } : {}),
60
+ ...(typeof f.ts === 'string' ? { ts: f.ts } : {}),
61
+ ...(f.screenshot ? { screenshot: true } : {}),
62
+ };
63
+ }
64
+
65
+ /**
66
+ * @param {{
67
+ * serverUrl: string,
68
+ * token: string,
69
+ * wake: import('./wakeConfig.mjs').WakeConfig,
70
+ * fetch?: typeof fetch,
71
+ * log?: (line: string) => void,
72
+ * graceMs?: number,
73
+ * pollMs?: number,
74
+ * rewakeMs?: number,
75
+ * backoffMs?: readonly number[],
76
+ * waker?: ReturnType<typeof createWaker>,
77
+ * isAwake?: () => Promise<boolean> | boolean,
78
+ * sleep?: (ms: number, signal?: AbortSignal) => Promise<void>,
79
+ * now?: () => number,
80
+ * signal?: AbortSignal,
81
+ * }} options
82
+ * @returns {Promise<{ reason: 'stopped' | 'token_revoked' | 'expired' | 'unauthorized' }>}
83
+ */
84
+ export async function runListener(options) {
85
+ const urls = agentUrls(options.serverUrl);
86
+ const doFetch = options.fetch || fetch;
87
+ const log = options.log || (() => {});
88
+ const graceMs = options.graceMs ?? LISTEN_GRACE_MS;
89
+ const pollMs = options.pollMs ?? LISTEN_POLL_MS;
90
+ const rewakeMs = options.rewakeMs ?? LISTEN_REWAKE_MS;
91
+ const backoff = options.backoffMs || LISTEN_BACKOFF_MS;
92
+ const waker = options.waker || createWaker(options.wake);
93
+ const isAwake = options.isAwake || (() => false);
94
+ const now = options.now || (() => Date.now());
95
+ const signal = options.signal;
96
+ const sleep = options.sleep || ((ms, sig) => new Promise((resolve) => {
97
+ if (sig?.aborted) { resolve(); return; }
98
+ const timer = setTimeout(done, ms);
99
+ function done() {
100
+ clearTimeout(timer);
101
+ sig?.removeEventListener('abort', done);
102
+ resolve();
103
+ }
104
+ sig?.addEventListener('abort', done, { once: true });
105
+ }));
106
+
107
+ /** Prompts seen and not yet known to be read: id → { prompt, due, wakes }. */
108
+ const waiting = new Map();
109
+ /** Ids that are finished here (read by an agent, or given up on). */
110
+ const settled = new Set();
111
+ const session = newSession();
112
+
113
+ /**
114
+ * @param {string} sessionId
115
+ * @param {number} timeoutMs
116
+ * @returns {Promise<object[]>}
117
+ */
118
+ async function pull(sessionId, timeoutMs) {
119
+ const url = new URL(urls.promptsUrl);
120
+ url.searchParams.set('timeout', String(timeoutMs));
121
+ url.searchParams.set('session', sessionId);
122
+ let res;
123
+ try {
124
+ res = await doFetch(url, {
125
+ method: 'GET',
126
+ headers: { Authorization: `Bearer ${options.token}` },
127
+ signal,
128
+ });
129
+ } catch {
130
+ throw Object.assign(new Error('unreachable'), { code: 'unreachable' });
131
+ }
132
+ if (res.status === 401) {
133
+ let json = null;
134
+ try { json = await res.json(); } catch { json = null; }
135
+ const code = json && typeof json.error === 'string' ? json.error : '';
136
+ throw Object.assign(new Error('unauthorized'), {
137
+ code: code === 'expired' || code === 'token_revoked' ? code : 'unauthorized',
138
+ });
139
+ }
140
+ if (!res.ok) {
141
+ try { await res.body?.cancel?.(); } catch { /* noop */ }
142
+ throw Object.assign(new Error(`pull ${res.status}`), { code: 'bridge_error' });
143
+ }
144
+ let json = null;
145
+ try { json = await res.json(); } catch { json = null; }
146
+ return json && Array.isArray(json.messages) ? json.messages : [];
147
+ }
148
+
149
+ /** @param {object[]} frames */
150
+ function note(frames) {
151
+ for (const frame of frames) {
152
+ const prompt = promptFromFrame(frame);
153
+ if (!prompt || settled.has(prompt.id) || waiting.has(prompt.id)) continue;
154
+ waiting.set(prompt.id, { prompt, due: now() + graceMs, wakes: 0 });
155
+ log(`message ${prompt.id} is waiting; checking in ${Math.round(graceMs / 1000)} s whether an agent read it`);
156
+ }
157
+ }
158
+
159
+ function settle(id) {
160
+ waiting.delete(id);
161
+ settled.add(id);
162
+ if (settled.size > SEEN_CAP) settled.delete(settled.values().next().value);
163
+ }
164
+
165
+ /**
166
+ * Wake for every prompt that is past its grace and still held.
167
+ * @returns {Promise<void>}
168
+ */
169
+ async function check() {
170
+ const due = [...waiting.values()].filter((row) => row.due <= now());
171
+ if (!due.length) return;
172
+ // A fresh session is offered everything the server still holds.
173
+ const held = new Map();
174
+ for (const frame of await pull(newSession(), 0)) {
175
+ const prompt = promptFromFrame(frame);
176
+ if (prompt) held.set(prompt.id, prompt);
177
+ }
178
+ const unread = [];
179
+ for (const row of due) {
180
+ if (!held.has(row.prompt.id)) {
181
+ log(`message ${row.prompt.id} was read (or cancelled); no wake`);
182
+ settle(row.prompt.id);
183
+ } else if (row.wakes >= 2) {
184
+ log(`message ${row.prompt.id} is still unread after two wakes; leaving it for the agent's next turn`);
185
+ settle(row.prompt.id);
186
+ } else {
187
+ unread.push(row);
188
+ }
189
+ }
190
+ // Anything else still held that this loop has not met is new to it.
191
+ note([...held.values()].map((p) => ({ type: 'agent.prompt', ...p })));
192
+ if (!unread.length) return;
193
+ // An agent in a turn is not woken: it reads the message at its next
194
+ // read_messages, and a wake would start a second turn beside the first.
195
+ if (await isAwake()) {
196
+ for (const row of unread) {
197
+ if (!row.deferred) log(`message ${row.prompt.id} is unread but the agent is in a turn; waiting for it to read the message or go idle`);
198
+ row.deferred = true;
199
+ row.due = now() + LISTEN_BUSY_RETRY_MS;
200
+ }
201
+ return;
202
+ }
203
+ const outcome = await waker.wake(wakePayload(unread.map((row) => row.prompt)));
204
+ if (outcome.ok) {
205
+ log(`woke the agent by ${outcome.form} for ${unread.length} message${unread.length === 1 ? '' : 's'}`);
206
+ for (const row of unread) {
207
+ row.wakes += 1;
208
+ row.due = now() + rewakeMs;
209
+ }
210
+ return;
211
+ }
212
+ if (outcome.error === 'wake_exec_busy') {
213
+ log('the wake command from an earlier message is still running; checking again shortly');
214
+ for (const row of unread) row.due = now() + LISTEN_BUSY_RETRY_MS;
215
+ return;
216
+ }
217
+ log(`wake failed (${outcome.error}); trying again in ${Math.round(rewakeMs / 1000)} s`);
218
+ for (const row of unread) row.due = now() + rewakeMs;
219
+ }
220
+
221
+ let failures = 0;
222
+ log(`listening for SurfCAD chat messages at ${urls.origin}`);
223
+ while (!signal?.aborted) {
224
+ try {
225
+ // Poll no longer than the next check is due.
226
+ let wait = pollMs;
227
+ for (const row of waiting.values()) wait = Math.min(wait, Math.max(0, row.due - now()));
228
+ if (wait > 0) note(await pull(session, Math.min(pollMs, Math.max(250, wait))));
229
+ if (signal?.aborted) break;
230
+ await check();
231
+ failures = 0;
232
+ } catch (err) {
233
+ if (signal?.aborted) break;
234
+ const code = err && typeof err === 'object' ? err.code : '';
235
+ if (code === 'token_revoked' || code === 'expired' || code === 'unauthorized') {
236
+ log(code === 'expired'
237
+ ? 'the SurfCAD login expired; run npx surfcad-mcp login, then start the listener again'
238
+ : 'the SurfCAD login is no longer valid; run npx surfcad-mcp login, then start the listener again');
239
+ return { reason: code };
240
+ }
241
+ const delay = backoff[Math.min(failures, backoff.length - 1)];
242
+ failures += 1;
243
+ if (failures === 1 || failures % 10 === 0) {
244
+ log(`cannot reach ${urls.origin} (${code || 'error'}); retrying`);
245
+ }
246
+ await sleep(delay, signal);
247
+ }
248
+ }
249
+ return { reason: 'stopped' };
250
+ }
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Fire a saved wake action.
3
+ *
4
+ * post POST the wake JSON. 10 s timeout, one retry, redirects not followed.
5
+ * exec run the saved command through the shell with the wake JSON on stdin.
6
+ *
7
+ * The command line is the saved text and nothing else. Message text goes to
8
+ * stdin only: never into argv and never into the environment, so a chat
9
+ * message cannot become shell syntax. The environment gets the prompt ids
10
+ * (opaque, server-made) and the reason.
11
+ *
12
+ * Forms are tried in order, post then exec, and the first that works is the
13
+ * wake. Firing both would start two agent turns for one message.
14
+ */
15
+
16
+ import { spawn as nodeSpawn } from 'node:child_process';
17
+
18
+ export const WAKE_POST_TIMEOUT_MS = 10_000;
19
+ export const WAKE_POST_ATTEMPTS = 2;
20
+
21
+ /** What the woken agent should do. Short, and the same for every host. */
22
+ export const WAKE_INSTRUCTION = 'A SurfCAD user sent you a chat message and this is a new session started to answer it. On the surfcad MCP server call read_messages { wait_ms: 10000 }, then follow guide { topic: "chat" }: set_status responding first, then reply_to_user. You have no memory of earlier sessions: the message is in "prompts", status gives the open part, and guide { topic: "start" } says how to build.';
23
+
24
+ /** What the agent says when it is first connected. Artur's wording, 2026-11-06. */
25
+ export const WAKE_GREETING = 'Hi, what can I help you design?';
26
+
27
+ /**
28
+ * The greeting wake. It fires once per login, right after pairing, and it is
29
+ * the check that the wake works: the session it starts says hello in the
30
+ * SurfCAD chat, where the user sees it.
31
+ */
32
+ export const WAKE_GREET_INSTRUCTION = `You were just connected to SurfCAD and this is a new session started to greet the user. On the surfcad MCP server call reply_to_user { text: "${WAKE_GREETING}" } with no in_reply_to. Then follow guide { topic: "chat" }: wait for their message with read_messages { wait_ms: 10000 }. Read guide { topic: "start" } before the first model call.`;
33
+
34
+ const WAKE_TEST_INSTRUCTION = 'This is a test of the SurfCAD wake setup. No user message is waiting.';
35
+
36
+ /**
37
+ * @param {Array<{ id: string, text?: string, ts?: string, screenshot?: unknown }>} prompts
38
+ * @param {{ reason?: 'prompt' | 'test' | 'greet' }} [opts]
39
+ */
40
+ export function wakePayload(prompts, opts = {}) {
41
+ const reason = opts.reason === 'test' || opts.reason === 'greet' ? opts.reason : 'prompt';
42
+ let instruction = WAKE_INSTRUCTION;
43
+ if (reason === 'test') instruction = WAKE_TEST_INSTRUCTION;
44
+ if (reason === 'greet') instruction = WAKE_GREET_INSTRUCTION;
45
+ return {
46
+ type: 'surfcad.wake',
47
+ v: 1,
48
+ reason,
49
+ instruction,
50
+ ...(reason === 'greet' ? { greeting: WAKE_GREETING } : {}),
51
+ prompts: (Array.isArray(prompts) ? prompts : []).map((p) => ({
52
+ id: String(p.id),
53
+ ...(typeof p.text === 'string' ? { text: p.text } : {}),
54
+ ...(typeof p.ts === 'string' ? { ts: p.ts } : {}),
55
+ // The picture stays on the server for read_messages. A wake is small.
56
+ ...(p.screenshot ? { hasScreenshot: true } : {}),
57
+ })),
58
+ };
59
+ }
60
+
61
+ /**
62
+ * @param {{ url: string, bearer?: string }} post
63
+ * @param {object} payload
64
+ * @param {{ fetch?: typeof fetch, timeoutMs?: number, attempts?: number }} [deps]
65
+ * @returns {Promise<{ ok: boolean, error?: string }>}
66
+ */
67
+ export async function postWake(post, payload, deps = {}) {
68
+ const doFetch = deps.fetch || fetch;
69
+ const timeoutMs = deps.timeoutMs ?? WAKE_POST_TIMEOUT_MS;
70
+ const attempts = deps.attempts ?? WAKE_POST_ATTEMPTS;
71
+ const headers = { 'content-type': 'application/json', accept: 'application/json' };
72
+ if (post.bearer) headers.authorization = `Bearer ${post.bearer}`;
73
+ const body = JSON.stringify(payload);
74
+ let error = 'wake_post_failed';
75
+ for (let i = 0; i < attempts; i += 1) {
76
+ try {
77
+ const res = await doFetch(post.url, {
78
+ method: 'POST',
79
+ headers,
80
+ body,
81
+ redirect: 'manual',
82
+ signal: AbortSignal.timeout(timeoutMs),
83
+ });
84
+ try { await res.body?.cancel?.(); } catch { /* noop */ }
85
+ if (res.status >= 200 && res.status < 300) return { ok: true };
86
+ error = `wake_post_status_${res.status}`;
87
+ } catch (err) {
88
+ error = err?.name === 'TimeoutError' || err?.name === 'AbortError' ? 'wake_post_timeout' : 'wake_post_failed';
89
+ }
90
+ }
91
+ return { ok: false, error };
92
+ }
93
+
94
+ /**
95
+ * Start the saved command. Resolves once it has started (or failed to):
96
+ * the command may be the agent's whole turn and run for minutes, so nothing
97
+ * here waits for it or kills it. `done` settles when it exits.
98
+ * @param {string} command
99
+ * @param {object} payload
100
+ * @param {{ spawn?: typeof nodeSpawn, env?: NodeJS.ProcessEnv }} [deps]
101
+ * @returns {Promise<{ ok: boolean, error?: string, pid?: number, done?: Promise<number | null> }>}
102
+ */
103
+ export function execWake(command, payload, deps = {}) {
104
+ const spawn = deps.spawn || nodeSpawn;
105
+ const env = {
106
+ ...(deps.env || process.env),
107
+ SURFCAD_WAKE: '1',
108
+ SURFCAD_WAKE_REASON: String(payload?.reason || 'prompt'),
109
+ SURFCAD_PROMPT_IDS: (payload?.prompts || []).map((p) => p.id).join(','),
110
+ };
111
+ return new Promise((resolve) => {
112
+ let child;
113
+ try {
114
+ child = spawn(command, { shell: true, stdio: ['pipe', 'ignore', 'ignore'], env, windowsHide: true });
115
+ } catch {
116
+ resolve({ ok: false, error: 'wake_exec_failed' });
117
+ return;
118
+ }
119
+ let started = false;
120
+ const done = new Promise((exited) => {
121
+ child.once('exit', (code) => exited(typeof code === 'number' ? code : null));
122
+ child.once('error', () => exited(null));
123
+ });
124
+ child.once('error', () => {
125
+ if (!started) resolve({ ok: false, error: 'wake_exec_failed' });
126
+ });
127
+ child.once('spawn', () => {
128
+ started = true;
129
+ // A command that does not read stdin closes the pipe: not an error.
130
+ child.stdin?.on('error', () => {});
131
+ try { child.stdin?.end(`${JSON.stringify(payload)}\n`); } catch { /* noop */ }
132
+ resolve({ ok: true, pid: child.pid, done });
133
+ });
134
+ });
135
+ }
136
+
137
+ /**
138
+ * One waker per process. `wake` tries post, then exec. While an exec'd
139
+ * command from an earlier wake is still running, exec answers `wake_exec_busy`
140
+ * instead of starting a second copy; `idle` resolves when it has exited.
141
+ * @param {import('./wakeConfig.mjs').WakeConfig} config
142
+ * @param {{ fetch?: typeof fetch, spawn?: typeof nodeSpawn, env?: NodeJS.ProcessEnv, timeoutMs?: number }} [deps]
143
+ */
144
+ export function createWaker(config, deps = {}) {
145
+ /** @type {Promise<number | null> | null} */
146
+ let running = null;
147
+ return {
148
+ /**
149
+ * @param {object} payload
150
+ * @returns {Promise<{ ok: boolean, form: 'post' | 'exec' | null, error?: string }>}
151
+ */
152
+ async wake(payload) {
153
+ let error = 'wake_not_set';
154
+ if (config?.post) {
155
+ const posted = await postWake(config.post, payload, deps);
156
+ if (posted.ok) return { ok: true, form: 'post' };
157
+ error = posted.error || 'wake_post_failed';
158
+ }
159
+ if (config?.exec) {
160
+ if (running) return { ok: false, form: 'exec', error: 'wake_exec_busy' };
161
+ const started = await execWake(config.exec, payload, deps);
162
+ if (started.ok) {
163
+ const done = started.done || Promise.resolve(null);
164
+ running = done;
165
+ done.then(() => { if (running === done) running = null; });
166
+ return { ok: true, form: 'exec' };
167
+ }
168
+ error = started.error || 'wake_exec_failed';
169
+ return { ok: false, form: 'exec', error };
170
+ }
171
+ return { ok: false, form: config?.post ? 'post' : null, error };
172
+ },
173
+ /** Resolves when no exec'd wake command is running. */
174
+ idle() {
175
+ return running ? running.then(() => {}) : Promise.resolve();
176
+ },
177
+ busy() {
178
+ return running != null;
179
+ },
180
+ };
181
+ }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Saved wake actions: how this machine starts an agent turn when the user
3
+ * sends a chat message from SurfCAD and no agent process is reading.
4
+ *
5
+ * Two forms, either or both:
6
+ * post POST the wake JSON to a URL the agent's host listens on.
7
+ * exec run a local command with the wake JSON on stdin.
8
+ *
9
+ * The file sits next to the saved login, mode 0600 in a 0700 directory. It
10
+ * is written only by `surfcad-mcp wake set` on this machine. Nothing a
11
+ * server, a tab, or a chat message sends can change it, and no part of a
12
+ * message is ever put into the command line.
13
+ */
14
+
15
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
16
+ import { join } from 'node:path';
17
+ import { configDir } from '../remote/config.mjs';
18
+
19
+ export const WAKE_EXEC_MAX_CHARS = 4000;
20
+ export const WAKE_BEARER_MAX_CHARS = 512;
21
+
22
+ /**
23
+ * @typedef {{ url: string, bearer?: string }} WakePost
24
+ * @typedef {{ post?: WakePost, exec?: string, savedAt?: string }} WakeConfig
25
+ */
26
+
27
+ /**
28
+ * @param {NodeJS.ProcessEnv} [env]
29
+ */
30
+ export function wakePath(env = process.env) {
31
+ return join(configDir(env), 'wake.json');
32
+ }
33
+
34
+ /**
35
+ * @param {string} hostname
36
+ */
37
+ export function isLoopbackHost(hostname) {
38
+ const host = String(hostname || '').toLowerCase().replace(/^\[|\]$/g, '');
39
+ if (host === 'localhost' || host === '::1') return true;
40
+ return /^127(?:\.\d{1,3}){3}$/.test(host);
41
+ }
42
+
43
+ function bad(message) {
44
+ return Object.assign(new Error(message), { code: 'bad_args' });
45
+ }
46
+
47
+ /**
48
+ * A wake URL is https, or cleartext http to this machine only. The listener
49
+ * runs beside the agent's host, so localhost is the common case; that is
50
+ * the difference from register_webhook, which refuses it.
51
+ * @param {unknown} input
52
+ * @returns {string}
53
+ */
54
+ export function normalizeWakeUrl(input) {
55
+ const text = typeof input === 'string' ? input.trim() : '';
56
+ if (!text) throw bad('--post needs a URL.');
57
+ /** @type {URL} */
58
+ let url;
59
+ try {
60
+ url = new URL(text);
61
+ } catch {
62
+ throw bad('--post needs a full URL, for example http://127.0.0.1:8644/wake.');
63
+ }
64
+ if (url.username || url.password) {
65
+ throw bad('Do not put a user name or password in the wake URL. Use --bearer.');
66
+ }
67
+ if (url.protocol === 'https:') return url.toString();
68
+ if (url.protocol === 'http:' && isLoopbackHost(url.hostname)) return url.toString();
69
+ throw bad('The wake URL must be https, or http to localhost, 127.0.0.1 or ::1.');
70
+ }
71
+
72
+ /**
73
+ * @param {unknown} input
74
+ * @returns {string}
75
+ */
76
+ export function normalizeWakeBearer(input) {
77
+ const text = typeof input === 'string' ? input.trim() : '';
78
+ if (!text) return '';
79
+ if (text.length > WAKE_BEARER_MAX_CHARS || /[\r\n]/.test(text)) {
80
+ throw bad(`--bearer must be one line of at most ${WAKE_BEARER_MAX_CHARS} characters.`);
81
+ }
82
+ return text;
83
+ }
84
+
85
+ /**
86
+ * @param {unknown} input
87
+ * @returns {string}
88
+ */
89
+ export function normalizeWakeExec(input) {
90
+ const text = typeof input === 'string' ? input.trim() : '';
91
+ if (!text) throw bad('--exec needs a command.');
92
+ if (text.length > WAKE_EXEC_MAX_CHARS || text.includes('\0')) {
93
+ throw bad(`--exec must be at most ${WAKE_EXEC_MAX_CHARS} characters.`);
94
+ }
95
+ return text;
96
+ }
97
+
98
+ /**
99
+ * @param {unknown} raw
100
+ * @returns {WakeConfig | null} null when no usable form is in it
101
+ */
102
+ export function normalizeWake(raw) {
103
+ if (!raw || typeof raw !== 'object') return null;
104
+ const record = /** @type {Record<string, any>} */ (raw);
105
+ /** @type {WakeConfig} */
106
+ const out = {};
107
+ if (record.post && typeof record.post === 'object' && typeof record.post.url === 'string') {
108
+ try {
109
+ const url = normalizeWakeUrl(record.post.url);
110
+ const bearer = normalizeWakeBearer(record.post.bearer);
111
+ out.post = bearer ? { url, bearer } : { url };
112
+ } catch {
113
+ /* a hand-edited bad URL is no wake, not a crash */
114
+ }
115
+ }
116
+ if (typeof record.exec === 'string') {
117
+ try {
118
+ out.exec = normalizeWakeExec(record.exec);
119
+ } catch {
120
+ /* same */
121
+ }
122
+ }
123
+ if (!out.post && !out.exec) return null;
124
+ if (typeof record.savedAt === 'string') out.savedAt = record.savedAt;
125
+ return out;
126
+ }
127
+
128
+ /**
129
+ * @param {NodeJS.ProcessEnv} [env]
130
+ * @returns {Promise<WakeConfig | null>}
131
+ */
132
+ export async function readWake(env = process.env) {
133
+ /** @type {string} */
134
+ let text;
135
+ try {
136
+ text = await readFile(wakePath(env), 'utf8');
137
+ } catch (err) {
138
+ if (err && typeof err === 'object' && err.code === 'ENOENT') return null;
139
+ throw Object.assign(new Error('The saved wake setup could not be read.'), { code: 'bad_wake_file' });
140
+ }
141
+ try {
142
+ return normalizeWake(JSON.parse(text));
143
+ } catch {
144
+ throw Object.assign(new Error('The saved wake setup could not be read.'), { code: 'bad_wake_file' });
145
+ }
146
+ }
147
+
148
+ /**
149
+ * @param {WakeConfig} config
150
+ * @param {NodeJS.ProcessEnv} [env]
151
+ * @returns {Promise<WakeConfig>}
152
+ */
153
+ export async function saveWake(config, env = process.env) {
154
+ const clean = normalizeWake(config);
155
+ if (!clean) throw bad('Pass --post URL, --exec COMMAND, or both.');
156
+ clean.savedAt = new Date().toISOString();
157
+ const dir = configDir(env);
158
+ await mkdir(dir, { recursive: true, mode: 0o700 });
159
+ await chmod(dir, 0o700);
160
+ const path = wakePath(env);
161
+ const tmp = join(dir, `.wake-${process.pid}-${Date.now()}.tmp`);
162
+ try {
163
+ await writeFile(tmp, `${JSON.stringify(clean)}\n`, { mode: 0o600, flag: 'wx' });
164
+ await chmod(tmp, 0o600);
165
+ await rename(tmp, path);
166
+ await chmod(path, 0o600);
167
+ } catch {
168
+ await rm(tmp, { force: true });
169
+ throw Object.assign(new Error('Could not save the wake setup.'), { code: 'save_failed' });
170
+ }
171
+ return clean;
172
+ }
173
+
174
+ /**
175
+ * @param {NodeJS.ProcessEnv} [env]
176
+ */
177
+ export async function clearWake(env = process.env) {
178
+ await rm(wakePath(env), { force: true });
179
+ }
180
+
181
+ /** Which forms are set, in the order they are tried. */
182
+ export function wakeForms(config) {
183
+ const forms = [];
184
+ if (config?.post) forms.push('post');
185
+ if (config?.exec) forms.push('exec');
186
+ return forms;
187
+ }
188
+
189
+ /**
190
+ * A wake URL as it may be shown: the origin only. A routine webhook (Grok
191
+ * Bot, Cursor) carries its secret in the path, so the path is never printed.
192
+ * @param {string} url
193
+ */
194
+ export function wakeUrlForDisplay(url) {
195
+ try {
196
+ const parsed = new URL(url);
197
+ const rest = `${parsed.pathname}${parsed.search}`;
198
+ return rest && rest !== '/' ? `${parsed.origin}/…` : parsed.origin;
199
+ } catch {
200
+ return '(a URL)';
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Status text. Never includes the bearer, nor the path of the URL.
206
+ * @param {WakeConfig | null} config
207
+ */
208
+ export function formatWake(config) {
209
+ if (!config) return 'wake: not set\n';
210
+ const lines = [];
211
+ if (config.post) lines.push(`wake post: ${wakeUrlForDisplay(config.post.url)}${config.post.bearer ? ' (with a bearer key)' : ''}`);
212
+ if (config.exec) lines.push(`wake exec: ${config.exec}`);
213
+ return `${lines.join('\n')}\n`;
214
+ }