@spmos/local-proxy 0.1.0 → 0.1.1

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,24 @@ 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.
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.1",
4
4
  "description": "Loopback-only SPM memory and compression proxy with local provider credentials",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/gateway.js CHANGED
@@ -3,7 +3,7 @@ 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
7
  import {
8
8
  ProjectionError,
9
9
  compressProjection,
@@ -132,9 +132,9 @@ async function writeChunk(response, chunk) {
132
132
  if (!response.write(chunk)) await once(response, "drain");
133
133
  }
134
134
 
135
- async function captureText(memory, text, sourceId) {
135
+ async function captureText(memory, text, sourceId, sourceKind = "", roleSpans = []) {
136
136
  try {
137
- await memory.ingest({ text, sourceId });
137
+ await memory.ingest({ text, sourceId, sourceKind, roleSpans });
138
138
  return true;
139
139
  } catch {
140
140
  return false;
@@ -145,12 +145,39 @@ async function captureInputs(memory, projection) {
145
145
  let ok = true;
146
146
  for (const unit of projection.units) {
147
147
  if (!unit.captureEligible || !unit.text) continue;
148
- const id = memorySourceId(`local:${projection.protocol}`, "input", unit.text);
149
- ok = await captureText(memory, unit.text, id) && ok;
148
+ const id = inputSourceId(projection, unit);
149
+ ok = await captureText(memory, unit.text, id, "input", unit.roleSpans) && ok;
150
150
  }
151
151
  return ok;
152
152
  }
153
153
 
154
+ function normalizeRecallOutcome(value) {
155
+ if (typeof value === "string") {
156
+ return { text: value, status: "legacy", gateReason: "legacy_unstructured", evidenceRefs: [] };
157
+ }
158
+ if (!value || typeof value !== "object" || typeof value.text !== "string") {
159
+ throw new Error("SPM recall returned an unsupported value");
160
+ }
161
+ return {
162
+ text: value.text,
163
+ status: String(value.status || "empty"),
164
+ gateReason: String(value.gateReason || "unknown"),
165
+ evidenceRefs: Array.isArray(value.evidenceRefs) ? value.evidenceRefs : [],
166
+ };
167
+ }
168
+
169
+ function inputSourceId(projection, unit) {
170
+ return memorySourceId(
171
+ `local:${projection.protocol}`,
172
+ "input",
173
+ JSON.stringify({ roles: unit.sourceRoles, text: unit.text }),
174
+ );
175
+ }
176
+
177
+ function legacyInputSourceId(projection, unit) {
178
+ return memorySourceId(`local:${projection.protocol}`, "input", unit.text);
179
+ }
180
+
154
181
  function assistantOutput(protocol, bytes) {
155
182
  let payload;
156
183
  try {
@@ -162,17 +189,23 @@ function assistantOutput(protocol, bytes) {
162
189
  return Array.isArray(payload.choices) ? payload.choices.flatMap((choice) => {
163
190
  const content = choice?.message?.content;
164
191
  if (typeof content === "string") return [content];
165
- if (Array.isArray(content)) return content.filter((block) => typeof block?.text === "string").map((block) => block.text);
192
+ if (Array.isArray(content)) return content
193
+ .filter((block) => block?.type === "text" && typeof block.text === "string")
194
+ .map((block) => block.text);
166
195
  return [];
167
196
  }).join("\n") : "";
168
197
  }
169
198
  if (protocol === "responses") {
170
199
  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") : "";
200
+ return Array.isArray(payload.output) ? payload.output
201
+ .filter((item) => item?.type === "message" && [undefined, "assistant"].includes(item.role))
202
+ .flatMap((item) => Array.isArray(item.content) ? item.content
203
+ .filter((block) => block?.type === "output_text" && typeof block.text === "string")
204
+ .map((block) => block.text) : []).join("\n") : "";
173
205
  }
174
206
  return Array.isArray(payload.content)
175
- ? payload.content.filter((block) => typeof block?.text === "string").map((block) => block.text).join("\n") : "";
207
+ ? payload.content.filter((block) => block?.type === "text" && typeof block.text === "string")
208
+ .map((block) => block.text).join("\n") : "";
176
209
  }
177
210
 
178
211
  class SseObserver {
@@ -217,32 +250,29 @@ class SseObserver {
217
250
  if (this.protocol === "chat") {
218
251
  for (const choice of Array.isArray(event.choices) ? event.choices : []) {
219
252
  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
253
  }
224
254
  return;
225
255
  }
226
256
  if (this.protocol === "responses") {
227
- if (String(event.type || "").endsWith(".delta")) this.append(event.delta);
257
+ if (event.type === "response.output_text.delta") this.append(event.delta);
228
258
  if (event.type === "response.completed") this.success = true;
229
259
  return;
230
260
  }
231
- if (event.type === "content_block_delta") {
261
+ if (event.type === "content_block_delta" && event.delta?.type === "text_delta") {
232
262
  this.append(event.delta?.text);
233
- this.append(event.delta?.partial_json);
234
263
  }
235
264
  if (event.type === "message_stop") this.success = true;
236
265
  }
237
266
  }
238
267
 
239
- function spmHeaders({ requestId, memoryMode, memoryState, compressionMode, original, forwarded, recalled }) {
268
+ function spmHeaders({ requestId, memoryMode, memoryState, compressionMode, continuityState, original, forwarded, recalled }) {
240
269
  return {
241
270
  "x-spm-local-proxy": "v1",
242
271
  "x-spm-request-id": requestId,
243
272
  "x-spm-memory-mode": memoryMode,
244
273
  "x-spm-memory-state": memoryState,
245
274
  "x-spm-compression-mode": compressionMode,
275
+ "x-spm-continuity-state": continuityState,
246
276
  "x-spm-original-input-tokens": String(original),
247
277
  "x-spm-forwarded-input-tokens": String(forwarded),
248
278
  "x-spm-recalled-tokens": String(recalled),
@@ -286,14 +316,18 @@ async function handleModelPost(request, response, config, memory, providerReques
286
316
  const { memoryMode, compressionMode } = requestModes(request, config);
287
317
  const original = estimateTokens(body);
288
318
  let recalledContext = "";
319
+ let recallOutcome = { text: "", status: "off", gateReason: "memory_read_disabled", evidenceRefs: [] };
289
320
  let recallFailed = false;
290
321
  const projectionBypass = projection.decision === "bypass";
291
322
  if (!projectionBypass && memoryMode.includes("read") && projection.newestUserText) {
292
323
  try {
293
- recalledContext = truncateTokens(await memory.recall({
324
+ recallOutcome = normalizeRecallOutcome(await memory.recall({
294
325
  query: projection.newestUserText,
295
326
  contextTokens: original,
296
- }), config.proxy.maxRecalledTokens);
327
+ }));
328
+ recalledContext = recallOutcome.status === "recalled" && recallOutcome.gateReason === "passed"
329
+ ? truncateTokens(recallOutcome.text, config.proxy.maxRecalledTokens)
330
+ : "";
297
331
  } catch {
298
332
  recallFailed = true;
299
333
  }
@@ -301,19 +335,40 @@ async function handleModelPost(request, response, config, memory, providerReques
301
335
  const compression = compressProjection(projection, {
302
336
  inputBudget: config.proxy.inputBudgetTokens,
303
337
  recalledContext,
338
+ keepRecentEligible: 2,
304
339
  });
305
340
  const deterministicBypass = compressionMode === "deterministic" && compression.mode === "bypass";
306
341
  let effectiveCompression = compressionMode;
342
+ let continuityState = "not_applicable";
307
343
  let forwardedBody;
308
- if (recallFailed || projectionBypass || deterministicBypass) {
344
+ const removedSourceIds = new Set(compression.removedUnitIndexes.flatMap((index) => {
345
+ const unit = projection.units[index];
346
+ return [inputSourceId(projection, unit), legacyInputSourceId(projection, unit)]
347
+ .flatMap((sourceId) => memorySourceIds(sourceId, unit.text));
348
+ }));
349
+ const recallCoversRemoval = recallOutcome.evidenceRefs
350
+ .some((item) => removedSourceIds.has(item.sourceId));
351
+ const recallPassed = recallOutcome.status === "recalled"
352
+ && recallOutcome.gateReason === "passed";
353
+ const unprovenRemoval = compressionMode === "deterministic"
354
+ && compression.removedUnitCount > 0
355
+ && (!recalledContext || !recallPassed || !recallCoversRemoval);
356
+ if (recallFailed || projectionBypass || deterministicBypass || unprovenRemoval) {
309
357
  effectiveCompression = "passthrough";
310
358
  forwardedBody = structuredClone(body);
359
+ continuityState = recallFailed ? "bypassed_recall_degraded"
360
+ : projectionBypass ? "bypassed_provider_state"
361
+ : deterministicBypass ? "bypassed_protected_context"
362
+ : !recalledContext ? "bypassed_empty_recall" : "bypassed_unproven_recall";
311
363
  } else if (compressionMode === "deterministic") {
312
364
  forwardedBody = compression.body;
365
+ continuityState = compression.removedUnitCount ? "committed" : "not_needed";
313
366
  } else if (compressionMode === "passthrough" && recalledContext) {
314
367
  forwardedBody = patchedBody(projection, { untrustedContext: recalledContext });
368
+ continuityState = "not_applicable";
315
369
  } else {
316
370
  forwardedBody = structuredClone(body);
371
+ continuityState = compressionMode === "shadow" ? "shadow_only" : "not_applicable";
317
372
  }
318
373
  let inputCaptureOk = true;
319
374
  if (memoryMode.includes("write")) inputCaptureOk = await captureInputs(memory, projection);
@@ -329,6 +384,7 @@ async function handleModelPost(request, response, config, memory, providerReques
329
384
  requestId,
330
385
  memoryMode,
331
386
  compressionMode: effectiveCompression,
387
+ continuityState,
332
388
  original,
333
389
  forwarded: estimateTokens(forwardedBody),
334
390
  recalled: estimateTokens(recalledContext),
@@ -349,7 +405,13 @@ async function handleModelPost(request, response, config, memory, providerReques
349
405
  upstream.close?.();
350
406
  if (memoryMode.includes("write") && observer.success && observer.parts.length) {
351
407
  const text = observer.parts.join("");
352
- await captureText(memory, text, memorySourceId("local", "assistant", text));
408
+ await captureText(
409
+ memory,
410
+ text,
411
+ memorySourceId("local", "assistant", text),
412
+ "assistant",
413
+ [["assistant", 0, [...text].length]],
414
+ );
353
415
  }
354
416
  }
355
417
  return;
@@ -364,7 +426,13 @@ async function handleModelPost(request, response, config, memory, providerReques
364
426
  let outputCaptureOk = true;
365
427
  if (memoryMode.includes("write") && upstream.statusCode >= 200 && upstream.statusCode < 300) {
366
428
  const text = assistantOutput(protocol, bytes);
367
- if (text) outputCaptureOk = await captureText(memory, text, memorySourceId("local", "assistant", text));
429
+ if (text) outputCaptureOk = await captureText(
430
+ memory,
431
+ text,
432
+ memorySourceId("local", "assistant", text),
433
+ "assistant",
434
+ [["assistant", 0, [...text].length]],
435
+ );
368
436
  }
369
437
  const state = recallFailed || !inputCaptureOk || !outputCaptureOk ? "degraded"
370
438
  : 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,21 +37,57 @@ 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
  }
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
  }