@spmos/local-proxy 0.1.0 → 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
@@ -95,3 +95,53 @@ service and remove the provider/SPM keys from the downstream harness process.
95
95
 
96
96
  SPM still receives recall queries and memory content. This package keeps the
97
97
  provider credential local; it is not an offline or zero-disclosure memory mode.
98
+
99
+ ## Continuity and capture hygiene in 0.1.1
100
+
101
+ Version `0.1.1` adds a stricter continuity contract:
102
+
103
+ - keep the two most recent eligible complete exchanges;
104
+ - remove older history only when recall returns `status=recalled`,
105
+ `gate_reason=passed`, and evidence from the exact removal set;
106
+ - preserve the full request on empty, degraded, unrelated, protected-context,
107
+ or provider-managed recall paths;
108
+ - emit `x-spm-continuity-state` with the commit or safe-bypass reason;
109
+ - transport `source_kind` and `role_spans` to hosted ingest while retaining a
110
+ stable identity for exact repeated content.
111
+
112
+ The same release narrows streamed assistant capture to visible Chat content,
113
+ Responses `output_text`, and Anthropic `text_delta`. Reasoning/thinking, tool
114
+ arguments, signatures, and partial JSON are not sent to memory. These changes
115
+ are covered by the repository's 32-test Local Proxy suite. The continuity gate
116
+ also recognizes deterministic input identities created by `0.1.0`, so an
117
+ upgrade does not require old content to be re-ingested before it can prove
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.0",
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
@@ -3,7 +3,8 @@ import { once } from "node:events";
3
3
  import { createServer } from "node:http";
4
4
  import { zstdDecompressSync } from "node:zlib";
5
5
 
6
- import { HostedMemoryClient, memorySourceId } from "./memory.js";
6
+ import { HostedMemoryClient, memorySourceId, memorySourceIds } from "./memory.js";
7
+ import { applyElision, elisionCandidates } from "./elision.js";
7
8
  import {
8
9
  ProjectionError,
9
10
  compressProjection,
@@ -132,9 +133,9 @@ async function writeChunk(response, chunk) {
132
133
  if (!response.write(chunk)) await once(response, "drain");
133
134
  }
134
135
 
135
- async function captureText(memory, text, sourceId) {
136
+ async function captureText(memory, text, sourceId, sourceKind = "", roleSpans = []) {
136
137
  try {
137
- await memory.ingest({ text, sourceId });
138
+ await memory.ingest({ text, sourceId, sourceKind, roleSpans });
138
139
  return true;
139
140
  } catch {
140
141
  return false;
@@ -145,12 +146,39 @@ async function captureInputs(memory, projection) {
145
146
  let ok = true;
146
147
  for (const unit of projection.units) {
147
148
  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;
149
+ const id = inputSourceId(projection, unit);
150
+ ok = await captureText(memory, unit.text, id, "input", unit.roleSpans) && ok;
150
151
  }
151
152
  return ok;
152
153
  }
153
154
 
155
+ function normalizeRecallOutcome(value) {
156
+ if (typeof value === "string") {
157
+ return { text: value, status: "legacy", gateReason: "legacy_unstructured", evidenceRefs: [] };
158
+ }
159
+ if (!value || typeof value !== "object" || typeof value.text !== "string") {
160
+ throw new Error("SPM recall returned an unsupported value");
161
+ }
162
+ return {
163
+ text: value.text,
164
+ status: String(value.status || "empty"),
165
+ gateReason: String(value.gateReason || "unknown"),
166
+ evidenceRefs: Array.isArray(value.evidenceRefs) ? value.evidenceRefs : [],
167
+ };
168
+ }
169
+
170
+ function inputSourceId(projection, unit) {
171
+ return memorySourceId(
172
+ `local:${projection.protocol}`,
173
+ "input",
174
+ JSON.stringify({ roles: unit.sourceRoles, text: unit.text }),
175
+ );
176
+ }
177
+
178
+ function legacyInputSourceId(projection, unit) {
179
+ return memorySourceId(`local:${projection.protocol}`, "input", unit.text);
180
+ }
181
+
154
182
  function assistantOutput(protocol, bytes) {
155
183
  let payload;
156
184
  try {
@@ -162,17 +190,23 @@ function assistantOutput(protocol, bytes) {
162
190
  return Array.isArray(payload.choices) ? payload.choices.flatMap((choice) => {
163
191
  const content = choice?.message?.content;
164
192
  if (typeof content === "string") return [content];
165
- if (Array.isArray(content)) return content.filter((block) => typeof block?.text === "string").map((block) => block.text);
193
+ if (Array.isArray(content)) return content
194
+ .filter((block) => block?.type === "text" && typeof block.text === "string")
195
+ .map((block) => block.text);
166
196
  return [];
167
197
  }).join("\n") : "";
168
198
  }
169
199
  if (protocol === "responses") {
170
200
  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") : "";
201
+ return Array.isArray(payload.output) ? payload.output
202
+ .filter((item) => item?.type === "message" && [undefined, "assistant"].includes(item.role))
203
+ .flatMap((item) => Array.isArray(item.content) ? item.content
204
+ .filter((block) => block?.type === "output_text" && typeof block.text === "string")
205
+ .map((block) => block.text) : []).join("\n") : "";
173
206
  }
174
207
  return Array.isArray(payload.content)
175
- ? payload.content.filter((block) => typeof block?.text === "string").map((block) => block.text).join("\n") : "";
208
+ ? payload.content.filter((block) => block?.type === "text" && typeof block.text === "string")
209
+ .map((block) => block.text).join("\n") : "";
176
210
  }
177
211
 
178
212
  class SseObserver {
@@ -217,35 +251,34 @@ class SseObserver {
217
251
  if (this.protocol === "chat") {
218
252
  for (const choice of Array.isArray(event.choices) ? event.choices : []) {
219
253
  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
254
  }
224
255
  return;
225
256
  }
226
257
  if (this.protocol === "responses") {
227
- if (String(event.type || "").endsWith(".delta")) this.append(event.delta);
258
+ if (event.type === "response.output_text.delta") this.append(event.delta);
228
259
  if (event.type === "response.completed") this.success = true;
229
260
  return;
230
261
  }
231
- if (event.type === "content_block_delta") {
262
+ if (event.type === "content_block_delta" && event.delta?.type === "text_delta") {
232
263
  this.append(event.delta?.text);
233
- this.append(event.delta?.partial_json);
234
264
  }
235
265
  if (event.type === "message_stop") this.success = true;
236
266
  }
237
267
  }
238
268
 
239
- function spmHeaders({ requestId, memoryMode, memoryState, compressionMode, original, forwarded, recalled }) {
269
+ function spmHeaders({ requestId, memoryMode, memoryState, compressionMode, continuityState, original, forwarded, recalled, elidedItems, elidedTokens }) {
240
270
  return {
241
271
  "x-spm-local-proxy": "v1",
242
272
  "x-spm-request-id": requestId,
243
273
  "x-spm-memory-mode": memoryMode,
244
274
  "x-spm-memory-state": memoryState,
245
275
  "x-spm-compression-mode": compressionMode,
276
+ "x-spm-continuity-state": continuityState,
246
277
  "x-spm-original-input-tokens": String(original),
247
278
  "x-spm-forwarded-input-tokens": String(forwarded),
248
279
  "x-spm-recalled-tokens": String(recalled),
280
+ "x-spm-elided-items": String(elidedItems || 0),
281
+ "x-spm-elided-tokens": String(elidedTokens || 0),
249
282
  };
250
283
  }
251
284
 
@@ -282,18 +315,72 @@ async function relayModelRequest(request, response, config, providerRequest) {
282
315
  async function handleModelPost(request, response, config, memory, providerRequest, protocol, route) {
283
316
  authenticate(request, config);
284
317
  const body = await readRequestBody(request);
285
- const projection = projectRequest(protocol, body);
286
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);
287
370
  const original = estimateTokens(body);
288
371
  let recalledContext = "";
372
+ let recallOutcome = { text: "", status: "off", gateReason: "memory_read_disabled", evidenceRefs: [] };
289
373
  let recallFailed = false;
290
374
  const projectionBypass = projection.decision === "bypass";
291
375
  if (!projectionBypass && memoryMode.includes("read") && projection.newestUserText) {
292
376
  try {
293
- recalledContext = truncateTokens(await memory.recall({
377
+ recallOutcome = normalizeRecallOutcome(await memory.recall({
294
378
  query: projection.newestUserText,
295
379
  contextTokens: original,
296
- }), config.proxy.maxRecalledTokens);
380
+ }));
381
+ recalledContext = recallOutcome.status === "recalled" && recallOutcome.gateReason === "passed"
382
+ ? truncateTokens(recallOutcome.text, config.proxy.maxRecalledTokens)
383
+ : "";
297
384
  } catch {
298
385
  recallFailed = true;
299
386
  }
@@ -301,20 +388,42 @@ async function handleModelPost(request, response, config, memory, providerReques
301
388
  const compression = compressProjection(projection, {
302
389
  inputBudget: config.proxy.inputBudgetTokens,
303
390
  recalledContext,
391
+ keepRecentEligible: 2,
304
392
  });
305
393
  const deterministicBypass = compressionMode === "deterministic" && compression.mode === "bypass";
306
394
  let effectiveCompression = compressionMode;
395
+ let continuityState = "not_applicable";
307
396
  let forwardedBody;
308
- if (recallFailed || projectionBypass || deterministicBypass) {
397
+ const removedSourceIds = new Set(compression.removedUnitIndexes.flatMap((index) => {
398
+ const unit = projection.units[index];
399
+ return [inputSourceId(projection, unit), legacyInputSourceId(projection, unit)]
400
+ .flatMap((sourceId) => memorySourceIds(sourceId, unit.text));
401
+ }));
402
+ const recallCoversRemoval = recallOutcome.evidenceRefs
403
+ .some((item) => removedSourceIds.has(item.sourceId));
404
+ const recallPassed = recallOutcome.status === "recalled"
405
+ && recallOutcome.gateReason === "passed";
406
+ const unprovenRemoval = compressionMode === "deterministic"
407
+ && compression.removedUnitCount > 0
408
+ && (!recalledContext || !recallPassed || !recallCoversRemoval);
409
+ if (recallFailed || projectionBypass || deterministicBypass || unprovenRemoval) {
309
410
  effectiveCompression = "passthrough";
310
- forwardedBody = structuredClone(body);
411
+ forwardedBody = structuredClone(workingBody);
412
+ continuityState = recallFailed ? "bypassed_recall_degraded"
413
+ : projectionBypass ? "bypassed_provider_state"
414
+ : deterministicBypass ? "bypassed_protected_context"
415
+ : !recalledContext ? "bypassed_empty_recall" : "bypassed_unproven_recall";
311
416
  } else if (compressionMode === "deterministic") {
312
417
  forwardedBody = compression.body;
418
+ continuityState = compression.removedUnitCount ? "committed" : "not_needed";
313
419
  } else if (compressionMode === "passthrough" && recalledContext) {
314
420
  forwardedBody = patchedBody(projection, { untrustedContext: recalledContext });
421
+ continuityState = "not_applicable";
315
422
  } else {
316
- forwardedBody = structuredClone(body);
423
+ forwardedBody = structuredClone(workingBody);
424
+ continuityState = compressionMode === "shadow" ? "shadow_only" : "not_applicable";
317
425
  }
426
+ if (elidedInfo && continuityState !== "committed") continuityState = "elided_tool_output";
318
427
  let inputCaptureOk = true;
319
428
  if (memoryMode.includes("write")) inputCaptureOk = await captureInputs(memory, projection);
320
429
  const upstream = await providerRequest({
@@ -329,9 +438,12 @@ async function handleModelPost(request, response, config, memory, providerReques
329
438
  requestId,
330
439
  memoryMode,
331
440
  compressionMode: effectiveCompression,
441
+ continuityState,
332
442
  original,
333
443
  forwarded: estimateTokens(forwardedBody),
334
444
  recalled: estimateTokens(recalledContext),
445
+ elidedItems: elidedInfo ? elidedInfo.items : 0,
446
+ elidedTokens: elidedInfo ? elidedInfo.tokens : 0,
335
447
  };
336
448
  if (body.stream === true) {
337
449
  const observer = new SseObserver(protocol);
@@ -349,7 +461,13 @@ async function handleModelPost(request, response, config, memory, providerReques
349
461
  upstream.close?.();
350
462
  if (memoryMode.includes("write") && observer.success && observer.parts.length) {
351
463
  const text = observer.parts.join("");
352
- await captureText(memory, text, memorySourceId("local", "assistant", text));
464
+ await captureText(
465
+ memory,
466
+ text,
467
+ memorySourceId("local", "assistant", text),
468
+ "assistant",
469
+ [["assistant", 0, [...text].length]],
470
+ );
353
471
  }
354
472
  }
355
473
  return;
@@ -364,7 +482,13 @@ async function handleModelPost(request, response, config, memory, providerReques
364
482
  let outputCaptureOk = true;
365
483
  if (memoryMode.includes("write") && upstream.statusCode >= 200 && upstream.statusCode < 300) {
366
484
  const text = assistantOutput(protocol, bytes);
367
- if (text) outputCaptureOk = await captureText(memory, text, memorySourceId("local", "assistant", text));
485
+ if (text) outputCaptureOk = await captureText(
486
+ memory,
487
+ text,
488
+ memorySourceId("local", "assistant", text),
489
+ "assistant",
490
+ [["assistant", 0, [...text].length]],
491
+ );
368
492
  }
369
493
  const state = recallFailed || !inputCaptureOk || !outputCaptureOk ? "degraded"
370
494
  : memoryMode.includes("write") ? "captured"
package/src/memory.js CHANGED
@@ -1,5 +1,13 @@
1
1
  import { createHash } from "node:crypto";
2
2
 
3
+ const MEMORY_CHUNK_CODE_POINTS = 12_000;
4
+
5
+ export function memorySourceIds(sourceId, text) {
6
+ const chunkCount = Math.max(1, Math.ceil([...text].length / MEMORY_CHUNK_CODE_POINTS));
7
+ if (chunkCount === 1) return [sourceId];
8
+ return Array.from({ length: chunkCount }, (_, index) => `${sourceId}:${index}`);
9
+ }
10
+
3
11
  export class HostedMemoryClient {
4
12
  constructor({ baseUrl, apiKey, fetchImpl = globalThis.fetch, timeoutMs = 30_000 }) {
5
13
  this.baseUrl = baseUrl.replace(/\/$/, "");
@@ -29,24 +37,121 @@ export class HostedMemoryClient {
29
37
  top_k: 6,
30
38
  context_tokens: Math.max(1, Math.min(contextTokens, 1_000_000)),
31
39
  });
32
- if (response.status === 424) return "";
40
+ if (response.status === 424) {
41
+ return { text: "", status: "empty", gateReason: "upstream_dependency", evidenceRefs: [] };
42
+ }
33
43
  if (!response.ok) throw new Error(`SPM recall returned HTTP ${response.status}`);
34
44
  const payload = await response.json();
35
45
  if (payload?.gate_reason !== "passed" || !Number.isInteger(payload.evidence_count)
36
- || payload.evidence_count < 1) return "";
46
+ || payload.evidence_count < 1) {
47
+ return {
48
+ text: "",
49
+ status: String(payload?.status || "empty"),
50
+ gateReason: String(payload?.gate_reason || "no_candidate"),
51
+ evidenceRefs: [],
52
+ };
53
+ }
37
54
  if (typeof payload.answer !== "string") throw new Error("SPM recall returned an invalid response");
38
- return payload.answer;
55
+ const evidenceRefs = Array.isArray(payload.evidence_refs)
56
+ ? payload.evidence_refs.filter((item) => item && typeof item.source_id === "string")
57
+ .map((item) => ({ sourceId: item.source_id, readToken: typeof item.read_token === "string" ? item.read_token : "" }))
58
+ : [];
59
+ return {
60
+ text: payload.answer,
61
+ status: String(payload.status || "recalled"),
62
+ gateReason: String(payload.gate_reason || "passed"),
63
+ evidenceRefs,
64
+ };
39
65
  }
40
66
 
41
- async ingest({ text, sourceId }) {
67
+ async ingest({ text, sourceId, sourceKind = "", roleSpans = [] }) {
68
+ const characters = [...text];
42
69
  const chunks = [];
43
- for (let index = 0; index < text.length; index += 12_000) chunks.push(text.slice(index, index + 12_000));
70
+ for (let index = 0; index < characters.length; index += MEMORY_CHUNK_CODE_POINTS) {
71
+ chunks.push(characters.slice(index, index + MEMORY_CHUNK_CODE_POINTS).join(""));
72
+ }
73
+ const sourceIds = memorySourceIds(sourceId, text);
44
74
  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 });
75
+ const id = sourceIds[index];
76
+ const chunkStart = index * MEMORY_CHUNK_CODE_POINTS;
77
+ const chunkEnd = chunkStart + [...chunks[index]].length;
78
+ const chunkSpans = roleSpans.flatMap(([role, start, end]) => {
79
+ const overlapStart = Math.max(start, chunkStart);
80
+ const overlapEnd = Math.min(end, chunkEnd);
81
+ return overlapStart < overlapEnd
82
+ ? [[role, overlapStart - chunkStart, overlapEnd - chunkStart]]
83
+ : [];
84
+ });
85
+ const response = await this.request("/v2/ingest", {
86
+ text: chunks[index],
87
+ source_id: id,
88
+ source_kind: sourceKind,
89
+ role_spans: chunkSpans,
90
+ });
47
91
  if (!response.ok) throw new Error(`SPM ingest returned HTTP ${response.status}`);
48
92
  }
49
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
+ }
50
155
  }
51
156
 
52
157
  export function memorySourceId(scope, kind, text) {
package/src/projection.js CHANGED
@@ -9,6 +9,10 @@ function clone(value) {
9
9
  return structuredClone(value);
10
10
  }
11
11
 
12
+ function textLength(value) {
13
+ return [...value].length;
14
+ }
15
+
12
16
  function extractText(content) {
13
17
  if (typeof content === "string") return content;
14
18
  if (!Array.isArray(content)) return "";
@@ -62,8 +66,9 @@ function groupExchanges(items, {
62
66
  const text = captureTexts[index];
63
67
  if (!text) continue;
64
68
  if (kept) offset += 1;
65
- roleSpans.push([roles[index], offset, offset + text.length]);
66
- offset += text.length;
69
+ const length = textLength(text);
70
+ roleSpans.push([roles[index], offset, offset + length]);
71
+ offset += length;
67
72
  kept = true;
68
73
  }
69
74
  units.push({
@@ -131,7 +136,7 @@ export function projectRequest(protocol, body) {
131
136
  } else if (typeof body.input === "string") {
132
137
  units = [{
133
138
  itemIndexes: [0], sourceRoles: ["user"], text: body.input,
134
- eligible: true, captureEligible: true, roleSpans: [["user", 0, body.input.length]],
139
+ eligible: true, captureEligible: true, roleSpans: [["user", 0, textLength(body.input)]],
135
140
  }];
136
141
  } else {
137
142
  units = groupExchanges(body.input, {
@@ -205,17 +210,23 @@ export function estimateTokens(value) {
205
210
  return text ? Math.max(1, Math.ceil(Buffer.byteLength(text, "utf8") / 4)) : 0;
206
211
  }
207
212
 
208
- export function compressProjection(projection, { inputBudget, recalledContext = "" }) {
213
+ export function compressProjection(projection, {
214
+ inputBudget,
215
+ recalledContext = "",
216
+ keepRecentEligible = 0,
217
+ }) {
209
218
  const originalInputTokens = estimateTokens(projection.body);
210
219
  if (projection.decision === "bypass") {
211
220
  return {
212
221
  body: clone(projection.body), mode: "bypass", removedUnitCount: 0,
213
222
  originalInputTokens, forwardedInputTokens: originalInputTokens, recalledTokens: 0,
223
+ removedUnitIndexes: [],
214
224
  };
215
225
  }
216
226
  const removable = projection.units
217
227
  .map((unit, index) => unit.eligible ? index : null)
218
228
  .filter((index) => index !== null);
229
+ removable.splice(Math.max(0, removable.length - keepRecentEligible));
219
230
  const removed = [];
220
231
  let candidate = patchedBody(projection, { untrustedContext: recalledContext });
221
232
  for (const unitIndex of removable) {
@@ -227,6 +238,7 @@ export function compressProjection(projection, { inputBudget, recalledContext =
227
238
  return {
228
239
  body: clone(projection.body), mode: "bypass", removedUnitCount: 0,
229
240
  originalInputTokens, forwardedInputTokens: originalInputTokens, recalledTokens: 0,
241
+ removedUnitIndexes: [],
230
242
  };
231
243
  }
232
244
  return {
@@ -236,5 +248,6 @@ export function compressProjection(projection, { inputBudget, recalledContext =
236
248
  originalInputTokens,
237
249
  forwardedInputTokens: estimateTokens(candidate),
238
250
  recalledTokens: estimateTokens(recalledContext),
251
+ removedUnitIndexes: removed,
239
252
  };
240
253
  }