surfcad-mcp 0.3.2 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -7
- package/bin/surfcad-mcp.js +12 -3
- package/data/commands.json +4424 -129
- package/data/helpers.json +35 -11
- package/package.json +2 -2
- package/src/bridge/bridgePopup.mjs +28 -1
- package/src/bridge/localAddress.mjs +43 -5
- package/src/bridge/relayHub.mjs +31 -9
- package/src/cli.mjs +229 -0
- package/src/commandProtocol.mjs +126 -0
- package/src/errors.mjs +80 -1
- package/src/helpers.mjs +1 -1
- package/src/pairWait.mjs +34 -0
- package/src/prompt/errorHints.mjs +21 -4
- package/src/prompt/guide.mjs +4 -4
- package/src/prompt/promptSession.mjs +2 -0
- package/src/relay.mjs +8 -5
- package/src/remote/config.mjs +177 -0
- package/src/remote/httpFallback.mjs +289 -0
- package/src/remote/login.mjs +192 -0
- package/src/remote/logout.mjs +67 -0
- package/src/remote/session.mjs +502 -0
- package/src/remote/tokenStore.mjs +109 -0
- package/src/server.mjs +52 -23
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Command protocol shared by the localhost agent relay and the server relay.
|
|
3
|
+
*
|
|
4
|
+
* This is the frame around one bridge call. It is not `window.surfcad.version`
|
|
5
|
+
* (the in-page envelope) and not the `v` on prompt messages. Pairing and
|
|
6
|
+
* prompt frames stay on their own `type` names in `relayMessages.mjs`.
|
|
7
|
+
*
|
|
8
|
+
* A frame we write always carries `v`. A frame we read may omit `v`; that
|
|
9
|
+
* means version 1, so a peer from before this field still works on the
|
|
10
|
+
* localhost relay. Any other `v` is not this protocol.
|
|
11
|
+
*
|
|
12
|
+
* The server relay's handshake is stricter: `checkAgentHandshakeVersion`
|
|
13
|
+
* requires an explicit `v`. A missing or older `v` is too old for that
|
|
14
|
+
* handshake. Local reads are unchanged.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export const AGENT_PROTOCOL_VERSION = 1;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @typedef {{ v: number, id: string | number, command: string, args: unknown }} CommandRequest
|
|
21
|
+
* @typedef {{
|
|
22
|
+
* v: number,
|
|
23
|
+
* id: string | number,
|
|
24
|
+
* ok: true,
|
|
25
|
+
* result: unknown,
|
|
26
|
+
* } | {
|
|
27
|
+
* v: number,
|
|
28
|
+
* id: string | number,
|
|
29
|
+
* ok: false,
|
|
30
|
+
* error?: unknown,
|
|
31
|
+
* }} CommandResponse
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {unknown} msg
|
|
36
|
+
* @returns {boolean}
|
|
37
|
+
*/
|
|
38
|
+
export function isSupportedProtocolVersion(msg) {
|
|
39
|
+
if (!msg || typeof msg !== 'object') return false;
|
|
40
|
+
const version = /** @type {{ v?: unknown }} */ (msg).v;
|
|
41
|
+
return version == null || version === AGENT_PROTOCOL_VERSION;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @param {{ id?: string | number, command: string, args?: unknown }} fields
|
|
46
|
+
* @returns {CommandRequest}
|
|
47
|
+
*/
|
|
48
|
+
export function commandRequest(fields) {
|
|
49
|
+
return {
|
|
50
|
+
v: AGENT_PROTOCOL_VERSION,
|
|
51
|
+
id: fields.id,
|
|
52
|
+
command: fields.command,
|
|
53
|
+
args: fields.args == null ? {} : fields.args,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @param {{ id?: string | number, ok: boolean, result?: unknown, error?: unknown }} fields
|
|
59
|
+
* @returns {CommandResponse}
|
|
60
|
+
*/
|
|
61
|
+
export function commandResponse(fields) {
|
|
62
|
+
if (fields.ok === true) {
|
|
63
|
+
return { v: AGENT_PROTOCOL_VERSION, id: fields.id, ok: true, result: fields.result };
|
|
64
|
+
}
|
|
65
|
+
const frame = { v: AGENT_PROTOCOL_VERSION, id: fields.id, ok: false };
|
|
66
|
+
if (fields.error !== undefined) frame.error = fields.error;
|
|
67
|
+
return frame;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* A command request: a string `command`, not a `pair` control frame, at a
|
|
72
|
+
* supported protocol version. Args that are not an object become `{}`.
|
|
73
|
+
* @param {unknown} msg
|
|
74
|
+
* @returns {CommandRequest | null}
|
|
75
|
+
*/
|
|
76
|
+
export function readCommandRequest(msg) {
|
|
77
|
+
if (!isSupportedProtocolVersion(msg)) return null;
|
|
78
|
+
const frame = /** @type {{ type?: unknown, command?: unknown, id?: string | number, args?: unknown, v?: unknown }} */ (msg);
|
|
79
|
+
if (frame.type === 'pair') return null;
|
|
80
|
+
if (typeof frame.command !== 'string') return null;
|
|
81
|
+
return {
|
|
82
|
+
v: frame.v == null ? AGENT_PROTOCOL_VERSION : /** @type {number} */ (frame.v),
|
|
83
|
+
id: frame.id,
|
|
84
|
+
command: frame.command,
|
|
85
|
+
args: frame.args && typeof frame.args === 'object' ? frame.args : {},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* A command response: an own `ok` field, not a `pair` control frame, at a
|
|
91
|
+
* supported protocol version. `ok` other than `true` is a failure.
|
|
92
|
+
* @param {unknown} msg
|
|
93
|
+
* @returns {CommandResponse | null}
|
|
94
|
+
*/
|
|
95
|
+
export function readCommandResponse(msg) {
|
|
96
|
+
if (!isSupportedProtocolVersion(msg)) return null;
|
|
97
|
+
const frame = /** @type {{ type?: unknown, ok?: unknown, id?: string | number, result?: unknown, error?: unknown, v?: unknown }} */ (msg);
|
|
98
|
+
if (frame.type === 'pair') return null;
|
|
99
|
+
if (!Object.prototype.hasOwnProperty.call(frame, 'ok')) return null;
|
|
100
|
+
const version = frame.v == null ? AGENT_PROTOCOL_VERSION : /** @type {number} */ (frame.v);
|
|
101
|
+
if (frame.ok === true) {
|
|
102
|
+
return { v: version, id: frame.id, ok: true, result: frame.result };
|
|
103
|
+
}
|
|
104
|
+
const failure = { v: version, id: frame.id, ok: false };
|
|
105
|
+
if (frame.error !== undefined) failure.error = frame.error;
|
|
106
|
+
return failure;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Shown when a server-relay client speaks a protocol older than this one. */
|
|
110
|
+
export const AGENT_HANDSHAKE_UPDATE_MESSAGE = 'please update surfcad-mcp';
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Server handshake version. Unlike `readCommandRequest`, a missing `v` is
|
|
114
|
+
* too old. `v` above {@link AGENT_PROTOCOL_VERSION} is a different protocol.
|
|
115
|
+
* @param {unknown} version
|
|
116
|
+
* @returns {{ ok: true, v: number } | { ok: false, error: string }}
|
|
117
|
+
*/
|
|
118
|
+
export function checkAgentHandshakeVersion(version) {
|
|
119
|
+
if (typeof version !== 'number' || !Number.isFinite(version) || version < AGENT_PROTOCOL_VERSION) {
|
|
120
|
+
return { ok: false, error: AGENT_HANDSHAKE_UPDATE_MESSAGE };
|
|
121
|
+
}
|
|
122
|
+
if (version !== AGENT_PROTOCOL_VERSION) {
|
|
123
|
+
return { ok: false, error: `Unsupported protocol version: ${version}` };
|
|
124
|
+
}
|
|
125
|
+
return { ok: true, v: version };
|
|
126
|
+
}
|
package/src/errors.mjs
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
import { AGENT_HANDSHAKE_UPDATE_MESSAGE } from './commandProtocol.mjs';
|
|
2
|
+
|
|
1
3
|
export const RECONNECT_HINT = 'Open SurfCAD in Chrome and keep the tab open; it will reconnect.';
|
|
2
4
|
|
|
5
|
+
export const LOGIN_AGAIN_MESSAGE = 'This agent login is no longer valid. Run npx surfcad-mcp login again.';
|
|
6
|
+
|
|
3
7
|
/**
|
|
4
8
|
* @param {{ code?: string, message?: string, details?: unknown, hint?: string, retryable?: boolean }} err
|
|
5
9
|
*/
|
|
@@ -40,5 +44,80 @@ export function pairPendingError() {
|
|
|
40
44
|
}
|
|
41
45
|
|
|
42
46
|
export function pairingEnvHint() {
|
|
43
|
-
return 'Copy the
|
|
47
|
+
return 'Copy the 8-character code from SurfCAD → Local agent → Show pairing code.';
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function tabAsleepError() {
|
|
51
|
+
return Object.assign(new Error('SurfCAD tab is asleep'), {
|
|
52
|
+
code: 'tab_asleep',
|
|
53
|
+
hint: 'Open SurfCAD in Chrome and keep that tab open, then retry this call.',
|
|
54
|
+
retryable: true,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function tooManyPendingError() {
|
|
59
|
+
return Object.assign(new Error('Too many commands are waiting'), {
|
|
60
|
+
code: 'too_many_pending',
|
|
61
|
+
hint: 'Wait for the SurfCAD tab to finish the commands already in flight, then retry.',
|
|
62
|
+
retryable: true,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function tokenRevokedError() {
|
|
67
|
+
return Object.assign(new Error(LOGIN_AGAIN_MESSAGE), {
|
|
68
|
+
code: 'token_revoked',
|
|
69
|
+
hint: 'Run npx surfcad-mcp login and approve the new code in SurfCAD.',
|
|
70
|
+
retryable: false,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* @param {string} [message]
|
|
76
|
+
*/
|
|
77
|
+
export function clientUpdateError(message = AGENT_HANDSHAKE_UPDATE_MESSAGE) {
|
|
78
|
+
const text = typeof message === 'string' && message.includes(AGENT_HANDSHAKE_UPDATE_MESSAGE)
|
|
79
|
+
? AGENT_HANDSHAKE_UPDATE_MESSAGE
|
|
80
|
+
: (message || AGENT_HANDSHAKE_UPDATE_MESSAGE);
|
|
81
|
+
return Object.assign(new Error(text), {
|
|
82
|
+
code: 'client_update_required',
|
|
83
|
+
hint: 'This surfcad-mcp is too old for the agent server. Update the package, then run npx surfcad-mcp login again.',
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Map a server-relay command error onto a clear Error. Leaves other errors alone.
|
|
89
|
+
* @param {unknown} error
|
|
90
|
+
*/
|
|
91
|
+
export function asRemoteError(error) {
|
|
92
|
+
if (error instanceof Error) {
|
|
93
|
+
const code = /** @type {Error & { code?: string }} */ (error).code;
|
|
94
|
+
if (
|
|
95
|
+
code === 'tab_asleep'
|
|
96
|
+
|| code === 'too_many_pending'
|
|
97
|
+
|| code === 'token_revoked'
|
|
98
|
+
|| code === 'client_update_required'
|
|
99
|
+
) return error;
|
|
100
|
+
}
|
|
101
|
+
const record = error && typeof error === 'object'
|
|
102
|
+
? /** @type {{ code?: unknown, message?: unknown }} */ (error)
|
|
103
|
+
: {};
|
|
104
|
+
const code = typeof record.code === 'string' ? record.code : (typeof error === 'string' ? error : '');
|
|
105
|
+
const message = typeof record.message === 'string'
|
|
106
|
+
? record.message
|
|
107
|
+
: (typeof error === 'string' ? error : '');
|
|
108
|
+
if (code === 'tab_asleep' || message === 'SurfCAD tab is asleep') return tabAsleepError();
|
|
109
|
+
if (code === 'too_many_pending' || message === 'Too many commands are waiting') return tooManyPendingError();
|
|
110
|
+
if (code === 'token_revoked' || code === 'unauthorized' || code === '4001') return tokenRevokedError();
|
|
111
|
+
if (
|
|
112
|
+
code === 'client_update_required'
|
|
113
|
+
|| code === AGENT_HANDSHAKE_UPDATE_MESSAGE
|
|
114
|
+
|| message === AGENT_HANDSHAKE_UPDATE_MESSAGE
|
|
115
|
+
|| message.includes(AGENT_HANDSHAKE_UPDATE_MESSAGE)
|
|
116
|
+
) {
|
|
117
|
+
return clientUpdateError(message || code);
|
|
118
|
+
}
|
|
119
|
+
if (error instanceof Error) return error;
|
|
120
|
+
return Object.assign(new Error(message || 'Bridge call failed'), {
|
|
121
|
+
code: code || 'bridge_error',
|
|
122
|
+
});
|
|
44
123
|
}
|
package/src/helpers.mjs
CHANGED
|
@@ -23,7 +23,7 @@ export const HELPER_GROUPS = Object.freeze({
|
|
|
23
23
|
blocks: ['roundedBox', 'tube', 'rectTube', 'hexPrism', 'sheetMetalSolid'],
|
|
24
24
|
shapes: ['makeCrossSection', 'solveContour', 'profileCircle', 'profileRectangle', 'profilePolygon', 'makeExtrude', 'makeRevolve', 'makeLoft', 'loft', 'sweep', 'sweepPoints', 'makeSweepPath', 'rotateContour', 'offsetPlaneFrame'],
|
|
25
25
|
build: ['cut', 'hollow', 'shell', 'hole', 'holeSpan', 'cboreHole', 'cskHole', 'clearanceHole', 'tapDrillHole', 'holePattern', 'holesOnContour', 'booleanBodies', 'externalBody', 'addDraft', 'draftFaces', 'moveFace', 'deleteFace'],
|
|
26
|
-
polish: ['filletEdges', 'chamferEdges', 'filletAlongPath', 'convexEdges', 'concaveEdges', 'signedFeatureEdges', 'edge', 'edgesBetween', 'boundaryEdges'],
|
|
26
|
+
polish: ['filletEdges', 'chamferEdges', 'filletAlongPath', 'edgesNamed', 'convexEdges', 'concaveEdges', 'signedFeatureEdges', 'edge', 'edgesBetween', 'boundaryEdges'],
|
|
27
27
|
place: ['move', 'rotateAbout', 'center', 'align', 'mirror', 'array3D', 'polarArray', 'patternOnPoints', 'getDimensions'],
|
|
28
28
|
faces: ['faceNames', 'facesNamed', 'edgesOf', 'surfaceOf', 'facesByNormal', 'planarFaceAt', 'edgesByOrientation', 'workplaneFromFace', 'placeInFrame', 'transformByFrame', 'placeOnFace'],
|
|
29
29
|
fasteners: ['fastenerClearanceDia', 'fastenerTapDrillDia', 'fastenerMajorDia', 'listFastenerSizes', 'resolveFastenerSize'],
|
package/src/pairWait.mjs
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { pairPendingError } from './errors.mjs';
|
|
2
|
+
|
|
3
|
+
/** Sentinel the pairing wait resolves with when the user has not clicked Allow in time. */
|
|
4
|
+
const PAIR_WAIT_TIMED_OUT = Symbol('pair_wait_timed_out');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Wait up to `waitMs` for a pairing attempt. Past that it is `pair_pending`:
|
|
8
|
+
* the attempt keeps running in the background and the caller retries.
|
|
9
|
+
*
|
|
10
|
+
* The timer used to resolve the timeout promise with itself, which is a
|
|
11
|
+
* TypeError ("Chaining cycle detected for promise"): every pairing that did
|
|
12
|
+
* not complete in time (an old tab that never answers, status before Allow
|
|
13
|
+
* with a code in the env) surfaced as that message instead of pair_pending
|
|
14
|
+
* (MVP 3 B4). A plain sentinel now marks the timeout.
|
|
15
|
+
*
|
|
16
|
+
* @template T
|
|
17
|
+
* @param {Promise<T>} attempt
|
|
18
|
+
* @param {number} waitMs
|
|
19
|
+
* @returns {Promise<T>}
|
|
20
|
+
*/
|
|
21
|
+
export async function waitForPairing(attempt, waitMs) {
|
|
22
|
+
attempt.catch(() => {});
|
|
23
|
+
let timer;
|
|
24
|
+
const timeout = new Promise((resolve) => {
|
|
25
|
+
timer = setTimeout(() => resolve(PAIR_WAIT_TIMED_OUT), waitMs);
|
|
26
|
+
});
|
|
27
|
+
try {
|
|
28
|
+
const outcome = await Promise.race([attempt, timeout]);
|
|
29
|
+
if (outcome === PAIR_WAIT_TIMED_OUT) throw pairPendingError();
|
|
30
|
+
return outcome;
|
|
31
|
+
} finally {
|
|
32
|
+
clearTimeout(timer);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -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
|
|
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.';
|
|
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
|
|
|
@@ -45,6 +45,13 @@ export const ERROR_HINTS = Object.freeze({
|
|
|
45
45
|
unknown_entity: { hint: 'The sketch entity id is not in the open contour: list_sketch_entities {} and use an id from it (p0, e0, a0, ...).' },
|
|
46
46
|
no_body: { hint: 'Name the body: body_index or at from list_bodies {}, face or face_id from list_faces, or select a face and pass use_selection: true.' },
|
|
47
47
|
no_mesh: { hint: 'No solid is shown yet: insert a block (insert_cube, insert_cylinder, ...) or run {} the part, then call again.' },
|
|
48
|
+
quote_failed: { hint: 'The molding quote service did not answer: retry mold_quote once. The part is unchanged and nothing was ordered.' },
|
|
49
|
+
lead_failed: { hint: 'The molding request did not go through: retry mold_request_firm_quote or mold_request_human_review once. Nothing was charged.' },
|
|
50
|
+
sign_in: { hint: 'Sign in, then retry mold_request_firm_quote or mold_request_human_review. Nothing was saved.' },
|
|
51
|
+
unknown_partner: { hint: 'That public label is not an active molding partner: mold_quote, then pass an anonLabel from vendors.' },
|
|
52
|
+
no_lead: { hint: 'Request a human review with mold_request_human_review before mold_pay_human_review. Nothing was charged.' },
|
|
53
|
+
review_unavailable: { hint: 'Human review checkout is not configured. Do not retry in a loop, and do not invent a card charge.' },
|
|
54
|
+
rate_limited: { hint: 'Too many requests in a short window: wait, then retry the same call once. Do not loop.' },
|
|
48
55
|
not_picked: { hint: 'pick_next { remove: true } named keys that are not picked: pick_next with no remove to see the live picks, or pick_clear {}.' },
|
|
49
56
|
empty_pick: { hint: 'The card needs at least one pick: pick_next { keys } before pick_done, or pick_cancel {}.' },
|
|
50
57
|
pick_count: { hint: 'Fewer picks than the card\'s minimum: pick_next more keys, then pick_done again.' },
|
|
@@ -107,6 +114,10 @@ export const ERROR_HINTS = Object.freeze({
|
|
|
107
114
|
hint: 'Place it with joint_create (one call creates the joint and solves placement). Fix a base part with type fixed first.',
|
|
108
115
|
guide: 'A part that touches or attaches to another part belongs in a joint. joint_create { type, picks } writes the joint and solves the placement in one call. Ground the base with type fixed and one whole-part pick { part_id }, then mate each touching part with two picks from list_faces (coincident, concentric, distance, and the other types). part_set_transform is only for a part that touches nothing. The warning does not block the call: the placement was written. A single-part document does not warn, and neither does the base part once it has a fixed joint. parts and status list the ids still in no joint as unjointedParts. Bodies, patterns, and insert_move inside one part are not assembly parts and do not warn.',
|
|
109
116
|
},
|
|
117
|
+
joint_broken: {
|
|
118
|
+
hint: 'A joint stopped solving after this call (its face moved or vanished, or it now conflicts): list_joints {} shows each joint with status and reason; fix the part, joint_edit it to new picks, or joint_delete it.',
|
|
119
|
+
guide: 'joint_broken is a warning on a successful result: the part edit or joint commit was written, and the solve that re-runs after every part run left one or more joints failing that were not failing before. status.jointFailures { count, ids } and list_joints {} (id, name, type, status ok | broken | conflict, reason such as "Face not found on Shaft", parts, picks) show the standing state at any time. A broken joint keeps the last good placement and is left out of the solve. Fix it by editing the part so the referenced face comes back, by joint_edit { joint_id } with picks from list_faces on the new mesh, or by joint_delete { joint_id }. The joints strip shows the same joints as red chips.',
|
|
120
|
+
},
|
|
110
121
|
no_joint_card: { hint: 'The joint card is closed: joint_open {} first, then joint_pick / joint_set_params / joint_commit.' },
|
|
111
122
|
no_joint_edit: { hint: 'No joint is open for editing: joint_open {} for a new joint or joint_edit { joint_id } for an existing one.' },
|
|
112
123
|
joints_unavailable: { hint: 'The joint card could not open because another card or session is open: close it (cancel_feature, sketch_cancel, sheet_exit) and call joint_create again.' },
|
|
@@ -130,6 +141,7 @@ export const ERROR_HINTS = Object.freeze({
|
|
|
130
141
|
real_repo_blocked: { hint: 'This session cannot get consent for a real-repo write: tell the user and stop; do not loop.', guide: CONSENT_GUIDE },
|
|
131
142
|
confirm_required: { hint: 'Nothing changed: ask the user (details lists what the change touches), and only then retry with confirm: true.', guide: CONSENT_GUIDE },
|
|
132
143
|
pending_save: { hint: 'The write is planned offline: ask the user to Save again when online; nothing more to do now.' },
|
|
144
|
+
unknown_save: { hint: 'No save with that id is running or recent in this tab: a git_save that finished within its budget answered its result directly; call git_save { message } again if the save is still wanted.' },
|
|
133
145
|
upgrade_required: { hint: 'Legacy vault: after the user agrees, git_upgrade_vault { confirm: true }, then git_save again.' },
|
|
134
146
|
upgrade_unavailable: { hint: 'The vault cannot be upgraded from here (message says why): tell the user and stop.' },
|
|
135
147
|
conflict: { hint: 'A remote edit overlaps this save: git_behind_resolve { action: "reload" | "branch", confirm: true } after the user chooses, or git_force_overwrite with confirm: true.' },
|
|
@@ -160,12 +172,17 @@ export const ERROR_HINTS = Object.freeze({
|
|
|
160
172
|
unknown_topic: { hint: 'guide {} lists the topics; error topics are errors.<code>.' },
|
|
161
173
|
// Pairing and prompts (MCP side)
|
|
162
174
|
not_paired: { hint: 'pair { code } with the code from SurfCAD → Local agent → Show pairing code, then the user clicks Allow; or set SURFCAD_PAIRING_CODE.', guide: PAIRING_GUIDE },
|
|
163
|
-
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.', guide: PAIRING_GUIDE },
|
|
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 },
|
|
164
176
|
pair_rejected: { hint: 'The user clicked Deny: ask them before calling pair again.', guide: PAIRING_GUIDE },
|
|
165
177
|
pair_cancelled: { hint: 'The pairing attempt was cancelled: pair { code } again when the user is ready.', guide: PAIRING_GUIDE },
|
|
166
|
-
pair_failed: { hint: 'Pairing failed (message): check the code (
|
|
178
|
+
pair_failed: { hint: 'Pairing failed (message): check the code (8 characters, from the open tab) and that the tab shows it, then pair again.', guide: PAIRING_GUIDE },
|
|
167
179
|
pairing_lost: { hint: '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.', guide: PAIRING_GUIDE },
|
|
168
|
-
bad_pairing_code: { hint: 'pair { code: "
|
|
180
|
+
bad_pairing_code: { hint: 'pair { code: "........" } with the 8-character code from SurfCAD → Local agent → Show pairing code.', guide: PAIRING_GUIDE },
|
|
181
|
+
tab_asleep: { hint: 'Open SurfCAD in Chrome and keep that tab open, then retry this call.' },
|
|
182
|
+
too_many_pending: { hint: 'Wait for the SurfCAD tab to finish the commands already in flight, then retry.' },
|
|
183
|
+
token_revoked: { hint: 'Run npx surfcad-mcp login and approve the new code in SurfCAD.' },
|
|
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: 'This session is on the HTTPS fallback because WebSocket was blocked. In-viewer prompts need the WebSocket; retry where the agent server allows wss.' },
|
|
169
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 },
|
|
170
187
|
bridge_error: { hint: 'The tab refused the call without a code: status {} and retry once; tell the user if it repeats.' },
|
|
171
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 },
|
package/src/prompt/guide.mjs
CHANGED
|
@@ -70,7 +70,7 @@ const SELECTION = `Selection. Faces and edges are addressed by keys that survive
|
|
|
70
70
|
|
|
71
71
|
Faces. list_faces { part_id?, filter?, page? } returns one row per face a viewport click selects, all bodies: id (f0, f1, ...), type (planar | cylindrical | curved), center, normal, axis and radius for cylinders, area, and key { at, n, area, src?, ord? } (the same fingerprint the viewport uses). frame is "local": center, normal, axis and key.at are the part's own coordinates, including on a placed part, and they match select_faces. Compose with part_get_transform when another part does not share that frame. The whole list on a detailed part is 100 KB or more: filter it in the tab. filter { kind, normalWithin: { n, deg }, minArea, maxArea, bbox: { min, max } } keeps the rows that match every given field. bbox keeps a face whose bounds overlap the box, including a large face whose center is outside it. page { offset, limit } returns one slice; omitting page returns the first 100 faces. The result carries total (after the filter), returned, offset, limit, and nextOffset when another page remains (pass offset: nextOffset). The top faces: { kind: "planar", normalWithin: { n: [0, 0, 1], deg: 5 } }. Hole walls: { kind: "cylindrical", maxArea }. Pass face_id together with its key to joint_pick so a stale id answers unknown_face instead of picking another face.
|
|
72
72
|
|
|
73
|
-
Edges. list_feature_edges
|
|
73
|
+
Edges. list_feature_edges lists every edge by name, the pair of stamped faces it lies between ("plate.top~boss.side", "[k]" for one chain of a pair that meets twice, "*" glob), with the two faces' list_faces keys; that name is the stable reference (select_edges { names }, pick_next { keys }, edgesNamed(part, name) in the script) and survives edits that keep the faces. list_edges gives raw mesh edges, also with name. Legacy e0, e1 ids still resolve but renumber after edits. Both set frame to "local" (midpoints in the same part frame as list_faces) and take filter { between: [faceKeyA, faceKeyB], minLength, maxLength, bbox } and page.
|
|
74
74
|
|
|
75
75
|
Picking. select_faces { keys: [...] } and select_edges { keys } set the viewport selection; select_clear {} clears faces, edges and contour picks. pick_begin → pick_next { keys: ["e3"] } → pick_done { accept: true } drives a card's pick session; a keys item is a grouped edge id (eN), a face id (fN), a face key, or an edge face pair { faceKeyA, faceKeyB }.
|
|
76
76
|
|
|
@@ -84,7 +84,7 @@ const PAINT = `Paint. Colours live on the assembly document (a colors map keyed
|
|
|
84
84
|
|
|
85
85
|
Sequence: set_active_part { part_id } → paint_open {} → paint_set_color { color: "#rrggbb" } (hex is an alias) → paint_part {} for the whole part, or paint_faces { keys: [...] } with keys from list_faces → paint_confirm {}. paint_undo {} steps back inside the session, paint_clear {} removes the part's colours, paint_cancel {} / paint_close {} leave without writing.
|
|
86
86
|
|
|
87
|
-
paint_open is safe straight after create_part or set_active_part: it waits up to 1.5 s for the viewport to take paint mode.
|
|
87
|
+
paint_open is safe straight after create_part or set_active_part: it waits up to 1.5 s for the viewport to take paint mode. While an in-viewer prompt is being worked it opens headless (the session runs with no card; result headless: true), so a paint during a prompt applies like any other. Past the wait it answers not_ready with details.reason (mode_not_ready) and details.retryable: true; call paint_open again.
|
|
88
88
|
|
|
89
89
|
Paint writes the working copy only; nothing reaches the vault until git_save.`;
|
|
90
90
|
|
|
@@ -120,13 +120,13 @@ Instances. insert_part { part_id, instance: true, position? } adds another place
|
|
|
120
120
|
|
|
121
121
|
Placement. ${JOINT_PLACEMENT_GUIDANCE} part_get_transform { part_id } reads a rigid placement: translation in mm, rotation as intrinsic XYZ Euler degrees. A placed part's features, previews and picks are in its own frame. list_faces, list_edges and list_feature_edges set frame to "local" (centers and edge midpoints are part-local, not world); compose them with part_get_transform when another part does not share that frame. part_set_transform { part_id, position?, rotation? } writes that placement in one assembly undo step and is only for a part that touches nothing. create_part and insert_part { position } are a rough block-out. In an assembly of two or more parts, part_set_transform, or create_part / insert_part with a position, returns warning { code: "unjointed_part", part_id, hint } when that part is in no joint. The call still succeeds. A single-part document does not warn, and neither does the base part once it has a fixed joint.
|
|
122
122
|
|
|
123
|
-
Joints. joint_create { type, picks } is the call. type is coincident, parallel, perpendicular, distance, angle, concentric, symmetric or fixed (planar is coincident). picks come from list_faces: face_id with its key, a cylindrical face as an axis, or { part_id } alone for a whole-part pick. A face_id selects that face, including on a pattern or an instance, and is never an ambiguous axis. A real tie (two different axes) is joint_unsolvable and details.candidates lists each axis id, origin, direction and radius. joint_delete { joint_id } removes one joint and is one undo step. Fixed takes one pick; every other type takes two, one per part. Distance is mm, angle is degrees.
|
|
123
|
+
Joints. joint_create { type, picks } is the call. type is coincident, parallel, perpendicular, distance, angle, concentric, symmetric or fixed (planar is coincident). picks come from list_faces: face_id with its key, a cylindrical face as an axis, or { part_id } alone for a whole-part pick. A face_id selects that face, including on a pattern or an instance, and is never an ambiguous axis. A real tie (two different axes) is joint_unsolvable and details.candidates lists each axis id, origin, direction and radius. joint_delete { joint_id } removes one joint and is one undo step. Fixed takes one pick; every other type takes two, one per part. Distance is mm, angle is degrees. list_joints {} lists every joint with status (ok | broken | conflict), reason and picks; status.jointFailures { count, ids } is the short form. A joint goes broken when a later part run no longer has its face (a remesh, a moved or deleted feature) and conflict when it cannot hold with the others; the solve re-runs after every part run, so the strip's red chips and this list agree. A part edit or joint commit that leaves a joint failing returns warning { code: "joint_broken", joints, hint } and still succeeds.
|
|
124
124
|
|
|
125
125
|
The Joints card is the advanced path for the same write: joint_open {} → joint_pick { part_id, face_id?, key? } (a whole part, a face with its key, or an edge) → joint_set_params { type, value?, sense?, opposed? } → joint_commit {}. Fixed takes one pick and no second reference: joint_pick { part_id } alone suggests fixed; a face pick needs joint_set_params { type: "fixed" }.
|
|
126
126
|
|
|
127
127
|
Hardware. One part per unique fastener type, patterned to every place it goes: list_faces on the fastened part (cylindrical rows, filter by radius) gives each hole's center and axis in that part's frame (frame is "local"); compose with part_get_transform when the fastener does not share it. insert_pattern_points { points: [{ at, axis }, ...], up } on the fastener part places one instance per hole; insert_array3_d covers a grid. A bolt circle of holes is insert_polar_array { count, boltCircleRadius, axis, boreRadius, boreHeight } on the part being drilled (boreRadius greater than 0 subtracts the holes and does not copy the body; boreRadius 0 copies it; boltCircleRadius defaults to 0, on the axis). Do not record a bolt-circle hole pattern as a FEATURE-GAP.
|
|
128
128
|
|
|
129
|
-
Saving. Working-copy tools never commit. git_save { message } is the one vault write; it answers consent_pending while the Allow dialog is up (retry the same call after the user clicks Allow), clean when nothing changed, and passes through pending_save, upgrade_required, conflict and repo-moved unchanged.`;
|
|
129
|
+
Saving. Working-copy tools never commit. git_save { message } is the one vault write; it answers consent_pending while the Allow dialog is up (retry the same call after the user clicks Allow), clean when nothing changed, and passes through pending_save, upgrade_required, conflict and repo-moved unchanged. A save is many GitHub round trips: when it is still running after about 20 s, git_save answers { status: "running", saveId } and keeps going; poll git_save_status { save_id } until it answers the save result.`;
|
|
130
130
|
|
|
131
131
|
/** Topic name → one-line summary and the text. Order is the listing order. */
|
|
132
132
|
export const GUIDE_TOPICS = Object.freeze({
|
package/src/relay.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { WebSocket } from 'ws';
|
|
2
|
+
import { commandRequest, readCommandResponse } from './commandProtocol.mjs';
|
|
2
3
|
import { connectPeer } from './nodeClient.mjs';
|
|
3
4
|
import { PAIR_MSG } from './relayMessages.mjs';
|
|
4
5
|
import { redactToken } from './bridge/relayHub.mjs';
|
|
@@ -282,12 +283,14 @@ export class RelaySession {
|
|
|
282
283
|
const waiter = id ? this.#pending.get(id) : undefined;
|
|
283
284
|
if (waiter) {
|
|
284
285
|
this.#pending.delete(id);
|
|
285
|
-
|
|
286
|
-
|
|
286
|
+
const response = readCommandResponse(msg);
|
|
287
|
+
if (response?.ok === true) {
|
|
288
|
+
waiter.resolve(response.result);
|
|
287
289
|
return;
|
|
288
290
|
}
|
|
289
|
-
const
|
|
290
|
-
|
|
291
|
+
const rawError = response?.error ?? msg.error;
|
|
292
|
+
const error = rawError && typeof rawError === 'object'
|
|
293
|
+
? rawError
|
|
291
294
|
: { code: 'bridge_error', message: 'Command refused' };
|
|
292
295
|
// hint and retryable ride along when the tab sent them (the server
|
|
293
296
|
// fills in a hint from its own table when it did not).
|
|
@@ -397,7 +400,7 @@ export class RelaySession {
|
|
|
397
400
|
return new Promise((resolve, reject) => {
|
|
398
401
|
this.#pending.set(id, { resolve, reject });
|
|
399
402
|
try {
|
|
400
|
-
ws.send(JSON.stringify({ id, command, args }));
|
|
403
|
+
ws.send(JSON.stringify(commandRequest({ id, command, args })));
|
|
401
404
|
} catch {
|
|
402
405
|
this.#lose(ws, 'send_failed');
|
|
403
406
|
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remote relay address, agent name, and local-vs-remote selection.
|
|
3
|
+
* The token never appears in these helpers.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_AGENT_SERVER = 'https://surfcad.com';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Per-user directory for the saved login. Override with
|
|
13
|
+
* SURFCAD_MCP_CONFIG_DIR (tests and unusual installs). Otherwise
|
|
14
|
+
* $XDG_CONFIG_HOME/surfcad-mcp, or ~/.config/surfcad-mcp.
|
|
15
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
16
|
+
*/
|
|
17
|
+
export function configDir(env = process.env) {
|
|
18
|
+
const override = env.SURFCAD_MCP_CONFIG_DIR;
|
|
19
|
+
if (typeof override === 'string' && override.trim()) return override.trim();
|
|
20
|
+
const xdg = env.XDG_CONFIG_HOME;
|
|
21
|
+
if (typeof xdg === 'string' && xdg.trim()) return join(xdg.trim(), 'surfcad-mcp');
|
|
22
|
+
const home = typeof env.HOME === 'string' && env.HOME.trim() ? env.HOME.trim() : homedir();
|
|
23
|
+
return join(home, '.config', 'surfcad-mcp');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
28
|
+
*/
|
|
29
|
+
export function tokenPath(env = process.env) {
|
|
30
|
+
return join(configDir(env), 'token.json');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Cleartext is only for a loopback dev server. Every other host must be https.
|
|
35
|
+
* @param {string} hostname URL.hostname (IPv6 has no brackets)
|
|
36
|
+
*/
|
|
37
|
+
function isCleartextLoopback(hostname) {
|
|
38
|
+
const host = hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
|
39
|
+
return host === 'localhost' || host === '127.0.0.1' || host === '::1';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Accept https, http, wss, or ws. Return the origin only (`https://host`).
|
|
44
|
+
* A path such as `/agent` is dropped; callers add it.
|
|
45
|
+
* `http://` and `ws://` are accepted only for localhost, 127.0.0.1, and ::1.
|
|
46
|
+
* @param {unknown} input
|
|
47
|
+
*/
|
|
48
|
+
export function normalizeServer(input) {
|
|
49
|
+
let text = String(input ?? '').trim();
|
|
50
|
+
if (!text) {
|
|
51
|
+
throw Object.assign(new Error('Server URL is empty.'), { code: 'bad_server' });
|
|
52
|
+
}
|
|
53
|
+
if (text.startsWith('wss://')) text = `https://${text.slice('wss://'.length)}`;
|
|
54
|
+
else if (text.startsWith('ws://')) text = `http://${text.slice('ws://'.length)}`;
|
|
55
|
+
else if (!/^https?:\/\//i.test(text)) text = `https://${text}`;
|
|
56
|
+
let url;
|
|
57
|
+
try {
|
|
58
|
+
url = new URL(text);
|
|
59
|
+
} catch {
|
|
60
|
+
throw Object.assign(new Error('Server URL is not a valid http(s) URL.'), { code: 'bad_server' });
|
|
61
|
+
}
|
|
62
|
+
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
|
|
63
|
+
throw Object.assign(new Error('Server URL must be http or https.'), { code: 'bad_server' });
|
|
64
|
+
}
|
|
65
|
+
if (!url.host) {
|
|
66
|
+
throw Object.assign(new Error('Server URL is missing a host.'), { code: 'bad_server' });
|
|
67
|
+
}
|
|
68
|
+
if (url.protocol === 'http:' && !isCleartextLoopback(url.hostname)) {
|
|
69
|
+
throw Object.assign(
|
|
70
|
+
new Error(`Cleartext is only allowed for localhost, 127.0.0.1, and ::1. Use https for ${url.host}.`),
|
|
71
|
+
{ code: 'bad_server' },
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
return `${url.protocol}//${url.host}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* `--server` wins, then SURFCAD_AGENT_SERVER, then the server stored with
|
|
79
|
+
* the login, then https://surfcad.com.
|
|
80
|
+
* @param {{ flag?: string, env?: NodeJS.ProcessEnv, saved?: { server?: string } | null }} [options]
|
|
81
|
+
*/
|
|
82
|
+
export function resolveServerUrl(options = {}) {
|
|
83
|
+
const env = options.env || process.env;
|
|
84
|
+
const flag = typeof options.flag === 'string' ? options.flag.trim() : '';
|
|
85
|
+
if (flag) return normalizeServer(flag);
|
|
86
|
+
const fromEnv = typeof env.SURFCAD_AGENT_SERVER === 'string' ? env.SURFCAD_AGENT_SERVER.trim() : '';
|
|
87
|
+
if (fromEnv) return normalizeServer(fromEnv);
|
|
88
|
+
const saved = options.saved && typeof options.saved.server === 'string' ? options.saved.server.trim() : '';
|
|
89
|
+
if (saved) return normalizeServer(saved);
|
|
90
|
+
return DEFAULT_AGENT_SERVER;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* @param {string} origin http(s) origin, no path
|
|
95
|
+
*/
|
|
96
|
+
export function agentUrls(origin) {
|
|
97
|
+
const base = normalizeServer(origin);
|
|
98
|
+
const url = new URL(base);
|
|
99
|
+
const wsProtocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
100
|
+
return {
|
|
101
|
+
origin: base,
|
|
102
|
+
approvalUrl: `${base}/agent`,
|
|
103
|
+
wsUrl: `${wsProtocol}//${url.host}/agent`,
|
|
104
|
+
pairUrl: `${base}/agent/pair`,
|
|
105
|
+
pollUrl: `${base}/agent/pair/poll`,
|
|
106
|
+
joinUrl: `${base}/agent/join/redeem`,
|
|
107
|
+
commandsUrl: `${base}/agent/commands`,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Name sent at login and on the hello frame.
|
|
113
|
+
* `--name`, then SURFCAD_AGENT_NAME, then the name stored at login, then
|
|
114
|
+
* the MCP client's `clientInfo.name`. Empty means the server says "an agent".
|
|
115
|
+
* `login` has no MCP client, so it never sees clientInfo.
|
|
116
|
+
* @param {{
|
|
117
|
+
* name?: string,
|
|
118
|
+
* savedName?: string,
|
|
119
|
+
* clientInfo?: { name?: string } | null,
|
|
120
|
+
* env?: NodeJS.ProcessEnv,
|
|
121
|
+
* }} [options]
|
|
122
|
+
*/
|
|
123
|
+
export function resolveAgentName(options = {}) {
|
|
124
|
+
const env = options.env || process.env;
|
|
125
|
+
const flag = typeof options.name === 'string' ? options.name.trim() : '';
|
|
126
|
+
if (flag) return flag;
|
|
127
|
+
const fromEnv = typeof env.SURFCAD_AGENT_NAME === 'string' ? env.SURFCAD_AGENT_NAME.trim() : '';
|
|
128
|
+
if (fromEnv) return fromEnv;
|
|
129
|
+
const saved = typeof options.savedName === 'string' ? options.savedName.trim() : '';
|
|
130
|
+
if (saved) return saved;
|
|
131
|
+
const fromClient = options.clientInfo && typeof options.clientInfo.name === 'string'
|
|
132
|
+
? options.clientInfo.name.trim()
|
|
133
|
+
: '';
|
|
134
|
+
return fromClient;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Loopback settings that must keep the local relay even after a login,
|
|
139
|
+
* so goldens and an existing local MCP config are not taken over.
|
|
140
|
+
* @param {NodeJS.ProcessEnv} env
|
|
141
|
+
*/
|
|
142
|
+
function explicitLocalRelay(env) {
|
|
143
|
+
const url = env.SURFCAD_AGENT_BRIDGE_WS_URL;
|
|
144
|
+
if (typeof url === 'string' && url.trim()) return true;
|
|
145
|
+
const port = env.SURFCAD_AGENT_BRIDGE_WS_PORT;
|
|
146
|
+
if (typeof port === 'string' && port.trim()) return true;
|
|
147
|
+
const code = env.SURFCAD_PAIRING_CODE;
|
|
148
|
+
if (typeof code === 'string' && code.trim()) return true;
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* First match wins:
|
|
154
|
+
* 1. `--remote` → remote
|
|
155
|
+
* 2. `--local` → local
|
|
156
|
+
* 3. an explicit loopback URL, port, or pairing code → local
|
|
157
|
+
* 4. a saved login → remote
|
|
158
|
+
* 5. local
|
|
159
|
+
* @param {{
|
|
160
|
+
* remote?: boolean,
|
|
161
|
+
* local?: boolean,
|
|
162
|
+
* loggedIn?: boolean,
|
|
163
|
+
* env?: NodeJS.ProcessEnv,
|
|
164
|
+
* }} [options]
|
|
165
|
+
* @returns {{ ok: true, mode: 'local' | 'remote' } | { ok: false, error: string }}
|
|
166
|
+
*/
|
|
167
|
+
export function selectRelayMode(options = {}) {
|
|
168
|
+
const env = options.env || process.env;
|
|
169
|
+
if (options.remote && options.local) {
|
|
170
|
+
return { ok: false, error: 'Pass either --remote or --local, not both.' };
|
|
171
|
+
}
|
|
172
|
+
if (options.remote) return { ok: true, mode: 'remote' };
|
|
173
|
+
if (options.local) return { ok: true, mode: 'local' };
|
|
174
|
+
if (explicitLocalRelay(env)) return { ok: true, mode: 'local' };
|
|
175
|
+
if (options.loggedIn) return { ok: true, mode: 'remote' };
|
|
176
|
+
return { ok: true, mode: 'local' };
|
|
177
|
+
}
|