surfcad-mcp 0.3.3 → 0.3.5

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.
@@ -125,13 +125,28 @@ function defaultSetTimer(fn, ms) {
125
125
  * rateLimitMs?: number,
126
126
  * idleMs?: number,
127
127
  * webhookTimeoutMs?: number,
128
+ * onTaken?: (ids: string[]) => void,
128
129
  * }} options
130
+ * `onTaken` fires with the prompt ids the agent now has (read_messages
131
+ * returned them, or the webhook POST succeeded). The server relay holds a
132
+ * prompt until it hears this, so a one-shot process that exits before
133
+ * reading does not lose it.
129
134
  */
130
135
  export function createPromptSession(options) {
131
136
  if (!options || typeof options.send !== 'function') {
132
137
  throw new TypeError('createPromptSession requires send');
133
138
  }
134
139
  const send = options.send;
140
+ const onTaken = typeof options.onTaken === 'function' ? options.onTaken : null;
141
+ /** @param {string[]} ids */
142
+ function noteTaken(ids) {
143
+ if (!onTaken || ids.length === 0) return;
144
+ try {
145
+ onTaken(ids);
146
+ } catch {
147
+ /* advisory */
148
+ }
149
+ }
135
150
  const now = options.now || (() => Date.now());
136
151
  const setTimer = options.setTimer || defaultSetTimer;
137
152
  const clearTimer = options.clearTimer || ((timer) => clearTimeout(/** @type {ReturnType<typeof setTimeout>} */ (timer)));
@@ -173,6 +188,8 @@ export function createPromptSession(options) {
173
188
  let promptEpoch = 0;
174
189
  let workedEpoch = 0;
175
190
  let lastAcceptedAt = -Infinity;
191
+ /** Last unsolicited session message. Separate from prompt accepts. */
192
+ let lastSessionAt = -Infinity;
176
193
  /** @type {string | null} */
177
194
  let lastId = null;
178
195
  /** @type {unknown} */
@@ -189,13 +206,43 @@ export function createPromptSession(options) {
189
206
  for (const resolve of list) resolve();
190
207
  }
191
208
 
192
- function emit(payload) {
209
+ function asSendError(err) {
210
+ const code = err && typeof err === 'object' && typeof err.code === 'string' && err.code
211
+ ? err.code
212
+ : 'not_paired';
213
+ const message = err instanceof Error && err.message ? err.message : 'Not paired';
214
+ const out = err instanceof Error ? err : new Error(message);
215
+ if (!out.message) out.message = message;
216
+ out.code = code;
217
+ if (err && typeof err === 'object' && typeof err.hint === 'string' && !out.hint) out.hint = err.hint;
218
+ return out;
219
+ }
220
+
221
+ /**
222
+ * @param {object} payload
223
+ * @param {{ required?: boolean }} [opts]
224
+ * A required send keeps the transport's error (a connected remote session
225
+ * is not rewritten as not_paired). Advisory sends stay quiet.
226
+ */
227
+ function emit(payload, { required = false } = {}) {
228
+ let result;
193
229
  try {
194
- send(payload);
195
- return true;
196
- } catch {
230
+ result = send(payload);
231
+ } catch (err) {
232
+ if (required) throw asSendError(err);
197
233
  return false;
198
234
  }
235
+ if (result && typeof result.then === 'function') {
236
+ const pending = Promise.resolve(result).then(() => true);
237
+ if (!required) {
238
+ pending.catch(() => {});
239
+ return true;
240
+ }
241
+ return pending.catch((err) => {
242
+ throw asSendError(err);
243
+ });
244
+ }
245
+ return true;
199
246
  }
200
247
 
201
248
  function clearIdle() {
@@ -256,8 +303,9 @@ export function createPromptSession(options) {
256
303
  * @param {string | null | undefined} id
257
304
  * @param {boolean} force
258
305
  * @param {string} [label]
306
+ * @param {boolean} [required]
259
307
  */
260
- function emitState(state, id, force, label) {
308
+ function emitState(state, id, force, label, required = false) {
261
309
  const next = state !== 'idle';
262
310
  if (!force && agentState === state && !stalled) {
263
311
  if (next) armIdle();
@@ -269,7 +317,7 @@ export function createPromptSession(options) {
269
317
  const msg = { type: PAIR_MSG.AGENT_STATUS, v: 1, working: next, state };
270
318
  if (typeof id === 'string' && id) msg.id = id;
271
319
  if (typeof label === 'string' && label) msg.label = label.slice(0, 120);
272
- const sent = emit(msg);
320
+ const sent = emit(msg, { required: required === true });
273
321
  if (next) armIdle();
274
322
  else clearIdle();
275
323
  return sent;
@@ -454,6 +502,7 @@ export function createPromptSession(options) {
454
502
  if (posted === 'sent') {
455
503
  remember(prompt.id, 'delivered');
456
504
  emit(ack(prompt.id, 'webhook'));
505
+ noteTaken([prompt.id]);
457
506
  return;
458
507
  }
459
508
  }
@@ -504,6 +553,15 @@ export function createPromptSession(options) {
504
553
  }
505
554
  screenshot = shot.value;
506
555
  }
556
+ // The server relay offers a held prompt to every new socket or pull
557
+ // session until one reports it taken, so the same id can arrive again
558
+ // (a reconnect in this process). Keep the copy this process has.
559
+ const known = states.get(id);
560
+ if (known) {
561
+ if (known === 'queued') emit(ack(id, 'queued'));
562
+ else if (known === 'delivered' || known === 'replied') noteTaken([id]);
563
+ return;
564
+ }
507
565
  const at = now();
508
566
  if (at - lastAcceptedAt < rateLimitMs) {
509
567
  failAck('rate_limited');
@@ -579,6 +637,7 @@ export function createPromptSession(options) {
579
637
  const taken = queue.splice(0, count);
580
638
  const messages = [];
581
639
  const images = [];
640
+ const takenIds = [];
582
641
  for (const item of taken) {
583
642
  if (item.kind === 'cancel') {
584
643
  messages.push({ type: 'cancel', id: item.id });
@@ -586,6 +645,7 @@ export function createPromptSession(options) {
586
645
  continue;
587
646
  }
588
647
  if (states.get(item.id) === 'queued') states.set(item.id, 'delivered');
648
+ takenIds.push(item.id);
589
649
  messages.push({
590
650
  v: 1,
591
651
  id: item.id,
@@ -607,29 +667,83 @@ export function createPromptSession(options) {
607
667
  : null);
608
668
  }
609
669
  noteActivity();
670
+ noteTaken(takenIds);
610
671
  return { messages, images };
611
672
  }
612
673
 
613
674
  /**
614
- * @param {{ in_reply_to?: unknown, text?: unknown, final?: unknown }} args
675
+ * Plain text for a reply or a session note. Not parsed as HTML.
676
+ * @param {unknown} text
615
677
  */
616
- function reply(args) {
617
- const inReplyTo = args?.in_reply_to;
618
- const text = args?.text;
619
- if (typeof inReplyTo !== 'string' || !inReplyTo || inReplyTo.length > 80) {
620
- throw Object.assign(new Error('in_reply_to is required'), { code: 'bad_args' });
621
- }
678
+ function requireReplyText(text) {
622
679
  if (typeof text !== 'string' || text.length === 0) {
623
680
  throw Object.assign(new Error('Reply text is required'), { code: 'bad_args' });
624
681
  }
625
682
  if (text.length > PROMPT_REPLY_MAX) {
626
683
  throw Object.assign(new Error('Reply text is too long'), { code: 'reply_too_long' });
627
684
  }
628
- // Only a prompt this session accepted. Checked before any send, so an
629
- // invented id never becomes an agent.reply on the tab.
630
- const state = states.get(inReplyTo);
685
+ return text;
686
+ }
687
+
688
+ /**
689
+ * A note for this paired session, with no prompt id. The page shows it
690
+ * as its own chat bubble. One per rate window. Does not touch prompt state.
691
+ * @param {unknown} raw
692
+ */
693
+ function postSessionMessage(raw) {
694
+ const run = chain.then(() => postSessionNow(raw));
695
+ chain = run.then(() => {}, () => {});
696
+ return run;
697
+ }
698
+
699
+ /**
700
+ * @param {unknown} raw
701
+ */
702
+ function postSessionNow(raw) {
703
+ const text = requireReplyText(raw);
704
+ const at = now();
705
+ if (at - lastSessionAt < rateLimitMs) {
706
+ throw Object.assign(new Error('Too many messages'), { code: 'rate_limited' });
707
+ }
708
+ const sent = emit({
709
+ type: PAIR_MSG.AGENT_MESSAGE,
710
+ v: 1,
711
+ text,
712
+ ts: new Date(at).toISOString(),
713
+ }, { required: true });
714
+ const finish = () => {
715
+ lastSessionAt = at;
716
+ return { ok: true, session: true };
717
+ };
718
+ if (sent && typeof sent.then === 'function') {
719
+ return sent.then(finish);
720
+ }
721
+ if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
722
+ return finish();
723
+ }
724
+
725
+ /**
726
+ * @param {{ in_reply_to?: unknown, text?: unknown, final?: unknown }} args
727
+ */
728
+ function reply(args) {
729
+ if (args?.in_reply_to == null) return postSessionMessage(args?.text);
730
+ const inReplyTo = args.in_reply_to;
731
+ const text = requireReplyText(args?.text);
732
+ if (typeof inReplyTo !== 'string' || !inReplyTo || inReplyTo.length > 80) {
733
+ throw Object.assign(new Error('in_reply_to is required'), { code: 'bad_args' });
734
+ }
735
+ // A prompt this session accepted, or a prompt id from an earlier
736
+ // one-shot process (a fresh surfcad-mcp per tool call reads in one
737
+ // process and replies from the next). Anything that is not a prompt id
738
+ // is refused before any send. The page drops a reply for an id it never
739
+ // sent, so an invented UUID cannot become a bubble.
740
+ let state = states.get(inReplyTo);
631
741
  if (!state) {
632
- throw Object.assign(new Error('in_reply_to is not a prompt delivered to this session'), { code: 'unknown_prompt' });
742
+ if (!UUID_RE.test(inReplyTo)) {
743
+ throw Object.assign(new Error('in_reply_to is not a prompt delivered to this session'), { code: 'unknown_prompt' });
744
+ }
745
+ remember(inReplyTo, 'delivered');
746
+ state = 'delivered';
633
747
  }
634
748
  if (state === 'cancelled') {
635
749
  return { ok: false, error: 'cancelled' };
@@ -642,22 +756,26 @@ export function createPromptSession(options) {
642
756
  text,
643
757
  ts: new Date(now()).toISOString(),
644
758
  final: isFinal,
645
- });
759
+ }, { required: true });
760
+ const finish = () => {
761
+ if (isFinal) {
762
+ queue = queue.filter((item) => item.kind === 'cancel' || item.id !== inReplyTo);
763
+ states.set(inReplyTo, 'replied');
764
+ emitStatus(false, inReplyTo, true);
765
+ } else if (agentState === 'working') {
766
+ // Building stays until the final reply. A partial reply only refreshes the stall window.
767
+ workedEpoch = promptEpoch;
768
+ noteActivity();
769
+ } else {
770
+ // A streamed reply while responding keeps the dots and restarts the window.
771
+ workedEpoch = promptEpoch;
772
+ emitState('typing', inReplyTo, false);
773
+ }
774
+ return { id: inReplyTo, final: isFinal };
775
+ };
776
+ if (sent && typeof sent.then === 'function') return sent.then(finish);
646
777
  if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
647
- if (isFinal) {
648
- queue = queue.filter((item) => item.kind === 'cancel' || item.id !== inReplyTo);
649
- states.set(inReplyTo, 'replied');
650
- emitStatus(false, inReplyTo, true);
651
- } else if (agentState === 'working') {
652
- // Building stays until the final reply. A partial reply only refreshes the stall window.
653
- workedEpoch = promptEpoch;
654
- noteActivity();
655
- } else {
656
- // A streamed reply while responding keeps the dots and restarts the window.
657
- workedEpoch = promptEpoch;
658
- emitState('typing', inReplyTo, false);
659
- }
660
- return { id: inReplyTo, final: isFinal };
778
+ return finish();
661
779
  }
662
780
 
663
781
  /**
@@ -691,9 +809,41 @@ export function createPromptSession(options) {
691
809
  return { ok: false, error: 'cancelled' };
692
810
  }
693
811
  workedEpoch = promptEpoch;
694
- const sent = emitState(state, id || lastId, true, typeof args.label === 'string' ? args.label : undefined);
812
+ const sent = emitState(state, id || lastId, true, typeof args.label === 'string' ? args.label : undefined, true);
813
+ const payload = { working: state !== 'idle', state };
814
+ if (sent && typeof sent.then === 'function') return sent.then(() => payload);
815
+ if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
816
+ return payload;
817
+ }
818
+
819
+ /**
820
+ * Working signal only. Optional text is accepted and never sent.
821
+ * @param {{ text?: unknown }} [args]
822
+ */
823
+ function postProgress(args = {}) {
824
+ if (args?.text != null && typeof args.text !== 'string') {
825
+ throw Object.assign(new Error('text must be a string'), { code: 'bad_args' });
826
+ }
827
+ if (typeof args?.text === 'string' && args.text.length > 500) {
828
+ throw Object.assign(new Error('text must be at most 500 characters'), { code: 'bad_args' });
829
+ }
830
+ const sent = emit({ type: PAIR_MSG.AGENT_PROGRESS, v: 1, working: true }, { required: true });
831
+ const payload = { ok: true, working: true };
832
+ if (sent && typeof sent.then === 'function') return sent.then(() => payload);
833
+ if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
834
+ return payload;
835
+ }
836
+
837
+ /**
838
+ * Deliberate end of the session. Not called from process exit, stdin
839
+ * end, or SIGTERM.
840
+ */
841
+ function closeSession() {
842
+ const sent = emit({ type: PAIR_MSG.AGENT_CLOSE_SESSION, v: 1 }, { required: true });
843
+ const payload = { ok: true, closed: true };
844
+ if (sent && typeof sent.then === 'function') return sent.then(() => payload);
695
845
  if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
696
- return { working: state !== 'idle', state };
846
+ return payload;
697
847
  }
698
848
 
699
849
  /**
@@ -772,6 +922,7 @@ export function createPromptSession(options) {
772
922
  promptEpoch = 0;
773
923
  workedEpoch = 0;
774
924
  lastAcceptedAt = -Infinity;
925
+ lastSessionAt = -Infinity;
775
926
  lastId = null;
776
927
  clearIdle();
777
928
  }
@@ -784,6 +935,8 @@ export function createPromptSession(options) {
784
935
  recentPrompts,
785
936
  reply,
786
937
  setStatus,
938
+ postProgress,
939
+ closeSession,
787
940
  noteToolCall,
788
941
  holdWork,
789
942
  registerWebhook,
@@ -25,11 +25,17 @@ export const CLOSING_REPLY_GUIDANCE = 'When you finish a task started from the S
25
25
  */
26
26
  export const BUILDING_STATUS_GUIDANCE = 'Call set_status { state: "building" } only once you have everything you need and are actually creating or editing geometry.';
27
27
 
28
+ /**
29
+ * Session presence. Kept short: it is part of the initialize instructions,
30
+ * which hosts truncate past 2 KB.
31
+ */
32
+ export const SESSION_PRESENCE_GUIDANCE = 'Be interactive: post_progress while working, especially during long reasoning. A fresh process per tool call is normal and stays present. A long-lived process is optional, never required. Call close_session when done, never on exit.';
33
+
28
34
  /**
29
35
  * First paragraph of the MCP initialize `instructions`.
30
36
  * Goldens pin the webhook sentence as the prefix.
31
37
  */
32
- export const PROMPT_SERVER_INSTRUCTIONS = `call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages. ${CLOSING_REPLY_GUIDANCE} ${BUILDING_STATUS_GUIDANCE}`;
38
+ export const PROMPT_SERVER_INSTRUCTIONS = `call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages. ${CLOSING_REPLY_GUIDANCE} ${BUILDING_STATUS_GUIDANCE} ${SESSION_PRESENCE_GUIDANCE}`;
33
39
 
34
40
  /** Exact wording the agent should relay when asking the user for a webhook. */
35
41
  export const PROMPT_ONBOARDING_ASK = 'To get SurfCAD messages instantly, send me your webhook URL and key. This only needs to be done once. Otherwise I\'ll check for SurfCAD messages between steps, so replies may lag.';
@@ -49,6 +55,8 @@ export const PROMPT_TOOL_NAMES = Object.freeze([
49
55
  'read_messages',
50
56
  'reply_to_user',
51
57
  'set_status',
58
+ 'post_progress',
59
+ 'close_session',
52
60
  ]);
53
61
 
54
62
  const PROMPT_TOOL_SET = new Set(PROMPT_TOOL_NAMES);
@@ -94,7 +102,7 @@ export function promptToolDefinitions() {
94
102
  },
95
103
  {
96
104
  name: 'read_messages',
97
- description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text. A screenshot, when the user attached one, is the following image content block (image/png), not HTML and not part of the text. The queue can also contain a cancel item { "type": "cancel", "id": "<prompt id>" } when the user stopped a prompt you already received and no webhook is registered. Stop work on that id. Do not call reply_to_user or set_status for it. Every response includes recent: the last ${PROMPT_QUEUE_CAP} prompts this session received, oldest first, each { id, state } (queued, delivered, replied, or cancelled), held in memory only. acked is only the ids this call removed. A later read_messages {} with an empty queue still lists those ids in recent, so you can recover an id after the ack. status.last is only the newest id. ${USER_CONTENT} Do not render the text or the image as HTML. When you finish the task from a prompt you received here, close that chat: ${CLOSING_REPLY_GUIDANCE}`,
105
+ description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text. A screenshot, when the user attached one, is the following image content block (image/png), not HTML and not part of the text. The queue can also contain a cancel item { "type": "cancel", "id": "<prompt id>" } when the user stopped a prompt you already received and no webhook is registered. Stop work on that id. Do not call reply_to_user or set_status for it. Every response includes recent: the last ${PROMPT_QUEUE_CAP} prompts this session received, oldest first, each { id, state } (queued, delivered, replied, or cancelled), held in memory only. A remote session returns that same recent list; an idle session that has not received a prompt has recent: []. acked is only the ids this call removed. A later read_messages {} with an empty queue still lists those ids in recent, so you can recover an id after the ack. status.last is only the newest id. ${USER_CONTENT} Do not render the text or the image as HTML. When you finish the task from a prompt you received here, close that chat: ${CLOSING_REPLY_GUIDANCE}`,
98
106
  inputSchema: {
99
107
  type: 'object',
100
108
  additionalProperties: false,
@@ -116,15 +124,15 @@ export function promptToolDefinitions() {
116
124
  },
117
125
  {
118
126
  name: 'reply_to_user',
119
- description: `${CLOSING_REPLY_GUIDANCE} The final reply is expected: it closes the task in the chat. Send a plain-text reply to the SurfCAD user for a prompt id this session received. Several replies may share one id, including non-final replies and a final reply after read_messages has acked that prompt. Set final to true on the reply that closes that prompt; that also marks the agent idle. The text is delivered as text, never rendered as HTML. This does not write the model or git. An in_reply_to that was never delivered to this session is an error unknown_prompt and nothing is sent to the tab. A cancelled id returns { "ok": false, "error": "cancelled" } and is not delivered.`,
127
+ description: `${CLOSING_REPLY_GUIDANCE} The final reply is expected: it closes the task in the chat. Send a plain-text reply to the SurfCAD user for a prompt id this session received. Several replies may share one id, including non-final replies and a final reply after read_messages has acked that prompt. Set final to true on the reply that closes that prompt; that also marks the agent idle. Omit in_reply_to to post one plain-text message to this paired session when no prompt is waiting. That note is not a prompt id, is limited to one per second, and does not close a prompt. The text is delivered as text, never rendered as HTML. This does not write the model or git. An in_reply_to that was never delivered to this session is an error unknown_prompt and nothing is sent to the tab. A cancelled id returns { "ok": false, "error": "cancelled" } and is not delivered.`,
120
128
  inputSchema: {
121
129
  type: 'object',
122
130
  additionalProperties: false,
123
- required: ['in_reply_to', 'text'],
131
+ required: ['text'],
124
132
  properties: {
125
133
  in_reply_to: {
126
134
  type: 'string',
127
- description: 'Prompt id this reply answers. Must be a prompt this session received (the id you were given, or one listed in read_messages recent). Any other id is unknown_prompt.',
135
+ description: 'Prompt id this reply answers. Omit it to post a session message with no prompt. When set, it must be a prompt this session received (the id you were given, or one listed in read_messages recent). Any other id is unknown_prompt.',
128
136
  },
129
137
  text: {
130
138
  type: 'string',
@@ -139,7 +147,7 @@ export function promptToolDefinitions() {
139
147
  },
140
148
  {
141
149
  name: 'set_status',
142
- description: `Tell the SurfCAD tab which phase the user's prompt is in. responding (alias typing): you are reading or writing an answer; the chat stays open with bouncing dots. building (alias working): you are creating or editing geometry; the chat collapses and the field shows "Agent is working...". ${BUILDING_STATUS_GUIDANCE} Do not call building to list parts, faces, edges, or transforms, or for status or read_messages. A model-changing tool also enters building if you skip this call. A read never does. set_status is for progress and does not close the task. A partial reply does not leave building; the final reply, Stop, or a disconnect does. No activity for ${agentPromptStallMinutes()} minutes, while responding or building, shows the stall notice and leaves Stop up. The result state is the tab value (responding and typing are typing; building and working are working). Without id it targets the latest prompt. A cancelled id returns { ok: false, error: cancelled }. ${CLOSING_REPLY_GUIDANCE}`,
150
+ description: `Tell the SurfCAD tab which phase the user's prompt is in. responding (alias typing): you are reading or writing an answer; the chat stays open with bouncing dots. building (alias working): you are creating or editing geometry; the chat collapses and the field shows "Agent is working...". ${BUILDING_STATUS_GUIDANCE} Do not call building to list parts, faces, edges, or transforms, or for status or read_messages. A model-changing tool also enters building if you skip this call. A read never does. set_status is for progress and does not close the task. A partial reply does not leave building; the final reply, Stop, or a disconnect does. No activity for ${agentPromptStallMinutes()} minutes, while responding or building, shows the stall notice and leaves Stop up. The result state is the tab value (responding and typing are typing; building and working are working). Without id it targets the latest prompt. With no prompt at all (a build you started yourself, or a prompt an earlier one-shot process read) the tab still shows the state: it keeps a session-level state fed by this call, by every model-changing tool you call, and by post_progress, and it returns to idle 60 s after the last of those. A cancelled id returns { ok: false, error: cancelled }. ${CLOSING_REPLY_GUIDANCE}`,
143
151
  inputSchema: {
144
152
  type: 'object',
145
153
  additionalProperties: false,
@@ -165,6 +173,30 @@ export function promptToolDefinitions() {
165
173
  },
166
174
  },
167
175
  },
176
+ {
177
+ name: 'post_progress',
178
+ description: 'Tell SurfCAD you are working, without showing thinking text. Call it while you work, especially during long reasoning, so the phone folds the chat and the bot button spins. Optional text is accepted and discarded; it is never shown. This also keeps the session present. It does not close the task.',
179
+ inputSchema: {
180
+ type: 'object',
181
+ additionalProperties: false,
182
+ properties: {
183
+ text: {
184
+ type: 'string',
185
+ maxLength: 500,
186
+ description: 'Optional note for yourself. It is not sent to the tab and is not shown.',
187
+ },
188
+ },
189
+ },
190
+ },
191
+ {
192
+ name: 'close_session',
193
+ description: 'End this SurfCAD agent session. Call it once when you are done. The server marks the agent offline immediately. Do not call it on process exit, stdin end, or SIGTERM. A later tool call can start a new session.',
194
+ inputSchema: {
195
+ type: 'object',
196
+ additionalProperties: false,
197
+ properties: {},
198
+ },
199
+ },
168
200
  ];
169
201
  }
170
202
 
@@ -209,11 +241,19 @@ export async function callPromptTool(prompts, name, args) {
209
241
  return { content };
210
242
  }
211
243
  if (name === 'reply_to_user') {
212
- const result = prompts.reply(args);
244
+ const result = await prompts.reply(args);
213
245
  return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
214
246
  }
215
247
  if (name === 'set_status') {
216
- const result = prompts.setStatus(args);
248
+ const result = await prompts.setStatus(args);
249
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
250
+ }
251
+ if (name === 'post_progress') {
252
+ const result = await prompts.postProgress(args);
253
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
254
+ }
255
+ if (name === 'close_session') {
256
+ const result = await prompts.closeSession();
217
257
  return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
218
258
  }
219
259
  throw Object.assign(new Error(`Unknown tool: ${name}`), { code: 'unknown_tool' });
@@ -19,12 +19,24 @@ export const PAIR_MSG = Object.freeze({
19
19
  AGENT_PROMPT_ACK: 'agent.prompt.ack',
20
20
  /** Agent → page. Contract v:1. Several replies may share one prompt id. */
21
21
  AGENT_REPLY: 'agent.reply',
22
+ /** Agent → page. Contract v:1. A plain-text note for this paired session, with no prompt id. */
23
+ AGENT_MESSAGE: 'agent.message',
22
24
  /** Agent → page. Contract v:1. */
23
25
  AGENT_STATUS: 'agent.status',
24
26
  /** Agent → page. Contract v:1. Refreshes the working deadline without changing state. */
25
27
  AGENT_ACTIVITY: 'agent.activity',
28
+ /** Agent → page. Contract v:1. Working signal only. No thinking text. */
29
+ AGENT_PROGRESS: 'agent.progress',
30
+ /** Agent → server. Ends the session. Not sent on process exit. */
31
+ AGENT_CLOSE_SESSION: 'agent.close_session',
26
32
  /** Page → paired agent. Contract v:1. `{ id }`. */
27
33
  AGENT_PROMPT_CANCEL: 'agent.prompt.cancel',
28
34
  /** Agent → page. Contract v:1. `{ id, state }`. */
29
35
  AGENT_PROMPT_CANCEL_RESULT: 'agent.prompt.cancel.result',
36
+ /**
37
+ * Agent → server relay only. Contract v:1. `{ ids }`: prompts the agent
38
+ * has now (read_messages returned them, or the webhook POST succeeded),
39
+ * so the server stops holding them for the next process. Not forwarded.
40
+ */
41
+ AGENT_PROMPT_TAKEN: 'agent.prompt.taken',
30
42
  });
@@ -105,6 +105,7 @@ export function agentUrls(origin) {
105
105
  pollUrl: `${base}/agent/pair/poll`,
106
106
  joinUrl: `${base}/agent/join/redeem`,
107
107
  commandsUrl: `${base}/agent/commands`,
108
+ promptsUrl: `${base}/agent/prompts`,
108
109
  };
109
110
  }
110
111
 
@@ -5,7 +5,7 @@
5
5
  */
6
6
 
7
7
  import { readCommandResponse } from '../commandProtocol.mjs';
8
- import { asRemoteError, tokenRevokedError } from '../errors.mjs';
8
+ import { asRemoteError, authErrorFromBody } from '../errors.mjs';
9
9
 
10
10
  /** How long a command may sit unanswered, on the WebSocket and on HTTPS. */
11
11
  export const COMMAND_WAIT_MS = 10 * 60 * 1000;
@@ -24,7 +24,7 @@ export function commandWaitTimeout() {
24
24
  * @param {any} json
25
25
  */
26
26
  function httpFailure(status, json) {
27
- if (status === 401) return tokenRevokedError();
27
+ if (status === 401) return authErrorFromBody(json);
28
28
  const code = typeof json?.error === 'string' ? json.error : '';
29
29
  const message = typeof json?.message === 'string' ? json.message : '';
30
30
  return asRemoteError({ code, message: message || code });
@@ -189,7 +189,7 @@ export async function callOverHttp(options) {
189
189
  } catch {
190
190
  posted = null;
191
191
  }
192
- if (post.status === 401) throw tokenRevokedError();
192
+ if (post.status === 401) throw authErrorFromBody(posted);
193
193
  if (post.status !== 202) throw httpFailure(post.status, posted);
194
194
 
195
195
  const deadline = now() + COMMAND_WAIT_MS;
@@ -221,8 +221,10 @@ export async function callOverHttp(options) {
221
221
  function isTerminal(err) {
222
222
  const code = err && typeof err === 'object' ? /** @type {{ code?: string }} */ (err).code : '';
223
223
  return code === 'tab_asleep'
224
+ || code === 'command_timeout'
224
225
  || code === 'too_many_pending'
225
226
  || code === 'token_revoked'
227
+ || code === 'expired'
226
228
  || code === 'client_update_required'
227
229
  || code === 'not_found';
228
230
  }
@@ -242,7 +244,11 @@ async function waitViaSse(options, fetchImpl, signal) {
242
244
  },
243
245
  signal,
244
246
  });
245
- if (res.status === 401) throw tokenRevokedError();
247
+ if (res.status === 401) {
248
+ let json = null;
249
+ try { json = await res.json(); } catch { json = null; }
250
+ throw authErrorFromBody(json);
251
+ }
246
252
  if (!res.ok) {
247
253
  try { await res.body?.cancel?.(); } catch { /* noop */ }
248
254
  throw Object.assign(new Error(`Event stream failed (${res.status})`), { code: 'sse_failed' });
@@ -274,7 +280,7 @@ async function waitViaPoll(options, fetchImpl, signal) {
274
280
  } catch {
275
281
  json = null;
276
282
  }
277
- if (res.status === 401) throw tokenRevokedError();
283
+ if (res.status === 401) throw authErrorFromBody(json);
278
284
  if (res.status === 404) {
279
285
  throw Object.assign(new Error('That command is no longer waiting.'), { code: 'not_found' });
280
286
  }