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.
- package/README.md +77 -2
- package/data/commands.json +2 -2
- package/package.json +1 -1
- package/src/cli.mjs +110 -9
- package/src/listen/awake.mjs +71 -0
- package/src/listen/bootstrap.mjs +232 -0
- package/src/listen/daemon.mjs +133 -0
- package/src/listen/listenCli.mjs +258 -0
- package/src/listen/listener.mjs +250 -0
- package/src/listen/wake.mjs +181 -0
- package/src/listen/wakeConfig.mjs +214 -0
- package/src/listen/wakeSetupText.mjs +55 -0
- package/src/prompt/guide.mjs +13 -9
- package/src/prompt/promptSession.mjs +25 -0
- package/src/prompt/promptTools.mjs +0 -9
- package/src/relay.mjs +1 -0
- package/src/remote/session.mjs +1 -0
- package/src/remote/tokenStore.mjs +20 -0
- package/src/server.mjs +185 -12
|
@@ -0,0 +1,232 @@
|
|
|
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
|
+
* 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.
|
|
21
|
+
*
|
|
22
|
+
* With no wake, nothing is pretended: the state says cold wake is
|
|
23
|
+
* unavailable, and the session that paired greets the user itself.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { createHash } from 'node:crypto';
|
|
27
|
+
import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
28
|
+
import { join } from 'node:path';
|
|
29
|
+
import { configDir } from '../remote/config.mjs';
|
|
30
|
+
import { readSavedLogin } from '../remote/tokenStore.mjs';
|
|
31
|
+
import { readListenerPid, startDetachedListener } from './daemon.mjs';
|
|
32
|
+
import { createWaker, wakePayload } from './wake.mjs';
|
|
33
|
+
import {
|
|
34
|
+
normalizeWakeBearer,
|
|
35
|
+
normalizeWakeExec,
|
|
36
|
+
normalizeWakeUrl,
|
|
37
|
+
readWake,
|
|
38
|
+
saveWake,
|
|
39
|
+
wakeForms,
|
|
40
|
+
} from './wakeConfig.mjs';
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The wake the host put in this server's environment, or null. A value that
|
|
44
|
+
* does not pass the `wake set` rules is left out and named in `problems`.
|
|
45
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
46
|
+
* @returns {{ config: import('./wakeConfig.mjs').WakeConfig | null, problems: string[] }}
|
|
47
|
+
*/
|
|
48
|
+
export function wakeFromEnv(env = process.env) {
|
|
49
|
+
/** @type {import('./wakeConfig.mjs').WakeConfig} */
|
|
50
|
+
const config = {};
|
|
51
|
+
const problems = [];
|
|
52
|
+
const text = (name) => (typeof env[name] === 'string' ? env[name].trim() : '');
|
|
53
|
+
if (text('SURFCAD_WAKE_POST')) {
|
|
54
|
+
try {
|
|
55
|
+
const url = normalizeWakeUrl(text('SURFCAD_WAKE_POST'));
|
|
56
|
+
const bearer = normalizeWakeBearer(text('SURFCAD_WAKE_BEARER'));
|
|
57
|
+
config.post = bearer ? { url, bearer } : { url };
|
|
58
|
+
} catch (err) {
|
|
59
|
+
problems.push(`SURFCAD_WAKE_POST: ${err?.message || 'not a usable URL'}`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (text('SURFCAD_WAKE_EXEC')) {
|
|
63
|
+
try {
|
|
64
|
+
config.exec = normalizeWakeExec(text('SURFCAD_WAKE_EXEC'));
|
|
65
|
+
} catch (err) {
|
|
66
|
+
problems.push(`SURFCAD_WAKE_EXEC: ${err?.message || 'not a usable command'}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return { config: config.post || config.exec ? config : null, problems };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function sameWake(a, b) {
|
|
73
|
+
const norm = (c) => JSON.stringify({ post: c?.post ? { url: c.post.url, bearer: c.post.bearer || '' } : null, exec: c?.exec || '' });
|
|
74
|
+
return norm(a) === norm(b);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The wake for this machine and where it came from. The environment wins: it
|
|
79
|
+
* is what the host says now, and it is written to wake.json so the listener,
|
|
80
|
+
* a separate process, uses the same one.
|
|
81
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
82
|
+
* @returns {Promise<{ config: import('./wakeConfig.mjs').WakeConfig | null, source: 'env' | 'saved' | null, problems: string[] }>}
|
|
83
|
+
*/
|
|
84
|
+
export async function provisionWake(env = process.env) {
|
|
85
|
+
const fromEnv = wakeFromEnv(env);
|
|
86
|
+
let saved = null;
|
|
87
|
+
try {
|
|
88
|
+
saved = await readWake(env);
|
|
89
|
+
} catch {
|
|
90
|
+
saved = null;
|
|
91
|
+
}
|
|
92
|
+
if (fromEnv.config) {
|
|
93
|
+
if (!sameWake(fromEnv.config, saved)) {
|
|
94
|
+
try {
|
|
95
|
+
saved = await saveWake(fromEnv.config, env);
|
|
96
|
+
} catch {
|
|
97
|
+
return { config: fromEnv.config, source: 'env', problems: [...fromEnv.problems, 'The wake could not be saved for the listener.'] };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return { config: saved || fromEnv.config, source: 'env', problems: fromEnv.problems };
|
|
101
|
+
}
|
|
102
|
+
return { config: saved, source: saved ? 'saved' : null, problems: fromEnv.problems };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** @param {NodeJS.ProcessEnv} [env] */
|
|
106
|
+
export function wakeStatePath(env = process.env) {
|
|
107
|
+
return join(configDir(env), 'wake-state.json');
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** A short one-way mark of a login. Never the token. */
|
|
111
|
+
function loginMark(token) {
|
|
112
|
+
return createHash('sha256').update(String(token || 'local')).digest('hex').slice(0, 16);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function readState(env) {
|
|
116
|
+
try {
|
|
117
|
+
const parsed = JSON.parse(await readFile(wakeStatePath(env), 'utf8'));
|
|
118
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
119
|
+
} catch {
|
|
120
|
+
return {};
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function writeState(state, env) {
|
|
125
|
+
try {
|
|
126
|
+
await mkdir(configDir(env), { recursive: true, mode: 0o700 });
|
|
127
|
+
await writeFile(wakeStatePath(env), `${JSON.stringify(state)}\n`, { mode: 0o600 });
|
|
128
|
+
await chmod(wakeStatePath(env), 0o600);
|
|
129
|
+
} catch {
|
|
130
|
+
/* a greeting sent twice is the worst that happens */
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* @typedef {{
|
|
136
|
+
* forms: string[],
|
|
137
|
+
* source: 'env' | 'saved' | null,
|
|
138
|
+
* listenerRunning: boolean,
|
|
139
|
+
* listenerStarted: boolean,
|
|
140
|
+
* coldWake: 'ready' | 'listener_stopped' | 'unavailable',
|
|
141
|
+
* greeting: 'sent_by_wake' | 'send_it_yourself' | 'already_sent' | 'wake_failed',
|
|
142
|
+
* problems: string[],
|
|
143
|
+
* }} WakeBootstrap
|
|
144
|
+
*/
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Run after a successful pair or login.
|
|
148
|
+
* @param {{
|
|
149
|
+
* env?: NodeJS.ProcessEnv,
|
|
150
|
+
* remote: boolean,
|
|
151
|
+
* greet?: boolean,
|
|
152
|
+
* selfGreet?: boolean,
|
|
153
|
+
* autoListen?: boolean,
|
|
154
|
+
* spawn?: any,
|
|
155
|
+
* fetch?: typeof fetch,
|
|
156
|
+
* waker?: ReturnType<typeof createWaker>,
|
|
157
|
+
* startListener?: typeof startDetachedListener,
|
|
158
|
+
* listenerPid?: typeof readListenerPid,
|
|
159
|
+
* }} options
|
|
160
|
+
* `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).
|
|
162
|
+
* `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.
|
|
165
|
+
* @returns {Promise<WakeBootstrap>}
|
|
166
|
+
*/
|
|
167
|
+
export async function bootstrapWake(options) {
|
|
168
|
+
const env = options.env || process.env;
|
|
169
|
+
const listenerPid = options.listenerPid || readListenerPid;
|
|
170
|
+
const { config, source, problems } = await provisionWake(env);
|
|
171
|
+
const forms = wakeForms(config);
|
|
172
|
+
|
|
173
|
+
let listenerRunning = false;
|
|
174
|
+
let listenerStarted = false;
|
|
175
|
+
let token = '';
|
|
176
|
+
if (options.remote) {
|
|
177
|
+
try {
|
|
178
|
+
token = (await readSavedLogin(env))?.token || '';
|
|
179
|
+
} catch {
|
|
180
|
+
token = '';
|
|
181
|
+
}
|
|
182
|
+
listenerRunning = (await listenerPid(env)) != null;
|
|
183
|
+
// A listener with no wake cannot start a turn, so it is not started.
|
|
184
|
+
if (config && token && !listenerRunning && options.autoListen !== false) {
|
|
185
|
+
try {
|
|
186
|
+
await (options.startListener || startDetachedListener)({ env, spawn: options.spawn });
|
|
187
|
+
listenerStarted = true;
|
|
188
|
+
listenerRunning = (await listenerPid(env)) != null;
|
|
189
|
+
} catch {
|
|
190
|
+
problems.push('The listener could not be started. Run: npx surfcad-mcp listen --detach');
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Cold wake: something can start a turn while no agent process is up.
|
|
196
|
+
// The local relay has no listener; there this process fires the wake, so
|
|
197
|
+
// it holds only while the host keeps the process running.
|
|
198
|
+
/** @type {WakeBootstrap['coldWake']} */
|
|
199
|
+
let coldWake = 'unavailable';
|
|
200
|
+
if (config) coldWake = !options.remote || listenerRunning ? 'ready' : 'listener_stopped';
|
|
201
|
+
|
|
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) {
|
|
207
|
+
const mark = loginMark(options.remote ? token : 'local');
|
|
208
|
+
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 {
|
|
217
|
+
const waker = options.waker || createWaker(config, { env, fetch: options.fetch, spawn: options.spawn });
|
|
218
|
+
const outcome = await waker.wake(wakePayload([], { reason: 'greet' }));
|
|
219
|
+
if (outcome.ok) {
|
|
220
|
+
greeting = 'sent_by_wake';
|
|
221
|
+
await done();
|
|
222
|
+
} else {
|
|
223
|
+
// Not marked: the next pair tries the wake again.
|
|
224
|
+
greeting = 'wake_failed';
|
|
225
|
+
problems.push(`The wake did not fire (${outcome.error}).`);
|
|
226
|
+
coldWake = 'unavailable';
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return { forms, source, listenerRunning, listenerStarted, coldWake, greeting, problems };
|
|
232
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One listener per config directory: a pid file, a log file, and a detached
|
|
3
|
+
* start for agents that set the listener up with one command and move on.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { spawn as nodeSpawn } from 'node:child_process';
|
|
7
|
+
import { closeSync, openSync } from 'node:fs';
|
|
8
|
+
import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { configDir } from '../remote/config.mjs';
|
|
12
|
+
|
|
13
|
+
/** @param {NodeJS.ProcessEnv} [env] */
|
|
14
|
+
export function listenerPidPath(env = process.env) {
|
|
15
|
+
return join(configDir(env), 'listener.pid');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** @param {NodeJS.ProcessEnv} [env] */
|
|
19
|
+
export function listenerLogPath(env = process.env) {
|
|
20
|
+
return join(configDir(env), 'listener.log');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param {number} pid
|
|
25
|
+
* @param {(pid: number, signal: number) => void} [kill]
|
|
26
|
+
*/
|
|
27
|
+
export function pidAlive(pid, kill = process.kill.bind(process)) {
|
|
28
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
29
|
+
try {
|
|
30
|
+
kill(pid, 0);
|
|
31
|
+
return true;
|
|
32
|
+
} catch (err) {
|
|
33
|
+
// EPERM: it exists and belongs to someone else. Still alive.
|
|
34
|
+
return Boolean(err && typeof err === 'object' && err.code === 'EPERM');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The pid of the running listener, or null. A pid file left by a listener
|
|
40
|
+
* that died is removed.
|
|
41
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
42
|
+
* @param {{ kill?: (pid: number, signal: number) => void }} [deps]
|
|
43
|
+
* @returns {Promise<number | null>}
|
|
44
|
+
*/
|
|
45
|
+
export async function readListenerPid(env = process.env, deps = {}) {
|
|
46
|
+
let text;
|
|
47
|
+
try {
|
|
48
|
+
text = await readFile(listenerPidPath(env), 'utf8');
|
|
49
|
+
} catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
const pid = Number.parseInt(text.trim(), 10);
|
|
53
|
+
if (pidAlive(pid, deps.kill)) return pid;
|
|
54
|
+
await rm(listenerPidPath(env), { force: true });
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {number} pid
|
|
60
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
61
|
+
*/
|
|
62
|
+
export async function writeListenerPid(pid, env = process.env) {
|
|
63
|
+
const dir = configDir(env);
|
|
64
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
65
|
+
await writeFile(listenerPidPath(env), `${pid}\n`, { mode: 0o600 });
|
|
66
|
+
await chmod(listenerPidPath(env), 0o600);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Remove the pid file if it still names `pid`.
|
|
71
|
+
* @param {number} pid
|
|
72
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
73
|
+
*/
|
|
74
|
+
export async function clearListenerPid(pid, env = process.env) {
|
|
75
|
+
try {
|
|
76
|
+
const text = await readFile(listenerPidPath(env), 'utf8');
|
|
77
|
+
if (Number.parseInt(text.trim(), 10) !== pid) return;
|
|
78
|
+
} catch {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
await rm(listenerPidPath(env), { force: true });
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Start `surfcad-mcp listen` as its own process group with its output in
|
|
86
|
+
* the log file, and return at once.
|
|
87
|
+
* @param {{ env?: NodeJS.ProcessEnv, spawn?: typeof nodeSpawn, bin?: string, args?: string[] }} [options]
|
|
88
|
+
* @returns {Promise<{ pid: number | undefined, log: string }>}
|
|
89
|
+
*/
|
|
90
|
+
export async function startDetachedListener(options = {}) {
|
|
91
|
+
const env = options.env || process.env;
|
|
92
|
+
const spawn = options.spawn || nodeSpawn;
|
|
93
|
+
const bin = options.bin || fileURLToPath(new URL('../../bin/surfcad-mcp.js', import.meta.url));
|
|
94
|
+
const dir = configDir(env);
|
|
95
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
96
|
+
const log = listenerLogPath(env);
|
|
97
|
+
const fd = openSync(log, 'a', 0o600);
|
|
98
|
+
try {
|
|
99
|
+
const child = spawn(process.execPath, [bin, 'listen', ...(options.args || [])], {
|
|
100
|
+
detached: true,
|
|
101
|
+
stdio: ['ignore', fd, fd],
|
|
102
|
+
env,
|
|
103
|
+
windowsHide: true,
|
|
104
|
+
});
|
|
105
|
+
child.unref?.();
|
|
106
|
+
// The listener writes this itself once it is up. Writing it here too
|
|
107
|
+
// means "running" is true the moment --detach returns, with no gap in
|
|
108
|
+
// which a second start or a status read sees nothing. A child that dies
|
|
109
|
+
// at once leaves a dead pid, and readListenerPid removes those.
|
|
110
|
+
if (Number.isInteger(child.pid) && child.pid > 0) await writeListenerPid(child.pid, env);
|
|
111
|
+
return { pid: child.pid, log };
|
|
112
|
+
} finally {
|
|
113
|
+
closeSync(fd);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
119
|
+
* @param {{ kill?: (pid: number, signal: number | string) => void }} [deps]
|
|
120
|
+
* @returns {Promise<{ stopped: boolean, pid: number | null }>}
|
|
121
|
+
*/
|
|
122
|
+
export async function stopListener(env = process.env, deps = {}) {
|
|
123
|
+
const kill = deps.kill || process.kill.bind(process);
|
|
124
|
+
const pid = await readListenerPid(env, { kill });
|
|
125
|
+
if (!pid) return { stopped: false, pid: null };
|
|
126
|
+
try {
|
|
127
|
+
kill(pid, 'SIGTERM');
|
|
128
|
+
} catch {
|
|
129
|
+
/* gone between the check and the signal */
|
|
130
|
+
}
|
|
131
|
+
await rm(listenerPidPath(env), { force: true });
|
|
132
|
+
return { stopped: true, pid };
|
|
133
|
+
}
|
|
@@ -0,0 +1,258 @@
|
|
|
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 { forgetLoginIfToken, 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 { bootstrapWake } from './bootstrap.mjs';
|
|
18
|
+
import { runListener } from './listener.mjs';
|
|
19
|
+
import { createWaker, WAKE_GREETING, wakePayload } from './wake.mjs';
|
|
20
|
+
import {
|
|
21
|
+
clearWake,
|
|
22
|
+
formatWake,
|
|
23
|
+
normalizeWakeBearer,
|
|
24
|
+
normalizeWakeExec,
|
|
25
|
+
normalizeWakeUrl,
|
|
26
|
+
readWake,
|
|
27
|
+
saveWake,
|
|
28
|
+
wakeForms,
|
|
29
|
+
} from './wakeConfig.mjs';
|
|
30
|
+
import { HOST_PROVISION_NOTE, WAKE_GUIDE_POINTER, WAKE_SETUP_STEPS } from './wakeSetupText.mjs';
|
|
31
|
+
|
|
32
|
+
export { WAKE_GUIDE_POINTER, WAKE_SETUP_STEPS };
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* What an agent is told about being reachable while idle. It says what is
|
|
36
|
+
* true and nothing more: "ready" only when a wake is set and something will
|
|
37
|
+
* fire it. It never tells the agent to ask the user for a webhook URL.
|
|
38
|
+
* @param {import('./bootstrap.mjs').WakeBootstrap} state
|
|
39
|
+
* @param {{ remote?: boolean }} [opts] remote: this process is on the server relay
|
|
40
|
+
*/
|
|
41
|
+
export function wakeReadinessNote(state, opts = {}) {
|
|
42
|
+
const forms = Array.isArray(state?.forms) ? state.forms : [];
|
|
43
|
+
const lines = [];
|
|
44
|
+
if (state?.coldWake === 'ready') {
|
|
45
|
+
lines.push(opts.remote === false
|
|
46
|
+
? `Idle wake: ready (${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.`
|
|
47
|
+
: `Idle wake: ready (${forms.join(', then ')}; listener running). When the user messages you from SurfCAD while you are idle, a new session of you starts and reads the message.`);
|
|
48
|
+
} else if (state?.coldWake === 'listener_stopped') {
|
|
49
|
+
lines.push(`Idle wake: set (${forms.join(', then ')}) but the listener is not running, so a message sent while you are idle will not start a session. Run: npx surfcad-mcp listen --detach`);
|
|
50
|
+
} else {
|
|
51
|
+
lines.push(`Idle wake: unavailable on this host. Nothing here can start a session of you, so the user's messages reach you only while you are in a turn and long-polling read_messages { wait_ms: 10000 }. Tell the user that if they expect answers while you are idle. Do not ask the user for a webhook URL. ${HOST_PROVISION_NOTE} Otherwise a host that can start a turn sets SURFCAD_WAKE_POST or SURFCAD_WAKE_EXEC in this MCP server's config; ${WAKE_GUIDE_POINTER} has the manual way.`);
|
|
52
|
+
}
|
|
53
|
+
if (state?.greeting === 'sent_by_wake') {
|
|
54
|
+
lines.push(`A new session of you was started to greet the user in the SurfCAD chat ("${WAKE_GREETING}"). That greeting is the check that the wake works. Do not greet again.`);
|
|
55
|
+
} else if (state?.greeting === 'send_it_yourself') {
|
|
56
|
+
lines.push(`Greet the user now: reply_to_user { text: "${WAKE_GREETING}" } with no in_reply_to.`);
|
|
57
|
+
} else if (state?.greeting === 'wake_failed') {
|
|
58
|
+
lines.push(`The wake did not start a session, so idle wake is not working yet. Greet the user yourself: reply_to_user { text: "${WAKE_GREETING}" } with no in_reply_to.`);
|
|
59
|
+
}
|
|
60
|
+
for (const problem of state?.problems || []) lines.push(problem);
|
|
61
|
+
return lines.join(' ');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function noWakeMessage() {
|
|
65
|
+
return 'No wake is set. Run: npx surfcad-mcp wake set --post URL and/or --exec COMMAND\n';
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* @param {{ action: string, post: string, exec: string, bearer: string }} parsed
|
|
70
|
+
* @param {{ env: NodeJS.ProcessEnv, io: { stdout: (t: string) => void, stderr: (t: string) => void }, fetch?: typeof fetch, spawn?: any }} ctx
|
|
71
|
+
* @returns {Promise<number>} exit code
|
|
72
|
+
*/
|
|
73
|
+
export async function runWakeCommand(parsed, ctx) {
|
|
74
|
+
const { env, io } = ctx;
|
|
75
|
+
const action = parsed.action || 'show';
|
|
76
|
+
if (action === 'show') {
|
|
77
|
+
io.stdout(formatWake(await readWake(env)));
|
|
78
|
+
return 0;
|
|
79
|
+
}
|
|
80
|
+
if (action === 'clear') {
|
|
81
|
+
await clearWake(env);
|
|
82
|
+
io.stdout('Wake setup cleared.\n');
|
|
83
|
+
return 0;
|
|
84
|
+
}
|
|
85
|
+
if (action === 'set') {
|
|
86
|
+
if (!parsed.post && !parsed.exec) {
|
|
87
|
+
throw Object.assign(new Error('wake set needs --post URL, --exec COMMAND, or both.'), { code: 'bad_args' });
|
|
88
|
+
}
|
|
89
|
+
const bearerInput = parsed.bearer || (typeof env.SURFCAD_WAKE_BEARER === 'string' ? env.SURFCAD_WAKE_BEARER : '');
|
|
90
|
+
/** @type {import('./wakeConfig.mjs').WakeConfig} */
|
|
91
|
+
const next = {};
|
|
92
|
+
if (parsed.post) {
|
|
93
|
+
const url = normalizeWakeUrl(parsed.post);
|
|
94
|
+
const bearer = normalizeWakeBearer(bearerInput);
|
|
95
|
+
next.post = bearer ? { url, bearer } : { url };
|
|
96
|
+
} else if (bearerInput) {
|
|
97
|
+
throw Object.assign(new Error('--bearer goes with --post.'), { code: 'bad_args' });
|
|
98
|
+
}
|
|
99
|
+
if (parsed.exec) next.exec = normalizeWakeExec(parsed.exec);
|
|
100
|
+
const saved = await saveWake(next, env);
|
|
101
|
+
io.stdout(`Wake saved on this machine.\n${formatWake(saved)}`);
|
|
102
|
+
const pid = await readListenerPid(env);
|
|
103
|
+
io.stdout(pid
|
|
104
|
+
? 'The listener is running with the old setup. Restart it: npx surfcad-mcp listen --stop, then npx surfcad-mcp listen --detach\n'
|
|
105
|
+
: 'Next: npx surfcad-mcp wake test, then npx surfcad-mcp listen --detach\n');
|
|
106
|
+
return 0;
|
|
107
|
+
}
|
|
108
|
+
if (action === 'test') {
|
|
109
|
+
const config = await readWake(env);
|
|
110
|
+
if (!config) {
|
|
111
|
+
io.stderr(noWakeMessage());
|
|
112
|
+
return 1;
|
|
113
|
+
}
|
|
114
|
+
const waker = createWaker(config, { fetch: ctx.fetch, spawn: ctx.spawn, env });
|
|
115
|
+
const outcome = await waker.wake(wakePayload([], { reason: 'test' }));
|
|
116
|
+
if (outcome.ok) {
|
|
117
|
+
io.stdout(`Wake sent by ${outcome.form}. Check that a turn of the agent started.\n`);
|
|
118
|
+
return 0;
|
|
119
|
+
}
|
|
120
|
+
io.stderr(`Wake failed (${outcome.error}).\n${formatWake(config)}`);
|
|
121
|
+
return 1;
|
|
122
|
+
}
|
|
123
|
+
throw Object.assign(new Error(`Unknown wake action: ${action}. Use set, show, test, or clear.`), { code: 'bad_args' });
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* @param {{ detach: boolean, stop: boolean, server: string }} parsed
|
|
128
|
+
* @param {{
|
|
129
|
+
* env: NodeJS.ProcessEnv,
|
|
130
|
+
* io: { stdout: (t: string) => void, stderr: (t: string) => void },
|
|
131
|
+
* fetch?: typeof fetch,
|
|
132
|
+
* spawn?: any,
|
|
133
|
+
* signal?: AbortSignal,
|
|
134
|
+
* pid?: number,
|
|
135
|
+
* onSignals?: (stop: () => void) => void,
|
|
136
|
+
* }} ctx
|
|
137
|
+
* @returns {Promise<number>} exit code
|
|
138
|
+
*/
|
|
139
|
+
export async function runListenCommand(parsed, ctx) {
|
|
140
|
+
const { env, io } = ctx;
|
|
141
|
+
if (parsed.stop) {
|
|
142
|
+
const out = await stopListener(env);
|
|
143
|
+
io.stdout(out.stopped ? `Listener stopped (pid ${out.pid}).\n` : 'No listener is running.\n');
|
|
144
|
+
return 0;
|
|
145
|
+
}
|
|
146
|
+
const saved = await readSavedLogin(env);
|
|
147
|
+
if (!saved?.token) {
|
|
148
|
+
io.stderr('No saved login. Run npx surfcad-mcp login first. The listener reaches SurfCAD through the server relay.\n');
|
|
149
|
+
return 1;
|
|
150
|
+
}
|
|
151
|
+
const wake = await readWake(env);
|
|
152
|
+
if (!wake) {
|
|
153
|
+
io.stderr(noWakeMessage());
|
|
154
|
+
return 1;
|
|
155
|
+
}
|
|
156
|
+
const pid = ctx.pid ?? process.pid;
|
|
157
|
+
const running = await readListenerPid(env);
|
|
158
|
+
// In the foreground, the pid file may already name this very process:
|
|
159
|
+
// --detach writes it before the listener it starts is up.
|
|
160
|
+
if (running && (parsed.detach || running !== pid)) {
|
|
161
|
+
io.stdout(`A listener is already running (pid ${running}).\n`);
|
|
162
|
+
return 0;
|
|
163
|
+
}
|
|
164
|
+
if (parsed.detach) {
|
|
165
|
+
const started = await startDetachedListener({ env, spawn: ctx.spawn, args: parsed.server ? ['--server', parsed.server] : [] });
|
|
166
|
+
io.stdout(`Listener started (pid ${started.pid}). Wake: ${wakeForms(wake).join(', then ')}. Log: ${started.log}\n`);
|
|
167
|
+
return 0;
|
|
168
|
+
}
|
|
169
|
+
const serverUrl = resolveServerUrl({ flag: parsed.server, env, saved });
|
|
170
|
+
await writeListenerPid(pid, env);
|
|
171
|
+
const ac = new AbortController();
|
|
172
|
+
const stop = () => ac.abort();
|
|
173
|
+
if (ctx.signal) ctx.signal.addEventListener('abort', stop, { once: true });
|
|
174
|
+
if (ctx.onSignals) ctx.onSignals(stop);
|
|
175
|
+
else {
|
|
176
|
+
process.once('SIGINT', stop);
|
|
177
|
+
process.once('SIGTERM', stop);
|
|
178
|
+
}
|
|
179
|
+
const log = (line) => io.stderr(`${new Date().toISOString()} [surfcad-mcp listen] ${line}\n`);
|
|
180
|
+
try {
|
|
181
|
+
log(`wake: ${wakeForms(wake).join(', then ')}`);
|
|
182
|
+
const out = await runListener({
|
|
183
|
+
serverUrl,
|
|
184
|
+
token: saved.token,
|
|
185
|
+
wake,
|
|
186
|
+
fetch: ctx.fetch,
|
|
187
|
+
log,
|
|
188
|
+
signal: ac.signal,
|
|
189
|
+
waker: createWaker(wake, { fetch: ctx.fetch, spawn: ctx.spawn, env }),
|
|
190
|
+
isAwake: () => agentAwake(env),
|
|
191
|
+
});
|
|
192
|
+
// Disconnected in SurfCAD, or expired: the saved login is dead. Forget
|
|
193
|
+
// it, so `status` says "not logged in" and nothing retries with it. The
|
|
194
|
+
// server answers a revoked token with a plain 401 ("unauthorized" here).
|
|
195
|
+
if (out.reason !== 'stopped') await forgetLoginIfToken(saved.token, env);
|
|
196
|
+
return out.reason === 'stopped' ? 0 : 2;
|
|
197
|
+
} finally {
|
|
198
|
+
await clearListenerPid(pid, env);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* After `surfcad-mcp login`: with a wake (from the environment or saved),
|
|
204
|
+
* start the listener, so the agent is reachable while idle from the first
|
|
205
|
+
* login on. No greeting from here: the tab may not be open yet, and the
|
|
206
|
+
* next pair greets. Returns the line to print.
|
|
207
|
+
* @param {{ env: NodeJS.ProcessEnv, spawn?: any }} ctx
|
|
208
|
+
*/
|
|
209
|
+
export async function bootstrapAfterLogin(ctx) {
|
|
210
|
+
const env = ctx.env;
|
|
211
|
+
if (env.SURFCAD_WAKE_BOOTSTRAP === '0') return '';
|
|
212
|
+
const state = await bootstrapWake({ env, remote: true, greet: false, spawn: ctx.spawn });
|
|
213
|
+
if (state.coldWake === 'ready') {
|
|
214
|
+
return `Idle wake: ready (${state.forms.join(', then ')}; listener ${state.listenerStarted ? 'started' : 'running'}). A SurfCAD chat message starts a session of the agent while it is idle.\n`;
|
|
215
|
+
}
|
|
216
|
+
if (state.coldWake === 'listener_stopped') {
|
|
217
|
+
return `Idle wake: set (${state.forms.join(', then ')}) but the listener is not running. Run: npx surfcad-mcp listen --detach\n`;
|
|
218
|
+
}
|
|
219
|
+
return 'Idle wake: unavailable (no wake is set). Chat messages reach the agent only while it is in a turn. See: npx surfcad-mcp --help, Wake.\n';
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Two status lines for `surfcad-mcp status`. Never includes the bearer.
|
|
224
|
+
* @param {NodeJS.ProcessEnv} env
|
|
225
|
+
*/
|
|
226
|
+
export async function wakeStatusText(env) {
|
|
227
|
+
let wake = null;
|
|
228
|
+
try {
|
|
229
|
+
wake = await readWake(env);
|
|
230
|
+
} catch {
|
|
231
|
+
wake = null;
|
|
232
|
+
}
|
|
233
|
+
const pid = await readListenerPid(env);
|
|
234
|
+
const listener = pid ? `listener: running (pid ${pid}, log ${listenerLogPath(env)})` : 'listener: not running';
|
|
235
|
+
return `${formatWake(wake)}${listener}\n`;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* What the MCP status tool reports, so an agent can see the setup is
|
|
240
|
+
* missing without a shell.
|
|
241
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
242
|
+
* @returns {Promise<{ forms: string[], listenerRunning: boolean }>}
|
|
243
|
+
*/
|
|
244
|
+
export async function wakeSetupState(env = process.env) {
|
|
245
|
+
let wake = null;
|
|
246
|
+
try {
|
|
247
|
+
wake = await readWake(env);
|
|
248
|
+
} catch {
|
|
249
|
+
wake = null;
|
|
250
|
+
}
|
|
251
|
+
let pid = null;
|
|
252
|
+
try {
|
|
253
|
+
pid = await readListenerPid(env);
|
|
254
|
+
} catch {
|
|
255
|
+
pid = null;
|
|
256
|
+
}
|
|
257
|
+
return { forms: wakeForms(wake), listenerRunning: pid != null };
|
|
258
|
+
}
|