@mastra/memory 1.41.0 → 1.41.1-alpha.1

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.
Files changed (31) hide show
  1. package/dist/docs/SKILL.md +3 -4
  2. package/dist/docs/assets/SOURCE_MAP.json +225 -191
  3. package/dist/docs/references/docs-harness-background-tasks.md +2 -1
  4. package/dist/docs/references/docs-harness-goals.md +1 -1
  5. package/dist/docs/references/docs-knowledge-overview.md +106 -0
  6. package/dist/docs/references/docs-memory-observational-memory.md +23 -23
  7. package/dist/docs/references/docs-memory-overview.md +19 -7
  8. package/dist/docs/references/docs-memory-semantic-recall.md +24 -1
  9. package/dist/docs/references/integrations-channels-github.md +63 -24
  10. package/dist/docs/references/integrations-databases-postgresql.md +46 -0
  11. package/dist/docs/references/reference-core-getMemory.md +2 -2
  12. package/dist/docs/references/reference-core-listMemory.md +3 -3
  13. package/dist/docs/references/reference-memory-memory-class.md +1 -1
  14. package/dist/docs/references/reference-memory-observational-memory.md +9 -7
  15. package/dist/docs/references/reference-processors-token-limiter-processor.md +1 -1
  16. package/dist/index.cjs +1 -1
  17. package/dist/index.d.ts +26 -8
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/processors/index.cjs +1 -1
  21. package/dist/processors/index.js +1 -1
  22. package/dist/processors/observational-memory/processor.d.ts.map +1 -1
  23. package/dist/{src-BncFunCW.js → src-BL6KZcyR.js} +309 -399
  24. package/dist/src-BL6KZcyR.js.map +1 -0
  25. package/dist/{src-gNoNdZv8.cjs → src-Bo9Kpfk_.cjs} +308 -398
  26. package/dist/src-Bo9Kpfk_.cjs.map +1 -0
  27. package/package.json +4 -4
  28. package/dist/docs/references/reference-migrations-agentnetwork.md +0 -102
  29. package/dist/docs/references/reference-migrations-upgrade-to-v1-memory.md +0 -290
  30. package/dist/src-BncFunCW.js.map +0 -1
  31. package/dist/src-gNoNdZv8.cjs.map +0 -1
@@ -6,7 +6,7 @@ import { toJSONSchema } from "zod/v4/core";
6
6
  import { Agent, MessageList } from "@mastra/core/agent";
7
7
  import { ErrorCategory, ErrorDomain, MastraError, classifyProviderError } from "@mastra/core/error";
8
8
  import { coreFeatures } from "@mastra/core/features";
9
- import { MastraMemory, getMemoryTokenBoundary, getThreadOMMetadata, isAfterMemoryTokenBoundary, isThreadTitlePinned, loadMessageHistory, normalizeMessageHistoryConfig, parseMemoryRequestContext, setThreadOMMetadata } from "@mastra/core/memory";
9
+ import { MESSAGE_EMBEDDING_CHARS_PER_TOKEN, MastraMemory, buildMessageEmbeddingRows, chunkMessageText, getMemoryTokenBoundary, getThreadOMMetadata, isAfterMemoryTokenBoundary, isThreadTitlePinned, loadMessageHistory, normalizeMessageHistoryConfig, parseMemoryRequestContext, resolveMaxChunkChars, setThreadOMMetadata, upsertMessageVectors } from "@mastra/core/memory";
10
10
  import * as coreObservability from "@mastra/core/observability";
11
11
  import { EntityType, SpanType, createObservabilityContext, getOrCreateSpan } from "@mastra/core/observability";
12
12
  import { MessageHistory, MessageHistory as MessageHistory$1, SemanticRecall, TokenLimiterProcessor, WorkingMemory } from "@mastra/core/processors";
@@ -3689,7 +3689,7 @@ function trimStartOfStream() {
3689
3689
  return text2;
3690
3690
  };
3691
3691
  }
3692
- // ../_vendored/ai_v5/dist/dist-CjxSswTJ.js
3692
+ // ../_vendored/ai_v5/dist/dist-BYnbJEqC.js
3693
3693
  var marker$1$16 = "vercel.ai.error";
3694
3694
  var symbol$1$17 = Symbol.for(marker$1$16);
3695
3695
  var _a$1$2;
@@ -4250,7 +4250,7 @@ function withUserAgentSuffix$2(headers, ...userAgentSuffixParts) {
4250
4250
  normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
4251
4251
  return Object.fromEntries(normalizedHeaders.entries());
4252
4252
  }
4253
- var VERSION$8 = "3.0.43";
4253
+ var VERSION$8 = "3.0.44";
4254
4254
  var getOriginalFetch$3 = () => globalThis.fetch;
4255
4255
  var getFromApi$2 = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch$3() }) => {
4256
4256
  try {
@@ -5674,10 +5674,24 @@ function asSchema$2(schema) {
5674
5674
  }) : isSchema$2(schema) ? schema : typeof schema === "function" ? schema() : zodSchema$2(schema);
5675
5675
  }
5676
5676
  var { btoa: btoa$3, atob: atob$6 } = globalThis;
5677
+ var typedArrayTag$2 = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
5678
+ var arrayBufferByteLength$2 = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
5679
+ function isUint8Array$2(value) {
5680
+ return ArrayBuffer.isView(value) && typedArrayTag$2.call(value) === "Uint8Array";
5681
+ }
5682
+ function isArrayBuffer$2(value) {
5683
+ if (typeof value !== "object" || value === null || !("byteLength" in value)) return false;
5684
+ try {
5685
+ arrayBufferByteLength$2.call(value);
5686
+ return true;
5687
+ } catch (e) {
5688
+ return false;
5689
+ }
5690
+ }
5677
5691
  function withoutTrailingSlash$2(url) {
5678
5692
  return url == null ? void 0 : url.replace(/\/$/, "");
5679
5693
  }
5680
- // ../_vendored/ai_v5/dist/dist-BB1ns2jp.js
5694
+ // ../_vendored/ai_v5/dist/dist-oTd7Lp_i.js
5681
5695
  function getContext$2() {
5682
5696
  return { headers: {} };
5683
5697
  }
@@ -6013,6 +6027,7 @@ function isTimeoutError$2(error) {
6013
6027
  }
6014
6028
  async function asGatewayError$2(error, authMethod) {
6015
6029
  var _a10;
6030
+ if ((error instanceof Error || typeof DOMException === "function" && error instanceof DOMException) && (error.name === "AbortError" || error.name === "TimeoutError")) throw error;
6016
6031
  if (GatewayError$2.isInstance(error)) return error;
6017
6032
  if (isTimeoutError$2(error)) return GatewayTimeoutError$2.createTimeoutError({
6018
6033
  originalMessage: error instanceof Error ? error.message : "Unknown error",
@@ -6656,7 +6671,7 @@ async function getVercelRequestId$2() {
6656
6671
  var _a10;
6657
6672
  return (_a10 = getContext$2().headers) == null ? void 0 : _a10["x-vercel-id"];
6658
6673
  }
6659
- var VERSION$7 = "2.0.174";
6674
+ var VERSION$7 = "2.0.176";
6660
6675
  var AI_GATEWAY_PROTOCOL_VERSION$2 = "0.0.1";
6661
6676
  function createGatewayProvider$1(options = {}) {
6662
6677
  var _a10, _b10;
@@ -7691,11 +7706,11 @@ function getGlobalProvider$2() {
7691
7706
  var _a17;
7692
7707
  return (_a17 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a17 : gateway$2;
7693
7708
  }
7694
- var VERSION$6 = "5.0.283";
7709
+ var VERSION$6 = "5.0.285";
7695
7710
  var dataContentSchema$1 = z$1.union([
7696
7711
  z$1.string(),
7697
- z$1.instanceof(Uint8Array),
7698
- z$1.instanceof(ArrayBuffer),
7712
+ z$1.custom(isUint8Array$2, { message: "Must be a Uint8Array" }),
7713
+ z$1.custom(isArrayBuffer$2, { message: "Must be an ArrayBuffer" }),
7699
7714
  z$1.custom((value) => {
7700
7715
  var _a17, _b;
7701
7716
  return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
@@ -8597,7 +8612,7 @@ var object$2 = ({ schema: inputSchema }) => {
8597
8612
  }
8598
8613
  };
8599
8614
  };
8600
- // ../_vendored/ai_v6/dist/dist-Cdb_i6Zs.js
8615
+ // ../_vendored/ai_v6/dist/dist-DwNW4Hp7.js
8601
8616
  var marker$1$14 = "vercel.ai.error";
8602
8617
  var symbol$1$15 = Symbol.for(marker$1$14);
8603
8618
  var _a$1$1;
@@ -9001,6 +9016,20 @@ function convertUint8ArrayToBase64$1(array) {
9001
9016
  for (let i = 0; i < array.length; i += chunkSize) chunks.push(String.fromCodePoint(...array.subarray(i, i + chunkSize)));
9002
9017
  return btoa$2(chunks.join(""));
9003
9018
  }
9019
+ var typedArrayTag$1 = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
9020
+ var arrayBufferByteLength$1 = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
9021
+ function isUint8Array$1(value) {
9022
+ return ArrayBuffer.isView(value) && typedArrayTag$1.call(value) === "Uint8Array";
9023
+ }
9024
+ function isArrayBuffer$1(value) {
9025
+ if (typeof value !== "object" || value === null || !("byteLength" in value)) return false;
9026
+ try {
9027
+ arrayBufferByteLength$1.call(value);
9028
+ return true;
9029
+ } catch (e) {
9030
+ return false;
9031
+ }
9032
+ }
9004
9033
  async function cancelResponseBody$1(response) {
9005
9034
  var _a2;
9006
9035
  try {
@@ -9455,7 +9484,7 @@ function withUserAgentSuffix$1(headers, ...userAgentSuffixParts) {
9455
9484
  normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
9456
9485
  return Object.fromEntries(normalizedHeaders.entries());
9457
9486
  }
9458
- var VERSION$5 = "4.0.63";
9487
+ var VERSION$5 = "4.0.64";
9459
9488
  var getOriginalFetch$1 = () => globalThis.fetch;
9460
9489
  var getFromApi$1 = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, validateUrl, credentialedOrigin, trustedOrigin }) => {
9461
9490
  try {
@@ -10931,7 +10960,7 @@ var createJsonResponseHandler$1 = (responseSchema) => async ({ response, url, re
10931
10960
  function withoutTrailingSlash$1(url) {
10932
10961
  return url == null ? void 0 : url.replace(/\/$/, "");
10933
10962
  }
10934
- // ../_vendored/ai_v6/dist/dist-nkEfZgfI.js
10963
+ // ../_vendored/ai_v6/dist/dist-B9RoRXxy.js
10935
10964
  function getContext$1() {
10936
10965
  return { headers: {} };
10937
10966
  }
@@ -11321,6 +11350,7 @@ function isTimeoutError$1(error) {
11321
11350
  }
11322
11351
  async function asGatewayError$1(error, authMethod) {
11323
11352
  var _a11;
11353
+ if ((error instanceof Error || typeof DOMException === "function" && error instanceof DOMException) && (error.name === "AbortError" || error.name === "TimeoutError")) throw error;
11324
11354
  if (GatewayError$1.isInstance(error)) return error;
11325
11355
  if (isTimeoutError$1(error)) return GatewayTimeoutError$1.createTimeoutError({
11326
11356
  originalMessage: error instanceof Error ? error.message : "Unknown error",
@@ -12381,6 +12411,54 @@ var browserbaseSearchToolFactory$1 = createProviderToolFactoryWithOutputSchema({
12381
12411
  })])))
12382
12412
  });
12383
12413
  var browserbaseSearch$1 = (config = {}) => browserbaseSearchToolFactory$1(config);
12414
+ var gatewayToolErrorSchema$1 = () => z.object({
12415
+ error: z.enum([
12416
+ "api_error",
12417
+ "configuration_error",
12418
+ "execution_error",
12419
+ "gateway_rate_limit",
12420
+ "invalid_input",
12421
+ "rate_limit",
12422
+ "timeout",
12423
+ "unknown",
12424
+ "unknown_tool"
12425
+ ]),
12426
+ message: z.string(),
12427
+ statusCode: z.number().optional(),
12428
+ retryAfter: z.string().optional(),
12429
+ statusText: z.string().optional()
12430
+ }).passthrough();
12431
+ var deepseekFetchToolFactory$1 = createProviderToolFactoryWithOutputSchema({
12432
+ id: "gateway.deepseek_fetch",
12433
+ inputSchema: lazySchema$1(() => zodSchema$1(z.object({ url: z.string().describe("URL to fetch, at most 8192 characters; HTTP(S) only, without a username or password.") }))),
12434
+ outputSchema: lazySchema$1(() => zodSchema$1(z.union([z.object({
12435
+ title: z.string().nullish(),
12436
+ content: z.string()
12437
+ }).passthrough(), gatewayToolErrorSchema$1()])))
12438
+ });
12439
+ var deepseekFetch$1 = (config = {}) => deepseekFetchToolFactory$1(config);
12440
+ var deepseekSearchToolFactory$1 = createProviderToolFactoryWithOutputSchema({
12441
+ id: "gateway.deepseek_search",
12442
+ inputSchema: lazySchema$1(() => zodSchema$1(z.object({
12443
+ query: z.string().describe("Web search query, 1 to 128 Unicode characters. Supports site:, -site:, lang:, after:, before:, and quoted phrases."),
12444
+ count: z.number().int().optional().describe("Number of results, 1 to 50 (default: 10)."),
12445
+ need_content: z.boolean().optional().describe("Include available page content (default: false)."),
12446
+ ori_question: z.string().nullable().optional().describe("Original user question, 1 to 128 Unicode characters.")
12447
+ }))),
12448
+ outputSchema: lazySchema$1(() => zodSchema$1(z.union([z.object({ results: z.array(z.object({
12449
+ authority: z.number().nullish(),
12450
+ content: z.string().nullish(),
12451
+ date: z.string().nullish(),
12452
+ rerank_score: z.number().nullish(),
12453
+ site_icon: z.string().nullish(),
12454
+ site_name: z.string().nullish(),
12455
+ snippet: z.string().nullish(),
12456
+ summary: z.string().nullish(),
12457
+ title: z.string().nullish(),
12458
+ url: z.string().nullish()
12459
+ }).passthrough()) }).passthrough(), gatewayToolErrorSchema$1()])))
12460
+ });
12461
+ var deepseekSearch$1 = (config = {}) => deepseekSearchToolFactory$1(config);
12384
12462
  var exaSearchToolFactory$1 = createProviderToolFactoryWithOutputSchema({
12385
12463
  id: "gateway.exa_search",
12386
12464
  inputSchema: lazySchema$1(() => zodSchema$1(z.object({
@@ -12537,21 +12615,7 @@ var parallelSearchToolFactory$1 = createProviderToolFactoryWithOutputSchema({
12537
12615
  count: z.number().optional()
12538
12616
  })).nullable().optional(),
12539
12617
  session_id: z.string().optional()
12540
- }), z.object({
12541
- error: z.enum([
12542
- "api_error",
12543
- "configuration_error",
12544
- "execution_error",
12545
- "gateway_rate_limit",
12546
- "invalid_input",
12547
- "rate_limit",
12548
- "timeout",
12549
- "unknown",
12550
- "unknown_tool"
12551
- ]),
12552
- statusCode: z.number().optional(),
12553
- message: z.string()
12554
- })])))
12618
+ }), gatewayToolErrorSchema$1()])))
12555
12619
  });
12556
12620
  var parallelSearch$1 = (config = {}) => parallelSearchToolFactory$1(config);
12557
12621
  var perplexitySearchToolFactory$1 = createProviderToolFactoryWithOutputSchema({
@@ -12782,19 +12846,7 @@ var takoSearchToolFactory$1 = createProviderToolFactoryWithOutputSchema({
12782
12846
  }).nullish()
12783
12847
  }).nullish(),
12784
12848
  related: z.array(z.object({}).passthrough()).nullish()
12785
- }).passthrough(), z.object({
12786
- error: z.enum([
12787
- "api_error",
12788
- "configuration_error",
12789
- "execution_error",
12790
- "invalid_input",
12791
- "rate_limit",
12792
- "timeout",
12793
- "unknown_tool"
12794
- ]),
12795
- statusCode: z.number().optional(),
12796
- message: z.string()
12797
- })])))
12849
+ }).passthrough(), gatewayToolErrorSchema$1()])))
12798
12850
  });
12799
12851
  var takoSearch$1 = (config = {}) => takoSearchToolFactory$1(config);
12800
12852
  var gatewayTools$1 = {
@@ -12813,6 +12865,16 @@ var gatewayTools$1 = {
12813
12865
  */
12814
12866
  browserbaseSearch: browserbaseSearch$1,
12815
12867
  /**
12868
+ * Fetch a page as Markdown through DeepSeek's standalone Fetch API.
12869
+ * Executed by AI Gateway for any model, separate from native model web search.
12870
+ */
12871
+ deepseekFetch: deepseekFetch$1,
12872
+ /**
12873
+ * Search the web through DeepSeek's standalone Search API.
12874
+ * Executed by AI Gateway for any model, separate from native model web search.
12875
+ */
12876
+ deepseekSearch: deepseekSearch$1,
12877
+ /**
12816
12878
  * Search the web using Exa for current information and token-efficient
12817
12879
  * excerpts optimized for agent workflows.
12818
12880
  *
@@ -12851,7 +12913,7 @@ async function getVercelRequestId$1() {
12851
12913
  var _a11;
12852
12914
  return (_a11 = getContext$1().headers) == null ? void 0 : _a11["x-vercel-id"];
12853
12915
  }
12854
- var VERSION$4 = "3.0.226";
12916
+ var VERSION$4 = "3.0.228";
12855
12917
  var AI_GATEWAY_PROTOCOL_VERSION$1 = "0.0.1";
12856
12918
  function createGatewayProvider(options = {}) {
12857
12919
  var _a11, _b11;
@@ -14027,11 +14089,11 @@ function getTotalTimeoutMs(timeout) {
14027
14089
  if (typeof timeout === "number") return timeout;
14028
14090
  return timeout.totalMs;
14029
14091
  }
14030
- var VERSION$3 = "6.0.320";
14092
+ var VERSION$3 = "6.0.322";
14031
14093
  var dataContentSchema = z$1.union([
14032
14094
  z$1.string(),
14033
- z$1.instanceof(Uint8Array),
14034
- z$1.instanceof(ArrayBuffer),
14095
+ z$1.custom(isUint8Array$1, { message: "Must be a Uint8Array" }),
14096
+ z$1.custom(isArrayBuffer$1, { message: "Must be an ArrayBuffer" }),
14035
14097
  z$1.custom((value) => {
14036
14098
  var _a23, _b;
14037
14099
  return (_b = (_a23 = globalThis.Buffer) == null ? void 0 : _a23.isBuffer(value)) != null ? _b : false;
@@ -15223,7 +15285,7 @@ createIdGenerator$1({
15223
15285
  prefix: "aiobj",
15224
15286
  size: 24
15225
15287
  });
15226
- // ../_vendored/ai_v7/dist/dist-VDS1iOhH.js
15288
+ // ../_vendored/ai_v7/dist/dist-CwN1TMYk.js
15227
15289
  /**
15228
15290
  * Symbol used for identifying AI SDK Error instances.
15229
15291
  * Enables checking if an error is an instance of AISDKError across package versions.
@@ -15822,7 +15884,9 @@ const { btoa: btoa$1, atob: atob$2 } = globalThis;
15822
15884
  function convertBase64ToUint8Array(base64String) {
15823
15885
  const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
15824
15886
  const latin1string = atob$2(base64Url);
15825
- return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
15887
+ const bytes = new Uint8Array(latin1string.length);
15888
+ for (let i = 0; i < latin1string.length; i++) bytes[i] = latin1string.charCodeAt(i);
15889
+ return bytes;
15826
15890
  }
15827
15891
  function convertUint8ArrayToBase64(array) {
15828
15892
  if (typeof globalThis.Buffer?.from === "function") return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString("base64");
@@ -15831,6 +15895,20 @@ function convertUint8ArrayToBase64(array) {
15831
15895
  for (let i = 0; i < array.length; i += chunkSize) chunks.push(String.fromCodePoint(...array.subarray(i, i + chunkSize)));
15832
15896
  return btoa$1(chunks.join(""));
15833
15897
  }
15898
+ const typedArrayTag = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
15899
+ const arrayBufferByteLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
15900
+ function isUint8Array(value) {
15901
+ return ArrayBuffer.isView(value) && typedArrayTag.call(value) === "Uint8Array";
15902
+ }
15903
+ function isArrayBuffer(value) {
15904
+ if (typeof value !== "object" || value === null || !("byteLength" in value)) return false;
15905
+ try {
15906
+ arrayBufferByteLength.call(value);
15907
+ return true;
15908
+ } catch {
15909
+ return false;
15910
+ }
15911
+ }
15834
15912
  /**
15835
15913
  * Extracts the headers from a response object and returns them as a key-value object.
15836
15914
  *
@@ -15908,7 +15986,7 @@ function handleFetchError({ error, url, requestBodyValues }) {
15908
15986
  }
15909
15987
  return error;
15910
15988
  }
15911
- const VERSION$2 = "5.0.72";
15989
+ const VERSION$2 = "5.0.74";
15912
15990
  /**
15913
15991
  * Normalizes different header inputs into a plain record with lower-case keys.
15914
15992
  * Entries with `undefined` or `null` values are removed.
@@ -18399,7 +18477,7 @@ function isSegment(value) {
18399
18477
  function withoutTrailingSlash(url) {
18400
18478
  return url?.replace(/\/$/, "");
18401
18479
  }
18402
- // ../_vendored/ai_v7/dist/dist-BBvYSanG.js
18480
+ // ../_vendored/ai_v7/dist/dist-D6YcYEgU.js
18403
18481
  /**
18404
18482
  * Symbol used to define custom serialization for user-defined class instances.
18405
18483
  * The static method should accept an instance and return serializable data.
@@ -21104,6 +21182,54 @@ const browserbaseSearchToolFactory = createProviderExecutedToolFactory({
21104
21182
  })])))
21105
21183
  });
21106
21184
  const browserbaseSearch = (config = {}) => browserbaseSearchToolFactory(config);
21185
+ const gatewayToolErrorSchema = () => z$3.object({
21186
+ error: z$3.enum([
21187
+ "api_error",
21188
+ "configuration_error",
21189
+ "execution_error",
21190
+ "gateway_rate_limit",
21191
+ "invalid_input",
21192
+ "rate_limit",
21193
+ "timeout",
21194
+ "unknown",
21195
+ "unknown_tool"
21196
+ ]),
21197
+ message: z$3.string(),
21198
+ statusCode: z$3.number().optional(),
21199
+ retryAfter: z$3.string().optional(),
21200
+ statusText: z$3.string().optional()
21201
+ }).passthrough();
21202
+ const deepseekFetchToolFactory = createProviderExecutedToolFactory({
21203
+ id: "gateway.deepseek_fetch",
21204
+ inputSchema: lazySchema(() => zodSchema(z$3.object({ url: z$3.string().describe("URL to fetch, at most 8192 characters; HTTP(S) only, without a username or password.") }))),
21205
+ outputSchema: lazySchema(() => zodSchema(z$3.union([z$3.object({
21206
+ title: z$3.string().nullish(),
21207
+ content: z$3.string()
21208
+ }).passthrough(), gatewayToolErrorSchema()])))
21209
+ });
21210
+ const deepseekFetch = (config = {}) => deepseekFetchToolFactory(config);
21211
+ const deepseekSearchToolFactory = createProviderExecutedToolFactory({
21212
+ id: "gateway.deepseek_search",
21213
+ inputSchema: lazySchema(() => zodSchema(z$3.object({
21214
+ query: z$3.string().describe("Web search query, 1 to 128 Unicode characters. Supports site:, -site:, lang:, after:, before:, and quoted phrases."),
21215
+ count: z$3.number().int().optional().describe("Number of results, 1 to 50 (default: 10)."),
21216
+ need_content: z$3.boolean().optional().describe("Include available page content (default: false)."),
21217
+ ori_question: z$3.string().nullable().optional().describe("Original user question, 1 to 128 Unicode characters.")
21218
+ }))),
21219
+ outputSchema: lazySchema(() => zodSchema(z$3.union([z$3.object({ results: z$3.array(z$3.object({
21220
+ authority: z$3.number().nullish(),
21221
+ content: z$3.string().nullish(),
21222
+ date: z$3.string().nullish(),
21223
+ rerank_score: z$3.number().nullish(),
21224
+ site_icon: z$3.string().nullish(),
21225
+ site_name: z$3.string().nullish(),
21226
+ snippet: z$3.string().nullish(),
21227
+ summary: z$3.string().nullish(),
21228
+ title: z$3.string().nullish(),
21229
+ url: z$3.string().nullish()
21230
+ }).passthrough()) }).passthrough(), gatewayToolErrorSchema()])))
21231
+ });
21232
+ const deepseekSearch = (config = {}) => deepseekSearchToolFactory(config);
21107
21233
  const exaSearchToolFactory = createProviderExecutedToolFactory({
21108
21234
  id: "gateway.exa_search",
21109
21235
  inputSchema: lazySchema(() => zodSchema(z$3.object({
@@ -21260,21 +21386,7 @@ const parallelSearchToolFactory = createProviderExecutedToolFactory({
21260
21386
  count: z$3.number().optional()
21261
21387
  })).nullable().optional(),
21262
21388
  session_id: z$3.string().optional()
21263
- }), z$3.object({
21264
- error: z$3.enum([
21265
- "api_error",
21266
- "configuration_error",
21267
- "execution_error",
21268
- "gateway_rate_limit",
21269
- "invalid_input",
21270
- "rate_limit",
21271
- "timeout",
21272
- "unknown",
21273
- "unknown_tool"
21274
- ]),
21275
- statusCode: z$3.number().optional(),
21276
- message: z$3.string()
21277
- })])))
21389
+ }), gatewayToolErrorSchema()])))
21278
21390
  });
21279
21391
  const parallelSearch = (config = {}) => parallelSearchToolFactory(config);
21280
21392
  const perplexitySearchToolFactory = createProviderExecutedToolFactory({
@@ -21505,19 +21617,7 @@ const takoSearchToolFactory = createProviderExecutedToolFactory({
21505
21617
  }).nullish()
21506
21618
  }).nullish(),
21507
21619
  related: z$3.array(z$3.object({}).passthrough()).nullish()
21508
- }).passthrough(), z$3.object({
21509
- error: z$3.enum([
21510
- "api_error",
21511
- "configuration_error",
21512
- "execution_error",
21513
- "invalid_input",
21514
- "rate_limit",
21515
- "timeout",
21516
- "unknown_tool"
21517
- ]),
21518
- statusCode: z$3.number().optional(),
21519
- message: z$3.string()
21520
- })])))
21620
+ }).passthrough(), gatewayToolErrorSchema()])))
21521
21621
  });
21522
21622
  const takoSearch = (config = {}) => takoSearchToolFactory(config);
21523
21623
  /**
@@ -21539,6 +21639,16 @@ const gatewayTools = {
21539
21639
  */
21540
21640
  browserbaseSearch,
21541
21641
  /**
21642
+ * Fetch a page as Markdown through DeepSeek's standalone Fetch API.
21643
+ * Executed by AI Gateway for any model, separate from native model web search.
21644
+ */
21645
+ deepseekFetch,
21646
+ /**
21647
+ * Search the web through DeepSeek's standalone Search API.
21648
+ * Executed by AI Gateway for any model, separate from native model web search.
21649
+ */
21650
+ deepseekSearch,
21651
+ /**
21542
21652
  * Search the web using Exa for current information and token-efficient
21543
21653
  * excerpts optimized for agent workflows.
21544
21654
  *
@@ -21576,7 +21686,7 @@ const gatewayTools = {
21576
21686
  async function getVercelRequestId() {
21577
21687
  return getContext().headers?.["x-vercel-id"];
21578
21688
  }
21579
- const VERSION$1 = "4.0.132";
21689
+ const VERSION$1 = "4.0.135";
21580
21690
  const AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
21581
21691
  /** Response shape of `POST /v1/realtime/client-secrets`. `expiresAt` is epoch seconds. */
21582
21692
  const gatewayClientSecretResponseSchema = lazySchema(() => zodSchema(z$3.object({
@@ -22384,7 +22494,7 @@ function resolveEmbeddingModel(model) {
22384
22494
  function getGlobalProvider() {
22385
22495
  return asProviderV4(globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway);
22386
22496
  }
22387
- const VERSION = "7.0.159";
22497
+ const VERSION = "7.0.162";
22388
22498
  /**
22389
22499
  * Reads a property by an untrusted key, ignoring inherited prototype members.
22390
22500
  *
@@ -23254,8 +23364,8 @@ createIdGenerator({
23254
23364
  });
23255
23365
  const fileInlineDataSchema = z$2.union([
23256
23366
  z$2.string(),
23257
- z$2.instanceof(Uint8Array),
23258
- z$2.instanceof(ArrayBuffer),
23367
+ z$2.custom(isUint8Array, { message: "Must be a Uint8Array" }),
23368
+ z$2.custom(isArrayBuffer, { message: "Must be an ArrayBuffer" }),
23259
23369
  z$2.custom(isBuffer, { message: "Must be a Buffer" })
23260
23370
  ]);
23261
23371
  const providerReferenceSchema = z$2.record(z$2.string(), z$2.string());
@@ -23558,15 +23668,7 @@ createIdGenerator({
23558
23668
  size: 24
23559
23669
  });
23560
23670
  // src/processors/observational-memory/constants.ts
23561
- var constants_exports = /* @__PURE__ */ __exportAll({
23562
- OBSERVATIONAL_MEMORY_DEFAULTS: () => OBSERVATIONAL_MEMORY_DEFAULTS,
23563
- OBSERVATION_CONTEXT_INSTRUCTIONS: () => OBSERVATION_CONTEXT_INSTRUCTIONS,
23564
- OBSERVATION_CONTEXT_PROMPT: () => OBSERVATION_CONTEXT_PROMPT,
23565
- OBSERVATION_CONTEXT_PROMPT_THREAD: () => OBSERVATION_CONTEXT_PROMPT_THREAD,
23566
- OBSERVATION_CONTINUATION_HINT: () => OBSERVATION_CONTINUATION_HINT,
23567
- getObservationContextPrompt: () => getObservationContextPrompt,
23568
- getRetrievalInstructions: () => getRetrievalInstructions
23569
- });
23671
+ var constants_exports = /* @__PURE__ */ __exportAll({ OBSERVATION_CONTINUATION_HINT: () => OBSERVATION_CONTINUATION_HINT });
23570
23672
  /**
23571
23673
  * Default configuration values matching the spec
23572
23674
  */
@@ -39736,7 +39838,8 @@ var ObservationalMemoryProcessor = class {
39736
39838
  ctx = await step.prepare();
39737
39839
  } catch (error) {
39738
39840
  const err = error instanceof Error ? error : new Error(String(error));
39739
- const abortMessage = abortSignal?.aborted ? "Agent execution was aborted" : `Encountered error during memory observation: ${err.message}`;
39841
+ const abortReason = abortSignal?.reason;
39842
+ const abortMessage = abortSignal?.aborted ? abortReason instanceof Error && abortReason.name !== "AbortError" ? `Agent execution was aborted: ${abortReason.message}` : "Agent execution was aborted" : `Encountered error during memory observation: ${err.message}`;
39740
39843
  const failedTurn = this.turn;
39741
39844
  await failedTurn.end().catch(() => {});
39742
39845
  if (this.turn === failedTurn) this.turn = void 0;
@@ -39898,44 +40001,11 @@ function getObservationsAsOf(activeObservations, asOf) {
39898
40001
  }
39899
40002
  // src/processors/observational-memory/index.ts
39900
40003
  var observational_memory_exports = /* @__PURE__ */ __exportAll({
39901
- AUTO_MODEL_BY_PROVIDER: () => AUTO_MODEL_BY_PROVIDER,
39902
- Extractor: () => Extractor,
39903
- ModelByInputTokens: () => ModelByInputTokens,
39904
- OBSERVATIONAL_MEMORY_DEFAULTS: () => OBSERVATIONAL_MEMORY_DEFAULTS,
39905
- OBSERVATION_CONTEXT_INSTRUCTIONS: () => OBSERVATION_CONTEXT_INSTRUCTIONS,
39906
- OBSERVATION_CONTEXT_PROMPT: () => OBSERVATION_CONTEXT_PROMPT,
39907
- OBSERVATION_CONTEXT_PROMPT_THREAD: () => OBSERVATION_CONTEXT_PROMPT_THREAD,
39908
- OBSERVATION_CONTINUATION_HINT: () => OBSERVATION_CONTINUATION_HINT,
39909
- OBSERVER_SYSTEM_PROMPT: () => OBSERVER_SYSTEM_PROMPT,
39910
40004
  ObservationalMemory: () => ObservationalMemory,
39911
- ObservationalMemoryProcessor: () => ObservationalMemoryProcessor,
39912
- TokenCounter: () => TokenCounter,
39913
- WorkingMemoryExtractor: () => WorkingMemoryExtractor,
39914
- buildObserverPrompt: () => buildObserverPrompt,
39915
- buildObserverSystemPrompt: () => buildObserverSystemPrompt,
39916
- combineObservationGroupRanges: () => combineObservationGroupRanges,
39917
- deriveObservationGroupProvenance: () => deriveObservationGroupProvenance,
39918
- extractCurrentTask: () => extractCurrentTask,
39919
- formatMessagesForObserver: () => formatMessagesForObserver,
39920
- getObservationContextPrompt: () => getObservationContextPrompt,
39921
- getObservationsAsOf: () => getObservationsAsOf,
39922
- hasCurrentTaskSection: () => hasCurrentTaskSection,
39923
- injectAnchorIds: () => injectAnchorIds,
39924
- optimizeObservationsForContext: () => optimizeObservationsForContext,
39925
- parseAnchorId: () => parseAnchorId,
39926
- parseObservationGroups: () => parseObservationGroups,
39927
- parseObserverOutput: () => parseObserverOutput,
39928
- reconcileObservationGroupsFromReflection: () => reconcileObservationGroupsFromReflection,
39929
- renderObservationGroupsForReflection: () => renderObservationGroupsForReflection,
39930
- resolveAutoModelId: () => resolveAutoModelId,
39931
- stripEphemeralAnchorIds: () => stripEphemeralAnchorIds,
39932
- stripObservationGroups: () => stripObservationGroups,
39933
- summarizeConversation: () => summarizeConversation,
39934
- wrapInObservationGroup: () => wrapInObservationGroup
40005
+ ObservationalMemoryProcessor: () => ObservationalMemoryProcessor
39935
40006
  });
39936
40007
  // src/processors/working-memory-state/index.ts
39937
40008
  var working_memory_state_exports = /* @__PURE__ */ __exportAll({
39938
- WORKING_MEMORY_STATE_ID: () => WORKING_MEMORY_STATE_ID,
39939
40009
  WORKING_MEMORY_STATE_PROCESSOR_ID: () => WORKING_MEMORY_STATE_PROCESSOR_ID,
39940
40010
  WorkingMemoryStateProcessor: () => WorkingMemoryStateProcessor
39941
40011
  });
@@ -40078,7 +40148,6 @@ function normalizeObservationalMemoryConfig(config) {
40078
40148
  function hasWorkingMemoryExtractor(extractors) {
40079
40149
  return !!extractors?.some((extractor) => extractor.slug === "working-memory");
40080
40150
  }
40081
- const CHARS_PER_TOKEN = 4;
40082
40151
  const DEFAULT_MESSAGE_RANGE = {
40083
40152
  before: 1,
40084
40153
  after: 1
@@ -40221,6 +40290,7 @@ var Memory = class Memory extends MastraMemory {
40221
40290
  });
40222
40291
  this.assertWorkingMemoryStateSignalsCompatibility(mergedConfig);
40223
40292
  this.threadConfig = mergedConfig;
40293
+ resolveMaxChunkChars({ maxChunkChars: this.configuredMaxChunkChars });
40224
40294
  const omConfig = normalizeObservationalMemoryConfig(mergedConfig.observationalMemory);
40225
40295
  if (omConfig?.retrieval && typeof omConfig.retrieval === "object" && omConfig.retrieval.vector) {
40226
40296
  if (!this.vector) throw new Error("`retrieval: { vector: true }` requires a vector store. Pass a `vector` option to your Memory instance.");
@@ -40736,28 +40806,9 @@ ${workingMemory}`;
40736
40806
  release();
40737
40807
  }
40738
40808
  }
40809
+ /** Splits text into chunks of at most `tokenSize` English tokens, measured as characters. */
40739
40810
  chunkText(text, tokenSize = 4096) {
40740
- const charSize = tokenSize * CHARS_PER_TOKEN;
40741
- const chunks = [];
40742
- let currentChunk = "";
40743
- const words = text.split(/\s+/);
40744
- for (const word of words) {
40745
- if (word.length > charSize) {
40746
- if (currentChunk) {
40747
- chunks.push(currentChunk);
40748
- currentChunk = "";
40749
- }
40750
- for (let i = 0; i < word.length; i += charSize) chunks.push(word.slice(i, i + charSize));
40751
- continue;
40752
- }
40753
- const wordWithSpace = currentChunk ? " " + word : word;
40754
- if (currentChunk.length + wordWithSpace.length > charSize) {
40755
- if (currentChunk) chunks.push(currentChunk);
40756
- currentChunk = word;
40757
- } else currentChunk += wordWithSpace;
40758
- }
40759
- if (currentChunk) chunks.push(currentChunk);
40760
- return chunks;
40811
+ return chunkMessageText(text, tokenSize * MESSAGE_EMBEDDING_CHARS_PER_TOKEN);
40761
40812
  }
40762
40813
  hasher = xxhash();
40763
40814
  embeddingCache = new LRUCache({ max: DEFAULT_EMBEDDING_CACHE_MAX_SIZE });
@@ -40773,11 +40824,23 @@ ${workingMemory}`;
40773
40824
  return cached;
40774
40825
  }
40775
40826
  const chunks = this.chunkText(content);
40827
+ const { embeddings, usage } = await this.embedValues(chunks);
40828
+ const result = {
40829
+ embeddings,
40830
+ chunks,
40831
+ usage,
40832
+ dimension: embeddings[0]?.length
40833
+ };
40834
+ this.embeddingCache.set(key, result);
40835
+ return result;
40836
+ }
40837
+ /** Sends texts to the embedder through the AI SDK version that matches its spec. */
40838
+ async embedValues(values) {
40776
40839
  if (typeof this.embedder === `undefined`) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
40777
40840
  const isFastEmbed = this.embedder.provider === `fastembed`;
40778
40841
  if (isFastEmbed && this.firstEmbed instanceof Promise) await this.firstEmbed;
40779
40842
  const options = {
40780
- values: chunks,
40843
+ values,
40781
40844
  maxRetries: 3
40782
40845
  };
40783
40846
  const model = this.embedder;
@@ -40812,106 +40875,87 @@ ${workingMemory}`;
40812
40875
  }
40813
40876
  if (isFastEmbed && !this.firstEmbed) this.firstEmbed = promise;
40814
40877
  const { embeddings, usage } = await promise;
40815
- const result = {
40878
+ return {
40816
40879
  embeddings,
40817
- chunks,
40818
- usage,
40819
- dimension: embeddings[0]?.length
40880
+ usage
40820
40881
  };
40821
- this.embeddingCache.set(key, result);
40822
- return result;
40823
40882
  }
40824
- async saveMessages({ messages, memoryConfig, observabilityContext }) {
40883
+ /**
40884
+ * Metadata of each thread, spread onto that thread's vector rows so `semanticRecall.filter`
40885
+ * can match thread attributes.
40886
+ */
40887
+ async loadThreadMetadata(threadIds) {
40888
+ const memoryStore = await this.getMemoryStore();
40889
+ const metadataByThread = /* @__PURE__ */ new Map();
40890
+ await Promise.all(threadIds.map(async (threadId) => {
40891
+ try {
40892
+ const thread = await memoryStore.getThreadById({ threadId });
40893
+ if (thread?.metadata) metadataByThread.set(threadId, thread.metadata);
40894
+ } catch (error) {
40895
+ const message = error instanceof Error ? error.message : String(error);
40896
+ throw new Error(`Could not fetch metadata for thread ${threadId} while writing semantic recall embeddings: ${message}`);
40897
+ }
40898
+ }));
40899
+ return metadataByThread;
40900
+ }
40901
+ /**
40902
+ * Embeds messages into vector rows in the shared format, without writing them. Every
40903
+ * message-vector write in this class builds its rows here.
40904
+ */
40905
+ async buildMessageVectorRows({ items, embeddedMessages }) {
40906
+ if (items.length === 0) return {
40907
+ ids: [],
40908
+ metadata: [],
40909
+ embeddedEntries: []
40910
+ };
40911
+ if (!this.embedder && !this.isSelfEmbedding) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
40912
+ return buildMessageEmbeddingRows({
40913
+ items,
40914
+ embed: this.isSelfEmbedding ? void 0 : (chunks) => this.embedValues(chunks),
40915
+ maxChunkChars: resolveMaxChunkChars({
40916
+ maxChunkChars: this.configuredMaxChunkChars,
40917
+ embedder: this.embedder
40918
+ }),
40919
+ loadThreadMetadata: (threadIds) => this.loadThreadMetadata(threadIds),
40920
+ embeddedMessages,
40921
+ indexName: embeddedMessages ? this.getEmbeddingIndexName(this.isSelfEmbedding ? void 0 : await this.getEmbeddingDimension()) : void 0
40922
+ });
40923
+ }
40924
+ /** Writes rows from {@link buildMessageVectorRows} into the message index for `config`. */
40925
+ async writeMessageVectorRows({ rows, config, embeddedMessages }) {
40926
+ if (!this.vector || rows.ids.length === 0) return;
40927
+ const { indexName } = await this.createEmbeddingIndex(rows.dimension, config);
40928
+ await upsertMessageVectors(this.vector, indexName, rows, embeddedMessages);
40929
+ }
40930
+ /**
40931
+ * Embeds messages and writes their vector rows.
40932
+ *
40933
+ * @returns Tokens billed by the embedder, if any.
40934
+ */
40935
+ async writeMessageVectors(args) {
40936
+ if (!this.vector) return void 0;
40937
+ const rows = await this.buildMessageVectorRows(args);
40938
+ await this.writeMessageVectorRows({
40939
+ ...args,
40940
+ rows
40941
+ });
40942
+ return rows.usage;
40943
+ }
40944
+ async saveMessages({ messages, memoryConfig, observabilityContext, embeddedMessages }) {
40825
40945
  const span = this.createMemorySpan("save", observabilityContext, void 0, { messageCount: messages.length });
40826
40946
  try {
40827
40947
  const updatedMessages = this.prepareMessagesForPersistence(messages);
40828
40948
  const config = this.getMergedThreadConfig(memoryConfig);
40829
40949
  const dbMessages = new MessageList({ generateMessageId: () => this.generateId() }).add(updatedMessages, "memory").get.all.db();
40830
- const memoryStore = await this.getMemoryStore();
40831
- const result = await memoryStore.saveMessages({ messages: dbMessages });
40832
- let totalTokens = 0;
40833
- if (this.vector && config.semanticRecall) {
40834
- const messagesByThread = /* @__PURE__ */ new Map();
40835
- updatedMessages.forEach((message) => {
40836
- if (message.threadId) {
40837
- if (!messagesByThread.has(message.threadId)) messagesByThread.set(message.threadId, []);
40838
- messagesByThread.get(message.threadId).push(message);
40839
- }
40840
- });
40841
- const threadMetadataMap = /* @__PURE__ */ new Map();
40842
- await Promise.all(Array.from(messagesByThread.keys()).map(async (threadId) => {
40843
- try {
40844
- const thread = await memoryStore.getThreadById({ threadId });
40845
- if (thread?.metadata) threadMetadataMap.set(threadId, thread.metadata);
40846
- } catch (error) {
40847
- const message = error instanceof Error ? error.message : String(error);
40848
- throw new Error(`Could not fetch metadata for thread ${threadId} while saving semantic recall embeddings: ${message}`);
40849
- }
40850
- }));
40851
- const embeddingData = [];
40852
- let dimension;
40853
- await Promise.all(updatedMessages.map(async (message) => {
40854
- let textForEmbedding = null;
40855
- if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
40856
- else if (message.content.parts && message.content.parts.length > 0) {
40857
- const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
40858
- if (joined) textForEmbedding = joined;
40859
- }
40860
- if (!textForEmbedding) return;
40861
- let embeddings = [];
40862
- let documents;
40863
- let chunks;
40864
- if (this.isSelfEmbedding) {
40865
- chunks = this.chunkText(textForEmbedding);
40866
- documents = chunks;
40867
- } else {
40868
- const result = await this.embedMessageContent(textForEmbedding);
40869
- dimension = result.dimension;
40870
- if (result.usage?.tokens) totalTokens += result.usage.tokens;
40871
- embeddings = result.embeddings;
40872
- chunks = result.chunks;
40873
- }
40874
- const threadMetadata = message.threadId ? threadMetadataMap.get(message.threadId) || {} : {};
40875
- embeddingData.push({
40876
- embeddings,
40877
- documents,
40878
- metadata: chunks.map(() => ({
40879
- ...threadMetadata,
40880
- message_id: message.id,
40881
- thread_id: message.threadId,
40882
- resource_id: message.resourceId,
40883
- role: message.role,
40884
- content: textForEmbedding,
40885
- created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
40886
- }))
40887
- });
40888
- }));
40889
- if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
40890
- if (typeof this.vector === `undefined`) throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);
40891
- const { indexName } = await this.createEmbeddingIndex(dimension, config);
40892
- const allVectors = [];
40893
- const allMetadata = [];
40894
- const allDocuments = [];
40895
- for (const data of embeddingData) {
40896
- allVectors.push(...data.embeddings);
40897
- if (data.documents) allDocuments.push(...data.documents);
40898
- allMetadata.push(...data.metadata);
40899
- }
40900
- if (this.isSelfEmbedding) await this.vector.upsert({
40901
- indexName,
40902
- documents: allDocuments,
40903
- metadata: allMetadata
40904
- });
40905
- else await this.vector.upsert({
40906
- indexName,
40907
- vectors: allVectors,
40908
- metadata: allMetadata
40909
- });
40910
- }
40911
- }
40950
+ const result = await (await this.getMemoryStore()).saveMessages({ messages: dbMessages });
40951
+ const usage = this.vector && config.semanticRecall ? await this.writeMessageVectors({
40952
+ items: updatedMessages.map((message) => ({ message })),
40953
+ config,
40954
+ embeddedMessages
40955
+ }) : void 0;
40912
40956
  const saveResult = {
40913
40957
  ...result,
40914
- usage: totalTokens > 0 ? { tokens: totalTokens } : void 0
40958
+ usage
40915
40959
  };
40916
40960
  span?.end({
40917
40961
  output: { success: true },
@@ -41634,51 +41678,6 @@ Notes:
41634
41678
  return collected;
41635
41679
  }
41636
41680
  /**
41637
- * Index a list of messages directly (without querying storage).
41638
- * Used by observe-time indexing to vectorize newly-observed messages.
41639
- */
41640
- async indexMessagesList(messages) {
41641
- if (!this.vector || !this.embedder) return;
41642
- const embeddingData = [];
41643
- let dimension;
41644
- await Promise.all(messages.map(async (message) => {
41645
- let textForEmbedding = null;
41646
- if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
41647
- else if (message.content.parts && message.content.parts.length > 0) {
41648
- const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
41649
- if (joined) textForEmbedding = joined;
41650
- }
41651
- if (!textForEmbedding) return;
41652
- const embedResult = await this.embedMessageContent(textForEmbedding);
41653
- dimension = embedResult.dimension;
41654
- embeddingData.push({
41655
- embeddings: embedResult.embeddings,
41656
- metadata: embedResult.chunks.map(() => ({
41657
- message_id: message.id,
41658
- thread_id: message.threadId,
41659
- resource_id: message.resourceId,
41660
- role: message.role,
41661
- content: textForEmbedding,
41662
- created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
41663
- }))
41664
- });
41665
- }));
41666
- if (embeddingData.length > 0 && dimension !== void 0) {
41667
- const { indexName } = await this.createEmbeddingIndex(dimension);
41668
- const allVectors = [];
41669
- const allMetadata = [];
41670
- for (const data of embeddingData) {
41671
- allVectors.push(...data.embeddings);
41672
- allMetadata.push(...data.metadata);
41673
- }
41674
- await this.vector.upsert({
41675
- indexName,
41676
- vectors: allVectors,
41677
- metadata: allMetadata
41678
- });
41679
- }
41680
- }
41681
- /**
41682
41681
  * Check whether retrieval search (vector-based) is enabled.
41683
41682
  * Returns true when `retrieval: { vector: true }` and Memory has a vector store plus either an
41684
41683
  * embedder or a store that generates embeddings itself.
@@ -41784,43 +41783,19 @@ Notes:
41784
41783
  const messagesWithTextUpdates = [...textForEmbeddingById.keys()].map((id) => ({ id }));
41785
41784
  if (messagesWithTextUpdates.length > 0) {
41786
41785
  const existingMessagesMap = new Map(existing.messages.map((m) => [m.id, m]));
41787
- const embeddingData = [];
41788
- let dimension;
41789
- const messageIdsWithNewEmbeddings = /* @__PURE__ */ new Set();
41790
- const messageIdsWithClearedContent = /* @__PURE__ */ new Set();
41791
- await Promise.all(messagesWithTextUpdates.map(async (message) => {
41792
- const existingMessage = existingMessagesMap.get(message.id);
41793
- if (!existingMessage) return;
41794
- const textForEmbedding = textForEmbeddingById.get(message.id) ?? null;
41795
- if (textForEmbedding) {
41796
- let embeddings = [];
41797
- let documents;
41798
- let chunks;
41799
- if (this.isSelfEmbedding) {
41800
- chunks = this.chunkText(textForEmbedding);
41801
- documents = chunks;
41802
- } else {
41803
- const result = await this.embedMessageContent(textForEmbedding);
41804
- dimension = result.dimension;
41805
- embeddings = result.embeddings;
41806
- chunks = result.chunks;
41807
- }
41808
- embeddingData.push({
41809
- embeddings,
41810
- documents,
41811
- metadata: chunks.map(() => ({
41812
- message_id: message.id,
41813
- thread_id: existingMessage.threadId,
41814
- resource_id: existingMessage.resourceId,
41815
- role: existingMessage.role,
41816
- content: textForEmbedding,
41817
- created_at: existingMessage.createdAt instanceof Date ? existingMessage.createdAt.toISOString() : String(existingMessage.createdAt)
41818
- }))
41819
- });
41820
- messageIdsWithNewEmbeddings.add(message.id);
41821
- } else messageIdsWithClearedContent.add(message.id);
41822
- }));
41823
- const messageIdsNeedingDeletion = /* @__PURE__ */ new Set([...messageIdsWithClearedContent, ...messageIdsWithNewEmbeddings]);
41786
+ const messageIdsNeedingDeletion = /* @__PURE__ */ new Set();
41787
+ const items = [];
41788
+ for (const { id } of messagesWithTextUpdates) {
41789
+ const existingMessage = existingMessagesMap.get(id);
41790
+ if (!existingMessage) continue;
41791
+ messageIdsNeedingDeletion.add(id);
41792
+ const text = textForEmbeddingById.get(id);
41793
+ if (text) items.push({
41794
+ message: existingMessage,
41795
+ text
41796
+ });
41797
+ }
41798
+ const rows = await this.buildMessageVectorRows({ items });
41824
41799
  if (messageIdsNeedingDeletion.size > 0) try {
41825
41800
  const memoryIndexes = await this.getMemoryVectorIndexes([this.messageIndexPrefix]);
41826
41801
  const idsToDelete = [...messageIdsNeedingDeletion];
@@ -41843,27 +41818,10 @@ Notes:
41843
41818
  } catch {
41844
41819
  this.logger.debug("Failed to clean up old vectors during message update");
41845
41820
  }
41846
- if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
41847
- const { indexName } = await this.createEmbeddingIndex(dimension, config);
41848
- const allVectors = [];
41849
- const allMetadata = [];
41850
- const allDocuments = [];
41851
- for (const data of embeddingData) {
41852
- allVectors.push(...data.embeddings);
41853
- if (data.documents) allDocuments.push(...data.documents);
41854
- allMetadata.push(...data.metadata);
41855
- }
41856
- if (this.isSelfEmbedding) await this.vector.upsert({
41857
- indexName,
41858
- documents: allDocuments,
41859
- metadata: allMetadata
41860
- });
41861
- else await this.vector.upsert({
41862
- indexName,
41863
- vectors: allVectors,
41864
- metadata: allMetadata
41865
- });
41866
- }
41821
+ await this.writeMessageVectorRows({
41822
+ rows,
41823
+ config
41824
+ });
41867
41825
  }
41868
41826
  }
41869
41827
  return memoryStore.updateMessages({ messages });
@@ -42128,6 +42086,7 @@ Notes:
42128
42086
  threadId,
42129
42087
  perPage: false
42130
42088
  });
42089
+ const rows = await this.buildMessageVectorRows({ items: messages.map((message) => ({ message })) });
42131
42090
  const messageIndexes = await this.getMemoryVectorIndexes([this.messageIndexPrefix]);
42132
42091
  await Promise.all(messageIndexes.map(async (indexName) => {
42133
42092
  await this.vector.deleteVectors({
@@ -42135,7 +42094,10 @@ Notes:
42135
42094
  filter: { thread_id: threadId }
42136
42095
  });
42137
42096
  }));
42138
- if (messages.length > 0) await this.embedClonedMessages(messages, config);
42097
+ await this.writeMessageVectorRows({
42098
+ rows,
42099
+ config
42100
+ });
42139
42101
  } catch (error) {
42140
42102
  this.logger.error("Failed to migrate semantic-recall vectors during thread transfer", {
42141
42103
  threadId,
@@ -42283,67 +42245,15 @@ Notes:
42283
42245
  return cloned;
42284
42246
  }
42285
42247
  /**
42286
- * Embed cloned messages for semantic recall.
42287
- * This is similar to the embedding logic in saveMessages but operates on already-saved messages.
42248
+ * Embed cloned messages for semantic recall. Cloned messages have new ids, so they get rows of
42249
+ * their own next to the source thread's rows.
42288
42250
  */
42289
42251
  async embedClonedMessages(messages, config) {
42290
42252
  if (!this.vector || !this.embedder && !this.isSelfEmbedding) return;
42291
- const embeddingData = [];
42292
- let dimension;
42293
- await Promise.all(messages.map(async (message) => {
42294
- let textForEmbedding = null;
42295
- if (message.content?.content && typeof message.content.content === "string" && message.content.content.trim() !== "") textForEmbedding = message.content.content;
42296
- else if (message.content?.parts && message.content.parts.length > 0) {
42297
- const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
42298
- if (joined) textForEmbedding = joined;
42299
- }
42300
- if (!textForEmbedding) return;
42301
- let embeddings = [];
42302
- let documents;
42303
- let chunks;
42304
- if (this.isSelfEmbedding) {
42305
- chunks = this.chunkText(textForEmbedding);
42306
- documents = chunks;
42307
- } else {
42308
- const result = await this.embedMessageContent(textForEmbedding);
42309
- dimension = result.dimension;
42310
- embeddings = result.embeddings;
42311
- chunks = result.chunks;
42312
- }
42313
- embeddingData.push({
42314
- embeddings,
42315
- documents,
42316
- metadata: chunks.map(() => ({
42317
- message_id: message.id,
42318
- thread_id: message.threadId,
42319
- resource_id: message.resourceId,
42320
- role: message.role,
42321
- content: textForEmbedding,
42322
- created_at: message.createdAt instanceof Date ? message.createdAt.toISOString() : String(message.createdAt)
42323
- }))
42324
- });
42325
- }));
42326
- if (embeddingData.length > 0 && (this.isSelfEmbedding || dimension !== void 0)) {
42327
- const { indexName } = await this.createEmbeddingIndex(dimension, config);
42328
- const allVectors = [];
42329
- const allMetadata = [];
42330
- const allDocuments = [];
42331
- for (const data of embeddingData) {
42332
- allVectors.push(...data.embeddings);
42333
- if (data.documents) allDocuments.push(...data.documents);
42334
- allMetadata.push(...data.metadata);
42335
- }
42336
- if (this.isSelfEmbedding) await this.vector.upsert({
42337
- indexName,
42338
- documents: allDocuments,
42339
- metadata: allMetadata
42340
- });
42341
- else await this.vector.upsert({
42342
- indexName,
42343
- vectors: allVectors,
42344
- metadata: allMetadata
42345
- });
42346
- }
42253
+ await this.writeMessageVectors({
42254
+ items: messages.map((message) => ({ message })),
42255
+ config
42256
+ });
42347
42257
  }
42348
42258
  /**
42349
42259
  * Get the clone metadata from a thread if it was cloned from another thread.
@@ -42527,4 +42437,4 @@ Notes:
42527
42437
  };
42528
42438
  export { summarizeConversation as A, injectAnchorIds as B, wrapInObservationGroup as C, WorkingMemoryExtractor as D, Subconscious as E, extractCurrentTask as F, OBSERVATION_CONTEXT_INSTRUCTIONS as G, stripEphemeralAnchorIds as H, formatMessagesForObserver as I, OBSERVATION_CONTINUATION_HINT as J, OBSERVATION_CONTEXT_PROMPT as K, hasCurrentTaskSection as L, OBSERVER_SYSTEM_PROMPT as M, buildObserverPrompt as N, deepMergeWorkingMemory as O, buildObserverSystemPrompt as P, optimizeObservationsForContext as R, stripObservationGroups as S, StaleKnowledgeSemanticIndexError as T, Extractor as U, parseAnchorId as V, OBSERVATIONAL_MEMORY_DEFAULTS as W, getObservationContextPrompt as Y, combineObservationGroupRanges as _, extractWorkingMemoryContent as a, reconcileObservationGroupsFromReflection as b, getObservationsAsOf as c, AUTO_MODEL_BY_PROVIDER as d, resolveAutoModelId as f, ModelByInputTokens as g, WorkingMemoryStateProcessor as h, WorkingMemory as i, TokenCounter as j, SUMMARIZE_THREAD_DEFAULTS as k, ObservationalMemoryProcessor as l, WORKING_MEMORY_STATE_PROCESSOR_ID as m, MessageHistory$1 as n, extractWorkingMemoryTags as o, WORKING_MEMORY_STATE_ID as p, OBSERVATION_CONTEXT_PROMPT_THREAD as q, SemanticRecall as r, removeWorkingMemoryTags as s, Memory as t, ObservationalMemory as u, deriveObservationGroupProvenance as v, KnowledgeSemanticIndexCoordinator as w, renderObservationGroupsForReflection as x, parseObservationGroups as y, parseObserverOutput as z };
42529
42439
 
42530
- //# sourceMappingURL=src-BncFunCW.js.map
42440
+ //# sourceMappingURL=src-BL6KZcyR.js.map