@maximem/synap-js-sdk 0.6.8 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/anticipation-cache-Q7IYC3ID.cjs.map +1 -1
- package/dist/{chunk-DEFC7NHQ.js → chunk-BMA3HZEX.js} +6 -1
- package/dist/chunk-BMA3HZEX.js.map +1 -0
- package/dist/chunk-BYUGILQI.cjs.map +1 -1
- package/dist/{chunk-7IZHVYO2.cjs → chunk-JPDEKN5M.cjs} +28 -23
- package/dist/chunk-JPDEKN5M.cjs.map +1 -0
- package/dist/{chunk-YUCHB2YK.js → chunk-RKKTOLXP.js} +2 -2
- package/dist/{chunk-EI4AGILN.cjs → chunk-SAKMZI7G.cjs} +6 -6
- package/dist/chunk-SAKMZI7G.cjs.map +1 -0
- package/dist/chunk-ZKOJDUN4.cjs.map +1 -1
- package/dist/env-55ULHNJZ.cjs.map +1 -1
- package/dist/{errors-x5bpgxmC.d.ts → errors-DEJFTN6v.d.cts} +9 -2
- package/dist/{errors-x5bpgxmC.d.cts → errors-DEJFTN6v.d.ts} +9 -2
- package/dist/grpc/index.cjs +7 -7
- package/dist/grpc/index.cjs.map +1 -1
- package/dist/grpc/index.d.cts +1 -1
- package/dist/grpc/index.d.ts +1 -1
- package/dist/grpc/index.js +3 -3
- package/dist/index.cjs +710 -235
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +200 -4
- package/dist/index.d.ts +200 -4
- package/dist/index.js +486 -11
- package/dist/index.js.map +1 -1
- package/dist/onnx-encoder-4RSL6ID4.cjs.map +1 -1
- package/dist/{stream-client-Q2RR5SCS.js → stream-client-7A2DQ3H3.js} +3 -3
- package/dist/stream-client-H2ES74FF.cjs +22 -0
- package/dist/stream-client-H2ES74FF.cjs.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-7IZHVYO2.cjs.map +0 -1
- package/dist/chunk-DEFC7NHQ.js.map +0 -1
- package/dist/chunk-EI4AGILN.cjs.map +0 -1
- package/dist/stream-client-TDHTS7F4.cjs +0 -22
- package/dist/stream-client-TDHTS7F4.cjs.map +0 -1
- /package/dist/{chunk-YUCHB2YK.js.map → chunk-RKKTOLXP.js.map} +0 -0
- /package/dist/{stream-client-Q2RR5SCS.js.map → stream-client-7A2DQ3H3.js.map} +0 -0
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/scaler/maximem_synap_npm_publish/synap/sdk/js/dist/index.cjs","../src/local-mode.ts","../src/transport/endpoints.ts","../src/transport/retry.ts","../src/transport/keepalive.ts","../src/scoping.ts","../src/transport/http.ts","../src/context/ranked.ts","../src/context/no-query.ts","../src/context/fetch.ts","../src/context/normalize.ts","../src/context/flatten.ts","../src/memories/parts.ts","../src/memories/interface.ts","../src/util/validators.ts","../src/agent-model.ts","../src/conversation/interface.ts","../src/data/interface.ts","../src/user/interface.ts","../src/credits/interface.ts","../src/cache/interface.ts","../src/instance/interface.ts","../src/version.ts","../src/registry.ts","../src/cache/short-term-store.ts","../src/cache/turn-store.ts","../src/cache/history-search.ts","../src/context/overlay.ts","../src/context/local-prompt.ts","../src/context/user-summary.ts","../src/context/anticipated.ts","../src/context/assembled.ts","../src/context/unified.ts","../src/tool/as-tool.ts","../src/client.ts"],"names":["response","dt","list","checkCustomerId","n","s","j","options"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACrCO,SAAS,WAAA,CAAY,MAAA,EAA4B,OAAA,EAAsC;AAC5F,EAAA,GAAA,CAAI,OAAA,GAAU,sCAAA,eAAsB,CAAA,EAAG,OAAO,KAAA;AAC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AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/scaler/maximem_synap_npm_publish/synap/sdk/js/dist/index.cjs","sourcesContent":[null,"/**\n * Local mode: talking to the open-source Synap server, which has no auth.\n *\n * It is on when no API key is given (option or SYNAP_API_KEY) and a base URL\n * is configured. A key always wins, so Cloud callers never see a difference.\n */\nimport { getEnv } from './util/env.js';\n\nexport function isLocalMode(apiKey: string | undefined, baseUrl: string | undefined): boolean {\n if (apiKey || getEnv('SYNAP_API_KEY')) return false;\n return baseUrl !== undefined && baseUrl.trim() !== '';\n}\n\n/**\n * The optional shared token the open-source server may require. Read from the\n * environment only. Empty means send no Authorization header.\n */\nexport function localToken(): string {\n return getEnv('SYNAP_API_TOKEN')?.trim() ?? '';\n}\n","/**\n * AUTOGENERATED FROM synap/sdk/CONTRACT/endpoints.yaml -- DO NOT EDIT.\n * Regenerate with synap/sdk/scripts/sync-contract.sh.\n *\n * The /api/v1 vs /v1 prefix split is intentional and load-bearing. See the\n * contract file: normalising it 404s every affected call in production.\n */\n\nexport interface EndpointSpec {\n readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';\n readonly path: string;\n /**\n * Whether a retry after an ambiguous failure is safe.\n *\n * False here means a retry can double-ingest and therefore double-bill.\n * See defect D / gotcha G-L in the migration plan.\n */\n readonly idempotent: boolean;\n}\n\nexport const ENDPOINTS = {\n whoami: { method: \"GET\", path: \"/api/v1/auth/whoami\", idempotent: true },\n memories_create: { method: \"POST\", path: \"/api/v1/memories/create\", idempotent: false },\n memories_batch: { method: \"POST\", path: \"/api/v1/memories/batch\", idempotent: false },\n memories_upload: { method: \"POST\", path: \"/api/v1/memories/upload\", idempotent: false },\n memories_create_multipart: { method: \"POST\", path: \"/api/v1/memories/create-multipart\", idempotent: false },\n memories_status: { method: \"GET\", path: \"/api/v1/memories/status/{ingestion_id}\", idempotent: true },\n memories_get: { method: \"GET\", path: \"/api/v1/memories/{memory_id}\", idempotent: true },\n memories_update: { method: \"PATCH\", path: \"/api/v1/memories/{memory_id}\", idempotent: false },\n memories_delete: { method: \"DELETE\", path: \"/api/v1/memories/{memory_id}\", idempotent: true },\n memories_forget: { method: \"POST\", path: \"/api/v1/memories/forget\", idempotent: false },\n data_delete: { method: \"POST\", path: \"/v1/data/delete\", idempotent: true },\n data_delete_status: { method: \"GET\", path: \"/v1/data/delete/{deletion_id}\", idempotent: true },\n context_fetch_user: { method: \"POST\", path: \"/v1/context/user/fetch\", idempotent: true },\n context_fetch_customer: { method: \"POST\", path: \"/v1/context/customer/fetch\", idempotent: true },\n context_fetch_client: { method: \"POST\", path: \"/v1/context/client/fetch\", idempotent: true },\n context_fetch_conversation: { method: \"POST\", path: \"/v1/context/conversation/fetch\", idempotent: true },\n context_for_prompt: { method: \"GET\", path: \"/v1/conversations/{conversation_id}/context-for-prompt\", idempotent: true },\n conversation_turns: { method: \"GET\", path: \"/v1/conversations/{conversation_id}/messages\", idempotent: true },\n conversations_ingest: { method: \"POST\", path: \"/v1/conversations/ingest\", idempotent: false },\n conversations_messages: { method: \"POST\", path: \"/v1/conversations/messages\", idempotent: false },\n conversations_messages_batch: { method: \"POST\", path: \"/v1/conversations/messages/batch\", idempotent: false },\n conversations_compact: { method: \"POST\", path: \"/v1/conversations/compact\", idempotent: false },\n conversations_compacted: { method: \"GET\", path: \"/v1/conversations/{conversation_id}/compacted\", idempotent: true },\n conversations_compaction_status: { method: \"GET\", path: \"/v1/conversations/{conversation_id}/compaction/status\", idempotent: true },\n user_profile: { method: \"GET\", path: \"/v1/users/{user_id}/profile\", idempotent: true },\n credits_balance: { method: \"GET\", path: \"/v1/credits/balance\", idempotent: true },\n credits_ledger: { method: \"GET\", path: \"/v1/credits/ledger\", idempotent: true },\n credits_estimate: { method: \"POST\", path: \"/v1/credits/estimate\", idempotent: true },\n credits_redeem: { method: \"POST\", path: \"/v1/credits/redeem\", idempotent: false },\n telemetry_batch: { method: \"POST\", path: \"/v1/telemetry/batch\", idempotent: false },\n} as const satisfies Record<string, EndpointSpec>;\n\nexport type EndpointName = keyof typeof ENDPOINTS;\n\n/** Substitute `{placeholder}` segments. Values are URL-encoded.\n *\n * Encoding matters: an unencoded id containing `/` or `?` silently\n * retargets the request at a different route.\n */\nexport function resolvePath(\n name: EndpointName,\n params: Readonly<Record<string, string | number>> = {},\n): string {\n return ENDPOINTS[name].path.replace(/\\{(\\w+)\\}/g, (_m, key: string) => {\n const value = params[key];\n if (value === undefined || value === null || value === '') {\n throw new Error(\n `Endpoint ${name} requires path parameter '${key}'.`,\n );\n }\n return encodeURIComponent(String(value));\n });\n}\n","/**\n * Retry policy, mirroring `maximem_synap/resilience/retry.py` plus the\n * idempotency gate added there for defect D.\n *\n * ## Why idempotency is part of the retry decision\n *\n * The obvious retry rule is \"retry transient errors\". That rule double-bills.\n *\n * `POST /api/v1/memories/create` is metered ingestion. If the request reached\n * the server, was processed, and the *response* was lost, a retry ingests the\n * same content twice and bills for it twice. The client cannot tell that case\n * apart from \"the request never arrived\" by looking at the error type alone.\n *\n * So retries are gated on two independent questions:\n *\n * 1. Is the error transient? (worth retrying at all)\n * 2. Is the outcome *knowable*? (safe to retry a non-idempotent call)\n *\n * A connection error means the request provably never reached the application,\n * so the outcome is known: nothing happened. A read timeout means the request\n * may well have been processed. That is the ambiguous case, and for a\n * non-idempotent method it is where we stop.\n *\n * The residual window -- server accepted the request, began processing, then\n * died before responding -- cannot be closed from the client at all. Closing it\n * requires a server-honoured idempotency key on the ingest route. Until that\n * exists, this policy narrows the window rather than eliminating it.\n */\n\nimport { RateLimitError, SynapError, isSynapError } from '../errors.js';\n\n/** HTTP methods that are idempotent by specification. */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\n 'GET',\n 'HEAD',\n 'OPTIONS',\n 'PUT',\n 'DELETE',\n]);\n\nexport interface RetryPolicy {\n maxAttempts: number;\n /** Base delay in seconds. */\n backoffBase: number;\n /** Delay cap in seconds. */\n backoffMax: number;\n /** Randomise the delay to avoid a thundering herd. */\n backoffJitter: boolean;\n}\n\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n maxAttempts: 3,\n backoffBase: 1.0,\n backoffMax: 10.0,\n backoffJitter: true,\n};\n\nexport interface RetryDecisionInput {\n error: unknown;\n /** 1-based. */\n attempt: number;\n policy: RetryPolicy;\n method: string;\n /**\n * True when the request may have been processed by the server despite the\n * error. Read timeouts and mid-flight disconnects are ambiguous; connection\n * errors and definitive HTTP status responses are not.\n */\n outcomeUnknown: boolean;\n /** Overrides idempotency for a route, e.g. a read-only POST. */\n idempotent?: boolean;\n}\n\nexport interface RetryDecision {\n retry: boolean;\n /** Seconds to wait before the next attempt. */\n delaySeconds: number;\n reason: string;\n}\n\nexport function shouldRetry(input: RetryDecisionInput): RetryDecision {\n const { error, attempt, policy, method, outcomeUnknown } = input;\n\n if (attempt >= policy.maxAttempts) {\n return { retry: false, delaySeconds: 0, reason: 'max_attempts_exhausted' };\n }\n\n if (!isSynapError(error) || !(error as SynapError).transient) {\n return { retry: false, delaySeconds: 0, reason: 'not_transient' };\n }\n\n // The trial cap and an inactive subscription arrive as 429 but clear with a\n // plan change or a new cycle, never within a retry.\n if (error instanceof RateLimitError && error.reason) {\n return { retry: false, delaySeconds: 0, reason: 'credit_stop' };\n }\n\n const idempotent = input.idempotent ?? IDEMPOTENT_METHODS.has(method.toUpperCase());\n if (outcomeUnknown && !idempotent) {\n // The request may have been processed. For ingestion that means a retry\n // would store and bill twice. Surfacing the error is the cheaper mistake.\n return {\n retry: false,\n delaySeconds: 0,\n reason: 'non_idempotent_outcome_unknown',\n };\n }\n\n return {\n retry: true,\n delaySeconds: backoffDelay(error, attempt, policy),\n reason: 'transient_retryable',\n };\n}\n\n/** Exponential backoff, honouring Retry-After when the server sent one. */\nexport function backoffDelay(error: unknown, attempt: number, policy: RetryPolicy): number {\n if (error instanceof RateLimitError && error.retryAfterSeconds != null) {\n // The server told us when to come back. Guessing shorter just gets us\n // rejected again and burns quota.\n return Math.min(error.retryAfterSeconds, policy.backoffMax);\n }\n const exponential = policy.backoffBase * 2 ** (attempt - 1);\n const capped = Math.min(exponential, policy.backoffMax);\n if (!policy.backoffJitter) return capped;\n // Full jitter. Equal-jitter still synchronises a fleet after a shared outage.\n return Math.random() * capped;\n}\n\nexport const _IDEMPOTENT_METHODS = IDEMPOTENT_METHODS;\n","/**\n * Connection reuse for the HTTP transport.\n *\n * ## Why this file exists at all\n *\n * Node's global `fetch` keeps an idle socket for roughly 4 seconds. Our real\n * call pattern is one fetch per conversation turn, often minutes apart, so\n * essentially every call would pay a full connection setup. Through the CDN to\n * the origin that was measured at 600-950ms.\n *\n * The Python SDK already solved this: `keepalive_expiry=300s` plus a 240s\n * `/health` heartbeat that keeps the socket warm for as long as the client\n * lives. Porting the SDK without porting this would ship a \"native and faster\"\n * release that is measurably *slower* than the Python-subprocess wrapper it\n * replaces, on every call, from day one. That is gotcha G-A.\n *\n * ## Why it is optional and lazily loaded\n *\n * `undici` is Node-only. Edge runtimes and Workers have their own connection\n * pooling and no `dispatcher` option, so there the correct behavior is to use\n * global `fetch` unchanged. Importing undici eagerly would break those builds\n * at bundle time, so it is behind a lazy `import()` and every failure path\n * degrades to plain `fetch` rather than throwing.\n */\n\n/** Mirrors HTTPTransport.KEEPALIVE_EXPIRY_SECONDS in the Python SDK. */\nexport const KEEPALIVE_EXPIRY_MS = 300_000;\n/** Mirrors HTTPTransport.HEARTBEAT_INTERVAL_SECONDS. */\nexport const HEARTBEAT_INTERVAL_MS = 240_000;\nexport const MAX_CONNECTIONS = 20;\n\nexport interface KeepAliveOptions {\n keepAliveExpiryMs?: number;\n maxConnections?: number;\n}\n\n/** An undici Dispatcher, typed loosely so undici is not a hard type dependency. */\nexport type Dispatcher = object;\n\nlet cached: Dispatcher | null | undefined;\n\n/** True when we are on a runtime that can host an undici dispatcher. */\nexport function supportsDispatcher(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.versions?.node !== undefined &&\n // Edge builds of Next expose a partial `process` shim, but no real Node.\n typeof (globalThis as { EdgeRuntime?: unknown }).EdgeRuntime === 'undefined'\n );\n}\n\n/**\n * Build (once) a dispatcher with Python-equivalent keep-alive.\n *\n * Returns null on any runtime where that is not possible, in which case the\n * caller should simply omit the dispatcher.\n */\nexport async function getKeepAliveDispatcher(\n options: KeepAliveOptions = {},\n): Promise<Dispatcher | null> {\n if (cached !== undefined) return cached;\n if (!supportsDispatcher()) {\n cached = null;\n return cached;\n }\n try {\n // Bundlers must not try to follow this statically on Edge builds.\n const undici = (await import(/* @vite-ignore */ 'undici')) as {\n Agent: new (opts: Record<string, unknown>) => Dispatcher;\n };\n cached = new undici.Agent({\n keepAliveTimeout: options.keepAliveExpiryMs ?? KEEPALIVE_EXPIRY_MS,\n // undici will not honour a keepAliveTimeout above this ceiling.\n keepAliveMaxTimeout: options.keepAliveExpiryMs ?? KEEPALIVE_EXPIRY_MS,\n connections: options.maxConnections ?? MAX_CONNECTIONS,\n });\n } catch {\n // undici is an optionalDependency. Missing or unloadable is not fatal:\n // global fetch still works, just with a short-lived pool.\n cached = null;\n }\n return cached;\n}\n\n/** Test seam. */\nexport function _resetDispatcherCache(): void {\n cached = undefined;\n}\n\n/**\n * Keep an idle connection warm.\n *\n * The timer is `unref`'d. Without that the Node event loop stays alive for as\n * long as the interval exists and any CLI built on this SDK hangs forever\n * instead of exiting. Python has no equivalent symptom, so no parity test would\n * ever catch it: that is gotcha G-J.\n */\nexport class Heartbeat {\n private timer: ReturnType<typeof setInterval> | null = null;\n\n constructor(\n private readonly ping: () => void | Promise<void>,\n private readonly intervalMs: number = HEARTBEAT_INTERVAL_MS,\n ) {}\n\n start(): void {\n if (this.timer !== null) return;\n // 0 disables, matching the Python transport's convention.\n if (this.intervalMs <= 0) return;\n if (typeof setInterval !== 'function') return;\n\n this.timer = setInterval(() => {\n // A failed heartbeat is not an error the caller should ever see. The\n // next real request will surface a genuine connectivity problem.\n void Promise.resolve(this.ping()).catch(() => {});\n }, this.intervalMs);\n\n (this.timer as { unref?: () => void }).unref?.();\n }\n\n stop(): void {\n if (this.timer !== null) {\n clearInterval(this.timer);\n this.timer = null;\n }\n }\n\n get running(): boolean {\n return this.timer !== null;\n }\n}\n","/**\n * The B2C identifier contract, client side.\n *\n * B2C send user_id, and nothing else. customer_id is not accepted.\n * B2B customer_id is required.\n *\n * The server is authoritative and rejects independently. This exists so the\n * failure happens at the call site, with a message that says what to do,\n * instead of as a round trip that returns an empty result.\n *\n * That last part is the whole reason. Sending a customer_id on a B2C instance\n * used to produce no exception anywhere: the write was filed under the\n * customer, the read asked for the user, and both returned success. One client\n * ran 4,634 consecutive empty fetches across seven days without a single error\n * to look at. An SDK that stays quiet about a misuse it can see is not being\n * permissive, it is hiding the bug.\n */\nimport { CustomerIdNotAcceptedError } from './errors.js';\n\nexport const B2C_ISOLATION = 'equals_customer';\n\n/**\n * Throw if this call breaks the contract.\n *\n * `isolation` is what `GET /api/v1/auth/whoami` reported. **undefined means the\n * server did not tell us**, which is true of any deployment older than that\n * field, and it must mean \"do nothing\". Guessing B2C there would make this SDK\n * refuse a B2B client's mandatory field against every server not yet upgraded,\n * a far worse failure than the one it prevents.\n */\nexport function checkCustomerId(\n isolation: string | undefined,\n customerId: unknown,\n where: string,\n instanceId?: string,\n): void {\n if (customerId === undefined || customerId === null || customerId === '') return;\n if (isolation !== B2C_ISOLATION) return;\n throw new CustomerIdNotAcceptedError(where, String(customerId), instanceId);\n}\n","/**\n * Native HTTP transport.\n *\n * Port of `maximem_synap/transport/http_client.py`. Uses global `fetch` so the\n * same code runs on Node, Edge, Workers and Bun, with an optional undici\n * dispatcher on Node to restore Python's connection reuse (see keepalive.ts).\n */\n\nimport {\n AgentUnavailableError,\n AuthenticationError,\n ContextNotFoundError,\n ConflictError,\n TranscriptConflictError,\n InstanceNotReadyError,\n InstanceBuildFailedError,\n InsufficientCreditsError,\n InvalidInputError,\n NetworkTimeoutError,\n RateLimitError,\n ServiceUnavailableError,\n SynapError,\n SynapPermanentError,\n} from '../errors.js';\nimport { newCorrelationId } from '../util/correlation.js';\nimport { ENDPOINTS, resolvePath, type EndpointName } from './endpoints.js';\nimport {\n DEFAULT_RETRY_POLICY,\n shouldRetry,\n type RetryPolicy,\n} from './retry.js';\nimport {\n getKeepAliveDispatcher,\n Heartbeat,\n HEARTBEAT_INTERVAL_MS,\n type KeepAliveOptions,\n} from './keepalive.js';\nimport { checkCustomerId } from '../scoping.js';\n\nexport const DEFAULT_BASE_URL = 'https://synap-cloud-prod.maximem.ai';\n\n/**\n * Client-side cooldown for `instance_not_ready`.\n *\n * The server refuses memory calls while an instance's memory architecture is\n * being built, and says how long to wait. After one refusal the SDK answers the\n * same refusal locally, with no network call, until that wait has passed.\n *\n * Only the routes the server gates (`require_instance_ready` in\n * `synap/cloud/application/admin_api/routes/sdk_*.py` and `migrations.py`) are\n * covered. Everything else (whoami, health, auth, status, credits, telemetry,\n * forget, compaction, profile reads) is not gated by the server and is never\n * short-circuited here. Matching is on the path (or a sub-path) AND the POST\n * method. Same list as `GATED_POST_PATHS` in `http_client.py`.\n */\nexport const GATED_POST_PATHS: readonly string[] = [\n '/v1/context/conversation/fetch', // sdk_context.py\n '/v1/context/user/fetch', // sdk_context.py\n '/v1/context/customer/fetch', // sdk_context.py\n '/v1/context/client/fetch', // sdk_context.py\n '/v1/conversations/messages', // sdk_conversations.py (+ /messages/batch)\n '/v1/conversations/ingest', // sdk_conversations.py\n '/v1/events/batch', // sdk_events.py\n '/api/v1/memories/create', // sdk_memories.py\n '/api/v1/memories/batch', // sdk_memories.py\n '/api/v1/memories/upload', // sdk_memories.py\n '/v1/migrations', // migrations.py (create, /{id}/approve, /{id}/run)\n];\n\n/** The most the SDK will ever wait on a server hint (seconds). */\nexport const COOLDOWN_MAX_SECONDS = 300;\n\n/** True when the server refuses this call while the instance is building. */\nexport function isGatedPath(method: string, path: string): boolean {\n if (method.toUpperCase() !== 'POST') return false;\n const bare = (path.split('?', 1)[0] ?? '').replace(/\\/+$/, '');\n return GATED_POST_PATHS.some((p) => bare === p || bare.startsWith(p + '/'));\n}\n\nexport interface TimeoutConfig {\n /**\n * Seconds. Same fields as TimeoutConfig in the Python SDK, but only `read`\n * is applied here: it limits the whole request. `connect` and `write` are\n * accepted so a config round-trips between the SDKs, and have no effect.\n */\n connect: number;\n read: number;\n write: number;\n /**\n * gRPC stream idle timeout. Not used by the HTTP transport; the stream\n * client reads it. Present so a config object round-trips between the two\n * SDKs, and because Python's TimeoutConfig has it.\n */\n streamIdle: number;\n}\n\nexport const DEFAULT_TIMEOUTS: TimeoutConfig = {\n connect: 5.0, read: 30.0, write: 10.0, streamIdle: 60.0,\n};\n\nexport interface Credentials {\n apiKey: string;\n clientId: string;\n instanceId: string;\n}\n\nexport interface HttpTransportOptions {\n credentials: Credentials;\n baseUrl?: string;\n timeouts?: Partial<TimeoutConfig>;\n /** `null` disables retries entirely, as Python's `retry_policy=None` does. */\n retryPolicy?: Partial<RetryPolicy> | null;\n keepAlive?: KeepAliveOptions & { heartbeatIntervalMs?: number };\n userAgent?: string;\n /** Injected in tests. Defaults to global fetch. */\n fetchImpl?: typeof fetch;\n /** Monotonic clock in milliseconds. Injected in tests; defaults to `performance.now`. */\n clock?: () => number;\n}\n\nexport interface RequestOptions {\n pathParams?: Record<string, string | number>;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n /**\n * Send `body` as-is instead of JSON-encoding it, and drop the JSON\n * Content-Type so the runtime can set `multipart/form-data` with its own\n * boundary. Setting Content-Type by hand for FormData produces a body the\n * server cannot parse, because the boundary will not match.\n */\n rawBody?: boolean;\n correlationId?: string;\n /** Overrides the endpoint's declared idempotency. */\n idempotent?: boolean;\n /**\n * Re-map an HTTP error for this one call, given the status. Returns the\n * error to throw instead, or undefined to keep it. Applied before the retry\n * decision, so the retry policy sees what the caller will.\n */\n mapError?: (status: number, error: SynapError) => SynapError | undefined;\n signal?: AbortSignal;\n}\n\ninterface AttemptOutcome {\n error: unknown;\n /** True when the server may have processed the request despite the failure. */\n outcomeUnknown: boolean;\n}\n\nexport class HttpTransport {\n readonly baseUrl: string;\n // Mutable so `configure()` can adjust them before the first request, and so\n // `initialize()` can write back the identity resolved from whoami.\n timeouts: TimeoutConfig;\n retryPolicy: RetryPolicy;\n\n #credentials: Credentials;\n private readonly userAgent: string;\n private readonly fetchImpl: typeof fetch;\n private readonly keepAliveOptions: KeepAliveOptions;\n private readonly heartbeat: Heartbeat;\n private closed = false;\n private readonly clock: () => number;\n // instance id -> when the refusal's wait ends (monotonic ms), and what was said.\n // One JS thread runs every request, so a plain Map needs no lock.\n private readonly notReadyCooldown = new Map<\n string, { until: number; message: string; state: string | null }\n >();\n\n constructor(options: HttpTransportOptions) {\n this.clock = options.clock ?? (() => performance.now());\n this.#credentials = options.credentials;\n // Trailing slash would produce `//v1/...`, which some proxies 404.\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '');\n this.timeouts = { ...DEFAULT_TIMEOUTS, ...options.timeouts };\n this.retryPolicy = options.retryPolicy === null\n ? { ...DEFAULT_RETRY_POLICY, maxAttempts: 1 }\n : { ...DEFAULT_RETRY_POLICY, ...options.retryPolicy };\n this.userAgent = options.userAgent ?? '@maximem/synap-js-sdk';\n this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);\n this.keepAliveOptions = options.keepAlive ?? {};\n this.heartbeat = new Heartbeat(\n () => this.pingHealth(),\n options.keepAlive?.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS,\n );\n }\n\n /**\n * @internal Fetch a URL that is not Synap's, with this transport's fetch.\n *\n * Used to read a `FilePart` given by `url`: the SDK fetches it, the server\n * never does. Deliberately sends none of this transport's headers, because\n * the URL belongs to somebody else and the API key must not reach them.\n */\n fetchExternal(url: string, init: RequestInit = {}): Promise<Response> {\n return this.fetchImpl(url, init);\n }\n\n /** Start keeping the connection warm. Opt-in: it is pointless in serverless. */\n startHeartbeat(): void {\n if (!this.closed) this.heartbeat.start();\n }\n\n /**\n * Release timers. Safe to call more than once.\n *\n * This is the supported shutdown path, deliberately explicit rather than\n * hooked to `process.on('exit')`: those handlers leak a listener per client,\n * never fire in Lambda, and `process` does not exist in Workers (gotcha G-I).\n */\n /**\n * A COPY of the current credentials.\n *\n * A copy, not the live object: handing out the internal reference is how\n * `client.transport.credentials.apiKey` became readable and mutable from\n * outside in the first place.\n */\n currentCredentials(): Credentials {\n return { ...this.#credentials };\n }\n\n /** Write back identity resolved from `GET /api/v1/auth/whoami`. */\n updateCredentials(patch: Partial<Credentials>): void {\n this.#credentials = { ...this.#credentials, ...patch };\n }\n\n /**\n * The instance's scoping mode, from whoami. Lives here rather than on the\n * client because every interface factory already receives the transport,\n * and it is per-client, so a module-level global would be wrong the moment a\n * process holds two clients.\n *\n * undefined means the server did not report it, which is true of any\n * deployment older than the field, and must mean \"enforce nothing\".\n */\n userContextIsolation: string | undefined = undefined;\n\n /**\n * Set by the client to its identity resolution (`initialize()`'s whoami).\n * Python refuses every call before `initialize()`; here the first request\n * runs it instead, so a caller who skips it gets the same identity-dependent\n * behaviour (client-scope cache hits, the B2C check) rather than an error.\n */\n identityResolver: (() => Promise<void>) | undefined = undefined;\n\n /** Resolve identity once, before the first request. Never throws. */\n async ready(): Promise<void> {\n if (this.identityResolver !== undefined) await this.identityResolver();\n }\n\n /**\n * Refuse a customer_id on a B2C instance, at the call site. Resolves identity\n * first: the isolation comes from whoami, so on the first call of a client\n * that skipped initialize() the check would otherwise see nothing and pass.\n */\n async checkCustomerId(customerId: unknown, where: string): Promise<void> {\n await this.ready();\n checkCustomerId(\n this.userContextIsolation, customerId, where, this.#credentials.instanceId,\n );\n }\n\n setTimeouts(timeouts: Partial<TimeoutConfig>): void {\n this.timeouts = { ...this.timeouts, ...timeouts };\n }\n\n /**\n * `null` DISABLES retries, matching Python.\n *\n * Python's `SDKConfig(retry_policy=None)` leaves `self.retry_policy` unset and\n * `max_attempts` falls to 1 (http_client.py:180). We restored the default\n * policy instead, so a caller following the \"Disabling Retries\" documentation\n * got three attempts and no way to turn them off.\n */\n setRetryPolicy(policy: Partial<RetryPolicy> | null): void {\n this.retryPolicy = policy === null\n ? { ...DEFAULT_RETRY_POLICY, maxAttempts: 1 }\n : { ...this.retryPolicy, ...policy };\n }\n\n close(): void {\n this.closed = true;\n this.heartbeat.stop();\n }\n\n /** Throw InstanceNotReadyError locally if this instance is cooling down. */\n private cooldownCheck(instanceId: string, correlationId: string): void {\n const entry = this.notReadyCooldown.get(instanceId);\n if (entry === undefined) return;\n const remainingMs = entry.until - this.clock();\n if (remainingMs <= 0) {\n this.notReadyCooldown.delete(instanceId);\n return;\n }\n throw new InstanceNotReadyError(entry.message, {\n correlationId,\n retryAfterSeconds: Math.max(1, Math.ceil(remainingMs / 1000)),\n instanceId,\n state: entry.state,\n fromCooldown: true,\n });\n }\n\n /** Remember a server refusal. Never longer than the server's hint. */\n private cooldownStart(instanceId: string, error: InstanceNotReadyError): void {\n const hint = error.retryAfterSeconds;\n if (hint === null || !(hint > 0)) return; // no hint: nothing to base a wait on\n const waitMs = Math.min(hint, COOLDOWN_MAX_SECONDS) * 1000;\n this.notReadyCooldown.set(instanceId, {\n until: this.clock() + waitMs,\n message: error.message,\n state: error.state,\n });\n }\n\n async request<T = unknown>(name: EndpointName, options: RequestOptions = {}): Promise<T> {\n const spec = ENDPOINTS[name];\n const correlationId = options.correlationId ?? newCorrelationId();\n const idempotent = options.idempotent ?? spec.idempotent;\n // whoami IS the identity resolution, so it must not wait on itself.\n if (name !== 'whoami') await this.ready();\n\n const gated = isGatedPath(spec.method, resolvePath(name, options.pathParams));\n const cooldownKey = this.#credentials.instanceId;\n if (gated) this.cooldownCheck(cooldownKey, correlationId);\n\n let attempt = 0;\n let last: AttemptOutcome | null = null;\n\n // At least one attempt: maxAttempts 0 used to send nothing and throw\n // \"Request failed with no recorded error\".\n while (attempt < Math.max(1, this.retryPolicy.maxAttempts)) {\n attempt += 1;\n try {\n const result = await this.attempt<T>(name, options, correlationId);\n // The server accepted a memory call: the instance is ready.\n if (gated) this.notReadyCooldown.delete(cooldownKey);\n return result;\n } catch (error) {\n // Remember the refusal so the next calls need no round trip.\n if (gated && error instanceof InstanceNotReadyError && !error.fromCooldown) {\n this.cooldownStart(cooldownKey, error);\n }\n last = { error, outcomeUnknown: isOutcomeUnknown(error) };\n const decision = shouldRetry({\n error,\n attempt,\n policy: this.retryPolicy,\n method: spec.method,\n outcomeUnknown: last.outcomeUnknown,\n idempotent,\n });\n if (!decision.retry) throw error;\n await sleep(decision.delaySeconds * 1000, options.signal);\n }\n }\n throw last?.error ?? new SynapError('Request failed with no recorded error');\n }\n\n private async attempt<T>(\n name: EndpointName,\n options: RequestOptions,\n correlationId: string,\n ): Promise<T> {\n const spec = ENDPOINTS[name];\n const url = this.buildUrl(resolvePath(name, options.pathParams), options.query);\n\n const dispatcher = await getKeepAliveDispatcher(this.keepAliveOptions);\n const signal = withTimeout(this.timeouts.read * 1000, options.signal);\n\n const init: RequestInit = {\n method: spec.method,\n headers: this.buildHeaders(correlationId, { json: options.rawBody !== true }),\n signal: signal.signal,\n };\n if (options.body !== undefined && spec.method !== 'GET') {\n // `BodyInit` is a DOM-lib type and this package does not include that lib,\n // so the field's own type is used instead of naming it.\n init.body = options.rawBody === true\n ? (options.body as NonNullable<RequestInit['body']>)\n : JSON.stringify(options.body);\n }\n // `dispatcher` is a Node/undici extension. Its ambient type is only\n // present when undici's types are installed, so it is set structurally\n // rather than declared -- otherwise this file fails to compile for anyone\n // who has not installed the optional dependency.\n if (dispatcher) (init as Record<string, unknown>)['dispatcher'] = dispatcher;\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, init);\n } catch (error) {\n throw toTransportError(error, correlationId);\n } finally {\n signal.dispose();\n }\n\n if (!response.ok) {\n const error = await toHttpError(response, correlationId);\n throw options.mapError?.(response.status, error) ?? error;\n }\n\n if (response.status === 204) return undefined as T;\n const text = await response.text();\n if (!text) return undefined as T;\n try {\n return JSON.parse(text) as T;\n } catch {\n throw new SynapError(`Malformed JSON in response from ${url}`, { correlationId });\n }\n }\n\n private buildUrl(path: string, query?: RequestOptions['query']): string {\n const url = new URL(this.baseUrl + path);\n for (const [k, v] of Object.entries(query ?? {})) {\n if (v !== undefined) url.searchParams.set(k, String(v));\n }\n return url.toString();\n }\n\n private buildHeaders(\n correlationId: string,\n options: { json?: boolean } = {},\n ): Record<string, string> {\n return {\n // Empty only in local mode with no SYNAP_API_TOKEN: send no header at all.\n ...(this.#credentials.apiKey !== '' ? { Authorization: `Bearer ${this.#credentials.apiKey}` } : {}),\n 'X-Client-ID': this.#credentials.clientId,\n 'X-Instance-ID': this.#credentials.instanceId,\n 'X-Correlation-ID': correlationId,\n ...(options.json === false ? {} : { 'Content-Type': 'application/json' }),\n 'User-Agent': this.userAgent,\n };\n }\n\n /** Unauthenticated and unmetered, exactly like the Python heartbeat. */\n private async pingHealth(): Promise<void> {\n const signal = withTimeout(10_000);\n try {\n const dispatcher = await getKeepAliveDispatcher(this.keepAliveOptions);\n const init: RequestInit = { signal: signal.signal };\n if (dispatcher) (init as Record<string, unknown>)['dispatcher'] = dispatcher;\n await this.fetchImpl(`${this.baseUrl}/health`, init);\n } finally {\n signal.dispose();\n }\n }\n}\n\n// ─── Error classification ─────────────────────────────────────────────────────\n\n/**\n * Whether the server may have processed the request despite this error.\n *\n * This is the input to the double-billing gate in retry.ts, so the bias is\n * deliberate: anything we cannot positively rule out counts as ambiguous.\n */\nexport function isOutcomeUnknown(error: unknown): boolean {\n // A definitive HTTP status means the server answered. Nothing ambiguous.\n if (error instanceof RateLimitError) return false;\n if (error instanceof ServiceUnavailableError) return false;\n if (error instanceof AuthenticationError) return false;\n if (error instanceof InvalidInputError) return false;\n if (error instanceof ConflictError) return false;\n if (error instanceof InsufficientCreditsError) return false;\n if (error instanceof ContextNotFoundError) return false;\n\n // Connection-level failures mean the request never reached the application.\n // Checked before the class: since 0.5.13 they are NetworkTimeoutErrors too,\n // and they must stay safe to retry.\n if (isConnectionRefusal(error)) return false;\n\n // Timeouts are the ambiguous case: the request may have been handled and\n // only the response lost.\n if (error instanceof NetworkTimeoutError) return true;\n\n return true;\n}\n\nconst CONNECTION_REFUSAL_CODES = new Set([\n 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ECONNRESET', 'EHOSTUNREACH',\n]);\n\n/**\n * A refusal code anywhere on the cause chain. fetch nests the socket error\n * under its own, and a SynapError carries a `code` of its own\n * ('network_timeout'), so the walk cannot stop at the first `code` it sees.\n */\nfunction isConnectionRefusal(error: unknown): boolean {\n let cur: unknown = error;\n for (let depth = 0; depth < 4 && cur !== null && typeof cur === 'object'; depth += 1) {\n const code = (cur as { code?: unknown }).code;\n if (typeof code === 'string' && CONNECTION_REFUSAL_CODES.has(code)) return true;\n cur = (cur as { cause?: unknown }).cause;\n }\n return false;\n}\n\nfunction toTransportError(error: unknown, correlationId: string): SynapError {\n if (error instanceof SynapError) return error;\n const name = (error as { name?: string })?.name;\n if (name === 'AbortError' || name === 'TimeoutError') {\n return new NetworkTimeoutError('Request timed out', { correlationId, cause: error });\n }\n // A refused, unresolvable or dropped connection is a NetworkTimeoutError,\n // as Python raises it (httpx ConnectError and RemoteProtocolError), so one\n // `catch` handles \"could not reach Synap\" in both SDKs. Until 0.5.13 these\n // were ServiceUnavailableErrors, the class for a 5xx the server sent.\n if (isConnectionRefusal(error)) {\n return new NetworkTimeoutError(\n `Connection failed: ${(error as Error)?.message ?? String(error)}`,\n { correlationId, cause: error },\n );\n }\n return new ServiceUnavailableError(\n `Network request failed: ${(error as Error)?.message ?? String(error)}`,\n { correlationId, cause: error },\n );\n}\n\n/**\n * Values the credit gate sends as the body's `error` field. Only these are read\n * as a reason, so an unrelated 429 carrying some other `error` string is not\n * mistaken for a credit stop. Mirrors `_CREDIT_ERRORS` in `http_client.py`.\n */\nconst CREDIT_ERRORS = new Set(['insufficient_credits', 'trial_limit_reached']);\n\n/**\n * The credit gate's structured body, however the server nested it.\n *\n * The gate raises an HTTPException, so FastAPI wraps its payload in `detail`;\n * the burn-service path returns the same fields at the top level. Reading only\n * the top level (what this transport did) meant the gate's balance, reason and\n * URLs never reached the caller.\n */\nfunction creditPayload(\n parsed: Record<string, unknown>,\n detailObject: Record<string, unknown> | null,\n): Record<string, unknown> {\n return detailObject ?? parsed;\n}\n\n/** Why the request was refused, or null if this was not a credit stop. */\nfunction creditReason(payload: Record<string, unknown>): string | null {\n const reason = stringOrNull(payload['reason']);\n if (reason !== null) return reason;\n const error = stringOrNull(payload['error']);\n return error !== null && CREDIT_ERRORS.has(error) ? error : null;\n}\n\nasync function toHttpError(response: Response, correlationId: string): Promise<SynapError> {\n const body = await response.text().catch(() => '');\n let parsed: Record<string, unknown> = {};\n try {\n parsed = JSON.parse(body) as Record<string, unknown>;\n } catch {\n /* body is not JSON; the raw text is still used in the message */\n }\n // `detail` is a string on most routes but a structured object on the ones\n // that need a machine-readable code: {\"detail\": {\"code\": ..., \"message\": ...}}.\n // Casting it straight to string rendered those as \"[object Object]\".\n const rawDetail = parsed['detail'] ?? parsed['message'] ?? body ?? '';\n const detailObject =\n typeof rawDetail === 'object' && rawDetail !== null\n ? (rawDetail as Record<string, unknown>)\n : null;\n const detail =\n detailObject !== null\n ? String(detailObject['message'] ?? JSON.stringify(detailObject))\n : String(rawDetail);\n const message = `HTTP ${response.status}: ${detail || response.statusText}`;\n const opts = { correlationId };\n\n switch (response.status) {\n case 400:\n case 422:\n // Wrong method, too large, unsupported media type: each says what was\n // wrong with the request, and none of them goes away on a retry.\n case 405:\n case 413:\n case 415:\n return new InvalidInputError(message, opts);\n case 401:\n case 403:\n return new AuthenticationError(message, opts);\n case 404:\n return new ContextNotFoundError(message, opts);\n case 402: {\n // The server sends `minimum_required_credits` (see\n // synap/cloud/application/credits/enforcement.py). We read\n // `required_credits` for a while, a key that never exists, so\n // `requiredCredits` was always null. `recovery_url` and `redeem_url`\n // were dropped entirely, leaving no way to surface a top-up link.\n const credit = creditPayload(parsed, detailObject);\n return new InsufficientCreditsError(message, {\n ...opts,\n balanceCredits: numberOrNull(credit['balance_credits']),\n requiredCredits:\n numberOrNull(credit['minimum_required_credits']) ??\n numberOrNull(credit['required_credits']),\n recoveryUrl: stringOrNull(credit['recovery_url']),\n redeemUrl: stringOrNull(credit['redeem_url']),\n reason: creditReason(credit),\n manageUrl: stringOrNull(credit['manage_url']),\n });\n }\n case 409:\n // Conflict is PERMANENT and never retried. Python discriminates on the\n // structured body so a transcript-immutability conflict becomes\n // TranscriptConflictError and anything else (e.g. compact()'s \"already\n // in progress\") stays the generic ConflictError. Without this, a\n // customer's `catch (e) { if (e instanceof TranscriptConflictError) }`\n // never fires in JS while the identical Python code works.\n if (\n parsed['error'] === 'instance_build_failed' ||\n detailObject?.['code'] === 'instance_build_failed' ||\n detailObject?.['error'] === 'instance_build_failed'\n ) {\n // Not time based: no cooldown, no retry. Mirrors `_instance_build_failed`.\n const pick = (key: string): unknown => parsed[key] ?? detailObject?.[key];\n const msg = pick('message');\n const attempts = Number(pick('attempts'));\n return new InstanceBuildFailedError(\n typeof msg === 'string' && msg !== ''\n ? msg\n : \"This instance's memory architecture build failed.\",\n {\n ...opts,\n instanceId: stringOrNull(pick('instance_id')),\n attempts: pick('attempts') !== undefined && pick('attempts') !== null\n && Number.isFinite(attempts) ? Math.trunc(attempts) : null,\n hint: stringOrNull(pick('hint')),\n },\n );\n }\n if (\n parsed['error'] === 'instance_not_ready' ||\n detailObject?.['code'] === 'instance_not_ready' ||\n detailObject?.['error'] === 'instance_not_ready'\n ) {\n // Fields come from the flat copy, then the `detail` copy, then the\n // Retry-After header. Mirrors `_instance_not_ready` in http_client.py.\n const pick = (key: string): unknown => parsed[key] ?? detailObject?.[key];\n const rawWait = pick('retry_after_seconds') ?? response.headers.get('retry-after');\n const wait =\n rawWait !== null && rawWait !== undefined && String(rawWait).trim() !== ''\n ? Number(rawWait)\n : NaN;\n const msg = pick('message');\n return new InstanceNotReadyError(\n typeof msg === 'string' && msg !== ''\n ? msg\n : \"This instance's memory architecture is still being built.\",\n {\n ...opts,\n retryAfterSeconds: Number.isFinite(wait) ? Math.trunc(wait) : null,\n instanceId: stringOrNull(pick('instance_id')),\n state: stringOrNull(pick('state')) ?? 'building',\n },\n );\n }\n if (detailObject !== null && detailObject['code'] === 'transcript_conflict') {\n return new TranscriptConflictError(message, opts);\n }\n return new ConflictError(message, opts);\n case 429: {\n // Either an ordinary rate limit or a credit stop that time or a plan\n // change clears: the spent Trial cap (`trial_limit_reached`) and a paid\n // plan whose subscription lapsed (`subscription_inactive`). The credit\n // fields are absent on the plain rate limit.\n const header = response.headers.get('retry-after');\n const retryAfter = header !== null && header.trim() !== '' ? Number(header) : null;\n const credit = creditPayload(parsed, detailObject);\n return new RateLimitError(message, {\n ...opts,\n retryAfterSeconds: retryAfter !== null && Number.isFinite(retryAfter) ? retryAfter : null,\n reason: creditReason(credit),\n upgradeUrl: stringOrNull(credit['upgrade_url']),\n manageUrl: stringOrNull(credit['manage_url']),\n });\n }\n case 503:\n return new ServiceUnavailableError(message, opts);\n case 504:\n return new AgentUnavailableError(message, opts);\n default:\n if (response.status >= 500) return new ServiceUnavailableError(message, opts);\n // Any other 4xx is the request's fault and fails the same way again:\n // permanent, as Python raises it. It was a bare SynapError.\n if (response.status >= 400) return new SynapPermanentError(message, opts);\n return new SynapError(message, opts);\n }\n}\n\nfunction numberOrNull(v: unknown): number | null {\n return typeof v === 'number' && Number.isFinite(v) ? v : null;\n}\n\nfunction stringOrNull(v: unknown): string | null {\n return typeof v === 'string' && v !== '' ? v : null;\n}\n\n// ─── Utilities ────────────────────────────────────────────────────────────────\n\ninterface DisposableSignal {\n signal: AbortSignal;\n dispose(): void;\n}\n\n/**\n * Compose a timeout with a caller-supplied signal.\n *\n * Hand-rolled rather than `AbortSignal.timeout` + `AbortSignal.any` because\n * `any` is Node 20.3+ and this must also run on Workers and older Bun. The\n * timer is cleared in `dispose` so a fast response does not hold the event\n * loop open for the full timeout.\n */\nfunction withTimeout(ms: number, external?: AbortSignal): DisposableSignal {\n const controller = new AbortController();\n const onExternalAbort = () => controller.abort(external?.reason);\n const timer = setTimeout(() => {\n controller.abort(new NetworkTimeoutError(`Timed out after ${ms}ms`));\n }, ms);\n (timer as { unref?: () => void }).unref?.();\n\n if (external) {\n if (external.aborted) onExternalAbort();\n else external.addEventListener('abort', onExternalAbort, { once: true });\n }\n\n return {\n signal: controller.signal,\n dispose() {\n clearTimeout(timer);\n external?.removeEventListener('abort', onExternalAbort);\n },\n };\n}\n\n/**\n * Retry backoff.\n *\n * Deliberately NOT `unref`'d, unlike the heartbeat timer in keepalive.ts. That\n * distinction is the whole point: a heartbeat is background work and must not\n * hold the process open, but a backoff is FOREGROUND work that a caller is\n * awaiting. With it unref'd, a process whose only pending work was this sleep\n * exited during the backoff and the awaited request never settled -- Node\n * reports it as \"Detected unsettled top-level await\". Invisible in a server\n * with other traffic; fatal in a CLI or an idle serverless handler.\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) return Promise.resolve();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n function onAbort() {\n clearTimeout(timer);\n reject(signal?.reason ?? new Error('Aborted'));\n }\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","/**\n * `response_shape: \"ranked\"`: one list in the order the server ranked it.\n *\n * Ports the ranked half of Python's `models/context.py` (`rank_items`,\n * `_wire_rank_score`, `_wire_category` and the ranked branch of\n * `ContextResponse.from_cloud_response`). The cases are pinned in\n * `CONTRACT/conformance/ranked_shape.json`, captured from Python.\n *\n * Opt-in. A by-type fetch, the default, is returned exactly as the server sent\n * it, so nothing here touches a caller who does not ask for the ranked shape.\n */\n\nimport type { Json, RawContext, RawContextItem } from './types.js';\n\n/** The two shapes a context fetch can ask for. */\nexport const RESPONSE_SHAPES = ['by_type', 'ranked'] as const;\nexport type ResponseShape = (typeof RESPONSE_SHAPES)[number];\n\n/** The memory types, in the order the by-type response lists them. */\nexport const MEMORY_TYPES = [\n 'facts',\n 'preferences',\n 'episodes',\n 'emotions',\n 'temporal_events',\n] as const;\n\n/**\n * The type of a chunk in a ranked response: a quote from a source document,\n * not an extracted memory. A by-type response files it under `facts`.\n */\nexport const EXCERPT_CATEGORY = 'excerpts';\n\n/**\n * An item's rank score: `metadata.rank_score` on the HTTP response, a\n * top-level `rank_score` on a prefetched (gRPC) item. `null` when neither is a\n * number, which is how a server that predates ranking reads.\n */\nexport function wireRankScore(item: RawContextItem): number | null {\n const md = item.metadata;\n let raw: unknown = md !== null && typeof md === 'object' ? (md as Json)['rank_score'] : undefined;\n if (raw === undefined || raw === null) raw = item['rank_score'];\n return typeof raw === 'number' && Number.isFinite(raw) ? raw : null;\n}\n\n/**\n * An item's type. A chunk is an excerpt whatever list it came in: a server or\n * a prefetched bundle that predates ranking files it under facts.\n */\nexport function wireCategory(item: RawContextItem, fallback = ''): string {\n if (item.source === 'chunks') return EXCERPT_CATEGORY;\n const category = item['category'];\n if (typeof category === 'string' && category !== '') return category;\n const contextType = item['context_type'];\n if (typeof contextType === 'string' && contextType !== '') return contextType;\n return fallback;\n}\n\n/** Highest score first; items without one after, in the order they came. */\nfunction byRankScore(a: RawContextItem, b: RawContextItem): number {\n const sa = wireRankScore(a);\n const sb = wireRankScore(b);\n if (sa === null && sb === null) return 0;\n if (sa === null) return 1;\n if (sb === null) return -1;\n return sb - sa;\n}\n\n/**\n * Merge per-type item lists into one list in rank order, numbered from 1.\n *\n * For a server that predates `response_shape` (it returned the five lists) and\n * for a prefetched cache hit. Each returned item is a copy carrying `rank`,\n * `category` and `id` (a prefetched item names it `item_id`), so the input is\n * not changed. `Array.prototype.sort` is stable, like Python's.\n */\nexport function rankItems(byType: RawContext): RawContextItem[] {\n const flat: RawContextItem[] = [];\n // The five lists only: a raw context also carries other arrays\n // (`conversations` in summary mode), and none of them are memories.\n for (const type of MEMORY_TYPES) {\n const list = (byType as Json)[type];\n if (!Array.isArray(list)) continue;\n for (const it of list as RawContextItem[]) {\n if (it === null || typeof it !== 'object') continue;\n flat.push({\n ...it,\n category: wireCategory(it, type),\n id: (it.id || it.item_id || '') as string,\n });\n }\n }\n flat.sort(byRankScore);\n return flat.map((it, n) => ({ ...it, rank: n + 1 }));\n}\n\n/**\n * The raw context in the shape the caller asked for.\n *\n * \"ranked\": `items` in rank order (the server's own list, or one rebuilt by\n * rank score when the server or the cache predates the parameter), the five\n * typed lists as views of those items, and `excerpts` for the chunks. A\n * response that already carries `items` is read the same way even when the\n * caller did not ask, as Python does. Anything else is returned untouched.\n */\nexport function applyResponseShape(raw: RawContext, shape: string = 'by_type'): RawContext {\n const wire = (raw as Json)['items'];\n if (shape !== 'ranked' && !Array.isArray(wire)) return raw;\n const source: RawContextItem[] = Array.isArray(wire)\n ? (wire as RawContextItem[])\n : rankItems(raw);\n const items = source.map((it) => ({\n ...it,\n id: (it.id || it.item_id || '') as string,\n category: wireCategory(it),\n }));\n const out: RawContext = { ...raw, items };\n for (const type of MEMORY_TYPES) {\n out[type] = items.filter((it) => it['category'] === type);\n }\n (out as Json)['excerpts'] = items.filter((it) => it['category'] === EXCERPT_CATEGORY);\n return out;\n}\n\n/** How each type is named on a line of the ranked prompt list. */\nconst RANKED_LABELS: Record<string, string> = {\n facts: 'fact',\n preferences: 'preference',\n episodes: 'episode',\n emotions: 'emotion',\n temporal_events: 'temporal event',\n [EXCERPT_CATEGORY]: 'excerpt',\n};\n\n/** The label printed in front of a ranked item: `fact`, `temporal event`, ... */\nexport function rankedLabel(category: string): string {\n return RANKED_LABELS[category] ?? (category !== '' ? category : 'item');\n}\n\n/** Shared by the ranked merge: the same ordering Python's `merge` sorts with. */\nexport function sortByRankScore(items: RawContextItem[]): RawContextItem[] {\n return [...items].sort(byRankScore);\n}\n","/**\n * A fetch with no query. Mirrors `has_query`, `conversation_state_context` and\n * `profile_context` in the Python SDK's `models/context.py`; the corpus both\n * run is `CONTRACT/conformance/no_query_fetch.json`.\n *\n * Without a query the server embedded an empty string and ranked memories\n * against it, so the answer was close to arbitrary. A conversation fetch now\n * answers with the conversation's state (what `get_context_for_prompt` gives)\n * and a user fetch with the user's profile when there is one.\n */\n\nimport type { Json, RawContext } from './types.js';\n\nconst MEMORY_TYPES = ['facts', 'preferences', 'episodes', 'emotions', 'temporal_events'] as const;\n\nconst emptyLists = (): Record<string, unknown[]> =>\n Object.fromEntries(MEMORY_TYPES.map((t) => [t, []]));\n\n/** Whether a fetch names something to search for. Blank strings are no query. */\nexport function hasQuery(searchQuery: unknown): boolean {\n if (typeof searchQuery === 'string') return searchQuery.trim() !== '';\n if (!Array.isArray(searchQuery)) return false;\n return searchQuery.some((q) => typeof q === 'string' && q.trim() !== '');\n}\n\n/** The answer to a conversation fetch without a query, in the fetch's wire shape. */\nexport function conversationStateContext(prompt: Json, conversationId: string): RawContext {\n const recent = Array.isArray(prompt['recent_messages']) ? (prompt['recent_messages'] as unknown[]) : [];\n const turns = recent\n .filter((m): m is Record<string, unknown> => typeof m === 'object' && m !== null && !Array.isArray(m))\n .map((m) => ({ role: m['role'] ?? null, content: m['content'] ?? null, timestamp: m['timestamp'] ?? null }));\n return {\n ...emptyLists(),\n conversation_context: {\n conversation_id: conversationId,\n summary: (prompt['context_block'] as string | undefined) || null,\n recent_turns: turns,\n compaction_id: (prompt['compaction_id'] as string | undefined) || null,\n formatted_context: (prompt['formatted_context'] as string | undefined) || null,\n },\n } as unknown as RawContext;\n}\n\n/**\n * The answer to a user fetch without a query, or null when there is no profile.\n * Takes the profile document flat or wrapped in `{ profile: ... }`. One with no\n * attributes and no overview counts as none.\n */\nexport function profileContext(profile: unknown): RawContext | null {\n if (typeof profile !== 'object' || profile === null || Array.isArray(profile)) return null;\n let doc = profile as Record<string, unknown>;\n const inner = doc['profile'];\n if (!('attributes' in doc) && typeof inner === 'object' && inner !== null && !Array.isArray(inner)) {\n doc = inner as Record<string, unknown>;\n }\n const attributes = doc['attributes'];\n const hasAttributes = typeof attributes === 'object' && attributes !== null && Object.keys(attributes).length > 0;\n if (!hasAttributes && !doc['overview']) return null;\n return { ...emptyLists(), profile: doc } as unknown as RawContext;\n}\n","/**\n * Scope-aware context fetching.\n *\n * Scopes are client > customer > user. `conversation_id` is NOT a tier: it\n * groups turns within a scope. Passing it narrows an existing scope rather\n * than selecting a different one.\n */\n\nimport type { EndpointName } from '../transport/endpoints.js';\nimport type { HttpTransport } from '../transport/http.js';\nimport { InvalidInputError } from '../errors.js';\nimport { RESPONSE_SHAPES, applyResponseShape } from './ranked.js';\nimport { hasQuery } from './no-query.js';\nimport type { FetchOptions, Json, RawContext } from './types.js';\n\nexport type Scope = 'user' | 'customer' | 'client' | 'conversation';\n\nconst ENDPOINT_BY_SCOPE: Record<Scope, EndpointName> = {\n user: 'context_fetch_user',\n customer: 'context_fetch_customer',\n client: 'context_fetch_client',\n conversation: 'context_fetch_conversation',\n};\n\n/** Reads either spelling of an option. Callers depend on both. */\nfunction opt<T>(options: FetchOptions, snake: keyof FetchOptions, camel: keyof FetchOptions): T | undefined {\n const a = options[snake];\n if (a !== undefined) return a as T;\n const b = options[camel];\n return b === undefined ? undefined : (b as T);\n}\n\nexport interface BuiltRequest {\n endpoint: EndpointName;\n body: Json;\n}\n\nexport function buildFetchRequest(scope: Scope, options: FetchOptions): BuiltRequest {\n const userId = opt<string>(options, 'user_id', 'userId');\n const customerId = opt<string>(options, 'customer_id', 'customerId');\n const conversationId = opt<string>(options, 'conversation_id', 'conversationId');\n const searchQuery = opt<string[]>(options, 'search_query', 'searchQuery');\n const maxResults = opt<number>(options, 'max_results', 'maxResults') ?? 10;\n const queryDate = opt<string>(options, 'query_date', 'queryDate');\n const perQuery = opt<number>(options, 'max_results_per_query', 'maxResultsPerQuery');\n const responseShape = responseShapeOf(options);\n const { mode, precisionLevel } = retrievalOptionsOf(options);\n const { contextMode, lastN } = scopeOptionsOf(scope, options);\n\n if (searchQuery !== undefined && !Array.isArray(searchQuery)) {\n throw new InvalidInputError('search_query must be an array when provided');\n }\n if (options.types !== undefined && !Array.isArray(options.types)) {\n throw new InvalidInputError('types must be an array when provided');\n }\n\n // Field-for-field identical to what the Python controllers post, because the\n // server is tuned against that payload and Python is the reference\n // implementation. In particular:\n // - conversation_id is ALWAYS present, null when unset, not omitted\n // - mode always defaults to \"fast\"\n // - precision_level is sent ONLY when it differs from \"high\"\n // - query_date is sent ONLY when the caller supplied one\n // - max_results_per_query is sent ONLY when the caller supplied one\n // - response_shape is sent ONLY when \"ranked\"\n // - include_conversation_context is sent ONLY when false\n // Sending an extra key, or omitting one Python always sends, is exactly the\n // kind of difference that shows up as \"works in Python, empty in JS\".\n const body: Json = {\n conversation_id: conversationId ?? null,\n search_query: searchQuery ?? [],\n max_results: maxResults,\n types: options.types ?? ['all'],\n mode,\n };\n if (precisionLevel !== 'high') body['precision_level'] = precisionLevel;\n // Omitted at its default, for the same reason precision_level is.\n if (queryDate) body['query_date'] = queryDate;\n // Omitted when unset, and `0` counts as unset, as in Python.\n if (perQuery) body['max_results_per_query'] = perQuery;\n if (responseShape !== 'by_type') body['response_shape'] = responseShape;\n if (options.include_conversation_context === false) {\n body['include_conversation_context'] = false;\n }\n // On all four scopes, as Python sends it. Until 0.5.10 only the user scope\n // did, so a scope_path passed to the client, customer or conversation fetch\n // was dropped and the read was served at the default levels instead.\n // Omitted when absent or empty, like Python's `if scope_path:`, so a caller\n // who does not use custom levels sends exactly the body they sent before.\n const scopePath = opt<Record<string, string>>(options, 'scope_path', 'scopePath');\n if (scopePath !== undefined && scopePath !== null && Object.keys(scopePath).length > 0) {\n body['scope'] = scopePath;\n }\n\n switch (scope) {\n case 'user': {\n body['user_id'] = userId as string;\n\n // Conditional, exactly as Python does it: the summary-mode keys are sent\n // ONLY in summary mode, so an in-conversation fetch is byte-identical to\n // one that never knew about them.\n if (contextMode === 'conversation-summary') {\n body['context_mode'] = contextMode;\n body['include_profile'] = opt<boolean>(options, 'include_profile', 'includeProfile') ?? true;\n body['last_n_conversations'] = lastN;\n }\n // Python sends this only when not None. It is passed through the same\n // way rather than defaulted to '', so the server sees the same request\n // from either SDK.\n if (customerId !== undefined) body['customer_id'] = customerId;\n break;\n }\n break;\n case 'customer':\n body['customer_id'] = customerId as string;\n break;\n case 'conversation':\n if (userId !== undefined) body['user_id'] = userId;\n if (customerId !== undefined) body['customer_id'] = customerId;\n break;\n case 'client':\n break;\n }\n\n return { endpoint: ENDPOINT_BY_SCOPE[scope], body };\n}\n\n/**\n * Hooks that let the client serve a fetch locally and report the outcome.\n *\n * Passed in rather than imported so this module stays free of the cache and\n * the stream: it is the one place every scope's fetch goes through, and it\n * should not grow a dependency on either.\n */\nexport interface AnticipatedServe {\n response: RawContext;\n servedItemIds: string[];\n bundleId: string;\n /**\n * A semantic match below the sure bar. The server is asked too, and its\n * answer is used if it arrives within `raceDeadlineMs`. Python:\n * `_race_borderline`.\n */\n borderline?: boolean;\n raceDeadlineMs?: number;\n}\n\nexport interface FetchHooks {\n /** Returns a response to short-circuit the network, or null to continue. */\n beforeFetch?: (\n scope: Scope,\n options: FetchOptions,\n ) => AnticipatedServe | null | Promise<AnticipatedServe | null>;\n /** Called after a cache hit is served, for the learning-loop event. */\n onServedFromCache?: (\n scope: Scope,\n options: FetchOptions,\n served: { servedItemIds: string[]; bundleId: string },\n ) => void;\n /** Called after EVERY fetch resolves, cache or network, for the audit event. */\n onAssembled?: (\n scope: Scope,\n options: FetchOptions,\n response: RawContext,\n startedAt: number,\n ) => void;\n /**\n * Called last on every path, with the shaped response, which it may modify:\n * the periodic user-summary splice Python runs at the end of each scoped\n * fetch.\n */\n onResponse?: (scope: Scope, options: FetchOptions, response: RawContext) => void;\n /**\n * True when this process already holds the conversation's compaction and\n * every turn after it, so the request asks the server not to assemble them\n * (`include_conversation_context: false`), as Python does on every scope.\n */\n skipServerShortTerm?: (conversationId: string) => boolean;\n /**\n * The answer to a fetch with no query, or null to make the fetch as before:\n * the conversation's state for the conversation scope, the profile for the\n * user scope. Python answers these inside the two scoped fetches; here the\n * client holds what they need, so it answers through this hook.\n */\n withoutQuery?: (scope: Scope, options: FetchOptions) => Promise<RawContext | null>;\n}\n\nconst VALID_CONTEXT_MODES = ['in-conversation', 'conversation-summary'];\n\n/** The shape asked for, validated as Python validates it, before any request. */\nexport function responseShapeOf(options: FetchOptions): string {\n const shape = opt<string>(options, 'response_shape', 'responseShape') ?? 'by_type';\n if (!(RESPONSE_SHAPES as readonly string[]).includes(shape)) {\n throw new InvalidInputError(\n `Invalid response_shape '${shape}'. Must be one of: ${RESPONSE_SHAPES.join(', ')}`,\n );\n }\n return shape;\n}\n\nconst REQUIRED_ID: Record<Scope, readonly [keyof FetchOptions, keyof FetchOptions] | null> = {\n user: ['user_id', 'userId'],\n customer: ['customer_id', 'customerId'],\n conversation: ['conversation_id', 'conversationId'],\n client: null,\n};\n\n/**\n * The scope's required id and, at user scope, the summary-mode options,\n * validated as Python validates them: before the anticipation cache, so a bad\n * value fails the same way whether or not a prefetched bundle would have\n * answered. Until 0.5.12 these ran only on the network path.\n */\nexport function scopeOptionsOf(\n scope: Scope,\n options: FetchOptions,\n): { contextMode: string; lastN: number } {\n const required = REQUIRED_ID[scope];\n if (required !== null && !opt<string>(options, required[0], required[1])) {\n throw new InvalidInputError(`${required[0]} is required`);\n }\n const contextMode = opt<string>(options, 'context_mode', 'contextMode') ?? 'in-conversation';\n const lastN = opt<number>(options, 'last_n_conversations', 'lastNConversations') ?? 1;\n if (scope !== 'user') return { contextMode, lastN };\n if (!VALID_CONTEXT_MODES.includes(contextMode)) {\n throw new InvalidInputError(\n `Invalid context_mode '${contextMode}'. Must be one of: ${VALID_CONTEXT_MODES.join(', ')}`,\n );\n }\n if (!Number.isInteger(lastN)) {\n throw new InvalidInputError('last_n_conversations must be an integer');\n }\n if (lastN < 0 || lastN > 20) {\n throw new InvalidInputError('last_n_conversations must be between 0 and 20');\n }\n return { contextMode, lastN };\n}\n\nconst VALID_MODES = ['fast', 'accurate'];\nconst VALID_PRECISION = ['high', 'medium'];\n\n/**\n * `mode` and `precision_level`, validated as Python validates them, before any\n * request. Without this a typo reached the server, which reads anything that\n * is not \"fast\" as \"accurate\": a slower, costlier read and no error.\n */\nexport function retrievalOptionsOf(options: FetchOptions): { mode: string; precisionLevel: string } {\n const mode = options.mode ?? 'fast';\n if (!VALID_MODES.includes(mode)) {\n throw new InvalidInputError(\n `Invalid mode '${mode}'. Must be one of: ${VALID_MODES.join(', ')}`,\n );\n }\n const precisionLevel = opt<string>(options, 'precision_level', 'precisionLevel') ?? 'high';\n if (!VALID_PRECISION.includes(precisionLevel)) {\n throw new InvalidInputError(\n `Invalid precision_level '${precisionLevel}'. Must be one of: ${VALID_PRECISION.join(', ')}`,\n );\n }\n return { mode, precisionLevel };\n}\n\n/** Keep local no-query answers subject to the wire request's query contract. */\nfunction validateSearchQuery(searchQuery: unknown): void {\n if (searchQuery === undefined || searchQuery === null) return;\n if (!Array.isArray(searchQuery) || searchQuery.some((query) => typeof query !== 'string')) {\n throw new InvalidInputError('search_query must be an array of strings when provided');\n }\n}\n\n/** Fetches and returns the RAW snake_case context, as the namespaced surface does. */\nexport async function fetchContext(\n transport: HttpTransport,\n scope: Scope,\n options: FetchOptions = {},\n hooks: FetchHooks = {},\n): Promise<RawContext> {\n // Anticipation cache FIRST, as Python does on all four scope fetches. Without\n // this the stream's bundles are never read and every fetch is a billed round\n // trip.\n const startedAt = Date.now();\n\n // Identity first, as Python requires initialize() before any fetch: the\n // cache lookup below filters on client_id and the B2C check on the\n // instance's isolation, and both come from whoami. Resolved once, on the\n // first request of a client that never called initialize().\n await transport.ready?.();\n\n // Before the anticipation cache, not after: a cached hit would otherwise let\n // an illegal shape through silently, which is the exact failure mode this\n // contract exists to remove.\n await transport.checkCustomerId(\n opt<string>(options, 'customer_id', 'customerId'),\n `${scope}.context.fetch`,\n );\n\n // Validated before the cache, like customer_id above, so a bad value fails\n // the same way whether or not a prefetched bundle would have answered.\n const responseShape = responseShapeOf(options);\n retrievalOptionsOf(options);\n const { contextMode } = scopeOptionsOf(scope, options);\n const searchQuery = opt<unknown>(options, 'search_query', 'searchQuery');\n validateSearchQuery(searchQuery);\n // Summary mode is a different read: a caller profile and past-conversation\n // summaries, assembled by the server. A prefetched bundle holds neither, and\n // with no search query the cache answered it with the newest bundle, so the\n // call-start read came back without a profile and no request was sent.\n const summaryMode = scope === 'user' && contextMode === 'conversation-summary';\n\n // No query: there is nothing to search for, and the search the server ran\n // instead embedded an empty string. Answered before the cache, as Python\n // answers it before its cache, and without the user-summary splice, which\n // Python's early return skips too.\n if (!summaryMode && hooks.withoutQuery && !hasQuery(searchQuery)) {\n const answer = await hooks.withoutQuery(scope, options);\n if (answer !== null) return applyResponseShape(answer, responseShape);\n }\n\n const finish = (response: RawContext): RawContext => {\n hooks.onResponse?.(scope, options, response);\n return response;\n };\n\n const conversationId = opt<string>(options, 'conversation_id', 'conversationId');\n const skipServerSt = conversationId ? hooks.skipServerShortTerm?.(conversationId) === true : false;\n\n const network = async (): Promise<RawContext> => {\n const { endpoint, body } = buildFetchRequest(\n scope,\n skipServerSt ? { ...options, include_conversation_context: false } : options,\n );\n const result = await transport.request<Json>(endpoint, { body });\n // The wrapper returned `result.context || {}`; preserve that exactly.\n return applyResponseShape((result?.['context'] as RawContext) ?? {}, responseShape);\n };\n\n // Awaited: matching by meaning embeds the query with the local model first.\n const anticipated = summaryMode ? null : (await hooks.beforeFetch?.(scope, options)) ?? null;\n if (anticipated !== null && anticipated.borderline) {\n // A borderline match races the server: its answer if in time, the cached\n // one if not. A late server call finishes unobserved.\n const pending = network();\n pending.catch(() => undefined);\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<null>((resolve) => {\n timer = setTimeout(() => resolve(null), anticipated.raceDeadlineMs ?? 250);\n });\n const won = await Promise.race([pending.then((r) => r, () => null), late]);\n if (timer !== undefined) clearTimeout(timer);\n if (won !== null) {\n hooks.onAssembled?.(scope, options, won, startedAt);\n return finish(won);\n }\n }\n if (anticipated !== null) {\n hooks.onServedFromCache?.(scope, options, anticipated);\n hooks.onAssembled?.(scope, options, anticipated.response, startedAt);\n // A hit is items picked from several prefetched bundles, so a ranked hit\n // is ordered by each item's own rank_score.\n return finish(applyResponseShape(anticipated.response, responseShape));\n }\n\n const response = await network();\n hooks.onAssembled?.(scope, options, response, startedAt);\n return finish(response);\n}\n","/**\n * camelCase normalisers for the legacy top-level methods.\n *\n * A faithful port of the normalisers in the removed `src/synap-client.js`,\n * including their quirks:\n *\n * - `score` and `source` on a memory item are passed through WITHOUT a\n * default, so `undefined` survives. Adding `?? 0` here would change the\n * shape consumers already branch on.\n * - `strength` falls back to `confidence`, `summary` falls back to `content`,\n * `intensity` falls back to `confidence`. Those fallbacks exist because the\n * server does not always send the specific field.\n * - `pickDefined` treats `null` as a real value and only skips `undefined`,\n * so an explicit server `null` is preserved rather than replaced.\n *\n * See gotcha G-B: this shape is one of two live shapes and must not converge\n * with the raw one before 2.0.\n */\n\nimport type {\n ConversationContext, ContextMetadata, Emotion, Episode, Fact, Json,\n NormalisedContext, Preference, RawContext, RawContextItem,\n RawConversationContext, RetrievalHealth, TemporalEvent, TemporalFields,\n} from './types.js';\n\n/** Returns the first argument that is not `undefined`. `null` counts as a value. */\nexport function pickDefined<T>(...values: (T | undefined)[]): T | undefined {\n for (const v of values) if (v !== undefined) return v;\n return undefined;\n}\n\nfunction pick<T>(...values: (T | undefined)[]): T {\n return pickDefined(...values) as T;\n}\n\nconst obj = (v: unknown): Json => (v as Json) ?? {};\n\n/** Always an array, so a caller can group by it without a null check. */\nfunction matchedQueries(item: RawContextItem = {}): string[] {\n const raw = item['matchedQueries'] ?? item.matched_queries;\n return Array.isArray(raw) ? (raw as string[]) : [];\n}\n\nfunction normalizeTemporalFields(item: RawContextItem = {}): TemporalFields {\n return {\n eventDate: pick(item['eventDate'] as string, item.event_date, null),\n eventEnd: pick(item['eventEnd'] as string, item.event_end as string, null),\n eventPrecision: pick(item['eventPrecision'] as string, item.event_precision as string, null),\n saidAt: pick(item['saidAt'] as string, item.said_at, null),\n validUntil: pick(item['validUntil'] as string, item.valid_until, null),\n temporalCategory: pick(item['temporalCategory'] as string, item.temporal_category, null),\n temporalConfidence: pick(item['temporalConfidence'] as number, item.temporal_confidence, 0),\n };\n}\n\nexport function normalizeFact(item: RawContextItem = {}): Fact {\n return {\n id: item.id || '',\n content: item.content || '',\n confidence: pick(item.confidence, 0),\n source: item.source || '',\n extractedAt: pick(item['extractedAt'] as string, item.extracted_at, null),\n metadata: obj(item.metadata),\n ...normalizeTemporalFields(item),\n matchedQueries: matchedQueries(item),\n };\n}\n\nexport function normalizePreference(item: RawContextItem = {}): Preference {\n return {\n id: item.id || '',\n category: (item['category'] as string) || '',\n content: item.content || '',\n strength: pick(item['strength'] as number, item.confidence, 0),\n source: item.source || '',\n extractedAt: pick(item['extractedAt'] as string, item.extracted_at, null),\n metadata: obj(item.metadata),\n ...normalizeTemporalFields(item),\n matchedQueries: matchedQueries(item),\n };\n}\n\nexport function normalizeEpisode(item: RawContextItem = {}): Episode {\n return {\n id: item.id || '',\n summary: pick(item['summary'] as string, item.content, ''),\n occurredAt: pick(item['occurredAt'] as string, item['occurred_at'] as string, null),\n significance: pick(item['significance'] as number, item.confidence, 0),\n participants: (item['participants'] as unknown[]) || [],\n metadata: obj(item.metadata),\n ...normalizeTemporalFields(item),\n matchedQueries: matchedQueries(item),\n };\n}\n\nexport function normalizeEmotion(item: RawContextItem = {}): Emotion {\n return {\n id: item.id || '',\n emotionType: pick(item['emotionType'] as string, item['emotion_type'] as string, ''),\n intensity: pick(item['intensity'] as number, item.confidence, 0),\n detectedAt: pick(item['detectedAt'] as string, item['detected_at'] as string, null),\n context: (item['context'] as string) || '',\n metadata: obj(item.metadata),\n ...normalizeTemporalFields(item),\n matchedQueries: matchedQueries(item),\n };\n}\n\nexport function normalizeTemporalEvent(item: RawContextItem = {}): TemporalEvent {\n return {\n id: item.id || '',\n content: item.content || '',\n eventDate: pick(item['eventDate'] as string, item.event_date, null),\n eventEnd: pick(item['eventEnd'] as string, item.event_end as string, null),\n eventPrecision: pick(item['eventPrecision'] as string, item.event_precision as string, null),\n saidAt: pick(item['saidAt'] as string, item.said_at, null),\n validUntil: pick(item['validUntil'] as string, item.valid_until, null),\n temporalCategory: pick(item['temporalCategory'] as string, item.temporal_category, ''),\n temporalConfidence: pick(item['temporalConfidence'] as number, item.temporal_confidence, 0),\n confidence: pick(item.confidence, 0),\n source: item.source || '',\n extractedAt: pick(item['extractedAt'] as string, item.extracted_at, null),\n metadata: obj(item.metadata),\n matchedQueries: matchedQueries(item),\n };\n}\n\nexport function normalizeContextMetadata(metadata: Json = {}): ContextMetadata {\n return {\n correlationId: pick(metadata['correlationId'] as string, metadata['correlation_id'] as string, ''),\n ttlSeconds: pick(metadata['ttlSeconds'] as number, metadata['ttl_seconds'] as number, 0),\n source: (metadata['source'] as string) || 'unknown',\n retrievedAt: pick(metadata['retrievedAt'] as string, metadata['retrieved_at'] as string, null),\n compactionApplied: pick(\n metadata['compactionApplied'] as boolean,\n metadata['compaction_applied'] as boolean,\n null,\n ),\n };\n}\n\nexport function normalizeConversationContext(\n value: RawConversationContext | null | undefined,\n): ConversationContext | null {\n if (!value) return null;\n return {\n summary: value.summary || null,\n currentState: pick(value['currentState'] as Json, value.current_state, {}),\n keyExtractions: pick(value['keyExtractions'] as Json, value.key_extractions, {}),\n recentTurns: pick(value['recentTurns'] as unknown[], value.recent_turns, []),\n compactionId: pick(value['compactionId'] as string, value.compaction_id, null),\n compactedAt: pick(value['compactedAt'] as string, value.compacted_at, null),\n conversationId: pick(value['conversationId'] as string, value.conversation_id, null),\n };\n}\n\nfunction normalizeRetrievalHealth(raw: unknown): RetrievalHealth | null {\n if (!raw || typeof raw !== 'object') return null;\n const r = raw as Json;\n const warnings = r['warnings'];\n return {\n degraded: r['degraded'] === undefined ? true : Boolean(r['degraded']),\n level: (r['level'] as string) ?? null,\n code: (r['code'] as string) ?? null,\n warnings: Array.isArray(warnings) ? warnings.map((w) => String(w)) : [],\n };\n}\n\n/** Accepts either a bare context or a `{ context: ... }` envelope, as the wrapper did. */\nexport function normalizeContextResponse(result: Json = {}): NormalisedContext {\n const context = (result['context'] as RawContext) ?? (result as RawContext);\n return {\n facts: (context.facts || []).map((i) => normalizeFact(i)),\n preferences: (context.preferences || []).map((i) => normalizePreference(i)),\n episodes: (context.episodes || []).map((i) => normalizeEpisode(i)),\n emotions: (context.emotions || []).map((i) => normalizeEmotion(i)),\n temporalEvents: (\n pick(context['temporalEvents'] as RawContextItem[], context.temporal_events, []) || []\n ).map((i) => normalizeTemporalEvent(i)),\n conversationContext: normalizeConversationContext(\n pick(\n context['conversationContext'] as RawConversationContext,\n context.conversation_context,\n null,\n ),\n ),\n metadata: normalizeContextMetadata(obj(context.metadata)),\n // `retrieval` is a SIBLING of `context` in the body, so it is read off the\n // envelope first and only then off a bare context. Reading it from\n // `context` alone is how the Python SDK dropped it.\n retrieval: normalizeRetrievalHealth(\n pick((result as Json)['retrieval'] as Json, (context as Json)['retrieval'] as Json, null),\n ),\n rawResponse: pick(context['rawResponse'] as Json, context['raw_response'] as Json, {}),\n // Only for a ranked fetch, so a by-type result has exactly the keys it had.\n ...(Array.isArray(context.items)\n ? { items: context.items, excerpts: Array.isArray(context.excerpts) ? context.excerpts : [] }\n : {}),\n };\n}\n","/**\n * Flatten typed context collections into one memory list.\n *\n * A faithful port of `flatten_context_items` from the 0.3.x bridge, which is\n * what `searchMemory` and `getMemories` returned. The per-type asymmetries are\n * deliberate and are reproduced exactly:\n *\n * - `memory` comes from a different field per type: fact/preference/temporal\n * event use `content`, episode uses `summary`, emotion uses `context`.\n * - `score` likewise: fact -> confidence, preference -> strength,\n * episode -> significance, emotion -> intensity, temporal event ->\n * temporal_confidence.\n * - **episode and emotion carry no `source` key at all.** The bridge simply\n * did not set one. Adding it would be an improvement and a shape change, so\n * it stays absent.\n * - Order is facts, preferences, episodes, emotions, temporal events.\n */\n\nimport type { Json, RawContext, RawContextItem } from './types.js';\n\nexport interface FlatMemory {\n id: string;\n memory: string;\n score: number;\n /** Absent for episodes and emotions, matching the 0.3.x bridge. */\n source?: string;\n metadata: Json;\n context_type: 'fact' | 'preference' | 'episode' | 'emotion' | 'temporal_event';\n event_date: string | null;\n /** See `TemporalFields.saidAt` in ./types. */\n said_at: string | null;\n valid_until: string | null;\n temporal_category: string | null;\n temporal_confidence: number;\n}\n\nconst s = (v: unknown): string => (typeof v === 'string' ? v : v == null ? '' : String(v));\nconst n = (v: unknown, d = 0): number => (typeof v === 'number' ? v : d);\nconst o = (v: unknown): Json => (v as Json) ?? {};\n/** The bridge stringified datetimes and mapped falsy to null. */\nconst dt = (v: unknown): string | null => (v ? String(v) : null);\n\nfunction temporal(item: RawContextItem) {\n return {\n event_date: dt(item['event_date']),\n said_at: dt(item['said_at']),\n valid_until: dt(item['valid_until']),\n temporal_category: (item['temporal_category'] as string | null) ?? null,\n temporal_confidence: n(item['temporal_confidence'], 0),\n };\n}\n\nexport function flattenContextItems(context: RawContext): FlatMemory[] {\n const items: FlatMemory[] = [];\n\n for (const f of context.facts ?? []) {\n items.push({\n id: s(f['id']), memory: s(f['content']), score: n(f['confidence']),\n source: s(f['source']), metadata: o(f['metadata']),\n context_type: 'fact', ...temporal(f),\n });\n }\n for (const p of context.preferences ?? []) {\n items.push({\n id: s(p['id']), memory: s(p['content']), score: n(p['strength']),\n source: s(p['source']), metadata: o(p['metadata']),\n context_type: 'preference', ...temporal(p),\n });\n }\n for (const e of context.episodes ?? []) {\n // No `source`: the bridge did not set one for episodes.\n items.push({\n id: s(e['id']), memory: s(e['summary']), score: n(e['significance']),\n metadata: o(e['metadata']), context_type: 'episode', ...temporal(e),\n });\n }\n for (const m of context.emotions ?? []) {\n // No `source` here either, and `memory` comes from `context`, not `content`.\n items.push({\n id: s(m['id']), memory: s(m['context']), score: n(m['intensity']),\n metadata: o(m['metadata']), context_type: 'emotion', ...temporal(m),\n });\n }\n for (const t of context.temporal_events ?? []) {\n items.push({\n id: s(t['id']), memory: s(t['content']), score: n(t['temporal_confidence']),\n source: s(t['source']), metadata: o(t['metadata']),\n context_type: 'temporal_event', ...temporal(t),\n });\n }\n\n return items;\n}\n","/**\n * Content parts: text and files (today, images) carried by `memories.create`,\n * `conversation.record_message` and `instance.send_message`.\n *\n * Mirrors `TextPart`, `FilePart` and `AttachmentResult` in the Python SDK.\n *\n * ## A text-only list is a string\n *\n * Every existing call has to keep sending exactly the bytes it sends today, so\n * a list with no file in it is joined with `\"\\n\"` and sent as that one string,\n * down the same route a string always took. Only a file changes the shape of a\n * request.\n *\n * ## Runs everywhere\n *\n * Nothing here imports a node builtin at the top level. Reading a `path` uses a\n * lazy `import('node:fs/promises')`, the same as `create_from_file`, and base64\n * uses `Buffer` when the runtime has it and `btoa` when it does not, so the main\n * entry stays safe on Edge, Workers and in a browser.\n */\n\nimport { InvalidInputError } from '../errors.js';\n\n/**\n * What the caller is asking a memory to do. Stored with the ingestion as\n * metadata; any other string is accepted too. Mirrors Python's `OBJECTIVES`.\n */\nexport const OBJECTIVES = [\n 'conversation', 'bootstrap', 'knowledge-base', 'record', 'profile',\n] as const;\nexport type Objective = (typeof OBJECTIVES)[number];\n\n/** Each file, however it is supplied. Larger is refused before anything is sent. */\nexport const MAX_FILE_BYTES = 10 * 1024 * 1024;\n/**\n * Total raw image bytes one `instance.send_message` event may carry. The gRPC\n * stream's message limit is 4 MB and base64 adds a third, so 2.5 MB of raw\n * bytes is what fits with room for the rest of the event.\n */\nexport const MAX_STREAM_IMAGE_BYTES = 2.5 * 1024 * 1024;\n/** A `url` part is fetched by the SDK, never by the server. */\nexport const URL_FETCH_TIMEOUT_MS = 30_000;\n\n/** Raw bytes for a `FilePart`. A Node `Buffer` is a `Uint8Array`. */\nexport type FileData = Uint8Array | ArrayBuffer | Blob;\n\nexport interface TextPart {\n type: 'text';\n text: string;\n}\n\n/**\n * A file. Exactly one of `data`, `path` or `url`.\n *\n * Build one with `filePart()`, which fills `filename` and `media_type`. A\n * literal `{ type: 'file', ... }` works too; the same defaults are applied when\n * it is sent.\n */\nexport interface FilePart {\n type: 'file';\n data?: FileData;\n /** Node only: read from disk when the call is made. */\n path?: string;\n /** Fetched by the SDK when the call is made (30 s, at most 10 MB). */\n url?: string;\n /** Defaults to the basename of `path` or `url`, else `\"file\"`. */\n filename?: string;\n /** Defaults to a guess from `filename`, else `\"application/octet-stream\"`. */\n media_type?: string;\n}\n\nexport interface FilePartInit {\n data?: FileData | null;\n path?: string | null;\n url?: string | null;\n filename?: string | null;\n media_type?: string | null;\n mediaType?: string | null;\n}\n\n/** One item of a content list. A bare string is a text part. */\nexport type ContentPart = string | TextPart | FilePart;\n\n/**\n * What the server did with one file of a `memories.create` call, in the order\n * the files were sent. Mirrors Python's `AttachmentResult`.\n */\nexport interface AttachmentResult {\n filename: string;\n media_type: string;\n status: 'read' | 'failed' | string;\n error?: string | null;\n}\n\n/**\n * Marks an object made by `textPart()` or `filePart()`.\n *\n * A plain object passed as `document` has always been a dict document, sent\n * untouched, and one may well carry `type: \"text\"` of its own. So at the top\n * level only a branded object is read as a part; inside a list (never valid\n * before parts existed) a plain `{ type: 'text' | 'file' }` is accepted too.\n * Non-enumerable, so it never reaches JSON or a deep-equality check, and\n * `Symbol.for` so two copies of the SDK (ESM and CJS) recognise each other's.\n */\nconst PART_BRAND = Symbol.for('@maximem/synap-js-sdk.ContentPart');\n\nfunction brand<T extends object>(part: T): T {\n Object.defineProperty(part, PART_BRAND, { value: true, enumerable: false });\n return part;\n}\n\nfunction isBranded(value: unknown): boolean {\n return typeof value === 'object' && value !== null && PART_BRAND in value;\n}\n\n/** `{ type: 'text', text }`. Mirrors Python's `TextPart(text)`. */\nexport function textPart(text: string): TextPart {\n if (typeof text !== 'string') throw new InvalidInputError('TextPart text must be a string');\n return brand({ type: 'text', text });\n}\n\n/**\n * A file part with its defaults filled in. Mirrors Python's `FilePart(...)`.\n *\n * Throws `InvalidInputError` unless exactly one of `data`, `path` or `url` is\n * given.\n */\nexport function filePart(init: FilePartInit): FilePart {\n const source = checkOneSource(init);\n const filename = defaultFilename(init, source);\n const mediaType =\n init.media_type ?? init.mediaType ?? defaultMediaType(filename, init.data ?? undefined);\n const part: FilePart = { type: 'file' };\n if (source === 'data') part.data = init.data as FileData;\n else if (source === 'path') part.path = init.path as string;\n else part.url = init.url as string;\n part.filename = filename;\n part.media_type = mediaType;\n return brand(part);\n}\n\nexport function isTextPart(value: unknown): value is TextPart {\n return isPlainPart(value) && value['type'] === 'text' && typeof value['text'] === 'string';\n}\n\nexport function isFilePart(value: unknown): value is FilePart {\n return isPlainPart(value) && value['type'] === 'file';\n}\n\nfunction isPlainPart(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\ntype Source = 'data' | 'path' | 'url';\n\nfunction checkOneSource(p: { data?: unknown; path?: unknown; url?: unknown }): Source {\n const given = (['data', 'path', 'url'] as const).filter(\n (k) => p[k] !== undefined && p[k] !== null,\n );\n if (given.length !== 1) {\n // Python's message, word for word.\n throw new InvalidInputError(\n 'FilePart takes exactly one of data, path or url' +\n (given.length > 0 ? ` (got ${given.join(', ')})` : ''),\n );\n }\n return given[0]!;\n}\n\nfunction lastSegment(p: string): string {\n const parts = p.split(/[\\\\/]/);\n return parts[parts.length - 1] ?? '';\n}\n\nfunction defaultFilename(\n p: { data?: unknown; path?: unknown; url?: unknown; filename?: string | null },\n source: Source,\n): string {\n if (p.filename) return p.filename;\n if (source === 'path') return lastSegment(String(p.path)) || 'file';\n if (source === 'url') {\n let pathname = '';\n try {\n pathname = new URL(String(p.url)).pathname;\n } catch {\n pathname = String(p.url).split(/[?#]/)[0] ?? '';\n }\n return lastSegment(pathname) || 'file';\n }\n // A browser `File` carries its own name. Python bytes cannot, so this only\n // ever fills a gap Python leaves as \"file\".\n const named = (p.data as { name?: unknown } | undefined)?.name;\n return typeof named === 'string' && named ? named : 'file';\n}\n\n/**\n * Python's table (png, jpg, jpeg, webp, gif, pdf) plus what its\n * `mimetypes.guess_type` answers for other common extensions. Case-insensitive,\n * as Python's is. The server sniffs image bytes regardless, so a wrong or\n * missing guess is corrected there, never trusted.\n */\nconst MEDIA_TYPES: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n jpe: 'image/jpeg',\n webp: 'image/webp',\n gif: 'image/gif',\n bmp: 'image/bmp',\n tif: 'image/tiff',\n tiff: 'image/tiff',\n svg: 'image/svg+xml',\n pdf: 'application/pdf',\n txt: 'text/plain',\n csv: 'text/csv',\n htm: 'text/html',\n html: 'text/html',\n json: 'application/json',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n mp3: 'audio/mpeg',\n wav: 'audio/x-wav',\n mp4: 'video/mp4',\n};\n\nexport function guessMediaType(filename: string): string | null {\n const dot = filename.lastIndexOf('.');\n // Python's splitext gives \".png\" no extension, so neither does this.\n if (dot <= 0) return null;\n const ext = filename.slice(dot + 1).toLowerCase();\n return MEDIA_TYPES[ext] ?? null;\n}\n\nfunction defaultMediaType(filename: string, data?: unknown): string {\n const guessed = guessMediaType(filename);\n if (guessed !== null) return guessed;\n const blobType = (data as { type?: unknown } | undefined)?.type;\n return typeof blobType === 'string' && blobType ? blobType : DEFAULT_MEDIA_TYPE;\n}\n\n/**\n * The outcome of normalising a content value.\n *\n * `text`: send this string exactly as a string always was sent.\n * `parts`: at least one file; strings have become text parts, in order.\n */\nexport type Normalised =\n | { kind: 'text'; text: string }\n | { kind: 'parts'; parts: Array<TextPart | FilePart> };\n\n/**\n * Normalise a part, or a list of parts, for the field named `field`.\n *\n * Returns null for anything that is neither: a string, or a dict document,\n * which the caller passes through untouched so its bytes do not change. A\n * single part counts only when `textPart()` or `filePart()` made it; a plain\n * object is a dict, as it always was.\n */\nexport function normaliseContent(value: unknown, field: string): Normalised | null {\n if (isBranded(value) && isTextPart(value)) return { kind: 'text', text: value.text };\n if (isBranded(value) && isFilePart(value)) return { kind: 'parts', parts: [value] };\n if (!Array.isArray(value)) return null;\n if (value.length === 0) {\n // Explicit: an empty array is truthy, so the `!document` check that\n // guards a string never sees it.\n throw new InvalidInputError(`${field} is an empty list; pass at least one part`);\n }\n const parts: Array<TextPart | FilePart> = value.map((item, i) => {\n if (typeof item === 'string') return { type: 'text', text: item };\n if (isTextPart(item) || isFilePart(item)) return item;\n throw new InvalidInputError(\n `${field}[${i}] is a ${typeName(item)}; expected a string, TextPart or FilePart`,\n );\n });\n if (!parts.some(isFilePart)) {\n return { kind: 'text', text: parts.map((p) => (p as TextPart).text).join('\\n') };\n }\n return { kind: 'parts', parts };\n}\n\nfunction typeName(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n if (typeof value === 'object') {\n return (value as { constructor?: { name?: string } }).constructor?.name ?? 'object';\n }\n return typeof value;\n}\n\n/** A file's resolved name, type and bytes. */\nexport interface ResolvedFile {\n filename: string;\n media_type: string;\n bytes: Uint8Array;\n}\n\n/**\n * Read a file part's bytes: from `data`, from disk, or over HTTP.\n *\n * `fetchImpl` is the transport's fetch, so a test or a proxying caller sees\n * the request. It is called with no Synap credentials: the URL belongs to\n * somebody else.\n */\nexport async function resolveFile(part: FilePart, fetchImpl: typeof fetch): Promise<ResolvedFile> {\n const source = checkOneSource(part);\n const filename = defaultFilename(part, source);\n let mediaType = part.media_type || defaultMediaType(filename, part.data);\n\n let bytes: Uint8Array;\n if (source === 'data') {\n bytes = await toBytes(part.data as FileData);\n } else if (source === 'path') {\n // Lazy, so importing the SDK on Edge or in a Worker stays safe: a\n // top-level `node:fs` import fails the BUILD there, not the call.\n const { readFile } = await import('node:fs/promises');\n try {\n bytes = new Uint8Array(await readFile(part.path as string));\n } catch (error) {\n throw new InvalidInputError(\n `Could not read FilePart path '${part.path}': ${(error as Error)?.message ?? String(error)}`,\n { cause: error },\n );\n }\n } else {\n const fetched = await fetchUrl(part.url as string, fetchImpl);\n bytes = fetched.bytes;\n // The filename said nothing useful, so trust what the server said, as\n // Python does.\n if (mediaType === DEFAULT_MEDIA_TYPE && fetched.contentType) mediaType = fetched.contentType;\n }\n if (bytes.byteLength > MAX_FILE_BYTES) {\n throw new InvalidInputError(\n `${filename} is ${bytes.byteLength} bytes; the limit is ${MAX_FILE_BYTES} bytes per file`,\n );\n }\n return { filename, media_type: mediaType, bytes };\n}\n\nconst DEFAULT_MEDIA_TYPE = 'application/octet-stream';\n\nfunction urlTooLarge(url: string): string {\n return `FilePart url '${url}' is over the limit of ${MAX_FILE_BYTES} bytes per file`;\n}\n\nasync function toBytes(data: FileData): Promise<Uint8Array> {\n if (data instanceof Uint8Array) return data;\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n if (ArrayBuffer.isView(data)) {\n const view = data as ArrayBufferView;\n return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n }\n if (typeof Blob !== 'undefined' && data instanceof Blob) {\n return new Uint8Array(await data.arrayBuffer());\n }\n throw new InvalidInputError('FilePart data must be a Uint8Array, ArrayBuffer or Blob');\n}\n\n/** GET a URL, at most 10 MB, within 30 s. Every failure is the caller's input. */\nexport async function fetchUrlBytes(url: string, fetchImpl: typeof fetch): Promise<Uint8Array> {\n return (await fetchUrl(url, fetchImpl)).bytes;\n}\n\nasync function fetchUrl(\n url: string,\n fetchImpl: typeof fetch,\n): Promise<{ bytes: Uint8Array; contentType: string | null }> {\n let scheme = '';\n try {\n scheme = new URL(url).protocol;\n } catch {\n throw new InvalidInputError(`Could not fetch FilePart url '${url}': not a valid URL`);\n }\n // What httpx supports, so the same URLs fail in both SDKs.\n if (scheme !== 'http:' && scheme !== 'https:') {\n throw new InvalidInputError(\n `Could not fetch FilePart url '${url}': only http and https are supported`,\n );\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), URL_FETCH_TIMEOUT_MS);\n try {\n const response = await fetchImpl(url, { method: 'GET', signal: controller.signal });\n if (response.status < 200 || response.status >= 300) {\n throw new InvalidInputError(\n `Fetching FilePart url '${url}' returned HTTP ${response.status}`,\n );\n }\n const declared = Number(response.headers.get('content-length') ?? '');\n if (Number.isFinite(declared) && declared > MAX_FILE_BYTES) {\n throw new InvalidInputError(urlTooLarge(url));\n }\n const bytes = await readCapped(response, url);\n const rawType = response.headers.get('content-type');\n const contentType = rawType ? rawType.split(';', 1)[0]!.trim().toLowerCase() || null : null;\n return { bytes, contentType };\n } catch (error) {\n if (error instanceof InvalidInputError) throw error;\n if (controller.signal.aborted) {\n throw new InvalidInputError(\n `Could not fetch FilePart url '${url}': timed out after ${URL_FETCH_TIMEOUT_MS / 1000} s`,\n { cause: error },\n );\n }\n throw new InvalidInputError(\n `Could not fetch FilePart url '${url}': ${(error as Error)?.message ?? String(error)}`,\n { cause: error },\n );\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Stops reading as soon as the body passes the cap, rather than buffering all of it. */\nasync function readCapped(response: Response, url: string): Promise<Uint8Array> {\n const body = response.body;\n if (body === null || typeof body.getReader !== 'function') {\n return new Uint8Array(await response.arrayBuffer());\n }\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > MAX_FILE_BYTES) {\n await reader.cancel().catch(() => {});\n throw new InvalidInputError(urlTooLarge(url));\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let at = 0;\n for (const c of chunks) {\n out.set(c, at);\n at += c.byteLength;\n }\n return out;\n}\n\n/** Standard base64. `Buffer` where there is one, chunked `btoa` everywhere else. */\nexport function toBase64(bytes: Uint8Array): string {\n const B = (globalThis as { Buffer?: { from(b: Uint8Array): { toString(enc: string): string } } })\n .Buffer;\n if (B !== undefined) return B.from(bytes).toString('base64');\n let binary = '';\n const CHUNK = 0x8000;\n for (let i = 0; i < bytes.length; i += CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));\n }\n return btoa(binary);\n}\n\n/** `{type: \"text\", text}` on the wire. */\nexport interface WireTextPart {\n type: 'text';\n text: string;\n}\n\n/** A file in a `memories.create` multipart manifest; its bytes are the form field `field`. */\nexport interface WireFilePart {\n type: 'file';\n field: string;\n filename: string;\n media_type: string;\n}\n\n/** A file carried inline as base64 (record_message JSON, the gRPC metadata key). */\nexport interface WireImagePart {\n type: 'image';\n filename: string;\n media_type: string;\n data: string;\n}\n\n/**\n * What an image becomes in text where it cannot be read: `[image: <filename>]`.\n * Text parts stay as they are and the pieces are joined with `\"\\n\"`.\n */\nexport function placeholderText(parts: Array<{ type: string; text?: string; filename?: string }>): string {\n return parts\n .map((p) => (p.type === 'text' ? String(p.text ?? '') : `[image: ${p.filename || 'image'}]`))\n .join('\\n');\n}\n\nexport interface InlineParts {\n /** Text and inline-image wire parts, in order. */\n wire: Array<WireTextPart | WireImagePart>;\n /** The placeholder rendering of `wire`. */\n placeholder: string;\n /** Raw bytes across every file, before base64. */\n rawBytes: number;\n}\n\n/** Read every file (concurrently, order kept) and inline it as base64. */\nexport async function toInlineParts(\n parts: Array<TextPart | FilePart>,\n fetchImpl: typeof fetch,\n): Promise<InlineParts> {\n const resolved = await Promise.all(\n parts.map((p) => (isFilePart(p) ? resolveFile(p, fetchImpl) : null)),\n );\n let rawBytes = 0;\n const wire = parts.map((p, i): WireTextPart | WireImagePart => {\n const file = resolved[i];\n if (file === null || file === undefined) return { type: 'text', text: (p as TextPart).text };\n rawBytes += file.bytes.byteLength;\n return {\n type: 'image',\n filename: file.filename,\n media_type: file.media_type,\n data: toBase64(file.bytes),\n };\n });\n return { wire, placeholder: placeholderText(wire), rawBytes };\n}\n","/**\n * Memories namespace. Mirrors `maximem_synap.memories.interface.MemoriesInterface`.\n *\n * ## The request body is built the way Python builds it, on purpose\n *\n * Python constructs a pydantic `CreateMemoryRequest` and posts\n * `model_dump(mode=\"json\")`, which emits **every** field, nulls included, with\n * defaults applied. It is tempting to omit unset keys instead and send a\n * tidier body. Do not: the server sees a different request, and the difference\n * that matters most is `document_type`.\n *\n * `document_type` defaults to `\"ai-chat-conversation\"`. Leaving it off is not\n * neutral, because the extraction path is type-dependent and the\n * `\"document\"` type extracts dramatically less from the same text. A body that\n * merely looks cleaner is how you get \"the JS SDK stores fewer memories than\n * the Python one from identical input\", which is slow and miserable to\n * diagnose.\n */\n\nimport { InvalidInputError } from '../errors.js';\nimport type { HttpTransport } from '../transport/http.js';\nimport type { Json } from '../context/types.js';\nimport {\n isFilePart, normaliseContent, resolveFile,\n type AttachmentResult, type FilePart, type Objective, type TextPart, type WireFilePart,\n type WireTextPart,\n} from './parts.js';\n\n/**\n * What `new Blob([...])` accepts here.\n *\n * Derived from the Blob constructor rather than written out, because `BlobPart`\n * lives in the DOM lib, which this package deliberately does not include, and\n * Node's own Blob accepts a slightly narrower set than the DOM's. Deriving it\n * means this keeps compiling if either definition shifts.\n */\ntype BlobSource = NonNullable<ConstructorParameters<typeof Blob>[0]>[number];\n\n/** Mirrors the Python DocumentType enum. */\nexport const DOCUMENT_TYPES = [\n 'ai-chat-conversation', 'document', 'email', 'pdf', 'image', 'audio', 'meeting-transcript',\n] as const;\nexport type DocumentType = (typeof DOCUMENT_TYPES)[number];\n\n/** Mirrors the Python IngestMode enum. */\nexport const INGEST_MODES = ['fast', 'long-range'] as const;\nexport type IngestMode = (typeof INGEST_MODES)[number];\n\nexport const DEFAULT_DOCUMENT_TYPE: DocumentType = 'ai-chat-conversation';\nexport const DEFAULT_INGEST_MODE: IngestMode = 'long-range';\n\n/**\n * What `memories.create` takes as `document`. Mirrors Python's\n * `Union[str, Dict[str, Any], TextPart, FilePart, List[Union[str, TextPart, FilePart]]]`.\n *\n * A string, a dict, a `TextPart` or a list with no file in it is sent as JSON\n * to `/create`, byte for byte as a string always was (a list is joined with\n * `\"\\n\"`). Any `FilePart` sends the call as multipart to `/create-multipart`.\n */\nexport type CreateDocument =\n | string\n | Record<string, unknown>\n | TextPart\n | FilePart\n | Array<string | TextPart | FilePart>;\n\nexport interface CreateMemoryOptions {\n document: CreateDocument;\n user_id?: string | null;\n userId?: string | null;\n customer_id?: string | null;\n customerId?: string | null;\n document_type?: DocumentType | string;\n documentType?: DocumentType | string;\n document_id?: string | null;\n documentId?: string | null;\n /** ISO-8601 string or Date. Serialised the way Python serialises a datetime. */\n document_created_at?: string | Date | null;\n documentCreatedAt?: string | Date | null;\n mode?: IngestMode | string;\n metadata?: Json;\n /**\n * The level this memory belongs to, named in full, one entry per level down\n * to it: `{ customer: \"acme\", team: \"payments\", user: \"dana\" }`.\n *\n * Only needed by an account whose scope ladder has a level between its\n * customer and its user levels. `user_id` and `customer_id` cannot say which\n * one a write belongs to, so on such a ladder the server refuses the write\n * rather than guessing: a wrong guess at or above the customer level crosses\n * a tenant boundary.\n *\n * Omit it and nothing changes. Sending one to an account without nested\n * scoping is an error rather than ignored, because a caller who asks to be\n * narrowed and is ignored gets widened instead.\n */\n scope?: Record<string, string> | null;\n /**\n * What this memory is for. One of `OBJECTIVES` (`conversation`, `bootstrap`,\n * `knowledge-base`, `record`, `profile`) or free text, at most 500\n * characters. Sent only when set, so a call without it is unchanged.\n */\n objective?: Objective | string | null;\n}\n\n/**\n * Mirrors Python's `CreateMemoryResponse`.\n *\n * The first four fields are required there (Pydantic would raise if the server\n * omitted one), so they are required here too. Declaring `ingestion_id` optional\n * made the commonest two-line pattern in the docs fail to compile under strict\n * TypeScript: `wait_for_completion(result.ingestion_id)` cannot take\n * `string | undefined`.\n */\nexport interface CreateMemoryResult {\n ingestion_id: string;\n document_id: string;\n status: string;\n /** ISO-8601. Python types this as a datetime. */\n queued_at: string;\n error_message?: string | null;\n memories_created?: number;\n /**\n * One per file part, in order, when the call carried files. Absent\n * otherwise. A file that could not be read is still `failed` here while the\n * rest of the document was ingested.\n */\n attachments?: AttachmentResult[] | null;\n [key: string]: unknown;\n}\n\nfunction either<T>(o: Record<string, unknown>, snake: string, camel: string): T | undefined {\n const a = o[snake];\n if (a !== undefined) return a as T;\n const b = o[camel];\n return b === undefined ? undefined : (b as T);\n}\n\nfunction isoOrNull(v: string | Date | null | undefined): string | null {\n if (v === undefined || v === null) return null;\n return v instanceof Date ? v.toISOString() : v;\n}\n\n/**\n * The fields every create carries besides `document`, validated, in the\n * pydantic model's order. `documentType` is null only for the multipart\n * manifest, where an unset type is sent as null and the server picks.\n */\nfunction createFields(options: CreateMemoryOptions, defaultType: string | null): Json {\n const o = options as unknown as Record<string, unknown>;\n const documentType = either<string>(o, 'document_type', 'documentType') ?? defaultType;\n const mode = (options.mode as string) ?? DEFAULT_INGEST_MODE;\n\n // Validated client-side because Python's enum coercion raises before any\n // request is sent. A silent pass-through would turn a typo into a server\n // error, or worse, a silently different extraction path.\n if (documentType !== null && !(DOCUMENT_TYPES as readonly string[]).includes(documentType)) {\n throw new InvalidInputError(\n `Invalid document_type '${documentType}'. Expected one of: ${DOCUMENT_TYPES.join(', ')}`,\n );\n }\n if (!(INGEST_MODES as readonly string[]).includes(mode)) {\n throw new InvalidInputError(\n `Invalid mode '${mode}'. Expected one of: ${INGEST_MODES.join(', ')}`,\n );\n }\n const userId = either<string>(o, 'user_id', 'userId') ?? null;\n const customerId = either<string>(o, 'customer_id', 'customerId') ?? null;\n\n // Key order matches the pydantic model's field order. Not semantically\n // required, but it makes a captured-body diff against Python readable.\n const fields: Json = {\n document_type: documentType,\n document_id: either<string>(o, 'document_id', 'documentId') ?? null,\n document_created_at: isoOrNull(\n either<string | Date>(o, 'document_created_at', 'documentCreatedAt'),\n ),\n user_id: userId,\n customer_id: customerId,\n // null, never `{}`. An empty path is not absence: the server treats one as\n // an error, because a caller asking to be narrowed and being ignored gets\n // widened instead.\n scope: normaliseCreateScope(options.scope, userId, customerId),\n mode,\n metadata: options.metadata ?? {},\n };\n // Only when set, so every existing body stays byte-identical.\n if (options.objective !== undefined && options.objective !== null) {\n fields['objective'] = options.objective;\n }\n return fields;\n}\n\n/**\n * `scope: { client: \"self\" }` names the client level, which is what a write\n * with no user_id and no customer_id already is. Mirrors Python's\n * `CreateMemoryRequest` validator.\n *\n * - On its own, it is sent as `scope: null`, so the body is the one a call\n * without it sends.\n * - With a user_id or customer_id, it is a contradiction, refused.\n * - `\"self\"` under any key alongside other entries is refused.\n * - Every other use of a `client` key is passed through untouched.\n */\nexport function normaliseCreateScope(\n scope: Record<string, string> | null | undefined,\n userId: string | null,\n customerId: string | null,\n): Record<string, string> | null {\n if (scope === undefined || scope === null) return null;\n const entries = Object.entries(scope);\n if (entries.length > 1 && entries.some(([, v]) => v === 'self')) {\n throw new InvalidInputError(\n `\"self\" can only be used alone, as scope={\"client\": \"self\"}; got ${JSON.stringify(scope)}`,\n );\n }\n if (entries.length === 1 && entries[0]![0] === 'client' && entries[0]![1] === 'self') {\n // Python checks `is not None`, so an empty-string id counts as given.\n if (userId !== null || customerId !== null) {\n throw new InvalidInputError(\n 'scope={\"client\": \"self\"} names the client level, so it ' +\n 'cannot be combined with user_id or customer_id',\n );\n }\n return null;\n }\n return scope;\n}\n\n/** What `document` becomes on the JSON route: a string, or a dict untouched. */\nfunction jsonDocument(document: unknown, where: string): unknown {\n const n = normaliseContent(document, 'document');\n if (n === null) return document;\n if (n.kind === 'parts') {\n throw new InvalidInputError(\n `${where} cannot carry a FilePart. memories.create sends files as multipart; ` +\n 'call it once per document that has files.',\n );\n }\n return n.text;\n}\n\n/**\n * Byte-for-byte equivalent of Python's `CreateMemoryRequest.model_dump(mode=\"json\")`.\n *\n * Takes the JSON-route shapes only: a string, a dict, a `TextPart`, or a list\n * with no file in it (joined with `\"\\n\"`). A `FilePart` throws; it is sent by\n * `memories.create` as multipart, built by `buildCreateManifest`.\n */\nexport function buildCreateBody(options: CreateMemoryOptions): Json {\n const document = jsonDocument(options.document, 'This request');\n if (!document) throw new InvalidInputError('document is required');\n return { document, ...createFields(options, DEFAULT_DOCUMENT_TYPE) };\n}\n\n/**\n * The `manifest` form field of a multipart create, before any file is read.\n *\n * `document` lists the parts in order; file `i` (counting files only) is the\n * form field `file_<i>`. `document_type` is null unless the caller set it.\n */\nexport function buildCreateManifest(\n options: CreateMemoryOptions,\n parts: Array<TextPart | FilePart>,\n files: Array<{ filename: string; media_type: string }>,\n): Json {\n let next = 0;\n const document = parts.map((p): WireTextPart | WireFilePart => {\n if (!isFilePart(p)) return { type: 'text', text: (p as TextPart).text };\n const index = next++;\n const file = files[index]!;\n return { type: 'file', field: `file_${index}`, filename: file.filename, media_type: file.media_type };\n });\n return { document, ...createFields(options, null) };\n}\n\n/**\n * Result of `memories.batch_create`, mirroring Python's `BatchCreateResponse`.\n * It was `Json`, so `results` came back as `unknown` and could not be iterated.\n */\nexport interface BatchCreateResult {\n batch_id: string;\n total: number;\n succeeded: number;\n failed: number;\n results: CreateMemoryResult[];\n [key: string]: unknown;\n}\n\nexport interface BatchCreateOptions {\n documents: CreateMemoryOptions[];\n fail_fast?: boolean;\n failFast?: boolean;\n}\n\n/** Mirrors the Python ForgetMode enum. */\nexport const FORGET_MODES = ['preview', 'direct'] as const;\nexport type ForgetMode = (typeof FORGET_MODES)[number];\n\nexport const FORGET_DESCRIPTION_MIN = 3;\nexport const FORGET_DESCRIPTION_MAX = 500;\n\nexport interface ForgetOptions {\n /** What to forget, in the user's own words (3 to 500 characters). */\n description: string;\n user_id?: string | null;\n userId?: string | null;\n customer_id?: string | null;\n customerId?: string | null;\n /**\n * The level to search, named in full, one entry per level down to it:\n * `{ customer: \"acme\", team: \"payments\", user: \"dana\" }`. Only needed when\n * your scope ladder has a level between customer and user.\n */\n scope?: Record<string, string> | null;\n /** `\"preview\"` (default) or `\"direct\"`. See `MemoriesInterface.forget`. */\n mode?: ForgetMode | string;\n /**\n * The conversation this request is made in (1 to 200 characters). Used only\n * by `mode: \"direct\"`. Pass it when you record the conversation through the\n * SDK's listening stream (gRPC): messages on that path are saved in batches,\n * so what the user just said may not exist as a memory yet. With the id, the\n * request also stays open until the batch of that conversation that holds it\n * has been saved and checked, whether or not the search finds something now,\n * and removes what it describes then (`retry_scheduled` is true). Without it,\n * the request is answered once (`nothing_matches` if nothing is found) and\n * nothing waits. Not needed for `memories.create()`.\n */\n conversation_id?: string | null;\n conversationId?: string | null;\n}\n\n/** A memory the description matched. Mirrors Python's `ForgetCandidate`. */\nexport interface ForgetCandidate {\n memory_id: string;\n content: string;\n memory_type?: string | null;\n /** `\"memory\"`, or where a copy lives: chunk, sentence, entity, triple, profile, candidate. */\n store?: string;\n}\n\nexport type ForgetStatus = 'nothing_matches' | 'preview' | 'deleted' | 'partial';\n\n/** Result of `memories.forget`. Mirrors Python's `ForgetResponse`. */\nexport interface ForgetResult {\n status: ForgetStatus;\n request_id: string | null;\n candidates: ForgetCandidate[];\n deleted_ids: string[];\n failed_ids: string[];\n still_present_in: string[];\n may_be_incomplete: boolean;\n /**\n * True when a `direct` request named its `conversation_id` and stays open until\n * the batch of that conversation that holds it has been saved and checked,\n * whether or not the search found something now. Absent from servers that\n * predate it; read it as false.\n */\n retry_scheduled?: boolean;\n}\n\n/** The body Python builds for `memories.forget`, key order included. */\nexport function buildForgetBody(options: ForgetOptions): Json {\n const description = options.description;\n if (\n typeof description !== 'string' ||\n // Code points, as Python's len() and the server count; `.length` counts\n // UTF-16 units, so 251 emoji (502 units) were refused here only.\n [...description].length < FORGET_DESCRIPTION_MIN ||\n [...description].length > FORGET_DESCRIPTION_MAX\n ) {\n throw new InvalidInputError(\n `description must be between ${FORGET_DESCRIPTION_MIN} and ${FORGET_DESCRIPTION_MAX} characters`,\n );\n }\n const mode = (options.mode as string | undefined) ?? 'preview';\n if (!(FORGET_MODES as readonly string[]).includes(mode)) {\n throw new InvalidInputError(\n `Invalid mode '${mode}'. Expected one of: ${FORGET_MODES.join(', ')}`,\n );\n }\n const o = options as unknown as Record<string, unknown>;\n const body: Record<string, unknown> = {\n description,\n user_id: either<string>(o, 'user_id', 'userId') ?? null,\n customer_id: either<string>(o, 'customer_id', 'customerId') ?? null,\n scope: options.scope ?? null,\n mode,\n };\n // Sent only when given, as Python does, so a call without it is unchanged.\n const conversationId = either<string>(o, 'conversation_id', 'conversationId');\n if (conversationId !== undefined && conversationId !== null) {\n if (\n typeof conversationId !== 'string' ||\n [...conversationId].length < 1 ||\n [...conversationId].length > 200\n ) {\n throw new InvalidInputError('conversation_id must be a string of 1 to 200 characters');\n }\n body['conversation_id'] = conversationId;\n }\n return body as Json;\n}\n\nexport interface MemoriesInterface {\n create(options: CreateMemoryOptions): Promise<CreateMemoryResult>;\n batch_create(options: BatchCreateOptions): Promise<BatchCreateResult>;\n create_from_file(options: CreateFromFileOptions): Promise<CreateMemoryResult>;\n get(memoryId: string): Promise<Json>;\n update(options: UpdateMemoryOptions): Promise<Json>;\n delete(memoryId: string): Promise<Json>;\n /**\n * Forget memories by describing them in the user's own words. Use it when\n * you do not hold memory ids; to delete one memory by id, use `delete()`.\n *\n * The call must be scoped to exactly one user: pass `user_id`, plus\n * `customer_id` on a B2B instance. Otherwise the server answers 400, raised\n * as `InvalidInputError`.\n *\n * Modes:\n * - `\"preview\"` (default): files a pending request that a person approves in\n * the dashboard under Deletion requests. Deletes nothing. `candidates`\n * lists what matched.\n * - `\"direct\"`: finds and soft-deletes in one call. Not idempotent as a\n * request: a repeat is harmless and finds nothing new, but it is a new\n * request.\n *\n * `status` is `\"nothing_matches\"`, `\"preview\"`, `\"deleted\"` or `\"partial\"`.\n * `\"partial\"` means the memories are hidden but a store named in\n * `still_present_in` may still hold the text, so do not tell an end user it\n * was removed unless `status === \"deleted\"`. `failed_ids` lists memories that\n * could not be deleted; `may_be_incomplete` is true when the match may not\n * have covered everything.\n *\n * Errors: `InvalidInputError` for 400/422 or a bad `description`/`mode`\n * caught before sending; `ServiceUnavailableError` for 503 (the matcher was\n * unavailable and nothing was deleted, so trying again is safe; the\n * transport applies its normal retry policy first); `RateLimitError` for 429.\n */\n forget(options: ForgetOptions): Promise<ForgetResult>;\n status(ingestionId: string): Promise<Json>;\n wait_for_completion(ingestionId: string, options?: WaitOptions): Promise<Json>;\n}\n\n/**\n * Options for `create_from_file`.\n *\n * Exactly one of `file_path`, `file`, or `text` must be supplied, matching\n * Python. `file_path` reads from disk and so is Node-only; `file` takes a\n * Blob/File/Uint8Array and works anywhere, which is the portable route for\n * Edge and Workers.\n */\nexport interface CreateFromFileOptions {\n user_id?: string;\n userId?: string;\n customer_id?: string;\n customerId?: string;\n /** \"b2b\" or \"b2c\". Defaults to \"b2c\", as in Python. */\n relationship_type?: string;\n relationshipType?: string;\n /** Node-only: read this path from disk. Uses a lazy `node:fs` import. */\n file_path?: string;\n filePath?: string;\n /** Portable alternative to `file_path`. Pass `filename` alongside a raw buffer. */\n file?: Blob | Uint8Array | ArrayBuffer;\n filename?: string;\n /** Ingest raw text instead of a file. */\n text?: string;\n document_type?: string;\n documentType?: string;\n mode?: IngestMode | string;\n metadata?: Json;\n /**\n * The level this memory belongs to, named in full, one entry per level down\n * to it: `{ customer: \"acme\", team: \"payments\", user: \"dana\" }`.\n *\n * Only needed by an account whose scope ladder has a level between its\n * customer and its user levels. `user_id` and `customer_id` cannot say which\n * one a write belongs to, so on such a ladder the server refuses the write\n * rather than guessing: a wrong guess at or above the customer level crosses\n * a tenant boundary.\n *\n * Omit it and nothing changes. Sending one to an account without nested\n * scoping is an error rather than ignored, because a caller who asks to be\n * narrowed and is ignored gets widened instead.\n */\n scope?: Record<string, string> | null;\n}\n\nexport interface UpdateMemoryOptions {\n memory_id?: string;\n memoryId?: string;\n document: string;\n merge_strategy?: string;\n mergeStrategy?: string;\n document_type?: string;\n documentType?: string;\n metadata?: Json;\n}\n\nexport interface WaitOptions {\n /** Seconds. Matches Python's default. */\n timeout_seconds?: number;\n timeoutSeconds?: number;\n poll_interval_seconds?: number;\n pollIntervalSeconds?: number;\n signal?: AbortSignal;\n}\n\n// The server's statuses are queued, processing, completed, failed and\n// partial_success. Python stops on the last three; 'error' and 'cancelled' are\n// never emitted by the server and are kept only so an older value still stops.\nconst TERMINAL_STATUSES = new Set(['completed', 'failed', 'partial_success', 'error', 'cancelled']);\n\nexport function createMemoriesInterface(\n transport: HttpTransport,\n // Called after a forget that deleted something, so the caller can stop serving\n // that user's cached context. Mirrors Python's `_evict_forgotten`.\n onForgotten?: (ids: { userId: string | null; customerId: string | null }) => void,\n): MemoriesInterface {\n return {\n async create(options) {\n const o = options as unknown as Record<string, unknown>;\n const customerId = o['customer_id'] ?? o['customerId'];\n if (customerId !== undefined && customerId !== null && customerId !== '') {\n await transport.checkCustomerId(customerId, 'memories.create');\n }\n const n = normaliseContent(options.document, 'document');\n if (n === null || n.kind === 'text') {\n return transport.request<CreateMemoryResult>('memories_create', {\n body: buildCreateBody(options),\n });\n }\n\n // Everything but the files is validated before any file is read, so a\n // typo in document_type does not cost a 10 MB download first.\n buildCreateManifest(options, n.parts.filter((p) => !isFilePart(p)), []);\n const fetchImpl = ((url: string, init?: RequestInit) =>\n transport.fetchExternal(url, init)) as typeof fetch;\n const files = await Promise.all(\n n.parts.filter(isFilePart).map((p) => resolveFile(p, fetchImpl)),\n );\n\n const form = new FormData();\n form.set('manifest', JSON.stringify(buildCreateManifest(options, n.parts, files)));\n files.forEach((file, i) => {\n form.set(\n `file_${i}`,\n new Blob([file.bytes as unknown as BlobSource], { type: file.media_type }),\n file.filename,\n );\n });\n // Not retried: the endpoint is declared non-idempotent, as /create is.\n return transport.request<CreateMemoryResult>('memories_create_multipart', {\n body: form,\n rawBody: true,\n // A server older than this route answers 404, or 405 because\n // /api/v1/memories/{memory_id} exists with other methods. Either would\n // otherwise read as \"context not found\" or a bare HTTP error.\n // InvalidInputError, with Python's message.\n mapError: (status, error) =>\n status === 404 || status === 405\n ? new InvalidInputError(\n 'This Synap server does not support file parts in memories.create. ' +\n 'Upgrade the Synap server, or send text only.',\n { correlationId: error.correlationId, cause: error },\n )\n : undefined,\n });\n },\n\n async batch_create(options) {\n const docs = options.documents;\n if (!Array.isArray(docs) || docs.length === 0) {\n throw new InvalidInputError('documents must be a non-empty array');\n }\n const failFast = options.fail_fast ?? options.failFast ?? false;\n return transport.request<BatchCreateResult>('memories_batch', {\n body: {\n documents: docs.map((d) => {\n jsonDocument(d.document, 'memories.batch_create');\n return buildCreateBody(d);\n }),\n fail_fast: failFast,\n },\n });\n },\n\n async create_from_file(options) {\n const userId = options.user_id ?? options.userId;\n const customerId = options.customer_id ?? options.customerId;\n // Checked first, as Python checks it: a flat map of level key to id.\n // Until 0.5.20 any shape was serialised and sent.\n const scope = options.scope as unknown;\n if (scope !== undefined && scope !== null && (\n typeof scope !== 'object' || Array.isArray(scope)\n || !Object.values(scope as Record<string, unknown>).every((v) => typeof v === 'string')\n )) {\n throw new InvalidInputError('scope must be a flat dict of level key to id, both strings.');\n }\n if (!userId) throw new InvalidInputError('user_id is required');\n // Not required: rejected on B2C, so requiring it made the documented\n // default combination impossible to call.\n await transport.checkCustomerId(customerId, 'memories.create_from_file');\n\n const filePath = options.file_path ?? options.filePath;\n const sources = [filePath, options.file, options.text].filter((v) => v !== undefined);\n if (sources.length === 0) {\n // Python raises ValueError here. There is no JS equivalent, and every\n // other validation in this SDK raises InvalidInputError, so the\n // taxonomy wins over a literal transcription of the exception type.\n throw new InvalidInputError('One of file_path, file, or text must be provided.');\n }\n if (sources.length > 1) {\n throw new InvalidInputError(\n 'Provide exactly one of file_path, file, or text, not several.',\n );\n }\n\n const form = new FormData();\n form.set('user_id', userId);\n // Only when there is one. `form.set('customer_id', undefined)` sends the\n // string \"undefined\", which a B2C instance refuses as a customer id.\n if (typeof customerId === 'string' && customerId !== '') {\n form.set('customer_id', customerId);\n }\n form.set('relationship_type', options.relationship_type ?? options.relationshipType ?? 'b2c');\n form.set('mode', String(options.mode ?? DEFAULT_INGEST_MODE));\n\n // Python appends these only when truthy, so an empty document_type or an\n // empty metadata object is absent from the form rather than present-empty.\n const documentType = options.document_type ?? options.documentType;\n if (documentType) form.set('document_type', String(documentType));\n if (options.metadata !== undefined && Object.keys(options.metadata).length > 0) {\n form.set('metadata', JSON.stringify(options.metadata));\n }\n // The upload route is multipart and cannot carry an object, so the scope\n // map goes as a JSON string; the server parses it with json.loads.\n if (options.scope && Object.keys(options.scope).length > 0) {\n form.set('scope', JSON.stringify(options.scope));\n }\n\n if (filePath !== undefined) {\n // Lazy, so importing the SDK on Edge or in a Worker stays safe: a\n // top-level `node:fs` import fails the BUILD there, not the call.\n const { readFile } = await import('node:fs/promises');\n const { basename } = await import('node:path');\n const bytes = await readFile(filePath);\n form.set('file', new Blob([bytes as unknown as BlobSource]), basename(filePath));\n } else if (options.file !== undefined) {\n const blob = options.file instanceof Blob\n ? options.file\n : new Blob([options.file as unknown as BlobSource]);\n // Python defaults the name to \"upload\" when `filename` is omitted.\n form.set('file', blob, options.filename ?? 'upload');\n } else {\n form.set('text', String(options.text));\n }\n\n return transport.request<CreateMemoryResult>('memories_upload', {\n body: form,\n rawBody: true,\n });\n },\n\n async get(memoryId) {\n if (!memoryId) throw new InvalidInputError('memory_id is required');\n return transport.request<Json>('memories_get', { pathParams: { memory_id: memoryId } });\n },\n\n async update(options) {\n const memoryId = options.memory_id ?? options.memoryId;\n if (!memoryId) throw new InvalidInputError('memory_id is required');\n if (!options.document) throw new InvalidInputError('document is required');\n const body: Json = {\n document: options.document,\n merge_strategy: options.merge_strategy ?? options.mergeStrategy ?? 'smart-merge',\n };\n const dt = options.document_type ?? options.documentType;\n if (dt !== undefined) body['document_type'] = dt;\n if (options.metadata !== undefined) body['metadata'] = options.metadata;\n // PUT, so idempotent by verb: safe to retry even on an ambiguous failure.\n return transport.request<Json>('memories_update', {\n pathParams: { memory_id: memoryId },\n body,\n });\n },\n\n async delete(memoryId) {\n // The 0.3.x wrapper let you delete \"all of this user's memories\" from a\n // process-local id list, which deleted nothing in serverless while\n // reporting success. Deliberately not ported.\n if (!memoryId) {\n throw new InvalidInputError(\n 'memory_id is required. Deleting by user is no longer supported: the ' +\n 'previous implementation tracked ids in process memory, so it silently ' +\n 'deleted nothing in any serverless or multi-process deployment while ' +\n 'reporting success.',\n );\n }\n return transport.request<Json>('memories_delete', { pathParams: { memory_id: memoryId } });\n },\n\n async forget(options) {\n const o = options as unknown as Record<string, unknown>;\n await transport.checkCustomerId(o['customer_id'] ?? o['customerId'], 'memories.forget');\n const body = buildForgetBody(options) as Record<string, unknown>;\n const result = await transport.request<ForgetResult>('memories_forget', { body: body as Json });\n // A preview deletes nothing, so it evicts nothing. Never let a cache\n // problem turn a successful delete into an error.\n // A forget can remove only copies (a profile entry, a chunk) and so return no\n // memory ids; those are served from the same caches.\n const removed = !!result?.deleted_ids?.length\n || result?.status === 'deleted' || result?.status === 'partial';\n if (removed && onForgotten) {\n try {\n onForgotten({\n userId: (body['user_id'] as string | null) ?? null,\n customerId: (body['customer_id'] as string | null) ?? null,\n });\n } catch { /* eviction is best effort */ }\n }\n return result;\n },\n\n async status(ingestionId) {\n if (!ingestionId) throw new InvalidInputError('ingestion_id is required');\n return transport.request<Json>('memories_status', {\n pathParams: { ingestion_id: ingestionId },\n });\n },\n\n async wait_for_completion(ingestionId, options = {}) {\n if (!ingestionId) throw new InvalidInputError('ingestion_id is required');\n const timeoutMs =\n (options.timeout_seconds ?? options.timeoutSeconds ?? 300) * 1000;\n const pollMs =\n (options.poll_interval_seconds ?? options.pollIntervalSeconds ?? 2) * 1000;\n\n const deadline = Date.now() + timeoutMs;\n let last: Json = {};\n for (;;) {\n last = await this.status(ingestionId);\n const status = String(last['status'] ?? '').toLowerCase();\n if (TERMINAL_STATUSES.has(status)) return last;\n if (Date.now() >= deadline) {\n // Python returns the last status rather than raising, so a caller\n // that only checks `.status` behaves identically in both SDKs.\n return last;\n }\n await sleep(Math.min(pollMs, Math.max(0, deadline - Date.now())), options.signal);\n }\n },\n };\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) return Promise.resolve();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n // NOT unref'd. This is the poll interval inside wait_for_completion, which\n // a caller is awaiting: foreground work. Unref'ing it let a process whose\n // only pending work was this sleep exit mid-poll, so an awaited\n // wait_for_completion never settled. Node calls it \"Detected unsettled\n // top-level await\". The unref'd timers in this SDK are the two heartbeats\n // and the request watchdog, all of which are genuinely background.\n function onAbort() {\n clearTimeout(timer);\n reject(signal?.reason ?? new Error('Aborted'));\n }\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","/**\n * Client-side identifier validation, mirroring Python's\n * ``maximem_synap/utils/validators.py``.\n *\n * These raise the *specific* ``InvalidInputError`` subtypes so callers can\n * catch them directly (``catch (e) { if (e instanceof InvalidConversationIdError) }``)\n * instead of the generic parent. Validation happens before any network call,\n * so a malformed id fails locally rather than becoming a billed round trip.\n *\n * Both errors were exported from day one and thrown at zero sites until this\n * module existed, which meant a typo'd conversation id reached the server and\n * came back as a generic 4xx.\n */\n\nimport { InvalidConversationIdError, InvalidInstanceIdError } from '../errors.js';\n\n// Instance ids are issued as `inst_` followed by 16 hex characters.\nconst INSTANCE_ID_RE = /^inst_[0-9a-fA-F]{16}$/;\n\n// Accepts any RFC 4122 shape. Deliberately laxer than a version-specific\n// check: Python defers to `uuid.UUID(...)`, which likewise accepts any\n// variant, and rejecting a valid-but-unexpected version here would diverge.\nconst UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\n\n/**\n * Throw `InvalidConversationIdError` if a non-empty `conversationId` is not a\n * UUID string.\n *\n * Empty / null / undefined values pass through untouched: callers that require\n * a conversation id surface that separately, so this only rejects a clearly\n * malformed value such as `\"conv_123\"`.\n */\nexport function validateConversationId(conversationId: unknown): void {\n if (conversationId === undefined || conversationId === null || conversationId === '') return;\n if (typeof conversationId !== 'string' || !UUID_RE.test(conversationId)) {\n // Message text matches Python's `f\"Invalid conversation ID: {id}\"` byte for byte.\n throw new InvalidConversationIdError(`Invalid conversation ID: ${String(conversationId)}`);\n }\n}\n\n/**\n * Throw `InvalidInstanceIdError` if a non-empty `instanceId` is not in the\n * `inst_<hex16>` format.\n *\n * Empty values pass through: the instance id is normally resolved from the API\n * key during `initialize()`, so only an explicitly provided malformed id is\n * rejected.\n */\nexport function validateInstanceId(instanceId: unknown): void {\n if (instanceId === undefined || instanceId === null || instanceId === '') return;\n if (typeof instanceId !== 'string' || !INSTANCE_ID_RE.test(instanceId)) {\n throw new InvalidInstanceIdError(`Invalid instance ID: ${String(instanceId)}`);\n }\n}\n","/**\n * Which model the agent runs on, sent with each conversation turn.\n *\n * The server sizes compaction to the agent's context window: it compacts at\n * about 11.7% of the window (15K tokens on a 128K model) and caps the\n * compacted record at half that. It reads the window from the latest turn's\n * metadata, under `agent_model` and `agent_context_window`. A model name is\n * enough: the server has a model -> window table. Give `context_window` only\n * for a model the table would not know, or to override it.\n *\n * Precedence, highest first: the value passed on the call, the client option\n * (`agent_model` / `agent_context_window`), a value already in the caller's\n * own metadata. With none of them the server assumes 128K. Mirrors Python's\n * `agent_model.py`.\n */\nexport const AGENT_MODEL_KEY = 'agent_model';\nexport const AGENT_CONTEXT_WINDOW_KEY = 'agent_context_window';\n\nexport interface AgentModel {\n model?: string | undefined;\n contextWindow?: number | undefined;\n}\n\n/** The per-call `model` / `context_window` (either spelling) off an options object. */\nexport function agentModelOf(options: unknown): AgentModel {\n const o = (options ?? {}) as Record<string, unknown>;\n const window = o['context_window'] ?? o['contextWindow'];\n return {\n model: typeof o['model'] === 'string' ? (o['model'] as string) : undefined,\n contextWindow: typeof window === 'number' ? window : undefined,\n };\n}\n\n/**\n * `metadata` with the agent's model folded in. `asStrings` for the gRPC\n * stream, whose metadata is a string map. Returns the input unchanged when\n * there is nothing to add.\n */\nexport function withAgentModel<T extends Record<string, unknown>>(\n metadata: T | undefined,\n perCall: AgentModel,\n defaults: AgentModel,\n asStrings = false,\n): T | undefined {\n const model = perCall.model || defaults.model;\n const window = perCall.contextWindow || defaults.contextWindow;\n if (!model && !window) return metadata;\n const out: Record<string, unknown> = { ...(metadata ?? {}) };\n if (model) out[AGENT_MODEL_KEY] = String(model);\n if (window) out[AGENT_CONTEXT_WINDOW_KEY] = asStrings ? String(Math.trunc(window)) : Math.trunc(window);\n return out as T;\n}\n","/**\n * Conversation namespace. Mirrors `ConversationInterface` and\n * `ConversationContextInterface` in the Python SDK.\n */\n\nimport { InvalidInputError } from '../errors.js';\nimport { validateConversationId } from '../util/validators.js';\nimport type { HttpTransport } from '../transport/http.js';\nimport { fetchContext, type FetchHooks } from '../context/fetch.js';\nimport { agentModelOf, withAgentModel, type AgentModel } from '../agent-model.js';\nimport type { FetchOptions, Json, RawContext } from '../context/types.js';\nimport {\n normaliseContent, toInlineParts,\n type ContentPart, type WireImagePart, type WireTextPart,\n} from '../memories/parts.js';\n\nexport interface RecordMessageOptions {\n conversation_id?: string;\n conversationId?: string;\n role: string;\n /**\n * The message. A string, or a list of strings, `TextPart`s and `FilePart`s\n * (images today). A list with no file is joined with `\"\\n\"` and sent as that\n * string. With a file, the parts are sent in order with each file inline as\n * base64; the server reads the images and stores the message as text.\n */\n content: string | ContentPart[];\n user_id?: string;\n userId?: string;\n customer_id?: string;\n customerId?: string;\n session_id?: string;\n sessionId?: string;\n metadata?: Json;\n /**\n * The rung this conversation belongs to, named in full, e.g.\n * `{ tenant: 'acme', practice: 'high_street' }`.\n *\n * Only relevant to a client whose ladder is deeper than the default three\n * rungs (root, tenant, person). On the default ladder `customer_id` and\n * `user_id` already say everything a path could.\n *\n * Sent as `scope` on the wire, matching Python's `scope_path`. Sending it\n * once per conversation is enough: the server fills a missing path and never\n * overwrites one.\n */\n scope_path?: Record<string, string>;\n scopePath?: Record<string, string>;\n /**\n * The model the agent runs on, e.g. `'gpt-4o'`. Overrides the client's\n * `agent_model` for this turn. The server sizes compaction to this model's\n * context window. Python's `model=`.\n */\n model?: string;\n /** The agent model's context window in tokens, for a model the server would not know. */\n context_window?: number;\n contextWindow?: number;\n}\n\nexport interface TranscriptTurn {\n role: string;\n content: string;\n [key: string]: unknown;\n}\n\nexport interface IngestTranscriptOptions {\n conversation_id?: string;\n conversationId?: string;\n user_id?: string;\n userId?: string;\n transcript: string | TranscriptTurn[];\n customer_id?: string;\n customerId?: string;\n conversation_type?: string;\n conversationType?: string;\n analysis?: Json;\n metadata?: Json;\n started_at?: string | Date;\n startedAt?: string | Date;\n ended_at?: string | Date;\n endedAt?: string | Date;\n /**\n * The rung this conversation belongs to, named in full, e.g.\n * `{ tenant: 'acme', practice: 'high_street' }`.\n *\n * Only relevant to a client whose ladder is deeper than the default three\n * rungs (root, tenant, person). On the default ladder `customer_id` and\n * `user_id` already say everything a path could.\n *\n * Sent as `scope` on the wire, matching Python's `scope_path`. Sending it\n * once per conversation is enough: the server fills a missing path and never\n * overwrites one.\n */\n scope_path?: Record<string, string>;\n scopePath?: Record<string, string>;\n}\n\n/**\n * Compaction levels, mirroring Python's `CompactionLevel` enum. The JS SDK\n * exported no equivalent, so `compaction_level` was an untyped `string` and a\n * typo reached the server instead of the compiler.\n */\nexport const COMPACTION_LEVELS = [\n 'low', 'medium', 'high', 'adaptive', 'aggressive', 'balanced', 'conservative',\n] as const;\n\nexport type CompactionLevel = (typeof COMPACTION_LEVELS)[number];\n\nexport interface CompactOptions {\n conversation_id?: string;\n conversationId?: string;\n strategy?: string;\n compaction_level?: CompactionLevel | string;\n compactionLevel?: CompactionLevel | string;\n target_tokens?: number;\n targetTokens?: number;\n force?: boolean;\n}\n\nfunction either<T>(o: Record<string, unknown>, snake: string, camel: string): T | undefined {\n const a = o[snake];\n if (a !== undefined) return a as T;\n const b = o[camel];\n return b === undefined ? undefined : (b as T);\n}\n\nfunction iso(v: string | Date | undefined): string | undefined {\n if (v === undefined) return undefined;\n return v instanceof Date ? v.toISOString() : v;\n}\n\n/**\n * The JSON body Python sends for one message.\n *\n * `resolvedContent` is the content after its files were read, supplied by\n * `record_message`. Without it, a list with no file is joined into one string,\n * and a list with a file throws: reading a file is async, and this is not.\n */\nexport function buildRecordMessageBody(\n options: RecordMessageOptions,\n resolvedContent?: string | Array<WireTextPart | WireImagePart>,\n field = 'content',\n): Json {\n const o = options as unknown as Record<string, unknown>;\n const conversationId = either<string>(o, 'conversation_id', 'conversationId');\n const userId = either<string>(o, 'user_id', 'userId');\n const customerId = either<string>(o, 'customer_id', 'customerId');\n\n if (!conversationId) throw new InvalidInputError('conversation_id is required');\n // Python validates the format here (and in record_messages_batch, which\n // reuses this builder per message). Note it deliberately does NOT validate\n // in ingest_transcript.\n validateConversationId(conversationId);\n if (!options.role) throw new InvalidInputError('role is required');\n // Checked before sending, as Python checks it. The server refuses any other\n // role with a 422; until 0.5.17 JS sent it to find out.\n if (!(MESSAGE_ROLES as readonly string[]).includes(options.role)) {\n throw new InvalidInputError(`Invalid role '${options.role}'. Must be 'user' or 'assistant'.`);\n }\n if (options.content === undefined || options.content === null) {\n throw new InvalidInputError('content is required');\n }\n if (!userId) throw new InvalidInputError('user_id is required');\n // customer_id is NOT required. A B2C instance rejects one, so demanding it\n // here made the only correct B2C shape impossible to express.\n // checked by the caller, which holds the transport; see createConversationNamespace\n\n let content: unknown = options.content;\n if (resolvedContent !== undefined) {\n content = resolvedContent;\n } else {\n const n = normaliseContent(options.content, field);\n if (n?.kind === 'parts') {\n throw new InvalidInputError(\n 'content holds a FilePart, whose bytes have to be read first. ' +\n 'Send it with conversation.record_message.',\n );\n }\n if (n !== null) content = n.text;\n }\n\n const body: Json = {\n conversation_id: conversationId,\n role: options.role,\n content,\n user_id: userId,\n customer_id: customerId,\n // Python always sends this, defaulting to {}.\n metadata: options.metadata ?? {},\n };\n // Only when set, like Python's `if session_id:`. An empty one reached the\n // server, which turns any non-UUID session id into its UUID5, so every\n // conversation sent \"\" shared one session.\n const sessionId = either<string>(o, 'session_id', 'sessionId');\n if (sessionId) body['session_id'] = sessionId;\n // `scope` on the wire, `scope_path` in the SDK, the same split Python makes.\n // Omitted when unset so a client on the default ladder sends exactly the\n // body it sends today.\n const scopePath = either<Record<string, string>>(o, 'scope_path', 'scopePath');\n // Omitted when absent or empty, like Python's `if scope_path:`.\n if (scopePath !== undefined && scopePath !== null && Object.keys(scopePath).length > 0) {\n body['scope'] = scopePath;\n }\n return body;\n}\n\nexport function buildIngestTranscriptBody(options: IngestTranscriptOptions): Json {\n const o = options as unknown as Record<string, unknown>;\n const conversationId = either<string>(o, 'conversation_id', 'conversationId');\n const userId = either<string>(o, 'user_id', 'userId');\n if (!conversationId) throw new InvalidInputError('conversation_id is required');\n if (!userId) throw new InvalidInputError('user_id is required');\n if (options.transcript === undefined || options.transcript === null) {\n throw new InvalidInputError('transcript is required');\n }\n\n const body: Json = {\n conversation_id: conversationId,\n user_id: userId,\n transcript: options.transcript,\n };\n // Unset optionals are omitted so the server applies its own defaults, which\n // is what Python does here (and notably NOT what it does for memories.create).\n const customerId = either<string>(o, 'customer_id', 'customerId');\n const conversationType = either<string>(o, 'conversation_type', 'conversationType');\n const startedAt = iso(either<string | Date>(o, 'started_at', 'startedAt'));\n const endedAt = iso(either<string | Date>(o, 'ended_at', 'endedAt'));\n if (customerId !== undefined) body['customer_id'] = customerId;\n if (conversationType !== undefined) body['conversation_type'] = conversationType;\n if (options.analysis !== undefined) body['analysis'] = options.analysis;\n if (options.metadata !== undefined) body['metadata'] = options.metadata;\n if (startedAt !== undefined) body['started_at'] = startedAt;\n if (endedAt !== undefined) body['ended_at'] = endedAt;\n // Python 0.4.10 sends this on `ingest_transcript` and JS did not, so a\n // TypeScript client on a deep ladder had no route that could name a rung.\n // Omitted when absent or empty, like Python's `if scope_path:`.\n const scopePath = either<Record<string, string>>(o, 'scope_path', 'scopePath');\n if (scopePath !== undefined && scopePath !== null && Object.keys(scopePath).length > 0) {\n body['scope'] = scopePath;\n }\n return body;\n}\n\nexport function buildCompactBody(options: CompactOptions): Json {\n const o = options as unknown as Record<string, unknown>;\n const conversationId = either<string>(o, 'conversation_id', 'conversationId');\n if (!conversationId) throw new InvalidInputError('conversation_id is required');\n validateConversationId(conversationId);\n\n const body: Json = { conversation_id: conversationId, force: options.force ?? false };\n const strategy = options.strategy ?? either<string>(o, 'compaction_level', 'compactionLevel');\n const targetTokens = either<number>(o, 'target_tokens', 'targetTokens');\n if (strategy !== undefined) body['strategy'] = strategy;\n if (targetTokens !== undefined) body['target_tokens'] = targetTokens;\n return body;\n}\n\n/**\n * Result of `conversation.ingest_transcript`, mirroring Python's\n * `TranscriptIngestResponse`. It was `Json` here, so `ingestion_id` came back\n * as `unknown` and could not be handed to `wait_for_completion` without a cast.\n */\nexport interface TranscriptIngestResult {\n conversation_id: string;\n /** The raw client-supplied id, echoed back. */\n external_conversation_id: string;\n /** Always set on a 2xx, including the `duplicate` branch. */\n ingestion_id: string;\n status: 'queued' | 'duplicate';\n turns_recorded: number;\n summary_status: 'in_progress' | 'already_compacted' | 'skipped';\n /**\n * What the server could not do with this push: no event time supplied\n * (recency ranking cannot order these memories), or existing turns kept.\n * Always a list. Since 0.5.16.\n */\n warnings: string[];\n /** ISO-8601. */\n queued_at: string;\n [key: string]: unknown;\n}\n\nexport interface ConversationNamespace {\n record_message(options: RecordMessageOptions): Promise<Json>;\n record_messages_batch(messages: RecordMessageOptions[]): Promise<Json>;\n ingest_transcript(options: IngestTranscriptOptions): Promise<TranscriptIngestResult>;\n context: {\n fetch(options?: FetchOptions): Promise<RawContext>;\n get_context_for_prompt(options?: {\n conversation_id?: string;\n conversationId?: string;\n style?: string;\n /** Search the earlier turns locally after a compaction (default true). */\n search_history?: boolean;\n searchHistory?: boolean;\n /** What to search for; defaults to the latest user message. */\n query?: string;\n }): Promise<Json>;\n compact(options: CompactOptions): Promise<Json>;\n get_compacted(options: { conversation_id?: string; conversationId?: string; version?: number; format?: string }): Promise<Json | null>;\n get_compaction_status(options: { conversation_id?: string; conversationId?: string } | string): Promise<Json>;\n subscribe_to_compaction_updates(\n conversationId: string,\n callback: CompactionCallback,\n ): () => void;\n unsubscribe_all_compaction_updates(conversationId?: string): number;\n };\n}\n\nexport type CompactionCallback = (bundle: Json) => unknown;\n\n/**\n * Registry of per-conversation compaction subscribers.\n *\n * Split out from the namespace so the instance stream can dispatch into it\n * without the two namespaces importing each other.\n */\nexport class CompactionSubscribers {\n readonly #byConversation = new Map<string, CompactionCallback[]>();\n\n add(conversationId: string, callback: CompactionCallback): () => void {\n const list = this.#byConversation.get(conversationId);\n if (list === undefined) this.#byConversation.set(conversationId, [callback]);\n else list.push(callback);\n\n let unsubscribed = false;\n return () => {\n // Idempotent, matching Python: calling the thunk twice is a no-op.\n if (unsubscribed) return;\n unsubscribed = true;\n const current = this.#byConversation.get(conversationId);\n if (current === undefined) return;\n const at = current.indexOf(callback);\n if (at !== -1) current.splice(at, 1);\n if (current.length === 0) this.#byConversation.delete(conversationId);\n };\n }\n\n removeAll(conversationId?: string): number {\n if (conversationId === undefined) {\n let count = 0;\n for (const list of this.#byConversation.values()) count += list.length;\n this.#byConversation.clear();\n return count;\n }\n const list = this.#byConversation.get(conversationId);\n if (list === undefined) return 0;\n this.#byConversation.delete(conversationId);\n return list.length;\n }\n\n /** Fires subscribers in registration order. A throwing listener must not break the stream reader. */\n dispatch(conversationId: string, bundle: Json, onError: (e: unknown) => void): void {\n // Copy first: a callback that unsubscribes itself would otherwise mutate\n // the array mid-iteration and skip the next listener.\n for (const callback of [...(this.#byConversation.get(conversationId) ?? [])]) {\n try {\n const result = callback(bundle) as unknown;\n // An async callback returns a promise; swallow its rejection the way\n // Python swallows one from an asyncio task.\n if (result instanceof Promise) result.catch(onError);\n } catch (error) {\n onError(error);\n }\n }\n }\n}\n\n/**\n * Pair each message a batch write stored with the server's row for it.\n *\n * The server's `results` holds the messages that were stored, in input order,\n * and leaves the failed ones out; those are in `errors`, each with the `index`\n * it had in the request. Buffering every body, or pairing `results` against\n * the whole input by position, puts a message the server refused into the\n * caller's next prompt.\n *\n * Returns nothing when the two cannot be lined up, as Python does. A row with\n * no `message_id` is treated as not stored.\n */\nexport function storedBatchRows(\n bodies: Array<Record<string, unknown>>,\n result: unknown,\n): Array<[Record<string, unknown>, Record<string, unknown>]> {\n const r = (result ?? {}) as Record<string, unknown>;\n const results = Array.isArray(r['results']) ? (r['results'] as Array<Record<string, unknown>>) : [];\n const errors = Array.isArray(r['errors']) ? (r['errors'] as Array<Record<string, unknown>>) : [];\n const failed = new Set(errors.map((e) => e?.['index']));\n const stored = bodies.filter((_, index) => !failed.has(index));\n if (stored.length !== results.length) return [];\n const pairs: Array<[Record<string, unknown>, Record<string, unknown>]> = [];\n stored.forEach((body, i) => {\n const row = results[i];\n if (row && typeof row === 'object' && row['message_id']) pairs.push([body, row]);\n });\n return pairs;\n}\n\n/**\n * Called after a successful write with the ids that were written for.\n *\n * Backs `SYNAP_SDK_CACHE_INVALIDATE_ON_WRITE`. The cloud invalidates its own\n * Redis caches on ingest, but that stops at the process boundary: without this\n * the in-SDK anticipation cache keeps serving the pre-write view for the rest\n * of its TTL. Python calls its equivalent from these same three write paths.\n */\nexport type WriteInvalidator = (ids: {\n userId?: string | undefined;\n customerId?: string | undefined;\n}) => void;\n\n/**\n * Called with each turn a write path sends, so it can be buffered locally.\n *\n * This is what makes the next fetch see the turn that was just recorded, ahead\n * of the server having persisted and compacted it.\n */\nexport type TurnRecorder = (turn: {\n conversationId: string;\n role: string;\n content: string;\n timestamp?: string | undefined;\n /** The server's id for the turn, from the write's response. */\n messageId?: string | undefined;\n /**\n * The conversation's message count after this write, as the server reported\n * it. This is what tells the local store whether it holds the whole\n * conversation. Absent from a server that predates it.\n */\n serverMessageCount?: number | null | undefined;\n /** Other writes this process still has outstanding for the conversation. */\n inFlight?: number | undefined;\n}) => void;\n\n/** The roles the server accepts on a recorded message (RecordMessageRequest.role). */\nexport const MESSAGE_ROLES: readonly string[] = ['user', 'assistant'];\n\n/** The styles the server renders (CompactedContext.get_injection_format). */\nexport const PROMPT_STYLES: readonly string[] = ['structured', 'narrative', 'bullet_points'];\n\nexport function createConversationNamespace(\n transport: HttpTransport,\n subscribers: CompactionSubscribers = new CompactionSubscribers(),\n onWrite: WriteInvalidator = () => {},\n onTurn: TurnRecorder = () => {},\n /**\n * Applied to a conversation-scoped response before it is returned.\n *\n * `scopePath` is carried because one of the things this hook does is splice\n * in a cached user summary, and a summary prefetched at one rung must not be\n * spliced into a response for a caller standing at another. Python reads the\n * path off the fetch arguments at that call site; here the call site is a\n * callback, so the path has to travel with it or the rung check is silently\n * skipped on this one path.\n */\n onFetched: (\n response: RawContext,\n conversationId: string | undefined,\n userId: string | undefined,\n scopePath: Record<string, string> | undefined,\n ) => void = () => {},\n /**\n * SDK-authoritative short-term context. Returns a locally rendered response\n * when the flag is on AND the store is warm for this conversation, which\n * skips the cloud round trip entirely; null falls through to the network.\n */\n localShortTerm: {\n prompt: (conversationId: string, style: string) => Json | null;\n compacted: (conversationId: string, format: string) => Json | null;\n /**\n * Handed the server's `/context-for-prompt` answer after the local store\n * could not answer, so the store can be brought back in step.\n */\n reseed?: (conversationId: string, serverResponse: Json) => void;\n /**\n * The response with the earlier turns that best match `query` appended,\n * found by a local search of the turn archive. Python:\n * `MaximemSynapSDK._with_history_excerpts`.\n */\n historyExcerpts?: (conversationId: string, response: Json, query: string | undefined) => Promise<Json>;\n } = { prompt: () => null, compacted: () => null },\n /** The client's `agent_model` / `agent_context_window`, folded into each turn's metadata. */\n agentModel: () => AgentModel = () => ({}),\n fetchHooks: FetchHooks = {},\n): ConversationNamespace {\n // conversation_id -> REST writes sent and not yet buffered locally. Lets the\n // local store tell two of this process's own concurrent writes apart from a\n // second writer.\n const writesInFlight = new Map<string, number>();\n const withTurnModel = (body: Json, options: unknown): Json => {\n const metadata = withAgentModel(\n body['metadata'] as Record<string, unknown> | undefined, agentModelOf(options), agentModel(),\n );\n return metadata === undefined ? body : { ...body, metadata: metadata as Json };\n };\n const writeStarted = (conversationId: string): void => {\n writesInFlight.set(conversationId, (writesInFlight.get(conversationId) ?? 0) + 1);\n };\n const writeLanded = (conversationId: string): void => {\n const remaining = (writesInFlight.get(conversationId) ?? 0) - 1;\n if (remaining > 0) writesInFlight.set(conversationId, remaining);\n else writesInFlight.delete(conversationId);\n };\n const confirmation = (\n result: unknown,\n conversationId: string,\n ): { messageId?: string; serverMessageCount?: number | null; inFlight: number } => {\n const r = (result ?? {}) as Record<string, unknown>;\n const count = r['conversation_message_count'];\n return {\n ...(typeof r['message_id'] === 'string' ? { messageId: r['message_id'] } : {}),\n serverMessageCount: typeof count === 'number' ? count : null,\n inFlight: writesInFlight.get(conversationId) ?? 0,\n };\n };\n const fetchImpl = ((url: string, init?: RequestInit) =>\n transport.fetchExternal(url, init)) as typeof fetch;\n /** Everything but the content's files, so a bad id fails before a download. */\n const validateMessage = (options: RecordMessageOptions, field = 'content'): void => {\n if (normaliseContent(options.content, field)?.kind === 'parts') {\n buildRecordMessageBody(options, '', field);\n } else {\n buildRecordMessageBody(options, undefined, field);\n }\n };\n /**\n * The body for one message, and what the local short-term store keeps for\n * it: the content itself, or, when it carries images, the placeholder\n * rendering (`[image: <filename>]`), never base64.\n */\n const prepareMessage = async (\n options: RecordMessageOptions,\n field = 'content',\n ): Promise<{ body: Json; mirror: string }> => {\n const n = normaliseContent(options.content, field);\n if (n?.kind !== 'parts') {\n const body = buildRecordMessageBody(options, undefined, field);\n return { body, mirror: String(body['content'] ?? '') };\n }\n validateMessage(options, field);\n const inline = await toInlineParts(n.parts, fetchImpl);\n return { body: buildRecordMessageBody(options, inline.wire), mirror: inline.placeholder };\n };\n const convId = (v: { conversation_id?: string; conversationId?: string } | string): string => {\n const id = typeof v === 'string' ? v : (v.conversation_id ?? v.conversationId);\n if (!id) throw new InvalidInputError('conversation_id is required');\n // Covers context.fetch, get_compacted, get_compaction_status and\n // get_context_for_prompt: the four routes Python validates through this\n // same shape. ingest_transcript does not go through here, which is correct.\n validateConversationId(id);\n return id;\n };\n\n return {\n async record_message(options) {\n await transport.checkCustomerId(\n (options as unknown as Record<string, unknown>)['customer_id'] ??\n (options as unknown as Record<string, unknown>)['customerId'],\n 'conversation.record_message',\n );\n const prepared = await prepareMessage(options);\n const body = withTurnModel(prepared.body, options);\n const mirror = prepared.mirror;\n const conversationId = String(body['conversation_id'] ?? '');\n writeStarted(conversationId);\n let result: Json;\n try {\n result = await transport.request<Json>('conversations_messages', { body });\n } finally {\n writeLanded(conversationId);\n }\n // Buffer locally only AFTER the server accepted it. Recording a turn the\n // write failed on would surface a message that does not exist.\n onTurn({\n conversationId,\n role: String(body['role'] ?? 'user'),\n content: mirror,\n timestamp: body['timestamp'] as string | undefined,\n ...confirmation(result, conversationId),\n });\n onWrite({\n userId: body['user_id'] as string | undefined,\n customerId: body['customer_id'] as string | undefined,\n });\n return result;\n },\n\n async record_messages_batch(messages) {\n if (!Array.isArray(messages) || messages.length === 0) {\n throw new InvalidInputError('messages must be a non-empty array');\n }\n // Every message checked BEFORE any is sent: a batch that fails on its\n // fifth message would otherwise be half-applied.\n for (const m of messages) {\n const mo = m as unknown as Record<string, unknown>;\n await transport.checkCustomerId(\n mo['customer_id'] ?? mo['customerId'], 'conversation.record_messages_batch',\n );\n }\n // Every message validated before any file is read, then the files of\n // all of them read together.\n // Python names the failing message in the error, so this does too.\n const field = (i: number) => `messages[${i}].content`;\n messages.forEach((m, i) => validateMessage(m, field(i)));\n const prepared = await Promise.all(messages.map((m, i) => prepareMessage(m, field(i))));\n const bodies = prepared.map((p, i) => withTurnModel(p.body, messages[i]!));\n const mirrors = new Map(prepared.map((p, i) => [bodies[i]!, p.mirror]));\n const result = await transport.request<Json>('conversations_messages_batch', {\n body: { messages: bodies },\n });\n // Buffer only what the server stored, each paired with its own row.\n for (const [body, row] of storedBatchRows(bodies, result)) {\n const conversationId = String(body['conversation_id'] ?? '');\n onTurn({\n conversationId,\n role: String(body['role'] ?? 'user'),\n content: mirrors.get(body) ?? String(body['content'] ?? ''),\n timestamp: body['timestamp'] as string | undefined,\n ...confirmation(row, conversationId),\n });\n }\n // Every distinct entity in the batch, not just the first message's.\n for (const body of bodies) {\n onWrite({\n userId: body['user_id'] as string | undefined,\n customerId: body['customer_id'] as string | undefined,\n });\n }\n return result;\n },\n\n async ingest_transcript(options) {\n // First, as Python checks it and as every other write here does. Until\n // 0.5.16 this was the one write that skipped it, so a B2C customer_id\n // went to the server and came back as a plain InvalidInputError.\n const o = options as unknown as Record<string, unknown>;\n await transport.checkCustomerId(\n o['customer_id'] ?? o['customerId'], 'conversation.ingest_transcript',\n );\n const body = buildIngestTranscriptBody(options);\n const raw = await transport.request<TranscriptIngestResult>('conversations_ingest', { body });\n // Always a list, as Python's response model defaults it.\n const result: TranscriptIngestResult = {\n ...raw,\n warnings: Array.isArray(raw?.warnings) ? raw.warnings.map(String) : [],\n };\n onWrite({\n userId: body['user_id'] as string | undefined,\n customerId: body['customer_id'] as string | undefined,\n });\n return result;\n },\n\n context: {\n async fetch(options = {}) {\n // Conversation-scope fetch is one of Python's seven validation sites.\n // It does not route through convId() because the id travels in the\n // body rather than the path, so validate it explicitly.\n const id =\n (options as { conversation_id?: string; conversationId?: string }).conversation_id ??\n (options as { conversationId?: string }).conversationId;\n validateConversationId(id);\n const response = await fetchContext(transport, 'conversation', options, fetchHooks);\n // Read-your-writes. This is the path where it matters most: a fast\n // follow-up on the same conversation would otherwise retrieve context\n // missing the turn just recorded.\n onFetched(\n response,\n id,\n (options as { user_id?: string; userId?: string }).user_id ??\n (options as { userId?: string }).userId,\n (options as { scope_path?: Record<string, string> }).scope_path ??\n (options as { scopePath?: Record<string, string> }).scopePath,\n );\n return response;\n },\n\n get_context_for_prompt: async (options = {}) => {\n const id = convId(options);\n const style = options.style ?? 'structured';\n // Refused here, as Python refuses it. A style the server cannot render\n // was a 500 from it, or silently ignored when the compaction has a block.\n if (!PROMPT_STYLES.includes(style)) {\n throw new InvalidInputError(\n `Invalid style '${style}'. Must be one of: ${PROMPT_STYLES.join(', ')}`,\n );\n }\n const search = (options.search_history ?? options.searchHistory ?? true) && localShortTerm.historyExcerpts;\n const withHistory = async (response: Json): Promise<Json> => {\n if (!search) return response;\n try {\n return await localShortTerm.historyExcerpts!(id, response, options.query);\n } catch {\n return response; // never fail the prompt over its extras\n }\n };\n const local = localShortTerm.prompt(id, style);\n if (local !== null) return withHistory(local);\n const result = await transport.request<Json>('context_for_prompt', {\n pathParams: { conversation_id: id },\n query: { style },\n });\n const response = (result?.['context_for_prompt'] as Json) ?? result ?? {};\n localShortTerm.reseed?.(id, response);\n return withHistory(response);\n },\n\n async compact(options) {\n return transport.request<Json>('conversations_compact', { body: buildCompactBody(options) });\n },\n\n get_compacted: async (options) => {\n const id = convId(options);\n // Python only takes the local path when no explicit version is asked\n // for: a pinned version is a request for a specific server artefact.\n if (options.version === undefined) {\n const local = localShortTerm.compacted(id, options.format ?? 'structured');\n if (local !== null) return local;\n }\n const query: Record<string, string | number> = { format: options.format ?? 'structured' };\n if (options.version !== undefined) query['version'] = options.version;\n try {\n return await transport.request<Json>('conversations_compacted', {\n pathParams: { conversation_id: id },\n query,\n });\n } catch (error) {\n // Python returns None when there is nothing compacted yet, rather\n // than surfacing a 404. Matching that keeps callers identical.\n if ((error as { code?: string }).code === 'context_not_found') return null;\n throw error;\n }\n },\n\n async get_compaction_status(options) {\n return transport.request<Json>('conversations_compaction_status', {\n pathParams: { conversation_id: convId(options) },\n });\n },\n\n /**\n * Fire `callback` whenever a `compaction_update` bundle arrives on the\n * Listen stream for this conversation.\n *\n * Requires an active `client.instance.listen()`; without it no bundles\n * arrive and the callback never fires. Registering before listening is\n * fine, which is why this does not throw when the stream is down.\n *\n * Returns an idempotent unsubscribe thunk, matching Python.\n */\n subscribe_to_compaction_updates(conversationId, callback) {\n if (!conversationId) throw new InvalidInputError('conversation_id is required');\n if (typeof callback !== 'function') throw new InvalidInputError('callback is required');\n return subscribers.add(conversationId, callback);\n },\n\n /** Remove subscribers for one conversation, or all of them. Returns the count removed. */\n unsubscribe_all_compaction_updates(conversationId?: string) {\n return subscribers.removeAll(conversationId);\n },\n },\n };\n}\n","/**\n * Data namespace. Mirrors `maximem_synap.data.interface.DataInterface`.\n *\n * Delete personal data by scope (user, conversation, customer). Validation\n * messages are identical to Python's, and the body has the same keys in the\n * same order, nulls included.\n */\n\nimport { InvalidInputError } from '../errors.js';\nimport type { HttpTransport } from '../transport/http.js';\nimport type { Json } from '../context/types.js';\n\nexport const DATA_SCOPES = ['user', 'conversation', 'customer'] as const;\nexport type DataScope = (typeof DATA_SCOPES)[number];\n\n/** The most calls `wait` makes. Same as Python's MAX_WAIT_CALLS. */\nexport const MAX_WAIT_CALLS = 50;\n\nconst ID_FIELD: Record<DataScope, string> = {\n user: 'user_id',\n customer: 'customer_id',\n conversation: 'conversation_id',\n};\n\nexport interface DeleteDataOptions {\n /** `\"user\"`, `\"conversation\"` or `\"customer\"`. Client-wide delete is not supported. */\n scope: DataScope | string;\n user_id?: string | null;\n userId?: string | null;\n customer_id?: string | null;\n customerId?: string | null;\n conversation_id?: string | null;\n conversationId?: string | null;\n /** Count what would be removed and change nothing. No `confirm` needed. */\n dry_run?: boolean;\n dryRun?: boolean;\n /** Required unless `dryRun`. Must equal the id of the scope being deleted. */\n confirm?: string | null;\n /** Repeat the call while the server says `continue` (default true, max 50 calls). */\n wait?: boolean;\n}\n\n/** Result of `data.delete` / `data.status`. Mirrors Python's `DeleteDataResult`. */\nexport interface DeleteDataResult {\n deletion_id: string | null;\n /** `complete`, `partial`, `in_progress` or `dry_run`. */\n status: string;\n scope: string | null;\n dry_run: boolean;\n found: boolean;\n counts: Record<string, unknown>;\n stores: Record<string, unknown>;\n still_present_in: string[];\n fully_removed: boolean;\n /** True when the server's size cap stopped the call. */\n continue: boolean;\n kept: string[];\n note: string | null;\n memories_kept: boolean;\n audit: string | null;\n /** What the SDK cleared on this machine after the server finished. */\n local_cleared: string[];\n [key: string]: unknown;\n}\n\nfunction either<T>(o: Record<string, unknown>, snake: string, camel: string): T | undefined {\n const a = o[snake];\n if (a !== undefined) return a as T;\n const b = o[camel];\n return b === undefined ? undefined : (b as T);\n}\n\n/** Validate and build the request body. Throws before any request is sent. */\nexport function buildDeleteBody(options: DeleteDataOptions, instanceId: string): Json {\n const o = options as unknown as Record<string, unknown>;\n const scope = options.scope as unknown;\n if (scope !== null && typeof scope === 'object') {\n throw new InvalidInputError(\n 'scope must be one of: user, conversation, customer. A dict is not ' +\n 'accepted here (the rung-path dict used by memories.create and fetch ' +\n 'is a different parameter).',\n );\n }\n if (typeof scope !== 'string' || !(DATA_SCOPES as readonly string[]).includes(scope)) {\n throw new InvalidInputError(\n `Invalid scope '${String(scope)}'. Expected one of: ${DATA_SCOPES.join(', ')}`,\n );\n }\n const dryRun = either<boolean>(o, 'dry_run', 'dryRun') ?? false;\n if (typeof dryRun !== 'boolean') throw new InvalidInputError('dry_run must be a boolean');\n\n const ids: Record<string, string | null | undefined> = {\n user_id: either<string | null>(o, 'user_id', 'userId'),\n customer_id: either<string | null>(o, 'customer_id', 'customerId'),\n conversation_id: either<string | null>(o, 'conversation_id', 'conversationId'),\n };\n for (const [name, value] of Object.entries(ids)) {\n if (value !== undefined && value !== null && (typeof value !== 'string' || value.trim() === '')) {\n throw new InvalidInputError(`${name} must not be empty`);\n }\n }\n const field = ID_FIELD[scope as DataScope];\n const target = ids[field];\n if (target === undefined || target === null) {\n throw new InvalidInputError(`${field} is required for scope='${scope}'`);\n }\n const confirm = options.confirm ?? null;\n if (!dryRun) {\n if (confirm === null || confirm === '') {\n throw new InvalidInputError(\n `confirm is required unless dry_run=True: pass the ${field} being deleted as confirm`,\n );\n }\n if (confirm !== target) {\n throw new InvalidInputError(`confirm must equal the ${field} being deleted`);\n }\n }\n return {\n scope,\n instance_id: instanceId,\n user_id: ids['user_id'] ?? null,\n customer_id: ids['customer_id'] ?? null,\n conversation_id: ids['conversation_id'] ?? null,\n dry_run: dryRun,\n confirm,\n };\n}\n\n/** Fill every documented field so callers can rely on the shape. */\nfunction normalise(raw: Record<string, unknown>): DeleteDataResult {\n return {\n deletion_id: null,\n status: 'unknown',\n scope: null,\n dry_run: false,\n found: false,\n counts: {},\n stores: {},\n still_present_in: [],\n // Pessimistic: true only when the server said so.\n fully_removed: false,\n continue: false,\n kept: [],\n note: null,\n memories_kept: false,\n audit: null,\n local_cleared: [],\n ...raw,\n } as DeleteDataResult;\n}\n\nexport interface DataInterface {\n /**\n * Delete data for one user, one conversation or one customer. Permanent.\n * scope 'conversation' removes turns, summaries, telemetry and the turn buffer ONLY;\n * memories learned from it are kept (use scope 'user' or memories.delete). Data in\n * another instance is never touched; stores that cannot be scoped by instance are\n * skipped and named in still_present_in.\n *\n * scope 'customer' needs a management key (management:* or *); a runtime key gets 403.\n * LLM call traces are not removed (llm_call_bodies up to 14 days, llm_calls up to 180 days).\n *\n * A store that could not be cleared is in `still_present_in` and\n * `fully_removed` is false; it is a result, not an exception. Errors:\n * `InvalidInputError` (bad arguments, caught before any request, or 400),\n * `AuthenticationError` (401/403), `ConflictError` (409), `RateLimitError`.\n */\n delete(options: DeleteDataOptions): Promise<DeleteDataResult>;\n /** The audit record of a delete (status, counts, still_present_in). */\n status(deletionId: string): Promise<DeleteDataResult>;\n}\n\nexport type DataDeletedHook = (info: {\n scope: string;\n userId: string | null;\n customerId: string | null;\n conversationId: string | null;\n}) => string[];\n\nexport function createDataInterface(\n transport: HttpTransport,\n // Drops this machine's copies; returns what it cleared. Mirrors Python's `_evict_deleted`.\n onDeleted?: DataDeletedHook,\n): DataInterface {\n return {\n async delete(options) {\n const o = options as unknown as Record<string, unknown>;\n await transport.checkCustomerId(\n either<string>(o, 'customer_id', 'customerId'), 'data.delete',\n );\n const body = buildDeleteBody(options, transport.currentCredentials().instanceId);\n const dryRun = body['dry_run'] === true;\n const wait = options.wait ?? true;\n\n let result: DeleteDataResult | null = null;\n for (let i = 0; i < (wait ? MAX_WAIT_CALLS : 1); i += 1) {\n result = normalise(\n await transport.request<Record<string, unknown>>('data_delete', { body }),\n );\n if (dryRun || !result.continue) break;\n }\n const final = result as DeleteDataResult;\n if (!dryRun && ['complete', 'partial', 'in_progress'].includes(final.status) && onDeleted) {\n try {\n final.local_cleared = onDeleted({\n scope: body['scope'] as string,\n userId: (body['user_id'] as string | null) ?? null,\n customerId: (body['customer_id'] as string | null) ?? null,\n conversationId: (body['conversation_id'] as string | null) ?? null,\n });\n } catch { /* eviction is best effort */ }\n }\n return final;\n },\n\n async status(deletionId) {\n if (typeof deletionId !== 'string' || deletionId.trim() === '') {\n throw new InvalidInputError('deletion_id is required');\n }\n return normalise(\n await transport.request<Record<string, unknown>>('data_delete_status', {\n pathParams: { deletion_id: deletionId },\n query: { instance_id: transport.currentCredentials().instanceId },\n }),\n );\n },\n };\n}\n","/** User namespace. Mirrors `UserInterface` in the Python SDK. */\n\nimport { InvalidInputError } from '../errors.js';\nimport type { HttpTransport } from '../transport/http.js';\nimport { fetchContext, type FetchHooks } from '../context/fetch.js';\nimport type { FetchOptions, Json, RawContext } from '../context/types.js';\n\nexport interface UserNamespace {\n get_profile(options: { user_id?: string; userId?: string; customer_id?: string; customerId?: string } | string): Promise<Json>;\n context: { fetch(options?: FetchOptions): Promise<RawContext> };\n}\n\nexport function createUserNamespace(\n transport: HttpTransport,\n hooks: FetchHooks = {},\n): UserNamespace {\n return {\n async get_profile(options) {\n const userId = typeof options === 'string' ? options : (options.user_id ?? options.userId);\n if (!userId) throw new InvalidInputError('user_id is required');\n const customerId =\n typeof options === 'string' ? undefined : (options.customer_id ?? options.customerId);\n return transport.request<Json>('user_profile', {\n pathParams: { user_id: userId },\n // Sent only when provided, matching Python. Note the server returns\n // 500 rather than a clean error if it needs one and does not get it.\n ...(customerId !== undefined ? { query: { customer_id: customerId } } : {}),\n });\n },\n context: { async fetch(options = {}) { return fetchContext(transport, 'user', options, hooks); } },\n };\n}\n","/** Credits namespace. Mirrors `CreditsInterface` in the Python SDK. */\n\nimport { InvalidInputError } from '../errors.js';\nimport type { HttpTransport } from '../transport/http.js';\nimport type { Json } from '../context/types.js';\n\nexport interface EstimateOptions {\n metric_type?: string;\n metricType?: string;\n units?: number;\n item_count?: number;\n itemCount?: number;\n endpoint?: string;\n mode?: string;\n}\n\nexport interface CreditsNamespace {\n get_balance(): Promise<CreditBalance>;\n get_ledger(options?: LedgerOptions): Promise<CreditLedgerPage>;\n estimate(options: EstimateOptions): Promise<CreditEstimate>;\n redeem(code: string): Promise<RedeemResult>;\n}\n\n/**\n * Return types for the credits namespace, mirroring Python's dataclasses in\n * `maximem_synap/credits.py`. These were all `Json` (`Record<string, unknown>`)\n * before, so every field read was `unknown` and no documented example compiled.\n */\nexport interface CreditBucket {\n source_type: string;\n balance: number;\n /** ISO-8601, or null when the bucket does not expire. */\n expires_at: string | null;\n}\n\nexport interface CreditBalance {\n client_id: string;\n balance_credits: number;\n warning_low: boolean;\n buckets: CreditBucket[];\n [key: string]: unknown;\n}\n\nexport interface CreditLedgerEntry {\n ledger_id: string;\n entry_type: string;\n delta: number;\n metric_type: string | null;\n category: string | null;\n /** ISO-8601. */\n created_at: string;\n}\n\nexport interface CreditLedgerPage {\n entries: CreditLedgerEntry[];\n total: number;\n limit: number;\n offset: number;\n [key: string]: unknown;\n}\n\nexport interface CreditEstimate {\n credits_estimate: number;\n [key: string]: unknown;\n}\n\nexport interface RedeemResult {\n redemption_id: string;\n credits_granted: number;\n new_balance_credits: number;\n /** ISO-8601, or null when the granted credits do not expire. */\n expires_at: string | null;\n [key: string]: unknown;\n}\n\n/** Options for `credits.get_ledger`. Mirrors Python's keyword arguments. */\nexport interface LedgerOptions {\n /** Filter to one ledger entry type. */\n entry_type?: string;\n entryType?: string;\n /** Inclusive lower bound. ISO-8601 string or Date. Sent as `from`. */\n from_time?: string | Date;\n fromTime?: string | Date;\n /** Inclusive upper bound. ISO-8601 string or Date. Sent as `to`. */\n to_time?: string | Date;\n toTime?: string | Date;\n /** Defaults to 100, as in Python. */\n limit?: number;\n offset?: number;\n}\n\nfunction iso(v: string | Date): string {\n return v instanceof Date ? v.toISOString() : v;\n}\n\nexport function createCreditsNamespace(transport: HttpTransport): CreditsNamespace {\n return {\n async get_balance() { return transport.request<CreditBalance>('credits_balance'); },\n\n async get_ledger(options: LedgerOptions = {}) {\n // Mirrors Python's CreditsInterface.get_ledger: the three filters were\n // missing here entirely, and the default limit was 50 against Python's\n // 100, so the same call returned different pages in the two SDKs.\n const query: Record<string, string | number> = {\n limit: options.limit ?? 100,\n offset: options.offset ?? 0,\n };\n const entryType = options.entry_type ?? options.entryType;\n if (entryType !== undefined) query['entry_type'] = entryType;\n const from = options.from_time ?? options.fromTime;\n if (from !== undefined) query['from'] = iso(from);\n const to = options.to_time ?? options.toTime;\n if (to !== undefined) query['to'] = iso(to);\n return transport.request<CreditLedgerPage>('credits_ledger', { query });\n },\n\n async estimate(options) {\n return transport.request<CreditEstimate>('credits_estimate', {\n body: {\n metric_type: options.metric_type ?? options.metricType ?? null,\n units: options.units ?? null,\n item_count: options.item_count ?? options.itemCount ?? null,\n endpoint: options.endpoint ?? null,\n mode: options.mode ?? null,\n },\n });\n },\n\n async redeem(code) {\n if (!code) throw new InvalidInputError('code is required');\n // Non-idempotent by contract: redeeming twice consumes two codes.\n return transport.request<RedeemResult>('credits_redeem', { body: { code } });\n },\n };\n}\n","/**\n * Cache namespace. Same method names as `CacheInterface` in the Python SDK,\n * but it covers only the in-memory cache of prefetched context: `stats()`\n * returns `{ bundles, items }`, not Python's `enabled`, `total_entries`,\n * `total_bytes` and `backends`. There is no on-disk cache in JS.\n *\n * This is a deliberately narrow facade over the AnticipationCache rather than\n * the cache object itself. Exposing the instance directly leaked internals\n * (`client.cache.now` was reachable) and gave JS a different surface from\n * Python for no benefit. The cache is still reachable as\n * `client.anticipationCache` for advanced use.\n */\n\nimport type { AnticipationCache } from '../context/anticipation-cache.js';\nimport { InvalidInputError } from '../errors.js';\n\nexport interface CacheStats {\n bundles: number;\n items: number;\n [key: string]: unknown;\n}\n\nexport interface CacheNamespace {\n clear(): void;\n clear_user(userId: string): void;\n clear_customer(customerId: string): void;\n stats(): CacheStats;\n}\n\nexport function createCacheNamespace(cache: AnticipationCache): CacheNamespace {\n return {\n clear: () => cache.clear(),\n\n clear_user: (userId) => {\n if (!userId) throw new InvalidInputError('user_id is required');\n cache.dropEntity(userId);\n },\n\n clear_customer: (customerId) => {\n if (!customerId) throw new InvalidInputError('customer_id is required');\n cache.dropEntity(customerId);\n },\n\n stats: () => ({ bundles: cache.size, items: cache.itemCount }),\n };\n}\n","/**\n * Instance namespace. Mirrors `InstanceInterface` in the Python SDK.\n *\n * Everything here rides the bidirectional gRPC Listen stream. The stream module\n * is loaded through a lazy `import()` so that importing this SDK on Edge or in\n * a Worker stays safe: grpc-js is built on `node:http2`/`node:net`/`node:tls`\n * and a static import fails the BUILD there, not the call.\n */\n\nimport { agentModelOf, withAgentModel, type AgentModel } from '../agent-model.js';\nimport {\n InvalidInputError, ListeningAlreadyActiveError, ListeningNotActiveError, SynapError,\n SynapPermanentError,\n} from '../errors.js';\nimport type { AnticipationCache } from '../context/anticipation-cache.js';\nimport type { StreamCredentials, StreamState } from '../grpc/stream-client.js';\nimport { getEnv } from '../util/env.js';\nimport { newCorrelationId } from '../util/correlation.js';\nimport {\n MAX_STREAM_IMAGE_BYTES, normaliseContent, toInlineParts, type ContentPart,\n} from '../memories/parts.js';\n\n/**\n * The metadata key a streamed event's parts travel under. The proto has no\n * field for them, so they ride in metadata as a JSON string, and `content`\n * carries the placeholder rendering so an older server still records text.\n */\nexport const CONTENT_PARTS_METADATA_KEY = 'synap_content_parts';\n\nexport interface ListenOptions {\n /** Called with the attempt count each time the stream reconnects. */\n on_reconnect?: (attempt: number) => void;\n onReconnect?: (attempt: number) => void;\n /** Called with a reason string when the stream drops. */\n on_disconnect?: (reason: string) => void;\n onDisconnect?: (reason: string) => void;\n /**\n * Called for every bundle that arrives. Bundles are ALSO stored in the\n * anticipation cache automatically, so `fetch()` finds them without a round\n * trip; this callback is for observing, not for wiring up storage.\n */\n on_context?: (bundle: Record<string, unknown>) => void;\n onContext?: (bundle: Record<string, unknown>) => void;\n /** Overrides `SYNAP_GRPC_HOST`. */\n host?: string;\n /** Overrides `SYNAP_GRPC_PORT`. */\n port?: number;\n /** Overrides `SYNAP_GRPC_USE_TLS`. Plaintext only makes sense against localhost. */\n use_tls?: boolean;\n useTls?: boolean;\n}\n\nexport interface SendMessageOptions {\n /**\n * A string, or a list of strings, `TextPart`s and `FilePart`s (images). A\n * list with no file is joined with `\"\\n\"`. With a file, the parts go in\n * `metadata.synap_content_parts` (images inline as base64, at most 2.5 MB of\n * raw image bytes per event) and `content` becomes the placeholder text,\n * each image as `[image: <filename>]`.\n */\n content: string | ContentPart[];\n role?: string;\n conversation_id?: string;\n conversationId?: string;\n user_id?: string;\n userId?: string;\n customer_id?: string;\n customerId?: string;\n session_id?: string;\n sessionId?: string;\n event_type?: string;\n eventType?: string;\n metadata?: Record<string, string>;\n /** The agent's model, as on `conversation.record_message`. Python's `model=`. */\n model?: string;\n context_window?: number;\n contextWindow?: number;\n /**\n * Report a tool call on the stream. Python's `send_message` takes both, and\n * the proto has `tool_name` / `tool_args_json`; the JS surface simply never\n * exposed them, so a tool call could not be reported from JavaScript.\n */\n tool_name?: string;\n toolName?: string;\n tool_args?: Record<string, unknown>;\n toolArgs?: Record<string, unknown>;\n /**\n * What a tool returned. Travels in its own proto field, not in `content`: a\n * result is not something a person said, and everything that filters on\n * messages reads `content`.\n */\n tool_result?: unknown;\n toolResult?: unknown;\n /** Ties a result to the call that asked for it. */\n tool_call_id?: string;\n toolCallId?: string;\n search_queries?: string[];\n searchQueries?: string[];\n context_types?: string[];\n contextTypes?: string[];\n /**\n * The level of your scope ladder this conversation belongs to. Sent as the\n * event's `scope`; the server keeps the first one it sees. Since 0.5.18.\n */\n scope_path?: Record<string, string>;\n scopePath?: Record<string, string>;\n}\n\nexport interface RecordThinkingOptions {\n content: string;\n /**\n * Ordinal of this thought within the current turn. Sent as a `step_index`\n * metadata key, which is how Python's `record_thinking` transmits it: the\n * proto has no dedicated field.\n */\n step_index?: number;\n stepIndex?: number;\n /** Free-form label for the kind of reasoning. Sent as `thought_type`. */\n thought_type?: string;\n thoughtType?: string;\n conversation_id?: string;\n conversationId?: string;\n user_id?: string;\n userId?: string;\n customer_id?: string;\n customerId?: string;\n session_id?: string;\n sessionId?: string;\n metadata?: Record<string, string>;\n}\n\nexport interface RecordToolCallOptions {\n tool_name?: string;\n toolName?: string;\n tool_args?: Record<string, unknown>;\n toolArgs?: Record<string, unknown>;\n tool_call_id?: string;\n toolCallId?: string;\n conversation_id?: string;\n conversationId?: string;\n user_id?: string;\n userId?: string;\n customer_id?: string;\n customerId?: string;\n session_id?: string;\n sessionId?: string;\n metadata?: Record<string, string>;\n}\n\nexport interface RecordToolResultOptions {\n /** JSON-encodable, or a plain string. A string is sent as itself. */\n result: unknown;\n tool_name?: string;\n toolName?: string;\n tool_call_id?: string;\n toolCallId?: string;\n conversation_id?: string;\n conversationId?: string;\n user_id?: string;\n userId?: string;\n customer_id?: string;\n customerId?: string;\n session_id?: string;\n sessionId?: string;\n metadata?: Record<string, string>;\n}\n\nexport interface InstanceNamespace {\n listen(options?: ListenOptions): Promise<void>;\n stop_listening(): Promise<void>;\n send_message(options: SendMessageOptions): Promise<void>;\n record_thinking(options: RecordThinkingOptions): Promise<void>;\n record_tool_call(options: RecordToolCallOptions): Promise<void>;\n record_tool_result(options: RecordToolResultOptions): Promise<void>;\n end_session(conversationId: string): Promise<void>;\n /** Property, not a method, matching Python's InstanceInterface.is_listening. */\n readonly is_listening: boolean;\n /** Not in Python: lets the compaction subscriptions share this one stream. */\n readonly _internal: InstanceInternals;\n}\n\n/** @internal Shared with the conversation namespace so both use one stream. */\nexport interface InstanceInternals {\n onCompactionUpdate(conversationId: string, bundle: Record<string, unknown>): void;\n /** Set by the client so a compaction can prune the locally buffered tail. */\n setCompactionApplier(apply: (bundle: Record<string, unknown>) => void): void;\n /**\n * Set by the client: called when `listen()` starts, which is when prefetched\n * bundles begin to arrive, so the local embedding model loads then.\n */\n setOnListen(handle: () => void): void;\n /** Set by the client in local mode: `listen()` then throws this message instead of opening a stream. */\n blockListen(message: string): void;\n /**\n * Set by the client. Receives the server's message count for a conversation\n * after each streamed write has been stored.\n */\n setConversationStateHandler(\n handle: (conversationId: string, messageCount: number) => void,\n ): void;\n /** Learning-loop event, fired after a fetch is served from the cache. */\n sendContextUsed(event: Record<string, unknown>): void;\n /** Audit event, fired after every fetch resolves. */\n sendContextAssembled(event: Record<string, unknown>): void;\n setCompactionDispatcher(\n dispatch: (conversationId: string, bundle: Record<string, unknown>) => void,\n ): void;\n isListening(): boolean;\n}\n\ntype StreamClient = import('../grpc/stream-client.js').GrpcStreamClient;\n\nconst DEFAULT_GRPC_HOST = 'synap-cloud-prod.maximem.ai';\nconst DEFAULT_GRPC_PORT = 443;\n\nfunction envPort(): number | undefined {\n const raw = getEnv('SYNAP_GRPC_PORT');\n if (raw === undefined || raw === '') return undefined;\n const parsed = Number(raw);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction envTls(): boolean | undefined {\n // SYNAP_GRPC_TLS is the 0.3.x wrapper's spelling. Honoured as a fallback,\n // because silently ignoring it turns a working plaintext deployment into one\n // that attempts TLS and cannot connect, with nothing pointing at the cause.\n const raw = getEnv('SYNAP_GRPC_USE_TLS') ?? getEnv('SYNAP_GRPC_TLS');\n if (raw === undefined || raw === '') return undefined;\n return !['0', 'false', 'no', 'off'].includes(raw.trim().toLowerCase());\n}\n\n/**\n * Fold `step_index` and `thought_type` into the metadata map.\n *\n * Python does exactly this (`sdk.py`, record_thinking): the proto carries no\n * dedicated fields, so the values ride in metadata under those two keys. A\n * caller-supplied metadata entry of the same name is not overwritten.\n */\nfunction thinkingMetadata(options: RecordThinkingOptions): Record<string, string> {\n const md: Record<string, string> = { ...(options.metadata ?? {}) };\n const step = options.step_index ?? options.stepIndex;\n if (step !== undefined && md['step_index'] === undefined) {\n md['step_index'] = String(step);\n }\n const kind = options.thought_type ?? options.thoughtType;\n if (kind && md['thought_type'] === undefined) {\n md['thought_type'] = kind;\n }\n return md;\n}\n\n/**\n * Event types the server has a reader for. Mirrors `KNOWN_EVENT_TYPES` in the\n * Python SDK. An unknown type falls through every classifier on the server into\n * UNKNOWN, where nothing reads it, so a typo used to cost the whole signal\n * without saying so.\n */\nconst KNOWN_EVENT_TYPES: ReadonlySet<string> = new Set([\n 'user_message',\n 'assistant_message',\n 'tool_call',\n 'tool_result',\n 'agent_thinking',\n 'context_request',\n 'context_fetch',\n 'session_start',\n 'session_end',\n]);\n\n/**\n * Serialise a tool result the way Python does: a string travels as itself,\n * anything else as JSON. `JSON.stringify` on a plain-text answer would wrap it\n * in quotes and the agent would read the quotes as part of the result.\n */\nfunction toolResultJson(result: unknown): string {\n if (result === undefined || result === null) return '';\n return typeof result === 'string' ? result : jsonOrText(result);\n}\n\n/**\n * JSON for whatever serialises, the value's text form for whatever does not.\n * Mirrors Python's `_json_or_text` in `sdk.py`.\n *\n * ⚠ This was a bare `JSON.stringify` and that lost events. It throws on a\n * circular object and on a `BigInt`, and it returns `undefined` rather than a\n * string for a function or a bare `undefined`. Every integration reports\n * through a helper that swallows exceptions on purpose, so a telemetry call can\n * never break somebody's agent loop, which means the throw went nowhere and the\n * whole tool event was silently never sent. Losing the exact shape of an object\n * is a far smaller loss than losing the event.\n */\nfunction jsonOrText(value: unknown): string {\n try {\n const out = JSON.stringify(\n value,\n (_k, v: unknown) => (typeof v === 'bigint' ? String(v) : v),\n );\n // `undefined` for a function, a symbol, or `undefined` itself.\n return out === undefined ? String(value) : out;\n } catch {\n // A cycle, or a `toJSON` of the caller's that throws.\n try {\n return String(value);\n } catch {\n return '';\n }\n }\n}\n\nexport function createInstanceNamespace(\n credentials: () => StreamCredentials,\n cache: AnticipationCache,\n /** Buffers a stream-sent turn locally, same as the HTTP write paths. */\n onTurn?: (turn: { conversationId: string; role: string; content: string }) => void,\n // `fetchUrl` was introduced before the later internal callbacks. Accept both\n // call layouts while consumers move to the current one:\n // (onTurn, fetchUrl, agentModel, onToolResult, checkCustomerId), and\n // (onTurn, agentModel, onToolResult, checkCustomerId).\n fetchOrAgentModel?: typeof fetch | (() => AgentModel),\n agentModelOrToolResult?: (() => AgentModel) | ((r: { conversationId: string; result: unknown; toolName: string }) => void),\n onToolResultOrCheck?: ((r: { conversationId: string; result: unknown; toolName: string }) => void) | ((customerId: unknown, where: string) => Promise<void>),\n checkCustomerIdArg?: (customerId: unknown, where: string) => Promise<void>,\n): InstanceNamespace {\n const defaultFetch = ((url: string, init?: RequestInit) => globalThis.fetch(url, init)) as typeof fetch;\n const imageFirst = fetchOrAgentModel !== undefined\n && (fetchOrAgentModel.length > 0 || agentModelOrToolResult === undefined);\n const fetchUrl = imageFirst ? fetchOrAgentModel as typeof fetch : defaultFetch;\n const agentModel = (imageFirst ? agentModelOrToolResult : fetchOrAgentModel) as (() => AgentModel) | undefined\n ?? (() => ({}));\n const onToolResult = (imageFirst ? onToolResultOrCheck : agentModelOrToolResult) as\n | ((r: { conversationId: string; result: unknown; toolName: string }) => void)\n | undefined;\n const checkCustomerId = (imageFirst ? checkCustomerIdArg : onToolResultOrCheck) as\n | ((customerId: unknown, where: string) => Promise<void>)\n | undefined\n ?? (async () => {});\n const hasCustomerIdCheck = (imageFirst ? checkCustomerIdArg : onToolResultOrCheck) !== undefined;\n let client: StreamClient | null = null;\n // conversationId -> sessionId, for conversations this stream has opened a\n // session for. Cleared on reconnect: a session belongs to the stream that\n // carried it, and the server's new stream has never seen it.\n const openSessions = new Map<string, string>();\n let dispatchCompaction:\n | ((conversationId: string, bundle: Record<string, unknown>) => void)\n | null = null;\n\n let applyCompaction: ((bundle: Record<string, unknown>) => void) | null = null;\n let onListen: (() => void) | null = null;\n let listenBlockedBy: string | null = null;\n let onConversationState: ((conversationId: string, messageCount: number) => void) | null =\n null;\n\n const internals: InstanceInternals = {\n onCompactionUpdate(conversationId, bundle) {\n // Prune the local tail FIRST, then notify subscribers, so a subscriber\n // that immediately fetches sees the post-compaction view.\n applyCompaction?.(bundle);\n dispatchCompaction?.(conversationId, bundle);\n },\n setCompactionApplier(apply) {\n applyCompaction = apply;\n },\n setOnListen(handle) {\n onListen = handle;\n },\n blockListen(message) {\n listenBlockedBy = message;\n },\n setConversationStateHandler(handle) {\n onConversationState = handle;\n },\n sendContextUsed(event) {\n // Fire-and-forget. A reconnecting stream holds the report and sends it\n // when it is back; with no stream at all (listen never started, or\n // stopped) nothing was prefetched, so there is no hit to report.\n client?.sendContextUsed(event);\n },\n sendContextAssembled(event) {\n client?.sendContextAssembled(event);\n },\n setCompactionDispatcher(dispatch) {\n dispatchCompaction = dispatch;\n },\n isListening() {\n return client !== null && client.isConnected;\n },\n };\n\n /**\n * Open a session for this conversation if the stream has not yet.\n *\n * The developer never calls this. `session_start` is what makes the server\n * run its warm-up prefetch before the first message arrives, and asking every\n * caller to remember a lifecycle call is how the first turn of every\n * conversation stayed a cold fetch: neither SDK sent one, ever.\n *\n * Best effort. A session that cannot be opened must not stop the event that\n * triggered it, so the conversation stays unmarked and the next event retries.\n */\n function ensureSession(\n conversationId: string, userId: string, customerId: string,\n ): void {\n // Both ids, or no session. The server refuses a session_start with no\n // user_id, and writing one only says it went out, not that it was\n // accepted — so opening on an event with no user_id marked the\n // conversation as open, never retried, and left `end_session` referring to\n // a session the server never had. The next event that carries a user_id\n // opens it.\n if (!conversationId || !userId || client === null) return;\n if (openSessions.has(conversationId)) return;\n // The same helper the correlation ids use: a session id is an identifier\n // for tracing, never a security value, and that helper is the one that is\n // safe on Edge and Workers, where `node:crypto` breaks the build.\n const sessionId = newCorrelationId();\n try {\n client.sendSessionControl({\n action: 'start',\n session_id: sessionId,\n conversation_id: conversationId,\n ...(userId ? { user_id: userId } : {}),\n ...(customerId ? { customer_id: customerId } : {}),\n });\n openSessions.set(conversationId, sessionId);\n } catch {\n // Leave it unmarked so the next event opens it.\n }\n }\n\n /**\n * Keeps conversation events in call order.\n *\n * A send whose content holds a file has to read it first, which is async,\n * so a caller who fires `send_message(image)` then `send_message(text)`\n * without awaiting would otherwise see the text reach the stream first. A\n * send that needs no read, while nothing is queued ahead of it, goes out\n * synchronously exactly as it always did; anything else waits its turn. File\n * reads still start at once, so only the sending is serialised.\n */\n let tail: Promise<void> = Promise.resolve();\n let queued = 0;\n function inOrder<T>(prepared: Promise<T> | null, send: (value: T) => void, sync?: T): Promise<void> {\n if (prepared === null && queued === 0) {\n send(sync as T);\n return Promise.resolve();\n }\n // Marked handled now: a rejection is surfaced through `run`, but only once\n // the sends ahead of it are done, and Node must not flag it before then.\n prepared?.catch(() => {});\n queued += 1;\n const run = tail.then(async () => {\n send(prepared === null ? (sync as T) : await prepared);\n });\n const done = () => {\n queued -= 1;\n };\n // The chain never rejects, so one failed send cannot block the next.\n tail = run.then(done, done);\n return run;\n }\n\n const namespace: InstanceNamespace = {\n async listen(options: ListenOptions = {}) {\n if (listenBlockedBy !== null) throw new SynapPermanentError(listenBlockedBy);\n if (client !== null) {\n // Python raises this from InstanceController when a second listen()\n // lands on an already-active stream.\n throw new ListeningAlreadyActiveError('Listening is already active on this instance');\n }\n\n try {\n onListen?.();\n } catch {\n /* loading the local model must never stop the stream */\n }\n const { GrpcStreamClient } = await import('../grpc/stream-client.js');\n const onContext = options.on_context ?? options.onContext;\n const onDisconnect = options.on_disconnect ?? options.onDisconnect;\n const onReconnect = options.on_reconnect ?? options.onReconnect;\n let reconnectAttempts = 0;\n\n // Assigned immediately below; the callbacks that read it only run later,\n // once the stream is live.\n let stream: InstanceType<typeof GrpcStreamClient> | null = null;\n\n const created = new GrpcStreamClient(credentials(), cache, {\n host: options.host ?? getEnv('SYNAP_GRPC_HOST') ?? DEFAULT_GRPC_HOST,\n port: options.port ?? envPort() ?? DEFAULT_GRPC_PORT,\n useTls: options.use_tls ?? options.useTls ?? envTls() ?? true,\n ...(onContext !== undefined ? { onContext } : {}),\n onCompactionUpdate: (conversationId, bundle) => {\n internals.onCompactionUpdate(conversationId, bundle);\n },\n onConversationState: (conversationId, messageCount) => {\n onConversationState?.(conversationId, messageCount);\n },\n onStateChange: (state: StreamState) => {\n // Any state change away from connected retires the sessions this\n // stream opened: the server's next stream has no memory of them, and\n // a client that believes one is open never warms up again.\n if (state !== 'connected') openSessions.clear();\n if (state === 'reconnecting') {\n reconnectAttempts += 1;\n onReconnect?.(reconnectAttempts);\n } else if (state === 'disconnected') {\n // A credit refusal names itself, the way Python's transport does,\n // so a handler can tell \"the server ran out of patience\" from\n // \"this account cannot pay for the stream\".\n const stopped = stream?.lastError ?? null;\n const reason = stopped === null\n ? 'stream disconnected'\n : `credit_stop:${(stopped as { reason?: string | null }).reason ?? 'unknown'}`;\n onDisconnect?.(reason);\n }\n },\n });\n stream = created;\n\n try {\n await created.connect();\n } catch (error) {\n // Leave `client` null so a retry is possible rather than being\n // rejected as \"already active\" forever.\n if (error instanceof SynapError) throw error;\n throw new SynapError(\n `Could not open the Synap anticipation stream: ${(error as Error)?.message ?? String(error)}`,\n { cause: error },\n );\n }\n client = created;\n },\n\n async stop_listening() {\n // Resolves rather than rejecting: stopping something that was never\n // started is a no-op in Python too, and a cleanup path that throws is\n // worse than useless in a finally block.\n if (client === null) return;\n // Close what this stream opened. A session that is never closed leaves\n // the turn it was in the middle of uncommitted on the server: that row is\n // written when the NEXT user message arrives, and the last turn of a\n // conversation has no next one.\n for (const conversationId of [...openSessions.keys()]) {\n await namespace.end_session(conversationId);\n }\n const active = client;\n client = null;\n await active.disconnect();\n },\n\n async end_session(conversationId: string) {\n const sessionId = openSessions.get(conversationId);\n if (sessionId === undefined || client === null) return;\n openSessions.delete(conversationId);\n try {\n client.sendSessionControl({\n action: 'end',\n session_id: sessionId,\n conversation_id: conversationId,\n });\n } catch {\n // A teardown path must not throw.\n }\n },\n\n async send_message(options: SendMessageOptions) {\n // First, as Python checks it. Until 0.5.18 the stream skipped it, so a\n // B2C customer_id went out and the server refused the event on the\n // stream, where nothing surfaced it.\n if (hasCustomerIdCheck) {\n await checkCustomerId(\n options.customer_id ?? options.customerId, 'instance.send_message',\n );\n }\n if (client === null) throw new ListeningNotActiveError('Listening is not active');\n const eventType = options.event_type ?? options.eventType ?? 'user_message';\n // InvalidInputError, as Python raises both. Until 0.5.18 a bad\n // event_type was a bare SynapError and a missing content a\n // ListeningNotActiveError.\n if (!KNOWN_EVENT_TYPES.has(eventType)) {\n throw new InvalidInputError(\n `unknown event_type '${eventType}'. Expected one of: `\n + [...KNOWN_EVENT_TYPES].sort().join(', '),\n );\n }\n if (options.content === undefined || options.content === null) {\n throw new InvalidInputError('content is required');\n }\n const parts = normaliseContent(options.content, 'content');\n const emit = ({ content, metadata }: { content: string; metadata: Record<string, string> }) => {\n // A file read can take a while; the stream may have gone in the meantime.\n if (client === null) throw new ListeningNotActiveError('Listening is not active');\n const conversationId = options.conversation_id ?? options.conversationId ?? '';\n ensureSession(\n conversationId,\n options.user_id ?? options.userId ?? '',\n options.customer_id ?? options.customerId ?? '',\n );\n // Only conversational turns belong in the local short-term buffer. A tool\n // call or a result is not a turn, and buffering one splices it into the\n // caller's own prompt as if somebody had said it. Python mirrors user and\n // assistant messages only; this side mirrored everything.\n if (eventType === 'user_message' || eventType === 'assistant_message') {\n onTurn?.({\n conversationId,\n role: options.role ?? 'user',\n content,\n });\n }\n client.sendConversationEvent({\n event_type: eventType,\n content,\n role: options.role ?? 'user',\n conversation_id: options.conversation_id ?? options.conversationId ?? '',\n user_id: options.user_id ?? options.userId ?? '',\n customer_id: options.customer_id ?? options.customerId ?? '',\n session_id: options.session_id ?? options.sessionId\n ?? openSessions.get(conversationId) ?? '',\n metadata: withAgentModel(metadata, agentModelOf(options), agentModel(), true) ?? {},\n timestamp_ms: Date.now(),\n tool_name: options.tool_name ?? options.toolName ?? '',\n // Python serialises tool_args with json.dumps into tool_args_json.\n tool_args_json: (() => {\n const a = options.tool_args ?? options.toolArgs;\n return a === undefined ? '' : jsonOrText(a);\n })(),\n tool_result_json: toolResultJson(options.tool_result ?? options.toolResult),\n tool_call_id: options.tool_call_id ?? options.toolCallId ?? '',\n search_queries: options.search_queries ?? options.searchQueries ?? [],\n context_types: options.context_types ?? options.contextTypes ?? [],\n ...(() => {\n const sp = options.scope_path ?? options.scopePath;\n return sp && Object.keys(sp).length > 0 ? { scope: sp } : {};\n })(),\n });\n };\n\n if (parts?.kind !== 'parts') {\n const content = parts?.kind === 'text' ? parts.text : (options.content as string);\n return inOrder(null, emit, { content, metadata: options.metadata ?? {} });\n }\n const prepared = (async () => {\n const inline = await toInlineParts(parts.parts, fetchUrl);\n if (inline.rawBytes > MAX_STREAM_IMAGE_BYTES) {\n // Python's message, word for word.\n throw new InvalidInputError(\n `The images in this event come to more than ${MAX_STREAM_IMAGE_BYTES} bytes, ` +\n 'which is over what one streamed event can carry. Send them with ' +\n 'memories.create or conversation.record_message instead.',\n );\n }\n return {\n content: inline.placeholder,\n metadata: {\n ...(options.metadata ?? {}),\n [CONTENT_PARTS_METADATA_KEY]: JSON.stringify(inline.wire),\n },\n };\n })();\n return inOrder(prepared, emit);\n },\n\n async record_tool_call(options: RecordToolCallOptions) {\n // Prefer this over `send_message({ event_type: 'tool_call' })`. The event\n // carries both an event_type and a role and the two have to agree;\n // getting the role wrong was silent, and our own published example got it\n // wrong. Here you cannot: the method sets both.\n await namespace.send_message({\n content: '',\n role: 'assistant',\n event_type: 'tool_call',\n tool_name: options.tool_name ?? options.toolName ?? '',\n ...(options.tool_args ?? options.toolArgs\n ? { tool_args: options.tool_args ?? options.toolArgs }\n : {}),\n tool_call_id: options.tool_call_id ?? options.toolCallId ?? '',\n conversation_id: options.conversation_id ?? options.conversationId ?? '',\n user_id: options.user_id ?? options.userId ?? '',\n customer_id: options.customer_id ?? options.customerId ?? '',\n session_id: options.session_id ?? options.sessionId ?? '',\n metadata: options.metadata ?? {},\n });\n },\n\n async record_tool_result(options: RecordToolResultOptions) {\n // ⚠ A tool result is usually the caller's customer data. It is an\n // anticipation hint and is not written into long-term memory, but it does\n // reach us: send what the agent needs, not the whole row.\n const conversationId = options.conversation_id ?? options.conversationId ?? '';\n if (conversationId) {\n onToolResult?.({ conversationId, result: options.result, toolName: options.tool_name ?? options.toolName ?? '' });\n }\n await namespace.send_message({\n content: '',\n role: 'tool',\n event_type: 'tool_result',\n tool_result: options.result,\n tool_name: options.tool_name ?? options.toolName ?? '',\n tool_call_id: options.tool_call_id ?? options.toolCallId ?? '',\n conversation_id: options.conversation_id ?? options.conversationId ?? '',\n user_id: options.user_id ?? options.userId ?? '',\n customer_id: options.customer_id ?? options.customerId ?? '',\n session_id: options.session_id ?? options.sessionId ?? '',\n metadata: options.metadata ?? {},\n });\n },\n\n async record_thinking(options: RecordThinkingOptions) {\n if (client === null) throw new ListeningNotActiveError('Listening is not active');\n const conversationId = options.conversation_id ?? options.conversationId ?? '';\n ensureSession(\n conversationId,\n options.user_id ?? options.userId ?? '',\n options.customer_id ?? options.customerId ?? '',\n );\n // Queued behind an earlier send that is still reading a file, so the\n // thought reaches the stream after it, as it was called.\n return inOrder(null, () => {\n if (client === null) throw new ListeningNotActiveError('Listening is not active');\n client.sendConversationEvent({\n // Python emits reasoning as an `agent_thinking` conversation event.\n event_type: 'agent_thinking',\n content: options.content,\n // Deliberately no role. A thought is not the assistant's reply, and\n // this went out as 'assistant' from the day it shipped: the server\n // checked role before event_type, so every reasoning step any client\n // sent was filed as the final answer and the reasoning path never ran.\n // Sending no role is correct against both the fixed server and one that\n // has not been updated yet.\n role: '',\n conversation_id: options.conversation_id ?? options.conversationId ?? '',\n user_id: options.user_id ?? options.userId ?? '',\n customer_id: options.customer_id ?? options.customerId ?? '',\n session_id: options.session_id ?? options.sessionId ?? '',\n metadata: thinkingMetadata(options),\n timestamp_ms: Date.now(),\n });\n }, undefined);\n },\n\n get is_listening() {\n return client !== null && client.isConnected;\n },\n\n _internal: internals,\n };\n\n return namespace;\n}\n","/**\n * Kept in sync with package.json by the release workflow, in the\n * \"Sync SDK_VERSION to the resolved version\" step of publish-npm-js-sdk.yml.\n *\n * Until that step existed nothing kept it in sync, so this constant sat at\n * 1.0.0-beta.0 while the package shipped 0.4.x, and every request's User-Agent\n * and every telemetry event reported a version that was never released.\n *\n * ⚠ The workflow only covers a workflow release. 0.4.8 was published by hand\n * and shipped reporting 0.4.7, so every request from it carries a User-Agent\n * for a version it is not. `version-matches-package.test.ts` now fails the\n * build when the two disagree, which is the only thing that makes a manual\n * publish safe.\n */\nexport const SDK_VERSION = '0.6.8';\n","/**\n * Client registry: one shared client per identity, per process.\n *\n * Mirrors Python's `registry.py`. Without it, every `new SynapClient()` gets\n * its own anticipation cache, so a framework integration that constructs a\n * client per request or per agent never gets a cache hit and pays for a fresh\n * retrieval every time. Python has shared state here since 0.2; matching it is\n * the difference between a warm cache and a metered fetch on every turn.\n *\n * JavaScript reaches the same end differently. Python does\n * `self.__dict__ = existing.__dict__`, aliasing state between distinct\n * objects. A JS constructor can simply RETURN the existing instance, so the\n * two callers hold the same object rather than two objects sharing a state\n * bag. That is stricter than Python and avoids its `__dict__`-identity\n * comparisons entirely.\n */\n\n/** Kept structural so the registry does not depend on the client's type. */\nexport interface RegistrableClient {\n shutdown(): Promise<void>;\n}\n\nconst instances = new Map<string, RegistrableClient>();\n\n/**\n * Which registry slot an identity belongs in.\n *\n * `instanceId` keys the singleton when present, but it is usually empty at\n * construction and only resolved from the API key during `initialize()`.\n * Keying on it directly would put every `new SynapClient({ apiKey })` in one\n * process onto the single `''` slot, where the second would adopt the first's\n * credentials. So fall back to the credential that WILL resolve the identity,\n * stored as a truncated SHA-256 digest rather than plaintext, so a registry\n * dump or a log line cannot leak a key.\n *\n * `SYNAP_INSTANCE_ID` is deliberately not consulted: the client applies that\n * fallback after the lookup, and honouring it here would put two different\n * credentials back onto one slot whenever the variable happens to be set.\n */\nexport function buildRegistryKey(instanceId: string, apiKey: string | undefined): string {\n if (instanceId) return instanceId;\n const key = apiKey ?? '';\n // Nothing to key on. The client cannot initialise without a credential\n // anyway, so preserve the empty slot rather than inventing one.\n if (!key) return '';\n return `apikey:${digest(key)}`;\n}\n\n/**\n * 64-bit FNV-1a over the credential.\n *\n * Python uses SHA-256 here. This cannot: the digest is needed synchronously\n * inside a constructor, `node:crypto` is unavailable on Edge and Workers (and\n * a static import of it would fail those builds outright), and Web Crypto's\n * `subtle.digest` is async. So this is a non-cryptographic digest, chosen for\n * the one property that actually matters here: the raw key never becomes a Map\n * key that something could enumerate or log.\n *\n * It is not collision-resistant against an adversary, and it does not need to\n * be. A collision would make two clients share state, so the bound that\n * matters is accidental collision between the handful of distinct API keys\n * present in a single process, which at 64 bits is negligible. It is never\n * persisted, never sent anywhere, and never compared against anything outside\n * this module.\n */\nfunction digest(value: string): string {\n // FNV-1a, 64-bit. BigInt keeps the arithmetic exact; Number would lose\n // precision past 2^53 and collapse the space.\n const PRIME = 1099511628211n;\n const MASK = 0xffffffffffffffffn;\n let hash = 14695981039346656037n;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= BigInt(value.charCodeAt(i));\n hash = (hash * PRIME) & MASK;\n }\n return hash.toString(16).padStart(16, '0');\n}\n\nexport function get(key: string): RegistrableClient | undefined {\n return instances.get(key);\n}\n\n/**\n * Claim `key` for `client`, or hand back whoever already holds it.\n *\n * A separate `get` then `set` would let two callers constructing the first\n * client for one identity both miss the lookup, with the second overwriting\n * the first. JavaScript's single-threaded execution makes that impossible\n * between two synchronous statements, so this is a single operation for\n * clarity rather than for locking: there is no equivalent of Python's mutex\n * to hold, and none is needed.\n *\n * Returns `undefined` when `client` won the slot, or the incumbent when not.\n */\nexport function registerIfAbsent(\n key: string,\n client: RegistrableClient,\n): RegistrableClient | undefined {\n const existing = instances.get(key);\n if (existing !== undefined) return existing;\n instances.set(key, client);\n return undefined;\n}\n\n/**\n * Point `key` at `client` as well, unless the slot is taken.\n *\n * Used once `initialize()` resolves the real instance id. The client was keyed\n * on its credential because the id did not exist yet, so a later\n * `new SynapClient({ instanceId })` for that same instance would miss and\n * build a second client: two anticipation caches and two Listen streams for\n * one instance. The credential slot is KEPT rather than moved, so constructing\n * by API key keeps returning the same client too.\n *\n * An occupied target is never clobbered. Evicting a live client is worse than\n * the duplication it would fix.\n */\nexport function aliasIfAbsent(key: string, client: RegistrableClient): boolean {\n if (!key || instances.has(key)) return false;\n instances.set(key, client);\n return true;\n}\n\n/**\n * Drop `key`, but only if it still points at `client`.\n *\n * A shutting-down client must not evict whoever currently holds its old slot.\n */\nexport function unregisterIfOwner(key: string, client: RegistrableClient): void {\n if (instances.get(key) === client) instances.delete(key);\n}\n\n/** Test seam. Never call this from library code. */\nexport function clear(): void {\n instances.clear();\n}\n\n/** Diagnostics only. */\nexport function size(): number {\n return instances.size;\n}\n","/**\n * Per-conversation short-term context, held locally.\n *\n * Mirrors Python's `cache/short_term_store.py`. This is what makes reads see\n * your own writes: a turn recorded a moment ago is buffered here and spliced\n * onto the next fetch, so a fast follow-up does not retrieve context that omits\n * what the user just said. Python's own comment on the overlay puts it plainly:\n * the pre-compaction window \"is exactly when the playground's fast follow-ups\n * happen.\"\n *\n * LRU by conversation, with an absolute age cap. Everything here is per process\n * and holds only what this process wrote, so nothing is authoritative: the\n * server's view wins for the summary fields, and this only ever contributes the\n * verbatim tail.\n *\n * Holding an entry is not the same as holding the conversation. A process that\n * restarted, evicted the entry, or shares the conversation with another process\n * has only the turns it recorded itself. So the server reports how many\n * messages it holds, on every write and on every compaction bundle, and\n * `isComplete()` says whether the entry can answer on its own. When it cannot,\n * the caller asks the server and hands the answer to `reseed`.\n */\n\nimport type { TurnStore } from './turn-store.js';\n\nconst DEFAULT_MAX_CONVERSATIONS = 100;\n/** 12 hours, as in Python. */\nconst DEFAULT_MAX_AGE_MS = 12 * 60 * 60 * 1000;\n\nexport interface ShortTermTurn {\n role: string;\n content: string;\n /** ISO-8601. */\n timestamp: string;\n /** The server's id for the turn, when the write returned one. */\n message_id?: string;\n}\n\n/**\n * How every v3 context_block begins (server: compaction/v3/render.py). A\n * summary that begins this way IS the block, which is how a REST-fed entry is\n * recognised. Same constant as Python's `CONTEXT_BLOCK_PREFIX`.\n */\nexport const CONTEXT_BLOCK_PREFIX = '## Conversation so far (compacted';\n\n/** The v3 block in a conversation_context payload, or null (v2 server). */\nexport function contextBlockOf(cc: Record<string, unknown>): string | null {\n const block = cc['context_block'];\n if (typeof block === 'string' && block) return block;\n const summary = cc['summary'];\n if (typeof summary === 'string' && summary.startsWith(CONTEXT_BLOCK_PREFIX)) return summary;\n return null;\n}\n\nexport interface ShortTermEntry {\n conversationId: string;\n summary: string | null;\n /**\n * Compaction v3: the server's one framed block, printed as received and\n * once. When set, the paragraphs are not used (the server sends them empty).\n */\n contextBlock: string | null;\n factualParagraph: string | null;\n conversationalParagraph: string | null;\n currentState: Record<string, unknown>;\n keyExtractions: Record<string, unknown>;\n compactionId: string | null;\n compactedAt: string | null;\n endTimestamp: string | null;\n recentTurns: ShortTermTurn[];\n lastActivityAt: number;\n // --- Completeness bookkeeping. See `isComplete`. ---\n /** Messages the cached summary covers, from the start of the conversation. */\n compactedMessageCount: number;\n /** The highest message count the server has reported. null = never heard. */\n serverMessageCount: number | null;\n /**\n * The server has confirmed at least one write made by this process. A\n * process that only reads never hears a count again after it is seeded, so\n * it could not notice the conversation moving on without it.\n */\n participant: boolean;\n /** At some point this entry held everything the server held. */\n synced: boolean;\n /**\n * The server's count ran ahead of an entry that was in sync, so something\n * else is writing to this conversation. Latched: this process cannot see\n * those writes when they happen, only at its own next write.\n */\n shared: boolean;\n}\n\n/** What a write learned from the server about the turn and the conversation. */\nexport interface TurnConfirmation {\n /** The server's id for the turn. A turn already held under it is not appended twice. */\n messageId?: string | undefined;\n /** The conversation's message count as the server reported it on this write. */\n serverMessageCount?: number | null | undefined;\n /** Other writes this process still has outstanding for the conversation. */\n inFlight?: number | undefined;\n}\n\n/** What `/context-for-prompt` returned, as far as `reseed` needs it. */\nexport interface ServerPromptState {\n compactionId: string | null;\n recentMessages: ShortTermTurn[];\n compactedMessageCount: number;\n totalMessageCount: number;\n}\n\nexport function localMessageCount(entry: ShortTermEntry): number {\n return entry.compactedMessageCount + entry.recentTurns.length;\n}\n\n/**\n * Whether an entry can stand in for the server's short-term context.\n *\n * True when the server holds nothing this entry lacks. Holding MORE than the\n * server has confirmed is fine: those are this process's own turns, sent and\n * not yet counted.\n */\nexport function isComplete(entry: ShortTermEntry): boolean {\n return (\n entry.participant &&\n entry.synced &&\n !entry.shared &&\n entry.serverMessageCount !== null &&\n entry.serverMessageCount <= localMessageCount(entry)\n );\n}\n\n/**\n * Whether `turns` already holds `turn`.\n *\n * By message id where both sides have one. Otherwise by role and text: a\n * streamed turn has no id (the server assigns it in a background write), and\n * the turns in a `fetch` response carry none either.\n */\nfunction heldIn(turn: ShortTermTurn, turns: ShortTermTurn[]): boolean {\n return turns.some((held) =>\n turn.message_id && held.message_id\n ? held.message_id === turn.message_id\n : held.role === turn.role && held.content === turn.content,\n );\n}\n\n/**\n * The local turns that come after everything in `serverTurns`.\n *\n * Walks back from the newest local turn and stops at the first one the\n * server's list already holds. What is left is what this process wrote or sent\n * after the server's list was built.\n *\n * A turn the server rewrote before storing it (a privacy policy) does not\n * match its local copy by text, so it can come back from here as well as from\n * the server. That shows one turn twice; it never loses one.\n */\nexport function turnsAfter(\n localTurns: readonly ShortTermTurn[],\n serverTurns: ShortTermTurn[],\n): ShortTermTurn[] {\n const newer: ShortTermTurn[] = [];\n for (let i = localTurns.length - 1; i >= 0; i -= 1) {\n const turn = localTurns[i] as ShortTermTurn;\n if (heldIn(turn, serverTurns)) break;\n newer.unshift(turn);\n }\n return newer;\n}\n\nexport interface ShortTermStoreOptions {\n maxConversations?: number;\n maxAgeMs?: number;\n /** Injected in tests. Wall clock, because entries are compared to ISO stamps. */\n now?: () => number;\n}\n\n/** Parse an ISO-8601 stamp to epoch millis, or null. */\nexport function parseIso(value: unknown): number | null {\n if (value === null || value === undefined || value === '') return null;\n if (value instanceof Date) return value.getTime();\n if (typeof value !== 'string') return null;\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? null : parsed;\n}\n\n/**\n * True when a turn is strictly after the cutoff.\n *\n * An unparseable timestamp KEEPS the turn. Dropping it would silently lose a\n * message, which is worse than briefly showing one the server has already\n * folded into its summary.\n */\nfunction isAfter(turnTimestamp: unknown, cutoffMs: number): boolean {\n const parsed = parseIso(turnTimestamp);\n if (parsed === null) return true;\n return parsed > cutoffMs;\n}\n\nexport class ShortTermStore {\n // Insertion order IS the LRU order: re-inserting on touch moves an entry to\n // the end, so the first key Map yields is the least recently used.\n readonly #entries = new Map<string, ShortTermEntry>();\n readonly #maxConversations: number;\n readonly #maxAgeMs: number;\n readonly #now: () => number;\n\n /**\n * Every turn appended here is also kept in the archive (a TurnStore), which\n * a compaction does not prune: the turns it covers stay searchable locally\n * (history-search.ts). Python: `ShortTermContextStore.attach_archive`.\n */\n #archive: TurnStore | null = null;\n\n constructor(options: ShortTermStoreOptions = {}) {\n this.#maxConversations = options.maxConversations ?? DEFAULT_MAX_CONVERSATIONS;\n this.#maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;\n this.#now = options.now ?? (() => Date.now());\n }\n\n attachArchive(archive: TurnStore | null): void {\n this.#archive = archive;\n }\n\n get archive(): TurnStore | null {\n return this.#archive;\n }\n\n /** The entry, or null. Age-evicts on read, as Python does. */\n get(conversationId: string): ShortTermEntry | null {\n if (!conversationId) return null;\n const entry = this.#entries.get(conversationId);\n if (entry === undefined) return null;\n if (this.#now() - entry.lastActivityAt > this.#maxAgeMs) {\n this.#entries.delete(conversationId);\n return null;\n }\n this.#touch(conversationId, entry);\n return entry;\n }\n\n has(conversationId: string): boolean {\n return this.get(conversationId) !== null;\n }\n\n get size(): number {\n return this.#entries.size;\n }\n\n /**\n * Append a raw turn.\n *\n * Called from `record_message` and the stream's `send_message`. When no entry\n * exists yet (the first turn, before any compaction has arrived) a fresh one\n * is created with an empty summary; the next `compaction_update` fills the\n * summary fields in and prunes the turns it covers.\n *\n * `confirmation` is what the write learned from the server. See\n * `TurnConfirmation` and `noteServerCount`.\n */\n appendTurn(\n conversationId: string,\n role: string,\n content: string,\n timestamp?: string,\n confirmation: TurnConfirmation = {},\n ): void {\n if (!conversationId) return;\n const stamp = timestamp ?? new Date(this.#now()).toISOString();\n if (this.#archive !== null) {\n try {\n this.#archive.add(conversationId, role, content, stamp, { messageId: confirmation.messageId ?? null });\n } catch {\n // The archive never blocks the prompt path.\n }\n }\n const entry = this.#entries.get(conversationId) ?? this.#blank(conversationId);\n const messageId = confirmation.messageId;\n const alreadyHeld =\n Boolean(messageId) && entry.recentTurns.some((t) => t.message_id === messageId);\n if (!alreadyHeld) {\n const turn: ShortTermTurn = { role, content, timestamp: stamp };\n if (messageId) turn.message_id = messageId;\n entry.recentTurns.push(turn);\n }\n const count = confirmation.serverMessageCount;\n if (count !== null && count !== undefined) {\n this.#noteCount(entry, Number(count), confirmation.inFlight ?? 0);\n }\n entry.lastActivityAt = parseIso(stamp) ?? this.#now();\n this.#touch(conversationId, entry);\n this.#evict();\n }\n\n /**\n * Record the server's message count for a conversation.\n *\n * The streamed write path's half of `appendTurn`'s confirmation: a streamed\n * turn is appended when it is sent, and the count arrives later, once the\n * server has written it. A count for a conversation this process holds\n * nothing for is ignored.\n */\n noteServerCount(conversationId: string, count: number): void {\n if (!conversationId) return;\n const entry = this.#entries.get(conversationId);\n if (entry !== undefined) this.#noteCount(entry, Number(count), 0);\n }\n\n /**\n * Compare the server's count with what the entry holds.\n *\n * The count is taken after one of this process's own writes, so it proves\n * the process takes part in the conversation.\n *\n * Server ahead of an entry that was in sync: something else wrote, and the\n * entry is marked shared for good. Server ahead of an entry that was never\n * in sync: this process joined late (a restart, an eviction), and `reseed`\n * will fix it. `inFlight` covers this process's own writes that the server\n * has counted and the entry has not appended yet, so two concurrent writes\n * do not look like a second writer.\n */\n #noteCount(entry: ShortTermEntry, count: number, inFlight: number): void {\n entry.participant = true;\n if (count > localMessageCount(entry) + inFlight) {\n if (entry.synced) entry.shared = true;\n } else if (entry.serverMessageCount === null) {\n // First word from the server, and nothing is missing.\n entry.synced = true;\n }\n entry.serverMessageCount = Math.max(entry.serverMessageCount ?? 0, count);\n }\n\n /**\n * Apply a `compaction_update` bundle.\n *\n * Replaces the summary fields from the bundle's `conversation_context` and\n * drops the buffered turns the new summary covers.\n *\n * Which turns those are is decided by count, not by clock. The bundle says\n * how many messages the summary covers and how many the conversation held\n * when the bundle was built, so the last `total - compacted` of its\n * `recent_turns` are exactly the uncovered messages. Turns this process\n * appended after the server took that count are kept behind them. Timestamps\n * cannot do this job: the REST write returns the time of the response and\n * not of the stored row, a caller may supply its own message time, and a\n * streamed turn is stamped when a background write runs.\n *\n * A bundle from a server that sends no counts falls back to the older\n * timestamp prune, and the entry is left out of sync so it is never used to\n * answer on its own.\n */\n applyCompaction(bundle: Record<string, unknown>): void {\n if (typeof bundle !== 'object' || bundle === null) return;\n const cc = (bundle['conversation_context'] ?? {}) as Record<string, unknown>;\n const conversationId = String(\n cc['conversation_id'] ??\n bundle['anticipation_conversation_id'] ??\n bundle['conversation_id'] ??\n '',\n );\n if (!conversationId) return;\n\n const endTs = parseIso(cc['end_timestamp'] ?? cc['compacted_at']);\n const compactedAt = parseIso(cc['compacted_at']);\n const compactedCount = Number(cc['compacted_message_count'] ?? 0) || 0;\n const totalCount = Number(cc['total_message_count'] ?? 0) || 0;\n const entry = this.#entries.get(conversationId) ?? this.#blank(conversationId);\n\n const heldAt = parseIso(entry.compactedAt);\n // An older compaction must not replace a newer one.\n if (compactedAt !== null && heldAt !== null && compactedAt < heldAt) return;\n\n // `x || existing` throughout, matching Python: a blank field from the\n // server must not erase what is already held.\n const block = contextBlockOf(cc);\n if (block) {\n // A v3 compaction replaces the whole record. Keeping a v2 paragraph\n // cached from an earlier push would print it next to the block, so the\n // paragraphs are cleared, not kept.\n entry.contextBlock = block;\n entry.summary = (cc['summary'] as string) || block;\n entry.factualParagraph = null;\n entry.conversationalParagraph = null;\n } else {\n entry.summary = (cc['summary'] as string) || entry.summary;\n entry.factualParagraph = (cc['factual_paragraph'] as string) || entry.factualParagraph;\n entry.conversationalParagraph =\n (cc['conversational_paragraph'] as string) || entry.conversationalParagraph;\n }\n entry.currentState = { ...((cc['current_state'] as Record<string, unknown>) ?? {}) };\n entry.keyExtractions = { ...((cc['key_extractions'] as Record<string, unknown>) ?? {}) };\n entry.compactionId = (cc['compaction_id'] as string) || entry.compactionId;\n entry.compactedAt = (cc['compacted_at'] as string) || entry.compactedAt;\n entry.endTimestamp = (cc['end_timestamp'] as string) || entry.endTimestamp;\n\n if (compactedCount > 0 && compactedCount <= totalCount) {\n const uncovered = totalCount - compactedCount;\n const serverTurns = Array.isArray(cc['recent_turns'])\n ? (cc['recent_turns'] as ShortTermTurn[])\n : [];\n const tail: ShortTermTurn[] =\n uncovered > 0 ? serverTurns.slice(-uncovered).map((t) => ({ ...t })) : [];\n // Turns appended here after the server counted. Only an entry that was\n // in sync knows how many of its own turns those are.\n const ahead = localMessageCount(entry) - totalCount;\n const newer =\n entry.synced && ahead > 0\n ? entry.recentTurns.slice(-ahead).filter((t) => !heldIn(t, tail))\n : [];\n entry.recentTurns = [...tail, ...newer];\n entry.compactedMessageCount = compactedCount;\n entry.serverMessageCount = Math.max(entry.serverMessageCount ?? 0, totalCount);\n // A short tail means the bundle did not carry every uncovered message,\n // so the entry cannot claim to hold them.\n entry.synced = tail.length === uncovered;\n } else {\n if (endTs !== null && entry.recentTurns.length > 0) {\n entry.recentTurns = entry.recentTurns.filter((t) => isAfter(t.timestamp, endTs));\n }\n entry.synced = false;\n }\n entry.lastActivityAt = this.#now();\n this.#touch(conversationId, entry);\n this.#evict();\n }\n\n /**\n * Bring an entry back in step from a `/context-for-prompt` response.\n *\n * Called after the server was asked because the entry was not complete. The\n * response lists every message the server's summary does not cover, which is\n * what `recentTurns` is meant to hold.\n *\n * Only an entry that already exists is reseeded. Creating one here would let\n * a process that never writes to the conversation answer from a snapshot it\n * has no way to refresh.\n *\n * If the server's summary is not the one cached here, the entry cannot\n * render it, so it stays out of sync until the next bundle brings the\n * summary itself.\n *\n * Turns held locally and absent from the response are kept when they come\n * after everything the response has: they were written or sent after the\n * server read its messages.\n */\n reseed(conversationId: string, state: ServerPromptState): void {\n if (!conversationId) return;\n const entry = this.#entries.get(conversationId);\n if (entry === undefined || entry.shared) return;\n entry.serverMessageCount = Math.max(\n entry.serverMessageCount ?? 0,\n Number(state.totalMessageCount) || 0,\n );\n if ((state.compactionId || null) !== entry.compactionId) {\n entry.synced = false;\n return;\n }\n const serverTurns = state.recentMessages.map((m) => ({ ...m }));\n entry.recentTurns = [...serverTurns, ...turnsAfter(entry.recentTurns, serverTurns)];\n entry.compactedMessageCount = Number(state.compactedMessageCount) || 0;\n entry.synced = true;\n }\n\n invalidate(conversationId: string): void {\n this.#entries.delete(conversationId);\n }\n\n clear(): void {\n this.#entries.clear();\n }\n\n #blank(conversationId: string): ShortTermEntry {\n return {\n conversationId,\n summary: null,\n contextBlock: null,\n factualParagraph: null,\n conversationalParagraph: null,\n currentState: {},\n keyExtractions: {},\n compactionId: null,\n compactedAt: null,\n endTimestamp: null,\n recentTurns: [],\n lastActivityAt: this.#now(),\n compactedMessageCount: 0,\n serverMessageCount: null,\n participant: false,\n synced: false,\n shared: false,\n };\n }\n\n /** Re-insert so this key becomes the most recently used. */\n #touch(conversationId: string, entry: ShortTermEntry): void {\n this.#entries.delete(conversationId);\n this.#entries.set(conversationId, entry);\n }\n\n #evict(): void {\n while (this.#entries.size > this.#maxConversations) {\n const oldest = this.#entries.keys().next();\n if (oldest.done === true) break;\n this.#entries.delete(oldest.value);\n }\n }\n}\n","/**\n * Local store of a conversation's raw turns, for search after compaction.\n *\n * Port of `maximem_synap/cache/turn_store.py`. The short-term store keeps\n * only the turns a compaction has not covered yet; this store keeps every\n * turn this process saw or fetched, so the details a compaction leaves out\n * can be found again by a local search (history-search.ts).\n *\n * Python keeps it in a SQLite file under ~/.synap. This one holds it in\n * memory, with the same limits and the same answers, because the SDK also\n * runs in browsers and edge runtimes, and the main entry may not load a node\n * builtin eagerly (bundle-hygiene.test.ts). A turn this process did not see\n * arrives through `addMany` from the turns route, with its position.\n */\n\nimport { HISTORY_SEARCH } from '../behavior/contract.js';\n\nexport interface StoreLimits {\n max_conversations: number;\n max_turns_per_conversation: number;\n max_bytes_per_conversation: number;\n idle_ttl_seconds: number;\n max_file_bytes: number;\n}\n\nexport interface StoredTurn {\n /** Insertion order in this store. */\n seq: number;\n role: string;\n content: string;\n timestamp: string;\n message_id: string | null;\n /** 1-based turn number on the server, when known. */\n position: number | null;\n}\n\nexport interface TurnInput {\n role?: string;\n content?: string;\n timestamp?: string | Date | null;\n message_id?: string | null;\n position?: number | string | null;\n}\n\nconst SWEEP_EVERY_WRITES = 50;\n\ninterface Conversation {\n lastActivity: number;\n turns: StoredTurn[];\n}\n\nfunction bytesOf(text: string): number {\n return new TextEncoder().encode(text).length;\n}\n\nexport class TurnStore {\n readonly limits: StoreLimits;\n readonly onDisk = false;\n #now: () => number;\n #seq = 0;\n #writes = 0;\n #conversations = new Map<string, Conversation>();\n #vectors = new Map<string, Map<number, Float32Array>>();\n\n constructor(options: { limits?: StoreLimits; now?: () => number } = {}) {\n this.limits = options.limits ?? { ...HISTORY_SEARCH.store_limits };\n this.#now = options.now ?? (() => Date.now() / 1000);\n }\n\n add(\n conversationId: string,\n role: string,\n content: string,\n timestamp?: string | null,\n options: { messageId?: string | null; position?: number | null } = {},\n ): void {\n this.addMany(conversationId, [\n { role, content, timestamp: timestamp ?? '', message_id: options.messageId ?? null, position: options.position ?? null },\n ]);\n }\n\n /**\n * Insert turns not held yet; returns how many were new. A turn held without\n * an id or position (a streamed write) gets them when the same role and\n * text come back from the server.\n */\n addMany(conversationId: string, turns: Iterable<TurnInput>): number {\n if (!conversationId) return 0;\n const conv = this.#conversations.get(conversationId) ?? { lastActivity: 0, turns: [] };\n let added = 0;\n for (const turn of turns) {\n const role = String(turn.role || 'user');\n const content = String(turn.content ?? '');\n if (!content) continue;\n const messageId = turn.message_id ? String(turn.message_id) : null;\n const raw = turn.position;\n const position =\n typeof raw === 'number' && Number.isInteger(raw) ? raw : /^\\d+$/.test(String(raw ?? '')) ? Number(raw) : null;\n const ts = turn.timestamp instanceof Date ? turn.timestamp.toISOString() : String(turn.timestamp ?? '');\n if (messageId !== null) {\n const held = conv.turns.find((t) => t.message_id === messageId);\n if (held !== undefined) {\n if (position !== null) held.position = position;\n continue;\n }\n }\n const same = conv.turns.find(\n (t) => t.role === role && t.content === content && (t.message_id === null || t.position === null),\n );\n if (same !== undefined) {\n same.message_id = same.message_id ?? messageId;\n same.position = position ?? same.position;\n continue;\n }\n conv.turns.push({ seq: ++this.#seq, role, content, timestamp: ts, message_id: messageId, position });\n added += 1;\n }\n conv.lastActivity = this.#now();\n this.#conversations.set(conversationId, conv);\n this.#trim(conv);\n this.#writes += 1;\n if (this.#writes % SWEEP_EVERY_WRITES === 0) this.sweep();\n return added;\n }\n\n #trim(conv: Conversation): void {\n const limits = this.limits;\n let size = conv.turns.reduce((n, t) => n + bytesOf(t.content), 0);\n while (conv.turns.length > limits.max_turns_per_conversation || size > limits.max_bytes_per_conversation) {\n const excess = Math.max(conv.turns.length - limits.max_turns_per_conversation, 1);\n const order = [...conv.turns].sort(\n (a, b) => (a.position ?? Number.MAX_SAFE_INTEGER) - (b.position ?? Number.MAX_SAFE_INTEGER) || a.seq - b.seq,\n );\n const gone = new Set(order.slice(0, excess).map((t) => t.seq));\n if (gone.size === 0) break;\n for (const t of conv.turns) if (gone.has(t.seq)) size -= bytesOf(t.content);\n conv.turns = conv.turns.filter((t) => !gone.has(t.seq));\n for (const vectors of this.#vectors.values()) for (const seq of gone) vectors.delete(seq);\n }\n }\n\n /** Idle conversations, then the least recently used beyond the count, then more until the bytes fit. */\n sweep(): void {\n const limits = this.limits;\n const now = this.#now();\n for (const [id, conv] of this.#conversations) {\n if (conv.lastActivity < now - limits.idle_ttl_seconds) this.drop(id);\n }\n const byRecent = [...this.#conversations.entries()].sort((a, b) => b[1].lastActivity - a[1].lastActivity);\n for (const [id] of byRecent.slice(limits.max_conversations)) this.drop(id);\n while (this.sizeBytes() > limits.max_file_bytes) {\n const oldest = this.conversations()[0];\n if (oldest === undefined) break;\n this.drop(oldest);\n }\n }\n\n drop(conversationId: string): void {\n const conv = this.#conversations.get(conversationId);\n if (conv === undefined) return;\n for (const vectors of this.#vectors.values()) for (const t of conv.turns) vectors.delete(t.seq);\n this.#conversations.delete(conversationId);\n }\n\n clear(): void {\n this.#conversations.clear();\n this.#vectors.clear();\n }\n\n close(): void {\n // Nothing to release in memory; kept for parity with the Python store.\n }\n\n /** In conversation order: by server position where known, else as written here. */\n turns(conversationId: string): StoredTurn[] {\n const conv = this.#conversations.get(conversationId);\n if (conv === undefined) return [];\n const bySeq = [...conv.turns].sort((a, b) => a.seq - b.seq);\n const key = new Map<number, number>();\n let top = 0;\n let step = 0;\n for (const t of bySeq) {\n if (t.position !== null) {\n key.set(t.seq, t.position);\n top = Math.max(top, t.position);\n step = 0;\n } else {\n step += 1;\n key.set(t.seq, top + step * 1e-6);\n }\n }\n return bySeq\n .sort((a, b) => (key.get(a.seq) ?? 0) - (key.get(b.seq) ?? 0) || a.seq - b.seq)\n .map((t) => ({ ...t }));\n }\n\n /** Turns the server also holds: archived tool results are local only. Python: `count`. */\n count(conversationId: string): number {\n return (this.#conversations.get(conversationId)?.turns ?? []).filter((t) => t.role !== 'tool').length;\n }\n\n sizeBytes(): number {\n let n = 0;\n for (const conv of this.#conversations.values()) for (const t of conv.turns) n += bytesOf(t.content);\n return n;\n }\n\n /** Conversation ids, least recently active first. */\n conversations(): string[] {\n return [...this.#conversations.entries()].sort((a, b) => a[1].lastActivity - b[1].lastActivity).map(([id]) => id);\n }\n\n vectors(seqs: readonly number[], model: string): Map<number, Float32Array> {\n const held = this.#vectors.get(model);\n const out = new Map<number, Float32Array>();\n if (held === undefined) return out;\n for (const seq of seqs) {\n const v = held.get(seq);\n if (v !== undefined) out.set(seq, v);\n }\n return out;\n }\n\n putVectors(model: string, items: Map<number, Float32Array>): void {\n const held = this.#vectors.get(model) ?? new Map<number, Float32Array>();\n for (const [seq, vec] of items) held.set(seq, vec);\n this.#vectors.set(model, held);\n }\n}\n","/**\n * Local search over a conversation's earlier turns.\n *\n * Port of `maximem_synap/cache/history_search.py`; see it for the design.\n * Cascade, cheapest first: literal values in the query, then BM25 (the\n * anticipation cache's tokenizer and parameters), then an embedding model\n * when one is supplied. Ranks are fused by reciprocal rank with a small recency prior, and\n * excerpts are shown in conversation order. The rendered block reaches the\n * LLM prompt and is byte-identical to Python's.\n */\n\nimport { HISTORY_SEARCH } from '../behavior/contract.js';\nimport { BM25, tokenize as latinTokenize } from './bm25.js';\nimport type { StoredTurn, TurnStore } from './turn-store.js';\n\n/** A local embedding model. `model` names it, so vectors from another model are never compared. */\nexport interface Encoder {\n model: string;\n encode(texts: string[]): number[][] | Promise<number[][]>;\n /** Optional: a model trained with a query prefix (e5) encodes queries here and turns with `encode`. */\n encodeQuery?(texts: string[]): number[][] | Promise<number[][]>;\n}\n\nexport interface Excerpt {\n position: number | null;\n role: string;\n text: string;\n score: number;\n timestamp: string;\n /** \"literal\", \"bm25\" or \"embedding\": the strongest signal that found it. */\n via: string;\n}\n\n// Any script's letters and digits; Latin words still go through the\n// anticipation tokenizer for its stop words and stemming. Python: `tokenize`.\nconst WORD_RE = /[\\p{L}\\p{N}\\p{M}]+/gu;\n\nconst FORMS: Readonly<Record<string, string>> = HISTORY_SEARCH.irregular_forms ?? {};\n\nfunction tokenize(text: string): string[] {\n const out: string[] = [];\n for (const word of (text || '').toLowerCase().match(WORD_RE) ?? []) {\n // \"sold\" and \"sell\" are one word to a search; the stemmer only strips regular endings.\n if (/^[\\x00-\\x7f]+$/.test(word)) out.push(...latinTokenize(FORMS[word] ?? word));\n else out.push(word);\n }\n return out;\n}\n\nconst LITERAL_SOURCE = String.raw`\"([^\"]{3,})\"|\\b([A-Z0-9][A-Z0-9-]{3,})\\b|(\\d[\\d,.:/-]*\\d|\\d)`;\nconst SENTENCE_RE = /(?<=[.!?])\\s+/;\n\nfunction literalsOf(query: string): string[] {\n const out: string[] = [];\n for (const m of (query || '').matchAll(new RegExp(LITERAL_SOURCE, 'g'))) {\n const quoted = m[1];\n const value = quoted || m[2] || m[3];\n if (value && (quoted || /\\d/.test(value))) out.push(value.toLowerCase());\n }\n return out;\n}\n\nfunction cosine(a: ArrayLike<number>, b: ArrayLike<number>): number {\n let dot = 0;\n let na = 0;\n let nb = 0;\n const n = Math.min(a.length, b.length);\n for (let i = 0; i < n; i++) {\n dot += a[i]! * b[i]!;\n na += a[i]! * a[i]!;\n nb += b[i]! * b[i]!;\n }\n return na && nb ? dot / (Math.sqrt(na) * Math.sqrt(nb)) : 0;\n}\n\nfunction words(text: string): string[] {\n return text.split(/\\s+/).filter(Boolean);\n}\n\nfunction excerptOf(content: string, terms: Set<string>, literals: string[], maxWords: number): string {\n let sentences = content.trim().split(SENTENCE_RE).filter((s) => s.trim());\n if (sentences.length === 0) sentences = [content.trim()];\n const score = (sentence: string): number => {\n const low = sentence.toLowerCase();\n const held = new Set(tokenize(sentence));\n let n = 0;\n for (const t of terms) if (held.has(t)) n += 1;\n for (const lit of literals) if (low.includes(lit)) n += 2;\n return n;\n };\n let best = 0;\n for (let i = 1; i < sentences.length; i++) if (score(sentences[i]!) > score(sentences[best]!)) best = i;\n let lo = best;\n let hi = best;\n let count = words(sentences[best]!).length;\n for (;;) {\n let grew = false;\n for (const j of [hi + 1, lo - 1]) {\n if (j >= 0 && j < sentences.length && count + words(sentences[j]!).length <= maxWords) {\n count += words(sentences[j]!).length;\n lo = Math.min(lo, j);\n hi = Math.max(hi, j);\n grew = true;\n }\n }\n if (!grew) break;\n }\n let text = sentences.slice(lo, hi + 1).join(' ');\n if (words(text).length > maxWords) text = words(text).slice(0, maxWords).join(' ') + ' ...';\n return (lo > 0 ? '... ' : '') + text + (hi < sentences.length - 1 && !text.endsWith('...') ? ' ...' : '');\n}\n\n/**\n * The best-matching earlier turns for `query`. `exclude`: message ids or\n * exact texts already in the prompt (the recent turns).\n */\nconst FENCE = /^\\s*(?:```|~~~)/;\nconst TABLE_RULE = /^\\s*\\|?\\s*:?-{2,}/;\nconst SENTENCE = /(?<=[.!?])\\s+/;\n\n/**\n * A long turn as passages of up to about `maxWords` words: table rows carry the\n * table's header row, fenced blocks and other line-shaped text go a few lines\n * at a time, prose a few sentences at a time. Python: `split_passages`.\n */\nexport function splitPassages(content: string, maxWords: number): string[] {\n const text = (content ?? '').trim();\n if (words(text).length <= maxWords) return text ? [text] : [];\n const out: string[] = [];\n const lines = text.split('\\n');\n let i = 0;\n while (i < lines.length) {\n const line = lines[i]!;\n if (FENCE.test(line)) {\n let j = i + 1;\n while (j < lines.length && !FENCE.test(lines[j]!)) j += 1;\n out.push(...windowsOf(lines.slice(i + 1, j), maxWords));\n i = j + 1;\n continue;\n }\n if (line.trim().startsWith('|')) {\n let j = i;\n while (j < lines.length && lines[j]!.trim().startsWith('|')) j += 1;\n const rows = lines.slice(i, j).filter((r) => !TABLE_RULE.test(r)).map((r) => r.trim());\n const [header, body] = rows.length > 1 ? [rows[0]!, rows.slice(1)] : ['', rows];\n for (const row of body) {\n const both = `${header} ${row}`.trim();\n out.push(words(both).length <= Math.trunc((maxWords * 3) / 2) ? both : row);\n }\n i = j;\n continue;\n }\n let j = i;\n while (j < lines.length && lines[j]!.trim() && !FENCE.test(lines[j]!) && !lines[j]!.trim().startsWith('|')) j += 1;\n if (j === i) {\n i += 1;\n continue;\n }\n const block = lines.slice(i, j);\n if (block.length > 1 && block.every((b) => words(b).length <= 25)) {\n out.push(...windowsOf(block, maxWords));\n } else {\n const sentences = block.map((b) => b.trim()).join(' ').split(SENTENCE).filter((x) => x.trim());\n out.push(...windowsOf(sentences, maxWords));\n }\n i = j;\n }\n const kept = out.filter((x) => x.trim());\n return kept.length ? kept : [text];\n}\n\nfunction windowsOf(pieces: readonly string[], maxWords: number): string[] {\n const out: string[] = [];\n let cur: string[] = [];\n let used = 0;\n for (const raw of pieces) {\n const piece = raw.trim();\n if (!piece) continue;\n const n = words(piece).length;\n if (cur.length && used + n > maxWords) {\n out.push(cur.join(' '));\n cur = [];\n used = 0;\n }\n if (n > maxWords) {\n const w = words(piece);\n for (let k = 0; k < w.length; k += maxWords) out.push(w.slice(k, k + maxWords).join(' '));\n continue;\n }\n cur.push(piece);\n used += n;\n }\n if (cur.length) out.push(cur.join(' '));\n return out;\n}\n\n/** What search scores: a whole turn, or one passage of a long turn. */\ninterface Unit {\n seq: number;\n content: string;\n turn: number;\n first: boolean;\n last: boolean;\n /** The passage's index, -1 for a whole turn (its vector is the turn's). */\n part: number;\n}\n\n/** The value patterns of the kinds of value `query` asks for. Python: `_asked_kinds`. */\nfunction askedKinds(query: string): RegExp[] {\n const out: RegExp[] = [];\n for (const [name, spec] of Object.entries(HISTORY_SEARCH.asked_kinds ?? {})) {\n if (name.startsWith('$') || typeof spec !== 'object') continue;\n if (new RegExp(spec.query, 'i').test(query ?? '')) out.push(new RegExp(spec.value));\n }\n return out;\n}\n\n/** A question about how things started gets no recency prior. Python: `_asks_how_it_started`. */\nfunction asksHowItStarted(query: string): boolean {\n const spec = HISTORY_SEARCH.early_query;\n if (!spec?.pattern) return false;\n return new RegExp(spec.pattern, (spec.flags ?? '').includes('i') ? 'i' : '').test(query ?? '');\n}\n\nexport async function searchTurns(\n turns: readonly StoredTurn[],\n query: string,\n options: { exclude?: Iterable<string>; encoder?: Encoder | null; store?: TurnStore | null } = {},\n): Promise<Excerpt[]> {\n const params = HISTORY_SEARCH;\n const k = params.max_excerpts;\n const skip = new Set(options.exclude ?? []);\n const pool = turns.filter((t) => t.content && !skip.has(t.content) && !skip.has(t.message_id ?? ''));\n const terms = new Set(tokenize(query || ''));\n const literals = literalsOf(query);\n if (pool.length === 0 || (terms.size === 0 && literals.length === 0 && !options.encoder)) return [];\n\n const maxWords = params.max_words_per_excerpt;\n const units: Unit[] = [];\n pool.forEach((t, ti) => {\n if (!params.passages) {\n units.push({ seq: t.seq, content: t.content, turn: ti, first: true, last: true, part: -1 });\n return;\n }\n const parts = splitPassages(t.content, maxWords);\n parts.forEach((part, pi) => {\n // A one-passage turn keeps the turn's vector; passages of a longer one are stored per passage.\n units.push({\n seq: t.seq, content: part, turn: ti, first: pi === 0, last: pi === parts.length - 1,\n part: parts.length > 1 ? pi : -1,\n });\n });\n });\n\n const docs = units.map((u) => tokenize(u.content));\n const bm = new BM25(docs);\n const termList = [...terms];\n const rows = units.map((turn, i) => {\n const held = new Set(docs[i]);\n let matched = 0;\n for (const t of terms) if (held.has(t)) matched += 1;\n const low = turn.content.toLowerCase();\n let literal = 0;\n for (const lit of literals) if (low.includes(lit)) literal += 1;\n return { i, bm25: matched ? bm.score(termList, i) : 0, matched, literal };\n });\n const need = Math.min(params.min_matched_terms, Math.max(1, terms.size));\n // One query word is enough when few turns use it, not when many do.\n const rareCap = Math.max(1, Math.trunc((params.rare_term_max_share ?? 0) * units.length));\n const rare = new Set<string>();\n for (const t of terms) {\n let n = 0;\n for (const doc of docs) if (doc.includes(t)) n += 1;\n if (n > 0 && n <= rareCap) rare.add(t);\n }\n let eligible;\n if (params.passages) {\n // A passage of a turn that matches enough query words as a whole.\n const turnTerms = new Map<number, Set<string>>();\n for (const r of rows) {\n const held = turnTerms.get(units[r.i]!.turn) ?? new Set<string>();\n for (const t of docs[r.i]!) if (terms.has(t)) held.add(t);\n turnTerms.set(units[r.i]!.turn, held);\n }\n eligible = rows.filter(\n (r) =>\n r.literal > 0 ||\n (r.matched > 0 &&\n (turnTerms.get(units[r.i]!.turn)!.size >= need || docs[r.i]!.some((t) => rare.has(t)))),\n );\n } else {\n eligible = rows.filter(\n (r) => r.literal > 0 || r.matched >= need || (r.matched > 0 && docs[r.i]!.some((t) => rare.has(t))),\n );\n }\n\n const rrf = params.rrf_k;\n const fused = new Map<number, number>();\n const via = new Map<number, string>();\n for (const r of eligible) fused.set(r.i, 0);\n const add = (i: number, rank: number, how: string): void => {\n fused.set(i, (fused.get(i) ?? 0) + 1 / (rrf + rank + 1));\n if (!via.has(i)) via.set(i, how);\n };\n eligible\n .filter((r) => r.literal > 0)\n .sort((a, b) => b.literal - a.literal || a.i - b.i)\n .forEach((r, rank) => add(r.i, rank, 'literal'));\n eligible\n .filter((r) => r.bm25 > 0)\n .sort((a, b) => b.bm25 - a.bm25 || a.i - b.i)\n .forEach((r, rank) => add(r.i, rank, 'bm25'));\n\n // A question asking for a kind of value also ranks the passages holding one.\n const kinds = askedKinds(query);\n if (kinds.length) {\n rows\n .filter((r) => r.matched > 0 && kinds.some((k) => k.test(units[r.i]!.content)))\n .sort((a, b) => b.bm25 - a.bm25 || a.i - b.i)\n .forEach((r, rank) => add(r.i, rank, 'kind'));\n }\n\n // Fused on every query when a model is supplied (Python: measured 19 Oct).\n if (options.encoder) {\n const ranked = await embeddingRanks(units, query, options.encoder, options.store ?? null, params.min_cosine ?? 0.4);\n ranked.forEach(([i], rank) => add(i, rank, 'embedding'));\n }\n if (fused.size === 0) return [];\n\n const n = Math.max(pool.length - 1, 1);\n const weight = asksHowItStarted(query) ? 0 : params.recency_weight;\n // A turn ranks by its best unit; its best units are what is shown of it.\n const top = new Map<number, [number, number]>();\n const ranked = new Map<number, [number, number][]>();\n for (const [u, v] of fused) {\n const ti = units[u]!.turn;\n const score = v + (weight * (ti / n)) / (rrf + 1);\n ranked.set(ti, [...(ranked.get(ti) ?? []), [score, u]]);\n const held = top.get(ti);\n if (!held || score > held[0]) top.set(ti, [score, u]);\n }\n const best = [...top.keys()].sort((a, b) => top.get(b)![0] - top.get(a)![0] || a - b).slice(0, k);\n const perTurn = params.passages_per_turn ?? 1;\n const shown = (ti: number): string => {\n const unit = units[top.get(ti)![1]]!;\n if (!params.passages || (unit.first && unit.last)) return excerptOf(pool[ti]!.content, terms, literals, maxWords);\n const picked = [...ranked.get(ti)!]\n .sort((a, b) => b[0] - a[0] || b[1] - a[1])\n .slice(0, perTurn)\n .map(([, u]) => u)\n .sort((a, b) => a - b);\n const parts: string[] = [];\n for (const u of picked) parts.push((units[u]!.first || parts.length ? '' : '... ') + units[u]!.content);\n return parts.join(' ... ') + (units[picked[picked.length - 1]!]!.last ? '' : ' ...');\n };\n const found = new Map<number, Excerpt>();\n for (const ti of best) {\n found.set(ti, {\n position: pool[ti]!.position,\n role: pool[ti]!.role,\n timestamp: pool[ti]!.timestamp,\n score: top.get(ti)![0],\n via: via.get(top.get(ti)![1]) ?? '',\n text: shown(ti),\n });\n }\n // The turn before a hit is often what it answers or confirms; it comes along, cut to its end.\n const before = params.previous_turns ?? 0;\n const tail = params.previous_turn_words ?? 40;\n for (const i of best) {\n for (let j = i - before; j < i; j++) {\n if (j < 0 || found.has(j)) continue;\n const hit = pool[i]!.position;\n const prev = pool[j]!.position;\n if (hit && prev && hit - prev > before) continue; // the turn just before is in the prompt\n const w = words(pool[j]!.content);\n found.set(j, {\n position: prev,\n role: pool[j]!.role,\n timestamp: pool[j]!.timestamp,\n score: 0,\n via: 'previous',\n text: w.length <= tail ? w.join(' ') : '... ' + w.slice(-tail).join(' '),\n });\n }\n }\n return [...found.keys()].sort((a, b) => a - b).map((i) => found.get(i)!);\n}\n\nasync function embeddingRanks(\n pool: readonly { seq: number; content: string; part?: number }[],\n query: string,\n encoder: Encoder,\n store: TurnStore | null,\n minCosine: number,\n): Promise<[number, number][]> {\n // Stored under the turn's seq and the model's name (a passage's: name + \"#p<index>\"). Python: `_embedding_ranks`.\n const keyOf = (u: { part?: number }): string => ((u.part ?? -1) < 0 ? encoder.model : `${encoder.model}#p${u.part}`);\n const vectors = new Map<number, ArrayLike<number>>();\n if (store !== null) {\n const byKey = new Map<string, number[]>();\n pool.forEach((u, i) => byKey.set(keyOf(u), [...(byKey.get(keyOf(u)) ?? []), i]));\n for (const [key, idx] of byKey) {\n const held = store.vectors(idx.map((i) => pool[i]!.seq), key);\n for (const i of idx) {\n const v = held.get(pool[i]!.seq);\n if (v) vectors.set(i, v);\n }\n }\n }\n const missing = pool.map((_, i) => i).filter((i) => !vectors.has(i));\n if (missing.length > 0) {\n const fresh = await encoder.encode(missing.map((i) => pool[i]!.content));\n const put = new Map<string, Map<number, Float32Array>>();\n missing.forEach((i, j) => {\n const v = Float32Array.from(fresh[j] ?? []);\n vectors.set(i, v);\n const key = keyOf(pool[i]!);\n put.set(key, (put.get(key) ?? new Map()).set(pool[i]!.seq, v));\n });\n if (store) for (const [key, items] of put) store.putVectors(key, items);\n }\n const q = (await (encoder.encodeQuery ?? encoder.encode).call(encoder, [query]))[0] ?? [];\n return pool\n .map((_, i): [number, number] => [i, cosine(q, vectors.get(i) ?? [])])\n .filter(([, c]) => c >= minCosine)\n .sort((a, b) => b[1] - a[1]);\n}\n\n/**\n * How an archived tool result reads in the turn store and in excerpts: compact\n * JSON, cut to the contract's size. Python: `tool_result_text`.\n */\nexport function toolResultText(result: unknown, toolName?: string | null): string {\n let text = typeof result === 'string' ? result : JSON.stringify(result) ?? String(result);\n const limit = HISTORY_SEARCH.tool_result_max_chars ?? 16_000;\n if (text.length > limit) text = text.slice(0, limit) + ' ...[cut]';\n return `[tool result: ${toolName || 'tool'}] ${text}`;\n}\n\n/** The block appended after the compaction and the recent turns. */\nexport function renderExcerpts(excerpts: readonly Excerpt[], latest = ''): string {\n if (excerpts.length === 0) return '';\n const lines = [HISTORY_SEARCH.heading];\n for (const e of excerpts) {\n let where = e.position ? `turn ${e.position}, ${e.role}` : `${e.role}, earlier`;\n if (e.timestamp) {\n const ago = before(e.timestamp, latest);\n where += `, ${e.timestamp}` + (ago ? ` (${ago})` : '');\n }\n lines.push(`- ${where}: \"${e.text}\"`);\n }\n return lines.join('\\n');\n}\n\nconst ZONED = /(?:Z|[+-]\\d{2}:\\d{2})$/;\n\n/** Seconds since the epoch, for an ISO-8601 timestamp with a zone only. Python: `_instant`. */\nfunction instant(stamp: string): number | null {\n const text = (stamp ?? '').trim();\n if (!ZONED.test(text)) return null;\n const ms = Date.parse(text);\n return Number.isNaN(ms) ? null : ms / 1000;\n}\n\n/** \"3 days before the latest message\", or \"\" when either is unreadable. Python: `_before`. */\nfunction before(stamp: string, latest: string): string {\n const at = instant(stamp);\n const now = instant(latest);\n if (at === null || now === null || now < at) return '';\n const seconds = Math.trunc(now - at);\n for (const [unit, size] of [['day', 86_400], ['hour', 3_600], ['minute', 60]] as const) {\n if (seconds >= size) {\n const n = Math.trunc(seconds / size);\n return `${n} ${unit}${n !== 1 ? 's' : ''} before the latest message`;\n }\n }\n return 'less than a minute before the latest message';\n}\n","/**\n * Read-your-writes overlay for fetch responses.\n *\n * Ports Python's `_overlay_local_recent_turns` and `_budget_recent_turns`.\n *\n * The server's `recent_turns` reflects what it has persisted and compacted. A\n * turn recorded moments ago may not be in there yet, so a fast follow-up would\n * fetch context missing the thing the user just said. The overlay replaces\n * `recent_turns` with the locally buffered tail while leaving every summary\n * field to the server.\n *\n * On by default, matching Python. `SYNAP_ST_VERBATIM_OVERLAY` is the\n * kill-switch.\n */\n\nimport type { Json, RawContext } from './types.js';\nimport { isComplete, turnsAfter } from '../cache/short-term-store.js';\nimport type { ShortTermStore, ShortTermTurn } from '../cache/short-term-store.js';\nimport { getEnv } from '../util/env.js';\n\n/**\n * The server trims `recent_turns` to this window before returning it. The\n * overlay re-applies the same budget so a long pre-compaction local tail\n * cannot silently re-inflate the prompt past what the server would have\n * allowed.\n */\nconst MAX_TURNS = 20;\nconst TOKEN_BUDGET = 2000;\n\n/**\n * Whether to splice the local tail in.\n *\n * Default ON: this is the correctness switch (a just-written turn must surface\n * on the next fetch), separate from the cost-side `st_authoritative` flag that\n * tells the server to skip assembling short-term context at all.\n */\nexport function verbatimOverlayEnabled(configured?: boolean): boolean {\n // Resolution order matches Python's `_is_st_verbatim_overlay`: the env var\n // is an explicit override / kill-switch and wins over the config field.\n const raw = (getEnv('SYNAP_ST_VERBATIM_OVERLAY') ?? '').trim().toLowerCase();\n if (['0', 'false', 'no', 'off'].includes(raw)) return false;\n if (['1', 'true', 'yes', 'on'].includes(raw)) return true;\n return configured ?? true;\n}\n\n/** ~4 characters per token, matching the server-side heuristic. */\nfunction estimateTokens(turn: ShortTermTurn): number {\n return Math.max(1, Math.floor(String(turn.content ?? '').length / 4));\n}\n\n/**\n * Cap the tail to the server's window, then drop OLDEST turns until it fits\n * the token budget. Oldest-first because the newest turn is the one the caller\n * is most likely to be following up on.\n */\nexport function budgetRecentTurns(turns: readonly ShortTermTurn[]): ShortTermTurn[] {\n const windowed = turns.slice(-MAX_TURNS);\n let total = windowed.reduce((n, t) => n + estimateTokens(t), 0);\n while (windowed.length > 0 && total > TOKEN_BUDGET) {\n const dropped = windowed.shift() as ShortTermTurn;\n total -= estimateTokens(dropped);\n }\n return windowed;\n}\n\n/**\n * Splice the local tail into a fetch response, in place.\n *\n * Deliberately never throws: this runs inside the fetch path, and a bookkeeping\n * problem here must not fail a retrieval that otherwise succeeded.\n */\nexport function overlayLocalRecentTurns(\n response: RawContext,\n store: ShortTermStore,\n /** `null` too: callers spell \"no conversation\" as `convId || null`. */\n conversationId: string | null | undefined,\n /** `st_verbatim_overlay` from the client options. The env var still wins. */\n configured?: boolean,\n): void {\n if (conversationId === undefined || conversationId === null || conversationId === '') return;\n try {\n const entry = store.get(conversationId);\n // Cold store: nothing locally, so leave the server's response untouched.\n if (entry === null) return;\n\n const existing = (response.conversation_context ?? null) as Json | null;\n\n // The server returned a conversation_context AND the overlay is switched\n // off: leave it exactly as sent. When the server OMITTED one we still\n // splice from local, so the skip-server-ST optimisation keeps working\n // regardless of this switch.\n if (existing !== null && !verbatimOverlayEnabled(configured)) return;\n\n // Which turns the tail is built from. The local list replaces the\n // server's only when it is known to be the whole conversation and to\n // follow the same summary the server sent. Otherwise the server's turns\n // stand, and the local list adds only what comes after them. A process\n // that has just restarted holds one turn, and replacing the server's list\n // with it dropped every turn before the restart.\n const serverCompaction = existing === null ? null : existing['compaction_id'];\n const localIsWhole =\n isComplete(entry) && (!serverCompaction || serverCompaction === entry.compactionId);\n let sourceTurns: ShortTermTurn[] = entry.recentTurns;\n if (existing !== null && !localIsWhole) {\n const raw = Array.isArray(existing['recent_turns']) ? existing['recent_turns'] : [];\n const serverTurns: ShortTermTurn[] = (raw as Array<Record<string, unknown>>).map((t) => ({\n role: String(t['role'] ?? 'user'),\n content: String(t['content'] ?? ''),\n timestamp: String(t['timestamp'] ?? ''),\n }));\n sourceTurns = [...serverTurns, ...turnsAfter(entry.recentTurns, serverTurns)];\n }\n // Role, text and time only, as Python sends: the server's id for a turn is\n // bookkeeping for the store, not part of the response.\n const localTurns = budgetRecentTurns(sourceTurns).map((t) => ({\n role: t.role,\n content: t.content,\n timestamp: t.timestamp,\n }));\n\n // `x || fallback`, not `??`, matching Python: the server sends '' and {}\n // for absent fields rather than null, and those must not win over a local\n // value that actually has content.\n const serverField = (name: string): unknown =>\n existing === null ? undefined : existing[name];\n const orLocal = <T>(name: string, local: T): unknown => {\n const value = serverField(name);\n if (value === undefined || value === null || value === '') return local;\n if (typeof value === 'object' && Object.keys(value as object).length === 0) return local;\n return value;\n };\n\n // Server wins on every summary field; local only ever supplies the tail.\n response.conversation_context = {\n summary: orLocal('summary', entry.summary),\n current_state: orLocal('current_state', { ...entry.currentState }),\n key_extractions: orLocal('key_extractions', { ...entry.keyExtractions }),\n recent_turns: localTurns,\n compaction_id: orLocal('compaction_id', entry.compactionId),\n compacted_at: orLocal('compacted_at', entry.compactedAt),\n conversation_id: conversationId,\n } as NonNullable<RawContext['conversation_context']>;\n } catch {\n // Non-fatal by design. See the note above.\n }\n}\n","/**\n * Render `get_context_for_prompt` locally from the short-term store.\n *\n * A direct port of Python's `formatter/context_for_prompt.py`. It exists for\n * the same reason: when the SDK is authoritative for short-term context, a\n * warm conversation can answer this call without a cloud round trip at all,\n * which is a latency saving and a metered-call saving both.\n *\n * The three styles and their exact heading text are copied from Python\n * deliberately. A prompt assembled by one SDK and one assembled by the other\n * must be the same string, or an application that switches languages silently\n * changes what its model sees.\n */\n\nimport { CONTEXT_BLOCK_PREFIX } from '../cache/short-term-store.js';\nimport type { ShortTermEntry, ShortTermTurn } from '../cache/short-term-store.js';\nimport type { Json } from './types.js';\n\nexport const SUPPORTED_STYLES = ['structured', 'narrative', 'bullet_points'] as const;\nexport type PromptStyle = (typeof SUPPORTED_STYLES)[number];\nexport const DEFAULT_STYLE: PromptStyle = 'structured';\n\nexport interface LocalRecentMessage {\n role: string;\n content: string;\n /** ISO-8601. */\n timestamp: string;\n message_id: string;\n}\n\nexport interface LocalPromptResponse {\n formatted_context: string | null;\n available: boolean;\n is_stale: boolean;\n compression_ratio: number | null;\n validation_score: number | null;\n compaction_age_seconds: number | null;\n quality_warning: boolean;\n recent_messages: LocalRecentMessage[];\n recent_message_count: number;\n compacted_message_count: number;\n total_message_count: number;\n /**\n * The framed compaction block alone (also inside formatted_context), for a\n * framework that keeps its own message list: a system message ahead of\n * recent_messages, in place of the turns it covers.\n */\n context_block: string | null;\n compaction_id: string | null;\n [key: string]: unknown;\n}\n\nfunction stringify(value: unknown): string {\n if (value === null || value === undefined) return '';\n const t = typeof value;\n if (t === 'string' || t === 'number' || t === 'boolean') return String(value);\n try {\n return JSON.stringify(value) ?? '';\n } catch {\n return String(value);\n }\n}\n\n/** Key extractions arrive as a list, a bare string, or a single object. */\nfunction asListOfObjects(value: unknown): Record<string, unknown>[] {\n if (!value) return [];\n if (Array.isArray(value)) {\n const out: Record<string, unknown>[] = [];\n for (const v of value) {\n if (v && typeof v === 'object' && !Array.isArray(v)) out.push(v as Record<string, unknown>);\n else if (typeof v === 'string') out.push({ content: v });\n }\n return out;\n }\n if (typeof value === 'object') return [value as Record<string, unknown>];\n return [];\n}\n\nfunction itemText(item: Record<string, unknown>): string {\n return (item['content'] as string) || (item['text'] as string) || stringify(item);\n}\n\nfunction buildRecentMessages(turns: readonly ShortTermTurn[]): LocalRecentMessage[] {\n return (turns ?? []).map((t, idx) => ({\n role: t.role || 'user',\n content: t.content ?? '',\n timestamp: t.timestamp,\n message_id: t.message_id || `local-${idx}`,\n }));\n}\n\n/**\n * The SDK does not know how many messages a compaction covered: the server\n * does not put that count in the bundle. Python reports 0 here for the same\n * reason, and both must agree.\n */\nfunction compactedMessageCount(_entry: ShortTermEntry): number {\n return 0;\n}\n\n/** The v3 block, which is printed as received, once, under its own header. */\nfunction blockOf(entry: ShortTermEntry): string | null {\n if (entry.contextBlock) return entry.contextBlock.trim();\n if (entry.summary && entry.summary.startsWith(CONTEXT_BLOCK_PREFIX)) return entry.summary.trim();\n return null;\n}\n\nfunction formatStructured(entry: ShortTermEntry, recent: LocalRecentMessage[]): string {\n const parts: string[] = [];\n const block = blockOf(entry);\n if (block) {\n parts.push(block);\n if (recent.length > 0) {\n parts.push(`## Recent Turns (${recent.length})`);\n for (const m of recent) parts.push(`**${m.role}**: ${m.content}`);\n }\n return parts.filter(Boolean).join('\\n\\n').trim();\n }\n if (entry.summary) { parts.push('## Summary'); parts.push(entry.summary.trim()); }\n if (entry.factualParagraph) { parts.push('## Facts'); parts.push(entry.factualParagraph.trim()); }\n if (entry.conversationalParagraph) {\n parts.push('## Conversation'); parts.push(entry.conversationalParagraph.trim());\n }\n\n const cs = entry.currentState ?? {};\n if (Object.keys(cs).length > 0) {\n parts.push('## Current State');\n for (const [k, v] of Object.entries(cs)) parts.push(`- ${k}: ${stringify(v)}`);\n }\n\n const ke = entry.keyExtractions ?? {};\n if (Object.keys(ke).length > 0) {\n parts.push('## Key Extractions');\n for (const [cat, items] of Object.entries(ke)) {\n if (!items) continue;\n parts.push(`### ${cat}`);\n for (const it of asListOfObjects(items)) parts.push(`- ${itemText(it)}`);\n }\n }\n\n if (recent.length > 0) {\n parts.push(`## Recent Turns (${recent.length})`);\n for (const m of recent) parts.push(`**${m.role}**: ${m.content}`);\n }\n\n return parts.filter(Boolean).join('\\n\\n').trim();\n}\n\nfunction formatNarrative(entry: ShortTermEntry, recent: LocalRecentMessage[]): string {\n const parts: string[] = [];\n const block = blockOf(entry);\n if (block) parts.push(block);\n else if (entry.summary) parts.push(entry.summary.trim());\n if (!block && entry.conversationalParagraph) parts.push(entry.conversationalParagraph.trim());\n else if (!block && entry.factualParagraph) parts.push(entry.factualParagraph.trim());\n\n if (recent.length > 0) {\n const tail = recent.map((m) => `${m.role}: ${m.content}`).join('\\n');\n parts.push(`Recent exchanges:\\n${tail}`);\n }\n return parts.filter(Boolean).join('\\n\\n').trim();\n}\n\nfunction formatBullets(entry: ShortTermEntry, recent: LocalRecentMessage[]): string {\n const parts: string[] = [];\n const block = blockOf(entry);\n if (block) {\n // The block is structured text already; bulleting it would mangle it.\n return [block, ...recent.map((m) => `- ${m.role}: ${m.content}`)].join('\\n').trim();\n }\n if (entry.summary) parts.push(`- Summary: ${entry.summary.trim()}`);\n\n for (const [k, v] of Object.entries(entry.currentState ?? {})) {\n parts.push(`- ${k}: ${stringify(v)}`);\n }\n for (const [cat, items] of Object.entries(entry.keyExtractions ?? {})) {\n for (const it of asListOfObjects(items)) parts.push(`- (${cat}) ${itemText(it)}`);\n }\n for (const m of recent) parts.push(`- ${m.role}: ${m.content}`);\n\n return parts.join('\\n').trim();\n}\n\nfunction formatBlock(entry: ShortTermEntry, recent: LocalRecentMessage[], style: string): string {\n if (style === 'narrative') return formatNarrative(entry, recent);\n if (style === 'bullet_points') return formatBullets(entry, recent);\n return formatStructured(entry, recent);\n}\n\n/** Build a context-for-prompt response from a cached entry. */\nexport function renderForPrompt(\n entry: ShortTermEntry,\n style: string = DEFAULT_STYLE,\n now: () => number = Date.now,\n): LocalPromptResponse {\n const chosen: string = (SUPPORTED_STYLES as readonly string[]).includes(style)\n ? style\n : DEFAULT_STYLE;\n\n const recent = buildRecentMessages(entry.recentTurns);\n const formatted = formatBlock(entry, recent, chosen);\n const available = entry.compactionId !== null || entry.recentTurns.length > 0;\n\n let compactionAge: number | null = null;\n if (entry.compactedAt !== null) {\n const parsed = Date.parse(entry.compactedAt);\n if (!Number.isNaN(parsed)) compactionAge = Math.floor((now() - parsed) / 1000);\n }\n\n const compacted = compactedMessageCount(entry);\n return {\n formatted_context: available ? formatted : null,\n available,\n is_stale: false,\n compression_ratio: null,\n validation_score: null,\n compaction_age_seconds: compactionAge,\n quality_warning: false,\n recent_messages: recent,\n recent_message_count: recent.length,\n compacted_message_count: compacted,\n total_message_count: recent.length + compacted,\n context_block: blockOf(entry),\n compaction_id: entry.compactionId,\n };\n}\n\n/** Build a compaction response from a cached entry, or null if none landed. */\nexport function renderCompacted(\n entry: ShortTermEntry,\n format = 'structured',\n correlationId = '',\n): Json | null {\n if (entry.compactionId === null) return null;\n\n const formatted = formatBlock(\n entry,\n buildRecentMessages(entry.recentTurns),\n format === 'narrative' ? 'narrative' : 'structured',\n );\n\n return {\n compacted_context: formatted,\n compaction_id: entry.compactionId,\n compacted_at: entry.compactedAt,\n conversation_id: entry.conversationId,\n current_state: entry.currentState,\n correlation_id: correlationId,\n original_token_count: null,\n compacted_token_count: null,\n compression_ratio: null,\n level_applied: null,\n validation_score: null,\n validation_passed: null,\n quality_warning: false,\n };\n}\n","/**\n * Periodic user-summary injection.\n *\n * Ports Python's `_should_inject_user_summary` / `_merge_user_summary_into_response`.\n *\n * Every Nth turn, a cached `user_summary` bundle is folded into the fetch\n * response. It is what keeps a long conversation grounded in who the user is\n * without paying for a broader retrieval on every turn. Without it, JS returns\n * less context than Python from identical usage, and the gap widens the longer\n * the conversation runs.\n */\n\nimport type { Json, RawContext, RawContextItem } from './types.js';\n\n/** Python's `_user_summary_interval`. */\nexport const USER_SUMMARY_INTERVAL = 5;\n/** Python's `max_summary_items`. */\nconst MAX_SUMMARY_ITEMS = 3;\n\nconst COLLECTIONS = ['facts', 'preferences', 'episodes', 'emotions', 'temporal_events'] as const;\n\n/** Per-conversation turn counters, so the cadence is per conversation. */\nexport class TurnCounter {\n readonly #counts = new Map<string, number>();\n\n /** Increment and return the new count. Python buckets a missing id under `_global`. */\n increment(conversationId: string | undefined): number {\n const key = conversationId !== undefined && conversationId !== '' ? conversationId : '_global';\n const next = (this.#counts.get(key) ?? 0) + 1;\n this.#counts.set(key, next);\n return next;\n }\n\n /**\n * True on every Nth turn, and never on the first.\n *\n * Python: `count > 0 and count % interval == 0`. Turn 5 injects, turn 1 does\n * not, which matters because the first turn is usually the one that just\n * triggered a fresh retrieval anyway.\n */\n shouldInject(conversationId: string | undefined): boolean {\n const key = conversationId !== undefined && conversationId !== '' ? conversationId : '_global';\n const count = this.#counts.get(key) ?? 0;\n return count > 0 && count % USER_SUMMARY_INTERVAL === 0;\n }\n\n clear(): void {\n this.#counts.clear();\n }\n}\n\nfunction itemId(item: Json): string {\n return String(item['item_id'] ?? item['id'] ?? '');\n}\n\nfunction pick(item: Json, ...names: string[]): unknown {\n for (const name of names) {\n const value = item[name];\n if (value !== undefined && value !== null) return value;\n }\n return undefined;\n}\n\n/**\n * Normalise a summary-bundle item to the response item shape.\n *\n * The bundle carries the proto's field names, which differ from the REST\n * response's. Python spells the whole mapping out rather than passing items\n * through, because a consumer reading `.content` on an episode would otherwise\n * get undefined.\n */\nfunction normalise(item: Json): RawContextItem {\n const content = pick(item, 'content') ?? '';\n const confidence = pick(item, 'confidence') ?? 0;\n const extractedAt = pick(item, 'extracted_at', 'created_at') ?? null;\n return {\n id: itemId(item),\n content: String(content),\n confidence: Number(confidence),\n source: String(pick(item, 'source') ?? ''),\n category: String(pick(item, 'context_type', 'category') ?? ''),\n emotion_type: String(pick(item, 'context_type', 'emotion_type') ?? ''),\n strength: Number(pick(item, 'strength', 'confidence') ?? 0),\n summary: String(pick(item, 'summary', 'content') ?? ''),\n significance: Number(pick(item, 'significance', 'confidence') ?? 0),\n intensity: Number(pick(item, 'intensity', 'confidence') ?? 0),\n context: String(pick(item, 'context', 'content') ?? ''),\n participants: (pick(item, 'participants') ?? []) as unknown[],\n extracted_at: extractedAt as string | null,\n occurred_at: (pick(item, 'occurred_at', 'extracted_at', 'created_at') ?? null) as string | null,\n detected_at: (pick(item, 'detected_at', 'extracted_at', 'created_at') ?? null) as string | null,\n metadata: (pick(item, 'metadata') ?? {}) as Json,\n event_date: (pick(item, 'event_date') ?? null) as string | null,\n said_at: (pick(item, 'said_at') ?? null) as string | null,\n valid_until: (pick(item, 'valid_until') ?? null) as string | null,\n temporal_category: (pick(item, 'temporal_category') ?? null) as string | null,\n temporal_confidence: Number(pick(item, 'temporal_confidence') ?? 0),\n };\n}\n\n/**\n * Fold a cached summary bundle into a response, in place.\n *\n * Appends at most `MAX_SUMMARY_ITEMS` per collection, skipping anything whose\n * id the response already carries: the summary supplements a retrieval, it does\n * not replace or duplicate it.\n */\nexport function mergeUserSummary(response: RawContext, bundle: Json): RawContext {\n const itemsByType = (bundle['items_by_type'] ?? {}) as Record<string, unknown>;\n for (const collection of COLLECTIONS) {\n const items = itemsByType[collection];\n if (!Array.isArray(items)) continue;\n\n const existing = (response[collection] ?? []) as RawContextItem[];\n const existingIds = new Set(existing.map((i) => String(i.id ?? i.item_id ?? '')));\n const fresh = (items as Json[])\n .filter((i) => typeof i === 'object' && i !== null && !existingIds.has(itemId(i)))\n .slice(0, MAX_SUMMARY_ITEMS)\n .map(normalise);\n if (fresh.length === 0) continue;\n\n response[collection] = [...existing, ...fresh];\n }\n return response;\n}\n","/**\n * Serving a fetch from the anticipation cache.\n *\n * Ports Python's `_build_anticipation_response` and the cache-first branch each\n * scope fetch runs before going to the network.\n *\n * This is the point of the whole anticipation feature. The gRPC stream pushes\n * bundles ahead of time; without a lookup on the read path the cache is\n * write-only, every fetch is a billed round trip, and the stream does nothing\n * but consume bandwidth. That was the state of this SDK before: `store()` was\n * wired, `lookup()` was never called.\n */\n\nimport type { Json, RawContext } from './types.js';\nimport type { AnticipationCache, LookupResult } from './anticipation-cache.js';\n\nexport type Scope = 'conversation' | 'user' | 'customer' | 'client';\n\nexport interface AnticipationLookupParams {\n // `| undefined` explicitly, because exactOptionalPropertyTypes distinguishes\n // an absent key from one set to undefined, and callers build these by\n // spreading optionals.\n searchQuery?: readonly string[] | null | undefined;\n /** Each query's share of the places, applied on a hit as the server applies it. */\n maxResultsPerQuery?: number | null | undefined;\n /** The user. Absent for customer- and client-scope fetches. */\n entityId?: string | null | undefined;\n customerId?: string | null | undefined;\n clientId?: string | null | undefined;\n conversationId?: string | null | undefined;\n /**\n * The rung the request names, from its `scope_path`. Passed through every\n * scope unchanged: unlike the ids below it, a rung never widens, so there is\n * no scope for which dropping it would be the safe thing to do.\n */\n scopeRung?: string | null | undefined;\n}\n\n/**\n * Which identifiers a scope may widen its lookup across.\n *\n * A customer-scope request widens to client-shared bundles but explicitly NOT\n * to user-scoped ones: those would leak one visitor's data into another\n * visitor's customer fetch. Client scope narrows furthest for the same reason.\n * This mirrors the scoping notes on Python's four fetch methods.\n */\nexport function scopeLookupParams(\n scope: Scope,\n params: AnticipationLookupParams,\n): AnticipationLookupParams {\n const { searchQuery, entityId, customerId, clientId, conversationId, scopeRung, maxResultsPerQuery } = params;\n switch (scope) {\n case 'conversation':\n return { searchQuery, entityId, customerId, clientId, conversationId, scopeRung, maxResultsPerQuery };\n case 'user':\n // No conversationId: a user-scope fetch is not bound to one thread.\n return { searchQuery, entityId, customerId, clientId, scopeRung, maxResultsPerQuery };\n case 'customer':\n return { searchQuery, entityId: null, customerId, clientId, scopeRung, maxResultsPerQuery };\n case 'client':\n return { searchQuery, entityId: null, customerId: null, clientId, scopeRung, maxResultsPerQuery };\n }\n}\n\n/**\n * An item's metadata, carrying its `scope` whichever shape it arrived in.\n *\n * The HTTP response puts `scope` inside `metadata`; a prefetched (gRPC) item\n * carries it top-level and has no `metadata`. Readers look in `metadata`, so a\n * cache hit read every client-scope item as unlabelled. Returns a copy, and a\n * `scope` already in `metadata` wins. Python: `_wire_metadata` in\n * `models/context.py`.\n */\nfunction wireMetadata(item: Json): Json {\n const md = item['metadata'];\n const out: Json = md !== null && typeof md === 'object' && !Array.isArray(md) ? { ...(md as Json) } : {};\n if (!out['scope'] && item['scope']) out['scope'] = item['scope'];\n return out;\n}\n\n/** Turn a cache hit into the same raw shape the network path returns. */\nexport function buildAnticipationResponse(hit: LookupResult): RawContext {\n const response: RawContext = {};\n for (const [type, items] of Object.entries(hit.itemsByType)) {\n (response as Json)[type] = items.map((item) => ({ ...item, metadata: wireMetadata(item as Json) }));\n }\n // `source: \"anticipation\"` is how a caller (and the metering that reads it)\n // can tell a locally served fetch from a billed one.\n response.metadata = {\n source: 'anticipation',\n ttl_seconds: 0,\n cache_hit: true,\n retrieved_at: new Date().toISOString(),\n };\n return response;\n}\n\n/** Every item id in a hit, for the `context_used` event's `served_item_ids`. */\nexport function servedItemIds(hit: LookupResult): string[] {\n const ids: string[] = [];\n for (const items of Object.values(hit.itemsByType)) {\n for (const item of items) {\n const id = item.item_id ?? (item as Json)['id'];\n if (typeof id === 'string' && id !== '') ids.push(id);\n }\n }\n return ids;\n}\n\nexport interface AnticipationAttempt {\n /** The response to return, or null to fall through to the network. */\n response: RawContext | null;\n hit: LookupResult | null;\n}\n\n/**\n * Try to serve this fetch locally.\n *\n * Deliberately swallows its own errors: a fault in the cache must degrade to a\n * network fetch, never fail a retrieval that the server could have answered.\n */\nexport async function tryServeFromCache(\n cache: AnticipationCache,\n scope: Scope,\n params: AnticipationLookupParams,\n maxItems: number,\n): Promise<AnticipationAttempt> {\n try {\n const scoped = scopeLookupParams(scope, params);\n const hit = await cache.lookupAsync({\n searchQuery: scoped.searchQuery ?? null,\n entityId: scoped.entityId ?? null,\n customerId: scoped.customerId ?? null,\n clientId: scoped.clientId ?? null,\n conversationId: scoped.conversationId ?? null,\n scopeRung: scoped.scopeRung ?? null,\n maxItems,\n maxResultsPerQuery: scoped.maxResultsPerQuery ?? null,\n });\n if (hit === null) return { response: null, hit: null };\n return { response: buildAnticipationResponse(hit), hit };\n } catch {\n return { response: null, hit: null };\n }\n}\n\n/**\n * How many distinct, non-empty search queries a fetch carried, for the\n * `context_used` event's `query_count`. Matches the Python SDK and the count\n * the server itself uses when it answers a fetch: the same query sent twice is\n * one, and an empty string is none.\n */\nexport function distinctQueryCount(searchQuery: unknown): number {\n if (!Array.isArray(searchQuery)) return 0;\n return new Set(searchQuery.filter((q) => typeof q === 'string' && q.length > 0)).size;\n}\n","/**\n * `context_assembled`: what the SDK actually composed for this turn.\n *\n * Ports Python's `_emit_context_assembled_event`. Fires after every fetch\n * resolves, whether it was served from the cache, the local short-term store or\n * the network, and records what the caller actually received. That can differ\n * from what the server returned, because of SDK-side trimming, the overlay, or\n * a cache hit that skipped the server entirely.\n *\n * It drives the Requests-page audit. The server backfills a synthetic row if no\n * event arrives within its window, so a missing event is not silently lost, it\n * just produces a less accurate one.\n *\n * Privacy: ids, counts and assembly metadata only. Never prompt or item content.\n */\n\nimport type { Json, RawContext } from './types.js';\n\nconst COLLECTIONS = ['facts', 'preferences', 'episodes', 'emotions', 'temporal_events'] as const;\n\nexport interface AssembledEvent extends Json {\n correlation_id: string;\n conversation_id: string;\n user_id: string;\n customer_id: string;\n final_item_ids: string[];\n final_total_tokens: number;\n compaction_id: string;\n recent_turn_count: number;\n compaction_end_timestamp: string;\n assembly_source: string;\n assembly_duration_ms: number;\n cache_hit: boolean;\n sdk_version: string;\n}\n\n/** Every item id the caller ended up with, across all five collections. */\nexport function finalItemIds(response: RawContext): string[] {\n const ids: string[] = [];\n for (const collection of COLLECTIONS) {\n const items = response[collection];\n if (!Array.isArray(items)) continue;\n for (const item of items) {\n const id = (item as Json)['id'] ?? (item as Json)['item_id'];\n if (typeof id === 'string' && id !== '') ids.push(id);\n }\n }\n return ids;\n}\n\n/**\n * Normalise the assembly source and derive `cache_hit` from it.\n *\n * `ResponseMetadata` uses `cache` as shorthand for the local HTTP cache; the\n * proto wants the explicit name. Three sources imply a hit regardless of what\n * the metadata's own flag says, because in each the server was not consulted.\n */\nexport function resolveSource(\n response: RawContext,\n override?: string,\n): { source: string; cacheHit: boolean } {\n const metadata = (response.metadata ?? {}) as Json;\n let source = override ?? String(metadata['source'] ?? '') ?? '';\n if (source === '') source = 'cloud';\n if (source === 'cache') source = 'http_cache';\n const impliesHit = ['anticipation', 'anticipation_cache', 'http_cache', 'sdk_authoritative'];\n const cacheHit = impliesHit.includes(source) ? true : Boolean(metadata['cache_hit']);\n return { source, cacheHit };\n}\n\nexport function buildAssembledEvent(params: {\n correlationId: string;\n response: RawContext;\n conversationId?: string | undefined;\n userId?: string | undefined;\n customerId?: string | undefined;\n startedAt: number;\n sdkVersion: string;\n sourceOverride?: string | undefined;\n}): AssembledEvent {\n const { response } = params;\n const { source, cacheHit } = resolveSource(response, params.sourceOverride);\n const conversationContext = (response.conversation_context ?? {}) as Json;\n const recentTurns = conversationContext['recent_turns'];\n const metadata = (response.metadata ?? {}) as Json;\n\n return {\n correlation_id: params.correlationId,\n conversation_id: params.conversationId ?? '',\n user_id: params.userId ?? '',\n customer_id: params.customerId ?? '',\n final_item_ids: finalItemIds(response),\n final_total_tokens: Number(metadata['total_tokens'] ?? 0),\n compaction_id: String(conversationContext['compaction_id'] ?? ''),\n recent_turn_count: Array.isArray(recentTurns) ? recentTurns.length : 0,\n compaction_end_timestamp: String(\n conversationContext['end_timestamp'] ?? conversationContext['compacted_at'] ?? '',\n ),\n assembly_source: source,\n assembly_duration_ms: Math.max(0, Date.now() - params.startedAt),\n cache_hit: cacheHit,\n sdk_version: params.sdkVersion,\n };\n}\n","/**\n * Cross-scope merge + prompt formatting for `client.fetch()`.\n *\n * Ports Python's `UnifiedContextResponse.merge` and `format_for_prompt` from\n * `models/context.py`. The formatted string is the part customers actually\n * paste into a system prompt, so it is reproduced character for character:\n * section order, the `- ` bullet, the `[scope: x]` / `strength: 0.8` bracket\n * suffixes, the `## User Context` wrapper, and the blank-line joins. A\n * cosmetic drift here shows up as a diff in every prompt a customer builds.\n */\n\nimport { rankedLabel, sortByRankScore } from './ranked.js';\nimport type { Json, RawContext, RawContextItem } from './types.js';\n\n/** The five item collections, in Python's iteration order. */\nexport const ITEM_COLLECTIONS = [\n 'facts',\n 'preferences',\n 'episodes',\n 'emotions',\n 'temporal_events',\n] as const;\n\nexport type ItemCollection = (typeof ITEM_COLLECTIONS)[number];\n\nexport interface UnifiedContext {\n facts: RawContextItem[];\n preferences: RawContextItem[];\n episodes: RawContextItem[];\n emotions: RawContextItem[];\n temporal_events: RawContextItem[];\n /**\n * `response_shape: \"ranked\"` only: every item once, best first across\n * scopes and types, renumbered from 1. Empty for a by-type fetch.\n */\n items: RawContextItem[];\n /** `response_shape: \"ranked\"` only: the chunks (quotes from source documents). */\n excerpts: RawContextItem[];\n /** item id -> the scope that supplied it. */\n scope_map: Record<string, string>;\n conversation_context: Json | null;\n profile: Json | null;\n conversations: Json[] | null;\n formatted_context: string;\n scopes_queried: string[];\n total_items: number;\n metadata: Json | null;\n}\n\nfunction itemId(item: RawContextItem): string | undefined {\n const id = item.id ?? item.item_id;\n return typeof id === 'string' && id !== '' ? id : undefined;\n}\n\n/**\n * Merge per-scope responses, deduplicating by item id.\n *\n * First scope wins on a duplicate, so the caller's scope order is significant.\n * An item with no usable id is kept rather than dropped: Python indexes\n * `scope_map` by `item.id`, and a missing id there would collide every such\n * item onto one key, so keeping-and-not-mapping is the closest faithful\n * behaviour.\n */\nexport function mergeScopeResults(\n scopeResults: ReadonlyArray<readonly [string, RawContext]>,\n): UnifiedContext {\n const seen = new Set<string>();\n const out: UnifiedContext = {\n facts: [], preferences: [], episodes: [], emotions: [], temporal_events: [],\n items: [], excerpts: [],\n scope_map: {},\n conversation_context: null,\n profile: null,\n conversations: null,\n formatted_context: '',\n scopes_queried: [],\n total_items: 0,\n metadata: null,\n };\n\n const rankedSeen = new Set<string>();\n const rankedItems: RawContextItem[] = [];\n\n for (const [scopeName, response] of scopeResults) {\n out.scopes_queried.push(scopeName);\n if (out.metadata === null && response.metadata !== undefined) {\n out.metadata = response.metadata as Json;\n }\n // The C4 summary sections ride up from whichever scope produced them,\n // which is always the user-scope sub-fetch. See the fan-out rule in fetch().\n if (out.profile === null && response['profile'] !== undefined && response['profile'] !== null) {\n out.profile = response['profile'] as Json;\n }\n if (\n out.conversations === null &&\n response['conversations'] !== undefined &&\n response['conversations'] !== null\n ) {\n out.conversations = response['conversations'] as Json[];\n }\n\n for (const collection of ITEM_COLLECTIONS) {\n const items = response[collection];\n if (!Array.isArray(items)) continue;\n for (const item of items as RawContextItem[]) {\n const id = itemId(item);\n if (id !== undefined) {\n if (seen.has(id)) continue;\n seen.add(id);\n out.scope_map[id] = scopeName;\n }\n out[collection].push(item);\n }\n }\n\n // Ranked responses only, and in Python's order: excerpts share the typed\n // lists' dedup and scope map; the ranked items have a dedup of their own,\n // because they are the same items again, in order.\n const excerpts = response['excerpts'];\n if (Array.isArray(excerpts)) {\n for (const item of excerpts as RawContextItem[]) {\n const id = itemId(item);\n if (id !== undefined) {\n if (seen.has(id)) continue;\n seen.add(id);\n out.scope_map[id] = scopeName;\n }\n out.excerpts.push(item);\n }\n }\n const ranked = response['items'];\n if (Array.isArray(ranked)) {\n for (const item of ranked as RawContextItem[]) {\n const id = itemId(item);\n if (id !== undefined) {\n if (rankedSeen.has(id)) continue;\n rankedSeen.add(id);\n }\n rankedItems.push(item);\n }\n }\n }\n\n // One order across scopes, by each item's rank_score. The sort is stable, so\n // equal scores keep scope order, as Python's does, and unscored items go last.\n out.items = sortByRankScore(rankedItems).map((item, n) => ({ ...item, rank: n + 1 }));\n out.total_items =\n ITEM_COLLECTIONS.reduce((n, c) => n + out[c].length, 0) + out.excerpts.length;\n return out;\n}\n\n/** Python's `f\"{x:.1f}\"`. */\nfunction oneDecimal(value: number): string {\n return value.toFixed(1);\n}\n\n/** Python's `datetime.strftime(\"%Y-%m-%d\")` on an ISO string. */\nfunction isoDate(value: unknown): string | null {\n if (typeof value !== 'string' || value === '') return null;\n const parsed = new Date(value);\n if (Number.isNaN(parsed.getTime())) return null;\n return parsed.toISOString().slice(0, 10);\n}\n\nfunction numberOf(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null;\n}\n\nfunction scopeOf(ctx: UnifiedContext, item: RawContextItem): string {\n const id = itemId(item);\n return (id !== undefined ? ctx.scope_map[id] : undefined) ?? 'unknown';\n}\n\n/** `- text [a, b]`, with the bracket omitted when there are no extras. */\nfunction bulletWithExtras(text: string, extras: string[]): string {\n return extras.length > 0 ? `- ${text} [${extras.join(', ')}]` : `- ${text}`;\n}\n\nexport interface FormatOptions {\n includeScope?: boolean;\n includeConversationContext?: boolean;\n}\n\n/**\n * Render the merged context for prompt injection.\n *\n * Mirrors `UnifiedContextResponse.format_for_prompt`. Note the two different\n * bracket styles: facts and episodes only ever carry `[scope: x]` appended\n * directly, while preferences, emotions and temporal events build a joined\n * extras list. That asymmetry is in Python and is preserved.\n */\nexport function formatForPrompt(ctx: UnifiedContext, options: FormatOptions = {}): string {\n const includeScope = options.includeScope ?? false;\n const includeConversationContext = options.includeConversationContext ?? true;\n const sections: string[] = [];\n\n // A ranked response is one numbered list in rank order, as in Python: the\n // typed sections below would split the order back up by type.\n const ranked = ctx.items ?? [];\n if (ranked.length > 0) {\n const lines = ranked.map((it, n) => {\n let label = rankedLabel(String(it['category'] ?? ''));\n if (includeScope) label += `, scope: ${scopeOf(ctx, it)}`;\n return `${n + 1}. [${label}] ${String(it.content ?? '')}`;\n });\n sections.push(`### Memories\\n${lines.join('\\n')}`);\n }\n const typed = ranked.length === 0;\n\n if (typed && ctx.facts.length > 0) {\n const lines = ctx.facts.map((f) => {\n let line = `- ${String(f.content ?? '')}`;\n if (includeScope) line += ` [scope: ${scopeOf(ctx, f)}]`;\n return line;\n });\n sections.push(`### Facts\\n${lines.join('\\n')}`);\n }\n\n if (typed && ctx.preferences.length > 0) {\n const lines = ctx.preferences.map((p) => {\n const extras: string[] = [];\n if (includeScope) extras.push(`scope: ${scopeOf(ctx, p)}`);\n const strength = numberOf(p['strength']);\n // Python: `if p.strength and p.strength >= 0.7` -- 0 is falsy there, so a\n // zero strength is omitted rather than printed.\n if (strength !== null && strength !== 0 && strength >= 0.7) {\n extras.push(`strength: ${oneDecimal(strength)}`);\n }\n return bulletWithExtras(String(p.content ?? ''), extras);\n });\n sections.push(`### Preferences\\n${lines.join('\\n')}`);\n }\n\n if (typed && ctx.episodes.length > 0) {\n const lines = ctx.episodes.map((e) => {\n // Episodes render `summary`, not `content`.\n let line = `- ${String(e['summary'] ?? '')}`;\n if (includeScope) line += ` [scope: ${scopeOf(ctx, e)}]`;\n return line;\n });\n sections.push(`### Episodes\\n${lines.join('\\n')}`);\n }\n\n if (typed && ctx.emotions.length > 0) {\n const lines = ctx.emotions.map((em) => {\n const extras: string[] = [];\n if (includeScope) extras.push(`scope: ${scopeOf(ctx, em)}`);\n const intensity = numberOf(em['intensity']);\n if (intensity !== null && intensity !== 0 && intensity >= 0.5) {\n extras.push(`intensity: ${oneDecimal(intensity)}`);\n }\n // Emotions render \"type: context\", not a bare content field.\n const text = `${String(em['emotion_type'] ?? '')}: ${String(em['context'] ?? '')}`;\n return bulletWithExtras(text, extras);\n });\n sections.push(`### Emotions\\n${lines.join('\\n')}`);\n }\n\n if (typed && ctx.temporal_events.length > 0) {\n const lines = ctx.temporal_events.map((te) => {\n const extras: string[] = [];\n if (includeScope) extras.push(`scope: ${scopeOf(ctx, te)}`);\n const validUntil = isoDate(te['valid_until']);\n if (validUntil !== null) extras.push(`valid until: ${validUntil}`);\n return bulletWithExtras(String(te.content ?? ''), extras);\n });\n sections.push(`### Temporal Events\\n${lines.join('\\n')}`);\n }\n\n if (includeConversationContext && ctx.conversation_context !== null) {\n const formatted = ctx.conversation_context['formatted_context'];\n if (typeof formatted === 'string' && formatted !== '') {\n sections.push(`### Conversation History\\n${formatted}`);\n }\n }\n\n const blocks: string[] = [];\n if (sections.length > 0) blocks.push(`## User Context\\n${sections.join('\\n\\n')}`);\n\n const profileBlock = formatProfileBlock(ctx.profile);\n if (profileBlock !== null) blocks.push(profileBlock);\n\n const conversationsBlock = formatConversationsBlock(ctx.conversations);\n if (conversationsBlock !== null) blocks.push(conversationsBlock);\n\n return blocks.length > 0 ? blocks.join('\\n\\n') : '';\n}\n\n/** `## Caller Profile`, or null when there is nothing to show. */\nfunction formatProfileBlock(profile: Json | null): string | null {\n if (profile === null) return null;\n const attributes = profile['attributes'];\n const lines: string[] = [];\n if (typeof attributes === 'object' && attributes !== null) {\n for (const [name, attr] of Object.entries(attributes as Json)) {\n const value =\n typeof attr === 'object' && attr !== null\n ? (attr as Json)['value']\n : undefined;\n let valueStr: string;\n if (Array.isArray(value)) valueStr = value.map((v) => String(v)).join(', ');\n else if (value === null || value === undefined) valueStr = '';\n else valueStr = String(value);\n // Python does `f\"- {name}: {value}\".rstrip()`, so an empty value leaves\n // \"- name:\" with no trailing space.\n lines.push(`- ${name}: ${valueStr}`.replace(/\\s+$/, ''));\n }\n }\n const bodyParts: string[] = [];\n if (lines.length > 0) bodyParts.push(lines.join('\\n'));\n const overview = profile['overview'];\n if (typeof overview === 'string' && overview !== '') bodyParts.push(overview);\n if (bodyParts.length === 0) return null;\n return `## Caller Profile\\n${bodyParts.join('\\n\\n')}`;\n}\n\n/** `## Previous Conversations`, or null. */\nfunction formatConversationsBlock(conversations: Json[] | null): string | null {\n if (conversations === null || conversations.length === 0) return null;\n const callBlocks = conversations.map((conv) => {\n const when =\n isoDate(conv['started_at']) ?? isoDate(conv['last_message_at']) ?? isoDate(conv['ended_at']);\n let header = `### Call on ${when ?? 'unknown date'}`;\n const convType = conv['conversation_type'];\n if (typeof convType === 'string' && convType !== '') header += ` (${convType})`;\n const callLines = [header];\n const overview = overviewText(conv);\n if (overview !== null) callLines.push(`Overview: ${overview}`);\n const outcome = outcomeText(conv);\n if (outcome !== null) callLines.push(`Outcome: ${outcome}`);\n if (overview === null && outcome === null) {\n // No compaction yet, or it failed. Still tell the model the call\n // happened so it can acknowledge the prior contact.\n // Python's model defaults summary_status to \"pending\", so an absent\n // field renders as \"pending\", not as an empty string.\n callLines.push(`Status: ${String(conv['summary_status'] ?? 'pending')}`);\n }\n return callLines.join('\\n');\n });\n return `## Previous Conversations\\n${callBlocks.join('\\n\\n')}`;\n}\n\n/**\n * Mirrors `ConversationSummaryModel.overview_text()`.\n *\n * Reads the nested `summary` OBJECT (not a string) and takes the first of four\n * keys that holds non-blank text, in this exact order.\n */\nfunction overviewText(conv: Json): string | null {\n const summary = conv['summary'];\n if (typeof summary !== 'object' || summary === null || Array.isArray(summary)) return null;\n for (const key of ['narrative_summary', 'overview', 'narrative', 'summary'] as const) {\n const val = (summary as Json)[key];\n if (typeof val === 'string' && val.trim() !== '') return val.trim();\n }\n return null;\n}\n\n/**\n * Mirrors `ConversationSummaryModel.outcome_text()`.\n *\n * Joins up to three classification fields with \" / \", skipping blanks, and\n * returns null when nothing survives.\n */\nfunction outcomeText(conv: Json): string | null {\n const classification = conv['classification'];\n if (typeof classification !== 'object' || classification === null || Array.isArray(classification)) {\n return null;\n }\n const c = classification as Json;\n const parts = [c['primary_category'], c['subcategory'], c['objective']]\n .filter((p): p is string => typeof p === 'string' && p.trim() !== '');\n return parts.length > 0 ? parts.join(' / ') : null;\n}\n","/**\n * `client.as_tool(...)`: an LLM-ready tool definition for fetching context.\n *\n * Ports Python's `MaximemSynapSDK.as_tool` plus its three module helpers.\n *\n * The point of the helper is that the scope identifiers are CLOSED OVER rather\n * than exposed in the JSON schema. The LLM chooses the query and the limits; it\n * cannot choose whose memory to read. Handing the model a `user_id` parameter\n * is how the per-user privacy filter gets dropped by accident, so the schema\n * deliberately has no such field.\n */\n\nimport { InvalidInputError } from '../errors.js';\nimport type { Json } from '../context/types.js';\n\nexport type ToolScope = 'conversation' | 'user' | 'customer' | 'client' | 'unified';\nexport type ToolStyle = 'openai' | 'anthropic';\n\nconst VALID_SCOPES: readonly ToolScope[] = ['conversation', 'user', 'customer', 'client', 'unified'];\n\nexport interface AsToolOptions {\n scope?: string;\n user_id?: string;\n userId?: string;\n customer_id?: string;\n customerId?: string;\n conversation_id?: string;\n conversationId?: string;\n name?: string;\n description?: string;\n style?: string;\n}\n\nexport type ToolHandler = (callArgs?: Json) => Promise<Json>;\n\nexport interface OpenAiToolDefinition {\n type: 'function';\n function: { name: string; description: string; parameters: Json };\n handler: ToolHandler;\n}\n\nexport interface AnthropicToolDefinition {\n name: string;\n description: string;\n input_schema: Json;\n handler: ToolHandler;\n}\n\nexport type ToolDefinition = OpenAiToolDefinition | AnthropicToolDefinition;\n\nconst BASE_DESCRIPTION =\n 'Retrieve stored context (facts, preferences, recent episodes, ' +\n 'emotions, temporal events) from Synap memory.';\n\n/** Python's `_default_tool_description`. Wording is load-bearing: it primes the model to call the tool. */\nexport function defaultToolDescription(scope: ToolScope): string {\n switch (scope) {\n case 'conversation':\n return (\n BASE_DESCRIPTION +\n ' Scoped to a specific conversation. Call this when you ' +\n 'need facts already established in the current conversation, ' +\n 'or to reload context after a topic shift.'\n );\n case 'user':\n return (\n BASE_DESCRIPTION +\n \" Scoped to the user's long-term memory. Call this when \" +\n 'you need to recall who the user is, their preferences, or ' +\n 'their history across conversations.'\n );\n case 'customer':\n return (\n BASE_DESCRIPTION +\n ' Scoped to the customer/organization. Call this when ' +\n 'you need facts about the customer org rather than an individual.'\n );\n case 'client':\n return (\n BASE_DESCRIPTION +\n ' Scoped to the integrating client/product. Call this for ' +\n 'product-level knowledge (e.g. policies, documentation).'\n );\n default:\n return (\n BASE_DESCRIPTION +\n ' Cross-scope: merges conversation, user, customer, and ' +\n 'client memory in one call. Call this at the start of a turn when ' +\n 'you need general grounding before responding.'\n );\n }\n}\n\n/**\n * Python's `_tool_input_schema`.\n *\n * `conversation_id` appears ONLY for `scope=\"conversation\"` when it was not\n * closed over, in which case it is also the one required field.\n */\nexport function toolInputSchema(scope: ToolScope, options: { hasConversationId: boolean }): Json {\n const props: Json = {\n search_query: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Optional list of search queries describing what context ' +\n 'you need. Free-form natural language is fine. Omit to ' +\n 'retrieve the most relevant recent context.',\n },\n max_results: {\n type: 'integer',\n minimum: 1,\n maximum: 50,\n description: 'Maximum items to return (default 10).',\n },\n types: {\n type: 'array',\n items: {\n type: 'string',\n enum: ['facts', 'preferences', 'episodes', 'emotions', 'temporal_events'],\n },\n description: 'Filter to specific memory categories. Omit to retrieve all.',\n },\n mode: {\n type: 'string',\n enum: ['fast', 'accurate'],\n description:\n \"Retrieval mode. 'fast' = low-latency (~50ms); 'accurate' = \" +\n \"LLM-decomposed multi-query (~200-500ms). Default 'fast'.\",\n },\n precision_level: {\n type: 'string',\n enum: ['high', 'medium'],\n description:\n \"Result filtering precision. 'high' (default) applies an extra \" +\n \"relevance-refinement pass; 'medium' skips it for faster, less \" +\n 'precisely filtered results (recall unaffected).',\n },\n };\n\n let required: string[] = [];\n if (scope === 'conversation' && !options.hasConversationId) {\n props['conversation_id'] = {\n type: 'string',\n description: 'The conversation id to fetch context for.',\n };\n required = ['conversation_id'];\n }\n\n return { type: 'object', properties: props, required, additionalProperties: false };\n}\n\n/** What `as_tool` needs from the client, so this module stays testable in isolation. */\nexport interface ToolDispatchTarget {\n fetch(options: Json): Promise<{\n formatted_context: string;\n scopes_queried: string[];\n total_items: number;\n }>;\n conversation: { context: { fetch(options: Json): Promise<Json> } };\n user: { context: { fetch(options: Json): Promise<Json> } };\n customer: { context: { fetch(options: Json): Promise<Json> } };\n client: { context: { fetch(options: Json): Promise<Json> } };\n}\n\nconst RESULT_COLLECTIONS = ['facts', 'preferences', 'episodes', 'emotions', 'temporal_events'] as const;\n\n/**\n * Python's `_invoke_scope_fetch`.\n *\n * Returns a plain object so the host runtime can JSON-serialise it straight\n * into the LLM's tool-result message.\n */\nexport async function invokeScopeFetch(params: {\n target: ToolDispatchTarget;\n scope: ToolScope;\n userId: string | undefined;\n customerId: string | undefined;\n conversationId: string | undefined;\n callArgs: Json;\n}): Promise<Json> {\n const { target, scope, userId, customerId, conversationId, callArgs } = params;\n\n const searchQuery = callArgs['search_query'];\n // Python: `int(call_args.get(\"max_results\") or 10)` -- so 0 falls back to 10.\n const rawMax = callArgs['max_results'];\n const maxResults = typeof rawMax === 'number' && rawMax !== 0 ? Math.trunc(rawMax) : 10;\n const types = callArgs['types'];\n const mode = String(callArgs['mode'] ?? '') || 'fast';\n const precisionLevel = String(callArgs['precision_level'] ?? '') || 'high';\n const callConvId =\n (typeof callArgs['conversation_id'] === 'string' && callArgs['conversation_id'] !== ''\n ? (callArgs['conversation_id'] as string)\n : undefined) ?? conversationId;\n\n const shared: Json = {\n search_query: searchQuery,\n max_results: maxResults,\n types,\n mode,\n precision_level: precisionLevel,\n };\n\n if (scope === 'unified') {\n const response = await target.fetch({\n conversation_id: callConvId,\n user_id: userId,\n customer_id: customerId,\n ...shared,\n });\n return {\n formatted_context: response.formatted_context,\n scopes_queried: response.scopes_queried,\n total_items: response.total_items,\n };\n }\n\n let response: Json;\n if (scope === 'conversation') {\n if (callConvId === undefined || callConvId === '') {\n // Python returns this as DATA, not an exception: the LLM sees the error\n // string in its tool result and can retry with an id.\n return { error: 'conversation_id is required', items: [] };\n }\n response = await target.conversation.context.fetch({\n conversation_id: callConvId,\n ...shared,\n user_id: userId,\n });\n } else if (scope === 'user') {\n response = await target.user.context.fetch({\n user_id: userId,\n conversation_id: callConvId,\n ...shared,\n customer_id: customerId,\n });\n } else if (scope === 'customer') {\n response = await target.customer.context.fetch({\n customer_id: customerId,\n conversation_id: callConvId,\n ...shared,\n });\n } else {\n response = await target.client.context.fetch({\n conversation_id: callConvId,\n ...shared,\n });\n }\n\n const out: Json = {};\n for (const collection of RESULT_COLLECTIONS) {\n out[collection] = Array.isArray(response[collection]) ? response[collection] : [];\n }\n return out;\n}\n\n/**\n * Build the tool definition.\n *\n * `onWarning` receives Python's `logger.warning` for the\n * `scope=\"conversation\"` without `user_id` case, which is a soft warning\n * rather than an error.\n */\nexport function buildTool(\n target: ToolDispatchTarget,\n options: AsToolOptions = {},\n onWarning: (message: string) => void = () => {},\n): ToolDefinition {\n const scope = String(options.scope ?? 'user').toLowerCase() as ToolScope;\n if (!VALID_SCOPES.includes(scope)) {\n // Python formats the valid set with sorted() and repr() on the input.\n const sorted = [...VALID_SCOPES].sort();\n throw new InvalidInputError(\n `scope must be one of ['${sorted.join(\"', '\")}'], got '${String(options.scope)}'`,\n );\n }\n\n const userId = options.user_id ?? options.userId;\n const customerId = options.customer_id ?? options.customerId;\n const conversationId = options.conversation_id ?? options.conversationId;\n\n if (scope === 'user' && (userId === undefined || userId === '')) {\n throw new InvalidInputError(\"scope='user' requires user_id\");\n }\n if (scope === 'customer' && (customerId === undefined || customerId === '')) {\n throw new InvalidInputError(\"scope='customer' requires customer_id\");\n }\n if (scope === 'conversation' && (userId === undefined || userId === '')) {\n // Not a hard error: the anticipation cache refuses cross-user matches\n // anyway. But the caller is leaving privacy on the floor, so say so.\n onWarning(\n \"as_tool(scope='conversation') without user_id: the SDK \" +\n 'anticipation cache cannot apply per-user filtering. Pass ' +\n 'user_id to enable the Section 15 privacy guarantee.',\n );\n }\n\n const style = String(options.style ?? 'openai');\n if (style !== 'openai' && style !== 'anthropic') {\n throw new InvalidInputError(`style must be 'openai' or 'anthropic', got '${style}'`);\n }\n\n const toolName = options.name ?? `synap_fetch_${scope}_context`;\n const toolDesc = options.description ?? defaultToolDescription(scope);\n const schema = toolInputSchema(scope, { hasConversationId: conversationId !== undefined });\n\n const handler: ToolHandler = (callArgs: Json = {}) =>\n invokeScopeFetch({ target, scope, userId, customerId, conversationId, callArgs });\n\n if (style === 'openai') {\n return {\n type: 'function',\n function: { name: toolName, description: toolDesc, parameters: schema },\n handler,\n };\n }\n return { name: toolName, description: toolDesc, input_schema: schema, handler };\n}\n","/**\n * SynapClient: the public entry point.\n *\n * Exposes two surfaces, both live in production:\n *\n * - **Namespaced, snake_case** (`client.user.context.fetch(...)`) is the\n * canonical surface and mirrors the Python SDK method for method. It\n * returns raw snake_case.\n * - **Top-level camelCase** (`client.fetchUserContext(...)`) is deprecated but\n * fully supported. It returns the normalised camelCase shape, and it exists\n * because the 0.3.x wrapper had it.\n *\n * They return different shapes on purpose. See gotcha G-B.\n */\n\nimport type { AgentModel } from './agent-model.js';\nimport { AuthenticationError, InvalidInputError } from './errors.js';\nimport { getEnv } from './util/env.js';\nimport { isLocalMode, localToken } from './local-mode.js';\nimport { HttpTransport, type Credentials, type HttpTransportOptions } from './transport/http.js';\nimport { fetchContext, responseShapeOf } from './context/fetch.js';\nimport { normalizeContextResponse } from './context/normalize.js';\nimport {\n AnticipationCache, type AnticipationCacheSnapshot,\n} from './context/anticipation-cache.js';\nimport { flattenContextItems, type FlatMemory } from './context/flatten.js';\nimport {\n createMemoriesInterface, type CreateMemoryOptions, type CreateMemoryResult,\n type MemoriesInterface,\n} from './memories/interface.js';\nimport {\n createConversationNamespace, CompactionSubscribers, type ConversationNamespace,\n} from './conversation/interface.js';\nimport { createDataInterface, type DataInterface } from './data/interface.js';\nimport { createUserNamespace, type UserNamespace } from './user/interface.js';\nimport { createCreditsNamespace, type CreditsNamespace } from './credits/interface.js';\nimport { createCacheNamespace, type CacheNamespace } from './cache/interface.js';\nimport { createInstanceNamespace, type InstanceNamespace } from './instance/interface.js';\nimport type { FetchOptions, Json, NormalisedContext, RawContext } from './context/types.js';\nimport { SDK_VERSION } from './version.js';\nimport * as registry from './registry.js';\nimport { ShortTermStore, isComplete, type ShortTermTurn } from './cache/short-term-store.js';\nimport { TurnStore, type TurnInput } from './cache/turn-store.js';\nimport { renderExcerpts, searchTurns, toolResultText, type Encoder } from './cache/history-search.js';\nimport { SEMANTIC_MATCH } from './behavior/contract.js';\nimport { overlayLocalRecentTurns } from './context/overlay.js';\nimport { renderForPrompt, renderCompacted } from './context/local-prompt.js';\nimport { TurnCounter, mergeUserSummary } from './context/user-summary.js';\nimport {\n tryServeFromCache, servedItemIds, distinctQueryCount, type Scope as AnticipationScope,\n} from './context/anticipated.js';\nimport { rungKey } from './context/anticipation-cache.js';\nimport type { FetchHooks } from './context/fetch.js';\nimport { buildAssembledEvent } from './context/assembled.js';\nimport { newCorrelationId } from './util/correlation.js';\nimport { validateConversationId, validateInstanceId } from './util/validators.js';\nimport {\n mergeScopeResults, formatForPrompt, type UnifiedContext,\n} from './context/unified.js';\nimport { conversationStateContext, hasQuery, profileContext } from './context/no-query.js';\nimport { buildTool, type AsToolOptions, type ToolDefinition } from './tool/as-tool.js';\nimport { checkCustomerId } from './scoping.js';\n\n/** Levels the SDK emits. Mirrors the subset of Python's logging it uses. */\nexport type SynapLogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Receives every diagnostic the SDK would otherwise write to the console.\n *\n * Python routes these through the stdlib `logging` module, which is why it\n * takes `log_level` and `logger`. There is no global logger in JavaScript, so\n * the SDK takes the sink directly instead of a level plus a framework.\n */\nexport type SynapLogger = (level: SynapLogLevel, message: string) => void;\n\nexport interface SynapClientOptions {\n /**\n * The four identity fields are `| undefined` rather than plain optional so a\n * consumer with `exactOptionalPropertyTypes` can pass `process.env.X`\n * directly, which is what every example does. Undefined already means \"fall\n * back to the environment\" at runtime; this makes the type say so.\n */\n apiKey?: string | undefined;\n clientId?: string | undefined;\n instanceId?: string | undefined;\n baseUrl?: string | undefined;\n /** Python spells this `api_base_url`; both are accepted so one config\n * object works against either SDK. */\n api_base_url?: string | undefined;\n timeouts?: HttpTransportOptions['timeouts'];\n retryPolicy?: HttpTransportOptions['retryPolicy'];\n keepAlive?: HttpTransportOptions['keepAlive'];\n /**\n * Keep the connection warm with a periodic /health ping.\n *\n * Off by default. A clear win for a long-lived process, pure waste in\n * serverless where the container is frozen between requests anyway.\n */\n heartbeat?: boolean;\n fetchImpl?: typeof fetch;\n /**\n * Splice locally-recorded turns into the next conversation-scope fetch, so a\n * just-written turn is visible before the server compacts. Defaults to true,\n * matching Python's `st_verbatim_overlay`. `SYNAP_ST_VERBATIM_OVERLAY`\n * overrides this either way.\n */\n st_verbatim_overlay?: boolean | undefined;\n stVerbatimOverlay?: boolean | undefined;\n /**\n * The model the agent runs on, and optionally its context window. Sent with\n * every recorded turn so the server sizes compaction to the agent's window\n * (it compacts at ~11.7% of it: 15K tokens on a 128K model). A name is\n * enough; the server knows common models' windows. Unset = 128K. Python's\n * `SDKConfig.agent_model` / `agent_context_window`; per-call `model` /\n * `context_window` override them.\n */\n agent_model?: string | undefined;\n agentModel?: string | undefined;\n agent_context_window?: number | undefined;\n agentContextWindow?: number | undefined;\n\n /**\n * Let the SDK answer `get_context_for_prompt` and `get_compacted` from its\n * own short-term store when the conversation is warm, skipping the cloud\n * round trip. Off by default. `SYNAP_SDK_ST_AUTHORITATIVE` overrides this in\n * either direction.\n *\n * Leave it off for an application that runs more than one process against\n * the same conversation. A process learns the server's message count only\n * when it writes. If it reads before it writes (build the prompt, then\n * record the turn), it cannot know that another process recorded a turn in\n * between, and it answers without that turn. Turn it on where one process\n * owns a conversation for its whole life, such as a voice agent.\n *\n * This is the COST switch. `st_verbatim_overlay` is the correctness one and\n * is independent of it.\n */\n sdk_st_authoritative?: boolean | undefined;\n sdkStAuthoritative?: boolean | undefined;\n\n /**\n * Your own embedding model for history search after compaction\n * (cache/history-search.ts), any `{ model, encode }`. It replaces the\n * SDK's model for history search; the anticipation cache uses it only if it\n * is the model its thresholds were tuned on (`history_search_model`).\n */\n history_search_encoder?: Encoder | undefined;\n historySearchEncoder?: Encoder | undefined;\n\n /**\n * The local embedding model, as Python's `history_search_model`: history\n * search after compaction, and matching fetch queries to prefetched items by\n * meaning. \"auto\" (default) runs the SDK's multilingual model in Node when\n * the optional `onnxruntime-node` and `@huggingface/tokenizers` packages are\n * installed: downloaded once (about 135 MB) into ~/.synap/models when the\n * first stream starts or the first history search runs, then loaded in the\n * background. An \"onnx:<repo>@<revision>/<file>\" names another (history\n * search only). null keeps keyword matching. Never loaded on Edge or in a\n * browser.\n */\n history_search_model?: string | null | undefined;\n historySearchModel?: string | null | undefined;\n\n /**\n * Where the SDK's diagnostics go. Defaults to `console.warn` prefixed with\n * `[synap]`. Pass a no-op to silence them, or your own logger to route them.\n */\n logger?: SynapLogger | undefined;\n\n /**\n * Bypass the process registry and build a genuinely separate client.\n *\n * Underscored because it mirrors Python's `_force_new` and is not part of the\n * everyday surface. Needed in tests, and for the rare case of deliberately\n * running two clients on one identity with separate caches.\n */\n _force_new?: boolean;\n}\n\ninterface ScopedContext {\n context: { fetch: (options?: FetchOptions) => Promise<RawContext> };\n}\n\n/**\n * Options for `configure()`.\n *\n * The Python-only keys are declared so a config object can be shared between\n * the two SDKs without a type error. They are accepted and ignored: there is\n * no SQLite cache backend and no global logger to replace here.\n */\nexport interface ConfigureOptions {\n timeouts?: HttpTransportOptions['timeouts'];\n retryPolicy?: HttpTransportOptions['retryPolicy'] | null;\n retry_policy?: HttpTransportOptions['retryPolicy'] | null;\n /** Accepted and ignored. Python-only. */\n storage_path?: string;\n /** Accepted and ignored. Python-only. */\n cache_backend?: string | null;\n /** Accepted and ignored. Python-only. */\n session_timeout_minutes?: number;\n /** Accepted and ignored. Python-only. */\n log_level?: string;\n /** The agent's model; see `SynapClientOptions.agent_model`. */\n agent_model?: string;\n agentModel?: string;\n agent_context_window?: number;\n agentContextWindow?: number;\n /**\n * The local model for history search and matching a fetch to prefetched\n * context by meaning: \"auto\" (default) or a model id, null for keyword\n * matching only. As Python's SDKConfig.history_search_model. Since 0.5.19.\n */\n history_search_model?: string | null;\n historySearchModel?: string | null;\n /** Replaces the diagnostic sink, same as the constructor option. */\n logger?: SynapLogger | undefined;\n}\n\n/** Options for the cross-scope `fetch()`. Snake_case, matching Python's kwargs.\n *\n * The three identifiers accept `null` as well as `undefined`, because that is\n * what callers actually pass: `conversation_id: convId || null` is the normal\n * way to say \"there is no conversation here\", and `validateConversationId`\n * has always treated `null` as absent. The declared type said otherwise, so\n * the `SynapClient`-to-`SynapSdkLike` assignability test in\n * `synap-claude-agent` (TS) could not typecheck, and the scope guards below\n * did not agree with the validator either. See the guards for that half.\n */\nexport interface UnifiedFetchOptions {\n conversation_id?: string | null;\n user_id?: string | null;\n customer_id?: string | null;\n search_query?: string[];\n max_results?: number;\n types?: string[];\n mode?: string;\n precision_level?: string;\n /** The moment the question is being asked. See FetchOptions.query_date. */\n query_date?: string;\n /** A share of the response per search query. See FetchOptions.max_results_per_query. */\n max_results_per_query?: number;\n include_conversation_context?: boolean;\n scopes?: string[];\n include_scope_labels?: boolean;\n context_mode?: string;\n include_profile?: boolean;\n last_n_conversations?: number;\n /**\n * `\"by_type\"` (default) or `\"ranked\"`. Ranked asks every scope for its\n * ranked list and merges them into `items`, best first across scopes and\n * types, by each item's `rank_score`; `formatted_context` is then one\n * numbered list in that order. The typed lists are filled either way.\n */\n response_shape?: string;\n}\n\n/** `SYNAP_SDK_LOCAL_MODEL=off` keeps the local embedding model from loading. Python: the same. */\nfunction localModelOff(): boolean {\n return ['off', '0', 'false', 'no', 'none'].includes((getEnv('SYNAP_SDK_LOCAL_MODEL') ?? '').trim().toLowerCase());\n}\n\nexport class SynapClient {\n // Native-private (`#`), not TypeScript `private`. TS `private` is erased at\n // compile time, so the field stays enumerable at runtime and a JS consumer\n // can still reach it. These two were public and made `client.transport\n // .credentials.apiKey` and the raw cache's `now`/`fire`/`invalidateEntity`\n // reachable, which is exactly what `client.cache` exists to prevent.\n // Definite-assignment assertions (`!`) because the constructor can RETURN an\n // existing client from the registry before reaching any of these. TypeScript\n // cannot follow a constructor return, so it sees a path where the fields are\n // unassigned. On that path the object is discarded and the incumbent is\n // handed back instead, so nothing observes them.\n readonly #transport!: HttpTransport;\n readonly #anticipationCache!: AnticipationCache;\n\n readonly user!: UserNamespace;\n readonly customer!: ScopedContext;\n readonly client!: ScopedContext;\n readonly conversation!: ConversationNamespace;\n readonly memories!: MemoriesInterface;\n readonly data!: DataInterface;\n readonly credits!: CreditsNamespace;\n readonly cache!: CacheNamespace;\n readonly instance!: InstanceNamespace;\n\n #closed = false;\n #initialized = false;\n #identity: Promise<void> | undefined;\n #localMode = false;\n readonly #registryKeys!: string[];\n readonly #compactionSubscribers!: CompactionSubscribers;\n readonly #shortTerm!: ShortTermStore;\n /** Every raw turn, past compaction, for local history search. */\n readonly #turnStore!: TurnStore;\n /** A local embedding model for history search; null = keywords only. */\n #localEncoder: Encoder | null = null;\n /** `history_search_model`: \"auto\", an \"onnx:...\" name, or null for none. */\n #localModelName: string | null = 'auto';\n #localModelStarted = false;\n readonly #backfillAfter = new Map<string, number>();\n readonly #stVerbatimOverlay!: boolean | undefined;\n #agentModel: AgentModel = {};\n #logger!: SynapLogger | undefined;\n readonly #stAuthoritative!: boolean | undefined;\n readonly #turns!: TurnCounter;\n readonly #fetchHooks!: FetchHooks;\n\n constructor(options: SynapClientOptions = {}) {\n const resolvedBaseUrl = resolveBaseUrl(options);\n const localMode = isLocalMode(options.apiKey, resolvedBaseUrl);\n const credentials = resolveCredentials(options, localMode);\n // Fail locally on a malformed id rather than sending it upstream.\n validateInstanceId(credentials.instanceId);\n\n // ── Registry: one client per identity, per process ──────────────────────\n // Python has shared state here since 0.2. Without it, a framework\n // integration that builds a client per request or per agent gets a cold\n // anticipation cache every time and pays for a retrieval that Python would\n // have served locally.\n //\n // Returning from a constructor is unusual in JS but legal, and it is the\n // closest equivalent of Python's `self.__dict__ = existing.__dict__`. The\n // two callers then hold the SAME object rather than two objects sharing a\n // state bag, which is stricter than Python.\n const registryKey = registry.buildRegistryKey(credentials.instanceId, credentials.apiKey);\n if (options._force_new !== true) {\n const existing = registry.get(registryKey) as SynapClient | undefined;\n if (existing !== undefined) {\n // Handing back a client built on a DIFFERENT credential than the caller\n // just supplied. Only reachable on the explicit instanceId path, where\n // the id is the identity and the key is not part of it. The caller has\n // no other way to find out: the returned object looks exactly like the\n // one they asked for.\n const incumbent = existing.#transport.currentCredentials().apiKey;\n if (credentials.apiKey && incumbent && credentials.apiKey !== incumbent) {\n existing.#warn(\n `Instance ${registryKey} is already running in this process on a different ` +\n 'API key. The key passed here is ignored; this client will authenticate ' +\n 'as the existing one. Rotating a key this way has no effect. Construct ' +\n 'with apiKey and no instanceId to get a client on your own credential.',\n );\n }\n return existing;\n }\n }\n this.#registryKeys = options._force_new === true ? [] : [registryKey];\n this.#localMode = localMode;\n\n this.#transport = new HttpTransport({\n credentials,\n // SYNAP_BASE_URL is honoured, as Python does (sdk.py) and as the 0.3.x\n // wrapper did. Ignoring it was a wrong-DESTINATION bug rather than a\n // missing convenience: anyone pointing at a self-hosted or staging\n // deployment through the environment would silently have started sending\n // their data to production on upgrade.\n ...(resolvedBaseUrl !== undefined ? { baseUrl: resolvedBaseUrl } : {}),\n ...(options.timeouts !== undefined ? { timeouts: options.timeouts } : {}),\n ...(options.retryPolicy !== undefined ? { retryPolicy: options.retryPolicy } : {}),\n ...(options.keepAlive !== undefined ? { keepAlive: options.keepAlive } : {}),\n ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}),\n userAgent: `@maximem/synap-js-sdk/${SDK_VERSION}`,\n });\n if (options.heartbeat) this.#transport.startHeartbeat();\n this.#transport.identityResolver = () => this.#resolveIdentity();\n\n this.#anticipationCache = new AnticipationCache();\n\n this.#fetchHooks = {\n beforeFetch: async (scope, options) => {\n const o = options as Record<string, unknown>;\n // A prefetched bundle was assembled with no period restriction, so it\n // cannot answer a request that names one. Same class as the scope_path\n // defect described below: a bundle built for one question served to a\n // different one, entirely inside this process and invisible to every\n // server log. Skipping the cache costs one round trip; serving a bundle\n // that ignores the date costs the answer.\n if (o['query_date'] ?? o['queryDate']) return null;\n // Deliberately kept: only benchmarks and evaluation tools send a date.\n // A per-query share no longer skips: the hit applies it, by the\n // server's rule (anticipation-cache `reservePerQuery`).\n const attempt = await tryServeFromCache(\n this.#anticipationCache,\n scope as AnticipationScope,\n {\n searchQuery: (o['search_query'] ?? o['searchQuery']) as string[] | undefined,\n entityId: (o['user_id'] ?? o['userId']) as string | undefined,\n customerId: (o['customer_id'] ?? o['customerId']) as string | undefined,\n clientId: this.#transport.currentCredentials().clientId || null,\n conversationId: (o['conversation_id'] ?? o['conversationId']) as string | undefined,\n // The rung this read is addressed to, in the same words the server\n // stamped on the bundles it pushed. Without it the cache matched\n // on entity and conversation alone, so a bundle prefetched for one\n // rung answered a caller standing at another, entirely inside this\n // process and invisible to every server log.\n scopeRung: rungKey(\n (o['scope_path'] ?? o['scopePath']) as Record<string, string> | undefined,\n ),\n maxResultsPerQuery: (o['max_results_per_query'] ?? o['maxResultsPerQuery'] ?? null) as number | null,\n },\n Number(o['max_results'] ?? o['maxResults'] ?? 10),\n );\n if (attempt.response === null || attempt.hit === null) return null;\n return {\n response: attempt.response,\n servedItemIds: servedItemIds(attempt.hit),\n bundleId: attempt.hit.bundleIds[0] ?? '',\n borderline: attempt.hit.band === 'borderline',\n raceDeadlineMs: SEMANTIC_MATCH.race_deadline_ms,\n };\n },\n onAssembled: (scope, options, response, startedAt) => {\n this.#emitContextAssembled(scope, options as Record<string, unknown>, response, startedAt);\n },\n onServedFromCache: (_scope, options, served) => {\n // Fire-and-forget over the Listen stream. Drives the server's learning\n // loop: per-prefetch outcome scoring, per-pattern hit rates. Carries\n // ids and scope only, never prompt content.\n this.#emitContextUsed(options as Record<string, unknown>, _scope, served);\n },\n // The periodic user-summary splice, as Python runs it at the end of the\n // user, customer and client fetches (the conversation fetch does its own\n // through `onFetched`). Until 0.5.12 only the conversation fetch had it,\n // so the same usage gave the model different context in JS.\n // Python's `_should_skip_server_st`: when this process already holds the\n // conversation's compaction and every turn after it, the server is told\n // not to assemble them again.\n // A fetch with no query, as Python answers it inside the two scoped\n // fetches: the conversation's state, or the user's profile when there\n // is one. A profile read that fails falls back to the fetch as before.\n withoutQuery: async (scope, options) => {\n const o = options as Record<string, unknown>;\n if (scope === 'conversation') {\n const id = (o['conversation_id'] ?? o['conversationId']) as string;\n const prompt = await this.conversation.context.get_context_for_prompt({ conversation_id: id });\n return conversationStateContext(prompt as Json, id);\n }\n if (scope === 'user') {\n try {\n const customerId = (o['customer_id'] ?? o['customerId']) as string | undefined;\n const profile = await this.user.get_profile({\n user_id: (o['user_id'] ?? o['userId']) as string,\n ...(customerId !== undefined ? { customer_id: customerId } : {}),\n });\n return profileContext(profile);\n } catch {\n // The caller's input was checked before this point, so any error\n // here is the profile read's own: no profile, or a failure.\n return null;\n }\n }\n return null;\n },\n skipServerShortTerm: (conversationId) => {\n if (!this.#isStAuthoritative()) return false;\n const entry = this.#shortTerm.get(conversationId);\n return entry !== null && entry.compactionId !== null && isComplete(entry);\n },\n onResponse: (scope, options, response) => {\n if (scope === 'conversation') return;\n const o = options as Record<string, unknown>;\n const owner = scope === 'user'\n ? (o['user_id'] ?? o['userId'])\n : scope === 'customer' ? (o['customer_id'] ?? o['customerId']) : '_client';\n this.#injectUserSummary(\n response,\n (o['conversation_id'] ?? o['conversationId']) as string | undefined,\n owner as string | undefined,\n rungKey((o['scope_path'] ?? o['scopePath']) as Record<string, string> | undefined),\n );\n },\n };\n\n this.user = createUserNamespace(this.#transport, this.#fetchHooks);\n // `async` arrows, not bare ones. fetchContext is already async so nothing\n // can throw synchronously today, but these are the only two namespace\n // methods that were not async, and the next person to add a validation\n // line above the call would reintroduce a throw that bypasses .catch().\n this.customer = { context: { fetch: async (o = {}) => fetchContext(this.#transport, 'customer', o, this.#fetchHooks) } };\n this.client = { context: { fetch: async (o = {}) => fetchContext(this.#transport, 'client', o, this.#fetchHooks) } };\n this.#compactionSubscribers = new CompactionSubscribers();\n this.#shortTerm = new ShortTermStore();\n // Every raw turn, kept past compaction for local search (turn-store.ts).\n this.#turnStore = new TurnStore();\n this.#shortTerm.attachArchive(this.#turnStore);\n this.#stVerbatimOverlay = options.st_verbatim_overlay ?? options.stVerbatimOverlay;\n this.#agentModel = {\n model: options.agent_model ?? options.agentModel,\n contextWindow: options.agent_context_window ?? options.agentContextWindow,\n };\n this.#logger = options.logger;\n this.#stAuthoritative = options.sdk_st_authoritative ?? options.sdkStAuthoritative;\n this.#localEncoder = options.history_search_encoder ?? options.historySearchEncoder ?? null;\n const modelOption = options.history_search_model !== undefined\n ? options.history_search_model\n : options.historySearchModel;\n this.#localModelName = modelOption === undefined ? 'auto' : modelOption;\n if (this.#localEncoder?.model === SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(this.#localEncoder);\n this.#turns = new TurnCounter();\n this.conversation = createConversationNamespace(\n this.#transport,\n this.#compactionSubscribers,\n // Mirrors Python's `_invalidate_anticipation_on_write`, including its\n // gate: `invalidateEntity` is a no-op unless\n // SYNAP_SDK_CACHE_INVALIDATE_ON_WRITE is set, so default behaviour is\n // unchanged. Over-invalidating after a failed write is safe; it only\n // costs the next lookup a cold fetch.\n ({ userId, customerId }) => {\n for (const id of new Set([userId, customerId])) {\n if (id) this.#anticipationCache.invalidateEntity(id);\n }\n },\n // Buffer the turn locally so the next fetch sees it, ahead of the server\n // having persisted and compacted it.\n ({ conversationId, role, content, timestamp, messageId, serverMessageCount, inFlight }) => {\n this.#shortTerm.appendTurn(conversationId, role, content, timestamp, {\n messageId,\n serverMessageCount,\n inFlight,\n });\n },\n (response, conversationId, userId, scopePath) => {\n overlayLocalRecentTurns(response, this.#shortTerm, conversationId, this.#stVerbatimOverlay);\n this.#injectUserSummary(response, conversationId, userId, rungKey(scopePath));\n },\n {\n prompt: (conversationId, style) => this.#localPrompt(conversationId, style),\n compacted: (conversationId, format) => this.#localCompacted(conversationId, format),\n reseed: (conversationId, response) => this.#reseedShortTerm(conversationId, response),\n historyExcerpts: (conversationId, response, query) => this.#withHistoryExcerpts(conversationId, response, query),\n },\n () => this.#agentModel,\n // The same hooks as the other three scopes: the anticipation cache first,\n // as Python's conversation fetch does, and the audit events. Until 0.5.13\n // the conversation fetch was built without them, so every JS conversation\n // fetch was a billed round trip, including ones the stream had answered.\n this.#fetchHooks,\n );\n // After a forget that deleted something, drop that user's cached bundles so\n // they are not served until the TTL runs out. Unconditional, unlike the\n // invalidate-on-write hook: a forgotten memory must not be served.\n this.memories = createMemoriesInterface(this.#transport, ({ userId, customerId }) => {\n for (const id of new Set([userId, customerId])) {\n if (id) this.#anticipationCache.dropEntity(id);\n }\n });\n // After a delete, drop this machine's copies of what the server removed.\n this.data = createDataInterface(this.#transport, ({ scope, userId, customerId, conversationId }) => {\n const cleared: string[] = [];\n if (scope === 'conversation') {\n if (conversationId) {\n this.#shortTerm.invalidate(conversationId);\n this.#turnStore.drop(conversationId);\n cleared.push('short_term_context', 'turns');\n }\n } else {\n for (const id of new Set(scope === 'user' ? [userId, customerId] : [customerId])) {\n if (id) this.#anticipationCache.dropEntity(id);\n }\n // Only the anticipation cache is dropped here; the JS SDK keeps no other\n // per-entity context cache, so nothing else is claimed.\n cleared.push('anticipation_cache');\n }\n return cleared;\n });\n this.credits = createCreditsNamespace(this.#transport);\n this.cache = createCacheNamespace(this.#anticipationCache);\n this.instance = createInstanceNamespace(\n () => this.#transport.currentCredentials(),\n this.#anticipationCache,\n ({ conversationId, role, content }) => {\n this.#shortTerm.appendTurn(conversationId, role, content);\n },\n // A FilePart given by url is read with the same fetch as everything else.\n ((url: string, init?: RequestInit) =>\n this.#transport.fetchExternal(url, init)) as typeof fetch,\n () => this.#agentModel,\n ({ conversationId, result, toolName }: { conversationId: string; result: unknown; toolName: string }) =>\n this.archive_tool_result(conversationId, result, { tool_name: toolName }),\n (customerId, where) => this.#transport.checkCustomerId(customerId, where),\n );\n // A compaction folds turns into the server's summary, so the local copies\n // of those turns must go or they keep being spliced back in.\n // Prefetched bundles start arriving with the stream: load the local model\n // then, not at construction, so a process that never listens or searches\n // never downloads it.\n this.instance._internal.setOnListen(() => this.#startLocalModel());\n if (localMode) {\n this.instance._internal.blockListen(\n 'Not available in the open-source server: listen() needs the gRPC stream and ' +\n 'anticipation, which it does not have.',\n );\n }\n this.instance._internal.setCompactionApplier((bundle) => {\n this.#shortTerm.applyCompaction(bundle);\n });\n // The server's message count after each streamed write, which is how the\n // store learns whether it holds the whole conversation.\n this.instance._internal.setConversationStateHandler((conversationId, messageCount) => {\n this.#shortTerm.noteServerCount(conversationId, messageCount);\n });\n\n if (options._force_new !== true) {\n // Claim the slot. A separate get-then-set would race in a threaded\n // runtime; JS is single-threaded between these statements, so this is\n // one operation for clarity rather than for locking.\n const incumbent = registry.registerIfAbsent(registryKey, this) as SynapClient | undefined;\n if (incumbent !== undefined) return incumbent;\n }\n // Route compaction bundles from the one Listen stream into the typed\n // per-conversation subscriptions. Wired here rather than inside either\n // namespace so the two do not have to import each other.\n this.instance._internal.setCompactionDispatcher((conversationId, bundle) => {\n this.#compactionSubscribers.dispatch(conversationId, bundle as Json, (error) => {\n this.#warn(`compaction subscriber threw: ${String(error)}`);\n });\n });\n }\n\n // ── Deprecated camelCase surface, carried over from the 0.3.x wrapper ───────\n // These return the NORMALISED shape, unlike their namespaced equivalents.\n\n /** @deprecated Use `client.user.context.fetch()`. Note it returns raw snake_case. */\n async fetchUserContext(options: FetchOptions = {}): Promise<NormalisedContext> {\n return normalizeContextResponse((await fetchContext(this.#transport, 'user', options)) as Json);\n }\n\n /** @deprecated Use `client.customer.context.fetch()`. */\n async fetchCustomerContext(options: FetchOptions = {}): Promise<NormalisedContext> {\n return normalizeContextResponse((await fetchContext(this.#transport, 'customer', options)) as Json);\n }\n\n /** @deprecated Use `client.client.context.fetch()`. */\n async fetchClientContext(options: FetchOptions = {}): Promise<NormalisedContext> {\n return normalizeContextResponse((await fetchContext(this.#transport, 'client', options)) as Json);\n }\n\n /** @deprecated Use `client.conversation.context.get_context_for_prompt()`. */\n async getContextForPrompt(\n options: { conversationId?: string; conversation_id?: string; style?: string } = {},\n ): Promise<Json> {\n return this.conversation.context.get_context_for_prompt(options);\n }\n\n /**\n * @deprecated Use `client.user.context.fetch()` and read the typed collections.\n *\n * Flattens every context type into one list, exactly as the 0.3.x bridge did.\n */\n async searchMemory(options: {\n userId?: string; user_id?: string;\n customerId?: string; customer_id?: string;\n query: string;\n maxResults?: number; max_results?: number;\n mode?: string;\n conversationId?: string; conversation_id?: string;\n types?: string[];\n }): Promise<{ results: FlatMemory[]; count: number }> {\n const userId = options.user_id ?? options.userId;\n if (!userId) throw new InvalidInputError('user_id is required');\n if (options.query === undefined || options.query === null) {\n throw new InvalidInputError('query is required');\n }\n const context = await fetchContext(this.#transport, 'user', {\n user_id: userId,\n ...(pick(options, 'customer_id', 'customerId') !== undefined\n ? { customer_id: pick(options, 'customer_id', 'customerId') as string }\n : {}),\n ...(pick(options, 'conversation_id', 'conversationId') !== undefined\n ? { conversation_id: pick(options, 'conversation_id', 'conversationId') as string }\n : {}),\n search_query: [options.query],\n max_results: (pick(options, 'max_results', 'maxResults') as number) ?? 10,\n types: options.types ?? ['all'],\n ...(options.mode !== undefined ? { mode: options.mode } : {}),\n });\n const results = flattenContextItems(context);\n return { results, count: results.length };\n }\n\n /**\n * @deprecated Use `client.user.context.fetch()` with an empty `search_query`.\n *\n * Note the default of 100, not 10: it matches the 0.3.x bridge.\n */\n async getMemories(options: {\n userId?: string; user_id?: string;\n customerId?: string; customer_id?: string;\n mode?: string;\n conversationId?: string; conversation_id?: string;\n maxResults?: number; max_results?: number;\n types?: string[];\n }): Promise<{ results: FlatMemory[]; count: number }> {\n const userId = options.user_id ?? options.userId;\n if (!userId) throw new InvalidInputError('user_id is required');\n const context = await fetchContext(this.#transport, 'user', {\n user_id: userId,\n ...(pick(options, 'customer_id', 'customerId') !== undefined\n ? { customer_id: pick(options, 'customer_id', 'customerId') as string }\n : {}),\n ...(pick(options, 'conversation_id', 'conversationId') !== undefined\n ? { conversation_id: pick(options, 'conversation_id', 'conversationId') as string }\n : {}),\n search_query: [],\n max_results: (pick(options, 'max_results', 'maxResults') as number) ?? 100,\n types: options.types ?? ['all'],\n ...(options.mode !== undefined ? { mode: options.mode } : {}),\n });\n const results = flattenContextItems(context);\n return { results, count: results.length };\n }\n\n /** @deprecated Use `client.memories.create()`. */\n async addMemory(options: CreateMemoryOptions): Promise<CreateMemoryResult> {\n return this.memories.create(options);\n }\n\n /**\n * @deprecated Use `client.memories.delete(memoryId)`.\n *\n * The `{ userId }` form is gone: it relied on a process-local id list and so\n * deleted nothing in serverless while reporting success (gotcha G-F).\n */\n async deleteMemory(options: { memoryId?: string; memory_id?: string }): Promise<Json> {\n return this.memories.delete(options.memory_id ?? options.memoryId ?? '');\n }\n\n /**\n * Resolve `client_id` and `instance_id` from the API key.\n *\n * Mirrors Python's `initialize()`. Python raises \"SDK not initialized\" on\n * any call made before it; here the first request runs the same resolution\n * instead (`identityResolver` on the transport), so skipping this call costs\n * nothing and breaks no existing caller. It matters for the anticipation\n * cache: a bundle shared at client scope is filtered on `client_id`, and an\n * empty one fails that filter for every bundle.\n *\n * Calling it explicitly still locks `configure()`, as in Python. Resolving\n * on first use does not, because a caller who never called it could always\n * configure after a request, and that keeps working.\n *\n * Best-effort and idempotent. A whoami failure leaves whatever the\n * constructor resolved and is not fatal.\n */\n async initialize(): Promise<void> {\n this.#initialized = true;\n await this.#resolveIdentity();\n }\n\n /** Runs whoami at most once, however many calls arrive together. */\n #resolveIdentity(): Promise<void> {\n this.#identity ??= this.#whoami().catch((error: unknown) => {\n // Only local mode throws. Forget the failure so a later call asks again.\n this.#identity = undefined;\n throw error;\n });\n return this.#identity;\n }\n\n async #whoami(): Promise<void> {\n const credentials = this.#transport.currentCredentials();\n if (!this.#localMode && credentials.clientId !== '' && credentials.instanceId !== '') return;\n try {\n const whoami = (await this.#transport.request('whoami', {})) as Json;\n const resolvedClientId = String(whoami['client_id'] ?? '');\n const resolvedInstanceId = String(whoami['instance_id'] ?? '');\n // The instance's scoping mode. Absent against any server older than this\n // field, and absent stays undefined, which every check treats as \"do not\n // enforce\". The server rejects independently either way.\n const iso = whoami['user_context_isolation'];\n // Stored on the transport, not on the client: every interface factory\n // already receives the transport, and surface-parity.test.ts is right\n // that a public member Python does not have is a divergence.\n this.#transport.userContextIsolation = typeof iso === 'string' ? iso : undefined;\n this.#transport.updateCredentials({\n ...(resolvedClientId !== '' && credentials.clientId === ''\n ? { clientId: resolvedClientId }\n : {}),\n ...(resolvedInstanceId !== '' && credentials.instanceId === ''\n ? { instanceId: resolvedInstanceId }\n : {}),\n });\n\n // Now that the real instance id is known, point it at this client too.\n // It was keyed on the credential because the id did not exist yet, so a\n // later `new SynapClient({ instanceId })` for the same instance would\n // otherwise miss and build a second client: two anticipation caches and\n // two Listen streams for one instance. The credential slot is kept, so\n // constructing by API key keeps resolving here as well.\n if (resolvedInstanceId !== '' && this.#registryKeys.length > 0) {\n if (registry.aliasIfAbsent(resolvedInstanceId, this)) {\n this.#registryKeys.push(resolvedInstanceId);\n }\n }\n } catch (error) {\n // Non-fatal, exactly as in Python: identity resolution is an\n // optimisation, and every route still authenticates on the API key.\n // Local mode has no key to fall back on, so there it is an error.\n if (this.#localMode) {\n throw new AuthenticationError(\n `Could not reach the Synap server at ${this.#transport.baseUrl}, or it did not ` +\n `identify itself: GET /api/v1/auth/whoami failed (${(error as Error)?.message ?? String(error)}).`,\n { cause: error },\n );\n }\n }\n if (this.#localMode) {\n const known = this.#transport.currentCredentials();\n if (known.clientId === '' || known.instanceId === '') {\n throw new AuthenticationError(\n `The Synap server at ${this.#transport.baseUrl} did not identify itself: ` +\n 'GET /api/v1/auth/whoami returned no client_id or instance_id.',\n );\n }\n }\n }\n\n /**\n * @deprecated Use `initialize()`, which is the Python name. `init()` was a\n * JS-only spelling with no Python counterpart; it now forwards, so a 0.3.x\n * startup script keeps working.\n */\n async init(): Promise<void> {\n return this.initialize();\n }\n\n /** The resolved instance id. Empty until `initialize()` resolves it. */\n get instance_id(): string {\n return this.#transport.currentCredentials().instanceId;\n }\n\n /** The resolved client id. Empty until `initialize()` resolves it. */\n get client_id(): string {\n return this.#transport.currentCredentials().clientId;\n }\n\n /**\n * Update configuration before `initialize()`.\n *\n * Mirrors Python's `configure()`, including its refusal to reconfigure after\n * initialization: the transport and cache are already built by then and a\n * half-applied config is worse than a rejected one.\n *\n * `logger` is honoured here as well as on the constructor. The remaining\n * Python-only keys (`storage_path`, `cache_backend`,\n * `session_timeout_minutes`, `log_level`) are accepted and ignored rather\n * than rejected, because this SDK has no SQLite cache backend and no global\n * logging framework whose level there would be to set. Ignoring them keeps\n * a shared config object portable between the two SDKs.\n */\n configure(options: ConfigureOptions = {}): void {\n if (this.#initialized) {\n throw new InvalidInputError('Cannot reconfigure after initialization');\n }\n if (options.timeouts !== undefined) this.#transport.setTimeouts(options.timeouts);\n if (options.retryPolicy !== undefined || options.retry_policy !== undefined) {\n this.#transport.setRetryPolicy(options.retryPolicy ?? options.retry_policy ?? null);\n }\n if (options.logger !== undefined) this.#logger = options.logger;\n // As Python's SDKConfig.history_search_model. Until 0.5.19 only the\n // constructor took it here. It applies to the model the SDK loads when it\n // first needs one; once that has started, changing it does nothing.\n const historyModel = options.history_search_model !== undefined\n ? options.history_search_model\n : options.historySearchModel;\n if (historyModel !== undefined && !this.#localModelStarted) this.#localModelName = historyModel;\n const model = options.agent_model ?? options.agentModel;\n const window = options.agent_context_window ?? options.agentContextWindow;\n if (model !== undefined || window !== undefined) {\n this.#agentModel = {\n model: model ?? this.#agentModel.model,\n contextWindow: window ?? this.#agentModel.contextWindow,\n };\n }\n }\n\n /**\n * Fetch and merge context across every scope with an identifier, in one call.\n *\n * Mirrors Python's `sdk.fetch()`. The three behaviours worth knowing:\n *\n * - Scope fetches run in parallel and a FAILED scope is dropped with a\n * warning rather than failing the call, so partial context still gets\n * returned. The one exception is `InvalidInputError`: a bad request must\n * surface instead of degrading into a silently-empty context.\n * - `user_id` is threaded into the conversation-scope sub-fetch so the\n * anticipation cache can apply its per-user filter.\n * - The summary-mode parameters go ONLY to the user-scope sub-fetch. The\n * other three routes return 422 for `context_mode=\"conversation-summary\"`,\n * and that rejection would be swallowed by the drop-failed-scope rule.\n */\n async fetch(options: UnifiedFetchOptions = {}): Promise<UnifiedContext> {\n const {\n conversation_id: conversationId,\n user_id: userId,\n customer_id: customerId,\n search_query: searchQuery,\n max_results: maxResults = 20,\n types,\n mode = 'fast',\n precision_level: precisionLevel = 'high',\n query_date: queryDate,\n max_results_per_query: maxResultsPerQuery,\n include_conversation_context: includeConversationContext = true,\n scopes,\n include_scope_labels: includeScopeLabels = false,\n context_mode: contextMode = 'in-conversation',\n include_profile: includeProfile = true,\n last_n_conversations: lastNConversations = 1,\n response_shape: responseShape = 'by_type',\n } = options;\n\n // First, as Python checks it: on B2C a customer_id is refused even when\n // `scopes` leaves out every sub-fetch that would have carried it.\n await this.#transport.checkCustomerId(customerId, 'sdk.fetch');\n validateConversationId(conversationId);\n // Up front, as Python does: a bad value inside a scope fetch would be an\n // InvalidInputError too, but only once a scope is queried.\n responseShapeOf({ response_shape: responseShape });\n\n const wants = (scope: string): boolean => scopes === undefined || scopes.includes(scope);\n const shared = {\n search_query: searchQuery,\n max_results: maxResults,\n types,\n mode,\n precision_level: precisionLevel,\n // In `shared` so it reaches all four branches at once. The Python edit\n // threaded three call sites by hand and missed the client branch, which\n // sits one indent deeper; spreading removes that whole class of miss.\n query_date: queryDate,\n max_results_per_query: maxResultsPerQuery,\n response_shape: responseShape,\n };\n\n const labels: string[] = [];\n const tasks: Array<Promise<RawContext>> = [];\n\n // `null` means absent, exactly as `validateConversationId` already reads\n // it. The guards below used to test only `!== undefined && !== ''`, so a\n // caller writing `conversation_id: convId || null` -- which is what the\n // Claude Agent (TS) integration writes, and the obvious way to spell \"no\n // conversation\" -- sailed past them and fired a conversation-scope fetch\n // carrying `conversation_id: null`. The validator waved it through and the\n // scope was queried for a conversation that does not exist.\n const present = (v: string | null | undefined): v is string =>\n v !== undefined && v !== null && v !== '';\n\n // No query: the conversation scope answers with the conversation's state\n // (get_context_for_prompt, below) instead of searching for nothing; the\n // user scope answers with the profile when there is one. Summary mode is\n // its own assembly and is unchanged. The state is added only when\n // include_conversation_context asks for it: a framework that keeps its own\n // message history turns it off (pydantic-ai, Mastra), and must not get\n // those turns twice. Python: sdk.fetch.\n const conversationState =\n present(conversationId) && contextMode !== 'conversation-summary'\n && !hasQuery(searchQuery) && wants('conversation');\n const withConversationContext = includeConversationContext;\n\n if (present(conversationId) && wants('conversation') && !conversationState) {\n labels.push('conversation');\n tasks.push(this.conversation.context.fetch({\n conversation_id: conversationId, ...shared,\n user_id: userId, customer_id: customerId,\n } as FetchOptions));\n }\n if (present(userId) && wants('user')) {\n labels.push('user');\n tasks.push(this.user.context.fetch({\n user_id: userId, conversation_id: conversationId, ...shared,\n customer_id: customerId,\n context_mode: contextMode,\n include_profile: includeProfile,\n last_n_conversations: lastNConversations,\n } as FetchOptions));\n }\n if (present(customerId) && wants('customer')) {\n labels.push('customer');\n tasks.push(this.customer.context.fetch({\n customer_id: customerId, conversation_id: conversationId, ...shared,\n } as FetchOptions));\n }\n // Client scope needs no identifier (it is inferred from auth), but Python\n // only queries it when EXPLICITLY named in `scopes`. Preserved: including\n // it by default would add a billed fetch to every unified call.\n if (scopes !== undefined && scopes.includes('client')) {\n labels.push('client');\n tasks.push(this.client.context.fetch({\n conversation_id: conversationId, ...shared,\n } as FetchOptions));\n }\n\n if (tasks.length === 0 && !(conversationState && includeConversationContext)) {\n const empty = mergeScopeResults([]);\n return empty;\n }\n\n const settled = await Promise.allSettled(tasks);\n const successful: Array<readonly [string, RawContext]> = [];\n for (const [i, result] of settled.entries()) {\n const label = labels[i] as string;\n if (result.status === 'fulfilled') {\n successful.push([label, result.value]);\n continue;\n }\n if (result.reason instanceof InvalidInputError) throw result.reason;\n this.#warn(`Scope '${label}' fetch failed in unified fetch (non-fatal): ${String(result.reason)}`);\n }\n\n const merged = mergeScopeResults(successful);\n\n // Read-your-writes: splice the locally buffered tail over whatever the\n // server returned for this conversation.\n for (const [, response] of successful) {\n overlayLocalRecentTurns(response, this.#shortTerm, conversationId, this.#stVerbatimOverlay);\n }\n\n if (withConversationContext && present(conversationId)) {\n try {\n merged.conversation_context = (await this.conversation.context.get_context_for_prompt({\n conversation_id: conversationId,\n })) as Json;\n if (conversationState && !merged.scopes_queried.includes('conversation')) {\n merged.scopes_queried.unshift('conversation');\n }\n } catch {\n // Non-fatal in Python too: the merged items are still worth returning.\n }\n }\n\n merged.formatted_context = formatForPrompt(merged, {\n includeScope: includeScopeLabels,\n includeConversationContext: withConversationContext,\n });\n return merged;\n }\n\n /**\n * An LLM-ready tool definition that fetches Synap context.\n *\n * Mirrors Python's `as_tool()`. The scope identifiers are closed over, so\n * the model cannot choose whose memory to read.\n */\n as_tool(options: AsToolOptions = {}): ToolDefinition {\n return buildTool(this as never, options, (message) => this.#warn(message));\n }\n\n /**\n * A read-only diagnostic view of the in-process anticipation cache.\n *\n * Mirrors Python's `anticipation_cache_snapshot()`. Returns the same\n * snake_case shape, since this output gets logged and compared across SDKs.\n */\n anticipation_cache_snapshot(): AnticipationCacheSnapshot {\n return this.#anticipationCache.snapshot();\n }\n\n /**\n * Report a locally served fetch back to the server.\n *\n * It rides the Listen stream. While the stream is reconnecting the stream\n * client holds it and sends it on reconnect: a hit never reaches a fetch\n * route, so this report is the only count of it. Never throws, because a\n * telemetry failure must not fail a retrieval that already succeeded.\n */\n #emitContextUsed(\n options: Record<string, unknown>,\n scope: string,\n served: { servedItemIds: string[]; bundleId: string },\n ): void {\n try {\n this.instance._internal.sendContextUsed({\n bundle_id: served.bundleId,\n conversation_id: String(options['conversation_id'] ?? options['conversationId'] ?? ''),\n user_id: String(options['user_id'] ?? options['userId'] ?? ''),\n customer_id: String(options['customer_id'] ?? options['customerId'] ?? ''),\n served_item_ids: served.servedItemIds,\n scope,\n source_bundle_ids: served.bundleId ? [served.bundleId] : [],\n timestamp_ms: Date.now(),\n // How many distinct search queries the fetch carried. A hit never\n // reaches the fetch route, so this event is how the server learns it\n // happened and what it is charged by. The count only: this event must\n // not carry the caller's words.\n query_count: distinctQueryCount(options['search_query'] ?? options['searchQuery']),\n });\n } catch {\n // Non-fatal by design.\n }\n }\n\n /**\n * Report what was actually composed for this turn.\n *\n * Fires whether the fetch was served from the cache or the network, because\n * the audit needs to distinguish them. Like the other stream events it is\n * fire-and-forget and only goes anywhere while listening.\n */\n #emitContextAssembled(\n scope: string,\n options: Record<string, unknown>,\n response: RawContext,\n startedAt: number,\n ): void {\n try {\n if (!this.instance.is_listening) return;\n this.instance._internal.sendContextAssembled({\n ...buildAssembledEvent({\n correlationId: newCorrelationId(),\n response,\n conversationId: (options['conversation_id'] ?? options['conversationId']) as string | undefined,\n userId: (options['user_id'] ?? options['userId']) as string | undefined,\n customerId: (options['customer_id'] ?? options['customerId']) as string | undefined,\n startedAt,\n sdkVersion: SDK_VERSION,\n }),\n scope,\n });\n } catch {\n // Non-fatal by design.\n }\n }\n\n /**\n * Fold a cached user summary in, every Nth turn.\n *\n * Only when the caller supplied a user_id. Without one the summary lookup\n * cannot be scoped, and an unscoped lookup is how user A's summary ends up in\n * user B's response.\n */\n #injectUserSummary(\n response: RawContext,\n conversationId: string | undefined,\n userId: string | undefined,\n scopeRung: string | null,\n ): void {\n this.#turns.increment(conversationId);\n if (userId === undefined || userId === '') return;\n if (!this.#turns.shouldInject(conversationId)) return;\n // The rung, for the same reason the user id is here: a summary prefetched\n // for one rung is not this caller's summary if they are standing at\n // another, and splicing it in is the same failure one level down.\n const summary = this.#anticipationCache.lookupUserSummary(userId, scopeRung);\n if (summary === null) return;\n mergeUserSummary(response, summary as Json);\n }\n\n /**\n * Whether the SDK is authoritative for short-term context.\n *\n * Resolution order matches Python's `_is_st_authoritative`:\n * `SYNAP_SDK_ST_AUTHORITATIVE` first, as an explicit override in either\n * direction, then the option. Off by default. Being enabled does not mean\n * the local store is used: that also takes an entry that holds the whole\n * conversation, see `isComplete`.\n */\n #isStAuthoritative(): boolean {\n const raw = (getEnv('SYNAP_SDK_ST_AUTHORITATIVE') ?? '').trim().toLowerCase();\n if (['0', 'false', 'no', 'off'].includes(raw)) return false;\n if (['1', 'true', 'yes', 'on'].includes(raw)) return true;\n return this.#stAuthoritative === true;\n }\n\n /**\n * Render `get_context_for_prompt` from the local store, or null to fall\n * through to the network.\n *\n * The store answers only when it holds the whole conversation: the server\n * has confirmed a count the entry accounts for. An entry that is merely\n * present is not enough. After a restart or an eviction it holds one turn,\n * and rendering that as the conversation drops everything said before it.\n */\n /**\n * `response` with the earlier turns that best match `query` (by default the\n * latest user message) appended, when a compaction exists. The search runs\n * here, over the turn archive. Python: `_with_history_excerpts`.\n */\n async #withHistoryExcerpts(conversationId: string, response: Json, query: string | undefined): Promise<Json> {\n const r = (response ?? {}) as Record<string, unknown>;\n const store = this.#turnStore;\n const recent = (Array.isArray(r['recent_messages']) ? r['recent_messages'] : []) as Array<Record<string, unknown>>;\n store.addMany(\n conversationId,\n recent.map((m) => ({\n role: String(m['role'] ?? 'user'),\n content: String(m['content'] ?? ''),\n timestamp: String(m['timestamp'] ?? ''),\n message_id: typeof m['message_id'] === 'string' ? m['message_id'] : null,\n })),\n );\n const entry = this.#shortTerm.get(conversationId);\n const total = Math.max(Number(r['total_message_count'] ?? 0) || 0, Number(entry?.serverMessageCount ?? 0) || 0);\n this.#maybeBackfillTurns(conversationId, total);\n if (!r['context_block']) return response;\n const turns = store.turns(conversationId);\n let q = query;\n if (!q) {\n const latest = [...recent].reverse().find((m) => m['role'] === 'user');\n q = latest ? String(latest['content'] ?? '') : ([...turns].reverse().find((t) => t.role === 'user')?.content ?? '');\n }\n if (!q) return response;\n const exclude = new Set<string>();\n for (const m of recent) {\n if (typeof m['message_id'] === 'string' && m['message_id']) exclude.add(m['message_id']);\n exclude.add(String(m['content'] ?? ''));\n }\n this.#startLocalModel();\n const hits = await searchTurns(turns, q, { exclude, encoder: this.#localEncoder, store });\n if (hits.length === 0) return response;\n const block = renderExcerpts(hits, turns.length ? turns[turns.length - 1]!.timestamp : '');\n return {\n ...r,\n history_excerpts: hits.map((h) => ({ position: h.position, role: h.role, text: h.text })),\n history_block: block,\n formatted_context: (String(r['formatted_context'] ?? '').trimEnd() + '\\n\\n' + block).trim(),\n } as Json;\n }\n\n /**\n * Keep what a tool returned in this process's turn archive, so history search\n * can find it after a compaction. Never sent anywhere: the server's\n * conversation holds what people said, and a compaction is made from that.\n * `instance.record_tool_result` calls this too. Python: `archive_tool_result`.\n */\n archive_tool_result(\n conversationId: string,\n result: unknown,\n options: { tool_name?: string | null; toolName?: string | null; timestamp?: string } = {},\n ): void {\n if (!conversationId || result === null || result === undefined) return;\n try {\n this.#turnStore.add(conversationId, 'tool', toolResultText(result, options.tool_name ?? options.toolName),\n options.timestamp ?? new Date().toISOString());\n } catch {\n // The archive is a convenience: never fail the agent's call.\n }\n }\n\n static readonly BACKFILL_COOLDOWN_MS = 60_000;\n static readonly BACKFILL_PAGE = 500;\n\n /** Fetch, in the background, turns the server holds and the archive does not. */\n /**\n * Load the local embedding model in the background, once. Searches and\n * lookups before it is ready match by words. Python: `_start_history_encoder`.\n */\n #startLocalModel(): void {\n if (this.#localModelStarted) return;\n this.#localModelStarted = true;\n if (localModelOff()) return;\n const name = this.#localModelName === 'auto' ? SEMANTIC_MATCH.model : this.#localModelName;\n if (!name) return;\n const callerEncoder = this.#localEncoder;\n void import('./cache/onnx-encoder.js')\n .then(({ canRunLocalModel, loadOnnxEncoder }) => (canRunLocalModel() ? loadOnnxEncoder(name) : null))\n .then((encoder) => {\n if (encoder === null) return;\n // A caller's own encoder keeps history search.\n if (callerEncoder === null) this.#localEncoder = encoder;\n // The anticipation thresholds hold for one model only.\n if (encoder.model === SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(encoder);\n })\n .catch(() => {\n /* words only, as without a model */\n });\n }\n\n #maybeBackfillTurns(conversationId: string, total: number): void {\n if (total <= this.#turnStore.count(conversationId)) return;\n const now = Date.now();\n if (now < (this.#backfillAfter.get(conversationId) ?? 0)) return;\n this.#backfillAfter.set(conversationId, now + SynapClient.BACKFILL_COOLDOWN_MS);\n void this.#backfillTurns(conversationId, total);\n }\n\n async #backfillTurns(conversationId: string, total: number): Promise<void> {\n try {\n let start = 1;\n while (start <= total) {\n const result = await this.#transport.request<Json>('conversation_turns', {\n pathParams: { conversation_id: conversationId },\n query: { start, limit: SynapClient.BACKFILL_PAGE },\n });\n const page = (((result ?? {}) as Record<string, unknown>)['turns'] ?? []) as TurnInput[];\n this.#turnStore.addMany(conversationId, page);\n if (page.length < SynapClient.BACKFILL_PAGE) break;\n start += SynapClient.BACKFILL_PAGE;\n }\n } catch (error) {\n this.#warn(`Turn backfill for ${conversationId} failed: ${String(error)}`);\n }\n }\n\n #localPrompt(conversationId: string, style: string): Json | null {\n if (!this.#isStAuthoritative()) return null;\n const entry = this.#shortTerm.get(conversationId);\n if (entry === null || !isComplete(entry)) return null;\n if (entry.compactionId === null && entry.recentTurns.length === 0) return null;\n return renderForPrompt(entry, style) as unknown as Json;\n }\n\n /** Same, for `get_compacted`. Requires an actual compaction, not just turns. */\n #localCompacted(conversationId: string, format: string): Json | null {\n if (!this.#isStAuthoritative()) return null;\n const entry = this.#shortTerm.get(conversationId);\n if (entry === null || entry.compactionId === null || !isComplete(entry)) return null;\n return renderCompacted(entry, format);\n }\n\n /**\n * Bring the local store back in step from the server's answer.\n *\n * Only for a conversation this process writes to. The server's answer lists\n * every message its summary does not cover, which is exactly what the entry\n * was missing.\n */\n #reseedShortTerm(conversationId: string, response: Json): void {\n if (!this.#isStAuthoritative()) return;\n const entry = this.#shortTerm.get(conversationId);\n if (entry === null || !entry.participant) return;\n const r = (response ?? {}) as Record<string, unknown>;\n const recent = Array.isArray(r['recent_messages']) ? r['recent_messages'] : [];\n this.#shortTerm.reseed(conversationId, {\n compactionId: typeof r['compaction_id'] === 'string' ? r['compaction_id'] : null,\n recentMessages: recent as ShortTermTurn[],\n compactedMessageCount: Number(r['compacted_message_count'] ?? 0) || 0,\n totalMessageCount: Number(r['total_message_count'] ?? 0) || 0,\n });\n }\n\n /** Every diagnostic the SDK emits passes through here. */\n #warn(message: string): void {\n if (this.#logger !== undefined) {\n this.#logger('warn', message);\n return;\n }\n // eslint-disable-next-line no-console\n console.warn(`[synap] ${message}`);\n }\n\n /** Release timers and connections. Safe to call more than once. */\n async shutdown(): Promise<void> {\n if (this.#closed) return;\n this.#closed = true;\n this.#shortTerm.clear();\n this.#turns.clear();\n // Release every registry slot pointing here, so a later construction\n // builds a fresh client rather than adopting this shut-down one. Only\n // slots still owned by this client are dropped.\n for (const key of this.#registryKeys) registry.unregisterIfOwner(key, this);\n\n // Stop the stream first: it holds a socket and a heartbeat timer, and\n // leaving either alive is what keeps a finished process from exiting.\n await this.instance.stop_listening();\n this.#compactionSubscribers.removeAll();\n this.#transport.close();\n this.#anticipationCache.clear();\n }\n}\n\nfunction pick(o: Record<string, unknown>, snake: string, camel: string): unknown {\n const a = o[snake];\n return a !== undefined ? a : o[camel];\n}\n\n/** Explicit option wins, then the environment, then the SDK default. */\nfunction resolveBaseUrl(options: SynapClientOptions): string | undefined {\n const explicit = options.baseUrl ?? options.api_base_url;\n if (explicit !== undefined) return explicit;\n const fromEnv = getEnv('SYNAP_BASE_URL')?.trim();\n return fromEnv !== undefined && fromEnv !== '' ? fromEnv : undefined;\n}\n\nfunction resolveCredentials(options: SynapClientOptions, localMode: boolean): Credentials {\n // Read at call time, not module load, so a late process.env mutation works.\n // `||`, not `??`: an empty apiKey falls back to the environment, as\n // Python's `api_key or os.environ.get(...)` does.\n const apiKey = options.apiKey || getEnv('SYNAP_API_KEY');\n // An AuthenticationError, as Python raises it (auth/manager.py), so one\n // `catch` handles \"no usable key\" in both SDKs. Until 0.5.13 this was an\n // InvalidInputError.\n if (!apiKey && !localMode) {\n throw new AuthenticationError(\n 'No Synap API key found. Set SYNAP_API_KEY in your environment, or pass ' +\n 'apiKey to the SynapClient constructor.',\n );\n }\n return {\n // In local mode the credential is the optional token, '' when there is none.\n apiKey: apiKey || localToken(),\n clientId: options.clientId ?? getEnv('SYNAP_CLIENT_ID') ?? '',\n instanceId: options.instanceId ?? getEnv('SYNAP_INSTANCE_ID') ?? '',\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/Users/scaler/wt_sl_wave2/synap/sdk/js/dist/index.cjs","../src/local-mode.ts","../src/transport/endpoints.ts","../src/transport/retry.ts","../src/transport/keepalive.ts","../src/scoping.ts","../src/scope-ladder.ts","../src/transport/http.ts","../src/context/ranked.ts","../src/context/no-query.ts","../src/context/fetch.ts","../src/context/normalize.ts","../src/context/flatten.ts","../src/memories/parts.ts","../src/memories/interface.ts","../src/util/validators.ts","../src/agent-model.ts","../src/conversation/interface.ts","../src/data/interface.ts","../src/user/interface.ts","../src/credits/interface.ts","../src/maca/interface.ts","../src/cache/interface.ts","../src/instance/interface.ts","../src/version.ts","../src/registry.ts","../src/cache/short-term-store.ts","../src/cache/turn-store.ts","../src/cache/history-search.ts","../src/context/overlay.ts","../src/context/local-prompt.ts","../src/context/user-summary.ts","../src/context/anticipated.ts","../src/context/assembled.ts","../src/context/unified.ts","../src/tool/as-tool.ts","../src/client.ts"],"names":["o","MEMORY_TYPES","n","sleep","either","iso","fetchUrl","checkCustomerId","tokenize","ranked","before","pick","normalise","COLLECTIONS","itemId"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF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O,EAAA;AACL,IAAA;AACA,IAAA;AACE,MAAA;AACA,sBAAA;AACF,IAAA;AACF,EAAA;AACF;AAaS;AACH,EAAA;AACG,EAAA;AACL,IAAA;AACE,sBAAA;AACA,MAAA;AACG,IAAA;AACL,IAAA;AACE,MAAA;AACA,MAAA;AACF,IAAA;AACA,oBAAA;AACD,EAAA;AACH;AP4GS;AACA;AQzgCI;AAIA;AACX,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACF;AAMa;AAOG;AACR,EAAA;AACF,EAAA;AACA,EAAA;AACG,EAAA;AACT;AAMgB;AACV,EAAA;AACE,EAAA;AACF,EAAA;AACE,EAAA;AACF,EAAA;AACG,EAAA;AACT;AAGS;AACD,EAAA;AACA,EAAA;AACF,EAAA;AACA,EAAA;AACA,EAAA;AACG,EAAA;AACT;AAUgB;AACR,EAAA;AAGN,EAAA;AACE,IAAA;AACK,IAAA;AACL,IAAA;AACE,MAAA;AACA,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACD,MAAA;AACH,IAAA;AACF,EAAA;AACK,EAAA;AACE,EAAA;AACT;AAWgB;AACR,EAAA;AACF,EAAA;AACE,EAAA;AAGA,EAAA;AACD,IAAA;AACE,IAAA;AACL,IAAA;AACA,EAAA;AACI,EAAA;AACN,EAAA;AACM,IAAA;AACN,EAAA;AACc,EAAA;AACP,EAAA;AACT;AAGM;AACG,EAAA;AACP,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACC,EAAA;AACH;AAGgB;AACP,EAAA;AACT;AAGgB;AACP,EAAA;AACT;ARy9BS;AACA;AS3lCHC;AAEA;AAIU;AACV,EAAA;AACC,EAAA;AACE,EAAA;AACT;AAGgB;AACR,EAAA;AACA,EAAA;AAGC,EAAA;AACF,IAAA;AACH,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACF,IAAA;AACF,EAAA;AACF;AAOgB;AACV,EAAA;AACA,EAAA;AACE,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T;AAES;AAID,EAAA;AACF,EAAA;AACA,EAAA;AACE,IAAA;AACA,IAAA;AACF,MAAA;AACF,IAAA;AACE,MAAA;AACF,IAAA;AACA,IAAA;AACF,EAAA;AAGM,EAAA;AACC,EAAA;AACT;AAQM;AACC,EAAA;AACA,EAAA;AACC,EAAA;AACD,EAAA;AACC,EAAA;AACD,EAAA;AACA,EAAA;AACA,EAAA;AACC,EAAA;AACD,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACC,EAAA;AACA,EAAA;AACD,EAAA;AACC,EAAA;AACA,EAAA;AACA,EAAA;AACD,EAAA;AACA,EAAA;AACA,EAAA;AACP;AAEgB;AACR,EAAA;AAEF,EAAA;AACE,EAAA;AACC,EAAA;AACT;AAES;AACD,EAAA;AACF,EAAA;AACE,EAAA;AACC,EAAA;AACT;AAoBgB;AACV,EAAA;AACA,EAAA;AACC,EAAA;AACD,EAAA;AAGF,IAAA;AACF,EAAA;AACM,EAAA;AACA,IAAA;AACA,IAAA;AACJ,IAAA;AACK,MAAA;AACL,IAAA;AACD,EAAA;AACI,EAAA;AACH,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAES;AACH,EAAA;AACA,EAAA;AACA,EAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAgBA;AACQ,EAAA;AACA,EAAA;AACF,EAAA;AAEA,EAAA;AACA,EAAA;AACF,IAAA;AACF,EAAA;AAGE,IAAA;AACI,IAAA;AACF,MAAA;AACF,IAAA;AACE,MAAA;AACE,QAAA;AACA,QAAA;AACF,MAAA;AACF,IAAA;AACK,EAAA;AACL,IAAA;AACA,IAAA;AAGI,IAAA;AACN,EAAA;AACI,EAAA;AACF,IAAA;AACK,MAAA;AACL,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAEM;AAEG;AACA,EAAA;AACT;AAEA;AACM,EAAA;AACA,EAAA;AACA,EAAA;AACF,IAAA;AACA,IAAA;AACF,EAAA;AACI,EAAA;AACF,IAAA;AACF,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A;AACO,EAAA;AACT;AAEM;AACA;AAEG;AACD,EAAA;AACN,EAAA;AACE,IAAA;AACA,IAAA;AACI,IAAA;AACN,EAAA;AACO,EAAA;AACT;AAES;AACH,EAAA;AACA,EAAA;AACA,EAAA;AACEN,EAAAA;AACN,EAAA;AACE,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAES;AACA,EAAA;AACT;AAES;AACH,EAAA;AACA,EAAA;AACE,EAAA;AACJ,IAAA;AACA,IAAA;AACIA,IAAAA;AACJ,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACI,EAAA;AACJ,EAAA;AACI,EAAA;AACA,EAAA;AACA,EAAA;AACJ,EAAA;AACM,IAAA;AACJ,IAAA;AACE,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACF,IAAA;AACK,IAAA;AACP,EAAA;AACI,EAAA;AACA,EAAA;AACJ,EAAA;AACF;AAMM;AACA;AACA;AAOU;AACR,EAAA;AACF,EAAA;AACE,EAAA;AACA,EAAA;AACF,EAAA;AACG,EAAA;AACL,IAAA;AACI,IAAA;AACF,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACF,IAAA;AACI,IAAA;AACF,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACE,QAAA;AACA,QAAA;AACF,MAAA;AACA,MAAA;AACA,MAAA;AACF,IAAA;AACI,IAAA;AACJ,IAAA;AACI,IAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AACA,IAAA;AACI,IAAA;AACF,MAAA;AACF,IAAA;AACE,MAAA;AACA,MAAA;AACF,IAAA;AACI,IAAA;AACN,EAAA;AACM,EAAA;AACC,EAAA;AACT;AAES;AACD,EAAA;AACF,EAAA;AACA,EAAA;AACJ,EAAA;AACE,IAAA;AACK,IAAA;AACL,IAAA;AACI,IAAA;AACF,MAAA;AACA,MAAA;AACA,MAAA;AACF,IAAA;AAC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A;AACA,IAAA;AACA,IAAA;AACK,IAAA;AACP,EAAA;AACM,EAAA;AACA,EAAA;AACA,EAAA;AACJ,IAAA;AACK,IAAA;AACL,IAAA;AAKA,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACM,EAAA;AACN,EAAA;AACE,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACD,IAAA;AACH,EAAA;AAEMQ,EAAAA;AACA,EAAA;AACN,EAAA;AACE,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACE,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACD,MAAA;AACH,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAEA;AAQQ,EAAA;AACA,EAAA;AACF,EAAA;AACF,IAAA;AACK,IAAA;AACL,IAAA;AACE,MAAA;AACA,MAAA;AACE,QAAA;AACA,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACM,EAAA;AACF,EAAA;AACF,IAAA;AACA,IAAA;AACA,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACD,IAAA;AACG,IAAA;AACN,EAAA;AACM,EAAA;AACC,EAAA;AAIT;AAMgB;AACV,EAAA;AACE,EAAA;AACF,EAAA;AACG,EAAA;AACT;AAGgB;AACV,EAAA;AACE,EAAA;AACN,EAAA;AACM,IAAA;AACA,IAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AACA,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAEM;AAGG;AACD,EAAA;AACD,EAAA;AACC,EAAA;AACC,EAAA;AACT;AAGS;AACD,EAAA;AACA,EAAA;AACF,EAAA;AACE,EAAA;AACN,EAAA;AACM,IAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;A5BgjHS;AACA;A6Br/HH;AACA;AASU;AAGR,EAAA;A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AACA,IAAA;AACP,EAAA;AAEM,EAAA;AACA,IAAA;AACF,MAAA;AACA,MAAA;AACE,QAAA;AAAyE,UAAA;AACzB,UAAA;AAE/C,QAAA;AACD,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACF,IAAA;AACE,MAAA;AACF,IAAA;AACF,EAAA;AAEA,EAAA;AACO,IAAA;AACL,IAAA;AACI,IAAA;AACA,IAAA;AACJ,IAAA;AACF,EAAA;AAAA;AAGA,EAAA;AACO,IAAA;AACL,IAAA;AACI,IAAA;AACJ,IAAA;AACF,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,EAAA;AACO,IAAA;AACL,IAAA;AACI,IAAA;AACJ,IAAA;AACA,IAAA;AACK,IAAA;AACH,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACD,IAAA;AACH,EAAA;AAAA;AAGM,EAAA;AACA,IAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AAEA,IAAA;AACF,EAAA;AAAA;AAGM,EAAA;AACA,IAAA;AACC,IAAA;AACA,IAAA;AACA,IAAA;AAIL,IAAA;AAIA,IAAA;AACK,IAAA;AACA,IAAA;AACA,IAAA;AACP,EAAA;AACF;AAESA;AACD,EAAA;AACC,EAAA;AACT;AAGS;AACD,EAAA;AACF,EAAA;AACE,EAAA;AACC,EAAA;AACT;AAES;AAID,EAAA;AAID,EAAA;AACH,IAAA;AACE,MAAA;AAEF,IAAA;AACF,EAAA;AACO,EAAA;AAAA;AAEL,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACF;ApCs1IS;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/scaler/wt_sl_wave2/synap/sdk/js/dist/index.cjs","sourcesContent":[null,"/**\n * Local mode: talking to the open-source Synap server, which has no auth.\n *\n * It is on when no API key is given (option or SYNAP_API_KEY) and a base URL\n * is configured. A key always wins, so Cloud callers never see a difference.\n */\nimport { getEnv } from './util/env.js';\n\nexport function isLocalMode(apiKey: string | undefined, baseUrl: string | undefined): boolean {\n if (apiKey || getEnv('SYNAP_API_KEY')) return false;\n return baseUrl !== undefined && baseUrl.trim() !== '';\n}\n\n/**\n * The optional shared token the open-source server may require. Read from the\n * environment only. Empty means send no Authorization header.\n */\nexport function localToken(): string {\n return getEnv('SYNAP_API_TOKEN')?.trim() ?? '';\n}\n","/**\n * AUTOGENERATED FROM synap/sdk/CONTRACT/endpoints.yaml -- DO NOT EDIT.\n * Regenerate with synap/sdk/scripts/sync-contract.sh.\n *\n * The /api/v1 vs /v1 prefix split is intentional and load-bearing. See the\n * contract file: normalising it 404s every affected call in production.\n */\n\nexport interface EndpointSpec {\n readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';\n readonly path: string;\n /**\n * Whether a retry after an ambiguous failure is safe.\n *\n * False here means a retry can double-ingest and therefore double-bill.\n * See defect D / gotcha G-L in the migration plan.\n */\n readonly idempotent: boolean;\n}\n\nexport const ENDPOINTS = {\n whoami: { method: \"GET\", path: \"/api/v1/auth/whoami\", idempotent: true },\n memories_create: { method: \"POST\", path: \"/api/v1/memories/create\", idempotent: false },\n memories_batch: { method: \"POST\", path: \"/api/v1/memories/batch\", idempotent: false },\n memories_upload: { method: \"POST\", path: \"/api/v1/memories/upload\", idempotent: false },\n memories_create_multipart: { method: \"POST\", path: \"/api/v1/memories/create-multipart\", idempotent: false },\n memories_status: { method: \"GET\", path: \"/api/v1/memories/status/{ingestion_id}\", idempotent: true },\n memories_get: { method: \"GET\", path: \"/api/v1/memories/{memory_id}\", idempotent: true },\n memories_update: { method: \"PATCH\", path: \"/api/v1/memories/{memory_id}\", idempotent: false },\n memories_delete: { method: \"DELETE\", path: \"/api/v1/memories/{memory_id}\", idempotent: true },\n memories_forget: { method: \"POST\", path: \"/api/v1/memories/forget\", idempotent: false },\n data_delete: { method: \"POST\", path: \"/v1/data/delete\", idempotent: true },\n data_delete_status: { method: \"GET\", path: \"/v1/data/delete/{deletion_id}\", idempotent: true },\n context_fetch_user: { method: \"POST\", path: \"/v1/context/user/fetch\", idempotent: true },\n context_fetch_customer: { method: \"POST\", path: \"/v1/context/customer/fetch\", idempotent: true },\n context_fetch_client: { method: \"POST\", path: \"/v1/context/client/fetch\", idempotent: true },\n context_fetch_conversation: { method: \"POST\", path: \"/v1/context/conversation/fetch\", idempotent: true },\n context_for_prompt: { method: \"GET\", path: \"/v1/conversations/{conversation_id}/context-for-prompt\", idempotent: true },\n conversation_turns: { method: \"GET\", path: \"/v1/conversations/{conversation_id}/messages\", idempotent: true },\n conversations_ingest: { method: \"POST\", path: \"/v1/conversations/ingest\", idempotent: false },\n conversations_messages: { method: \"POST\", path: \"/v1/conversations/messages\", idempotent: false },\n conversations_messages_batch: { method: \"POST\", path: \"/v1/conversations/messages/batch\", idempotent: false },\n conversations_compact: { method: \"POST\", path: \"/v1/conversations/compact\", idempotent: false },\n conversations_compacted: { method: \"GET\", path: \"/v1/conversations/{conversation_id}/compacted\", idempotent: true },\n conversations_compaction_status: { method: \"GET\", path: \"/v1/conversations/{conversation_id}/compaction/status\", idempotent: true },\n user_profile: { method: \"GET\", path: \"/v1/users/{user_id}/profile\", idempotent: true },\n credits_balance: { method: \"GET\", path: \"/v1/credits/balance\", idempotent: true },\n credits_ledger: { method: \"GET\", path: \"/v1/credits/ledger\", idempotent: true },\n credits_estimate: { method: \"POST\", path: \"/v1/credits/estimate\", idempotent: true },\n credits_redeem: { method: \"POST\", path: \"/v1/credits/redeem\", idempotent: false },\n telemetry_batch: { method: \"POST\", path: \"/v1/telemetry/batch\", idempotent: false },\n maca_generate: { method: \"POST\", path: \"/v1/maca/generate\", idempotent: false },\n maca_job: { method: \"GET\", path: \"/v1/maca/jobs/{job_id}\", idempotent: true },\n} as const satisfies Record<string, EndpointSpec>;\n\nexport type EndpointName = keyof typeof ENDPOINTS;\n\n/** Substitute `{placeholder}` segments. Values are URL-encoded.\n *\n * Encoding matters: an unencoded id containing `/` or `?` silently\n * retargets the request at a different route.\n */\nexport function resolvePath(\n name: EndpointName,\n params: Readonly<Record<string, string | number>> = {},\n): string {\n return ENDPOINTS[name].path.replace(/\\{(\\w+)\\}/g, (_m, key: string) => {\n const value = params[key];\n if (value === undefined || value === null || value === '') {\n throw new Error(\n `Endpoint ${name} requires path parameter '${key}'.`,\n );\n }\n return encodeURIComponent(String(value));\n });\n}\n","/**\n * Retry policy, mirroring `maximem_synap/resilience/retry.py` plus the\n * idempotency gate added there for defect D.\n *\n * ## Why idempotency is part of the retry decision\n *\n * The obvious retry rule is \"retry transient errors\". That rule double-bills.\n *\n * `POST /api/v1/memories/create` is metered ingestion. If the request reached\n * the server, was processed, and the *response* was lost, a retry ingests the\n * same content twice and bills for it twice. The client cannot tell that case\n * apart from \"the request never arrived\" by looking at the error type alone.\n *\n * So retries are gated on two independent questions:\n *\n * 1. Is the error transient? (worth retrying at all)\n * 2. Is the outcome *knowable*? (safe to retry a non-idempotent call)\n *\n * A connection error means the request provably never reached the application,\n * so the outcome is known: nothing happened. A read timeout means the request\n * may well have been processed. That is the ambiguous case, and for a\n * non-idempotent method it is where we stop.\n *\n * The residual window -- server accepted the request, began processing, then\n * died before responding -- cannot be closed from the client at all. Closing it\n * requires a server-honoured idempotency key on the ingest route. Until that\n * exists, this policy narrows the window rather than eliminating it.\n */\n\nimport { RateLimitError, SynapError, isSynapError } from '../errors.js';\n\n/** HTTP methods that are idempotent by specification. */\nconst IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\n 'GET',\n 'HEAD',\n 'OPTIONS',\n 'PUT',\n 'DELETE',\n]);\n\nexport interface RetryPolicy {\n maxAttempts: number;\n /** Base delay in seconds. */\n backoffBase: number;\n /** Delay cap in seconds. */\n backoffMax: number;\n /** Randomise the delay to avoid a thundering herd. */\n backoffJitter: boolean;\n}\n\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\n maxAttempts: 3,\n backoffBase: 1.0,\n backoffMax: 10.0,\n backoffJitter: true,\n};\n\nexport interface RetryDecisionInput {\n error: unknown;\n /** 1-based. */\n attempt: number;\n policy: RetryPolicy;\n method: string;\n /**\n * True when the request may have been processed by the server despite the\n * error. Read timeouts and mid-flight disconnects are ambiguous; connection\n * errors and definitive HTTP status responses are not.\n */\n outcomeUnknown: boolean;\n /** Overrides idempotency for a route, e.g. a read-only POST. */\n idempotent?: boolean;\n}\n\nexport interface RetryDecision {\n retry: boolean;\n /** Seconds to wait before the next attempt. */\n delaySeconds: number;\n reason: string;\n}\n\nexport function shouldRetry(input: RetryDecisionInput): RetryDecision {\n const { error, attempt, policy, method, outcomeUnknown } = input;\n\n if (attempt >= policy.maxAttempts) {\n return { retry: false, delaySeconds: 0, reason: 'max_attempts_exhausted' };\n }\n\n if (!isSynapError(error) || !(error as SynapError).transient) {\n return { retry: false, delaySeconds: 0, reason: 'not_transient' };\n }\n\n // The trial cap and an inactive subscription arrive as 429 but clear with a\n // plan change or a new cycle, never within a retry.\n if (error instanceof RateLimitError && error.reason) {\n return { retry: false, delaySeconds: 0, reason: 'credit_stop' };\n }\n\n const idempotent = input.idempotent ?? IDEMPOTENT_METHODS.has(method.toUpperCase());\n if (outcomeUnknown && !idempotent) {\n // The request may have been processed. For ingestion that means a retry\n // would store and bill twice. Surfacing the error is the cheaper mistake.\n return {\n retry: false,\n delaySeconds: 0,\n reason: 'non_idempotent_outcome_unknown',\n };\n }\n\n return {\n retry: true,\n delaySeconds: backoffDelay(error, attempt, policy),\n reason: 'transient_retryable',\n };\n}\n\n/** Exponential backoff, honouring Retry-After when the server sent one. */\nexport function backoffDelay(error: unknown, attempt: number, policy: RetryPolicy): number {\n if (error instanceof RateLimitError && error.retryAfterSeconds != null) {\n // The server told us when to come back. Guessing shorter just gets us\n // rejected again and burns quota.\n return Math.min(error.retryAfterSeconds, policy.backoffMax);\n }\n const exponential = policy.backoffBase * 2 ** (attempt - 1);\n const capped = Math.min(exponential, policy.backoffMax);\n if (!policy.backoffJitter) return capped;\n // Full jitter. Equal-jitter still synchronises a fleet after a shared outage.\n return Math.random() * capped;\n}\n\nexport const _IDEMPOTENT_METHODS = IDEMPOTENT_METHODS;\n","/**\n * Connection reuse for the HTTP transport.\n *\n * ## Why this file exists at all\n *\n * Node's global `fetch` keeps an idle socket for roughly 4 seconds. Our real\n * call pattern is one fetch per conversation turn, often minutes apart, so\n * essentially every call would pay a full connection setup. Through the CDN to\n * the origin that was measured at 600-950ms.\n *\n * The Python SDK already solved this: `keepalive_expiry=300s` plus a 240s\n * `/health` heartbeat that keeps the socket warm for as long as the client\n * lives. Porting the SDK without porting this would ship a \"native and faster\"\n * release that is measurably *slower* than the Python-subprocess wrapper it\n * replaces, on every call, from day one. That is gotcha G-A.\n *\n * ## Why it is optional and lazily loaded\n *\n * `undici` is Node-only. Edge runtimes and Workers have their own connection\n * pooling and no `dispatcher` option, so there the correct behavior is to use\n * global `fetch` unchanged. Importing undici eagerly would break those builds\n * at bundle time, so it is behind a lazy `import()` and every failure path\n * degrades to plain `fetch` rather than throwing.\n */\n\n/** Mirrors HTTPTransport.KEEPALIVE_EXPIRY_SECONDS in the Python SDK. */\nexport const KEEPALIVE_EXPIRY_MS = 300_000;\n/** Mirrors HTTPTransport.HEARTBEAT_INTERVAL_SECONDS. */\nexport const HEARTBEAT_INTERVAL_MS = 240_000;\nexport const MAX_CONNECTIONS = 20;\n\nexport interface KeepAliveOptions {\n keepAliveExpiryMs?: number;\n maxConnections?: number;\n}\n\n/** An undici Dispatcher, typed loosely so undici is not a hard type dependency. */\nexport type Dispatcher = object;\n\nlet cached: Dispatcher | null | undefined;\n\n/** True when we are on a runtime that can host an undici dispatcher. */\nexport function supportsDispatcher(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.versions?.node !== undefined &&\n // Edge builds of Next expose a partial `process` shim, but no real Node.\n typeof (globalThis as { EdgeRuntime?: unknown }).EdgeRuntime === 'undefined'\n );\n}\n\n/**\n * Build (once) a dispatcher with Python-equivalent keep-alive.\n *\n * Returns null on any runtime where that is not possible, in which case the\n * caller should simply omit the dispatcher.\n */\nexport async function getKeepAliveDispatcher(\n options: KeepAliveOptions = {},\n): Promise<Dispatcher | null> {\n if (cached !== undefined) return cached;\n if (!supportsDispatcher()) {\n cached = null;\n return cached;\n }\n try {\n // Bundlers must not try to follow this statically on Edge builds.\n const undici = (await import(/* @vite-ignore */ 'undici')) as {\n Agent: new (opts: Record<string, unknown>) => Dispatcher;\n };\n cached = new undici.Agent({\n keepAliveTimeout: options.keepAliveExpiryMs ?? KEEPALIVE_EXPIRY_MS,\n // undici will not honour a keepAliveTimeout above this ceiling.\n keepAliveMaxTimeout: options.keepAliveExpiryMs ?? KEEPALIVE_EXPIRY_MS,\n connections: options.maxConnections ?? MAX_CONNECTIONS,\n });\n } catch {\n // undici is an optionalDependency. Missing or unloadable is not fatal:\n // global fetch still works, just with a short-lived pool.\n cached = null;\n }\n return cached;\n}\n\n/** Test seam. */\nexport function _resetDispatcherCache(): void {\n cached = undefined;\n}\n\n/**\n * Keep an idle connection warm.\n *\n * The timer is `unref`'d. Without that the Node event loop stays alive for as\n * long as the interval exists and any CLI built on this SDK hangs forever\n * instead of exiting. Python has no equivalent symptom, so no parity test would\n * ever catch it: that is gotcha G-J.\n */\nexport class Heartbeat {\n private timer: ReturnType<typeof setInterval> | null = null;\n\n constructor(\n private readonly ping: () => void | Promise<void>,\n private readonly intervalMs: number = HEARTBEAT_INTERVAL_MS,\n ) {}\n\n start(): void {\n if (this.timer !== null) return;\n // 0 disables, matching the Python transport's convention.\n if (this.intervalMs <= 0) return;\n if (typeof setInterval !== 'function') return;\n\n this.timer = setInterval(() => {\n // A failed heartbeat is not an error the caller should ever see. The\n // next real request will surface a genuine connectivity problem.\n void Promise.resolve(this.ping()).catch(() => {});\n }, this.intervalMs);\n\n (this.timer as { unref?: () => void }).unref?.();\n }\n\n stop(): void {\n if (this.timer !== null) {\n clearInterval(this.timer);\n this.timer = null;\n }\n }\n\n get running(): boolean {\n return this.timer !== null;\n }\n}\n","/**\n * The B2C identifier contract, client side.\n *\n * B2C send user_id, and nothing else. customer_id is not accepted.\n * B2B customer_id is required.\n *\n * The server is authoritative and rejects independently. This exists so the\n * failure happens at the call site, with a message that says what to do,\n * instead of as a round trip that returns an empty result.\n *\n * That last part is the whole reason. Sending a customer_id on a B2C instance\n * used to produce no exception anywhere: the write was filed under the\n * customer, the read asked for the user, and both returned success. One client\n * ran 4,634 consecutive empty fetches across seven days without a single error\n * to look at. An SDK that stays quiet about a misuse it can see is not being\n * permissive, it is hiding the bug.\n */\nimport { CustomerIdNotAcceptedError } from './errors.js';\n\nexport const B2C_ISOLATION = 'equals_customer';\n\n/**\n * Throw if this call breaks the contract.\n *\n * `isolation` is what `GET /api/v1/auth/whoami` reported. **undefined means the\n * server did not tell us**, which is true of any deployment older than that\n * field, and it must mean \"do nothing\". Guessing B2C there would make this SDK\n * refuse a B2B client's mandatory field against every server not yet upgraded,\n * a far worse failure than the one it prevents.\n */\nexport function checkCustomerId(\n isolation: string | undefined,\n customerId: unknown,\n where: string,\n instanceId?: string,\n): void {\n if (customerId === undefined || customerId === null || customerId === '') return;\n if (isolation !== B2C_ISOLATION) return;\n throw new CustomerIdNotAcceptedError(where, String(customerId), instanceId);\n}\n","/**\n * The account's scope ladder, as the SDK sees it. Mirrors\n * `maximem_synap/scope_ladder.py`; if you change a rule here, change it there\n * in the same piece of work.\n *\n * A ladder is the ordered list of levels an account files memory under. The\n * default has two non-root levels, `customer` then `user` (B2C: `user` alone).\n * An account may add levels in between, for example `team`.\n *\n * This module turns \"values, outermost first\" into the arguments the SDK calls\n * take (`user_id`, `customer_id` and, on a deeper ladder, `scope_path` for\n * reads or `scope` for memories), and refuses before any network call when the\n * values cannot be addressed.\n *\n * The rules, each read from the server (`synap/cloud/shared/scope_ladder.py`\n * `_normalise`, `synap/cloud/shared/scope.py` `resolve_identity`):\n *\n * - A path never names the root level, must be contiguous from the first\n * level, and a shorter path (a prefix) means that level.\n * - The server reads the path keys `customer` and `user` over the flat ids,\n * so ids are always sent as well.\n * - A path is honoured only when nested scoping is on for the instance AND the\n * account's ladder is ratified; otherwise the server refuses it. So on a\n * default ladder this module never produces a path.\n * - B2C (`user_context_isolation == \"equals_customer\"`): `resolve_identity`\n * collapses customer and user onto the user's id, and `customer_id` is\n * refused by the SDK. The tenant level of a path therefore carries the\n * identity's value, and only `user_id` is sent.\n */\n\nimport { ScopeLadderError } from './errors.js';\n\nexport const ROLE_TENANT = 'tenant_of_record';\nexport const ROLE_IDENTITY = 'identity';\n\n/** How long a ladder is trusted before whoami is read again. As the server's cache. */\nexport const LADDER_TTL_MS = 300_000;\n/** After a failed re-read, how long to keep serving the last known ladder. */\nexport const LADDER_RETRY_BACKOFF_MS = 60_000;\n\n/**\n * Minimum time between re-reads that an invalidation triggers. A caller whose\n * every request is refused would otherwise read whoami once per request.\n */\nexport const LADDER_INVALIDATION_MIN_INTERVAL_MS = 5_000;\n\nexport interface ScopeLevel {\n readonly key: string;\n readonly label: string;\n readonly position: number;\n readonly role: string | null;\n readonly required: boolean;\n}\n\n/** Where a call reads or writes: ids, plus a path on a deeper ladder. `scope_path` is null on a default ladder. */\nexport class ScopeAddress {\n readonly user_id: string | null;\n readonly customer_id: string | null;\n readonly scope_path: Readonly<Record<string, string>> | null;\n\n constructor(init: {\n user_id?: string | null;\n customer_id?: string | null;\n scope_path?: Record<string, string> | null;\n } = {}) {\n this.user_id = init.user_id ?? null;\n this.customer_id = init.customer_id ?? null;\n this.scope_path = init.scope_path ?? null;\n }\n\n /**\n * Options for reads: `fetch`, `send_message`, `record_message`,\n * `user.context.fetch`, `conversation.context.fetch` and\n * `client.context.fetch`. The path is `scope_path`.\n *\n * Not for `customer.context.fetch`: that route refuses a path that names the\n * identity rung (HTTP 400, it reads shared material only) and takes no\n * `user_id`. Call `client.fetch(addr.read_kwargs())`, which sends the\n * customer route the path cut above the identity rung.\n */\n read_kwargs(): { user_id?: string; customer_id?: string; scope_path?: Record<string, string> } {\n const out: { user_id?: string; customer_id?: string; scope_path?: Record<string, string> } = {};\n if (this.user_id) out.user_id = this.user_id;\n if (this.customer_id) out.customer_id = this.customer_id;\n if (this.scope_path && Object.keys(this.scope_path).length > 0) {\n out.scope_path = { ...this.scope_path };\n }\n return out;\n }\n\n /** Options for `memories.create` / `create_from_file` / `forget`: the path is `scope`. */\n write_kwargs(): { user_id?: string; customer_id?: string; scope?: Record<string, string> } {\n const out: { user_id?: string; customer_id?: string; scope?: Record<string, string> } = {};\n if (this.user_id) out.user_id = this.user_id;\n if (this.customer_id) out.customer_id = this.customer_id;\n if (this.scope_path && Object.keys(this.scope_path).length > 0) {\n out.scope = { ...this.scope_path };\n }\n return out;\n }\n}\n\n/** The reserved key of the identity level, used when the ladder is not known. */\nexport const RESERVED_IDENTITY_KEY = 'user';\n\n/**\n * `scopePath` cut above the identity rung, or `undefined` when nothing is left.\n * Python: `path_above_identity`.\n *\n * `POST /v1/context/customer/fetch` reads shared material only and refuses\n * (HTTP 400) any path that resolves to a rung holding the `identity` role\n * (`customer_scope_reaches_an_identity`). The identity level is found by ROLE\n * on `ladder` and every level at or below it is removed; without a ladder, or\n * one with no identity level, the reserved key `user` is removed. A path with\n * no identity rung comes back unchanged (as a copy).\n */\nexport function pathAboveIdentity(\n scopePath: Readonly<Record<string, string>> | null | undefined,\n ladder?: ScopeLadder | null,\n): Record<string, string> | undefined {\n if (!scopePath || Object.keys(scopePath).length === 0) return undefined;\n const identity = ladder?.levels.find((lv) => lv.role === ROLE_IDENTITY);\n const out: Record<string, string> = {};\n if (!ladder || !identity) {\n for (const [k, v] of Object.entries(scopePath)) if (k !== RESERVED_IDENTITY_KEY) out[k] = v;\n } else {\n const position = new Map(ladder.levels.map((lv) => [lv.key, lv.position] as const));\n for (const [k, v] of Object.entries(scopePath)) {\n if ((position.get(k) ?? -1) < identity.position) out[k] = v;\n }\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\nconst REFRESH_HINT =\n \"The account's ladder may not be accepted yet, or nested scoping may be off for \" +\n 'this instance. If that changed recently, ' +\n '`await sdk.get_scope_ladder({ refresh: true })` re-reads it.';\n\nexport class ScopeLadder {\n readonly levels: readonly ScopeLevel[];\n readonly is_default: boolean;\n readonly ladder_ratified: boolean;\n readonly nested_scoping_enabled: boolean;\n /** \"server\" | \"inferred\" */\n readonly source: 'server' | 'inferred';\n /** True when the instance is B2C: the tenant and identity level are one node. */\n readonly b2c: boolean;\n\n constructor(init: {\n levels: readonly ScopeLevel[];\n is_default: boolean;\n ladder_ratified: boolean;\n nested_scoping_enabled: boolean;\n source: 'server' | 'inferred';\n b2c?: boolean;\n }) {\n this.levels = Object.freeze([...init.levels]);\n this.is_default = init.is_default;\n this.ladder_ratified = init.ladder_ratified;\n this.nested_scoping_enabled = init.nested_scoping_enabled;\n this.source = init.source;\n this.b2c = init.b2c ?? false;\n }\n\n get keys(): readonly string[] {\n return this.levels.map((l) => l.key);\n }\n\n /**\n * Map `values` (outermost level first) to ids and, on a deeper ladder, the\n * full prefix path. A shorter list addresses a higher level. Throws\n * `ScopeLadderError` before any call when the values cannot be addressed.\n */\n address(values: readonly string[]): ScopeAddress {\n if (!Array.isArray(values)) {\n throw new ScopeLadderError(\n `address() takes a list of values, outermost level first, got ${typeof values}.`,\n );\n }\n const vals = [...values];\n if (vals.length === 0) {\n throw new ScopeLadderError(\n 'address() needs at least one value. The client level is addressed ' +\n \"explicitly elsewhere (scope='client'), not through the ladder. \" +\n `Levels, outermost first: ${JSON.stringify(this.keys)}.`,\n );\n }\n for (const v of vals) {\n if (typeof v !== 'string' || v === '') {\n throw new ScopeLadderError(`address() values must be non-empty strings, got ${JSON.stringify(v)}.`);\n }\n }\n\n const levels = this.levels;\n // B2C: the tenant level takes the identity's value, so the caller gives one\n // value per level except the tenant level.\n const expected = this.b2c ? levels.filter((l) => l.role !== ROLE_TENANT) : levels;\n if (vals.length > expected.length) {\n throw new ScopeLadderError(\n `${vals.length} values for ${expected.length} levels ` +\n `(${JSON.stringify(expected.map((l) => l.key))}, outermost first).`,\n );\n }\n\n if (!this.is_default && (!this.nested_scoping_enabled || !this.ladder_ratified)) {\n throw new ScopeLadderError(\n `This account has a deeper scope ladder (${JSON.stringify(this.keys)}), but the server ` +\n 'would refuse a scope path ' +\n `(nested_scoping_enabled=${this.nested_scoping_enabled}, ` +\n `ladder_ratified=${this.ladder_ratified}). ` + REFRESH_HINT,\n );\n }\n\n let userId: string | null = null;\n let customerId: string | null = null;\n const path: Record<string, string> = {};\n\n if (this.b2c) {\n const identity = levels.find((l) => l.role === ROLE_IDENTITY);\n if (identity === undefined) {\n throw new ScopeLadderError('This ladder has no identity level, so a B2C address cannot be built.');\n }\n if (vals.length < expected.length) {\n // The tenant level carries the identity's value, which a shorter list\n // does not reach. Guessing would file under the wrong node.\n throw new ScopeLadderError(\n \"On a B2C instance the tenant level takes the identity's value, so give one value \" +\n `for every level after it (${JSON.stringify(expected.map((l) => l.key))}); got ${vals.length}.`,\n );\n }\n const byKey = new Map<string, string>();\n expected.forEach((l, i) => byKey.set(l.key, vals[i] as string));\n const identityValue = byKey.get(identity.key) as string;\n userId = identityValue;\n if (!this.is_default) {\n for (const l of levels) {\n path[l.key] = l.role === ROLE_TENANT ? identityValue : (byKey.get(l.key) as string);\n }\n }\n } else {\n levels.slice(0, vals.length).forEach((l, i) => {\n const v = vals[i] as string;\n if (l.role === ROLE_TENANT) customerId = v;\n else if (l.role === ROLE_IDENTITY) userId = v;\n if (!this.is_default) path[l.key] = v;\n });\n }\n\n return new ScopeAddress({\n user_id: userId,\n customer_id: customerId,\n scope_path: Object.keys(path).length > 0 ? path : null,\n });\n }\n}\n\nconst STRICT_LEVELS: readonly ScopeLevel[] = [\n { key: 'customer', label: 'Customer', position: 1, role: ROLE_TENANT, required: true },\n { key: 'user', label: 'User', position: 2, role: ROLE_IDENTITY, required: true },\n];\nconst B2C_LEVELS: readonly ScopeLevel[] = [\n { key: 'user', label: 'User', position: 1, role: ROLE_IDENTITY, required: true },\n];\n\nfunction parseLevels(raw: unknown): ScopeLevel[] | null {\n if (!Array.isArray(raw) || raw.length === 0) return null;\n const out: ScopeLevel[] = [];\n for (const item of raw) {\n if (typeof item !== 'object' || item === null || Array.isArray(item)) return null;\n const o = item as Record<string, unknown>;\n const key = o['key'];\n if (typeof key !== 'string' || key === '') return null;\n const position = Number(o['position']);\n if (!Number.isFinite(position) || o['position'] === null || o['position'] === '') return null;\n const label = o['label'];\n const role = o['role'];\n out.push({\n key,\n label: typeof label === 'string' && label !== '' ? label : key,\n position: Math.trunc(position),\n role: typeof role === 'string' && role !== '' ? role : null,\n required: o['required'] === undefined ? true : Boolean(o['required']),\n });\n }\n out.sort((a, b) => a.position - b.position);\n return out;\n}\n\n/**\n * The ladder a whoami answer describes, or null when it does not say.\n *\n * Uses the `scope_ladder` block when present and well formed. A missing key and\n * an explicit null both mean \"no block\"; anything else that is not a well\n * formed block is treated as absent with a warning, never an exception. With no\n * usable block the default ladder is inferred from `user_context_isolation`\n * (`strict`: customer, user; `equals_customer`: user), `source: \"inferred\"`.\n */\nexport function ladderFromWhoami(\n whoami: Record<string, unknown>,\n fallbackIsolation?: string,\n warn: (message: string) => void = () => {},\n): ScopeLadder | null {\n const rawIso = whoami['user_context_isolation'];\n const isolation = (typeof rawIso === 'string' && rawIso !== '' ? rawIso : undefined) ?? fallbackIsolation;\n const b2c = isolation === 'equals_customer';\n\n const block = whoami['scope_ladder'];\n if (block !== undefined && block !== null) {\n const levels =\n typeof block === 'object' && !Array.isArray(block)\n ? parseLevels((block as Record<string, unknown>)['levels'])\n : null;\n if (levels === null) {\n warn('whoami returned a malformed scope_ladder block; ignoring it and inferring the default ladder.');\n } else {\n const b = block as Record<string, unknown>;\n return new ScopeLadder({\n levels,\n is_default: Boolean(b['is_default']),\n ladder_ratified: Boolean(b['ladder_ratified']),\n nested_scoping_enabled: Boolean(b['nested_scoping_enabled']),\n source: 'server',\n b2c,\n });\n }\n }\n\n if (isolation === undefined) return null;\n return new ScopeLadder({\n levels: b2c ? B2C_LEVELS : STRICT_LEVELS,\n is_default: true,\n ladder_ratified: false,\n nested_scoping_enabled: false,\n source: 'inferred',\n b2c,\n });\n}\n","/**\n * Native HTTP transport.\n *\n * Port of `maximem_synap/transport/http_client.py`. Uses global `fetch` so the\n * same code runs on Node, Edge, Workers and Bun, with an optional undici\n * dispatcher on Node to restore Python's connection reuse (see keepalive.ts).\n */\n\nimport {\n AgentUnavailableError,\n AuthenticationError,\n ContextNotFoundError,\n ConflictError,\n TranscriptConflictError,\n InstanceNotReadyError,\n InstanceBuildFailedError,\n InsufficientCreditsError,\n InvalidInputError,\n NetworkTimeoutError,\n RateLimitError,\n ServiceUnavailableError,\n SynapError,\n SynapPermanentError,\n} from '../errors.js';\nimport { newCorrelationId } from '../util/correlation.js';\nimport { ENDPOINTS, resolvePath, type EndpointName } from './endpoints.js';\nimport {\n DEFAULT_RETRY_POLICY,\n shouldRetry,\n type RetryPolicy,\n} from './retry.js';\nimport {\n getKeepAliveDispatcher,\n Heartbeat,\n HEARTBEAT_INTERVAL_MS,\n type KeepAliveOptions,\n} from './keepalive.js';\nimport { checkCustomerId } from '../scoping.js';\nimport {\n LADDER_INVALIDATION_MIN_INTERVAL_MS, LADDER_RETRY_BACKOFF_MS, LADDER_TTL_MS, ladderFromWhoami, type ScopeLadder,\n} from '../scope-ladder.js';\n\nexport const DEFAULT_BASE_URL = 'https://synap-cloud-prod.maximem.ai';\n\n/**\n * Client-side cooldown for `instance_not_ready`.\n *\n * The server refuses memory calls while an instance's memory architecture is\n * being built, and says how long to wait. After one refusal the SDK answers the\n * same refusal locally, with no network call, until that wait has passed.\n *\n * Only the routes the server gates (`require_instance_ready` in\n * `synap/cloud/application/admin_api/routes/sdk_*.py` and `migrations.py`) are\n * covered. Everything else (whoami, health, auth, status, credits, telemetry,\n * forget, compaction, profile reads) is not gated by the server and is never\n * short-circuited here. Matching is on the path (or a sub-path) AND the POST\n * method. Same list as `GATED_POST_PATHS` in `http_client.py`.\n */\nexport const GATED_POST_PATHS: readonly string[] = [\n '/v1/context/conversation/fetch', // sdk_context.py\n '/v1/context/user/fetch', // sdk_context.py\n '/v1/context/customer/fetch', // sdk_context.py\n '/v1/context/client/fetch', // sdk_context.py\n '/v1/conversations/messages', // sdk_conversations.py (+ /messages/batch)\n '/v1/conversations/ingest', // sdk_conversations.py\n '/v1/events/batch', // sdk_events.py\n '/api/v1/memories/create', // sdk_memories.py\n '/api/v1/memories/batch', // sdk_memories.py\n '/api/v1/memories/upload', // sdk_memories.py\n '/v1/migrations', // migrations.py (create, /{id}/approve, /{id}/run)\n];\n\n/** The most the SDK will ever wait on a server hint (seconds). */\nexport const COOLDOWN_MAX_SECONDS = 300;\n\n/** True when the server refuses this call while the instance is building. */\nexport function isGatedPath(method: string, path: string): boolean {\n if (method.toUpperCase() !== 'POST') return false;\n const bare = (path.split('?', 1)[0] ?? '').replace(/\\/+$/, '');\n return GATED_POST_PATHS.some((p) => bare === p || bare.startsWith(p + '/'));\n}\n\nexport interface TimeoutConfig {\n /**\n * Seconds. Same fields as TimeoutConfig in the Python SDK, but only `read`\n * is applied here: it limits the whole request. `connect` and `write` are\n * accepted so a config round-trips between the SDKs, and have no effect.\n */\n connect: number;\n read: number;\n write: number;\n /**\n * gRPC stream idle timeout. Not used by the HTTP transport; the stream\n * client reads it. Present so a config object round-trips between the two\n * SDKs, and because Python's TimeoutConfig has it.\n */\n streamIdle: number;\n}\n\nexport const DEFAULT_TIMEOUTS: TimeoutConfig = {\n connect: 5.0, read: 30.0, write: 10.0, streamIdle: 60.0,\n};\n\nexport interface Credentials {\n apiKey: string;\n clientId: string;\n instanceId: string;\n}\n\nexport interface HttpTransportOptions {\n credentials: Credentials;\n baseUrl?: string;\n timeouts?: Partial<TimeoutConfig>;\n /** `null` disables retries entirely, as Python's `retry_policy=None` does. */\n retryPolicy?: Partial<RetryPolicy> | null;\n keepAlive?: KeepAliveOptions & { heartbeatIntervalMs?: number };\n userAgent?: string;\n /** Injected in tests. Defaults to global fetch. */\n fetchImpl?: typeof fetch;\n /** Monotonic clock in milliseconds. Injected in tests; defaults to `performance.now`. */\n clock?: () => number;\n}\n\nexport interface RequestOptions {\n pathParams?: Record<string, string | number>;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n /**\n * Send `body` as-is instead of JSON-encoding it, and drop the JSON\n * Content-Type so the runtime can set `multipart/form-data` with its own\n * boundary. Setting Content-Type by hand for FormData produces a body the\n * server cannot parse, because the boundary will not match.\n */\n rawBody?: boolean;\n correlationId?: string;\n /** Overrides the endpoint's declared idempotency. */\n idempotent?: boolean;\n /**\n * Re-map an HTTP error for this one call, given the status. Returns the\n * error to throw instead, or undefined to keep it. Applied before the retry\n * decision, so the retry policy sees what the caller will.\n */\n mapError?: (status: number, error: SynapError) => SynapError | undefined;\n signal?: AbortSignal;\n}\n\ninterface AttemptOutcome {\n error: unknown;\n /** True when the server may have processed the request despite the failure. */\n outcomeUnknown: boolean;\n}\n\nexport class HttpTransport {\n readonly baseUrl: string;\n // Mutable so `configure()` can adjust them before the first request, and so\n // `initialize()` can write back the identity resolved from whoami.\n timeouts: TimeoutConfig;\n retryPolicy: RetryPolicy;\n\n #credentials: Credentials;\n private readonly userAgent: string;\n private readonly fetchImpl: typeof fetch;\n private readonly keepAliveOptions: KeepAliveOptions;\n private readonly heartbeat: Heartbeat;\n private closed = false;\n private readonly clock: () => number;\n // instance id -> when the refusal's wait ends (monotonic ms), and what was said.\n // One JS thread runs every request, so a plain Map needs no lock.\n private readonly notReadyCooldown = new Map<\n string, { until: number; message: string; state: string | null }\n >();\n\n constructor(options: HttpTransportOptions) {\n this.clock = options.clock ?? (() => performance.now());\n this.#credentials = options.credentials;\n // Trailing slash would produce `//v1/...`, which some proxies 404.\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '');\n this.timeouts = { ...DEFAULT_TIMEOUTS, ...options.timeouts };\n this.retryPolicy = options.retryPolicy === null\n ? { ...DEFAULT_RETRY_POLICY, maxAttempts: 1 }\n : { ...DEFAULT_RETRY_POLICY, ...options.retryPolicy };\n this.userAgent = options.userAgent ?? '@maximem/synap-js-sdk';\n this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);\n this.keepAliveOptions = options.keepAlive ?? {};\n this.heartbeat = new Heartbeat(\n () => this.pingHealth(),\n options.keepAlive?.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS,\n );\n }\n\n /**\n * @internal Fetch a URL that is not Synap's, with this transport's fetch.\n *\n * Used to read a `FilePart` given by `url`: the SDK fetches it, the server\n * never does. Deliberately sends none of this transport's headers, because\n * the URL belongs to somebody else and the API key must not reach them.\n */\n fetchExternal(url: string, init: RequestInit = {}): Promise<Response> {\n return this.fetchImpl(url, init);\n }\n\n /** Start keeping the connection warm. Opt-in: it is pointless in serverless. */\n startHeartbeat(): void {\n if (!this.closed) this.heartbeat.start();\n }\n\n /**\n * Release timers. Safe to call more than once.\n *\n * This is the supported shutdown path, deliberately explicit rather than\n * hooked to `process.on('exit')`: those handlers leak a listener per client,\n * never fire in Lambda, and `process` does not exist in Workers (gotcha G-I).\n */\n /**\n * A COPY of the current credentials.\n *\n * A copy, not the live object: handing out the internal reference is how\n * `client.transport.credentials.apiKey` became readable and mutable from\n * outside in the first place.\n */\n currentCredentials(): Credentials {\n return { ...this.#credentials };\n }\n\n /** Write back identity resolved from `GET /api/v1/auth/whoami`. */\n updateCredentials(patch: Partial<Credentials>): void {\n this.#credentials = { ...this.#credentials, ...patch };\n }\n\n /**\n * The instance's scoping mode, from whoami. Lives here rather than on the\n * client because every interface factory already receives the transport,\n * and it is per-client, so a module-level global would be wrong the moment a\n * process holds two clients.\n *\n * undefined means the server did not report it, which is true of any\n * deployment older than the field, and must mean \"enforce nothing\".\n */\n userContextIsolation: string | undefined = undefined;\n\n // ── Scope ladder (Python: MaximemSynapSDK.get_scope_ladder) ───────────────\n // Held here, like `userContextIsolation`, so the interface factories that\n // receive the transport can reach it and the client's public surface carries\n // only the method Python has.\n #ladder: ScopeLadder | null = null;\n // Loaded is separate from the value: \"the server does not say\" (null) is an\n // answer too, and is cached for the same 300 s.\n #ladderLoaded = false;\n #ladderExpiresAt = 0;\n #ladderRetryAt = 0;\n // Bumped by every invalidation. A read that started under an older number is\n // not stored when it finishes.\n #ladderGeneration = 0;\n #ladderInvalidated = false;\n #ladderInvalidationReadAt = Number.NEGATIVE_INFINITY;\n // The read in flight, shared by concurrent callers.\n #ladderInflight:\n | { promise: Promise<ScopeLadder | null>; generation: number; keepOnFailure: boolean }\n | undefined = undefined;\n\n /**\n * Called as observer(error, carriedScopePath) for every 400 answer.\n * `carriedScopePath` says whether the refused request named a scope path,\n * which is how the client learns its cached ladder may be stale. Never\n * allowed to throw.\n */\n onInvalidInput: ((error: SynapError, carriedScopePath: boolean) => void) | undefined = undefined;\n\n /**\n * A 400 answered a call that carried a scope path: the ladder we hold may be\n * stale. The next read is at most one per LADDER_INVALIDATION_MIN_INTERVAL_MS,\n * the last known ladder stays as the answer if it fails, and a read already\n * in flight will not be stored.\n *\n * The server's refusal wording is deliberately not inspected. The gRPC\n * stream does not surface HTTP 400, so a ladder error on the stream is not\n * observed here.\n */\n invalidateScopeLadder(): void {\n this.#ladderGeneration += 1;\n this.#ladderInvalidated = true;\n this.#ladderRetryAt = 0;\n }\n\n /** The ladder already held, or null when none has been read. Makes no request. */\n cachedScopeLadder(): ScopeLadder | null {\n return this.#ladderLoaded ? this.#ladder : null;\n }\n\n /**\n * The account's ladder, from whoami, cached for 300 s (`null` included).\n * Concurrent callers share one read. A failed re-read after expiry keeps the\n * last known ladder (with a warning) and waits 60 s before trying again. A\n * failure on the first read, or with `refresh`, is thrown.\n */\n async getScopeLadder(refresh: boolean, warn: (message: string) => void): Promise<ScopeLadder | null> {\n const now = this.clock();\n const cached = this.#ladder;\n const loaded = this.#ladderLoaded;\n if (!refresh && loaded) {\n if (now < this.#ladderRetryAt) return cached;\n if (this.#ladderInvalidated) {\n // At most one invalidation-triggered re-read per interval.\n if (now < this.#ladderInvalidationReadAt + LADDER_INVALIDATION_MIN_INTERVAL_MS) return cached;\n } else if (now < this.#ladderExpiresAt) {\n return cached;\n }\n }\n\n const keepOnFailure = loaded && !refresh;\n const inflight = this.#ladderInflight;\n if (\n inflight !== undefined\n && inflight.generation === this.#ladderGeneration\n && inflight.keepOnFailure === keepOnFailure\n ) {\n // Concurrent callers share the one read, and its outcome. Only callers\n // with the same failure rule join it: a `refresh` caller must see a\n // failed read thrown, so it never joins a read that would answer a\n // failure with the stale ladder (and the other way round), and starts\n // its own instead.\n return inflight.promise;\n }\n\n const generation = this.#ladderGeneration;\n if (this.#ladderInvalidated && !refresh) this.#ladderInvalidationReadAt = now;\n const promise = this.#readScopeLadder(now, generation, cached, keepOnFailure, warn);\n const entry = { promise, generation, keepOnFailure };\n this.#ladderInflight = entry;\n const clear = (): void => {\n if (this.#ladderInflight === entry) this.#ladderInflight = undefined;\n };\n promise.then(clear, clear);\n return promise;\n }\n\n async #readScopeLadder(\n now: number,\n generation: number,\n cached: ScopeLadder | null,\n keepOnFailure: boolean,\n warn: (message: string) => void,\n ): Promise<ScopeLadder | null> {\n let whoami: Record<string, unknown>;\n try {\n const raw = await this.request('whoami', {});\n whoami = typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};\n } catch (error) {\n if (keepOnFailure) {\n warn(\n `Could not re-read the scope ladder (${(error as Error)?.message ?? String(error)}); ` +\n `keeping the last known one and retrying in ${LADDER_RETRY_BACKOFF_MS / 1000}s.`,\n );\n this.#ladderRetryAt = now + LADDER_RETRY_BACKOFF_MS;\n return cached;\n }\n throw error;\n }\n const ladder = ladderFromWhoami(whoami, this.userContextIsolation, warn);\n if (generation === this.#ladderGeneration) {\n this.#ladder = ladder;\n this.#ladderLoaded = true;\n this.#ladderExpiresAt = now + LADDER_TTL_MS;\n this.#ladderRetryAt = 0;\n this.#ladderInvalidated = false;\n }\n // else: invalidated while this read was in flight. Its callers get the\n // value, but it is not stored, so the next call re-reads.\n return ladder;\n }\n\n /**\n * Set by the client to its identity resolution (`initialize()`'s whoami).\n * Python refuses every call before `initialize()`; here the first request\n * runs it instead, so a caller who skips it gets the same identity-dependent\n * behaviour (client-scope cache hits, the B2C check) rather than an error.\n */\n identityResolver: (() => Promise<void>) | undefined = undefined;\n\n /** Resolve identity once, before the first request. Never throws. */\n async ready(): Promise<void> {\n if (this.identityResolver !== undefined) await this.identityResolver();\n }\n\n /**\n * Refuse a customer_id on a B2C instance, at the call site. Resolves identity\n * first: the isolation comes from whoami, so on the first call of a client\n * that skipped initialize() the check would otherwise see nothing and pass.\n */\n async checkCustomerId(customerId: unknown, where: string): Promise<void> {\n await this.ready();\n checkCustomerId(\n this.userContextIsolation, customerId, where, this.#credentials.instanceId,\n );\n }\n\n setTimeouts(timeouts: Partial<TimeoutConfig>): void {\n this.timeouts = { ...this.timeouts, ...timeouts };\n }\n\n /**\n * `null` DISABLES retries, matching Python.\n *\n * Python's `SDKConfig(retry_policy=None)` leaves `self.retry_policy` unset and\n * `max_attempts` falls to 1 (http_client.py:180). We restored the default\n * policy instead, so a caller following the \"Disabling Retries\" documentation\n * got three attempts and no way to turn them off.\n */\n setRetryPolicy(policy: Partial<RetryPolicy> | null): void {\n this.retryPolicy = policy === null\n ? { ...DEFAULT_RETRY_POLICY, maxAttempts: 1 }\n : { ...this.retryPolicy, ...policy };\n }\n\n close(): void {\n this.closed = true;\n this.heartbeat.stop();\n }\n\n /** Throw InstanceNotReadyError locally if this instance is cooling down. */\n private cooldownCheck(instanceId: string, correlationId: string): void {\n const entry = this.notReadyCooldown.get(instanceId);\n if (entry === undefined) return;\n const remainingMs = entry.until - this.clock();\n if (remainingMs <= 0) {\n this.notReadyCooldown.delete(instanceId);\n return;\n }\n throw new InstanceNotReadyError(entry.message, {\n correlationId,\n retryAfterSeconds: Math.max(1, Math.ceil(remainingMs / 1000)),\n instanceId,\n state: entry.state,\n fromCooldown: true,\n });\n }\n\n /** Remember a server refusal. Never longer than the server's hint. */\n private cooldownStart(instanceId: string, error: InstanceNotReadyError): void {\n const hint = error.retryAfterSeconds;\n if (hint === null || !(hint > 0)) return; // no hint: nothing to base a wait on\n const waitMs = Math.min(hint, COOLDOWN_MAX_SECONDS) * 1000;\n this.notReadyCooldown.set(instanceId, {\n until: this.clock() + waitMs,\n message: error.message,\n state: error.state,\n });\n }\n\n async request<T = unknown>(name: EndpointName, options: RequestOptions = {}): Promise<T> {\n const spec = ENDPOINTS[name];\n const correlationId = options.correlationId ?? newCorrelationId();\n const idempotent = options.idempotent ?? spec.idempotent;\n // whoami IS the identity resolution, so it must not wait on itself.\n if (name !== 'whoami') await this.ready();\n\n const gated = isGatedPath(spec.method, resolvePath(name, options.pathParams));\n const cooldownKey = this.#credentials.instanceId;\n if (gated) this.cooldownCheck(cooldownKey, correlationId);\n\n let attempt = 0;\n let last: AttemptOutcome | null = null;\n\n // At least one attempt: maxAttempts 0 used to send nothing and throw\n // \"Request failed with no recorded error\".\n while (attempt < Math.max(1, this.retryPolicy.maxAttempts)) {\n attempt += 1;\n try {\n const result = await this.attempt<T>(name, options, correlationId);\n // The server accepted a memory call: the instance is ready.\n if (gated) this.notReadyCooldown.delete(cooldownKey);\n return result;\n } catch (error) {\n // Remember the refusal so the next calls need no round trip.\n if (gated && error instanceof InstanceNotReadyError && !error.fromCooldown) {\n this.cooldownStart(cooldownKey, error);\n }\n last = { error, outcomeUnknown: isOutcomeUnknown(error) };\n const decision = shouldRetry({\n error,\n attempt,\n policy: this.retryPolicy,\n method: spec.method,\n outcomeUnknown: last.outcomeUnknown,\n idempotent,\n });\n if (!decision.retry) throw error;\n await sleep(decision.delaySeconds * 1000, options.signal);\n }\n }\n throw last?.error ?? new SynapError('Request failed with no recorded error');\n }\n\n private async attempt<T>(\n name: EndpointName,\n options: RequestOptions,\n correlationId: string,\n ): Promise<T> {\n const spec = ENDPOINTS[name];\n const url = this.buildUrl(resolvePath(name, options.pathParams), options.query);\n\n const dispatcher = await getKeepAliveDispatcher(this.keepAliveOptions);\n const signal = withTimeout(this.timeouts.read * 1000, options.signal);\n\n const init: RequestInit = {\n method: spec.method,\n headers: this.buildHeaders(correlationId, { json: options.rawBody !== true }),\n signal: signal.signal,\n };\n if (options.body !== undefined && spec.method !== 'GET') {\n // `BodyInit` is a DOM-lib type and this package does not include that lib,\n // so the field's own type is used instead of naming it.\n init.body = options.rawBody === true\n ? (options.body as NonNullable<RequestInit['body']>)\n : JSON.stringify(options.body);\n }\n // `dispatcher` is a Node/undici extension. Its ambient type is only\n // present when undici's types are installed, so it is set structurally\n // rather than declared -- otherwise this file fails to compile for anyone\n // who has not installed the optional dependency.\n if (dispatcher) (init as Record<string, unknown>)['dispatcher'] = dispatcher;\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, init);\n } catch (error) {\n throw toTransportError(error, correlationId);\n } finally {\n signal.dispose();\n }\n\n if (!response.ok) {\n const error = await toHttpError(response, correlationId);\n if (response.status === 400 && error instanceof InvalidInputError) {\n try { this.onInvalidInput?.(error, carriesScopePath(options.body)); } catch { /* an observer must never change the error */ }\n }\n throw options.mapError?.(response.status, error) ?? error;\n }\n\n if (response.status === 204) return undefined as T;\n const text = await response.text();\n if (!text) return undefined as T;\n try {\n return JSON.parse(text) as T;\n } catch {\n throw new SynapError(`Malformed JSON in response from ${url}`, { correlationId });\n }\n }\n\n private buildUrl(path: string, query?: RequestOptions['query']): string {\n const url = new URL(this.baseUrl + path);\n for (const [k, v] of Object.entries(query ?? {})) {\n if (v !== undefined) url.searchParams.set(k, String(v));\n }\n return url.toString();\n }\n\n private buildHeaders(\n correlationId: string,\n options: { json?: boolean } = {},\n ): Record<string, string> {\n return {\n // Empty only in local mode with no SYNAP_API_TOKEN: send no header at all.\n ...(this.#credentials.apiKey !== '' ? { Authorization: `Bearer ${this.#credentials.apiKey}` } : {}),\n 'X-Client-ID': this.#credentials.clientId,\n 'X-Instance-ID': this.#credentials.instanceId,\n 'X-Correlation-ID': correlationId,\n ...(options.json === false ? {} : { 'Content-Type': 'application/json' }),\n 'User-Agent': this.userAgent,\n };\n }\n\n /** Unauthenticated and unmetered, exactly like the Python heartbeat. */\n private async pingHealth(): Promise<void> {\n const signal = withTimeout(10_000);\n try {\n const dispatcher = await getKeepAliveDispatcher(this.keepAliveOptions);\n const init: RequestInit = { signal: signal.signal };\n if (dispatcher) (init as Record<string, unknown>)['dispatcher'] = dispatcher;\n await this.fetchImpl(`${this.baseUrl}/health`, init);\n } finally {\n signal.dispose();\n }\n }\n}\n\n// ─── Error classification ─────────────────────────────────────────────────────\n\n/**\n * Whether the server may have processed the request despite this error.\n *\n * This is the input to the double-billing gate in retry.ts, so the bias is\n * deliberate: anything we cannot positively rule out counts as ambiguous.\n */\nexport function isOutcomeUnknown(error: unknown): boolean {\n // A definitive HTTP status means the server answered. Nothing ambiguous.\n if (error instanceof RateLimitError) return false;\n if (error instanceof ServiceUnavailableError) return false;\n if (error instanceof AuthenticationError) return false;\n if (error instanceof InvalidInputError) return false;\n if (error instanceof ConflictError) return false;\n if (error instanceof InsufficientCreditsError) return false;\n if (error instanceof ContextNotFoundError) return false;\n\n // Connection-level failures mean the request never reached the application.\n // Checked before the class: since 0.5.13 they are NetworkTimeoutErrors too,\n // and they must stay safe to retry.\n if (isConnectionRefusal(error)) return false;\n\n // Timeouts are the ambiguous case: the request may have been handled and\n // only the response lost.\n if (error instanceof NetworkTimeoutError) return true;\n\n return true;\n}\n\nconst CONNECTION_REFUSAL_CODES = new Set([\n 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ECONNRESET', 'EHOSTUNREACH',\n]);\n\n/**\n * A refusal code anywhere on the cause chain. fetch nests the socket error\n * under its own, and a SynapError carries a `code` of its own\n * ('network_timeout'), so the walk cannot stop at the first `code` it sees.\n */\nfunction isConnectionRefusal(error: unknown): boolean {\n let cur: unknown = error;\n for (let depth = 0; depth < 4 && cur !== null && typeof cur === 'object'; depth += 1) {\n const code = (cur as { code?: unknown }).code;\n if (typeof code === 'string' && CONNECTION_REFUSAL_CODES.has(code)) return true;\n cur = (cur as { cause?: unknown }).cause;\n }\n return false;\n}\n\nfunction toTransportError(error: unknown, correlationId: string): SynapError {\n if (error instanceof SynapError) return error;\n const name = (error as { name?: string })?.name;\n if (name === 'AbortError' || name === 'TimeoutError') {\n return new NetworkTimeoutError('Request timed out', { correlationId, cause: error });\n }\n // A refused, unresolvable or dropped connection is a NetworkTimeoutError,\n // as Python raises it (httpx ConnectError and RemoteProtocolError), so one\n // `catch` handles \"could not reach Synap\" in both SDKs. Until 0.5.13 these\n // were ServiceUnavailableErrors, the class for a 5xx the server sent.\n if (isConnectionRefusal(error)) {\n return new NetworkTimeoutError(\n `Connection failed: ${(error as Error)?.message ?? String(error)}`,\n { correlationId, cause: error },\n );\n }\n return new ServiceUnavailableError(\n `Network request failed: ${(error as Error)?.message ?? String(error)}`,\n { correlationId, cause: error },\n );\n}\n\n/**\n * Values the credit gate sends as the body's `error` field. Only these are read\n * as a reason, so an unrelated 429 carrying some other `error` string is not\n * mistaken for a credit stop. Mirrors `_CREDIT_ERRORS` in `http_client.py`.\n */\nconst CREDIT_ERRORS = new Set(['insufficient_credits', 'trial_limit_reached']);\n\n/**\n * The credit gate's structured body, however the server nested it.\n *\n * The gate raises an HTTPException, so FastAPI wraps its payload in `detail`;\n * the burn-service path returns the same fields at the top level. Reading only\n * the top level (what this transport did) meant the gate's balance, reason and\n * URLs never reached the caller.\n */\nfunction creditPayload(\n parsed: Record<string, unknown>,\n detailObject: Record<string, unknown> | null,\n): Record<string, unknown> {\n return detailObject ?? parsed;\n}\n\n/** Why the request was refused, or null if this was not a credit stop. */\nfunction creditReason(payload: Record<string, unknown>): string | null {\n const reason = stringOrNull(payload['reason']);\n if (reason !== null) return reason;\n const error = stringOrNull(payload['error']);\n return error !== null && CREDIT_ERRORS.has(error) ? error : null;\n}\n\n/** A scope path is a non-empty object of level key to id; a multipart form sends it as a JSON string. */\nfunction isScopePath(value: unknown): boolean {\n let v = value;\n if (typeof v === 'string' && v.trimStart().startsWith('{')) {\n try { v = JSON.parse(v); } catch { return false; }\n }\n return typeof v === 'object' && v !== null && !Array.isArray(v) && Object.keys(v).length > 0;\n}\n\n/**\n * Whether a request body names a scope path: a top-level `scope` (context\n * fetches, record_message, ingest_transcript, memories, send_message) or one on\n * a message of a batch. `data.delete` also has a `scope` field, but it is a\n * plain string such as \"user\", so it is not a path. Mirrors Python's\n * `_carries_scope_path`.\n */\nexport function carriesScopePath(body: unknown): boolean {\n if (typeof FormData !== 'undefined' && body instanceof FormData) {\n if (isScopePath(body.get('scope'))) return true;\n // `memories.create` with file parts posts one `manifest` field: a JSON\n // string whose `scope` key holds the path. Unreadable means \"no path\".\n const manifest = body.get('manifest');\n if (typeof manifest === 'string') {\n try {\n const parsed: unknown = JSON.parse(manifest);\n return typeof parsed === 'object' && parsed !== null\n && isScopePath((parsed as Record<string, unknown>)['scope']);\n } catch { return false; }\n }\n return false;\n }\n if (typeof body !== 'object' || body === null || Array.isArray(body)) return false;\n const o = body as Record<string, unknown>;\n if (isScopePath(o['scope'])) return true;\n return Object.values(o).some(\n (v) => Array.isArray(v) && v.some((i) => typeof i === 'object' && i !== null && isScopePath((i as Record<string, unknown>)['scope'])),\n );\n}\n\nasync function toHttpError(response: Response, correlationId: string): Promise<SynapError> {\n const body = await response.text().catch(() => '');\n let parsed: Record<string, unknown> = {};\n try {\n parsed = JSON.parse(body) as Record<string, unknown>;\n } catch {\n /* body is not JSON; the raw text is still used in the message */\n }\n // `detail` is a string on most routes but a structured object on the ones\n // that need a machine-readable code: {\"detail\": {\"code\": ..., \"message\": ...}}.\n // Casting it straight to string rendered those as \"[object Object]\".\n const rawDetail = parsed['detail'] ?? parsed['message'] ?? body ?? '';\n const detailObject =\n typeof rawDetail === 'object' && rawDetail !== null\n ? (rawDetail as Record<string, unknown>)\n : null;\n const detail =\n detailObject !== null\n ? String(detailObject['message'] ?? JSON.stringify(detailObject))\n : String(rawDetail);\n const message = `HTTP ${response.status}: ${detail || response.statusText}`;\n const opts = { correlationId };\n\n switch (response.status) {\n case 400:\n case 422:\n // Wrong method, too large, unsupported media type: each says what was\n // wrong with the request, and none of them goes away on a retry.\n case 405:\n case 413:\n case 415:\n return new InvalidInputError(message, opts);\n case 401:\n case 403:\n return new AuthenticationError(message, opts);\n case 404:\n return new ContextNotFoundError(message, opts);\n case 402: {\n // The server sends `minimum_required_credits` (see\n // synap/cloud/application/credits/enforcement.py). We read\n // `required_credits` for a while, a key that never exists, so\n // `requiredCredits` was always null. `recovery_url` and `redeem_url`\n // were dropped entirely, leaving no way to surface a top-up link.\n const credit = creditPayload(parsed, detailObject);\n return new InsufficientCreditsError(message, {\n ...opts,\n balanceCredits: numberOrNull(credit['balance_credits']),\n requiredCredits:\n numberOrNull(credit['minimum_required_credits']) ??\n numberOrNull(credit['required_credits']),\n recoveryUrl: stringOrNull(credit['recovery_url']),\n redeemUrl: stringOrNull(credit['redeem_url']),\n reason: creditReason(credit),\n manageUrl: stringOrNull(credit['manage_url']),\n });\n }\n case 409:\n // Conflict is PERMANENT and never retried. Python discriminates on the\n // structured body so a transcript-immutability conflict becomes\n // TranscriptConflictError and anything else (e.g. compact()'s \"already\n // in progress\") stays the generic ConflictError. Without this, a\n // customer's `catch (e) { if (e instanceof TranscriptConflictError) }`\n // never fires in JS while the identical Python code works.\n if (\n parsed['error'] === 'instance_build_failed' ||\n detailObject?.['code'] === 'instance_build_failed' ||\n detailObject?.['error'] === 'instance_build_failed'\n ) {\n // Not time based: no cooldown, no retry. Mirrors `_instance_build_failed`.\n const pick = (key: string): unknown => parsed[key] ?? detailObject?.[key];\n const msg = pick('message');\n const attempts = Number(pick('attempts'));\n return new InstanceBuildFailedError(\n typeof msg === 'string' && msg !== ''\n ? msg\n : \"This instance's memory architecture build failed.\",\n {\n ...opts,\n instanceId: stringOrNull(pick('instance_id')),\n attempts: pick('attempts') !== undefined && pick('attempts') !== null\n && Number.isFinite(attempts) ? Math.trunc(attempts) : null,\n hint: stringOrNull(pick('hint')),\n },\n );\n }\n if (\n parsed['error'] === 'instance_not_ready' ||\n detailObject?.['code'] === 'instance_not_ready' ||\n detailObject?.['error'] === 'instance_not_ready'\n ) {\n // Fields come from the flat copy, then the `detail` copy, then the\n // Retry-After header. Mirrors `_instance_not_ready` in http_client.py.\n const pick = (key: string): unknown => parsed[key] ?? detailObject?.[key];\n const rawWait = pick('retry_after_seconds') ?? response.headers.get('retry-after');\n const wait =\n rawWait !== null && rawWait !== undefined && String(rawWait).trim() !== ''\n ? Number(rawWait)\n : NaN;\n const msg = pick('message');\n return new InstanceNotReadyError(\n typeof msg === 'string' && msg !== ''\n ? msg\n : \"This instance's memory architecture is still being built.\",\n {\n ...opts,\n retryAfterSeconds: Number.isFinite(wait) ? Math.trunc(wait) : null,\n instanceId: stringOrNull(pick('instance_id')),\n state: stringOrNull(pick('state')) ?? 'building',\n },\n );\n }\n if (detailObject !== null && detailObject['code'] === 'transcript_conflict') {\n return new TranscriptConflictError(message, opts);\n }\n return new ConflictError(message, opts);\n case 429: {\n // Either an ordinary rate limit or a credit stop that time or a plan\n // change clears: the spent Trial cap (`trial_limit_reached`) and a paid\n // plan whose subscription lapsed (`subscription_inactive`). The credit\n // fields are absent on the plain rate limit.\n const header = response.headers.get('retry-after');\n const retryAfter = header !== null && header.trim() !== '' ? Number(header) : null;\n const credit = creditPayload(parsed, detailObject);\n return new RateLimitError(message, {\n ...opts,\n retryAfterSeconds: retryAfter !== null && Number.isFinite(retryAfter) ? retryAfter : null,\n reason: creditReason(credit),\n upgradeUrl: stringOrNull(credit['upgrade_url']),\n manageUrl: stringOrNull(credit['manage_url']),\n });\n }\n case 503:\n return new ServiceUnavailableError(message, opts);\n case 504:\n return new AgentUnavailableError(message, opts);\n default:\n if (response.status >= 500) return new ServiceUnavailableError(message, opts);\n // Any other 4xx is the request's fault and fails the same way again:\n // permanent, as Python raises it. It was a bare SynapError.\n if (response.status >= 400) return new SynapPermanentError(message, opts);\n return new SynapError(message, opts);\n }\n}\n\nfunction numberOrNull(v: unknown): number | null {\n return typeof v === 'number' && Number.isFinite(v) ? v : null;\n}\n\nfunction stringOrNull(v: unknown): string | null {\n return typeof v === 'string' && v !== '' ? v : null;\n}\n\n// ─── Utilities ────────────────────────────────────────────────────────────────\n\ninterface DisposableSignal {\n signal: AbortSignal;\n dispose(): void;\n}\n\n/**\n * Compose a timeout with a caller-supplied signal.\n *\n * Hand-rolled rather than `AbortSignal.timeout` + `AbortSignal.any` because\n * `any` is Node 20.3+ and this must also run on Workers and older Bun. The\n * timer is cleared in `dispose` so a fast response does not hold the event\n * loop open for the full timeout.\n */\nfunction withTimeout(ms: number, external?: AbortSignal): DisposableSignal {\n const controller = new AbortController();\n const onExternalAbort = () => controller.abort(external?.reason);\n const timer = setTimeout(() => {\n controller.abort(new NetworkTimeoutError(`Timed out after ${ms}ms`));\n }, ms);\n (timer as { unref?: () => void }).unref?.();\n\n if (external) {\n if (external.aborted) onExternalAbort();\n else external.addEventListener('abort', onExternalAbort, { once: true });\n }\n\n return {\n signal: controller.signal,\n dispose() {\n clearTimeout(timer);\n external?.removeEventListener('abort', onExternalAbort);\n },\n };\n}\n\n/**\n * Retry backoff.\n *\n * Deliberately NOT `unref`'d, unlike the heartbeat timer in keepalive.ts. That\n * distinction is the whole point: a heartbeat is background work and must not\n * hold the process open, but a backoff is FOREGROUND work that a caller is\n * awaiting. With it unref'd, a process whose only pending work was this sleep\n * exited during the backoff and the awaited request never settled -- Node\n * reports it as \"Detected unsettled top-level await\". Invisible in a server\n * with other traffic; fatal in a CLI or an idle serverless handler.\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) return Promise.resolve();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n function onAbort() {\n clearTimeout(timer);\n reject(signal?.reason ?? new Error('Aborted'));\n }\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","/**\n * `response_shape: \"ranked\"`: one list in the order the server ranked it.\n *\n * Ports the ranked half of Python's `models/context.py` (`rank_items`,\n * `_wire_rank_score`, `_wire_category` and the ranked branch of\n * `ContextResponse.from_cloud_response`). The cases are pinned in\n * `CONTRACT/conformance/ranked_shape.json`, captured from Python.\n *\n * Opt-in. A by-type fetch, the default, is returned exactly as the server sent\n * it, so nothing here touches a caller who does not ask for the ranked shape.\n */\n\nimport type { Json, RawContext, RawContextItem } from './types.js';\n\n/** The two shapes a context fetch can ask for. */\nexport const RESPONSE_SHAPES = ['by_type', 'ranked'] as const;\nexport type ResponseShape = (typeof RESPONSE_SHAPES)[number];\n\n/** The memory types, in the order the by-type response lists them. */\nexport const MEMORY_TYPES = [\n 'facts',\n 'preferences',\n 'episodes',\n 'emotions',\n 'temporal_events',\n] as const;\n\n/**\n * The type of a chunk in a ranked response: a quote from a source document,\n * not an extracted memory. A by-type response files it under `facts`.\n */\nexport const EXCERPT_CATEGORY = 'excerpts';\n\n/**\n * An item's rank score: `metadata.rank_score` on the HTTP response, a\n * top-level `rank_score` on a prefetched (gRPC) item. `null` when neither is a\n * number, which is how a server that predates ranking reads.\n */\nexport function wireRankScore(item: RawContextItem): number | null {\n const md = item.metadata;\n let raw: unknown = md !== null && typeof md === 'object' ? (md as Json)['rank_score'] : undefined;\n if (raw === undefined || raw === null) raw = item['rank_score'];\n return typeof raw === 'number' && Number.isFinite(raw) ? raw : null;\n}\n\n/**\n * An item's type. A chunk is an excerpt whatever list it came in: a server or\n * a prefetched bundle that predates ranking files it under facts.\n */\nexport function wireCategory(item: RawContextItem, fallback = ''): string {\n if (item.source === 'chunks') return EXCERPT_CATEGORY;\n const category = item['category'];\n if (typeof category === 'string' && category !== '') return category;\n const contextType = item['context_type'];\n if (typeof contextType === 'string' && contextType !== '') return contextType;\n return fallback;\n}\n\n/** Highest score first; items without one after, in the order they came. */\nfunction byRankScore(a: RawContextItem, b: RawContextItem): number {\n const sa = wireRankScore(a);\n const sb = wireRankScore(b);\n if (sa === null && sb === null) return 0;\n if (sa === null) return 1;\n if (sb === null) return -1;\n return sb - sa;\n}\n\n/**\n * Merge per-type item lists into one list in rank order, numbered from 1.\n *\n * For a server that predates `response_shape` (it returned the five lists) and\n * for a prefetched cache hit. Each returned item is a copy carrying `rank`,\n * `category` and `id` (a prefetched item names it `item_id`), so the input is\n * not changed. `Array.prototype.sort` is stable, like Python's.\n */\nexport function rankItems(byType: RawContext): RawContextItem[] {\n const flat: RawContextItem[] = [];\n // The five lists only: a raw context also carries other arrays\n // (`conversations` in summary mode), and none of them are memories.\n for (const type of MEMORY_TYPES) {\n const list = (byType as Json)[type];\n if (!Array.isArray(list)) continue;\n for (const it of list as RawContextItem[]) {\n if (it === null || typeof it !== 'object') continue;\n flat.push({\n ...it,\n category: wireCategory(it, type),\n id: (it.id || it.item_id || '') as string,\n });\n }\n }\n flat.sort(byRankScore);\n return flat.map((it, n) => ({ ...it, rank: n + 1 }));\n}\n\n/**\n * The raw context in the shape the caller asked for.\n *\n * \"ranked\": `items` in rank order (the server's own list, or one rebuilt by\n * rank score when the server or the cache predates the parameter), the five\n * typed lists as views of those items, and `excerpts` for the chunks. A\n * response that already carries `items` is read the same way even when the\n * caller did not ask, as Python does. Anything else is returned untouched.\n */\nexport function applyResponseShape(raw: RawContext, shape: string = 'by_type'): RawContext {\n const wire = (raw as Json)['items'];\n if (shape !== 'ranked' && !Array.isArray(wire)) return raw;\n const source: RawContextItem[] = Array.isArray(wire)\n ? (wire as RawContextItem[])\n : rankItems(raw);\n const items = source.map((it) => ({\n ...it,\n id: (it.id || it.item_id || '') as string,\n category: wireCategory(it),\n }));\n const out: RawContext = { ...raw, items };\n for (const type of MEMORY_TYPES) {\n out[type] = items.filter((it) => it['category'] === type);\n }\n (out as Json)['excerpts'] = items.filter((it) => it['category'] === EXCERPT_CATEGORY);\n return out;\n}\n\n/** How each type is named on a line of the ranked prompt list. */\nconst RANKED_LABELS: Record<string, string> = {\n facts: 'fact',\n preferences: 'preference',\n episodes: 'episode',\n emotions: 'emotion',\n temporal_events: 'temporal event',\n [EXCERPT_CATEGORY]: 'excerpt',\n};\n\n/** The label printed in front of a ranked item: `fact`, `temporal event`, ... */\nexport function rankedLabel(category: string): string {\n return RANKED_LABELS[category] ?? (category !== '' ? category : 'item');\n}\n\n/** Shared by the ranked merge: the same ordering Python's `merge` sorts with. */\nexport function sortByRankScore(items: RawContextItem[]): RawContextItem[] {\n return [...items].sort(byRankScore);\n}\n","/**\n * A fetch with no query. Mirrors `has_query`, `conversation_state_context` and\n * `profile_context` in the Python SDK's `models/context.py`; the corpus both\n * run is `CONTRACT/conformance/no_query_fetch.json`.\n *\n * Without a query the server embedded an empty string and ranked memories\n * against it, so the answer was close to arbitrary. A conversation fetch now\n * answers with the conversation's state (what `get_context_for_prompt` gives)\n * and a user fetch with the user's profile when there is one.\n */\n\nimport type { Json, RawContext } from './types.js';\n\nconst MEMORY_TYPES = ['facts', 'preferences', 'episodes', 'emotions', 'temporal_events'] as const;\n\nconst emptyLists = (): Record<string, unknown[]> =>\n Object.fromEntries(MEMORY_TYPES.map((t) => [t, []]));\n\n/** Whether a fetch names something to search for. Blank strings are no query. */\nexport function hasQuery(searchQuery: unknown): boolean {\n if (typeof searchQuery === 'string') return searchQuery.trim() !== '';\n if (!Array.isArray(searchQuery)) return false;\n return searchQuery.some((q) => typeof q === 'string' && q.trim() !== '');\n}\n\n/** The answer to a conversation fetch without a query, in the fetch's wire shape. */\nexport function conversationStateContext(prompt: Json, conversationId: string): RawContext {\n const recent = Array.isArray(prompt['recent_messages']) ? (prompt['recent_messages'] as unknown[]) : [];\n const turns = recent\n .filter((m): m is Record<string, unknown> => typeof m === 'object' && m !== null && !Array.isArray(m))\n .map((m) => ({ role: m['role'] ?? null, content: m['content'] ?? null, timestamp: m['timestamp'] ?? null }));\n return {\n ...emptyLists(),\n conversation_context: {\n conversation_id: conversationId,\n summary: (prompt['context_block'] as string | undefined) || null,\n recent_turns: turns,\n compaction_id: (prompt['compaction_id'] as string | undefined) || null,\n formatted_context: (prompt['formatted_context'] as string | undefined) || null,\n },\n } as unknown as RawContext;\n}\n\n/**\n * The answer to a user fetch without a query, or null when there is no profile.\n * Takes the profile document flat or wrapped in `{ profile: ... }`. One with no\n * attributes and no overview counts as none.\n */\nexport function profileContext(profile: unknown): RawContext | null {\n if (typeof profile !== 'object' || profile === null || Array.isArray(profile)) return null;\n let doc = profile as Record<string, unknown>;\n const inner = doc['profile'];\n if (!('attributes' in doc) && typeof inner === 'object' && inner !== null && !Array.isArray(inner)) {\n doc = inner as Record<string, unknown>;\n }\n const attributes = doc['attributes'];\n const hasAttributes = typeof attributes === 'object' && attributes !== null && Object.keys(attributes).length > 0;\n if (!hasAttributes && !doc['overview']) return null;\n return { ...emptyLists(), profile: doc } as unknown as RawContext;\n}\n","/**\n * Scope-aware context fetching.\n *\n * Scopes are client > customer > user. `conversation_id` is NOT a tier: it\n * groups turns within a scope. Passing it narrows an existing scope rather\n * than selecting a different one.\n */\n\nimport type { EndpointName } from '../transport/endpoints.js';\nimport type { HttpTransport } from '../transport/http.js';\nimport { InvalidInputError } from '../errors.js';\nimport { RESPONSE_SHAPES, applyResponseShape } from './ranked.js';\nimport { hasQuery } from './no-query.js';\nimport type { FetchOptions, Json, RawContext } from './types.js';\n\nexport type Scope = 'user' | 'customer' | 'client' | 'conversation';\n\nconst ENDPOINT_BY_SCOPE: Record<Scope, EndpointName> = {\n user: 'context_fetch_user',\n customer: 'context_fetch_customer',\n client: 'context_fetch_client',\n conversation: 'context_fetch_conversation',\n};\n\n/** Reads either spelling of an option. Callers depend on both. */\nfunction opt<T>(options: FetchOptions, snake: keyof FetchOptions, camel: keyof FetchOptions): T | undefined {\n const a = options[snake];\n if (a !== undefined) return a as T;\n const b = options[camel];\n return b === undefined ? undefined : (b as T);\n}\n\nexport interface BuiltRequest {\n endpoint: EndpointName;\n body: Json;\n}\n\nexport function buildFetchRequest(scope: Scope, options: FetchOptions): BuiltRequest {\n const userId = opt<string>(options, 'user_id', 'userId');\n const customerId = opt<string>(options, 'customer_id', 'customerId');\n const conversationId = opt<string>(options, 'conversation_id', 'conversationId');\n const searchQuery = opt<string[]>(options, 'search_query', 'searchQuery');\n const maxResults = opt<number>(options, 'max_results', 'maxResults') ?? 10;\n const queryDate = opt<string>(options, 'query_date', 'queryDate');\n const perQuery = opt<number>(options, 'max_results_per_query', 'maxResultsPerQuery');\n const responseShape = responseShapeOf(options);\n const { mode, precisionLevel } = retrievalOptionsOf(options);\n const { contextMode, lastN } = scopeOptionsOf(scope, options);\n\n if (searchQuery !== undefined && !Array.isArray(searchQuery)) {\n throw new InvalidInputError('search_query must be an array when provided');\n }\n if (options.types !== undefined && !Array.isArray(options.types)) {\n throw new InvalidInputError('types must be an array when provided');\n }\n\n // Field-for-field identical to what the Python controllers post, because the\n // server is tuned against that payload and Python is the reference\n // implementation. In particular:\n // - conversation_id is ALWAYS present, null when unset, not omitted\n // - mode always defaults to \"fast\"\n // - precision_level is sent ONLY when it differs from \"high\"\n // - query_date is sent ONLY when the caller supplied one\n // - max_results_per_query is sent ONLY when the caller supplied one\n // - response_shape is sent ONLY when \"ranked\"\n // - include_conversation_context is sent ONLY when false\n // Sending an extra key, or omitting one Python always sends, is exactly the\n // kind of difference that shows up as \"works in Python, empty in JS\".\n const body: Json = {\n conversation_id: conversationId ?? null,\n search_query: searchQuery ?? [],\n max_results: maxResults,\n types: options.types ?? ['all'],\n mode,\n };\n if (precisionLevel !== 'high') body['precision_level'] = precisionLevel;\n // Omitted at its default, for the same reason precision_level is.\n if (queryDate) body['query_date'] = queryDate;\n // Omitted when unset, and `0` counts as unset, as in Python.\n if (perQuery) body['max_results_per_query'] = perQuery;\n if (responseShape !== 'by_type') body['response_shape'] = responseShape;\n if (options.include_conversation_context === false) {\n body['include_conversation_context'] = false;\n }\n // On all four scopes, as Python sends it. Until 0.5.10 only the user scope\n // did, so a scope_path passed to the client, customer or conversation fetch\n // was dropped and the read was served at the default levels instead.\n // Omitted when absent or empty, like Python's `if scope_path:`, so a caller\n // who does not use custom levels sends exactly the body they sent before.\n const scopePath = opt<Record<string, string>>(options, 'scope_path', 'scopePath');\n if (scopePath !== undefined && scopePath !== null && Object.keys(scopePath).length > 0) {\n body['scope'] = scopePath;\n }\n\n switch (scope) {\n case 'user': {\n body['user_id'] = userId as string;\n\n // Conditional, exactly as Python does it: the summary-mode keys are sent\n // ONLY in summary mode, so an in-conversation fetch is byte-identical to\n // one that never knew about them.\n if (contextMode === 'conversation-summary') {\n body['context_mode'] = contextMode;\n body['include_profile'] = opt<boolean>(options, 'include_profile', 'includeProfile') ?? true;\n body['last_n_conversations'] = lastN;\n }\n // Python sends this only when not None. It is passed through the same\n // way rather than defaulted to '', so the server sees the same request\n // from either SDK.\n if (customerId !== undefined) body['customer_id'] = customerId;\n break;\n }\n break;\n case 'customer':\n body['customer_id'] = customerId as string;\n break;\n case 'conversation':\n if (userId !== undefined) body['user_id'] = userId;\n if (customerId !== undefined) body['customer_id'] = customerId;\n break;\n case 'client':\n break;\n }\n\n return { endpoint: ENDPOINT_BY_SCOPE[scope], body };\n}\n\n/**\n * Hooks that let the client serve a fetch locally and report the outcome.\n *\n * Passed in rather than imported so this module stays free of the cache and\n * the stream: it is the one place every scope's fetch goes through, and it\n * should not grow a dependency on either.\n */\nexport interface AnticipatedServe {\n response: RawContext;\n servedItemIds: string[];\n bundleId: string;\n /**\n * A semantic match below the sure bar. The server is asked too, and its\n * answer is used if it arrives within `raceDeadlineMs`. Python:\n * `_race_borderline`.\n */\n borderline?: boolean;\n raceDeadlineMs?: number;\n}\n\nexport interface FetchHooks {\n /** Returns a response to short-circuit the network, or null to continue. */\n beforeFetch?: (\n scope: Scope,\n options: FetchOptions,\n ) => AnticipatedServe | null | Promise<AnticipatedServe | null>;\n /** Called after a cache hit is served, for the learning-loop event. */\n onServedFromCache?: (\n scope: Scope,\n options: FetchOptions,\n served: { servedItemIds: string[]; bundleId: string },\n ) => void;\n /** Called after EVERY fetch resolves, cache or network, for the audit event. */\n onAssembled?: (\n scope: Scope,\n options: FetchOptions,\n response: RawContext,\n startedAt: number,\n ) => void;\n /**\n * Called last on every path, with the shaped response, which it may modify:\n * the periodic user-summary splice Python runs at the end of each scoped\n * fetch.\n */\n onResponse?: (scope: Scope, options: FetchOptions, response: RawContext) => void;\n /**\n * True when this process already holds the conversation's compaction and\n * every turn after it, so the request asks the server not to assemble them\n * (`include_conversation_context: false`), as Python does on every scope.\n */\n skipServerShortTerm?: (conversationId: string) => boolean;\n /**\n * The answer to a fetch with no query, or null to make the fetch as before:\n * the conversation's state for the conversation scope, the profile for the\n * user scope. Python answers these inside the two scoped fetches; here the\n * client holds what they need, so it answers through this hook.\n */\n withoutQuery?: (scope: Scope, options: FetchOptions) => Promise<RawContext | null>;\n}\n\nconst VALID_CONTEXT_MODES = ['in-conversation', 'conversation-summary'];\n\n/** The shape asked for, validated as Python validates it, before any request. */\nexport function responseShapeOf(options: FetchOptions): string {\n const shape = opt<string>(options, 'response_shape', 'responseShape') ?? 'by_type';\n if (!(RESPONSE_SHAPES as readonly string[]).includes(shape)) {\n throw new InvalidInputError(\n `Invalid response_shape '${shape}'. Must be one of: ${RESPONSE_SHAPES.join(', ')}`,\n );\n }\n return shape;\n}\n\nconst REQUIRED_ID: Record<Scope, readonly [keyof FetchOptions, keyof FetchOptions] | null> = {\n user: ['user_id', 'userId'],\n customer: ['customer_id', 'customerId'],\n conversation: ['conversation_id', 'conversationId'],\n client: null,\n};\n\n/**\n * The scope's required id and, at user scope, the summary-mode options,\n * validated as Python validates them: before the anticipation cache, so a bad\n * value fails the same way whether or not a prefetched bundle would have\n * answered. Until 0.5.12 these ran only on the network path.\n */\nexport function scopeOptionsOf(\n scope: Scope,\n options: FetchOptions,\n): { contextMode: string; lastN: number } {\n const required = REQUIRED_ID[scope];\n if (required !== null && !opt<string>(options, required[0], required[1])) {\n throw new InvalidInputError(`${required[0]} is required`);\n }\n const contextMode = opt<string>(options, 'context_mode', 'contextMode') ?? 'in-conversation';\n const lastN = opt<number>(options, 'last_n_conversations', 'lastNConversations') ?? 1;\n if (scope !== 'user') return { contextMode, lastN };\n if (!VALID_CONTEXT_MODES.includes(contextMode)) {\n throw new InvalidInputError(\n `Invalid context_mode '${contextMode}'. Must be one of: ${VALID_CONTEXT_MODES.join(', ')}`,\n );\n }\n if (!Number.isInteger(lastN)) {\n throw new InvalidInputError('last_n_conversations must be an integer');\n }\n if (lastN < 0 || lastN > 20) {\n throw new InvalidInputError('last_n_conversations must be between 0 and 20');\n }\n return { contextMode, lastN };\n}\n\nconst VALID_MODES = ['fast', 'accurate'];\nconst VALID_PRECISION = ['high', 'medium'];\n\n/**\n * `mode` and `precision_level`, validated as Python validates them, before any\n * request. Without this a typo reached the server, which reads anything that\n * is not \"fast\" as \"accurate\": a slower, costlier read and no error.\n */\nexport function retrievalOptionsOf(options: FetchOptions): { mode: string; precisionLevel: string } {\n const mode = options.mode ?? 'fast';\n if (!VALID_MODES.includes(mode)) {\n throw new InvalidInputError(\n `Invalid mode '${mode}'. Must be one of: ${VALID_MODES.join(', ')}`,\n );\n }\n const precisionLevel = opt<string>(options, 'precision_level', 'precisionLevel') ?? 'high';\n if (!VALID_PRECISION.includes(precisionLevel)) {\n throw new InvalidInputError(\n `Invalid precision_level '${precisionLevel}'. Must be one of: ${VALID_PRECISION.join(', ')}`,\n );\n }\n return { mode, precisionLevel };\n}\n\n/** Keep local no-query answers subject to the wire request's query contract. */\nfunction validateSearchQuery(searchQuery: unknown): void {\n if (searchQuery === undefined || searchQuery === null) return;\n if (!Array.isArray(searchQuery) || searchQuery.some((query) => typeof query !== 'string')) {\n throw new InvalidInputError('search_query must be an array of strings when provided');\n }\n}\n\n/** Fetches and returns the RAW snake_case context, as the namespaced surface does. */\nexport async function fetchContext(\n transport: HttpTransport,\n scope: Scope,\n options: FetchOptions = {},\n hooks: FetchHooks = {},\n): Promise<RawContext> {\n // Anticipation cache FIRST, as Python does on all four scope fetches. Without\n // this the stream's bundles are never read and every fetch is a billed round\n // trip.\n const startedAt = Date.now();\n\n // Identity first, as Python requires initialize() before any fetch: the\n // cache lookup below filters on client_id and the B2C check on the\n // instance's isolation, and both come from whoami. Resolved once, on the\n // first request of a client that never called initialize().\n await transport.ready?.();\n\n // Before the anticipation cache, not after: a cached hit would otherwise let\n // an illegal shape through silently, which is the exact failure mode this\n // contract exists to remove.\n await transport.checkCustomerId(\n opt<string>(options, 'customer_id', 'customerId'),\n `${scope}.context.fetch`,\n );\n\n // Validated before the cache, like customer_id above, so a bad value fails\n // the same way whether or not a prefetched bundle would have answered.\n const responseShape = responseShapeOf(options);\n retrievalOptionsOf(options);\n const { contextMode } = scopeOptionsOf(scope, options);\n const searchQuery = opt<unknown>(options, 'search_query', 'searchQuery');\n validateSearchQuery(searchQuery);\n // Summary mode is a different read: a caller profile and past-conversation\n // summaries, assembled by the server. A prefetched bundle holds neither, and\n // with no search query the cache answered it with the newest bundle, so the\n // call-start read came back without a profile and no request was sent.\n const summaryMode = scope === 'user' && contextMode === 'conversation-summary';\n\n // No query: there is nothing to search for, and the search the server ran\n // instead embedded an empty string. Answered before the cache, as Python\n // answers it before its cache, and without the user-summary splice, which\n // Python's early return skips too.\n if (!summaryMode && hooks.withoutQuery && !hasQuery(searchQuery)) {\n const answer = await hooks.withoutQuery(scope, options);\n if (answer !== null) return applyResponseShape(answer, responseShape);\n }\n\n const finish = (response: RawContext): RawContext => {\n hooks.onResponse?.(scope, options, response);\n return response;\n };\n\n const conversationId = opt<string>(options, 'conversation_id', 'conversationId');\n const skipServerSt = conversationId ? hooks.skipServerShortTerm?.(conversationId) === true : false;\n\n const network = async (): Promise<RawContext> => {\n const { endpoint, body } = buildFetchRequest(\n scope,\n skipServerSt ? { ...options, include_conversation_context: false } : options,\n );\n const result = await transport.request<Json>(endpoint, { body });\n // The wrapper returned `result.context || {}`; preserve that exactly.\n return applyResponseShape((result?.['context'] as RawContext) ?? {}, responseShape);\n };\n\n // Awaited: matching by meaning embeds the query with the local model first.\n const anticipated = summaryMode ? null : (await hooks.beforeFetch?.(scope, options)) ?? null;\n if (anticipated !== null && anticipated.borderline) {\n // A borderline match races the server: its answer if in time, the cached\n // one if not. A late server call finishes unobserved.\n const pending = network();\n pending.catch(() => undefined);\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<null>((resolve) => {\n timer = setTimeout(() => resolve(null), anticipated.raceDeadlineMs ?? 250);\n });\n const won = await Promise.race([pending.then((r) => r, () => null), late]);\n if (timer !== undefined) clearTimeout(timer);\n if (won !== null) {\n hooks.onAssembled?.(scope, options, won, startedAt);\n return finish(won);\n }\n }\n if (anticipated !== null) {\n hooks.onServedFromCache?.(scope, options, anticipated);\n hooks.onAssembled?.(scope, options, anticipated.response, startedAt);\n // A hit is items picked from several prefetched bundles, so a ranked hit\n // is ordered by each item's own rank_score.\n return finish(applyResponseShape(anticipated.response, responseShape));\n }\n\n const response = await network();\n hooks.onAssembled?.(scope, options, response, startedAt);\n return finish(response);\n}\n","/**\n * camelCase normalisers for the legacy top-level methods.\n *\n * A faithful port of the normalisers in the removed `src/synap-client.js`,\n * including their quirks:\n *\n * - `score` and `source` on a memory item are passed through WITHOUT a\n * default, so `undefined` survives. Adding `?? 0` here would change the\n * shape consumers already branch on.\n * - `strength` falls back to `confidence`, `summary` falls back to `content`,\n * `intensity` falls back to `confidence`. Those fallbacks exist because the\n * server does not always send the specific field.\n * - `pickDefined` treats `null` as a real value and only skips `undefined`,\n * so an explicit server `null` is preserved rather than replaced.\n *\n * See gotcha G-B: this shape is one of two live shapes and must not converge\n * with the raw one before 2.0.\n */\n\nimport type {\n ConversationContext, ContextMetadata, Emotion, Episode, Fact, Json,\n NormalisedContext, Preference, RawContext, RawContextItem,\n RawConversationContext, RetrievalHealth, TemporalEvent, TemporalFields,\n} from './types.js';\n\n/** Returns the first argument that is not `undefined`. `null` counts as a value. */\nexport function pickDefined<T>(...values: (T | undefined)[]): T | undefined {\n for (const v of values) if (v !== undefined) return v;\n return undefined;\n}\n\nfunction pick<T>(...values: (T | undefined)[]): T {\n return pickDefined(...values) as T;\n}\n\nconst obj = (v: unknown): Json => (v as Json) ?? {};\n\n/** Always an array, so a caller can group by it without a null check. */\nfunction matchedQueries(item: RawContextItem = {}): string[] {\n const raw = item['matchedQueries'] ?? item.matched_queries;\n return Array.isArray(raw) ? (raw as string[]) : [];\n}\n\nfunction normalizeTemporalFields(item: RawContextItem = {}): TemporalFields {\n return {\n eventDate: pick(item['eventDate'] as string, item.event_date, null),\n eventEnd: pick(item['eventEnd'] as string, item.event_end as string, null),\n eventPrecision: pick(item['eventPrecision'] as string, item.event_precision as string, null),\n saidAt: pick(item['saidAt'] as string, item.said_at, null),\n validUntil: pick(item['validUntil'] as string, item.valid_until, null),\n temporalCategory: pick(item['temporalCategory'] as string, item.temporal_category, null),\n temporalConfidence: pick(item['temporalConfidence'] as number, item.temporal_confidence, 0),\n };\n}\n\nexport function normalizeFact(item: RawContextItem = {}): Fact {\n return {\n id: item.id || '',\n content: item.content || '',\n confidence: pick(item.confidence, 0),\n source: item.source || '',\n extractedAt: pick(item['extractedAt'] as string, item.extracted_at, null),\n metadata: obj(item.metadata),\n ...normalizeTemporalFields(item),\n matchedQueries: matchedQueries(item),\n };\n}\n\nexport function normalizePreference(item: RawContextItem = {}): Preference {\n return {\n id: item.id || '',\n category: (item['category'] as string) || '',\n content: item.content || '',\n strength: pick(item['strength'] as number, item.confidence, 0),\n source: item.source || '',\n extractedAt: pick(item['extractedAt'] as string, item.extracted_at, null),\n metadata: obj(item.metadata),\n ...normalizeTemporalFields(item),\n matchedQueries: matchedQueries(item),\n };\n}\n\nexport function normalizeEpisode(item: RawContextItem = {}): Episode {\n return {\n id: item.id || '',\n summary: pick(item['summary'] as string, item.content, ''),\n occurredAt: pick(item['occurredAt'] as string, item['occurred_at'] as string, null),\n significance: pick(item['significance'] as number, item.confidence, 0),\n participants: (item['participants'] as unknown[]) || [],\n metadata: obj(item.metadata),\n ...normalizeTemporalFields(item),\n matchedQueries: matchedQueries(item),\n };\n}\n\nexport function normalizeEmotion(item: RawContextItem = {}): Emotion {\n return {\n id: item.id || '',\n emotionType: pick(item['emotionType'] as string, item['emotion_type'] as string, ''),\n intensity: pick(item['intensity'] as number, item.confidence, 0),\n detectedAt: pick(item['detectedAt'] as string, item['detected_at'] as string, null),\n context: (item['context'] as string) || '',\n metadata: obj(item.metadata),\n ...normalizeTemporalFields(item),\n matchedQueries: matchedQueries(item),\n };\n}\n\nexport function normalizeTemporalEvent(item: RawContextItem = {}): TemporalEvent {\n return {\n id: item.id || '',\n content: item.content || '',\n eventDate: pick(item['eventDate'] as string, item.event_date, null),\n eventEnd: pick(item['eventEnd'] as string, item.event_end as string, null),\n eventPrecision: pick(item['eventPrecision'] as string, item.event_precision as string, null),\n saidAt: pick(item['saidAt'] as string, item.said_at, null),\n validUntil: pick(item['validUntil'] as string, item.valid_until, null),\n temporalCategory: pick(item['temporalCategory'] as string, item.temporal_category, ''),\n temporalConfidence: pick(item['temporalConfidence'] as number, item.temporal_confidence, 0),\n confidence: pick(item.confidence, 0),\n source: item.source || '',\n extractedAt: pick(item['extractedAt'] as string, item.extracted_at, null),\n metadata: obj(item.metadata),\n matchedQueries: matchedQueries(item),\n };\n}\n\nexport function normalizeContextMetadata(metadata: Json = {}): ContextMetadata {\n return {\n correlationId: pick(metadata['correlationId'] as string, metadata['correlation_id'] as string, ''),\n ttlSeconds: pick(metadata['ttlSeconds'] as number, metadata['ttl_seconds'] as number, 0),\n source: (metadata['source'] as string) || 'unknown',\n retrievedAt: pick(metadata['retrievedAt'] as string, metadata['retrieved_at'] as string, null),\n compactionApplied: pick(\n metadata['compactionApplied'] as boolean,\n metadata['compaction_applied'] as boolean,\n null,\n ),\n };\n}\n\nexport function normalizeConversationContext(\n value: RawConversationContext | null | undefined,\n): ConversationContext | null {\n if (!value) return null;\n return {\n summary: value.summary || null,\n currentState: pick(value['currentState'] as Json, value.current_state, {}),\n keyExtractions: pick(value['keyExtractions'] as Json, value.key_extractions, {}),\n recentTurns: pick(value['recentTurns'] as unknown[], value.recent_turns, []),\n compactionId: pick(value['compactionId'] as string, value.compaction_id, null),\n compactedAt: pick(value['compactedAt'] as string, value.compacted_at, null),\n conversationId: pick(value['conversationId'] as string, value.conversation_id, null),\n };\n}\n\nfunction normalizeRetrievalHealth(raw: unknown): RetrievalHealth | null {\n if (!raw || typeof raw !== 'object') return null;\n const r = raw as Json;\n const warnings = r['warnings'];\n return {\n degraded: r['degraded'] === undefined ? true : Boolean(r['degraded']),\n level: (r['level'] as string) ?? null,\n code: (r['code'] as string) ?? null,\n warnings: Array.isArray(warnings) ? warnings.map((w) => String(w)) : [],\n };\n}\n\n/** Accepts either a bare context or a `{ context: ... }` envelope, as the wrapper did. */\nexport function normalizeContextResponse(result: Json = {}): NormalisedContext {\n const context = (result['context'] as RawContext) ?? (result as RawContext);\n return {\n facts: (context.facts || []).map((i) => normalizeFact(i)),\n preferences: (context.preferences || []).map((i) => normalizePreference(i)),\n episodes: (context.episodes || []).map((i) => normalizeEpisode(i)),\n emotions: (context.emotions || []).map((i) => normalizeEmotion(i)),\n temporalEvents: (\n pick(context['temporalEvents'] as RawContextItem[], context.temporal_events, []) || []\n ).map((i) => normalizeTemporalEvent(i)),\n conversationContext: normalizeConversationContext(\n pick(\n context['conversationContext'] as RawConversationContext,\n context.conversation_context,\n null,\n ),\n ),\n metadata: normalizeContextMetadata(obj(context.metadata)),\n // `retrieval` is a SIBLING of `context` in the body, so it is read off the\n // envelope first and only then off a bare context. Reading it from\n // `context` alone is how the Python SDK dropped it.\n retrieval: normalizeRetrievalHealth(\n pick((result as Json)['retrieval'] as Json, (context as Json)['retrieval'] as Json, null),\n ),\n rawResponse: pick(context['rawResponse'] as Json, context['raw_response'] as Json, {}),\n // Only for a ranked fetch, so a by-type result has exactly the keys it had.\n ...(Array.isArray(context.items)\n ? { items: context.items, excerpts: Array.isArray(context.excerpts) ? context.excerpts : [] }\n : {}),\n };\n}\n","/**\n * Flatten typed context collections into one memory list.\n *\n * A faithful port of `flatten_context_items` from the 0.3.x bridge, which is\n * what `searchMemory` and `getMemories` returned. The per-type asymmetries are\n * deliberate and are reproduced exactly:\n *\n * - `memory` comes from a different field per type: fact/preference/temporal\n * event use `content`, episode uses `summary`, emotion uses `context`.\n * - `score` likewise: fact -> confidence, preference -> strength,\n * episode -> significance, emotion -> intensity, temporal event ->\n * temporal_confidence.\n * - **episode and emotion carry no `source` key at all.** The bridge simply\n * did not set one. Adding it would be an improvement and a shape change, so\n * it stays absent.\n * - Order is facts, preferences, episodes, emotions, temporal events.\n */\n\nimport type { Json, RawContext, RawContextItem } from './types.js';\n\nexport interface FlatMemory {\n id: string;\n memory: string;\n score: number;\n /** Absent for episodes and emotions, matching the 0.3.x bridge. */\n source?: string;\n metadata: Json;\n context_type: 'fact' | 'preference' | 'episode' | 'emotion' | 'temporal_event';\n event_date: string | null;\n /** See `TemporalFields.saidAt` in ./types. */\n said_at: string | null;\n valid_until: string | null;\n temporal_category: string | null;\n temporal_confidence: number;\n}\n\nconst s = (v: unknown): string => (typeof v === 'string' ? v : v == null ? '' : String(v));\nconst n = (v: unknown, d = 0): number => (typeof v === 'number' ? v : d);\nconst o = (v: unknown): Json => (v as Json) ?? {};\n/** The bridge stringified datetimes and mapped falsy to null. */\nconst dt = (v: unknown): string | null => (v ? String(v) : null);\n\nfunction temporal(item: RawContextItem) {\n return {\n event_date: dt(item['event_date']),\n said_at: dt(item['said_at']),\n valid_until: dt(item['valid_until']),\n temporal_category: (item['temporal_category'] as string | null) ?? null,\n temporal_confidence: n(item['temporal_confidence'], 0),\n };\n}\n\nexport function flattenContextItems(context: RawContext): FlatMemory[] {\n const items: FlatMemory[] = [];\n\n for (const f of context.facts ?? []) {\n items.push({\n id: s(f['id']), memory: s(f['content']), score: n(f['confidence']),\n source: s(f['source']), metadata: o(f['metadata']),\n context_type: 'fact', ...temporal(f),\n });\n }\n for (const p of context.preferences ?? []) {\n items.push({\n id: s(p['id']), memory: s(p['content']), score: n(p['strength']),\n source: s(p['source']), metadata: o(p['metadata']),\n context_type: 'preference', ...temporal(p),\n });\n }\n for (const e of context.episodes ?? []) {\n // No `source`: the bridge did not set one for episodes.\n items.push({\n id: s(e['id']), memory: s(e['summary']), score: n(e['significance']),\n metadata: o(e['metadata']), context_type: 'episode', ...temporal(e),\n });\n }\n for (const m of context.emotions ?? []) {\n // No `source` here either, and `memory` comes from `context`, not `content`.\n items.push({\n id: s(m['id']), memory: s(m['context']), score: n(m['intensity']),\n metadata: o(m['metadata']), context_type: 'emotion', ...temporal(m),\n });\n }\n for (const t of context.temporal_events ?? []) {\n items.push({\n id: s(t['id']), memory: s(t['content']), score: n(t['temporal_confidence']),\n source: s(t['source']), metadata: o(t['metadata']),\n context_type: 'temporal_event', ...temporal(t),\n });\n }\n\n return items;\n}\n","/**\n * Content parts: text and files (today, images) carried by `memories.create`,\n * `conversation.record_message` and `instance.send_message`.\n *\n * Mirrors `TextPart`, `FilePart` and `AttachmentResult` in the Python SDK.\n *\n * ## A text-only list is a string\n *\n * Every existing call has to keep sending exactly the bytes it sends today, so\n * a list with no file in it is joined with `\"\\n\"` and sent as that one string,\n * down the same route a string always took. Only a file changes the shape of a\n * request.\n *\n * ## Runs everywhere\n *\n * Nothing here imports a node builtin at the top level. Reading a `path` uses a\n * lazy `import('node:fs/promises')`, the same as `create_from_file`, and base64\n * uses `Buffer` when the runtime has it and `btoa` when it does not, so the main\n * entry stays safe on Edge, Workers and in a browser.\n */\n\nimport { InvalidInputError } from '../errors.js';\n\n/**\n * What the caller is asking a memory to do. Stored with the ingestion as\n * metadata; any other string is accepted too. Mirrors Python's `OBJECTIVES`.\n */\nexport const OBJECTIVES = [\n 'conversation', 'bootstrap', 'knowledge-base', 'record', 'profile',\n] as const;\nexport type Objective = (typeof OBJECTIVES)[number];\n\n/** Each file, however it is supplied. Larger is refused before anything is sent. */\nexport const MAX_FILE_BYTES = 10 * 1024 * 1024;\n/**\n * Total raw image bytes one `instance.send_message` event may carry. The gRPC\n * stream's message limit is 4 MB and base64 adds a third, so 2.5 MB of raw\n * bytes is what fits with room for the rest of the event.\n */\nexport const MAX_STREAM_IMAGE_BYTES = 2.5 * 1024 * 1024;\n/** A `url` part is fetched by the SDK, never by the server. */\nexport const URL_FETCH_TIMEOUT_MS = 30_000;\n\n/** Raw bytes for a `FilePart`. A Node `Buffer` is a `Uint8Array`. */\nexport type FileData = Uint8Array | ArrayBuffer | Blob;\n\nexport interface TextPart {\n type: 'text';\n text: string;\n}\n\n/**\n * A file. Exactly one of `data`, `path` or `url`.\n *\n * Build one with `filePart()`, which fills `filename` and `media_type`. A\n * literal `{ type: 'file', ... }` works too; the same defaults are applied when\n * it is sent.\n */\nexport interface FilePart {\n type: 'file';\n data?: FileData;\n /** Node only: read from disk when the call is made. */\n path?: string;\n /** Fetched by the SDK when the call is made (30 s, at most 10 MB). */\n url?: string;\n /** Defaults to the basename of `path` or `url`, else `\"file\"`. */\n filename?: string;\n /** Defaults to a guess from `filename`, else `\"application/octet-stream\"`. */\n media_type?: string;\n}\n\nexport interface FilePartInit {\n data?: FileData | null;\n path?: string | null;\n url?: string | null;\n filename?: string | null;\n media_type?: string | null;\n mediaType?: string | null;\n}\n\n/** One item of a content list. A bare string is a text part. */\nexport type ContentPart = string | TextPart | FilePart;\n\n/**\n * What the server did with one file of a `memories.create` call, in the order\n * the files were sent. Mirrors Python's `AttachmentResult`.\n */\nexport interface AttachmentResult {\n filename: string;\n media_type: string;\n status: 'read' | 'failed' | string;\n error?: string | null;\n}\n\n/**\n * Marks an object made by `textPart()` or `filePart()`.\n *\n * A plain object passed as `document` has always been a dict document, sent\n * untouched, and one may well carry `type: \"text\"` of its own. So at the top\n * level only a branded object is read as a part; inside a list (never valid\n * before parts existed) a plain `{ type: 'text' | 'file' }` is accepted too.\n * Non-enumerable, so it never reaches JSON or a deep-equality check, and\n * `Symbol.for` so two copies of the SDK (ESM and CJS) recognise each other's.\n */\nconst PART_BRAND = Symbol.for('@maximem/synap-js-sdk.ContentPart');\n\nfunction brand<T extends object>(part: T): T {\n Object.defineProperty(part, PART_BRAND, { value: true, enumerable: false });\n return part;\n}\n\nfunction isBranded(value: unknown): boolean {\n return typeof value === 'object' && value !== null && PART_BRAND in value;\n}\n\n/** `{ type: 'text', text }`. Mirrors Python's `TextPart(text)`. */\nexport function textPart(text: string): TextPart {\n if (typeof text !== 'string') throw new InvalidInputError('TextPart text must be a string');\n return brand({ type: 'text', text });\n}\n\n/**\n * A file part with its defaults filled in. Mirrors Python's `FilePart(...)`.\n *\n * Throws `InvalidInputError` unless exactly one of `data`, `path` or `url` is\n * given.\n */\nexport function filePart(init: FilePartInit): FilePart {\n const source = checkOneSource(init);\n const filename = defaultFilename(init, source);\n const mediaType =\n init.media_type ?? init.mediaType ?? defaultMediaType(filename, init.data ?? undefined);\n const part: FilePart = { type: 'file' };\n if (source === 'data') part.data = init.data as FileData;\n else if (source === 'path') part.path = init.path as string;\n else part.url = init.url as string;\n part.filename = filename;\n part.media_type = mediaType;\n return brand(part);\n}\n\nexport function isTextPart(value: unknown): value is TextPart {\n return isPlainPart(value) && value['type'] === 'text' && typeof value['text'] === 'string';\n}\n\nexport function isFilePart(value: unknown): value is FilePart {\n return isPlainPart(value) && value['type'] === 'file';\n}\n\nfunction isPlainPart(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\ntype Source = 'data' | 'path' | 'url';\n\nfunction checkOneSource(p: { data?: unknown; path?: unknown; url?: unknown }): Source {\n const given = (['data', 'path', 'url'] as const).filter(\n (k) => p[k] !== undefined && p[k] !== null,\n );\n if (given.length !== 1) {\n // Python's message, word for word.\n throw new InvalidInputError(\n 'FilePart takes exactly one of data, path or url' +\n (given.length > 0 ? ` (got ${given.join(', ')})` : ''),\n );\n }\n return given[0]!;\n}\n\nfunction lastSegment(p: string): string {\n const parts = p.split(/[\\\\/]/);\n return parts[parts.length - 1] ?? '';\n}\n\nfunction defaultFilename(\n p: { data?: unknown; path?: unknown; url?: unknown; filename?: string | null },\n source: Source,\n): string {\n if (p.filename) return p.filename;\n if (source === 'path') return lastSegment(String(p.path)) || 'file';\n if (source === 'url') {\n let pathname = '';\n try {\n pathname = new URL(String(p.url)).pathname;\n } catch {\n pathname = String(p.url).split(/[?#]/)[0] ?? '';\n }\n return lastSegment(pathname) || 'file';\n }\n // A browser `File` carries its own name. Python bytes cannot, so this only\n // ever fills a gap Python leaves as \"file\".\n const named = (p.data as { name?: unknown } | undefined)?.name;\n return typeof named === 'string' && named ? named : 'file';\n}\n\n/**\n * Python's table (png, jpg, jpeg, webp, gif, pdf) plus what its\n * `mimetypes.guess_type` answers for other common extensions. Case-insensitive,\n * as Python's is. The server sniffs image bytes regardless, so a wrong or\n * missing guess is corrected there, never trusted.\n */\nconst MEDIA_TYPES: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n jpe: 'image/jpeg',\n webp: 'image/webp',\n gif: 'image/gif',\n bmp: 'image/bmp',\n tif: 'image/tiff',\n tiff: 'image/tiff',\n svg: 'image/svg+xml',\n pdf: 'application/pdf',\n txt: 'text/plain',\n csv: 'text/csv',\n htm: 'text/html',\n html: 'text/html',\n json: 'application/json',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n mp3: 'audio/mpeg',\n wav: 'audio/x-wav',\n mp4: 'video/mp4',\n};\n\nexport function guessMediaType(filename: string): string | null {\n const dot = filename.lastIndexOf('.');\n // Python's splitext gives \".png\" no extension, so neither does this.\n if (dot <= 0) return null;\n const ext = filename.slice(dot + 1).toLowerCase();\n return MEDIA_TYPES[ext] ?? null;\n}\n\nfunction defaultMediaType(filename: string, data?: unknown): string {\n const guessed = guessMediaType(filename);\n if (guessed !== null) return guessed;\n const blobType = (data as { type?: unknown } | undefined)?.type;\n return typeof blobType === 'string' && blobType ? blobType : DEFAULT_MEDIA_TYPE;\n}\n\n/**\n * The outcome of normalising a content value.\n *\n * `text`: send this string exactly as a string always was sent.\n * `parts`: at least one file; strings have become text parts, in order.\n */\nexport type Normalised =\n | { kind: 'text'; text: string }\n | { kind: 'parts'; parts: Array<TextPart | FilePart> };\n\n/**\n * Normalise a part, or a list of parts, for the field named `field`.\n *\n * Returns null for anything that is neither: a string, or a dict document,\n * which the caller passes through untouched so its bytes do not change. A\n * single part counts only when `textPart()` or `filePart()` made it; a plain\n * object is a dict, as it always was.\n */\nexport function normaliseContent(value: unknown, field: string): Normalised | null {\n if (isBranded(value) && isTextPart(value)) return { kind: 'text', text: value.text };\n if (isBranded(value) && isFilePart(value)) return { kind: 'parts', parts: [value] };\n if (!Array.isArray(value)) return null;\n if (value.length === 0) {\n // Explicit: an empty array is truthy, so the `!document` check that\n // guards a string never sees it.\n throw new InvalidInputError(`${field} is an empty list; pass at least one part`);\n }\n const parts: Array<TextPart | FilePart> = value.map((item, i) => {\n if (typeof item === 'string') return { type: 'text', text: item };\n if (isTextPart(item) || isFilePart(item)) return item;\n throw new InvalidInputError(\n `${field}[${i}] is a ${typeName(item)}; expected a string, TextPart or FilePart`,\n );\n });\n if (!parts.some(isFilePart)) {\n return { kind: 'text', text: parts.map((p) => (p as TextPart).text).join('\\n') };\n }\n return { kind: 'parts', parts };\n}\n\nfunction typeName(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n if (typeof value === 'object') {\n return (value as { constructor?: { name?: string } }).constructor?.name ?? 'object';\n }\n return typeof value;\n}\n\n/** A file's resolved name, type and bytes. */\nexport interface ResolvedFile {\n filename: string;\n media_type: string;\n bytes: Uint8Array;\n}\n\n/**\n * Read a file part's bytes: from `data`, from disk, or over HTTP.\n *\n * `fetchImpl` is the transport's fetch, so a test or a proxying caller sees\n * the request. It is called with no Synap credentials: the URL belongs to\n * somebody else.\n */\nexport async function resolveFile(part: FilePart, fetchImpl: typeof fetch): Promise<ResolvedFile> {\n const source = checkOneSource(part);\n const filename = defaultFilename(part, source);\n let mediaType = part.media_type || defaultMediaType(filename, part.data);\n\n let bytes: Uint8Array;\n if (source === 'data') {\n bytes = await toBytes(part.data as FileData);\n } else if (source === 'path') {\n // Lazy, so importing the SDK on Edge or in a Worker stays safe: a\n // top-level `node:fs` import fails the BUILD there, not the call.\n const { readFile } = await import('node:fs/promises');\n try {\n bytes = new Uint8Array(await readFile(part.path as string));\n } catch (error) {\n throw new InvalidInputError(\n `Could not read FilePart path '${part.path}': ${(error as Error)?.message ?? String(error)}`,\n { cause: error },\n );\n }\n } else {\n const fetched = await fetchUrl(part.url as string, fetchImpl);\n bytes = fetched.bytes;\n // The filename said nothing useful, so trust what the server said, as\n // Python does.\n if (mediaType === DEFAULT_MEDIA_TYPE && fetched.contentType) mediaType = fetched.contentType;\n }\n if (bytes.byteLength > MAX_FILE_BYTES) {\n throw new InvalidInputError(\n `${filename} is ${bytes.byteLength} bytes; the limit is ${MAX_FILE_BYTES} bytes per file`,\n );\n }\n return { filename, media_type: mediaType, bytes };\n}\n\nconst DEFAULT_MEDIA_TYPE = 'application/octet-stream';\n\nfunction urlTooLarge(url: string): string {\n return `FilePart url '${url}' is over the limit of ${MAX_FILE_BYTES} bytes per file`;\n}\n\nasync function toBytes(data: FileData): Promise<Uint8Array> {\n if (data instanceof Uint8Array) return data;\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n if (ArrayBuffer.isView(data)) {\n const view = data as ArrayBufferView;\n return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n }\n if (typeof Blob !== 'undefined' && data instanceof Blob) {\n return new Uint8Array(await data.arrayBuffer());\n }\n throw new InvalidInputError('FilePart data must be a Uint8Array, ArrayBuffer or Blob');\n}\n\n/** GET a URL, at most 10 MB, within 30 s. Every failure is the caller's input. */\nexport async function fetchUrlBytes(url: string, fetchImpl: typeof fetch): Promise<Uint8Array> {\n return (await fetchUrl(url, fetchImpl)).bytes;\n}\n\nasync function fetchUrl(\n url: string,\n fetchImpl: typeof fetch,\n): Promise<{ bytes: Uint8Array; contentType: string | null }> {\n let scheme = '';\n try {\n scheme = new URL(url).protocol;\n } catch {\n throw new InvalidInputError(`Could not fetch FilePart url '${url}': not a valid URL`);\n }\n // What httpx supports, so the same URLs fail in both SDKs.\n if (scheme !== 'http:' && scheme !== 'https:') {\n throw new InvalidInputError(\n `Could not fetch FilePart url '${url}': only http and https are supported`,\n );\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), URL_FETCH_TIMEOUT_MS);\n try {\n const response = await fetchImpl(url, { method: 'GET', signal: controller.signal });\n if (response.status < 200 || response.status >= 300) {\n throw new InvalidInputError(\n `Fetching FilePart url '${url}' returned HTTP ${response.status}`,\n );\n }\n const declared = Number(response.headers.get('content-length') ?? '');\n if (Number.isFinite(declared) && declared > MAX_FILE_BYTES) {\n throw new InvalidInputError(urlTooLarge(url));\n }\n const bytes = await readCapped(response, url);\n const rawType = response.headers.get('content-type');\n const contentType = rawType ? rawType.split(';', 1)[0]!.trim().toLowerCase() || null : null;\n return { bytes, contentType };\n } catch (error) {\n if (error instanceof InvalidInputError) throw error;\n if (controller.signal.aborted) {\n throw new InvalidInputError(\n `Could not fetch FilePart url '${url}': timed out after ${URL_FETCH_TIMEOUT_MS / 1000} s`,\n { cause: error },\n );\n }\n throw new InvalidInputError(\n `Could not fetch FilePart url '${url}': ${(error as Error)?.message ?? String(error)}`,\n { cause: error },\n );\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Stops reading as soon as the body passes the cap, rather than buffering all of it. */\nasync function readCapped(response: Response, url: string): Promise<Uint8Array> {\n const body = response.body;\n if (body === null || typeof body.getReader !== 'function') {\n return new Uint8Array(await response.arrayBuffer());\n }\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > MAX_FILE_BYTES) {\n await reader.cancel().catch(() => {});\n throw new InvalidInputError(urlTooLarge(url));\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let at = 0;\n for (const c of chunks) {\n out.set(c, at);\n at += c.byteLength;\n }\n return out;\n}\n\n/** Standard base64. `Buffer` where there is one, chunked `btoa` everywhere else. */\nexport function toBase64(bytes: Uint8Array): string {\n const B = (globalThis as { Buffer?: { from(b: Uint8Array): { toString(enc: string): string } } })\n .Buffer;\n if (B !== undefined) return B.from(bytes).toString('base64');\n let binary = '';\n const CHUNK = 0x8000;\n for (let i = 0; i < bytes.length; i += CHUNK) {\n binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));\n }\n return btoa(binary);\n}\n\n/** `{type: \"text\", text}` on the wire. */\nexport interface WireTextPart {\n type: 'text';\n text: string;\n}\n\n/** A file in a `memories.create` multipart manifest; its bytes are the form field `field`. */\nexport interface WireFilePart {\n type: 'file';\n field: string;\n filename: string;\n media_type: string;\n}\n\n/** A file carried inline as base64 (record_message JSON, the gRPC metadata key). */\nexport interface WireImagePart {\n type: 'image';\n filename: string;\n media_type: string;\n data: string;\n}\n\n/**\n * What an image becomes in text where it cannot be read: `[image: <filename>]`.\n * Text parts stay as they are and the pieces are joined with `\"\\n\"`.\n */\nexport function placeholderText(parts: Array<{ type: string; text?: string; filename?: string }>): string {\n return parts\n .map((p) => (p.type === 'text' ? String(p.text ?? '') : `[image: ${p.filename || 'image'}]`))\n .join('\\n');\n}\n\nexport interface InlineParts {\n /** Text and inline-image wire parts, in order. */\n wire: Array<WireTextPart | WireImagePart>;\n /** The placeholder rendering of `wire`. */\n placeholder: string;\n /** Raw bytes across every file, before base64. */\n rawBytes: number;\n}\n\n/** Read every file (concurrently, order kept) and inline it as base64. */\nexport async function toInlineParts(\n parts: Array<TextPart | FilePart>,\n fetchImpl: typeof fetch,\n): Promise<InlineParts> {\n const resolved = await Promise.all(\n parts.map((p) => (isFilePart(p) ? resolveFile(p, fetchImpl) : null)),\n );\n let rawBytes = 0;\n const wire = parts.map((p, i): WireTextPart | WireImagePart => {\n const file = resolved[i];\n if (file === null || file === undefined) return { type: 'text', text: (p as TextPart).text };\n rawBytes += file.bytes.byteLength;\n return {\n type: 'image',\n filename: file.filename,\n media_type: file.media_type,\n data: toBase64(file.bytes),\n };\n });\n return { wire, placeholder: placeholderText(wire), rawBytes };\n}\n","/**\n * Memories namespace. Mirrors `maximem_synap.memories.interface.MemoriesInterface`.\n *\n * ## The request body is built the way Python builds it, on purpose\n *\n * Python constructs a pydantic `CreateMemoryRequest` and posts\n * `model_dump(mode=\"json\")`, which emits **every** field, nulls included, with\n * defaults applied. It is tempting to omit unset keys instead and send a\n * tidier body. Do not: the server sees a different request, and the difference\n * that matters most is `document_type`.\n *\n * `document_type` defaults to `\"ai-chat-conversation\"`. Leaving it off is not\n * neutral, because the extraction path is type-dependent and the\n * `\"document\"` type extracts dramatically less from the same text. A body that\n * merely looks cleaner is how you get \"the JS SDK stores fewer memories than\n * the Python one from identical input\", which is slow and miserable to\n * diagnose.\n */\n\nimport { InvalidInputError } from '../errors.js';\nimport type { HttpTransport } from '../transport/http.js';\nimport type { Json } from '../context/types.js';\nimport {\n isFilePart, normaliseContent, resolveFile,\n type AttachmentResult, type FilePart, type Objective, type TextPart, type WireFilePart,\n type WireTextPart,\n} from './parts.js';\n\n/**\n * What `new Blob([...])` accepts here.\n *\n * Derived from the Blob constructor rather than written out, because `BlobPart`\n * lives in the DOM lib, which this package deliberately does not include, and\n * Node's own Blob accepts a slightly narrower set than the DOM's. Deriving it\n * means this keeps compiling if either definition shifts.\n */\ntype BlobSource = NonNullable<ConstructorParameters<typeof Blob>[0]>[number];\n\n/** Mirrors the Python DocumentType enum. */\nexport const DOCUMENT_TYPES = [\n 'ai-chat-conversation', 'document', 'email', 'pdf', 'image', 'audio', 'meeting-transcript',\n] as const;\nexport type DocumentType = (typeof DOCUMENT_TYPES)[number];\n\n/** Mirrors the Python IngestMode enum. */\nexport const INGEST_MODES = ['fast', 'long-range'] as const;\nexport type IngestMode = (typeof INGEST_MODES)[number];\n\nexport const DEFAULT_DOCUMENT_TYPE: DocumentType = 'ai-chat-conversation';\nexport const DEFAULT_INGEST_MODE: IngestMode = 'long-range';\n\n/**\n * What `memories.create` takes as `document`. Mirrors Python's\n * `Union[str, Dict[str, Any], TextPart, FilePart, List[Union[str, TextPart, FilePart]]]`.\n *\n * A string, a dict, a `TextPart` or a list with no file in it is sent as JSON\n * to `/create`, byte for byte as a string always was (a list is joined with\n * `\"\\n\"`). Any `FilePart` sends the call as multipart to `/create-multipart`.\n */\nexport type CreateDocument =\n | string\n | Record<string, unknown>\n | TextPart\n | FilePart\n | Array<string | TextPart | FilePart>;\n\nexport interface CreateMemoryOptions {\n document: CreateDocument;\n user_id?: string | null;\n userId?: string | null;\n customer_id?: string | null;\n customerId?: string | null;\n document_type?: DocumentType | string;\n documentType?: DocumentType | string;\n document_id?: string | null;\n documentId?: string | null;\n /** ISO-8601 string or Date. Serialised the way Python serialises a datetime. */\n document_created_at?: string | Date | null;\n documentCreatedAt?: string | Date | null;\n mode?: IngestMode | string;\n metadata?: Json;\n /**\n * The level this memory belongs to, named in full, one entry per level down\n * to it: `{ customer: \"acme\", team: \"payments\", user: \"dana\" }`.\n *\n * Only needed by an account whose scope ladder has a level between its\n * customer and its user levels. `user_id` and `customer_id` cannot say which\n * one a write belongs to, so on such a ladder the server refuses the write\n * rather than guessing: a wrong guess at or above the customer level crosses\n * a tenant boundary.\n *\n * Omit it and nothing changes. Sending one to an account without nested\n * scoping is an error rather than ignored, because a caller who asks to be\n * narrowed and is ignored gets widened instead.\n */\n scope?: Record<string, string> | null;\n /**\n * What this memory is for. One of `OBJECTIVES` (`conversation`, `bootstrap`,\n * `knowledge-base`, `record`, `profile`) or free text, at most 500\n * characters. Sent only when set, so a call without it is unchanged.\n */\n objective?: Objective | string | null;\n}\n\n/**\n * Mirrors Python's `CreateMemoryResponse`.\n *\n * The first four fields are required there (Pydantic would raise if the server\n * omitted one), so they are required here too. Declaring `ingestion_id` optional\n * made the commonest two-line pattern in the docs fail to compile under strict\n * TypeScript: `wait_for_completion(result.ingestion_id)` cannot take\n * `string | undefined`.\n */\nexport interface CreateMemoryResult {\n ingestion_id: string;\n document_id: string;\n status: string;\n /** ISO-8601. Python types this as a datetime. */\n queued_at: string;\n error_message?: string | null;\n memories_created?: number;\n /**\n * One per file part, in order, when the call carried files. Absent\n * otherwise. A file that could not be read is still `failed` here while the\n * rest of the document was ingested.\n */\n attachments?: AttachmentResult[] | null;\n [key: string]: unknown;\n}\n\nfunction either<T>(o: Record<string, unknown>, snake: string, camel: string): T | undefined {\n const a = o[snake];\n if (a !== undefined) return a as T;\n const b = o[camel];\n return b === undefined ? undefined : (b as T);\n}\n\nfunction isoOrNull(v: string | Date | null | undefined): string | null {\n if (v === undefined || v === null) return null;\n return v instanceof Date ? v.toISOString() : v;\n}\n\n/**\n * The fields every create carries besides `document`, validated, in the\n * pydantic model's order. `documentType` is null only for the multipart\n * manifest, where an unset type is sent as null and the server picks.\n */\nfunction createFields(options: CreateMemoryOptions, defaultType: string | null): Json {\n const o = options as unknown as Record<string, unknown>;\n const documentType = either<string>(o, 'document_type', 'documentType') ?? defaultType;\n const mode = (options.mode as string) ?? DEFAULT_INGEST_MODE;\n\n // Validated client-side because Python's enum coercion raises before any\n // request is sent. A silent pass-through would turn a typo into a server\n // error, or worse, a silently different extraction path.\n if (documentType !== null && !(DOCUMENT_TYPES as readonly string[]).includes(documentType)) {\n throw new InvalidInputError(\n `Invalid document_type '${documentType}'. Expected one of: ${DOCUMENT_TYPES.join(', ')}`,\n );\n }\n if (!(INGEST_MODES as readonly string[]).includes(mode)) {\n throw new InvalidInputError(\n `Invalid mode '${mode}'. Expected one of: ${INGEST_MODES.join(', ')}`,\n );\n }\n const userId = either<string>(o, 'user_id', 'userId') ?? null;\n const customerId = either<string>(o, 'customer_id', 'customerId') ?? null;\n\n // Key order matches the pydantic model's field order. Not semantically\n // required, but it makes a captured-body diff against Python readable.\n const fields: Json = {\n document_type: documentType,\n document_id: either<string>(o, 'document_id', 'documentId') ?? null,\n document_created_at: isoOrNull(\n either<string | Date>(o, 'document_created_at', 'documentCreatedAt'),\n ),\n user_id: userId,\n customer_id: customerId,\n // null, never `{}`. An empty path is not absence: the server treats one as\n // an error, because a caller asking to be narrowed and being ignored gets\n // widened instead.\n scope: normaliseCreateScope(options.scope, userId, customerId),\n mode,\n metadata: options.metadata ?? {},\n };\n // Only when set, so every existing body stays byte-identical.\n if (options.objective !== undefined && options.objective !== null) {\n fields['objective'] = options.objective;\n }\n return fields;\n}\n\n/**\n * `scope: { client: \"self\" }` names the client level, which is what a write\n * with no user_id and no customer_id already is. Mirrors Python's\n * `CreateMemoryRequest` validator.\n *\n * - On its own, it is sent as `scope: null`, so the body is the one a call\n * without it sends.\n * - With a user_id or customer_id, it is a contradiction, refused.\n * - `\"self\"` under any key alongside other entries is refused.\n * - Every other use of a `client` key is passed through untouched.\n */\nexport function normaliseCreateScope(\n scope: Record<string, string> | null | undefined,\n userId: string | null,\n customerId: string | null,\n): Record<string, string> | null {\n if (scope === undefined || scope === null) return null;\n const entries = Object.entries(scope);\n if (entries.length > 1 && entries.some(([, v]) => v === 'self')) {\n throw new InvalidInputError(\n `\"self\" can only be used alone, as scope={\"client\": \"self\"}; got ${JSON.stringify(scope)}`,\n );\n }\n if (entries.length === 1 && entries[0]![0] === 'client' && entries[0]![1] === 'self') {\n // Python checks `is not None`, so an empty-string id counts as given.\n if (userId !== null || customerId !== null) {\n throw new InvalidInputError(\n 'scope={\"client\": \"self\"} names the client level, so it ' +\n 'cannot be combined with user_id or customer_id',\n );\n }\n return null;\n }\n return scope;\n}\n\n/** What `document` becomes on the JSON route: a string, or a dict untouched. */\nfunction jsonDocument(document: unknown, where: string): unknown {\n const n = normaliseContent(document, 'document');\n if (n === null) return document;\n if (n.kind === 'parts') {\n throw new InvalidInputError(\n `${where} cannot carry a FilePart. memories.create sends files as multipart; ` +\n 'call it once per document that has files.',\n );\n }\n return n.text;\n}\n\n/**\n * Byte-for-byte equivalent of Python's `CreateMemoryRequest.model_dump(mode=\"json\")`.\n *\n * Takes the JSON-route shapes only: a string, a dict, a `TextPart`, or a list\n * with no file in it (joined with `\"\\n\"`). A `FilePart` throws; it is sent by\n * `memories.create` as multipart, built by `buildCreateManifest`.\n */\nexport function buildCreateBody(options: CreateMemoryOptions): Json {\n const document = jsonDocument(options.document, 'This request');\n if (!document) throw new InvalidInputError('document is required');\n return { document, ...createFields(options, DEFAULT_DOCUMENT_TYPE) };\n}\n\n/**\n * The `manifest` form field of a multipart create, before any file is read.\n *\n * `document` lists the parts in order; file `i` (counting files only) is the\n * form field `file_<i>`. `document_type` is null unless the caller set it.\n */\nexport function buildCreateManifest(\n options: CreateMemoryOptions,\n parts: Array<TextPart | FilePart>,\n files: Array<{ filename: string; media_type: string }>,\n): Json {\n let next = 0;\n const document = parts.map((p): WireTextPart | WireFilePart => {\n if (!isFilePart(p)) return { type: 'text', text: (p as TextPart).text };\n const index = next++;\n const file = files[index]!;\n return { type: 'file', field: `file_${index}`, filename: file.filename, media_type: file.media_type };\n });\n return { document, ...createFields(options, null) };\n}\n\n/**\n * Result of `memories.batch_create`, mirroring Python's `BatchCreateResponse`.\n * It was `Json`, so `results` came back as `unknown` and could not be iterated.\n */\nexport interface BatchCreateResult {\n batch_id: string;\n total: number;\n succeeded: number;\n failed: number;\n results: CreateMemoryResult[];\n [key: string]: unknown;\n}\n\nexport interface BatchCreateOptions {\n documents: CreateMemoryOptions[];\n fail_fast?: boolean;\n failFast?: boolean;\n}\n\n/** Mirrors the Python ForgetMode enum. */\nexport const FORGET_MODES = ['preview', 'direct'] as const;\nexport type ForgetMode = (typeof FORGET_MODES)[number];\n\nexport const FORGET_DESCRIPTION_MIN = 3;\nexport const FORGET_DESCRIPTION_MAX = 500;\n\nexport interface ForgetOptions {\n /** What to forget, in the user's own words (3 to 500 characters). */\n description: string;\n user_id?: string | null;\n userId?: string | null;\n customer_id?: string | null;\n customerId?: string | null;\n /**\n * The level to search, named in full, one entry per level down to it:\n * `{ customer: \"acme\", team: \"payments\", user: \"dana\" }`. Only needed when\n * your scope ladder has a level between customer and user.\n */\n scope?: Record<string, string> | null;\n /** `\"preview\"` (default) or `\"direct\"`. See `MemoriesInterface.forget`. */\n mode?: ForgetMode | string;\n /**\n * The conversation this request is made in (1 to 200 characters). Used only\n * by `mode: \"direct\"`. Pass it when you record the conversation through the\n * SDK's listening stream (gRPC): messages on that path are saved in batches,\n * so what the user just said may not exist as a memory yet. With the id, the\n * request also stays open until the batch of that conversation that holds it\n * has been saved and checked, whether or not the search finds something now,\n * and removes what it describes then (`retry_scheduled` is true). Without it,\n * the request is answered once (`nothing_matches` if nothing is found) and\n * nothing waits. Not needed for `memories.create()`.\n */\n conversation_id?: string | null;\n conversationId?: string | null;\n}\n\n/** A memory the description matched. Mirrors Python's `ForgetCandidate`. */\nexport interface ForgetCandidate {\n memory_id: string;\n content: string;\n memory_type?: string | null;\n /** `\"memory\"`, or where a copy lives: chunk, sentence, entity, triple, profile, candidate. */\n store?: string;\n}\n\nexport type ForgetStatus = 'nothing_matches' | 'preview' | 'deleted' | 'partial';\n\n/** Result of `memories.forget`. Mirrors Python's `ForgetResponse`. */\nexport interface ForgetResult {\n status: ForgetStatus;\n request_id: string | null;\n candidates: ForgetCandidate[];\n deleted_ids: string[];\n failed_ids: string[];\n still_present_in: string[];\n may_be_incomplete: boolean;\n /**\n * True when a `direct` request named its `conversation_id` and stays open until\n * the batch of that conversation that holds it has been saved and checked,\n * whether or not the search found something now. Absent from servers that\n * predate it; read it as false.\n */\n retry_scheduled?: boolean;\n}\n\n/** The body Python builds for `memories.forget`, key order included. */\nexport function buildForgetBody(options: ForgetOptions): Json {\n const description = options.description;\n if (\n typeof description !== 'string' ||\n // Code points, as Python's len() and the server count; `.length` counts\n // UTF-16 units, so 251 emoji (502 units) were refused here only.\n [...description].length < FORGET_DESCRIPTION_MIN ||\n [...description].length > FORGET_DESCRIPTION_MAX\n ) {\n throw new InvalidInputError(\n `description must be between ${FORGET_DESCRIPTION_MIN} and ${FORGET_DESCRIPTION_MAX} characters`,\n );\n }\n const mode = (options.mode as string | undefined) ?? 'preview';\n if (!(FORGET_MODES as readonly string[]).includes(mode)) {\n throw new InvalidInputError(\n `Invalid mode '${mode}'. Expected one of: ${FORGET_MODES.join(', ')}`,\n );\n }\n const o = options as unknown as Record<string, unknown>;\n const body: Record<string, unknown> = {\n description,\n user_id: either<string>(o, 'user_id', 'userId') ?? null,\n customer_id: either<string>(o, 'customer_id', 'customerId') ?? null,\n scope: options.scope ?? null,\n mode,\n };\n // Sent only when given, as Python does, so a call without it is unchanged.\n const conversationId = either<string>(o, 'conversation_id', 'conversationId');\n if (conversationId !== undefined && conversationId !== null) {\n if (\n typeof conversationId !== 'string' ||\n [...conversationId].length < 1 ||\n [...conversationId].length > 200\n ) {\n throw new InvalidInputError('conversation_id must be a string of 1 to 200 characters');\n }\n body['conversation_id'] = conversationId;\n }\n return body as Json;\n}\n\nexport interface MemoriesInterface {\n create(options: CreateMemoryOptions): Promise<CreateMemoryResult>;\n batch_create(options: BatchCreateOptions): Promise<BatchCreateResult>;\n create_from_file(options: CreateFromFileOptions): Promise<CreateMemoryResult>;\n get(memoryId: string): Promise<Json>;\n update(options: UpdateMemoryOptions): Promise<Json>;\n delete(memoryId: string): Promise<Json>;\n /**\n * Forget memories by describing them in the user's own words. Use it when\n * you do not hold memory ids; to delete one memory by id, use `delete()`.\n *\n * The call must be scoped to exactly one user: pass `user_id`, plus\n * `customer_id` on a B2B instance. Otherwise the server answers 400, raised\n * as `InvalidInputError`.\n *\n * Modes:\n * - `\"preview\"` (default): files a pending request that a person approves in\n * the dashboard under Deletion requests. Deletes nothing. `candidates`\n * lists what matched.\n * - `\"direct\"`: finds and soft-deletes in one call. Not idempotent as a\n * request: a repeat is harmless and finds nothing new, but it is a new\n * request.\n *\n * `status` is `\"nothing_matches\"`, `\"preview\"`, `\"deleted\"` or `\"partial\"`.\n * `\"partial\"` means the memories are hidden but a store named in\n * `still_present_in` may still hold the text, so do not tell an end user it\n * was removed unless `status === \"deleted\"`. `failed_ids` lists memories that\n * could not be deleted; `may_be_incomplete` is true when the match may not\n * have covered everything.\n *\n * Errors: `InvalidInputError` for 400/422 or a bad `description`/`mode`\n * caught before sending; `ServiceUnavailableError` for 503 (the matcher was\n * unavailable and nothing was deleted, so trying again is safe; the\n * transport applies its normal retry policy first); `RateLimitError` for 429.\n */\n forget(options: ForgetOptions): Promise<ForgetResult>;\n status(ingestionId: string): Promise<Json>;\n wait_for_completion(ingestionId: string, options?: WaitOptions): Promise<Json>;\n}\n\n/**\n * Options for `create_from_file`.\n *\n * Exactly one of `file_path`, `file`, or `text` must be supplied, matching\n * Python. `file_path` reads from disk and so is Node-only; `file` takes a\n * Blob/File/Uint8Array and works anywhere, which is the portable route for\n * Edge and Workers.\n */\nexport interface CreateFromFileOptions {\n user_id?: string;\n userId?: string;\n customer_id?: string;\n customerId?: string;\n /** \"b2b\" or \"b2c\". Defaults to \"b2c\", as in Python. */\n relationship_type?: string;\n relationshipType?: string;\n /** Node-only: read this path from disk. Uses a lazy `node:fs` import. */\n file_path?: string;\n filePath?: string;\n /** Portable alternative to `file_path`. Pass `filename` alongside a raw buffer. */\n file?: Blob | Uint8Array | ArrayBuffer;\n filename?: string;\n /** Ingest raw text instead of a file. */\n text?: string;\n document_type?: string;\n documentType?: string;\n mode?: IngestMode | string;\n metadata?: Json;\n /**\n * The level this memory belongs to, named in full, one entry per level down\n * to it: `{ customer: \"acme\", team: \"payments\", user: \"dana\" }`.\n *\n * Only needed by an account whose scope ladder has a level between its\n * customer and its user levels. `user_id` and `customer_id` cannot say which\n * one a write belongs to, so on such a ladder the server refuses the write\n * rather than guessing: a wrong guess at or above the customer level crosses\n * a tenant boundary.\n *\n * Omit it and nothing changes. Sending one to an account without nested\n * scoping is an error rather than ignored, because a caller who asks to be\n * narrowed and is ignored gets widened instead.\n */\n scope?: Record<string, string> | null;\n}\n\nexport interface UpdateMemoryOptions {\n memory_id?: string;\n memoryId?: string;\n document: string;\n merge_strategy?: string;\n mergeStrategy?: string;\n document_type?: string;\n documentType?: string;\n metadata?: Json;\n}\n\nexport interface WaitOptions {\n /** Seconds. Matches Python's default. */\n timeout_seconds?: number;\n timeoutSeconds?: number;\n poll_interval_seconds?: number;\n pollIntervalSeconds?: number;\n signal?: AbortSignal;\n}\n\n// The server's statuses are queued, processing, completed, failed and\n// partial_success. Python stops on the last three; 'error' and 'cancelled' are\n// never emitted by the server and are kept only so an older value still stops.\nconst TERMINAL_STATUSES = new Set(['completed', 'failed', 'partial_success', 'error', 'cancelled']);\n\nexport function createMemoriesInterface(\n transport: HttpTransport,\n // Called after a forget that deleted something, so the caller can stop serving\n // that user's cached context. Mirrors Python's `_evict_forgotten`.\n onForgotten?: (ids: { userId: string | null; customerId: string | null }) => void,\n): MemoriesInterface {\n return {\n async create(options) {\n const o = options as unknown as Record<string, unknown>;\n const customerId = o['customer_id'] ?? o['customerId'];\n if (customerId !== undefined && customerId !== null && customerId !== '') {\n await transport.checkCustomerId(customerId, 'memories.create');\n }\n const n = normaliseContent(options.document, 'document');\n if (n === null || n.kind === 'text') {\n return transport.request<CreateMemoryResult>('memories_create', {\n body: buildCreateBody(options),\n });\n }\n\n // Everything but the files is validated before any file is read, so a\n // typo in document_type does not cost a 10 MB download first.\n buildCreateManifest(options, n.parts.filter((p) => !isFilePart(p)), []);\n const fetchImpl = ((url: string, init?: RequestInit) =>\n transport.fetchExternal(url, init)) as typeof fetch;\n const files = await Promise.all(\n n.parts.filter(isFilePart).map((p) => resolveFile(p, fetchImpl)),\n );\n\n const form = new FormData();\n form.set('manifest', JSON.stringify(buildCreateManifest(options, n.parts, files)));\n files.forEach((file, i) => {\n form.set(\n `file_${i}`,\n new Blob([file.bytes as unknown as BlobSource], { type: file.media_type }),\n file.filename,\n );\n });\n // Not retried: the endpoint is declared non-idempotent, as /create is.\n return transport.request<CreateMemoryResult>('memories_create_multipart', {\n body: form,\n rawBody: true,\n // A server older than this route answers 404, or 405 because\n // /api/v1/memories/{memory_id} exists with other methods. Either would\n // otherwise read as \"context not found\" or a bare HTTP error.\n // InvalidInputError, with Python's message.\n mapError: (status, error) =>\n status === 404 || status === 405\n ? new InvalidInputError(\n 'This Synap server does not support file parts in memories.create. ' +\n 'Upgrade the Synap server, or send text only.',\n { correlationId: error.correlationId, cause: error },\n )\n : undefined,\n });\n },\n\n async batch_create(options) {\n const docs = options.documents;\n if (!Array.isArray(docs) || docs.length === 0) {\n throw new InvalidInputError('documents must be a non-empty array');\n }\n const failFast = options.fail_fast ?? options.failFast ?? false;\n return transport.request<BatchCreateResult>('memories_batch', {\n body: {\n documents: docs.map((d) => {\n jsonDocument(d.document, 'memories.batch_create');\n return buildCreateBody(d);\n }),\n fail_fast: failFast,\n },\n });\n },\n\n async create_from_file(options) {\n const userId = options.user_id ?? options.userId;\n const customerId = options.customer_id ?? options.customerId;\n // Checked first, as Python checks it: a flat map of level key to id.\n // Until 0.5.20 any shape was serialised and sent.\n const scope = options.scope as unknown;\n if (scope !== undefined && scope !== null && (\n typeof scope !== 'object' || Array.isArray(scope)\n || !Object.values(scope as Record<string, unknown>).every((v) => typeof v === 'string')\n )) {\n throw new InvalidInputError('scope must be a flat dict of level key to id, both strings.');\n }\n if (!userId) throw new InvalidInputError('user_id is required');\n // Not required: rejected on B2C, so requiring it made the documented\n // default combination impossible to call.\n await transport.checkCustomerId(customerId, 'memories.create_from_file');\n\n const filePath = options.file_path ?? options.filePath;\n const sources = [filePath, options.file, options.text].filter((v) => v !== undefined);\n if (sources.length === 0) {\n // Python raises ValueError here. There is no JS equivalent, and every\n // other validation in this SDK raises InvalidInputError, so the\n // taxonomy wins over a literal transcription of the exception type.\n throw new InvalidInputError('One of file_path, file, or text must be provided.');\n }\n if (sources.length > 1) {\n throw new InvalidInputError(\n 'Provide exactly one of file_path, file, or text, not several.',\n );\n }\n\n const form = new FormData();\n form.set('user_id', userId);\n // Only when there is one. `form.set('customer_id', undefined)` sends the\n // string \"undefined\", which a B2C instance refuses as a customer id.\n if (typeof customerId === 'string' && customerId !== '') {\n form.set('customer_id', customerId);\n }\n form.set('relationship_type', options.relationship_type ?? options.relationshipType ?? 'b2c');\n form.set('mode', String(options.mode ?? DEFAULT_INGEST_MODE));\n\n // Python appends these only when truthy, so an empty document_type or an\n // empty metadata object is absent from the form rather than present-empty.\n const documentType = options.document_type ?? options.documentType;\n if (documentType) form.set('document_type', String(documentType));\n if (options.metadata !== undefined && Object.keys(options.metadata).length > 0) {\n form.set('metadata', JSON.stringify(options.metadata));\n }\n // The upload route is multipart and cannot carry an object, so the scope\n // map goes as a JSON string; the server parses it with json.loads.\n if (options.scope && Object.keys(options.scope).length > 0) {\n form.set('scope', JSON.stringify(options.scope));\n }\n\n if (filePath !== undefined) {\n // Lazy, so importing the SDK on Edge or in a Worker stays safe: a\n // top-level `node:fs` import fails the BUILD there, not the call.\n const { readFile } = await import('node:fs/promises');\n const { basename } = await import('node:path');\n const bytes = await readFile(filePath);\n form.set('file', new Blob([bytes as unknown as BlobSource]), basename(filePath));\n } else if (options.file !== undefined) {\n const blob = options.file instanceof Blob\n ? options.file\n : new Blob([options.file as unknown as BlobSource]);\n // Python defaults the name to \"upload\" when `filename` is omitted.\n form.set('file', blob, options.filename ?? 'upload');\n } else {\n form.set('text', String(options.text));\n }\n\n return transport.request<CreateMemoryResult>('memories_upload', {\n body: form,\n rawBody: true,\n });\n },\n\n async get(memoryId) {\n if (!memoryId) throw new InvalidInputError('memory_id is required');\n return transport.request<Json>('memories_get', { pathParams: { memory_id: memoryId } });\n },\n\n async update(options) {\n const memoryId = options.memory_id ?? options.memoryId;\n if (!memoryId) throw new InvalidInputError('memory_id is required');\n if (!options.document) throw new InvalidInputError('document is required');\n const body: Json = {\n document: options.document,\n merge_strategy: options.merge_strategy ?? options.mergeStrategy ?? 'smart-merge',\n };\n const dt = options.document_type ?? options.documentType;\n if (dt !== undefined) body['document_type'] = dt;\n if (options.metadata !== undefined) body['metadata'] = options.metadata;\n // PUT, so idempotent by verb: safe to retry even on an ambiguous failure.\n return transport.request<Json>('memories_update', {\n pathParams: { memory_id: memoryId },\n body,\n });\n },\n\n async delete(memoryId) {\n // The 0.3.x wrapper let you delete \"all of this user's memories\" from a\n // process-local id list, which deleted nothing in serverless while\n // reporting success. Deliberately not ported.\n if (!memoryId) {\n throw new InvalidInputError(\n 'memory_id is required. Deleting by user is no longer supported: the ' +\n 'previous implementation tracked ids in process memory, so it silently ' +\n 'deleted nothing in any serverless or multi-process deployment while ' +\n 'reporting success.',\n );\n }\n return transport.request<Json>('memories_delete', { pathParams: { memory_id: memoryId } });\n },\n\n async forget(options) {\n const o = options as unknown as Record<string, unknown>;\n await transport.checkCustomerId(o['customer_id'] ?? o['customerId'], 'memories.forget');\n const body = buildForgetBody(options) as Record<string, unknown>;\n const result = await transport.request<ForgetResult>('memories_forget', { body: body as Json });\n // A preview deletes nothing, so it evicts nothing. Never let a cache\n // problem turn a successful delete into an error.\n // A forget can remove only copies (a profile entry, a chunk) and so return no\n // memory ids; those are served from the same caches.\n const removed = !!result?.deleted_ids?.length\n || result?.status === 'deleted' || result?.status === 'partial';\n if (removed && onForgotten) {\n try {\n onForgotten({\n userId: (body['user_id'] as string | null) ?? null,\n customerId: (body['customer_id'] as string | null) ?? null,\n });\n } catch { /* eviction is best effort */ }\n }\n return result;\n },\n\n async status(ingestionId) {\n if (!ingestionId) throw new InvalidInputError('ingestion_id is required');\n return transport.request<Json>('memories_status', {\n pathParams: { ingestion_id: ingestionId },\n });\n },\n\n async wait_for_completion(ingestionId, options = {}) {\n if (!ingestionId) throw new InvalidInputError('ingestion_id is required');\n const timeoutMs =\n (options.timeout_seconds ?? options.timeoutSeconds ?? 300) * 1000;\n const pollMs =\n (options.poll_interval_seconds ?? options.pollIntervalSeconds ?? 2) * 1000;\n\n const deadline = Date.now() + timeoutMs;\n let last: Json = {};\n for (;;) {\n last = await this.status(ingestionId);\n const status = String(last['status'] ?? '').toLowerCase();\n if (TERMINAL_STATUSES.has(status)) return last;\n if (Date.now() >= deadline) {\n // Python returns the last status rather than raising, so a caller\n // that only checks `.status` behaves identically in both SDKs.\n return last;\n }\n await sleep(Math.min(pollMs, Math.max(0, deadline - Date.now())), options.signal);\n }\n },\n };\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) return Promise.resolve();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n // NOT unref'd. This is the poll interval inside wait_for_completion, which\n // a caller is awaiting: foreground work. Unref'ing it let a process whose\n // only pending work was this sleep exit mid-poll, so an awaited\n // wait_for_completion never settled. Node calls it \"Detected unsettled\n // top-level await\". The unref'd timers in this SDK are the two heartbeats\n // and the request watchdog, all of which are genuinely background.\n function onAbort() {\n clearTimeout(timer);\n reject(signal?.reason ?? new Error('Aborted'));\n }\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","/**\n * Client-side identifier validation, mirroring Python's\n * ``maximem_synap/utils/validators.py``.\n *\n * These raise the *specific* ``InvalidInputError`` subtypes so callers can\n * catch them directly (``catch (e) { if (e instanceof InvalidConversationIdError) }``)\n * instead of the generic parent. Validation happens before any network call,\n * so a malformed id fails locally rather than becoming a billed round trip.\n *\n * Both errors were exported from day one and thrown at zero sites until this\n * module existed, which meant a typo'd conversation id reached the server and\n * came back as a generic 4xx.\n */\n\nimport { InvalidConversationIdError, InvalidInstanceIdError } from '../errors.js';\n\n// Instance ids are issued as `inst_` followed by 16 hex characters.\nconst INSTANCE_ID_RE = /^inst_[0-9a-fA-F]{16}$/;\n\n// Accepts any RFC 4122 shape. Deliberately laxer than a version-specific\n// check: Python defers to `uuid.UUID(...)`, which likewise accepts any\n// variant, and rejecting a valid-but-unexpected version here would diverge.\nconst UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\n\n/**\n * Throw `InvalidConversationIdError` if a non-empty `conversationId` is not a\n * UUID string.\n *\n * Empty / null / undefined values pass through untouched: callers that require\n * a conversation id surface that separately, so this only rejects a clearly\n * malformed value such as `\"conv_123\"`.\n */\nexport function validateConversationId(conversationId: unknown): void {\n if (conversationId === undefined || conversationId === null || conversationId === '') return;\n if (typeof conversationId !== 'string' || !UUID_RE.test(conversationId)) {\n // Message text matches Python's `f\"Invalid conversation ID: {id}\"` byte for byte.\n throw new InvalidConversationIdError(`Invalid conversation ID: ${String(conversationId)}`);\n }\n}\n\n/**\n * Throw `InvalidInstanceIdError` if a non-empty `instanceId` is not in the\n * `inst_<hex16>` format.\n *\n * Empty values pass through: the instance id is normally resolved from the API\n * key during `initialize()`, so only an explicitly provided malformed id is\n * rejected.\n */\nexport function validateInstanceId(instanceId: unknown): void {\n if (instanceId === undefined || instanceId === null || instanceId === '') return;\n if (typeof instanceId !== 'string' || !INSTANCE_ID_RE.test(instanceId)) {\n throw new InvalidInstanceIdError(`Invalid instance ID: ${String(instanceId)}`);\n }\n}\n","/**\n * Which model the agent runs on, sent with each conversation turn.\n *\n * The server sizes compaction to the agent's context window: it compacts at\n * about 11.7% of the window (15K tokens on a 128K model) and caps the\n * compacted record at half that. It reads the window from the latest turn's\n * metadata, under `agent_model` and `agent_context_window`. A model name is\n * enough: the server has a model -> window table. Give `context_window` only\n * for a model the table would not know, or to override it.\n *\n * Precedence, highest first: the value passed on the call, the client option\n * (`agent_model` / `agent_context_window`), a value already in the caller's\n * own metadata. With none of them the server assumes 128K. Mirrors Python's\n * `agent_model.py`.\n */\nexport const AGENT_MODEL_KEY = 'agent_model';\nexport const AGENT_CONTEXT_WINDOW_KEY = 'agent_context_window';\n\nexport interface AgentModel {\n model?: string | undefined;\n contextWindow?: number | undefined;\n}\n\n/** The per-call `model` / `context_window` (either spelling) off an options object. */\nexport function agentModelOf(options: unknown): AgentModel {\n const o = (options ?? {}) as Record<string, unknown>;\n const window = o['context_window'] ?? o['contextWindow'];\n return {\n model: typeof o['model'] === 'string' ? (o['model'] as string) : undefined,\n contextWindow: typeof window === 'number' ? window : undefined,\n };\n}\n\n/**\n * `metadata` with the agent's model folded in. `asStrings` for the gRPC\n * stream, whose metadata is a string map. Returns the input unchanged when\n * there is nothing to add.\n */\nexport function withAgentModel<T extends Record<string, unknown>>(\n metadata: T | undefined,\n perCall: AgentModel,\n defaults: AgentModel,\n asStrings = false,\n): T | undefined {\n const model = perCall.model || defaults.model;\n const window = perCall.contextWindow || defaults.contextWindow;\n if (!model && !window) return metadata;\n const out: Record<string, unknown> = { ...(metadata ?? {}) };\n if (model) out[AGENT_MODEL_KEY] = String(model);\n if (window) out[AGENT_CONTEXT_WINDOW_KEY] = asStrings ? String(Math.trunc(window)) : Math.trunc(window);\n return out as T;\n}\n","/**\n * Conversation namespace. Mirrors `ConversationInterface` and\n * `ConversationContextInterface` in the Python SDK.\n */\n\nimport { InvalidInputError } from '../errors.js';\nimport { validateConversationId } from '../util/validators.js';\nimport type { HttpTransport } from '../transport/http.js';\nimport { fetchContext, type FetchHooks } from '../context/fetch.js';\nimport { agentModelOf, withAgentModel, type AgentModel } from '../agent-model.js';\nimport type { FetchOptions, Json, RawContext } from '../context/types.js';\nimport {\n normaliseContent, toInlineParts,\n type ContentPart, type WireImagePart, type WireTextPart,\n} from '../memories/parts.js';\n\nexport interface RecordMessageOptions {\n conversation_id?: string;\n conversationId?: string;\n role: string;\n /**\n * The message. A string, or a list of strings, `TextPart`s and `FilePart`s\n * (images today). A list with no file is joined with `\"\\n\"` and sent as that\n * string. With a file, the parts are sent in order with each file inline as\n * base64; the server reads the images and stores the message as text.\n */\n content: string | ContentPart[];\n user_id?: string;\n userId?: string;\n customer_id?: string;\n customerId?: string;\n session_id?: string;\n sessionId?: string;\n metadata?: Json;\n /**\n * The rung this conversation belongs to, named in full, e.g.\n * `{ tenant: 'acme', practice: 'high_street' }`.\n *\n * Only relevant to a client whose ladder is deeper than the default three\n * rungs (root, tenant, person). On the default ladder `customer_id` and\n * `user_id` already say everything a path could.\n *\n * Sent as `scope` on the wire, matching Python's `scope_path`. Sending it\n * once per conversation is enough: the server fills a missing path and never\n * overwrites one.\n */\n scope_path?: Record<string, string>;\n scopePath?: Record<string, string>;\n /**\n * The model the agent runs on, e.g. `'gpt-4o'`. Overrides the client's\n * `agent_model` for this turn. The server sizes compaction to this model's\n * context window. Python's `model=`.\n */\n model?: string;\n /** The agent model's context window in tokens, for a model the server would not know. */\n context_window?: number;\n contextWindow?: number;\n}\n\nexport interface TranscriptTurn {\n role: string;\n content: string;\n [key: string]: unknown;\n}\n\nexport interface IngestTranscriptOptions {\n conversation_id?: string;\n conversationId?: string;\n user_id?: string;\n userId?: string;\n transcript: string | TranscriptTurn[];\n customer_id?: string;\n customerId?: string;\n conversation_type?: string;\n conversationType?: string;\n analysis?: Json;\n metadata?: Json;\n started_at?: string | Date;\n startedAt?: string | Date;\n ended_at?: string | Date;\n endedAt?: string | Date;\n /**\n * The rung this conversation belongs to, named in full, e.g.\n * `{ tenant: 'acme', practice: 'high_street' }`.\n *\n * Only relevant to a client whose ladder is deeper than the default three\n * rungs (root, tenant, person). On the default ladder `customer_id` and\n * `user_id` already say everything a path could.\n *\n * Sent as `scope` on the wire, matching Python's `scope_path`. Sending it\n * once per conversation is enough: the server fills a missing path and never\n * overwrites one.\n */\n scope_path?: Record<string, string>;\n scopePath?: Record<string, string>;\n}\n\n/**\n * Compaction levels, mirroring Python's `CompactionLevel` enum. The JS SDK\n * exported no equivalent, so `compaction_level` was an untyped `string` and a\n * typo reached the server instead of the compiler.\n */\nexport const COMPACTION_LEVELS = [\n 'low', 'medium', 'high', 'adaptive', 'aggressive', 'balanced', 'conservative',\n] as const;\n\nexport type CompactionLevel = (typeof COMPACTION_LEVELS)[number];\n\nexport interface CompactOptions {\n conversation_id?: string;\n conversationId?: string;\n strategy?: string;\n compaction_level?: CompactionLevel | string;\n compactionLevel?: CompactionLevel | string;\n target_tokens?: number;\n targetTokens?: number;\n force?: boolean;\n}\n\nfunction either<T>(o: Record<string, unknown>, snake: string, camel: string): T | undefined {\n const a = o[snake];\n if (a !== undefined) return a as T;\n const b = o[camel];\n return b === undefined ? undefined : (b as T);\n}\n\nfunction iso(v: string | Date | undefined): string | undefined {\n if (v === undefined) return undefined;\n return v instanceof Date ? v.toISOString() : v;\n}\n\n/**\n * The JSON body Python sends for one message.\n *\n * `resolvedContent` is the content after its files were read, supplied by\n * `record_message`. Without it, a list with no file is joined into one string,\n * and a list with a file throws: reading a file is async, and this is not.\n */\nexport function buildRecordMessageBody(\n options: RecordMessageOptions,\n resolvedContent?: string | Array<WireTextPart | WireImagePart>,\n field = 'content',\n): Json {\n const o = options as unknown as Record<string, unknown>;\n const conversationId = either<string>(o, 'conversation_id', 'conversationId');\n const userId = either<string>(o, 'user_id', 'userId');\n const customerId = either<string>(o, 'customer_id', 'customerId');\n\n if (!conversationId) throw new InvalidInputError('conversation_id is required');\n // Python validates the format here (and in record_messages_batch, which\n // reuses this builder per message). Note it deliberately does NOT validate\n // in ingest_transcript.\n validateConversationId(conversationId);\n if (!options.role) throw new InvalidInputError('role is required');\n // Checked before sending, as Python checks it. The server refuses any other\n // role with a 422; until 0.5.17 JS sent it to find out.\n if (!(MESSAGE_ROLES as readonly string[]).includes(options.role)) {\n throw new InvalidInputError(`Invalid role '${options.role}'. Must be 'user' or 'assistant'.`);\n }\n if (options.content === undefined || options.content === null) {\n throw new InvalidInputError('content is required');\n }\n if (!userId) throw new InvalidInputError('user_id is required');\n // customer_id is NOT required. A B2C instance rejects one, so demanding it\n // here made the only correct B2C shape impossible to express.\n // checked by the caller, which holds the transport; see createConversationNamespace\n\n let content: unknown = options.content;\n if (resolvedContent !== undefined) {\n content = resolvedContent;\n } else {\n const n = normaliseContent(options.content, field);\n if (n?.kind === 'parts') {\n throw new InvalidInputError(\n 'content holds a FilePart, whose bytes have to be read first. ' +\n 'Send it with conversation.record_message.',\n );\n }\n if (n !== null) content = n.text;\n }\n\n const body: Json = {\n conversation_id: conversationId,\n role: options.role,\n content,\n user_id: userId,\n customer_id: customerId,\n // Python always sends this, defaulting to {}.\n metadata: options.metadata ?? {},\n };\n // Only when set, like Python's `if session_id:`. An empty one reached the\n // server, which turns any non-UUID session id into its UUID5, so every\n // conversation sent \"\" shared one session.\n const sessionId = either<string>(o, 'session_id', 'sessionId');\n if (sessionId) body['session_id'] = sessionId;\n // `scope` on the wire, `scope_path` in the SDK, the same split Python makes.\n // Omitted when unset so a client on the default ladder sends exactly the\n // body it sends today.\n const scopePath = either<Record<string, string>>(o, 'scope_path', 'scopePath');\n // Omitted when absent or empty, like Python's `if scope_path:`.\n if (scopePath !== undefined && scopePath !== null && Object.keys(scopePath).length > 0) {\n body['scope'] = scopePath;\n }\n return body;\n}\n\nexport function buildIngestTranscriptBody(options: IngestTranscriptOptions): Json {\n const o = options as unknown as Record<string, unknown>;\n const conversationId = either<string>(o, 'conversation_id', 'conversationId');\n const userId = either<string>(o, 'user_id', 'userId');\n if (!conversationId) throw new InvalidInputError('conversation_id is required');\n if (!userId) throw new InvalidInputError('user_id is required');\n if (options.transcript === undefined || options.transcript === null) {\n throw new InvalidInputError('transcript is required');\n }\n\n const body: Json = {\n conversation_id: conversationId,\n user_id: userId,\n transcript: options.transcript,\n };\n // Unset optionals are omitted so the server applies its own defaults, which\n // is what Python does here (and notably NOT what it does for memories.create).\n const customerId = either<string>(o, 'customer_id', 'customerId');\n const conversationType = either<string>(o, 'conversation_type', 'conversationType');\n const startedAt = iso(either<string | Date>(o, 'started_at', 'startedAt'));\n const endedAt = iso(either<string | Date>(o, 'ended_at', 'endedAt'));\n if (customerId !== undefined) body['customer_id'] = customerId;\n if (conversationType !== undefined) body['conversation_type'] = conversationType;\n if (options.analysis !== undefined) body['analysis'] = options.analysis;\n if (options.metadata !== undefined) body['metadata'] = options.metadata;\n if (startedAt !== undefined) body['started_at'] = startedAt;\n if (endedAt !== undefined) body['ended_at'] = endedAt;\n // Python 0.4.10 sends this on `ingest_transcript` and JS did not, so a\n // TypeScript client on a deep ladder had no route that could name a rung.\n // Omitted when absent or empty, like Python's `if scope_path:`.\n const scopePath = either<Record<string, string>>(o, 'scope_path', 'scopePath');\n if (scopePath !== undefined && scopePath !== null && Object.keys(scopePath).length > 0) {\n body['scope'] = scopePath;\n }\n return body;\n}\n\nexport function buildCompactBody(options: CompactOptions): Json {\n const o = options as unknown as Record<string, unknown>;\n const conversationId = either<string>(o, 'conversation_id', 'conversationId');\n if (!conversationId) throw new InvalidInputError('conversation_id is required');\n validateConversationId(conversationId);\n\n const body: Json = { conversation_id: conversationId, force: options.force ?? false };\n const strategy = options.strategy ?? either<string>(o, 'compaction_level', 'compactionLevel');\n const targetTokens = either<number>(o, 'target_tokens', 'targetTokens');\n if (strategy !== undefined) body['strategy'] = strategy;\n if (targetTokens !== undefined) body['target_tokens'] = targetTokens;\n return body;\n}\n\n/**\n * Result of `conversation.ingest_transcript`, mirroring Python's\n * `TranscriptIngestResponse`. It was `Json` here, so `ingestion_id` came back\n * as `unknown` and could not be handed to `wait_for_completion` without a cast.\n */\nexport interface TranscriptIngestResult {\n conversation_id: string;\n /** The raw client-supplied id, echoed back. */\n external_conversation_id: string;\n /** Always set on a 2xx, including the `duplicate` branch. */\n ingestion_id: string;\n status: 'queued' | 'duplicate';\n turns_recorded: number;\n summary_status: 'in_progress' | 'already_compacted' | 'skipped';\n /**\n * What the server could not do with this push: no event time supplied\n * (recency ranking cannot order these memories), or existing turns kept.\n * Always a list. Since 0.5.16.\n */\n warnings: string[];\n /** ISO-8601. */\n queued_at: string;\n [key: string]: unknown;\n}\n\nexport interface ConversationNamespace {\n record_message(options: RecordMessageOptions): Promise<Json>;\n record_messages_batch(messages: RecordMessageOptions[]): Promise<Json>;\n ingest_transcript(options: IngestTranscriptOptions): Promise<TranscriptIngestResult>;\n context: {\n fetch(options?: FetchOptions): Promise<RawContext>;\n get_context_for_prompt(options?: {\n conversation_id?: string;\n conversationId?: string;\n style?: string;\n /** Search the earlier turns locally after a compaction (default true). */\n search_history?: boolean;\n searchHistory?: boolean;\n /** What to search for; defaults to the latest user message. */\n query?: string;\n }): Promise<Json>;\n compact(options: CompactOptions): Promise<Json>;\n get_compacted(options: { conversation_id?: string; conversationId?: string; version?: number; format?: string }): Promise<Json | null>;\n get_compaction_status(options: { conversation_id?: string; conversationId?: string } | string): Promise<Json>;\n subscribe_to_compaction_updates(\n conversationId: string,\n callback: CompactionCallback,\n ): () => void;\n unsubscribe_all_compaction_updates(conversationId?: string): number;\n };\n}\n\nexport type CompactionCallback = (bundle: Json) => unknown;\n\n/**\n * Registry of per-conversation compaction subscribers.\n *\n * Split out from the namespace so the instance stream can dispatch into it\n * without the two namespaces importing each other.\n */\nexport class CompactionSubscribers {\n readonly #byConversation = new Map<string, CompactionCallback[]>();\n\n add(conversationId: string, callback: CompactionCallback): () => void {\n const list = this.#byConversation.get(conversationId);\n if (list === undefined) this.#byConversation.set(conversationId, [callback]);\n else list.push(callback);\n\n let unsubscribed = false;\n return () => {\n // Idempotent, matching Python: calling the thunk twice is a no-op.\n if (unsubscribed) return;\n unsubscribed = true;\n const current = this.#byConversation.get(conversationId);\n if (current === undefined) return;\n const at = current.indexOf(callback);\n if (at !== -1) current.splice(at, 1);\n if (current.length === 0) this.#byConversation.delete(conversationId);\n };\n }\n\n removeAll(conversationId?: string): number {\n if (conversationId === undefined) {\n let count = 0;\n for (const list of this.#byConversation.values()) count += list.length;\n this.#byConversation.clear();\n return count;\n }\n const list = this.#byConversation.get(conversationId);\n if (list === undefined) return 0;\n this.#byConversation.delete(conversationId);\n return list.length;\n }\n\n /** Fires subscribers in registration order. A throwing listener must not break the stream reader. */\n dispatch(conversationId: string, bundle: Json, onError: (e: unknown) => void): void {\n // Copy first: a callback that unsubscribes itself would otherwise mutate\n // the array mid-iteration and skip the next listener.\n for (const callback of [...(this.#byConversation.get(conversationId) ?? [])]) {\n try {\n const result = callback(bundle) as unknown;\n // An async callback returns a promise; swallow its rejection the way\n // Python swallows one from an asyncio task.\n if (result instanceof Promise) result.catch(onError);\n } catch (error) {\n onError(error);\n }\n }\n }\n}\n\n/**\n * Pair each message a batch write stored with the server's row for it.\n *\n * The server's `results` holds the messages that were stored, in input order,\n * and leaves the failed ones out; those are in `errors`, each with the `index`\n * it had in the request. Buffering every body, or pairing `results` against\n * the whole input by position, puts a message the server refused into the\n * caller's next prompt.\n *\n * Returns nothing when the two cannot be lined up, as Python does. A row with\n * no `message_id` is treated as not stored.\n */\nexport function storedBatchRows(\n bodies: Array<Record<string, unknown>>,\n result: unknown,\n): Array<[Record<string, unknown>, Record<string, unknown>]> {\n const r = (result ?? {}) as Record<string, unknown>;\n const results = Array.isArray(r['results']) ? (r['results'] as Array<Record<string, unknown>>) : [];\n const errors = Array.isArray(r['errors']) ? (r['errors'] as Array<Record<string, unknown>>) : [];\n const failed = new Set(errors.map((e) => e?.['index']));\n const stored = bodies.filter((_, index) => !failed.has(index));\n if (stored.length !== results.length) return [];\n const pairs: Array<[Record<string, unknown>, Record<string, unknown>]> = [];\n stored.forEach((body, i) => {\n const row = results[i];\n if (row && typeof row === 'object' && row['message_id']) pairs.push([body, row]);\n });\n return pairs;\n}\n\n/**\n * Called after a successful write with the ids that were written for.\n *\n * Backs `SYNAP_SDK_CACHE_INVALIDATE_ON_WRITE`. The cloud invalidates its own\n * Redis caches on ingest, but that stops at the process boundary: without this\n * the in-SDK anticipation cache keeps serving the pre-write view for the rest\n * of its TTL. Python calls its equivalent from these same three write paths.\n */\nexport type WriteInvalidator = (ids: {\n userId?: string | undefined;\n customerId?: string | undefined;\n}) => void;\n\n/**\n * Called with each turn a write path sends, so it can be buffered locally.\n *\n * This is what makes the next fetch see the turn that was just recorded, ahead\n * of the server having persisted and compacted it.\n */\nexport type TurnRecorder = (turn: {\n conversationId: string;\n role: string;\n content: string;\n timestamp?: string | undefined;\n /** The server's id for the turn, from the write's response. */\n messageId?: string | undefined;\n /**\n * The conversation's message count after this write, as the server reported\n * it. This is what tells the local store whether it holds the whole\n * conversation. Absent from a server that predates it.\n */\n serverMessageCount?: number | null | undefined;\n /** Other writes this process still has outstanding for the conversation. */\n inFlight?: number | undefined;\n}) => void;\n\n/** The roles the server accepts on a recorded message (RecordMessageRequest.role). */\nexport const MESSAGE_ROLES: readonly string[] = ['user', 'assistant'];\n\n/** The styles the server renders (CompactedContext.get_injection_format). */\nexport const PROMPT_STYLES: readonly string[] = ['structured', 'narrative', 'bullet_points'];\n\nexport function createConversationNamespace(\n transport: HttpTransport,\n subscribers: CompactionSubscribers = new CompactionSubscribers(),\n onWrite: WriteInvalidator = () => {},\n onTurn: TurnRecorder = () => {},\n /**\n * Applied to a conversation-scoped response before it is returned.\n *\n * `scopePath` is carried because one of the things this hook does is splice\n * in a cached user summary, and a summary prefetched at one rung must not be\n * spliced into a response for a caller standing at another. Python reads the\n * path off the fetch arguments at that call site; here the call site is a\n * callback, so the path has to travel with it or the rung check is silently\n * skipped on this one path.\n */\n onFetched: (\n response: RawContext,\n conversationId: string | undefined,\n userId: string | undefined,\n scopePath: Record<string, string> | undefined,\n ) => void = () => {},\n /**\n * SDK-authoritative short-term context. Returns a locally rendered response\n * when the flag is on AND the store is warm for this conversation, which\n * skips the cloud round trip entirely; null falls through to the network.\n */\n localShortTerm: {\n prompt: (conversationId: string, style: string) => Json | null;\n compacted: (conversationId: string, format: string) => Json | null;\n /**\n * Handed the server's `/context-for-prompt` answer after the local store\n * could not answer, so the store can be brought back in step.\n */\n reseed?: (conversationId: string, serverResponse: Json) => void;\n /**\n * The response with the earlier turns that best match `query` appended,\n * found by a local search of the turn archive. Python:\n * `MaximemSynapSDK._with_history_excerpts`.\n */\n historyExcerpts?: (conversationId: string, response: Json, query: string | undefined) => Promise<Json>;\n } = { prompt: () => null, compacted: () => null },\n /** The client's `agent_model` / `agent_context_window`, folded into each turn's metadata. */\n agentModel: () => AgentModel = () => ({}),\n fetchHooks: FetchHooks = {},\n): ConversationNamespace {\n // conversation_id -> REST writes sent and not yet buffered locally. Lets the\n // local store tell two of this process's own concurrent writes apart from a\n // second writer.\n const writesInFlight = new Map<string, number>();\n const withTurnModel = (body: Json, options: unknown): Json => {\n const metadata = withAgentModel(\n body['metadata'] as Record<string, unknown> | undefined, agentModelOf(options), agentModel(),\n );\n return metadata === undefined ? body : { ...body, metadata: metadata as Json };\n };\n const writeStarted = (conversationId: string): void => {\n writesInFlight.set(conversationId, (writesInFlight.get(conversationId) ?? 0) + 1);\n };\n const writeLanded = (conversationId: string): void => {\n const remaining = (writesInFlight.get(conversationId) ?? 0) - 1;\n if (remaining > 0) writesInFlight.set(conversationId, remaining);\n else writesInFlight.delete(conversationId);\n };\n const confirmation = (\n result: unknown,\n conversationId: string,\n ): { messageId?: string; serverMessageCount?: number | null; inFlight: number } => {\n const r = (result ?? {}) as Record<string, unknown>;\n const count = r['conversation_message_count'];\n return {\n ...(typeof r['message_id'] === 'string' ? { messageId: r['message_id'] } : {}),\n serverMessageCount: typeof count === 'number' ? count : null,\n inFlight: writesInFlight.get(conversationId) ?? 0,\n };\n };\n const fetchImpl = ((url: string, init?: RequestInit) =>\n transport.fetchExternal(url, init)) as typeof fetch;\n /** Everything but the content's files, so a bad id fails before a download. */\n const validateMessage = (options: RecordMessageOptions, field = 'content'): void => {\n if (normaliseContent(options.content, field)?.kind === 'parts') {\n buildRecordMessageBody(options, '', field);\n } else {\n buildRecordMessageBody(options, undefined, field);\n }\n };\n /**\n * The body for one message, and what the local short-term store keeps for\n * it: the content itself, or, when it carries images, the placeholder\n * rendering (`[image: <filename>]`), never base64.\n */\n const prepareMessage = async (\n options: RecordMessageOptions,\n field = 'content',\n ): Promise<{ body: Json; mirror: string }> => {\n const n = normaliseContent(options.content, field);\n if (n?.kind !== 'parts') {\n const body = buildRecordMessageBody(options, undefined, field);\n return { body, mirror: String(body['content'] ?? '') };\n }\n validateMessage(options, field);\n const inline = await toInlineParts(n.parts, fetchImpl);\n return { body: buildRecordMessageBody(options, inline.wire), mirror: inline.placeholder };\n };\n const convId = (v: { conversation_id?: string; conversationId?: string } | string): string => {\n const id = typeof v === 'string' ? v : (v.conversation_id ?? v.conversationId);\n if (!id) throw new InvalidInputError('conversation_id is required');\n // Covers context.fetch, get_compacted, get_compaction_status and\n // get_context_for_prompt: the four routes Python validates through this\n // same shape. ingest_transcript does not go through here, which is correct.\n validateConversationId(id);\n return id;\n };\n\n return {\n async record_message(options) {\n await transport.checkCustomerId(\n (options as unknown as Record<string, unknown>)['customer_id'] ??\n (options as unknown as Record<string, unknown>)['customerId'],\n 'conversation.record_message',\n );\n const prepared = await prepareMessage(options);\n const body = withTurnModel(prepared.body, options);\n const mirror = prepared.mirror;\n const conversationId = String(body['conversation_id'] ?? '');\n writeStarted(conversationId);\n let result: Json;\n try {\n result = await transport.request<Json>('conversations_messages', { body });\n } finally {\n writeLanded(conversationId);\n }\n // Buffer locally only AFTER the server accepted it. Recording a turn the\n // write failed on would surface a message that does not exist.\n onTurn({\n conversationId,\n role: String(body['role'] ?? 'user'),\n content: mirror,\n timestamp: body['timestamp'] as string | undefined,\n ...confirmation(result, conversationId),\n });\n onWrite({\n userId: body['user_id'] as string | undefined,\n customerId: body['customer_id'] as string | undefined,\n });\n return result;\n },\n\n async record_messages_batch(messages) {\n if (!Array.isArray(messages) || messages.length === 0) {\n throw new InvalidInputError('messages must be a non-empty array');\n }\n // Every message checked BEFORE any is sent: a batch that fails on its\n // fifth message would otherwise be half-applied.\n for (const m of messages) {\n const mo = m as unknown as Record<string, unknown>;\n await transport.checkCustomerId(\n mo['customer_id'] ?? mo['customerId'], 'conversation.record_messages_batch',\n );\n }\n // Every message validated before any file is read, then the files of\n // all of them read together.\n // Python names the failing message in the error, so this does too.\n const field = (i: number) => `messages[${i}].content`;\n messages.forEach((m, i) => validateMessage(m, field(i)));\n const prepared = await Promise.all(messages.map((m, i) => prepareMessage(m, field(i))));\n const bodies = prepared.map((p, i) => withTurnModel(p.body, messages[i]!));\n const mirrors = new Map(prepared.map((p, i) => [bodies[i]!, p.mirror]));\n const result = await transport.request<Json>('conversations_messages_batch', {\n body: { messages: bodies },\n });\n // Buffer only what the server stored, each paired with its own row.\n for (const [body, row] of storedBatchRows(bodies, result)) {\n const conversationId = String(body['conversation_id'] ?? '');\n onTurn({\n conversationId,\n role: String(body['role'] ?? 'user'),\n content: mirrors.get(body) ?? String(body['content'] ?? ''),\n timestamp: body['timestamp'] as string | undefined,\n ...confirmation(row, conversationId),\n });\n }\n // Every distinct entity in the batch, not just the first message's.\n for (const body of bodies) {\n onWrite({\n userId: body['user_id'] as string | undefined,\n customerId: body['customer_id'] as string | undefined,\n });\n }\n return result;\n },\n\n async ingest_transcript(options) {\n // First, as Python checks it and as every other write here does. Until\n // 0.5.16 this was the one write that skipped it, so a B2C customer_id\n // went to the server and came back as a plain InvalidInputError.\n const o = options as unknown as Record<string, unknown>;\n await transport.checkCustomerId(\n o['customer_id'] ?? o['customerId'], 'conversation.ingest_transcript',\n );\n const body = buildIngestTranscriptBody(options);\n const raw = await transport.request<TranscriptIngestResult>('conversations_ingest', { body });\n // Always a list, as Python's response model defaults it.\n const result: TranscriptIngestResult = {\n ...raw,\n warnings: Array.isArray(raw?.warnings) ? raw.warnings.map(String) : [],\n };\n onWrite({\n userId: body['user_id'] as string | undefined,\n customerId: body['customer_id'] as string | undefined,\n });\n return result;\n },\n\n context: {\n async fetch(options = {}) {\n // Conversation-scope fetch is one of Python's seven validation sites.\n // It does not route through convId() because the id travels in the\n // body rather than the path, so validate it explicitly.\n const id =\n (options as { conversation_id?: string; conversationId?: string }).conversation_id ??\n (options as { conversationId?: string }).conversationId;\n validateConversationId(id);\n const response = await fetchContext(transport, 'conversation', options, fetchHooks);\n // Read-your-writes. This is the path where it matters most: a fast\n // follow-up on the same conversation would otherwise retrieve context\n // missing the turn just recorded.\n onFetched(\n response,\n id,\n (options as { user_id?: string; userId?: string }).user_id ??\n (options as { userId?: string }).userId,\n (options as { scope_path?: Record<string, string> }).scope_path ??\n (options as { scopePath?: Record<string, string> }).scopePath,\n );\n return response;\n },\n\n get_context_for_prompt: async (options = {}) => {\n const id = convId(options);\n const style = options.style ?? 'structured';\n // Refused here, as Python refuses it. A style the server cannot render\n // was a 500 from it, or silently ignored when the compaction has a block.\n if (!PROMPT_STYLES.includes(style)) {\n throw new InvalidInputError(\n `Invalid style '${style}'. Must be one of: ${PROMPT_STYLES.join(', ')}`,\n );\n }\n const search = (options.search_history ?? options.searchHistory ?? true) && localShortTerm.historyExcerpts;\n const withHistory = async (response: Json): Promise<Json> => {\n if (!search) return response;\n try {\n return await localShortTerm.historyExcerpts!(id, response, options.query);\n } catch {\n return response; // never fail the prompt over its extras\n }\n };\n const local = localShortTerm.prompt(id, style);\n if (local !== null) return withHistory(local);\n const result = await transport.request<Json>('context_for_prompt', {\n pathParams: { conversation_id: id },\n query: { style },\n });\n const response = (result?.['context_for_prompt'] as Json) ?? result ?? {};\n localShortTerm.reseed?.(id, response);\n return withHistory(response);\n },\n\n async compact(options) {\n return transport.request<Json>('conversations_compact', { body: buildCompactBody(options) });\n },\n\n get_compacted: async (options) => {\n const id = convId(options);\n // Python only takes the local path when no explicit version is asked\n // for: a pinned version is a request for a specific server artefact.\n if (options.version === undefined) {\n const local = localShortTerm.compacted(id, options.format ?? 'structured');\n if (local !== null) return local;\n }\n const query: Record<string, string | number> = { format: options.format ?? 'structured' };\n if (options.version !== undefined) query['version'] = options.version;\n try {\n return await transport.request<Json>('conversations_compacted', {\n pathParams: { conversation_id: id },\n query,\n });\n } catch (error) {\n // Python returns None when there is nothing compacted yet, rather\n // than surfacing a 404. Matching that keeps callers identical.\n if ((error as { code?: string }).code === 'context_not_found') return null;\n throw error;\n }\n },\n\n async get_compaction_status(options) {\n return transport.request<Json>('conversations_compaction_status', {\n pathParams: { conversation_id: convId(options) },\n });\n },\n\n /**\n * Fire `callback` whenever a `compaction_update` bundle arrives on the\n * Listen stream for this conversation.\n *\n * Requires an active `client.instance.listen()`; without it no bundles\n * arrive and the callback never fires. Registering before listening is\n * fine, which is why this does not throw when the stream is down.\n *\n * Returns an idempotent unsubscribe thunk, matching Python.\n */\n subscribe_to_compaction_updates(conversationId, callback) {\n if (!conversationId) throw new InvalidInputError('conversation_id is required');\n if (typeof callback !== 'function') throw new InvalidInputError('callback is required');\n return subscribers.add(conversationId, callback);\n },\n\n /** Remove subscribers for one conversation, or all of them. Returns the count removed. */\n unsubscribe_all_compaction_updates(conversationId?: string) {\n return subscribers.removeAll(conversationId);\n },\n },\n };\n}\n","/**\n * Data namespace. Mirrors `maximem_synap.data.interface.DataInterface`.\n *\n * Delete personal data by scope (user, conversation, customer). Validation\n * messages are identical to Python's, and the body has the same keys in the\n * same order, nulls included.\n */\n\nimport { InvalidInputError } from '../errors.js';\nimport type { HttpTransport } from '../transport/http.js';\nimport type { Json } from '../context/types.js';\n\nexport const DATA_SCOPES = ['user', 'conversation', 'customer'] as const;\nexport type DataScope = (typeof DATA_SCOPES)[number];\n\n/** The most calls `wait` makes. Same as Python's MAX_WAIT_CALLS. */\nexport const MAX_WAIT_CALLS = 50;\n\nconst ID_FIELD: Record<DataScope, string> = {\n user: 'user_id',\n customer: 'customer_id',\n conversation: 'conversation_id',\n};\n\nexport interface DeleteDataOptions {\n /** `\"user\"`, `\"conversation\"` or `\"customer\"`. Client-wide delete is not supported. */\n scope: DataScope | string;\n user_id?: string | null;\n userId?: string | null;\n customer_id?: string | null;\n customerId?: string | null;\n conversation_id?: string | null;\n conversationId?: string | null;\n /** Count what would be removed and change nothing. No `confirm` needed. */\n dry_run?: boolean;\n dryRun?: boolean;\n /** Required unless `dryRun`. Must equal the id of the scope being deleted. */\n confirm?: string | null;\n /** Repeat the call while the server says `continue` (default true, max 50 calls). */\n wait?: boolean;\n}\n\n/** Result of `data.delete` / `data.status`. Mirrors Python's `DeleteDataResult`. */\nexport interface DeleteDataResult {\n deletion_id: string | null;\n /** `complete`, `partial`, `in_progress` or `dry_run`. */\n status: string;\n scope: string | null;\n dry_run: boolean;\n found: boolean;\n counts: Record<string, unknown>;\n stores: Record<string, unknown>;\n still_present_in: string[];\n fully_removed: boolean;\n /** True when the server's size cap stopped the call. */\n continue: boolean;\n kept: string[];\n note: string | null;\n memories_kept: boolean;\n audit: string | null;\n /** What the SDK cleared on this machine after the server finished. */\n local_cleared: string[];\n [key: string]: unknown;\n}\n\nfunction either<T>(o: Record<string, unknown>, snake: string, camel: string): T | undefined {\n const a = o[snake];\n if (a !== undefined) return a as T;\n const b = o[camel];\n return b === undefined ? undefined : (b as T);\n}\n\n/** Validate and build the request body. Throws before any request is sent. */\nexport function buildDeleteBody(options: DeleteDataOptions, instanceId: string): Json {\n const o = options as unknown as Record<string, unknown>;\n const scope = options.scope as unknown;\n if (scope !== null && typeof scope === 'object') {\n throw new InvalidInputError(\n 'scope must be one of: user, conversation, customer. A dict is not ' +\n 'accepted here (the rung-path dict used by memories.create and fetch ' +\n 'is a different parameter).',\n );\n }\n if (typeof scope !== 'string' || !(DATA_SCOPES as readonly string[]).includes(scope)) {\n throw new InvalidInputError(\n `Invalid scope '${String(scope)}'. Expected one of: ${DATA_SCOPES.join(', ')}`,\n );\n }\n const dryRun = either<boolean>(o, 'dry_run', 'dryRun') ?? false;\n if (typeof dryRun !== 'boolean') throw new InvalidInputError('dry_run must be a boolean');\n\n const ids: Record<string, string | null | undefined> = {\n user_id: either<string | null>(o, 'user_id', 'userId'),\n customer_id: either<string | null>(o, 'customer_id', 'customerId'),\n conversation_id: either<string | null>(o, 'conversation_id', 'conversationId'),\n };\n for (const [name, value] of Object.entries(ids)) {\n if (value !== undefined && value !== null && (typeof value !== 'string' || value.trim() === '')) {\n throw new InvalidInputError(`${name} must not be empty`);\n }\n }\n const field = ID_FIELD[scope as DataScope];\n const target = ids[field];\n if (target === undefined || target === null) {\n throw new InvalidInputError(`${field} is required for scope='${scope}'`);\n }\n const confirm = options.confirm ?? null;\n if (!dryRun) {\n if (confirm === null || confirm === '') {\n throw new InvalidInputError(\n `confirm is required unless dry_run=True: pass the ${field} being deleted as confirm`,\n );\n }\n if (confirm !== target) {\n throw new InvalidInputError(`confirm must equal the ${field} being deleted`);\n }\n }\n return {\n scope,\n instance_id: instanceId,\n user_id: ids['user_id'] ?? null,\n customer_id: ids['customer_id'] ?? null,\n conversation_id: ids['conversation_id'] ?? null,\n dry_run: dryRun,\n confirm,\n };\n}\n\n/** Fill every documented field so callers can rely on the shape. */\nfunction normalise(raw: Record<string, unknown>): DeleteDataResult {\n return {\n deletion_id: null,\n status: 'unknown',\n scope: null,\n dry_run: false,\n found: false,\n counts: {},\n stores: {},\n still_present_in: [],\n // Pessimistic: true only when the server said so.\n fully_removed: false,\n continue: false,\n kept: [],\n note: null,\n memories_kept: false,\n audit: null,\n local_cleared: [],\n ...raw,\n } as DeleteDataResult;\n}\n\nexport interface DataInterface {\n /**\n * Delete data for one user, one conversation or one customer. Permanent.\n * scope 'conversation' removes turns, summaries, telemetry and the turn buffer ONLY;\n * memories learned from it are kept (use scope 'user' or memories.delete). Data in\n * another instance is never touched; stores that cannot be scoped by instance are\n * skipped and named in still_present_in.\n *\n * scope 'customer' needs a management key (management:* or *); a runtime key gets 403.\n * LLM call traces are not removed (llm_call_bodies up to 14 days, llm_calls up to 180 days).\n *\n * A store that could not be cleared is in `still_present_in` and\n * `fully_removed` is false; it is a result, not an exception. Errors:\n * `InvalidInputError` (bad arguments, caught before any request, or 400),\n * `AuthenticationError` (401/403), `ConflictError` (409), `RateLimitError`.\n */\n delete(options: DeleteDataOptions): Promise<DeleteDataResult>;\n /** The audit record of a delete (status, counts, still_present_in). */\n status(deletionId: string): Promise<DeleteDataResult>;\n}\n\nexport type DataDeletedHook = (info: {\n scope: string;\n userId: string | null;\n customerId: string | null;\n conversationId: string | null;\n}) => string[];\n\nexport function createDataInterface(\n transport: HttpTransport,\n // Drops this machine's copies; returns what it cleared. Mirrors Python's `_evict_deleted`.\n onDeleted?: DataDeletedHook,\n): DataInterface {\n return {\n async delete(options) {\n const o = options as unknown as Record<string, unknown>;\n await transport.checkCustomerId(\n either<string>(o, 'customer_id', 'customerId'), 'data.delete',\n );\n const body = buildDeleteBody(options, transport.currentCredentials().instanceId);\n const dryRun = body['dry_run'] === true;\n const wait = options.wait ?? true;\n\n let result: DeleteDataResult | null = null;\n for (let i = 0; i < (wait ? MAX_WAIT_CALLS : 1); i += 1) {\n result = normalise(\n await transport.request<Record<string, unknown>>('data_delete', { body }),\n );\n if (dryRun || !result.continue) break;\n }\n const final = result as DeleteDataResult;\n if (!dryRun && ['complete', 'partial', 'in_progress'].includes(final.status) && onDeleted) {\n try {\n final.local_cleared = onDeleted({\n scope: body['scope'] as string,\n userId: (body['user_id'] as string | null) ?? null,\n customerId: (body['customer_id'] as string | null) ?? null,\n conversationId: (body['conversation_id'] as string | null) ?? null,\n });\n } catch { /* eviction is best effort */ }\n }\n return final;\n },\n\n async status(deletionId) {\n if (typeof deletionId !== 'string' || deletionId.trim() === '') {\n throw new InvalidInputError('deletion_id is required');\n }\n return normalise(\n await transport.request<Record<string, unknown>>('data_delete_status', {\n pathParams: { deletion_id: deletionId },\n query: { instance_id: transport.currentCredentials().instanceId },\n }),\n );\n },\n };\n}\n","/** User namespace. Mirrors `UserInterface` in the Python SDK. */\n\nimport { InvalidInputError } from '../errors.js';\nimport type { HttpTransport } from '../transport/http.js';\nimport { fetchContext, type FetchHooks } from '../context/fetch.js';\nimport type { FetchOptions, Json, RawContext } from '../context/types.js';\n\nexport interface UserNamespace {\n get_profile(options: { user_id?: string; userId?: string; customer_id?: string; customerId?: string } | string): Promise<Json>;\n context: { fetch(options?: FetchOptions): Promise<RawContext> };\n}\n\nexport function createUserNamespace(\n transport: HttpTransport,\n hooks: FetchHooks = {},\n): UserNamespace {\n return {\n async get_profile(options) {\n const userId = typeof options === 'string' ? options : (options.user_id ?? options.userId);\n if (!userId) throw new InvalidInputError('user_id is required');\n const customerId =\n typeof options === 'string' ? undefined : (options.customer_id ?? options.customerId);\n return transport.request<Json>('user_profile', {\n pathParams: { user_id: userId },\n // Sent only when provided, matching Python. Note the server returns\n // 500 rather than a clean error if it needs one and does not get it.\n ...(customerId !== undefined ? { query: { customer_id: customerId } } : {}),\n });\n },\n context: { async fetch(options = {}) { return fetchContext(transport, 'user', options, hooks); } },\n };\n}\n","/** Credits namespace. Mirrors `CreditsInterface` in the Python SDK. */\n\nimport { InvalidInputError } from '../errors.js';\nimport type { HttpTransport } from '../transport/http.js';\nimport type { Json } from '../context/types.js';\n\nexport interface EstimateOptions {\n metric_type?: string;\n metricType?: string;\n units?: number;\n item_count?: number;\n itemCount?: number;\n endpoint?: string;\n mode?: string;\n}\n\nexport interface CreditsNamespace {\n get_balance(): Promise<CreditBalance>;\n get_ledger(options?: LedgerOptions): Promise<CreditLedgerPage>;\n estimate(options: EstimateOptions): Promise<CreditEstimate>;\n redeem(code: string): Promise<RedeemResult>;\n}\n\n/**\n * Return types for the credits namespace, mirroring Python's dataclasses in\n * `maximem_synap/credits.py`. These were all `Json` (`Record<string, unknown>`)\n * before, so every field read was `unknown` and no documented example compiled.\n */\nexport interface CreditBucket {\n source_type: string;\n balance: number;\n /** ISO-8601, or null when the bucket does not expire. */\n expires_at: string | null;\n}\n\nexport interface CreditBalance {\n client_id: string;\n balance_credits: number;\n warning_low: boolean;\n buckets: CreditBucket[];\n [key: string]: unknown;\n}\n\nexport interface CreditLedgerEntry {\n ledger_id: string;\n entry_type: string;\n delta: number;\n metric_type: string | null;\n category: string | null;\n /** ISO-8601. */\n created_at: string;\n}\n\nexport interface CreditLedgerPage {\n entries: CreditLedgerEntry[];\n total: number;\n limit: number;\n offset: number;\n [key: string]: unknown;\n}\n\nexport interface CreditEstimate {\n credits_estimate: number;\n [key: string]: unknown;\n}\n\nexport interface RedeemResult {\n redemption_id: string;\n credits_granted: number;\n new_balance_credits: number;\n /** ISO-8601, or null when the granted credits do not expire. */\n expires_at: string | null;\n [key: string]: unknown;\n}\n\n/** Options for `credits.get_ledger`. Mirrors Python's keyword arguments. */\nexport interface LedgerOptions {\n /** Filter to one ledger entry type. */\n entry_type?: string;\n entryType?: string;\n /** Inclusive lower bound. ISO-8601 string or Date. Sent as `from`. */\n from_time?: string | Date;\n fromTime?: string | Date;\n /** Inclusive upper bound. ISO-8601 string or Date. Sent as `to`. */\n to_time?: string | Date;\n toTime?: string | Date;\n /** Defaults to 100, as in Python. */\n limit?: number;\n offset?: number;\n}\n\nfunction iso(v: string | Date): string {\n return v instanceof Date ? v.toISOString() : v;\n}\n\nexport function createCreditsNamespace(transport: HttpTransport): CreditsNamespace {\n return {\n async get_balance() { return transport.request<CreditBalance>('credits_balance'); },\n\n async get_ledger(options: LedgerOptions = {}) {\n // Mirrors Python's CreditsInterface.get_ledger: the three filters were\n // missing here entirely, and the default limit was 50 against Python's\n // 100, so the same call returned different pages in the two SDKs.\n const query: Record<string, string | number> = {\n limit: options.limit ?? 100,\n offset: options.offset ?? 0,\n };\n const entryType = options.entry_type ?? options.entryType;\n if (entryType !== undefined) query['entry_type'] = entryType;\n const from = options.from_time ?? options.fromTime;\n if (from !== undefined) query['from'] = iso(from);\n const to = options.to_time ?? options.toTime;\n if (to !== undefined) query['to'] = iso(to);\n return transport.request<CreditLedgerPage>('credits_ledger', { query });\n },\n\n async estimate(options) {\n return transport.request<CreditEstimate>('credits_estimate', {\n body: {\n metric_type: options.metric_type ?? options.metricType ?? null,\n units: options.units ?? null,\n item_count: options.item_count ?? options.itemCount ?? null,\n endpoint: options.endpoint ?? null,\n mode: options.mode ?? null,\n },\n });\n },\n\n async redeem(code) {\n if (!code) throw new InvalidInputError('code is required');\n // Non-idempotent by contract: redeeming twice consumes two codes.\n return transport.request<RedeemResult>('credits_redeem', { body: { code } });\n },\n };\n}\n","/**\n * MACA plugin namespace (Synap Core). Mirrors `MacaInterface` in the Python SDK.\n *\n * A Synap Core server can have Synap Cloud write its memory config from a short\n * description of your use case. The server holds the Synap Cloud key; this\n * namespace only starts the job and reads it back. Synap Cloud has no such\n * route and answers 404.\n */\n\nimport { InvalidInputError } from '../errors.js';\nimport type { HttpTransport } from '../transport/http.js';\n\ntype BlobSource = NonNullable<ConstructorParameters<typeof Blob>[0]>[number];\n\n/** What a job can end as. Anything else is still running. */\nexport const MACA_FINAL_STATUSES = ['succeeded', 'invalid', 'failed'] as const;\n\nexport type MacaRelationship = 'b2c' | 'b2b';\n\nexport interface MacaJob {\n job_id: string;\n status: string;\n message: string;\n created_at: string | null;\n updated_at: string | null;\n removed_fields: string[];\n problems: string[];\n config_file: string | null;\n /** The generated config, once the job has ended with `succeeded` or `invalid`. */\n yaml: string | null;\n}\n\nexport interface MacaGenerateOptions {\n /** The use-case file (UTF-8 text, at most 256 KB), uploaded as is. */\n file_path?: string;\n filePath?: string;\n /** `b2c`: each user is their own customer. `b2b`: users sit under a customer. */\n user_relationship?: MacaRelationship;\n userRelationship?: MacaRelationship;\n}\n\n/** The server refuses a larger use-case file. */\nexport const MACA_MAX_FILE_BYTES = 256 * 1024;\n\nexport interface MacaWaitOptions {\n timeout_seconds?: number;\n timeoutSeconds?: number;\n poll_interval_seconds?: number;\n pollIntervalSeconds?: number;\n}\n\nexport interface MacaNamespace {\n generate(options: MacaGenerateOptions): Promise<MacaJob>;\n get_job(jobId: string): Promise<MacaJob>;\n wait_for_completion(jobId: string, options?: MacaWaitOptions): Promise<MacaJob>;\n}\n\nfunction toJob(raw: Record<string, unknown>): MacaJob {\n return {\n job_id: String(raw['job_id']),\n status: String(raw['status']),\n message: typeof raw['message'] === 'string' ? raw['message'] : '',\n created_at: typeof raw['created_at'] === 'string' ? raw['created_at'] : null,\n updated_at: typeof raw['updated_at'] === 'string' ? raw['updated_at'] : null,\n removed_fields: Array.isArray(raw['removed_fields']) ? (raw['removed_fields'] as string[]) : [],\n problems: Array.isArray(raw['problems']) ? (raw['problems'] as string[]) : [],\n config_file: typeof raw['config_file'] === 'string' ? raw['config_file'] : null,\n yaml: typeof raw['yaml'] === 'string' ? raw['yaml'] : null,\n };\n}\n\nexport function createMacaNamespace(transport: HttpTransport): MacaNamespace {\n const namespace: MacaNamespace = {\n async generate(options) {\n const filePath = options.file_path ?? options.filePath;\n const relationship = options.user_relationship ?? options.userRelationship;\n if (relationship !== 'b2c' && relationship !== 'b2b') {\n throw new InvalidInputError(\"user_relationship must be 'b2c' or 'b2b'\");\n }\n if (typeof filePath !== 'string' || !filePath) throw new InvalidInputError('file_path is required');\n\n // Lazy, so importing the SDK on Edge or in a Worker stays safe: a top-level `node:fs` import fails the BUILD there.\n const { readFile, stat } = await import('node:fs/promises');\n const { basename } = await import('node:path');\n let size: number;\n try {\n size = (await stat(filePath)).size;\n } catch {\n throw new InvalidInputError(`file_path does not point to a readable file: ${filePath}`);\n }\n if (size === 0) throw new InvalidInputError('The use-case file is empty');\n if (size > MACA_MAX_FILE_BYTES) {\n throw new InvalidInputError(`The use-case file is larger than ${MACA_MAX_FILE_BYTES / 1024} KB`);\n }\n const bytes = await readFile(filePath);\n\n const form = new FormData();\n form.set('user_relationship', relationship);\n form.set('file', new Blob([bytes as unknown as BlobSource]), basename(filePath));\n // Non-idempotent by contract: a second call starts a second job (the server refuses it with 409).\n return toJob(await transport.request<Record<string, unknown>>('maca_generate', { body: form, rawBody: true }));\n },\n\n async get_job(jobId) {\n if (!jobId) throw new InvalidInputError('job_id is required');\n return toJob(await transport.request<Record<string, unknown>>('maca_job', { pathParams: { job_id: jobId } }));\n },\n\n async wait_for_completion(jobId, options = {}) {\n const timeout = (options.timeout_seconds ?? options.timeoutSeconds ?? 3000) * 1000;\n const interval = (options.poll_interval_seconds ?? options.pollIntervalSeconds ?? 15) * 1000;\n const start = Date.now();\n while (Date.now() - start < timeout) {\n const job = await namespace.get_job(jobId);\n if ((MACA_FINAL_STATUSES as readonly string[]).includes(job.status)) return job;\n await new Promise((resolve) => setTimeout(resolve, interval));\n }\n throw new Error(`MACA job ${jobId} did not finish within ${timeout / 1000}s`);\n },\n };\n return namespace;\n}\n","/**\n * Cache namespace. Same method names as `CacheInterface` in the Python SDK,\n * but it covers only the in-memory cache of prefetched context: `stats()`\n * returns `{ bundles, items }`, not Python's `enabled`, `total_entries`,\n * `total_bytes` and `backends`. There is no on-disk cache in JS.\n *\n * This is a deliberately narrow facade over the AnticipationCache rather than\n * the cache object itself. Exposing the instance directly leaked internals\n * (`client.cache.now` was reachable) and gave JS a different surface from\n * Python for no benefit. The cache is still reachable as\n * `client.anticipationCache` for advanced use.\n */\n\nimport type { AnticipationCache } from '../context/anticipation-cache.js';\nimport { InvalidInputError } from '../errors.js';\n\nexport interface CacheStats {\n bundles: number;\n items: number;\n [key: string]: unknown;\n}\n\nexport interface CacheNamespace {\n clear(): void;\n clear_user(userId: string): void;\n clear_customer(customerId: string): void;\n stats(): CacheStats;\n}\n\nexport function createCacheNamespace(cache: AnticipationCache): CacheNamespace {\n return {\n clear: () => cache.clear(),\n\n clear_user: (userId) => {\n if (!userId) throw new InvalidInputError('user_id is required');\n cache.dropEntity(userId);\n },\n\n clear_customer: (customerId) => {\n if (!customerId) throw new InvalidInputError('customer_id is required');\n cache.dropEntity(customerId);\n },\n\n stats: () => ({ bundles: cache.size, items: cache.itemCount }),\n };\n}\n","/**\n * Instance namespace. Mirrors `InstanceInterface` in the Python SDK.\n *\n * Everything here rides the bidirectional gRPC Listen stream. The stream module\n * is loaded through a lazy `import()` so that importing this SDK on Edge or in\n * a Worker stays safe: grpc-js is built on `node:http2`/`node:net`/`node:tls`\n * and a static import fails the BUILD there, not the call.\n */\n\nimport { agentModelOf, withAgentModel, type AgentModel } from '../agent-model.js';\nimport {\n InvalidInputError, ListeningAlreadyActiveError, ListeningNotActiveError, SynapError,\n SynapPermanentError,\n} from '../errors.js';\nimport type { AnticipationCache } from '../context/anticipation-cache.js';\nimport type { StreamCredentials, StreamState } from '../grpc/stream-client.js';\nimport { getEnv } from '../util/env.js';\nimport { newCorrelationId } from '../util/correlation.js';\nimport {\n MAX_STREAM_IMAGE_BYTES, normaliseContent, toInlineParts, type ContentPart,\n} from '../memories/parts.js';\n\n/**\n * The metadata key a streamed event's parts travel under. The proto has no\n * field for them, so they ride in metadata as a JSON string, and `content`\n * carries the placeholder rendering so an older server still records text.\n */\nexport const CONTENT_PARTS_METADATA_KEY = 'synap_content_parts';\n\nexport interface ListenOptions {\n /** Called with the attempt count each time the stream reconnects. */\n on_reconnect?: (attempt: number) => void;\n onReconnect?: (attempt: number) => void;\n /** Called with a reason string when the stream drops. */\n on_disconnect?: (reason: string) => void;\n onDisconnect?: (reason: string) => void;\n /**\n * Called for every bundle that arrives. Bundles are ALSO stored in the\n * anticipation cache automatically, so `fetch()` finds them without a round\n * trip; this callback is for observing, not for wiring up storage.\n */\n on_context?: (bundle: Record<string, unknown>) => void;\n onContext?: (bundle: Record<string, unknown>) => void;\n /** Overrides `SYNAP_GRPC_HOST`. */\n host?: string;\n /** Overrides `SYNAP_GRPC_PORT`. */\n port?: number;\n /** Overrides `SYNAP_GRPC_USE_TLS`. Plaintext only makes sense against localhost. */\n use_tls?: boolean;\n useTls?: boolean;\n}\n\nexport interface SendMessageOptions {\n /**\n * A string, or a list of strings, `TextPart`s and `FilePart`s (images). A\n * list with no file is joined with `\"\\n\"`. With a file, the parts go in\n * `metadata.synap_content_parts` (images inline as base64, at most 2.5 MB of\n * raw image bytes per event) and `content` becomes the placeholder text,\n * each image as `[image: <filename>]`.\n */\n content: string | ContentPart[];\n role?: string;\n conversation_id?: string;\n conversationId?: string;\n user_id?: string;\n userId?: string;\n customer_id?: string;\n customerId?: string;\n session_id?: string;\n sessionId?: string;\n event_type?: string;\n eventType?: string;\n metadata?: Record<string, string>;\n /** The agent's model, as on `conversation.record_message`. Python's `model=`. */\n model?: string;\n context_window?: number;\n contextWindow?: number;\n /**\n * Report a tool call on the stream. Python's `send_message` takes both, and\n * the proto has `tool_name` / `tool_args_json`; the JS surface simply never\n * exposed them, so a tool call could not be reported from JavaScript.\n */\n tool_name?: string;\n toolName?: string;\n tool_args?: Record<string, unknown>;\n toolArgs?: Record<string, unknown>;\n /**\n * What a tool returned. Travels in its own proto field, not in `content`: a\n * result is not something a person said, and everything that filters on\n * messages reads `content`.\n */\n tool_result?: unknown;\n toolResult?: unknown;\n /** Ties a result to the call that asked for it. */\n tool_call_id?: string;\n toolCallId?: string;\n search_queries?: string[];\n searchQueries?: string[];\n context_types?: string[];\n contextTypes?: string[];\n /**\n * The level of your scope ladder this conversation belongs to. Sent as the\n * event's `scope`; the server keeps the first one it sees. Since 0.5.18.\n */\n scope_path?: Record<string, string>;\n scopePath?: Record<string, string>;\n}\n\nexport interface RecordThinkingOptions {\n content: string;\n /**\n * Ordinal of this thought within the current turn. Sent as a `step_index`\n * metadata key, which is how Python's `record_thinking` transmits it: the\n * proto has no dedicated field.\n */\n step_index?: number;\n stepIndex?: number;\n /** Free-form label for the kind of reasoning. Sent as `thought_type`. */\n thought_type?: string;\n thoughtType?: string;\n conversation_id?: string;\n conversationId?: string;\n user_id?: string;\n userId?: string;\n customer_id?: string;\n customerId?: string;\n session_id?: string;\n sessionId?: string;\n metadata?: Record<string, string>;\n}\n\nexport interface RecordToolCallOptions {\n tool_name?: string;\n toolName?: string;\n tool_args?: Record<string, unknown>;\n toolArgs?: Record<string, unknown>;\n tool_call_id?: string;\n toolCallId?: string;\n conversation_id?: string;\n conversationId?: string;\n user_id?: string;\n userId?: string;\n customer_id?: string;\n customerId?: string;\n session_id?: string;\n sessionId?: string;\n metadata?: Record<string, string>;\n}\n\nexport interface RecordToolResultOptions {\n /** JSON-encodable, or a plain string. A string is sent as itself. */\n result: unknown;\n tool_name?: string;\n toolName?: string;\n tool_call_id?: string;\n toolCallId?: string;\n conversation_id?: string;\n conversationId?: string;\n user_id?: string;\n userId?: string;\n customer_id?: string;\n customerId?: string;\n session_id?: string;\n sessionId?: string;\n metadata?: Record<string, string>;\n}\n\nexport interface InstanceNamespace {\n listen(options?: ListenOptions): Promise<void>;\n stop_listening(): Promise<void>;\n send_message(options: SendMessageOptions): Promise<void>;\n record_thinking(options: RecordThinkingOptions): Promise<void>;\n record_tool_call(options: RecordToolCallOptions): Promise<void>;\n record_tool_result(options: RecordToolResultOptions): Promise<void>;\n end_session(conversationId: string): Promise<void>;\n /** Property, not a method, matching Python's InstanceInterface.is_listening. */\n readonly is_listening: boolean;\n /** Not in Python: lets the compaction subscriptions share this one stream. */\n readonly _internal: InstanceInternals;\n}\n\n/** @internal Shared with the conversation namespace so both use one stream. */\nexport interface InstanceInternals {\n onCompactionUpdate(conversationId: string, bundle: Record<string, unknown>): void;\n /** Set by the client so a compaction can prune the locally buffered tail. */\n setCompactionApplier(apply: (bundle: Record<string, unknown>) => void): void;\n /**\n * Set by the client: called when `listen()` starts, which is when prefetched\n * bundles begin to arrive, so the local embedding model loads then.\n */\n setOnListen(handle: () => void): void;\n /** Set by the client in local mode: `listen()` then throws this message instead of opening a stream. */\n blockListen(message: string): void;\n /**\n * Set by the client. Receives the server's message count for a conversation\n * after each streamed write has been stored.\n */\n setConversationStateHandler(\n handle: (conversationId: string, messageCount: number) => void,\n ): void;\n /** Learning-loop event, fired after a fetch is served from the cache. */\n sendContextUsed(event: Record<string, unknown>): void;\n /** Audit event, fired after every fetch resolves. */\n sendContextAssembled(event: Record<string, unknown>): void;\n setCompactionDispatcher(\n dispatch: (conversationId: string, bundle: Record<string, unknown>) => void,\n ): void;\n isListening(): boolean;\n}\n\ntype StreamClient = import('../grpc/stream-client.js').GrpcStreamClient;\n\nconst DEFAULT_GRPC_HOST = 'synap-cloud-prod.maximem.ai';\nconst DEFAULT_GRPC_PORT = 443;\n\nfunction envPort(): number | undefined {\n const raw = getEnv('SYNAP_GRPC_PORT');\n if (raw === undefined || raw === '') return undefined;\n const parsed = Number(raw);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\n\nfunction envTls(): boolean | undefined {\n // SYNAP_GRPC_TLS is the 0.3.x wrapper's spelling. Honoured as a fallback,\n // because silently ignoring it turns a working plaintext deployment into one\n // that attempts TLS and cannot connect, with nothing pointing at the cause.\n const raw = getEnv('SYNAP_GRPC_USE_TLS') ?? getEnv('SYNAP_GRPC_TLS');\n if (raw === undefined || raw === '') return undefined;\n return !['0', 'false', 'no', 'off'].includes(raw.trim().toLowerCase());\n}\n\n/**\n * Fold `step_index` and `thought_type` into the metadata map.\n *\n * Python does exactly this (`sdk.py`, record_thinking): the proto carries no\n * dedicated fields, so the values ride in metadata under those two keys. A\n * caller-supplied metadata entry of the same name is not overwritten.\n */\nfunction thinkingMetadata(options: RecordThinkingOptions): Record<string, string> {\n const md: Record<string, string> = { ...(options.metadata ?? {}) };\n const step = options.step_index ?? options.stepIndex;\n if (step !== undefined && md['step_index'] === undefined) {\n md['step_index'] = String(step);\n }\n const kind = options.thought_type ?? options.thoughtType;\n if (kind && md['thought_type'] === undefined) {\n md['thought_type'] = kind;\n }\n return md;\n}\n\n/**\n * Event types the server has a reader for. Mirrors `KNOWN_EVENT_TYPES` in the\n * Python SDK. An unknown type falls through every classifier on the server into\n * UNKNOWN, where nothing reads it, so a typo used to cost the whole signal\n * without saying so.\n */\nconst KNOWN_EVENT_TYPES: ReadonlySet<string> = new Set([\n 'user_message',\n 'assistant_message',\n 'tool_call',\n 'tool_result',\n 'agent_thinking',\n 'context_request',\n 'context_fetch',\n 'session_start',\n 'session_end',\n]);\n\n/**\n * Serialise a tool result the way Python does: a string travels as itself,\n * anything else as JSON. `JSON.stringify` on a plain-text answer would wrap it\n * in quotes and the agent would read the quotes as part of the result.\n */\nfunction toolResultJson(result: unknown): string {\n if (result === undefined || result === null) return '';\n return typeof result === 'string' ? result : jsonOrText(result);\n}\n\n/**\n * JSON for whatever serialises, the value's text form for whatever does not.\n * Mirrors Python's `_json_or_text` in `sdk.py`.\n *\n * ⚠ This was a bare `JSON.stringify` and that lost events. It throws on a\n * circular object and on a `BigInt`, and it returns `undefined` rather than a\n * string for a function or a bare `undefined`. Every integration reports\n * through a helper that swallows exceptions on purpose, so a telemetry call can\n * never break somebody's agent loop, which means the throw went nowhere and the\n * whole tool event was silently never sent. Losing the exact shape of an object\n * is a far smaller loss than losing the event.\n */\nfunction jsonOrText(value: unknown): string {\n try {\n const out = JSON.stringify(\n value,\n (_k, v: unknown) => (typeof v === 'bigint' ? String(v) : v),\n );\n // `undefined` for a function, a symbol, or `undefined` itself.\n return out === undefined ? String(value) : out;\n } catch {\n // A cycle, or a `toJSON` of the caller's that throws.\n try {\n return String(value);\n } catch {\n return '';\n }\n }\n}\n\nexport function createInstanceNamespace(\n credentials: () => StreamCredentials,\n cache: AnticipationCache,\n /** Buffers a stream-sent turn locally, same as the HTTP write paths. */\n onTurn?: (turn: { conversationId: string; role: string; content: string }) => void,\n // `fetchUrl` was introduced before the later internal callbacks. Accept both\n // call layouts while consumers move to the current one:\n // (onTurn, fetchUrl, agentModel, onToolResult, checkCustomerId), and\n // (onTurn, agentModel, onToolResult, checkCustomerId).\n fetchOrAgentModel?: typeof fetch | (() => AgentModel),\n agentModelOrToolResult?: (() => AgentModel) | ((r: { conversationId: string; result: unknown; toolName: string }) => void),\n onToolResultOrCheck?: ((r: { conversationId: string; result: unknown; toolName: string }) => void) | ((customerId: unknown, where: string) => Promise<void>),\n checkCustomerIdArg?: (customerId: unknown, where: string) => Promise<void>,\n): InstanceNamespace {\n const defaultFetch = ((url: string, init?: RequestInit) => globalThis.fetch(url, init)) as typeof fetch;\n const imageFirst = fetchOrAgentModel !== undefined\n && (fetchOrAgentModel.length > 0 || agentModelOrToolResult === undefined);\n const fetchUrl = imageFirst ? fetchOrAgentModel as typeof fetch : defaultFetch;\n const agentModel = (imageFirst ? agentModelOrToolResult : fetchOrAgentModel) as (() => AgentModel) | undefined\n ?? (() => ({}));\n const onToolResult = (imageFirst ? onToolResultOrCheck : agentModelOrToolResult) as\n | ((r: { conversationId: string; result: unknown; toolName: string }) => void)\n | undefined;\n const checkCustomerId = (imageFirst ? checkCustomerIdArg : onToolResultOrCheck) as\n | ((customerId: unknown, where: string) => Promise<void>)\n | undefined\n ?? (async () => {});\n const hasCustomerIdCheck = (imageFirst ? checkCustomerIdArg : onToolResultOrCheck) !== undefined;\n let client: StreamClient | null = null;\n // conversationId -> sessionId, for conversations this stream has opened a\n // session for. Cleared on reconnect: a session belongs to the stream that\n // carried it, and the server's new stream has never seen it.\n const openSessions = new Map<string, string>();\n let dispatchCompaction:\n | ((conversationId: string, bundle: Record<string, unknown>) => void)\n | null = null;\n\n let applyCompaction: ((bundle: Record<string, unknown>) => void) | null = null;\n let onListen: (() => void) | null = null;\n let listenBlockedBy: string | null = null;\n let onConversationState: ((conversationId: string, messageCount: number) => void) | null =\n null;\n\n const internals: InstanceInternals = {\n onCompactionUpdate(conversationId, bundle) {\n // Prune the local tail FIRST, then notify subscribers, so a subscriber\n // that immediately fetches sees the post-compaction view.\n applyCompaction?.(bundle);\n dispatchCompaction?.(conversationId, bundle);\n },\n setCompactionApplier(apply) {\n applyCompaction = apply;\n },\n setOnListen(handle) {\n onListen = handle;\n },\n blockListen(message) {\n listenBlockedBy = message;\n },\n setConversationStateHandler(handle) {\n onConversationState = handle;\n },\n sendContextUsed(event) {\n // Fire-and-forget. A reconnecting stream holds the report and sends it\n // when it is back; with no stream at all (listen never started, or\n // stopped) nothing was prefetched, so there is no hit to report.\n client?.sendContextUsed(event);\n },\n sendContextAssembled(event) {\n client?.sendContextAssembled(event);\n },\n setCompactionDispatcher(dispatch) {\n dispatchCompaction = dispatch;\n },\n isListening() {\n return client !== null && client.isConnected;\n },\n };\n\n /**\n * Open a session for this conversation if the stream has not yet.\n *\n * The developer never calls this. `session_start` is what makes the server\n * run its warm-up prefetch before the first message arrives, and asking every\n * caller to remember a lifecycle call is how the first turn of every\n * conversation stayed a cold fetch: neither SDK sent one, ever.\n *\n * Best effort. A session that cannot be opened must not stop the event that\n * triggered it, so the conversation stays unmarked and the next event retries.\n */\n function ensureSession(\n conversationId: string, userId: string, customerId: string,\n ): void {\n // Both ids, or no session. The server refuses a session_start with no\n // user_id, and writing one only says it went out, not that it was\n // accepted — so opening on an event with no user_id marked the\n // conversation as open, never retried, and left `end_session` referring to\n // a session the server never had. The next event that carries a user_id\n // opens it.\n if (!conversationId || !userId || client === null) return;\n if (openSessions.has(conversationId)) return;\n // The same helper the correlation ids use: a session id is an identifier\n // for tracing, never a security value, and that helper is the one that is\n // safe on Edge and Workers, where `node:crypto` breaks the build.\n const sessionId = newCorrelationId();\n try {\n client.sendSessionControl({\n action: 'start',\n session_id: sessionId,\n conversation_id: conversationId,\n ...(userId ? { user_id: userId } : {}),\n ...(customerId ? { customer_id: customerId } : {}),\n });\n openSessions.set(conversationId, sessionId);\n } catch {\n // Leave it unmarked so the next event opens it.\n }\n }\n\n /**\n * Keeps conversation events in call order.\n *\n * A send whose content holds a file has to read it first, which is async,\n * so a caller who fires `send_message(image)` then `send_message(text)`\n * without awaiting would otherwise see the text reach the stream first. A\n * send that needs no read, while nothing is queued ahead of it, goes out\n * synchronously exactly as it always did; anything else waits its turn. File\n * reads still start at once, so only the sending is serialised.\n */\n let tail: Promise<void> = Promise.resolve();\n let queued = 0;\n function inOrder<T>(prepared: Promise<T> | null, send: (value: T) => void, sync?: T): Promise<void> {\n if (prepared === null && queued === 0) {\n send(sync as T);\n return Promise.resolve();\n }\n // Marked handled now: a rejection is surfaced through `run`, but only once\n // the sends ahead of it are done, and Node must not flag it before then.\n prepared?.catch(() => {});\n queued += 1;\n const run = tail.then(async () => {\n send(prepared === null ? (sync as T) : await prepared);\n });\n const done = () => {\n queued -= 1;\n };\n // The chain never rejects, so one failed send cannot block the next.\n tail = run.then(done, done);\n return run;\n }\n\n const namespace: InstanceNamespace = {\n async listen(options: ListenOptions = {}) {\n if (listenBlockedBy !== null) throw new SynapPermanentError(listenBlockedBy);\n if (client !== null) {\n // Python raises this from InstanceController when a second listen()\n // lands on an already-active stream.\n throw new ListeningAlreadyActiveError('Listening is already active on this instance');\n }\n\n try {\n onListen?.();\n } catch {\n /* loading the local model must never stop the stream */\n }\n const { GrpcStreamClient } = await import('../grpc/stream-client.js');\n const onContext = options.on_context ?? options.onContext;\n const onDisconnect = options.on_disconnect ?? options.onDisconnect;\n const onReconnect = options.on_reconnect ?? options.onReconnect;\n let reconnectAttempts = 0;\n\n // Assigned immediately below; the callbacks that read it only run later,\n // once the stream is live.\n let stream: InstanceType<typeof GrpcStreamClient> | null = null;\n\n const created = new GrpcStreamClient(credentials(), cache, {\n host: options.host ?? getEnv('SYNAP_GRPC_HOST') ?? DEFAULT_GRPC_HOST,\n port: options.port ?? envPort() ?? DEFAULT_GRPC_PORT,\n useTls: options.use_tls ?? options.useTls ?? envTls() ?? true,\n ...(onContext !== undefined ? { onContext } : {}),\n onCompactionUpdate: (conversationId, bundle) => {\n internals.onCompactionUpdate(conversationId, bundle);\n },\n onConversationState: (conversationId, messageCount) => {\n onConversationState?.(conversationId, messageCount);\n },\n onStateChange: (state: StreamState) => {\n // Any state change away from connected retires the sessions this\n // stream opened: the server's next stream has no memory of them, and\n // a client that believes one is open never warms up again.\n if (state !== 'connected') openSessions.clear();\n if (state === 'reconnecting') {\n reconnectAttempts += 1;\n onReconnect?.(reconnectAttempts);\n } else if (state === 'disconnected') {\n // A credit refusal names itself, the way Python's transport does,\n // so a handler can tell \"the server ran out of patience\" from\n // \"this account cannot pay for the stream\".\n const stopped = stream?.lastError ?? null;\n const reason = stopped === null\n ? 'stream disconnected'\n : `credit_stop:${(stopped as { reason?: string | null }).reason ?? 'unknown'}`;\n onDisconnect?.(reason);\n }\n },\n });\n stream = created;\n\n try {\n await created.connect();\n } catch (error) {\n // Leave `client` null so a retry is possible rather than being\n // rejected as \"already active\" forever.\n if (error instanceof SynapError) throw error;\n throw new SynapError(\n `Could not open the Synap anticipation stream: ${(error as Error)?.message ?? String(error)}`,\n { cause: error },\n );\n }\n client = created;\n },\n\n async stop_listening() {\n // Resolves rather than rejecting: stopping something that was never\n // started is a no-op in Python too, and a cleanup path that throws is\n // worse than useless in a finally block.\n if (client === null) return;\n // Close what this stream opened. A session that is never closed leaves\n // the turn it was in the middle of uncommitted on the server: that row is\n // written when the NEXT user message arrives, and the last turn of a\n // conversation has no next one.\n for (const conversationId of [...openSessions.keys()]) {\n await namespace.end_session(conversationId);\n }\n const active = client;\n client = null;\n await active.disconnect();\n },\n\n async end_session(conversationId: string) {\n const sessionId = openSessions.get(conversationId);\n if (sessionId === undefined || client === null) return;\n openSessions.delete(conversationId);\n try {\n client.sendSessionControl({\n action: 'end',\n session_id: sessionId,\n conversation_id: conversationId,\n });\n } catch {\n // A teardown path must not throw.\n }\n },\n\n async send_message(options: SendMessageOptions) {\n // First, as Python checks it. Until 0.5.18 the stream skipped it, so a\n // B2C customer_id went out and the server refused the event on the\n // stream, where nothing surfaced it.\n if (hasCustomerIdCheck) {\n await checkCustomerId(\n options.customer_id ?? options.customerId, 'instance.send_message',\n );\n }\n if (client === null) throw new ListeningNotActiveError('Listening is not active');\n const eventType = options.event_type ?? options.eventType ?? 'user_message';\n // InvalidInputError, as Python raises both. Until 0.5.18 a bad\n // event_type was a bare SynapError and a missing content a\n // ListeningNotActiveError.\n if (!KNOWN_EVENT_TYPES.has(eventType)) {\n throw new InvalidInputError(\n `unknown event_type '${eventType}'. Expected one of: `\n + [...KNOWN_EVENT_TYPES].sort().join(', '),\n );\n }\n if (options.content === undefined || options.content === null) {\n throw new InvalidInputError('content is required');\n }\n const parts = normaliseContent(options.content, 'content');\n const emit = ({ content, metadata }: { content: string; metadata: Record<string, string> }) => {\n // A file read can take a while; the stream may have gone in the meantime.\n if (client === null) throw new ListeningNotActiveError('Listening is not active');\n const conversationId = options.conversation_id ?? options.conversationId ?? '';\n ensureSession(\n conversationId,\n options.user_id ?? options.userId ?? '',\n options.customer_id ?? options.customerId ?? '',\n );\n // Only conversational turns belong in the local short-term buffer. A tool\n // call or a result is not a turn, and buffering one splices it into the\n // caller's own prompt as if somebody had said it. Python mirrors user and\n // assistant messages only; this side mirrored everything.\n if (eventType === 'user_message' || eventType === 'assistant_message') {\n onTurn?.({\n conversationId,\n role: options.role ?? 'user',\n content,\n });\n }\n client.sendConversationEvent({\n event_type: eventType,\n content,\n role: options.role ?? 'user',\n conversation_id: options.conversation_id ?? options.conversationId ?? '',\n user_id: options.user_id ?? options.userId ?? '',\n customer_id: options.customer_id ?? options.customerId ?? '',\n session_id: options.session_id ?? options.sessionId\n ?? openSessions.get(conversationId) ?? '',\n metadata: withAgentModel(metadata, agentModelOf(options), agentModel(), true) ?? {},\n timestamp_ms: Date.now(),\n tool_name: options.tool_name ?? options.toolName ?? '',\n // Python serialises tool_args with json.dumps into tool_args_json.\n tool_args_json: (() => {\n const a = options.tool_args ?? options.toolArgs;\n return a === undefined ? '' : jsonOrText(a);\n })(),\n tool_result_json: toolResultJson(options.tool_result ?? options.toolResult),\n tool_call_id: options.tool_call_id ?? options.toolCallId ?? '',\n search_queries: options.search_queries ?? options.searchQueries ?? [],\n context_types: options.context_types ?? options.contextTypes ?? [],\n ...(() => {\n const sp = options.scope_path ?? options.scopePath;\n return sp && Object.keys(sp).length > 0 ? { scope: sp } : {};\n })(),\n });\n };\n\n if (parts?.kind !== 'parts') {\n const content = parts?.kind === 'text' ? parts.text : (options.content as string);\n return inOrder(null, emit, { content, metadata: options.metadata ?? {} });\n }\n const prepared = (async () => {\n const inline = await toInlineParts(parts.parts, fetchUrl);\n if (inline.rawBytes > MAX_STREAM_IMAGE_BYTES) {\n // Python's message, word for word.\n throw new InvalidInputError(\n `The images in this event come to more than ${MAX_STREAM_IMAGE_BYTES} bytes, ` +\n 'which is over what one streamed event can carry. Send them with ' +\n 'memories.create or conversation.record_message instead.',\n );\n }\n return {\n content: inline.placeholder,\n metadata: {\n ...(options.metadata ?? {}),\n [CONTENT_PARTS_METADATA_KEY]: JSON.stringify(inline.wire),\n },\n };\n })();\n return inOrder(prepared, emit);\n },\n\n async record_tool_call(options: RecordToolCallOptions) {\n // Prefer this over `send_message({ event_type: 'tool_call' })`. The event\n // carries both an event_type and a role and the two have to agree;\n // getting the role wrong was silent, and our own published example got it\n // wrong. Here you cannot: the method sets both.\n await namespace.send_message({\n content: '',\n role: 'assistant',\n event_type: 'tool_call',\n tool_name: options.tool_name ?? options.toolName ?? '',\n ...(options.tool_args ?? options.toolArgs\n ? { tool_args: options.tool_args ?? options.toolArgs }\n : {}),\n tool_call_id: options.tool_call_id ?? options.toolCallId ?? '',\n conversation_id: options.conversation_id ?? options.conversationId ?? '',\n user_id: options.user_id ?? options.userId ?? '',\n customer_id: options.customer_id ?? options.customerId ?? '',\n session_id: options.session_id ?? options.sessionId ?? '',\n metadata: options.metadata ?? {},\n });\n },\n\n async record_tool_result(options: RecordToolResultOptions) {\n // ⚠ A tool result is usually the caller's customer data. It is an\n // anticipation hint and is not written into long-term memory, but it does\n // reach us: send what the agent needs, not the whole row.\n const conversationId = options.conversation_id ?? options.conversationId ?? '';\n if (conversationId) {\n onToolResult?.({ conversationId, result: options.result, toolName: options.tool_name ?? options.toolName ?? '' });\n }\n await namespace.send_message({\n content: '',\n role: 'tool',\n event_type: 'tool_result',\n tool_result: options.result,\n tool_name: options.tool_name ?? options.toolName ?? '',\n tool_call_id: options.tool_call_id ?? options.toolCallId ?? '',\n conversation_id: options.conversation_id ?? options.conversationId ?? '',\n user_id: options.user_id ?? options.userId ?? '',\n customer_id: options.customer_id ?? options.customerId ?? '',\n session_id: options.session_id ?? options.sessionId ?? '',\n metadata: options.metadata ?? {},\n });\n },\n\n async record_thinking(options: RecordThinkingOptions) {\n if (client === null) throw new ListeningNotActiveError('Listening is not active');\n const conversationId = options.conversation_id ?? options.conversationId ?? '';\n ensureSession(\n conversationId,\n options.user_id ?? options.userId ?? '',\n options.customer_id ?? options.customerId ?? '',\n );\n // Queued behind an earlier send that is still reading a file, so the\n // thought reaches the stream after it, as it was called.\n return inOrder(null, () => {\n if (client === null) throw new ListeningNotActiveError('Listening is not active');\n client.sendConversationEvent({\n // Python emits reasoning as an `agent_thinking` conversation event.\n event_type: 'agent_thinking',\n content: options.content,\n // Deliberately no role. A thought is not the assistant's reply, and\n // this went out as 'assistant' from the day it shipped: the server\n // checked role before event_type, so every reasoning step any client\n // sent was filed as the final answer and the reasoning path never ran.\n // Sending no role is correct against both the fixed server and one that\n // has not been updated yet.\n role: '',\n conversation_id: options.conversation_id ?? options.conversationId ?? '',\n user_id: options.user_id ?? options.userId ?? '',\n customer_id: options.customer_id ?? options.customerId ?? '',\n session_id: options.session_id ?? options.sessionId ?? '',\n metadata: thinkingMetadata(options),\n timestamp_ms: Date.now(),\n });\n }, undefined);\n },\n\n get is_listening() {\n return client !== null && client.isConnected;\n },\n\n _internal: internals,\n };\n\n return namespace;\n}\n","/**\n * Kept in sync with package.json by the release workflow, in the\n * \"Sync SDK_VERSION to the resolved version\" step of publish-npm-js-sdk.yml.\n *\n * Until that step existed nothing kept it in sync, so this constant sat at\n * 1.0.0-beta.0 while the package shipped 0.4.x, and every request's User-Agent\n * and every telemetry event reported a version that was never released.\n *\n * ⚠ The workflow only covers a workflow release. 0.4.8 was published by hand\n * and shipped reporting 0.4.7, so every request from it carries a User-Agent\n * for a version it is not. `version-matches-package.test.ts` now fails the\n * build when the two disagree, which is the only thing that makes a manual\n * publish safe.\n */\nexport const SDK_VERSION = '0.7.1';\n","/**\n * Client registry: one shared client per identity, per process.\n *\n * Mirrors Python's `registry.py`. Without it, every `new SynapClient()` gets\n * its own anticipation cache, so a framework integration that constructs a\n * client per request or per agent never gets a cache hit and pays for a fresh\n * retrieval every time. Python has shared state here since 0.2; matching it is\n * the difference between a warm cache and a metered fetch on every turn.\n *\n * JavaScript reaches the same end differently. Python does\n * `self.__dict__ = existing.__dict__`, aliasing state between distinct\n * objects. A JS constructor can simply RETURN the existing instance, so the\n * two callers hold the same object rather than two objects sharing a state\n * bag. That is stricter than Python and avoids its `__dict__`-identity\n * comparisons entirely.\n */\n\n/** Kept structural so the registry does not depend on the client's type. */\nexport interface RegistrableClient {\n shutdown(): Promise<void>;\n}\n\nconst instances = new Map<string, RegistrableClient>();\n\n/**\n * Which registry slot an identity belongs in.\n *\n * `instanceId` keys the singleton when present, but it is usually empty at\n * construction and only resolved from the API key during `initialize()`.\n * Keying on it directly would put every `new SynapClient({ apiKey })` in one\n * process onto the single `''` slot, where the second would adopt the first's\n * credentials. So fall back to the credential that WILL resolve the identity,\n * stored as a truncated SHA-256 digest rather than plaintext, so a registry\n * dump or a log line cannot leak a key.\n *\n * `SYNAP_INSTANCE_ID` is deliberately not consulted: the client applies that\n * fallback after the lookup, and honouring it here would put two different\n * credentials back onto one slot whenever the variable happens to be set.\n */\nexport function buildRegistryKey(instanceId: string, apiKey: string | undefined): string {\n if (instanceId) return instanceId;\n const key = apiKey ?? '';\n // Nothing to key on. The client cannot initialise without a credential\n // anyway, so preserve the empty slot rather than inventing one.\n if (!key) return '';\n return `apikey:${digest(key)}`;\n}\n\n/**\n * 64-bit FNV-1a over the credential.\n *\n * Python uses SHA-256 here. This cannot: the digest is needed synchronously\n * inside a constructor, `node:crypto` is unavailable on Edge and Workers (and\n * a static import of it would fail those builds outright), and Web Crypto's\n * `subtle.digest` is async. So this is a non-cryptographic digest, chosen for\n * the one property that actually matters here: the raw key never becomes a Map\n * key that something could enumerate or log.\n *\n * It is not collision-resistant against an adversary, and it does not need to\n * be. A collision would make two clients share state, so the bound that\n * matters is accidental collision between the handful of distinct API keys\n * present in a single process, which at 64 bits is negligible. It is never\n * persisted, never sent anywhere, and never compared against anything outside\n * this module.\n */\nfunction digest(value: string): string {\n // FNV-1a, 64-bit. BigInt keeps the arithmetic exact; Number would lose\n // precision past 2^53 and collapse the space.\n const PRIME = 1099511628211n;\n const MASK = 0xffffffffffffffffn;\n let hash = 14695981039346656037n;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= BigInt(value.charCodeAt(i));\n hash = (hash * PRIME) & MASK;\n }\n return hash.toString(16).padStart(16, '0');\n}\n\nexport function get(key: string): RegistrableClient | undefined {\n return instances.get(key);\n}\n\n/**\n * Claim `key` for `client`, or hand back whoever already holds it.\n *\n * A separate `get` then `set` would let two callers constructing the first\n * client for one identity both miss the lookup, with the second overwriting\n * the first. JavaScript's single-threaded execution makes that impossible\n * between two synchronous statements, so this is a single operation for\n * clarity rather than for locking: there is no equivalent of Python's mutex\n * to hold, and none is needed.\n *\n * Returns `undefined` when `client` won the slot, or the incumbent when not.\n */\nexport function registerIfAbsent(\n key: string,\n client: RegistrableClient,\n): RegistrableClient | undefined {\n const existing = instances.get(key);\n if (existing !== undefined) return existing;\n instances.set(key, client);\n return undefined;\n}\n\n/**\n * Point `key` at `client` as well, unless the slot is taken.\n *\n * Used once `initialize()` resolves the real instance id. The client was keyed\n * on its credential because the id did not exist yet, so a later\n * `new SynapClient({ instanceId })` for that same instance would miss and\n * build a second client: two anticipation caches and two Listen streams for\n * one instance. The credential slot is KEPT rather than moved, so constructing\n * by API key keeps returning the same client too.\n *\n * An occupied target is never clobbered. Evicting a live client is worse than\n * the duplication it would fix.\n */\nexport function aliasIfAbsent(key: string, client: RegistrableClient): boolean {\n if (!key || instances.has(key)) return false;\n instances.set(key, client);\n return true;\n}\n\n/**\n * Drop `key`, but only if it still points at `client`.\n *\n * A shutting-down client must not evict whoever currently holds its old slot.\n */\nexport function unregisterIfOwner(key: string, client: RegistrableClient): void {\n if (instances.get(key) === client) instances.delete(key);\n}\n\n/** Test seam. Never call this from library code. */\nexport function clear(): void {\n instances.clear();\n}\n\n/** Diagnostics only. */\nexport function size(): number {\n return instances.size;\n}\n","/**\n * Per-conversation short-term context, held locally.\n *\n * Mirrors Python's `cache/short_term_store.py`. This is what makes reads see\n * your own writes: a turn recorded a moment ago is buffered here and spliced\n * onto the next fetch, so a fast follow-up does not retrieve context that omits\n * what the user just said. Python's own comment on the overlay puts it plainly:\n * the pre-compaction window \"is exactly when the playground's fast follow-ups\n * happen.\"\n *\n * LRU by conversation, with an absolute age cap. Everything here is per process\n * and holds only what this process wrote, so nothing is authoritative: the\n * server's view wins for the summary fields, and this only ever contributes the\n * verbatim tail.\n *\n * Holding an entry is not the same as holding the conversation. A process that\n * restarted, evicted the entry, or shares the conversation with another process\n * has only the turns it recorded itself. So the server reports how many\n * messages it holds, on every write and on every compaction bundle, and\n * `isComplete()` says whether the entry can answer on its own. When it cannot,\n * the caller asks the server and hands the answer to `reseed`.\n */\n\nimport type { TurnStore } from './turn-store.js';\n\nconst DEFAULT_MAX_CONVERSATIONS = 100;\n/** 12 hours, as in Python. */\nconst DEFAULT_MAX_AGE_MS = 12 * 60 * 60 * 1000;\n\nexport interface ShortTermTurn {\n role: string;\n content: string;\n /** ISO-8601. */\n timestamp: string;\n /** The server's id for the turn, when the write returned one. */\n message_id?: string;\n}\n\n/**\n * How every v3 context_block begins (server: compaction/v3/render.py). A\n * summary that begins this way IS the block, which is how a REST-fed entry is\n * recognised. Same constant as Python's `CONTEXT_BLOCK_PREFIX`.\n */\nexport const CONTEXT_BLOCK_PREFIX = '## Conversation so far (compacted';\n\n/** The v3 block in a conversation_context payload, or null (v2 server). */\nexport function contextBlockOf(cc: Record<string, unknown>): string | null {\n const block = cc['context_block'];\n if (typeof block === 'string' && block) return block;\n const summary = cc['summary'];\n if (typeof summary === 'string' && summary.startsWith(CONTEXT_BLOCK_PREFIX)) return summary;\n return null;\n}\n\nexport interface ShortTermEntry {\n conversationId: string;\n summary: string | null;\n /**\n * Compaction v3: the server's one framed block, printed as received and\n * once. When set, the paragraphs are not used (the server sends them empty).\n */\n contextBlock: string | null;\n factualParagraph: string | null;\n conversationalParagraph: string | null;\n currentState: Record<string, unknown>;\n keyExtractions: Record<string, unknown>;\n compactionId: string | null;\n compactedAt: string | null;\n endTimestamp: string | null;\n recentTurns: ShortTermTurn[];\n lastActivityAt: number;\n // --- Completeness bookkeeping. See `isComplete`. ---\n /** Messages the cached summary covers, from the start of the conversation. */\n compactedMessageCount: number;\n /** The highest message count the server has reported. null = never heard. */\n serverMessageCount: number | null;\n /**\n * The server has confirmed at least one write made by this process. A\n * process that only reads never hears a count again after it is seeded, so\n * it could not notice the conversation moving on without it.\n */\n participant: boolean;\n /** At some point this entry held everything the server held. */\n synced: boolean;\n /**\n * The server's count ran ahead of an entry that was in sync, so something\n * else is writing to this conversation. Latched: this process cannot see\n * those writes when they happen, only at its own next write.\n */\n shared: boolean;\n}\n\n/** What a write learned from the server about the turn and the conversation. */\nexport interface TurnConfirmation {\n /** The server's id for the turn. A turn already held under it is not appended twice. */\n messageId?: string | undefined;\n /** The conversation's message count as the server reported it on this write. */\n serverMessageCount?: number | null | undefined;\n /** Other writes this process still has outstanding for the conversation. */\n inFlight?: number | undefined;\n}\n\n/** What `/context-for-prompt` returned, as far as `reseed` needs it. */\nexport interface ServerPromptState {\n compactionId: string | null;\n recentMessages: ShortTermTurn[];\n compactedMessageCount: number;\n totalMessageCount: number;\n}\n\nexport function localMessageCount(entry: ShortTermEntry): number {\n return entry.compactedMessageCount + entry.recentTurns.length;\n}\n\n/**\n * Whether an entry can stand in for the server's short-term context.\n *\n * True when the server holds nothing this entry lacks. Holding MORE than the\n * server has confirmed is fine: those are this process's own turns, sent and\n * not yet counted.\n */\nexport function isComplete(entry: ShortTermEntry): boolean {\n return (\n entry.participant &&\n entry.synced &&\n !entry.shared &&\n entry.serverMessageCount !== null &&\n entry.serverMessageCount <= localMessageCount(entry)\n );\n}\n\n/**\n * Whether `turns` already holds `turn`.\n *\n * By message id where both sides have one. Otherwise by role and text: a\n * streamed turn has no id (the server assigns it in a background write), and\n * the turns in a `fetch` response carry none either.\n */\nfunction heldIn(turn: ShortTermTurn, turns: ShortTermTurn[]): boolean {\n return turns.some((held) =>\n turn.message_id && held.message_id\n ? held.message_id === turn.message_id\n : held.role === turn.role && held.content === turn.content,\n );\n}\n\n/**\n * The local turns that come after everything in `serverTurns`.\n *\n * Walks back from the newest local turn and stops at the first one the\n * server's list already holds. What is left is what this process wrote or sent\n * after the server's list was built.\n *\n * A turn the server rewrote before storing it (a privacy policy) does not\n * match its local copy by text, so it can come back from here as well as from\n * the server. That shows one turn twice; it never loses one.\n */\nexport function turnsAfter(\n localTurns: readonly ShortTermTurn[],\n serverTurns: ShortTermTurn[],\n): ShortTermTurn[] {\n const newer: ShortTermTurn[] = [];\n for (let i = localTurns.length - 1; i >= 0; i -= 1) {\n const turn = localTurns[i] as ShortTermTurn;\n if (heldIn(turn, serverTurns)) break;\n newer.unshift(turn);\n }\n return newer;\n}\n\nexport interface ShortTermStoreOptions {\n maxConversations?: number;\n maxAgeMs?: number;\n /** Injected in tests. Wall clock, because entries are compared to ISO stamps. */\n now?: () => number;\n}\n\n/** Parse an ISO-8601 stamp to epoch millis, or null. */\nexport function parseIso(value: unknown): number | null {\n if (value === null || value === undefined || value === '') return null;\n if (value instanceof Date) return value.getTime();\n if (typeof value !== 'string') return null;\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? null : parsed;\n}\n\n/**\n * True when a turn is strictly after the cutoff.\n *\n * An unparseable timestamp KEEPS the turn. Dropping it would silently lose a\n * message, which is worse than briefly showing one the server has already\n * folded into its summary.\n */\nfunction isAfter(turnTimestamp: unknown, cutoffMs: number): boolean {\n const parsed = parseIso(turnTimestamp);\n if (parsed === null) return true;\n return parsed > cutoffMs;\n}\n\nexport class ShortTermStore {\n // Insertion order IS the LRU order: re-inserting on touch moves an entry to\n // the end, so the first key Map yields is the least recently used.\n readonly #entries = new Map<string, ShortTermEntry>();\n readonly #maxConversations: number;\n readonly #maxAgeMs: number;\n readonly #now: () => number;\n\n /**\n * Every turn appended here is also kept in the archive (a TurnStore), which\n * a compaction does not prune: the turns it covers stay searchable locally\n * (history-search.ts). Python: `ShortTermContextStore.attach_archive`.\n */\n #archive: TurnStore | null = null;\n\n constructor(options: ShortTermStoreOptions = {}) {\n this.#maxConversations = options.maxConversations ?? DEFAULT_MAX_CONVERSATIONS;\n this.#maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;\n this.#now = options.now ?? (() => Date.now());\n }\n\n attachArchive(archive: TurnStore | null): void {\n this.#archive = archive;\n }\n\n get archive(): TurnStore | null {\n return this.#archive;\n }\n\n /** The entry, or null. Age-evicts on read, as Python does. */\n get(conversationId: string): ShortTermEntry | null {\n if (!conversationId) return null;\n const entry = this.#entries.get(conversationId);\n if (entry === undefined) return null;\n if (this.#now() - entry.lastActivityAt > this.#maxAgeMs) {\n this.#entries.delete(conversationId);\n return null;\n }\n this.#touch(conversationId, entry);\n return entry;\n }\n\n has(conversationId: string): boolean {\n return this.get(conversationId) !== null;\n }\n\n get size(): number {\n return this.#entries.size;\n }\n\n /**\n * Append a raw turn.\n *\n * Called from `record_message` and the stream's `send_message`. When no entry\n * exists yet (the first turn, before any compaction has arrived) a fresh one\n * is created with an empty summary; the next `compaction_update` fills the\n * summary fields in and prunes the turns it covers.\n *\n * `confirmation` is what the write learned from the server. See\n * `TurnConfirmation` and `noteServerCount`.\n */\n appendTurn(\n conversationId: string,\n role: string,\n content: string,\n timestamp?: string,\n confirmation: TurnConfirmation = {},\n ): void {\n if (!conversationId) return;\n const stamp = timestamp ?? new Date(this.#now()).toISOString();\n if (this.#archive !== null) {\n try {\n this.#archive.add(conversationId, role, content, stamp, { messageId: confirmation.messageId ?? null });\n } catch {\n // The archive never blocks the prompt path.\n }\n }\n const entry = this.#entries.get(conversationId) ?? this.#blank(conversationId);\n const messageId = confirmation.messageId;\n const alreadyHeld =\n Boolean(messageId) && entry.recentTurns.some((t) => t.message_id === messageId);\n if (!alreadyHeld) {\n const turn: ShortTermTurn = { role, content, timestamp: stamp };\n if (messageId) turn.message_id = messageId;\n entry.recentTurns.push(turn);\n }\n const count = confirmation.serverMessageCount;\n if (count !== null && count !== undefined) {\n this.#noteCount(entry, Number(count), confirmation.inFlight ?? 0);\n }\n entry.lastActivityAt = parseIso(stamp) ?? this.#now();\n this.#touch(conversationId, entry);\n this.#evict();\n }\n\n /**\n * Record the server's message count for a conversation.\n *\n * The streamed write path's half of `appendTurn`'s confirmation: a streamed\n * turn is appended when it is sent, and the count arrives later, once the\n * server has written it. A count for a conversation this process holds\n * nothing for is ignored.\n */\n noteServerCount(conversationId: string, count: number): void {\n if (!conversationId) return;\n const entry = this.#entries.get(conversationId);\n if (entry !== undefined) this.#noteCount(entry, Number(count), 0);\n }\n\n /**\n * Compare the server's count with what the entry holds.\n *\n * The count is taken after one of this process's own writes, so it proves\n * the process takes part in the conversation.\n *\n * Server ahead of an entry that was in sync: something else wrote, and the\n * entry is marked shared for good. Server ahead of an entry that was never\n * in sync: this process joined late (a restart, an eviction), and `reseed`\n * will fix it. `inFlight` covers this process's own writes that the server\n * has counted and the entry has not appended yet, so two concurrent writes\n * do not look like a second writer.\n */\n #noteCount(entry: ShortTermEntry, count: number, inFlight: number): void {\n entry.participant = true;\n if (count > localMessageCount(entry) + inFlight) {\n if (entry.synced) entry.shared = true;\n } else if (entry.serverMessageCount === null) {\n // First word from the server, and nothing is missing.\n entry.synced = true;\n }\n entry.serverMessageCount = Math.max(entry.serverMessageCount ?? 0, count);\n }\n\n /**\n * Apply a `compaction_update` bundle.\n *\n * Replaces the summary fields from the bundle's `conversation_context` and\n * drops the buffered turns the new summary covers.\n *\n * Which turns those are is decided by count, not by clock. The bundle says\n * how many messages the summary covers and how many the conversation held\n * when the bundle was built, so the last `total - compacted` of its\n * `recent_turns` are exactly the uncovered messages. Turns this process\n * appended after the server took that count are kept behind them. Timestamps\n * cannot do this job: the REST write returns the time of the response and\n * not of the stored row, a caller may supply its own message time, and a\n * streamed turn is stamped when a background write runs.\n *\n * A bundle from a server that sends no counts falls back to the older\n * timestamp prune, and the entry is left out of sync so it is never used to\n * answer on its own.\n */\n applyCompaction(bundle: Record<string, unknown>): void {\n if (typeof bundle !== 'object' || bundle === null) return;\n const cc = (bundle['conversation_context'] ?? {}) as Record<string, unknown>;\n const conversationId = String(\n cc['conversation_id'] ??\n bundle['anticipation_conversation_id'] ??\n bundle['conversation_id'] ??\n '',\n );\n if (!conversationId) return;\n\n const endTs = parseIso(cc['end_timestamp'] ?? cc['compacted_at']);\n const compactedAt = parseIso(cc['compacted_at']);\n const compactedCount = Number(cc['compacted_message_count'] ?? 0) || 0;\n const totalCount = Number(cc['total_message_count'] ?? 0) || 0;\n const entry = this.#entries.get(conversationId) ?? this.#blank(conversationId);\n\n const heldAt = parseIso(entry.compactedAt);\n // An older compaction must not replace a newer one.\n if (compactedAt !== null && heldAt !== null && compactedAt < heldAt) return;\n\n // `x || existing` throughout, matching Python: a blank field from the\n // server must not erase what is already held.\n const block = contextBlockOf(cc);\n if (block) {\n // A v3 compaction replaces the whole record. Keeping a v2 paragraph\n // cached from an earlier push would print it next to the block, so the\n // paragraphs are cleared, not kept.\n entry.contextBlock = block;\n entry.summary = (cc['summary'] as string) || block;\n entry.factualParagraph = null;\n entry.conversationalParagraph = null;\n } else {\n entry.summary = (cc['summary'] as string) || entry.summary;\n entry.factualParagraph = (cc['factual_paragraph'] as string) || entry.factualParagraph;\n entry.conversationalParagraph =\n (cc['conversational_paragraph'] as string) || entry.conversationalParagraph;\n }\n entry.currentState = { ...((cc['current_state'] as Record<string, unknown>) ?? {}) };\n entry.keyExtractions = { ...((cc['key_extractions'] as Record<string, unknown>) ?? {}) };\n entry.compactionId = (cc['compaction_id'] as string) || entry.compactionId;\n entry.compactedAt = (cc['compacted_at'] as string) || entry.compactedAt;\n entry.endTimestamp = (cc['end_timestamp'] as string) || entry.endTimestamp;\n\n if (compactedCount > 0 && compactedCount <= totalCount) {\n const uncovered = totalCount - compactedCount;\n const serverTurns = Array.isArray(cc['recent_turns'])\n ? (cc['recent_turns'] as ShortTermTurn[])\n : [];\n const tail: ShortTermTurn[] =\n uncovered > 0 ? serverTurns.slice(-uncovered).map((t) => ({ ...t })) : [];\n // Turns appended here after the server counted. Only an entry that was\n // in sync knows how many of its own turns those are.\n const ahead = localMessageCount(entry) - totalCount;\n const newer =\n entry.synced && ahead > 0\n ? entry.recentTurns.slice(-ahead).filter((t) => !heldIn(t, tail))\n : [];\n entry.recentTurns = [...tail, ...newer];\n entry.compactedMessageCount = compactedCount;\n entry.serverMessageCount = Math.max(entry.serverMessageCount ?? 0, totalCount);\n // A short tail means the bundle did not carry every uncovered message,\n // so the entry cannot claim to hold them.\n entry.synced = tail.length === uncovered;\n } else {\n if (endTs !== null && entry.recentTurns.length > 0) {\n entry.recentTurns = entry.recentTurns.filter((t) => isAfter(t.timestamp, endTs));\n }\n entry.synced = false;\n }\n entry.lastActivityAt = this.#now();\n this.#touch(conversationId, entry);\n this.#evict();\n }\n\n /**\n * Bring an entry back in step from a `/context-for-prompt` response.\n *\n * Called after the server was asked because the entry was not complete. The\n * response lists every message the server's summary does not cover, which is\n * what `recentTurns` is meant to hold.\n *\n * Only an entry that already exists is reseeded. Creating one here would let\n * a process that never writes to the conversation answer from a snapshot it\n * has no way to refresh.\n *\n * If the server's summary is not the one cached here, the entry cannot\n * render it, so it stays out of sync until the next bundle brings the\n * summary itself.\n *\n * Turns held locally and absent from the response are kept when they come\n * after everything the response has: they were written or sent after the\n * server read its messages.\n */\n reseed(conversationId: string, state: ServerPromptState): void {\n if (!conversationId) return;\n const entry = this.#entries.get(conversationId);\n if (entry === undefined || entry.shared) return;\n entry.serverMessageCount = Math.max(\n entry.serverMessageCount ?? 0,\n Number(state.totalMessageCount) || 0,\n );\n if ((state.compactionId || null) !== entry.compactionId) {\n entry.synced = false;\n return;\n }\n const serverTurns = state.recentMessages.map((m) => ({ ...m }));\n entry.recentTurns = [...serverTurns, ...turnsAfter(entry.recentTurns, serverTurns)];\n entry.compactedMessageCount = Number(state.compactedMessageCount) || 0;\n entry.synced = true;\n }\n\n invalidate(conversationId: string): void {\n this.#entries.delete(conversationId);\n }\n\n clear(): void {\n this.#entries.clear();\n }\n\n #blank(conversationId: string): ShortTermEntry {\n return {\n conversationId,\n summary: null,\n contextBlock: null,\n factualParagraph: null,\n conversationalParagraph: null,\n currentState: {},\n keyExtractions: {},\n compactionId: null,\n compactedAt: null,\n endTimestamp: null,\n recentTurns: [],\n lastActivityAt: this.#now(),\n compactedMessageCount: 0,\n serverMessageCount: null,\n participant: false,\n synced: false,\n shared: false,\n };\n }\n\n /** Re-insert so this key becomes the most recently used. */\n #touch(conversationId: string, entry: ShortTermEntry): void {\n this.#entries.delete(conversationId);\n this.#entries.set(conversationId, entry);\n }\n\n #evict(): void {\n while (this.#entries.size > this.#maxConversations) {\n const oldest = this.#entries.keys().next();\n if (oldest.done === true) break;\n this.#entries.delete(oldest.value);\n }\n }\n}\n","/**\n * Local store of a conversation's raw turns, for search after compaction.\n *\n * Port of `maximem_synap/cache/turn_store.py`. The short-term store keeps\n * only the turns a compaction has not covered yet; this store keeps every\n * turn this process saw or fetched, so the details a compaction leaves out\n * can be found again by a local search (history-search.ts).\n *\n * Python keeps it in a SQLite file under ~/.synap. This one holds it in\n * memory, with the same limits and the same answers, because the SDK also\n * runs in browsers and edge runtimes, and the main entry may not load a node\n * builtin eagerly (bundle-hygiene.test.ts). A turn this process did not see\n * arrives through `addMany` from the turns route, with its position.\n */\n\nimport { HISTORY_SEARCH } from '../behavior/contract.js';\n\nexport interface StoreLimits {\n max_conversations: number;\n max_turns_per_conversation: number;\n max_bytes_per_conversation: number;\n idle_ttl_seconds: number;\n max_file_bytes: number;\n}\n\nexport interface StoredTurn {\n /** Insertion order in this store. */\n seq: number;\n role: string;\n content: string;\n timestamp: string;\n message_id: string | null;\n /** 1-based turn number on the server, when known. */\n position: number | null;\n}\n\nexport interface TurnInput {\n role?: string;\n content?: string;\n timestamp?: string | Date | null;\n message_id?: string | null;\n position?: number | string | null;\n}\n\nconst SWEEP_EVERY_WRITES = 50;\n\ninterface Conversation {\n lastActivity: number;\n turns: StoredTurn[];\n}\n\nfunction bytesOf(text: string): number {\n return new TextEncoder().encode(text).length;\n}\n\nexport class TurnStore {\n readonly limits: StoreLimits;\n readonly onDisk = false;\n #now: () => number;\n #seq = 0;\n #writes = 0;\n #conversations = new Map<string, Conversation>();\n #vectors = new Map<string, Map<number, Float32Array>>();\n\n constructor(options: { limits?: StoreLimits; now?: () => number } = {}) {\n this.limits = options.limits ?? { ...HISTORY_SEARCH.store_limits };\n this.#now = options.now ?? (() => Date.now() / 1000);\n }\n\n add(\n conversationId: string,\n role: string,\n content: string,\n timestamp?: string | null,\n options: { messageId?: string | null; position?: number | null } = {},\n ): void {\n this.addMany(conversationId, [\n { role, content, timestamp: timestamp ?? '', message_id: options.messageId ?? null, position: options.position ?? null },\n ]);\n }\n\n /**\n * Insert turns not held yet; returns how many were new. A turn held without\n * an id or position (a streamed write) gets them when the same role and\n * text come back from the server.\n */\n addMany(conversationId: string, turns: Iterable<TurnInput>): number {\n if (!conversationId) return 0;\n const conv = this.#conversations.get(conversationId) ?? { lastActivity: 0, turns: [] };\n let added = 0;\n for (const turn of turns) {\n const role = String(turn.role || 'user');\n const content = String(turn.content ?? '');\n if (!content) continue;\n const messageId = turn.message_id ? String(turn.message_id) : null;\n const raw = turn.position;\n const position =\n typeof raw === 'number' && Number.isInteger(raw) ? raw : /^\\d+$/.test(String(raw ?? '')) ? Number(raw) : null;\n const ts = turn.timestamp instanceof Date ? turn.timestamp.toISOString() : String(turn.timestamp ?? '');\n if (messageId !== null) {\n const held = conv.turns.find((t) => t.message_id === messageId);\n if (held !== undefined) {\n if (position !== null) held.position = position;\n continue;\n }\n }\n const same = conv.turns.find(\n (t) => t.role === role && t.content === content && (t.message_id === null || t.position === null),\n );\n if (same !== undefined) {\n same.message_id = same.message_id ?? messageId;\n same.position = position ?? same.position;\n continue;\n }\n conv.turns.push({ seq: ++this.#seq, role, content, timestamp: ts, message_id: messageId, position });\n added += 1;\n }\n conv.lastActivity = this.#now();\n this.#conversations.set(conversationId, conv);\n this.#trim(conv);\n this.#writes += 1;\n if (this.#writes % SWEEP_EVERY_WRITES === 0) this.sweep();\n return added;\n }\n\n #trim(conv: Conversation): void {\n const limits = this.limits;\n let size = conv.turns.reduce((n, t) => n + bytesOf(t.content), 0);\n while (conv.turns.length > limits.max_turns_per_conversation || size > limits.max_bytes_per_conversation) {\n const excess = Math.max(conv.turns.length - limits.max_turns_per_conversation, 1);\n const order = [...conv.turns].sort(\n (a, b) => (a.position ?? Number.MAX_SAFE_INTEGER) - (b.position ?? Number.MAX_SAFE_INTEGER) || a.seq - b.seq,\n );\n const gone = new Set(order.slice(0, excess).map((t) => t.seq));\n if (gone.size === 0) break;\n for (const t of conv.turns) if (gone.has(t.seq)) size -= bytesOf(t.content);\n conv.turns = conv.turns.filter((t) => !gone.has(t.seq));\n for (const vectors of this.#vectors.values()) for (const seq of gone) vectors.delete(seq);\n }\n }\n\n /** Idle conversations, then the least recently used beyond the count, then more until the bytes fit. */\n sweep(): void {\n const limits = this.limits;\n const now = this.#now();\n for (const [id, conv] of this.#conversations) {\n if (conv.lastActivity < now - limits.idle_ttl_seconds) this.drop(id);\n }\n const byRecent = [...this.#conversations.entries()].sort((a, b) => b[1].lastActivity - a[1].lastActivity);\n for (const [id] of byRecent.slice(limits.max_conversations)) this.drop(id);\n while (this.sizeBytes() > limits.max_file_bytes) {\n const oldest = this.conversations()[0];\n if (oldest === undefined) break;\n this.drop(oldest);\n }\n }\n\n drop(conversationId: string): void {\n const conv = this.#conversations.get(conversationId);\n if (conv === undefined) return;\n for (const vectors of this.#vectors.values()) for (const t of conv.turns) vectors.delete(t.seq);\n this.#conversations.delete(conversationId);\n }\n\n clear(): void {\n this.#conversations.clear();\n this.#vectors.clear();\n }\n\n close(): void {\n // Nothing to release in memory; kept for parity with the Python store.\n }\n\n /** In conversation order: by server position where known, else as written here. */\n turns(conversationId: string): StoredTurn[] {\n const conv = this.#conversations.get(conversationId);\n if (conv === undefined) return [];\n const bySeq = [...conv.turns].sort((a, b) => a.seq - b.seq);\n const key = new Map<number, number>();\n let top = 0;\n let step = 0;\n for (const t of bySeq) {\n if (t.position !== null) {\n key.set(t.seq, t.position);\n top = Math.max(top, t.position);\n step = 0;\n } else {\n step += 1;\n key.set(t.seq, top + step * 1e-6);\n }\n }\n return bySeq\n .sort((a, b) => (key.get(a.seq) ?? 0) - (key.get(b.seq) ?? 0) || a.seq - b.seq)\n .map((t) => ({ ...t }));\n }\n\n /** Turns the server also holds: archived tool results are local only. Python: `count`. */\n count(conversationId: string): number {\n return (this.#conversations.get(conversationId)?.turns ?? []).filter((t) => t.role !== 'tool').length;\n }\n\n sizeBytes(): number {\n let n = 0;\n for (const conv of this.#conversations.values()) for (const t of conv.turns) n += bytesOf(t.content);\n return n;\n }\n\n /** Conversation ids, least recently active first. */\n conversations(): string[] {\n return [...this.#conversations.entries()].sort((a, b) => a[1].lastActivity - b[1].lastActivity).map(([id]) => id);\n }\n\n vectors(seqs: readonly number[], model: string): Map<number, Float32Array> {\n const held = this.#vectors.get(model);\n const out = new Map<number, Float32Array>();\n if (held === undefined) return out;\n for (const seq of seqs) {\n const v = held.get(seq);\n if (v !== undefined) out.set(seq, v);\n }\n return out;\n }\n\n putVectors(model: string, items: Map<number, Float32Array>): void {\n const held = this.#vectors.get(model) ?? new Map<number, Float32Array>();\n for (const [seq, vec] of items) held.set(seq, vec);\n this.#vectors.set(model, held);\n }\n}\n","/**\n * Local search over a conversation's earlier turns.\n *\n * Port of `maximem_synap/cache/history_search.py`; see it for the design.\n * Cascade, cheapest first: literal values in the query, then BM25 (the\n * anticipation cache's tokenizer and parameters), then an embedding model\n * when one is supplied. Ranks are fused by reciprocal rank with a small recency prior, and\n * excerpts are shown in conversation order. The rendered block reaches the\n * LLM prompt and is byte-identical to Python's.\n */\n\nimport { HISTORY_SEARCH } from '../behavior/contract.js';\nimport { BM25, tokenize as latinTokenize } from './bm25.js';\nimport type { StoredTurn, TurnStore } from './turn-store.js';\n\n/** A local embedding model. `model` names it, so vectors from another model are never compared. */\nexport interface Encoder {\n model: string;\n encode(texts: string[]): number[][] | Promise<number[][]>;\n /** Optional: a model trained with a query prefix (e5) encodes queries here and turns with `encode`. */\n encodeQuery?(texts: string[]): number[][] | Promise<number[][]>;\n}\n\nexport interface Excerpt {\n position: number | null;\n role: string;\n text: string;\n score: number;\n timestamp: string;\n /** \"literal\", \"bm25\" or \"embedding\": the strongest signal that found it. */\n via: string;\n}\n\n// Any script's letters and digits; Latin words still go through the\n// anticipation tokenizer for its stop words and stemming. Python: `tokenize`.\nconst WORD_RE = /[\\p{L}\\p{N}\\p{M}]+/gu;\n\nconst FORMS: Readonly<Record<string, string>> = HISTORY_SEARCH.irregular_forms ?? {};\n\nfunction tokenize(text: string): string[] {\n const out: string[] = [];\n for (const word of (text || '').toLowerCase().match(WORD_RE) ?? []) {\n // \"sold\" and \"sell\" are one word to a search; the stemmer only strips regular endings.\n if (/^[\\x00-\\x7f]+$/.test(word)) out.push(...latinTokenize(FORMS[word] ?? word));\n else out.push(word);\n }\n return out;\n}\n\nconst LITERAL_SOURCE = String.raw`\"([^\"]{3,})\"|\\b([A-Z0-9][A-Z0-9-]{3,})\\b|(\\d[\\d,.:/-]*\\d|\\d)`;\nconst SENTENCE_RE = /(?<=[.!?])\\s+/;\n\nfunction literalsOf(query: string): string[] {\n const out: string[] = [];\n for (const m of (query || '').matchAll(new RegExp(LITERAL_SOURCE, 'g'))) {\n const quoted = m[1];\n const value = quoted || m[2] || m[3];\n if (value && (quoted || /\\d/.test(value))) out.push(value.toLowerCase());\n }\n return out;\n}\n\nfunction cosine(a: ArrayLike<number>, b: ArrayLike<number>): number {\n let dot = 0;\n let na = 0;\n let nb = 0;\n const n = Math.min(a.length, b.length);\n for (let i = 0; i < n; i++) {\n dot += a[i]! * b[i]!;\n na += a[i]! * a[i]!;\n nb += b[i]! * b[i]!;\n }\n return na && nb ? dot / (Math.sqrt(na) * Math.sqrt(nb)) : 0;\n}\n\nfunction words(text: string): string[] {\n return text.split(/\\s+/).filter(Boolean);\n}\n\nfunction excerptOf(content: string, terms: Set<string>, literals: string[], maxWords: number): string {\n let sentences = content.trim().split(SENTENCE_RE).filter((s) => s.trim());\n if (sentences.length === 0) sentences = [content.trim()];\n const score = (sentence: string): number => {\n const low = sentence.toLowerCase();\n const held = new Set(tokenize(sentence));\n let n = 0;\n for (const t of terms) if (held.has(t)) n += 1;\n for (const lit of literals) if (low.includes(lit)) n += 2;\n return n;\n };\n let best = 0;\n for (let i = 1; i < sentences.length; i++) if (score(sentences[i]!) > score(sentences[best]!)) best = i;\n let lo = best;\n let hi = best;\n let count = words(sentences[best]!).length;\n for (;;) {\n let grew = false;\n for (const j of [hi + 1, lo - 1]) {\n if (j >= 0 && j < sentences.length && count + words(sentences[j]!).length <= maxWords) {\n count += words(sentences[j]!).length;\n lo = Math.min(lo, j);\n hi = Math.max(hi, j);\n grew = true;\n }\n }\n if (!grew) break;\n }\n let text = sentences.slice(lo, hi + 1).join(' ');\n if (words(text).length > maxWords) text = words(text).slice(0, maxWords).join(' ') + ' ...';\n return (lo > 0 ? '... ' : '') + text + (hi < sentences.length - 1 && !text.endsWith('...') ? ' ...' : '');\n}\n\n/**\n * The best-matching earlier turns for `query`. `exclude`: message ids or\n * exact texts already in the prompt (the recent turns).\n */\nconst FENCE = /^\\s*(?:```|~~~)/;\nconst TABLE_RULE = /^\\s*\\|?\\s*:?-{2,}/;\nconst SENTENCE = /(?<=[.!?])\\s+/;\n\n/**\n * A long turn as passages of up to about `maxWords` words: table rows carry the\n * table's header row, fenced blocks and other line-shaped text go a few lines\n * at a time, prose a few sentences at a time. Python: `split_passages`.\n */\nexport function splitPassages(content: string, maxWords: number): string[] {\n const text = (content ?? '').trim();\n if (words(text).length <= maxWords) return text ? [text] : [];\n const out: string[] = [];\n const lines = text.split('\\n');\n let i = 0;\n while (i < lines.length) {\n const line = lines[i]!;\n if (FENCE.test(line)) {\n let j = i + 1;\n while (j < lines.length && !FENCE.test(lines[j]!)) j += 1;\n out.push(...windowsOf(lines.slice(i + 1, j), maxWords));\n i = j + 1;\n continue;\n }\n if (line.trim().startsWith('|')) {\n let j = i;\n while (j < lines.length && lines[j]!.trim().startsWith('|')) j += 1;\n const rows = lines.slice(i, j).filter((r) => !TABLE_RULE.test(r)).map((r) => r.trim());\n const [header, body] = rows.length > 1 ? [rows[0]!, rows.slice(1)] : ['', rows];\n for (const row of body) {\n const both = `${header} ${row}`.trim();\n out.push(words(both).length <= Math.trunc((maxWords * 3) / 2) ? both : row);\n }\n i = j;\n continue;\n }\n let j = i;\n while (j < lines.length && lines[j]!.trim() && !FENCE.test(lines[j]!) && !lines[j]!.trim().startsWith('|')) j += 1;\n if (j === i) {\n i += 1;\n continue;\n }\n const block = lines.slice(i, j);\n if (block.length > 1 && block.every((b) => words(b).length <= 25)) {\n out.push(...windowsOf(block, maxWords));\n } else {\n const sentences = block.map((b) => b.trim()).join(' ').split(SENTENCE).filter((x) => x.trim());\n out.push(...windowsOf(sentences, maxWords));\n }\n i = j;\n }\n const kept = out.filter((x) => x.trim());\n return kept.length ? kept : [text];\n}\n\nfunction windowsOf(pieces: readonly string[], maxWords: number): string[] {\n const out: string[] = [];\n let cur: string[] = [];\n let used = 0;\n for (const raw of pieces) {\n const piece = raw.trim();\n if (!piece) continue;\n const n = words(piece).length;\n if (cur.length && used + n > maxWords) {\n out.push(cur.join(' '));\n cur = [];\n used = 0;\n }\n if (n > maxWords) {\n const w = words(piece);\n for (let k = 0; k < w.length; k += maxWords) out.push(w.slice(k, k + maxWords).join(' '));\n continue;\n }\n cur.push(piece);\n used += n;\n }\n if (cur.length) out.push(cur.join(' '));\n return out;\n}\n\n/** What search scores: a whole turn, or one passage of a long turn. */\ninterface Unit {\n seq: number;\n content: string;\n turn: number;\n first: boolean;\n last: boolean;\n /** The passage's index, -1 for a whole turn (its vector is the turn's). */\n part: number;\n}\n\n/** The value patterns of the kinds of value `query` asks for. Python: `_asked_kinds`. */\nfunction askedKinds(query: string): RegExp[] {\n const out: RegExp[] = [];\n for (const [name, spec] of Object.entries(HISTORY_SEARCH.asked_kinds ?? {})) {\n if (name.startsWith('$') || typeof spec !== 'object') continue;\n if (new RegExp(spec.query, 'i').test(query ?? '')) out.push(new RegExp(spec.value));\n }\n return out;\n}\n\n/** A question about how things started gets no recency prior. Python: `_asks_how_it_started`. */\nfunction asksHowItStarted(query: string): boolean {\n const spec = HISTORY_SEARCH.early_query;\n if (!spec?.pattern) return false;\n return new RegExp(spec.pattern, (spec.flags ?? '').includes('i') ? 'i' : '').test(query ?? '');\n}\n\nexport async function searchTurns(\n turns: readonly StoredTurn[],\n query: string,\n options: { exclude?: Iterable<string>; encoder?: Encoder | null; store?: TurnStore | null } = {},\n): Promise<Excerpt[]> {\n const params = HISTORY_SEARCH;\n const k = params.max_excerpts;\n const skip = new Set(options.exclude ?? []);\n const pool = turns.filter((t) => t.content && !skip.has(t.content) && !skip.has(t.message_id ?? ''));\n const terms = new Set(tokenize(query || ''));\n const literals = literalsOf(query);\n if (pool.length === 0 || (terms.size === 0 && literals.length === 0 && !options.encoder)) return [];\n\n const maxWords = params.max_words_per_excerpt;\n const units: Unit[] = [];\n pool.forEach((t, ti) => {\n if (!params.passages) {\n units.push({ seq: t.seq, content: t.content, turn: ti, first: true, last: true, part: -1 });\n return;\n }\n const parts = splitPassages(t.content, maxWords);\n parts.forEach((part, pi) => {\n // A one-passage turn keeps the turn's vector; passages of a longer one are stored per passage.\n units.push({\n seq: t.seq, content: part, turn: ti, first: pi === 0, last: pi === parts.length - 1,\n part: parts.length > 1 ? pi : -1,\n });\n });\n });\n\n const docs = units.map((u) => tokenize(u.content));\n const bm = new BM25(docs);\n const termList = [...terms];\n const rows = units.map((turn, i) => {\n const held = new Set(docs[i]);\n let matched = 0;\n for (const t of terms) if (held.has(t)) matched += 1;\n const low = turn.content.toLowerCase();\n let literal = 0;\n for (const lit of literals) if (low.includes(lit)) literal += 1;\n return { i, bm25: matched ? bm.score(termList, i) : 0, matched, literal };\n });\n const need = Math.min(params.min_matched_terms, Math.max(1, terms.size));\n // One query word is enough when few turns use it, not when many do.\n const rareCap = Math.max(1, Math.trunc((params.rare_term_max_share ?? 0) * units.length));\n const rare = new Set<string>();\n for (const t of terms) {\n let n = 0;\n for (const doc of docs) if (doc.includes(t)) n += 1;\n if (n > 0 && n <= rareCap) rare.add(t);\n }\n let eligible;\n if (params.passages) {\n // A passage of a turn that matches enough query words as a whole.\n const turnTerms = new Map<number, Set<string>>();\n for (const r of rows) {\n const held = turnTerms.get(units[r.i]!.turn) ?? new Set<string>();\n for (const t of docs[r.i]!) if (terms.has(t)) held.add(t);\n turnTerms.set(units[r.i]!.turn, held);\n }\n eligible = rows.filter(\n (r) =>\n r.literal > 0 ||\n (r.matched > 0 &&\n (turnTerms.get(units[r.i]!.turn)!.size >= need || docs[r.i]!.some((t) => rare.has(t)))),\n );\n } else {\n eligible = rows.filter(\n (r) => r.literal > 0 || r.matched >= need || (r.matched > 0 && docs[r.i]!.some((t) => rare.has(t))),\n );\n }\n\n const rrf = params.rrf_k;\n const fused = new Map<number, number>();\n const via = new Map<number, string>();\n for (const r of eligible) fused.set(r.i, 0);\n const add = (i: number, rank: number, how: string): void => {\n fused.set(i, (fused.get(i) ?? 0) + 1 / (rrf + rank + 1));\n if (!via.has(i)) via.set(i, how);\n };\n eligible\n .filter((r) => r.literal > 0)\n .sort((a, b) => b.literal - a.literal || a.i - b.i)\n .forEach((r, rank) => add(r.i, rank, 'literal'));\n eligible\n .filter((r) => r.bm25 > 0)\n .sort((a, b) => b.bm25 - a.bm25 || a.i - b.i)\n .forEach((r, rank) => add(r.i, rank, 'bm25'));\n\n // A question asking for a kind of value also ranks the passages holding one.\n const kinds = askedKinds(query);\n if (kinds.length) {\n rows\n .filter((r) => r.matched > 0 && kinds.some((k) => k.test(units[r.i]!.content)))\n .sort((a, b) => b.bm25 - a.bm25 || a.i - b.i)\n .forEach((r, rank) => add(r.i, rank, 'kind'));\n }\n\n // Fused on every query when a model is supplied (Python: measured 19 Oct).\n if (options.encoder) {\n const ranked = await embeddingRanks(units, query, options.encoder, options.store ?? null, params.min_cosine ?? 0.4);\n ranked.forEach(([i], rank) => add(i, rank, 'embedding'));\n }\n if (fused.size === 0) return [];\n\n const n = Math.max(pool.length - 1, 1);\n const weight = asksHowItStarted(query) ? 0 : params.recency_weight;\n // A turn ranks by its best unit; its best units are what is shown of it.\n const top = new Map<number, [number, number]>();\n const ranked = new Map<number, [number, number][]>();\n for (const [u, v] of fused) {\n const ti = units[u]!.turn;\n const score = v + (weight * (ti / n)) / (rrf + 1);\n ranked.set(ti, [...(ranked.get(ti) ?? []), [score, u]]);\n const held = top.get(ti);\n if (!held || score > held[0]) top.set(ti, [score, u]);\n }\n const best = [...top.keys()].sort((a, b) => top.get(b)![0] - top.get(a)![0] || a - b).slice(0, k);\n const perTurn = params.passages_per_turn ?? 1;\n const shown = (ti: number): string => {\n const unit = units[top.get(ti)![1]]!;\n if (!params.passages || (unit.first && unit.last)) return excerptOf(pool[ti]!.content, terms, literals, maxWords);\n const picked = [...ranked.get(ti)!]\n .sort((a, b) => b[0] - a[0] || b[1] - a[1])\n .slice(0, perTurn)\n .map(([, u]) => u)\n .sort((a, b) => a - b);\n const parts: string[] = [];\n for (const u of picked) parts.push((units[u]!.first || parts.length ? '' : '... ') + units[u]!.content);\n return parts.join(' ... ') + (units[picked[picked.length - 1]!]!.last ? '' : ' ...');\n };\n const found = new Map<number, Excerpt>();\n for (const ti of best) {\n found.set(ti, {\n position: pool[ti]!.position,\n role: pool[ti]!.role,\n timestamp: pool[ti]!.timestamp,\n score: top.get(ti)![0],\n via: via.get(top.get(ti)![1]) ?? '',\n text: shown(ti),\n });\n }\n // The turn before a hit is often what it answers or confirms; it comes along, cut to its end.\n const before = params.previous_turns ?? 0;\n const tail = params.previous_turn_words ?? 40;\n for (const i of best) {\n for (let j = i - before; j < i; j++) {\n if (j < 0 || found.has(j)) continue;\n const hit = pool[i]!.position;\n const prev = pool[j]!.position;\n if (hit && prev && hit - prev > before) continue; // the turn just before is in the prompt\n const w = words(pool[j]!.content);\n found.set(j, {\n position: prev,\n role: pool[j]!.role,\n timestamp: pool[j]!.timestamp,\n score: 0,\n via: 'previous',\n text: w.length <= tail ? w.join(' ') : '... ' + w.slice(-tail).join(' '),\n });\n }\n }\n return [...found.keys()].sort((a, b) => a - b).map((i) => found.get(i)!);\n}\n\nasync function embeddingRanks(\n pool: readonly { seq: number; content: string; part?: number }[],\n query: string,\n encoder: Encoder,\n store: TurnStore | null,\n minCosine: number,\n): Promise<[number, number][]> {\n // Stored under the turn's seq and the model's name (a passage's: name + \"#p<index>\"). Python: `_embedding_ranks`.\n const keyOf = (u: { part?: number }): string => ((u.part ?? -1) < 0 ? encoder.model : `${encoder.model}#p${u.part}`);\n const vectors = new Map<number, ArrayLike<number>>();\n if (store !== null) {\n const byKey = new Map<string, number[]>();\n pool.forEach((u, i) => byKey.set(keyOf(u), [...(byKey.get(keyOf(u)) ?? []), i]));\n for (const [key, idx] of byKey) {\n const held = store.vectors(idx.map((i) => pool[i]!.seq), key);\n for (const i of idx) {\n const v = held.get(pool[i]!.seq);\n if (v) vectors.set(i, v);\n }\n }\n }\n const missing = pool.map((_, i) => i).filter((i) => !vectors.has(i));\n if (missing.length > 0) {\n const fresh = await encoder.encode(missing.map((i) => pool[i]!.content));\n const put = new Map<string, Map<number, Float32Array>>();\n missing.forEach((i, j) => {\n const v = Float32Array.from(fresh[j] ?? []);\n vectors.set(i, v);\n const key = keyOf(pool[i]!);\n put.set(key, (put.get(key) ?? new Map()).set(pool[i]!.seq, v));\n });\n if (store) for (const [key, items] of put) store.putVectors(key, items);\n }\n const q = (await (encoder.encodeQuery ?? encoder.encode).call(encoder, [query]))[0] ?? [];\n return pool\n .map((_, i): [number, number] => [i, cosine(q, vectors.get(i) ?? [])])\n .filter(([, c]) => c >= minCosine)\n .sort((a, b) => b[1] - a[1]);\n}\n\n/**\n * How an archived tool result reads in the turn store and in excerpts: compact\n * JSON, cut to the contract's size. Python: `tool_result_text`.\n */\nexport function toolResultText(result: unknown, toolName?: string | null): string {\n let text = typeof result === 'string' ? result : JSON.stringify(result) ?? String(result);\n const limit = HISTORY_SEARCH.tool_result_max_chars ?? 16_000;\n if (text.length > limit) text = text.slice(0, limit) + ' ...[cut]';\n return `[tool result: ${toolName || 'tool'}] ${text}`;\n}\n\n/** The block appended after the compaction and the recent turns. */\nexport function renderExcerpts(excerpts: readonly Excerpt[], latest = ''): string {\n if (excerpts.length === 0) return '';\n const lines = [HISTORY_SEARCH.heading];\n for (const e of excerpts) {\n let where = e.position ? `turn ${e.position}, ${e.role}` : `${e.role}, earlier`;\n if (e.timestamp) {\n const ago = before(e.timestamp, latest);\n where += `, ${e.timestamp}` + (ago ? ` (${ago})` : '');\n }\n lines.push(`- ${where}: \"${e.text}\"`);\n }\n return lines.join('\\n');\n}\n\nconst ZONED = /(?:Z|[+-]\\d{2}:\\d{2})$/;\n\n/** Seconds since the epoch, for an ISO-8601 timestamp with a zone only. Python: `_instant`. */\nfunction instant(stamp: string): number | null {\n const text = (stamp ?? '').trim();\n if (!ZONED.test(text)) return null;\n const ms = Date.parse(text);\n return Number.isNaN(ms) ? null : ms / 1000;\n}\n\n/** \"3 days before the latest message\", or \"\" when either is unreadable. Python: `_before`. */\nfunction before(stamp: string, latest: string): string {\n const at = instant(stamp);\n const now = instant(latest);\n if (at === null || now === null || now < at) return '';\n const seconds = Math.trunc(now - at);\n for (const [unit, size] of [['day', 86_400], ['hour', 3_600], ['minute', 60]] as const) {\n if (seconds >= size) {\n const n = Math.trunc(seconds / size);\n return `${n} ${unit}${n !== 1 ? 's' : ''} before the latest message`;\n }\n }\n return 'less than a minute before the latest message';\n}\n","/**\n * Read-your-writes overlay for fetch responses.\n *\n * Ports Python's `_overlay_local_recent_turns` and `_budget_recent_turns`.\n *\n * The server's `recent_turns` reflects what it has persisted and compacted. A\n * turn recorded moments ago may not be in there yet, so a fast follow-up would\n * fetch context missing the thing the user just said. The overlay replaces\n * `recent_turns` with the locally buffered tail while leaving every summary\n * field to the server.\n *\n * On by default, matching Python. `SYNAP_ST_VERBATIM_OVERLAY` is the\n * kill-switch.\n */\n\nimport type { Json, RawContext } from './types.js';\nimport { isComplete, turnsAfter } from '../cache/short-term-store.js';\nimport type { ShortTermStore, ShortTermTurn } from '../cache/short-term-store.js';\nimport { getEnv } from '../util/env.js';\n\n/**\n * The server trims `recent_turns` to this window before returning it. The\n * overlay re-applies the same budget so a long pre-compaction local tail\n * cannot silently re-inflate the prompt past what the server would have\n * allowed.\n */\nconst MAX_TURNS = 20;\nconst TOKEN_BUDGET = 2000;\n\n/**\n * Whether to splice the local tail in.\n *\n * Default ON: this is the correctness switch (a just-written turn must surface\n * on the next fetch), separate from the cost-side `st_authoritative` flag that\n * tells the server to skip assembling short-term context at all.\n */\nexport function verbatimOverlayEnabled(configured?: boolean): boolean {\n // Resolution order matches Python's `_is_st_verbatim_overlay`: the env var\n // is an explicit override / kill-switch and wins over the config field.\n const raw = (getEnv('SYNAP_ST_VERBATIM_OVERLAY') ?? '').trim().toLowerCase();\n if (['0', 'false', 'no', 'off'].includes(raw)) return false;\n if (['1', 'true', 'yes', 'on'].includes(raw)) return true;\n return configured ?? true;\n}\n\n/** ~4 characters per token, matching the server-side heuristic. */\nfunction estimateTokens(turn: ShortTermTurn): number {\n return Math.max(1, Math.floor(String(turn.content ?? '').length / 4));\n}\n\n/**\n * Cap the tail to the server's window, then drop OLDEST turns until it fits\n * the token budget. Oldest-first because the newest turn is the one the caller\n * is most likely to be following up on.\n */\nexport function budgetRecentTurns(turns: readonly ShortTermTurn[]): ShortTermTurn[] {\n const windowed = turns.slice(-MAX_TURNS);\n let total = windowed.reduce((n, t) => n + estimateTokens(t), 0);\n while (windowed.length > 0 && total > TOKEN_BUDGET) {\n const dropped = windowed.shift() as ShortTermTurn;\n total -= estimateTokens(dropped);\n }\n return windowed;\n}\n\n/**\n * Splice the local tail into a fetch response, in place.\n *\n * Deliberately never throws: this runs inside the fetch path, and a bookkeeping\n * problem here must not fail a retrieval that otherwise succeeded.\n */\nexport function overlayLocalRecentTurns(\n response: RawContext,\n store: ShortTermStore,\n /** `null` too: callers spell \"no conversation\" as `convId || null`. */\n conversationId: string | null | undefined,\n /** `st_verbatim_overlay` from the client options. The env var still wins. */\n configured?: boolean,\n): void {\n if (conversationId === undefined || conversationId === null || conversationId === '') return;\n try {\n const entry = store.get(conversationId);\n // Cold store: nothing locally, so leave the server's response untouched.\n if (entry === null) return;\n\n const existing = (response.conversation_context ?? null) as Json | null;\n\n // The server returned a conversation_context AND the overlay is switched\n // off: leave it exactly as sent. When the server OMITTED one we still\n // splice from local, so the skip-server-ST optimisation keeps working\n // regardless of this switch.\n if (existing !== null && !verbatimOverlayEnabled(configured)) return;\n\n // Which turns the tail is built from. The local list replaces the\n // server's only when it is known to be the whole conversation and to\n // follow the same summary the server sent. Otherwise the server's turns\n // stand, and the local list adds only what comes after them. A process\n // that has just restarted holds one turn, and replacing the server's list\n // with it dropped every turn before the restart.\n const serverCompaction = existing === null ? null : existing['compaction_id'];\n const localIsWhole =\n isComplete(entry) && (!serverCompaction || serverCompaction === entry.compactionId);\n let sourceTurns: ShortTermTurn[] = entry.recentTurns;\n if (existing !== null && !localIsWhole) {\n const raw = Array.isArray(existing['recent_turns']) ? existing['recent_turns'] : [];\n const serverTurns: ShortTermTurn[] = (raw as Array<Record<string, unknown>>).map((t) => ({\n role: String(t['role'] ?? 'user'),\n content: String(t['content'] ?? ''),\n timestamp: String(t['timestamp'] ?? ''),\n }));\n sourceTurns = [...serverTurns, ...turnsAfter(entry.recentTurns, serverTurns)];\n }\n // Role, text and time only, as Python sends: the server's id for a turn is\n // bookkeeping for the store, not part of the response.\n const localTurns = budgetRecentTurns(sourceTurns).map((t) => ({\n role: t.role,\n content: t.content,\n timestamp: t.timestamp,\n }));\n\n // `x || fallback`, not `??`, matching Python: the server sends '' and {}\n // for absent fields rather than null, and those must not win over a local\n // value that actually has content.\n const serverField = (name: string): unknown =>\n existing === null ? undefined : existing[name];\n const orLocal = <T>(name: string, local: T): unknown => {\n const value = serverField(name);\n if (value === undefined || value === null || value === '') return local;\n if (typeof value === 'object' && Object.keys(value as object).length === 0) return local;\n return value;\n };\n\n // Server wins on every summary field; local only ever supplies the tail.\n response.conversation_context = {\n summary: orLocal('summary', entry.summary),\n current_state: orLocal('current_state', { ...entry.currentState }),\n key_extractions: orLocal('key_extractions', { ...entry.keyExtractions }),\n recent_turns: localTurns,\n compaction_id: orLocal('compaction_id', entry.compactionId),\n compacted_at: orLocal('compacted_at', entry.compactedAt),\n conversation_id: conversationId,\n } as NonNullable<RawContext['conversation_context']>;\n } catch {\n // Non-fatal by design. See the note above.\n }\n}\n","/**\n * Render `get_context_for_prompt` locally from the short-term store.\n *\n * A direct port of Python's `formatter/context_for_prompt.py`. It exists for\n * the same reason: when the SDK is authoritative for short-term context, a\n * warm conversation can answer this call without a cloud round trip at all,\n * which is a latency saving and a metered-call saving both.\n *\n * The three styles and their exact heading text are copied from Python\n * deliberately. A prompt assembled by one SDK and one assembled by the other\n * must be the same string, or an application that switches languages silently\n * changes what its model sees.\n */\n\nimport { CONTEXT_BLOCK_PREFIX } from '../cache/short-term-store.js';\nimport type { ShortTermEntry, ShortTermTurn } from '../cache/short-term-store.js';\nimport type { Json } from './types.js';\n\nexport const SUPPORTED_STYLES = ['structured', 'narrative', 'bullet_points'] as const;\nexport type PromptStyle = (typeof SUPPORTED_STYLES)[number];\nexport const DEFAULT_STYLE: PromptStyle = 'structured';\n\nexport interface LocalRecentMessage {\n role: string;\n content: string;\n /** ISO-8601. */\n timestamp: string;\n message_id: string;\n}\n\nexport interface LocalPromptResponse {\n formatted_context: string | null;\n available: boolean;\n is_stale: boolean;\n compression_ratio: number | null;\n validation_score: number | null;\n compaction_age_seconds: number | null;\n quality_warning: boolean;\n recent_messages: LocalRecentMessage[];\n recent_message_count: number;\n compacted_message_count: number;\n total_message_count: number;\n /**\n * The framed compaction block alone (also inside formatted_context), for a\n * framework that keeps its own message list: a system message ahead of\n * recent_messages, in place of the turns it covers.\n */\n context_block: string | null;\n compaction_id: string | null;\n [key: string]: unknown;\n}\n\nfunction stringify(value: unknown): string {\n if (value === null || value === undefined) return '';\n const t = typeof value;\n if (t === 'string' || t === 'number' || t === 'boolean') return String(value);\n try {\n return JSON.stringify(value) ?? '';\n } catch {\n return String(value);\n }\n}\n\n/** Key extractions arrive as a list, a bare string, or a single object. */\nfunction asListOfObjects(value: unknown): Record<string, unknown>[] {\n if (!value) return [];\n if (Array.isArray(value)) {\n const out: Record<string, unknown>[] = [];\n for (const v of value) {\n if (v && typeof v === 'object' && !Array.isArray(v)) out.push(v as Record<string, unknown>);\n else if (typeof v === 'string') out.push({ content: v });\n }\n return out;\n }\n if (typeof value === 'object') return [value as Record<string, unknown>];\n return [];\n}\n\nfunction itemText(item: Record<string, unknown>): string {\n return (item['content'] as string) || (item['text'] as string) || stringify(item);\n}\n\nfunction buildRecentMessages(turns: readonly ShortTermTurn[]): LocalRecentMessage[] {\n return (turns ?? []).map((t, idx) => ({\n role: t.role || 'user',\n content: t.content ?? '',\n timestamp: t.timestamp,\n message_id: t.message_id || `local-${idx}`,\n }));\n}\n\n/**\n * The SDK does not know how many messages a compaction covered: the server\n * does not put that count in the bundle. Python reports 0 here for the same\n * reason, and both must agree.\n */\nfunction compactedMessageCount(_entry: ShortTermEntry): number {\n return 0;\n}\n\n/** The v3 block, which is printed as received, once, under its own header. */\nfunction blockOf(entry: ShortTermEntry): string | null {\n if (entry.contextBlock) return entry.contextBlock.trim();\n if (entry.summary && entry.summary.startsWith(CONTEXT_BLOCK_PREFIX)) return entry.summary.trim();\n return null;\n}\n\nfunction formatStructured(entry: ShortTermEntry, recent: LocalRecentMessage[]): string {\n const parts: string[] = [];\n const block = blockOf(entry);\n if (block) {\n parts.push(block);\n if (recent.length > 0) {\n parts.push(`## Recent Turns (${recent.length})`);\n for (const m of recent) parts.push(`**${m.role}**: ${m.content}`);\n }\n return parts.filter(Boolean).join('\\n\\n').trim();\n }\n if (entry.summary) { parts.push('## Summary'); parts.push(entry.summary.trim()); }\n if (entry.factualParagraph) { parts.push('## Facts'); parts.push(entry.factualParagraph.trim()); }\n if (entry.conversationalParagraph) {\n parts.push('## Conversation'); parts.push(entry.conversationalParagraph.trim());\n }\n\n const cs = entry.currentState ?? {};\n if (Object.keys(cs).length > 0) {\n parts.push('## Current State');\n for (const [k, v] of Object.entries(cs)) parts.push(`- ${k}: ${stringify(v)}`);\n }\n\n const ke = entry.keyExtractions ?? {};\n if (Object.keys(ke).length > 0) {\n parts.push('## Key Extractions');\n for (const [cat, items] of Object.entries(ke)) {\n if (!items) continue;\n parts.push(`### ${cat}`);\n for (const it of asListOfObjects(items)) parts.push(`- ${itemText(it)}`);\n }\n }\n\n if (recent.length > 0) {\n parts.push(`## Recent Turns (${recent.length})`);\n for (const m of recent) parts.push(`**${m.role}**: ${m.content}`);\n }\n\n return parts.filter(Boolean).join('\\n\\n').trim();\n}\n\nfunction formatNarrative(entry: ShortTermEntry, recent: LocalRecentMessage[]): string {\n const parts: string[] = [];\n const block = blockOf(entry);\n if (block) parts.push(block);\n else if (entry.summary) parts.push(entry.summary.trim());\n if (!block && entry.conversationalParagraph) parts.push(entry.conversationalParagraph.trim());\n else if (!block && entry.factualParagraph) parts.push(entry.factualParagraph.trim());\n\n if (recent.length > 0) {\n const tail = recent.map((m) => `${m.role}: ${m.content}`).join('\\n');\n parts.push(`Recent exchanges:\\n${tail}`);\n }\n return parts.filter(Boolean).join('\\n\\n').trim();\n}\n\nfunction formatBullets(entry: ShortTermEntry, recent: LocalRecentMessage[]): string {\n const parts: string[] = [];\n const block = blockOf(entry);\n if (block) {\n // The block is structured text already; bulleting it would mangle it.\n return [block, ...recent.map((m) => `- ${m.role}: ${m.content}`)].join('\\n').trim();\n }\n if (entry.summary) parts.push(`- Summary: ${entry.summary.trim()}`);\n\n for (const [k, v] of Object.entries(entry.currentState ?? {})) {\n parts.push(`- ${k}: ${stringify(v)}`);\n }\n for (const [cat, items] of Object.entries(entry.keyExtractions ?? {})) {\n for (const it of asListOfObjects(items)) parts.push(`- (${cat}) ${itemText(it)}`);\n }\n for (const m of recent) parts.push(`- ${m.role}: ${m.content}`);\n\n return parts.join('\\n').trim();\n}\n\nfunction formatBlock(entry: ShortTermEntry, recent: LocalRecentMessage[], style: string): string {\n if (style === 'narrative') return formatNarrative(entry, recent);\n if (style === 'bullet_points') return formatBullets(entry, recent);\n return formatStructured(entry, recent);\n}\n\n/** Build a context-for-prompt response from a cached entry. */\nexport function renderForPrompt(\n entry: ShortTermEntry,\n style: string = DEFAULT_STYLE,\n now: () => number = Date.now,\n): LocalPromptResponse {\n const chosen: string = (SUPPORTED_STYLES as readonly string[]).includes(style)\n ? style\n : DEFAULT_STYLE;\n\n const recent = buildRecentMessages(entry.recentTurns);\n const formatted = formatBlock(entry, recent, chosen);\n const available = entry.compactionId !== null || entry.recentTurns.length > 0;\n\n let compactionAge: number | null = null;\n if (entry.compactedAt !== null) {\n const parsed = Date.parse(entry.compactedAt);\n if (!Number.isNaN(parsed)) compactionAge = Math.floor((now() - parsed) / 1000);\n }\n\n const compacted = compactedMessageCount(entry);\n return {\n formatted_context: available ? formatted : null,\n available,\n is_stale: false,\n compression_ratio: null,\n validation_score: null,\n compaction_age_seconds: compactionAge,\n quality_warning: false,\n recent_messages: recent,\n recent_message_count: recent.length,\n compacted_message_count: compacted,\n total_message_count: recent.length + compacted,\n context_block: blockOf(entry),\n compaction_id: entry.compactionId,\n };\n}\n\n/** Build a compaction response from a cached entry, or null if none landed. */\nexport function renderCompacted(\n entry: ShortTermEntry,\n format = 'structured',\n correlationId = '',\n): Json | null {\n if (entry.compactionId === null) return null;\n\n const formatted = formatBlock(\n entry,\n buildRecentMessages(entry.recentTurns),\n format === 'narrative' ? 'narrative' : 'structured',\n );\n\n return {\n compacted_context: formatted,\n compaction_id: entry.compactionId,\n compacted_at: entry.compactedAt,\n conversation_id: entry.conversationId,\n current_state: entry.currentState,\n correlation_id: correlationId,\n original_token_count: null,\n compacted_token_count: null,\n compression_ratio: null,\n level_applied: null,\n validation_score: null,\n validation_passed: null,\n quality_warning: false,\n };\n}\n","/**\n * Periodic user-summary injection.\n *\n * Ports Python's `_should_inject_user_summary` / `_merge_user_summary_into_response`.\n *\n * Every Nth turn, a cached `user_summary` bundle is folded into the fetch\n * response. It is what keeps a long conversation grounded in who the user is\n * without paying for a broader retrieval on every turn. Without it, JS returns\n * less context than Python from identical usage, and the gap widens the longer\n * the conversation runs.\n */\n\nimport type { Json, RawContext, RawContextItem } from './types.js';\n\n/** Python's `_user_summary_interval`. */\nexport const USER_SUMMARY_INTERVAL = 5;\n/** Python's `max_summary_items`. */\nconst MAX_SUMMARY_ITEMS = 3;\n\nconst COLLECTIONS = ['facts', 'preferences', 'episodes', 'emotions', 'temporal_events'] as const;\n\n/** Per-conversation turn counters, so the cadence is per conversation. */\nexport class TurnCounter {\n readonly #counts = new Map<string, number>();\n\n /** Increment and return the new count. Python buckets a missing id under `_global`. */\n increment(conversationId: string | undefined): number {\n const key = conversationId !== undefined && conversationId !== '' ? conversationId : '_global';\n const next = (this.#counts.get(key) ?? 0) + 1;\n this.#counts.set(key, next);\n return next;\n }\n\n /**\n * True on every Nth turn, and never on the first.\n *\n * Python: `count > 0 and count % interval == 0`. Turn 5 injects, turn 1 does\n * not, which matters because the first turn is usually the one that just\n * triggered a fresh retrieval anyway.\n */\n shouldInject(conversationId: string | undefined): boolean {\n const key = conversationId !== undefined && conversationId !== '' ? conversationId : '_global';\n const count = this.#counts.get(key) ?? 0;\n return count > 0 && count % USER_SUMMARY_INTERVAL === 0;\n }\n\n clear(): void {\n this.#counts.clear();\n }\n}\n\nfunction itemId(item: Json): string {\n return String(item['item_id'] ?? item['id'] ?? '');\n}\n\nfunction pick(item: Json, ...names: string[]): unknown {\n for (const name of names) {\n const value = item[name];\n if (value !== undefined && value !== null) return value;\n }\n return undefined;\n}\n\n/**\n * Normalise a summary-bundle item to the response item shape.\n *\n * The bundle carries the proto's field names, which differ from the REST\n * response's. Python spells the whole mapping out rather than passing items\n * through, because a consumer reading `.content` on an episode would otherwise\n * get undefined.\n */\nfunction normalise(item: Json): RawContextItem {\n const content = pick(item, 'content') ?? '';\n const confidence = pick(item, 'confidence') ?? 0;\n const extractedAt = pick(item, 'extracted_at', 'created_at') ?? null;\n return {\n id: itemId(item),\n content: String(content),\n confidence: Number(confidence),\n source: String(pick(item, 'source') ?? ''),\n category: String(pick(item, 'context_type', 'category') ?? ''),\n emotion_type: String(pick(item, 'context_type', 'emotion_type') ?? ''),\n strength: Number(pick(item, 'strength', 'confidence') ?? 0),\n summary: String(pick(item, 'summary', 'content') ?? ''),\n significance: Number(pick(item, 'significance', 'confidence') ?? 0),\n intensity: Number(pick(item, 'intensity', 'confidence') ?? 0),\n context: String(pick(item, 'context', 'content') ?? ''),\n participants: (pick(item, 'participants') ?? []) as unknown[],\n extracted_at: extractedAt as string | null,\n occurred_at: (pick(item, 'occurred_at', 'extracted_at', 'created_at') ?? null) as string | null,\n detected_at: (pick(item, 'detected_at', 'extracted_at', 'created_at') ?? null) as string | null,\n metadata: (pick(item, 'metadata') ?? {}) as Json,\n event_date: (pick(item, 'event_date') ?? null) as string | null,\n said_at: (pick(item, 'said_at') ?? null) as string | null,\n valid_until: (pick(item, 'valid_until') ?? null) as string | null,\n temporal_category: (pick(item, 'temporal_category') ?? null) as string | null,\n temporal_confidence: Number(pick(item, 'temporal_confidence') ?? 0),\n };\n}\n\n/**\n * Fold a cached summary bundle into a response, in place.\n *\n * Appends at most `MAX_SUMMARY_ITEMS` per collection, skipping anything whose\n * id the response already carries: the summary supplements a retrieval, it does\n * not replace or duplicate it.\n */\nexport function mergeUserSummary(response: RawContext, bundle: Json): RawContext {\n const itemsByType = (bundle['items_by_type'] ?? {}) as Record<string, unknown>;\n for (const collection of COLLECTIONS) {\n const items = itemsByType[collection];\n if (!Array.isArray(items)) continue;\n\n const existing = (response[collection] ?? []) as RawContextItem[];\n const existingIds = new Set(existing.map((i) => String(i.id ?? i.item_id ?? '')));\n const fresh = (items as Json[])\n .filter((i) => typeof i === 'object' && i !== null && !existingIds.has(itemId(i)))\n .slice(0, MAX_SUMMARY_ITEMS)\n .map(normalise);\n if (fresh.length === 0) continue;\n\n response[collection] = [...existing, ...fresh];\n }\n return response;\n}\n","/**\n * Serving a fetch from the anticipation cache.\n *\n * Ports Python's `_build_anticipation_response` and the cache-first branch each\n * scope fetch runs before going to the network.\n *\n * This is the point of the whole anticipation feature. The gRPC stream pushes\n * bundles ahead of time; without a lookup on the read path the cache is\n * write-only, every fetch is a billed round trip, and the stream does nothing\n * but consume bandwidth. That was the state of this SDK before: `store()` was\n * wired, `lookup()` was never called.\n */\n\nimport type { Json, RawContext } from './types.js';\nimport type { AnticipationCache, LookupResult } from './anticipation-cache.js';\n\nexport type Scope = 'conversation' | 'user' | 'customer' | 'client';\n\nexport interface AnticipationLookupParams {\n // `| undefined` explicitly, because exactOptionalPropertyTypes distinguishes\n // an absent key from one set to undefined, and callers build these by\n // spreading optionals.\n searchQuery?: readonly string[] | null | undefined;\n /** Each query's share of the places, applied on a hit as the server applies it. */\n maxResultsPerQuery?: number | null | undefined;\n /** The user. Absent for customer- and client-scope fetches. */\n entityId?: string | null | undefined;\n customerId?: string | null | undefined;\n clientId?: string | null | undefined;\n conversationId?: string | null | undefined;\n /**\n * The rung the request names, from its `scope_path`. Passed through every\n * scope unchanged: unlike the ids below it, a rung never widens, so there is\n * no scope for which dropping it would be the safe thing to do.\n */\n scopeRung?: string | null | undefined;\n}\n\n/**\n * Which identifiers a scope may widen its lookup across.\n *\n * A customer-scope request widens to client-shared bundles but explicitly NOT\n * to user-scoped ones: those would leak one visitor's data into another\n * visitor's customer fetch. Client scope narrows furthest for the same reason.\n * This mirrors the scoping notes on Python's four fetch methods.\n */\nexport function scopeLookupParams(\n scope: Scope,\n params: AnticipationLookupParams,\n): AnticipationLookupParams {\n const { searchQuery, entityId, customerId, clientId, conversationId, scopeRung, maxResultsPerQuery } = params;\n switch (scope) {\n case 'conversation':\n return { searchQuery, entityId, customerId, clientId, conversationId, scopeRung, maxResultsPerQuery };\n case 'user':\n // No conversationId: a user-scope fetch is not bound to one thread.\n return { searchQuery, entityId, customerId, clientId, scopeRung, maxResultsPerQuery };\n case 'customer':\n return { searchQuery, entityId: null, customerId, clientId, scopeRung, maxResultsPerQuery };\n case 'client':\n return { searchQuery, entityId: null, customerId: null, clientId, scopeRung, maxResultsPerQuery };\n }\n}\n\n/**\n * An item's metadata, carrying its `scope` whichever shape it arrived in.\n *\n * The HTTP response puts `scope` inside `metadata`; a prefetched (gRPC) item\n * carries it top-level and has no `metadata`. Readers look in `metadata`, so a\n * cache hit read every client-scope item as unlabelled. Returns a copy, and a\n * `scope` already in `metadata` wins. Python: `_wire_metadata` in\n * `models/context.py`.\n */\nfunction wireMetadata(item: Json): Json {\n const md = item['metadata'];\n const out: Json = md !== null && typeof md === 'object' && !Array.isArray(md) ? { ...(md as Json) } : {};\n if (!out['scope'] && item['scope']) out['scope'] = item['scope'];\n return out;\n}\n\n/** Turn a cache hit into the same raw shape the network path returns. */\nexport function buildAnticipationResponse(hit: LookupResult): RawContext {\n const response: RawContext = {};\n for (const [type, items] of Object.entries(hit.itemsByType)) {\n (response as Json)[type] = items.map((item) => ({ ...item, metadata: wireMetadata(item as Json) }));\n }\n // `source: \"anticipation\"` is how a caller (and the metering that reads it)\n // can tell a locally served fetch from a billed one.\n response.metadata = {\n source: 'anticipation',\n ttl_seconds: 0,\n cache_hit: true,\n retrieved_at: new Date().toISOString(),\n };\n return response;\n}\n\n/** Every item id in a hit, for the `context_used` event's `served_item_ids`. */\nexport function servedItemIds(hit: LookupResult): string[] {\n const ids: string[] = [];\n for (const items of Object.values(hit.itemsByType)) {\n for (const item of items) {\n const id = item.item_id ?? (item as Json)['id'];\n if (typeof id === 'string' && id !== '') ids.push(id);\n }\n }\n return ids;\n}\n\nexport interface AnticipationAttempt {\n /** The response to return, or null to fall through to the network. */\n response: RawContext | null;\n hit: LookupResult | null;\n}\n\n/**\n * Try to serve this fetch locally.\n *\n * Deliberately swallows its own errors: a fault in the cache must degrade to a\n * network fetch, never fail a retrieval that the server could have answered.\n */\nexport async function tryServeFromCache(\n cache: AnticipationCache,\n scope: Scope,\n params: AnticipationLookupParams,\n maxItems: number,\n): Promise<AnticipationAttempt> {\n try {\n const scoped = scopeLookupParams(scope, params);\n const hit = await cache.lookupAsync({\n searchQuery: scoped.searchQuery ?? null,\n entityId: scoped.entityId ?? null,\n customerId: scoped.customerId ?? null,\n clientId: scoped.clientId ?? null,\n conversationId: scoped.conversationId ?? null,\n scopeRung: scoped.scopeRung ?? null,\n maxItems,\n maxResultsPerQuery: scoped.maxResultsPerQuery ?? null,\n });\n if (hit === null) return { response: null, hit: null };\n return { response: buildAnticipationResponse(hit), hit };\n } catch {\n return { response: null, hit: null };\n }\n}\n\n/**\n * How many distinct, non-empty search queries a fetch carried, for the\n * `context_used` event's `query_count`. Matches the Python SDK and the count\n * the server itself uses when it answers a fetch: the same query sent twice is\n * one, and an empty string is none.\n */\nexport function distinctQueryCount(searchQuery: unknown): number {\n if (!Array.isArray(searchQuery)) return 0;\n return new Set(searchQuery.filter((q) => typeof q === 'string' && q.length > 0)).size;\n}\n","/**\n * `context_assembled`: what the SDK actually composed for this turn.\n *\n * Ports Python's `_emit_context_assembled_event`. Fires after every fetch\n * resolves, whether it was served from the cache, the local short-term store or\n * the network, and records what the caller actually received. That can differ\n * from what the server returned, because of SDK-side trimming, the overlay, or\n * a cache hit that skipped the server entirely.\n *\n * It drives the Requests-page audit. The server backfills a synthetic row if no\n * event arrives within its window, so a missing event is not silently lost, it\n * just produces a less accurate one.\n *\n * Privacy: ids, counts and assembly metadata only. Never prompt or item content.\n */\n\nimport type { Json, RawContext } from './types.js';\n\nconst COLLECTIONS = ['facts', 'preferences', 'episodes', 'emotions', 'temporal_events'] as const;\n\nexport interface AssembledEvent extends Json {\n correlation_id: string;\n conversation_id: string;\n user_id: string;\n customer_id: string;\n final_item_ids: string[];\n final_total_tokens: number;\n compaction_id: string;\n recent_turn_count: number;\n compaction_end_timestamp: string;\n assembly_source: string;\n assembly_duration_ms: number;\n cache_hit: boolean;\n sdk_version: string;\n}\n\n/** Every item id the caller ended up with, across all five collections. */\nexport function finalItemIds(response: RawContext): string[] {\n const ids: string[] = [];\n for (const collection of COLLECTIONS) {\n const items = response[collection];\n if (!Array.isArray(items)) continue;\n for (const item of items) {\n const id = (item as Json)['id'] ?? (item as Json)['item_id'];\n if (typeof id === 'string' && id !== '') ids.push(id);\n }\n }\n return ids;\n}\n\n/**\n * Normalise the assembly source and derive `cache_hit` from it.\n *\n * `ResponseMetadata` uses `cache` as shorthand for the local HTTP cache; the\n * proto wants the explicit name. Three sources imply a hit regardless of what\n * the metadata's own flag says, because in each the server was not consulted.\n */\nexport function resolveSource(\n response: RawContext,\n override?: string,\n): { source: string; cacheHit: boolean } {\n const metadata = (response.metadata ?? {}) as Json;\n let source = override ?? String(metadata['source'] ?? '') ?? '';\n if (source === '') source = 'cloud';\n if (source === 'cache') source = 'http_cache';\n const impliesHit = ['anticipation', 'anticipation_cache', 'http_cache', 'sdk_authoritative'];\n const cacheHit = impliesHit.includes(source) ? true : Boolean(metadata['cache_hit']);\n return { source, cacheHit };\n}\n\nexport function buildAssembledEvent(params: {\n correlationId: string;\n response: RawContext;\n conversationId?: string | undefined;\n userId?: string | undefined;\n customerId?: string | undefined;\n startedAt: number;\n sdkVersion: string;\n sourceOverride?: string | undefined;\n}): AssembledEvent {\n const { response } = params;\n const { source, cacheHit } = resolveSource(response, params.sourceOverride);\n const conversationContext = (response.conversation_context ?? {}) as Json;\n const recentTurns = conversationContext['recent_turns'];\n const metadata = (response.metadata ?? {}) as Json;\n\n return {\n correlation_id: params.correlationId,\n conversation_id: params.conversationId ?? '',\n user_id: params.userId ?? '',\n customer_id: params.customerId ?? '',\n final_item_ids: finalItemIds(response),\n final_total_tokens: Number(metadata['total_tokens'] ?? 0),\n compaction_id: String(conversationContext['compaction_id'] ?? ''),\n recent_turn_count: Array.isArray(recentTurns) ? recentTurns.length : 0,\n compaction_end_timestamp: String(\n conversationContext['end_timestamp'] ?? conversationContext['compacted_at'] ?? '',\n ),\n assembly_source: source,\n assembly_duration_ms: Math.max(0, Date.now() - params.startedAt),\n cache_hit: cacheHit,\n sdk_version: params.sdkVersion,\n };\n}\n","/**\n * Cross-scope merge + prompt formatting for `client.fetch()`.\n *\n * Ports Python's `UnifiedContextResponse.merge` and `format_for_prompt` from\n * `models/context.py`. The formatted string is the part customers actually\n * paste into a system prompt, so it is reproduced character for character:\n * section order, the `- ` bullet, the `[scope: x]` / `strength: 0.8` bracket\n * suffixes, the `## User Context` wrapper, and the blank-line joins. A\n * cosmetic drift here shows up as a diff in every prompt a customer builds.\n */\n\nimport { rankedLabel, sortByRankScore } from './ranked.js';\nimport type { Json, RawContext, RawContextItem } from './types.js';\n\n/** The five item collections, in Python's iteration order. */\nexport const ITEM_COLLECTIONS = [\n 'facts',\n 'preferences',\n 'episodes',\n 'emotions',\n 'temporal_events',\n] as const;\n\nexport type ItemCollection = (typeof ITEM_COLLECTIONS)[number];\n\nexport interface UnifiedContext {\n facts: RawContextItem[];\n preferences: RawContextItem[];\n episodes: RawContextItem[];\n emotions: RawContextItem[];\n temporal_events: RawContextItem[];\n /**\n * `response_shape: \"ranked\"` only: every item once, best first across\n * scopes and types, renumbered from 1. Empty for a by-type fetch.\n */\n items: RawContextItem[];\n /** `response_shape: \"ranked\"` only: the chunks (quotes from source documents). */\n excerpts: RawContextItem[];\n /** item id -> the scope that supplied it. */\n scope_map: Record<string, string>;\n conversation_context: Json | null;\n profile: Json | null;\n conversations: Json[] | null;\n formatted_context: string;\n scopes_queried: string[];\n total_items: number;\n metadata: Json | null;\n}\n\nfunction itemId(item: RawContextItem): string | undefined {\n const id = item.id ?? item.item_id;\n return typeof id === 'string' && id !== '' ? id : undefined;\n}\n\n/**\n * Merge per-scope responses, deduplicating by item id.\n *\n * First scope wins on a duplicate, so the caller's scope order is significant.\n * An item with no usable id is kept rather than dropped: Python indexes\n * `scope_map` by `item.id`, and a missing id there would collide every such\n * item onto one key, so keeping-and-not-mapping is the closest faithful\n * behaviour.\n */\nexport function mergeScopeResults(\n scopeResults: ReadonlyArray<readonly [string, RawContext]>,\n): UnifiedContext {\n const seen = new Set<string>();\n const out: UnifiedContext = {\n facts: [], preferences: [], episodes: [], emotions: [], temporal_events: [],\n items: [], excerpts: [],\n scope_map: {},\n conversation_context: null,\n profile: null,\n conversations: null,\n formatted_context: '',\n scopes_queried: [],\n total_items: 0,\n metadata: null,\n };\n\n const rankedSeen = new Set<string>();\n const rankedItems: RawContextItem[] = [];\n\n for (const [scopeName, response] of scopeResults) {\n out.scopes_queried.push(scopeName);\n if (out.metadata === null && response.metadata !== undefined) {\n out.metadata = response.metadata as Json;\n }\n // The C4 summary sections ride up from whichever scope produced them,\n // which is always the user-scope sub-fetch. See the fan-out rule in fetch().\n if (out.profile === null && response['profile'] !== undefined && response['profile'] !== null) {\n out.profile = response['profile'] as Json;\n }\n if (\n out.conversations === null &&\n response['conversations'] !== undefined &&\n response['conversations'] !== null\n ) {\n out.conversations = response['conversations'] as Json[];\n }\n\n for (const collection of ITEM_COLLECTIONS) {\n const items = response[collection];\n if (!Array.isArray(items)) continue;\n for (const item of items as RawContextItem[]) {\n const id = itemId(item);\n if (id !== undefined) {\n if (seen.has(id)) continue;\n seen.add(id);\n out.scope_map[id] = scopeName;\n }\n out[collection].push(item);\n }\n }\n\n // Ranked responses only, and in Python's order: excerpts share the typed\n // lists' dedup and scope map; the ranked items have a dedup of their own,\n // because they are the same items again, in order.\n const excerpts = response['excerpts'];\n if (Array.isArray(excerpts)) {\n for (const item of excerpts as RawContextItem[]) {\n const id = itemId(item);\n if (id !== undefined) {\n if (seen.has(id)) continue;\n seen.add(id);\n out.scope_map[id] = scopeName;\n }\n out.excerpts.push(item);\n }\n }\n const ranked = response['items'];\n if (Array.isArray(ranked)) {\n for (const item of ranked as RawContextItem[]) {\n const id = itemId(item);\n if (id !== undefined) {\n if (rankedSeen.has(id)) continue;\n rankedSeen.add(id);\n }\n rankedItems.push(item);\n }\n }\n }\n\n // One order across scopes, by each item's rank_score. The sort is stable, so\n // equal scores keep scope order, as Python's does, and unscored items go last.\n out.items = sortByRankScore(rankedItems).map((item, n) => ({ ...item, rank: n + 1 }));\n out.total_items =\n ITEM_COLLECTIONS.reduce((n, c) => n + out[c].length, 0) + out.excerpts.length;\n return out;\n}\n\n/** Python's `f\"{x:.1f}\"`. */\nfunction oneDecimal(value: number): string {\n return value.toFixed(1);\n}\n\n/** Python's `datetime.strftime(\"%Y-%m-%d\")` on an ISO string. */\nfunction isoDate(value: unknown): string | null {\n if (typeof value !== 'string' || value === '') return null;\n const parsed = new Date(value);\n if (Number.isNaN(parsed.getTime())) return null;\n return parsed.toISOString().slice(0, 10);\n}\n\nfunction numberOf(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null;\n}\n\nfunction scopeOf(ctx: UnifiedContext, item: RawContextItem): string {\n const id = itemId(item);\n return (id !== undefined ? ctx.scope_map[id] : undefined) ?? 'unknown';\n}\n\n/** `- text [a, b]`, with the bracket omitted when there are no extras. */\nfunction bulletWithExtras(text: string, extras: string[]): string {\n return extras.length > 0 ? `- ${text} [${extras.join(', ')}]` : `- ${text}`;\n}\n\nexport interface FormatOptions {\n includeScope?: boolean;\n includeConversationContext?: boolean;\n}\n\n/**\n * Render the merged context for prompt injection.\n *\n * Mirrors `UnifiedContextResponse.format_for_prompt`. Note the two different\n * bracket styles: facts and episodes only ever carry `[scope: x]` appended\n * directly, while preferences, emotions and temporal events build a joined\n * extras list. That asymmetry is in Python and is preserved.\n */\nexport function formatForPrompt(ctx: UnifiedContext, options: FormatOptions = {}): string {\n const includeScope = options.includeScope ?? false;\n const includeConversationContext = options.includeConversationContext ?? true;\n const sections: string[] = [];\n\n // A ranked response is one numbered list in rank order, as in Python: the\n // typed sections below would split the order back up by type.\n const ranked = ctx.items ?? [];\n if (ranked.length > 0) {\n const lines = ranked.map((it, n) => {\n let label = rankedLabel(String(it['category'] ?? ''));\n if (includeScope) label += `, scope: ${scopeOf(ctx, it)}`;\n return `${n + 1}. [${label}] ${String(it.content ?? '')}`;\n });\n sections.push(`### Memories\\n${lines.join('\\n')}`);\n }\n const typed = ranked.length === 0;\n\n if (typed && ctx.facts.length > 0) {\n const lines = ctx.facts.map((f) => {\n let line = `- ${String(f.content ?? '')}`;\n if (includeScope) line += ` [scope: ${scopeOf(ctx, f)}]`;\n return line;\n });\n sections.push(`### Facts\\n${lines.join('\\n')}`);\n }\n\n if (typed && ctx.preferences.length > 0) {\n const lines = ctx.preferences.map((p) => {\n const extras: string[] = [];\n if (includeScope) extras.push(`scope: ${scopeOf(ctx, p)}`);\n const strength = numberOf(p['strength']);\n // Python: `if p.strength and p.strength >= 0.7` -- 0 is falsy there, so a\n // zero strength is omitted rather than printed.\n if (strength !== null && strength !== 0 && strength >= 0.7) {\n extras.push(`strength: ${oneDecimal(strength)}`);\n }\n return bulletWithExtras(String(p.content ?? ''), extras);\n });\n sections.push(`### Preferences\\n${lines.join('\\n')}`);\n }\n\n if (typed && ctx.episodes.length > 0) {\n const lines = ctx.episodes.map((e) => {\n // Episodes render `summary`, not `content`.\n let line = `- ${String(e['summary'] ?? '')}`;\n if (includeScope) line += ` [scope: ${scopeOf(ctx, e)}]`;\n return line;\n });\n sections.push(`### Episodes\\n${lines.join('\\n')}`);\n }\n\n if (typed && ctx.emotions.length > 0) {\n const lines = ctx.emotions.map((em) => {\n const extras: string[] = [];\n if (includeScope) extras.push(`scope: ${scopeOf(ctx, em)}`);\n const intensity = numberOf(em['intensity']);\n if (intensity !== null && intensity !== 0 && intensity >= 0.5) {\n extras.push(`intensity: ${oneDecimal(intensity)}`);\n }\n // Emotions render \"type: context\", not a bare content field.\n const text = `${String(em['emotion_type'] ?? '')}: ${String(em['context'] ?? '')}`;\n return bulletWithExtras(text, extras);\n });\n sections.push(`### Emotions\\n${lines.join('\\n')}`);\n }\n\n if (typed && ctx.temporal_events.length > 0) {\n const lines = ctx.temporal_events.map((te) => {\n const extras: string[] = [];\n if (includeScope) extras.push(`scope: ${scopeOf(ctx, te)}`);\n const validUntil = isoDate(te['valid_until']);\n if (validUntil !== null) extras.push(`valid until: ${validUntil}`);\n return bulletWithExtras(String(te.content ?? ''), extras);\n });\n sections.push(`### Temporal Events\\n${lines.join('\\n')}`);\n }\n\n if (includeConversationContext && ctx.conversation_context !== null) {\n const formatted = ctx.conversation_context['formatted_context'];\n if (typeof formatted === 'string' && formatted !== '') {\n sections.push(`### Conversation History\\n${formatted}`);\n }\n }\n\n const blocks: string[] = [];\n if (sections.length > 0) blocks.push(`## User Context\\n${sections.join('\\n\\n')}`);\n\n const profileBlock = formatProfileBlock(ctx.profile);\n if (profileBlock !== null) blocks.push(profileBlock);\n\n const conversationsBlock = formatConversationsBlock(ctx.conversations);\n if (conversationsBlock !== null) blocks.push(conversationsBlock);\n\n return blocks.length > 0 ? blocks.join('\\n\\n') : '';\n}\n\n/** `## Caller Profile`, or null when there is nothing to show. */\nfunction formatProfileBlock(profile: Json | null): string | null {\n if (profile === null) return null;\n const attributes = profile['attributes'];\n const lines: string[] = [];\n if (typeof attributes === 'object' && attributes !== null) {\n for (const [name, attr] of Object.entries(attributes as Json)) {\n const value =\n typeof attr === 'object' && attr !== null\n ? (attr as Json)['value']\n : undefined;\n let valueStr: string;\n if (Array.isArray(value)) valueStr = value.map((v) => String(v)).join(', ');\n else if (value === null || value === undefined) valueStr = '';\n else valueStr = String(value);\n // Python does `f\"- {name}: {value}\".rstrip()`, so an empty value leaves\n // \"- name:\" with no trailing space.\n lines.push(`- ${name}: ${valueStr}`.replace(/\\s+$/, ''));\n }\n }\n const bodyParts: string[] = [];\n if (lines.length > 0) bodyParts.push(lines.join('\\n'));\n const overview = profile['overview'];\n if (typeof overview === 'string' && overview !== '') bodyParts.push(overview);\n if (bodyParts.length === 0) return null;\n return `## Caller Profile\\n${bodyParts.join('\\n\\n')}`;\n}\n\n/** `## Previous Conversations`, or null. */\nfunction formatConversationsBlock(conversations: Json[] | null): string | null {\n if (conversations === null || conversations.length === 0) return null;\n const callBlocks = conversations.map((conv) => {\n const when =\n isoDate(conv['started_at']) ?? isoDate(conv['last_message_at']) ?? isoDate(conv['ended_at']);\n let header = `### Call on ${when ?? 'unknown date'}`;\n const convType = conv['conversation_type'];\n if (typeof convType === 'string' && convType !== '') header += ` (${convType})`;\n const callLines = [header];\n const overview = overviewText(conv);\n if (overview !== null) callLines.push(`Overview: ${overview}`);\n const outcome = outcomeText(conv);\n if (outcome !== null) callLines.push(`Outcome: ${outcome}`);\n if (overview === null && outcome === null) {\n // No compaction yet, or it failed. Still tell the model the call\n // happened so it can acknowledge the prior contact.\n // Python's model defaults summary_status to \"pending\", so an absent\n // field renders as \"pending\", not as an empty string.\n callLines.push(`Status: ${String(conv['summary_status'] ?? 'pending')}`);\n }\n return callLines.join('\\n');\n });\n return `## Previous Conversations\\n${callBlocks.join('\\n\\n')}`;\n}\n\n/**\n * Mirrors `ConversationSummaryModel.overview_text()`.\n *\n * Reads the nested `summary` OBJECT (not a string) and takes the first of four\n * keys that holds non-blank text, in this exact order.\n */\nfunction overviewText(conv: Json): string | null {\n const summary = conv['summary'];\n if (typeof summary !== 'object' || summary === null || Array.isArray(summary)) return null;\n for (const key of ['narrative_summary', 'overview', 'narrative', 'summary'] as const) {\n const val = (summary as Json)[key];\n if (typeof val === 'string' && val.trim() !== '') return val.trim();\n }\n return null;\n}\n\n/**\n * Mirrors `ConversationSummaryModel.outcome_text()`.\n *\n * Joins up to three classification fields with \" / \", skipping blanks, and\n * returns null when nothing survives.\n */\nfunction outcomeText(conv: Json): string | null {\n const classification = conv['classification'];\n if (typeof classification !== 'object' || classification === null || Array.isArray(classification)) {\n return null;\n }\n const c = classification as Json;\n const parts = [c['primary_category'], c['subcategory'], c['objective']]\n .filter((p): p is string => typeof p === 'string' && p.trim() !== '');\n return parts.length > 0 ? parts.join(' / ') : null;\n}\n","/**\n * `client.as_tool(...)`: an LLM-ready tool definition for fetching context.\n *\n * Ports Python's `MaximemSynapSDK.as_tool` plus its three module helpers.\n *\n * The point of the helper is that the scope identifiers are CLOSED OVER rather\n * than exposed in the JSON schema. The LLM chooses the query and the limits; it\n * cannot choose whose memory to read. Handing the model a `user_id` parameter\n * is how the per-user privacy filter gets dropped by accident, so the schema\n * deliberately has no such field.\n */\n\nimport { InvalidInputError } from '../errors.js';\nimport type { Json } from '../context/types.js';\n\nexport type ToolScope = 'conversation' | 'user' | 'customer' | 'client' | 'unified';\nexport type ToolStyle = 'openai' | 'anthropic';\n\nconst VALID_SCOPES: readonly ToolScope[] = ['conversation', 'user', 'customer', 'client', 'unified'];\n\nexport interface AsToolOptions {\n scope?: string;\n user_id?: string;\n userId?: string;\n customer_id?: string;\n customerId?: string;\n conversation_id?: string;\n conversationId?: string;\n name?: string;\n description?: string;\n style?: string;\n /**\n * Closed-over rung for an account with a deeper ladder. Never part of the\n * schema the LLM sees, so the model cannot change it. Forwarded only when set.\n * With `scope: 'unified'` the customer fetch gets it cut above the identity\n * rung, as in `fetch`. With `scope: 'customer'` it goes as given, and the\n * server refuses (HTTP 400) a path that names the identity rung.\n */\n scope_path?: Record<string, string> | null;\n}\n\nexport type ToolHandler = (callArgs?: Json) => Promise<Json>;\n\nexport interface OpenAiToolDefinition {\n type: 'function';\n function: { name: string; description: string; parameters: Json };\n handler: ToolHandler;\n}\n\nexport interface AnthropicToolDefinition {\n name: string;\n description: string;\n input_schema: Json;\n handler: ToolHandler;\n}\n\nexport type ToolDefinition = OpenAiToolDefinition | AnthropicToolDefinition;\n\nconst BASE_DESCRIPTION =\n 'Retrieve stored context (facts, preferences, recent episodes, ' +\n 'emotions, temporal events) from Synap memory.';\n\n/** Python's `_default_tool_description`. Wording is load-bearing: it primes the model to call the tool. */\nexport function defaultToolDescription(scope: ToolScope): string {\n switch (scope) {\n case 'conversation':\n return (\n BASE_DESCRIPTION +\n ' Scoped to a specific conversation. Call this when you ' +\n 'need facts already established in the current conversation, ' +\n 'or to reload context after a topic shift.'\n );\n case 'user':\n return (\n BASE_DESCRIPTION +\n \" Scoped to the user's long-term memory. Call this when \" +\n 'you need to recall who the user is, their preferences, or ' +\n 'their history across conversations.'\n );\n case 'customer':\n return (\n BASE_DESCRIPTION +\n ' Scoped to the customer/organization. Call this when ' +\n 'you need facts about the customer org rather than an individual.'\n );\n case 'client':\n return (\n BASE_DESCRIPTION +\n ' Scoped to the integrating client/product. Call this for ' +\n 'product-level knowledge (e.g. policies, documentation).'\n );\n default:\n return (\n BASE_DESCRIPTION +\n ' Cross-scope: merges conversation, user, customer, and ' +\n 'client memory in one call. Call this at the start of a turn when ' +\n 'you need general grounding before responding.'\n );\n }\n}\n\n/**\n * Python's `_tool_input_schema`.\n *\n * `conversation_id` appears ONLY for `scope=\"conversation\"` when it was not\n * closed over, in which case it is also the one required field.\n */\nexport function toolInputSchema(scope: ToolScope, options: { hasConversationId: boolean }): Json {\n const props: Json = {\n search_query: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Optional list of search queries describing what context ' +\n 'you need. Free-form natural language is fine. Omit to ' +\n 'retrieve the most relevant recent context.',\n },\n max_results: {\n type: 'integer',\n minimum: 1,\n maximum: 50,\n description: 'Maximum items to return (default 10).',\n },\n types: {\n type: 'array',\n items: {\n type: 'string',\n enum: ['facts', 'preferences', 'episodes', 'emotions', 'temporal_events'],\n },\n description: 'Filter to specific memory categories. Omit to retrieve all.',\n },\n mode: {\n type: 'string',\n enum: ['fast', 'accurate'],\n description:\n \"Retrieval mode. 'fast' = low-latency (~50ms); 'accurate' = \" +\n \"LLM-decomposed multi-query (~200-500ms). Default 'fast'.\",\n },\n precision_level: {\n type: 'string',\n enum: ['high', 'medium'],\n description:\n \"Result filtering precision. 'high' (default) applies an extra \" +\n \"relevance-refinement pass; 'medium' skips it for faster, less \" +\n 'precisely filtered results (recall unaffected).',\n },\n };\n\n let required: string[] = [];\n if (scope === 'conversation' && !options.hasConversationId) {\n props['conversation_id'] = {\n type: 'string',\n description: 'The conversation id to fetch context for.',\n };\n required = ['conversation_id'];\n }\n\n return { type: 'object', properties: props, required, additionalProperties: false };\n}\n\n/** What `as_tool` needs from the client, so this module stays testable in isolation. */\nexport interface ToolDispatchTarget {\n fetch(options: Json): Promise<{\n formatted_context: string;\n scopes_queried: string[];\n total_items: number;\n }>;\n conversation: { context: { fetch(options: Json): Promise<Json> } };\n user: { context: { fetch(options: Json): Promise<Json> } };\n customer: { context: { fetch(options: Json): Promise<Json> } };\n client: { context: { fetch(options: Json): Promise<Json> } };\n}\n\nconst RESULT_COLLECTIONS = ['facts', 'preferences', 'episodes', 'emotions', 'temporal_events'] as const;\n\n/**\n * Python's `_invoke_scope_fetch`.\n *\n * Returns a plain object so the host runtime can JSON-serialise it straight\n * into the LLM's tool-result message.\n */\nexport async function invokeScopeFetch(params: {\n target: ToolDispatchTarget;\n scope: ToolScope;\n userId: string | undefined;\n customerId: string | undefined;\n conversationId: string | undefined;\n callArgs: Json;\n scopePath?: Record<string, string> | null | undefined;\n}): Promise<Json> {\n const { target, scope, userId, customerId, conversationId, callArgs, scopePath } = params;\n // Closed over, never read from callArgs: the model cannot change it. Added\n // only when set, so a tool without one hands the fetch what it always got.\n const pathOpt: Json =\n scopePath !== undefined && scopePath !== null && Object.keys(scopePath).length > 0\n ? { scope_path: scopePath }\n : {};\n\n const searchQuery = callArgs['search_query'];\n // Python: `int(call_args.get(\"max_results\") or 10)` -- so 0 falls back to 10.\n const rawMax = callArgs['max_results'];\n const maxResults = typeof rawMax === 'number' && rawMax !== 0 ? Math.trunc(rawMax) : 10;\n const types = callArgs['types'];\n const mode = String(callArgs['mode'] ?? '') || 'fast';\n const precisionLevel = String(callArgs['precision_level'] ?? '') || 'high';\n const callConvId =\n (typeof callArgs['conversation_id'] === 'string' && callArgs['conversation_id'] !== ''\n ? (callArgs['conversation_id'] as string)\n : undefined) ?? conversationId;\n\n const shared: Json = {\n search_query: searchQuery,\n max_results: maxResults,\n types,\n mode,\n precision_level: precisionLevel,\n ...pathOpt,\n };\n\n if (scope === 'unified') {\n const response = await target.fetch({\n conversation_id: callConvId,\n user_id: userId,\n customer_id: customerId,\n ...shared,\n });\n return {\n formatted_context: response.formatted_context,\n scopes_queried: response.scopes_queried,\n total_items: response.total_items,\n };\n }\n\n let response: Json;\n if (scope === 'conversation') {\n if (callConvId === undefined || callConvId === '') {\n // Python returns this as DATA, not an exception: the LLM sees the error\n // string in its tool result and can retry with an id.\n return { error: 'conversation_id is required', items: [] };\n }\n response = await target.conversation.context.fetch({\n conversation_id: callConvId,\n ...shared,\n user_id: userId,\n });\n } else if (scope === 'user') {\n response = await target.user.context.fetch({\n user_id: userId,\n conversation_id: callConvId,\n ...shared,\n customer_id: customerId,\n });\n } else if (scope === 'customer') {\n response = await target.customer.context.fetch({\n customer_id: customerId,\n conversation_id: callConvId,\n ...shared,\n });\n } else {\n response = await target.client.context.fetch({\n conversation_id: callConvId,\n ...shared,\n });\n }\n\n const out: Json = {};\n for (const collection of RESULT_COLLECTIONS) {\n out[collection] = Array.isArray(response[collection]) ? response[collection] : [];\n }\n return out;\n}\n\n/**\n * Build the tool definition.\n *\n * `onWarning` receives Python's `logger.warning` for the\n * `scope=\"conversation\"` without `user_id` case, which is a soft warning\n * rather than an error.\n */\nexport function buildTool(\n target: ToolDispatchTarget,\n options: AsToolOptions = {},\n onWarning: (message: string) => void = () => {},\n): ToolDefinition {\n const scope = String(options.scope ?? 'user').toLowerCase() as ToolScope;\n if (!VALID_SCOPES.includes(scope)) {\n // Python formats the valid set with sorted() and repr() on the input.\n const sorted = [...VALID_SCOPES].sort();\n throw new InvalidInputError(\n `scope must be one of ['${sorted.join(\"', '\")}'], got '${String(options.scope)}'`,\n );\n }\n\n const userId = options.user_id ?? options.userId;\n const customerId = options.customer_id ?? options.customerId;\n const conversationId = options.conversation_id ?? options.conversationId;\n\n if (scope === 'user' && (userId === undefined || userId === '')) {\n throw new InvalidInputError(\"scope='user' requires user_id\");\n }\n if (scope === 'customer' && (customerId === undefined || customerId === '')) {\n throw new InvalidInputError(\"scope='customer' requires customer_id\");\n }\n if (scope === 'conversation' && (userId === undefined || userId === '')) {\n // Not a hard error: the anticipation cache refuses cross-user matches\n // anyway. But the caller is leaving privacy on the floor, so say so.\n onWarning(\n \"as_tool(scope='conversation') without user_id: the SDK \" +\n 'anticipation cache cannot apply per-user filtering. Pass ' +\n 'user_id to enable the Section 15 privacy guarantee.',\n );\n }\n\n const style = String(options.style ?? 'openai');\n if (style !== 'openai' && style !== 'anthropic') {\n throw new InvalidInputError(`style must be 'openai' or 'anthropic', got '${style}'`);\n }\n\n const toolName = options.name ?? `synap_fetch_${scope}_context`;\n const toolDesc = options.description ?? defaultToolDescription(scope);\n const schema = toolInputSchema(scope, { hasConversationId: conversationId !== undefined });\n\n const handler: ToolHandler = (callArgs: Json = {}) =>\n invokeScopeFetch({\n target, scope, userId, customerId, conversationId, callArgs, scopePath: options.scope_path,\n });\n\n if (style === 'openai') {\n return {\n type: 'function',\n function: { name: toolName, description: toolDesc, parameters: schema },\n handler,\n };\n }\n return { name: toolName, description: toolDesc, input_schema: schema, handler };\n}\n","/**\n * SynapClient: the public entry point.\n *\n * Exposes two surfaces, both live in production:\n *\n * - **Namespaced, snake_case** (`client.user.context.fetch(...)`) is the\n * canonical surface and mirrors the Python SDK method for method. It\n * returns raw snake_case.\n * - **Top-level camelCase** (`client.fetchUserContext(...)`) is deprecated but\n * fully supported. It returns the normalised camelCase shape, and it exists\n * because the 0.3.x wrapper had it.\n *\n * They return different shapes on purpose. See gotcha G-B.\n */\n\nimport type { AgentModel } from './agent-model.js';\nimport { AuthenticationError, InvalidInputError } from './errors.js';\nimport { getEnv } from './util/env.js';\nimport { isLocalMode, localToken } from './local-mode.js';\nimport { HttpTransport, type Credentials, type HttpTransportOptions } from './transport/http.js';\nimport { fetchContext, responseShapeOf } from './context/fetch.js';\nimport { normalizeContextResponse } from './context/normalize.js';\nimport {\n AnticipationCache, type AnticipationCacheSnapshot,\n} from './context/anticipation-cache.js';\nimport { flattenContextItems, type FlatMemory } from './context/flatten.js';\nimport {\n createMemoriesInterface, type CreateMemoryOptions, type CreateMemoryResult,\n type MemoriesInterface,\n} from './memories/interface.js';\nimport {\n createConversationNamespace, CompactionSubscribers, type ConversationNamespace,\n} from './conversation/interface.js';\nimport { createDataInterface, type DataInterface } from './data/interface.js';\nimport { createUserNamespace, type UserNamespace } from './user/interface.js';\nimport { createCreditsNamespace, type CreditsNamespace } from './credits/interface.js';\nimport { createMacaNamespace, type MacaNamespace } from './maca/interface.js';\nimport { createCacheNamespace, type CacheNamespace } from './cache/interface.js';\nimport { createInstanceNamespace, type InstanceNamespace } from './instance/interface.js';\nimport type { FetchOptions, Json, NormalisedContext, RawContext } from './context/types.js';\nimport { SDK_VERSION } from './version.js';\nimport * as registry from './registry.js';\nimport { ShortTermStore, isComplete, type ShortTermTurn } from './cache/short-term-store.js';\nimport { TurnStore, type TurnInput } from './cache/turn-store.js';\nimport { renderExcerpts, searchTurns, toolResultText, type Encoder } from './cache/history-search.js';\nimport { SEMANTIC_MATCH } from './behavior/contract.js';\nimport { overlayLocalRecentTurns } from './context/overlay.js';\nimport { renderForPrompt, renderCompacted } from './context/local-prompt.js';\nimport { TurnCounter, mergeUserSummary } from './context/user-summary.js';\nimport {\n tryServeFromCache, servedItemIds, distinctQueryCount, type Scope as AnticipationScope,\n} from './context/anticipated.js';\nimport { rungKey } from './context/anticipation-cache.js';\nimport type { FetchHooks } from './context/fetch.js';\nimport { buildAssembledEvent } from './context/assembled.js';\nimport { newCorrelationId } from './util/correlation.js';\nimport { validateConversationId, validateInstanceId } from './util/validators.js';\nimport {\n mergeScopeResults, formatForPrompt, type UnifiedContext,\n} from './context/unified.js';\nimport { conversationStateContext, hasQuery, profileContext } from './context/no-query.js';\nimport { buildTool, type AsToolOptions, type ToolDefinition } from './tool/as-tool.js';\nimport { checkCustomerId } from './scoping.js';\nimport { type ScopeLadder, pathAboveIdentity } from './scope-ladder.js';\n\n/** Levels the SDK emits. Mirrors the subset of Python's logging it uses. */\nexport type SynapLogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Receives every diagnostic the SDK would otherwise write to the console.\n *\n * Python routes these through the stdlib `logging` module, which is why it\n * takes `log_level` and `logger`. There is no global logger in JavaScript, so\n * the SDK takes the sink directly instead of a level plus a framework.\n */\nexport type SynapLogger = (level: SynapLogLevel, message: string) => void;\n\nexport interface SynapClientOptions {\n /**\n * The four identity fields are `| undefined` rather than plain optional so a\n * consumer with `exactOptionalPropertyTypes` can pass `process.env.X`\n * directly, which is what every example does. Undefined already means \"fall\n * back to the environment\" at runtime; this makes the type say so.\n */\n apiKey?: string | undefined;\n clientId?: string | undefined;\n instanceId?: string | undefined;\n baseUrl?: string | undefined;\n /** Python spells this `api_base_url`; both are accepted so one config\n * object works against either SDK. */\n api_base_url?: string | undefined;\n timeouts?: HttpTransportOptions['timeouts'];\n retryPolicy?: HttpTransportOptions['retryPolicy'];\n keepAlive?: HttpTransportOptions['keepAlive'];\n /**\n * Keep the connection warm with a periodic /health ping.\n *\n * Off by default. A clear win for a long-lived process, pure waste in\n * serverless where the container is frozen between requests anyway.\n */\n heartbeat?: boolean;\n fetchImpl?: typeof fetch;\n /**\n * Splice locally-recorded turns into the next conversation-scope fetch, so a\n * just-written turn is visible before the server compacts. Defaults to true,\n * matching Python's `st_verbatim_overlay`. `SYNAP_ST_VERBATIM_OVERLAY`\n * overrides this either way.\n */\n st_verbatim_overlay?: boolean | undefined;\n stVerbatimOverlay?: boolean | undefined;\n /**\n * The model the agent runs on, and optionally its context window. Sent with\n * every recorded turn so the server sizes compaction to the agent's window\n * (it compacts at ~11.7% of it: 15K tokens on a 128K model). A name is\n * enough; the server knows common models' windows. Unset = 128K. Python's\n * `SDKConfig.agent_model` / `agent_context_window`; per-call `model` /\n * `context_window` override them.\n */\n agent_model?: string | undefined;\n agentModel?: string | undefined;\n agent_context_window?: number | undefined;\n agentContextWindow?: number | undefined;\n\n /**\n * Let the SDK answer `get_context_for_prompt` and `get_compacted` from its\n * own short-term store when the conversation is warm, skipping the cloud\n * round trip. Off by default. `SYNAP_SDK_ST_AUTHORITATIVE` overrides this in\n * either direction.\n *\n * Leave it off for an application that runs more than one process against\n * the same conversation. A process learns the server's message count only\n * when it writes. If it reads before it writes (build the prompt, then\n * record the turn), it cannot know that another process recorded a turn in\n * between, and it answers without that turn. Turn it on where one process\n * owns a conversation for its whole life, such as a voice agent.\n *\n * This is the COST switch. `st_verbatim_overlay` is the correctness one and\n * is independent of it.\n */\n sdk_st_authoritative?: boolean | undefined;\n sdkStAuthoritative?: boolean | undefined;\n\n /**\n * Your own embedding model for history search after compaction\n * (cache/history-search.ts), any `{ model, encode }`. It replaces the\n * SDK's model for history search; the anticipation cache uses it only if it\n * is the model its thresholds were tuned on (`history_search_model`).\n */\n history_search_encoder?: Encoder | undefined;\n historySearchEncoder?: Encoder | undefined;\n\n /**\n * The local embedding model, as Python's `history_search_model`: history\n * search after compaction, and matching fetch queries to prefetched items by\n * meaning. \"auto\" (default) runs the SDK's multilingual model in Node when\n * the optional `onnxruntime-node` and `@huggingface/tokenizers` packages are\n * installed: downloaded once (about 135 MB) into ~/.synap/models when the\n * first stream starts or the first history search runs, then loaded in the\n * background. An \"onnx:<repo>@<revision>/<file>\" names another (history\n * search only). null keeps keyword matching. Never loaded on Edge or in a\n * browser.\n */\n history_search_model?: string | null | undefined;\n historySearchModel?: string | null | undefined;\n\n /**\n * Where the SDK's diagnostics go. Defaults to `console.warn` prefixed with\n * `[synap]`. Pass a no-op to silence them, or your own logger to route them.\n */\n logger?: SynapLogger | undefined;\n\n /**\n * Bypass the process registry and build a genuinely separate client.\n *\n * Underscored because it mirrors Python's `_force_new` and is not part of the\n * everyday surface. Needed in tests, and for the rare case of deliberately\n * running two clients on one identity with separate caches.\n */\n _force_new?: boolean;\n /** Test seam: a monotonic clock in milliseconds for the scope-ladder cache. Not part of the everyday surface. */\n _clock?: () => number;\n}\n\ninterface ScopedContext {\n context: { fetch: (options?: FetchOptions) => Promise<RawContext> };\n}\n\n/**\n * Options for `configure()`.\n *\n * The Python-only keys are declared so a config object can be shared between\n * the two SDKs without a type error. They are accepted and ignored: there is\n * no SQLite cache backend and no global logger to replace here.\n */\nexport interface ConfigureOptions {\n timeouts?: HttpTransportOptions['timeouts'];\n retryPolicy?: HttpTransportOptions['retryPolicy'] | null;\n retry_policy?: HttpTransportOptions['retryPolicy'] | null;\n /** Accepted and ignored. Python-only. */\n storage_path?: string;\n /** Accepted and ignored. Python-only. */\n cache_backend?: string | null;\n /** Accepted and ignored. Python-only. */\n session_timeout_minutes?: number;\n /** Accepted and ignored. Python-only. */\n log_level?: string;\n /** The agent's model; see `SynapClientOptions.agent_model`. */\n agent_model?: string;\n agentModel?: string;\n agent_context_window?: number;\n agentContextWindow?: number;\n /**\n * The local model for history search and matching a fetch to prefetched\n * context by meaning: \"auto\" (default) or a model id, null for keyword\n * matching only. As Python's SDKConfig.history_search_model. Since 0.5.19.\n */\n history_search_model?: string | null;\n historySearchModel?: string | null;\n /** Replaces the diagnostic sink, same as the constructor option. */\n logger?: SynapLogger | undefined;\n}\n\n/** Options for the cross-scope `fetch()`. Snake_case, matching Python's kwargs.\n *\n * The three identifiers accept `null` as well as `undefined`, because that is\n * what callers actually pass: `conversation_id: convId || null` is the normal\n * way to say \"there is no conversation here\", and `validateConversationId`\n * has always treated `null` as absent. The declared type said otherwise, so\n * the `SynapClient`-to-`SynapSdkLike` assignability test in\n * `synap-claude-agent` (TS) could not typecheck, and the scope guards below\n * did not agree with the validator either. See the guards for that half.\n */\nexport interface UnifiedFetchOptions {\n conversation_id?: string | null;\n user_id?: string | null;\n customer_id?: string | null;\n search_query?: string[];\n max_results?: number;\n types?: string[];\n mode?: string;\n precision_level?: string;\n /** The moment the question is being asked. See FetchOptions.query_date. */\n query_date?: string;\n /** A share of the response per search query. See FetchOptions.max_results_per_query. */\n max_results_per_query?: number;\n include_conversation_context?: boolean;\n scopes?: string[];\n include_scope_labels?: boolean;\n context_mode?: string;\n include_profile?: boolean;\n last_n_conversations?: number;\n /**\n * `\"by_type\"` (default) or `\"ranked\"`. Ranked asks every scope for its\n * ranked list and merges them into `items`, best first across scopes and\n * types, by each item's `rank_score`; `formatted_context` is then one\n * numbered list in that order. The typed lists are filled either way.\n */\n response_shape?: string;\n /**\n * The rung to read at, one entry per level from the first, for an account\n * with a deeper ladder (see `get_scope_ladder` and `ScopeLadder.address`).\n * Only when set. Send ids as well. Not needed on a default ladder. The user\n * and conversation fetches get the path as given. The client fetch gets no\n * path. The client read is meant to return the account-wide shared memory,\n * and the user and customer reads already cover the person's and the team's\n * own levels. The server does apply a path on that route (it narrows the read\n * to that chain's own nodes), so sending one would narrow the shared read,\n * duplicate results the other reads return, and create registry nodes on a\n * read; it is also validated strictly (HTTP 400 if it is invalid or nested\n * scoping is off). SDK 0.7.0 sent it. The customer fetch\n * reads shared material only and the server refuses (HTTP 400) a path that\n * names the identity rung, so it gets the path with the identity level and\n * every level below it removed. The identity level is found by its role on\n * the account's ladder, which `fetch` reads first when a path is set and the\n * customer scope runs (one shared read, cached 300 s; no request when it is\n * cached, and none for a call without a path). If that read fails, a warning\n * is logged and only the reserved key `user` is removed. A path with no\n * identity level goes to the user, conversation and customer fetches as given.\n */\n scope_path?: Record<string, string> | null;\n}\n\n/** `SYNAP_SDK_LOCAL_MODEL=off` keeps the local embedding model from loading. Python: the same. */\nfunction localModelOff(): boolean {\n return ['off', '0', 'false', 'no', 'none'].includes((getEnv('SYNAP_SDK_LOCAL_MODEL') ?? '').trim().toLowerCase());\n}\n\nexport class SynapClient {\n // Native-private (`#`), not TypeScript `private`. TS `private` is erased at\n // compile time, so the field stays enumerable at runtime and a JS consumer\n // can still reach it. These two were public and made `client.transport\n // .credentials.apiKey` and the raw cache's `now`/`fire`/`invalidateEntity`\n // reachable, which is exactly what `client.cache` exists to prevent.\n // Definite-assignment assertions (`!`) because the constructor can RETURN an\n // existing client from the registry before reaching any of these. TypeScript\n // cannot follow a constructor return, so it sees a path where the fields are\n // unassigned. On that path the object is discarded and the incumbent is\n // handed back instead, so nothing observes them.\n readonly #transport!: HttpTransport;\n readonly #anticipationCache!: AnticipationCache;\n\n readonly user!: UserNamespace;\n readonly customer!: ScopedContext;\n readonly client!: ScopedContext;\n readonly conversation!: ConversationNamespace;\n readonly memories!: MemoriesInterface;\n readonly data!: DataInterface;\n readonly credits!: CreditsNamespace;\n readonly maca!: MacaNamespace;\n readonly cache!: CacheNamespace;\n readonly instance!: InstanceNamespace;\n\n #closed = false;\n #initialized = false;\n #identity: Promise<void> | undefined;\n #localMode = false;\n readonly #registryKeys!: string[];\n readonly #compactionSubscribers!: CompactionSubscribers;\n readonly #shortTerm!: ShortTermStore;\n /** Every raw turn, past compaction, for local history search. */\n readonly #turnStore!: TurnStore;\n /** A local embedding model for history search; null = keywords only. */\n #localEncoder: Encoder | null = null;\n /** `history_search_model`: \"auto\", an \"onnx:...\" name, or null for none. */\n #localModelName: string | null = 'auto';\n #localModelStarted = false;\n readonly #backfillAfter = new Map<string, number>();\n readonly #stVerbatimOverlay!: boolean | undefined;\n #agentModel: AgentModel = {};\n #logger!: SynapLogger | undefined;\n readonly #stAuthoritative!: boolean | undefined;\n readonly #turns!: TurnCounter;\n readonly #fetchHooks!: FetchHooks;\n\n constructor(options: SynapClientOptions = {}) {\n const resolvedBaseUrl = resolveBaseUrl(options);\n const localMode = isLocalMode(options.apiKey, resolvedBaseUrl);\n const credentials = resolveCredentials(options, localMode);\n // Fail locally on a malformed id rather than sending it upstream.\n validateInstanceId(credentials.instanceId);\n\n // ── Registry: one client per identity, per process ──────────────────────\n // Python has shared state here since 0.2. Without it, a framework\n // integration that builds a client per request or per agent gets a cold\n // anticipation cache every time and pays for a retrieval that Python would\n // have served locally.\n //\n // Returning from a constructor is unusual in JS but legal, and it is the\n // closest equivalent of Python's `self.__dict__ = existing.__dict__`. The\n // two callers then hold the SAME object rather than two objects sharing a\n // state bag, which is stricter than Python.\n const registryKey = registry.buildRegistryKey(credentials.instanceId, credentials.apiKey);\n if (options._force_new !== true) {\n const existing = registry.get(registryKey) as SynapClient | undefined;\n if (existing !== undefined) {\n // Handing back a client built on a DIFFERENT credential than the caller\n // just supplied. Only reachable on the explicit instanceId path, where\n // the id is the identity and the key is not part of it. The caller has\n // no other way to find out: the returned object looks exactly like the\n // one they asked for.\n const incumbent = existing.#transport.currentCredentials().apiKey;\n if (credentials.apiKey && incumbent && credentials.apiKey !== incumbent) {\n existing.#warn(\n `Instance ${registryKey} is already running in this process on a different ` +\n 'API key. The key passed here is ignored; this client will authenticate ' +\n 'as the existing one. Rotating a key this way has no effect. Construct ' +\n 'with apiKey and no instanceId to get a client on your own credential.',\n );\n }\n return existing;\n }\n }\n this.#registryKeys = options._force_new === true ? [] : [registryKey];\n this.#localMode = localMode;\n\n this.#transport = new HttpTransport({\n credentials,\n // SYNAP_BASE_URL is honoured, as Python does (sdk.py) and as the 0.3.x\n // wrapper did. Ignoring it was a wrong-DESTINATION bug rather than a\n // missing convenience: anyone pointing at a self-hosted or staging\n // deployment through the environment would silently have started sending\n // their data to production on upgrade.\n ...(resolvedBaseUrl !== undefined ? { baseUrl: resolvedBaseUrl } : {}),\n ...(options.timeouts !== undefined ? { timeouts: options.timeouts } : {}),\n ...(options.retryPolicy !== undefined ? { retryPolicy: options.retryPolicy } : {}),\n ...(options.keepAlive !== undefined ? { keepAlive: options.keepAlive } : {}),\n ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}),\n ...(options._clock !== undefined ? { clock: options._clock } : {}),\n userAgent: `@maximem/synap-js-sdk/${SDK_VERSION}`,\n });\n if (options.heartbeat) this.#transport.startHeartbeat();\n this.#transport.identityResolver = () => this.#resolveIdentity();\n // A 400 that answers a call which carried a scope path may mean the ladder\n // we hold is stale, so the next get_scope_ladder() re-reads. A 400 on a call\n // with no path says nothing about it, and the server's wording is not read.\n this.#transport.onInvalidInput = (_error, carriedScopePath) => {\n if (carriedScopePath) this.#transport.invalidateScopeLadder();\n };\n\n this.#anticipationCache = new AnticipationCache();\n\n this.#fetchHooks = {\n beforeFetch: async (scope, options) => {\n const o = options as Record<string, unknown>;\n // A prefetched bundle was assembled with no period restriction, so it\n // cannot answer a request that names one. Same class as the scope_path\n // defect described below: a bundle built for one question served to a\n // different one, entirely inside this process and invisible to every\n // server log. Skipping the cache costs one round trip; serving a bundle\n // that ignores the date costs the answer.\n if (o['query_date'] ?? o['queryDate']) return null;\n // Deliberately kept: only benchmarks and evaluation tools send a date.\n // A per-query share no longer skips: the hit applies it, by the\n // server's rule (anticipation-cache `reservePerQuery`).\n const attempt = await tryServeFromCache(\n this.#anticipationCache,\n scope as AnticipationScope,\n {\n searchQuery: (o['search_query'] ?? o['searchQuery']) as string[] | undefined,\n entityId: (o['user_id'] ?? o['userId']) as string | undefined,\n customerId: (o['customer_id'] ?? o['customerId']) as string | undefined,\n clientId: this.#transport.currentCredentials().clientId || null,\n conversationId: (o['conversation_id'] ?? o['conversationId']) as string | undefined,\n // The rung this read is addressed to, in the same words the server\n // stamped on the bundles it pushed. Without it the cache matched\n // on entity and conversation alone, so a bundle prefetched for one\n // rung answered a caller standing at another, entirely inside this\n // process and invisible to every server log.\n scopeRung: rungKey(\n (o['scope_path'] ?? o['scopePath']) as Record<string, string> | undefined,\n ),\n maxResultsPerQuery: (o['max_results_per_query'] ?? o['maxResultsPerQuery'] ?? null) as number | null,\n },\n Number(o['max_results'] ?? o['maxResults'] ?? 10),\n );\n if (attempt.response === null || attempt.hit === null) return null;\n return {\n response: attempt.response,\n servedItemIds: servedItemIds(attempt.hit),\n bundleId: attempt.hit.bundleIds[0] ?? '',\n borderline: attempt.hit.band === 'borderline',\n raceDeadlineMs: SEMANTIC_MATCH.race_deadline_ms,\n };\n },\n onAssembled: (scope, options, response, startedAt) => {\n this.#emitContextAssembled(scope, options as Record<string, unknown>, response, startedAt);\n },\n onServedFromCache: (_scope, options, served) => {\n // Fire-and-forget over the Listen stream. Drives the server's learning\n // loop: per-prefetch outcome scoring, per-pattern hit rates. Carries\n // ids and scope only, never prompt content.\n this.#emitContextUsed(options as Record<string, unknown>, _scope, served);\n },\n // The periodic user-summary splice, as Python runs it at the end of the\n // user, customer and client fetches (the conversation fetch does its own\n // through `onFetched`). Until 0.5.12 only the conversation fetch had it,\n // so the same usage gave the model different context in JS.\n // Python's `_should_skip_server_st`: when this process already holds the\n // conversation's compaction and every turn after it, the server is told\n // not to assemble them again.\n // A fetch with no query, as Python answers it inside the two scoped\n // fetches: the conversation's state, or the user's profile when there\n // is one. A profile read that fails falls back to the fetch as before.\n withoutQuery: async (scope, options) => {\n const o = options as Record<string, unknown>;\n if (scope === 'conversation') {\n const id = (o['conversation_id'] ?? o['conversationId']) as string;\n const prompt = await this.conversation.context.get_context_for_prompt({ conversation_id: id });\n return conversationStateContext(prompt as Json, id);\n }\n if (scope === 'user') {\n try {\n const customerId = (o['customer_id'] ?? o['customerId']) as string | undefined;\n const profile = await this.user.get_profile({\n user_id: (o['user_id'] ?? o['userId']) as string,\n ...(customerId !== undefined ? { customer_id: customerId } : {}),\n });\n return profileContext(profile);\n } catch {\n // The caller's input was checked before this point, so any error\n // here is the profile read's own: no profile, or a failure.\n return null;\n }\n }\n return null;\n },\n skipServerShortTerm: (conversationId) => {\n if (!this.#isStAuthoritative()) return false;\n const entry = this.#shortTerm.get(conversationId);\n return entry !== null && entry.compactionId !== null && isComplete(entry);\n },\n onResponse: (scope, options, response) => {\n if (scope === 'conversation') return;\n const o = options as Record<string, unknown>;\n const owner = scope === 'user'\n ? (o['user_id'] ?? o['userId'])\n : scope === 'customer' ? (o['customer_id'] ?? o['customerId']) : '_client';\n this.#injectUserSummary(\n response,\n (o['conversation_id'] ?? o['conversationId']) as string | undefined,\n owner as string | undefined,\n rungKey((o['scope_path'] ?? o['scopePath']) as Record<string, string> | undefined),\n );\n },\n };\n\n this.user = createUserNamespace(this.#transport, this.#fetchHooks);\n // `async` arrows, not bare ones. fetchContext is already async so nothing\n // can throw synchronously today, but these are the only two namespace\n // methods that were not async, and the next person to add a validation\n // line above the call would reintroduce a throw that bypasses .catch().\n this.customer = { context: { fetch: async (o = {}) => fetchContext(this.#transport, 'customer', o, this.#fetchHooks) } };\n this.client = { context: { fetch: async (o = {}) => fetchContext(this.#transport, 'client', o, this.#fetchHooks) } };\n this.#compactionSubscribers = new CompactionSubscribers();\n this.#shortTerm = new ShortTermStore();\n // Every raw turn, kept past compaction for local search (turn-store.ts).\n this.#turnStore = new TurnStore();\n this.#shortTerm.attachArchive(this.#turnStore);\n this.#stVerbatimOverlay = options.st_verbatim_overlay ?? options.stVerbatimOverlay;\n this.#agentModel = {\n model: options.agent_model ?? options.agentModel,\n contextWindow: options.agent_context_window ?? options.agentContextWindow,\n };\n this.#logger = options.logger;\n this.#stAuthoritative = options.sdk_st_authoritative ?? options.sdkStAuthoritative;\n this.#localEncoder = options.history_search_encoder ?? options.historySearchEncoder ?? null;\n const modelOption = options.history_search_model !== undefined\n ? options.history_search_model\n : options.historySearchModel;\n this.#localModelName = modelOption === undefined ? 'auto' : modelOption;\n if (this.#localEncoder?.model === SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(this.#localEncoder);\n this.#turns = new TurnCounter();\n this.conversation = createConversationNamespace(\n this.#transport,\n this.#compactionSubscribers,\n // Mirrors Python's `_invalidate_anticipation_on_write`, including its\n // gate: `invalidateEntity` is a no-op unless\n // SYNAP_SDK_CACHE_INVALIDATE_ON_WRITE is set, so default behaviour is\n // unchanged. Over-invalidating after a failed write is safe; it only\n // costs the next lookup a cold fetch.\n ({ userId, customerId }) => {\n for (const id of new Set([userId, customerId])) {\n if (id) this.#anticipationCache.invalidateEntity(id);\n }\n },\n // Buffer the turn locally so the next fetch sees it, ahead of the server\n // having persisted and compacted it.\n ({ conversationId, role, content, timestamp, messageId, serverMessageCount, inFlight }) => {\n this.#shortTerm.appendTurn(conversationId, role, content, timestamp, {\n messageId,\n serverMessageCount,\n inFlight,\n });\n },\n (response, conversationId, userId, scopePath) => {\n overlayLocalRecentTurns(response, this.#shortTerm, conversationId, this.#stVerbatimOverlay);\n this.#injectUserSummary(response, conversationId, userId, rungKey(scopePath));\n },\n {\n prompt: (conversationId, style) => this.#localPrompt(conversationId, style),\n compacted: (conversationId, format) => this.#localCompacted(conversationId, format),\n reseed: (conversationId, response) => this.#reseedShortTerm(conversationId, response),\n historyExcerpts: (conversationId, response, query) => this.#withHistoryExcerpts(conversationId, response, query),\n },\n () => this.#agentModel,\n // The same hooks as the other three scopes: the anticipation cache first,\n // as Python's conversation fetch does, and the audit events. Until 0.5.13\n // the conversation fetch was built without them, so every JS conversation\n // fetch was a billed round trip, including ones the stream had answered.\n this.#fetchHooks,\n );\n // After a forget that deleted something, drop that user's cached bundles so\n // they are not served until the TTL runs out. Unconditional, unlike the\n // invalidate-on-write hook: a forgotten memory must not be served.\n this.memories = createMemoriesInterface(this.#transport, ({ userId, customerId }) => {\n for (const id of new Set([userId, customerId])) {\n if (id) this.#anticipationCache.dropEntity(id);\n }\n });\n // After a delete, drop this machine's copies of what the server removed.\n this.data = createDataInterface(this.#transport, ({ scope, userId, customerId, conversationId }) => {\n const cleared: string[] = [];\n if (scope === 'conversation') {\n if (conversationId) {\n this.#shortTerm.invalidate(conversationId);\n this.#turnStore.drop(conversationId);\n cleared.push('short_term_context', 'turns');\n }\n } else {\n for (const id of new Set(scope === 'user' ? [userId, customerId] : [customerId])) {\n if (id) this.#anticipationCache.dropEntity(id);\n }\n // Only the anticipation cache is dropped here; the JS SDK keeps no other\n // per-entity context cache, so nothing else is claimed.\n cleared.push('anticipation_cache');\n }\n return cleared;\n });\n this.credits = createCreditsNamespace(this.#transport);\n this.maca = createMacaNamespace(this.#transport);\n this.cache = createCacheNamespace(this.#anticipationCache);\n this.instance = createInstanceNamespace(\n () => this.#transport.currentCredentials(),\n this.#anticipationCache,\n ({ conversationId, role, content }) => {\n this.#shortTerm.appendTurn(conversationId, role, content);\n },\n // A FilePart given by url is read with the same fetch as everything else.\n ((url: string, init?: RequestInit) =>\n this.#transport.fetchExternal(url, init)) as typeof fetch,\n () => this.#agentModel,\n ({ conversationId, result, toolName }: { conversationId: string; result: unknown; toolName: string }) =>\n this.archive_tool_result(conversationId, result, { tool_name: toolName }),\n (customerId, where) => this.#transport.checkCustomerId(customerId, where),\n );\n // A compaction folds turns into the server's summary, so the local copies\n // of those turns must go or they keep being spliced back in.\n // Prefetched bundles start arriving with the stream: load the local model\n // then, not at construction, so a process that never listens or searches\n // never downloads it.\n this.instance._internal.setOnListen(() => this.#startLocalModel());\n if (localMode) {\n this.instance._internal.blockListen(\n 'Not available in the open-source server: listen() needs the gRPC stream and ' +\n 'anticipation, which it does not have.',\n );\n }\n this.instance._internal.setCompactionApplier((bundle) => {\n this.#shortTerm.applyCompaction(bundle);\n });\n // The server's message count after each streamed write, which is how the\n // store learns whether it holds the whole conversation.\n this.instance._internal.setConversationStateHandler((conversationId, messageCount) => {\n this.#shortTerm.noteServerCount(conversationId, messageCount);\n });\n\n if (options._force_new !== true) {\n // Claim the slot. A separate get-then-set would race in a threaded\n // runtime; JS is single-threaded between these statements, so this is\n // one operation for clarity rather than for locking.\n const incumbent = registry.registerIfAbsent(registryKey, this) as SynapClient | undefined;\n if (incumbent !== undefined) return incumbent;\n }\n // Route compaction bundles from the one Listen stream into the typed\n // per-conversation subscriptions. Wired here rather than inside either\n // namespace so the two do not have to import each other.\n this.instance._internal.setCompactionDispatcher((conversationId, bundle) => {\n this.#compactionSubscribers.dispatch(conversationId, bundle as Json, (error) => {\n this.#warn(`compaction subscriber threw: ${String(error)}`);\n });\n });\n }\n\n // ── Deprecated camelCase surface, carried over from the 0.3.x wrapper ───────\n // These return the NORMALISED shape, unlike their namespaced equivalents.\n\n /** @deprecated Use `client.user.context.fetch()`. Note it returns raw snake_case. */\n async fetchUserContext(options: FetchOptions = {}): Promise<NormalisedContext> {\n return normalizeContextResponse((await fetchContext(this.#transport, 'user', options)) as Json);\n }\n\n /** @deprecated Use `client.customer.context.fetch()`. */\n async fetchCustomerContext(options: FetchOptions = {}): Promise<NormalisedContext> {\n return normalizeContextResponse((await fetchContext(this.#transport, 'customer', options)) as Json);\n }\n\n /** @deprecated Use `client.client.context.fetch()`. */\n async fetchClientContext(options: FetchOptions = {}): Promise<NormalisedContext> {\n return normalizeContextResponse((await fetchContext(this.#transport, 'client', options)) as Json);\n }\n\n /** @deprecated Use `client.conversation.context.get_context_for_prompt()`. */\n async getContextForPrompt(\n options: { conversationId?: string; conversation_id?: string; style?: string } = {},\n ): Promise<Json> {\n return this.conversation.context.get_context_for_prompt(options);\n }\n\n /**\n * @deprecated Use `client.user.context.fetch()` and read the typed collections.\n *\n * Flattens every context type into one list, exactly as the 0.3.x bridge did.\n */\n async searchMemory(options: {\n userId?: string; user_id?: string;\n customerId?: string; customer_id?: string;\n query: string;\n maxResults?: number; max_results?: number;\n mode?: string;\n conversationId?: string; conversation_id?: string;\n types?: string[];\n }): Promise<{ results: FlatMemory[]; count: number }> {\n const userId = options.user_id ?? options.userId;\n if (!userId) throw new InvalidInputError('user_id is required');\n if (options.query === undefined || options.query === null) {\n throw new InvalidInputError('query is required');\n }\n const context = await fetchContext(this.#transport, 'user', {\n user_id: userId,\n ...(pick(options, 'customer_id', 'customerId') !== undefined\n ? { customer_id: pick(options, 'customer_id', 'customerId') as string }\n : {}),\n ...(pick(options, 'conversation_id', 'conversationId') !== undefined\n ? { conversation_id: pick(options, 'conversation_id', 'conversationId') as string }\n : {}),\n search_query: [options.query],\n max_results: (pick(options, 'max_results', 'maxResults') as number) ?? 10,\n types: options.types ?? ['all'],\n ...(options.mode !== undefined ? { mode: options.mode } : {}),\n });\n const results = flattenContextItems(context);\n return { results, count: results.length };\n }\n\n /**\n * @deprecated Use `client.user.context.fetch()` with an empty `search_query`.\n *\n * Note the default of 100, not 10: it matches the 0.3.x bridge.\n */\n async getMemories(options: {\n userId?: string; user_id?: string;\n customerId?: string; customer_id?: string;\n mode?: string;\n conversationId?: string; conversation_id?: string;\n maxResults?: number; max_results?: number;\n types?: string[];\n }): Promise<{ results: FlatMemory[]; count: number }> {\n const userId = options.user_id ?? options.userId;\n if (!userId) throw new InvalidInputError('user_id is required');\n const context = await fetchContext(this.#transport, 'user', {\n user_id: userId,\n ...(pick(options, 'customer_id', 'customerId') !== undefined\n ? { customer_id: pick(options, 'customer_id', 'customerId') as string }\n : {}),\n ...(pick(options, 'conversation_id', 'conversationId') !== undefined\n ? { conversation_id: pick(options, 'conversation_id', 'conversationId') as string }\n : {}),\n search_query: [],\n max_results: (pick(options, 'max_results', 'maxResults') as number) ?? 100,\n types: options.types ?? ['all'],\n ...(options.mode !== undefined ? { mode: options.mode } : {}),\n });\n const results = flattenContextItems(context);\n return { results, count: results.length };\n }\n\n /** @deprecated Use `client.memories.create()`. */\n async addMemory(options: CreateMemoryOptions): Promise<CreateMemoryResult> {\n return this.memories.create(options);\n }\n\n /**\n * @deprecated Use `client.memories.delete(memoryId)`.\n *\n * The `{ userId }` form is gone: it relied on a process-local id list and so\n * deleted nothing in serverless while reporting success (gotcha G-F).\n */\n async deleteMemory(options: { memoryId?: string; memory_id?: string }): Promise<Json> {\n return this.memories.delete(options.memory_id ?? options.memoryId ?? '');\n }\n\n /**\n * Resolve `client_id` and `instance_id` from the API key.\n *\n * Mirrors Python's `initialize()`. Python raises \"SDK not initialized\" on\n * any call made before it; here the first request runs the same resolution\n * instead (`identityResolver` on the transport), so skipping this call costs\n * nothing and breaks no existing caller. It matters for the anticipation\n * cache: a bundle shared at client scope is filtered on `client_id`, and an\n * empty one fails that filter for every bundle.\n *\n * Calling it explicitly still locks `configure()`, as in Python. Resolving\n * on first use does not, because a caller who never called it could always\n * configure after a request, and that keeps working.\n *\n * Best-effort and idempotent. A whoami failure leaves whatever the\n * constructor resolved and is not fatal.\n */\n async initialize(): Promise<void> {\n this.#initialized = true;\n await this.#resolveIdentity();\n }\n\n /**\n * The account's scope ladder, or `null` when it cannot be known.\n *\n * Mirrors Python's `get_scope_ladder()`. Read lazily from\n * `GET /api/v1/auth/whoami` (even when the client and instance ids are\n * already known), cached for 300 s (`null` included), re-read on `refresh: true`. Concurrent\n * callers share one read. If a re-read\n * after expiry fails, the last known ladder is returned with a warning and\n * the next try waits 60 s. A failure on the very first read, or with\n * `refresh`, is thrown. With no `scope_ladder` block the default ladder is\n * inferred from `user_context_isolation` (`source: \"inferred\"`).\n *\n * const ladder = await client.get_scope_ladder();\n * const addr = ladder!.address(['acme', 'payments', 'dana']);\n * await client.fetch({ search_query: ['...'], ...addr.read_kwargs() });\n */\n async get_scope_ladder(options: { refresh?: boolean } = {}): Promise<ScopeLadder | null> {\n return this.#transport.getScopeLadder(options.refresh === true, (m) => this.#warn(m));\n }\n\n /** Runs whoami at most once, however many calls arrive together. */\n #resolveIdentity(): Promise<void> {\n this.#identity ??= this.#whoami().catch((error: unknown) => {\n // Only local mode throws. Forget the failure so a later call asks again.\n this.#identity = undefined;\n throw error;\n });\n return this.#identity;\n }\n\n async #whoami(): Promise<void> {\n const credentials = this.#transport.currentCredentials();\n if (!this.#localMode && credentials.clientId !== '' && credentials.instanceId !== '') return;\n try {\n const whoami = (await this.#transport.request('whoami', {})) as Json;\n const resolvedClientId = String(whoami['client_id'] ?? '');\n const resolvedInstanceId = String(whoami['instance_id'] ?? '');\n // The instance's scoping mode. Absent against any server older than this\n // field, and absent stays undefined, which every check treats as \"do not\n // enforce\". The server rejects independently either way.\n const iso = whoami['user_context_isolation'];\n // Stored on the transport, not on the client: every interface factory\n // already receives the transport, and surface-parity.test.ts is right\n // that a public member Python does not have is a divergence.\n this.#transport.userContextIsolation = typeof iso === 'string' ? iso : undefined;\n this.#transport.updateCredentials({\n ...(resolvedClientId !== '' && credentials.clientId === ''\n ? { clientId: resolvedClientId }\n : {}),\n ...(resolvedInstanceId !== '' && credentials.instanceId === ''\n ? { instanceId: resolvedInstanceId }\n : {}),\n });\n\n // Now that the real instance id is known, point it at this client too.\n // It was keyed on the credential because the id did not exist yet, so a\n // later `new SynapClient({ instanceId })` for the same instance would\n // otherwise miss and build a second client: two anticipation caches and\n // two Listen streams for one instance. The credential slot is kept, so\n // constructing by API key keeps resolving here as well.\n if (resolvedInstanceId !== '' && this.#registryKeys.length > 0) {\n if (registry.aliasIfAbsent(resolvedInstanceId, this)) {\n this.#registryKeys.push(resolvedInstanceId);\n }\n }\n } catch (error) {\n // Non-fatal, exactly as in Python: identity resolution is an\n // optimisation, and every route still authenticates on the API key.\n // Local mode has no key to fall back on, so there it is an error.\n if (this.#localMode) {\n throw new AuthenticationError(\n `Could not reach the Synap server at ${this.#transport.baseUrl}, or it did not ` +\n `identify itself: GET /api/v1/auth/whoami failed (${(error as Error)?.message ?? String(error)}).`,\n { cause: error },\n );\n }\n }\n if (this.#localMode) {\n const known = this.#transport.currentCredentials();\n if (known.clientId === '' || known.instanceId === '') {\n throw new AuthenticationError(\n `The Synap server at ${this.#transport.baseUrl} did not identify itself: ` +\n 'GET /api/v1/auth/whoami returned no client_id or instance_id.',\n );\n }\n }\n }\n\n /**\n * @deprecated Use `initialize()`, which is the Python name. `init()` was a\n * JS-only spelling with no Python counterpart; it now forwards, so a 0.3.x\n * startup script keeps working.\n */\n async init(): Promise<void> {\n return this.initialize();\n }\n\n /** The resolved instance id. Empty until `initialize()` resolves it. */\n get instance_id(): string {\n return this.#transport.currentCredentials().instanceId;\n }\n\n /** The resolved client id. Empty until `initialize()` resolves it. */\n get client_id(): string {\n return this.#transport.currentCredentials().clientId;\n }\n\n /**\n * Update configuration before `initialize()`.\n *\n * Mirrors Python's `configure()`, including its refusal to reconfigure after\n * initialization: the transport and cache are already built by then and a\n * half-applied config is worse than a rejected one.\n *\n * `logger` is honoured here as well as on the constructor. The remaining\n * Python-only keys (`storage_path`, `cache_backend`,\n * `session_timeout_minutes`, `log_level`) are accepted and ignored rather\n * than rejected, because this SDK has no SQLite cache backend and no global\n * logging framework whose level there would be to set. Ignoring them keeps\n * a shared config object portable between the two SDKs.\n */\n configure(options: ConfigureOptions = {}): void {\n if (this.#initialized) {\n throw new InvalidInputError('Cannot reconfigure after initialization');\n }\n if (options.timeouts !== undefined) this.#transport.setTimeouts(options.timeouts);\n if (options.retryPolicy !== undefined || options.retry_policy !== undefined) {\n this.#transport.setRetryPolicy(options.retryPolicy ?? options.retry_policy ?? null);\n }\n if (options.logger !== undefined) this.#logger = options.logger;\n // As Python's SDKConfig.history_search_model. Until 0.5.19 only the\n // constructor took it here. It applies to the model the SDK loads when it\n // first needs one; once that has started, changing it does nothing.\n const historyModel = options.history_search_model !== undefined\n ? options.history_search_model\n : options.historySearchModel;\n if (historyModel !== undefined && !this.#localModelStarted) this.#localModelName = historyModel;\n const model = options.agent_model ?? options.agentModel;\n const window = options.agent_context_window ?? options.agentContextWindow;\n if (model !== undefined || window !== undefined) {\n this.#agentModel = {\n model: model ?? this.#agentModel.model,\n contextWindow: window ?? this.#agentModel.contextWindow,\n };\n }\n }\n\n /**\n * Fetch and merge context across every scope with an identifier, in one call.\n *\n * Mirrors Python's `sdk.fetch()`. The three behaviours worth knowing:\n *\n * - Scope fetches run in parallel and a FAILED scope is dropped with a\n * warning rather than failing the call, so partial context still gets\n * returned. The one exception is `InvalidInputError`: a bad request must\n * surface instead of degrading into a silently-empty context.\n * - `user_id` is threaded into the conversation-scope sub-fetch so the\n * anticipation cache can apply its per-user filter.\n * - The summary-mode parameters go ONLY to the user-scope sub-fetch. The\n * other three routes return 422 for `context_mode=\"conversation-summary\"`,\n * and that rejection would be swallowed by the drop-failed-scope rule.\n */\n async fetch(options: UnifiedFetchOptions = {}): Promise<UnifiedContext> {\n const {\n conversation_id: conversationId,\n user_id: userId,\n customer_id: customerId,\n search_query: searchQuery,\n max_results: maxResults = 20,\n types,\n mode = 'fast',\n precision_level: precisionLevel = 'high',\n query_date: queryDate,\n max_results_per_query: maxResultsPerQuery,\n include_conversation_context: includeConversationContext = true,\n scopes,\n include_scope_labels: includeScopeLabels = false,\n context_mode: contextMode = 'in-conversation',\n include_profile: includeProfile = true,\n last_n_conversations: lastNConversations = 1,\n response_shape: responseShape = 'by_type',\n scope_path: scopePath,\n } = options;\n\n // First, as Python checks it: on B2C a customer_id is refused even when\n // `scopes` leaves out every sub-fetch that would have carried it.\n await this.#transport.checkCustomerId(customerId, 'sdk.fetch');\n validateConversationId(conversationId);\n // Up front, as Python does: a bad value inside a scope fetch would be an\n // InvalidInputError too, but only once a scope is queried.\n responseShapeOf({ response_shape: responseShape });\n\n const wants = (scope: string): boolean => scopes === undefined || scopes.includes(scope);\n const shared = {\n search_query: searchQuery,\n max_results: maxResults,\n types,\n mode,\n precision_level: precisionLevel,\n // In `shared` so it reaches all four branches at once. The Python edit\n // threaded three call sites by hand and missed the client branch, which\n // sits one indent deeper; spreading removes that whole class of miss.\n query_date: queryDate,\n max_results_per_query: maxResultsPerQuery,\n response_shape: responseShape,\n // Forwarded only when set (Python: `if scope_path`), so a call without\n // one hands every scope fetch exactly the options it always got.\n ...(scopePath !== undefined && scopePath !== null && Object.keys(scopePath).length > 0\n ? { scope_path: scopePath }\n : {}),\n };\n\n // The customer route reads shared material and refuses a path that names\n // the identity rung (HTTP 400), so it gets the path stopped above that\n // rung. The identity level is found by role on the account's ladder, so the\n // ladder is read first (get_scope_ladder: one shared read, cached 300 s, so\n // usually no request). Only when a path is set AND the customer fetch will\n // run: any other call makes no ladder request. If the read fails, the\n // reserved key `user` is the identity and the failure is warned about.\n // Python: sdk.fetch.\n const { scope_path: _fullPath, ...sharedNoPath } = shared as typeof shared & { scope_path?: Record<string, string> };\n void _fullPath;\n let customerPath: Record<string, string> | undefined;\n if (scopePath && Object.keys(scopePath).length > 0\n && customerId !== undefined && customerId !== null && customerId !== '' && wants('customer')) {\n let ladder: ScopeLadder | null = null;\n try {\n ladder = await this.get_scope_ladder();\n } catch (e) {\n this.#warn(`Could not read the scope ladder (${e instanceof Error ? e.message : String(e)}); `\n + \"cutting the customer scope's path at the reserved key 'user'.\");\n }\n customerPath = pathAboveIdentity(scopePath, ladder);\n }\n const customerShared = customerPath ? { ...sharedNoPath, scope_path: customerPath } : sharedNoPath;\n\n const labels: string[] = [];\n const tasks: Array<Promise<RawContext>> = [];\n\n // `null` means absent, exactly as `validateConversationId` already reads\n // it. The guards below used to test only `!== undefined && !== ''`, so a\n // caller writing `conversation_id: convId || null` -- which is what the\n // Claude Agent (TS) integration writes, and the obvious way to spell \"no\n // conversation\" -- sailed past them and fired a conversation-scope fetch\n // carrying `conversation_id: null`. The validator waved it through and the\n // scope was queried for a conversation that does not exist.\n const present = (v: string | null | undefined): v is string =>\n v !== undefined && v !== null && v !== '';\n\n // No query: the conversation scope answers with the conversation's state\n // (get_context_for_prompt, below) instead of searching for nothing; the\n // user scope answers with the profile when there is one. Summary mode is\n // its own assembly and is unchanged. The state is added only when\n // include_conversation_context asks for it: a framework that keeps its own\n // message history turns it off (pydantic-ai, Mastra), and must not get\n // those turns twice. Python: sdk.fetch.\n const conversationState =\n present(conversationId) && contextMode !== 'conversation-summary'\n && !hasQuery(searchQuery) && wants('conversation');\n const withConversationContext = includeConversationContext;\n\n if (present(conversationId) && wants('conversation') && !conversationState) {\n labels.push('conversation');\n tasks.push(this.conversation.context.fetch({\n conversation_id: conversationId, ...shared,\n user_id: userId, customer_id: customerId,\n } as FetchOptions));\n }\n if (present(userId) && wants('user')) {\n labels.push('user');\n tasks.push(this.user.context.fetch({\n user_id: userId, conversation_id: conversationId, ...shared,\n customer_id: customerId,\n context_mode: contextMode,\n include_profile: includeProfile,\n last_n_conversations: lastNConversations,\n } as FetchOptions));\n }\n if (present(customerId) && wants('customer')) {\n labels.push('customer');\n tasks.push(this.customer.context.fetch({\n customer_id: customerId, conversation_id: conversationId, ...customerShared,\n } as FetchOptions));\n }\n // Client scope needs no identifier (it is inferred from auth), but Python\n // only queries it when EXPLICITLY named in `scopes`. Preserved: including\n // it by default would add a billed fetch to every unified call.\n if (scopes !== undefined && scopes.includes('client')) {\n labels.push('client');\n tasks.push(this.client.context.fetch({\n conversation_id: conversationId, ...sharedNoPath,\n } as FetchOptions));\n }\n\n if (tasks.length === 0 && !(conversationState && includeConversationContext)) {\n const empty = mergeScopeResults([]);\n return empty;\n }\n\n const settled = await Promise.allSettled(tasks);\n const successful: Array<readonly [string, RawContext]> = [];\n for (const [i, result] of settled.entries()) {\n const label = labels[i] as string;\n if (result.status === 'fulfilled') {\n successful.push([label, result.value]);\n continue;\n }\n if (result.reason instanceof InvalidInputError) throw result.reason;\n this.#warn(`Scope '${label}' fetch failed in unified fetch (non-fatal): ${String(result.reason)}`);\n }\n\n const merged = mergeScopeResults(successful);\n\n // Read-your-writes: splice the locally buffered tail over whatever the\n // server returned for this conversation.\n for (const [, response] of successful) {\n overlayLocalRecentTurns(response, this.#shortTerm, conversationId, this.#stVerbatimOverlay);\n }\n\n if (withConversationContext && present(conversationId)) {\n try {\n merged.conversation_context = (await this.conversation.context.get_context_for_prompt({\n conversation_id: conversationId,\n })) as Json;\n if (conversationState && !merged.scopes_queried.includes('conversation')) {\n merged.scopes_queried.unshift('conversation');\n }\n } catch {\n // Non-fatal in Python too: the merged items are still worth returning.\n }\n }\n\n merged.formatted_context = formatForPrompt(merged, {\n includeScope: includeScopeLabels,\n includeConversationContext: withConversationContext,\n });\n return merged;\n }\n\n /**\n * An LLM-ready tool definition that fetches Synap context.\n *\n * Mirrors Python's `as_tool()`. The scope identifiers are closed over, so\n * the model cannot choose whose memory to read.\n */\n as_tool(options: AsToolOptions = {}): ToolDefinition {\n return buildTool(this as never, options, (message) => this.#warn(message));\n }\n\n /**\n * A read-only diagnostic view of the in-process anticipation cache.\n *\n * Mirrors Python's `anticipation_cache_snapshot()`. Returns the same\n * snake_case shape, since this output gets logged and compared across SDKs.\n */\n anticipation_cache_snapshot(): AnticipationCacheSnapshot {\n return this.#anticipationCache.snapshot();\n }\n\n /**\n * Report a locally served fetch back to the server.\n *\n * It rides the Listen stream. While the stream is reconnecting the stream\n * client holds it and sends it on reconnect: a hit never reaches a fetch\n * route, so this report is the only count of it. Never throws, because a\n * telemetry failure must not fail a retrieval that already succeeded.\n */\n #emitContextUsed(\n options: Record<string, unknown>,\n scope: string,\n served: { servedItemIds: string[]; bundleId: string },\n ): void {\n try {\n this.instance._internal.sendContextUsed({\n bundle_id: served.bundleId,\n conversation_id: String(options['conversation_id'] ?? options['conversationId'] ?? ''),\n user_id: String(options['user_id'] ?? options['userId'] ?? ''),\n customer_id: String(options['customer_id'] ?? options['customerId'] ?? ''),\n served_item_ids: served.servedItemIds,\n scope,\n source_bundle_ids: served.bundleId ? [served.bundleId] : [],\n timestamp_ms: Date.now(),\n // How many distinct search queries the fetch carried. A hit never\n // reaches the fetch route, so this event is how the server learns it\n // happened and what it is charged by. The count only: this event must\n // not carry the caller's words.\n query_count: distinctQueryCount(options['search_query'] ?? options['searchQuery']),\n });\n } catch {\n // Non-fatal by design.\n }\n }\n\n /**\n * Report what was actually composed for this turn.\n *\n * Fires whether the fetch was served from the cache or the network, because\n * the audit needs to distinguish them. Like the other stream events it is\n * fire-and-forget and only goes anywhere while listening.\n */\n #emitContextAssembled(\n scope: string,\n options: Record<string, unknown>,\n response: RawContext,\n startedAt: number,\n ): void {\n try {\n if (!this.instance.is_listening) return;\n this.instance._internal.sendContextAssembled({\n ...buildAssembledEvent({\n correlationId: newCorrelationId(),\n response,\n conversationId: (options['conversation_id'] ?? options['conversationId']) as string | undefined,\n userId: (options['user_id'] ?? options['userId']) as string | undefined,\n customerId: (options['customer_id'] ?? options['customerId']) as string | undefined,\n startedAt,\n sdkVersion: SDK_VERSION,\n }),\n scope,\n });\n } catch {\n // Non-fatal by design.\n }\n }\n\n /**\n * Fold a cached user summary in, every Nth turn.\n *\n * Only when the caller supplied a user_id. Without one the summary lookup\n * cannot be scoped, and an unscoped lookup is how user A's summary ends up in\n * user B's response.\n */\n #injectUserSummary(\n response: RawContext,\n conversationId: string | undefined,\n userId: string | undefined,\n scopeRung: string | null,\n ): void {\n this.#turns.increment(conversationId);\n if (userId === undefined || userId === '') return;\n if (!this.#turns.shouldInject(conversationId)) return;\n // The rung, for the same reason the user id is here: a summary prefetched\n // for one rung is not this caller's summary if they are standing at\n // another, and splicing it in is the same failure one level down.\n const summary = this.#anticipationCache.lookupUserSummary(userId, scopeRung);\n if (summary === null) return;\n mergeUserSummary(response, summary as Json);\n }\n\n /**\n * Whether the SDK is authoritative for short-term context.\n *\n * Resolution order matches Python's `_is_st_authoritative`:\n * `SYNAP_SDK_ST_AUTHORITATIVE` first, as an explicit override in either\n * direction, then the option. Off by default. Being enabled does not mean\n * the local store is used: that also takes an entry that holds the whole\n * conversation, see `isComplete`.\n */\n #isStAuthoritative(): boolean {\n const raw = (getEnv('SYNAP_SDK_ST_AUTHORITATIVE') ?? '').trim().toLowerCase();\n if (['0', 'false', 'no', 'off'].includes(raw)) return false;\n if (['1', 'true', 'yes', 'on'].includes(raw)) return true;\n return this.#stAuthoritative === true;\n }\n\n /**\n * Render `get_context_for_prompt` from the local store, or null to fall\n * through to the network.\n *\n * The store answers only when it holds the whole conversation: the server\n * has confirmed a count the entry accounts for. An entry that is merely\n * present is not enough. After a restart or an eviction it holds one turn,\n * and rendering that as the conversation drops everything said before it.\n */\n /**\n * `response` with the earlier turns that best match `query` (by default the\n * latest user message) appended, when a compaction exists. The search runs\n * here, over the turn archive. Python: `_with_history_excerpts`.\n */\n async #withHistoryExcerpts(conversationId: string, response: Json, query: string | undefined): Promise<Json> {\n const r = (response ?? {}) as Record<string, unknown>;\n const store = this.#turnStore;\n const recent = (Array.isArray(r['recent_messages']) ? r['recent_messages'] : []) as Array<Record<string, unknown>>;\n store.addMany(\n conversationId,\n recent.map((m) => ({\n role: String(m['role'] ?? 'user'),\n content: String(m['content'] ?? ''),\n timestamp: String(m['timestamp'] ?? ''),\n message_id: typeof m['message_id'] === 'string' ? m['message_id'] : null,\n })),\n );\n const entry = this.#shortTerm.get(conversationId);\n const total = Math.max(Number(r['total_message_count'] ?? 0) || 0, Number(entry?.serverMessageCount ?? 0) || 0);\n this.#maybeBackfillTurns(conversationId, total);\n if (!r['context_block']) return response;\n const turns = store.turns(conversationId);\n let q = query;\n if (!q) {\n const latest = [...recent].reverse().find((m) => m['role'] === 'user');\n q = latest ? String(latest['content'] ?? '') : ([...turns].reverse().find((t) => t.role === 'user')?.content ?? '');\n }\n if (!q) return response;\n const exclude = new Set<string>();\n for (const m of recent) {\n if (typeof m['message_id'] === 'string' && m['message_id']) exclude.add(m['message_id']);\n exclude.add(String(m['content'] ?? ''));\n }\n this.#startLocalModel();\n const hits = await searchTurns(turns, q, { exclude, encoder: this.#localEncoder, store });\n if (hits.length === 0) return response;\n const block = renderExcerpts(hits, turns.length ? turns[turns.length - 1]!.timestamp : '');\n return {\n ...r,\n history_excerpts: hits.map((h) => ({ position: h.position, role: h.role, text: h.text })),\n history_block: block,\n formatted_context: (String(r['formatted_context'] ?? '').trimEnd() + '\\n\\n' + block).trim(),\n } as Json;\n }\n\n /**\n * Keep what a tool returned in this process's turn archive, so history search\n * can find it after a compaction. Never sent anywhere: the server's\n * conversation holds what people said, and a compaction is made from that.\n * `instance.record_tool_result` calls this too. Python: `archive_tool_result`.\n */\n archive_tool_result(\n conversationId: string,\n result: unknown,\n options: { tool_name?: string | null; toolName?: string | null; timestamp?: string } = {},\n ): void {\n if (!conversationId || result === null || result === undefined) return;\n try {\n this.#turnStore.add(conversationId, 'tool', toolResultText(result, options.tool_name ?? options.toolName),\n options.timestamp ?? new Date().toISOString());\n } catch {\n // The archive is a convenience: never fail the agent's call.\n }\n }\n\n static readonly BACKFILL_COOLDOWN_MS = 60_000;\n static readonly BACKFILL_PAGE = 500;\n\n /** Fetch, in the background, turns the server holds and the archive does not. */\n /**\n * Load the local embedding model in the background, once. Searches and\n * lookups before it is ready match by words. Python: `_start_history_encoder`.\n */\n #startLocalModel(): void {\n if (this.#localModelStarted) return;\n this.#localModelStarted = true;\n if (localModelOff()) return;\n const name = this.#localModelName === 'auto' ? SEMANTIC_MATCH.model : this.#localModelName;\n if (!name) return;\n const callerEncoder = this.#localEncoder;\n void import('./cache/onnx-encoder.js')\n .then(({ canRunLocalModel, loadOnnxEncoder }) => (canRunLocalModel() ? loadOnnxEncoder(name) : null))\n .then((encoder) => {\n if (encoder === null) return;\n // A caller's own encoder keeps history search.\n if (callerEncoder === null) this.#localEncoder = encoder;\n // The anticipation thresholds hold for one model only.\n if (encoder.model === SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(encoder);\n })\n .catch(() => {\n /* words only, as without a model */\n });\n }\n\n #maybeBackfillTurns(conversationId: string, total: number): void {\n if (total <= this.#turnStore.count(conversationId)) return;\n const now = Date.now();\n if (now < (this.#backfillAfter.get(conversationId) ?? 0)) return;\n this.#backfillAfter.set(conversationId, now + SynapClient.BACKFILL_COOLDOWN_MS);\n void this.#backfillTurns(conversationId, total);\n }\n\n async #backfillTurns(conversationId: string, total: number): Promise<void> {\n try {\n let start = 1;\n while (start <= total) {\n const result = await this.#transport.request<Json>('conversation_turns', {\n pathParams: { conversation_id: conversationId },\n query: { start, limit: SynapClient.BACKFILL_PAGE },\n });\n const page = (((result ?? {}) as Record<string, unknown>)['turns'] ?? []) as TurnInput[];\n this.#turnStore.addMany(conversationId, page);\n if (page.length < SynapClient.BACKFILL_PAGE) break;\n start += SynapClient.BACKFILL_PAGE;\n }\n } catch (error) {\n this.#warn(`Turn backfill for ${conversationId} failed: ${String(error)}`);\n }\n }\n\n #localPrompt(conversationId: string, style: string): Json | null {\n if (!this.#isStAuthoritative()) return null;\n const entry = this.#shortTerm.get(conversationId);\n if (entry === null || !isComplete(entry)) return null;\n if (entry.compactionId === null && entry.recentTurns.length === 0) return null;\n return renderForPrompt(entry, style) as unknown as Json;\n }\n\n /** Same, for `get_compacted`. Requires an actual compaction, not just turns. */\n #localCompacted(conversationId: string, format: string): Json | null {\n if (!this.#isStAuthoritative()) return null;\n const entry = this.#shortTerm.get(conversationId);\n if (entry === null || entry.compactionId === null || !isComplete(entry)) return null;\n return renderCompacted(entry, format);\n }\n\n /**\n * Bring the local store back in step from the server's answer.\n *\n * Only for a conversation this process writes to. The server's answer lists\n * every message its summary does not cover, which is exactly what the entry\n * was missing.\n */\n #reseedShortTerm(conversationId: string, response: Json): void {\n if (!this.#isStAuthoritative()) return;\n const entry = this.#shortTerm.get(conversationId);\n if (entry === null || !entry.participant) return;\n const r = (response ?? {}) as Record<string, unknown>;\n const recent = Array.isArray(r['recent_messages']) ? r['recent_messages'] : [];\n this.#shortTerm.reseed(conversationId, {\n compactionId: typeof r['compaction_id'] === 'string' ? r['compaction_id'] : null,\n recentMessages: recent as ShortTermTurn[],\n compactedMessageCount: Number(r['compacted_message_count'] ?? 0) || 0,\n totalMessageCount: Number(r['total_message_count'] ?? 0) || 0,\n });\n }\n\n /** Every diagnostic the SDK emits passes through here. */\n #warn(message: string): void {\n if (this.#logger !== undefined) {\n this.#logger('warn', message);\n return;\n }\n // eslint-disable-next-line no-console\n console.warn(`[synap] ${message}`);\n }\n\n /** Release timers and connections. Safe to call more than once. */\n async shutdown(): Promise<void> {\n if (this.#closed) return;\n this.#closed = true;\n this.#shortTerm.clear();\n this.#turns.clear();\n // Release every registry slot pointing here, so a later construction\n // builds a fresh client rather than adopting this shut-down one. Only\n // slots still owned by this client are dropped.\n for (const key of this.#registryKeys) registry.unregisterIfOwner(key, this);\n\n // Stop the stream first: it holds a socket and a heartbeat timer, and\n // leaving either alive is what keeps a finished process from exiting.\n await this.instance.stop_listening();\n this.#compactionSubscribers.removeAll();\n this.#transport.close();\n this.#anticipationCache.clear();\n }\n}\n\nfunction pick(o: Record<string, unknown>, snake: string, camel: string): unknown {\n const a = o[snake];\n return a !== undefined ? a : o[camel];\n}\n\n/** Explicit option wins, then the environment, then the SDK default. */\nfunction resolveBaseUrl(options: SynapClientOptions): string | undefined {\n const explicit = options.baseUrl ?? options.api_base_url;\n if (explicit !== undefined) return explicit;\n const fromEnv = getEnv('SYNAP_BASE_URL')?.trim();\n return fromEnv !== undefined && fromEnv !== '' ? fromEnv : undefined;\n}\n\nfunction resolveCredentials(options: SynapClientOptions, localMode: boolean): Credentials {\n // Read at call time, not module load, so a late process.env mutation works.\n // `||`, not `??`: an empty apiKey falls back to the environment, as\n // Python's `api_key or os.environ.get(...)` does.\n const apiKey = options.apiKey || getEnv('SYNAP_API_KEY');\n // An AuthenticationError, as Python raises it (auth/manager.py), so one\n // `catch` handles \"no usable key\" in both SDKs. Until 0.5.13 this was an\n // InvalidInputError.\n if (!apiKey && !localMode) {\n throw new AuthenticationError(\n 'No Synap API key found. Set SYNAP_API_KEY in your environment, or pass ' +\n 'apiKey to the SynapClient constructor.',\n );\n }\n return {\n // In local mode the credential is the optional token, '' when there is none.\n apiKey: apiKey || localToken(),\n clientId: options.clientId ?? getEnv('SYNAP_CLIENT_ID') ?? '',\n instanceId: options.instanceId ?? getEnv('SYNAP_INSTANCE_ID') ?? '',\n };\n}\n"]}
|