@maximem/synap-js-sdk 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6,10 +6,11 @@ import {
6
6
  HISTORY_SEARCH,
7
7
  SEMANTIC_MATCH,
8
8
  THRESHOLDS,
9
+ normalizeConversationId,
9
10
  rungKey,
10
11
  stem,
11
12
  tokenize
12
- } from "./chunk-CSG3N5E3.js";
13
+ } from "./chunk-W6AH4CPC.js";
13
14
  import {
14
15
  getEnv
15
16
  } from "./chunk-QBCVMPGK.js";
@@ -66,6 +67,7 @@ var ENDPOINTS = {
66
67
  memories_delete: { method: "DELETE", path: "/api/v1/memories/{memory_id}", idempotent: true },
67
68
  memories_forget: { method: "POST", path: "/api/v1/memories/forget", idempotent: false },
68
69
  data_delete: { method: "POST", path: "/v1/data/delete", idempotent: true },
70
+ data_restore: { method: "POST", path: "/v1/data/restore", idempotent: true },
69
71
  data_delete_status: { method: "GET", path: "/v1/data/delete/{deletion_id}", idempotent: true },
70
72
  context_fetch_user: { method: "POST", path: "/v1/context/user/fetch", idempotent: true },
71
73
  context_fetch_customer: { method: "POST", path: "/v1/context/customer/fetch", idempotent: true },
@@ -2129,13 +2131,28 @@ function createMemoriesInterface(transport, onForgotten) {
2129
2131
  body
2130
2132
  });
2131
2133
  },
2132
- async delete(memoryId) {
2134
+ async delete(memoryId, options) {
2135
+ const permanent = options?.permanent ?? false;
2136
+ if (typeof permanent !== "boolean") throw new InvalidInputError("permanent must be a boolean");
2133
2137
  if (!memoryId) {
2134
2138
  throw new InvalidInputError(
2135
2139
  "memory_id is required. Deleting by user is no longer supported: the previous implementation tracked ids in process memory, so it silently deleted nothing in any serverless or multi-process deployment while reporting success."
2136
2140
  );
2137
2141
  }
2138
- return transport.request("memories_delete", { pathParams: { memory_id: memoryId } });
2142
+ const r = await transport.request("memories_delete", {
2143
+ pathParams: { memory_id: memoryId },
2144
+ ...permanent ? { query: { permanent: "true" } } : {}
2145
+ });
2146
+ return {
2147
+ memory_id: String(r?.["memory_id"] ?? memoryId),
2148
+ deleted_at: String(r?.["deleted_at"] ?? ""),
2149
+ fully_removed: r?.["fully_removed"] === true,
2150
+ still_present_in: Array.isArray(r?.["still_present_in"]) ? r["still_present_in"] : [],
2151
+ source_text_kept: r?.["source_text_kept"] === true,
2152
+ status: typeof r?.["status"] === "string" && r["status"] ? r["status"] : "complete",
2153
+ purge_after: typeof r?.["purge_after"] === "string" ? r["purge_after"] : null,
2154
+ permanent: r?.["permanent"] === true
2155
+ };
2139
2156
  },
2140
2157
  async forget(options) {
2141
2158
  const o2 = options;
@@ -2339,6 +2356,7 @@ function buildCompactBody(options) {
2339
2356
  var CompactionSubscribers = class {
2340
2357
  #byConversation = /* @__PURE__ */ new Map();
2341
2358
  add(conversationId, callback) {
2359
+ conversationId = normalizeConversationId(conversationId);
2342
2360
  const list = this.#byConversation.get(conversationId);
2343
2361
  if (list === void 0) this.#byConversation.set(conversationId, [callback]);
2344
2362
  else list.push(callback);
@@ -2354,6 +2372,7 @@ var CompactionSubscribers = class {
2354
2372
  };
2355
2373
  }
2356
2374
  removeAll(conversationId) {
2375
+ if (conversationId !== void 0) conversationId = normalizeConversationId(conversationId);
2357
2376
  if (conversationId === void 0) {
2358
2377
  let count = 0;
2359
2378
  for (const list2 of this.#byConversation.values()) count += list2.length;
@@ -2367,6 +2386,7 @@ var CompactionSubscribers = class {
2367
2386
  }
2368
2387
  /** Fires subscribers in registration order. A throwing listener must not break the stream reader. */
2369
2388
  dispatch(conversationId, bundle, onError) {
2389
+ conversationId = normalizeConversationId(conversationId);
2370
2390
  for (const callback of [...this.#byConversation.get(conversationId) ?? []]) {
2371
2391
  try {
2372
2392
  const result = callback(bundle);
@@ -2629,6 +2649,7 @@ var ID_FIELD = {
2629
2649
  customer: "customer_id",
2630
2650
  conversation: "conversation_id"
2631
2651
  };
2652
+ var MAX_RESTORE_IDS = 200;
2632
2653
  function either3(o2, snake, camel) {
2633
2654
  const a = o2[snake];
2634
2655
  if (a !== void 0) return a;
@@ -2676,15 +2697,39 @@ function buildDeleteBody(options, instanceId) {
2676
2697
  throw new InvalidInputError(`confirm must equal the ${field} being deleted`);
2677
2698
  }
2678
2699
  }
2679
- return {
2700
+ const instances2 = options.instances === void 0 || options.instances === null ? null : checkInstances(options.instances);
2701
+ const permanent = options.permanent ?? false;
2702
+ if (typeof permanent !== "boolean") throw new InvalidInputError("permanent must be a boolean");
2703
+ const body = {
2680
2704
  scope,
2681
- instance_id: instanceId,
2705
+ // Without `instances` the body is byte-identical to earlier versions.
2706
+ instance_id: instances2 === null ? instanceId : null,
2682
2707
  user_id: ids["user_id"] ?? null,
2683
2708
  customer_id: ids["customer_id"] ?? null,
2684
2709
  conversation_id: ids["conversation_id"] ?? null,
2685
2710
  dry_run: dryRun,
2686
2711
  confirm
2687
2712
  };
2713
+ if (instances2 !== null) body["instance_ids"] = instances2;
2714
+ if (permanent) body["permanent"] = true;
2715
+ return body;
2716
+ }
2717
+ function checkInstances(instances2) {
2718
+ if (instances2 === "all") return "all";
2719
+ if (!Array.isArray(instances2)) {
2720
+ throw new InvalidInputError('instances must be "all" or a list of instance ids');
2721
+ }
2722
+ const out = [];
2723
+ for (const i of instances2) {
2724
+ if (typeof i !== "string" || i.trim() === "") {
2725
+ throw new InvalidInputError("instances must not contain an empty instance id");
2726
+ }
2727
+ if (!out.includes(i.trim())) out.push(i.trim());
2728
+ }
2729
+ if (out.length === 0) {
2730
+ throw new InvalidInputError('instances is empty: name at least one instance, or "all"');
2731
+ }
2732
+ return out;
2688
2733
  }
2689
2734
  function normalise(raw) {
2690
2735
  return {
@@ -2700,13 +2745,43 @@ function normalise(raw) {
2700
2745
  fully_removed: false,
2701
2746
  continue: false,
2702
2747
  kept: [],
2748
+ not_covered: [],
2703
2749
  note: null,
2704
2750
  memories_kept: false,
2705
2751
  audit: null,
2706
2752
  local_cleared: [],
2753
+ instances: [],
2754
+ not_started: [],
2755
+ deletion_ids: [],
2756
+ purge_after: null,
2707
2757
  ...raw
2708
2758
  };
2709
2759
  }
2760
+ function buildRestoreBody(memoryIds, instanceId, deletionId = null) {
2761
+ const noIds = memoryIds === null || memoryIds === void 0;
2762
+ const noDeletion = deletionId === null || deletionId === void 0;
2763
+ if (noIds === noDeletion) {
2764
+ throw new InvalidInputError("send exactly one of memory_ids or deletion_id");
2765
+ }
2766
+ if (!noDeletion) {
2767
+ if (typeof deletionId !== "string" || deletionId.trim() === "") {
2768
+ throw new InvalidInputError("deletion_id must not be empty");
2769
+ }
2770
+ return { deletion_id: deletionId.trim(), instance_id: instanceId };
2771
+ }
2772
+ if (typeof memoryIds === "string" || !Array.isArray(memoryIds)) {
2773
+ throw new InvalidInputError("memory_ids must be a list of memory ids");
2774
+ }
2775
+ const ids = memoryIds.map((i) => String(i));
2776
+ if (ids.length === 0) throw new InvalidInputError("memory_ids must not be empty");
2777
+ if (ids.length > MAX_RESTORE_IDS) {
2778
+ throw new InvalidInputError("at most " + String(MAX_RESTORE_IDS) + " memory_ids per call");
2779
+ }
2780
+ if (ids.some((i) => i.trim() === "")) {
2781
+ throw new InvalidInputError("memory_ids must not contain empty ids");
2782
+ }
2783
+ return { memory_ids: ids, instance_id: instanceId };
2784
+ }
2710
2785
  function createDataInterface(transport, onDeleted) {
2711
2786
  return {
2712
2787
  async delete(options) {
@@ -2726,7 +2801,7 @@ function createDataInterface(transport, onDeleted) {
2726
2801
  if (dryRun || !result.continue) break;
2727
2802
  }
2728
2803
  const final = result;
2729
- if (!dryRun && ["complete", "partial", "in_progress"].includes(final.status) && onDeleted) {
2804
+ if (!dryRun && ["complete", "pending_purge", "partial", "in_progress"].includes(final.status) && onDeleted) {
2730
2805
  try {
2731
2806
  final.local_cleared = onDeleted({
2732
2807
  scope: body["scope"],
@@ -2749,6 +2824,29 @@ function createDataInterface(transport, onDeleted) {
2749
2824
  query: { instance_id: transport.currentCredentials().instanceId }
2750
2825
  })
2751
2826
  );
2827
+ },
2828
+ async restore(target) {
2829
+ const instanceId = transport.currentCredentials().instanceId;
2830
+ let body;
2831
+ if (Array.isArray(target) || typeof target === "string" || target === null || target === void 0) {
2832
+ body = buildRestoreBody(target, instanceId);
2833
+ } else {
2834
+ const o2 = target;
2835
+ body = buildRestoreBody(
2836
+ either3(o2, "memory_ids", "memoryIds") ?? null,
2837
+ instanceId,
2838
+ either3(o2, "deletion_id", "deletionId") ?? null
2839
+ );
2840
+ }
2841
+ const raw = await transport.request("data_restore", { body });
2842
+ return {
2843
+ restored_ids: [],
2844
+ not_restorable_ids: [],
2845
+ still_missing_in: [],
2846
+ reindexed_ids: [],
2847
+ fully_restored: false,
2848
+ ...raw
2849
+ };
2752
2850
  }
2753
2851
  };
2754
2852
  }
@@ -2994,9 +3092,18 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2994
3092
  return client !== null && client.isConnected;
2995
3093
  }
2996
3094
  };
3095
+ function openSessionKey(conversationId) {
3096
+ if (!conversationId) return void 0;
3097
+ if (openSessions.has(conversationId)) return conversationId;
3098
+ const wanted = normalizeConversationId(conversationId);
3099
+ for (const key of openSessions.keys()) {
3100
+ if (normalizeConversationId(key) === wanted) return key;
3101
+ }
3102
+ return void 0;
3103
+ }
2997
3104
  function ensureSession(conversationId, userId, customerId) {
2998
3105
  if (!conversationId || !userId || client === null) return;
2999
- if (openSessions.has(conversationId)) return;
3106
+ if (openSessionKey(conversationId) !== void 0) return;
3000
3107
  const sessionId = newCorrelationId();
3001
3108
  try {
3002
3109
  client.sendSessionControl({
@@ -3090,9 +3197,10 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
3090
3197
  await active.disconnect();
3091
3198
  },
3092
3199
  async end_session(conversationId) {
3093
- const sessionId = openSessions.get(conversationId);
3094
- if (sessionId === void 0 || client === null) return;
3095
- openSessions.delete(conversationId);
3200
+ const openedAs = openSessionKey(conversationId);
3201
+ const sessionId = openedAs === void 0 ? void 0 : openSessions.get(openedAs);
3202
+ if (openedAs === void 0 || sessionId === void 0 || client === null) return;
3203
+ openSessions.delete(openedAs);
3096
3204
  try {
3097
3205
  client.sendSessionControl({
3098
3206
  action: "end",
@@ -3142,7 +3250,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
3142
3250
  conversation_id: options.conversation_id ?? options.conversationId ?? "",
3143
3251
  user_id: options.user_id ?? options.userId ?? "",
3144
3252
  customer_id: options.customer_id ?? options.customerId ?? "",
3145
- session_id: options.session_id ?? options.sessionId ?? openSessions.get(conversationId) ?? "",
3253
+ session_id: options.session_id ?? options.sessionId ?? openSessions.get(openSessionKey(conversationId) ?? "") ?? "",
3146
3254
  metadata: withAgentModel(metadata, agentModelOf(options), agentModel(), true) ?? {},
3147
3255
  timestamp_ms: Date.now(),
3148
3256
  tool_name: options.tool_name ?? options.toolName ?? "",
@@ -3255,7 +3363,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
3255
3363
  }
3256
3364
 
3257
3365
  // src/version.ts
3258
- var SDK_VERSION = "0.7.1";
3366
+ var SDK_VERSION = "0.8.0";
3259
3367
 
3260
3368
  // src/registry.ts
3261
3369
  var instances = /* @__PURE__ */ new Map();
@@ -3363,6 +3471,7 @@ var ShortTermStore = class {
3363
3471
  /** The entry, or null. Age-evicts on read, as Python does. */
3364
3472
  get(conversationId) {
3365
3473
  if (!conversationId) return null;
3474
+ conversationId = normalizeConversationId(conversationId);
3366
3475
  const entry = this.#entries.get(conversationId);
3367
3476
  if (entry === void 0) return null;
3368
3477
  if (this.#now() - entry.lastActivityAt > this.#maxAgeMs) {
@@ -3391,6 +3500,7 @@ var ShortTermStore = class {
3391
3500
  */
3392
3501
  appendTurn(conversationId, role, content, timestamp, confirmation = {}) {
3393
3502
  if (!conversationId) return;
3503
+ conversationId = normalizeConversationId(conversationId);
3394
3504
  const stamp = timestamp ?? new Date(this.#now()).toISOString();
3395
3505
  if (this.#archive !== null) {
3396
3506
  try {
@@ -3424,6 +3534,7 @@ var ShortTermStore = class {
3424
3534
  */
3425
3535
  noteServerCount(conversationId, count) {
3426
3536
  if (!conversationId) return;
3537
+ conversationId = normalizeConversationId(conversationId);
3427
3538
  const entry = this.#entries.get(conversationId);
3428
3539
  if (entry !== void 0) this.#noteCount(entry, Number(count), 0);
3429
3540
  }
@@ -3471,10 +3582,11 @@ var ShortTermStore = class {
3471
3582
  applyCompaction(bundle) {
3472
3583
  if (typeof bundle !== "object" || bundle === null) return;
3473
3584
  const cc = bundle["conversation_context"] ?? {};
3474
- const conversationId = String(
3585
+ const rawConversationId = String(
3475
3586
  cc["conversation_id"] ?? bundle["anticipation_conversation_id"] ?? bundle["conversation_id"] ?? ""
3476
3587
  );
3477
- if (!conversationId) return;
3588
+ if (!rawConversationId) return;
3589
+ const conversationId = normalizeConversationId(rawConversationId);
3478
3590
  const endTs = parseIso(cc["end_timestamp"] ?? cc["compacted_at"]);
3479
3591
  const compactedAt = parseIso(cc["compacted_at"]);
3480
3592
  const compactedCount = Number(cc["compacted_message_count"] ?? 0) || 0;
@@ -3539,6 +3651,7 @@ var ShortTermStore = class {
3539
3651
  */
3540
3652
  reseed(conversationId, state) {
3541
3653
  if (!conversationId) return;
3654
+ conversationId = normalizeConversationId(conversationId);
3542
3655
  const entry = this.#entries.get(conversationId);
3543
3656
  if (entry === void 0 || entry.shared) return;
3544
3657
  entry.serverMessageCount = Math.max(
@@ -3555,7 +3668,7 @@ var ShortTermStore = class {
3555
3668
  entry.synced = true;
3556
3669
  }
3557
3670
  invalidate(conversationId) {
3558
- this.#entries.delete(conversationId);
3671
+ this.#entries.delete(normalizeConversationId(conversationId));
3559
3672
  }
3560
3673
  clear() {
3561
3674
  this.#entries.clear();
@@ -4356,7 +4469,7 @@ var TurnCounter = class {
4356
4469
  #counts = /* @__PURE__ */ new Map();
4357
4470
  /** Increment and return the new count. Python buckets a missing id under `_global`. */
4358
4471
  increment(conversationId) {
4359
- const key = conversationId !== void 0 && conversationId !== "" ? conversationId : "_global";
4472
+ const key = conversationId !== void 0 && conversationId !== "" ? normalizeConversationId(conversationId) : "_global";
4360
4473
  const next = (this.#counts.get(key) ?? 0) + 1;
4361
4474
  this.#counts.set(key, next);
4362
4475
  return next;
@@ -4369,7 +4482,7 @@ var TurnCounter = class {
4369
4482
  * triggered a fresh retrieval anyway.
4370
4483
  */
4371
4484
  shouldInject(conversationId) {
4372
- const key = conversationId !== void 0 && conversationId !== "" ? conversationId : "_global";
4485
+ const key = conversationId !== void 0 && conversationId !== "" ? normalizeConversationId(conversationId) : "_global";
4373
4486
  const count = this.#counts.get(key) ?? 0;
4374
4487
  return count > 0 && count % USER_SUMMARY_INTERVAL === 0;
4375
4488
  }
@@ -5216,7 +5329,7 @@ var SynapClient = class _SynapClient {
5216
5329
  if (scope === "conversation") {
5217
5330
  if (conversationId) {
5218
5331
  this.#shortTerm.invalidate(conversationId);
5219
- this.#turnStore.drop(conversationId);
5332
+ this.#turnStore.drop(normalizeConversationId(conversationId));
5220
5333
  cleared.push("short_term_context", "turns");
5221
5334
  }
5222
5335
  } else {
@@ -5735,6 +5848,7 @@ var SynapClient = class _SynapClient {
5735
5848
  async #withHistoryExcerpts(conversationId, response, query) {
5736
5849
  const r = response ?? {};
5737
5850
  const store = this.#turnStore;
5851
+ conversationId = normalizeConversationId(conversationId);
5738
5852
  const recent = Array.isArray(r["recent_messages"]) ? r["recent_messages"] : [];
5739
5853
  store.addMany(
5740
5854
  conversationId,
@@ -5782,7 +5896,7 @@ var SynapClient = class _SynapClient {
5782
5896
  if (!conversationId || result === null || result === void 0) return;
5783
5897
  try {
5784
5898
  this.#turnStore.add(
5785
- conversationId,
5899
+ normalizeConversationId(conversationId),
5786
5900
  "tool",
5787
5901
  toolResultText(result, options.tool_name ?? options.toolName),
5788
5902
  options.timestamp ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -5812,6 +5926,7 @@ var SynapClient = class _SynapClient {
5812
5926
  });
5813
5927
  }
5814
5928
  #maybeBackfillTurns(conversationId, total) {
5929
+ conversationId = normalizeConversationId(conversationId);
5815
5930
  if (total <= this.#turnStore.count(conversationId)) return;
5816
5931
  const now = Date.now();
5817
5932
  if (now < (this.#backfillAfter.get(conversationId) ?? 0)) return;
@@ -5819,6 +5934,7 @@ var SynapClient = class _SynapClient {
5819
5934
  void this.#backfillTurns(conversationId, total);
5820
5935
  }
5821
5936
  async #backfillTurns(conversationId, total) {
5937
+ conversationId = normalizeConversationId(conversationId);
5822
5938
  try {
5823
5939
  let start = 1;
5824
5940
  while (start <= total) {
@@ -5947,6 +6063,7 @@ export {
5947
6063
  InvalidInstanceIdError,
5948
6064
  ListeningAlreadyActiveError,
5949
6065
  ListeningNotActiveError,
6066
+ MAX_RESTORE_IDS,
5950
6067
  MEMORY_TYPES,
5951
6068
  NetworkTimeoutError,
5952
6069
  OBJECTIVES,