@maximem/synap-js-sdk 0.6.5 → 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.
package/dist/index.cjs CHANGED
@@ -49,6 +49,7 @@ var ENDPOINTS = {
49
49
  memories_create: { method: "POST", path: "/api/v1/memories/create", idempotent: false },
50
50
  memories_batch: { method: "POST", path: "/api/v1/memories/batch", idempotent: false },
51
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 },
52
53
  memories_status: { method: "GET", path: "/api/v1/memories/status/{ingestion_id}", idempotent: true },
53
54
  memories_get: { method: "GET", path: "/api/v1/memories/{memory_id}", idempotent: true },
54
55
  memories_update: { method: "PATCH", path: "/api/v1/memories/{memory_id}", idempotent: false },
@@ -272,6 +273,16 @@ var HttpTransport = (_class2 = class {
272
273
  _nullishCoalesce(_optionalChain([options, 'access', _7 => _7.keepAlive, 'optionalAccess', _8 => _8.heartbeatIntervalMs]), () => ( HEARTBEAT_INTERVAL_MS))
273
274
  );
274
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
+ }
275
286
  /** Start keeping the connection warm. Opt-in: it is pointless in serverless. */
276
287
  startHeartbeat() {
277
288
  if (!this.closed) this.heartbeat.start();
@@ -436,7 +447,8 @@ var HttpTransport = (_class2 = class {
436
447
  signal.dispose();
437
448
  }
438
449
  if (!response.ok) {
439
- 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));
440
452
  }
441
453
  if (response.status === 204) return void 0;
442
454
  const text = await response.text();
@@ -507,18 +519,18 @@ function isConnectionRefusal(error) {
507
519
  }
508
520
  function toTransportError(error, correlationId) {
509
521
  if (error instanceof _chunk7IZHVYO2cjs.SynapError) return error;
510
- const name = _optionalChain([error, 'optionalAccess', _10 => _10.name]);
522
+ const name = _optionalChain([error, 'optionalAccess', _12 => _12.name]);
511
523
  if (name === "AbortError" || name === "TimeoutError") {
512
524
  return new (0, _chunk7IZHVYO2cjs.NetworkTimeoutError)("Request timed out", { correlationId, cause: error });
513
525
  }
514
526
  if (isConnectionRefusal(error)) {
515
527
  return new (0, _chunk7IZHVYO2cjs.NetworkTimeoutError)(
516
- `Connection failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _11 => _11.message]), () => ( String(error)))}`,
528
+ `Connection failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _13 => _13.message]), () => ( String(error)))}`,
517
529
  { correlationId, cause: error }
518
530
  );
519
531
  }
520
532
  return new (0, _chunk7IZHVYO2cjs.ServiceUnavailableError)(
521
- `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)))}`,
522
534
  { correlationId, cause: error }
523
535
  );
524
536
  }
@@ -547,6 +559,11 @@ async function toHttpError(response, correlationId) {
547
559
  switch (response.status) {
548
560
  case 400:
549
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:
550
567
  return new (0, _chunk7IZHVYO2cjs.InvalidInputError)(message, opts);
551
568
  case 401:
552
569
  case 403:
@@ -566,8 +583,8 @@ async function toHttpError(response, correlationId) {
566
583
  });
567
584
  }
568
585
  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]])));
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]])));
571
588
  const msg = pick4("message");
572
589
  const attempts = Number(pick4("attempts"));
573
590
  return new (0, _chunk7IZHVYO2cjs.InstanceBuildFailedError)(
@@ -580,8 +597,8 @@ async function toHttpError(response, correlationId) {
580
597
  }
581
598
  );
582
599
  }
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]])));
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]])));
585
602
  const rawWait = _nullishCoalesce(pick4("retry_after_seconds"), () => ( response.headers.get("retry-after")));
586
603
  const wait = rawWait !== null && rawWait !== void 0 && String(rawWait).trim() !== "" ? Number(rawWait) : NaN;
587
604
  const msg = pick4("message");
@@ -629,11 +646,11 @@ function stringOrNull(v) {
629
646
  }
630
647
  function withTimeout(ms, external) {
631
648
  const controller = new AbortController();
632
- const onExternalAbort = () => controller.abort(_optionalChain([external, 'optionalAccess', _19 => _19.reason]));
649
+ const onExternalAbort = () => controller.abort(_optionalChain([external, 'optionalAccess', _21 => _21.reason]));
633
650
  const timer = setTimeout(() => {
634
651
  controller.abort(new (0, _chunk7IZHVYO2cjs.NetworkTimeoutError)(`Timed out after ${ms}ms`));
635
652
  }, ms);
636
- _optionalChain([timer, 'access', _20 => _20.unref, 'optionalCall', _21 => _21()]);
653
+ _optionalChain([timer, 'access', _22 => _22.unref, 'optionalCall', _23 => _23()]);
637
654
  if (external) {
638
655
  if (external.aborted) onExternalAbort();
639
656
  else external.addEventListener("abort", onExternalAbort, { once: true });
@@ -642,7 +659,7 @@ function withTimeout(ms, external) {
642
659
  signal: controller.signal,
643
660
  dispose() {
644
661
  clearTimeout(timer);
645
- _optionalChain([external, 'optionalAccess', _22 => _22.removeEventListener, 'call', _23 => _23("abort", onExternalAbort)]);
662
+ _optionalChain([external, 'optionalAccess', _24 => _24.removeEventListener, 'call', _25 => _25("abort", onExternalAbort)]);
646
663
  }
647
664
  };
648
665
  }
@@ -650,14 +667,14 @@ function sleep(ms, signal) {
650
667
  if (ms <= 0) return Promise.resolve();
651
668
  return new Promise((resolve, reject) => {
652
669
  const timer = setTimeout(() => {
653
- _optionalChain([signal, 'optionalAccess', _24 => _24.removeEventListener, 'call', _25 => _25("abort", onAbort)]);
670
+ _optionalChain([signal, 'optionalAccess', _26 => _26.removeEventListener, 'call', _27 => _27("abort", onAbort)]);
654
671
  resolve();
655
672
  }, ms);
656
673
  function onAbort() {
657
674
  clearTimeout(timer);
658
- reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _26 => _26.reason]), () => ( new Error("Aborted"))));
675
+ reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _28 => _28.reason]), () => ( new Error("Aborted"))));
659
676
  }
660
- _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 })]);
661
678
  });
662
679
  }
663
680
 
@@ -911,7 +928,7 @@ function validateSearchQuery(searchQuery) {
911
928
  }
912
929
  async function fetchContext(transport, scope, options = {}, hooks = {}) {
913
930
  const startedAt = Date.now();
914
- await _optionalChain([transport, 'access', _29 => _29.ready, 'optionalCall', _30 => _30()]);
931
+ await _optionalChain([transport, 'access', _31 => _31.ready, 'optionalCall', _32 => _32()]);
915
932
  await transport.checkCustomerId(
916
933
  opt(options, "customer_id", "customerId"),
917
934
  `${scope}.context.fetch`
@@ -927,20 +944,20 @@ async function fetchContext(transport, scope, options = {}, hooks = {}) {
927
944
  if (answer !== null) return applyResponseShape(answer, responseShape);
928
945
  }
929
946
  const finish = (response2) => {
930
- _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)]);
931
948
  return response2;
932
949
  };
933
950
  const conversationId = opt(options, "conversation_id", "conversationId");
934
- 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;
935
952
  const network = async () => {
936
953
  const { endpoint, body } = buildFetchRequest(
937
954
  scope,
938
955
  skipServerSt ? { ...options, include_conversation_context: false } : options
939
956
  );
940
957
  const result = await transport.request(endpoint, { body });
941
- return applyResponseShape(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _35 => _35["context"]]), () => ( {})), responseShape);
958
+ return applyResponseShape(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _37 => _37["context"]]), () => ( {})), responseShape);
942
959
  };
943
- 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));
944
961
  if (anticipated !== null && anticipated.borderline) {
945
962
  const pending = network();
946
963
  pending.catch(() => void 0);
@@ -951,17 +968,17 @@ async function fetchContext(transport, scope, options = {}, hooks = {}) {
951
968
  const won = await Promise.race([pending.then((r) => r, () => null), late]);
952
969
  if (timer !== void 0) clearTimeout(timer);
953
970
  if (won !== null) {
954
- _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)]);
955
972
  return finish(won);
956
973
  }
957
974
  }
958
975
  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)]);
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)]);
961
978
  return finish(applyResponseShape(anticipated.response, responseShape));
962
979
  }
963
980
  const response = await network();
964
- _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)]);
965
982
  return finish(response);
966
983
  }
967
984
 
@@ -1192,6 +1209,293 @@ function flattenContextItems(context) {
1192
1209
  return items;
1193
1210
  }
1194
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
+
1195
1499
  // src/memories/interface.ts
1196
1500
  var DOCUMENT_TYPES = [
1197
1501
  "ai-chat-conversation",
@@ -1215,12 +1519,11 @@ function isoOrNull(v) {
1215
1519
  if (v === void 0 || v === null) return null;
1216
1520
  return v instanceof Date ? v.toISOString() : v;
1217
1521
  }
1218
- function buildCreateBody(options) {
1219
- if (!options.document) throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("document is required");
1522
+ function createFields(options, defaultType) {
1220
1523
  const o2 = options;
1221
- const documentType = _nullishCoalesce(either(o2, "document_type", "documentType"), () => ( DEFAULT_DOCUMENT_TYPE));
1524
+ const documentType = _nullishCoalesce(either(o2, "document_type", "documentType"), () => ( defaultType));
1222
1525
  const mode = _nullishCoalesce(options.mode, () => ( DEFAULT_INGEST_MODE));
1223
- if (!DOCUMENT_TYPES.includes(documentType)) {
1526
+ if (documentType !== null && !DOCUMENT_TYPES.includes(documentType)) {
1224
1527
  throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1225
1528
  `Invalid document_type '${documentType}'. Expected one of: ${DOCUMENT_TYPES.join(", ")}`
1226
1529
  );
@@ -1230,22 +1533,70 @@ function buildCreateBody(options) {
1230
1533
  `Invalid mode '${mode}'. Expected one of: ${INGEST_MODES.join(", ")}`
1231
1534
  );
1232
1535
  }
1233
- return {
1234
- 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 = {
1235
1539
  document_type: documentType,
1236
1540
  document_id: _nullishCoalesce(either(o2, "document_id", "documentId"), () => ( null)),
1237
1541
  document_created_at: isoOrNull(
1238
1542
  either(o2, "document_created_at", "documentCreatedAt")
1239
1543
  ),
1240
- user_id: _nullishCoalesce(either(o2, "user_id", "userId"), () => ( null)),
1241
- customer_id: _nullishCoalesce(either(o2, "customer_id", "customerId"), () => ( null)),
1544
+ user_id: userId,
1545
+ customer_id: customerId,
1242
1546
  // null, never `{}`. An empty path is not absence: the server treats one as
1243
1547
  // an error, because a caller asking to be narrowed and being ignored gets
1244
1548
  // widened instead.
1245
- scope: _nullishCoalesce(options.scope, () => ( null)),
1549
+ scope: normaliseCreateScope(options.scope, userId, customerId),
1246
1550
  mode,
1247
1551
  metadata: _nullishCoalesce(options.metadata, () => ( {}))
1248
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) };
1249
1600
  }
1250
1601
  var FORGET_MODES = ["preview", "direct"];
1251
1602
  var FORGET_DESCRIPTION_MIN = 3;
@@ -1266,21 +1617,63 @@ function buildForgetBody(options) {
1266
1617
  );
1267
1618
  }
1268
1619
  const o2 = options;
1269
- return {
1620
+ const body = {
1270
1621
  description,
1271
1622
  user_id: _nullishCoalesce(either(o2, "user_id", "userId"), () => ( null)),
1272
1623
  customer_id: _nullishCoalesce(either(o2, "customer_id", "customerId"), () => ( null)),
1273
1624
  scope: _nullishCoalesce(options.scope, () => ( null)),
1274
1625
  mode
1275
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;
1276
1635
  }
1277
1636
  var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "partial_success", "error", "cancelled"]);
1278
1637
  function createMemoriesInterface(transport, onForgotten) {
1279
1638
  return {
1280
1639
  async create(options) {
1281
1640
  const o2 = options;
1282
- await transport.checkCustomerId(_nullishCoalesce(o2["customer_id"], () => ( o2["customerId"])), "memories.create");
1283
- 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
+ });
1284
1677
  },
1285
1678
  async batch_create(options) {
1286
1679
  const docs = options.documents;
@@ -1289,7 +1682,13 @@ function createMemoriesInterface(transport, onForgotten) {
1289
1682
  }
1290
1683
  const failFast = _nullishCoalesce(_nullishCoalesce(options.fail_fast, () => ( options.failFast)), () => ( false));
1291
1684
  return transport.request("memories_batch", {
1292
- 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
+ }
1293
1692
  });
1294
1693
  },
1295
1694
  async create_from_file(options) {
@@ -1375,14 +1774,14 @@ function createMemoriesInterface(transport, onForgotten) {
1375
1774
  await transport.checkCustomerId(_nullishCoalesce(o2["customer_id"], () => ( o2["customerId"])), "memories.forget");
1376
1775
  const body = buildForgetBody(options);
1377
1776
  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";
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";
1379
1778
  if (removed && onForgotten) {
1380
1779
  try {
1381
1780
  onForgotten({
1382
1781
  userId: _nullishCoalesce(body["user_id"], () => ( null)),
1383
1782
  customerId: _nullishCoalesce(body["customer_id"], () => ( null))
1384
1783
  });
1385
- } catch (e5) {
1784
+ } catch (e7) {
1386
1785
  }
1387
1786
  }
1388
1787
  return result;
@@ -1415,14 +1814,14 @@ function sleep2(ms, signal) {
1415
1814
  if (ms <= 0) return Promise.resolve();
1416
1815
  return new Promise((resolve, reject) => {
1417
1816
  const timer = setTimeout(() => {
1418
- _optionalChain([signal, 'optionalAccess', _50 => _50.removeEventListener, 'call', _51 => _51("abort", onAbort)]);
1817
+ _optionalChain([signal, 'optionalAccess', _59 => _59.removeEventListener, 'call', _60 => _60("abort", onAbort)]);
1419
1818
  resolve();
1420
1819
  }, ms);
1421
1820
  function onAbort() {
1422
1821
  clearTimeout(timer);
1423
- reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _52 => _52.reason]), () => ( new Error("Aborted"))));
1822
+ reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _61 => _61.reason]), () => ( new Error("Aborted"))));
1424
1823
  }
1425
- _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 })]);
1426
1825
  });
1427
1826
  }
1428
1827
 
@@ -1483,7 +1882,7 @@ function iso(v) {
1483
1882
  if (v === void 0) return void 0;
1484
1883
  return v instanceof Date ? v.toISOString() : v;
1485
1884
  }
1486
- function buildRecordMessageBody(options) {
1885
+ function buildRecordMessageBody(options, resolvedContent, field = "content") {
1487
1886
  const o2 = options;
1488
1887
  const conversationId = either2(o2, "conversation_id", "conversationId");
1489
1888
  const userId = either2(o2, "user_id", "userId");
@@ -1498,10 +1897,22 @@ function buildRecordMessageBody(options) {
1498
1897
  throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("content is required");
1499
1898
  }
1500
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
+ }
1501
1912
  const body = {
1502
1913
  conversation_id: conversationId,
1503
1914
  role: options.role,
1504
- content: options.content,
1915
+ content,
1505
1916
  user_id: userId,
1506
1917
  customer_id: customerId,
1507
1918
  // Python always sends this, defaulting to {}.
@@ -1602,7 +2013,7 @@ function storedBatchRows(bodies, result) {
1602
2013
  const r = _nullishCoalesce(result, () => ( {}));
1603
2014
  const results = Array.isArray(r["results"]) ? r["results"] : [];
1604
2015
  const errors = Array.isArray(r["errors"]) ? r["errors"] : [];
1605
- 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"]])));
1606
2017
  const stored = bodies.filter((_, index) => !failed.has(index));
1607
2018
  if (stored.length !== results.length) return [];
1608
2019
  const pairs = [];
@@ -1644,6 +2055,24 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1644
2055
  inFlight: _nullishCoalesce(writesInFlight.get(conversationId), () => ( 0))
1645
2056
  };
1646
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
+ };
1647
2076
  const convId = (v) => {
1648
2077
  const id = typeof v === "string" ? v : _nullishCoalesce(v.conversation_id, () => ( v.conversationId));
1649
2078
  if (!id) throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("conversation_id is required");
@@ -1656,7 +2085,9 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1656
2085
  _nullishCoalesce(options["customer_id"], () => ( options["customerId"])),
1657
2086
  "conversation.record_message"
1658
2087
  );
1659
- const body = withTurnModel(buildRecordMessageBody(options), options);
2088
+ const prepared = await prepareMessage(options);
2089
+ const body = withTurnModel(prepared.body, options);
2090
+ const mirror = prepared.mirror;
1660
2091
  const conversationId = String(_nullishCoalesce(body["conversation_id"], () => ( "")));
1661
2092
  writeStarted(conversationId);
1662
2093
  let result;
@@ -1668,7 +2099,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1668
2099
  onTurn({
1669
2100
  conversationId,
1670
2101
  role: String(_nullishCoalesce(body["role"], () => ( "user"))),
1671
- content: String(_nullishCoalesce(body["content"], () => ( ""))),
2102
+ content: mirror,
1672
2103
  timestamp: body["timestamp"],
1673
2104
  ...confirmation(result, conversationId)
1674
2105
  });
@@ -1689,7 +2120,11 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1689
2120
  "conversation.record_messages_batch"
1690
2121
  );
1691
2122
  }
1692
- 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]));
1693
2128
  const result = await transport.request("conversations_messages_batch", {
1694
2129
  body: { messages: bodies }
1695
2130
  });
@@ -1698,7 +2133,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1698
2133
  onTurn({
1699
2134
  conversationId,
1700
2135
  role: String(_nullishCoalesce(body["role"], () => ( "user"))),
1701
- content: String(_nullishCoalesce(body["content"], () => ( ""))),
2136
+ content: _nullishCoalesce(mirrors.get(body), () => ( String(_nullishCoalesce(body["content"], () => ( ""))))),
1702
2137
  timestamp: body["timestamp"],
1703
2138
  ...confirmation(row, conversationId)
1704
2139
  });
@@ -1721,7 +2156,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1721
2156
  const raw = await transport.request("conversations_ingest", { body });
1722
2157
  const result = {
1723
2158
  ...raw,
1724
- 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) : []
1725
2160
  };
1726
2161
  onWrite({
1727
2162
  userId: body["user_id"],
@@ -1755,7 +2190,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1755
2190
  if (!search) return response2;
1756
2191
  try {
1757
2192
  return await localShortTerm.historyExcerpts(id, response2, options.query);
1758
- } catch (e6) {
2193
+ } catch (e8) {
1759
2194
  return response2;
1760
2195
  }
1761
2196
  };
@@ -1765,8 +2200,8 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1765
2200
  pathParams: { conversation_id: id },
1766
2201
  query: { style }
1767
2202
  });
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)]);
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)]);
1770
2205
  return withHistory(response);
1771
2206
  },
1772
2207
  async compact(options) {
@@ -1931,7 +2366,7 @@ function createDataInterface(transport, onDeleted) {
1931
2366
  customerId: _nullishCoalesce(body["customer_id"], () => ( null)),
1932
2367
  conversationId: _nullishCoalesce(body["conversation_id"], () => ( null))
1933
2368
  });
1934
- } catch (e7) {
2369
+ } catch (e9) {
1935
2370
  }
1936
2371
  }
1937
2372
  return final;
@@ -2027,6 +2462,7 @@ function createCacheNamespace(cache) {
2027
2462
  }
2028
2463
 
2029
2464
  // src/instance/interface.ts
2465
+ var CONTENT_PARTS_METADATA_KEY = "synap_content_parts";
2030
2466
  var DEFAULT_GRPC_HOST = "synap-cloud-prod.maximem.ai";
2031
2467
  var DEFAULT_GRPC_PORT = 443;
2032
2468
  function envPort() {
@@ -2074,16 +2510,23 @@ function jsonOrText(value) {
2074
2510
  (_k, v) => typeof v === "bigint" ? String(v) : v
2075
2511
  );
2076
2512
  return out === void 0 ? String(value) : out;
2077
- } catch (e8) {
2513
+ } catch (e10) {
2078
2514
  try {
2079
2515
  return String(value);
2080
- } catch (e9) {
2516
+ } catch (e11) {
2081
2517
  return "";
2082
2518
  }
2083
2519
  }
2084
2520
  }
2085
- function createInstanceNamespace(credentials, cache, onTurn, agentModel = () => ({}), onToolResult, checkCustomerId3 = async () => {
2086
- }) {
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;
2087
2530
  let client = null;
2088
2531
  const openSessions = /* @__PURE__ */ new Map();
2089
2532
  let dispatchCompaction = null;
@@ -2092,8 +2535,8 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2092
2535
  let onConversationState = null;
2093
2536
  const internals = {
2094
2537
  onCompactionUpdate(conversationId, bundle) {
2095
- _optionalChain([applyCompaction, 'optionalCall', _60 => _60(bundle)]);
2096
- _optionalChain([dispatchCompaction, 'optionalCall', _61 => _61(conversationId, bundle)]);
2538
+ _optionalChain([applyCompaction, 'optionalCall', _73 => _73(bundle)]);
2539
+ _optionalChain([dispatchCompaction, 'optionalCall', _74 => _74(conversationId, bundle)]);
2097
2540
  },
2098
2541
  setCompactionApplier(apply) {
2099
2542
  applyCompaction = apply;
@@ -2105,10 +2548,10 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2105
2548
  onConversationState = handle;
2106
2549
  },
2107
2550
  sendContextUsed(event) {
2108
- _optionalChain([client, 'optionalAccess', _62 => _62.sendContextUsed, 'call', _63 => _63(event)]);
2551
+ _optionalChain([client, 'optionalAccess', _75 => _75.sendContextUsed, 'call', _76 => _76(event)]);
2109
2552
  },
2110
2553
  sendContextAssembled(event) {
2111
- _optionalChain([client, 'optionalAccess', _64 => _64.sendContextAssembled, 'call', _65 => _65(event)]);
2554
+ _optionalChain([client, 'optionalAccess', _77 => _77.sendContextAssembled, 'call', _78 => _78(event)]);
2112
2555
  },
2113
2556
  setCompactionDispatcher(dispatch) {
2114
2557
  dispatchCompaction = dispatch;
@@ -2130,8 +2573,27 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2130
2573
  ...customerId ? { customer_id: customerId } : {}
2131
2574
  });
2132
2575
  openSessions.set(conversationId, sessionId);
2133
- } catch (e10) {
2576
+ } catch (e12) {
2577
+ }
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();
2134
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;
2135
2597
  }
2136
2598
  const namespace = {
2137
2599
  async listen(options = {}) {
@@ -2139,10 +2601,10 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2139
2601
  throw new (0, _chunk7IZHVYO2cjs.ListeningAlreadyActiveError)("Listening is already active on this instance");
2140
2602
  }
2141
2603
  try {
2142
- _optionalChain([onListen, 'optionalCall', _66 => _66()]);
2143
- } catch (e11) {
2604
+ _optionalChain([onListen, 'optionalCall', _81 => _81()]);
2605
+ } catch (e13) {
2144
2606
  }
2145
- const { GrpcStreamClient } = await Promise.resolve().then(() => _interopRequireWildcard(require("./stream-client-IPHDTXQO.cjs")));
2607
+ const { GrpcStreamClient } = await Promise.resolve().then(() => _interopRequireWildcard(require("./stream-client-BY5LNLVB.cjs")));
2146
2608
  const onContext = _nullishCoalesce(options.on_context, () => ( options.onContext));
2147
2609
  const onDisconnect = _nullishCoalesce(options.on_disconnect, () => ( options.onDisconnect));
2148
2610
  const onReconnect = _nullishCoalesce(options.on_reconnect, () => ( options.onReconnect));
@@ -2157,17 +2619,17 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2157
2619
  internals.onCompactionUpdate(conversationId, bundle);
2158
2620
  },
2159
2621
  onConversationState: (conversationId, messageCount) => {
2160
- _optionalChain([onConversationState, 'optionalCall', _67 => _67(conversationId, messageCount)]);
2622
+ _optionalChain([onConversationState, 'optionalCall', _82 => _82(conversationId, messageCount)]);
2161
2623
  },
2162
2624
  onStateChange: (state) => {
2163
2625
  if (state !== "connected") openSessions.clear();
2164
2626
  if (state === "reconnecting") {
2165
2627
  reconnectAttempts += 1;
2166
- _optionalChain([onReconnect, 'optionalCall', _68 => _68(reconnectAttempts)]);
2628
+ _optionalChain([onReconnect, 'optionalCall', _83 => _83(reconnectAttempts)]);
2167
2629
  } else if (state === "disconnected") {
2168
- const stopped = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _69 => _69.lastError]), () => ( null));
2630
+ const stopped = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _84 => _84.lastError]), () => ( null));
2169
2631
  const reason = stopped === null ? "stream disconnected" : `credit_stop:${_nullishCoalesce(stopped.reason, () => ( "unknown"))}`;
2170
- _optionalChain([onDisconnect, 'optionalCall', _70 => _70(reason)]);
2632
+ _optionalChain([onDisconnect, 'optionalCall', _85 => _85(reason)]);
2171
2633
  }
2172
2634
  }
2173
2635
  });
@@ -2177,7 +2639,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2177
2639
  } catch (error) {
2178
2640
  if (error instanceof _chunk7IZHVYO2cjs.SynapError) throw error;
2179
2641
  throw new (0, _chunk7IZHVYO2cjs.SynapError)(
2180
- `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)))}`,
2181
2643
  { cause: error }
2182
2644
  );
2183
2645
  }
@@ -2202,14 +2664,16 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2202
2664
  session_id: sessionId,
2203
2665
  conversation_id: conversationId
2204
2666
  });
2205
- } catch (e12) {
2667
+ } catch (e14) {
2206
2668
  }
2207
2669
  },
2208
2670
  async send_message(options) {
2209
- await checkCustomerId3(
2210
- _nullishCoalesce(options.customer_id, () => ( options.customerId)),
2211
- "instance.send_message"
2212
- );
2671
+ if (hasCustomerIdCheck) {
2672
+ await checkCustomerId3(
2673
+ _nullishCoalesce(options.customer_id, () => ( options.customerId)),
2674
+ "instance.send_message"
2675
+ );
2676
+ }
2213
2677
  if (client === null) throw new (0, _chunk7IZHVYO2cjs.ListeningNotActiveError)("Listening is not active");
2214
2678
  const eventType = _nullishCoalesce(_nullishCoalesce(options.event_type, () => ( options.eventType)), () => ( "user_message"));
2215
2679
  if (!KNOWN_EVENT_TYPES.has(eventType)) {
@@ -2220,46 +2684,68 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2220
2684
  if (options.content === void 0 || options.content === null) {
2221
2685
  throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)("content is required");
2222
2686
  }
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({
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(
2231
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,
2232
2706
  role: _nullishCoalesce(options.role, () => ( "user")),
2233
- content: options.content
2234
- })]);
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, () => ( {})) });
2235
2732
  }
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
- });
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);
2263
2749
  },
2264
2750
  async record_tool_call(options) {
2265
2751
  await namespace.send_message({
@@ -2279,7 +2765,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2279
2765
  async record_tool_result(options) {
2280
2766
  const conversationId = _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( ""));
2281
2767
  if (conversationId) {
2282
- _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)), () => ( "")) })]);
2283
2769
  }
2284
2770
  await namespace.send_message({
2285
2771
  content: "",
@@ -2303,24 +2789,27 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2303
2789
  _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
2304
2790
  _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( ""))
2305
2791
  );
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
- });
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);
2324
2813
  },
2325
2814
  get is_listening() {
2326
2815
  return client !== null && client.isConnected;
@@ -2331,7 +2820,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2331
2820
  }
2332
2821
 
2333
2822
  // src/version.ts
2334
- var SDK_VERSION = "0.6.5";
2823
+ var SDK_VERSION = "0.6.6";
2335
2824
 
2336
2825
  // src/registry.ts
2337
2826
  var instances = /* @__PURE__ */ new Map();
@@ -2471,7 +2960,7 @@ var ShortTermStore = class {
2471
2960
  if (this.#archive !== null) {
2472
2961
  try {
2473
2962
  this.#archive.add(conversationId, role, content, stamp, { messageId: _nullishCoalesce(confirmation.messageId, () => ( null)) });
2474
- } catch (e13) {
2963
+ } catch (e15) {
2475
2964
  }
2476
2965
  }
2477
2966
  const entry = _nullishCoalesce(this.#entries.get(conversationId), () => ( this.#blank(conversationId)));
@@ -2799,7 +3288,7 @@ var TurnStore = (_class3 = class {
2799
3288
  }
2800
3289
  /** Turns the server also holds: archived tool results are local only. Python: `count`. */
2801
3290
  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;
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;
2803
3292
  }
2804
3293
  sizeBytes() {
2805
3294
  let n2 = 0;
@@ -2978,7 +3467,7 @@ function askedKinds(query) {
2978
3467
  }
2979
3468
  function asksHowItStarted(query) {
2980
3469
  const spec = _chunkBYUGILQIcjs.HISTORY_SEARCH.early_query;
2981
- if (!_optionalChain([spec, 'optionalAccess', _78 => _78.pattern])) return false;
3470
+ if (!_optionalChain([spec, 'optionalAccess', _95 => _95.pattern])) return false;
2982
3471
  return new RegExp(spec.pattern, (_nullishCoalesce(spec.flags, () => ( ""))).includes("i") ? "i" : "").test(_nullishCoalesce(query, () => ( "")));
2983
3472
  }
2984
3473
  async function searchTurns(turns, query, options = {}) {
@@ -3246,7 +3735,7 @@ function overlayLocalRecentTurns(response, store, conversationId, configured) {
3246
3735
  compacted_at: orLocal("compacted_at", entry.compactedAt),
3247
3736
  conversation_id: conversationId
3248
3737
  };
3249
- } catch (e14) {
3738
+ } catch (e16) {
3250
3739
  }
3251
3740
  }
3252
3741
 
@@ -3259,7 +3748,7 @@ function stringify(value) {
3259
3748
  if (t === "string" || t === "number" || t === "boolean") return String(value);
3260
3749
  try {
3261
3750
  return _nullishCoalesce(JSON.stringify(value), () => ( ""));
3262
- } catch (e15) {
3751
+ } catch (e17) {
3263
3752
  return String(value);
3264
3753
  }
3265
3754
  }
@@ -3557,7 +4046,7 @@ async function tryServeFromCache(cache, scope, params, maxItems) {
3557
4046
  });
3558
4047
  if (hit === null) return { response: null, hit: null };
3559
4048
  return { response: buildAnticipationResponse(hit), hit };
3560
- } catch (e16) {
4049
+ } catch (e18) {
3561
4050
  return { response: null, hit: null };
3562
4051
  }
3563
4052
  }
@@ -4177,7 +4666,7 @@ var SynapClient = (_class4 = class _SynapClient {
4177
4666
  ...customerId !== void 0 ? { customer_id: customerId } : {}
4178
4667
  });
4179
4668
  return profileContext(profile);
4180
- } catch (e17) {
4669
+ } catch (e19) {
4181
4670
  return null;
4182
4671
  }
4183
4672
  }
@@ -4217,7 +4706,7 @@ var SynapClient = (_class4 = class _SynapClient {
4217
4706
  this.#localEncoder = _nullishCoalesce(_nullishCoalesce(options.history_search_encoder, () => ( options.historySearchEncoder)), () => ( null));
4218
4707
  const modelOption = options.history_search_model !== void 0 ? options.history_search_model : options.historySearchModel;
4219
4708
  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);
4709
+ if (_optionalChain([this, 'access', _96 => _96.#localEncoder, 'optionalAccess', _97 => _97.model]) === _chunkBYUGILQIcjs.SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(this.#localEncoder);
4221
4710
  this.#turns = new TurnCounter();
4222
4711
  this.conversation = createConversationNamespace(
4223
4712
  this.#transport,
@@ -4287,6 +4776,8 @@ var SynapClient = (_class4 = class _SynapClient {
4287
4776
  ({ conversationId, role, content }) => {
4288
4777
  this.#shortTerm.appendTurn(conversationId, role, content);
4289
4778
  },
4779
+ // A FilePart given by url is read with the same fetch as everything else.
4780
+ ((url, init) => this.#transport.fetchExternal(url, init)),
4290
4781
  () => this.#agentModel,
4291
4782
  ({ conversationId, result, toolName }) => this.archive_tool_result(conversationId, result, { tool_name: toolName }),
4292
4783
  (customerId, where) => this.#transport.checkCustomerId(customerId, where)
@@ -4426,7 +4917,7 @@ var SynapClient = (_class4 = class _SynapClient {
4426
4917
  this.#registryKeys.push(resolvedInstanceId);
4427
4918
  }
4428
4919
  }
4429
- } catch (e18) {
4920
+ } catch (e20) {
4430
4921
  }
4431
4922
  }
4432
4923
  /**
@@ -4599,7 +5090,7 @@ var SynapClient = (_class4 = class _SynapClient {
4599
5090
  if (conversationState && !merged.scopes_queried.includes("conversation")) {
4600
5091
  merged.scopes_queried.unshift("conversation");
4601
5092
  }
4602
- } catch (e19) {
5093
+ } catch (e21) {
4603
5094
  }
4604
5095
  }
4605
5096
  merged.formatted_context = formatForPrompt(merged, {
@@ -4651,7 +5142,7 @@ var SynapClient = (_class4 = class _SynapClient {
4651
5142
  // not carry the caller's words.
4652
5143
  query_count: distinctQueryCount(_nullishCoalesce(options["search_query"], () => ( options["searchQuery"])))
4653
5144
  });
4654
- } catch (e20) {
5145
+ } catch (e22) {
4655
5146
  }
4656
5147
  }
4657
5148
  /**
@@ -4676,7 +5167,7 @@ var SynapClient = (_class4 = class _SynapClient {
4676
5167
  }),
4677
5168
  scope
4678
5169
  });
4679
- } catch (e21) {
5170
+ } catch (e23) {
4680
5171
  }
4681
5172
  }
4682
5173
  /**
@@ -4737,14 +5228,14 @@ var SynapClient = (_class4 = class _SynapClient {
4737
5228
  }))
4738
5229
  );
4739
5230
  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);
5231
+ const total = Math.max(Number(_nullishCoalesce(r["total_message_count"], () => ( 0))) || 0, Number(_nullishCoalesce(_optionalChain([entry, 'optionalAccess', _98 => _98.serverMessageCount]), () => ( 0))) || 0);
4741
5232
  this.#maybeBackfillTurns(conversationId, total);
4742
5233
  if (!r["context_block"]) return response;
4743
5234
  const turns = store.turns(conversationId);
4744
5235
  let q = query;
4745
5236
  if (!q) {
4746
5237
  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]), () => ( ""));
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]), () => ( ""));
4748
5239
  }
4749
5240
  if (!q) return response;
4750
5241
  const exclude = /* @__PURE__ */ new Set();
@@ -4778,7 +5269,7 @@ var SynapClient = (_class4 = class _SynapClient {
4778
5269
  toolResultText(result, _nullishCoalesce(options.tool_name, () => ( options.toolName))),
4779
5270
  _nullishCoalesce(options.timestamp, () => ( (/* @__PURE__ */ new Date()).toISOString()))
4780
5271
  );
4781
- } catch (e22) {
5272
+ } catch (e24) {
4782
5273
  }
4783
5274
  }
4784
5275
  static __initStatic() {this.BACKFILL_COOLDOWN_MS = 6e4}
@@ -4888,7 +5379,7 @@ function pick3(o2, snake, camel) {
4888
5379
  function resolveBaseUrl(options) {
4889
5380
  const explicit = _nullishCoalesce(options.baseUrl, () => ( options.api_base_url));
4890
5381
  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()]);
5382
+ const fromEnv = _optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_BASE_URL"), 'optionalAccess', _104 => _104.trim, 'call', _105 => _105()]);
4892
5383
  return fromEnv !== void 0 && fromEnv !== "" ? fromEnv : void 0;
4893
5384
  }
4894
5385
  function resolveCredentials(options) {
@@ -4965,5 +5456,8 @@ function resolveCredentials(options) {
4965
5456
 
4966
5457
 
4967
5458
 
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;
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;
4969
5463
  //# sourceMappingURL=index.cjs.map