@maximem/synap-js-sdk 0.4.8 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/anticipation-cache-LRE3TLK4.cjs.map +1 -1
  2. package/dist/{chunk-T5QQBJ6T.js → chunk-ASM2OIIG.js} +292 -7
  3. package/dist/chunk-ASM2OIIG.js.map +1 -0
  4. package/dist/{chunk-OCMM2Z5P.js → chunk-BWMPKLFG.js} +40 -2
  5. package/dist/chunk-BWMPKLFG.js.map +1 -0
  6. package/dist/{chunk-7CWBRHUO.cjs → chunk-IA2N5NUY.cjs} +302 -17
  7. package/dist/chunk-IA2N5NUY.cjs.map +1 -0
  8. package/dist/{chunk-2TVL5IPQ.cjs → chunk-T372OL3Q.cjs} +41 -3
  9. package/dist/chunk-T372OL3Q.cjs.map +1 -0
  10. package/dist/chunk-T6U5PVAD.cjs.map +1 -1
  11. package/dist/chunk-ZKOJDUN4.cjs.map +1 -1
  12. package/dist/env-55ULHNJZ.cjs.map +1 -1
  13. package/dist/errors-Bl3vY1eb.d.cts +382 -0
  14. package/dist/errors-Bl3vY1eb.d.ts +382 -0
  15. package/dist/grpc/index.cjs +7 -7
  16. package/dist/grpc/index.cjs.map +1 -1
  17. package/dist/grpc/index.d.cts +44 -4
  18. package/dist/grpc/index.d.ts +44 -4
  19. package/dist/grpc/index.js +5 -5
  20. package/dist/index.cjs +278 -161
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +97 -148
  23. package/dist/index.d.ts +97 -148
  24. package/dist/index.js +171 -54
  25. package/dist/index.js.map +1 -1
  26. package/dist/stream-client-6OWRYOA4.js +16 -0
  27. package/dist/stream-client-Y5JGSF2R.cjs +16 -0
  28. package/dist/stream-client-Y5JGSF2R.cjs.map +1 -0
  29. package/package.json +1 -1
  30. package/dist/anticipation-cache-C1rUEpaW.d.cts +0 -211
  31. package/dist/anticipation-cache-C1rUEpaW.d.ts +0 -211
  32. package/dist/chunk-2TVL5IPQ.cjs.map +0 -1
  33. package/dist/chunk-7CWBRHUO.cjs.map +0 -1
  34. package/dist/chunk-OCMM2Z5P.js.map +0 -1
  35. package/dist/chunk-T5QQBJ6T.js.map +0 -1
  36. package/dist/stream-client-2C5KIOWP.js +0 -7
  37. package/dist/stream-client-GPU37E6F.cjs +0 -7
  38. package/dist/stream-client-GPU37E6F.cjs.map +0 -1
  39. /package/dist/{stream-client-2C5KIOWP.js.map → stream-client-6OWRYOA4.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["/private/tmp/ndeep-main/synap/sdk/js/dist/anticipation-cache-LRE3TLK4.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,iNAAC","file":"/private/tmp/ndeep-main/synap/sdk/js/dist/anticipation-cache-LRE3TLK4.cjs"}
1
+ {"version":3,"sources":["/Users/scaler/maximem_synap/synap/sdk/js/dist/anticipation-cache-LRE3TLK4.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,iNAAC","file":"/Users/scaler/maximem_synap/synap/sdk/js/dist/anticipation-cache-LRE3TLK4.cjs"}
@@ -1,5 +1,11 @@
1
+ import {
2
+ InsufficientCreditsError,
3
+ RateLimitError,
4
+ newCorrelationId
5
+ } from "./chunk-BWMPKLFG.js";
6
+
1
7
  // src/grpc/descriptor.ts
2
- var PROTO_SHA = "a58c9b031b41530d";
8
+ var PROTO_SHA = "c1d834043608ad4f";
3
9
  var SYNAP_PROTO_DESCRIPTOR = {
4
10
  "nested": {
5
11
  "synap": {
@@ -202,6 +208,14 @@ var SYNAP_PROTO_DESCRIPTOR = {
202
208
  "type": "string",
203
209
  "id": 11
204
210
  },
211
+ "tool_result_json": {
212
+ "type": "string",
213
+ "id": 15
214
+ },
215
+ "tool_call_id": {
216
+ "type": "string",
217
+ "id": 16
218
+ },
205
219
  "search_queries": {
206
220
  "rule": "repeated",
207
221
  "type": "string",
@@ -216,6 +230,14 @@ var SYNAP_PROTO_DESCRIPTOR = {
216
230
  "keyType": "string",
217
231
  "type": "string",
218
232
  "id": 14
233
+ },
234
+ "event_id": {
235
+ "type": "string",
236
+ "id": 17
237
+ },
238
+ "sent_at_ms": {
239
+ "type": "int64",
240
+ "id": 18
219
241
  }
220
242
  }
221
243
  },
@@ -257,7 +279,8 @@ var SYNAP_PROTO_DESCRIPTOR = {
257
279
  "oneof": [
258
280
  "context_bundle",
259
281
  "heartbeat_pong",
260
- "signal"
282
+ "signal",
283
+ "event_ack"
261
284
  ]
262
285
  }
263
286
  },
@@ -273,6 +296,23 @@ var SYNAP_PROTO_DESCRIPTOR = {
273
296
  "signal": {
274
297
  "type": "StreamSignal",
275
298
  "id": 3
299
+ },
300
+ "event_ack": {
301
+ "type": "EventAck",
302
+ "id": 4
303
+ }
304
+ }
305
+ },
306
+ "EventAck": {
307
+ "fields": {
308
+ "event_ids": {
309
+ "rule": "repeated",
310
+ "type": "string",
311
+ "id": 1
312
+ },
313
+ "timestamp_ms": {
314
+ "type": "int64",
315
+ "id": 2
276
316
  }
277
317
  }
278
318
  },
@@ -624,7 +664,66 @@ var BACKOFF_MAX_MS = 3e4;
624
664
  var HEARTBEAT_INTERVAL_MS = 3e4;
625
665
  var HEARTBEAT_TIMEOUT_MS = 1e4;
626
666
  var MAX_MISSED_HEARTBEATS = 3;
667
+ var SEND_QUEUE_MAX_DEPTH = 100;
668
+ var CLOSE_GRACE_MS = 2e3;
669
+ var SEND_QUEUE_MAX_AGE_MS = 5 * 60 * 1e3;
627
670
  var MIN_TTL_SECONDS = 60;
671
+ var GRPC_RESOURCE_EXHAUSTED = 8;
672
+ var CREDIT_ABORT_DETAILS = "insufficient_credits";
673
+ var CREDIT_STOP_REASONS = /* @__PURE__ */ new Set([
674
+ "overages_disabled",
675
+ "trial_limit_reached",
676
+ "subscription_inactive"
677
+ ]);
678
+ function metadataValue(metadata, key) {
679
+ if (metadata === null || typeof metadata !== "object") return null;
680
+ const getter = metadata.get;
681
+ const raw = typeof getter === "function" ? getter.call(metadata, key) : metadata[key];
682
+ const value = Array.isArray(raw) ? raw[0] : raw;
683
+ if (value === void 0 || value === null) return null;
684
+ const text = typeof value === "string" ? value : String(value);
685
+ return text === "" ? null : text;
686
+ }
687
+ function numberOrNull(value) {
688
+ if (value === null) return null;
689
+ const parsed = Number(value);
690
+ return Number.isFinite(parsed) ? parsed : null;
691
+ }
692
+ function creditErrorFromRpc(error, correlationId = null) {
693
+ if (error === null || typeof error !== "object") return null;
694
+ if (error.code !== GRPC_RESOURCE_EXHAUSTED) return null;
695
+ const metadata = error.metadata;
696
+ const reason = metadataValue(metadata, "credit-reason");
697
+ if (reason === null || !CREDIT_STOP_REASONS.has(reason)) return null;
698
+ const rawDetails = error.details;
699
+ const details = typeof rawDetails === "string" && rawDetails !== "" ? rawDetails : CREDIT_ABORT_DETAILS;
700
+ const requestId = metadataValue(metadata, "request-id") ?? correlationId;
701
+ const manageUrl = metadataValue(metadata, "credit-manage-url");
702
+ if (reason === "overages_disabled") {
703
+ return new InsufficientCreditsError(details, {
704
+ correlationId: requestId,
705
+ balanceCredits: numberOrNull(metadataValue(metadata, "credit-balance")),
706
+ requiredCredits: numberOrNull(metadataValue(metadata, "credit-minimum-required")),
707
+ recoveryUrl: metadataValue(metadata, "credit-recovery-url"),
708
+ redeemUrl: metadataValue(metadata, "credit-redeem-url"),
709
+ reason,
710
+ manageUrl
711
+ });
712
+ }
713
+ return new RateLimitError(details, {
714
+ correlationId: requestId,
715
+ reason,
716
+ upgradeUrl: metadataValue(metadata, "credit-upgrade-url"),
717
+ manageUrl
718
+ });
719
+ }
720
+ function isCreditStop(error) {
721
+ if (!(error instanceof InsufficientCreditsError) && !(error instanceof RateLimitError)) {
722
+ return false;
723
+ }
724
+ const reason = error.reason;
725
+ return typeof reason === "string" && CREDIT_STOP_REASONS.has(reason);
726
+ }
628
727
  var GrpcStreamClient = class {
629
728
  host;
630
729
  port;
@@ -636,6 +735,16 @@ var GrpcStreamClient = class {
636
735
  #missedHeartbeats = 0;
637
736
  #heartbeatTimer = null;
638
737
  #shutdownRequested = false;
738
+ // Events that could not be written because there was no stream.
739
+ #sendQueue = [];
740
+ // Events written to a live stream that the server has not acknowledged. The
741
+ // queue above covers "the stream was down"; this covers the half that
742
+ // actually loses sessions — the write succeeded, the stream broke before the
743
+ // server processed it, and nobody knows.
744
+ #unacked = /* @__PURE__ */ new Map();
745
+ // Why the stream stopped, when it stopped for a reason the caller can act on
746
+ // (today: a credit refusal). Mirrors Python's `last_error`.
747
+ #lastError = null;
639
748
  #grpc = null;
640
749
  #ServiceStub = null;
641
750
  #credentials;
@@ -659,21 +768,149 @@ var GrpcStreamClient = class {
659
768
  get isConnected() {
660
769
  return this.#state === "connected";
661
770
  }
771
+ /**
772
+ * The error that ended the stream, if one did.
773
+ *
774
+ * Set when the server refused the stream for credits, so an `onDisconnect`
775
+ * handler can read the balance, the reason and the URL to fix it. Null for an
776
+ * ordinary disconnect.
777
+ */
778
+ get lastError() {
779
+ return this.#lastError;
780
+ }
662
781
  async connect() {
663
782
  await this.#loadGrpc();
664
783
  this.#shutdownRequested = false;
784
+ this.#lastError = null;
665
785
  await this.#establish();
666
786
  this.#startHeartbeat();
667
787
  }
668
788
  async disconnect() {
669
789
  this.#shutdownRequested = true;
670
790
  this.#stopHeartbeat();
671
- this.#closeCall();
791
+ this.#flushBeforeClose();
792
+ const call = this.#call;
793
+ if (call !== null) {
794
+ try {
795
+ call.end();
796
+ } catch {
797
+ }
798
+ await new Promise((resolve) => {
799
+ let settled = false;
800
+ const done = () => {
801
+ if (!settled) {
802
+ settled = true;
803
+ resolve();
804
+ }
805
+ };
806
+ const timer = setTimeout(() => {
807
+ const left = this.undelivered();
808
+ if (left.unacknowledged > 0 || left.queued > 0) {
809
+ console.warn(
810
+ `[synap] closing with ${left.queued} queued and ${left.unacknowledged} unacknowledged event(s) the server did not confirm within ${CLOSE_GRACE_MS}ms`
811
+ );
812
+ }
813
+ done();
814
+ }, CLOSE_GRACE_MS);
815
+ if (typeof timer.unref === "function") timer.unref();
816
+ call.on("end", () => {
817
+ clearTimeout(timer);
818
+ done();
819
+ });
820
+ call.on("status", () => {
821
+ clearTimeout(timer);
822
+ done();
823
+ });
824
+ call.on("error", () => {
825
+ clearTimeout(timer);
826
+ done();
827
+ });
828
+ });
829
+ }
830
+ this.#call = null;
672
831
  this.#setState("closed");
673
832
  }
674
- /** Fire-and-forget: a dropped event must never fail the caller's turn. */
833
+ /**
834
+ * What this client could not get to the server.
835
+ *
836
+ * Every send path returns void, so a caller had no way to tell a delivered
837
+ * turn from a lost one. Mirrors Python's `undelivered()`.
838
+ */
839
+ undelivered() {
840
+ return { queued: this.#sendQueue.length, unacknowledged: this.#unacked.size };
841
+ }
842
+ /**
843
+ * Never fails the caller's turn, and no longer loses it either.
844
+ *
845
+ * A write that cannot go out is buffered and replayed on reconnect, and a
846
+ * write that does go out is held until the server acknowledges it. Before
847
+ * this, both cases ended at a silent `return`.
848
+ */
675
849
  sendConversationEvent(event) {
676
- this.#write({ conversation_event: { ...event } });
850
+ const stamped = {
851
+ ...event,
852
+ event_id: event.event_id && event.event_id !== "" ? event.event_id : newCorrelationId(),
853
+ sent_at_ms: event.sent_at_ms ?? Date.now()
854
+ };
855
+ if (!this.isConnected || this.#call === null) {
856
+ this.#enqueue(stamped);
857
+ return;
858
+ }
859
+ this.#write({ conversation_event: { ...stamped } });
860
+ this.#trackUnacked(stamped);
861
+ }
862
+ #enqueue(event) {
863
+ this.#pruneQueue();
864
+ if (this.#sendQueue.length >= SEND_QUEUE_MAX_DEPTH) {
865
+ const evicted = this.#sendQueue.shift();
866
+ console.warn(
867
+ `[synap] send queue full (max=${SEND_QUEUE_MAX_DEPTH}); dropping oldest event (event_type=${evicted?.event.event_type})`
868
+ );
869
+ }
870
+ this.#sendQueue.push({ queuedAt: Date.now(), event });
871
+ }
872
+ #pruneQueue() {
873
+ const cutoff = Date.now() - SEND_QUEUE_MAX_AGE_MS;
874
+ while (this.#sendQueue.length > 0 && (this.#sendQueue[0]?.queuedAt ?? 0) < cutoff) {
875
+ const expired = this.#sendQueue.shift();
876
+ console.warn(
877
+ `[synap] queued event expired (age>${SEND_QUEUE_MAX_AGE_MS}ms); dropping (event_type=${expired?.event.event_type})`
878
+ );
879
+ }
880
+ }
881
+ #trackUnacked(event) {
882
+ const id = event.event_id;
883
+ if (id === void 0 || id === "") return;
884
+ const cutoff = Date.now() - SEND_QUEUE_MAX_AGE_MS;
885
+ for (const [oldestId, held] of this.#unacked) {
886
+ if (held.queuedAt >= cutoff && this.#unacked.size < SEND_QUEUE_MAX_DEPTH) break;
887
+ this.#unacked.delete(oldestId);
888
+ console.warn(
889
+ `[synap] unacknowledged event dropped: the server never confirmed it (event_type=${held.event.event_type})`
890
+ );
891
+ }
892
+ this.#unacked.set(id, { queuedAt: Date.now(), event });
893
+ }
894
+ /**
895
+ * Replay what the server never confirmed, then what never went out.
896
+ *
897
+ * That order is the order things happened in: an unacked event was written
898
+ * to the previous stream, so it is older than anything that piled up while
899
+ * there was no stream at all. Safe to repeat — every event carries the id it
900
+ * was first sent with and the server drops a second sighting of it.
901
+ */
902
+ #replayBuffered() {
903
+ const unacked = [...this.#unacked.values()];
904
+ const queued = this.#sendQueue;
905
+ this.#sendQueue = [];
906
+ for (const held of [...unacked, ...queued]) {
907
+ this.#write({ conversation_event: { ...held.event } });
908
+ }
909
+ if (unacked.length > 0 || queued.length > 0) {
910
+ console.warn(
911
+ `[synap] replayed ${unacked.length} unacknowledged and ${queued.length} queued event(s) after reconnect`
912
+ );
913
+ }
677
914
  }
678
915
  sendSessionControl(input) {
679
916
  this.#write({ session_control: { ...input } });
@@ -684,6 +921,21 @@ var GrpcStreamClient = class {
684
921
  sendContextAssembled(event) {
685
922
  this.#write({ context_assembled: { ...event } });
686
923
  }
924
+ #flushBeforeClose() {
925
+ if (!this.isConnected || this.#call === null) {
926
+ if (this.#sendQueue.length > 0 || this.#unacked.size > 0) {
927
+ console.warn(
928
+ `[synap] closing with ${this.#sendQueue.length} queued and ${this.#unacked.size} unacknowledged event(s) and no stream to send them on; they are lost`
929
+ );
930
+ }
931
+ return;
932
+ }
933
+ const queued = this.#sendQueue;
934
+ this.#sendQueue = [];
935
+ for (const held of queued) {
936
+ this.#write({ conversation_event: { ...held.event } });
937
+ }
938
+ }
687
939
  #write(msg) {
688
940
  if (!this.isConnected || this.#call === null) return;
689
941
  try {
@@ -741,6 +993,11 @@ var GrpcStreamClient = class {
741
993
  const call = stub["Listen"](metadata);
742
994
  call.on("data", (msg) => this.#handleMessage(msg));
743
995
  call.on("error", (err) => {
996
+ const creditError = creditErrorFromRpc(err);
997
+ if (creditError !== null) {
998
+ this.#handleCreditStop(creditError);
999
+ return;
1000
+ }
744
1001
  void this.#handleDisconnect(`error: ${String(err)}`);
745
1002
  });
746
1003
  call.on("end", () => {
@@ -750,8 +1007,14 @@ var GrpcStreamClient = class {
750
1007
  this.#setState("connected");
751
1008
  this.#reconnectAttempts = 0;
752
1009
  this.#lastPongAt = Date.now();
1010
+ this.#replayBuffered();
753
1011
  }
754
1012
  #handleMessage(msg) {
1013
+ const ack = msg["event_ack"];
1014
+ if (ack) {
1015
+ for (const id of ack.event_ids ?? []) this.#unacked.delete(id);
1016
+ return;
1017
+ }
755
1018
  if (msg["context_bundle"]) {
756
1019
  this.#handleBundle(msg["context_bundle"]);
757
1020
  return;
@@ -803,6 +1066,20 @@ var GrpcStreamClient = class {
803
1066
  ]
804
1067
  });
805
1068
  }
1069
+ /**
1070
+ * End the stream because the server refused it for credits.
1071
+ *
1072
+ * Reconnecting cannot clear a credit refusal, so the stream closes and the
1073
+ * typed error is kept on `lastError` for the application to read. Mirrors
1074
+ * Python's `_handle_credit_stop`.
1075
+ */
1076
+ #handleCreditStop(error) {
1077
+ this.#lastError = error;
1078
+ this.#shutdownRequested = true;
1079
+ this.#stopHeartbeat();
1080
+ this.#closeCall();
1081
+ this.#setState("disconnected");
1082
+ }
806
1083
  async #handleDisconnect(_reason) {
807
1084
  if (this.#shutdownRequested) return;
808
1085
  this.#closeCall();
@@ -820,7 +1097,11 @@ var GrpcStreamClient = class {
820
1097
  if (this.#shutdownRequested) return;
821
1098
  try {
822
1099
  await this.#establish();
823
- } catch {
1100
+ } catch (error) {
1101
+ if (isCreditStop(error)) {
1102
+ this.#handleCreditStop(error);
1103
+ return;
1104
+ }
824
1105
  void this.#handleDisconnect("reconnect_failed");
825
1106
  }
826
1107
  }
@@ -864,6 +1145,10 @@ var GrpcStreamClient = class {
864
1145
 
865
1146
  export {
866
1147
  PROTO_SHA,
1148
+ CREDIT_ABORT_DETAILS,
1149
+ CREDIT_STOP_REASONS,
1150
+ creditErrorFromRpc,
1151
+ isCreditStop,
867
1152
  GrpcStreamClient
868
1153
  };
869
- //# sourceMappingURL=chunk-T5QQBJ6T.js.map
1154
+ //# sourceMappingURL=chunk-ASM2OIIG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/grpc/descriptor.ts","../src/grpc/stream-client.ts"],"sourcesContent":["/**\n * GENERATED FILE. Do not edit by hand.\n *\n * Source: synap/proto/synap_service.proto\n * Generator: synap/sdk/scripts/gen_proto_descriptor.mjs\n * Proto SHA: c1d834043608ad4f\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 = 'c1d834043608ad4f';\n\nexport const SYNAP_PROTO_DESCRIPTOR = {\n \"nested\": {\n \"synap\": {\n \"nested\": {\n \"v1\": {\n \"nested\": {\n \"SynapService\": {\n \"methods\": {\n \"Listen\": {\n \"requestType\": \"StreamEvent\",\n \"requestStream\": true,\n \"responseType\": \"StreamResponse\",\n \"responseStream\": true\n },\n \"IngestTelemetry\": {\n \"requestType\": \"TelemetryEvent\",\n \"requestStream\": true,\n \"responseType\": \"TelemetryAck\"\n }\n }\n },\n \"StreamEvent\": {\n \"oneofs\": {\n \"payload\": {\n \"oneof\": [\n \"conversation_event\",\n \"heartbeat_ping\",\n \"session_control\",\n \"context_used\",\n \"context_assembled\"\n ]\n }\n },\n \"fields\": {\n \"conversation_event\": {\n \"type\": \"ConversationEvent\",\n \"id\": 1\n },\n \"heartbeat_ping\": {\n \"type\": \"HeartbeatPing\",\n \"id\": 2\n },\n \"session_control\": {\n \"type\": \"SessionControl\",\n \"id\": 3\n },\n \"context_used\": {\n \"type\": \"ContextUsedEvent\",\n \"id\": 4\n },\n \"context_assembled\": {\n \"type\": \"ContextAssembledEvent\",\n \"id\": 5\n }\n }\n },\n \"ContextUsedEvent\": {\n \"fields\": {\n \"bundle_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"served_item_ids\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 5\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 6\n },\n \"scope\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"source_bundle_ids\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 8\n }\n }\n },\n \"ContextAssembledEvent\": {\n \"fields\": {\n \"correlation_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"final_item_ids\": {\n \"rule\": \"repeated\",\n \"type\": \"string\",\n \"id\": 5\n },\n \"final_total_tokens\": {\n \"type\": \"int32\",\n \"id\": 6\n },\n \"compaction_id\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"recent_turn_count\": {\n \"type\": \"int32\",\n \"id\": 8\n },\n \"compaction_end_timestamp\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"assembly_source\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"assembly_duration_ms\": {\n \"type\": \"int32\",\n \"id\": 11\n },\n \"cache_hit\": {\n \"type\": \"bool\",\n \"id\": 12\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 13\n },\n \"sdk_version\": {\n \"type\": \"string\",\n \"id\": 14\n }\n }\n },\n \"ConversationEvent\": {\n \"fields\": {\n \"event_type\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"conversation_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"user_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"role\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"content\": {\n \"type\": \"string\",\n \"id\": 5\n },\n \"customer_id\": {\n \"type\": \"string\",\n \"id\": 6\n },\n \"session_id\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"metadata\": {\n \"keyType\": \"string\",\n \"type\": \"string\",\n \"id\": 8\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 9\n },\n \"tool_name\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"tool_args_json\": {\n \"type\": \"string\",\n \"id\": 11\n },\n \"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 ]\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 }\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 }\n },\n \"RecentTurnProto\": {\n \"fields\": {\n \"role\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"content\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"timestamp\": {\n \"type\": \"string\",\n \"id\": 3\n }\n }\n },\n \"ContextItemList\": {\n \"fields\": {\n \"items\": {\n \"rule\": \"repeated\",\n \"type\": \"ContextItemProto\",\n \"id\": 1\n }\n }\n },\n \"ContextItemProto\": {\n \"fields\": {\n \"item_id\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"content\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"context_type\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"source\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"similarity_score\": {\n \"type\": \"float\",\n \"id\": 5\n },\n \"relevance_score\": {\n \"type\": \"float\",\n \"id\": 6\n },\n \"confidence\": {\n \"type\": \"float\",\n \"id\": 7\n },\n \"scope\": {\n \"type\": \"string\",\n \"id\": 8\n },\n \"entity_id\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"created_at\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"event_date\": {\n \"type\": \"string\",\n \"id\": 11\n },\n \"valid_until\": {\n \"type\": \"string\",\n \"id\": 12\n },\n \"temporal_category\": {\n \"type\": \"string\",\n \"id\": 13\n },\n \"temporal_confidence\": {\n \"type\": \"float\",\n \"id\": 14\n }\n }\n },\n \"TelemetryEvent\": {\n \"fields\": {\n \"event_type\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"instance_id\": {\n \"type\": \"string\",\n \"id\": 2\n },\n \"client_id\": {\n \"type\": \"string\",\n \"id\": 3\n },\n \"correlation_id\": {\n \"type\": \"string\",\n \"id\": 4\n },\n \"timestamp_ms\": {\n \"type\": \"int64\",\n \"id\": 5\n },\n \"latency_ms\": {\n \"type\": \"int32\",\n \"id\": 6\n },\n \"status\": {\n \"type\": \"string\",\n \"id\": 7\n },\n \"error_code\": {\n \"type\": \"string\",\n \"id\": 8\n },\n \"scope\": {\n \"type\": \"string\",\n \"id\": 9\n },\n \"cache_status\": {\n \"type\": \"string\",\n \"id\": 10\n },\n \"attempt\": {\n \"type\": \"int32\",\n \"id\": 11\n },\n \"http_method\": {\n \"type\": \"string\",\n \"id\": 12\n },\n \"http_path\": {\n \"type\": \"string\",\n \"id\": 13\n },\n \"http_status_code\": {\n \"type\": \"int32\",\n \"id\": 14\n },\n \"metadata\": {\n \"keyType\": \"string\",\n \"type\": \"string\",\n \"id\": 15\n },\n \"sdk_version\": {\n \"type\": \"string\",\n \"id\": 16\n },\n \"batch_id\": {\n \"type\": \"string\",\n \"id\": 17\n }\n }\n },\n \"TelemetryAck\": {\n \"fields\": {\n \"status\": {\n \"type\": \"string\",\n \"id\": 1\n },\n \"events_received\": {\n \"type\": \"int32\",\n \"id\": 2\n }\n }\n }\n }\n }\n }\n }\n }\n} as const;\n","/**\n * Bidirectional gRPC stream client for the Synap anticipation channel.\n *\n * Mirrors Python's `GRPCTransport` and the synap-vercel-adk client:\n * - `/synap.v1.SynapService/Listen`, StreamEvent in, StreamResponse out\n * - Auth via `authorization: Bearer <key>` plus `x-client-id` / `x-instance-id`\n * - 30s heartbeat, exponential-backoff reconnect\n * - Server pushes ContextBundleProto, which lands in the AnticipationCache\n *\n * Node-only, and reached exclusively through a lazy `import()` so that merely\n * importing the SDK on Edge or in a Worker stays safe. grpc-js is built on\n * `node:http2`/`node:net`/`node:tls`; a static import fails the BUILD there.\n *\n * The proto arrives as an inlined descriptor (see ./descriptor.ts) rather than\n * being read from disk, so bundlers and Vercel file tracing cannot lose it.\n */\n\nimport type { AnticipationCache } from '../context/anticipation-cache.js';\nimport { SYNAP_PROTO_DESCRIPTOR } from './descriptor.js';\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// 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/** The server may only SHORTEN the SDK default, never extend it past this floor. */\nconst MIN_TTL_SECONDS = 60;\n\nexport interface StreamCredentials {\n apiKey: string;\n clientId: string;\n instanceId: string;\n}\n\nexport interface StreamClientOptions {\n host?: string;\n port?: number;\n useTls?: boolean;\n /** Injected in tests so reconnect backoff does not make the suite slow. */\n sleep?: (ms: number) => Promise<void>;\n /** How long to wait for the channel to become ready. Default 10s. */\n connectTimeoutMs?: number;\n onStateChange?: (state: StreamState) => void;\n /** Fires for every bundle, before the cache filter. Backs `listen({onContext})`. */\n onContext?: (bundle: Record<string, unknown>) => void;\n /** Fires only for `compaction_update` bundles. Backs the compaction subscriptions. */\n onCompactionUpdate?: (conversationId: string, bundle: Record<string, unknown>) => void;\n}\n\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 /**\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 // 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 // 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\n #grpc: typeof import('@grpc/grpc-js') | null = null;\n #ServiceStub: (new (target: string, creds: unknown, opts: unknown) => Record<string, unknown>) | null = null;\n\n readonly #credentials: StreamCredentials;\n readonly #cache: AnticipationCache;\n readonly #options: StreamClientOptions;\n readonly #sleep: (ms: number) => Promise<void>;\n readonly #connectTimeoutMs: number;\n\n constructor(\n credentials: StreamCredentials,\n cache: AnticipationCache,\n options: StreamClientOptions = {},\n ) {\n this.#credentials = credentials;\n this.#cache = cache;\n this.#options = options;\n this.host = options.host ?? 'synap-cloud-prod.maximem.ai';\n this.port = options.port ?? 443;\n this.useTls = options.useTls ?? true;\n this.#sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));\n this.#connectTimeoutMs = options.connectTimeoutMs ?? 10_000;\n }\n\n get currentState(): StreamState { return this.#state; }\n get isConnected(): boolean { return this.#state === 'connected'; }\n\n /**\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 async connect(): Promise<void> {\n await this.#loadGrpc();\n this.#shutdownRequested = false;\n this.#lastError = null;\n await this.#establish();\n this.#startHeartbeat();\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\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 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 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 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 }\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 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 if (held.queuedAt >= cutoff && this.#unacked.size < SEND_QUEUE_MAX_DEPTH) break;\n this.#unacked.delete(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 }\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, ...queued]) {\n this.#write({ conversation_event: { ...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 sendContextUsed(event: Record<string, unknown>): void {\n this.#write({ context_used: { ...event } });\n }\n\n sendContextAssembled(event: Record<string, unknown>): void {\n this.#write({ context_assembled: { ...event } });\n }\n\n #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.\n this.#replayBuffered();\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 ?? []) this.#unacked.delete(id);\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 signal = msg['signal'] as { signal_type?: string } | undefined;\n if (signal?.signal_type === 'closing') {\n void this.#handleDisconnect('server_signal_closing');\n }\n }\n\n #handleBundle(bundle: Record<string, unknown>): void {\n const bundleType = String(bundle['bundle_type'] ?? '') || 'anticipation';\n const conversationId = String(bundle['anticipation_conversation_id'] ?? '');\n\n if (bundleType !== UNCACHEABLE_BUNDLE_TYPE) this.#store(bundle, bundleType, conversationId);\n\n if (bundleType === 'compaction_update' && conversationId !== '') {\n // Python also deletes this conversation's `compacted_full` /\n // `compacted_context` entries from its separate CacheManager. This SDK\n // has no such cache, and calling dropConversation() here would delete\n // the bundle just stored above, so there is nothing to invalidate.\n this.#options.onCompactionUpdate?.(conversationId, bundle);\n }\n\n // Fires for every type, after storing, matching Python's ordering.\n this.#options.onContext?.(bundle);\n }\n\n #store(bundle: Record<string, unknown>, bundleType: string, conversationId: string): void {\n const itemsByType: Record<string, Array<Record<string, unknown>>> = {};\n for (const [type, list] of Object.entries(bundle['items_by_type'] ?? {})) {\n const items = (list as { items?: Array<Record<string, unknown>> })?.items;\n itemsByType[type] = items ?? [];\n }\n\n const ttlHint = Number(bundle['ttl_hint_seconds'] ?? 0);\n this.#cache.store({\n bundleId: String(bundle['bundle_id'] ?? ''),\n // The cache keys on ONE entity. User id wins when present, so a bundle\n // pushed for a user cannot be served to a different user in the same\n // customer; falling back to customer id keeps org-scope bundles usable.\n entityId:\n String(bundle['anticipation_user_id'] ?? '') ||\n String(bundle['anticipation_customer_id'] ?? '') ||\n null,\n conversationId: conversationId || null,\n // The rung the server retrieved this bundle at. Absent from anything an\n // older server sent, and absent reads as \"named no rung\" rather than as\n // \"matches anything\".\n scopeRung: String(bundle['anticipation_scope_rung'] ?? '') || null,\n itemsByType,\n // 0 means \"use the SDK default\"; anything else is floored at 60s.\n ttlHintSeconds: ttlHint > 0 ? Math.max(ttlHint, MIN_TTL_SECONDS) : null,\n bundleType,\n searchQueries: [\n ...((bundle['search_queries'] as string[] | undefined) ?? []),\n ...((bundle['search_keywords'] as string[] | undefined) ?? []),\n ],\n });\n }\n\n /**\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,UAAU;AAAA,QACR,MAAM;AAAA,UACJ,UAAU;AAAA,YACR,gBAAgB;AAAA,cACd,WAAW;AAAA,gBACT,UAAU;AAAA,kBACR,eAAe;AAAA,kBACf,iBAAiB;AAAA,kBACjB,gBAAgB;AAAA,kBAChB,kBAAkB;AAAA,gBACpB;AAAA,gBACA,mBAAmB;AAAA,kBACjB,eAAe;AAAA,kBACf,iBAAiB;AAAA,kBACjB,gBAAgB;AAAA,gBAClB;AAAA,cACF;AAAA,YACF;AAAA,YACA,eAAe;AAAA,cACb,UAAU;AAAA,gBACR,WAAW;AAAA,kBACT,SAAS;AAAA,oBACP;AAAA,oBACA;AAAA,oBACA;AAAA,oBACA;AAAA,oBACA;AAAA,kBACF;AAAA,gBACF;AAAA,cACF;AAAA,cACA,UAAU;AAAA,gBACR,sBAAsB;AAAA,kBACpB,QAAQ;AAAA,kBACR,MAAM;AAAA,gBACR;AAAA,gBACA,kBAAkB;AAAA,kBAChB,QAAQ;AAAA,kBACR,MAAM;AAAA,gBACR;AAAA,gBACA,mBAAmB;AAAA,kBACjB,QAAQ;AAAA,kBACR,MAAM;AAAA,gBACR;AAAA,gBACA,gBAAgB;AAAA,kBACd,QAAQ;AAAA,kBACR,MAAM;AAAA,gBACR;AAAA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AAqB,KAAK,OAAO,IAAI;AAAA,MACjE;AAAA,IACF;AACA,SAAK,sBAAsB;AAE3B,UAAM,KAAK,OAAO,KAAK;AACvB,QAAI,KAAK,mBAAoB;AAC7B,QAAI;AACF,YAAM,KAAK,WAAW;AAAA,IACxB,SAAS,OAAO;AACd,UAAI,aAAa,KAAK,GAAG;AACvB,aAAK,kBAAkB,KAAmB;AAC1C;AAAA,MACF;AACA,WAAK,KAAK,kBAAkB,kBAAkB;AAAA,IAChD;AAAA,EACF;AAAA,EAEA,kBAAwB;AACtB,SAAK,kBAAkB,YAAY,MAAM;AACvC,UAAI,CAAC,KAAK,eAAe,KAAK,UAAU,KAAM;AAC9C,YAAM,MAAM,KAAK,IAAI;AAErB,UAAI,MAAM,KAAK,cAAc,sBAAsB;AACjD,aAAK,qBAAqB;AAC1B,YAAI,KAAK,qBAAqB,uBAAuB;AACnD,eAAK,KAAK,kBAAkB,mBAAmB;AAC/C;AAAA,QACF;AAAA,MACF;AACA,UAAI;AACF,aAAK,MAAM,MAAM,EAAE,gBAAgB,EAAE,cAAc,IAAI,EAAE,CAAC;AAAA,MAC5D,QAAQ;AACN,aAAK,KAAK,kBAAkB,uBAAuB;AAAA,MACrD;AAAA,IACF,GAAG,qBAAqB;AAGxB,SAAK,gBAAgB,QAAQ;AAAA,EAC/B;AAAA,EAEA,iBAAuB;AACrB,QAAI,KAAK,oBAAoB,MAAM;AACjC,oBAAc,KAAK,eAAe;AAClC,WAAK,kBAAkB;AAAA,IACzB;AAAA,EACF;AAAA,EAEA,aAAmB;AACjB,QAAI;AACF,WAAK,OAAO,IAAI;AAAA,IAClB,QAAQ;AAAA,IAER;AACA,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,UAAU,OAA0B;AAClC,SAAK,SAAS;AACd,SAAK,SAAS,gBAAgB,KAAK;AAAA,EACrC;AACF;","names":[]}
@@ -56,9 +56,18 @@ var NetworkTimeoutError = class extends SynapTransientError {
56
56
  var RateLimitError = class extends SynapTransientError {
57
57
  static errorCode = "rate_limit";
58
58
  retryAfterSeconds;
59
+ /** Machine-readable cause, when the stop was a credit stop. */
60
+ reason;
61
+ /** Where a Trial customer upgrades. Python calls this `upgrade_url`. */
62
+ upgradeUrl;
63
+ /** Where billing is managed. Python calls this `manage_url`. */
64
+ manageUrl;
59
65
  constructor(message, options = {}) {
60
66
  super(message, options);
61
67
  this.retryAfterSeconds = options.retryAfterSeconds ?? null;
68
+ this.reason = options.reason ?? null;
69
+ this.upgradeUrl = options.upgradeUrl ?? null;
70
+ this.manageUrl = options.manageUrl ?? null;
62
71
  }
63
72
  };
64
73
  var ServiceUnavailableError = class extends SynapTransientError {
@@ -78,12 +87,23 @@ var InsufficientCreditsError = class extends SynapPermanentError {
78
87
  recoveryUrl;
79
88
  /** Where a redeem code can be entered. Python calls this `redeem_url`. */
80
89
  redeemUrl;
90
+ /**
91
+ * Machine-readable cause. `'overages_disabled'` means the plan is paid and
92
+ * the balance is spent, but the account has not allowed usage past zero, so
93
+ * the work stops until someone allows overages or adds credits. Null when an
94
+ * older server did not send one.
95
+ */
96
+ reason;
97
+ /** Where that setting and billing are managed. Python calls this `manage_url`. */
98
+ manageUrl;
81
99
  constructor(message, options = {}) {
82
100
  super(message, options);
83
101
  this.balanceCredits = options.balanceCredits ?? null;
84
102
  this.requiredCredits = options.requiredCredits ?? null;
85
103
  this.recoveryUrl = options.recoveryUrl ?? null;
86
104
  this.redeemUrl = options.redeemUrl ?? null;
105
+ this.reason = options.reason ?? null;
106
+ this.manageUrl = options.manageUrl ?? null;
87
107
  }
88
108
  };
89
109
  var InvalidInputError = class extends SynapPermanentError {
@@ -150,6 +170,23 @@ var TransientError = SynapTransientError;
150
170
  var PermanentError = SynapPermanentError;
151
171
  var ConnectionError = NetworkTimeoutError;
152
172
 
173
+ // src/util/correlation.ts
174
+ function newCorrelationId() {
175
+ const c = globalThis.crypto;
176
+ if (typeof c?.randomUUID === "function") return c.randomUUID();
177
+ if (typeof c?.getRandomValues === "function") {
178
+ const b = c.getRandomValues(new Uint8Array(16));
179
+ b[6] = (b[6] ?? 0) & 15 | 64;
180
+ b[8] = (b[8] ?? 0) & 63 | 128;
181
+ const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
182
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
183
+ }
184
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (ch) => {
185
+ const r = Math.random() * 16 | 0;
186
+ return (ch === "x" ? r : r & 3 | 8).toString(16);
187
+ });
188
+ }
189
+
153
190
  export {
154
191
  SynapError,
155
192
  isSynapError,
@@ -173,6 +210,7 @@ export {
173
210
  SDKError,
174
211
  TransientError,
175
212
  PermanentError,
176
- ConnectionError
213
+ ConnectionError,
214
+ newCorrelationId
177
215
  };
178
- //# sourceMappingURL=chunk-OCMM2Z5P.js.map
216
+ //# sourceMappingURL=chunk-BWMPKLFG.js.map