@maximem/synap-js-sdk 0.4.7 → 0.4.8

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.
Files changed (43) hide show
  1. package/dist/{anticipation-cache-BMVF5sXb.d.cts → anticipation-cache-C1rUEpaW.d.cts} +22 -1
  2. package/dist/{anticipation-cache-BMVF5sXb.d.ts → anticipation-cache-C1rUEpaW.d.ts} +22 -1
  3. package/dist/anticipation-cache-LRE3TLK4.cjs +14 -0
  4. package/dist/anticipation-cache-LRE3TLK4.cjs.map +1 -0
  5. package/dist/anticipation-cache-WLU4NMD5.js +14 -0
  6. package/dist/chunk-2TVL5IPQ.cjs.map +1 -1
  7. package/dist/{chunk-3JSE64GW.cjs → chunk-7CWBRHUO.cjs} +15 -2
  8. package/dist/chunk-7CWBRHUO.cjs.map +1 -0
  9. package/dist/{chunk-6LDUDKHS.js → chunk-ODVOQOSO.js} +124 -8
  10. package/dist/chunk-ODVOQOSO.js.map +1 -0
  11. package/dist/{chunk-ZU6ZC4SU.js → chunk-T5QQBJ6T.js} +15 -2
  12. package/dist/chunk-T5QQBJ6T.js.map +1 -0
  13. package/dist/{chunk-RB57I2IQ.cjs → chunk-T6U5PVAD.cjs} +125 -9
  14. package/dist/chunk-T6U5PVAD.cjs.map +1 -0
  15. package/dist/chunk-ZKOJDUN4.cjs.map +1 -1
  16. package/dist/env-55ULHNJZ.cjs.map +1 -1
  17. package/dist/grpc/index.cjs +4 -4
  18. package/dist/grpc/index.cjs.map +1 -1
  19. package/dist/grpc/index.d.cts +3 -3
  20. package/dist/grpc/index.d.ts +3 -3
  21. package/dist/grpc/index.js +3 -3
  22. package/dist/index.cjs +27 -16
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +11 -4
  25. package/dist/index.d.ts +11 -4
  26. package/dist/index.js +25 -14
  27. package/dist/index.js.map +1 -1
  28. package/dist/stream-client-2C5KIOWP.js +7 -0
  29. package/dist/stream-client-GPU37E6F.cjs +7 -0
  30. package/dist/stream-client-GPU37E6F.cjs.map +1 -0
  31. package/package.json +6 -1
  32. package/dist/anticipation-cache-ARYEEKMU.cjs +0 -10
  33. package/dist/anticipation-cache-ARYEEKMU.cjs.map +0 -1
  34. package/dist/anticipation-cache-H7HEVWQC.js +0 -10
  35. package/dist/chunk-3JSE64GW.cjs.map +0 -1
  36. package/dist/chunk-6LDUDKHS.js.map +0 -1
  37. package/dist/chunk-RB57I2IQ.cjs.map +0 -1
  38. package/dist/chunk-ZU6ZC4SU.js.map +0 -1
  39. package/dist/stream-client-6V4FGKZ3.js +0 -7
  40. package/dist/stream-client-PRTOH62B.cjs +0 -7
  41. package/dist/stream-client-PRTOH62B.cjs.map +0 -1
  42. /package/dist/{anticipation-cache-H7HEVWQC.js.map → anticipation-cache-WLU4NMD5.js.map} +0 -0
  43. /package/dist/{stream-client-6V4FGKZ3.js.map → stream-client-2C5KIOWP.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/behavior/anticipation.json","../src/behavior/contract.ts","../src/cache/bm25.ts","../src/context/anticipation-cache.ts"],"sourcesContent":["{\n \"$comment\": \"SOURCE OF TRUTH for anticipation-cache behavior, shared by the Python and JS/TS SDKs. Do not duplicate these values into either SDK's source. See ../README.md. Regexes are restricted to the intersection of Python 're' and ECMAScript; both SDKs have a parity test.\",\n \"version\": 1,\n \"recall_bypass\": {\n \"note\": \"WS4 of the playground query-hygiene plan. A recall-shaped question never serves from the anticipation cache. Asymmetric cost is why: a stale false-hit makes the agent answer 'I don't see that' while the store holds the fact (the BZQR6J cross-session failure), whereas bypassing costs only cold-fetch latency on a turn where the user already expects a lookup. Stem coverage cannot gate this \\u2014 false hits were measured at coverage=1.00. Ties break toward INCLUDING a pattern.\",\n \"env_flag\": \"SYNAP_SDK_CACHE_RECALL_BYPASS\",\n \"default\": false,\n \"patterns\": [\n {\n \"pattern\": \"\\\\bremind me\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4, playground query-hygiene plan).\"\n },\n {\n \"pattern\": \"\\\\bon file\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\b(your|my|the) records\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bdo you (have|know|remember|recall|see)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhat (do|did) (i|you) (say|tell|mention|have)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhat('s| is) my\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhere (am i|do i live)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bhow long have i\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhich of my\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\bwhat .{0,40}\\\\b(again|earlier|last time|previously|yesterday)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4). 'again' alone is deliberately NOT a marker: 'book me a ride again' is a task query, not a recall query.\"\n },\n {\n \"pattern\": \"\\\\bwill you use to (contact|reach|notify)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"Original set (WS4).\"\n },\n {\n \"pattern\": \"\\\\b(confirm|verify|double.?check)\\\\b.{0,40}\\\\bmy\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11: 'can you confirm my email address?' served a stale bundle. Also catches 'confirm my booking' \\u2014 an intentional over-match, costing one cloud fetch.\"\n },\n {\n \"pattern\": \"\\\\b(linked to|associated with|registered (to|on|with)) my\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11: 'what name is linked to my Uber account?' served a stale bundle.\"\n },\n {\n \"pattern\": \"\\\\b(best|preferred) way to (reach|contact|update|notify) me\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11: 'best way to contact me with updates' served a stale bundle.\"\n },\n {\n \"pattern\": \"\\\\bhow (do|will|can|should) you (reach|contact|notify) me\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11, sibling phrasing of the above.\"\n },\n {\n \"pattern\": \"\\\\bwhich .{0,40}\\\\b(are|will) you (going to )?(use|using)\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11: 'which email are you going to use?' served a stale bundle.\"\n },\n {\n \"pattern\": \"\\\\bon (my|the) account\\\\b\",\n \"flags\": \"i\",\n \"note\": \"2026-07-16 eval register issue #11.\"\n }\n ]\n },\n \"thresholds\": {\n \"bm25\": {\n \"value\": 1.5,\n \"note\": \"Nominal threshold. The value actually applied is derived per query: max(effective_floor, min(bm25, query_token_scale * len(query_tokens))). Short queries cannot reach the nominal score, so holding them to it would miss every time.\"\n },\n \"novel_term\": {\n \"value\": 0.45,\n \"note\": \"Fraction of query stems absent from the cached corpus that forces a miss.\"\n },\n \"min_corpus_for_novel_gate\": {\n \"value\": 200,\n \"note\": \"The novel-term gate is meaningless on a small corpus, where the ratio is dominated by ordinary English word forms. Measured: a fresh playground conversation reaches ~60 stems after the first push and would trip the 0.45 gate on essentially every second-turn query. 200 means the gate engages once a customer has ~3-4 typical bundles cached.\"\n },\n \"effective_floor\": {\n \"value\": 0.6,\n \"note\": \"Lower bound on the derived per-query threshold. Below this, BM25 stops discriminating.\"\n },\n \"query_token_scale\": {\n \"value\": 0.3,\n \"note\": \"Scales the threshold down for short queries: 0.3 points of score per query token.\"\n }\n },\n \"bm25\": {\n \"k1\": 1.5,\n \"b\": 0.75,\n \"idf_floor\": 0.5,\n \"min_token_len\": 2,\n \"min_stem_len\": 4,\n \"suffixes\": [\n \"ences\",\n \"ances\",\n \"ation\",\n \"tion\",\n \"sion\",\n \"ence\",\n \"ance\",\n \"ness\",\n \"ment\",\n \"able\",\n \"ible\",\n \"ical\",\n \"ally\",\n \"ies\",\n \"ive\",\n \"ful\",\n \"ous\",\n \"ing\",\n \"ary\",\n \"ly\",\n \"ed\",\n \"es\",\n \"s\"\n ],\n \"stop_words\": [\n \"a\",\n \"about\",\n \"after\",\n \"an\",\n \"and\",\n \"are\",\n \"at\",\n \"be\",\n \"been\",\n \"before\",\n \"being\",\n \"but\",\n \"by\",\n \"can\",\n \"could\",\n \"did\",\n \"do\",\n \"does\",\n \"for\",\n \"from\",\n \"had\",\n \"has\",\n \"have\",\n \"how\",\n \"if\",\n \"in\",\n \"into\",\n \"is\",\n \"it\",\n \"its\",\n \"may\",\n \"might\",\n \"no\",\n \"nor\",\n \"not\",\n \"of\",\n \"on\",\n \"or\",\n \"over\",\n \"should\",\n \"so\",\n \"than\",\n \"that\",\n \"the\",\n \"then\",\n \"these\",\n \"this\",\n \"those\",\n \"to\",\n \"was\",\n \"were\",\n \"what\",\n \"when\",\n \"where\",\n \"which\",\n \"who\",\n \"whom\",\n \"why\",\n \"will\",\n \"with\",\n \"would\"\n ],\n \"alias_token\": {\n \"pattern\": \"\\\\[\\\\[([A-Za-z][A-Za-z0-9_]*_[a-z0-9]{12})\\\\]\\\\]\",\n \"note\": \"An alias label as it appears in text: [[PERSON_PHONE_h2n7v5cx8m0d]]. Kept whole rather than split, because 'person' and 'phone' are boilerplate shared by every label of that field type and would make two different people's memories score alike. Mirrors synap/cloud/shared/tokenizer.py \\u2014 keep the two in step.\"\n },\n \"suffix_note\": \"Order matters: longest-first, because _stem returns on first match. Reordering this list silently changes every stem and therefore every BM25 score.\"\n },\n \"env_flags\": {\n \"$comment\": \"Read at CALL time, never at module load. Python does os.environ.get inside the function bodies; JS must do the same or late process.env mutation stops working and the flag looks broken. See gotcha G-S.\",\n \"SYNAP_SDK_CACHE_RECALL_BYPASS\": {\n \"default\": false,\n \"truthy\": [\n \"true\",\n \"1\",\n \"yes\"\n ]\n },\n \"SYNAP_SDK_CACHE_HONOR_TTL_HINT\": {\n \"default\": false,\n \"truthy\": [\n \"true\",\n \"1\",\n \"yes\"\n ],\n \"note\": \"A bundle's server ttl_hint_seconds may only SHORTEN the global TTL, never extend it.\"\n },\n \"SYNAP_SDK_CACHE_INVALIDATE_ON_WRITE\": {\n \"default\": false,\n \"truthy\": [\n \"true\",\n \"1\",\n \"yes\"\n ],\n \"note\": \"2026-07-16 eval register issue #8: the cloud invalidates its own Redis caches on ingest, but that stops at the process boundary.\"\n },\n \"SYNAP_SDK_CACHE_MAX_ENTRY_AGE\": {\n \"default\": null,\n \"note\": \"2026-07-16 eval register issue #6: stored_at is a sliding lease renewed on hit, so under steady traffic a pre-update snapshot never expired. Defaults to 2x the sliding TTL; 0 disables.\"\n },\n \"SYNAP_SDK_CACHE_COVERAGE_MIN\": {\n \"default\": null\n }\n },\n \"coverage_gate\": {\n \"note\": \"Fraction of the query's stems present in the picked items. A bundle can clear the BM25 threshold on one shared token ('account') while lacking the asked-for fact entirely: the false HIT behind the eval's 'forgot the name' failure. ALWAYS computed and reported; ENFORCED only when SYNAP_SDK_CACHE_COVERAGE_MIN is explicitly set, so default behavior is unchanged. When it does fire it must gate BEFORE any side effect, so a rejected lookup leaves cache state untouched.\",\n \"env_flag\": \"SYNAP_SDK_CACHE_COVERAGE_MIN\",\n \"default\": null,\n \"empty_query_coverage\": 1.0\n },\n \"telemetry\": {\n \"rejected_items_cap\": {\n \"value\": 20,\n \"note\": \"Rejected items reported per lookup, highest score first, so a large cache cannot bloat the payload.\"\n },\n \"content_preview_chars\": 120\n },\n \"rung_key\": {\n \"$comment\": \"SOURCE OF TRUTH for how a scope rung is written on the wire and compared in both SDK anticipation caches. The server stamps a pushed bundle with this string (ContextBundleProto.anticipation_scope_rung) and each SDK builds the same string from the `scope` path its own fetch names; a bundle is servable only when the two agree. Three implementations exist by necessity (server Python, SDK Python, SDK TypeScript) because the producer is not an SDK, so the vectors below are what stops them drifting.\",\n \"note\": \"Node ids are deliberately not what travels. They are registry surrogates and an SDK in a customer's process has never seen one; a caller names a rung with level keys and its own external ids, so that is the vocabulary the comparison happens in. Level keys are ^[a-z][a-z0-9_]{0,63}$ so they can hold neither separator and only the value needs escaping.\",\n \"separator\": \"|\",\n \"assign\": \"=\",\n \"sort\": \"by level key, ascending, plain codepoint order\",\n \"escapes\": {\n \"\\\\\": \"\\\\\\\\\",\n \"|\": \"\\\\p\",\n \"=\": \"\\\\e\"\n },\n \"escape_order\": \"backslash first. Reversing it makes `a|b` and `a\\\\pb` encode to the same string, which is a false match between two different rungs.\",\n \"absent\": \"null (an empty proto string on the wire) means the bundle or the request named no rung. Serving requires the two to be EQUAL, so absent matches only absent. That leaves every client without nested scoping byte-identical to today and refuses every genuinely cross-rung serve; the cost of the rule being wrong is a cold fetch, and the cost of a subset rule being wrong is one person's context handed to another.\",\n \"vectors\": [\n {\n \"path\": {},\n \"key\": null,\n \"note\": \"no path named\"\n },\n {\n \"path\": {\n \"customer\": \"acme\"\n },\n \"key\": \"customer=acme\"\n },\n {\n \"path\": {\n \"customer\": \"acme\",\n \"team\": \"payments\",\n \"user\": \"dana\"\n },\n \"key\": \"customer=acme|team=payments|user=dana\"\n },\n {\n \"path\": {\n \"user\": \"dana\",\n \"team\": \"payments\",\n \"customer\": \"acme\"\n },\n \"key\": \"customer=acme|team=payments|user=dana\",\n \"note\": \"insertion order must not change the key; a dict has whatever order the caller wrote and ladder order is not available here\"\n },\n {\n \"path\": {\n \"customer\": \"a|b\"\n },\n \"key\": \"customer=a\\\\pb\"\n },\n {\n \"path\": {\n \"customer\": \"a=b\"\n },\n \"key\": \"customer=a\\\\eb\"\n },\n {\n \"path\": {\n \"customer\": \"a\\\\b\"\n },\n \"key\": \"customer=a\\\\\\\\b\"\n },\n {\n \"path\": {\n \"customer\": \"a\\\\pb\"\n },\n \"key\": \"customer=a\\\\\\\\pb\",\n \"note\": \"the escape-order case: this must NOT collide with a|b above\"\n },\n {\n \"path\": {\n \"customer\": \"ab\"\n },\n \"key\": \"customer=ab\"\n },\n {\n \"path\": {\n \"customer\": \"a\",\n \"b\": \"c\"\n },\n \"key\": \"b=c|customer=a\",\n \"note\": \"sorted by key, so `customer=ab` and this cannot collapse\"\n }\n ]\n }\n}\n","/**\n * Loader for the shared SDK behavior contract.\n *\n * The values here are tuned against measured eval failures and are shared,\n * byte-identical, with the Python SDK. They live in data rather than code\n * specifically so the two SDKs cannot drift. See\n * `synap/sdk/CONTRACT/README.md`.\n *\n * `anticipation.json` is vendored into `src/` by\n * `synap/sdk/scripts/sync-behavior.sh` and imported (not read from disk) so\n * that the bundler inlines it. Reading it with `node:fs` at runtime would work\n * in Node and break in every bundled target: Edge, Workers, and anything under\n * webpack/turbopack, where `dist/` is rewritten and relative paths do not\n * survive. It is the same failure mode as `@grpc/proto-loader` reading a\n * `.proto` off disk (gotcha G-P).\n */\n\nimport contractJson from './anticipation.json' with { type: 'json' };\n\nexport interface RecallPattern {\n pattern: string;\n flags: string;\n note: string;\n}\n\nexport interface BehaviorContract {\n version: number;\n recall_bypass: {\n note: string;\n env_flag: string;\n default: boolean;\n patterns: RecallPattern[];\n };\n thresholds: {\n bm25: { value: number; note: string };\n novel_term: { value: number; note: string };\n min_corpus_for_novel_gate: { value: number; note: string };\n effective_floor: { value: number; note: string };\n query_token_scale: { value: number; note: string };\n };\n coverage_gate: {\n note: string;\n env_flag: string;\n default: number | null;\n empty_query_coverage: number;\n };\n telemetry: {\n rejected_items_cap: { value: number; note: string };\n content_preview_chars: number;\n };\n bm25: {\n k1: number;\n b: number;\n idf_floor: number;\n min_token_len: number;\n min_stem_len: number;\n suffixes: string[];\n stop_words: string[];\n alias_token: { pattern: string; note: string };\n };\n}\n\nexport const CONTRACT = contractJson as unknown as BehaviorContract;\n\n/** ECMAScript flags we accept. Anything else is invalid in Python too. */\nconst ALLOWED_FLAGS = new Set(['i', 'm', 's']);\n\nfunction compile(pattern: string, flags: string): RegExp {\n for (const ch of flags) {\n if (!ALLOWED_FLAGS.has(ch)) {\n throw new Error(\n `Unsupported regex flag '${ch}' in behavior contract. Flags must be ` +\n `valid in both Python and ECMAScript.`,\n );\n }\n }\n return new RegExp(pattern, flags);\n}\n\n/**\n * Compiled recall-bypass patterns, in contract order.\n *\n * Deliberately NOT using the `g` flag: a global RegExp carries `lastIndex`\n * between calls, so a shared instance would match on one query and then miss\n * on the next. That failure is intermittent and traffic-dependent, which is\n * the worst kind to debug.\n */\nexport const RECALL_PATTERNS: readonly RegExp[] = CONTRACT.recall_bypass.patterns.map((p) =>\n compile(p.pattern, p.flags ?? ''),\n);\n\nexport const THRESHOLDS = {\n bm25: CONTRACT.thresholds.bm25.value,\n novelTerm: CONTRACT.thresholds.novel_term.value,\n minCorpusForNovelGate: CONTRACT.thresholds.min_corpus_for_novel_gate.value,\n /** Lower bound on the derived per-query threshold. */\n effectiveFloor: CONTRACT.thresholds.effective_floor.value,\n /** Points of score allowed per query token when deriving the threshold. */\n queryTokenScale: CONTRACT.thresholds.query_token_scale.value,\n} as const;\n\nexport const BM25_PARAMS = CONTRACT.bm25;\nexport const STOP_WORDS: ReadonlySet<string> = new Set(CONTRACT.bm25.stop_words);\n// Order is load-bearing: stem() returns on first match, so this must stay\n// longest-first exactly as the contract lists it.\nexport const SUFFIXES: readonly string[] = CONTRACT.bm25.suffixes;\nexport const ALIAS_TOKEN_SOURCE = CONTRACT.bm25.alias_token.pattern;\n\n/** True when any query string looks like an explicit memory-recall ask. */\nexport function isRecallQuery(searchQuery: readonly (string | null | undefined)[] | null | undefined): boolean {\n for (const q of searchQuery ?? []) {\n if (!q) continue;\n for (const pattern of RECALL_PATTERNS) {\n if (pattern.test(q)) return true;\n }\n }\n return false;\n}\n","/**\n * BM25 scorer for the anticipation cache.\n *\n * A faithful port of `maximem_synap/cache/bm25.py`. Every tuned value comes\n * from the shared behavior contract, so the two implementations cannot drift\n * on parameters. What they *can* still drift on is arithmetic, which is what\n * the shared conformance corpus is for.\n */\n\nimport { BM25_PARAMS, STOP_WORDS, SUFFIXES, ALIAS_TOKEN_SOURCE } from '../behavior/contract.js';\n\nconst MIN_STEM_LEN = BM25_PARAMS.min_stem_len;\nconst MIN_TOKEN_LEN = BM25_PARAMS.min_token_len;\n\nexport function stem(word: string): string {\n // Order is load-bearing: longest suffix first, return on first match.\n for (const suffix of SUFFIXES) {\n if (word.endsWith(suffix) && word.length - suffix.length >= MIN_STEM_LEN) {\n return word.slice(0, word.length - suffix.length);\n }\n }\n return word;\n}\n\n/**\n * An alias label, as it appears in text: `[[PERSON_PHONE_h2n7v5cx8m0d]]`.\n *\n * Kept whole rather than split into `person`, `phone` and the suffix, because\n * the first two are boilerplate shared by every label of that field type and\n * would make two different people's memories score alike.\n *\n * Mirrors `synap/cloud/shared/tokenizer.py`. Keep the two in step.\n */\nfunction aliasTokenRe(): RegExp {\n // Constructed per call because `g` regexes carry `lastIndex`, and this one\n // is used with replace(). A module-level shared instance would produce\n // different results on alternating calls.\n return new RegExp(ALIAS_TOKEN_SOURCE, 'g');\n}\n\nconst WORD_RE = /[a-z0-9]+/g;\n\n/** Tokenize, lowercase, remove stop words, and stem. Alias labels survive whole. */\nexport function tokenize(text: string | null | undefined): string[] {\n if (!text) return [];\n\n const labels: string[] = [];\n const remainder = text.replace(aliasTokenRe(), (_match, captured: string) => {\n labels.push(captured.toLowerCase());\n return ' ';\n });\n\n const words = remainder.toLowerCase().match(WORD_RE) ?? [];\n const out = labels.slice();\n for (const w of words) {\n if (w.length >= MIN_TOKEN_LEN && !STOP_WORDS.has(w)) out.push(stem(w));\n }\n return out;\n}\n\n/** Okapi BM25 scorer over a small in-memory corpus. */\nexport class BM25 {\n static readonly IDF_FLOOR = BM25_PARAMS.idf_floor;\n\n readonly k1: number;\n readonly b: number;\n readonly corpus: readonly (readonly string[])[];\n readonly docCount: number;\n readonly avgdl: number;\n readonly docLens: readonly number[];\n readonly idf: ReadonlyMap<string, number>;\n\n constructor(\n corpus: readonly (readonly string[])[],\n k1: number = BM25_PARAMS.k1,\n b: number = BM25_PARAMS.b,\n ) {\n this.k1 = k1;\n this.b = b;\n this.corpus = corpus;\n this.docCount = corpus.length;\n this.docLens = corpus.map((doc) => doc.length);\n // Python falls back to 1.0 rather than dividing by zero on an empty corpus.\n this.avgdl = this.docCount\n ? this.docLens.reduce((a, n) => a + n, 0) / this.docCount\n : 1.0;\n\n const idf = new Map<string, number>();\n const allTerms = new Set<string>();\n for (const doc of corpus) for (const t of doc) allTerms.add(t);\n for (const term of allTerms) {\n let df = 0;\n for (const doc of corpus) if (doc.includes(term)) df++;\n const raw = Math.log((this.docCount - df + 0.5) / (df + 0.5) + 1.0);\n idf.set(term, Math.max(raw, BM25.IDF_FLOOR));\n }\n this.idf = idf;\n }\n\n score(queryTokens: readonly string[], docIdx: number): number {\n const doc = this.corpus[docIdx];\n if (doc === undefined) return 0;\n const dl = this.docLens[docIdx] ?? 0;\n\n const tfMap = new Map<string, number>();\n for (const t of doc) tfMap.set(t, (tfMap.get(t) ?? 0) + 1);\n\n let s = 0;\n for (const term of queryTokens) {\n const tf = tfMap.get(term);\n if (tf === undefined) continue;\n const idf = this.idf.get(term) ?? BM25.IDF_FLOOR;\n const numerator = tf * (this.k1 + 1);\n const denominator = tf + this.k1 * (1 - this.b + (this.b * dl) / this.avgdl);\n s += (idf * numerator) / denominator;\n }\n return s;\n }\n\n scores(queryTokens: readonly string[]): number[] {\n return this.corpus.map((_, i) => this.score(queryTokens, i));\n }\n}\n","/**\n * In-memory TTL cache for context bundles pushed over gRPC.\n *\n * Port of `maximem_synap/cache/anticipation_cache.py`.\n *\n * ## Why this is a faithful port and not a simplification\n *\n * `@maximem/synap-vercel-adk` already contains a native TS anticipation cache,\n * and it is a simplification: a hardcoded 30-minute TTL, a plain BM25 threshold\n * with no per-query derivation, and none of the gates below. Shipping that as\n * the SDK's cache would mean two retrieval behaviors under one brand, which is\n * gotcha G-C. Every gate here exists because a specific eval failed without it:\n *\n * - **Recall bypass** runs BEFORE scoring. The measured false hit scored 2.86\n * at coverage 1.00, so no score-side gate could ever have caught it.\n * - **The novel-term gate** is suppressed below a 200-stem corpus, because at\n * cold start ordinary English trips it on nearly every query.\n * - **The per-query threshold** scales down for short queries, which otherwise\n * cannot reach the nominal score at all.\n * - **The coverage gate** catches a bundle that clears BM25 on one shared\n * token (\"account\") while lacking the asked-for fact.\n *\n * All thresholds come from the shared behavior contract.\n */\n\nimport { BM25, tokenize } from '../cache/bm25.js';\nimport { CONTRACT, THRESHOLDS, isRecallQuery } from '../behavior/contract.js';\nimport { getEnvFlag, getEnvFloat } from '../util/env.js';\n\nconst EFFECTIVE_FLOOR = CONTRACT.thresholds.effective_floor.value;\nconst QUERY_TOKEN_SCALE = CONTRACT.thresholds.query_token_scale.value;\nconst REJECTED_CAP = CONTRACT.telemetry.rejected_items_cap.value;\nconst PREVIEW_CHARS = CONTRACT.telemetry.content_preview_chars;\n\n/** Sentinel scope that matches any requester. */\nexport const ANY_SCOPE = '_any';\n\n// ── the rung a request or a bundle stands at ───────────────────────────────\n//\n// A pushed bundle is stamped with the scope rung the server retrieved it at,\n// and a fetch names one through `scope_path`. Both are written the same way so\n// they can be compared as strings, because nothing in this process can resolve\n// anything: the server speaks in registry node ids and an SDK in a customer's\n// app has never seen one, so the comparison happens in the vocabulary the\n// CALLER uses, which is level keys and the client's own external ids.\n//\n// The recipe and its golden vectors live in the shared behavior contract\n// (CONTRACT/behavior/anticipation.json, `rung_key`). It is written three times\n// (here, the Python SDK, the server) because the producer is not an SDK, so\n// the usual \"port it once\" rule cannot apply. Do NOT re-tune it here.\nconst RUNG_SEPARATOR = '|';\nconst RUNG_ASSIGN = '=';\n\n/**\n * The rung a `scope_path` names, canonically, or null for no path.\n *\n * Sorted by level key because an object carries whatever order the caller\n * wrote it in, and the ladder's own order is not knowable here. Only the value\n * is escaped: level keys are `^[a-z][a-z0-9_]{0,63}$`, so they can hold\n * neither separator. Backslash is escaped first, or `a|b` and `a\\pb` would\n * encode to the same string, which is a false match between two rungs.\n */\nexport function rungKey(\n scopePath: Record<string, string> | null | undefined,\n): string | null {\n if (!scopePath) return null;\n const pairs: [string, string][] = [];\n for (const [k, v] of Object.entries(scopePath)) {\n if (k === '' || v === null || v === undefined || String(v) === '') continue;\n pairs.push([String(k), String(v)]);\n }\n if (pairs.length === 0) return null;\n pairs.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n return pairs\n .map(([k, v]) => {\n const escaped = v\n .split('\\\\').join('\\\\\\\\')\n .split(RUNG_SEPARATOR).join('\\\\p')\n .split(RUNG_ASSIGN).join('\\\\e');\n return `${k}${RUNG_ASSIGN}${escaped}`;\n })\n .join(RUNG_SEPARATOR);\n}\n\n/**\n * May a bundle stamped `bundleRung` answer a request at `requestRung`?\n *\n * Equality, and equality on purpose. A subset rule (\"the bundle names more\n * rungs than you did, close enough\") reads as the generous option and is the\n * dangerous one: the rung nobody named is exactly the rung that tells two\n * people sharing an external id apart, which is the case the whole ladder\n * exists for. Being wrong here costs a cold fetch; being wrong the other way\n * hands one person's context to another.\n *\n * null on either side means \"named no rung\". Both null is every request in\n * production today and it serves, so nothing changes for anyone who has not\n * turned nested scoping on. `''` normalises to null because a proto string\n * field has no null and an unstamped bundle arrives as the empty string.\n */\nexport function rungServes(\n bundleRung: string | null | undefined,\n requestRung: string | null | undefined,\n): boolean {\n return (bundleRung || null) === (requestRung || null);\n}\n\nexport interface BundleItem {\n item_id?: string;\n content?: string;\n [key: string]: unknown;\n}\n\nexport interface ContextBundle {\n bundleId: string;\n entityId?: string | null;\n conversationId?: string | null;\n itemsByType: Record<string, BundleItem[]>;\n /** Server hint; may only SHORTEN the global TTL, never extend it. */\n ttlHintSeconds?: number | null;\n /** Which anticipation pattern produced this bundle. Diagnostics only. */\n bundleType?: string | null;\n /** The queries the server anticipated. Diagnostics only. */\n searchQueries?: readonly string[] | null;\n /**\n * The scope rung the server retrieved this bundle at, as `rungKey` writes\n * one. Absent from anything an older server sent, which reads as \"named no\n * rung\" rather than as \"matches anything\".\n */\n scopeRung?: string | null;\n}\n\ninterface ItemRecord {\n bundleId: string;\n itemType: string;\n content: string;\n tokens: string[];\n itemDict: BundleItem;\n}\n\ninterface EntryRecord {\n bundleId: string;\n entityId: string;\n conversationId: string | null;\n bundleType: string | null;\n searchQueries: string[];\n /** Sliding lease, refreshed on hit unless TTL hints are honoured. */\n storedAt: number;\n /** Absolute creation time; the max-entry-age cap uses this, not the lease. */\n createdAt: number;\n ttlHintSeconds: number | null;\n scopeRung: string | null;\n}\n\nexport interface LookupResult {\n itemsByType: Record<string, BundleItem[]>;\n bundleIds: string[];\n score: number;\n coverage: number;\n}\n\nexport interface LookupParams {\n searchQuery?: readonly string[] | null;\n entityId?: string | null;\n customerId?: string | null;\n clientId?: string | null;\n conversationId?: string | null;\n /**\n * The rung this request names, from its `scope_path`. A SECOND, independent\n * dimension and NOT another tier of the entity funnel: the funnel widens and\n * the rung does not, because a rung is a boundary and a boundary that widens\n * is not one.\n */\n scopeRung?: string | null;\n maxItems?: number;\n}\n\nexport type ExitReason =\n | 'empty'\n | 'recall_bypass'\n | 'no_query_tokens'\n | 'novel_term_gate'\n | 'empty_corpus'\n | 'no_items_above_threshold'\n | 'coverage_gate'\n | 'hit';\n\nexport interface LookupTelemetry {\n searchQuery: string[];\n entityId: string | null;\n customerId: string | null;\n clientId: string | null;\n conversationId: string | null;\n scopeRung: string | null;\n scopeFilterAccepted: string[];\n novelTermRatio: number | null;\n bm25Threshold: number | null;\n bm25QueryTokens: string[];\n itemsPicked: unknown[];\n itemsRejected: unknown[];\n coverage: number | null;\n hit: boolean;\n exitReason: ExitReason;\n}\n\nexport interface SnapshotItemPreview {\n type: string;\n scope: string | null;\n content: string;\n}\n\nexport interface SnapshotItemRecord {\n bundle_id: string;\n item_type: string;\n tokens: string[];\n content: string;\n}\n\nexport interface SnapshotBundle {\n bundle_id: string;\n entity_id: string;\n conversation_id: string | null;\n bundle_type: string | null;\n search_queries: string[];\n scope_counts: Record<string, number>;\n total_items: number;\n items: SnapshotItemPreview[];\n}\n\nexport interface AnticipationCacheSnapshot {\n total_entries: number;\n total_item_records: number;\n scope_breakdown_overall: Record<string, number>;\n corpus_vocab_size: number;\n corpus_vocab_sample: string[];\n item_records: SnapshotItemRecord[];\n bundles: SnapshotBundle[];\n}\n\nexport interface AnticipationCacheOptions {\n ttlSeconds?: number;\n maxBundles?: number;\n /** Injected in tests. Defaults to a monotonic clock. */\n now?: () => number;\n onLookup?: (telemetry: LookupTelemetry) => void;\n}\n\nconst DEFAULT_TTL_SECONDS = 1800;\nconst DEFAULT_MAX_BUNDLES = 50;\n\nexport class AnticipationCache {\n private readonly ttlSeconds: number;\n private readonly maxBundles: number;\n private readonly now: () => number;\n private readonly onLookup: ((t: LookupTelemetry) => void) | undefined;\n\n private entries = new Map<string, EntryRecord>();\n private items: ItemRecord[] = [];\n private corpusVocab = new Set<string>();\n private bm25: BM25 | null = null;\n private bm25Dirty = true;\n\n constructor(options: AnticipationCacheOptions = {}) {\n this.ttlSeconds = options.ttlSeconds ?? DEFAULT_TTL_SECONDS;\n this.maxBundles = options.maxBundles ?? DEFAULT_MAX_BUNDLES;\n this.now = options.now ?? monotonicNow;\n this.onLookup = options.onLookup;\n }\n\n get size(): number {\n return this.entries.size;\n }\n\n get itemCount(): number {\n return this.items.length;\n }\n\n store(bundle: ContextBundle): void {\n if (!bundle.bundleId) return;\n this.evictExpired();\n\n // Client-scope knowledge (FAQs, policies) arrives with no entity, and the\n // sentinel makes it visible to every requester.\n const entityId = bundle.entityId || ANY_SCOPE;\n\n if (this.entries.has(bundle.bundleId)) this.dropBundle(bundle.bundleId);\n\n const now = this.now();\n this.entries.set(bundle.bundleId, {\n bundleId: bundle.bundleId,\n entityId,\n conversationId: bundle.conversationId ?? null,\n bundleType: bundle.bundleType ?? null,\n searchQueries: [...(bundle.searchQueries ?? [])],\n storedAt: now,\n createdAt: now,\n ttlHintSeconds: bundle.ttlHintSeconds ?? null,\n scopeRung: bundle.scopeRung || null,\n });\n\n for (const [itemType, list] of Object.entries(bundle.itemsByType ?? {})) {\n for (const item of list ?? []) {\n const content = String(item.content ?? '');\n const tokens = tokenize(content);\n this.items.push({ bundleId: bundle.bundleId, itemType, content, tokens, itemDict: item });\n for (const t of tokens) this.corpusVocab.add(t);\n }\n }\n this.bm25Dirty = true;\n\n // LRU by lease age.\n while (this.entries.size > this.maxBundles) {\n let oldest: EntryRecord | null = null;\n for (const e of this.entries.values()) {\n if (oldest === null || e.storedAt < oldest.storedAt) oldest = e;\n }\n if (oldest === null) break;\n this.dropBundle(oldest.bundleId);\n }\n }\n\n lookup(params: LookupParams): LookupResult | null {\n const {\n searchQuery = null, entityId = null, customerId = null,\n clientId = null, conversationId = null, scopeRung = null, maxItems = 10,\n } = params;\n\n this.evictExpired();\n\n const accepted = this.buildAcceptedScope(entityId, customerId, clientId);\n const telemetry: LookupTelemetry = {\n searchQuery: (searchQuery ?? []).filter((q): q is string => Boolean(q)),\n entityId, customerId, clientId, conversationId,\n scopeRung: scopeRung ?? null,\n scopeFilterAccepted: [...accepted].sort(),\n novelTermRatio: null, bm25Threshold: null, bm25QueryTokens: [],\n itemsPicked: [], itemsRejected: [], coverage: null,\n hit: false, exitReason: 'empty',\n };\n\n if (this.entries.size === 0 || this.items.length === 0) {\n return this.miss(telemetry, 'empty');\n }\n\n const hasQuery = (searchQuery ?? []).some((q) => q && q.trim() !== '');\n if (!hasQuery) {\n return this.freshnessLookup(entityId, scopeRung ?? null, maxItems, telemetry);\n }\n\n // Recall bypass fires BEFORE scoring: a stale false-hit on a recall-shaped\n // question makes the agent deny a fact the store holds, and the measured\n // failure cleared every score-side gate.\n if (getEnvFlag(CONTRACT.recall_bypass.env_flag) && isRecallQuery(searchQuery)) {\n return this.miss(telemetry, 'recall_bypass');\n }\n\n const queryTokens = (searchQuery ?? []).flatMap((q) => tokenize(q));\n telemetry.bm25QueryTokens = queryTokens;\n if (queryTokens.length === 0) {\n return this.miss(telemetry, 'no_query_tokens');\n }\n\n const uniqueStems = new Set(queryTokens);\n let novel = 0;\n for (const s of uniqueStems) if (!this.corpusVocab.has(s)) novel++;\n const novelRatio = uniqueStems.size ? novel / uniqueStems.size : 0;\n telemetry.novelTermRatio = round4(novelRatio);\n\n // Only meaningful once the corpus has real vocabulary. Below the floor the\n // ratio is dominated by ordinary English and would miss on nearly anything.\n if (\n this.corpusVocab.size >= THRESHOLDS.minCorpusForNovelGate &&\n novelRatio >= THRESHOLDS.novelTerm\n ) {\n return this.miss(telemetry, 'novel_term_gate');\n }\n\n if (this.bm25Dirty || this.bm25 === null) {\n if (this.items.length === 0) return this.miss(telemetry, 'empty_corpus');\n this.bm25 = new BM25(this.items.map((i) => i.tokens));\n this.bm25Dirty = false;\n }\n\n const scores = this.bm25.scores(queryTokens);\n const validBundles = this.getValidBundleIds(accepted, conversationId, scopeRung ?? null);\n\n const effectiveThreshold = Math.max(\n EFFECTIVE_FLOOR,\n Math.min(THRESHOLDS.bm25, QUERY_TOKEN_SCALE * queryTokens.length),\n );\n telemetry.bm25Threshold = round4(effectiveThreshold);\n\n const picked: { score: number; item: ItemRecord }[] = [];\n const rejected: { score: number; payload: Record<string, unknown> }[] = [];\n\n for (let idx = 0; idx < scores.length; idx++) {\n const item = this.items[idx]!;\n const score = scores[idx]!;\n const reject = (reason: string) =>\n rejected.push({\n score,\n payload: {\n item_index: idx, bundle_id: item.bundleId, item_type: item.itemType,\n content_first_120: item.content.slice(0, PREVIEW_CHARS),\n bm25_score: round4(score), reason,\n },\n });\n if (score < effectiveThreshold) { reject('below_threshold'); continue; }\n if (!validBundles.has(item.bundleId)) { reject('scope_filter_excluded'); continue; }\n picked.push({ score, item });\n }\n\n rejected.sort((a, b) => b.score - a.score);\n telemetry.itemsRejected = rejected.slice(0, REJECTED_CAP).map((r) => r.payload);\n\n if (picked.length === 0) {\n return this.miss(telemetry, 'no_items_above_threshold');\n }\n\n picked.sort((a, b) => b.score - a.score);\n const top = picked.slice(0, maxItems);\n\n const pickedStems = new Set<string>();\n for (const { item } of top) for (const t of item.tokens) pickedStems.add(t);\n let overlap = 0;\n for (const s of uniqueStems) if (pickedStems.has(s)) overlap++;\n const coverage = uniqueStems.size ? overlap / uniqueStems.size : 1.0;\n telemetry.coverage = round4(coverage);\n\n // Observe-only unless explicitly configured. A malformed setting stays\n // observe-only rather than failing closed on every lookup.\n const coverageMin = getEnvFloat('SYNAP_SDK_CACHE_COVERAGE_MIN');\n if (coverageMin !== null && coverage < coverageMin) {\n // Gate BEFORE any side effect, so a rejected lookup leaves cache state\n // untouched and does not refresh a lease.\n return this.miss(telemetry, 'coverage_gate');\n }\n\n const itemsByType: Record<string, BundleItem[]> = {};\n const bundleIds = new Set<string>();\n for (const { item } of top) {\n (itemsByType[item.itemType] ??= []).push(item.itemDict);\n bundleIds.add(item.bundleId);\n }\n\n // Honouring a TTL hint also means a hit stops renewing the lease, otherwise\n // a hinted bundle under steady traffic would outlive its hint.\n const refreshOnHit = !getEnvFlag('SYNAP_SDK_CACHE_HONOR_TTL_HINT');\n if (refreshOnHit) {\n const now = this.now();\n for (const id of bundleIds) {\n const entry = this.entries.get(id);\n if (entry) entry.storedAt = now;\n }\n }\n\n telemetry.hit = true;\n telemetry.exitReason = 'hit';\n telemetry.itemsPicked = top.map(({ score, item }) => ({\n bundle_id: item.bundleId, item_type: item.itemType,\n content_first_120: item.content.slice(0, PREVIEW_CHARS), bm25_score: round4(score),\n }));\n this.fire(telemetry);\n\n return {\n itemsByType,\n bundleIds: [...bundleIds],\n score: top[0]!.score,\n coverage,\n };\n }\n\n /**\n * Drop this entity's bundles after a write, so the cache stops serving a\n * pre-write view. Gated on the flag: this is the write-path hook.\n */\n invalidateEntity(entityId: string): number {\n if (!getEnvFlag('SYNAP_SDK_CACHE_INVALIDATE_ON_WRITE')) return 0;\n return this.dropEntity(entityId);\n }\n\n /**\n * Unconditionally drop this entity's bundles. Backs `cache.clear_user` and\n * `cache.clear_customer`, which are explicit user requests and so are not\n * gated on the invalidate-on-write flag.\n */\n dropEntity(entityId: string): number {\n let dropped = 0;\n for (const entry of [...this.entries.values()]) {\n // Never drop shared client-scope knowledge on one entity's behalf.\n if (entry.entityId === ANY_SCOPE) continue;\n if (entry.entityId === entityId) { this.dropBundle(entry.bundleId); dropped++; }\n }\n return dropped;\n }\n\n /**\n * A read-only diagnostic projection of the cache.\n *\n * Backs `client.anticipation_cache_snapshot()` and mirrors Python's shape\n * key for key, including snake_case keys: this output gets logged, diffed\n * and pasted into issues across both SDKs, so it is a wire format.\n *\n * Note the 140-character content previews. That is Python's literal, and it\n * is deliberately NOT the 120 of `telemetry.content_preview_chars` from the\n * contract, which caps lookup telemetry rather than this snapshot.\n */\n snapshot(): AnticipationCacheSnapshot {\n const SNAPSHOT_PREVIEW_CHARS = 140;\n const overallScope = new Map<string, number>();\n const itemsByBundle = new Map<string, ItemRecord[]>();\n for (const record of this.items) {\n const list = itemsByBundle.get(record.bundleId);\n if (list === undefined) itemsByBundle.set(record.bundleId, [record]);\n else list.push(record);\n }\n\n const bundles: SnapshotBundle[] = [];\n for (const [bundleId, entry] of this.entries) {\n const perBundle = new Map<string, number>();\n const itemPreviews: SnapshotItemPreview[] = [];\n for (const record of itemsByBundle.get(bundleId) ?? []) {\n // `scope` is absent on plenty of items; Python's Counter happily keys\n // on None, which JSON-serialises to null, so preserve the distinction\n // rather than coercing to a string.\n const scope = (record.itemDict['scope'] ?? null) as string | null;\n const key = scope === null ? '' : scope;\n overallScope.set(key, (overallScope.get(key) ?? 0) + 1);\n perBundle.set(key, (perBundle.get(key) ?? 0) + 1);\n itemPreviews.push({\n type: record.itemType,\n scope,\n content: record.content.slice(0, SNAPSHOT_PREVIEW_CHARS),\n });\n }\n let totalItems = 0;\n for (const n of perBundle.values()) totalItems += n;\n bundles.push({\n bundle_id: bundleId,\n entity_id: entry.entityId,\n conversation_id: entry.conversationId,\n bundle_type: entry.bundleType,\n search_queries: [...entry.searchQueries],\n scope_counts: Object.fromEntries(perBundle),\n total_items: totalItems,\n items: itemPreviews,\n });\n }\n\n return {\n total_entries: this.entries.size,\n total_item_records: this.items.length,\n scope_breakdown_overall: Object.fromEntries(overallScope),\n corpus_vocab_size: this.corpusVocab.size,\n corpus_vocab_sample: [...this.corpusVocab].sort().slice(0, 80),\n item_records: this.items.slice(0, 20).map((rec) => ({\n bundle_id: rec.bundleId,\n item_type: rec.itemType,\n tokens: rec.tokens.slice(0, 25),\n content: rec.content.slice(0, SNAPSHOT_PREVIEW_CHARS),\n })),\n bundles,\n };\n }\n\n /**\n * The freshest `user_summary` bundle for this entity, or null.\n *\n * `entityId` is REQUIRED, and a missing one refuses the lookup rather than\n * falling back to the freshest summary across all users. Python hardened this\n * for exactly that reason: the permissive version could splice user A's\n * summary into user B's response on the conversation-scope path.\n */\n lookupUserSummary(\n entityId: string | null | undefined,\n scopeRung: string | null = null,\n ): Record<string, unknown> | null {\n if (!entityId) return null;\n this.evictExpired();\n\n let freshest: EntryRecord | null = null;\n for (const entry of this.entries.values()) {\n if (entry.bundleType !== 'user_summary') continue;\n if (!rungServes(entry.scopeRung, scopeRung)) continue;\n // ANY_SCOPE covers client-shared summaries, which are safe for everyone.\n if (entry.entityId !== entityId && entry.entityId !== ANY_SCOPE) continue;\n if (freshest === null || entry.storedAt > freshest.storedAt) freshest = entry;\n }\n if (freshest === null) return null;\n\n // Serving refreshes the sliding lease, unless the server's TTL hint is\n // being honoured, in which case the hint owns expiry.\n if (!getEnvFlag('SYNAP_SDK_CACHE_HONOR_TTL_HINT')) {\n freshest.storedAt = this.now();\n }\n return this.#bundleFor(freshest.bundleId);\n }\n\n /** Rebuild a bundle's items_by_type from the flat item records. */\n #bundleFor(bundleId: string): Record<string, unknown> {\n const itemsByType: Record<string, BundleItem[]> = {};\n for (const record of this.items) {\n if (record.bundleId !== bundleId) continue;\n (itemsByType[record.itemType] ??= []).push(record.itemDict);\n }\n return { bundle_id: bundleId, items_by_type: itemsByType };\n }\n\n /**\n * Drop every bundle belonging to one conversation.\n *\n * Backs the `compaction_update` signal on the Listen stream: a compaction\n * rewrites the conversation's summary, so any bundle built from the previous\n * state is stale and must not keep serving for the rest of its TTL.\n *\n * Unlike `dropEntity`, client-scope bundles are NOT spared: a bundle is only\n * dropped here if it is bound to this specific conversation, and a shared\n * client-scope bundle has no conversation id to match.\n */\n dropConversation(conversationId: string): number {\n if (!conversationId) return 0;\n let dropped = 0;\n for (const entry of [...this.entries.values()]) {\n if (entry.conversationId === conversationId) { this.dropBundle(entry.bundleId); dropped++; }\n }\n return dropped;\n }\n\n clear(): void {\n this.entries.clear();\n this.items = [];\n this.corpusVocab.clear();\n this.bm25 = null;\n this.bm25Dirty = true;\n }\n\n // ── internals ───────────────────────────────────────────────────────────────\n\n private miss(telemetry: LookupTelemetry, reason: ExitReason): null {\n telemetry.exitReason = reason;\n telemetry.hit = false;\n this.fire(telemetry);\n return null;\n }\n\n private fire(telemetry: LookupTelemetry): void {\n // Exception-safe by contract: a buggy hook must never break the SDK.\n try {\n this.onLookup?.(telemetry);\n } catch {\n /* ignored on purpose */\n }\n }\n\n private freshnessLookup(\n entityId: string | null,\n scopeRung: string | null,\n maxItems: number,\n telemetry: LookupTelemetry,\n ): LookupResult | null {\n // This path serves a WHOLE bundle on no query at all, so it is the least\n // filtered way out of this cache and needs the rung as much as the scored\n // path does.\n const candidates = [...this.entries.values()]\n .filter((e) => rungServes(e.scopeRung, scopeRung))\n .filter((e) => entityId === null || e.entityId === entityId || e.entityId === ANY_SCOPE)\n .sort((a, b) => b.storedAt - a.storedAt);\n if (candidates.length === 0) return this.miss(telemetry, 'empty');\n\n const newest = candidates[0]!;\n const itemsByType: Record<string, BundleItem[]> = {};\n let n = 0;\n for (const item of this.items) {\n if (item.bundleId !== newest.bundleId) continue;\n if (n >= maxItems) break;\n (itemsByType[item.itemType] ??= []).push(item.itemDict);\n n++;\n }\n if (n === 0) return this.miss(telemetry, 'empty');\n\n telemetry.hit = true;\n telemetry.exitReason = 'hit';\n this.fire(telemetry);\n return { itemsByType, bundleIds: [newest.bundleId], score: 0, coverage: 1.0 };\n }\n\n /**\n * The widened scope-match set for a request.\n *\n * A narrower-scope request also matches broader-scope bundles for the same\n * customer or client. Falsy ids are dropped so an empty customer_id cannot\n * accidentally match bundles keyed at \"\".\n */\n private buildAcceptedScope(\n entityId: string | null, customerId: string | null, clientId: string | null,\n ): Set<string> {\n const accepted = new Set<string>([ANY_SCOPE]);\n if (entityId) accepted.add(entityId);\n if (customerId) accepted.add(customerId);\n if (clientId) accepted.add(clientId);\n return accepted;\n }\n\n /**\n * The rung is checked FIRST and it never widens. Everything else here widens\n * deliberately: a user-scope request reaches customer-shared bundles, and a\n * conversation-scope request reaches user-scope ones. A rung is the opposite\n * kind of thing, so it is checked before the tiers and no amount of widening\n * can put a cross-rung bundle back in.\n */\n private getValidBundleIds(\n accepted: Set<string>, conversationId: string | null, scopeRung: string | null,\n ): Set<string> {\n const valid = new Set<string>();\n for (const entry of this.entries.values()) {\n if (!rungServes(entry.scopeRung, scopeRung)) continue;\n if (!accepted.has(entry.entityId)) continue;\n // A conversation-scoped bundle is only valid inside its conversation.\n if (entry.conversationId && conversationId && entry.conversationId !== conversationId) continue;\n valid.add(entry.bundleId);\n }\n return valid;\n }\n\n private effectiveTtl(entry: EntryRecord): number {\n if (!getEnvFlag('SYNAP_SDK_CACHE_HONOR_TTL_HINT')) return this.ttlSeconds;\n if (entry.ttlHintSeconds == null || entry.ttlHintSeconds <= 0) return this.ttlSeconds;\n // A hint may only shorten.\n return Math.min(this.ttlSeconds, entry.ttlHintSeconds);\n }\n\n private evictExpired(): void {\n const now = this.now();\n // Default cap is twice the sliding TTL; 0 disables. Without it a bundle\n // under steady traffic renews forever and can serve a retired value\n // indefinitely.\n const configuredMaxAge = getEnvFloat('SYNAP_SDK_CACHE_MAX_ENTRY_AGE');\n const maxAge = configuredMaxAge ?? this.ttlSeconds * 2;\n\n for (const entry of [...this.entries.values()]) {\n const idleExpired = now - entry.storedAt > this.effectiveTtl(entry);\n const ageExpired = maxAge > 0 && now - entry.createdAt > maxAge;\n if (idleExpired || ageExpired) this.dropBundle(entry.bundleId);\n }\n }\n\n private dropBundle(bundleId: string): void {\n if (!this.entries.delete(bundleId)) return;\n this.items = this.items.filter((i) => i.bundleId !== bundleId);\n // Vocabulary is rebuilt rather than decremented: a stem can be shared by\n // several bundles, so per-bundle subtraction would drop stems still in use.\n this.corpusVocab = new Set(this.items.flatMap((i) => i.tokens));\n this.bm25Dirty = true;\n }\n}\n\nfunction monotonicNow(): number {\n // performance.now() is monotonic and unaffected by wall-clock adjustments,\n // matching Python's time.monotonic(). Date.now() would let an NTP step\n // expire or resurrect every entry at once.\n return typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now() / 1000\n : Date.now() / 1000;\n}\n\nfunction round4(n: number): number {\n return Number(n.toFixed(4));\n}\n"],"mappings":";;;;;;AAAA;AAAA,EACE,UAAY;AAAA,EACZ,SAAW;AAAA,EACX,eAAiB;AAAA,IACf,MAAQ;AAAA,IACR,UAAY;AAAA,IACZ,SAAW;AAAA,IACX,UAAY;AAAA,MACV;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QACT,MAAQ;AAAA,MACV;AAAA,MACA;AAAA,QACE,SAAW;AAAA,QACX,OAAS;AAAA,QAC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AAC3B,UAAM,MAAM,KAAK,IAAI;AAIrB,UAAM,mBAAmB,YAAY,+BAA+B;AACpE,UAAM,SAAS,oBAAoB,KAAK,aAAa;AAErD,eAAW,SAAS,CAAC,GAAG,KAAK,QAAQ,OAAO,CAAC,GAAG;AAC9C,YAAM,cAAc,MAAM,MAAM,WAAW,KAAK,aAAa,KAAK;AAClE,YAAM,aAAa,SAAS,KAAK,MAAM,MAAM,YAAY;AACzD,UAAI,eAAe,WAAY,MAAK,WAAW,MAAM,QAAQ;AAAA,IAC/D;AAAA,EACF;AAAA,EAEQ,WAAW,UAAwB;AACzC,QAAI,CAAC,KAAK,QAAQ,OAAO,QAAQ,EAAG;AACpC,SAAK,QAAQ,KAAK,MAAM,OAAO,CAAC,MAAM,EAAE,aAAa,QAAQ;AAG7D,SAAK,cAAc,IAAI,IAAI,KAAK,MAAM,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;AAC9D,SAAK,YAAY;AAAA,EACnB;AACF;AAEA,SAAS,eAAuB;AAI9B,SAAO,OAAO,gBAAgB,eAAe,OAAO,YAAY,QAAQ,aACpE,YAAY,IAAI,IAAI,MACpB,KAAK,IAAI,IAAI;AACnB;AAEA,SAAS,OAAO,GAAmB;AACjC,SAAO,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC5B;","names":[]}
@@ -1,5 +1,5 @@
1
1
  // src/grpc/descriptor.ts
2
- var PROTO_SHA = "1a9a098645d1b3cf";
2
+ var PROTO_SHA = "a58c9b031b41530d";
3
3
  var SYNAP_PROTO_DESCRIPTOR = {
4
4
  "nested": {
5
5
  "synap": {
@@ -211,6 +211,11 @@ var SYNAP_PROTO_DESCRIPTOR = {
211
211
  "rule": "repeated",
212
212
  "type": "string",
213
213
  "id": 13
214
+ },
215
+ "scope": {
216
+ "keyType": "string",
217
+ "type": "string",
218
+ "id": 14
214
219
  }
215
220
  }
216
221
  },
@@ -394,6 +399,10 @@ var SYNAP_PROTO_DESCRIPTOR = {
394
399
  "ttl_hint_seconds": {
395
400
  "type": "int32",
396
401
  "id": 23
402
+ },
403
+ "anticipation_scope_rung": {
404
+ "type": "string",
405
+ "id": 24
397
406
  }
398
407
  }
399
408
  },
@@ -780,6 +789,10 @@ var GrpcStreamClient = class {
780
789
  // customer; falling back to customer id keeps org-scope bundles usable.
781
790
  entityId: String(bundle["anticipation_user_id"] ?? "") || String(bundle["anticipation_customer_id"] ?? "") || null,
782
791
  conversationId: conversationId || null,
792
+ // The rung the server retrieved this bundle at. Absent from anything an
793
+ // older server sent, and absent reads as "named no rung" rather than as
794
+ // "matches anything".
795
+ scopeRung: String(bundle["anticipation_scope_rung"] ?? "") || null,
783
796
  itemsByType,
784
797
  // 0 means "use the SDK default"; anything else is floored at 60s.
785
798
  ttlHintSeconds: ttlHint > 0 ? Math.max(ttlHint, MIN_TTL_SECONDS) : null,
@@ -853,4 +866,4 @@ export {
853
866
  PROTO_SHA,
854
867
  GrpcStreamClient
855
868
  };
856
- //# sourceMappingURL=chunk-ZU6ZC4SU.js.map
869
+ //# sourceMappingURL=chunk-T5QQBJ6T.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/grpc/descriptor.ts","../src/grpc/stream-client.ts"],"sourcesContent":["/**\n * GENERATED FILE. Do not edit by hand.\n *\n * Source: synap/proto/synap_service.proto\n * Generator: synap/sdk/scripts/gen_proto_descriptor.mjs\n * Proto SHA: a58c9b031b41530d\n *\n * The proto is inlined as a JSON descriptor rather than loaded from disk so\n * that bundlers and Vercel file tracing cannot lose it. Regenerate with\n * `npm run sync-behavior` in synap/sdk/js.\n */\n\n/** sha256 (first 16 hex chars) of the proto this descriptor was built from. */\nexport const PROTO_SHA = 'a58c9b031b41530d';\n\nexport const SYNAP_PROTO_DESCRIPTOR = {\n \"nested\": {\n \"synap\": {\n \"nested\": {\n \"v1\": {\n \"nested\": {\n \"SynapService\": {\n \"methods\": {\n \"Listen\": {\n \"requestType\": \"StreamEvent\",\n \"requestStream\": true,\n \"responseType\": \"StreamResponse\",\n \"responseStream\": true\n },\n \"IngestTelemetry\": {\n \"requestType\": \"TelemetryEvent\",\n \"requestStream\": true,\n \"responseType\": \"TelemetryAck\"\n }\n }\n },\n \"StreamEvent\": {\n \"oneofs\": {\n \"payload\": {\n \"oneof\": [\n \"conversation_event\",\n \"heartbeat_ping\",\n \"session_control\",\n \"context_used\",\n \"context_assembled\"\n ]\n }\n },\n \"fields\": {\n \"conversation_event\": {\n \"type\": \"ConversationEvent\",\n \"id\": 1\n },\n \"heartbeat_ping\": {\n \"type\": \"HeartbeatPing\",\n \"id\": 2\n },\n \"session_control\": {\n \"type\": \"SessionControl\",\n \"id\": 3\n },\n \"context_used\": {\n \"type\": \"ContextUsedEvent\",\n \"id\": 4\n },\n \"context_assembled\": {\n \"type\": \"ContextAssembledEvent\",\n \"id\": 5\n }\n }\n },\n \"ContextUsedEvent\": {\n \"fields\": {\n \"bundle_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"served_item_ids\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 5\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 6\n },\n \"scope\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"source_bundle_ids\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 8\n }\n }\n },\n \"ContextAssembledEvent\": {\n \"fields\": {\n \"correlation_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"final_item_ids\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 5\n },\n \"final_total_tokens\": {\n \"type\": \"int32\",\n \"id\": 6\n },\n \"compaction_id\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"recent_turn_count\": {\n \"type\": \"int32\",\n \"id\": 8\n },\n \"compaction_end_timestamp\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"assembly_source\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"assembly_duration_ms\": {\n \"type\": \"int32\",\n \"id\": 11\n },\n \"cache_hit\": {\n \"type\": \"bool\",\n \"id\": 12\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 13\n },\n \"sdk_version\": {\n \"type\": \"string\",\n \"id\": 14\n }\n }\n },\n \"ConversationEvent\": {\n \"fields\": {\n \"event_type\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"role\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"content\": {\n \"type\": \"string\",\n \"id\": 5\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 6\n },\n \"session_id\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"metadata\": {\n \"keyType\": \"string\",\n \"type\": \"string\",\n \"id\": 8\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 9\n },\n \"tool_name\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"tool_args_json\": {\n \"type\": \"string\",\n \"id\": 11\n },\n \"search_queries\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 12\n },\n \"context_types\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 13\n },\n \"scope\": {\n \"keyType\": \"string\",\n \"type\": \"string\",\n \"id\": 14\n }\n }\n },\n \"HeartbeatPing\": {\n \"fields\": {\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 1\n }\n }\n },\n \"SessionControl\": {\n \"fields\": {\n \"action\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"session_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 5\n }\n }\n },\n \"StreamResponse\": {\n \"oneofs\": {\n \"payload\": {\n \"oneof\": [\n \"context_bundle\",\n \"heartbeat_pong\",\n \"signal\"\n ]\n }\n },\n \"fields\": {\n \"context_bundle\": {\n \"type\": \"ContextBundleProto\",\n \"id\": 1\n },\n \"heartbeat_pong\": {\n \"type\": \"HeartbeatPong\",\n \"id\": 2\n },\n \"signal\": {\n \"type\": \"StreamSignal\",\n \"id\": 3\n }\n }\n },\n \"HeartbeatPong\": {\n \"fields\": {\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 1\n }\n }\n },\n \"StreamSignal\": {\n \"fields\": {\n \"signal_type\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"reason\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"metadata\": {\n \"keyType\": \"string\",\n \"type\": \"string\",\n \"id\": 3\n }\n }\n },\n \"ContextBundleProto\": {\n \"fields\": {\n \"bundle_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"decision_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"items_by_type\": {\n \"keyType\": \"string\",\n \"type\": \"ContextItemList\",\n \"id\": 3\n },\n \"total_tokens\": {\n \"type\": \"int32\",\n \"id\": 4\n },\n \"token_budget\": {\n \"type\": \"int32\",\n \"id\": 5\n },\n \"budget_exceeded\": {\n \"type\": \"bool\",\n \"id\": 6\n },\n \"retrieval_mode\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"sources_queried\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 8\n },\n \"degradation_level\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"warnings\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 10\n },\n \"created_at\": {\n \"type\": \"string\",\n \"id\": 11\n },\n \"retrieval_time_ms\": {\n \"type\": \"int32\",\n \"id\": 12\n },\n \"cache_hit\": {\n \"type\": \"bool\",\n \"id\": 13\n },\n \"search_queries\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 14\n },\n \"anticipation_user_id\": {\n \"type\": \"string\",\n \"id\": 15\n },\n \"anticipation_customer_id\": {\n \"type\": \"string\",\n \"id\": 16\n },\n \"anticipation_conversation_id\": {\n \"type\": \"string\",\n \"id\": 17\n },\n \"search_keywords\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 18\n },\n \"bundle_type\": {\n \"type\": \"string\",\n \"id\": 19\n },\n \"conversation_context\": {\n \"type\": \"ConversationContextProto\",\n \"id\": 20\n },\n \"bundle_confidence\": {\n \"type\": \"float\",\n \"id\": 21\n },\n \"origin_pattern_id\": {\n \"type\": \"string\",\n \"id\": 22\n },\n \"ttl_hint_seconds\": {\n \"type\": \"int32\",\n \"id\": 23\n },\n \"anticipation_scope_rung\": {\n \"type\": \"string\",\n \"id\": 24\n }\n }\n },\n \"ConversationContextProto\": {\n \"fields\": {\n \"summary\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"current_state_json\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"key_extractions_json\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"recent_turns\": {\n \"rule\": \"repeated\",\n \"type\": \"RecentTurnProto\",\n \"id\": 4\n },\n \"compaction_id\": {\n \"type\": \"string\",\n \"id\": 5\n },\n \"compacted_at\": {\n \"type\": \"string\",\n \"id\": 6\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 7\n }\n }\n },\n \"RecentTurnProto\": {\n \"fields\": {\n \"role\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"content\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"timestamp\": {\n \"type\": \"string\",\n \"id\": 3\n }\n }\n },\n \"ContextItemList\": {\n \"fields\": {\n \"items\": {\n \"rule\": \"repeated\",\n \"type\": \"ContextItemProto\",\n \"id\": 1\n }\n }\n },\n \"ContextItemProto\": {\n \"fields\": {\n \"item_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"content\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"context_type\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"source\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"similarity_score\": {\n \"type\": \"float\",\n \"id\": 5\n },\n \"relevance_score\": {\n \"type\": \"float\",\n \"id\": 6\n },\n \"confidence\": {\n \"type\": \"float\",\n \"id\": 7\n },\n \"scope\": {\n \"type\": \"string\",\n \"id\": 8\n },\n \"entity_id\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"created_at\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"event_date\": {\n \"type\": \"string\",\n \"id\": 11\n },\n \"valid_until\": {\n \"type\": \"string\",\n \"id\": 12\n },\n \"temporal_category\": {\n \"type\": \"string\",\n \"id\": 13\n },\n \"temporal_confidence\": {\n \"type\": \"float\",\n \"id\": 14\n }\n }\n },\n \"TelemetryEvent\": {\n \"fields\": {\n \"event_type\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"instance_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"client_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"correlation_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 5\n },\n \"latency_ms\": {\n \"type\": \"int32\",\n \"id\": 6\n },\n \"status\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"error_code\": {\n \"type\": \"string\",\n \"id\": 8\n },\n \"scope\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"cache_status\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"attempt\": {\n \"type\": \"int32\",\n \"id\": 11\n },\n \"http_method\": {\n \"type\": \"string\",\n \"id\": 12\n },\n \"http_path\": {\n \"type\": \"string\",\n \"id\": 13\n },\n \"http_status_code\": {\n \"type\": \"int32\",\n \"id\": 14\n },\n \"metadata\": {\n \"keyType\": \"string\",\n \"type\": \"string\",\n \"id\": 15\n },\n \"sdk_version\": {\n \"type\": \"string\",\n \"id\": 16\n },\n \"batch_id\": {\n \"type\": \"string\",\n \"id\": 17\n }\n }\n },\n \"TelemetryAck\": {\n \"fields\": {\n \"status\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"events_received\": {\n \"type\": \"int32\",\n \"id\": 2\n }\n }\n }\n }\n }\n }\n }\n }\n} as const;\n","/**\n * Bidirectional gRPC stream client for the Synap anticipation channel.\n *\n * Mirrors Python's `GRPCTransport` and the synap-vercel-adk client:\n * - `/synap.v1.SynapService/Listen`, StreamEvent in, StreamResponse out\n * - Auth via `authorization: Bearer <key>` plus `x-client-id` / `x-instance-id`\n * - 30s heartbeat, exponential-backoff reconnect\n * - Server pushes ContextBundleProto, which lands in the AnticipationCache\n *\n * Node-only, and reached exclusively through a lazy `import()` so that merely\n * importing the SDK on Edge or in a Worker stays safe. grpc-js is built on\n * `node:http2`/`node:net`/`node:tls`; a static import fails the BUILD there.\n *\n * The proto arrives as an inlined descriptor (see ./descriptor.ts) rather than\n * being read from disk, so bundlers and Vercel file tracing cannot lose it.\n */\n\nimport type { AnticipationCache } from '../context/anticipation-cache.js';\nimport { SYNAP_PROTO_DESCRIPTOR } from './descriptor.js';\n\nexport type StreamState =\n | 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'closed';\n\n/**\n * The ONLY bundle type the cache refuses.\n *\n * NOTE: this deliberately differs from the synap-vercel-adk stream client,\n * which caches an allowlist of `anticipation` and `user_summary` and drops\n * compaction updates. Python's `_handle_anticipated_bundle` stores everything\n * except `reactive`, and Python is the reference implementation, so an\n * allowlist here would silently cache less than the pip SDK does.\n *\n * Reactive bundles are excluded because they answer a fetch that already\n * happened; caching one serves a stale answer to a different question.\n */\nconst UNCACHEABLE_BUNDLE_TYPE = 'reactive';\n\n// Mirrors the Python GRPCTransport constants.\nconst MAX_RECONNECT_ATTEMPTS = 10;\nconst BACKOFF_BASE_MS = 1_000;\nconst BACKOFF_MAX_MS = 30_000;\nconst HEARTBEAT_INTERVAL_MS = 30_000;\nconst HEARTBEAT_TIMEOUT_MS = 10_000;\nconst MAX_MISSED_HEARTBEATS = 3;\n/** The server may only SHORTEN the SDK default, never extend it past this floor. */\nconst MIN_TTL_SECONDS = 60;\n\nexport interface StreamCredentials {\n apiKey: string;\n clientId: string;\n instanceId: string;\n}\n\nexport interface StreamClientOptions {\n host?: string;\n port?: number;\n useTls?: boolean;\n /** Injected in tests so reconnect backoff does not make the suite slow. */\n sleep?: (ms: number) => Promise<void>;\n /** How long to wait for the channel to become ready. Default 10s. */\n connectTimeoutMs?: number;\n onStateChange?: (state: StreamState) => void;\n /** Fires for every bundle, before the cache filter. Backs `listen({onContext})`. */\n onContext?: (bundle: Record<string, unknown>) => void;\n /** Fires only for `compaction_update` bundles. Backs the compaction subscriptions. */\n onCompactionUpdate?: (conversationId: string, bundle: Record<string, unknown>) => void;\n}\n\ninterface DuplexCall {\n write: (msg: unknown) => void;\n on: (event: string, handler: (arg?: unknown) => void) => void;\n end: () => void;\n}\n\nexport interface ConversationEventInput {\n event_type: string;\n conversation_id?: string;\n user_id?: string;\n customer_id?: string;\n role?: string;\n content?: string;\n session_id?: string;\n metadata?: Record<string, string>;\n timestamp_ms?: number;\n /** proto: ConversationEvent.tool_name */\n tool_name?: string;\n /** proto: ConversationEvent.tool_args_json. Python sends json.dumps(tool_args). */\n tool_args_json?: string;\n search_queries?: string[];\n context_types?: string[];\n}\n\nexport class GrpcStreamClient {\n readonly host: string;\n readonly port: number;\n readonly useTls: boolean;\n\n #state: StreamState = 'disconnected';\n #call: DuplexCall | null = null;\n #reconnectAttempts = 0;\n #lastPongAt = 0;\n #missedHeartbeats = 0;\n #heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n #shutdownRequested = false;\n\n #grpc: typeof import('@grpc/grpc-js') | null = null;\n #ServiceStub: (new (target: string, creds: unknown, opts: unknown) => Record<string, unknown>) | null = null;\n\n readonly #credentials: StreamCredentials;\n readonly #cache: AnticipationCache;\n readonly #options: StreamClientOptions;\n readonly #sleep: (ms: number) => Promise<void>;\n readonly #connectTimeoutMs: number;\n\n constructor(\n credentials: StreamCredentials,\n cache: AnticipationCache,\n options: StreamClientOptions = {},\n ) {\n this.#credentials = credentials;\n this.#cache = cache;\n this.#options = options;\n this.host = options.host ?? 'synap-cloud-prod.maximem.ai';\n this.port = options.port ?? 443;\n this.useTls = options.useTls ?? true;\n this.#sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));\n this.#connectTimeoutMs = options.connectTimeoutMs ?? 10_000;\n }\n\n get currentState(): StreamState { return this.#state; }\n get isConnected(): boolean { return this.#state === 'connected'; }\n\n async connect(): Promise<void> {\n await this.#loadGrpc();\n this.#shutdownRequested = false;\n await this.#establish();\n this.#startHeartbeat();\n }\n\n async disconnect(): Promise<void> {\n this.#shutdownRequested = true;\n this.#stopHeartbeat();\n this.#closeCall();\n this.#setState('closed');\n }\n\n /** Fire-and-forget: a dropped event must never fail the caller's turn. */\n sendConversationEvent(event: ConversationEventInput): void {\n this.#write({ conversation_event: { ...event } });\n }\n\n sendSessionControl(input: {\n action: string;\n session_id?: string;\n conversation_id?: string;\n user_id?: string;\n customer_id?: string;\n }): void {\n this.#write({ session_control: { ...input } });\n }\n\n sendContextUsed(event: Record<string, unknown>): void {\n this.#write({ context_used: { ...event } });\n }\n\n sendContextAssembled(event: Record<string, unknown>): void {\n this.#write({ context_assembled: { ...event } });\n }\n\n #write(msg: unknown): void {\n if (!this.isConnected || this.#call === null) return;\n try {\n this.#call.write(msg);\n } catch {\n // Non-fatal. These are telemetry and control events; losing one is\n // strictly better than surfacing a stream hiccup to the caller.\n }\n }\n\n async #loadGrpc(): Promise<void> {\n if (this.#grpc !== null) return;\n const [grpcMod, protoMod] = await Promise.all([\n import(/* @vite-ignore */ '@grpc/grpc-js'),\n import(/* @vite-ignore */ '@grpc/proto-loader'),\n ]);\n this.#grpc = grpcMod;\n\n // `fromJSON`, not `loadSync`: no path, no disk read, nothing for a bundler\n // to fail to trace. `keepCase` keeps the snake_case field names the server\n // and the Python SDK both use.\n const pkgDef = protoMod.fromJSON(\n SYNAP_PROTO_DESCRIPTOR as unknown as Parameters<typeof protoMod.fromJSON>[0],\n { keepCase: true, longs: Number, enums: String, defaults: true, oneofs: true },\n );\n const pkg = grpcMod.loadPackageDefinition(pkgDef) as unknown as {\n synap: { v1: { SynapService: new (t: string, c: unknown, o: unknown) => Record<string, unknown> } };\n };\n this.#ServiceStub = pkg.synap.v1.SynapService;\n }\n\n async #establish(): Promise<void> {\n this.#setState('connecting');\n const grpc = this.#grpc;\n const Stub = this.#ServiceStub;\n if (grpc === null || Stub === null) throw new Error('gRPC not loaded');\n\n const channelCreds = this.useTls\n ? grpc.credentials.createSsl()\n : grpc.credentials.createInsecure();\n\n const stub = new Stub(`${this.host}:${this.port}`, channelCreds, {\n 'grpc.keepalive_time_ms': 30_000,\n 'grpc.keepalive_timeout_ms': 10_000,\n 'grpc.keepalive_permit_without_calls': 1,\n });\n\n // Wait for the channel before reporting success.\n //\n // grpc-js connects LAZILY: constructing the stub and creating the call both\n // return immediately, and a bad host surfaces later through the call's\n // 'error' event. Without this, `await listen()` resolved against an\n // unreachable port, `is_listening` read true for a stream that never\n // connected, and `send_message()` then dropped every event silently,\n // because sends are deliberately fire-and-forget. Failing loudly here is\n // the difference between a clear error and an agent that looks like it has\n // no memory.\n await new Promise<void>((resolve, reject) => {\n const deadline = new Date(Date.now() + this.#connectTimeoutMs);\n const waitForReady = (stub as unknown as {\n waitForReady?: (d: Date, cb: (e?: Error) => void) => void;\n }).waitForReady;\n if (typeof waitForReady !== 'function') {\n // Older grpc-js, or a stub that does not expose it. Fall back to the\n // lazy behaviour rather than failing outright.\n resolve();\n return;\n }\n waitForReady.call(stub, deadline, (error?: Error) => {\n if (error) reject(error);\n else resolve();\n });\n });\n\n const metadata = new grpc.Metadata();\n metadata.add('authorization', `Bearer ${this.#credentials.apiKey}`);\n metadata.add('x-client-id', this.#credentials.clientId);\n metadata.add('x-instance-id', this.#credentials.instanceId);\n\n const call = (stub['Listen'] as (m: unknown) => DuplexCall)(metadata);\n call.on('data', (msg) => this.#handleMessage(msg as Record<string, unknown>));\n call.on('error', (err) => { void this.#handleDisconnect(`error: ${String(err)}`); });\n call.on('end', () => { void this.#handleDisconnect('server_close'); });\n\n this.#call = call;\n this.#setState('connected');\n this.#reconnectAttempts = 0;\n this.#lastPongAt = Date.now();\n }\n\n #handleMessage(msg: Record<string, unknown>): void {\n if (msg['context_bundle']) {\n this.#handleBundle(msg['context_bundle'] as Record<string, unknown>);\n return;\n }\n if (msg['heartbeat_pong']) {\n this.#lastPongAt = Date.now();\n this.#missedHeartbeats = 0;\n return;\n }\n const signal = msg['signal'] as { signal_type?: string } | undefined;\n if (signal?.signal_type === 'closing') {\n void this.#handleDisconnect('server_signal_closing');\n }\n }\n\n #handleBundle(bundle: Record<string, unknown>): void {\n const bundleType = String(bundle['bundle_type'] ?? '') || 'anticipation';\n const conversationId = String(bundle['anticipation_conversation_id'] ?? '');\n\n if (bundleType !== UNCACHEABLE_BUNDLE_TYPE) this.#store(bundle, bundleType, conversationId);\n\n if (bundleType === 'compaction_update' && conversationId !== '') {\n // Python also deletes this conversation's `compacted_full` /\n // `compacted_context` entries from its separate CacheManager. This SDK\n // has no such cache, and calling dropConversation() here would delete\n // the bundle just stored above, so there is nothing to invalidate.\n this.#options.onCompactionUpdate?.(conversationId, bundle);\n }\n\n // Fires for every type, after storing, matching Python's ordering.\n this.#options.onContext?.(bundle);\n }\n\n #store(bundle: Record<string, unknown>, bundleType: string, conversationId: string): void {\n const itemsByType: Record<string, Array<Record<string, unknown>>> = {};\n for (const [type, list] of Object.entries(bundle['items_by_type'] ?? {})) {\n const items = (list as { items?: Array<Record<string, unknown>> })?.items;\n itemsByType[type] = items ?? [];\n }\n\n const ttlHint = Number(bundle['ttl_hint_seconds'] ?? 0);\n this.#cache.store({\n bundleId: String(bundle['bundle_id'] ?? ''),\n // The cache keys on ONE entity. User id wins when present, so a bundle\n // pushed for a user cannot be served to a different user in the same\n // customer; falling back to customer id keeps org-scope bundles usable.\n entityId:\n String(bundle['anticipation_user_id'] ?? '') ||\n String(bundle['anticipation_customer_id'] ?? '') ||\n null,\n conversationId: conversationId || null,\n // The rung the server retrieved this bundle at. Absent from anything an\n // older server sent, and absent reads as \"named no rung\" rather than as\n // \"matches anything\".\n scopeRung: String(bundle['anticipation_scope_rung'] ?? '') || null,\n itemsByType,\n // 0 means \"use the SDK default\"; anything else is floored at 60s.\n ttlHintSeconds: ttlHint > 0 ? Math.max(ttlHint, MIN_TTL_SECONDS) : null,\n bundleType,\n searchQueries: [\n ...((bundle['search_queries'] as string[] | undefined) ?? []),\n ...((bundle['search_keywords'] as string[] | undefined) ?? []),\n ],\n });\n }\n\n async #handleDisconnect(_reason: string): Promise<void> {\n if (this.#shutdownRequested) return;\n\n this.#closeCall();\n this.#setState('reconnecting');\n\n if (this.#reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {\n this.#setState('disconnected');\n return;\n }\n\n // Jittered exponential backoff. The jitter matters with many SDK instances\n // behind one deploy: without it they all retry in lockstep.\n const delay = Math.min(\n BACKOFF_BASE_MS * 2 ** this.#reconnectAttempts + Math.random() * 1_000,\n BACKOFF_MAX_MS,\n );\n this.#reconnectAttempts += 1;\n\n await this.#sleep(delay);\n if (this.#shutdownRequested) return;\n try {\n await this.#establish();\n } catch {\n void this.#handleDisconnect('reconnect_failed');\n }\n }\n\n #startHeartbeat(): void {\n this.#heartbeatTimer = setInterval(() => {\n if (!this.isConnected || this.#call === null) return;\n const now = Date.now();\n\n if (now - this.#lastPongAt > HEARTBEAT_TIMEOUT_MS) {\n this.#missedHeartbeats += 1;\n if (this.#missedHeartbeats >= MAX_MISSED_HEARTBEATS) {\n void this.#handleDisconnect('heartbeat_timeout');\n return;\n }\n }\n try {\n this.#call.write({ heartbeat_ping: { timestamp_ms: now } });\n } catch {\n void this.#handleDisconnect('heartbeat_write_error');\n }\n }, HEARTBEAT_INTERVAL_MS);\n // Never hold the process open on the heartbeat alone: a CLI that finishes\n // its work should exit, not hang for 30s.\n this.#heartbeatTimer.unref?.();\n }\n\n #stopHeartbeat(): void {\n if (this.#heartbeatTimer !== null) {\n clearInterval(this.#heartbeatTimer);\n this.#heartbeatTimer = null;\n }\n }\n\n #closeCall(): void {\n try {\n this.#call?.end();\n } catch {\n /* already torn down */\n }\n this.#call = null;\n }\n\n #setState(state: StreamState): void {\n this.#state = state;\n this.#options.onStateChange?.(state);\n }\n}\n"],"mappings":";AAaO,IAAM,YAAY;AAElB,IAAM,yBAAyB;AAAA,EACpC,UAAU;AAAA,IACR,SAAS;AAAA,MACP,UAAU;AAAA,QACR,MAAM;AAAA,UACJ,UAAU;AAAA,YACR,gBAAgB;AAAA,cACd,WAAW;AAAA,gBACT,UAAU;AAAA,kBACR,eAAe;AAAA,kBACf,iBAAiB;AAAA,kBACjB,gBAAgB;AAAA,kBAChB,kBAAkB;AAAA,gBACpB;AAAA,gBACA,mBAAmB;AAAA,kBACjB,eAAe;AAAA,kBACf,iBAAiB;AAAA,kBACjB,gBAAgB;AAAA,gBAClB;AAAA,cACF;AAAA,YACF;AAAA,YACA,eAAe;AAAA,cACb,UAAU;AAAA,gBACR,WAAW;AAAA,kBACT,SAAS;AAAA,oBACP;AAAA,oBACA;AAAA,oBACA;AAAA,oBACA;AAAA,oBACA;AAAA,kBACF;AAAA,gBACF;AAAA,cACF;AAAA,cACA,UAAU;AAAA,gBACR,sBAAsB;AAAA,kBACpB,QAAQ;AAAA,kBACR,MAAM;AAAA,gBACR;AAAA,gBACA,kBAAkB;AAAA,kBAChB,QAAQ;AAAA,kBACR,MAAM;AAAA,gBACR;AAAA,gBACA,mBAAmB;AAAA,kBACjB,QAAQ;AAAA,kBACR,MAAM;AAAA,gBAC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B;AAAA,IACF;AAIA,UAAM,QAAQ,KAAK;AAAA,MACjB,kBAAkB,KAAK,KAAK,qBAAqB,KAAK,OAAO,IAAI;AAAA,MACjE;AAAA,IACF;AACA,SAAK,sBAAsB;AAE3B,UAAM,KAAK,OAAO,KAAK;AACvB,QAAI,KAAK,mBAAoB;AAC7B,QAAI;AACF,YAAM,KAAK,WAAW;AAAA,IACxB,QAAQ;AACN,WAAK,KAAK,kBAAkB,kBAAkB;AAAA,IAChD;AAAA,EACF;AAAA,EAEA,kBAAwB;AACtB,SAAK,kBAAkB,YAAY,MAAM;AACvC,UAAI,CAAC,KAAK,eAAe,KAAK,UAAU,KAAM;AAC9C,YAAM,MAAM,KAAK,IAAI;AAErB,UAAI,MAAM,KAAK,cAAc,sBAAsB;AACjD,aAAK,qBAAqB;AAC1B,YAAI,KAAK,qBAAqB,uBAAuB;AACnD,eAAK,KAAK,kBAAkB,mBAAmB;AAC/C;AAAA,QACF;AAAA,MACF;AACA,UAAI;AACF,aAAK,MAAM,MAAM,EAAE,gBAAgB,EAAE,cAAc,IAAI,EAAE,CAAC;AAAA,MAC5D,QAAQ;AACN,aAAK,KAAK,kBAAkB,uBAAuB;AAAA,MACrD;AAAA,IACF,GAAG,qBAAqB;AAGxB,SAAK,gBAAgB,QAAQ;AAAA,EAC/B;AAAA,EAEA,iBAAuB;AACrB,QAAI,KAAK,oBAAoB,MAAM;AACjC,oBAAc,KAAK,eAAe;AAClC,WAAK,kBAAkB;AAAA,IACzB;AAAA,EACF;AAAA,EAEA,aAAmB;AACjB,QAAI;AACF,WAAK,OAAO,IAAI;AAAA,IAClB,QAAQ;AAAA,IAER;AACA,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,UAAU,OAA0B;AAClC,SAAK,SAAS;AACd,SAAK,SAAS,gBAAgB,KAAK;AAAA,EACrC;AACF;","names":[]}
@@ -269,6 +269,89 @@ var anticipation_default = {
269
269
  note: "Rejected items reported per lookup, highest score first, so a large cache cannot bloat the payload."
270
270
  },
271
271
  content_preview_chars: 120
272
+ },
273
+ rung_key: {
274
+ $comment: "SOURCE OF TRUTH for how a scope rung is written on the wire and compared in both SDK anticipation caches. The server stamps a pushed bundle with this string (ContextBundleProto.anticipation_scope_rung) and each SDK builds the same string from the `scope` path its own fetch names; a bundle is servable only when the two agree. Three implementations exist by necessity (server Python, SDK Python, SDK TypeScript) because the producer is not an SDK, so the vectors below are what stops them drifting.",
275
+ note: "Node ids are deliberately not what travels. They are registry surrogates and an SDK in a customer's process has never seen one; a caller names a rung with level keys and its own external ids, so that is the vocabulary the comparison happens in. Level keys are ^[a-z][a-z0-9_]{0,63}$ so they can hold neither separator and only the value needs escaping.",
276
+ separator: "|",
277
+ assign: "=",
278
+ sort: "by level key, ascending, plain codepoint order",
279
+ escapes: {
280
+ "\\": "\\\\",
281
+ "|": "\\p",
282
+ "=": "\\e"
283
+ },
284
+ escape_order: "backslash first. Reversing it makes `a|b` and `a\\pb` encode to the same string, which is a false match between two different rungs.",
285
+ absent: "null (an empty proto string on the wire) means the bundle or the request named no rung. Serving requires the two to be EQUAL, so absent matches only absent. That leaves every client without nested scoping byte-identical to today and refuses every genuinely cross-rung serve; the cost of the rule being wrong is a cold fetch, and the cost of a subset rule being wrong is one person's context handed to another.",
286
+ vectors: [
287
+ {
288
+ path: {},
289
+ key: null,
290
+ note: "no path named"
291
+ },
292
+ {
293
+ path: {
294
+ customer: "acme"
295
+ },
296
+ key: "customer=acme"
297
+ },
298
+ {
299
+ path: {
300
+ customer: "acme",
301
+ team: "payments",
302
+ user: "dana"
303
+ },
304
+ key: "customer=acme|team=payments|user=dana"
305
+ },
306
+ {
307
+ path: {
308
+ user: "dana",
309
+ team: "payments",
310
+ customer: "acme"
311
+ },
312
+ key: "customer=acme|team=payments|user=dana",
313
+ note: "insertion order must not change the key; a dict has whatever order the caller wrote and ladder order is not available here"
314
+ },
315
+ {
316
+ path: {
317
+ customer: "a|b"
318
+ },
319
+ key: "customer=a\\pb"
320
+ },
321
+ {
322
+ path: {
323
+ customer: "a=b"
324
+ },
325
+ key: "customer=a\\eb"
326
+ },
327
+ {
328
+ path: {
329
+ customer: "a\\b"
330
+ },
331
+ key: "customer=a\\\\b"
332
+ },
333
+ {
334
+ path: {
335
+ customer: "a\\pb"
336
+ },
337
+ key: "customer=a\\\\pb",
338
+ note: "the escape-order case: this must NOT collide with a|b above"
339
+ },
340
+ {
341
+ path: {
342
+ customer: "ab"
343
+ },
344
+ key: "customer=ab"
345
+ },
346
+ {
347
+ path: {
348
+ customer: "a",
349
+ b: "c"
350
+ },
351
+ key: "b=c|customer=a",
352
+ note: "sorted by key, so `customer=ab` and this cannot collapse"
353
+ }
354
+ ]
272
355
  }
273
356
  };
274
357
 
@@ -395,6 +478,25 @@ var QUERY_TOKEN_SCALE = CONTRACT.thresholds.query_token_scale.value;
395
478
  var REJECTED_CAP = CONTRACT.telemetry.rejected_items_cap.value;
396
479
  var PREVIEW_CHARS = CONTRACT.telemetry.content_preview_chars;
397
480
  var ANY_SCOPE = "_any";
481
+ var RUNG_SEPARATOR = "|";
482
+ var RUNG_ASSIGN = "=";
483
+ function rungKey(scopePath) {
484
+ if (!scopePath) return null;
485
+ const pairs = [];
486
+ for (const [k, v] of Object.entries(scopePath)) {
487
+ if (k === "" || v === null || v === void 0 || String(v) === "") continue;
488
+ pairs.push([String(k), String(v)]);
489
+ }
490
+ if (pairs.length === 0) return null;
491
+ pairs.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
492
+ return pairs.map(([k, v]) => {
493
+ const escaped = v.split("\\").join("\\\\").split(RUNG_SEPARATOR).join("\\p").split(RUNG_ASSIGN).join("\\e");
494
+ return `${k}${RUNG_ASSIGN}${escaped}`;
495
+ }).join(RUNG_SEPARATOR);
496
+ }
497
+ function rungServes(bundleRung, requestRung) {
498
+ return (bundleRung || null) === (requestRung || null);
499
+ }
398
500
  var DEFAULT_TTL_SECONDS = 1800;
399
501
  var DEFAULT_MAX_BUNDLES = 50;
400
502
  var AnticipationCache = (_class2 = class {
@@ -433,7 +535,8 @@ var AnticipationCache = (_class2 = class {
433
535
  searchQueries: [..._nullishCoalesce(bundle.searchQueries, () => ( []))],
434
536
  storedAt: now,
435
537
  createdAt: now,
436
- ttlHintSeconds: _nullishCoalesce(bundle.ttlHintSeconds, () => ( null))
538
+ ttlHintSeconds: _nullishCoalesce(bundle.ttlHintSeconds, () => ( null)),
539
+ scopeRung: bundle.scopeRung || null
437
540
  });
438
541
  for (const [itemType, list] of Object.entries(_nullishCoalesce(bundle.itemsByType, () => ( {})))) {
439
542
  for (const item of _nullishCoalesce(list, () => ( []))) {
@@ -460,6 +563,7 @@ var AnticipationCache = (_class2 = class {
460
563
  customerId = null,
461
564
  clientId = null,
462
565
  conversationId = null,
566
+ scopeRung = null,
463
567
  maxItems = 10
464
568
  } = params;
465
569
  this.evictExpired();
@@ -470,6 +574,7 @@ var AnticipationCache = (_class2 = class {
470
574
  customerId,
471
575
  clientId,
472
576
  conversationId,
577
+ scopeRung: _nullishCoalesce(scopeRung, () => ( null)),
473
578
  scopeFilterAccepted: [...accepted].sort(),
474
579
  novelTermRatio: null,
475
580
  bm25Threshold: null,
@@ -485,7 +590,7 @@ var AnticipationCache = (_class2 = class {
485
590
  }
486
591
  const hasQuery = (_nullishCoalesce(searchQuery, () => ( []))).some((q) => q && q.trim() !== "");
487
592
  if (!hasQuery) {
488
- return this.freshnessLookup(entityId, maxItems, telemetry);
593
+ return this.freshnessLookup(entityId, _nullishCoalesce(scopeRung, () => ( null)), maxItems, telemetry);
489
594
  }
490
595
  if (_chunkZKOJDUN4cjs.getEnvFlag.call(void 0, CONTRACT.recall_bypass.env_flag) && isRecallQuery(searchQuery)) {
491
596
  return this.miss(telemetry, "recall_bypass");
@@ -509,7 +614,7 @@ var AnticipationCache = (_class2 = class {
509
614
  this.bm25Dirty = false;
510
615
  }
511
616
  const scores = this.bm25.scores(queryTokens);
512
- const validBundles = this.getValidBundleIds(accepted, conversationId);
617
+ const validBundles = this.getValidBundleIds(accepted, conversationId, _nullishCoalesce(scopeRung, () => ( null)));
513
618
  const effectiveThreshold = Math.max(
514
619
  EFFECTIVE_FLOOR,
515
620
  Math.min(THRESHOLDS.bm25, QUERY_TOKEN_SCALE * queryTokens.length)
@@ -683,12 +788,13 @@ var AnticipationCache = (_class2 = class {
683
788
  * for exactly that reason: the permissive version could splice user A's
684
789
  * summary into user B's response on the conversation-scope path.
685
790
  */
686
- lookupUserSummary(entityId) {
791
+ lookupUserSummary(entityId, scopeRung = null) {
687
792
  if (!entityId) return null;
688
793
  this.evictExpired();
689
794
  let freshest = null;
690
795
  for (const entry of this.entries.values()) {
691
796
  if (entry.bundleType !== "user_summary") continue;
797
+ if (!rungServes(entry.scopeRung, scopeRung)) continue;
692
798
  if (entry.entityId !== entityId && entry.entityId !== ANY_SCOPE) continue;
693
799
  if (freshest === null || entry.storedAt > freshest.storedAt) freshest = entry;
694
800
  }
@@ -749,8 +855,8 @@ var AnticipationCache = (_class2 = class {
749
855
  } catch (e2) {
750
856
  }
751
857
  }
752
- freshnessLookup(entityId, maxItems, telemetry) {
753
- const candidates = [...this.entries.values()].filter((e) => entityId === null || e.entityId === entityId || e.entityId === ANY_SCOPE).sort((a, b) => b.storedAt - a.storedAt);
858
+ freshnessLookup(entityId, scopeRung, maxItems, telemetry) {
859
+ const candidates = [...this.entries.values()].filter((e) => rungServes(e.scopeRung, scopeRung)).filter((e) => entityId === null || e.entityId === entityId || e.entityId === ANY_SCOPE).sort((a, b) => b.storedAt - a.storedAt);
754
860
  if (candidates.length === 0) return this.miss(telemetry, "empty");
755
861
  const newest = candidates[0];
756
862
  const itemsByType = {};
@@ -781,9 +887,17 @@ var AnticipationCache = (_class2 = class {
781
887
  if (clientId) accepted.add(clientId);
782
888
  return accepted;
783
889
  }
784
- getValidBundleIds(accepted, conversationId) {
890
+ /**
891
+ * The rung is checked FIRST and it never widens. Everything else here widens
892
+ * deliberately: a user-scope request reaches customer-shared bundles, and a
893
+ * conversation-scope request reaches user-scope ones. A rung is the opposite
894
+ * kind of thing, so it is checked before the tiers and no amount of widening
895
+ * can put a cross-rung bundle back in.
896
+ */
897
+ getValidBundleIds(accepted, conversationId, scopeRung) {
785
898
  const valid = /* @__PURE__ */ new Set();
786
899
  for (const entry of this.entries.values()) {
900
+ if (!rungServes(entry.scopeRung, scopeRung)) continue;
787
901
  if (!accepted.has(entry.entityId)) continue;
788
902
  if (entry.conversationId && conversationId && entry.conversationId !== conversationId) continue;
789
903
  valid.add(entry.bundleId);
@@ -828,5 +942,7 @@ function round4(n) {
828
942
 
829
943
 
830
944
 
831
- exports.CONTRACT = CONTRACT; exports.THRESHOLDS = THRESHOLDS; exports.isRecallQuery = isRecallQuery; exports.stem = stem; exports.tokenize = tokenize; exports.BM25 = BM25; exports.ANY_SCOPE = ANY_SCOPE; exports.AnticipationCache = AnticipationCache;
832
- //# sourceMappingURL=chunk-RB57I2IQ.cjs.map
945
+
946
+
947
+ exports.CONTRACT = CONTRACT; exports.THRESHOLDS = THRESHOLDS; exports.isRecallQuery = isRecallQuery; exports.stem = stem; exports.tokenize = tokenize; exports.BM25 = BM25; exports.ANY_SCOPE = ANY_SCOPE; exports.rungKey = rungKey; exports.rungServes = rungServes; exports.AnticipationCache = AnticipationCache;
948
+ //# sourceMappingURL=chunk-T6U5PVAD.cjs.map