@spmos/local-proxy 0.1.1 → 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 +52 -0
- package/package.json +1 -1
- package/src/cli.js +58 -6
- package/src/config.js +30 -0
- package/src/elision.js +149 -0
- package/src/gateway.js +82 -6
- package/src/memory.js +82 -1
- package/src/terminal.js +15 -0
package/README.md
CHANGED
|
@@ -116,3 +116,55 @@ are covered by the repository's 32-test Local Proxy suite. The continuity gate
|
|
|
116
116
|
also recognizes deterministic input identities created by `0.1.0`, so an
|
|
117
117
|
upgrade does not require old content to be re-ingested before it can prove
|
|
118
118
|
continuity.
|
|
119
|
+
|
|
120
|
+
## Tool-output elision in 0.1.2
|
|
121
|
+
|
|
122
|
+
Version `0.1.2` ports the hosted gateway's tool-output elision to the local
|
|
123
|
+
path, across all three protocols (Chat Completions tool messages, Responses
|
|
124
|
+
`function_call_output`, Anthropic `tool_result` blocks):
|
|
125
|
+
|
|
126
|
+
- tool outputs older than `proxy.elisionKeepRounds` assistant rounds
|
|
127
|
+
(default 4) become candidates;
|
|
128
|
+
- a candidate is replaced by a bounded stub only when the identical content
|
|
129
|
+
is already persisted in hosted SPM and extraction-ready (readiness is
|
|
130
|
+
checked per request through the memory status tool); otherwise the full
|
|
131
|
+
output is kept and captured in the background so a later turn can elide it;
|
|
132
|
+
- Anthropic `tool_use`/`tool_result` pairing is never broken: only the
|
|
133
|
+
block content is stubbed, and blocks carrying `cache_control` breakpoints
|
|
134
|
+
are never touched;
|
|
135
|
+
- responses carry `x-spm-elided-items` / `x-spm-elided-tokens`, and
|
|
136
|
+
`x-spm-continuity-state` reports `elided_tool_output` when a request was
|
|
137
|
+
served with stubs.
|
|
138
|
+
|
|
139
|
+
Configuration (all optional):
|
|
140
|
+
|
|
141
|
+
- `proxy.elisionEnabled` (default `true`);
|
|
142
|
+
- `proxy.elisionKeepRounds` (default `4`);
|
|
143
|
+
- `proxy.elisionCaptureLimit` (default `8`, bounds background capture work
|
|
144
|
+
per request).
|
|
145
|
+
|
|
146
|
+
Elision is best-effort: any readiness-check or capture failure leaves the
|
|
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) {
|
|
@@ -68,11 +85,20 @@ export function validateConfig(input) {
|
|
|
68
85
|
if (!Number.isInteger(maxRecalledTokens) || maxRecalledTokens < 1) {
|
|
69
86
|
throw new Error("proxy.maxRecalledTokens must be a positive integer");
|
|
70
87
|
}
|
|
88
|
+
const elisionKeepRounds = Number(proxy.elisionKeepRounds || 4);
|
|
89
|
+
const elisionCaptureLimit = Number(proxy.elisionCaptureLimit || 8);
|
|
90
|
+
if (!Number.isInteger(elisionKeepRounds) || elisionKeepRounds < 1) {
|
|
91
|
+
throw new Error("proxy.elisionKeepRounds must be a positive integer");
|
|
92
|
+
}
|
|
93
|
+
if (!Number.isInteger(elisionCaptureLimit) || elisionCaptureLimit < 0) {
|
|
94
|
+
throw new Error("proxy.elisionCaptureLimit must be a non-negative integer");
|
|
95
|
+
}
|
|
71
96
|
return {
|
|
72
97
|
version: CONFIG_VERSION,
|
|
73
98
|
spm: {
|
|
74
99
|
apiKey: spmKey,
|
|
75
100
|
baseUrl: httpsUrl(spm.baseUrl || "https://api.spmos.ai", "spm.baseUrl"),
|
|
101
|
+
userPartition,
|
|
76
102
|
},
|
|
77
103
|
provider: {
|
|
78
104
|
id: requireString(provider.id || "custom", "provider.id"),
|
|
@@ -95,6 +121,9 @@ export function validateConfig(input) {
|
|
|
95
121
|
? proxy.memoryMode : "read-write",
|
|
96
122
|
compressionMode: ["passthrough", "shadow", "deterministic"].includes(proxy.compressionMode)
|
|
97
123
|
? proxy.compressionMode : "deterministic",
|
|
124
|
+
elisionEnabled: proxy.elisionEnabled !== false,
|
|
125
|
+
elisionKeepRounds,
|
|
126
|
+
elisionCaptureLimit,
|
|
98
127
|
},
|
|
99
128
|
};
|
|
100
129
|
}
|
|
@@ -115,6 +144,7 @@ export async function loadConfig(path = configPath(), env = process.env) {
|
|
|
115
144
|
const parsed = JSON.parse(await readFile(path, "utf8"));
|
|
116
145
|
const overridden = structuredClone(parsed);
|
|
117
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;
|
|
118
148
|
if (env.SPM_LOCAL_PROVIDER_API_KEY) overridden.provider.apiKey = env.SPM_LOCAL_PROVIDER_API_KEY;
|
|
119
149
|
if (env.SPM_LOCAL_PROXY_TOKEN) overridden.proxy.localToken = env.SPM_LOCAL_PROXY_TOKEN;
|
|
120
150
|
return validateConfig(overridden);
|
package/src/elision.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { estimateTokens } from "./projection.js";
|
|
2
|
+
import { memorySourceId } from "./memory.js";
|
|
3
|
+
|
|
4
|
+
// Tool-output elision (0.1.2): local port of the hosted gateway rule.
|
|
5
|
+
// Agentic histories are mostly old tool outputs; the exchange-unit
|
|
6
|
+
// compressor cannot touch them (protected units veto the request), so
|
|
7
|
+
// elision works at item level: tool RESULTS older than K assistant rounds
|
|
8
|
+
// are replaced with a bounded stub, but only when the identical content is
|
|
9
|
+
// already persisted in hosted SPM and extraction-ready (Gate C). The model
|
|
10
|
+
// can always retrieve the original through memory recall by source id.
|
|
11
|
+
|
|
12
|
+
export const MIN_OUTPUT_CHARS = 200;
|
|
13
|
+
export const MAX_OUTPUT_CHARS = 12_000;
|
|
14
|
+
|
|
15
|
+
export function elisionStub(sourceId, tokens) {
|
|
16
|
+
return "[SPM: tool output elided — " + tokens + " tokens retrievable via memory recall "
|
|
17
|
+
+ "(source " + sourceId + "). Ask for this source or re-run the tool if the full "
|
|
18
|
+
+ "content is needed.]";
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function toolOutputSourceId(scope, text) {
|
|
22
|
+
return memorySourceId(scope, "tool_output", text);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function walkChat(messages, keepRounds, scope) {
|
|
26
|
+
const elidable = [];
|
|
27
|
+
const capturable = [];
|
|
28
|
+
let roundsAfter = 0;
|
|
29
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
30
|
+
const item = messages[index];
|
|
31
|
+
if (!item || typeof item !== "object") continue;
|
|
32
|
+
if (item.role === "assistant") { roundsAfter += 1; continue; }
|
|
33
|
+
if (item.role !== "tool") continue;
|
|
34
|
+
const text = typeof item.content === "string" ? item.content : "";
|
|
35
|
+
if (text.length < MIN_OUTPUT_CHARS || text.length > MAX_OUTPUT_CHARS) continue;
|
|
36
|
+
const candidate = { item, sourceId: toolOutputSourceId(scope, text), text, tokens: estimateTokens(item) };
|
|
37
|
+
(roundsAfter >= keepRounds ? elidable : capturable).push({ index, candidate });
|
|
38
|
+
}
|
|
39
|
+
elidable.reverse();
|
|
40
|
+
capturable.reverse();
|
|
41
|
+
return [elidable, capturable];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function walkResponses(items, keepRounds, scope) {
|
|
45
|
+
const elidable = [];
|
|
46
|
+
const capturable = [];
|
|
47
|
+
let roundsAfter = 0;
|
|
48
|
+
for (let index = items.length - 1; index >= 0; index -= 1) {
|
|
49
|
+
const item = items[index];
|
|
50
|
+
if (!item || typeof item !== "object") continue;
|
|
51
|
+
if (item.type === "message" && item.role === "assistant") { roundsAfter += 1; continue; }
|
|
52
|
+
if (item.type !== "function_call_output") continue;
|
|
53
|
+
const text = typeof item.output === "string" ? item.output : "";
|
|
54
|
+
if (text.length < MIN_OUTPUT_CHARS || text.length > MAX_OUTPUT_CHARS) continue;
|
|
55
|
+
const candidate = { item, sourceId: toolOutputSourceId(scope, text), text, tokens: estimateTokens(item) };
|
|
56
|
+
(roundsAfter >= keepRounds ? elidable : capturable).push({ index, candidate });
|
|
57
|
+
}
|
|
58
|
+
elidable.reverse();
|
|
59
|
+
capturable.reverse();
|
|
60
|
+
return [elidable, capturable];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function anthropicToolResultText(block) {
|
|
64
|
+
const content = block.content;
|
|
65
|
+
if (typeof content === "string") return content;
|
|
66
|
+
if (Array.isArray(content)) {
|
|
67
|
+
const texts = [];
|
|
68
|
+
for (const sub of content) {
|
|
69
|
+
if (!sub || typeof sub !== "object" || sub.type !== "text" || typeof sub.text !== "string") return null;
|
|
70
|
+
texts.push(sub.text);
|
|
71
|
+
}
|
|
72
|
+
return texts.join(String.fromCharCode(10));
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function walkAnthropic(messages, keepRounds, scope) {
|
|
78
|
+
// The block is never removed -- Anthropic requires every tool_use to keep
|
|
79
|
+
// its paired tool_result -- so elision replaces only the block CONTENT,
|
|
80
|
+
// leaving tool_use_id pairing intact. Blocks with cache_control are
|
|
81
|
+
// skipped: they are deliberate prompt-cache breakpoints.
|
|
82
|
+
const elidable = [];
|
|
83
|
+
const capturable = [];
|
|
84
|
+
let roundsAfter = 0;
|
|
85
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
86
|
+
const item = messages[index];
|
|
87
|
+
if (!item || typeof item !== "object") continue;
|
|
88
|
+
if (item.role === "assistant") { roundsAfter += 1; continue; }
|
|
89
|
+
if (item.role !== "user" || !Array.isArray(item.content)) continue;
|
|
90
|
+
item.content.forEach((block, blockIndex) => {
|
|
91
|
+
if (!block || typeof block !== "object" || block.type !== "tool_result") return;
|
|
92
|
+
if (block.cache_control) return;
|
|
93
|
+
const text = anthropicToolResultText(block);
|
|
94
|
+
if (text === null || text.length < MIN_OUTPUT_CHARS || text.length > MAX_OUTPUT_CHARS) return;
|
|
95
|
+
const candidate = {
|
|
96
|
+
item,
|
|
97
|
+
sourceId: toolOutputSourceId(scope, text),
|
|
98
|
+
text,
|
|
99
|
+
tokens: estimateTokens({ t: text }),
|
|
100
|
+
blockIndex,
|
|
101
|
+
};
|
|
102
|
+
(roundsAfter >= keepRounds ? elidable : capturable).push({ index, candidate });
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
elidable.reverse();
|
|
106
|
+
capturable.reverse();
|
|
107
|
+
return [elidable, capturable];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function elisionCandidates(protocol, body, { scope, keepRounds }) {
|
|
111
|
+
if (!Number.isInteger(keepRounds) || keepRounds < 1) {
|
|
112
|
+
throw new Error("keepRounds must be a positive integer");
|
|
113
|
+
}
|
|
114
|
+
if (protocol === "chat" && Array.isArray(body.messages)) {
|
|
115
|
+
return walkChat(body.messages, keepRounds, scope);
|
|
116
|
+
}
|
|
117
|
+
if (protocol === "responses" && Array.isArray(body.input)) {
|
|
118
|
+
return walkResponses(body.input, keepRounds, scope);
|
|
119
|
+
}
|
|
120
|
+
if (protocol === "messages" && Array.isArray(body.messages)) {
|
|
121
|
+
return walkAnthropic(body.messages, keepRounds, scope);
|
|
122
|
+
}
|
|
123
|
+
return [[], []];
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function applyElision(protocol, body, { elided }) {
|
|
127
|
+
const result = structuredClone(body);
|
|
128
|
+
const collectionName = protocol === "responses" ? "input" : "messages";
|
|
129
|
+
const collection = result[collectionName];
|
|
130
|
+
if (!Array.isArray(collection)) return result;
|
|
131
|
+
for (const { index, candidate } of elided) {
|
|
132
|
+
if (index < 0 || index >= collection.length) continue;
|
|
133
|
+
const item = collection[index];
|
|
134
|
+
if (!item || typeof item !== "object") continue;
|
|
135
|
+
const stub = elisionStub(candidate.sourceId, candidate.tokens);
|
|
136
|
+
if (protocol === "chat" && item.role === "tool") {
|
|
137
|
+
item.content = stub;
|
|
138
|
+
} else if (protocol === "responses" && item.type === "function_call_output") {
|
|
139
|
+
item.output = stub;
|
|
140
|
+
} else if (protocol === "messages" && Number.isInteger(candidate.blockIndex)) {
|
|
141
|
+
const content = item.content;
|
|
142
|
+
const block = Array.isArray(content) ? content[candidate.blockIndex] : null;
|
|
143
|
+
if (block && typeof block === "object" && block.type === "tool_result") {
|
|
144
|
+
block.content = stub;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return result;
|
|
149
|
+
}
|
package/src/gateway.js
CHANGED
|
@@ -4,6 +4,8 @@ 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";
|
|
8
|
+
import { applyElision, elisionCandidates } from "./elision.js";
|
|
7
9
|
import {
|
|
8
10
|
ProjectionError,
|
|
9
11
|
compressProjection,
|
|
@@ -265,7 +267,7 @@ class SseObserver {
|
|
|
265
267
|
}
|
|
266
268
|
}
|
|
267
269
|
|
|
268
|
-
function spmHeaders({ requestId, memoryMode, memoryState, compressionMode, continuityState, original, forwarded, recalled }) {
|
|
270
|
+
function spmHeaders({ requestId, memoryMode, memoryState, compressionMode, continuityState, original, forwarded, recalled, elidedItems, elidedTokens }) {
|
|
269
271
|
return {
|
|
270
272
|
"x-spm-local-proxy": "v1",
|
|
271
273
|
"x-spm-request-id": requestId,
|
|
@@ -276,6 +278,8 @@ function spmHeaders({ requestId, memoryMode, memoryState, compressionMode, conti
|
|
|
276
278
|
"x-spm-original-input-tokens": String(original),
|
|
277
279
|
"x-spm-forwarded-input-tokens": String(forwarded),
|
|
278
280
|
"x-spm-recalled-tokens": String(recalled),
|
|
281
|
+
"x-spm-elided-items": String(elidedItems || 0),
|
|
282
|
+
"x-spm-elided-tokens": String(elidedTokens || 0),
|
|
279
283
|
};
|
|
280
284
|
}
|
|
281
285
|
|
|
@@ -312,8 +316,58 @@ async function relayModelRequest(request, response, config, providerRequest) {
|
|
|
312
316
|
async function handleModelPost(request, response, config, memory, providerRequest, protocol, route) {
|
|
313
317
|
authenticate(request, config);
|
|
314
318
|
const body = await readRequestBody(request);
|
|
315
|
-
const projection = projectRequest(protocol, body);
|
|
316
319
|
const { memoryMode, compressionMode } = requestModes(request, config);
|
|
320
|
+
// Tool-output elision (0.1.2): stub old tool results whose identical
|
|
321
|
+
// content hosted SPM has already persisted and indexed (Gate C); capture
|
|
322
|
+
// the rest fire-and-forget so later turns can elide them. Elision runs
|
|
323
|
+
// before projection/recall/compression, mirroring the hosted gateway;
|
|
324
|
+
// every downstream path (including compression bypass) forwards the
|
|
325
|
+
// elided body. Best-effort: any failure leaves the body untouched.
|
|
326
|
+
let workingBody = body;
|
|
327
|
+
let elidedInfo = null;
|
|
328
|
+
if (config.proxy.elisionEnabled && memoryMode.includes("write")) {
|
|
329
|
+
try {
|
|
330
|
+
const scope = "local:" + protocol;
|
|
331
|
+
const [elidable, capturable] = elisionCandidates(protocol, body, {
|
|
332
|
+
scope,
|
|
333
|
+
keepRounds: config.proxy.elisionKeepRounds,
|
|
334
|
+
});
|
|
335
|
+
let ready = new Set();
|
|
336
|
+
if (elidable.length) {
|
|
337
|
+
try {
|
|
338
|
+
const report = await memory.status(elidable.map((entry) => entry.candidate.sourceId));
|
|
339
|
+
ready = new Set(report.readySourceIds);
|
|
340
|
+
} catch {
|
|
341
|
+
ready = new Set();
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
const elideNow = elidable.filter((entry) => ready.has(entry.candidate.sourceId));
|
|
345
|
+
const captureQueue = [
|
|
346
|
+
...capturable,
|
|
347
|
+
...elidable.filter((entry) => !ready.has(entry.candidate.sourceId)),
|
|
348
|
+
].slice(0, config.proxy.elisionCaptureLimit);
|
|
349
|
+
for (const { candidate } of captureQueue) {
|
|
350
|
+
void captureText(
|
|
351
|
+
memory,
|
|
352
|
+
candidate.text,
|
|
353
|
+
candidate.sourceId,
|
|
354
|
+
"tool_output",
|
|
355
|
+
[["assistant", 0, [...candidate.text].length]],
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
if (elideNow.length) {
|
|
359
|
+
workingBody = applyElision(protocol, body, { elided: elideNow });
|
|
360
|
+
elidedInfo = {
|
|
361
|
+
items: elideNow.length,
|
|
362
|
+
tokens: elideNow.reduce((sum, entry) => sum + entry.candidate.tokens, 0),
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
} catch {
|
|
366
|
+
workingBody = body;
|
|
367
|
+
elidedInfo = null;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
const projection = projectRequest(protocol, workingBody);
|
|
317
371
|
const original = estimateTokens(body);
|
|
318
372
|
let recalledContext = "";
|
|
319
373
|
let recallOutcome = { text: "", status: "off", gateReason: "memory_read_disabled", evidenceRefs: [] };
|
|
@@ -355,7 +409,7 @@ async function handleModelPost(request, response, config, memory, providerReques
|
|
|
355
409
|
&& (!recalledContext || !recallPassed || !recallCoversRemoval);
|
|
356
410
|
if (recallFailed || projectionBypass || deterministicBypass || unprovenRemoval) {
|
|
357
411
|
effectiveCompression = "passthrough";
|
|
358
|
-
forwardedBody = structuredClone(
|
|
412
|
+
forwardedBody = structuredClone(workingBody);
|
|
359
413
|
continuityState = recallFailed ? "bypassed_recall_degraded"
|
|
360
414
|
: projectionBypass ? "bypassed_provider_state"
|
|
361
415
|
: deterministicBypass ? "bypassed_protected_context"
|
|
@@ -367,9 +421,10 @@ async function handleModelPost(request, response, config, memory, providerReques
|
|
|
367
421
|
forwardedBody = patchedBody(projection, { untrustedContext: recalledContext });
|
|
368
422
|
continuityState = "not_applicable";
|
|
369
423
|
} else {
|
|
370
|
-
forwardedBody = structuredClone(
|
|
424
|
+
forwardedBody = structuredClone(workingBody);
|
|
371
425
|
continuityState = compressionMode === "shadow" ? "shadow_only" : "not_applicable";
|
|
372
426
|
}
|
|
427
|
+
if (elidedInfo && continuityState !== "committed") continuityState = "elided_tool_output";
|
|
373
428
|
let inputCaptureOk = true;
|
|
374
429
|
if (memoryMode.includes("write")) inputCaptureOk = await captureInputs(memory, projection);
|
|
375
430
|
const upstream = await providerRequest({
|
|
@@ -388,6 +443,8 @@ async function handleModelPost(request, response, config, memory, providerReques
|
|
|
388
443
|
original,
|
|
389
444
|
forwarded: estimateTokens(forwardedBody),
|
|
390
445
|
recalled: estimateTokens(recalledContext),
|
|
446
|
+
elidedItems: elidedInfo ? elidedInfo.items : 0,
|
|
447
|
+
elidedTokens: elidedInfo ? elidedInfo.tokens : 0,
|
|
391
448
|
};
|
|
392
449
|
if (body.stream === true) {
|
|
393
450
|
const observer = new SseObserver(protocol);
|
|
@@ -443,7 +500,11 @@ async function handleModelPost(request, response, config, memory, providerReques
|
|
|
443
500
|
|
|
444
501
|
export function createGateway({
|
|
445
502
|
config,
|
|
446
|
-
memory = new HostedMemoryClient({
|
|
503
|
+
memory = new HostedMemoryClient({
|
|
504
|
+
baseUrl: config.spm.baseUrl,
|
|
505
|
+
apiKey: config.spm.apiKey,
|
|
506
|
+
userPartition: config.spm.userPartition || "",
|
|
507
|
+
}),
|
|
447
508
|
providerRequest = requestProvider,
|
|
448
509
|
} = {}) {
|
|
449
510
|
return createServer(async (request, response) => {
|
|
@@ -452,6 +513,21 @@ export function createGateway({
|
|
|
452
513
|
const host = requestHost(request);
|
|
453
514
|
if (!LOOPBACK.has(host)) throw Object.assign(new Error("Local Proxy Host is forbidden"), { code: "spm_local_host_forbidden", statusCode: 403 });
|
|
454
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
|
+
}
|
|
455
531
|
const local = new URL(request.url, "http://localhost");
|
|
456
532
|
if (request.method === "GET" && ["/health", "/livez"].includes(local.pathname)) {
|
|
457
533
|
sendJson(response, 200, local.pathname === "/livez" ? { status: "ok" } : {
|
|
@@ -477,7 +553,7 @@ export function createGateway({
|
|
|
477
553
|
if (config.provider.apiStyle !== expected) {
|
|
478
554
|
throw Object.assign(new Error("Request protocol is incompatible with the configured provider"), { code: "spm_provider_route_invalid", statusCode: 422 });
|
|
479
555
|
}
|
|
480
|
-
await handleModelPost(request, response, config,
|
|
556
|
+
await handleModelPost(request, response, config, requestMemory, providerRequest, protocol, target[1]);
|
|
481
557
|
} catch (error) {
|
|
482
558
|
if (response.headersSent) {
|
|
483
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,10 +106,72 @@ 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
|
}
|
|
93
113
|
}
|
|
114
|
+
|
|
115
|
+
async mcpCall(toolName, args) {
|
|
116
|
+
const headers = {
|
|
117
|
+
authorization: "Bearer " + this.apiKey,
|
|
118
|
+
"content-type": "application/json",
|
|
119
|
+
accept: "application/json, text/event-stream",
|
|
120
|
+
};
|
|
121
|
+
const init = await this.fetchImpl(this.baseUrl + "/mcp", {
|
|
122
|
+
method: "POST",
|
|
123
|
+
redirect: "error",
|
|
124
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
125
|
+
headers,
|
|
126
|
+
body: JSON.stringify({
|
|
127
|
+
jsonrpc: "2.0",
|
|
128
|
+
id: 1,
|
|
129
|
+
method: "initialize",
|
|
130
|
+
params: {
|
|
131
|
+
protocolVersion: "2025-03-26",
|
|
132
|
+
capabilities: {},
|
|
133
|
+
clientInfo: { name: "spm-local-proxy", version: "0" },
|
|
134
|
+
},
|
|
135
|
+
}),
|
|
136
|
+
});
|
|
137
|
+
if (!init.ok) throw new Error("SPM MCP initialize returned HTTP " + init.status);
|
|
138
|
+
const response = await this.fetchImpl(this.baseUrl + "/mcp", {
|
|
139
|
+
method: "POST",
|
|
140
|
+
redirect: "error",
|
|
141
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
142
|
+
headers,
|
|
143
|
+
body: JSON.stringify({
|
|
144
|
+
jsonrpc: "2.0",
|
|
145
|
+
id: 2,
|
|
146
|
+
method: "tools/call",
|
|
147
|
+
params: { name: toolName, arguments: args },
|
|
148
|
+
}),
|
|
149
|
+
});
|
|
150
|
+
if (!response.ok) throw new Error("SPM MCP tools/call returned HTTP " + response.status);
|
|
151
|
+
const raw = await response.text();
|
|
152
|
+
for (const line of raw.split(String.fromCharCode(10))) {
|
|
153
|
+
if (line.startsWith("data:")) return JSON.parse(line.slice(5).trim());
|
|
154
|
+
}
|
|
155
|
+
return JSON.parse(raw);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Readiness check (Gate C): which candidate source ids are persisted and
|
|
159
|
+
// extraction-ready. Elision must only stub outputs the memory plane can
|
|
160
|
+
// actually serve back.
|
|
161
|
+
async status(sourceIds) {
|
|
162
|
+
const result = await this.mcpCall("status", { source_ids: sourceIds, ...this.partitionFields() });
|
|
163
|
+
let payload = result && result.result && result.result.structuredContent;
|
|
164
|
+
if (!payload) {
|
|
165
|
+
const content = result && result.result && result.result.content;
|
|
166
|
+
const text = content && content[0] && content[0].text;
|
|
167
|
+
payload = {};
|
|
168
|
+
if (typeof text === "string") {
|
|
169
|
+
try { payload = JSON.parse(text); } catch { payload = {}; }
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const ready = Array.isArray(payload.ready_source_ids) ? payload.ready_source_ids : [];
|
|
173
|
+
return { readySourceIds: ready.map(String) };
|
|
174
|
+
}
|
|
94
175
|
}
|
|
95
176
|
|
|
96
177
|
export function memorySourceId(scope, kind, text) {
|
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,
|