@mastra/platform 0.0.0-feat-platform-unified-20261104220759
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 +53 -0
- package/dist/index.cjs +595 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +582 -0
- package/dist/index.js.map +1 -0
- package/dist/knowledge/index.d.ts +21 -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 +85 -0
- package/dist/memory/platform-memory.d.ts.map +1 -0
- package/package.json +68 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Portions of this software are licensed as follows:
|
|
2
|
+
|
|
3
|
+
- All content that resides under any directory named `ee/` within this
|
|
4
|
+
repository, including but not limited to:
|
|
5
|
+
- `@mastra/core/auth/ee`
|
|
6
|
+
- `@mastra/core/agent-builder/ee`
|
|
7
|
+
- `@mastra/editor/ee`
|
|
8
|
+
|
|
9
|
+
is licensed under the license defined in [`ee/LICENSE`](https://github.com/mastra-ai/mastra/blob/main/ee/LICENSE).
|
|
10
|
+
|
|
11
|
+
- All third-party components incorporated into the Mastra Software are
|
|
12
|
+
licensed under the original license provided by the owner of the
|
|
13
|
+
applicable component.
|
|
14
|
+
|
|
15
|
+
- Content outside of the above-mentioned directories or restrictions is
|
|
16
|
+
available under the "Apache License 2.0" as defined below.
|
|
17
|
+
|
|
18
|
+
# Apache License 2.0
|
|
19
|
+
|
|
20
|
+
Copyright (c) 2025 Kepler Software, Inc.
|
|
21
|
+
|
|
22
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
23
|
+
you may not use this file except in compliance with the License.
|
|
24
|
+
You may obtain a copy of the License at
|
|
25
|
+
|
|
26
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
27
|
+
|
|
28
|
+
Unless required by applicable law or agreed to in writing, software
|
|
29
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
30
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
31
|
+
See the License for the specific language governing permissions and
|
|
32
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# @mastra/platform (experimental)
|
|
2
|
+
|
|
3
|
+
Hosted Mastra Platform clients for Memory and Knowledge, with Sandbox and Filesystem re-exported from the `@mastra/platform-workspace` dependency.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @mastra/platform
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
Set `MASTRA_PLATFORM_ACCESS_TOKEN` (or `MASTRA_PLATFORM_SECRET_KEY`). `PlatformMemory` also needs `MASTRA_MEMORY_INSTANCE_ID` and `PlatformKnowledge` needs `MASTRA_KNOWLEDGE_INSTANCE_ID`; the example below uses both, so set both IDs. Obtain your instance IDs and credentials from Mastra Platform.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { Agent } from '@mastra/core/agent';
|
|
17
|
+
import { PlatformMemory, PlatformKnowledge } from '@mastra/platform';
|
|
18
|
+
|
|
19
|
+
const model = 'openai/gpt-4o-mini';
|
|
20
|
+
const agent = new Agent({
|
|
21
|
+
name: 'assistant',
|
|
22
|
+
model,
|
|
23
|
+
memory: new PlatformMemory(),
|
|
24
|
+
});
|
|
25
|
+
const knowledge = new PlatformKnowledge();
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`PlatformSandbox` and `PlatformFilesystem` are also available from `@mastra/platform`.
|
|
29
|
+
|
|
30
|
+
### Knowledge transport contract
|
|
31
|
+
|
|
32
|
+
- `POST {apiUrl}/v1/knowledge/{instanceId}/operations/{operation}` with `Authorization: Bearer {accessToken}` and JSON body `{ input }`; returns `{ result }`.
|
|
33
|
+
- `instanceId` and `apiUrl` come from options or `MASTRA_KNOWLEDGE_INSTANCE_ID` and `MASTRA_KNOWLEDGE_API_URL`; `apiUrl` defaults to `https://knowledge-api.mastra.ai`. The service derives the authorized project from the instance and credential; `projectId` is accepted for compatibility but is not sent.
|
|
34
|
+
- `renameScopeDeclaration` is not forwarded and rejects with `KnowledgeUnsupportedCapabilityError`: its `check` callback cannot be sent to the hosted store.
|
|
35
|
+
- Credential priority: option `accessToken`, `MASTRA_PLATFORM_ACCESS_TOKEN`, `MASTRA_PLATFORM_SECRET_KEY`.
|
|
36
|
+
- The server checks that the instance belongs to the credential's organization and, for project-bound tokens, its project; it allowlists page-store operations and never accepts a connection string from the caller.
|
|
37
|
+
- Hosted Knowledge requires a core and PostgreSQL adapter release implementing the Knowledge pages-v4 contract; production release alignment remains pending.
|
|
38
|
+
|
|
39
|
+
## Documentation
|
|
40
|
+
|
|
41
|
+
`PlatformKnowledge` extends core `Knowledge` and delegates schema-v4 page-store operations to the hosted service. The provider, connection string, importer, and sync scheduler belong to Platform rather than this client. For general API concepts, see [Mastra documentation](https://mastra.ai/docs).
|
|
42
|
+
|
|
43
|
+
### Verification matrix
|
|
44
|
+
|
|
45
|
+
The same scenarios must run once with core `Knowledge` on local PostgreSQL and again with `PlatformKnowledge` against Compose-backed Platform: scope materialization and discovery; nested page create/update/move/delete; search and read; notes and links; pin visibility; editor/viewer access; agent tool attachment, including denial across scopes. Connect-backed source provisioning, import, and incremental re-sync require a separate linked-source scenario; host page writes alone do not prove this integration.
|
|
46
|
+
|
|
47
|
+
## Changelog
|
|
48
|
+
|
|
49
|
+
See the [package changelog](https://github.com/mastra-ai/mastra/blob/main/packages/platform/CHANGELOG.md).
|
|
50
|
+
|
|
51
|
+
## Support
|
|
52
|
+
|
|
53
|
+
We have an [open community Discord](https://discord.gg/mastra-ai). Come and say hello and let us know if you have any questions or need any help getting things running.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,595 @@
|
|
|
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_core_knowledge = require("@mastra/core/knowledge");
|
|
6
|
+
let _mastra_core_storage = require("@mastra/core/storage");
|
|
7
|
+
// src/memory/client.ts
|
|
8
|
+
const DEFAULT_API_URL$1 = "https://memory-api.mastra.ai";
|
|
9
|
+
const REQUEST_TIMEOUT_MS = 3e4;
|
|
10
|
+
const PROCESSOR_TIMEOUT_MS = 3e5;
|
|
11
|
+
function env(name) {
|
|
12
|
+
return process.env[name]?.trim() || void 0;
|
|
13
|
+
}
|
|
14
|
+
function required(value, name) {
|
|
15
|
+
if (!value) throw new Error(`PlatformMemory: ${name} is required`);
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
function resolvePlatformMemoryOptions(options = {}) {
|
|
19
|
+
return {
|
|
20
|
+
accessToken: required(options.accessToken ?? env("MASTRA_PLATFORM_ACCESS_TOKEN") ?? env("MASTRA_PLATFORM_SECRET_KEY"), "accessToken"),
|
|
21
|
+
instanceId: required(options.instanceId ?? env("MASTRA_MEMORY_INSTANCE_ID"), "instanceId"),
|
|
22
|
+
projectId: options.projectId ?? env("MASTRA_PROJECT_ID"),
|
|
23
|
+
environmentId: options.environmentId ?? env("MASTRA_ENVIRONMENT_ID"),
|
|
24
|
+
actingUserId: options.actingUserId,
|
|
25
|
+
apiUrl: (options.apiUrl ?? env("MASTRA_MEMORY_API_URL") ?? DEFAULT_API_URL$1).replace(/\/$/, ""),
|
|
26
|
+
fetch: options.fetch ?? fetch
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
var PlatformMemoryApiError = class extends Error {
|
|
30
|
+
status;
|
|
31
|
+
body;
|
|
32
|
+
constructor(status, body) {
|
|
33
|
+
super(`Platform Memory request failed with ${status}${body ? `: ${body}` : ""}`);
|
|
34
|
+
this.status = status;
|
|
35
|
+
this.body = body;
|
|
36
|
+
this.name = "PlatformMemoryApiError";
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
/** Typed client for the Platform Memory API (`/v1/memory/:instanceId/*`). */
|
|
40
|
+
var PlatformMemoryClient = class {
|
|
41
|
+
instanceId;
|
|
42
|
+
opts;
|
|
43
|
+
constructor(options = {}) {
|
|
44
|
+
this.opts = resolvePlatformMemoryOptions(options);
|
|
45
|
+
this.instanceId = this.opts.instanceId;
|
|
46
|
+
}
|
|
47
|
+
/** MCP endpoint for this instance, for clients that speak MCP directly. */
|
|
48
|
+
get mcpUrl() {
|
|
49
|
+
return `${this.base}/mcp`;
|
|
50
|
+
}
|
|
51
|
+
listThreads(query = {}) {
|
|
52
|
+
return this.request("GET", "/threads", { query });
|
|
53
|
+
}
|
|
54
|
+
createThread(body) {
|
|
55
|
+
return this.request("POST", "/threads", { body });
|
|
56
|
+
}
|
|
57
|
+
/** Returns null when the thread does not exist. */
|
|
58
|
+
async getThread(threadId) {
|
|
59
|
+
try {
|
|
60
|
+
return await this.request("GET", `/threads/${encodeURIComponent(threadId)}`);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (error instanceof PlatformMemoryApiError && error.status === 404) return null;
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
updateThread(threadId, body) {
|
|
67
|
+
return this.request("PATCH", `/threads/${encodeURIComponent(threadId)}`, { body });
|
|
68
|
+
}
|
|
69
|
+
async deleteThread(threadId) {
|
|
70
|
+
await this.request("DELETE", `/threads/${encodeURIComponent(threadId)}`);
|
|
71
|
+
}
|
|
72
|
+
listMessages(threadId, query = {}) {
|
|
73
|
+
return this.request("GET", `/threads/${encodeURIComponent(threadId)}/messages`, { query });
|
|
74
|
+
}
|
|
75
|
+
/** Saves messages and schedules observation in the background. Creates the thread if needed. */
|
|
76
|
+
saveMessages(threadId, body) {
|
|
77
|
+
return this.request("POST", `/threads/${encodeURIComponent(threadId)}/messages`, { body });
|
|
78
|
+
}
|
|
79
|
+
getContext(threadId, resourceId, opts = {}) {
|
|
80
|
+
return this.request("GET", `/threads/${encodeURIComponent(threadId)}/context`, { query: {
|
|
81
|
+
resourceId,
|
|
82
|
+
...opts.workingMemory ? { workingMemory: opts.workingMemory } : {}
|
|
83
|
+
} });
|
|
84
|
+
}
|
|
85
|
+
async getWorkingMemory(resourceId) {
|
|
86
|
+
return (await this.request("GET", "/working-memory", { query: { resourceId } })).workingMemory;
|
|
87
|
+
}
|
|
88
|
+
async updateWorkingMemory(resourceId, workingMemory) {
|
|
89
|
+
await this.request("PUT", "/working-memory", { body: {
|
|
90
|
+
resourceId,
|
|
91
|
+
workingMemory
|
|
92
|
+
} });
|
|
93
|
+
}
|
|
94
|
+
/** Omit resourceId to search the instance's most recently active threads. */
|
|
95
|
+
async search(body) {
|
|
96
|
+
return (await this.request("POST", "/search", { body })).matches;
|
|
97
|
+
}
|
|
98
|
+
/** Current observational-memory record for the thread, or null before the first observation. */
|
|
99
|
+
async getObservations(threadId) {
|
|
100
|
+
return (await this.request("GET", `/threads/${encodeURIComponent(threadId)}/observations`)).record;
|
|
101
|
+
}
|
|
102
|
+
/** Runs the instance's memory processors for one agent phase on a serialized message list. */
|
|
103
|
+
runProcessors(threadId, body, signal) {
|
|
104
|
+
return this.request("POST", `/threads/${encodeURIComponent(threadId)}/processors`, {
|
|
105
|
+
body,
|
|
106
|
+
signal,
|
|
107
|
+
timeoutMs: PROCESSOR_TIMEOUT_MS
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
async listObservationRuns(query = {}) {
|
|
111
|
+
return (await this.request("GET", "/runs", { query })).runs;
|
|
112
|
+
}
|
|
113
|
+
/** Effective observation thresholds for the thread and which ones it overrides. */
|
|
114
|
+
getThreadConfig(threadId) {
|
|
115
|
+
return this.request("GET", `/threads/${encodeURIComponent(threadId)}/config`);
|
|
116
|
+
}
|
|
117
|
+
/** Overrides thresholds for one thread. Pass `null` to fall back to the instance value. */
|
|
118
|
+
updateThreadConfig(threadId, config) {
|
|
119
|
+
return this.request("PATCH", `/threads/${encodeURIComponent(threadId)}/config`, { body: config });
|
|
120
|
+
}
|
|
121
|
+
/** Copies a thread, its messages, and its observations. */
|
|
122
|
+
cloneThread(threadId, body = {}) {
|
|
123
|
+
return this.request("POST", `/threads/${encodeURIComponent(threadId)}/clone`, { body });
|
|
124
|
+
}
|
|
125
|
+
/** Deletes messages from a thread. Ids that belong to other threads are ignored. */
|
|
126
|
+
async deleteMessages(threadId, messageIds) {
|
|
127
|
+
return (await this.request("POST", `/threads/${encodeURIComponent(threadId)}/messages/delete`, { body: { messageIds } })).deleted;
|
|
128
|
+
}
|
|
129
|
+
/** Everything stored for one resource (user): working memory and threads. */
|
|
130
|
+
getResource(resourceId, query = {}) {
|
|
131
|
+
return this.request("GET", `/resources/${encodeURIComponent(resourceId)}`, { query });
|
|
132
|
+
}
|
|
133
|
+
/** Resources (users) in the instance, most recently active first. */
|
|
134
|
+
listResources(query = {}) {
|
|
135
|
+
return this.request("GET", "/resources", { query });
|
|
136
|
+
}
|
|
137
|
+
/** Deletes every thread, message, observation and the working memory for a resource. */
|
|
138
|
+
async deleteResource(resourceId) {
|
|
139
|
+
return (await this.request("DELETE", `/resources/${encodeURIComponent(resourceId)}`)).deletedThreads;
|
|
140
|
+
}
|
|
141
|
+
get base() {
|
|
142
|
+
return `${this.opts.apiUrl}/v1/memory/${encodeURIComponent(this.opts.instanceId)}`;
|
|
143
|
+
}
|
|
144
|
+
async request(method, path, init = {}) {
|
|
145
|
+
const url = new URL(this.base + path);
|
|
146
|
+
for (const [key, value] of Object.entries(init.query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
|
|
147
|
+
const headers = { authorization: `Bearer ${this.opts.accessToken}` };
|
|
148
|
+
if (this.opts.actingUserId) headers["x-acting-user-id"] = this.opts.actingUserId;
|
|
149
|
+
if (this.opts.projectId) headers["x-mastra-project-id"] = this.opts.projectId;
|
|
150
|
+
if (this.opts.environmentId) headers["x-mastra-environment-id"] = this.opts.environmentId;
|
|
151
|
+
if (init.body !== void 0) headers["content-type"] = "application/json";
|
|
152
|
+
const deadline = AbortSignal.timeout(init.timeoutMs ?? REQUEST_TIMEOUT_MS);
|
|
153
|
+
const res = await this.opts.fetch(url, {
|
|
154
|
+
method,
|
|
155
|
+
headers,
|
|
156
|
+
body: init.body === void 0 ? void 0 : JSON.stringify(init.body),
|
|
157
|
+
signal: init.signal ? AbortSignal.any([init.signal, deadline]) : deadline
|
|
158
|
+
});
|
|
159
|
+
if (!res.ok) throw new PlatformMemoryApiError(res.status, await res.text().catch(() => ""));
|
|
160
|
+
if (res.status === 204) return void 0;
|
|
161
|
+
return await res.json();
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
// src/memory/platform-memory.ts
|
|
165
|
+
function threadFromApi(thread) {
|
|
166
|
+
return {
|
|
167
|
+
id: thread.id,
|
|
168
|
+
resourceId: thread.resourceId,
|
|
169
|
+
title: thread.title ?? void 0,
|
|
170
|
+
metadata: thread.metadata ?? void 0,
|
|
171
|
+
createdAt: new Date(thread.createdAt),
|
|
172
|
+
updatedAt: new Date(thread.updatedAt)
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
function messageFromApi(message, threadId, resourceId) {
|
|
176
|
+
return {
|
|
177
|
+
id: message.id,
|
|
178
|
+
role: message.role === "assistant" ? "assistant" : "user",
|
|
179
|
+
createdAt: new Date(message.createdAt),
|
|
180
|
+
threadId,
|
|
181
|
+
resourceId,
|
|
182
|
+
content: {
|
|
183
|
+
format: 2,
|
|
184
|
+
parts: message.parts?.length ? message.parts : [{
|
|
185
|
+
type: "text",
|
|
186
|
+
text: message.content
|
|
187
|
+
}]
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
function textOf(message) {
|
|
192
|
+
return (message.content.parts ?? []).filter((part) => part.type === "text").map((part) => part.text).join("\n") || message.content.content || "";
|
|
193
|
+
}
|
|
194
|
+
/** User/assistant messages with all their parts (tool calls, reasoning, files). System messages are skipped. */
|
|
195
|
+
function toApiMessages(messages) {
|
|
196
|
+
return messages.flatMap((message) => {
|
|
197
|
+
if (message.role !== "user" && message.role !== "assistant") return [];
|
|
198
|
+
const parts = message.content.parts ?? [];
|
|
199
|
+
const createdAt = new Date(message.createdAt).toISOString();
|
|
200
|
+
const content = textOf(message) || void 0;
|
|
201
|
+
if (!parts.length && !content) return [];
|
|
202
|
+
return [{
|
|
203
|
+
id: message.id,
|
|
204
|
+
role: message.role,
|
|
205
|
+
content,
|
|
206
|
+
parts: parts.length ? parts : void 0,
|
|
207
|
+
createdAt
|
|
208
|
+
}];
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
function memoryContext(requestContext, messageList) {
|
|
212
|
+
const ctx = (0, _mastra_core_memory.parseMemoryRequestContext)(requestContext);
|
|
213
|
+
if (ctx?.thread?.id) return {
|
|
214
|
+
threadId: ctx.thread.id,
|
|
215
|
+
resourceId: ctx.resourceId ?? ctx.thread.id,
|
|
216
|
+
readOnly: ctx.memoryConfig?.readOnly
|
|
217
|
+
};
|
|
218
|
+
const info = messageList.serialize().memoryInfo;
|
|
219
|
+
if (info?.threadId) return {
|
|
220
|
+
threadId: info.threadId,
|
|
221
|
+
resourceId: info.resourceId ?? info.threadId,
|
|
222
|
+
readOnly: false
|
|
223
|
+
};
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
async function applyResult(result, agent) {
|
|
227
|
+
for (const chunk of result.chunks) await agent.writer?.custom(chunk);
|
|
228
|
+
for (let i = 0; i < result.rotations; i++) agent.rotateResponseMessageId?.();
|
|
229
|
+
if (result.aborted !== null || !result.messageList) return agent.abort(result.aborted ?? void 0);
|
|
230
|
+
return agent.messageList.deserialize(result.messageList);
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Mastra memory backed by a hosted Platform Memory instance.
|
|
234
|
+
*
|
|
235
|
+
* Observation and reflection run on the Platform: on each input step and on the final output this
|
|
236
|
+
* class sends the serialized message list to the instance's memory processors and applies the
|
|
237
|
+
* result. Messages are stored with all their parts (text, tool calls, reasoning, files).
|
|
238
|
+
*/
|
|
239
|
+
var PlatformMemory = class extends _mastra_core_memory.MastraMemory {
|
|
240
|
+
client;
|
|
241
|
+
workingMemoryMode;
|
|
242
|
+
constructor(options = {}) {
|
|
243
|
+
super({
|
|
244
|
+
id: options.id ?? "platform-memory",
|
|
245
|
+
name: "PlatformMemory"
|
|
246
|
+
});
|
|
247
|
+
this.client = options.client ?? new PlatformMemoryClient(options);
|
|
248
|
+
this.workingMemoryMode = options.workingMemory ?? "readonly";
|
|
249
|
+
}
|
|
250
|
+
listTools(config) {
|
|
251
|
+
if (this.workingMemoryMode !== "tool" || config?.readOnly) return {};
|
|
252
|
+
this.assertResourceScopedWorkingMemory(config);
|
|
253
|
+
const client = this.client;
|
|
254
|
+
return { updateWorkingMemory: (0, _mastra_core_tools.createTool)({
|
|
255
|
+
id: "update-working-memory",
|
|
256
|
+
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.",
|
|
257
|
+
inputSchema: zod.z.object({ memory: zod.z.string().describe("The Markdown formatted working memory content to store.") }),
|
|
258
|
+
execute: async ({ memory }, context) => {
|
|
259
|
+
const resourceId = context?.agent?.resourceId ?? context?.agent?.threadId;
|
|
260
|
+
if (!resourceId) throw new Error("updateWorkingMemory needs a thread or resource");
|
|
261
|
+
await client.updateWorkingMemory(resourceId, memory);
|
|
262
|
+
return { success: true };
|
|
263
|
+
}
|
|
264
|
+
}) };
|
|
265
|
+
}
|
|
266
|
+
async getInputProcessors() {
|
|
267
|
+
const client = this.client;
|
|
268
|
+
return [{
|
|
269
|
+
id: "platform-memory",
|
|
270
|
+
name: "Platform Memory",
|
|
271
|
+
async processInputStep({ messageList, requestContext, stepNumber, model, writer, abort, abortSignal, rotateResponseMessageId }) {
|
|
272
|
+
const ctx = memoryContext(requestContext, messageList);
|
|
273
|
+
if (!ctx || ctx.readOnly) return messageList;
|
|
274
|
+
return applyResult(await client.runProcessors(ctx.threadId, {
|
|
275
|
+
phase: "inputStep",
|
|
276
|
+
resourceId: ctx.resourceId,
|
|
277
|
+
stepNumber,
|
|
278
|
+
messageList: messageList.serialize(),
|
|
279
|
+
model: model ? {
|
|
280
|
+
provider: model.provider,
|
|
281
|
+
modelId: model.modelId
|
|
282
|
+
} : void 0
|
|
283
|
+
}, abortSignal), {
|
|
284
|
+
messageList,
|
|
285
|
+
writer,
|
|
286
|
+
abort,
|
|
287
|
+
rotateResponseMessageId
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
}];
|
|
291
|
+
}
|
|
292
|
+
async getOutputProcessors() {
|
|
293
|
+
const client = this.client;
|
|
294
|
+
return [{
|
|
295
|
+
id: "platform-memory",
|
|
296
|
+
name: "Platform Memory",
|
|
297
|
+
async processOutputResult({ messageList, requestContext, result, writer, abort }) {
|
|
298
|
+
const ctx = memoryContext(requestContext, messageList);
|
|
299
|
+
if (!ctx || ctx.readOnly) return messageList;
|
|
300
|
+
return applyResult(await client.runProcessors(ctx.threadId, {
|
|
301
|
+
phase: "output",
|
|
302
|
+
resourceId: ctx.resourceId,
|
|
303
|
+
messageList: messageList.serialize(),
|
|
304
|
+
finishReason: result?.finishReason
|
|
305
|
+
}), {
|
|
306
|
+
messageList,
|
|
307
|
+
writer,
|
|
308
|
+
abort
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
}];
|
|
312
|
+
}
|
|
313
|
+
async getThreadById({ threadId }) {
|
|
314
|
+
const thread = await this.client.getThread(threadId);
|
|
315
|
+
return thread ? threadFromApi(thread) : null;
|
|
316
|
+
}
|
|
317
|
+
async listThreads(args) {
|
|
318
|
+
const page = args.page ?? 0;
|
|
319
|
+
const perPage = args.perPage === false ? 200 : args.perPage ?? 100;
|
|
320
|
+
const threads = [];
|
|
321
|
+
for (let next = 0;; next++) {
|
|
322
|
+
const res = await this.client.listThreads({
|
|
323
|
+
resourceId: args.filter?.resourceId,
|
|
324
|
+
page: next,
|
|
325
|
+
perPage: 200
|
|
326
|
+
});
|
|
327
|
+
threads.push(...res.threads.map(threadFromApi));
|
|
328
|
+
if (!res.hasMore) break;
|
|
329
|
+
}
|
|
330
|
+
const filtered = threads.filter((thread) => Object.entries(args.filter?.metadata ?? {}).every(([key, value]) => thread.metadata?.[key] === value));
|
|
331
|
+
const field = args.orderBy?.field ?? "updatedAt";
|
|
332
|
+
const direction = args.orderBy?.direction === "ASC" ? 1 : -1;
|
|
333
|
+
filtered.sort((a, b) => direction * (a[field].getTime() - b[field].getTime()));
|
|
334
|
+
return {
|
|
335
|
+
threads: args.perPage === false ? filtered : filtered.slice(page * perPage, (page + 1) * perPage),
|
|
336
|
+
hasMore: args.perPage === false ? false : (page + 1) * perPage < filtered.length,
|
|
337
|
+
page,
|
|
338
|
+
perPage: args.perPage === false ? false : perPage,
|
|
339
|
+
total: filtered.length
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
async saveThread({ thread }) {
|
|
343
|
+
return threadFromApi(await this.client.getThread(thread.id) ? await this.client.updateThread(thread.id, {
|
|
344
|
+
title: thread.title,
|
|
345
|
+
metadata: thread.metadata
|
|
346
|
+
}) : await this.client.createThread({
|
|
347
|
+
id: thread.id,
|
|
348
|
+
resourceId: thread.resourceId,
|
|
349
|
+
title: thread.title,
|
|
350
|
+
metadata: thread.metadata
|
|
351
|
+
}));
|
|
352
|
+
}
|
|
353
|
+
async updateThread({ id, title, metadata }) {
|
|
354
|
+
return threadFromApi(await this.client.updateThread(id, {
|
|
355
|
+
title,
|
|
356
|
+
metadata
|
|
357
|
+
}));
|
|
358
|
+
}
|
|
359
|
+
async deleteThread(threadId) {
|
|
360
|
+
await this.client.deleteThread(threadId);
|
|
361
|
+
}
|
|
362
|
+
async saveMessages(args) {
|
|
363
|
+
const byThread = /* @__PURE__ */ new Map();
|
|
364
|
+
for (const message of args.messages) {
|
|
365
|
+
if (!message.threadId) continue;
|
|
366
|
+
byThread.set(message.threadId, [...byThread.get(message.threadId) ?? [], message]);
|
|
367
|
+
}
|
|
368
|
+
for (const [threadId, messages] of byThread) {
|
|
369
|
+
const apiMessages = toApiMessages(messages);
|
|
370
|
+
if (!apiMessages.length) continue;
|
|
371
|
+
const resourceId = messages[0].resourceId ?? threadId;
|
|
372
|
+
await this.client.saveMessages(threadId, {
|
|
373
|
+
resourceId,
|
|
374
|
+
messages: apiMessages
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
return { messages: args.messages };
|
|
378
|
+
}
|
|
379
|
+
async recall(args) {
|
|
380
|
+
const threadIds = Array.isArray(args.threadId) ? args.threadId : [args.threadId];
|
|
381
|
+
if (!threadIds.length || threadIds.some((id) => !id)) throw new Error("PlatformMemory.recall requires a threadId");
|
|
382
|
+
if (Object.keys(args.filter?.metadata ?? {}).length || args.include?.length) throw new Error("PlatformMemory.recall does not support metadata filters or include windows");
|
|
383
|
+
const page = args.page ?? 0;
|
|
384
|
+
const perPage = args.perPage === false ? 200 : args.perPage ?? 40;
|
|
385
|
+
const messages = [];
|
|
386
|
+
for (const threadId of threadIds) {
|
|
387
|
+
const thread = await this.client.getThread(threadId);
|
|
388
|
+
if (!thread || args.resourceId && thread.resourceId !== args.resourceId) continue;
|
|
389
|
+
const resourceId = thread.resourceId;
|
|
390
|
+
for (let next = 0;; next++) {
|
|
391
|
+
const res = await this.client.listMessages(threadId, {
|
|
392
|
+
page: next,
|
|
393
|
+
perPage: 200
|
|
394
|
+
});
|
|
395
|
+
messages.push(...res.messages.map((message) => messageFromApi(message, threadId, resourceId)));
|
|
396
|
+
if (!res.hasMore) break;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
const { start, end, startExclusive, endExclusive } = args.filter?.dateRange ?? {};
|
|
400
|
+
const filtered = messages.filter((message) => {
|
|
401
|
+
const timestamp = message.createdAt.getTime();
|
|
402
|
+
return (!start || (startExclusive ? timestamp > start.getTime() : timestamp >= start.getTime())) && (!end || (endExclusive ? timestamp < end.getTime() : timestamp <= end.getTime()));
|
|
403
|
+
});
|
|
404
|
+
const direction = args.orderBy?.direction === "DESC" ? -1 : 1;
|
|
405
|
+
filtered.sort((a, b) => direction * (a.createdAt.getTime() - b.createdAt.getTime()));
|
|
406
|
+
return {
|
|
407
|
+
messages: args.perPage === false ? filtered : filtered.slice(page * perPage, (page + 1) * perPage),
|
|
408
|
+
total: filtered.length,
|
|
409
|
+
page,
|
|
410
|
+
perPage: args.perPage === false ? false : perPage,
|
|
411
|
+
hasMore: args.perPage === false ? false : (page + 1) * perPage < filtered.length
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
assertResourceScopedWorkingMemory(config) {
|
|
415
|
+
if (this.getMergedThreadConfig(config ?? {}).workingMemory?.scope === "thread") throw new Error("PlatformMemory does not support thread-scoped working memory");
|
|
416
|
+
}
|
|
417
|
+
async getWorkingMemory({ threadId, resourceId, memoryConfig }) {
|
|
418
|
+
this.assertResourceScopedWorkingMemory(memoryConfig);
|
|
419
|
+
return this.client.getWorkingMemory(resourceId ?? threadId);
|
|
420
|
+
}
|
|
421
|
+
async getWorkingMemoryTemplate() {
|
|
422
|
+
return null;
|
|
423
|
+
}
|
|
424
|
+
async updateWorkingMemory({ threadId, resourceId, workingMemory, memoryConfig }) {
|
|
425
|
+
this.assertResourceScopedWorkingMemory(memoryConfig);
|
|
426
|
+
await this.client.updateWorkingMemory(resourceId ?? threadId, workingMemory);
|
|
427
|
+
}
|
|
428
|
+
async __experimental_updateWorkingMemoryVNext(args) {
|
|
429
|
+
await this.updateWorkingMemory(args);
|
|
430
|
+
return {
|
|
431
|
+
success: true,
|
|
432
|
+
reason: "replaced"
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
async deleteMessages() {
|
|
436
|
+
throw new Error("PlatformMemory does not support deleting individual messages yet");
|
|
437
|
+
}
|
|
438
|
+
async cloneThread(_args) {
|
|
439
|
+
throw new Error("PlatformMemory does not support cloning threads yet");
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
// src/knowledge/index.ts
|
|
443
|
+
const operations = [
|
|
444
|
+
"materializeScope",
|
|
445
|
+
"getScopesByAddress",
|
|
446
|
+
"listScopeDeclarations",
|
|
447
|
+
"listChildScopes",
|
|
448
|
+
"countChildScopes",
|
|
449
|
+
"getPage",
|
|
450
|
+
"getPages",
|
|
451
|
+
"getPageByPath",
|
|
452
|
+
"findPagesByName",
|
|
453
|
+
"listChildPages",
|
|
454
|
+
"countChildPages",
|
|
455
|
+
"listPages",
|
|
456
|
+
"createPage",
|
|
457
|
+
"updatePage",
|
|
458
|
+
"movePage",
|
|
459
|
+
"mergePages",
|
|
460
|
+
"deletePage",
|
|
461
|
+
"getNote",
|
|
462
|
+
"countNotes",
|
|
463
|
+
"listNotes",
|
|
464
|
+
"listNotesMentioning",
|
|
465
|
+
"addNote",
|
|
466
|
+
"restampNote",
|
|
467
|
+
"removeNote",
|
|
468
|
+
"restoreNote",
|
|
469
|
+
"searchPages",
|
|
470
|
+
"listPageActivity",
|
|
471
|
+
"addPinAudience",
|
|
472
|
+
"removePinAudience",
|
|
473
|
+
"listPins",
|
|
474
|
+
"countPageLinks",
|
|
475
|
+
"listPageLinks",
|
|
476
|
+
"replacePageBodyLinks",
|
|
477
|
+
"listPageBodyLinkSources"
|
|
478
|
+
];
|
|
479
|
+
function encode(value) {
|
|
480
|
+
return JSON.stringify(value, function(key, item) {
|
|
481
|
+
const original = key ? this[key] : item;
|
|
482
|
+
return original instanceof Date ? { __knowledgeDate: original.toISOString() } : item;
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
function decode(text) {
|
|
486
|
+
return JSON.parse(text, (_key, value) => {
|
|
487
|
+
if (value && typeof value === "object" && "__knowledgeDate" in value) return new Date(value.__knowledgeDate);
|
|
488
|
+
return value;
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
var RemoteKnowledgeStorage = class extends _mastra_core_storage.KnowledgeStorage {
|
|
492
|
+
endpoint;
|
|
493
|
+
token;
|
|
494
|
+
constructor(endpoint, token) {
|
|
495
|
+
super({ storageIsolationKey: endpoint });
|
|
496
|
+
this.endpoint = endpoint;
|
|
497
|
+
this.token = token;
|
|
498
|
+
return new Proxy(this, { get(target, key) {
|
|
499
|
+
if (typeof key === "string" && operations.includes(key)) return (input) => target.request(key, input);
|
|
500
|
+
const value = Reflect.get(target, key, target);
|
|
501
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
502
|
+
} });
|
|
503
|
+
}
|
|
504
|
+
async request(operation, input) {
|
|
505
|
+
const response = await fetch(`${this.endpoint}/operations/${operation}`, {
|
|
506
|
+
method: "POST",
|
|
507
|
+
headers: {
|
|
508
|
+
authorization: `Bearer ${this.token}`,
|
|
509
|
+
"content-type": "application/json"
|
|
510
|
+
},
|
|
511
|
+
body: encode({ input }),
|
|
512
|
+
signal: AbortSignal.timeout(3e4)
|
|
513
|
+
});
|
|
514
|
+
const text = await response.text();
|
|
515
|
+
if (!response.ok) {
|
|
516
|
+
let body = {};
|
|
517
|
+
try {
|
|
518
|
+
const parsed = JSON.parse(text);
|
|
519
|
+
if (parsed && typeof parsed === "object") body = parsed;
|
|
520
|
+
} catch {}
|
|
521
|
+
const message = body.detail || body.error?.message || body.title || (text ? `Knowledge request failed (${response.status}): ${text}` : `Knowledge request failed (${response.status})`);
|
|
522
|
+
const name = body.name ?? body.error?.name;
|
|
523
|
+
if (name === "KnowledgeNotFoundError") {
|
|
524
|
+
const error = new _mastra_core_storage.KnowledgeNotFoundError("record", operation);
|
|
525
|
+
error.message = message;
|
|
526
|
+
throw error;
|
|
527
|
+
}
|
|
528
|
+
if (name === "KnowledgeConflictError") {
|
|
529
|
+
const error = new _mastra_core_storage.KnowledgeConflictError(operation);
|
|
530
|
+
error.message = message;
|
|
531
|
+
throw error;
|
|
532
|
+
}
|
|
533
|
+
if (name === "KnowledgePageKeyConflictError") {
|
|
534
|
+
const error = new _mastra_core_storage.KnowledgePageKeyConflictError("", "");
|
|
535
|
+
error.message = message;
|
|
536
|
+
throw error;
|
|
537
|
+
}
|
|
538
|
+
if (name === "KnowledgePageHasChildrenError") {
|
|
539
|
+
const error = new _mastra_core_storage.KnowledgePageHasChildrenError("");
|
|
540
|
+
error.message = message;
|
|
541
|
+
throw error;
|
|
542
|
+
}
|
|
543
|
+
throw new Error(message);
|
|
544
|
+
}
|
|
545
|
+
return decode(text).result;
|
|
546
|
+
}
|
|
547
|
+
getCapabilities() {
|
|
548
|
+
return {
|
|
549
|
+
contractVersion: 4,
|
|
550
|
+
schemaVersion: 4,
|
|
551
|
+
supportsSchemaInspection: false,
|
|
552
|
+
supportsExplicitReset: false
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
async dangerouslyClearAll() {
|
|
556
|
+
throw new Error("Hosted Knowledge cannot be cleared from the client");
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
const DEFAULT_API_URL = "https://knowledge-api.mastra.ai";
|
|
560
|
+
var PlatformKnowledge = class extends _mastra_core_knowledge.Knowledge {
|
|
561
|
+
constructor(options = {}) {
|
|
562
|
+
const token = options.accessToken ?? process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY;
|
|
563
|
+
const instanceId = options.instanceId ?? process.env.MASTRA_KNOWLEDGE_INSTANCE_ID;
|
|
564
|
+
const apiUrl = options.apiUrl ?? (process.env.MASTRA_KNOWLEDGE_API_URL?.trim() || void 0) ?? DEFAULT_API_URL;
|
|
565
|
+
if (!token || !instanceId) throw new Error("PlatformKnowledge requires a Platform access token and Knowledge instance ID");
|
|
566
|
+
const { accessToken: _accessToken, projectId: _projectId, instanceId: _instanceId, apiUrl: _apiUrl, ...config } = options;
|
|
567
|
+
const endpoint = `${apiUrl.replace(/\/$/, "")}/v1/knowledge/${encodeURIComponent(instanceId)}`;
|
|
568
|
+
const storage = new _mastra_core_storage.MastraCompositeStore({
|
|
569
|
+
id: `platform-knowledge-${instanceId}`,
|
|
570
|
+
domains: { knowledge: new RemoteKnowledgeStorage(endpoint, token) }
|
|
571
|
+
});
|
|
572
|
+
super({
|
|
573
|
+
...config,
|
|
574
|
+
tools: config.tools ?? { read: true },
|
|
575
|
+
scopes: config.scopes ?? (0, _mastra_core_knowledge.knowledgeMemoryScopes)(),
|
|
576
|
+
storage
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
};
|
|
580
|
+
exports.PlatformKnowledge = PlatformKnowledge;
|
|
581
|
+
exports.PlatformMemory = PlatformMemory;
|
|
582
|
+
exports.PlatformMemoryApiError = PlatformMemoryApiError;
|
|
583
|
+
exports.PlatformMemoryClient = PlatformMemoryClient;
|
|
584
|
+
exports.resolvePlatformMemoryOptions = resolvePlatformMemoryOptions;
|
|
585
|
+
var _mastra_platform_workspace = require("@mastra/platform-workspace");
|
|
586
|
+
Object.keys(_mastra_platform_workspace).forEach(function(k) {
|
|
587
|
+
if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
|
588
|
+
enumerable: true,
|
|
589
|
+
get: function() {
|
|
590
|
+
return _mastra_platform_workspace[k];
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
//# sourceMappingURL=index.cjs.map
|