@maximem/synap-js-sdk 0.5.4 → 0.5.6

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/scaler/maximem_synap/synap/sdk/js/dist/chunk-ZKOJDUN4.cjs","../src/util/env.ts"],"names":[],"mappings":"AAAA;ACaA,IAAM,OAAA,kBAAS,IAAI,GAAA,CAAI,CAAC,MAAA,EAAQ,GAAA,EAAK,KAAK,CAAC,CAAA;AAE3C,SAAS,OAAA,CAAQ,IAAA,EAAkC;AACjD,EAAA,GAAA,CAAI,OAAO,QAAA,IAAY,YAAA,GAAe,OAAA,CAAQ,IAAA,IAAQ,KAAA,CAAA,EAAW,OAAO,KAAA,CAAA;AACxE,EAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,IAAI,CAAA;AACzB;AAGO,SAAS,UAAA,CAAW,IAAA,EAAc,SAAA,EAAW,KAAA,EAAgB;AAClE,EAAA,MAAM,IAAA,EAAM,OAAA,CAAQ,IAAI,CAAA;AACxB,EAAA,GAAA,CAAI,IAAA,IAAQ,KAAA,EAAA,GAAa,GAAA,CAAI,IAAA,CAAK,EAAA,IAAM,EAAA,EAAI,OAAO,QAAA;AACnD,EAAA,OAAO,MAAA,CAAO,GAAA,CAAI,GAAA,CAAI,IAAA,CAAK,CAAA,CAAE,WAAA,CAAY,CAAC,CAAA;AAC5C;AAGO,SAAS,WAAA,CAAY,IAAA,EAA6B;AACvD,EAAA,MAAM,IAAA,kBAAM,OAAA,iBAAQ,IAAI,CAAA,6BAAG,IAAA,mBAAK,GAAA;AAChC,EAAA,GAAA,CAAI,CAAC,GAAA,EAAK,OAAO,IAAA;AACjB,EAAA,MAAM,EAAA,EAAI,MAAA,CAAO,GAAG,CAAA;AACpB,EAAA,OAAO,MAAA,CAAO,QAAA,CAAS,CAAC,EAAA,EAAI,EAAA,EAAI,IAAA;AAClC;AAEO,SAAS,MAAA,CAAO,IAAA,EAAkC;AACvD,EAAA,MAAM,EAAA,EAAI,OAAA,CAAQ,IAAI,CAAA;AACtB,EAAA,OAAO,EAAA,IAAM,KAAA,EAAA,GAAa,EAAA,IAAM,GAAA,EAAK,KAAA,EAAA,EAAY,CAAA;AACnD;ADjBA;AACA;AACE;AACA;AACA;AACF,4FAAC","file":"/Users/scaler/maximem_synap/synap/sdk/js/dist/chunk-ZKOJDUN4.cjs","sourcesContent":[null,"/**\n * Environment access.\n *\n * Every read happens at CALL time, never at module load. Python does\n * `os.environ.get(...)` inside the function bodies, and tests plus runtime\n * toggles depend on that: a value captured at import time makes a later\n * `process.env` mutation look like the flag simply does not work. That is\n * gotcha G-S.\n *\n * `process` is absent on Workers and in the browser, so every accessor\n * tolerates it being missing.\n */\n\nconst TRUTHY = new Set(['true', '1', 'yes']);\n\nfunction readEnv(name: string): string | undefined {\n if (typeof process === 'undefined' || process.env === undefined) return undefined;\n return process.env[name];\n}\n\n/** Boolean flag. Defaults to false, matching the Python SDK's flags. */\nexport function getEnvFlag(name: string, fallback = false): boolean {\n const raw = readEnv(name);\n if (raw === undefined || raw.trim() === '') return fallback;\n return TRUTHY.has(raw.trim().toLowerCase());\n}\n\n/** Numeric setting. Returns null when unset OR malformed: a bad value must not fail closed. */\nexport function getEnvFloat(name: string): number | null {\n const raw = readEnv(name)?.trim();\n if (!raw) return null;\n const n = Number(raw);\n return Number.isFinite(n) ? n : null;\n}\n\nexport function getEnv(name: string): string | undefined {\n const v = readEnv(name);\n return v === undefined || v === '' ? undefined : v;\n}\n"]}
1
+ {"version":3,"sources":["/private/tmp/claude-501/-Users-anish-maximemai-maximem-synap/364ae6d0-b8b7-4119-bfaf-7676354661c6/scratchpad/jsrel/synap/sdk/js/dist/chunk-ZKOJDUN4.cjs","../src/util/env.ts"],"names":[],"mappings":"AAAA;ACaA,IAAM,OAAA,kBAAS,IAAI,GAAA,CAAI,CAAC,MAAA,EAAQ,GAAA,EAAK,KAAK,CAAC,CAAA;AAE3C,SAAS,O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n * Environment access.\n *\n * Every read happens at CALL time, never at module load. Python does\n * `os.environ.get(...)` inside the function bodies, and tests plus runtime\n * toggles depend on that: a value captured at import time makes a later\n * `process.env` mutation look like the flag simply does not work. That is\n * gotcha G-S.\n *\n * `process` is absent on Workers and in the browser, so every accessor\n * tolerates it being missing.\n */\n\nconst TRUTHY = new Set(['true', '1', 'yes']);\n\nfunction readEnv(name: string): string | undefined {\n if (typeof process === 'undefined' || process.env === undefined) return undefined;\n return process.env[name];\n}\n\n/** Boolean flag. Defaults to false, matching the Python SDK's flags. */\nexport function getEnvFlag(name: string, fallback = false): boolean {\n const raw = readEnv(name);\n if (raw === undefined || raw.trim() === '') return fallback;\n return TRUTHY.has(raw.trim().toLowerCase());\n}\n\n/** Numeric setting. Returns null when unset OR malformed: a bad value must not fail closed. */\nexport function getEnvFloat(name: string): number | null {\n const raw = readEnv(name)?.trim();\n if (!raw) return null;\n const n = Number(raw);\n return Number.isFinite(n) ? n : null;\n}\n\nexport function getEnv(name: string): string | undefined {\n const v = readEnv(name);\n return v === undefined || v === '' ? undefined : v;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/scaler/maximem_synap/synap/sdk/js/dist/env-55ULHNJZ.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF,kJAAC","file":"/Users/scaler/maximem_synap/synap/sdk/js/dist/env-55ULHNJZ.cjs"}
1
+ {"version":3,"sources":["/private/tmp/claude-501/-Users-anish-maximemai-maximem-synap/364ae6d0-b8b7-4119-bfaf-7676354661c6/scratchpad/jsrel/synap/sdk/js/dist/env-55ULHNJZ.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACF,kJAAC","file":"/private/tmp/claude-501/-Users-anish-maximemai-maximem-synap/364ae6d0-b8b7-4119-bfaf-7676354661c6/scratchpad/jsrel/synap/sdk/js/dist/env-55ULHNJZ.cjs"}
@@ -1,7 +1,7 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
3
 
4
- var _chunkWWTGJZA7cjs = require('../chunk-WWTGJZA7.cjs');
4
+ var _chunkWE4QSR6Acjs = require('../chunk-WE4QSR6A.cjs');
5
5
 
6
6
 
7
7
  var _chunkT372OL3Qcjs = require('../chunk-T372OL3Q.cjs');
@@ -39,7 +39,7 @@ async function listen(options) {
39
39
  throw new (0, _chunkT372OL3Qcjs.ListeningNotActiveError)(availability.detail);
40
40
  }
41
41
  const [{ GrpcStreamClient: StreamClient }, { AnticipationCache }, { getEnv }] = await Promise.all([
42
- Promise.resolve().then(() => _interopRequireWildcard(require("../stream-client-GJM4YSXW.cjs"))),
42
+ Promise.resolve().then(() => _interopRequireWildcard(require("../stream-client-A6IO6E47.cjs"))),
43
43
  Promise.resolve().then(() => _interopRequireWildcard(require("../anticipation-cache-LRE3TLK4.cjs"))),
44
44
  Promise.resolve().then(() => _interopRequireWildcard(require("../env-55ULHNJZ.cjs")))
45
45
  ]);
@@ -83,5 +83,5 @@ async function listen(options) {
83
83
 
84
84
 
85
85
 
86
- exports.GrpcStreamClient = _chunkWWTGJZA7cjs.GrpcStreamClient; exports.PROTO_SHA = _chunkWWTGJZA7cjs.PROTO_SHA; exports.checkGrpcAvailability = checkGrpcAvailability; exports.listen = listen;
86
+ exports.GrpcStreamClient = _chunkWE4QSR6Acjs.GrpcStreamClient; exports.PROTO_SHA = _chunkWE4QSR6Acjs.PROTO_SHA; exports.checkGrpcAvailability = checkGrpcAvailability; exports.listen = listen;
87
87
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/scaler/maximem_synap/synap/sdk/js/dist/grpc/index.cjs","../../src/grpc/index.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,yDAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B;AACA;ACkCA,MAAA,SAAsB,qBAAA,CAAA,EAAmD;AACvE,EAAA,MAAM,OAAA,EACJ,OAAO,QAAA,IAAY,YAAA,mBACnB,OAAA,mBAAQ,QAAA,6BAAU,OAAA,IAAS,KAAA,EAAA,GAC3B,OAAQ,UAAA,CAAyC,YAAA,IAAgB,WAAA;AAEnE,EAAA,GAAA,CAAI,CAAC,MAAA,EAAQ;AACX,IAAA,OAAO;AAAA,MACL,SAAA,EAAW,KAAA;AAAA,MACX,MAAA,EAAQ,UAAA;AAAA,MACR,MAAA,EACE;AAAA,IAIJ,CAAA;AAAA,EACF;AAEA,EAAA,IAAI;AACF,IAAA,MAAM,4DAAA;AAAA;AAAA,MAA0B;AAAA,IAAe,GAAA;AAC/C,IAAA,OAAO,EAAE,SAAA,EAAW,KAAK,CAAA;AAAA,EAC3B,EAAA,MAAA,CAAS,KAAA,EAAO;AACd,IAAA,OAAO;AAAA,MACL,SAAA,EAAW,KAAA;AAAA,MACX,MAAA,EAAQ,gBAAA;AAAA,MACR,MAAA,EACE,CAAA,oIAAA,mCAEK,KAAA,6BAAiB,SAAA,UAAW,MAAA,CAAO,KAAK,GAAC,CAAA,CAAA;AAAA,IAClD,CAAA;AAAA,EACF;AACF;AA4BA,MAAA,SAAsB,MAAA,CACpB,OAAA,EAQ2B;AAC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OAAA,CAAQ,KAAK,EAAA,EAAI,CAAC,CAAA;AAAA,MAC3D,GAAI,OAAA,CAAQ,KAAA,IAAS,KAAA,EAAA,EAAY,EAAE,IAAA,EAAM,OAAA,CAAQ,KAAK,EAAA,EAAI,CAAC,CAAA;AAAA,MAC3D,GAAI,OAAA,CAAQ,OAAA,IAAW,KAAA,EAAA,EAAY,EAAE,MAAA,EAAQ,OAAA,CAAQ,OAAO,EAAA,EAAI,CAAC,CAAA;AAAA,MACjE,GAAI,OAAA,CAAQ,SAAA,IAAa,KAAA,EAAA,EAAY,EAAE,SAAA,EAAW,OAAA,CAAQ,SAAS,EAAA,EAAI,CAAC;AAAA,IAC1E;AAAA,EACF,CAAA;AACA,EAAA,MAAM,MAAA,CAAO,OAAA,CAAQ,CAAA;AACrB,EAAA,MAAA,CAAO,kBAAA,CAAmB;AAAA,IACxB,MAAA,EAAQ,OAAA;AAAA,IACR,eAAA,EAAiB,OAAA,CAAQ,cAAA;AAAA,IACzB,GAAI,OAAA,CAAQ,OAAA,IAAW,KAAA,EAAA,EAAY,EAAE,OAAA,EAAS,OAAA,CAAQ,OAAO,EAAA,EAAI,CAAC,CAAA;AAAA,IAClE,GAAI,OAAA,CAAQ,WAAA,IAAe,KAAA,EAAA,EAAY,EAAE,WAAA,EAAa,OAAA,CAAQ,WAAW,EAAA,EAAI,CAAC;AAAA,EAChF,CAAC,CAAA;AAED,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,CAAA,EAAA,GAAM,MAAA,CAAO,UAAA,CAAW,CAAA;AAAA,IAC9B,IAAI,MAAA,CAAA,EAAS;AAAE,MAAA,OAAO,MAAA,CAAO,WAAA;AAAA,IAAa;AAAA,EAC5C,CAAA;AACF;ADlFA;AACE;AACA;AACA;AACA;AACF,+LAAC","file":"/Users/scaler/maximem_synap/synap/sdk/js/dist/grpc/index.cjs","sourcesContent":[null,"/**\n * gRPC anticipation stream: availability and loading.\n *\n * This is a SUBPATH export (`@maximem/synap-js-sdk/grpc`) and is never\n * imported by the main entry point. Three reasons, all of which have bitten\n * someone already:\n *\n * 1. `@grpc/grpc-js` plus its protos is roughly 5MB. HTTP-only and Edge users\n * should not pay for it (gotcha G-Q).\n * 2. grpc-js is built on `node:http2`, `node:net` and `node:tls`. Merely\n * importing it on Edge or Workers fails the *build*, not the call. Keeping\n * it behind a subpath plus a lazy `import()` means importing the SDK on\n * Edge stays safe.\n * 3. It is an `optionalDependency`, so it may legitimately be absent.\n *\n * ## Proto loading\n *\n * The stream is live. The proto ships as an INLINED JSON descriptor\n * (./descriptor.ts) loaded through `proto-loader.fromJSON`, not through\n * `loadSync(path)`. proto-loader's file-based path reads the `.proto` off disk\n * at runtime, which breaks under webpack/turbopack bundling and Vercel's `nft`\n * file tracing: at deploy time rather than at test time (gotcha G-P). Inlining\n * gets the same result as ts-proto codegen without a codegen toolchain.\n */\n\nimport { ListeningNotActiveError } from '../errors.js';\nexport { GrpcStreamClient } from './stream-client.js';\nexport type {\n StreamState, StreamCredentials, StreamClientOptions, ConversationEventInput,\n} from './stream-client.js';\nexport { PROTO_SHA } from './descriptor.js';\n\nexport type GrpcAvailability =\n | { available: true }\n | { available: false; reason: 'not-node' | 'module-missing'; detail: string };\n\n/**\n * Whether a gRPC stream could run here.\n *\n * Deliberately does not throw: callers use this to decide whether to offer the\n * stream at all, and a hard failure at that point is unhelpful.\n */\nexport async function checkGrpcAvailability(): Promise<GrpcAvailability> {\n const isNode =\n typeof process !== 'undefined' &&\n process.versions?.node !== undefined &&\n typeof (globalThis as { EdgeRuntime?: unknown }).EdgeRuntime === 'undefined';\n\n if (!isNode) {\n return {\n available: false,\n reason: 'not-node',\n detail:\n 'gRPC needs raw TCP and node:http2, which Edge runtimes and Workers do ' +\n 'not provide. HTTP context fetching works normally here; only the ' +\n 'anticipation stream is unavailable. Reaching Edge would require a ' +\n 'gRPC-Web or Connect endpoint on the server, which does not exist yet.',\n };\n }\n\n try {\n await import(/* @vite-ignore */ '@grpc/grpc-js');\n return { available: true };\n } catch (error) {\n return {\n available: false,\n reason: 'module-missing',\n detail:\n '@grpc/grpc-js is an optional dependency and is not installed. Run ' +\n '`npm install @grpc/grpc-js` to enable the anticipation stream. ' +\n `(${(error as Error)?.message ?? String(error)})`,\n };\n }\n}\n\nexport interface ListenOptions {\n conversationId: string;\n userId?: string;\n customerId?: string;\n onBundle?: (bundle: unknown) => void;\n}\n\nexport interface ListeningSession {\n stop(): Promise<void>;\n readonly active: boolean;\n}\n\n/**\n * Start the anticipation stream directly, without a SynapClient.\n *\n * Most callers want `client.instance.listen()` instead, which shares the\n * client's credentials and anticipation cache. This exists for the case where\n * only the stream is wanted.\n *\n * **Opt-in, and off by default.** The removed wrapper called `listen()`\n * unconditionally during init, so every user had a stream whether they asked\n * for one or not. Making it opt-in is the right default, but it is not a\n * neutral change: fewer streams means fewer anticipation hits and therefore\n * MORE billed cloud fetches for existing users. That has to be announced\n * rather than discovered (gotcha G-Y).\n */\nexport async function listen(\n options: ListenOptions & {\n apiKey?: string;\n clientId?: string;\n instanceId?: string;\n host?: string;\n port?: number;\n useTls?: boolean;\n },\n): Promise<ListeningSession> {\n if (!options.conversationId) {\n // conversation_id is not a scope tier, but the stream genuinely requires\n // one: it is what the server keys the anticipation session on.\n throw new ListeningNotActiveError('conversation_id is required to start a listening stream');\n }\n\n const availability = await checkGrpcAvailability();\n if (!availability.available) {\n throw new ListeningNotActiveError(availability.detail);\n }\n\n const [{ GrpcStreamClient: StreamClient }, { AnticipationCache }, { getEnv }] = await Promise.all([\n import('./stream-client.js'),\n import('../context/anticipation-cache.js'),\n import('../util/env.js'),\n ]);\n\n const apiKey = options.apiKey ?? getEnv('SYNAP_API_KEY') ?? '';\n if (apiKey === '') {\n throw new ListeningNotActiveError(\n 'No Synap API key found. Set SYNAP_API_KEY or pass apiKey.',\n );\n }\n\n const cache = new AnticipationCache();\n const client = new StreamClient(\n {\n apiKey,\n clientId: options.clientId ?? getEnv('SYNAP_CLIENT_ID') ?? '',\n instanceId: options.instanceId ?? getEnv('SYNAP_INSTANCE_ID') ?? '',\n },\n cache,\n {\n ...(options.host !== undefined ? { host: options.host } : {}),\n ...(options.port !== undefined ? { port: options.port } : {}),\n ...(options.useTls !== undefined ? { useTls: options.useTls } : {}),\n ...(options.onBundle !== undefined ? { onContext: options.onBundle } : {}),\n },\n );\n await client.connect();\n client.sendSessionControl({\n action: 'start',\n conversation_id: options.conversationId,\n ...(options.userId !== undefined ? { user_id: options.userId } : {}),\n ...(options.customerId !== undefined ? { customer_id: options.customerId } : {}),\n });\n\n return {\n stop: () => client.disconnect(),\n get active() { return client.isConnected; },\n };\n}\n"]}
1
+ {"version":3,"sources":["/private/tmp/claude-501/-Users-anish-maximemai-maximem-synap/364ae6d0-b8b7-4119-bfaf-7676354661c6/scratchpad/jsrel/synap/sdk/js/dist/grpc/index.cjs","../../src/grpc/index.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,yDAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B;AACA;ACkCA,MAAA,SAAsB,qBAAA,CAAA,EAAmD;AACvE,EAAA,MAAM,OAAA,EACJ,OAAO,QAAA,IAAY,YAAA,mBACnB,OAAA,mBAAQ,QAAA,6BAAU,OAAA,IAAS,KAAA,EAAA,GAC3B,OAAQ,UAAA,CAAyC,YAAA,IAAgB,WAAA;AAEnE,EAAA,GAAA,CAAI,CAAC,MAAA,EAAQ;AACX,IAAA,OAAO;AAAA,MACL,SAAA,EAAW,KAAA;AAAA,MACX,MAAA,EAAQ,UAAA;AAAA,MACR,MAAA,EACE;AAAA,IAIJ,CAAA;AAAA,EACF;AAEA,EAAA,IAAI;AACF,IAAA,MAAM,4DAAA;AAAA;AAAA,MAA0B;AAAA,IAAe,GAAA;AAC/C,IAAA,OAAO,EAAE,SAAA,EAAW,KAAK,CAAA;AAAA,EAC3B,EAAA,MAAA,CAAS,KAAA,EAAO;AACd,IAAA,OAAO;AAAA,MACL,SAAA,EAAW,KAAA;AAAA,MACX,MAAA,EAAQ,gBAAA;AAA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5C,CAAA;AACF;ADlFA;AACE;AACA;AACA;AACA;AACF,+LAAC","file":"/private/tmp/claude-501/-Users-anish-maximemai-maximem-synap/364ae6d0-b8b7-4119-bfaf-7676354661c6/scratchpad/jsrel/synap/sdk/js/dist/grpc/index.cjs","sourcesContent":[null,"/**\n * gRPC anticipation stream: availability and loading.\n *\n * This is a SUBPATH export (`@maximem/synap-js-sdk/grpc`) and is never\n * imported by the main entry point. Three reasons, all of which have bitten\n * someone already:\n *\n * 1. `@grpc/grpc-js` plus its protos is roughly 5MB. HTTP-only and Edge users\n * should not pay for it (gotcha G-Q).\n * 2. grpc-js is built on `node:http2`, `node:net` and `node:tls`. Merely\n * importing it on Edge or Workers fails the *build*, not the call. Keeping\n * it behind a subpath plus a lazy `import()` means importing the SDK on\n * Edge stays safe.\n * 3. It is an `optionalDependency`, so it may legitimately be absent.\n *\n * ## Proto loading\n *\n * The stream is live. The proto ships as an INLINED JSON descriptor\n * (./descriptor.ts) loaded through `proto-loader.fromJSON`, not through\n * `loadSync(path)`. proto-loader's file-based path reads the `.proto` off disk\n * at runtime, which breaks under webpack/turbopack bundling and Vercel's `nft`\n * file tracing: at deploy time rather than at test time (gotcha G-P). Inlining\n * gets the same result as ts-proto codegen without a codegen toolchain.\n */\n\nimport { ListeningNotActiveError } from '../errors.js';\nexport { GrpcStreamClient } from './stream-client.js';\nexport type {\n StreamState, StreamCredentials, StreamClientOptions, ConversationEventInput,\n} from './stream-client.js';\nexport { PROTO_SHA } from './descriptor.js';\n\nexport type GrpcAvailability =\n | { available: true }\n | { available: false; reason: 'not-node' | 'module-missing'; detail: string };\n\n/**\n * Whether a gRPC stream could run here.\n *\n * Deliberately does not throw: callers use this to decide whether to offer the\n * stream at all, and a hard failure at that point is unhelpful.\n */\nexport async function checkGrpcAvailability(): Promise<GrpcAvailability> {\n const isNode =\n typeof process !== 'undefined' &&\n process.versions?.node !== undefined &&\n typeof (globalThis as { EdgeRuntime?: unknown }).EdgeRuntime === 'undefined';\n\n if (!isNode) {\n return {\n available: false,\n reason: 'not-node',\n detail:\n 'gRPC needs raw TCP and node:http2, which Edge runtimes and Workers do ' +\n 'not provide. HTTP context fetching works normally here; only the ' +\n 'anticipation stream is unavailable. Reaching Edge would require a ' +\n 'gRPC-Web or Connect endpoint on the server, which does not exist yet.',\n };\n }\n\n try {\n await import(/* @vite-ignore */ '@grpc/grpc-js');\n return { available: true };\n } catch (error) {\n return {\n available: false,\n reason: 'module-missing',\n detail:\n '@grpc/grpc-js is an optional dependency and is not installed. Run ' +\n '`npm install @grpc/grpc-js` to enable the anticipation stream. ' +\n `(${(error as Error)?.message ?? String(error)})`,\n };\n }\n}\n\nexport interface ListenOptions {\n conversationId: string;\n userId?: string;\n customerId?: string;\n onBundle?: (bundle: unknown) => void;\n}\n\nexport interface ListeningSession {\n stop(): Promise<void>;\n readonly active: boolean;\n}\n\n/**\n * Start the anticipation stream directly, without a SynapClient.\n *\n * Most callers want `client.instance.listen()` instead, which shares the\n * client's credentials and anticipation cache. This exists for the case where\n * only the stream is wanted.\n *\n * **Opt-in, and off by default.** The removed wrapper called `listen()`\n * unconditionally during init, so every user had a stream whether they asked\n * for one or not. Making it opt-in is the right default, but it is not a\n * neutral change: fewer streams means fewer anticipation hits and therefore\n * MORE billed cloud fetches for existing users. That has to be announced\n * rather than discovered (gotcha G-Y).\n */\nexport async function listen(\n options: ListenOptions & {\n apiKey?: string;\n clientId?: string;\n instanceId?: string;\n host?: string;\n port?: number;\n useTls?: boolean;\n },\n): Promise<ListeningSession> {\n if (!options.conversationId) {\n // conversation_id is not a scope tier, but the stream genuinely requires\n // one: it is what the server keys the anticipation session on.\n throw new ListeningNotActiveError('conversation_id is required to start a listening stream');\n }\n\n const availability = await checkGrpcAvailability();\n if (!availability.available) {\n throw new ListeningNotActiveError(availability.detail);\n }\n\n const [{ GrpcStreamClient: StreamClient }, { AnticipationCache }, { getEnv }] = await Promise.all([\n import('./stream-client.js'),\n import('../context/anticipation-cache.js'),\n import('../util/env.js'),\n ]);\n\n const apiKey = options.apiKey ?? getEnv('SYNAP_API_KEY') ?? '';\n if (apiKey === '') {\n throw new ListeningNotActiveError(\n 'No Synap API key found. Set SYNAP_API_KEY or pass apiKey.',\n );\n }\n\n const cache = new AnticipationCache();\n const client = new StreamClient(\n {\n apiKey,\n clientId: options.clientId ?? getEnv('SYNAP_CLIENT_ID') ?? '',\n instanceId: options.instanceId ?? getEnv('SYNAP_INSTANCE_ID') ?? '',\n },\n cache,\n {\n ...(options.host !== undefined ? { host: options.host } : {}),\n ...(options.port !== undefined ? { port: options.port } : {}),\n ...(options.useTls !== undefined ? { useTls: options.useTls } : {}),\n ...(options.onBundle !== undefined ? { onContext: options.onBundle } : {}),\n },\n );\n await client.connect();\n client.sendSessionControl({\n action: 'start',\n conversation_id: options.conversationId,\n ...(options.userId !== undefined ? { user_id: options.userId } : {}),\n ...(options.customerId !== undefined ? { customer_id: options.customerId } : {}),\n });\n\n return {\n stop: () => client.disconnect(),\n get active() { return client.isConnected; },\n };\n}\n"]}
@@ -128,14 +128,14 @@ declare class GrpcStreamClient {
128
128
  *
129
129
  * Source: synap/proto/synap_service.proto
130
130
  * Generator: synap/sdk/scripts/gen_proto_descriptor.mjs
131
- * Proto SHA: c1d834043608ad4f
131
+ * Proto SHA: a0813b78a8c5d8dc
132
132
  *
133
133
  * The proto is inlined as a JSON descriptor rather than loaded from disk so
134
134
  * that bundlers and Vercel file tracing cannot lose it. Regenerate with
135
135
  * `npm run sync-behavior` in synap/sdk/js.
136
136
  */
137
137
  /** sha256 (first 16 hex chars) of the proto this descriptor was built from. */
138
- declare const PROTO_SHA = "c1d834043608ad4f";
138
+ declare const PROTO_SHA = "a0813b78a8c5d8dc";
139
139
 
140
140
  /**
141
141
  * gRPC anticipation stream: availability and loading.
@@ -128,14 +128,14 @@ declare class GrpcStreamClient {
128
128
  *
129
129
  * Source: synap/proto/synap_service.proto
130
130
  * Generator: synap/sdk/scripts/gen_proto_descriptor.mjs
131
- * Proto SHA: c1d834043608ad4f
131
+ * Proto SHA: a0813b78a8c5d8dc
132
132
  *
133
133
  * The proto is inlined as a JSON descriptor rather than loaded from disk so
134
134
  * that bundlers and Vercel file tracing cannot lose it. Regenerate with
135
135
  * `npm run sync-behavior` in synap/sdk/js.
136
136
  */
137
137
  /** sha256 (first 16 hex chars) of the proto this descriptor was built from. */
138
- declare const PROTO_SHA = "c1d834043608ad4f";
138
+ declare const PROTO_SHA = "a0813b78a8c5d8dc";
139
139
 
140
140
  /**
141
141
  * gRPC anticipation stream: availability and loading.
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  GrpcStreamClient,
3
3
  PROTO_SHA
4
- } from "../chunk-DJPYUPSV.js";
4
+ } from "../chunk-RP4YOEUN.js";
5
5
  import {
6
6
  ListeningNotActiveError
7
7
  } from "../chunk-BWMPKLFG.js";
@@ -39,7 +39,7 @@ async function listen(options) {
39
39
  throw new ListeningNotActiveError(availability.detail);
40
40
  }
41
41
  const [{ GrpcStreamClient: StreamClient }, { AnticipationCache }, { getEnv }] = await Promise.all([
42
- import("../stream-client-5CGJNTH4.js"),
42
+ import("../stream-client-Y5NFAMIH.js"),
43
43
  import("../anticipation-cache-WLU4NMD5.js"),
44
44
  import("../env-QCUKKW36.js")
45
45
  ]);
package/dist/index.cjs CHANGED
@@ -49,6 +49,7 @@ var ENDPOINTS = {
49
49
  memories_get: { method: "GET", path: "/api/v1/memories/{memory_id}", idempotent: true },
50
50
  memories_update: { method: "PATCH", path: "/api/v1/memories/{memory_id}", idempotent: false },
51
51
  memories_delete: { method: "DELETE", path: "/api/v1/memories/{memory_id}", idempotent: true },
52
+ memories_forget: { method: "POST", path: "/api/v1/memories/forget", idempotent: false },
52
53
  context_fetch_user: { method: "POST", path: "/v1/context/user/fetch", idempotent: true },
53
54
  context_fetch_customer: { method: "POST", path: "/v1/context/customer/fetch", idempotent: true },
54
55
  context_fetch_client: { method: "POST", path: "/v1/context/client/fetch", idempotent: true },
@@ -537,6 +538,7 @@ function buildFetchRequest(scope, options) {
537
538
  const maxResults = _nullishCoalesce(opt(options, "max_results", "maxResults"), () => ( 10));
538
539
  const precisionLevel = _nullishCoalesce(opt(options, "precision_level", "precisionLevel"), () => ( "high"));
539
540
  const queryDate = opt(options, "query_date", "queryDate");
541
+ const perQuery = opt(options, "max_results_per_query", "maxResultsPerQuery");
540
542
  const mode = _nullishCoalesce(options.mode, () => ( "fast"));
541
543
  if (searchQuery !== void 0 && !Array.isArray(searchQuery)) {
542
544
  throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("search_query must be an array when provided");
@@ -553,6 +555,7 @@ function buildFetchRequest(scope, options) {
553
555
  };
554
556
  if (precisionLevel !== "high") body["precision_level"] = precisionLevel;
555
557
  if (queryDate) body["query_date"] = queryDate;
558
+ if (perQuery) body["max_results_per_query"] = perQuery;
556
559
  if (options.include_conversation_context === false) {
557
560
  body["include_conversation_context"] = false;
558
561
  }
@@ -628,6 +631,10 @@ function pick(...values) {
628
631
  return pickDefined(...values);
629
632
  }
630
633
  var obj = (v) => _nullishCoalesce(v, () => ( {}));
634
+ function matchedQueries(item = {}) {
635
+ const raw = _nullishCoalesce(item["matchedQueries"], () => ( item.matched_queries));
636
+ return Array.isArray(raw) ? raw : [];
637
+ }
631
638
  function normalizeTemporalFields(item = {}) {
632
639
  return {
633
640
  eventDate: pick(item["eventDate"], item.event_date, null),
@@ -644,7 +651,8 @@ function normalizeFact(item = {}) {
644
651
  source: item.source || "",
645
652
  extractedAt: pick(item["extractedAt"], item.extracted_at, null),
646
653
  metadata: obj(item.metadata),
647
- ...normalizeTemporalFields(item)
654
+ ...normalizeTemporalFields(item),
655
+ matchedQueries: matchedQueries(item)
648
656
  };
649
657
  }
650
658
  function normalizePreference(item = {}) {
@@ -656,7 +664,8 @@ function normalizePreference(item = {}) {
656
664
  source: item.source || "",
657
665
  extractedAt: pick(item["extractedAt"], item.extracted_at, null),
658
666
  metadata: obj(item.metadata),
659
- ...normalizeTemporalFields(item)
667
+ ...normalizeTemporalFields(item),
668
+ matchedQueries: matchedQueries(item)
660
669
  };
661
670
  }
662
671
  function normalizeEpisode(item = {}) {
@@ -667,7 +676,8 @@ function normalizeEpisode(item = {}) {
667
676
  significance: pick(item["significance"], item.confidence, 0),
668
677
  participants: item["participants"] || [],
669
678
  metadata: obj(item.metadata),
670
- ...normalizeTemporalFields(item)
679
+ ...normalizeTemporalFields(item),
680
+ matchedQueries: matchedQueries(item)
671
681
  };
672
682
  }
673
683
  function normalizeEmotion(item = {}) {
@@ -678,7 +688,8 @@ function normalizeEmotion(item = {}) {
678
688
  detectedAt: pick(item["detectedAt"], item["detected_at"], null),
679
689
  context: item["context"] || "",
680
690
  metadata: obj(item.metadata),
681
- ...normalizeTemporalFields(item)
691
+ ...normalizeTemporalFields(item),
692
+ matchedQueries: matchedQueries(item)
682
693
  };
683
694
  }
684
695
  function normalizeTemporalEvent(item = {}) {
@@ -692,7 +703,8 @@ function normalizeTemporalEvent(item = {}) {
692
703
  confidence: pick(item.confidence, 0),
693
704
  source: item.source || "",
694
705
  extractedAt: pick(item["extractedAt"], item.extracted_at, null),
695
- metadata: obj(item.metadata)
706
+ metadata: obj(item.metadata),
707
+ matchedQueries: matchedQueries(item)
696
708
  };
697
709
  }
698
710
  function normalizeContextMetadata(metadata = {}) {
@@ -866,8 +878,33 @@ function buildCreateBody(options) {
866
878
  metadata: _nullishCoalesce(options.metadata, () => ( {}))
867
879
  };
868
880
  }
881
+ var FORGET_MODES = ["preview", "direct"];
882
+ var FORGET_DESCRIPTION_MIN = 3;
883
+ var FORGET_DESCRIPTION_MAX = 500;
884
+ function buildForgetBody(options) {
885
+ const description = options.description;
886
+ if (typeof description !== "string" || description.length < FORGET_DESCRIPTION_MIN || description.length > FORGET_DESCRIPTION_MAX) {
887
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)(
888
+ `description must be between ${FORGET_DESCRIPTION_MIN} and ${FORGET_DESCRIPTION_MAX} characters`
889
+ );
890
+ }
891
+ const mode = _nullishCoalesce(options.mode, () => ( "preview"));
892
+ if (!FORGET_MODES.includes(mode)) {
893
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)(
894
+ `Invalid mode '${mode}'. Expected one of: ${FORGET_MODES.join(", ")}`
895
+ );
896
+ }
897
+ const o2 = options;
898
+ return {
899
+ description,
900
+ user_id: _nullishCoalesce(either(o2, "user_id", "userId"), () => ( null)),
901
+ customer_id: _nullishCoalesce(either(o2, "customer_id", "customerId"), () => ( null)),
902
+ scope: _nullishCoalesce(options.scope, () => ( null)),
903
+ mode
904
+ };
905
+ }
869
906
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "error", "cancelled"]);
870
- function createMemoriesInterface(transport) {
907
+ function createMemoriesInterface(transport, onForgotten) {
871
908
  return {
872
909
  async create(options) {
873
910
  const o2 = options;
@@ -953,6 +990,23 @@ function createMemoriesInterface(transport) {
953
990
  }
954
991
  return transport.request("memories_delete", { pathParams: { memory_id: memoryId } });
955
992
  },
993
+ async forget(options) {
994
+ const o2 = options;
995
+ transport.checkCustomerId(_nullishCoalesce(o2["customer_id"], () => ( o2["customerId"])), "memories.forget");
996
+ const body = buildForgetBody(options);
997
+ const result = await transport.request("memories_forget", { body });
998
+ const removed = !!_optionalChain([result, 'optionalAccess', _33 => _33.deleted_ids, 'optionalAccess', _34 => _34.length]) || _optionalChain([result, 'optionalAccess', _35 => _35.status]) === "deleted" || _optionalChain([result, 'optionalAccess', _36 => _36.status]) === "partial";
999
+ if (removed && onForgotten) {
1000
+ try {
1001
+ onForgotten({
1002
+ userId: _nullishCoalesce(body["user_id"], () => ( null)),
1003
+ customerId: _nullishCoalesce(body["customer_id"], () => ( null))
1004
+ });
1005
+ } catch (e5) {
1006
+ }
1007
+ }
1008
+ return result;
1009
+ },
956
1010
  async status(ingestionId) {
957
1011
  if (!ingestionId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("ingestion_id is required");
958
1012
  return transport.request("memories_status", {
@@ -981,14 +1035,14 @@ function sleep2(ms, signal) {
981
1035
  if (ms <= 0) return Promise.resolve();
982
1036
  return new Promise((resolve, reject) => {
983
1037
  const timer = setTimeout(() => {
984
- _optionalChain([signal, 'optionalAccess', _33 => _33.removeEventListener, 'call', _34 => _34("abort", onAbort)]);
1038
+ _optionalChain([signal, 'optionalAccess', _37 => _37.removeEventListener, 'call', _38 => _38("abort", onAbort)]);
985
1039
  resolve();
986
1040
  }, ms);
987
1041
  function onAbort() {
988
1042
  clearTimeout(timer);
989
- reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _35 => _35.reason]), () => ( new Error("Aborted"))));
1043
+ reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _39 => _39.reason]), () => ( new Error("Aborted"))));
990
1044
  }
991
- _optionalChain([signal, 'optionalAccess', _36 => _36.addEventListener, 'call', _37 => _37("abort", onAbort, { once: true })]);
1045
+ _optionalChain([signal, 'optionalAccess', _40 => _40.addEventListener, 'call', _41 => _41("abort", onAbort, { once: true })]);
992
1046
  });
993
1047
  }
994
1048
 
@@ -1227,7 +1281,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1227
1281
  pathParams: { conversation_id: id },
1228
1282
  query: { style: _nullishCoalesce(options.style, () => ( "structured")) }
1229
1283
  });
1230
- return _nullishCoalesce(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _38 => _38["context_for_prompt"]]), () => ( result)), () => ( {}));
1284
+ return _nullishCoalesce(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _42 => _42["context_for_prompt"]]), () => ( result)), () => ( {}));
1231
1285
  },
1232
1286
  async compact(options) {
1233
1287
  return transport.request("conversations_compact", { body: buildCompactBody(options) });
@@ -1402,10 +1456,10 @@ function jsonOrText(value) {
1402
1456
  (_k, v) => typeof v === "bigint" ? String(v) : v
1403
1457
  );
1404
1458
  return out === void 0 ? String(value) : out;
1405
- } catch (e5) {
1459
+ } catch (e6) {
1406
1460
  try {
1407
1461
  return String(value);
1408
- } catch (e6) {
1462
+ } catch (e7) {
1409
1463
  return "";
1410
1464
  }
1411
1465
  }
@@ -1417,17 +1471,17 @@ function createInstanceNamespace(credentials, cache, onTurn) {
1417
1471
  let applyCompaction = null;
1418
1472
  const internals = {
1419
1473
  onCompactionUpdate(conversationId, bundle) {
1420
- _optionalChain([applyCompaction, 'optionalCall', _39 => _39(bundle)]);
1421
- _optionalChain([dispatchCompaction, 'optionalCall', _40 => _40(conversationId, bundle)]);
1474
+ _optionalChain([applyCompaction, 'optionalCall', _43 => _43(bundle)]);
1475
+ _optionalChain([dispatchCompaction, 'optionalCall', _44 => _44(conversationId, bundle)]);
1422
1476
  },
1423
1477
  setCompactionApplier(apply) {
1424
1478
  applyCompaction = apply;
1425
1479
  },
1426
1480
  sendContextUsed(event) {
1427
- _optionalChain([client, 'optionalAccess', _41 => _41.sendContextUsed, 'call', _42 => _42(event)]);
1481
+ _optionalChain([client, 'optionalAccess', _45 => _45.sendContextUsed, 'call', _46 => _46(event)]);
1428
1482
  },
1429
1483
  sendContextAssembled(event) {
1430
- _optionalChain([client, 'optionalAccess', _43 => _43.sendContextAssembled, 'call', _44 => _44(event)]);
1484
+ _optionalChain([client, 'optionalAccess', _47 => _47.sendContextAssembled, 'call', _48 => _48(event)]);
1431
1485
  },
1432
1486
  setCompactionDispatcher(dispatch) {
1433
1487
  dispatchCompaction = dispatch;
@@ -1449,7 +1503,7 @@ function createInstanceNamespace(credentials, cache, onTurn) {
1449
1503
  ...customerId ? { customer_id: customerId } : {}
1450
1504
  });
1451
1505
  openSessions.set(conversationId, sessionId);
1452
- } catch (e7) {
1506
+ } catch (e8) {
1453
1507
  }
1454
1508
  }
1455
1509
  const namespace = {
@@ -1457,7 +1511,7 @@ function createInstanceNamespace(credentials, cache, onTurn) {
1457
1511
  if (client !== null) {
1458
1512
  throw new (0, _chunkT372OL3Qcjs.ListeningAlreadyActiveError)("Listening is already active on this instance");
1459
1513
  }
1460
- const { GrpcStreamClient } = await Promise.resolve().then(() => _interopRequireWildcard(require("./stream-client-GJM4YSXW.cjs")));
1514
+ const { GrpcStreamClient } = await Promise.resolve().then(() => _interopRequireWildcard(require("./stream-client-A6IO6E47.cjs")));
1461
1515
  const onContext = _nullishCoalesce(options.on_context, () => ( options.onContext));
1462
1516
  const onDisconnect = _nullishCoalesce(options.on_disconnect, () => ( options.onDisconnect));
1463
1517
  const onReconnect = _nullishCoalesce(options.on_reconnect, () => ( options.onReconnect));
@@ -1475,11 +1529,11 @@ function createInstanceNamespace(credentials, cache, onTurn) {
1475
1529
  if (state !== "connected") openSessions.clear();
1476
1530
  if (state === "reconnecting") {
1477
1531
  reconnectAttempts += 1;
1478
- _optionalChain([onReconnect, 'optionalCall', _45 => _45(reconnectAttempts)]);
1532
+ _optionalChain([onReconnect, 'optionalCall', _49 => _49(reconnectAttempts)]);
1479
1533
  } else if (state === "disconnected") {
1480
- const stopped = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _46 => _46.lastError]), () => ( null));
1534
+ const stopped = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _50 => _50.lastError]), () => ( null));
1481
1535
  const reason = stopped === null ? "stream disconnected" : `credit_stop:${_nullishCoalesce(stopped.reason, () => ( "unknown"))}`;
1482
- _optionalChain([onDisconnect, 'optionalCall', _47 => _47(reason)]);
1536
+ _optionalChain([onDisconnect, 'optionalCall', _51 => _51(reason)]);
1483
1537
  }
1484
1538
  }
1485
1539
  });
@@ -1489,7 +1543,7 @@ function createInstanceNamespace(credentials, cache, onTurn) {
1489
1543
  } catch (error) {
1490
1544
  if (error instanceof _chunkT372OL3Qcjs.SynapError) throw error;
1491
1545
  throw new (0, _chunkT372OL3Qcjs.SynapError)(
1492
- `Could not open the Synap anticipation stream: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _48 => _48.message]), () => ( String(error)))}`,
1546
+ `Could not open the Synap anticipation stream: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _52 => _52.message]), () => ( String(error)))}`,
1493
1547
  { cause: error }
1494
1548
  );
1495
1549
  }
@@ -1514,7 +1568,7 @@ function createInstanceNamespace(credentials, cache, onTurn) {
1514
1568
  session_id: sessionId,
1515
1569
  conversation_id: conversationId
1516
1570
  });
1517
- } catch (e8) {
1571
+ } catch (e9) {
1518
1572
  }
1519
1573
  },
1520
1574
  async send_message(options) {
@@ -1535,7 +1589,7 @@ function createInstanceNamespace(credentials, cache, onTurn) {
1535
1589
  _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( ""))
1536
1590
  );
1537
1591
  if (eventType === "user_message" || eventType === "assistant_message") {
1538
- _optionalChain([onTurn, 'optionalCall', _49 => _49({
1592
+ _optionalChain([onTurn, 'optionalCall', _53 => _53({
1539
1593
  conversationId,
1540
1594
  role: _nullishCoalesce(options.role, () => ( "user")),
1541
1595
  content: options.content
@@ -1629,7 +1683,7 @@ function createInstanceNamespace(credentials, cache, onTurn) {
1629
1683
  }
1630
1684
 
1631
1685
  // src/version.ts
1632
- var SDK_VERSION = "0.5.4";
1686
+ var SDK_VERSION = "0.5.6";
1633
1687
 
1634
1688
  // src/registry.ts
1635
1689
  var instances = /* @__PURE__ */ new Map();
@@ -1841,7 +1895,7 @@ function overlayLocalRecentTurns(response, store, conversationId, configured) {
1841
1895
  compacted_at: orLocal("compacted_at", entry.compactedAt),
1842
1896
  conversation_id: conversationId
1843
1897
  };
1844
- } catch (e9) {
1898
+ } catch (e10) {
1845
1899
  }
1846
1900
  }
1847
1901
 
@@ -1854,7 +1908,7 @@ function stringify(value) {
1854
1908
  if (t === "string" || t === "number" || t === "boolean") return String(value);
1855
1909
  try {
1856
1910
  return _nullishCoalesce(JSON.stringify(value), () => ( ""));
1857
- } catch (e10) {
1911
+ } catch (e11) {
1858
1912
  return String(value);
1859
1913
  }
1860
1914
  }
@@ -2128,10 +2182,14 @@ function tryServeFromCache(cache, scope, params, maxItems) {
2128
2182
  });
2129
2183
  if (hit === null) return { response: null, hit: null };
2130
2184
  return { response: buildAnticipationResponse(hit), hit };
2131
- } catch (e11) {
2185
+ } catch (e12) {
2132
2186
  return { response: null, hit: null };
2133
2187
  }
2134
2188
  }
2189
+ function distinctQueryCount(searchQuery) {
2190
+ if (!Array.isArray(searchQuery)) return 0;
2191
+ return new Set(searchQuery.filter((q) => typeof q === "string" && q.length > 0)).size;
2192
+ }
2135
2193
 
2136
2194
  // src/context/assembled.ts
2137
2195
  var COLLECTIONS2 = ["facts", "preferences", "episodes", "emotions", "temporal_events"];
@@ -2629,6 +2687,7 @@ var SynapClient = class {
2629
2687
  beforeFetch: (scope, options2) => {
2630
2688
  const o2 = options2;
2631
2689
  if (_nullishCoalesce(o2["query_date"], () => ( o2["queryDate"]))) return null;
2690
+ if (_nullishCoalesce(o2["max_results_per_query"], () => ( o2["maxResultsPerQuery"]))) return null;
2632
2691
  const attempt = tryServeFromCache(
2633
2692
  this.#anticipationCache,
2634
2693
  scope,
@@ -2699,7 +2758,11 @@ var SynapClient = class {
2699
2758
  compacted: (conversationId, format) => this.#localCompacted(conversationId, format)
2700
2759
  }
2701
2760
  );
2702
- this.memories = createMemoriesInterface(this.#transport);
2761
+ this.memories = createMemoriesInterface(this.#transport, ({ userId, customerId }) => {
2762
+ for (const id of /* @__PURE__ */ new Set([userId, customerId])) {
2763
+ if (id) this.#anticipationCache.dropEntity(id);
2764
+ }
2765
+ });
2703
2766
  this.credits = createCreditsNamespace(this.#transport);
2704
2767
  this.cache = createCacheNamespace(this.#anticipationCache);
2705
2768
  this.instance = createInstanceNamespace(
@@ -2829,7 +2892,7 @@ var SynapClient = class {
2829
2892
  this.#registryKeys.push(resolvedInstanceId);
2830
2893
  }
2831
2894
  }
2832
- } catch (e12) {
2895
+ } catch (e13) {
2833
2896
  }
2834
2897
  }
2835
2898
  /**
@@ -2898,6 +2961,7 @@ var SynapClient = class {
2898
2961
  mode = "fast",
2899
2962
  precision_level: precisionLevel = "high",
2900
2963
  query_date: queryDate,
2964
+ max_results_per_query: maxResultsPerQuery,
2901
2965
  include_conversation_context: includeConversationContext = true,
2902
2966
  scopes,
2903
2967
  include_scope_labels: includeScopeLabels = false,
@@ -2916,7 +2980,8 @@ var SynapClient = class {
2916
2980
  // In `shared` so it reaches all four branches at once. The Python edit
2917
2981
  // threaded three call sites by hand and missed the client branch, which
2918
2982
  // sits one indent deeper; spreading removes that whole class of miss.
2919
- query_date: queryDate
2983
+ query_date: queryDate,
2984
+ max_results_per_query: maxResultsPerQuery
2920
2985
  };
2921
2986
  const labels = [];
2922
2987
  const tasks = [];
@@ -2981,7 +3046,7 @@ var SynapClient = class {
2981
3046
  merged.conversation_context = await this.conversation.context.get_context_for_prompt({
2982
3047
  conversation_id: conversationId
2983
3048
  });
2984
- } catch (e13) {
3049
+ } catch (e14) {
2985
3050
  }
2986
3051
  }
2987
3052
  merged.formatted_context = formatForPrompt(merged, {
@@ -3026,9 +3091,14 @@ var SynapClient = class {
3026
3091
  served_item_ids: served.servedItemIds,
3027
3092
  scope,
3028
3093
  source_bundle_ids: served.bundleId ? [served.bundleId] : [],
3029
- timestamp_ms: Date.now()
3094
+ timestamp_ms: Date.now(),
3095
+ // How many distinct search queries the fetch carried. A hit never
3096
+ // reaches the fetch route, so this event is how the server learns it
3097
+ // happened and what it is charged by. The count only: this event must
3098
+ // not carry the caller's words.
3099
+ query_count: distinctQueryCount(_nullishCoalesce(options["search_query"], () => ( options["searchQuery"])))
3030
3100
  });
3031
- } catch (e14) {
3101
+ } catch (e15) {
3032
3102
  }
3033
3103
  }
3034
3104
  /**
@@ -3053,7 +3123,7 @@ var SynapClient = class {
3053
3123
  }),
3054
3124
  scope
3055
3125
  });
3056
- } catch (e15) {
3126
+ } catch (e16) {
3057
3127
  }
3058
3128
  }
3059
3129
  /**
@@ -3131,7 +3201,7 @@ function pick3(o2, snake, camel) {
3131
3201
  function resolveBaseUrl(options) {
3132
3202
  const explicit = _nullishCoalesce(options.baseUrl, () => ( options.api_base_url));
3133
3203
  if (explicit !== void 0) return explicit;
3134
- const fromEnv = _optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_BASE_URL"), 'optionalAccess', _50 => _50.trim, 'call', _51 => _51()]);
3204
+ const fromEnv = _optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_BASE_URL"), 'optionalAccess', _54 => _54.trim, 'call', _55 => _55()]);
3135
3205
  return fromEnv !== void 0 && fromEnv !== "" ? fromEnv : void 0;
3136
3206
  }
3137
3207
  function resolveCredentials(options) {
@@ -3198,5 +3268,6 @@ function resolveCredentials(options) {
3198
3268
 
3199
3269
 
3200
3270
 
3201
- exports.ANY_SCOPE = _chunkT6U5PVADcjs.ANY_SCOPE; exports.AgentUnavailableError = _chunkT372OL3Qcjs.AgentUnavailableError; exports.AnticipationCache = _chunkT6U5PVADcjs.AnticipationCache; exports.AuthenticationError = _chunkT372OL3Qcjs.AuthenticationError; exports.BM25 = _chunkT6U5PVADcjs.BM25; exports.COMPACTION_LEVELS = COMPACTION_LEVELS; exports.CONTRACT = _chunkT6U5PVADcjs.CONTRACT; exports.ConflictError = _chunkT372OL3Qcjs.ConflictError; exports.ConnectionError = _chunkT372OL3Qcjs.ConnectionError; exports.ContextNotFoundError = _chunkT372OL3Qcjs.ContextNotFoundError; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL; exports.DEFAULT_DOCUMENT_TYPE = DEFAULT_DOCUMENT_TYPE; exports.DEFAULT_INGEST_MODE = DEFAULT_INGEST_MODE; exports.DEFAULT_RETRY_POLICY = DEFAULT_RETRY_POLICY; exports.DEFAULT_TIMEOUTS = DEFAULT_TIMEOUTS; exports.DOCUMENT_TYPES = DOCUMENT_TYPES; exports.ENDPOINTS = ENDPOINTS; exports.HttpTransport = HttpTransport; exports.INGEST_MODES = INGEST_MODES; exports.ITEM_COLLECTIONS = ITEM_COLLECTIONS; exports.InsufficientCreditsError = _chunkT372OL3Qcjs.InsufficientCreditsError; exports.InvalidConversationIdError = _chunkT372OL3Qcjs.InvalidConversationIdError; exports.InvalidInputError = _chunkT372OL3Qcjs.InvalidInputError; exports.InvalidInstanceIdError = _chunkT372OL3Qcjs.InvalidInstanceIdError; exports.ListeningAlreadyActiveError = _chunkT372OL3Qcjs.ListeningAlreadyActiveError; exports.ListeningNotActiveError = _chunkT372OL3Qcjs.ListeningNotActiveError; exports.NetworkTimeoutError = _chunkT372OL3Qcjs.NetworkTimeoutError; exports.PermanentError = _chunkT372OL3Qcjs.PermanentError; exports.RateLimitError = _chunkT372OL3Qcjs.RateLimitError; exports.SDKError = _chunkT372OL3Qcjs.SDKError; exports.SDK_VERSION = SDK_VERSION; exports.ServiceUnavailableError = _chunkT372OL3Qcjs.ServiceUnavailableError; exports.SessionExpiredError = _chunkT372OL3Qcjs.SessionExpiredError; exports.SynapClient = SynapClient; exports.SynapError = _chunkT372OL3Qcjs.SynapError; exports.SynapPermanentError = _chunkT372OL3Qcjs.SynapPermanentError; exports.SynapTransientError = _chunkT372OL3Qcjs.SynapTransientError; exports.THRESHOLDS = _chunkT6U5PVADcjs.THRESHOLDS; exports.TranscriptConflictError = _chunkT372OL3Qcjs.TranscriptConflictError; exports.TransientError = _chunkT372OL3Qcjs.TransientError; exports.flattenContextItems = flattenContextItems; exports.formatForPrompt = formatForPrompt; exports.isOutcomeUnknown = isOutcomeUnknown; exports.isRecallQuery = _chunkT6U5PVADcjs.isRecallQuery; exports.isSynapError = _chunkT372OL3Qcjs.isSynapError; exports.mergeScopeResults = mergeScopeResults; exports.resolvePath = resolvePath; exports.shouldRetry = shouldRetry; exports.stem = _chunkT6U5PVADcjs.stem; exports.tokenize = _chunkT6U5PVADcjs.tokenize;
3271
+
3272
+ exports.ANY_SCOPE = _chunkT6U5PVADcjs.ANY_SCOPE; exports.AgentUnavailableError = _chunkT372OL3Qcjs.AgentUnavailableError; exports.AnticipationCache = _chunkT6U5PVADcjs.AnticipationCache; exports.AuthenticationError = _chunkT372OL3Qcjs.AuthenticationError; exports.BM25 = _chunkT6U5PVADcjs.BM25; exports.COMPACTION_LEVELS = COMPACTION_LEVELS; exports.CONTRACT = _chunkT6U5PVADcjs.CONTRACT; exports.ConflictError = _chunkT372OL3Qcjs.ConflictError; exports.ConnectionError = _chunkT372OL3Qcjs.ConnectionError; exports.ContextNotFoundError = _chunkT372OL3Qcjs.ContextNotFoundError; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL; exports.DEFAULT_DOCUMENT_TYPE = DEFAULT_DOCUMENT_TYPE; exports.DEFAULT_INGEST_MODE = DEFAULT_INGEST_MODE; exports.DEFAULT_RETRY_POLICY = DEFAULT_RETRY_POLICY; exports.DEFAULT_TIMEOUTS = DEFAULT_TIMEOUTS; exports.DOCUMENT_TYPES = DOCUMENT_TYPES; exports.ENDPOINTS = ENDPOINTS; exports.FORGET_MODES = FORGET_MODES; exports.HttpTransport = HttpTransport; exports.INGEST_MODES = INGEST_MODES; exports.ITEM_COLLECTIONS = ITEM_COLLECTIONS; exports.InsufficientCreditsError = _chunkT372OL3Qcjs.InsufficientCreditsError; exports.InvalidConversationIdError = _chunkT372OL3Qcjs.InvalidConversationIdError; exports.InvalidInputError = _chunkT372OL3Qcjs.InvalidInputError; exports.InvalidInstanceIdError = _chunkT372OL3Qcjs.InvalidInstanceIdError; exports.ListeningAlreadyActiveError = _chunkT372OL3Qcjs.ListeningAlreadyActiveError; exports.ListeningNotActiveError = _chunkT372OL3Qcjs.ListeningNotActiveError; exports.NetworkTimeoutError = _chunkT372OL3Qcjs.NetworkTimeoutError; exports.PermanentError = _chunkT372OL3Qcjs.PermanentError; exports.RateLimitError = _chunkT372OL3Qcjs.RateLimitError; exports.SDKError = _chunkT372OL3Qcjs.SDKError; exports.SDK_VERSION = SDK_VERSION; exports.ServiceUnavailableError = _chunkT372OL3Qcjs.ServiceUnavailableError; exports.SessionExpiredError = _chunkT372OL3Qcjs.SessionExpiredError; exports.SynapClient = SynapClient; exports.SynapError = _chunkT372OL3Qcjs.SynapError; exports.SynapPermanentError = _chunkT372OL3Qcjs.SynapPermanentError; exports.SynapTransientError = _chunkT372OL3Qcjs.SynapTransientError; exports.THRESHOLDS = _chunkT6U5PVADcjs.THRESHOLDS; exports.TranscriptConflictError = _chunkT372OL3Qcjs.TranscriptConflictError; exports.TransientError = _chunkT372OL3Qcjs.TransientError; exports.flattenContextItems = flattenContextItems; exports.formatForPrompt = formatForPrompt; exports.isOutcomeUnknown = isOutcomeUnknown; exports.isRecallQuery = _chunkT6U5PVADcjs.isRecallQuery; exports.isSynapError = _chunkT372OL3Qcjs.isSynapError; exports.mergeScopeResults = mergeScopeResults; exports.resolvePath = resolvePath; exports.shouldRetry = shouldRetry; exports.stem = _chunkT6U5PVADcjs.stem; exports.tokenize = _chunkT6U5PVADcjs.tokenize;
3202
3273
  //# sourceMappingURL=index.cjs.map