@maximem/synap-js-sdk 0.4.7 → 0.5.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.
Files changed (50) hide show
  1. package/dist/anticipation-cache-LRE3TLK4.cjs +14 -0
  2. package/dist/anticipation-cache-LRE3TLK4.cjs.map +1 -0
  3. package/dist/anticipation-cache-WLU4NMD5.js +14 -0
  4. package/dist/{chunk-ZU6ZC4SU.js → chunk-ASM2OIIG.js} +305 -7
  5. package/dist/chunk-ASM2OIIG.js.map +1 -0
  6. package/dist/{chunk-OCMM2Z5P.js → chunk-BWMPKLFG.js} +40 -2
  7. package/dist/chunk-BWMPKLFG.js.map +1 -0
  8. package/dist/{chunk-3JSE64GW.cjs → chunk-IA2N5NUY.cjs} +315 -17
  9. package/dist/chunk-IA2N5NUY.cjs.map +1 -0
  10. package/dist/{chunk-6LDUDKHS.js → chunk-ODVOQOSO.js} +124 -8
  11. package/dist/chunk-ODVOQOSO.js.map +1 -0
  12. package/dist/{chunk-2TVL5IPQ.cjs → chunk-T372OL3Q.cjs} +41 -3
  13. package/dist/chunk-T372OL3Q.cjs.map +1 -0
  14. package/dist/{chunk-RB57I2IQ.cjs → chunk-T6U5PVAD.cjs} +125 -9
  15. package/dist/chunk-T6U5PVAD.cjs.map +1 -0
  16. package/dist/chunk-ZKOJDUN4.cjs.map +1 -1
  17. package/dist/env-55ULHNJZ.cjs.map +1 -1
  18. package/dist/errors-Bl3vY1eb.d.cts +382 -0
  19. package/dist/errors-Bl3vY1eb.d.ts +382 -0
  20. package/dist/grpc/index.cjs +8 -8
  21. package/dist/grpc/index.cjs.map +1 -1
  22. package/dist/grpc/index.d.cts +44 -4
  23. package/dist/grpc/index.d.ts +44 -4
  24. package/dist/grpc/index.js +6 -6
  25. package/dist/index.cjs +301 -173
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.cts +102 -146
  28. package/dist/index.d.ts +102 -146
  29. package/dist/index.js +192 -64
  30. package/dist/index.js.map +1 -1
  31. package/dist/stream-client-6OWRYOA4.js +16 -0
  32. package/dist/stream-client-Y5JGSF2R.cjs +16 -0
  33. package/dist/stream-client-Y5JGSF2R.cjs.map +1 -0
  34. package/package.json +6 -1
  35. package/dist/anticipation-cache-ARYEEKMU.cjs +0 -10
  36. package/dist/anticipation-cache-ARYEEKMU.cjs.map +0 -1
  37. package/dist/anticipation-cache-BMVF5sXb.d.cts +0 -190
  38. package/dist/anticipation-cache-BMVF5sXb.d.ts +0 -190
  39. package/dist/anticipation-cache-H7HEVWQC.js +0 -10
  40. package/dist/chunk-2TVL5IPQ.cjs.map +0 -1
  41. package/dist/chunk-3JSE64GW.cjs.map +0 -1
  42. package/dist/chunk-6LDUDKHS.js.map +0 -1
  43. package/dist/chunk-OCMM2Z5P.js.map +0 -1
  44. package/dist/chunk-RB57I2IQ.cjs.map +0 -1
  45. package/dist/chunk-ZU6ZC4SU.js.map +0 -1
  46. package/dist/stream-client-6V4FGKZ3.js +0 -7
  47. package/dist/stream-client-PRTOH62B.cjs +0 -7
  48. package/dist/stream-client-PRTOH62B.cjs.map +0 -1
  49. /package/dist/{anticipation-cache-H7HEVWQC.js.map → anticipation-cache-WLU4NMD5.js.map} +0 -0
  50. /package/dist/{stream-client-6V4FGKZ3.js.map → stream-client-6OWRYOA4.js.map} +0 -0
@@ -0,0 +1,382 @@
1
+ /**
2
+ * In-memory TTL cache for context bundles pushed over gRPC.
3
+ *
4
+ * Port of `maximem_synap/cache/anticipation_cache.py`.
5
+ *
6
+ * ## Why this is a faithful port and not a simplification
7
+ *
8
+ * `@maximem/synap-vercel-adk` already contains a native TS anticipation cache,
9
+ * and it is a simplification: a hardcoded 30-minute TTL, a plain BM25 threshold
10
+ * with no per-query derivation, and none of the gates below. Shipping that as
11
+ * the SDK's cache would mean two retrieval behaviors under one brand, which is
12
+ * gotcha G-C. Every gate here exists because a specific eval failed without it:
13
+ *
14
+ * - **Recall bypass** runs BEFORE scoring. The measured false hit scored 2.86
15
+ * at coverage 1.00, so no score-side gate could ever have caught it.
16
+ * - **The novel-term gate** is suppressed below a 200-stem corpus, because at
17
+ * cold start ordinary English trips it on nearly every query.
18
+ * - **The per-query threshold** scales down for short queries, which otherwise
19
+ * cannot reach the nominal score at all.
20
+ * - **The coverage gate** catches a bundle that clears BM25 on one shared
21
+ * token ("account") while lacking the asked-for fact.
22
+ *
23
+ * All thresholds come from the shared behavior contract.
24
+ */
25
+ /** Sentinel scope that matches any requester. */
26
+ declare const ANY_SCOPE = "_any";
27
+ interface BundleItem {
28
+ item_id?: string;
29
+ content?: string;
30
+ [key: string]: unknown;
31
+ }
32
+ interface ContextBundle {
33
+ bundleId: string;
34
+ entityId?: string | null;
35
+ conversationId?: string | null;
36
+ itemsByType: Record<string, BundleItem[]>;
37
+ /** Server hint; may only SHORTEN the global TTL, never extend it. */
38
+ ttlHintSeconds?: number | null;
39
+ /** Which anticipation pattern produced this bundle. Diagnostics only. */
40
+ bundleType?: string | null;
41
+ /** The queries the server anticipated. Diagnostics only. */
42
+ searchQueries?: readonly string[] | null;
43
+ /**
44
+ * The scope rung the server retrieved this bundle at, as `rungKey` writes
45
+ * one. Absent from anything an older server sent, which reads as "named no
46
+ * rung" rather than as "matches anything".
47
+ */
48
+ scopeRung?: string | null;
49
+ }
50
+ interface LookupResult {
51
+ itemsByType: Record<string, BundleItem[]>;
52
+ bundleIds: string[];
53
+ score: number;
54
+ coverage: number;
55
+ }
56
+ interface LookupParams {
57
+ searchQuery?: readonly string[] | null;
58
+ entityId?: string | null;
59
+ customerId?: string | null;
60
+ clientId?: string | null;
61
+ conversationId?: string | null;
62
+ /**
63
+ * The rung this request names, from its `scope_path`. A SECOND, independent
64
+ * dimension and NOT another tier of the entity funnel: the funnel widens and
65
+ * the rung does not, because a rung is a boundary and a boundary that widens
66
+ * is not one.
67
+ */
68
+ scopeRung?: string | null;
69
+ maxItems?: number;
70
+ }
71
+ type ExitReason = 'empty' | 'recall_bypass' | 'no_query_tokens' | 'novel_term_gate' | 'empty_corpus' | 'no_items_above_threshold' | 'coverage_gate' | 'hit';
72
+ interface LookupTelemetry {
73
+ searchQuery: string[];
74
+ entityId: string | null;
75
+ customerId: string | null;
76
+ clientId: string | null;
77
+ conversationId: string | null;
78
+ scopeRung: string | null;
79
+ scopeFilterAccepted: string[];
80
+ novelTermRatio: number | null;
81
+ bm25Threshold: number | null;
82
+ bm25QueryTokens: string[];
83
+ itemsPicked: unknown[];
84
+ itemsRejected: unknown[];
85
+ coverage: number | null;
86
+ hit: boolean;
87
+ exitReason: ExitReason;
88
+ }
89
+ interface SnapshotItemPreview {
90
+ type: string;
91
+ scope: string | null;
92
+ content: string;
93
+ }
94
+ interface SnapshotItemRecord {
95
+ bundle_id: string;
96
+ item_type: string;
97
+ tokens: string[];
98
+ content: string;
99
+ }
100
+ interface SnapshotBundle {
101
+ bundle_id: string;
102
+ entity_id: string;
103
+ conversation_id: string | null;
104
+ bundle_type: string | null;
105
+ search_queries: string[];
106
+ scope_counts: Record<string, number>;
107
+ total_items: number;
108
+ items: SnapshotItemPreview[];
109
+ }
110
+ interface AnticipationCacheSnapshot {
111
+ total_entries: number;
112
+ total_item_records: number;
113
+ scope_breakdown_overall: Record<string, number>;
114
+ corpus_vocab_size: number;
115
+ corpus_vocab_sample: string[];
116
+ item_records: SnapshotItemRecord[];
117
+ bundles: SnapshotBundle[];
118
+ }
119
+ interface AnticipationCacheOptions {
120
+ ttlSeconds?: number;
121
+ maxBundles?: number;
122
+ /** Injected in tests. Defaults to a monotonic clock. */
123
+ now?: () => number;
124
+ onLookup?: (telemetry: LookupTelemetry) => void;
125
+ }
126
+ declare class AnticipationCache {
127
+ #private;
128
+ private readonly ttlSeconds;
129
+ private readonly maxBundles;
130
+ private readonly now;
131
+ private readonly onLookup;
132
+ private entries;
133
+ private items;
134
+ private corpusVocab;
135
+ private bm25;
136
+ private bm25Dirty;
137
+ constructor(options?: AnticipationCacheOptions);
138
+ get size(): number;
139
+ get itemCount(): number;
140
+ store(bundle: ContextBundle): void;
141
+ lookup(params: LookupParams): LookupResult | null;
142
+ /**
143
+ * Drop this entity's bundles after a write, so the cache stops serving a
144
+ * pre-write view. Gated on the flag: this is the write-path hook.
145
+ */
146
+ invalidateEntity(entityId: string): number;
147
+ /**
148
+ * Unconditionally drop this entity's bundles. Backs `cache.clear_user` and
149
+ * `cache.clear_customer`, which are explicit user requests and so are not
150
+ * gated on the invalidate-on-write flag.
151
+ */
152
+ dropEntity(entityId: string): number;
153
+ /**
154
+ * A read-only diagnostic projection of the cache.
155
+ *
156
+ * Backs `client.anticipation_cache_snapshot()` and mirrors Python's shape
157
+ * key for key, including snake_case keys: this output gets logged, diffed
158
+ * and pasted into issues across both SDKs, so it is a wire format.
159
+ *
160
+ * Note the 140-character content previews. That is Python's literal, and it
161
+ * is deliberately NOT the 120 of `telemetry.content_preview_chars` from the
162
+ * contract, which caps lookup telemetry rather than this snapshot.
163
+ */
164
+ snapshot(): AnticipationCacheSnapshot;
165
+ /**
166
+ * The freshest `user_summary` bundle for this entity, or null.
167
+ *
168
+ * `entityId` is REQUIRED, and a missing one refuses the lookup rather than
169
+ * falling back to the freshest summary across all users. Python hardened this
170
+ * for exactly that reason: the permissive version could splice user A's
171
+ * summary into user B's response on the conversation-scope path.
172
+ */
173
+ lookupUserSummary(entityId: string | null | undefined, scopeRung?: string | null): Record<string, unknown> | null;
174
+ /**
175
+ * Drop every bundle belonging to one conversation.
176
+ *
177
+ * Backs the `compaction_update` signal on the Listen stream: a compaction
178
+ * rewrites the conversation's summary, so any bundle built from the previous
179
+ * state is stale and must not keep serving for the rest of its TTL.
180
+ *
181
+ * Unlike `dropEntity`, client-scope bundles are NOT spared: a bundle is only
182
+ * dropped here if it is bound to this specific conversation, and a shared
183
+ * client-scope bundle has no conversation id to match.
184
+ */
185
+ dropConversation(conversationId: string): number;
186
+ clear(): void;
187
+ private miss;
188
+ private fire;
189
+ private freshnessLookup;
190
+ /**
191
+ * The widened scope-match set for a request.
192
+ *
193
+ * A narrower-scope request also matches broader-scope bundles for the same
194
+ * customer or client. Falsy ids are dropped so an empty customer_id cannot
195
+ * accidentally match bundles keyed at "".
196
+ */
197
+ private buildAcceptedScope;
198
+ /**
199
+ * The rung is checked FIRST and it never widens. Everything else here widens
200
+ * deliberately: a user-scope request reaches customer-shared bundles, and a
201
+ * conversation-scope request reaches user-scope ones. A rung is the opposite
202
+ * kind of thing, so it is checked before the tiers and no amount of widening
203
+ * can put a cross-rung bundle back in.
204
+ */
205
+ private getValidBundleIds;
206
+ private effectiveTtl;
207
+ private evictExpired;
208
+ private dropBundle;
209
+ }
210
+
211
+ /**
212
+ * Synap SDK error taxonomy.
213
+ *
214
+ * Mirrors `maximem_synap/models/errors.py` 1:1, including the four
215
+ * backward-compatibility aliases at the bottom. If you add an error to one
216
+ * SDK, add it to the other in the same change.
217
+ *
218
+ * ## Why every error carries a `.code`
219
+ *
220
+ * This package ships dual ESM + CJS. A consumer whose dependency graph pulls
221
+ * in both formats gets *two* copies of every class in this file, and then:
222
+ *
223
+ * try { ... } catch (e) { if (e instanceof SynapError) { ... } }
224
+ *
225
+ * silently evaluates to `false` against the copy from the other format. Error
226
+ * handling stops working and nothing throws to tell you. `.code` is a plain
227
+ * string, so it is immune. Prefer it at package boundaries:
228
+ *
229
+ * if (isSynapError(e) && e.code === 'rate_limit') { ... }
230
+ *
231
+ * `Symbol.hasInstance` is also wired up on the base class, so `instanceof`
232
+ * works across realms too -- but `.code` is the documented contract.
233
+ */
234
+ /** Stable, format-independent discriminators. Never renumber or reuse. */
235
+ type SynapErrorCode = 'synap_error' | 'transient' | 'permanent' | 'network_timeout' | 'rate_limit' | 'insufficient_credits' | 'service_unavailable' | 'invalid_input' | 'invalid_instance_id' | 'invalid_conversation_id' | 'authentication' | 'context_not_found' | 'conflict' | 'transcript_conflict' | 'session_expired' | 'listening_already_active' | 'listening_not_active' | 'agent_unavailable';
236
+ interface SynapErrorOptions {
237
+ correlationId?: string | null;
238
+ cause?: unknown;
239
+ }
240
+ declare class SynapError extends Error {
241
+ /**
242
+ * The single declaration site for each subclass's code.
243
+ *
244
+ * It is `static` rather than a class field on purpose. Under
245
+ * `useDefineForClassFields` (the default at our ES2022 target) a class field
246
+ * is an *instance* property, so it is invisible from the constructor object.
247
+ * `Symbol.hasInstance` below only has the constructor to work with, so a
248
+ * field would leave it unable to tell `AuthenticationError` from
249
+ * `RateLimitError` -- it would report every Synap error as an instance of
250
+ * every other one.
251
+ */
252
+ static readonly errorCode: SynapErrorCode;
253
+ /** True for errors where a retry may succeed. Static for the same reason. */
254
+ static readonly isTransient: boolean;
255
+ /** Own, enumerable, so logs and JSON.stringify include it. */
256
+ readonly code: SynapErrorCode;
257
+ readonly correlationId: string | null;
258
+ readonly transient: boolean;
259
+ constructor(message: string, options?: SynapErrorOptions);
260
+ static [Symbol.hasInstance](instance: unknown): boolean;
261
+ }
262
+ /** Type guard that works across ESM/CJS copies and realms. */
263
+ declare function isSynapError(e: unknown): e is SynapError;
264
+ declare class SynapTransientError extends SynapError {
265
+ static readonly errorCode: SynapErrorCode;
266
+ static readonly isTransient: boolean;
267
+ }
268
+ declare class SynapPermanentError extends SynapError {
269
+ static readonly errorCode: SynapErrorCode;
270
+ static readonly isTransient: boolean;
271
+ }
272
+ declare class NetworkTimeoutError extends SynapTransientError {
273
+ static readonly errorCode: SynapErrorCode;
274
+ }
275
+ /**
276
+ * Rate limit exceeded (HTTP 429, gRPC RESOURCE_EXHAUSTED).
277
+ *
278
+ * Also carries the two credit stops the server reports as 429, because both
279
+ * recover with time or a plan change rather than with a retry of this request:
280
+ * `reason: 'trial_limit_reached'` (the Trial cap is spent, see `upgradeUrl`)
281
+ * and `reason: 'subscription_inactive'` (a paid plan whose subscription is past
282
+ * due, unpaid or cancelled, see `manageUrl`). `reason` is null for an ordinary
283
+ * rate limit and against a server too old to send one.
284
+ */
285
+ declare class RateLimitError extends SynapTransientError {
286
+ static readonly errorCode: SynapErrorCode;
287
+ readonly retryAfterSeconds: number | null;
288
+ /** Machine-readable cause, when the stop was a credit stop. */
289
+ readonly reason: string | null;
290
+ /** Where a Trial customer upgrades. Python calls this `upgrade_url`. */
291
+ readonly upgradeUrl: string | null;
292
+ /** Where billing is managed. Python calls this `manage_url`. */
293
+ readonly manageUrl: string | null;
294
+ constructor(message: string, options?: SynapErrorOptions & {
295
+ retryAfterSeconds?: number | null;
296
+ reason?: string | null;
297
+ upgradeUrl?: string | null;
298
+ manageUrl?: string | null;
299
+ });
300
+ }
301
+ declare class ServiceUnavailableError extends SynapTransientError {
302
+ static readonly errorCode: SynapErrorCode;
303
+ }
304
+ declare class AgentUnavailableError extends SynapTransientError {
305
+ static readonly errorCode: SynapErrorCode;
306
+ constructor(message?: string, options?: SynapErrorOptions);
307
+ }
308
+ /**
309
+ * The caller's credit wallet cannot cover this request.
310
+ *
311
+ * HTTP 402, and gRPC RESOURCE_EXHAUSTED with credit-related trailing metadata.
312
+ * Permanent by design: retrying without topping up burns quota and never
313
+ * succeeds. This is the error behind "the agent forgot" reports where retrieval
314
+ * silently returns nothing.
315
+ */
316
+ declare class InsufficientCreditsError extends SynapPermanentError {
317
+ static readonly errorCode: SynapErrorCode;
318
+ readonly balanceCredits: number | null;
319
+ readonly requiredCredits: number | null;
320
+ /** Where the balance can be viewed. Python calls this `recovery_url`. */
321
+ readonly recoveryUrl: string | null;
322
+ /** Where a redeem code can be entered. Python calls this `redeem_url`. */
323
+ readonly redeemUrl: string | null;
324
+ /**
325
+ * Machine-readable cause. `'overages_disabled'` means the plan is paid and
326
+ * the balance is spent, but the account has not allowed usage past zero, so
327
+ * the work stops until someone allows overages or adds credits. Null when an
328
+ * older server did not send one.
329
+ */
330
+ readonly reason: string | null;
331
+ /** Where that setting and billing are managed. Python calls this `manage_url`. */
332
+ readonly manageUrl: string | null;
333
+ constructor(message: string, options?: SynapErrorOptions & {
334
+ balanceCredits?: number | null;
335
+ requiredCredits?: number | null;
336
+ recoveryUrl?: string | null;
337
+ redeemUrl?: string | null;
338
+ reason?: string | null;
339
+ manageUrl?: string | null;
340
+ });
341
+ }
342
+ declare class InvalidInputError extends SynapPermanentError {
343
+ static readonly errorCode: SynapErrorCode;
344
+ }
345
+ /**
346
+ * Raised by `validateInstanceId` before any network call, matching Python's
347
+ * `utils/validators.py`. The message text is identical in both SDKs.
348
+ */
349
+ declare class InvalidInstanceIdError extends InvalidInputError {
350
+ static readonly errorCode: SynapErrorCode;
351
+ }
352
+ /** See the note on InvalidInstanceIdError. Raised by `validateConversationId`. */
353
+ declare class InvalidConversationIdError extends InvalidInputError {
354
+ static readonly errorCode: SynapErrorCode;
355
+ }
356
+ declare class AuthenticationError extends SynapPermanentError {
357
+ static readonly errorCode: SynapErrorCode;
358
+ }
359
+ declare class ContextNotFoundError extends SynapPermanentError {
360
+ static readonly errorCode: SynapErrorCode;
361
+ }
362
+ declare class ConflictError extends SynapPermanentError {
363
+ static readonly errorCode: SynapErrorCode;
364
+ }
365
+ declare class TranscriptConflictError extends ConflictError {
366
+ static readonly errorCode: SynapErrorCode;
367
+ }
368
+ declare class SessionExpiredError extends SynapPermanentError {
369
+ static readonly errorCode: SynapErrorCode;
370
+ }
371
+ declare class ListeningAlreadyActiveError extends SynapPermanentError {
372
+ static readonly errorCode: SynapErrorCode;
373
+ }
374
+ declare class ListeningNotActiveError extends SynapPermanentError {
375
+ static readonly errorCode: SynapErrorCode;
376
+ }
377
+ declare const SDKError: typeof SynapError;
378
+ declare const TransientError: typeof SynapTransientError;
379
+ declare const PermanentError: typeof SynapPermanentError;
380
+ declare const ConnectionError: typeof NetworkTimeoutError;
381
+
382
+ export { AnticipationCache as A, type BundleItem as B, ConflictError as C, isSynapError as D, type ExitReason as E, InsufficientCreditsError as I, ListeningAlreadyActiveError as L, NetworkTimeoutError as N, PermanentError as P, RateLimitError as R, SynapError as S, TranscriptConflictError as T, type AnticipationCacheSnapshot as a, ANY_SCOPE as b, AgentUnavailableError as c, type AnticipationCacheOptions as d, AuthenticationError as e, ConnectionError as f, type ContextBundle as g, ContextNotFoundError as h, InvalidConversationIdError as i, InvalidInputError as j, InvalidInstanceIdError as k, ListeningNotActiveError as l, type LookupParams as m, type LookupResult as n, type LookupTelemetry as o, SDKError as p, ServiceUnavailableError as q, SessionExpiredError as r, type SnapshotBundle as s, type SnapshotItemPreview as t, type SnapshotItemRecord as u, type SynapErrorCode as v, type SynapErrorOptions as w, SynapPermanentError as x, SynapTransientError as y, TransientError as z };