@q-division/prism-mcp 0.0.0-stage → 0.1.1
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/LICENSE +4 -0
- package/README.md +30 -2
- package/dist/mcp-shim.cjs +1329 -0
- package/package.json +9 -4
|
@@ -0,0 +1,1329 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
9
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
20
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
21
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
22
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
23
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
24
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
25
|
+
mod
|
|
26
|
+
));
|
|
27
|
+
|
|
28
|
+
// packages/prism-client/package.json
|
|
29
|
+
var require_package = __commonJS({
|
|
30
|
+
"packages/prism-client/package.json"(exports2, module2) {
|
|
31
|
+
module2.exports = {
|
|
32
|
+
name: "@q-division/prism-mcp",
|
|
33
|
+
version: "0.1.1",
|
|
34
|
+
description: "Remote-only Prism MCP transport",
|
|
35
|
+
license: "SEE LICENSE IN LICENSE",
|
|
36
|
+
repository: { type: "git", url: "git+https://github.com/justinqpham/prism-mcp.git" },
|
|
37
|
+
publishConfig: { access: "public", registry: "https://registry.npmjs.org" },
|
|
38
|
+
bin: { prism: "dist/mcp-shim.cjs" },
|
|
39
|
+
files: ["dist/mcp-shim.cjs", "README.md"],
|
|
40
|
+
engines: { node: ">=18" }
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
// src/mcp-shim.ts
|
|
46
|
+
var path = __toESM(require("path"));
|
|
47
|
+
var fs = __toESM(require("fs"));
|
|
48
|
+
var os = __toESM(require("os"));
|
|
49
|
+
var import_crypto = require("crypto");
|
|
50
|
+
var import_http = require("http");
|
|
51
|
+
|
|
52
|
+
// src/prism-client-sign-in.ts
|
|
53
|
+
var import_node_crypto = require("node:crypto");
|
|
54
|
+
var import_node_fs = require("node:fs");
|
|
55
|
+
var import_node_http = require("node:http");
|
|
56
|
+
var import_node_path = require("node:path");
|
|
57
|
+
var import_node_child_process = require("node:child_process");
|
|
58
|
+
var import_node_os = require("node:os");
|
|
59
|
+
var origin = "https://prism-api.qdivision.one";
|
|
60
|
+
var issuer = "https://auth.qdivision.one";
|
|
61
|
+
var clientId = "https://qdivision.one/.well-known/oauth-client/prism-cli.json";
|
|
62
|
+
var resource = origin + "/session";
|
|
63
|
+
var audience = "prism";
|
|
64
|
+
var lifetime = 2592e6;
|
|
65
|
+
var random = (length) => (0, import_node_crypto.randomBytes)(length).toString("base64url");
|
|
66
|
+
var sha = (value) => (0, import_node_crypto.createHash)("sha256").update(value, "utf8").digest();
|
|
67
|
+
var canonical = (value, size) => typeof value === "string" && value.length === Math.ceil(size * 4 / 3) && /^[A-Za-z0-9_-]+$/.test(value) && Buffer.from(value, "base64url").toString("base64url") === value;
|
|
68
|
+
var record = (value, fields) => !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === fields.length && fields.every((name) => Object.hasOwn(value, name));
|
|
69
|
+
var current = (value) => typeof value === "number" && Number.isSafeInteger(value) && Date.now() < value;
|
|
70
|
+
var SignInError = class extends Error {
|
|
71
|
+
constructor(code, retryable = false) {
|
|
72
|
+
super(code);
|
|
73
|
+
this.code = code;
|
|
74
|
+
this.retryable = retryable;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
function stop(code) {
|
|
78
|
+
throw new SignInError(code);
|
|
79
|
+
}
|
|
80
|
+
async function post(path2, body, extra = {}, qdivision = false) {
|
|
81
|
+
const signal = new AbortController();
|
|
82
|
+
const timeout = setTimeout(() => signal.abort(), 8e3);
|
|
83
|
+
try {
|
|
84
|
+
const response = await fetch(path2.startsWith("https://") ? path2 : origin + path2, { method: "POST", body, headers: { "Content-Type": "application/json", ...extra }, signal: signal.signal, redirect: "error" });
|
|
85
|
+
if (qdivision && [401, 503].includes(response.status)) {
|
|
86
|
+
void response.body?.cancel().catch(() => {
|
|
87
|
+
});
|
|
88
|
+
throw new SignInError(response.status === 503 ? "qdivision_unavailable" : "qdivision_unauthorized", response.status === 503);
|
|
89
|
+
}
|
|
90
|
+
if (qdivision && response.status === 403 && !response.body) stop("qdivision_forbidden");
|
|
91
|
+
if (!response.body) stop("invalid_login_response");
|
|
92
|
+
const reader = response.body.getReader();
|
|
93
|
+
const data = [];
|
|
94
|
+
let size = 0;
|
|
95
|
+
try {
|
|
96
|
+
while (true) {
|
|
97
|
+
const item = await reader.read();
|
|
98
|
+
if (item.done) break;
|
|
99
|
+
size += item.value.byteLength;
|
|
100
|
+
if (size > 16384) stop("invalid_login_response");
|
|
101
|
+
data.push(Buffer.from(item.value));
|
|
102
|
+
}
|
|
103
|
+
} finally {
|
|
104
|
+
void reader.cancel().catch(() => {
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
let parsed;
|
|
108
|
+
try {
|
|
109
|
+
parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(data)));
|
|
110
|
+
} catch {
|
|
111
|
+
stop(qdivision && response.status === 403 ? "qdivision_forbidden" : "invalid_login_response");
|
|
112
|
+
}
|
|
113
|
+
if (!response.ok) {
|
|
114
|
+
if (qdivision && response.status === 403) throw new SignInError(parsed?.code === "account_not_found" || parsed?.error === "account_not_found" ? "account_not_found" : "qdivision_forbidden");
|
|
115
|
+
const code = typeof parsed?.code === "string" && /^[a-z_]{1,64}$/.test(parsed.code) ? parsed.code : "invalid_login_response";
|
|
116
|
+
throw new SignInError(code, response.status === 503);
|
|
117
|
+
}
|
|
118
|
+
return parsed;
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (error instanceof SignInError) throw error;
|
|
121
|
+
throw new SignInError(qdivision ? "qdivision_network_error" : "auth_temporarily_unavailable", true);
|
|
122
|
+
} finally {
|
|
123
|
+
clearTimeout(timeout);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function replaceCredential(authPath, config) {
|
|
127
|
+
const dir = (0, import_node_path.dirname)(authPath);
|
|
128
|
+
try {
|
|
129
|
+
(0, import_node_fs.mkdirSync)(dir, { mode: 448 });
|
|
130
|
+
} catch (error) {
|
|
131
|
+
if (error?.code !== "EEXIST") throw error;
|
|
132
|
+
}
|
|
133
|
+
const stat = (0, import_node_fs.lstatSync)(dir);
|
|
134
|
+
if (!stat.isDirectory() || stat.mode & 18 || process.getuid && stat.uid !== process.getuid()) stop("auth_credential_unavailable");
|
|
135
|
+
const temporary = (0, import_node_path.join)(dir, ".auth-" + random(24));
|
|
136
|
+
const fd = (0, import_node_fs.openSync)(temporary, "wx", 384);
|
|
137
|
+
try {
|
|
138
|
+
try {
|
|
139
|
+
(0, import_node_fs.writeFileSync)(fd, JSON.stringify(config) + "\n", "utf8");
|
|
140
|
+
(0, import_node_fs.fsyncSync)(fd);
|
|
141
|
+
} finally {
|
|
142
|
+
(0, import_node_fs.closeSync)(fd);
|
|
143
|
+
}
|
|
144
|
+
(0, import_node_fs.renameSync)(temporary, authPath);
|
|
145
|
+
} finally {
|
|
146
|
+
try {
|
|
147
|
+
(0, import_node_fs.unlinkSync)(temporary);
|
|
148
|
+
} catch {
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
var machineNameMaxChars = 80;
|
|
153
|
+
var machineNameMaxBytes = 256;
|
|
154
|
+
function normalizeMachineName(value) {
|
|
155
|
+
if (typeof value !== "string") return "";
|
|
156
|
+
const text = value.split(/\s+/).join(" ").replace(new RegExp("\\p{C}", "gu"), "").split(/\s+/).join(" ").trim();
|
|
157
|
+
let result = "", bytes = 0, count = 0;
|
|
158
|
+
for (const char of text) {
|
|
159
|
+
const size = Buffer.byteLength(char, "utf8");
|
|
160
|
+
if (++count > machineNameMaxChars || bytes + size > machineNameMaxBytes) break;
|
|
161
|
+
result += char;
|
|
162
|
+
bytes += size;
|
|
163
|
+
}
|
|
164
|
+
return result.trim();
|
|
165
|
+
}
|
|
166
|
+
async function machineName() {
|
|
167
|
+
try {
|
|
168
|
+
let name = "";
|
|
169
|
+
if (process.platform === "darwin") {
|
|
170
|
+
name = await new Promise((resolve) => {
|
|
171
|
+
try {
|
|
172
|
+
(0, import_node_child_process.execFile)("/usr/sbin/scutil", ["--get", "ComputerName"], { timeout: 3e3, encoding: "utf8" }, (error, stdout) => resolve(error ? "" : String(stdout)));
|
|
173
|
+
} catch {
|
|
174
|
+
resolve("");
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
if (!normalizeMachineName(name)) {
|
|
179
|
+
try {
|
|
180
|
+
name = (0, import_node_os.hostname)();
|
|
181
|
+
} catch {
|
|
182
|
+
name = "";
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return normalizeMachineName(name);
|
|
186
|
+
} catch {
|
|
187
|
+
return "";
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
async function resolveMachineName(override) {
|
|
191
|
+
if (override !== void 0) return normalizeMachineName(override);
|
|
192
|
+
const configured = process.env.PRISM_MACHINE_NAME;
|
|
193
|
+
if (configured && configured.trim()) return normalizeMachineName(configured);
|
|
194
|
+
return machineName();
|
|
195
|
+
}
|
|
196
|
+
async function signInPrism(authPath, output, legacy = false, machineNameOverride, notice = (message) => {
|
|
197
|
+
process.stderr.write(message + "\n");
|
|
198
|
+
}) {
|
|
199
|
+
if (legacy) return signInPrismLegacy(authPath, output);
|
|
200
|
+
const name = await resolveMachineName(machineNameOverride);
|
|
201
|
+
if (name) notice('This computer will be listed on your Q Division account as "' + name + '" (change it with --machine-name).');
|
|
202
|
+
const verifier = random(32), state = random(32), deadline = Date.now() + 12e4;
|
|
203
|
+
let callbackUri, selected = false;
|
|
204
|
+
let finish;
|
|
205
|
+
const callback = new Promise((resolve) => {
|
|
206
|
+
finish = resolve;
|
|
207
|
+
});
|
|
208
|
+
const listener = (0, import_node_http.createServer)({ requestTimeout: 5e3, headersTimeout: 4e3 }, (request, response) => {
|
|
209
|
+
let result;
|
|
210
|
+
let callbackRequest = false;
|
|
211
|
+
try {
|
|
212
|
+
const url = new URL(request.url ?? "", callbackUri), params = url.searchParams;
|
|
213
|
+
const keys = [...params.keys()].sort().join(",");
|
|
214
|
+
const code = params.get("code"), error = params.get("error");
|
|
215
|
+
callbackRequest = !selected && Date.now() < deadline && request.method === "GET" && request.headers.host === new URL(callbackUri).host && (request.url ?? "").length <= 8192 && /^\/callback\?/.test(request.url ?? "") && !url.hash && url.origin + url.pathname === callbackUri;
|
|
216
|
+
if (callbackRequest && params.get("state") === state && params.get("iss") === issuer) {
|
|
217
|
+
if (keys === "code,iss,state" && code && code.length <= 4096) result = { code };
|
|
218
|
+
if (["error,iss,state", "error,error_description,iss,state"].includes(keys) && error) result = { error };
|
|
219
|
+
}
|
|
220
|
+
} catch {
|
|
221
|
+
}
|
|
222
|
+
if (callbackRequest) {
|
|
223
|
+
response.writeHead(303, {
|
|
224
|
+
Location: issuer + "/signed-in?client=" + encodeURIComponent(clientId) + "&result=" + (result?.code ? "ok" : "failed"),
|
|
225
|
+
"Cache-Control": "no-store",
|
|
226
|
+
"Referrer-Policy": "no-referrer",
|
|
227
|
+
"Connection": "close"
|
|
228
|
+
});
|
|
229
|
+
if (result) {
|
|
230
|
+
selected = true;
|
|
231
|
+
response.once("finish", () => finish(result));
|
|
232
|
+
}
|
|
233
|
+
response.end();
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
response.writeHead(400, {
|
|
237
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
238
|
+
"Cache-Control": "no-store",
|
|
239
|
+
"Referrer-Policy": "no-referrer",
|
|
240
|
+
"X-Content-Type-Options": "nosniff",
|
|
241
|
+
"Connection": "close"
|
|
242
|
+
});
|
|
243
|
+
response.end("This callback did not match a pending Prism sign-in.");
|
|
244
|
+
});
|
|
245
|
+
const sockets = /* @__PURE__ */ new Set();
|
|
246
|
+
listener.on("connection", (socket) => {
|
|
247
|
+
sockets.add(socket);
|
|
248
|
+
socket.once("close", () => sockets.delete(socket));
|
|
249
|
+
});
|
|
250
|
+
listener.maxConnections = 8;
|
|
251
|
+
let timer;
|
|
252
|
+
try {
|
|
253
|
+
await new Promise((resolve, reject) => {
|
|
254
|
+
listener.once("error", reject);
|
|
255
|
+
listener.listen(0, "127.0.0.1", () => {
|
|
256
|
+
listener.removeListener("error", reject);
|
|
257
|
+
resolve();
|
|
258
|
+
});
|
|
259
|
+
});
|
|
260
|
+
listener.on("error", () => finish(null));
|
|
261
|
+
const address = listener.address();
|
|
262
|
+
if (!address || typeof address === "string") stop("auth_temporarily_unavailable");
|
|
263
|
+
callbackUri = "http://127.0.0.1:" + address.port + "/callback";
|
|
264
|
+
const url = issuer + "/authorize?" + new URLSearchParams({
|
|
265
|
+
response_type: "code",
|
|
266
|
+
client_id: clientId,
|
|
267
|
+
redirect_uri: callbackUri,
|
|
268
|
+
scope: "prism:session",
|
|
269
|
+
resource,
|
|
270
|
+
state,
|
|
271
|
+
code_challenge: sha(verifier).toString("base64url"),
|
|
272
|
+
code_challenge_method: "S256",
|
|
273
|
+
// The AS binds every /session grant to a device-key fingerprint (64 lowercase hex); Prism's exchange checks no device
|
|
274
|
+
// proof, so a fresh random key per sign-in is enough.
|
|
275
|
+
qd_device_key: (0, import_node_crypto.createHash)("sha256").update((0, import_node_crypto.randomBytes)(32)).digest("hex")
|
|
276
|
+
});
|
|
277
|
+
timer = setTimeout(() => finish(null), Math.max(0, deadline - Date.now()));
|
|
278
|
+
output("Open this Q Division sign-in link in your browser:\n" + url);
|
|
279
|
+
const opened = (error) => {
|
|
280
|
+
if (error) output("Could not open the browser automatically. Open the link above.");
|
|
281
|
+
};
|
|
282
|
+
if (process.platform === "darwin") (0, import_node_child_process.execFile)("/usr/bin/open", [url], { timeout: 5e3 }, opened);
|
|
283
|
+
else if (process.platform === "win32") (0, import_node_child_process.execFile)("C:\\Windows\\System32\\rundll32.exe", ["url.dll,FileProtocolHandler", url], { timeout: 5e3 }, opened);
|
|
284
|
+
else (0, import_node_child_process.execFile)("xdg-open", [url], { timeout: 5e3 }, opened);
|
|
285
|
+
const result = await callback;
|
|
286
|
+
if (!result || Date.now() >= deadline) stop("login_expired");
|
|
287
|
+
if (result.error) stop("qdivision_access_denied");
|
|
288
|
+
const form = new URLSearchParams({
|
|
289
|
+
grant_type: "authorization_code",
|
|
290
|
+
code: result.code,
|
|
291
|
+
redirect_uri: callbackUri,
|
|
292
|
+
client_id: clientId,
|
|
293
|
+
code_verifier: verifier,
|
|
294
|
+
resource
|
|
295
|
+
});
|
|
296
|
+
if (name) form.set("qd_machine_name", name);
|
|
297
|
+
const token = await post(issuer + "/token", form.toString(), { "Content-Type": "application/x-www-form-urlencoded" }, true);
|
|
298
|
+
if (!token || typeof token.access_token !== "string" || !token.access_token || token.access_token.length > 8192 || !/^[\x21-\x7e]+$/.test(token.access_token) || typeof token.token_type !== "string" || token.token_type.toLowerCase() !== "bearer") stop("invalid_login_response");
|
|
299
|
+
const session = await post("/auth/qdivision/exchange", "{}", { "Authorization": "Bearer " + token.access_token }, true);
|
|
300
|
+
if (!session || !["token", "email", "accountId"].every((key) => typeof session[key] === "string" && session[key].length > 0 && session[key].length <= 4096) || !/^[\x21-\x7e]+$/.test(session.token)) stop("invalid_login_response");
|
|
301
|
+
try {
|
|
302
|
+
replaceCredential(authPath, { token: session.token, email: session.email, accountId: session.accountId });
|
|
303
|
+
} catch {
|
|
304
|
+
stop("auth_credential_unavailable");
|
|
305
|
+
}
|
|
306
|
+
output("Prism backend=remote. Signed in. Reconnect your MCP client.");
|
|
307
|
+
} finally {
|
|
308
|
+
clearTimeout(timer);
|
|
309
|
+
listener.close();
|
|
310
|
+
for (const socket of sockets) socket.destroy();
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
async function signInPrismLegacy(authPath, output) {
|
|
314
|
+
const { privateKey, publicKey } = (0, import_node_crypto.generateKeyPairSync)("ed25519");
|
|
315
|
+
const spki = publicKey.export({ type: "spki", format: "der" });
|
|
316
|
+
const deviceProofPublicKey = spki.subarray(-32).toString("base64url");
|
|
317
|
+
const verifier = random(32), clientNonce = random(32);
|
|
318
|
+
let transactionId, deadline = Date.now() + 6e5, selected;
|
|
319
|
+
let finish;
|
|
320
|
+
const callback = new Promise((resolve) => {
|
|
321
|
+
finish = resolve;
|
|
322
|
+
});
|
|
323
|
+
let callbackUri;
|
|
324
|
+
const listener = (0, import_node_http.createServer)({ requestTimeout: 5e3, headersTimeout: 4e3 }, (request, response) => {
|
|
325
|
+
let valid = false;
|
|
326
|
+
try {
|
|
327
|
+
const url = new URL(request.url ?? "", callbackUri);
|
|
328
|
+
const values = url.searchParams;
|
|
329
|
+
const keys = [...values.keys()].sort().join(",");
|
|
330
|
+
const code = values.get("loginCode");
|
|
331
|
+
if (!selected && transactionId && Date.now() < deadline && request.method === "GET" && request.headers.host === new URL(callbackUri).host && /^\/callback\?/.test(request.url ?? "") && url.origin + url.pathname === callbackUri && keys === "clientNonce,loginCode,transactionId" && values.get("clientNonce") === clientNonce && values.get("transactionId") === transactionId && canonical(code, 32)) {
|
|
332
|
+
selected = code;
|
|
333
|
+
valid = true;
|
|
334
|
+
}
|
|
335
|
+
} catch {
|
|
336
|
+
}
|
|
337
|
+
response.writeHead(valid ? 200 : 400, {
|
|
338
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
339
|
+
"Cache-Control": "no-store",
|
|
340
|
+
"Referrer-Policy": "no-referrer",
|
|
341
|
+
"X-Content-Type-Options": "nosniff",
|
|
342
|
+
"Connection": "close"
|
|
343
|
+
});
|
|
344
|
+
if (valid) response.once("finish", () => finish(selected));
|
|
345
|
+
response.end(valid ? "Prism received the sign-in. Return to your terminal for the result." : "This callback did not match a pending Prism sign-in.");
|
|
346
|
+
});
|
|
347
|
+
const sockets = /* @__PURE__ */ new Set();
|
|
348
|
+
listener.on("connection", (socket) => {
|
|
349
|
+
sockets.add(socket);
|
|
350
|
+
socket.once("close", () => sockets.delete(socket));
|
|
351
|
+
});
|
|
352
|
+
listener.maxConnections = 8;
|
|
353
|
+
let timer;
|
|
354
|
+
try {
|
|
355
|
+
await new Promise((resolve, reject) => {
|
|
356
|
+
listener.once("error", reject);
|
|
357
|
+
listener.listen(0, "127.0.0.1", () => {
|
|
358
|
+
listener.removeListener("error", reject);
|
|
359
|
+
resolve();
|
|
360
|
+
});
|
|
361
|
+
});
|
|
362
|
+
listener.on("error", () => finish(null));
|
|
363
|
+
const address = listener.address();
|
|
364
|
+
if (!address || typeof address === "string") throw new SignInError("auth_temporarily_unavailable");
|
|
365
|
+
callbackUri = "http://127.0.0.1:" + address.port + "/callback";
|
|
366
|
+
const parent = await post("/auth/transactions", JSON.stringify({
|
|
367
|
+
clientId: "prism-cli-loopback-v1",
|
|
368
|
+
callbackUri,
|
|
369
|
+
pkceChallengeS256: sha(verifier).toString("base64url"),
|
|
370
|
+
deviceProofPublicKey,
|
|
371
|
+
clientNonce
|
|
372
|
+
}));
|
|
373
|
+
if (!record(parent, ["transactionId", "deviceIncarnation", "createdAtMs", "expiresAtMs", "loginUrl"]) || !canonical(parent.transactionId, 32) || !canonical(parent.deviceIncarnation, 16) || !Number.isSafeInteger(parent.createdAtMs) || !current(parent.expiresAtMs) || parent.expiresAtMs - parent.createdAtMs !== 6e5 || typeof parent.loginUrl !== "string" || !new RegExp("^" + origin.replace(/\./g, "\\.") + "/auth/login\\?launch=[A-Za-z0-9_-]{43}$").test(parent.loginUrl)) throw new SignInError("invalid_login_response");
|
|
374
|
+
transactionId = parent.transactionId;
|
|
375
|
+
deadline = Math.min(deadline, parent.expiresAtMs);
|
|
376
|
+
timer = setTimeout(() => finish(null), Math.max(0, deadline - Date.now()));
|
|
377
|
+
output("Prism backend=remote. Open this sign-in link in your browser:\n" + parent.loginUrl);
|
|
378
|
+
const loginCode = await callback;
|
|
379
|
+
if (!loginCode || Date.now() >= deadline) throw new SignInError("login_expired");
|
|
380
|
+
const wire = JSON.stringify({ transactionId, loginCode, codeVerifier: verifier });
|
|
381
|
+
let result, previousNonce, retryDeadline = deadline;
|
|
382
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
383
|
+
try {
|
|
384
|
+
const nonce = await post("/auth/nonce", JSON.stringify({ transactionId, loginCode }));
|
|
385
|
+
if (!record(nonce, ["ok", "nonce", "expiresAtMs"]) || nonce.ok !== true || !canonical(nonce.nonce, 32) || !current(nonce.expiresAtMs) || nonce.expiresAtMs > deadline || nonce.nonce === previousNonce) throw new SignInError("invalid_login_response");
|
|
386
|
+
if (Date.now() >= retryDeadline) throw new SignInError("login_expired");
|
|
387
|
+
previousNonce = nonce.nonce;
|
|
388
|
+
retryDeadline = Math.min(retryDeadline, nonce.expiresAtMs);
|
|
389
|
+
const proof = [
|
|
390
|
+
"qdivision-device-proof-v1",
|
|
391
|
+
audience,
|
|
392
|
+
parent.deviceIncarnation,
|
|
393
|
+
"POST",
|
|
394
|
+
origin + "/auth/redeem",
|
|
395
|
+
sha(wire).toString("hex"),
|
|
396
|
+
sha("login-code:" + loginCode).toString("hex"),
|
|
397
|
+
nonce.nonce
|
|
398
|
+
].join("\n");
|
|
399
|
+
result = await post("/auth/redeem", wire, { "X-QDivision-Nonce": nonce.nonce, "X-QDivision-Proof": (0, import_node_crypto.sign)(null, Buffer.from(proof), privateKey).toString("base64url") });
|
|
400
|
+
break;
|
|
401
|
+
} catch (error) {
|
|
402
|
+
if (attempt !== 0 || !(error instanceof SignInError) || !error.retryable || Date.now() + 2e3 >= retryDeadline) throw error;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
if (!record(result, ["ok", "authToken", "expiresAtMs"]) || result.ok !== true || typeof result.authToken !== "string" || result.authToken.length > 4096 || !current(result.expiresAtMs) || Date.now() >= retryDeadline) throw new SignInError("invalid_login_response");
|
|
406
|
+
const [version, payload, signature, ...rest] = result.authToken.split(".");
|
|
407
|
+
if (version !== "qds2" || rest.length || !payload || !canonical(signature, 64) || !canonical(payload, Buffer.from(payload, "base64url").length)) throw new SignInError("invalid_login_response");
|
|
408
|
+
const claims = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(payload, "base64url")));
|
|
409
|
+
if (!record(claims, ["ver", "iss", "aud", "sub", "mintAtMs", "expiresAtMs", "kid"]) || claims.ver !== 2 || claims.aud !== audience || ![origin, "https://senti-api.qdivision.one"].includes(claims.iss) || claims.expiresAtMs !== result.expiresAtMs || !Number.isSafeInteger(claims.mintAtMs) || claims.mintAtMs < 0 || claims.mintAtMs - Date.now() > 6e4 || claims.expiresAtMs - claims.mintAtMs !== lifetime || typeof claims.sub !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(claims.sub) || typeof claims.kid !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(claims.kid)) throw new SignInError("invalid_login_response");
|
|
410
|
+
try {
|
|
411
|
+
replaceCredential(authPath, {
|
|
412
|
+
token: result.authToken,
|
|
413
|
+
expiresAtMs: result.expiresAtMs,
|
|
414
|
+
deviceIncarnation: parent.deviceIncarnation,
|
|
415
|
+
deviceProofPublicKey,
|
|
416
|
+
deviceProofPrivateKeyPkcs8Base64: privateKey.export({ type: "pkcs8", format: "der" }).toString("base64")
|
|
417
|
+
});
|
|
418
|
+
} catch {
|
|
419
|
+
throw new SignInError("auth_credential_unavailable");
|
|
420
|
+
}
|
|
421
|
+
output("Prism backend=remote. Signed in. Reconnect your MCP client.");
|
|
422
|
+
} finally {
|
|
423
|
+
clearTimeout(timer);
|
|
424
|
+
listener.close();
|
|
425
|
+
for (const socket of sockets) socket.destroy();
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// src/prism-response-origin.mjs
|
|
430
|
+
var BACKEND = "qdivision.one/backend";
|
|
431
|
+
function isRecord(value) {
|
|
432
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
433
|
+
}
|
|
434
|
+
function attributePrismMessage(message, backend) {
|
|
435
|
+
if (Object.hasOwn(message, "error")) {
|
|
436
|
+
const error = message.error;
|
|
437
|
+
return { ...message, error: { ...error, message: `[Prism backend=${backend}] ${error.message}` } };
|
|
438
|
+
}
|
|
439
|
+
const field = Object.hasOwn(message, "result") ? "result" : "params";
|
|
440
|
+
const payload = message[field] ?? {};
|
|
441
|
+
if (!isRecord(payload)) throw new Error("Invalid MCP message payload");
|
|
442
|
+
const upstream = isRecord(payload._meta) ? payload._meta : {};
|
|
443
|
+
return { ...message, [field]: { ...payload, _meta: { ...upstream, [BACKEND]: backend } } };
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// prism/contracts/mcp_deadlines.json
|
|
447
|
+
var mcp_deadlines_default = {
|
|
448
|
+
contract: "prism-mcp-deadlines",
|
|
449
|
+
version: 1,
|
|
450
|
+
about: "One deadline policy for every layer of a Prism MCP request. The shim (src/mcp-shim.ts), the prism-api Worker (src/mcp-deadlines.json, a byte-identical copy checked by its contract test), the server's per-request budget (prism/mcp/stage_timing.py), the client backstops (scripts/fix-mcp-configs.py, prism/cli/init.py) and the health check (scripts/check-mcp-health.py) all read this file. Each layer must answer before the one in front of it gives up: backendBudgetMs < workerMs < shimMs < clientBackstopMs, with at least the margins below. tests/test_mcp_deadline_contract.py enforces the ordering.",
|
|
451
|
+
default: { backendBudgetMs: 8e3, workerMs: 1e4, shimMs: 11e3 },
|
|
452
|
+
tools: {
|
|
453
|
+
adapt_pattern_to_repo: { backendBudgetMs: 21e3, workerMs: 24e3, shimMs: 25e3 },
|
|
454
|
+
record_research: { backendBudgetMs: 26e3, workerMs: 29e3, shimMs: 3e4 },
|
|
455
|
+
manage_research_documents: { backendBudgetMs: 26e3, workerMs: 29e3, shimMs: 3e4 },
|
|
456
|
+
check_paper_integrity: { backendBudgetMs: 26e3, workerMs: 29e3, shimMs: 3e4 }
|
|
457
|
+
},
|
|
458
|
+
optionalWorkMs: { find_similar_bug: 2e3, record_fix: 1200 },
|
|
459
|
+
targetsP95Ms: { find_similar_bug: 3e3, record_fix: 2e3 },
|
|
460
|
+
notificationShimMs: 1e4,
|
|
461
|
+
shimBackstopGraceMs: 250,
|
|
462
|
+
clientBackstopMs: 45e3,
|
|
463
|
+
clientBackstopMaxMs: 12e4,
|
|
464
|
+
overrideMinMs: 1e3,
|
|
465
|
+
margins: { backendToWorkerMs: 2e3, workerToShimMs: 1e3, shimToClientMs: 5e3 }
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
// src/mcp-shim.ts
|
|
469
|
+
var LOADED_SHA256 = (() => {
|
|
470
|
+
try {
|
|
471
|
+
return (0, import_crypto.createHash)("sha256").update(fs.readFileSync(__filename)).digest("hex");
|
|
472
|
+
} catch {
|
|
473
|
+
return "unreadable";
|
|
474
|
+
}
|
|
475
|
+
})();
|
|
476
|
+
var REMOTE_URL = "https://prism-api.qdivision.one/mcp";
|
|
477
|
+
var AUTH_PATH = path.join(os.homedir(), ".prism", "auth.json");
|
|
478
|
+
var TRUSTED_REAUTH_ORIGIN = "https://auth.qdivision.one";
|
|
479
|
+
var TEAM_CACHE_FILES = ["team-cache.json", "team-lease.json", "team-rules-cache.json"];
|
|
480
|
+
var SESSION_WARNING_COOLDOWN_MS = 60 * 60 * 1e3;
|
|
481
|
+
var lastSessionWarningAt = 0;
|
|
482
|
+
var ISO_EXPIRY_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
483
|
+
function maybeWarnSessionExpiry(headers) {
|
|
484
|
+
const warning = (headers.get("X-Prism-Session-Warning") || "").trim().toLowerCase();
|
|
485
|
+
if (warning !== "expiring_soon" && warning !== "expiring-soon") return;
|
|
486
|
+
const now = Date.now();
|
|
487
|
+
if (lastSessionWarningAt > 0 && now - lastSessionWarningAt < SESSION_WARNING_COOLDOWN_MS) return;
|
|
488
|
+
lastSessionWarningAt = now;
|
|
489
|
+
const rawExpires = (headers.get("X-Prism-Session-Expires-At") || "").trim();
|
|
490
|
+
const expiresAt = rawExpires.length <= 40 && ISO_EXPIRY_RE.test(rawExpires) ? rawExpires : "";
|
|
491
|
+
const rawReauth = (headers.get("X-Prism-Reauth-Url") || "").trim();
|
|
492
|
+
const reauthUrl = rawReauth === TRUSTED_REAUTH_ORIGIN ? rawReauth : TRUSTED_REAUTH_ORIGIN;
|
|
493
|
+
logErr(`session expiring soon${expiresAt ? ` (expires ${expiresAt})` : ""}; run \`prism login\` or re-authenticate at ${reauthUrl}`, "remote");
|
|
494
|
+
}
|
|
495
|
+
function purgeLocalTeamCache() {
|
|
496
|
+
const dir = path.dirname(AUTH_PATH);
|
|
497
|
+
for (const name of TEAM_CACHE_FILES) {
|
|
498
|
+
try {
|
|
499
|
+
fs.unlinkSync(path.join(dir, name));
|
|
500
|
+
} catch {
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
function currentToken() {
|
|
505
|
+
let raw;
|
|
506
|
+
try {
|
|
507
|
+
raw = fs.readFileSync(AUTH_PATH, "utf8");
|
|
508
|
+
} catch (error) {
|
|
509
|
+
if (error?.code === "ENOENT") return { token: process.env.PRISM_AUTH_TOKEN || "" };
|
|
510
|
+
return { token: "", failure: "auth_credential_unavailable" };
|
|
511
|
+
}
|
|
512
|
+
try {
|
|
513
|
+
const saved = JSON.parse(raw);
|
|
514
|
+
if (saved && typeof saved === "object" && !Array.isArray(saved) && typeof saved.token === "string") return { token: saved.token };
|
|
515
|
+
return { token: "", failure: "auth_required" };
|
|
516
|
+
} catch {
|
|
517
|
+
return { token: "", failure: "malformed_token" };
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
var REMOTE_ENABLED = process.env.PRISM_REMOTE_DISABLE !== "1";
|
|
521
|
+
var DEFAULT_DEADLINE_MS = (() => {
|
|
522
|
+
const raw = Number(process.env.PRISM_REQUEST_DEADLINE_MS);
|
|
523
|
+
const cap = mcp_deadlines_default.clientBackstopMs - mcp_deadlines_default.margins.shimToClientMs;
|
|
524
|
+
return Number.isFinite(raw) && raw >= mcp_deadlines_default.overrideMinMs && raw <= cap ? Math.round(raw) : mcp_deadlines_default.default.shimMs;
|
|
525
|
+
})();
|
|
526
|
+
var TOOL_DEADLINE_MS = Object.fromEntries(
|
|
527
|
+
Object.entries(mcp_deadlines_default.tools).filter(([, limits]) => typeof limits.shimMs === "number").map(([tool, limits]) => [tool, limits.shimMs])
|
|
528
|
+
);
|
|
529
|
+
var NOTIFICATION_DEADLINE_MS = mcp_deadlines_default.notificationShimMs;
|
|
530
|
+
var BACKSTOP_GRACE_MS = mcp_deadlines_default.shimBackstopGraceMs;
|
|
531
|
+
var NO_FALLBACK = { used: false, reason: "This Prism client is remote-only; it has no local fallback." };
|
|
532
|
+
function deadlineFor(obj) {
|
|
533
|
+
if (obj?.method === "tools/call") {
|
|
534
|
+
const tool = obj.params?.name;
|
|
535
|
+
if (typeof tool === "string" && Object.hasOwn(TOOL_DEADLINE_MS, tool)) return Math.max(TOOL_DEADLINE_MS[tool], DEFAULT_DEADLINE_MS);
|
|
536
|
+
}
|
|
537
|
+
return DEFAULT_DEADLINE_MS;
|
|
538
|
+
}
|
|
539
|
+
function requestLabel(obj) {
|
|
540
|
+
return obj?.method === "tools/call" && typeof obj.params?.name === "string" ? obj.params.name : String(obj?.method ?? "request");
|
|
541
|
+
}
|
|
542
|
+
function shimBuild() {
|
|
543
|
+
let version = "unknown";
|
|
544
|
+
try {
|
|
545
|
+
version = String(require_package().version);
|
|
546
|
+
} catch {
|
|
547
|
+
}
|
|
548
|
+
return { version, path: __filename, sha256: LOADED_SHA256 };
|
|
549
|
+
}
|
|
550
|
+
function shimIdentity() {
|
|
551
|
+
const build = shimBuild();
|
|
552
|
+
return `version=${build.version} path=${build.path} sha256=${build.sha256.slice(0, 12)}`;
|
|
553
|
+
}
|
|
554
|
+
var RUN_DIR = process.env.PRISM_RUN_DIR || path.join(os.homedir(), ".prism", "run");
|
|
555
|
+
function recordRunningBuild() {
|
|
556
|
+
const file = path.join(RUN_DIR, `shim-${process.pid}.json`);
|
|
557
|
+
try {
|
|
558
|
+
fs.mkdirSync(RUN_DIR, { recursive: true, mode: 448 });
|
|
559
|
+
fs.writeFileSync(file, JSON.stringify({ pid: process.pid, ...shimBuild(), startedAt: (/* @__PURE__ */ new Date()).toISOString() }), { mode: 384 });
|
|
560
|
+
process.on("exit", () => {
|
|
561
|
+
try {
|
|
562
|
+
fs.unlinkSync(file);
|
|
563
|
+
} catch {
|
|
564
|
+
}
|
|
565
|
+
});
|
|
566
|
+
} catch {
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
var MAX_STDIN_BUFFER = 10 * 1024 * 1024;
|
|
570
|
+
var PARENT_CHECK_INTERVAL_MS = 3e4;
|
|
571
|
+
function logErr(msg, backend = "none") {
|
|
572
|
+
try {
|
|
573
|
+
process.stderr.write(`prism-shim: backend=${backend} target=remote ${msg}
|
|
574
|
+
`);
|
|
575
|
+
} catch {
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
function safeWrite(stream, data) {
|
|
579
|
+
if (!stream || !stream.writable) return false;
|
|
580
|
+
try {
|
|
581
|
+
stream.write(data);
|
|
582
|
+
return true;
|
|
583
|
+
} catch {
|
|
584
|
+
return false;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
function writeClient(line) {
|
|
588
|
+
if (!safeWrite(process.stdout, line + "\n")) {
|
|
589
|
+
process.exit(0);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
var AUTH_MESSAGES = {
|
|
593
|
+
missing_token: "Prism sign-in is required. Run prism login, then reconnect Prism.",
|
|
594
|
+
auth_required: "Prism sign-in is required. Run prism login, then reconnect Prism.",
|
|
595
|
+
malformed_token: "Prism could not read this sign-in credential. Sign in to Prism again, then reconnect.",
|
|
596
|
+
auth_credential_unavailable: "Prism could not access the saved sign-in credential. Check access to ~/.prism/auth.json, then reconnect. Your credential is retained.",
|
|
597
|
+
wrong_audience: "This credential declares another Q Division product. Sign in to Prism, then reconnect.",
|
|
598
|
+
unknown_key: "Prism no longer accepts this sign-in credential. Sign in to Prism again, then reconnect.",
|
|
599
|
+
invalid_signature: "Prism could not verify this sign-in credential. Sign in to Prism again, then reconnect.",
|
|
600
|
+
invalid_token_time: "This Prism sign-in credential has an invalid time. Check your clock and sign in again.",
|
|
601
|
+
token_expired: "Your Prism sign-in has expired. Sign in to Prism again, then reconnect.",
|
|
602
|
+
session_revoked: "Your Prism session was revoked. Sign in to Prism again, then reconnect.",
|
|
603
|
+
account_disabled: "Your Prism account is disabled. Contact Q Division support.",
|
|
604
|
+
legacy_issuance_closed: "Legacy sign-in issuance closed on December 14, 2026. Sign in to Prism again.",
|
|
605
|
+
legacy_session_retired: "Legacy sign-in retired on January 15, 2027. Sign in to Prism again, then reconnect.",
|
|
606
|
+
identity_recovery_required: "Prism needs you to sign in and recover your existing identity. Your saved data is retained.",
|
|
607
|
+
auth_temporarily_unavailable: "Prism sign-in verification is temporarily unavailable. Your credential is retained; reconnect to retry.",
|
|
608
|
+
qdivision_unauthorized: "Q Division sign-in was rejected (401). Run prism login again. Your saved credential was retained.",
|
|
609
|
+
qdivision_unavailable: "Q Division sign-in is temporarily unavailable (503). Retry prism login. Your saved credential was retained.",
|
|
610
|
+
qdivision_network_error: "Q Division sign-in is temporarily unavailable. Retry prism login. Your saved credential was retained.",
|
|
611
|
+
qdivision_forbidden: "This Q Division account cannot sign in to Prism (403). Contact Q Division support.",
|
|
612
|
+
account_not_found: "No Prism account is linked to this Q Division account (403 account_not_found). Contact Q Division support.",
|
|
613
|
+
qdivision_access_denied: "Q Division sign-in was cancelled or denied. Run prism login again."
|
|
614
|
+
};
|
|
615
|
+
function authFailure(code) {
|
|
616
|
+
return {
|
|
617
|
+
error: code,
|
|
618
|
+
code,
|
|
619
|
+
product: "prism",
|
|
620
|
+
message: AUTH_MESSAGES[code],
|
|
621
|
+
signIn: "prism:sign-in",
|
|
622
|
+
retryable: code === "auth_temporarily_unavailable",
|
|
623
|
+
...code === "legacy_session_retired" ? { cutoff: "2027-01-15T00:00:00.000Z" } : {}
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
function remoteFailure(status, body = "") {
|
|
627
|
+
if (status !== 401 && status !== 403 && status !== 503) return null;
|
|
628
|
+
let code;
|
|
629
|
+
try {
|
|
630
|
+
const parsed = JSON.parse(body);
|
|
631
|
+
code = parsed?.code ?? parsed?.error;
|
|
632
|
+
if (status === 403 && parsed?.purge_team_cache === true) {
|
|
633
|
+
purgeLocalTeamCache();
|
|
634
|
+
}
|
|
635
|
+
} catch {
|
|
636
|
+
}
|
|
637
|
+
if (status === 503) return code === "auth_temporarily_unavailable" ? { ...authFailure(code), backend: "remote" } : null;
|
|
638
|
+
if (typeof code === "string" && Object.hasOwn(AUTH_MESSAGES, code) && code !== "auth_temporarily_unavailable") {
|
|
639
|
+
return { ...authFailure(code), backend: "remote" };
|
|
640
|
+
}
|
|
641
|
+
return { ...authFailure("auth_required"), backend: "remote" };
|
|
642
|
+
}
|
|
643
|
+
var NOT_SENT_CODES = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ENETUNREACH", "EHOSTUNREACH", "ENETDOWN"]);
|
|
644
|
+
function networkFailure(error) {
|
|
645
|
+
const code = String(error?.cause?.code ?? error?.code ?? error?.name ?? "error").slice(0, 60);
|
|
646
|
+
return { cause: "network", sent: !NOT_SENT_CODES.has(code), backend: "none", detail: code };
|
|
647
|
+
}
|
|
648
|
+
var MIN_DISPATCH_MS = Math.min(1e3, Math.round(DEFAULT_DEADLINE_MS / 5));
|
|
649
|
+
function sseEvents(text) {
|
|
650
|
+
const payloads = [];
|
|
651
|
+
let data = [];
|
|
652
|
+
const flush = () => {
|
|
653
|
+
const payload = data.join("\n").trim();
|
|
654
|
+
if (payload && payload !== "[DONE]") payloads.push(payload);
|
|
655
|
+
data = [];
|
|
656
|
+
};
|
|
657
|
+
for (const raw of text.split("\n")) {
|
|
658
|
+
const line = raw.replace(/\r$/, "");
|
|
659
|
+
if (line === "") {
|
|
660
|
+
flush();
|
|
661
|
+
continue;
|
|
662
|
+
}
|
|
663
|
+
if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
|
|
664
|
+
}
|
|
665
|
+
flush();
|
|
666
|
+
return payloads;
|
|
667
|
+
}
|
|
668
|
+
function isTerminalFor(payload, id, requireResult = false) {
|
|
669
|
+
try {
|
|
670
|
+
const item = JSON.parse(payload);
|
|
671
|
+
if (!item || typeof item !== "object" || item.id !== id) return false;
|
|
672
|
+
const result = Object.hasOwn(item, "result");
|
|
673
|
+
return requireResult ? result && !Object.hasOwn(item, "error") : result !== Object.hasOwn(item, "error");
|
|
674
|
+
} catch {
|
|
675
|
+
return false;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
var HttpBackend = class {
|
|
679
|
+
constructor(hooks) {
|
|
680
|
+
this.hooks = hooks;
|
|
681
|
+
}
|
|
682
|
+
sessionId = null;
|
|
683
|
+
queue = Promise.resolve();
|
|
684
|
+
stopped = false;
|
|
685
|
+
controller = null;
|
|
686
|
+
// The client's own initialize, kept so a session the server forgot (HTTP 404
|
|
687
|
+
// after a backend restart) can be reopened without involving the client.
|
|
688
|
+
initializeMessage = null;
|
|
689
|
+
reopenCount = 0;
|
|
690
|
+
start() {
|
|
691
|
+
this.stopped = false;
|
|
692
|
+
this.sessionId = null;
|
|
693
|
+
}
|
|
694
|
+
stop() {
|
|
695
|
+
this.stopped = true;
|
|
696
|
+
this.controller?.abort();
|
|
697
|
+
}
|
|
698
|
+
// Requests are serialized so the session id from initialize is set before
|
|
699
|
+
// dependent calls go out. Every post settles by its deadline, so one stalled
|
|
700
|
+
// response can never hold the requests queued behind it.
|
|
701
|
+
send(message, id, deadlineAt) {
|
|
702
|
+
this.queue = this.queue.then(() => this.post(message, id, deadlineAt)).catch((error) => {
|
|
703
|
+
if (id !== void 0) this.hooks.onRequestFailure(id, { ...networkFailure(error), sent: true, detail: "unexpected transport failure" });
|
|
704
|
+
else logErr("notification failed: unexpected transport failure");
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
drain() {
|
|
708
|
+
return this.queue;
|
|
709
|
+
}
|
|
710
|
+
fail(id, failure) {
|
|
711
|
+
if (id !== void 0) this.hooks.onRequestFailure(id, failure);
|
|
712
|
+
else logErr(`notification not delivered (${failure.cause}${failure.httpStatus ? ` HTTP ${failure.httpStatus}` : ""})`, failure.backend);
|
|
713
|
+
}
|
|
714
|
+
authHeaders() {
|
|
715
|
+
const headers = new Headers({
|
|
716
|
+
"Content-Type": "application/json",
|
|
717
|
+
"Accept": "application/json, text/event-stream"
|
|
718
|
+
});
|
|
719
|
+
const credential = currentToken();
|
|
720
|
+
if (credential.failure) return authFailure(credential.failure);
|
|
721
|
+
if (!credential.token) return authFailure("auth_required");
|
|
722
|
+
try {
|
|
723
|
+
(0, import_http.validateHeaderValue)("Authorization", `Bearer ${credential.token}`);
|
|
724
|
+
headers.set("Authorization", `Bearer ${credential.token}`);
|
|
725
|
+
} catch {
|
|
726
|
+
return authFailure("malformed_token");
|
|
727
|
+
}
|
|
728
|
+
return headers;
|
|
729
|
+
}
|
|
730
|
+
// One HTTP exchange, headers AND body, bounded by deadlineAt. It never throws.
|
|
731
|
+
// The race, not the abort, ends the wait: abort is only best-effort cleanup.
|
|
732
|
+
// An SSE body is read only until the terminal response for requestId arrives,
|
|
733
|
+
// so a server that keeps the stream open after answering cannot cause a timeout.
|
|
734
|
+
async exchange(message, requestId, deadlineAt, headers) {
|
|
735
|
+
const r = { status: 0, ct: "", retryAfter: "", text: "", headersSeen: false, timedOut: false };
|
|
736
|
+
if (this.sessionId) headers.set("mcp-session-id", this.sessionId);
|
|
737
|
+
const ctrl = new AbortController();
|
|
738
|
+
this.controller = ctrl;
|
|
739
|
+
let reader;
|
|
740
|
+
const run = (async () => {
|
|
741
|
+
const res = await fetch(REMOTE_URL, {
|
|
742
|
+
method: "POST",
|
|
743
|
+
headers,
|
|
744
|
+
body: message,
|
|
745
|
+
signal: ctrl.signal,
|
|
746
|
+
redirect: "error"
|
|
747
|
+
});
|
|
748
|
+
r.headersSeen = true;
|
|
749
|
+
maybeWarnSessionExpiry(res.headers);
|
|
750
|
+
const sid = res.headers.get("mcp-session-id");
|
|
751
|
+
if (sid) this.sessionId = sid;
|
|
752
|
+
r.status = res.status;
|
|
753
|
+
if (remoteFailure(r.status)) this.hooks.onRefusalHeaders();
|
|
754
|
+
r.ct = (res.headers.get("content-type") || "").toLowerCase();
|
|
755
|
+
r.retryAfter = res.headers.get("Retry-After") ?? "";
|
|
756
|
+
if (!res.body) return;
|
|
757
|
+
reader = res.body.getReader();
|
|
758
|
+
const watchForAnswer = requestId !== void 0 && r.ct.includes("text/event-stream") && r.status >= 200 && r.status < 300;
|
|
759
|
+
const decoder = new TextDecoder();
|
|
760
|
+
const separator = /\r?\n\r?\n/g;
|
|
761
|
+
let scanned = 0;
|
|
762
|
+
for (; ; ) {
|
|
763
|
+
const { done, value } = await reader.read();
|
|
764
|
+
if (done) break;
|
|
765
|
+
r.text += decoder.decode(value, { stream: true });
|
|
766
|
+
if (!watchForAnswer) continue;
|
|
767
|
+
separator.lastIndex = scanned;
|
|
768
|
+
let end = -1;
|
|
769
|
+
for (let m = separator.exec(r.text); m; m = separator.exec(r.text)) end = m.index + m[0].length;
|
|
770
|
+
if (end <= scanned) continue;
|
|
771
|
+
const answered = sseEvents(r.text.slice(scanned, end)).some((payload) => isTerminalFor(payload, requestId));
|
|
772
|
+
scanned = end;
|
|
773
|
+
if (answered) {
|
|
774
|
+
r.text = r.text.slice(0, end);
|
|
775
|
+
reader.cancel().catch(() => {
|
|
776
|
+
});
|
|
777
|
+
return;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
r.text += decoder.decode();
|
|
781
|
+
})();
|
|
782
|
+
run.catch(() => {
|
|
783
|
+
});
|
|
784
|
+
let timer;
|
|
785
|
+
const deadline = new Promise((resolve) => {
|
|
786
|
+
timer = setTimeout(() => resolve(TIMED_OUT), Math.max(0, deadlineAt - Date.now()));
|
|
787
|
+
});
|
|
788
|
+
try {
|
|
789
|
+
if (await Promise.race([run, deadline]) === TIMED_OUT) {
|
|
790
|
+
r.timedOut = true;
|
|
791
|
+
ctrl.abort();
|
|
792
|
+
reader?.cancel().catch(() => {
|
|
793
|
+
});
|
|
794
|
+
}
|
|
795
|
+
} catch (error) {
|
|
796
|
+
r.error = error;
|
|
797
|
+
} finally {
|
|
798
|
+
clearTimeout(timer);
|
|
799
|
+
this.controller = null;
|
|
800
|
+
}
|
|
801
|
+
return r;
|
|
802
|
+
}
|
|
803
|
+
// The server answered 404: it no longer knows this MCP session (a backend
|
|
804
|
+
// restart drops every session). Open a new one with the client's initialize,
|
|
805
|
+
// under a private id so its answer never reaches the client.
|
|
806
|
+
// A sign-in refusal while reopening is returned so the client is asked to sign in.
|
|
807
|
+
async reopenSession(deadlineAt) {
|
|
808
|
+
if (!this.initializeMessage) return false;
|
|
809
|
+
let init;
|
|
810
|
+
try {
|
|
811
|
+
init = JSON.parse(this.initializeMessage);
|
|
812
|
+
} catch {
|
|
813
|
+
return false;
|
|
814
|
+
}
|
|
815
|
+
const internalId = `prism-shim-reopen-${++this.reopenCount}`;
|
|
816
|
+
init.id = internalId;
|
|
817
|
+
this.sessionId = null;
|
|
818
|
+
const headers = this.authHeaders();
|
|
819
|
+
if (!(headers instanceof Headers)) return headers;
|
|
820
|
+
const opened = await this.exchange(JSON.stringify(init), internalId, deadlineAt, headers);
|
|
821
|
+
const refused = opened.headersSeen ? remoteFailure(opened.status, opened.text) : null;
|
|
822
|
+
if (refused) return refused;
|
|
823
|
+
if (opened.timedOut || opened.error || opened.status !== 200 || !this.sessionId) return false;
|
|
824
|
+
const payloads = opened.ct.includes("text/event-stream") ? sseEvents(opened.text) : opened.text.split("\n").map((line) => line.trim()).filter(Boolean);
|
|
825
|
+
if (!payloads.some((payload) => isTerminalFor(payload, internalId, true))) return false;
|
|
826
|
+
const again = this.authHeaders();
|
|
827
|
+
if (!(again instanceof Headers)) return again;
|
|
828
|
+
const notified = await this.exchange(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }), void 0, deadlineAt, again);
|
|
829
|
+
const refusedNotice = notified.headersSeen ? remoteFailure(notified.status, notified.text) : null;
|
|
830
|
+
if (refusedNotice) return refusedNotice;
|
|
831
|
+
return !notified.timedOut && !notified.error && notified.status >= 200 && notified.status < 300;
|
|
832
|
+
}
|
|
833
|
+
async post(message, id, deadlineAt, reopened = false) {
|
|
834
|
+
if (this.stopped) return;
|
|
835
|
+
let obj;
|
|
836
|
+
try {
|
|
837
|
+
obj = JSON.parse(message);
|
|
838
|
+
} catch {
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
if (obj?.method === "initialize" && this.initializeMessage === null) this.initializeMessage = message;
|
|
842
|
+
if (id !== void 0 && !this.hooks.isPending(id)) return;
|
|
843
|
+
const remaining = deadlineAt - Date.now();
|
|
844
|
+
if (remaining <= (id === void 0 ? 0 : MIN_DISPATCH_MS)) {
|
|
845
|
+
this.fail(id, { cause: "timeout", sent: false, backend: "none" });
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
const headers = this.authHeaders();
|
|
849
|
+
if (!(headers instanceof Headers)) {
|
|
850
|
+
this.hooks.onRefusal(headers);
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
853
|
+
if (id !== void 0) this.hooks.onDispatch(id);
|
|
854
|
+
const r = await this.exchange(message, id, deadlineAt, headers);
|
|
855
|
+
if (this.stopped) return;
|
|
856
|
+
const status = r.status;
|
|
857
|
+
const ct = r.ct;
|
|
858
|
+
const refusalAtHeaders = r.headersSeen ? remoteFailure(status) : null;
|
|
859
|
+
if (r.timedOut) {
|
|
860
|
+
if (refusalAtHeaders) {
|
|
861
|
+
this.hooks.onRefusal(refusalAtHeaders, id);
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
this.fail(id, { cause: "timeout", sent: true, backend: "none", ...r.headersSeen ? { httpStatus: status, contentType: ct } : {} });
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
if (r.error !== void 0) {
|
|
868
|
+
if (refusalAtHeaders) {
|
|
869
|
+
this.hooks.onRefusal(refusalAtHeaders, id);
|
|
870
|
+
return;
|
|
871
|
+
}
|
|
872
|
+
this.fail(id, r.headersSeen ? { cause: "stream_closed_early", sent: true, backend: "remote", httpStatus: status, contentType: ct } : networkFailure(r.error));
|
|
873
|
+
return;
|
|
874
|
+
}
|
|
875
|
+
const text = r.text;
|
|
876
|
+
const refusal = remoteFailure(status, text);
|
|
877
|
+
if (refusal) {
|
|
878
|
+
this.hooks.onRefusal(refusal, id);
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
if (status === 429) {
|
|
882
|
+
let code;
|
|
883
|
+
try {
|
|
884
|
+
code = JSON.parse(text)?.code;
|
|
885
|
+
} catch {
|
|
886
|
+
}
|
|
887
|
+
if (code === "abuse_limit" || code === "weekly_limit") {
|
|
888
|
+
const retryAfter = /^[1-9][0-9]{0,5}$/.test(r.retryAfter) && Number(r.retryAfter) <= 604800 ? Number(r.retryAfter) : void 0;
|
|
889
|
+
const message2 = code === "weekly_limit" ? "Weekly Prism lookup limit reached." : "Prism request limit reached.";
|
|
890
|
+
if (id !== void 0) this.hooks.onLine(JSON.stringify({ jsonrpc: "2.0", id, error: {
|
|
891
|
+
code: -32e3,
|
|
892
|
+
message: message2,
|
|
893
|
+
data: { code, product: "prism", retryable: true, backend: "remote", ...retryAfter ? { retryAfter } : {} }
|
|
894
|
+
} }));
|
|
895
|
+
else logErr(message2, "remote");
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
if (status === 404) {
|
|
900
|
+
const outcome = !reopened && obj?.method !== "initialize" ? await this.reopenSession(deadlineAt) : false;
|
|
901
|
+
if (this.stopped) return;
|
|
902
|
+
if (typeof outcome === "object") {
|
|
903
|
+
this.hooks.onRefusal(outcome, id);
|
|
904
|
+
return;
|
|
905
|
+
}
|
|
906
|
+
if (outcome) {
|
|
907
|
+
logErr("the server no longer knew this MCP session; opened a new one and resent the message once", "remote");
|
|
908
|
+
return this.post(message, id, deadlineAt, true);
|
|
909
|
+
}
|
|
910
|
+
if (!this.stopped) this.hooks.onSessionLost(status, id);
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
const httpFailure = { cause: "http_status", sent: true, backend: "remote", httpStatus: status, contentType: ct };
|
|
914
|
+
if (status >= 500 || status < 200) {
|
|
915
|
+
this.fail(id, httpFailure);
|
|
916
|
+
return;
|
|
917
|
+
}
|
|
918
|
+
if (status === 202) {
|
|
919
|
+
if (id !== void 0) this.fail(id, { cause: "stream_closed_early", sent: true, backend: "remote", httpStatus: status, contentType: ct });
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
const sse = ct.includes("text/event-stream");
|
|
923
|
+
const payloads = sse ? sseEvents(text) : text.split("\n").map((line) => line.trim()).filter(Boolean);
|
|
924
|
+
const tolerated = status >= 300 ? httpFailure : null;
|
|
925
|
+
if (payloads.length === 0) {
|
|
926
|
+
if (id !== void 0) this.fail(id, tolerated ?? { cause: "stream_closed_early", sent: true, backend: "remote", httpStatus: status, contentType: ct });
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
const decoded = [];
|
|
930
|
+
for (const payload of payloads) {
|
|
931
|
+
let item;
|
|
932
|
+
try {
|
|
933
|
+
item = JSON.parse(payload);
|
|
934
|
+
} catch {
|
|
935
|
+
this.fail(id, tolerated ?? { cause: "non_json_body", sent: true, backend: "remote", httpStatus: status, contentType: ct });
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
try {
|
|
939
|
+
if (!item || item.jsonrpc !== "2.0" || Array.isArray(item)) throw new Error("invalid envelope");
|
|
940
|
+
const result = Object.hasOwn(item, "result");
|
|
941
|
+
const error = Object.hasOwn(item, "error");
|
|
942
|
+
const method = Object.hasOwn(item, "method");
|
|
943
|
+
const validId = (value) => typeof value === "string" || typeof value === "number" && Number.isSafeInteger(value);
|
|
944
|
+
if (method) {
|
|
945
|
+
if (result || error || typeof item.method !== "string" || Object.hasOwn(item, "id") && !validId(item.id) || item.params != null && (typeof item.params !== "object" || Array.isArray(item.params))) throw new Error("invalid method envelope");
|
|
946
|
+
} else {
|
|
947
|
+
if (result === error || !validId(item.id) || item.id !== obj.id) throw new Error("invalid terminal envelope");
|
|
948
|
+
if (error && (!item.error || typeof item.error !== "object" || Array.isArray(item.error) || !Number.isSafeInteger(item.error.code) || typeof item.error.message !== "string")) throw new Error("invalid error envelope");
|
|
949
|
+
if (result && (!item.result || typeof item.result !== "object" || Array.isArray(item.result))) throw new Error("invalid result envelope");
|
|
950
|
+
}
|
|
951
|
+
decoded.push(item);
|
|
952
|
+
} catch {
|
|
953
|
+
this.fail(id, tolerated ?? { cause: "invalid_envelope", sent: true, backend: "remote", httpStatus: status, contentType: ct });
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
if (id !== void 0 && decoded.filter((item) => item.id === obj.id && Object.hasOwn(item, "result") !== Object.hasOwn(item, "error")).length !== 1) {
|
|
958
|
+
this.fail(id, tolerated ?? { cause: sse ? "stream_closed_early" : "invalid_envelope", sent: true, backend: "remote", httpStatus: status, contentType: ct });
|
|
959
|
+
return;
|
|
960
|
+
}
|
|
961
|
+
for (const p of payloads) this.hooks.onLine(p);
|
|
962
|
+
}
|
|
963
|
+
};
|
|
964
|
+
var TIMED_OUT = /* @__PURE__ */ Symbol("timed out");
|
|
965
|
+
var FAILURE_TEXT = {
|
|
966
|
+
timeout: (label, f, seconds) => f.sent ? `did not answer ${label} within ${seconds} s (timeout)` : `could not send ${label} within ${seconds} s because earlier requests were still running (timeout)`,
|
|
967
|
+
http_status: (label, f) => `answered ${label} with HTTP ${f.httpStatus} (non-2xx status)`,
|
|
968
|
+
non_json_body: (label, f) => `answered ${label} with a body that is not JSON (${f.contentType || "no content type"})`,
|
|
969
|
+
stream_closed_early: (label) => `closed the response stream for ${label} before sending a result (stream closed early)`,
|
|
970
|
+
network: (label, f) => `could not be reached for ${label} (network failure${f.detail ? `: ${f.detail}` : ""})`,
|
|
971
|
+
invalid_envelope: (label) => `answered ${label} with JSON that is not a valid MCP response (invalid envelope)`
|
|
972
|
+
};
|
|
973
|
+
var Router = class {
|
|
974
|
+
http = null;
|
|
975
|
+
disposed = false;
|
|
976
|
+
retiring = false;
|
|
977
|
+
outstanding = /* @__PURE__ */ new Map();
|
|
978
|
+
parentTimer = null;
|
|
979
|
+
start() {
|
|
980
|
+
if (process.env.PRISM_REMOTE_URL && process.env.PRISM_REMOTE_URL !== REMOTE_URL) {
|
|
981
|
+
this.onRemoteRefusal({
|
|
982
|
+
code: "unsupported_remote",
|
|
983
|
+
product: "prism",
|
|
984
|
+
retryable: false,
|
|
985
|
+
message: "This Prism client only connects to its authenticated production service. Remove PRISM_REMOTE_URL and reconnect."
|
|
986
|
+
});
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
if (!REMOTE_ENABLED) {
|
|
990
|
+
this.onRemoteRefusal({
|
|
991
|
+
code: "remote_required",
|
|
992
|
+
product: "prism",
|
|
993
|
+
retryable: false,
|
|
994
|
+
message: "Prism requires its remote service. Remove PRISM_REMOTE_DISABLE and reconnect Prism."
|
|
995
|
+
});
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
this.http = new HttpBackend({
|
|
999
|
+
onLine: (line) => this.onBackendLine(line),
|
|
1000
|
+
onRequestFailure: (id, failure) => this.failRequest(id, failure),
|
|
1001
|
+
onSessionLost: (status, id) => this.onRemoteRefusal({
|
|
1002
|
+
code: "remote_unavailable",
|
|
1003
|
+
product: "prism",
|
|
1004
|
+
retryable: false,
|
|
1005
|
+
outcomeUnknown: true,
|
|
1006
|
+
backend: "remote",
|
|
1007
|
+
cause: "http_status",
|
|
1008
|
+
httpStatus: status,
|
|
1009
|
+
message: `Prism remote answered HTTP ${status}: it no longer knows this MCP session. Reconnect Prism to start a new one. The request outcome is unknown; it was not replayed. Check its result before retrying.`
|
|
1010
|
+
}, id),
|
|
1011
|
+
onRefusal: (failure, repliedId) => this.onRemoteRefusal(failure, repliedId),
|
|
1012
|
+
onRefusalHeaders: () => {
|
|
1013
|
+
this.retiring = true;
|
|
1014
|
+
},
|
|
1015
|
+
isPending: (id) => this.outstanding.has(id),
|
|
1016
|
+
onDispatch: (id) => {
|
|
1017
|
+
const entry = this.outstanding.get(id);
|
|
1018
|
+
if (entry) entry.sent = true;
|
|
1019
|
+
}
|
|
1020
|
+
});
|
|
1021
|
+
this.http.start();
|
|
1022
|
+
logErr(`using the remote Prism transport; ${shimIdentity()} deadline=${DEFAULT_DEADLINE_MS}ms fallback=none`);
|
|
1023
|
+
}
|
|
1024
|
+
dispose() {
|
|
1025
|
+
this.disposed = true;
|
|
1026
|
+
if (this.parentTimer) {
|
|
1027
|
+
clearInterval(this.parentTimer);
|
|
1028
|
+
this.parentTimer = null;
|
|
1029
|
+
}
|
|
1030
|
+
for (const entry of this.outstanding.values()) clearTimeout(entry.timer);
|
|
1031
|
+
this.http?.stop();
|
|
1032
|
+
}
|
|
1033
|
+
endInput() {
|
|
1034
|
+
if (this.retiring) return;
|
|
1035
|
+
void this.http?.drain().then(() => {
|
|
1036
|
+
if (this.disposed || this.retiring) return;
|
|
1037
|
+
this.dispose();
|
|
1038
|
+
process.exitCode = 0;
|
|
1039
|
+
process.stdout.write("", () => process.exit(0));
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
handleClientMessage(message) {
|
|
1043
|
+
if (this.disposed) return;
|
|
1044
|
+
let obj = null;
|
|
1045
|
+
try {
|
|
1046
|
+
obj = JSON.parse(message);
|
|
1047
|
+
} catch {
|
|
1048
|
+
}
|
|
1049
|
+
if (Array.isArray(obj)) {
|
|
1050
|
+
this.refuseBatch(obj);
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
const isRequest = !!obj && obj.id !== void 0 && obj.id !== null && !!obj.method;
|
|
1054
|
+
let deadlineMs = NOTIFICATION_DEADLINE_MS;
|
|
1055
|
+
if (isRequest && !this.outstanding.has(obj.id)) {
|
|
1056
|
+
deadlineMs = deadlineFor(obj);
|
|
1057
|
+
const id = obj.id;
|
|
1058
|
+
const entry = {
|
|
1059
|
+
label: requestLabel(obj),
|
|
1060
|
+
receivedAt: Date.now(),
|
|
1061
|
+
deadlineMs,
|
|
1062
|
+
sent: false,
|
|
1063
|
+
// Backstop: answers the client by itself whatever the transport is doing. The
|
|
1064
|
+
// transport's own deadline race fires first and classifies the outcome
|
|
1065
|
+
// (a sign-in refusal in the headers is not a timeout); this fires only if it did not.
|
|
1066
|
+
timer: setTimeout(() => this.failRequest(id, { cause: "timeout", sent: entry.sent, backend: "none" }), deadlineMs + BACKSTOP_GRACE_MS)
|
|
1067
|
+
};
|
|
1068
|
+
this.outstanding.set(id, entry);
|
|
1069
|
+
}
|
|
1070
|
+
if (!this.retiring) this.http?.send(message, isRequest ? obj.id : void 0, Date.now() + deadlineMs);
|
|
1071
|
+
}
|
|
1072
|
+
// MCP has no JSON-RPC batches (2025-06-18) and the service refuses them, so a batch is
|
|
1073
|
+
// answered here, request by request, and nothing is sent: nothing ran, so a retry is safe.
|
|
1074
|
+
refuseBatch(batch) {
|
|
1075
|
+
const message = "Prism does not accept JSON-RPC batches; send each request as its own message.";
|
|
1076
|
+
const data = {
|
|
1077
|
+
code: "batch_not_supported",
|
|
1078
|
+
cause: "invalid_request",
|
|
1079
|
+
product: "prism",
|
|
1080
|
+
retryable: true,
|
|
1081
|
+
outcomeUnknown: false,
|
|
1082
|
+
backend: "none",
|
|
1083
|
+
target: "remote",
|
|
1084
|
+
fallback: NO_FALLBACK,
|
|
1085
|
+
message
|
|
1086
|
+
};
|
|
1087
|
+
const ids = batch.filter((item) => item && typeof item === "object" && item.method && item.id !== void 0 && item.id !== null).map((item) => item.id);
|
|
1088
|
+
logErr(`refused a JSON-RPC batch of ${batch.length} message(s)`);
|
|
1089
|
+
for (const id of ids.length ? ids : [null]) {
|
|
1090
|
+
writeClient(JSON.stringify({ jsonrpc: "2.0", id, error: { code: -32600, message: `[Prism backend=none] ${message}`, data } }));
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
settle(id) {
|
|
1094
|
+
const entry = this.outstanding.get(id);
|
|
1095
|
+
if (!entry) return void 0;
|
|
1096
|
+
clearTimeout(entry.timer);
|
|
1097
|
+
this.outstanding.delete(id);
|
|
1098
|
+
return entry;
|
|
1099
|
+
}
|
|
1100
|
+
// Answer one request with a typed error; the connection stays open.
|
|
1101
|
+
failRequest(id, failure) {
|
|
1102
|
+
if (this.disposed) return;
|
|
1103
|
+
const entry = this.settle(id);
|
|
1104
|
+
if (!entry) return;
|
|
1105
|
+
const seconds = String(Math.round(entry.deadlineMs / 1e3));
|
|
1106
|
+
const outcome = failure.sent ? "The request outcome is unknown; it was not replayed. Check its result before retrying." : "Nothing was sent to Prism, so nothing ran; it is safe to retry.";
|
|
1107
|
+
const message = `Prism remote ${FAILURE_TEXT[failure.cause](entry.label, failure, seconds)}. ${outcome} No local fallback was used: this client is remote-only.`;
|
|
1108
|
+
logErr(`${entry.label} failed: ${failure.cause}${failure.httpStatus ? ` HTTP ${failure.httpStatus}` : ""} after ${Date.now() - entry.receivedAt}ms`, failure.backend);
|
|
1109
|
+
writeClient(JSON.stringify({
|
|
1110
|
+
jsonrpc: "2.0",
|
|
1111
|
+
id,
|
|
1112
|
+
error: {
|
|
1113
|
+
code: failure.sent ? -32002 : -32001,
|
|
1114
|
+
message: `[Prism backend=${failure.backend}] ${message}`,
|
|
1115
|
+
data: {
|
|
1116
|
+
code: failure.cause === "timeout" ? "remote_timeout" : "remote_unavailable",
|
|
1117
|
+
cause: failure.cause,
|
|
1118
|
+
product: "prism",
|
|
1119
|
+
retryable: !failure.sent,
|
|
1120
|
+
outcomeUnknown: failure.sent,
|
|
1121
|
+
backend: failure.backend,
|
|
1122
|
+
target: "remote",
|
|
1123
|
+
request: entry.label,
|
|
1124
|
+
elapsedMs: Date.now() - entry.receivedAt,
|
|
1125
|
+
deadlineMs: entry.deadlineMs,
|
|
1126
|
+
...failure.httpStatus ? { httpStatus: failure.httpStatus } : {},
|
|
1127
|
+
...failure.contentType ? { contentType: failure.contentType.slice(0, 100) } : {},
|
|
1128
|
+
fallback: NO_FALLBACK,
|
|
1129
|
+
message
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
}));
|
|
1133
|
+
}
|
|
1134
|
+
onBackendLine(line) {
|
|
1135
|
+
if (this.disposed || this.retiring) return;
|
|
1136
|
+
let msg;
|
|
1137
|
+
try {
|
|
1138
|
+
msg = JSON.parse(line);
|
|
1139
|
+
} catch {
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
const isResponse = msg && msg.id !== void 0 && msg.id !== null && (msg.result !== void 0 || msg.error !== void 0);
|
|
1143
|
+
if (isResponse && !this.outstanding.has(msg.id)) {
|
|
1144
|
+
logErr("dropped a late response for a request that was already answered", "remote");
|
|
1145
|
+
return;
|
|
1146
|
+
}
|
|
1147
|
+
let attributed;
|
|
1148
|
+
try {
|
|
1149
|
+
attributed = JSON.stringify(attributePrismMessage(msg, "remote"));
|
|
1150
|
+
} catch {
|
|
1151
|
+
if (isResponse) this.failRequest(msg.id, { cause: "invalid_envelope", sent: true, backend: "remote" });
|
|
1152
|
+
return;
|
|
1153
|
+
}
|
|
1154
|
+
if (isResponse) {
|
|
1155
|
+
this.settle(msg.id);
|
|
1156
|
+
logErr("MCP response", "remote");
|
|
1157
|
+
}
|
|
1158
|
+
writeClient(attributed);
|
|
1159
|
+
}
|
|
1160
|
+
onRemoteRefusal(failure, repliedId) {
|
|
1161
|
+
if (this.disposed) return;
|
|
1162
|
+
this.retiring = true;
|
|
1163
|
+
const backend = failure.backend ?? "none";
|
|
1164
|
+
const replies = [...this.outstanding.keys()].map((id) => {
|
|
1165
|
+
const servedBy = id === repliedId ? backend : "none";
|
|
1166
|
+
return JSON.stringify({
|
|
1167
|
+
jsonrpc: "2.0",
|
|
1168
|
+
id,
|
|
1169
|
+
error: {
|
|
1170
|
+
code: failure.outcomeUnknown ? -32002 : -32001,
|
|
1171
|
+
message: `[Prism backend=${servedBy}] ${failure.message}`,
|
|
1172
|
+
data: { ...failure, backend: servedBy, target: "remote", fallback: NO_FALLBACK }
|
|
1173
|
+
}
|
|
1174
|
+
});
|
|
1175
|
+
});
|
|
1176
|
+
this.dispose();
|
|
1177
|
+
this.outstanding.clear();
|
|
1178
|
+
process.stdin.pause();
|
|
1179
|
+
process.exitCode = 1;
|
|
1180
|
+
try {
|
|
1181
|
+
if (replies.length) {
|
|
1182
|
+
logErr(`${failure.code}: ${failure.message}`, backend);
|
|
1183
|
+
process.stdout.write(replies.join("\n") + "\n", () => process.exit(1));
|
|
1184
|
+
} else {
|
|
1185
|
+
process.stderr.write(`prism-shim: backend=${backend} target=remote ${failure.code}: ${failure.message}
|
|
1186
|
+
`, () => process.exit(1));
|
|
1187
|
+
}
|
|
1188
|
+
} catch {
|
|
1189
|
+
process.exit(1);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
};
|
|
1193
|
+
var ClientPump = class {
|
|
1194
|
+
constructor(onMessage, onEnd) {
|
|
1195
|
+
this.onMessage = onMessage;
|
|
1196
|
+
this.onEnd = onEnd;
|
|
1197
|
+
}
|
|
1198
|
+
buf = Buffer.alloc(0);
|
|
1199
|
+
framing = null;
|
|
1200
|
+
listening = false;
|
|
1201
|
+
start() {
|
|
1202
|
+
if (this.listening) return;
|
|
1203
|
+
this.listening = true;
|
|
1204
|
+
process.stdin.on("data", (chunk) => this.onData(chunk));
|
|
1205
|
+
process.stdin.on("end", () => this.onEnd());
|
|
1206
|
+
process.stdin.resume();
|
|
1207
|
+
}
|
|
1208
|
+
onData(chunk) {
|
|
1209
|
+
const newSize = this.buf.length + chunk.length;
|
|
1210
|
+
if (newSize > MAX_STDIN_BUFFER) {
|
|
1211
|
+
logErr(`stdin buffer exceeded ${MAX_STDIN_BUFFER} bytes, dropping oldest messages`);
|
|
1212
|
+
const combined = Buffer.concat([this.buf, chunk]);
|
|
1213
|
+
const overflow = combined.length - MAX_STDIN_BUFFER;
|
|
1214
|
+
const dropTo = combined.indexOf(10, overflow);
|
|
1215
|
+
this.buf = dropTo < 0 ? Buffer.alloc(0) : combined.subarray(dropTo + 1);
|
|
1216
|
+
return;
|
|
1217
|
+
}
|
|
1218
|
+
this.buf = Buffer.concat([this.buf, chunk]);
|
|
1219
|
+
this.parse();
|
|
1220
|
+
}
|
|
1221
|
+
parse() {
|
|
1222
|
+
while (this.buf.length > 0) {
|
|
1223
|
+
if (this.framing === null) {
|
|
1224
|
+
const nl = this.buf.indexOf(10);
|
|
1225
|
+
if (nl < 0) return;
|
|
1226
|
+
const first = this.buf.subarray(0, nl).toString().trim();
|
|
1227
|
+
if (first === "") {
|
|
1228
|
+
this.buf = this.buf.subarray(nl + 1);
|
|
1229
|
+
continue;
|
|
1230
|
+
}
|
|
1231
|
+
this.framing = first.toLowerCase().startsWith("content-length:") ? "content-length" : "newline";
|
|
1232
|
+
continue;
|
|
1233
|
+
}
|
|
1234
|
+
if (this.framing === "newline") {
|
|
1235
|
+
const nl = this.buf.indexOf(10);
|
|
1236
|
+
if (nl < 0) return;
|
|
1237
|
+
const line = this.buf.subarray(0, nl).toString().trim();
|
|
1238
|
+
this.buf = this.buf.subarray(nl + 1);
|
|
1239
|
+
if (line) this.onMessage(line);
|
|
1240
|
+
continue;
|
|
1241
|
+
}
|
|
1242
|
+
const headerEnd = this.buf.indexOf("\r\n\r\n");
|
|
1243
|
+
if (headerEnd < 0) return;
|
|
1244
|
+
const headerBlock = this.buf.subarray(0, headerEnd).toString();
|
|
1245
|
+
let contentLength = -1;
|
|
1246
|
+
for (const h of headerBlock.split(/\r?\n/)) {
|
|
1247
|
+
if (h.toLowerCase().startsWith("content-length:")) {
|
|
1248
|
+
contentLength = parseInt(h.split(":")[1].trim(), 10);
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
if (contentLength < 0 || !Number.isFinite(contentLength)) {
|
|
1252
|
+
this.buf = this.buf.subarray(headerEnd + 4);
|
|
1253
|
+
continue;
|
|
1254
|
+
}
|
|
1255
|
+
const bodyStart = headerEnd + 4;
|
|
1256
|
+
if (this.buf.length < bodyStart + contentLength) return;
|
|
1257
|
+
const body = this.buf.subarray(bodyStart, bodyStart + contentLength).toString().trim();
|
|
1258
|
+
this.buf = this.buf.subarray(bodyStart + contentLength);
|
|
1259
|
+
if (body) this.onMessage(body);
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
};
|
|
1263
|
+
function startParentMonitoring(onDead) {
|
|
1264
|
+
const parentPid = process.ppid;
|
|
1265
|
+
if (parentPid <= 1) {
|
|
1266
|
+
logErr(`started with no parent (ppid=${parentPid}), exiting`);
|
|
1267
|
+
onDead();
|
|
1268
|
+
process.exit(0);
|
|
1269
|
+
}
|
|
1270
|
+
const t = setInterval(() => {
|
|
1271
|
+
try {
|
|
1272
|
+
process.kill(parentPid, 0);
|
|
1273
|
+
} catch (e) {
|
|
1274
|
+
if (e?.code === "ESRCH") {
|
|
1275
|
+
logErr("parent process died, shutting down");
|
|
1276
|
+
onDead();
|
|
1277
|
+
process.exit(0);
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
}, PARENT_CHECK_INTERVAL_MS);
|
|
1281
|
+
t.unref();
|
|
1282
|
+
return t;
|
|
1283
|
+
}
|
|
1284
|
+
var router;
|
|
1285
|
+
function main() {
|
|
1286
|
+
process.stdout.on("error", () => {
|
|
1287
|
+
router?.dispose();
|
|
1288
|
+
process.exit(0);
|
|
1289
|
+
});
|
|
1290
|
+
process.stderr.on("error", () => {
|
|
1291
|
+
});
|
|
1292
|
+
const shutdown = (signal) => {
|
|
1293
|
+
logErr(`received ${signal}, shutting down`);
|
|
1294
|
+
router?.dispose();
|
|
1295
|
+
process.exit(0);
|
|
1296
|
+
};
|
|
1297
|
+
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
1298
|
+
process.on("SIGINT", () => shutdown("SIGINT"));
|
|
1299
|
+
process.on("SIGHUP", () => shutdown("SIGHUP"));
|
|
1300
|
+
recordRunningBuild();
|
|
1301
|
+
router = new Router();
|
|
1302
|
+
router.parentTimer = startParentMonitoring(() => router?.dispose());
|
|
1303
|
+
const pump = new ClientPump(
|
|
1304
|
+
(message) => router.handleClientMessage(message),
|
|
1305
|
+
() => router?.endInput()
|
|
1306
|
+
);
|
|
1307
|
+
pump.start();
|
|
1308
|
+
router.start();
|
|
1309
|
+
}
|
|
1310
|
+
if (["login", "--sign-in"].includes(process.argv[2])) {
|
|
1311
|
+
const args = process.argv.slice(3);
|
|
1312
|
+
const usage = "Usage: prism login [--legacy] [--machine-name NAME]";
|
|
1313
|
+
let legacy = false;
|
|
1314
|
+
let machineName2;
|
|
1315
|
+
let login = true;
|
|
1316
|
+
for (let index = 0; index < args.length; index++) {
|
|
1317
|
+
const arg = args[index];
|
|
1318
|
+
if (arg === "--legacy" && !legacy) legacy = true;
|
|
1319
|
+
else if (arg === "--machine-name" && machineName2 === void 0 && index + 1 < args.length) machineName2 = args[++index];
|
|
1320
|
+
else if (arg.startsWith("--machine-name=") && machineName2 === void 0) machineName2 = arg.slice("--machine-name=".length);
|
|
1321
|
+
else login = false;
|
|
1322
|
+
}
|
|
1323
|
+
(login ? signInPrism(AUTH_PATH, (message) => process.stdout.write(message + "\n"), legacy, machineName2) : Promise.reject(new Error(usage))).catch((error) => {
|
|
1324
|
+
const code = error instanceof Error && Object.hasOwn(error, "code") ? error.code : "";
|
|
1325
|
+
const message = Object.hasOwn(AUTH_MESSAGES, code) ? AUTH_MESSAGES[code] : code === "login_expired" ? "This Prism sign-in expired. Run prism login again." : "Prism sign-in did not complete. Your saved credential was retained.";
|
|
1326
|
+
logErr(login ? message : usage);
|
|
1327
|
+
process.exitCode = 1;
|
|
1328
|
+
});
|
|
1329
|
+
} else main();
|