@mastra/platform 0.1.0-alpha.1 → 0.1.1-alpha.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/README.md +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/knowledge/index.d.ts.map +1 -1
- package/package.json +8 -8
package/README.md
CHANGED
|
@@ -55,7 +55,7 @@ const browser = new PlatformBrowser({ projectId: 'your-project-id' });
|
|
|
55
55
|
- `POST {apiUrl}/v1/knowledge/{instanceId}/operations/{operation}` with `Authorization: Bearer {accessToken}` and JSON body `{ input }`; returns `{ result }`.
|
|
56
56
|
- `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.
|
|
57
57
|
- `renameScopeDeclaration` is not forwarded and rejects with `KnowledgeUnsupportedCapabilityError`: its `check` callback cannot be sent to the hosted store.
|
|
58
|
-
- Credential priority: option `accessToken`, `MASTRA_PLATFORM_ACCESS_TOKEN`, `MASTRA_PLATFORM_SECRET_KEY`.
|
|
58
|
+
- Credential priority: option `accessToken`, `MASTRA_KNOWLEDGE_ACCESS_TOKEN` (a Knowledge-only token, used when set and non-empty), `MASTRA_PLATFORM_ACCESS_TOKEN`, `MASTRA_PLATFORM_SECRET_KEY`.
|
|
59
59
|
- 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.
|
|
60
60
|
- Hosted Knowledge requires a core and PostgreSQL adapter release implementing the Knowledge pages-v4 contract; production release alignment remains pending.
|
|
61
61
|
|
package/dist/index.cjs
CHANGED
|
@@ -672,7 +672,7 @@ var RemoteKnowledgeStorage = class extends _mastra_core_storage.KnowledgeStorage
|
|
|
672
672
|
const DEFAULT_API_URL = "https://knowledge-api.mastra.ai";
|
|
673
673
|
var PlatformKnowledge = class extends _mastra_core_knowledge.Knowledge {
|
|
674
674
|
constructor(options = {}) {
|
|
675
|
-
const token = options.accessToken ?? process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY;
|
|
675
|
+
const token = options.accessToken ?? (process.env.MASTRA_KNOWLEDGE_ACCESS_TOKEN?.trim() || void 0) ?? process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY;
|
|
676
676
|
const instanceId = options.instanceId ?? process.env.MASTRA_KNOWLEDGE_INSTANCE_ID;
|
|
677
677
|
const apiUrl = options.apiUrl ?? (process.env.MASTRA_KNOWLEDGE_API_URL?.trim() || void 0) ?? DEFAULT_API_URL;
|
|
678
678
|
if (!token || !instanceId) throw new Error("PlatformKnowledge requires a Platform access token and Knowledge instance ID");
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["DEFAULT_API_URL","parseMemoryRequestContext","MastraMemory","createTool","z","DEFAULT_API_URL","StagehandBrowser","KnowledgeStorage","KnowledgeNotFoundError","KnowledgeConflictError","KnowledgePageKeyConflictError","KnowledgePageHasChildrenError","Knowledge","MastraCompositeStore"],"sources":["../src/memory/client.ts","../src/memory/platform-memory.ts","../src/browser/index.ts","../src/knowledge/index.ts"],"sourcesContent":["export interface PlatformMemoryClientOptions {\n /** Platform access token. Falls back to `MASTRA_PLATFORM_ACCESS_TOKEN`, then `MASTRA_PLATFORM_SECRET_KEY`. */\n accessToken?: string;\n /** Memory instance id. Falls back to `MASTRA_MEMORY_INSTANCE_ID`. */\n instanceId?: string;\n /** Falls back to `MASTRA_PROJECT_ID`. Sent as a hint; ownership is enforced server-side from the token. */\n projectId?: string;\n /** Falls back to `MASTRA_ENVIRONMENT_ID`. */\n environmentId?: string;\n /** Sent as `x-acting-user-id`, used by the API when the token is not tied to a user. */\n actingUserId?: string;\n /**\n * Memory API URL. Falls back to `MASTRA_MEMORY_API_URL`, then `https://memory-api.mastra.ai`.\n */\n apiUrl?: string;\n fetch?: typeof fetch;\n}\n\nexport interface MemoryThread {\n id: string;\n resourceId: string;\n title: string | null;\n metadata: Record<string, unknown> | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport type MemoryMessagePart = { type: string; [key: string]: unknown };\n\nexport interface MemoryMessage {\n id: string;\n role: string;\n content: string;\n /** Mastra V2 parts (text, tool-invocation, reasoning, file, …), stored verbatim. */\n parts: MemoryMessagePart[];\n createdAt: string;\n}\n\nexport interface MemoryMessageInput {\n id?: string;\n role: 'user' | 'assistant';\n /** Text content. Optional when `parts` is set. */\n content?: string;\n parts?: MemoryMessagePart[];\n createdAt?: string;\n}\n\nexport interface MemoryContext {\n /** Rendered observations, ready to use as a system message. */\n system: string | null;\n /**\n * User-role reminder that goes before `messages` once observations exist, so the model\n * continues the conversation instead of treating the observations as a new prompt.\n * Older servers omit it.\n */\n continuation?: string | null;\n /** Messages not yet folded into observations, oldest first. */\n messages: MemoryMessage[];\n /**\n * Ready-to-send prefix in `@mastra/memory` order: system (`om-system`), continuation\n * (`om-continuation`), then `messages`. Older servers omit it; use `promptOf`.\n */\n prompt?: MemoryMessage[];\n observedAt: string | null;\n}\n\nexport interface MemoryObservationRecord {\n activeObservations: string | null;\n lastObservedAt: string | null;\n [key: string]: unknown;\n}\n\ntype SerializedMessageList = ReturnType<import('@mastra/core/agent').MessageList['serialize']>;\n\nexport type RunMemoryProcessorsInput =\n | {\n phase: 'inputStep';\n resourceId: string;\n stepNumber: number;\n messageList: SerializedMessageList;\n model?: { provider: string; modelId: string };\n }\n | { phase: 'output'; resourceId: string; messageList: SerializedMessageList; finishReason?: string };\n\nexport interface MemoryProcessorsResult {\n /** Null when a processor aborted the run. */\n messageList: SerializedMessageList | null;\n chunks: unknown[];\n rotations: number;\n aborted: string | null;\n}\n\nexport interface MemoryObservationMatch {\n text: string;\n threadId: string | null;\n observedAt: string | null;\n}\n\nexport interface MemoryThreadConfigUpdate {\n observationTokens?: number | null;\n reflectionTokens?: number | null;\n}\n\nexport interface MemoryThreadConfig {\n observationTokens: number;\n reflectionTokens: number;\n overrides: { observationTokens: number | null; reflectionTokens: number | null };\n}\n\nexport interface MemoryObservationRun {\n id: string;\n threadId: string;\n resourceId: string;\n startedAt: string;\n durationMs: number;\n observed: boolean;\n reflected: boolean;\n tokensBefore: number;\n tokensAfter: number | null;\n error: string | null;\n}\n\nconst DEFAULT_API_URL = 'https://memory-api.mastra.ai';\nconst REQUEST_TIMEOUT_MS = 30_000;\n// Processor runs execute the hosted observer/reflector (LLM calls) inside the request.\nconst PROCESSOR_TIMEOUT_MS = 5 * 60_000;\n\nfunction env(name: string): string | undefined {\n return process.env[name]?.trim() || undefined;\n}\n\nfunction required(value: string | undefined, name: string): string {\n if (!value) throw new Error(`PlatformMemory: ${name} is required`);\n return value;\n}\n\nexport function resolvePlatformMemoryOptions(options: PlatformMemoryClientOptions = {}) {\n return {\n accessToken: required(\n options.accessToken ?? env('MASTRA_PLATFORM_ACCESS_TOKEN') ?? env('MASTRA_PLATFORM_SECRET_KEY'),\n 'accessToken',\n ),\n instanceId: required(options.instanceId ?? env('MASTRA_MEMORY_INSTANCE_ID'), 'instanceId'),\n projectId: options.projectId ?? env('MASTRA_PROJECT_ID'),\n environmentId: options.environmentId ?? env('MASTRA_ENVIRONMENT_ID'),\n actingUserId: options.actingUserId,\n apiUrl: (options.apiUrl ?? env('MASTRA_MEMORY_API_URL') ?? DEFAULT_API_URL).replace(/\\/$/, ''),\n fetch: options.fetch ?? fetch,\n };\n}\n\nexport class PlatformMemoryApiError extends Error {\n constructor(\n readonly status: number,\n readonly body: string,\n ) {\n super(`Platform Memory request failed with ${status}${body ? `: ${body}` : ''}`);\n this.name = 'PlatformMemoryApiError';\n }\n}\n\ntype Query = Record<string, string | number | undefined>;\n\n/** Typed client for the Platform Memory API (`/v1/memory/:instanceId/*`). */\nexport class PlatformMemoryClient {\n readonly instanceId: string;\n private readonly opts: ReturnType<typeof resolvePlatformMemoryOptions>;\n\n constructor(options: PlatformMemoryClientOptions = {}) {\n this.opts = resolvePlatformMemoryOptions(options);\n this.instanceId = this.opts.instanceId;\n }\n\n /** MCP endpoint for this instance, for clients that speak MCP directly. */\n get mcpUrl(): string {\n return `${this.base}/mcp`;\n }\n\n listThreads(query: { resourceId?: string; page?: number; perPage?: number } = {}) {\n return this.request<{ threads: MemoryThread[]; hasMore: boolean }>('GET', '/threads', { query });\n }\n\n createThread(body: { id?: string; resourceId: string; title?: string; metadata?: Record<string, unknown> }) {\n return this.request<MemoryThread>('POST', '/threads', { body });\n }\n\n /** Returns null when the thread does not exist. */\n async getThread(threadId: string): Promise<MemoryThread | null> {\n try {\n return await this.request<MemoryThread>('GET', `/threads/${encodeURIComponent(threadId)}`);\n } catch (error) {\n if (error instanceof PlatformMemoryApiError && error.status === 404) return null;\n throw error;\n }\n }\n\n updateThread(threadId: string, body: { title?: string; metadata?: Record<string, unknown> }) {\n return this.request<MemoryThread>('PATCH', `/threads/${encodeURIComponent(threadId)}`, { body });\n }\n\n async deleteThread(threadId: string): Promise<void> {\n await this.request('DELETE', `/threads/${encodeURIComponent(threadId)}`);\n }\n\n listMessages(threadId: string, query: { page?: number; perPage?: number } = {}) {\n return this.request<{ messages: MemoryMessage[]; hasMore: boolean }>(\n 'GET',\n `/threads/${encodeURIComponent(threadId)}/messages`,\n { query },\n );\n }\n\n /** Saves messages and schedules observation in the background. Creates the thread if needed. */\n saveMessages(threadId: string, body: { resourceId: string; messages: MemoryMessageInput[] }) {\n return this.request<{ messages: MemoryMessage[] }>('POST', `/threads/${encodeURIComponent(threadId)}/messages`, {\n body,\n });\n }\n\n getContext(threadId: string, resourceId: string, opts: { workingMemory?: 'readonly' | 'tool' | 'off' } = {}) {\n return this.request<MemoryContext>('GET', `/threads/${encodeURIComponent(threadId)}/context`, {\n query: { resourceId, ...(opts.workingMemory ? { workingMemory: opts.workingMemory } : {}) },\n });\n }\n\n async getWorkingMemory(resourceId: string): Promise<string | null> {\n const res = await this.request<{ workingMemory: string | null }>('GET', '/working-memory', {\n query: { resourceId },\n });\n return res.workingMemory;\n }\n\n async updateWorkingMemory(resourceId: string, workingMemory: string): Promise<void> {\n await this.request('PUT', '/working-memory', { body: { resourceId, workingMemory } });\n }\n\n /** Omit resourceId to search the instance's most recently active threads. */\n async search(body: { resourceId?: string; threadId?: string; query: string; limit?: number }) {\n const res = await this.request<{ matches: MemoryObservationMatch[] }>('POST', '/search', { body });\n return res.matches;\n }\n\n /** Current observational-memory record for the thread, or null before the first observation. */\n async getObservations(threadId: string): Promise<MemoryObservationRecord | null> {\n const res = await this.request<{ record: MemoryObservationRecord | null }>(\n 'GET',\n `/threads/${encodeURIComponent(threadId)}/observations`,\n );\n return res.record;\n }\n\n /** Runs the instance's memory processors for one agent phase on a serialized message list. */\n runProcessors(threadId: string, body: RunMemoryProcessorsInput, signal?: AbortSignal) {\n return this.request<MemoryProcessorsResult>('POST', `/threads/${encodeURIComponent(threadId)}/processors`, {\n body,\n signal,\n timeoutMs: PROCESSOR_TIMEOUT_MS,\n });\n }\n\n async listObservationRuns(query: { threadId?: string; limit?: number } = {}) {\n const res = await this.request<{ runs: MemoryObservationRun[] }>('GET', '/runs', { query });\n return res.runs;\n }\n\n /** Effective observation thresholds for the thread and which ones it overrides. */\n getThreadConfig(threadId: string) {\n return this.request<MemoryThreadConfig>('GET', `/threads/${encodeURIComponent(threadId)}/config`);\n }\n\n /** Overrides thresholds for one thread. Pass `null` to fall back to the instance value. */\n updateThreadConfig(threadId: string, config: MemoryThreadConfigUpdate) {\n return this.request<MemoryThreadConfig>('PATCH', `/threads/${encodeURIComponent(threadId)}/config`, {\n body: config,\n });\n }\n\n /** Copies a thread, its messages, and its observations. */\n cloneThread(\n threadId: string,\n body: { newThreadId?: string; title?: string; metadata?: Record<string, unknown>; messageLimit?: number } = {},\n ) {\n return this.request<{ thread: MemoryThread; clonedMessageCount: number }>(\n 'POST',\n `/threads/${encodeURIComponent(threadId)}/clone`,\n { body },\n );\n }\n\n /** Deletes messages from a thread. Ids that belong to other threads are ignored. */\n async deleteMessages(threadId: string, messageIds: string[]): Promise<number> {\n const res = await this.request<{ deleted: number }>(\n 'POST',\n `/threads/${encodeURIComponent(threadId)}/messages/delete`,\n { body: { messageIds } },\n );\n return res.deleted;\n }\n\n /** Everything stored for one resource (user): working memory and threads. */\n getResource(resourceId: string, query: { page?: number; perPage?: number } = {}) {\n return this.request<{\n resourceId: string;\n workingMemory: string | null;\n threads: MemoryThread[];\n totalThreads: number;\n hasMore: boolean;\n }>('GET', `/resources/${encodeURIComponent(resourceId)}`, { query });\n }\n\n /** Resources (users) in the instance, most recently active first. */\n listResources(query: { page?: number; perPage?: number } = {}) {\n return this.request<{\n resources: { resourceId: string; threadCount: number; lastActiveAt: string }[];\n hasMore: boolean;\n }>('GET', '/resources', { query });\n }\n\n /** Deletes every thread, message, observation and the working memory for a resource. */\n async deleteResource(resourceId: string): Promise<number> {\n const res = await this.request<{ deletedThreads: number }>(\n 'DELETE',\n `/resources/${encodeURIComponent(resourceId)}`,\n );\n return res.deletedThreads;\n }\n\n private get base(): string {\n return `${this.opts.apiUrl}/v1/memory/${encodeURIComponent(this.opts.instanceId)}`;\n }\n\n private async request<T>(\n method: string,\n path: string,\n init: { query?: Query; body?: unknown; signal?: AbortSignal; timeoutMs?: number } = {},\n ): Promise<T> {\n const url = new URL(this.base + path);\n for (const [key, value] of Object.entries(init.query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value));\n }\n const headers: Record<string, string> = { authorization: `Bearer ${this.opts.accessToken}` };\n if (this.opts.actingUserId) headers['x-acting-user-id'] = this.opts.actingUserId;\n if (this.opts.projectId) headers['x-mastra-project-id'] = this.opts.projectId;\n if (this.opts.environmentId) headers['x-mastra-environment-id'] = this.opts.environmentId;\n if (init.body !== undefined) headers['content-type'] = 'application/json';\n\n const deadline = AbortSignal.timeout(init.timeoutMs ?? REQUEST_TIMEOUT_MS);\n const res = await this.opts.fetch(url, {\n method,\n headers,\n body: init.body === undefined ? undefined : JSON.stringify(init.body),\n signal: init.signal ? AbortSignal.any([init.signal, deadline]) : deadline,\n });\n if (!res.ok) throw new PlatformMemoryApiError(res.status, await res.text().catch(() => ''));\n if (res.status === 204) return undefined as T;\n return (await res.json()) as T;\n }\n}\n","import type { MastraDBMessage } from '@mastra/core/agent';\nimport { MastraMemory, parseMemoryRequestContext } from '@mastra/core/memory';\nimport type { MemoryConfig, MemoryConfigInternal, StorageThreadType, WorkingMemoryTemplate } from '@mastra/core/memory';\nimport type {\n InputProcessor,\n OutputProcessor,\n ProcessInputArgs,\n ProcessInputStepArgs,\n ProcessOutputResultArgs,\n} from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type {\n StorageCloneThreadInput,\n StorageCloneThreadOutput,\n StorageListMessagesInput,\n StorageListThreadsInput,\n StorageListThreadsOutput,\n} from '@mastra/core/storage';\nimport { createTool } from '@mastra/core/tools';\nimport type { ToolAction } from '@mastra/core/tools';\n\nimport { z } from 'zod';\n\nimport { PlatformMemoryClient } from './client';\nimport type {\n MemoryMessage,\n MemoryMessageInput,\n MemoryProcessorsResult,\n MemoryThread,\n PlatformMemoryClientOptions,\n} from './client';\n\nexport type PlatformMemoryOptions = PlatformMemoryClientOptions & {\n id?: string;\n /** Use a preconfigured client instead of building one from the options above. */\n client?: PlatformMemoryClient;\n /**\n * How working memory is shown to the model. Defaults to `readonly`: the resource's stored\n * working memory is added to each run's prompt. `tool` also gives the agent an\n * `updateWorkingMemory` tool (not in read-only runs); `off` leaves working memory out.\n */\n workingMemory?: 'readonly' | 'tool' | 'off';\n};\n\ntype MessageListLike = ProcessInputArgs['messageList'];\n\nfunction threadFromApi(thread: MemoryThread): StorageThreadType {\n return {\n id: thread.id,\n resourceId: thread.resourceId,\n title: thread.title ?? undefined,\n metadata: thread.metadata ?? undefined,\n createdAt: new Date(thread.createdAt),\n updatedAt: new Date(thread.updatedAt),\n };\n}\n\nfunction messageFromApi(message: MemoryMessage, threadId: string, resourceId?: string): MastraDBMessage {\n return {\n id: message.id,\n role: message.role === 'assistant' ? 'assistant' : 'user',\n createdAt: new Date(message.createdAt),\n threadId,\n resourceId,\n content: {\n format: 2,\n parts: (message.parts?.length\n ? message.parts\n : [{ type: 'text', text: message.content }]) as MastraDBMessage['content']['parts'],\n },\n };\n}\n\nfunction textOf(message: MastraDBMessage): string {\n const parts = message.content.parts ?? [];\n const text = parts\n .filter((part): part is { type: 'text'; text: string } => part.type === 'text')\n .map(part => part.text)\n .join('\\n');\n return text || message.content.content || '';\n}\n\n/** User/assistant messages with all their parts (tool calls, reasoning, files). System messages are skipped. */\nfunction toApiMessages(messages: MastraDBMessage[]): MemoryMessageInput[] {\n return messages.flatMap((message): MemoryMessageInput[] => {\n if (message.role !== 'user' && message.role !== 'assistant') return [];\n const parts = message.content.parts ?? [];\n const createdAt = new Date(message.createdAt).toISOString();\n const content = textOf(message) || undefined;\n if (!parts.length && !content) return [];\n return [{ id: message.id, role: message.role, content, parts: parts.length ? parts : undefined, createdAt }];\n });\n}\n\nfunction memoryContext(requestContext: RequestContext | undefined, messageList: MessageListLike) {\n const ctx = parseMemoryRequestContext(requestContext);\n if (ctx?.thread?.id) {\n return {\n threadId: ctx.thread.id,\n resourceId: ctx.resourceId ?? ctx.thread.id,\n readOnly: ctx.memoryConfig?.readOnly,\n };\n }\n const info = messageList.serialize().memoryInfo;\n if (info?.threadId) return { threadId: info.threadId, resourceId: info.resourceId ?? info.threadId, readOnly: false };\n return null;\n}\n\nconst WORKING_MEMORY_TAG = 'platform-working-memory';\n\n/**\n * Adds the resource's stored working memory as a system message. The hosted processors don't\n * deliver it, so the client reads it on the first step of every run: a fresh read each run, so an\n * update between runs shows up on the next one.\n */\nasync function addWorkingMemory(\n client: PlatformMemoryClient,\n messageList: MessageListLike,\n resourceId: string,\n canUpdate: boolean,\n) {\n const data = await client.getWorkingMemory(resourceId);\n messageList.clearSystemMessages(WORKING_MEMORY_TAG);\n if (canUpdate) {\n messageList.addSystem(\n `WORKING_MEMORY_SYSTEM_INSTRUCTION:\nStore 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.\n\n<working_memory_data>\n${data ?? ''}\n</working_memory_data>`,\n WORKING_MEMORY_TAG,\n );\n } else if (data) {\n messageList.addSystem(\n `WORKING_MEMORY_SYSTEM_INSTRUCTION (READ-ONLY):\nThe following is what is remembered about the user. Use it for context; you cannot change it.\n\n<working_memory_data>\n${data}\n</working_memory_data>`,\n WORKING_MEMORY_TAG,\n );\n }\n}\n\n/**\n * What a read-only run sees of the thread, read through the context route, which writes nothing:\n * observations, the continuation reminder, then the messages not yet observed. Running the hosted\n * processors instead would save messages and start observation.\n */\nasync function addReadOnlyContext(\n client: PlatformMemoryClient,\n messageList: MessageListLike,\n threadId: string,\n resourceId: string,\n) {\n const context = await client.getContext(threadId, resourceId, { workingMemory: 'off' });\n const prompt = context.prompt ?? [\n ...(context.system\n ? [{ id: 'om-system', role: 'system', content: context.system, parts: [], createdAt: new Date(0).toISOString() }]\n : []),\n ...(context.continuation\n ? [\n {\n id: 'om-continuation',\n role: 'user',\n content: context.continuation,\n parts: [],\n createdAt: new Date(0).toISOString(),\n },\n ]\n : []),\n ...context.messages,\n ];\n for (const message of prompt) {\n if (message.role === 'system') messageList.addSystem(message.content, 'memory');\n else messageList.add(messageFromApi(message, threadId, resourceId), 'memory');\n }\n}\n\nasync function applyResult(\n result: MemoryProcessorsResult,\n agent: Pick<ProcessInputStepArgs, 'messageList' | 'writer' | 'abort' | 'rotateResponseMessageId'>,\n) {\n for (const chunk of result.chunks) await agent.writer?.custom(chunk as never);\n for (let i = 0; i < result.rotations; i++) agent.rotateResponseMessageId?.();\n if (result.aborted !== null || !result.messageList) return agent.abort(result.aborted ?? undefined);\n return agent.messageList.deserialize(result.messageList);\n}\n\n/**\n * Mastra memory backed by a hosted Platform Memory instance.\n *\n * Observation and reflection run on the Platform: on each input step and on the final output this\n * class sends the serialized message list to the instance's memory processors and applies the\n * result. Messages are stored with all their parts (text, tool calls, reasoning, files).\n */\nexport class PlatformMemory extends MastraMemory {\n readonly client: PlatformMemoryClient;\n private readonly workingMemoryMode: 'readonly' | 'tool' | 'off';\n\n constructor(options: PlatformMemoryOptions = {}) {\n super({ id: options.id ?? 'platform-memory', name: 'PlatformMemory' });\n this.client = options.client ?? new PlatformMemoryClient(options);\n this.workingMemoryMode = options.workingMemory ?? 'readonly';\n }\n\n listTools(config?: MemoryConfig): Record<string, ToolAction<any, any, any, any, any>> {\n if (this.workingMemoryMode !== 'tool' || config?.readOnly) return {};\n this.assertResourceScopedWorkingMemory(config);\n const client = this.client;\n return {\n updateWorkingMemory: createTool({\n id: 'update-working-memory',\n description:\n '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.',\n inputSchema: z.object({\n memory: z.string().describe('The Markdown formatted working memory content to store.'),\n }),\n execute: async ({ memory }, context) => {\n const resourceId = context?.agent?.resourceId ?? context?.agent?.threadId;\n if (!resourceId) throw new Error('updateWorkingMemory needs a thread or resource');\n await client.updateWorkingMemory(resourceId, memory);\n return { success: true };\n },\n }),\n };\n }\n\n // The instance runs the real @mastra/memory processors; these only ship the message list\n // there and apply what comes back (list, stream parts, message-id rotations, abort).\n async getInputProcessors(): Promise<InputProcessor[]> {\n const client = this.client;\n const workingMemoryMode = this.workingMemoryMode;\n return [\n {\n id: 'platform-memory',\n name: 'Platform Memory',\n async processInputStep({\n messageList,\n requestContext,\n stepNumber,\n model,\n writer,\n abort,\n abortSignal,\n rotateResponseMessageId,\n }: ProcessInputStepArgs) {\n const ctx = memoryContext(requestContext, messageList);\n if (!ctx) return messageList;\n if (ctx.readOnly) {\n if (stepNumber === 0) {\n await addReadOnlyContext(client, messageList, ctx.threadId, ctx.resourceId);\n if (workingMemoryMode !== 'off') await addWorkingMemory(client, messageList, ctx.resourceId, false);\n }\n return messageList;\n }\n const result = await client.runProcessors(\n ctx.threadId,\n {\n phase: 'inputStep',\n resourceId: ctx.resourceId,\n stepNumber,\n messageList: messageList.serialize(),\n model: model ? { provider: model.provider, modelId: model.modelId } : undefined,\n },\n abortSignal,\n );\n const list = await applyResult(result, { messageList, writer, abort, rotateResponseMessageId });\n if (stepNumber === 0 && workingMemoryMode !== 'off') {\n await addWorkingMemory(client, messageList, ctx.resourceId, workingMemoryMode === 'tool');\n }\n return list;\n },\n },\n ];\n }\n\n async getOutputProcessors(): Promise<OutputProcessor[]> {\n const client = this.client;\n return [\n {\n id: 'platform-memory',\n name: 'Platform Memory',\n async processOutputResult({ messageList, requestContext, result, writer, abort }: ProcessOutputResultArgs) {\n const ctx = memoryContext(requestContext, messageList);\n if (!ctx || ctx.readOnly) return messageList;\n // No abortSignal here: this call saves the turn's messages, and aborting mid-save can lose them.\n const res = await client.runProcessors(ctx.threadId, {\n phase: 'output',\n resourceId: ctx.resourceId,\n messageList: messageList.serialize(),\n finishReason: result?.finishReason,\n });\n return applyResult(res, { messageList, writer, abort });\n },\n },\n ];\n }\n\n async getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null> {\n const thread = await this.client.getThread(threadId);\n return thread ? threadFromApi(thread) : null;\n }\n\n async listThreads(args: StorageListThreadsInput): Promise<StorageListThreadsOutput> {\n const page = args.page ?? 0;\n const perPage = args.perPage === false ? 200 : (args.perPage ?? 100);\n const threads: StorageThreadType[] = [];\n for (let next = 0; ; next++) {\n const res = await this.client.listThreads({ resourceId: args.filter?.resourceId, page: next, perPage: 200 });\n threads.push(...res.threads.map(threadFromApi));\n if (!res.hasMore) break;\n }\n const filtered = threads.filter(thread =>\n Object.entries(args.filter?.metadata ?? {}).every(([key, value]) => thread.metadata?.[key] === value),\n );\n const field = args.orderBy?.field ?? 'updatedAt';\n const direction = args.orderBy?.direction === 'ASC' ? 1 : -1;\n filtered.sort((a, b) => direction * (a[field].getTime() - b[field].getTime()));\n const selected = args.perPage === false ? filtered : filtered.slice(page * perPage, (page + 1) * perPage);\n return {\n threads: selected,\n hasMore: args.perPage === false ? false : (page + 1) * perPage < filtered.length,\n page,\n perPage: args.perPage === false ? (false as const) : perPage,\n total: filtered.length,\n };\n }\n\n async saveThread({ thread }: { thread: StorageThreadType }): Promise<StorageThreadType> {\n const existing = await this.client.getThread(thread.id);\n const saved = existing\n ? await this.client.updateThread(thread.id, { title: thread.title, metadata: thread.metadata })\n : await this.client.createThread({\n id: thread.id,\n resourceId: thread.resourceId,\n title: thread.title,\n metadata: thread.metadata,\n });\n return threadFromApi(saved);\n }\n\n async updateThread({\n id,\n title,\n metadata,\n }: {\n id: string;\n title?: string;\n metadata?: Record<string, unknown>;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<StorageThreadType> {\n return threadFromApi(await this.client.updateThread(id, { title, metadata }));\n }\n\n async deleteThread(threadId: string): Promise<void> {\n await this.client.deleteThread(threadId);\n }\n\n async saveMessages(args: {\n messages: MastraDBMessage[];\n memoryConfig?: MemoryConfig;\n }): Promise<{ messages: MastraDBMessage[] }> {\n const byThread = new Map<string, MastraDBMessage[]>();\n for (const message of args.messages) {\n if (!message.threadId) continue;\n byThread.set(message.threadId, [...(byThread.get(message.threadId) ?? []), message]);\n }\n for (const [threadId, messages] of byThread) {\n const apiMessages = toApiMessages(messages);\n if (!apiMessages.length) continue;\n const resourceId = messages[0]!.resourceId ?? threadId;\n await this.client.saveMessages(threadId, { resourceId, messages: apiMessages });\n }\n return { messages: args.messages };\n }\n\n async recall(args: StorageListMessagesInput) {\n const threadIds = Array.isArray(args.threadId) ? args.threadId : [args.threadId];\n if (!threadIds.length || threadIds.some(id => !id)) throw new Error('PlatformMemory.recall requires a threadId');\n if (Object.keys(args.filter?.metadata ?? {}).length || args.include?.length) {\n throw new Error('PlatformMemory.recall does not support metadata filters or include windows');\n }\n const page = args.page ?? 0;\n const perPage = args.perPage === false ? 200 : (args.perPage ?? 40);\n const messages: MastraDBMessage[] = [];\n for (const threadId of threadIds) {\n const thread = await this.client.getThread(threadId);\n if (!thread || (args.resourceId && thread.resourceId !== args.resourceId)) continue;\n const resourceId = thread.resourceId;\n for (let next = 0; ; next++) {\n const res = await this.client.listMessages(threadId, { page: next, perPage: 200 });\n messages.push(...res.messages.map(message => messageFromApi(message, threadId, resourceId)));\n if (!res.hasMore) break;\n }\n }\n const { start, end, startExclusive, endExclusive } = args.filter?.dateRange ?? {};\n const filtered = messages.filter(message => {\n const timestamp = message.createdAt.getTime();\n return (\n (!start || (startExclusive ? timestamp > start.getTime() : timestamp >= start.getTime())) &&\n (!end || (endExclusive ? timestamp < end.getTime() : timestamp <= end.getTime()))\n );\n });\n const direction = args.orderBy?.direction === 'DESC' ? -1 : 1;\n filtered.sort((a, b) => direction * (a.createdAt.getTime() - b.createdAt.getTime()));\n const selected = args.perPage === false ? filtered : filtered.slice(page * perPage, (page + 1) * perPage);\n return {\n messages: selected,\n total: filtered.length,\n page,\n perPage: args.perPage === false ? (false as const) : perPage,\n hasMore: args.perPage === false ? false : (page + 1) * perPage < filtered.length,\n };\n }\n\n // Hosted working memory is keyed by resource only, so thread scope would silently be shared\n // across every thread of the same resource.\n private assertResourceScopedWorkingMemory(config?: MemoryConfig | MemoryConfigInternal): void {\n if (this.getMergedThreadConfig(config ?? {}).workingMemory?.scope === 'thread') {\n throw new Error('PlatformMemory does not support thread-scoped working memory');\n }\n }\n\n async getWorkingMemory({\n threadId,\n resourceId,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<string | null> {\n this.assertResourceScopedWorkingMemory(memoryConfig);\n return this.client.getWorkingMemory(resourceId ?? threadId);\n }\n\n async getWorkingMemoryTemplate(): Promise<WorkingMemoryTemplate | null> {\n return null;\n }\n\n async updateWorkingMemory({\n threadId,\n resourceId,\n workingMemory,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<void> {\n this.assertResourceScopedWorkingMemory(memoryConfig);\n await this.client.updateWorkingMemory(resourceId ?? threadId, workingMemory);\n }\n\n async __experimental_updateWorkingMemoryVNext(args: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<{ success: boolean; reason: string }> {\n await this.updateWorkingMemory(args);\n return { success: true, reason: 'replaced' };\n }\n\n async deleteMessages(): Promise<void> {\n throw new Error('PlatformMemory does not support deleting individual messages yet');\n }\n\n async cloneThread(_args: StorageCloneThreadInput): Promise<StorageCloneThreadOutput> {\n throw new Error('PlatformMemory does not support cloning threads yet');\n }\n}\n","import { StagehandBrowser } from '@mastra/stagehand';\nimport type { StagehandBrowserConfig } from '@mastra/stagehand';\n\nexport interface PlatformBrowserOptions extends Omit<\n StagehandBrowserConfig,\n 'cdpUrl' | 'scope' | 'env' | 'apiKey' | 'projectId'\n> {\n /** Existing Platform-provisioned CDP URL. When supplied, no API request or access token is needed. */\n cdpUrl?: string;\n /** Platform access token. Falls back to `MASTRA_PLATFORM_ACCESS_TOKEN`, then `MASTRA_PLATFORM_SECRET_KEY`. */\n accessToken?: string;\n /** Mastra Platform project ID. Falls back to `MASTRA_PROJECT_ID`. */\n projectId?: string;\n /** Browser provisioning API URL. Falls back to `MASTRA_BROWSER_API_URL`. */\n apiUrl?: string;\n fetch?: typeof fetch;\n}\n\nconst DEFAULT_API_URL = 'https://platform.mastra.ai';\n\nfunction trimTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === '/') end--;\n return url.slice(0, end);\n}\n\n/** A Stagehand browser connected to a Platform-provisioned Browserbase session. */\nexport class PlatformBrowser extends StagehandBrowser {\n constructor(options: PlatformBrowserOptions = {}) {\n const {\n cdpUrl,\n accessToken = process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY,\n projectId = process.env.MASTRA_PROJECT_ID,\n apiUrl = process.env.MASTRA_BROWSER_API_URL ?? DEFAULT_API_URL,\n fetch: fetchImpl = fetch,\n ...stagehandOptions\n } = options;\n if (!cdpUrl && !accessToken) throw new Error('PlatformBrowser: accessToken is required');\n if (!cdpUrl && !projectId) throw new Error('PlatformBrowser: projectId is required');\n\n super({\n ...stagehandOptions,\n scope: 'shared',\n cdpUrl:\n cdpUrl ||\n (async () => {\n const response = await fetchImpl(`${trimTrailingSlashes(apiUrl)}/v1/browsers/sessions`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({ projectId }),\n signal: AbortSignal.timeout(30_000),\n });\n if (!response.ok) throw new Error(`PlatformBrowser: browser provisioning failed (${response.status})`);\n const result: unknown = await response.json();\n if (\n !result ||\n typeof result !== 'object' ||\n !('connectUrl' in result) ||\n typeof result.connectUrl !== 'string'\n ) {\n throw new Error('PlatformBrowser: browser provisioning returned no connectUrl');\n }\n return result.connectUrl;\n }),\n });\n }\n}\n","import { Knowledge } from '@mastra/core/knowledge';\nimport type { KnowledgeConfig, KnowledgeScopeDeclarations } from '@mastra/core/knowledge';\nimport {\n MastraCompositeStore,\n KnowledgeStorage,\n KnowledgeConflictError,\n KnowledgeNotFoundError,\n KnowledgePageHasChildrenError,\n KnowledgePageKeyConflictError,\n} from '@mastra/core/storage';\nimport type { KnowledgePageStore } from '@mastra/core/storage';\n\nexport interface PlatformKnowledgeOptions extends Omit<\n KnowledgeConfig,\n 'storage' | 'vector' | 'embedder' | 'embedderOptions' | 'scopes'\n> {\n accessToken?: string;\n projectId?: string;\n instanceId?: string;\n /**\n * Knowledge API URL. Falls back to `MASTRA_KNOWLEDGE_API_URL`, then `https://knowledge-api.mastra.ai`.\n */\n apiUrl?: string;\n}\n\n// These are the schema-v4 page-store methods, not arbitrary object properties or storage lifecycle methods.\n// `renameScopeDeclaration` is left to the base class, which rejects it: its `check` callback can't be\n// serialized, so the hosted store couldn't validate affected scopes before re-keying them.\nconst operations = [\n 'materializeScope',\n 'getScopesByAddress',\n 'listScopeDeclarations',\n 'listChildScopes',\n 'countChildScopes',\n 'getPage',\n 'getPages',\n 'getPageByPath',\n 'findPagesByName',\n 'listChildPages',\n 'countChildPages',\n 'listPages',\n 'createPage',\n 'updatePage',\n 'movePage',\n 'mergePages',\n 'deletePage',\n 'getNote',\n 'countNotes',\n 'listNotes',\n 'listNotesMentioning',\n 'addNote',\n 'restampNote',\n 'removeNote',\n 'restoreNote',\n 'searchPages',\n 'listPageActivity',\n 'addPinAudience',\n 'removePinAudience',\n 'listPins',\n 'countPageLinks',\n 'listPageLinks',\n 'replacePageBodyLinks',\n 'listPageBodyLinkSources',\n] as const satisfies readonly (keyof KnowledgePageStore)[];\n\n// Fails to compile when a page-store method is neither forwarded nor deliberately left to the base class.\ntype UnforwardedOperation = Exclude<keyof KnowledgePageStore, (typeof operations)[number]>;\nconst operationsAreExhaustive: [UnforwardedOperation] extends ['renameScopeDeclaration']\n ? ['renameScopeDeclaration'] extends [UnforwardedOperation]\n ? true\n : never\n : never = true;\nvoid operationsAreExhaustive;\n\nfunction encode(value: unknown): string {\n return JSON.stringify(value, function (key, item: unknown) {\n const original: unknown = key ? (this as Record<string, unknown>)[key] : item;\n return original instanceof Date ? { __knowledgeDate: original.toISOString() } : item;\n });\n}\n\nfunction decode<T>(text: string): T {\n return JSON.parse(text, (_key, value: unknown) => {\n if (value && typeof value === 'object' && '__knowledgeDate' in value) {\n return new Date((value as { __knowledgeDate: string }).__knowledgeDate);\n }\n return value;\n }) as T;\n}\n\nclass RemoteKnowledgeStorage extends KnowledgeStorage {\n constructor(\n private readonly endpoint: string,\n private readonly token: string,\n ) {\n super({ storageIsolationKey: endpoint });\n return new Proxy(this, {\n get(target, key) {\n if (typeof key === 'string' && operations.includes(key as (typeof operations)[number])) {\n return (input?: unknown) => target.request(key, input);\n }\n const value: unknown = Reflect.get(target, key, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n }\n\n private async request(operation: string, input?: unknown): Promise<unknown> {\n const response = await fetch(`${this.endpoint}/operations/${operation}`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${this.token}`,\n 'content-type': 'application/json',\n // This client merges the instance's scope declarations (`getScopeDeclarations`) into its own, so\n // the service leaves its read views as they are rather than widening them for older clients.\n 'x-mastra-knowledge-store-declarations': 'merged',\n },\n body: encode({ input }),\n signal: AbortSignal.timeout(30_000),\n });\n const text = await response.text();\n if (!response.ok) {\n let body: { name?: string; detail?: string; title?: string; error?: { name?: string; message?: string } } = {};\n try {\n const parsed: unknown = JSON.parse(text);\n if (parsed && typeof parsed === 'object') body = parsed;\n } catch {\n // Gateways can return non-JSON error pages.\n }\n const message =\n body.detail ||\n body.error?.message ||\n body.title ||\n (text\n ? `Knowledge request failed (${response.status}): ${text}`\n : `Knowledge request failed (${response.status})`);\n const name = body.name ?? body.error?.name;\n if (name === 'KnowledgeNotFoundError') {\n const error = new KnowledgeNotFoundError('record', operation);\n error.message = message;\n throw error;\n }\n if (name === 'KnowledgeConflictError') {\n const error = new KnowledgeConflictError(operation);\n error.message = message;\n throw error;\n }\n if (name === 'KnowledgePageKeyConflictError') {\n const error = new KnowledgePageKeyConflictError('', '');\n error.message = message;\n throw error;\n }\n if (name === 'KnowledgePageHasChildrenError') {\n const error = new KnowledgePageHasChildrenError('');\n error.message = message;\n throw error;\n }\n throw Object.assign(new Error(message), { status: response.status });\n }\n return decode<{ result?: unknown }>(text).result;\n }\n\n /**\n * The scope declarations the instance supplies, such as the ones its importers write to, with their\n * access rules. A service that doesn't have the operation yet answers 404 \"Knowledge operation not\n * found\" and supplies none. Any other failure, including another 404 (a missing instance, a wrong\n * URL), and anything but a declaration record is a broken response, not \"none\".\n */\n override async getScopeDeclarations(): Promise<KnowledgeScopeDeclarations> {\n let result: unknown;\n try {\n result = await this.request('getScopeDeclarations');\n } catch (error) {\n const status = (error as { status?: unknown }).status;\n if (status === 404 && (error as Error).message === 'Knowledge operation not found') return {};\n throw error;\n }\n if (!result || typeof result !== 'object' || Array.isArray(result)) {\n throw new Error('Knowledge service answered getScopeDeclarations without a declaration record');\n }\n return result as KnowledgeScopeDeclarations;\n }\n\n override getCapabilities() {\n return {\n contractVersion: 4,\n schemaVersion: 4,\n supportsSchemaInspection: false,\n supportsExplicitReset: false,\n // The service's stores keep a pin's kind and depth, so listing pins round-trip.\n supportsPinKinds: true,\n } as const;\n }\n\n override async dangerouslyClearAll(): Promise<void> {\n throw new Error('Hosted Knowledge cannot be cleared from the client');\n }\n}\n\nconst DEFAULT_API_URL = 'https://knowledge-api.mastra.ai';\n\nexport class PlatformKnowledge extends Knowledge {\n constructor(options: PlatformKnowledgeOptions = {}) {\n const token =\n options.accessToken ?? process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY;\n const instanceId = options.instanceId ?? process.env.MASTRA_KNOWLEDGE_INSTANCE_ID;\n const apiUrl = options.apiUrl ?? (process.env.MASTRA_KNOWLEDGE_API_URL?.trim() || undefined) ?? DEFAULT_API_URL;\n if (!token || !instanceId) {\n throw new Error('PlatformKnowledge requires a Platform access token and Knowledge instance ID');\n }\n const {\n accessToken: _accessToken,\n projectId: _projectId,\n instanceId: _instanceId,\n apiUrl: _apiUrl,\n ...config\n } = options;\n const endpoint = `${apiUrl.replace(/\\/$/, '')}/v1/knowledge/${encodeURIComponent(instanceId)}`;\n const storage = new MastraCompositeStore({\n id: `platform-knowledge-${instanceId}`,\n domains: { knowledge: new RemoteKnowledgeStorage(endpoint, token) },\n });\n super({\n ...config,\n tools: config.tools ?? { read: true },\n // Platform owns every scope declaration and access grant: the instance serves them all through\n // `getScopeDeclarations`, so there is one place to change who reads what. Declaring scopes here\n // too would conflict with the instance's (a key both declare silently takes the code's rules,\n // and overlapping patterns break every call), so PlatformKnowledge takes no `scopes` option.\n scopes: {},\n storage,\n });\n }\n}\n\nexport { encode as encodeKnowledgeTransport, decode as decodeKnowledgeTransport };\nexport { operations as knowledgeOperations };\n"],"mappings":";;;;;;;;AA0HA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M,IAAI,MAAM,8EAA8E;EAEhG,OAAO;CACT;CAEA,kBAA2B;EACzB,OAAO;GACL,iBAAiB;GACjB,eAAe;GACf,0BAA0B;GAC1B,uBAAuB;GAEvB,kBAAkB;EACpB;CACF;CAEA,MAAe,sBAAqC;EAClD,MAAM,IAAI,MAAM,oDAAoD;CACtE;AACF;AAEA,MAAM,kBAAkB;AAExB,IAAa,oBAAb,cAAuCC,uBAAAA,UAAU;CAC/C,YAAY,UAAoC,CAAC,GAAG;EAClD,MAAM,QACJ,QAAQ,eAAe,QAAQ,IAAI,gCAAgC,QAAQ,IAAI;EACjF,MAAM,aAAa,QAAQ,cAAc,QAAQ,IAAI;EACrD,MAAM,SAAS,QAAQ,WAAW,QAAQ,IAAI,0BAA0B,KAAK,KAAK,KAAA,MAAc;EAChG,IAAI,CAAC,SAAS,CAAC,YACb,MAAM,IAAI,MAAM,8EAA8E;EAEhG,MAAM,EACJ,aAAa,cACb,WAAW,YACX,YAAY,aACZ,QAAQ,SACR,GAAG,WACD;EACJ,MAAM,WAAW,GAAG,OAAO,QAAQ,OAAO,EAAE,EAAE,gBAAgB,mBAAmB,UAAU;EAC3F,MAAM,UAAU,IAAIC,qBAAAA,qBAAqB;GACvC,IAAI,sBAAsB;GAC1B,SAAS,EAAE,WAAW,IAAI,uBAAuB,UAAU,KAAK,EAAE;EACpE,CAAC;EACD,MAAM;GACJ,GAAG;GACH,OAAO,OAAO,SAAS,EAAE,MAAM,KAAK;GAKpC,QAAQ,CAAC;GACT;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["DEFAULT_API_URL","parseMemoryRequestContext","MastraMemory","createTool","z","DEFAULT_API_URL","StagehandBrowser","KnowledgeStorage","KnowledgeNotFoundError","KnowledgeConflictError","KnowledgePageKeyConflictError","KnowledgePageHasChildrenError","Knowledge","MastraCompositeStore"],"sources":["../src/memory/client.ts","../src/memory/platform-memory.ts","../src/browser/index.ts","../src/knowledge/index.ts"],"sourcesContent":["export interface PlatformMemoryClientOptions {\n /** Platform access token. Falls back to `MASTRA_PLATFORM_ACCESS_TOKEN`, then `MASTRA_PLATFORM_SECRET_KEY`. */\n accessToken?: string;\n /** Memory instance id. Falls back to `MASTRA_MEMORY_INSTANCE_ID`. */\n instanceId?: string;\n /** Falls back to `MASTRA_PROJECT_ID`. Sent as a hint; ownership is enforced server-side from the token. */\n projectId?: string;\n /** Falls back to `MASTRA_ENVIRONMENT_ID`. */\n environmentId?: string;\n /** Sent as `x-acting-user-id`, used by the API when the token is not tied to a user. */\n actingUserId?: string;\n /**\n * Memory API URL. Falls back to `MASTRA_MEMORY_API_URL`, then `https://memory-api.mastra.ai`.\n */\n apiUrl?: string;\n fetch?: typeof fetch;\n}\n\nexport interface MemoryThread {\n id: string;\n resourceId: string;\n title: string | null;\n metadata: Record<string, unknown> | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport type MemoryMessagePart = { type: string; [key: string]: unknown };\n\nexport interface MemoryMessage {\n id: string;\n role: string;\n content: string;\n /** Mastra V2 parts (text, tool-invocation, reasoning, file, …), stored verbatim. */\n parts: MemoryMessagePart[];\n createdAt: string;\n}\n\nexport interface MemoryMessageInput {\n id?: string;\n role: 'user' | 'assistant';\n /** Text content. Optional when `parts` is set. */\n content?: string;\n parts?: MemoryMessagePart[];\n createdAt?: string;\n}\n\nexport interface MemoryContext {\n /** Rendered observations, ready to use as a system message. */\n system: string | null;\n /**\n * User-role reminder that goes before `messages` once observations exist, so the model\n * continues the conversation instead of treating the observations as a new prompt.\n * Older servers omit it.\n */\n continuation?: string | null;\n /** Messages not yet folded into observations, oldest first. */\n messages: MemoryMessage[];\n /**\n * Ready-to-send prefix in `@mastra/memory` order: system (`om-system`), continuation\n * (`om-continuation`), then `messages`. Older servers omit it; use `promptOf`.\n */\n prompt?: MemoryMessage[];\n observedAt: string | null;\n}\n\nexport interface MemoryObservationRecord {\n activeObservations: string | null;\n lastObservedAt: string | null;\n [key: string]: unknown;\n}\n\ntype SerializedMessageList = ReturnType<import('@mastra/core/agent').MessageList['serialize']>;\n\nexport type RunMemoryProcessorsInput =\n | {\n phase: 'inputStep';\n resourceId: string;\n stepNumber: number;\n messageList: SerializedMessageList;\n model?: { provider: string; modelId: string };\n }\n | { phase: 'output'; resourceId: string; messageList: SerializedMessageList; finishReason?: string };\n\nexport interface MemoryProcessorsResult {\n /** Null when a processor aborted the run. */\n messageList: SerializedMessageList | null;\n chunks: unknown[];\n rotations: number;\n aborted: string | null;\n}\n\nexport interface MemoryObservationMatch {\n text: string;\n threadId: string | null;\n observedAt: string | null;\n}\n\nexport interface MemoryThreadConfigUpdate {\n observationTokens?: number | null;\n reflectionTokens?: number | null;\n}\n\nexport interface MemoryThreadConfig {\n observationTokens: number;\n reflectionTokens: number;\n overrides: { observationTokens: number | null; reflectionTokens: number | null };\n}\n\nexport interface MemoryObservationRun {\n id: string;\n threadId: string;\n resourceId: string;\n startedAt: string;\n durationMs: number;\n observed: boolean;\n reflected: boolean;\n tokensBefore: number;\n tokensAfter: number | null;\n error: string | null;\n}\n\nconst DEFAULT_API_URL = 'https://memory-api.mastra.ai';\nconst REQUEST_TIMEOUT_MS = 30_000;\n// Processor runs execute the hosted observer/reflector (LLM calls) inside the request.\nconst PROCESSOR_TIMEOUT_MS = 5 * 60_000;\n\nfunction env(name: string): string | undefined {\n return process.env[name]?.trim() || undefined;\n}\n\nfunction required(value: string | undefined, name: string): string {\n if (!value) throw new Error(`PlatformMemory: ${name} is required`);\n return value;\n}\n\nexport function resolvePlatformMemoryOptions(options: PlatformMemoryClientOptions = {}) {\n return {\n accessToken: required(\n options.accessToken ?? env('MASTRA_PLATFORM_ACCESS_TOKEN') ?? env('MASTRA_PLATFORM_SECRET_KEY'),\n 'accessToken',\n ),\n instanceId: required(options.instanceId ?? env('MASTRA_MEMORY_INSTANCE_ID'), 'instanceId'),\n projectId: options.projectId ?? env('MASTRA_PROJECT_ID'),\n environmentId: options.environmentId ?? env('MASTRA_ENVIRONMENT_ID'),\n actingUserId: options.actingUserId,\n apiUrl: (options.apiUrl ?? env('MASTRA_MEMORY_API_URL') ?? DEFAULT_API_URL).replace(/\\/$/, ''),\n fetch: options.fetch ?? fetch,\n };\n}\n\nexport class PlatformMemoryApiError extends Error {\n constructor(\n readonly status: number,\n readonly body: string,\n ) {\n super(`Platform Memory request failed with ${status}${body ? `: ${body}` : ''}`);\n this.name = 'PlatformMemoryApiError';\n }\n}\n\ntype Query = Record<string, string | number | undefined>;\n\n/** Typed client for the Platform Memory API (`/v1/memory/:instanceId/*`). */\nexport class PlatformMemoryClient {\n readonly instanceId: string;\n private readonly opts: ReturnType<typeof resolvePlatformMemoryOptions>;\n\n constructor(options: PlatformMemoryClientOptions = {}) {\n this.opts = resolvePlatformMemoryOptions(options);\n this.instanceId = this.opts.instanceId;\n }\n\n /** MCP endpoint for this instance, for clients that speak MCP directly. */\n get mcpUrl(): string {\n return `${this.base}/mcp`;\n }\n\n listThreads(query: { resourceId?: string; page?: number; perPage?: number } = {}) {\n return this.request<{ threads: MemoryThread[]; hasMore: boolean }>('GET', '/threads', { query });\n }\n\n createThread(body: { id?: string; resourceId: string; title?: string; metadata?: Record<string, unknown> }) {\n return this.request<MemoryThread>('POST', '/threads', { body });\n }\n\n /** Returns null when the thread does not exist. */\n async getThread(threadId: string): Promise<MemoryThread | null> {\n try {\n return await this.request<MemoryThread>('GET', `/threads/${encodeURIComponent(threadId)}`);\n } catch (error) {\n if (error instanceof PlatformMemoryApiError && error.status === 404) return null;\n throw error;\n }\n }\n\n updateThread(threadId: string, body: { title?: string; metadata?: Record<string, unknown> }) {\n return this.request<MemoryThread>('PATCH', `/threads/${encodeURIComponent(threadId)}`, { body });\n }\n\n async deleteThread(threadId: string): Promise<void> {\n await this.request('DELETE', `/threads/${encodeURIComponent(threadId)}`);\n }\n\n listMessages(threadId: string, query: { page?: number; perPage?: number } = {}) {\n return this.request<{ messages: MemoryMessage[]; hasMore: boolean }>(\n 'GET',\n `/threads/${encodeURIComponent(threadId)}/messages`,\n { query },\n );\n }\n\n /** Saves messages and schedules observation in the background. Creates the thread if needed. */\n saveMessages(threadId: string, body: { resourceId: string; messages: MemoryMessageInput[] }) {\n return this.request<{ messages: MemoryMessage[] }>('POST', `/threads/${encodeURIComponent(threadId)}/messages`, {\n body,\n });\n }\n\n getContext(threadId: string, resourceId: string, opts: { workingMemory?: 'readonly' | 'tool' | 'off' } = {}) {\n return this.request<MemoryContext>('GET', `/threads/${encodeURIComponent(threadId)}/context`, {\n query: { resourceId, ...(opts.workingMemory ? { workingMemory: opts.workingMemory } : {}) },\n });\n }\n\n async getWorkingMemory(resourceId: string): Promise<string | null> {\n const res = await this.request<{ workingMemory: string | null }>('GET', '/working-memory', {\n query: { resourceId },\n });\n return res.workingMemory;\n }\n\n async updateWorkingMemory(resourceId: string, workingMemory: string): Promise<void> {\n await this.request('PUT', '/working-memory', { body: { resourceId, workingMemory } });\n }\n\n /** Omit resourceId to search the instance's most recently active threads. */\n async search(body: { resourceId?: string; threadId?: string; query: string; limit?: number }) {\n const res = await this.request<{ matches: MemoryObservationMatch[] }>('POST', '/search', { body });\n return res.matches;\n }\n\n /** Current observational-memory record for the thread, or null before the first observation. */\n async getObservations(threadId: string): Promise<MemoryObservationRecord | null> {\n const res = await this.request<{ record: MemoryObservationRecord | null }>(\n 'GET',\n `/threads/${encodeURIComponent(threadId)}/observations`,\n );\n return res.record;\n }\n\n /** Runs the instance's memory processors for one agent phase on a serialized message list. */\n runProcessors(threadId: string, body: RunMemoryProcessorsInput, signal?: AbortSignal) {\n return this.request<MemoryProcessorsResult>('POST', `/threads/${encodeURIComponent(threadId)}/processors`, {\n body,\n signal,\n timeoutMs: PROCESSOR_TIMEOUT_MS,\n });\n }\n\n async listObservationRuns(query: { threadId?: string; limit?: number } = {}) {\n const res = await this.request<{ runs: MemoryObservationRun[] }>('GET', '/runs', { query });\n return res.runs;\n }\n\n /** Effective observation thresholds for the thread and which ones it overrides. */\n getThreadConfig(threadId: string) {\n return this.request<MemoryThreadConfig>('GET', `/threads/${encodeURIComponent(threadId)}/config`);\n }\n\n /** Overrides thresholds for one thread. Pass `null` to fall back to the instance value. */\n updateThreadConfig(threadId: string, config: MemoryThreadConfigUpdate) {\n return this.request<MemoryThreadConfig>('PATCH', `/threads/${encodeURIComponent(threadId)}/config`, {\n body: config,\n });\n }\n\n /** Copies a thread, its messages, and its observations. */\n cloneThread(\n threadId: string,\n body: { newThreadId?: string; title?: string; metadata?: Record<string, unknown>; messageLimit?: number } = {},\n ) {\n return this.request<{ thread: MemoryThread; clonedMessageCount: number }>(\n 'POST',\n `/threads/${encodeURIComponent(threadId)}/clone`,\n { body },\n );\n }\n\n /** Deletes messages from a thread. Ids that belong to other threads are ignored. */\n async deleteMessages(threadId: string, messageIds: string[]): Promise<number> {\n const res = await this.request<{ deleted: number }>(\n 'POST',\n `/threads/${encodeURIComponent(threadId)}/messages/delete`,\n { body: { messageIds } },\n );\n return res.deleted;\n }\n\n /** Everything stored for one resource (user): working memory and threads. */\n getResource(resourceId: string, query: { page?: number; perPage?: number } = {}) {\n return this.request<{\n resourceId: string;\n workingMemory: string | null;\n threads: MemoryThread[];\n totalThreads: number;\n hasMore: boolean;\n }>('GET', `/resources/${encodeURIComponent(resourceId)}`, { query });\n }\n\n /** Resources (users) in the instance, most recently active first. */\n listResources(query: { page?: number; perPage?: number } = {}) {\n return this.request<{\n resources: { resourceId: string; threadCount: number; lastActiveAt: string }[];\n hasMore: boolean;\n }>('GET', '/resources', { query });\n }\n\n /** Deletes every thread, message, observation and the working memory for a resource. */\n async deleteResource(resourceId: string): Promise<number> {\n const res = await this.request<{ deletedThreads: number }>(\n 'DELETE',\n `/resources/${encodeURIComponent(resourceId)}`,\n );\n return res.deletedThreads;\n }\n\n private get base(): string {\n return `${this.opts.apiUrl}/v1/memory/${encodeURIComponent(this.opts.instanceId)}`;\n }\n\n private async request<T>(\n method: string,\n path: string,\n init: { query?: Query; body?: unknown; signal?: AbortSignal; timeoutMs?: number } = {},\n ): Promise<T> {\n const url = new URL(this.base + path);\n for (const [key, value] of Object.entries(init.query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value));\n }\n const headers: Record<string, string> = { authorization: `Bearer ${this.opts.accessToken}` };\n if (this.opts.actingUserId) headers['x-acting-user-id'] = this.opts.actingUserId;\n if (this.opts.projectId) headers['x-mastra-project-id'] = this.opts.projectId;\n if (this.opts.environmentId) headers['x-mastra-environment-id'] = this.opts.environmentId;\n if (init.body !== undefined) headers['content-type'] = 'application/json';\n\n const deadline = AbortSignal.timeout(init.timeoutMs ?? REQUEST_TIMEOUT_MS);\n const res = await this.opts.fetch(url, {\n method,\n headers,\n body: init.body === undefined ? undefined : JSON.stringify(init.body),\n signal: init.signal ? AbortSignal.any([init.signal, deadline]) : deadline,\n });\n if (!res.ok) throw new PlatformMemoryApiError(res.status, await res.text().catch(() => ''));\n if (res.status === 204) return undefined as T;\n return (await res.json()) as T;\n }\n}\n","import type { MastraDBMessage } from '@mastra/core/agent';\nimport { MastraMemory, parseMemoryRequestContext } from '@mastra/core/memory';\nimport type { MemoryConfig, MemoryConfigInternal, StorageThreadType, WorkingMemoryTemplate } from '@mastra/core/memory';\nimport type {\n InputProcessor,\n OutputProcessor,\n ProcessInputArgs,\n ProcessInputStepArgs,\n ProcessOutputResultArgs,\n} from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type {\n StorageCloneThreadInput,\n StorageCloneThreadOutput,\n StorageListMessagesInput,\n StorageListThreadsInput,\n StorageListThreadsOutput,\n} from '@mastra/core/storage';\nimport { createTool } from '@mastra/core/tools';\nimport type { ToolAction } from '@mastra/core/tools';\n\nimport { z } from 'zod';\n\nimport { PlatformMemoryClient } from './client';\nimport type {\n MemoryMessage,\n MemoryMessageInput,\n MemoryProcessorsResult,\n MemoryThread,\n PlatformMemoryClientOptions,\n} from './client';\n\nexport type PlatformMemoryOptions = PlatformMemoryClientOptions & {\n id?: string;\n /** Use a preconfigured client instead of building one from the options above. */\n client?: PlatformMemoryClient;\n /**\n * How working memory is shown to the model. Defaults to `readonly`: the resource's stored\n * working memory is added to each run's prompt. `tool` also gives the agent an\n * `updateWorkingMemory` tool (not in read-only runs); `off` leaves working memory out.\n */\n workingMemory?: 'readonly' | 'tool' | 'off';\n};\n\ntype MessageListLike = ProcessInputArgs['messageList'];\n\nfunction threadFromApi(thread: MemoryThread): StorageThreadType {\n return {\n id: thread.id,\n resourceId: thread.resourceId,\n title: thread.title ?? undefined,\n metadata: thread.metadata ?? undefined,\n createdAt: new Date(thread.createdAt),\n updatedAt: new Date(thread.updatedAt),\n };\n}\n\nfunction messageFromApi(message: MemoryMessage, threadId: string, resourceId?: string): MastraDBMessage {\n return {\n id: message.id,\n role: message.role === 'assistant' ? 'assistant' : 'user',\n createdAt: new Date(message.createdAt),\n threadId,\n resourceId,\n content: {\n format: 2,\n parts: (message.parts?.length\n ? message.parts\n : [{ type: 'text', text: message.content }]) as MastraDBMessage['content']['parts'],\n },\n };\n}\n\nfunction textOf(message: MastraDBMessage): string {\n const parts = message.content.parts ?? [];\n const text = parts\n .filter((part): part is { type: 'text'; text: string } => part.type === 'text')\n .map(part => part.text)\n .join('\\n');\n return text || message.content.content || '';\n}\n\n/** User/assistant messages with all their parts (tool calls, reasoning, files). System messages are skipped. */\nfunction toApiMessages(messages: MastraDBMessage[]): MemoryMessageInput[] {\n return messages.flatMap((message): MemoryMessageInput[] => {\n if (message.role !== 'user' && message.role !== 'assistant') return [];\n const parts = message.content.parts ?? [];\n const createdAt = new Date(message.createdAt).toISOString();\n const content = textOf(message) || undefined;\n if (!parts.length && !content) return [];\n return [{ id: message.id, role: message.role, content, parts: parts.length ? parts : undefined, createdAt }];\n });\n}\n\nfunction memoryContext(requestContext: RequestContext | undefined, messageList: MessageListLike) {\n const ctx = parseMemoryRequestContext(requestContext);\n if (ctx?.thread?.id) {\n return {\n threadId: ctx.thread.id,\n resourceId: ctx.resourceId ?? ctx.thread.id,\n readOnly: ctx.memoryConfig?.readOnly,\n };\n }\n const info = messageList.serialize().memoryInfo;\n if (info?.threadId) return { threadId: info.threadId, resourceId: info.resourceId ?? info.threadId, readOnly: false };\n return null;\n}\n\nconst WORKING_MEMORY_TAG = 'platform-working-memory';\n\n/**\n * Adds the resource's stored working memory as a system message. The hosted processors don't\n * deliver it, so the client reads it on the first step of every run: a fresh read each run, so an\n * update between runs shows up on the next one.\n */\nasync function addWorkingMemory(\n client: PlatformMemoryClient,\n messageList: MessageListLike,\n resourceId: string,\n canUpdate: boolean,\n) {\n const data = await client.getWorkingMemory(resourceId);\n messageList.clearSystemMessages(WORKING_MEMORY_TAG);\n if (canUpdate) {\n messageList.addSystem(\n `WORKING_MEMORY_SYSTEM_INSTRUCTION:\nStore 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.\n\n<working_memory_data>\n${data ?? ''}\n</working_memory_data>`,\n WORKING_MEMORY_TAG,\n );\n } else if (data) {\n messageList.addSystem(\n `WORKING_MEMORY_SYSTEM_INSTRUCTION (READ-ONLY):\nThe following is what is remembered about the user. Use it for context; you cannot change it.\n\n<working_memory_data>\n${data}\n</working_memory_data>`,\n WORKING_MEMORY_TAG,\n );\n }\n}\n\n/**\n * What a read-only run sees of the thread, read through the context route, which writes nothing:\n * observations, the continuation reminder, then the messages not yet observed. Running the hosted\n * processors instead would save messages and start observation.\n */\nasync function addReadOnlyContext(\n client: PlatformMemoryClient,\n messageList: MessageListLike,\n threadId: string,\n resourceId: string,\n) {\n const context = await client.getContext(threadId, resourceId, { workingMemory: 'off' });\n const prompt = context.prompt ?? [\n ...(context.system\n ? [{ id: 'om-system', role: 'system', content: context.system, parts: [], createdAt: new Date(0).toISOString() }]\n : []),\n ...(context.continuation\n ? [\n {\n id: 'om-continuation',\n role: 'user',\n content: context.continuation,\n parts: [],\n createdAt: new Date(0).toISOString(),\n },\n ]\n : []),\n ...context.messages,\n ];\n for (const message of prompt) {\n if (message.role === 'system') messageList.addSystem(message.content, 'memory');\n else messageList.add(messageFromApi(message, threadId, resourceId), 'memory');\n }\n}\n\nasync function applyResult(\n result: MemoryProcessorsResult,\n agent: Pick<ProcessInputStepArgs, 'messageList' | 'writer' | 'abort' | 'rotateResponseMessageId'>,\n) {\n for (const chunk of result.chunks) await agent.writer?.custom(chunk as never);\n for (let i = 0; i < result.rotations; i++) agent.rotateResponseMessageId?.();\n if (result.aborted !== null || !result.messageList) return agent.abort(result.aborted ?? undefined);\n return agent.messageList.deserialize(result.messageList);\n}\n\n/**\n * Mastra memory backed by a hosted Platform Memory instance.\n *\n * Observation and reflection run on the Platform: on each input step and on the final output this\n * class sends the serialized message list to the instance's memory processors and applies the\n * result. Messages are stored with all their parts (text, tool calls, reasoning, files).\n */\nexport class PlatformMemory extends MastraMemory {\n readonly client: PlatformMemoryClient;\n private readonly workingMemoryMode: 'readonly' | 'tool' | 'off';\n\n constructor(options: PlatformMemoryOptions = {}) {\n super({ id: options.id ?? 'platform-memory', name: 'PlatformMemory' });\n this.client = options.client ?? new PlatformMemoryClient(options);\n this.workingMemoryMode = options.workingMemory ?? 'readonly';\n }\n\n listTools(config?: MemoryConfig): Record<string, ToolAction<any, any, any, any, any>> {\n if (this.workingMemoryMode !== 'tool' || config?.readOnly) return {};\n this.assertResourceScopedWorkingMemory(config);\n const client = this.client;\n return {\n updateWorkingMemory: createTool({\n id: 'update-working-memory',\n description:\n '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.',\n inputSchema: z.object({\n memory: z.string().describe('The Markdown formatted working memory content to store.'),\n }),\n execute: async ({ memory }, context) => {\n const resourceId = context?.agent?.resourceId ?? context?.agent?.threadId;\n if (!resourceId) throw new Error('updateWorkingMemory needs a thread or resource');\n await client.updateWorkingMemory(resourceId, memory);\n return { success: true };\n },\n }),\n };\n }\n\n // The instance runs the real @mastra/memory processors; these only ship the message list\n // there and apply what comes back (list, stream parts, message-id rotations, abort).\n async getInputProcessors(): Promise<InputProcessor[]> {\n const client = this.client;\n const workingMemoryMode = this.workingMemoryMode;\n return [\n {\n id: 'platform-memory',\n name: 'Platform Memory',\n async processInputStep({\n messageList,\n requestContext,\n stepNumber,\n model,\n writer,\n abort,\n abortSignal,\n rotateResponseMessageId,\n }: ProcessInputStepArgs) {\n const ctx = memoryContext(requestContext, messageList);\n if (!ctx) return messageList;\n if (ctx.readOnly) {\n if (stepNumber === 0) {\n await addReadOnlyContext(client, messageList, ctx.threadId, ctx.resourceId);\n if (workingMemoryMode !== 'off') await addWorkingMemory(client, messageList, ctx.resourceId, false);\n }\n return messageList;\n }\n const result = await client.runProcessors(\n ctx.threadId,\n {\n phase: 'inputStep',\n resourceId: ctx.resourceId,\n stepNumber,\n messageList: messageList.serialize(),\n model: model ? { provider: model.provider, modelId: model.modelId } : undefined,\n },\n abortSignal,\n );\n const list = await applyResult(result, { messageList, writer, abort, rotateResponseMessageId });\n if (stepNumber === 0 && workingMemoryMode !== 'off') {\n await addWorkingMemory(client, messageList, ctx.resourceId, workingMemoryMode === 'tool');\n }\n return list;\n },\n },\n ];\n }\n\n async getOutputProcessors(): Promise<OutputProcessor[]> {\n const client = this.client;\n return [\n {\n id: 'platform-memory',\n name: 'Platform Memory',\n async processOutputResult({ messageList, requestContext, result, writer, abort }: ProcessOutputResultArgs) {\n const ctx = memoryContext(requestContext, messageList);\n if (!ctx || ctx.readOnly) return messageList;\n // No abortSignal here: this call saves the turn's messages, and aborting mid-save can lose them.\n const res = await client.runProcessors(ctx.threadId, {\n phase: 'output',\n resourceId: ctx.resourceId,\n messageList: messageList.serialize(),\n finishReason: result?.finishReason,\n });\n return applyResult(res, { messageList, writer, abort });\n },\n },\n ];\n }\n\n async getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null> {\n const thread = await this.client.getThread(threadId);\n return thread ? threadFromApi(thread) : null;\n }\n\n async listThreads(args: StorageListThreadsInput): Promise<StorageListThreadsOutput> {\n const page = args.page ?? 0;\n const perPage = args.perPage === false ? 200 : (args.perPage ?? 100);\n const threads: StorageThreadType[] = [];\n for (let next = 0; ; next++) {\n const res = await this.client.listThreads({ resourceId: args.filter?.resourceId, page: next, perPage: 200 });\n threads.push(...res.threads.map(threadFromApi));\n if (!res.hasMore) break;\n }\n const filtered = threads.filter(thread =>\n Object.entries(args.filter?.metadata ?? {}).every(([key, value]) => thread.metadata?.[key] === value),\n );\n const field = args.orderBy?.field ?? 'updatedAt';\n const direction = args.orderBy?.direction === 'ASC' ? 1 : -1;\n filtered.sort((a, b) => direction * (a[field].getTime() - b[field].getTime()));\n const selected = args.perPage === false ? filtered : filtered.slice(page * perPage, (page + 1) * perPage);\n return {\n threads: selected,\n hasMore: args.perPage === false ? false : (page + 1) * perPage < filtered.length,\n page,\n perPage: args.perPage === false ? (false as const) : perPage,\n total: filtered.length,\n };\n }\n\n async saveThread({ thread }: { thread: StorageThreadType }): Promise<StorageThreadType> {\n const existing = await this.client.getThread(thread.id);\n const saved = existing\n ? await this.client.updateThread(thread.id, { title: thread.title, metadata: thread.metadata })\n : await this.client.createThread({\n id: thread.id,\n resourceId: thread.resourceId,\n title: thread.title,\n metadata: thread.metadata,\n });\n return threadFromApi(saved);\n }\n\n async updateThread({\n id,\n title,\n metadata,\n }: {\n id: string;\n title?: string;\n metadata?: Record<string, unknown>;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<StorageThreadType> {\n return threadFromApi(await this.client.updateThread(id, { title, metadata }));\n }\n\n async deleteThread(threadId: string): Promise<void> {\n await this.client.deleteThread(threadId);\n }\n\n async saveMessages(args: {\n messages: MastraDBMessage[];\n memoryConfig?: MemoryConfig;\n }): Promise<{ messages: MastraDBMessage[] }> {\n const byThread = new Map<string, MastraDBMessage[]>();\n for (const message of args.messages) {\n if (!message.threadId) continue;\n byThread.set(message.threadId, [...(byThread.get(message.threadId) ?? []), message]);\n }\n for (const [threadId, messages] of byThread) {\n const apiMessages = toApiMessages(messages);\n if (!apiMessages.length) continue;\n const resourceId = messages[0]!.resourceId ?? threadId;\n await this.client.saveMessages(threadId, { resourceId, messages: apiMessages });\n }\n return { messages: args.messages };\n }\n\n async recall(args: StorageListMessagesInput) {\n const threadIds = Array.isArray(args.threadId) ? args.threadId : [args.threadId];\n if (!threadIds.length || threadIds.some(id => !id)) throw new Error('PlatformMemory.recall requires a threadId');\n if (Object.keys(args.filter?.metadata ?? {}).length || args.include?.length) {\n throw new Error('PlatformMemory.recall does not support metadata filters or include windows');\n }\n const page = args.page ?? 0;\n const perPage = args.perPage === false ? 200 : (args.perPage ?? 40);\n const messages: MastraDBMessage[] = [];\n for (const threadId of threadIds) {\n const thread = await this.client.getThread(threadId);\n if (!thread || (args.resourceId && thread.resourceId !== args.resourceId)) continue;\n const resourceId = thread.resourceId;\n for (let next = 0; ; next++) {\n const res = await this.client.listMessages(threadId, { page: next, perPage: 200 });\n messages.push(...res.messages.map(message => messageFromApi(message, threadId, resourceId)));\n if (!res.hasMore) break;\n }\n }\n const { start, end, startExclusive, endExclusive } = args.filter?.dateRange ?? {};\n const filtered = messages.filter(message => {\n const timestamp = message.createdAt.getTime();\n return (\n (!start || (startExclusive ? timestamp > start.getTime() : timestamp >= start.getTime())) &&\n (!end || (endExclusive ? timestamp < end.getTime() : timestamp <= end.getTime()))\n );\n });\n const direction = args.orderBy?.direction === 'DESC' ? -1 : 1;\n filtered.sort((a, b) => direction * (a.createdAt.getTime() - b.createdAt.getTime()));\n const selected = args.perPage === false ? filtered : filtered.slice(page * perPage, (page + 1) * perPage);\n return {\n messages: selected,\n total: filtered.length,\n page,\n perPage: args.perPage === false ? (false as const) : perPage,\n hasMore: args.perPage === false ? false : (page + 1) * perPage < filtered.length,\n };\n }\n\n // Hosted working memory is keyed by resource only, so thread scope would silently be shared\n // across every thread of the same resource.\n private assertResourceScopedWorkingMemory(config?: MemoryConfig | MemoryConfigInternal): void {\n if (this.getMergedThreadConfig(config ?? {}).workingMemory?.scope === 'thread') {\n throw new Error('PlatformMemory does not support thread-scoped working memory');\n }\n }\n\n async getWorkingMemory({\n threadId,\n resourceId,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<string | null> {\n this.assertResourceScopedWorkingMemory(memoryConfig);\n return this.client.getWorkingMemory(resourceId ?? threadId);\n }\n\n async getWorkingMemoryTemplate(): Promise<WorkingMemoryTemplate | null> {\n return null;\n }\n\n async updateWorkingMemory({\n threadId,\n resourceId,\n workingMemory,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<void> {\n this.assertResourceScopedWorkingMemory(memoryConfig);\n await this.client.updateWorkingMemory(resourceId ?? threadId, workingMemory);\n }\n\n async __experimental_updateWorkingMemoryVNext(args: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<{ success: boolean; reason: string }> {\n await this.updateWorkingMemory(args);\n return { success: true, reason: 'replaced' };\n }\n\n async deleteMessages(): Promise<void> {\n throw new Error('PlatformMemory does not support deleting individual messages yet');\n }\n\n async cloneThread(_args: StorageCloneThreadInput): Promise<StorageCloneThreadOutput> {\n throw new Error('PlatformMemory does not support cloning threads yet');\n }\n}\n","import { StagehandBrowser } from '@mastra/stagehand';\nimport type { StagehandBrowserConfig } from '@mastra/stagehand';\n\nexport interface PlatformBrowserOptions extends Omit<\n StagehandBrowserConfig,\n 'cdpUrl' | 'scope' | 'env' | 'apiKey' | 'projectId'\n> {\n /** Existing Platform-provisioned CDP URL. When supplied, no API request or access token is needed. */\n cdpUrl?: string;\n /** Platform access token. Falls back to `MASTRA_PLATFORM_ACCESS_TOKEN`, then `MASTRA_PLATFORM_SECRET_KEY`. */\n accessToken?: string;\n /** Mastra Platform project ID. Falls back to `MASTRA_PROJECT_ID`. */\n projectId?: string;\n /** Browser provisioning API URL. Falls back to `MASTRA_BROWSER_API_URL`. */\n apiUrl?: string;\n fetch?: typeof fetch;\n}\n\nconst DEFAULT_API_URL = 'https://platform.mastra.ai';\n\nfunction trimTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === '/') end--;\n return url.slice(0, end);\n}\n\n/** A Stagehand browser connected to a Platform-provisioned Browserbase session. */\nexport class PlatformBrowser extends StagehandBrowser {\n constructor(options: PlatformBrowserOptions = {}) {\n const {\n cdpUrl,\n accessToken = process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY,\n projectId = process.env.MASTRA_PROJECT_ID,\n apiUrl = process.env.MASTRA_BROWSER_API_URL ?? DEFAULT_API_URL,\n fetch: fetchImpl = fetch,\n ...stagehandOptions\n } = options;\n if (!cdpUrl && !accessToken) throw new Error('PlatformBrowser: accessToken is required');\n if (!cdpUrl && !projectId) throw new Error('PlatformBrowser: projectId is required');\n\n super({\n ...stagehandOptions,\n scope: 'shared',\n cdpUrl:\n cdpUrl ||\n (async () => {\n const response = await fetchImpl(`${trimTrailingSlashes(apiUrl)}/v1/browsers/sessions`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({ projectId }),\n signal: AbortSignal.timeout(30_000),\n });\n if (!response.ok) throw new Error(`PlatformBrowser: browser provisioning failed (${response.status})`);\n const result: unknown = await response.json();\n if (\n !result ||\n typeof result !== 'object' ||\n !('connectUrl' in result) ||\n typeof result.connectUrl !== 'string'\n ) {\n throw new Error('PlatformBrowser: browser provisioning returned no connectUrl');\n }\n return result.connectUrl;\n }),\n });\n }\n}\n","import { Knowledge } from '@mastra/core/knowledge';\nimport type { KnowledgeConfig, KnowledgeScopeDeclarations } from '@mastra/core/knowledge';\nimport {\n MastraCompositeStore,\n KnowledgeStorage,\n KnowledgeConflictError,\n KnowledgeNotFoundError,\n KnowledgePageHasChildrenError,\n KnowledgePageKeyConflictError,\n} from '@mastra/core/storage';\nimport type { KnowledgePageStore } from '@mastra/core/storage';\n\nexport interface PlatformKnowledgeOptions extends Omit<\n KnowledgeConfig,\n 'storage' | 'vector' | 'embedder' | 'embedderOptions' | 'scopes'\n> {\n accessToken?: string;\n projectId?: string;\n instanceId?: string;\n /**\n * Knowledge API URL. Falls back to `MASTRA_KNOWLEDGE_API_URL`, then `https://knowledge-api.mastra.ai`.\n */\n apiUrl?: string;\n}\n\n// These are the schema-v4 page-store methods, not arbitrary object properties or storage lifecycle methods.\n// `renameScopeDeclaration` is left to the base class, which rejects it: its `check` callback can't be\n// serialized, so the hosted store couldn't validate affected scopes before re-keying them.\nconst operations = [\n 'materializeScope',\n 'getScopesByAddress',\n 'listScopeDeclarations',\n 'listChildScopes',\n 'countChildScopes',\n 'getPage',\n 'getPages',\n 'getPageByPath',\n 'findPagesByName',\n 'listChildPages',\n 'countChildPages',\n 'listPages',\n 'createPage',\n 'updatePage',\n 'movePage',\n 'mergePages',\n 'deletePage',\n 'getNote',\n 'countNotes',\n 'listNotes',\n 'listNotesMentioning',\n 'addNote',\n 'restampNote',\n 'removeNote',\n 'restoreNote',\n 'searchPages',\n 'listPageActivity',\n 'addPinAudience',\n 'removePinAudience',\n 'listPins',\n 'countPageLinks',\n 'listPageLinks',\n 'replacePageBodyLinks',\n 'listPageBodyLinkSources',\n] as const satisfies readonly (keyof KnowledgePageStore)[];\n\n// Fails to compile when a page-store method is neither forwarded nor deliberately left to the base class.\ntype UnforwardedOperation = Exclude<keyof KnowledgePageStore, (typeof operations)[number]>;\nconst operationsAreExhaustive: [UnforwardedOperation] extends ['renameScopeDeclaration']\n ? ['renameScopeDeclaration'] extends [UnforwardedOperation]\n ? true\n : never\n : never = true;\nvoid operationsAreExhaustive;\n\nfunction encode(value: unknown): string {\n return JSON.stringify(value, function (key, item: unknown) {\n const original: unknown = key ? (this as Record<string, unknown>)[key] : item;\n return original instanceof Date ? { __knowledgeDate: original.toISOString() } : item;\n });\n}\n\nfunction decode<T>(text: string): T {\n return JSON.parse(text, (_key, value: unknown) => {\n if (value && typeof value === 'object' && '__knowledgeDate' in value) {\n return new Date((value as { __knowledgeDate: string }).__knowledgeDate);\n }\n return value;\n }) as T;\n}\n\nclass RemoteKnowledgeStorage extends KnowledgeStorage {\n constructor(\n private readonly endpoint: string,\n private readonly token: string,\n ) {\n super({ storageIsolationKey: endpoint });\n return new Proxy(this, {\n get(target, key) {\n if (typeof key === 'string' && operations.includes(key as (typeof operations)[number])) {\n return (input?: unknown) => target.request(key, input);\n }\n const value: unknown = Reflect.get(target, key, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n }\n\n private async request(operation: string, input?: unknown): Promise<unknown> {\n const response = await fetch(`${this.endpoint}/operations/${operation}`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${this.token}`,\n 'content-type': 'application/json',\n // This client merges the instance's scope declarations (`getScopeDeclarations`) into its own, so\n // the service leaves its read views as they are rather than widening them for older clients.\n 'x-mastra-knowledge-store-declarations': 'merged',\n },\n body: encode({ input }),\n signal: AbortSignal.timeout(30_000),\n });\n const text = await response.text();\n if (!response.ok) {\n let body: { name?: string; detail?: string; title?: string; error?: { name?: string; message?: string } } = {};\n try {\n const parsed: unknown = JSON.parse(text);\n if (parsed && typeof parsed === 'object') body = parsed;\n } catch {\n // Gateways can return non-JSON error pages.\n }\n const message =\n body.detail ||\n body.error?.message ||\n body.title ||\n (text\n ? `Knowledge request failed (${response.status}): ${text}`\n : `Knowledge request failed (${response.status})`);\n const name = body.name ?? body.error?.name;\n if (name === 'KnowledgeNotFoundError') {\n const error = new KnowledgeNotFoundError('record', operation);\n error.message = message;\n throw error;\n }\n if (name === 'KnowledgeConflictError') {\n const error = new KnowledgeConflictError(operation);\n error.message = message;\n throw error;\n }\n if (name === 'KnowledgePageKeyConflictError') {\n const error = new KnowledgePageKeyConflictError('', '');\n error.message = message;\n throw error;\n }\n if (name === 'KnowledgePageHasChildrenError') {\n const error = new KnowledgePageHasChildrenError('');\n error.message = message;\n throw error;\n }\n throw Object.assign(new Error(message), { status: response.status });\n }\n return decode<{ result?: unknown }>(text).result;\n }\n\n /**\n * The scope declarations the instance supplies, such as the ones its importers write to, with their\n * access rules. A service that doesn't have the operation yet answers 404 \"Knowledge operation not\n * found\" and supplies none. Any other failure, including another 404 (a missing instance, a wrong\n * URL), and anything but a declaration record is a broken response, not \"none\".\n */\n override async getScopeDeclarations(): Promise<KnowledgeScopeDeclarations> {\n let result: unknown;\n try {\n result = await this.request('getScopeDeclarations');\n } catch (error) {\n const status = (error as { status?: unknown }).status;\n if (status === 404 && (error as Error).message === 'Knowledge operation not found') return {};\n throw error;\n }\n if (!result || typeof result !== 'object' || Array.isArray(result)) {\n throw new Error('Knowledge service answered getScopeDeclarations without a declaration record');\n }\n return result as KnowledgeScopeDeclarations;\n }\n\n override getCapabilities() {\n return {\n contractVersion: 4,\n schemaVersion: 4,\n supportsSchemaInspection: false,\n supportsExplicitReset: false,\n // The service's stores keep a pin's kind and depth, so listing pins round-trip.\n supportsPinKinds: true,\n } as const;\n }\n\n override async dangerouslyClearAll(): Promise<void> {\n throw new Error('Hosted Knowledge cannot be cleared from the client');\n }\n}\n\nconst DEFAULT_API_URL = 'https://knowledge-api.mastra.ai';\n\nexport class PlatformKnowledge extends Knowledge {\n constructor(options: PlatformKnowledgeOptions = {}) {\n // `MASTRA_KNOWLEDGE_ACCESS_TOKEN` is a Knowledge-only credential, narrower than the general\n // Platform token, so it's preferred when set.\n const token =\n options.accessToken ??\n (process.env.MASTRA_KNOWLEDGE_ACCESS_TOKEN?.trim() || undefined) ??\n process.env.MASTRA_PLATFORM_ACCESS_TOKEN ??\n process.env.MASTRA_PLATFORM_SECRET_KEY;\n const instanceId = options.instanceId ?? process.env.MASTRA_KNOWLEDGE_INSTANCE_ID;\n const apiUrl = options.apiUrl ?? (process.env.MASTRA_KNOWLEDGE_API_URL?.trim() || undefined) ?? DEFAULT_API_URL;\n if (!token || !instanceId) {\n throw new Error('PlatformKnowledge requires a Platform access token and Knowledge instance ID');\n }\n const {\n accessToken: _accessToken,\n projectId: _projectId,\n instanceId: _instanceId,\n apiUrl: _apiUrl,\n ...config\n } = options;\n const endpoint = `${apiUrl.replace(/\\/$/, '')}/v1/knowledge/${encodeURIComponent(instanceId)}`;\n const storage = new MastraCompositeStore({\n id: `platform-knowledge-${instanceId}`,\n domains: { knowledge: new RemoteKnowledgeStorage(endpoint, token) },\n });\n super({\n ...config,\n tools: config.tools ?? { read: true },\n // Platform owns every scope declaration and access grant: the instance serves them all through\n // `getScopeDeclarations`, so there is one place to change who reads what. Declaring scopes here\n // too would conflict with the instance's (a key both declare silently takes the code's rules,\n // and overlapping patterns break every call), so PlatformKnowledge takes no `scopes` option.\n scopes: {},\n storage,\n });\n }\n}\n\nexport { encode as encodeKnowledgeTransport, decode as decodeKnowledgeTransport };\nexport { operations as knowledgeOperations };\n"],"mappings":";;;;;;;;AA0HA,MAAMA,oBAAkB;AACxB,MAAM,qBAAqB;AAE3B,MAAM,uBAAuB;AAE7B,SAAS,IAAI,MAAkC;CAC7C,OAAO,QAAQ,IAAI,KAAK,EAAE,KAAK,KAAK,KAAA;AACtC;AAEA,SAAS,SAAS,OAA2B,MAAsB;CACjE,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,mBAAmB,KAAK,aAAa;CACjE,OAAO;AACT;AAEA,SAAgB,6BAA6B,UAAuC,CAAC,GAAG;CACtF,OAAO;EACL,aAAa,SACX,QAAQ,eAAe,IAAI,8BAA8B,KAAK,IAAI,4BAA4B,GAC9F,aACF;EACA,YAAY,SAAS,QAAQ,cAAc,IAAI,2BAA2B,GAAG,YAAY;EACzF,WAAW,QAAQ,aAAa,IAAI,mBAAmB;EACvD,eAAe,QAAQ,iBAAiB,IAAI,uBAAuB;EACnE,cAAc,QAAQ;EACtB,SAAS,QAAQ,UAAU,IAAI,uBAAuB,KAAKA,kBAAAA,CAAiB,QAAQ,OAAO,EAAE;EAC7F,OAAO,QAAQ,SAAS;CAC1B;AACF;AAEA,IAAa,yBAAb,cAA4C,MAAM;CAErC;CACA;CAFX,YACE,QACA,MACA;EACA,MAAM,uCAAuC,SAAS,OAAO,KAAK,S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AAU,IAAIC,qBAAAA,qBAAqB;GACvC,IAAI,sBAAsB;GAC1B,SAAS,EAAE,WAAW,IAAI,uBAAuB,UAAU,KAAK,EAAE;EACpE,CAAC;EACD,MAAM;GACJ,GAAG;GACH,OAAO,OAAO,SAAS,EAAE,MAAM,KAAK;GAKpC,QAAQ,CAAC;GACT;EACF,CAAC;CACH;AACF"}
|
package/dist/index.js
CHANGED
|
@@ -672,7 +672,7 @@ var RemoteKnowledgeStorage = class extends KnowledgeStorage {
|
|
|
672
672
|
const DEFAULT_API_URL = "https://knowledge-api.mastra.ai";
|
|
673
673
|
var PlatformKnowledge = class extends Knowledge {
|
|
674
674
|
constructor(options = {}) {
|
|
675
|
-
const token = options.accessToken ?? process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY;
|
|
675
|
+
const token = options.accessToken ?? (process.env.MASTRA_KNOWLEDGE_ACCESS_TOKEN?.trim() || void 0) ?? process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY;
|
|
676
676
|
const instanceId = options.instanceId ?? process.env.MASTRA_KNOWLEDGE_INSTANCE_ID;
|
|
677
677
|
const apiUrl = options.apiUrl ?? (process.env.MASTRA_KNOWLEDGE_API_URL?.trim() || void 0) ?? DEFAULT_API_URL;
|
|
678
678
|
if (!token || !instanceId) throw new Error("PlatformKnowledge requires a Platform access token and Knowledge instance ID");
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["DEFAULT_API_URL","DEFAULT_API_URL"],"sources":["../src/memory/client.ts","../src/memory/platform-memory.ts","../src/browser/index.ts","../src/knowledge/index.ts"],"sourcesContent":["export interface PlatformMemoryClientOptions {\n /** Platform access token. Falls back to `MASTRA_PLATFORM_ACCESS_TOKEN`, then `MASTRA_PLATFORM_SECRET_KEY`. */\n accessToken?: string;\n /** Memory instance id. Falls back to `MASTRA_MEMORY_INSTANCE_ID`. */\n instanceId?: string;\n /** Falls back to `MASTRA_PROJECT_ID`. Sent as a hint; ownership is enforced server-side from the token. */\n projectId?: string;\n /** Falls back to `MASTRA_ENVIRONMENT_ID`. */\n environmentId?: string;\n /** Sent as `x-acting-user-id`, used by the API when the token is not tied to a user. */\n actingUserId?: string;\n /**\n * Memory API URL. Falls back to `MASTRA_MEMORY_API_URL`, then `https://memory-api.mastra.ai`.\n */\n apiUrl?: string;\n fetch?: typeof fetch;\n}\n\nexport interface MemoryThread {\n id: string;\n resourceId: string;\n title: string | null;\n metadata: Record<string, unknown> | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport type MemoryMessagePart = { type: string; [key: string]: unknown };\n\nexport interface MemoryMessage {\n id: string;\n role: string;\n content: string;\n /** Mastra V2 parts (text, tool-invocation, reasoning, file, …), stored verbatim. */\n parts: MemoryMessagePart[];\n createdAt: string;\n}\n\nexport interface MemoryMessageInput {\n id?: string;\n role: 'user' | 'assistant';\n /** Text content. Optional when `parts` is set. */\n content?: string;\n parts?: MemoryMessagePart[];\n createdAt?: string;\n}\n\nexport interface MemoryContext {\n /** Rendered observations, ready to use as a system message. */\n system: string | null;\n /**\n * User-role reminder that goes before `messages` once observations exist, so the model\n * continues the conversation instead of treating the observations as a new prompt.\n * Older servers omit it.\n */\n continuation?: string | null;\n /** Messages not yet folded into observations, oldest first. */\n messages: MemoryMessage[];\n /**\n * Ready-to-send prefix in `@mastra/memory` order: system (`om-system`), continuation\n * (`om-continuation`), then `messages`. Older servers omit it; use `promptOf`.\n */\n prompt?: MemoryMessage[];\n observedAt: string | null;\n}\n\nexport interface MemoryObservationRecord {\n activeObservations: string | null;\n lastObservedAt: string | null;\n [key: string]: unknown;\n}\n\ntype SerializedMessageList = ReturnType<import('@mastra/core/agent').MessageList['serialize']>;\n\nexport type RunMemoryProcessorsInput =\n | {\n phase: 'inputStep';\n resourceId: string;\n stepNumber: number;\n messageList: SerializedMessageList;\n model?: { provider: string; modelId: string };\n }\n | { phase: 'output'; resourceId: string; messageList: SerializedMessageList; finishReason?: string };\n\nexport interface MemoryProcessorsResult {\n /** Null when a processor aborted the run. */\n messageList: SerializedMessageList | null;\n chunks: unknown[];\n rotations: number;\n aborted: string | null;\n}\n\nexport interface MemoryObservationMatch {\n text: string;\n threadId: string | null;\n observedAt: string | null;\n}\n\nexport interface MemoryThreadConfigUpdate {\n observationTokens?: number | null;\n reflectionTokens?: number | null;\n}\n\nexport interface MemoryThreadConfig {\n observationTokens: number;\n reflectionTokens: number;\n overrides: { observationTokens: number | null; reflectionTokens: number | null };\n}\n\nexport interface MemoryObservationRun {\n id: string;\n threadId: string;\n resourceId: string;\n startedAt: string;\n durationMs: number;\n observed: boolean;\n reflected: boolean;\n tokensBefore: number;\n tokensAfter: number | null;\n error: string | null;\n}\n\nconst DEFAULT_API_URL = 'https://memory-api.mastra.ai';\nconst REQUEST_TIMEOUT_MS = 30_000;\n// Processor runs execute the hosted observer/reflector (LLM calls) inside the request.\nconst PROCESSOR_TIMEOUT_MS = 5 * 60_000;\n\nfunction env(name: string): string | undefined {\n return process.env[name]?.trim() || undefined;\n}\n\nfunction required(value: string | undefined, name: string): string {\n if (!value) throw new Error(`PlatformMemory: ${name} is required`);\n return value;\n}\n\nexport function resolvePlatformMemoryOptions(options: PlatformMemoryClientOptions = {}) {\n return {\n accessToken: required(\n options.accessToken ?? env('MASTRA_PLATFORM_ACCESS_TOKEN') ?? env('MASTRA_PLATFORM_SECRET_KEY'),\n 'accessToken',\n ),\n instanceId: required(options.instanceId ?? env('MASTRA_MEMORY_INSTANCE_ID'), 'instanceId'),\n projectId: options.projectId ?? env('MASTRA_PROJECT_ID'),\n environmentId: options.environmentId ?? env('MASTRA_ENVIRONMENT_ID'),\n actingUserId: options.actingUserId,\n apiUrl: (options.apiUrl ?? env('MASTRA_MEMORY_API_URL') ?? DEFAULT_API_URL).replace(/\\/$/, ''),\n fetch: options.fetch ?? fetch,\n };\n}\n\nexport class PlatformMemoryApiError extends Error {\n constructor(\n readonly status: number,\n readonly body: string,\n ) {\n super(`Platform Memory request failed with ${status}${body ? `: ${body}` : ''}`);\n this.name = 'PlatformMemoryApiError';\n }\n}\n\ntype Query = Record<string, string | number | undefined>;\n\n/** Typed client for the Platform Memory API (`/v1/memory/:instanceId/*`). */\nexport class PlatformMemoryClient {\n readonly instanceId: string;\n private readonly opts: ReturnType<typeof resolvePlatformMemoryOptions>;\n\n constructor(options: PlatformMemoryClientOptions = {}) {\n this.opts = resolvePlatformMemoryOptions(options);\n this.instanceId = this.opts.instanceId;\n }\n\n /** MCP endpoint for this instance, for clients that speak MCP directly. */\n get mcpUrl(): string {\n return `${this.base}/mcp`;\n }\n\n listThreads(query: { resourceId?: string; page?: number; perPage?: number } = {}) {\n return this.request<{ threads: MemoryThread[]; hasMore: boolean }>('GET', '/threads', { query });\n }\n\n createThread(body: { id?: string; resourceId: string; title?: string; metadata?: Record<string, unknown> }) {\n return this.request<MemoryThread>('POST', '/threads', { body });\n }\n\n /** Returns null when the thread does not exist. */\n async getThread(threadId: string): Promise<MemoryThread | null> {\n try {\n return await this.request<MemoryThread>('GET', `/threads/${encodeURIComponent(threadId)}`);\n } catch (error) {\n if (error instanceof PlatformMemoryApiError && error.status === 404) return null;\n throw error;\n }\n }\n\n updateThread(threadId: string, body: { title?: string; metadata?: Record<string, unknown> }) {\n return this.request<MemoryThread>('PATCH', `/threads/${encodeURIComponent(threadId)}`, { body });\n }\n\n async deleteThread(threadId: string): Promise<void> {\n await this.request('DELETE', `/threads/${encodeURIComponent(threadId)}`);\n }\n\n listMessages(threadId: string, query: { page?: number; perPage?: number } = {}) {\n return this.request<{ messages: MemoryMessage[]; hasMore: boolean }>(\n 'GET',\n `/threads/${encodeURIComponent(threadId)}/messages`,\n { query },\n );\n }\n\n /** Saves messages and schedules observation in the background. Creates the thread if needed. */\n saveMessages(threadId: string, body: { resourceId: string; messages: MemoryMessageInput[] }) {\n return this.request<{ messages: MemoryMessage[] }>('POST', `/threads/${encodeURIComponent(threadId)}/messages`, {\n body,\n });\n }\n\n getContext(threadId: string, resourceId: string, opts: { workingMemory?: 'readonly' | 'tool' | 'off' } = {}) {\n return this.request<MemoryContext>('GET', `/threads/${encodeURIComponent(threadId)}/context`, {\n query: { resourceId, ...(opts.workingMemory ? { workingMemory: opts.workingMemory } : {}) },\n });\n }\n\n async getWorkingMemory(resourceId: string): Promise<string | null> {\n const res = await this.request<{ workingMemory: string | null }>('GET', '/working-memory', {\n query: { resourceId },\n });\n return res.workingMemory;\n }\n\n async updateWorkingMemory(resourceId: string, workingMemory: string): Promise<void> {\n await this.request('PUT', '/working-memory', { body: { resourceId, workingMemory } });\n }\n\n /** Omit resourceId to search the instance's most recently active threads. */\n async search(body: { resourceId?: string; threadId?: string; query: string; limit?: number }) {\n const res = await this.request<{ matches: MemoryObservationMatch[] }>('POST', '/search', { body });\n return res.matches;\n }\n\n /** Current observational-memory record for the thread, or null before the first observation. */\n async getObservations(threadId: string): Promise<MemoryObservationRecord | null> {\n const res = await this.request<{ record: MemoryObservationRecord | null }>(\n 'GET',\n `/threads/${encodeURIComponent(threadId)}/observations`,\n );\n return res.record;\n }\n\n /** Runs the instance's memory processors for one agent phase on a serialized message list. */\n runProcessors(threadId: string, body: RunMemoryProcessorsInput, signal?: AbortSignal) {\n return this.request<MemoryProcessorsResult>('POST', `/threads/${encodeURIComponent(threadId)}/processors`, {\n body,\n signal,\n timeoutMs: PROCESSOR_TIMEOUT_MS,\n });\n }\n\n async listObservationRuns(query: { threadId?: string; limit?: number } = {}) {\n const res = await this.request<{ runs: MemoryObservationRun[] }>('GET', '/runs', { query });\n return res.runs;\n }\n\n /** Effective observation thresholds for the thread and which ones it overrides. */\n getThreadConfig(threadId: string) {\n return this.request<MemoryThreadConfig>('GET', `/threads/${encodeURIComponent(threadId)}/config`);\n }\n\n /** Overrides thresholds for one thread. Pass `null` to fall back to the instance value. */\n updateThreadConfig(threadId: string, config: MemoryThreadConfigUpdate) {\n return this.request<MemoryThreadConfig>('PATCH', `/threads/${encodeURIComponent(threadId)}/config`, {\n body: config,\n });\n }\n\n /** Copies a thread, its messages, and its observations. */\n cloneThread(\n threadId: string,\n body: { newThreadId?: string; title?: string; metadata?: Record<string, unknown>; messageLimit?: number } = {},\n ) {\n return this.request<{ thread: MemoryThread; clonedMessageCount: number }>(\n 'POST',\n `/threads/${encodeURIComponent(threadId)}/clone`,\n { body },\n );\n }\n\n /** Deletes messages from a thread. Ids that belong to other threads are ignored. */\n async deleteMessages(threadId: string, messageIds: string[]): Promise<number> {\n const res = await this.request<{ deleted: number }>(\n 'POST',\n `/threads/${encodeURIComponent(threadId)}/messages/delete`,\n { body: { messageIds } },\n );\n return res.deleted;\n }\n\n /** Everything stored for one resource (user): working memory and threads. */\n getResource(resourceId: string, query: { page?: number; perPage?: number } = {}) {\n return this.request<{\n resourceId: string;\n workingMemory: string | null;\n threads: MemoryThread[];\n totalThreads: number;\n hasMore: boolean;\n }>('GET', `/resources/${encodeURIComponent(resourceId)}`, { query });\n }\n\n /** Resources (users) in the instance, most recently active first. */\n listResources(query: { page?: number; perPage?: number } = {}) {\n return this.request<{\n resources: { resourceId: string; threadCount: number; lastActiveAt: string }[];\n hasMore: boolean;\n }>('GET', '/resources', { query });\n }\n\n /** Deletes every thread, message, observation and the working memory for a resource. */\n async deleteResource(resourceId: string): Promise<number> {\n const res = await this.request<{ deletedThreads: number }>(\n 'DELETE',\n `/resources/${encodeURIComponent(resourceId)}`,\n );\n return res.deletedThreads;\n }\n\n private get base(): string {\n return `${this.opts.apiUrl}/v1/memory/${encodeURIComponent(this.opts.instanceId)}`;\n }\n\n private async request<T>(\n method: string,\n path: string,\n init: { query?: Query; body?: unknown; signal?: AbortSignal; timeoutMs?: number } = {},\n ): Promise<T> {\n const url = new URL(this.base + path);\n for (const [key, value] of Object.entries(init.query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value));\n }\n const headers: Record<string, string> = { authorization: `Bearer ${this.opts.accessToken}` };\n if (this.opts.actingUserId) headers['x-acting-user-id'] = this.opts.actingUserId;\n if (this.opts.projectId) headers['x-mastra-project-id'] = this.opts.projectId;\n if (this.opts.environmentId) headers['x-mastra-environment-id'] = this.opts.environmentId;\n if (init.body !== undefined) headers['content-type'] = 'application/json';\n\n const deadline = AbortSignal.timeout(init.timeoutMs ?? REQUEST_TIMEOUT_MS);\n const res = await this.opts.fetch(url, {\n method,\n headers,\n body: init.body === undefined ? undefined : JSON.stringify(init.body),\n signal: init.signal ? AbortSignal.any([init.signal, deadline]) : deadline,\n });\n if (!res.ok) throw new PlatformMemoryApiError(res.status, await res.text().catch(() => ''));\n if (res.status === 204) return undefined as T;\n return (await res.json()) as T;\n }\n}\n","import type { MastraDBMessage } from '@mastra/core/agent';\nimport { MastraMemory, parseMemoryRequestContext } from '@mastra/core/memory';\nimport type { MemoryConfig, MemoryConfigInternal, StorageThreadType, WorkingMemoryTemplate } from '@mastra/core/memory';\nimport type {\n InputProcessor,\n OutputProcessor,\n ProcessInputArgs,\n ProcessInputStepArgs,\n ProcessOutputResultArgs,\n} from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type {\n StorageCloneThreadInput,\n StorageCloneThreadOutput,\n StorageListMessagesInput,\n StorageListThreadsInput,\n StorageListThreadsOutput,\n} from '@mastra/core/storage';\nimport { createTool } from '@mastra/core/tools';\nimport type { ToolAction } from '@mastra/core/tools';\n\nimport { z } from 'zod';\n\nimport { PlatformMemoryClient } from './client';\nimport type {\n MemoryMessage,\n MemoryMessageInput,\n MemoryProcessorsResult,\n MemoryThread,\n PlatformMemoryClientOptions,\n} from './client';\n\nexport type PlatformMemoryOptions = PlatformMemoryClientOptions & {\n id?: string;\n /** Use a preconfigured client instead of building one from the options above. */\n client?: PlatformMemoryClient;\n /**\n * How working memory is shown to the model. Defaults to `readonly`: the resource's stored\n * working memory is added to each run's prompt. `tool` also gives the agent an\n * `updateWorkingMemory` tool (not in read-only runs); `off` leaves working memory out.\n */\n workingMemory?: 'readonly' | 'tool' | 'off';\n};\n\ntype MessageListLike = ProcessInputArgs['messageList'];\n\nfunction threadFromApi(thread: MemoryThread): StorageThreadType {\n return {\n id: thread.id,\n resourceId: thread.resourceId,\n title: thread.title ?? undefined,\n metadata: thread.metadata ?? undefined,\n createdAt: new Date(thread.createdAt),\n updatedAt: new Date(thread.updatedAt),\n };\n}\n\nfunction messageFromApi(message: MemoryMessage, threadId: string, resourceId?: string): MastraDBMessage {\n return {\n id: message.id,\n role: message.role === 'assistant' ? 'assistant' : 'user',\n createdAt: new Date(message.createdAt),\n threadId,\n resourceId,\n content: {\n format: 2,\n parts: (message.parts?.length\n ? message.parts\n : [{ type: 'text', text: message.content }]) as MastraDBMessage['content']['parts'],\n },\n };\n}\n\nfunction textOf(message: MastraDBMessage): string {\n const parts = message.content.parts ?? [];\n const text = parts\n .filter((part): part is { type: 'text'; text: string } => part.type === 'text')\n .map(part => part.text)\n .join('\\n');\n return text || message.content.content || '';\n}\n\n/** User/assistant messages with all their parts (tool calls, reasoning, files). System messages are skipped. */\nfunction toApiMessages(messages: MastraDBMessage[]): MemoryMessageInput[] {\n return messages.flatMap((message): MemoryMessageInput[] => {\n if (message.role !== 'user' && message.role !== 'assistant') return [];\n const parts = message.content.parts ?? [];\n const createdAt = new Date(message.createdAt).toISOString();\n const content = textOf(message) || undefined;\n if (!parts.length && !content) return [];\n return [{ id: message.id, role: message.role, content, parts: parts.length ? parts : undefined, createdAt }];\n });\n}\n\nfunction memoryContext(requestContext: RequestContext | undefined, messageList: MessageListLike) {\n const ctx = parseMemoryRequestContext(requestContext);\n if (ctx?.thread?.id) {\n return {\n threadId: ctx.thread.id,\n resourceId: ctx.resourceId ?? ctx.thread.id,\n readOnly: ctx.memoryConfig?.readOnly,\n };\n }\n const info = messageList.serialize().memoryInfo;\n if (info?.threadId) return { threadId: info.threadId, resourceId: info.resourceId ?? info.threadId, readOnly: false };\n return null;\n}\n\nconst WORKING_MEMORY_TAG = 'platform-working-memory';\n\n/**\n * Adds the resource's stored working memory as a system message. The hosted processors don't\n * deliver it, so the client reads it on the first step of every run: a fresh read each run, so an\n * update between runs shows up on the next one.\n */\nasync function addWorkingMemory(\n client: PlatformMemoryClient,\n messageList: MessageListLike,\n resourceId: string,\n canUpdate: boolean,\n) {\n const data = await client.getWorkingMemory(resourceId);\n messageList.clearSystemMessages(WORKING_MEMORY_TAG);\n if (canUpdate) {\n messageList.addSystem(\n `WORKING_MEMORY_SYSTEM_INSTRUCTION:\nStore 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.\n\n<working_memory_data>\n${data ?? ''}\n</working_memory_data>`,\n WORKING_MEMORY_TAG,\n );\n } else if (data) {\n messageList.addSystem(\n `WORKING_MEMORY_SYSTEM_INSTRUCTION (READ-ONLY):\nThe following is what is remembered about the user. Use it for context; you cannot change it.\n\n<working_memory_data>\n${data}\n</working_memory_data>`,\n WORKING_MEMORY_TAG,\n );\n }\n}\n\n/**\n * What a read-only run sees of the thread, read through the context route, which writes nothing:\n * observations, the continuation reminder, then the messages not yet observed. Running the hosted\n * processors instead would save messages and start observation.\n */\nasync function addReadOnlyContext(\n client: PlatformMemoryClient,\n messageList: MessageListLike,\n threadId: string,\n resourceId: string,\n) {\n const context = await client.getContext(threadId, resourceId, { workingMemory: 'off' });\n const prompt = context.prompt ?? [\n ...(context.system\n ? [{ id: 'om-system', role: 'system', content: context.system, parts: [], createdAt: new Date(0).toISOString() }]\n : []),\n ...(context.continuation\n ? [\n {\n id: 'om-continuation',\n role: 'user',\n content: context.continuation,\n parts: [],\n createdAt: new Date(0).toISOString(),\n },\n ]\n : []),\n ...context.messages,\n ];\n for (const message of prompt) {\n if (message.role === 'system') messageList.addSystem(message.content, 'memory');\n else messageList.add(messageFromApi(message, threadId, resourceId), 'memory');\n }\n}\n\nasync function applyResult(\n result: MemoryProcessorsResult,\n agent: Pick<ProcessInputStepArgs, 'messageList' | 'writer' | 'abort' | 'rotateResponseMessageId'>,\n) {\n for (const chunk of result.chunks) await agent.writer?.custom(chunk as never);\n for (let i = 0; i < result.rotations; i++) agent.rotateResponseMessageId?.();\n if (result.aborted !== null || !result.messageList) return agent.abort(result.aborted ?? undefined);\n return agent.messageList.deserialize(result.messageList);\n}\n\n/**\n * Mastra memory backed by a hosted Platform Memory instance.\n *\n * Observation and reflection run on the Platform: on each input step and on the final output this\n * class sends the serialized message list to the instance's memory processors and applies the\n * result. Messages are stored with all their parts (text, tool calls, reasoning, files).\n */\nexport class PlatformMemory extends MastraMemory {\n readonly client: PlatformMemoryClient;\n private readonly workingMemoryMode: 'readonly' | 'tool' | 'off';\n\n constructor(options: PlatformMemoryOptions = {}) {\n super({ id: options.id ?? 'platform-memory', name: 'PlatformMemory' });\n this.client = options.client ?? new PlatformMemoryClient(options);\n this.workingMemoryMode = options.workingMemory ?? 'readonly';\n }\n\n listTools(config?: MemoryConfig): Record<string, ToolAction<any, any, any, any, any>> {\n if (this.workingMemoryMode !== 'tool' || config?.readOnly) return {};\n this.assertResourceScopedWorkingMemory(config);\n const client = this.client;\n return {\n updateWorkingMemory: createTool({\n id: 'update-working-memory',\n description:\n '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.',\n inputSchema: z.object({\n memory: z.string().describe('The Markdown formatted working memory content to store.'),\n }),\n execute: async ({ memory }, context) => {\n const resourceId = context?.agent?.resourceId ?? context?.agent?.threadId;\n if (!resourceId) throw new Error('updateWorkingMemory needs a thread or resource');\n await client.updateWorkingMemory(resourceId, memory);\n return { success: true };\n },\n }),\n };\n }\n\n // The instance runs the real @mastra/memory processors; these only ship the message list\n // there and apply what comes back (list, stream parts, message-id rotations, abort).\n async getInputProcessors(): Promise<InputProcessor[]> {\n const client = this.client;\n const workingMemoryMode = this.workingMemoryMode;\n return [\n {\n id: 'platform-memory',\n name: 'Platform Memory',\n async processInputStep({\n messageList,\n requestContext,\n stepNumber,\n model,\n writer,\n abort,\n abortSignal,\n rotateResponseMessageId,\n }: ProcessInputStepArgs) {\n const ctx = memoryContext(requestContext, messageList);\n if (!ctx) return messageList;\n if (ctx.readOnly) {\n if (stepNumber === 0) {\n await addReadOnlyContext(client, messageList, ctx.threadId, ctx.resourceId);\n if (workingMemoryMode !== 'off') await addWorkingMemory(client, messageList, ctx.resourceId, false);\n }\n return messageList;\n }\n const result = await client.runProcessors(\n ctx.threadId,\n {\n phase: 'inputStep',\n resourceId: ctx.resourceId,\n stepNumber,\n messageList: messageList.serialize(),\n model: model ? { provider: model.provider, modelId: model.modelId } : undefined,\n },\n abortSignal,\n );\n const list = await applyResult(result, { messageList, writer, abort, rotateResponseMessageId });\n if (stepNumber === 0 && workingMemoryMode !== 'off') {\n await addWorkingMemory(client, messageList, ctx.resourceId, workingMemoryMode === 'tool');\n }\n return list;\n },\n },\n ];\n }\n\n async getOutputProcessors(): Promise<OutputProcessor[]> {\n const client = this.client;\n return [\n {\n id: 'platform-memory',\n name: 'Platform Memory',\n async processOutputResult({ messageList, requestContext, result, writer, abort }: ProcessOutputResultArgs) {\n const ctx = memoryContext(requestContext, messageList);\n if (!ctx || ctx.readOnly) return messageList;\n // No abortSignal here: this call saves the turn's messages, and aborting mid-save can lose them.\n const res = await client.runProcessors(ctx.threadId, {\n phase: 'output',\n resourceId: ctx.resourceId,\n messageList: messageList.serialize(),\n finishReason: result?.finishReason,\n });\n return applyResult(res, { messageList, writer, abort });\n },\n },\n ];\n }\n\n async getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null> {\n const thread = await this.client.getThread(threadId);\n return thread ? threadFromApi(thread) : null;\n }\n\n async listThreads(args: StorageListThreadsInput): Promise<StorageListThreadsOutput> {\n const page = args.page ?? 0;\n const perPage = args.perPage === false ? 200 : (args.perPage ?? 100);\n const threads: StorageThreadType[] = [];\n for (let next = 0; ; next++) {\n const res = await this.client.listThreads({ resourceId: args.filter?.resourceId, page: next, perPage: 200 });\n threads.push(...res.threads.map(threadFromApi));\n if (!res.hasMore) break;\n }\n const filtered = threads.filter(thread =>\n Object.entries(args.filter?.metadata ?? {}).every(([key, value]) => thread.metadata?.[key] === value),\n );\n const field = args.orderBy?.field ?? 'updatedAt';\n const direction = args.orderBy?.direction === 'ASC' ? 1 : -1;\n filtered.sort((a, b) => direction * (a[field].getTime() - b[field].getTime()));\n const selected = args.perPage === false ? filtered : filtered.slice(page * perPage, (page + 1) * perPage);\n return {\n threads: selected,\n hasMore: args.perPage === false ? false : (page + 1) * perPage < filtered.length,\n page,\n perPage: args.perPage === false ? (false as const) : perPage,\n total: filtered.length,\n };\n }\n\n async saveThread({ thread }: { thread: StorageThreadType }): Promise<StorageThreadType> {\n const existing = await this.client.getThread(thread.id);\n const saved = existing\n ? await this.client.updateThread(thread.id, { title: thread.title, metadata: thread.metadata })\n : await this.client.createThread({\n id: thread.id,\n resourceId: thread.resourceId,\n title: thread.title,\n metadata: thread.metadata,\n });\n return threadFromApi(saved);\n }\n\n async updateThread({\n id,\n title,\n metadata,\n }: {\n id: string;\n title?: string;\n metadata?: Record<string, unknown>;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<StorageThreadType> {\n return threadFromApi(await this.client.updateThread(id, { title, metadata }));\n }\n\n async deleteThread(threadId: string): Promise<void> {\n await this.client.deleteThread(threadId);\n }\n\n async saveMessages(args: {\n messages: MastraDBMessage[];\n memoryConfig?: MemoryConfig;\n }): Promise<{ messages: MastraDBMessage[] }> {\n const byThread = new Map<string, MastraDBMessage[]>();\n for (const message of args.messages) {\n if (!message.threadId) continue;\n byThread.set(message.threadId, [...(byThread.get(message.threadId) ?? []), message]);\n }\n for (const [threadId, messages] of byThread) {\n const apiMessages = toApiMessages(messages);\n if (!apiMessages.length) continue;\n const resourceId = messages[0]!.resourceId ?? threadId;\n await this.client.saveMessages(threadId, { resourceId, messages: apiMessages });\n }\n return { messages: args.messages };\n }\n\n async recall(args: StorageListMessagesInput) {\n const threadIds = Array.isArray(args.threadId) ? args.threadId : [args.threadId];\n if (!threadIds.length || threadIds.some(id => !id)) throw new Error('PlatformMemory.recall requires a threadId');\n if (Object.keys(args.filter?.metadata ?? {}).length || args.include?.length) {\n throw new Error('PlatformMemory.recall does not support metadata filters or include windows');\n }\n const page = args.page ?? 0;\n const perPage = args.perPage === false ? 200 : (args.perPage ?? 40);\n const messages: MastraDBMessage[] = [];\n for (const threadId of threadIds) {\n const thread = await this.client.getThread(threadId);\n if (!thread || (args.resourceId && thread.resourceId !== args.resourceId)) continue;\n const resourceId = thread.resourceId;\n for (let next = 0; ; next++) {\n const res = await this.client.listMessages(threadId, { page: next, perPage: 200 });\n messages.push(...res.messages.map(message => messageFromApi(message, threadId, resourceId)));\n if (!res.hasMore) break;\n }\n }\n const { start, end, startExclusive, endExclusive } = args.filter?.dateRange ?? {};\n const filtered = messages.filter(message => {\n const timestamp = message.createdAt.getTime();\n return (\n (!start || (startExclusive ? timestamp > start.getTime() : timestamp >= start.getTime())) &&\n (!end || (endExclusive ? timestamp < end.getTime() : timestamp <= end.getTime()))\n );\n });\n const direction = args.orderBy?.direction === 'DESC' ? -1 : 1;\n filtered.sort((a, b) => direction * (a.createdAt.getTime() - b.createdAt.getTime()));\n const selected = args.perPage === false ? filtered : filtered.slice(page * perPage, (page + 1) * perPage);\n return {\n messages: selected,\n total: filtered.length,\n page,\n perPage: args.perPage === false ? (false as const) : perPage,\n hasMore: args.perPage === false ? false : (page + 1) * perPage < filtered.length,\n };\n }\n\n // Hosted working memory is keyed by resource only, so thread scope would silently be shared\n // across every thread of the same resource.\n private assertResourceScopedWorkingMemory(config?: MemoryConfig | MemoryConfigInternal): void {\n if (this.getMergedThreadConfig(config ?? {}).workingMemory?.scope === 'thread') {\n throw new Error('PlatformMemory does not support thread-scoped working memory');\n }\n }\n\n async getWorkingMemory({\n threadId,\n resourceId,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<string | null> {\n this.assertResourceScopedWorkingMemory(memoryConfig);\n return this.client.getWorkingMemory(resourceId ?? threadId);\n }\n\n async getWorkingMemoryTemplate(): Promise<WorkingMemoryTemplate | null> {\n return null;\n }\n\n async updateWorkingMemory({\n threadId,\n resourceId,\n workingMemory,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<void> {\n this.assertResourceScopedWorkingMemory(memoryConfig);\n await this.client.updateWorkingMemory(resourceId ?? threadId, workingMemory);\n }\n\n async __experimental_updateWorkingMemoryVNext(args: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<{ success: boolean; reason: string }> {\n await this.updateWorkingMemory(args);\n return { success: true, reason: 'replaced' };\n }\n\n async deleteMessages(): Promise<void> {\n throw new Error('PlatformMemory does not support deleting individual messages yet');\n }\n\n async cloneThread(_args: StorageCloneThreadInput): Promise<StorageCloneThreadOutput> {\n throw new Error('PlatformMemory does not support cloning threads yet');\n }\n}\n","import { StagehandBrowser } from '@mastra/stagehand';\nimport type { StagehandBrowserConfig } from '@mastra/stagehand';\n\nexport interface PlatformBrowserOptions extends Omit<\n StagehandBrowserConfig,\n 'cdpUrl' | 'scope' | 'env' | 'apiKey' | 'projectId'\n> {\n /** Existing Platform-provisioned CDP URL. When supplied, no API request or access token is needed. */\n cdpUrl?: string;\n /** Platform access token. Falls back to `MASTRA_PLATFORM_ACCESS_TOKEN`, then `MASTRA_PLATFORM_SECRET_KEY`. */\n accessToken?: string;\n /** Mastra Platform project ID. Falls back to `MASTRA_PROJECT_ID`. */\n projectId?: string;\n /** Browser provisioning API URL. Falls back to `MASTRA_BROWSER_API_URL`. */\n apiUrl?: string;\n fetch?: typeof fetch;\n}\n\nconst DEFAULT_API_URL = 'https://platform.mastra.ai';\n\nfunction trimTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === '/') end--;\n return url.slice(0, end);\n}\n\n/** A Stagehand browser connected to a Platform-provisioned Browserbase session. */\nexport class PlatformBrowser extends StagehandBrowser {\n constructor(options: PlatformBrowserOptions = {}) {\n const {\n cdpUrl,\n accessToken = process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY,\n projectId = process.env.MASTRA_PROJECT_ID,\n apiUrl = process.env.MASTRA_BROWSER_API_URL ?? DEFAULT_API_URL,\n fetch: fetchImpl = fetch,\n ...stagehandOptions\n } = options;\n if (!cdpUrl && !accessToken) throw new Error('PlatformBrowser: accessToken is required');\n if (!cdpUrl && !projectId) throw new Error('PlatformBrowser: projectId is required');\n\n super({\n ...stagehandOptions,\n scope: 'shared',\n cdpUrl:\n cdpUrl ||\n (async () => {\n const response = await fetchImpl(`${trimTrailingSlashes(apiUrl)}/v1/browsers/sessions`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({ projectId }),\n signal: AbortSignal.timeout(30_000),\n });\n if (!response.ok) throw new Error(`PlatformBrowser: browser provisioning failed (${response.status})`);\n const result: unknown = await response.json();\n if (\n !result ||\n typeof result !== 'object' ||\n !('connectUrl' in result) ||\n typeof result.connectUrl !== 'string'\n ) {\n throw new Error('PlatformBrowser: browser provisioning returned no connectUrl');\n }\n return result.connectUrl;\n }),\n });\n }\n}\n","import { Knowledge } from '@mastra/core/knowledge';\nimport type { KnowledgeConfig, KnowledgeScopeDeclarations } from '@mastra/core/knowledge';\nimport {\n MastraCompositeStore,\n KnowledgeStorage,\n KnowledgeConflictError,\n KnowledgeNotFoundError,\n KnowledgePageHasChildrenError,\n KnowledgePageKeyConflictError,\n} from '@mastra/core/storage';\nimport type { KnowledgePageStore } from '@mastra/core/storage';\n\nexport interface PlatformKnowledgeOptions extends Omit<\n KnowledgeConfig,\n 'storage' | 'vector' | 'embedder' | 'embedderOptions' | 'scopes'\n> {\n accessToken?: string;\n projectId?: string;\n instanceId?: string;\n /**\n * Knowledge API URL. Falls back to `MASTRA_KNOWLEDGE_API_URL`, then `https://knowledge-api.mastra.ai`.\n */\n apiUrl?: string;\n}\n\n// These are the schema-v4 page-store methods, not arbitrary object properties or storage lifecycle methods.\n// `renameScopeDeclaration` is left to the base class, which rejects it: its `check` callback can't be\n// serialized, so the hosted store couldn't validate affected scopes before re-keying them.\nconst operations = [\n 'materializeScope',\n 'getScopesByAddress',\n 'listScopeDeclarations',\n 'listChildScopes',\n 'countChildScopes',\n 'getPage',\n 'getPages',\n 'getPageByPath',\n 'findPagesByName',\n 'listChildPages',\n 'countChildPages',\n 'listPages',\n 'createPage',\n 'updatePage',\n 'movePage',\n 'mergePages',\n 'deletePage',\n 'getNote',\n 'countNotes',\n 'listNotes',\n 'listNotesMentioning',\n 'addNote',\n 'restampNote',\n 'removeNote',\n 'restoreNote',\n 'searchPages',\n 'listPageActivity',\n 'addPinAudience',\n 'removePinAudience',\n 'listPins',\n 'countPageLinks',\n 'listPageLinks',\n 'replacePageBodyLinks',\n 'listPageBodyLinkSources',\n] as const satisfies readonly (keyof KnowledgePageStore)[];\n\n// Fails to compile when a page-store method is neither forwarded nor deliberately left to the base class.\ntype UnforwardedOperation = Exclude<keyof KnowledgePageStore, (typeof operations)[number]>;\nconst operationsAreExhaustive: [UnforwardedOperation] extends ['renameScopeDeclaration']\n ? ['renameScopeDeclaration'] extends [UnforwardedOperation]\n ? true\n : never\n : never = true;\nvoid operationsAreExhaustive;\n\nfunction encode(value: unknown): string {\n return JSON.stringify(value, function (key, item: unknown) {\n const original: unknown = key ? (this as Record<string, unknown>)[key] : item;\n return original instanceof Date ? { __knowledgeDate: original.toISOString() } : item;\n });\n}\n\nfunction decode<T>(text: string): T {\n return JSON.parse(text, (_key, value: unknown) => {\n if (value && typeof value === 'object' && '__knowledgeDate' in value) {\n return new Date((value as { __knowledgeDate: string }).__knowledgeDate);\n }\n return value;\n }) as T;\n}\n\nclass RemoteKnowledgeStorage extends KnowledgeStorage {\n constructor(\n private readonly endpoint: string,\n private readonly token: string,\n ) {\n super({ storageIsolationKey: endpoint });\n return new Proxy(this, {\n get(target, key) {\n if (typeof key === 'string' && operations.includes(key as (typeof operations)[number])) {\n return (input?: unknown) => target.request(key, input);\n }\n const value: unknown = Reflect.get(target, key, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n }\n\n private async request(operation: string, input?: unknown): Promise<unknown> {\n const response = await fetch(`${this.endpoint}/operations/${operation}`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${this.token}`,\n 'content-type': 'application/json',\n // This client merges the instance's scope declarations (`getScopeDeclarations`) into its own, so\n // the service leaves its read views as they are rather than widening them for older clients.\n 'x-mastra-knowledge-store-declarations': 'merged',\n },\n body: encode({ input }),\n signal: AbortSignal.timeout(30_000),\n });\n const text = await response.text();\n if (!response.ok) {\n let body: { name?: string; detail?: string; title?: string; error?: { name?: string; message?: string } } = {};\n try {\n const parsed: unknown = JSON.parse(text);\n if (parsed && typeof parsed === 'object') body = parsed;\n } catch {\n // Gateways can return non-JSON error pages.\n }\n const message =\n body.detail ||\n body.error?.message ||\n body.title ||\n (text\n ? `Knowledge request failed (${response.status}): ${text}`\n : `Knowledge request failed (${response.status})`);\n const name = body.name ?? body.error?.name;\n if (name === 'KnowledgeNotFoundError') {\n const error = new KnowledgeNotFoundError('record', operation);\n error.message = message;\n throw error;\n }\n if (name === 'KnowledgeConflictError') {\n const error = new KnowledgeConflictError(operation);\n error.message = message;\n throw error;\n }\n if (name === 'KnowledgePageKeyConflictError') {\n const error = new KnowledgePageKeyConflictError('', '');\n error.message = message;\n throw error;\n }\n if (name === 'KnowledgePageHasChildrenError') {\n const error = new KnowledgePageHasChildrenError('');\n error.message = message;\n throw error;\n }\n throw Object.assign(new Error(message), { status: response.status });\n }\n return decode<{ result?: unknown }>(text).result;\n }\n\n /**\n * The scope declarations the instance supplies, such as the ones its importers write to, with their\n * access rules. A service that doesn't have the operation yet answers 404 \"Knowledge operation not\n * found\" and supplies none. Any other failure, including another 404 (a missing instance, a wrong\n * URL), and anything but a declaration record is a broken response, not \"none\".\n */\n override async getScopeDeclarations(): Promise<KnowledgeScopeDeclarations> {\n let result: unknown;\n try {\n result = await this.request('getScopeDeclarations');\n } catch (error) {\n const status = (error as { status?: unknown }).status;\n if (status === 404 && (error as Error).message === 'Knowledge operation not found') return {};\n throw error;\n }\n if (!result || typeof result !== 'object' || Array.isArray(result)) {\n throw new Error('Knowledge service answered getScopeDeclarations without a declaration record');\n }\n return result as KnowledgeScopeDeclarations;\n }\n\n override getCapabilities() {\n return {\n contractVersion: 4,\n schemaVersion: 4,\n supportsSchemaInspection: false,\n supportsExplicitReset: false,\n // The service's stores keep a pin's kind and depth, so listing pins round-trip.\n supportsPinKinds: true,\n } as const;\n }\n\n override async dangerouslyClearAll(): Promise<void> {\n throw new Error('Hosted Knowledge cannot be cleared from the client');\n }\n}\n\nconst DEFAULT_API_URL = 'https://knowledge-api.mastra.ai';\n\nexport class PlatformKnowledge extends Knowledge {\n constructor(options: PlatformKnowledgeOptions = {}) {\n const token =\n options.accessToken ?? process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY;\n const instanceId = options.instanceId ?? process.env.MASTRA_KNOWLEDGE_INSTANCE_ID;\n const apiUrl = options.apiUrl ?? (process.env.MASTRA_KNOWLEDGE_API_URL?.trim() || undefined) ?? DEFAULT_API_URL;\n if (!token || !instanceId) {\n throw new Error('PlatformKnowledge requires a Platform access token and Knowledge instance ID');\n }\n const {\n accessToken: _accessToken,\n projectId: _projectId,\n instanceId: _instanceId,\n apiUrl: _apiUrl,\n ...config\n } = options;\n const endpoint = `${apiUrl.replace(/\\/$/, '')}/v1/knowledge/${encodeURIComponent(instanceId)}`;\n const storage = new MastraCompositeStore({\n id: `platform-knowledge-${instanceId}`,\n domains: { knowledge: new RemoteKnowledgeStorage(endpoint, token) },\n });\n super({\n ...config,\n tools: config.tools ?? { read: true },\n // Platform owns every scope declaration and access grant: the instance serves them all through\n // `getScopeDeclarations`, so there is one place to change who reads what. Declaring scopes here\n // too would conflict with the instance's (a key both declare silently takes the code's rules,\n // and overlapping patterns break every call), so PlatformKnowledge takes no `scopes` option.\n scopes: {},\n storage,\n });\n }\n}\n\nexport { encode as encodeKnowledgeTransport, decode as decodeKnowledgeTransport };\nexport { operations as knowledgeOperations };\n"],"mappings":";;;;;;;;AA0HA,MAAMA,oBAAkB;AACxB,MAAM,qBAAqB;AAE3B,MAAM,uBAAuB;AAE7B,SAAS,IAAI,MAAkC;CAC7C,OAAO,QAAQ,IAAI,KAAK,EAAE,KAAK,KAAK,KAAA;AACtC;AAEA,SAAS,SAAS,OAA2B,MAAsB;CACjE,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,mBAAmB,KAAK,aAAa;CACjE,OAAO;AACT;AAEA,SAAgB,6BAA6B,UAAuC,CAAC,GAAG;CACtF,OAAO;EACL,aAAa,SACX,QAAQ,eAAe,IAAI,8BAA8B,KAAK,IAAI,4BAA4B,GAC9F,aACF;EACA,YAAY,SAAS,QAAQ,cAAc,IAAI,2BAA2B,GAAG,YAAY;EACzF,WAAW,QAAQ,aAAa,IAAI,mBAAmB;EACvD,eAAe,QAAQ,iBAAiB,IAAI,uBAAuB;EACnE,cAAc,QAAQ;EACtB,SAAS,QAAQ,UAAU,IAAI,uBAAuB,KAAKA,kBAAAA,CAAiB,QAAQ,OAAO,EAAE;EAC7F,OAAO,QAAQ,SAAS;CAC1B;AACF;AAEA,IAAa,yBAAb,cAA4C,MAAM;CAErC;CACA;CAFX,YACE,QACA,MACA;EACA,MAAM,uCAAuC,SAAS,OAAO,KAAK,SAAS,IAAI;EAHtE,KAAA,SAAA;EACA,KAAA,OAAA;EAGT,KAAK,OAAO;CACd;AACF;;AAKA,IAAa,uBAAb,MAAkC;CAChC;CACA;CAEA,YAAY,UAAuC,CAAC,GAAG;EACrD,KAAK,OAAO,6BAA6B,OAAO;EAChD,KAAK,aAAa,KAAK,KAAK;CAC9B;;CAGA,IAAI,SAAiB;EACnB,OAAO,GAAG,KAAK,KAAK;CACtB;CAEA,YAAY,QAAkE,CAA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AAW,YAAY,MAAM,QAAQ,MAAM,GAC/D,MAAM,IAAI,MAAM,8EAA8E;EAEhG,OAAO;CACT;CAEA,kBAA2B;EACzB,OAAO;GACL,iBAAiB;GACjB,eAAe;GACf,0BAA0B;GAC1B,uBAAuB;GAEvB,kBAAkB;EACpB;CACF;CAEA,MAAe,sBAAqC;EAClD,MAAM,IAAI,MAAM,oDAAoD;CACtE;AACF;AAEA,MAAM,kBAAkB;AAExB,IAAa,oBAAb,cAAuC,UAAU;CAC/C,YAAY,UAAoC,CAAC,GAAG;EAClD,MAAM,QACJ,QAAQ,eAAe,QAAQ,IAAI,gCAAgC,QAAQ,IAAI;EACjF,MAAM,aAAa,QAAQ,cAAc,QAAQ,IAAI;EACrD,MAAM,SAAS,QAAQ,WAAW,QAAQ,IAAI,0BAA0B,KAAK,KAAK,KAAA,MAAc;EAChG,IAAI,CAAC,SAAS,CAAC,YACb,MAAM,IAAI,MAAM,8EAA8E;EAEhG,MAAM,EACJ,aAAa,cACb,WAAW,YACX,YAAY,aACZ,QAAQ,SACR,GAAG,WACD;EACJ,MAAM,WAAW,GAAG,OAAO,QAAQ,OAAO,EAAE,EAAE,gBAAgB,mBAAmB,UAAU;EAC3F,MAAM,UAAU,IAAI,qBAAqB;GACvC,IAAI,sBAAsB;GAC1B,SAAS,EAAE,WAAW,IAAI,uBAAuB,UAAU,KAAK,EAAE;EACpE,CAAC;EACD,MAAM;GACJ,GAAG;GACH,OAAO,OAAO,SAAS,EAAE,MAAM,KAAK;GAKpC,QAAQ,CAAC;GACT;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["DEFAULT_API_URL","DEFAULT_API_URL"],"sources":["../src/memory/client.ts","../src/memory/platform-memory.ts","../src/browser/index.ts","../src/knowledge/index.ts"],"sourcesContent":["export interface PlatformMemoryClientOptions {\n /** Platform access token. Falls back to `MASTRA_PLATFORM_ACCESS_TOKEN`, then `MASTRA_PLATFORM_SECRET_KEY`. */\n accessToken?: string;\n /** Memory instance id. Falls back to `MASTRA_MEMORY_INSTANCE_ID`. */\n instanceId?: string;\n /** Falls back to `MASTRA_PROJECT_ID`. Sent as a hint; ownership is enforced server-side from the token. */\n projectId?: string;\n /** Falls back to `MASTRA_ENVIRONMENT_ID`. */\n environmentId?: string;\n /** Sent as `x-acting-user-id`, used by the API when the token is not tied to a user. */\n actingUserId?: string;\n /**\n * Memory API URL. Falls back to `MASTRA_MEMORY_API_URL`, then `https://memory-api.mastra.ai`.\n */\n apiUrl?: string;\n fetch?: typeof fetch;\n}\n\nexport interface MemoryThread {\n id: string;\n resourceId: string;\n title: string | null;\n metadata: Record<string, unknown> | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport type MemoryMessagePart = { type: string; [key: string]: unknown };\n\nexport interface MemoryMessage {\n id: string;\n role: string;\n content: string;\n /** Mastra V2 parts (text, tool-invocation, reasoning, file, …), stored verbatim. */\n parts: MemoryMessagePart[];\n createdAt: string;\n}\n\nexport interface MemoryMessageInput {\n id?: string;\n role: 'user' | 'assistant';\n /** Text content. Optional when `parts` is set. */\n content?: string;\n parts?: MemoryMessagePart[];\n createdAt?: string;\n}\n\nexport interface MemoryContext {\n /** Rendered observations, ready to use as a system message. */\n system: string | null;\n /**\n * User-role reminder that goes before `messages` once observations exist, so the model\n * continues the conversation instead of treating the observations as a new prompt.\n * Older servers omit it.\n */\n continuation?: string | null;\n /** Messages not yet folded into observations, oldest first. */\n messages: MemoryMessage[];\n /**\n * Ready-to-send prefix in `@mastra/memory` order: system (`om-system`), continuation\n * (`om-continuation`), then `messages`. Older servers omit it; use `promptOf`.\n */\n prompt?: MemoryMessage[];\n observedAt: string | null;\n}\n\nexport interface MemoryObservationRecord {\n activeObservations: string | null;\n lastObservedAt: string | null;\n [key: string]: unknown;\n}\n\ntype SerializedMessageList = ReturnType<import('@mastra/core/agent').MessageList['serialize']>;\n\nexport type RunMemoryProcessorsInput =\n | {\n phase: 'inputStep';\n resourceId: string;\n stepNumber: number;\n messageList: SerializedMessageList;\n model?: { provider: string; modelId: string };\n }\n | { phase: 'output'; resourceId: string; messageList: SerializedMessageList; finishReason?: string };\n\nexport interface MemoryProcessorsResult {\n /** Null when a processor aborted the run. */\n messageList: SerializedMessageList | null;\n chunks: unknown[];\n rotations: number;\n aborted: string | null;\n}\n\nexport interface MemoryObservationMatch {\n text: string;\n threadId: string | null;\n observedAt: string | null;\n}\n\nexport interface MemoryThreadConfigUpdate {\n observationTokens?: number | null;\n reflectionTokens?: number | null;\n}\n\nexport interface MemoryThreadConfig {\n observationTokens: number;\n reflectionTokens: number;\n overrides: { observationTokens: number | null; reflectionTokens: number | null };\n}\n\nexport interface MemoryObservationRun {\n id: string;\n threadId: string;\n resourceId: string;\n startedAt: string;\n durationMs: number;\n observed: boolean;\n reflected: boolean;\n tokensBefore: number;\n tokensAfter: number | null;\n error: string | null;\n}\n\nconst DEFAULT_API_URL = 'https://memory-api.mastra.ai';\nconst REQUEST_TIMEOUT_MS = 30_000;\n// Processor runs execute the hosted observer/reflector (LLM calls) inside the request.\nconst PROCESSOR_TIMEOUT_MS = 5 * 60_000;\n\nfunction env(name: string): string | undefined {\n return process.env[name]?.trim() || undefined;\n}\n\nfunction required(value: string | undefined, name: string): string {\n if (!value) throw new Error(`PlatformMemory: ${name} is required`);\n return value;\n}\n\nexport function resolvePlatformMemoryOptions(options: PlatformMemoryClientOptions = {}) {\n return {\n accessToken: required(\n options.accessToken ?? env('MASTRA_PLATFORM_ACCESS_TOKEN') ?? env('MASTRA_PLATFORM_SECRET_KEY'),\n 'accessToken',\n ),\n instanceId: required(options.instanceId ?? env('MASTRA_MEMORY_INSTANCE_ID'), 'instanceId'),\n projectId: options.projectId ?? env('MASTRA_PROJECT_ID'),\n environmentId: options.environmentId ?? env('MASTRA_ENVIRONMENT_ID'),\n actingUserId: options.actingUserId,\n apiUrl: (options.apiUrl ?? env('MASTRA_MEMORY_API_URL') ?? DEFAULT_API_URL).replace(/\\/$/, ''),\n fetch: options.fetch ?? fetch,\n };\n}\n\nexport class PlatformMemoryApiError extends Error {\n constructor(\n readonly status: number,\n readonly body: string,\n ) {\n super(`Platform Memory request failed with ${status}${body ? `: ${body}` : ''}`);\n this.name = 'PlatformMemoryApiError';\n }\n}\n\ntype Query = Record<string, string | number | undefined>;\n\n/** Typed client for the Platform Memory API (`/v1/memory/:instanceId/*`). */\nexport class PlatformMemoryClient {\n readonly instanceId: string;\n private readonly opts: ReturnType<typeof resolvePlatformMemoryOptions>;\n\n constructor(options: PlatformMemoryClientOptions = {}) {\n this.opts = resolvePlatformMemoryOptions(options);\n this.instanceId = this.opts.instanceId;\n }\n\n /** MCP endpoint for this instance, for clients that speak MCP directly. */\n get mcpUrl(): string {\n return `${this.base}/mcp`;\n }\n\n listThreads(query: { resourceId?: string; page?: number; perPage?: number } = {}) {\n return this.request<{ threads: MemoryThread[]; hasMore: boolean }>('GET', '/threads', { query });\n }\n\n createThread(body: { id?: string; resourceId: string; title?: string; metadata?: Record<string, unknown> }) {\n return this.request<MemoryThread>('POST', '/threads', { body });\n }\n\n /** Returns null when the thread does not exist. */\n async getThread(threadId: string): Promise<MemoryThread | null> {\n try {\n return await this.request<MemoryThread>('GET', `/threads/${encodeURIComponent(threadId)}`);\n } catch (error) {\n if (error instanceof PlatformMemoryApiError && error.status === 404) return null;\n throw error;\n }\n }\n\n updateThread(threadId: string, body: { title?: string; metadata?: Record<string, unknown> }) {\n return this.request<MemoryThread>('PATCH', `/threads/${encodeURIComponent(threadId)}`, { body });\n }\n\n async deleteThread(threadId: string): Promise<void> {\n await this.request('DELETE', `/threads/${encodeURIComponent(threadId)}`);\n }\n\n listMessages(threadId: string, query: { page?: number; perPage?: number } = {}) {\n return this.request<{ messages: MemoryMessage[]; hasMore: boolean }>(\n 'GET',\n `/threads/${encodeURIComponent(threadId)}/messages`,\n { query },\n );\n }\n\n /** Saves messages and schedules observation in the background. Creates the thread if needed. */\n saveMessages(threadId: string, body: { resourceId: string; messages: MemoryMessageInput[] }) {\n return this.request<{ messages: MemoryMessage[] }>('POST', `/threads/${encodeURIComponent(threadId)}/messages`, {\n body,\n });\n }\n\n getContext(threadId: string, resourceId: string, opts: { workingMemory?: 'readonly' | 'tool' | 'off' } = {}) {\n return this.request<MemoryContext>('GET', `/threads/${encodeURIComponent(threadId)}/context`, {\n query: { resourceId, ...(opts.workingMemory ? { workingMemory: opts.workingMemory } : {}) },\n });\n }\n\n async getWorkingMemory(resourceId: string): Promise<string | null> {\n const res = await this.request<{ workingMemory: string | null }>('GET', '/working-memory', {\n query: { resourceId },\n });\n return res.workingMemory;\n }\n\n async updateWorkingMemory(resourceId: string, workingMemory: string): Promise<void> {\n await this.request('PUT', '/working-memory', { body: { resourceId, workingMemory } });\n }\n\n /** Omit resourceId to search the instance's most recently active threads. */\n async search(body: { resourceId?: string; threadId?: string; query: string; limit?: number }) {\n const res = await this.request<{ matches: MemoryObservationMatch[] }>('POST', '/search', { body });\n return res.matches;\n }\n\n /** Current observational-memory record for the thread, or null before the first observation. */\n async getObservations(threadId: string): Promise<MemoryObservationRecord | null> {\n const res = await this.request<{ record: MemoryObservationRecord | null }>(\n 'GET',\n `/threads/${encodeURIComponent(threadId)}/observations`,\n );\n return res.record;\n }\n\n /** Runs the instance's memory processors for one agent phase on a serialized message list. */\n runProcessors(threadId: string, body: RunMemoryProcessorsInput, signal?: AbortSignal) {\n return this.request<MemoryProcessorsResult>('POST', `/threads/${encodeURIComponent(threadId)}/processors`, {\n body,\n signal,\n timeoutMs: PROCESSOR_TIMEOUT_MS,\n });\n }\n\n async listObservationRuns(query: { threadId?: string; limit?: number } = {}) {\n const res = await this.request<{ runs: MemoryObservationRun[] }>('GET', '/runs', { query });\n return res.runs;\n }\n\n /** Effective observation thresholds for the thread and which ones it overrides. */\n getThreadConfig(threadId: string) {\n return this.request<MemoryThreadConfig>('GET', `/threads/${encodeURIComponent(threadId)}/config`);\n }\n\n /** Overrides thresholds for one thread. Pass `null` to fall back to the instance value. */\n updateThreadConfig(threadId: string, config: MemoryThreadConfigUpdate) {\n return this.request<MemoryThreadConfig>('PATCH', `/threads/${encodeURIComponent(threadId)}/config`, {\n body: config,\n });\n }\n\n /** Copies a thread, its messages, and its observations. */\n cloneThread(\n threadId: string,\n body: { newThreadId?: string; title?: string; metadata?: Record<string, unknown>; messageLimit?: number } = {},\n ) {\n return this.request<{ thread: MemoryThread; clonedMessageCount: number }>(\n 'POST',\n `/threads/${encodeURIComponent(threadId)}/clone`,\n { body },\n );\n }\n\n /** Deletes messages from a thread. Ids that belong to other threads are ignored. */\n async deleteMessages(threadId: string, messageIds: string[]): Promise<number> {\n const res = await this.request<{ deleted: number }>(\n 'POST',\n `/threads/${encodeURIComponent(threadId)}/messages/delete`,\n { body: { messageIds } },\n );\n return res.deleted;\n }\n\n /** Everything stored for one resource (user): working memory and threads. */\n getResource(resourceId: string, query: { page?: number; perPage?: number } = {}) {\n return this.request<{\n resourceId: string;\n workingMemory: string | null;\n threads: MemoryThread[];\n totalThreads: number;\n hasMore: boolean;\n }>('GET', `/resources/${encodeURIComponent(resourceId)}`, { query });\n }\n\n /** Resources (users) in the instance, most recently active first. */\n listResources(query: { page?: number; perPage?: number } = {}) {\n return this.request<{\n resources: { resourceId: string; threadCount: number; lastActiveAt: string }[];\n hasMore: boolean;\n }>('GET', '/resources', { query });\n }\n\n /** Deletes every thread, message, observation and the working memory for a resource. */\n async deleteResource(resourceId: string): Promise<number> {\n const res = await this.request<{ deletedThreads: number }>(\n 'DELETE',\n `/resources/${encodeURIComponent(resourceId)}`,\n );\n return res.deletedThreads;\n }\n\n private get base(): string {\n return `${this.opts.apiUrl}/v1/memory/${encodeURIComponent(this.opts.instanceId)}`;\n }\n\n private async request<T>(\n method: string,\n path: string,\n init: { query?: Query; body?: unknown; signal?: AbortSignal; timeoutMs?: number } = {},\n ): Promise<T> {\n const url = new URL(this.base + path);\n for (const [key, value] of Object.entries(init.query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value));\n }\n const headers: Record<string, string> = { authorization: `Bearer ${this.opts.accessToken}` };\n if (this.opts.actingUserId) headers['x-acting-user-id'] = this.opts.actingUserId;\n if (this.opts.projectId) headers['x-mastra-project-id'] = this.opts.projectId;\n if (this.opts.environmentId) headers['x-mastra-environment-id'] = this.opts.environmentId;\n if (init.body !== undefined) headers['content-type'] = 'application/json';\n\n const deadline = AbortSignal.timeout(init.timeoutMs ?? REQUEST_TIMEOUT_MS);\n const res = await this.opts.fetch(url, {\n method,\n headers,\n body: init.body === undefined ? undefined : JSON.stringify(init.body),\n signal: init.signal ? AbortSignal.any([init.signal, deadline]) : deadline,\n });\n if (!res.ok) throw new PlatformMemoryApiError(res.status, await res.text().catch(() => ''));\n if (res.status === 204) return undefined as T;\n return (await res.json()) as T;\n }\n}\n","import type { MastraDBMessage } from '@mastra/core/agent';\nimport { MastraMemory, parseMemoryRequestContext } from '@mastra/core/memory';\nimport type { MemoryConfig, MemoryConfigInternal, StorageThreadType, WorkingMemoryTemplate } from '@mastra/core/memory';\nimport type {\n InputProcessor,\n OutputProcessor,\n ProcessInputArgs,\n ProcessInputStepArgs,\n ProcessOutputResultArgs,\n} from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type {\n StorageCloneThreadInput,\n StorageCloneThreadOutput,\n StorageListMessagesInput,\n StorageListThreadsInput,\n StorageListThreadsOutput,\n} from '@mastra/core/storage';\nimport { createTool } from '@mastra/core/tools';\nimport type { ToolAction } from '@mastra/core/tools';\n\nimport { z } from 'zod';\n\nimport { PlatformMemoryClient } from './client';\nimport type {\n MemoryMessage,\n MemoryMessageInput,\n MemoryProcessorsResult,\n MemoryThread,\n PlatformMemoryClientOptions,\n} from './client';\n\nexport type PlatformMemoryOptions = PlatformMemoryClientOptions & {\n id?: string;\n /** Use a preconfigured client instead of building one from the options above. */\n client?: PlatformMemoryClient;\n /**\n * How working memory is shown to the model. Defaults to `readonly`: the resource's stored\n * working memory is added to each run's prompt. `tool` also gives the agent an\n * `updateWorkingMemory` tool (not in read-only runs); `off` leaves working memory out.\n */\n workingMemory?: 'readonly' | 'tool' | 'off';\n};\n\ntype MessageListLike = ProcessInputArgs['messageList'];\n\nfunction threadFromApi(thread: MemoryThread): StorageThreadType {\n return {\n id: thread.id,\n resourceId: thread.resourceId,\n title: thread.title ?? undefined,\n metadata: thread.metadata ?? undefined,\n createdAt: new Date(thread.createdAt),\n updatedAt: new Date(thread.updatedAt),\n };\n}\n\nfunction messageFromApi(message: MemoryMessage, threadId: string, resourceId?: string): MastraDBMessage {\n return {\n id: message.id,\n role: message.role === 'assistant' ? 'assistant' : 'user',\n createdAt: new Date(message.createdAt),\n threadId,\n resourceId,\n content: {\n format: 2,\n parts: (message.parts?.length\n ? message.parts\n : [{ type: 'text', text: message.content }]) as MastraDBMessage['content']['parts'],\n },\n };\n}\n\nfunction textOf(message: MastraDBMessage): string {\n const parts = message.content.parts ?? [];\n const text = parts\n .filter((part): part is { type: 'text'; text: string } => part.type === 'text')\n .map(part => part.text)\n .join('\\n');\n return text || message.content.content || '';\n}\n\n/** User/assistant messages with all their parts (tool calls, reasoning, files). System messages are skipped. */\nfunction toApiMessages(messages: MastraDBMessage[]): MemoryMessageInput[] {\n return messages.flatMap((message): MemoryMessageInput[] => {\n if (message.role !== 'user' && message.role !== 'assistant') return [];\n const parts = message.content.parts ?? [];\n const createdAt = new Date(message.createdAt).toISOString();\n const content = textOf(message) || undefined;\n if (!parts.length && !content) return [];\n return [{ id: message.id, role: message.role, content, parts: parts.length ? parts : undefined, createdAt }];\n });\n}\n\nfunction memoryContext(requestContext: RequestContext | undefined, messageList: MessageListLike) {\n const ctx = parseMemoryRequestContext(requestContext);\n if (ctx?.thread?.id) {\n return {\n threadId: ctx.thread.id,\n resourceId: ctx.resourceId ?? ctx.thread.id,\n readOnly: ctx.memoryConfig?.readOnly,\n };\n }\n const info = messageList.serialize().memoryInfo;\n if (info?.threadId) return { threadId: info.threadId, resourceId: info.resourceId ?? info.threadId, readOnly: false };\n return null;\n}\n\nconst WORKING_MEMORY_TAG = 'platform-working-memory';\n\n/**\n * Adds the resource's stored working memory as a system message. The hosted processors don't\n * deliver it, so the client reads it on the first step of every run: a fresh read each run, so an\n * update between runs shows up on the next one.\n */\nasync function addWorkingMemory(\n client: PlatformMemoryClient,\n messageList: MessageListLike,\n resourceId: string,\n canUpdate: boolean,\n) {\n const data = await client.getWorkingMemory(resourceId);\n messageList.clearSystemMessages(WORKING_MEMORY_TAG);\n if (canUpdate) {\n messageList.addSystem(\n `WORKING_MEMORY_SYSTEM_INSTRUCTION:\nStore 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.\n\n<working_memory_data>\n${data ?? ''}\n</working_memory_data>`,\n WORKING_MEMORY_TAG,\n );\n } else if (data) {\n messageList.addSystem(\n `WORKING_MEMORY_SYSTEM_INSTRUCTION (READ-ONLY):\nThe following is what is remembered about the user. Use it for context; you cannot change it.\n\n<working_memory_data>\n${data}\n</working_memory_data>`,\n WORKING_MEMORY_TAG,\n );\n }\n}\n\n/**\n * What a read-only run sees of the thread, read through the context route, which writes nothing:\n * observations, the continuation reminder, then the messages not yet observed. Running the hosted\n * processors instead would save messages and start observation.\n */\nasync function addReadOnlyContext(\n client: PlatformMemoryClient,\n messageList: MessageListLike,\n threadId: string,\n resourceId: string,\n) {\n const context = await client.getContext(threadId, resourceId, { workingMemory: 'off' });\n const prompt = context.prompt ?? [\n ...(context.system\n ? [{ id: 'om-system', role: 'system', content: context.system, parts: [], createdAt: new Date(0).toISOString() }]\n : []),\n ...(context.continuation\n ? [\n {\n id: 'om-continuation',\n role: 'user',\n content: context.continuation,\n parts: [],\n createdAt: new Date(0).toISOString(),\n },\n ]\n : []),\n ...context.messages,\n ];\n for (const message of prompt) {\n if (message.role === 'system') messageList.addSystem(message.content, 'memory');\n else messageList.add(messageFromApi(message, threadId, resourceId), 'memory');\n }\n}\n\nasync function applyResult(\n result: MemoryProcessorsResult,\n agent: Pick<ProcessInputStepArgs, 'messageList' | 'writer' | 'abort' | 'rotateResponseMessageId'>,\n) {\n for (const chunk of result.chunks) await agent.writer?.custom(chunk as never);\n for (let i = 0; i < result.rotations; i++) agent.rotateResponseMessageId?.();\n if (result.aborted !== null || !result.messageList) return agent.abort(result.aborted ?? undefined);\n return agent.messageList.deserialize(result.messageList);\n}\n\n/**\n * Mastra memory backed by a hosted Platform Memory instance.\n *\n * Observation and reflection run on the Platform: on each input step and on the final output this\n * class sends the serialized message list to the instance's memory processors and applies the\n * result. Messages are stored with all their parts (text, tool calls, reasoning, files).\n */\nexport class PlatformMemory extends MastraMemory {\n readonly client: PlatformMemoryClient;\n private readonly workingMemoryMode: 'readonly' | 'tool' | 'off';\n\n constructor(options: PlatformMemoryOptions = {}) {\n super({ id: options.id ?? 'platform-memory', name: 'PlatformMemory' });\n this.client = options.client ?? new PlatformMemoryClient(options);\n this.workingMemoryMode = options.workingMemory ?? 'readonly';\n }\n\n listTools(config?: MemoryConfig): Record<string, ToolAction<any, any, any, any, any>> {\n if (this.workingMemoryMode !== 'tool' || config?.readOnly) return {};\n this.assertResourceScopedWorkingMemory(config);\n const client = this.client;\n return {\n updateWorkingMemory: createTool({\n id: 'update-working-memory',\n description:\n '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.',\n inputSchema: z.object({\n memory: z.string().describe('The Markdown formatted working memory content to store.'),\n }),\n execute: async ({ memory }, context) => {\n const resourceId = context?.agent?.resourceId ?? context?.agent?.threadId;\n if (!resourceId) throw new Error('updateWorkingMemory needs a thread or resource');\n await client.updateWorkingMemory(resourceId, memory);\n return { success: true };\n },\n }),\n };\n }\n\n // The instance runs the real @mastra/memory processors; these only ship the message list\n // there and apply what comes back (list, stream parts, message-id rotations, abort).\n async getInputProcessors(): Promise<InputProcessor[]> {\n const client = this.client;\n const workingMemoryMode = this.workingMemoryMode;\n return [\n {\n id: 'platform-memory',\n name: 'Platform Memory',\n async processInputStep({\n messageList,\n requestContext,\n stepNumber,\n model,\n writer,\n abort,\n abortSignal,\n rotateResponseMessageId,\n }: ProcessInputStepArgs) {\n const ctx = memoryContext(requestContext, messageList);\n if (!ctx) return messageList;\n if (ctx.readOnly) {\n if (stepNumber === 0) {\n await addReadOnlyContext(client, messageList, ctx.threadId, ctx.resourceId);\n if (workingMemoryMode !== 'off') await addWorkingMemory(client, messageList, ctx.resourceId, false);\n }\n return messageList;\n }\n const result = await client.runProcessors(\n ctx.threadId,\n {\n phase: 'inputStep',\n resourceId: ctx.resourceId,\n stepNumber,\n messageList: messageList.serialize(),\n model: model ? { provider: model.provider, modelId: model.modelId } : undefined,\n },\n abortSignal,\n );\n const list = await applyResult(result, { messageList, writer, abort, rotateResponseMessageId });\n if (stepNumber === 0 && workingMemoryMode !== 'off') {\n await addWorkingMemory(client, messageList, ctx.resourceId, workingMemoryMode === 'tool');\n }\n return list;\n },\n },\n ];\n }\n\n async getOutputProcessors(): Promise<OutputProcessor[]> {\n const client = this.client;\n return [\n {\n id: 'platform-memory',\n name: 'Platform Memory',\n async processOutputResult({ messageList, requestContext, result, writer, abort }: ProcessOutputResultArgs) {\n const ctx = memoryContext(requestContext, messageList);\n if (!ctx || ctx.readOnly) return messageList;\n // No abortSignal here: this call saves the turn's messages, and aborting mid-save can lose them.\n const res = await client.runProcessors(ctx.threadId, {\n phase: 'output',\n resourceId: ctx.resourceId,\n messageList: messageList.serialize(),\n finishReason: result?.finishReason,\n });\n return applyResult(res, { messageList, writer, abort });\n },\n },\n ];\n }\n\n async getThreadById({ threadId }: { threadId: string }): Promise<StorageThreadType | null> {\n const thread = await this.client.getThread(threadId);\n return thread ? threadFromApi(thread) : null;\n }\n\n async listThreads(args: StorageListThreadsInput): Promise<StorageListThreadsOutput> {\n const page = args.page ?? 0;\n const perPage = args.perPage === false ? 200 : (args.perPage ?? 100);\n const threads: StorageThreadType[] = [];\n for (let next = 0; ; next++) {\n const res = await this.client.listThreads({ resourceId: args.filter?.resourceId, page: next, perPage: 200 });\n threads.push(...res.threads.map(threadFromApi));\n if (!res.hasMore) break;\n }\n const filtered = threads.filter(thread =>\n Object.entries(args.filter?.metadata ?? {}).every(([key, value]) => thread.metadata?.[key] === value),\n );\n const field = args.orderBy?.field ?? 'updatedAt';\n const direction = args.orderBy?.direction === 'ASC' ? 1 : -1;\n filtered.sort((a, b) => direction * (a[field].getTime() - b[field].getTime()));\n const selected = args.perPage === false ? filtered : filtered.slice(page * perPage, (page + 1) * perPage);\n return {\n threads: selected,\n hasMore: args.perPage === false ? false : (page + 1) * perPage < filtered.length,\n page,\n perPage: args.perPage === false ? (false as const) : perPage,\n total: filtered.length,\n };\n }\n\n async saveThread({ thread }: { thread: StorageThreadType }): Promise<StorageThreadType> {\n const existing = await this.client.getThread(thread.id);\n const saved = existing\n ? await this.client.updateThread(thread.id, { title: thread.title, metadata: thread.metadata })\n : await this.client.createThread({\n id: thread.id,\n resourceId: thread.resourceId,\n title: thread.title,\n metadata: thread.metadata,\n });\n return threadFromApi(saved);\n }\n\n async updateThread({\n id,\n title,\n metadata,\n }: {\n id: string;\n title?: string;\n metadata?: Record<string, unknown>;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<StorageThreadType> {\n return threadFromApi(await this.client.updateThread(id, { title, metadata }));\n }\n\n async deleteThread(threadId: string): Promise<void> {\n await this.client.deleteThread(threadId);\n }\n\n async saveMessages(args: {\n messages: MastraDBMessage[];\n memoryConfig?: MemoryConfig;\n }): Promise<{ messages: MastraDBMessage[] }> {\n const byThread = new Map<string, MastraDBMessage[]>();\n for (const message of args.messages) {\n if (!message.threadId) continue;\n byThread.set(message.threadId, [...(byThread.get(message.threadId) ?? []), message]);\n }\n for (const [threadId, messages] of byThread) {\n const apiMessages = toApiMessages(messages);\n if (!apiMessages.length) continue;\n const resourceId = messages[0]!.resourceId ?? threadId;\n await this.client.saveMessages(threadId, { resourceId, messages: apiMessages });\n }\n return { messages: args.messages };\n }\n\n async recall(args: StorageListMessagesInput) {\n const threadIds = Array.isArray(args.threadId) ? args.threadId : [args.threadId];\n if (!threadIds.length || threadIds.some(id => !id)) throw new Error('PlatformMemory.recall requires a threadId');\n if (Object.keys(args.filter?.metadata ?? {}).length || args.include?.length) {\n throw new Error('PlatformMemory.recall does not support metadata filters or include windows');\n }\n const page = args.page ?? 0;\n const perPage = args.perPage === false ? 200 : (args.perPage ?? 40);\n const messages: MastraDBMessage[] = [];\n for (const threadId of threadIds) {\n const thread = await this.client.getThread(threadId);\n if (!thread || (args.resourceId && thread.resourceId !== args.resourceId)) continue;\n const resourceId = thread.resourceId;\n for (let next = 0; ; next++) {\n const res = await this.client.listMessages(threadId, { page: next, perPage: 200 });\n messages.push(...res.messages.map(message => messageFromApi(message, threadId, resourceId)));\n if (!res.hasMore) break;\n }\n }\n const { start, end, startExclusive, endExclusive } = args.filter?.dateRange ?? {};\n const filtered = messages.filter(message => {\n const timestamp = message.createdAt.getTime();\n return (\n (!start || (startExclusive ? timestamp > start.getTime() : timestamp >= start.getTime())) &&\n (!end || (endExclusive ? timestamp < end.getTime() : timestamp <= end.getTime()))\n );\n });\n const direction = args.orderBy?.direction === 'DESC' ? -1 : 1;\n filtered.sort((a, b) => direction * (a.createdAt.getTime() - b.createdAt.getTime()));\n const selected = args.perPage === false ? filtered : filtered.slice(page * perPage, (page + 1) * perPage);\n return {\n messages: selected,\n total: filtered.length,\n page,\n perPage: args.perPage === false ? (false as const) : perPage,\n hasMore: args.perPage === false ? false : (page + 1) * perPage < filtered.length,\n };\n }\n\n // Hosted working memory is keyed by resource only, so thread scope would silently be shared\n // across every thread of the same resource.\n private assertResourceScopedWorkingMemory(config?: MemoryConfig | MemoryConfigInternal): void {\n if (this.getMergedThreadConfig(config ?? {}).workingMemory?.scope === 'thread') {\n throw new Error('PlatformMemory does not support thread-scoped working memory');\n }\n }\n\n async getWorkingMemory({\n threadId,\n resourceId,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<string | null> {\n this.assertResourceScopedWorkingMemory(memoryConfig);\n return this.client.getWorkingMemory(resourceId ?? threadId);\n }\n\n async getWorkingMemoryTemplate(): Promise<WorkingMemoryTemplate | null> {\n return null;\n }\n\n async updateWorkingMemory({\n threadId,\n resourceId,\n workingMemory,\n memoryConfig,\n }: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<void> {\n this.assertResourceScopedWorkingMemory(memoryConfig);\n await this.client.updateWorkingMemory(resourceId ?? threadId, workingMemory);\n }\n\n async __experimental_updateWorkingMemoryVNext(args: {\n threadId: string;\n resourceId?: string;\n workingMemory: string;\n memoryConfig?: MemoryConfigInternal;\n }): Promise<{ success: boolean; reason: string }> {\n await this.updateWorkingMemory(args);\n return { success: true, reason: 'replaced' };\n }\n\n async deleteMessages(): Promise<void> {\n throw new Error('PlatformMemory does not support deleting individual messages yet');\n }\n\n async cloneThread(_args: StorageCloneThreadInput): Promise<StorageCloneThreadOutput> {\n throw new Error('PlatformMemory does not support cloning threads yet');\n }\n}\n","import { StagehandBrowser } from '@mastra/stagehand';\nimport type { StagehandBrowserConfig } from '@mastra/stagehand';\n\nexport interface PlatformBrowserOptions extends Omit<\n StagehandBrowserConfig,\n 'cdpUrl' | 'scope' | 'env' | 'apiKey' | 'projectId'\n> {\n /** Existing Platform-provisioned CDP URL. When supplied, no API request or access token is needed. */\n cdpUrl?: string;\n /** Platform access token. Falls back to `MASTRA_PLATFORM_ACCESS_TOKEN`, then `MASTRA_PLATFORM_SECRET_KEY`. */\n accessToken?: string;\n /** Mastra Platform project ID. Falls back to `MASTRA_PROJECT_ID`. */\n projectId?: string;\n /** Browser provisioning API URL. Falls back to `MASTRA_BROWSER_API_URL`. */\n apiUrl?: string;\n fetch?: typeof fetch;\n}\n\nconst DEFAULT_API_URL = 'https://platform.mastra.ai';\n\nfunction trimTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === '/') end--;\n return url.slice(0, end);\n}\n\n/** A Stagehand browser connected to a Platform-provisioned Browserbase session. */\nexport class PlatformBrowser extends StagehandBrowser {\n constructor(options: PlatformBrowserOptions = {}) {\n const {\n cdpUrl,\n accessToken = process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY,\n projectId = process.env.MASTRA_PROJECT_ID,\n apiUrl = process.env.MASTRA_BROWSER_API_URL ?? DEFAULT_API_URL,\n fetch: fetchImpl = fetch,\n ...stagehandOptions\n } = options;\n if (!cdpUrl && !accessToken) throw new Error('PlatformBrowser: accessToken is required');\n if (!cdpUrl && !projectId) throw new Error('PlatformBrowser: projectId is required');\n\n super({\n ...stagehandOptions,\n scope: 'shared',\n cdpUrl:\n cdpUrl ||\n (async () => {\n const response = await fetchImpl(`${trimTrailingSlashes(apiUrl)}/v1/browsers/sessions`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({ projectId }),\n signal: AbortSignal.timeout(30_000),\n });\n if (!response.ok) throw new Error(`PlatformBrowser: browser provisioning failed (${response.status})`);\n const result: unknown = await response.json();\n if (\n !result ||\n typeof result !== 'object' ||\n !('connectUrl' in result) ||\n typeof result.connectUrl !== 'string'\n ) {\n throw new Error('PlatformBrowser: browser provisioning returned no connectUrl');\n }\n return result.connectUrl;\n }),\n });\n }\n}\n","import { Knowledge } from '@mastra/core/knowledge';\nimport type { KnowledgeConfig, KnowledgeScopeDeclarations } from '@mastra/core/knowledge';\nimport {\n MastraCompositeStore,\n KnowledgeStorage,\n KnowledgeConflictError,\n KnowledgeNotFoundError,\n KnowledgePageHasChildrenError,\n KnowledgePageKeyConflictError,\n} from '@mastra/core/storage';\nimport type { KnowledgePageStore } from '@mastra/core/storage';\n\nexport interface PlatformKnowledgeOptions extends Omit<\n KnowledgeConfig,\n 'storage' | 'vector' | 'embedder' | 'embedderOptions' | 'scopes'\n> {\n accessToken?: string;\n projectId?: string;\n instanceId?: string;\n /**\n * Knowledge API URL. Falls back to `MASTRA_KNOWLEDGE_API_URL`, then `https://knowledge-api.mastra.ai`.\n */\n apiUrl?: string;\n}\n\n// These are the schema-v4 page-store methods, not arbitrary object properties or storage lifecycle methods.\n// `renameScopeDeclaration` is left to the base class, which rejects it: its `check` callback can't be\n// serialized, so the hosted store couldn't validate affected scopes before re-keying them.\nconst operations = [\n 'materializeScope',\n 'getScopesByAddress',\n 'listScopeDeclarations',\n 'listChildScopes',\n 'countChildScopes',\n 'getPage',\n 'getPages',\n 'getPageByPath',\n 'findPagesByName',\n 'listChildPages',\n 'countChildPages',\n 'listPages',\n 'createPage',\n 'updatePage',\n 'movePage',\n 'mergePages',\n 'deletePage',\n 'getNote',\n 'countNotes',\n 'listNotes',\n 'listNotesMentioning',\n 'addNote',\n 'restampNote',\n 'removeNote',\n 'restoreNote',\n 'searchPages',\n 'listPageActivity',\n 'addPinAudience',\n 'removePinAudience',\n 'listPins',\n 'countPageLinks',\n 'listPageLinks',\n 'replacePageBodyLinks',\n 'listPageBodyLinkSources',\n] as const satisfies readonly (keyof KnowledgePageStore)[];\n\n// Fails to compile when a page-store method is neither forwarded nor deliberately left to the base class.\ntype UnforwardedOperation = Exclude<keyof KnowledgePageStore, (typeof operations)[number]>;\nconst operationsAreExhaustive: [UnforwardedOperation] extends ['renameScopeDeclaration']\n ? ['renameScopeDeclaration'] extends [UnforwardedOperation]\n ? true\n : never\n : never = true;\nvoid operationsAreExhaustive;\n\nfunction encode(value: unknown): string {\n return JSON.stringify(value, function (key, item: unknown) {\n const original: unknown = key ? (this as Record<string, unknown>)[key] : item;\n return original instanceof Date ? { __knowledgeDate: original.toISOString() } : item;\n });\n}\n\nfunction decode<T>(text: string): T {\n return JSON.parse(text, (_key, value: unknown) => {\n if (value && typeof value === 'object' && '__knowledgeDate' in value) {\n return new Date((value as { __knowledgeDate: string }).__knowledgeDate);\n }\n return value;\n }) as T;\n}\n\nclass RemoteKnowledgeStorage extends KnowledgeStorage {\n constructor(\n private readonly endpoint: string,\n private readonly token: string,\n ) {\n super({ storageIsolationKey: endpoint });\n return new Proxy(this, {\n get(target, key) {\n if (typeof key === 'string' && operations.includes(key as (typeof operations)[number])) {\n return (input?: unknown) => target.request(key, input);\n }\n const value: unknown = Reflect.get(target, key, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n }\n\n private async request(operation: string, input?: unknown): Promise<unknown> {\n const response = await fetch(`${this.endpoint}/operations/${operation}`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${this.token}`,\n 'content-type': 'application/json',\n // This client merges the instance's scope declarations (`getScopeDeclarations`) into its own, so\n // the service leaves its read views as they are rather than widening them for older clients.\n 'x-mastra-knowledge-store-declarations': 'merged',\n },\n body: encode({ input }),\n signal: AbortSignal.timeout(30_000),\n });\n const text = await response.text();\n if (!response.ok) {\n let body: { name?: string; detail?: string; title?: string; error?: { name?: string; message?: string } } = {};\n try {\n const parsed: unknown = JSON.parse(text);\n if (parsed && typeof parsed === 'object') body = parsed;\n } catch {\n // Gateways can return non-JSON error pages.\n }\n const message =\n body.detail ||\n body.error?.message ||\n body.title ||\n (text\n ? `Knowledge request failed (${response.status}): ${text}`\n : `Knowledge request failed (${response.status})`);\n const name = body.name ?? body.error?.name;\n if (name === 'KnowledgeNotFoundError') {\n const error = new KnowledgeNotFoundError('record', operation);\n error.message = message;\n throw error;\n }\n if (name === 'KnowledgeConflictError') {\n const error = new KnowledgeConflictError(operation);\n error.message = message;\n throw error;\n }\n if (name === 'KnowledgePageKeyConflictError') {\n const error = new KnowledgePageKeyConflictError('', '');\n error.message = message;\n throw error;\n }\n if (name === 'KnowledgePageHasChildrenError') {\n const error = new KnowledgePageHasChildrenError('');\n error.message = message;\n throw error;\n }\n throw Object.assign(new Error(message), { status: response.status });\n }\n return decode<{ result?: unknown }>(text).result;\n }\n\n /**\n * The scope declarations the instance supplies, such as the ones its importers write to, with their\n * access rules. A service that doesn't have the operation yet answers 404 \"Knowledge operation not\n * found\" and supplies none. Any other failure, including another 404 (a missing instance, a wrong\n * URL), and anything but a declaration record is a broken response, not \"none\".\n */\n override async getScopeDeclarations(): Promise<KnowledgeScopeDeclarations> {\n let result: unknown;\n try {\n result = await this.request('getScopeDeclarations');\n } catch (error) {\n const status = (error as { status?: unknown }).status;\n if (status === 404 && (error as Error).message === 'Knowledge operation not found') return {};\n throw error;\n }\n if (!result || typeof result !== 'object' || Array.isArray(result)) {\n throw new Error('Knowledge service answered getScopeDeclarations without a declaration record');\n }\n return result as KnowledgeScopeDeclarations;\n }\n\n override getCapabilities() {\n return {\n contractVersion: 4,\n schemaVersion: 4,\n supportsSchemaInspection: false,\n supportsExplicitReset: false,\n // The service's stores keep a pin's kind and depth, so listing pins round-trip.\n supportsPinKinds: true,\n } as const;\n }\n\n override async dangerouslyClearAll(): Promise<void> {\n throw new Error('Hosted Knowledge cannot be cleared from the client');\n }\n}\n\nconst DEFAULT_API_URL = 'https://knowledge-api.mastra.ai';\n\nexport class PlatformKnowledge extends Knowledge {\n constructor(options: PlatformKnowledgeOptions = {}) {\n // `MASTRA_KNOWLEDGE_ACCESS_TOKEN` is a Knowledge-only credential, narrower than the general\n // Platform token, so it's preferred when set.\n const token =\n options.accessToken ??\n (process.env.MASTRA_KNOWLEDGE_ACCESS_TOKEN?.trim() || undefined) ??\n process.env.MASTRA_PLATFORM_ACCESS_TOKEN ??\n process.env.MASTRA_PLATFORM_SECRET_KEY;\n const instanceId = options.instanceId ?? process.env.MASTRA_KNOWLEDGE_INSTANCE_ID;\n const apiUrl = options.apiUrl ?? (process.env.MASTRA_KNOWLEDGE_API_URL?.trim() || undefined) ?? DEFAULT_API_URL;\n if (!token || !instanceId) {\n throw new Error('PlatformKnowledge requires a Platform access token and Knowledge instance ID');\n }\n const {\n accessToken: _accessToken,\n projectId: _projectId,\n instanceId: _instanceId,\n apiUrl: _apiUrl,\n ...config\n } = options;\n const endpoint = `${apiUrl.replace(/\\/$/, '')}/v1/knowledge/${encodeURIComponent(instanceId)}`;\n const storage = new MastraCompositeStore({\n id: `platform-knowledge-${instanceId}`,\n domains: { knowledge: new RemoteKnowledgeStorage(endpoint, token) },\n });\n super({\n ...config,\n tools: config.tools ?? { read: true },\n // Platform owns every scope declaration and access grant: the instance serves them all through\n // `getScopeDeclarations`, so there is one place to change who reads what. Declaring scopes here\n // too would conflict with the instance's (a key both declare silently takes the code's rules,\n // and overlapping patterns break every call), so PlatformKnowledge takes no `scopes` option.\n scopes: {},\n storage,\n });\n }\n}\n\nexport { encode as encodeKnowledgeTransport, decode as decodeKnowledgeTransport };\nexport { operations as knowledgeOperations };\n"],"mappings":";;;;;;;;AA0HA,MAAMA,oBAAkB;AACxB,MAAM,qBAAqB;AAE3B,MAAM,uBAAuB;AAE7B,SAAS,IAAI,MAAkC;CAC7C,OAAO,QAAQ,IAAI,KAAK,EAAE,KAAK,KAAK,KAAA;AACtC;AAEA,SAAS,SAAS,OAA2B,MAAsB;CACjE,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,mBAAmB,KAAK,aAAa;CACjE,OAAO;AACT;AAEA,SAAgB,6BAA6B,UAAuC,CAAC,GAAG;CACtF,OAAO;EACL,aAAa,SACX,QAAQ,eAAe,IAAI,8BAA8B,KAAK,IAAI,4BAA4B,GAC9F,aACF;EACA,YAAY,SAAS,QAAQ,cAAc,IAAI,2BAA2B,GAAG,YAAY;EACzF,WAAW,QAAQ,aAAa,IAAI,mBAAmB;EACvD,eAAe,QAAQ,iBAAiB,IAAI,uBAAuB;EACnE,cAAc,QAAQ;EACtB,SAAS,QAAQ,UAAU,IAAI,uBAAuB,KAAKA,kBAAAA,CAAiB,QAAQ,OAAO,EAAE;EAC7F,OAAO,QAAQ,SAAS;CAC1B;AACF;AAEA,IAAa,yBAAb,cAA4C,MAAM;CAErC;CACA;CAFX,YACE,QACA,MACA;EACA,MAAM,uCAAuC,SAAS,OAAO,KAAK,SAAS,IAAI;EAHtE,KAAA,SAAA;EACA,KAAA,OAAA;EAGT,KAAK,OAAO;CACd;AACF;;AAKA,IAAa,uBAAb,MAAkC;CAChC;CACA;CAEA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"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/knowledge/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,KAAK,EAAE,eAAe,EAA8B,MAAM,wBAAwB,CAAC;AAW1F,MAAM,WAAW,wBAAyB,SAAQ,IAAI,CACpD,eAAe,EACf,SAAS,GAAG,QAAQ,GAAG,UAAU,GAAG,iBAAiB,GAAG,QAAQ,CACjE;IACC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAKD,QAAA,MAAM,UAAU,skBAmC0C,CAAC;AAW3D,iBAAS,MAAM,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAKtC;AAED,iBAAS,MAAM,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,CAAC,CAOlC;AAiHD,qBAAa,iBAAkB,SAAQ,SAAS;IAC9C,YAAY,OAAO,GAAE,wBAA6B,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/knowledge/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,KAAK,EAAE,eAAe,EAA8B,MAAM,wBAAwB,CAAC;AAW1F,MAAM,WAAW,wBAAyB,SAAQ,IAAI,CACpD,eAAe,EACf,SAAS,GAAG,QAAQ,GAAG,UAAU,GAAG,iBAAiB,GAAG,QAAQ,CACjE;IACC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAKD,QAAA,MAAM,UAAU,skBAmC0C,CAAC;AAW3D,iBAAS,MAAM,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAKtC;AAED,iBAAS,MAAM,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,CAAC,CAOlC;AAiHD,qBAAa,iBAAkB,SAAQ,SAAS;IAC9C,YAAY,OAAO,GAAE,wBAA6B,EAmCjD;CACF;AAED,OAAO,EAAE,MAAM,IAAI,wBAAwB,EAAE,MAAM,IAAI,wBAAwB,EAAE,CAAC;AAClF,OAAO,EAAE,UAAU,IAAI,mBAAmB,EAAE,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/platform",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1-alpha.0",
|
|
4
4
|
"description": "Mastra Platform hosted Memory, Knowledge, Browser, and workspace clients",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -27,12 +27,12 @@
|
|
|
27
27
|
"typescript": "^7.0.2",
|
|
28
28
|
"vitest": "5.1.0",
|
|
29
29
|
"zod": "^4.6.7",
|
|
30
|
-
"@internal/ai-sdk-v5": "0.0.
|
|
31
|
-
"@internal/types-builder": "0.0.
|
|
32
|
-
"@mastra/core": "1.
|
|
33
|
-
"@mastra/memory": "1.41.2
|
|
34
|
-
"@mastra/pg": "1.37.0
|
|
35
|
-
"@mastra/platform-workspace": "1.13.1
|
|
30
|
+
"@internal/ai-sdk-v5": "0.0.97",
|
|
31
|
+
"@internal/types-builder": "0.0.125",
|
|
32
|
+
"@mastra/core": "1.85.0-alpha.1",
|
|
33
|
+
"@mastra/memory": "1.41.2",
|
|
34
|
+
"@mastra/pg": "1.37.0",
|
|
35
|
+
"@mastra/platform-workspace": "1.13.1"
|
|
36
36
|
},
|
|
37
37
|
"peerDependencies": {
|
|
38
38
|
"@mastra/core": ">=1.82.0-0 <2.0.0-0",
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
"node": ">=22.13.0"
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
|
-
"@mastra/platform-workspace": "1.13.1
|
|
57
|
+
"@mastra/platform-workspace": "1.13.1",
|
|
58
58
|
"@mastra/stagehand": "0.4.0"
|
|
59
59
|
},
|
|
60
60
|
"scripts": {
|