@maximem/synap-js-sdk 0.6.4 → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/anticipation-cache-Q7IYC3ID.cjs +26 -0
  2. package/dist/anticipation-cache-Q7IYC3ID.cjs.map +1 -0
  3. package/dist/{anticipation-cache-RWKF55J4.js → anticipation-cache-VL5WHTJB.js} +8 -2
  4. package/dist/chunk-7IZHVYO2.cjs.map +1 -1
  5. package/dist/{chunk-ICUFS3B5.cjs → chunk-BYUGILQI.cjs} +136 -142
  6. package/dist/chunk-BYUGILQI.cjs.map +1 -0
  7. package/dist/{chunk-R72YL6Q4.js → chunk-CSG3N5E3.js} +136 -142
  8. package/dist/chunk-CSG3N5E3.js.map +1 -0
  9. package/dist/{chunk-2VJV4HCF.cjs → chunk-PYJOWTI5.cjs} +72 -20
  10. package/dist/chunk-PYJOWTI5.cjs.map +1 -0
  11. package/dist/{chunk-N55UBGER.js → chunk-VCCZ33ZU.js} +59 -7
  12. package/dist/chunk-VCCZ33ZU.js.map +1 -0
  13. package/dist/chunk-ZKOJDUN4.cjs.map +1 -1
  14. package/dist/env-55ULHNJZ.cjs.map +1 -1
  15. package/dist/{errors-DWjdpExq.d.cts → errors-x5bpgxmC.d.cts} +18 -3
  16. package/dist/{errors-DWjdpExq.d.ts → errors-x5bpgxmC.d.ts} +18 -3
  17. package/dist/grpc/index.cjs +4 -4
  18. package/dist/grpc/index.cjs.map +1 -1
  19. package/dist/grpc/index.d.cts +11 -3
  20. package/dist/grpc/index.d.ts +11 -3
  21. package/dist/grpc/index.js +3 -3
  22. package/dist/index.cjs +906 -185
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +242 -20
  25. package/dist/index.d.ts +242 -20
  26. package/dist/index.js +826 -105
  27. package/dist/index.js.map +1 -1
  28. package/dist/onnx-encoder-4RSL6ID4.cjs.map +1 -1
  29. package/dist/stream-client-BY5LNLVB.cjs +22 -0
  30. package/dist/stream-client-BY5LNLVB.cjs.map +1 -0
  31. package/dist/{stream-client-GRDVRBFA.js → stream-client-JKFBVZPN.js} +2 -2
  32. package/package.json +1 -1
  33. package/dist/anticipation-cache-LPNKMRBH.cjs +0 -20
  34. package/dist/anticipation-cache-LPNKMRBH.cjs.map +0 -1
  35. package/dist/chunk-2VJV4HCF.cjs.map +0 -1
  36. package/dist/chunk-ICUFS3B5.cjs.map +0 -1
  37. package/dist/chunk-N55UBGER.js.map +0 -1
  38. package/dist/chunk-R72YL6Q4.js.map +0 -1
  39. package/dist/stream-client-SZIYGVVJ.cjs +0 -22
  40. package/dist/stream-client-SZIYGVVJ.cjs.map +0 -1
  41. /package/dist/{anticipation-cache-RWKF55J4.js.map → anticipation-cache-VL5WHTJB.js.map} +0 -0
  42. /package/dist/{stream-client-GRDVRBFA.js.map → stream-client-JKFBVZPN.js.map} +0 -0
package/dist/index.cjs CHANGED
@@ -9,8 +9,7 @@
9
9
 
10
10
 
11
11
 
12
-
13
- var _chunkICUFS3B5cjs = require('./chunk-ICUFS3B5.cjs');
12
+ var _chunkBYUGILQIcjs = require('./chunk-BYUGILQI.cjs');
14
13
 
15
14
 
16
15
  var _chunkZKOJDUN4cjs = require('./chunk-ZKOJDUN4.cjs');
@@ -50,11 +49,14 @@ var ENDPOINTS = {
50
49
  memories_create: { method: "POST", path: "/api/v1/memories/create", idempotent: false },
51
50
  memories_batch: { method: "POST", path: "/api/v1/memories/batch", idempotent: false },
52
51
  memories_upload: { method: "POST", path: "/api/v1/memories/upload", idempotent: false },
52
+ memories_create_multipart: { method: "POST", path: "/api/v1/memories/create-multipart", idempotent: false },
53
53
  memories_status: { method: "GET", path: "/api/v1/memories/status/{ingestion_id}", idempotent: true },
54
54
  memories_get: { method: "GET", path: "/api/v1/memories/{memory_id}", idempotent: true },
55
55
  memories_update: { method: "PATCH", path: "/api/v1/memories/{memory_id}", idempotent: false },
56
56
  memories_delete: { method: "DELETE", path: "/api/v1/memories/{memory_id}", idempotent: true },
57
57
  memories_forget: { method: "POST", path: "/api/v1/memories/forget", idempotent: false },
58
+ data_delete: { method: "POST", path: "/v1/data/delete", idempotent: true },
59
+ data_delete_status: { method: "GET", path: "/v1/data/delete/{deletion_id}", idempotent: true },
58
60
  context_fetch_user: { method: "POST", path: "/v1/context/user/fetch", idempotent: true },
59
61
  context_fetch_customer: { method: "POST", path: "/v1/context/customer/fetch", idempotent: true },
60
62
  context_fetch_client: { method: "POST", path: "/v1/context/client/fetch", idempotent: true },
@@ -271,6 +273,16 @@ var HttpTransport = (_class2 = class {
271
273
  _nullishCoalesce(_optionalChain([options, 'access', _7 => _7.keepAlive, 'optionalAccess', _8 => _8.heartbeatIntervalMs]), () => ( HEARTBEAT_INTERVAL_MS))
272
274
  );
273
275
  }
276
+ /**
277
+ * @internal Fetch a URL that is not Synap's, with this transport's fetch.
278
+ *
279
+ * Used to read a `FilePart` given by `url`: the SDK fetches it, the server
280
+ * never does. Deliberately sends none of this transport's headers, because
281
+ * the URL belongs to somebody else and the API key must not reach them.
282
+ */
283
+ fetchExternal(url, init = {}) {
284
+ return this.fetchImpl(url, init);
285
+ }
274
286
  /** Start keeping the connection warm. Opt-in: it is pointless in serverless. */
275
287
  startHeartbeat() {
276
288
  if (!this.closed) this.heartbeat.start();
@@ -387,7 +399,7 @@ var HttpTransport = (_class2 = class {
387
399
  if (gated) this.cooldownCheck(cooldownKey, correlationId);
388
400
  let attempt = 0;
389
401
  let last = null;
390
- while (attempt < this.retryPolicy.maxAttempts) {
402
+ while (attempt < Math.max(1, this.retryPolicy.maxAttempts)) {
391
403
  attempt += 1;
392
404
  try {
393
405
  const result = await this.attempt(name, options, correlationId);
@@ -435,7 +447,8 @@ var HttpTransport = (_class2 = class {
435
447
  signal.dispose();
436
448
  }
437
449
  if (!response.ok) {
438
- throw await toHttpError(response, correlationId);
450
+ const error = await toHttpError(response, correlationId);
451
+ throw _nullishCoalesce(_optionalChain([options, 'access', _10 => _10.mapError, 'optionalCall', _11 => _11(response.status, error)]), () => ( error));
439
452
  }
440
453
  if (response.status === 204) return void 0;
441
454
  const text = await response.text();
@@ -506,18 +519,18 @@ function isConnectionRefusal(error) {
506
519
  }
507
520
  function toTransportError(error, correlationId) {
508
521
  if (error instanceof _chunk7IZHVYO2cjs.SynapError) return error;
509
- const name = _optionalChain([error, 'optionalAccess', _10 => _10.name]);
522
+ const name = _optionalChain([error, 'optionalAccess', _12 => _12.name]);
510
523
  if (name === "AbortError" || name === "TimeoutError") {
511
524
  return new (0, _chunk7IZHVYO2cjs.NetworkTimeoutError)("Request timed out", { correlationId, cause: error });
512
525
  }
513
526
  if (isConnectionRefusal(error)) {
514
527
  return new (0, _chunk7IZHVYO2cjs.NetworkTimeoutError)(
515
- `Connection failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _11 => _11.message]), () => ( String(error)))}`,
528
+ `Connection failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _13 => _13.message]), () => ( String(error)))}`,
516
529
  { correlationId, cause: error }
517
530
  );
518
531
  }
519
532
  return new (0, _chunk7IZHVYO2cjs.ServiceUnavailableError)(
520
- `Network request failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _12 => _12.message]), () => ( String(error)))}`,
533
+ `Network request failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _14 => _14.message]), () => ( String(error)))}`,
521
534
  { correlationId, cause: error }
522
535
  );
523
536
  }
@@ -546,6 +559,11 @@ async function toHttpError(response, correlationId) {
546
559
  switch (response.status) {
547
560
  case 400:
548
561
  case 422:
562
+ // Wrong method, too large, unsupported media type: each says what was
563
+ // wrong with the request, and none of them goes away on a retry.
564
+ case 405:
565
+ case 413:
566
+ case 415:
549
567
  return new (0, _chunk7IZHVYO2cjs.InvalidInputError)(message, opts);
550
568
  case 401:
551
569
  case 403:
@@ -565,8 +583,8 @@ async function toHttpError(response, correlationId) {
565
583
  });
566
584
  }
567
585
  case 409:
568
- if (parsed["error"] === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _13 => _13["code"]]) === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _14 => _14["error"]]) === "instance_build_failed") {
569
- const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _15 => _15[key]])));
586
+ if (parsed["error"] === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _15 => _15["code"]]) === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _16 => _16["error"]]) === "instance_build_failed") {
587
+ const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _17 => _17[key]])));
570
588
  const msg = pick4("message");
571
589
  const attempts = Number(pick4("attempts"));
572
590
  return new (0, _chunk7IZHVYO2cjs.InstanceBuildFailedError)(
@@ -579,8 +597,8 @@ async function toHttpError(response, correlationId) {
579
597
  }
580
598
  );
581
599
  }
582
- if (parsed["error"] === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _16 => _16["code"]]) === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _17 => _17["error"]]) === "instance_not_ready") {
583
- const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _18 => _18[key]])));
600
+ if (parsed["error"] === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _18 => _18["code"]]) === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _19 => _19["error"]]) === "instance_not_ready") {
601
+ const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _20 => _20[key]])));
584
602
  const rawWait = _nullishCoalesce(pick4("retry_after_seconds"), () => ( response.headers.get("retry-after")));
585
603
  const wait = rawWait !== null && rawWait !== void 0 && String(rawWait).trim() !== "" ? Number(rawWait) : NaN;
586
604
  const msg = pick4("message");
@@ -628,11 +646,11 @@ function stringOrNull(v) {
628
646
  }
629
647
  function withTimeout(ms, external) {
630
648
  const controller = new AbortController();
631
- const onExternalAbort = () => controller.abort(_optionalChain([external, 'optionalAccess', _19 => _19.reason]));
649
+ const onExternalAbort = () => controller.abort(_optionalChain([external, 'optionalAccess', _21 => _21.reason]));
632
650
  const timer = setTimeout(() => {
633
651
  controller.abort(new (0, _chunk7IZHVYO2cjs.NetworkTimeoutError)(`Timed out after ${ms}ms`));
634
652
  }, ms);
635
- _optionalChain([timer, 'access', _20 => _20.unref, 'optionalCall', _21 => _21()]);
653
+ _optionalChain([timer, 'access', _22 => _22.unref, 'optionalCall', _23 => _23()]);
636
654
  if (external) {
637
655
  if (external.aborted) onExternalAbort();
638
656
  else external.addEventListener("abort", onExternalAbort, { once: true });
@@ -641,7 +659,7 @@ function withTimeout(ms, external) {
641
659
  signal: controller.signal,
642
660
  dispose() {
643
661
  clearTimeout(timer);
644
- _optionalChain([external, 'optionalAccess', _22 => _22.removeEventListener, 'call', _23 => _23("abort", onExternalAbort)]);
662
+ _optionalChain([external, 'optionalAccess', _24 => _24.removeEventListener, 'call', _25 => _25("abort", onExternalAbort)]);
645
663
  }
646
664
  };
647
665
  }
@@ -649,14 +667,14 @@ function sleep(ms, signal) {
649
667
  if (ms <= 0) return Promise.resolve();
650
668
  return new Promise((resolve, reject) => {
651
669
  const timer = setTimeout(() => {
652
- _optionalChain([signal, 'optionalAccess', _24 => _24.removeEventListener, 'call', _25 => _25("abort", onAbort)]);
670
+ _optionalChain([signal, 'optionalAccess', _26 => _26.removeEventListener, 'call', _27 => _27("abort", onAbort)]);
653
671
  resolve();
654
672
  }, ms);
655
673
  function onAbort() {
656
674
  clearTimeout(timer);
657
- reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _26 => _26.reason]), () => ( new Error("Aborted"))));
675
+ reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _28 => _28.reason]), () => ( new Error("Aborted"))));
658
676
  }
659
- _optionalChain([signal, 'optionalAccess', _27 => _27.addEventListener, 'call', _28 => _28("abort", onAbort, { once: true })]);
677
+ _optionalChain([signal, 'optionalAccess', _29 => _29.addEventListener, 'call', _30 => _30("abort", onAbort, { once: true })]);
660
678
  });
661
679
  }
662
680
 
@@ -740,6 +758,41 @@ function sortByRankScore(items) {
740
758
  return [...items].sort(byRankScore);
741
759
  }
742
760
 
761
+ // src/context/no-query.ts
762
+ var MEMORY_TYPES2 = ["facts", "preferences", "episodes", "emotions", "temporal_events"];
763
+ var emptyLists = () => Object.fromEntries(MEMORY_TYPES2.map((t) => [t, []]));
764
+ function hasQuery(searchQuery) {
765
+ if (typeof searchQuery === "string") return searchQuery.trim() !== "";
766
+ if (!Array.isArray(searchQuery)) return false;
767
+ return searchQuery.some((q) => typeof q === "string" && q.trim() !== "");
768
+ }
769
+ function conversationStateContext(prompt, conversationId) {
770
+ const recent = Array.isArray(prompt["recent_messages"]) ? prompt["recent_messages"] : [];
771
+ const turns = recent.filter((m) => typeof m === "object" && m !== null && !Array.isArray(m)).map((m) => ({ role: _nullishCoalesce(m["role"], () => ( null)), content: _nullishCoalesce(m["content"], () => ( null)), timestamp: _nullishCoalesce(m["timestamp"], () => ( null)) }));
772
+ return {
773
+ ...emptyLists(),
774
+ conversation_context: {
775
+ conversation_id: conversationId,
776
+ summary: prompt["context_block"] || null,
777
+ recent_turns: turns,
778
+ compaction_id: prompt["compaction_id"] || null,
779
+ formatted_context: prompt["formatted_context"] || null
780
+ }
781
+ };
782
+ }
783
+ function profileContext(profile) {
784
+ if (typeof profile !== "object" || profile === null || Array.isArray(profile)) return null;
785
+ let doc = profile;
786
+ const inner = doc["profile"];
787
+ if (!("attributes" in doc) && typeof inner === "object" && inner !== null && !Array.isArray(inner)) {
788
+ doc = inner;
789
+ }
790
+ const attributes = doc["attributes"];
791
+ const hasAttributes = typeof attributes === "object" && attributes !== null && Object.keys(attributes).length > 0;
792
+ if (!hasAttributes && !doc["overview"]) return null;
793
+ return { ...emptyLists(), profile: doc };
794
+ }
795
+
743
796
  // src/context/fetch.ts
744
797
  var ENDPOINT_BY_SCOPE = {
745
798
  user: "context_fetch_user",
@@ -867,9 +920,15 @@ function retrievalOptionsOf(options) {
867
920
  }
868
921
  return { mode, precisionLevel };
869
922
  }
923
+ function validateSearchQuery(searchQuery) {
924
+ if (searchQuery === void 0 || searchQuery === null) return;
925
+ if (!Array.isArray(searchQuery) || searchQuery.some((query) => typeof query !== "string")) {
926
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("search_query must be an array of strings when provided");
927
+ }
928
+ }
870
929
  async function fetchContext(transport, scope, options = {}, hooks = {}) {
871
930
  const startedAt = Date.now();
872
- await _optionalChain([transport, 'access', _29 => _29.ready, 'optionalCall', _30 => _30()]);
931
+ await _optionalChain([transport, 'access', _31 => _31.ready, 'optionalCall', _32 => _32()]);
873
932
  await transport.checkCustomerId(
874
933
  opt(options, "customer_id", "customerId"),
875
934
  `${scope}.context.fetch`
@@ -877,22 +936,28 @@ async function fetchContext(transport, scope, options = {}, hooks = {}) {
877
936
  const responseShape = responseShapeOf(options);
878
937
  retrievalOptionsOf(options);
879
938
  const { contextMode } = scopeOptionsOf(scope, options);
939
+ const searchQuery = opt(options, "search_query", "searchQuery");
940
+ validateSearchQuery(searchQuery);
880
941
  const summaryMode = scope === "user" && contextMode === "conversation-summary";
942
+ if (!summaryMode && hooks.withoutQuery && !hasQuery(searchQuery)) {
943
+ const answer = await hooks.withoutQuery(scope, options);
944
+ if (answer !== null) return applyResponseShape(answer, responseShape);
945
+ }
881
946
  const finish = (response2) => {
882
- _optionalChain([hooks, 'access', _31 => _31.onResponse, 'optionalCall', _32 => _32(scope, options, response2)]);
947
+ _optionalChain([hooks, 'access', _33 => _33.onResponse, 'optionalCall', _34 => _34(scope, options, response2)]);
883
948
  return response2;
884
949
  };
885
950
  const conversationId = opt(options, "conversation_id", "conversationId");
886
- const skipServerSt = conversationId ? _optionalChain([hooks, 'access', _33 => _33.skipServerShortTerm, 'optionalCall', _34 => _34(conversationId)]) === true : false;
951
+ const skipServerSt = conversationId ? _optionalChain([hooks, 'access', _35 => _35.skipServerShortTerm, 'optionalCall', _36 => _36(conversationId)]) === true : false;
887
952
  const network = async () => {
888
953
  const { endpoint, body } = buildFetchRequest(
889
954
  scope,
890
955
  skipServerSt ? { ...options, include_conversation_context: false } : options
891
956
  );
892
957
  const result = await transport.request(endpoint, { body });
893
- return applyResponseShape(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _35 => _35["context"]]), () => ( {})), responseShape);
958
+ return applyResponseShape(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _37 => _37["context"]]), () => ( {})), responseShape);
894
959
  };
895
- const anticipated = summaryMode ? null : await _asyncNullishCoalesce(await _optionalChain([hooks, 'access', _36 => _36.beforeFetch, 'optionalCall', _37 => _37(scope, options)]), async () => ( null));
960
+ const anticipated = summaryMode ? null : await _asyncNullishCoalesce(await _optionalChain([hooks, 'access', _38 => _38.beforeFetch, 'optionalCall', _39 => _39(scope, options)]), async () => ( null));
896
961
  if (anticipated !== null && anticipated.borderline) {
897
962
  const pending = network();
898
963
  pending.catch(() => void 0);
@@ -903,17 +968,17 @@ async function fetchContext(transport, scope, options = {}, hooks = {}) {
903
968
  const won = await Promise.race([pending.then((r) => r, () => null), late]);
904
969
  if (timer !== void 0) clearTimeout(timer);
905
970
  if (won !== null) {
906
- _optionalChain([hooks, 'access', _38 => _38.onAssembled, 'optionalCall', _39 => _39(scope, options, won, startedAt)]);
971
+ _optionalChain([hooks, 'access', _40 => _40.onAssembled, 'optionalCall', _41 => _41(scope, options, won, startedAt)]);
907
972
  return finish(won);
908
973
  }
909
974
  }
910
975
  if (anticipated !== null) {
911
- _optionalChain([hooks, 'access', _40 => _40.onServedFromCache, 'optionalCall', _41 => _41(scope, options, anticipated)]);
912
- _optionalChain([hooks, 'access', _42 => _42.onAssembled, 'optionalCall', _43 => _43(scope, options, anticipated.response, startedAt)]);
976
+ _optionalChain([hooks, 'access', _42 => _42.onServedFromCache, 'optionalCall', _43 => _43(scope, options, anticipated)]);
977
+ _optionalChain([hooks, 'access', _44 => _44.onAssembled, 'optionalCall', _45 => _45(scope, options, anticipated.response, startedAt)]);
913
978
  return finish(applyResponseShape(anticipated.response, responseShape));
914
979
  }
915
980
  const response = await network();
916
- _optionalChain([hooks, 'access', _44 => _44.onAssembled, 'optionalCall', _45 => _45(scope, options, response, startedAt)]);
981
+ _optionalChain([hooks, 'access', _46 => _46.onAssembled, 'optionalCall', _47 => _47(scope, options, response, startedAt)]);
917
982
  return finish(response);
918
983
  }
919
984
 
@@ -1144,6 +1209,293 @@ function flattenContextItems(context) {
1144
1209
  return items;
1145
1210
  }
1146
1211
 
1212
+ // src/memories/parts.ts
1213
+ var OBJECTIVES = [
1214
+ "conversation",
1215
+ "bootstrap",
1216
+ "knowledge-base",
1217
+ "record",
1218
+ "profile"
1219
+ ];
1220
+ var MAX_FILE_BYTES = 10 * 1024 * 1024;
1221
+ var MAX_STREAM_IMAGE_BYTES = 2.5 * 1024 * 1024;
1222
+ var URL_FETCH_TIMEOUT_MS = 3e4;
1223
+ var PART_BRAND = /* @__PURE__ */ Symbol.for("@maximem/synap-js-sdk.ContentPart");
1224
+ function brand(part) {
1225
+ Object.defineProperty(part, PART_BRAND, { value: true, enumerable: false });
1226
+ return part;
1227
+ }
1228
+ function isBranded(value) {
1229
+ return typeof value === "object" && value !== null && PART_BRAND in value;
1230
+ }
1231
+ function textPart(text) {
1232
+ if (typeof text !== "string") throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("TextPart text must be a string");
1233
+ return brand({ type: "text", text });
1234
+ }
1235
+ function filePart(init) {
1236
+ const source = checkOneSource(init);
1237
+ const filename = defaultFilename(init, source);
1238
+ const mediaType = _nullishCoalesce(_nullishCoalesce(init.media_type, () => ( init.mediaType)), () => ( defaultMediaType(filename, _nullishCoalesce(init.data, () => ( void 0)))));
1239
+ const part = { type: "file" };
1240
+ if (source === "data") part.data = init.data;
1241
+ else if (source === "path") part.path = init.path;
1242
+ else part.url = init.url;
1243
+ part.filename = filename;
1244
+ part.media_type = mediaType;
1245
+ return brand(part);
1246
+ }
1247
+ function isTextPart(value) {
1248
+ return isPlainPart(value) && value["type"] === "text" && typeof value["text"] === "string";
1249
+ }
1250
+ function isFilePart(value) {
1251
+ return isPlainPart(value) && value["type"] === "file";
1252
+ }
1253
+ function isPlainPart(value) {
1254
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1255
+ }
1256
+ function checkOneSource(p) {
1257
+ const given = ["data", "path", "url"].filter(
1258
+ (k) => p[k] !== void 0 && p[k] !== null
1259
+ );
1260
+ if (given.length !== 1) {
1261
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1262
+ "FilePart takes exactly one of data, path or url" + (given.length > 0 ? ` (got ${given.join(", ")})` : "")
1263
+ );
1264
+ }
1265
+ return given[0];
1266
+ }
1267
+ function lastSegment(p) {
1268
+ const parts = p.split(/[\\/]/);
1269
+ return _nullishCoalesce(parts[parts.length - 1], () => ( ""));
1270
+ }
1271
+ function defaultFilename(p, source) {
1272
+ if (p.filename) return p.filename;
1273
+ if (source === "path") return lastSegment(String(p.path)) || "file";
1274
+ if (source === "url") {
1275
+ let pathname = "";
1276
+ try {
1277
+ pathname = new URL(String(p.url)).pathname;
1278
+ } catch (e5) {
1279
+ pathname = _nullishCoalesce(String(p.url).split(/[?#]/)[0], () => ( ""));
1280
+ }
1281
+ return lastSegment(pathname) || "file";
1282
+ }
1283
+ const named = _optionalChain([p, 'access', _48 => _48.data, 'optionalAccess', _49 => _49.name]);
1284
+ return typeof named === "string" && named ? named : "file";
1285
+ }
1286
+ var MEDIA_TYPES = {
1287
+ png: "image/png",
1288
+ jpg: "image/jpeg",
1289
+ jpeg: "image/jpeg",
1290
+ jpe: "image/jpeg",
1291
+ webp: "image/webp",
1292
+ gif: "image/gif",
1293
+ bmp: "image/bmp",
1294
+ tif: "image/tiff",
1295
+ tiff: "image/tiff",
1296
+ svg: "image/svg+xml",
1297
+ pdf: "application/pdf",
1298
+ txt: "text/plain",
1299
+ csv: "text/csv",
1300
+ htm: "text/html",
1301
+ html: "text/html",
1302
+ json: "application/json",
1303
+ doc: "application/msword",
1304
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1305
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1306
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1307
+ mp3: "audio/mpeg",
1308
+ wav: "audio/x-wav",
1309
+ mp4: "video/mp4"
1310
+ };
1311
+ function guessMediaType(filename) {
1312
+ const dot = filename.lastIndexOf(".");
1313
+ if (dot <= 0) return null;
1314
+ const ext = filename.slice(dot + 1).toLowerCase();
1315
+ return _nullishCoalesce(MEDIA_TYPES[ext], () => ( null));
1316
+ }
1317
+ function defaultMediaType(filename, data) {
1318
+ const guessed = guessMediaType(filename);
1319
+ if (guessed !== null) return guessed;
1320
+ const blobType = _optionalChain([data, 'optionalAccess', _50 => _50.type]);
1321
+ return typeof blobType === "string" && blobType ? blobType : DEFAULT_MEDIA_TYPE;
1322
+ }
1323
+ function normaliseContent(value, field) {
1324
+ if (isBranded(value) && isTextPart(value)) return { kind: "text", text: value.text };
1325
+ if (isBranded(value) && isFilePart(value)) return { kind: "parts", parts: [value] };
1326
+ if (!Array.isArray(value)) return null;
1327
+ if (value.length === 0) {
1328
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(`${field} is an empty list; pass at least one part`);
1329
+ }
1330
+ const parts = value.map((item, i) => {
1331
+ if (typeof item === "string") return { type: "text", text: item };
1332
+ if (isTextPart(item) || isFilePart(item)) return item;
1333
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1334
+ `${field}[${i}] is a ${typeName(item)}; expected a string, TextPart or FilePart`
1335
+ );
1336
+ });
1337
+ if (!parts.some(isFilePart)) {
1338
+ return { kind: "text", text: parts.map((p) => p.text).join("\n") };
1339
+ }
1340
+ return { kind: "parts", parts };
1341
+ }
1342
+ function typeName(value) {
1343
+ if (value === null) return "null";
1344
+ if (Array.isArray(value)) return "array";
1345
+ if (typeof value === "object") {
1346
+ return _nullishCoalesce(_optionalChain([value, 'access', _51 => _51.constructor, 'optionalAccess', _52 => _52.name]), () => ( "object"));
1347
+ }
1348
+ return typeof value;
1349
+ }
1350
+ async function resolveFile(part, fetchImpl) {
1351
+ const source = checkOneSource(part);
1352
+ const filename = defaultFilename(part, source);
1353
+ let mediaType = part.media_type || defaultMediaType(filename, part.data);
1354
+ let bytes;
1355
+ if (source === "data") {
1356
+ bytes = await toBytes(part.data);
1357
+ } else if (source === "path") {
1358
+ const { readFile } = await Promise.resolve().then(() => _interopRequireWildcard(require("fs/promises")));
1359
+ try {
1360
+ bytes = new Uint8Array(await readFile(part.path));
1361
+ } catch (error) {
1362
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1363
+ `Could not read FilePart path '${part.path}': ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _53 => _53.message]), () => ( String(error)))}`,
1364
+ { cause: error }
1365
+ );
1366
+ }
1367
+ } else {
1368
+ const fetched = await fetchUrl(part.url, fetchImpl);
1369
+ bytes = fetched.bytes;
1370
+ if (mediaType === DEFAULT_MEDIA_TYPE && fetched.contentType) mediaType = fetched.contentType;
1371
+ }
1372
+ if (bytes.byteLength > MAX_FILE_BYTES) {
1373
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1374
+ `${filename} is ${bytes.byteLength} bytes; the limit is ${MAX_FILE_BYTES} bytes per file`
1375
+ );
1376
+ }
1377
+ return { filename, media_type: mediaType, bytes };
1378
+ }
1379
+ var DEFAULT_MEDIA_TYPE = "application/octet-stream";
1380
+ function urlTooLarge(url) {
1381
+ return `FilePart url '${url}' is over the limit of ${MAX_FILE_BYTES} bytes per file`;
1382
+ }
1383
+ async function toBytes(data) {
1384
+ if (data instanceof Uint8Array) return data;
1385
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
1386
+ if (ArrayBuffer.isView(data)) {
1387
+ const view = data;
1388
+ return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
1389
+ }
1390
+ if (typeof Blob !== "undefined" && data instanceof Blob) {
1391
+ return new Uint8Array(await data.arrayBuffer());
1392
+ }
1393
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("FilePart data must be a Uint8Array, ArrayBuffer or Blob");
1394
+ }
1395
+ async function fetchUrl(url, fetchImpl) {
1396
+ let scheme = "";
1397
+ try {
1398
+ scheme = new URL(url).protocol;
1399
+ } catch (e6) {
1400
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(`Could not fetch FilePart url '${url}': not a valid URL`);
1401
+ }
1402
+ if (scheme !== "http:" && scheme !== "https:") {
1403
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1404
+ `Could not fetch FilePart url '${url}': only http and https are supported`
1405
+ );
1406
+ }
1407
+ const controller = new AbortController();
1408
+ const timer = setTimeout(() => controller.abort(), URL_FETCH_TIMEOUT_MS);
1409
+ try {
1410
+ const response = await fetchImpl(url, { method: "GET", signal: controller.signal });
1411
+ if (response.status < 200 || response.status >= 300) {
1412
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1413
+ `Fetching FilePart url '${url}' returned HTTP ${response.status}`
1414
+ );
1415
+ }
1416
+ const declared = Number(_nullishCoalesce(response.headers.get("content-length"), () => ( "")));
1417
+ if (Number.isFinite(declared) && declared > MAX_FILE_BYTES) {
1418
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(urlTooLarge(url));
1419
+ }
1420
+ const bytes = await readCapped(response, url);
1421
+ const rawType = response.headers.get("content-type");
1422
+ const contentType = rawType ? rawType.split(";", 1)[0].trim().toLowerCase() || null : null;
1423
+ return { bytes, contentType };
1424
+ } catch (error) {
1425
+ if (error instanceof _chunk7IZHVYO2cjs.InvalidInputError) throw error;
1426
+ if (controller.signal.aborted) {
1427
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1428
+ `Could not fetch FilePart url '${url}': timed out after ${URL_FETCH_TIMEOUT_MS / 1e3} s`,
1429
+ { cause: error }
1430
+ );
1431
+ }
1432
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1433
+ `Could not fetch FilePart url '${url}': ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _54 => _54.message]), () => ( String(error)))}`,
1434
+ { cause: error }
1435
+ );
1436
+ } finally {
1437
+ clearTimeout(timer);
1438
+ }
1439
+ }
1440
+ async function readCapped(response, url) {
1441
+ const body = response.body;
1442
+ if (body === null || typeof body.getReader !== "function") {
1443
+ return new Uint8Array(await response.arrayBuffer());
1444
+ }
1445
+ const reader = body.getReader();
1446
+ const chunks = [];
1447
+ let total = 0;
1448
+ for (; ; ) {
1449
+ const { done, value } = await reader.read();
1450
+ if (done) break;
1451
+ total += value.byteLength;
1452
+ if (total > MAX_FILE_BYTES) {
1453
+ await reader.cancel().catch(() => {
1454
+ });
1455
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(urlTooLarge(url));
1456
+ }
1457
+ chunks.push(value);
1458
+ }
1459
+ const out = new Uint8Array(total);
1460
+ let at = 0;
1461
+ for (const c of chunks) {
1462
+ out.set(c, at);
1463
+ at += c.byteLength;
1464
+ }
1465
+ return out;
1466
+ }
1467
+ function toBase64(bytes) {
1468
+ const B = globalThis.Buffer;
1469
+ if (B !== void 0) return B.from(bytes).toString("base64");
1470
+ let binary = "";
1471
+ const CHUNK = 32768;
1472
+ for (let i = 0; i < bytes.length; i += CHUNK) {
1473
+ binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
1474
+ }
1475
+ return btoa(binary);
1476
+ }
1477
+ function placeholderText(parts) {
1478
+ return parts.map((p) => p.type === "text" ? String(_nullishCoalesce(p.text, () => ( ""))) : `[image: ${p.filename || "image"}]`).join("\n");
1479
+ }
1480
+ async function toInlineParts(parts, fetchImpl) {
1481
+ const resolved = await Promise.all(
1482
+ parts.map((p) => isFilePart(p) ? resolveFile(p, fetchImpl) : null)
1483
+ );
1484
+ let rawBytes = 0;
1485
+ const wire = parts.map((p, i) => {
1486
+ const file = resolved[i];
1487
+ if (file === null || file === void 0) return { type: "text", text: p.text };
1488
+ rawBytes += file.bytes.byteLength;
1489
+ return {
1490
+ type: "image",
1491
+ filename: file.filename,
1492
+ media_type: file.media_type,
1493
+ data: toBase64(file.bytes)
1494
+ };
1495
+ });
1496
+ return { wire, placeholder: placeholderText(wire), rawBytes };
1497
+ }
1498
+
1147
1499
  // src/memories/interface.ts
1148
1500
  var DOCUMENT_TYPES = [
1149
1501
  "ai-chat-conversation",
@@ -1167,12 +1519,11 @@ function isoOrNull(v) {
1167
1519
  if (v === void 0 || v === null) return null;
1168
1520
  return v instanceof Date ? v.toISOString() : v;
1169
1521
  }
1170
- function buildCreateBody(options) {
1171
- if (!options.document) throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("document is required");
1522
+ function createFields(options, defaultType) {
1172
1523
  const o2 = options;
1173
- const documentType = _nullishCoalesce(either(o2, "document_type", "documentType"), () => ( DEFAULT_DOCUMENT_TYPE));
1524
+ const documentType = _nullishCoalesce(either(o2, "document_type", "documentType"), () => ( defaultType));
1174
1525
  const mode = _nullishCoalesce(options.mode, () => ( DEFAULT_INGEST_MODE));
1175
- if (!DOCUMENT_TYPES.includes(documentType)) {
1526
+ if (documentType !== null && !DOCUMENT_TYPES.includes(documentType)) {
1176
1527
  throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1177
1528
  `Invalid document_type '${documentType}'. Expected one of: ${DOCUMENT_TYPES.join(", ")}`
1178
1529
  );
@@ -1182,22 +1533,70 @@ function buildCreateBody(options) {
1182
1533
  `Invalid mode '${mode}'. Expected one of: ${INGEST_MODES.join(", ")}`
1183
1534
  );
1184
1535
  }
1185
- return {
1186
- document: options.document,
1536
+ const userId = _nullishCoalesce(either(o2, "user_id", "userId"), () => ( null));
1537
+ const customerId = _nullishCoalesce(either(o2, "customer_id", "customerId"), () => ( null));
1538
+ const fields = {
1187
1539
  document_type: documentType,
1188
1540
  document_id: _nullishCoalesce(either(o2, "document_id", "documentId"), () => ( null)),
1189
1541
  document_created_at: isoOrNull(
1190
1542
  either(o2, "document_created_at", "documentCreatedAt")
1191
1543
  ),
1192
- user_id: _nullishCoalesce(either(o2, "user_id", "userId"), () => ( null)),
1193
- customer_id: _nullishCoalesce(either(o2, "customer_id", "customerId"), () => ( null)),
1544
+ user_id: userId,
1545
+ customer_id: customerId,
1194
1546
  // null, never `{}`. An empty path is not absence: the server treats one as
1195
1547
  // an error, because a caller asking to be narrowed and being ignored gets
1196
1548
  // widened instead.
1197
- scope: _nullishCoalesce(options.scope, () => ( null)),
1549
+ scope: normaliseCreateScope(options.scope, userId, customerId),
1198
1550
  mode,
1199
1551
  metadata: _nullishCoalesce(options.metadata, () => ( {}))
1200
1552
  };
1553
+ if (options.objective !== void 0 && options.objective !== null) {
1554
+ fields["objective"] = options.objective;
1555
+ }
1556
+ return fields;
1557
+ }
1558
+ function normaliseCreateScope(scope, userId, customerId) {
1559
+ if (scope === void 0 || scope === null) return null;
1560
+ const entries = Object.entries(scope);
1561
+ if (entries.length > 1 && entries.some(([, v]) => v === "self")) {
1562
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1563
+ `"self" can only be used alone, as scope={"client": "self"}; got ${JSON.stringify(scope)}`
1564
+ );
1565
+ }
1566
+ if (entries.length === 1 && entries[0][0] === "client" && entries[0][1] === "self") {
1567
+ if (userId !== null || customerId !== null) {
1568
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1569
+ 'scope={"client": "self"} names the client level, so it cannot be combined with user_id or customer_id'
1570
+ );
1571
+ }
1572
+ return null;
1573
+ }
1574
+ return scope;
1575
+ }
1576
+ function jsonDocument(document, where) {
1577
+ const n2 = normaliseContent(document, "document");
1578
+ if (n2 === null) return document;
1579
+ if (n2.kind === "parts") {
1580
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1581
+ `${where} cannot carry a FilePart. memories.create sends files as multipart; call it once per document that has files.`
1582
+ );
1583
+ }
1584
+ return n2.text;
1585
+ }
1586
+ function buildCreateBody(options) {
1587
+ const document = jsonDocument(options.document, "This request");
1588
+ if (!document) throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("document is required");
1589
+ return { document, ...createFields(options, DEFAULT_DOCUMENT_TYPE) };
1590
+ }
1591
+ function buildCreateManifest(options, parts, files) {
1592
+ let next = 0;
1593
+ const document = parts.map((p) => {
1594
+ if (!isFilePart(p)) return { type: "text", text: p.text };
1595
+ const index = next++;
1596
+ const file = files[index];
1597
+ return { type: "file", field: `file_${index}`, filename: file.filename, media_type: file.media_type };
1598
+ });
1599
+ return { document, ...createFields(options, null) };
1201
1600
  }
1202
1601
  var FORGET_MODES = ["preview", "direct"];
1203
1602
  var FORGET_DESCRIPTION_MIN = 3;
@@ -1218,21 +1617,63 @@ function buildForgetBody(options) {
1218
1617
  );
1219
1618
  }
1220
1619
  const o2 = options;
1221
- return {
1620
+ const body = {
1222
1621
  description,
1223
1622
  user_id: _nullishCoalesce(either(o2, "user_id", "userId"), () => ( null)),
1224
1623
  customer_id: _nullishCoalesce(either(o2, "customer_id", "customerId"), () => ( null)),
1225
1624
  scope: _nullishCoalesce(options.scope, () => ( null)),
1226
1625
  mode
1227
1626
  };
1627
+ const conversationId = either(o2, "conversation_id", "conversationId");
1628
+ if (conversationId !== void 0 && conversationId !== null) {
1629
+ if (typeof conversationId !== "string" || [...conversationId].length < 1 || [...conversationId].length > 200) {
1630
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("conversation_id must be a string of 1 to 200 characters");
1631
+ }
1632
+ body["conversation_id"] = conversationId;
1633
+ }
1634
+ return body;
1228
1635
  }
1229
1636
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "partial_success", "error", "cancelled"]);
1230
1637
  function createMemoriesInterface(transport, onForgotten) {
1231
1638
  return {
1232
1639
  async create(options) {
1233
1640
  const o2 = options;
1234
- await transport.checkCustomerId(_nullishCoalesce(o2["customer_id"], () => ( o2["customerId"])), "memories.create");
1235
- return transport.request("memories_create", { body: buildCreateBody(options) });
1641
+ const customerId = _nullishCoalesce(o2["customer_id"], () => ( o2["customerId"]));
1642
+ if (customerId !== void 0 && customerId !== null && customerId !== "") {
1643
+ await transport.checkCustomerId(customerId, "memories.create");
1644
+ }
1645
+ const n2 = normaliseContent(options.document, "document");
1646
+ if (n2 === null || n2.kind === "text") {
1647
+ return transport.request("memories_create", {
1648
+ body: buildCreateBody(options)
1649
+ });
1650
+ }
1651
+ buildCreateManifest(options, n2.parts.filter((p) => !isFilePart(p)), []);
1652
+ const fetchImpl = ((url, init) => transport.fetchExternal(url, init));
1653
+ const files = await Promise.all(
1654
+ n2.parts.filter(isFilePart).map((p) => resolveFile(p, fetchImpl))
1655
+ );
1656
+ const form = new FormData();
1657
+ form.set("manifest", JSON.stringify(buildCreateManifest(options, n2.parts, files)));
1658
+ files.forEach((file, i) => {
1659
+ form.set(
1660
+ `file_${i}`,
1661
+ new Blob([file.bytes], { type: file.media_type }),
1662
+ file.filename
1663
+ );
1664
+ });
1665
+ return transport.request("memories_create_multipart", {
1666
+ body: form,
1667
+ rawBody: true,
1668
+ // A server older than this route answers 404, or 405 because
1669
+ // /api/v1/memories/{memory_id} exists with other methods. Either would
1670
+ // otherwise read as "context not found" or a bare HTTP error.
1671
+ // InvalidInputError, with Python's message.
1672
+ mapError: (status, error) => status === 404 || status === 405 ? new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1673
+ "This Synap server does not support file parts in memories.create. Upgrade the Synap server, or send text only.",
1674
+ { correlationId: error.correlationId, cause: error }
1675
+ ) : void 0
1676
+ });
1236
1677
  },
1237
1678
  async batch_create(options) {
1238
1679
  const docs = options.documents;
@@ -1241,7 +1682,13 @@ function createMemoriesInterface(transport, onForgotten) {
1241
1682
  }
1242
1683
  const failFast = _nullishCoalesce(_nullishCoalesce(options.fail_fast, () => ( options.failFast)), () => ( false));
1243
1684
  return transport.request("memories_batch", {
1244
- body: { documents: docs.map(buildCreateBody), fail_fast: failFast }
1685
+ body: {
1686
+ documents: docs.map((d) => {
1687
+ jsonDocument(d.document, "memories.batch_create");
1688
+ return buildCreateBody(d);
1689
+ }),
1690
+ fail_fast: failFast
1691
+ }
1245
1692
  });
1246
1693
  },
1247
1694
  async create_from_file(options) {
@@ -1327,14 +1774,14 @@ function createMemoriesInterface(transport, onForgotten) {
1327
1774
  await transport.checkCustomerId(_nullishCoalesce(o2["customer_id"], () => ( o2["customerId"])), "memories.forget");
1328
1775
  const body = buildForgetBody(options);
1329
1776
  const result = await transport.request("memories_forget", { body });
1330
- const removed = !!_optionalChain([result, 'optionalAccess', _46 => _46.deleted_ids, 'optionalAccess', _47 => _47.length]) || _optionalChain([result, 'optionalAccess', _48 => _48.status]) === "deleted" || _optionalChain([result, 'optionalAccess', _49 => _49.status]) === "partial";
1777
+ const removed = !!_optionalChain([result, 'optionalAccess', _55 => _55.deleted_ids, 'optionalAccess', _56 => _56.length]) || _optionalChain([result, 'optionalAccess', _57 => _57.status]) === "deleted" || _optionalChain([result, 'optionalAccess', _58 => _58.status]) === "partial";
1331
1778
  if (removed && onForgotten) {
1332
1779
  try {
1333
1780
  onForgotten({
1334
1781
  userId: _nullishCoalesce(body["user_id"], () => ( null)),
1335
1782
  customerId: _nullishCoalesce(body["customer_id"], () => ( null))
1336
1783
  });
1337
- } catch (e5) {
1784
+ } catch (e7) {
1338
1785
  }
1339
1786
  }
1340
1787
  return result;
@@ -1367,14 +1814,14 @@ function sleep2(ms, signal) {
1367
1814
  if (ms <= 0) return Promise.resolve();
1368
1815
  return new Promise((resolve, reject) => {
1369
1816
  const timer = setTimeout(() => {
1370
- _optionalChain([signal, 'optionalAccess', _50 => _50.removeEventListener, 'call', _51 => _51("abort", onAbort)]);
1817
+ _optionalChain([signal, 'optionalAccess', _59 => _59.removeEventListener, 'call', _60 => _60("abort", onAbort)]);
1371
1818
  resolve();
1372
1819
  }, ms);
1373
1820
  function onAbort() {
1374
1821
  clearTimeout(timer);
1375
- reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _52 => _52.reason]), () => ( new Error("Aborted"))));
1822
+ reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _61 => _61.reason]), () => ( new Error("Aborted"))));
1376
1823
  }
1377
- _optionalChain([signal, 'optionalAccess', _53 => _53.addEventListener, 'call', _54 => _54("abort", onAbort, { once: true })]);
1824
+ _optionalChain([signal, 'optionalAccess', _62 => _62.addEventListener, 'call', _63 => _63("abort", onAbort, { once: true })]);
1378
1825
  });
1379
1826
  }
1380
1827
 
@@ -1435,7 +1882,7 @@ function iso(v) {
1435
1882
  if (v === void 0) return void 0;
1436
1883
  return v instanceof Date ? v.toISOString() : v;
1437
1884
  }
1438
- function buildRecordMessageBody(options) {
1885
+ function buildRecordMessageBody(options, resolvedContent, field = "content") {
1439
1886
  const o2 = options;
1440
1887
  const conversationId = either2(o2, "conversation_id", "conversationId");
1441
1888
  const userId = either2(o2, "user_id", "userId");
@@ -1450,10 +1897,22 @@ function buildRecordMessageBody(options) {
1450
1897
  throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("content is required");
1451
1898
  }
1452
1899
  if (!userId) throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("user_id is required");
1900
+ let content = options.content;
1901
+ if (resolvedContent !== void 0) {
1902
+ content = resolvedContent;
1903
+ } else {
1904
+ const n2 = normaliseContent(options.content, field);
1905
+ if (_optionalChain([n2, 'optionalAccess', _64 => _64.kind]) === "parts") {
1906
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1907
+ "content holds a FilePart, whose bytes have to be read first. Send it with conversation.record_message."
1908
+ );
1909
+ }
1910
+ if (n2 !== null) content = n2.text;
1911
+ }
1453
1912
  const body = {
1454
1913
  conversation_id: conversationId,
1455
1914
  role: options.role,
1456
- content: options.content,
1915
+ content,
1457
1916
  user_id: userId,
1458
1917
  customer_id: customerId,
1459
1918
  // Python always sends this, defaulting to {}.
@@ -1554,7 +2013,7 @@ function storedBatchRows(bodies, result) {
1554
2013
  const r = _nullishCoalesce(result, () => ( {}));
1555
2014
  const results = Array.isArray(r["results"]) ? r["results"] : [];
1556
2015
  const errors = Array.isArray(r["errors"]) ? r["errors"] : [];
1557
- const failed = new Set(errors.map((e) => _optionalChain([e, 'optionalAccess', _55 => _55["index"]])));
2016
+ const failed = new Set(errors.map((e) => _optionalChain([e, 'optionalAccess', _65 => _65["index"]])));
1558
2017
  const stored = bodies.filter((_, index) => !failed.has(index));
1559
2018
  if (stored.length !== results.length) return [];
1560
2019
  const pairs = [];
@@ -1596,6 +2055,24 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1596
2055
  inFlight: _nullishCoalesce(writesInFlight.get(conversationId), () => ( 0))
1597
2056
  };
1598
2057
  };
2058
+ const fetchImpl = ((url, init) => transport.fetchExternal(url, init));
2059
+ const validateMessage = (options, field = "content") => {
2060
+ if (_optionalChain([normaliseContent, 'call', _66 => _66(options.content, field), 'optionalAccess', _67 => _67.kind]) === "parts") {
2061
+ buildRecordMessageBody(options, "", field);
2062
+ } else {
2063
+ buildRecordMessageBody(options, void 0, field);
2064
+ }
2065
+ };
2066
+ const prepareMessage = async (options, field = "content") => {
2067
+ const n2 = normaliseContent(options.content, field);
2068
+ if (_optionalChain([n2, 'optionalAccess', _68 => _68.kind]) !== "parts") {
2069
+ const body = buildRecordMessageBody(options, void 0, field);
2070
+ return { body, mirror: String(_nullishCoalesce(body["content"], () => ( ""))) };
2071
+ }
2072
+ validateMessage(options, field);
2073
+ const inline = await toInlineParts(n2.parts, fetchImpl);
2074
+ return { body: buildRecordMessageBody(options, inline.wire), mirror: inline.placeholder };
2075
+ };
1599
2076
  const convId = (v) => {
1600
2077
  const id = typeof v === "string" ? v : _nullishCoalesce(v.conversation_id, () => ( v.conversationId));
1601
2078
  if (!id) throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("conversation_id is required");
@@ -1608,7 +2085,9 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1608
2085
  _nullishCoalesce(options["customer_id"], () => ( options["customerId"])),
1609
2086
  "conversation.record_message"
1610
2087
  );
1611
- const body = withTurnModel(buildRecordMessageBody(options), options);
2088
+ const prepared = await prepareMessage(options);
2089
+ const body = withTurnModel(prepared.body, options);
2090
+ const mirror = prepared.mirror;
1612
2091
  const conversationId = String(_nullishCoalesce(body["conversation_id"], () => ( "")));
1613
2092
  writeStarted(conversationId);
1614
2093
  let result;
@@ -1620,7 +2099,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1620
2099
  onTurn({
1621
2100
  conversationId,
1622
2101
  role: String(_nullishCoalesce(body["role"], () => ( "user"))),
1623
- content: String(_nullishCoalesce(body["content"], () => ( ""))),
2102
+ content: mirror,
1624
2103
  timestamp: body["timestamp"],
1625
2104
  ...confirmation(result, conversationId)
1626
2105
  });
@@ -1641,7 +2120,11 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1641
2120
  "conversation.record_messages_batch"
1642
2121
  );
1643
2122
  }
1644
- const bodies = messages.map((m) => withTurnModel(buildRecordMessageBody(m), m));
2123
+ const field = (i) => `messages[${i}].content`;
2124
+ messages.forEach((m, i) => validateMessage(m, field(i)));
2125
+ const prepared = await Promise.all(messages.map((m, i) => prepareMessage(m, field(i))));
2126
+ const bodies = prepared.map((p, i) => withTurnModel(p.body, messages[i]));
2127
+ const mirrors = new Map(prepared.map((p, i) => [bodies[i], p.mirror]));
1645
2128
  const result = await transport.request("conversations_messages_batch", {
1646
2129
  body: { messages: bodies }
1647
2130
  });
@@ -1650,7 +2133,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1650
2133
  onTurn({
1651
2134
  conversationId,
1652
2135
  role: String(_nullishCoalesce(body["role"], () => ( "user"))),
1653
- content: String(_nullishCoalesce(body["content"], () => ( ""))),
2136
+ content: _nullishCoalesce(mirrors.get(body), () => ( String(_nullishCoalesce(body["content"], () => ( ""))))),
1654
2137
  timestamp: body["timestamp"],
1655
2138
  ...confirmation(row, conversationId)
1656
2139
  });
@@ -1673,7 +2156,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1673
2156
  const raw = await transport.request("conversations_ingest", { body });
1674
2157
  const result = {
1675
2158
  ...raw,
1676
- warnings: Array.isArray(_optionalChain([raw, 'optionalAccess', _56 => _56.warnings])) ? raw.warnings.map(String) : []
2159
+ warnings: Array.isArray(_optionalChain([raw, 'optionalAccess', _69 => _69.warnings])) ? raw.warnings.map(String) : []
1677
2160
  };
1678
2161
  onWrite({
1679
2162
  userId: body["user_id"],
@@ -1707,7 +2190,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1707
2190
  if (!search) return response2;
1708
2191
  try {
1709
2192
  return await localShortTerm.historyExcerpts(id, response2, options.query);
1710
- } catch (e6) {
2193
+ } catch (e8) {
1711
2194
  return response2;
1712
2195
  }
1713
2196
  };
@@ -1717,8 +2200,8 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1717
2200
  pathParams: { conversation_id: id },
1718
2201
  query: { style }
1719
2202
  });
1720
- const response = _nullishCoalesce(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _57 => _57["context_for_prompt"]]), () => ( result)), () => ( {}));
1721
- _optionalChain([localShortTerm, 'access', _58 => _58.reseed, 'optionalCall', _59 => _59(id, response)]);
2203
+ const response = _nullishCoalesce(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _70 => _70["context_for_prompt"]]), () => ( result)), () => ( {}));
2204
+ _optionalChain([localShortTerm, 'access', _71 => _71.reseed, 'optionalCall', _72 => _72(id, response)]);
1722
2205
  return withHistory(response);
1723
2206
  },
1724
2207
  async compact(options) {
@@ -1770,6 +2253,138 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1770
2253
  };
1771
2254
  }
1772
2255
 
2256
+ // src/data/interface.ts
2257
+ var DATA_SCOPES = ["user", "conversation", "customer"];
2258
+ var MAX_WAIT_CALLS = 50;
2259
+ var ID_FIELD = {
2260
+ user: "user_id",
2261
+ customer: "customer_id",
2262
+ conversation: "conversation_id"
2263
+ };
2264
+ function either3(o2, snake, camel) {
2265
+ const a = o2[snake];
2266
+ if (a !== void 0) return a;
2267
+ const b = o2[camel];
2268
+ return b === void 0 ? void 0 : b;
2269
+ }
2270
+ function buildDeleteBody(options, instanceId) {
2271
+ const o2 = options;
2272
+ const scope = options.scope;
2273
+ if (scope !== null && typeof scope === "object") {
2274
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
2275
+ "scope must be one of: user, conversation, customer. A dict is not accepted here (the rung-path dict used by memories.create and fetch is a different parameter)."
2276
+ );
2277
+ }
2278
+ if (typeof scope !== "string" || !DATA_SCOPES.includes(scope)) {
2279
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
2280
+ `Invalid scope '${String(scope)}'. Expected one of: ${DATA_SCOPES.join(", ")}`
2281
+ );
2282
+ }
2283
+ const dryRun = _nullishCoalesce(either3(o2, "dry_run", "dryRun"), () => ( false));
2284
+ if (typeof dryRun !== "boolean") throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("dry_run must be a boolean");
2285
+ const ids = {
2286
+ user_id: either3(o2, "user_id", "userId"),
2287
+ customer_id: either3(o2, "customer_id", "customerId"),
2288
+ conversation_id: either3(o2, "conversation_id", "conversationId")
2289
+ };
2290
+ for (const [name, value] of Object.entries(ids)) {
2291
+ if (value !== void 0 && value !== null && (typeof value !== "string" || value.trim() === "")) {
2292
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(`${name} must not be empty`);
2293
+ }
2294
+ }
2295
+ const field = ID_FIELD[scope];
2296
+ const target = ids[field];
2297
+ if (target === void 0 || target === null) {
2298
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(`${field} is required for scope='${scope}'`);
2299
+ }
2300
+ const confirm = _nullishCoalesce(options.confirm, () => ( null));
2301
+ if (!dryRun) {
2302
+ if (confirm === null || confirm === "") {
2303
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
2304
+ `confirm is required unless dry_run=True: pass the ${field} being deleted as confirm`
2305
+ );
2306
+ }
2307
+ if (confirm !== target) {
2308
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(`confirm must equal the ${field} being deleted`);
2309
+ }
2310
+ }
2311
+ return {
2312
+ scope,
2313
+ instance_id: instanceId,
2314
+ user_id: _nullishCoalesce(ids["user_id"], () => ( null)),
2315
+ customer_id: _nullishCoalesce(ids["customer_id"], () => ( null)),
2316
+ conversation_id: _nullishCoalesce(ids["conversation_id"], () => ( null)),
2317
+ dry_run: dryRun,
2318
+ confirm
2319
+ };
2320
+ }
2321
+ function normalise(raw) {
2322
+ return {
2323
+ deletion_id: null,
2324
+ status: "unknown",
2325
+ scope: null,
2326
+ dry_run: false,
2327
+ found: false,
2328
+ counts: {},
2329
+ stores: {},
2330
+ still_present_in: [],
2331
+ // Pessimistic: true only when the server said so.
2332
+ fully_removed: false,
2333
+ continue: false,
2334
+ kept: [],
2335
+ note: null,
2336
+ memories_kept: false,
2337
+ audit: null,
2338
+ local_cleared: [],
2339
+ ...raw
2340
+ };
2341
+ }
2342
+ function createDataInterface(transport, onDeleted) {
2343
+ return {
2344
+ async delete(options) {
2345
+ const o2 = options;
2346
+ await transport.checkCustomerId(
2347
+ either3(o2, "customer_id", "customerId"),
2348
+ "data.delete"
2349
+ );
2350
+ const body = buildDeleteBody(options, transport.currentCredentials().instanceId);
2351
+ const dryRun = body["dry_run"] === true;
2352
+ const wait = _nullishCoalesce(options.wait, () => ( true));
2353
+ let result = null;
2354
+ for (let i = 0; i < (wait ? MAX_WAIT_CALLS : 1); i += 1) {
2355
+ result = normalise(
2356
+ await transport.request("data_delete", { body })
2357
+ );
2358
+ if (dryRun || !result.continue) break;
2359
+ }
2360
+ const final = result;
2361
+ if (!dryRun && ["complete", "partial", "in_progress"].includes(final.status) && onDeleted) {
2362
+ try {
2363
+ final.local_cleared = onDeleted({
2364
+ scope: body["scope"],
2365
+ userId: _nullishCoalesce(body["user_id"], () => ( null)),
2366
+ customerId: _nullishCoalesce(body["customer_id"], () => ( null)),
2367
+ conversationId: _nullishCoalesce(body["conversation_id"], () => ( null))
2368
+ });
2369
+ } catch (e9) {
2370
+ }
2371
+ }
2372
+ return final;
2373
+ },
2374
+ async status(deletionId) {
2375
+ if (typeof deletionId !== "string" || deletionId.trim() === "") {
2376
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("deletion_id is required");
2377
+ }
2378
+ return normalise(
2379
+ await transport.request("data_delete_status", {
2380
+ pathParams: { deletion_id: deletionId },
2381
+ query: { instance_id: transport.currentCredentials().instanceId }
2382
+ })
2383
+ );
2384
+ }
2385
+ };
2386
+ }
2387
+
1773
2388
  // src/user/interface.ts
1774
2389
  function createUserNamespace(transport, hooks = {}) {
1775
2390
  return {
@@ -1847,6 +2462,7 @@ function createCacheNamespace(cache) {
1847
2462
  }
1848
2463
 
1849
2464
  // src/instance/interface.ts
2465
+ var CONTENT_PARTS_METADATA_KEY = "synap_content_parts";
1850
2466
  var DEFAULT_GRPC_HOST = "synap-cloud-prod.maximem.ai";
1851
2467
  var DEFAULT_GRPC_PORT = 443;
1852
2468
  function envPort() {
@@ -1894,16 +2510,23 @@ function jsonOrText(value) {
1894
2510
  (_k, v) => typeof v === "bigint" ? String(v) : v
1895
2511
  );
1896
2512
  return out === void 0 ? String(value) : out;
1897
- } catch (e7) {
2513
+ } catch (e10) {
1898
2514
  try {
1899
2515
  return String(value);
1900
- } catch (e8) {
2516
+ } catch (e11) {
1901
2517
  return "";
1902
2518
  }
1903
2519
  }
1904
2520
  }
1905
- function createInstanceNamespace(credentials, cache, onTurn, agentModel = () => ({}), onToolResult, checkCustomerId3 = async () => {
1906
- }) {
2521
+ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel, agentModelOrToolResult, onToolResultOrCheck, checkCustomerIdArg) {
2522
+ const defaultFetch = ((url, init) => globalThis.fetch(url, init));
2523
+ const imageFirst = fetchOrAgentModel !== void 0 && (fetchOrAgentModel.length > 0 || agentModelOrToolResult === void 0);
2524
+ const fetchUrl2 = imageFirst ? fetchOrAgentModel : defaultFetch;
2525
+ const agentModel = _nullishCoalesce((imageFirst ? agentModelOrToolResult : fetchOrAgentModel), () => ( (() => ({}))));
2526
+ const onToolResult = imageFirst ? onToolResultOrCheck : agentModelOrToolResult;
2527
+ const checkCustomerId3 = _nullishCoalesce((imageFirst ? checkCustomerIdArg : onToolResultOrCheck), () => ( (async () => {
2528
+ })));
2529
+ const hasCustomerIdCheck = (imageFirst ? checkCustomerIdArg : onToolResultOrCheck) !== void 0;
1907
2530
  let client = null;
1908
2531
  const openSessions = /* @__PURE__ */ new Map();
1909
2532
  let dispatchCompaction = null;
@@ -1912,8 +2535,8 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
1912
2535
  let onConversationState = null;
1913
2536
  const internals = {
1914
2537
  onCompactionUpdate(conversationId, bundle) {
1915
- _optionalChain([applyCompaction, 'optionalCall', _60 => _60(bundle)]);
1916
- _optionalChain([dispatchCompaction, 'optionalCall', _61 => _61(conversationId, bundle)]);
2538
+ _optionalChain([applyCompaction, 'optionalCall', _73 => _73(bundle)]);
2539
+ _optionalChain([dispatchCompaction, 'optionalCall', _74 => _74(conversationId, bundle)]);
1917
2540
  },
1918
2541
  setCompactionApplier(apply) {
1919
2542
  applyCompaction = apply;
@@ -1925,10 +2548,10 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
1925
2548
  onConversationState = handle;
1926
2549
  },
1927
2550
  sendContextUsed(event) {
1928
- _optionalChain([client, 'optionalAccess', _62 => _62.sendContextUsed, 'call', _63 => _63(event)]);
2551
+ _optionalChain([client, 'optionalAccess', _75 => _75.sendContextUsed, 'call', _76 => _76(event)]);
1929
2552
  },
1930
2553
  sendContextAssembled(event) {
1931
- _optionalChain([client, 'optionalAccess', _64 => _64.sendContextAssembled, 'call', _65 => _65(event)]);
2554
+ _optionalChain([client, 'optionalAccess', _77 => _77.sendContextAssembled, 'call', _78 => _78(event)]);
1932
2555
  },
1933
2556
  setCompactionDispatcher(dispatch) {
1934
2557
  dispatchCompaction = dispatch;
@@ -1950,19 +2573,38 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
1950
2573
  ...customerId ? { customer_id: customerId } : {}
1951
2574
  });
1952
2575
  openSessions.set(conversationId, sessionId);
1953
- } catch (e9) {
2576
+ } catch (e12) {
1954
2577
  }
1955
2578
  }
2579
+ let tail = Promise.resolve();
2580
+ let queued = 0;
2581
+ function inOrder(prepared, send, sync) {
2582
+ if (prepared === null && queued === 0) {
2583
+ send(sync);
2584
+ return Promise.resolve();
2585
+ }
2586
+ _optionalChain([prepared, 'optionalAccess', _79 => _79.catch, 'call', _80 => _80(() => {
2587
+ })]);
2588
+ queued += 1;
2589
+ const run = tail.then(async () => {
2590
+ send(prepared === null ? sync : await prepared);
2591
+ });
2592
+ const done = () => {
2593
+ queued -= 1;
2594
+ };
2595
+ tail = run.then(done, done);
2596
+ return run;
2597
+ }
1956
2598
  const namespace = {
1957
2599
  async listen(options = {}) {
1958
2600
  if (client !== null) {
1959
2601
  throw new (0, _chunk7IZHVYO2cjs.ListeningAlreadyActiveError)("Listening is already active on this instance");
1960
2602
  }
1961
2603
  try {
1962
- _optionalChain([onListen, 'optionalCall', _66 => _66()]);
1963
- } catch (e10) {
2604
+ _optionalChain([onListen, 'optionalCall', _81 => _81()]);
2605
+ } catch (e13) {
1964
2606
  }
1965
- const { GrpcStreamClient } = await Promise.resolve().then(() => _interopRequireWildcard(require("./stream-client-SZIYGVVJ.cjs")));
2607
+ const { GrpcStreamClient } = await Promise.resolve().then(() => _interopRequireWildcard(require("./stream-client-BY5LNLVB.cjs")));
1966
2608
  const onContext = _nullishCoalesce(options.on_context, () => ( options.onContext));
1967
2609
  const onDisconnect = _nullishCoalesce(options.on_disconnect, () => ( options.onDisconnect));
1968
2610
  const onReconnect = _nullishCoalesce(options.on_reconnect, () => ( options.onReconnect));
@@ -1977,17 +2619,17 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
1977
2619
  internals.onCompactionUpdate(conversationId, bundle);
1978
2620
  },
1979
2621
  onConversationState: (conversationId, messageCount) => {
1980
- _optionalChain([onConversationState, 'optionalCall', _67 => _67(conversationId, messageCount)]);
2622
+ _optionalChain([onConversationState, 'optionalCall', _82 => _82(conversationId, messageCount)]);
1981
2623
  },
1982
2624
  onStateChange: (state) => {
1983
2625
  if (state !== "connected") openSessions.clear();
1984
2626
  if (state === "reconnecting") {
1985
2627
  reconnectAttempts += 1;
1986
- _optionalChain([onReconnect, 'optionalCall', _68 => _68(reconnectAttempts)]);
2628
+ _optionalChain([onReconnect, 'optionalCall', _83 => _83(reconnectAttempts)]);
1987
2629
  } else if (state === "disconnected") {
1988
- const stopped = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _69 => _69.lastError]), () => ( null));
2630
+ const stopped = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _84 => _84.lastError]), () => ( null));
1989
2631
  const reason = stopped === null ? "stream disconnected" : `credit_stop:${_nullishCoalesce(stopped.reason, () => ( "unknown"))}`;
1990
- _optionalChain([onDisconnect, 'optionalCall', _70 => _70(reason)]);
2632
+ _optionalChain([onDisconnect, 'optionalCall', _85 => _85(reason)]);
1991
2633
  }
1992
2634
  }
1993
2635
  });
@@ -1997,7 +2639,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
1997
2639
  } catch (error) {
1998
2640
  if (error instanceof _chunk7IZHVYO2cjs.SynapError) throw error;
1999
2641
  throw new (0, _chunk7IZHVYO2cjs.SynapError)(
2000
- `Could not open the Synap anticipation stream: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _71 => _71.message]), () => ( String(error)))}`,
2642
+ `Could not open the Synap anticipation stream: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _86 => _86.message]), () => ( String(error)))}`,
2001
2643
  { cause: error }
2002
2644
  );
2003
2645
  }
@@ -2022,14 +2664,16 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2022
2664
  session_id: sessionId,
2023
2665
  conversation_id: conversationId
2024
2666
  });
2025
- } catch (e11) {
2667
+ } catch (e14) {
2026
2668
  }
2027
2669
  },
2028
2670
  async send_message(options) {
2029
- await checkCustomerId3(
2030
- _nullishCoalesce(options.customer_id, () => ( options.customerId)),
2031
- "instance.send_message"
2032
- );
2671
+ if (hasCustomerIdCheck) {
2672
+ await checkCustomerId3(
2673
+ _nullishCoalesce(options.customer_id, () => ( options.customerId)),
2674
+ "instance.send_message"
2675
+ );
2676
+ }
2033
2677
  if (client === null) throw new (0, _chunk7IZHVYO2cjs.ListeningNotActiveError)("Listening is not active");
2034
2678
  const eventType = _nullishCoalesce(_nullishCoalesce(options.event_type, () => ( options.eventType)), () => ( "user_message"));
2035
2679
  if (!KNOWN_EVENT_TYPES.has(eventType)) {
@@ -2040,46 +2684,68 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2040
2684
  if (options.content === void 0 || options.content === null) {
2041
2685
  throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("content is required");
2042
2686
  }
2043
- const conversationId = _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( ""));
2044
- ensureSession(
2045
- conversationId,
2046
- _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2047
- _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( ""))
2048
- );
2049
- if (eventType === "user_message" || eventType === "assistant_message") {
2050
- _optionalChain([onTurn, 'optionalCall', _72 => _72({
2687
+ const parts = normaliseContent(options.content, "content");
2688
+ const emit = ({ content, metadata }) => {
2689
+ if (client === null) throw new (0, _chunk7IZHVYO2cjs.ListeningNotActiveError)("Listening is not active");
2690
+ const conversationId = _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( ""));
2691
+ ensureSession(
2051
2692
  conversationId,
2693
+ _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2694
+ _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( ""))
2695
+ );
2696
+ if (eventType === "user_message" || eventType === "assistant_message") {
2697
+ _optionalChain([onTurn, 'optionalCall', _87 => _87({
2698
+ conversationId,
2699
+ role: _nullishCoalesce(options.role, () => ( "user")),
2700
+ content
2701
+ })]);
2702
+ }
2703
+ client.sendConversationEvent({
2704
+ event_type: eventType,
2705
+ content,
2052
2706
  role: _nullishCoalesce(options.role, () => ( "user")),
2053
- content: options.content
2054
- })]);
2707
+ conversation_id: _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( "")),
2708
+ user_id: _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2709
+ customer_id: _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( "")),
2710
+ session_id: _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(options.session_id, () => ( options.sessionId)), () => ( openSessions.get(conversationId))), () => ( "")),
2711
+ metadata: _nullishCoalesce(withAgentModel(metadata, agentModelOf(options), agentModel(), true), () => ( {})),
2712
+ timestamp_ms: Date.now(),
2713
+ tool_name: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")),
2714
+ // Python serialises tool_args with json.dumps into tool_args_json.
2715
+ tool_args_json: (() => {
2716
+ const a = _nullishCoalesce(options.tool_args, () => ( options.toolArgs));
2717
+ return a === void 0 ? "" : jsonOrText(a);
2718
+ })(),
2719
+ tool_result_json: toolResultJson(_nullishCoalesce(options.tool_result, () => ( options.toolResult))),
2720
+ tool_call_id: _nullishCoalesce(_nullishCoalesce(options.tool_call_id, () => ( options.toolCallId)), () => ( "")),
2721
+ search_queries: _nullishCoalesce(_nullishCoalesce(options.search_queries, () => ( options.searchQueries)), () => ( [])),
2722
+ context_types: _nullishCoalesce(_nullishCoalesce(options.context_types, () => ( options.contextTypes)), () => ( [])),
2723
+ ...(() => {
2724
+ const sp = _nullishCoalesce(options.scope_path, () => ( options.scopePath));
2725
+ return sp && Object.keys(sp).length > 0 ? { scope: sp } : {};
2726
+ })()
2727
+ });
2728
+ };
2729
+ if (_optionalChain([parts, 'optionalAccess', _88 => _88.kind]) !== "parts") {
2730
+ const content = _optionalChain([parts, 'optionalAccess', _89 => _89.kind]) === "text" ? parts.text : options.content;
2731
+ return inOrder(null, emit, { content, metadata: _nullishCoalesce(options.metadata, () => ( {})) });
2055
2732
  }
2056
- client.sendConversationEvent({
2057
- event_type: eventType,
2058
- content: options.content,
2059
- role: _nullishCoalesce(options.role, () => ( "user")),
2060
- conversation_id: _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( "")),
2061
- user_id: _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2062
- customer_id: _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( "")),
2063
- session_id: _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(options.session_id, () => ( options.sessionId)), () => ( openSessions.get(conversationId))), () => ( "")),
2064
- metadata: _nullishCoalesce(withAgentModel(options.metadata, agentModelOf(options), agentModel(), true), () => ( {})),
2065
- timestamp_ms: Date.now(),
2066
- tool_name: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")),
2067
- // Python serialises tool_args with json.dumps into tool_args_json.
2068
- tool_args_json: (() => {
2069
- const a = _nullishCoalesce(options.tool_args, () => ( options.toolArgs));
2070
- return a === void 0 ? "" : jsonOrText(a);
2071
- })(),
2072
- tool_result_json: toolResultJson(_nullishCoalesce(options.tool_result, () => ( options.toolResult))),
2073
- tool_call_id: _nullishCoalesce(_nullishCoalesce(options.tool_call_id, () => ( options.toolCallId)), () => ( "")),
2074
- search_queries: _nullishCoalesce(_nullishCoalesce(options.search_queries, () => ( options.searchQueries)), () => ( [])),
2075
- context_types: _nullishCoalesce(_nullishCoalesce(options.context_types, () => ( options.contextTypes)), () => ( [])),
2076
- // The proto's `scope`: the conversation's rung, kept from the first
2077
- // event that names one. Omitted when absent or empty, as in Python.
2078
- ...(() => {
2079
- const sp = _nullishCoalesce(options.scope_path, () => ( options.scopePath));
2080
- return sp && Object.keys(sp).length > 0 ? { scope: sp } : {};
2081
- })()
2082
- });
2733
+ const prepared = (async () => {
2734
+ const inline = await toInlineParts(parts.parts, fetchUrl2);
2735
+ if (inline.rawBytes > MAX_STREAM_IMAGE_BYTES) {
2736
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
2737
+ `The images in this event come to more than ${MAX_STREAM_IMAGE_BYTES} bytes, which is over what one streamed event can carry. Send them with memories.create or conversation.record_message instead.`
2738
+ );
2739
+ }
2740
+ return {
2741
+ content: inline.placeholder,
2742
+ metadata: {
2743
+ ..._nullishCoalesce(options.metadata, () => ( {})),
2744
+ [CONTENT_PARTS_METADATA_KEY]: JSON.stringify(inline.wire)
2745
+ }
2746
+ };
2747
+ })();
2748
+ return inOrder(prepared, emit);
2083
2749
  },
2084
2750
  async record_tool_call(options) {
2085
2751
  await namespace.send_message({
@@ -2099,7 +2765,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2099
2765
  async record_tool_result(options) {
2100
2766
  const conversationId = _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( ""));
2101
2767
  if (conversationId) {
2102
- _optionalChain([onToolResult, 'optionalCall', _73 => _73({ conversationId, result: options.result, toolName: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")) })]);
2768
+ _optionalChain([onToolResult, 'optionalCall', _90 => _90({ conversationId, result: options.result, toolName: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")) })]);
2103
2769
  }
2104
2770
  await namespace.send_message({
2105
2771
  content: "",
@@ -2123,24 +2789,27 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2123
2789
  _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2124
2790
  _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( ""))
2125
2791
  );
2126
- client.sendConversationEvent({
2127
- // Python emits reasoning as an `agent_thinking` conversation event.
2128
- event_type: "agent_thinking",
2129
- content: options.content,
2130
- // Deliberately no role. A thought is not the assistant's reply, and
2131
- // this went out as 'assistant' from the day it shipped: the server
2132
- // checked role before event_type, so every reasoning step any client
2133
- // sent was filed as the final answer and the reasoning path never ran.
2134
- // Sending no role is correct against both the fixed server and one that
2135
- // has not been updated yet.
2136
- role: "",
2137
- conversation_id: _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( "")),
2138
- user_id: _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2139
- customer_id: _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( "")),
2140
- session_id: _nullishCoalesce(_nullishCoalesce(options.session_id, () => ( options.sessionId)), () => ( "")),
2141
- metadata: thinkingMetadata(options),
2142
- timestamp_ms: Date.now()
2143
- });
2792
+ return inOrder(null, () => {
2793
+ if (client === null) throw new (0, _chunk7IZHVYO2cjs.ListeningNotActiveError)("Listening is not active");
2794
+ client.sendConversationEvent({
2795
+ // Python emits reasoning as an `agent_thinking` conversation event.
2796
+ event_type: "agent_thinking",
2797
+ content: options.content,
2798
+ // Deliberately no role. A thought is not the assistant's reply, and
2799
+ // this went out as 'assistant' from the day it shipped: the server
2800
+ // checked role before event_type, so every reasoning step any client
2801
+ // sent was filed as the final answer and the reasoning path never ran.
2802
+ // Sending no role is correct against both the fixed server and one that
2803
+ // has not been updated yet.
2804
+ role: "",
2805
+ conversation_id: _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( "")),
2806
+ user_id: _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2807
+ customer_id: _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( "")),
2808
+ session_id: _nullishCoalesce(_nullishCoalesce(options.session_id, () => ( options.sessionId)), () => ( "")),
2809
+ metadata: thinkingMetadata(options),
2810
+ timestamp_ms: Date.now()
2811
+ });
2812
+ }, void 0);
2144
2813
  },
2145
2814
  get is_listening() {
2146
2815
  return client !== null && client.isConnected;
@@ -2151,7 +2820,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2151
2820
  }
2152
2821
 
2153
2822
  // src/version.ts
2154
- var SDK_VERSION = "0.6.1";
2823
+ var SDK_VERSION = "0.6.6";
2155
2824
 
2156
2825
  // src/registry.ts
2157
2826
  var instances = /* @__PURE__ */ new Map();
@@ -2291,7 +2960,7 @@ var ShortTermStore = class {
2291
2960
  if (this.#archive !== null) {
2292
2961
  try {
2293
2962
  this.#archive.add(conversationId, role, content, stamp, { messageId: _nullishCoalesce(confirmation.messageId, () => ( null)) });
2294
- } catch (e12) {
2963
+ } catch (e15) {
2295
2964
  }
2296
2965
  }
2297
2966
  const entry = _nullishCoalesce(this.#entries.get(conversationId), () => ( this.#blank(conversationId)));
@@ -2505,7 +3174,7 @@ var TurnStore = (_class3 = class {
2505
3174
  #conversations = /* @__PURE__ */ new Map();
2506
3175
  #vectors = /* @__PURE__ */ new Map();
2507
3176
  constructor(options = {}) {;_class3.prototype.__init6.call(this);
2508
- this.limits = _nullishCoalesce(options.limits, () => ( { ..._chunkICUFS3B5cjs.HISTORY_SEARCH.store_limits }));
3177
+ this.limits = _nullishCoalesce(options.limits, () => ( { ..._chunkBYUGILQIcjs.HISTORY_SEARCH.store_limits }));
2509
3178
  this.#now = _nullishCoalesce(options.now, () => ( (() => Date.now() / 1e3)));
2510
3179
  }
2511
3180
  add(conversationId, role, content, timestamp, options = {}) {
@@ -2619,7 +3288,7 @@ var TurnStore = (_class3 = class {
2619
3288
  }
2620
3289
  /** Turns the server also holds: archived tool results are local only. Python: `count`. */
2621
3290
  count(conversationId) {
2622
- return (_nullishCoalesce(_optionalChain([this, 'access', _74 => _74.#conversations, 'access', _75 => _75.get, 'call', _76 => _76(conversationId), 'optionalAccess', _77 => _77.turns]), () => ( []))).filter((t) => t.role !== "tool").length;
3291
+ return (_nullishCoalesce(_optionalChain([this, 'access', _91 => _91.#conversations, 'access', _92 => _92.get, 'call', _93 => _93(conversationId), 'optionalAccess', _94 => _94.turns]), () => ( []))).filter((t) => t.role !== "tool").length;
2623
3292
  }
2624
3293
  sizeBytes() {
2625
3294
  let n2 = 0;
@@ -2649,11 +3318,11 @@ var TurnStore = (_class3 = class {
2649
3318
 
2650
3319
  // src/cache/history-search.ts
2651
3320
  var WORD_RE = /[\p{L}\p{N}\p{M}]+/gu;
2652
- var FORMS = _nullishCoalesce(_chunkICUFS3B5cjs.HISTORY_SEARCH.irregular_forms, () => ( {}));
3321
+ var FORMS = _nullishCoalesce(_chunkBYUGILQIcjs.HISTORY_SEARCH.irregular_forms, () => ( {}));
2653
3322
  function tokenize2(text) {
2654
3323
  const out = [];
2655
3324
  for (const word of _nullishCoalesce((text || "").toLowerCase().match(WORD_RE), () => ( []))) {
2656
- if (/^[\x00-\x7f]+$/.test(word)) out.push(..._chunkICUFS3B5cjs.tokenize.call(void 0, _nullishCoalesce(FORMS[word], () => ( word))));
3325
+ if (/^[\x00-\x7f]+$/.test(word)) out.push(..._chunkBYUGILQIcjs.tokenize.call(void 0, _nullishCoalesce(FORMS[word], () => ( word))));
2657
3326
  else out.push(word);
2658
3327
  }
2659
3328
  return out;
@@ -2790,19 +3459,19 @@ function windowsOf(pieces, maxWords) {
2790
3459
  }
2791
3460
  function askedKinds(query) {
2792
3461
  const out = [];
2793
- for (const [name, spec] of Object.entries(_nullishCoalesce(_chunkICUFS3B5cjs.HISTORY_SEARCH.asked_kinds, () => ( {})))) {
3462
+ for (const [name, spec] of Object.entries(_nullishCoalesce(_chunkBYUGILQIcjs.HISTORY_SEARCH.asked_kinds, () => ( {})))) {
2794
3463
  if (name.startsWith("$") || typeof spec !== "object") continue;
2795
3464
  if (new RegExp(spec.query, "i").test(_nullishCoalesce(query, () => ( "")))) out.push(new RegExp(spec.value));
2796
3465
  }
2797
3466
  return out;
2798
3467
  }
2799
3468
  function asksHowItStarted(query) {
2800
- const spec = _chunkICUFS3B5cjs.HISTORY_SEARCH.early_query;
2801
- if (!_optionalChain([spec, 'optionalAccess', _78 => _78.pattern])) return false;
3469
+ const spec = _chunkBYUGILQIcjs.HISTORY_SEARCH.early_query;
3470
+ if (!_optionalChain([spec, 'optionalAccess', _95 => _95.pattern])) return false;
2802
3471
  return new RegExp(spec.pattern, (_nullishCoalesce(spec.flags, () => ( ""))).includes("i") ? "i" : "").test(_nullishCoalesce(query, () => ( "")));
2803
3472
  }
2804
3473
  async function searchTurns(turns, query, options = {}) {
2805
- const params = _chunkICUFS3B5cjs.HISTORY_SEARCH;
3474
+ const params = _chunkBYUGILQIcjs.HISTORY_SEARCH;
2806
3475
  const k = params.max_excerpts;
2807
3476
  const skip = new Set(_nullishCoalesce(options.exclude, () => ( [])));
2808
3477
  const pool = turns.filter((t) => t.content && !skip.has(t.content) && !skip.has(_nullishCoalesce(t.message_id, () => ( ""))));
@@ -2829,7 +3498,7 @@ async function searchTurns(turns, query, options = {}) {
2829
3498
  });
2830
3499
  });
2831
3500
  const docs = units.map((u) => tokenize2(u.content));
2832
- const bm = new (0, _chunkICUFS3B5cjs.BM25)(docs);
3501
+ const bm = new (0, _chunkBYUGILQIcjs.BM25)(docs);
2833
3502
  const termList = [...terms];
2834
3503
  const rows = units.map((turn, i) => {
2835
3504
  const held = new Set(docs[i]);
@@ -2967,13 +3636,13 @@ async function embeddingRanks(pool, query, encoder, store, minCosine) {
2967
3636
  }
2968
3637
  function toolResultText(result, toolName) {
2969
3638
  let text = typeof result === "string" ? result : _nullishCoalesce(JSON.stringify(result), () => ( String(result)));
2970
- const limit = _nullishCoalesce(_chunkICUFS3B5cjs.HISTORY_SEARCH.tool_result_max_chars, () => ( 16e3));
3639
+ const limit = _nullishCoalesce(_chunkBYUGILQIcjs.HISTORY_SEARCH.tool_result_max_chars, () => ( 16e3));
2971
3640
  if (text.length > limit) text = text.slice(0, limit) + " ...[cut]";
2972
3641
  return `[tool result: ${toolName || "tool"}] ${text}`;
2973
3642
  }
2974
3643
  function renderExcerpts(excerpts, latest = "") {
2975
3644
  if (excerpts.length === 0) return "";
2976
- const lines = [_chunkICUFS3B5cjs.HISTORY_SEARCH.heading];
3645
+ const lines = [_chunkBYUGILQIcjs.HISTORY_SEARCH.heading];
2977
3646
  for (const e of excerpts) {
2978
3647
  let where = e.position ? `turn ${e.position}, ${e.role}` : `${e.role}, earlier`;
2979
3648
  if (e.timestamp) {
@@ -3066,7 +3735,7 @@ function overlayLocalRecentTurns(response, store, conversationId, configured) {
3066
3735
  compacted_at: orLocal("compacted_at", entry.compactedAt),
3067
3736
  conversation_id: conversationId
3068
3737
  };
3069
- } catch (e13) {
3738
+ } catch (e16) {
3070
3739
  }
3071
3740
  }
3072
3741
 
@@ -3079,7 +3748,7 @@ function stringify(value) {
3079
3748
  if (t === "string" || t === "number" || t === "boolean") return String(value);
3080
3749
  try {
3081
3750
  return _nullishCoalesce(JSON.stringify(value), () => ( ""));
3082
- } catch (e14) {
3751
+ } catch (e17) {
3083
3752
  return String(value);
3084
3753
  }
3085
3754
  }
@@ -3283,7 +3952,7 @@ function pick2(item, ...names) {
3283
3952
  }
3284
3953
  return void 0;
3285
3954
  }
3286
- function normalise(item) {
3955
+ function normalise2(item) {
3287
3956
  const content = _nullishCoalesce(pick2(item, "content"), () => ( ""));
3288
3957
  const confidence = _nullishCoalesce(pick2(item, "confidence"), () => ( 0));
3289
3958
  const extractedAt = _nullishCoalesce(pick2(item, "extracted_at", "created_at"), () => ( null));
@@ -3318,7 +3987,7 @@ function mergeUserSummary(response, bundle) {
3318
3987
  if (!Array.isArray(items)) continue;
3319
3988
  const existing = _nullishCoalesce(response[collection], () => ( []));
3320
3989
  const existingIds = new Set(existing.map((i) => String(_nullishCoalesce(_nullishCoalesce(i.id, () => ( i.item_id)), () => ( "")))));
3321
- const fresh = items.filter((i) => typeof i === "object" && i !== null && !existingIds.has(itemId(i))).slice(0, MAX_SUMMARY_ITEMS).map(normalise);
3990
+ const fresh = items.filter((i) => typeof i === "object" && i !== null && !existingIds.has(itemId(i))).slice(0, MAX_SUMMARY_ITEMS).map(normalise2);
3322
3991
  if (fresh.length === 0) continue;
3323
3992
  response[collection] = [...existing, ...fresh];
3324
3993
  }
@@ -3327,16 +3996,16 @@ function mergeUserSummary(response, bundle) {
3327
3996
 
3328
3997
  // src/context/anticipated.ts
3329
3998
  function scopeLookupParams(scope, params) {
3330
- const { searchQuery, entityId, customerId, clientId, conversationId, scopeRung } = params;
3999
+ const { searchQuery, entityId, customerId, clientId, conversationId, scopeRung, maxResultsPerQuery } = params;
3331
4000
  switch (scope) {
3332
4001
  case "conversation":
3333
- return { searchQuery, entityId, customerId, clientId, conversationId, scopeRung };
4002
+ return { searchQuery, entityId, customerId, clientId, conversationId, scopeRung, maxResultsPerQuery };
3334
4003
  case "user":
3335
- return { searchQuery, entityId, customerId, clientId, scopeRung };
4004
+ return { searchQuery, entityId, customerId, clientId, scopeRung, maxResultsPerQuery };
3336
4005
  case "customer":
3337
- return { searchQuery, entityId: null, customerId, clientId, scopeRung };
4006
+ return { searchQuery, entityId: null, customerId, clientId, scopeRung, maxResultsPerQuery };
3338
4007
  case "client":
3339
- return { searchQuery, entityId: null, customerId: null, clientId, scopeRung };
4008
+ return { searchQuery, entityId: null, customerId: null, clientId, scopeRung, maxResultsPerQuery };
3340
4009
  }
3341
4010
  }
3342
4011
  function buildAnticipationResponse(hit) {
@@ -3372,11 +4041,12 @@ async function tryServeFromCache(cache, scope, params, maxItems) {
3372
4041
  clientId: _nullishCoalesce(scoped.clientId, () => ( null)),
3373
4042
  conversationId: _nullishCoalesce(scoped.conversationId, () => ( null)),
3374
4043
  scopeRung: _nullishCoalesce(scoped.scopeRung, () => ( null)),
3375
- maxItems
4044
+ maxItems,
4045
+ maxResultsPerQuery: _nullishCoalesce(scoped.maxResultsPerQuery, () => ( null))
3376
4046
  });
3377
4047
  if (hit === null) return { response: null, hit: null };
3378
4048
  return { response: buildAnticipationResponse(hit), hit };
3379
- } catch (e15) {
4049
+ } catch (e18) {
3380
4050
  return { response: null, hit: null };
3381
4051
  }
3382
4052
  }
@@ -3875,6 +4545,7 @@ var SynapClient = (_class4 = class _SynapClient {
3875
4545
 
3876
4546
 
3877
4547
 
4548
+
3878
4549
  #closed = false;
3879
4550
  #initialized = false;
3880
4551
  #identity;
@@ -3929,12 +4600,11 @@ var SynapClient = (_class4 = class _SynapClient {
3929
4600
  });
3930
4601
  if (options.heartbeat) this.#transport.startHeartbeat();
3931
4602
  this.#transport.identityResolver = () => this.#resolveIdentity();
3932
- this.#anticipationCache = new (0, _chunkICUFS3B5cjs.AnticipationCache)();
4603
+ this.#anticipationCache = new (0, _chunkBYUGILQIcjs.AnticipationCache)();
3933
4604
  this.#fetchHooks = {
3934
4605
  beforeFetch: async (scope, options2) => {
3935
4606
  const o2 = options2;
3936
4607
  if (_nullishCoalesce(o2["query_date"], () => ( o2["queryDate"]))) return null;
3937
- if (_nullishCoalesce(o2["max_results_per_query"], () => ( o2["maxResultsPerQuery"]))) return null;
3938
4608
  const attempt = await tryServeFromCache(
3939
4609
  this.#anticipationCache,
3940
4610
  scope,
@@ -3949,9 +4619,10 @@ var SynapClient = (_class4 = class _SynapClient {
3949
4619
  // on entity and conversation alone, so a bundle prefetched for one
3950
4620
  // rung answered a caller standing at another, entirely inside this
3951
4621
  // process and invisible to every server log.
3952
- scopeRung: _chunkICUFS3B5cjs.rungKey.call(void 0,
4622
+ scopeRung: _chunkBYUGILQIcjs.rungKey.call(void 0,
3953
4623
  _nullishCoalesce(o2["scope_path"], () => ( o2["scopePath"]))
3954
- )
4624
+ ),
4625
+ maxResultsPerQuery: _nullishCoalesce(_nullishCoalesce(o2["max_results_per_query"], () => ( o2["maxResultsPerQuery"])), () => ( null))
3955
4626
  },
3956
4627
  Number(_nullishCoalesce(_nullishCoalesce(o2["max_results"], () => ( o2["maxResults"])), () => ( 10)))
3957
4628
  );
@@ -3961,7 +4632,7 @@ var SynapClient = (_class4 = class _SynapClient {
3961
4632
  servedItemIds: servedItemIds(attempt.hit),
3962
4633
  bundleId: _nullishCoalesce(attempt.hit.bundleIds[0], () => ( "")),
3963
4634
  borderline: attempt.hit.band === "borderline",
3964
- raceDeadlineMs: _chunkICUFS3B5cjs.SEMANTIC_MATCH.race_deadline_ms
4635
+ raceDeadlineMs: _chunkBYUGILQIcjs.SEMANTIC_MATCH.race_deadline_ms
3965
4636
  };
3966
4637
  },
3967
4638
  onAssembled: (scope, options2, response, startedAt) => {
@@ -3977,6 +4648,30 @@ var SynapClient = (_class4 = class _SynapClient {
3977
4648
  // Python's `_should_skip_server_st`: when this process already holds the
3978
4649
  // conversation's compaction and every turn after it, the server is told
3979
4650
  // not to assemble them again.
4651
+ // A fetch with no query, as Python answers it inside the two scoped
4652
+ // fetches: the conversation's state, or the user's profile when there
4653
+ // is one. A profile read that fails falls back to the fetch as before.
4654
+ withoutQuery: async (scope, options2) => {
4655
+ const o2 = options2;
4656
+ if (scope === "conversation") {
4657
+ const id = _nullishCoalesce(o2["conversation_id"], () => ( o2["conversationId"]));
4658
+ const prompt = await this.conversation.context.get_context_for_prompt({ conversation_id: id });
4659
+ return conversationStateContext(prompt, id);
4660
+ }
4661
+ if (scope === "user") {
4662
+ try {
4663
+ const customerId = _nullishCoalesce(o2["customer_id"], () => ( o2["customerId"]));
4664
+ const profile = await this.user.get_profile({
4665
+ user_id: _nullishCoalesce(o2["user_id"], () => ( o2["userId"])),
4666
+ ...customerId !== void 0 ? { customer_id: customerId } : {}
4667
+ });
4668
+ return profileContext(profile);
4669
+ } catch (e19) {
4670
+ return null;
4671
+ }
4672
+ }
4673
+ return null;
4674
+ },
3980
4675
  skipServerShortTerm: (conversationId) => {
3981
4676
  if (!this.#isStAuthoritative()) return false;
3982
4677
  const entry = this.#shortTerm.get(conversationId);
@@ -3990,7 +4685,7 @@ var SynapClient = (_class4 = class _SynapClient {
3990
4685
  response,
3991
4686
  _nullishCoalesce(o2["conversation_id"], () => ( o2["conversationId"])),
3992
4687
  owner,
3993
- _chunkICUFS3B5cjs.rungKey.call(void 0, _nullishCoalesce(o2["scope_path"], () => ( o2["scopePath"])))
4688
+ _chunkBYUGILQIcjs.rungKey.call(void 0, _nullishCoalesce(o2["scope_path"], () => ( o2["scopePath"])))
3994
4689
  );
3995
4690
  }
3996
4691
  };
@@ -4011,7 +4706,7 @@ var SynapClient = (_class4 = class _SynapClient {
4011
4706
  this.#localEncoder = _nullishCoalesce(_nullishCoalesce(options.history_search_encoder, () => ( options.historySearchEncoder)), () => ( null));
4012
4707
  const modelOption = options.history_search_model !== void 0 ? options.history_search_model : options.historySearchModel;
4013
4708
  this.#localModelName = modelOption === void 0 ? "auto" : modelOption;
4014
- if (_optionalChain([this, 'access', _79 => _79.#localEncoder, 'optionalAccess', _80 => _80.model]) === _chunkICUFS3B5cjs.SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(this.#localEncoder);
4709
+ if (_optionalChain([this, 'access', _96 => _96.#localEncoder, 'optionalAccess', _97 => _97.model]) === _chunkBYUGILQIcjs.SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(this.#localEncoder);
4015
4710
  this.#turns = new TurnCounter();
4016
4711
  this.conversation = createConversationNamespace(
4017
4712
  this.#transport,
@@ -4037,7 +4732,7 @@ var SynapClient = (_class4 = class _SynapClient {
4037
4732
  },
4038
4733
  (response, conversationId, userId, scopePath) => {
4039
4734
  overlayLocalRecentTurns(response, this.#shortTerm, conversationId, this.#stVerbatimOverlay);
4040
- this.#injectUserSummary(response, conversationId, userId, _chunkICUFS3B5cjs.rungKey.call(void 0, scopePath));
4735
+ this.#injectUserSummary(response, conversationId, userId, _chunkBYUGILQIcjs.rungKey.call(void 0, scopePath));
4041
4736
  },
4042
4737
  {
4043
4738
  prompt: (conversationId, style) => this.#localPrompt(conversationId, style),
@@ -4057,6 +4752,22 @@ var SynapClient = (_class4 = class _SynapClient {
4057
4752
  if (id) this.#anticipationCache.dropEntity(id);
4058
4753
  }
4059
4754
  });
4755
+ this.data = createDataInterface(this.#transport, ({ scope, userId, customerId, conversationId }) => {
4756
+ const cleared = [];
4757
+ if (scope === "conversation") {
4758
+ if (conversationId) {
4759
+ this.#shortTerm.invalidate(conversationId);
4760
+ this.#turnStore.drop(conversationId);
4761
+ cleared.push("short_term_context", "turns");
4762
+ }
4763
+ } else {
4764
+ for (const id of new Set(scope === "user" ? [userId, customerId] : [customerId])) {
4765
+ if (id) this.#anticipationCache.dropEntity(id);
4766
+ }
4767
+ cleared.push("anticipation_cache");
4768
+ }
4769
+ return cleared;
4770
+ });
4060
4771
  this.credits = createCreditsNamespace(this.#transport);
4061
4772
  this.cache = createCacheNamespace(this.#anticipationCache);
4062
4773
  this.instance = createInstanceNamespace(
@@ -4065,6 +4776,8 @@ var SynapClient = (_class4 = class _SynapClient {
4065
4776
  ({ conversationId, role, content }) => {
4066
4777
  this.#shortTerm.appendTurn(conversationId, role, content);
4067
4778
  },
4779
+ // A FilePart given by url is read with the same fetch as everything else.
4780
+ ((url, init) => this.#transport.fetchExternal(url, init)),
4068
4781
  () => this.#agentModel,
4069
4782
  ({ conversationId, result, toolName }) => this.archive_tool_result(conversationId, result, { tool_name: toolName }),
4070
4783
  (customerId, where) => this.#transport.checkCustomerId(customerId, where)
@@ -4204,7 +4917,7 @@ var SynapClient = (_class4 = class _SynapClient {
4204
4917
  this.#registryKeys.push(resolvedInstanceId);
4205
4918
  }
4206
4919
  }
4207
- } catch (e16) {
4920
+ } catch (e20) {
4208
4921
  }
4209
4922
  }
4210
4923
  /**
@@ -4312,7 +5025,9 @@ var SynapClient = (_class4 = class _SynapClient {
4312
5025
  const labels = [];
4313
5026
  const tasks = [];
4314
5027
  const present = (v) => v !== void 0 && v !== null && v !== "";
4315
- if (present(conversationId) && wants("conversation")) {
5028
+ const conversationState = present(conversationId) && contextMode !== "conversation-summary" && !hasQuery(searchQuery) && wants("conversation");
5029
+ const withConversationContext = includeConversationContext;
5030
+ if (present(conversationId) && wants("conversation") && !conversationState) {
4316
5031
  labels.push("conversation");
4317
5032
  tasks.push(this.conversation.context.fetch({
4318
5033
  conversation_id: conversationId,
@@ -4348,7 +5063,7 @@ var SynapClient = (_class4 = class _SynapClient {
4348
5063
  ...shared
4349
5064
  }));
4350
5065
  }
4351
- if (tasks.length === 0) {
5066
+ if (tasks.length === 0 && !(conversationState && includeConversationContext)) {
4352
5067
  const empty = mergeScopeResults([]);
4353
5068
  return empty;
4354
5069
  }
@@ -4367,17 +5082,20 @@ var SynapClient = (_class4 = class _SynapClient {
4367
5082
  for (const [, response] of successful) {
4368
5083
  overlayLocalRecentTurns(response, this.#shortTerm, conversationId, this.#stVerbatimOverlay);
4369
5084
  }
4370
- if (includeConversationContext && present(conversationId)) {
5085
+ if (withConversationContext && present(conversationId)) {
4371
5086
  try {
4372
5087
  merged.conversation_context = await this.conversation.context.get_context_for_prompt({
4373
5088
  conversation_id: conversationId
4374
5089
  });
4375
- } catch (e17) {
5090
+ if (conversationState && !merged.scopes_queried.includes("conversation")) {
5091
+ merged.scopes_queried.unshift("conversation");
5092
+ }
5093
+ } catch (e21) {
4376
5094
  }
4377
5095
  }
4378
5096
  merged.formatted_context = formatForPrompt(merged, {
4379
5097
  includeScope: includeScopeLabels,
4380
- includeConversationContext
5098
+ includeConversationContext: withConversationContext
4381
5099
  });
4382
5100
  return merged;
4383
5101
  }
@@ -4402,13 +5120,13 @@ var SynapClient = (_class4 = class _SynapClient {
4402
5120
  /**
4403
5121
  * Report a locally served fetch back to the server.
4404
5122
  *
4405
- * Only while listening: the event rides the Listen stream, and there is
4406
- * nowhere to put it otherwise. Never throws, because a telemetry failure
4407
- * must not fail a retrieval that already succeeded.
5123
+ * It rides the Listen stream. While the stream is reconnecting the stream
5124
+ * client holds it and sends it on reconnect: a hit never reaches a fetch
5125
+ * route, so this report is the only count of it. Never throws, because a
5126
+ * telemetry failure must not fail a retrieval that already succeeded.
4408
5127
  */
4409
5128
  #emitContextUsed(options, scope, served) {
4410
5129
  try {
4411
- if (!this.instance.is_listening) return;
4412
5130
  this.instance._internal.sendContextUsed({
4413
5131
  bundle_id: served.bundleId,
4414
5132
  conversation_id: String(_nullishCoalesce(_nullishCoalesce(options["conversation_id"], () => ( options["conversationId"])), () => ( ""))),
@@ -4424,7 +5142,7 @@ var SynapClient = (_class4 = class _SynapClient {
4424
5142
  // not carry the caller's words.
4425
5143
  query_count: distinctQueryCount(_nullishCoalesce(options["search_query"], () => ( options["searchQuery"])))
4426
5144
  });
4427
- } catch (e18) {
5145
+ } catch (e22) {
4428
5146
  }
4429
5147
  }
4430
5148
  /**
@@ -4449,7 +5167,7 @@ var SynapClient = (_class4 = class _SynapClient {
4449
5167
  }),
4450
5168
  scope
4451
5169
  });
4452
- } catch (e19) {
5170
+ } catch (e23) {
4453
5171
  }
4454
5172
  }
4455
5173
  /**
@@ -4510,14 +5228,14 @@ var SynapClient = (_class4 = class _SynapClient {
4510
5228
  }))
4511
5229
  );
4512
5230
  const entry = this.#shortTerm.get(conversationId);
4513
- const total = Math.max(Number(_nullishCoalesce(r["total_message_count"], () => ( 0))) || 0, Number(_nullishCoalesce(_optionalChain([entry, 'optionalAccess', _81 => _81.serverMessageCount]), () => ( 0))) || 0);
5231
+ const total = Math.max(Number(_nullishCoalesce(r["total_message_count"], () => ( 0))) || 0, Number(_nullishCoalesce(_optionalChain([entry, 'optionalAccess', _98 => _98.serverMessageCount]), () => ( 0))) || 0);
4514
5232
  this.#maybeBackfillTurns(conversationId, total);
4515
5233
  if (!r["context_block"]) return response;
4516
5234
  const turns = store.turns(conversationId);
4517
5235
  let q = query;
4518
5236
  if (!q) {
4519
5237
  const latest = [...recent].reverse().find((m) => m["role"] === "user");
4520
- q = latest ? String(_nullishCoalesce(latest["content"], () => ( ""))) : _nullishCoalesce(_optionalChain([[...turns], 'access', _82 => _82.reverse, 'call', _83 => _83(), 'access', _84 => _84.find, 'call', _85 => _85((t) => t.role === "user"), 'optionalAccess', _86 => _86.content]), () => ( ""));
5238
+ q = latest ? String(_nullishCoalesce(latest["content"], () => ( ""))) : _nullishCoalesce(_optionalChain([[...turns], 'access', _99 => _99.reverse, 'call', _100 => _100(), 'access', _101 => _101.find, 'call', _102 => _102((t) => t.role === "user"), 'optionalAccess', _103 => _103.content]), () => ( ""));
4521
5239
  }
4522
5240
  if (!q) return response;
4523
5241
  const exclude = /* @__PURE__ */ new Set();
@@ -4551,7 +5269,7 @@ var SynapClient = (_class4 = class _SynapClient {
4551
5269
  toolResultText(result, _nullishCoalesce(options.tool_name, () => ( options.toolName))),
4552
5270
  _nullishCoalesce(options.timestamp, () => ( (/* @__PURE__ */ new Date()).toISOString()))
4553
5271
  );
4554
- } catch (e20) {
5272
+ } catch (e24) {
4555
5273
  }
4556
5274
  }
4557
5275
  static __initStatic() {this.BACKFILL_COOLDOWN_MS = 6e4}
@@ -4565,13 +5283,13 @@ var SynapClient = (_class4 = class _SynapClient {
4565
5283
  if (this.#localModelStarted) return;
4566
5284
  this.#localModelStarted = true;
4567
5285
  if (localModelOff()) return;
4568
- const name = this.#localModelName === "auto" ? _chunkICUFS3B5cjs.SEMANTIC_MATCH.model : this.#localModelName;
5286
+ const name = this.#localModelName === "auto" ? _chunkBYUGILQIcjs.SEMANTIC_MATCH.model : this.#localModelName;
4569
5287
  if (!name) return;
4570
5288
  const callerEncoder = this.#localEncoder;
4571
5289
  void Promise.resolve().then(() => _interopRequireWildcard(require("./onnx-encoder-4RSL6ID4.cjs"))).then(({ canRunLocalModel, loadOnnxEncoder }) => canRunLocalModel() ? loadOnnxEncoder(name) : null).then((encoder) => {
4572
5290
  if (encoder === null) return;
4573
5291
  if (callerEncoder === null) this.#localEncoder = encoder;
4574
- if (encoder.model === _chunkICUFS3B5cjs.SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(encoder);
5292
+ if (encoder.model === _chunkBYUGILQIcjs.SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(encoder);
4575
5293
  }).catch(() => {
4576
5294
  });
4577
5295
  }
@@ -4661,11 +5379,11 @@ function pick3(o2, snake, camel) {
4661
5379
  function resolveBaseUrl(options) {
4662
5380
  const explicit = _nullishCoalesce(options.baseUrl, () => ( options.api_base_url));
4663
5381
  if (explicit !== void 0) return explicit;
4664
- const fromEnv = _optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_BASE_URL"), 'optionalAccess', _87 => _87.trim, 'call', _88 => _88()]);
5382
+ const fromEnv = _optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_BASE_URL"), 'optionalAccess', _104 => _104.trim, 'call', _105 => _105()]);
4665
5383
  return fromEnv !== void 0 && fromEnv !== "" ? fromEnv : void 0;
4666
5384
  }
4667
5385
  function resolveCredentials(options) {
4668
- const apiKey = _nullishCoalesce(options.apiKey, () => ( _chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_API_KEY")));
5386
+ const apiKey = options.apiKey || _chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_API_KEY");
4669
5387
  if (!apiKey) {
4670
5388
  throw new (0, _chunk7IZHVYO2cjs.AuthenticationError)(
4671
5389
  "No Synap API key found. Set SYNAP_API_KEY in your environment, or pass apiKey to the SynapClient constructor."
@@ -4738,5 +5456,8 @@ function resolveCredentials(options) {
4738
5456
 
4739
5457
 
4740
5458
 
4741
- exports.ANY_SCOPE = _chunkICUFS3B5cjs.ANY_SCOPE; exports.AgentUnavailableError = _chunk7IZHVYO2cjs.AgentUnavailableError; exports.AnticipationCache = _chunkICUFS3B5cjs.AnticipationCache; exports.AuthenticationError = _chunk7IZHVYO2cjs.AuthenticationError; exports.BM25 = _chunkICUFS3B5cjs.BM25; exports.COMPACTION_LEVELS = COMPACTION_LEVELS; exports.CONTRACT = _chunkICUFS3B5cjs.CONTRACT; exports.ConflictError = _chunk7IZHVYO2cjs.ConflictError; exports.ConnectionError = _chunk7IZHVYO2cjs.ConnectionError; exports.ContextNotFoundError = _chunk7IZHVYO2cjs.ContextNotFoundError; exports.CustomerIdNotAcceptedError = _chunk7IZHVYO2cjs.CustomerIdNotAcceptedError; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL; exports.DEFAULT_DOCUMENT_TYPE = DEFAULT_DOCUMENT_TYPE; exports.DEFAULT_INGEST_MODE = DEFAULT_INGEST_MODE; exports.DEFAULT_RETRY_POLICY = DEFAULT_RETRY_POLICY; exports.DEFAULT_TIMEOUTS = DEFAULT_TIMEOUTS; exports.DOCUMENT_TYPES = DOCUMENT_TYPES; exports.ENDPOINTS = ENDPOINTS; exports.EXCERPT_CATEGORY = EXCERPT_CATEGORY; exports.FORGET_MODES = FORGET_MODES; exports.HttpTransport = HttpTransport; exports.INGEST_MODES = INGEST_MODES; exports.ITEM_COLLECTIONS = ITEM_COLLECTIONS; exports.InstanceBuildFailedError = _chunk7IZHVYO2cjs.InstanceBuildFailedError; exports.InstanceNotReadyError = _chunk7IZHVYO2cjs.InstanceNotReadyError; exports.InsufficientCreditsError = _chunk7IZHVYO2cjs.InsufficientCreditsError; exports.InvalidConversationIdError = _chunk7IZHVYO2cjs.InvalidConversationIdError; exports.InvalidInputError = _chunk7IZHVYO2cjs.InvalidInputError; exports.InvalidInstanceIdError = _chunk7IZHVYO2cjs.InvalidInstanceIdError; exports.ListeningAlreadyActiveError = _chunk7IZHVYO2cjs.ListeningAlreadyActiveError; exports.ListeningNotActiveError = _chunk7IZHVYO2cjs.ListeningNotActiveError; exports.MEMORY_TYPES = MEMORY_TYPES; exports.NetworkTimeoutError = _chunk7IZHVYO2cjs.NetworkTimeoutError; exports.PermanentError = _chunk7IZHVYO2cjs.PermanentError; exports.RESPONSE_SHAPES = RESPONSE_SHAPES; exports.RateLimitError = _chunk7IZHVYO2cjs.RateLimitError; exports.SDKError = _chunk7IZHVYO2cjs.SDKError; exports.SDK_VERSION = SDK_VERSION; exports.ServiceUnavailableError = _chunk7IZHVYO2cjs.ServiceUnavailableError; exports.SessionExpiredError = _chunk7IZHVYO2cjs.SessionExpiredError; exports.SynapClient = SynapClient; exports.SynapError = _chunk7IZHVYO2cjs.SynapError; exports.SynapPermanentError = _chunk7IZHVYO2cjs.SynapPermanentError; exports.SynapTransientError = _chunk7IZHVYO2cjs.SynapTransientError; exports.THRESHOLDS = _chunkICUFS3B5cjs.THRESHOLDS; exports.TranscriptConflictError = _chunk7IZHVYO2cjs.TranscriptConflictError; exports.TransientError = _chunk7IZHVYO2cjs.TransientError; exports.applyResponseShape = applyResponseShape; exports.flattenContextItems = flattenContextItems; exports.formatForPrompt = formatForPrompt; exports.isOutcomeUnknown = isOutcomeUnknown; exports.isRecallQuery = _chunkICUFS3B5cjs.isRecallQuery; exports.isSynapError = _chunk7IZHVYO2cjs.isSynapError; exports.mergeScopeResults = mergeScopeResults; exports.rankItems = rankItems; exports.resolvePath = resolvePath; exports.shouldRetry = shouldRetry; exports.stem = _chunkICUFS3B5cjs.stem; exports.tokenize = _chunkICUFS3B5cjs.tokenize; exports.wireRankScore = wireRankScore;
5459
+
5460
+
5461
+
5462
+ exports.ANY_SCOPE = _chunkBYUGILQIcjs.ANY_SCOPE; exports.AgentUnavailableError = _chunk7IZHVYO2cjs.AgentUnavailableError; exports.AnticipationCache = _chunkBYUGILQIcjs.AnticipationCache; exports.AuthenticationError = _chunk7IZHVYO2cjs.AuthenticationError; exports.BM25 = _chunkBYUGILQIcjs.BM25; exports.COMPACTION_LEVELS = COMPACTION_LEVELS; exports.CONTRACT = _chunkBYUGILQIcjs.CONTRACT; exports.ConflictError = _chunk7IZHVYO2cjs.ConflictError; exports.ConnectionError = _chunk7IZHVYO2cjs.ConnectionError; exports.ContextNotFoundError = _chunk7IZHVYO2cjs.ContextNotFoundError; exports.CustomerIdNotAcceptedError = _chunk7IZHVYO2cjs.CustomerIdNotAcceptedError; exports.DATA_SCOPES = DATA_SCOPES; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL; exports.DEFAULT_DOCUMENT_TYPE = DEFAULT_DOCUMENT_TYPE; exports.DEFAULT_INGEST_MODE = DEFAULT_INGEST_MODE; exports.DEFAULT_RETRY_POLICY = DEFAULT_RETRY_POLICY; exports.DEFAULT_TIMEOUTS = DEFAULT_TIMEOUTS; exports.DOCUMENT_TYPES = DOCUMENT_TYPES; exports.ENDPOINTS = ENDPOINTS; exports.EXCERPT_CATEGORY = EXCERPT_CATEGORY; exports.FORGET_MODES = FORGET_MODES; exports.HttpTransport = HttpTransport; exports.INGEST_MODES = INGEST_MODES; exports.ITEM_COLLECTIONS = ITEM_COLLECTIONS; exports.InstanceBuildFailedError = _chunk7IZHVYO2cjs.InstanceBuildFailedError; exports.InstanceNotReadyError = _chunk7IZHVYO2cjs.InstanceNotReadyError; exports.InsufficientCreditsError = _chunk7IZHVYO2cjs.InsufficientCreditsError; exports.InvalidConversationIdError = _chunk7IZHVYO2cjs.InvalidConversationIdError; exports.InvalidInputError = _chunk7IZHVYO2cjs.InvalidInputError; exports.InvalidInstanceIdError = _chunk7IZHVYO2cjs.InvalidInstanceIdError; exports.ListeningAlreadyActiveError = _chunk7IZHVYO2cjs.ListeningAlreadyActiveError; exports.ListeningNotActiveError = _chunk7IZHVYO2cjs.ListeningNotActiveError; exports.MEMORY_TYPES = MEMORY_TYPES; exports.NetworkTimeoutError = _chunk7IZHVYO2cjs.NetworkTimeoutError; exports.OBJECTIVES = OBJECTIVES; exports.PermanentError = _chunk7IZHVYO2cjs.PermanentError; exports.RESPONSE_SHAPES = RESPONSE_SHAPES; exports.RateLimitError = _chunk7IZHVYO2cjs.RateLimitError; exports.SDKError = _chunk7IZHVYO2cjs.SDKError; exports.SDK_VERSION = SDK_VERSION; exports.ServiceUnavailableError = _chunk7IZHVYO2cjs.ServiceUnavailableError; exports.SessionExpiredError = _chunk7IZHVYO2cjs.SessionExpiredError; exports.SynapClient = SynapClient; exports.SynapError = _chunk7IZHVYO2cjs.SynapError; exports.SynapPermanentError = _chunk7IZHVYO2cjs.SynapPermanentError; exports.SynapTransientError = _chunk7IZHVYO2cjs.SynapTransientError; exports.THRESHOLDS = _chunkBYUGILQIcjs.THRESHOLDS; exports.TranscriptConflictError = _chunk7IZHVYO2cjs.TranscriptConflictError; exports.TransientError = _chunk7IZHVYO2cjs.TransientError; exports.applyResponseShape = applyResponseShape; exports.filePart = filePart; exports.flattenContextItems = flattenContextItems; exports.formatForPrompt = formatForPrompt; exports.isOutcomeUnknown = isOutcomeUnknown; exports.isSynapError = _chunk7IZHVYO2cjs.isSynapError; exports.mergeScopeResults = mergeScopeResults; exports.rankItems = rankItems; exports.resolvePath = resolvePath; exports.shouldRetry = shouldRetry; exports.stem = _chunkBYUGILQIcjs.stem; exports.textPart = textPart; exports.tokenize = _chunkBYUGILQIcjs.tokenize; exports.wireRankScore = wireRankScore;
4742
5463
  //# sourceMappingURL=index.cjs.map