@spmos/local-proxy 0.1.1 → 0.1.2

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 CHANGED
@@ -116,3 +116,32 @@ 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spmos/local-proxy",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Loopback-only SPM memory and compression proxy with local provider credentials",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/config.js CHANGED
@@ -68,6 +68,14 @@ export function validateConfig(input) {
68
68
  if (!Number.isInteger(maxRecalledTokens) || maxRecalledTokens < 1) {
69
69
  throw new Error("proxy.maxRecalledTokens must be a positive integer");
70
70
  }
71
+ const elisionKeepRounds = Number(proxy.elisionKeepRounds || 4);
72
+ const elisionCaptureLimit = Number(proxy.elisionCaptureLimit || 8);
73
+ if (!Number.isInteger(elisionKeepRounds) || elisionKeepRounds < 1) {
74
+ throw new Error("proxy.elisionKeepRounds must be a positive integer");
75
+ }
76
+ if (!Number.isInteger(elisionCaptureLimit) || elisionCaptureLimit < 0) {
77
+ throw new Error("proxy.elisionCaptureLimit must be a non-negative integer");
78
+ }
71
79
  return {
72
80
  version: CONFIG_VERSION,
73
81
  spm: {
@@ -95,6 +103,9 @@ export function validateConfig(input) {
95
103
  ? proxy.memoryMode : "read-write",
96
104
  compressionMode: ["passthrough", "shadow", "deterministic"].includes(proxy.compressionMode)
97
105
  ? proxy.compressionMode : "deterministic",
106
+ elisionEnabled: proxy.elisionEnabled !== false,
107
+ elisionKeepRounds,
108
+ elisionCaptureLimit,
98
109
  },
99
110
  };
100
111
  }
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,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 { applyElision, elisionCandidates } from "./elision.js";
7
8
  import {
8
9
  ProjectionError,
9
10
  compressProjection,
@@ -265,7 +266,7 @@ class SseObserver {
265
266
  }
266
267
  }
267
268
 
268
- function spmHeaders({ requestId, memoryMode, memoryState, compressionMode, continuityState, original, forwarded, recalled }) {
269
+ function spmHeaders({ requestId, memoryMode, memoryState, compressionMode, continuityState, original, forwarded, recalled, elidedItems, elidedTokens }) {
269
270
  return {
270
271
  "x-spm-local-proxy": "v1",
271
272
  "x-spm-request-id": requestId,
@@ -276,6 +277,8 @@ function spmHeaders({ requestId, memoryMode, memoryState, compressionMode, conti
276
277
  "x-spm-original-input-tokens": String(original),
277
278
  "x-spm-forwarded-input-tokens": String(forwarded),
278
279
  "x-spm-recalled-tokens": String(recalled),
280
+ "x-spm-elided-items": String(elidedItems || 0),
281
+ "x-spm-elided-tokens": String(elidedTokens || 0),
279
282
  };
280
283
  }
281
284
 
@@ -312,8 +315,58 @@ async function relayModelRequest(request, response, config, providerRequest) {
312
315
  async function handleModelPost(request, response, config, memory, providerRequest, protocol, route) {
313
316
  authenticate(request, config);
314
317
  const body = await readRequestBody(request);
315
- const projection = projectRequest(protocol, body);
316
318
  const { memoryMode, compressionMode } = requestModes(request, config);
319
+ // Tool-output elision (0.1.2): stub old tool results whose identical
320
+ // content hosted SPM has already persisted and indexed (Gate C); capture
321
+ // the rest fire-and-forget so later turns can elide them. Elision runs
322
+ // before projection/recall/compression, mirroring the hosted gateway;
323
+ // every downstream path (including compression bypass) forwards the
324
+ // elided body. Best-effort: any failure leaves the body untouched.
325
+ let workingBody = body;
326
+ let elidedInfo = null;
327
+ if (config.proxy.elisionEnabled && memoryMode.includes("write")) {
328
+ try {
329
+ const scope = "local:" + protocol;
330
+ const [elidable, capturable] = elisionCandidates(protocol, body, {
331
+ scope,
332
+ keepRounds: config.proxy.elisionKeepRounds,
333
+ });
334
+ let ready = new Set();
335
+ if (elidable.length) {
336
+ try {
337
+ const report = await memory.status(elidable.map((entry) => entry.candidate.sourceId));
338
+ ready = new Set(report.readySourceIds);
339
+ } catch {
340
+ ready = new Set();
341
+ }
342
+ }
343
+ const elideNow = elidable.filter((entry) => ready.has(entry.candidate.sourceId));
344
+ const captureQueue = [
345
+ ...capturable,
346
+ ...elidable.filter((entry) => !ready.has(entry.candidate.sourceId)),
347
+ ].slice(0, config.proxy.elisionCaptureLimit);
348
+ for (const { candidate } of captureQueue) {
349
+ void captureText(
350
+ memory,
351
+ candidate.text,
352
+ candidate.sourceId,
353
+ "tool_output",
354
+ [["assistant", 0, [...candidate.text].length]],
355
+ );
356
+ }
357
+ if (elideNow.length) {
358
+ workingBody = applyElision(protocol, body, { elided: elideNow });
359
+ elidedInfo = {
360
+ items: elideNow.length,
361
+ tokens: elideNow.reduce((sum, entry) => sum + entry.candidate.tokens, 0),
362
+ };
363
+ }
364
+ } catch {
365
+ workingBody = body;
366
+ elidedInfo = null;
367
+ }
368
+ }
369
+ const projection = projectRequest(protocol, workingBody);
317
370
  const original = estimateTokens(body);
318
371
  let recalledContext = "";
319
372
  let recallOutcome = { text: "", status: "off", gateReason: "memory_read_disabled", evidenceRefs: [] };
@@ -355,7 +408,7 @@ async function handleModelPost(request, response, config, memory, providerReques
355
408
  && (!recalledContext || !recallPassed || !recallCoversRemoval);
356
409
  if (recallFailed || projectionBypass || deterministicBypass || unprovenRemoval) {
357
410
  effectiveCompression = "passthrough";
358
- forwardedBody = structuredClone(body);
411
+ forwardedBody = structuredClone(workingBody);
359
412
  continuityState = recallFailed ? "bypassed_recall_degraded"
360
413
  : projectionBypass ? "bypassed_provider_state"
361
414
  : deterministicBypass ? "bypassed_protected_context"
@@ -367,9 +420,10 @@ async function handleModelPost(request, response, config, memory, providerReques
367
420
  forwardedBody = patchedBody(projection, { untrustedContext: recalledContext });
368
421
  continuityState = "not_applicable";
369
422
  } else {
370
- forwardedBody = structuredClone(body);
423
+ forwardedBody = structuredClone(workingBody);
371
424
  continuityState = compressionMode === "shadow" ? "shadow_only" : "not_applicable";
372
425
  }
426
+ if (elidedInfo && continuityState !== "committed") continuityState = "elided_tool_output";
373
427
  let inputCaptureOk = true;
374
428
  if (memoryMode.includes("write")) inputCaptureOk = await captureInputs(memory, projection);
375
429
  const upstream = await providerRequest({
@@ -388,6 +442,8 @@ async function handleModelPost(request, response, config, memory, providerReques
388
442
  original,
389
443
  forwarded: estimateTokens(forwardedBody),
390
444
  recalled: estimateTokens(recalledContext),
445
+ elidedItems: elidedInfo ? elidedInfo.items : 0,
446
+ elidedTokens: elidedInfo ? elidedInfo.tokens : 0,
391
447
  };
392
448
  if (body.stream === true) {
393
449
  const observer = new SseObserver(protocol);
package/src/memory.js CHANGED
@@ -91,6 +91,67 @@ export class HostedMemoryClient {
91
91
  if (!response.ok) throw new Error(`SPM ingest returned HTTP ${response.status}`);
92
92
  }
93
93
  }
94
+
95
+ async mcpCall(toolName, args) {
96
+ const headers = {
97
+ authorization: "Bearer " + this.apiKey,
98
+ "content-type": "application/json",
99
+ accept: "application/json, text/event-stream",
100
+ };
101
+ const init = await this.fetchImpl(this.baseUrl + "/mcp", {
102
+ method: "POST",
103
+ redirect: "error",
104
+ signal: AbortSignal.timeout(this.timeoutMs),
105
+ headers,
106
+ body: JSON.stringify({
107
+ jsonrpc: "2.0",
108
+ id: 1,
109
+ method: "initialize",
110
+ params: {
111
+ protocolVersion: "2025-03-26",
112
+ capabilities: {},
113
+ clientInfo: { name: "spm-local-proxy", version: "0" },
114
+ },
115
+ }),
116
+ });
117
+ if (!init.ok) throw new Error("SPM MCP initialize returned HTTP " + init.status);
118
+ const response = await this.fetchImpl(this.baseUrl + "/mcp", {
119
+ method: "POST",
120
+ redirect: "error",
121
+ signal: AbortSignal.timeout(this.timeoutMs),
122
+ headers,
123
+ body: JSON.stringify({
124
+ jsonrpc: "2.0",
125
+ id: 2,
126
+ method: "tools/call",
127
+ params: { name: toolName, arguments: args },
128
+ }),
129
+ });
130
+ if (!response.ok) throw new Error("SPM MCP tools/call returned HTTP " + response.status);
131
+ const raw = await response.text();
132
+ for (const line of raw.split(String.fromCharCode(10))) {
133
+ if (line.startsWith("data:")) return JSON.parse(line.slice(5).trim());
134
+ }
135
+ return JSON.parse(raw);
136
+ }
137
+
138
+ // Readiness check (Gate C): which candidate source ids are persisted and
139
+ // extraction-ready. Elision must only stub outputs the memory plane can
140
+ // actually serve back.
141
+ async status(sourceIds) {
142
+ const result = await this.mcpCall("status", { source_ids: sourceIds });
143
+ let payload = result && result.result && result.result.structuredContent;
144
+ if (!payload) {
145
+ const content = result && result.result && result.result.content;
146
+ const text = content && content[0] && content[0].text;
147
+ payload = {};
148
+ if (typeof text === "string") {
149
+ try { payload = JSON.parse(text); } catch { payload = {}; }
150
+ }
151
+ }
152
+ const ready = Array.isArray(payload.ready_source_ids) ? payload.ready_source_ids : [];
153
+ return { readySourceIds: ready.map(String) };
154
+ }
94
155
  }
95
156
 
96
157
  export function memorySourceId(scope, kind, text) {