surfcad-mcp 0.3.9 → 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 (41) hide show
  1. package/README.md +70 -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 +221 -23
  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 +87 -34
  12. package/src/listen/claudeCodeWake.mjs +74 -0
  13. package/src/listen/daemon.mjs +35 -0
  14. package/src/listen/listenCli.mjs +121 -30
  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 +39 -19
  19. package/src/listen/wakeSetupText.mjs +23 -5
  20. package/src/pairWait.mjs +3 -3
  21. package/src/pairingCode.mjs +10 -0
  22. package/src/prompt/buildGuidance.mjs +9 -7
  23. package/src/prompt/chatFlow.mjs +15 -0
  24. package/src/prompt/errorHints.mjs +24 -10
  25. package/src/prompt/guide.mjs +27 -14
  26. package/src/prompt/promptSession.mjs +74 -10
  27. package/src/prompt/promptTools.mjs +10 -6
  28. package/src/prompt/replyConfirm.mjs +69 -0
  29. package/src/relayMessages.mjs +43 -1
  30. package/src/remote/config.mjs +17 -13
  31. package/src/remote/session.mjs +103 -5
  32. package/src/room/seat.mjs +334 -0
  33. package/src/screenshotFile.mjs +9 -0
  34. package/src/server.mjs +155 -111
  35. package/src/stepUploadLimit.mjs +8 -0
  36. package/src/bridge/bridgePage.mjs +0 -132
  37. package/src/bridge/bridgePopup.mjs +0 -288
  38. package/src/bridge/relayHub.mjs +0 -556
  39. package/src/bridge/relayServer.mjs +0 -291
  40. package/src/nodeClient.mjs +0 -63
  41. package/src/relay.mjs +0 -419
@@ -3,20 +3,24 @@
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
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';
17
- import { bootstrapWake } from './bootstrap.mjs';
21
+ import { bootstrapWake, loginMark } from './bootstrap.mjs';
18
22
  import { runListener } from './listener.mjs';
19
- import { createWaker, WAKE_GREETING, wakePayload } from './wake.mjs';
23
+ import { createWaker, wakePayload } from './wake.mjs';
20
24
  import {
21
25
  clearWake,
22
26
  formatWake,
@@ -27,7 +31,7 @@ import {
27
31
  saveWake,
28
32
  wakeForms,
29
33
  } from './wakeConfig.mjs';
30
- import { HOST_PROVISION_NOTE, 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';
31
35
 
32
36
  export { WAKE_GUIDE_POINTER, WAKE_SETUP_STEPS };
33
37
 
@@ -50,13 +54,17 @@ export function wakeReadinessNote(state, opts = {}) {
50
54
  } else {
51
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.`);
52
56
  }
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.`);
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.');
59
63
  }
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);
60
68
  for (const problem of state?.problems || []) lines.push(problem);
61
69
  return lines.join(' ');
62
70
  }
@@ -73,6 +81,9 @@ function noWakeMessage() {
73
81
  export async function runWakeCommand(parsed, ctx) {
74
82
  const { env, io } = ctx;
75
83
  const action = parsed.action || 'show';
84
+ if (action === 'claude-code') {
85
+ return runClaudeCodeWake({ env, io, spawn: ctx.spawn });
86
+ }
76
87
  if (action === 'show') {
77
88
  io.stdout(formatWake(await readWake(env)));
78
89
  return 0;
@@ -133,16 +144,31 @@ export async function runWakeCommand(parsed, ctx) {
133
144
  * signal?: AbortSignal,
134
145
  * pid?: number,
135
146
  * onSignals?: (stop: () => void) => void,
147
+ * stopListener?: typeof stopListener,
136
148
  * }} ctx
137
149
  * @returns {Promise<number>} exit code
138
150
  */
139
151
  export async function runListenCommand(parsed, ctx) {
152
+ parsed = { ...parsed };
140
153
  const { env, io } = ctx;
141
154
  if (parsed.stop) {
142
155
  const out = await stopListener(env);
143
156
  io.stdout(out.stopped ? `Listener stopped (pid ${out.pid}).\n` : 'No listener is running.\n');
144
157
  return 0;
145
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
+ }
146
172
  const saved = await readSavedLogin(env);
147
173
  if (!saved?.token) {
148
174
  io.stderr('No saved login. Run npx surfcad-mcp login first. The listener reaches SurfCAD through the server relay.\n');
@@ -157,17 +183,32 @@ export async function runListenCommand(parsed, ctx) {
157
183
  const running = await readListenerPid(env);
158
184
  // In the foreground, the pid file may already name this very process:
159
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.
160
188
  if (running && (parsed.detach || running !== pid)) {
161
- io.stdout(`A listener is already running (pid ${running}).\n`);
162
- return 0;
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);
163
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
+ };
164
203
  if (parsed.detach) {
165
204
  const started = await startDetachedListener({ env, spawn: ctx.spawn, args: parsed.server ? ['--server', parsed.server] : [] });
205
+ await noteLogin(saved.token);
166
206
  io.stdout(`Listener started (pid ${started.pid}). Wake: ${wakeForms(wake).join(', then ')}. Log: ${started.log}\n`);
167
207
  return 0;
168
208
  }
169
209
  const serverUrl = resolveServerUrl({ flag: parsed.server, env, saved });
170
210
  await writeListenerPid(pid, env);
211
+ await noteLogin(saved.token);
171
212
  const ac = new AbortController();
172
213
  const stop = () => ac.abort();
173
214
  if (ctx.signal) ctx.signal.addEventListener('abort', stop, { once: true });
@@ -188,11 +229,20 @@ export async function runListenCommand(parsed, ctx) {
188
229
  signal: ac.signal,
189
230
  waker: createWaker(wake, { fetch: ctx.fetch, spawn: ctx.spawn, env }),
190
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,
191
239
  });
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);
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);
196
246
  return out.reason === 'stopped' ? 0 : 2;
197
247
  } finally {
198
248
  await clearListenerPid(pid, env);
@@ -202,25 +252,66 @@ export async function runListenCommand(parsed, ctx) {
202
252
  /**
203
253
  * After `surfcad-mcp login`: with a wake (from the environment or saved),
204
254
  * 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
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
208
264
  */
209
265
  export async function bootstrapAfterLogin(ctx) {
210
266
  const env = ctx.env;
211
267
  if (env.SURFCAD_WAKE_BOOTSTRAP === '0') return '';
212
- const state = await bootstrapWake({ env, remote: true, greet: false, spawn: ctx.spawn });
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
+ });
213
277
  if (state.coldWake === 'ready') {
214
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`;
215
279
  }
216
280
  if (state.coldWake === 'listener_stopped') {
217
281
  return `Idle wake: set (${state.forms.join(', then ')}) but the listener is not running. Run: npx surfcad-mcp listen --detach\n`;
218
282
  }
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';
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`;
220
284
  }
221
285
 
222
286
  /**
223
- * Two status lines for `surfcad-mcp status`. Never includes the bearer.
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.
224
315
  * @param {NodeJS.ProcessEnv} env
225
316
  */
226
317
  export async function wakeStatusText(env) {
@@ -230,8 +321,13 @@ export async function wakeStatusText(env) {
230
321
  } catch {
231
322
  wake = null;
232
323
  }
233
- const pid = await readListenerPid(env);
234
- 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
+ }
235
331
  return `${formatWake(wake)}${listener}\n`;
236
332
  }
237
333
 
@@ -248,11 +344,6 @@ export async function wakeSetupState(env = process.env) {
248
344
  } catch {
249
345
  wake = null;
250
346
  }
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 };
347
+ const state = await listenerState(env);
348
+ return { forms: wakeForms(wake), listenerRunning: state.pid != null && state.current };
258
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;