@mastra/platform 0.0.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +32 -0
- package/README.md +71 -4
- package/dist/browser/index.d.ts +18 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/index.cjs +709 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +695 -0
- package/dist/index.js.map +1 -0
- package/dist/knowledge/index.d.ts +20 -0
- package/dist/knowledge/index.d.ts.map +1 -0
- package/dist/memory/client.d.ts +242 -0
- package/dist/memory/client.d.ts.map +1 -0
- package/dist/memory/index.d.ts +5 -0
- package/dist/memory/index.d.ts.map +1 -0
- package/dist/memory/platform-memory.d.ts +86 -0
- package/dist/memory/platform-memory.d.ts.map +1 -0
- package/package.json +61 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,709 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _mastra_core_memory = require("@mastra/core/memory");
|
|
3
|
+
let _mastra_core_tools = require("@mastra/core/tools");
|
|
4
|
+
let zod = require("zod");
|
|
5
|
+
let _mastra_stagehand = require("@mastra/stagehand");
|
|
6
|
+
let _mastra_core_knowledge = require("@mastra/core/knowledge");
|
|
7
|
+
let _mastra_core_storage = require("@mastra/core/storage");
|
|
8
|
+
// src/memory/client.ts
|
|
9
|
+
const DEFAULT_API_URL$2 = "https://memory-api.mastra.ai";
|
|
10
|
+
const REQUEST_TIMEOUT_MS = 3e4;
|
|
11
|
+
const PROCESSOR_TIMEOUT_MS = 3e5;
|
|
12
|
+
function env(name) {
|
|
13
|
+
return process.env[name]?.trim() || void 0;
|
|
14
|
+
}
|
|
15
|
+
function required(value, name) {
|
|
16
|
+
if (!value) throw new Error(`PlatformMemory: ${name} is required`);
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
function resolvePlatformMemoryOptions(options = {}) {
|
|
20
|
+
return {
|
|
21
|
+
accessToken: required(options.accessToken ?? env("MASTRA_PLATFORM_ACCESS_TOKEN") ?? env("MASTRA_PLATFORM_SECRET_KEY"), "accessToken"),
|
|
22
|
+
instanceId: required(options.instanceId ?? env("MASTRA_MEMORY_INSTANCE_ID"), "instanceId"),
|
|
23
|
+
projectId: options.projectId ?? env("MASTRA_PROJECT_ID"),
|
|
24
|
+
environmentId: options.environmentId ?? env("MASTRA_ENVIRONMENT_ID"),
|
|
25
|
+
actingUserId: options.actingUserId,
|
|
26
|
+
apiUrl: (options.apiUrl ?? env("MASTRA_MEMORY_API_URL") ?? DEFAULT_API_URL$2).replace(/\/$/, ""),
|
|
27
|
+
fetch: options.fetch ?? fetch
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
var PlatformMemoryApiError = class extends Error {
|
|
31
|
+
status;
|
|
32
|
+
body;
|
|
33
|
+
constructor(status, body) {
|
|
34
|
+
super(`Platform Memory request failed with ${status}${body ? `: ${body}` : ""}`);
|
|
35
|
+
this.status = status;
|
|
36
|
+
this.body = body;
|
|
37
|
+
this.name = "PlatformMemoryApiError";
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
/** Typed client for the Platform Memory API (`/v1/memory/:instanceId/*`). */
|
|
41
|
+
var PlatformMemoryClient = class {
|
|
42
|
+
instanceId;
|
|
43
|
+
opts;
|
|
44
|
+
constructor(options = {}) {
|
|
45
|
+
this.opts = resolvePlatformMemoryOptions(options);
|
|
46
|
+
this.instanceId = this.opts.instanceId;
|
|
47
|
+
}
|
|
48
|
+
/** MCP endpoint for this instance, for clients that speak MCP directly. */
|
|
49
|
+
get mcpUrl() {
|
|
50
|
+
return `${this.base}/mcp`;
|
|
51
|
+
}
|
|
52
|
+
listThreads(query = {}) {
|
|
53
|
+
return this.request("GET", "/threads", { query });
|
|
54
|
+
}
|
|
55
|
+
createThread(body) {
|
|
56
|
+
return this.request("POST", "/threads", { body });
|
|
57
|
+
}
|
|
58
|
+
/** Returns null when the thread does not exist. */
|
|
59
|
+
async getThread(threadId) {
|
|
60
|
+
try {
|
|
61
|
+
return await this.request("GET", `/threads/${encodeURIComponent(threadId)}`);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (error instanceof PlatformMemoryApiError && error.status === 404) return null;
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
updateThread(threadId, body) {
|
|
68
|
+
return this.request("PATCH", `/threads/${encodeURIComponent(threadId)}`, { body });
|
|
69
|
+
}
|
|
70
|
+
async deleteThread(threadId) {
|
|
71
|
+
await this.request("DELETE", `/threads/${encodeURIComponent(threadId)}`);
|
|
72
|
+
}
|
|
73
|
+
listMessages(threadId, query = {}) {
|
|
74
|
+
return this.request("GET", `/threads/${encodeURIComponent(threadId)}/messages`, { query });
|
|
75
|
+
}
|
|
76
|
+
/** Saves messages and schedules observation in the background. Creates the thread if needed. */
|
|
77
|
+
saveMessages(threadId, body) {
|
|
78
|
+
return this.request("POST", `/threads/${encodeURIComponent(threadId)}/messages`, { body });
|
|
79
|
+
}
|
|
80
|
+
getContext(threadId, resourceId, opts = {}) {
|
|
81
|
+
return this.request("GET", `/threads/${encodeURIComponent(threadId)}/context`, { query: {
|
|
82
|
+
resourceId,
|
|
83
|
+
...opts.workingMemory ? { workingMemory: opts.workingMemory } : {}
|
|
84
|
+
} });
|
|
85
|
+
}
|
|
86
|
+
async getWorkingMemory(resourceId) {
|
|
87
|
+
return (await this.request("GET", "/working-memory", { query: { resourceId } })).workingMemory;
|
|
88
|
+
}
|
|
89
|
+
async updateWorkingMemory(resourceId, workingMemory) {
|
|
90
|
+
await this.request("PUT", "/working-memory", { body: {
|
|
91
|
+
resourceId,
|
|
92
|
+
workingMemory
|
|
93
|
+
} });
|
|
94
|
+
}
|
|
95
|
+
/** Omit resourceId to search the instance's most recently active threads. */
|
|
96
|
+
async search(body) {
|
|
97
|
+
return (await this.request("POST", "/search", { body })).matches;
|
|
98
|
+
}
|
|
99
|
+
/** Current observational-memory record for the thread, or null before the first observation. */
|
|
100
|
+
async getObservations(threadId) {
|
|
101
|
+
return (await this.request("GET", `/threads/${encodeURIComponent(threadId)}/observations`)).record;
|
|
102
|
+
}
|
|
103
|
+
/** Runs the instance's memory processors for one agent phase on a serialized message list. */
|
|
104
|
+
runProcessors(threadId, body, signal) {
|
|
105
|
+
return this.request("POST", `/threads/${encodeURIComponent(threadId)}/processors`, {
|
|
106
|
+
body,
|
|
107
|
+
signal,
|
|
108
|
+
timeoutMs: PROCESSOR_TIMEOUT_MS
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
async listObservationRuns(query = {}) {
|
|
112
|
+
return (await this.request("GET", "/runs", { query })).runs;
|
|
113
|
+
}
|
|
114
|
+
/** Effective observation thresholds for the thread and which ones it overrides. */
|
|
115
|
+
getThreadConfig(threadId) {
|
|
116
|
+
return this.request("GET", `/threads/${encodeURIComponent(threadId)}/config`);
|
|
117
|
+
}
|
|
118
|
+
/** Overrides thresholds for one thread. Pass `null` to fall back to the instance value. */
|
|
119
|
+
updateThreadConfig(threadId, config) {
|
|
120
|
+
return this.request("PATCH", `/threads/${encodeURIComponent(threadId)}/config`, { body: config });
|
|
121
|
+
}
|
|
122
|
+
/** Copies a thread, its messages, and its observations. */
|
|
123
|
+
cloneThread(threadId, body = {}) {
|
|
124
|
+
return this.request("POST", `/threads/${encodeURIComponent(threadId)}/clone`, { body });
|
|
125
|
+
}
|
|
126
|
+
/** Deletes messages from a thread. Ids that belong to other threads are ignored. */
|
|
127
|
+
async deleteMessages(threadId, messageIds) {
|
|
128
|
+
return (await this.request("POST", `/threads/${encodeURIComponent(threadId)}/messages/delete`, { body: { messageIds } })).deleted;
|
|
129
|
+
}
|
|
130
|
+
/** Everything stored for one resource (user): working memory and threads. */
|
|
131
|
+
getResource(resourceId, query = {}) {
|
|
132
|
+
return this.request("GET", `/resources/${encodeURIComponent(resourceId)}`, { query });
|
|
133
|
+
}
|
|
134
|
+
/** Resources (users) in the instance, most recently active first. */
|
|
135
|
+
listResources(query = {}) {
|
|
136
|
+
return this.request("GET", "/resources", { query });
|
|
137
|
+
}
|
|
138
|
+
/** Deletes every thread, message, observation and the working memory for a resource. */
|
|
139
|
+
async deleteResource(resourceId) {
|
|
140
|
+
return (await this.request("DELETE", `/resources/${encodeURIComponent(resourceId)}`)).deletedThreads;
|
|
141
|
+
}
|
|
142
|
+
get base() {
|
|
143
|
+
return `${this.opts.apiUrl}/v1/memory/${encodeURIComponent(this.opts.instanceId)}`;
|
|
144
|
+
}
|
|
145
|
+
async request(method, path, init = {}) {
|
|
146
|
+
const url = new URL(this.base + path);
|
|
147
|
+
for (const [key, value] of Object.entries(init.query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
|
|
148
|
+
const headers = { authorization: `Bearer ${this.opts.accessToken}` };
|
|
149
|
+
if (this.opts.actingUserId) headers["x-acting-user-id"] = this.opts.actingUserId;
|
|
150
|
+
if (this.opts.projectId) headers["x-mastra-project-id"] = this.opts.projectId;
|
|
151
|
+
if (this.opts.environmentId) headers["x-mastra-environment-id"] = this.opts.environmentId;
|
|
152
|
+
if (init.body !== void 0) headers["content-type"] = "application/json";
|
|
153
|
+
const deadline = AbortSignal.timeout(init.timeoutMs ?? REQUEST_TIMEOUT_MS);
|
|
154
|
+
const res = await this.opts.fetch(url, {
|
|
155
|
+
method,
|
|
156
|
+
headers,
|
|
157
|
+
body: init.body === void 0 ? void 0 : JSON.stringify(init.body),
|
|
158
|
+
signal: init.signal ? AbortSignal.any([init.signal, deadline]) : deadline
|
|
159
|
+
});
|
|
160
|
+
if (!res.ok) throw new PlatformMemoryApiError(res.status, await res.text().catch(() => ""));
|
|
161
|
+
if (res.status === 204) return void 0;
|
|
162
|
+
return await res.json();
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
// src/memory/platform-memory.ts
|
|
166
|
+
function threadFromApi(thread) {
|
|
167
|
+
return {
|
|
168
|
+
id: thread.id,
|
|
169
|
+
resourceId: thread.resourceId,
|
|
170
|
+
title: thread.title ?? void 0,
|
|
171
|
+
metadata: thread.metadata ?? void 0,
|
|
172
|
+
createdAt: new Date(thread.createdAt),
|
|
173
|
+
updatedAt: new Date(thread.updatedAt)
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function messageFromApi(message, threadId, resourceId) {
|
|
177
|
+
return {
|
|
178
|
+
id: message.id,
|
|
179
|
+
role: message.role === "assistant" ? "assistant" : "user",
|
|
180
|
+
createdAt: new Date(message.createdAt),
|
|
181
|
+
threadId,
|
|
182
|
+
resourceId,
|
|
183
|
+
content: {
|
|
184
|
+
format: 2,
|
|
185
|
+
parts: message.parts?.length ? message.parts : [{
|
|
186
|
+
type: "text",
|
|
187
|
+
text: message.content
|
|
188
|
+
}]
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
function textOf(message) {
|
|
193
|
+
return (message.content.parts ?? []).filter((part) => part.type === "text").map((part) => part.text).join("\n") || message.content.content || "";
|
|
194
|
+
}
|
|
195
|
+
/** User/assistant messages with all their parts (tool calls, reasoning, files). System messages are skipped. */
|
|
196
|
+
function toApiMessages(messages) {
|
|
197
|
+
return messages.flatMap((message) => {
|
|
198
|
+
if (message.role !== "user" && message.role !== "assistant") return [];
|
|
199
|
+
const parts = message.content.parts ?? [];
|
|
200
|
+
const createdAt = new Date(message.createdAt).toISOString();
|
|
201
|
+
const content = textOf(message) || void 0;
|
|
202
|
+
if (!parts.length && !content) return [];
|
|
203
|
+
return [{
|
|
204
|
+
id: message.id,
|
|
205
|
+
role: message.role,
|
|
206
|
+
content,
|
|
207
|
+
parts: parts.length ? parts : void 0,
|
|
208
|
+
createdAt
|
|
209
|
+
}];
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
function memoryContext(requestContext, messageList) {
|
|
213
|
+
const ctx = (0, _mastra_core_memory.parseMemoryRequestContext)(requestContext);
|
|
214
|
+
if (ctx?.thread?.id) return {
|
|
215
|
+
threadId: ctx.thread.id,
|
|
216
|
+
resourceId: ctx.resourceId ?? ctx.thread.id,
|
|
217
|
+
readOnly: ctx.memoryConfig?.readOnly
|
|
218
|
+
};
|
|
219
|
+
const info = messageList.serialize().memoryInfo;
|
|
220
|
+
if (info?.threadId) return {
|
|
221
|
+
threadId: info.threadId,
|
|
222
|
+
resourceId: info.resourceId ?? info.threadId,
|
|
223
|
+
readOnly: false
|
|
224
|
+
};
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
const WORKING_MEMORY_TAG = "platform-working-memory";
|
|
228
|
+
/**
|
|
229
|
+
* Adds the resource's stored working memory as a system message. The hosted processors don't
|
|
230
|
+
* deliver it, so the client reads it on the first step of every run: a fresh read each run, so an
|
|
231
|
+
* update between runs shows up on the next one.
|
|
232
|
+
*/
|
|
233
|
+
async function addWorkingMemory(client, messageList, resourceId, canUpdate) {
|
|
234
|
+
const data = await client.getWorkingMemory(resourceId);
|
|
235
|
+
messageList.clearSystemMessages(WORKING_MEMORY_TAG);
|
|
236
|
+
if (canUpdate) messageList.addSystem(`WORKING_MEMORY_SYSTEM_INSTRUCTION:
|
|
237
|
+
Store and update any conversation-relevant information about the user by calling the updateWorkingMemory tool. Pass the whole memory each time: anything you leave out is removed.
|
|
238
|
+
|
|
239
|
+
<working_memory_data>
|
|
240
|
+
${data ?? ""}
|
|
241
|
+
</working_memory_data>`, WORKING_MEMORY_TAG);
|
|
242
|
+
else if (data) messageList.addSystem(`WORKING_MEMORY_SYSTEM_INSTRUCTION (READ-ONLY):
|
|
243
|
+
The following is what is remembered about the user. Use it for context; you cannot change it.
|
|
244
|
+
|
|
245
|
+
<working_memory_data>
|
|
246
|
+
${data}
|
|
247
|
+
</working_memory_data>`, WORKING_MEMORY_TAG);
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* What a read-only run sees of the thread, read through the context route, which writes nothing:
|
|
251
|
+
* observations, the continuation reminder, then the messages not yet observed. Running the hosted
|
|
252
|
+
* processors instead would save messages and start observation.
|
|
253
|
+
*/
|
|
254
|
+
async function addReadOnlyContext(client, messageList, threadId, resourceId) {
|
|
255
|
+
const context = await client.getContext(threadId, resourceId, { workingMemory: "off" });
|
|
256
|
+
const prompt = context.prompt ?? [
|
|
257
|
+
...context.system ? [{
|
|
258
|
+
id: "om-system",
|
|
259
|
+
role: "system",
|
|
260
|
+
content: context.system,
|
|
261
|
+
parts: [],
|
|
262
|
+
createdAt: (/* @__PURE__ */ new Date(0)).toISOString()
|
|
263
|
+
}] : [],
|
|
264
|
+
...context.continuation ? [{
|
|
265
|
+
id: "om-continuation",
|
|
266
|
+
role: "user",
|
|
267
|
+
content: context.continuation,
|
|
268
|
+
parts: [],
|
|
269
|
+
createdAt: (/* @__PURE__ */ new Date(0)).toISOString()
|
|
270
|
+
}] : [],
|
|
271
|
+
...context.messages
|
|
272
|
+
];
|
|
273
|
+
for (const message of prompt) if (message.role === "system") messageList.addSystem(message.content, "memory");
|
|
274
|
+
else messageList.add(messageFromApi(message, threadId, resourceId), "memory");
|
|
275
|
+
}
|
|
276
|
+
async function applyResult(result, agent) {
|
|
277
|
+
for (const chunk of result.chunks) await agent.writer?.custom(chunk);
|
|
278
|
+
for (let i = 0; i < result.rotations; i++) agent.rotateResponseMessageId?.();
|
|
279
|
+
if (result.aborted !== null || !result.messageList) return agent.abort(result.aborted ?? void 0);
|
|
280
|
+
return agent.messageList.deserialize(result.messageList);
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Mastra memory backed by a hosted Platform Memory instance.
|
|
284
|
+
*
|
|
285
|
+
* Observation and reflection run on the Platform: on each input step and on the final output this
|
|
286
|
+
* class sends the serialized message list to the instance's memory processors and applies the
|
|
287
|
+
* result. Messages are stored with all their parts (text, tool calls, reasoning, files).
|
|
288
|
+
*/
|
|
289
|
+
var PlatformMemory = class extends _mastra_core_memory.MastraMemory {
|
|
290
|
+
client;
|
|
291
|
+
workingMemoryMode;
|
|
292
|
+
constructor(options = {}) {
|
|
293
|
+
super({
|
|
294
|
+
id: options.id ?? "platform-memory",
|
|
295
|
+
name: "PlatformMemory"
|
|
296
|
+
});
|
|
297
|
+
this.client = options.client ?? new PlatformMemoryClient(options);
|
|
298
|
+
this.workingMemoryMode = options.workingMemory ?? "readonly";
|
|
299
|
+
}
|
|
300
|
+
listTools(config) {
|
|
301
|
+
if (this.workingMemoryMode !== "tool" || config?.readOnly) return {};
|
|
302
|
+
this.assertResourceScopedWorkingMemory(config);
|
|
303
|
+
const client = this.client;
|
|
304
|
+
return { updateWorkingMemory: (0, _mastra_core_tools.createTool)({
|
|
305
|
+
id: "update-working-memory",
|
|
306
|
+
description: "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.",
|
|
307
|
+
inputSchema: zod.z.object({ memory: zod.z.string().describe("The Markdown formatted working memory content to store.") }),
|
|
308
|
+
execute: async ({ memory }, context) => {
|
|
309
|
+
const resourceId = context?.agent?.resourceId ?? context?.agent?.threadId;
|
|
310
|
+
if (!resourceId) throw new Error("updateWorkingMemory needs a thread or resource");
|
|
311
|
+
await client.updateWorkingMemory(resourceId, memory);
|
|
312
|
+
return { success: true };
|
|
313
|
+
}
|
|
314
|
+
}) };
|
|
315
|
+
}
|
|
316
|
+
async getInputProcessors() {
|
|
317
|
+
const client = this.client;
|
|
318
|
+
const workingMemoryMode = this.workingMemoryMode;
|
|
319
|
+
return [{
|
|
320
|
+
id: "platform-memory",
|
|
321
|
+
name: "Platform Memory",
|
|
322
|
+
async processInputStep({ messageList, requestContext, stepNumber, model, writer, abort, abortSignal, rotateResponseMessageId }) {
|
|
323
|
+
const ctx = memoryContext(requestContext, messageList);
|
|
324
|
+
if (!ctx) return messageList;
|
|
325
|
+
if (ctx.readOnly) {
|
|
326
|
+
if (stepNumber === 0) {
|
|
327
|
+
await addReadOnlyContext(client, messageList, ctx.threadId, ctx.resourceId);
|
|
328
|
+
if (workingMemoryMode !== "off") await addWorkingMemory(client, messageList, ctx.resourceId, false);
|
|
329
|
+
}
|
|
330
|
+
return messageList;
|
|
331
|
+
}
|
|
332
|
+
const list = await applyResult(await client.runProcessors(ctx.threadId, {
|
|
333
|
+
phase: "inputStep",
|
|
334
|
+
resourceId: ctx.resourceId,
|
|
335
|
+
stepNumber,
|
|
336
|
+
messageList: messageList.serialize(),
|
|
337
|
+
model: model ? {
|
|
338
|
+
provider: model.provider,
|
|
339
|
+
modelId: model.modelId
|
|
340
|
+
} : void 0
|
|
341
|
+
}, abortSignal), {
|
|
342
|
+
messageList,
|
|
343
|
+
writer,
|
|
344
|
+
abort,
|
|
345
|
+
rotateResponseMessageId
|
|
346
|
+
});
|
|
347
|
+
if (stepNumber === 0 && workingMemoryMode !== "off") await addWorkingMemory(client, messageList, ctx.resourceId, workingMemoryMode === "tool");
|
|
348
|
+
return list;
|
|
349
|
+
}
|
|
350
|
+
}];
|
|
351
|
+
}
|
|
352
|
+
async getOutputProcessors() {
|
|
353
|
+
const client = this.client;
|
|
354
|
+
return [{
|
|
355
|
+
id: "platform-memory",
|
|
356
|
+
name: "Platform Memory",
|
|
357
|
+
async processOutputResult({ messageList, requestContext, result, writer, abort }) {
|
|
358
|
+
const ctx = memoryContext(requestContext, messageList);
|
|
359
|
+
if (!ctx || ctx.readOnly) return messageList;
|
|
360
|
+
return applyResult(await client.runProcessors(ctx.threadId, {
|
|
361
|
+
phase: "output",
|
|
362
|
+
resourceId: ctx.resourceId,
|
|
363
|
+
messageList: messageList.serialize(),
|
|
364
|
+
finishReason: result?.finishReason
|
|
365
|
+
}), {
|
|
366
|
+
messageList,
|
|
367
|
+
writer,
|
|
368
|
+
abort
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
}];
|
|
372
|
+
}
|
|
373
|
+
async getThreadById({ threadId }) {
|
|
374
|
+
const thread = await this.client.getThread(threadId);
|
|
375
|
+
return thread ? threadFromApi(thread) : null;
|
|
376
|
+
}
|
|
377
|
+
async listThreads(args) {
|
|
378
|
+
const page = args.page ?? 0;
|
|
379
|
+
const perPage = args.perPage === false ? 200 : args.perPage ?? 100;
|
|
380
|
+
const threads = [];
|
|
381
|
+
for (let next = 0;; next++) {
|
|
382
|
+
const res = await this.client.listThreads({
|
|
383
|
+
resourceId: args.filter?.resourceId,
|
|
384
|
+
page: next,
|
|
385
|
+
perPage: 200
|
|
386
|
+
});
|
|
387
|
+
threads.push(...res.threads.map(threadFromApi));
|
|
388
|
+
if (!res.hasMore) break;
|
|
389
|
+
}
|
|
390
|
+
const filtered = threads.filter((thread) => Object.entries(args.filter?.metadata ?? {}).every(([key, value]) => thread.metadata?.[key] === value));
|
|
391
|
+
const field = args.orderBy?.field ?? "updatedAt";
|
|
392
|
+
const direction = args.orderBy?.direction === "ASC" ? 1 : -1;
|
|
393
|
+
filtered.sort((a, b) => direction * (a[field].getTime() - b[field].getTime()));
|
|
394
|
+
return {
|
|
395
|
+
threads: args.perPage === false ? filtered : filtered.slice(page * perPage, (page + 1) * perPage),
|
|
396
|
+
hasMore: args.perPage === false ? false : (page + 1) * perPage < filtered.length,
|
|
397
|
+
page,
|
|
398
|
+
perPage: args.perPage === false ? false : perPage,
|
|
399
|
+
total: filtered.length
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
async saveThread({ thread }) {
|
|
403
|
+
return threadFromApi(await this.client.getThread(thread.id) ? await this.client.updateThread(thread.id, {
|
|
404
|
+
title: thread.title,
|
|
405
|
+
metadata: thread.metadata
|
|
406
|
+
}) : await this.client.createThread({
|
|
407
|
+
id: thread.id,
|
|
408
|
+
resourceId: thread.resourceId,
|
|
409
|
+
title: thread.title,
|
|
410
|
+
metadata: thread.metadata
|
|
411
|
+
}));
|
|
412
|
+
}
|
|
413
|
+
async updateThread({ id, title, metadata }) {
|
|
414
|
+
return threadFromApi(await this.client.updateThread(id, {
|
|
415
|
+
title,
|
|
416
|
+
metadata
|
|
417
|
+
}));
|
|
418
|
+
}
|
|
419
|
+
async deleteThread(threadId) {
|
|
420
|
+
await this.client.deleteThread(threadId);
|
|
421
|
+
}
|
|
422
|
+
async saveMessages(args) {
|
|
423
|
+
const byThread = /* @__PURE__ */ new Map();
|
|
424
|
+
for (const message of args.messages) {
|
|
425
|
+
if (!message.threadId) continue;
|
|
426
|
+
byThread.set(message.threadId, [...byThread.get(message.threadId) ?? [], message]);
|
|
427
|
+
}
|
|
428
|
+
for (const [threadId, messages] of byThread) {
|
|
429
|
+
const apiMessages = toApiMessages(messages);
|
|
430
|
+
if (!apiMessages.length) continue;
|
|
431
|
+
const resourceId = messages[0].resourceId ?? threadId;
|
|
432
|
+
await this.client.saveMessages(threadId, {
|
|
433
|
+
resourceId,
|
|
434
|
+
messages: apiMessages
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
return { messages: args.messages };
|
|
438
|
+
}
|
|
439
|
+
async recall(args) {
|
|
440
|
+
const threadIds = Array.isArray(args.threadId) ? args.threadId : [args.threadId];
|
|
441
|
+
if (!threadIds.length || threadIds.some((id) => !id)) throw new Error("PlatformMemory.recall requires a threadId");
|
|
442
|
+
if (Object.keys(args.filter?.metadata ?? {}).length || args.include?.length) throw new Error("PlatformMemory.recall does not support metadata filters or include windows");
|
|
443
|
+
const page = args.page ?? 0;
|
|
444
|
+
const perPage = args.perPage === false ? 200 : args.perPage ?? 40;
|
|
445
|
+
const messages = [];
|
|
446
|
+
for (const threadId of threadIds) {
|
|
447
|
+
const thread = await this.client.getThread(threadId);
|
|
448
|
+
if (!thread || args.resourceId && thread.resourceId !== args.resourceId) continue;
|
|
449
|
+
const resourceId = thread.resourceId;
|
|
450
|
+
for (let next = 0;; next++) {
|
|
451
|
+
const res = await this.client.listMessages(threadId, {
|
|
452
|
+
page: next,
|
|
453
|
+
perPage: 200
|
|
454
|
+
});
|
|
455
|
+
messages.push(...res.messages.map((message) => messageFromApi(message, threadId, resourceId)));
|
|
456
|
+
if (!res.hasMore) break;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
const { start, end, startExclusive, endExclusive } = args.filter?.dateRange ?? {};
|
|
460
|
+
const filtered = messages.filter((message) => {
|
|
461
|
+
const timestamp = message.createdAt.getTime();
|
|
462
|
+
return (!start || (startExclusive ? timestamp > start.getTime() : timestamp >= start.getTime())) && (!end || (endExclusive ? timestamp < end.getTime() : timestamp <= end.getTime()));
|
|
463
|
+
});
|
|
464
|
+
const direction = args.orderBy?.direction === "DESC" ? -1 : 1;
|
|
465
|
+
filtered.sort((a, b) => direction * (a.createdAt.getTime() - b.createdAt.getTime()));
|
|
466
|
+
return {
|
|
467
|
+
messages: args.perPage === false ? filtered : filtered.slice(page * perPage, (page + 1) * perPage),
|
|
468
|
+
total: filtered.length,
|
|
469
|
+
page,
|
|
470
|
+
perPage: args.perPage === false ? false : perPage,
|
|
471
|
+
hasMore: args.perPage === false ? false : (page + 1) * perPage < filtered.length
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
assertResourceScopedWorkingMemory(config) {
|
|
475
|
+
if (this.getMergedThreadConfig(config ?? {}).workingMemory?.scope === "thread") throw new Error("PlatformMemory does not support thread-scoped working memory");
|
|
476
|
+
}
|
|
477
|
+
async getWorkingMemory({ threadId, resourceId, memoryConfig }) {
|
|
478
|
+
this.assertResourceScopedWorkingMemory(memoryConfig);
|
|
479
|
+
return this.client.getWorkingMemory(resourceId ?? threadId);
|
|
480
|
+
}
|
|
481
|
+
async getWorkingMemoryTemplate() {
|
|
482
|
+
return null;
|
|
483
|
+
}
|
|
484
|
+
async updateWorkingMemory({ threadId, resourceId, workingMemory, memoryConfig }) {
|
|
485
|
+
this.assertResourceScopedWorkingMemory(memoryConfig);
|
|
486
|
+
await this.client.updateWorkingMemory(resourceId ?? threadId, workingMemory);
|
|
487
|
+
}
|
|
488
|
+
async __experimental_updateWorkingMemoryVNext(args) {
|
|
489
|
+
await this.updateWorkingMemory(args);
|
|
490
|
+
return {
|
|
491
|
+
success: true,
|
|
492
|
+
reason: "replaced"
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
async deleteMessages() {
|
|
496
|
+
throw new Error("PlatformMemory does not support deleting individual messages yet");
|
|
497
|
+
}
|
|
498
|
+
async cloneThread(_args) {
|
|
499
|
+
throw new Error("PlatformMemory does not support cloning threads yet");
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
// src/browser/index.ts
|
|
503
|
+
const DEFAULT_API_URL$1 = "https://platform.mastra.ai";
|
|
504
|
+
function trimTrailingSlashes(url) {
|
|
505
|
+
let end = url.length;
|
|
506
|
+
while (end > 0 && url[end - 1] === "/") end--;
|
|
507
|
+
return url.slice(0, end);
|
|
508
|
+
}
|
|
509
|
+
/** A Stagehand browser connected to a Platform-provisioned Browserbase session. */
|
|
510
|
+
var PlatformBrowser = class extends _mastra_stagehand.StagehandBrowser {
|
|
511
|
+
constructor(options = {}) {
|
|
512
|
+
const { cdpUrl, accessToken = process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY, projectId = process.env.MASTRA_PROJECT_ID, apiUrl = process.env.MASTRA_BROWSER_API_URL ?? DEFAULT_API_URL$1, fetch: fetchImpl = fetch, ...stagehandOptions } = options;
|
|
513
|
+
if (!cdpUrl && !accessToken) throw new Error("PlatformBrowser: accessToken is required");
|
|
514
|
+
if (!cdpUrl && !projectId) throw new Error("PlatformBrowser: projectId is required");
|
|
515
|
+
super({
|
|
516
|
+
...stagehandOptions,
|
|
517
|
+
scope: "shared",
|
|
518
|
+
cdpUrl: cdpUrl || (async () => {
|
|
519
|
+
const response = await fetchImpl(`${trimTrailingSlashes(apiUrl)}/v1/browsers/sessions`, {
|
|
520
|
+
method: "POST",
|
|
521
|
+
headers: {
|
|
522
|
+
authorization: `Bearer ${accessToken}`,
|
|
523
|
+
"content-type": "application/json"
|
|
524
|
+
},
|
|
525
|
+
body: JSON.stringify({ projectId }),
|
|
526
|
+
signal: AbortSignal.timeout(3e4)
|
|
527
|
+
});
|
|
528
|
+
if (!response.ok) throw new Error(`PlatformBrowser: browser provisioning failed (${response.status})`);
|
|
529
|
+
const result = await response.json();
|
|
530
|
+
if (!result || typeof result !== "object" || !("connectUrl" in result) || typeof result.connectUrl !== "string") throw new Error("PlatformBrowser: browser provisioning returned no connectUrl");
|
|
531
|
+
return result.connectUrl;
|
|
532
|
+
})
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
// src/knowledge/index.ts
|
|
537
|
+
const operations = [
|
|
538
|
+
"materializeScope",
|
|
539
|
+
"getScopesByAddress",
|
|
540
|
+
"listScopeDeclarations",
|
|
541
|
+
"listChildScopes",
|
|
542
|
+
"countChildScopes",
|
|
543
|
+
"getPage",
|
|
544
|
+
"getPages",
|
|
545
|
+
"getPageByPath",
|
|
546
|
+
"findPagesByName",
|
|
547
|
+
"listChildPages",
|
|
548
|
+
"countChildPages",
|
|
549
|
+
"listPages",
|
|
550
|
+
"createPage",
|
|
551
|
+
"updatePage",
|
|
552
|
+
"movePage",
|
|
553
|
+
"mergePages",
|
|
554
|
+
"deletePage",
|
|
555
|
+
"getNote",
|
|
556
|
+
"countNotes",
|
|
557
|
+
"listNotes",
|
|
558
|
+
"listNotesMentioning",
|
|
559
|
+
"addNote",
|
|
560
|
+
"restampNote",
|
|
561
|
+
"removeNote",
|
|
562
|
+
"restoreNote",
|
|
563
|
+
"searchPages",
|
|
564
|
+
"listPageActivity",
|
|
565
|
+
"addPinAudience",
|
|
566
|
+
"removePinAudience",
|
|
567
|
+
"listPins",
|
|
568
|
+
"countPageLinks",
|
|
569
|
+
"listPageLinks",
|
|
570
|
+
"replacePageBodyLinks",
|
|
571
|
+
"listPageBodyLinkSources"
|
|
572
|
+
];
|
|
573
|
+
function encode(value) {
|
|
574
|
+
return JSON.stringify(value, function(key, item) {
|
|
575
|
+
const original = key ? this[key] : item;
|
|
576
|
+
return original instanceof Date ? { __knowledgeDate: original.toISOString() } : item;
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
function decode(text) {
|
|
580
|
+
return JSON.parse(text, (_key, value) => {
|
|
581
|
+
if (value && typeof value === "object" && "__knowledgeDate" in value) return new Date(value.__knowledgeDate);
|
|
582
|
+
return value;
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
var RemoteKnowledgeStorage = class extends _mastra_core_storage.KnowledgeStorage {
|
|
586
|
+
endpoint;
|
|
587
|
+
token;
|
|
588
|
+
constructor(endpoint, token) {
|
|
589
|
+
super({ storageIsolationKey: endpoint });
|
|
590
|
+
this.endpoint = endpoint;
|
|
591
|
+
this.token = token;
|
|
592
|
+
return new Proxy(this, { get(target, key) {
|
|
593
|
+
if (typeof key === "string" && operations.includes(key)) return (input) => target.request(key, input);
|
|
594
|
+
const value = Reflect.get(target, key, target);
|
|
595
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
596
|
+
} });
|
|
597
|
+
}
|
|
598
|
+
async request(operation, input) {
|
|
599
|
+
const response = await fetch(`${this.endpoint}/operations/${operation}`, {
|
|
600
|
+
method: "POST",
|
|
601
|
+
headers: {
|
|
602
|
+
authorization: `Bearer ${this.token}`,
|
|
603
|
+
"content-type": "application/json",
|
|
604
|
+
"x-mastra-knowledge-store-declarations": "merged"
|
|
605
|
+
},
|
|
606
|
+
body: encode({ input }),
|
|
607
|
+
signal: AbortSignal.timeout(3e4)
|
|
608
|
+
});
|
|
609
|
+
const text = await response.text();
|
|
610
|
+
if (!response.ok) {
|
|
611
|
+
let body = {};
|
|
612
|
+
try {
|
|
613
|
+
const parsed = JSON.parse(text);
|
|
614
|
+
if (parsed && typeof parsed === "object") body = parsed;
|
|
615
|
+
} catch {}
|
|
616
|
+
const message = body.detail || body.error?.message || body.title || (text ? `Knowledge request failed (${response.status}): ${text}` : `Knowledge request failed (${response.status})`);
|
|
617
|
+
const name = body.name ?? body.error?.name;
|
|
618
|
+
if (name === "KnowledgeNotFoundError") {
|
|
619
|
+
const error = new _mastra_core_storage.KnowledgeNotFoundError("record", operation);
|
|
620
|
+
error.message = message;
|
|
621
|
+
throw error;
|
|
622
|
+
}
|
|
623
|
+
if (name === "KnowledgeConflictError") {
|
|
624
|
+
const error = new _mastra_core_storage.KnowledgeConflictError(operation);
|
|
625
|
+
error.message = message;
|
|
626
|
+
throw error;
|
|
627
|
+
}
|
|
628
|
+
if (name === "KnowledgePageKeyConflictError") {
|
|
629
|
+
const error = new _mastra_core_storage.KnowledgePageKeyConflictError("", "");
|
|
630
|
+
error.message = message;
|
|
631
|
+
throw error;
|
|
632
|
+
}
|
|
633
|
+
if (name === "KnowledgePageHasChildrenError") {
|
|
634
|
+
const error = new _mastra_core_storage.KnowledgePageHasChildrenError("");
|
|
635
|
+
error.message = message;
|
|
636
|
+
throw error;
|
|
637
|
+
}
|
|
638
|
+
throw Object.assign(new Error(message), { status: response.status });
|
|
639
|
+
}
|
|
640
|
+
return decode(text).result;
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* The scope declarations the instance supplies, such as the ones its importers write to, with their
|
|
644
|
+
* access rules. A service that doesn't have the operation yet answers 404 "Knowledge operation not
|
|
645
|
+
* found" and supplies none. Any other failure, including another 404 (a missing instance, a wrong
|
|
646
|
+
* URL), and anything but a declaration record is a broken response, not "none".
|
|
647
|
+
*/
|
|
648
|
+
async getScopeDeclarations() {
|
|
649
|
+
let result;
|
|
650
|
+
try {
|
|
651
|
+
result = await this.request("getScopeDeclarations");
|
|
652
|
+
} catch (error) {
|
|
653
|
+
if (error.status === 404 && error.message === "Knowledge operation not found") return {};
|
|
654
|
+
throw error;
|
|
655
|
+
}
|
|
656
|
+
if (!result || typeof result !== "object" || Array.isArray(result)) throw new Error("Knowledge service answered getScopeDeclarations without a declaration record");
|
|
657
|
+
return result;
|
|
658
|
+
}
|
|
659
|
+
getCapabilities() {
|
|
660
|
+
return {
|
|
661
|
+
contractVersion: 4,
|
|
662
|
+
schemaVersion: 4,
|
|
663
|
+
supportsSchemaInspection: false,
|
|
664
|
+
supportsExplicitReset: false,
|
|
665
|
+
supportsPinKinds: true
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
async dangerouslyClearAll() {
|
|
669
|
+
throw new Error("Hosted Knowledge cannot be cleared from the client");
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
const DEFAULT_API_URL = "https://knowledge-api.mastra.ai";
|
|
673
|
+
var PlatformKnowledge = class extends _mastra_core_knowledge.Knowledge {
|
|
674
|
+
constructor(options = {}) {
|
|
675
|
+
const token = options.accessToken ?? process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY;
|
|
676
|
+
const instanceId = options.instanceId ?? process.env.MASTRA_KNOWLEDGE_INSTANCE_ID;
|
|
677
|
+
const apiUrl = options.apiUrl ?? (process.env.MASTRA_KNOWLEDGE_API_URL?.trim() || void 0) ?? DEFAULT_API_URL;
|
|
678
|
+
if (!token || !instanceId) throw new Error("PlatformKnowledge requires a Platform access token and Knowledge instance ID");
|
|
679
|
+
const { accessToken: _accessToken, projectId: _projectId, instanceId: _instanceId, apiUrl: _apiUrl, ...config } = options;
|
|
680
|
+
const endpoint = `${apiUrl.replace(/\/$/, "")}/v1/knowledge/${encodeURIComponent(instanceId)}`;
|
|
681
|
+
const storage = new _mastra_core_storage.MastraCompositeStore({
|
|
682
|
+
id: `platform-knowledge-${instanceId}`,
|
|
683
|
+
domains: { knowledge: new RemoteKnowledgeStorage(endpoint, token) }
|
|
684
|
+
});
|
|
685
|
+
super({
|
|
686
|
+
...config,
|
|
687
|
+
tools: config.tools ?? { read: true },
|
|
688
|
+
scopes: {},
|
|
689
|
+
storage
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
exports.PlatformBrowser = PlatformBrowser;
|
|
694
|
+
exports.PlatformKnowledge = PlatformKnowledge;
|
|
695
|
+
exports.PlatformMemory = PlatformMemory;
|
|
696
|
+
exports.PlatformMemoryApiError = PlatformMemoryApiError;
|
|
697
|
+
exports.PlatformMemoryClient = PlatformMemoryClient;
|
|
698
|
+
exports.resolvePlatformMemoryOptions = resolvePlatformMemoryOptions;
|
|
699
|
+
var _mastra_platform_workspace = require("@mastra/platform-workspace");
|
|
700
|
+
Object.keys(_mastra_platform_workspace).forEach(function(k) {
|
|
701
|
+
if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
|
702
|
+
enumerable: true,
|
|
703
|
+
get: function() {
|
|
704
|
+
return _mastra_platform_workspace[k];
|
|
705
|
+
}
|
|
706
|
+
});
|
|
707
|
+
});
|
|
708
|
+
|
|
709
|
+
//# sourceMappingURL=index.cjs.map
|