@spmos/local-proxy 0.1.2 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -0
- package/package.json +1 -1
- package/src/cli.js +58 -6
- package/src/config.js +19 -0
- package/src/gateway.js +22 -2
- package/src/memory.js +22 -2
- package/src/terminal.js +15 -0
package/README.md
CHANGED
|
@@ -145,3 +145,26 @@ Configuration (all optional):
|
|
|
145
145
|
|
|
146
146
|
Elision is best-effort: any readiness-check or capture failure leaves the
|
|
147
147
|
request body untouched.
|
|
148
|
+
|
|
149
|
+
## End-user partitions and live doctor in 0.1.3
|
|
150
|
+
|
|
151
|
+
Version `0.1.3` adds tenant-internal end-user partitions and a live `doctor`.
|
|
152
|
+
|
|
153
|
+
Partitions let one SPM key serve many end users with isolated memory spaces
|
|
154
|
+
(the key needs the `memory:partition` scope):
|
|
155
|
+
|
|
156
|
+
- `spm.userPartition` in the configuration (the setup wizard asks for it)
|
|
157
|
+
sets the default partition for every memory call;
|
|
158
|
+
- `SPM_USER_PARTITION` overrides it without editing the file;
|
|
159
|
+
- the per-request header `x-spm-user-partition` overrides it for a single
|
|
160
|
+
request, so one Local Proxy can serve many downstream users.
|
|
161
|
+
|
|
162
|
+
Partition values must match `^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$` — use a
|
|
163
|
+
stable opaque id (for example your internal user UUID), not a secret or a
|
|
164
|
+
display name. An invalid header value fails the request closed with
|
|
165
|
+
`400 spm_invalid_user_partition` rather than silently mixing memory spaces.
|
|
166
|
+
|
|
167
|
+
`spm doctor` now also verifies the node.js version, that the configured port
|
|
168
|
+
is free, and — live — that the SPM API is reachable and accepts the key,
|
|
169
|
+
closing the "doctor passes but the live request fails" gap. `spm start`
|
|
170
|
+
prints the active memory mode and partition at launch.
|
package/package.json
CHANGED
package/src/cli.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { access } from "node:fs/promises";
|
|
2
|
+
import { createServer as createProbeServer } from "node:http";
|
|
2
3
|
|
|
3
4
|
import { getProviderCatalog } from "./catalog.js";
|
|
4
5
|
import {
|
|
@@ -9,7 +10,8 @@ import {
|
|
|
9
10
|
saveConfig,
|
|
10
11
|
} from "./config.js";
|
|
11
12
|
import { createGateway, listenGateway } from "./gateway.js";
|
|
12
|
-
import {
|
|
13
|
+
import { HostedMemoryClient } from "./memory.js";
|
|
14
|
+
import { blue, green, logo, promptLine, promptSecret, red, searchMenu, yellow } from "./terminal.js";
|
|
13
15
|
|
|
14
16
|
const HELP = `Usage: spm [command]
|
|
15
17
|
|
|
@@ -102,13 +104,17 @@ export async function setup({ refresh = false } = {}) {
|
|
|
102
104
|
);
|
|
103
105
|
const providerApiKey = await promptSecret("Provider API key");
|
|
104
106
|
const spmApiKey = await promptSecret("SPM API key");
|
|
107
|
+
const userPartition = await promptLine(
|
|
108
|
+
"End-user partition (optional opaque id; requires the memory:partition scope; empty = tenant default space)",
|
|
109
|
+
{ defaultValue: "" },
|
|
110
|
+
);
|
|
105
111
|
const customHeaders = selected.custom ? await objectPrompt("Custom headers JSON") : {};
|
|
106
112
|
const queryParams = selected.custom ? await objectPrompt("Query parameters JSON") : {};
|
|
107
113
|
const port = Number(await promptLine("Local Proxy port", { defaultValue: "8765" }));
|
|
108
114
|
const inputBudgetTokens = Number(await promptLine("Compression input budget", { defaultValue: "8192" }));
|
|
109
115
|
const config = await saveConfig({
|
|
110
116
|
version: 1,
|
|
111
|
-
spm: { apiKey: spmApiKey, baseUrl: "https://api.spmos.ai" },
|
|
117
|
+
spm: { apiKey: spmApiKey, baseUrl: "https://api.spmos.ai", userPartition },
|
|
112
118
|
provider: {
|
|
113
119
|
id: providerId,
|
|
114
120
|
name: providerName,
|
|
@@ -144,6 +150,8 @@ export async function start() {
|
|
|
144
150
|
process.stdout.write(` URL: http://${config.proxy.host}:${config.proxy.port}/v1\n`);
|
|
145
151
|
process.stdout.write(` Provider: ${config.provider.name}\n`);
|
|
146
152
|
process.stdout.write(` Base URL: ${config.provider.baseUrl}\n`);
|
|
153
|
+
process.stdout.write(` Memory: ${config.proxy.memoryMode} · compression ${config.proxy.compressionMode}\n`);
|
|
154
|
+
process.stdout.write(` Partition: ${config.spm.userPartition || "(tenant default space)"}\n`);
|
|
147
155
|
process.stdout.write(" Models: downstream discovery via GET /v1/models; request model is never rewritten\n");
|
|
148
156
|
process.stdout.write(" Logs: request and response bodies disabled\n\nPress Ctrl+C to stop.\n");
|
|
149
157
|
const close = () => server.close(() => process.exit(0));
|
|
@@ -214,10 +222,54 @@ export async function main(args = []) {
|
|
|
214
222
|
if (command === "doctor") {
|
|
215
223
|
logo();
|
|
216
224
|
const config = await loadConfig();
|
|
217
|
-
|
|
218
|
-
process.stdout.write(`${
|
|
219
|
-
process.stdout.write(`${
|
|
220
|
-
|
|
225
|
+
let failures = 0;
|
|
226
|
+
const pass = (label) => process.stdout.write(`${green("PASS")} ${label}\n`);
|
|
227
|
+
const warn = (label) => process.stdout.write(`${yellow("WARN")} ${label}\n`);
|
|
228
|
+
const fail = (label, hint) => {
|
|
229
|
+
failures += 1;
|
|
230
|
+
process.stdout.write(`${red("FAIL")} ${label}\n`);
|
|
231
|
+
if (hint) process.stdout.write(` \u2192 ${hint}\n`);
|
|
232
|
+
};
|
|
233
|
+
pass("configuration schema");
|
|
234
|
+
pass(`loopback-only listener ${config.proxy.host}:${config.proxy.port}`);
|
|
235
|
+
pass(`provider protocol ${config.provider.apiStyle}`);
|
|
236
|
+
pass("model ownership remains downstream");
|
|
237
|
+
const [nodeMajor, nodeMinor] = process.versions.node.split(".").map(Number);
|
|
238
|
+
if (nodeMajor > 22 || (nodeMajor === 22 && nodeMinor >= 15)) {
|
|
239
|
+
pass(`node.js ${process.versions.node}`);
|
|
240
|
+
} else {
|
|
241
|
+
fail(`node.js ${process.versions.node}`, "Local Proxy requires node.js >=22.15");
|
|
242
|
+
}
|
|
243
|
+
const probe = createProbeServer();
|
|
244
|
+
try {
|
|
245
|
+
await listenGateway(probe, config.proxy);
|
|
246
|
+
await new Promise((resolve) => probe.close(resolve));
|
|
247
|
+
pass(`port ${config.proxy.port} is available`);
|
|
248
|
+
} catch {
|
|
249
|
+
fail(`port ${config.proxy.host}:${config.proxy.port} is busy`, "stop the process using it, or pick another port in setup");
|
|
250
|
+
}
|
|
251
|
+
if (config.spm.userPartition) {
|
|
252
|
+
pass(`end-user partition "${config.spm.userPartition}" format`);
|
|
253
|
+
warn("partition calls require the memory:partition scope on the SPM key");
|
|
254
|
+
}
|
|
255
|
+
// Live check: a config-only validation cannot prove the SPM key is
|
|
256
|
+
// accepted (scopes, revocation, environment) — this is the gap behind
|
|
257
|
+
// "doctor passes but the live request fails".
|
|
258
|
+
try {
|
|
259
|
+
const client = new HostedMemoryClient({
|
|
260
|
+
baseUrl: config.spm.baseUrl,
|
|
261
|
+
apiKey: config.spm.apiKey,
|
|
262
|
+
userPartition: config.spm.userPartition,
|
|
263
|
+
});
|
|
264
|
+
await client.status([]);
|
|
265
|
+
pass(`SPM API reachable at ${config.spm.baseUrl}; key accepted`);
|
|
266
|
+
} catch (error) {
|
|
267
|
+
fail(
|
|
268
|
+
`SPM live check failed: ${error.message}`,
|
|
269
|
+
"verify the SPM key is not revoked, belongs to this environment, and carries memory:read (plus memory:partition when a partition is configured)",
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
if (failures > 0) throw new Error(`doctor found ${failures} problem(s)`);
|
|
221
273
|
return;
|
|
222
274
|
}
|
|
223
275
|
if (command === "print-config") {
|
package/src/config.js
CHANGED
|
@@ -5,6 +5,22 @@ import { dirname, join } from "node:path";
|
|
|
5
5
|
|
|
6
6
|
export const CONFIG_VERSION = 1;
|
|
7
7
|
const LOOPBACK = new Set(["127.0.0.1", "::1", "localhost"]);
|
|
8
|
+
// Mirrors the hosted data-plane contract (tenant principal validation):
|
|
9
|
+
// 1-128 chars, leading alphanumeric, then alphanumerics plus . _ : @ -
|
|
10
|
+
export const USER_PARTITION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/;
|
|
11
|
+
|
|
12
|
+
export function validateUserPartition(value, name = "spm.userPartition") {
|
|
13
|
+
if (value === undefined || value === null) return "";
|
|
14
|
+
if (typeof value !== "string") throw new Error(`${name} must be a string`);
|
|
15
|
+
const trimmed = value.trim();
|
|
16
|
+
if (!trimmed) return "";
|
|
17
|
+
if (!USER_PARTITION_PATTERN.test(trimmed)) {
|
|
18
|
+
throw new Error(
|
|
19
|
+
`${name} must match ^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$ (use a stable opaque id, not a secret or display name)`,
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
return trimmed;
|
|
23
|
+
}
|
|
8
24
|
|
|
9
25
|
export function configPath(env = process.env) {
|
|
10
26
|
const root = env.SPM_CONFIG_HOME
|
|
@@ -49,6 +65,7 @@ export function validateConfig(input) {
|
|
|
49
65
|
}
|
|
50
66
|
const providerKey = requireString(provider.apiKey, "provider.apiKey");
|
|
51
67
|
const spmKey = requireString(spm.apiKey, "spm.apiKey");
|
|
68
|
+
const userPartition = validateUserPartition(spm.userPartition);
|
|
52
69
|
const localToken = requireString(proxy.localToken, "proxy.localToken");
|
|
53
70
|
if (localToken.length < 16) throw new Error("proxy.localToken must contain at least 16 characters");
|
|
54
71
|
if (localToken === providerKey || localToken === spmKey) {
|
|
@@ -81,6 +98,7 @@ export function validateConfig(input) {
|
|
|
81
98
|
spm: {
|
|
82
99
|
apiKey: spmKey,
|
|
83
100
|
baseUrl: httpsUrl(spm.baseUrl || "https://api.spmos.ai", "spm.baseUrl"),
|
|
101
|
+
userPartition,
|
|
84
102
|
},
|
|
85
103
|
provider: {
|
|
86
104
|
id: requireString(provider.id || "custom", "provider.id"),
|
|
@@ -126,6 +144,7 @@ export async function loadConfig(path = configPath(), env = process.env) {
|
|
|
126
144
|
const parsed = JSON.parse(await readFile(path, "utf8"));
|
|
127
145
|
const overridden = structuredClone(parsed);
|
|
128
146
|
if (env.SPM_API_KEY) overridden.spm.apiKey = env.SPM_API_KEY;
|
|
147
|
+
if (env.SPM_USER_PARTITION) overridden.spm.userPartition = env.SPM_USER_PARTITION;
|
|
129
148
|
if (env.SPM_LOCAL_PROVIDER_API_KEY) overridden.provider.apiKey = env.SPM_LOCAL_PROVIDER_API_KEY;
|
|
130
149
|
if (env.SPM_LOCAL_PROXY_TOKEN) overridden.proxy.localToken = env.SPM_LOCAL_PROXY_TOKEN;
|
|
131
150
|
return validateConfig(overridden);
|
package/src/gateway.js
CHANGED
|
@@ -4,6 +4,7 @@ import { createServer } from "node:http";
|
|
|
4
4
|
import { zstdDecompressSync } from "node:zlib";
|
|
5
5
|
|
|
6
6
|
import { HostedMemoryClient, memorySourceId, memorySourceIds } from "./memory.js";
|
|
7
|
+
import { USER_PARTITION_PATTERN } from "./config.js";
|
|
7
8
|
import { applyElision, elisionCandidates } from "./elision.js";
|
|
8
9
|
import {
|
|
9
10
|
ProjectionError,
|
|
@@ -499,7 +500,11 @@ async function handleModelPost(request, response, config, memory, providerReques
|
|
|
499
500
|
|
|
500
501
|
export function createGateway({
|
|
501
502
|
config,
|
|
502
|
-
memory = new HostedMemoryClient({
|
|
503
|
+
memory = new HostedMemoryClient({
|
|
504
|
+
baseUrl: config.spm.baseUrl,
|
|
505
|
+
apiKey: config.spm.apiKey,
|
|
506
|
+
userPartition: config.spm.userPartition || "",
|
|
507
|
+
}),
|
|
503
508
|
providerRequest = requestProvider,
|
|
504
509
|
} = {}) {
|
|
505
510
|
return createServer(async (request, response) => {
|
|
@@ -508,6 +513,21 @@ export function createGateway({
|
|
|
508
513
|
const host = requestHost(request);
|
|
509
514
|
if (!LOOPBACK.has(host)) throw Object.assign(new Error("Local Proxy Host is forbidden"), { code: "spm_local_host_forbidden", statusCode: 403 });
|
|
510
515
|
if (request.headers.origin) throw Object.assign(new Error("Browser-origin requests are forbidden"), { code: "spm_local_browser_forbidden", statusCode: 403 });
|
|
516
|
+
// Optional per-request end-user partition. An invalid value fails the
|
|
517
|
+
// request closed: silently falling back to the configured partition
|
|
518
|
+
// would mix one user's memory into another user's space.
|
|
519
|
+
let requestMemory = memory;
|
|
520
|
+
const partitionHeader = request.headers["x-spm-user-partition"];
|
|
521
|
+
if (typeof partitionHeader === "string" && partitionHeader.trim()) {
|
|
522
|
+
const partition = partitionHeader.trim();
|
|
523
|
+
if (!USER_PARTITION_PATTERN.test(partition)) {
|
|
524
|
+
throw Object.assign(
|
|
525
|
+
new Error("x-spm-user-partition must match ^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$"),
|
|
526
|
+
{ code: "spm_invalid_user_partition", statusCode: 400 },
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
requestMemory = memory.withPartition(partition);
|
|
530
|
+
}
|
|
511
531
|
const local = new URL(request.url, "http://localhost");
|
|
512
532
|
if (request.method === "GET" && ["/health", "/livez"].includes(local.pathname)) {
|
|
513
533
|
sendJson(response, 200, local.pathname === "/livez" ? { status: "ok" } : {
|
|
@@ -533,7 +553,7 @@ export function createGateway({
|
|
|
533
553
|
if (config.provider.apiStyle !== expected) {
|
|
534
554
|
throw Object.assign(new Error("Request protocol is incompatible with the configured provider"), { code: "spm_provider_route_invalid", statusCode: 422 });
|
|
535
555
|
}
|
|
536
|
-
await handleModelPost(request, response, config,
|
|
556
|
+
await handleModelPost(request, response, config, requestMemory, providerRequest, protocol, target[1]);
|
|
537
557
|
} catch (error) {
|
|
538
558
|
if (response.headersSent) {
|
|
539
559
|
response.destroy();
|
package/src/memory.js
CHANGED
|
@@ -9,13 +9,31 @@ export function memorySourceIds(sourceId, text) {
|
|
|
9
9
|
}
|
|
10
10
|
|
|
11
11
|
export class HostedMemoryClient {
|
|
12
|
-
constructor({ baseUrl, apiKey, fetchImpl = globalThis.fetch, timeoutMs = 30_000 }) {
|
|
12
|
+
constructor({ baseUrl, apiKey, userPartition = "", fetchImpl = globalThis.fetch, timeoutMs = 30_000 }) {
|
|
13
13
|
this.baseUrl = baseUrl.replace(/\/$/, "");
|
|
14
14
|
this.apiKey = apiKey;
|
|
15
|
+
this.userPartition = userPartition;
|
|
15
16
|
this.fetchImpl = fetchImpl;
|
|
16
17
|
this.timeoutMs = timeoutMs;
|
|
17
18
|
}
|
|
18
19
|
|
|
20
|
+
// A per-request partition override shares the transport but never mutates
|
|
21
|
+
// the configured client: cross-partition memory mixing is a data-integrity
|
|
22
|
+
// failure, so the scoped client is always a separate object.
|
|
23
|
+
withPartition(userPartition) {
|
|
24
|
+
return new HostedMemoryClient({
|
|
25
|
+
baseUrl: this.baseUrl,
|
|
26
|
+
apiKey: this.apiKey,
|
|
27
|
+
userPartition,
|
|
28
|
+
fetchImpl: this.fetchImpl,
|
|
29
|
+
timeoutMs: this.timeoutMs,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
partitionFields() {
|
|
34
|
+
return this.userPartition ? { user_partition: this.userPartition } : {};
|
|
35
|
+
}
|
|
36
|
+
|
|
19
37
|
async request(path, body) {
|
|
20
38
|
const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
21
39
|
method: "POST",
|
|
@@ -36,6 +54,7 @@ export class HostedMemoryClient {
|
|
|
36
54
|
query: query.slice(0, 2000),
|
|
37
55
|
top_k: 6,
|
|
38
56
|
context_tokens: Math.max(1, Math.min(contextTokens, 1_000_000)),
|
|
57
|
+
...this.partitionFields(),
|
|
39
58
|
});
|
|
40
59
|
if (response.status === 424) {
|
|
41
60
|
return { text: "", status: "empty", gateReason: "upstream_dependency", evidenceRefs: [] };
|
|
@@ -87,6 +106,7 @@ export class HostedMemoryClient {
|
|
|
87
106
|
source_id: id,
|
|
88
107
|
source_kind: sourceKind,
|
|
89
108
|
role_spans: chunkSpans,
|
|
109
|
+
...this.partitionFields(),
|
|
90
110
|
});
|
|
91
111
|
if (!response.ok) throw new Error(`SPM ingest returned HTTP ${response.status}`);
|
|
92
112
|
}
|
|
@@ -139,7 +159,7 @@ export class HostedMemoryClient {
|
|
|
139
159
|
// extraction-ready. Elision must only stub outputs the memory plane can
|
|
140
160
|
// actually serve back.
|
|
141
161
|
async status(sourceIds) {
|
|
142
|
-
const result = await this.mcpCall("status", { source_ids: sourceIds });
|
|
162
|
+
const result = await this.mcpCall("status", { source_ids: sourceIds, ...this.partitionFields() });
|
|
143
163
|
let payload = result && result.result && result.result.structuredContent;
|
|
144
164
|
if (!payload) {
|
|
145
165
|
const content = result && result.result && result.result.content;
|
package/src/terminal.js
CHANGED
|
@@ -3,6 +3,9 @@ import { createInterface } from "node:readline/promises";
|
|
|
3
3
|
const BLUE = "\u001b[38;2;65;145;255m";
|
|
4
4
|
const DIM = "\u001b[2m";
|
|
5
5
|
const RESET = "\u001b[0m";
|
|
6
|
+
const RED = "\u001b[31m";
|
|
7
|
+
const YELLOW = "\u001b[33m";
|
|
8
|
+
const GREEN = "\u001b[32m";
|
|
6
9
|
|
|
7
10
|
export const SPM_ART = String.raw`
|
|
8
11
|
███████╗██████╗ ███╗ ███╗
|
|
@@ -20,6 +23,18 @@ export function blue(text) {
|
|
|
20
23
|
return `${BLUE}${text}${RESET}`;
|
|
21
24
|
}
|
|
22
25
|
|
|
26
|
+
export function red(text) {
|
|
27
|
+
return `${RED}${text}${RESET}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function yellow(text) {
|
|
31
|
+
return `${YELLOW}${text}${RESET}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function green(text) {
|
|
35
|
+
return `${GREEN}${text}${RESET}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
23
38
|
export async function promptLine(question, {
|
|
24
39
|
input = process.stdin,
|
|
25
40
|
output = process.stdout,
|