@mastra/core 1.5.0-alpha.1 → 1.5.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/CHANGELOG.md +364 -0
- package/dist/agent/index.cjs +8 -8
- package/dist/agent/index.js +1 -1
- package/dist/{chunk-I3AWF54W.js → chunk-4GB2GS4S.js} +3 -3
- package/dist/{chunk-I3AWF54W.js.map → chunk-4GB2GS4S.js.map} +1 -1
- package/dist/{chunk-RH2K66O2.cjs → chunk-7S6LA43E.cjs} +3 -3
- package/dist/{chunk-RH2K66O2.cjs.map → chunk-7S6LA43E.cjs.map} +1 -1
- package/dist/{chunk-IJIE3ZID.cjs → chunk-7WC7ALDW.cjs} +6 -6
- package/dist/{chunk-IJIE3ZID.cjs.map → chunk-7WC7ALDW.cjs.map} +1 -1
- package/dist/{chunk-E2FHTXAI.cjs → chunk-CQ4Z6ZAV.cjs} +5 -5
- package/dist/{chunk-E2FHTXAI.cjs.map → chunk-CQ4Z6ZAV.cjs.map} +1 -1
- package/dist/{chunk-GEDGDKQ6.js → chunk-D57U4II4.js} +7 -7
- package/dist/{chunk-GEDGDKQ6.js.map → chunk-D57U4II4.js.map} +1 -1
- package/dist/{chunk-5EOLBHHS.js → chunk-DST75PA4.js} +4 -4
- package/dist/{chunk-5EOLBHHS.js.map → chunk-DST75PA4.js.map} +1 -1
- package/dist/{chunk-BKQAP27M.cjs → chunk-G5JVVFIG.cjs} +5 -5
- package/dist/{chunk-BKQAP27M.cjs.map → chunk-G5JVVFIG.cjs.map} +1 -1
- package/dist/{chunk-A7V2NSY3.js → chunk-MZIMV2BB.js} +3 -3
- package/dist/{chunk-A7V2NSY3.js.map → chunk-MZIMV2BB.js.map} +1 -1
- package/dist/{chunk-JWG272ZZ.cjs → chunk-NUV3BLRH.cjs} +15 -15
- package/dist/{chunk-JWG272ZZ.cjs.map → chunk-NUV3BLRH.cjs.map} +1 -1
- package/dist/{chunk-FTBLAVTF.cjs → chunk-OQ5LZ6OV.cjs} +46 -46
- package/dist/{chunk-FTBLAVTF.cjs.map → chunk-OQ5LZ6OV.cjs.map} +1 -1
- package/dist/{chunk-PECKKR4C.js → chunk-R3364RAL.js} +3 -3
- package/dist/{chunk-PECKKR4C.js.map → chunk-R3364RAL.js.map} +1 -1
- package/dist/{chunk-IBNCZTNQ.js → chunk-YV2YGQRY.js} +3 -3
- package/dist/{chunk-IBNCZTNQ.js.map → chunk-YV2YGQRY.js.map} +1 -1
- package/dist/datasets/index.cjs +11 -11
- package/dist/datasets/index.js +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +103 -103
- package/dist/docs/references/docs-workflows-suspend-and-resume.md +1 -1
- package/dist/evals/index.cjs +5 -5
- package/dist/evals/index.js +2 -2
- package/dist/evals/scoreTraces/index.cjs +3 -3
- package/dist/evals/scoreTraces/index.js +1 -1
- package/dist/harness/index.cjs +2 -2
- package/dist/harness/index.js +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.js +1 -1
- package/dist/loop/index.cjs +12 -12
- package/dist/loop/index.js +1 -1
- package/dist/mastra/index.cjs +2 -2
- package/dist/mastra/index.js +1 -1
- package/dist/memory/index.cjs +14 -14
- package/dist/memory/index.js +1 -1
- package/dist/processors/index.cjs +41 -41
- package/dist/processors/index.js +1 -1
- package/dist/relevance/index.cjs +3 -3
- package/dist/relevance/index.js +1 -1
- package/dist/stream/index.cjs +8 -8
- package/dist/stream/index.js +1 -1
- package/dist/tool-loop-agent/index.cjs +4 -4
- package/dist/tool-loop-agent/index.js +1 -1
- package/dist/workflows/evented/index.cjs +10 -10
- package/dist/workflows/evented/index.js +1 -1
- package/dist/workflows/index.cjs +25 -25
- package/dist/workflows/index.js +1 -1
- package/package.json +8 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,369 @@
|
|
|
1
1
|
# @mastra/core
|
|
2
2
|
|
|
3
|
+
## 1.5.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Added `allowedPaths` option to `LocalFilesystem` for granting agents access to specific directories outside `basePath` without disabling containment. ([#13054](https://github.com/mastra-ai/mastra/pull/13054))
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
const workspace = new Workspace({
|
|
11
|
+
filesystem: new LocalFilesystem({
|
|
12
|
+
basePath: './workspace',
|
|
13
|
+
allowedPaths: ['/home/user/.config', '/home/user/documents'],
|
|
14
|
+
}),
|
|
15
|
+
});
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Allowed paths can be updated at runtime using `setAllowedPaths()`:
|
|
19
|
+
|
|
20
|
+
```typescript
|
|
21
|
+
workspace.filesystem.setAllowedPaths(prev => [...prev, '/home/user/new-dir']);
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
This is the recommended approach for least-privilege access — agents can only reach the specific directories you allow, while containment stays enabled for everything else.
|
|
25
|
+
|
|
26
|
+
- Added generic Harness class to @mastra/core for orchestrating agents with modes, state management, built-in tools (ask_user, submit_plan), subagent support, Observational Memory integration, model discovery, and permission-aware tool approval. The Harness provides a reusable foundation for building agent-powered applications with features like thread management, heartbeat monitoring, and event-driven architecture. ([#13245](https://github.com/mastra-ai/mastra/pull/13245))
|
|
27
|
+
|
|
28
|
+
- Added glob pattern support for workspace configuration. The `list_files` tool now accepts a `pattern` parameter for filtering files (e.g., `**/*.ts`, `src/**/*.test.ts`). `autoIndexPaths` accepts glob patterns like `./docs/**/*.md` to selectively index files for BM25 search. Skills paths support globs like `./**/skills` to discover skill directories at any depth, including dot-directories like `.agents/skills`. ([#13023](https://github.com/mastra-ai/mastra/pull/13023))
|
|
29
|
+
|
|
30
|
+
**`list_files` tool with pattern:**
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
// Agent can now use glob patterns to filter files
|
|
34
|
+
const result = await workspace.tools.workspace_list_files({
|
|
35
|
+
path: '/',
|
|
36
|
+
pattern: '**/*.test.ts',
|
|
37
|
+
});
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
**`autoIndexPaths` with globs:**
|
|
41
|
+
|
|
42
|
+
```typescript
|
|
43
|
+
const workspace = new Workspace({
|
|
44
|
+
filesystem: new LocalFilesystem({ basePath: './project' }),
|
|
45
|
+
bm25: true,
|
|
46
|
+
// Only index markdown files under ./docs
|
|
47
|
+
autoIndexPaths: ['./docs/**/*.md'],
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
**Skills paths with globs:**
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
const workspace = new Workspace({
|
|
55
|
+
filesystem: new LocalFilesystem({ basePath: './project' }),
|
|
56
|
+
// Discover any directory named 'skills' within 4 levels of depth
|
|
57
|
+
skills: ['./**/skills'],
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Note: Skills glob discovery walks up to 4 directory levels deep from the glob's static prefix. Use more specific patterns like `./src/**/skills` to narrow the search scope for large workspaces.
|
|
62
|
+
|
|
63
|
+
- Added direct skill path discovery — you can now pass a path directly to a skill directory or SKILL.md file in the workspace skills configuration (e.g., `skills: ['/path/to/my-skill']` or `skills: ['/path/to/my-skill/SKILL.md']`). Previously only parent directories were supported. Also improved error handling when a configured skills path is inaccessible (e.g., permission denied), logging a warning instead of breaking discovery for all skills. ([#13031](https://github.com/mastra-ai/mastra/pull/13031))
|
|
64
|
+
|
|
65
|
+
- Add optional `instruction` field to ObservationalMemory config types ([#13240](https://github.com/mastra-ai/mastra/pull/13240))
|
|
66
|
+
|
|
67
|
+
Adds `instruction?: string` to `ObservationalMemoryObservationConfig` and `ObservationalMemoryReflectionConfig` interfaces, allowing external consumers to pass custom instructions to observational memory.
|
|
68
|
+
|
|
69
|
+
- Added typed workspace providers — `workspace.filesystem` and `workspace.sandbox` now return the concrete types you passed to the constructor, improving autocomplete and eliminating casts. ([#13021](https://github.com/mastra-ai/mastra/pull/13021))
|
|
70
|
+
|
|
71
|
+
When mounts are configured, `workspace.filesystem` returns a typed `CompositeFilesystem<TMounts>` with per-key narrowing via `mounts.get()`.
|
|
72
|
+
|
|
73
|
+
**Before:**
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
const workspace = new Workspace({
|
|
77
|
+
filesystem: new LocalFilesystem({ basePath: '/tmp' }),
|
|
78
|
+
sandbox: new E2BSandbox({ timeout: 60000 }),
|
|
79
|
+
});
|
|
80
|
+
workspace.filesystem; // WorkspaceFilesystem | undefined
|
|
81
|
+
workspace.sandbox; // WorkspaceSandbox | undefined
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
**After:**
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
const workspace = new Workspace({
|
|
88
|
+
filesystem: new LocalFilesystem({ basePath: '/tmp' }),
|
|
89
|
+
sandbox: new E2BSandbox({ timeout: 60000 }),
|
|
90
|
+
});
|
|
91
|
+
workspace.filesystem; // LocalFilesystem
|
|
92
|
+
workspace.sandbox; // E2BSandbox
|
|
93
|
+
|
|
94
|
+
// Mount-aware workspaces get typed per-key access:
|
|
95
|
+
const ws = new Workspace({
|
|
96
|
+
mounts: { '/local': new LocalFilesystem({ basePath: '/tmp' }) },
|
|
97
|
+
});
|
|
98
|
+
ws.filesystem.mounts.get('/local'); // LocalFilesystem
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
- Added support for Vercel AI Gateway in the model router. You can now use `model: 'vercel/google/gemini-3-flash'` with agents and it will route through the official AI SDK gateway provider. ([#13149](https://github.com/mastra-ai/mastra/pull/13149))
|
|
102
|
+
|
|
103
|
+
- Added workspace and skill storage domains with full CRUD, versioning, and implementations across LibSQL, Postgres, and MongoDB. Added `editor.workspace` and `editor.skill` namespaces for managing workspace configurations and skill definitions through the editor. Agents stored in the editor can now reference workspaces (by ID or inline config) and skills, with full hydration to runtime `Workspace` instances during agent resolution. ([#13156](https://github.com/mastra-ai/mastra/pull/13156))
|
|
104
|
+
|
|
105
|
+
**Filesystem-native skill versioning (draft → publish model):**
|
|
106
|
+
|
|
107
|
+
Skills are versioned as filesystem trees with content-addressable blob storage. The editing surface (live filesystem) is separated from the serving surface (versioned blob store), enabling a `draft → publish` workflow:
|
|
108
|
+
- `editor.skill.publish(skillId, source, skillPath)` — Snapshots a skill directory from the filesystem into blob storage, creates a new version with a tree manifest, and sets `activeVersionId`
|
|
109
|
+
- Version switching via `editor.skill.update({ id, activeVersionId })` — Points the skill to a previous version without re-publishing
|
|
110
|
+
- Publishing a skill automatically invalidates cached agents that reference it, so they re-hydrate with the updated version on next access
|
|
111
|
+
|
|
112
|
+
**Agent skill resolution strategies:**
|
|
113
|
+
|
|
114
|
+
Agents can reference skills with different resolution strategies:
|
|
115
|
+
- `strategy: 'latest'` — Resolves the skill's active version (honors `activeVersionId` for rollback)
|
|
116
|
+
- `pin: '<versionId>'` — Pins to a specific version, immune to publishes
|
|
117
|
+
- `strategy: 'live'` — Reads directly from the live filesystem (no blob store)
|
|
118
|
+
|
|
119
|
+
**Blob storage infrastructure:**
|
|
120
|
+
- `BlobStore` abstract class for content-addressable storage keyed by SHA-256 hash
|
|
121
|
+
- `InMemoryBlobStore` for testing
|
|
122
|
+
- LibSQL, Postgres, and MongoDB implementations
|
|
123
|
+
- `S3BlobStore` for storing blobs in S3 or S3-compatible storage (AWS, R2, MinIO, DO Spaces)
|
|
124
|
+
- `BlobStoreProvider` interface and `MastraEditorConfig.blobStores` registry for pluggable blob storage
|
|
125
|
+
- `VersionedSkillSource` and `CompositeVersionedSkillSource` for reading skill files from the blob store at runtime
|
|
126
|
+
|
|
127
|
+
**New storage types:**
|
|
128
|
+
- `StorageWorkspaceSnapshotType` and `StorageSkillSnapshotType` with corresponding input/output types
|
|
129
|
+
- `StorageWorkspaceRef` for ID-based or inline workspace references on agents
|
|
130
|
+
- `StorageSkillConfig` for per-agent skill overrides (`pin`, `strategy`, description, instructions)
|
|
131
|
+
- `SkillVersionTree` and `SkillVersionTreeEntry` for tree manifests
|
|
132
|
+
- `StorageBlobEntry` for content-addressable blob entries
|
|
133
|
+
- `SKILL_BLOBS_SCHEMA` for the `mastra_skill_blobs` table
|
|
134
|
+
|
|
135
|
+
**New editor namespaces:**
|
|
136
|
+
- `editor.workspace` — CRUD for workspace configs, plus `hydrateSnapshotToWorkspace()` for resolving to runtime `Workspace` instances
|
|
137
|
+
- `editor.skill` — CRUD for skill definitions, plus `publish()` for filesystem-to-blob snapshots
|
|
138
|
+
|
|
139
|
+
**Provider registries:**
|
|
140
|
+
- `MastraEditorConfig` accepts `filesystems`, `sandboxes`, and `blobStores` provider registries (keyed by provider ID)
|
|
141
|
+
- Built-in `local` filesystem and sandbox providers are auto-registered
|
|
142
|
+
- `editor.resolveBlobStore()` resolves from provider registry or falls back to the storage backend's blobs domain
|
|
143
|
+
- Providers expose `id`, `name`, `description`, `configSchema` (JSON Schema for UI form rendering), and a factory method
|
|
144
|
+
|
|
145
|
+
**Storage adapter support:**
|
|
146
|
+
- LibSQL: Full `workspaces`, `skills`, and `blobs` domain implementations
|
|
147
|
+
- Postgres: Full `workspaces`, `skills`, and `blobs` domain implementations
|
|
148
|
+
- MongoDB: Full `workspaces`, `skills`, and `blobs` domain implementations
|
|
149
|
+
- All three include `workspace`, `skills`, and `skillsFormat` fields on agent versions
|
|
150
|
+
|
|
151
|
+
**Server endpoints:**
|
|
152
|
+
- `GET/POST/PATCH/DELETE /stored/workspaces` — CRUD for stored workspaces
|
|
153
|
+
- `GET/POST/PATCH/DELETE /stored/skills` — CRUD for stored skills
|
|
154
|
+
- `POST /stored/skills/:id/publish` — Publish a skill from a filesystem source
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
import { MastraEditor } from '@mastra/editor';
|
|
158
|
+
import { s3FilesystemProvider, s3BlobStoreProvider } from '@mastra/s3';
|
|
159
|
+
import { e2bSandboxProvider } from '@mastra/e2b';
|
|
160
|
+
|
|
161
|
+
const editor = new MastraEditor({
|
|
162
|
+
filesystems: { s3: s3FilesystemProvider },
|
|
163
|
+
sandboxes: { e2b: e2bSandboxProvider },
|
|
164
|
+
blobStores: { s3: s3BlobStoreProvider },
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
// Create a skill and publish it
|
|
168
|
+
const skill = await editor.skill.create({
|
|
169
|
+
name: 'Code Review',
|
|
170
|
+
description: 'Reviews code for best practices',
|
|
171
|
+
instructions: 'Analyze the code and provide feedback...',
|
|
172
|
+
});
|
|
173
|
+
await editor.skill.publish(skill.id, source, 'skills/code-review');
|
|
174
|
+
|
|
175
|
+
// Agents resolve skills by strategy
|
|
176
|
+
await editor.agent.create({
|
|
177
|
+
name: 'Dev Assistant',
|
|
178
|
+
model: { provider: 'openai', name: 'gpt-4' },
|
|
179
|
+
workspace: { type: 'id', workspaceId: workspace.id },
|
|
180
|
+
skills: { [skill.id]: { strategy: 'latest' } },
|
|
181
|
+
skillsFormat: 'xml',
|
|
182
|
+
});
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
- Added draft/publish version management for all editor primitives (agents, scorers, MCP clients, prompt blocks). ([#13061](https://github.com/mastra-ai/mastra/pull/13061))
|
|
186
|
+
|
|
187
|
+
**Status filtering on list endpoints** — All list endpoints now accept a `?status=draft|published|archived` query parameter to filter by entity status. Defaults to `published` to preserve backward compatibility.
|
|
188
|
+
|
|
189
|
+
**Draft vs published resolution on get-by-id endpoints** — All get-by-id endpoints now accept `?status=draft` to resolve the entity with its latest (unpublished) version, or `?status=published` (default) to resolve with the active published version.
|
|
190
|
+
|
|
191
|
+
**Edits no longer auto-publish** — When updating any primitive, a new version is created but `activeVersionId` is no longer automatically updated. Edits stay as drafts until explicitly published via the activate endpoint.
|
|
192
|
+
|
|
193
|
+
**Full version management for all primitives** — Scorers, MCP clients, and prompt blocks now have the same version management API that agents have: list versions, create version snapshots, get specific versions, activate/publish, restore from a previous version, delete versions, and compare versions.
|
|
194
|
+
|
|
195
|
+
**New prompt block CRUD routes** — Prompt blocks now have full server routes (`GET /stored/prompt-blocks`, `GET /stored/prompt-blocks/:id`, `POST`, `PATCH`, `DELETE`).
|
|
196
|
+
|
|
197
|
+
**New version endpoints** — Each primitive now exposes 7 version management endpoints under `/stored/{type}/:id/versions` (list, create, get, activate, restore, delete, compare).
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
// Fetch the published version (default behavior, backward compatible)
|
|
201
|
+
const published = await fetch('/api/stored/scorers/my-scorer');
|
|
202
|
+
|
|
203
|
+
// Fetch the draft version for editing in the UI
|
|
204
|
+
const draft = await fetch('/api/stored/scorers/my-scorer?status=draft');
|
|
205
|
+
|
|
206
|
+
// Publish a specific version
|
|
207
|
+
await fetch('/api/stored/scorers/my-scorer/versions/abc123/activate', { method: 'POST' });
|
|
208
|
+
|
|
209
|
+
// Compare two versions
|
|
210
|
+
const diff = await fetch('/api/stored/scorers/my-scorer/versions/compare?from=v1&to=v2');
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
- Added `toModelOutput` support to the agent loop. Tool definitions can now include a `toModelOutput` function that transforms the raw tool result before it's sent to the model, while preserving the raw result in storage. This matches the AI SDK `toModelOutput` convention — the function receives the raw output directly and returns `{ type: 'text', value: string }` or `{ type: 'content', value: ContentPart[] }`. ([#13171](https://github.com/mastra-ai/mastra/pull/13171))
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
import { createTool } from '@mastra/core/tools';
|
|
217
|
+
import { z } from 'zod';
|
|
218
|
+
|
|
219
|
+
const weatherTool = createTool({
|
|
220
|
+
id: 'weather',
|
|
221
|
+
inputSchema: z.object({ city: z.string() }),
|
|
222
|
+
execute: async ({ city }) => ({
|
|
223
|
+
city,
|
|
224
|
+
temperature: 72,
|
|
225
|
+
conditions: 'sunny',
|
|
226
|
+
humidity: 45,
|
|
227
|
+
raw_sensor_data: [0.12, 0.45, 0.78],
|
|
228
|
+
}),
|
|
229
|
+
// The model sees a concise summary instead of the full JSON
|
|
230
|
+
toModelOutput: output => ({
|
|
231
|
+
type: 'text',
|
|
232
|
+
value: `${output.city}: ${output.temperature}°F, ${output.conditions}`,
|
|
233
|
+
}),
|
|
234
|
+
});
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
- Added `mastra_workspace_grep` workspace tool for regex-based content search across files. This complements the existing semantic search tool by providing direct pattern matching with support for case-insensitive search, file filtering by extension, context lines, and result limiting. ([#13010](https://github.com/mastra-ai/mastra/pull/13010))
|
|
238
|
+
|
|
239
|
+
The tool is automatically available when a workspace has a filesystem configured:
|
|
240
|
+
|
|
241
|
+
```typescript
|
|
242
|
+
import { Workspace, WORKSPACE_TOOLS } from '@mastra/core/workspace';
|
|
243
|
+
import { LocalFilesystem } from '@mastra/core/workspace';
|
|
244
|
+
|
|
245
|
+
const workspace = new Workspace({
|
|
246
|
+
filesystem: new LocalFilesystem({ basePath: './my-project' }),
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
// The grep tool is auto-injected and available as:
|
|
250
|
+
// WORKSPACE_TOOLS.SEARCH.GREP → 'mastra_workspace_grep'
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
- Removed `outputSchema` from workspace tools to return raw text instead of JSON, optimizing for token usage and LLM performance. Structured metadata that was previously returned in tool output is now emitted as `data-workspace-metadata` chunks via `writer.custom()`, keeping it available for UI consumption without passing it to the LLM. Tools are also extracted into individual files and can be imported directly (e.g. `import { readFileTool } from '@mastra/core/workspace'`). ([#13166](https://github.com/mastra-ai/mastra/pull/13166))
|
|
254
|
+
|
|
255
|
+
### Patch Changes
|
|
256
|
+
|
|
257
|
+
- dependencies updates: ([#13127](https://github.com/mastra-ai/mastra/pull/13127))
|
|
258
|
+
- Updated dependency [`hono@^4.11.9` ↗︎](https://www.npmjs.com/package/hono/v/4.11.9) (from `^4.11.3`, in `dependencies`)
|
|
259
|
+
|
|
260
|
+
- dependencies updates: ([#13167](https://github.com/mastra-ai/mastra/pull/13167))
|
|
261
|
+
- Updated dependency [`lru-cache@^11.2.6` ↗︎](https://www.npmjs.com/package/lru-cache/v/11.2.6) (from `^11.2.2`, in `dependencies`)
|
|
262
|
+
|
|
263
|
+
- Export `AnyWorkspace` type from `@mastra/core/workspace` for accepting any Workspace regardless of generic parameters. Updates Agent and Mastra to use `AnyWorkspace` so workspaces with typed mounts/sandbox (e.g. E2BSandbox, GCSFilesystem) are accepted without type errors. ([#13155](https://github.com/mastra-ai/mastra/pull/13155))
|
|
264
|
+
|
|
265
|
+
- Update provider registry and model documentation with latest models and providers ([`e37ef84`](https://github.com/mastra-ai/mastra/commit/e37ef8404043c94ca0c8e35ecdedb093b8087878))
|
|
266
|
+
|
|
267
|
+
- Fixed skill processor tools (skill-activate, skill-search, skill-read-reference, skill-read-script, skill-read-asset) being incorrectly suspended for approval when `requireToolApproval: true` is set. These internal tools now bypass the approval check and execute directly. ([#13160](https://github.com/mastra-ai/mastra/pull/13160))
|
|
268
|
+
|
|
269
|
+
- Fixed a bug where `requestContext` metadata was not propagated to child spans. When using `requestContextKeys`, only root spans were enriched with request context values — child spans (e.g. `agent_run` inside a workflow) were missing them. All spans in a trace are now correctly enriched. Fixes #12818. ([#12819](https://github.com/mastra-ai/mastra/pull/12819))
|
|
270
|
+
|
|
271
|
+
- Fixed semantic recall search in Mastra Studio returning no results when using non-default embedding dimensions (e.g., fastembed with 384-dim). The SemanticRecall processor now probes the embedder for its actual output dimension, ensuring the vector index name matches between write and read paths. Previously, the processor defaulted to a 1536-dim index name regardless of the actual embedder, causing a mismatch with the dimension-aware index name used by Studio's search. Fixes #13039 ([#13059](https://github.com/mastra-ai/mastra/pull/13059))
|
|
272
|
+
|
|
273
|
+
- Fixed `CompositeFilesystem` instructions: agents and tools no longer receive an incorrect claim that files written via workspace tools are accessible at sandbox paths. The instructions now accurately describe only the available mounted filesystems. ([#13221](https://github.com/mastra-ai/mastra/pull/13221))
|
|
274
|
+
|
|
275
|
+
- Fixed onChunk callback to receive raw Mastra chunks instead of AI SDK v5 converted chunks for tool results. Also added missing onChunk calls for tool-error chunks and tool-result chunks in mixed-error scenarios. ([#13243](https://github.com/mastra-ai/mastra/pull/13243))
|
|
276
|
+
|
|
277
|
+
- Fixed tool execution errors stopping the agentic loop. The agent now continues after tool errors, allowing the model to see the error and retry with corrected arguments. ([#13242](https://github.com/mastra-ai/mastra/pull/13242))
|
|
278
|
+
|
|
279
|
+
- Fixed conditional rules not being persisted for workflows, agents, and scorers when creating or updating agents in the CMS. Rules configured on these entities are now correctly saved to storage. ([#13044](https://github.com/mastra-ai/mastra/pull/13044))
|
|
280
|
+
|
|
281
|
+
- Added runtime `requestContext` forwarding to tool executions. ([#13094](https://github.com/mastra-ai/mastra/pull/13094))
|
|
282
|
+
|
|
283
|
+
Tools invoked within agentic workflow steps now receive the caller's `requestContext` — including authenticated API clients, feature flags, and user metadata set by middleware. Runtime `requestContext` is preferred over build-time context when both are available.
|
|
284
|
+
|
|
285
|
+
**Why:** Previously, `requestContext` values were silently dropped in two places: (1) the workflow loop stream created a new empty `RequestContext` instead of forwarding the caller's, and (2) `createToolCallStep` didn't pass `requestContext` in tool options. This aligns both the agent generate/stream and agentic workflow paths with the agent network path, where `requestContext` was already forwarded correctly.
|
|
286
|
+
|
|
287
|
+
**Before:** Tools received an empty `requestContext`, losing all values set by the workflow step.
|
|
288
|
+
|
|
289
|
+
```ts
|
|
290
|
+
// requestContext with auth data set in workflow step
|
|
291
|
+
requestContext.set('apiClient', authedClient);
|
|
292
|
+
// tool receives empty RequestContext — apiClient is undefined
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
**After:** Pass `requestContext` via `MastraToolInvocationOptions` and tools receive it.
|
|
296
|
+
|
|
297
|
+
```ts
|
|
298
|
+
// requestContext with auth data flows through to the tool
|
|
299
|
+
requestContext.set('apiClient', authedClient);
|
|
300
|
+
// tool receives the same RequestContext — apiClient is available
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
Fixes #13088
|
|
304
|
+
|
|
305
|
+
- Fixed tsc out-of-memory crash caused by step-schema.d.ts expanding to 50k lines. Added explicit type annotations to all exported Zod schema constants, reducing declaration output from 49,729 to ~500 lines without changing runtime behavior. ([#13229](https://github.com/mastra-ai/mastra/pull/13229))
|
|
306
|
+
|
|
307
|
+
- Fixed TypeScript type generation hanging or running out of memory when packages depend on @mastra/core tool types. Changed ZodLikeSchema from a nominal union type to structural typing, which prevents TypeScript from performing deep comparisons of zod v3/v4 type trees during generic inference. ([#13239](https://github.com/mastra-ai/mastra/pull/13239))
|
|
308
|
+
|
|
309
|
+
- Fixed tool execution errors being emitted as `tool-result` instead of `tool-error` in fullStream. Previously, when a tool's execute function threw an error, the error was caught and returned as a value, causing the stream to emit a `tool-result` chunk containing the error object. Now errors are properly propagated, so the stream emits `tool-error` chunks, allowing consumers (including the `@mastra/ai-sdk` conversion pipeline) to correctly distinguish between successful tool results and failed tool executions. Fixes #13123. ([#13147](https://github.com/mastra-ai/mastra/pull/13147))
|
|
310
|
+
|
|
311
|
+
- Fixed thread title not being generated for pre-created threads. When threads were created before starting a conversation (e.g., for URL routing or storing metadata), the title stayed as a placeholder because the title generation condition checked whether the thread existed rather than whether it had a title. Threads created without an explicit title now get an empty title instead of a placeholder, and title generation fires whenever a thread has no title. Resolves #13145. ([#13151](https://github.com/mastra-ai/mastra/pull/13151))
|
|
312
|
+
|
|
313
|
+
- Fixed `inputData` in `dowhile` and `dountil` loop condition functions to be properly typed as the step's output schema instead of `any`. This means you no longer need to manually cast `inputData` in your loop conditions — TypeScript will now correctly infer the type from your step's `outputSchema`. ([#12977](https://github.com/mastra-ai/mastra/pull/12977))
|
|
314
|
+
|
|
315
|
+
- Migrated MastraCode from the prototype harness to the generic CoreHarness from @mastra/core. The createMastraCode function is now fully configurable with optional parameters for modes, subagents, storage, tools, and more. Removed the deprecated prototype harness implementation. ([#13245](https://github.com/mastra-ai/mastra/pull/13245))
|
|
316
|
+
|
|
317
|
+
- Fixed the writer object being undefined in processOutputStream, allowing output processors to emit custom events to the stream during chunk processing. This enables use cases like streaming moderation results back to the client. ([#13056](https://github.com/mastra-ai/mastra/pull/13056))
|
|
318
|
+
|
|
319
|
+
- Fixed sub-agent tool approval resume flow. When a sub-agent tool required approval and was approved, the agent would restart from scratch instead of resuming, causing an infinite loop. The resume data is now correctly passed through for agent tools so they properly resume after approval. ([#13241](https://github.com/mastra-ai/mastra/pull/13241))
|
|
320
|
+
|
|
321
|
+
- Dataset schemas now appear in the Edit Dataset dialog. Previously the `inputSchema` and `groundTruthSchema` fields were not passed to the dialog, so editing a dataset always showed empty schemas. ([#13175](https://github.com/mastra-ai/mastra/pull/13175))
|
|
322
|
+
|
|
323
|
+
Schema edits in the JSON editor no longer cause the cursor to jump to the top of the field. Typing `{"type": "object"}` in the schema editor now behaves like a normal text input instead of resetting on every keystroke.
|
|
324
|
+
|
|
325
|
+
Validation errors are now surfaced when updating a dataset schema that conflicts with existing items. For example, adding a `required: ["name"]` constraint when existing items lack a `name` field now shows "2 existing item(s) fail validation" in the dialog instead of silently dropping the error.
|
|
326
|
+
|
|
327
|
+
Disabling a dataset schema from the Studio UI now correctly clears it. Previously the server converted `null` (disable) to `undefined` (no change), so the old schema persisted and validation continued.
|
|
328
|
+
|
|
329
|
+
Workflow schemas fetched via `client.getWorkflow().getSchema()` are now correctly parsed. The server serializes schemas with `superjson`, but the client was using plain `JSON.parse`, yielding a `{json: {...}}` wrapper instead of the actual JSON Schema object.
|
|
330
|
+
|
|
331
|
+
- Fixed network mode messages missing metadata for filtering. All internal network messages (sub-agent results, tool execution results, workflow results) now include `metadata.mode: 'network'` in their content metadata, making it possible to filter them from user-facing messages without parsing JSON content. Previously, consumers had to parse the JSON body of each message to check for `isNetwork: true` — now they can simply check `message.content.metadata.mode === 'network'`. Fixes #13106. ([#13144](https://github.com/mastra-ai/mastra/pull/13144))
|
|
332
|
+
|
|
333
|
+
- Fixed sub-agent memory context pollution that caused 'Exhausted all fallback models' errors when using Observational Memory with sub-agents. The parent agent's memory context is now preserved across sub-agent tool execution. ([#13051](https://github.com/mastra-ai/mastra/pull/13051))
|
|
334
|
+
|
|
335
|
+
- CMS draft support with status badges for agents. ([#13194](https://github.com/mastra-ai/mastra/pull/13194))
|
|
336
|
+
- Agent list now resolves the latest (draft) version for each stored agent, showing current edits rather than the last published state.
|
|
337
|
+
- Added `hasDraft` and `activeVersionId` fields to the agent list API response.
|
|
338
|
+
- Agent list badges: "Published" (green) when a published version exists, "Draft" (colored when unpublished changes exist, grayed out otherwise).
|
|
339
|
+
- Added `resolvedVersionId` to all `StorageResolved*Type` types so the server can detect whether the latest version differs from the active version.
|
|
340
|
+
- Added `status` option to `GetByIdOptions` to allow resolving draft vs published versions through the editor layer.
|
|
341
|
+
- Fixed editor cache not being cleared on version activate, restore, and delete — all four versioned domains (agents, scorers, prompt-blocks, mcp-clients) now clear the cache after version mutations.
|
|
342
|
+
- Added `ALTER TABLE` migration for `mastra_agent_versions` in libsql and pg to add newer columns (`mcpClients`, `requestContextSchema`, `workspace`, `skills`, `skillsFormat`).
|
|
343
|
+
|
|
344
|
+
- Added scorer version management and CMS draft/publish flow for scorers. ([#13194](https://github.com/mastra-ai/mastra/pull/13194))
|
|
345
|
+
- Added scorer version methods to the client SDK: `listVersions`, `createVersion`, `getVersion`, `activateVersion`, `restoreVersion`, `deleteVersion`, `compareVersions`.
|
|
346
|
+
- Added `ScorerVersionCombobox` for navigating scorer versions with Published/Draft labels.
|
|
347
|
+
- Scorer edit page now supports Save (draft) and Publish workflows with an "Unpublished changes" indicator.
|
|
348
|
+
- Storage list methods for agents and scorers no longer default to filtering only published entities, allowing drafts to appear in the playground.
|
|
349
|
+
|
|
350
|
+
- Fixed CompositeAuth losing public and protected route configurations from underlying auth providers. Routes marked as public or protected now work correctly when deployed to Mastra Cloud. ([#13086](https://github.com/mastra-ai/mastra/pull/13086))
|
|
351
|
+
|
|
352
|
+
- Trimmed the agent experiment result `output` to only persist relevant fields instead of the entire `FullOutput` blob. The stored output now contains: `text`, `object`, `toolCalls`, `toolResults`, `sources`, `files`, `usage`, `reasoningText`, `traceId`, and `error`. ([#13158](https://github.com/mastra-ai/mastra/pull/13158))
|
|
353
|
+
|
|
354
|
+
Dropped fields like `steps`, `response`, `messages`, `rememberedMessages`, `request`, `providerMetadata`, `warnings`, `scoringData`, `suspendPayload`, and other provider/debugging internals that were duplicated elsewhere or not useful for experiment evaluation.
|
|
355
|
+
|
|
356
|
+
- Fixed `.branch()` condition receiving `undefined` inputData when resuming a suspended nested workflow after `.map()`. ([#13055](https://github.com/mastra-ai/mastra/pull/13055))
|
|
357
|
+
|
|
358
|
+
Previously, when a workflow used `.map()` followed by `.branch()` and a nested workflow inside the branch called `suspend()`, resuming would fail with `TypeError: Cannot read properties of undefined` because the branch conditions were unnecessarily re-evaluated with stale data.
|
|
359
|
+
|
|
360
|
+
Resume now skips condition re-evaluation for `.branch()` entries and goes directly to the correct suspended branch, matching the existing behavior for `.parallel()` entries.
|
|
361
|
+
|
|
362
|
+
Fixes #12982
|
|
363
|
+
|
|
364
|
+
- Updated dependencies [[`1415bcd`](https://github.com/mastra-ai/mastra/commit/1415bcd894baba03e07640b3b1986037db49559d)]:
|
|
365
|
+
- @mastra/schema-compat@1.1.1
|
|
366
|
+
|
|
3
367
|
## 1.5.0-alpha.1
|
|
4
368
|
|
|
5
369
|
### Patch Changes
|
package/dist/agent/index.cjs
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunk7S6LA43E_cjs = require('../chunk-7S6LA43E.cjs');
|
|
4
4
|
var chunkYW54RH77_cjs = require('../chunk-YW54RH77.cjs');
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
Object.defineProperty(exports, "Agent", {
|
|
9
9
|
enumerable: true,
|
|
10
|
-
get: function () { return
|
|
10
|
+
get: function () { return chunk7S6LA43E_cjs.Agent; }
|
|
11
11
|
});
|
|
12
12
|
Object.defineProperty(exports, "TripWire", {
|
|
13
13
|
enumerable: true,
|
|
14
|
-
get: function () { return
|
|
14
|
+
get: function () { return chunk7S6LA43E_cjs.TripWire; }
|
|
15
15
|
});
|
|
16
16
|
Object.defineProperty(exports, "isSupportedLanguageModel", {
|
|
17
17
|
enumerable: true,
|
|
18
|
-
get: function () { return
|
|
18
|
+
get: function () { return chunk7S6LA43E_cjs.isSupportedLanguageModel; }
|
|
19
19
|
});
|
|
20
20
|
Object.defineProperty(exports, "resolveThreadIdFromArgs", {
|
|
21
21
|
enumerable: true,
|
|
22
|
-
get: function () { return
|
|
22
|
+
get: function () { return chunk7S6LA43E_cjs.resolveThreadIdFromArgs; }
|
|
23
23
|
});
|
|
24
24
|
Object.defineProperty(exports, "supportedLanguageModelSpecifications", {
|
|
25
25
|
enumerable: true,
|
|
26
|
-
get: function () { return
|
|
26
|
+
get: function () { return chunk7S6LA43E_cjs.supportedLanguageModelSpecifications; }
|
|
27
27
|
});
|
|
28
28
|
Object.defineProperty(exports, "tryGenerateWithJsonFallback", {
|
|
29
29
|
enumerable: true,
|
|
30
|
-
get: function () { return
|
|
30
|
+
get: function () { return chunk7S6LA43E_cjs.tryGenerateWithJsonFallback; }
|
|
31
31
|
});
|
|
32
32
|
Object.defineProperty(exports, "tryStreamWithJsonFallback", {
|
|
33
33
|
enumerable: true,
|
|
34
|
-
get: function () { return
|
|
34
|
+
get: function () { return chunk7S6LA43E_cjs.tryStreamWithJsonFallback; }
|
|
35
35
|
});
|
|
36
36
|
Object.defineProperty(exports, "MessageList", {
|
|
37
37
|
enumerable: true,
|
package/dist/agent/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { Agent, TripWire, isSupportedLanguageModel, resolveThreadIdFromArgs, supportedLanguageModelSpecifications, tryGenerateWithJsonFallback, tryStreamWithJsonFallback } from '../chunk-
|
|
1
|
+
export { Agent, TripWire, isSupportedLanguageModel, resolveThreadIdFromArgs, supportedLanguageModelSpecifications, tryGenerateWithJsonFallback, tryStreamWithJsonFallback } from '../chunk-MZIMV2BB.js';
|
|
2
2
|
export { MessageList, TypeDetector, aiV5ModelMessageToV2PromptMessage, convertMessages } from '../chunk-OHLVZVIK.js';
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Agent, isSupportedLanguageModel } from './chunk-
|
|
1
|
+
import { Agent, isSupportedLanguageModel } from './chunk-MZIMV2BB.js';
|
|
2
2
|
import { generateId } from './chunk-CPLRD2VP.js';
|
|
3
3
|
import { resolveModelConfig } from './chunk-AIRMLZ43.js';
|
|
4
4
|
import { ToolLoopAgent } from './chunk-CXVMDV2B.js';
|
|
@@ -255,5 +255,5 @@ function toolLoopAgentToMastraAgent(agent, options) {
|
|
|
255
255
|
}
|
|
256
256
|
|
|
257
257
|
export { getSettings, isToolLoopAgentLike, toolLoopAgentToMastraAgent };
|
|
258
|
-
//# sourceMappingURL=chunk-
|
|
259
|
-
//# sourceMappingURL=chunk-
|
|
258
|
+
//# sourceMappingURL=chunk-4GB2GS4S.js.map
|
|
259
|
+
//# sourceMappingURL=chunk-4GB2GS4S.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tool-loop-agent/utils.ts","../src/tool-loop-agent/tool-loop-processor.ts","../src/tool-loop-agent/index.ts"],"names":[],"mappings":";;;;;;AAeO,SAAS,oBAAoB,GAAA,EAAoC;AACtE,EAAA,IAAI,CAAC,KAAK,OAAO,KAAA;AACjB,EAAA,IAAI,GAAA,YAAe,eAAe,OAAO,IAAA;AACzC,EAAA,OACE,SAAA,IAAa,GAAA,IACb,OAAO,GAAA,CAAI,OAAA,KAAY,QAAA,KACtB,GAAA,CAAI,OAAA,KAAY,UAAA,IAAc,GAAA,CAAI,OAAA,CAAQ,UAAA,CAAW,SAAS,CAAA,CAAA;AAEnE;AAMO,SAAS,YAAY,KAAA,EAAgE;AAC1F,EAAA,MAAM,WAAY,KAAA,CAAwE,QAAA;AAC1F,EAAA,IAAI,CAAC,QAAA,EAAU;AACb,IAAA,MAAM,IAAI,MAAM,+FAA+F,CAAA;AAAA,EACjH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AAA,CAAK,2BAAA,CAA4B,iBAAwB,CAAA;AAE9E,QAAA,MAAA,GAAS,EAAE,GAAG,MAAA,EAAQ,GAAG,YAAA,EAAa;AAAA,MACxC;AAAA,IACF;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AACF,CAAA;;;AC1TO,SAAS,0BAAA,CAA2B,OAA0B,OAAA,EAAqC;AACxG,EAAA,MAAM,SAAA,GAAY,IAAI,sBAAA,CAAuB,KAAK,CAAA;AAClD,EAAA,MAAM,WAAA,GAAc,UAAU,cAAA,EAAe;AAC7C,EAAA,MAAM,KAAK,WAAA,CAAY,EAAA,IAAM,SAAS,YAAA,IAAgB,CAAA,gBAAA,EAAmB,YAAY,CAAA,CAAA;AAErF,EAAA,OAAO,IAAI,KAAA,CAAM;AAAA,IACf,GAAG,WAAA;AAAA,IACH,EAAA;AAAA,IACA,IAAA,EAAM,YAAY,IAAA,IAAQ,EAAA;AAAA,IAC1B,eAAA,EAAiB,CAAC,SAAS;AAAA,GAC5B,CAAA;AACH","file":"chunk-I3AWF54W.js","sourcesContent":["import { ToolLoopAgent } from '@internal/ai-v6';\nimport type { ToolLoopAgentSettings } from '@internal/ai-v6';\n\n/**\n * Shape of a ToolLoopAgent-like object for runtime extraction.\n * We use this looser type because TypeScript's structural typing doesn't work\n * well with private properties across different package declarations.\n */\nexport interface ToolLoopAgentLike {\n readonly id?: string;\n readonly version?: string;\n // The settings property is private in ToolLoopAgent but accessible at runtime\n // We don't declare it here since we access it via type casting\n}\n\nexport function isToolLoopAgentLike(obj: any): obj is ToolLoopAgentLike {\n if (!obj) return false;\n if (obj instanceof ToolLoopAgent) return true;\n return (\n 'version' in obj &&\n typeof obj.version === 'string' &&\n (obj.version === 'agent-v1' || obj.version.startsWith('agent-v'))\n );\n}\n\n/**\n * Extracts the settings from a ToolLoopAgent instance.\n * ToolLoopAgent.settings is private in TypeScript but accessible at runtime.\n */\nexport function getSettings(agent: ToolLoopAgentLike): ToolLoopAgentSettings<any, any, any> {\n const settings = (agent as unknown as { settings: ToolLoopAgentSettings<any, any, any> }).settings;\n if (!settings) {\n throw new Error('Could not extract settings from ToolLoopAgent. The agent may be from an incompatible version.');\n }\n return settings;\n}\n","import type {\n ToolLoopAgent,\n AgentCallParameters,\n ModelMessage,\n StepResult,\n ToolLoopAgentSettings,\n} from '@internal/ai-v6';\nimport { isSupportedLanguageModel } from '../agent';\nimport type { AgentExecutionOptions, AgentInstructions } from '../agent';\nimport { resolveModelConfig } from '../llm/model/resolve-model';\nimport type { MastraLanguageModel } from '../llm/model/shared.types';\nimport type { ProcessInputStepArgs, ProcessInputStepResult, Processor } from '../processors';\nimport { getSettings as getToolLoopAgentSettings } from './utils';\nimport type { ToolLoopAgentLike } from './utils';\n\ntype PrepareCallInput = AgentCallParameters<never> &\n Pick<\n ToolLoopAgentSettings<never, any, any>,\n | 'model'\n | 'tools'\n | 'maxOutputTokens'\n | 'temperature'\n | 'topP'\n | 'topK'\n | 'presencePenalty'\n | 'frequencyPenalty'\n | 'stopSequences'\n | 'seed'\n | 'headers'\n | 'instructions'\n | 'stopWhen'\n | 'experimental_telemetry'\n | 'activeTools'\n | 'providerOptions'\n | 'experimental_context'\n | 'experimental_download'\n >;\n\nexport class ToolLoopAgentProcessor implements Processor<'tool-loop-agent-processor'> {\n readonly id = 'tool-loop-agent-processor';\n readonly name = 'ToolLoop to Mastra Agent Processor';\n\n private agent: ToolLoopAgentLike;\n private settings: ToolLoopAgentSettings<any, any, any>;\n private prepareCallResult?: Awaited<ReturnType<NonNullable<ToolLoopAgentSettings<any, any, any>['prepareCall']>>>;\n\n constructor(agent: ToolLoopAgentLike) {\n this.agent = agent;\n this.settings = getToolLoopAgentSettings(agent);\n }\n\n public getAgentConfig() {\n const tools = 'tools' in this.agent ? (this.agent as ToolLoopAgent).tools : undefined;\n\n // Build default options from ToolLoopAgent config params\n const defaultOptions: Omit<AgentExecutionOptions<unknown>, 'abortSignal'> = {};\n\n // AgentExecutionOptions\n if (this.settings.toolChoice) {\n defaultOptions.toolChoice = this.settings.toolChoice;\n }\n if (this.settings.providerOptions) {\n defaultOptions.providerOptions = this.settings.providerOptions;\n }\n // AgentExecutionOptions[\"modelSettings\"]\n if (this.settings.temperature !== undefined) {\n defaultOptions.modelSettings = {\n ...(defaultOptions.modelSettings ?? {}),\n temperature: this.settings.temperature,\n };\n }\n if (this.settings.topP !== undefined) {\n defaultOptions.modelSettings = { ...(defaultOptions.modelSettings ?? {}), topP: this.settings.topP };\n }\n if (this.settings.topK !== undefined) {\n defaultOptions.modelSettings = { ...(defaultOptions.modelSettings ?? {}), topK: this.settings.topK };\n }\n if (this.settings.seed !== undefined) {\n defaultOptions.modelSettings = { ...(defaultOptions.modelSettings ?? {}), seed: this.settings.seed };\n }\n if (this.settings.maxOutputTokens !== undefined) {\n defaultOptions.modelSettings = {\n ...(defaultOptions.modelSettings ?? {}),\n maxOutputTokens: this.settings.maxOutputTokens,\n };\n }\n if (this.settings.presencePenalty !== undefined) {\n defaultOptions.modelSettings = {\n ...(defaultOptions.modelSettings ?? {}),\n presencePenalty: this.settings.presencePenalty,\n };\n }\n if (this.settings.frequencyPenalty !== undefined) {\n defaultOptions.modelSettings = {\n ...(defaultOptions.modelSettings ?? {}),\n frequencyPenalty: this.settings.frequencyPenalty,\n };\n }\n if (this.settings.stopSequences !== undefined) {\n defaultOptions.modelSettings = {\n ...(defaultOptions.modelSettings ?? {}),\n stopSequences: this.settings.stopSequences,\n };\n }\n if (this.settings.stopWhen) {\n // TODO: The callback signatures differ (Types of parameters stepResult and event are incompatible)\n defaultOptions.stopWhen = this.settings.stopWhen as any;\n }\n if (this.settings.onStepFinish) {\n // TODO: The callback signatures differ (Types of parameters stepResult and event are incompatible)\n defaultOptions.onStepFinish = this.settings.onStepFinish as any;\n }\n if (this.settings.onFinish) {\n // TODO: The callback signatures differ (Types of parameters 'event' and 'event' are incompatible)\n defaultOptions.onFinish = this.settings.onFinish as any;\n }\n\n return {\n id: this.settings.id,\n name: this.settings.id,\n instructions: (this.settings.instructions as AgentInstructions) ?? '',\n model: this.settings.model,\n tools,\n maxRetries: this.settings.maxRetries,\n defaultOptions: Object.keys(defaultOptions).length > 0 ? defaultOptions : undefined,\n };\n }\n\n /**\n * Maps prepareCall or prepareStep result to ProcessInputStepResult.\n * Both hooks return similar structures that can override model, tools, activeTools, etc.\n */\n private mapToProcessInputStepResult(\n result: Awaited<ReturnType<NonNullable<ToolLoopAgentSettings<any, any, any>['prepareCall']>>> | undefined,\n ): ProcessInputStepResult {\n if (!result) {\n return {};\n }\n\n const stepResult: ProcessInputStepResult = {};\n\n // Map model (both prepareCall and prepareStep can return this)\n if (result.model) {\n stepResult.model = result.model;\n }\n\n // Map tools (prepareCall can return this)\n if ('tools' in result && result.tools) {\n stepResult.tools = result.tools as Record<string, unknown>;\n }\n\n // Map toolChoice (prepareStep can return this)\n if ('toolChoice' in result && result.toolChoice !== undefined) {\n stepResult.toolChoice = result.toolChoice as ProcessInputStepResult['toolChoice'];\n }\n\n // Map activeTools (both can return this)\n if (result.activeTools) {\n stepResult.activeTools = result.activeTools as string[];\n }\n\n // Map providerOptions (prepareCall can return this)\n if ('providerOptions' in result && result.providerOptions) {\n stepResult.providerOptions = result.providerOptions;\n }\n\n // Map model settings (prepareCall can return individual settings)\n const modelSettings: ProcessInputStepResult['modelSettings'] = {};\n if ('temperature' in result && result.temperature !== undefined) {\n modelSettings.temperature = result.temperature;\n }\n if ('topP' in result && result.topP !== undefined) {\n modelSettings.topP = result.topP;\n }\n if ('topK' in result && result.topK !== undefined) {\n modelSettings.topK = result.topK;\n }\n if ('maxOutputTokens' in result && result.maxOutputTokens !== undefined) {\n modelSettings.maxOutputTokens = result.maxOutputTokens;\n }\n if ('presencePenalty' in result && result.presencePenalty !== undefined) {\n modelSettings.presencePenalty = result.presencePenalty;\n }\n if ('frequencyPenalty' in result && result.frequencyPenalty !== undefined) {\n modelSettings.frequencyPenalty = result.frequencyPenalty;\n }\n if ('stopSequences' in result && result.stopSequences !== undefined) {\n modelSettings.stopSequences = result.stopSequences;\n }\n if ('seed' in result && result.seed !== undefined) {\n modelSettings.seed = result.seed;\n }\n\n if (Object.keys(modelSettings).length > 0) {\n stepResult.modelSettings = modelSettings;\n }\n\n // Map system/instructions to systemMessages\n // prepareCall returns 'instructions', prepareStep returns 'system'\n const systemContent =\n 'instructions' in result ? result.instructions : 'system' in result ? result.system : undefined;\n if (systemContent) {\n // Convert to CoreMessageV4 format\n if (typeof systemContent === 'string') {\n stepResult.systemMessages = [{ role: 'system', content: systemContent }];\n } else if (Array.isArray(systemContent)) {\n stepResult.systemMessages = systemContent.map(msg =>\n typeof msg === 'string' ? { role: 'system' as const, content: msg } : msg,\n );\n } else if (typeof systemContent === 'object' && 'role' in systemContent && 'content' in systemContent) {\n stepResult.systemMessages = [systemContent as { role: 'system'; content: string }];\n }\n }\n\n // Map messages if prepareStep returns them\n // Convert AI SDK ModelMessage[] to MastraDBMessage[]\n if ('messages' in result && result.messages && Array.isArray(result.messages)) {\n // AI SDK v6 ModelMessage is compatible with MessageListInput at runtime\n // stepResult.messages = convertMessages(result.messages as any).to('Mastra.V2');\n stepResult.messages = result.messages as any;\n }\n\n return stepResult;\n }\n\n private async handlePrepareCall(args: ProcessInputStepArgs) {\n if (this.settings.prepareCall) {\n const { model, messages, activeTools, providerOptions, modelSettings, tools } = args;\n // TODO: This should probably happen in processInput, currently calling in processInputStep if stepNumber === 0\n\n // Build the prepareCall input object\n // AI SDK prepareCall expects: AgentCallParameters & Pick<ToolLoopAgentSettings, ...settings>\n const prepareCallInput: PrepareCallInput = {\n // TODO: prepareCall expects messages in AI SDK format, we have them in Mastra format\n messages: messages as unknown as any,\n model,\n tools,\n instructions: this.settings.instructions,\n stopWhen: this.settings.stopWhen,\n activeTools,\n providerOptions,\n\n // Model settings\n temperature: modelSettings?.temperature,\n topP: modelSettings?.topP,\n topK: modelSettings?.topK,\n maxOutputTokens: modelSettings?.maxOutputTokens,\n presencePenalty: modelSettings?.presencePenalty,\n frequencyPenalty: modelSettings?.frequencyPenalty,\n stopSequences: modelSettings?.stopSequences,\n seed: modelSettings?.seed,\n\n // Experimental options\n // experimental_telemetry: this.settings.experimental_telemetry,\n // experimental_context: this.settings.experimental_context,\n // experimental_download: this.settings.experimental_download,\n };\n\n // Call prepareCall and apply any returned overrides\n const prepareCallResult = await this.settings.prepareCall(prepareCallInput as any); // TODO: types\n this.prepareCallResult = prepareCallResult;\n }\n }\n\n private async handlePrepareStep(args: ProcessInputStepArgs, currentResult: ProcessInputStepResult) {\n if (this.settings.prepareStep) {\n const { messages, steps, stepNumber } = args;\n\n let model = args.model;\n if (currentResult.model) {\n const resolvedModel = await resolveModelConfig(currentResult.model);\n if (!isSupportedLanguageModel(resolvedModel)) {\n throw new Error('prepareStep returned an unsupported model version');\n }\n model = resolvedModel;\n }\n\n // Use the model from currentResult if prepareCall overrode it, otherwise use args.model\n\n // Note: We pass messages and steps in Mastra format rather than converting to AI SDK format.\n // This is intentional - most prepareStep callbacks only return overrides and don't inspect\n // the message content. The type casts handle the format difference at runtime.\n const prepareStepInputArgs: {\n /**\n * The steps that have been executed so far.\n */\n steps: Array<StepResult<NoInfer<any>>>;\n /**\n * The number of the step that is being executed.\n */\n stepNumber: number;\n /**\n * The model instance that is being used for this step.\n */\n model: MastraLanguageModel;\n /**\n * The messages that will be sent to the model for the current step.\n * Note: These are in Mastra format (MastraDBMessage[]), not AI SDK ModelMessage format.\n */\n messages: Array<ModelMessage>;\n /**\n * The context passed via the experimental_context setting (experimental).\n */\n experimental_context: unknown;\n } = {\n model,\n // Messages are in Mastra format (MastraDBMessage[])\n messages: messages as any,\n // Steps may have minor type differences in usage properties (inputTokenDetails/outputTokenDetails)\n steps: steps as any,\n stepNumber,\n experimental_context: undefined,\n };\n\n const prepareStepResult = await this.settings.prepareStep(prepareStepInputArgs);\n return prepareStepResult;\n }\n }\n\n async processInputStep(args: ProcessInputStepArgs): Promise<ProcessInputStepResult | undefined | void> {\n const { stepNumber } = args;\n\n if (stepNumber === 0 && this.settings.prepareCall) {\n await this.handlePrepareCall(args);\n }\n\n let result: ProcessInputStepResult = {};\n\n // Apply prepareCall result (only on step 0, already called above)\n if (this.prepareCallResult) {\n const mappedResult = this.mapToProcessInputStepResult(this.prepareCallResult);\n if (Object.keys(mappedResult).length > 0) {\n result = { ...result, ...mappedResult };\n }\n }\n\n // Apply prepareStep result (called on every step)\n // Pass the current result so prepareStep sees any overrides from prepareCall\n if (this.settings.prepareStep) {\n const prepareStepResult = await this.handlePrepareStep(args, result);\n if (prepareStepResult) {\n const mappedResult = this.mapToProcessInputStepResult(prepareStepResult as any);\n // prepareStep overrides prepareCall for this step\n result = { ...result, ...mappedResult };\n }\n }\n\n return result;\n }\n}\n","import { generateId } from '@internal/ai-sdk-v5';\nimport { Agent } from '../agent';\nimport { ToolLoopAgentProcessor } from './tool-loop-processor';\nimport type { ToolLoopAgentLike } from './utils';\nexport { type ToolLoopAgentLike, isToolLoopAgentLike, getSettings } from './utils';\n\n/**\n * Converts an AI SDK v6 ToolLoopAgent instance into a Mastra Agent.\n *\n * This enables users to create a ToolLoopAgent using AI SDK's API\n * while gaining access to Mastra features like memory, processors, scorers, and observability.\n *\n * @example\n * ```typescript\n * import { ToolLoopAgent, tool } from 'ai';\n * import { openai } from '@ai-sdk/openai';\n * import { toolLoopAgentToMastraAgent } from '@mastra/core/tool-loop-agent';\n *\n * const toolLoopAgent = new ToolLoopAgent({\n * id: 'weather-agent',\n * model: openai('gpt-4o'),\n * instructions: 'You are a helpful weather assistant.',\n * tools: { weather: weatherTool },\n * temperature: 0.7,\n * });\n *\n * const mastraAgent = toolLoopAgentToMastraAgent(toolLoopAgent);\n *\n * const result = await mastraAgent.generate({ prompt: 'What is the weather in NYC?' });\n * ```\n *\n * @param agent - The ToolLoopAgent instance\n * @param options - Optional name fallback since Mastra Agent requires id/name but ToolLoopAgent doesn't\n * @returns A Mastra Agent instance\n */\nexport function toolLoopAgentToMastraAgent(agent: ToolLoopAgentLike, options?: { fallbackName?: string }) {\n const processor = new ToolLoopAgentProcessor(agent);\n const agentConfig = processor.getAgentConfig();\n const id = agentConfig.id || options?.fallbackName || `tool-loop-agent-${generateId()}`;\n\n return new Agent({\n ...agentConfig,\n id,\n name: agentConfig.name || id,\n inputProcessors: [processor],\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/tool-loop-agent/utils.ts","../src/tool-loop-agent/tool-loop-processor.ts","../src/tool-loop-agent/index.ts"],"names":[],"mappings":";;;;;;AAeO,SAAS,oBAAoB,GAAA,EAAoC;AACtE,EAAA,IAAI,CAAC,KAAK,OAAO,KAAA;AACjB,EAAA,IAAI,GAAA,YAAe,eAAe,OAAO,IAAA;AACzC,EAAA,OACE,SAAA,IAAa,GAAA,IACb,OAAO,GAAA,CAAI,OAAA,KAAY,QAAA,KACtB,GAAA,CAAI,OAAA,KAAY,UAAA,IAAc,GAAA,CAAI,OAAA,CAAQ,UAAA,CAAW,SAAS,CAAA,CAAA;AAEnE;AAMO,SAAS,YAAY,KAAA,EAAgE;AAC1F,EAAA,MAAM,WAAY,KAAA,CAAwE,QAAA;AAC1F,EAAA,IAAI,CAAC,QAAA,EAAU;AACb,IAAA,MAAM,IAAI,MAAM,+FAA+F,CAAA;AAAA,EACjH;AACA,EAAA,OAAO,QAAA;AACT;;;ACGO,IAAM,yBAAN,MAA+E;AAAA,EAC3E,EAAA,GAAK,2BAAA;AAAA,EACL,IAAA,GAAO,oCAAA;AAAA,EAER,KAAA;AAAA,EACA,QAAA;AAAA,EACA,iBAAA;AAAA,EAER,YAAY,KAAA,EAA0B;AACpC,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AACb,IAAA,IAAA,CAAK,QAAA,GAAW,YAAyB,KAAK,CAAA;AAAA,EAChD;AAAA,EAEO,cAAA,GAAiB;AACtB,IAAA,MAAM,QAAQ,OAAA,IAAW,IAAA,CAAK,KAAA,GAAS,IAAA,CAAK,MAAwB,KAAA,GAAQ,MAAA;AAG5E,IAAA,MAAM,iBAAsE,EA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I,KAAA,CAAM;AAAA,IACf,GAAG,WAAA;AAAA,IACH,EAAA;AAAA,IACA,IAAA,EAAM,YAAY,IAAA,IAAQ,EAAA;AAAA,IAC1B,eAAA,EAAiB,CAAC,SAAS;AAAA,GAC5B,CAAA;AACH","file":"chunk-4GB2GS4S.js","sourcesContent":["import { ToolLoopAgent } from '@internal/ai-v6';\nimport type { ToolLoopAgentSettings } from '@internal/ai-v6';\n\n/**\n * Shape of a ToolLoopAgent-like object for runtime extraction.\n * We use this looser type because TypeScript's structural typing doesn't work\n * well with private properties across different package declarations.\n */\nexport interface ToolLoopAgentLike {\n readonly id?: string;\n readonly version?: string;\n // The settings property is private in ToolLoopAgent but accessible at runtime\n // We don't declare it here since we access it via type casting\n}\n\nexport function isToolLoopAgentLike(obj: any): obj is ToolLoopAgentLike {\n if (!obj) return false;\n if (obj instanceof ToolLoopAgent) return true;\n return (\n 'version' in obj &&\n typeof obj.version === 'string' &&\n (obj.version === 'agent-v1' || obj.version.startsWith('agent-v'))\n );\n}\n\n/**\n * Extracts the settings from a ToolLoopAgent instance.\n * ToolLoopAgent.settings is private in TypeScript but accessible at runtime.\n */\nexport function getSettings(agent: ToolLoopAgentLike): ToolLoopAgentSettings<any, any, any> {\n const settings = (agent as unknown as { settings: ToolLoopAgentSettings<any, any, any> }).settings;\n if (!settings) {\n throw new Error('Could not extract settings from ToolLoopAgent. The agent may be from an incompatible version.');\n }\n return settings;\n}\n","import type {\n ToolLoopAgent,\n AgentCallParameters,\n ModelMessage,\n StepResult,\n ToolLoopAgentSettings,\n} from '@internal/ai-v6';\nimport { isSupportedLanguageModel } from '../agent';\nimport type { AgentExecutionOptions, AgentInstructions } from '../agent';\nimport { resolveModelConfig } from '../llm/model/resolve-model';\nimport type { MastraLanguageModel } from '../llm/model/shared.types';\nimport type { ProcessInputStepArgs, ProcessInputStepResult, Processor } from '../processors';\nimport { getSettings as getToolLoopAgentSettings } from './utils';\nimport type { ToolLoopAgentLike } from './utils';\n\ntype PrepareCallInput = AgentCallParameters<never> &\n Pick<\n ToolLoopAgentSettings<never, any, any>,\n | 'model'\n | 'tools'\n | 'maxOutputTokens'\n | 'temperature'\n | 'topP'\n | 'topK'\n | 'presencePenalty'\n | 'frequencyPenalty'\n | 'stopSequences'\n | 'seed'\n | 'headers'\n | 'instructions'\n | 'stopWhen'\n | 'experimental_telemetry'\n | 'activeTools'\n | 'providerOptions'\n | 'experimental_context'\n | 'experimental_download'\n >;\n\nexport class ToolLoopAgentProcessor implements Processor<'tool-loop-agent-processor'> {\n readonly id = 'tool-loop-agent-processor';\n readonly name = 'ToolLoop to Mastra Agent Processor';\n\n private agent: ToolLoopAgentLike;\n private settings: ToolLoopAgentSettings<any, any, any>;\n private prepareCallResult?: Awaited<ReturnType<NonNullable<ToolLoopAgentSettings<any, any, any>['prepareCall']>>>;\n\n constructor(agent: ToolLoopAgentLike) {\n this.agent = agent;\n this.settings = getToolLoopAgentSettings(agent);\n }\n\n public getAgentConfig() {\n const tools = 'tools' in this.agent ? (this.agent as ToolLoopAgent).tools : undefined;\n\n // Build default options from ToolLoopAgent config params\n const defaultOptions: Omit<AgentExecutionOptions<unknown>, 'abortSignal'> = {};\n\n // AgentExecutionOptions\n if (this.settings.toolChoice) {\n defaultOptions.toolChoice = this.settings.toolChoice;\n }\n if (this.settings.providerOptions) {\n defaultOptions.providerOptions = this.settings.providerOptions;\n }\n // AgentExecutionOptions[\"modelSettings\"]\n if (this.settings.temperature !== undefined) {\n defaultOptions.modelSettings = {\n ...(defaultOptions.modelSettings ?? {}),\n temperature: this.settings.temperature,\n };\n }\n if (this.settings.topP !== undefined) {\n defaultOptions.modelSettings = { ...(defaultOptions.modelSettings ?? {}), topP: this.settings.topP };\n }\n if (this.settings.topK !== undefined) {\n defaultOptions.modelSettings = { ...(defaultOptions.modelSettings ?? {}), topK: this.settings.topK };\n }\n if (this.settings.seed !== undefined) {\n defaultOptions.modelSettings = { ...(defaultOptions.modelSettings ?? {}), seed: this.settings.seed };\n }\n if (this.settings.maxOutputTokens !== undefined) {\n defaultOptions.modelSettings = {\n ...(defaultOptions.modelSettings ?? {}),\n maxOutputTokens: this.settings.maxOutputTokens,\n };\n }\n if (this.settings.presencePenalty !== undefined) {\n defaultOptions.modelSettings = {\n ...(defaultOptions.modelSettings ?? {}),\n presencePenalty: this.settings.presencePenalty,\n };\n }\n if (this.settings.frequencyPenalty !== undefined) {\n defaultOptions.modelSettings = {\n ...(defaultOptions.modelSettings ?? {}),\n frequencyPenalty: this.settings.frequencyPenalty,\n };\n }\n if (this.settings.stopSequences !== undefined) {\n defaultOptions.modelSettings = {\n ...(defaultOptions.modelSettings ?? {}),\n stopSequences: this.settings.stopSequences,\n };\n }\n if (this.settings.stopWhen) {\n // TODO: The callback signatures differ (Types of parameters stepResult and event are incompatible)\n defaultOptions.stopWhen = this.settings.stopWhen as any;\n }\n if (this.settings.onStepFinish) {\n // TODO: The callback signatures differ (Types of parameters stepResult and event are incompatible)\n defaultOptions.onStepFinish = this.settings.onStepFinish as any;\n }\n if (this.settings.onFinish) {\n // TODO: The callback signatures differ (Types of parameters 'event' and 'event' are incompatible)\n defaultOptions.onFinish = this.settings.onFinish as any;\n }\n\n return {\n id: this.settings.id,\n name: this.settings.id,\n instructions: (this.settings.instructions as AgentInstructions) ?? '',\n model: this.settings.model,\n tools,\n maxRetries: this.settings.maxRetries,\n defaultOptions: Object.keys(defaultOptions).length > 0 ? defaultOptions : undefined,\n };\n }\n\n /**\n * Maps prepareCall or prepareStep result to ProcessInputStepResult.\n * Both hooks return similar structures that can override model, tools, activeTools, etc.\n */\n private mapToProcessInputStepResult(\n result: Awaited<ReturnType<NonNullable<ToolLoopAgentSettings<any, any, any>['prepareCall']>>> | undefined,\n ): ProcessInputStepResult {\n if (!result) {\n return {};\n }\n\n const stepResult: ProcessInputStepResult = {};\n\n // Map model (both prepareCall and prepareStep can return this)\n if (result.model) {\n stepResult.model = result.model;\n }\n\n // Map tools (prepareCall can return this)\n if ('tools' in result && result.tools) {\n stepResult.tools = result.tools as Record<string, unknown>;\n }\n\n // Map toolChoice (prepareStep can return this)\n if ('toolChoice' in result && result.toolChoice !== undefined) {\n stepResult.toolChoice = result.toolChoice as ProcessInputStepResult['toolChoice'];\n }\n\n // Map activeTools (both can return this)\n if (result.activeTools) {\n stepResult.activeTools = result.activeTools as string[];\n }\n\n // Map providerOptions (prepareCall can return this)\n if ('providerOptions' in result && result.providerOptions) {\n stepResult.providerOptions = result.providerOptions;\n }\n\n // Map model settings (prepareCall can return individual settings)\n const modelSettings: ProcessInputStepResult['modelSettings'] = {};\n if ('temperature' in result && result.temperature !== undefined) {\n modelSettings.temperature = result.temperature;\n }\n if ('topP' in result && result.topP !== undefined) {\n modelSettings.topP = result.topP;\n }\n if ('topK' in result && result.topK !== undefined) {\n modelSettings.topK = result.topK;\n }\n if ('maxOutputTokens' in result && result.maxOutputTokens !== undefined) {\n modelSettings.maxOutputTokens = result.maxOutputTokens;\n }\n if ('presencePenalty' in result && result.presencePenalty !== undefined) {\n modelSettings.presencePenalty = result.presencePenalty;\n }\n if ('frequencyPenalty' in result && result.frequencyPenalty !== undefined) {\n modelSettings.frequencyPenalty = result.frequencyPenalty;\n }\n if ('stopSequences' in result && result.stopSequences !== undefined) {\n modelSettings.stopSequences = result.stopSequences;\n }\n if ('seed' in result && result.seed !== undefined) {\n modelSettings.seed = result.seed;\n }\n\n if (Object.keys(modelSettings).length > 0) {\n stepResult.modelSettings = modelSettings;\n }\n\n // Map system/instructions to systemMessages\n // prepareCall returns 'instructions', prepareStep returns 'system'\n const systemContent =\n 'instructions' in result ? result.instructions : 'system' in result ? result.system : undefined;\n if (systemContent) {\n // Convert to CoreMessageV4 format\n if (typeof systemContent === 'string') {\n stepResult.systemMessages = [{ role: 'system', content: systemContent }];\n } else if (Array.isArray(systemContent)) {\n stepResult.systemMessages = systemContent.map(msg =>\n typeof msg === 'string' ? { role: 'system' as const, content: msg } : msg,\n );\n } else if (typeof systemContent === 'object' && 'role' in systemContent && 'content' in systemContent) {\n stepResult.systemMessages = [systemContent as { role: 'system'; content: string }];\n }\n }\n\n // Map messages if prepareStep returns them\n // Convert AI SDK ModelMessage[] to MastraDBMessage[]\n if ('messages' in result && result.messages && Array.isArray(result.messages)) {\n // AI SDK v6 ModelMessage is compatible with MessageListInput at runtime\n // stepResult.messages = convertMessages(result.messages as any).to('Mastra.V2');\n stepResult.messages = result.messages as any;\n }\n\n return stepResult;\n }\n\n private async handlePrepareCall(args: ProcessInputStepArgs) {\n if (this.settings.prepareCall) {\n const { model, messages, activeTools, providerOptions, modelSettings, tools } = args;\n // TODO: This should probably happen in processInput, currently calling in processInputStep if stepNumber === 0\n\n // Build the prepareCall input object\n // AI SDK prepareCall expects: AgentCallParameters & Pick<ToolLoopAgentSettings, ...settings>\n const prepareCallInput: PrepareCallInput = {\n // TODO: prepareCall expects messages in AI SDK format, we have them in Mastra format\n messages: messages as unknown as any,\n model,\n tools,\n instructions: this.settings.instructions,\n stopWhen: this.settings.stopWhen,\n activeTools,\n providerOptions,\n\n // Model settings\n temperature: modelSettings?.temperature,\n topP: modelSettings?.topP,\n topK: modelSettings?.topK,\n maxOutputTokens: modelSettings?.maxOutputTokens,\n presencePenalty: modelSettings?.presencePenalty,\n frequencyPenalty: modelSettings?.frequencyPenalty,\n stopSequences: modelSettings?.stopSequences,\n seed: modelSettings?.seed,\n\n // Experimental options\n // experimental_telemetry: this.settings.experimental_telemetry,\n // experimental_context: this.settings.experimental_context,\n // experimental_download: this.settings.experimental_download,\n };\n\n // Call prepareCall and apply any returned overrides\n const prepareCallResult = await this.settings.prepareCall(prepareCallInput as any); // TODO: types\n this.prepareCallResult = prepareCallResult;\n }\n }\n\n private async handlePrepareStep(args: ProcessInputStepArgs, currentResult: ProcessInputStepResult) {\n if (this.settings.prepareStep) {\n const { messages, steps, stepNumber } = args;\n\n let model = args.model;\n if (currentResult.model) {\n const resolvedModel = await resolveModelConfig(currentResult.model);\n if (!isSupportedLanguageModel(resolvedModel)) {\n throw new Error('prepareStep returned an unsupported model version');\n }\n model = resolvedModel;\n }\n\n // Use the model from currentResult if prepareCall overrode it, otherwise use args.model\n\n // Note: We pass messages and steps in Mastra format rather than converting to AI SDK format.\n // This is intentional - most prepareStep callbacks only return overrides and don't inspect\n // the message content. The type casts handle the format difference at runtime.\n const prepareStepInputArgs: {\n /**\n * The steps that have been executed so far.\n */\n steps: Array<StepResult<NoInfer<any>>>;\n /**\n * The number of the step that is being executed.\n */\n stepNumber: number;\n /**\n * The model instance that is being used for this step.\n */\n model: MastraLanguageModel;\n /**\n * The messages that will be sent to the model for the current step.\n * Note: These are in Mastra format (MastraDBMessage[]), not AI SDK ModelMessage format.\n */\n messages: Array<ModelMessage>;\n /**\n * The context passed via the experimental_context setting (experimental).\n */\n experimental_context: unknown;\n } = {\n model,\n // Messages are in Mastra format (MastraDBMessage[])\n messages: messages as any,\n // Steps may have minor type differences in usage properties (inputTokenDetails/outputTokenDetails)\n steps: steps as any,\n stepNumber,\n experimental_context: undefined,\n };\n\n const prepareStepResult = await this.settings.prepareStep(prepareStepInputArgs);\n return prepareStepResult;\n }\n }\n\n async processInputStep(args: ProcessInputStepArgs): Promise<ProcessInputStepResult | undefined | void> {\n const { stepNumber } = args;\n\n if (stepNumber === 0 && this.settings.prepareCall) {\n await this.handlePrepareCall(args);\n }\n\n let result: ProcessInputStepResult = {};\n\n // Apply prepareCall result (only on step 0, already called above)\n if (this.prepareCallResult) {\n const mappedResult = this.mapToProcessInputStepResult(this.prepareCallResult);\n if (Object.keys(mappedResult).length > 0) {\n result = { ...result, ...mappedResult };\n }\n }\n\n // Apply prepareStep result (called on every step)\n // Pass the current result so prepareStep sees any overrides from prepareCall\n if (this.settings.prepareStep) {\n const prepareStepResult = await this.handlePrepareStep(args, result);\n if (prepareStepResult) {\n const mappedResult = this.mapToProcessInputStepResult(prepareStepResult as any);\n // prepareStep overrides prepareCall for this step\n result = { ...result, ...mappedResult };\n }\n }\n\n return result;\n }\n}\n","import { generateId } from '@internal/ai-sdk-v5';\nimport { Agent } from '../agent';\nimport { ToolLoopAgentProcessor } from './tool-loop-processor';\nimport type { ToolLoopAgentLike } from './utils';\nexport { type ToolLoopAgentLike, isToolLoopAgentLike, getSettings } from './utils';\n\n/**\n * Converts an AI SDK v6 ToolLoopAgent instance into a Mastra Agent.\n *\n * This enables users to create a ToolLoopAgent using AI SDK's API\n * while gaining access to Mastra features like memory, processors, scorers, and observability.\n *\n * @example\n * ```typescript\n * import { ToolLoopAgent, tool } from 'ai';\n * import { openai } from '@ai-sdk/openai';\n * import { toolLoopAgentToMastraAgent } from '@mastra/core/tool-loop-agent';\n *\n * const toolLoopAgent = new ToolLoopAgent({\n * id: 'weather-agent',\n * model: openai('gpt-4o'),\n * instructions: 'You are a helpful weather assistant.',\n * tools: { weather: weatherTool },\n * temperature: 0.7,\n * });\n *\n * const mastraAgent = toolLoopAgentToMastraAgent(toolLoopAgent);\n *\n * const result = await mastraAgent.generate({ prompt: 'What is the weather in NYC?' });\n * ```\n *\n * @param agent - The ToolLoopAgent instance\n * @param options - Optional name fallback since Mastra Agent requires id/name but ToolLoopAgent doesn't\n * @returns A Mastra Agent instance\n */\nexport function toolLoopAgentToMastraAgent(agent: ToolLoopAgentLike, options?: { fallbackName?: string }) {\n const processor = new ToolLoopAgentProcessor(agent);\n const agentConfig = processor.getAgentConfig();\n const id = agentConfig.id || options?.fallbackName || `tool-loop-agent-${generateId()}`;\n\n return new Agent({\n ...agentConfig,\n id,\n name: agentConfig.name || id,\n inputProcessors: [processor],\n });\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var chunkRQ56ZSIR_cjs = require('./chunk-RQ56ZSIR.cjs');
|
|
4
|
-
var chunkZCBG4ZQT_cjs = require('./chunk-ZCBG4ZQT.cjs');
|
|
5
4
|
var chunkS4VVZI4E_cjs = require('./chunk-S4VVZI4E.cjs');
|
|
5
|
+
var chunkZCBG4ZQT_cjs = require('./chunk-ZCBG4ZQT.cjs');
|
|
6
6
|
var chunkJZ6TH4HQ_cjs = require('./chunk-JZ6TH4HQ.cjs');
|
|
7
7
|
var chunkYW54RH77_cjs = require('./chunk-YW54RH77.cjs');
|
|
8
8
|
var chunkZIEQA3YP_cjs = require('./chunk-ZIEQA3YP.cjs');
|
|
@@ -25416,5 +25416,5 @@ exports.validateStepRequestContext = validateStepRequestContext;
|
|
|
25416
25416
|
exports.validateStepResumeData = validateStepResumeData;
|
|
25417
25417
|
exports.validateStepStateData = validateStepStateData;
|
|
25418
25418
|
exports.validateStepSuspendData = validateStepSuspendData;
|
|
25419
|
-
//# sourceMappingURL=chunk-
|
|
25420
|
-
//# sourceMappingURL=chunk-
|
|
25419
|
+
//# sourceMappingURL=chunk-7S6LA43E.cjs.map
|
|
25420
|
+
//# sourceMappingURL=chunk-7S6LA43E.cjs.map
|