@maximem/synap-js-sdk 0.6.6 → 0.6.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/grpc/descriptor.ts","../src/grpc/outbox-journal.ts","../src/grpc/stream-client.ts"],"sourcesContent":["/**\n * GENERATED FILE. Do not edit by hand.\n *\n * Source: synap/proto/synap_service.proto\n * Generator: synap/sdk/scripts/gen_proto_descriptor.mjs\n * Proto SHA: 2f2b7989ea808cf5\n *\n * The proto is inlined as a JSON descriptor rather than loaded from disk so\n * that bundlers and Vercel file tracing cannot lose it. Regenerate with\n * `npm run sync-behavior` in synap/sdk/js.\n */\n\n/** sha256 (first 16 hex chars) of the proto this descriptor was built from. */\nexport const PROTO_SHA = '2f2b7989ea808cf5';\n\nexport const SYNAP_PROTO_DESCRIPTOR = {\n \"nested\": {\n \"synap\": {\n \"nested\": {\n \"v1\": {\n \"nested\": {\n \"SynapService\": {\n \"methods\": {\n \"Listen\": {\n \"requestType\": \"StreamEvent\",\n \"requestStream\": true,\n \"responseType\": \"StreamResponse\",\n \"responseStream\": true\n },\n \"IngestTelemetry\": {\n \"requestType\": \"TelemetryEvent\",\n \"requestStream\": true,\n \"responseType\": \"TelemetryAck\"\n }\n }\n },\n \"StreamEvent\": {\n \"oneofs\": {\n \"payload\": {\n \"oneof\": [\n \"conversation_event\",\n \"heartbeat_ping\",\n \"session_control\",\n \"context_used\",\n \"context_assembled\"\n ]\n }\n },\n \"fields\": {\n \"conversation_event\": {\n \"type\": \"ConversationEvent\",\n \"id\": 1\n },\n \"heartbeat_ping\": {\n \"type\": \"HeartbeatPing\",\n \"id\": 2\n },\n \"session_control\": {\n \"type\": \"SessionControl\",\n \"id\": 3\n },\n \"context_used\": {\n \"type\": \"ContextUsedEvent\",\n \"id\": 4\n },\n \"context_assembled\": {\n \"type\": \"ContextAssembledEvent\",\n \"id\": 5\n }\n }\n },\n \"ContextUsedEvent\": {\n \"fields\": {\n \"bundle_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"served_item_ids\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 5\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 6\n },\n \"scope\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"source_bundle_ids\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 8\n },\n \"query_count\": {\n \"type\": \"int32\",\n \"id\": 9\n }\n }\n },\n \"ContextAssembledEvent\": {\n \"fields\": {\n \"correlation_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"final_item_ids\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 5\n },\n \"final_total_tokens\": {\n \"type\": \"int32\",\n \"id\": 6\n },\n \"compaction_id\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"recent_turn_count\": {\n \"type\": \"int32\",\n \"id\": 8\n },\n \"compaction_end_timestamp\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"assembly_source\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"assembly_duration_ms\": {\n \"type\": \"int32\",\n \"id\": 11\n },\n \"cache_hit\": {\n \"type\": \"bool\",\n \"id\": 12\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 13\n },\n \"sdk_version\": {\n \"type\": \"string\",\n \"id\": 14\n }\n }\n },\n \"ConversationEvent\": {\n \"fields\": {\n \"event_type\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"role\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"content\": {\n \"type\": \"string\",\n \"id\": 5\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 6\n },\n \"session_id\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"metadata\": {\n \"keyType\": \"string\",\n \"type\": \"string\",\n \"id\": 8\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 9\n },\n \"tool_name\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"tool_args_json\": {\n \"type\": \"string\",\n \"id\": 11\n },\n \"tool_result_json\": {\n \"type\": \"string\",\n \"id\": 15\n },\n \"tool_call_id\": {\n \"type\": \"string\",\n \"id\": 16\n },\n \"search_queries\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 12\n },\n \"context_types\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 13\n },\n \"scope\": {\n \"keyType\": \"string\",\n \"type\": \"string\",\n \"id\": 14\n },\n \"event_id\": {\n \"type\": \"string\",\n \"id\": 17\n },\n \"sent_at_ms\": {\n \"type\": \"int64\",\n \"id\": 18\n }\n }\n },\n \"HeartbeatPing\": {\n \"fields\": {\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 1\n }\n }\n },\n \"SessionControl\": {\n \"fields\": {\n \"action\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"session_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 5\n }\n }\n },\n \"StreamResponse\": {\n \"oneofs\": {\n \"payload\": {\n \"oneof\": [\n \"context_bundle\",\n \"heartbeat_pong\",\n \"signal\",\n \"event_ack\",\n \"conversation_state\"\n ]\n }\n },\n \"fields\": {\n \"context_bundle\": {\n \"type\": \"ContextBundleProto\",\n \"id\": 1\n },\n \"heartbeat_pong\": {\n \"type\": \"HeartbeatPong\",\n \"id\": 2\n },\n \"signal\": {\n \"type\": \"StreamSignal\",\n \"id\": 3\n },\n \"event_ack\": {\n \"type\": \"EventAck\",\n \"id\": 4\n },\n \"conversation_state\": {\n \"type\": \"ConversationState\",\n \"id\": 5\n }\n }\n },\n \"ConversationState\": {\n \"fields\": {\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"message_count\": {\n \"type\": \"int64\",\n \"id\": 2\n }\n }\n },\n \"EventAck\": {\n \"fields\": {\n \"event_ids\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 1\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 2\n }\n }\n },\n \"HeartbeatPong\": {\n \"fields\": {\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 1\n }\n }\n },\n \"StreamSignal\": {\n \"fields\": {\n \"signal_type\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"reason\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"metadata\": {\n \"keyType\": \"string\",\n \"type\": \"string\",\n \"id\": 3\n }\n }\n },\n \"ContextBundleProto\": {\n \"fields\": {\n \"bundle_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"decision_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"items_by_type\": {\n \"keyType\": \"string\",\n \"type\": \"ContextItemList\",\n \"id\": 3\n },\n \"total_tokens\": {\n \"type\": \"int32\",\n \"id\": 4\n },\n \"token_budget\": {\n \"type\": \"int32\",\n \"id\": 5\n },\n \"budget_exceeded\": {\n \"type\": \"bool\",\n \"id\": 6\n },\n \"retrieval_mode\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"sources_queried\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 8\n },\n \"degradation_level\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"warnings\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 10\n },\n \"created_at\": {\n \"type\": \"string\",\n \"id\": 11\n },\n \"retrieval_time_ms\": {\n \"type\": \"int32\",\n \"id\": 12\n },\n \"cache_hit\": {\n \"type\": \"bool\",\n \"id\": 13\n },\n \"search_queries\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 14\n },\n \"anticipation_user_id\": {\n \"type\": \"string\",\n \"id\": 15\n },\n \"anticipation_customer_id\": {\n \"type\": \"string\",\n \"id\": 16\n },\n \"anticipation_conversation_id\": {\n \"type\": \"string\",\n \"id\": 17\n },\n \"search_keywords\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 18\n },\n \"bundle_type\": {\n \"type\": \"string\",\n \"id\": 19\n },\n \"conversation_context\": {\n \"type\": \"ConversationContextProto\",\n \"id\": 20\n },\n \"bundle_confidence\": {\n \"type\": \"float\",\n \"id\": 21\n },\n \"origin_pattern_id\": {\n \"type\": \"string\",\n \"id\": 22\n },\n \"ttl_hint_seconds\": {\n \"type\": \"int32\",\n \"id\": 23\n },\n \"anticipation_scope_rung\": {\n \"type\": \"string\",\n \"id\": 24\n }\n }\n },\n \"ConversationContextProto\": {\n \"fields\": {\n \"summary\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"current_state_json\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"key_extractions_json\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"recent_turns\": {\n \"rule\": \"repeated\",\n \"type\": \"RecentTurnProto\",\n \"id\": 4\n },\n \"compaction_id\": {\n \"type\": \"string\",\n \"id\": 5\n },\n \"compacted_at\": {\n \"type\": \"string\",\n \"id\": 6\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"compacted_message_count\": {\n \"type\": \"int32\",\n \"id\": 8\n },\n \"total_message_count\": {\n \"type\": \"int32\",\n \"id\": 9\n },\n \"context_block\": {\n \"type\": \"string\",\n \"id\": 10\n }\n }\n },\n \"RecentTurnProto\": {\n \"fields\": {\n \"role\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"content\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"timestamp\": {\n \"type\": \"string\",\n \"id\": 3\n }\n }\n },\n \"ContextItemList\": {\n \"fields\": {\n \"items\": {\n \"rule\": \"repeated\",\n \"type\": \"ContextItemProto\",\n \"id\": 1\n }\n }\n },\n \"ContextItemProto\": {\n \"oneofs\": {\n \"_rank_score\": {\n \"oneof\": [\n \"rank_score\"\n ]\n }\n },\n \"fields\": {\n \"item_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"content\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"context_type\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"source\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"similarity_score\": {\n \"type\": \"float\",\n \"id\": 5\n },\n \"relevance_score\": {\n \"type\": \"float\",\n \"id\": 6\n },\n \"confidence\": {\n \"type\": \"float\",\n \"id\": 7\n },\n \"scope\": {\n \"type\": \"string\",\n \"id\": 8\n },\n \"entity_id\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"created_at\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"event_date\": {\n \"type\": \"string\",\n \"id\": 11\n },\n \"valid_until\": {\n \"type\": \"string\",\n \"id\": 12\n },\n \"temporal_category\": {\n \"type\": \"string\",\n \"id\": 13\n },\n \"temporal_confidence\": {\n \"type\": \"float\",\n \"id\": 14\n },\n \"said_at\": {\n \"type\": \"string\",\n \"id\": 15\n },\n \"rank_score\": {\n \"type\": \"double\",\n \"id\": 16,\n \"options\": {\n \"proto3_optional\": true\n }\n },\n \"questions\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 17\n },\n \"date_prefix\": {\n \"type\": \"string\",\n \"id\": 18\n }\n }\n },\n \"TelemetryEvent\": {\n \"fields\": {\n \"event_type\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"instance_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"client_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"correlation_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 5\n },\n \"latency_ms\": {\n \"type\": \"int32\",\n \"id\": 6\n },\n \"status\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"error_code\": {\n \"type\": \"string\",\n \"id\": 8\n },\n \"scope\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"cache_status\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"attempt\": {\n \"type\": \"int32\",\n \"id\": 11\n },\n \"http_method\": {\n \"type\": \"string\",\n \"id\": 12\n },\n \"http_path\": {\n \"type\": \"string\",\n \"id\": 13\n },\n \"http_status_code\": {\n \"type\": \"int32\",\n \"id\": 14\n },\n \"metadata\": {\n \"keyType\": \"string\",\n \"type\": \"string\",\n \"id\": 15\n },\n \"sdk_version\": {\n \"type\": \"string\",\n \"id\": 16\n },\n \"batch_id\": {\n \"type\": \"string\",\n \"id\": 17\n }\n }\n },\n \"TelemetryAck\": {\n \"fields\": {\n \"status\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"events_received\": {\n \"type\": \"int32\",\n \"id\": 2\n }\n }\n }\n }\n }\n }\n }\n }\n} as const;\n","/**\n * Disk backing for the stream client's outbound buffers.\n *\n * The send queue and the unacknowledged map already survive a dropped\n * connection. Neither survives the process: both live in memory, so a hard\n * kill between a turn being recorded and the server acknowledging it loses\n * that turn with no trace anywhere.\n *\n * Every change to either buffer appends one line here, and the next start\n * reads the file back before the first event goes out. Mirrors Python's\n * `transport/outbox_journal.py` line for line, including the file format, so\n * a Python process and a Node process on the same storage root read each\n * other's journals.\n *\n * **Why a log and not a snapshot.** Rewriting both buffers on every change is\n * O(depth) per event and leaves a window between the change and the write.\n * Debouncing the write widens that window on purpose, which is the opposite of\n * the point. An append is one small line and happens before the caller is told\n * the event was accepted.\n *\n * **Why synchronous.** `appendFileSync`, not the promise form. An async write\n * still pending when the process dies is a write that did not happen, and this\n * file exists precisely for the case where the process dies.\n *\n * **Where it does not run.** Workers, edge runtimes and the browser have no\n * filesystem. `node:fs` is loaded through a guarded dynamic require and, when\n * it is not there, the journal disables itself and the SDK behaves exactly as\n * it did before: buffered events survive a reconnect and not a restart. That\n * is a real gap against Python and it is declared in SDK_PARITY.md rather than\n * papered over, because those runtimes have no disk to offer.\n */\n\n/** The ops, one character each because they are written once per event. */\nconst OP_QUEUED = 'q';\nconst OP_UNACKED = 'u';\nconst OP_ACKED = 'a';\nconst OP_DROPPED = 'd';\n\n/** Rewrite the file once it holds this many lines. The buffers are bounded at\n * 100 entries each, so past a few hundred lines it is mostly tombstones. */\nconst COMPACT_AT_LINES = 500;\n\ninterface NodeFs {\n appendFileSync: (p: string, data: string, enc: string) => void;\n readFileSync: (p: string, enc: string) => string;\n writeFileSync: (p: string, data: string, enc: string) => void;\n mkdirSync: (p: string, opts: { recursive: boolean }) => void;\n existsSync: (p: string) => boolean;\n renameSync: (a: string, b: string) => void;\n unlinkSync: (p: string) => void;\n}\n\n/**\n * `node:fs`, resolved once for the process.\n *\n * It has to be a dynamic `import()`, because this package ships an ESM build\n * and a CJS one and is also used on edge runtimes: a static import would make\n * the edge bundle fail to load over a module it can never use, and `require`\n * is not defined under ESM, which is what the test runner uses. A dynamic\n * import works in all three and simply rejects where there is no `node:fs`.\n *\n * Resolving it is therefore async, but every write here has to be synchronous\n * (an async write still pending when the process dies is a write that did not\n * happen). So it is resolved ONCE, up front, by `OutboxJournal.init()`, which\n * the stream client awaits inside `connect()` before any event can flow. After\n * that the module object is in hand and the appends are plain sync calls.\n */\nlet _fs: NodeFs | null = null;\nlet _fsResolved = false;\nlet _fsPending: Promise<void> | null = null;\n\nasync function resolveFs(): Promise<void> {\n if (_fsResolved) return;\n // Share one in-flight import. Two clients constructed at once would\n // otherwise each start their own, and the second could observe `_fs` still\n // null and disable itself for the life of the process.\n if (_fsPending === null) {\n _fsPending = (async () => {\n try {\n _fs = (await import('node:fs')) as unknown as NodeFs;\n } catch {\n _fs = null; // edge runtime, worker, browser\n }\n _fsResolved = true;\n })();\n }\n await _fsPending;\n}\n\nexport interface JournalEvent { event_id?: string; [k: string]: unknown }\n\n/**\n * The stream protocol carries inline image bytes under this metadata key. The\n * placeholder in `content` is enough for an interrupted event to be replayed,\n * while retaining the bytes would put customer images on disk.\n */\nfunction withoutContentParts(event: JournalEvent): JournalEvent {\n const metadata = event['metadata'];\n if (metadata === null || typeof metadata !== 'object' || Array.isArray(metadata)\n || !Object.prototype.hasOwnProperty.call(metadata, 'synap_content_parts')) {\n return event;\n }\n const cleanMetadata = { ...(metadata as Record<string, unknown>) };\n delete cleanMetadata['synap_content_parts'];\n return { ...event, metadata: cleanMetadata };\n}\n\n/**\n * `~/.synap`, the same root Python's SDK uses, so a Node process and a Python\n * process on one machine read each other's journals. Empty string where there\n * is no home directory to ask for, which disables the journal.\n */\nexport function defaultOutboxRoot(): string {\n try {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env;\n const home = env?.['SYNAP_STORAGE_PATH'] ?? env?.['HOME'] ?? env?.['USERPROFILE'];\n if (home !== undefined && home !== '') {\n return env?.['SYNAP_STORAGE_PATH'] !== undefined && env['SYNAP_STORAGE_PATH'] !== ''\n ? env['SYNAP_STORAGE_PATH'] : `${home}/.synap`;\n }\n } catch { /* no process object: edge runtime */ }\n return '';\n}\n\nexport class OutboxJournal {\n readonly path: string;\n #fs: NodeFs | null;\n #lines = 0;\n #disabled = false;\n\n /**\n * @param root Directory the journal lives under. One file per instance id,\n * because two clients on one instance share a stream in the\n * registry and so the events are the instance's, not the\n * object's.\n */\n /**\n * Resolve `node:fs` once for the process. The stream client awaits this in\n * `connect()` before any event can flow, so by the time anything is written\n * the module is in hand and every append is a plain synchronous call. An\n * async write still pending when the process dies is a write that did not\n * happen, and this file exists for exactly that case.\n */\n static async init(): Promise<void> {\n await resolveFs();\n }\n\n constructor(root: string, instanceId: string, fsImpl?: NodeFs | null) {\n // An empty root means there is nowhere to put this: no home directory, or\n // the caller turned it off. Without this guard the path became\n // `/outbox/<id>.jsonl`, which is a write to the filesystem root.\n this.path = root === '' ? '' : `${root}/outbox/${instanceId}.jsonl`;\n this.#fs = fsImpl !== undefined ? fsImpl : _fs;\n if (this.#fs === null || this.path === '') this.#disabled = true;\n }\n\n get enabled(): boolean { return !this.#disabled; }\n\n // ------------------------------------------------------------------ writes\n\n recordQueued(event: JournalEvent): void {\n this.#append({ op: OP_QUEUED, e: withoutContentParts(event) });\n }\n recordUnacked(event: JournalEvent): void {\n this.#append({ op: OP_UNACKED, e: withoutContentParts(event) });\n }\n recordAcked(id: string): void { this.#append({ op: OP_ACKED, id }); }\n\n /** An event the buffers gave up on. It does not come back on restart either:\n * replaying what the depth or age bound deliberately evicted would quietly\n * undo the bound that evicted it. */\n recordDropped(id: string | undefined): void {\n if (id === undefined || id === '') return;\n this.#append({ op: OP_DROPPED, id });\n }\n\n // ------------------------------------------------------------------- reads\n\n /**\n * Replay the file into `{queued, unacked}`, oldest first.\n *\n * A partial last line from a kill mid-append stops the read there. What came\n * before it is the prefix that was durably written; a torn line is an event\n * the caller was never told had been accepted.\n */\n load(): { queued: JournalEvent[]; unacked: JournalEvent[] } {\n const empty = { queued: [], unacked: [] };\n if (this.#disabled || this.#fs === null) return empty;\n let text: string;\n try {\n if (!this.#fs.existsSync(this.path)) return empty;\n text = this.#fs.readFileSync(this.path, 'utf8');\n } catch {\n return empty;\n }\n const queued = new Map<string, JournalEvent>();\n const unacked = new Map<string, JournalEvent>();\n let lines = 0;\n for (const raw of text.split('\\n')) {\n const line = raw.trim();\n if (line === '') continue;\n let rec: { op?: string; id?: string; e?: JournalEvent };\n try {\n rec = JSON.parse(line) as typeof rec;\n } catch {\n break; // torn last line; everything before it stands\n }\n lines += 1;\n const id = rec.op === OP_QUEUED || rec.op === OP_UNACKED\n ? rec.e?.event_id : rec.id;\n if (id === undefined || id === '') continue;\n if (rec.op === OP_QUEUED) {\n queued.set(id, rec.e as JournalEvent);\n } else if (rec.op === OP_UNACKED) {\n // It left the queue to be written, so it is no longer queued. Without\n // this a reconnect-then-kill replays it from both lists.\n queued.delete(id);\n unacked.set(id, rec.e as JournalEvent);\n } else if (rec.op === OP_ACKED || rec.op === OP_DROPPED) {\n queued.delete(id);\n unacked.delete(id);\n }\n }\n this.#lines = lines;\n return { queued: [...queued.values()], unacked: [...unacked.values()] };\n }\n\n // ------------------------------------------------------------- maintenance\n\n /**\n * Rewrite the file to hold exactly what the buffers hold now.\n *\n * Written beside the target and renamed over it, because rename is atomic: a\n * kill during a compaction leaves either the whole old file or the whole new\n * one, never a half-written mix.\n */\n compact(queued: JournalEvent[], unacked: JournalEvent[]): void {\n if (this.#disabled || this.#fs === null) return;\n if (queued.length === 0 && unacked.length === 0) { this.clear(); return; }\n try {\n this.#mkdir();\n const body = [\n ...unacked.map((e) => JSON.stringify({ op: OP_UNACKED, e: withoutContentParts(e) })),\n ...queued.map((e) => JSON.stringify({ op: OP_QUEUED, e: withoutContentParts(e) })),\n ].join('\\n') + '\\n';\n const tmp = `${this.path}.${Date.now()}.tmp`;\n this.#fs.writeFileSync(tmp, body, 'utf8');\n this.#fs.renameSync(tmp, this.path);\n this.#lines = queued.length + unacked.length;\n } catch {\n // Never break a turn or a close over bookkeeping.\n }\n }\n\n /** Nothing is outstanding, so there is nothing to replay. */\n clear(): void {\n if (this.#disabled || this.#fs === null) return;\n try { this.#fs.unlinkSync(this.path); } catch { /* already gone */ }\n this.#lines = 0;\n }\n\n get needsCompaction(): boolean { return this.#lines >= COMPACT_AT_LINES; }\n\n // ---------------------------------------------------------------- internal\n\n #mkdir(): void {\n const dir = this.path.slice(0, this.path.lastIndexOf('/'));\n this.#fs?.mkdirSync(dir, { recursive: true });\n }\n\n #append(record: Record<string, unknown>): void {\n if (this.#disabled || this.#fs === null) return;\n try {\n this.#mkdir();\n this.#fs.appendFileSync(this.path, `${JSON.stringify(record)}\\n`, 'utf8');\n this.#lines += 1;\n } catch (err) {\n // One warning, then stay quiet: a read-only or full filesystem would\n // otherwise log once per event for the life of the process.\n console.warn(\n `[synap] outbox journal write failed (${String(err)}); buffered events `\n + 'will not survive a restart from here on',\n );\n this.#disabled = true;\n }\n }\n}\n","/**\n * Bidirectional gRPC stream client for the Synap anticipation channel.\n *\n * Mirrors Python's `GRPCTransport` and the synap-vercel-adk client:\n * - `/synap.v1.SynapService/Listen`, StreamEvent in, StreamResponse out\n * - Auth via `authorization: Bearer <key>` plus `x-client-id` / `x-instance-id`\n * - 30s heartbeat, exponential-backoff reconnect\n * - Server pushes ContextBundleProto, which lands in the AnticipationCache\n *\n * Node-only, and reached exclusively through a lazy `import()` so that merely\n * importing the SDK on Edge or in a Worker stays safe. grpc-js is built on\n * `node:http2`/`node:net`/`node:tls`; a static import fails the BUILD there.\n *\n * The proto arrives as an inlined descriptor (see ./descriptor.ts) rather than\n * being read from disk, so bundlers and Vercel file tracing cannot lose it.\n */\n\nimport type { AnticipationCache } from '../context/anticipation-cache.js';\nimport { SYNAP_PROTO_DESCRIPTOR } from './descriptor.js';\nimport { OutboxJournal, defaultOutboxRoot } from './outbox-journal.js';\nimport { newCorrelationId } from '../util/correlation.js';\nimport { InsufficientCreditsError, RateLimitError, type SynapError } from '../errors.js';\n\nexport type StreamState =\n | 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'closed';\n\n/**\n * The ONLY bundle type the cache refuses.\n *\n * NOTE: this deliberately differs from the synap-vercel-adk stream client,\n * which caches an allowlist of `anticipation` and `user_summary` and drops\n * compaction updates. Python's `_handle_anticipated_bundle` stores everything\n * except `reactive`, and Python is the reference implementation, so an\n * allowlist here would silently cache less than the pip SDK does.\n *\n * Reactive bundles are excluded because they answer a fetch that already\n * happened; caching one serves a stale answer to a different question.\n */\nconst UNCACHEABLE_BUNDLE_TYPE = 'reactive';\n\n// Mirrors the Python GRPCTransport constants.\nconst MAX_RECONNECT_ATTEMPTS = 10;\nconst BACKOFF_BASE_MS = 1_000;\nconst BACKOFF_MAX_MS = 30_000;\nconst HEARTBEAT_INTERVAL_MS = 30_000;\nconst HEARTBEAT_TIMEOUT_MS = 10_000;\nconst MAX_MISSED_HEARTBEATS = 3;\n\n// The outbound buffer, same shape and same numbers as Python's transport\n// (SEND_QUEUE_MAX_DEPTH / SEND_QUEUE_MAX_AGE). Events written while the stream\n// is down were silently dropped here: `#write` returned early and said nothing,\n// so a reconnect lost every turn that happened during it.\nconst SEND_QUEUE_MAX_DEPTH = 100;\n// How long disconnect() waits for the server to finish reading after the\n// half-close. Matches Python's CLOSE_GRACE.\nconst CLOSE_GRACE_MS = 2_000;\nconst SEND_QUEUE_MAX_AGE_MS = 5 * 60 * 1_000;\n\n// Cache hits reported while the stream was down (context_used), sent on\n// reconnect. Their own queue: the server acknowledges conversation events,\n// never these. Kept longer than conversation events because a late report is\n// still a correct count and a correct charge (both idempotent on instance,\n// bundle and the hit's time). Python: GRPCTransport.HIT_QUEUE_*.\nconst HIT_QUEUE_MAX_DEPTH = 500;\nconst HIT_QUEUE_MAX_AGE_MS = 30 * 60 * 1_000;\n// How long disconnect() waits for the buffer to go out. Short: a shutdown path\n// that blocks is worse than a lost event.\nconst CLOSE_FLUSH_TIMEOUT_MS = 2_000;\n// Instance still building: the server answers events with a `throttle` signal\n// whose metadata code is `instance_not_ready`. The held events are probed again\n// after the server's retry_after_seconds, clamped to this range and jittered.\n// Same numbers as Python's GRPCTransport.NOT_READY_*.\nconst NOT_READY_MIN_WAIT_MS = 5_000;\nconst NOT_READY_MAX_WAIT_MS = 120_000;\nconst NOT_READY_JITTER = 0.2;\nconst NOT_READY_PROBE_GRACE_MS = 3_000;\n// Most events held in memory while the build runs (and until they are\n// acknowledged afterwards). At the cap the OLDEST are dropped, counted and\n// reported in one warning when the hold ends. Same value as Python's\n// GRPCTransport.NOT_READY_MAX_HELD.\nexport const NOT_READY_MAX_HELD = 5_000;\n// Instance build FAILED (throttle metadata code `instance_build_failed`). Not\n// time based, so there is no hint to wait for: events are held the same way but\n// probed at this slow fixed interval plus jitter, so the stream recovers by\n// itself after a rebuild, with no reconnect loop. Same numbers as Python's\n// GRPCTransport.BUILD_FAILED_PROBE_*.\nexport const BUILD_FAILED_PROBE_INTERVAL_MS = 60_000;\nexport const BUILD_FAILED_PROBE_JITTER_MS = 10_000;\n/** The server may only SHORTEN the SDK default, never extend it past this floor. */\nconst MIN_TTL_SECONDS = 60;\n\n/** What the server said when it refused events for an unfinished build. */\nexport interface InstanceNotReadyInfo {\n retryAfterSeconds: number;\n instanceId: string;\n state: string;\n message: string;\n /** `instance_not_ready` (building) or `instance_build_failed`. */\n code: string;\n /** Recovery instruction from the server; only set for `instance_build_failed`. */\n hint?: string;\n attempts?: string;\n}\n\nexport interface StreamCredentials {\n apiKey: string;\n clientId: string;\n instanceId: string;\n}\n\nexport interface StreamClientOptions {\n host?: string;\n port?: number;\n useTls?: boolean;\n /** Injected in tests so reconnect backoff does not make the suite slow. */\n sleep?: (ms: number) => Promise<void>;\n /** How long to wait for the channel to become ready. Default 10s. */\n connectTimeoutMs?: number;\n onStateChange?: (state: StreamState) => void;\n /** Fires for every bundle, before the cache filter. Backs `listen({onContext})`. */\n onContext?: (bundle: Record<string, unknown>) => void;\n /** Fires only for `compaction_update` bundles. Backs the compaction subscriptions. */\n onCompactionUpdate?: (conversationId: string, bundle: Record<string, unknown>) => void;\n /**\n * The server's message count for a conversation, sent after it has written a\n * streamed message. See `ConversationState` in the proto.\n */\n onConversationState?: (conversationId: string, messageCount: number) => void;\n /**\n * Where the outbox journal lives, so buffered events survive a restart.\n * Defaults to `~/.synap`, the same root Python uses. `''` turns it off, and\n * it is off anyway wherever there is no filesystem.\n */\n outboxPath?: string;\n}\n\n/**\n * grpc-js status code for RESOURCE_EXHAUSTED. Hard-coded rather than read from\n * `grpc.status`, because this module is loaded before grpc-js on some paths and\n * the numbers are fixed by the gRPC spec.\n */\nconst GRPC_RESOURCE_EXHAUSTED = 8;\n\n/**\n * The credit gate refuses a call with RESOURCE_EXHAUSTED, these details, and\n * the balance and reason in trailing metadata. See\n * synap/cloud/application/credits/grpc_gate.py.\n */\nexport const CREDIT_ABORT_DETAILS = 'insufficient_credits';\n\n/**\n * Reasons that end the stream. A reconnect re-runs the same gate with the same\n * balance, so retrying only delays the answer the caller needs. Mirrors\n * `CREDIT_STOP_REASONS` in `transport/grpc_client.py`.\n */\nexport const CREDIT_STOP_REASONS = new Set([\n 'overages_disabled',\n 'trial_limit_reached',\n 'subscription_inactive',\n]);\n\nfunction metadataValue(metadata: unknown, key: string): string | null {\n if (metadata === null || typeof metadata !== 'object') return null;\n const getter = (metadata as { get?: (k: string) => unknown }).get;\n const raw = typeof getter === 'function'\n ? getter.call(metadata, key)\n : (metadata as Record<string, unknown>)[key];\n const value = Array.isArray(raw) ? raw[0] : raw;\n if (value === undefined || value === null) return null;\n const text = typeof value === 'string' ? value : String(value);\n return text === '' ? null : text;\n}\n\nfunction numberOrNull(value: string | null): number | null {\n if (value === null) return null;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\n/**\n * Translate a credit refusal into the same error HTTP would have raised.\n *\n * RESOURCE_EXHAUSTED on its own is indistinguishable from server overload, so\n * this keys on `credit-reason`: `overages_disabled` is an\n * `InsufficientCreditsError` (permanent, a paid plan at zero that has not\n * allowed usage past zero), while `trial_limit_reached` and\n * `subscription_inactive` are a `RateLimitError`. Returns null for anything\n * else, including a RESOURCE_EXHAUSTED that is not a credit refusal and a\n * reason this SDK does not know: the caller then keeps its existing behaviour\n * of treating the abort as transient. Mirrors `credit_error_from_rpc`.\n */\nexport function creditErrorFromRpc(\n error: unknown,\n correlationId: string | null = null,\n): SynapError | null {\n if (error === null || typeof error !== 'object') return null;\n if ((error as { code?: unknown }).code !== GRPC_RESOURCE_EXHAUSTED) return null;\n\n const metadata = (error as { metadata?: unknown }).metadata;\n const reason = metadataValue(metadata, 'credit-reason');\n if (reason === null || !CREDIT_STOP_REASONS.has(reason)) return null;\n\n const rawDetails = (error as { details?: unknown }).details;\n const details = typeof rawDetails === 'string' && rawDetails !== ''\n ? rawDetails\n : CREDIT_ABORT_DETAILS;\n const requestId = metadataValue(metadata, 'request-id') ?? correlationId;\n const manageUrl = metadataValue(metadata, 'credit-manage-url');\n\n if (reason === 'overages_disabled') {\n return new InsufficientCreditsError(details, {\n correlationId: requestId,\n balanceCredits: numberOrNull(metadataValue(metadata, 'credit-balance')),\n requiredCredits: numberOrNull(metadataValue(metadata, 'credit-minimum-required')),\n recoveryUrl: metadataValue(metadata, 'credit-recovery-url'),\n redeemUrl: metadataValue(metadata, 'credit-redeem-url'),\n reason,\n manageUrl,\n });\n }\n\n return new RateLimitError(details, {\n correlationId: requestId,\n reason,\n upgradeUrl: metadataValue(metadata, 'credit-upgrade-url'),\n manageUrl,\n });\n}\n\n/** True for an error this module raised from a credit refusal. */\nexport function isCreditStop(error: unknown): boolean {\n if (!(error instanceof InsufficientCreditsError) && !(error instanceof RateLimitError)) {\n return false;\n }\n const reason = (error as { reason?: unknown }).reason;\n return typeof reason === 'string' && CREDIT_STOP_REASONS.has(reason);\n}\n\ninterface DuplexCall {\n write: (msg: unknown) => void;\n on: (event: string, handler: (arg?: unknown) => void) => void;\n end: () => void;\n}\n\nexport interface ConversationEventInput {\n event_type: string;\n conversation_id?: string;\n user_id?: string;\n customer_id?: string;\n role?: string;\n content?: string;\n session_id?: string;\n metadata?: Record<string, string>;\n timestamp_ms?: number;\n /** proto: ConversationEvent.tool_name */\n tool_name?: string;\n /** proto: ConversationEvent.tool_args_json. Python sends json.dumps(tool_args). */\n tool_args_json?: string;\n /**\n * proto: ConversationEvent.tool_result_json. A result is not a message, so\n * it does not ride in `content`; a string is sent as itself rather than as a\n * quoted JSON string, matching Python.\n */\n tool_result_json?: string;\n /** proto: ConversationEvent.tool_call_id. Ties a result to its call. */\n tool_call_id?: string;\n search_queries?: string[];\n context_types?: string[];\n /** proto: ConversationEvent.scope. The conversation's rung. */\n scope?: Record<string, string>;\n /**\n * proto: ConversationEvent.event_id. Minted here when absent, and the SAME\n * id travels on every replay — that is what the server's dedupe matches, so\n * a retry cannot double a turn.\n */\n event_id?: string;\n /** proto: ConversationEvent.sent_at_ms. When we FIRST tried, not when it happened. */\n sent_at_ms?: number;\n}\n\nexport class GrpcStreamClient {\n readonly host: string;\n readonly port: number;\n readonly useTls: boolean;\n\n #state: StreamState = 'disconnected';\n #call: DuplexCall | null = null;\n #reconnectAttempts = 0;\n #lastPongAt = 0;\n #missedHeartbeats = 0;\n #heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n #shutdownRequested = false;\n // Events that could not be written because there was no stream.\n #sendQueue: Array<{ queuedAt: number; event: ConversationEventInput }> = [];\n /** Cache-hit reports waiting for a stream. See HIT_QUEUE_*. */\n #pendingHits: Array<{ queuedAt: number; event: Record<string, unknown> }> = [];\n // Events written to a live stream that the server has not acknowledged. The\n // queue above covers \"the stream was down\"; this covers the half that\n // actually loses sessions — the write succeeded, the stream broke before the\n // server processed it, and nobody knows.\n #unacked = new Map<string, { queuedAt: number; event: ConversationEventInput }>();\n // Set while the server refuses events because the instance is still being\n // built. Null otherwise. See `#handleNotReady`.\n #notReady: InstanceNotReadyInfo | null = null;\n #notReadyWarned = false;\n // `instanceId|series` pairs already warned about for a failed build.\n #buildFailedWarned = new Set<string>();\n #notReadyResignalled = false;\n #notReadyRunning = false;\n // Events held (tracked, not written) since the last replay.\n #notReadyUnwritten: ConversationEventInput[] = [];\n // Held events dropped at NOT_READY_MAX_HELD, reported when the hold ends.\n #notReadyDropped = 0;\n // True from the first refusal until the backlog is acknowledged, so the\n // normal 100-event cap does not evict held events in the gap after resume.\n #heldBacklog = false;\n #notReadyWake: (() => void) | null = null;\n // Why the stream stopped, when it stopped for a reason the caller can act on\n // (today: a credit refusal). Mirrors Python's `last_error`.\n #lastError: SynapError | null = null;\n // Disk backing for the two buffers above. They survive a dropped\n // connection and not the process; this is what the next start reads.\n readonly #journal: OutboxJournal;\n\n #grpc: typeof import('@grpc/grpc-js') | null = null;\n #ServiceStub: (new (target: string, creds: unknown, opts: unknown) => Record<string, unknown>) | null = null;\n\n readonly #credentials: StreamCredentials;\n readonly #cache: AnticipationCache;\n readonly #options: StreamClientOptions;\n readonly #sleep: (ms: number) => Promise<void>;\n readonly #connectTimeoutMs: number;\n\n constructor(\n credentials: StreamCredentials,\n cache: AnticipationCache,\n options: StreamClientOptions = {},\n ) {\n this.#credentials = credentials;\n this.#cache = cache;\n this.#options = options;\n this.host = options.host ?? 'synap-cloud-prod.maximem.ai';\n this.port = options.port ?? 443;\n this.useTls = options.useTls ?? true;\n this.#sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));\n this.#connectTimeoutMs = options.connectTimeoutMs ?? 10_000;\n this.#journal = new OutboxJournal(\n options.outboxPath ?? defaultOutboxRoot(), credentials.instanceId);\n }\n\n get currentState(): StreamState { return this.#state; }\n get isConnected(): boolean { return this.#state === 'connected'; }\n\n /**\n * The error that ended the stream, if one did.\n *\n * Set when the server refused the stream for credits, so an `onDisconnect`\n * handler can read the balance, the reason and the URL to fix it. Null for an\n * ordinary disconnect.\n */\n get lastError(): SynapError | null { return this.#lastError; }\n\n /**\n * Why the server is refusing events right now, or null.\n *\n * Set from the moment the server answers an event with an\n * `instance_not_ready` throttle until a replay of the held events is\n * accepted. The events are held, not dropped. Mirrors Python's\n * `GRPCTransport.instance_not_ready`.\n */\n get instanceNotReady(): InstanceNotReadyInfo | null {\n return this.#notReady === null ? null : { ...this.#notReady };\n }\n\n async connect(): Promise<void> {\n await this.#loadGrpc();\n // Resolve node:fs once, before anything can be written. Every journal\n // append after this is synchronous, which is the point: an async write\n // still pending when the process dies is a write that did not happen.\n await OutboxJournal.init();\n this.#shutdownRequested = false;\n this.#lastError = null;\n // Before the connection, so a previous process's unsent events are already\n // in the queue when the stream comes up and go out ahead of this process's\n // first event. That is the order they happened in.\n this.#restoreFromJournal();\n await this.#establish();\n this.#startHeartbeat();\n }\n\n /**\n * Pull a previous process's unsent events back into the send queue.\n *\n * Everything lands in the send queue, including what was unacknowledged last\n * time. The stream those events were written to is gone, so \"the server may\n * already have it\" is not a state we can resume; it has to be written again.\n * That is safe because each event carries the id it was first sent with and\n * the server drops a second sighting of it before dispatch, so an event it\n * DID process is deduplicated there rather than doubling the turn.\n */\n #restoreFromJournal(): void {\n const { queued, unacked } = this.#journal.load();\n if (queued.length === 0 && unacked.length === 0) return;\n const now = Date.now();\n // Unacknowledged first: an event written to the old stream is older than\n // anything that piled up after it died.\n for (const event of [...unacked, ...queued]) {\n this.#sendQueue.push({\n queuedAt: now, event: event as unknown as ConversationEventInput,\n });\n }\n console.warn(\n `[synap] restored ${unacked.length + queued.length} event(s) from the `\n + `previous process (${unacked.length} unacknowledged, ${queued.length} `\n + 'queued); they go out on this stream',\n );\n this.#compactJournal();\n }\n\n #compactJournal(): void {\n this.#journal.compact(\n this.#sendQueue.map((h) => h.event as unknown as Record<string, unknown>),\n [...this.#unacked.values()].map(\n (h) => h.event as unknown as Record<string, unknown>),\n );\n }\n\n async disconnect(): Promise<void> {\n // Stop the heartbeat first: it writes, and a write after the half-close\n // below is an error.\n this.#shutdownRequested = true;\n this.#stopHeartbeat();\n this.#notReadyWake?.();\n\n // What is still buffered goes out before the half-close.\n this.#flushBeforeClose();\n\n // ⚠ `end()` half-closes the write side, which is right, but on its own it\n // is not enough. It used to return immediately and the process would exit\n // while the server was still reading, so the events were written and never\n // processed. Waiting for the server to finish its side is what makes the\n // half-close mean anything.\n //\n // Bounded, because a shutdown that hangs on a dead network is its own kind\n // of broken, and whatever misses the deadline is reported rather than lost\n // silently. See `undelivered()`.\n const call = this.#call;\n if (call !== null) {\n try { call.end(); } catch { /* already torn down */ }\n await new Promise<void>((resolve) => {\n let settled = false;\n const done = () => { if (!settled) { settled = true; resolve(); } };\n const timer = setTimeout(() => {\n const left = this.undelivered();\n if (left.unacknowledged > 0 || left.queued > 0) {\n console.warn(\n `[synap] closing with ${left.queued} queued and `\n + `${left.unacknowledged} unacknowledged event(s) the server did `\n + `not confirm within ${CLOSE_GRACE_MS}ms`,\n );\n }\n done();\n }, CLOSE_GRACE_MS);\n if (typeof timer.unref === 'function') timer.unref();\n call.on('end', () => { clearTimeout(timer); done(); });\n call.on('status', () => { clearTimeout(timer); done(); });\n call.on('error', () => { clearTimeout(timer); done(); });\n });\n }\n\n this.#call = null;\n // After the flush and the half-close, so the file describes what is\n // actually still outstanding. An empty pair removes it, which is how a\n // clean shutdown leaves nothing for the next start to replay.\n this.#compactJournal();\n this.#setState('closed');\n }\n\n /**\n * What this client could not get to the server.\n *\n * Every send path returns void, so a caller had no way to tell a delivered\n * turn from a lost one. Mirrors Python's `undelivered()`.\n */\n undelivered(): { queued: number; unacknowledged: number } {\n return { queued: this.#sendQueue.length, unacknowledged: this.#unacked.size };\n }\n\n /**\n * Never fails the caller's turn, and no longer loses it either.\n *\n * A write that cannot go out is buffered and replayed on reconnect, and a\n * write that does go out is held until the server acknowledges it. Before\n * this, both cases ended at a silent `return`.\n */\n sendConversationEvent(event: ConversationEventInput): void {\n const stamped: ConversationEventInput = {\n ...event,\n event_id: event.event_id && event.event_id !== '' ? event.event_id : newCorrelationId(),\n sent_at_ms: event.sent_at_ms ?? Date.now(),\n };\n if (!this.isConnected || this.#call === null) {\n this.#enqueue(stamped);\n return;\n }\n if (this.#notReady !== null) {\n // The server is refusing events until the build finishes. Writing this\n // one would only earn another refusal, so hold it with the rest; the\n // probe loop replays everything in order.\n this.#trackUnacked(stamped);\n this.#notReadyUnwritten.push(stamped);\n return;\n }\n this.#write({ conversation_event: { ...stamped } });\n this.#trackUnacked(stamped);\n }\n\n #enqueue(event: ConversationEventInput): void {\n this.#pruneQueue();\n if (this.#sendQueue.length >= SEND_QUEUE_MAX_DEPTH) {\n const evicted = this.#sendQueue.shift();\n this.#journal.recordDropped(evicted?.event.event_id);\n console.warn(\n `[synap] send queue full (max=${SEND_QUEUE_MAX_DEPTH}); dropping oldest `\n + `event (event_type=${evicted?.event.event_type})`,\n );\n }\n this.#sendQueue.push({ queuedAt: Date.now(), event });\n this.#journal.recordQueued(event as unknown as Record<string, unknown>);\n }\n\n #pruneQueue(): void {\n const cutoff = Date.now() - SEND_QUEUE_MAX_AGE_MS;\n while (this.#sendQueue.length > 0 && (this.#sendQueue[0]?.queuedAt ?? 0) < cutoff) {\n const expired = this.#sendQueue.shift();\n this.#journal.recordDropped(expired?.event.event_id);\n console.warn(\n `[synap] queued event expired (age>${SEND_QUEUE_MAX_AGE_MS}ms); dropping `\n + `(event_type=${expired?.event.event_type})`,\n );\n }\n }\n\n #trackUnacked(event: ConversationEventInput): void {\n const id = event.event_id;\n if (id === undefined || id === '') return;\n const cutoff = Date.now() - SEND_QUEUE_MAX_AGE_MS;\n for (const [oldestId, held] of this.#unacked) {\n // While the build runs (and until the backlog is acknowledged) the age\n // limit does not apply and the depth limit is NOT_READY_MAX_HELD: a build\n // outlasts the 5 minute window and holding 100 events would drop data.\n const holding = this.#notReady !== null || this.#heldBacklog;\n const limit = holding ? NOT_READY_MAX_HELD : SEND_QUEUE_MAX_DEPTH;\n const youngEnough = held.queuedAt >= cutoff || holding;\n if (youngEnough && this.#unacked.size < limit) break;\n if (holding) {\n this.#unacked.delete(oldestId);\n this.#journal.recordDropped(oldestId);\n this.#notReadyDropped += 1;\n continue;\n }\n this.#unacked.delete(oldestId);\n this.#journal.recordDropped(oldestId);\n console.warn(\n '[synap] unacknowledged event dropped: the server never confirmed it '\n + `(event_type=${held.event.event_type})`,\n );\n }\n this.#unacked.set(id, { queuedAt: Date.now(), event });\n this.#journal.recordUnacked(event as unknown as Record<string, unknown>);\n }\n\n /**\n * Replay what the server never confirmed, then what never went out.\n *\n * That order is the order things happened in: an unacked event was written\n * to the previous stream, so it is older than anything that piled up while\n * there was no stream at all. Safe to repeat — every event carries the id it\n * was first sent with and the server drops a second sighting of it.\n */\n #replayBuffered(): void {\n const unacked = [...this.#unacked.values()];\n const queued = this.#sendQueue;\n this.#sendQueue = [];\n for (const held of unacked) {\n this.#write({ conversation_event: { ...held.event } });\n }\n for (const held of queued) {\n this.#write({ conversation_event: { ...held.event } });\n // Written and not yet acknowledged is exactly what `#unacked` is for.\n // Without this a refusal after the replay (an unfinished build, a stream\n // that breaks again) lost every event the replay had just sent. Python's\n // `_drain_send_queue` has always tracked them.\n this.#trackUnacked(held.event);\n }\n if (unacked.length > 0 || queued.length > 0) {\n console.warn(\n `[synap] replayed ${unacked.length} unacknowledged and ${queued.length} `\n + 'queued event(s) after reconnect',\n );\n }\n }\n\n sendSessionControl(input: {\n action: string;\n session_id?: string;\n conversation_id?: string;\n user_id?: string;\n customer_id?: string;\n }): void {\n this.#write({ session_control: { ...input } });\n }\n\n /**\n * Report a fetch served from the anticipation cache. It is the only report\n * of that fetch, so it is held while the stream is down and sent on\n * reconnect, with the time the hit happened (the caller's `timestamp_ms`),\n * never dropped. Python: `GRPCTransport.send_context_used`.\n */\n sendContextUsed(event: Record<string, unknown>): void {\n const stamped = { ...event, timestamp_ms: event['timestamp_ms'] ?? Date.now() };\n if (!this.isConnected || this.#call === null) {\n this.#queueHit(stamped);\n return;\n }\n this.#write({ context_used: stamped });\n }\n\n #queueHit(event: Record<string, unknown>): void {\n const cutoff = Date.now() - HIT_QUEUE_MAX_AGE_MS;\n while (this.#pendingHits.length > 0 && (this.#pendingHits[0]?.queuedAt ?? 0) < cutoff) {\n this.#pendingHits.shift();\n }\n if (this.#pendingHits.length >= HIT_QUEUE_MAX_DEPTH) {\n this.#pendingHits.shift();\n console.warn(`[synap] cache-hit report queue full (max=${HIT_QUEUE_MAX_DEPTH}); dropping the oldest`);\n }\n this.#pendingHits.push({ queuedAt: Date.now(), event });\n }\n\n #flushPendingHits(): void {\n const cutoff = Date.now() - HIT_QUEUE_MAX_AGE_MS;\n const held = this.#pendingHits;\n this.#pendingHits = [];\n for (const h of held) {\n if (h.queuedAt >= cutoff) this.#write({ context_used: h.event });\n }\n }\n\n /** How many cache-hit reports are waiting for a stream. */\n get pendingHitReports(): number {\n return this.#pendingHits.length;\n }\n\n sendContextAssembled(event: Record<string, unknown>): void {\n this.#write({ context_assembled: { ...event } });\n }\n\n #flushBeforeClose(): void {\n if (!this.isConnected || this.#call === null) {\n if (this.#sendQueue.length > 0 || this.#unacked.size > 0) {\n console.warn(\n `[synap] closing with ${this.#sendQueue.length} queued and `\n + `${this.#unacked.size} unacknowledged event(s) and no stream to send `\n + 'them on; they are lost',\n );\n }\n return;\n }\n const queued = this.#sendQueue;\n this.#sendQueue = [];\n for (const held of queued) {\n this.#write({ conversation_event: { ...held.event } });\n }\n }\n\n #write(msg: unknown): void {\n if (!this.isConnected || this.#call === null) return;\n try {\n this.#call.write(msg);\n } catch {\n // Non-fatal. These are telemetry and control events; losing one is\n // strictly better than surfacing a stream hiccup to the caller.\n }\n }\n\n async #loadGrpc(): Promise<void> {\n if (this.#grpc !== null) return;\n const [grpcMod, protoMod] = await Promise.all([\n import(/* @vite-ignore */ '@grpc/grpc-js'),\n import(/* @vite-ignore */ '@grpc/proto-loader'),\n ]);\n this.#grpc = grpcMod;\n\n // `fromJSON`, not `loadSync`: no path, no disk read, nothing for a bundler\n // to fail to trace. `keepCase` keeps the snake_case field names the server\n // and the Python SDK both use.\n const pkgDef = protoMod.fromJSON(\n SYNAP_PROTO_DESCRIPTOR as unknown as Parameters<typeof protoMod.fromJSON>[0],\n { keepCase: true, longs: Number, enums: String, defaults: true, oneofs: true },\n );\n const pkg = grpcMod.loadPackageDefinition(pkgDef) as unknown as {\n synap: { v1: { SynapService: new (t: string, c: unknown, o: unknown) => Record<string, unknown> } };\n };\n this.#ServiceStub = pkg.synap.v1.SynapService;\n }\n\n async #establish(): Promise<void> {\n this.#setState('connecting');\n const grpc = this.#grpc;\n const Stub = this.#ServiceStub;\n if (grpc === null || Stub === null) throw new Error('gRPC not loaded');\n\n const channelCreds = this.useTls\n ? grpc.credentials.createSsl()\n : grpc.credentials.createInsecure();\n\n const stub = new Stub(`${this.host}:${this.port}`, channelCreds, {\n 'grpc.keepalive_time_ms': 30_000,\n 'grpc.keepalive_timeout_ms': 10_000,\n 'grpc.keepalive_permit_without_calls': 1,\n });\n\n // Wait for the channel before reporting success.\n //\n // grpc-js connects LAZILY: constructing the stub and creating the call both\n // return immediately, and a bad host surfaces later through the call's\n // 'error' event. Without this, `await listen()` resolved against an\n // unreachable port, `is_listening` read true for a stream that never\n // connected, and `send_message()` then dropped every event silently,\n // because sends are deliberately fire-and-forget. Failing loudly here is\n // the difference between a clear error and an agent that looks like it has\n // no memory.\n await new Promise<void>((resolve, reject) => {\n const deadline = new Date(Date.now() + this.#connectTimeoutMs);\n const waitForReady = (stub as unknown as {\n waitForReady?: (d: Date, cb: (e?: Error) => void) => void;\n }).waitForReady;\n if (typeof waitForReady !== 'function') {\n // Older grpc-js, or a stub that does not expose it. Fall back to the\n // lazy behaviour rather than failing outright.\n resolve();\n return;\n }\n waitForReady.call(stub, deadline, (error?: Error) => {\n if (error) reject(error);\n else resolve();\n });\n });\n\n const metadata = new grpc.Metadata();\n metadata.add('authorization', `Bearer ${this.#credentials.apiKey}`);\n metadata.add('x-client-id', this.#credentials.clientId);\n metadata.add('x-instance-id', this.#credentials.instanceId);\n\n const call = (stub['Listen'] as (m: unknown) => DuplexCall)(metadata);\n call.on('data', (msg) => this.#handleMessage(msg as Record<string, unknown>));\n call.on('error', (err) => {\n // A credit refusal arrives here, not from waitForReady: the channel is\n // healthy and the gate aborts the call itself.\n const creditError = creditErrorFromRpc(err);\n if (creditError !== null) {\n this.#handleCreditStop(creditError);\n return;\n }\n void this.#handleDisconnect(`error: ${String(err)}`);\n });\n call.on('end', () => { void this.#handleDisconnect('server_close'); });\n\n // NOTE, and this is where JS and Python legitimately differ.\n //\n // Python waits on `call.wait_for_connection()` here, because grpc.aio\n // reports CONNECTED off a call object the server has not accepted and\n // events written in that window were written into a buffer that the close\n // then discarded.\n //\n // grpc-js has no equivalent, and the obvious stand-in does not work: a\n // grpc-js server sends no initial metadata until it writes, so waiting on\n // the 'metadata' event stalls for the whole connect timeout on a server\n // that is perfectly healthy. Measured: it made every test here time out.\n //\n // It is also not needed. grpc-js buffers writes on the call and flushes\n // them once the call is established, so an event written this early is not\n // lost by the write. It is lost by the TEARDOWN, which is what\n // `disconnect()` now fixes: half-close, then wait for the server to finish\n // reading. The parity is in the outcome the tests assert, a whole turn\n // reaching the server with no pause anywhere, not in the mechanism.\n this.#call = call;\n this.#setState('connected');\n this.#reconnectAttempts = 0;\n this.#lastPongAt = Date.now();\n // Before anything else on the new stream: the turns that happened while\n // there was not one, then the cache hits.\n this.#replayBuffered();\n this.#flushPendingHits();\n }\n\n #handleMessage(msg: Record<string, unknown>): void {\n const ack = msg['event_ack'] as { event_ids?: string[] } | undefined;\n if (ack) {\n for (const id of ack.event_ids ?? []) {\n this.#unacked.delete(id);\n this.#journal.recordAcked(id);\n }\n if (this.#notReady === null && this.#unacked.size < SEND_QUEUE_MAX_DEPTH) {\n this.#heldBacklog = false;\n }\n if (\n this.#notReady === null && (ack.event_ids ?? []).length > 0\n && (this.#notReadyWarned || this.#buildFailedWarned.size > 0)\n ) {\n // The server is accepting again, so the next build gets its own warning.\n this.#notReadyWarned = false;\n this.#buildFailedWarned.clear();\n }\n if (this.#journal.needsCompaction) this.#compactJournal();\n return;\n }\n if (msg['context_bundle']) {\n this.#handleBundle(msg['context_bundle'] as Record<string, unknown>);\n return;\n }\n if (msg['heartbeat_pong']) {\n this.#lastPongAt = Date.now();\n this.#missedHeartbeats = 0;\n return;\n }\n const state = msg['conversation_state'] as\n | { conversation_id?: string; message_count?: number | string }\n | undefined;\n if (state) {\n // int64 arrives as a string or a number depending on the loader options.\n const count = Number(state.message_count ?? 0);\n if (state.conversation_id && Number.isFinite(count)) {\n this.#options.onConversationState?.(state.conversation_id, count);\n }\n return;\n }\n const signal = msg['signal'] as\n | { signal_type?: string; reason?: string; metadata?: Record<string, string> }\n | undefined;\n if (signal?.signal_type === 'throttle') {\n const metadata = signal.metadata ?? {};\n if (metadata['code'] === 'instance_not_ready' || metadata['code'] === 'instance_build_failed') {\n this.#handleNotReady(metadata, signal.reason ?? '');\n } else {\n console.warn(`[synap] server throttle signal: ${signal.reason ?? ''}`);\n }\n return;\n }\n if (signal?.signal_type === 'closing') {\n void this.#handleDisconnect('server_signal_closing');\n } else if (signal?.signal_type === 'error') {\n // Logged, as Python logs it, and not fatal: the server sends it for one\n // refused event or session_start and keeps the stream open. Until 0.5.18\n // it was dropped here without a word.\n console.warn(`[synap] server error signal (stream stays open): ${signal.reason ?? ''}`);\n }\n }\n\n /**\n * The server refused work: the instance is still being built.\n *\n * The refused event is still in `#unacked` (the server neither recorded nor\n * acknowledged it), so nothing is dropped here. This does not close the\n * stream and does not reconnect: a reconnect would replay the same events\n * into the same refusal for the whole build. One probe loop waits\n * `retry_after_seconds` (clamped, jittered), replays the held events and,\n * once the server accepts them, resumes normally. Mirrors Python's\n * `_handle_not_ready`.\n *\n * Logged once per build, not once per event: replaying N held events draws N\n * refusals and a warning each would bury the log.\n */\n #handleNotReady(metadata: Record<string, string>, reason: string): void {\n const code = metadata['code'] || 'instance_not_ready';\n const failed = code === 'instance_build_failed';\n const retry = Number(metadata['retry_after_seconds']);\n this.#notReady = {\n retryAfterSeconds: Number.isFinite(retry) ? Math.trunc(retry) : NOT_READY_MAX_WAIT_MS / 1000,\n instanceId: metadata['instance_id'] || this.#credentials.instanceId,\n state: metadata['state'] || (failed ? 'failed' : 'building'),\n message: reason,\n code,\n ...(failed ? { hint: metadata['hint'] || '', attempts: metadata['attempts'] || '' } : {}),\n };\n this.#notReadyResignalled = true;\n this.#heldBacklog = true;\n if (failed) {\n const key = `${this.#notReady.instanceId}|${metadata['series'] || ''}`;\n if (!this.#buildFailedWarned.has(key)) {\n this.#buildFailedWarned.add(key);\n const hint = this.#notReady.hint;\n console.warn(\n `[synap] instance ${this.#notReady.instanceId}: its memory architecture build FAILED, `\n + `so the server is refusing events. ${this.#unacked.size} event(s) are held in `\n + `memory (up to ${NOT_READY_MAX_HELD}; beyond that the oldest are dropped and the `\n + 'count is reported). Waiting alone will not fix this. '\n + `${hint ? `To recover: ${hint}` : 'Rebuild the instance.'} The SDK checks again `\n + `about every ${Math.round(BUILD_FAILED_PROBE_INTERVAL_MS / 1000)}s and resumes by `\n + `itself after a successful rebuild. Server said: ${reason}`,\n );\n }\n } else if (!this.#notReadyWarned) {\n this.#notReadyWarned = true;\n console.warn(\n `[synap] instance ${this.#notReady.instanceId} is still building its memory `\n + `architecture; the server is refusing events for now. ${this.#unacked.size} `\n + 'event(s) are held in memory and will be re-sent automatically when it is '\n + `ready (next check in about ${Math.round(this.#notReadyWait() / 1000)}s). Up to `\n + `${NOT_READY_MAX_HELD} events are held; beyond that the oldest are dropped and `\n + `the count is reported. Server said: ${reason}`,\n );\n }\n if (!this.#notReadyRunning) {\n this.#notReadyRunning = true;\n void this.#notReadyProbeLoop();\n }\n }\n\n /** Milliseconds until the next probe: the hint, clamped, with jitter. */\n #notReadyWait(): number {\n if (this.#notReady?.code === 'instance_build_failed') {\n return BUILD_FAILED_PROBE_INTERVAL_MS + Math.random() * BUILD_FAILED_PROBE_JITTER_MS;\n }\n const hintMs = (this.#notReady?.retryAfterSeconds ?? 0) * 1000;\n const base = Math.min(Math.max(hintMs, NOT_READY_MIN_WAIT_MS), NOT_READY_MAX_WAIT_MS);\n const jitter = 1 - NOT_READY_JITTER + Math.random() * 2 * NOT_READY_JITTER;\n return Math.max(base * jitter, NOT_READY_MIN_WAIT_MS);\n }\n\n /** Cancellable on disconnect, and never the only thing holding the process open. */\n #notReadySleep(ms: number): Promise<void> {\n if (this.#options.sleep) return this.#options.sleep(ms);\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => { this.#notReadyWake = null; resolve(); }, ms);\n if (typeof timer.unref === 'function') timer.unref();\n this.#notReadyWake = () => { clearTimeout(timer); this.#notReadyWake = null; resolve(); };\n });\n }\n\n async #notReadyProbeLoop(): Promise<void> {\n try {\n while (!this.#shutdownRequested) {\n await this.#notReadySleep(this.#notReadyWait());\n if (this.#shutdownRequested) return;\n // The reconnect path replays everything. If the build is still running\n // the next refusal restarts this loop, and the warning has been given.\n if (!this.isConnected || this.#call === null) return;\n this.#notReadyResignalled = false;\n // Fresh timestamps, so the age limit cannot evict a held event in the\n // moment between the build finishing and its ack.\n const now = Date.now();\n for (const held of this.#unacked.values()) held.queuedAt = now;\n // Emptied only after the replay has written every event it covers.\n const covered = new Set(this.#unacked.keys());\n for (const held of [...this.#unacked.values()]) {\n this.#write({ conversation_event: { ...held.event } });\n }\n this.#notReadyUnwritten = this.#notReadyUnwritten.filter(\n (e) => !covered.has(String(e.event_id)));\n await this.#notReadySleep(NOT_READY_PROBE_GRACE_MS);\n if (this.#shutdownRequested) return;\n if (!this.#notReadyResignalled) {\n // Accepted. New sends go straight out from here; write what was held\n // after the replay or it would wait for a reconnect.\n const instanceId = this.#notReady?.instanceId ?? this.#credentials.instanceId;\n this.#notReady = null;\n const late = this.#notReadyUnwritten;\n this.#notReadyUnwritten = [];\n for (const event of late) {\n if (!this.#unacked.has(String(event.event_id))) continue; // dropped at the cap\n this.#write({ conversation_event: { ...event } });\n }\n this.#notReadyWarned = false;\n this.#buildFailedWarned.clear();\n console.info(\n `[synap] instance ${instanceId} is ready; held events were accepted and `\n + 'the stream is back to normal',\n );\n return;\n }\n }\n } finally {\n this.#notReady = null;\n this.#notReadyUnwritten = [];\n this.#notReadyRunning = false;\n if (this.#notReadyDropped > 0) {\n console.warn(\n `[synap] while the instance was building, ${this.#notReadyDropped} held event(s) `\n + `were DROPPED (oldest first) because the in-memory limit of ${NOT_READY_MAX_HELD} `\n + 'was reached. They were not sent.',\n );\n this.#notReadyDropped = 0;\n }\n }\n }\n\n #handleBundle(bundle: Record<string, unknown>): void {\n const bundleType = String(bundle['bundle_type'] ?? '') || 'anticipation';\n const conversationId = String(bundle['anticipation_conversation_id'] ?? '');\n\n if (bundleType !== UNCACHEABLE_BUNDLE_TYPE) this.#store(bundle, bundleType, conversationId);\n\n if (bundleType === 'compaction_update' && conversationId !== '') {\n // Python also deletes this conversation's `compacted_full` /\n // `compacted_context` entries from its separate CacheManager. This SDK\n // has no such cache, and calling dropConversation() here would delete\n // the bundle just stored above, so there is nothing to invalidate.\n this.#options.onCompactionUpdate?.(conversationId, bundle);\n }\n\n // Fires for every type, after storing, matching Python's ordering.\n this.#options.onContext?.(bundle);\n }\n\n #store(bundle: Record<string, unknown>, bundleType: string, conversationId: string): void {\n const itemsByType: Record<string, Array<Record<string, unknown>>> = {};\n for (const [type, list] of Object.entries(bundle['items_by_type'] ?? {})) {\n const items = (list as { items?: Array<Record<string, unknown>> })?.items;\n itemsByType[type] = items ?? [];\n }\n\n const ttlHint = Number(bundle['ttl_hint_seconds'] ?? 0);\n this.#cache.store({\n bundleId: String(bundle['bundle_id'] ?? ''),\n // The cache keys on ONE entity. User id wins when present, so a bundle\n // pushed for a user cannot be served to a different user in the same\n // customer; falling back to customer id keeps org-scope bundles usable.\n entityId:\n String(bundle['anticipation_user_id'] ?? '') ||\n String(bundle['anticipation_customer_id'] ?? '') ||\n null,\n conversationId: conversationId || null,\n // The rung the server retrieved this bundle at. Absent from anything an\n // older server sent, and absent reads as \"named no rung\" rather than as\n // \"matches anything\".\n scopeRung: String(bundle['anticipation_scope_rung'] ?? '') || null,\n itemsByType,\n // 0 means \"use the SDK default\"; anything else is floored at 60s.\n ttlHintSeconds: ttlHint > 0 ? Math.max(ttlHint, MIN_TTL_SECONDS) : null,\n bundleType,\n searchQueries: [\n ...((bundle['search_queries'] as string[] | undefined) ?? []),\n ...((bundle['search_keywords'] as string[] | undefined) ?? []),\n ],\n });\n }\n\n /**\n * End the stream because the server refused it for credits.\n *\n * Reconnecting cannot clear a credit refusal, so the stream closes and the\n * typed error is kept on `lastError` for the application to read. Mirrors\n * Python's `_handle_credit_stop`.\n */\n #handleCreditStop(error: SynapError): void {\n this.#lastError = error;\n this.#shutdownRequested = true;\n this.#stopHeartbeat();\n this.#closeCall();\n this.#setState('disconnected');\n }\n\n async #handleDisconnect(_reason: string): Promise<void> {\n if (this.#shutdownRequested) return;\n\n this.#closeCall();\n this.#setState('reconnecting');\n\n if (this.#reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {\n this.#setState('disconnected');\n return;\n }\n\n // Jittered exponential backoff. The jitter matters with many SDK instances\n // behind one deploy: without it they all retry in lockstep.\n const delay = Math.min(\n BACKOFF_BASE_MS * 2 ** this.#reconnectAttempts + Math.random() * 1_000,\n BACKOFF_MAX_MS,\n );\n this.#reconnectAttempts += 1;\n\n await this.#sleep(delay);\n if (this.#shutdownRequested) return;\n try {\n await this.#establish();\n } catch (error) {\n if (isCreditStop(error)) {\n this.#handleCreditStop(error as SynapError);\n return;\n }\n void this.#handleDisconnect('reconnect_failed');\n }\n }\n\n #startHeartbeat(): void {\n this.#heartbeatTimer = setInterval(() => {\n if (!this.isConnected || this.#call === null) return;\n const now = Date.now();\n\n if (now - this.#lastPongAt > HEARTBEAT_TIMEOUT_MS) {\n this.#missedHeartbeats += 1;\n if (this.#missedHeartbeats >= MAX_MISSED_HEARTBEATS) {\n void this.#handleDisconnect('heartbeat_timeout');\n return;\n }\n }\n try {\n this.#call.write({ heartbeat_ping: { timestamp_ms: now } });\n } catch {\n void this.#handleDisconnect('heartbeat_write_error');\n }\n }, HEARTBEAT_INTERVAL_MS);\n // Never hold the process open on the heartbeat alone: a CLI that finishes\n // its work should exit, not hang for 30s.\n this.#heartbeatTimer.unref?.();\n }\n\n #stopHeartbeat(): void {\n if (this.#heartbeatTimer !== null) {\n clearInterval(this.#heartbeatTimer);\n this.#heartbeatTimer = null;\n }\n }\n\n #closeCall(): void {\n try {\n this.#call?.end();\n } catch {\n /* already torn down */\n }\n this.#call = null;\n }\n\n #setState(state: StreamState): void {\n this.#state = state;\n this.#options.onStateChange?.(state);\n }\n}\n"],"mappings":";;;;;;;AAaO,IAAM,YAAY;AAElB,IAAM,yBAAyB;AAAA,EACpC,UAAU;AAAA,IACR,SAAS;AAAA,MACP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,aAAmB;AACjB,QAAI;AACF,WAAK,OAAO,IAAI;AAAA,IAClB,QAAQ;AAAA,IAER;AACA,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,UAAU,OAA0B;AAClC,SAAK,SAAS;AACd,SAAK,SAAS,gBAAgB,KAAK;AAAA,EACrC;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/grpc/descriptor.ts","../src/grpc/outbox-journal.ts","../src/grpc/stream-client.ts"],"sourcesContent":["/**\n * GENERATED FILE. Do not edit by hand.\n *\n * Source: synap/proto/synap_service.proto\n * Generator: synap/sdk/scripts/gen_proto_descriptor.mjs\n * Proto SHA: 2f2b7989ea808cf5\n *\n * The proto is inlined as a JSON descriptor rather than loaded from disk so\n * that bundlers and Vercel file tracing cannot lose it. Regenerate with\n * `npm run sync-behavior` in synap/sdk/js.\n */\n\n/** sha256 (first 16 hex chars) of the proto this descriptor was built from. */\nexport const PROTO_SHA = '2f2b7989ea808cf5';\n\nexport const SYNAP_PROTO_DESCRIPTOR = {\n \"nested\": {\n \"synap\": {\n \"nested\": {\n \"v1\": {\n \"nested\": {\n \"SynapService\": {\n \"methods\": {\n \"Listen\": {\n \"requestType\": \"StreamEvent\",\n \"requestStream\": true,\n \"responseType\": \"StreamResponse\",\n \"responseStream\": true\n },\n \"IngestTelemetry\": {\n \"requestType\": \"TelemetryEvent\",\n \"requestStream\": true,\n \"responseType\": \"TelemetryAck\"\n }\n }\n },\n \"StreamEvent\": {\n \"oneofs\": {\n \"payload\": {\n \"oneof\": [\n \"conversation_event\",\n \"heartbeat_ping\",\n \"session_control\",\n \"context_used\",\n \"context_assembled\"\n ]\n }\n },\n \"fields\": {\n \"conversation_event\": {\n \"type\": \"ConversationEvent\",\n \"id\": 1\n },\n \"heartbeat_ping\": {\n \"type\": \"HeartbeatPing\",\n \"id\": 2\n },\n \"session_control\": {\n \"type\": \"SessionControl\",\n \"id\": 3\n },\n \"context_used\": {\n \"type\": \"ContextUsedEvent\",\n \"id\": 4\n },\n \"context_assembled\": {\n \"type\": \"ContextAssembledEvent\",\n \"id\": 5\n }\n }\n },\n \"ContextUsedEvent\": {\n \"fields\": {\n \"bundle_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"served_item_ids\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 5\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 6\n },\n \"scope\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"source_bundle_ids\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 8\n },\n \"query_count\": {\n \"type\": \"int32\",\n \"id\": 9\n }\n }\n },\n \"ContextAssembledEvent\": {\n \"fields\": {\n \"correlation_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"final_item_ids\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 5\n },\n \"final_total_tokens\": {\n \"type\": \"int32\",\n \"id\": 6\n },\n \"compaction_id\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"recent_turn_count\": {\n \"type\": \"int32\",\n \"id\": 8\n },\n \"compaction_end_timestamp\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"assembly_source\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"assembly_duration_ms\": {\n \"type\": \"int32\",\n \"id\": 11\n },\n \"cache_hit\": {\n \"type\": \"bool\",\n \"id\": 12\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 13\n },\n \"sdk_version\": {\n \"type\": \"string\",\n \"id\": 14\n }\n }\n },\n \"ConversationEvent\": {\n \"fields\": {\n \"event_type\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"role\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"content\": {\n \"type\": \"string\",\n \"id\": 5\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 6\n },\n \"session_id\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"metadata\": {\n \"keyType\": \"string\",\n \"type\": \"string\",\n \"id\": 8\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 9\n },\n \"tool_name\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"tool_args_json\": {\n \"type\": \"string\",\n \"id\": 11\n },\n \"tool_result_json\": {\n \"type\": \"string\",\n \"id\": 15\n },\n \"tool_call_id\": {\n \"type\": \"string\",\n \"id\": 16\n },\n \"search_queries\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 12\n },\n \"context_types\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 13\n },\n \"scope\": {\n \"keyType\": \"string\",\n \"type\": \"string\",\n \"id\": 14\n },\n \"event_id\": {\n \"type\": \"string\",\n \"id\": 17\n },\n \"sent_at_ms\": {\n \"type\": \"int64\",\n \"id\": 18\n }\n }\n },\n \"HeartbeatPing\": {\n \"fields\": {\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 1\n }\n }\n },\n \"SessionControl\": {\n \"fields\": {\n \"action\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"session_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 5\n }\n }\n },\n \"StreamResponse\": {\n \"oneofs\": {\n \"payload\": {\n \"oneof\": [\n \"context_bundle\",\n \"heartbeat_pong\",\n \"signal\",\n \"event_ack\",\n \"conversation_state\"\n ]\n }\n },\n \"fields\": {\n \"context_bundle\": {\n \"type\": \"ContextBundleProto\",\n \"id\": 1\n },\n \"heartbeat_pong\": {\n \"type\": \"HeartbeatPong\",\n \"id\": 2\n },\n \"signal\": {\n \"type\": \"StreamSignal\",\n \"id\": 3\n },\n \"event_ack\": {\n \"type\": \"EventAck\",\n \"id\": 4\n },\n \"conversation_state\": {\n \"type\": \"ConversationState\",\n \"id\": 5\n }\n }\n },\n \"ConversationState\": {\n \"fields\": {\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"message_count\": {\n \"type\": \"int64\",\n \"id\": 2\n }\n }\n },\n \"EventAck\": {\n \"fields\": {\n \"event_ids\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 1\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 2\n }\n }\n },\n \"HeartbeatPong\": {\n \"fields\": {\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 1\n }\n }\n },\n \"StreamSignal\": {\n \"fields\": {\n \"signal_type\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"reason\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"metadata\": {\n \"keyType\": \"string\",\n \"type\": \"string\",\n \"id\": 3\n }\n }\n },\n \"ContextBundleProto\": {\n \"fields\": {\n \"bundle_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"decision_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"items_by_type\": {\n \"keyType\": \"string\",\n \"type\": \"ContextItemList\",\n \"id\": 3\n },\n \"total_tokens\": {\n \"type\": \"int32\",\n \"id\": 4\n },\n \"token_budget\": {\n \"type\": \"int32\",\n \"id\": 5\n },\n \"budget_exceeded\": {\n \"type\": \"bool\",\n \"id\": 6\n },\n \"retrieval_mode\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"sources_queried\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 8\n },\n \"degradation_level\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"warnings\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 10\n },\n \"created_at\": {\n \"type\": \"string\",\n \"id\": 11\n },\n \"retrieval_time_ms\": {\n \"type\": \"int32\",\n \"id\": 12\n },\n \"cache_hit\": {\n \"type\": \"bool\",\n \"id\": 13\n },\n \"search_queries\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 14\n },\n \"anticipation_user_id\": {\n \"type\": \"string\",\n \"id\": 15\n },\n \"anticipation_customer_id\": {\n \"type\": \"string\",\n \"id\": 16\n },\n \"anticipation_conversation_id\": {\n \"type\": \"string\",\n \"id\": 17\n },\n \"search_keywords\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 18\n },\n \"bundle_type\": {\n \"type\": \"string\",\n \"id\": 19\n },\n \"conversation_context\": {\n \"type\": \"ConversationContextProto\",\n \"id\": 20\n },\n \"bundle_confidence\": {\n \"type\": \"float\",\n \"id\": 21\n },\n \"origin_pattern_id\": {\n \"type\": \"string\",\n \"id\": 22\n },\n \"ttl_hint_seconds\": {\n \"type\": \"int32\",\n \"id\": 23\n },\n \"anticipation_scope_rung\": {\n \"type\": \"string\",\n \"id\": 24\n }\n }\n },\n \"ConversationContextProto\": {\n \"fields\": {\n \"summary\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"current_state_json\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"key_extractions_json\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"recent_turns\": {\n \"rule\": \"repeated\",\n \"type\": \"RecentTurnProto\",\n \"id\": 4\n },\n \"compaction_id\": {\n \"type\": \"string\",\n \"id\": 5\n },\n \"compacted_at\": {\n \"type\": \"string\",\n \"id\": 6\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"compacted_message_count\": {\n \"type\": \"int32\",\n \"id\": 8\n },\n \"total_message_count\": {\n \"type\": \"int32\",\n \"id\": 9\n },\n \"context_block\": {\n \"type\": \"string\",\n \"id\": 10\n }\n }\n },\n \"RecentTurnProto\": {\n \"fields\": {\n \"role\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"content\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"timestamp\": {\n \"type\": \"string\",\n \"id\": 3\n }\n }\n },\n \"ContextItemList\": {\n \"fields\": {\n \"items\": {\n \"rule\": \"repeated\",\n \"type\": \"ContextItemProto\",\n \"id\": 1\n }\n }\n },\n \"ContextItemProto\": {\n \"oneofs\": {\n \"_rank_score\": {\n \"oneof\": [\n \"rank_score\"\n ]\n }\n },\n \"fields\": {\n \"item_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"content\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"context_type\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"source\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"similarity_score\": {\n \"type\": \"float\",\n \"id\": 5\n },\n \"relevance_score\": {\n \"type\": \"float\",\n \"id\": 6\n },\n \"confidence\": {\n \"type\": \"float\",\n \"id\": 7\n },\n \"scope\": {\n \"type\": \"string\",\n \"id\": 8\n },\n \"entity_id\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"created_at\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"event_date\": {\n \"type\": \"string\",\n \"id\": 11\n },\n \"valid_until\": {\n \"type\": \"string\",\n \"id\": 12\n },\n \"temporal_category\": {\n \"type\": \"string\",\n \"id\": 13\n },\n \"temporal_confidence\": {\n \"type\": \"float\",\n \"id\": 14\n },\n \"said_at\": {\n \"type\": \"string\",\n \"id\": 15\n },\n \"rank_score\": {\n \"type\": \"double\",\n \"id\": 16,\n \"options\": {\n \"proto3_optional\": true\n }\n },\n \"questions\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 17\n },\n \"date_prefix\": {\n \"type\": \"string\",\n \"id\": 18\n }\n }\n },\n \"TelemetryEvent\": {\n \"fields\": {\n \"event_type\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"instance_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"client_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"correlation_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 5\n },\n \"latency_ms\": {\n \"type\": \"int32\",\n \"id\": 6\n },\n \"status\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"error_code\": {\n \"type\": \"string\",\n \"id\": 8\n },\n \"scope\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"cache_status\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"attempt\": {\n \"type\": \"int32\",\n \"id\": 11\n },\n \"http_method\": {\n \"type\": \"string\",\n \"id\": 12\n },\n \"http_path\": {\n \"type\": \"string\",\n \"id\": 13\n },\n \"http_status_code\": {\n \"type\": \"int32\",\n \"id\": 14\n },\n \"metadata\": {\n \"keyType\": \"string\",\n \"type\": \"string\",\n \"id\": 15\n },\n \"sdk_version\": {\n \"type\": \"string\",\n \"id\": 16\n },\n \"batch_id\": {\n \"type\": \"string\",\n \"id\": 17\n }\n }\n },\n \"TelemetryAck\": {\n \"fields\": {\n \"status\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"events_received\": {\n \"type\": \"int32\",\n \"id\": 2\n }\n }\n }\n }\n }\n }\n }\n }\n} as const;\n","/**\n * Disk backing for the stream client's outbound buffers.\n *\n * The send queue and the unacknowledged map already survive a dropped\n * connection. Neither survives the process: both live in memory, so a hard\n * kill between a turn being recorded and the server acknowledging it loses\n * that turn with no trace anywhere.\n *\n * Every change to either buffer appends one line here, and the next start\n * reads the file back before the first event goes out. Mirrors Python's\n * `transport/outbox_journal.py` line for line, including the file format, so\n * a Python process and a Node process on the same storage root read each\n * other's journals.\n *\n * **Why a log and not a snapshot.** Rewriting both buffers on every change is\n * O(depth) per event and leaves a window between the change and the write.\n * Debouncing the write widens that window on purpose, which is the opposite of\n * the point. An append is one small line and happens before the caller is told\n * the event was accepted.\n *\n * **Why synchronous.** `appendFileSync`, not the promise form. An async write\n * still pending when the process dies is a write that did not happen, and this\n * file exists precisely for the case where the process dies.\n *\n * **Where it does not run.** Workers, edge runtimes and the browser have no\n * filesystem. `node:fs` is loaded through a guarded dynamic require and, when\n * it is not there, the journal disables itself and the SDK behaves exactly as\n * it did before: buffered events survive a reconnect and not a restart. That\n * is a real gap against Python and it is declared in SDK_PARITY.md rather than\n * papered over, because those runtimes have no disk to offer.\n */\n\n/** The ops, one character each because they are written once per event. */\nconst OP_QUEUED = 'q';\nconst OP_UNACKED = 'u';\nconst OP_ACKED = 'a';\nconst OP_DROPPED = 'd';\n\n/** Rewrite the file once it holds this many lines. The buffers are bounded at\n * 100 entries each, so past a few hundred lines it is mostly tombstones. */\nconst COMPACT_AT_LINES = 500;\n\ninterface NodeFs {\n appendFileSync: (p: string, data: string, enc: string) => void;\n readFileSync: (p: string, enc: string) => string;\n writeFileSync: (p: string, data: string, enc: string) => void;\n mkdirSync: (p: string, opts: { recursive: boolean }) => void;\n existsSync: (p: string) => boolean;\n renameSync: (a: string, b: string) => void;\n unlinkSync: (p: string) => void;\n}\n\n/**\n * `node:fs`, resolved once for the process.\n *\n * It has to be a dynamic `import()`, because this package ships an ESM build\n * and a CJS one and is also used on edge runtimes: a static import would make\n * the edge bundle fail to load over a module it can never use, and `require`\n * is not defined under ESM, which is what the test runner uses. A dynamic\n * import works in all three and simply rejects where there is no `node:fs`.\n *\n * Resolving it is therefore async, but every write here has to be synchronous\n * (an async write still pending when the process dies is a write that did not\n * happen). So it is resolved ONCE, up front, by `OutboxJournal.init()`, which\n * the stream client awaits inside `connect()` before any event can flow. After\n * that the module object is in hand and the appends are plain sync calls.\n */\nlet _fs: NodeFs | null = null;\nlet _fsResolved = false;\nlet _fsPending: Promise<void> | null = null;\n\nasync function resolveFs(): Promise<void> {\n if (_fsResolved) return;\n // Share one in-flight import. Two clients constructed at once would\n // otherwise each start their own, and the second could observe `_fs` still\n // null and disable itself for the life of the process.\n if (_fsPending === null) {\n _fsPending = (async () => {\n try {\n _fs = (await import('node:fs')) as unknown as NodeFs;\n } catch {\n _fs = null; // edge runtime, worker, browser\n }\n _fsResolved = true;\n })();\n }\n await _fsPending;\n}\n\nexport interface JournalEvent { event_id?: string; [k: string]: unknown }\n\n/**\n * The stream protocol carries inline image bytes under this metadata key. The\n * placeholder in `content` is enough for an interrupted event to be replayed,\n * while retaining the bytes would put customer images on disk.\n */\nfunction withoutContentParts(event: JournalEvent): JournalEvent {\n const metadata = event['metadata'];\n if (metadata === null || typeof metadata !== 'object' || Array.isArray(metadata)\n || !Object.prototype.hasOwnProperty.call(metadata, 'synap_content_parts')) {\n return event;\n }\n const cleanMetadata = { ...(metadata as Record<string, unknown>) };\n delete cleanMetadata['synap_content_parts'];\n return { ...event, metadata: cleanMetadata };\n}\n\n/**\n * `~/.synap`, the same root Python's SDK uses, so a Node process and a Python\n * process on one machine read each other's journals. Empty string where there\n * is no home directory to ask for, which disables the journal.\n */\nexport function defaultOutboxRoot(): string {\n try {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env;\n const home = env?.['SYNAP_STORAGE_PATH'] ?? env?.['HOME'] ?? env?.['USERPROFILE'];\n if (home !== undefined && home !== '') {\n return env?.['SYNAP_STORAGE_PATH'] !== undefined && env['SYNAP_STORAGE_PATH'] !== ''\n ? env['SYNAP_STORAGE_PATH'] : `${home}/.synap`;\n }\n } catch { /* no process object: edge runtime */ }\n return '';\n}\n\nexport class OutboxJournal {\n readonly path: string;\n #fs: NodeFs | null;\n #lines = 0;\n #disabled = false;\n\n /**\n * @param root Directory the journal lives under. One file per instance id,\n * because two clients on one instance share a stream in the\n * registry and so the events are the instance's, not the\n * object's.\n */\n /**\n * Resolve `node:fs` once for the process. The stream client awaits this in\n * `connect()` before any event can flow, so by the time anything is written\n * the module is in hand and every append is a plain synchronous call. An\n * async write still pending when the process dies is a write that did not\n * happen, and this file exists for exactly that case.\n */\n static async init(): Promise<void> {\n await resolveFs();\n }\n\n constructor(root: string, instanceId: string, fsImpl?: NodeFs | null) {\n // An empty root means there is nowhere to put this: no home directory, or\n // the caller turned it off. Without this guard the path became\n // `/outbox/<id>.jsonl`, which is a write to the filesystem root.\n this.path = root === '' ? '' : `${root}/outbox/${instanceId}.jsonl`;\n this.#fs = fsImpl !== undefined ? fsImpl : _fs;\n if (this.#fs === null || this.path === '') this.#disabled = true;\n }\n\n get enabled(): boolean { return !this.#disabled; }\n\n // ------------------------------------------------------------------ writes\n\n recordQueued(event: JournalEvent): void {\n this.#append({ op: OP_QUEUED, e: withoutContentParts(event) });\n }\n recordUnacked(event: JournalEvent): void {\n this.#append({ op: OP_UNACKED, e: withoutContentParts(event) });\n }\n recordAcked(id: string): void { this.#append({ op: OP_ACKED, id }); }\n\n /** An event the buffers gave up on. It does not come back on restart either:\n * replaying what the depth or age bound deliberately evicted would quietly\n * undo the bound that evicted it. */\n recordDropped(id: string | undefined): void {\n if (id === undefined || id === '') return;\n this.#append({ op: OP_DROPPED, id });\n }\n\n // ------------------------------------------------------------------- reads\n\n /**\n * Replay the file into `{queued, unacked}`, oldest first.\n *\n * A partial last line from a kill mid-append stops the read there. What came\n * before it is the prefix that was durably written; a torn line is an event\n * the caller was never told had been accepted.\n */\n load(): { queued: JournalEvent[]; unacked: JournalEvent[] } {\n const empty = { queued: [], unacked: [] };\n if (this.#disabled || this.#fs === null) return empty;\n let text: string;\n try {\n if (!this.#fs.existsSync(this.path)) return empty;\n text = this.#fs.readFileSync(this.path, 'utf8');\n } catch {\n return empty;\n }\n const queued = new Map<string, JournalEvent>();\n const unacked = new Map<string, JournalEvent>();\n let lines = 0;\n for (const raw of text.split('\\n')) {\n const line = raw.trim();\n if (line === '') continue;\n let rec: { op?: string; id?: string; e?: JournalEvent };\n try {\n rec = JSON.parse(line) as typeof rec;\n } catch {\n break; // torn last line; everything before it stands\n }\n lines += 1;\n const id = rec.op === OP_QUEUED || rec.op === OP_UNACKED\n ? rec.e?.event_id : rec.id;\n if (id === undefined || id === '') continue;\n if (rec.op === OP_QUEUED) {\n queued.set(id, rec.e as JournalEvent);\n } else if (rec.op === OP_UNACKED) {\n // It left the queue to be written, so it is no longer queued. Without\n // this a reconnect-then-kill replays it from both lists.\n queued.delete(id);\n unacked.set(id, rec.e as JournalEvent);\n } else if (rec.op === OP_ACKED || rec.op === OP_DROPPED) {\n queued.delete(id);\n unacked.delete(id);\n }\n }\n this.#lines = lines;\n return { queued: [...queued.values()], unacked: [...unacked.values()] };\n }\n\n // ------------------------------------------------------------- maintenance\n\n /**\n * Rewrite the file to hold exactly what the buffers hold now.\n *\n * Written beside the target and renamed over it, because rename is atomic: a\n * kill during a compaction leaves either the whole old file or the whole new\n * one, never a half-written mix.\n */\n compact(queued: JournalEvent[], unacked: JournalEvent[]): void {\n if (this.#disabled || this.#fs === null) return;\n if (queued.length === 0 && unacked.length === 0) { this.clear(); return; }\n try {\n this.#mkdir();\n const body = [\n ...unacked.map((e) => JSON.stringify({ op: OP_UNACKED, e: withoutContentParts(e) })),\n ...queued.map((e) => JSON.stringify({ op: OP_QUEUED, e: withoutContentParts(e) })),\n ].join('\\n') + '\\n';\n const tmp = `${this.path}.${Date.now()}.tmp`;\n this.#fs.writeFileSync(tmp, body, 'utf8');\n this.#fs.renameSync(tmp, this.path);\n this.#lines = queued.length + unacked.length;\n } catch {\n // Never break a turn or a close over bookkeeping.\n }\n }\n\n /** Nothing is outstanding, so there is nothing to replay. */\n clear(): void {\n if (this.#disabled || this.#fs === null) return;\n try { this.#fs.unlinkSync(this.path); } catch { /* already gone */ }\n this.#lines = 0;\n }\n\n get needsCompaction(): boolean { return this.#lines >= COMPACT_AT_LINES; }\n\n // ---------------------------------------------------------------- internal\n\n #mkdir(): void {\n const dir = this.path.slice(0, this.path.lastIndexOf('/'));\n this.#fs?.mkdirSync(dir, { recursive: true });\n }\n\n #append(record: Record<string, unknown>): void {\n if (this.#disabled || this.#fs === null) return;\n try {\n this.#mkdir();\n this.#fs.appendFileSync(this.path, `${JSON.stringify(record)}\\n`, 'utf8');\n this.#lines += 1;\n } catch (err) {\n // One warning, then stay quiet: a read-only or full filesystem would\n // otherwise log once per event for the life of the process.\n console.warn(\n `[synap] outbox journal write failed (${String(err)}); buffered events `\n + 'will not survive a restart from here on',\n );\n this.#disabled = true;\n }\n }\n}\n","/**\n * Bidirectional gRPC stream client for the Synap anticipation channel.\n *\n * Mirrors Python's `GRPCTransport` and the synap-vercel-adk client:\n * - `/synap.v1.SynapService/Listen`, StreamEvent in, StreamResponse out\n * - Auth via `authorization: Bearer <key>` plus `x-client-id` / `x-instance-id`\n * - 30s heartbeat, exponential-backoff reconnect\n * - Server pushes ContextBundleProto, which lands in the AnticipationCache\n *\n * Node-only, and reached exclusively through a lazy `import()` so that merely\n * importing the SDK on Edge or in a Worker stays safe. grpc-js is built on\n * `node:http2`/`node:net`/`node:tls`; a static import fails the BUILD there.\n *\n * The proto arrives as an inlined descriptor (see ./descriptor.ts) rather than\n * being read from disk, so bundlers and Vercel file tracing cannot lose it.\n */\n\nimport type { AnticipationCache } from '../context/anticipation-cache.js';\nimport { SYNAP_PROTO_DESCRIPTOR } from './descriptor.js';\nimport { OutboxJournal, defaultOutboxRoot } from './outbox-journal.js';\nimport { newCorrelationId } from '../util/correlation.js';\nimport { InsufficientCreditsError, RateLimitError, type SynapError } from '../errors.js';\n\nexport type StreamState =\n | 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'closed';\n\n/**\n * The ONLY bundle type the cache refuses.\n *\n * NOTE: this deliberately differs from the synap-vercel-adk stream client,\n * which caches an allowlist of `anticipation` and `user_summary` and drops\n * compaction updates. Python's `_handle_anticipated_bundle` stores everything\n * except `reactive`, and Python is the reference implementation, so an\n * allowlist here would silently cache less than the pip SDK does.\n *\n * Reactive bundles are excluded because they answer a fetch that already\n * happened; caching one serves a stale answer to a different question.\n */\nconst UNCACHEABLE_BUNDLE_TYPE = 'reactive';\n\n// Mirrors the Python GRPCTransport constants.\nconst MAX_RECONNECT_ATTEMPTS = 10;\nconst BACKOFF_BASE_MS = 1_000;\nconst BACKOFF_MAX_MS = 30_000;\nconst HEARTBEAT_INTERVAL_MS = 30_000;\nconst HEARTBEAT_TIMEOUT_MS = 10_000;\nconst MAX_MISSED_HEARTBEATS = 3;\n\n// The outbound buffer, same shape and same numbers as Python's transport\n// (SEND_QUEUE_MAX_DEPTH / SEND_QUEUE_MAX_AGE). Events written while the stream\n// is down were silently dropped here: `#write` returned early and said nothing,\n// so a reconnect lost every turn that happened during it.\nconst SEND_QUEUE_MAX_DEPTH = 100;\n// How long disconnect() waits for the server to finish reading after the\n// half-close. Matches Python's CLOSE_GRACE.\nconst CLOSE_GRACE_MS = 2_000;\nconst SEND_QUEUE_MAX_AGE_MS = 5 * 60 * 1_000;\n\n// Cache hits reported while the stream was down (context_used), sent on\n// reconnect. Their own queue: the server acknowledges conversation events,\n// never these. Kept longer than conversation events because a late report is\n// still a correct count and a correct charge (both idempotent on instance,\n// bundle and the hit's time). Python: GRPCTransport.HIT_QUEUE_*.\nconst HIT_QUEUE_MAX_DEPTH = 500;\nconst HIT_QUEUE_MAX_AGE_MS = 30 * 60 * 1_000;\n// How long disconnect() waits for the buffer to go out. Short: a shutdown path\n// that blocks is worse than a lost event.\nconst CLOSE_FLUSH_TIMEOUT_MS = 2_000;\n// Instance still building: the server answers events with a `throttle` signal\n// whose metadata code is `instance_not_ready`. The held events are probed again\n// after the server's retry_after_seconds, clamped to this range and jittered.\n// Same numbers as Python's GRPCTransport.NOT_READY_*.\nconst NOT_READY_MIN_WAIT_MS = 5_000;\nconst NOT_READY_MAX_WAIT_MS = 120_000;\nconst NOT_READY_JITTER = 0.2;\nconst NOT_READY_PROBE_GRACE_MS = 3_000;\n// Most events held in memory while the build runs (and until they are\n// acknowledged afterwards). At the cap the OLDEST are dropped, counted and\n// reported in one warning when the hold ends. Same value as Python's\n// GRPCTransport.NOT_READY_MAX_HELD.\nexport const NOT_READY_MAX_HELD = 5_000;\n// Instance build FAILED (throttle metadata code `instance_build_failed`). Not\n// time based, so there is no hint to wait for: events are held the same way but\n// probed at this slow fixed interval plus jitter, so the stream recovers by\n// itself after a rebuild, with no reconnect loop. Same numbers as Python's\n// GRPCTransport.BUILD_FAILED_PROBE_*.\nexport const BUILD_FAILED_PROBE_INTERVAL_MS = 60_000;\nexport const BUILD_FAILED_PROBE_JITTER_MS = 10_000;\n/** The server may only SHORTEN the SDK default, never extend it past this floor. */\nconst MIN_TTL_SECONDS = 60;\n\n/** What the server said when it refused events for an unfinished build. */\nexport interface InstanceNotReadyInfo {\n retryAfterSeconds: number;\n instanceId: string;\n state: string;\n message: string;\n /** `instance_not_ready` (building) or `instance_build_failed`. */\n code: string;\n /** Recovery instruction from the server; only set for `instance_build_failed`. */\n hint?: string;\n attempts?: string;\n}\n\nexport interface StreamCredentials {\n apiKey: string;\n clientId: string;\n instanceId: string;\n}\n\nexport interface StreamClientOptions {\n host?: string;\n port?: number;\n useTls?: boolean;\n /** Injected in tests so reconnect backoff does not make the suite slow. */\n sleep?: (ms: number) => Promise<void>;\n /** How long to wait for the channel to become ready. Default 10s. */\n connectTimeoutMs?: number;\n onStateChange?: (state: StreamState) => void;\n /** Fires for every bundle, before the cache filter. Backs `listen({onContext})`. */\n onContext?: (bundle: Record<string, unknown>) => void;\n /** Fires only for `compaction_update` bundles. Backs the compaction subscriptions. */\n onCompactionUpdate?: (conversationId: string, bundle: Record<string, unknown>) => void;\n /**\n * The server's message count for a conversation, sent after it has written a\n * streamed message. See `ConversationState` in the proto.\n */\n onConversationState?: (conversationId: string, messageCount: number) => void;\n /**\n * Where the outbox journal lives, so buffered events survive a restart.\n * Defaults to `~/.synap`, the same root Python uses. `''` turns it off, and\n * it is off anyway wherever there is no filesystem.\n */\n outboxPath?: string;\n}\n\n/**\n * grpc-js status code for RESOURCE_EXHAUSTED. Hard-coded rather than read from\n * `grpc.status`, because this module is loaded before grpc-js on some paths and\n * the numbers are fixed by the gRPC spec.\n */\nconst GRPC_RESOURCE_EXHAUSTED = 8;\n\n/**\n * The credit gate refuses a call with RESOURCE_EXHAUSTED, these details, and\n * the balance and reason in trailing metadata. See\n * synap/cloud/application/credits/grpc_gate.py.\n */\nexport const CREDIT_ABORT_DETAILS = 'insufficient_credits';\n\n/**\n * Reasons that end the stream. A reconnect re-runs the same gate with the same\n * balance, so retrying only delays the answer the caller needs. Mirrors\n * `CREDIT_STOP_REASONS` in `transport/grpc_client.py`.\n */\nexport const CREDIT_STOP_REASONS = new Set([\n 'overages_disabled',\n 'trial_limit_reached',\n 'subscription_inactive',\n]);\n\nfunction metadataValue(metadata: unknown, key: string): string | null {\n if (metadata === null || typeof metadata !== 'object') return null;\n const getter = (metadata as { get?: (k: string) => unknown }).get;\n const raw = typeof getter === 'function'\n ? getter.call(metadata, key)\n : (metadata as Record<string, unknown>)[key];\n const value = Array.isArray(raw) ? raw[0] : raw;\n if (value === undefined || value === null) return null;\n const text = typeof value === 'string' ? value : String(value);\n return text === '' ? null : text;\n}\n\nfunction numberOrNull(value: string | null): number | null {\n if (value === null) return null;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\n/**\n * Translate a credit refusal into the same error HTTP would have raised.\n *\n * RESOURCE_EXHAUSTED on its own is indistinguishable from server overload, so\n * this keys on `credit-reason`: `overages_disabled` is an\n * `InsufficientCreditsError` (permanent, a paid plan at zero that has not\n * allowed usage past zero), while `trial_limit_reached` and\n * `subscription_inactive` are a `RateLimitError`. Returns null for anything\n * else, including a RESOURCE_EXHAUSTED that is not a credit refusal and a\n * reason this SDK does not know: the caller then keeps its existing behaviour\n * of treating the abort as transient. Mirrors `credit_error_from_rpc`.\n */\nexport function creditErrorFromRpc(\n error: unknown,\n correlationId: string | null = null,\n): SynapError | null {\n if (error === null || typeof error !== 'object') return null;\n if ((error as { code?: unknown }).code !== GRPC_RESOURCE_EXHAUSTED) return null;\n\n const metadata = (error as { metadata?: unknown }).metadata;\n const reason = metadataValue(metadata, 'credit-reason');\n if (reason === null || !CREDIT_STOP_REASONS.has(reason)) return null;\n\n const rawDetails = (error as { details?: unknown }).details;\n const details = typeof rawDetails === 'string' && rawDetails !== ''\n ? rawDetails\n : CREDIT_ABORT_DETAILS;\n const requestId = metadataValue(metadata, 'request-id') ?? correlationId;\n const manageUrl = metadataValue(metadata, 'credit-manage-url');\n\n if (reason === 'overages_disabled') {\n return new InsufficientCreditsError(details, {\n correlationId: requestId,\n balanceCredits: numberOrNull(metadataValue(metadata, 'credit-balance')),\n requiredCredits: numberOrNull(metadataValue(metadata, 'credit-minimum-required')),\n recoveryUrl: metadataValue(metadata, 'credit-recovery-url'),\n redeemUrl: metadataValue(metadata, 'credit-redeem-url'),\n reason,\n manageUrl,\n });\n }\n\n return new RateLimitError(details, {\n correlationId: requestId,\n reason,\n upgradeUrl: metadataValue(metadata, 'credit-upgrade-url'),\n manageUrl,\n });\n}\n\n/** True for an error this module raised from a credit refusal. */\nexport function isCreditStop(error: unknown): boolean {\n if (!(error instanceof InsufficientCreditsError) && !(error instanceof RateLimitError)) {\n return false;\n }\n const reason = (error as { reason?: unknown }).reason;\n return typeof reason === 'string' && CREDIT_STOP_REASONS.has(reason);\n}\n\ninterface DuplexCall {\n write: (msg: unknown) => void;\n on: (event: string, handler: (arg?: unknown) => void) => void;\n end: () => void;\n}\n\nexport interface ConversationEventInput {\n event_type: string;\n conversation_id?: string;\n user_id?: string;\n customer_id?: string;\n role?: string;\n content?: string;\n session_id?: string;\n metadata?: Record<string, string>;\n timestamp_ms?: number;\n /** proto: ConversationEvent.tool_name */\n tool_name?: string;\n /** proto: ConversationEvent.tool_args_json. Python sends json.dumps(tool_args). */\n tool_args_json?: string;\n /**\n * proto: ConversationEvent.tool_result_json. A result is not a message, so\n * it does not ride in `content`; a string is sent as itself rather than as a\n * quoted JSON string, matching Python.\n */\n tool_result_json?: string;\n /** proto: ConversationEvent.tool_call_id. Ties a result to its call. */\n tool_call_id?: string;\n search_queries?: string[];\n context_types?: string[];\n /** proto: ConversationEvent.scope. The conversation's rung. */\n scope?: Record<string, string>;\n /**\n * proto: ConversationEvent.event_id. Minted here when absent, and the SAME\n * id travels on every replay — that is what the server's dedupe matches, so\n * a retry cannot double a turn.\n */\n event_id?: string;\n /** proto: ConversationEvent.sent_at_ms. When we FIRST tried, not when it happened. */\n sent_at_ms?: number;\n}\n\nexport class GrpcStreamClient {\n readonly host: string;\n readonly port: number;\n readonly useTls: boolean;\n\n #state: StreamState = 'disconnected';\n #call: DuplexCall | null = null;\n #reconnectAttempts = 0;\n #lastPongAt = 0;\n #missedHeartbeats = 0;\n #heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n #shutdownRequested = false;\n // Events that could not be written because there was no stream.\n #sendQueue: Array<{ queuedAt: number; event: ConversationEventInput }> = [];\n /** Cache-hit reports waiting for a stream. See HIT_QUEUE_*. */\n #pendingHits: Array<{ queuedAt: number; event: Record<string, unknown> }> = [];\n // Events written to a live stream that the server has not acknowledged. The\n // queue above covers \"the stream was down\"; this covers the half that\n // actually loses sessions — the write succeeded, the stream broke before the\n // server processed it, and nobody knows.\n #unacked = new Map<string, { queuedAt: number; event: ConversationEventInput }>();\n // Set while the server refuses events because the instance is still being\n // built. Null otherwise. See `#handleNotReady`.\n #notReady: InstanceNotReadyInfo | null = null;\n #notReadyWarned = false;\n // `instanceId|series` pairs already warned about for a failed build.\n #buildFailedWarned = new Set<string>();\n #notReadyResignalled = false;\n #notReadyRunning = false;\n // Events held (tracked, not written) since the last replay.\n #notReadyUnwritten: ConversationEventInput[] = [];\n // Held events dropped at NOT_READY_MAX_HELD, reported when the hold ends.\n #notReadyDropped = 0;\n // True from the first refusal until the backlog is acknowledged, so the\n // normal 100-event cap does not evict held events in the gap after resume.\n #heldBacklog = false;\n #notReadyWake: (() => void) | null = null;\n // Why the stream stopped, when it stopped for a reason the caller can act on\n // (today: a credit refusal). Mirrors Python's `last_error`.\n #lastError: SynapError | null = null;\n // Disk backing for the two buffers above. They survive a dropped\n // connection and not the process; this is what the next start reads.\n readonly #journal: OutboxJournal;\n\n #grpc: typeof import('@grpc/grpc-js') | null = null;\n #ServiceStub: (new (target: string, creds: unknown, opts: unknown) => Record<string, unknown>) | null = null;\n\n readonly #credentials: StreamCredentials;\n readonly #cache: AnticipationCache;\n readonly #options: StreamClientOptions;\n readonly #sleep: (ms: number) => Promise<void>;\n readonly #connectTimeoutMs: number;\n\n constructor(\n credentials: StreamCredentials,\n cache: AnticipationCache,\n options: StreamClientOptions = {},\n ) {\n this.#credentials = credentials;\n this.#cache = cache;\n this.#options = options;\n this.host = options.host ?? 'synap-cloud-prod.maximem.ai';\n this.port = options.port ?? 443;\n this.useTls = options.useTls ?? true;\n this.#sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));\n this.#connectTimeoutMs = options.connectTimeoutMs ?? 10_000;\n this.#journal = new OutboxJournal(\n options.outboxPath ?? defaultOutboxRoot(), credentials.instanceId);\n }\n\n get currentState(): StreamState { return this.#state; }\n get isConnected(): boolean { return this.#state === 'connected'; }\n\n /**\n * The error that ended the stream, if one did.\n *\n * Set when the server refused the stream for credits, so an `onDisconnect`\n * handler can read the balance, the reason and the URL to fix it. Null for an\n * ordinary disconnect.\n */\n get lastError(): SynapError | null { return this.#lastError; }\n\n /**\n * Why the server is refusing events right now, or null.\n *\n * Set from the moment the server answers an event with an\n * `instance_not_ready` throttle until a replay of the held events is\n * accepted. The events are held, not dropped. Mirrors Python's\n * `GRPCTransport.instance_not_ready`.\n */\n get instanceNotReady(): InstanceNotReadyInfo | null {\n return this.#notReady === null ? null : { ...this.#notReady };\n }\n\n async connect(): Promise<void> {\n await this.#loadGrpc();\n // Resolve node:fs once, before anything can be written. Every journal\n // append after this is synchronous, which is the point: an async write\n // still pending when the process dies is a write that did not happen.\n await OutboxJournal.init();\n this.#shutdownRequested = false;\n this.#lastError = null;\n // Before the connection, so a previous process's unsent events are already\n // in the queue when the stream comes up and go out ahead of this process's\n // first event. That is the order they happened in.\n this.#restoreFromJournal();\n await this.#establish();\n this.#startHeartbeat();\n }\n\n /**\n * Pull a previous process's unsent events back into the send queue.\n *\n * Everything lands in the send queue, including what was unacknowledged last\n * time. The stream those events were written to is gone, so \"the server may\n * already have it\" is not a state we can resume; it has to be written again.\n * That is safe because each event carries the id it was first sent with and\n * the server drops a second sighting of it before dispatch, so an event it\n * DID process is deduplicated there rather than doubling the turn.\n */\n #restoreFromJournal(): void {\n const { queued, unacked } = this.#journal.load();\n if (queued.length === 0 && unacked.length === 0) return;\n const now = Date.now();\n // Unacknowledged first: an event written to the old stream is older than\n // anything that piled up after it died.\n for (const event of [...unacked, ...queued]) {\n this.#sendQueue.push({\n queuedAt: now, event: event as unknown as ConversationEventInput,\n });\n }\n console.warn(\n `[synap] restored ${unacked.length + queued.length} event(s) from the `\n + `previous process (${unacked.length} unacknowledged, ${queued.length} `\n + 'queued); they go out on this stream',\n );\n this.#compactJournal();\n }\n\n #compactJournal(): void {\n this.#journal.compact(\n this.#sendQueue.map((h) => h.event as unknown as Record<string, unknown>),\n [...this.#unacked.values()].map(\n (h) => h.event as unknown as Record<string, unknown>),\n );\n }\n\n async disconnect(): Promise<void> {\n // Stop the heartbeat first: it writes, and a write after the half-close\n // below is an error.\n this.#shutdownRequested = true;\n this.#stopHeartbeat();\n this.#notReadyWake?.();\n\n // What is still buffered goes out before the half-close.\n this.#flushBeforeClose();\n\n // ⚠ `end()` half-closes the write side, which is right, but on its own it\n // is not enough. It used to return immediately and the process would exit\n // while the server was still reading, so the events were written and never\n // processed. Waiting for the server to finish its side is what makes the\n // half-close mean anything.\n //\n // Bounded, because a shutdown that hangs on a dead network is its own kind\n // of broken, and whatever misses the deadline is reported rather than lost\n // silently. See `undelivered()`.\n const call = this.#call;\n if (call !== null) {\n try { call.end(); } catch { /* already torn down */ }\n await new Promise<void>((resolve) => {\n let settled = false;\n const done = () => { if (!settled) { settled = true; resolve(); } };\n const timer = setTimeout(() => {\n const left = this.undelivered();\n if (left.unacknowledged > 0 || left.queued > 0) {\n console.warn(\n `[synap] closing with ${left.queued} queued and `\n + `${left.unacknowledged} unacknowledged event(s) the server did `\n + `not confirm within ${CLOSE_GRACE_MS}ms`,\n );\n }\n done();\n }, CLOSE_GRACE_MS);\n if (typeof timer.unref === 'function') timer.unref();\n call.on('end', () => { clearTimeout(timer); done(); });\n call.on('status', () => { clearTimeout(timer); done(); });\n call.on('error', () => { clearTimeout(timer); done(); });\n });\n }\n\n this.#call = null;\n // After the flush and the half-close, so the file describes what is\n // actually still outstanding. An empty pair removes it, which is how a\n // clean shutdown leaves nothing for the next start to replay.\n this.#compactJournal();\n this.#setState('closed');\n }\n\n /**\n * What this client could not get to the server.\n *\n * Every send path returns void, so a caller had no way to tell a delivered\n * turn from a lost one. Mirrors Python's `undelivered()`.\n */\n undelivered(): { queued: number; unacknowledged: number } {\n return { queued: this.#sendQueue.length, unacknowledged: this.#unacked.size };\n }\n\n /**\n * Never fails the caller's turn, and no longer loses it either.\n *\n * A write that cannot go out is buffered and replayed on reconnect, and a\n * write that does go out is held until the server acknowledges it. Before\n * this, both cases ended at a silent `return`.\n */\n sendConversationEvent(event: ConversationEventInput): void {\n const stamped: ConversationEventInput = {\n ...event,\n event_id: event.event_id && event.event_id !== '' ? event.event_id : newCorrelationId(),\n sent_at_ms: event.sent_at_ms ?? Date.now(),\n };\n if (!this.isConnected || this.#call === null) {\n this.#enqueue(stamped);\n return;\n }\n if (this.#notReady !== null) {\n // The server is refusing events until the build finishes. Writing this\n // one would only earn another refusal, so hold it with the rest; the\n // probe loop replays everything in order.\n this.#trackUnacked(stamped);\n this.#notReadyUnwritten.push(stamped);\n return;\n }\n this.#write({ conversation_event: { ...stamped } });\n this.#trackUnacked(stamped);\n }\n\n #enqueue(event: ConversationEventInput): void {\n this.#pruneQueue();\n if (this.#sendQueue.length >= SEND_QUEUE_MAX_DEPTH) {\n const evicted = this.#sendQueue.shift();\n this.#journal.recordDropped(evicted?.event.event_id);\n console.warn(\n `[synap] send queue full (max=${SEND_QUEUE_MAX_DEPTH}); dropping oldest `\n + `event (event_type=${evicted?.event.event_type})`,\n );\n }\n this.#sendQueue.push({ queuedAt: Date.now(), event });\n this.#journal.recordQueued(event as unknown as Record<string, unknown>);\n }\n\n #pruneQueue(): void {\n const cutoff = Date.now() - SEND_QUEUE_MAX_AGE_MS;\n while (this.#sendQueue.length > 0 && (this.#sendQueue[0]?.queuedAt ?? 0) < cutoff) {\n const expired = this.#sendQueue.shift();\n this.#journal.recordDropped(expired?.event.event_id);\n console.warn(\n `[synap] queued event expired (age>${SEND_QUEUE_MAX_AGE_MS}ms); dropping `\n + `(event_type=${expired?.event.event_type})`,\n );\n }\n }\n\n #trackUnacked(event: ConversationEventInput): void {\n const id = event.event_id;\n if (id === undefined || id === '') return;\n const cutoff = Date.now() - SEND_QUEUE_MAX_AGE_MS;\n for (const [oldestId, held] of this.#unacked) {\n // While the build runs (and until the backlog is acknowledged) the age\n // limit does not apply and the depth limit is NOT_READY_MAX_HELD: a build\n // outlasts the 5 minute window and holding 100 events would drop data.\n const holding = this.#notReady !== null || this.#heldBacklog;\n const limit = holding ? NOT_READY_MAX_HELD : SEND_QUEUE_MAX_DEPTH;\n const youngEnough = held.queuedAt >= cutoff || holding;\n if (youngEnough && this.#unacked.size < limit) break;\n if (holding) {\n this.#unacked.delete(oldestId);\n this.#journal.recordDropped(oldestId);\n this.#notReadyDropped += 1;\n continue;\n }\n this.#unacked.delete(oldestId);\n this.#journal.recordDropped(oldestId);\n console.warn(\n '[synap] unacknowledged event dropped: the server never confirmed it '\n + `(event_type=${held.event.event_type})`,\n );\n }\n this.#unacked.set(id, { queuedAt: Date.now(), event });\n this.#journal.recordUnacked(event as unknown as Record<string, unknown>);\n }\n\n /**\n * Replay what the server never confirmed, then what never went out.\n *\n * That order is the order things happened in: an unacked event was written\n * to the previous stream, so it is older than anything that piled up while\n * there was no stream at all. Safe to repeat — every event carries the id it\n * was first sent with and the server drops a second sighting of it.\n */\n #replayBuffered(): void {\n const unacked = [...this.#unacked.values()];\n const queued = this.#sendQueue;\n this.#sendQueue = [];\n for (const held of unacked) {\n this.#write({ conversation_event: { ...held.event } });\n }\n for (const held of queued) {\n this.#write({ conversation_event: { ...held.event } });\n // Written and not yet acknowledged is exactly what `#unacked` is for.\n // Without this a refusal after the replay (an unfinished build, a stream\n // that breaks again) lost every event the replay had just sent. Python's\n // `_drain_send_queue` has always tracked them.\n this.#trackUnacked(held.event);\n }\n if (unacked.length > 0 || queued.length > 0) {\n console.warn(\n `[synap] replayed ${unacked.length} unacknowledged and ${queued.length} `\n + 'queued event(s) after reconnect',\n );\n }\n }\n\n sendSessionControl(input: {\n action: string;\n session_id?: string;\n conversation_id?: string;\n user_id?: string;\n customer_id?: string;\n }): void {\n this.#write({ session_control: { ...input } });\n }\n\n /**\n * Report a fetch served from the anticipation cache. It is the only report\n * of that fetch, so it is held while the stream is down and sent on\n * reconnect, with the time the hit happened (the caller's `timestamp_ms`),\n * never dropped. Python: `GRPCTransport.send_context_used`.\n */\n sendContextUsed(event: Record<string, unknown>): void {\n const stamped = { ...event, timestamp_ms: event['timestamp_ms'] ?? Date.now() };\n if (!this.isConnected || this.#call === null) {\n this.#queueHit(stamped);\n return;\n }\n this.#write({ context_used: stamped });\n }\n\n #queueHit(event: Record<string, unknown>): void {\n const cutoff = Date.now() - HIT_QUEUE_MAX_AGE_MS;\n while (this.#pendingHits.length > 0 && (this.#pendingHits[0]?.queuedAt ?? 0) < cutoff) {\n this.#pendingHits.shift();\n }\n if (this.#pendingHits.length >= HIT_QUEUE_MAX_DEPTH) {\n this.#pendingHits.shift();\n console.warn(`[synap] cache-hit report queue full (max=${HIT_QUEUE_MAX_DEPTH}); dropping the oldest`);\n }\n this.#pendingHits.push({ queuedAt: Date.now(), event });\n }\n\n #flushPendingHits(): void {\n const cutoff = Date.now() - HIT_QUEUE_MAX_AGE_MS;\n const held = this.#pendingHits;\n this.#pendingHits = [];\n for (const h of held) {\n if (h.queuedAt >= cutoff) this.#write({ context_used: h.event });\n }\n }\n\n /** How many cache-hit reports are waiting for a stream. */\n get pendingHitReports(): number {\n return this.#pendingHits.length;\n }\n\n sendContextAssembled(event: Record<string, unknown>): void {\n this.#write({ context_assembled: { ...event } });\n }\n\n #flushBeforeClose(): void {\n if (!this.isConnected || this.#call === null) {\n if (this.#sendQueue.length > 0 || this.#unacked.size > 0) {\n console.warn(\n `[synap] closing with ${this.#sendQueue.length} queued and `\n + `${this.#unacked.size} unacknowledged event(s) and no stream to send `\n + 'them on; they are lost',\n );\n }\n return;\n }\n const queued = this.#sendQueue;\n this.#sendQueue = [];\n for (const held of queued) {\n this.#write({ conversation_event: { ...held.event } });\n }\n }\n\n #write(msg: unknown): void {\n if (!this.isConnected || this.#call === null) return;\n try {\n this.#call.write(msg);\n } catch {\n // Non-fatal. These are telemetry and control events; losing one is\n // strictly better than surfacing a stream hiccup to the caller.\n }\n }\n\n async #loadGrpc(): Promise<void> {\n if (this.#grpc !== null) return;\n const [grpcMod, protoMod] = await Promise.all([\n import(/* @vite-ignore */ '@grpc/grpc-js'),\n import(/* @vite-ignore */ '@grpc/proto-loader'),\n ]);\n this.#grpc = grpcMod;\n\n // `fromJSON`, not `loadSync`: no path, no disk read, nothing for a bundler\n // to fail to trace. `keepCase` keeps the snake_case field names the server\n // and the Python SDK both use.\n const pkgDef = protoMod.fromJSON(\n SYNAP_PROTO_DESCRIPTOR as unknown as Parameters<typeof protoMod.fromJSON>[0],\n { keepCase: true, longs: Number, enums: String, defaults: true, oneofs: true },\n );\n const pkg = grpcMod.loadPackageDefinition(pkgDef) as unknown as {\n synap: { v1: { SynapService: new (t: string, c: unknown, o: unknown) => Record<string, unknown> } };\n };\n this.#ServiceStub = pkg.synap.v1.SynapService;\n }\n\n async #establish(): Promise<void> {\n this.#setState('connecting');\n const grpc = this.#grpc;\n const Stub = this.#ServiceStub;\n if (grpc === null || Stub === null) throw new Error('gRPC not loaded');\n\n const channelCreds = this.useTls\n ? grpc.credentials.createSsl()\n : grpc.credentials.createInsecure();\n\n const stub = new Stub(`${this.host}:${this.port}`, channelCreds, {\n 'grpc.keepalive_time_ms': 30_000,\n 'grpc.keepalive_timeout_ms': 10_000,\n 'grpc.keepalive_permit_without_calls': 1,\n });\n\n // Wait for the channel before reporting success.\n //\n // grpc-js connects LAZILY: constructing the stub and creating the call both\n // return immediately, and a bad host surfaces later through the call's\n // 'error' event. Without this, `await listen()` resolved against an\n // unreachable port, `is_listening` read true for a stream that never\n // connected, and `send_message()` then dropped every event silently,\n // because sends are deliberately fire-and-forget. Failing loudly here is\n // the difference between a clear error and an agent that looks like it has\n // no memory.\n await new Promise<void>((resolve, reject) => {\n const deadline = new Date(Date.now() + this.#connectTimeoutMs);\n const waitForReady = (stub as unknown as {\n waitForReady?: (d: Date, cb: (e?: Error) => void) => void;\n }).waitForReady;\n if (typeof waitForReady !== 'function') {\n // Older grpc-js, or a stub that does not expose it. Fall back to the\n // lazy behaviour rather than failing outright.\n resolve();\n return;\n }\n waitForReady.call(stub, deadline, (error?: Error) => {\n if (error) reject(error);\n else resolve();\n });\n });\n\n const metadata = new grpc.Metadata();\n if (this.#credentials.apiKey !== '') {\n metadata.add('authorization', `Bearer ${this.#credentials.apiKey}`);\n }\n metadata.add('x-client-id', this.#credentials.clientId);\n metadata.add('x-instance-id', this.#credentials.instanceId);\n\n const call = (stub['Listen'] as (m: unknown) => DuplexCall)(metadata);\n call.on('data', (msg) => this.#handleMessage(msg as Record<string, unknown>));\n call.on('error', (err) => {\n // A credit refusal arrives here, not from waitForReady: the channel is\n // healthy and the gate aborts the call itself.\n const creditError = creditErrorFromRpc(err);\n if (creditError !== null) {\n this.#handleCreditStop(creditError);\n return;\n }\n void this.#handleDisconnect(`error: ${String(err)}`);\n });\n call.on('end', () => { void this.#handleDisconnect('server_close'); });\n\n // NOTE, and this is where JS and Python legitimately differ.\n //\n // Python waits on `call.wait_for_connection()` here, because grpc.aio\n // reports CONNECTED off a call object the server has not accepted and\n // events written in that window were written into a buffer that the close\n // then discarded.\n //\n // grpc-js has no equivalent, and the obvious stand-in does not work: a\n // grpc-js server sends no initial metadata until it writes, so waiting on\n // the 'metadata' event stalls for the whole connect timeout on a server\n // that is perfectly healthy. Measured: it made every test here time out.\n //\n // It is also not needed. grpc-js buffers writes on the call and flushes\n // them once the call is established, so an event written this early is not\n // lost by the write. It is lost by the TEARDOWN, which is what\n // `disconnect()` now fixes: half-close, then wait for the server to finish\n // reading. The parity is in the outcome the tests assert, a whole turn\n // reaching the server with no pause anywhere, not in the mechanism.\n this.#call = call;\n this.#setState('connected');\n this.#reconnectAttempts = 0;\n this.#lastPongAt = Date.now();\n // Before anything else on the new stream: the turns that happened while\n // there was not one, then the cache hits.\n this.#replayBuffered();\n this.#flushPendingHits();\n }\n\n #handleMessage(msg: Record<string, unknown>): void {\n const ack = msg['event_ack'] as { event_ids?: string[] } | undefined;\n if (ack) {\n for (const id of ack.event_ids ?? []) {\n this.#unacked.delete(id);\n this.#journal.recordAcked(id);\n }\n if (this.#notReady === null && this.#unacked.size < SEND_QUEUE_MAX_DEPTH) {\n this.#heldBacklog = false;\n }\n if (\n this.#notReady === null && (ack.event_ids ?? []).length > 0\n && (this.#notReadyWarned || this.#buildFailedWarned.size > 0)\n ) {\n // The server is accepting again, so the next build gets its own warning.\n this.#notReadyWarned = false;\n this.#buildFailedWarned.clear();\n }\n if (this.#journal.needsCompaction) this.#compactJournal();\n return;\n }\n if (msg['context_bundle']) {\n this.#handleBundle(msg['context_bundle'] as Record<string, unknown>);\n return;\n }\n if (msg['heartbeat_pong']) {\n this.#lastPongAt = Date.now();\n this.#missedHeartbeats = 0;\n return;\n }\n const state = msg['conversation_state'] as\n | { conversation_id?: string; message_count?: number | string }\n | undefined;\n if (state) {\n // int64 arrives as a string or a number depending on the loader options.\n const count = Number(state.message_count ?? 0);\n if (state.conversation_id && Number.isFinite(count)) {\n this.#options.onConversationState?.(state.conversation_id, count);\n }\n return;\n }\n const signal = msg['signal'] as\n | { signal_type?: string; reason?: string; metadata?: Record<string, string> }\n | undefined;\n if (signal?.signal_type === 'throttle') {\n const metadata = signal.metadata ?? {};\n if (metadata['code'] === 'instance_not_ready' || metadata['code'] === 'instance_build_failed') {\n this.#handleNotReady(metadata, signal.reason ?? '');\n } else {\n console.warn(`[synap] server throttle signal: ${signal.reason ?? ''}`);\n }\n return;\n }\n if (signal?.signal_type === 'closing') {\n void this.#handleDisconnect('server_signal_closing');\n } else if (signal?.signal_type === 'error') {\n // Logged, as Python logs it, and not fatal: the server sends it for one\n // refused event or session_start and keeps the stream open. Until 0.5.18\n // it was dropped here without a word.\n console.warn(`[synap] server error signal (stream stays open): ${signal.reason ?? ''}`);\n }\n }\n\n /**\n * The server refused work: the instance is still being built.\n *\n * The refused event is still in `#unacked` (the server neither recorded nor\n * acknowledged it), so nothing is dropped here. This does not close the\n * stream and does not reconnect: a reconnect would replay the same events\n * into the same refusal for the whole build. One probe loop waits\n * `retry_after_seconds` (clamped, jittered), replays the held events and,\n * once the server accepts them, resumes normally. Mirrors Python's\n * `_handle_not_ready`.\n *\n * Logged once per build, not once per event: replaying N held events draws N\n * refusals and a warning each would bury the log.\n */\n #handleNotReady(metadata: Record<string, string>, reason: string): void {\n const code = metadata['code'] || 'instance_not_ready';\n const failed = code === 'instance_build_failed';\n const retry = Number(metadata['retry_after_seconds']);\n this.#notReady = {\n retryAfterSeconds: Number.isFinite(retry) ? Math.trunc(retry) : NOT_READY_MAX_WAIT_MS / 1000,\n instanceId: metadata['instance_id'] || this.#credentials.instanceId,\n state: metadata['state'] || (failed ? 'failed' : 'building'),\n message: reason,\n code,\n ...(failed ? { hint: metadata['hint'] || '', attempts: metadata['attempts'] || '' } : {}),\n };\n this.#notReadyResignalled = true;\n this.#heldBacklog = true;\n if (failed) {\n const key = `${this.#notReady.instanceId}|${metadata['series'] || ''}`;\n if (!this.#buildFailedWarned.has(key)) {\n this.#buildFailedWarned.add(key);\n const hint = this.#notReady.hint;\n console.warn(\n `[synap] instance ${this.#notReady.instanceId}: its memory architecture build FAILED, `\n + `so the server is refusing events. ${this.#unacked.size} event(s) are held in `\n + `memory (up to ${NOT_READY_MAX_HELD}; beyond that the oldest are dropped and the `\n + 'count is reported). Waiting alone will not fix this. '\n + `${hint ? `To recover: ${hint}` : 'Rebuild the instance.'} The SDK checks again `\n + `about every ${Math.round(BUILD_FAILED_PROBE_INTERVAL_MS / 1000)}s and resumes by `\n + `itself after a successful rebuild. Server said: ${reason}`,\n );\n }\n } else if (!this.#notReadyWarned) {\n this.#notReadyWarned = true;\n console.warn(\n `[synap] instance ${this.#notReady.instanceId} is still building its memory `\n + `architecture; the server is refusing events for now. ${this.#unacked.size} `\n + 'event(s) are held in memory and will be re-sent automatically when it is '\n + `ready (next check in about ${Math.round(this.#notReadyWait() / 1000)}s). Up to `\n + `${NOT_READY_MAX_HELD} events are held; beyond that the oldest are dropped and `\n + `the count is reported. Server said: ${reason}`,\n );\n }\n if (!this.#notReadyRunning) {\n this.#notReadyRunning = true;\n void this.#notReadyProbeLoop();\n }\n }\n\n /** Milliseconds until the next probe: the hint, clamped, with jitter. */\n #notReadyWait(): number {\n if (this.#notReady?.code === 'instance_build_failed') {\n return BUILD_FAILED_PROBE_INTERVAL_MS + Math.random() * BUILD_FAILED_PROBE_JITTER_MS;\n }\n const hintMs = (this.#notReady?.retryAfterSeconds ?? 0) * 1000;\n const base = Math.min(Math.max(hintMs, NOT_READY_MIN_WAIT_MS), NOT_READY_MAX_WAIT_MS);\n const jitter = 1 - NOT_READY_JITTER + Math.random() * 2 * NOT_READY_JITTER;\n return Math.max(base * jitter, NOT_READY_MIN_WAIT_MS);\n }\n\n /** Cancellable on disconnect, and never the only thing holding the process open. */\n #notReadySleep(ms: number): Promise<void> {\n if (this.#options.sleep) return this.#options.sleep(ms);\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => { this.#notReadyWake = null; resolve(); }, ms);\n if (typeof timer.unref === 'function') timer.unref();\n this.#notReadyWake = () => { clearTimeout(timer); this.#notReadyWake = null; resolve(); };\n });\n }\n\n async #notReadyProbeLoop(): Promise<void> {\n try {\n while (!this.#shutdownRequested) {\n await this.#notReadySleep(this.#notReadyWait());\n if (this.#shutdownRequested) return;\n // The reconnect path replays everything. If the build is still running\n // the next refusal restarts this loop, and the warning has been given.\n if (!this.isConnected || this.#call === null) return;\n this.#notReadyResignalled = false;\n // Fresh timestamps, so the age limit cannot evict a held event in the\n // moment between the build finishing and its ack.\n const now = Date.now();\n for (const held of this.#unacked.values()) held.queuedAt = now;\n // Emptied only after the replay has written every event it covers.\n const covered = new Set(this.#unacked.keys());\n for (const held of [...this.#unacked.values()]) {\n this.#write({ conversation_event: { ...held.event } });\n }\n this.#notReadyUnwritten = this.#notReadyUnwritten.filter(\n (e) => !covered.has(String(e.event_id)));\n await this.#notReadySleep(NOT_READY_PROBE_GRACE_MS);\n if (this.#shutdownRequested) return;\n if (!this.#notReadyResignalled) {\n // Accepted. New sends go straight out from here; write what was held\n // after the replay or it would wait for a reconnect.\n const instanceId = this.#notReady?.instanceId ?? this.#credentials.instanceId;\n this.#notReady = null;\n const late = this.#notReadyUnwritten;\n this.#notReadyUnwritten = [];\n for (const event of late) {\n if (!this.#unacked.has(String(event.event_id))) continue; // dropped at the cap\n this.#write({ conversation_event: { ...event } });\n }\n this.#notReadyWarned = false;\n this.#buildFailedWarned.clear();\n console.info(\n `[synap] instance ${instanceId} is ready; held events were accepted and `\n + 'the stream is back to normal',\n );\n return;\n }\n }\n } finally {\n this.#notReady = null;\n this.#notReadyUnwritten = [];\n this.#notReadyRunning = false;\n if (this.#notReadyDropped > 0) {\n console.warn(\n `[synap] while the instance was building, ${this.#notReadyDropped} held event(s) `\n + `were DROPPED (oldest first) because the in-memory limit of ${NOT_READY_MAX_HELD} `\n + 'was reached. They were not sent.',\n );\n this.#notReadyDropped = 0;\n }\n }\n }\n\n #handleBundle(bundle: Record<string, unknown>): void {\n const bundleType = String(bundle['bundle_type'] ?? '') || 'anticipation';\n const conversationId = String(bundle['anticipation_conversation_id'] ?? '');\n\n if (bundleType !== UNCACHEABLE_BUNDLE_TYPE) this.#store(bundle, bundleType, conversationId);\n\n if (bundleType === 'compaction_update' && conversationId !== '') {\n // Python also deletes this conversation's `compacted_full` /\n // `compacted_context` entries from its separate CacheManager. This SDK\n // has no such cache, and calling dropConversation() here would delete\n // the bundle just stored above, so there is nothing to invalidate.\n this.#options.onCompactionUpdate?.(conversationId, bundle);\n }\n\n // Fires for every type, after storing, matching Python's ordering.\n this.#options.onContext?.(bundle);\n }\n\n #store(bundle: Record<string, unknown>, bundleType: string, conversationId: string): void {\n const itemsByType: Record<string, Array<Record<string, unknown>>> = {};\n for (const [type, list] of Object.entries(bundle['items_by_type'] ?? {})) {\n const items = (list as { items?: Array<Record<string, unknown>> })?.items;\n itemsByType[type] = items ?? [];\n }\n\n const ttlHint = Number(bundle['ttl_hint_seconds'] ?? 0);\n this.#cache.store({\n bundleId: String(bundle['bundle_id'] ?? ''),\n // The cache keys on ONE entity. User id wins when present, so a bundle\n // pushed for a user cannot be served to a different user in the same\n // customer; falling back to customer id keeps org-scope bundles usable.\n entityId:\n String(bundle['anticipation_user_id'] ?? '') ||\n String(bundle['anticipation_customer_id'] ?? '') ||\n null,\n conversationId: conversationId || null,\n // The rung the server retrieved this bundle at. Absent from anything an\n // older server sent, and absent reads as \"named no rung\" rather than as\n // \"matches anything\".\n scopeRung: String(bundle['anticipation_scope_rung'] ?? '') || null,\n itemsByType,\n // 0 means \"use the SDK default\"; anything else is floored at 60s.\n ttlHintSeconds: ttlHint > 0 ? Math.max(ttlHint, MIN_TTL_SECONDS) : null,\n bundleType,\n searchQueries: [\n ...((bundle['search_queries'] as string[] | undefined) ?? []),\n ...((bundle['search_keywords'] as string[] | undefined) ?? []),\n ],\n });\n }\n\n /**\n * End the stream because the server refused it for credits.\n *\n * Reconnecting cannot clear a credit refusal, so the stream closes and the\n * typed error is kept on `lastError` for the application to read. Mirrors\n * Python's `_handle_credit_stop`.\n */\n #handleCreditStop(error: SynapError): void {\n this.#lastError = error;\n this.#shutdownRequested = true;\n this.#stopHeartbeat();\n this.#closeCall();\n this.#setState('disconnected');\n }\n\n async #handleDisconnect(_reason: string): Promise<void> {\n if (this.#shutdownRequested) return;\n\n this.#closeCall();\n this.#setState('reconnecting');\n\n if (this.#reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {\n this.#setState('disconnected');\n return;\n }\n\n // Jittered exponential backoff. The jitter matters with many SDK instances\n // behind one deploy: without it they all retry in lockstep.\n const delay = Math.min(\n BACKOFF_BASE_MS * 2 ** this.#reconnectAttempts + Math.random() * 1_000,\n BACKOFF_MAX_MS,\n );\n this.#reconnectAttempts += 1;\n\n await this.#sleep(delay);\n if (this.#shutdownRequested) return;\n try {\n await this.#establish();\n } catch (error) {\n if (isCreditStop(error)) {\n this.#handleCreditStop(error as SynapError);\n return;\n }\n void this.#handleDisconnect('reconnect_failed');\n }\n }\n\n #startHeartbeat(): void {\n this.#heartbeatTimer = setInterval(() => {\n if (!this.isConnected || this.#call === null) return;\n const now = Date.now();\n\n if (now - this.#lastPongAt > HEARTBEAT_TIMEOUT_MS) {\n this.#missedHeartbeats += 1;\n if (this.#missedHeartbeats >= MAX_MISSED_HEARTBEATS) {\n void this.#handleDisconnect('heartbeat_timeout');\n return;\n }\n }\n try {\n this.#call.write({ heartbeat_ping: { timestamp_ms: now } });\n } catch {\n void this.#handleDisconnect('heartbeat_write_error');\n }\n }, HEARTBEAT_INTERVAL_MS);\n // Never hold the process open on the heartbeat alone: a CLI that finishes\n // its work should exit, not hang for 30s.\n this.#heartbeatTimer.unref?.();\n }\n\n #stopHeartbeat(): void {\n if (this.#heartbeatTimer !== null) {\n clearInterval(this.#heartbeatTimer);\n this.#heartbeatTimer = null;\n }\n }\n\n #closeCall(): void {\n try {\n this.#call?.end();\n } catch {\n /* already torn down */\n }\n this.#call = null;\n }\n\n #setState(state: StreamState): void {\n this.#state = state;\n this.#options.onStateChange?.(state);\n }\n}\n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mBAAK,GAAA;AAChC,EAAA,GAAA,CAAI,CAAC,GAAA,EAAK,OAAO,IAAA;AACjB,EAAA,MAAM,EAAA,EAAI,MAAA,CAAO,GAAG,CAAA;AACpB,EAAA,OAAO,MAAA,CAAO,QAAA,CAAS,CAAC,EAAA,EAAI,EAAA,EAAI,IAAA;AAClC;AAEO,SAAS,MAAA,CAAO,IAAA,EAAkC;AACvD,EAAA,MAAM,EAAA,EAAI,OAAA,CAAQ,IAAI,CAAA;AACtB,EAAA,OAAO,EAAA,IAAM,KAAA,EAAA,GAAa,EAAA,IAAM,GAAA,EAAK,KAAA,EAAA,EAAY,CAAA;AACnD;ADjBA;AACA;AACE;AACA;AACA;AACF,4FAAC","file":"/Users/anish/npm-publish-0.6.6/synap/sdk/js/dist/chunk-ZKOJDUN4.cjs","sourcesContent":[null,"/**\n * Environment access.\n *\n * Every read happens at CALL time, never at module load. Python does\n * `os.environ.get(...)` inside the function bodies, and tests plus runtime\n * toggles depend on that: a value captured at import time makes a later\n * `process.env` mutation look like the flag simply does not work. That is\n * gotcha G-S.\n *\n * `process` is absent on Workers and in the browser, so every accessor\n * tolerates it being missing.\n */\n\nconst TRUTHY = new Set(['true', '1', 'yes']);\n\nfunction readEnv(name: string): string | undefined {\n if (typeof process === 'undefined' || process.env === undefined) return undefined;\n return process.env[name];\n}\n\n/** Boolean flag. Defaults to false, matching the Python SDK's flags. */\nexport function getEnvFlag(name: string, fallback = false): boolean {\n const raw = readEnv(name);\n if (raw === undefined || raw.trim() === '') return fallback;\n return TRUTHY.has(raw.trim().toLowerCase());\n}\n\n/** Numeric setting. Returns null when unset OR malformed: a bad value must not fail closed. */\nexport function getEnvFloat(name: string): number | null {\n const raw = readEnv(name)?.trim();\n if (!raw) return null;\n const n = Number(raw);\n return Number.isFinite(n) ? n : null;\n}\n\nexport function getEnv(name: string): string | undefined {\n const v = readEnv(name);\n return v === undefined || v === '' ? undefined : v;\n}\n"]}
1
+ {"version":3,"sources":["/Users/scaler/maximem_synap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AACnD;ADjBA;AACA;AACE;AACA;AACA;AACF,4FAAC","file":"/Users/scaler/maximem_synap_npm_publish/synap/sdk/js/dist/chunk-ZKOJDUN4.cjs","sourcesContent":[null,"/**\n * Environment access.\n *\n * Every read happens at CALL time, never at module load. Python does\n * `os.environ.get(...)` inside the function bodies, and tests plus runtime\n * toggles depend on that: a value captured at import time makes a later\n * `process.env` mutation look like the flag simply does not work. That is\n * gotcha G-S.\n *\n * `process` is absent on Workers and in the browser, so every accessor\n * tolerates it being missing.\n */\n\nconst TRUTHY = new Set(['true', '1', 'yes']);\n\nfunction readEnv(name: string): string | undefined {\n if (typeof process === 'undefined' || process.env === undefined) return undefined;\n return process.env[name];\n}\n\n/** Boolean flag. Defaults to false, matching the Python SDK's flags. */\nexport function getEnvFlag(name: string, fallback = false): boolean {\n const raw = readEnv(name);\n if (raw === undefined || raw.trim() === '') return fallback;\n return TRUTHY.has(raw.trim().toLowerCase());\n}\n\n/** Numeric setting. Returns null when unset OR malformed: a bad value must not fail closed. */\nexport function getEnvFloat(name: string): number | null {\n const raw = readEnv(name)?.trim();\n if (!raw) return null;\n const n = Number(raw);\n return Number.isFinite(n) ? n : null;\n}\n\nexport function getEnv(name: string): string | undefined {\n const v = readEnv(name);\n return v === undefined || v === '' ? undefined : v;\n}\n"]}