@maximem/synap-js-sdk 0.6.5 → 0.6.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/anticipation-cache-Q7IYC3ID.cjs.map +1 -1
- package/dist/chunk-7IZHVYO2.cjs.map +1 -1
- package/dist/chunk-BYUGILQI.cjs.map +1 -1
- package/dist/{chunk-IZUIPREP.cjs → chunk-EI4AGILN.cjs} +17 -6
- package/dist/chunk-EI4AGILN.cjs.map +1 -0
- package/dist/{chunk-4HD6KU3D.js → chunk-YUCHB2YK.js} +17 -6
- package/dist/chunk-YUCHB2YK.js.map +1 -0
- package/dist/chunk-ZKOJDUN4.cjs.map +1 -1
- package/dist/env-55ULHNJZ.cjs.map +1 -1
- package/dist/grpc/index.cjs +3 -3
- package/dist/grpc/index.cjs.map +1 -1
- package/dist/grpc/index.js +2 -2
- package/dist/index.cjs +695 -160
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +163 -7
- package/dist/index.d.ts +163 -7
- package/dist/index.js +625 -90
- package/dist/index.js.map +1 -1
- package/dist/onnx-encoder-4RSL6ID4.cjs.map +1 -1
- package/dist/{stream-client-7YONF2GD.js → stream-client-Q2RR5SCS.js} +2 -2
- package/dist/stream-client-TDHTS7F4.cjs +22 -0
- package/dist/stream-client-TDHTS7F4.cjs.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-4HD6KU3D.js.map +0 -1
- package/dist/chunk-IZUIPREP.cjs.map +0 -1
- package/dist/stream-client-IPHDTXQO.cjs +0 -22
- package/dist/stream-client-IPHDTXQO.cjs.map +0 -1
- /package/dist/{stream-client-7YONF2GD.js.map → stream-client-Q2RR5SCS.js.map} +0 -0
package/dist/index.js
CHANGED
|
@@ -43,12 +43,22 @@ import {
|
|
|
43
43
|
newCorrelationId
|
|
44
44
|
} from "./chunk-DEFC7NHQ.js";
|
|
45
45
|
|
|
46
|
+
// src/local-mode.ts
|
|
47
|
+
function isLocalMode(apiKey, baseUrl) {
|
|
48
|
+
if (apiKey || getEnv("SYNAP_API_KEY")) return false;
|
|
49
|
+
return baseUrl !== void 0 && baseUrl.trim() !== "";
|
|
50
|
+
}
|
|
51
|
+
function localToken() {
|
|
52
|
+
return getEnv("SYNAP_API_TOKEN")?.trim() ?? "";
|
|
53
|
+
}
|
|
54
|
+
|
|
46
55
|
// src/transport/endpoints.ts
|
|
47
56
|
var ENDPOINTS = {
|
|
48
57
|
whoami: { method: "GET", path: "/api/v1/auth/whoami", idempotent: true },
|
|
49
58
|
memories_create: { method: "POST", path: "/api/v1/memories/create", idempotent: false },
|
|
50
59
|
memories_batch: { method: "POST", path: "/api/v1/memories/batch", idempotent: false },
|
|
51
60
|
memories_upload: { method: "POST", path: "/api/v1/memories/upload", idempotent: false },
|
|
61
|
+
memories_create_multipart: { method: "POST", path: "/api/v1/memories/create-multipart", idempotent: false },
|
|
52
62
|
memories_status: { method: "GET", path: "/api/v1/memories/status/{ingestion_id}", idempotent: true },
|
|
53
63
|
memories_get: { method: "GET", path: "/api/v1/memories/{memory_id}", idempotent: true },
|
|
54
64
|
memories_update: { method: "PATCH", path: "/api/v1/memories/{memory_id}", idempotent: false },
|
|
@@ -272,6 +282,16 @@ var HttpTransport = class {
|
|
|
272
282
|
options.keepAlive?.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS
|
|
273
283
|
);
|
|
274
284
|
}
|
|
285
|
+
/**
|
|
286
|
+
* @internal Fetch a URL that is not Synap's, with this transport's fetch.
|
|
287
|
+
*
|
|
288
|
+
* Used to read a `FilePart` given by `url`: the SDK fetches it, the server
|
|
289
|
+
* never does. Deliberately sends none of this transport's headers, because
|
|
290
|
+
* the URL belongs to somebody else and the API key must not reach them.
|
|
291
|
+
*/
|
|
292
|
+
fetchExternal(url, init = {}) {
|
|
293
|
+
return this.fetchImpl(url, init);
|
|
294
|
+
}
|
|
275
295
|
/** Start keeping the connection warm. Opt-in: it is pointless in serverless. */
|
|
276
296
|
startHeartbeat() {
|
|
277
297
|
if (!this.closed) this.heartbeat.start();
|
|
@@ -436,7 +456,8 @@ var HttpTransport = class {
|
|
|
436
456
|
signal.dispose();
|
|
437
457
|
}
|
|
438
458
|
if (!response.ok) {
|
|
439
|
-
|
|
459
|
+
const error = await toHttpError(response, correlationId);
|
|
460
|
+
throw options.mapError?.(response.status, error) ?? error;
|
|
440
461
|
}
|
|
441
462
|
if (response.status === 204) return void 0;
|
|
442
463
|
const text = await response.text();
|
|
@@ -456,7 +477,8 @@ var HttpTransport = class {
|
|
|
456
477
|
}
|
|
457
478
|
buildHeaders(correlationId, options = {}) {
|
|
458
479
|
return {
|
|
459
|
-
|
|
480
|
+
// Empty only in local mode with no SYNAP_API_TOKEN: send no header at all.
|
|
481
|
+
...this.#credentials.apiKey !== "" ? { Authorization: `Bearer ${this.#credentials.apiKey}` } : {},
|
|
460
482
|
"X-Client-ID": this.#credentials.clientId,
|
|
461
483
|
"X-Instance-ID": this.#credentials.instanceId,
|
|
462
484
|
"X-Correlation-ID": correlationId,
|
|
@@ -547,6 +569,11 @@ async function toHttpError(response, correlationId) {
|
|
|
547
569
|
switch (response.status) {
|
|
548
570
|
case 400:
|
|
549
571
|
case 422:
|
|
572
|
+
// Wrong method, too large, unsupported media type: each says what was
|
|
573
|
+
// wrong with the request, and none of them goes away on a retry.
|
|
574
|
+
case 405:
|
|
575
|
+
case 413:
|
|
576
|
+
case 415:
|
|
550
577
|
return new InvalidInputError(message, opts);
|
|
551
578
|
case 401:
|
|
552
579
|
case 403:
|
|
@@ -1192,6 +1219,293 @@ function flattenContextItems(context) {
|
|
|
1192
1219
|
return items;
|
|
1193
1220
|
}
|
|
1194
1221
|
|
|
1222
|
+
// src/memories/parts.ts
|
|
1223
|
+
var OBJECTIVES = [
|
|
1224
|
+
"conversation",
|
|
1225
|
+
"bootstrap",
|
|
1226
|
+
"knowledge-base",
|
|
1227
|
+
"record",
|
|
1228
|
+
"profile"
|
|
1229
|
+
];
|
|
1230
|
+
var MAX_FILE_BYTES = 10 * 1024 * 1024;
|
|
1231
|
+
var MAX_STREAM_IMAGE_BYTES = 2.5 * 1024 * 1024;
|
|
1232
|
+
var URL_FETCH_TIMEOUT_MS = 3e4;
|
|
1233
|
+
var PART_BRAND = /* @__PURE__ */ Symbol.for("@maximem/synap-js-sdk.ContentPart");
|
|
1234
|
+
function brand(part) {
|
|
1235
|
+
Object.defineProperty(part, PART_BRAND, { value: true, enumerable: false });
|
|
1236
|
+
return part;
|
|
1237
|
+
}
|
|
1238
|
+
function isBranded(value) {
|
|
1239
|
+
return typeof value === "object" && value !== null && PART_BRAND in value;
|
|
1240
|
+
}
|
|
1241
|
+
function textPart(text) {
|
|
1242
|
+
if (typeof text !== "string") throw new InvalidInputError("TextPart text must be a string");
|
|
1243
|
+
return brand({ type: "text", text });
|
|
1244
|
+
}
|
|
1245
|
+
function filePart(init) {
|
|
1246
|
+
const source = checkOneSource(init);
|
|
1247
|
+
const filename = defaultFilename(init, source);
|
|
1248
|
+
const mediaType = init.media_type ?? init.mediaType ?? defaultMediaType(filename, init.data ?? void 0);
|
|
1249
|
+
const part = { type: "file" };
|
|
1250
|
+
if (source === "data") part.data = init.data;
|
|
1251
|
+
else if (source === "path") part.path = init.path;
|
|
1252
|
+
else part.url = init.url;
|
|
1253
|
+
part.filename = filename;
|
|
1254
|
+
part.media_type = mediaType;
|
|
1255
|
+
return brand(part);
|
|
1256
|
+
}
|
|
1257
|
+
function isTextPart(value) {
|
|
1258
|
+
return isPlainPart(value) && value["type"] === "text" && typeof value["text"] === "string";
|
|
1259
|
+
}
|
|
1260
|
+
function isFilePart(value) {
|
|
1261
|
+
return isPlainPart(value) && value["type"] === "file";
|
|
1262
|
+
}
|
|
1263
|
+
function isPlainPart(value) {
|
|
1264
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1265
|
+
}
|
|
1266
|
+
function checkOneSource(p) {
|
|
1267
|
+
const given = ["data", "path", "url"].filter(
|
|
1268
|
+
(k) => p[k] !== void 0 && p[k] !== null
|
|
1269
|
+
);
|
|
1270
|
+
if (given.length !== 1) {
|
|
1271
|
+
throw new InvalidInputError(
|
|
1272
|
+
"FilePart takes exactly one of data, path or url" + (given.length > 0 ? ` (got ${given.join(", ")})` : "")
|
|
1273
|
+
);
|
|
1274
|
+
}
|
|
1275
|
+
return given[0];
|
|
1276
|
+
}
|
|
1277
|
+
function lastSegment(p) {
|
|
1278
|
+
const parts = p.split(/[\\/]/);
|
|
1279
|
+
return parts[parts.length - 1] ?? "";
|
|
1280
|
+
}
|
|
1281
|
+
function defaultFilename(p, source) {
|
|
1282
|
+
if (p.filename) return p.filename;
|
|
1283
|
+
if (source === "path") return lastSegment(String(p.path)) || "file";
|
|
1284
|
+
if (source === "url") {
|
|
1285
|
+
let pathname = "";
|
|
1286
|
+
try {
|
|
1287
|
+
pathname = new URL(String(p.url)).pathname;
|
|
1288
|
+
} catch {
|
|
1289
|
+
pathname = String(p.url).split(/[?#]/)[0] ?? "";
|
|
1290
|
+
}
|
|
1291
|
+
return lastSegment(pathname) || "file";
|
|
1292
|
+
}
|
|
1293
|
+
const named = p.data?.name;
|
|
1294
|
+
return typeof named === "string" && named ? named : "file";
|
|
1295
|
+
}
|
|
1296
|
+
var MEDIA_TYPES = {
|
|
1297
|
+
png: "image/png",
|
|
1298
|
+
jpg: "image/jpeg",
|
|
1299
|
+
jpeg: "image/jpeg",
|
|
1300
|
+
jpe: "image/jpeg",
|
|
1301
|
+
webp: "image/webp",
|
|
1302
|
+
gif: "image/gif",
|
|
1303
|
+
bmp: "image/bmp",
|
|
1304
|
+
tif: "image/tiff",
|
|
1305
|
+
tiff: "image/tiff",
|
|
1306
|
+
svg: "image/svg+xml",
|
|
1307
|
+
pdf: "application/pdf",
|
|
1308
|
+
txt: "text/plain",
|
|
1309
|
+
csv: "text/csv",
|
|
1310
|
+
htm: "text/html",
|
|
1311
|
+
html: "text/html",
|
|
1312
|
+
json: "application/json",
|
|
1313
|
+
doc: "application/msword",
|
|
1314
|
+
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
1315
|
+
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
1316
|
+
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
1317
|
+
mp3: "audio/mpeg",
|
|
1318
|
+
wav: "audio/x-wav",
|
|
1319
|
+
mp4: "video/mp4"
|
|
1320
|
+
};
|
|
1321
|
+
function guessMediaType(filename) {
|
|
1322
|
+
const dot = filename.lastIndexOf(".");
|
|
1323
|
+
if (dot <= 0) return null;
|
|
1324
|
+
const ext = filename.slice(dot + 1).toLowerCase();
|
|
1325
|
+
return MEDIA_TYPES[ext] ?? null;
|
|
1326
|
+
}
|
|
1327
|
+
function defaultMediaType(filename, data) {
|
|
1328
|
+
const guessed = guessMediaType(filename);
|
|
1329
|
+
if (guessed !== null) return guessed;
|
|
1330
|
+
const blobType = data?.type;
|
|
1331
|
+
return typeof blobType === "string" && blobType ? blobType : DEFAULT_MEDIA_TYPE;
|
|
1332
|
+
}
|
|
1333
|
+
function normaliseContent(value, field) {
|
|
1334
|
+
if (isBranded(value) && isTextPart(value)) return { kind: "text", text: value.text };
|
|
1335
|
+
if (isBranded(value) && isFilePart(value)) return { kind: "parts", parts: [value] };
|
|
1336
|
+
if (!Array.isArray(value)) return null;
|
|
1337
|
+
if (value.length === 0) {
|
|
1338
|
+
throw new InvalidInputError(`${field} is an empty list; pass at least one part`);
|
|
1339
|
+
}
|
|
1340
|
+
const parts = value.map((item, i) => {
|
|
1341
|
+
if (typeof item === "string") return { type: "text", text: item };
|
|
1342
|
+
if (isTextPart(item) || isFilePart(item)) return item;
|
|
1343
|
+
throw new InvalidInputError(
|
|
1344
|
+
`${field}[${i}] is a ${typeName(item)}; expected a string, TextPart or FilePart`
|
|
1345
|
+
);
|
|
1346
|
+
});
|
|
1347
|
+
if (!parts.some(isFilePart)) {
|
|
1348
|
+
return { kind: "text", text: parts.map((p) => p.text).join("\n") };
|
|
1349
|
+
}
|
|
1350
|
+
return { kind: "parts", parts };
|
|
1351
|
+
}
|
|
1352
|
+
function typeName(value) {
|
|
1353
|
+
if (value === null) return "null";
|
|
1354
|
+
if (Array.isArray(value)) return "array";
|
|
1355
|
+
if (typeof value === "object") {
|
|
1356
|
+
return value.constructor?.name ?? "object";
|
|
1357
|
+
}
|
|
1358
|
+
return typeof value;
|
|
1359
|
+
}
|
|
1360
|
+
async function resolveFile(part, fetchImpl) {
|
|
1361
|
+
const source = checkOneSource(part);
|
|
1362
|
+
const filename = defaultFilename(part, source);
|
|
1363
|
+
let mediaType = part.media_type || defaultMediaType(filename, part.data);
|
|
1364
|
+
let bytes;
|
|
1365
|
+
if (source === "data") {
|
|
1366
|
+
bytes = await toBytes(part.data);
|
|
1367
|
+
} else if (source === "path") {
|
|
1368
|
+
const { readFile } = await import("fs/promises");
|
|
1369
|
+
try {
|
|
1370
|
+
bytes = new Uint8Array(await readFile(part.path));
|
|
1371
|
+
} catch (error) {
|
|
1372
|
+
throw new InvalidInputError(
|
|
1373
|
+
`Could not read FilePart path '${part.path}': ${error?.message ?? String(error)}`,
|
|
1374
|
+
{ cause: error }
|
|
1375
|
+
);
|
|
1376
|
+
}
|
|
1377
|
+
} else {
|
|
1378
|
+
const fetched = await fetchUrl(part.url, fetchImpl);
|
|
1379
|
+
bytes = fetched.bytes;
|
|
1380
|
+
if (mediaType === DEFAULT_MEDIA_TYPE && fetched.contentType) mediaType = fetched.contentType;
|
|
1381
|
+
}
|
|
1382
|
+
if (bytes.byteLength > MAX_FILE_BYTES) {
|
|
1383
|
+
throw new InvalidInputError(
|
|
1384
|
+
`${filename} is ${bytes.byteLength} bytes; the limit is ${MAX_FILE_BYTES} bytes per file`
|
|
1385
|
+
);
|
|
1386
|
+
}
|
|
1387
|
+
return { filename, media_type: mediaType, bytes };
|
|
1388
|
+
}
|
|
1389
|
+
var DEFAULT_MEDIA_TYPE = "application/octet-stream";
|
|
1390
|
+
function urlTooLarge(url) {
|
|
1391
|
+
return `FilePart url '${url}' is over the limit of ${MAX_FILE_BYTES} bytes per file`;
|
|
1392
|
+
}
|
|
1393
|
+
async function toBytes(data) {
|
|
1394
|
+
if (data instanceof Uint8Array) return data;
|
|
1395
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
1396
|
+
if (ArrayBuffer.isView(data)) {
|
|
1397
|
+
const view = data;
|
|
1398
|
+
return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
|
1399
|
+
}
|
|
1400
|
+
if (typeof Blob !== "undefined" && data instanceof Blob) {
|
|
1401
|
+
return new Uint8Array(await data.arrayBuffer());
|
|
1402
|
+
}
|
|
1403
|
+
throw new InvalidInputError("FilePart data must be a Uint8Array, ArrayBuffer or Blob");
|
|
1404
|
+
}
|
|
1405
|
+
async function fetchUrl(url, fetchImpl) {
|
|
1406
|
+
let scheme = "";
|
|
1407
|
+
try {
|
|
1408
|
+
scheme = new URL(url).protocol;
|
|
1409
|
+
} catch {
|
|
1410
|
+
throw new InvalidInputError(`Could not fetch FilePart url '${url}': not a valid URL`);
|
|
1411
|
+
}
|
|
1412
|
+
if (scheme !== "http:" && scheme !== "https:") {
|
|
1413
|
+
throw new InvalidInputError(
|
|
1414
|
+
`Could not fetch FilePart url '${url}': only http and https are supported`
|
|
1415
|
+
);
|
|
1416
|
+
}
|
|
1417
|
+
const controller = new AbortController();
|
|
1418
|
+
const timer = setTimeout(() => controller.abort(), URL_FETCH_TIMEOUT_MS);
|
|
1419
|
+
try {
|
|
1420
|
+
const response = await fetchImpl(url, { method: "GET", signal: controller.signal });
|
|
1421
|
+
if (response.status < 200 || response.status >= 300) {
|
|
1422
|
+
throw new InvalidInputError(
|
|
1423
|
+
`Fetching FilePart url '${url}' returned HTTP ${response.status}`
|
|
1424
|
+
);
|
|
1425
|
+
}
|
|
1426
|
+
const declared = Number(response.headers.get("content-length") ?? "");
|
|
1427
|
+
if (Number.isFinite(declared) && declared > MAX_FILE_BYTES) {
|
|
1428
|
+
throw new InvalidInputError(urlTooLarge(url));
|
|
1429
|
+
}
|
|
1430
|
+
const bytes = await readCapped(response, url);
|
|
1431
|
+
const rawType = response.headers.get("content-type");
|
|
1432
|
+
const contentType = rawType ? rawType.split(";", 1)[0].trim().toLowerCase() || null : null;
|
|
1433
|
+
return { bytes, contentType };
|
|
1434
|
+
} catch (error) {
|
|
1435
|
+
if (error instanceof InvalidInputError) throw error;
|
|
1436
|
+
if (controller.signal.aborted) {
|
|
1437
|
+
throw new InvalidInputError(
|
|
1438
|
+
`Could not fetch FilePart url '${url}': timed out after ${URL_FETCH_TIMEOUT_MS / 1e3} s`,
|
|
1439
|
+
{ cause: error }
|
|
1440
|
+
);
|
|
1441
|
+
}
|
|
1442
|
+
throw new InvalidInputError(
|
|
1443
|
+
`Could not fetch FilePart url '${url}': ${error?.message ?? String(error)}`,
|
|
1444
|
+
{ cause: error }
|
|
1445
|
+
);
|
|
1446
|
+
} finally {
|
|
1447
|
+
clearTimeout(timer);
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
async function readCapped(response, url) {
|
|
1451
|
+
const body = response.body;
|
|
1452
|
+
if (body === null || typeof body.getReader !== "function") {
|
|
1453
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
1454
|
+
}
|
|
1455
|
+
const reader = body.getReader();
|
|
1456
|
+
const chunks = [];
|
|
1457
|
+
let total = 0;
|
|
1458
|
+
for (; ; ) {
|
|
1459
|
+
const { done, value } = await reader.read();
|
|
1460
|
+
if (done) break;
|
|
1461
|
+
total += value.byteLength;
|
|
1462
|
+
if (total > MAX_FILE_BYTES) {
|
|
1463
|
+
await reader.cancel().catch(() => {
|
|
1464
|
+
});
|
|
1465
|
+
throw new InvalidInputError(urlTooLarge(url));
|
|
1466
|
+
}
|
|
1467
|
+
chunks.push(value);
|
|
1468
|
+
}
|
|
1469
|
+
const out = new Uint8Array(total);
|
|
1470
|
+
let at = 0;
|
|
1471
|
+
for (const c of chunks) {
|
|
1472
|
+
out.set(c, at);
|
|
1473
|
+
at += c.byteLength;
|
|
1474
|
+
}
|
|
1475
|
+
return out;
|
|
1476
|
+
}
|
|
1477
|
+
function toBase64(bytes) {
|
|
1478
|
+
const B = globalThis.Buffer;
|
|
1479
|
+
if (B !== void 0) return B.from(bytes).toString("base64");
|
|
1480
|
+
let binary = "";
|
|
1481
|
+
const CHUNK = 32768;
|
|
1482
|
+
for (let i = 0; i < bytes.length; i += CHUNK) {
|
|
1483
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
|
|
1484
|
+
}
|
|
1485
|
+
return btoa(binary);
|
|
1486
|
+
}
|
|
1487
|
+
function placeholderText(parts) {
|
|
1488
|
+
return parts.map((p) => p.type === "text" ? String(p.text ?? "") : `[image: ${p.filename || "image"}]`).join("\n");
|
|
1489
|
+
}
|
|
1490
|
+
async function toInlineParts(parts, fetchImpl) {
|
|
1491
|
+
const resolved = await Promise.all(
|
|
1492
|
+
parts.map((p) => isFilePart(p) ? resolveFile(p, fetchImpl) : null)
|
|
1493
|
+
);
|
|
1494
|
+
let rawBytes = 0;
|
|
1495
|
+
const wire = parts.map((p, i) => {
|
|
1496
|
+
const file = resolved[i];
|
|
1497
|
+
if (file === null || file === void 0) return { type: "text", text: p.text };
|
|
1498
|
+
rawBytes += file.bytes.byteLength;
|
|
1499
|
+
return {
|
|
1500
|
+
type: "image",
|
|
1501
|
+
filename: file.filename,
|
|
1502
|
+
media_type: file.media_type,
|
|
1503
|
+
data: toBase64(file.bytes)
|
|
1504
|
+
};
|
|
1505
|
+
});
|
|
1506
|
+
return { wire, placeholder: placeholderText(wire), rawBytes };
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1195
1509
|
// src/memories/interface.ts
|
|
1196
1510
|
var DOCUMENT_TYPES = [
|
|
1197
1511
|
"ai-chat-conversation",
|
|
@@ -1215,12 +1529,11 @@ function isoOrNull(v) {
|
|
|
1215
1529
|
if (v === void 0 || v === null) return null;
|
|
1216
1530
|
return v instanceof Date ? v.toISOString() : v;
|
|
1217
1531
|
}
|
|
1218
|
-
function
|
|
1219
|
-
if (!options.document) throw new InvalidInputError("document is required");
|
|
1532
|
+
function createFields(options, defaultType) {
|
|
1220
1533
|
const o2 = options;
|
|
1221
|
-
const documentType = either(o2, "document_type", "documentType") ??
|
|
1534
|
+
const documentType = either(o2, "document_type", "documentType") ?? defaultType;
|
|
1222
1535
|
const mode = options.mode ?? DEFAULT_INGEST_MODE;
|
|
1223
|
-
if (!DOCUMENT_TYPES.includes(documentType)) {
|
|
1536
|
+
if (documentType !== null && !DOCUMENT_TYPES.includes(documentType)) {
|
|
1224
1537
|
throw new InvalidInputError(
|
|
1225
1538
|
`Invalid document_type '${documentType}'. Expected one of: ${DOCUMENT_TYPES.join(", ")}`
|
|
1226
1539
|
);
|
|
@@ -1230,22 +1543,70 @@ function buildCreateBody(options) {
|
|
|
1230
1543
|
`Invalid mode '${mode}'. Expected one of: ${INGEST_MODES.join(", ")}`
|
|
1231
1544
|
);
|
|
1232
1545
|
}
|
|
1233
|
-
|
|
1234
|
-
|
|
1546
|
+
const userId = either(o2, "user_id", "userId") ?? null;
|
|
1547
|
+
const customerId = either(o2, "customer_id", "customerId") ?? null;
|
|
1548
|
+
const fields = {
|
|
1235
1549
|
document_type: documentType,
|
|
1236
1550
|
document_id: either(o2, "document_id", "documentId") ?? null,
|
|
1237
1551
|
document_created_at: isoOrNull(
|
|
1238
1552
|
either(o2, "document_created_at", "documentCreatedAt")
|
|
1239
1553
|
),
|
|
1240
|
-
user_id:
|
|
1241
|
-
customer_id:
|
|
1554
|
+
user_id: userId,
|
|
1555
|
+
customer_id: customerId,
|
|
1242
1556
|
// null, never `{}`. An empty path is not absence: the server treats one as
|
|
1243
1557
|
// an error, because a caller asking to be narrowed and being ignored gets
|
|
1244
1558
|
// widened instead.
|
|
1245
|
-
scope: options.scope
|
|
1559
|
+
scope: normaliseCreateScope(options.scope, userId, customerId),
|
|
1246
1560
|
mode,
|
|
1247
1561
|
metadata: options.metadata ?? {}
|
|
1248
1562
|
};
|
|
1563
|
+
if (options.objective !== void 0 && options.objective !== null) {
|
|
1564
|
+
fields["objective"] = options.objective;
|
|
1565
|
+
}
|
|
1566
|
+
return fields;
|
|
1567
|
+
}
|
|
1568
|
+
function normaliseCreateScope(scope, userId, customerId) {
|
|
1569
|
+
if (scope === void 0 || scope === null) return null;
|
|
1570
|
+
const entries = Object.entries(scope);
|
|
1571
|
+
if (entries.length > 1 && entries.some(([, v]) => v === "self")) {
|
|
1572
|
+
throw new InvalidInputError(
|
|
1573
|
+
`"self" can only be used alone, as scope={"client": "self"}; got ${JSON.stringify(scope)}`
|
|
1574
|
+
);
|
|
1575
|
+
}
|
|
1576
|
+
if (entries.length === 1 && entries[0][0] === "client" && entries[0][1] === "self") {
|
|
1577
|
+
if (userId !== null || customerId !== null) {
|
|
1578
|
+
throw new InvalidInputError(
|
|
1579
|
+
'scope={"client": "self"} names the client level, so it cannot be combined with user_id or customer_id'
|
|
1580
|
+
);
|
|
1581
|
+
}
|
|
1582
|
+
return null;
|
|
1583
|
+
}
|
|
1584
|
+
return scope;
|
|
1585
|
+
}
|
|
1586
|
+
function jsonDocument(document, where) {
|
|
1587
|
+
const n2 = normaliseContent(document, "document");
|
|
1588
|
+
if (n2 === null) return document;
|
|
1589
|
+
if (n2.kind === "parts") {
|
|
1590
|
+
throw new InvalidInputError(
|
|
1591
|
+
`${where} cannot carry a FilePart. memories.create sends files as multipart; call it once per document that has files.`
|
|
1592
|
+
);
|
|
1593
|
+
}
|
|
1594
|
+
return n2.text;
|
|
1595
|
+
}
|
|
1596
|
+
function buildCreateBody(options) {
|
|
1597
|
+
const document = jsonDocument(options.document, "This request");
|
|
1598
|
+
if (!document) throw new InvalidInputError("document is required");
|
|
1599
|
+
return { document, ...createFields(options, DEFAULT_DOCUMENT_TYPE) };
|
|
1600
|
+
}
|
|
1601
|
+
function buildCreateManifest(options, parts, files) {
|
|
1602
|
+
let next = 0;
|
|
1603
|
+
const document = parts.map((p) => {
|
|
1604
|
+
if (!isFilePart(p)) return { type: "text", text: p.text };
|
|
1605
|
+
const index = next++;
|
|
1606
|
+
const file = files[index];
|
|
1607
|
+
return { type: "file", field: `file_${index}`, filename: file.filename, media_type: file.media_type };
|
|
1608
|
+
});
|
|
1609
|
+
return { document, ...createFields(options, null) };
|
|
1249
1610
|
}
|
|
1250
1611
|
var FORGET_MODES = ["preview", "direct"];
|
|
1251
1612
|
var FORGET_DESCRIPTION_MIN = 3;
|
|
@@ -1266,21 +1627,63 @@ function buildForgetBody(options) {
|
|
|
1266
1627
|
);
|
|
1267
1628
|
}
|
|
1268
1629
|
const o2 = options;
|
|
1269
|
-
|
|
1630
|
+
const body = {
|
|
1270
1631
|
description,
|
|
1271
1632
|
user_id: either(o2, "user_id", "userId") ?? null,
|
|
1272
1633
|
customer_id: either(o2, "customer_id", "customerId") ?? null,
|
|
1273
1634
|
scope: options.scope ?? null,
|
|
1274
1635
|
mode
|
|
1275
1636
|
};
|
|
1637
|
+
const conversationId = either(o2, "conversation_id", "conversationId");
|
|
1638
|
+
if (conversationId !== void 0 && conversationId !== null) {
|
|
1639
|
+
if (typeof conversationId !== "string" || [...conversationId].length < 1 || [...conversationId].length > 200) {
|
|
1640
|
+
throw new InvalidInputError("conversation_id must be a string of 1 to 200 characters");
|
|
1641
|
+
}
|
|
1642
|
+
body["conversation_id"] = conversationId;
|
|
1643
|
+
}
|
|
1644
|
+
return body;
|
|
1276
1645
|
}
|
|
1277
1646
|
var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "partial_success", "error", "cancelled"]);
|
|
1278
1647
|
function createMemoriesInterface(transport, onForgotten) {
|
|
1279
1648
|
return {
|
|
1280
1649
|
async create(options) {
|
|
1281
1650
|
const o2 = options;
|
|
1282
|
-
|
|
1283
|
-
|
|
1651
|
+
const customerId = o2["customer_id"] ?? o2["customerId"];
|
|
1652
|
+
if (customerId !== void 0 && customerId !== null && customerId !== "") {
|
|
1653
|
+
await transport.checkCustomerId(customerId, "memories.create");
|
|
1654
|
+
}
|
|
1655
|
+
const n2 = normaliseContent(options.document, "document");
|
|
1656
|
+
if (n2 === null || n2.kind === "text") {
|
|
1657
|
+
return transport.request("memories_create", {
|
|
1658
|
+
body: buildCreateBody(options)
|
|
1659
|
+
});
|
|
1660
|
+
}
|
|
1661
|
+
buildCreateManifest(options, n2.parts.filter((p) => !isFilePart(p)), []);
|
|
1662
|
+
const fetchImpl = ((url, init) => transport.fetchExternal(url, init));
|
|
1663
|
+
const files = await Promise.all(
|
|
1664
|
+
n2.parts.filter(isFilePart).map((p) => resolveFile(p, fetchImpl))
|
|
1665
|
+
);
|
|
1666
|
+
const form = new FormData();
|
|
1667
|
+
form.set("manifest", JSON.stringify(buildCreateManifest(options, n2.parts, files)));
|
|
1668
|
+
files.forEach((file, i) => {
|
|
1669
|
+
form.set(
|
|
1670
|
+
`file_${i}`,
|
|
1671
|
+
new Blob([file.bytes], { type: file.media_type }),
|
|
1672
|
+
file.filename
|
|
1673
|
+
);
|
|
1674
|
+
});
|
|
1675
|
+
return transport.request("memories_create_multipart", {
|
|
1676
|
+
body: form,
|
|
1677
|
+
rawBody: true,
|
|
1678
|
+
// A server older than this route answers 404, or 405 because
|
|
1679
|
+
// /api/v1/memories/{memory_id} exists with other methods. Either would
|
|
1680
|
+
// otherwise read as "context not found" or a bare HTTP error.
|
|
1681
|
+
// InvalidInputError, with Python's message.
|
|
1682
|
+
mapError: (status, error) => status === 404 || status === 405 ? new InvalidInputError(
|
|
1683
|
+
"This Synap server does not support file parts in memories.create. Upgrade the Synap server, or send text only.",
|
|
1684
|
+
{ correlationId: error.correlationId, cause: error }
|
|
1685
|
+
) : void 0
|
|
1686
|
+
});
|
|
1284
1687
|
},
|
|
1285
1688
|
async batch_create(options) {
|
|
1286
1689
|
const docs = options.documents;
|
|
@@ -1289,7 +1692,13 @@ function createMemoriesInterface(transport, onForgotten) {
|
|
|
1289
1692
|
}
|
|
1290
1693
|
const failFast = options.fail_fast ?? options.failFast ?? false;
|
|
1291
1694
|
return transport.request("memories_batch", {
|
|
1292
|
-
body: {
|
|
1695
|
+
body: {
|
|
1696
|
+
documents: docs.map((d) => {
|
|
1697
|
+
jsonDocument(d.document, "memories.batch_create");
|
|
1698
|
+
return buildCreateBody(d);
|
|
1699
|
+
}),
|
|
1700
|
+
fail_fast: failFast
|
|
1701
|
+
}
|
|
1293
1702
|
});
|
|
1294
1703
|
},
|
|
1295
1704
|
async create_from_file(options) {
|
|
@@ -1483,7 +1892,7 @@ function iso(v) {
|
|
|
1483
1892
|
if (v === void 0) return void 0;
|
|
1484
1893
|
return v instanceof Date ? v.toISOString() : v;
|
|
1485
1894
|
}
|
|
1486
|
-
function buildRecordMessageBody(options) {
|
|
1895
|
+
function buildRecordMessageBody(options, resolvedContent, field = "content") {
|
|
1487
1896
|
const o2 = options;
|
|
1488
1897
|
const conversationId = either2(o2, "conversation_id", "conversationId");
|
|
1489
1898
|
const userId = either2(o2, "user_id", "userId");
|
|
@@ -1498,10 +1907,22 @@ function buildRecordMessageBody(options) {
|
|
|
1498
1907
|
throw new InvalidInputError("content is required");
|
|
1499
1908
|
}
|
|
1500
1909
|
if (!userId) throw new InvalidInputError("user_id is required");
|
|
1910
|
+
let content = options.content;
|
|
1911
|
+
if (resolvedContent !== void 0) {
|
|
1912
|
+
content = resolvedContent;
|
|
1913
|
+
} else {
|
|
1914
|
+
const n2 = normaliseContent(options.content, field);
|
|
1915
|
+
if (n2?.kind === "parts") {
|
|
1916
|
+
throw new InvalidInputError(
|
|
1917
|
+
"content holds a FilePart, whose bytes have to be read first. Send it with conversation.record_message."
|
|
1918
|
+
);
|
|
1919
|
+
}
|
|
1920
|
+
if (n2 !== null) content = n2.text;
|
|
1921
|
+
}
|
|
1501
1922
|
const body = {
|
|
1502
1923
|
conversation_id: conversationId,
|
|
1503
1924
|
role: options.role,
|
|
1504
|
-
content
|
|
1925
|
+
content,
|
|
1505
1926
|
user_id: userId,
|
|
1506
1927
|
customer_id: customerId,
|
|
1507
1928
|
// Python always sends this, defaulting to {}.
|
|
@@ -1644,6 +2065,24 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
|
|
|
1644
2065
|
inFlight: writesInFlight.get(conversationId) ?? 0
|
|
1645
2066
|
};
|
|
1646
2067
|
};
|
|
2068
|
+
const fetchImpl = ((url, init) => transport.fetchExternal(url, init));
|
|
2069
|
+
const validateMessage = (options, field = "content") => {
|
|
2070
|
+
if (normaliseContent(options.content, field)?.kind === "parts") {
|
|
2071
|
+
buildRecordMessageBody(options, "", field);
|
|
2072
|
+
} else {
|
|
2073
|
+
buildRecordMessageBody(options, void 0, field);
|
|
2074
|
+
}
|
|
2075
|
+
};
|
|
2076
|
+
const prepareMessage = async (options, field = "content") => {
|
|
2077
|
+
const n2 = normaliseContent(options.content, field);
|
|
2078
|
+
if (n2?.kind !== "parts") {
|
|
2079
|
+
const body = buildRecordMessageBody(options, void 0, field);
|
|
2080
|
+
return { body, mirror: String(body["content"] ?? "") };
|
|
2081
|
+
}
|
|
2082
|
+
validateMessage(options, field);
|
|
2083
|
+
const inline = await toInlineParts(n2.parts, fetchImpl);
|
|
2084
|
+
return { body: buildRecordMessageBody(options, inline.wire), mirror: inline.placeholder };
|
|
2085
|
+
};
|
|
1647
2086
|
const convId = (v) => {
|
|
1648
2087
|
const id = typeof v === "string" ? v : v.conversation_id ?? v.conversationId;
|
|
1649
2088
|
if (!id) throw new InvalidInputError("conversation_id is required");
|
|
@@ -1656,7 +2095,9 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
|
|
|
1656
2095
|
options["customer_id"] ?? options["customerId"],
|
|
1657
2096
|
"conversation.record_message"
|
|
1658
2097
|
);
|
|
1659
|
-
const
|
|
2098
|
+
const prepared = await prepareMessage(options);
|
|
2099
|
+
const body = withTurnModel(prepared.body, options);
|
|
2100
|
+
const mirror = prepared.mirror;
|
|
1660
2101
|
const conversationId = String(body["conversation_id"] ?? "");
|
|
1661
2102
|
writeStarted(conversationId);
|
|
1662
2103
|
let result;
|
|
@@ -1668,7 +2109,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
|
|
|
1668
2109
|
onTurn({
|
|
1669
2110
|
conversationId,
|
|
1670
2111
|
role: String(body["role"] ?? "user"),
|
|
1671
|
-
content:
|
|
2112
|
+
content: mirror,
|
|
1672
2113
|
timestamp: body["timestamp"],
|
|
1673
2114
|
...confirmation(result, conversationId)
|
|
1674
2115
|
});
|
|
@@ -1689,7 +2130,11 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
|
|
|
1689
2130
|
"conversation.record_messages_batch"
|
|
1690
2131
|
);
|
|
1691
2132
|
}
|
|
1692
|
-
const
|
|
2133
|
+
const field = (i) => `messages[${i}].content`;
|
|
2134
|
+
messages.forEach((m, i) => validateMessage(m, field(i)));
|
|
2135
|
+
const prepared = await Promise.all(messages.map((m, i) => prepareMessage(m, field(i))));
|
|
2136
|
+
const bodies = prepared.map((p, i) => withTurnModel(p.body, messages[i]));
|
|
2137
|
+
const mirrors = new Map(prepared.map((p, i) => [bodies[i], p.mirror]));
|
|
1693
2138
|
const result = await transport.request("conversations_messages_batch", {
|
|
1694
2139
|
body: { messages: bodies }
|
|
1695
2140
|
});
|
|
@@ -1698,7 +2143,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
|
|
|
1698
2143
|
onTurn({
|
|
1699
2144
|
conversationId,
|
|
1700
2145
|
role: String(body["role"] ?? "user"),
|
|
1701
|
-
content: String(body["content"] ?? ""),
|
|
2146
|
+
content: mirrors.get(body) ?? String(body["content"] ?? ""),
|
|
1702
2147
|
timestamp: body["timestamp"],
|
|
1703
2148
|
...confirmation(row, conversationId)
|
|
1704
2149
|
});
|
|
@@ -2027,6 +2472,7 @@ function createCacheNamespace(cache) {
|
|
|
2027
2472
|
}
|
|
2028
2473
|
|
|
2029
2474
|
// src/instance/interface.ts
|
|
2475
|
+
var CONTENT_PARTS_METADATA_KEY = "synap_content_parts";
|
|
2030
2476
|
var DEFAULT_GRPC_HOST = "synap-cloud-prod.maximem.ai";
|
|
2031
2477
|
var DEFAULT_GRPC_PORT = 443;
|
|
2032
2478
|
function envPort() {
|
|
@@ -2082,13 +2528,21 @@ function jsonOrText(value) {
|
|
|
2082
2528
|
}
|
|
2083
2529
|
}
|
|
2084
2530
|
}
|
|
2085
|
-
function createInstanceNamespace(credentials, cache, onTurn,
|
|
2086
|
-
|
|
2531
|
+
function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel, agentModelOrToolResult, onToolResultOrCheck, checkCustomerIdArg) {
|
|
2532
|
+
const defaultFetch = ((url, init) => globalThis.fetch(url, init));
|
|
2533
|
+
const imageFirst = fetchOrAgentModel !== void 0 && (fetchOrAgentModel.length > 0 || agentModelOrToolResult === void 0);
|
|
2534
|
+
const fetchUrl2 = imageFirst ? fetchOrAgentModel : defaultFetch;
|
|
2535
|
+
const agentModel = (imageFirst ? agentModelOrToolResult : fetchOrAgentModel) ?? (() => ({}));
|
|
2536
|
+
const onToolResult = imageFirst ? onToolResultOrCheck : agentModelOrToolResult;
|
|
2537
|
+
const checkCustomerId3 = (imageFirst ? checkCustomerIdArg : onToolResultOrCheck) ?? (async () => {
|
|
2538
|
+
});
|
|
2539
|
+
const hasCustomerIdCheck = (imageFirst ? checkCustomerIdArg : onToolResultOrCheck) !== void 0;
|
|
2087
2540
|
let client = null;
|
|
2088
2541
|
const openSessions = /* @__PURE__ */ new Map();
|
|
2089
2542
|
let dispatchCompaction = null;
|
|
2090
2543
|
let applyCompaction = null;
|
|
2091
2544
|
let onListen = null;
|
|
2545
|
+
let listenBlockedBy = null;
|
|
2092
2546
|
let onConversationState = null;
|
|
2093
2547
|
const internals = {
|
|
2094
2548
|
onCompactionUpdate(conversationId, bundle) {
|
|
@@ -2101,6 +2555,9 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
|
|
|
2101
2555
|
setOnListen(handle) {
|
|
2102
2556
|
onListen = handle;
|
|
2103
2557
|
},
|
|
2558
|
+
blockListen(message) {
|
|
2559
|
+
listenBlockedBy = message;
|
|
2560
|
+
},
|
|
2104
2561
|
setConversationStateHandler(handle) {
|
|
2105
2562
|
onConversationState = handle;
|
|
2106
2563
|
},
|
|
@@ -2133,8 +2590,28 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
|
|
|
2133
2590
|
} catch {
|
|
2134
2591
|
}
|
|
2135
2592
|
}
|
|
2593
|
+
let tail = Promise.resolve();
|
|
2594
|
+
let queued = 0;
|
|
2595
|
+
function inOrder(prepared, send, sync) {
|
|
2596
|
+
if (prepared === null && queued === 0) {
|
|
2597
|
+
send(sync);
|
|
2598
|
+
return Promise.resolve();
|
|
2599
|
+
}
|
|
2600
|
+
prepared?.catch(() => {
|
|
2601
|
+
});
|
|
2602
|
+
queued += 1;
|
|
2603
|
+
const run = tail.then(async () => {
|
|
2604
|
+
send(prepared === null ? sync : await prepared);
|
|
2605
|
+
});
|
|
2606
|
+
const done = () => {
|
|
2607
|
+
queued -= 1;
|
|
2608
|
+
};
|
|
2609
|
+
tail = run.then(done, done);
|
|
2610
|
+
return run;
|
|
2611
|
+
}
|
|
2136
2612
|
const namespace = {
|
|
2137
2613
|
async listen(options = {}) {
|
|
2614
|
+
if (listenBlockedBy !== null) throw new SynapPermanentError(listenBlockedBy);
|
|
2138
2615
|
if (client !== null) {
|
|
2139
2616
|
throw new ListeningAlreadyActiveError("Listening is already active on this instance");
|
|
2140
2617
|
}
|
|
@@ -2142,7 +2619,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
|
|
|
2142
2619
|
onListen?.();
|
|
2143
2620
|
} catch {
|
|
2144
2621
|
}
|
|
2145
|
-
const { GrpcStreamClient } = await import("./stream-client-
|
|
2622
|
+
const { GrpcStreamClient } = await import("./stream-client-Q2RR5SCS.js");
|
|
2146
2623
|
const onContext = options.on_context ?? options.onContext;
|
|
2147
2624
|
const onDisconnect = options.on_disconnect ?? options.onDisconnect;
|
|
2148
2625
|
const onReconnect = options.on_reconnect ?? options.onReconnect;
|
|
@@ -2206,10 +2683,12 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
|
|
|
2206
2683
|
}
|
|
2207
2684
|
},
|
|
2208
2685
|
async send_message(options) {
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2686
|
+
if (hasCustomerIdCheck) {
|
|
2687
|
+
await checkCustomerId3(
|
|
2688
|
+
options.customer_id ?? options.customerId,
|
|
2689
|
+
"instance.send_message"
|
|
2690
|
+
);
|
|
2691
|
+
}
|
|
2213
2692
|
if (client === null) throw new ListeningNotActiveError("Listening is not active");
|
|
2214
2693
|
const eventType = options.event_type ?? options.eventType ?? "user_message";
|
|
2215
2694
|
if (!KNOWN_EVENT_TYPES.has(eventType)) {
|
|
@@ -2220,46 +2699,68 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
|
|
|
2220
2699
|
if (options.content === void 0 || options.content === null) {
|
|
2221
2700
|
throw new InvalidInputError("content is required");
|
|
2222
2701
|
}
|
|
2223
|
-
const
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
options.
|
|
2227
|
-
|
|
2228
|
-
);
|
|
2229
|
-
if (eventType === "user_message" || eventType === "assistant_message") {
|
|
2230
|
-
onTurn?.({
|
|
2702
|
+
const parts = normaliseContent(options.content, "content");
|
|
2703
|
+
const emit = ({ content, metadata }) => {
|
|
2704
|
+
if (client === null) throw new ListeningNotActiveError("Listening is not active");
|
|
2705
|
+
const conversationId = options.conversation_id ?? options.conversationId ?? "";
|
|
2706
|
+
ensureSession(
|
|
2231
2707
|
conversationId,
|
|
2708
|
+
options.user_id ?? options.userId ?? "",
|
|
2709
|
+
options.customer_id ?? options.customerId ?? ""
|
|
2710
|
+
);
|
|
2711
|
+
if (eventType === "user_message" || eventType === "assistant_message") {
|
|
2712
|
+
onTurn?.({
|
|
2713
|
+
conversationId,
|
|
2714
|
+
role: options.role ?? "user",
|
|
2715
|
+
content
|
|
2716
|
+
});
|
|
2717
|
+
}
|
|
2718
|
+
client.sendConversationEvent({
|
|
2719
|
+
event_type: eventType,
|
|
2720
|
+
content,
|
|
2232
2721
|
role: options.role ?? "user",
|
|
2233
|
-
|
|
2722
|
+
conversation_id: options.conversation_id ?? options.conversationId ?? "",
|
|
2723
|
+
user_id: options.user_id ?? options.userId ?? "",
|
|
2724
|
+
customer_id: options.customer_id ?? options.customerId ?? "",
|
|
2725
|
+
session_id: options.session_id ?? options.sessionId ?? openSessions.get(conversationId) ?? "",
|
|
2726
|
+
metadata: withAgentModel(metadata, agentModelOf(options), agentModel(), true) ?? {},
|
|
2727
|
+
timestamp_ms: Date.now(),
|
|
2728
|
+
tool_name: options.tool_name ?? options.toolName ?? "",
|
|
2729
|
+
// Python serialises tool_args with json.dumps into tool_args_json.
|
|
2730
|
+
tool_args_json: (() => {
|
|
2731
|
+
const a = options.tool_args ?? options.toolArgs;
|
|
2732
|
+
return a === void 0 ? "" : jsonOrText(a);
|
|
2733
|
+
})(),
|
|
2734
|
+
tool_result_json: toolResultJson(options.tool_result ?? options.toolResult),
|
|
2735
|
+
tool_call_id: options.tool_call_id ?? options.toolCallId ?? "",
|
|
2736
|
+
search_queries: options.search_queries ?? options.searchQueries ?? [],
|
|
2737
|
+
context_types: options.context_types ?? options.contextTypes ?? [],
|
|
2738
|
+
...(() => {
|
|
2739
|
+
const sp = options.scope_path ?? options.scopePath;
|
|
2740
|
+
return sp && Object.keys(sp).length > 0 ? { scope: sp } : {};
|
|
2741
|
+
})()
|
|
2234
2742
|
});
|
|
2743
|
+
};
|
|
2744
|
+
if (parts?.kind !== "parts") {
|
|
2745
|
+
const content = parts?.kind === "text" ? parts.text : options.content;
|
|
2746
|
+
return inOrder(null, emit, { content, metadata: options.metadata ?? {} });
|
|
2235
2747
|
}
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
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
|
-
});
|
|
2748
|
+
const prepared = (async () => {
|
|
2749
|
+
const inline = await toInlineParts(parts.parts, fetchUrl2);
|
|
2750
|
+
if (inline.rawBytes > MAX_STREAM_IMAGE_BYTES) {
|
|
2751
|
+
throw new InvalidInputError(
|
|
2752
|
+
`The images in this event come to more than ${MAX_STREAM_IMAGE_BYTES} bytes, which is over what one streamed event can carry. Send them with memories.create or conversation.record_message instead.`
|
|
2753
|
+
);
|
|
2754
|
+
}
|
|
2755
|
+
return {
|
|
2756
|
+
content: inline.placeholder,
|
|
2757
|
+
metadata: {
|
|
2758
|
+
...options.metadata ?? {},
|
|
2759
|
+
[CONTENT_PARTS_METADATA_KEY]: JSON.stringify(inline.wire)
|
|
2760
|
+
}
|
|
2761
|
+
};
|
|
2762
|
+
})();
|
|
2763
|
+
return inOrder(prepared, emit);
|
|
2263
2764
|
},
|
|
2264
2765
|
async record_tool_call(options) {
|
|
2265
2766
|
await namespace.send_message({
|
|
@@ -2303,24 +2804,27 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
|
|
|
2303
2804
|
options.user_id ?? options.userId ?? "",
|
|
2304
2805
|
options.customer_id ?? options.customerId ?? ""
|
|
2305
2806
|
);
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2807
|
+
return inOrder(null, () => {
|
|
2808
|
+
if (client === null) throw new ListeningNotActiveError("Listening is not active");
|
|
2809
|
+
client.sendConversationEvent({
|
|
2810
|
+
// Python emits reasoning as an `agent_thinking` conversation event.
|
|
2811
|
+
event_type: "agent_thinking",
|
|
2812
|
+
content: options.content,
|
|
2813
|
+
// Deliberately no role. A thought is not the assistant's reply, and
|
|
2814
|
+
// this went out as 'assistant' from the day it shipped: the server
|
|
2815
|
+
// checked role before event_type, so every reasoning step any client
|
|
2816
|
+
// sent was filed as the final answer and the reasoning path never ran.
|
|
2817
|
+
// Sending no role is correct against both the fixed server and one that
|
|
2818
|
+
// has not been updated yet.
|
|
2819
|
+
role: "",
|
|
2820
|
+
conversation_id: options.conversation_id ?? options.conversationId ?? "",
|
|
2821
|
+
user_id: options.user_id ?? options.userId ?? "",
|
|
2822
|
+
customer_id: options.customer_id ?? options.customerId ?? "",
|
|
2823
|
+
session_id: options.session_id ?? options.sessionId ?? "",
|
|
2824
|
+
metadata: thinkingMetadata(options),
|
|
2825
|
+
timestamp_ms: Date.now()
|
|
2826
|
+
});
|
|
2827
|
+
}, void 0);
|
|
2324
2828
|
},
|
|
2325
2829
|
get is_listening() {
|
|
2326
2830
|
return client !== null && client.isConnected;
|
|
@@ -2331,7 +2835,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
|
|
|
2331
2835
|
}
|
|
2332
2836
|
|
|
2333
2837
|
// src/version.ts
|
|
2334
|
-
var SDK_VERSION = "0.6.
|
|
2838
|
+
var SDK_VERSION = "0.6.7";
|
|
2335
2839
|
|
|
2336
2840
|
// src/registry.ts
|
|
2337
2841
|
var instances = /* @__PURE__ */ new Map();
|
|
@@ -4060,6 +4564,7 @@ var SynapClient = class _SynapClient {
|
|
|
4060
4564
|
#closed = false;
|
|
4061
4565
|
#initialized = false;
|
|
4062
4566
|
#identity;
|
|
4567
|
+
#localMode = false;
|
|
4063
4568
|
#registryKeys;
|
|
4064
4569
|
#compactionSubscribers;
|
|
4065
4570
|
#shortTerm;
|
|
@@ -4078,8 +4583,9 @@ var SynapClient = class _SynapClient {
|
|
|
4078
4583
|
#turns;
|
|
4079
4584
|
#fetchHooks;
|
|
4080
4585
|
constructor(options = {}) {
|
|
4081
|
-
const credentials = resolveCredentials(options);
|
|
4082
4586
|
const resolvedBaseUrl = resolveBaseUrl(options);
|
|
4587
|
+
const localMode = isLocalMode(options.apiKey, resolvedBaseUrl);
|
|
4588
|
+
const credentials = resolveCredentials(options, localMode);
|
|
4083
4589
|
validateInstanceId(credentials.instanceId);
|
|
4084
4590
|
const registryKey = buildRegistryKey(credentials.instanceId, credentials.apiKey);
|
|
4085
4591
|
if (options._force_new !== true) {
|
|
@@ -4095,6 +4601,7 @@ var SynapClient = class _SynapClient {
|
|
|
4095
4601
|
}
|
|
4096
4602
|
}
|
|
4097
4603
|
this.#registryKeys = options._force_new === true ? [] : [registryKey];
|
|
4604
|
+
this.#localMode = localMode;
|
|
4098
4605
|
this.#transport = new HttpTransport({
|
|
4099
4606
|
credentials,
|
|
4100
4607
|
// SYNAP_BASE_URL is honoured, as Python does (sdk.py) and as the 0.3.x
|
|
@@ -4287,11 +4794,18 @@ var SynapClient = class _SynapClient {
|
|
|
4287
4794
|
({ conversationId, role, content }) => {
|
|
4288
4795
|
this.#shortTerm.appendTurn(conversationId, role, content);
|
|
4289
4796
|
},
|
|
4797
|
+
// A FilePart given by url is read with the same fetch as everything else.
|
|
4798
|
+
((url, init) => this.#transport.fetchExternal(url, init)),
|
|
4290
4799
|
() => this.#agentModel,
|
|
4291
4800
|
({ conversationId, result, toolName }) => this.archive_tool_result(conversationId, result, { tool_name: toolName }),
|
|
4292
4801
|
(customerId, where) => this.#transport.checkCustomerId(customerId, where)
|
|
4293
4802
|
);
|
|
4294
4803
|
this.instance._internal.setOnListen(() => this.#startLocalModel());
|
|
4804
|
+
if (localMode) {
|
|
4805
|
+
this.instance._internal.blockListen(
|
|
4806
|
+
"Not available in the open-source server: listen() needs the gRPC stream and anticipation, which it does not have."
|
|
4807
|
+
);
|
|
4808
|
+
}
|
|
4295
4809
|
this.instance._internal.setCompactionApplier((bundle) => {
|
|
4296
4810
|
this.#shortTerm.applyCompaction(bundle);
|
|
4297
4811
|
});
|
|
@@ -4405,12 +4919,15 @@ var SynapClient = class _SynapClient {
|
|
|
4405
4919
|
}
|
|
4406
4920
|
/** Runs whoami at most once, however many calls arrive together. */
|
|
4407
4921
|
#resolveIdentity() {
|
|
4408
|
-
this.#identity ??= this.#whoami()
|
|
4922
|
+
this.#identity ??= this.#whoami().catch((error) => {
|
|
4923
|
+
this.#identity = void 0;
|
|
4924
|
+
throw error;
|
|
4925
|
+
});
|
|
4409
4926
|
return this.#identity;
|
|
4410
4927
|
}
|
|
4411
4928
|
async #whoami() {
|
|
4412
4929
|
const credentials = this.#transport.currentCredentials();
|
|
4413
|
-
if (credentials.clientId !== "" && credentials.instanceId !== "") return;
|
|
4930
|
+
if (!this.#localMode && credentials.clientId !== "" && credentials.instanceId !== "") return;
|
|
4414
4931
|
try {
|
|
4415
4932
|
const whoami = await this.#transport.request("whoami", {});
|
|
4416
4933
|
const resolvedClientId = String(whoami["client_id"] ?? "");
|
|
@@ -4426,7 +4943,21 @@ var SynapClient = class _SynapClient {
|
|
|
4426
4943
|
this.#registryKeys.push(resolvedInstanceId);
|
|
4427
4944
|
}
|
|
4428
4945
|
}
|
|
4429
|
-
} catch {
|
|
4946
|
+
} catch (error) {
|
|
4947
|
+
if (this.#localMode) {
|
|
4948
|
+
throw new AuthenticationError(
|
|
4949
|
+
`Could not reach the Synap server at ${this.#transport.baseUrl}, or it did not identify itself: GET /api/v1/auth/whoami failed (${error?.message ?? String(error)}).`,
|
|
4950
|
+
{ cause: error }
|
|
4951
|
+
);
|
|
4952
|
+
}
|
|
4953
|
+
}
|
|
4954
|
+
if (this.#localMode) {
|
|
4955
|
+
const known = this.#transport.currentCredentials();
|
|
4956
|
+
if (known.clientId === "" || known.instanceId === "") {
|
|
4957
|
+
throw new AuthenticationError(
|
|
4958
|
+
`The Synap server at ${this.#transport.baseUrl} did not identify itself: GET /api/v1/auth/whoami returned no client_id or instance_id.`
|
|
4959
|
+
);
|
|
4960
|
+
}
|
|
4430
4961
|
}
|
|
4431
4962
|
}
|
|
4432
4963
|
/**
|
|
@@ -4891,15 +5422,16 @@ function resolveBaseUrl(options) {
|
|
|
4891
5422
|
const fromEnv = getEnv("SYNAP_BASE_URL")?.trim();
|
|
4892
5423
|
return fromEnv !== void 0 && fromEnv !== "" ? fromEnv : void 0;
|
|
4893
5424
|
}
|
|
4894
|
-
function resolveCredentials(options) {
|
|
5425
|
+
function resolveCredentials(options, localMode) {
|
|
4895
5426
|
const apiKey = options.apiKey || getEnv("SYNAP_API_KEY");
|
|
4896
|
-
if (!apiKey) {
|
|
5427
|
+
if (!apiKey && !localMode) {
|
|
4897
5428
|
throw new AuthenticationError(
|
|
4898
5429
|
"No Synap API key found. Set SYNAP_API_KEY in your environment, or pass apiKey to the SynapClient constructor."
|
|
4899
5430
|
);
|
|
4900
5431
|
}
|
|
4901
5432
|
return {
|
|
4902
|
-
|
|
5433
|
+
// In local mode the credential is the optional token, '' when there is none.
|
|
5434
|
+
apiKey: apiKey || localToken(),
|
|
4903
5435
|
clientId: options.clientId ?? getEnv("SYNAP_CLIENT_ID") ?? "",
|
|
4904
5436
|
instanceId: options.instanceId ?? getEnv("SYNAP_INSTANCE_ID") ?? ""
|
|
4905
5437
|
};
|
|
@@ -4939,6 +5471,7 @@ export {
|
|
|
4939
5471
|
ListeningNotActiveError,
|
|
4940
5472
|
MEMORY_TYPES,
|
|
4941
5473
|
NetworkTimeoutError,
|
|
5474
|
+
OBJECTIVES,
|
|
4942
5475
|
PermanentError,
|
|
4943
5476
|
RESPONSE_SHAPES,
|
|
4944
5477
|
RateLimitError,
|
|
@@ -4954,6 +5487,7 @@ export {
|
|
|
4954
5487
|
TranscriptConflictError,
|
|
4955
5488
|
TransientError,
|
|
4956
5489
|
applyResponseShape,
|
|
5490
|
+
filePart,
|
|
4957
5491
|
flattenContextItems,
|
|
4958
5492
|
formatForPrompt,
|
|
4959
5493
|
isOutcomeUnknown,
|
|
@@ -4963,6 +5497,7 @@ export {
|
|
|
4963
5497
|
resolvePath,
|
|
4964
5498
|
shouldRetry,
|
|
4965
5499
|
stem,
|
|
5500
|
+
textPart,
|
|
4966
5501
|
tokenize,
|
|
4967
5502
|
wireRankScore
|
|
4968
5503
|
};
|