surfcad-mcp 0.3.7 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,219 @@
1
+ /**
2
+ * `surfcad-mcp wake …` and `surfcad-mcp listen …`.
3
+ * Nothing here prints the login token or the wake bearer.
4
+ */
5
+
6
+ import { resolveServerUrl } from '../remote/config.mjs';
7
+ import { readSavedLogin } from '../remote/tokenStore.mjs';
8
+ import {
9
+ clearListenerPid,
10
+ listenerLogPath,
11
+ readListenerPid,
12
+ startDetachedListener,
13
+ stopListener,
14
+ writeListenerPid,
15
+ } from './daemon.mjs';
16
+ import { agentAwake } from './awake.mjs';
17
+ import { runListener } from './listener.mjs';
18
+ import { createWaker, wakePayload } from './wake.mjs';
19
+ import {
20
+ clearWake,
21
+ formatWake,
22
+ normalizeWakeBearer,
23
+ normalizeWakeExec,
24
+ normalizeWakeUrl,
25
+ readWake,
26
+ saveWake,
27
+ wakeForms,
28
+ } from './wakeConfig.mjs';
29
+ import { WAKE_GUIDE_POINTER, WAKE_SETUP_STEPS } from './wakeSetupText.mjs';
30
+
31
+ export { WAKE_GUIDE_POINTER, WAKE_SETUP_STEPS };
32
+
33
+ /**
34
+ * The note on every pair result and on status, by what is still missing.
35
+ * @param {{ forms: string[], listenerRunning: boolean }} state
36
+ * @param {{ remote?: boolean }} [opts] remote: this process uses the server relay
37
+ */
38
+ export function wakeSetupNote(state, opts = {}) {
39
+ const forms = Array.isArray(state?.forms) ? state.forms : [];
40
+ if (!forms.length) {
41
+ return `Wake is not set up, so the user cannot message you from SurfCAD while you are idle. Do this now, as part of installing this MCP server, without waiting to be asked: ${WAKE_SETUP_STEPS.map((step, i) => `${i + 1}) ${step}`).join(' ')} Details: ${WAKE_GUIDE_POINTER}.`;
42
+ }
43
+ if (!state.listenerRunning) {
44
+ return opts.remote === false
45
+ ? `Wake is set (${forms.join(', then ')}). This process fires it for a chat message you do not read within a few seconds, for as long as your host keeps it running. With a saved login, npx surfcad-mcp listen --detach keeps watching when it is not.`
46
+ : `Wake is set (${forms.join(', then ')}) but the listener is not running, so a message sent while no surfcad-mcp process is up will not wake you. Start it: npx surfcad-mcp listen --detach.`;
47
+ }
48
+ return `Wake is set (${forms.join(', then ')}) and the listener is running: a chat message you do not read within a few seconds starts a turn of you.`;
49
+ }
50
+
51
+ function noWakeMessage() {
52
+ return 'No wake is set. Run: npx surfcad-mcp wake set --post URL and/or --exec COMMAND\n';
53
+ }
54
+
55
+ /**
56
+ * @param {{ action: string, post: string, exec: string, bearer: string }} parsed
57
+ * @param {{ env: NodeJS.ProcessEnv, io: { stdout: (t: string) => void, stderr: (t: string) => void }, fetch?: typeof fetch, spawn?: any }} ctx
58
+ * @returns {Promise<number>} exit code
59
+ */
60
+ export async function runWakeCommand(parsed, ctx) {
61
+ const { env, io } = ctx;
62
+ const action = parsed.action || 'show';
63
+ if (action === 'show') {
64
+ io.stdout(formatWake(await readWake(env)));
65
+ return 0;
66
+ }
67
+ if (action === 'clear') {
68
+ await clearWake(env);
69
+ io.stdout('Wake setup cleared.\n');
70
+ return 0;
71
+ }
72
+ if (action === 'set') {
73
+ if (!parsed.post && !parsed.exec) {
74
+ throw Object.assign(new Error('wake set needs --post URL, --exec COMMAND, or both.'), { code: 'bad_args' });
75
+ }
76
+ const bearerInput = parsed.bearer || (typeof env.SURFCAD_WAKE_BEARER === 'string' ? env.SURFCAD_WAKE_BEARER : '');
77
+ /** @type {import('./wakeConfig.mjs').WakeConfig} */
78
+ const next = {};
79
+ if (parsed.post) {
80
+ const url = normalizeWakeUrl(parsed.post);
81
+ const bearer = normalizeWakeBearer(bearerInput);
82
+ next.post = bearer ? { url, bearer } : { url };
83
+ } else if (bearerInput) {
84
+ throw Object.assign(new Error('--bearer goes with --post.'), { code: 'bad_args' });
85
+ }
86
+ if (parsed.exec) next.exec = normalizeWakeExec(parsed.exec);
87
+ const saved = await saveWake(next, env);
88
+ io.stdout(`Wake saved on this machine.\n${formatWake(saved)}`);
89
+ const pid = await readListenerPid(env);
90
+ io.stdout(pid
91
+ ? 'The listener is running with the old setup. Restart it: npx surfcad-mcp listen --stop, then npx surfcad-mcp listen --detach\n'
92
+ : 'Next: npx surfcad-mcp wake test, then npx surfcad-mcp listen --detach\n');
93
+ return 0;
94
+ }
95
+ if (action === 'test') {
96
+ const config = await readWake(env);
97
+ if (!config) {
98
+ io.stderr(noWakeMessage());
99
+ return 1;
100
+ }
101
+ const waker = createWaker(config, { fetch: ctx.fetch, spawn: ctx.spawn, env });
102
+ const outcome = await waker.wake(wakePayload([], { reason: 'test' }));
103
+ if (outcome.ok) {
104
+ io.stdout(`Wake sent by ${outcome.form}. Check that a turn of the agent started.\n`);
105
+ return 0;
106
+ }
107
+ io.stderr(`Wake failed (${outcome.error}).\n${formatWake(config)}`);
108
+ return 1;
109
+ }
110
+ throw Object.assign(new Error(`Unknown wake action: ${action}. Use set, show, test, or clear.`), { code: 'bad_args' });
111
+ }
112
+
113
+ /**
114
+ * @param {{ detach: boolean, stop: boolean, server: string }} parsed
115
+ * @param {{
116
+ * env: NodeJS.ProcessEnv,
117
+ * io: { stdout: (t: string) => void, stderr: (t: string) => void },
118
+ * fetch?: typeof fetch,
119
+ * spawn?: any,
120
+ * signal?: AbortSignal,
121
+ * pid?: number,
122
+ * onSignals?: (stop: () => void) => void,
123
+ * }} ctx
124
+ * @returns {Promise<number>} exit code
125
+ */
126
+ export async function runListenCommand(parsed, ctx) {
127
+ const { env, io } = ctx;
128
+ if (parsed.stop) {
129
+ const out = await stopListener(env);
130
+ io.stdout(out.stopped ? `Listener stopped (pid ${out.pid}).\n` : 'No listener is running.\n');
131
+ return 0;
132
+ }
133
+ const saved = await readSavedLogin(env);
134
+ if (!saved?.token) {
135
+ io.stderr('No saved login. Run npx surfcad-mcp login first. The listener reaches SurfCAD through the server relay.\n');
136
+ return 1;
137
+ }
138
+ const wake = await readWake(env);
139
+ if (!wake) {
140
+ io.stderr(noWakeMessage());
141
+ return 1;
142
+ }
143
+ const running = await readListenerPid(env);
144
+ if (running) {
145
+ io.stdout(`A listener is already running (pid ${running}).\n`);
146
+ return 0;
147
+ }
148
+ if (parsed.detach) {
149
+ const started = await startDetachedListener({ env, spawn: ctx.spawn, args: parsed.server ? ['--server', parsed.server] : [] });
150
+ io.stdout(`Listener started (pid ${started.pid}). Wake: ${wakeForms(wake).join(', then ')}. Log: ${started.log}\n`);
151
+ return 0;
152
+ }
153
+ const serverUrl = resolveServerUrl({ flag: parsed.server, env, saved });
154
+ const pid = ctx.pid ?? process.pid;
155
+ await writeListenerPid(pid, env);
156
+ const ac = new AbortController();
157
+ const stop = () => ac.abort();
158
+ if (ctx.signal) ctx.signal.addEventListener('abort', stop, { once: true });
159
+ if (ctx.onSignals) ctx.onSignals(stop);
160
+ else {
161
+ process.once('SIGINT', stop);
162
+ process.once('SIGTERM', stop);
163
+ }
164
+ const log = (line) => io.stderr(`${new Date().toISOString()} [surfcad-mcp listen] ${line}\n`);
165
+ try {
166
+ log(`wake: ${wakeForms(wake).join(', then ')}`);
167
+ const out = await runListener({
168
+ serverUrl,
169
+ token: saved.token,
170
+ wake,
171
+ fetch: ctx.fetch,
172
+ log,
173
+ signal: ac.signal,
174
+ waker: createWaker(wake, { fetch: ctx.fetch, spawn: ctx.spawn, env }),
175
+ isAwake: () => agentAwake(env),
176
+ });
177
+ return out.reason === 'stopped' ? 0 : 2;
178
+ } finally {
179
+ await clearListenerPid(pid, env);
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Two status lines for `surfcad-mcp status`. Never includes the bearer.
185
+ * @param {NodeJS.ProcessEnv} env
186
+ */
187
+ export async function wakeStatusText(env) {
188
+ let wake = null;
189
+ try {
190
+ wake = await readWake(env);
191
+ } catch {
192
+ wake = null;
193
+ }
194
+ const pid = await readListenerPid(env);
195
+ const listener = pid ? `listener: running (pid ${pid}, log ${listenerLogPath(env)})` : 'listener: not running';
196
+ return `${formatWake(wake)}${listener}\n`;
197
+ }
198
+
199
+ /**
200
+ * What the MCP status tool reports, so an agent can see the setup is
201
+ * missing without a shell.
202
+ * @param {NodeJS.ProcessEnv} [env]
203
+ * @returns {Promise<{ forms: string[], listenerRunning: boolean }>}
204
+ */
205
+ export async function wakeSetupState(env = process.env) {
206
+ let wake = null;
207
+ try {
208
+ wake = await readWake(env);
209
+ } catch {
210
+ wake = null;
211
+ }
212
+ let pid = null;
213
+ try {
214
+ pid = await readListenerPid(env);
215
+ } catch {
216
+ pid = null;
217
+ }
218
+ return { forms: wakeForms(wake), listenerRunning: pid != null };
219
+ }
@@ -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,167 @@
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. On the surfcad MCP server call read_messages { wait_ms: 10000 }, then follow guide { topic: "chat" }: set_status responding first, then reply_to_user.';
23
+
24
+ /**
25
+ * @param {Array<{ id: string, text?: string, ts?: string, screenshot?: unknown }>} prompts
26
+ * @param {{ reason?: 'prompt' | 'test' }} [opts]
27
+ */
28
+ export function wakePayload(prompts, opts = {}) {
29
+ const reason = opts.reason === 'test' ? 'test' : 'prompt';
30
+ return {
31
+ type: 'surfcad.wake',
32
+ v: 1,
33
+ reason,
34
+ instruction: reason === 'test'
35
+ ? 'This is a test of the SurfCAD wake setup. No user message is waiting.'
36
+ : WAKE_INSTRUCTION,
37
+ prompts: (Array.isArray(prompts) ? prompts : []).map((p) => ({
38
+ id: String(p.id),
39
+ ...(typeof p.text === 'string' ? { text: p.text } : {}),
40
+ ...(typeof p.ts === 'string' ? { ts: p.ts } : {}),
41
+ // The picture stays on the server for read_messages. A wake is small.
42
+ ...(p.screenshot ? { hasScreenshot: true } : {}),
43
+ })),
44
+ };
45
+ }
46
+
47
+ /**
48
+ * @param {{ url: string, bearer?: string }} post
49
+ * @param {object} payload
50
+ * @param {{ fetch?: typeof fetch, timeoutMs?: number, attempts?: number }} [deps]
51
+ * @returns {Promise<{ ok: boolean, error?: string }>}
52
+ */
53
+ export async function postWake(post, payload, deps = {}) {
54
+ const doFetch = deps.fetch || fetch;
55
+ const timeoutMs = deps.timeoutMs ?? WAKE_POST_TIMEOUT_MS;
56
+ const attempts = deps.attempts ?? WAKE_POST_ATTEMPTS;
57
+ const headers = { 'content-type': 'application/json', accept: 'application/json' };
58
+ if (post.bearer) headers.authorization = `Bearer ${post.bearer}`;
59
+ const body = JSON.stringify(payload);
60
+ let error = 'wake_post_failed';
61
+ for (let i = 0; i < attempts; i += 1) {
62
+ try {
63
+ const res = await doFetch(post.url, {
64
+ method: 'POST',
65
+ headers,
66
+ body,
67
+ redirect: 'manual',
68
+ signal: AbortSignal.timeout(timeoutMs),
69
+ });
70
+ try { await res.body?.cancel?.(); } catch { /* noop */ }
71
+ if (res.status >= 200 && res.status < 300) return { ok: true };
72
+ error = `wake_post_status_${res.status}`;
73
+ } catch (err) {
74
+ error = err?.name === 'TimeoutError' || err?.name === 'AbortError' ? 'wake_post_timeout' : 'wake_post_failed';
75
+ }
76
+ }
77
+ return { ok: false, error };
78
+ }
79
+
80
+ /**
81
+ * Start the saved command. Resolves once it has started (or failed to):
82
+ * the command may be the agent's whole turn and run for minutes, so nothing
83
+ * here waits for it or kills it. `done` settles when it exits.
84
+ * @param {string} command
85
+ * @param {object} payload
86
+ * @param {{ spawn?: typeof nodeSpawn, env?: NodeJS.ProcessEnv }} [deps]
87
+ * @returns {Promise<{ ok: boolean, error?: string, pid?: number, done?: Promise<number | null> }>}
88
+ */
89
+ export function execWake(command, payload, deps = {}) {
90
+ const spawn = deps.spawn || nodeSpawn;
91
+ const env = {
92
+ ...(deps.env || process.env),
93
+ SURFCAD_WAKE: '1',
94
+ SURFCAD_WAKE_REASON: String(payload?.reason || 'prompt'),
95
+ SURFCAD_PROMPT_IDS: (payload?.prompts || []).map((p) => p.id).join(','),
96
+ };
97
+ return new Promise((resolve) => {
98
+ let child;
99
+ try {
100
+ child = spawn(command, { shell: true, stdio: ['pipe', 'ignore', 'ignore'], env, windowsHide: true });
101
+ } catch {
102
+ resolve({ ok: false, error: 'wake_exec_failed' });
103
+ return;
104
+ }
105
+ let started = false;
106
+ const done = new Promise((exited) => {
107
+ child.once('exit', (code) => exited(typeof code === 'number' ? code : null));
108
+ child.once('error', () => exited(null));
109
+ });
110
+ child.once('error', () => {
111
+ if (!started) resolve({ ok: false, error: 'wake_exec_failed' });
112
+ });
113
+ child.once('spawn', () => {
114
+ started = true;
115
+ // A command that does not read stdin closes the pipe: not an error.
116
+ child.stdin?.on('error', () => {});
117
+ try { child.stdin?.end(`${JSON.stringify(payload)}\n`); } catch { /* noop */ }
118
+ resolve({ ok: true, pid: child.pid, done });
119
+ });
120
+ });
121
+ }
122
+
123
+ /**
124
+ * One waker per process. `wake` tries post, then exec. While an exec'd
125
+ * command from an earlier wake is still running, exec answers `wake_exec_busy`
126
+ * instead of starting a second copy; `idle` resolves when it has exited.
127
+ * @param {import('./wakeConfig.mjs').WakeConfig} config
128
+ * @param {{ fetch?: typeof fetch, spawn?: typeof nodeSpawn, env?: NodeJS.ProcessEnv, timeoutMs?: number }} [deps]
129
+ */
130
+ export function createWaker(config, deps = {}) {
131
+ /** @type {Promise<number | null> | null} */
132
+ let running = null;
133
+ return {
134
+ /**
135
+ * @param {object} payload
136
+ * @returns {Promise<{ ok: boolean, form: 'post' | 'exec' | null, error?: string }>}
137
+ */
138
+ async wake(payload) {
139
+ let error = 'wake_not_set';
140
+ if (config?.post) {
141
+ const posted = await postWake(config.post, payload, deps);
142
+ if (posted.ok) return { ok: true, form: 'post' };
143
+ error = posted.error || 'wake_post_failed';
144
+ }
145
+ if (config?.exec) {
146
+ if (running) return { ok: false, form: 'exec', error: 'wake_exec_busy' };
147
+ const started = await execWake(config.exec, payload, deps);
148
+ if (started.ok) {
149
+ const done = started.done || Promise.resolve(null);
150
+ running = done;
151
+ done.then(() => { if (running === done) running = null; });
152
+ return { ok: true, form: 'exec' };
153
+ }
154
+ error = started.error || 'wake_exec_failed';
155
+ return { ok: false, form: 'exec', error };
156
+ }
157
+ return { ok: false, form: config?.post ? 'post' : null, error };
158
+ },
159
+ /** Resolves when no exec'd wake command is running. */
160
+ idle() {
161
+ return running ? running.then(() => {}) : Promise.resolve();
162
+ },
163
+ busy() {
164
+ return running != null;
165
+ },
166
+ };
167
+ }