@maximem/synap-js-sdk 0.6.5 → 0.6.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -43,12 +43,22 @@ var _chunkZKOJDUN4cjs = require('./chunk-ZKOJDUN4.cjs');
43
43
 
44
44
  var _chunk7IZHVYO2cjs = require('./chunk-7IZHVYO2.cjs');
45
45
 
46
+ // src/local-mode.ts
47
+ function isLocalMode(apiKey, baseUrl) {
48
+ if (apiKey || _chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_API_KEY")) return false;
49
+ return baseUrl !== void 0 && baseUrl.trim() !== "";
50
+ }
51
+ function localToken() {
52
+ return _nullishCoalesce(_optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_API_TOKEN"), 'optionalAccess', _2 => _2.trim, 'call', _3 => _3()]), () => ( ""));
53
+ }
54
+
46
55
  // src/transport/endpoints.ts
47
56
  var ENDPOINTS = {
48
57
  whoami: { method: "GET", path: "/api/v1/auth/whoami", idempotent: true },
49
58
  memories_create: { method: "POST", path: "/api/v1/memories/create", idempotent: false },
50
59
  memories_batch: { method: "POST", path: "/api/v1/memories/batch", idempotent: false },
51
60
  memories_upload: { method: "POST", path: "/api/v1/memories/upload", idempotent: false },
61
+ memories_create_multipart: { method: "POST", path: "/api/v1/memories/create-multipart", idempotent: false },
52
62
  memories_status: { method: "GET", path: "/api/v1/memories/status/{ingestion_id}", idempotent: true },
53
63
  memories_get: { method: "GET", path: "/api/v1/memories/{memory_id}", idempotent: true },
54
64
  memories_update: { method: "PATCH", path: "/api/v1/memories/{memory_id}", idempotent: false },
@@ -142,7 +152,7 @@ var HEARTBEAT_INTERVAL_MS = 24e4;
142
152
  var MAX_CONNECTIONS = 20;
143
153
  var cached;
144
154
  function supportsDispatcher() {
145
- return typeof process !== "undefined" && _optionalChain([process, 'access', _2 => _2.versions, 'optionalAccess', _3 => _3.node]) !== void 0 && // Edge builds of Next expose a partial `process` shim, but no real Node.
155
+ return typeof process !== "undefined" && _optionalChain([process, 'access', _4 => _4.versions, 'optionalAccess', _5 => _5.node]) !== void 0 && // Edge builds of Next expose a partial `process` shim, but no real Node.
146
156
  typeof globalThis.EdgeRuntime === "undefined";
147
157
  }
148
158
  async function getKeepAliveDispatcher(options = {}) {
@@ -183,7 +193,7 @@ var Heartbeat = (_class = class {
183
193
  void Promise.resolve(this.ping()).catch(() => {
184
194
  });
185
195
  }, this.intervalMs);
186
- _optionalChain([this, 'access', _4 => _4.timer, 'access', _5 => _5.unref, 'optionalCall', _6 => _6()]);
196
+ _optionalChain([this, 'access', _6 => _6.timer, 'access', _7 => _7.unref, 'optionalCall', _8 => _8()]);
187
197
  }
188
198
  stop() {
189
199
  if (this.timer !== null) {
@@ -269,9 +279,19 @@ var HttpTransport = (_class2 = class {
269
279
  this.keepAliveOptions = _nullishCoalesce(options.keepAlive, () => ( {}));
270
280
  this.heartbeat = new Heartbeat(
271
281
  () => this.pingHealth(),
272
- _nullishCoalesce(_optionalChain([options, 'access', _7 => _7.keepAlive, 'optionalAccess', _8 => _8.heartbeatIntervalMs]), () => ( HEARTBEAT_INTERVAL_MS))
282
+ _nullishCoalesce(_optionalChain([options, 'access', _9 => _9.keepAlive, 'optionalAccess', _10 => _10.heartbeatIntervalMs]), () => ( HEARTBEAT_INTERVAL_MS))
273
283
  );
274
284
  }
285
+ /**
286
+ * @internal Fetch a URL that is not Synap's, with this transport's fetch.
287
+ *
288
+ * Used to read a `FilePart` given by `url`: the SDK fetches it, the server
289
+ * never does. Deliberately sends none of this transport's headers, because
290
+ * the URL belongs to somebody else and the API key must not reach them.
291
+ */
292
+ fetchExternal(url, init = {}) {
293
+ return this.fetchImpl(url, init);
294
+ }
275
295
  /** Start keeping the connection warm. Opt-in: it is pointless in serverless. */
276
296
  startHeartbeat() {
277
297
  if (!this.closed) this.heartbeat.start();
@@ -411,7 +431,7 @@ var HttpTransport = (_class2 = class {
411
431
  await sleep(decision.delaySeconds * 1e3, options.signal);
412
432
  }
413
433
  }
414
- throw _nullishCoalesce(_optionalChain([last, 'optionalAccess', _9 => _9.error]), () => ( new (0, _chunk7IZHVYO2cjs.SynapError)("Request failed with no recorded error")));
434
+ throw _nullishCoalesce(_optionalChain([last, 'optionalAccess', _11 => _11.error]), () => ( new (0, _chunk7IZHVYO2cjs.SynapError)("Request failed with no recorded error")));
415
435
  }
416
436
  async attempt(name, options, correlationId) {
417
437
  const spec = ENDPOINTS[name];
@@ -436,7 +456,8 @@ var HttpTransport = (_class2 = class {
436
456
  signal.dispose();
437
457
  }
438
458
  if (!response.ok) {
439
- throw await toHttpError(response, correlationId);
459
+ const error = await toHttpError(response, correlationId);
460
+ throw _nullishCoalesce(_optionalChain([options, 'access', _12 => _12.mapError, 'optionalCall', _13 => _13(response.status, error)]), () => ( error));
440
461
  }
441
462
  if (response.status === 204) return void 0;
442
463
  const text = await response.text();
@@ -456,7 +477,8 @@ var HttpTransport = (_class2 = class {
456
477
  }
457
478
  buildHeaders(correlationId, options = {}) {
458
479
  return {
459
- Authorization: `Bearer ${this.#credentials.apiKey}`,
480
+ // Empty only in local mode with no SYNAP_API_TOKEN: send no header at all.
481
+ ...this.#credentials.apiKey !== "" ? { Authorization: `Bearer ${this.#credentials.apiKey}` } : {},
460
482
  "X-Client-ID": this.#credentials.clientId,
461
483
  "X-Instance-ID": this.#credentials.instanceId,
462
484
  "X-Correlation-ID": correlationId,
@@ -507,18 +529,18 @@ function isConnectionRefusal(error) {
507
529
  }
508
530
  function toTransportError(error, correlationId) {
509
531
  if (error instanceof _chunk7IZHVYO2cjs.SynapError) return error;
510
- const name = _optionalChain([error, 'optionalAccess', _10 => _10.name]);
532
+ const name = _optionalChain([error, 'optionalAccess', _14 => _14.name]);
511
533
  if (name === "AbortError" || name === "TimeoutError") {
512
534
  return new (0, _chunk7IZHVYO2cjs.NetworkTimeoutError)("Request timed out", { correlationId, cause: error });
513
535
  }
514
536
  if (isConnectionRefusal(error)) {
515
537
  return new (0, _chunk7IZHVYO2cjs.NetworkTimeoutError)(
516
- `Connection failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _11 => _11.message]), () => ( String(error)))}`,
538
+ `Connection failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _15 => _15.message]), () => ( String(error)))}`,
517
539
  { correlationId, cause: error }
518
540
  );
519
541
  }
520
542
  return new (0, _chunk7IZHVYO2cjs.ServiceUnavailableError)(
521
- `Network request failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _12 => _12.message]), () => ( String(error)))}`,
543
+ `Network request failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _16 => _16.message]), () => ( String(error)))}`,
522
544
  { correlationId, cause: error }
523
545
  );
524
546
  }
@@ -547,6 +569,11 @@ async function toHttpError(response, correlationId) {
547
569
  switch (response.status) {
548
570
  case 400:
549
571
  case 422:
572
+ // Wrong method, too large, unsupported media type: each says what was
573
+ // wrong with the request, and none of them goes away on a retry.
574
+ case 405:
575
+ case 413:
576
+ case 415:
550
577
  return new (0, _chunk7IZHVYO2cjs.InvalidInputError)(message, opts);
551
578
  case 401:
552
579
  case 403:
@@ -566,8 +593,8 @@ async function toHttpError(response, correlationId) {
566
593
  });
567
594
  }
568
595
  case 409:
569
- if (parsed["error"] === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _13 => _13["code"]]) === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _14 => _14["error"]]) === "instance_build_failed") {
570
- const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _15 => _15[key]])));
596
+ if (parsed["error"] === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _17 => _17["code"]]) === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _18 => _18["error"]]) === "instance_build_failed") {
597
+ const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _19 => _19[key]])));
571
598
  const msg = pick4("message");
572
599
  const attempts = Number(pick4("attempts"));
573
600
  return new (0, _chunk7IZHVYO2cjs.InstanceBuildFailedError)(
@@ -580,8 +607,8 @@ async function toHttpError(response, correlationId) {
580
607
  }
581
608
  );
582
609
  }
583
- if (parsed["error"] === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _16 => _16["code"]]) === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _17 => _17["error"]]) === "instance_not_ready") {
584
- const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _18 => _18[key]])));
610
+ if (parsed["error"] === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _20 => _20["code"]]) === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _21 => _21["error"]]) === "instance_not_ready") {
611
+ const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _22 => _22[key]])));
585
612
  const rawWait = _nullishCoalesce(pick4("retry_after_seconds"), () => ( response.headers.get("retry-after")));
586
613
  const wait = rawWait !== null && rawWait !== void 0 && String(rawWait).trim() !== "" ? Number(rawWait) : NaN;
587
614
  const msg = pick4("message");
@@ -629,11 +656,11 @@ function stringOrNull(v) {
629
656
  }
630
657
  function withTimeout(ms, external) {
631
658
  const controller = new AbortController();
632
- const onExternalAbort = () => controller.abort(_optionalChain([external, 'optionalAccess', _19 => _19.reason]));
659
+ const onExternalAbort = () => controller.abort(_optionalChain([external, 'optionalAccess', _23 => _23.reason]));
633
660
  const timer = setTimeout(() => {
634
661
  controller.abort(new (0, _chunk7IZHVYO2cjs.NetworkTimeoutError)(`Timed out after ${ms}ms`));
635
662
  }, ms);
636
- _optionalChain([timer, 'access', _20 => _20.unref, 'optionalCall', _21 => _21()]);
663
+ _optionalChain([timer, 'access', _24 => _24.unref, 'optionalCall', _25 => _25()]);
637
664
  if (external) {
638
665
  if (external.aborted) onExternalAbort();
639
666
  else external.addEventListener("abort", onExternalAbort, { once: true });
@@ -642,7 +669,7 @@ function withTimeout(ms, external) {
642
669
  signal: controller.signal,
643
670
  dispose() {
644
671
  clearTimeout(timer);
645
- _optionalChain([external, 'optionalAccess', _22 => _22.removeEventListener, 'call', _23 => _23("abort", onExternalAbort)]);
672
+ _optionalChain([external, 'optionalAccess', _26 => _26.removeEventListener, 'call', _27 => _27("abort", onExternalAbort)]);
646
673
  }
647
674
  };
648
675
  }
@@ -650,14 +677,14 @@ function sleep(ms, signal) {
650
677
  if (ms <= 0) return Promise.resolve();
651
678
  return new Promise((resolve, reject) => {
652
679
  const timer = setTimeout(() => {
653
- _optionalChain([signal, 'optionalAccess', _24 => _24.removeEventListener, 'call', _25 => _25("abort", onAbort)]);
680
+ _optionalChain([signal, 'optionalAccess', _28 => _28.removeEventListener, 'call', _29 => _29("abort", onAbort)]);
654
681
  resolve();
655
682
  }, ms);
656
683
  function onAbort() {
657
684
  clearTimeout(timer);
658
- reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _26 => _26.reason]), () => ( new Error("Aborted"))));
685
+ reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _30 => _30.reason]), () => ( new Error("Aborted"))));
659
686
  }
660
- _optionalChain([signal, 'optionalAccess', _27 => _27.addEventListener, 'call', _28 => _28("abort", onAbort, { once: true })]);
687
+ _optionalChain([signal, 'optionalAccess', _31 => _31.addEventListener, 'call', _32 => _32("abort", onAbort, { once: true })]);
661
688
  });
662
689
  }
663
690
 
@@ -911,7 +938,7 @@ function validateSearchQuery(searchQuery) {
911
938
  }
912
939
  async function fetchContext(transport, scope, options = {}, hooks = {}) {
913
940
  const startedAt = Date.now();
914
- await _optionalChain([transport, 'access', _29 => _29.ready, 'optionalCall', _30 => _30()]);
941
+ await _optionalChain([transport, 'access', _33 => _33.ready, 'optionalCall', _34 => _34()]);
915
942
  await transport.checkCustomerId(
916
943
  opt(options, "customer_id", "customerId"),
917
944
  `${scope}.context.fetch`
@@ -927,20 +954,20 @@ async function fetchContext(transport, scope, options = {}, hooks = {}) {
927
954
  if (answer !== null) return applyResponseShape(answer, responseShape);
928
955
  }
929
956
  const finish = (response2) => {
930
- _optionalChain([hooks, 'access', _31 => _31.onResponse, 'optionalCall', _32 => _32(scope, options, response2)]);
957
+ _optionalChain([hooks, 'access', _35 => _35.onResponse, 'optionalCall', _36 => _36(scope, options, response2)]);
931
958
  return response2;
932
959
  };
933
960
  const conversationId = opt(options, "conversation_id", "conversationId");
934
- const skipServerSt = conversationId ? _optionalChain([hooks, 'access', _33 => _33.skipServerShortTerm, 'optionalCall', _34 => _34(conversationId)]) === true : false;
961
+ const skipServerSt = conversationId ? _optionalChain([hooks, 'access', _37 => _37.skipServerShortTerm, 'optionalCall', _38 => _38(conversationId)]) === true : false;
935
962
  const network = async () => {
936
963
  const { endpoint, body } = buildFetchRequest(
937
964
  scope,
938
965
  skipServerSt ? { ...options, include_conversation_context: false } : options
939
966
  );
940
967
  const result = await transport.request(endpoint, { body });
941
- return applyResponseShape(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _35 => _35["context"]]), () => ( {})), responseShape);
968
+ return applyResponseShape(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _39 => _39["context"]]), () => ( {})), responseShape);
942
969
  };
943
- const anticipated = summaryMode ? null : await _asyncNullishCoalesce(await _optionalChain([hooks, 'access', _36 => _36.beforeFetch, 'optionalCall', _37 => _37(scope, options)]), async () => ( null));
970
+ const anticipated = summaryMode ? null : await _asyncNullishCoalesce(await _optionalChain([hooks, 'access', _40 => _40.beforeFetch, 'optionalCall', _41 => _41(scope, options)]), async () => ( null));
944
971
  if (anticipated !== null && anticipated.borderline) {
945
972
  const pending = network();
946
973
  pending.catch(() => void 0);
@@ -951,17 +978,17 @@ async function fetchContext(transport, scope, options = {}, hooks = {}) {
951
978
  const won = await Promise.race([pending.then((r) => r, () => null), late]);
952
979
  if (timer !== void 0) clearTimeout(timer);
953
980
  if (won !== null) {
954
- _optionalChain([hooks, 'access', _38 => _38.onAssembled, 'optionalCall', _39 => _39(scope, options, won, startedAt)]);
981
+ _optionalChain([hooks, 'access', _42 => _42.onAssembled, 'optionalCall', _43 => _43(scope, options, won, startedAt)]);
955
982
  return finish(won);
956
983
  }
957
984
  }
958
985
  if (anticipated !== null) {
959
- _optionalChain([hooks, 'access', _40 => _40.onServedFromCache, 'optionalCall', _41 => _41(scope, options, anticipated)]);
960
- _optionalChain([hooks, 'access', _42 => _42.onAssembled, 'optionalCall', _43 => _43(scope, options, anticipated.response, startedAt)]);
986
+ _optionalChain([hooks, 'access', _44 => _44.onServedFromCache, 'optionalCall', _45 => _45(scope, options, anticipated)]);
987
+ _optionalChain([hooks, 'access', _46 => _46.onAssembled, 'optionalCall', _47 => _47(scope, options, anticipated.response, startedAt)]);
961
988
  return finish(applyResponseShape(anticipated.response, responseShape));
962
989
  }
963
990
  const response = await network();
964
- _optionalChain([hooks, 'access', _44 => _44.onAssembled, 'optionalCall', _45 => _45(scope, options, response, startedAt)]);
991
+ _optionalChain([hooks, 'access', _48 => _48.onAssembled, 'optionalCall', _49 => _49(scope, options, response, startedAt)]);
965
992
  return finish(response);
966
993
  }
967
994
 
@@ -1192,6 +1219,293 @@ function flattenContextItems(context) {
1192
1219
  return items;
1193
1220
  }
1194
1221
 
1222
+ // src/memories/parts.ts
1223
+ var OBJECTIVES = [
1224
+ "conversation",
1225
+ "bootstrap",
1226
+ "knowledge-base",
1227
+ "record",
1228
+ "profile"
1229
+ ];
1230
+ var MAX_FILE_BYTES = 10 * 1024 * 1024;
1231
+ var MAX_STREAM_IMAGE_BYTES = 2.5 * 1024 * 1024;
1232
+ var URL_FETCH_TIMEOUT_MS = 3e4;
1233
+ var PART_BRAND = /* @__PURE__ */ Symbol.for("@maximem/synap-js-sdk.ContentPart");
1234
+ function brand(part) {
1235
+ Object.defineProperty(part, PART_BRAND, { value: true, enumerable: false });
1236
+ return part;
1237
+ }
1238
+ function isBranded(value) {
1239
+ return typeof value === "object" && value !== null && PART_BRAND in value;
1240
+ }
1241
+ function textPart(text) {
1242
+ if (typeof text !== "string") throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("TextPart text must be a string");
1243
+ return brand({ type: "text", text });
1244
+ }
1245
+ function filePart(init) {
1246
+ const source = checkOneSource(init);
1247
+ const filename = defaultFilename(init, source);
1248
+ const mediaType = _nullishCoalesce(_nullishCoalesce(init.media_type, () => ( init.mediaType)), () => ( defaultMediaType(filename, _nullishCoalesce(init.data, () => ( void 0)))));
1249
+ const part = { type: "file" };
1250
+ if (source === "data") part.data = init.data;
1251
+ else if (source === "path") part.path = init.path;
1252
+ else part.url = init.url;
1253
+ part.filename = filename;
1254
+ part.media_type = mediaType;
1255
+ return brand(part);
1256
+ }
1257
+ function isTextPart(value) {
1258
+ return isPlainPart(value) && value["type"] === "text" && typeof value["text"] === "string";
1259
+ }
1260
+ function isFilePart(value) {
1261
+ return isPlainPart(value) && value["type"] === "file";
1262
+ }
1263
+ function isPlainPart(value) {
1264
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1265
+ }
1266
+ function checkOneSource(p) {
1267
+ const given = ["data", "path", "url"].filter(
1268
+ (k) => p[k] !== void 0 && p[k] !== null
1269
+ );
1270
+ if (given.length !== 1) {
1271
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1272
+ "FilePart takes exactly one of data, path or url" + (given.length > 0 ? ` (got ${given.join(", ")})` : "")
1273
+ );
1274
+ }
1275
+ return given[0];
1276
+ }
1277
+ function lastSegment(p) {
1278
+ const parts = p.split(/[\\/]/);
1279
+ return _nullishCoalesce(parts[parts.length - 1], () => ( ""));
1280
+ }
1281
+ function defaultFilename(p, source) {
1282
+ if (p.filename) return p.filename;
1283
+ if (source === "path") return lastSegment(String(p.path)) || "file";
1284
+ if (source === "url") {
1285
+ let pathname = "";
1286
+ try {
1287
+ pathname = new URL(String(p.url)).pathname;
1288
+ } catch (e5) {
1289
+ pathname = _nullishCoalesce(String(p.url).split(/[?#]/)[0], () => ( ""));
1290
+ }
1291
+ return lastSegment(pathname) || "file";
1292
+ }
1293
+ const named = _optionalChain([p, 'access', _50 => _50.data, 'optionalAccess', _51 => _51.name]);
1294
+ return typeof named === "string" && named ? named : "file";
1295
+ }
1296
+ var MEDIA_TYPES = {
1297
+ png: "image/png",
1298
+ jpg: "image/jpeg",
1299
+ jpeg: "image/jpeg",
1300
+ jpe: "image/jpeg",
1301
+ webp: "image/webp",
1302
+ gif: "image/gif",
1303
+ bmp: "image/bmp",
1304
+ tif: "image/tiff",
1305
+ tiff: "image/tiff",
1306
+ svg: "image/svg+xml",
1307
+ pdf: "application/pdf",
1308
+ txt: "text/plain",
1309
+ csv: "text/csv",
1310
+ htm: "text/html",
1311
+ html: "text/html",
1312
+ json: "application/json",
1313
+ doc: "application/msword",
1314
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1315
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1316
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1317
+ mp3: "audio/mpeg",
1318
+ wav: "audio/x-wav",
1319
+ mp4: "video/mp4"
1320
+ };
1321
+ function guessMediaType(filename) {
1322
+ const dot = filename.lastIndexOf(".");
1323
+ if (dot <= 0) return null;
1324
+ const ext = filename.slice(dot + 1).toLowerCase();
1325
+ return _nullishCoalesce(MEDIA_TYPES[ext], () => ( null));
1326
+ }
1327
+ function defaultMediaType(filename, data) {
1328
+ const guessed = guessMediaType(filename);
1329
+ if (guessed !== null) return guessed;
1330
+ const blobType = _optionalChain([data, 'optionalAccess', _52 => _52.type]);
1331
+ return typeof blobType === "string" && blobType ? blobType : DEFAULT_MEDIA_TYPE;
1332
+ }
1333
+ function normaliseContent(value, field) {
1334
+ if (isBranded(value) && isTextPart(value)) return { kind: "text", text: value.text };
1335
+ if (isBranded(value) && isFilePart(value)) return { kind: "parts", parts: [value] };
1336
+ if (!Array.isArray(value)) return null;
1337
+ if (value.length === 0) {
1338
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(`${field} is an empty list; pass at least one part`);
1339
+ }
1340
+ const parts = value.map((item, i) => {
1341
+ if (typeof item === "string") return { type: "text", text: item };
1342
+ if (isTextPart(item) || isFilePart(item)) return item;
1343
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1344
+ `${field}[${i}] is a ${typeName(item)}; expected a string, TextPart or FilePart`
1345
+ );
1346
+ });
1347
+ if (!parts.some(isFilePart)) {
1348
+ return { kind: "text", text: parts.map((p) => p.text).join("\n") };
1349
+ }
1350
+ return { kind: "parts", parts };
1351
+ }
1352
+ function typeName(value) {
1353
+ if (value === null) return "null";
1354
+ if (Array.isArray(value)) return "array";
1355
+ if (typeof value === "object") {
1356
+ return _nullishCoalesce(_optionalChain([value, 'access', _53 => _53.constructor, 'optionalAccess', _54 => _54.name]), () => ( "object"));
1357
+ }
1358
+ return typeof value;
1359
+ }
1360
+ async function resolveFile(part, fetchImpl) {
1361
+ const source = checkOneSource(part);
1362
+ const filename = defaultFilename(part, source);
1363
+ let mediaType = part.media_type || defaultMediaType(filename, part.data);
1364
+ let bytes;
1365
+ if (source === "data") {
1366
+ bytes = await toBytes(part.data);
1367
+ } else if (source === "path") {
1368
+ const { readFile } = await Promise.resolve().then(() => _interopRequireWildcard(require("fs/promises")));
1369
+ try {
1370
+ bytes = new Uint8Array(await readFile(part.path));
1371
+ } catch (error) {
1372
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1373
+ `Could not read FilePart path '${part.path}': ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _55 => _55.message]), () => ( String(error)))}`,
1374
+ { cause: error }
1375
+ );
1376
+ }
1377
+ } else {
1378
+ const fetched = await fetchUrl(part.url, fetchImpl);
1379
+ bytes = fetched.bytes;
1380
+ if (mediaType === DEFAULT_MEDIA_TYPE && fetched.contentType) mediaType = fetched.contentType;
1381
+ }
1382
+ if (bytes.byteLength > MAX_FILE_BYTES) {
1383
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1384
+ `${filename} is ${bytes.byteLength} bytes; the limit is ${MAX_FILE_BYTES} bytes per file`
1385
+ );
1386
+ }
1387
+ return { filename, media_type: mediaType, bytes };
1388
+ }
1389
+ var DEFAULT_MEDIA_TYPE = "application/octet-stream";
1390
+ function urlTooLarge(url) {
1391
+ return `FilePart url '${url}' is over the limit of ${MAX_FILE_BYTES} bytes per file`;
1392
+ }
1393
+ async function toBytes(data) {
1394
+ if (data instanceof Uint8Array) return data;
1395
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
1396
+ if (ArrayBuffer.isView(data)) {
1397
+ const view = data;
1398
+ return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
1399
+ }
1400
+ if (typeof Blob !== "undefined" && data instanceof Blob) {
1401
+ return new Uint8Array(await data.arrayBuffer());
1402
+ }
1403
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("FilePart data must be a Uint8Array, ArrayBuffer or Blob");
1404
+ }
1405
+ async function fetchUrl(url, fetchImpl) {
1406
+ let scheme = "";
1407
+ try {
1408
+ scheme = new URL(url).protocol;
1409
+ } catch (e6) {
1410
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(`Could not fetch FilePart url '${url}': not a valid URL`);
1411
+ }
1412
+ if (scheme !== "http:" && scheme !== "https:") {
1413
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1414
+ `Could not fetch FilePart url '${url}': only http and https are supported`
1415
+ );
1416
+ }
1417
+ const controller = new AbortController();
1418
+ const timer = setTimeout(() => controller.abort(), URL_FETCH_TIMEOUT_MS);
1419
+ try {
1420
+ const response = await fetchImpl(url, { method: "GET", signal: controller.signal });
1421
+ if (response.status < 200 || response.status >= 300) {
1422
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1423
+ `Fetching FilePart url '${url}' returned HTTP ${response.status}`
1424
+ );
1425
+ }
1426
+ const declared = Number(_nullishCoalesce(response.headers.get("content-length"), () => ( "")));
1427
+ if (Number.isFinite(declared) && declared > MAX_FILE_BYTES) {
1428
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(urlTooLarge(url));
1429
+ }
1430
+ const bytes = await readCapped(response, url);
1431
+ const rawType = response.headers.get("content-type");
1432
+ const contentType = rawType ? rawType.split(";", 1)[0].trim().toLowerCase() || null : null;
1433
+ return { bytes, contentType };
1434
+ } catch (error) {
1435
+ if (error instanceof _chunk7IZHVYO2cjs.InvalidInputError) throw error;
1436
+ if (controller.signal.aborted) {
1437
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1438
+ `Could not fetch FilePart url '${url}': timed out after ${URL_FETCH_TIMEOUT_MS / 1e3} s`,
1439
+ { cause: error }
1440
+ );
1441
+ }
1442
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1443
+ `Could not fetch FilePart url '${url}': ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _56 => _56.message]), () => ( String(error)))}`,
1444
+ { cause: error }
1445
+ );
1446
+ } finally {
1447
+ clearTimeout(timer);
1448
+ }
1449
+ }
1450
+ async function readCapped(response, url) {
1451
+ const body = response.body;
1452
+ if (body === null || typeof body.getReader !== "function") {
1453
+ return new Uint8Array(await response.arrayBuffer());
1454
+ }
1455
+ const reader = body.getReader();
1456
+ const chunks = [];
1457
+ let total = 0;
1458
+ for (; ; ) {
1459
+ const { done, value } = await reader.read();
1460
+ if (done) break;
1461
+ total += value.byteLength;
1462
+ if (total > MAX_FILE_BYTES) {
1463
+ await reader.cancel().catch(() => {
1464
+ });
1465
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(urlTooLarge(url));
1466
+ }
1467
+ chunks.push(value);
1468
+ }
1469
+ const out = new Uint8Array(total);
1470
+ let at = 0;
1471
+ for (const c of chunks) {
1472
+ out.set(c, at);
1473
+ at += c.byteLength;
1474
+ }
1475
+ return out;
1476
+ }
1477
+ function toBase64(bytes) {
1478
+ const B = globalThis.Buffer;
1479
+ if (B !== void 0) return B.from(bytes).toString("base64");
1480
+ let binary = "";
1481
+ const CHUNK = 32768;
1482
+ for (let i = 0; i < bytes.length; i += CHUNK) {
1483
+ binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
1484
+ }
1485
+ return btoa(binary);
1486
+ }
1487
+ function placeholderText(parts) {
1488
+ return parts.map((p) => p.type === "text" ? String(_nullishCoalesce(p.text, () => ( ""))) : `[image: ${p.filename || "image"}]`).join("\n");
1489
+ }
1490
+ async function toInlineParts(parts, fetchImpl) {
1491
+ const resolved = await Promise.all(
1492
+ parts.map((p) => isFilePart(p) ? resolveFile(p, fetchImpl) : null)
1493
+ );
1494
+ let rawBytes = 0;
1495
+ const wire = parts.map((p, i) => {
1496
+ const file = resolved[i];
1497
+ if (file === null || file === void 0) return { type: "text", text: p.text };
1498
+ rawBytes += file.bytes.byteLength;
1499
+ return {
1500
+ type: "image",
1501
+ filename: file.filename,
1502
+ media_type: file.media_type,
1503
+ data: toBase64(file.bytes)
1504
+ };
1505
+ });
1506
+ return { wire, placeholder: placeholderText(wire), rawBytes };
1507
+ }
1508
+
1195
1509
  // src/memories/interface.ts
1196
1510
  var DOCUMENT_TYPES = [
1197
1511
  "ai-chat-conversation",
@@ -1215,12 +1529,11 @@ function isoOrNull(v) {
1215
1529
  if (v === void 0 || v === null) return null;
1216
1530
  return v instanceof Date ? v.toISOString() : v;
1217
1531
  }
1218
- function buildCreateBody(options) {
1219
- if (!options.document) throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("document is required");
1532
+ function createFields(options, defaultType) {
1220
1533
  const o2 = options;
1221
- const documentType = _nullishCoalesce(either(o2, "document_type", "documentType"), () => ( DEFAULT_DOCUMENT_TYPE));
1534
+ const documentType = _nullishCoalesce(either(o2, "document_type", "documentType"), () => ( defaultType));
1222
1535
  const mode = _nullishCoalesce(options.mode, () => ( DEFAULT_INGEST_MODE));
1223
- if (!DOCUMENT_TYPES.includes(documentType)) {
1536
+ if (documentType !== null && !DOCUMENT_TYPES.includes(documentType)) {
1224
1537
  throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1225
1538
  `Invalid document_type '${documentType}'. Expected one of: ${DOCUMENT_TYPES.join(", ")}`
1226
1539
  );
@@ -1230,22 +1543,70 @@ function buildCreateBody(options) {
1230
1543
  `Invalid mode '${mode}'. Expected one of: ${INGEST_MODES.join(", ")}`
1231
1544
  );
1232
1545
  }
1233
- return {
1234
- document: options.document,
1546
+ const userId = _nullishCoalesce(either(o2, "user_id", "userId"), () => ( null));
1547
+ const customerId = _nullishCoalesce(either(o2, "customer_id", "customerId"), () => ( null));
1548
+ const fields = {
1235
1549
  document_type: documentType,
1236
1550
  document_id: _nullishCoalesce(either(o2, "document_id", "documentId"), () => ( null)),
1237
1551
  document_created_at: isoOrNull(
1238
1552
  either(o2, "document_created_at", "documentCreatedAt")
1239
1553
  ),
1240
- user_id: _nullishCoalesce(either(o2, "user_id", "userId"), () => ( null)),
1241
- customer_id: _nullishCoalesce(either(o2, "customer_id", "customerId"), () => ( null)),
1554
+ user_id: userId,
1555
+ customer_id: customerId,
1242
1556
  // null, never `{}`. An empty path is not absence: the server treats one as
1243
1557
  // an error, because a caller asking to be narrowed and being ignored gets
1244
1558
  // widened instead.
1245
- scope: _nullishCoalesce(options.scope, () => ( null)),
1559
+ scope: normaliseCreateScope(options.scope, userId, customerId),
1246
1560
  mode,
1247
1561
  metadata: _nullishCoalesce(options.metadata, () => ( {}))
1248
1562
  };
1563
+ if (options.objective !== void 0 && options.objective !== null) {
1564
+ fields["objective"] = options.objective;
1565
+ }
1566
+ return fields;
1567
+ }
1568
+ function normaliseCreateScope(scope, userId, customerId) {
1569
+ if (scope === void 0 || scope === null) return null;
1570
+ const entries = Object.entries(scope);
1571
+ if (entries.length > 1 && entries.some(([, v]) => v === "self")) {
1572
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1573
+ `"self" can only be used alone, as scope={"client": "self"}; got ${JSON.stringify(scope)}`
1574
+ );
1575
+ }
1576
+ if (entries.length === 1 && entries[0][0] === "client" && entries[0][1] === "self") {
1577
+ if (userId !== null || customerId !== null) {
1578
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1579
+ 'scope={"client": "self"} names the client level, so it cannot be combined with user_id or customer_id'
1580
+ );
1581
+ }
1582
+ return null;
1583
+ }
1584
+ return scope;
1585
+ }
1586
+ function jsonDocument(document, where) {
1587
+ const n2 = normaliseContent(document, "document");
1588
+ if (n2 === null) return document;
1589
+ if (n2.kind === "parts") {
1590
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1591
+ `${where} cannot carry a FilePart. memories.create sends files as multipart; call it once per document that has files.`
1592
+ );
1593
+ }
1594
+ return n2.text;
1595
+ }
1596
+ function buildCreateBody(options) {
1597
+ const document = jsonDocument(options.document, "This request");
1598
+ if (!document) throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("document is required");
1599
+ return { document, ...createFields(options, DEFAULT_DOCUMENT_TYPE) };
1600
+ }
1601
+ function buildCreateManifest(options, parts, files) {
1602
+ let next = 0;
1603
+ const document = parts.map((p) => {
1604
+ if (!isFilePart(p)) return { type: "text", text: p.text };
1605
+ const index = next++;
1606
+ const file = files[index];
1607
+ return { type: "file", field: `file_${index}`, filename: file.filename, media_type: file.media_type };
1608
+ });
1609
+ return { document, ...createFields(options, null) };
1249
1610
  }
1250
1611
  var FORGET_MODES = ["preview", "direct"];
1251
1612
  var FORGET_DESCRIPTION_MIN = 3;
@@ -1266,21 +1627,63 @@ function buildForgetBody(options) {
1266
1627
  );
1267
1628
  }
1268
1629
  const o2 = options;
1269
- return {
1630
+ const body = {
1270
1631
  description,
1271
1632
  user_id: _nullishCoalesce(either(o2, "user_id", "userId"), () => ( null)),
1272
1633
  customer_id: _nullishCoalesce(either(o2, "customer_id", "customerId"), () => ( null)),
1273
1634
  scope: _nullishCoalesce(options.scope, () => ( null)),
1274
1635
  mode
1275
1636
  };
1637
+ const conversationId = either(o2, "conversation_id", "conversationId");
1638
+ if (conversationId !== void 0 && conversationId !== null) {
1639
+ if (typeof conversationId !== "string" || [...conversationId].length < 1 || [...conversationId].length > 200) {
1640
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("conversation_id must be a string of 1 to 200 characters");
1641
+ }
1642
+ body["conversation_id"] = conversationId;
1643
+ }
1644
+ return body;
1276
1645
  }
1277
1646
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "partial_success", "error", "cancelled"]);
1278
1647
  function createMemoriesInterface(transport, onForgotten) {
1279
1648
  return {
1280
1649
  async create(options) {
1281
1650
  const o2 = options;
1282
- await transport.checkCustomerId(_nullishCoalesce(o2["customer_id"], () => ( o2["customerId"])), "memories.create");
1283
- return transport.request("memories_create", { body: buildCreateBody(options) });
1651
+ const customerId = _nullishCoalesce(o2["customer_id"], () => ( o2["customerId"]));
1652
+ if (customerId !== void 0 && customerId !== null && customerId !== "") {
1653
+ await transport.checkCustomerId(customerId, "memories.create");
1654
+ }
1655
+ const n2 = normaliseContent(options.document, "document");
1656
+ if (n2 === null || n2.kind === "text") {
1657
+ return transport.request("memories_create", {
1658
+ body: buildCreateBody(options)
1659
+ });
1660
+ }
1661
+ buildCreateManifest(options, n2.parts.filter((p) => !isFilePart(p)), []);
1662
+ const fetchImpl = ((url, init) => transport.fetchExternal(url, init));
1663
+ const files = await Promise.all(
1664
+ n2.parts.filter(isFilePart).map((p) => resolveFile(p, fetchImpl))
1665
+ );
1666
+ const form = new FormData();
1667
+ form.set("manifest", JSON.stringify(buildCreateManifest(options, n2.parts, files)));
1668
+ files.forEach((file, i) => {
1669
+ form.set(
1670
+ `file_${i}`,
1671
+ new Blob([file.bytes], { type: file.media_type }),
1672
+ file.filename
1673
+ );
1674
+ });
1675
+ return transport.request("memories_create_multipart", {
1676
+ body: form,
1677
+ rawBody: true,
1678
+ // A server older than this route answers 404, or 405 because
1679
+ // /api/v1/memories/{memory_id} exists with other methods. Either would
1680
+ // otherwise read as "context not found" or a bare HTTP error.
1681
+ // InvalidInputError, with Python's message.
1682
+ mapError: (status, error) => status === 404 || status === 405 ? new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1683
+ "This Synap server does not support file parts in memories.create. Upgrade the Synap server, or send text only.",
1684
+ { correlationId: error.correlationId, cause: error }
1685
+ ) : void 0
1686
+ });
1284
1687
  },
1285
1688
  async batch_create(options) {
1286
1689
  const docs = options.documents;
@@ -1289,7 +1692,13 @@ function createMemoriesInterface(transport, onForgotten) {
1289
1692
  }
1290
1693
  const failFast = _nullishCoalesce(_nullishCoalesce(options.fail_fast, () => ( options.failFast)), () => ( false));
1291
1694
  return transport.request("memories_batch", {
1292
- body: { documents: docs.map(buildCreateBody), fail_fast: failFast }
1695
+ body: {
1696
+ documents: docs.map((d) => {
1697
+ jsonDocument(d.document, "memories.batch_create");
1698
+ return buildCreateBody(d);
1699
+ }),
1700
+ fail_fast: failFast
1701
+ }
1293
1702
  });
1294
1703
  },
1295
1704
  async create_from_file(options) {
@@ -1375,14 +1784,14 @@ function createMemoriesInterface(transport, onForgotten) {
1375
1784
  await transport.checkCustomerId(_nullishCoalesce(o2["customer_id"], () => ( o2["customerId"])), "memories.forget");
1376
1785
  const body = buildForgetBody(options);
1377
1786
  const result = await transport.request("memories_forget", { body });
1378
- 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";
1787
+ const removed = !!_optionalChain([result, 'optionalAccess', _57 => _57.deleted_ids, 'optionalAccess', _58 => _58.length]) || _optionalChain([result, 'optionalAccess', _59 => _59.status]) === "deleted" || _optionalChain([result, 'optionalAccess', _60 => _60.status]) === "partial";
1379
1788
  if (removed && onForgotten) {
1380
1789
  try {
1381
1790
  onForgotten({
1382
1791
  userId: _nullishCoalesce(body["user_id"], () => ( null)),
1383
1792
  customerId: _nullishCoalesce(body["customer_id"], () => ( null))
1384
1793
  });
1385
- } catch (e5) {
1794
+ } catch (e7) {
1386
1795
  }
1387
1796
  }
1388
1797
  return result;
@@ -1415,14 +1824,14 @@ function sleep2(ms, signal) {
1415
1824
  if (ms <= 0) return Promise.resolve();
1416
1825
  return new Promise((resolve, reject) => {
1417
1826
  const timer = setTimeout(() => {
1418
- _optionalChain([signal, 'optionalAccess', _50 => _50.removeEventListener, 'call', _51 => _51("abort", onAbort)]);
1827
+ _optionalChain([signal, 'optionalAccess', _61 => _61.removeEventListener, 'call', _62 => _62("abort", onAbort)]);
1419
1828
  resolve();
1420
1829
  }, ms);
1421
1830
  function onAbort() {
1422
1831
  clearTimeout(timer);
1423
- reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _52 => _52.reason]), () => ( new Error("Aborted"))));
1832
+ reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _63 => _63.reason]), () => ( new Error("Aborted"))));
1424
1833
  }
1425
- _optionalChain([signal, 'optionalAccess', _53 => _53.addEventListener, 'call', _54 => _54("abort", onAbort, { once: true })]);
1834
+ _optionalChain([signal, 'optionalAccess', _64 => _64.addEventListener, 'call', _65 => _65("abort", onAbort, { once: true })]);
1426
1835
  });
1427
1836
  }
1428
1837
 
@@ -1483,7 +1892,7 @@ function iso(v) {
1483
1892
  if (v === void 0) return void 0;
1484
1893
  return v instanceof Date ? v.toISOString() : v;
1485
1894
  }
1486
- function buildRecordMessageBody(options) {
1895
+ function buildRecordMessageBody(options, resolvedContent, field = "content") {
1487
1896
  const o2 = options;
1488
1897
  const conversationId = either2(o2, "conversation_id", "conversationId");
1489
1898
  const userId = either2(o2, "user_id", "userId");
@@ -1498,10 +1907,22 @@ function buildRecordMessageBody(options) {
1498
1907
  throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("content is required");
1499
1908
  }
1500
1909
  if (!userId) throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("user_id is required");
1910
+ let content = options.content;
1911
+ if (resolvedContent !== void 0) {
1912
+ content = resolvedContent;
1913
+ } else {
1914
+ const n2 = normaliseContent(options.content, field);
1915
+ if (_optionalChain([n2, 'optionalAccess', _66 => _66.kind]) === "parts") {
1916
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1917
+ "content holds a FilePart, whose bytes have to be read first. Send it with conversation.record_message."
1918
+ );
1919
+ }
1920
+ if (n2 !== null) content = n2.text;
1921
+ }
1501
1922
  const body = {
1502
1923
  conversation_id: conversationId,
1503
1924
  role: options.role,
1504
- content: options.content,
1925
+ content,
1505
1926
  user_id: userId,
1506
1927
  customer_id: customerId,
1507
1928
  // Python always sends this, defaulting to {}.
@@ -1602,7 +2023,7 @@ function storedBatchRows(bodies, result) {
1602
2023
  const r = _nullishCoalesce(result, () => ( {}));
1603
2024
  const results = Array.isArray(r["results"]) ? r["results"] : [];
1604
2025
  const errors = Array.isArray(r["errors"]) ? r["errors"] : [];
1605
- const failed = new Set(errors.map((e) => _optionalChain([e, 'optionalAccess', _55 => _55["index"]])));
2026
+ const failed = new Set(errors.map((e) => _optionalChain([e, 'optionalAccess', _67 => _67["index"]])));
1606
2027
  const stored = bodies.filter((_, index) => !failed.has(index));
1607
2028
  if (stored.length !== results.length) return [];
1608
2029
  const pairs = [];
@@ -1644,6 +2065,24 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1644
2065
  inFlight: _nullishCoalesce(writesInFlight.get(conversationId), () => ( 0))
1645
2066
  };
1646
2067
  };
2068
+ const fetchImpl = ((url, init) => transport.fetchExternal(url, init));
2069
+ const validateMessage = (options, field = "content") => {
2070
+ if (_optionalChain([normaliseContent, 'call', _68 => _68(options.content, field), 'optionalAccess', _69 => _69.kind]) === "parts") {
2071
+ buildRecordMessageBody(options, "", field);
2072
+ } else {
2073
+ buildRecordMessageBody(options, void 0, field);
2074
+ }
2075
+ };
2076
+ const prepareMessage = async (options, field = "content") => {
2077
+ const n2 = normaliseContent(options.content, field);
2078
+ if (_optionalChain([n2, 'optionalAccess', _70 => _70.kind]) !== "parts") {
2079
+ const body = buildRecordMessageBody(options, void 0, field);
2080
+ return { body, mirror: String(_nullishCoalesce(body["content"], () => ( ""))) };
2081
+ }
2082
+ validateMessage(options, field);
2083
+ const inline = await toInlineParts(n2.parts, fetchImpl);
2084
+ return { body: buildRecordMessageBody(options, inline.wire), mirror: inline.placeholder };
2085
+ };
1647
2086
  const convId = (v) => {
1648
2087
  const id = typeof v === "string" ? v : _nullishCoalesce(v.conversation_id, () => ( v.conversationId));
1649
2088
  if (!id) throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("conversation_id is required");
@@ -1656,7 +2095,9 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1656
2095
  _nullishCoalesce(options["customer_id"], () => ( options["customerId"])),
1657
2096
  "conversation.record_message"
1658
2097
  );
1659
- const body = withTurnModel(buildRecordMessageBody(options), options);
2098
+ const prepared = await prepareMessage(options);
2099
+ const body = withTurnModel(prepared.body, options);
2100
+ const mirror = prepared.mirror;
1660
2101
  const conversationId = String(_nullishCoalesce(body["conversation_id"], () => ( "")));
1661
2102
  writeStarted(conversationId);
1662
2103
  let result;
@@ -1668,7 +2109,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1668
2109
  onTurn({
1669
2110
  conversationId,
1670
2111
  role: String(_nullishCoalesce(body["role"], () => ( "user"))),
1671
- content: String(_nullishCoalesce(body["content"], () => ( ""))),
2112
+ content: mirror,
1672
2113
  timestamp: body["timestamp"],
1673
2114
  ...confirmation(result, conversationId)
1674
2115
  });
@@ -1689,7 +2130,11 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1689
2130
  "conversation.record_messages_batch"
1690
2131
  );
1691
2132
  }
1692
- const bodies = messages.map((m) => withTurnModel(buildRecordMessageBody(m), m));
2133
+ const field = (i) => `messages[${i}].content`;
2134
+ messages.forEach((m, i) => validateMessage(m, field(i)));
2135
+ const prepared = await Promise.all(messages.map((m, i) => prepareMessage(m, field(i))));
2136
+ const bodies = prepared.map((p, i) => withTurnModel(p.body, messages[i]));
2137
+ const mirrors = new Map(prepared.map((p, i) => [bodies[i], p.mirror]));
1693
2138
  const result = await transport.request("conversations_messages_batch", {
1694
2139
  body: { messages: bodies }
1695
2140
  });
@@ -1698,7 +2143,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1698
2143
  onTurn({
1699
2144
  conversationId,
1700
2145
  role: String(_nullishCoalesce(body["role"], () => ( "user"))),
1701
- content: String(_nullishCoalesce(body["content"], () => ( ""))),
2146
+ content: _nullishCoalesce(mirrors.get(body), () => ( String(_nullishCoalesce(body["content"], () => ( ""))))),
1702
2147
  timestamp: body["timestamp"],
1703
2148
  ...confirmation(row, conversationId)
1704
2149
  });
@@ -1721,7 +2166,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1721
2166
  const raw = await transport.request("conversations_ingest", { body });
1722
2167
  const result = {
1723
2168
  ...raw,
1724
- warnings: Array.isArray(_optionalChain([raw, 'optionalAccess', _56 => _56.warnings])) ? raw.warnings.map(String) : []
2169
+ warnings: Array.isArray(_optionalChain([raw, 'optionalAccess', _71 => _71.warnings])) ? raw.warnings.map(String) : []
1725
2170
  };
1726
2171
  onWrite({
1727
2172
  userId: body["user_id"],
@@ -1755,7 +2200,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1755
2200
  if (!search) return response2;
1756
2201
  try {
1757
2202
  return await localShortTerm.historyExcerpts(id, response2, options.query);
1758
- } catch (e6) {
2203
+ } catch (e8) {
1759
2204
  return response2;
1760
2205
  }
1761
2206
  };
@@ -1765,8 +2210,8 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1765
2210
  pathParams: { conversation_id: id },
1766
2211
  query: { style }
1767
2212
  });
1768
- const response = _nullishCoalesce(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _57 => _57["context_for_prompt"]]), () => ( result)), () => ( {}));
1769
- _optionalChain([localShortTerm, 'access', _58 => _58.reseed, 'optionalCall', _59 => _59(id, response)]);
2213
+ const response = _nullishCoalesce(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _72 => _72["context_for_prompt"]]), () => ( result)), () => ( {}));
2214
+ _optionalChain([localShortTerm, 'access', _73 => _73.reseed, 'optionalCall', _74 => _74(id, response)]);
1770
2215
  return withHistory(response);
1771
2216
  },
1772
2217
  async compact(options) {
@@ -1931,7 +2376,7 @@ function createDataInterface(transport, onDeleted) {
1931
2376
  customerId: _nullishCoalesce(body["customer_id"], () => ( null)),
1932
2377
  conversationId: _nullishCoalesce(body["conversation_id"], () => ( null))
1933
2378
  });
1934
- } catch (e7) {
2379
+ } catch (e9) {
1935
2380
  }
1936
2381
  }
1937
2382
  return final;
@@ -2027,6 +2472,7 @@ function createCacheNamespace(cache) {
2027
2472
  }
2028
2473
 
2029
2474
  // src/instance/interface.ts
2475
+ var CONTENT_PARTS_METADATA_KEY = "synap_content_parts";
2030
2476
  var DEFAULT_GRPC_HOST = "synap-cloud-prod.maximem.ai";
2031
2477
  var DEFAULT_GRPC_PORT = 443;
2032
2478
  function envPort() {
@@ -2074,26 +2520,34 @@ function jsonOrText(value) {
2074
2520
  (_k, v) => typeof v === "bigint" ? String(v) : v
2075
2521
  );
2076
2522
  return out === void 0 ? String(value) : out;
2077
- } catch (e8) {
2523
+ } catch (e10) {
2078
2524
  try {
2079
2525
  return String(value);
2080
- } catch (e9) {
2526
+ } catch (e11) {
2081
2527
  return "";
2082
2528
  }
2083
2529
  }
2084
2530
  }
2085
- function createInstanceNamespace(credentials, cache, onTurn, agentModel = () => ({}), onToolResult, checkCustomerId3 = async () => {
2086
- }) {
2531
+ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel, agentModelOrToolResult, onToolResultOrCheck, checkCustomerIdArg) {
2532
+ const defaultFetch = ((url, init) => globalThis.fetch(url, init));
2533
+ const imageFirst = fetchOrAgentModel !== void 0 && (fetchOrAgentModel.length > 0 || agentModelOrToolResult === void 0);
2534
+ const fetchUrl2 = imageFirst ? fetchOrAgentModel : defaultFetch;
2535
+ const agentModel = _nullishCoalesce((imageFirst ? agentModelOrToolResult : fetchOrAgentModel), () => ( (() => ({}))));
2536
+ const onToolResult = imageFirst ? onToolResultOrCheck : agentModelOrToolResult;
2537
+ const checkCustomerId3 = _nullishCoalesce((imageFirst ? checkCustomerIdArg : onToolResultOrCheck), () => ( (async () => {
2538
+ })));
2539
+ const hasCustomerIdCheck = (imageFirst ? checkCustomerIdArg : onToolResultOrCheck) !== void 0;
2087
2540
  let client = null;
2088
2541
  const openSessions = /* @__PURE__ */ new Map();
2089
2542
  let dispatchCompaction = null;
2090
2543
  let applyCompaction = null;
2091
2544
  let onListen = null;
2545
+ let listenBlockedBy = null;
2092
2546
  let onConversationState = null;
2093
2547
  const internals = {
2094
2548
  onCompactionUpdate(conversationId, bundle) {
2095
- _optionalChain([applyCompaction, 'optionalCall', _60 => _60(bundle)]);
2096
- _optionalChain([dispatchCompaction, 'optionalCall', _61 => _61(conversationId, bundle)]);
2549
+ _optionalChain([applyCompaction, 'optionalCall', _75 => _75(bundle)]);
2550
+ _optionalChain([dispatchCompaction, 'optionalCall', _76 => _76(conversationId, bundle)]);
2097
2551
  },
2098
2552
  setCompactionApplier(apply) {
2099
2553
  applyCompaction = apply;
@@ -2101,14 +2555,17 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2101
2555
  setOnListen(handle) {
2102
2556
  onListen = handle;
2103
2557
  },
2558
+ blockListen(message) {
2559
+ listenBlockedBy = message;
2560
+ },
2104
2561
  setConversationStateHandler(handle) {
2105
2562
  onConversationState = handle;
2106
2563
  },
2107
2564
  sendContextUsed(event) {
2108
- _optionalChain([client, 'optionalAccess', _62 => _62.sendContextUsed, 'call', _63 => _63(event)]);
2565
+ _optionalChain([client, 'optionalAccess', _77 => _77.sendContextUsed, 'call', _78 => _78(event)]);
2109
2566
  },
2110
2567
  sendContextAssembled(event) {
2111
- _optionalChain([client, 'optionalAccess', _64 => _64.sendContextAssembled, 'call', _65 => _65(event)]);
2568
+ _optionalChain([client, 'optionalAccess', _79 => _79.sendContextAssembled, 'call', _80 => _80(event)]);
2112
2569
  },
2113
2570
  setCompactionDispatcher(dispatch) {
2114
2571
  dispatchCompaction = dispatch;
@@ -2130,19 +2587,39 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2130
2587
  ...customerId ? { customer_id: customerId } : {}
2131
2588
  });
2132
2589
  openSessions.set(conversationId, sessionId);
2133
- } catch (e10) {
2590
+ } catch (e12) {
2591
+ }
2592
+ }
2593
+ let tail = Promise.resolve();
2594
+ let queued = 0;
2595
+ function inOrder(prepared, send, sync) {
2596
+ if (prepared === null && queued === 0) {
2597
+ send(sync);
2598
+ return Promise.resolve();
2134
2599
  }
2600
+ _optionalChain([prepared, 'optionalAccess', _81 => _81.catch, 'call', _82 => _82(() => {
2601
+ })]);
2602
+ queued += 1;
2603
+ const run = tail.then(async () => {
2604
+ send(prepared === null ? sync : await prepared);
2605
+ });
2606
+ const done = () => {
2607
+ queued -= 1;
2608
+ };
2609
+ tail = run.then(done, done);
2610
+ return run;
2135
2611
  }
2136
2612
  const namespace = {
2137
2613
  async listen(options = {}) {
2614
+ if (listenBlockedBy !== null) throw new (0, _chunk7IZHVYO2cjs.SynapPermanentError)(listenBlockedBy);
2138
2615
  if (client !== null) {
2139
2616
  throw new (0, _chunk7IZHVYO2cjs.ListeningAlreadyActiveError)("Listening is already active on this instance");
2140
2617
  }
2141
2618
  try {
2142
- _optionalChain([onListen, 'optionalCall', _66 => _66()]);
2143
- } catch (e11) {
2619
+ _optionalChain([onListen, 'optionalCall', _83 => _83()]);
2620
+ } catch (e13) {
2144
2621
  }
2145
- const { GrpcStreamClient } = await Promise.resolve().then(() => _interopRequireWildcard(require("./stream-client-IPHDTXQO.cjs")));
2622
+ const { GrpcStreamClient } = await Promise.resolve().then(() => _interopRequireWildcard(require("./stream-client-TDHTS7F4.cjs")));
2146
2623
  const onContext = _nullishCoalesce(options.on_context, () => ( options.onContext));
2147
2624
  const onDisconnect = _nullishCoalesce(options.on_disconnect, () => ( options.onDisconnect));
2148
2625
  const onReconnect = _nullishCoalesce(options.on_reconnect, () => ( options.onReconnect));
@@ -2157,17 +2634,17 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2157
2634
  internals.onCompactionUpdate(conversationId, bundle);
2158
2635
  },
2159
2636
  onConversationState: (conversationId, messageCount) => {
2160
- _optionalChain([onConversationState, 'optionalCall', _67 => _67(conversationId, messageCount)]);
2637
+ _optionalChain([onConversationState, 'optionalCall', _84 => _84(conversationId, messageCount)]);
2161
2638
  },
2162
2639
  onStateChange: (state) => {
2163
2640
  if (state !== "connected") openSessions.clear();
2164
2641
  if (state === "reconnecting") {
2165
2642
  reconnectAttempts += 1;
2166
- _optionalChain([onReconnect, 'optionalCall', _68 => _68(reconnectAttempts)]);
2643
+ _optionalChain([onReconnect, 'optionalCall', _85 => _85(reconnectAttempts)]);
2167
2644
  } else if (state === "disconnected") {
2168
- const stopped = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _69 => _69.lastError]), () => ( null));
2645
+ const stopped = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _86 => _86.lastError]), () => ( null));
2169
2646
  const reason = stopped === null ? "stream disconnected" : `credit_stop:${_nullishCoalesce(stopped.reason, () => ( "unknown"))}`;
2170
- _optionalChain([onDisconnect, 'optionalCall', _70 => _70(reason)]);
2647
+ _optionalChain([onDisconnect, 'optionalCall', _87 => _87(reason)]);
2171
2648
  }
2172
2649
  }
2173
2650
  });
@@ -2177,7 +2654,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2177
2654
  } catch (error) {
2178
2655
  if (error instanceof _chunk7IZHVYO2cjs.SynapError) throw error;
2179
2656
  throw new (0, _chunk7IZHVYO2cjs.SynapError)(
2180
- `Could not open the Synap anticipation stream: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _71 => _71.message]), () => ( String(error)))}`,
2657
+ `Could not open the Synap anticipation stream: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _88 => _88.message]), () => ( String(error)))}`,
2181
2658
  { cause: error }
2182
2659
  );
2183
2660
  }
@@ -2202,14 +2679,16 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2202
2679
  session_id: sessionId,
2203
2680
  conversation_id: conversationId
2204
2681
  });
2205
- } catch (e12) {
2682
+ } catch (e14) {
2206
2683
  }
2207
2684
  },
2208
2685
  async send_message(options) {
2209
- await checkCustomerId3(
2210
- _nullishCoalesce(options.customer_id, () => ( options.customerId)),
2211
- "instance.send_message"
2212
- );
2686
+ if (hasCustomerIdCheck) {
2687
+ await checkCustomerId3(
2688
+ _nullishCoalesce(options.customer_id, () => ( options.customerId)),
2689
+ "instance.send_message"
2690
+ );
2691
+ }
2213
2692
  if (client === null) throw new (0, _chunk7IZHVYO2cjs.ListeningNotActiveError)("Listening is not active");
2214
2693
  const eventType = _nullishCoalesce(_nullishCoalesce(options.event_type, () => ( options.eventType)), () => ( "user_message"));
2215
2694
  if (!KNOWN_EVENT_TYPES.has(eventType)) {
@@ -2220,46 +2699,68 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2220
2699
  if (options.content === void 0 || options.content === null) {
2221
2700
  throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("content is required");
2222
2701
  }
2223
- const conversationId = _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( ""));
2224
- ensureSession(
2225
- conversationId,
2226
- _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2227
- _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( ""))
2228
- );
2229
- if (eventType === "user_message" || eventType === "assistant_message") {
2230
- _optionalChain([onTurn, 'optionalCall', _72 => _72({
2702
+ const parts = normaliseContent(options.content, "content");
2703
+ const emit = ({ content, metadata }) => {
2704
+ if (client === null) throw new (0, _chunk7IZHVYO2cjs.ListeningNotActiveError)("Listening is not active");
2705
+ const conversationId = _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( ""));
2706
+ ensureSession(
2231
2707
  conversationId,
2708
+ _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2709
+ _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( ""))
2710
+ );
2711
+ if (eventType === "user_message" || eventType === "assistant_message") {
2712
+ _optionalChain([onTurn, 'optionalCall', _89 => _89({
2713
+ conversationId,
2714
+ role: _nullishCoalesce(options.role, () => ( "user")),
2715
+ content
2716
+ })]);
2717
+ }
2718
+ client.sendConversationEvent({
2719
+ event_type: eventType,
2720
+ content,
2232
2721
  role: _nullishCoalesce(options.role, () => ( "user")),
2233
- content: options.content
2234
- })]);
2722
+ conversation_id: _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( "")),
2723
+ user_id: _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2724
+ customer_id: _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( "")),
2725
+ session_id: _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(options.session_id, () => ( options.sessionId)), () => ( openSessions.get(conversationId))), () => ( "")),
2726
+ metadata: _nullishCoalesce(withAgentModel(metadata, agentModelOf(options), agentModel(), true), () => ( {})),
2727
+ timestamp_ms: Date.now(),
2728
+ tool_name: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")),
2729
+ // Python serialises tool_args with json.dumps into tool_args_json.
2730
+ tool_args_json: (() => {
2731
+ const a = _nullishCoalesce(options.tool_args, () => ( options.toolArgs));
2732
+ return a === void 0 ? "" : jsonOrText(a);
2733
+ })(),
2734
+ tool_result_json: toolResultJson(_nullishCoalesce(options.tool_result, () => ( options.toolResult))),
2735
+ tool_call_id: _nullishCoalesce(_nullishCoalesce(options.tool_call_id, () => ( options.toolCallId)), () => ( "")),
2736
+ search_queries: _nullishCoalesce(_nullishCoalesce(options.search_queries, () => ( options.searchQueries)), () => ( [])),
2737
+ context_types: _nullishCoalesce(_nullishCoalesce(options.context_types, () => ( options.contextTypes)), () => ( [])),
2738
+ ...(() => {
2739
+ const sp = _nullishCoalesce(options.scope_path, () => ( options.scopePath));
2740
+ return sp && Object.keys(sp).length > 0 ? { scope: sp } : {};
2741
+ })()
2742
+ });
2743
+ };
2744
+ if (_optionalChain([parts, 'optionalAccess', _90 => _90.kind]) !== "parts") {
2745
+ const content = _optionalChain([parts, 'optionalAccess', _91 => _91.kind]) === "text" ? parts.text : options.content;
2746
+ return inOrder(null, emit, { content, metadata: _nullishCoalesce(options.metadata, () => ( {})) });
2235
2747
  }
2236
- client.sendConversationEvent({
2237
- event_type: eventType,
2238
- content: options.content,
2239
- role: _nullishCoalesce(options.role, () => ( "user")),
2240
- conversation_id: _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( "")),
2241
- user_id: _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2242
- customer_id: _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( "")),
2243
- session_id: _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(options.session_id, () => ( options.sessionId)), () => ( openSessions.get(conversationId))), () => ( "")),
2244
- metadata: _nullishCoalesce(withAgentModel(options.metadata, agentModelOf(options), agentModel(), true), () => ( {})),
2245
- timestamp_ms: Date.now(),
2246
- tool_name: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")),
2247
- // Python serialises tool_args with json.dumps into tool_args_json.
2248
- tool_args_json: (() => {
2249
- const a = _nullishCoalesce(options.tool_args, () => ( options.toolArgs));
2250
- return a === void 0 ? "" : jsonOrText(a);
2251
- })(),
2252
- tool_result_json: toolResultJson(_nullishCoalesce(options.tool_result, () => ( options.toolResult))),
2253
- tool_call_id: _nullishCoalesce(_nullishCoalesce(options.tool_call_id, () => ( options.toolCallId)), () => ( "")),
2254
- search_queries: _nullishCoalesce(_nullishCoalesce(options.search_queries, () => ( options.searchQueries)), () => ( [])),
2255
- context_types: _nullishCoalesce(_nullishCoalesce(options.context_types, () => ( options.contextTypes)), () => ( [])),
2256
- // The proto's `scope`: the conversation's rung, kept from the first
2257
- // event that names one. Omitted when absent or empty, as in Python.
2258
- ...(() => {
2259
- const sp = _nullishCoalesce(options.scope_path, () => ( options.scopePath));
2260
- return sp && Object.keys(sp).length > 0 ? { scope: sp } : {};
2261
- })()
2262
- });
2748
+ const prepared = (async () => {
2749
+ const inline = await toInlineParts(parts.parts, fetchUrl2);
2750
+ if (inline.rawBytes > MAX_STREAM_IMAGE_BYTES) {
2751
+ throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
2752
+ `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.`
2753
+ );
2754
+ }
2755
+ return {
2756
+ content: inline.placeholder,
2757
+ metadata: {
2758
+ ..._nullishCoalesce(options.metadata, () => ( {})),
2759
+ [CONTENT_PARTS_METADATA_KEY]: JSON.stringify(inline.wire)
2760
+ }
2761
+ };
2762
+ })();
2763
+ return inOrder(prepared, emit);
2263
2764
  },
2264
2765
  async record_tool_call(options) {
2265
2766
  await namespace.send_message({
@@ -2279,7 +2780,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2279
2780
  async record_tool_result(options) {
2280
2781
  const conversationId = _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( ""));
2281
2782
  if (conversationId) {
2282
- _optionalChain([onToolResult, 'optionalCall', _73 => _73({ conversationId, result: options.result, toolName: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")) })]);
2783
+ _optionalChain([onToolResult, 'optionalCall', _92 => _92({ conversationId, result: options.result, toolName: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")) })]);
2283
2784
  }
2284
2785
  await namespace.send_message({
2285
2786
  content: "",
@@ -2303,24 +2804,27 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2303
2804
  _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2304
2805
  _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( ""))
2305
2806
  );
2306
- client.sendConversationEvent({
2307
- // Python emits reasoning as an `agent_thinking` conversation event.
2308
- event_type: "agent_thinking",
2309
- content: options.content,
2310
- // Deliberately no role. A thought is not the assistant's reply, and
2311
- // this went out as 'assistant' from the day it shipped: the server
2312
- // checked role before event_type, so every reasoning step any client
2313
- // sent was filed as the final answer and the reasoning path never ran.
2314
- // Sending no role is correct against both the fixed server and one that
2315
- // has not been updated yet.
2316
- role: "",
2317
- conversation_id: _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( "")),
2318
- user_id: _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2319
- customer_id: _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( "")),
2320
- session_id: _nullishCoalesce(_nullishCoalesce(options.session_id, () => ( options.sessionId)), () => ( "")),
2321
- metadata: thinkingMetadata(options),
2322
- timestamp_ms: Date.now()
2323
- });
2807
+ return inOrder(null, () => {
2808
+ if (client === null) throw new (0, _chunk7IZHVYO2cjs.ListeningNotActiveError)("Listening is not active");
2809
+ client.sendConversationEvent({
2810
+ // Python emits reasoning as an `agent_thinking` conversation event.
2811
+ event_type: "agent_thinking",
2812
+ content: options.content,
2813
+ // Deliberately no role. A thought is not the assistant's reply, and
2814
+ // this went out as 'assistant' from the day it shipped: the server
2815
+ // checked role before event_type, so every reasoning step any client
2816
+ // sent was filed as the final answer and the reasoning path never ran.
2817
+ // Sending no role is correct against both the fixed server and one that
2818
+ // has not been updated yet.
2819
+ role: "",
2820
+ conversation_id: _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( "")),
2821
+ user_id: _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2822
+ customer_id: _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( "")),
2823
+ session_id: _nullishCoalesce(_nullishCoalesce(options.session_id, () => ( options.sessionId)), () => ( "")),
2824
+ metadata: thinkingMetadata(options),
2825
+ timestamp_ms: Date.now()
2826
+ });
2827
+ }, void 0);
2324
2828
  },
2325
2829
  get is_listening() {
2326
2830
  return client !== null && client.isConnected;
@@ -2331,7 +2835,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2331
2835
  }
2332
2836
 
2333
2837
  // src/version.ts
2334
- var SDK_VERSION = "0.6.5";
2838
+ var SDK_VERSION = "0.6.7";
2335
2839
 
2336
2840
  // src/registry.ts
2337
2841
  var instances = /* @__PURE__ */ new Map();
@@ -2471,7 +2975,7 @@ var ShortTermStore = class {
2471
2975
  if (this.#archive !== null) {
2472
2976
  try {
2473
2977
  this.#archive.add(conversationId, role, content, stamp, { messageId: _nullishCoalesce(confirmation.messageId, () => ( null)) });
2474
- } catch (e13) {
2978
+ } catch (e15) {
2475
2979
  }
2476
2980
  }
2477
2981
  const entry = _nullishCoalesce(this.#entries.get(conversationId), () => ( this.#blank(conversationId)));
@@ -2799,7 +3303,7 @@ var TurnStore = (_class3 = class {
2799
3303
  }
2800
3304
  /** Turns the server also holds: archived tool results are local only. Python: `count`. */
2801
3305
  count(conversationId) {
2802
- 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;
3306
+ return (_nullishCoalesce(_optionalChain([this, 'access', _93 => _93.#conversations, 'access', _94 => _94.get, 'call', _95 => _95(conversationId), 'optionalAccess', _96 => _96.turns]), () => ( []))).filter((t) => t.role !== "tool").length;
2803
3307
  }
2804
3308
  sizeBytes() {
2805
3309
  let n2 = 0;
@@ -2978,7 +3482,7 @@ function askedKinds(query) {
2978
3482
  }
2979
3483
  function asksHowItStarted(query) {
2980
3484
  const spec = _chunkBYUGILQIcjs.HISTORY_SEARCH.early_query;
2981
- if (!_optionalChain([spec, 'optionalAccess', _78 => _78.pattern])) return false;
3485
+ if (!_optionalChain([spec, 'optionalAccess', _97 => _97.pattern])) return false;
2982
3486
  return new RegExp(spec.pattern, (_nullishCoalesce(spec.flags, () => ( ""))).includes("i") ? "i" : "").test(_nullishCoalesce(query, () => ( "")));
2983
3487
  }
2984
3488
  async function searchTurns(turns, query, options = {}) {
@@ -3246,7 +3750,7 @@ function overlayLocalRecentTurns(response, store, conversationId, configured) {
3246
3750
  compacted_at: orLocal("compacted_at", entry.compactedAt),
3247
3751
  conversation_id: conversationId
3248
3752
  };
3249
- } catch (e14) {
3753
+ } catch (e16) {
3250
3754
  }
3251
3755
  }
3252
3756
 
@@ -3259,7 +3763,7 @@ function stringify(value) {
3259
3763
  if (t === "string" || t === "number" || t === "boolean") return String(value);
3260
3764
  try {
3261
3765
  return _nullishCoalesce(JSON.stringify(value), () => ( ""));
3262
- } catch (e15) {
3766
+ } catch (e17) {
3263
3767
  return String(value);
3264
3768
  }
3265
3769
  }
@@ -3557,7 +4061,7 @@ async function tryServeFromCache(cache, scope, params, maxItems) {
3557
4061
  });
3558
4062
  if (hit === null) return { response: null, hit: null };
3559
4063
  return { response: buildAnticipationResponse(hit), hit };
3560
- } catch (e16) {
4064
+ } catch (e18) {
3561
4065
  return { response: null, hit: null };
3562
4066
  }
3563
4067
  }
@@ -4060,6 +4564,7 @@ var SynapClient = (_class4 = class _SynapClient {
4060
4564
  #closed = false;
4061
4565
  #initialized = false;
4062
4566
  #identity;
4567
+ #localMode = false;
4063
4568
  #registryKeys;
4064
4569
  #compactionSubscribers;
4065
4570
  #shortTerm;
@@ -4078,8 +4583,9 @@ var SynapClient = (_class4 = class _SynapClient {
4078
4583
  #turns;
4079
4584
  #fetchHooks;
4080
4585
  constructor(options = {}) {
4081
- const credentials = resolveCredentials(options);
4082
4586
  const resolvedBaseUrl = resolveBaseUrl(options);
4587
+ const localMode = isLocalMode(options.apiKey, resolvedBaseUrl);
4588
+ const credentials = resolveCredentials(options, localMode);
4083
4589
  validateInstanceId(credentials.instanceId);
4084
4590
  const registryKey = buildRegistryKey(credentials.instanceId, credentials.apiKey);
4085
4591
  if (options._force_new !== true) {
@@ -4095,6 +4601,7 @@ var SynapClient = (_class4 = class _SynapClient {
4095
4601
  }
4096
4602
  }
4097
4603
  this.#registryKeys = options._force_new === true ? [] : [registryKey];
4604
+ this.#localMode = localMode;
4098
4605
  this.#transport = new HttpTransport({
4099
4606
  credentials,
4100
4607
  // SYNAP_BASE_URL is honoured, as Python does (sdk.py) and as the 0.3.x
@@ -4177,7 +4684,7 @@ var SynapClient = (_class4 = class _SynapClient {
4177
4684
  ...customerId !== void 0 ? { customer_id: customerId } : {}
4178
4685
  });
4179
4686
  return profileContext(profile);
4180
- } catch (e17) {
4687
+ } catch (e19) {
4181
4688
  return null;
4182
4689
  }
4183
4690
  }
@@ -4217,7 +4724,7 @@ var SynapClient = (_class4 = class _SynapClient {
4217
4724
  this.#localEncoder = _nullishCoalesce(_nullishCoalesce(options.history_search_encoder, () => ( options.historySearchEncoder)), () => ( null));
4218
4725
  const modelOption = options.history_search_model !== void 0 ? options.history_search_model : options.historySearchModel;
4219
4726
  this.#localModelName = modelOption === void 0 ? "auto" : modelOption;
4220
- if (_optionalChain([this, 'access', _79 => _79.#localEncoder, 'optionalAccess', _80 => _80.model]) === _chunkBYUGILQIcjs.SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(this.#localEncoder);
4727
+ if (_optionalChain([this, 'access', _98 => _98.#localEncoder, 'optionalAccess', _99 => _99.model]) === _chunkBYUGILQIcjs.SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(this.#localEncoder);
4221
4728
  this.#turns = new TurnCounter();
4222
4729
  this.conversation = createConversationNamespace(
4223
4730
  this.#transport,
@@ -4287,11 +4794,18 @@ var SynapClient = (_class4 = class _SynapClient {
4287
4794
  ({ conversationId, role, content }) => {
4288
4795
  this.#shortTerm.appendTurn(conversationId, role, content);
4289
4796
  },
4797
+ // A FilePart given by url is read with the same fetch as everything else.
4798
+ ((url, init) => this.#transport.fetchExternal(url, init)),
4290
4799
  () => this.#agentModel,
4291
4800
  ({ conversationId, result, toolName }) => this.archive_tool_result(conversationId, result, { tool_name: toolName }),
4292
4801
  (customerId, where) => this.#transport.checkCustomerId(customerId, where)
4293
4802
  );
4294
4803
  this.instance._internal.setOnListen(() => this.#startLocalModel());
4804
+ if (localMode) {
4805
+ this.instance._internal.blockListen(
4806
+ "Not available in the open-source server: listen() needs the gRPC stream and anticipation, which it does not have."
4807
+ );
4808
+ }
4295
4809
  this.instance._internal.setCompactionApplier((bundle) => {
4296
4810
  this.#shortTerm.applyCompaction(bundle);
4297
4811
  });
@@ -4405,12 +4919,15 @@ var SynapClient = (_class4 = class _SynapClient {
4405
4919
  }
4406
4920
  /** Runs whoami at most once, however many calls arrive together. */
4407
4921
  #resolveIdentity() {
4408
- this.#identity ??= this.#whoami();
4922
+ this.#identity ??= this.#whoami().catch((error) => {
4923
+ this.#identity = void 0;
4924
+ throw error;
4925
+ });
4409
4926
  return this.#identity;
4410
4927
  }
4411
4928
  async #whoami() {
4412
4929
  const credentials = this.#transport.currentCredentials();
4413
- if (credentials.clientId !== "" && credentials.instanceId !== "") return;
4930
+ if (!this.#localMode && credentials.clientId !== "" && credentials.instanceId !== "") return;
4414
4931
  try {
4415
4932
  const whoami = await this.#transport.request("whoami", {});
4416
4933
  const resolvedClientId = String(_nullishCoalesce(whoami["client_id"], () => ( "")));
@@ -4426,7 +4943,21 @@ var SynapClient = (_class4 = class _SynapClient {
4426
4943
  this.#registryKeys.push(resolvedInstanceId);
4427
4944
  }
4428
4945
  }
4429
- } catch (e18) {
4946
+ } catch (error) {
4947
+ if (this.#localMode) {
4948
+ throw new (0, _chunk7IZHVYO2cjs.AuthenticationError)(
4949
+ `Could not reach the Synap server at ${this.#transport.baseUrl}, or it did not identify itself: GET /api/v1/auth/whoami failed (${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _100 => _100.message]), () => ( String(error)))}).`,
4950
+ { cause: error }
4951
+ );
4952
+ }
4953
+ }
4954
+ if (this.#localMode) {
4955
+ const known = this.#transport.currentCredentials();
4956
+ if (known.clientId === "" || known.instanceId === "") {
4957
+ throw new (0, _chunk7IZHVYO2cjs.AuthenticationError)(
4958
+ `The Synap server at ${this.#transport.baseUrl} did not identify itself: GET /api/v1/auth/whoami returned no client_id or instance_id.`
4959
+ );
4960
+ }
4430
4961
  }
4431
4962
  }
4432
4963
  /**
@@ -4599,7 +5130,7 @@ var SynapClient = (_class4 = class _SynapClient {
4599
5130
  if (conversationState && !merged.scopes_queried.includes("conversation")) {
4600
5131
  merged.scopes_queried.unshift("conversation");
4601
5132
  }
4602
- } catch (e19) {
5133
+ } catch (e20) {
4603
5134
  }
4604
5135
  }
4605
5136
  merged.formatted_context = formatForPrompt(merged, {
@@ -4651,7 +5182,7 @@ var SynapClient = (_class4 = class _SynapClient {
4651
5182
  // not carry the caller's words.
4652
5183
  query_count: distinctQueryCount(_nullishCoalesce(options["search_query"], () => ( options["searchQuery"])))
4653
5184
  });
4654
- } catch (e20) {
5185
+ } catch (e21) {
4655
5186
  }
4656
5187
  }
4657
5188
  /**
@@ -4676,7 +5207,7 @@ var SynapClient = (_class4 = class _SynapClient {
4676
5207
  }),
4677
5208
  scope
4678
5209
  });
4679
- } catch (e21) {
5210
+ } catch (e22) {
4680
5211
  }
4681
5212
  }
4682
5213
  /**
@@ -4737,14 +5268,14 @@ var SynapClient = (_class4 = class _SynapClient {
4737
5268
  }))
4738
5269
  );
4739
5270
  const entry = this.#shortTerm.get(conversationId);
4740
- const total = Math.max(Number(_nullishCoalesce(r["total_message_count"], () => ( 0))) || 0, Number(_nullishCoalesce(_optionalChain([entry, 'optionalAccess', _81 => _81.serverMessageCount]), () => ( 0))) || 0);
5271
+ const total = Math.max(Number(_nullishCoalesce(r["total_message_count"], () => ( 0))) || 0, Number(_nullishCoalesce(_optionalChain([entry, 'optionalAccess', _101 => _101.serverMessageCount]), () => ( 0))) || 0);
4741
5272
  this.#maybeBackfillTurns(conversationId, total);
4742
5273
  if (!r["context_block"]) return response;
4743
5274
  const turns = store.turns(conversationId);
4744
5275
  let q = query;
4745
5276
  if (!q) {
4746
5277
  const latest = [...recent].reverse().find((m) => m["role"] === "user");
4747
- 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]), () => ( ""));
5278
+ q = latest ? String(_nullishCoalesce(latest["content"], () => ( ""))) : _nullishCoalesce(_optionalChain([[...turns], 'access', _102 => _102.reverse, 'call', _103 => _103(), 'access', _104 => _104.find, 'call', _105 => _105((t) => t.role === "user"), 'optionalAccess', _106 => _106.content]), () => ( ""));
4748
5279
  }
4749
5280
  if (!q) return response;
4750
5281
  const exclude = /* @__PURE__ */ new Set();
@@ -4778,7 +5309,7 @@ var SynapClient = (_class4 = class _SynapClient {
4778
5309
  toolResultText(result, _nullishCoalesce(options.tool_name, () => ( options.toolName))),
4779
5310
  _nullishCoalesce(options.timestamp, () => ( (/* @__PURE__ */ new Date()).toISOString()))
4780
5311
  );
4781
- } catch (e22) {
5312
+ } catch (e23) {
4782
5313
  }
4783
5314
  }
4784
5315
  static __initStatic() {this.BACKFILL_COOLDOWN_MS = 6e4}
@@ -4888,18 +5419,19 @@ function pick3(o2, snake, camel) {
4888
5419
  function resolveBaseUrl(options) {
4889
5420
  const explicit = _nullishCoalesce(options.baseUrl, () => ( options.api_base_url));
4890
5421
  if (explicit !== void 0) return explicit;
4891
- const fromEnv = _optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_BASE_URL"), 'optionalAccess', _87 => _87.trim, 'call', _88 => _88()]);
5422
+ const fromEnv = _optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_BASE_URL"), 'optionalAccess', _107 => _107.trim, 'call', _108 => _108()]);
4892
5423
  return fromEnv !== void 0 && fromEnv !== "" ? fromEnv : void 0;
4893
5424
  }
4894
- function resolveCredentials(options) {
5425
+ function resolveCredentials(options, localMode) {
4895
5426
  const apiKey = options.apiKey || _chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_API_KEY");
4896
- if (!apiKey) {
5427
+ if (!apiKey && !localMode) {
4897
5428
  throw new (0, _chunk7IZHVYO2cjs.AuthenticationError)(
4898
5429
  "No Synap API key found. Set SYNAP_API_KEY in your environment, or pass apiKey to the SynapClient constructor."
4899
5430
  );
4900
5431
  }
4901
5432
  return {
4902
- apiKey,
5433
+ // In local mode the credential is the optional token, '' when there is none.
5434
+ apiKey: apiKey || localToken(),
4903
5435
  clientId: _nullishCoalesce(_nullishCoalesce(options.clientId, () => ( _chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_CLIENT_ID"))), () => ( "")),
4904
5436
  instanceId: _nullishCoalesce(_nullishCoalesce(options.instanceId, () => ( _chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_INSTANCE_ID"))), () => ( ""))
4905
5437
  };
@@ -4965,5 +5497,8 @@ function resolveCredentials(options) {
4965
5497
 
4966
5498
 
4967
5499
 
4968
- 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.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.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.tokenize = _chunkBYUGILQIcjs.tokenize; exports.wireRankScore = wireRankScore;
5500
+
5501
+
5502
+
5503
+ 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;
4969
5504
  //# sourceMappingURL=index.cjs.map