surfcad-mcp 0.3.8 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +102 -49
  2. package/bin/surfcad-mcp.js +4 -3
  3. package/data/commands.json +6481 -5817
  4. package/data/helpers.json +243 -268
  5. package/package.json +2 -2
  6. package/src/cli.mjs +234 -24
  7. package/src/cliCall.mjs +221 -0
  8. package/src/errors.mjs +8 -5
  9. package/src/helpers.mjs +7 -5
  10. package/src/importFile.mjs +186 -0
  11. package/src/listen/bootstrap.mjs +285 -0
  12. package/src/listen/claudeCodeWake.mjs +74 -0
  13. package/src/listen/daemon.mjs +40 -0
  14. package/src/listen/listenCli.mjs +157 -27
  15. package/src/listen/listener.mjs +138 -8
  16. package/src/listen/owner.mjs +293 -0
  17. package/src/listen/waitCli.mjs +133 -0
  18. package/src/listen/wake.mjs +42 -8
  19. package/src/listen/wakeConfig.mjs +17 -2
  20. package/src/listen/wakeSetupText.mjs +53 -14
  21. package/src/pairWait.mjs +3 -3
  22. package/src/pairingCode.mjs +10 -0
  23. package/src/prompt/buildGuidance.mjs +9 -7
  24. package/src/prompt/chatFlow.mjs +15 -0
  25. package/src/prompt/errorHints.mjs +24 -10
  26. package/src/prompt/guide.mjs +31 -18
  27. package/src/prompt/promptSession.mjs +74 -10
  28. package/src/prompt/promptTools.mjs +10 -15
  29. package/src/prompt/replyConfirm.mjs +69 -0
  30. package/src/relayMessages.mjs +43 -1
  31. package/src/remote/config.mjs +17 -13
  32. package/src/remote/session.mjs +103 -5
  33. package/src/remote/tokenStore.mjs +20 -0
  34. package/src/room/seat.mjs +334 -0
  35. package/src/screenshotFile.mjs +9 -0
  36. package/src/server.mjs +241 -119
  37. package/src/stepUploadLimit.mjs +8 -0
  38. package/src/bridge/bridgePage.mjs +0 -132
  39. package/src/bridge/bridgePopup.mjs +0 -288
  40. package/src/bridge/relayHub.mjs +0 -556
  41. package/src/bridge/relayServer.mjs +0 -291
  42. package/src/nodeClient.mjs +0 -63
  43. package/src/relay.mjs +0 -419
@@ -3,17 +3,22 @@
3
3
  * Nothing here prints the login token or the wake bearer.
4
4
  */
5
5
 
6
+ import { ownerAttached, releaseOwner, setListenPaused, wakeTarget } from './owner.mjs';
7
+ import { runClaudeCodeWake } from './claudeCodeWake.mjs';
6
8
  import { resolveServerUrl } from '../remote/config.mjs';
7
- import { readSavedLogin } from '../remote/tokenStore.mjs';
9
+ import { forgetLoginIfToken, readSavedLogin } from '../remote/tokenStore.mjs';
8
10
  import {
9
11
  clearListenerPid,
10
12
  listenerLogPath,
13
+ readListenerLoginMark,
11
14
  readListenerPid,
12
15
  startDetachedListener,
13
16
  stopListener,
17
+ writeListenerLoginMark,
14
18
  writeListenerPid,
15
19
  } from './daemon.mjs';
16
20
  import { agentAwake } from './awake.mjs';
21
+ import { bootstrapWake, loginMark } from './bootstrap.mjs';
17
22
  import { runListener } from './listener.mjs';
18
23
  import { createWaker, wakePayload } from './wake.mjs';
19
24
  import {
@@ -26,26 +31,42 @@ import {
26
31
  saveWake,
27
32
  wakeForms,
28
33
  } from './wakeConfig.mjs';
29
- import { WAKE_GUIDE_POINTER, WAKE_SETUP_STEPS } from './wakeSetupText.mjs';
34
+ import { HOST_PROVISION_NOTE, NO_GREETING_LINE, WAKE_GUIDE_POINTER, WAKE_SETUP_STEPS, WAKE_UNAVAILABLE_USER_MESSAGE } from './wakeSetupText.mjs';
30
35
 
31
36
  export { WAKE_GUIDE_POINTER, WAKE_SETUP_STEPS };
32
37
 
33
38
  /**
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
39
+ * What an agent is told about being reachable while idle. It says what is
40
+ * true and nothing more: "ready" only when a wake is set and something will
41
+ * fire it. It never tells the agent to ask the user for a webhook URL.
42
+ * @param {import('./bootstrap.mjs').WakeBootstrap} state
43
+ * @param {{ remote?: boolean }} [opts] remote: this process is on the server relay
37
44
  */
38
- export function wakeSetupNote(state, opts = {}) {
45
+ export function wakeReadinessNote(state, opts = {}) {
39
46
  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}.`;
47
+ const lines = [];
48
+ if (state?.coldWake === 'ready') {
49
+ lines.push(opts.remote === false
50
+ ? `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.`
51
+ : `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.`);
52
+ } else if (state?.coldWake === 'listener_stopped') {
53
+ 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`);
54
+ } else {
55
+ 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.`);
42
56
  }
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.`;
57
+ // The wake check is a silent test wake, once per login. The greeting is
58
+ // the tab's (NO_GREETING_LINE); no session is ever told to say it.
59
+ if (state?.wakeCheck === 'fired') {
60
+ lines.push('A test wake was fired once for this login (reason "test"); the session it starts calls status once and ends without messaging the user. If no session of you started from it, the wake is not reaching your host.');
61
+ } else if (state?.wakeCheck === 'not_fired') {
62
+ lines.push('The wake did not start a session, so idle wake is not working yet.');
47
63
  }
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.`;
64
+ if (state?.userNotice === 'tell_now') {
65
+ lines.push(`Once, tell the user in the SurfCAD chat that the setup is still needed, in these words: reply_to_user { text: "${WAKE_UNAVAILABLE_USER_MESSAGE}" } with no in_reply_to. Do not repeat it on later pairs, and do not ask the user for a URL or a key.`);
66
+ }
67
+ lines.push(NO_GREETING_LINE);
68
+ for (const problem of state?.problems || []) lines.push(problem);
69
+ return lines.join(' ');
49
70
  }
50
71
 
51
72
  function noWakeMessage() {
@@ -60,6 +81,9 @@ function noWakeMessage() {
60
81
  export async function runWakeCommand(parsed, ctx) {
61
82
  const { env, io } = ctx;
62
83
  const action = parsed.action || 'show';
84
+ if (action === 'claude-code') {
85
+ return runClaudeCodeWake({ env, io, spawn: ctx.spawn });
86
+ }
63
87
  if (action === 'show') {
64
88
  io.stdout(formatWake(await readWake(env)));
65
89
  return 0;
@@ -120,16 +144,31 @@ export async function runWakeCommand(parsed, ctx) {
120
144
  * signal?: AbortSignal,
121
145
  * pid?: number,
122
146
  * onSignals?: (stop: () => void) => void,
147
+ * stopListener?: typeof stopListener,
123
148
  * }} ctx
124
149
  * @returns {Promise<number>} exit code
125
150
  */
126
151
  export async function runListenCommand(parsed, ctx) {
152
+ parsed = { ...parsed };
127
153
  const { env, io } = ctx;
128
154
  if (parsed.stop) {
129
155
  const out = await stopListener(env);
130
156
  io.stdout(out.stopped ? `Listener stopped (pid ${out.pid}).\n` : 'No listener is running.\n');
131
157
  return 0;
132
158
  }
159
+ if (parsed.pause) {
160
+ // A pause sticks: no surfcad-mcp process starts the listener again
161
+ // until listen --resume.
162
+ await setListenPaused(true, env);
163
+ const out = await stopListener(env);
164
+ io.stdout(`Listener paused${out.stopped ? ` (stopped pid ${out.pid})` : ''}. Nothing starts it again until: npx surfcad-mcp listen --resume\n`);
165
+ return 0;
166
+ }
167
+ if (parsed.resume) {
168
+ await setListenPaused(false, env);
169
+ io.stdout('Listener pause cleared.\n');
170
+ parsed = { ...parsed, resume: false, detach: true };
171
+ }
133
172
  const saved = await readSavedLogin(env);
134
173
  if (!saved?.token) {
135
174
  io.stderr('No saved login. Run npx surfcad-mcp login first. The listener reaches SurfCAD through the server relay.\n');
@@ -140,19 +179,36 @@ export async function runListenCommand(parsed, ctx) {
140
179
  io.stderr(noWakeMessage());
141
180
  return 1;
142
181
  }
182
+ const pid = ctx.pid ?? process.pid;
143
183
  const running = await readListenerPid(env);
144
- if (running) {
145
- io.stdout(`A listener is already running (pid ${running}).\n`);
146
- return 0;
184
+ // In the foreground, the pid file may already name this very process:
185
+ // --detach writes it before the listener it starts is up.
186
+ // A detached listener still on a replaced login is not "already running":
187
+ // that login was revoked, and this start replaces the process.
188
+ if (running && (parsed.detach || running !== pid)) {
189
+ const replaced = parsed.detach && (await readListenerLoginMark(env)) !== loginMark(saved.token);
190
+ if (!replaced) {
191
+ io.stdout(`A listener is already running (pid ${running}).\n`);
192
+ return 0;
193
+ }
194
+ await (ctx.stopListener || stopListener)(env);
147
195
  }
196
+ const noteLogin = async (next) => {
197
+ try {
198
+ await writeListenerLoginMark(loginMark(next), env);
199
+ } catch {
200
+ /* a later pair restarts a listener whose mark was not recorded */
201
+ }
202
+ };
148
203
  if (parsed.detach) {
149
204
  const started = await startDetachedListener({ env, spawn: ctx.spawn, args: parsed.server ? ['--server', parsed.server] : [] });
205
+ await noteLogin(saved.token);
150
206
  io.stdout(`Listener started (pid ${started.pid}). Wake: ${wakeForms(wake).join(', then ')}. Log: ${started.log}\n`);
151
207
  return 0;
152
208
  }
153
209
  const serverUrl = resolveServerUrl({ flag: parsed.server, env, saved });
154
- const pid = ctx.pid ?? process.pid;
155
210
  await writeListenerPid(pid, env);
211
+ await noteLogin(saved.token);
156
212
  const ac = new AbortController();
157
213
  const stop = () => ac.abort();
158
214
  if (ctx.signal) ctx.signal.addEventListener('abort', stop, { once: true });
@@ -173,7 +229,20 @@ export async function runListenCommand(parsed, ctx) {
173
229
  signal: ac.signal,
174
230
  waker: createWaker(wake, { fetch: ctx.fetch, spawn: ctx.spawn, env }),
175
231
  isAwake: () => agentAwake(env),
232
+ isAttached: () => ownerAttached(env),
233
+ target: () => wakeTarget(env),
234
+ onChatReset: () => releaseOwner(env),
235
+ // A re-pair writes the new token before this process notices the
236
+ // old one was revoked. Adopt that token once; do not drop it.
237
+ readToken: async () => (await readSavedLogin(env))?.token || '',
238
+ onToken: noteLogin,
176
239
  });
240
+ // Disconnected in SurfCAD, or expired, and no newer login was saved.
241
+ // Forget the token this process was refused, so `status` says "not
242
+ // logged in" and nothing retries with it. A newer token in the file
243
+ // is left there. The server answers a revoked token with a plain 401
244
+ // ("unauthorized" here).
245
+ if (out.reason !== 'stopped') await forgetLoginIfToken(out.token || saved.token, env);
177
246
  return out.reason === 'stopped' ? 0 : 2;
178
247
  } finally {
179
248
  await clearListenerPid(pid, env);
@@ -181,7 +250,68 @@ export async function runListenCommand(parsed, ctx) {
181
250
  }
182
251
 
183
252
  /**
184
- * Two status lines for `surfcad-mcp status`. Never includes the bearer.
253
+ * After `surfcad-mcp login`: with a wake (from the environment or saved),
254
+ * start the listener, so the agent is reachable while idle from the first
255
+ * login on. No test wake from here: the tab may not be open yet, and the
256
+ * next pair fires it. Returns the line to print.
257
+ * @param {{
258
+ * env: NodeJS.ProcessEnv,
259
+ * spawn?: any,
260
+ * stopListener?: typeof stopListener,
261
+ * startListener?: import('./daemon.mjs').startDetachedListener,
262
+ * listenerPid?: import('./daemon.mjs').readListenerPid,
263
+ * }} ctx
264
+ */
265
+ export async function bootstrapAfterLogin(ctx) {
266
+ const env = ctx.env;
267
+ if (env.SURFCAD_WAKE_BOOTSTRAP === '0') return '';
268
+ const state = await bootstrapWake({
269
+ env,
270
+ remote: true,
271
+ check: false,
272
+ spawn: ctx.spawn,
273
+ stopListener: ctx.stopListener,
274
+ startListener: ctx.startListener,
275
+ listenerPid: ctx.listenerPid,
276
+ });
277
+ if (state.coldWake === 'ready') {
278
+ 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`;
279
+ }
280
+ if (state.coldWake === 'listener_stopped') {
281
+ return `Idle wake: set (${state.forms.join(', then ')}) but the listener is not running. Run: npx surfcad-mcp listen --detach\n`;
282
+ }
283
+ return `Idle wake: unavailable (no wake is set), so chat messages reach the agent only while it is in a turn. Next, as the agent: call the pair tool and do what its note says. ${HOST_PROVISION_NOTE} Or set SURFCAD_WAKE_POST / SURFCAD_WAKE_BEARER (or SURFCAD_WAKE_EXEC) in the MCP server's config. See: npx surfcad-mcp --help, Wake.\n`;
284
+ }
285
+
286
+ /**
287
+ * The listener process, and whether it was started with the saved login.
288
+ * A pid left from a replaced login is not serving this login: status says
289
+ * so, and pair / login / `listen --detach` replace it.
290
+ * @param {NodeJS.ProcessEnv} env
291
+ * @returns {Promise<{ pid: number | null, current: boolean }>}
292
+ */
293
+ async function listenerState(env) {
294
+ let pid = null;
295
+ try {
296
+ pid = await readListenerPid(env);
297
+ } catch {
298
+ pid = null;
299
+ }
300
+ if (!pid) return { pid: null, current: false };
301
+ let saved = null;
302
+ try {
303
+ saved = await readSavedLogin(env);
304
+ } catch {
305
+ saved = null;
306
+ }
307
+ if (!saved?.token) return { pid, current: true };
308
+ const mark = await readListenerLoginMark(env);
309
+ return { pid, current: mark === loginMark(saved.token) };
310
+ }
311
+
312
+ /**
313
+ * Two status lines for `surfcad-mcp status`. Never includes the bearer or
314
+ * the login token.
185
315
  * @param {NodeJS.ProcessEnv} env
186
316
  */
187
317
  export async function wakeStatusText(env) {
@@ -191,8 +321,13 @@ export async function wakeStatusText(env) {
191
321
  } catch {
192
322
  wake = null;
193
323
  }
194
- const pid = await readListenerPid(env);
195
- const listener = pid ? `listener: running (pid ${pid}, log ${listenerLogPath(env)})` : 'listener: not running';
324
+ const state = await listenerState(env);
325
+ let listener = 'listener: not running';
326
+ if (state.pid && state.current) {
327
+ listener = `listener: running (pid ${state.pid}, log ${listenerLogPath(env)})`;
328
+ } else if (state.pid) {
329
+ listener = `listener: not on this login (pid ${state.pid}, log ${listenerLogPath(env)}). Run: npx surfcad-mcp listen --stop, then npx surfcad-mcp listen --detach`;
330
+ }
196
331
  return `${formatWake(wake)}${listener}\n`;
197
332
  }
198
333
 
@@ -209,11 +344,6 @@ export async function wakeSetupState(env = process.env) {
209
344
  } catch {
210
345
  wake = null;
211
346
  }
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 };
347
+ const state = await listenerState(env);
348
+ return { forms: wakeForms(wake), listenerRunning: state.pid != null && state.current };
219
349
  }
@@ -39,6 +39,8 @@ export const LISTEN_GRACE_MS = 4_000;
39
39
  export const LISTEN_REWAKE_MS = 120_000;
40
40
  /** While the wake command of an earlier message still runs, look again this often. */
41
41
  export const LISTEN_BUSY_RETRY_MS = 15_000;
42
+ /** A busy owner that has not read a message for this long: the chat says so once. */
43
+ export const LISTEN_BUSY_NOTICE_MS = 5 * 60_000;
42
44
  export const LISTEN_BACKOFF_MS = Object.freeze([1_000, 2_000, 5_000, 10_000, 30_000]);
43
45
  const SEEN_CAP = 500;
44
46
 
@@ -78,8 +80,18 @@ export function promptFromFrame(frame) {
78
80
  * sleep?: (ms: number, signal?: AbortSignal) => Promise<void>,
79
81
  * now?: () => number,
80
82
  * signal?: AbortSignal,
83
+ * readToken?: () => Promise<string | null | undefined> | string | null | undefined,
84
+ * isAttached?: () => Promise<boolean> | boolean,
85
+ * target?: () => Promise<{ action: 'fresh' | 'resume' | 'fork' | 'busy', session?: string, cwd?: string }>,
86
+ * busyNoticeMs?: number,
87
+ * onChatReset?: () => Promise<unknown> | unknown,
88
+ * onToken?: (token: string) => Promise<void> | void,
81
89
  * }} options
82
- * @returns {Promise<{ reason: 'stopped' | 'token_revoked' | 'expired' | 'unauthorized' }>}
90
+ * `readToken` is the saved login. On a rejection the loop reads it once
91
+ * and continues when it is a different token; the same token (or none)
92
+ * ends the loop. `onToken` is told the token now in use. Neither the log
93
+ * nor a thrown `readToken` may echo it.
94
+ * @returns {Promise<{ reason: 'stopped' | 'token_revoked' | 'expired' | 'unauthorized', token?: string }>}
83
95
  */
84
96
  export async function runListener(options) {
85
97
  const urls = agentUrls(options.serverUrl);
@@ -91,6 +103,30 @@ export async function runListener(options) {
91
103
  const backoff = options.backoffMs || LISTEN_BACKOFF_MS;
92
104
  const waker = options.waker || createWaker(options.wake);
93
105
  const isAwake = options.isAwake || (() => false);
106
+ const isAttached = options.isAttached || (() => false);
107
+ const chooseTarget = options.target || (async () => ({ action: 'fresh' }));
108
+ const busyNoticeMs = options.busyNoticeMs ?? LISTEN_BUSY_NOTICE_MS;
109
+
110
+ /**
111
+ * A one-line note in the person's chat (a session message), for a wake
112
+ * that failed or an agent that has not read a message for a while. Best
113
+ * effort: the relay rate-limits session notes, and a failure is logged.
114
+ * @param {string} text
115
+ */
116
+ async function notice(text) {
117
+ try {
118
+ const res = await doFetch(urls.promptsUrl, {
119
+ method: 'POST',
120
+ headers: { Authorization: `Bearer ${token}`, 'content-type': 'application/json' },
121
+ body: JSON.stringify({ type: 'agent.message', v: 1, text }),
122
+ signal,
123
+ });
124
+ try { await res.body?.cancel?.(); } catch { /* noop */ }
125
+ if (!res.ok) log(`could not post a chat note (${res.status})`);
126
+ } catch {
127
+ log('could not post a chat note (unreachable)');
128
+ }
129
+ }
94
130
  const now = options.now || (() => Date.now());
95
131
  const signal = options.signal;
96
132
  const sleep = options.sleep || ((ms, sig) => new Promise((resolve) => {
@@ -108,7 +144,21 @@ export async function runListener(options) {
108
144
  const waiting = new Map();
109
145
  /** Ids that are finished here (read by an agent, or given up on). */
110
146
  const settled = new Set();
111
- const session = newSession();
147
+ let token = options.token;
148
+ let session = newSession();
149
+ /** The chat epoch the relay reported last (bumped by Delete history). */
150
+ let chatEpoch = null;
151
+
152
+ /** The saved login, or '' when it cannot be read. Never logged. */
153
+ async function savedToken() {
154
+ if (typeof options.readToken !== 'function') return '';
155
+ try {
156
+ const next = await options.readToken();
157
+ return typeof next === 'string' ? next : '';
158
+ } catch {
159
+ return '';
160
+ }
161
+ }
112
162
 
113
163
  /**
114
164
  * @param {string} sessionId
@@ -123,7 +173,7 @@ export async function runListener(options) {
123
173
  try {
124
174
  res = await doFetch(url, {
125
175
  method: 'GET',
126
- headers: { Authorization: `Bearer ${options.token}` },
176
+ headers: { Authorization: `Bearer ${token}` },
127
177
  signal,
128
178
  });
129
179
  } catch {
@@ -143,7 +193,30 @@ export async function runListener(options) {
143
193
  }
144
194
  let json = null;
145
195
  try { json = await res.json(); } catch { json = null; }
146
- return json && Array.isArray(json.messages) ? json.messages : [];
196
+ const messages = json && Array.isArray(json.messages) ? json.messages : [];
197
+ // The person deleted the chat history (a reset frame, or a higher chat
198
+ // epoch than this loop has seen): the local chat owner lets go.
199
+ const epoch = json && json.chat && Number.isInteger(json.chat.epoch) ? json.chat.epoch : null;
200
+ const resetFrame = messages.some((f) => f && f.type === 'agent.chat.reset');
201
+ if (resetFrame || (epoch != null && chatEpoch != null && epoch > chatEpoch)) {
202
+ log('the chat history was deleted in SurfCAD; the next message starts a new agent session');
203
+ try { await options.onChatReset?.(); } catch { /* best effort */ }
204
+ }
205
+ if (epoch != null) chatEpoch = epoch;
206
+ // Answer now: the person wants a copy of the owner to answer this one,
207
+ // even if the owner still looks busy or attached.
208
+ for (const f of messages) {
209
+ if (!f || f.type !== 'agent.chat.answer_now' || typeof f.id !== 'string') continue;
210
+ const row = waiting.get(f.id);
211
+ if (row) {
212
+ row.force = true;
213
+ row.due = now();
214
+ } else if (!settled.has(f.id)) {
215
+ waiting.set(f.id, { prompt: { id: f.id }, due: now(), wakes: 0, force: true });
216
+ }
217
+ log(`Answer now for message ${f.id}: starting a copy of the agent that owns the chat`);
218
+ }
219
+ return messages.filter((f) => !(f && (f.type === 'agent.chat.reset' || f.type === 'agent.chat.answer_now')));
147
220
  }
148
221
 
149
222
  /** @param {object[]} frames */
@@ -180,19 +253,50 @@ export async function runListener(options) {
180
253
  if (!held.has(row.prompt.id)) {
181
254
  log(`message ${row.prompt.id} was read (or cancelled); no wake`);
182
255
  settle(row.prompt.id);
183
- } else if (row.wakes >= 2) {
256
+ } else if (row.wakes >= 2 && !row.force) {
184
257
  log(`message ${row.prompt.id} is still unread after two wakes; leaving it for the agent's next turn`);
185
258
  settle(row.prompt.id);
186
259
  } else {
260
+ row.prompt = held.get(row.prompt.id) || row.prompt;
187
261
  unread.push(row);
188
262
  }
189
263
  }
190
264
  // Anything else still held that this loop has not met is new to it.
191
265
  note([...held.values()].map((p) => ({ type: 'agent.prompt', ...p })));
192
266
  if (!unread.length) return;
267
+ const forced = unread.some((row) => row.force);
268
+ // The chat's owner is waiting for this message (surfcad-mcp wait): its
269
+ // waiter hands the message to the same session, so nobody is woken.
270
+ if (!forced && await isAttached()) {
271
+ for (const row of unread) {
272
+ if (!row.attached) log(`message ${row.prompt.id} goes to the agent session that owns the chat (it is waiting); no wake`);
273
+ row.attached = true;
274
+ row.due = now() + LISTEN_BUSY_RETRY_MS;
275
+ }
276
+ return;
277
+ }
278
+ // Who answers: the owner's conversation (resumed, or a fork of it when
279
+ // it is open but idle), or a fresh session when nobody owns the chat.
280
+ let target = await chooseTarget();
281
+ // Answer now overrides busy: fork the owner.
282
+ if (forced && target.action === 'busy') target = { ...target, action: 'fork' };
283
+ if (target.action === 'busy') {
284
+ for (const row of unread) {
285
+ if (!row.deferred) log(`message ${row.prompt.id} is unread; the agent session that owns the chat is working and reads it at its next tool call`);
286
+ row.deferred = true;
287
+ row.busySince = row.busySince ?? now();
288
+ if (!row.busyNoted && now() - row.busySince >= busyNoticeMs) {
289
+ row.busyNoted = true;
290
+ await notice('The agent is still working and has not read your message yet. It reads it at its next step.');
291
+ }
292
+ row.due = now() + LISTEN_BUSY_RETRY_MS;
293
+ }
294
+ return;
295
+ }
193
296
  // An agent in a turn is not woken: it reads the message at its next
194
297
  // read_messages, and a wake would start a second turn beside the first.
195
- if (await isAwake()) {
298
+ // (Hosts with no chat owner: the session-wide tool call stamp.)
299
+ if (!forced && target.action === 'fresh' && await isAwake()) {
196
300
  for (const row of unread) {
197
301
  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
302
  row.deferred = true;
@@ -200,11 +304,12 @@ export async function runListener(options) {
200
304
  }
201
305
  return;
202
306
  }
203
- const outcome = await waker.wake(wakePayload(unread.map((row) => row.prompt)));
307
+ const outcome = await waker.wake(wakePayload(unread.map((row) => row.prompt), { session: target }));
204
308
  if (outcome.ok) {
205
309
  log(`woke the agent by ${outcome.form} for ${unread.length} message${unread.length === 1 ? '' : 's'}`);
206
310
  for (const row of unread) {
207
311
  row.wakes += 1;
312
+ row.force = false;
208
313
  row.due = now() + rewakeMs;
209
314
  }
210
315
  return;
@@ -215,6 +320,11 @@ export async function runListener(options) {
215
320
  return;
216
321
  }
217
322
  log(`wake failed (${outcome.error}); trying again in ${Math.round(rewakeMs / 1000)} s`);
323
+ // Never silent: the person sees why nobody answers yet.
324
+ if (unread.some((row) => !row.failNoted)) {
325
+ for (const row of unread) row.failNoted = true;
326
+ await notice(`SurfCAD could not start your agent (${outcome.error}). Your message is kept and is read as soon as an agent connects.`);
327
+ }
218
328
  for (const row of unread) row.due = now() + rewakeMs;
219
329
  }
220
330
 
@@ -233,10 +343,30 @@ export async function runListener(options) {
233
343
  if (signal?.aborted) break;
234
344
  const code = err && typeof err === 'object' ? err.code : '';
235
345
  if (code === 'token_revoked' || code === 'expired' || code === 'unauthorized') {
346
+ // One look at the saved login per rejection. A newer token (a
347
+ // re-pair that already wrote token.json) replaces the one the
348
+ // server just refused. The same token is not tried again.
349
+ if (signal?.aborted) break;
350
+ const next = await savedToken();
351
+ if (signal?.aborted) break;
352
+ if (next && next !== token) {
353
+ token = next;
354
+ session = newSession();
355
+ waiting.clear();
356
+ settled.clear();
357
+ failures = 0;
358
+ try {
359
+ await options.onToken?.(token);
360
+ } catch {
361
+ /* recording the login is not what keeps the listen alive */
362
+ }
363
+ log('the saved login changed; listening with it');
364
+ continue;
365
+ }
236
366
  log(code === 'expired'
237
367
  ? 'the SurfCAD login expired; run npx surfcad-mcp login, then start the listener again'
238
368
  : 'the SurfCAD login is no longer valid; run npx surfcad-mcp login, then start the listener again');
239
- return { reason: code };
369
+ return { reason: code, token };
240
370
  }
241
371
  const delay = backoff[Math.min(failures, backoff.length - 1)];
242
372
  failures += 1;