@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.js 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 = class {
272
273
  options.keepAlive?.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 = 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 options.mapError?.(response.status, error) ?? error;
440
452
  }
441
453
  if (response.status === 204) return void 0;
442
454
  const text = await response.text();
@@ -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 InvalidInputError(message, opts);
551
568
  case 401:
552
569
  case 403:
@@ -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 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 = init.media_type ?? init.mediaType ?? defaultMediaType(filename, 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 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 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 {
1279
+ pathname = String(p.url).split(/[?#]/)[0] ?? "";
1280
+ }
1281
+ return lastSegment(pathname) || "file";
1282
+ }
1283
+ const named = p.data?.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 MEDIA_TYPES[ext] ?? null;
1316
+ }
1317
+ function defaultMediaType(filename, data) {
1318
+ const guessed = guessMediaType(filename);
1319
+ if (guessed !== null) return guessed;
1320
+ const blobType = data?.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 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 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 value.constructor?.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 import("fs/promises");
1359
+ try {
1360
+ bytes = new Uint8Array(await readFile(part.path));
1361
+ } catch (error) {
1362
+ throw new InvalidInputError(
1363
+ `Could not read FilePart path '${part.path}': ${error?.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 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 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 {
1400
+ throw new InvalidInputError(`Could not fetch FilePart url '${url}': not a valid URL`);
1401
+ }
1402
+ if (scheme !== "http:" && scheme !== "https:") {
1403
+ throw new 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 InvalidInputError(
1413
+ `Fetching FilePart url '${url}' returned HTTP ${response.status}`
1414
+ );
1415
+ }
1416
+ const declared = Number(response.headers.get("content-length") ?? "");
1417
+ if (Number.isFinite(declared) && declared > MAX_FILE_BYTES) {
1418
+ throw new 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 InvalidInputError) throw error;
1426
+ if (controller.signal.aborted) {
1427
+ throw new 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 InvalidInputError(
1433
+ `Could not fetch FilePart url '${url}': ${error?.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 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(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 InvalidInputError("document is required");
1522
+ function createFields(options, defaultType) {
1220
1523
  const o2 = options;
1221
- const documentType = either(o2, "document_type", "documentType") ?? DEFAULT_DOCUMENT_TYPE;
1524
+ const documentType = either(o2, "document_type", "documentType") ?? defaultType;
1222
1525
  const mode = options.mode ?? DEFAULT_INGEST_MODE;
1223
- if (!DOCUMENT_TYPES.includes(documentType)) {
1526
+ if (documentType !== null && !DOCUMENT_TYPES.includes(documentType)) {
1224
1527
  throw new 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 = either(o2, "user_id", "userId") ?? null;
1537
+ const customerId = either(o2, "customer_id", "customerId") ?? null;
1538
+ const fields = {
1235
1539
  document_type: documentType,
1236
1540
  document_id: 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: either(o2, "user_id", "userId") ?? null,
1241
- customer_id: 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: options.scope ?? null,
1549
+ scope: normaliseCreateScope(options.scope, userId, customerId),
1246
1550
  mode,
1247
1551
  metadata: 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 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 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 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 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: either(o2, "user_id", "userId") ?? null,
1272
1623
  customer_id: either(o2, "customer_id", "customerId") ?? null,
1273
1624
  scope: 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 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(o2["customer_id"] ?? o2["customerId"], "memories.create");
1283
- return transport.request("memories_create", { body: buildCreateBody(options) });
1641
+ const customerId = 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 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 = 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) {
@@ -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 InvalidInputError("content is required");
1499
1898
  }
1500
1899
  if (!userId) throw new 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 (n2?.kind === "parts") {
1906
+ throw new 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 {}.
@@ -1644,6 +2055,24 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1644
2055
  inFlight: 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 (normaliseContent(options.content, field)?.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 (n2?.kind !== "parts") {
2069
+ const body = buildRecordMessageBody(options, void 0, field);
2070
+ return { body, mirror: String(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 : v.conversation_id ?? v.conversationId;
1649
2078
  if (!id) throw new InvalidInputError("conversation_id is required");
@@ -1656,7 +2085,9 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1656
2085
  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(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(body["role"] ?? "user"),
1671
- content: String(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(body["role"] ?? "user"),
1701
- content: String(body["content"] ?? ""),
2136
+ content: mirrors.get(body) ?? String(body["content"] ?? ""),
1702
2137
  timestamp: body["timestamp"],
1703
2138
  ...confirmation(row, conversationId)
1704
2139
  });
@@ -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() {
@@ -2082,8 +2518,15 @@ function jsonOrText(value) {
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 = (imageFirst ? agentModelOrToolResult : fetchOrAgentModel) ?? (() => ({}));
2526
+ const onToolResult = imageFirst ? onToolResultOrCheck : agentModelOrToolResult;
2527
+ const checkCustomerId3 = (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;
@@ -2133,6 +2576,25 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2133
2576
  } catch {
2134
2577
  }
2135
2578
  }
2579
+ let tail = Promise.resolve();
2580
+ let queued = 0;
2581
+ function inOrder(prepared, send, sync) {
2582
+ if (prepared === null && queued === 0) {
2583
+ send(sync);
2584
+ return Promise.resolve();
2585
+ }
2586
+ prepared?.catch(() => {
2587
+ });
2588
+ queued += 1;
2589
+ const run = tail.then(async () => {
2590
+ send(prepared === null ? sync : await prepared);
2591
+ });
2592
+ const done = () => {
2593
+ queued -= 1;
2594
+ };
2595
+ tail = run.then(done, done);
2596
+ return run;
2597
+ }
2136
2598
  const namespace = {
2137
2599
  async listen(options = {}) {
2138
2600
  if (client !== null) {
@@ -2142,7 +2604,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2142
2604
  onListen?.();
2143
2605
  } catch {
2144
2606
  }
2145
- const { GrpcStreamClient } = await import("./stream-client-7YONF2GD.js");
2607
+ const { GrpcStreamClient } = await import("./stream-client-JKFBVZPN.js");
2146
2608
  const onContext = options.on_context ?? options.onContext;
2147
2609
  const onDisconnect = options.on_disconnect ?? options.onDisconnect;
2148
2610
  const onReconnect = options.on_reconnect ?? options.onReconnect;
@@ -2206,10 +2668,12 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2206
2668
  }
2207
2669
  },
2208
2670
  async send_message(options) {
2209
- await checkCustomerId3(
2210
- options.customer_id ?? options.customerId,
2211
- "instance.send_message"
2212
- );
2671
+ if (hasCustomerIdCheck) {
2672
+ await checkCustomerId3(
2673
+ options.customer_id ?? options.customerId,
2674
+ "instance.send_message"
2675
+ );
2676
+ }
2213
2677
  if (client === null) throw new ListeningNotActiveError("Listening is not active");
2214
2678
  const eventType = 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 InvalidInputError("content is required");
2222
2686
  }
2223
- const conversationId = options.conversation_id ?? options.conversationId ?? "";
2224
- ensureSession(
2225
- conversationId,
2226
- options.user_id ?? options.userId ?? "",
2227
- options.customer_id ?? options.customerId ?? ""
2228
- );
2229
- if (eventType === "user_message" || eventType === "assistant_message") {
2230
- onTurn?.({
2687
+ const parts = normaliseContent(options.content, "content");
2688
+ const emit = ({ content, metadata }) => {
2689
+ if (client === null) throw new ListeningNotActiveError("Listening is not active");
2690
+ const conversationId = options.conversation_id ?? options.conversationId ?? "";
2691
+ ensureSession(
2231
2692
  conversationId,
2693
+ options.user_id ?? options.userId ?? "",
2694
+ options.customer_id ?? options.customerId ?? ""
2695
+ );
2696
+ if (eventType === "user_message" || eventType === "assistant_message") {
2697
+ onTurn?.({
2698
+ conversationId,
2699
+ role: options.role ?? "user",
2700
+ content
2701
+ });
2702
+ }
2703
+ client.sendConversationEvent({
2704
+ event_type: eventType,
2705
+ content,
2232
2706
  role: options.role ?? "user",
2233
- content: options.content
2707
+ conversation_id: options.conversation_id ?? options.conversationId ?? "",
2708
+ user_id: options.user_id ?? options.userId ?? "",
2709
+ customer_id: options.customer_id ?? options.customerId ?? "",
2710
+ session_id: options.session_id ?? options.sessionId ?? openSessions.get(conversationId) ?? "",
2711
+ metadata: withAgentModel(metadata, agentModelOf(options), agentModel(), true) ?? {},
2712
+ timestamp_ms: Date.now(),
2713
+ tool_name: options.tool_name ?? options.toolName ?? "",
2714
+ // Python serialises tool_args with json.dumps into tool_args_json.
2715
+ tool_args_json: (() => {
2716
+ const a = options.tool_args ?? options.toolArgs;
2717
+ return a === void 0 ? "" : jsonOrText(a);
2718
+ })(),
2719
+ tool_result_json: toolResultJson(options.tool_result ?? options.toolResult),
2720
+ tool_call_id: options.tool_call_id ?? options.toolCallId ?? "",
2721
+ search_queries: options.search_queries ?? options.searchQueries ?? [],
2722
+ context_types: options.context_types ?? options.contextTypes ?? [],
2723
+ ...(() => {
2724
+ const sp = options.scope_path ?? options.scopePath;
2725
+ return sp && Object.keys(sp).length > 0 ? { scope: sp } : {};
2726
+ })()
2234
2727
  });
2728
+ };
2729
+ if (parts?.kind !== "parts") {
2730
+ const content = parts?.kind === "text" ? parts.text : options.content;
2731
+ return inOrder(null, emit, { content, metadata: options.metadata ?? {} });
2235
2732
  }
2236
- client.sendConversationEvent({
2237
- event_type: eventType,
2238
- content: options.content,
2239
- role: options.role ?? "user",
2240
- conversation_id: options.conversation_id ?? options.conversationId ?? "",
2241
- user_id: options.user_id ?? options.userId ?? "",
2242
- customer_id: options.customer_id ?? options.customerId ?? "",
2243
- session_id: options.session_id ?? options.sessionId ?? openSessions.get(conversationId) ?? "",
2244
- metadata: withAgentModel(options.metadata, agentModelOf(options), agentModel(), true) ?? {},
2245
- timestamp_ms: Date.now(),
2246
- tool_name: options.tool_name ?? options.toolName ?? "",
2247
- // Python serialises tool_args with json.dumps into tool_args_json.
2248
- tool_args_json: (() => {
2249
- const a = options.tool_args ?? options.toolArgs;
2250
- return a === void 0 ? "" : jsonOrText(a);
2251
- })(),
2252
- tool_result_json: toolResultJson(options.tool_result ?? options.toolResult),
2253
- tool_call_id: options.tool_call_id ?? options.toolCallId ?? "",
2254
- search_queries: options.search_queries ?? options.searchQueries ?? [],
2255
- context_types: 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 = 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 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
+ ...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({
@@ -2303,24 +2789,27 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2303
2789
  options.user_id ?? options.userId ?? "",
2304
2790
  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: options.conversation_id ?? options.conversationId ?? "",
2318
- user_id: options.user_id ?? options.userId ?? "",
2319
- customer_id: options.customer_id ?? options.customerId ?? "",
2320
- session_id: 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 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: options.conversation_id ?? options.conversationId ?? "",
2806
+ user_id: options.user_id ?? options.userId ?? "",
2807
+ customer_id: options.customer_id ?? options.customerId ?? "",
2808
+ session_id: 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();
@@ -4287,6 +4776,8 @@ var SynapClient = 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)
@@ -4939,6 +5430,7 @@ export {
4939
5430
  ListeningNotActiveError,
4940
5431
  MEMORY_TYPES,
4941
5432
  NetworkTimeoutError,
5433
+ OBJECTIVES,
4942
5434
  PermanentError,
4943
5435
  RESPONSE_SHAPES,
4944
5436
  RateLimitError,
@@ -4954,6 +5446,7 @@ export {
4954
5446
  TranscriptConflictError,
4955
5447
  TransientError,
4956
5448
  applyResponseShape,
5449
+ filePart,
4957
5450
  flattenContextItems,
4958
5451
  formatForPrompt,
4959
5452
  isOutcomeUnknown,
@@ -4963,6 +5456,7 @@ export {
4963
5456
  resolvePath,
4964
5457
  shouldRetry,
4965
5458
  stem,
5459
+ textPart,
4966
5460
  tokenize,
4967
5461
  wireRankScore
4968
5462
  };