surfcad-mcp 0.3.3 → 0.3.4
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/bin/surfcad-mcp.js +25 -1
- package/data/commands.json +2 -2
- package/package.json +1 -1
- package/src/cli.mjs +3 -2
- package/src/errors.mjs +2 -2
- package/src/prompt/errorHints.mjs +3 -3
- package/src/prompt/promptSession.mjs +60 -23
- package/src/prompt/promptTools.mjs +2 -2
- package/src/remote/config.mjs +1 -0
- package/src/remote/login.mjs +77 -11
- package/src/remote/session.mjs +51 -19
package/bin/surfcad-mcp.js
CHANGED
|
@@ -2,9 +2,33 @@
|
|
|
2
2
|
import { runCli } from '../src/cli.mjs';
|
|
3
3
|
import { runSurfcadMcpServer } from '../src/server.mjs';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* `process.exit` drops a stderr write that has not reached the OS yet,
|
|
7
|
+
* so a bad flag can look like a silent non-zero exit. Finish the write first.
|
|
8
|
+
* @param {NodeJS.WriteStream} stream
|
|
9
|
+
*/
|
|
10
|
+
function flushed(stream) {
|
|
11
|
+
return new Promise((resolve) => {
|
|
12
|
+
if (typeof stream.write !== 'function') {
|
|
13
|
+
resolve();
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
// A full pipe with no reader must not hang login. 50 ms is enough for
|
|
17
|
+
// a live stderr to take the error and the usage text.
|
|
18
|
+
const timer = setTimeout(resolve, 50);
|
|
19
|
+
stream.write('', () => {
|
|
20
|
+
clearTimeout(timer);
|
|
21
|
+
resolve();
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
5
26
|
try {
|
|
6
27
|
const outcome = await runCli(process.argv.slice(2));
|
|
7
|
-
if (outcome.action === 'exit')
|
|
28
|
+
if (outcome.action === 'exit') {
|
|
29
|
+
await Promise.all([flushed(process.stdout), flushed(process.stderr)]);
|
|
30
|
+
process.exit(outcome.code);
|
|
31
|
+
}
|
|
8
32
|
await runSurfcadMcpServer({
|
|
9
33
|
mode: outcome.mode,
|
|
10
34
|
server: outcome.server,
|
package/data/commands.json
CHANGED
|
@@ -2534,7 +2534,7 @@
|
|
|
2534
2534
|
},
|
|
2535
2535
|
{
|
|
2536
2536
|
"name": "mold_fit",
|
|
2537
|
-
"description": "Read-only moldability fit for one part mesh, in the part local frame (the same frame as list_faces). Searches bounding-box axes, large planar normals, and an icosphere (about 80 directions, deduped within 5°, d and -d are one axis). The chosen pull has the least occluded undercut area. Scores within max(2% of the part area, 25 mm²) of that best are tied; box axes and large planar normals win the tie over an icosphere sample, and drafted area breaks the rest. Fit is still good (0 undercut regions), fixable (1 to 4), or not_a_fit (5 or more), plus undercutCount, undercutArea, draftedArea, pull, and pullSource. Pass pull [x, y, z] to score that axis instead and keep its sign. The same result includes wall: a local thickness per triangle, nominal (mode, or the median when no thickness dominates the interior band), max, min, mean, median, and thin and thick regions. Thickness below 0.6× nominal is thin and above 1.5× nominal is thick. Wall thickness follows the geometric normal of each triangle. A stamp only flips that side when it points the other way, so one stamp on a curved face does not steer every facet. A triangle whose own normal is within 0.5° of perpendicular to the pull is
|
|
2537
|
+
"description": "Read-only moldability fit for one part mesh, in the part local frame (the same frame as list_faces). Searches bounding-box axes, large planar normals, and an icosphere (about 80 directions, deduped within 5°, d and -d are one axis). The chosen pull has the least occluded undercut area. Scores within max(2% of the part area, 25 mm²) of that best are tied; box axes and large planar normals win the tie over an icosphere sample, and drafted area breaks the rest. Fit is still good (0 undercut regions), fixable (1 to 4), or not_a_fit (5 or more), plus undercutCount, undercutArea, draftedArea, pull, and pullSource. Pass pull [x, y, z] to score that axis instead and keep its sign. The same result includes wall: a local thickness per triangle, nominal (mode, or the median when no thickness dominates the interior band), max, min, mean, median, and thin and thick regions. Thickness below 0.6× nominal is thin and above 1.5× nominal is thick. Wall thickness follows the geometric normal of each triangle. A stamp only flips that side when it points the other way, so one stamp on a curved face does not steer every facet. A triangle whose own normal is within 0.5° of perpendicular to the pull is not an undercut, and an undercut needs another triangle covering that point. A geometric check for later molding slices, not a supplier DFM. parting on the same result classifies every face as core or cavity by complete visibility (core along +pull, cavity along -pull). A wall within 0.5° of vertical takes the role of the labelled neighbour it can reach. There is no zero-draft class. One outer parting loop is kept. Stamped edges keep their names. sideActions on the same result clusters those undercuts into slides and lifters, each with a suggested pull. That split is a heuristic. count, slideCount, and lifterCount are the numbers a later tooling adder can use. moldDraft on the same result flags side walls below 1° of draft and lists ejector-pin and sleeve candidate positions. Those candidates are a heuristic. It does not edit CAD draft.",
|
|
2538
2538
|
"args": {
|
|
2539
2539
|
"type": "object",
|
|
2540
2540
|
"additionalProperties": false,
|
|
@@ -2676,7 +2676,7 @@
|
|
|
2676
2676
|
},
|
|
2677
2677
|
{
|
|
2678
2678
|
"name": "mold_parting",
|
|
2679
|
-
"description": "Show or hide the core and cavity colours on the active part, in the part local frame. on true classifies
|
|
2679
|
+
"description": "Show or hide the core and cavity colours on the active part, in the part local frame. on true classifies every face from the mold-analysis pull by complete visibility (core along +pull, cavity along -pull). A wall within 0.5° of vertical is still core or cavity: it takes the role of the labelled neighbour it can reach, so an inner pocket wall joins the core and an outer wall joins the cavity. There is no separate zero-draft colour. The outer parting loop is a polyline. Stamped faces keep their edge names on that loop. on false removes the skin so face paint and the part colour show again. Omit on to toggle. Read-only. Not a CAD draft edit and not a quote.",
|
|
2680
2680
|
"args": {
|
|
2681
2681
|
"type": "object",
|
|
2682
2682
|
"additionalProperties": false,
|
package/package.json
CHANGED
package/src/cli.mjs
CHANGED
|
@@ -145,7 +145,7 @@ export async function runCli(argv, options = {}) {
|
|
|
145
145
|
}
|
|
146
146
|
if (parsed.command === 'login' || parsed.command === 'logout' || parsed.command === 'status') {
|
|
147
147
|
if (parsed.remote || parsed.local) {
|
|
148
|
-
io.stderr(
|
|
148
|
+
io.stderr(`login, logout, and status do not take --remote or --local.\n${HELP}`);
|
|
149
149
|
return { action: 'exit', code: 1 };
|
|
150
150
|
}
|
|
151
151
|
}
|
|
@@ -194,7 +194,8 @@ export async function runCli(argv, options = {}) {
|
|
|
194
194
|
return { action: 'exit', code: 0 };
|
|
195
195
|
}
|
|
196
196
|
} catch (err) {
|
|
197
|
-
|
|
197
|
+
const usage = err?.code === 'bad_args' || err?.code === 'bad_server' ? HELP : '';
|
|
198
|
+
io.stderr(`${err?.message || 'Login failed'}\n${usage}`);
|
|
198
199
|
return { action: 'exit', code: 1 };
|
|
199
200
|
}
|
|
200
201
|
|
package/src/errors.mjs
CHANGED
|
@@ -20,7 +20,7 @@ export function formatBridgeError(err) {
|
|
|
20
20
|
export function notPairedError() {
|
|
21
21
|
return {
|
|
22
22
|
code: 'not_paired',
|
|
23
|
-
message: 'Not paired to a SurfCAD tab. Set SURFCAD_PAIRING_CODE or call the pair tool
|
|
23
|
+
message: 'Not paired to a SurfCAD tab. Set SURFCAD_PAIRING_CODE or call the pair tool and click Allow, or run npx surfcad-mcp login --code with the join code.',
|
|
24
24
|
hint: pairingEnvHint(),
|
|
25
25
|
};
|
|
26
26
|
}
|
|
@@ -44,7 +44,7 @@ export function pairPendingError() {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
export function pairingEnvHint() {
|
|
47
|
-
return 'Copy the 8-character code from SurfCAD → Local agent → Show pairing code.';
|
|
47
|
+
return 'Copy the 8-character code from SurfCAD → Local agent → Show pairing code, or run npx surfcad-mcp login --code with the join code.';
|
|
48
48
|
}
|
|
49
49
|
|
|
50
50
|
export function tabAsleepError() {
|
|
@@ -20,7 +20,7 @@ const CRASH_GUIDE = 'The whole run was treated as a crash (reason timeout, out_o
|
|
|
20
20
|
|
|
21
21
|
const NAMES_GUIDE = 'Faces and edges are addressed by the keys and names list_faces / list_feature_edges return for the current mesh. A key from before a rebuild, a display label, or a guess answers unknown_face / unknown_edge; a key that matches several patches answers ambiguous_face / ambiguous_edge with details.candidates. List again (filter and page the list on a detailed part), then select_faces { keys } or { names } with a row from that answer. Faces a helper built carry a name (feature.role) that survives upstream edits; prefer names when you will edit the part again.';
|
|
22
22
|
|
|
23
|
-
const PAIRING_GUIDE = 'A bridge call before pair is not_paired: call pair { code } with the 8-character code from SurfCAD → Local agent → Show pairing code (or set SURFCAD_PAIRING_CODE). pair_pending means the user has not clicked Allow yet; wait and retry the same call. pair_rejected means they clicked Deny; ask before trying again. pairing_lost means the tab or relay dropped and the server re-pairs on its own: retry in a few seconds, do not ask for a new code. Webhook errors (bad_webhook_url) need a public https URL; a local session polls read_messages { wait_ms: 25000 } instead.';
|
|
23
|
+
const PAIRING_GUIDE = 'A bridge call before pair is not_paired: call pair { code } with the 8-character code from SurfCAD → Local agent → Show pairing code (or set SURFCAD_PAIRING_CODE). A remote session uses the join code instead: npx surfcad-mcp login --code ABCD-EFGH. pair_pending means the user has not clicked Allow yet; wait and retry the same call. pair_rejected means they clicked Deny; ask before trying again. pairing_lost means the tab or relay dropped and the server re-pairs on its own: retry in a few seconds, do not ask for a new code. Webhook errors (bad_webhook_url) need a public https URL; a local session polls read_messages { wait_ms: 25000 } instead.';
|
|
24
24
|
|
|
25
25
|
const CONTOUR_GUIDE = 'open_feature on an extrude, revolve, loft or sweep that owns a contour reopens its sketch; edit_feature then patches the sketch (points, radius, width / height, polygon_preset, or tool) and confirm_feature saves the sketch and the feature in one step. no_feature_edit means nothing is open: open_feature { id } first (feature_tree {} lists ids), then edit, then confirm. sketch_cancel leaves a reopened sketch without writing.';
|
|
26
26
|
|
|
@@ -171,7 +171,7 @@ export const ERROR_HINTS = Object.freeze({
|
|
|
171
171
|
unknown_command: { hint: 'Not a bridge command: list_commands {} shows the names.' },
|
|
172
172
|
unknown_topic: { hint: 'guide {} lists the topics; error topics are errors.<code>.' },
|
|
173
173
|
// Pairing and prompts (MCP side)
|
|
174
|
-
not_paired: { hint: 'pair { code } with the code from SurfCAD → Local agent → Show pairing code,
|
|
174
|
+
not_paired: { hint: 'pair { code } with the 8-character code from SurfCAD → Local agent → Show pairing code (or set SURFCAD_PAIRING_CODE), or run npx surfcad-mcp login --code with the join code from SurfCAD.', guide: PAIRING_GUIDE },
|
|
175
175
|
pair_pending: { hint: 'The user has not clicked Allow yet: wait a few seconds and retry the same call; do not ask for a new code. If SurfCAD shows no Allow prompt, the tab may be an older build than this server: ask the user to reload SurfCAD and pair again.', guide: PAIRING_GUIDE },
|
|
176
176
|
pair_rejected: { hint: 'The user clicked Deny: ask them before calling pair again.', guide: PAIRING_GUIDE },
|
|
177
177
|
pair_cancelled: { hint: 'The pairing attempt was cancelled: pair { code } again when the user is ready.', guide: PAIRING_GUIDE },
|
|
@@ -182,7 +182,7 @@ export const ERROR_HINTS = Object.freeze({
|
|
|
182
182
|
too_many_pending: { hint: 'Wait for the SurfCAD tab to finish the commands already in flight, then retry.' },
|
|
183
183
|
token_revoked: { hint: 'Run npx surfcad-mcp login and approve the new code in SurfCAD.' },
|
|
184
184
|
client_update_required: { hint: 'This surfcad-mcp is too old for the agent server. Update the package, then run npx surfcad-mcp login again.' },
|
|
185
|
-
prompts_need_websocket: { hint: '
|
|
185
|
+
prompts_need_websocket: { hint: 'The agent WebSocket is not open. A paired session still sends status over HTTPS; retry the call. If it keeps failing, reconnect where the agent server allows wss.' },
|
|
186
186
|
relay_unavailable: { hint: 'The local relay is not running: start surfcad-mcp normally (it owns the relay) or set SURFCAD_AGENT_BRIDGE_WS_URL.', guide: PAIRING_GUIDE },
|
|
187
187
|
bridge_error: { hint: 'The tab refused the call without a code: status {} and retry once; tell the user if it repeats.' },
|
|
188
188
|
bad_webhook_url: { hint: 'Webhooks need a public https URL (no credentials, localhost or private hosts): fix it, or poll read_messages { wait_ms: 25000 } instead.', guide: PAIRING_GUIDE },
|
|
@@ -189,13 +189,43 @@ export function createPromptSession(options) {
|
|
|
189
189
|
for (const resolve of list) resolve();
|
|
190
190
|
}
|
|
191
191
|
|
|
192
|
-
function
|
|
192
|
+
function asSendError(err) {
|
|
193
|
+
const code = err && typeof err === 'object' && typeof err.code === 'string' && err.code
|
|
194
|
+
? err.code
|
|
195
|
+
: 'not_paired';
|
|
196
|
+
const message = err instanceof Error && err.message ? err.message : 'Not paired';
|
|
197
|
+
const out = err instanceof Error ? err : new Error(message);
|
|
198
|
+
if (!out.message) out.message = message;
|
|
199
|
+
out.code = code;
|
|
200
|
+
if (err && typeof err === 'object' && typeof err.hint === 'string' && !out.hint) out.hint = err.hint;
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* @param {object} payload
|
|
206
|
+
* @param {{ required?: boolean }} [opts]
|
|
207
|
+
* A required send keeps the transport's error (a connected remote session
|
|
208
|
+
* is not rewritten as not_paired). Advisory sends stay quiet.
|
|
209
|
+
*/
|
|
210
|
+
function emit(payload, { required = false } = {}) {
|
|
211
|
+
let result;
|
|
193
212
|
try {
|
|
194
|
-
send(payload);
|
|
195
|
-
|
|
196
|
-
|
|
213
|
+
result = send(payload);
|
|
214
|
+
} catch (err) {
|
|
215
|
+
if (required) throw asSendError(err);
|
|
197
216
|
return false;
|
|
198
217
|
}
|
|
218
|
+
if (result && typeof result.then === 'function') {
|
|
219
|
+
const pending = Promise.resolve(result).then(() => true);
|
|
220
|
+
if (!required) {
|
|
221
|
+
pending.catch(() => {});
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
return pending.catch((err) => {
|
|
225
|
+
throw asSendError(err);
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
return true;
|
|
199
229
|
}
|
|
200
230
|
|
|
201
231
|
function clearIdle() {
|
|
@@ -256,8 +286,9 @@ export function createPromptSession(options) {
|
|
|
256
286
|
* @param {string | null | undefined} id
|
|
257
287
|
* @param {boolean} force
|
|
258
288
|
* @param {string} [label]
|
|
289
|
+
* @param {boolean} [required]
|
|
259
290
|
*/
|
|
260
|
-
function emitState(state, id, force, label) {
|
|
291
|
+
function emitState(state, id, force, label, required = false) {
|
|
261
292
|
const next = state !== 'idle';
|
|
262
293
|
if (!force && agentState === state && !stalled) {
|
|
263
294
|
if (next) armIdle();
|
|
@@ -269,7 +300,7 @@ export function createPromptSession(options) {
|
|
|
269
300
|
const msg = { type: PAIR_MSG.AGENT_STATUS, v: 1, working: next, state };
|
|
270
301
|
if (typeof id === 'string' && id) msg.id = id;
|
|
271
302
|
if (typeof label === 'string' && label) msg.label = label.slice(0, 120);
|
|
272
|
-
const sent = emit(msg);
|
|
303
|
+
const sent = emit(msg, { required: required === true });
|
|
273
304
|
if (next) armIdle();
|
|
274
305
|
else clearIdle();
|
|
275
306
|
return sent;
|
|
@@ -642,22 +673,26 @@ export function createPromptSession(options) {
|
|
|
642
673
|
text,
|
|
643
674
|
ts: new Date(now()).toISOString(),
|
|
644
675
|
final: isFinal,
|
|
645
|
-
});
|
|
676
|
+
}, { required: true });
|
|
677
|
+
const finish = () => {
|
|
678
|
+
if (isFinal) {
|
|
679
|
+
queue = queue.filter((item) => item.kind === 'cancel' || item.id !== inReplyTo);
|
|
680
|
+
states.set(inReplyTo, 'replied');
|
|
681
|
+
emitStatus(false, inReplyTo, true);
|
|
682
|
+
} else if (agentState === 'working') {
|
|
683
|
+
// Building stays until the final reply. A partial reply only refreshes the stall window.
|
|
684
|
+
workedEpoch = promptEpoch;
|
|
685
|
+
noteActivity();
|
|
686
|
+
} else {
|
|
687
|
+
// A streamed reply while responding keeps the dots and restarts the window.
|
|
688
|
+
workedEpoch = promptEpoch;
|
|
689
|
+
emitState('typing', inReplyTo, false);
|
|
690
|
+
}
|
|
691
|
+
return { id: inReplyTo, final: isFinal };
|
|
692
|
+
};
|
|
693
|
+
if (sent && typeof sent.then === 'function') return sent.then(finish);
|
|
646
694
|
if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
|
|
647
|
-
|
|
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 };
|
|
695
|
+
return finish();
|
|
661
696
|
}
|
|
662
697
|
|
|
663
698
|
/**
|
|
@@ -691,9 +726,11 @@ export function createPromptSession(options) {
|
|
|
691
726
|
return { ok: false, error: 'cancelled' };
|
|
692
727
|
}
|
|
693
728
|
workedEpoch = promptEpoch;
|
|
694
|
-
const sent = emitState(state, id || lastId, true, typeof args.label === 'string' ? args.label : undefined);
|
|
729
|
+
const sent = emitState(state, id || lastId, true, typeof args.label === 'string' ? args.label : undefined, true);
|
|
730
|
+
const payload = { working: state !== 'idle', state };
|
|
731
|
+
if (sent && typeof sent.then === 'function') return sent.then(() => payload);
|
|
695
732
|
if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
|
|
696
|
-
return
|
|
733
|
+
return payload;
|
|
697
734
|
}
|
|
698
735
|
|
|
699
736
|
/**
|
|
@@ -209,11 +209,11 @@ export async function callPromptTool(prompts, name, args) {
|
|
|
209
209
|
return { content };
|
|
210
210
|
}
|
|
211
211
|
if (name === 'reply_to_user') {
|
|
212
|
-
const result = prompts.reply(args);
|
|
212
|
+
const result = await prompts.reply(args);
|
|
213
213
|
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
214
214
|
}
|
|
215
215
|
if (name === 'set_status') {
|
|
216
|
-
const result = prompts.setStatus(args);
|
|
216
|
+
const result = await prompts.setStatus(args);
|
|
217
217
|
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
218
218
|
}
|
|
219
219
|
throw Object.assign(new Error(`Unknown tool: ${name}`), { code: 'unknown_tool' });
|
package/src/remote/config.mjs
CHANGED
package/src/remote/login.mjs
CHANGED
|
@@ -31,12 +31,34 @@ export function loginStatusError(status) {
|
|
|
31
31
|
return 'Login ended before approval. Run npx surfcad-mcp login again.';
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
+
export const LOGIN_STALE_MESSAGE = 'That login code is stale. Run npx surfcad-mcp login again for a new one.';
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @param {unknown} retryAfterSec
|
|
38
|
+
* @returns {string} empty, or ` try again in N s.`
|
|
39
|
+
*/
|
|
40
|
+
export function formatRetryAfter(retryAfterSec) {
|
|
41
|
+
const sec = Number(retryAfterSec);
|
|
42
|
+
if (!Number.isFinite(sec) || sec <= 0) return '';
|
|
43
|
+
return ` try again in ${Math.ceil(sec)} s.`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @param {string} lead sentence ending in a period
|
|
48
|
+
* @param {unknown} retryAfterSec
|
|
49
|
+
* @param {string} again
|
|
50
|
+
*/
|
|
51
|
+
function rateLimitMessage(lead, retryAfterSec, again) {
|
|
52
|
+
return `${lead}${formatRetryAfter(retryAfterSec)} ${again}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
34
55
|
/**
|
|
35
56
|
* @param {string} url
|
|
36
57
|
* @param {object} body
|
|
37
58
|
* @param {typeof fetch} fetchImpl
|
|
59
|
+
* @param {AbortSignal} [signal]
|
|
38
60
|
*/
|
|
39
|
-
async function postJson(url, body, fetchImpl) {
|
|
61
|
+
async function postJson(url, body, fetchImpl, signal) {
|
|
40
62
|
/** @type {Response} */
|
|
41
63
|
let res;
|
|
42
64
|
try {
|
|
@@ -47,8 +69,12 @@ async function postJson(url, body, fetchImpl) {
|
|
|
47
69
|
Accept: 'application/json',
|
|
48
70
|
},
|
|
49
71
|
body: JSON.stringify(body),
|
|
72
|
+
signal,
|
|
50
73
|
});
|
|
51
|
-
} catch {
|
|
74
|
+
} catch (err) {
|
|
75
|
+
if (err?.name === 'AbortError') {
|
|
76
|
+
throw Object.assign(new Error('aborted'), { code: 'aborted' });
|
|
77
|
+
}
|
|
52
78
|
throw Object.assign(new Error('Could not reach the SurfCAD agent server.'), { code: 'unreachable' });
|
|
53
79
|
}
|
|
54
80
|
/** @type {any} */
|
|
@@ -93,7 +119,11 @@ export async function loginDevice(options) {
|
|
|
93
119
|
if (started.status !== 201 || !started.json?.userCode) {
|
|
94
120
|
const code = started.json?.error === 'rate_limited' ? 'rate_limited' : 'pair_failed';
|
|
95
121
|
const message = code === 'rate_limited'
|
|
96
|
-
?
|
|
122
|
+
? rateLimitMessage(
|
|
123
|
+
'Too many login attempts.',
|
|
124
|
+
started.json?.retryAfterSec,
|
|
125
|
+
'Run npx surfcad-mcp login again.',
|
|
126
|
+
)
|
|
97
127
|
: 'Could not start login.';
|
|
98
128
|
throw Object.assign(new Error(message), { code });
|
|
99
129
|
}
|
|
@@ -107,12 +137,47 @@ export async function loginDevice(options) {
|
|
|
107
137
|
interval: Number.isFinite(intervalSec) && intervalSec > 0 ? intervalSec : 5,
|
|
108
138
|
});
|
|
109
139
|
}
|
|
110
|
-
const
|
|
140
|
+
const expiresAtMs = Date.parse(started.json.expiresAt);
|
|
141
|
+
const deadline = Number.isFinite(expiresAtMs)
|
|
142
|
+
? expiresAtMs
|
|
143
|
+
: now() + (options.timeoutMs ?? 10 * 60 * 1000);
|
|
111
144
|
let first = true;
|
|
112
145
|
while (now() < deadline) {
|
|
113
|
-
if (!first)
|
|
146
|
+
if (!first) {
|
|
147
|
+
const wait = Math.min(pollMs, deadline - now());
|
|
148
|
+
if (wait > 0) await sleep(wait);
|
|
149
|
+
if (now() >= deadline) break;
|
|
150
|
+
}
|
|
114
151
|
first = false;
|
|
115
|
-
const
|
|
152
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
153
|
+
const remaining = Math.max(0, deadline - now());
|
|
154
|
+
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
|
155
|
+
let timeoutId;
|
|
156
|
+
const timeout = new Promise((resolve) => {
|
|
157
|
+
timeoutId = setTimeout(() => {
|
|
158
|
+
controller?.abort();
|
|
159
|
+
resolve({ timedOut: true });
|
|
160
|
+
}, remaining);
|
|
161
|
+
});
|
|
162
|
+
const pending = postJson(urls.pollUrl, { deviceSecret, userCode }, fetchImpl, controller?.signal)
|
|
163
|
+
.catch((err) => {
|
|
164
|
+
if (err?.code === 'aborted') return { timedOut: true };
|
|
165
|
+
throw err;
|
|
166
|
+
});
|
|
167
|
+
let polled;
|
|
168
|
+
try {
|
|
169
|
+
polled = await Promise.race([pending, timeout]);
|
|
170
|
+
} finally {
|
|
171
|
+
clearTimeout(timeoutId);
|
|
172
|
+
}
|
|
173
|
+
if (polled?.timedOut) break;
|
|
174
|
+
if (polled.status === 429) {
|
|
175
|
+
throw Object.assign(new Error(rateLimitMessage(
|
|
176
|
+
'Too many login attempts.',
|
|
177
|
+
polled.json?.retryAfterSec,
|
|
178
|
+
'Run npx surfcad-mcp login again.',
|
|
179
|
+
)), { code: 'rate_limited' });
|
|
180
|
+
}
|
|
116
181
|
if (polled.status !== 200 || !polled.json?.status) {
|
|
117
182
|
throw Object.assign(new Error('Could not check the login code.'), { code: 'poll_failed' });
|
|
118
183
|
}
|
|
@@ -136,10 +201,7 @@ export async function loginDevice(options) {
|
|
|
136
201
|
}
|
|
137
202
|
throw Object.assign(new Error(loginStatusError(status)), { code: status });
|
|
138
203
|
}
|
|
139
|
-
throw Object.assign(
|
|
140
|
-
new Error('Timed out waiting for approval. Run npx surfcad-mcp login again.'),
|
|
141
|
-
{ code: 'expired' },
|
|
142
|
-
);
|
|
204
|
+
throw Object.assign(new Error(LOGIN_STALE_MESSAGE), { code: 'expired' });
|
|
143
205
|
}
|
|
144
206
|
|
|
145
207
|
/**
|
|
@@ -171,7 +233,11 @@ export async function loginWithCode(options) {
|
|
|
171
233
|
}, fetchImpl);
|
|
172
234
|
if (redeemed.status === 429) {
|
|
173
235
|
throw Object.assign(
|
|
174
|
-
new Error(
|
|
236
|
+
new Error(rateLimitMessage(
|
|
237
|
+
'Too many attempts.',
|
|
238
|
+
redeemed.json?.retryAfterSec,
|
|
239
|
+
'Run npx surfcad-mcp login --code again.',
|
|
240
|
+
)),
|
|
175
241
|
{ code: 'rate_limited' },
|
|
176
242
|
);
|
|
177
243
|
}
|
package/src/remote/session.mjs
CHANGED
|
@@ -357,17 +357,15 @@ export class RemoteSession {
|
|
|
357
357
|
}
|
|
358
358
|
if (msg.type === PAIR_MSG.AGENT_PROMPT_CANCEL) {
|
|
359
359
|
const cancelId = typeof msg.id === 'string' ? msg.id : '';
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
});
|
|
368
|
-
} catch {
|
|
360
|
+
void this.#prompts.cancel(cancelId).then((result) => {
|
|
361
|
+
Promise.resolve(this.#sendToTab({
|
|
362
|
+
type: PAIR_MSG.AGENT_PROMPT_CANCEL_RESULT,
|
|
363
|
+
v: 1,
|
|
364
|
+
id: result.id,
|
|
365
|
+
state: result.state,
|
|
366
|
+
})).catch(() => {
|
|
369
367
|
/* socket closed before the result could be sent */
|
|
370
|
-
}
|
|
368
|
+
});
|
|
371
369
|
}, () => {});
|
|
372
370
|
return;
|
|
373
371
|
}
|
|
@@ -427,19 +425,53 @@ export class RemoteSession {
|
|
|
427
425
|
}
|
|
428
426
|
|
|
429
427
|
/**
|
|
428
|
+
* Status and prompt frames. A paired WebSocket sends them on the socket.
|
|
429
|
+
* A paired HTTPS fallback (join-code login when wss is blocked, or the
|
|
430
|
+
* socket dropped) POSTs them. Either way a connected session is connected:
|
|
431
|
+
* the caller hears the transport's error, not a collapsed not_paired.
|
|
430
432
|
* @param {object} payload
|
|
431
433
|
*/
|
|
432
|
-
#sendToTab(payload) {
|
|
433
|
-
if (
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
434
|
+
async #sendToTab(payload) {
|
|
435
|
+
if (!this.isPaired()) await this.connect();
|
|
436
|
+
if (this.#transport === 'ws' && this.#ws && this.#ws.readyState === WebSocket.OPEN) {
|
|
437
|
+
this.#ws.send(JSON.stringify(payload));
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
if (this.#state === 'paired' && this.#transport === 'http') {
|
|
441
|
+
await this.#postPrompt(payload);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* @param {object} payload
|
|
449
|
+
*/
|
|
450
|
+
async #postPrompt(payload) {
|
|
451
|
+
let res;
|
|
452
|
+
try {
|
|
453
|
+
res = await this.#fetch(this.#urls.promptsUrl, {
|
|
454
|
+
method: 'POST',
|
|
455
|
+
headers: {
|
|
456
|
+
Authorization: `Bearer ${this.#token}`,
|
|
457
|
+
'Content-Type': 'application/json',
|
|
439
458
|
},
|
|
440
|
-
|
|
459
|
+
body: JSON.stringify(payload),
|
|
460
|
+
});
|
|
461
|
+
} catch {
|
|
462
|
+
throw Object.assign(new Error('Could not reach the SurfCAD agent server.'), { code: 'unreachable' });
|
|
463
|
+
}
|
|
464
|
+
if (!res.ok) {
|
|
465
|
+
let json = null;
|
|
466
|
+
try { json = await res.json(); } catch { json = null; }
|
|
467
|
+
if (res.status === 401) throw tokenRevokedError();
|
|
468
|
+
const code = typeof json?.error === 'string' && json.error ? json.error : 'bridge_error';
|
|
469
|
+
const message = typeof json?.message === 'string' && json.message
|
|
470
|
+
? json.message
|
|
471
|
+
: `Prompt send failed (${res.status})`;
|
|
472
|
+
throw Object.assign(new Error(message), { code });
|
|
441
473
|
}
|
|
442
|
-
|
|
474
|
+
try { await res.body?.cancel?.(); } catch { /* noop */ }
|
|
443
475
|
}
|
|
444
476
|
|
|
445
477
|
/**
|