@forklaunch/core 3.3.0 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/gateway-mock/routes/payments.mjs +47 -0
- package/lib/agent/agent.d.ts +26 -0
- package/lib/agent/agent.d.ts.map +1 -0
- package/lib/agent/continuation.d.ts +29 -0
- package/lib/agent/continuation.d.ts.map +1 -0
- package/lib/agent/index.d.ts +8 -0
- package/lib/agent/index.d.ts.map +1 -0
- package/lib/agent/index.js +1049 -0
- package/lib/agent/index.js.map +1 -0
- package/lib/agent/index.mjs +1005 -0
- package/lib/agent/index.mjs.map +1 -0
- package/lib/agent/sources.d.ts +27 -0
- package/lib/agent/sources.d.ts.map +1 -0
- package/lib/agent/tools.d.ts +39 -0
- package/lib/agent/tools.d.ts.map +1 -0
- package/lib/agent/types.d.ts +130 -0
- package/lib/agent/types.d.ts.map +1 -0
- package/lib/http/index.d.ts +2 -0
- package/lib/http/index.d.ts.map +1 -1
- package/lib/http/index.js +430 -51
- package/lib/http/index.js.map +1 -1
- package/lib/http/index.mjs +425 -51
- package/lib/http/index.mjs.map +1 -1
- package/lib/http/localModelGatewayClient.d.ts +27 -0
- package/lib/http/localModelGatewayClient.d.ts.map +1 -0
- package/lib/http/mcpGenerator/mcpGenerator.d.ts.map +1 -1
- package/lib/http/mcpGenerator/mcpHttpHandler.d.ts +57 -0
- package/lib/http/mcpGenerator/mcpHttpHandler.d.ts.map +1 -0
- package/lib/http/modelGatewayClient.d.ts.map +1 -1
- package/lib/http/modelStream.d.ts +4 -0
- package/lib/http/modelStream.d.ts.map +1 -0
- package/lib/http/paymentsClient.d.ts +55 -1
- package/lib/http/paymentsClient.d.ts.map +1 -1
- package/lib/http/previewModelGatewayClient.d.ts +5 -1
- package/lib/http/previewModelGatewayClient.d.ts.map +1 -1
- package/lib/http/telemetry/openTelemetryCollector.d.ts.map +1 -1
- package/lib/http/types/expressLikeOptions.d.ts +12 -0
- package/lib/http/types/expressLikeOptions.d.ts.map +1 -1
- package/lib/persistence/compliantField.d.ts.map +1 -1
- package/lib/persistence/index.js +6 -1
- package/lib/persistence/index.js.map +1 -1
- package/lib/persistence/index.mjs +6 -1
- package/lib/persistence/index.mjs.map +1 -1
- package/package.json +33 -26
package/lib/http/index.js
CHANGED
|
@@ -38,6 +38,7 @@ __export(http_exports, {
|
|
|
38
38
|
ATTR_HTTP_ROUTE: () => import_semantic_conventions.ATTR_HTTP_ROUTE,
|
|
39
39
|
ATTR_SERVICE_NAME: () => import_semantic_conventions.ATTR_SERVICE_NAME,
|
|
40
40
|
AuditLogger: () => AuditLogger,
|
|
41
|
+
DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS: () => DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS,
|
|
41
42
|
EMAIL_LIMITS: () => EMAIL_LIMITS,
|
|
42
43
|
EmailRequestError: () => EmailRequestError,
|
|
43
44
|
ForklaunchExpressLikeApplication: () => ForklaunchExpressLikeApplication,
|
|
@@ -71,6 +72,8 @@ __export(http_exports, {
|
|
|
71
72
|
createEmailClient: () => createEmailClient,
|
|
72
73
|
createHmacToken: () => createHmacToken,
|
|
73
74
|
createInstanceGatewayTransport: () => createInstanceGatewayTransport,
|
|
75
|
+
createLocalModelGatewayClient: () => createLocalModelGatewayClient,
|
|
76
|
+
createMcpHttpHandler: () => createMcpHttpHandler,
|
|
74
77
|
createModelGatewayClient: () => createModelGatewayClient,
|
|
75
78
|
createPaymentsClient: () => createPaymentsClient,
|
|
76
79
|
createPreviewModelGatewayClient: () => createPreviewModelGatewayClient,
|
|
@@ -91,6 +94,7 @@ __export(http_exports, {
|
|
|
91
94
|
get: () => get,
|
|
92
95
|
getCachedJwks: () => getCachedJwks,
|
|
93
96
|
getCodeForStatus: () => getCodeForStatus,
|
|
97
|
+
getMcpTransportHeaders: () => getMcpTransportHeaders,
|
|
94
98
|
head: () => head,
|
|
95
99
|
httpErrorsTotalCounter: () => httpErrorsTotalCounter,
|
|
96
100
|
httpRequestDurationMsHistogram: () => httpRequestDurationMsHistogram,
|
|
@@ -107,6 +111,7 @@ __export(http_exports, {
|
|
|
107
111
|
isManagedInstance: () => isManagedInstance,
|
|
108
112
|
isPortBound: () => isPortBound,
|
|
109
113
|
isRedirection: () => isRedirection,
|
|
114
|
+
isSeparateMcpListener: () => isSeparateMcpListener,
|
|
110
115
|
isServerError: () => isServerError,
|
|
111
116
|
isSuccessful: () => isSuccessful,
|
|
112
117
|
isValidStatusCode: () => isValidStatusCode,
|
|
@@ -569,13 +574,15 @@ new import_sdk_node.NodeSDK({
|
|
|
569
574
|
url: `${(0, import_common3.getEnvVar)("OTEL_EXPORTER_OTLP_ENDPOINT") ?? "http://localhost:4318"}/v1/traces`,
|
|
570
575
|
headers: otelHeaders
|
|
571
576
|
}),
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
577
|
+
metricReaders: [
|
|
578
|
+
new import_sdk_metrics.PeriodicExportingMetricReader({
|
|
579
|
+
exporter: new import_exporter_metrics_otlp_http.OTLPMetricExporter({
|
|
580
|
+
url: `${(0, import_common3.getEnvVar)("OTEL_EXPORTER_OTLP_ENDPOINT") ?? "http://localhost:4318"}/v1/metrics`,
|
|
581
|
+
headers: otelHeaders
|
|
582
|
+
}),
|
|
583
|
+
exportIntervalMillis: 5e3
|
|
584
|
+
})
|
|
585
|
+
],
|
|
579
586
|
logRecordProcessors: [
|
|
580
587
|
new import_sdk_logs.BatchLogRecordProcessor({
|
|
581
588
|
exporter: new import_exporter_logs_otlp_http.OTLPLogExporter({
|
|
@@ -2978,12 +2985,55 @@ function signPlatformEvent(params) {
|
|
|
2978
2985
|
});
|
|
2979
2986
|
}
|
|
2980
2987
|
|
|
2988
|
+
// src/http/modelStream.ts
|
|
2989
|
+
async function* readModelStream(response) {
|
|
2990
|
+
const reader = response.body?.getReader();
|
|
2991
|
+
if (!reader)
|
|
2992
|
+
throw new ModelGatewayRequestError(502, "The model stream is empty.");
|
|
2993
|
+
const decoder = new TextDecoder();
|
|
2994
|
+
let buffer = "", bytes = 0;
|
|
2995
|
+
try {
|
|
2996
|
+
for (; ; ) {
|
|
2997
|
+
const part = await reader.read();
|
|
2998
|
+
if (part.done) break;
|
|
2999
|
+
bytes += part.value.byteLength;
|
|
3000
|
+
if (bytes > 512e3) throw new Error("oversized");
|
|
3001
|
+
buffer += decoder.decode(part.value, { stream: true });
|
|
3002
|
+
let match;
|
|
3003
|
+
while (match = buffer.match(/\r?\n\r?\n/)) {
|
|
3004
|
+
const event = buffer.slice(0, match.index);
|
|
3005
|
+
buffer = buffer.slice(match.index + match[0].length);
|
|
3006
|
+
const data = event.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
|
|
3007
|
+
if (!data) continue;
|
|
3008
|
+
if (data === "[DONE]") return;
|
|
3009
|
+
const value = JSON.parse(data);
|
|
3010
|
+
if (value.error || !Array.isArray(value.choices))
|
|
3011
|
+
throw new Error("invalid");
|
|
3012
|
+
yield value;
|
|
3013
|
+
}
|
|
3014
|
+
}
|
|
3015
|
+
throw new Error("interrupted");
|
|
3016
|
+
} catch {
|
|
3017
|
+
throw new ModelGatewayRequestError(
|
|
3018
|
+
502,
|
|
3019
|
+
"The model stream was interrupted. No automatic retry was sent."
|
|
3020
|
+
);
|
|
3021
|
+
} finally {
|
|
3022
|
+
await reader.cancel().catch(() => {
|
|
3023
|
+
});
|
|
3024
|
+
reader.releaseLock();
|
|
3025
|
+
}
|
|
3026
|
+
}
|
|
3027
|
+
|
|
2981
3028
|
// src/http/modelGatewayClient.ts
|
|
2982
3029
|
var ModelGatewayRequestError = class extends InstanceGatewayRequestError {
|
|
2983
3030
|
name = "ModelGatewayRequestError";
|
|
2984
3031
|
};
|
|
2985
3032
|
function createModelGatewayClient(options2 = {}) {
|
|
2986
|
-
const transport = createInstanceGatewayTransport(
|
|
3033
|
+
const transport = createInstanceGatewayTransport(
|
|
3034
|
+
options2,
|
|
3035
|
+
"The model gateway"
|
|
3036
|
+
);
|
|
2987
3037
|
async function send(method, route, body, signal) {
|
|
2988
3038
|
try {
|
|
2989
3039
|
return await transport.request(method, route, body, { signal });
|
|
@@ -3019,42 +3069,12 @@ function createModelGatewayClient(options2 = {}) {
|
|
|
3019
3069
|
request,
|
|
3020
3070
|
streamOptions.signal
|
|
3021
3071
|
);
|
|
3022
|
-
|
|
3023
|
-
for await (const data of sseData(response.body)) {
|
|
3024
|
-
if (data === "[DONE]") return;
|
|
3025
|
-
try {
|
|
3026
|
-
yield JSON.parse(data);
|
|
3027
|
-
} catch {
|
|
3028
|
-
}
|
|
3029
|
-
}
|
|
3072
|
+
yield* readModelStream(response);
|
|
3030
3073
|
}
|
|
3031
3074
|
}
|
|
3032
3075
|
}
|
|
3033
3076
|
};
|
|
3034
3077
|
}
|
|
3035
|
-
async function* sseData(stream) {
|
|
3036
|
-
const decoder = new TextDecoder();
|
|
3037
|
-
let buffer = "";
|
|
3038
|
-
const reader = stream.getReader();
|
|
3039
|
-
try {
|
|
3040
|
-
for (; ; ) {
|
|
3041
|
-
const { value, done } = await reader.read();
|
|
3042
|
-
if (done) break;
|
|
3043
|
-
buffer += decoder.decode(value, { stream: true });
|
|
3044
|
-
let boundary;
|
|
3045
|
-
while ((boundary = buffer.search(/\r?\n\r?\n/)) !== -1) {
|
|
3046
|
-
const event = buffer.slice(0, boundary);
|
|
3047
|
-
buffer = buffer.slice(boundary).replace(/^\r?\n\r?\n/, "");
|
|
3048
|
-
const data = event.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
|
|
3049
|
-
if (data) yield data;
|
|
3050
|
-
}
|
|
3051
|
-
}
|
|
3052
|
-
const tail = buffer.trim();
|
|
3053
|
-
if (tail.startsWith("data:")) yield tail.slice(5).trimStart();
|
|
3054
|
-
} finally {
|
|
3055
|
-
reader.releaseLock();
|
|
3056
|
-
}
|
|
3057
|
-
}
|
|
3058
3078
|
|
|
3059
3079
|
// src/http/previewModelGatewayClient.ts
|
|
3060
3080
|
function record(value) {
|
|
@@ -3110,9 +3130,9 @@ function createPreviewModelGatewayClient(options2 = {}) {
|
|
|
3110
3130
|
options2,
|
|
3111
3131
|
"The local preview model gateway"
|
|
3112
3132
|
);
|
|
3113
|
-
async function send(method, route, body) {
|
|
3133
|
+
async function send(method, route, body, signal) {
|
|
3114
3134
|
try {
|
|
3115
|
-
return await transport.request(method, route, body);
|
|
3135
|
+
return await transport.request(method, route, body, { signal });
|
|
3116
3136
|
} catch (error) {
|
|
3117
3137
|
if (error instanceof InstanceGatewayRequestError)
|
|
3118
3138
|
throw new ModelGatewayRequestError(
|
|
@@ -3130,6 +3150,15 @@ function createPreviewModelGatewayClient(options2 = {}) {
|
|
|
3130
3150
|
},
|
|
3131
3151
|
chat: {
|
|
3132
3152
|
completions: {
|
|
3153
|
+
async *stream(request, options3 = {}) {
|
|
3154
|
+
const response = await send(
|
|
3155
|
+
"POST",
|
|
3156
|
+
"/models/chat/completions",
|
|
3157
|
+
{ ...request, stream: true },
|
|
3158
|
+
options3.signal
|
|
3159
|
+
);
|
|
3160
|
+
yield* readModelStream(response);
|
|
3161
|
+
},
|
|
3133
3162
|
async create(request) {
|
|
3134
3163
|
return await (await send(
|
|
3135
3164
|
"POST",
|
|
@@ -3664,6 +3693,19 @@ function createPaymentsClient(options2 = {}) {
|
|
|
3664
3693
|
},
|
|
3665
3694
|
status() {
|
|
3666
3695
|
return call("GET", "/payments/status");
|
|
3696
|
+
},
|
|
3697
|
+
payouts(params = {}) {
|
|
3698
|
+
const { limit } = params;
|
|
3699
|
+
if (limit !== void 0 && (!Number.isInteger(limit) || limit < 1 || limit > 50)) {
|
|
3700
|
+
throw new TypeError("limit must be a whole number from 1 to 50");
|
|
3701
|
+
}
|
|
3702
|
+
return call(
|
|
3703
|
+
"GET",
|
|
3704
|
+
limit === void 0 ? "/payments/payouts" : `/payments/payouts?limit=${limit}`
|
|
3705
|
+
);
|
|
3706
|
+
},
|
|
3707
|
+
dashboardLink() {
|
|
3708
|
+
return call("POST", "/payments/dashboard-link", {});
|
|
3667
3709
|
}
|
|
3668
3710
|
};
|
|
3669
3711
|
}
|
|
@@ -3748,8 +3790,8 @@ function createStripeClient(options2 = {}) {
|
|
|
3748
3790
|
return new StripeClass(options2.apiKey, options2.config);
|
|
3749
3791
|
}
|
|
3750
3792
|
const settings = instanceGatewaySettings(options2, "Payments");
|
|
3751
|
-
const
|
|
3752
|
-
const protocol =
|
|
3793
|
+
const gateway2 = new URL(settings.gatewayUrl);
|
|
3794
|
+
const protocol = gateway2.protocol === "http:" ? "http" : "https";
|
|
3753
3795
|
return new StripeClass(
|
|
3754
3796
|
// No key: the authenticator below replaces it, and the gateway holds the
|
|
3755
3797
|
// real one. (stripe-node accepts an authenticator in place of a key.)
|
|
@@ -3757,8 +3799,8 @@ function createStripeClient(options2 = {}) {
|
|
|
3757
3799
|
{
|
|
3758
3800
|
maxNetworkRetries: 2,
|
|
3759
3801
|
...options2.config,
|
|
3760
|
-
host:
|
|
3761
|
-
port:
|
|
3802
|
+
host: gateway2.hostname,
|
|
3803
|
+
port: gateway2.port || (protocol === "http" ? 80 : 443),
|
|
3762
3804
|
protocol,
|
|
3763
3805
|
telemetry: false,
|
|
3764
3806
|
// The signed fetch sets `authorization`; nothing else may.
|
|
@@ -4863,6 +4905,182 @@ function unpackRouters(routers, recursiveBasePath = []) {
|
|
|
4863
4905
|
}, []);
|
|
4864
4906
|
}
|
|
4865
4907
|
|
|
4908
|
+
// src/http/mcpGenerator/mcpHttpHandler.ts
|
|
4909
|
+
var import_webStandardStreamableHttp = require("@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js");
|
|
4910
|
+
var import_async_hooks = require("async_hooks");
|
|
4911
|
+
var import_crypto6 = require("crypto");
|
|
4912
|
+
var DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS = 15 * 60 * 1e3;
|
|
4913
|
+
var mcpTransportHeaders = new import_async_hooks.AsyncLocalStorage();
|
|
4914
|
+
function getMcpTransportHeaders() {
|
|
4915
|
+
return mcpTransportHeaders.getStore();
|
|
4916
|
+
}
|
|
4917
|
+
function createMcpHttpHandler(mcpServer, options2) {
|
|
4918
|
+
const mode = options2?.sessions ?? "stateless";
|
|
4919
|
+
if (mode === "stateful" && (options2?.workerCount ?? 1) > 1) {
|
|
4920
|
+
throw new Error(
|
|
4921
|
+
"Stateful MCP sessions live in one process's memory and cannot be shared across workers. Use mcp.sessions: 'stateless' or a single worker."
|
|
4922
|
+
);
|
|
4923
|
+
}
|
|
4924
|
+
const idleTimeoutMs = options2?.sessionIdleTimeoutMs ?? DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS;
|
|
4925
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
4926
|
+
const jsonRpcError = (status, code, message, headers) => new Response(
|
|
4927
|
+
JSON.stringify({ jsonrpc: "2.0", error: { code, message }, id: null }),
|
|
4928
|
+
{
|
|
4929
|
+
status,
|
|
4930
|
+
headers: { "Content-Type": "application/json", ...headers }
|
|
4931
|
+
}
|
|
4932
|
+
);
|
|
4933
|
+
let sweepTimer;
|
|
4934
|
+
if (mode === "stateful") {
|
|
4935
|
+
sweepTimer = setInterval(
|
|
4936
|
+
() => {
|
|
4937
|
+
const cutoff = Date.now() - idleTimeoutMs;
|
|
4938
|
+
for (const [id, entry] of sessions) {
|
|
4939
|
+
if (entry.lastSeen < cutoff) {
|
|
4940
|
+
sessions.delete(id);
|
|
4941
|
+
entry.session.close().catch(() => void 0);
|
|
4942
|
+
}
|
|
4943
|
+
}
|
|
4944
|
+
},
|
|
4945
|
+
Math.min(idleTimeoutMs, 6e4)
|
|
4946
|
+
);
|
|
4947
|
+
sweepTimer.unref();
|
|
4948
|
+
}
|
|
4949
|
+
async function authenticateRequest(authRequest) {
|
|
4950
|
+
if (!options2?.authenticate) {
|
|
4951
|
+
return { ok: true, auth: void 0 };
|
|
4952
|
+
}
|
|
4953
|
+
try {
|
|
4954
|
+
const auth = await options2.authenticate(authRequest);
|
|
4955
|
+
return auth ? { ok: true, auth } : { ok: false };
|
|
4956
|
+
} catch {
|
|
4957
|
+
return { ok: false };
|
|
4958
|
+
}
|
|
4959
|
+
}
|
|
4960
|
+
async function handleStateless(request, auth) {
|
|
4961
|
+
if (request.method !== "POST") {
|
|
4962
|
+
return jsonRpcError(405, -32e3, "Method not allowed", {
|
|
4963
|
+
Allow: "POST"
|
|
4964
|
+
});
|
|
4965
|
+
}
|
|
4966
|
+
const transport = new import_webStandardStreamableHttp.WebStandardStreamableHTTPServerTransport({
|
|
4967
|
+
sessionIdGenerator: void 0
|
|
4968
|
+
});
|
|
4969
|
+
const session = await mcpServer.connect(transport, auth);
|
|
4970
|
+
let closed = false;
|
|
4971
|
+
const closeSession = () => {
|
|
4972
|
+
if (!closed) {
|
|
4973
|
+
closed = true;
|
|
4974
|
+
session.close().catch(() => void 0);
|
|
4975
|
+
}
|
|
4976
|
+
};
|
|
4977
|
+
try {
|
|
4978
|
+
const response = await mcpTransportHeaders.run(
|
|
4979
|
+
request.headers,
|
|
4980
|
+
() => transport.handleRequest(request)
|
|
4981
|
+
);
|
|
4982
|
+
return closeWhenBodyEnds(response, closeSession);
|
|
4983
|
+
} catch (error) {
|
|
4984
|
+
closeSession();
|
|
4985
|
+
throw error;
|
|
4986
|
+
}
|
|
4987
|
+
}
|
|
4988
|
+
async function handleStateful(request, auth) {
|
|
4989
|
+
const sessionId = request.headers.get("mcp-session-id");
|
|
4990
|
+
if (sessionId) {
|
|
4991
|
+
const entry = sessions.get(sessionId);
|
|
4992
|
+
if (!entry) {
|
|
4993
|
+
return jsonRpcError(404, -32001, "Session not found");
|
|
4994
|
+
}
|
|
4995
|
+
entry.lastSeen = Date.now();
|
|
4996
|
+
if (auth) {
|
|
4997
|
+
entry.session.updateAuth(auth);
|
|
4998
|
+
}
|
|
4999
|
+
return mcpTransportHeaders.run(
|
|
5000
|
+
request.headers,
|
|
5001
|
+
() => entry.transport.handleRequest(request)
|
|
5002
|
+
);
|
|
5003
|
+
}
|
|
5004
|
+
const transport = new import_webStandardStreamableHttp.WebStandardStreamableHTTPServerTransport({
|
|
5005
|
+
sessionIdGenerator: () => (0, import_crypto6.randomUUID)(),
|
|
5006
|
+
onsessioninitialized: (id) => {
|
|
5007
|
+
sessions.set(id, { transport, session, lastSeen: Date.now() });
|
|
5008
|
+
},
|
|
5009
|
+
onsessionclosed: (id) => {
|
|
5010
|
+
sessions.delete(id);
|
|
5011
|
+
}
|
|
5012
|
+
});
|
|
5013
|
+
const session = await mcpServer.connect(transport, auth);
|
|
5014
|
+
transport.onclose = /* @__PURE__ */ ((onclose) => () => {
|
|
5015
|
+
if (transport.sessionId) {
|
|
5016
|
+
sessions.delete(transport.sessionId);
|
|
5017
|
+
}
|
|
5018
|
+
onclose?.();
|
|
5019
|
+
})(transport.onclose);
|
|
5020
|
+
const response = await mcpTransportHeaders.run(
|
|
5021
|
+
request.headers,
|
|
5022
|
+
() => transport.handleRequest(request)
|
|
5023
|
+
);
|
|
5024
|
+
if (!transport.sessionId) {
|
|
5025
|
+
await session.close();
|
|
5026
|
+
}
|
|
5027
|
+
return response;
|
|
5028
|
+
}
|
|
5029
|
+
async function handle(request, authRequest) {
|
|
5030
|
+
const authResult = await authenticateRequest(authRequest);
|
|
5031
|
+
if (!authResult.ok) {
|
|
5032
|
+
return jsonRpcError(401, -32001, "Unauthorized", {
|
|
5033
|
+
"WWW-Authenticate": "Bearer"
|
|
5034
|
+
});
|
|
5035
|
+
}
|
|
5036
|
+
return mode === "stateless" ? handleStateless(request, authResult.auth) : handleStateful(request, authResult.auth);
|
|
5037
|
+
}
|
|
5038
|
+
async function close() {
|
|
5039
|
+
if (sweepTimer) {
|
|
5040
|
+
clearInterval(sweepTimer);
|
|
5041
|
+
}
|
|
5042
|
+
const entries = [...sessions.values()];
|
|
5043
|
+
sessions.clear();
|
|
5044
|
+
await Promise.all(entries.map(({ session }) => session.close()));
|
|
5045
|
+
}
|
|
5046
|
+
return { handle, close, sessions };
|
|
5047
|
+
}
|
|
5048
|
+
function closeWhenBodyEnds(response, done) {
|
|
5049
|
+
if (!response.body) {
|
|
5050
|
+
done();
|
|
5051
|
+
return response;
|
|
5052
|
+
}
|
|
5053
|
+
const reader = response.body.getReader();
|
|
5054
|
+
const body = new ReadableStream({
|
|
5055
|
+
async pull(controller) {
|
|
5056
|
+
try {
|
|
5057
|
+
const { done: finished, value } = await reader.read();
|
|
5058
|
+
if (finished) {
|
|
5059
|
+
controller.close();
|
|
5060
|
+
done();
|
|
5061
|
+
} else {
|
|
5062
|
+
controller.enqueue(value);
|
|
5063
|
+
}
|
|
5064
|
+
} catch (error) {
|
|
5065
|
+
controller.error(error);
|
|
5066
|
+
done();
|
|
5067
|
+
}
|
|
5068
|
+
},
|
|
5069
|
+
cancel(reason) {
|
|
5070
|
+
done();
|
|
5071
|
+
return reader.cancel(reason);
|
|
5072
|
+
}
|
|
5073
|
+
});
|
|
5074
|
+
return new Response(body, {
|
|
5075
|
+
status: response.status,
|
|
5076
|
+
statusText: response.statusText,
|
|
5077
|
+
headers: response.headers
|
|
5078
|
+
});
|
|
5079
|
+
}
|
|
5080
|
+
function isSeparateMcpListener(configuredPort) {
|
|
5081
|
+
return process.env.MCP_LISTENER === "separate" || configuredPort != null || Boolean(Number(process.env.MCP_PORT));
|
|
5082
|
+
}
|
|
5083
|
+
|
|
4866
5084
|
// src/http/mcpGenerator/mcpGenerator.ts
|
|
4867
5085
|
function generateInputSchema(schemaValidator, body, params, query, requestHeaders, auth) {
|
|
4868
5086
|
let discriminatedBody;
|
|
@@ -4892,6 +5110,36 @@ function generateInputSchema(schemaValidator, body, params, query, requestHeader
|
|
|
4892
5110
|
} : {}
|
|
4893
5111
|
});
|
|
4894
5112
|
}
|
|
5113
|
+
function buildRouteHeaders(toolHeaders, contentType) {
|
|
5114
|
+
const transportHeaders = getMcpTransportHeaders();
|
|
5115
|
+
const routeHeaders = new Headers();
|
|
5116
|
+
const authorization = transportHeaders?.get("authorization");
|
|
5117
|
+
if (authorization) {
|
|
5118
|
+
routeHeaders.set("authorization", authorization);
|
|
5119
|
+
}
|
|
5120
|
+
for (const [name, value] of Object.entries(toolHeaders ?? {})) {
|
|
5121
|
+
if (value != null) {
|
|
5122
|
+
routeHeaders.set(name, String(value));
|
|
5123
|
+
}
|
|
5124
|
+
}
|
|
5125
|
+
const correlationId = transportHeaders?.get("x-correlation-id");
|
|
5126
|
+
if (correlationId) {
|
|
5127
|
+
routeHeaders.set("x-correlation-id", correlationId);
|
|
5128
|
+
}
|
|
5129
|
+
const traceparent = transportHeaders?.get("traceparent");
|
|
5130
|
+
if (traceparent) {
|
|
5131
|
+
routeHeaders.set("traceparent", traceparent);
|
|
5132
|
+
routeHeaders.delete("tracestate");
|
|
5133
|
+
const tracestate = transportHeaders?.get("tracestate");
|
|
5134
|
+
if (tracestate) {
|
|
5135
|
+
routeHeaders.set("tracestate", tracestate);
|
|
5136
|
+
}
|
|
5137
|
+
}
|
|
5138
|
+
if (contentType !== void 0) {
|
|
5139
|
+
routeHeaders.set("content-type", contentType);
|
|
5140
|
+
}
|
|
5141
|
+
return routeHeaders;
|
|
5142
|
+
}
|
|
4895
5143
|
function generateMcpServer(schemaValidator, protocol, host, port, version, application, appOptions, options2, contentTypeMap, authenticate) {
|
|
4896
5144
|
if (!(schemaValidator instanceof import_zod.ZodSchemaValidator)) {
|
|
4897
5145
|
throw new Error(
|
|
@@ -5044,12 +5292,10 @@ function generateMcpServer(schemaValidator, protocol, host, port, version, appli
|
|
|
5044
5292
|
}
|
|
5045
5293
|
const response = await fetch(url, {
|
|
5046
5294
|
method: route.method.toUpperCase(),
|
|
5047
|
-
headers:
|
|
5048
|
-
|
|
5049
|
-
|
|
5050
|
-
|
|
5051
|
-
} : {}
|
|
5052
|
-
},
|
|
5295
|
+
headers: buildRouteHeaders(
|
|
5296
|
+
headers,
|
|
5297
|
+
discriminatedBody?.contentType != "multipart/form-data" ? contentType ?? discriminatedBody?.contentType : void 0
|
|
5298
|
+
),
|
|
5053
5299
|
body: parsedBody
|
|
5054
5300
|
});
|
|
5055
5301
|
if (response.status >= 300) {
|
|
@@ -5871,6 +6117,134 @@ function registerDelegatedSurface(surface, mount, register) {
|
|
|
5871
6117
|
}
|
|
5872
6118
|
return register(mount);
|
|
5873
6119
|
}
|
|
6120
|
+
|
|
6121
|
+
// src/http/localModelGatewayClient.ts
|
|
6122
|
+
var import_node_child_process = require("child_process");
|
|
6123
|
+
var import_node_util = require("util");
|
|
6124
|
+
var execute = (0, import_node_util.promisify)(import_node_child_process.execFile);
|
|
6125
|
+
var gateway = "https://studio-orchestrator.forklaunch.com/studio-orchestrator/desktop-runtime-model-gateway";
|
|
6126
|
+
function validate(value) {
|
|
6127
|
+
if (!value || !/^[a-f0-9]{64}$/.test(value.grantId) || !/^[a-f0-9]{64}$/.test(value.capability) || value.gatewayBaseUrl !== `${gateway}/${value.grantId}/v1` || value.scope !== "local-runtime" || !Number.isSafeInteger(value.expiresAt) || value.expiresAt <= Date.now() || value.expiresAt > Date.now() + 9e5 || !/^[A-Za-z0-9._-]{1,128}$/.test(value.model) || !Number.isInteger(value.maxCalls) || value.maxCalls < 1 || value.maxCalls > 20 || !Number.isInteger(value.maxUnits) || value.maxUnits < 1 || value.maxUnits > 1e5) {
|
|
6128
|
+
throw new Error(
|
|
6129
|
+
"Invalid local model connection. No model request was sent."
|
|
6130
|
+
);
|
|
6131
|
+
}
|
|
6132
|
+
return value;
|
|
6133
|
+
}
|
|
6134
|
+
function createLocalModelGatewayClient(options2 = {}) {
|
|
6135
|
+
if (process.env.FORKLAUNCH_API_KEY === void 0 && !options2.credentialProvider && process.env.FORKLAUNCH_LOCAL_MODEL_RELAY === "1") {
|
|
6136
|
+
return createPreviewModelGatewayClient({ fetch: options2.fetch });
|
|
6137
|
+
}
|
|
6138
|
+
const applicationId = options2.applicationId ?? process.env.FORKLAUNCH_APPLICATION_ID;
|
|
6139
|
+
const model = options2.model ?? process.env.AGENT_MODEL;
|
|
6140
|
+
if (applicationId && !/^[a-f0-9-]{36}$/i.test(applicationId)) {
|
|
6141
|
+
throw new Error(
|
|
6142
|
+
"FORKLAUNCH_APPLICATION_ID must be a saved application UUID."
|
|
6143
|
+
);
|
|
6144
|
+
}
|
|
6145
|
+
const provider = options2.credentialProvider ?? (async () => {
|
|
6146
|
+
const args = ["model", "credential", "--json"];
|
|
6147
|
+
if (applicationId) args.push("--application-id", applicationId);
|
|
6148
|
+
if (model) args.push("--model", model);
|
|
6149
|
+
try {
|
|
6150
|
+
const { stdout } = await execute("forklaunch", args, {
|
|
6151
|
+
timeout: 35e3,
|
|
6152
|
+
maxBuffer: 65536,
|
|
6153
|
+
windowsHide: true
|
|
6154
|
+
});
|
|
6155
|
+
return JSON.parse(stdout);
|
|
6156
|
+
} catch {
|
|
6157
|
+
throw new Error(
|
|
6158
|
+
"Could not connect the local agent. Run forklaunch login, check app access, and use a CLI that supports model credential."
|
|
6159
|
+
);
|
|
6160
|
+
}
|
|
6161
|
+
});
|
|
6162
|
+
const optionsFetch = options2.fetch ?? fetch;
|
|
6163
|
+
let pending;
|
|
6164
|
+
let credential;
|
|
6165
|
+
async function connection() {
|
|
6166
|
+
if (credential && credential.expiresAt > Date.now()) return credential;
|
|
6167
|
+
pending ??= provider().then(validate).then((value) => credential = value).finally(() => {
|
|
6168
|
+
pending = void 0;
|
|
6169
|
+
});
|
|
6170
|
+
return pending;
|
|
6171
|
+
}
|
|
6172
|
+
return {
|
|
6173
|
+
async models() {
|
|
6174
|
+
const c = await connection();
|
|
6175
|
+
return {
|
|
6176
|
+
models: [{ id: c.model }],
|
|
6177
|
+
preview: {
|
|
6178
|
+
expiresAt: c.expiresAt,
|
|
6179
|
+
maxCalls: c.maxCalls,
|
|
6180
|
+
maxUnits: c.maxUnits
|
|
6181
|
+
}
|
|
6182
|
+
};
|
|
6183
|
+
},
|
|
6184
|
+
chat: {
|
|
6185
|
+
completions: {
|
|
6186
|
+
async *stream(request, options3 = {}) {
|
|
6187
|
+
const c = await connection();
|
|
6188
|
+
if (request.model !== c.model)
|
|
6189
|
+
throw new ModelGatewayRequestError(
|
|
6190
|
+
400,
|
|
6191
|
+
"Choose the model authorized for this local session."
|
|
6192
|
+
);
|
|
6193
|
+
const response = await optionsFetch(
|
|
6194
|
+
`${c.gatewayBaseUrl}/chat/completions`,
|
|
6195
|
+
{
|
|
6196
|
+
method: "POST",
|
|
6197
|
+
redirect: "error",
|
|
6198
|
+
signal: options3.signal ? AbortSignal.any([options3.signal, AbortSignal.timeout(6e4)]) : AbortSignal.timeout(6e4),
|
|
6199
|
+
headers: {
|
|
6200
|
+
authorization: `Bearer ${c.capability}`,
|
|
6201
|
+
"content-type": "application/json"
|
|
6202
|
+
},
|
|
6203
|
+
body: JSON.stringify({ ...request, stream: true })
|
|
6204
|
+
}
|
|
6205
|
+
);
|
|
6206
|
+
if (!response.ok) {
|
|
6207
|
+
await response.body?.cancel();
|
|
6208
|
+
throw new ModelGatewayRequestError(
|
|
6209
|
+
response.status,
|
|
6210
|
+
"The local model stream was refused. No automatic retry was sent."
|
|
6211
|
+
);
|
|
6212
|
+
}
|
|
6213
|
+
yield* readModelStream(response);
|
|
6214
|
+
},
|
|
6215
|
+
async create(request) {
|
|
6216
|
+
const c = await connection();
|
|
6217
|
+
if (request.model !== c.model)
|
|
6218
|
+
throw new ModelGatewayRequestError(
|
|
6219
|
+
400,
|
|
6220
|
+
"Choose the model authorized for this local session."
|
|
6221
|
+
);
|
|
6222
|
+
const response = await (options2.fetch ?? fetch)(
|
|
6223
|
+
`${c.gatewayBaseUrl}/chat/completions`,
|
|
6224
|
+
{
|
|
6225
|
+
method: "POST",
|
|
6226
|
+
redirect: "error",
|
|
6227
|
+
signal: AbortSignal.timeout(6e4),
|
|
6228
|
+
headers: {
|
|
6229
|
+
authorization: `Bearer ${c.capability}`,
|
|
6230
|
+
"content-type": "application/json"
|
|
6231
|
+
},
|
|
6232
|
+
body: JSON.stringify({ ...request, stream: false })
|
|
6233
|
+
}
|
|
6234
|
+
);
|
|
6235
|
+
if (!response.ok) {
|
|
6236
|
+
await response.body?.cancel();
|
|
6237
|
+
throw new ModelGatewayRequestError(
|
|
6238
|
+
response.status,
|
|
6239
|
+
"The local model request was refused or failed. No automatic retry was sent."
|
|
6240
|
+
);
|
|
6241
|
+
}
|
|
6242
|
+
return response.json();
|
|
6243
|
+
}
|
|
6244
|
+
}
|
|
6245
|
+
}
|
|
6246
|
+
};
|
|
6247
|
+
}
|
|
5874
6248
|
// Annotate the CommonJS export names for ESM import in node:
|
|
5875
6249
|
0 && (module.exports = {
|
|
5876
6250
|
ATTR_API_NAME,
|
|
@@ -5881,6 +6255,7 @@ function registerDelegatedSurface(surface, mount, register) {
|
|
|
5881
6255
|
ATTR_HTTP_ROUTE,
|
|
5882
6256
|
ATTR_SERVICE_NAME,
|
|
5883
6257
|
AuditLogger,
|
|
6258
|
+
DEFAULT_MCP_SESSION_IDLE_TIMEOUT_MS,
|
|
5884
6259
|
EMAIL_LIMITS,
|
|
5885
6260
|
EmailRequestError,
|
|
5886
6261
|
ForklaunchExpressLikeApplication,
|
|
@@ -5914,6 +6289,8 @@ function registerDelegatedSurface(surface, mount, register) {
|
|
|
5914
6289
|
createEmailClient,
|
|
5915
6290
|
createHmacToken,
|
|
5916
6291
|
createInstanceGatewayTransport,
|
|
6292
|
+
createLocalModelGatewayClient,
|
|
6293
|
+
createMcpHttpHandler,
|
|
5917
6294
|
createModelGatewayClient,
|
|
5918
6295
|
createPaymentsClient,
|
|
5919
6296
|
createPreviewModelGatewayClient,
|
|
@@ -5934,6 +6311,7 @@ function registerDelegatedSurface(surface, mount, register) {
|
|
|
5934
6311
|
get,
|
|
5935
6312
|
getCachedJwks,
|
|
5936
6313
|
getCodeForStatus,
|
|
6314
|
+
getMcpTransportHeaders,
|
|
5937
6315
|
head,
|
|
5938
6316
|
httpErrorsTotalCounter,
|
|
5939
6317
|
httpRequestDurationMsHistogram,
|
|
@@ -5950,6 +6328,7 @@ function registerDelegatedSurface(surface, mount, register) {
|
|
|
5950
6328
|
isManagedInstance,
|
|
5951
6329
|
isPortBound,
|
|
5952
6330
|
isRedirection,
|
|
6331
|
+
isSeparateMcpListener,
|
|
5953
6332
|
isServerError,
|
|
5954
6333
|
isSuccessful,
|
|
5955
6334
|
isValidStatusCode,
|