@spmos/local-proxy 0.1.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/src/config.js ADDED
@@ -0,0 +1,137 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+
6
+ export const CONFIG_VERSION = 1;
7
+ const LOOPBACK = new Set(["127.0.0.1", "::1", "localhost"]);
8
+
9
+ export function configPath(env = process.env) {
10
+ const root = env.SPM_CONFIG_HOME
11
+ || env.XDG_CONFIG_HOME && join(env.XDG_CONFIG_HOME, "spm")
12
+ || join(homedir(), ".config", "spm");
13
+ return join(root, "local-proxy.json");
14
+ }
15
+
16
+ export function newLocalToken() {
17
+ return randomBytes(32).toString("base64url");
18
+ }
19
+
20
+ function requireString(value, name) {
21
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${name} is required`);
22
+ return value.trim();
23
+ }
24
+
25
+ function httpsUrl(value, name) {
26
+ const parsed = new URL(requireString(value, name));
27
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
28
+ throw new Error(`${name} must be an HTTPS URL without user info`);
29
+ }
30
+ return parsed.toString().replace(/\/$/, "");
31
+ }
32
+
33
+ export function validateConfig(input) {
34
+ if (!input || typeof input !== "object") throw new Error("Configuration must be an object");
35
+ const provider = input.provider || {};
36
+ const proxy = input.proxy || {};
37
+ const spm = input.spm || {};
38
+ const host = requireString(proxy.host || "127.0.0.1", "proxy.host");
39
+ if (!LOOPBACK.has(host)) throw new Error("Local Proxy may only bind to loopback");
40
+ const port = Number(proxy.port ?? 8765);
41
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("proxy.port is invalid");
42
+ const apiStyle = provider.apiStyle || "openai_compatible";
43
+ if (!["openai_compatible", "anthropic_messages"].includes(apiStyle)) {
44
+ throw new Error("provider.apiStyle is unsupported");
45
+ }
46
+ const authScheme = provider.authScheme || (apiStyle === "anthropic_messages" ? "x-api-key" : "bearer");
47
+ if (!["bearer", "x-api-key", "api-key"].includes(authScheme)) {
48
+ throw new Error("provider.authScheme is unsupported");
49
+ }
50
+ const providerKey = requireString(provider.apiKey, "provider.apiKey");
51
+ const spmKey = requireString(spm.apiKey, "spm.apiKey");
52
+ const localToken = requireString(proxy.localToken, "proxy.localToken");
53
+ if (localToken.length < 16) throw new Error("proxy.localToken must contain at least 16 characters");
54
+ if (localToken === providerKey || localToken === spmKey) {
55
+ throw new Error("proxy.localToken must be distinct from provider and SPM keys");
56
+ }
57
+ const customHeaders = provider.customHeaders && typeof provider.customHeaders === "object"
58
+ ? Object.fromEntries(Object.entries(provider.customHeaders).map(([key, value]) => [String(key), String(value)]))
59
+ : {};
60
+ const queryParams = provider.queryParams && typeof provider.queryParams === "object"
61
+ ? Object.fromEntries(Object.entries(provider.queryParams).map(([key, value]) => [String(key), String(value)]))
62
+ : {};
63
+ const inputBudgetTokens = Number(proxy.inputBudgetTokens || 8192);
64
+ const maxRecalledTokens = Number(proxy.maxRecalledTokens || 512);
65
+ if (!Number.isInteger(inputBudgetTokens) || inputBudgetTokens < 1) {
66
+ throw new Error("proxy.inputBudgetTokens must be a positive integer");
67
+ }
68
+ if (!Number.isInteger(maxRecalledTokens) || maxRecalledTokens < 1) {
69
+ throw new Error("proxy.maxRecalledTokens must be a positive integer");
70
+ }
71
+ return {
72
+ version: CONFIG_VERSION,
73
+ spm: {
74
+ apiKey: spmKey,
75
+ baseUrl: httpsUrl(spm.baseUrl || "https://api.spmos.ai", "spm.baseUrl"),
76
+ },
77
+ provider: {
78
+ id: requireString(provider.id || "custom", "provider.id"),
79
+ name: requireString(provider.name || provider.id || "Custom provider", "provider.name"),
80
+ source: provider.source === "models.dev" ? "models.dev" : "byo",
81
+ baseUrl: httpsUrl(provider.baseUrl, "provider.baseUrl"),
82
+ apiStyle,
83
+ authScheme,
84
+ apiKey: providerKey,
85
+ customHeaders,
86
+ queryParams,
87
+ },
88
+ proxy: {
89
+ host,
90
+ port,
91
+ localToken,
92
+ inputBudgetTokens,
93
+ maxRecalledTokens,
94
+ memoryMode: ["off", "read", "write", "read-write"].includes(proxy.memoryMode)
95
+ ? proxy.memoryMode : "read-write",
96
+ compressionMode: ["passthrough", "shadow", "deterministic"].includes(proxy.compressionMode)
97
+ ? proxy.compressionMode : "deterministic",
98
+ },
99
+ };
100
+ }
101
+
102
+ export async function saveConfig(config, path = configPath()) {
103
+ const normalized = validateConfig(config);
104
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
105
+ await chmod(dirname(path), 0o700).catch(() => {});
106
+ const temporary = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
107
+ await writeFile(temporary, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600, flag: "wx" });
108
+ await chmod(temporary, 0o600).catch(() => {});
109
+ await rename(temporary, path);
110
+ await chmod(path, 0o600).catch(() => {});
111
+ return normalized;
112
+ }
113
+
114
+ export async function loadConfig(path = configPath(), env = process.env) {
115
+ const parsed = JSON.parse(await readFile(path, "utf8"));
116
+ const overridden = structuredClone(parsed);
117
+ if (env.SPM_API_KEY) overridden.spm.apiKey = env.SPM_API_KEY;
118
+ if (env.SPM_LOCAL_PROVIDER_API_KEY) overridden.provider.apiKey = env.SPM_LOCAL_PROVIDER_API_KEY;
119
+ if (env.SPM_LOCAL_PROXY_TOKEN) overridden.proxy.localToken = env.SPM_LOCAL_PROXY_TOKEN;
120
+ return validateConfig(overridden);
121
+ }
122
+
123
+ export function maskedConfig(config) {
124
+ const copy = structuredClone(config);
125
+ for (const target of [copy.spm, copy.provider, copy.proxy]) {
126
+ const key = target === copy.proxy ? "localToken" : "apiKey";
127
+ const value = target[key] || "";
128
+ target[key] = value ? `${value.slice(0, 4)}…${value.slice(-4)}` : "";
129
+ }
130
+ copy.provider.customHeaders = Object.fromEntries(
131
+ Object.keys(copy.provider.customHeaders || {}).map((key) => [key, "••••••••"]),
132
+ );
133
+ copy.provider.queryParams = Object.fromEntries(
134
+ Object.keys(copy.provider.queryParams || {}).map((key) => [key, "••••••••"]),
135
+ );
136
+ return copy;
137
+ }
package/src/gateway.js ADDED
@@ -0,0 +1,432 @@
1
+ import { randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { once } from "node:events";
3
+ import { createServer } from "node:http";
4
+ import { zstdDecompressSync } from "node:zlib";
5
+
6
+ import { HostedMemoryClient, memorySourceId } from "./memory.js";
7
+ import {
8
+ ProjectionError,
9
+ compressProjection,
10
+ estimateTokens,
11
+ patchedBody,
12
+ projectRequest,
13
+ } from "./projection.js";
14
+ import { requestProvider } from "./provider.js";
15
+
16
+ const MAX_BODY_BYTES = 10 * 1024 * 1024;
17
+ const POST_ROUTES = new Map([
18
+ ["/v1/chat/completions", ["chat", "/chat/completions"]],
19
+ ["/v1/responses", ["responses", "/responses"]],
20
+ ["/v1/messages", ["messages", "/messages"]],
21
+ ]);
22
+ const LOOPBACK = new Set(["127.0.0.1", "::1", "localhost"]);
23
+
24
+ function constantEqual(left, right) {
25
+ const a = Buffer.from(left || "");
26
+ const b = Buffer.from(right || "");
27
+ return a.length === b.length && timingSafeEqual(a, b);
28
+ }
29
+
30
+ function incomingToken(request) {
31
+ const authorization = request.headers.authorization || "";
32
+ const [scheme, value] = authorization.split(/\s+/, 2);
33
+ const bearer = scheme?.toLowerCase() === "bearer" ? value : "";
34
+ return [bearer, request.headers["x-api-key"] || ""];
35
+ }
36
+
37
+ function authenticate(request, config) {
38
+ if (!incomingToken(request).some((value) => value && constantEqual(value, config.proxy.localToken))) {
39
+ const error = new Error("Local Proxy authentication failed");
40
+ error.code = "spm_local_auth_invalid";
41
+ error.statusCode = 401;
42
+ throw error;
43
+ }
44
+ }
45
+
46
+ function requestHost(request) {
47
+ try {
48
+ return new URL(`http://${request.headers.host || ""}`).hostname.replace(/^\[|\]$/g, "");
49
+ } catch {
50
+ return "";
51
+ }
52
+ }
53
+
54
+ function errorPayload(protocol, code, message) {
55
+ if (protocol === "messages") {
56
+ return { type: "error", error: { type: code, message } };
57
+ }
58
+ return { error: { message, type: code, code } };
59
+ }
60
+
61
+ function sendJson(response, statusCode, payload, headers = {}) {
62
+ const body = Buffer.from(JSON.stringify(payload), "utf8");
63
+ response.writeHead(statusCode, {
64
+ "content-type": "application/json",
65
+ "content-length": String(body.length),
66
+ "cache-control": "no-store",
67
+ "x-content-type-options": "nosniff",
68
+ ...headers,
69
+ });
70
+ response.end(body);
71
+ }
72
+
73
+ async function readRequestBody(request) {
74
+ const declared = Number(request.headers["content-length"] || 0);
75
+ if (declared > MAX_BODY_BYTES) throw Object.assign(new Error("Request body is too large"), { code: "spm_request_too_large", statusCode: 413 });
76
+ const chunks = [];
77
+ let size = 0;
78
+ for await (const chunk of request) {
79
+ size += chunk.length;
80
+ if (size > MAX_BODY_BYTES) throw Object.assign(new Error("Request body is too large"), { code: "spm_request_too_large", statusCode: 413 });
81
+ chunks.push(chunk);
82
+ }
83
+ let bytes = Buffer.concat(chunks);
84
+ if (bytes.subarray(0, 4).equals(Buffer.from([0x28, 0xb5, 0x2f, 0xfd]))) {
85
+ try {
86
+ bytes = zstdDecompressSync(bytes, { maxOutputLength: MAX_BODY_BYTES + 1 });
87
+ } catch (cause) {
88
+ throw Object.assign(new Error("Request body decompression failed"), { code: "spm_invalid_request", statusCode: 422, cause });
89
+ }
90
+ if (bytes.length > MAX_BODY_BYTES) throw Object.assign(new Error("Decompressed request body is too large"), { code: "spm_request_too_large", statusCode: 413 });
91
+ }
92
+ try {
93
+ const body = JSON.parse(bytes.toString("utf8"));
94
+ if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("not an object");
95
+ return body;
96
+ } catch (cause) {
97
+ throw Object.assign(new Error("Request body must be a JSON object"), { code: "spm_invalid_request", statusCode: 422, cause });
98
+ }
99
+ }
100
+
101
+ function requestModes(request, config) {
102
+ const memoryMode = String(request.headers["x-spm-memory-mode"] || config.proxy.memoryMode).toLowerCase();
103
+ const compressionMode = String(request.headers["x-spm-compression-mode"] || config.proxy.compressionMode).toLowerCase();
104
+ if (!["off", "read", "write", "read-write"].includes(memoryMode)) {
105
+ throw Object.assign(new Error("Unsupported memory mode"), { code: "spm_invalid_memory_mode", statusCode: 422 });
106
+ }
107
+ if (!["passthrough", "shadow", "deterministic"].includes(compressionMode)) {
108
+ throw Object.assign(new Error("Unsupported compression mode"), { code: "spm_invalid_compression_mode", statusCode: 422 });
109
+ }
110
+ return { memoryMode, compressionMode };
111
+ }
112
+
113
+ function forwardHeaders(headers) {
114
+ const denied = new Set(["authorization", "x-api-key", "host", "origin", "content-length", "content-encoding"]);
115
+ const output = {};
116
+ for (const [key, value] of Object.entries(headers)) {
117
+ const lower = key.toLowerCase();
118
+ if (!denied.has(lower)
119
+ && !["cf-", "x-forwarded-", "x-spm-", "x-vercel-"].some((prefix) => lower.startsWith(prefix))) {
120
+ output[lower] = Array.isArray(value) ? value.join(", ") : String(value);
121
+ }
122
+ }
123
+ return output;
124
+ }
125
+
126
+ function truncateTokens(text, maxTokens) {
127
+ const bytes = Buffer.from(text, "utf8").subarray(0, maxTokens * 4);
128
+ return new TextDecoder("utf-8", { fatal: false }).decode(bytes).replace(/�$/, "");
129
+ }
130
+
131
+ async function writeChunk(response, chunk) {
132
+ if (!response.write(chunk)) await once(response, "drain");
133
+ }
134
+
135
+ async function captureText(memory, text, sourceId) {
136
+ try {
137
+ await memory.ingest({ text, sourceId });
138
+ return true;
139
+ } catch {
140
+ return false;
141
+ }
142
+ }
143
+
144
+ async function captureInputs(memory, projection) {
145
+ let ok = true;
146
+ for (const unit of projection.units) {
147
+ if (!unit.captureEligible || !unit.text) continue;
148
+ const id = memorySourceId(`local:${projection.protocol}`, "input", unit.text);
149
+ ok = await captureText(memory, unit.text, id) && ok;
150
+ }
151
+ return ok;
152
+ }
153
+
154
+ function assistantOutput(protocol, bytes) {
155
+ let payload;
156
+ try {
157
+ payload = JSON.parse(bytes.toString("utf8"));
158
+ } catch {
159
+ return "";
160
+ }
161
+ if (protocol === "chat") {
162
+ return Array.isArray(payload.choices) ? payload.choices.flatMap((choice) => {
163
+ const content = choice?.message?.content;
164
+ if (typeof content === "string") return [content];
165
+ if (Array.isArray(content)) return content.filter((block) => typeof block?.text === "string").map((block) => block.text);
166
+ return [];
167
+ }).join("\n") : "";
168
+ }
169
+ if (protocol === "responses") {
170
+ if (typeof payload.output_text === "string") return payload.output_text;
171
+ return Array.isArray(payload.output) ? payload.output.flatMap((item) =>
172
+ Array.isArray(item?.content) ? item.content.filter((block) => typeof block?.text === "string").map((block) => block.text) : []).join("\n") : "";
173
+ }
174
+ return Array.isArray(payload.content)
175
+ ? payload.content.filter((block) => typeof block?.text === "string").map((block) => block.text).join("\n") : "";
176
+ }
177
+
178
+ class SseObserver {
179
+ constructor(protocol) {
180
+ this.protocol = protocol;
181
+ this.buffer = Buffer.alloc(0);
182
+ this.parts = [];
183
+ this.success = false;
184
+ }
185
+
186
+ feed(chunk) {
187
+ this.buffer = Buffer.concat([this.buffer, chunk]);
188
+ while (true) {
189
+ const lf = this.buffer.indexOf("\n\n");
190
+ const crlf = this.buffer.indexOf("\r\n\r\n");
191
+ let index = -1;
192
+ let width = 0;
193
+ if (lf >= 0 && (crlf < 0 || lf < crlf)) [index, width] = [lf, 2];
194
+ else if (crlf >= 0) [index, width] = [crlf, 4];
195
+ if (index < 0) return;
196
+ const frame = this.buffer.subarray(0, index);
197
+ this.buffer = this.buffer.subarray(index + width);
198
+ this.observe(frame);
199
+ }
200
+ }
201
+
202
+ append(value) {
203
+ if (typeof value === "string" && value) this.parts.push(value);
204
+ }
205
+
206
+ observe(frame) {
207
+ const data = frame.toString("utf8").replaceAll("\r\n", "\n").split("\n")
208
+ .filter((line) => line.startsWith("data:"))
209
+ .map((line) => line.slice(5).trimStart()).join("\n");
210
+ if (!data) return;
211
+ if (this.protocol === "chat" && data.trim() === "[DONE]") {
212
+ this.success = true;
213
+ return;
214
+ }
215
+ let event;
216
+ try { event = JSON.parse(data); } catch { return; }
217
+ if (this.protocol === "chat") {
218
+ for (const choice of Array.isArray(event.choices) ? event.choices : []) {
219
+ this.append(choice?.delta?.content);
220
+ for (const call of Array.isArray(choice?.delta?.tool_calls) ? choice.delta.tool_calls : []) {
221
+ this.append(call?.function?.arguments);
222
+ }
223
+ }
224
+ return;
225
+ }
226
+ if (this.protocol === "responses") {
227
+ if (String(event.type || "").endsWith(".delta")) this.append(event.delta);
228
+ if (event.type === "response.completed") this.success = true;
229
+ return;
230
+ }
231
+ if (event.type === "content_block_delta") {
232
+ this.append(event.delta?.text);
233
+ this.append(event.delta?.partial_json);
234
+ }
235
+ if (event.type === "message_stop") this.success = true;
236
+ }
237
+ }
238
+
239
+ function spmHeaders({ requestId, memoryMode, memoryState, compressionMode, original, forwarded, recalled }) {
240
+ return {
241
+ "x-spm-local-proxy": "v1",
242
+ "x-spm-request-id": requestId,
243
+ "x-spm-memory-mode": memoryMode,
244
+ "x-spm-memory-state": memoryState,
245
+ "x-spm-compression-mode": compressionMode,
246
+ "x-spm-original-input-tokens": String(original),
247
+ "x-spm-forwarded-input-tokens": String(forwarded),
248
+ "x-spm-recalled-tokens": String(recalled),
249
+ };
250
+ }
251
+
252
+ function writeUpstreamHeaders(response, upstream, extra = {}) {
253
+ const safe = {};
254
+ const denied = new Set(["connection", "content-length", "set-cookie", "transfer-encoding"]);
255
+ for (const [key, value] of Object.entries(upstream.headers || {})) {
256
+ if (!denied.has(key.toLowerCase())) safe[key.toLowerCase()] = value;
257
+ }
258
+ response.writeHead(upstream.statusCode, {
259
+ ...safe,
260
+ ...extra,
261
+ "cache-control": "no-store",
262
+ "x-content-type-options": "nosniff",
263
+ });
264
+ }
265
+
266
+ async function relayModelRequest(request, response, config, providerRequest) {
267
+ authenticate(request, config);
268
+ const local = new URL(request.url, "http://localhost");
269
+ const route = `${local.pathname.replace(/^\/v1/, "")}${local.search}`;
270
+ const upstream = await providerRequest({
271
+ config, method: "GET", route, headers: forwardHeaders(request.headers),
272
+ });
273
+ writeUpstreamHeaders(response, upstream, { "x-spm-local-proxy": "v1" });
274
+ try {
275
+ for await (const chunk of upstream.body) await writeChunk(response, chunk);
276
+ response.end();
277
+ } finally {
278
+ upstream.close?.();
279
+ }
280
+ }
281
+
282
+ async function handleModelPost(request, response, config, memory, providerRequest, protocol, route) {
283
+ authenticate(request, config);
284
+ const body = await readRequestBody(request);
285
+ const projection = projectRequest(protocol, body);
286
+ const { memoryMode, compressionMode } = requestModes(request, config);
287
+ const original = estimateTokens(body);
288
+ let recalledContext = "";
289
+ let recallFailed = false;
290
+ const projectionBypass = projection.decision === "bypass";
291
+ if (!projectionBypass && memoryMode.includes("read") && projection.newestUserText) {
292
+ try {
293
+ recalledContext = truncateTokens(await memory.recall({
294
+ query: projection.newestUserText,
295
+ contextTokens: original,
296
+ }), config.proxy.maxRecalledTokens);
297
+ } catch {
298
+ recallFailed = true;
299
+ }
300
+ }
301
+ const compression = compressProjection(projection, {
302
+ inputBudget: config.proxy.inputBudgetTokens,
303
+ recalledContext,
304
+ });
305
+ const deterministicBypass = compressionMode === "deterministic" && compression.mode === "bypass";
306
+ let effectiveCompression = compressionMode;
307
+ let forwardedBody;
308
+ if (recallFailed || projectionBypass || deterministicBypass) {
309
+ effectiveCompression = "passthrough";
310
+ forwardedBody = structuredClone(body);
311
+ } else if (compressionMode === "deterministic") {
312
+ forwardedBody = compression.body;
313
+ } else if (compressionMode === "passthrough" && recalledContext) {
314
+ forwardedBody = patchedBody(projection, { untrustedContext: recalledContext });
315
+ } else {
316
+ forwardedBody = structuredClone(body);
317
+ }
318
+ let inputCaptureOk = true;
319
+ if (memoryMode.includes("write")) inputCaptureOk = await captureInputs(memory, projection);
320
+ const upstream = await providerRequest({
321
+ config,
322
+ method: "POST",
323
+ route,
324
+ body: forwardedBody,
325
+ headers: forwardHeaders(request.headers),
326
+ });
327
+ const requestId = String(request.headers["x-request-id"] || `spm_local_${randomUUID()}`);
328
+ const metrics = {
329
+ requestId,
330
+ memoryMode,
331
+ compressionMode: effectiveCompression,
332
+ original,
333
+ forwarded: estimateTokens(forwardedBody),
334
+ recalled: estimateTokens(recalledContext),
335
+ };
336
+ if (body.stream === true) {
337
+ const observer = new SseObserver(protocol);
338
+ const state = recallFailed || !inputCaptureOk ? "degraded"
339
+ : memoryMode.includes("write") ? "pending"
340
+ : metrics.recalled ? "recalled" : memoryMode.includes("read") ? "empty" : "off";
341
+ writeUpstreamHeaders(response, upstream, spmHeaders({ ...metrics, memoryState: state }));
342
+ try {
343
+ for await (const chunk of upstream.body) {
344
+ observer.feed(chunk);
345
+ await writeChunk(response, chunk);
346
+ }
347
+ response.end();
348
+ } finally {
349
+ upstream.close?.();
350
+ if (memoryMode.includes("write") && observer.success && observer.parts.length) {
351
+ const text = observer.parts.join("");
352
+ await captureText(memory, text, memorySourceId("local", "assistant", text));
353
+ }
354
+ }
355
+ return;
356
+ }
357
+ const chunks = [];
358
+ try {
359
+ for await (const chunk of upstream.body) chunks.push(chunk);
360
+ } finally {
361
+ upstream.close?.();
362
+ }
363
+ const bytes = Buffer.concat(chunks);
364
+ let outputCaptureOk = true;
365
+ if (memoryMode.includes("write") && upstream.statusCode >= 200 && upstream.statusCode < 300) {
366
+ const text = assistantOutput(protocol, bytes);
367
+ if (text) outputCaptureOk = await captureText(memory, text, memorySourceId("local", "assistant", text));
368
+ }
369
+ const state = recallFailed || !inputCaptureOk || !outputCaptureOk ? "degraded"
370
+ : memoryMode.includes("write") ? "captured"
371
+ : metrics.recalled ? "recalled" : memoryMode.includes("read") ? "empty" : "off";
372
+ writeUpstreamHeaders(response, upstream, spmHeaders({ ...metrics, memoryState: state }));
373
+ response.end(bytes);
374
+ }
375
+
376
+ export function createGateway({
377
+ config,
378
+ memory = new HostedMemoryClient({ baseUrl: config.spm.baseUrl, apiKey: config.spm.apiKey }),
379
+ providerRequest = requestProvider,
380
+ } = {}) {
381
+ return createServer(async (request, response) => {
382
+ let protocol = "chat";
383
+ try {
384
+ const host = requestHost(request);
385
+ if (!LOOPBACK.has(host)) throw Object.assign(new Error("Local Proxy Host is forbidden"), { code: "spm_local_host_forbidden", statusCode: 403 });
386
+ if (request.headers.origin) throw Object.assign(new Error("Browser-origin requests are forbidden"), { code: "spm_local_browser_forbidden", statusCode: 403 });
387
+ const local = new URL(request.url, "http://localhost");
388
+ if (request.method === "GET" && ["/health", "/livez"].includes(local.pathname)) {
389
+ sendJson(response, 200, local.pathname === "/livez" ? { status: "ok" } : {
390
+ status: "ok",
391
+ provider: config.provider.id,
392
+ base_url: config.provider.baseUrl,
393
+ api_style: config.provider.apiStyle,
394
+ models: "downstream",
395
+ });
396
+ return;
397
+ }
398
+ if (request.method === "GET" && /^\/v1\/models(?:\/|$)/.test(local.pathname)) {
399
+ await relayModelRequest(request, response, config, providerRequest);
400
+ return;
401
+ }
402
+ const target = POST_ROUTES.get(local.pathname);
403
+ if (request.method !== "POST" || !target) {
404
+ sendJson(response, 404, errorPayload("chat", "spm_not_found", "Route not found"));
405
+ return;
406
+ }
407
+ [protocol] = target;
408
+ const expected = protocol === "messages" ? "anthropic_messages" : "openai_compatible";
409
+ if (config.provider.apiStyle !== expected) {
410
+ throw Object.assign(new Error("Request protocol is incompatible with the configured provider"), { code: "spm_provider_route_invalid", statusCode: 422 });
411
+ }
412
+ await handleModelPost(request, response, config, memory, providerRequest, protocol, target[1]);
413
+ } catch (error) {
414
+ if (response.headersSent) {
415
+ response.destroy();
416
+ return;
417
+ }
418
+ const code = error instanceof ProjectionError ? error.code : error.code || "spm_local_proxy_unavailable";
419
+ const status = error instanceof ProjectionError ? 422 : error.statusCode || 503;
420
+ const message = status >= 500 ? "Local Proxy request failed" : error.message;
421
+ sendJson(response, status, errorPayload(protocol, code, message));
422
+ }
423
+ });
424
+ }
425
+
426
+ export async function listenGateway(server, { host, port }) {
427
+ await new Promise((resolve, reject) => {
428
+ server.once("error", reject);
429
+ server.listen(port, host, resolve);
430
+ });
431
+ return server;
432
+ }
package/src/index.js ADDED
@@ -0,0 +1,13 @@
1
+ export { getProviderCatalog, parseCatalog } from "./catalog.js";
2
+ export {
3
+ configPath,
4
+ loadConfig,
5
+ maskedConfig,
6
+ newLocalToken,
7
+ saveConfig,
8
+ validateConfig,
9
+ } from "./config.js";
10
+ export { createGateway, listenGateway } from "./gateway.js";
11
+ export { HostedMemoryClient } from "./memory.js";
12
+ export { compressProjection, projectRequest } from "./projection.js";
13
+ export { requestProvider } from "./provider.js";
package/src/memory.js ADDED
@@ -0,0 +1,55 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export class HostedMemoryClient {
4
+ constructor({ baseUrl, apiKey, fetchImpl = globalThis.fetch, timeoutMs = 30_000 }) {
5
+ this.baseUrl = baseUrl.replace(/\/$/, "");
6
+ this.apiKey = apiKey;
7
+ this.fetchImpl = fetchImpl;
8
+ this.timeoutMs = timeoutMs;
9
+ }
10
+
11
+ async request(path, body) {
12
+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
13
+ method: "POST",
14
+ redirect: "error",
15
+ signal: AbortSignal.timeout(this.timeoutMs),
16
+ headers: {
17
+ authorization: `Bearer ${this.apiKey}`,
18
+ "content-type": "application/json",
19
+ accept: "application/json",
20
+ },
21
+ body: JSON.stringify(body),
22
+ });
23
+ return response;
24
+ }
25
+
26
+ async recall({ query, contextTokens }) {
27
+ const response = await this.request("/v2/recall", {
28
+ query: query.slice(0, 2000),
29
+ top_k: 6,
30
+ context_tokens: Math.max(1, Math.min(contextTokens, 1_000_000)),
31
+ });
32
+ if (response.status === 424) return "";
33
+ if (!response.ok) throw new Error(`SPM recall returned HTTP ${response.status}`);
34
+ const payload = await response.json();
35
+ if (payload?.gate_reason !== "passed" || !Number.isInteger(payload.evidence_count)
36
+ || payload.evidence_count < 1) return "";
37
+ if (typeof payload.answer !== "string") throw new Error("SPM recall returned an invalid response");
38
+ return payload.answer;
39
+ }
40
+
41
+ async ingest({ text, sourceId }) {
42
+ const chunks = [];
43
+ for (let index = 0; index < text.length; index += 12_000) chunks.push(text.slice(index, index + 12_000));
44
+ for (let index = 0; index < chunks.length; index += 1) {
45
+ const id = chunks.length === 1 ? sourceId : `${sourceId}:${index}`;
46
+ const response = await this.request("/v2/ingest", { text: chunks[index], source_id: id });
47
+ if (!response.ok) throw new Error(`SPM ingest returned HTTP ${response.status}`);
48
+ }
49
+ }
50
+ }
51
+
52
+ export function memorySourceId(scope, kind, text) {
53
+ const digest = createHash("sha256").update(text, "utf8").digest("hex").slice(0, 24);
54
+ return `gateway:${scope}:${kind}:${digest}`;
55
+ }