@anuma/sdk 1.1.4 → 1.1.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.
@@ -1291,50 +1291,85 @@ async function getMessagesPageOp(ctx, convId, opts) {
1291
1291
  )
1292
1292
  );
1293
1293
  }
1294
- async function getMessageSkeletonsOp(ctx, convId) {
1295
- const results = await ctx.messagesCollection.query(Q.where("conversation_id", convId), Q.sortBy("message_id", Q.asc)).fetch();
1296
- const roleById = /* @__PURE__ */ new Map();
1297
- for (const msg of results) {
1298
- roleById.set(msg.id, msg.role);
1299
- }
1300
- const skeletons = results.map((msg) => ({
1301
- uniqueId: msg.id,
1302
- messageId: msg.messageId,
1303
- conversationId: String(msg._getRaw("conversation_id")),
1304
- role: msg.role,
1305
- createdAt: msg.createdAt,
1306
- // WatermelonDB surfaces unset text columns as null at runtime — normalize
1307
- // to undefined so `parentMessageId ?? undefined` keying works everywhere.
1308
- parentMessageId: msg.parentMessageId ?? void 0,
1309
- model: msg.model ?? void 0
1310
- }));
1311
- const artifactIndices = [];
1312
- for (let i = 0; i < results.length; i++) {
1313
- const msg = results[i];
1314
- if (msg.role !== "user" || !msg.parentMessageId) continue;
1315
- if (roleById.get(msg.parentMessageId) === "user") {
1316
- artifactIndices.push(i);
1294
+ var SKELETON_PAGE_SIZE = 2e3;
1295
+ function narrowSkeletonRow(raw) {
1296
+ return {
1297
+ id: raw.id,
1298
+ message_id: raw.message_id,
1299
+ conversation_id: raw.conversation_id,
1300
+ role: raw.role,
1301
+ created_at: raw.created_at,
1302
+ parent_message_id: raw.parent_message_id ?? null,
1303
+ model: raw.model ?? null,
1304
+ content: raw.content ?? null
1305
+ };
1306
+ }
1307
+ async function fetchThreadSkeletonRawPaged(collection, convId, pageSize = SKELETON_PAGE_SIZE) {
1308
+ const all = [];
1309
+ let cursor;
1310
+ for (; ; ) {
1311
+ const clauses = [Q.where("conversation_id", convId)];
1312
+ if (cursor) {
1313
+ clauses.push(
1314
+ Q.or(
1315
+ Q.where("message_id", Q.gt(cursor.messageId)),
1316
+ Q.and(Q.where("message_id", cursor.messageId), Q.where("id", Q.gt(cursor.id)))
1317
+ )
1318
+ );
1317
1319
  }
1320
+ const page = await collection.query(...clauses, Q.sortBy("message_id", Q.asc), Q.sortBy("id", Q.asc), Q.take(pageSize)).unsafeFetchRaw();
1321
+ if (page.length === 0) break;
1322
+ for (const raw of page) all.push(narrowSkeletonRow(raw));
1323
+ if (page.length < pageSize) break;
1324
+ const last = all[all.length - 1];
1325
+ cursor = { messageId: last.message_id, id: last.id };
1318
1326
  }
1327
+ return all;
1328
+ }
1329
+ function collectArtifactIndices(rows, roleById) {
1330
+ const indices = [];
1331
+ for (let i = 0; i < rows.length; i++) {
1332
+ const row = rows[i];
1333
+ if (row.role !== "user" || !row.parent_message_id) continue;
1334
+ if (roleById.get(row.parent_message_id) === "user") indices.push(i);
1335
+ }
1336
+ return indices;
1337
+ }
1338
+ async function decryptArtifactContent(skeletons, rows, artifactIndices, ctx) {
1319
1339
  const address = ctx.walletAddress;
1320
- if (artifactIndices.length > 0 && address) {
1321
- if (ctx.signMessage) {
1322
- try {
1323
- await requestEncryptionKey(address, ctx.signMessage, ctx.embeddedWalletSigner);
1324
- } catch (error) {
1325
- getLogger().warn("Failed to request encryption key for skeleton decryption:", error);
1326
- }
1327
- }
1328
- await Promise.all(
1329
- artifactIndices.map(async (i) => {
1330
- skeletons[i].content = await decryptField(results[i].content, address);
1331
- })
1332
- );
1333
- } else {
1334
- for (const i of artifactIndices) {
1335
- skeletons[i].content = results[i].content;
1340
+ if (artifactIndices.length === 0 || !address) {
1341
+ for (const i of artifactIndices) skeletons[i].content = rows[i].content ?? void 0;
1342
+ return;
1343
+ }
1344
+ if (ctx.signMessage) {
1345
+ try {
1346
+ await requestEncryptionKey(address, ctx.signMessage, ctx.embeddedWalletSigner);
1347
+ } catch (error) {
1348
+ getLogger().warn("Failed to request encryption key for skeleton decryption:", error);
1336
1349
  }
1337
1350
  }
1351
+ await Promise.all(
1352
+ artifactIndices.map(async (i) => {
1353
+ skeletons[i].content = await decryptField(rows[i].content ?? "", address);
1354
+ })
1355
+ );
1356
+ }
1357
+ async function getMessageSkeletonsOp(ctx, convId) {
1358
+ const rows = await fetchThreadSkeletonRawPaged(ctx.messagesCollection, convId);
1359
+ const roleById = /* @__PURE__ */ new Map();
1360
+ for (const row of rows) roleById.set(row.id, row.role);
1361
+ const skeletons = rows.map((row) => ({
1362
+ uniqueId: row.id,
1363
+ messageId: row.message_id,
1364
+ conversationId: String(row.conversation_id),
1365
+ role: row.role,
1366
+ createdAt: new Date(row.created_at),
1367
+ // WatermelonDB surfaces unset text columns as null at runtime — normalize
1368
+ // to undefined so `parentMessageId ?? undefined` keying works everywhere.
1369
+ parentMessageId: row.parent_message_id ?? void 0,
1370
+ model: row.model ?? void 0
1371
+ }));
1372
+ await decryptArtifactContent(skeletons, rows, collectArtifactIndices(rows, roleById), ctx);
1338
1373
  return skeletons;
1339
1374
  }
1340
1375
  async function clearMessagesOp(ctx, convId) {
@@ -3501,6 +3536,20 @@ async function withEmbeddingRetry(call) {
3501
3536
  if (threw) throw lastThrown;
3502
3537
  return last;
3503
3538
  }
3539
+ var EmbeddingHttpError = class extends Error {
3540
+ constructor(message, status) {
3541
+ super(message);
3542
+ this.name = "EmbeddingHttpError";
3543
+ this.status = status;
3544
+ }
3545
+ };
3546
+ function isFatalEmbeddingError(err) {
3547
+ return err instanceof EmbeddingHttpError && (err.status === 401 || err.status === 402 || err.status === 403);
3548
+ }
3549
+ function embeddingErrorFrom(response) {
3550
+ const message = typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed";
3551
+ return new EmbeddingHttpError(message, response.response?.status);
3552
+ }
3504
3553
  async function generateEmbedding(text, options) {
3505
3554
  const { baseUrl = BASE_URL, getToken, apiKey, model, cache } = options;
3506
3555
  if (cache) {
@@ -3532,9 +3581,7 @@ async function generateEmbedding(text, options) {
3532
3581
  })
3533
3582
  );
3534
3583
  if (response.error) {
3535
- throw new Error(
3536
- typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed"
3537
- );
3584
+ throw embeddingErrorFrom(response);
3538
3585
  }
3539
3586
  if (!response.data?.data?.[0]?.embedding) {
3540
3587
  throw new Error("No embedding returned from API");
@@ -3563,9 +3610,7 @@ async function generateEmbeddingsBatch(texts, headers, baseUrl, model, onUsage,
3563
3610
  })
3564
3611
  );
3565
3612
  if (response.error) {
3566
- throw new Error(
3567
- typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed"
3568
- );
3613
+ throw embeddingErrorFrom(response);
3569
3614
  }
3570
3615
  if (!response.data?.data) {
3571
3616
  throw new Error("No embeddings returned from API");
@@ -3701,6 +3746,7 @@ async function embedAllMessages(ctx, options, filter) {
3701
3746
  await updateMessageEmbeddingOp(ctx, message.uniqueId, embedding, embeddingModel);
3702
3747
  embeddedCount++;
3703
3748
  } catch (error) {
3749
+ if (isFatalEmbeddingError(error)) throw error;
3704
3750
  getLogger().error(`Failed to embed message ${message.uniqueId}:`, error);
3705
3751
  }
3706
3752
  }
@@ -3788,6 +3834,7 @@ async function chunkAndEmbedAllMessages(ctx, options, filter) {
3788
3834
  }
3789
3835
  }
3790
3836
  } catch (error) {
3837
+ if (isFatalEmbeddingError(error)) throw error;
3791
3838
  getLogger().error("Failed to batch-embed short messages:", error);
3792
3839
  }
3793
3840
  }
@@ -3804,6 +3851,7 @@ async function chunkAndEmbedAllMessages(ctx, options, filter) {
3804
3851
  await updateMessageChunksOp(ctx, msg.uniqueId, messageChunks, embeddingModel);
3805
3852
  embeddedCount++;
3806
3853
  } catch (error) {
3854
+ if (isFatalEmbeddingError(error)) throw error;
3807
3855
  getLogger().error(`Failed to embed message ${msg.uniqueId}:`, error);
3808
3856
  }
3809
3857
  }
@@ -4998,7 +5046,7 @@ function createMemoryVaultSearchTool(vaultCtx, embeddingOptions, cache, searchOp
4998
5046
  legacy.map((r) => ({ id: r.uniqueId, content: r.content, score: r.similarity }))
4999
5047
  );
5000
5048
  }
5001
- const { recall: recall2 } = await import("./recall-6AQ4WFJO.mjs");
5049
+ const { recall: recall2 } = await import("./recall-RGKS2OIP.mjs");
5002
5050
  const result = await recall2(
5003
5051
  query,
5004
5052
  { vaultCtx, embeddingOptions, vaultCache: cache },
@@ -2468,50 +2468,84 @@ async function getMessagesPageOp(ctx, convId, opts) {
2468
2468
  )
2469
2469
  );
2470
2470
  }
2471
- async function getMessageSkeletonsOp(ctx, convId) {
2472
- const results = await ctx.messagesCollection.query(import_watermelondb.Q.where("conversation_id", convId), import_watermelondb.Q.sortBy("message_id", import_watermelondb.Q.asc)).fetch();
2473
- const roleById = /* @__PURE__ */ new Map();
2474
- for (const msg of results) {
2475
- roleById.set(msg.id, msg.role);
2476
- }
2477
- const skeletons = results.map((msg) => ({
2478
- uniqueId: msg.id,
2479
- messageId: msg.messageId,
2480
- conversationId: String(msg._getRaw("conversation_id")),
2481
- role: msg.role,
2482
- createdAt: msg.createdAt,
2483
- // WatermelonDB surfaces unset text columns as null at runtime — normalize
2484
- // to undefined so `parentMessageId ?? undefined` keying works everywhere.
2485
- parentMessageId: msg.parentMessageId ?? void 0,
2486
- model: msg.model ?? void 0
2487
- }));
2488
- const artifactIndices = [];
2489
- for (let i = 0; i < results.length; i++) {
2490
- const msg = results[i];
2491
- if (msg.role !== "user" || !msg.parentMessageId) continue;
2492
- if (roleById.get(msg.parentMessageId) === "user") {
2493
- artifactIndices.push(i);
2471
+ function narrowSkeletonRow(raw) {
2472
+ return {
2473
+ id: raw.id,
2474
+ message_id: raw.message_id,
2475
+ conversation_id: raw.conversation_id,
2476
+ role: raw.role,
2477
+ created_at: raw.created_at,
2478
+ parent_message_id: raw.parent_message_id ?? null,
2479
+ model: raw.model ?? null,
2480
+ content: raw.content ?? null
2481
+ };
2482
+ }
2483
+ async function fetchThreadSkeletonRawPaged(collection, convId, pageSize = SKELETON_PAGE_SIZE) {
2484
+ const all = [];
2485
+ let cursor;
2486
+ for (; ; ) {
2487
+ const clauses = [import_watermelondb.Q.where("conversation_id", convId)];
2488
+ if (cursor) {
2489
+ clauses.push(
2490
+ import_watermelondb.Q.or(
2491
+ import_watermelondb.Q.where("message_id", import_watermelondb.Q.gt(cursor.messageId)),
2492
+ import_watermelondb.Q.and(import_watermelondb.Q.where("message_id", cursor.messageId), import_watermelondb.Q.where("id", import_watermelondb.Q.gt(cursor.id)))
2493
+ )
2494
+ );
2494
2495
  }
2496
+ const page = await collection.query(...clauses, import_watermelondb.Q.sortBy("message_id", import_watermelondb.Q.asc), import_watermelondb.Q.sortBy("id", import_watermelondb.Q.asc), import_watermelondb.Q.take(pageSize)).unsafeFetchRaw();
2497
+ if (page.length === 0) break;
2498
+ for (const raw of page) all.push(narrowSkeletonRow(raw));
2499
+ if (page.length < pageSize) break;
2500
+ const last = all[all.length - 1];
2501
+ cursor = { messageId: last.message_id, id: last.id };
2495
2502
  }
2503
+ return all;
2504
+ }
2505
+ function collectArtifactIndices(rows, roleById) {
2506
+ const indices = [];
2507
+ for (let i = 0; i < rows.length; i++) {
2508
+ const row = rows[i];
2509
+ if (row.role !== "user" || !row.parent_message_id) continue;
2510
+ if (roleById.get(row.parent_message_id) === "user") indices.push(i);
2511
+ }
2512
+ return indices;
2513
+ }
2514
+ async function decryptArtifactContent(skeletons, rows, artifactIndices, ctx) {
2496
2515
  const address = ctx.walletAddress;
2497
- if (artifactIndices.length > 0 && address) {
2498
- if (ctx.signMessage) {
2499
- try {
2500
- await requestEncryptionKey(address, ctx.signMessage, ctx.embeddedWalletSigner);
2501
- } catch (error) {
2502
- getLogger().warn("Failed to request encryption key for skeleton decryption:", error);
2503
- }
2504
- }
2505
- await Promise.all(
2506
- artifactIndices.map(async (i) => {
2507
- skeletons[i].content = await decryptField(results[i].content, address);
2508
- })
2509
- );
2510
- } else {
2511
- for (const i of artifactIndices) {
2512
- skeletons[i].content = results[i].content;
2516
+ if (artifactIndices.length === 0 || !address) {
2517
+ for (const i of artifactIndices) skeletons[i].content = rows[i].content ?? void 0;
2518
+ return;
2519
+ }
2520
+ if (ctx.signMessage) {
2521
+ try {
2522
+ await requestEncryptionKey(address, ctx.signMessage, ctx.embeddedWalletSigner);
2523
+ } catch (error) {
2524
+ getLogger().warn("Failed to request encryption key for skeleton decryption:", error);
2513
2525
  }
2514
2526
  }
2527
+ await Promise.all(
2528
+ artifactIndices.map(async (i) => {
2529
+ skeletons[i].content = await decryptField(rows[i].content ?? "", address);
2530
+ })
2531
+ );
2532
+ }
2533
+ async function getMessageSkeletonsOp(ctx, convId) {
2534
+ const rows = await fetchThreadSkeletonRawPaged(ctx.messagesCollection, convId);
2535
+ const roleById = /* @__PURE__ */ new Map();
2536
+ for (const row of rows) roleById.set(row.id, row.role);
2537
+ const skeletons = rows.map((row) => ({
2538
+ uniqueId: row.id,
2539
+ messageId: row.message_id,
2540
+ conversationId: String(row.conversation_id),
2541
+ role: row.role,
2542
+ createdAt: new Date(row.created_at),
2543
+ // WatermelonDB surfaces unset text columns as null at runtime — normalize
2544
+ // to undefined so `parentMessageId ?? undefined` keying works everywhere.
2545
+ parentMessageId: row.parent_message_id ?? void 0,
2546
+ model: row.model ?? void 0
2547
+ }));
2548
+ await decryptArtifactContent(skeletons, rows, collectArtifactIndices(rows, roleById), ctx);
2515
2549
  return skeletons;
2516
2550
  }
2517
2551
  async function clearMessagesOp(ctx, convId) {
@@ -2902,7 +2936,7 @@ function makeSyntheticStoredConversation(opts, defaultTitle) {
2902
2936
  isDeleted: false
2903
2937
  };
2904
2938
  }
2905
- var import_watermelondb, import_uuid2;
2939
+ var import_watermelondb, import_uuid2, SKELETON_PAGE_SIZE;
2906
2940
  var init_operations = __esm({
2907
2941
  "src/lib/db/chat/operations.ts"() {
2908
2942
  "use strict";
@@ -2915,6 +2949,7 @@ var init_operations = __esm({
2915
2949
  init_conversationEncryption();
2916
2950
  init_encryption();
2917
2951
  init_types2();
2952
+ SKELETON_PAGE_SIZE = 2e3;
2918
2953
  }
2919
2954
  });
2920
2955
 
@@ -3093,6 +3128,13 @@ async function withEmbeddingRetry(call) {
3093
3128
  if (threw) throw lastThrown;
3094
3129
  return last;
3095
3130
  }
3131
+ function isFatalEmbeddingError(err) {
3132
+ return err instanceof EmbeddingHttpError && (err.status === 401 || err.status === 402 || err.status === 403);
3133
+ }
3134
+ function embeddingErrorFrom(response) {
3135
+ const message = typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed";
3136
+ return new EmbeddingHttpError(message, response.response?.status);
3137
+ }
3096
3138
  async function generateEmbedding(text11, options) {
3097
3139
  const { baseUrl = BASE_URL, getToken, apiKey, model, cache } = options;
3098
3140
  if (cache) {
@@ -3124,9 +3166,7 @@ async function generateEmbedding(text11, options) {
3124
3166
  })
3125
3167
  );
3126
3168
  if (response.error) {
3127
- throw new Error(
3128
- typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed"
3129
- );
3169
+ throw embeddingErrorFrom(response);
3130
3170
  }
3131
3171
  if (!response.data?.data?.[0]?.embedding) {
3132
3172
  throw new Error("No embedding returned from API");
@@ -3153,9 +3193,7 @@ async function generateEmbeddingsBatch(texts, headers, baseUrl, model, onUsage,
3153
3193
  })
3154
3194
  );
3155
3195
  if (response.error) {
3156
- throw new Error(
3157
- typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed"
3158
- );
3196
+ throw embeddingErrorFrom(response);
3159
3197
  }
3160
3198
  if (!response.data?.data) {
3161
3199
  throw new Error("No embeddings returned from API");
@@ -3291,6 +3329,7 @@ async function embedAllMessages(ctx, options, filter) {
3291
3329
  await updateMessageEmbeddingOp(ctx, message.uniqueId, embedding, embeddingModel);
3292
3330
  embeddedCount++;
3293
3331
  } catch (error) {
3332
+ if (isFatalEmbeddingError(error)) throw error;
3294
3333
  getLogger().error(`Failed to embed message ${message.uniqueId}:`, error);
3295
3334
  }
3296
3335
  }
@@ -3378,6 +3417,7 @@ async function chunkAndEmbedAllMessages(ctx, options, filter) {
3378
3417
  }
3379
3418
  }
3380
3419
  } catch (error) {
3420
+ if (isFatalEmbeddingError(error)) throw error;
3381
3421
  getLogger().error("Failed to batch-embed short messages:", error);
3382
3422
  }
3383
3423
  }
@@ -3394,12 +3434,13 @@ async function chunkAndEmbedAllMessages(ctx, options, filter) {
3394
3434
  await updateMessageChunksOp(ctx, msg.uniqueId, messageChunks, embeddingModel);
3395
3435
  embeddedCount++;
3396
3436
  } catch (error) {
3437
+ if (isFatalEmbeddingError(error)) throw error;
3397
3438
  getLogger().error(`Failed to embed message ${msg.uniqueId}:`, error);
3398
3439
  }
3399
3440
  }
3400
3441
  return embeddedCount;
3401
3442
  }
3402
- var DEFAULT_MIN_CONTENT_LENGTH, EMBED_MAX_ATTEMPTS, DEFAULT_EMBEDDING_BATCH_SIZE, DEFAULT_EMBEDDING_BATCH_CONCURRENCY;
3443
+ var DEFAULT_MIN_CONTENT_LENGTH, EMBED_MAX_ATTEMPTS, EmbeddingHttpError, DEFAULT_EMBEDDING_BATCH_SIZE, DEFAULT_EMBEDDING_BATCH_CONCURRENCY;
3403
3444
  var init_embeddings = __esm({
3404
3445
  "src/lib/memoryEngine/embeddings.ts"() {
3405
3446
  "use strict";
@@ -3411,6 +3452,13 @@ var init_embeddings = __esm({
3411
3452
  init_constants();
3412
3453
  DEFAULT_MIN_CONTENT_LENGTH = 10;
3413
3454
  EMBED_MAX_ATTEMPTS = 4;
3455
+ EmbeddingHttpError = class extends Error {
3456
+ constructor(message, status) {
3457
+ super(message);
3458
+ this.name = "EmbeddingHttpError";
3459
+ this.status = status;
3460
+ }
3461
+ };
3414
3462
  DEFAULT_EMBEDDING_BATCH_SIZE = 100;
3415
3463
  DEFAULT_EMBEDDING_BATCH_CONCURRENCY = 3;
3416
3464
  }
@@ -19928,6 +19976,7 @@ var DatabaseManager = class {
19928
19976
  from: this.currentWalletAddress,
19929
19977
  to: walletAddress
19930
19978
  });
19979
+ void this.disposeAdapter(this.database);
19931
19980
  this.database = null;
19932
19981
  }
19933
19982
  if (this.database) {
@@ -19957,11 +20006,37 @@ var DatabaseManager = class {
19957
20006
  async resetDatabase() {
19958
20007
  const db = this.database;
19959
20008
  if (db) {
20009
+ this.database = null;
20010
+ this.currentWalletAddress = void 0;
19960
20011
  await db.write(async () => {
19961
20012
  await db.unsafeResetDatabase();
19962
20013
  });
19963
- this.database = null;
19964
- this.currentWalletAddress = void 0;
20014
+ await this.disposeAdapter(db);
20015
+ }
20016
+ }
20017
+ /**
20018
+ * Best-effort dispose of the adapter backing a Database, if it exposes one.
20019
+ *
20020
+ * OPFS/SQLite adapters use this to terminate their dedicated worker and release
20021
+ * the exclusive SAHPool (+ WASM heap) they hold. The SDK only sees a generic
20022
+ * `DatabaseAdapter`, so we probe `adapter.underlyingAdapter.dispose` rather than
20023
+ * type it. Client-side implementations are refcounted + idempotent, so calling
20024
+ * this is safe even when the adapter factory also disposes.
20025
+ *
20026
+ * Awaitable and never rejects: a sync throw or async rejection from `dispose`
20027
+ * is caught + logged. Awaited on the async `resetDatabase` path so teardown
20028
+ * completes before the caller reopens; fire-and-forget on the synchronous
20029
+ * `getDatabase` path (which cannot block).
20030
+ */
20031
+ async disposeAdapter(db) {
20032
+ try {
20033
+ const underlying = db.adapter?.underlyingAdapter;
20034
+ await underlying?.dispose?.();
20035
+ } catch (error) {
20036
+ this.logger.warn?.("Adapter dispose failed", {
20037
+ component: "DatabaseManager",
20038
+ error
20039
+ });
19965
20040
  }
19966
20041
  }
19967
20042
  /**
@@ -8103,6 +8103,21 @@ declare class DatabaseManager {
8103
8103
  * Reset the current database (useful for logout or testing).
8104
8104
  */
8105
8105
  resetDatabase(): Promise<void>;
8106
+ /**
8107
+ * Best-effort dispose of the adapter backing a Database, if it exposes one.
8108
+ *
8109
+ * OPFS/SQLite adapters use this to terminate their dedicated worker and release
8110
+ * the exclusive SAHPool (+ WASM heap) they hold. The SDK only sees a generic
8111
+ * `DatabaseAdapter`, so we probe `adapter.underlyingAdapter.dispose` rather than
8112
+ * type it. Client-side implementations are refcounted + idempotent, so calling
8113
+ * this is safe even when the adapter factory also disposes.
8114
+ *
8115
+ * Awaitable and never rejects: a sync throw or async rejection from `dispose`
8116
+ * is caught + logged. Awaited on the async `resetDatabase` path so teardown
8117
+ * completes before the caller reopens; fire-and-forget on the synchronous
8118
+ * `getDatabase` path (which cannot block).
8119
+ */
8120
+ private disposeAdapter;
8106
8121
  /**
8107
8122
  * Check and handle schema migrations for a specific wallet.
8108
8123
  * Returns true if a destructive migration is in progress.
@@ -8103,6 +8103,21 @@ declare class DatabaseManager {
8103
8103
  * Reset the current database (useful for logout or testing).
8104
8104
  */
8105
8105
  resetDatabase(): Promise<void>;
8106
+ /**
8107
+ * Best-effort dispose of the adapter backing a Database, if it exposes one.
8108
+ *
8109
+ * OPFS/SQLite adapters use this to terminate their dedicated worker and release
8110
+ * the exclusive SAHPool (+ WASM heap) they hold. The SDK only sees a generic
8111
+ * `DatabaseAdapter`, so we probe `adapter.underlyingAdapter.dispose` rather than
8112
+ * type it. Client-side implementations are refcounted + idempotent, so calling
8113
+ * this is safe even when the adapter factory also disposes.
8114
+ *
8115
+ * Awaitable and never rejects: a sync throw or async rejection from `dispose`
8116
+ * is caught + logged. Awaited on the async `resetDatabase` path so teardown
8117
+ * completes before the caller reopens; fire-and-forget on the synchronous
8118
+ * `getDatabase` path (which cannot block).
8119
+ */
8120
+ private disposeAdapter;
8106
8121
  /**
8107
8122
  * Check and handle schema migrations for a specific wallet.
8108
8123
  * Returns true if a destructive migration is in progress.
@@ -121,7 +121,7 @@ import {
121
121
  updateVaultMemoryEmbeddingOp,
122
122
  updateVaultMemoryOp,
123
123
  useEncryption
124
- } from "./chunk-DVGJ5NBT.mjs";
124
+ } from "./chunk-DC6J5RX5.mjs";
125
125
  import {
126
126
  PiiRedactor,
127
127
  createStreamingDeAnonymizer,
@@ -12664,6 +12664,7 @@ var DatabaseManager = class {
12664
12664
  from: this.currentWalletAddress,
12665
12665
  to: walletAddress
12666
12666
  });
12667
+ void this.disposeAdapter(this.database);
12667
12668
  this.database = null;
12668
12669
  }
12669
12670
  if (this.database) {
@@ -12693,11 +12694,37 @@ var DatabaseManager = class {
12693
12694
  async resetDatabase() {
12694
12695
  const db = this.database;
12695
12696
  if (db) {
12697
+ this.database = null;
12698
+ this.currentWalletAddress = void 0;
12696
12699
  await db.write(async () => {
12697
12700
  await db.unsafeResetDatabase();
12698
12701
  });
12699
- this.database = null;
12700
- this.currentWalletAddress = void 0;
12702
+ await this.disposeAdapter(db);
12703
+ }
12704
+ }
12705
+ /**
12706
+ * Best-effort dispose of the adapter backing a Database, if it exposes one.
12707
+ *
12708
+ * OPFS/SQLite adapters use this to terminate their dedicated worker and release
12709
+ * the exclusive SAHPool (+ WASM heap) they hold. The SDK only sees a generic
12710
+ * `DatabaseAdapter`, so we probe `adapter.underlyingAdapter.dispose` rather than
12711
+ * type it. Client-side implementations are refcounted + idempotent, so calling
12712
+ * this is safe even when the adapter factory also disposes.
12713
+ *
12714
+ * Awaitable and never rejects: a sync throw or async rejection from `dispose`
12715
+ * is caught + logged. Awaited on the async `resetDatabase` path so teardown
12716
+ * completes before the caller reopens; fire-and-forget on the synchronous
12717
+ * `getDatabase` path (which cannot block).
12718
+ */
12719
+ async disposeAdapter(db) {
12720
+ try {
12721
+ const underlying = db.adapter?.underlyingAdapter;
12722
+ await underlying?.dispose?.();
12723
+ } catch (error) {
12724
+ this.logger.warn?.("Adapter dispose failed", {
12725
+ component: "DatabaseManager",
12726
+ error
12727
+ });
12701
12728
  }
12702
12729
  }
12703
12730
  /**
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  recall
3
- } from "./chunk-DVGJ5NBT.mjs";
3
+ } from "./chunk-DC6J5RX5.mjs";
4
4
  import "./chunk-DFVCS3QQ.mjs";
5
5
  import "./chunk-GYKJOWEO.mjs";
6
6
  export {
@@ -17328,6 +17328,20 @@ async function withEmbeddingRetry(call) {
17328
17328
  if (threw) throw lastThrown;
17329
17329
  return last;
17330
17330
  }
17331
+ var EmbeddingHttpError = class extends Error {
17332
+ constructor(message, status) {
17333
+ super(message);
17334
+ this.name = "EmbeddingHttpError";
17335
+ this.status = status;
17336
+ }
17337
+ };
17338
+ function isFatalEmbeddingError(err) {
17339
+ return err instanceof EmbeddingHttpError && (err.status === 401 || err.status === 402 || err.status === 403);
17340
+ }
17341
+ function embeddingErrorFrom(response) {
17342
+ const message = typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed";
17343
+ return new EmbeddingHttpError(message, response.response?.status);
17344
+ }
17331
17345
  async function generateEmbedding(text, options) {
17332
17346
  const { baseUrl = BASE_URL, getToken, apiKey, model, cache } = options;
17333
17347
  if (cache) {
@@ -17359,9 +17373,7 @@ async function generateEmbedding(text, options) {
17359
17373
  })
17360
17374
  );
17361
17375
  if (response.error) {
17362
- throw new Error(
17363
- typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed"
17364
- );
17376
+ throw embeddingErrorFrom(response);
17365
17377
  }
17366
17378
  if (!response.data?.data?.[0]?.embedding) {
17367
17379
  throw new Error("No embedding returned from API");
@@ -17390,9 +17402,7 @@ async function generateEmbeddingsBatch(texts, headers, baseUrl, model, onUsage,
17390
17402
  })
17391
17403
  );
17392
17404
  if (response.error) {
17393
- throw new Error(
17394
- typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed"
17395
- );
17405
+ throw embeddingErrorFrom(response);
17396
17406
  }
17397
17407
  if (!response.data?.data) {
17398
17408
  throw new Error("No embeddings returned from API");
@@ -17528,6 +17538,7 @@ async function embedAllMessages(ctx, options, filter) {
17528
17538
  await updateMessageEmbeddingOp(ctx, message.uniqueId, embedding, embeddingModel);
17529
17539
  embeddedCount++;
17530
17540
  } catch (error) {
17541
+ if (isFatalEmbeddingError(error)) throw error;
17531
17542
  getLogger().error(`Failed to embed message ${message.uniqueId}:`, error);
17532
17543
  }
17533
17544
  }
@@ -17615,6 +17626,7 @@ async function chunkAndEmbedAllMessages(ctx, options, filter) {
17615
17626
  }
17616
17627
  }
17617
17628
  } catch (error) {
17629
+ if (isFatalEmbeddingError(error)) throw error;
17618
17630
  getLogger().error("Failed to batch-embed short messages:", error);
17619
17631
  }
17620
17632
  }
@@ -17631,6 +17643,7 @@ async function chunkAndEmbedAllMessages(ctx, options, filter) {
17631
17643
  await updateMessageChunksOp(ctx, msg.uniqueId, messageChunks, embeddingModel);
17632
17644
  embeddedCount++;
17633
17645
  } catch (error) {
17646
+ if (isFatalEmbeddingError(error)) throw error;
17634
17647
  getLogger().error(`Failed to embed message ${msg.uniqueId}:`, error);
17635
17648
  }
17636
17649
  }
@@ -18825,7 +18838,7 @@ function createMemoryVaultSearchTool(vaultCtx, embeddingOptions, cache, searchOp
18825
18838
  legacy.map((r) => ({ id: r.uniqueId, content: r.content, score: r.similarity }))
18826
18839
  );
18827
18840
  }
18828
- const { recall: recall2 } = await import("./recall-2XUT7CCN.mjs");
18841
+ const { recall: recall2 } = await import("./recall-V4763HKS.mjs");
18829
18842
  const result = await recall2(
18830
18843
  query,
18831
18844
  { vaultCtx, embeddingOptions, vaultCache: cache },