surfcad-mcp 0.3.6 → 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.
- package/README.md +53 -8
- package/data/commands.json +48 -12
- package/data/helpers.json +1 -1
- package/package.json +1 -1
- package/src/cli.mjs +98 -9
- package/src/listen/awake.mjs +71 -0
- package/src/listen/daemon.mjs +128 -0
- package/src/listen/listenCli.mjs +219 -0
- package/src/listen/listener.mjs +250 -0
- package/src/listen/wake.mjs +167 -0
- package/src/listen/wakeConfig.mjs +199 -0
- package/src/listen/wakeSetupText.mjs +34 -0
- package/src/prompt/buildGuidance.mjs +2 -2
- package/src/prompt/errorHints.mjs +2 -1
- package/src/prompt/guide.mjs +83 -19
- package/src/prompt/promptSession.mjs +40 -7
- package/src/prompt/promptStall.mjs +3 -2
- package/src/prompt/promptTools.mjs +50 -7
- package/src/relay.mjs +1 -0
- package/src/remote/session.mjs +1 -0
- package/src/server.mjs +113 -8
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* "The agent is in a turn right now": the time of its last MCP tool call,
|
|
3
|
+
* shared between surfcad-mcp processes on this machine through one small
|
|
4
|
+
* file. The MCP server stamps it on every tool call. The listener reads it
|
|
5
|
+
* before a wake.
|
|
6
|
+
*
|
|
7
|
+
* An agent in a turn is not woken. It reads the message at its next
|
|
8
|
+
* read_messages, as the chat guide requires, and a wake on top of that would
|
|
9
|
+
* start a second turn beside the first (with an exec wake, a second copy of
|
|
10
|
+
* the agent). Once it has made no tool call for AWAKE_MS it counts as idle,
|
|
11
|
+
* the same 60 s after which the tab shows it idle, and an unread message
|
|
12
|
+
* wakes it.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
import { configDir } from '../remote/config.mjs';
|
|
18
|
+
|
|
19
|
+
/** No tool call for this long: the agent is idle and may be woken. */
|
|
20
|
+
export const AWAKE_MS = 60_000;
|
|
21
|
+
/** The stamp is rewritten at most this often. */
|
|
22
|
+
const STAMP_EVERY_MS = 5_000;
|
|
23
|
+
|
|
24
|
+
/** @param {NodeJS.ProcessEnv} [env] */
|
|
25
|
+
export function awakePath(env = process.env) {
|
|
26
|
+
return join(configDir(env), 'awake');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
let lastStampAt = 0;
|
|
30
|
+
let lastStampPath = '';
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Record a tool call. Best effort and throttled: a failure to write must
|
|
34
|
+
* never fail the tool call.
|
|
35
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
36
|
+
* @param {number} [now]
|
|
37
|
+
*/
|
|
38
|
+
export async function stampAwake(env = process.env, now = Date.now()) {
|
|
39
|
+
const path = awakePath(env);
|
|
40
|
+
if (path === lastStampPath && now - lastStampAt < STAMP_EVERY_MS) return;
|
|
41
|
+
lastStampAt = now;
|
|
42
|
+
lastStampPath = path;
|
|
43
|
+
try {
|
|
44
|
+
await mkdir(configDir(env), { recursive: true, mode: 0o700 });
|
|
45
|
+
await writeFile(path, `${now}\n`, { mode: 0o600 });
|
|
46
|
+
} catch {
|
|
47
|
+
/* best effort */
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
53
|
+
* @returns {Promise<number>} ms timestamp of the last tool call, 0 when none is recorded
|
|
54
|
+
*/
|
|
55
|
+
export async function lastAwakeAt(env = process.env) {
|
|
56
|
+
try {
|
|
57
|
+
const at = Number.parseInt((await readFile(awakePath(env), 'utf8')).trim(), 10);
|
|
58
|
+
return Number.isFinite(at) && at > 0 ? at : 0;
|
|
59
|
+
} catch {
|
|
60
|
+
return 0;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
66
|
+
* @param {number} [now]
|
|
67
|
+
*/
|
|
68
|
+
export async function agentAwake(env = process.env, now = Date.now()) {
|
|
69
|
+
const at = await lastAwakeAt(env);
|
|
70
|
+
return at > 0 && now - at >= 0 && now - at < AWAKE_MS;
|
|
71
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
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
|
+
return { pid: child.pid, log };
|
|
107
|
+
} finally {
|
|
108
|
+
closeSync(fd);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
114
|
+
* @param {{ kill?: (pid: number, signal: number | string) => void }} [deps]
|
|
115
|
+
* @returns {Promise<{ stopped: boolean, pid: number | null }>}
|
|
116
|
+
*/
|
|
117
|
+
export async function stopListener(env = process.env, deps = {}) {
|
|
118
|
+
const kill = deps.kill || process.kill.bind(process);
|
|
119
|
+
const pid = await readListenerPid(env, { kill });
|
|
120
|
+
if (!pid) return { stopped: false, pid: null };
|
|
121
|
+
try {
|
|
122
|
+
kill(pid, 'SIGTERM');
|
|
123
|
+
} catch {
|
|
124
|
+
/* gone between the check and the signal */
|
|
125
|
+
}
|
|
126
|
+
await rm(listenerPidPath(env), { force: true });
|
|
127
|
+
return { stopped: true, pid };
|
|
128
|
+
}
|
|
@@ -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
|
+
}
|