@mastra/memory 0.0.0-studio-deploy-20260404182525 → 0.0.0-studio-cli-20260504022012
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/CHANGELOG.md +461 -3
- package/dist/_types/@internal_ai-sdk-v4/dist/index.d.ts +51 -5
- package/dist/{chunk-4FMHSWZD.cjs → chunk-6ODYOMHN.cjs} +1279 -492
- package/dist/chunk-6ODYOMHN.cjs.map +1 -0
- package/dist/{chunk-C7PARRAD.js → chunk-Z5GWA7LB.js} +1280 -493
- package/dist/chunk-Z5GWA7LB.js.map +1 -0
- package/dist/{constants-HXOCZPB7.cjs → constants-PJXB7ZIS.cjs} +2 -2
- package/dist/{constants-HXOCZPB7.cjs.map → constants-PJXB7ZIS.cjs.map} +1 -1
- package/dist/{constants-BDOITAO3.js → constants-XEHPYRDJ.js} +2 -2
- package/dist/{constants-BDOITAO3.js.map → constants-XEHPYRDJ.js.map} +1 -1
- package/dist/docs/SKILL.md +3 -1
- package/dist/docs/assets/SOURCE_MAP.json +47 -59
- package/dist/docs/references/docs-agents-background-tasks.md +242 -0
- package/dist/docs/references/docs-agents-supervisor-agents.md +65 -0
- package/dist/docs/references/docs-memory-memory-processors.md +3 -3
- package/dist/docs/references/docs-memory-message-history.md +8 -2
- package/dist/docs/references/docs-memory-observational-memory.md +65 -8
- package/dist/docs/references/docs-memory-storage.md +1 -2
- package/dist/docs/references/docs-memory-working-memory.md +2 -2
- package/dist/docs/references/reference-memory-clone-utilities.md +4 -2
- package/dist/docs/references/reference-memory-cloneThread.md +4 -2
- package/dist/docs/references/reference-memory-observational-memory.md +4 -0
- package/dist/docs/references/reference-storage-redis.md +266 -0
- package/dist/docs/references/reference-vectors-mongodb.md +0 -2
- package/dist/index.cjs +1168 -553
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +35 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1158 -535
- package/dist/index.js.map +1 -1
- package/dist/{observational-memory-5YDQLKHE.cjs → observational-memory-OVSEK47Z.cjs} +26 -26
- package/dist/{observational-memory-5YDQLKHE.cjs.map → observational-memory-OVSEK47Z.cjs.map} +1 -1
- package/dist/{observational-memory-B7AUSTEY.js → observational-memory-UMDC4VC2.js} +3 -3
- package/dist/{observational-memory-B7AUSTEY.js.map → observational-memory-UMDC4VC2.js.map} +1 -1
- package/dist/processors/index.cjs +24 -24
- package/dist/processors/index.js +1 -1
- package/dist/processors/observational-memory/date-utils.d.ts +6 -0
- package/dist/processors/observational-memory/date-utils.d.ts.map +1 -1
- package/dist/processors/observational-memory/index.d.ts +1 -1
- package/dist/processors/observational-memory/index.d.ts.map +1 -1
- package/dist/processors/observational-memory/markers.d.ts +5 -0
- package/dist/processors/observational-memory/markers.d.ts.map +1 -1
- package/dist/processors/observational-memory/message-utils.d.ts.map +1 -1
- package/dist/processors/observational-memory/model-context.d.ts +10 -0
- package/dist/processors/observational-memory/model-context.d.ts.map +1 -0
- package/dist/processors/observational-memory/observation-strategies/async-buffer.d.ts.map +1 -1
- package/dist/processors/observational-memory/observation-strategies/base.d.ts +3 -3
- package/dist/processors/observational-memory/observation-strategies/base.d.ts.map +1 -1
- package/dist/processors/observational-memory/observation-strategies/types.d.ts +9 -0
- package/dist/processors/observational-memory/observation-strategies/types.d.ts.map +1 -1
- package/dist/processors/observational-memory/observation-turn/step.d.ts.map +1 -1
- package/dist/processors/observational-memory/observation-turn/turn.d.ts +6 -2
- package/dist/processors/observational-memory/observation-turn/turn.d.ts.map +1 -1
- package/dist/processors/observational-memory/observation-turn/types.d.ts +1 -0
- package/dist/processors/observational-memory/observation-turn/types.d.ts.map +1 -1
- package/dist/processors/observational-memory/observational-memory.d.ts +54 -3
- package/dist/processors/observational-memory/observational-memory.d.ts.map +1 -1
- package/dist/processors/observational-memory/observer-agent.d.ts.map +1 -1
- package/dist/processors/observational-memory/processor.d.ts +5 -1
- package/dist/processors/observational-memory/processor.d.ts.map +1 -1
- package/dist/processors/observational-memory/reflector-runner.d.ts +14 -2
- package/dist/processors/observational-memory/reflector-runner.d.ts.map +1 -1
- package/dist/processors/observational-memory/repro-capture.d.ts +8 -0
- package/dist/processors/observational-memory/repro-capture.d.ts.map +1 -1
- package/dist/processors/observational-memory/string-utils.d.ts +13 -0
- package/dist/processors/observational-memory/string-utils.d.ts.map +1 -0
- package/dist/processors/observational-memory/temporal-markers.d.ts +4 -0
- package/dist/processors/observational-memory/temporal-markers.d.ts.map +1 -0
- package/dist/processors/observational-memory/tool-result-helpers.d.ts.map +1 -1
- package/dist/processors/observational-memory/types.d.ts +56 -2
- package/dist/processors/observational-memory/types.d.ts.map +1 -1
- package/dist/tools/om-tools.d.ts +14 -2
- package/dist/tools/om-tools.d.ts.map +1 -1
- package/dist/tools/working-memory.d.ts.map +1 -1
- package/package.json +15 -15
- package/dist/chunk-3PUO6DLX.js +0 -439
- package/dist/chunk-3PUO6DLX.js.map +0 -1
- package/dist/chunk-4FMHSWZD.cjs.map +0 -1
- package/dist/chunk-C7PARRAD.js.map +0 -1
- package/dist/chunk-CK4U3AYR.cjs +0 -84
- package/dist/chunk-CK4U3AYR.cjs.map +0 -1
- package/dist/chunk-DAJJSFVA.cjs +0 -441
- package/dist/chunk-DAJJSFVA.cjs.map +0 -1
- package/dist/chunk-DGUM43GV.js +0 -10
- package/dist/chunk-DGUM43GV.js.map +0 -1
- package/dist/chunk-EQ4M72KU.js +0 -439
- package/dist/chunk-EQ4M72KU.js.map +0 -1
- package/dist/chunk-IDRQZVB4.cjs +0 -84
- package/dist/chunk-IDRQZVB4.cjs.map +0 -1
- package/dist/chunk-JEQ2X3Z6.cjs +0 -12
- package/dist/chunk-JEQ2X3Z6.cjs.map +0 -1
- package/dist/chunk-RC6RZVYE.js +0 -79
- package/dist/chunk-RC6RZVYE.js.map +0 -1
- package/dist/chunk-SVPZMV27.js +0 -79
- package/dist/chunk-SVPZMV27.js.map +0 -1
- package/dist/chunk-ZD3BKU5O.cjs +0 -441
- package/dist/chunk-ZD3BKU5O.cjs.map +0 -1
- package/dist/token-APYSY3BW-2DN6RAUY.js +0 -61
- package/dist/token-APYSY3BW-2DN6RAUY.js.map +0 -1
- package/dist/token-APYSY3BW-POD4OUWN.cjs +0 -63
- package/dist/token-APYSY3BW-POD4OUWN.cjs.map +0 -1
- package/dist/token-APYSY3BW-YTVQELJT.js +0 -61
- package/dist/token-APYSY3BW-YTVQELJT.js.map +0 -1
- package/dist/token-APYSY3BW-ZQ7TMBY7.cjs +0 -63
- package/dist/token-APYSY3BW-ZQ7TMBY7.cjs.map +0 -1
- package/dist/token-util-RMHT2CPJ-6TGPE335.cjs +0 -10
- package/dist/token-util-RMHT2CPJ-6TGPE335.cjs.map +0 -1
- package/dist/token-util-RMHT2CPJ-77HHGIQN.cjs +0 -10
- package/dist/token-util-RMHT2CPJ-77HHGIQN.cjs.map +0 -1
- package/dist/token-util-RMHT2CPJ-RJEA3FAN.js +0 -8
- package/dist/token-util-RMHT2CPJ-RJEA3FAN.js.map +0 -1
- package/dist/token-util-RMHT2CPJ-WJZ2SYAR.js +0 -8
- package/dist/token-util-RMHT2CPJ-WJZ2SYAR.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,15 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
import { truncateStringByTokens, resolveToolResultValue, formatToolResultForObserver } from './chunk-C7PARRAD.js';
|
|
4
|
-
export { ModelByInputTokens, getObservationsAsOf } from './chunk-C7PARRAD.js';
|
|
1
|
+
import { truncateStringByTokens, resolveToolResultValue, formatToolResultForObserver } from './chunk-Z5GWA7LB.js';
|
|
2
|
+
export { ModelByInputTokens, getObservationsAsOf } from './chunk-Z5GWA7LB.js';
|
|
5
3
|
import { ZodFirstPartyTypeKind } from 'zod/v3';
|
|
6
4
|
import { z } from 'zod';
|
|
7
5
|
import * as z4 from 'zod/v4';
|
|
8
6
|
import { z as z$1 } from 'zod/v4';
|
|
9
7
|
import { MessageList } from '@mastra/core/agent';
|
|
10
8
|
import { coreFeatures } from '@mastra/core/features';
|
|
11
|
-
import { MastraMemory
|
|
12
|
-
|
|
9
|
+
import { MastraMemory } from '@mastra/core/memory';
|
|
10
|
+
import { EntityType, SpanType } from '@mastra/core/observability';
|
|
13
11
|
import { generateEmptyFromSchema } from '@mastra/core/utils';
|
|
14
12
|
import { isStandardSchemaWithJSON, toStandardSchema, standardSchemaToJSONSchema } from '@mastra/schema-compat/schema';
|
|
15
13
|
import { Mutex } from 'async-mutex';
|
|
@@ -26,7 +24,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
|
26
24
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
27
25
|
var __getProtoOf = Object.getPrototypeOf;
|
|
28
26
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
29
|
-
var
|
|
27
|
+
var __commonJS = (cb, mod) => function __require2() {
|
|
30
28
|
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
31
29
|
};
|
|
32
30
|
var __copyProps = (to, from, except, desc) => {
|
|
@@ -37,7 +35,7 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
37
35
|
}
|
|
38
36
|
return to;
|
|
39
37
|
};
|
|
40
|
-
var
|
|
38
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
41
39
|
// If the importer is in node compatibility mode or this is not an ESM
|
|
42
40
|
// file that has been converted to a CommonJS file using a Babel-
|
|
43
41
|
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
@@ -45,7 +43,7 @@ var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create(__g
|
|
|
45
43
|
__defProp(target, "default", { value: mod, enumerable: true }),
|
|
46
44
|
mod
|
|
47
45
|
));
|
|
48
|
-
var require_secure_json_parse =
|
|
46
|
+
var require_secure_json_parse = __commonJS({
|
|
49
47
|
"../../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports$1, module) {
|
|
50
48
|
var hasBuffer = typeof Buffer !== "undefined";
|
|
51
49
|
var suspectProtoRx3 = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
|
|
@@ -316,7 +314,7 @@ var customAlphabet = (alphabet, defaultSize = 21) => {
|
|
|
316
314
|
return id;
|
|
317
315
|
};
|
|
318
316
|
};
|
|
319
|
-
var import_secure_json_parse =
|
|
317
|
+
var import_secure_json_parse = __toESM(require_secure_json_parse());
|
|
320
318
|
function convertAsyncIteratorToReadableStream(iterator) {
|
|
321
319
|
return new ReadableStream({
|
|
322
320
|
/**
|
|
@@ -4563,7 +4561,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
|
|
|
4563
4561
|
);
|
|
4564
4562
|
return Object.fromEntries(normalizedHeaders.entries());
|
|
4565
4563
|
}
|
|
4566
|
-
var VERSION2 = "3.0.
|
|
4564
|
+
var VERSION2 = "3.0.23";
|
|
4567
4565
|
var getOriginalFetch = () => globalThis.fetch;
|
|
4568
4566
|
var getFromApi = async ({
|
|
4569
4567
|
url,
|
|
@@ -6225,138 +6223,17 @@ function asSchema2(schema) {
|
|
|
6225
6223
|
function withoutTrailingSlash(url) {
|
|
6226
6224
|
return url == null ? void 0 : url.replace(/\/$/, "");
|
|
6227
6225
|
}
|
|
6228
|
-
|
|
6229
|
-
|
|
6230
|
-
|
|
6231
|
-
|
|
6232
|
-
|
|
6233
|
-
|
|
6234
|
-
|
|
6235
|
-
|
|
6236
|
-
__defProp22(target, name163, { get: all[name163], enumerable: true });
|
|
6237
|
-
};
|
|
6238
|
-
var __copyProps2 = (to, from, except, desc) => {
|
|
6239
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
6240
|
-
for (let key of __getOwnPropNames2(from))
|
|
6241
|
-
if (!__hasOwnProp2.call(to, key) && key !== except)
|
|
6242
|
-
__defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
|
|
6243
|
-
}
|
|
6244
|
-
return to;
|
|
6245
|
-
};
|
|
6246
|
-
var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
|
|
6247
|
-
var get_context_exports = {};
|
|
6248
|
-
__export22(get_context_exports, {
|
|
6249
|
-
SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,
|
|
6250
|
-
getContext: () => getContext3
|
|
6251
|
-
});
|
|
6252
|
-
module.exports = __toCommonJS(get_context_exports);
|
|
6253
|
-
var SYMBOL_FOR_REQ_CONTEXT = /* @__PURE__ */ Symbol.for("@vercel/request-context");
|
|
6254
|
-
function getContext3() {
|
|
6255
|
-
const fromSymbol = globalThis;
|
|
6256
|
-
return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
|
|
6257
|
-
}
|
|
6258
|
-
}
|
|
6259
|
-
});
|
|
6260
|
-
var require_get_vercel_oidc_token = __commonJS({
|
|
6261
|
-
"../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports$1, module) {
|
|
6262
|
-
var __defProp22 = Object.defineProperty;
|
|
6263
|
-
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
6264
|
-
var __getOwnPropNames2 = Object.getOwnPropertyNames;
|
|
6265
|
-
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
|
6266
|
-
var __export22 = (target, all) => {
|
|
6267
|
-
for (var name163 in all)
|
|
6268
|
-
__defProp22(target, name163, { get: all[name163], enumerable: true });
|
|
6269
|
-
};
|
|
6270
|
-
var __copyProps2 = (to, from, except, desc) => {
|
|
6271
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
6272
|
-
for (let key of __getOwnPropNames2(from))
|
|
6273
|
-
if (!__hasOwnProp2.call(to, key) && key !== except)
|
|
6274
|
-
__defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
|
|
6275
|
-
}
|
|
6276
|
-
return to;
|
|
6277
|
-
};
|
|
6278
|
-
var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
|
|
6279
|
-
var get_vercel_oidc_token_exports = {};
|
|
6280
|
-
__export22(get_vercel_oidc_token_exports, {
|
|
6281
|
-
getVercelOidcToken: () => getVercelOidcToken3,
|
|
6282
|
-
getVercelOidcTokenSync: () => getVercelOidcTokenSync2
|
|
6283
|
-
});
|
|
6284
|
-
module.exports = __toCommonJS(get_vercel_oidc_token_exports);
|
|
6285
|
-
var import_get_context = require_get_context();
|
|
6286
|
-
var import_token_error = require_token_error();
|
|
6287
|
-
async function getVercelOidcToken3() {
|
|
6288
|
-
let token = "";
|
|
6289
|
-
let err;
|
|
6290
|
-
try {
|
|
6291
|
-
token = getVercelOidcTokenSync2();
|
|
6292
|
-
} catch (error) {
|
|
6293
|
-
err = error;
|
|
6294
|
-
}
|
|
6295
|
-
try {
|
|
6296
|
-
const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
|
|
6297
|
-
await import('./token-util-RMHT2CPJ-WJZ2SYAR.js'),
|
|
6298
|
-
await import('./token-APYSY3BW-YTVQELJT.js')
|
|
6299
|
-
]);
|
|
6300
|
-
if (!token || isExpired(getTokenPayload(token))) {
|
|
6301
|
-
await refreshToken();
|
|
6302
|
-
token = getVercelOidcTokenSync2();
|
|
6303
|
-
}
|
|
6304
|
-
} catch (error) {
|
|
6305
|
-
let message = err instanceof Error ? err.message : "";
|
|
6306
|
-
if (error instanceof Error) {
|
|
6307
|
-
message = `${message}
|
|
6308
|
-
${error.message}`;
|
|
6309
|
-
}
|
|
6310
|
-
if (message) {
|
|
6311
|
-
throw new import_token_error.VercelOidcTokenError(message);
|
|
6312
|
-
}
|
|
6313
|
-
throw error;
|
|
6314
|
-
}
|
|
6315
|
-
return token;
|
|
6316
|
-
}
|
|
6317
|
-
function getVercelOidcTokenSync2() {
|
|
6318
|
-
const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
|
|
6319
|
-
if (!token) {
|
|
6320
|
-
throw new Error(
|
|
6321
|
-
`The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`
|
|
6322
|
-
);
|
|
6323
|
-
}
|
|
6324
|
-
return token;
|
|
6325
|
-
}
|
|
6326
|
-
}
|
|
6327
|
-
});
|
|
6328
|
-
var require_dist = __commonJS({
|
|
6329
|
-
"../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/index.js"(exports$1, module) {
|
|
6330
|
-
var __defProp22 = Object.defineProperty;
|
|
6331
|
-
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
6332
|
-
var __getOwnPropNames2 = Object.getOwnPropertyNames;
|
|
6333
|
-
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
|
6334
|
-
var __export22 = (target, all) => {
|
|
6335
|
-
for (var name163 in all)
|
|
6336
|
-
__defProp22(target, name163, { get: all[name163], enumerable: true });
|
|
6337
|
-
};
|
|
6338
|
-
var __copyProps2 = (to, from, except, desc) => {
|
|
6339
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
6340
|
-
for (let key of __getOwnPropNames2(from))
|
|
6341
|
-
if (!__hasOwnProp2.call(to, key) && key !== except)
|
|
6342
|
-
__defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
|
|
6343
|
-
}
|
|
6344
|
-
return to;
|
|
6345
|
-
};
|
|
6346
|
-
var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
|
|
6347
|
-
var src_exports = {};
|
|
6348
|
-
__export22(src_exports, {
|
|
6349
|
-
getContext: () => import_get_context.getContext,
|
|
6350
|
-
getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
|
|
6351
|
-
getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync
|
|
6352
|
-
});
|
|
6353
|
-
module.exports = __toCommonJS(src_exports);
|
|
6354
|
-
var import_get_vercel_oidc_token = require_get_vercel_oidc_token();
|
|
6355
|
-
var import_get_context = require_get_context();
|
|
6226
|
+
function getContext() {
|
|
6227
|
+
return {
|
|
6228
|
+
headers: {}
|
|
6229
|
+
};
|
|
6230
|
+
}
|
|
6231
|
+
async function getVercelOidcToken() {
|
|
6232
|
+
if (process.env.VERCEL_OIDC_TOKEN) {
|
|
6233
|
+
return process.env.VERCEL_OIDC_TOKEN ?? "";
|
|
6356
6234
|
}
|
|
6357
|
-
|
|
6358
|
-
|
|
6359
|
-
var import_oidc2 = __toESM(require_dist(), 1);
|
|
6235
|
+
throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.");
|
|
6236
|
+
}
|
|
6360
6237
|
var marker18 = "vercel.ai.gateway.error";
|
|
6361
6238
|
var symbol18 = Symbol.for(marker18);
|
|
6362
6239
|
var _a18;
|
|
@@ -6731,6 +6608,7 @@ async function parseAuthMethod(headers) {
|
|
|
6731
6608
|
var gatewayAuthMethodSchema = lazyValidator(
|
|
6732
6609
|
() => zodSchema2(z$1.union([z$1.literal("api-key"), z$1.literal("oidc")]))
|
|
6733
6610
|
);
|
|
6611
|
+
var KNOWN_MODEL_TYPES = ["embedding", "image", "language"];
|
|
6734
6612
|
var GatewayFetchMetadata = class {
|
|
6735
6613
|
constructor(config) {
|
|
6736
6614
|
this.config = config;
|
|
@@ -6801,8 +6679,12 @@ var gatewayAvailableModelsResponseSchema = lazyValidator(
|
|
|
6801
6679
|
provider: z$1.string(),
|
|
6802
6680
|
modelId: z$1.string()
|
|
6803
6681
|
}),
|
|
6804
|
-
modelType: z$1.
|
|
6682
|
+
modelType: z$1.string().nullish()
|
|
6805
6683
|
})
|
|
6684
|
+
).transform(
|
|
6685
|
+
(models) => models.filter(
|
|
6686
|
+
(m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType)
|
|
6687
|
+
)
|
|
6806
6688
|
)
|
|
6807
6689
|
})
|
|
6808
6690
|
)
|
|
@@ -6818,6 +6700,187 @@ var gatewayCreditsResponseSchema = lazyValidator(
|
|
|
6818
6700
|
}))
|
|
6819
6701
|
)
|
|
6820
6702
|
);
|
|
6703
|
+
var GatewaySpendReport = class {
|
|
6704
|
+
constructor(config) {
|
|
6705
|
+
this.config = config;
|
|
6706
|
+
}
|
|
6707
|
+
async getSpendReport(params) {
|
|
6708
|
+
try {
|
|
6709
|
+
const baseUrl = new URL(this.config.baseURL);
|
|
6710
|
+
const searchParams = new URLSearchParams();
|
|
6711
|
+
searchParams.set("start_date", params.startDate);
|
|
6712
|
+
searchParams.set("end_date", params.endDate);
|
|
6713
|
+
if (params.groupBy) {
|
|
6714
|
+
searchParams.set("group_by", params.groupBy);
|
|
6715
|
+
}
|
|
6716
|
+
if (params.datePart) {
|
|
6717
|
+
searchParams.set("date_part", params.datePart);
|
|
6718
|
+
}
|
|
6719
|
+
if (params.userId) {
|
|
6720
|
+
searchParams.set("user_id", params.userId);
|
|
6721
|
+
}
|
|
6722
|
+
if (params.model) {
|
|
6723
|
+
searchParams.set("model", params.model);
|
|
6724
|
+
}
|
|
6725
|
+
if (params.provider) {
|
|
6726
|
+
searchParams.set("provider", params.provider);
|
|
6727
|
+
}
|
|
6728
|
+
if (params.credentialType) {
|
|
6729
|
+
searchParams.set("credential_type", params.credentialType);
|
|
6730
|
+
}
|
|
6731
|
+
if (params.tags && params.tags.length > 0) {
|
|
6732
|
+
searchParams.set("tags", params.tags.join(","));
|
|
6733
|
+
}
|
|
6734
|
+
const { value } = await getFromApi({
|
|
6735
|
+
url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
|
|
6736
|
+
headers: await resolve(this.config.headers()),
|
|
6737
|
+
successfulResponseHandler: createJsonResponseHandler(
|
|
6738
|
+
gatewaySpendReportResponseSchema
|
|
6739
|
+
),
|
|
6740
|
+
failedResponseHandler: createJsonErrorResponseHandler({
|
|
6741
|
+
errorSchema: z$1.any(),
|
|
6742
|
+
errorToMessage: (data) => data
|
|
6743
|
+
}),
|
|
6744
|
+
fetch: this.config.fetch
|
|
6745
|
+
});
|
|
6746
|
+
return value;
|
|
6747
|
+
} catch (error) {
|
|
6748
|
+
throw await asGatewayError(error);
|
|
6749
|
+
}
|
|
6750
|
+
}
|
|
6751
|
+
};
|
|
6752
|
+
var gatewaySpendReportResponseSchema = lazySchema(
|
|
6753
|
+
() => zodSchema2(
|
|
6754
|
+
z$1.object({
|
|
6755
|
+
results: z$1.array(
|
|
6756
|
+
z$1.object({
|
|
6757
|
+
day: z$1.string().optional(),
|
|
6758
|
+
hour: z$1.string().optional(),
|
|
6759
|
+
user: z$1.string().optional(),
|
|
6760
|
+
model: z$1.string().optional(),
|
|
6761
|
+
tag: z$1.string().optional(),
|
|
6762
|
+
provider: z$1.string().optional(),
|
|
6763
|
+
credential_type: z$1.enum(["byok", "system"]).optional(),
|
|
6764
|
+
total_cost: z$1.number(),
|
|
6765
|
+
market_cost: z$1.number().optional(),
|
|
6766
|
+
input_tokens: z$1.number().optional(),
|
|
6767
|
+
output_tokens: z$1.number().optional(),
|
|
6768
|
+
cached_input_tokens: z$1.number().optional(),
|
|
6769
|
+
cache_creation_input_tokens: z$1.number().optional(),
|
|
6770
|
+
reasoning_tokens: z$1.number().optional(),
|
|
6771
|
+
request_count: z$1.number().optional()
|
|
6772
|
+
}).transform(
|
|
6773
|
+
({
|
|
6774
|
+
credential_type,
|
|
6775
|
+
total_cost,
|
|
6776
|
+
market_cost,
|
|
6777
|
+
input_tokens,
|
|
6778
|
+
output_tokens,
|
|
6779
|
+
cached_input_tokens,
|
|
6780
|
+
cache_creation_input_tokens,
|
|
6781
|
+
reasoning_tokens,
|
|
6782
|
+
request_count,
|
|
6783
|
+
...rest
|
|
6784
|
+
}) => ({
|
|
6785
|
+
...rest,
|
|
6786
|
+
...credential_type !== void 0 ? { credentialType: credential_type } : {},
|
|
6787
|
+
totalCost: total_cost,
|
|
6788
|
+
...market_cost !== void 0 ? { marketCost: market_cost } : {},
|
|
6789
|
+
...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},
|
|
6790
|
+
...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},
|
|
6791
|
+
...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},
|
|
6792
|
+
...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
|
|
6793
|
+
...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},
|
|
6794
|
+
...request_count !== void 0 ? { requestCount: request_count } : {}
|
|
6795
|
+
})
|
|
6796
|
+
)
|
|
6797
|
+
)
|
|
6798
|
+
})
|
|
6799
|
+
)
|
|
6800
|
+
);
|
|
6801
|
+
var GatewayGenerationInfoFetcher = class {
|
|
6802
|
+
constructor(config) {
|
|
6803
|
+
this.config = config;
|
|
6804
|
+
}
|
|
6805
|
+
async getGenerationInfo(params) {
|
|
6806
|
+
try {
|
|
6807
|
+
const baseUrl = new URL(this.config.baseURL);
|
|
6808
|
+
const { value } = await getFromApi({
|
|
6809
|
+
url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
|
|
6810
|
+
headers: await resolve(this.config.headers()),
|
|
6811
|
+
successfulResponseHandler: createJsonResponseHandler(
|
|
6812
|
+
gatewayGenerationInfoResponseSchema
|
|
6813
|
+
),
|
|
6814
|
+
failedResponseHandler: createJsonErrorResponseHandler({
|
|
6815
|
+
errorSchema: z$1.any(),
|
|
6816
|
+
errorToMessage: (data) => data
|
|
6817
|
+
}),
|
|
6818
|
+
fetch: this.config.fetch
|
|
6819
|
+
});
|
|
6820
|
+
return value;
|
|
6821
|
+
} catch (error) {
|
|
6822
|
+
throw await asGatewayError(error);
|
|
6823
|
+
}
|
|
6824
|
+
}
|
|
6825
|
+
};
|
|
6826
|
+
var gatewayGenerationInfoResponseSchema = lazySchema(
|
|
6827
|
+
() => zodSchema2(
|
|
6828
|
+
z$1.object({
|
|
6829
|
+
data: z$1.object({
|
|
6830
|
+
id: z$1.string(),
|
|
6831
|
+
total_cost: z$1.number(),
|
|
6832
|
+
upstream_inference_cost: z$1.number(),
|
|
6833
|
+
usage: z$1.number(),
|
|
6834
|
+
created_at: z$1.string(),
|
|
6835
|
+
model: z$1.string(),
|
|
6836
|
+
is_byok: z$1.boolean(),
|
|
6837
|
+
provider_name: z$1.string(),
|
|
6838
|
+
streamed: z$1.boolean(),
|
|
6839
|
+
finish_reason: z$1.string(),
|
|
6840
|
+
latency: z$1.number(),
|
|
6841
|
+
generation_time: z$1.number(),
|
|
6842
|
+
native_tokens_prompt: z$1.number(),
|
|
6843
|
+
native_tokens_completion: z$1.number(),
|
|
6844
|
+
native_tokens_reasoning: z$1.number(),
|
|
6845
|
+
native_tokens_cached: z$1.number(),
|
|
6846
|
+
native_tokens_cache_creation: z$1.number(),
|
|
6847
|
+
billable_web_search_calls: z$1.number()
|
|
6848
|
+
}).transform(
|
|
6849
|
+
({
|
|
6850
|
+
total_cost,
|
|
6851
|
+
upstream_inference_cost,
|
|
6852
|
+
created_at,
|
|
6853
|
+
is_byok,
|
|
6854
|
+
provider_name,
|
|
6855
|
+
finish_reason,
|
|
6856
|
+
generation_time,
|
|
6857
|
+
native_tokens_prompt,
|
|
6858
|
+
native_tokens_completion,
|
|
6859
|
+
native_tokens_reasoning,
|
|
6860
|
+
native_tokens_cached,
|
|
6861
|
+
native_tokens_cache_creation,
|
|
6862
|
+
billable_web_search_calls,
|
|
6863
|
+
...rest
|
|
6864
|
+
}) => ({
|
|
6865
|
+
...rest,
|
|
6866
|
+
totalCost: total_cost,
|
|
6867
|
+
upstreamInferenceCost: upstream_inference_cost,
|
|
6868
|
+
createdAt: created_at,
|
|
6869
|
+
isByok: is_byok,
|
|
6870
|
+
providerName: provider_name,
|
|
6871
|
+
finishReason: finish_reason,
|
|
6872
|
+
generationTime: generation_time,
|
|
6873
|
+
promptTokens: native_tokens_prompt,
|
|
6874
|
+
completionTokens: native_tokens_completion,
|
|
6875
|
+
reasoningTokens: native_tokens_reasoning,
|
|
6876
|
+
cachedTokens: native_tokens_cached,
|
|
6877
|
+
cacheCreationTokens: native_tokens_cache_creation,
|
|
6878
|
+
billableWebSearchCalls: billable_web_search_calls
|
|
6879
|
+
})
|
|
6880
|
+
)
|
|
6881
|
+
}).transform(({ data }) => data)
|
|
6882
|
+
)
|
|
6883
|
+
);
|
|
6821
6884
|
var GatewayLanguageModel = class {
|
|
6822
6885
|
constructor(modelId, config) {
|
|
6823
6886
|
this.modelId = modelId;
|
|
@@ -7318,9 +7381,9 @@ var gatewayTools = {
|
|
|
7318
7381
|
};
|
|
7319
7382
|
async function getVercelRequestId() {
|
|
7320
7383
|
var _a932;
|
|
7321
|
-
return (_a932 =
|
|
7384
|
+
return (_a932 = getContext().headers) == null ? void 0 : _a932["x-vercel-id"];
|
|
7322
7385
|
}
|
|
7323
|
-
var VERSION3 = "2.0.
|
|
7386
|
+
var VERSION3 = "2.0.82";
|
|
7324
7387
|
var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
|
|
7325
7388
|
function createGatewayProvider(options = {}) {
|
|
7326
7389
|
var _a932, _b93;
|
|
@@ -7418,6 +7481,30 @@ function createGatewayProvider(options = {}) {
|
|
|
7418
7481
|
);
|
|
7419
7482
|
});
|
|
7420
7483
|
};
|
|
7484
|
+
const getSpendReport = async (params) => {
|
|
7485
|
+
return new GatewaySpendReport({
|
|
7486
|
+
baseURL,
|
|
7487
|
+
headers: getHeaders,
|
|
7488
|
+
fetch: options.fetch
|
|
7489
|
+
}).getSpendReport(params).catch(async (error) => {
|
|
7490
|
+
throw await asGatewayError(
|
|
7491
|
+
error,
|
|
7492
|
+
await parseAuthMethod(await getHeaders())
|
|
7493
|
+
);
|
|
7494
|
+
});
|
|
7495
|
+
};
|
|
7496
|
+
const getGenerationInfo = async (params) => {
|
|
7497
|
+
return new GatewayGenerationInfoFetcher({
|
|
7498
|
+
baseURL,
|
|
7499
|
+
headers: getHeaders,
|
|
7500
|
+
fetch: options.fetch
|
|
7501
|
+
}).getGenerationInfo(params).catch(async (error) => {
|
|
7502
|
+
throw await asGatewayError(
|
|
7503
|
+
error,
|
|
7504
|
+
await parseAuthMethod(await getHeaders())
|
|
7505
|
+
);
|
|
7506
|
+
});
|
|
7507
|
+
};
|
|
7421
7508
|
const provider = function(modelId) {
|
|
7422
7509
|
if (new.target) {
|
|
7423
7510
|
throw new Error(
|
|
@@ -7428,6 +7515,8 @@ function createGatewayProvider(options = {}) {
|
|
|
7428
7515
|
};
|
|
7429
7516
|
provider.getAvailableModels = getAvailableModels;
|
|
7430
7517
|
provider.getCredits = getCredits;
|
|
7518
|
+
provider.getSpendReport = getSpendReport;
|
|
7519
|
+
provider.getGenerationInfo = getGenerationInfo;
|
|
7431
7520
|
provider.imageModel = (modelId) => {
|
|
7432
7521
|
return new GatewayImageModel(modelId, {
|
|
7433
7522
|
provider: "gateway",
|
|
@@ -7463,7 +7552,7 @@ async function getGatewayAuthToken(options) {
|
|
|
7463
7552
|
};
|
|
7464
7553
|
}
|
|
7465
7554
|
try {
|
|
7466
|
-
const oidcToken = await
|
|
7555
|
+
const oidcToken = await getVercelOidcToken();
|
|
7467
7556
|
return {
|
|
7468
7557
|
token: oidcToken,
|
|
7469
7558
|
authMethod: "oidc"
|
|
@@ -8281,7 +8370,7 @@ function getGlobalProvider() {
|
|
|
8281
8370
|
var _a163;
|
|
8282
8371
|
return (_a163 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a163 : gateway;
|
|
8283
8372
|
}
|
|
8284
|
-
var VERSION32 = "5.0.
|
|
8373
|
+
var VERSION32 = "5.0.179";
|
|
8285
8374
|
var dataContentSchema2 = z$1.union([
|
|
8286
8375
|
z$1.string(),
|
|
8287
8376
|
z$1.instanceof(Uint8Array),
|
|
@@ -9892,7 +9981,7 @@ function withUserAgentSuffix2(headers, ...userAgentSuffixParts) {
|
|
|
9892
9981
|
);
|
|
9893
9982
|
return Object.fromEntries(normalizedHeaders.entries());
|
|
9894
9983
|
}
|
|
9895
|
-
var VERSION4 = "4.0.
|
|
9984
|
+
var VERSION4 = "4.0.23";
|
|
9896
9985
|
var getOriginalFetch3 = () => globalThis.fetch;
|
|
9897
9986
|
var getFromApi2 = async ({
|
|
9898
9987
|
url,
|
|
@@ -11552,138 +11641,17 @@ var createJsonResponseHandler2 = (responseSchema) => async ({ response, url, req
|
|
|
11552
11641
|
function withoutTrailingSlash2(url) {
|
|
11553
11642
|
return url == null ? void 0 : url.replace(/\/$/, "");
|
|
11554
11643
|
}
|
|
11555
|
-
|
|
11556
|
-
|
|
11557
|
-
|
|
11558
|
-
|
|
11559
|
-
|
|
11560
|
-
|
|
11561
|
-
|
|
11562
|
-
|
|
11563
|
-
__defProp22(target, name21, { get: all[name21], enumerable: true });
|
|
11564
|
-
};
|
|
11565
|
-
var __copyProps2 = (to, from, except, desc) => {
|
|
11566
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
11567
|
-
for (let key of __getOwnPropNames2(from))
|
|
11568
|
-
if (!__hasOwnProp2.call(to, key) && key !== except)
|
|
11569
|
-
__defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
|
|
11570
|
-
}
|
|
11571
|
-
return to;
|
|
11572
|
-
};
|
|
11573
|
-
var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
|
|
11574
|
-
var get_context_exports = {};
|
|
11575
|
-
__export22(get_context_exports, {
|
|
11576
|
-
SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,
|
|
11577
|
-
getContext: () => getContext3
|
|
11578
|
-
});
|
|
11579
|
-
module.exports = __toCommonJS(get_context_exports);
|
|
11580
|
-
var SYMBOL_FOR_REQ_CONTEXT = /* @__PURE__ */ Symbol.for("@vercel/request-context");
|
|
11581
|
-
function getContext3() {
|
|
11582
|
-
const fromSymbol = globalThis;
|
|
11583
|
-
return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
|
|
11584
|
-
}
|
|
11585
|
-
}
|
|
11586
|
-
});
|
|
11587
|
-
var require_get_vercel_oidc_token2 = __commonJS$1({
|
|
11588
|
-
"../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports$1, module) {
|
|
11589
|
-
var __defProp22 = Object.defineProperty;
|
|
11590
|
-
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
11591
|
-
var __getOwnPropNames2 = Object.getOwnPropertyNames;
|
|
11592
|
-
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
|
11593
|
-
var __export22 = (target, all) => {
|
|
11594
|
-
for (var name21 in all)
|
|
11595
|
-
__defProp22(target, name21, { get: all[name21], enumerable: true });
|
|
11596
|
-
};
|
|
11597
|
-
var __copyProps2 = (to, from, except, desc) => {
|
|
11598
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
11599
|
-
for (let key of __getOwnPropNames2(from))
|
|
11600
|
-
if (!__hasOwnProp2.call(to, key) && key !== except)
|
|
11601
|
-
__defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
|
|
11602
|
-
}
|
|
11603
|
-
return to;
|
|
11604
|
-
};
|
|
11605
|
-
var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
|
|
11606
|
-
var get_vercel_oidc_token_exports = {};
|
|
11607
|
-
__export22(get_vercel_oidc_token_exports, {
|
|
11608
|
-
getVercelOidcToken: () => getVercelOidcToken3,
|
|
11609
|
-
getVercelOidcTokenSync: () => getVercelOidcTokenSync2
|
|
11610
|
-
});
|
|
11611
|
-
module.exports = __toCommonJS(get_vercel_oidc_token_exports);
|
|
11612
|
-
var import_get_context = require_get_context2();
|
|
11613
|
-
var import_token_error = require_token_error$1();
|
|
11614
|
-
async function getVercelOidcToken3() {
|
|
11615
|
-
let token = "";
|
|
11616
|
-
let err;
|
|
11617
|
-
try {
|
|
11618
|
-
token = getVercelOidcTokenSync2();
|
|
11619
|
-
} catch (error) {
|
|
11620
|
-
err = error;
|
|
11621
|
-
}
|
|
11622
|
-
try {
|
|
11623
|
-
const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
|
|
11624
|
-
await import('./token-util-RMHT2CPJ-RJEA3FAN.js'),
|
|
11625
|
-
await import('./token-APYSY3BW-2DN6RAUY.js')
|
|
11626
|
-
]);
|
|
11627
|
-
if (!token || isExpired(getTokenPayload(token))) {
|
|
11628
|
-
await refreshToken();
|
|
11629
|
-
token = getVercelOidcTokenSync2();
|
|
11630
|
-
}
|
|
11631
|
-
} catch (error) {
|
|
11632
|
-
let message = err instanceof Error ? err.message : "";
|
|
11633
|
-
if (error instanceof Error) {
|
|
11634
|
-
message = `${message}
|
|
11635
|
-
${error.message}`;
|
|
11636
|
-
}
|
|
11637
|
-
if (message) {
|
|
11638
|
-
throw new import_token_error.VercelOidcTokenError(message);
|
|
11639
|
-
}
|
|
11640
|
-
throw error;
|
|
11641
|
-
}
|
|
11642
|
-
return token;
|
|
11643
|
-
}
|
|
11644
|
-
function getVercelOidcTokenSync2() {
|
|
11645
|
-
const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
|
|
11646
|
-
if (!token) {
|
|
11647
|
-
throw new Error(
|
|
11648
|
-
`The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`
|
|
11649
|
-
);
|
|
11650
|
-
}
|
|
11651
|
-
return token;
|
|
11652
|
-
}
|
|
11653
|
-
}
|
|
11654
|
-
});
|
|
11655
|
-
var require_dist2 = __commonJS$1({
|
|
11656
|
-
"../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/index.js"(exports$1, module) {
|
|
11657
|
-
var __defProp22 = Object.defineProperty;
|
|
11658
|
-
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
11659
|
-
var __getOwnPropNames2 = Object.getOwnPropertyNames;
|
|
11660
|
-
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
|
11661
|
-
var __export22 = (target, all) => {
|
|
11662
|
-
for (var name21 in all)
|
|
11663
|
-
__defProp22(target, name21, { get: all[name21], enumerable: true });
|
|
11664
|
-
};
|
|
11665
|
-
var __copyProps2 = (to, from, except, desc) => {
|
|
11666
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
11667
|
-
for (let key of __getOwnPropNames2(from))
|
|
11668
|
-
if (!__hasOwnProp2.call(to, key) && key !== except)
|
|
11669
|
-
__defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
|
|
11670
|
-
}
|
|
11671
|
-
return to;
|
|
11672
|
-
};
|
|
11673
|
-
var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
|
|
11674
|
-
var src_exports = {};
|
|
11675
|
-
__export22(src_exports, {
|
|
11676
|
-
getContext: () => import_get_context.getContext,
|
|
11677
|
-
getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
|
|
11678
|
-
getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync
|
|
11679
|
-
});
|
|
11680
|
-
module.exports = __toCommonJS(src_exports);
|
|
11681
|
-
var import_get_vercel_oidc_token = require_get_vercel_oidc_token2();
|
|
11682
|
-
var import_get_context = require_get_context2();
|
|
11644
|
+
function getContext2() {
|
|
11645
|
+
return {
|
|
11646
|
+
headers: {}
|
|
11647
|
+
};
|
|
11648
|
+
}
|
|
11649
|
+
async function getVercelOidcToken2() {
|
|
11650
|
+
if (process.env.VERCEL_OIDC_TOKEN) {
|
|
11651
|
+
return process.env.VERCEL_OIDC_TOKEN ?? "";
|
|
11683
11652
|
}
|
|
11684
|
-
|
|
11685
|
-
|
|
11686
|
-
var import_oidc22 = __toESM$1(require_dist2(), 1);
|
|
11653
|
+
throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.");
|
|
11654
|
+
}
|
|
11687
11655
|
var marker20 = "vercel.ai.gateway.error";
|
|
11688
11656
|
var symbol20 = Symbol.for(marker20);
|
|
11689
11657
|
var _a20;
|
|
@@ -12098,6 +12066,13 @@ async function parseAuthMethod2(headers) {
|
|
|
12098
12066
|
var gatewayAuthMethodSchema2 = lazySchema2(
|
|
12099
12067
|
() => zodSchema3(z$1.union([z$1.literal("api-key"), z$1.literal("oidc")]))
|
|
12100
12068
|
);
|
|
12069
|
+
var KNOWN_MODEL_TYPES2 = [
|
|
12070
|
+
"embedding",
|
|
12071
|
+
"image",
|
|
12072
|
+
"language",
|
|
12073
|
+
"reranking",
|
|
12074
|
+
"video"
|
|
12075
|
+
];
|
|
12101
12076
|
var GatewayFetchMetadata2 = class {
|
|
12102
12077
|
constructor(config) {
|
|
12103
12078
|
this.config = config;
|
|
@@ -12168,8 +12143,12 @@ var gatewayAvailableModelsResponseSchema2 = lazySchema2(
|
|
|
12168
12143
|
provider: z$1.string(),
|
|
12169
12144
|
modelId: z$1.string()
|
|
12170
12145
|
}),
|
|
12171
|
-
modelType: z$1.
|
|
12146
|
+
modelType: z$1.string().nullish()
|
|
12172
12147
|
})
|
|
12148
|
+
).transform(
|
|
12149
|
+
(models) => models.filter(
|
|
12150
|
+
(m) => m.modelType == null || KNOWN_MODEL_TYPES2.includes(m.modelType)
|
|
12151
|
+
)
|
|
12173
12152
|
)
|
|
12174
12153
|
})
|
|
12175
12154
|
)
|
|
@@ -12185,6 +12164,187 @@ var gatewayCreditsResponseSchema2 = lazySchema2(
|
|
|
12185
12164
|
}))
|
|
12186
12165
|
)
|
|
12187
12166
|
);
|
|
12167
|
+
var GatewaySpendReport2 = class {
|
|
12168
|
+
constructor(config) {
|
|
12169
|
+
this.config = config;
|
|
12170
|
+
}
|
|
12171
|
+
async getSpendReport(params) {
|
|
12172
|
+
try {
|
|
12173
|
+
const baseUrl = new URL(this.config.baseURL);
|
|
12174
|
+
const searchParams = new URLSearchParams();
|
|
12175
|
+
searchParams.set("start_date", params.startDate);
|
|
12176
|
+
searchParams.set("end_date", params.endDate);
|
|
12177
|
+
if (params.groupBy) {
|
|
12178
|
+
searchParams.set("group_by", params.groupBy);
|
|
12179
|
+
}
|
|
12180
|
+
if (params.datePart) {
|
|
12181
|
+
searchParams.set("date_part", params.datePart);
|
|
12182
|
+
}
|
|
12183
|
+
if (params.userId) {
|
|
12184
|
+
searchParams.set("user_id", params.userId);
|
|
12185
|
+
}
|
|
12186
|
+
if (params.model) {
|
|
12187
|
+
searchParams.set("model", params.model);
|
|
12188
|
+
}
|
|
12189
|
+
if (params.provider) {
|
|
12190
|
+
searchParams.set("provider", params.provider);
|
|
12191
|
+
}
|
|
12192
|
+
if (params.credentialType) {
|
|
12193
|
+
searchParams.set("credential_type", params.credentialType);
|
|
12194
|
+
}
|
|
12195
|
+
if (params.tags && params.tags.length > 0) {
|
|
12196
|
+
searchParams.set("tags", params.tags.join(","));
|
|
12197
|
+
}
|
|
12198
|
+
const { value } = await getFromApi2({
|
|
12199
|
+
url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
|
|
12200
|
+
headers: await resolve2(this.config.headers()),
|
|
12201
|
+
successfulResponseHandler: createJsonResponseHandler2(
|
|
12202
|
+
gatewaySpendReportResponseSchema2
|
|
12203
|
+
),
|
|
12204
|
+
failedResponseHandler: createJsonErrorResponseHandler2({
|
|
12205
|
+
errorSchema: z$1.any(),
|
|
12206
|
+
errorToMessage: (data) => data
|
|
12207
|
+
}),
|
|
12208
|
+
fetch: this.config.fetch
|
|
12209
|
+
});
|
|
12210
|
+
return value;
|
|
12211
|
+
} catch (error) {
|
|
12212
|
+
throw await asGatewayError2(error);
|
|
12213
|
+
}
|
|
12214
|
+
}
|
|
12215
|
+
};
|
|
12216
|
+
var gatewaySpendReportResponseSchema2 = lazySchema2(
|
|
12217
|
+
() => zodSchema3(
|
|
12218
|
+
z$1.object({
|
|
12219
|
+
results: z$1.array(
|
|
12220
|
+
z$1.object({
|
|
12221
|
+
day: z$1.string().optional(),
|
|
12222
|
+
hour: z$1.string().optional(),
|
|
12223
|
+
user: z$1.string().optional(),
|
|
12224
|
+
model: z$1.string().optional(),
|
|
12225
|
+
tag: z$1.string().optional(),
|
|
12226
|
+
provider: z$1.string().optional(),
|
|
12227
|
+
credential_type: z$1.enum(["byok", "system"]).optional(),
|
|
12228
|
+
total_cost: z$1.number(),
|
|
12229
|
+
market_cost: z$1.number().optional(),
|
|
12230
|
+
input_tokens: z$1.number().optional(),
|
|
12231
|
+
output_tokens: z$1.number().optional(),
|
|
12232
|
+
cached_input_tokens: z$1.number().optional(),
|
|
12233
|
+
cache_creation_input_tokens: z$1.number().optional(),
|
|
12234
|
+
reasoning_tokens: z$1.number().optional(),
|
|
12235
|
+
request_count: z$1.number().optional()
|
|
12236
|
+
}).transform(
|
|
12237
|
+
({
|
|
12238
|
+
credential_type,
|
|
12239
|
+
total_cost,
|
|
12240
|
+
market_cost,
|
|
12241
|
+
input_tokens,
|
|
12242
|
+
output_tokens,
|
|
12243
|
+
cached_input_tokens,
|
|
12244
|
+
cache_creation_input_tokens,
|
|
12245
|
+
reasoning_tokens,
|
|
12246
|
+
request_count,
|
|
12247
|
+
...rest
|
|
12248
|
+
}) => ({
|
|
12249
|
+
...rest,
|
|
12250
|
+
...credential_type !== void 0 ? { credentialType: credential_type } : {},
|
|
12251
|
+
totalCost: total_cost,
|
|
12252
|
+
...market_cost !== void 0 ? { marketCost: market_cost } : {},
|
|
12253
|
+
...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},
|
|
12254
|
+
...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},
|
|
12255
|
+
...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},
|
|
12256
|
+
...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
|
|
12257
|
+
...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},
|
|
12258
|
+
...request_count !== void 0 ? { requestCount: request_count } : {}
|
|
12259
|
+
})
|
|
12260
|
+
)
|
|
12261
|
+
)
|
|
12262
|
+
})
|
|
12263
|
+
)
|
|
12264
|
+
);
|
|
12265
|
+
var GatewayGenerationInfoFetcher2 = class {
|
|
12266
|
+
constructor(config) {
|
|
12267
|
+
this.config = config;
|
|
12268
|
+
}
|
|
12269
|
+
async getGenerationInfo(params) {
|
|
12270
|
+
try {
|
|
12271
|
+
const baseUrl = new URL(this.config.baseURL);
|
|
12272
|
+
const { value } = await getFromApi2({
|
|
12273
|
+
url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
|
|
12274
|
+
headers: await resolve2(this.config.headers()),
|
|
12275
|
+
successfulResponseHandler: createJsonResponseHandler2(
|
|
12276
|
+
gatewayGenerationInfoResponseSchema2
|
|
12277
|
+
),
|
|
12278
|
+
failedResponseHandler: createJsonErrorResponseHandler2({
|
|
12279
|
+
errorSchema: z$1.any(),
|
|
12280
|
+
errorToMessage: (data) => data
|
|
12281
|
+
}),
|
|
12282
|
+
fetch: this.config.fetch
|
|
12283
|
+
});
|
|
12284
|
+
return value;
|
|
12285
|
+
} catch (error) {
|
|
12286
|
+
throw await asGatewayError2(error);
|
|
12287
|
+
}
|
|
12288
|
+
}
|
|
12289
|
+
};
|
|
12290
|
+
var gatewayGenerationInfoResponseSchema2 = lazySchema2(
|
|
12291
|
+
() => zodSchema3(
|
|
12292
|
+
z$1.object({
|
|
12293
|
+
data: z$1.object({
|
|
12294
|
+
id: z$1.string(),
|
|
12295
|
+
total_cost: z$1.number(),
|
|
12296
|
+
upstream_inference_cost: z$1.number(),
|
|
12297
|
+
usage: z$1.number(),
|
|
12298
|
+
created_at: z$1.string(),
|
|
12299
|
+
model: z$1.string(),
|
|
12300
|
+
is_byok: z$1.boolean(),
|
|
12301
|
+
provider_name: z$1.string(),
|
|
12302
|
+
streamed: z$1.boolean(),
|
|
12303
|
+
finish_reason: z$1.string(),
|
|
12304
|
+
latency: z$1.number(),
|
|
12305
|
+
generation_time: z$1.number(),
|
|
12306
|
+
native_tokens_prompt: z$1.number(),
|
|
12307
|
+
native_tokens_completion: z$1.number(),
|
|
12308
|
+
native_tokens_reasoning: z$1.number(),
|
|
12309
|
+
native_tokens_cached: z$1.number(),
|
|
12310
|
+
native_tokens_cache_creation: z$1.number(),
|
|
12311
|
+
billable_web_search_calls: z$1.number()
|
|
12312
|
+
}).transform(
|
|
12313
|
+
({
|
|
12314
|
+
total_cost,
|
|
12315
|
+
upstream_inference_cost,
|
|
12316
|
+
created_at,
|
|
12317
|
+
is_byok,
|
|
12318
|
+
provider_name,
|
|
12319
|
+
finish_reason,
|
|
12320
|
+
generation_time,
|
|
12321
|
+
native_tokens_prompt,
|
|
12322
|
+
native_tokens_completion,
|
|
12323
|
+
native_tokens_reasoning,
|
|
12324
|
+
native_tokens_cached,
|
|
12325
|
+
native_tokens_cache_creation,
|
|
12326
|
+
billable_web_search_calls,
|
|
12327
|
+
...rest
|
|
12328
|
+
}) => ({
|
|
12329
|
+
...rest,
|
|
12330
|
+
totalCost: total_cost,
|
|
12331
|
+
upstreamInferenceCost: upstream_inference_cost,
|
|
12332
|
+
createdAt: created_at,
|
|
12333
|
+
isByok: is_byok,
|
|
12334
|
+
providerName: provider_name,
|
|
12335
|
+
finishReason: finish_reason,
|
|
12336
|
+
generationTime: generation_time,
|
|
12337
|
+
promptTokens: native_tokens_prompt,
|
|
12338
|
+
completionTokens: native_tokens_completion,
|
|
12339
|
+
reasoningTokens: native_tokens_reasoning,
|
|
12340
|
+
cachedTokens: native_tokens_cached,
|
|
12341
|
+
cacheCreationTokens: native_tokens_cache_creation,
|
|
12342
|
+
billableWebSearchCalls: billable_web_search_calls
|
|
12343
|
+
})
|
|
12344
|
+
)
|
|
12345
|
+
}).transform(({ data }) => data)
|
|
12346
|
+
)
|
|
12347
|
+
);
|
|
12188
12348
|
var GatewayLanguageModel2 = class {
|
|
12189
12349
|
constructor(modelId, config) {
|
|
12190
12350
|
this.modelId = modelId;
|
|
@@ -12732,37 +12892,117 @@ var gatewayVideoEventSchema = z$1.discriminatedUnion("type", [
|
|
|
12732
12892
|
param: z$1.unknown().nullable()
|
|
12733
12893
|
})
|
|
12734
12894
|
]);
|
|
12735
|
-
var
|
|
12736
|
-
()
|
|
12737
|
-
|
|
12738
|
-
|
|
12739
|
-
|
|
12740
|
-
|
|
12741
|
-
|
|
12742
|
-
|
|
12743
|
-
|
|
12744
|
-
|
|
12745
|
-
|
|
12746
|
-
|
|
12747
|
-
|
|
12748
|
-
|
|
12749
|
-
|
|
12750
|
-
|
|
12751
|
-
|
|
12752
|
-
|
|
12753
|
-
|
|
12754
|
-
|
|
12755
|
-
|
|
12756
|
-
|
|
12757
|
-
|
|
12758
|
-
|
|
12759
|
-
|
|
12760
|
-
|
|
12761
|
-
|
|
12762
|
-
|
|
12763
|
-
|
|
12764
|
-
|
|
12765
|
-
|
|
12895
|
+
var GatewayRerankingModel = class {
|
|
12896
|
+
constructor(modelId, config) {
|
|
12897
|
+
this.modelId = modelId;
|
|
12898
|
+
this.config = config;
|
|
12899
|
+
this.specificationVersion = "v3";
|
|
12900
|
+
}
|
|
12901
|
+
get provider() {
|
|
12902
|
+
return this.config.provider;
|
|
12903
|
+
}
|
|
12904
|
+
async doRerank({
|
|
12905
|
+
documents,
|
|
12906
|
+
query,
|
|
12907
|
+
topN,
|
|
12908
|
+
headers,
|
|
12909
|
+
abortSignal,
|
|
12910
|
+
providerOptions
|
|
12911
|
+
}) {
|
|
12912
|
+
const resolvedHeaders = await resolve2(this.config.headers());
|
|
12913
|
+
try {
|
|
12914
|
+
const {
|
|
12915
|
+
responseHeaders,
|
|
12916
|
+
value: responseBody,
|
|
12917
|
+
rawValue
|
|
12918
|
+
} = await postJsonToApi2({
|
|
12919
|
+
url: this.getUrl(),
|
|
12920
|
+
headers: combineHeaders2(
|
|
12921
|
+
resolvedHeaders,
|
|
12922
|
+
headers != null ? headers : {},
|
|
12923
|
+
this.getModelConfigHeaders(),
|
|
12924
|
+
await resolve2(this.config.o11yHeaders)
|
|
12925
|
+
),
|
|
12926
|
+
body: {
|
|
12927
|
+
documents,
|
|
12928
|
+
query,
|
|
12929
|
+
...topN != null ? { topN } : {},
|
|
12930
|
+
...providerOptions ? { providerOptions } : {}
|
|
12931
|
+
},
|
|
12932
|
+
successfulResponseHandler: createJsonResponseHandler2(
|
|
12933
|
+
gatewayRerankingResponseSchema
|
|
12934
|
+
),
|
|
12935
|
+
failedResponseHandler: createJsonErrorResponseHandler2({
|
|
12936
|
+
errorSchema: z$1.any(),
|
|
12937
|
+
errorToMessage: (data) => data
|
|
12938
|
+
}),
|
|
12939
|
+
...abortSignal && { abortSignal },
|
|
12940
|
+
fetch: this.config.fetch
|
|
12941
|
+
});
|
|
12942
|
+
return {
|
|
12943
|
+
ranking: responseBody.ranking,
|
|
12944
|
+
providerMetadata: responseBody.providerMetadata,
|
|
12945
|
+
response: { headers: responseHeaders, body: rawValue },
|
|
12946
|
+
warnings: []
|
|
12947
|
+
};
|
|
12948
|
+
} catch (error) {
|
|
12949
|
+
throw await asGatewayError2(error, await parseAuthMethod2(resolvedHeaders));
|
|
12950
|
+
}
|
|
12951
|
+
}
|
|
12952
|
+
getUrl() {
|
|
12953
|
+
return `${this.config.baseURL}/reranking-model`;
|
|
12954
|
+
}
|
|
12955
|
+
getModelConfigHeaders() {
|
|
12956
|
+
return {
|
|
12957
|
+
"ai-reranking-model-specification-version": "3",
|
|
12958
|
+
"ai-model-id": this.modelId
|
|
12959
|
+
};
|
|
12960
|
+
}
|
|
12961
|
+
};
|
|
12962
|
+
var gatewayRerankingResponseSchema = lazySchema2(
|
|
12963
|
+
() => zodSchema3(
|
|
12964
|
+
z$1.object({
|
|
12965
|
+
ranking: z$1.array(
|
|
12966
|
+
z$1.object({
|
|
12967
|
+
index: z$1.number(),
|
|
12968
|
+
relevanceScore: z$1.number()
|
|
12969
|
+
})
|
|
12970
|
+
),
|
|
12971
|
+
providerMetadata: z$1.record(z$1.string(), z$1.record(z$1.string(), z$1.unknown())).optional()
|
|
12972
|
+
})
|
|
12973
|
+
)
|
|
12974
|
+
);
|
|
12975
|
+
var parallelSearchInputSchema2 = lazySchema2(
|
|
12976
|
+
() => zodSchema3(
|
|
12977
|
+
z.object({
|
|
12978
|
+
objective: z.string().describe(
|
|
12979
|
+
"Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."
|
|
12980
|
+
),
|
|
12981
|
+
search_queries: z.array(z.string()).optional().describe(
|
|
12982
|
+
"Optional search queries to supplement the objective. Maximum 200 characters per query."
|
|
12983
|
+
),
|
|
12984
|
+
mode: z.enum(["one-shot", "agentic"]).optional().describe(
|
|
12985
|
+
'Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'
|
|
12986
|
+
),
|
|
12987
|
+
max_results: z.number().optional().describe(
|
|
12988
|
+
"Maximum number of results to return (1-20). Defaults to 10 if not specified."
|
|
12989
|
+
),
|
|
12990
|
+
source_policy: z.object({
|
|
12991
|
+
include_domains: z.array(z.string()).optional().describe("List of domains to include in search results."),
|
|
12992
|
+
exclude_domains: z.array(z.string()).optional().describe("List of domains to exclude from search results."),
|
|
12993
|
+
after_date: z.string().optional().describe(
|
|
12994
|
+
"Only include results published after this date (ISO 8601 format)."
|
|
12995
|
+
)
|
|
12996
|
+
}).optional().describe(
|
|
12997
|
+
"Source policy for controlling which domains to include/exclude and freshness."
|
|
12998
|
+
),
|
|
12999
|
+
excerpts: z.object({
|
|
13000
|
+
max_chars_per_result: z.number().optional().describe("Maximum characters per result."),
|
|
13001
|
+
max_chars_total: z.number().optional().describe("Maximum total characters across all results.")
|
|
13002
|
+
}).optional().describe("Excerpt configuration for controlling result length."),
|
|
13003
|
+
fetch_policy: z.object({
|
|
13004
|
+
max_age_seconds: z.number().optional().describe(
|
|
13005
|
+
"Maximum age in seconds for cached content. Set to 0 to always fetch fresh content."
|
|
12766
13006
|
)
|
|
12767
13007
|
}).optional().describe("Fetch policy for controlling content freshness.")
|
|
12768
13008
|
})
|
|
@@ -12906,9 +13146,9 @@ var gatewayTools2 = {
|
|
|
12906
13146
|
};
|
|
12907
13147
|
async function getVercelRequestId2() {
|
|
12908
13148
|
var _a932;
|
|
12909
|
-
return (_a932 = (
|
|
13149
|
+
return (_a932 = getContext2().headers) == null ? void 0 : _a932["x-vercel-id"];
|
|
12910
13150
|
}
|
|
12911
|
-
var VERSION5 = "3.0.
|
|
13151
|
+
var VERSION5 = "3.0.104";
|
|
12912
13152
|
var AI_GATEWAY_PROTOCOL_VERSION2 = "0.0.1";
|
|
12913
13153
|
function createGatewayProvider2(options = {}) {
|
|
12914
13154
|
var _a932, _b93;
|
|
@@ -13008,6 +13248,30 @@ function createGatewayProvider2(options = {}) {
|
|
|
13008
13248
|
);
|
|
13009
13249
|
});
|
|
13010
13250
|
};
|
|
13251
|
+
const getSpendReport = async (params) => {
|
|
13252
|
+
return new GatewaySpendReport2({
|
|
13253
|
+
baseURL,
|
|
13254
|
+
headers: getHeaders,
|
|
13255
|
+
fetch: options.fetch
|
|
13256
|
+
}).getSpendReport(params).catch(async (error) => {
|
|
13257
|
+
throw await asGatewayError2(
|
|
13258
|
+
error,
|
|
13259
|
+
await parseAuthMethod2(await getHeaders())
|
|
13260
|
+
);
|
|
13261
|
+
});
|
|
13262
|
+
};
|
|
13263
|
+
const getGenerationInfo = async (params) => {
|
|
13264
|
+
return new GatewayGenerationInfoFetcher2({
|
|
13265
|
+
baseURL,
|
|
13266
|
+
headers: getHeaders,
|
|
13267
|
+
fetch: options.fetch
|
|
13268
|
+
}).getGenerationInfo(params).catch(async (error) => {
|
|
13269
|
+
throw await asGatewayError2(
|
|
13270
|
+
error,
|
|
13271
|
+
await parseAuthMethod2(await getHeaders())
|
|
13272
|
+
);
|
|
13273
|
+
});
|
|
13274
|
+
};
|
|
13011
13275
|
const provider = function(modelId) {
|
|
13012
13276
|
if (new.target) {
|
|
13013
13277
|
throw new Error(
|
|
@@ -13019,6 +13283,8 @@ function createGatewayProvider2(options = {}) {
|
|
|
13019
13283
|
provider.specificationVersion = "v3";
|
|
13020
13284
|
provider.getAvailableModels = getAvailableModels;
|
|
13021
13285
|
provider.getCredits = getCredits;
|
|
13286
|
+
provider.getSpendReport = getSpendReport;
|
|
13287
|
+
provider.getGenerationInfo = getGenerationInfo;
|
|
13022
13288
|
provider.imageModel = (modelId) => {
|
|
13023
13289
|
return new GatewayImageModel2(modelId, {
|
|
13024
13290
|
provider: "gateway",
|
|
@@ -13049,6 +13315,17 @@ function createGatewayProvider2(options = {}) {
|
|
|
13049
13315
|
o11yHeaders: createO11yHeaders()
|
|
13050
13316
|
});
|
|
13051
13317
|
};
|
|
13318
|
+
const createRerankingModel = (modelId) => {
|
|
13319
|
+
return new GatewayRerankingModel(modelId, {
|
|
13320
|
+
provider: "gateway",
|
|
13321
|
+
baseURL,
|
|
13322
|
+
headers: getHeaders,
|
|
13323
|
+
fetch: options.fetch,
|
|
13324
|
+
o11yHeaders: createO11yHeaders()
|
|
13325
|
+
});
|
|
13326
|
+
};
|
|
13327
|
+
provider.rerankingModel = createRerankingModel;
|
|
13328
|
+
provider.reranking = createRerankingModel;
|
|
13052
13329
|
provider.chat = provider.languageModel;
|
|
13053
13330
|
provider.embedding = provider.embeddingModel;
|
|
13054
13331
|
provider.image = provider.imageModel;
|
|
@@ -13068,7 +13345,7 @@ async function getGatewayAuthToken2(options) {
|
|
|
13068
13345
|
authMethod: "api-key"
|
|
13069
13346
|
};
|
|
13070
13347
|
}
|
|
13071
|
-
const oidcToken = await (
|
|
13348
|
+
const oidcToken = await getVercelOidcToken2();
|
|
13072
13349
|
return {
|
|
13073
13350
|
token: oidcToken,
|
|
13074
13351
|
authMethod: "oidc"
|
|
@@ -13981,7 +14258,7 @@ function getTotalTimeoutMs(timeout) {
|
|
|
13981
14258
|
}
|
|
13982
14259
|
return timeout.totalMs;
|
|
13983
14260
|
}
|
|
13984
|
-
var VERSION33 = "6.0.
|
|
14261
|
+
var VERSION33 = "6.0.168";
|
|
13985
14262
|
var dataContentSchema3 = z$1.union([
|
|
13986
14263
|
z$1.string(),
|
|
13987
14264
|
z$1.instanceof(Uint8Array),
|
|
@@ -15425,10 +15702,16 @@ var DefaultEmbedManyResult3 = class {
|
|
|
15425
15702
|
};
|
|
15426
15703
|
createIdGenerator3({ prefix: "aiobj", size: 24 });
|
|
15427
15704
|
createIdGenerator3({ prefix: "aiobj", size: 24 });
|
|
15705
|
+
function getMessageParts(msg) {
|
|
15706
|
+
if (typeof msg.content === "string") return [];
|
|
15707
|
+
if (Array.isArray(msg.content)) return msg.content;
|
|
15708
|
+
const parts = msg.content?.parts;
|
|
15709
|
+
return Array.isArray(parts) ? parts : [];
|
|
15710
|
+
}
|
|
15428
15711
|
function hasVisibleParts(msg) {
|
|
15429
15712
|
if (typeof msg.content === "string") return msg.content.length > 0;
|
|
15430
|
-
const parts = msg
|
|
15431
|
-
if (
|
|
15713
|
+
const parts = getMessageParts(msg);
|
|
15714
|
+
if (parts.length === 0) return Boolean(msg.content?.content);
|
|
15432
15715
|
return parts.some((p) => !p.type?.startsWith("data-"));
|
|
15433
15716
|
}
|
|
15434
15717
|
function parseRangeFormat(cursor) {
|
|
@@ -15689,13 +15972,13 @@ function lowDetailPartLimit(type) {
|
|
|
15689
15972
|
if (type === "tool-result" || type === "tool-call") return AUTO_EXPAND_TOOL_TOKENS;
|
|
15690
15973
|
return LOW_DETAIL_PART_TOKENS;
|
|
15691
15974
|
}
|
|
15692
|
-
function makePart(msg, partIndex, type, fullText, detail) {
|
|
15975
|
+
function makePart(msg, partIndex, type, fullText, detail, toolName) {
|
|
15693
15976
|
if (detail === "high") {
|
|
15694
|
-
return { messageId: msg.id, partIndex, role: msg.role, type, text: fullText, fullText };
|
|
15977
|
+
return { messageId: msg.id, partIndex, role: msg.role, type, text: fullText, fullText, toolName };
|
|
15695
15978
|
}
|
|
15696
15979
|
const hint = `recall cursor="${msg.id}" partIndex=${partIndex} detail="high"`;
|
|
15697
15980
|
const { text: text4 } = truncateByTokens(fullText, lowDetailPartLimit(type), hint);
|
|
15698
|
-
return { messageId: msg.id, partIndex, role: msg.role, type, text: text4, fullText };
|
|
15981
|
+
return { messageId: msg.id, partIndex, role: msg.role, type, text: text4, fullText, toolName };
|
|
15699
15982
|
}
|
|
15700
15983
|
function formatMessageParts(msg, detail) {
|
|
15701
15984
|
const parts = [];
|
|
@@ -15703,32 +15986,73 @@ function formatMessageParts(msg, detail) {
|
|
|
15703
15986
|
parts.push(makePart(msg, 0, "text", msg.content, detail));
|
|
15704
15987
|
return parts;
|
|
15705
15988
|
}
|
|
15706
|
-
|
|
15707
|
-
|
|
15708
|
-
|
|
15989
|
+
const messageParts = getMessageParts(msg);
|
|
15990
|
+
if (messageParts.length > 0) {
|
|
15991
|
+
for (let i = 0; i < messageParts.length; i++) {
|
|
15992
|
+
const part = messageParts[i];
|
|
15709
15993
|
const partType = part.type;
|
|
15710
15994
|
if (partType === "text") {
|
|
15711
15995
|
const text4 = part.text;
|
|
15712
|
-
|
|
15996
|
+
if (text4) {
|
|
15997
|
+
parts.push(makePart(msg, i, "text", text4, detail));
|
|
15998
|
+
}
|
|
15713
15999
|
} else if (partType === "tool-invocation") {
|
|
15714
16000
|
const inv = part.toolInvocation;
|
|
15715
|
-
if (inv
|
|
15716
|
-
const
|
|
15717
|
-
|
|
15718
|
-
|
|
15719
|
-
);
|
|
15720
|
-
const resultStr = formatToolResultForObserver(resultValue, { maxTokens: HIGH_DETAIL_TOOL_RESULT_TOKENS });
|
|
15721
|
-
const fullText = `[Tool Result: ${inv.toolName}]
|
|
15722
|
-
${resultStr}`;
|
|
15723
|
-
parts.push(makePart(msg, i, "tool-result", fullText, detail));
|
|
15724
|
-
} else {
|
|
15725
|
-
const argsStr = detail === "low" ? "" : `
|
|
16001
|
+
if (inv?.toolName) {
|
|
16002
|
+
const hasArgs = inv.args != null;
|
|
16003
|
+
if (inv.state !== "partial-call" && hasArgs) {
|
|
16004
|
+
const argsStr = detail === "low" ? "" : `
|
|
15726
16005
|
${JSON.stringify(inv.args, null, 2)}`;
|
|
15727
|
-
|
|
15728
|
-
|
|
16006
|
+
const fullText = `[Tool Call: ${inv.toolName}]${argsStr}`;
|
|
16007
|
+
parts.push({
|
|
16008
|
+
messageId: msg.id,
|
|
16009
|
+
partIndex: i,
|
|
16010
|
+
role: msg.role,
|
|
16011
|
+
type: "tool-call",
|
|
16012
|
+
text: fullText,
|
|
16013
|
+
fullText,
|
|
16014
|
+
toolName: inv.toolName
|
|
16015
|
+
});
|
|
16016
|
+
}
|
|
16017
|
+
if (inv.state === "result") {
|
|
16018
|
+
const { value: resultValue } = resolveToolResultValue(
|
|
16019
|
+
part,
|
|
16020
|
+
inv.result
|
|
16021
|
+
);
|
|
16022
|
+
const resultStr = formatToolResultForObserver(resultValue, { maxTokens: HIGH_DETAIL_TOOL_RESULT_TOKENS });
|
|
16023
|
+
const fullText = `[Tool Result: ${inv.toolName}]
|
|
16024
|
+
${resultStr}`;
|
|
16025
|
+
parts.push(makePart(msg, i, "tool-result", fullText, detail, inv.toolName));
|
|
16026
|
+
}
|
|
16027
|
+
}
|
|
16028
|
+
} else if (partType === "tool-call") {
|
|
16029
|
+
const toolName = part.toolName;
|
|
16030
|
+
if (toolName) {
|
|
16031
|
+
const rawArgs = part.input ?? part.args;
|
|
16032
|
+
const argsStr = detail === "low" || rawArgs == null ? "" : `
|
|
16033
|
+
${typeof rawArgs === "string" ? rawArgs : JSON.stringify(rawArgs, null, 2)}`;
|
|
16034
|
+
const fullText = `[Tool Call: ${toolName}]${argsStr}`;
|
|
16035
|
+
parts.push({
|
|
16036
|
+
messageId: msg.id,
|
|
16037
|
+
partIndex: i,
|
|
16038
|
+
role: msg.role,
|
|
16039
|
+
type: "tool-call",
|
|
16040
|
+
text: fullText,
|
|
16041
|
+
fullText,
|
|
16042
|
+
toolName
|
|
16043
|
+
});
|
|
16044
|
+
}
|
|
16045
|
+
} else if (partType === "tool-result") {
|
|
16046
|
+
const toolName = part.toolName;
|
|
16047
|
+
if (toolName) {
|
|
16048
|
+
const rawResult = part.output ?? part.result;
|
|
16049
|
+
const resultStr = formatToolResultForObserver(rawResult, { maxTokens: HIGH_DETAIL_TOOL_RESULT_TOKENS });
|
|
16050
|
+
const fullText = `[Tool Result: ${toolName}]
|
|
16051
|
+
${resultStr}`;
|
|
16052
|
+
parts.push(makePart(msg, i, "tool-result", fullText, detail, toolName));
|
|
15729
16053
|
}
|
|
15730
16054
|
} else if (partType === "reasoning") {
|
|
15731
|
-
const reasoning = part.reasoning;
|
|
16055
|
+
const reasoning = part.reasoning ?? part.text;
|
|
15732
16056
|
if (reasoning) {
|
|
15733
16057
|
parts.push(makePart(msg, i, "reasoning", reasoning, detail));
|
|
15734
16058
|
}
|
|
@@ -15866,7 +16190,7 @@ async function recallPart({
|
|
|
15866
16190
|
`Message ${cursor} has no visible content (it may be an internal system message). Try a neighboring message ID instead.`
|
|
15867
16191
|
);
|
|
15868
16192
|
}
|
|
15869
|
-
const target = allParts.find((p) => p.partIndex === partIndex);
|
|
16193
|
+
const target = [...allParts].reverse().find((p) => p.partIndex === partIndex);
|
|
15870
16194
|
if (!target) {
|
|
15871
16195
|
const availableIndices = allParts.map((p) => p.partIndex).join(", ");
|
|
15872
16196
|
const highestVisiblePartIndex = Math.max(...allParts.map((p) => p.partIndex));
|
|
@@ -15919,6 +16243,8 @@ async function recallMessages({
|
|
|
15919
16243
|
page = 1,
|
|
15920
16244
|
limit = 20,
|
|
15921
16245
|
detail = "low",
|
|
16246
|
+
partType,
|
|
16247
|
+
toolName,
|
|
15922
16248
|
threadScope,
|
|
15923
16249
|
maxTokens = DEFAULT_MAX_RESULT_TOKENS
|
|
15924
16250
|
}) {
|
|
@@ -16008,12 +16334,18 @@ async function recallMessages({
|
|
|
16008
16334
|
}
|
|
16009
16335
|
const hasNextPage = isForward ? hasMore : pageIndex > 0;
|
|
16010
16336
|
const hasPrevPage = isForward ? pageIndex > 0 : hasMore;
|
|
16011
|
-
|
|
16337
|
+
let allParts = [];
|
|
16012
16338
|
const timestamps = /* @__PURE__ */ new Map();
|
|
16013
16339
|
for (const msg of messages) {
|
|
16014
16340
|
timestamps.set(msg.id, msg.createdAt);
|
|
16015
16341
|
allParts.push(...formatMessageParts(msg, detail));
|
|
16016
16342
|
}
|
|
16343
|
+
if (toolName) {
|
|
16344
|
+
allParts = allParts.filter((p) => (p.type === "tool-call" || p.type === "tool-result") && p.toolName === toolName);
|
|
16345
|
+
}
|
|
16346
|
+
if (partType) {
|
|
16347
|
+
allParts = allParts.filter((p) => p.type === partType);
|
|
16348
|
+
}
|
|
16017
16349
|
if (detail === "high" && allParts.length > 0) {
|
|
16018
16350
|
const firstPart = allParts[0];
|
|
16019
16351
|
const sameMsgParts = allParts.filter((p) => p.messageId === firstPart.messageId);
|
|
@@ -16050,8 +16382,9 @@ High detail returns 1 part at a time. To continue: ${hints.join(", or ")}.`;
|
|
|
16050
16382
|
};
|
|
16051
16383
|
}
|
|
16052
16384
|
const rendered = renderFormattedParts(allParts, timestamps, { maxTokens });
|
|
16385
|
+
const emptyMessage = allParts.length === 0 ? partType || toolName ? "(no message parts matched the current filters)" : "(no visible message parts found for this page)" : "(no messages found)";
|
|
16053
16386
|
return {
|
|
16054
|
-
messages: rendered.text,
|
|
16387
|
+
messages: rendered.text || emptyMessage,
|
|
16055
16388
|
count: messages.length,
|
|
16056
16389
|
cursor,
|
|
16057
16390
|
page: normalizedPage,
|
|
@@ -16070,6 +16403,9 @@ async function recallThreadFromStart({
|
|
|
16070
16403
|
page = 1,
|
|
16071
16404
|
limit = 20,
|
|
16072
16405
|
detail = "low",
|
|
16406
|
+
partType,
|
|
16407
|
+
toolName,
|
|
16408
|
+
anchor = "start",
|
|
16073
16409
|
maxTokens = DEFAULT_MAX_RESULT_TOKENS
|
|
16074
16410
|
}) {
|
|
16075
16411
|
if (!memory) {
|
|
@@ -16095,29 +16431,37 @@ async function recallThreadFromStart({
|
|
|
16095
16431
|
resourceId,
|
|
16096
16432
|
page: 0,
|
|
16097
16433
|
perPage: fetchCount,
|
|
16098
|
-
orderBy: { field: "createdAt", direction: "ASC" }
|
|
16434
|
+
orderBy: { field: "createdAt", direction: anchor === "end" ? "DESC" : "ASC" }
|
|
16099
16435
|
});
|
|
16100
|
-
const visibleMessages = result.messages.filter(hasVisibleParts);
|
|
16101
|
-
const total = visibleMessages.length;
|
|
16436
|
+
const visibleMessages = anchor === "end" ? result.messages.slice(0, fetchCount).filter(hasVisibleParts).reverse() : result.messages.slice(0, fetchCount).filter(hasVisibleParts);
|
|
16102
16437
|
const skip = pageIndex * normalizedLimit;
|
|
16103
|
-
const hasMore = total > skip + normalizedLimit;
|
|
16104
16438
|
const messages = visibleMessages.slice(skip, skip + normalizedLimit);
|
|
16105
|
-
const
|
|
16439
|
+
const hasExtraMessage = visibleMessages.length > skip + messages.length;
|
|
16440
|
+
const hasNextPage = messages.length > 0 ? anchor === "end" ? pageIndex > 0 : hasExtraMessage : false;
|
|
16441
|
+
const hasPrevPage = messages.length > 0 ? anchor === "end" ? hasExtraMessage : pageIndex > 0 : pageIndex > 0;
|
|
16442
|
+
let allParts = [];
|
|
16106
16443
|
const timestamps = /* @__PURE__ */ new Map();
|
|
16107
16444
|
for (const msg of messages) {
|
|
16108
16445
|
timestamps.set(msg.id, msg.createdAt);
|
|
16109
16446
|
allParts.push(...formatMessageParts(msg, detail));
|
|
16110
16447
|
}
|
|
16448
|
+
if (toolName) {
|
|
16449
|
+
allParts = allParts.filter((p) => (p.type === "tool-call" || p.type === "tool-result") && p.toolName === toolName);
|
|
16450
|
+
}
|
|
16451
|
+
if (partType) {
|
|
16452
|
+
allParts = allParts.filter((p) => p.type === partType);
|
|
16453
|
+
}
|
|
16111
16454
|
const rendered = renderFormattedParts(allParts, timestamps, { maxTokens });
|
|
16455
|
+
const emptyMessage = messages.length === 0 ? pageIndex > 0 ? `(no messages found on page ${normalizedPage} for this thread)` : "(no messages in this thread)" : partType || toolName ? "(no message parts matched the current filters)" : "(no messages found)";
|
|
16112
16456
|
return {
|
|
16113
|
-
messages: rendered.text ||
|
|
16457
|
+
messages: rendered.text || emptyMessage,
|
|
16114
16458
|
count: messages.length,
|
|
16115
16459
|
cursor: messages[0]?.id || "",
|
|
16116
16460
|
page: normalizedPage,
|
|
16117
16461
|
limit: normalizedLimit,
|
|
16118
16462
|
detail,
|
|
16119
|
-
hasNextPage
|
|
16120
|
-
hasPrevPage
|
|
16463
|
+
hasNextPage,
|
|
16464
|
+
hasPrevPage,
|
|
16121
16465
|
truncated: rendered.truncated,
|
|
16122
16466
|
tokenOffset: rendered.tokenOffset
|
|
16123
16467
|
};
|
|
@@ -16125,7 +16469,7 @@ async function recallThreadFromStart({
|
|
|
16125
16469
|
var recallTool = (_memoryConfig, options) => {
|
|
16126
16470
|
const retrievalScope = options?.retrievalScope ?? "thread";
|
|
16127
16471
|
const isResourceScope = retrievalScope === "resource";
|
|
16128
|
-
const description = isResourceScope ? 'Browse conversation history. Use mode="threads" to list all threads for the current user. Use mode="messages" (default) to browse messages in the current thread or pass threadId to browse another thread in the active resource. If you pass only a cursor, it must belong to the current thread. Use mode="search" to find messages by content across all threads.' : `Browse conversation history in the current thread. Use mode="messages" (default) to page through messages near a cursor. Use mode="search" to find messages by content in this thread. Use mode="threads" to get the current thread's ID and title.`;
|
|
16472
|
+
const description = isResourceScope ? 'Browse conversation history. Use mode="threads" to list all threads for the current user. Use mode="messages" (default) to browse messages in the current thread or pass threadId to browse another thread in the active resource. When mode="messages" has no cursor or threadId, it defaults to the current thread and says so at the top of the result. If you pass only a cursor, it must belong to the current thread. Use mode="search" to find messages by content across all threads.' : `Browse conversation history in the current thread. Use mode="messages" (default) to page through messages near a cursor. Use mode="search" to find messages by content in this thread. Use mode="threads" to get the current thread's ID and title.`;
|
|
16129
16473
|
return createTool({
|
|
16130
16474
|
id: "recall",
|
|
16131
16475
|
description,
|
|
@@ -16134,7 +16478,9 @@ var recallTool = (_memoryConfig, options) => {
|
|
|
16134
16478
|
mode: z.enum(["messages", "threads", "search"]).optional().describe(
|
|
16135
16479
|
'What to retrieve. "messages" (default) pages through message history. "threads" lists all threads for the current user. "search" finds messages by semantic similarity across all threads.'
|
|
16136
16480
|
),
|
|
16137
|
-
threadId: z.string().min(1).optional().describe(
|
|
16481
|
+
threadId: z.string().min(1).optional().describe(
|
|
16482
|
+
'Browse a different thread, or use "current" for the active thread. Use mode="threads" first to discover thread IDs.'
|
|
16483
|
+
),
|
|
16138
16484
|
before: z.string().optional().describe(
|
|
16139
16485
|
'For mode="threads": only show threads created before this date. ISO 8601 or natural date string (e.g. "2026-03-15", "2026-03-10T00:00:00Z").'
|
|
16140
16486
|
),
|
|
@@ -16148,7 +16494,10 @@ var recallTool = (_memoryConfig, options) => {
|
|
|
16148
16494
|
},
|
|
16149
16495
|
query: z.string().min(1).optional().describe('Search query for mode="search". Finds messages semantically similar to this text.'),
|
|
16150
16496
|
cursor: z.string().min(1).optional().describe(
|
|
16151
|
-
'A message ID to use as the pagination cursor. For mode="messages",
|
|
16497
|
+
'A message ID to use as the pagination cursor. For mode="messages", omit both cursor and threadId to browse the current thread. If only cursor is provided, it must belong to the current thread. Extract it from the start or end of an observation group range.'
|
|
16498
|
+
),
|
|
16499
|
+
anchor: z.enum(["start", "end"]).optional().describe(
|
|
16500
|
+
'For mode="messages" without a cursor, page from the start (oldest-first) or end (newest-first) of the thread. Defaults to "start".'
|
|
16152
16501
|
),
|
|
16153
16502
|
page: z.number().int().min(-50).max(50).optional().describe(
|
|
16154
16503
|
"Pagination offset. For messages: positive pages move forward from cursor, negative move backward. For threads: page number (0-indexed). 0 is treated as 1 for messages."
|
|
@@ -16157,6 +16506,10 @@ var recallTool = (_memoryConfig, options) => {
|
|
|
16157
16506
|
detail: z.enum(["low", "high"]).optional().describe(
|
|
16158
16507
|
'Detail level for messages. "low" (default) returns truncated text and tool names. "high" returns full content with tool args/results.'
|
|
16159
16508
|
),
|
|
16509
|
+
partType: z.enum(["text", "tool-call", "tool-result", "reasoning", "image", "file"]).optional().describe('Filter results to only include parts of this type. Only applies to mode="messages".'),
|
|
16510
|
+
toolName: z.string().min(1).optional().describe(
|
|
16511
|
+
'Filter results to only include tool-call and tool-result parts matching this tool name. Only applies to mode="messages".'
|
|
16512
|
+
),
|
|
16160
16513
|
partIndex: z.number().int().min(0).optional().describe(
|
|
16161
16514
|
"Fetch a single part from the cursor message by its positional index. When provided, returns only that part at high detail. Indices are shown as [p0], [p1], etc. in recall results."
|
|
16162
16515
|
)
|
|
@@ -16166,9 +16519,12 @@ var recallTool = (_memoryConfig, options) => {
|
|
|
16166
16519
|
query,
|
|
16167
16520
|
cursor,
|
|
16168
16521
|
threadId: explicitThreadId,
|
|
16522
|
+
anchor,
|
|
16169
16523
|
page,
|
|
16170
16524
|
limit,
|
|
16171
16525
|
detail,
|
|
16526
|
+
partType,
|
|
16527
|
+
toolName,
|
|
16172
16528
|
partIndex,
|
|
16173
16529
|
before,
|
|
16174
16530
|
after
|
|
@@ -16176,9 +16532,13 @@ var recallTool = (_memoryConfig, options) => {
|
|
|
16176
16532
|
const memory = context2?.memory;
|
|
16177
16533
|
const currentThreadId = context2?.agent?.threadId;
|
|
16178
16534
|
const resourceId = context2?.agent?.resourceId;
|
|
16535
|
+
const resolvedExplicitThreadId = explicitThreadId === "current" ? currentThreadId : explicitThreadId;
|
|
16179
16536
|
if (!memory) {
|
|
16180
16537
|
throw new Error("Memory instance is required for recall");
|
|
16181
16538
|
}
|
|
16539
|
+
if (explicitThreadId === "current" && !currentThreadId) {
|
|
16540
|
+
throw new Error("Could not resolve current thread.");
|
|
16541
|
+
}
|
|
16182
16542
|
if (mode === "search") {
|
|
16183
16543
|
if (!query) {
|
|
16184
16544
|
throw new Error('query is required for mode="search"');
|
|
@@ -16194,11 +16554,12 @@ var recallTool = (_memoryConfig, options) => {
|
|
|
16194
16554
|
topK: limit ?? 10,
|
|
16195
16555
|
before,
|
|
16196
16556
|
after,
|
|
16197
|
-
threadScope: !isResourceScope ? currentThreadId || void 0 : void 0
|
|
16557
|
+
threadScope: !isResourceScope ? currentThreadId || void 0 : resolvedExplicitThreadId || void 0
|
|
16198
16558
|
});
|
|
16199
16559
|
}
|
|
16200
16560
|
if (mode === "threads") {
|
|
16201
|
-
|
|
16561
|
+
const requestedCurrentThread = explicitThreadId === "current";
|
|
16562
|
+
if (!isResourceScope || requestedCurrentThread) {
|
|
16202
16563
|
if (!currentThreadId || !memory.getThreadById) {
|
|
16203
16564
|
return { error: "Could not resolve current thread." };
|
|
16204
16565
|
}
|
|
@@ -16206,6 +16567,9 @@ var recallTool = (_memoryConfig, options) => {
|
|
|
16206
16567
|
if (!thread) {
|
|
16207
16568
|
return { error: "Could not resolve current thread." };
|
|
16208
16569
|
}
|
|
16570
|
+
if (isResourceScope && resourceId && thread.resourceId !== resourceId) {
|
|
16571
|
+
throw new Error("Thread does not belong to the active resource");
|
|
16572
|
+
}
|
|
16209
16573
|
return {
|
|
16210
16574
|
threads: `- **${thread.title || "(untitled)"}** \u2190 current
|
|
16211
16575
|
id: ${thread.id}
|
|
@@ -16228,7 +16592,13 @@ var recallTool = (_memoryConfig, options) => {
|
|
|
16228
16592
|
after
|
|
16229
16593
|
});
|
|
16230
16594
|
}
|
|
16231
|
-
const
|
|
16595
|
+
const usedDefaultThreadId = isResourceScope && !explicitThreadId && !cursor && Boolean(currentThreadId);
|
|
16596
|
+
const defaultThreadNote = usedDefaultThreadId ? `threadId wasn't passed so used default ${currentThreadId}.
|
|
16597
|
+
|
|
16598
|
+
` : "";
|
|
16599
|
+
const effectiveThreadId = explicitThreadId || (usedDefaultThreadId ? "current" : void 0);
|
|
16600
|
+
const resolvedThreadId = effectiveThreadId === "current" ? currentThreadId : effectiveThreadId;
|
|
16601
|
+
const hasExplicitThreadId = typeof resolvedThreadId === "string" && resolvedThreadId.length > 0;
|
|
16232
16602
|
const hasCursor = typeof cursor === "string" && cursor.length > 0;
|
|
16233
16603
|
if (!hasExplicitThreadId && !hasCursor) {
|
|
16234
16604
|
throw new Error('Either cursor or threadId is required for mode="messages"');
|
|
@@ -16245,7 +16615,7 @@ var recallTool = (_memoryConfig, options) => {
|
|
|
16245
16615
|
if (!memory.getThreadById) {
|
|
16246
16616
|
throw new Error("Memory instance cannot verify thread access for recall");
|
|
16247
16617
|
}
|
|
16248
|
-
const thread = await memory.getThreadById({ threadId:
|
|
16618
|
+
const thread = await memory.getThreadById({ threadId: resolvedThreadId });
|
|
16249
16619
|
if (!thread || thread.resourceId !== resourceId) {
|
|
16250
16620
|
throw new Error("Thread does not belong to the active resource");
|
|
16251
16621
|
}
|
|
@@ -16280,14 +16650,21 @@ var recallTool = (_memoryConfig, options) => {
|
|
|
16280
16650
|
throw new Error("Thread ID is required for recall");
|
|
16281
16651
|
}
|
|
16282
16652
|
if (!cursor) {
|
|
16283
|
-
|
|
16653
|
+
const result = await recallThreadFromStart({
|
|
16284
16654
|
memory,
|
|
16285
16655
|
threadId: targetThreadId,
|
|
16286
16656
|
resourceId: isResourceScope ? resourceId : void 0,
|
|
16287
16657
|
page: page ?? 1,
|
|
16288
16658
|
limit: limit ?? 20,
|
|
16289
|
-
detail: detail ?? "low"
|
|
16659
|
+
detail: detail ?? "low",
|
|
16660
|
+
partType,
|
|
16661
|
+
toolName,
|
|
16662
|
+
anchor: anchor ?? "start"
|
|
16290
16663
|
});
|
|
16664
|
+
if (defaultThreadNote) {
|
|
16665
|
+
return { ...result, messages: `${defaultThreadNote}${result.messages}` };
|
|
16666
|
+
}
|
|
16667
|
+
return result;
|
|
16291
16668
|
}
|
|
16292
16669
|
if (partIndex !== void 0 && partIndex !== null) {
|
|
16293
16670
|
return recallPart({
|
|
@@ -16307,6 +16684,8 @@ var recallTool = (_memoryConfig, options) => {
|
|
|
16307
16684
|
page,
|
|
16308
16685
|
limit,
|
|
16309
16686
|
detail: detail ?? "low",
|
|
16687
|
+
partType,
|
|
16688
|
+
toolName,
|
|
16310
16689
|
threadScope
|
|
16311
16690
|
});
|
|
16312
16691
|
}
|
|
@@ -16338,6 +16717,25 @@ function deepMergeWorkingMemory(existing, update) {
|
|
|
16338
16717
|
}
|
|
16339
16718
|
return result;
|
|
16340
16719
|
}
|
|
16720
|
+
function stripNullsFromOptional(value, schema) {
|
|
16721
|
+
if (Array.isArray(value)) {
|
|
16722
|
+
const itemSchema = schema.items ?? {};
|
|
16723
|
+
return value.map((item) => stripNullsFromOptional(item, itemSchema));
|
|
16724
|
+
}
|
|
16725
|
+
if (typeof value === "object" && value !== null) {
|
|
16726
|
+
const properties = schema.properties ?? {};
|
|
16727
|
+
const required = schema.required ?? [];
|
|
16728
|
+
const result = {};
|
|
16729
|
+
for (const [key, propertyValue] of Object.entries(value)) {
|
|
16730
|
+
if (propertyValue === null && !required.includes(key)) {
|
|
16731
|
+
continue;
|
|
16732
|
+
}
|
|
16733
|
+
result[key] = stripNullsFromOptional(propertyValue, properties[key] ?? {});
|
|
16734
|
+
}
|
|
16735
|
+
return result;
|
|
16736
|
+
}
|
|
16737
|
+
return value;
|
|
16738
|
+
}
|
|
16341
16739
|
var updateWorkingMemoryTool = (memoryConfig) => {
|
|
16342
16740
|
const schema = memoryConfig?.workingMemory?.schema;
|
|
16343
16741
|
let inputSchema = z.object({
|
|
@@ -16347,7 +16745,7 @@ var updateWorkingMemoryTool = (memoryConfig) => {
|
|
|
16347
16745
|
const standardSchema2 = isStandardSchemaWithJSON$1(schema) ? schema : toStandardSchema$1(schema);
|
|
16348
16746
|
const jsonSchema4 = standardSchemaToJSONSchema(standardSchema2, { io: "input" });
|
|
16349
16747
|
delete jsonSchema4.$schema;
|
|
16350
|
-
|
|
16748
|
+
const wrappedSchema = toStandardSchema$1({
|
|
16351
16749
|
$schema: "http://json-schema.org/draft-07/schema#",
|
|
16352
16750
|
type: "object",
|
|
16353
16751
|
description: "The JSON formatted working memory content to store.",
|
|
@@ -16356,6 +16754,41 @@ var updateWorkingMemoryTool = (memoryConfig) => {
|
|
|
16356
16754
|
},
|
|
16357
16755
|
required: ["memory"]
|
|
16358
16756
|
});
|
|
16757
|
+
inputSchema = {
|
|
16758
|
+
"~standard": {
|
|
16759
|
+
version: 1,
|
|
16760
|
+
vendor: "mastra",
|
|
16761
|
+
validate: (value) => {
|
|
16762
|
+
const wrappedResult = wrappedSchema["~standard"].validate(value);
|
|
16763
|
+
if (wrappedResult instanceof Promise) {
|
|
16764
|
+
return wrappedResult.then((result) => {
|
|
16765
|
+
if (!("issues" in result) || !result.issues) {
|
|
16766
|
+
return result;
|
|
16767
|
+
}
|
|
16768
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || "memory" in value) {
|
|
16769
|
+
return result;
|
|
16770
|
+
}
|
|
16771
|
+
return wrappedSchema["~standard"].validate({
|
|
16772
|
+
memory: stripNullsFromOptional(value, jsonSchema4)
|
|
16773
|
+
});
|
|
16774
|
+
});
|
|
16775
|
+
}
|
|
16776
|
+
if (!("issues" in wrappedResult) || !wrappedResult.issues) {
|
|
16777
|
+
return wrappedResult;
|
|
16778
|
+
}
|
|
16779
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || "memory" in value) {
|
|
16780
|
+
return wrappedResult;
|
|
16781
|
+
}
|
|
16782
|
+
return wrappedSchema["~standard"].validate({
|
|
16783
|
+
memory: stripNullsFromOptional(value, jsonSchema4)
|
|
16784
|
+
});
|
|
16785
|
+
},
|
|
16786
|
+
jsonSchema: {
|
|
16787
|
+
input: (props) => wrappedSchema["~standard"].jsonSchema.input(props),
|
|
16788
|
+
output: (props) => wrappedSchema["~standard"].jsonSchema.output(props)
|
|
16789
|
+
}
|
|
16790
|
+
}
|
|
16791
|
+
};
|
|
16359
16792
|
}
|
|
16360
16793
|
const usesMergeSemantics = Boolean(schema);
|
|
16361
16794
|
const description = schema ? `Update the working memory with new information. Data is merged with existing memory - only include fields you want to add or update. To preserve existing data, omit the field entirely. Arrays are replaced entirely when provided, so pass the complete array or omit it to keep the existing values.` : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`;
|
|
@@ -16527,6 +16960,69 @@ var __experimental_updateWorkingMemoryToolVNext = (config) => {
|
|
|
16527
16960
|
}
|
|
16528
16961
|
});
|
|
16529
16962
|
};
|
|
16963
|
+
var WORKING_MEMORY_START_TAG = "<working_memory>";
|
|
16964
|
+
var WORKING_MEMORY_END_TAG = "</working_memory>";
|
|
16965
|
+
var LEGACY_SYSTEM_REMINDER_METADATA_KEY = "dynamicAgentsMdReminder";
|
|
16966
|
+
function isRecord(value) {
|
|
16967
|
+
return typeof value === "object" && value !== null;
|
|
16968
|
+
}
|
|
16969
|
+
function extractWorkingMemoryTags(text4) {
|
|
16970
|
+
const results = [];
|
|
16971
|
+
let pos = 0;
|
|
16972
|
+
while (pos < text4.length) {
|
|
16973
|
+
const start = text4.indexOf(WORKING_MEMORY_START_TAG, pos);
|
|
16974
|
+
if (start === -1) break;
|
|
16975
|
+
const end = text4.indexOf(WORKING_MEMORY_END_TAG, start + WORKING_MEMORY_START_TAG.length);
|
|
16976
|
+
if (end === -1) break;
|
|
16977
|
+
results.push(text4.substring(start, end + WORKING_MEMORY_END_TAG.length));
|
|
16978
|
+
pos = end + WORKING_MEMORY_END_TAG.length;
|
|
16979
|
+
}
|
|
16980
|
+
return results.length > 0 ? results : null;
|
|
16981
|
+
}
|
|
16982
|
+
function removeWorkingMemoryTags(text4) {
|
|
16983
|
+
let result = "";
|
|
16984
|
+
let pos = 0;
|
|
16985
|
+
while (pos < text4.length) {
|
|
16986
|
+
const start = text4.indexOf(WORKING_MEMORY_START_TAG, pos);
|
|
16987
|
+
if (start === -1) {
|
|
16988
|
+
result += text4.substring(pos);
|
|
16989
|
+
break;
|
|
16990
|
+
}
|
|
16991
|
+
result += text4.substring(pos, start);
|
|
16992
|
+
const end = text4.indexOf(WORKING_MEMORY_END_TAG, start + WORKING_MEMORY_START_TAG.length);
|
|
16993
|
+
if (end === -1) {
|
|
16994
|
+
result += text4.substring(start);
|
|
16995
|
+
break;
|
|
16996
|
+
}
|
|
16997
|
+
pos = end + WORKING_MEMORY_END_TAG.length;
|
|
16998
|
+
}
|
|
16999
|
+
return result;
|
|
17000
|
+
}
|
|
17001
|
+
function extractWorkingMemoryContent(text4) {
|
|
17002
|
+
const start = text4.indexOf(WORKING_MEMORY_START_TAG);
|
|
17003
|
+
if (start === -1) return null;
|
|
17004
|
+
const contentStart = start + WORKING_MEMORY_START_TAG.length;
|
|
17005
|
+
const end = text4.indexOf(WORKING_MEMORY_END_TAG, contentStart);
|
|
17006
|
+
if (end === -1) return null;
|
|
17007
|
+
return text4.substring(contentStart, end);
|
|
17008
|
+
}
|
|
17009
|
+
function isSystemReminderMessage(message) {
|
|
17010
|
+
if (message.role !== "user" || !isRecord(message.content)) {
|
|
17011
|
+
return false;
|
|
17012
|
+
}
|
|
17013
|
+
const metadata = message.content.metadata;
|
|
17014
|
+
if (isRecord(metadata) && (isRecord(metadata.systemReminder) || LEGACY_SYSTEM_REMINDER_METADATA_KEY in metadata)) {
|
|
17015
|
+
return true;
|
|
17016
|
+
}
|
|
17017
|
+
const firstTextPart = message.content.parts.find((part) => part.type === "text");
|
|
17018
|
+
return typeof firstTextPart?.text === "string" && firstTextPart.text.startsWith("<system-reminder");
|
|
17019
|
+
}
|
|
17020
|
+
function filterSystemReminderMessages(messages, includeSystemReminders) {
|
|
17021
|
+
if (includeSystemReminders) {
|
|
17022
|
+
return messages;
|
|
17023
|
+
}
|
|
17024
|
+
return messages.filter((message) => !isSystemReminderMessage(message));
|
|
17025
|
+
}
|
|
16530
17026
|
function normalizeObservationalMemoryConfig(config) {
|
|
16531
17027
|
if (config === true) return { model: "google/gemini-2.5-flash" };
|
|
16532
17028
|
if (config === false || config === void 0) return void 0;
|
|
@@ -16599,94 +17095,149 @@ var Memory = class extends MastraMemory {
|
|
|
16599
17095
|
);
|
|
16600
17096
|
}
|
|
16601
17097
|
}
|
|
17098
|
+
createMemorySpan(operationType, observabilityContext, input, attributes) {
|
|
17099
|
+
const currentSpan = observabilityContext?.tracingContext?.currentSpan;
|
|
17100
|
+
if (!currentSpan) return void 0;
|
|
17101
|
+
return currentSpan.createChildSpan({
|
|
17102
|
+
type: SpanType.MEMORY_OPERATION,
|
|
17103
|
+
name: `memory: ${operationType}`,
|
|
17104
|
+
entityType: EntityType.MEMORY,
|
|
17105
|
+
entityName: "Memory",
|
|
17106
|
+
input,
|
|
17107
|
+
attributes: { operationType, ...attributes }
|
|
17108
|
+
});
|
|
17109
|
+
}
|
|
16602
17110
|
async recall(args) {
|
|
16603
|
-
const {
|
|
16604
|
-
const config = this.getMergedThreadConfig(threadConfig || {});
|
|
16605
|
-
if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId, config);
|
|
16606
|
-
const perPage = perPageArg !== void 0 ? perPageArg : config.lastMessages;
|
|
16607
|
-
const historyDisabledByConfig = config.lastMessages === false && perPageArg === void 0;
|
|
16608
|
-
const shouldGetNewestAndReverse = !orderBy && perPage !== false;
|
|
16609
|
-
const effectiveOrderBy = shouldGetNewestAndReverse ? { field: "createdAt", direction: "DESC" } : orderBy;
|
|
16610
|
-
const vectorResults = [];
|
|
16611
|
-
this.logger.debug("Memory recall", {
|
|
17111
|
+
const {
|
|
16612
17112
|
threadId,
|
|
16613
|
-
|
|
17113
|
+
resourceId,
|
|
17114
|
+
perPage: perPageArg,
|
|
16614
17115
|
page,
|
|
16615
|
-
orderBy
|
|
16616
|
-
|
|
16617
|
-
|
|
16618
|
-
|
|
16619
|
-
|
|
16620
|
-
}
|
|
16621
|
-
const
|
|
16622
|
-
const
|
|
16623
|
-
const
|
|
16624
|
-
|
|
16625
|
-
|
|
16626
|
-
|
|
16627
|
-
|
|
16628
|
-
|
|
16629
|
-
|
|
16630
|
-
|
|
16631
|
-
|
|
16632
|
-
|
|
16633
|
-
|
|
16634
|
-
|
|
16635
|
-
|
|
16636
|
-
|
|
16637
|
-
|
|
16638
|
-
|
|
16639
|
-
|
|
16640
|
-
|
|
16641
|
-
|
|
16642
|
-
|
|
16643
|
-
|
|
16644
|
-
|
|
16645
|
-
|
|
16646
|
-
|
|
16647
|
-
|
|
16648
|
-
|
|
16649
|
-
|
|
17116
|
+
orderBy,
|
|
17117
|
+
threadConfig,
|
|
17118
|
+
vectorSearchString,
|
|
17119
|
+
includeSystemReminders,
|
|
17120
|
+
filter: filter3
|
|
17121
|
+
} = args;
|
|
17122
|
+
const config = this.getMergedThreadConfig(threadConfig || {});
|
|
17123
|
+
const semanticRecallEnabled = Boolean(config.semanticRecall);
|
|
17124
|
+
const span = this.createMemorySpan(
|
|
17125
|
+
"recall",
|
|
17126
|
+
args.observabilityContext,
|
|
17127
|
+
{ threadId, resourceId, vectorSearchString },
|
|
17128
|
+
{
|
|
17129
|
+
semanticRecallEnabled,
|
|
17130
|
+
lastMessages: config.lastMessages
|
|
17131
|
+
}
|
|
17132
|
+
);
|
|
17133
|
+
try {
|
|
17134
|
+
if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId, config);
|
|
17135
|
+
const perPage = perPageArg !== void 0 ? perPageArg : config.lastMessages;
|
|
17136
|
+
const historyDisabledByConfig = config.lastMessages === false && perPageArg === void 0;
|
|
17137
|
+
const shouldGetNewestAndReverse = !orderBy && perPage !== false;
|
|
17138
|
+
const effectiveOrderBy = shouldGetNewestAndReverse ? { field: "createdAt", direction: "DESC" } : orderBy;
|
|
17139
|
+
const vectorResults = [];
|
|
17140
|
+
this.logger.debug("Memory recall", {
|
|
17141
|
+
threadId,
|
|
17142
|
+
perPage,
|
|
17143
|
+
page,
|
|
17144
|
+
orderBy: effectiveOrderBy,
|
|
17145
|
+
hasWorkingMemorySchema: Boolean(config.workingMemory?.schema),
|
|
17146
|
+
workingMemoryEnabled: config.workingMemory?.enabled,
|
|
17147
|
+
semanticRecallEnabled,
|
|
17148
|
+
historyDisabledByConfig
|
|
17149
|
+
});
|
|
17150
|
+
const defaultRange = DEFAULT_MESSAGE_RANGE;
|
|
17151
|
+
const defaultTopK = DEFAULT_TOP_K;
|
|
17152
|
+
const vectorConfig = typeof config?.semanticRecall === `boolean` ? {
|
|
17153
|
+
topK: defaultTopK,
|
|
17154
|
+
messageRange: defaultRange
|
|
17155
|
+
} : {
|
|
17156
|
+
topK: config?.semanticRecall?.topK ?? defaultTopK,
|
|
17157
|
+
messageRange: config?.semanticRecall?.messageRange ?? defaultRange
|
|
17158
|
+
};
|
|
17159
|
+
const resourceScope = typeof config?.semanticRecall === "object" && config?.semanticRecall?.scope !== `thread` || config.semanticRecall === true;
|
|
17160
|
+
if (resourceScope && !resourceId && config?.semanticRecall && vectorSearchString) {
|
|
17161
|
+
throw new Error(
|
|
17162
|
+
`Memory error: Resource-scoped semantic recall is enabled but no resourceId was provided. Either provide a resourceId or explicitly set semanticRecall.scope to 'thread'.`
|
|
17163
|
+
);
|
|
17164
|
+
}
|
|
17165
|
+
let usage;
|
|
17166
|
+
if (historyDisabledByConfig && (!config.semanticRecall || !vectorSearchString || !this.vector)) {
|
|
17167
|
+
const result = {
|
|
17168
|
+
messages: [],
|
|
17169
|
+
usage: void 0,
|
|
17170
|
+
total: 0,
|
|
17171
|
+
page: page ?? 0,
|
|
17172
|
+
perPage: 0,
|
|
17173
|
+
hasMore: false
|
|
17174
|
+
};
|
|
17175
|
+
span?.end({ output: { success: true }, attributes: { messageCount: 0 } });
|
|
17176
|
+
return result;
|
|
17177
|
+
}
|
|
17178
|
+
if (config?.semanticRecall && vectorSearchString && this.vector) {
|
|
17179
|
+
const result = await this.embedMessageContent(vectorSearchString);
|
|
17180
|
+
usage = result.usage;
|
|
17181
|
+
const { embeddings, dimension } = result;
|
|
17182
|
+
const { indexName } = await this.createEmbeddingIndex(dimension, config);
|
|
17183
|
+
await Promise.all(
|
|
17184
|
+
embeddings.map(async (embedding) => {
|
|
17185
|
+
if (typeof this.vector === `undefined`) {
|
|
17186
|
+
throw new Error(
|
|
17187
|
+
`Tried to query vector index ${indexName} but this Memory instance doesn't have an attached vector db.`
|
|
17188
|
+
);
|
|
17189
|
+
}
|
|
17190
|
+
vectorResults.push(
|
|
17191
|
+
...await this.vector.query({
|
|
17192
|
+
indexName,
|
|
17193
|
+
queryVector: embedding,
|
|
17194
|
+
topK: vectorConfig.topK,
|
|
17195
|
+
filter: resourceScope ? {
|
|
17196
|
+
resource_id: resourceId
|
|
17197
|
+
} : {
|
|
17198
|
+
thread_id: threadId
|
|
17199
|
+
}
|
|
17200
|
+
})
|
|
16650
17201
|
);
|
|
16651
|
-
}
|
|
16652
|
-
|
|
16653
|
-
|
|
16654
|
-
|
|
16655
|
-
|
|
16656
|
-
|
|
16657
|
-
|
|
16658
|
-
|
|
16659
|
-
|
|
16660
|
-
|
|
16661
|
-
|
|
16662
|
-
|
|
16663
|
-
|
|
16664
|
-
|
|
16665
|
-
|
|
17202
|
+
})
|
|
17203
|
+
);
|
|
17204
|
+
}
|
|
17205
|
+
const memoryStore = await this.getMemoryStore();
|
|
17206
|
+
const effectivePerPage = historyDisabledByConfig ? 0 : perPage;
|
|
17207
|
+
const paginatedResult = await memoryStore.listMessages({
|
|
17208
|
+
threadId,
|
|
17209
|
+
resourceId,
|
|
17210
|
+
perPage: effectivePerPage,
|
|
17211
|
+
page,
|
|
17212
|
+
orderBy: effectiveOrderBy,
|
|
17213
|
+
filter: filter3,
|
|
17214
|
+
...vectorResults?.length ? {
|
|
17215
|
+
include: vectorResults.map((r) => ({
|
|
17216
|
+
id: r.metadata?.message_id,
|
|
17217
|
+
threadId: r.metadata?.thread_id,
|
|
17218
|
+
withNextMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.after,
|
|
17219
|
+
withPreviousMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.before
|
|
17220
|
+
}))
|
|
17221
|
+
} : {}
|
|
17222
|
+
});
|
|
17223
|
+
const rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;
|
|
17224
|
+
const list = new MessageList({ threadId, resourceId }).add(rawMessages, "memory");
|
|
17225
|
+
const messages = filterSystemReminderMessages(list.get.all.db(), includeSystemReminders);
|
|
17226
|
+
const { total, page: resultPage, perPage: resultPerPage, hasMore } = paginatedResult;
|
|
17227
|
+
const recallResult = { messages, usage, total, page: resultPage, perPage: resultPerPage, hasMore };
|
|
17228
|
+
span?.end({
|
|
17229
|
+
output: { success: true },
|
|
17230
|
+
attributes: {
|
|
17231
|
+
messageCount: messages.length,
|
|
17232
|
+
embeddingTokens: usage?.tokens,
|
|
17233
|
+
vectorResultCount: vectorResults.length
|
|
17234
|
+
}
|
|
17235
|
+
});
|
|
17236
|
+
return recallResult;
|
|
17237
|
+
} catch (error) {
|
|
17238
|
+
span?.error({ error, endSpan: true });
|
|
17239
|
+
throw error;
|
|
16666
17240
|
}
|
|
16667
|
-
const memoryStore = await this.getMemoryStore();
|
|
16668
|
-
const effectivePerPage = historyDisabledByConfig ? 0 : perPage;
|
|
16669
|
-
const paginatedResult = await memoryStore.listMessages({
|
|
16670
|
-
threadId,
|
|
16671
|
-
resourceId,
|
|
16672
|
-
perPage: effectivePerPage,
|
|
16673
|
-
page,
|
|
16674
|
-
orderBy: effectiveOrderBy,
|
|
16675
|
-
filter: filter3,
|
|
16676
|
-
...vectorResults?.length ? {
|
|
16677
|
-
include: vectorResults.map((r) => ({
|
|
16678
|
-
id: r.metadata?.message_id,
|
|
16679
|
-
threadId: r.metadata?.thread_id,
|
|
16680
|
-
withNextMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.after,
|
|
16681
|
-
withPreviousMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.before
|
|
16682
|
-
}))
|
|
16683
|
-
} : {}
|
|
16684
|
-
});
|
|
16685
|
-
const rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;
|
|
16686
|
-
const list = new MessageList({ threadId, resourceId }).add(rawMessages, "memory");
|
|
16687
|
-
const messages = list.get.all.db();
|
|
16688
|
-
const { total, page: resultPage, perPage: resultPerPage, hasMore } = paginatedResult;
|
|
16689
|
-
return { messages, usage, total, page: resultPage, perPage: resultPerPage, hasMore };
|
|
16690
17241
|
}
|
|
16691
17242
|
async getThreadById({ threadId }) {
|
|
16692
17243
|
const memoryStore = await this.getMemoryStore();
|
|
@@ -16796,45 +17347,60 @@ var Memory = class extends MastraMemory {
|
|
|
16796
17347
|
threadId,
|
|
16797
17348
|
resourceId,
|
|
16798
17349
|
workingMemory,
|
|
16799
|
-
memoryConfig
|
|
17350
|
+
memoryConfig,
|
|
17351
|
+
observabilityContext
|
|
16800
17352
|
}) {
|
|
16801
17353
|
const config = this.getMergedThreadConfig(memoryConfig || {});
|
|
16802
17354
|
if (!config.workingMemory?.enabled) {
|
|
16803
17355
|
throw new Error("Working memory is not enabled for this memory instance");
|
|
16804
17356
|
}
|
|
16805
|
-
const
|
|
16806
|
-
|
|
16807
|
-
|
|
16808
|
-
|
|
16809
|
-
|
|
16810
|
-
|
|
16811
|
-
|
|
16812
|
-
|
|
16813
|
-
this.updateWorkingMemoryMutexes.set(mutexKey, mutex);
|
|
16814
|
-
const release = await mutex.acquire();
|
|
17357
|
+
const span = this.createMemorySpan(
|
|
17358
|
+
"update",
|
|
17359
|
+
observabilityContext,
|
|
17360
|
+
{ threadId, resourceId },
|
|
17361
|
+
{
|
|
17362
|
+
workingMemoryEnabled: true
|
|
17363
|
+
}
|
|
17364
|
+
);
|
|
16815
17365
|
try {
|
|
16816
|
-
const
|
|
16817
|
-
if (scope === "resource" && resourceId) {
|
|
16818
|
-
|
|
16819
|
-
resourceId
|
|
16820
|
-
|
|
16821
|
-
|
|
16822
|
-
}
|
|
16823
|
-
|
|
16824
|
-
|
|
16825
|
-
|
|
16826
|
-
|
|
16827
|
-
await
|
|
16828
|
-
|
|
16829
|
-
|
|
16830
|
-
|
|
16831
|
-
...thread.metadata,
|
|
17366
|
+
const scope = config.workingMemory.scope || "resource";
|
|
17367
|
+
if (scope === "resource" && !resourceId) {
|
|
17368
|
+
throw new Error(
|
|
17369
|
+
`Memory error: Resource-scoped working memory is enabled but no resourceId was provided. Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`
|
|
17370
|
+
);
|
|
17371
|
+
}
|
|
17372
|
+
const mutexKey = scope === "resource" ? `resource-${resourceId}` : `thread-${threadId}`;
|
|
17373
|
+
const mutex = this.updateWorkingMemoryMutexes.has(mutexKey) ? this.updateWorkingMemoryMutexes.get(mutexKey) : new Mutex();
|
|
17374
|
+
this.updateWorkingMemoryMutexes.set(mutexKey, mutex);
|
|
17375
|
+
const release = await mutex.acquire();
|
|
17376
|
+
try {
|
|
17377
|
+
const memoryStore = await this.getMemoryStore();
|
|
17378
|
+
if (scope === "resource" && resourceId) {
|
|
17379
|
+
await memoryStore.updateResource({
|
|
17380
|
+
resourceId,
|
|
16832
17381
|
workingMemory
|
|
17382
|
+
});
|
|
17383
|
+
} else {
|
|
17384
|
+
const thread = await this.getThreadById({ threadId });
|
|
17385
|
+
if (!thread) {
|
|
17386
|
+
throw new Error(`Thread ${threadId} not found`);
|
|
16833
17387
|
}
|
|
16834
|
-
|
|
17388
|
+
await memoryStore.updateThread({
|
|
17389
|
+
id: threadId,
|
|
17390
|
+
title: thread.title || "",
|
|
17391
|
+
metadata: {
|
|
17392
|
+
...thread.metadata,
|
|
17393
|
+
workingMemory
|
|
17394
|
+
}
|
|
17395
|
+
});
|
|
17396
|
+
}
|
|
17397
|
+
} finally {
|
|
17398
|
+
release();
|
|
16835
17399
|
}
|
|
16836
|
-
|
|
16837
|
-
|
|
17400
|
+
span?.end({ output: { success: true } });
|
|
17401
|
+
} catch (error) {
|
|
17402
|
+
span?.error({ error, endSpan: true });
|
|
17403
|
+
throw error;
|
|
16838
17404
|
}
|
|
16839
17405
|
}
|
|
16840
17406
|
updateWorkingMemoryMutexes = /* @__PURE__ */ new Map();
|
|
@@ -17012,67 +17578,85 @@ ${workingMemory}`;
|
|
|
17012
17578
|
}
|
|
17013
17579
|
async saveMessages({
|
|
17014
17580
|
messages,
|
|
17015
|
-
memoryConfig
|
|
17581
|
+
memoryConfig,
|
|
17582
|
+
observabilityContext
|
|
17016
17583
|
}) {
|
|
17017
|
-
const
|
|
17018
|
-
|
|
17019
|
-
}).filter((m) => Boolean(m));
|
|
17020
|
-
const config = this.getMergedThreadConfig(memoryConfig);
|
|
17021
|
-
const dbMessages = new MessageList({
|
|
17022
|
-
generateMessageId: () => this.generateId()
|
|
17023
|
-
}).add(updatedMessages, "memory").get.all.db();
|
|
17024
|
-
const memoryStore = await this.getMemoryStore();
|
|
17025
|
-
const result = await memoryStore.saveMessages({
|
|
17026
|
-
messages: dbMessages
|
|
17584
|
+
const span = this.createMemorySpan("save", observabilityContext, void 0, {
|
|
17585
|
+
messageCount: messages.length
|
|
17027
17586
|
});
|
|
17028
|
-
|
|
17029
|
-
|
|
17030
|
-
|
|
17031
|
-
|
|
17032
|
-
|
|
17033
|
-
|
|
17034
|
-
|
|
17035
|
-
|
|
17036
|
-
|
|
17037
|
-
|
|
17038
|
-
|
|
17039
|
-
|
|
17587
|
+
try {
|
|
17588
|
+
const updatedMessages = messages.map((m) => {
|
|
17589
|
+
return this.updateMessageToHideWorkingMemoryV2(m);
|
|
17590
|
+
}).filter((m) => Boolean(m));
|
|
17591
|
+
const config = this.getMergedThreadConfig(memoryConfig);
|
|
17592
|
+
const dbMessages = new MessageList({
|
|
17593
|
+
generateMessageId: () => this.generateId()
|
|
17594
|
+
}).add(updatedMessages, "memory").get.all.db();
|
|
17595
|
+
const memoryStore = await this.getMemoryStore();
|
|
17596
|
+
const result = await memoryStore.saveMessages({
|
|
17597
|
+
messages: dbMessages
|
|
17598
|
+
});
|
|
17599
|
+
let totalTokens = 0;
|
|
17600
|
+
if (this.vector && config.semanticRecall) {
|
|
17601
|
+
const embeddingData = [];
|
|
17602
|
+
let dimension;
|
|
17603
|
+
await Promise.all(
|
|
17604
|
+
updatedMessages.map(async (message) => {
|
|
17605
|
+
let textForEmbedding = null;
|
|
17606
|
+
if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") {
|
|
17607
|
+
textForEmbedding = message.content.content;
|
|
17608
|
+
} else if (message.content.parts && message.content.parts.length > 0) {
|
|
17609
|
+
const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
|
|
17610
|
+
if (joined) textForEmbedding = joined;
|
|
17611
|
+
}
|
|
17612
|
+
if (!textForEmbedding) return;
|
|
17613
|
+
const result2 = await this.embedMessageContent(textForEmbedding);
|
|
17614
|
+
dimension = result2.dimension;
|
|
17615
|
+
if (result2.usage?.tokens) {
|
|
17616
|
+
totalTokens += result2.usage.tokens;
|
|
17617
|
+
}
|
|
17618
|
+
embeddingData.push({
|
|
17619
|
+
embeddings: result2.embeddings,
|
|
17620
|
+
metadata: result2.chunks.map(() => ({
|
|
17621
|
+
message_id: message.id,
|
|
17622
|
+
thread_id: message.threadId,
|
|
17623
|
+
resource_id: message.resourceId
|
|
17624
|
+
}))
|
|
17625
|
+
});
|
|
17626
|
+
})
|
|
17627
|
+
);
|
|
17628
|
+
if (embeddingData.length > 0 && dimension !== void 0) {
|
|
17629
|
+
if (typeof this.vector === `undefined`) {
|
|
17630
|
+
throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);
|
|
17040
17631
|
}
|
|
17041
|
-
|
|
17042
|
-
const
|
|
17043
|
-
|
|
17044
|
-
|
|
17045
|
-
|
|
17632
|
+
const { indexName } = await this.createEmbeddingIndex(dimension, config);
|
|
17633
|
+
const allVectors = [];
|
|
17634
|
+
const allMetadata = [];
|
|
17635
|
+
for (const data of embeddingData) {
|
|
17636
|
+
allVectors.push(...data.embeddings);
|
|
17637
|
+
allMetadata.push(...data.metadata);
|
|
17046
17638
|
}
|
|
17047
|
-
|
|
17048
|
-
|
|
17049
|
-
|
|
17050
|
-
|
|
17051
|
-
thread_id: message.threadId,
|
|
17052
|
-
resource_id: message.resourceId
|
|
17053
|
-
}))
|
|
17639
|
+
await this.vector.upsert({
|
|
17640
|
+
indexName,
|
|
17641
|
+
vectors: allVectors,
|
|
17642
|
+
metadata: allMetadata
|
|
17054
17643
|
});
|
|
17055
|
-
})
|
|
17056
|
-
);
|
|
17057
|
-
if (embeddingData.length > 0 && dimension !== void 0) {
|
|
17058
|
-
if (typeof this.vector === `undefined`) {
|
|
17059
|
-
throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);
|
|
17060
|
-
}
|
|
17061
|
-
const { indexName } = await this.createEmbeddingIndex(dimension, config);
|
|
17062
|
-
const allVectors = [];
|
|
17063
|
-
const allMetadata = [];
|
|
17064
|
-
for (const data of embeddingData) {
|
|
17065
|
-
allVectors.push(...data.embeddings);
|
|
17066
|
-
allMetadata.push(...data.metadata);
|
|
17067
17644
|
}
|
|
17068
|
-
await this.vector.upsert({
|
|
17069
|
-
indexName,
|
|
17070
|
-
vectors: allVectors,
|
|
17071
|
-
metadata: allMetadata
|
|
17072
|
-
});
|
|
17073
17645
|
}
|
|
17646
|
+
const saveResult = { ...result, usage: totalTokens > 0 ? { tokens: totalTokens } : void 0 };
|
|
17647
|
+
span?.end({
|
|
17648
|
+
output: { success: true },
|
|
17649
|
+
attributes: {
|
|
17650
|
+
messageCount: dbMessages.length,
|
|
17651
|
+
embeddingTokens: saveResult.usage?.tokens,
|
|
17652
|
+
semanticRecallEnabled: Boolean(config.semanticRecall)
|
|
17653
|
+
}
|
|
17654
|
+
});
|
|
17655
|
+
return saveResult;
|
|
17656
|
+
} catch (error) {
|
|
17657
|
+
span?.error({ error, endSpan: true });
|
|
17658
|
+
throw error;
|
|
17074
17659
|
}
|
|
17075
|
-
return { ...result, usage: totalTokens > 0 ? { tokens: totalTokens } : void 0 };
|
|
17076
17660
|
}
|
|
17077
17661
|
updateMessageToHideWorkingMemoryV2(message) {
|
|
17078
17662
|
const newMessage = { ...message };
|
|
@@ -17244,7 +17828,7 @@ ${workingMemory}`;
|
|
|
17244
17828
|
if (obsSystemMessage) {
|
|
17245
17829
|
systemParts.push(obsSystemMessage);
|
|
17246
17830
|
}
|
|
17247
|
-
const { OBSERVATION_CONTINUATION_HINT } = await import('./constants-
|
|
17831
|
+
const { OBSERVATION_CONTINUATION_HINT } = await import('./constants-XEHPYRDJ.js');
|
|
17248
17832
|
continuationMessage = {
|
|
17249
17833
|
id: "om-continuation",
|
|
17250
17834
|
role: "user",
|
|
@@ -17344,7 +17928,7 @@ ${workingMemory}`;
|
|
|
17344
17928
|
"Observational memory requires @mastra/core support for request-response-id-rotation. Please bump @mastra/core to a newer version."
|
|
17345
17929
|
);
|
|
17346
17930
|
}
|
|
17347
|
-
const { ObservationalMemory: OMClass } = await import('./observational-memory-
|
|
17931
|
+
const { ObservationalMemory: OMClass } = await import('./observational-memory-UMDC4VC2.js');
|
|
17348
17932
|
const onIndexObservations = this.hasRetrievalSearch(omConfig.retrieval) ? async (observation) => {
|
|
17349
17933
|
await this.indexObservation(observation);
|
|
17350
17934
|
} : void 0;
|
|
@@ -17352,6 +17936,8 @@ ${workingMemory}`;
|
|
|
17352
17936
|
storage: memoryStore,
|
|
17353
17937
|
scope: omConfig.scope,
|
|
17354
17938
|
retrieval: omConfig.retrieval,
|
|
17939
|
+
activateAfterIdle: omConfig.activateAfterIdle,
|
|
17940
|
+
activateOnProviderChange: omConfig.activateOnProviderChange,
|
|
17355
17941
|
shareTokenBudget: omConfig.shareTokenBudget,
|
|
17356
17942
|
model: omConfig.model,
|
|
17357
17943
|
onIndexObservations,
|
|
@@ -17607,6 +18193,32 @@ Notes:
|
|
|
17607
18193
|
}))
|
|
17608
18194
|
});
|
|
17609
18195
|
}
|
|
18196
|
+
/**
|
|
18197
|
+
* Update per-record observational memory config overrides for a thread.
|
|
18198
|
+
* The provided config is deep-merged, so you only need to specify fields you want to change.
|
|
18199
|
+
*
|
|
18200
|
+
* @example
|
|
18201
|
+
* ```ts
|
|
18202
|
+
* await memory.updateObservationalMemoryConfig({
|
|
18203
|
+
* threadId: 'thread-1',
|
|
18204
|
+
* config: {
|
|
18205
|
+
* observation: { messageTokens: 2000 },
|
|
18206
|
+
* reflection: { observationTokens: 8000 },
|
|
18207
|
+
* },
|
|
18208
|
+
* });
|
|
18209
|
+
* ```
|
|
18210
|
+
*/
|
|
18211
|
+
async updateObservationalMemoryConfig({
|
|
18212
|
+
threadId,
|
|
18213
|
+
resourceId,
|
|
18214
|
+
config
|
|
18215
|
+
}) {
|
|
18216
|
+
const omEngine = await this.omEngine;
|
|
18217
|
+
if (!omEngine) {
|
|
18218
|
+
throw new Error("Observational memory is not enabled");
|
|
18219
|
+
}
|
|
18220
|
+
await omEngine.updateRecordConfig(threadId, resourceId, config);
|
|
18221
|
+
}
|
|
17610
18222
|
/**
|
|
17611
18223
|
* Index a list of messages directly (without querying storage).
|
|
17612
18224
|
* Used by observe-time indexing to vectorize newly-observed messages.
|
|
@@ -17780,7 +18392,7 @@ Notes:
|
|
|
17780
18392
|
* - Message objects with 'id' properties
|
|
17781
18393
|
* @returns Promise that resolves when all messages are deleted
|
|
17782
18394
|
*/
|
|
17783
|
-
async deleteMessages(input) {
|
|
18395
|
+
async deleteMessages(input, observabilityContext) {
|
|
17784
18396
|
let messageIds;
|
|
17785
18397
|
if (!Array.isArray(input)) {
|
|
17786
18398
|
throw new Error("Invalid input: must be an array of message IDs or message objects");
|
|
@@ -17801,10 +18413,19 @@ Notes:
|
|
|
17801
18413
|
if (invalidIds.length > 0) {
|
|
17802
18414
|
throw new Error("All message IDs must be non-empty strings");
|
|
17803
18415
|
}
|
|
17804
|
-
const
|
|
17805
|
-
|
|
17806
|
-
|
|
17807
|
-
|
|
18416
|
+
const span = this.createMemorySpan("delete", observabilityContext, void 0, {
|
|
18417
|
+
messageCount: messageIds.length
|
|
18418
|
+
});
|
|
18419
|
+
try {
|
|
18420
|
+
const memoryStore = await this.getMemoryStore();
|
|
18421
|
+
await memoryStore.deleteMessages(messageIds);
|
|
18422
|
+
if (this.vector) {
|
|
18423
|
+
void this.deleteMessageVectors(messageIds);
|
|
18424
|
+
}
|
|
18425
|
+
span?.end({ output: { success: true }, attributes: { messageCount: messageIds.length } });
|
|
18426
|
+
} catch (error) {
|
|
18427
|
+
span?.error({ error, endSpan: true });
|
|
18428
|
+
throw error;
|
|
17808
18429
|
}
|
|
17809
18430
|
}
|
|
17810
18431
|
/**
|
|
@@ -18232,11 +18853,13 @@ Notes:
|
|
|
18232
18853
|
if (!effectiveConfig) return null;
|
|
18233
18854
|
const engine = await this.omEngine;
|
|
18234
18855
|
if (!engine) return null;
|
|
18235
|
-
const { ObservationalMemoryProcessor } = await import('./observational-memory-
|
|
18236
|
-
return new ObservationalMemoryProcessor(engine, this
|
|
18856
|
+
const { ObservationalMemoryProcessor } = await import('./observational-memory-UMDC4VC2.js');
|
|
18857
|
+
return new ObservationalMemoryProcessor(engine, this, {
|
|
18858
|
+
temporalMarkers: effectiveConfig.temporalMarkers
|
|
18859
|
+
});
|
|
18237
18860
|
}
|
|
18238
18861
|
};
|
|
18239
18862
|
|
|
18240
|
-
export { Memory, deepMergeWorkingMemory };
|
|
18863
|
+
export { Memory, deepMergeWorkingMemory, extractWorkingMemoryContent, extractWorkingMemoryTags, removeWorkingMemoryTags };
|
|
18241
18864
|
//# sourceMappingURL=index.js.map
|
|
18242
18865
|
//# sourceMappingURL=index.js.map
|