@dbx-tools/appkit-mastra 0.6.218 → 0.6.220

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.
Files changed (46) hide show
  1. package/README.md +72 -25
  2. package/index.ts +4 -7
  3. package/lib/index.d.ts +4 -7
  4. package/lib/index.js +4 -5
  5. package/lib/src/agents.d.ts +15 -6
  6. package/lib/src/agents.js +30 -12
  7. package/lib/src/chat.d.ts +7 -0
  8. package/lib/src/chat.js +19 -0
  9. package/lib/src/config.d.ts +2 -2
  10. package/lib/src/config.js +1 -1
  11. package/lib/src/genie.js +5 -4
  12. package/lib/src/memory.d.ts +2 -2
  13. package/lib/src/memory.js +2 -2
  14. package/lib/src/model.d.ts +2 -0
  15. package/lib/src/model.js +7 -1
  16. package/lib/src/plugin.d.ts +1 -1
  17. package/lib/src/plugin.js +3 -31
  18. package/lib/src/processors.d.ts +4 -28
  19. package/lib/src/processors.js +4 -61
  20. package/lib/src/server.d.ts +10 -21
  21. package/lib/src/server.js +52 -28
  22. package/lib/src/serving-sanitize.d.ts +8 -5
  23. package/lib/src/serving-sanitize.js +16 -11
  24. package/lib/src/trace-io.js +7 -3
  25. package/lib/src/writer.d.ts +7 -7
  26. package/lib/src/writer.js +12 -9
  27. package/lib/tsconfig.tsbuildinfo +1 -1
  28. package/package.json +23 -22
  29. package/src/agents.ts +92 -27
  30. package/src/chat.ts +20 -0
  31. package/src/config.ts +5 -2
  32. package/src/genie.ts +7 -11
  33. package/src/memory.ts +8 -8
  34. package/src/model.ts +7 -0
  35. package/src/plugin.ts +2 -30
  36. package/src/processors.ts +4 -66
  37. package/src/server.ts +49 -27
  38. package/src/serving-sanitize.ts +14 -10
  39. package/src/trace-io.ts +7 -2
  40. package/src/writer.ts +15 -11
  41. package/lib/src/history.d.ts +0 -93
  42. package/lib/src/history.js +0 -231
  43. package/lib/src/threads.d.ts +0 -104
  44. package/lib/src/threads.js +0 -264
  45. package/src/history.ts +0 -270
  46. package/src/threads.ts +0 -309
package/src/history.ts DELETED
@@ -1,270 +0,0 @@
1
- /**
2
- * Thread history loader 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 `recall` a page of `MastraDBMessage`s,
6
- * and converts the result to AI SDK V5 `UIMessage`s with the official
7
- * {@link toAISdkV5Messages} helper from `@mastra/ai-sdk/ui`. No direct
8
- * database reads.
9
- *
10
- * The route is registered through {@link historyRoute} as a Mastra
11
- * `registerApiRoute` so it sits in the same dispatcher pipeline as
12
- * the standard agent routes. That means the `MastraServer` auth
13
- * middleware (in `./server.ts`) has already populated `RequestContext` with
14
- * `MASTRA_THREAD_ID_KEY` and `MASTRA_RESOURCE_ID_KEY` by the time
15
- * the handler runs - no cookie or user lookups happen here, and the
16
- * session-cookie logic stays the single source of truth in `server.ts`.
17
- *
18
- * @module
19
- */
20
-
21
- import { error, log } from "@dbx-tools/shared-core";
22
- import type {
23
- MastraClearHistoryResponse,
24
- MastraHistoryResponse,
25
- MastraHistoryUIMessage,
26
- } from "@dbx-tools/shared-mastra";
27
- import { toAISdkV5Messages } from "@mastra/ai-sdk/ui";
28
- import type { Agent } from "@mastra/core/agent";
29
- import type { MastraDBMessage } from "@mastra/core/agent/message-list";
30
- import type { ContextWithMastra } from "@mastra/core/server";
31
- import { registerApiRoute } from "@mastra/core/server";
32
-
33
- import {
34
- resolveAgentRequestContext,
35
- resolveAgentRouteOptions,
36
- type AgentRouteOptions,
37
- } from "./_agent-route-context.ts";
38
- import { clampPerPage, parseIntParam } from "./pagination.ts";
39
-
40
- const logger = log.logger("mastra/history");
41
-
42
- /** Default history page size; matches the Mastra storage default. */
43
- const DEFAULT_PER_PAGE = 20;
44
- /** Hard cap so a misbehaving client can't fetch the whole thread at once. */
45
- const MAX_PER_PAGE = 200;
46
-
47
- /** Inputs accepted by {@link loadHistory}. */
48
- export interface LoadHistoryOptions {
49
- agent: Agent;
50
- threadId: string;
51
- resourceId: string;
52
- page?: number;
53
- perPage?: number;
54
- /** When true, returns the *oldest* page first (chronological). */
55
- ascending?: boolean;
56
- }
57
-
58
- /**
59
- * Fetch a page of UI-formatted messages for a thread.
60
- *
61
- * Uses the agent's resolved `Memory` (`getMemory()`) so per-agent
62
- * storage namespaces (`mastra_<agentId>` schemas) and any future
63
- * memory-side filters apply automatically. When the agent has no
64
- * memory configured the response is a successful empty page so
65
- * callers don't have to special-case stateless agents.
66
- *
67
- * Pagination is descending-by-default: page 0 is the most recent
68
- * page, page 1 the page before that, etc. The returned `uiMessages`
69
- * are always re-sorted into chronological order (oldest -> newest)
70
- * so the client can prepend them above the existing transcript
71
- * without sorting locally.
72
- */
73
- export async function loadHistory(opts: LoadHistoryOptions): Promise<MastraHistoryResponse> {
74
- const perPage = clampPerPage(opts.perPage, {
75
- fallback: DEFAULT_PER_PAGE,
76
- max: MAX_PER_PAGE,
77
- });
78
- const page = Math.max(0, Math.trunc(opts.page ?? 0));
79
- const memory = await opts.agent.getMemory();
80
- if (!memory) {
81
- logger.debug("recall:no-memory", { agentId: opts.agent.id, threadId: opts.threadId });
82
- return { uiMessages: [], page, perPage, total: 0, hasMore: false };
83
- }
84
- const startedAt = Date.now();
85
- const result = await memory.recall({
86
- threadId: opts.threadId,
87
- resourceId: opts.resourceId,
88
- page,
89
- perPage,
90
- orderBy: {
91
- field: "createdAt",
92
- direction: opts.ascending ? "ASC" : "DESC",
93
- },
94
- });
95
- const chronological = sortChronological(result.messages);
96
- const uiMessages = toAISdkV5Messages(chronological) as unknown as MastraHistoryUIMessage[];
97
- logger.debug("recall:done", {
98
- agentId: opts.agent.id,
99
- threadId: opts.threadId,
100
- page,
101
- perPage,
102
- returned: uiMessages.length,
103
- total: result.total,
104
- hasMore: result.hasMore,
105
- elapsedMs: Date.now() - startedAt,
106
- });
107
- return {
108
- uiMessages,
109
- page,
110
- perPage,
111
- total: result.total,
112
- hasMore: result.hasMore,
113
- };
114
- }
115
-
116
- /** Inputs accepted by {@link clearHistory}. */
117
- export interface ClearHistoryOptions {
118
- agent: Agent;
119
- threadId: string;
120
- resourceId: string;
121
- }
122
-
123
- /**
124
- * Wipe every persisted message tied to a thread. Returns the count
125
- * of messages that were on the thread at delete time so the caller
126
- * can render a "cleared N messages" affordance without an
127
- * additional round-trip.
128
- *
129
- * Agents without a configured `Memory` resolve to a no-op (count
130
- * 0), matching {@link loadHistory}'s "stateless agents return an
131
- * empty page" stance so callers don't have to special-case them.
132
- * Threads that don't exist yet are also a successful no-op - the
133
- * operation is idempotent so the UI can fire-and-forget without
134
- * tracking thread existence.
135
- */
136
- export async function clearHistory(opts: ClearHistoryOptions): Promise<{ cleared: number }> {
137
- const memory = await opts.agent.getMemory();
138
- if (!memory) {
139
- logger.debug("clear:no-memory", { agentId: opts.agent.id, threadId: opts.threadId });
140
- return { cleared: 0 };
141
- }
142
- const existing = await memory.getThreadById({ threadId: opts.threadId });
143
- if (!existing || existing.resourceId !== opts.resourceId) {
144
- logger.debug("clear:not-owned", {
145
- agentId: opts.agent.id,
146
- threadId: opts.threadId,
147
- found: existing !== null,
148
- });
149
- return { cleared: 0 };
150
- }
151
- // Mastra's `deleteThread` cascades to the message table, so we
152
- // can't ask for a count after the fact. Read it pre-delete with a
153
- // one-page recall sized to fit common threads in a single round
154
- // trip; the value is for telemetry / UI, not correctness.
155
- let cleared = 0;
156
- try {
157
- const probe = await memory.recall({
158
- threadId: opts.threadId,
159
- resourceId: opts.resourceId,
160
- page: 0,
161
- perPage: 1,
162
- });
163
- cleared = probe.total;
164
- } catch (err) {
165
- // A missing-thread error is the happy-path "nothing to count";
166
- // every other error is logged but doesn't block the delete.
167
- logger.debug("clear:probe-failed", {
168
- agentId: opts.agent.id,
169
- threadId: opts.threadId,
170
- error: error.errorMessage(err),
171
- });
172
- }
173
-
174
- const startedAt = Date.now();
175
- await memory.deleteThread(opts.threadId);
176
- logger.info("clear:done", {
177
- agentId: opts.agent.id,
178
- threadId: opts.threadId,
179
- cleared,
180
- elapsedMs: Date.now() - startedAt,
181
- });
182
- return { cleared };
183
- }
184
-
185
- /** Options accepted by {@link historyRoute}. */
186
- export type HistoryRouteOptions = AgentRouteOptions;
187
-
188
- /**
189
- * Register the `<path>` Mastra custom API route. Handles two
190
- * methods on the same mount:
191
- *
192
- * - `GET`: return a page of AI SDK V5 `UIMessage`s for the
193
- * caller's current thread ({@link loadHistory}).
194
- * - `DELETE`: wipe every persisted message on the caller's
195
- * thread ({@link clearHistory}). The session cookie that
196
- * anchors the thread id is left alone so the user keeps the
197
- * same thread - only the contents go away.
198
- *
199
- * Follows the `@mastra/ai-sdk` `chatRoute` convention for agent
200
- * binding: pass `agent` for a fixed-agent mount, or include
201
- * `:agentId` in the path for dynamic routing. The plugin registers
202
- * both `/route/history` (default agent) and `/route/history/:agentId`.
203
- *
204
- * The handler reads `threadId` and `resourceId` from `RequestContext`
205
- * (populated upstream by `MastraServer.registerAuthMiddleware`), so
206
- * no cookie or user lookups happen here.
207
- */
208
- export function historyRoute(options: HistoryRouteOptions) {
209
- const { path, fixedAgent } = resolveAgentRouteOptions(options, "historyRoute.path");
210
-
211
- return [
212
- registerApiRoute(path, {
213
- method: "GET",
214
- handler: async (c: ContextWithMastra) => {
215
- const ctx = resolveAgentRequestContext(c, { fixedAgent, threadId: "required" });
216
- if ("error" in ctx) return ctx.error;
217
- const payload = await loadHistory({
218
- agent: ctx.agent,
219
- threadId: ctx.threadId,
220
- resourceId: ctx.resourceId,
221
- page: parseIntParam(c.req.query("page")),
222
- perPage: parseIntParam(c.req.query("perPage")),
223
- });
224
- return c.json(payload);
225
- },
226
- }),
227
- registerApiRoute(path, {
228
- method: "DELETE",
229
- handler: async (c: ContextWithMastra) => {
230
- const ctx = resolveAgentRequestContext(c, { fixedAgent, threadId: "required" });
231
- if ("error" in ctx) return ctx.error;
232
- const { cleared } = await clearHistory({
233
- agent: ctx.agent,
234
- threadId: ctx.threadId,
235
- resourceId: ctx.resourceId,
236
- });
237
- const payload: MastraClearHistoryResponse = {
238
- ok: true,
239
- agentId: ctx.agentId,
240
- threadId: ctx.threadId,
241
- cleared,
242
- };
243
- return c.json(payload);
244
- },
245
- }),
246
- ];
247
- }
248
-
249
- /**
250
- * Sort messages oldest-first by `createdAt`, falling back to whatever
251
- * order the storage returned them in. The native `recall` call honors
252
- * `orderBy` but doesn't guarantee a stable secondary sort, so we
253
- * normalize here before handing the page to the AI SDK converter.
254
- */
255
- function sortChronological(messages: MastraDBMessage[]): MastraDBMessage[] {
256
- return [...messages].sort((a, b) => {
257
- const ta = toEpoch(a.createdAt);
258
- const tb = toEpoch(b.createdAt);
259
- return ta - tb;
260
- });
261
- }
262
-
263
- function toEpoch(value: unknown): number {
264
- if (value instanceof Date) return value.getTime();
265
- if (typeof value === "string" || typeof value === "number") {
266
- const parsed = new Date(value).getTime();
267
- return Number.isNaN(parsed) ? 0 : parsed;
268
- }
269
- return 0;
270
- }
package/src/threads.ts DELETED
@@ -1,309 +0,0 @@
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
- * @module
22
- */
23
-
24
- import { log } from "@dbx-tools/shared-core";
25
- import {
26
- wire,
27
- type MastraDeleteThreadResponse,
28
- type MastraThread,
29
- type MastraThreadsResponse,
30
- type MastraUpdateThreadResponse,
31
- } from "@dbx-tools/shared-mastra";
32
- import type { Agent } from "@mastra/core/agent";
33
- import type { StorageThreadType } from "@mastra/core/memory";
34
- import type { ContextWithMastra } from "@mastra/core/server";
35
- import { registerApiRoute } from "@mastra/core/server";
36
-
37
- import {
38
- resolveAgentRequestContext,
39
- resolveAgentRouteOptions,
40
- type AgentRouteOptions,
41
- } from "./_agent-route-context.ts";
42
- import { clampPerPage, parseIntParam } from "./pagination.ts";
43
- import { invalidFields } from "./validation.ts";
44
-
45
- const logger = log.logger("mastra/threads");
46
-
47
- /** Default threads page size. */
48
- const DEFAULT_PER_PAGE = 30;
49
- /** Hard cap so a misbehaving client can't fetch every thread at once. */
50
- const MAX_PER_PAGE = 200;
51
- /** Stable client message for a rename body that fails schema validation. */
52
- const INVALID_RENAME_MESSAGE = "Invalid thread rename request";
53
-
54
- /** Inputs accepted by {@link listThreads}. */
55
- export interface ListThreadsOptions {
56
- agent: Agent;
57
- resourceId: string;
58
- page?: number;
59
- perPage?: number;
60
- }
61
-
62
- /**
63
- * Fetch a page of the resource's conversation threads, newest
64
- * (`updatedAt` DESC) first.
65
- *
66
- * Uses the agent's resolved `Memory` (`getMemory()`) so the per-agent
67
- * storage namespace (`mastra_<agentId>` schema) applies automatically.
68
- * When the agent has no memory configured the response is a successful
69
- * empty page so callers don't have to special-case stateless agents.
70
- */
71
- export async function listThreads(opts: ListThreadsOptions): Promise<MastraThreadsResponse> {
72
- const perPage = clampPerPage(opts.perPage, {
73
- fallback: DEFAULT_PER_PAGE,
74
- max: MAX_PER_PAGE,
75
- });
76
- const page = Math.max(0, Math.trunc(opts.page ?? 0));
77
- const memory = await opts.agent.getMemory();
78
- if (!memory) {
79
- logger.debug("list:no-memory", { agentId: opts.agent.id });
80
- return { threads: [], page, perPage, total: 0, hasMore: false };
81
- }
82
- const startedAt = Date.now();
83
- const result = await memory.listThreads({
84
- filter: { resourceId: opts.resourceId },
85
- page,
86
- perPage,
87
- orderBy: { field: "updatedAt", direction: "DESC" },
88
- });
89
- const threads = result.threads.map(toWireThread);
90
- logger.debug("list:done", {
91
- agentId: opts.agent.id,
92
- resourceId: opts.resourceId,
93
- page,
94
- perPage,
95
- returned: threads.length,
96
- total: result.total,
97
- hasMore: result.hasMore,
98
- elapsedMs: Date.now() - startedAt,
99
- });
100
- return {
101
- threads,
102
- page,
103
- perPage,
104
- total: result.total,
105
- hasMore: result.hasMore,
106
- };
107
- }
108
-
109
- /** Inputs accepted by {@link deleteThread}. */
110
- export interface DeleteThreadOptions {
111
- agent: Agent;
112
- threadId: string;
113
- resourceId: string;
114
- }
115
-
116
- /**
117
- * Delete a single named thread (and every message on it).
118
- *
119
- * Ownership is enforced: the thread is only removed when it belongs to
120
- * the calling resource, so a client can't delete another user's
121
- * conversation by guessing its id. A thread that doesn't exist (or
122
- * isn't owned by the caller) is a successful no-op (`deleted: false`)
123
- * so the UI can fire-and-forget.
124
- */
125
- export async function deleteThread(opts: DeleteThreadOptions): Promise<{ deleted: boolean }> {
126
- const memory = await opts.agent.getMemory();
127
- if (!memory) {
128
- logger.debug("delete:no-memory", { agentId: opts.agent.id });
129
- return { deleted: false };
130
- }
131
- // Confirm the thread exists and is owned by the caller before
132
- // deleting; never let a guessed id touch another resource's data.
133
- const existing = await memory.getThreadById({ threadId: opts.threadId });
134
- if (!existing || existing.resourceId !== opts.resourceId) {
135
- logger.debug("delete:not-owned", {
136
- agentId: opts.agent.id,
137
- threadId: opts.threadId,
138
- found: existing !== null,
139
- });
140
- return { deleted: false };
141
- }
142
- const startedAt = Date.now();
143
- await memory.deleteThread(opts.threadId);
144
- logger.info("delete:done", {
145
- agentId: opts.agent.id,
146
- threadId: opts.threadId,
147
- elapsedMs: Date.now() - startedAt,
148
- });
149
- return { deleted: true };
150
- }
151
-
152
- /** Inputs accepted by {@link renameThread}. */
153
- export interface RenameThreadOptions {
154
- agent: Agent;
155
- threadId: string;
156
- resourceId: string;
157
- title: string;
158
- }
159
-
160
- /**
161
- * Rename a single thread, returning the updated wire thread.
162
- *
163
- * Ownership is enforced the same way {@link deleteThread} enforces it:
164
- * the title is only changed when the thread belongs to the calling
165
- * resource, so a client can't rename another user's conversation by
166
- * guessing its id. Existing thread `metadata` is preserved untouched
167
- * (Mastra's `updateThread` replaces the row, so it must be passed back
168
- * in). Returns `null` when the thread doesn't exist, isn't owned by the
169
- * caller, or the agent has no memory configured, letting the route map
170
- * that to a 404.
171
- */
172
- export async function renameThread(opts: RenameThreadOptions): Promise<MastraThread | null> {
173
- const memory = await opts.agent.getMemory();
174
- if (!memory) {
175
- logger.debug("rename:no-memory", { agentId: opts.agent.id });
176
- return null;
177
- }
178
- const existing = await memory.getThreadById({ threadId: opts.threadId });
179
- if (!existing || existing.resourceId !== opts.resourceId) {
180
- logger.debug("rename:not-owned", {
181
- agentId: opts.agent.id,
182
- threadId: opts.threadId,
183
- found: existing !== null,
184
- });
185
- return null;
186
- }
187
- const startedAt = Date.now();
188
- const updated = await memory.updateThread({
189
- id: opts.threadId,
190
- title: opts.title,
191
- metadata: existing.metadata ?? {},
192
- });
193
- logger.info("rename:done", {
194
- agentId: opts.agent.id,
195
- threadId: opts.threadId,
196
- elapsedMs: Date.now() - startedAt,
197
- });
198
- return toWireThread(updated);
199
- }
200
-
201
- /** Options accepted by {@link threadsRoute}. */
202
- export type ThreadsRouteOptions = AgentRouteOptions;
203
-
204
- /**
205
- * Register the `<path>` Mastra custom API route. Handles three methods
206
- * on the same mount:
207
- *
208
- * - `GET`: a page of the resource's conversation threads
209
- * ({@link listThreads}).
210
- * - `DELETE`: remove the thread named by the thread-selection header
211
- * / `?threadId=` query ({@link deleteThread}). The id is read from
212
- * `RequestContext` (the auth middleware resolves it the same way it
213
- * does for streaming and history), so the client deletes any of its
214
- * threads by stamping the target id - no separate path param.
215
- * - `PATCH`: rename the thread named by the thread-selection header /
216
- * `?threadId=` query to the `{ title }` in the JSON body
217
- * ({@link renameThread}). Targets a thread the same way `DELETE`
218
- * does; 404s when the thread isn't owned by the caller.
219
- *
220
- * Follows the `@mastra/ai-sdk` agent-binding convention: pass `agent`
221
- * for a fixed-agent mount, or include `:agentId` in the path for
222
- * dynamic routing. The plugin registers both `/route/threads` (default
223
- * agent) and `/route/threads/:agentId`.
224
- */
225
- export function threadsRoute(options: ThreadsRouteOptions) {
226
- const { path, fixedAgent } = resolveAgentRouteOptions(options, "threadsRoute.path");
227
-
228
- return [
229
- registerApiRoute(path, {
230
- method: "GET",
231
- handler: async (c: ContextWithMastra) => {
232
- const ctx = resolveAgentRequestContext(c, { fixedAgent });
233
- if ("error" in ctx) return ctx.error;
234
- const payload = await listThreads({
235
- agent: ctx.agent,
236
- resourceId: ctx.resourceId,
237
- page: parseIntParam(c.req.query("page")),
238
- perPage: parseIntParam(c.req.query("perPage")),
239
- });
240
- return c.json(payload);
241
- },
242
- }),
243
- registerApiRoute(path, {
244
- method: "DELETE",
245
- handler: async (c: ContextWithMastra) => {
246
- const ctx = resolveAgentRequestContext(c, { fixedAgent, threadId: "required" });
247
- if ("error" in ctx) return ctx.error;
248
- const { deleted } = await deleteThread({
249
- agent: ctx.agent,
250
- threadId: ctx.threadId,
251
- resourceId: ctx.resourceId,
252
- });
253
- const payload: MastraDeleteThreadResponse = {
254
- ok: true,
255
- agentId: ctx.agentId,
256
- threadId: ctx.threadId,
257
- deleted,
258
- };
259
- return c.json(payload);
260
- },
261
- }),
262
- registerApiRoute(path, {
263
- method: "PATCH",
264
- handler: async (c: ContextWithMastra) => {
265
- const ctx = resolveAgentRequestContext(c, { fixedAgent, threadId: "required" });
266
- if ("error" in ctx) return ctx.error;
267
- const body = wire.MastraUpdateThreadRequestSchema.safeParse(await c.req.json());
268
- if (!body.success) {
269
- logger.warn("rename:invalid", { error: body.error.message });
270
- return c.json({ error: INVALID_RENAME_MESSAGE, fields: invalidFields(body.error) }, 400);
271
- }
272
- const thread = await renameThread({
273
- agent: ctx.agent,
274
- threadId: ctx.threadId,
275
- resourceId: ctx.resourceId,
276
- title: body.data.title,
277
- });
278
- if (!thread) {
279
- return c.json({ error: `Unknown thread "${ctx.threadId}"` }, 404);
280
- }
281
- const payload: MastraUpdateThreadResponse = {
282
- ok: true,
283
- agentId: ctx.agentId,
284
- thread,
285
- };
286
- return c.json(payload);
287
- },
288
- }),
289
- ];
290
- }
291
-
292
- /** Coerce a Mastra `StorageThreadType` into the JSON-safe wire shape. */
293
- function toWireThread(thread: StorageThreadType): MastraThread {
294
- return {
295
- id: thread.id,
296
- ...(thread.title ? { title: thread.title } : {}),
297
- resourceId: thread.resourceId,
298
- createdAt: toIso(thread.createdAt),
299
- updatedAt: toIso(thread.updatedAt),
300
- ...(thread.metadata ? { metadata: thread.metadata } : {}),
301
- };
302
- }
303
-
304
- /** Render a storage timestamp as an ISO-8601 string for the wire. */
305
- function toIso(value: Date | string | number): string {
306
- if (value instanceof Date) return value.toISOString();
307
- const parsed = new Date(value);
308
- return Number.isNaN(parsed.getTime()) ? new Date(0).toISOString() : parsed.toISOString();
309
- }