@dbx-tools/appkit-mastra 0.1.13 → 0.1.14
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 +304 -645
- package/index.ts +46 -38
- package/package.json +58 -45
- package/src/agents.ts +224 -66
- package/src/chart.ts +531 -429
- package/src/config.ts +270 -19
- package/src/filesystems.ts +1090 -0
- package/src/genie.ts +1000 -660
- package/src/history.ts +166 -79
- package/src/mcp.ts +105 -0
- package/src/memory.ts +94 -92
- package/src/mlflow.ts +149 -0
- package/src/model.ts +75 -408
- package/src/observability.ts +121 -69
- package/src/pagination.ts +34 -0
- package/src/plugin.ts +552 -67
- package/src/processors.ts +168 -0
- package/src/rest.ts +67 -0
- package/src/server.ts +232 -45
- package/src/serving-sanitize.ts +167 -0
- package/src/serving.ts +27 -243
- package/src/statement.ts +89 -0
- package/src/storage-schema.ts +41 -0
- package/src/summarize.ts +176 -0
- package/src/threads.ts +338 -0
- package/src/workspaces.ts +346 -0
- package/src/writer.ts +44 -0
- package/tsconfig.json +41 -0
- package/dist/index.d.ts +0 -20
- package/dist/index.js +0 -20
- package/dist/src/agents.d.ts +0 -306
- package/dist/src/agents.js +0 -403
- package/dist/src/chart.d.ts +0 -170
- package/dist/src/chart.js +0 -491
- package/dist/src/config.d.ts +0 -183
- package/dist/src/config.js +0 -12
- package/dist/src/genie.d.ts +0 -131
- package/dist/src/genie.js +0 -630
- package/dist/src/history.d.ts +0 -67
- package/dist/src/history.js +0 -172
- package/dist/src/memory.d.ts +0 -100
- package/dist/src/memory.js +0 -242
- package/dist/src/model.d.ts +0 -159
- package/dist/src/model.js +0 -427
- package/dist/src/observability.d.ts +0 -33
- package/dist/src/observability.js +0 -71
- package/dist/src/plugin.d.ts +0 -130
- package/dist/src/plugin.js +0 -283
- package/dist/src/processors/strip-stale-charts.d.ts +0 -29
- package/dist/src/processors/strip-stale-charts.js +0 -96
- package/dist/src/server.d.ts +0 -46
- package/dist/src/server.js +0 -123
- package/dist/src/serving.d.ts +0 -156
- package/dist/src/serving.js +0 -231
- package/dist/src/tools/email.d.ts +0 -74
- package/dist/src/tools/email.js +0 -122
- package/dist/tsconfig.build.tsbuildinfo +0 -1
- package/src/processors/strip-stale-charts.ts +0 -105
- package/src/tools/email.ts +0 -147
package/src/summarize.ts
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small-tier summarization for the Mastra plugin.
|
|
3
|
+
*
|
|
4
|
+
* Two surfaces, both backed by the fast / small chat tier
|
|
5
|
+
* ({@link model.ModelClass.ChatFast}) resolved through the same
|
|
6
|
+
* `/serving-endpoints` pipeline as the main agents:
|
|
7
|
+
*
|
|
8
|
+
* - A dedicated `summarize` tool (see {@link buildSummarizeTool})
|
|
9
|
+
* agents can call to condense arbitrary text without burning the
|
|
10
|
+
* heavyweight chat model.
|
|
11
|
+
* - The model + instructions Mastra's memory uses to auto-name
|
|
12
|
+
* conversation threads (`generateTitle`), so titling reuses the
|
|
13
|
+
* same small tier rather than the agent's primary model.
|
|
14
|
+
*
|
|
15
|
+
* Mirrors the chart-planner wiring in `chart.ts`: a per-config cached
|
|
16
|
+
* `Agent` on the fast tier, invoked via `agent.generate(...)` inside
|
|
17
|
+
* the active `asUser` scope so tokens stay user-scoped.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { model } from "@dbx-tools/shared-model";
|
|
21
|
+
import { Agent } from "@mastra/core/agent";
|
|
22
|
+
import type { MastraModelConfig } from "@mastra/core/llm";
|
|
23
|
+
import type { RequestContext } from "@mastra/core/request-context";
|
|
24
|
+
import { createTool } from "@mastra/core/tools";
|
|
25
|
+
import { z } from "zod";
|
|
26
|
+
|
|
27
|
+
import type { MastraPluginConfig } from "./config";
|
|
28
|
+
import { buildModel } from "./model";
|
|
29
|
+
import { string } from "@dbx-tools/shared-core";
|
|
30
|
+
|
|
31
|
+
/** Fast / small chat tier used for both titling and summaries. */
|
|
32
|
+
const SUMMARY_MODEL_CLASS = model.ModelClass.ChatFast;
|
|
33
|
+
|
|
34
|
+
/** System prompt for the summarizer agent (and the `summarize` tool). */
|
|
35
|
+
const SUMMARIZER_INSTRUCTIONS = [
|
|
36
|
+
"You are a summarization engine.",
|
|
37
|
+
"Given a block of text, produce a faithful, concise summary of it.",
|
|
38
|
+
"Default to a few sentences; follow any length guidance the caller gives.",
|
|
39
|
+
"Plain prose. No preamble, no headers, no bullet points unless asked.",
|
|
40
|
+
"Never use emojis. Use hyphens (-) only, never em dashes or en dashes.",
|
|
41
|
+
"Never add information, opinions, or details not present in the input.",
|
|
42
|
+
"Output only the summary.",
|
|
43
|
+
].join("\n");
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Instructions Mastra's `generateTitle` hands the small-tier model to
|
|
47
|
+
* name a conversation thread from its opening turn. Kept terse so the
|
|
48
|
+
* model returns a bare title with no decoration.
|
|
49
|
+
*/
|
|
50
|
+
export const TITLE_INSTRUCTIONS = [
|
|
51
|
+
"Generate a short, specific title for this conversation, 3 to 6 words.",
|
|
52
|
+
"Capture the user's topic, not the assistant's response.",
|
|
53
|
+
"Plain text only: no surrounding quotes, no trailing punctuation,",
|
|
54
|
+
"no emojis, and no em dashes. Output only the title.",
|
|
55
|
+
].join(" ");
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Resolve the small-tier model for summarization / titling. Reused by
|
|
59
|
+
* both the summarizer agent and Mastra memory's `generateTitle`.
|
|
60
|
+
*
|
|
61
|
+
* Returned as a `requestContext`-taking function (a Mastra
|
|
62
|
+
* `DynamicArgument<MastraModelConfig>`) so each call mints user-scoped
|
|
63
|
+
* tokens via {@link buildModel}, exactly like the primary agents.
|
|
64
|
+
*/
|
|
65
|
+
export function summaryModel(
|
|
66
|
+
config: MastraPluginConfig,
|
|
67
|
+
): (args: { requestContext: RequestContext }) => Promise<MastraModelConfig> {
|
|
68
|
+
return ({ requestContext }) =>
|
|
69
|
+
buildModel(config, requestContext, { modelClass: SUMMARY_MODEL_CLASS });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* One summarizer `Agent` per plugin config, cached on config-object
|
|
74
|
+
* identity so a hot tool path doesn't pay the constructor cost each
|
|
75
|
+
* call. `WeakMap` lets retired configs (e.g. test reconfigurations)
|
|
76
|
+
* release their agent without manual eviction.
|
|
77
|
+
*/
|
|
78
|
+
const summarizerAgents = new WeakMap<MastraPluginConfig, Agent>();
|
|
79
|
+
|
|
80
|
+
function getSummarizerAgent(config: MastraPluginConfig): Agent {
|
|
81
|
+
let agent = summarizerAgents.get(config);
|
|
82
|
+
if (!agent) {
|
|
83
|
+
agent = new Agent({
|
|
84
|
+
id: "summarizer",
|
|
85
|
+
name: "Summarizer",
|
|
86
|
+
description: "Condenses text into a short summary using a fast, small model.",
|
|
87
|
+
instructions: SUMMARIZER_INSTRUCTIONS,
|
|
88
|
+
model: summaryModel(config),
|
|
89
|
+
});
|
|
90
|
+
summarizerAgents.set(config, agent);
|
|
91
|
+
}
|
|
92
|
+
return agent;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Inputs accepted by the `summarize` tool. */
|
|
96
|
+
const summarizeInput = z.object({
|
|
97
|
+
text: z.string().min(1).describe("The text to summarize."),
|
|
98
|
+
instructions: z
|
|
99
|
+
.string()
|
|
100
|
+
.optional()
|
|
101
|
+
.describe(
|
|
102
|
+
"Optional extra guidance for the summary, e.g. 'one sentence' or 'list the action items'.",
|
|
103
|
+
),
|
|
104
|
+
maxWords: z
|
|
105
|
+
.number()
|
|
106
|
+
.int()
|
|
107
|
+
.positive()
|
|
108
|
+
.optional()
|
|
109
|
+
.describe("Optional soft cap on the summary length, in words."),
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
/** Options accepted by {@link summarizeText}. */
|
|
113
|
+
export interface SummarizeOptions {
|
|
114
|
+
/** Extra guidance for the summary (length, focus, format). */
|
|
115
|
+
instructions?: string;
|
|
116
|
+
/** Soft cap on summary length, in words. */
|
|
117
|
+
maxWords?: number;
|
|
118
|
+
/** Active request context, so the model resolver mints user-scoped tokens. */
|
|
119
|
+
requestContext?: RequestContext;
|
|
120
|
+
/** Abort signal bridged from the calling tool / request. */
|
|
121
|
+
abortSignal?: AbortSignal;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Summarize `text` with the small-tier summarizer agent, returning the
|
|
126
|
+
* trimmed summary string. Throws on model failure (the caller decides
|
|
127
|
+
* how to degrade).
|
|
128
|
+
*/
|
|
129
|
+
export async function summarizeText(
|
|
130
|
+
config: MastraPluginConfig,
|
|
131
|
+
text: string,
|
|
132
|
+
options: SummarizeOptions = {},
|
|
133
|
+
): Promise<string> {
|
|
134
|
+
const { instructions, maxWords, requestContext, abortSignal } = options;
|
|
135
|
+
const prompt = string.toDescription({
|
|
136
|
+
...(instructions ? { Guidance: instructions } : {}),
|
|
137
|
+
...(maxWords !== undefined ? { "Max length (words)": String(maxWords) } : {}),
|
|
138
|
+
Text: text,
|
|
139
|
+
});
|
|
140
|
+
const result = await getSummarizerAgent(config).generate(prompt, {
|
|
141
|
+
...(requestContext ? { requestContext } : {}),
|
|
142
|
+
...(abortSignal ? { abortSignal } : {}),
|
|
143
|
+
});
|
|
144
|
+
return result.text.trim();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Build the `summarize` tool. Exposed as an ambient system tool (like
|
|
149
|
+
* `render_data`) so every agent can offload condensing long content,
|
|
150
|
+
* notes, transcripts, or bulky tool results to the fast tier instead of
|
|
151
|
+
* spending its primary chat model. The tool reads the live
|
|
152
|
+
* `requestContext` / `abortSignal` off the Mastra execution context so
|
|
153
|
+
* its model call stays user-scoped and cancels with the turn.
|
|
154
|
+
*/
|
|
155
|
+
export function buildSummarizeTool(config: MastraPluginConfig) {
|
|
156
|
+
return createTool({
|
|
157
|
+
id: "summarize",
|
|
158
|
+
description:
|
|
159
|
+
"Summarize a block of text using a fast, small model. Use it to condense long " +
|
|
160
|
+
"content, notes, transcripts, or tool results into a short summary without " +
|
|
161
|
+
"spending the main chat model.",
|
|
162
|
+
inputSchema: summarizeInput,
|
|
163
|
+
execute: async (input, context) => {
|
|
164
|
+
const { text, instructions, maxWords } = input as z.infer<typeof summarizeInput>;
|
|
165
|
+
const ctx = context as
|
|
166
|
+
{ requestContext?: RequestContext; abortSignal?: AbortSignal } | undefined;
|
|
167
|
+
const summary = await summarizeText(config, text, {
|
|
168
|
+
...(instructions ? { instructions } : {}),
|
|
169
|
+
...(maxWords !== undefined ? { maxWords } : {}),
|
|
170
|
+
...(ctx?.requestContext ? { requestContext: ctx.requestContext } : {}),
|
|
171
|
+
...(ctx?.abortSignal ? { abortSignal: ctx.abortSignal } : {}),
|
|
172
|
+
});
|
|
173
|
+
return { summary };
|
|
174
|
+
},
|
|
175
|
+
});
|
|
176
|
+
}
|
package/src/threads.ts
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conversation-thread listing exposed as a Mastra custom API route.
|
|
3
|
+
*
|
|
4
|
+
* Backed entirely by native Mastra: looks up the active agent by id,
|
|
5
|
+
* asks its `Memory` instance to `listThreads` filtered to the caller's
|
|
6
|
+
* resource, and shapes each into the JSON-safe {@link MastraThread}
|
|
7
|
+
* wire type. A sibling `DELETE` removes a single named thread.
|
|
8
|
+
*
|
|
9
|
+
* A sibling `DELETE` removes a single named thread; a `PATCH` renames
|
|
10
|
+
* one ({@link renameThread}).
|
|
11
|
+
*
|
|
12
|
+
* Like {@link historyRoute} this registers through Mastra's
|
|
13
|
+
* `registerApiRoute` so it shares the `MastraServer` auth-middleware
|
|
14
|
+
* pipeline (in `./server.ts`), which has already stamped the resource
|
|
15
|
+
* id (`MASTRA_RESOURCE_ID_KEY`) and the targeted thread id
|
|
16
|
+
* (`MASTRA_THREAD_ID_KEY`, resolved from the thread-selection header /
|
|
17
|
+
* cookie) on `RequestContext` by the time a handler runs. Resource
|
|
18
|
+
* scoping lives here so a caller can only ever see, rename, or delete
|
|
19
|
+
* its own threads; no cookie or user lookups happen in this module.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
wire,
|
|
24
|
+
type MastraDeleteThreadResponse,
|
|
25
|
+
type MastraThread,
|
|
26
|
+
type MastraThreadsResponse,
|
|
27
|
+
type MastraUpdateThreadResponse,
|
|
28
|
+
} from "@dbx-tools/shared-mastra";
|
|
29
|
+
import type { Agent } from "@mastra/core/agent";
|
|
30
|
+
import type { StorageThreadType } from "@mastra/core/memory";
|
|
31
|
+
import { MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY } from "@mastra/core/request-context";
|
|
32
|
+
import type { ContextWithMastra } from "@mastra/core/server";
|
|
33
|
+
import { registerApiRoute } from "@mastra/core/server";
|
|
34
|
+
|
|
35
|
+
import { clampPerPage, parseIntParam } from "./pagination";
|
|
36
|
+
import { log } from "@dbx-tools/shared-core";
|
|
37
|
+
|
|
38
|
+
const logger = log.logger("mastra/threads");
|
|
39
|
+
|
|
40
|
+
/** Default threads page size. */
|
|
41
|
+
const DEFAULT_PER_PAGE = 30;
|
|
42
|
+
/** Hard cap so a misbehaving client can't fetch every thread at once. */
|
|
43
|
+
const MAX_PER_PAGE = 200;
|
|
44
|
+
|
|
45
|
+
/** Inputs accepted by {@link listThreads}. */
|
|
46
|
+
export interface ListThreadsOptions {
|
|
47
|
+
agent: Agent;
|
|
48
|
+
resourceId: string;
|
|
49
|
+
page?: number;
|
|
50
|
+
perPage?: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Fetch a page of the resource's conversation threads, newest
|
|
55
|
+
* (`updatedAt` DESC) first.
|
|
56
|
+
*
|
|
57
|
+
* Uses the agent's resolved `Memory` (`getMemory()`) so the per-agent
|
|
58
|
+
* storage namespace (`mastra_<agentId>` schema) applies automatically.
|
|
59
|
+
* When the agent has no memory configured the response is a successful
|
|
60
|
+
* empty page so callers don't have to special-case stateless agents.
|
|
61
|
+
*/
|
|
62
|
+
export async function listThreads(opts: ListThreadsOptions): Promise<MastraThreadsResponse> {
|
|
63
|
+
const perPage = clampPerPage(opts.perPage, {
|
|
64
|
+
fallback: DEFAULT_PER_PAGE,
|
|
65
|
+
max: MAX_PER_PAGE,
|
|
66
|
+
});
|
|
67
|
+
const page = Math.max(0, Math.trunc(opts.page ?? 0));
|
|
68
|
+
const memory = await opts.agent.getMemory();
|
|
69
|
+
if (!memory) {
|
|
70
|
+
logger.debug("list:no-memory", { agentId: opts.agent.id });
|
|
71
|
+
return { threads: [], page, perPage, total: 0, hasMore: false };
|
|
72
|
+
}
|
|
73
|
+
const startedAt = Date.now();
|
|
74
|
+
const result = await memory.listThreads({
|
|
75
|
+
filter: { resourceId: opts.resourceId },
|
|
76
|
+
page,
|
|
77
|
+
perPage,
|
|
78
|
+
orderBy: { field: "updatedAt", direction: "DESC" },
|
|
79
|
+
});
|
|
80
|
+
const threads = result.threads.map(toWireThread);
|
|
81
|
+
logger.debug("list:done", {
|
|
82
|
+
agentId: opts.agent.id,
|
|
83
|
+
resourceId: opts.resourceId,
|
|
84
|
+
page,
|
|
85
|
+
perPage,
|
|
86
|
+
returned: threads.length,
|
|
87
|
+
total: result.total,
|
|
88
|
+
hasMore: result.hasMore,
|
|
89
|
+
elapsedMs: Date.now() - startedAt,
|
|
90
|
+
});
|
|
91
|
+
return {
|
|
92
|
+
threads,
|
|
93
|
+
page,
|
|
94
|
+
perPage,
|
|
95
|
+
total: result.total,
|
|
96
|
+
hasMore: result.hasMore,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Inputs accepted by {@link deleteThread}. */
|
|
101
|
+
export interface DeleteThreadOptions {
|
|
102
|
+
agent: Agent;
|
|
103
|
+
threadId: string;
|
|
104
|
+
resourceId: string;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Delete a single named thread (and every message on it).
|
|
109
|
+
*
|
|
110
|
+
* Ownership is enforced: the thread is only removed when it belongs to
|
|
111
|
+
* the calling resource, so a client can't delete another user's
|
|
112
|
+
* conversation by guessing its id. A thread that doesn't exist (or
|
|
113
|
+
* isn't owned by the caller) is a successful no-op (`deleted: false`)
|
|
114
|
+
* so the UI can fire-and-forget.
|
|
115
|
+
*/
|
|
116
|
+
export async function deleteThread(opts: DeleteThreadOptions): Promise<{ deleted: boolean }> {
|
|
117
|
+
const memory = await opts.agent.getMemory();
|
|
118
|
+
if (!memory) {
|
|
119
|
+
logger.debug("delete:no-memory", { agentId: opts.agent.id });
|
|
120
|
+
return { deleted: false };
|
|
121
|
+
}
|
|
122
|
+
// Confirm the thread exists and is owned by the caller before
|
|
123
|
+
// deleting; never let a guessed id touch another resource's data.
|
|
124
|
+
const existing = await memory.getThreadById({ threadId: opts.threadId });
|
|
125
|
+
if (!existing || existing.resourceId !== opts.resourceId) {
|
|
126
|
+
logger.debug("delete:not-owned", {
|
|
127
|
+
agentId: opts.agent.id,
|
|
128
|
+
threadId: opts.threadId,
|
|
129
|
+
found: existing !== null,
|
|
130
|
+
});
|
|
131
|
+
return { deleted: false };
|
|
132
|
+
}
|
|
133
|
+
const startedAt = Date.now();
|
|
134
|
+
await memory.deleteThread(opts.threadId);
|
|
135
|
+
logger.info("delete:done", {
|
|
136
|
+
agentId: opts.agent.id,
|
|
137
|
+
threadId: opts.threadId,
|
|
138
|
+
elapsedMs: Date.now() - startedAt,
|
|
139
|
+
});
|
|
140
|
+
return { deleted: true };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Inputs accepted by {@link renameThread}. */
|
|
144
|
+
export interface RenameThreadOptions {
|
|
145
|
+
agent: Agent;
|
|
146
|
+
threadId: string;
|
|
147
|
+
resourceId: string;
|
|
148
|
+
title: string;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Rename a single thread, returning the updated wire thread.
|
|
153
|
+
*
|
|
154
|
+
* Ownership is enforced the same way {@link deleteThread} enforces it:
|
|
155
|
+
* the title is only changed when the thread belongs to the calling
|
|
156
|
+
* resource, so a client can't rename another user's conversation by
|
|
157
|
+
* guessing its id. Existing thread `metadata` is preserved untouched
|
|
158
|
+
* (Mastra's `updateThread` replaces the row, so it must be passed back
|
|
159
|
+
* in). Returns `null` when the thread doesn't exist, isn't owned by the
|
|
160
|
+
* caller, or the agent has no memory configured, letting the route map
|
|
161
|
+
* that to a 404.
|
|
162
|
+
*/
|
|
163
|
+
export async function renameThread(opts: RenameThreadOptions): Promise<MastraThread | null> {
|
|
164
|
+
const memory = await opts.agent.getMemory();
|
|
165
|
+
if (!memory) {
|
|
166
|
+
logger.debug("rename:no-memory", { agentId: opts.agent.id });
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
const existing = await memory.getThreadById({ threadId: opts.threadId });
|
|
170
|
+
if (!existing || existing.resourceId !== opts.resourceId) {
|
|
171
|
+
logger.debug("rename:not-owned", {
|
|
172
|
+
agentId: opts.agent.id,
|
|
173
|
+
threadId: opts.threadId,
|
|
174
|
+
found: existing !== null,
|
|
175
|
+
});
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
const startedAt = Date.now();
|
|
179
|
+
const updated = await memory.updateThread({
|
|
180
|
+
id: opts.threadId,
|
|
181
|
+
title: opts.title,
|
|
182
|
+
metadata: existing.metadata ?? {},
|
|
183
|
+
});
|
|
184
|
+
logger.info("rename:done", {
|
|
185
|
+
agentId: opts.agent.id,
|
|
186
|
+
threadId: opts.threadId,
|
|
187
|
+
elapsedMs: Date.now() - startedAt,
|
|
188
|
+
});
|
|
189
|
+
return toWireThread(updated);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Options accepted by {@link threadsRoute}. */
|
|
193
|
+
export type ThreadsRouteOptions =
|
|
194
|
+
{ path: `${string}:agentId${string}`; agent?: never } | { path: string; agent: string };
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Register the `<path>` Mastra custom API route. Handles three methods
|
|
198
|
+
* on the same mount:
|
|
199
|
+
*
|
|
200
|
+
* - `GET`: a page of the resource's conversation threads
|
|
201
|
+
* ({@link listThreads}).
|
|
202
|
+
* - `DELETE`: remove the thread named by the thread-selection header
|
|
203
|
+
* / `?threadId=` query ({@link deleteThread}). The id is read from
|
|
204
|
+
* `RequestContext` (the auth middleware resolves it the same way it
|
|
205
|
+
* does for streaming and history), so the client deletes any of its
|
|
206
|
+
* threads by stamping the target id - no separate path param.
|
|
207
|
+
* - `PATCH`: rename the thread named by the thread-selection header /
|
|
208
|
+
* `?threadId=` query to the `{ title }` in the JSON body
|
|
209
|
+
* ({@link renameThread}). Targets a thread the same way `DELETE`
|
|
210
|
+
* does; 404s when the thread isn't owned by the caller.
|
|
211
|
+
*
|
|
212
|
+
* Follows the `@mastra/ai-sdk` agent-binding convention: pass `agent`
|
|
213
|
+
* for a fixed-agent mount, or include `:agentId` in the path for
|
|
214
|
+
* dynamic routing. The plugin registers both `/route/threads` (default
|
|
215
|
+
* agent) and `/route/threads/:agentId`.
|
|
216
|
+
*/
|
|
217
|
+
export function threadsRoute(options: ThreadsRouteOptions) {
|
|
218
|
+
const { path } = options;
|
|
219
|
+
const fixedAgent = "agent" in options ? options.agent : undefined;
|
|
220
|
+
if (!fixedAgent && !path.includes(":agentId")) {
|
|
221
|
+
throw new Error(
|
|
222
|
+
"threadsRoute path must include `:agentId` or `agent` must be passed explicitly",
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
// Shared by GET / DELETE: resolve the active agent and the caller's
|
|
226
|
+
// resource id, returning a JSON error response when either is
|
|
227
|
+
// missing. Keeps both handlers thin with identical validation.
|
|
228
|
+
const resolveContext = (c: ContextWithMastra) => {
|
|
229
|
+
const mastra = c.get("mastra");
|
|
230
|
+
const requestContext = c.get("requestContext");
|
|
231
|
+
const agentId = fixedAgent ?? c.req.param("agentId");
|
|
232
|
+
if (!agentId) {
|
|
233
|
+
return { error: c.json({ error: "agentId is required" }, 400) } as const;
|
|
234
|
+
}
|
|
235
|
+
const agent = mastra.getAgentById(agentId);
|
|
236
|
+
if (!agent) {
|
|
237
|
+
return {
|
|
238
|
+
error: c.json({ error: `Unknown agent "${agentId}"` }, 404),
|
|
239
|
+
} as const;
|
|
240
|
+
}
|
|
241
|
+
const resourceId = requestContext.get(MASTRA_RESOURCE_ID_KEY) as string | undefined;
|
|
242
|
+
if (!resourceId) {
|
|
243
|
+
return {
|
|
244
|
+
error: c.json({ error: "resource id missing from request context" }, 400),
|
|
245
|
+
} as const;
|
|
246
|
+
}
|
|
247
|
+
return { agentId, agent, requestContext, resourceId } as const;
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
return [
|
|
251
|
+
registerApiRoute(path, {
|
|
252
|
+
method: "GET",
|
|
253
|
+
handler: async (c: ContextWithMastra) => {
|
|
254
|
+
const ctx = resolveContext(c);
|
|
255
|
+
if ("error" in ctx) return ctx.error;
|
|
256
|
+
const payload = await listThreads({
|
|
257
|
+
agent: ctx.agent,
|
|
258
|
+
resourceId: ctx.resourceId,
|
|
259
|
+
page: parseIntParam(c.req.query("page")),
|
|
260
|
+
perPage: parseIntParam(c.req.query("perPage")),
|
|
261
|
+
});
|
|
262
|
+
return c.json(payload);
|
|
263
|
+
},
|
|
264
|
+
}),
|
|
265
|
+
registerApiRoute(path, {
|
|
266
|
+
method: "DELETE",
|
|
267
|
+
handler: async (c: ContextWithMastra) => {
|
|
268
|
+
const ctx = resolveContext(c);
|
|
269
|
+
if ("error" in ctx) return ctx.error;
|
|
270
|
+
const threadId = ctx.requestContext.get(MASTRA_THREAD_ID_KEY) as string | undefined;
|
|
271
|
+
if (!threadId) {
|
|
272
|
+
return c.json({ error: "thread id missing from request context" }, 400);
|
|
273
|
+
}
|
|
274
|
+
const { deleted } = await deleteThread({
|
|
275
|
+
agent: ctx.agent,
|
|
276
|
+
threadId,
|
|
277
|
+
resourceId: ctx.resourceId,
|
|
278
|
+
});
|
|
279
|
+
const payload: MastraDeleteThreadResponse = {
|
|
280
|
+
ok: true,
|
|
281
|
+
agentId: ctx.agentId,
|
|
282
|
+
threadId,
|
|
283
|
+
deleted,
|
|
284
|
+
};
|
|
285
|
+
return c.json(payload);
|
|
286
|
+
},
|
|
287
|
+
}),
|
|
288
|
+
registerApiRoute(path, {
|
|
289
|
+
method: "PATCH",
|
|
290
|
+
handler: async (c: ContextWithMastra) => {
|
|
291
|
+
const ctx = resolveContext(c);
|
|
292
|
+
if ("error" in ctx) return ctx.error;
|
|
293
|
+
const threadId = ctx.requestContext.get(MASTRA_THREAD_ID_KEY) as string | undefined;
|
|
294
|
+
if (!threadId) {
|
|
295
|
+
return c.json({ error: "thread id missing from request context" }, 400);
|
|
296
|
+
}
|
|
297
|
+
const body = wire.MastraUpdateThreadRequestSchema.safeParse(await c.req.json());
|
|
298
|
+
if (!body.success) {
|
|
299
|
+
return c.json({ error: body.error.message }, 400);
|
|
300
|
+
}
|
|
301
|
+
const thread = await renameThread({
|
|
302
|
+
agent: ctx.agent,
|
|
303
|
+
threadId,
|
|
304
|
+
resourceId: ctx.resourceId,
|
|
305
|
+
title: body.data.title,
|
|
306
|
+
});
|
|
307
|
+
if (!thread) {
|
|
308
|
+
return c.json({ error: `Unknown thread "${threadId}"` }, 404);
|
|
309
|
+
}
|
|
310
|
+
const payload: MastraUpdateThreadResponse = {
|
|
311
|
+
ok: true,
|
|
312
|
+
agentId: ctx.agentId,
|
|
313
|
+
thread,
|
|
314
|
+
};
|
|
315
|
+
return c.json(payload);
|
|
316
|
+
},
|
|
317
|
+
}),
|
|
318
|
+
];
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Coerce a Mastra `StorageThreadType` into the JSON-safe wire shape. */
|
|
322
|
+
function toWireThread(thread: StorageThreadType): MastraThread {
|
|
323
|
+
return {
|
|
324
|
+
id: thread.id,
|
|
325
|
+
...(thread.title ? { title: thread.title } : {}),
|
|
326
|
+
resourceId: thread.resourceId,
|
|
327
|
+
createdAt: toIso(thread.createdAt),
|
|
328
|
+
updatedAt: toIso(thread.updatedAt),
|
|
329
|
+
...(thread.metadata ? { metadata: thread.metadata } : {}),
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** Render a storage timestamp as an ISO-8601 string for the wire. */
|
|
334
|
+
function toIso(value: Date | string | number): string {
|
|
335
|
+
if (value instanceof Date) return value.toISOString();
|
|
336
|
+
const parsed = new Date(value);
|
|
337
|
+
return Number.isNaN(parsed.getTime()) ? new Date(0).toISOString() : parsed.toISOString();
|
|
338
|
+
}
|