@maximem/synap-js-sdk 0.6.4 → 0.6.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/anticipation-cache-Q7IYC3ID.cjs +26 -0
- package/dist/anticipation-cache-Q7IYC3ID.cjs.map +1 -0
- package/dist/{anticipation-cache-RWKF55J4.js → anticipation-cache-VL5WHTJB.js} +8 -2
- package/dist/chunk-7IZHVYO2.cjs.map +1 -1
- package/dist/{chunk-ICUFS3B5.cjs → chunk-BYUGILQI.cjs} +136 -142
- package/dist/chunk-BYUGILQI.cjs.map +1 -0
- package/dist/{chunk-R72YL6Q4.js → chunk-CSG3N5E3.js} +136 -142
- package/dist/chunk-CSG3N5E3.js.map +1 -0
- package/dist/{chunk-2VJV4HCF.cjs → chunk-PYJOWTI5.cjs} +72 -20
- package/dist/chunk-PYJOWTI5.cjs.map +1 -0
- package/dist/{chunk-N55UBGER.js → chunk-VCCZ33ZU.js} +59 -7
- package/dist/chunk-VCCZ33ZU.js.map +1 -0
- package/dist/chunk-ZKOJDUN4.cjs.map +1 -1
- package/dist/env-55ULHNJZ.cjs.map +1 -1
- package/dist/{errors-DWjdpExq.d.cts → errors-x5bpgxmC.d.cts} +18 -3
- package/dist/{errors-DWjdpExq.d.ts → errors-x5bpgxmC.d.ts} +18 -3
- package/dist/grpc/index.cjs +4 -4
- package/dist/grpc/index.cjs.map +1 -1
- package/dist/grpc/index.d.cts +11 -3
- package/dist/grpc/index.d.ts +11 -3
- package/dist/grpc/index.js +3 -3
- package/dist/index.cjs +906 -185
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +242 -20
- package/dist/index.d.ts +242 -20
- package/dist/index.js +826 -105
- package/dist/index.js.map +1 -1
- package/dist/onnx-encoder-4RSL6ID4.cjs.map +1 -1
- package/dist/stream-client-BY5LNLVB.cjs +22 -0
- package/dist/stream-client-BY5LNLVB.cjs.map +1 -0
- package/dist/{stream-client-GRDVRBFA.js → stream-client-JKFBVZPN.js} +2 -2
- package/package.json +1 -1
- package/dist/anticipation-cache-LPNKMRBH.cjs +0 -20
- package/dist/anticipation-cache-LPNKMRBH.cjs.map +0 -1
- package/dist/chunk-2VJV4HCF.cjs.map +0 -1
- package/dist/chunk-ICUFS3B5.cjs.map +0 -1
- package/dist/chunk-N55UBGER.js.map +0 -1
- package/dist/chunk-R72YL6Q4.js.map +0 -1
- package/dist/stream-client-SZIYGVVJ.cjs +0 -22
- package/dist/stream-client-SZIYGVVJ.cjs.map +0 -1
- /package/dist/{anticipation-cache-RWKF55J4.js.map → anticipation-cache-VL5WHTJB.js.map} +0 -0
- /package/dist/{stream-client-GRDVRBFA.js.map → stream-client-JKFBVZPN.js.map} +0 -0
package/dist/index.js
CHANGED
|
@@ -6,11 +6,10 @@ import {
|
|
|
6
6
|
HISTORY_SEARCH,
|
|
7
7
|
SEMANTIC_MATCH,
|
|
8
8
|
THRESHOLDS,
|
|
9
|
-
isRecallQuery,
|
|
10
9
|
rungKey,
|
|
11
10
|
stem,
|
|
12
11
|
tokenize
|
|
13
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-CSG3N5E3.js";
|
|
14
13
|
import {
|
|
15
14
|
getEnv
|
|
16
15
|
} from "./chunk-QBCVMPGK.js";
|
|
@@ -50,11 +49,14 @@ var ENDPOINTS = {
|
|
|
50
49
|
memories_create: { method: "POST", path: "/api/v1/memories/create", idempotent: false },
|
|
51
50
|
memories_batch: { method: "POST", path: "/api/v1/memories/batch", idempotent: false },
|
|
52
51
|
memories_upload: { method: "POST", path: "/api/v1/memories/upload", idempotent: false },
|
|
52
|
+
memories_create_multipart: { method: "POST", path: "/api/v1/memories/create-multipart", idempotent: false },
|
|
53
53
|
memories_status: { method: "GET", path: "/api/v1/memories/status/{ingestion_id}", idempotent: true },
|
|
54
54
|
memories_get: { method: "GET", path: "/api/v1/memories/{memory_id}", idempotent: true },
|
|
55
55
|
memories_update: { method: "PATCH", path: "/api/v1/memories/{memory_id}", idempotent: false },
|
|
56
56
|
memories_delete: { method: "DELETE", path: "/api/v1/memories/{memory_id}", idempotent: true },
|
|
57
57
|
memories_forget: { method: "POST", path: "/api/v1/memories/forget", idempotent: false },
|
|
58
|
+
data_delete: { method: "POST", path: "/v1/data/delete", idempotent: true },
|
|
59
|
+
data_delete_status: { method: "GET", path: "/v1/data/delete/{deletion_id}", idempotent: true },
|
|
58
60
|
context_fetch_user: { method: "POST", path: "/v1/context/user/fetch", idempotent: true },
|
|
59
61
|
context_fetch_customer: { method: "POST", path: "/v1/context/customer/fetch", idempotent: true },
|
|
60
62
|
context_fetch_client: { method: "POST", path: "/v1/context/client/fetch", idempotent: true },
|
|
@@ -271,6 +273,16 @@ var HttpTransport = class {
|
|
|
271
273
|
options.keepAlive?.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS
|
|
272
274
|
);
|
|
273
275
|
}
|
|
276
|
+
/**
|
|
277
|
+
* @internal Fetch a URL that is not Synap's, with this transport's fetch.
|
|
278
|
+
*
|
|
279
|
+
* Used to read a `FilePart` given by `url`: the SDK fetches it, the server
|
|
280
|
+
* never does. Deliberately sends none of this transport's headers, because
|
|
281
|
+
* the URL belongs to somebody else and the API key must not reach them.
|
|
282
|
+
*/
|
|
283
|
+
fetchExternal(url, init = {}) {
|
|
284
|
+
return this.fetchImpl(url, init);
|
|
285
|
+
}
|
|
274
286
|
/** Start keeping the connection warm. Opt-in: it is pointless in serverless. */
|
|
275
287
|
startHeartbeat() {
|
|
276
288
|
if (!this.closed) this.heartbeat.start();
|
|
@@ -387,7 +399,7 @@ var HttpTransport = class {
|
|
|
387
399
|
if (gated) this.cooldownCheck(cooldownKey, correlationId);
|
|
388
400
|
let attempt = 0;
|
|
389
401
|
let last = null;
|
|
390
|
-
while (attempt < this.retryPolicy.maxAttempts) {
|
|
402
|
+
while (attempt < Math.max(1, this.retryPolicy.maxAttempts)) {
|
|
391
403
|
attempt += 1;
|
|
392
404
|
try {
|
|
393
405
|
const result = await this.attempt(name, options, correlationId);
|
|
@@ -435,7 +447,8 @@ var HttpTransport = class {
|
|
|
435
447
|
signal.dispose();
|
|
436
448
|
}
|
|
437
449
|
if (!response.ok) {
|
|
438
|
-
|
|
450
|
+
const error = await toHttpError(response, correlationId);
|
|
451
|
+
throw options.mapError?.(response.status, error) ?? error;
|
|
439
452
|
}
|
|
440
453
|
if (response.status === 204) return void 0;
|
|
441
454
|
const text = await response.text();
|
|
@@ -546,6 +559,11 @@ async function toHttpError(response, correlationId) {
|
|
|
546
559
|
switch (response.status) {
|
|
547
560
|
case 400:
|
|
548
561
|
case 422:
|
|
562
|
+
// Wrong method, too large, unsupported media type: each says what was
|
|
563
|
+
// wrong with the request, and none of them goes away on a retry.
|
|
564
|
+
case 405:
|
|
565
|
+
case 413:
|
|
566
|
+
case 415:
|
|
549
567
|
return new InvalidInputError(message, opts);
|
|
550
568
|
case 401:
|
|
551
569
|
case 403:
|
|
@@ -740,6 +758,41 @@ function sortByRankScore(items) {
|
|
|
740
758
|
return [...items].sort(byRankScore);
|
|
741
759
|
}
|
|
742
760
|
|
|
761
|
+
// src/context/no-query.ts
|
|
762
|
+
var MEMORY_TYPES2 = ["facts", "preferences", "episodes", "emotions", "temporal_events"];
|
|
763
|
+
var emptyLists = () => Object.fromEntries(MEMORY_TYPES2.map((t) => [t, []]));
|
|
764
|
+
function hasQuery(searchQuery) {
|
|
765
|
+
if (typeof searchQuery === "string") return searchQuery.trim() !== "";
|
|
766
|
+
if (!Array.isArray(searchQuery)) return false;
|
|
767
|
+
return searchQuery.some((q) => typeof q === "string" && q.trim() !== "");
|
|
768
|
+
}
|
|
769
|
+
function conversationStateContext(prompt, conversationId) {
|
|
770
|
+
const recent = Array.isArray(prompt["recent_messages"]) ? prompt["recent_messages"] : [];
|
|
771
|
+
const turns = recent.filter((m) => typeof m === "object" && m !== null && !Array.isArray(m)).map((m) => ({ role: m["role"] ?? null, content: m["content"] ?? null, timestamp: m["timestamp"] ?? null }));
|
|
772
|
+
return {
|
|
773
|
+
...emptyLists(),
|
|
774
|
+
conversation_context: {
|
|
775
|
+
conversation_id: conversationId,
|
|
776
|
+
summary: prompt["context_block"] || null,
|
|
777
|
+
recent_turns: turns,
|
|
778
|
+
compaction_id: prompt["compaction_id"] || null,
|
|
779
|
+
formatted_context: prompt["formatted_context"] || null
|
|
780
|
+
}
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
function profileContext(profile) {
|
|
784
|
+
if (typeof profile !== "object" || profile === null || Array.isArray(profile)) return null;
|
|
785
|
+
let doc = profile;
|
|
786
|
+
const inner = doc["profile"];
|
|
787
|
+
if (!("attributes" in doc) && typeof inner === "object" && inner !== null && !Array.isArray(inner)) {
|
|
788
|
+
doc = inner;
|
|
789
|
+
}
|
|
790
|
+
const attributes = doc["attributes"];
|
|
791
|
+
const hasAttributes = typeof attributes === "object" && attributes !== null && Object.keys(attributes).length > 0;
|
|
792
|
+
if (!hasAttributes && !doc["overview"]) return null;
|
|
793
|
+
return { ...emptyLists(), profile: doc };
|
|
794
|
+
}
|
|
795
|
+
|
|
743
796
|
// src/context/fetch.ts
|
|
744
797
|
var ENDPOINT_BY_SCOPE = {
|
|
745
798
|
user: "context_fetch_user",
|
|
@@ -867,6 +920,12 @@ function retrievalOptionsOf(options) {
|
|
|
867
920
|
}
|
|
868
921
|
return { mode, precisionLevel };
|
|
869
922
|
}
|
|
923
|
+
function validateSearchQuery(searchQuery) {
|
|
924
|
+
if (searchQuery === void 0 || searchQuery === null) return;
|
|
925
|
+
if (!Array.isArray(searchQuery) || searchQuery.some((query) => typeof query !== "string")) {
|
|
926
|
+
throw new InvalidInputError("search_query must be an array of strings when provided");
|
|
927
|
+
}
|
|
928
|
+
}
|
|
870
929
|
async function fetchContext(transport, scope, options = {}, hooks = {}) {
|
|
871
930
|
const startedAt = Date.now();
|
|
872
931
|
await transport.ready?.();
|
|
@@ -877,7 +936,13 @@ async function fetchContext(transport, scope, options = {}, hooks = {}) {
|
|
|
877
936
|
const responseShape = responseShapeOf(options);
|
|
878
937
|
retrievalOptionsOf(options);
|
|
879
938
|
const { contextMode } = scopeOptionsOf(scope, options);
|
|
939
|
+
const searchQuery = opt(options, "search_query", "searchQuery");
|
|
940
|
+
validateSearchQuery(searchQuery);
|
|
880
941
|
const summaryMode = scope === "user" && contextMode === "conversation-summary";
|
|
942
|
+
if (!summaryMode && hooks.withoutQuery && !hasQuery(searchQuery)) {
|
|
943
|
+
const answer = await hooks.withoutQuery(scope, options);
|
|
944
|
+
if (answer !== null) return applyResponseShape(answer, responseShape);
|
|
945
|
+
}
|
|
881
946
|
const finish = (response2) => {
|
|
882
947
|
hooks.onResponse?.(scope, options, response2);
|
|
883
948
|
return response2;
|
|
@@ -1144,6 +1209,293 @@ function flattenContextItems(context) {
|
|
|
1144
1209
|
return items;
|
|
1145
1210
|
}
|
|
1146
1211
|
|
|
1212
|
+
// src/memories/parts.ts
|
|
1213
|
+
var OBJECTIVES = [
|
|
1214
|
+
"conversation",
|
|
1215
|
+
"bootstrap",
|
|
1216
|
+
"knowledge-base",
|
|
1217
|
+
"record",
|
|
1218
|
+
"profile"
|
|
1219
|
+
];
|
|
1220
|
+
var MAX_FILE_BYTES = 10 * 1024 * 1024;
|
|
1221
|
+
var MAX_STREAM_IMAGE_BYTES = 2.5 * 1024 * 1024;
|
|
1222
|
+
var URL_FETCH_TIMEOUT_MS = 3e4;
|
|
1223
|
+
var PART_BRAND = /* @__PURE__ */ Symbol.for("@maximem/synap-js-sdk.ContentPart");
|
|
1224
|
+
function brand(part) {
|
|
1225
|
+
Object.defineProperty(part, PART_BRAND, { value: true, enumerable: false });
|
|
1226
|
+
return part;
|
|
1227
|
+
}
|
|
1228
|
+
function isBranded(value) {
|
|
1229
|
+
return typeof value === "object" && value !== null && PART_BRAND in value;
|
|
1230
|
+
}
|
|
1231
|
+
function textPart(text) {
|
|
1232
|
+
if (typeof text !== "string") throw new 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
|
+
|
|
1147
1499
|
// src/memories/interface.ts
|
|
1148
1500
|
var DOCUMENT_TYPES = [
|
|
1149
1501
|
"ai-chat-conversation",
|
|
@@ -1167,12 +1519,11 @@ function isoOrNull(v) {
|
|
|
1167
1519
|
if (v === void 0 || v === null) return null;
|
|
1168
1520
|
return v instanceof Date ? v.toISOString() : v;
|
|
1169
1521
|
}
|
|
1170
|
-
function
|
|
1171
|
-
if (!options.document) throw new InvalidInputError("document is required");
|
|
1522
|
+
function createFields(options, defaultType) {
|
|
1172
1523
|
const o2 = options;
|
|
1173
|
-
const documentType = either(o2, "document_type", "documentType") ??
|
|
1524
|
+
const documentType = either(o2, "document_type", "documentType") ?? defaultType;
|
|
1174
1525
|
const mode = options.mode ?? DEFAULT_INGEST_MODE;
|
|
1175
|
-
if (!DOCUMENT_TYPES.includes(documentType)) {
|
|
1526
|
+
if (documentType !== null && !DOCUMENT_TYPES.includes(documentType)) {
|
|
1176
1527
|
throw new InvalidInputError(
|
|
1177
1528
|
`Invalid document_type '${documentType}'. Expected one of: ${DOCUMENT_TYPES.join(", ")}`
|
|
1178
1529
|
);
|
|
@@ -1182,22 +1533,70 @@ function buildCreateBody(options) {
|
|
|
1182
1533
|
`Invalid mode '${mode}'. Expected one of: ${INGEST_MODES.join(", ")}`
|
|
1183
1534
|
);
|
|
1184
1535
|
}
|
|
1185
|
-
|
|
1186
|
-
|
|
1536
|
+
const userId = either(o2, "user_id", "userId") ?? null;
|
|
1537
|
+
const customerId = either(o2, "customer_id", "customerId") ?? null;
|
|
1538
|
+
const fields = {
|
|
1187
1539
|
document_type: documentType,
|
|
1188
1540
|
document_id: either(o2, "document_id", "documentId") ?? null,
|
|
1189
1541
|
document_created_at: isoOrNull(
|
|
1190
1542
|
either(o2, "document_created_at", "documentCreatedAt")
|
|
1191
1543
|
),
|
|
1192
|
-
user_id:
|
|
1193
|
-
customer_id:
|
|
1544
|
+
user_id: userId,
|
|
1545
|
+
customer_id: customerId,
|
|
1194
1546
|
// null, never `{}`. An empty path is not absence: the server treats one as
|
|
1195
1547
|
// an error, because a caller asking to be narrowed and being ignored gets
|
|
1196
1548
|
// widened instead.
|
|
1197
|
-
scope: options.scope
|
|
1549
|
+
scope: normaliseCreateScope(options.scope, userId, customerId),
|
|
1198
1550
|
mode,
|
|
1199
1551
|
metadata: options.metadata ?? {}
|
|
1200
1552
|
};
|
|
1553
|
+
if (options.objective !== void 0 && options.objective !== null) {
|
|
1554
|
+
fields["objective"] = options.objective;
|
|
1555
|
+
}
|
|
1556
|
+
return fields;
|
|
1557
|
+
}
|
|
1558
|
+
function normaliseCreateScope(scope, userId, customerId) {
|
|
1559
|
+
if (scope === void 0 || scope === null) return null;
|
|
1560
|
+
const entries = Object.entries(scope);
|
|
1561
|
+
if (entries.length > 1 && entries.some(([, v]) => v === "self")) {
|
|
1562
|
+
throw new 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) };
|
|
1201
1600
|
}
|
|
1202
1601
|
var FORGET_MODES = ["preview", "direct"];
|
|
1203
1602
|
var FORGET_DESCRIPTION_MIN = 3;
|
|
@@ -1218,21 +1617,63 @@ function buildForgetBody(options) {
|
|
|
1218
1617
|
);
|
|
1219
1618
|
}
|
|
1220
1619
|
const o2 = options;
|
|
1221
|
-
|
|
1620
|
+
const body = {
|
|
1222
1621
|
description,
|
|
1223
1622
|
user_id: either(o2, "user_id", "userId") ?? null,
|
|
1224
1623
|
customer_id: either(o2, "customer_id", "customerId") ?? null,
|
|
1225
1624
|
scope: options.scope ?? null,
|
|
1226
1625
|
mode
|
|
1227
1626
|
};
|
|
1627
|
+
const conversationId = either(o2, "conversation_id", "conversationId");
|
|
1628
|
+
if (conversationId !== void 0 && conversationId !== null) {
|
|
1629
|
+
if (typeof conversationId !== "string" || [...conversationId].length < 1 || [...conversationId].length > 200) {
|
|
1630
|
+
throw new InvalidInputError("conversation_id must be a string of 1 to 200 characters");
|
|
1631
|
+
}
|
|
1632
|
+
body["conversation_id"] = conversationId;
|
|
1633
|
+
}
|
|
1634
|
+
return body;
|
|
1228
1635
|
}
|
|
1229
1636
|
var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "failed", "partial_success", "error", "cancelled"]);
|
|
1230
1637
|
function createMemoriesInterface(transport, onForgotten) {
|
|
1231
1638
|
return {
|
|
1232
1639
|
async create(options) {
|
|
1233
1640
|
const o2 = options;
|
|
1234
|
-
|
|
1235
|
-
|
|
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
|
+
});
|
|
1236
1677
|
},
|
|
1237
1678
|
async batch_create(options) {
|
|
1238
1679
|
const docs = options.documents;
|
|
@@ -1241,7 +1682,13 @@ function createMemoriesInterface(transport, onForgotten) {
|
|
|
1241
1682
|
}
|
|
1242
1683
|
const failFast = options.fail_fast ?? options.failFast ?? false;
|
|
1243
1684
|
return transport.request("memories_batch", {
|
|
1244
|
-
body: {
|
|
1685
|
+
body: {
|
|
1686
|
+
documents: docs.map((d) => {
|
|
1687
|
+
jsonDocument(d.document, "memories.batch_create");
|
|
1688
|
+
return buildCreateBody(d);
|
|
1689
|
+
}),
|
|
1690
|
+
fail_fast: failFast
|
|
1691
|
+
}
|
|
1245
1692
|
});
|
|
1246
1693
|
},
|
|
1247
1694
|
async create_from_file(options) {
|
|
@@ -1435,7 +1882,7 @@ function iso(v) {
|
|
|
1435
1882
|
if (v === void 0) return void 0;
|
|
1436
1883
|
return v instanceof Date ? v.toISOString() : v;
|
|
1437
1884
|
}
|
|
1438
|
-
function buildRecordMessageBody(options) {
|
|
1885
|
+
function buildRecordMessageBody(options, resolvedContent, field = "content") {
|
|
1439
1886
|
const o2 = options;
|
|
1440
1887
|
const conversationId = either2(o2, "conversation_id", "conversationId");
|
|
1441
1888
|
const userId = either2(o2, "user_id", "userId");
|
|
@@ -1450,10 +1897,22 @@ function buildRecordMessageBody(options) {
|
|
|
1450
1897
|
throw new InvalidInputError("content is required");
|
|
1451
1898
|
}
|
|
1452
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
|
+
}
|
|
1453
1912
|
const body = {
|
|
1454
1913
|
conversation_id: conversationId,
|
|
1455
1914
|
role: options.role,
|
|
1456
|
-
content
|
|
1915
|
+
content,
|
|
1457
1916
|
user_id: userId,
|
|
1458
1917
|
customer_id: customerId,
|
|
1459
1918
|
// Python always sends this, defaulting to {}.
|
|
@@ -1596,6 +2055,24 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
|
|
|
1596
2055
|
inFlight: writesInFlight.get(conversationId) ?? 0
|
|
1597
2056
|
};
|
|
1598
2057
|
};
|
|
2058
|
+
const fetchImpl = ((url, init) => transport.fetchExternal(url, init));
|
|
2059
|
+
const validateMessage = (options, field = "content") => {
|
|
2060
|
+
if (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
|
+
};
|
|
1599
2076
|
const convId = (v) => {
|
|
1600
2077
|
const id = typeof v === "string" ? v : v.conversation_id ?? v.conversationId;
|
|
1601
2078
|
if (!id) throw new InvalidInputError("conversation_id is required");
|
|
@@ -1608,7 +2085,9 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
|
|
|
1608
2085
|
options["customer_id"] ?? options["customerId"],
|
|
1609
2086
|
"conversation.record_message"
|
|
1610
2087
|
);
|
|
1611
|
-
const
|
|
2088
|
+
const prepared = await prepareMessage(options);
|
|
2089
|
+
const body = withTurnModel(prepared.body, options);
|
|
2090
|
+
const mirror = prepared.mirror;
|
|
1612
2091
|
const conversationId = String(body["conversation_id"] ?? "");
|
|
1613
2092
|
writeStarted(conversationId);
|
|
1614
2093
|
let result;
|
|
@@ -1620,7 +2099,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
|
|
|
1620
2099
|
onTurn({
|
|
1621
2100
|
conversationId,
|
|
1622
2101
|
role: String(body["role"] ?? "user"),
|
|
1623
|
-
content:
|
|
2102
|
+
content: mirror,
|
|
1624
2103
|
timestamp: body["timestamp"],
|
|
1625
2104
|
...confirmation(result, conversationId)
|
|
1626
2105
|
});
|
|
@@ -1641,7 +2120,11 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
|
|
|
1641
2120
|
"conversation.record_messages_batch"
|
|
1642
2121
|
);
|
|
1643
2122
|
}
|
|
1644
|
-
const
|
|
2123
|
+
const field = (i) => `messages[${i}].content`;
|
|
2124
|
+
messages.forEach((m, i) => validateMessage(m, field(i)));
|
|
2125
|
+
const prepared = await Promise.all(messages.map((m, i) => prepareMessage(m, field(i))));
|
|
2126
|
+
const bodies = prepared.map((p, i) => withTurnModel(p.body, messages[i]));
|
|
2127
|
+
const mirrors = new Map(prepared.map((p, i) => [bodies[i], p.mirror]));
|
|
1645
2128
|
const result = await transport.request("conversations_messages_batch", {
|
|
1646
2129
|
body: { messages: bodies }
|
|
1647
2130
|
});
|
|
@@ -1650,7 +2133,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
|
|
|
1650
2133
|
onTurn({
|
|
1651
2134
|
conversationId,
|
|
1652
2135
|
role: String(body["role"] ?? "user"),
|
|
1653
|
-
content: String(body["content"] ?? ""),
|
|
2136
|
+
content: mirrors.get(body) ?? String(body["content"] ?? ""),
|
|
1654
2137
|
timestamp: body["timestamp"],
|
|
1655
2138
|
...confirmation(row, conversationId)
|
|
1656
2139
|
});
|
|
@@ -1770,6 +2253,138 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
|
|
|
1770
2253
|
};
|
|
1771
2254
|
}
|
|
1772
2255
|
|
|
2256
|
+
// src/data/interface.ts
|
|
2257
|
+
var DATA_SCOPES = ["user", "conversation", "customer"];
|
|
2258
|
+
var MAX_WAIT_CALLS = 50;
|
|
2259
|
+
var ID_FIELD = {
|
|
2260
|
+
user: "user_id",
|
|
2261
|
+
customer: "customer_id",
|
|
2262
|
+
conversation: "conversation_id"
|
|
2263
|
+
};
|
|
2264
|
+
function either3(o2, snake, camel) {
|
|
2265
|
+
const a = o2[snake];
|
|
2266
|
+
if (a !== void 0) return a;
|
|
2267
|
+
const b = o2[camel];
|
|
2268
|
+
return b === void 0 ? void 0 : b;
|
|
2269
|
+
}
|
|
2270
|
+
function buildDeleteBody(options, instanceId) {
|
|
2271
|
+
const o2 = options;
|
|
2272
|
+
const scope = options.scope;
|
|
2273
|
+
if (scope !== null && typeof scope === "object") {
|
|
2274
|
+
throw new InvalidInputError(
|
|
2275
|
+
"scope must be one of: user, conversation, customer. A dict is not accepted here (the rung-path dict used by memories.create and fetch is a different parameter)."
|
|
2276
|
+
);
|
|
2277
|
+
}
|
|
2278
|
+
if (typeof scope !== "string" || !DATA_SCOPES.includes(scope)) {
|
|
2279
|
+
throw new InvalidInputError(
|
|
2280
|
+
`Invalid scope '${String(scope)}'. Expected one of: ${DATA_SCOPES.join(", ")}`
|
|
2281
|
+
);
|
|
2282
|
+
}
|
|
2283
|
+
const dryRun = either3(o2, "dry_run", "dryRun") ?? false;
|
|
2284
|
+
if (typeof dryRun !== "boolean") throw new InvalidInputError("dry_run must be a boolean");
|
|
2285
|
+
const ids = {
|
|
2286
|
+
user_id: either3(o2, "user_id", "userId"),
|
|
2287
|
+
customer_id: either3(o2, "customer_id", "customerId"),
|
|
2288
|
+
conversation_id: either3(o2, "conversation_id", "conversationId")
|
|
2289
|
+
};
|
|
2290
|
+
for (const [name, value] of Object.entries(ids)) {
|
|
2291
|
+
if (value !== void 0 && value !== null && (typeof value !== "string" || value.trim() === "")) {
|
|
2292
|
+
throw new InvalidInputError(`${name} must not be empty`);
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
const field = ID_FIELD[scope];
|
|
2296
|
+
const target = ids[field];
|
|
2297
|
+
if (target === void 0 || target === null) {
|
|
2298
|
+
throw new InvalidInputError(`${field} is required for scope='${scope}'`);
|
|
2299
|
+
}
|
|
2300
|
+
const confirm = options.confirm ?? null;
|
|
2301
|
+
if (!dryRun) {
|
|
2302
|
+
if (confirm === null || confirm === "") {
|
|
2303
|
+
throw new InvalidInputError(
|
|
2304
|
+
`confirm is required unless dry_run=True: pass the ${field} being deleted as confirm`
|
|
2305
|
+
);
|
|
2306
|
+
}
|
|
2307
|
+
if (confirm !== target) {
|
|
2308
|
+
throw new InvalidInputError(`confirm must equal the ${field} being deleted`);
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
return {
|
|
2312
|
+
scope,
|
|
2313
|
+
instance_id: instanceId,
|
|
2314
|
+
user_id: ids["user_id"] ?? null,
|
|
2315
|
+
customer_id: ids["customer_id"] ?? null,
|
|
2316
|
+
conversation_id: ids["conversation_id"] ?? null,
|
|
2317
|
+
dry_run: dryRun,
|
|
2318
|
+
confirm
|
|
2319
|
+
};
|
|
2320
|
+
}
|
|
2321
|
+
function normalise(raw) {
|
|
2322
|
+
return {
|
|
2323
|
+
deletion_id: null,
|
|
2324
|
+
status: "unknown",
|
|
2325
|
+
scope: null,
|
|
2326
|
+
dry_run: false,
|
|
2327
|
+
found: false,
|
|
2328
|
+
counts: {},
|
|
2329
|
+
stores: {},
|
|
2330
|
+
still_present_in: [],
|
|
2331
|
+
// Pessimistic: true only when the server said so.
|
|
2332
|
+
fully_removed: false,
|
|
2333
|
+
continue: false,
|
|
2334
|
+
kept: [],
|
|
2335
|
+
note: null,
|
|
2336
|
+
memories_kept: false,
|
|
2337
|
+
audit: null,
|
|
2338
|
+
local_cleared: [],
|
|
2339
|
+
...raw
|
|
2340
|
+
};
|
|
2341
|
+
}
|
|
2342
|
+
function createDataInterface(transport, onDeleted) {
|
|
2343
|
+
return {
|
|
2344
|
+
async delete(options) {
|
|
2345
|
+
const o2 = options;
|
|
2346
|
+
await transport.checkCustomerId(
|
|
2347
|
+
either3(o2, "customer_id", "customerId"),
|
|
2348
|
+
"data.delete"
|
|
2349
|
+
);
|
|
2350
|
+
const body = buildDeleteBody(options, transport.currentCredentials().instanceId);
|
|
2351
|
+
const dryRun = body["dry_run"] === true;
|
|
2352
|
+
const wait = options.wait ?? true;
|
|
2353
|
+
let result = null;
|
|
2354
|
+
for (let i = 0; i < (wait ? MAX_WAIT_CALLS : 1); i += 1) {
|
|
2355
|
+
result = normalise(
|
|
2356
|
+
await transport.request("data_delete", { body })
|
|
2357
|
+
);
|
|
2358
|
+
if (dryRun || !result.continue) break;
|
|
2359
|
+
}
|
|
2360
|
+
const final = result;
|
|
2361
|
+
if (!dryRun && ["complete", "partial", "in_progress"].includes(final.status) && onDeleted) {
|
|
2362
|
+
try {
|
|
2363
|
+
final.local_cleared = onDeleted({
|
|
2364
|
+
scope: body["scope"],
|
|
2365
|
+
userId: body["user_id"] ?? null,
|
|
2366
|
+
customerId: body["customer_id"] ?? null,
|
|
2367
|
+
conversationId: body["conversation_id"] ?? null
|
|
2368
|
+
});
|
|
2369
|
+
} catch {
|
|
2370
|
+
}
|
|
2371
|
+
}
|
|
2372
|
+
return final;
|
|
2373
|
+
},
|
|
2374
|
+
async status(deletionId) {
|
|
2375
|
+
if (typeof deletionId !== "string" || deletionId.trim() === "") {
|
|
2376
|
+
throw new InvalidInputError("deletion_id is required");
|
|
2377
|
+
}
|
|
2378
|
+
return normalise(
|
|
2379
|
+
await transport.request("data_delete_status", {
|
|
2380
|
+
pathParams: { deletion_id: deletionId },
|
|
2381
|
+
query: { instance_id: transport.currentCredentials().instanceId }
|
|
2382
|
+
})
|
|
2383
|
+
);
|
|
2384
|
+
}
|
|
2385
|
+
};
|
|
2386
|
+
}
|
|
2387
|
+
|
|
1773
2388
|
// src/user/interface.ts
|
|
1774
2389
|
function createUserNamespace(transport, hooks = {}) {
|
|
1775
2390
|
return {
|
|
@@ -1847,6 +2462,7 @@ function createCacheNamespace(cache) {
|
|
|
1847
2462
|
}
|
|
1848
2463
|
|
|
1849
2464
|
// src/instance/interface.ts
|
|
2465
|
+
var CONTENT_PARTS_METADATA_KEY = "synap_content_parts";
|
|
1850
2466
|
var DEFAULT_GRPC_HOST = "synap-cloud-prod.maximem.ai";
|
|
1851
2467
|
var DEFAULT_GRPC_PORT = 443;
|
|
1852
2468
|
function envPort() {
|
|
@@ -1902,8 +2518,15 @@ function jsonOrText(value) {
|
|
|
1902
2518
|
}
|
|
1903
2519
|
}
|
|
1904
2520
|
}
|
|
1905
|
-
function createInstanceNamespace(credentials, cache, onTurn,
|
|
1906
|
-
|
|
2521
|
+
function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel, agentModelOrToolResult, onToolResultOrCheck, checkCustomerIdArg) {
|
|
2522
|
+
const defaultFetch = ((url, init) => globalThis.fetch(url, init));
|
|
2523
|
+
const imageFirst = fetchOrAgentModel !== void 0 && (fetchOrAgentModel.length > 0 || agentModelOrToolResult === void 0);
|
|
2524
|
+
const fetchUrl2 = imageFirst ? fetchOrAgentModel : defaultFetch;
|
|
2525
|
+
const agentModel = (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;
|
|
1907
2530
|
let client = null;
|
|
1908
2531
|
const openSessions = /* @__PURE__ */ new Map();
|
|
1909
2532
|
let dispatchCompaction = null;
|
|
@@ -1953,6 +2576,25 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
|
|
|
1953
2576
|
} catch {
|
|
1954
2577
|
}
|
|
1955
2578
|
}
|
|
2579
|
+
let tail = Promise.resolve();
|
|
2580
|
+
let queued = 0;
|
|
2581
|
+
function inOrder(prepared, send, sync) {
|
|
2582
|
+
if (prepared === null && queued === 0) {
|
|
2583
|
+
send(sync);
|
|
2584
|
+
return Promise.resolve();
|
|
2585
|
+
}
|
|
2586
|
+
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
|
+
}
|
|
1956
2598
|
const namespace = {
|
|
1957
2599
|
async listen(options = {}) {
|
|
1958
2600
|
if (client !== null) {
|
|
@@ -1962,7 +2604,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
|
|
|
1962
2604
|
onListen?.();
|
|
1963
2605
|
} catch {
|
|
1964
2606
|
}
|
|
1965
|
-
const { GrpcStreamClient } = await import("./stream-client-
|
|
2607
|
+
const { GrpcStreamClient } = await import("./stream-client-JKFBVZPN.js");
|
|
1966
2608
|
const onContext = options.on_context ?? options.onContext;
|
|
1967
2609
|
const onDisconnect = options.on_disconnect ?? options.onDisconnect;
|
|
1968
2610
|
const onReconnect = options.on_reconnect ?? options.onReconnect;
|
|
@@ -2026,10 +2668,12 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
|
|
|
2026
2668
|
}
|
|
2027
2669
|
},
|
|
2028
2670
|
async send_message(options) {
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2671
|
+
if (hasCustomerIdCheck) {
|
|
2672
|
+
await checkCustomerId3(
|
|
2673
|
+
options.customer_id ?? options.customerId,
|
|
2674
|
+
"instance.send_message"
|
|
2675
|
+
);
|
|
2676
|
+
}
|
|
2033
2677
|
if (client === null) throw new ListeningNotActiveError("Listening is not active");
|
|
2034
2678
|
const eventType = options.event_type ?? options.eventType ?? "user_message";
|
|
2035
2679
|
if (!KNOWN_EVENT_TYPES.has(eventType)) {
|
|
@@ -2040,46 +2684,68 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
|
|
|
2040
2684
|
if (options.content === void 0 || options.content === null) {
|
|
2041
2685
|
throw new InvalidInputError("content is required");
|
|
2042
2686
|
}
|
|
2043
|
-
const
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
options.
|
|
2047
|
-
|
|
2048
|
-
);
|
|
2049
|
-
if (eventType === "user_message" || eventType === "assistant_message") {
|
|
2050
|
-
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(
|
|
2051
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,
|
|
2052
2706
|
role: options.role ?? "user",
|
|
2053
|
-
|
|
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
|
+
})()
|
|
2054
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 ?? {} });
|
|
2055
2732
|
}
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
tool_result_json: toolResultJson(options.tool_result ?? options.toolResult),
|
|
2073
|
-
tool_call_id: options.tool_call_id ?? options.toolCallId ?? "",
|
|
2074
|
-
search_queries: options.search_queries ?? options.searchQueries ?? [],
|
|
2075
|
-
context_types: options.context_types ?? options.contextTypes ?? [],
|
|
2076
|
-
// The proto's `scope`: the conversation's rung, kept from the first
|
|
2077
|
-
// event that names one. Omitted when absent or empty, as in Python.
|
|
2078
|
-
...(() => {
|
|
2079
|
-
const sp = options.scope_path ?? options.scopePath;
|
|
2080
|
-
return sp && Object.keys(sp).length > 0 ? { scope: sp } : {};
|
|
2081
|
-
})()
|
|
2082
|
-
});
|
|
2733
|
+
const prepared = (async () => {
|
|
2734
|
+
const inline = await toInlineParts(parts.parts, fetchUrl2);
|
|
2735
|
+
if (inline.rawBytes > MAX_STREAM_IMAGE_BYTES) {
|
|
2736
|
+
throw new 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);
|
|
2083
2749
|
},
|
|
2084
2750
|
async record_tool_call(options) {
|
|
2085
2751
|
await namespace.send_message({
|
|
@@ -2123,24 +2789,27 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
|
|
|
2123
2789
|
options.user_id ?? options.userId ?? "",
|
|
2124
2790
|
options.customer_id ?? options.customerId ?? ""
|
|
2125
2791
|
);
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
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);
|
|
2144
2813
|
},
|
|
2145
2814
|
get is_listening() {
|
|
2146
2815
|
return client !== null && client.isConnected;
|
|
@@ -2151,7 +2820,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
|
|
|
2151
2820
|
}
|
|
2152
2821
|
|
|
2153
2822
|
// src/version.ts
|
|
2154
|
-
var SDK_VERSION = "0.6.
|
|
2823
|
+
var SDK_VERSION = "0.6.6";
|
|
2155
2824
|
|
|
2156
2825
|
// src/registry.ts
|
|
2157
2826
|
var instances = /* @__PURE__ */ new Map();
|
|
@@ -3283,7 +3952,7 @@ function pick2(item, ...names) {
|
|
|
3283
3952
|
}
|
|
3284
3953
|
return void 0;
|
|
3285
3954
|
}
|
|
3286
|
-
function
|
|
3955
|
+
function normalise2(item) {
|
|
3287
3956
|
const content = pick2(item, "content") ?? "";
|
|
3288
3957
|
const confidence = pick2(item, "confidence") ?? 0;
|
|
3289
3958
|
const extractedAt = pick2(item, "extracted_at", "created_at") ?? null;
|
|
@@ -3318,7 +3987,7 @@ function mergeUserSummary(response, bundle) {
|
|
|
3318
3987
|
if (!Array.isArray(items)) continue;
|
|
3319
3988
|
const existing = response[collection] ?? [];
|
|
3320
3989
|
const existingIds = new Set(existing.map((i) => String(i.id ?? i.item_id ?? "")));
|
|
3321
|
-
const fresh = items.filter((i) => typeof i === "object" && i !== null && !existingIds.has(itemId(i))).slice(0, MAX_SUMMARY_ITEMS).map(
|
|
3990
|
+
const fresh = items.filter((i) => typeof i === "object" && i !== null && !existingIds.has(itemId(i))).slice(0, MAX_SUMMARY_ITEMS).map(normalise2);
|
|
3322
3991
|
if (fresh.length === 0) continue;
|
|
3323
3992
|
response[collection] = [...existing, ...fresh];
|
|
3324
3993
|
}
|
|
@@ -3327,16 +3996,16 @@ function mergeUserSummary(response, bundle) {
|
|
|
3327
3996
|
|
|
3328
3997
|
// src/context/anticipated.ts
|
|
3329
3998
|
function scopeLookupParams(scope, params) {
|
|
3330
|
-
const { searchQuery, entityId, customerId, clientId, conversationId, scopeRung } = params;
|
|
3999
|
+
const { searchQuery, entityId, customerId, clientId, conversationId, scopeRung, maxResultsPerQuery } = params;
|
|
3331
4000
|
switch (scope) {
|
|
3332
4001
|
case "conversation":
|
|
3333
|
-
return { searchQuery, entityId, customerId, clientId, conversationId, scopeRung };
|
|
4002
|
+
return { searchQuery, entityId, customerId, clientId, conversationId, scopeRung, maxResultsPerQuery };
|
|
3334
4003
|
case "user":
|
|
3335
|
-
return { searchQuery, entityId, customerId, clientId, scopeRung };
|
|
4004
|
+
return { searchQuery, entityId, customerId, clientId, scopeRung, maxResultsPerQuery };
|
|
3336
4005
|
case "customer":
|
|
3337
|
-
return { searchQuery, entityId: null, customerId, clientId, scopeRung };
|
|
4006
|
+
return { searchQuery, entityId: null, customerId, clientId, scopeRung, maxResultsPerQuery };
|
|
3338
4007
|
case "client":
|
|
3339
|
-
return { searchQuery, entityId: null, customerId: null, clientId, scopeRung };
|
|
4008
|
+
return { searchQuery, entityId: null, customerId: null, clientId, scopeRung, maxResultsPerQuery };
|
|
3340
4009
|
}
|
|
3341
4010
|
}
|
|
3342
4011
|
function buildAnticipationResponse(hit) {
|
|
@@ -3372,7 +4041,8 @@ async function tryServeFromCache(cache, scope, params, maxItems) {
|
|
|
3372
4041
|
clientId: scoped.clientId ?? null,
|
|
3373
4042
|
conversationId: scoped.conversationId ?? null,
|
|
3374
4043
|
scopeRung: scoped.scopeRung ?? null,
|
|
3375
|
-
maxItems
|
|
4044
|
+
maxItems,
|
|
4045
|
+
maxResultsPerQuery: scoped.maxResultsPerQuery ?? null
|
|
3376
4046
|
});
|
|
3377
4047
|
if (hit === null) return { response: null, hit: null };
|
|
3378
4048
|
return { response: buildAnticipationResponse(hit), hit };
|
|
@@ -3872,6 +4542,7 @@ var SynapClient = class _SynapClient {
|
|
|
3872
4542
|
client;
|
|
3873
4543
|
conversation;
|
|
3874
4544
|
memories;
|
|
4545
|
+
data;
|
|
3875
4546
|
credits;
|
|
3876
4547
|
cache;
|
|
3877
4548
|
instance;
|
|
@@ -3934,7 +4605,6 @@ var SynapClient = class _SynapClient {
|
|
|
3934
4605
|
beforeFetch: async (scope, options2) => {
|
|
3935
4606
|
const o2 = options2;
|
|
3936
4607
|
if (o2["query_date"] ?? o2["queryDate"]) return null;
|
|
3937
|
-
if (o2["max_results_per_query"] ?? o2["maxResultsPerQuery"]) return null;
|
|
3938
4608
|
const attempt = await tryServeFromCache(
|
|
3939
4609
|
this.#anticipationCache,
|
|
3940
4610
|
scope,
|
|
@@ -3951,7 +4621,8 @@ var SynapClient = class _SynapClient {
|
|
|
3951
4621
|
// process and invisible to every server log.
|
|
3952
4622
|
scopeRung: rungKey(
|
|
3953
4623
|
o2["scope_path"] ?? o2["scopePath"]
|
|
3954
|
-
)
|
|
4624
|
+
),
|
|
4625
|
+
maxResultsPerQuery: o2["max_results_per_query"] ?? o2["maxResultsPerQuery"] ?? null
|
|
3955
4626
|
},
|
|
3956
4627
|
Number(o2["max_results"] ?? o2["maxResults"] ?? 10)
|
|
3957
4628
|
);
|
|
@@ -3977,6 +4648,30 @@ var SynapClient = class _SynapClient {
|
|
|
3977
4648
|
// Python's `_should_skip_server_st`: when this process already holds the
|
|
3978
4649
|
// conversation's compaction and every turn after it, the server is told
|
|
3979
4650
|
// not to assemble them again.
|
|
4651
|
+
// A fetch with no query, as Python answers it inside the two scoped
|
|
4652
|
+
// fetches: the conversation's state, or the user's profile when there
|
|
4653
|
+
// is one. A profile read that fails falls back to the fetch as before.
|
|
4654
|
+
withoutQuery: async (scope, options2) => {
|
|
4655
|
+
const o2 = options2;
|
|
4656
|
+
if (scope === "conversation") {
|
|
4657
|
+
const id = o2["conversation_id"] ?? o2["conversationId"];
|
|
4658
|
+
const prompt = await this.conversation.context.get_context_for_prompt({ conversation_id: id });
|
|
4659
|
+
return conversationStateContext(prompt, id);
|
|
4660
|
+
}
|
|
4661
|
+
if (scope === "user") {
|
|
4662
|
+
try {
|
|
4663
|
+
const customerId = o2["customer_id"] ?? o2["customerId"];
|
|
4664
|
+
const profile = await this.user.get_profile({
|
|
4665
|
+
user_id: o2["user_id"] ?? o2["userId"],
|
|
4666
|
+
...customerId !== void 0 ? { customer_id: customerId } : {}
|
|
4667
|
+
});
|
|
4668
|
+
return profileContext(profile);
|
|
4669
|
+
} catch {
|
|
4670
|
+
return null;
|
|
4671
|
+
}
|
|
4672
|
+
}
|
|
4673
|
+
return null;
|
|
4674
|
+
},
|
|
3980
4675
|
skipServerShortTerm: (conversationId) => {
|
|
3981
4676
|
if (!this.#isStAuthoritative()) return false;
|
|
3982
4677
|
const entry = this.#shortTerm.get(conversationId);
|
|
@@ -4057,6 +4752,22 @@ var SynapClient = class _SynapClient {
|
|
|
4057
4752
|
if (id) this.#anticipationCache.dropEntity(id);
|
|
4058
4753
|
}
|
|
4059
4754
|
});
|
|
4755
|
+
this.data = createDataInterface(this.#transport, ({ scope, userId, customerId, conversationId }) => {
|
|
4756
|
+
const cleared = [];
|
|
4757
|
+
if (scope === "conversation") {
|
|
4758
|
+
if (conversationId) {
|
|
4759
|
+
this.#shortTerm.invalidate(conversationId);
|
|
4760
|
+
this.#turnStore.drop(conversationId);
|
|
4761
|
+
cleared.push("short_term_context", "turns");
|
|
4762
|
+
}
|
|
4763
|
+
} else {
|
|
4764
|
+
for (const id of new Set(scope === "user" ? [userId, customerId] : [customerId])) {
|
|
4765
|
+
if (id) this.#anticipationCache.dropEntity(id);
|
|
4766
|
+
}
|
|
4767
|
+
cleared.push("anticipation_cache");
|
|
4768
|
+
}
|
|
4769
|
+
return cleared;
|
|
4770
|
+
});
|
|
4060
4771
|
this.credits = createCreditsNamespace(this.#transport);
|
|
4061
4772
|
this.cache = createCacheNamespace(this.#anticipationCache);
|
|
4062
4773
|
this.instance = createInstanceNamespace(
|
|
@@ -4065,6 +4776,8 @@ var SynapClient = class _SynapClient {
|
|
|
4065
4776
|
({ conversationId, role, content }) => {
|
|
4066
4777
|
this.#shortTerm.appendTurn(conversationId, role, content);
|
|
4067
4778
|
},
|
|
4779
|
+
// A FilePart given by url is read with the same fetch as everything else.
|
|
4780
|
+
((url, init) => this.#transport.fetchExternal(url, init)),
|
|
4068
4781
|
() => this.#agentModel,
|
|
4069
4782
|
({ conversationId, result, toolName }) => this.archive_tool_result(conversationId, result, { tool_name: toolName }),
|
|
4070
4783
|
(customerId, where) => this.#transport.checkCustomerId(customerId, where)
|
|
@@ -4312,7 +5025,9 @@ var SynapClient = class _SynapClient {
|
|
|
4312
5025
|
const labels = [];
|
|
4313
5026
|
const tasks = [];
|
|
4314
5027
|
const present = (v) => v !== void 0 && v !== null && v !== "";
|
|
4315
|
-
|
|
5028
|
+
const conversationState = present(conversationId) && contextMode !== "conversation-summary" && !hasQuery(searchQuery) && wants("conversation");
|
|
5029
|
+
const withConversationContext = includeConversationContext;
|
|
5030
|
+
if (present(conversationId) && wants("conversation") && !conversationState) {
|
|
4316
5031
|
labels.push("conversation");
|
|
4317
5032
|
tasks.push(this.conversation.context.fetch({
|
|
4318
5033
|
conversation_id: conversationId,
|
|
@@ -4348,7 +5063,7 @@ var SynapClient = class _SynapClient {
|
|
|
4348
5063
|
...shared
|
|
4349
5064
|
}));
|
|
4350
5065
|
}
|
|
4351
|
-
if (tasks.length === 0) {
|
|
5066
|
+
if (tasks.length === 0 && !(conversationState && includeConversationContext)) {
|
|
4352
5067
|
const empty = mergeScopeResults([]);
|
|
4353
5068
|
return empty;
|
|
4354
5069
|
}
|
|
@@ -4367,17 +5082,20 @@ var SynapClient = class _SynapClient {
|
|
|
4367
5082
|
for (const [, response] of successful) {
|
|
4368
5083
|
overlayLocalRecentTurns(response, this.#shortTerm, conversationId, this.#stVerbatimOverlay);
|
|
4369
5084
|
}
|
|
4370
|
-
if (
|
|
5085
|
+
if (withConversationContext && present(conversationId)) {
|
|
4371
5086
|
try {
|
|
4372
5087
|
merged.conversation_context = await this.conversation.context.get_context_for_prompt({
|
|
4373
5088
|
conversation_id: conversationId
|
|
4374
5089
|
});
|
|
5090
|
+
if (conversationState && !merged.scopes_queried.includes("conversation")) {
|
|
5091
|
+
merged.scopes_queried.unshift("conversation");
|
|
5092
|
+
}
|
|
4375
5093
|
} catch {
|
|
4376
5094
|
}
|
|
4377
5095
|
}
|
|
4378
5096
|
merged.formatted_context = formatForPrompt(merged, {
|
|
4379
5097
|
includeScope: includeScopeLabels,
|
|
4380
|
-
includeConversationContext
|
|
5098
|
+
includeConversationContext: withConversationContext
|
|
4381
5099
|
});
|
|
4382
5100
|
return merged;
|
|
4383
5101
|
}
|
|
@@ -4402,13 +5120,13 @@ var SynapClient = class _SynapClient {
|
|
|
4402
5120
|
/**
|
|
4403
5121
|
* Report a locally served fetch back to the server.
|
|
4404
5122
|
*
|
|
4405
|
-
*
|
|
4406
|
-
*
|
|
4407
|
-
*
|
|
5123
|
+
* It rides the Listen stream. While the stream is reconnecting the stream
|
|
5124
|
+
* client holds it and sends it on reconnect: a hit never reaches a fetch
|
|
5125
|
+
* route, so this report is the only count of it. Never throws, because a
|
|
5126
|
+
* telemetry failure must not fail a retrieval that already succeeded.
|
|
4408
5127
|
*/
|
|
4409
5128
|
#emitContextUsed(options, scope, served) {
|
|
4410
5129
|
try {
|
|
4411
|
-
if (!this.instance.is_listening) return;
|
|
4412
5130
|
this.instance._internal.sendContextUsed({
|
|
4413
5131
|
bundle_id: served.bundleId,
|
|
4414
5132
|
conversation_id: String(options["conversation_id"] ?? options["conversationId"] ?? ""),
|
|
@@ -4665,7 +5383,7 @@ function resolveBaseUrl(options) {
|
|
|
4665
5383
|
return fromEnv !== void 0 && fromEnv !== "" ? fromEnv : void 0;
|
|
4666
5384
|
}
|
|
4667
5385
|
function resolveCredentials(options) {
|
|
4668
|
-
const apiKey = options.apiKey
|
|
5386
|
+
const apiKey = options.apiKey || getEnv("SYNAP_API_KEY");
|
|
4669
5387
|
if (!apiKey) {
|
|
4670
5388
|
throw new AuthenticationError(
|
|
4671
5389
|
"No Synap API key found. Set SYNAP_API_KEY in your environment, or pass apiKey to the SynapClient constructor."
|
|
@@ -4689,6 +5407,7 @@ export {
|
|
|
4689
5407
|
ConnectionError,
|
|
4690
5408
|
ContextNotFoundError,
|
|
4691
5409
|
CustomerIdNotAcceptedError,
|
|
5410
|
+
DATA_SCOPES,
|
|
4692
5411
|
DEFAULT_BASE_URL,
|
|
4693
5412
|
DEFAULT_DOCUMENT_TYPE,
|
|
4694
5413
|
DEFAULT_INGEST_MODE,
|
|
@@ -4711,6 +5430,7 @@ export {
|
|
|
4711
5430
|
ListeningNotActiveError,
|
|
4712
5431
|
MEMORY_TYPES,
|
|
4713
5432
|
NetworkTimeoutError,
|
|
5433
|
+
OBJECTIVES,
|
|
4714
5434
|
PermanentError,
|
|
4715
5435
|
RESPONSE_SHAPES,
|
|
4716
5436
|
RateLimitError,
|
|
@@ -4726,16 +5446,17 @@ export {
|
|
|
4726
5446
|
TranscriptConflictError,
|
|
4727
5447
|
TransientError,
|
|
4728
5448
|
applyResponseShape,
|
|
5449
|
+
filePart,
|
|
4729
5450
|
flattenContextItems,
|
|
4730
5451
|
formatForPrompt,
|
|
4731
5452
|
isOutcomeUnknown,
|
|
4732
|
-
isRecallQuery,
|
|
4733
5453
|
isSynapError,
|
|
4734
5454
|
mergeScopeResults,
|
|
4735
5455
|
rankItems,
|
|
4736
5456
|
resolvePath,
|
|
4737
5457
|
shouldRetry,
|
|
4738
5458
|
stem,
|
|
5459
|
+
textPart,
|
|
4739
5460
|
tokenize,
|
|
4740
5461
|
wireRankScore
|
|
4741
5462
|
};
|