diff --git a/.changeset/card-links-open-session.md b/.changeset/card-links-open-session.md deleted file mode 100644 index 2629a17ef6c..00000000000 --- a/.changeset/card-links-open-session.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@mastra/factory': patch ---- - -Factory card links that agents post (in Slack threads, GitHub comments and tool results) now open the card's session directly, the same as clicking the card on its board. Before, they opened the board with the card highlighted in the list, so you had to find and click the card again. diff --git a/.changeset/clever-carpets-enter.md b/.changeset/clever-carpets-enter.md deleted file mode 100644 index 864bb4a742d..00000000000 --- a/.changeset/clever-carpets-enter.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -'@mastra/factory': minor ---- - -Organization admins can now create skills for one Factory from Settings › Skills, without redeploying. Choose **New skill**, give it a name, description and instructions, and the Factory's sessions can load it from their next start. A phase of the Factory's boards can also run it as `runner.skill`. Created skills show a **Custom** badge and can be edited or deleted from the same page. Creating and deleting are recorded in the audit log as `factory.skill.created` and `factory.skill.deleted`. - -A board phase runs a created skill by its name, like any other skill: - -```ts -await factory.upsertBoard( - { - key: 'notes', - name: 'Release notes', - phases: [ - { key: 'queued', name: 'Queued', kind: 'resting', nextPhases: ['writing'] }, - { key: 'writing', name: 'Writing', kind: 'working', runner: { context: 'writer', skill: 'release-notes' }, nextPhases: ['done'] }, - { key: 'done', name: 'Done', kind: 'terminal' }, - ], - }, - // Each project listed must have created `release-notes`; a board for 'all' projects may only run the app's skills. - { projects: [{ orgId, factoryProjectId }] }, -); -``` - -If the app later ships a skill under the same name, the app's skill takes over the name and the Factory's text becomes an edit of it, which **Revert to original** removes. diff --git a/.changeset/curvy-nights-bet.md b/.changeset/curvy-nights-bet.md deleted file mode 100644 index 893dd930106..00000000000 --- a/.changeset/curvy-nights-bet.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'mastra': patch ---- - -The Factory sidebar now groups sessions by board and shows a second line under each session by default, with when it last changed and its pull request. Turn on **Compact view** or set **Group** to **None** in the sidebar's properties menu to get one line per session or a single list back. Settings you already changed keep their values; the rest follow the new defaults. diff --git a/.changeset/dry-worlds-sit.md b/.changeset/dry-worlds-sit.md deleted file mode 100644 index 8c8df41fc6b..00000000000 --- a/.changeset/dry-worlds-sit.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@mastra/factory': patch ---- - -The **Activity** sort in the Factory sidebar now orders sessions that share a status by their last update instead of their creation date, the same as **Last updated** does. An older session that was updated since no longer sinks below a newer one that was left alone. diff --git a/.changeset/factory-preferences-in-my-account.md b/.changeset/factory-preferences-in-my-account.md deleted file mode 100644 index c269b56211f..00000000000 --- a/.changeset/factory-preferences-in-my-account.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'mastra': patch ---- - -Factory **Settings** now shows theme and completion sound on **My account**, next to your profile and log out, instead of on a separate **Preferences** page. Settings opens on **My account**, and old Preferences links go there. diff --git a/.changeset/flush-diff-lines.md b/.changeset/flush-diff-lines.md deleted file mode 100644 index c4411d48629..00000000000 --- a/.changeset/flush-diff-lines.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@mastra/playground-ui': patch ---- - -`CodeDiff` with a file header now shows its lines flush against the header and the card's bottom edge, so stacked diffs in a `CodeDiffList` read like a pull request with no blank band above the first line or below the last. The horizontal scrollbar only takes room when lines overflow, and none on platforms with overlay scrollbars. Diffs without a header keep their padding. diff --git a/.changeset/knowledge-store-scope-declarations.md b/.changeset/knowledge-store-scope-declarations.md deleted file mode 100644 index 2944742812e..00000000000 --- a/.changeset/knowledge-store-scope-declarations.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -'@mastra/core': minor ---- - -Knowledge storage can supply scope declarations, access rules included. - -A store returns declarations from `getScopeDeclarations()` (none by default). Knowledge merges them under its config's: the config wins on a key both declare, and a declaration that doesn't compile is skipped with a warning. When stored scopes come from a skipped declaration, the declaration check's error names that declaration and why it was skipped, so it can be fixed in the store. The store's answer is reused for 30 seconds and read again after `renameScopeDeclaration`, so a declaration the store adds, removes or changes (access rules included) applies within that window without a store read on every call. Revoking access through the store can therefore take up to 30 seconds to take effect. - -```ts -class ImportingKnowledgeStorage extends InMemoryKnowledgeStorage { - override async getScopeDeclarations() { - return { - 'imports:$name': {}, - 'linear:$account:$connection': { access: [{ principal: 'imports:all', role: 'viewer' }] }, - }; - } -} -``` - -Runs that hold `imports:all` then read every Linear connection's pages. diff --git a/.changeset/plain-gates-refuse.md b/.changeset/plain-gates-refuse.md new file mode 100644 index 00000000000..8d9fcd28104 --- /dev/null +++ b/.changeset/plain-gates-refuse.md @@ -0,0 +1,5 @@ +--- +'@mastra/factory': patch +--- + +Factory now explains Mastra Gateway v2 refusals correctly in the web UI and in Slack. An organization budget, a key or organization spend limit, an unsupported billing plan, a routing policy refusal and a context that is too large each get their own message, and "Add credits" is offered only where adding credits helps. v1 Gateway billing replies are recognized by their structure rather than by a link in their text, so they are still named once the Gateway links to the Mastra dashboard, and the v1 monthly spend limit no longer offers to add credits. A rate limit now says whether the gateway's own limit on the key or organization was reached or the model provider behind the gateway is limiting requests, and no longer suggests changing credentials. A gateway at the configured base URL, such as staging or a self-hosted one, is recognized as well as the production one. The web UI recognizes v2 refusals from any gateway by their response body. In the web UI, rate limits and errors without a gateway reply body are recognized only for runs saved by a version of `@mastra/core` that records the request origin; older saved errors keep the generic provider message. diff --git a/.changeset/platform-browser.md b/.changeset/platform-browser.md deleted file mode 100644 index df214b4f250..00000000000 --- a/.changeset/platform-browser.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -'@mastra/platform': minor ---- - -Added `PlatformBrowser`, a Stagehand browser backed by a Mastra Platform browser session. By default it provisions a session with `POST /v1/browsers/sessions` on the Platform and connects to the returned CDP URL; pass `cdpUrl` to connect to a session you already provisioned, with no token or API call. The access token falls back to `MASTRA_PLATFORM_ACCESS_TOKEN` / `MASTRA_PLATFORM_SECRET_KEY`, the project to `MASTRA_PROJECT_ID`, and the API URL to `MASTRA_BROWSER_API_URL`. `@mastra/platform` now depends on `@mastra/stagehand` at runtime. - -```ts -import { PlatformBrowser } from '@mastra/platform'; - -const agent = new Agent({ name: 'browser-agent', model, browser: new PlatformBrowser() }); -``` diff --git a/.changeset/platform-knowledge-listing-pins.md b/.changeset/platform-knowledge-listing-pins.md deleted file mode 100644 index 714e66f55e3..00000000000 --- a/.changeset/platform-knowledge-listing-pins.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@mastra/platform': patch ---- - -`PlatformKnowledge` now supports listing pins: `knowledge_pin` with `kind: 'list'` pins a page's listing on hosted Knowledge instead of refusing it as an old storage adapter. diff --git a/.changeset/platform-memory-initial.md b/.changeset/platform-memory-initial.md deleted file mode 100644 index e9c55e0c1d7..00000000000 --- a/.changeset/platform-memory-initial.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -'@mastra/platform': minor ---- - -Added `@mastra/platform`: hosted Mastra Platform Memory and Knowledge clients, with Platform Sandbox and Filesystem re-exported from `@mastra/platform-workspace`. `PlatformMemory` is a drop-in `memory` for `Agent` that loads observations and recent messages from a Platform Memory instance and saves each turn back; observation and reflection run on the Platform. `PlatformMemoryClient` exposes the same API directly. Credentials fall back to `MASTRA_PLATFORM_ACCESS_TOKEN` / `MASTRA_PLATFORM_SECRET_KEY`. `PlatformMemory` uses `MASTRA_MEMORY_INSTANCE_ID`; `PlatformKnowledge` uses `MASTRA_KNOWLEDGE_INSTANCE_ID`. `PlatformKnowledge` takes every scope declaration and access rule from its instance, Memory's and Platform importers' included, and has no `scopes` option. Agents read imported pages when their runs hold the scope an importer's rule grants (for now `imports:all`). - -```ts -import { PlatformMemory, PlatformKnowledge, PlatformSandbox, PlatformFilesystem } from '@mastra/platform'; - -const agent = new Agent({ name: 'assistant', model, memory: new PlatformMemory() }); -``` diff --git a/.changeset/platform-memory-read-only-and-working-memory.md b/.changeset/platform-memory-read-only-and-working-memory.md deleted file mode 100644 index 3a22cab9d98..00000000000 --- a/.changeset/platform-memory-read-only-and-working-memory.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -'@mastra/platform': patch ---- - -`PlatformMemory` fixes for read-only runs and working memory: - -- A read-only run (`memory: { options: { readOnly: true } }`) now sees the thread's observations and unobserved messages, read through the Memory instance's read-only context route. Before, it got no stored context at all. It still saves nothing and starts no observation. -- The `workingMemory` option now delivers what it says: `readonly` and `tool` add the resource's stored working memory to each run's prompt, read fresh each run; `tool` also tells the agent to update it with `updateWorkingMemory`; `off` leaves it out. Before, stored working memory never reached the prompt in any mode. diff --git a/.changeset/pre.json b/.changeset/pre.json index 1af639fe419..7ca7d0f860a 100644 --- a/.changeset/pre.json +++ b/.changeset/pre.json @@ -195,8 +195,7 @@ "@mastra/s3": "0.6.5", "@mastra/sprites": "0.1.2", "@mastra/vercel": "1.6.3", - "@mastra/json-render": "0.0.0", - "@mastra/platform": "0.1.0-alpha.0" + "@mastra/json-render": "0.0.0" }, "changesets": [ "@mastra_auth-better-auth-30464-dependencies", @@ -212,27 +211,20 @@ "calm-sweeps-skip", "calm-threads-wait", "calm-verdicts-rest", - "clean-pigs-win", "clear-animals-enjoy", "code-sdk-core-peer-floor", - "code-sdk-custom-provider-own-key", "code-sdk-vendor-scope-encoder", "cold-birds-swim", "connect-image-default-sunburst", "cozy-ways-refuse", "create-factory-current-directory", - "create-factory-tag-flag", - "create-factory-tag-lookup-errors", "cuddly-symbols-laugh", "curly-pillows-argue", - "curvy-nights-bet", "cute-swans-march", "daytona-sdk-package-rename", - "dry-worlds-sit", "durable-agent-replay-takeover", "durable-recover-processor-errors", "e2b-run-as-user-mount-owner", - "easy-clocks-switch", "eight-buttons-juggle", "eight-places-invent", "eight-stars-hang", @@ -242,10 +234,6 @@ "factory-board-rules-page", "factory-card-actions", "factory-checkout-plan-preview", - "factory-connect-tool-list-ui", - "factory-connect-tool-list", - "factory-connect-tools-panel-ui", - "factory-connect-tools-panel", "factory-duplicate-plan-card", "factory-health-metrics", "factory-intake-order-cli", @@ -255,10 +243,8 @@ "factory-interactive-wakes", "factory-onboarding-check-align", "factory-onboarding-code-host-issues", - "factory-personal-custom-providers", "factory-phase-session-owner", "factory-pr-joins-external-card", - "factory-preferences-in-my-account", "factory-pull-request-reopen", "factory-recent-repos-picker", "factory-remove-provider-list-routes", @@ -278,7 +264,6 @@ "forty-toes-nail", "frank-ants-flow", "full-humans-glow", - "funky-bears-know", "funky-jobs-carry", "fuzzy-apes-warn", "gateway-live-chat-catalog", @@ -291,29 +276,20 @@ "jolly-geckos-change", "json-render-processor", "keep-processor-provider-metadata", - "khaki-eels-care", - "knowledge-host-move-page", - "knowledge-reembed-existing", "knowledge-scope-values-no-colons", - "knowledge-store-scope-declarations", "late-falcons-listen", "lazy-suns-dream", "legal-spies-kiss", "light-worlds-draw", "linear-intake-reads-once", - "linear-pr-number", - "linear-slash-trim", - "live-sidebar-sessions", "long-doors-obey", "loud-lizards-build", "loud-mentions-reply", "lovely-books-throw", "many-parrots-press", "mastracode-knowledge-canonical-scopes", - "mastracode-run-tui-export", "memory-save-no-pause", "mighty-pets-drive", - "modern-regions-lead", "modern-turtles-fix", "new-ads-hug", "nice-actors-stand", @@ -322,16 +298,11 @@ "nine-pigs-kneel", "odd-bottles-notice", "olive-pandas-carry", - "otel-resources-sec-323", "parked-run-lease-outage", "perky-colts-glow", "plain-lands-refuse", "plain-search-groups", "plan-feedback-revises", - "platform-browser", - "platform-knowledge-listing-pins", - "platform-memory-initial", - "platform-memory-read-only-and-working-memory", "plenty-boats-travel", "plenty-buckets-relate", "plenty-clouds-search", @@ -341,16 +312,12 @@ "plugin-reload-keeps-last-good", "plugin-startup-failure-notice", "polite-pianos-show", - "posthog-query-column-types", "pretty-pandas-beam", "proud-towns-smell", "public-dashboard-schemas", "puny-papers-joke", "puny-snakes-train", - "purple-buckets-spend", - "quick-plums-flash", "quick-waits-knob", - "quiet-cards-point", "quiet-counters-rest", "quiet-diffs-blend", "quiet-dirs-wander", @@ -382,23 +349,15 @@ "shy-zoos-write", "silent-islands-guess", "silly-colts-lay", - "silly-dingos-follow", "silly-drinks-trade", - "silly-moose-read", "six-mugs-lead", - "slimy-teeth-sell", "smart-guests-grab", "smooth-donkeys-split", - "smooth-sails-learn", "social-towns-sort", - "soft-shirts-lay", "solid-doors-mix", "sour-bananas-ring", - "sour-cities-show", - "sour-pants-type", "sour-rockets-grab", "spicy-canyons-yawn", - "spicy-peaches-crash", "spotty-webs-unite", "strict-crabs-hug", "summary-runs-app-side", @@ -426,7 +385,6 @@ "twenty-humans-shake", "vanta-2026-11-12-bedrock-template", "vast-masks-stand", - "wacky-chefs-repair", "warm-garlics-lick", "wet-geckos-work", "wet-regions-peel", diff --git a/.changeset/quiet-gateways-count.md b/.changeset/quiet-gateways-count.md new file mode 100644 index 00000000000..d641567a602 --- /dev/null +++ b/.changeset/quiet-gateways-count.md @@ -0,0 +1,10 @@ +--- +'@mastra/core': patch +--- + +Improved how `@mastra/core` works with the Mastra Gateway: + +- Streamed calls through the Gateway's chat endpoint now ask for token usage, so `agent.stream()` reports usage when the upstream provider sends it in a separate final chunk. Before, usage could be empty. +- The Gateway model list for organization keys is cached for a minute and shared between concurrent callers. If a refresh times out or the Gateway has an outage, the last list is kept for up to ten minutes. With no earlier list, the failure is reported again for 15 seconds without a new request, so Studio does not wait for the request timeout on every load during an outage. If the Gateway rejects the key (401 or 403), the cached list is dropped. The model list request now always sends the key in `Authorization` and no longer goes through a `customFetch`, which the v2 Gateway would not have authenticated. +- A `msk_` project key now always uses the v1 Gateway, even when `MASTRA_GATEWAY_VERSION=v2` is set. +- `mastra dev` no longer writes one organization's Gateway model list to the provider cache shared by other projects on the machine, whether the key comes from the environment or from a registered `MastraGateway`. A failing Gateway model list no longer stops the provider registry refresh. diff --git a/.changeset/quiet-logs-arrive.md b/.changeset/quiet-logs-arrive.md deleted file mode 100644 index ba86c08b369..00000000000 --- a/.changeset/quiet-logs-arrive.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@mastra/otel-bridge': patch ---- - -Fixed Mastra logs being dropped by `OtelBridge` in apps on OpenTelemetry JS SDK 3. The bridge now finds a `LoggerProvider` registered through `@opentelemetry/api` (SDK 3) as well as one registered through `@opentelemetry/api-logs` (SDK 2), including when it is registered after the bridge is created. When no provider is registered, the bridge now says so once at debug level. Fixes [#29695](https://github.com/mastra-ai/mastra/issues/29695). diff --git a/.changeset/saved-error-origins.md b/.changeset/saved-error-origins.md new file mode 100644 index 00000000000..42d4d00325d --- /dev/null +++ b/.changeset/saved-error-origins.md @@ -0,0 +1,8 @@ +--- +'@mastra/core': patch +--- + +Improved how `@mastra/core` reports on Mastra Gateway models: + +- The warning "No memory is configured but resourceId and threadId were passed in args" is shown again for Gateway models when the Gateway does not keep memory for your key, such as an organization key. It stays hidden when the Gateway manages memory. The check runs in the background and does not delay the run. +- Error parts saved to thread history for a failed model call now include `requestOrigin`, the scheme, host and port the request was sent to (for example `https://gateway-api.mastra.ai`). A UI that rebuilds the error from history can tell a Gateway error from a provider error with the same status. The path, query string and any credentials in the URL are not saved. diff --git a/.changeset/steady-gateway-versions.md b/.changeset/steady-gateway-versions.md new file mode 100644 index 00000000000..3a31dbbd23d --- /dev/null +++ b/.changeset/steady-gateway-versions.md @@ -0,0 +1,5 @@ +--- +'@mastra/server': patch +--- + +A `msk_` project key now always uses the v1 Gateway memory API, even when `MASTRA_GATEWAY_VERSION=v2` is set. Studio follows a registered `MastraGateway` and its own key when deciding between the v1 and v2 Gateway, so it agrees with the model calls. diff --git a/.changeset/steady-studio-providers.md b/.changeset/steady-studio-providers.md new file mode 100644 index 00000000000..e88159d6aa3 --- /dev/null +++ b/.changeset/steady-studio-providers.md @@ -0,0 +1,8 @@ +--- +'@mastra/server': patch +--- + +Fixed Studio for projects that use the Mastra Gateway: + +- The Gateway provider stays in the provider list, with no models, when its model list cannot be loaded (for example a revoked key or an outage). Before, it disappeared. +- "Enhance instructions" now works for agents on gateway models such as `mastra/...` when only the gateway's key, for example `MASTRA_GATEWAY_API_KEY`, is set. Before, it returned "No model with a configured API key found". A gateway model whose credential is missing is skipped in favour of the next connected model. diff --git a/.changeset/vast-parks-unite.md b/.changeset/vast-parks-unite.md deleted file mode 100644 index ab1ec12e0d0..00000000000 --- a/.changeset/vast-parks-unite.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -'mastra': minor ---- - -Added `mastra api factory skill create` to create a skill for one Factory project. `mastra api factory skill update` now also updates a skill the project created, and `mastra api factory skill revert` deletes one. Only organization admins can create skills. - -```sh -mastra api factory skill create '{"name":"release-notes","content":"---\nname: release-notes\ndescription: Write release notes for a merged change\n---\n\n# Release notes\n"}' -``` diff --git a/auth/supabase/CHANGELOG.md b/auth/supabase/CHANGELOG.md index aa1607771cd..583325d8fcc 100644 --- a/auth/supabase/CHANGELOG.md +++ b/auth/supabase/CHANGELOG.md @@ -1,11 +1,5 @@ # @mastra/auth-supabase -## 1.2.1-alpha.0 - -### Patch Changes - -- Fixed slow handling of Gateway base URLs and Supabase URLs that contain very long runs of `/`. The resulting URLs are unchanged. ([#30577](https://github.com/mastra-ai/mastra/pull/30577)) - ## 1.2.0 ### Minor Changes diff --git a/auth/supabase/package.json b/auth/supabase/package.json index ca34c9dbbc7..9cf19e51d0e 100644 --- a/auth/supabase/package.json +++ b/auth/supabase/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/auth-supabase", - "version": "1.2.1-alpha.0", + "version": "1.2.0", "description": "Mastra Supabase Auth integration", "type": "module", "main": "dist/index.js", diff --git a/client-sdks/client-js/CHANGELOG.md b/client-sdks/client-js/CHANGELOG.md index 58275b661c1..6cda58b39b1 100644 --- a/client-sdks/client-js/CHANGELOG.md +++ b/client-sdks/client-js/CHANGELOG.md @@ -1,19 +1,5 @@ # @mastra/client-js -## 1.60.1-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - -## 1.60.1-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - ## 1.60.1-alpha.4 ### Patch Changes diff --git a/client-sdks/client-js/package.json b/client-sdks/client-js/package.json index 69c40fc0d56..f57e0212af9 100644 --- a/client-sdks/client-js/package.json +++ b/client-sdks/client-js/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/client-js", - "version": "1.60.1-alpha.6", + "version": "1.60.1-alpha.4", "description": "The official TypeScript library for the Mastra Client API", "author": "", "type": "module", diff --git a/client-sdks/react/CHANGELOG.md b/client-sdks/react/CHANGELOG.md index 78123e64677..50728f5a6fb 100644 --- a/client-sdks/react/CHANGELOG.md +++ b/client-sdks/react/CHANGELOG.md @@ -1,21 +1,5 @@ # @mastra/react -## 1.15.1-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/client-js@1.60.1-alpha.6 - -## 1.15.1-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/client-js@1.60.1-alpha.5 - ## 1.15.1-alpha.4 ### Patch Changes diff --git a/client-sdks/react/package.json b/client-sdks/react/package.json index 528fb72cbaf..913f73d0f3e 100644 --- a/client-sdks/react/package.json +++ b/client-sdks/react/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/react", - "version": "1.15.1-alpha.6", + "version": "1.15.1-alpha.4", "repository": { "type": "git", "url": "git+https://github.com/mastra-ai/mastra.git", diff --git a/deployers/cloud/CHANGELOG.md b/deployers/cloud/CHANGELOG.md index d8e74d50130..f9926e38e0f 100644 --- a/deployers/cloud/CHANGELOG.md +++ b/deployers/cloud/CHANGELOG.md @@ -1,21 +1,5 @@ # @mastra/deployer-cloud -## 1.84.0-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/deployer@1.84.0-alpha.6 - -## 1.84.0-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/deployer@1.84.0-alpha.5 - ## 1.84.0-alpha.4 ### Patch Changes diff --git a/deployers/cloud/package.json b/deployers/cloud/package.json index 1508f332b90..2d2a81a98d4 100644 --- a/deployers/cloud/package.json +++ b/deployers/cloud/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/deployer-cloud", - "version": "1.84.0-alpha.6", + "version": "1.84.0-alpha.4", "description": "", "type": "module", "files": [ diff --git a/docs/src/content/en/integrations/observability/opentelemetry.mdx b/docs/src/content/en/integrations/observability/opentelemetry.mdx index 3c72c571eda..d2527be1ca8 100644 --- a/docs/src/content/en/integrations/observability/opentelemetry.mdx +++ b/docs/src/content/en/integrations/observability/opentelemetry.mdx @@ -13,13 +13,13 @@ Mastra supports OpenTelemetry (OTEL) through an exporter for sending traces and ## Exporter -The OpenTelemetry exporter sends your traces and logs using standardized [OpenTelemetry Semantic Conventions for GenAI](https://opentelemetry.io/docs/specs/semconv/gen-ai/). This ensures broad compatibility with platforms like Agnost AI, Dash0, Datadog, Laminar, Latitude, MLflow, New Relic, Sazabi, Sentry, SigNoz, telemetry.dev, Traceloop, and more. +The OpenTelemetry exporter sends your traces and logs using standardized [OpenTelemetry Semantic Conventions for GenAI](https://opentelemetry.io/docs/specs/semconv/gen-ai/). This ensures broad compatibility with platforms like Datadog, New Relic, Sentry, SigNoz, MLflow, Latitude, Dash0, Traceloop, Laminar, telemetry.dev, Sazabi, Agnost AI, and more. ### Installation Each provider requires specific protocol packages. Install the base exporter plus the protocol package for your provider: -#### For HTTP/Protobuf providers (Agnost AI, Laminar, Latitude, MLflow, New Relic, Sentry, SigNoz, telemetry.dev) +#### For HTTP/Protobuf providers (SigNoz, New Relic, Sentry, Laminar, MLflow, Latitude, telemetry.dev, Agnost AI) ```bash npm2yarn npm install @mastra/otel-exporter@latest @opentelemetry/exporter-trace-otlp-proto @@ -31,7 +31,7 @@ npm install @mastra/otel-exporter@latest @opentelemetry/exporter-trace-otlp-prot npm install @mastra/otel-exporter@latest @opentelemetry/exporter-trace-otlp-grpc @grpc/grpc-js ``` -#### For HTTP/JSON providers (Sazabi, Traceloop) +#### For HTTP/JSON providers (Traceloop, Sazabi) ```bash npm2yarn npm install @mastra/otel-exporter@latest @opentelemetry/exporter-trace-otlp-http @@ -44,13 +44,129 @@ All providers support zero-config setup via environment variables. Set the appro | Provider | Environment Variables | | - | - | | Dash0 | `DASH0_API_KEY` (required), `DASH0_ENDPOINT` (required), `DASH0_DATASET` (optional) | -| Laminar | `LMNR_PROJECT_API_KEY` (required), `LAMINAR_ENDPOINT` (optional) | -| New Relic | `NEW_RELIC_LICENSE_KEY` (required), `NEW_RELIC_ENDPOINT` (optional) | | SigNoz | `SIGNOZ_API_KEY` (required), `SIGNOZ_REGION` (optional), `SIGNOZ_ENDPOINT` (optional) | +| New Relic | `NEW_RELIC_LICENSE_KEY` (required), `NEW_RELIC_ENDPOINT` (optional) | | Traceloop | `TRACELOOP_API_KEY` (required), `TRACELOOP_DESTINATION_ID`, `TRACELOOP_ENDPOINT` (optional) | +| Laminar | `LMNR_PROJECT_API_KEY` (required), `LAMINAR_ENDPOINT` (optional) | ### Provider configurations +#### Sentry + +[Sentry](https://sentry.io/) accepts OpenTelemetry traces and logs through its OTLP endpoints. In Sentry, open [**Project Settings** > **Client Keys (DSN)**](https://sentry.io/settings/projects/) and copy the OTLP traces endpoint and authentication header. Add both values to your environment: + +```bash title=".env" +SENTRY_OTLP_ENDPOINT=https://o000000.ingest.sentry.io/api/0000000/integration/otlp/v1/traces +SENTRY_OTLP_AUTH_HEADER="sentry sentry_key=..." +``` + +Use the `custom` provider with HTTP/Protobuf: + +```typescript title="src/mastra/index.ts" +new OtelExporter({ + provider: { + custom: { + endpoint: process.env.SENTRY_OTLP_ENDPOINT!, + protocol: 'http/protobuf', + headers: { + 'x-sentry-auth': process.env.SENTRY_OTLP_AUTH_HEADER!, + }, + }, + }, +}) +``` + +See [Sentry's OTLP documentation](https://docs.sentry.io/concepts/otlp/) for endpoint setup, supported signals, and current ingestion limits. + +Choose an exporter based on your setup: + +- `OtelExporter`: Sends vendor-neutral traces and logs over OTLP. Use it with an existing OpenTelemetry pipeline or when you want backend portability. +- [`SentryExporter`](/integrations/observability/sentry): Uses the Sentry SDK to map Mastra span types to Sentry operations, add AI monitoring attributes, and capture span errors as Sentry issues. + +#### MLflow + +[MLflow](https://mlflow.org/docs/latest/genai/tracing/integrations/listing/mastra) supports native Mastra tracing through its OTLP endpoint at `/v1/traces`. Use the `custom` provider with HTTP/Protobuf and include the experiment header so traces are routed to the correct MLflow experiment: + +```typescript title="src/mastra/index.ts" +new OtelExporter({ + provider: { + custom: { + endpoint: `${process.env.MLFLOW_TRACKING_URI}/v1/traces`, + protocol: 'http/protobuf', + headers: { + 'x-mlflow-experiment-id': process.env.MLFLOW_EXPERIMENT_ID, + }, + }, + }, +}) +``` + +#### Latitude + +[Latitude](https://latitude.so) is an open-source LLM observability and evaluation platform that ingests OTLP traces. Use the `custom` provider with HTTP/Protobuf, pointing at Latitude's ingestion endpoint and authenticating with your API key and project slug: + +```typescript title="src/mastra/index.ts" +new OtelExporter({ + provider: { + custom: { + endpoint: 'https://ingest.latitude.so/v1/traces', + protocol: 'http/protobuf', + headers: { + Authorization: `Bearer ${process.env.LATITUDE_API_KEY}`, + 'X-Latitude-Project': process.env.LATITUDE_PROJECT, + }, + }, + }, +}) +``` + +Sign up at [console.latitude.so](https://console.latitude.so/login), or self-host and point the endpoint at your own ingestion host. + +#### telemetry.dev + +[telemetry.dev](https://telemetry.dev) ingests OTLP/HTTP protobuf traces and normalizes OpenTelemetry GenAI semantic conventions into model, provider, token, latency, and cost fields. Use the `custom` provider with your project API key: + +```bash title=".env" +TELEMETRY_DEV_API_KEY=td_live_... +``` + +```typescript title="src/mastra/index.ts" +new OtelExporter({ + provider: { + custom: { + endpoint: 'https://ingest.telemetry.dev/v1/traces', + protocol: 'http/protobuf', + headers: { + Authorization: `Bearer ${process.env.TELEMETRY_DEV_API_KEY}`, + }, + }, + }, +}) +``` + +#### Sazabi + +[Sazabi](https://sazabi.com) is an AI-native observability platform that ingests OTLP traces. In Sazabi, add a Mastra log source and copy its intake URL. The URL carries your project key, so no auth header is needed: + +```bash title=".env" +SAZABI_INTAKE_URL=https://... +``` + +Use the `custom` provider with HTTP/JSON: + +```typescript title="src/mastra/index.ts" +new OtelExporter({ + provider: { + custom: { + endpoint: process.env.SAZABI_INTAKE_URL!, + protocol: 'http/json', + }, + }, +}) +``` + +See [Sazabi's Mastra guide](https://docs.sazabi.com/catalogs/log-sources/send-to-an-endpoint/mastra) for the full setup. + #### Agnost AI [Agnost AI](https://agnost.ai) ingests OTLP/HTTP protobuf traces and groups them into conversations and users for production agent monitoring. Use the `custom` provider with your organization ID: @@ -149,6 +265,138 @@ Get your Dash0 endpoint from your dashboard. It should be in the format `ingress ::: +#### `SigNoz` + +[SigNoz](https://signoz.io/) is an open-source APM alternative with built-in Tracing support. + +##### Zero-Config Setup + +```bash title=".env" +# Required +SIGNOZ_API_KEY=your-api-key + +# Optional +SIGNOZ_REGION=us # 'us' | 'eu' | 'in' +SIGNOZ_ENDPOINT=https://my-signoz.example.com # For self-hosted +``` + +```typescript title="src/mastra/index.ts" +new OtelExporter({ provider: { signoz: {} } }) +``` + +##### Explicit Configuration + +```typescript title="src/mastra/index.ts" +new OtelExporter({ + provider: { + signoz: { + apiKey: process.env.SIGNOZ_API_KEY, + region: 'us', // 'us' | 'eu' | 'in' + // endpoint: 'https://my-signoz.example.com', // For self-hosted + }, + }, +}) +``` + +#### New Relic + +[New Relic](https://newrelic.com/) provides complete observability with AI monitoring capabilities. + +##### Zero-Config Setup + +```bash title=".env" +# Required +NEW_RELIC_LICENSE_KEY=your-license-key + +# Optional +NEW_RELIC_ENDPOINT=https://otlp.eu01.nr-data.net # For EU region +``` + +```typescript title="src/mastra/index.ts" +new OtelExporter({ provider: { newrelic: {} } }) +``` + +##### Explicit Configuration + +```typescript title="src/mastra/index.ts" +new OtelExporter({ + provider: { + newrelic: { + apiKey: process.env.NEW_RELIC_LICENSE_KEY, + // endpoint: 'https://otlp.eu01.nr-data.net', // For EU region + }, + }, +}) +``` + +#### Traceloop + +[Traceloop](https://www.traceloop.com/) specializes in LLM observability with automatic prompt tracking. + +##### Zero-Config Setup + +```bash title=".env" +# Required +TRACELOOP_API_KEY=your-api-key + +# Optional +TRACELOOP_DESTINATION_ID=my-destination +TRACELOOP_ENDPOINT=https://custom.traceloop.com +``` + +```typescript title="src/mastra/index.ts" +new OtelExporter({ provider: { traceloop: {} } }) +``` + +##### Explicit Configuration + +```typescript title="src/mastra/index.ts" +new OtelExporter({ + provider: { + traceloop: { + apiKey: process.env.TRACELOOP_API_KEY, + destinationId: 'my-destination', // Optional + }, + }, +}) +``` + +#### Laminar + +[Laminar](https://laminar.sh/) provides specialized LLM observability and analytics. + +##### Zero-Config Setup + +```bash title=".env" +# Required +LMNR_PROJECT_API_KEY=your-api-key + +# Optional +LAMINAR_ENDPOINT=https://api.lmnr.ai/v1/traces +``` + +```typescript title="src/mastra/index.ts" +new OtelExporter({ provider: { laminar: {} } }) +``` + +##### Explicit Configuration + +```typescript title="src/mastra/index.ts" +new OtelExporter({ + provider: { + laminar: { + apiKey: process.env.LMNR_PROJECT_API_KEY, + }, + }, +}) +``` + +:::tip Laminar-Native Exporter + +For Laminar-specific features like native span paths, metadata, and tags rendering in the Laminar dashboard, consider using the dedicated [`@mastra/laminar`](/integrations/observability/laminar) exporter instead. It provides optimized integration with Laminar's platform. + +::: + #### Datadog [Datadog](https://www.datadoghq.com/) APM provides application performance monitoring with distributed tracing. To send traces to Datadog via OTLP, you need the Datadog Agent running with OTLP ingestion enabled. @@ -217,254 +465,6 @@ For Datadog-specific features like automatic span type mapping, LLM span categor ::: -#### Laminar - -[Laminar](https://laminar.sh/) provides specialized LLM observability and analytics. - -##### Zero-Config Setup - -```bash title=".env" -# Required -LMNR_PROJECT_API_KEY=your-api-key - -# Optional -LAMINAR_ENDPOINT=https://api.lmnr.ai/v1/traces -``` - -```typescript title="src/mastra/index.ts" -new OtelExporter({ provider: { laminar: {} } }) -``` - -##### Explicit Configuration - -```typescript title="src/mastra/index.ts" -new OtelExporter({ - provider: { - laminar: { - apiKey: process.env.LMNR_PROJECT_API_KEY, - }, - }, -}) -``` - -:::tip Laminar-Native Exporter - -For Laminar-specific features like native span paths, metadata, and tags rendering in the Laminar dashboard, consider using the dedicated [`@mastra/laminar`](/integrations/observability/laminar) exporter instead. It provides optimized integration with Laminar's platform. - -::: - -#### Latitude - -[Latitude](https://latitude.so) is an open-source LLM observability and evaluation platform that ingests OTLP traces. Use the `custom` provider with HTTP/Protobuf, pointing at Latitude's ingestion endpoint and authenticating with your API key and project slug: - -```typescript title="src/mastra/index.ts" -new OtelExporter({ - provider: { - custom: { - endpoint: 'https://ingest.latitude.so/v1/traces', - protocol: 'http/protobuf', - headers: { - Authorization: `Bearer ${process.env.LATITUDE_API_KEY}`, - 'X-Latitude-Project': process.env.LATITUDE_PROJECT, - }, - }, - }, -}) -``` - -Sign up at [console.latitude.so](https://console.latitude.so/login), or self-host and point the endpoint at your own ingestion host. - -#### MLflow - -[MLflow](https://mlflow.org/docs/latest/genai/tracing/integrations/listing/mastra) supports native Mastra tracing through its OTLP endpoint at `/v1/traces`. Use the `custom` provider with HTTP/Protobuf and include the experiment header so traces are routed to the correct MLflow experiment: - -```typescript title="src/mastra/index.ts" -new OtelExporter({ - provider: { - custom: { - endpoint: `${process.env.MLFLOW_TRACKING_URI}/v1/traces`, - protocol: 'http/protobuf', - headers: { - 'x-mlflow-experiment-id': process.env.MLFLOW_EXPERIMENT_ID, - }, - }, - }, -}) -``` - -#### New Relic - -[New Relic](https://newrelic.com/) provides complete observability with AI monitoring capabilities. - -##### Zero-Config Setup - -```bash title=".env" -# Required -NEW_RELIC_LICENSE_KEY=your-license-key - -# Optional -NEW_RELIC_ENDPOINT=https://otlp.eu01.nr-data.net # For EU region -``` - -```typescript title="src/mastra/index.ts" -new OtelExporter({ provider: { newrelic: {} } }) -``` - -##### Explicit Configuration - -```typescript title="src/mastra/index.ts" -new OtelExporter({ - provider: { - newrelic: { - apiKey: process.env.NEW_RELIC_LICENSE_KEY, - // endpoint: 'https://otlp.eu01.nr-data.net', // For EU region - }, - }, -}) -``` - -#### Sazabi - -[Sazabi](https://sazabi.com) is an AI-native observability platform that ingests OTLP traces. In Sazabi, add a Mastra log source and copy its intake URL. The URL carries your project key, so no auth header is needed: - -```bash title=".env" -SAZABI_INTAKE_URL=https://... -``` - -Use the `custom` provider with HTTP/JSON: - -```typescript title="src/mastra/index.ts" -new OtelExporter({ - provider: { - custom: { - endpoint: process.env.SAZABI_INTAKE_URL!, - protocol: 'http/json', - }, - }, -}) -``` - -See [Sazabi's Mastra guide](https://docs.sazabi.com/catalogs/log-sources/send-to-an-endpoint/mastra) for the full setup. - -#### Sentry - -[Sentry](https://sentry.io/) accepts OpenTelemetry traces and logs through its OTLP endpoints. In Sentry, open [**Project Settings** > **Client Keys (DSN)**](https://sentry.io/settings/projects/) and copy the OTLP traces endpoint and authentication header. Add both values to your environment: - -```bash title=".env" -SENTRY_OTLP_ENDPOINT=https://o000000.ingest.sentry.io/api/0000000/integration/otlp/v1/traces -SENTRY_OTLP_AUTH_HEADER="sentry sentry_key=..." -``` - -Use the `custom` provider with HTTP/Protobuf: - -```typescript title="src/mastra/index.ts" -new OtelExporter({ - provider: { - custom: { - endpoint: process.env.SENTRY_OTLP_ENDPOINT!, - protocol: 'http/protobuf', - headers: { - 'x-sentry-auth': process.env.SENTRY_OTLP_AUTH_HEADER!, - }, - }, - }, -}) -``` - -See [Sentry's OTLP documentation](https://docs.sentry.io/concepts/otlp/) for endpoint setup, supported signals, and current ingestion limits. - -Choose an exporter based on your setup: - -- `OtelExporter`: Sends vendor-neutral traces and logs over OTLP. Use it with an existing OpenTelemetry pipeline or when you want backend portability. -- [`SentryExporter`](/integrations/observability/sentry): Uses the Sentry SDK to map Mastra span types to Sentry operations, add AI monitoring attributes, and capture span errors as Sentry issues. - -#### SigNoz - -[SigNoz](https://signoz.io/) is an open-source APM alternative with built-in Tracing support. - -##### Zero-Config Setup - -```bash title=".env" -# Required -SIGNOZ_API_KEY=your-api-key - -# Optional -SIGNOZ_REGION=us # 'us' | 'eu' | 'in' -SIGNOZ_ENDPOINT=https://my-signoz.example.com # For self-hosted -``` - -```typescript title="src/mastra/index.ts" -new OtelExporter({ provider: { signoz: {} } }) -``` - -##### Explicit Configuration - -```typescript title="src/mastra/index.ts" -new OtelExporter({ - provider: { - signoz: { - apiKey: process.env.SIGNOZ_API_KEY, - region: 'us', // 'us' | 'eu' | 'in' - // endpoint: 'https://my-signoz.example.com', // For self-hosted - }, - }, -}) -``` - -#### telemetry.dev - -[telemetry.dev](https://telemetry.dev) ingests OTLP/HTTP protobuf traces and normalizes OpenTelemetry GenAI semantic conventions into model, provider, token, latency, and cost fields. Use the `custom` provider with your project API key: - -```bash title=".env" -TELEMETRY_DEV_API_KEY=td_live_... -``` - -```typescript title="src/mastra/index.ts" -new OtelExporter({ - provider: { - custom: { - endpoint: 'https://ingest.telemetry.dev/v1/traces', - protocol: 'http/protobuf', - headers: { - Authorization: `Bearer ${process.env.TELEMETRY_DEV_API_KEY}`, - }, - }, - }, -}) -``` - -#### Traceloop - -[Traceloop](https://www.traceloop.com/) specializes in LLM observability with automatic prompt tracking. - -##### Zero-Config Setup - -```bash title=".env" -# Required -TRACELOOP_API_KEY=your-api-key - -# Optional -TRACELOOP_DESTINATION_ID=my-destination -TRACELOOP_ENDPOINT=https://custom.traceloop.com -``` - -```typescript title="src/mastra/index.ts" -new OtelExporter({ provider: { traceloop: {} } }) -``` - -##### Explicit Configuration - -```typescript title="src/mastra/index.ts" -new OtelExporter({ - provider: { - traceloop: { - apiKey: process.env.TRACELOOP_API_KEY, - destinationId: 'my-destination', // Optional - }, - }, -}) -``` - #### Custom/Generic OTEL Endpoints For other OTEL-compatible platforms or custom collectors: @@ -525,7 +525,7 @@ If the matching log exporter package isn't installed, log export is silently dis new OtelExporter({ // Provider configuration (required) provider: { - // Use one of: dash0, laminar, newrelic, signoz, traceloop, custom + // Use one of: dash0, signoz, newrelic, traceloop, laminar, custom }, // Per-signal toggles. Both default to true. @@ -577,10 +577,10 @@ Choose the right protocol package based on your provider: | - | - | - | | Dash0 | gRPC | `@opentelemetry/exporter-trace-otlp-grpc` | | Datadog | gRPC | `@opentelemetry/exporter-trace-otlp-grpc` | -| Laminar | HTTP/Protobuf | `@opentelemetry/exporter-trace-otlp-proto` | -| New Relic | HTTP/Protobuf | `@opentelemetry/exporter-trace-otlp-proto` | | SigNoz | HTTP/Protobuf | `@opentelemetry/exporter-trace-otlp-proto` | +| New Relic | HTTP/Protobuf | `@opentelemetry/exporter-trace-otlp-proto` | | Traceloop | HTTP/JSON | `@opentelemetry/exporter-trace-otlp-http` | +| Laminar | HTTP/Protobuf | `@opentelemetry/exporter-trace-otlp-proto` | | Custom | Varies | Depends on your collector | :::warning diff --git a/docs/src/content/en/reference/agents/durable-agent.mdx b/docs/src/content/en/reference/agents/durable-agent.mdx index b381f2a9544..5e7bf3a0aea 100644 --- a/docs/src/content/en/reference/agents/durable-agent.mdx +++ b/docs/src/content/en/reference/agents/durable-agent.mdx @@ -440,7 +440,7 @@ Returns: `boolean`. `true` when this process aborted the run locally or can see #### `abortThreadStream({ threadId, resourceId?, expectedRunId? })` -Aborts the active run on a memory thread with the same abort request as `abortRunStream()`. When this process runs the thread's active run, the abort applies here. When this process has observed the run through `subscribeToThread()`, the abort request is published to the process executing the run, and nothing stops in this process. When the process never saw the run, it looks the run up in the background through the thread's lease and asks the process executing it to stop, publishing the request over the shared PubSub. That lookup runs asynchronously. The method returns before the lookup finishes. The server route [`POST /agents/:agentId/threads/abort`](/reference/server/routes#thread-cancellation-routes) awaits the lookup when the abort wasn't resolved in this process, which is how it reports whether a run on another process was asked to stop. +Aborts the active run on a memory thread with the same abort request as `abortRunStream()`. The run is resolved from this process's thread runtime, so it must have been started here or observed through `subscribeToThread()` on this process. The server route `POST /agents/:agentId/threads/abort` uses this method. Pass `expectedRunId` when the request must only stop a specific run. If another queued run becomes active before the request is handled, the method returns `false` without aborting the successor. Omit `expectedRunId` to abort whichever run is active when the request is handled. @@ -452,7 +452,7 @@ const aborted = durableAgent.abortThreadStream({ }) ``` -Returns: `boolean`. `true` when this process aborted the run, or when the abort request was published to the process executing it. A published request doesn't confirm that the other process stopped the run. `false` is this process's own result: it had no run of the thread's to stop, the active run didn't match `expectedRunId`, or `localOnly: true` kept the abort local and left a run owned by another process alone. An `expectedRunId` mismatch and `localOnly: true` leave the run running by design. Otherwise `false` doesn't rule out a forwarded abort: the background lookup still publishes an abort request to the process holding the lease when it finishes, or finds nothing to publish. A failed lookup or publish is logged as a warning through the Mastra logger. Use the thread-abort route above when you need the forwarded outcome reported. +Returns: `boolean`. `false` when this process has no active run recorded for the thread or the active run doesn't match `expectedRunId`. No abort request is sent in either case. ### Recovery diff --git a/docs/src/content/en/reference/client-js/mastra-client.mdx b/docs/src/content/en/reference/client-js/mastra-client.mdx index 9de478a891e..1c34280cd35 100644 --- a/docs/src/content/en/reference/client-js/mastra-client.mdx +++ b/docs/src/content/en/reference/client-js/mastra-client.mdx @@ -56,7 +56,7 @@ You can also pass `requestContext` as a `Record`. name: 'retries', type: 'number', description: - "The number of times a request will be retried on failure before throwing an error. Retries apply to read requests (GET, HEAD, OPTIONS) by default, and to the observability queries that read server state even though they are sent as POST (aggregateTraces, aggregateSpans, queryTraceThreads, querySpans). Write requests (POST, PUT, PATCH, DELETE) are sent once unless you set `retries` here, so a server error can't repeat a state-changing request. Methods that accept request options, such as `createFeedback()` and `replaceFeedback()`, can also set `retries` per call, and that count takes precedence over this one. This count covers transport retries only: `createScore()`, `createFeedback()`, and `replaceFeedback()` also retry missing-trace and missing-span responses for up to 30 seconds unless you pass `anchorRetryTimeoutMs: 0`, as described in the observability reference under Signal write options.", + "The number of times a request will be retried on failure before throwing an error. Retries apply to read requests (GET, HEAD, OPTIONS) by default, and to the observability queries that read server state even though they are sent as POST (aggregateTraces, aggregateSpans, queryTraceThreads, querySpans). Write requests (POST, PUT, PATCH, DELETE) are sent once unless you set this explicitly, so a server error can't repeat a state-changing request.", isOptional: true, defaultValue: '3 for read requests, 0 for write requests', }, diff --git a/docs/src/content/en/reference/client-js/observability.mdx b/docs/src/content/en/reference/client-js/observability.mdx index 9940a39181c..e2d9ab0ce00 100644 --- a/docs/src/content/en/reference/client-js/observability.mdx +++ b/docs/src/content/en/reference/client-js/observability.mdx @@ -520,7 +520,7 @@ await mastraClient.replaceFeedback({ }) ``` -Use the normalized timestamp from the create response's `data` when available. OSS rejects changes to the original trace or timestamp with `409`. Platform uses the timestamp as part of record identity, so preserve it there too. The client preserves the replacement body across retries, but each accepted PUT retry is a new replacement and can supersede another edit. PUT requests get no transport retries by default, but a client configured with `retries` applies that count here too, and anchor retries stay on unless you turn them off. Pass `{ retries: 0, anchorRetryTimeoutMs: 0 }` as the second argument to disable both transport and anchor retries. `retries: 0` is only redundant when the client has no `retries` configured. +Use the normalized timestamp from the create response's `data` when available. OSS rejects changes to the original trace or timestamp with `409`. Platform uses the timestamp as part of record identity, so preserve it there too. The client preserves the replacement body across retries, but each accepted PUT retry is a new replacement and can supersede another edit. Pass `{ retries: 0, anchorRetryTimeoutMs: 0 }` as the second argument to disable automatic retries. ### Deleting feedback and scores diff --git a/explorations/longmemeval/CHANGELOG.md b/explorations/longmemeval/CHANGELOG.md index 4c5879ae698..9890a57a31e 100644 --- a/explorations/longmemeval/CHANGELOG.md +++ b/explorations/longmemeval/CHANGELOG.md @@ -1,20 +1,5 @@ # @mastra/longmemeval -## 1.1.43-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - -## 1.1.43-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/libsql@1.31.0-alpha.2 - ## 1.1.43-alpha.4 ### Patch Changes diff --git a/explorations/longmemeval/package.json b/explorations/longmemeval/package.json index c86ccf7075f..a64d6dbd805 100644 --- a/explorations/longmemeval/package.json +++ b/explorations/longmemeval/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/longmemeval", - "version": "1.1.43-alpha.6", + "version": "1.1.43-alpha.4", "description": "LongMemEval benchmark implementation for Mastra Memory", "scripts": { "test": "vitest", diff --git a/integrations/opencode/CHANGELOG.md b/integrations/opencode/CHANGELOG.md index d0af7db25ce..04739dcb261 100644 --- a/integrations/opencode/CHANGELOG.md +++ b/integrations/opencode/CHANGELOG.md @@ -1,20 +1,5 @@ # @mastra/opencode -## 0.1.43-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - -## 0.1.43-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/libsql@1.31.0-alpha.2 - ## 0.1.43-alpha.4 ### Patch Changes diff --git a/integrations/opencode/package.json b/integrations/opencode/package.json index 5829b3071b6..b6d1ec21dd6 100644 --- a/integrations/opencode/package.json +++ b/integrations/opencode/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/opencode", - "version": "0.1.43-alpha.6", + "version": "0.1.43-alpha.4", "description": "OpenCode plugin for Mastra Observational Memory", "type": "module", "main": "./dist/index.js", diff --git a/mastracode/factory-ui/src/api/types.ts b/mastracode/factory-ui/src/api/types.ts index 8a539ac17ca..97f1240f132 100644 --- a/mastracode/factory-ui/src/api/types.ts +++ b/mastracode/factory-ui/src/api/types.ts @@ -136,6 +136,8 @@ export interface ProvidersResponse { providers: ProviderInfo[]; /** Tenant mode: whether the caller may write org-wide keys. Absent locally. */ orgKeyAdmin?: boolean; + /** Origin of the Mastra Gateway this server sends model calls to. Absent from servers that predate it. */ + mastraGatewayOrigin?: string; } export interface CustomProvidersResponse { @@ -157,11 +159,8 @@ export interface FactorySkillInfo { description: string; /** SKILL.md body with the frontmatter removed. */ content: string; - /** - * Shipped with Factory, the app's `factory-skills/` folder, `MastraFactory({ skills })`, or `project` for a skill - * this Factory created. Absent from older servers. - */ - origin?: 'bundled' | 'folder' | 'code' | 'project'; + /** Shipped with Factory, the app's `factory-skills/` folder, or `MastraFactory({ skills })`. Absent from older servers. */ + origin?: 'bundled' | 'folder' | 'code'; /** True for a skill Factory ships, including when the app overrides it. Absent from older servers. */ builtIn?: boolean; /** Set when the SKILL.md fails runtime parsing/validation; the agent will not be able to load the skill. */ @@ -172,8 +171,6 @@ export interface FactorySkillInfo { edited?: { updatedBy: string; updatedAt: string }; /** True when the original SKILL.md changed since the project's edit was made. */ originalChanged?: boolean; - /** Set for a skill this Factory created (`origin: 'project'`): who saved it last, and when. */ - created?: { updatedBy: string; updatedAt: string }; } export interface FactorySkillsResponse { diff --git a/mastracode/factory-ui/src/hooks/use-providers.ts b/mastracode/factory-ui/src/hooks/use-providers.ts index 96e451eac7c..52e8a6cec65 100644 --- a/mastracode/factory-ui/src/hooks/use-providers.ts +++ b/mastracode/factory-ui/src/hooks/use-providers.ts @@ -41,6 +41,15 @@ export function useProvidersQuery() { }); } +/** Origin of the server's Mastra Gateway, so run errors from a staging or self-hosted gateway are recognized. */ +export function useMastraGatewayOrigin(): string | undefined { + const { client } = useApiConfig(); + return useQuery({ + ...providersQueryOptions(client), + select: (body: ProvidersResponse) => body.mastraGatewayOrigin, + }).data; +} + /** * Whether the caller may write org-wide keys (tenant mode). Shares the * providers cache entry — no extra request. Fails open when the server diff --git a/mastracode/factory-ui/src/hooks/useFactorySkills.ts b/mastracode/factory-ui/src/hooks/useFactorySkills.ts index 769da4bfd18..f342dbf738c 100644 --- a/mastracode/factory-ui/src/hooks/useFactorySkills.ts +++ b/mastracode/factory-ui/src/hooks/useFactorySkills.ts @@ -19,66 +19,42 @@ export function useFactorySkillsQuery(factoryProjectId?: string) { }); } -/** Sends one write to a project's skills and returns the skill it leaves, or null when it deleted the skill. */ -async function sendSkillWrite( +async function sendSkillEdit( baseUrl: string, - path: string, - method: 'POST' | 'PUT' | 'DELETE', - body?: Record, -): Promise { - const res = await fetch(`${baseUrl}${path}`, { - method, - credentials: 'include', - headers: { 'content-type': 'application/json', Accept: 'application/json' }, - ...(body ? { body: JSON.stringify(body) } : {}), - }); - const json = (await res.json().catch(() => undefined)) as - | { skill?: FactorySkillInfo | null; message?: string; error?: string } + factoryProjectId: string, + name: string, + init: { method: 'PUT'; content: string } | { method: 'DELETE' }, +): Promise { + const res = await fetch( + `${baseUrl}/web/factory/projects/${encodeURIComponent(factoryProjectId)}/skills/${encodeURIComponent(name)}`, + { + method: init.method, + credentials: 'include', + headers: { 'content-type': 'application/json', Accept: 'application/json' }, + ...(init.method === 'PUT' ? { body: JSON.stringify({ content: init.content }) } : {}), + }, + ); + const body = (await res.json().catch(() => undefined)) as + | { skill?: FactorySkillInfo; message?: string; error?: string } | undefined; - if (!res.ok || !json || json.skill === undefined) { - throw new Error(json?.message ?? json?.error ?? `Request failed (${res.status})`); + if (!res.ok || !body?.skill) { + throw new Error(body?.message ?? body?.error ?? `Request failed (${res.status})`); } - return json.skill; + return body.skill; } -const skillsPath = (factoryProjectId: string) => `/web/factory/projects/${encodeURIComponent(factoryProjectId)}/skills`; - -/** Refreshes the skills, and the boards, whose phases flag a skill that is missing. */ -function useInvalidateSkills(factoryProjectId: string | undefined) { - const queryClient = useQueryClient(); - return () => - Promise.all([ - queryClient.invalidateQueries({ queryKey: queryKeys.factorySkills(factoryProjectId) }), - queryClient.invalidateQueries({ queryKey: queryKeys.boardCatalog(factoryProjectId) }), - ]); -} - -/** - * Save (`content`) or revert (`content: null`) a project's edit of one skill. For a skill the project created, - * saving updates it and `content: null` deletes it. - */ +/** Save (`content`) or revert (`content: null`) a project's edit of one skill. */ export function useFactorySkillEditMutation(factoryProjectId: string | undefined) { const { baseUrl } = useApiConfig(); - const invalidate = useInvalidateSkills(factoryProjectId); + const queryClient = useQueryClient(); return useMutation({ mutationFn: ({ name, content }: { name: string; content: string | null }) => - sendSkillWrite( + sendSkillEdit( baseUrl, - `${skillsPath(factoryProjectId!)}/${encodeURIComponent(name)}`, - content === null ? 'DELETE' : 'PUT', - content === null ? undefined : { content }, + factoryProjectId!, + name, + content === null ? { method: 'DELETE' } : { method: 'PUT', content }, ), - onSuccess: invalidate, - }); -} - -/** Creates a skill for one Factory project. Mirrors `POST /web/factory/projects/:id/skills`. */ -export function useFactorySkillCreateMutation(factoryProjectId: string | undefined) { - const { baseUrl } = useApiConfig(); - const invalidate = useInvalidateSkills(factoryProjectId); - return useMutation({ - mutationFn: ({ name, content }: { name: string; content: string }) => - sendSkillWrite(baseUrl, skillsPath(factoryProjectId!), 'POST', { name, content }), - onSuccess: invalidate, + onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.factorySkills(factoryProjectId) }), }); } diff --git a/mastracode/factory-ui/src/ui/__tests__/AppStartup.msw.test.tsx b/mastracode/factory-ui/src/ui/__tests__/AppStartup.msw.test.tsx index 77a84ecf952..043f8c2bf43 100644 --- a/mastracode/factory-ui/src/ui/__tests__/AppStartup.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/__tests__/AppStartup.msw.test.tsx @@ -168,7 +168,7 @@ describe('Opening Factory', () => { models: USABLE_MODEL, cards: STARTER_COUNTS, }, - { page: 'Settings', path: '/factories/factory-1/settings/account', cards: [] }, + { page: 'Settings', path: '/factories/factory-1/settings/preferences', cards: [] }, { page: 'Work before a repository is linked', path: '/factories/factory-1/work', diff --git a/mastracode/factory-ui/src/ui/__tests__/SettingsScopesPage.msw.test.tsx b/mastracode/factory-ui/src/ui/__tests__/SettingsScopesPage.msw.test.tsx index ff8660859f2..0c6bbddf967 100644 --- a/mastracode/factory-ui/src/ui/__tests__/SettingsScopesPage.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/__tests__/SettingsScopesPage.msw.test.tsx @@ -164,18 +164,6 @@ describe('Settings ownership', () => { expect(screen.getByRole('link', { name: 'Models' })).toHaveAttribute('aria-current', 'page'); }); - it('sends retired Preferences links to My account, where theme and completion sound now live', async () => { - const router = renderSettings('preferences', { search: '?from=chat' }); - - expect(await screen.findByRole('radiogroup', { name: 'Theme' })).toBeInTheDocument(); - expect(router.state.location).toMatchObject({ - pathname: '/factories/fp-1/settings/account', - search: '?from=chat', - state: { settingsReturnTo: '/factories/fp-1/work' }, - }); - expect(screen.getByRole('link', { name: 'My account' })).toHaveAttribute('aria-current', 'page'); - }); - it('sends retired Factory memory links to Memory', async () => { const router = renderSettings('factory-memory'); diff --git a/mastracode/factory-ui/src/ui/domains/auth/components/SidebarSettingsLink.tsx b/mastracode/factory-ui/src/ui/domains/auth/components/SidebarSettingsLink.tsx index 22251d8b4d5..989e5dca0b2 100644 --- a/mastracode/factory-ui/src/ui/domains/auth/components/SidebarSettingsLink.tsx +++ b/mastracode/factory-ui/src/ui/domains/auth/components/SidebarSettingsLink.tsx @@ -39,7 +39,7 @@ export function SidebarSettingsLink() { const account = auth.data; const userName = signedInName(account); - const url = settingsSectionPath(factoryId, 'account'); + const url = settingsSectionPath(factoryId, 'preferences'); const backToAppState = settingsOpen ? location.state : { from: location }; return ( diff --git a/mastracode/factory-ui/src/ui/domains/auth/components/__tests__/SidebarSettingsLink.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/auth/components/__tests__/SidebarSettingsLink.msw.test.tsx index eda82281875..8996b436fad 100644 --- a/mastracode/factory-ui/src/ui/domains/auth/components/__tests__/SidebarSettingsLink.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/auth/components/__tests__/SidebarSettingsLink.msw.test.tsx @@ -72,7 +72,7 @@ describe('SidebarSettingsLink', () => { expect(within(link).getByRole('img', { name: 'Dev' })).toHaveAttribute('src', avatarUrl); await user.click(link); - expect(currentPath()).toHaveTextContent('/factories/fp-1/settings/account'); + expect(currentPath()).toHaveTextContent('/factories/fp-1/settings/preferences'); expect(screen.getByRole('link', { name: 'Settings for Dev' })).toHaveAttribute('aria-current', 'page'); }); @@ -123,7 +123,7 @@ describe('SidebarSettingsLink', () => { link.focus(); await user.keyboard('{Enter}'); - expect(currentPath()).toHaveTextContent('/factories/fp-1/settings/account'); + expect(currentPath()).toHaveTextContent('/factories/fp-1/settings/preferences'); }); it.each([404, 401, 500])('keeps settings available without a signed-in account (HTTP %s)', async status => { @@ -133,6 +133,6 @@ describe('SidebarSettingsLink', () => { await user.click(await screen.findByRole('link', { name: 'Settings' })); - expect(currentPath()).toHaveTextContent('/factories/fp-1/settings/account'); + expect(currentPath()).toHaveTextContent('/factories/fp-1/settings/preferences'); }); }); diff --git a/mastracode/factory-ui/src/ui/domains/boardConfig/__tests__/FactorySkillsSection.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/boardConfig/__tests__/FactorySkillsSection.msw.test.tsx index 55c8a17905c..3b4431ccfb6 100644 --- a/mastracode/factory-ui/src/ui/domains/boardConfig/__tests__/FactorySkillsSection.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/boardConfig/__tests__/FactorySkillsSection.msw.test.tsx @@ -5,14 +5,13 @@ import { describe, expect, it } from 'vitest'; import { builtinBoardCatalog } from '../../../../../e2e/ui/board-catalog'; import { server } from '../../../../../e2e/ui/msw-server'; -import { TEST_BASE_URL, renderWithProviders, waitForMutationsIdle } from '../../../../../e2e/ui/render'; +import { TEST_BASE_URL, renderWithProviders } from '../../../../../e2e/ui/render'; import type { BoardCatalogResponse, FactorySkillInfo, FactorySkillsResponse } from '../../../../api/types'; import { FactorySkillsSection } from '../components/FactorySkillsSection'; const SKILLS_URL = `${TEST_BASE_URL}/web/factory/skills`; const BOARDS_URL = `${TEST_BASE_URL}/web/factory/projects/fp-1/boards`; const SKILL_URL = `${TEST_BASE_URL}/web/factory/projects/fp-1/skills/:name`; -const CREATE_URL = `${TEST_BASE_URL}/web/factory/projects/fp-1/skills`; const bundled = { origin: 'bundled', builtIn: true } as const; @@ -50,7 +49,7 @@ function serve({ const { content } = (await request.json()) as { content: string }; const name = String(params.name); writes.push({ method: 'PUT', name, content }); - if (!content.includes(`name: ${JSON.stringify(name)}\n`)) { + if (!content.includes(`name: ${name}\n`)) { return HttpResponse.json({ error: 'invalid_skill', message: 'name must match' }, { status: 400 }); } const description = JSON.parse(/^description: (.*)$/m.exec(content)![1]) as string; @@ -68,34 +67,9 @@ function serve({ ); return HttpResponse.json({ skill: current.find(skill => skill.name === name) }); }), - http.post(CREATE_URL, async ({ request }) => { - const { name, content } = (await request.json()) as { name: string; content: string }; - writes.push({ method: 'POST', name, content }); - if (current.some(skill => skill.name === name)) { - return HttpResponse.json( - { error: 'skill_exists', message: `A skill named "${name}" already exists. Edit it instead.` }, - { status: 409 }, - ); - } - const description = JSON.parse(/^description: (.*)$/m.exec(content)![1]) as string; - const created: FactorySkillInfo = { - name, - description, - content: content.slice(content.indexOf('\n---\n') + 5).trim(), - origin: 'project', - builtIn: false, - created: { updatedBy: 'admin-1', updatedAt: '2026-11-17T00:00:00.000Z' }, - }; - current = [...current, created]; - return HttpResponse.json({ skill: created }, { status: 201 }); - }), http.delete(SKILL_URL, ({ params }) => { const name = String(params.name); writes.push({ method: 'DELETE', name }); - if (current.find(skill => skill.name === name)?.origin === 'project') { - current = current.filter(skill => skill.name !== name); - return HttpResponse.json({ skill: null }); - } const original = catalog.find(skill => skill.name === name)!; current = current.map(skill => skill.name === name ? { ...original, edited: undefined, originalChanged: undefined } : skill, @@ -245,7 +219,7 @@ describe('FactorySkillsSection', () => { { method: 'PUT', name: 'changelog-lint', - content: '---\nname: "changelog-lint"\ndescription: "Our lint: check # first"\n---\n\n# Lint\n', + content: '---\nname: changelog-lint\ndescription: "Our lint: check # first"\n---\n\n# Lint\n', }, ]); expect(await within(card('changelog-lint')).findByText('Edited')).toBeInTheDocument(); @@ -383,125 +357,6 @@ describe('FactorySkillsSection', () => { }); }); - describe('creating a skill', () => { - it('creates a skill for this Factory and lists it as custom', async () => { - const { writes } = serve(); - const user = userEvent.setup(); - const { client } = renderSection(); - - await user.click(await screen.findByRole('button', { name: 'New skill' })); - const dialog = await screen.findByRole('dialog', { name: 'New skill' }); - const create = within(dialog).getByRole('button', { name: 'Create' }); - expect(create).toBeDisabled(); - await user.type(within(dialog).getByRole('textbox', { name: 'Name' }), 'release-notes'); - expect(create).toBeDisabled(); - await user.type(within(dialog).getByRole('textbox', { name: 'Description' }), 'Write notes: what # changed'); - await user.click(create); - - await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); - expect(writes).toEqual([ - { - method: 'POST', - name: 'release-notes', - content: '---\nname: "release-notes"\ndescription: "Write notes: what # changed"\n---\n\n\n', - }, - ]); - const created = await screen.findByRole('button', { name: /^release-notes/ }); - expect(within(created).getByText('Custom')).toBeInTheDocument(); - expect(within(card('changelog-lint')).queryByText('Custom')).not.toBeInTheDocument(); - await waitForMutationsIdle(client); - }); - - it('keeps an all-digit name a string in the SKILL.md it sends', async () => { - const { writes } = serve(); - const user = userEvent.setup(); - const { client } = renderSection(); - - await user.click(await screen.findByRole('button', { name: 'New skill' })); - const dialog = await screen.findByRole('dialog', { name: 'New skill' }); - await user.type(within(dialog).getByRole('textbox', { name: 'Name' }), '123'); - await user.type(within(dialog).getByRole('textbox', { name: 'Description' }), 'Numbered'); - await user.click(within(dialog).getByRole('button', { name: 'Create' })); - - await waitFor(() => expect(writes).toHaveLength(1)); - expect(writes[0]).toMatchObject({ method: 'POST', name: '123' }); - expect(writes[0].content).toMatch(/^---\nname: "123"\n/); - await waitForMutationsIdle(client); - }); - - it('explains a name agents cannot use and keeps Create disabled', async () => { - const { writes } = serve(); - const user = userEvent.setup(); - renderSection(); - - await user.click(await screen.findByRole('button', { name: 'New skill' })); - const dialog = await screen.findByRole('dialog', { name: 'New skill' }); - await user.type(within(dialog).getByRole('textbox', { name: 'Name' }), 'Release_Notes'); - await user.type(within(dialog).getByRole('textbox', { name: 'Description' }), 'Write release notes'); - - expect(within(dialog).getByText(/lowercase letters, digits, and single hyphens/)).toBeInTheDocument(); - expect(within(dialog).getByRole('button', { name: 'Create' })).toBeDisabled(); - expect(writes).toEqual([]); - }); - - it('shows why the server refused it and keeps the editor open', async () => { - serve(); - const user = userEvent.setup(); - const { client } = renderSection(); - - await user.click(await screen.findByRole('button', { name: 'New skill' })); - const dialog = await screen.findByRole('dialog', { name: 'New skill' }); - await user.type(within(dialog).getByRole('textbox', { name: 'Name' }), 'changelog-lint'); - await user.type(within(dialog).getByRole('textbox', { name: 'Description' }), 'Mine'); - await user.click(within(dialog).getByRole('button', { name: 'Create' })); - - expect(await within(dialog).findByRole('alert')).toHaveTextContent( - 'A skill named "changelog-lint" already exists. Edit it instead.', - ); - expect(screen.getByRole('dialog', { name: 'New skill' })).toBeInTheDocument(); - await waitForMutationsIdle(client); - }); - - it('offers no New skill to members who are not admins', async () => { - serve({ canEdit: false }); - renderSection(); - - expect(await screen.findByRole('button', { name: 'View configure-factory-rules' })).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'New skill' })).not.toBeInTheDocument(); - }); - }); - - it('deletes a skill this Factory created once confirmed, and offers no revert for it', async () => { - const releaseNotes: FactorySkillInfo = { - name: 'release-notes', - description: 'Write release notes', - content: '# Notes', - origin: 'project', - builtIn: false, - created: { updatedBy: 'admin-1', updatedAt: '2026-11-17T00:00:00.000Z' }, - }; - const { writes } = serve({ catalog: [...skills, releaseNotes] }); - const user = userEvent.setup(); - const { client } = renderSection(); - - await user.click(await screen.findByRole('button', { name: 'Edit release-notes' })); - const dialog = await screen.findByRole('dialog', { name: 'Edit skill' }); - expect(within(dialog).queryByRole('button', { name: 'Revert to original' })).not.toBeInTheDocument(); - await user.click(within(dialog).getByRole('button', { name: 'Delete' })); - expect(within(dialog).getByText(/Delete release-notes\?/)).toBeInTheDocument(); - expect(writes).toEqual([]); - - // Keep backs out without deleting. - await user.click(within(dialog).getByRole('button', { name: 'Keep' })); - await user.click(within(dialog).getByRole('button', { name: 'Delete' })); - await user.click(within(dialog).getByRole('button', { name: 'Delete skill' })); - - await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()); - expect(writes).toEqual([{ method: 'DELETE', name: 'release-notes' }]); - await waitFor(() => expect(screen.queryByRole('button', { name: /^release-notes/ })).not.toBeInTheDocument()); - await waitForMutationsIdle(client); - }); - it('surfaces a load failure from the server', async () => { serve(); server.use(http.get(SKILLS_URL, () => HttpResponse.json({ error: 'boom' }, { status: 500 }))); diff --git a/mastracode/factory-ui/src/ui/domains/boardConfig/components/FactorySkillsSection.tsx b/mastracode/factory-ui/src/ui/domains/boardConfig/components/FactorySkillsSection.tsx index c3ca6dc5fb0..377b31ae655 100644 --- a/mastracode/factory-ui/src/ui/domains/boardConfig/components/FactorySkillsSection.tsx +++ b/mastracode/factory-ui/src/ui/domains/boardConfig/components/FactorySkillsSection.tsx @@ -17,7 +17,6 @@ import { FactorySkillEditorDialog } from '../../settings/components/FactorySkill import { IconFileText } from '@mastra/playground-ui/icons/central/IconFileText'; import { IconPencil } from '@mastra/playground-ui/icons/central/IconPencil'; import { IconCodeBrackets } from '@mastra/playground-ui/icons/central/IconCodeBrackets'; -import { IconPlusMedium } from '@mastra/playground-ui/icons/central/IconPlusMedium'; /** Skills some board's settings already show: the ones its phases run. None while the boards are unknown. */ function boardSkillNames(boards: InstalledBoardInfo[] | undefined): Set { @@ -68,7 +67,6 @@ function SkillCard({ skill, factoryId, canEdit }: { skill: FactorySkillInfo; fac {skill.builtIn && skill.origin !== undefined && skill.origin !== 'bundled' && ( Overridden by app )} - {skill.origin === 'project' && Custom} {skill.edited && Edited} {skill.error ? ( @@ -108,20 +106,6 @@ function SkillCard({ skill, factoryId, canEdit }: { skill: FactorySkillInfo; fac ); } -/** Opens the editor on a new skill; admins of an open Factory only. */ -function NewSkillButton({ factoryId }: { factoryId: string }) { - const [creating, setCreating] = useState(false); - - return ( -
- - {creating && setCreating(false)} />} -
- ); -} - /** * The skills no board phase runs. A skill a phase runs lives on that phase's page, so it isn't listed twice. */ @@ -136,7 +120,6 @@ export function FactorySkillsSection({ factoryId }: { factoryId?: string }) { return (
- {factoryId !== undefined && canEdit && } {loading && ( Loading skills… diff --git a/mastracode/factory-ui/src/ui/domains/boardConfig/components/PhaseConfig.tsx b/mastracode/factory-ui/src/ui/domains/boardConfig/components/PhaseConfig.tsx index af4aaf5544a..f9076fe2a9f 100644 --- a/mastracode/factory-ui/src/ui/domains/boardConfig/components/PhaseConfig.tsx +++ b/mastracode/factory-ui/src/ui/domains/boardConfig/components/PhaseConfig.tsx @@ -59,7 +59,6 @@ function SkillBadges({ skill, missing }: { skill?: FactorySkillInfo; missing: bo {missing && Not found} {skill?.error && Failed to load} {skill?.builtIn && skill.origin !== undefined && skill.origin !== 'bundled' && Overridden by app} - {skill?.origin === 'project' && Custom} {skill?.edited && Edited} ); diff --git a/mastracode/factory-ui/src/ui/domains/chat/components/RunErrorNotice.tsx b/mastracode/factory-ui/src/ui/domains/chat/components/RunErrorNotice.tsx index 60d1c2533f2..ac633b59f2b 100644 --- a/mastracode/factory-ui/src/ui/domains/chat/components/RunErrorNotice.tsx +++ b/mastracode/factory-ui/src/ui/domains/chat/components/RunErrorNotice.tsx @@ -17,6 +17,7 @@ import type { RunErrorRecovery } from '@mastra/factory/run-error'; import { useContext } from 'react'; import type { ComponentType } from 'react'; +import { useMastraGatewayOrigin } from '../../../../hooks/use-providers'; import { ChatSessionContext } from '../context/ChatSessionContext'; import { ChatThreadMessagesContext } from '../context/ChatThreadMessagesContext'; import { AddGatewayCreditsAction } from './AddGatewayCreditsAction'; @@ -37,7 +38,9 @@ const RECOVERY_ACTIONS: Record = { - 'factory-session': 'Factory session', - github: 'GitHub', - gitlab: 'GitLab', - linear: 'Linear', - jira: 'Jira', - slack: 'Slack', -}; - -/** A readable name for a notification source; unknown sources fall back to their id in sentence case. */ -export function notificationSourceName(source: string): string { - if (Object.hasOwn(NOTIFICATION_SOURCE_NAMES, source)) return NOTIFICATION_SOURCE_NAMES[source]; - const words = source.replace(/[-_]+/g, ' ').trim(); - return words ? words.charAt(0).toUpperCase() + words.slice(1) : source; -} - export function NotificationSummaryCard({ entry }: { entry: NotificationSummaryEntry }) { - const sources = Object.entries(entry.bySource).filter(([, count]) => count > 0); - const counted = entry.pending > 0 && sources.length > 0; - const urgent = (entry.byPriority.urgent ?? 0) > 0 || (entry.byPriority.high ?? 0) > 0; - - return ( - - - - - - Notifications - - {counted ? `${entry.pending} new` : entry.message} - - {counted && - sources.map(([source, count]) => ( - - {sources.length > 1 ? `${notificationSourceName(source)} ${count}` : notificationSourceName(source)} - - ))} - - - ); + return ; } export function notificationMetadata(entry: MessageEntry): Array { diff --git a/mastracode/factory-ui/src/ui/domains/chat/components/__tests__/TranscriptErrors.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/chat/components/__tests__/TranscriptErrors.msw.test.tsx index bc0bd2f0d22..58e27740ef5 100644 --- a/mastracode/factory-ui/src/ui/domains/chat/components/__tests__/TranscriptErrors.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/chat/components/__tests__/TranscriptErrors.msw.test.tsx @@ -319,6 +319,39 @@ describe('chat run errors', () => { expect(addCredits).toHaveAttribute('target', '_blank'); }); + describe("a gateway's own rate limit from a self-hosted gateway", () => { + const gatewayLimit = (): MastraDBMessage => { + const message = 'Gateway key requests limit exceeded. Retry in 12s.'; + // Saved by a core version that records the request's origin; this core's type does not name it yet. + const error = { + name: 'AI_APICallError', + message, + statusCode: 429, + responseBody: JSON.stringify({ error: { type: 'rate_limit_error', code: 'rate_limit_exceeded', message } }), + modelId: 'anthropic/claude-opus-4-5', + requestOrigin: 'http://127.0.0.1:4180', + }; + return { ...failedReply(), content: { format: 2, parts: [{ type: 'error', error }] } }; + }; + + it('names the gateway once the server reports that origin as its gateway', async () => { + server.use( + http.get(`${TEST_BASE_URL}/web/config/providers`, () => + HttpResponse.json({ providers: [], mastraGatewayOrigin: 'http://127.0.0.1:4180' }), + ), + ); + renderWithProviders(); + + expect(await screen.findByText('Mastra Gateway rate limit reached')).toBeVisible(); + }); + + it('stays a provider rate limit while the server names no gateway origin', async () => { + renderWithProviders(); + + expect(await screen.findByText('Provider rate limit reached')).toBeVisible(); + }); + }); + it('continues a timed-out run from the card', async () => { const sentMessages: unknown[] = []; server.use( diff --git a/mastracode/factory-ui/src/ui/domains/chat/components/__tests__/TranscriptNotifications.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/chat/components/__tests__/TranscriptNotifications.msw.test.tsx index 7196cd9da9e..f84f8327594 100644 --- a/mastracode/factory-ui/src/ui/domains/chat/components/__tests__/TranscriptNotifications.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/chat/components/__tests__/TranscriptNotifications.msw.test.tsx @@ -56,80 +56,22 @@ describe('Transcript notifications', () => { }); describe('when pending notifications are summarized', () => { - it('says how many are new and names their source', () => { + it('puts the summary in the transcript under its own label', () => { renderEntries([ { kind: 'notification_summary', id: 'summary', - message: 'factory-session: 1', - pending: 1, - bySource: { 'factory-session': 1 }, - byPriority: { low: 1 }, - notificationIds: ['1'], + message: '2 pull requests and 1 issue need attention.', + pending: 3, + bySource: { github: 3 }, + byPriority: { high: 3 }, + notificationIds: ['1', '2', '3'], }, ]); - const summary = screen.getByRole('group', { name: 'Notification summary' }); - expect(summary).toHaveAttribute('data-notification-state', 'summary'); - expect(within(summary).getByText('Notifications')).toBeVisible(); - expect(within(summary).getByText('1 new')).toBeVisible(); - expect(within(summary).getByText('Factory session')).toBeVisible(); - expect(within(summary).queryByText('factory-session: 1')).not.toBeInTheDocument(); - expect(within(summary).queryByRole('button')).not.toBeInTheDocument(); - }); - - it('counts each source when several are pending, including ones it has no name for', () => { - renderEntries([ - { - kind: 'notification_summary', - id: 'summary', - message: 'github: 3, my-webhook: 1', - pending: 4, - bySource: { github: 3, 'my-webhook': 1 }, - byPriority: { high: 3, low: 1 }, - notificationIds: ['1', '2', '3', '4'], - }, - ]); - - const summary = within(screen.getByRole('group', { name: 'Notification summary' })); - expect(summary.getByText('4 new')).toBeVisible(); - expect(summary.getByText('GitHub 3')).toBeVisible(); - expect(summary.getByText('My webhook 1')).toBeVisible(); - }); - - it('falls back to the summary text when it carries no counts', () => { - renderEntries([ - { - kind: 'notification_summary', - id: 'summary', - message: 'No pending notifications', - pending: 0, - bySource: {}, - byPriority: {}, - notificationIds: [], - }, - ]); - - const summary = within(screen.getByRole('group', { name: 'Notification summary' })); - expect(summary.getByText('No pending notifications')).toBeVisible(); - }); - - it('names a source that collides with a built-in object key from its id', () => { - renderEntries([ - { - kind: 'notification_summary', - id: 'summary', - message: '__proto__: 1', - pending: 1, - bySource: JSON.parse('{"__proto__": 1}') as Record, - byPriority: { low: 1 }, - notificationIds: ['1'], - }, - ]); - - const summary = within(screen.getByRole('group', { name: 'Notification summary' })); - expect(summary.getByText('1 new')).toBeVisible(); - expect(summary.getByText('Proto')).toBeVisible(); + const notification = within(screen.getByRole('group', { name: 'Notification: Notification summary' })); + expect(notification.getByText('2 pull requests and 1 issue need attention.')).toBeVisible(); + expect(notification.queryByRole('button')).not.toBeInTheDocument(); }); }); }); diff --git a/mastracode/factory-ui/src/ui/domains/factory/components/BoardColumn.tsx b/mastracode/factory-ui/src/ui/domains/factory/components/BoardColumn.tsx index c3b1a773797..4995511b2cf 100644 --- a/mastracode/factory-ui/src/ui/domains/factory/components/BoardColumn.tsx +++ b/mastracode/factory-ui/src/ui/domains/factory/components/BoardColumn.tsx @@ -10,7 +10,7 @@ import { BoardStageIcon } from './BoardIcons'; /** Header cells and card lanes share this so the two rows stay column-aligned. */ function columnWidthClass(collapsed: boolean): string { - return cn('min-w-0 shrink-0 transition-[width] motion-reduce:transition-none', collapsed ? 'w-14' : 'w-80'); + return cn('w-80 min-w-0 shrink-0 transition-[width] motion-reduce:transition-none', collapsed && 'lg:w-14'); } function ColumnTaskBadge({ count, total, label }: { count: number; total: number; label: string }) { @@ -73,7 +73,12 @@ export function BoardColumnHeader({ }) { if (collapsed) { return ( -
+
{headerAction ? ( -
+
{headerAction}
) : null} @@ -96,7 +106,7 @@ export function BoardColumnHeader({ tone="muted" as="h2" variant="label" - className="pointer-events-none absolute top-full left-1/2 m-0 -translate-x-1/2 py-1 whitespace-nowrap [writing-mode:vertical-rl]" + className="pointer-events-none absolute top-full right-0 m-0 py-1 whitespace-nowrap [writing-mode:horizontal-tb] lg:right-auto lg:left-1/2 lg:-translate-x-1/2 lg:[writing-mode:vertical-rl]" > {label} diff --git a/mastracode/factory-ui/src/ui/domains/search/__tests__/GlobalSearch.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/search/__tests__/GlobalSearch.msw.test.tsx index 77ad00546b6..54b436e50f8 100644 --- a/mastracode/factory-ui/src/ui/domains/search/__tests__/GlobalSearch.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/search/__tests__/GlobalSearch.msw.test.tsx @@ -307,7 +307,7 @@ function stubSearchApi(options: StubSearchOptions = {}): SearchRequestState { return state; } -function renderSearchRoute(initialEntry = `/factories/${ACTIVE_FACTORY_ID}/settings/account`) { +function renderSearchRoute(initialEntry = `/factories/${ACTIVE_FACTORY_ID}/settings/preferences`) { const router = createMemoryRouter(createAppRoutes(), { initialEntries: [initialEntry] }); const client = createQueryClient(); renderWithProviders( @@ -378,7 +378,7 @@ describe('Global search', () => { const user = userEvent.setup(); renderSearchRoute(); - await screen.findByRole('heading', { name: 'My account' }); + await screen.findByRole('heading', { name: 'Preferences' }); const settingsNavigation = await screen.findByRole('navigation', { name: 'Settings sections' }); const focusedBeforeSearch = within(settingsNavigation).getByRole('button', { name: 'Back to app' }); act(() => focusedBeforeSearch.focus()); @@ -476,7 +476,7 @@ describe('Global search', () => { 'Work', 'Pull requests', 'Rules', - 'My account', + 'Preferences', 'Manage Factory', 'Connections', 'Repositories', @@ -1024,7 +1024,7 @@ describe('Global search', () => { it('selects Settings with origin state and closes without creating a session', async () => { const requests = stubSearchApi(); - const origin = `/factories/${ACTIVE_FACTORY_ID}/settings/account`; + const origin = `/factories/${ACTIVE_FACTORY_ID}/settings/preferences`; const user = userEvent.setup(); const { router } = renderSearchRoute(origin); const dialog = await openWithShortcut(); @@ -1067,7 +1067,7 @@ describe('Global search', () => { }, ])('selects $title on the declared route and closes search', async ({ title, path, preservesOrigin }) => { const requests = stubSearchApi(); - const origin = `/factories/${ACTIVE_FACTORY_ID}/settings/account`; + const origin = `/factories/${ACTIVE_FACTORY_ID}/settings/preferences`; const user = userEvent.setup(); const { router } = renderSearchRoute(origin); const dialog = await openWithShortcut(); diff --git a/mastracode/factory-ui/src/ui/domains/search/components/GlobalSearchNavigationResults.tsx b/mastracode/factory-ui/src/ui/domains/search/components/GlobalSearchNavigationResults.tsx index 64172129603..33abe233362 100644 --- a/mastracode/factory-ui/src/ui/domains/search/components/GlobalSearchNavigationResults.tsx +++ b/mastracode/factory-ui/src/ui/domains/search/components/GlobalSearchNavigationResults.tsx @@ -51,10 +51,10 @@ export function GlobalSearchNavigationResults({ /> } - title={SETTINGS_SECTION_LABELS.account} + title={SETTINGS_SECTION_LABELS.preferences} subtitle="Settings" - value={`My account Settings account profile preferences theme ${settingsSectionPath(factoryId, 'account')}`} - onSelect={() => onSelect(settingsSectionPath(factoryId, 'account'), true)} + value={`Preferences Settings preferences ${settingsSectionPath(factoryId, 'preferences')}`} + onSelect={() => onSelect(settingsSectionPath(factoryId, 'preferences'), true)} /> } diff --git a/mastracode/factory-ui/src/ui/domains/settings/components/AccountSettingsSection.tsx b/mastracode/factory-ui/src/ui/domains/settings/components/AccountSettingsSection.tsx index 10a1d0446e3..f8378c5e17c 100644 --- a/mastracode/factory-ui/src/ui/domains/settings/components/AccountSettingsSection.tsx +++ b/mastracode/factory-ui/src/ui/domains/settings/components/AccountSettingsSection.tsx @@ -7,7 +7,6 @@ import { useFactoryAuth } from '../../../../hooks/useFactoryAuth'; import { clearMastraCodeStorage, redirectToLogout } from '../../auth/services/auth'; import { SettingsContainer, SettingsRow, SettingsSkeleton } from '@mastra/playground-ui/new/settings'; -import { PreferencesSettings } from './SettingsPanel.parts'; import { SettingsSubsection } from './SettingsSubsection'; import { IconArrowBoxLeft } from '@mastra/playground-ui/icons/central/IconArrowBoxLeft'; @@ -39,35 +38,7 @@ function AccountValue({ children }: { children: string }) { export function AccountSettingsSection() { const auth = useFactoryAuth(); const { baseUrl } = useApiConfig(); - const signedIn = !!auth.data?.authEnabled && auth.data.authenticated; - const logOut = () => { - clearMastraCodeStorage(); - redirectToLogout(baseUrl); - }; - - // Preferences are stored in this browser, so they don't wait on, or disappear with, the account details. - return ( - <> - - - {signedIn && ( - - - - - - - - )} - - ); -} - -function ProfileSubsection({ auth }: { auth: ReturnType }) { if (auth.isPending) { return ( @@ -93,33 +64,50 @@ function ProfileSubsection({ auth }: { auth: ReturnType } const user = state.user; + const logOut = () => { + clearMastraCodeStorage(); + redirectToLogout(baseUrl); + }; + return ( - - - - {user?.name ?? 'Not provided'} - - - {user?.email ?? 'Not provided'} - - - {authProviderLabel(state.provider)} - - {user?.userId && ( - - + <> + + + + {user?.name ?? 'Not provided'} - )} - {user?.organizationId && ( - - + + {user?.email ?? 'Not provided'} - )} - - + + {authProviderLabel(state.provider)} + + {user?.userId && ( + + + + )} + {user?.organizationId && ( + + + + )} + + + + + + + + + + ); } diff --git a/mastracode/factory-ui/src/ui/domains/settings/components/FactorySkillEditorDialog.tsx b/mastracode/factory-ui/src/ui/domains/settings/components/FactorySkillEditorDialog.tsx index 37e049e425b..24f7de88238 100644 --- a/mastracode/factory-ui/src/ui/domains/settings/components/FactorySkillEditorDialog.tsx +++ b/mastracode/factory-ui/src/ui/domains/settings/components/FactorySkillEditorDialog.tsx @@ -14,31 +14,20 @@ import { SkillSimpleForm } from '@mastra/playground-ui/domains/skills/skill-simp import { useState } from 'react'; import type { FactorySkillInfo } from '../../../../api/types'; -import { useFactorySkillCreateMutation, useFactorySkillEditMutation } from '../../../../hooks/useFactorySkills'; +import { useFactorySkillEditMutation } from '../../../../hooks/useFactorySkills'; interface FactorySkillEditorDialogProps { - /** The skill to open; without one the dialog creates a new skill. */ - skill?: FactorySkillInfo; + skill: FactorySkillInfo; /** The Factory project whose copy of the skill is edited; without one the skill is view-only. */ factoryId?: string; canEdit: boolean; onClose: () => void; } -/** The names the server accepts: what agents call the skill by, and its folder name. */ -const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; -const MAX_SKILL_NAME_LENGTH = 64; - -function nameProblem(name: string): string | undefined { - if (name === '' || (SKILL_NAME_RE.test(name) && name.length <= MAX_SKILL_NAME_LENGTH)) return undefined; - return 'Use up to 64 lowercase letters, digits, and single hyphens, such as release-notes.'; -} - /** * Writes the editor's fields back as a SKILL.md. Values are JSON-quoted, which - * YAML reads as the same strings, so descriptions with `:` or `#` stay intact - * and a name such as `123` stays a string, and frontmatter fields the editor - * does not show are kept. + * YAML reads as the same strings, so descriptions with `:` or `#` stay intact, + * and frontmatter fields the editor does not show are kept. */ export function composeSkillMarkdown({ name, @@ -52,7 +41,7 @@ export function composeSkillMarkdown({ instructions: string; }): string { const fields = [ - `name: ${JSON.stringify(name)}`, + `name: ${name}`, `description: ${JSON.stringify(description)}`, ...Object.entries(frontmatter ?? {}).map(([key, value]) => `${key}: ${JSON.stringify(value)}`), ]; @@ -65,119 +54,77 @@ function viewOnlyReason(factoryId: string | undefined, canEdit: boolean): string return undefined; } -function dialogTitle(creating: boolean, readOnly: boolean): string { - if (creating) return 'New skill'; - return readOnly ? 'View skill' : 'Edit skill'; -} - /** - * Opens a Factory skill in the shared skill editor, or creates one. Admins save an edit for this Factory - * project, revert it to the original, or delete a skill this Factory created; everyone else views it. + * Opens a Factory skill in the shared skill editor. Admins save the edit for + * this Factory project or revert it to the original; everyone else views it. */ export function FactorySkillEditorDialog({ skill, factoryId, canEdit, onClose }: FactorySkillEditorDialogProps) { - const creating = skill === undefined; - const [name, setName] = useState(skill?.name ?? ''); - const [description, setDescription] = useState(skill?.description ?? ''); - const [instructions, setInstructions] = useState(skill?.content ?? ''); - const [confirmingDelete, setConfirmingDelete] = useState(false); + const [description, setDescription] = useState(skill.description); + const [instructions, setInstructions] = useState(skill.content); const edit = useFactorySkillEditMutation(factoryId); - const create = useFactorySkillCreateMutation(factoryId); - const pending = edit.isPending || create.isPending; - const error = create.error ?? edit.error; const readOnlyReason = viewOnlyReason(factoryId, canEdit); - const createdHere = skill?.origin === 'project'; - const changed = description !== (skill?.description ?? '') || instructions !== (skill?.content ?? ''); - const invalidName = creating ? nameProblem(name) : undefined; - const canCreate = name !== '' && !invalidName && description.trim() !== ''; - const markdown = () => composeSkillMarkdown({ name, description, frontmatter: skill?.frontmatter, instructions }); + const changed = description !== skill.description || instructions !== skill.content; - const save = () => edit.mutate({ name, content: markdown() }, { onSuccess: onClose }); - const submitCreate = () => create.mutate({ name, content: markdown() }, { onSuccess: onClose }); - const revert = () => edit.mutate({ name, content: null }, { onSuccess: onClose }); + const save = () => + edit.mutate( + { + name: skill.name, + content: composeSkillMarkdown({ name: skill.name, description, frontmatter: skill.frontmatter, instructions }), + }, + { onSuccess: onClose }, + ); + const revert = () => edit.mutate({ name: skill.name, content: null }, { onSuccess: onClose }); return ( !open && onClose()}> - {dialogTitle(creating, readOnlyReason !== undefined)} + {readOnlyReason ? 'View skill' : 'Edit skill'} {readOnlyReason ?? - (creating - ? 'The skill belongs to this Factory only. Agents can load it from their next session, and a board phase can run it.' - : 'Changes apply to this Factory only. Agents pick them up from their next session; running sessions keep the version they started with.')} + 'Changes apply to this Factory only. Agents pick them up from their next session; running sessions keep the version they started with.'}
- {skill?.edited && skill.originalChanged && ( + {skill.edited && skill.originalChanged && ( The original changed since this was edited. Revert to use the new original. )} setName(value.trim())} - nameReadOnly={!creating} + name={skill.name} + onNameChange={() => {}} + nameReadOnly description={description} onDescriptionChange={setDescription} instructions={instructions} onInstructionsChange={setInstructions} readOnly={readOnlyReason !== undefined} /> - {invalidName && ( - - {invalidName} - - )}
- {error && ( + {edit.error && ( - {error.message} + {edit.error.message} )} - {confirmingDelete ? ( - <> - - Delete {name}? Cards entering a phase that runs it won't start until the phase gets another skill. - - - - - ) : ( - <> - {readOnlyReason ? 'Close' : 'Cancel'} - {!readOnlyReason && skill?.edited && ( - - )} - {!readOnlyReason && createdHere && ( - - )} - {!readOnlyReason && creating && ( - - )} - {!readOnlyReason && !creating && ( - - )} - + {readOnlyReason ? 'Close' : 'Cancel'} + {!readOnlyReason && skill.edited && ( + + )} + {!readOnlyReason && ( + )}
diff --git a/mastracode/factory-ui/src/ui/domains/settings/components/SettingsNavigation.tsx b/mastracode/factory-ui/src/ui/domains/settings/components/SettingsNavigation.tsx index f2ab9685142..b231f5ea331 100644 --- a/mastracode/factory-ui/src/ui/domains/settings/components/SettingsNavigation.tsx +++ b/mastracode/factory-ui/src/ui/domains/settings/components/SettingsNavigation.tsx @@ -14,6 +14,7 @@ import { IconBrain } from '@mastra/playground-ui/icons/central/IconBrain'; import { IconBranch } from '@mastra/playground-ui/icons/central/IconBranch'; import { IconBug } from '@mastra/playground-ui/icons/central/IconBug'; import { IconBuildings } from '@mastra/playground-ui/icons/central/IconBuildings'; +import { IconColorPalette } from '@mastra/playground-ui/icons/central/IconColorPalette'; import { IconInboxEmpty } from '@mastra/playground-ui/icons/central/IconInboxEmpty'; import { IconMaintenance } from '@mastra/playground-ui/icons/central/IconMaintenance'; import { IconRobot } from '@mastra/playground-ui/icons/central/IconRobot'; @@ -42,8 +43,13 @@ const SETTINGS_GROUPS: SettingsNavGroup[] = [ id: 'account', label: SETTINGS_SECTION_LABELS.account, icon: IconUser, - searchText: - 'my account profile identity email authentication preferences general theme appearance color scheme completion sound session log out sign out user', + searchText: 'my account profile identity email authentication session log out sign out user', + }, + { + id: 'preferences', + label: SETTINGS_SECTION_LABELS.preferences, + icon: IconColorPalette, + searchText: 'preferences general theme appearance color scheme completion sound', }, { id: 'connections', diff --git a/mastracode/factory-ui/src/ui/domains/settings/components/SettingsPanel.parts.tsx b/mastracode/factory-ui/src/ui/domains/settings/components/SettingsPanel.parts.tsx index 82c7e903ef6..099b3a90b04 100644 --- a/mastracode/factory-ui/src/ui/domains/settings/components/SettingsPanel.parts.tsx +++ b/mastracode/factory-ui/src/ui/domains/settings/components/SettingsPanel.parts.tsx @@ -16,7 +16,7 @@ import { SettingsContainer, SettingsRow } from '@mastra/playground-ui/new/settin import { SettingsSubsection } from './SettingsSubsection'; import { SoundPicker } from './SettingsFields'; -export function PreferencesSettings() { +export function GeneralSettings() { const [doneSound, setDoneSound] = useState(() => loadDoneSound()); const changeDoneSound = (next: DoneSound) => { setDoneSound(next); @@ -25,7 +25,7 @@ export function PreferencesSettings() { playDoneSound(next); }; return ( - + diff --git a/mastracode/factory-ui/src/ui/domains/settings/components/SettingsPanel.tsx b/mastracode/factory-ui/src/ui/domains/settings/components/SettingsPanel.tsx index 7883e384907..3e87cae1103 100644 --- a/mastracode/factory-ui/src/ui/domains/settings/components/SettingsPanel.tsx +++ b/mastracode/factory-ui/src/ui/domains/settings/components/SettingsPanel.tsx @@ -18,7 +18,7 @@ import { ConnectToolsSection } from './ConnectToolsSection'; import { FactoryManagementSection } from './FactoryManagementSection'; import { IntakeSection } from './IntakeSection'; import { RepositoriesSection } from './RepositoriesSection'; -import { BehaviorSettings } from './SettingsPanel.parts'; +import { BehaviorSettings, GeneralSettings } from './SettingsPanel.parts'; import { MemorySettings } from './MemorySettings'; import { ModelsSettings } from './models/ModelsSettings'; @@ -56,6 +56,7 @@ export function SettingsPanel() { return ( <> {section === 'account' && } + {section === 'preferences' && } {section === 'factory' && } {section === 'connections' && } {section === 'repositories' && } diff --git a/mastracode/factory-ui/src/ui/domains/settings/components/__tests__/AccountSettingsSection.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/settings/components/__tests__/AccountSettingsSection.msw.test.tsx index 766fd3c9614..c3532ad854e 100644 --- a/mastracode/factory-ui/src/ui/domains/settings/components/__tests__/AccountSettingsSection.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/settings/components/__tests__/AccountSettingsSection.msw.test.tsx @@ -1,4 +1,4 @@ -import { screen, within } from '@testing-library/react'; +import { screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { http, HttpResponse } from 'msw'; import { describe, expect, it } from 'vitest'; @@ -40,20 +40,6 @@ describe('AccountSettingsSection', () => { expect(screen.getByRole('button', { name: 'Copy organization ID' })).toBeInTheDocument(); }); - it('switches the theme from My account and remembers the choice', async () => { - stubAuthenticatedAccount(); - const user = userEvent.setup(); - - renderWithProviders(); - await screen.findByText('Dev'); - const theme = screen.getByRole('radiogroup', { name: 'Theme' }); - expect(within(theme).getByRole('radio', { name: 'System' })).toBeChecked(); - await user.click(within(theme).getByRole('radio', { name: 'Dark' })); - - expect(window.localStorage.getItem('mastracode.theme')).toBe('dark'); - expect(within(theme).getByRole('radio', { name: 'Dark' })).toBeChecked(); - }); - it('logs out by clearing MastraCode storage', async () => { stubAuthenticatedAccount(); localStorage.setItem('mastracode.theme', 'dark'); @@ -77,19 +63,4 @@ describe('AccountSettingsSection', () => { expect(screen.queryByRole('button', { name: 'Log out of MastraCode' })).not.toBeInTheDocument(); }); }); - - describe('when account details fail to load', () => { - it('still lets the user change their theme and completion sound', async () => { - server.use(http.get(`${TEST_BASE_URL}/auth/me`, () => new HttpResponse(null, { status: 500 }))); - const user = userEvent.setup(); - - renderWithProviders(); - await screen.findByText('Could not load your account details. Reload the page to try again.'); - await user.click(within(screen.getByRole('radiogroup', { name: 'Theme' })).getByRole('radio', { name: 'Light' })); - - expect(window.localStorage.getItem('mastracode.theme')).toBe('light'); - expect(screen.getByText('Completion sound')).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: 'Log out of MastraCode' })).not.toBeInTheDocument(); - }); - }); }); diff --git a/mastracode/factory-ui/src/ui/domains/settings/components/__tests__/GeneralSettings.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/settings/components/__tests__/GeneralSettings.msw.test.tsx new file mode 100644 index 00000000000..a370179e78b --- /dev/null +++ b/mastracode/factory-ui/src/ui/domains/settings/components/__tests__/GeneralSettings.msw.test.tsx @@ -0,0 +1,20 @@ +import { screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it } from 'vitest'; + +import { renderWithProviders } from '../../../../../../e2e/ui/render'; +import { GeneralSettings } from '../SettingsPanel.parts'; + +describe('GeneralSettings', () => { + it('switches the theme and remembers the choice', async () => { + const user = userEvent.setup(); + renderWithProviders(); + + const theme = screen.getByRole('radiogroup', { name: 'Theme' }); + expect(within(theme).getByRole('radio', { name: 'System' })).toBeChecked(); + await user.click(within(theme).getByRole('radio', { name: 'Dark' })); + + expect(window.localStorage.getItem('mastracode.theme')).toBe('dark'); + expect(within(theme).getByRole('radio', { name: 'Dark' })).toBeChecked(); + }); +}); diff --git a/mastracode/factory-ui/src/ui/domains/settings/components/__tests__/SettingsNavigation.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/settings/components/__tests__/SettingsNavigation.msw.test.tsx index 235b02ca98f..b489eab84fc 100644 --- a/mastracode/factory-ui/src/ui/domains/settings/components/__tests__/SettingsNavigation.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/settings/components/__tests__/SettingsNavigation.msw.test.tsx @@ -11,7 +11,7 @@ const STORAGE_KEY = 'settings-navigation-test'; function renderNavigation() { return renderWithProviders( - + } /> @@ -40,7 +40,7 @@ describe('SettingsNavigation', () => { within(screen.getByRole('region', { name: group })) .getAllByRole('link') .map(link => link.textContent); - expect(linksIn('Account')).toEqual(['My account', 'Connections']); + expect(linksIn('Account')).toEqual(['My account', 'Preferences', 'Connections']); expect(linksIn('Agent')).toEqual(['Models', 'Memory', 'Tools', 'Behavior']); expect(linksIn('Factory')).toEqual(['Repositories', 'Work Intake', 'Manage Factory', 'Debug']); expect(screen.getByRole('link', { name: 'Models' })).toHaveAttribute('href', '/factories/fp-1/settings/models'); @@ -58,15 +58,6 @@ describe('SettingsNavigation', () => { expect(screen.queryByRole('region', { name: 'Account' })).not.toBeInTheDocument(); }); - it.each(['preferences', 'theme', 'completion sound'])('finds My account by "%s"', async query => { - const user = userEvent.setup(); - renderNavigation(); - - await user.type(screen.getByRole('searchbox', { name: 'Search settings' }), query); - - expect(screen.getByRole('link', { name: 'My account' })).toBeInTheDocument(); - }); - it('finds Environment under Manage Factory and navigates to its canonical destination', async () => { const user = userEvent.setup(); renderNavigation(); diff --git a/mastracode/factory-ui/src/ui/domains/settings/hooks/useSettingsSection.ts b/mastracode/factory-ui/src/ui/domains/settings/hooks/useSettingsSection.ts index 209f36942bc..14676882396 100644 --- a/mastracode/factory-ui/src/ui/domains/settings/hooks/useSettingsSection.ts +++ b/mastracode/factory-ui/src/ui/domains/settings/hooks/useSettingsSection.ts @@ -17,5 +17,5 @@ export function useSettingsSection(): SettingsSection { matchPath('/factories/:factoryId/settings/:section/*', pathname)?.params.section ?? matchPath('/factories/:factoryId/settings/:section', pathname)?.params.section ?? matchPath('/settings/:section', pathname)?.params.section; - return isSettingsSection(section) ? section : 'account'; + return isSettingsSection(section) ? section : 'preferences'; } diff --git a/mastracode/factory-ui/src/ui/domains/settings/settingsSections.ts b/mastracode/factory-ui/src/ui/domains/settings/settingsSections.ts index f4b59ea148d..f95b7d4d2c9 100644 --- a/mastracode/factory-ui/src/ui/domains/settings/settingsSections.ts +++ b/mastracode/factory-ui/src/ui/domains/settings/settingsSections.ts @@ -4,6 +4,7 @@ import type { ModelDefaults } from './components/models/routing/model-routes'; export type SettingsSection = | 'account' + | 'preferences' | 'factory' | 'connections' | 'repositories' @@ -16,6 +17,7 @@ export type SettingsSection = export const SETTINGS_SECTION_LABELS: Record = { account: 'My account', + preferences: 'Preferences', factory: 'Manage Factory', connections: 'Connections', repositories: 'Repositories', @@ -46,7 +48,6 @@ type SettingsAnchor = ModelDefaultsAnchor | typeof VOICE_INPUT_ANCHOR; type SettingsTarget = { section: SettingsSection; anchor?: ModelDefaultsAnchor }; const RETIRED_SETTINGS_SECTIONS = new Map([ - ['preferences', { section: 'account' }], ['personal-models', { section: 'models', anchor: MODEL_DEFAULTS_ANCHORS.personal }], ['factory-memory', { section: 'memory' }], ['environment', { section: 'repositories' }], diff --git a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionCardContexts.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionCardContexts.msw.test.tsx index 31aab1330d2..a69504e7cf1 100644 --- a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionCardContexts.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionCardContexts.msw.test.tsx @@ -169,7 +169,6 @@ describe('Sessions sidebar lists one row per card', () => { }); it('renders a card row the same way as a plain user session', async () => { - localStorage.setItem('mastracode.sessionListView', JSON.stringify({ groupBy: 'none' })); renderSection(); const cardRow = await screen.findByRole('link', { name: 'Write docs' }); @@ -228,14 +227,15 @@ describe('Sessions sidebar view options', () => { expect(await screen.findByRole('link', { name: 'Build fix login' })).toHaveAttribute('aria-current', 'page'); }); - it('shows when a session last moved under its name until compact view is on', async () => { + it('shows when a session last moved under its name once compact view is off', async () => { const user = userEvent.setup(); renderSection(); const row = await screen.findByRole('link', { name: 'Build fix login' }); - expect(within(row).getByText('Sep 4')).toHaveAttribute('dateTime', '2026-09-04T10:00:00.000Z'); + expect(row.querySelector('time')).toBeNull(); await toggleSessionView(user, 'Compact view'); - expect(screen.getByRole('link', { name: 'Build fix login' }).querySelector('time')).toBeNull(); + const time = within(screen.getByRole('link', { name: 'Build fix login' })).getByText('Sep 4'); + expect(time).toHaveAttribute('dateTime', '2026-09-04T10:00:00.000Z'); }); }); diff --git a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionGroups.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionGroups.msw.test.tsx index 925dd5e1a5c..27bbf19f817 100644 --- a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionGroups.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionGroups.msw.test.tsx @@ -14,6 +14,7 @@ import type { FactoryUserSession } from '../../services/user-sessions'; import { SessionsSection } from '../SessionsSection'; import { closeSessionProperties, + groupSessionsByBoard, openNestedSessionProperty, openSessionProperties, openSessionProperty, @@ -85,6 +86,7 @@ const releaseItems = [releaseOld, releaseNew].map(release => ({ })); beforeEach(() => { + groupSessionsByBoard(); stubSessionsFactory(factoryId, [projectRepositoryId]); server.use( http.get(`${TEST_BASE_URL}/web/factory/projects/${factoryId}/boards`, () => @@ -191,12 +193,12 @@ describe('Sessions sidebar groups', () => { await waitFor(() => expect(screen.queryByRole('region', { name: 'Release Preview sessions' })).toBeNull()); expect(groupRegions()).toEqual(['Work sessions', 'User sessions']); - expect(sessionPropertiesTrigger(1)).toBeInTheDocument(); + expect(sessionPropertiesTrigger(2)).toBeInTheDocument(); await openSessionProperties(user); await user.click(screen.getByRole('menuitem', { name: 'Reset to default' })); - await waitFor(() => expect(groupRegions()).toEqual(['Work sessions', 'Release Preview sessions', 'User sessions'])); + await waitFor(() => expect(groupRegions()).toEqual(['All sessions'])); expect(sessionPropertiesTrigger()).toBeInTheDocument(); }); @@ -265,7 +267,7 @@ describe('Sessions sidebar groups', () => { await user.keyboard('{Alt>}{ArrowUp}{/Alt}'); await closeSessionProperties(user); - expect(sessionPropertiesTrigger()).toBeInTheDocument(); + expect(sessionPropertiesTrigger(1)).toBeInTheDocument(); }); it("never lists a custom board's terminal-phase session as Idle while the board catalog loads", async () => { diff --git a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionOrder.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionOrder.msw.test.tsx index 5ef3e8a9376..7982c83a31d 100644 --- a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionOrder.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionOrder.msw.test.tsx @@ -3,7 +3,7 @@ import { screen, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { http, HttpResponse } from 'msw'; import { MemoryRouter, Route, Routes } from 'react-router'; -import { describe, expect, it } from 'vitest'; +import { beforeEach, describe, expect, it } from 'vitest'; import { server } from '../../../../../../e2e/ui/msw-server'; import { TEST_BASE_URL, renderWithProviders, waitForMutationsIdle } from '../../../../../../e2e/ui/render'; @@ -11,7 +11,7 @@ import { ChatSessionContext } from '../../../chat/context/ChatSessionContext'; import { stubSessionsFactory, testChatSession } from './fixtures/sessionsSection'; import type { FactoryUserSession } from '../../services/user-sessions'; import { SessionsSection } from '../SessionsSection'; -import { pickSessionProperty } from './fixtures/sessionProperties'; +import { groupSessionsByBoard, pickSessionProperty } from './fixtures/sessionProperties'; const factoryProjectId = 'fp-1'; const projectRepositoryId = 'ghp-1'; @@ -115,6 +115,8 @@ async function reviewRowLabels(client: QueryClient): Promise<(string | null)[]> } describe('Sessions sidebar order', () => { + beforeEach(groupSessionsByBoard); + it('sinks a merged session below the open ones and keeps the rest newest-first', async () => { const oldestOpen = reviewSession(101, '2026-07-23T09:00:00.000Z'); const newestOpen = reviewSession(102, '2026-07-23T11:00:00.000Z'); @@ -248,6 +250,9 @@ describe('Sessions sidebar order', () => { const remounted = renderSection(); expect(await reviewRowLabels(remounted.client)).toEqual(byLastUpdate); - expect(JSON.parse(localStorage.getItem('mastracode.sessionListView') ?? '{}')).toEqual({ sort: 'updated' }); + expect(JSON.parse(localStorage.getItem('mastracode.sessionListView') ?? '{}')).toEqual({ + groupBy: 'board', + sort: 'updated', + }); }); }); diff --git a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionOwner.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionOwner.msw.test.tsx index bee7b82024e..4a594feafe9 100644 --- a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionOwner.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionOwner.msw.test.tsx @@ -11,7 +11,7 @@ import { ChatSessionContext } from '../../../chat/context/ChatSessionContext'; import { stubSessionsFactory, testChatSession } from './fixtures/sessionsSection'; import type { FactoryUserSession } from '../../services/user-sessions'; import { SessionsSection } from '../SessionsSection'; -import { pickSessionProperty, sessionPropertiesTrigger } from './fixtures/sessionProperties'; +import { groupSessionsByBoard, pickSessionProperty, sessionPropertiesTrigger } from './fixtures/sessionProperties'; const projectRepositoryId = 'ghp-1'; const viewerUserId = 'user-me'; @@ -90,6 +90,7 @@ describe('Sessions sidebar owner filter', () => { ]; it("narrows every group to the viewer's own sessions", async () => { + groupSessionsByBoard(); stubSessions(mixedSessions()); const user = userEvent.setup(); @@ -106,7 +107,7 @@ describe('Sessions sidebar owner filter', () => { expect(within(userGroup).getByRole('link', { name: 'task-20002' })).toBeInTheDocument(); expect(screen.queryByRole('link', { name: 'factory/issue-20003' })).not.toBeInTheDocument(); expect(screen.queryByRole('link', { name: 'task-20005' })).not.toBeInTheDocument(); - expect(sessionPropertiesTrigger(1)).toBeInTheDocument(); + expect(sessionPropertiesTrigger(2)).toBeInTheDocument(); }); it('keeps the owner filter after a reload', async () => { diff --git a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionProperties.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionProperties.msw.test.tsx index b073d52b047..b54b91d5c72 100644 --- a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionProperties.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionProperties.msw.test.tsx @@ -135,19 +135,19 @@ const sessionRowLabels = () => .map(row => row.getAttribute('aria-label')); describe('Sessions properties', () => { - it("opens on every owner's sessions grouped by board, with nothing changed", async () => { + it("opens on every owner's sessions in one ungrouped list, with nothing changed", async () => { const user = userEvent.setup(); await renderSection(); - const userGroup = await screen.findByRole('region', { name: 'User sessions' }); - expect(await within(userGroup).findByRole('link', { name: 'Fix authentication' })).toBeInTheDocument(); - expect(within(userGroup).getByRole('link', { name: 'Improve compiler output' })).toBeInTheDocument(); + const all = await screen.findByRole('region', { name: 'All sessions' }); + expect(await within(all).findByRole('link', { name: 'Fix authentication' })).toBeInTheDocument(); + expect(within(all).getByRole('link', { name: 'Improve compiler output' })).toBeInTheDocument(); expect(screen.getAllByRole('region', { name: /sessions$/ })).toHaveLength(1); expect(sessionPropertiesTrigger()).toBeInTheDocument(); await openSessionProperties(user); expect(screen.getByRole('menuitem', { name: /^Owner\s*All owners$/ })).toBeInTheDocument(); - expect(screen.getByRole('menuitem', { name: /^Group\s*Board$/ })).toBeInTheDocument(); + expect(screen.getByRole('menuitem', { name: /^Group\s*None$/ })).toBeInTheDocument(); expect(screen.getByRole('menuitem', { name: 'Reset to default' })).toHaveAttribute('aria-disabled', 'true'); await closeSessionProperties(user); }); diff --git a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionShowMore.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionShowMore.msw.test.tsx index 7311dd5e657..a9777cda83d 100644 --- a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionShowMore.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/SessionsSectionShowMore.msw.test.tsx @@ -14,7 +14,7 @@ import type { FactoryUserSession } from '../../services/user-sessions'; import { presentSessionRow } from '../../services/sessionRows'; import { SessionGroupList } from '../SessionGroupList'; import { SessionsSection } from '../SessionsSection'; -import { pickSessionProperty } from './fixtures/sessionProperties'; +import { groupSessionsByBoard, pickSessionProperty } from './fixtures/sessionProperties'; const projectRepositoryId = 'ghp-1'; @@ -82,6 +82,7 @@ function appReads(): URL[] { describe('Sessions sidebar show more', () => { beforeEach(() => { localStorage.removeItem('mastracode.pinnedSessions'); + groupSessionsByBoard(); }); it('caps a group at 5 sessions and reveals a small remainder on demand', async () => { diff --git a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/WorkspaceSidebarStatuses.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/WorkspaceSidebarStatuses.msw.test.tsx index a410f892ba2..77477b546ef 100644 --- a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/WorkspaceSidebarStatuses.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/WorkspaceSidebarStatuses.msw.test.tsx @@ -1,4 +1,5 @@ import { screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import { http, HttpResponse } from 'msw'; import { MemoryRouter, Route, Routes } from 'react-router'; import { describe, expect, it } from 'vitest'; @@ -11,6 +12,7 @@ import type { PullRequestSubscription } from '../../../factory/services/githubSu import type { WorkItemSessionRef } from '../../../factory/services/workItems'; import type { FactoryUserSession } from '../../services/user-sessions'; import { SessionsSection } from '../SessionsSection'; +import { closeSessionProperties, openSessionProperties } from './fixtures/sessionProperties'; import { LIVE_SESSION, testChatSession } from './fixtures/sessionsSection'; const factoryProjectId = 'factory-project-1'; @@ -232,10 +234,6 @@ function renderSection() { ); } -function showCompactRows() { - localStorage.setItem('mastracode.sessionListView', JSON.stringify({ compact: true })); -} - const terminalStatusCases: Array<{ status: PullRequestSubscription['status']; knownMerged: boolean; @@ -300,8 +298,7 @@ describe('Workspace sidebar statuses', () => { expect(row?.querySelector('[role="status"]')).toBeNull(); }); - it("shows the running status belt instead of a compact row's merged icon while the agent is active", async () => { - showCompactRows(); + it('shows the running status belt instead of a merged icon while the agent is active', async () => { stubWorkspaceStatuses({ items: baseItems(true), activeSessionIds: [workSession.sessionId], @@ -320,7 +317,6 @@ describe('Workspace sidebar statuses', () => { it.each(terminalStatusCases)( 'maps a matching $status subscription on a card known merged=$knownMerged to merged=$expectedMerged', async ({ status, knownMerged, expectedMerged }) => { - showCompactRows(); stubWorkspaceStatuses({ items: baseItems(knownMerged), activeSessionIds: [], @@ -392,7 +388,6 @@ describe('Workspace sidebar statuses', () => { updatedAt: '2026-07-21T00:00:00.000Z', }); const subscriptions = [pullRequestSubscription(201, 'merged'), pullRequestSubscription(202, newestStatus)]; - showCompactRows(); stubWorkspaceStatuses({ items: [workItem, olderReview, newerReview], activeSessionIds: [], @@ -411,7 +406,8 @@ describe('Workspace sidebar statuses', () => { }, ); - it("names an issue card's linked pull request on its second line", async () => { + it("names an issue card's linked pull request on its second line once compact view is off", async () => { + const user = userEvent.setup(); stubWorkspaceStatuses({ items: baseItems(false), activeSessionIds: [], @@ -423,6 +419,10 @@ describe('Workspace sidebar statuses', () => { const { client } = renderSection(); await waitForMutationsIdle(client); + await openSessionProperties(user); + await user.click(await screen.findByRole('menuitemcheckbox', { name: 'Compact view' })); + await closeSessionProperties(user); + const row = screen.getByRole('link', { name: 'Implement loader', description: /^Open pull request #202 / }); expect(within(row).getByText('PR mastra-ai/mastra#202')).toBeInTheDocument(); }); diff --git a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/fixtures/sessionProperties.ts b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/fixtures/sessionProperties.ts index 5ced4266ef5..fc95a552cab 100644 --- a/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/fixtures/sessionProperties.ts +++ b/mastracode/factory-ui/src/ui/domains/workspaces/components/__tests__/fixtures/sessionProperties.ts @@ -2,6 +2,11 @@ import { act, screen, waitFor } from '@testing-library/react'; import type { UserEvent } from '@testing-library/user-event'; import { expect } from 'vitest'; +/** The sidebar opens ungrouped; suites that exercise board groups start from a stored Board grouping. */ +export function groupSessionsByBoard() { + localStorage.setItem('mastracode.sessionListView', JSON.stringify({ groupBy: 'board' })); +} + export function sessionPropertiesTrigger(changedCount = 0): HTMLElement { return screen.getByRole('button', { name: changedCount === 0 ? 'Sessions properties' : `Sessions properties, ${changedCount} changed`, diff --git a/mastracode/factory-ui/src/ui/domains/workspaces/hooks/useSessionListView.msw.test.tsx b/mastracode/factory-ui/src/ui/domains/workspaces/hooks/useSessionListView.msw.test.tsx index 1d8212e8a6d..36770e30624 100644 --- a/mastracode/factory-ui/src/ui/domains/workspaces/hooks/useSessionListView.msw.test.tsx +++ b/mastracode/factory-ui/src/ui/domains/workspaces/hooks/useSessionListView.msw.test.tsx @@ -32,7 +32,7 @@ describe('useSessionListView', () => { it('opens on the default grouping when the stored grouping is unknown', () => { localStorage.setItem(STORAGE_KEY, JSON.stringify({ groupBy: 'project' })); - expect(renderHook(() => useSessionListView()).result.current.view.groupBy).toBe(DEFAULT_SESSION_LIST_VIEW.groupBy); + expect(renderHook(() => useSessionListView()).result.current.view.groupBy).toBe('none'); }); it('keeps hidden groups that are string lists and drops the malformed ones', () => { @@ -62,7 +62,7 @@ describe('useSessionListView', () => { it('does not count a stored setting that equals the default as a change', () => { localStorage.setItem( STORAGE_KEY, - JSON.stringify({ sort: 'activity', groupBy: 'board', compact: false, hiddenGroups: { status: [] } }), + JSON.stringify({ sort: 'activity', groupBy: 'none', hiddenGroups: { status: [] } }), ); expect(renderHook(() => useSessionListView()).result.current.changedSettingCount).toBe(0); @@ -85,14 +85,15 @@ describe('useSessionListView', () => { { key: 'user', label: 'User', icon: 'user' }, ]; const { result } = renderHook(() => useSessionListView()); + act(() => result.current.updateView({ groupBy: 'board' })); act(() => result.current.changeGroupOrder(['user', 'board:work'], defaultHeadings)); - expect(storedView()).toEqual({ groupOrder: { board: ['user', 'board:work'] } }); + expect(storedView()).toEqual({ groupBy: 'board', groupOrder: { board: ['user', 'board:work'] } }); expect(result.current.groupOrderKeys).toEqual(['user', 'board:work']); - expect(result.current.changedSettingCount).toBe(1); + expect(result.current.changedSettingCount).toBe(2); act(() => result.current.changeGroupOrder(['board:work', 'user'], defaultHeadings)); - expect(storedView()).toEqual({}); + expect(storedView()).toEqual({ groupBy: 'board' }); expect(result.current.groupOrderKeys).toEqual([]); }); diff --git a/mastracode/factory-ui/src/ui/domains/workspaces/hooks/useSessionListView.ts b/mastracode/factory-ui/src/ui/domains/workspaces/hooks/useSessionListView.ts index f29b0857e9b..47fc53f76d1 100644 --- a/mastracode/factory-ui/src/ui/domains/workspaces/hooks/useSessionListView.ts +++ b/mastracode/factory-ui/src/ui/domains/workspaces/hooks/useSessionListView.ts @@ -25,7 +25,7 @@ export const DEFAULT_SESSION_LIST_VIEW: SessionListView = { groupBy: DEFAULT_SESSION_GROUP_BY, hiddenGroups: {}, groupOrder: {}, - compact: false, + compact: true, revealChildSessions: false, }; diff --git a/mastracode/factory-ui/src/ui/domains/workspaces/services/sessionGroups.ts b/mastracode/factory-ui/src/ui/domains/workspaces/services/sessionGroups.ts index 1af93431b8f..4c9d25e52ab 100644 --- a/mastracode/factory-ui/src/ui/domains/workspaces/services/sessionGroups.ts +++ b/mastracode/factory-ui/src/ui/domains/workspaces/services/sessionGroups.ts @@ -12,7 +12,7 @@ import type { SessionListRow, SessionOwner } from './sessionRows'; export type SessionGroupBy = (typeof SESSION_ROW_GROUP_BYS)[number]; -export const DEFAULT_SESSION_GROUP_BY: SessionGroupBy = 'board'; +export const DEFAULT_SESSION_GROUP_BY: SessionGroupBy = 'none'; export const SESSION_GROUP_BY_LABELS: Record = { board: 'Board', diff --git a/mastracode/factory-ui/src/ui/pages/SettingsPage.tsx b/mastracode/factory-ui/src/ui/pages/SettingsPage.tsx index 2ff464c1c2b..f932ae19178 100644 --- a/mastracode/factory-ui/src/ui/pages/SettingsPage.tsx +++ b/mastracode/factory-ui/src/ui/pages/SettingsPage.tsx @@ -36,7 +36,7 @@ export function SettingsPage() { } if (!isSettingsSection(section)) { - return ; + return ; } return ( , createQueryClient()) }; } -describe('a card with sessions', () => { - it("opens the thread of the session its current phase runs in, as a chat's link to the card does", async () => { - stubDraftRoute(); - server.use( - http.get(`${TEST_BASE_URL}/web/factory/projects/${FACTORY_ID}/work-items`, () => - HttpResponse.json({ - workItems: [ - { - ...linearCard, - stages: ['execute'], - sessions: { - triage: { sessionId: 'session-triage', threadId: 'thread-triage' }, - work: { sessionId: 'session-work', threadId: 'thread-work' }, - }, - }, - ], - }), - ), - ); - const { router } = renderAt(`/factories/${FACTORY_ID}/cards/${CARD_ID}`); - - await waitFor(() => - expect(router.state.location.pathname).toBe( - `/factories/${FACTORY_ID}/workspaces/session-work/threads/thread-work`, - ), - ); - }); -}); - describe('a card without a session', () => { it('opens on a draft titled after the card that creates nothing until the first prompt', async () => { const route = stubDraftRoute(); diff --git a/mastracode/factory-ui/src/ui/router.tsx b/mastracode/factory-ui/src/ui/router.tsx index 9cb7c4c8533..c7be5133160 100644 --- a/mastracode/factory-ui/src/ui/router.tsx +++ b/mastracode/factory-ui/src/ui/router.tsx @@ -323,7 +323,7 @@ export function createAppRoutes(services?: RouteLoaderServices): RouteObject[] { { path: 'settings', children: [ - { index: true, element: }, + { index: true, element: }, { path: 'connections/slack', ...lazyRoute(SlackConnectionPage) }, { path: 'board', element: }, { path: 'skills', element: }, diff --git a/mastracode/factory/CHANGELOG.md b/mastracode/factory/CHANGELOG.md index 9211ee00385..0b3a8f2f790 100644 --- a/mastracode/factory/CHANGELOG.md +++ b/mastracode/factory/CHANGELOG.md @@ -1,115 +1,5 @@ # @mastra/factory -## 0.29.0-alpha.7 - -### Patch Changes - -- The **Activity** sort in the Factory sidebar now orders sessions that share a status by their last update instead of their creation date, the same as **Last updated** does. An older session that was updated since no longer sinks below a newer one that was left alone. ([#30656](https://github.com/mastra-ai/mastra/pull/30656)) - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/code-sdk@1.19.1-alpha.7 - -## 0.29.0-alpha.6 - -### Minor Changes - -- Added personal custom providers. A custom OpenAI-compatible endpoint is now saved either for yourself or for your organization, the same way provider API keys are. ([#29879](https://github.com/mastra-ai/mastra/pull/29879)) - - - **Personal endpoints** are visible only to you and are used by your personal sessions. - - **Organization endpoints** are used by work that runs on the organization's credentials. Adding, editing or removing one now requires an organization admin. - - Custom endpoints are added from the **Add provider** dialog and listed with the other providers. The separate "Custom providers" section is gone. - - Editing an endpoint without retyping its API key keeps the saved key, as long as the URL stays on the same host. Moving it to another host asks for the key again. - - Adding an endpoint under a name that is already in use is refused instead of replacing the existing one. So are names reserved for a built-in provider, its sign-in, or the Mastra Gateway (for example "OpenAI", "OpenAI Codex" or "Mastra Gateway"). - - A Factory hosted on the Mastra platform only calls custom endpoints at a public HTTPS address. Saving one on plain HTTP, `localhost`, a private network or the cloud metadata address is refused with a message explaining why. Local and self-hosted Factories can still use endpoints on their own machine or network, such as Ollama or vLLM. - - **Before you upgrade** - - - Organization endpoints no longer apply to personal sessions. Add the endpoint again as a personal one to keep using it there. - - On a hosted Factory, endpoints saved earlier on a local or plain-HTTP address are marked "URL not allowed" and their models are no longer offered. Edit them to a public HTTPS address. - - Review your organization's endpoints. One named like a built-in provider (for example "OpenAI") still takes over that provider's models; remove it or rename it. - - The custom provider routes take a `scope` (`user` by default, or `org`). Saving with `previousId` edits that provider; saving without it adds one: - - ```http - POST /web/config/custom-providers - { "name": "My gateway", "url": "https://llm.example.com/v1", "models": ["my-model"], "scope": "org" } - - DELETE /web/config/custom-providers/my-gateway?scope=org - ``` - -- Work Intake: what you select is what comes in. ([#30625](https://github.com/mastra-ai/mastra/pull/30625)) - - - **One list per service, no sync switches.** Settings → Work Intake lists each connected service with its selected sources and an Add account button. A service with nothing selected brings in nothing. Dependabot alerts keep their own switch. - - **GitHub issues follow the list.** New GitHub issues become cards only for repositories in the GitHub list. Pull requests still come from every linked repository. On upgrade, every repository already linked to a Factory is added to the list once, so nothing stops arriving. Linking a repository adds it to the list unless the request sends `selectIntake: false`, and adding a repository to the list brings in its open issues. - To link a repository without bringing in its issues: - - ```http - POST /web/factory/projects/:projectId/source-control-connections/:connectionId/repositories - { "repository": { "externalId": "99", "slug": "acme/app" }, "selectIntake": false } - ``` - - - **Vanta follows its selection.** Vulnerabilities sync only while the Vanta source is selected. Organizations whose Vanta sync was on with nothing selected get the source selected once on upgrade. - - **Routing has its own page.** The intake order and the Not routed list moved from Settings to Routing in board settings. - -- Fixed Factory server memory growing with every session it ever opened. Factory now unloads a session from server memory when it stops the session's sandbox (a card leaving a phase's context or finishing), and after 30 minutes without activity. Sessions that are running, waiting on an approval or answer, open in a browser tab, or running a background process in their sandbox stay loaded. Unloading keeps the thread, its messages, the session row and the sandbox, and the session's next message, run, wake or opened tab loads it again. Without `auth`, a deferred wake for an unloaded session waits until something else loads it, as it does after a restart. ([#30612](https://github.com/mastra-ai/mastra/pull/30612)) - - Change the timeout with `idleSessionUnload`, or pass `false` to keep every session loaded: - - ```ts - const factory = new MastraFactory({ - storage, - idleSessionUnload: { idleMs: 60 * 60_000, sweepIntervalMs: 5 * 60_000 }, - }); - ``` - -- Asking a Factory session to work on a card now goes through the board, the way the board's own buttons do. Before, asking a Slack or web session to "review" a pull request that already had a card often ended in a side session posting its review in the chat, while the card's own review waited for approval. ([#30628](https://github.com/mastra-ai/mastra/pull/30628)) - - - `factory_transition_work_item` takes `rerun: true` to run the stage a card is already in again, as the board's **Start** button does. The run counts as approved by the person asking, and a busy card is refused as on the board. A rerun needs a person in the turn. Without `rerun`, a request for the card's own stage changes nothing and says whether its run is waiting for approval. The result now includes the card's `url`. - - Asking for a side session still starts one. The tools now steer a plain "review this pull request" to the pull request's card, and keep side sessions for what people ask to run in one and for work no stage does, such as pushing fixes to a pull request. - - Every tool that takes a work item also accepts the issue or pull request it tracks: its link, `owner/repo#12`, `group/project!7`, or a tracker key such as `ENG-42`. With several repositories linked, the link finds the right card where a bare `#12` might not. `factory_list_work_items` takes the same references as its query. - - `factory_inspect_work_item` lists the card's stage, whether it can run again, and the stages its board lets it move to next. - - `factory_start_session` only starts side sessions. Its `workItem` and `role` inputs are removed: they started a card's role without the board's rules, such as which stage the card is in and whether it is busy. - -### Patch Changes - -- Added `GET /web/factory/projects/:id/work-items/:workItemId/session-repository`. It returns the repository a session on the card starts in, resolved with the same rules as the card's runs, or the reason the card has none. ([#30609](https://github.com/mastra-ai/mastra/pull/30609)) - -- Fixed reopened pull request review sessions loading the pull request's AGENTS.md and CLAUDE.md as trusted instructions. After a review card finished and the server restarted or unloaded the session, a new message in that session read instruction files from the pull request branch. Sessions that ever ran pull request or review work now keep reading instructions from the base branch, or read none when the trusted branch can't be determined. ([#30612](https://github.com/mastra-ai/mastra/pull/30612)) - -- **Settings › Tools** can now list each Mastra Connect connection's tools. The new `GET /web/integrations/platform/connect-tools/tools` route resolves the tools a session started by the signed-in user would get: Factory's default Connect tools, or what the `tools` option returns. It marks tools that ask for approval and lists the default tools Factory leaves out because they delete or archive. When the tools can't be resolved, it answers 502 `tools_unavailable` with the reason. ([#30610](https://github.com/mastra-ai/mastra/pull/30610)) - -- Fixed **Settings › Tools** saying Mastra Connect tools are off when a Factory sets the `tools` option, even when that option uses Connect tools (#30579). The page now lists the Platform project's connections whenever the Factory has Platform credentials and `MASTRA_PROJECT_ID`, and says that session tools come from code. When either one is missing, the page names it instead of listing every possible cause. ([#30607](https://github.com/mastra-ai/mastra/pull/30607)) - -- Reduced the work the Factory server does to keep the session sidebar and board up to date, and fixed session latency timestamps on LibSQL. ([#30648](https://github.com/mastra-ai/mastra/pull/30648)) - - - Projects without a linked repository no longer rebuild their session list on every sidebar poll. - - Session activity now sorts only the cards that are running, waiting or held by a session, instead of every card on the board. - - A session's first materialize, first message and first command times are now recorded once when several Factory processes share one LibSQL database, so a later write no longer replaces the first recorded time. - -- Fixed slow reading of the pull request number from GitHub card keys that contain very long runs of digits. The number returned is unchanged. ([#30577](https://github.com/mastra-ai/mastra/pull/30577)) - -- New, renamed and hidden sessions now show up in teammates' sidebars right away, instead of after up to a minute, and the sidebar no longer polls while a session starts. The `session-rows` and `session-activity` answers no longer include `settling`: every change to either answer now sends a frame on the project's feed. ([#30617](https://github.com/mastra-ai/mastra/pull/30617)) - -- Fixed deleting an intake rule being slow on remote databases and breaking other open rule edits. A delete now removes only the deleted rule instead of rewriting every rule after it, so the remaining rules keep their order and revision and edits opened before the delete still save. ([#30613](https://github.com/mastra-ai/mastra/pull/30613)) - -- Approving a held Factory run with `factory_resolve_proposal`, or retrying a failed one with `factory_retry_decision`, now makes the session follow the run's card, as moving the card already did. Before, a Slack session that approved a card's review could promise to post the result and then never hear how the review ended. Both results now include the card's `url`. ([#30637](https://github.com/mastra-ai/mastra/pull/30637)) - -- Fixed board cards showing a different session status than the sidebar. A card with a suggested run and a running session now shows it waits on you on the board too, and a card with one working and one starting session shows it working. ([#30624](https://github.com/mastra-ai/mastra/pull/30624)) - -- Fixed Factory starting a card's session in a repository the card doesn't come from. When a card's repository wasn't linked to the Factory, the draft started the session in the first linked repository and wrote that repository onto the card. The draft now asks the server which repository the card's session uses, and when there is none it shows why, for example "Repository acme/docs is not linked to this Factory.", starts nothing, and links to repository settings. When the lookup itself fails, the draft offers Retry. ([#30609](https://github.com/mastra-ai/mastra/pull/30609)) - - A card from GitHub in a Factory whose repositories are all on GitLab, or the reverse, is now refused the same way instead of starting in that Factory's repository, even when a repository there has the same name. - -- Improved sidebar performance in projects with many sessions. The Factory now builds the session list once and reuses it for everyone until a session, card or follow changes, so each sidebar request uses about a third of the server CPU it did. ([#30616](https://github.com/mastra-ai/mastra/pull/30616)) - -- Fixed the session status in Factory's sidebar and board. A person's own session now shows "Waiting on you" while its agent waits for their answer, instead of "Working". A session now shows "Working" while it runs on a thread opened after its first one, such as a new thread or a Slack conversation. A session shows "Initializing" only while a run waits on its first setup, so a session whose setup never finished, or that never ran, no longer stays stuck on "Initializing". ([#30627](https://github.com/mastra-ai/mastra/pull/30627)) - -- Updated dependencies [[`944bb3a`](https://github.com/mastra-ai/mastra/commit/944bb3ab0fdcd23debbc4090d50c7abdcfacc874), [`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`b1ba914`](https://github.com/mastra-ai/mastra/commit/b1ba914ea1f79fc5e691d4d68471aa1e20279b6e), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/code-sdk@1.19.1-alpha.6 - - @mastra/core@1.84.0-alpha.5 - - @mastra/connect@1.4.1-alpha.2 - ## 0.29.0-alpha.5 ### Minor Changes diff --git a/mastracode/factory/README.md b/mastracode/factory/README.md index d192f6ceaad..58cb2cef3b1 100644 --- a/mastracode/factory/README.md +++ b/mastracode/factory/README.md @@ -772,7 +772,6 @@ A phase's `runner.skill` runs a skill when a card enters the phase. Use a built- 1. **Code skills** — passed to `new MastraFactory({ skills })`, created with `createSkill()` from `@mastra/core/skills`. 2. **Folder skills** — `src/mastra/factory-skills//SKILL.md` in your app. `mastra build` copies the folder into the build output. The older `src/mastra/public/factory-skills` still works; when both exist, `src/mastra/factory-skills` wins. Factory also looks in `public/factory-skills`, `factory-skills` and `output/factory-skills` under the working directory, and uses the first that exists. Supporting files, such as `references/`, can sit next to `SKILL.md`. 3. **Built-in skills** shipped with `@mastra/factory`. -4. **Factory skills** — skills an organization admin created for one Factory in Settings › Skills (see [Create skills for one Factory](#create-skills-for-one-factory)). They only fill names the first three don't use. A skill with the same name as a built-in skill replaces it, for the built-in boards too. A code skill replaces the whole folder skill of the same name, including its supporting files. Repository skills in a project's own repository never replace these. @@ -835,20 +834,6 @@ An edited skill shows an **Edited** badge. When the original changes after the e Saves and reverts are recorded in the audit log as `factory.skill.updated` and `factory.skill.reverted`. The API is `PUT` and `DELETE` on `/web/factory/projects/:id/skills/:name`, and `GET /web/factory/skills?projectId=` lists a Factory's skills with its edits. -### Create skills for one Factory - -Organization admins can also add a skill to one Factory without changing the app. Open Settings › Skills, choose **New skill**, enter a name, a description and instructions, and choose **Create**. The name uses 1–64 lowercase letters, digits and single hyphens, such as `release-notes`, and can't be one an app or built-in skill already uses; edit that skill instead. - -A created skill belongs to that Factory only and shows a **Custom** badge. Its sessions can load it from their next start, like any other skill, and a phase of its boards can run it as `runner.skill`. `factory.upsertBoard()` accepts a board that runs a created skill only when `projects` lists the projects, and each of them must have created it; a board for `'all'` projects may only run the app's skills. Choose **Edit** to change it, and **Delete** to remove it; a phase that runs a deleted skill shows it as missing, and cards entering that phase fail to start until you pick another skill. A repository skill with the same name is hidden in that Factory's sessions, as it is for app skills. - -If your app later ships a skill under the same name, the app's skill takes over the name and the Factory's text becomes an edit of it: it keeps applying, the editor notes that the original changed, and **Revert to original** switches to the app's skill. - -Creating and deleting are recorded in the audit log as `factory.skill.created` and `factory.skill.deleted`; changes to a created skill as `factory.skill.updated`. The API is `POST /web/factory/projects/:id/skills` with `{ "name", "content" }`, where `content` is the full `SKILL.md` whose frontmatter `name` matches; `PUT` and `DELETE` on `/web/factory/projects/:id/skills/:name` update and delete it. `GET /web/factory/skills?projectId=` lists created skills with `origin: "project"`. From the CLI: - -```bash -mastra api factory skill create '{"name":"release-notes","content":"---\nname: release-notes\ndescription: Write release notes for a merged change\n---\n\n# Release notes\n"}' -``` - ### Execute a custom board Custom boards can create linked items, start working roles, transition through bound tools, and react to completed tool results. Board and phase identifiers contain 1–128 letters, digits, underscores, or hyphens and start with a letter or digit. Identifiers are case-sensitive and cannot contain surrounding whitespace. diff --git a/mastracode/factory/package.json b/mastracode/factory/package.json index 134ab365c61..b2e3071288b 100644 --- a/mastracode/factory/package.json +++ b/mastracode/factory/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/factory", - "version": "0.29.0-alpha.7", + "version": "0.29.0-alpha.5", "description": "Mastra Software Factory module: the server core behind the Mastra Software Factory — storage domains, integrations, and surfaces for agent-powered software delivery", "type": "module", "publishConfig": { diff --git a/mastracode/factory/src/boards/board-writes.test.ts b/mastracode/factory/src/boards/board-writes.test.ts index 315a26f4304..bfab7a8d94c 100644 --- a/mastracode/factory/src/boards/board-writes.test.ts +++ b/mastracode/factory/src/boards/board-writes.test.ts @@ -5,14 +5,12 @@ import { join } from 'node:path'; import { LibSQLFactoryStorage } from '@mastra/libsql'; import { PgFactoryStorage } from '@mastra/pg'; -import { describe, expect, it, onTestFinished, vi } from 'vitest'; +import { describe, expect, it, onTestFinished } from 'vitest'; -import { projectSkillNamesOf } from '../skills/catalog.js'; import type { EmitAuditInput } from '../storage/domains/audit/domain.js'; import { StoredBoardsStorage } from '../storage/domains/boards/base.js'; import type { StoredPhaseInput } from '../storage/domains/boards/base.js'; import { FactoryProjectsStorage } from '../storage/domains/projects/base.js'; -import { SkillOverridesStorage } from '../storage/domains/skill-overrides/base.js'; import { WorkItemsStorage } from '../storage/domains/work-items/base.js'; import { BoardWriteError, BoardWrites } from './board-writes.js'; import type { BoardWriter } from './board-writes.js'; @@ -59,107 +57,20 @@ describe.each(['libsql', ...(postgresUrl ? ['postgres'] : [])])('board writes on const projects = factoryStorage.registerDomain(new FactoryProjectsStorage()); const workItems = factoryStorage.registerDomain(new WorkItemsStorage()); const storage = factoryStorage.registerDomain(new StoredBoardsStorage()); - const skillOverrides = factoryStorage.registerDomain(new SkillOverridesStorage()); await factoryStorage.init(); onTestFinished(() => factoryStorage.close()); const orgId = `org-${randomUUID()}`; const project = await projects.create({ orgId, userId: 'admin', input: { name: 'Acme' } }); const scope = { orgId, factoryProjectId: project.id }; - const boards = new ProjectBoardCache({ - codeRegistry: createBoardRegistry(), - storage, - projects, - projectSkills: projectSkillNamesOf(skillOverrides), - recheckMs: 0, - warn: () => {}, - }); + const boards = new ProjectBoardCache({ codeRegistry: createBoardRegistry(), storage, projects, warn: () => {} }); const audits: EmitAuditInput[] = []; const writer: BoardWriter = { id: 'admin', audit: async input => void audits.push(input) }; const writes = new BoardWrites({ storage, boards, workItems }); const served = async (key: string) => (await boards.describe(scope)).registry.get(key); - return { storage, workItems, skillOverrides, scope, boards, writes, writer, audits, served }; + return { storage, workItems, scope, boards, writes, writer, audits, served }; } - it("runs a skill the project created, and flags the phase once it's deleted", async () => { - const { writes, writer, scope, boards, skillOverrides } = await setup(); - const notes = { - key: 'notes', - name: 'Release notes', - phases: [ - { key: 'queued', name: 'Queued', kind: 'resting', nextPhases: ['writing'] }, - { - key: 'writing', - name: 'Writing', - kind: 'working', - runner: { context: 'writer', skill: 'release-notes' }, - nextPhases: ['done'], - }, - { key: 'done', name: 'Done', kind: 'terminal' }, - ], - } satisfies { key: string; name: string; phases: StoredPhaseInput[] }; - const skill = { orgId: scope.orgId, projectId: scope.factoryProjectId, skillName: 'release-notes' }; - - expect(await refusal(() => writes.create(scope, notes, writer))).toMatchObject({ - status: 422, - code: 'unknown_skill', - }); - - await skillOverrides.create({ - ...skill, - content: '---\nname: release-notes\ndescription: Write release notes\n---\n\n# Notes\n', - updatedBy: 'admin', - }); - await writes.create(scope, notes, writer); - expect((await boards.describe(scope)).details.get('notes')?.problems).toEqual([]); - - // Another project has no such skill. - const other = { orgId: scope.orgId, factoryProjectId: randomUUID() }; - expect(await boards.projectSkillNames(other)).toEqual(new Set()); - - await skillOverrides.delete(skill); - expect((await boards.describe(scope)).details.get('notes')?.problems).toEqual([ - expect.stringContaining("runs skill 'release-notes', but no such skill exists"), - ]); - }); - - it("fails a write with the storage error, not unknown_skill, when the project's skills can't be read", async () => { - const { writes, writer, scope, skillOverrides, storage } = await setup(); - vi.spyOn(skillOverrides, 'list').mockRejectedValueOnce(new Error('connection reset')); - await expect(writes.create(scope, bugs, writer)).rejects.toThrow('connection reset'); - expect(await storage.get(scope, 'bugs')).toBeNull(); - }); - - it("flags a created skill as missing only while the project's skills can't be read", async () => { - const { writes, writer, scope, boards, skillOverrides } = await setup(); - const project = { orgId: scope.orgId, projectId: scope.factoryProjectId }; - const create = (skillName: string) => - skillOverrides.create({ - ...project, - skillName, - content: `---\nname: ${skillName}\ndescription: A skill\n---\n\n# ${skillName}\n`, - updatedBy: 'admin', - }); - await create('release-notes'); - const runsNotes = { - ...bugs, - phases: bugs.phases.map(phase => - phase.key === 'fixing' ? { ...phase, runner: { context: 'work', skill: 'release-notes' } } : phase, - ), - }; - await writes.create(scope, runsNotes, writer); - const problems = async () => (await boards.describe(scope)).details.get('bugs')?.problems; - expect(await problems()).toEqual([]); - - // Another save moves the revision; the names read after it fails once. - await create('changelog'); - vi.spyOn(skillOverrides, 'list').mockRejectedValueOnce(new Error('connection reset')); - expect(await problems()).toEqual([expect.stringContaining("runs skill 'release-notes', but no such skill exists")]); - - // The revision hasn't moved since, but the next load reads the names again. - expect(await problems()).toEqual([]); - }); - it('creates a board, serves it at once, and records who did it', async () => { const { writes, writer, scope, audits, served } = await setup(); const row = await writes.create(scope, bugs, writer); diff --git a/mastracode/factory/src/boards/board-writes.ts b/mastracode/factory/src/boards/board-writes.ts index 7fb5dbccdc3..8de8de6ee11 100644 --- a/mastracode/factory/src/boards/board-writes.ts +++ b/mastracode/factory/src/boards/board-writes.ts @@ -37,10 +37,7 @@ import { workBoard } from './work.js'; export interface BoardWritesDeps { storage: StoredBoardsStorage; /** The per-project boards: the code boards and their seeds, skills, and the cache to invalidate. */ - boards: Pick< - ProjectBoardCache, - 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills' | 'projectSkillNames' | 'seedFor' - >; + boards: Pick; /** Read to refuse edits that would strand cards; the retired Review board's cards leave `review` through it. */ workItems: Pick; } @@ -123,12 +120,10 @@ export class BoardWrites { } /** - * Validates a definition the way `defineBoard()` does, plus the skills its runners name: the app's, - * and `projectSkills`, the skills the project it is stored in created. `null` leaves the runners' - * skills unchecked, for a caller that checks them per project. A code board's copy is also checked - * against the code behaviour of its board and phase keys. + * Validates a definition the way `defineBoard()` does, plus the skills its runners name. A code + * board's copy is also checked against the code behaviour of its board and phase keys. */ - validate(input: unknown, projectSkills?: ReadonlySet | null): StoredBoardInput { + validate(input: unknown): StoredBoardInput { const { boards } = this.deps; const parsed = storedBoardInputSchema.safeParse(input); if (!parsed.success) { @@ -142,8 +137,7 @@ export class BoardWrites { } } const board = code ? compileStoredBoard(parsed.data, code) : compileStoredBoard(parsed.data); - if (projectSkills === null) return parsed.data; - const problems = findBoardSkillProblems(boardRegistryOf([board]), boards.codeSkills, undefined, projectSkills); + const problems = findBoardSkillProblems(boardRegistryOf([board]), boards.codeSkills); const unknown = problems.filter(problem => problem.includes(UNKNOWN_SKILL)); if (unknown.length > 0) throw new BoardWriteError(422, { error: 'unknown_skill', message: unknown.join(' ') }); return parsed.data; @@ -153,7 +147,7 @@ export class BoardWrites { async create(scope: StoredBoardScope, input: unknown, writer: BoardWriter): Promise { const key = (input as { key?: unknown } | null)?.key; if (typeof key === 'string') this.refuseCodeBoard(key, 'create'); - const board = this.validate(input, await this.deps.boards.projectSkillNames(scope)); + const board = this.validate(input); // Factory stores its boards only into a project that has none, so they go in first. await this.deps.boards.describe(scope); const row = await stored(() => @@ -228,7 +222,7 @@ export class BoardWrites { // The project's first load stores Factory's boards. if (seed) await boards.describe(scope); const row = await this.existing(scope, key); - const input = this.validate({ key, ...definition }, await boards.projectSkillNames(scope)); + const input = this.validate({ key, ...definition }); if (row.revision === expectedRevision && sameBoardDefinition(row, input)) { return { row, written: false }; } diff --git a/mastracode/factory/src/boards/project-boards.ts b/mastracode/factory/src/boards/project-boards.ts index c58f6d42db0..c39e12bd0c6 100644 --- a/mastracode/factory/src/boards/project-boards.ts +++ b/mastracode/factory/src/boards/project-boards.ts @@ -123,24 +123,9 @@ interface CacheEntry { boards: ProjectBoards; version: string | null; reviewInUse: boolean; - /** The project's skill revision the boards' skill problems were checked at. */ - skillsRevision: number; checkedAt: number; } -/** - * The skills a project created (Settings › Skills), which its boards' runners may name besides the app's. - * `revision` moves whenever the project's skills change, so loads recheck the names only then. - */ -export interface ProjectSkillNames { - revision(scope: StoredBoardScope): Promise; - names(scope: StoredBoardScope): Promise>; -} - -const NO_PROJECT_SKILLS: ReadonlySet = new Set(); -/** Recorded when the project's skills couldn't be read; never a stored revision, so the next load rereads them. */ -const UNREAD_SKILLS_REVISION = -1; - export interface ProjectBoardCacheOptions { /** The code boards, built-ins included when enabled. */ codeRegistry: BoardRegistry; @@ -162,8 +147,6 @@ export interface ProjectBoardCacheOptions { ops: FactoryStorageOps, ) => Promise> | null>; codeSkills?: readonly InlineSkill[]; - /** The skills each project created. Without it, runners may only name the app's skills. */ - projectSkills?: ProjectSkillNames; /** * Whether the project still uses the retired Review board (an open card is stored on it). Such * a project is served Review alongside its boards; without this, no project is. @@ -230,7 +213,6 @@ export class ProjectBoardCache implements ProjectBoardSource { readonly #warned = new Set(); readonly #seeded = new Set(); readonly #codeSkills: readonly InlineSkill[]; - readonly #projectSkills: ProjectSkillNames | undefined; readonly #seeds: ReadonlyMap; /** Boards the app upserted for every project, which a project with no boards gets before Factory's. */ readonly #appBoards = new Map(); @@ -246,7 +228,6 @@ export class ProjectBoardCache implements ProjectBoardSource { this.#occupiedPhases = options.occupiedPhases; this.#projects = options.projects; this.#codeSkills = options.codeSkills ?? []; - this.#projectSkills = options.projectSkills; this.#recheckMs = options.recheckMs ?? DEFAULT_RECHECK_MS; this.#now = options.now ?? Date.now; this.#warn = options.warn ?? (message => console.warn(`[factory] ${message}`)); @@ -365,39 +346,6 @@ export class ProjectBoardCache implements ProjectBoardSource { return this.#codeSkills; } - /** - * The skills the project created, which its runners may name besides the app's. Throws when they can't be - * read, so a board write fails with the storage error instead of refusing a skill the project has. - */ - async projectSkillNames(scope: StoredBoardScope): Promise> { - return this.#projectSkills ? this.#projectSkills.names(scope) : NO_PROJECT_SKILLS; - } - - /** - * The names for a load, or undefined when they can't be read: the load still serves the boards, flags their - * created skills as missing, and doesn't cache what it compiled without them. - */ - async #readProjectSkillNames(scope: StoredBoardScope): Promise | undefined> { - try { - return await this.projectSkillNames(scope); - } catch (error) { - this.#warnOnce( - `project-skills:${scopeKey(scope)}`, - `Could not read the skills project ${scope.factoryProjectId} created; boards that run them show them as missing: ${error instanceof Error ? error.message : String(error)}`, - ); - return undefined; - } - } - - async #projectSkillsRevision(scope: StoredBoardScope): Promise { - if (!this.#projectSkills) return 0; - try { - return await this.#projectSkills.revision(scope); - } catch { - return UNREAD_SKILLS_REVISION; - } - } - /** Makes the next load reread the project. The loaded boards keep serving sync reads until then. */ invalidate(scope: StoredBoardScope): void { const key = scopeKey(scope); @@ -430,30 +378,14 @@ export class ProjectBoardCache implements ProjectBoardSource { const current = this.#entries.get(key); const version = await this.#storage.readVersion(scope); const reviewInUse = (await this.#reviewBoardInUse?.(scope)) ?? false; - let skillsRevision = await this.#projectSkillsRevision(scope); - if ( - current && - current.version === version && - current.reviewInUse === reviewInUse && - current.skillsRevision === skillsRevision && - skillsRevision !== UNREAD_SKILLS_REVISION - ) { + if (current && current.version === version && current.reviewInUse === reviewInUse) { if ((this.#generations.get(key) ?? 0) === generation) current.checkedAt = this.#now(); return current.boards; } const snapshot = await this.#consistentSnapshot(scope); - const projectSkills = await this.#readProjectSkillNames(scope); - // Compiled without the names, the boards flag their skills as missing: the next load reads them again. - if (projectSkills === undefined) skillsRevision = UNREAD_SKILLS_REVISION; - const boards = this.#compile(scope, snapshot.boards, reviewInUse, projectSkills ?? NO_PROJECT_SKILLS); + const boards = this.#compile(scope, snapshot.boards, reviewInUse); if ((this.#generations.get(key) ?? 0) === generation) { - this.#entries.set(key, { - boards, - version: snapshot.version, - reviewInUse, - skillsRevision, - checkedAt: this.#now(), - }); + this.#entries.set(key, { boards, version: snapshot.version, reviewInUse, checkedAt: this.#now() }); } return boards; } @@ -547,12 +479,7 @@ export class ProjectBoardCache implements ProjectBoardSource { }; } - #compile( - scope: StoredBoardScope, - rows: readonly StoredBoardRecord[], - reviewInUse: boolean, - projectSkills: ReadonlySet, - ): ProjectBoards { + #compile(scope: StoredBoardScope, rows: readonly StoredBoardRecord[], reviewInUse: boolean): ProjectBoards { const byKey = new Map(rows.map(row => [row.key, row])); const details = new Map(this.#codeDetails); const problems: string[] = []; @@ -594,7 +521,7 @@ export class ProjectBoardCache implements ProjectBoardSource { report(row, merged.problems); details.set(code.id, { ...details.get(code.id)!, - problems: [...merged.problems, ...this.#skillProblems(merged.board, projectSkills)], + problems: [...merged.problems, ...this.#skillProblems(merged.board)], }); boards.push(merged.board); } @@ -621,7 +548,7 @@ export class ProjectBoardCache implements ProjectBoardSource { continue; } boards.push(board); - details.set(row.key, { source: 'stored', editable: true, problems: this.#skillProblems(board, projectSkills) }); + details.set(row.key, { source: 'stored', editable: true, problems: this.#skillProblems(board) }); } return { registry: boardRegistryOf(boards), @@ -630,8 +557,8 @@ export class ProjectBoardCache implements ProjectBoardSource { }; } - #skillProblems(board: InstalledBoard, projectSkills?: ReadonlySet): string[] { - return findBoardSkillProblems(boardRegistryOf([board]), this.#codeSkills, undefined, projectSkills); + #skillProblems(board: InstalledBoard): string[] { + return findBoardSkillProblems(boardRegistryOf([board]), this.#codeSkills); } #warnOnce(key: string, message: string, debug = false): void { diff --git a/mastracode/factory/src/boards/stored-board-runtime.test.ts b/mastracode/factory/src/boards/stored-board-runtime.test.ts index f343ea20b94..ae067c8a583 100644 --- a/mastracode/factory/src/boards/stored-board-runtime.test.ts +++ b/mastracode/factory/src/boards/stored-board-runtime.test.ts @@ -1077,45 +1077,6 @@ describe.each(['libsql', ...(postgresUrl ? ['postgres'] : [])])( ).rejects.toMatchObject({ code: 'project_not_found' }); }, 60_000); - it('lets a board run a skill the named projects created, and refuses it where one has none', async () => { - stubModel(); - const orgId = `org-${randomUUID()}`; - const replica = await boot(await isolatedDatabase(), orgId); - const [withSkill, without] = [await createProject(replica, 'With'), await createProject(replica, 'Without')]; - const created = await replica.send('POST', `/web/factory/projects/${withSkill}/skills`, { - name: 'release-notes', - content: '---\nname: release-notes\ndescription: Write release notes\n---\n\n# Notes\n', - }); - expect(created.status, JSON.stringify(created.json)).toBe(201); - const notes: StoredBoardInput = { - ...bugsBoard, - key: 'notes', - name: 'Notes', - phases: bugsBoard.phases.map(phase => - phase.key === 'fixing' ? { ...phase, runner: { context: 'work', skill: 'release-notes' } } : phase, - ), - }; - const scope = (factoryProjectId: string) => ({ orgId, factoryProjectId }); - - // A list with a project that lacks the skill is refused before any project is written. - await expect( - replica.factory.upsertBoard(notes, { projects: [scope(withSkill), scope(without)] }), - ).rejects.toMatchObject({ code: 'unknown_skill' }); - expect(await replica.boards.get(scope(withSkill), 'notes')).toBeNull(); - // A board for every project may only run the app's skills. - await expect(replica.factory.upsertBoard(notes, { projects: 'all' })).rejects.toMatchObject({ - code: 'unknown_skill', - }); - - expect(await replica.factory.upsertBoard(notes, { projects: [scope(withSkill)] })).toMatchObject({ - inserted: [scope(withSkill)], - }); - // Saved again, it is checked against the project's skills as an edit is. - expect(await replica.factory.upsertBoard(notes, { projects: [scope(withSkill)] })).toMatchObject({ - unchanged: [scope(withSkill)], - }); - }, 60_000); - it('stores the Work board the README shows for replacing Work in every project, over edits and cards in Triage, and keeps it through a reset', async () => { stubModel(); // The README, not the changeset: `changeset version` deletes changesets. diff --git a/mastracode/factory/src/factory.ts b/mastracode/factory/src/factory.ts index eebd320456d..609aeabd036 100644 --- a/mastracode/factory/src/factory.ts +++ b/mastracode/factory/src/factory.ts @@ -194,7 +194,6 @@ import { observeSessionThreadTitle } from './session/thread-title-mirror.js'; import { FactoryWorkItemStateProcessor } from './session/work-item-state-processor.js'; import { shareSessionListChanges } from './session-list-changes.js'; import { assertFactorySkills, findBoardSkillProblems } from './skills/app-skills.js'; -import { projectSkillNamesOf } from './skills/catalog.js'; import { createSpaStaticMiddleware, resolveUiDistDir } from './spa-static.js'; import { createStateSigner } from './state-signing.js'; import { observeAgentGitAction } from './storage/domains/audit/agent-audit.js'; @@ -736,9 +735,7 @@ export class MastraFactory { * project gets none. This lasts for the process, so run it at every startup. A Work or app * board's key keeps that board's code behaviour, * so the definition is checked as an edit is; a new key gets none (no tool, source-closed or - * event rules). The board is validated as the boards API validates it; a runner may name a skill a - * project created in Settings › Skills only when `projects` lists the projects, and each listed - * project must have it, while a board for `'all'` projects may only run the app's skills. Each write is audited + * event rules). The board is validated once, as the boards API does, and each write is audited * as `factory.board.created` or `factory.board.updated` by `system:factory`. Refusals throw a * `BoardWriteError` (`invalid_board`, `unknown_skill`, `code_behaviour`, `phase_in_use` when cards * sit in a phase it removes, `board_in_use` when the key is `review` and the retired Review board @@ -776,8 +773,7 @@ export class MastraFactory { ); } const { writes, boards, projects, audit } = store; - // Named projects may have created the skills their runners name, so those are checked per project below. - const input = writes.validate(board, options.projects === 'all' ? undefined : null); + const input = writes.validate(board); // Work and app boards are stored per project like any other. writes.refuseCodeBoard(input.key, 'edit'); await projects.ensureReady(); @@ -795,7 +791,6 @@ export class MastraFactory { message: `Project "${scope.factoryProjectId}" does not exist.`, }); } - writes.validate(input, await boards.projectSkillNames(scope)); } } const result: { inserted: StoredBoardScope[]; updated: StoredBoardScope[]; unchanged: StoredBoardScope[] } = { @@ -1126,10 +1121,6 @@ export class MastraFactory { storage: storedBoardsStorage, projects: factoryProjectsStorage, codeSkills: this.#skills, - // Runners may also name the skills a project created in Settings › Skills. - ...(storage.isDomainReady('skill-overrides') - ? { projectSkills: projectSkillNamesOf(skillOverridesStorage) } - : {}), // A project still using the retired Review board keeps it; work items are read once they're ready. ...(storage.isDomainReady('work-items') ? { diff --git a/mastracode/factory/src/integrations/slack/run-error-card.test.ts b/mastracode/factory/src/integrations/slack/run-error-card.test.ts index ad986f88ae6..42ccd942680 100644 --- a/mastracode/factory/src/integrations/slack/run-error-card.test.ts +++ b/mastracode/factory/src/integrations/slack/run-error-card.test.ts @@ -1,3 +1,7 @@ +import { mkdtempSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + import { prepareCredentialTenant, setCredentialStoreProvider } from '@mastra/code-sdk/agents/credential-resolver'; import type { CredentialTenant } from '@mastra/code-sdk/agents/credential-resolver'; import { ProviderAuthRequiredError } from '@mastra/code-sdk/auth/provider-auth-error'; @@ -213,4 +217,17 @@ describe('slackRunErrorCard', () => { expect(card).not.toContain('https://'); } }); + + it('recognizes a refusal from the gateway this server is configured to use', () => { + // An empty settings directory, so only the environment names the gateway. + vi.stubEnv('MASTRA_APP_DATA_DIR', mkdtempSync(join(tmpdir(), 'slack-gateway-settings-'))); + vi.stubEnv('MASTRA_GATEWAY_URL', 'https://gateway.staging.example.com/v1'); + const outOfCredits = Object.assign(new Error('Payment Required'), { + name: 'AI_APICallError', + statusCode: 402, + url: 'https://gateway.staging.example.com/v1/chat/completions', + }); + + expect(rendered(slackRunErrorCard(outOfCredits, slackRun()))).toContain('Out of Mastra Gateway credits'); + }); }); diff --git a/mastracode/factory/src/integrations/slack/run-error-card.ts b/mastracode/factory/src/integrations/slack/run-error-card.ts index 80980ca4a73..7b179bda0d8 100644 --- a/mastracode/factory/src/integrations/slack/run-error-card.ts +++ b/mastracode/factory/src/integrations/slack/run-error-card.ts @@ -4,6 +4,7 @@ import { providerRequestId } from '@mastra/core/error'; import type { RequestContext } from '@mastra/core/request-context'; import { Actions, Card, CardText, LinkButton } from 'chat'; +import { mastraGatewayBaseUrl } from '../../routes/mastra-gateway.js'; import { readFactorySessionScope } from '../../rules/binding-context.js'; import type { RunErrorRecovery } from '../../run-error.js'; import { describeRunError } from '../../run-error.js'; @@ -12,7 +13,7 @@ import { modelSettingsLink } from './channel-reply-processor.js'; import { sessionLinkFromRequest } from './channel-session-link-processor.js'; export function slackRunErrorCard(error: Error, { requestContext }: ChannelErrorContext) { - const { title, message, recoveries, model } = describeRunError(error); + const { title, message, recoveries, model } = describeRunError(error, { gatewayBaseUrl: mastraGatewayBaseUrl() }); const requestId = providerRequestId(error); const facts = [model && `Model: ${model}`, requestId && `Request id: ${requestId}`].filter(Boolean).join(' · '); const credential = model && recoveries.includes('credentials') ? credentialLine(requestContext, model) : undefined; diff --git a/mastracode/factory/src/links.test.ts b/mastracode/factory/src/links.test.ts index 5043dbf0702..9fd23b91c99 100644 --- a/mastracode/factory/src/links.test.ts +++ b/mastracode/factory/src/links.test.ts @@ -15,7 +15,7 @@ describe('factory links', () => { it('builds nothing when no public URL is configured', () => { vi.stubEnv('MASTRACODE_PUBLIC_URL', ' '); expect(factoryUiOrigin()).toBeNull(); - expect(factoryWorkItemUrl({ factoryProjectId: 'f', workItemId: 'i' })).toBeUndefined(); + expect(factoryWorkItemUrl({ factoryProjectId: 'f', board: 'work', workItemId: 'i' })).toBeUndefined(); }); it('links boards, cards, sessions, settings and rules', () => { @@ -24,7 +24,9 @@ describe('factory links', () => { // The Review board is retired; a board keyed `review` now is a custom board like any other. expect(factoryBoardUrl('f 1', 'review')).toBe(`${base}/boards/review`); expect(factoryBoardUrl('f 1', 'ops')).toBe(`${base}/boards/ops`); - expect(factoryWorkItemUrl({ factoryProjectId: 'f 1', workItemId: 'i 1' })).toBe(`${base}/cards/i%201`); + expect(factoryWorkItemUrl({ factoryProjectId: 'f 1', board: 'work', workItemId: 'i-1' })).toBe( + `${base}/work?item=i-1`, + ); expect(factorySessionUrl({ factoryProjectId: 'f 1', sessionId: 's', threadId: 't' })).toBe( `${base}/workspaces/s/threads/t`, ); diff --git a/mastracode/factory/src/links.ts b/mastracode/factory/src/links.ts index 70f81dca6e9..c3b55ead910 100644 --- a/mastracode/factory/src/links.ts +++ b/mastracode/factory/src/links.ts @@ -25,12 +25,14 @@ export function factoryBoardUrl(factoryProjectId: string, board: string): string return factoryUrl(factoryProjectId, boardSegment(board)); } -/** - * A card, opened as the board opens it on a click: the UI sends the link on to the session the card - * shows (its current phase's, else its last visited one's), or to a draft that starts one. - */ -export function factoryWorkItemUrl(input: { factoryProjectId: string; workItemId: string }): string | undefined { - return factoryUrl(input.factoryProjectId, `/cards/${encodeURIComponent(input.workItemId)}`); +/** A card opened on its board. */ +export function factoryWorkItemUrl(input: { + factoryProjectId: string; + board: string; + workItemId: string; +}): string | undefined { + const query = new URLSearchParams({ item: input.workItemId }); + return factoryUrl(input.factoryProjectId, `${boardSegment(input.board)}?${query}`); } export function factorySessionUrl(input: { diff --git a/mastracode/factory/src/routes/boards.ts b/mastracode/factory/src/routes/boards.ts index 7c2db25dc68..98cd77fc40f 100644 --- a/mastracode/factory/src/routes/boards.ts +++ b/mastracode/factory/src/routes/boards.ts @@ -31,10 +31,7 @@ export interface BoardRoutesDeps extends RouteDependencies { workItems: Pick; storage: StoredBoardsStorage; /** The per-project boards: the code boards and their seeds, skills, and the cache to invalidate. */ - boards: Pick< - ProjectBoardCache, - 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills' | 'projectSkillNames' | 'seedFor' - >; + boards: Pick; } type Resolved = StoredBoardScope & { userId: string }; diff --git a/mastracode/factory/src/routes/config.test.ts b/mastracode/factory/src/routes/config.test.ts index 371f1ab78a6..218a7476847 100644 --- a/mastracode/factory/src/routes/config.test.ts +++ b/mastracode/factory/src/routes/config.test.ts @@ -1018,6 +1018,30 @@ describe('Mastra Gateway routes with a tenant', () => { expect(await gatewayRow(buildApp(fakePlatform()))).toMatchObject({ connectWithMastraAccount: true }); expect(await gatewayRow(buildApp())).not.toHaveProperty('connectWithMastraAccount'); }); + describe('the gateway origin for the web UI', () => { + beforeEach(async () => { + // An empty settings directory, so a gateway URL in the developer's own settings cannot apply. + vi.stubEnv('MASTRA_APP_DATA_DIR', await fs.mkdtemp(join(tmpdir(), 'factory-gateway-origin-'))); + }); + afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + }); + + it.each([ + ['https://gateway-api.mastra.ai', 'https://gateway-api.mastra.ai'], + ['http://127.0.0.1:4180/v1/', 'http://127.0.0.1:4180'], + ])('reports the origin of the configured gateway %s', async (configured, origin) => { + vi.stubEnv('MASTRA_GATEWAY_URL', configured); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + + const body = (await (await buildApp(fakePlatform()).request('/web/config/providers')).json()) as { + mastraGatewayOrigin?: string; + }; + + expect(body.mastraGatewayOrigin).toBe(origin); + }); + }); }); describe('GET /web/config/models', () => { diff --git a/mastracode/factory/src/routes/config.ts b/mastracode/factory/src/routes/config.ts index 9058ebb0b71..bdf4f16cb1d 100644 --- a/mastracode/factory/src/routes/config.ts +++ b/mastracode/factory/src/routes/config.ts @@ -44,7 +44,13 @@ import type { WorkItemsStorage } from '../storage/domains/work-items/base.js'; import { THINKING_LEVELS } from './contracts.js'; import { customEndpointUrlProblem } from './custom-endpoint-url.js'; import { customProviderOwner } from './custom-provider-source.js'; -import { createGatewayKey, getGatewayCredits, MASTRA_SIGN_IN_REQUIRED, MastraGatewayError } from './mastra-gateway.js'; +import { + createGatewayKey, + getGatewayCredits, + MASTRA_SIGN_IN_REQUIRED, + MastraGatewayError, + mastraGatewayBaseUrl, +} from './mastra-gateway.js'; import { credentialLabel, getAuthProviderId, @@ -205,6 +211,15 @@ async function listCatalogModels( return [...models, ...gatewayModels]; } +function originOf(url: string): string | undefined { + try { + const origin = new URL(url).origin; + return origin === 'null' ? undefined : origin; + } catch { + return undefined; + } +} + /** * Build a deduplicated, sorted list of providers from the model catalog, * annotated with where each provider's credential currently comes from. @@ -1197,6 +1212,7 @@ export class ConfigRoutes extends Route { // keys, so the settings UI can gate the "Everyone in org" option. const tenant = auth.tenant(loose(c)); const orgKeyAdmin = tenant ? await auth.isOrganizationAdmin(loose(c), tenantOrgId(tenant)) : undefined; + const gatewayOrigin = originOf(mastraGatewayBaseUrl()); const customProviders = options.customProviders; const listCustomProviders = customProviders ? async () => { @@ -1215,6 +1231,8 @@ export class ConfigRoutes extends Route { connectWithMastraAccount, }), ...(orgKeyAdmin !== undefined ? { orgKeyAdmin } : {}), + // Lets the web UI recognize a saved run error from this server's gateway, wherever it is hosted. + ...(gatewayOrigin ? { mastraGatewayOrigin: gatewayOrigin } : {}), }); } catch (error) { return c.json({ error: error instanceof Error ? error.message : String(error) }, 500); diff --git a/mastracode/factory/src/routes/contracts.ts b/mastracode/factory/src/routes/contracts.ts index e39e17f4e87..847cb6fca48 100644 --- a/mastracode/factory/src/routes/contracts.ts +++ b/mastracode/factory/src/routes/contracts.ts @@ -1474,8 +1474,6 @@ const skillNameSchema = z .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/); const skillPathSchema = z.object({ id: uuidSchema, name: skillNameSchema }); const skillResponseSchema = z.object({ skill: entitySchema }); -/** `skill` is null when the request deleted a skill the project created. */ -const skillRevertResponseSchema = z.object({ skill: entitySchema.nullable() }); /** Adds the runtime's SKILL.md validation errors, checking the frontmatter name against `directoryName` when given. */ function refineSkillContent(content: string, context: z.RefinementCtx, directoryName?: string) { @@ -1498,12 +1496,6 @@ export const skillOverrideSaveRequestSchema = skillPathSchema .extend({ content: skillContentSchema }) .superRefine((input, context) => refineSkillContent(input.content, context, input.name)); -/** A new skill's SKILL.md must load under the name it is created with, exactly as the runtime validates it. */ -export const skillCreateBodySchema = z - .object({ name: skillNameSchema, content: skillContentSchema }) - .strict() - .superRefine((input, context) => refineSkillContent(input.content, context, input.name)); - export const FACTORY_ROUTE_CONTRACTS = { projectList: { method: 'GET', @@ -2082,18 +2074,10 @@ export const FACTORY_ROUTE_CONTRACTS = { querySchema: z.object({ projectId: uuidSchema.optional() }), responseSchema: z.object({ skills: z.array(entitySchema), canEdit: z.boolean().optional() }), }, - skillCreate: { - method: 'POST', - path: '/web/factory/projects/:id/skills', - description: 'Create a skill for one Factory project', - pathSchema: projectPathSchema, - bodySchema: skillCreateBodySchema, - responseSchema: skillResponseSchema, - }, skillOverrideSave: { method: 'PUT', path: '/web/factory/projects/:id/skills/:name', - description: "Save a project's SKILL.md for a Factory skill: an edit of an app skill, or a skill it created", + description: "Save a project's edited SKILL.md for a Factory skill", pathSchema: skillPathSchema, bodySchema: skillOverrideBodySchema, responseSchema: skillResponseSchema, @@ -2101,10 +2085,9 @@ export const FACTORY_ROUTE_CONTRACTS = { skillOverrideRevert: { method: 'DELETE', path: '/web/factory/projects/:id/skills/:name', - description: - "Revert a project's edited Factory skill to its original SKILL.md, or delete a skill the project created", + description: "Revert a project's edited Factory skill to its original SKILL.md", pathSchema: skillPathSchema, - responseSchema: skillRevertResponseSchema, + responseSchema: skillResponseSchema, }, } as const satisfies Record; diff --git a/mastracode/factory/src/routes/mastra-gateway.test.ts b/mastracode/factory/src/routes/mastra-gateway.test.ts new file mode 100644 index 00000000000..4842fee25d5 --- /dev/null +++ b/mastracode/factory/src/routes/mastra-gateway.test.ts @@ -0,0 +1,50 @@ +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { mastraGatewayBaseUrl } from './mastra-gateway.js'; + +function withSettings(settings?: unknown) { + const dir = mkdtempSync(join(tmpdir(), 'mastra-gateway-url-')); + if (settings !== undefined) writeFileSync(join(dir, 'settings.json'), JSON.stringify(settings)); + vi.stubEnv('MASTRA_APP_DATA_DIR', dir); +} + +describe('mastraGatewayBaseUrl', () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it('prefers the settings over the environment, as model calls do', () => { + withSettings({ memoryGateway: { baseUrl: 'https://gateway.settings.example.com/v1/' } }); + vi.stubEnv('MASTRA_GATEWAY_URL', 'https://gateway.env.example.com'); + + expect(mastraGatewayBaseUrl()).toBe('https://gateway.settings.example.com'); + }); + + it('uses the environment when the settings name no gateway', () => { + withSettings(); + vi.stubEnv('MASTRA_GATEWAY_URL', 'http://127.0.0.1:4180/v1'); + + expect(mastraGatewayBaseUrl()).toBe('http://127.0.0.1:4180'); + }); + + it.each([ + ['a number', 42], + ['a blank string', ' '], + ])('ignores a setting that is %s', (_shape, baseUrl) => { + withSettings({ memoryGateway: { baseUrl } }); + vi.stubEnv('MASTRA_GATEWAY_URL', 'https://gateway.env.example.com'); + + expect(mastraGatewayBaseUrl()).toBe('https://gateway.env.example.com'); + }); + + it('falls back to the production gateway', () => { + withSettings(); + vi.stubEnv('MASTRA_GATEWAY_URL', ''); + + expect(mastraGatewayBaseUrl()).toBe('https://gateway-api.mastra.ai'); + }); +}); diff --git a/mastracode/factory/src/routes/mastra-gateway.ts b/mastracode/factory/src/routes/mastra-gateway.ts index 58b72ea8071..9e75b2d2e98 100644 --- a/mastracode/factory/src/routes/mastra-gateway.ts +++ b/mastracode/factory/src/routes/mastra-gateway.ts @@ -1,8 +1,29 @@ +import { loadSettings } from '@mastra/code-sdk/onboarding/settings'; import type { Context } from 'hono'; import { z } from 'zod'; import type { RouteAuth } from './route.js'; +/** + * The Mastra Gateway this server sends model calls to: the `memoryGateway.baseUrl` setting, then + * `MASTRA_GATEWAY_URL`, then production, without a trailing slash or `/v1`. This is the order the SDK's + * per-request model resolution reads them in, which is where run calls go. (The SDK's startup reads the + * environment first, but only for its boot-time gateway, which does not send model calls.) A setting + * that is not a non-empty string is ignored. + */ +export function mastraGatewayBaseUrl(): string { + let configured: unknown; + try { + configured = loadSettings().memoryGateway?.baseUrl; + } catch { + // An unreadable settings file leaves the environment and the default in charge. + } + const fromSettings = typeof configured === 'string' && configured.trim() ? configured.trim() : undefined; + const fromEnv = process.env.MASTRA_GATEWAY_URL?.trim() || undefined; + const raw = fromSettings ?? fromEnv ?? 'https://gateway-api.mastra.ai'; + return raw.replace(/\/+$/, '').replace(/\/v1$/, ''); +} + const MASTRA_PROJECTS_URL = process.env.MASTRA_PROJECTS_URL || 'https://projects.mastra.ai'; /** The Starter plan's gateway credit pool, used when the customer names none. */ diff --git a/mastracode/factory/src/routes/skills.test.ts b/mastracode/factory/src/routes/skills.test.ts index 7af28503db3..6742fcde079 100644 --- a/mastracode/factory/src/routes/skills.test.ts +++ b/mastracode/factory/src/routes/skills.test.ts @@ -626,12 +626,10 @@ describe('project skill edit routes', () => { writeFileSync(join(projectDir, 'factory-skills', dir, 'SKILL.md'), content); } - /** `afterAudit` runs once each write is audited, before the route responds, as another request could. */ - async function setup({ afterAudit }: { afterAudit?: () => Promise } = {}) { + async function setup() { const seed = await createFactoryStorageForTests(); const admins = new Set([ADMIN.workosId]); const auth = fakeRouteAuth({ isOrganizationAdmin: async (_org, userId) => admins.has(userId) }); - const auditDomain = new AuditDomain({ auth, audit: seed.audit, projects: seed.projects }); const routes = new SkillRoutes({ auth, controllerId: 'code', @@ -639,12 +637,7 @@ describe('project skill edit routes', () => { overrides: { projects: seed.projects, storage: seed.skillOverrides, - audit: { - emit: async input => { - await auditDomain.emit(input); - await afterAudit?.(); - }, - }, + audit: new AuditDomain({ auth, audit: seed.audit, projects: seed.projects }), }, }).routes(); const projectA = await seed.projects.create({ orgId: 'org-1', userId: ADMIN.workosId, input: { name: 'A' } }); @@ -668,12 +661,6 @@ describe('project skill edit routes', () => { }); const revert = (user: TestAuthUser, projectId: string, name: string) => request(user, `/web/factory/projects/${projectId}/skills/${name}`, { method: 'DELETE' }); - const create = (user: TestAuthUser, projectId: string, name: string, content: string) => - request(user, `/web/factory/projects/${projectId}/skills`, { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ name, content }), - }); const list = async (user: TestAuthUser, projectId: string) => { const response = await request(user, `/web/factory/skills?projectId=${projectId}`); expect(response.status).toBe(200); @@ -685,7 +672,6 @@ describe('project skill edit routes', () => { content: string; origin: string; edited?: { updatedBy: string; updatedAt: string }; - created?: { updatedBy: string; updatedAt: string }; originalChanged?: boolean; }[]; }; @@ -698,203 +684,10 @@ describe('project skill edit routes', () => { project: event.factoryProjectId, targets: event.targets, })); - return { seed, projectA, projectB, elsewhere, save, revert, create, list, skill, auditActions }; + return { seed, projectA, projectB, elsewhere, save, revert, list, skill, auditActions }; } const editedPlan = (body: string) => `---\nname: factory-plan\ndescription: Our planning rules\n---\n\n${body}\n`; - const releaseNotes = (body: string) => - `---\nname: release-notes\ndescription: Write release notes for a merged change\n---\n\n${body}\n`; - - describe('creating skills', () => { - it('creates a skill for its project only, lists it as a project skill, and records it', async () => { - const { projectA, projectB, create, list, auditActions } = await setup(); - const response = await create(ADMIN, projectA.id, 'release-notes', releaseNotes('# Notes')); - expect(response.status).toBe(201); - expect(((await response.json()) as { skill: unknown }).skill).toMatchObject({ - name: 'release-notes', - description: 'Write release notes for a merged change', - content: '# Notes', - origin: 'project', - builtIn: false, - created: { updatedBy: ADMIN.workosId }, - }); - - const a = await list(ADMIN, projectA.id); - const created = a.skills.find(s => s.name === 'release-notes'); - expect(created).toMatchObject({ origin: 'project', content: '# Notes' }); - expect(created?.edited).toBeUndefined(); - // The catalog stays sorted by name with created skills among the others. - const names = a.skills.map(s => s.name); - expect(names).toEqual([...names].sort()); - expect((await list(ADMIN, projectB.id)).skills.map(s => s.name)).not.toContain('release-notes'); - expect(await auditActions()).toEqual([ - { action: 'factory.skill.created', project: projectA.id, targets: [{ type: 'skill', id: 'release-notes' }] }, - ]); - }); - - it('creates a skill with an all-digit name when the SKILL.md quotes it, as the settings editor writes it', async () => { - const { projectA, create, skill } = await setup(); - const response = await create( - ADMIN, - projectA.id, - '123', - '---\nname: "123"\ndescription: "Numbered"\n---\n\n# 123\n', - ); - expect(response.status).toBe(201); - expect(await skill(ADMIN, projectA.id, '123')).toMatchObject({ origin: 'project', description: 'Numbered' }); - }); - - it('answers a create or save with the skill it stored, even when another admin deletes it at once', async () => { - let deleteAfterAudit: (() => Promise) | undefined; - const { seed, projectA, create, save } = await setup({ - afterAudit: async () => void (await deleteAfterAudit?.()), - }); - const scope = { orgId: 'org-1', projectId: projectA.id, skillName: 'release-notes' }; - deleteAfterAudit = () => seed.skillOverrides.delete(scope); - - const created = await create(ADMIN, projectA.id, 'release-notes', releaseNotes('# Notes')); - expect(created.status).toBe(201); - expect(((await created.json()) as { skill: unknown }).skill).toMatchObject({ - name: 'release-notes', - content: '# Notes', - origin: 'project', - }); - expect(await seed.skillOverrides.get(scope)).toBeNull(); - - deleteAfterAudit = undefined; - await create(ADMIN, projectA.id, 'release-notes', releaseNotes('# Notes')); - deleteAfterAudit = () => seed.skillOverrides.delete(scope); - const saved = await save(ADMIN, projectA.id, 'release-notes', releaseNotes('# Shorter')); - expect(saved.status).toBe(200); - expect(((await saved.json()) as { skill: unknown }).skill).toMatchObject({ - content: '# Shorter', - origin: 'project', - }); - }); - - it('updates a created skill, then deletes it', async () => { - const { projectA, create, save, revert, list, auditActions } = await setup(); - expect((await create(ADMIN, projectA.id, 'release-notes', releaseNotes('# Notes'))).status).toBe(201); - - const updated = await save(ADMIN, projectA.id, 'release-notes', releaseNotes('# Shorter notes')); - expect(updated.status).toBe(200); - expect(((await updated.json()) as { skill: unknown }).skill).toMatchObject({ - content: '# Shorter notes', - origin: 'project', - }); - - const deleted = await revert(ADMIN, projectA.id, 'release-notes'); - expect(deleted.status).toBe(200); - expect(await deleted.json()).toEqual({ skill: null }); - expect((await list(ADMIN, projectA.id)).skills.map(s => s.name)).not.toContain('release-notes'); - // Gone, so neither a save nor a second delete finds it. - expect((await save(ADMIN, projectA.id, 'release-notes', releaseNotes('# Again'))).status).toBe(404); - expect((await revert(ADMIN, projectA.id, 'release-notes')).status).toBe(404); - expect((await auditActions()).map(event => event.action).sort()).toEqual([ - 'factory.skill.created', - 'factory.skill.deleted', - 'factory.skill.updated', - ]); - }); - - it('refuses a name an app skill or another created skill already has', async () => { - writeLocalSkill('deploy-notes', '---\nname: deploy-notes\ndescription: Folder skill\n---\n\n# Folder\n'); - const { projectA, projectB, create, skill } = await setup(); - const builtIn = await create(ADMIN, projectA.id, 'factory-plan', editedPlan('# Not a new skill')); - expect(builtIn.status).toBe(409); - expect(await builtIn.json()).toEqual({ - error: 'skill_exists', - message: 'A skill named "factory-plan" already exists. Edit it instead.', - }); - const folder = '---\nname: deploy-notes\ndescription: Mine\n---\n\n# Mine\n'; - expect((await create(ADMIN, projectA.id, 'deploy-notes', folder)).status).toBe(409); - - expect((await create(ADMIN, projectA.id, 'release-notes', releaseNotes('# First'))).status).toBe(201); - expect((await create(ADMIN, projectA.id, 'release-notes', releaseNotes('# Second'))).status).toBe(409); - expect((await skill(ADMIN, projectA.id, 'release-notes')).content).toBe('# First'); - // Another project may use the name. - expect((await create(ADMIN, projectB.id, 'release-notes', releaseNotes('# Other'))).status).toBe(201); - expect((await skill(ADMIN, projectA.id, 'factory-plan')).edited).toBeUndefined(); - }); - - it('creates one skill when two admins create the same name at once', async () => { - const { projectA, create, seed } = await setup(); - const statuses = await Promise.all( - ['# One', '# Two', '# Three'].map(body => create(ADMIN, projectA.id, 'release-notes', releaseNotes(body))), - ).then(responses => responses.map(response => response.status).sort()); - expect(statuses).toEqual([201, 409, 409]); - expect(await seed.skillOverrides.list({ orgId: 'org-1', projectId: projectA.id })).toHaveLength(1); - }); - - it('rejects a skill the runtime could not load, or a name that is not a skill name', async () => { - const { projectA, create, seed } = await setup(); - const cases = [ - [ - 'release-notes', - '---\nname: other-notes\ndescription: Renamed\n---\n\n# Notes\n', - /must match directory name/, - ], - ['release-notes', '---\nname: release-notes\n---\n\n# Notes\n', /description/i], - ['Release Notes', '---\nname: Release Notes\ndescription: x\n---\n\n# Notes\n', /Invalid/i], - ['release-notes', '', /Too small/], - ] as const; - for (const [name, content, message] of cases) { - const response = await create(ADMIN, projectA.id, name, content); - expect(response.status).toBe(400); - const body = (await response.json()) as { error: string; message: string }; - expect(body.error).toBe('invalid_skill'); - expect(body.message).toMatch(message); - } - expect(await seed.skillOverrides.list({ orgId: 'org-1', projectId: projectA.id })).toEqual([]); - }); - - it('refuses creation from members who are not org admins and in other organizations', async () => { - const { projectA, elsewhere, create, seed, auditActions } = await setup(); - const member = await create(MEMBER, projectA.id, 'release-notes', releaseNotes('# Notes')); - expect(member.status).toBe(403); - expect(await member.json()).toEqual({ - error: 'forbidden', - message: 'Organization administrator access is required to create skills.', - }); - expect((await create(ADMIN, elsewhere.id, 'release-notes', releaseNotes('# Notes'))).status).toBe(404); - expect((await create(ADMIN, 'not-a-uuid', 'release-notes', releaseNotes('# Notes'))).status).toBe(404); - expect(await seed.skillOverrides.list({ orgId: 'org-1', projectId: projectA.id })).toEqual([]); - expect(await auditActions()).toEqual([]); - }); - - it('treats a created skill as an edit once the app ships a skill of the same name', async () => { - const { projectA, create, revert, skill } = await setup(); - expect((await create(ADMIN, projectA.id, 'release-notes', releaseNotes('# Ours'))).status).toBe(201); - - writeLocalSkill('release-notes', releaseNotes('# From the app')); - expect(await skill(ADMIN, projectA.id, 'release-notes')).toMatchObject({ - origin: 'folder', - content: '# Ours', - edited: { updatedBy: ADMIN.workosId }, - originalChanged: true, - }); - - // Reverting drops the project's text for the app's skill. - const reverted = await revert(ADMIN, projectA.id, 'release-notes'); - expect(((await reverted.json()) as { skill: unknown }).skill).toMatchObject({ - origin: 'folder', - content: '# From the app', - }); - }); - - it('creates over an edit whose skill the app no longer has', async () => { - writeLocalSkill('release-notes', releaseNotes('# From the app')); - const { projectA, save, create, skill } = await setup(); - expect((await save(ADMIN, projectA.id, 'release-notes', releaseNotes('# Edited'))).status).toBe(200); - rmSync(join(projectDir, 'factory-skills', 'release-notes'), { recursive: true }); - - expect((await create(ADMIN, projectA.id, 'release-notes', releaseNotes('# Ours now'))).status).toBe(201); - expect(await skill(ADMIN, projectA.id, 'release-notes')).toMatchObject({ - origin: 'project', - content: '# Ours now', - }); - }); - }); it("serves an admin's edit to its project only, with who edited it", async () => { const { projectA, projectB, save, list, skill, auditActions } = await setup(); diff --git a/mastracode/factory/src/routes/skills.ts b/mastracode/factory/src/routes/skills.ts index 1cb6f693e9e..9e0d1bb1c9f 100644 --- a/mastracode/factory/src/routes/skills.ts +++ b/mastracode/factory/src/routes/skills.ts @@ -6,19 +6,13 @@ import { registerApiRoute } from '@mastra/core/server'; import type { InlineSkill } from '@mastra/core/skills'; import type { Context } from 'hono'; -import { - createdSkillInfo, - hashSkillContent, - listFactorySkills, - originalSkillInfo, - readFactorySkillOriginals, -} from '../skills/catalog.js'; +import { hashSkillContent, listFactorySkills, readFactorySkillOriginals } from '../skills/catalog.js'; import { formatSkillMessage, resolveSkillInvocation, SkillInvocationError } from '../skills/service.js'; import type { AuditEmitter } from '../storage/domains/audit/domain.js'; import type { FactoryProjectsStorage } from '../storage/domains/projects/base.js'; import type { SkillOverridesStorage } from '../storage/domains/skill-overrides/base.js'; import type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js'; -import { FACTORY_ROUTE_CONTRACTS, skillCreateBodySchema, skillOverrideSaveRequestSchema } from './contracts.js'; +import { FACTORY_ROUTE_CONTRACTS, skillOverrideSaveRequestSchema } from './contracts.js'; import type { RouteDependencies } from './route.js'; import { loose, Route } from './route.js'; @@ -51,10 +45,7 @@ export interface SkillRoutesDeps extends RouteDependencies { /** Per-project skill edits. Without it the catalog lists originals only and edit routes are not served. */ overrides?: { projects: Pick; - storage: Pick< - SkillOverridesStorage, - 'ensureReady' | 'list' | 'get' | 'upsert' | 'create' | 'updateCreated' | 'delete' - >; + storage: Pick; audit: AuditEmitter; }; } @@ -148,6 +139,12 @@ export class SkillRoutes extends Route { return !auth.enabled() || (await auth.isOrganizationAdmin(c, orgId)); } + async #catalogEntry(scope: { orgId: string; projectId: string }, name: string) { + const { overrides, skills } = this.deps; + const edits = overrides ? await overrides.storage.list(scope) : []; + return (await listFactorySkills(skills, edits)).find(skill => skill.name === name); + } + routes(): ApiRoute[] { const { controllerId, controller, authorizeSessionAddress: customAuthorize } = this.deps; const authorize = @@ -235,27 +232,23 @@ export class SkillRoutes extends Route { ); } const name = path.data.name; + const original = (await readFactorySkillOriginals(this.deps.skills)).get(name); + if (!original) return c.json({ error: 'not_found', message: `Skill "${name}" not found.` }, 404); const scope = { orgId: access.orgId, projectId: access.projectId, skillName: name }; await overrides!.storage.ensureReady(); - const original = (await readFactorySkillOriginals(this.deps.skills)).get(name); - // Without an original, the name can only be a skill this project created. - if (!original && (await overrides!.storage.get(scope))?.kind !== 'created') { - return c.json({ error: 'not_found', message: `Skill "${name}" not found.` }, 404); - } if (revert) { if (await overrides!.storage.delete(scope)) { await overrides!.audit.emit({ context: c, input: { - action: original ? 'factory.skill.reverted' : 'factory.skill.deleted', + action: 'factory.skill.reverted', targets: [{ type: 'skill', id: name }], factoryProjectId: access.projectId, }, }); } - // The response describes what the delete left, not a reread another write could change. - return c.json({ skill: original ? originalSkillInfo(name, original) : null }); + return c.json({ skill: await this.#catalogEntry(access, name) }); } let body: unknown; @@ -274,72 +267,22 @@ export class SkillRoutes extends Route { 400, ); } - const write = { ...scope, content: request.data.content, updatedBy: access.userId }; - // A created skill is only updated while it exists, so a save racing a delete doesn't bring it back. - const saved = original - ? await overrides!.storage.upsert({ ...write, baseHash: hashSkillContent(original.raw), kind: 'edit' }) - : await overrides!.storage.updateCreated(write); - if (!saved) return c.json({ error: 'not_found', message: `Skill "${name}" not found.` }, 404); + await overrides!.storage.upsert({ + ...scope, + content: request.data.content, + baseHash: hashSkillContent(original.raw), + updatedBy: access.userId, + }); await overrides!.audit.emit({ context: c, input: { action: 'factory.skill.updated', targets: [{ type: 'skill', id: name }], factoryProjectId: access.projectId, - metadata: { origin: original?.origin ?? 'project' }, + metadata: { origin: original.origin }, }, }); - return c.json({ skill: original ? originalSkillInfo(name, original, saved) : createdSkillInfo(saved) }); - }; - - const handleSkillCreate = async (context: unknown) => { - const c = loose(context); - const { overrides } = this.deps; - const path = FACTORY_ROUTE_CONTRACTS.skillCreate.pathSchema.safeParse({ id: c.req.param('id') }); - if (!path.success) return c.json({ error: 'Project not found' }, 404); - const access = await this.#projectAccess(c, path.data.id); - if ('response' in access) return access.response; - if (!(await this.#canEdit(c, access.orgId))) { - return c.json( - { error: 'forbidden', message: 'Organization administrator access is required to create skills.' }, - 403, - ); - } - - let body: unknown; - try { - body = await c.req.json(); - } catch { - return c.json({ error: 'invalid_request', message: 'Invalid JSON body.' }, 400); - } - const request = skillCreateBodySchema.safeParse(body); - if (!request.success) { - return c.json( - { error: 'invalid_skill', message: request.error.issues.map(issue => issue.message).join('\n') }, - 400, - ); - } - const { name, content } = request.data; - const exists = { error: 'skill_exists', message: `A skill named "${name}" already exists. Edit it instead.` }; - if ((await readFactorySkillOriginals(this.deps.skills)).has(name)) return c.json(exists, 409); - await overrides!.storage.ensureReady(); - const created = await overrides!.storage.create({ - orgId: access.orgId, - projectId: access.projectId, - skillName: name, - content, - updatedBy: access.userId, - }); - if (!created) return c.json(exists, 409); - await overrides!.audit.emit({ - context: c, - input: { - action: 'factory.skill.created', - targets: [{ type: 'skill', id: name }], - factoryProjectId: access.projectId, - }, - }); - return c.json({ skill: createdSkillInfo(created) }, 201); + return c.json({ skill: await this.#catalogEntry(access, name) }); }; return [ @@ -350,11 +293,6 @@ export class SkillRoutes extends Route { }), ...(this.deps.overrides ? [ - registerApiRoute(FACTORY_ROUTE_CONTRACTS.skillCreate.path, { - method: FACTORY_ROUTE_CONTRACTS.skillCreate.method, - requiresAuth: false, - handler: context => handleSkillCreate(context), - }), registerApiRoute(FACTORY_ROUTE_CONTRACTS.skillOverrideSave.path, { method: FACTORY_ROUTE_CONTRACTS.skillOverrideSave.method, requiresAuth: false, diff --git a/mastracode/factory/src/run-error.test.ts b/mastracode/factory/src/run-error.test.ts index 15710b9254a..eca019b38b3 100644 --- a/mastracode/factory/src/run-error.test.ts +++ b/mastracode/factory/src/run-error.test.ts @@ -1,3 +1,4 @@ +import { toPersistedErrorIdentity } from '@mastra/core/error'; import { describe, expect, it } from 'vitest'; import { describeRunError } from './run-error'; @@ -75,6 +76,78 @@ describe('describeRunError', () => { }); }); + describe('Mastra Gateway v1 billing refusals', () => { + // The v1 reply as the gateway sends it: a billing `type`, a `help_url`, and no `code`. The live + // error is called without a gateway URL or `mastra/` model, so only the reply can identify it. + const v1Refusal = (error: Record) => ({ + name: 'AI_APICallError', + message: error.message!, + statusCode: 402, + responseBody: JSON.stringify({ error }), + requestBodyValues: { model: 'anthropic/claude-opus-4-5' }, + }); + const outOfCredits = { + message: "You don't have inference credits left. Add credits at https://projects.mastra.ai/", + type: 'billing_error', + help_url: 'https://projects.mastra.ai/', + }; + const outOfMemoryTokens = { + message: "You don't have memory tokens left. Add credits or upgrade your plan at https://projects.mastra.ai/", + type: 'billing_error', + help_url: 'https://projects.mastra.ai/', + }; + const spendLimit = { + message: 'Your organization reached its monthly Gateway spend limit. Raise it at https://projects.mastra.ai/', + type: 'spend_limit_reached', + help_url: 'https://projects.mastra.ai/', + }; + + it.each([ + ['inference credits', outOfCredits], + ['memory tokens', outOfMemoryTokens], + ])('offers credits when %s run out, live and rebuilt from history', (_what, error) => { + const live = v1Refusal(error); + for (const failure of [live, toPersistedErrorIdentity(live)]) { + expect(describeRunError(failure)).toMatchObject({ + title: 'Out of Mastra Gateway credits', + recoveries: ['credits', 'continue', 'model'], + }); + } + }); + + it('sends a monthly spend limit to an organization admin instead of offering credits', () => { + const live = v1Refusal(spendLimit); + for (const failure of [live, toPersistedErrorIdentity(live)]) { + expect(describeRunError(failure)).toMatchObject({ + title: 'Mastra Gateway spend limit reached', + recoveries: ['model'], + }); + } + }); + + it('still recognizes the older replies that linked to the gateway host', () => { + const olderSpendLimit = v1Refusal({ + message: 'Your organization reached its monthly Gateway spend limit. Raise it at https://gateway.mastra.ai/', + type: 'spend_limit_reached', + help_url: 'https://gateway.mastra.ai/', + }); + expect(describeRunError(toPersistedErrorIdentity(olderSpendLimit))).toMatchObject({ + title: 'Mastra Gateway spend limit reached', + }); + }); + + it.each([ + ['a billing type with a help link elsewhere', { ...outOfCredits, help_url: 'https://billing.example.com/' }], + ['a dashboard link in its text only', { message: outOfCredits.message, type: 'insufficient_quota' }], + ['a look-alike help host', { ...outOfCredits, help_url: 'https://projects.mastra.ai.example.com/' }], + ])("keeps another provider's 402 with %s a provider quota error", (_shape, error) => { + expect(describeRunError(toPersistedErrorIdentity(v1Refusal(error)))).toMatchObject({ + title: 'Provider quota exhausted', + recoveries: ['credentials', 'model'], + }); + }); + }); + it('recognizes the gateway by the host it called when its reply names no gateway', () => { const outOfCredits = { name: 'AI_APICallError', @@ -113,6 +186,392 @@ describe('describeRunError', () => { expect(describeRunError(outOfCredits)).toMatchObject({ title: 'Provider quota exhausted' }); }); + describe('Mastra Gateway v2 refusals', () => { + // What v2 sends for a reason code it has no special reply for, and what history keeps of it: + // no request URL, and the model the request named without the `mastra/` prefix. + const gatewayRefusal = (status: number, code: string, message = code) => { + const responseBody = JSON.stringify({ error: { type: 'gateway_error', code, message } }); + const live = { + name: 'AI_APICallError', + message, + statusCode: status, + responseBody, + requestBodyValues: { model: 'anthropic/claude-opus-4-5' }, + }; + return toPersistedErrorIdentity(live); + }; + + it('keeps no request URL or gateway prefix in the saved part these cases are rebuilt from', () => { + const saved = gatewayRefusal(402, 'insufficient_credit'); + expect(saved).not.toHaveProperty('url'); + expect(saved).toMatchObject({ + modelId: 'anthropic/claude-opus-4-5', + codes: expect.arrayContaining(['gateway_error', 'insufficient_credit']), + }); + }); + + it('offers to add credits when the organization is out of credits', () => { + expect(describeRunError(gatewayRefusal(402, 'insufficient_credit'))).toEqual({ + title: 'Out of Mastra Gateway credits', + message: + 'Your organization has no gateway credits left. Add credits, then continue the run, or choose another model.', + recoveries: ['credits', 'continue', 'model'], + model: 'anthropic/claude-opus-4-5', + }); + }); + + it('names the organization budget, and still offers credits, which lift a starting budget', () => { + const description = describeRunError(gatewayRefusal(402, 'organization_budget_exhausted')); + expect(description).toMatchObject({ + title: 'Mastra Gateway budget reached', + recoveries: ['credits', 'continue', 'model'], + }); + expect(description.message).toContain('used its Mastra Gateway budget'); + expect(description.message).toContain('adding credits lifts it'); + }); + + it.each(['organization_budget_insufficient', 'organization_budget_unbounded_request'])( + 'says a %s request needs more than the budget has left', + code => { + const description = describeRunError(gatewayRefusal(402, code)); + expect(description).toMatchObject({ + title: 'Mastra Gateway budget reached', + recoveries: ['credits', 'continue', 'model'], + }); + expect(description.message).toContain('This request needs more than your organization has left'); + }, + ); + + it.each(['key_budget_exhausted', 'spend_limit_reached'])( + 'sends %s to an organization admin, without offering credits that would not help', + code => { + const description = describeRunError(gatewayRefusal(402, code)); + expect(description).toMatchObject({ title: 'Mastra Gateway spend limit reached', recoveries: ['model'] }); + expect(description.message).toContain('Ask an organization admin to raise the limit'); + }, + ); + + it('refuses usage the billing plan does not cover, without offering credits', () => { + expect(describeRunError(gatewayRefusal(402, 'billing_overage_unsupported'))).toMatchObject({ + title: 'Usage not covered by the billing plan', + recoveries: ['model'], + }); + }); + + it('keeps offering credits for a 402 code it does not know yet', () => { + expect(describeRunError(gatewayRefusal(402, 'some_new_billing_code'))).toMatchObject({ + title: 'Out of Mastra Gateway credits', + recoveries: ['credits', 'continue', 'model'], + }); + }); + + it('quotes the sentence the gateway wrote instead of the code', () => { + const description = describeRunError( + gatewayRefusal(402, 'spend_limit_reached', 'This key reached its monthly spend limit of $50.'), + ); + expect(description.message).toBe( + 'This key reached its monthly spend limit of $50. Ask an organization admin to raise the limit, or choose another model.', + ); + }); + + it.each(['no_eligible_route', 'model_not_allowed'])( + 'offers another model, not credentials, when routing policy refuses with %s', + code => { + expect(describeRunError(gatewayRefusal(403, code))).toMatchObject({ + title: 'Model not available through the Mastra Gateway', + recoveries: ['model'], + }); + }, + ); + + it.each([ + [413, 'context_too_large'], + [422, 'context_unaccountable'], + ])('treats a %i %s as a conversation over the model limit', (status, code) => { + expect(describeRunError(gatewayRefusal(status, code))).toMatchObject({ + title: 'Conversation exceeds the model’s limit', + recoveries: ['model', 'new_session'], + }); + }); + + it('reads the code from a Messages route reply, which repeats it as the message', () => { + const messagesReply = { + name: 'AI_APICallError', + message: 'organization_budget_exhausted', + statusCode: 402, + responseBody: JSON.stringify({ + type: 'error', + error: { type: 'gateway_error', message: 'organization_budget_exhausted' }, + }), + }; + expect(describeRunError(toPersistedErrorIdentity(messagesReply))).toMatchObject({ + title: 'Mastra Gateway budget reached', + }); + }); + + it("describes the gateway's own rate limit as the key's or organization's, not the provider account's", () => { + const limited = { + name: 'AI_APICallError', + message: 'Gateway key requests limit exceeded. Retry in 12s.', + statusCode: 429, + url: 'https://gateway-api.mastra.ai/v1/chat/completions', + responseBody: JSON.stringify({ + error: { + type: 'rate_limit_error', + code: 'rate_limit_exceeded', + message: 'Gateway key requests limit exceeded. Retry in 12s.', + }, + }), + }; + expect(describeRunError(limited)).toEqual({ + title: 'Mastra Gateway rate limit reached', + message: 'Gateway key requests limit exceeded. Retry in 12s. Continue once it resets, or choose another model.', + recoveries: ['continue', 'model'], + model: undefined, + }); + }); + + it('recognizes a gateway at the configured base URL', () => { + const staging = { + name: 'AI_APICallError', + message: 'Payment required', + statusCode: 402, + url: 'http://localhost:8787/v1/chat/completions', + }; + expect(describeRunError(staging)).toMatchObject({ title: 'Provider quota exhausted' }); + expect(describeRunError(staging, { gatewayBaseUrl: 'http://localhost:8787' })).toMatchObject({ + title: 'Out of Mastra Gateway credits', + }); + expect(describeRunError(staging, { gatewayBaseUrl: 'http://localhost:9999' })).toMatchObject({ + title: 'Provider quota exhausted', + }); + expect(describeRunError(staging, { gatewayBaseUrl: 'https://localhost:8787' })).toMatchObject({ + title: 'Provider quota exhausted', + }); + }); + + describe('a code another provider can also send', () => { + // A direct provider's saved error: no gateway type, no request origin, no `mastra/` model. + const direct = (status: number, code: string) => + toPersistedErrorIdentity({ + name: 'AI_APICallError', + message: 'Refused.', + statusCode: status, + responseBody: JSON.stringify({ error: { type: 'invalid_request_error', code, message: 'Refused.' } }), + requestBodyValues: { model: 'acme/model-1' }, + }); + + it.each([ + [403, 'model_not_allowed', 'Provider access failed'], + [402, 'insufficient_credit', 'Provider quota exhausted'], + [402, 'spend_limit_reached', 'Provider quota exhausted'], + ])('keeps a direct provider’s %i %s its own refusal', (status, code, title) => { + expect(describeRunError(direct(status, code))).toMatchObject({ title, recoveries: ['credentials', 'model'] }); + }); + + it('names the gateway when the saved request origin is the gateway’s', () => { + const saved = { ...direct(403, 'model_not_allowed'), requestOrigin: 'https://gateway-api.mastra.ai' }; + expect(describeRunError(saved)).toMatchObject({ title: 'Model not available through the Mastra Gateway' }); + }); + + it('names the gateway from saved codes alone only for a code no one else sends', () => { + const savedCodes = (codes: string[]) => ({ + name: 'AI_APICallError', + message: 'Refused.', + statusCode: 402, + codes, + }); + expect(describeRunError(savedCodes(['insufficient_credit']))).toMatchObject({ + title: 'Provider quota exhausted', + }); + expect(describeRunError(savedCodes(['key_budget_exhausted']))).toMatchObject({ + title: 'Mastra Gateway spend limit reached', + }); + }); + }); + + it('bounds a long gateway sentence before showing it', () => { + const long = 'The budget is spent. '.repeat(60).trim(); + const { message } = describeRunError(gatewayRefusal(402, 'spend_limit_reached', long)); + expect(message.length).toBeLessThan(600); + expect(message).toContain('…'); + }); + + it.each([ + [401, 'some_new_key_reason'], + [403, 'identity_policy_denied'], + [403, 'byok_connection_inactive'], + ])('keeps the credential recovery for a %i %s refusal of the key or connection', (status, code) => { + expect(describeRunError(gatewayRefusal(status, code))).toMatchObject({ + title: 'Provider access failed', + recoveries: ['credentials', 'model'], + }); + }); + + it('offers another model when no route in the key’s region serves it', () => { + expect(describeRunError(gatewayRefusal(403, 'no_route_in_region'))).toMatchObject({ + title: 'Model not available through the Mastra Gateway', + recoveries: ['model'], + }); + }); + + it('names the provider behind the gateway when it is the one limiting requests', () => { + const limited = toPersistedErrorIdentity({ + name: 'AI_APICallError', + message: 'Upstream provider rate limit reached. Try again shortly.', + statusCode: 429, + responseBody: JSON.stringify({ + error: { + type: 'rate_limit_error', + code: 'provider_rate_limited', + message: 'Upstream provider rate limit reached. Try again shortly.', + }, + }), + }); + expect(describeRunError(limited)).toMatchObject({ + title: 'Model provider rate limit reached', + recoveries: ['continue', 'model'], + }); + }); + + it.each(['key_budget_capacity_held', 'organization_budget_capacity_held'])( + 'asks to continue in a few seconds when %s', + code => { + expect(describeRunError(gatewayRefusal(429, code))).toMatchObject({ + title: 'Mastra Gateway budget busy', + recoveries: ['continue', 'model'], + }); + }, + ); + + it('recognizes the gateway from the saved codes alone when the body is gone', () => { + const withoutBody = { + name: 'AI_APICallError', + message: 'key_budget_exhausted', + statusCode: 402, + codes: ['gateway_error', 'key_budget_exhausted'], + }; + expect(describeRunError(withoutBody)).toMatchObject({ title: 'Mastra Gateway spend limit reached' }); + }); + + it.each([ + [ + 'an OpenAI-style', + { type: 'requests', code: 'rate_limit_exceeded', message: 'Rate limit reached for requests' }, + ], + ['an uncoded', { message: 'rate limited', type: 'rate_limit_error', code: null }], + ])( + "names the provider behind the gateway, not the session's credential, for %s 429 it relayed", + (_shape, error) => { + const relayed = { + name: 'AI_APICallError', + message: error.message, + statusCode: 429, + url: 'https://gateway-api.mastra.ai/v1/chat/completions', + responseBody: JSON.stringify({ error }), + }; + expect(describeRunError(relayed)).toEqual({ + title: 'Model provider rate limit reached', + message: + 'The model provider behind the Mastra Gateway is limiting requests. Continue shortly, or choose another model.', + recoveries: ['continue', 'model'], + model: undefined, + }); + }, + ); + + describe('a saved 429, rebuilt from history', () => { + // History keeps no request URL. Core saves the request's origin as `requestOrigin`; a part + // saved by an older core has none, which is what leaving the argument out stands for. + const saved429 = (url: string, error: Record, requestOrigin?: string) => { + const { requestOrigin: _recorded, ...part } = toPersistedErrorIdentity({ + name: 'AI_APICallError', + message: String(error.message), + statusCode: 429, + url, + responseBody: JSON.stringify({ error }), + }) as Record; + return { ...part, ...(requestOrigin ? { requestOrigin } : {}) }; + }; + const gatewayLimit = { + type: 'rate_limit_error', + code: 'rate_limit_exceeded', + message: 'Gateway key requests limit exceeded. Retry in 12s.', + }; + const relayedLimit = { message: 'rate limited', type: 'rate_limit_error', code: null }; + + it("names the gateway's own limit from the origin core saves with the error", () => { + const saved = toPersistedErrorIdentity({ + name: 'AI_APICallError', + message: gatewayLimit.message, + statusCode: 429, + url: 'https://gateway-api.mastra.ai/v1/chat/completions', + responseBody: JSON.stringify({ error: gatewayLimit }), + }); + expect(saved).toMatchObject({ requestOrigin: 'https://gateway-api.mastra.ai' }); + expect(saved).not.toHaveProperty('url'); + expect(describeRunError(saved)).toMatchObject({ title: 'Mastra Gateway rate limit reached' }); + }); + + it('stays a provider rate limit without a request origin, since its type and code are shared', () => { + const saved = saved429('https://gateway-api.mastra.ai/v1/chat/completions', gatewayLimit); + expect(saved).not.toHaveProperty('url'); + expect(describeRunError(saved)).toMatchObject({ title: 'Provider rate limit reached' }); + }); + + it("names the gateway's own limit when the request went to the production gateway", () => { + const saved = saved429( + 'https://gateway-api.mastra.ai/v1/chat/completions', + gatewayLimit, + 'https://gateway-api.mastra.ai', + ); + expect(describeRunError(saved)).toMatchObject({ + title: 'Mastra Gateway rate limit reached', + recoveries: ['continue', 'model'], + }); + }); + + it('names the provider behind the gateway for a limit the gateway relayed', () => { + const saved = saved429( + 'https://gateway-api.mastra.ai/v1/chat/completions', + relayedLimit, + 'https://gateway-api.mastra.ai', + ); + expect(describeRunError(saved)).toMatchObject({ + title: 'Model provider rate limit reached', + recoveries: ['continue', 'model'], + }); + }); + + it('recognizes a non-production gateway only when the configured origin is passed', () => { + const saved = saved429('http://127.0.0.1:4180/v1/chat/completions', gatewayLimit, 'http://127.0.0.1:4180'); + expect(describeRunError(saved)).toMatchObject({ title: 'Provider rate limit reached' }); + expect(describeRunError(saved, { gatewayBaseUrl: 'http://127.0.0.1:4180' })).toMatchObject({ + title: 'Mastra Gateway rate limit reached', + }); + }); + }); + + it('keeps an Anthropic 403 a credential problem', () => { + const anthropicDenied = { + name: 'AI_APICallError', + message: 'Your API key does not have permission to use the specified resource.', + statusCode: 403, + responseBody: JSON.stringify({ + type: 'error', + error: { + type: 'permission_error', + message: 'Your API key does not have permission to use the specified resource.', + }, + }), + }; + expect(describeRunError(anthropicDenied)).toMatchObject({ + title: 'Provider access failed', + recoveries: ['credentials', 'model'], + }); + }); + }); + it('quotes a plain-text body the provider sent instead of JSON', () => { const textBody = { name: 'AI_APICallError', diff --git a/mastracode/factory/src/run-error.ts b/mastracode/factory/src/run-error.ts index f0625e653a5..802061e163b 100644 --- a/mastracode/factory/src/run-error.ts +++ b/mastracode/factory/src/run-error.ts @@ -25,24 +25,39 @@ const UNEXPECTED_ERROR = 'An unexpected error stopped the run. Copy the error de const NO_REASON_AVAILABLE = 'The provider rejected the request. A specific reason isn’t available here. Copy the error details and check the server logs.'; -export function describeRunError(error: RunErrorIdentity): RunErrorDescription { - return { ...explainRunError(error), model: providerModelId(error) }; +export interface DescribeRunErrorOptions { + /** + * The Mastra Gateway base URL this server sends requests to. Requests to its host are recognized as + * gateway replies, so a staging, local or self-hosted gateway is handled like the production one. + */ + gatewayBaseUrl?: string; } -function explainRunError(error: RunErrorIdentity): Omit { +export function describeRunError(error: RunErrorIdentity, options: DescribeRunErrorOptions = {}): RunErrorDescription { + return { ...explainRunError(error, options), model: providerModelId(error) }; +} + +const CONTEXT_OVERFLOW: Omit = { + title: 'Conversation exceeds the model’s limit', + message: 'Choose a model with a larger context window or start a new session with a shorter prompt.', + recoveries: ['model', 'new_session'], +}; + +function explainRunError( + error: RunErrorIdentity, + options: DescribeRunErrorOptions, +): Omit { if (error.name === PROVIDER_AUTH_REQUIRED_ERROR) { return { title: 'Provider sign-in required', message: error.message, recoveries: ['credentials', 'model'] }; } - switch (classifyProviderError(error)) { + const kind = classifyProviderError(error); + const gateway = gatewayReply(error); + if (isMastraGatewayError(error, gateway, options)) { + const refusal = explainGatewayRefusal(kind, gateway); + if (refusal) return refusal; + } + switch (kind) { case 'quota': - if (isMastraGatewayError(error)) { - return { - title: 'Out of Mastra Gateway credits', - message: - 'Your organization has no gateway credits left. Add credits, then continue the run, or choose another model.', - recoveries: ['credits', 'continue', 'model'], - }; - } return { title: 'Provider quota exhausted', message: afterProviderReason( @@ -58,11 +73,7 @@ function explainRunError(error: RunErrorIdentity): Omit, + reply: GatewayReply | undefined, +): Omit | undefined { + const code = reply?.code; + const said = (fallback: string, next: string) => `${(reply?.message ?? fallback).replace(/\.?$/, '.')} ${next}`; + if (code && GATEWAY_CONTEXT_OVERFLOW.has(code)) return CONTEXT_OVERFLOW; + if (code === ORGANIZATION_BUDGET_EXHAUSTED) { + return { + title: 'Mastra Gateway budget reached', + message: said( + `Your organization has used its Mastra Gateway budget. ${STARTING_BUDGET} If your organization has already added credits, an organization admin can raise its spend limit`, + ADD_CREDITS_THEN_CONTINUE, + ), + recoveries: ['credits', 'continue', 'model'], + }; + } + if (code && ORGANIZATION_BUDGET_SHORT.has(code)) { + return { + title: 'Mastra Gateway budget reached', + message: said( + `This request needs more than your organization has left in its Mastra Gateway budget. ${STARTING_BUDGET}`, + ADD_CREDITS_THEN_CONTINUE, + ), + recoveries: ['credits', 'continue', 'model'], + }; + } + if (code && SPEND_LIMIT_REACHED.has(code)) { + return { + title: 'Mastra Gateway spend limit reached', + message: said( + 'A spend limit set on this gateway key or your organization was reached, and adding credits does not raise it', + 'Ask an organization admin to raise the limit, or choose another model.', + ), + recoveries: ['model'], + }; + } + if (code === BILLING_OVERAGE_UNSUPPORTED) { + return { + title: 'Usage not covered by the billing plan', + message: said( + 'Your organization’s billing plan does not allow this Mastra Gateway usage', + 'Choose another model, or ask an organization admin to review the plan.', + ), + recoveries: ['model'], + }; + } + if (kind === 'quota') { + // A credit refusal from v1, or a v2 code this version does not know yet. + return { + title: 'Out of Mastra Gateway credits', + message: OUT_OF_CREDITS.has(code ?? '') + ? said('Your organization has no gateway credits left', ADD_CREDITS_THEN_CONTINUE) + : `Your organization has no gateway credits left. ${ADD_CREDITS_THEN_CONTINUE}`, + recoveries: ['credits', 'continue', 'model'], + }; + } + // Any other refusal of the key or connection keeps the credential recovery. + if (kind === 'auth' && code !== undefined && ROUTE_REFUSED.has(code)) { + return { + title: 'Model not available through the Mastra Gateway', + message: said( + 'The Mastra Gateway has no route your organization may use for this model or feature', + 'Choose another model for this session.', + ), + recoveries: ['model'], + }; + } + if (kind !== 'rate_limited') return undefined; + if (code === UPSTREAM_RATE_LIMITED) { + return { + title: 'Model provider rate limit reached', + message: said( + 'The model provider behind the Mastra Gateway is limiting requests', + 'Continue shortly, or choose another model.', + ), + recoveries: ['continue', 'model'], + }; + } + if (code && BUDGET_CAPACITY_HELD.has(code)) { + return { + title: 'Mastra Gateway budget busy', + message: said( + 'Requests still in flight hold the rest of the gateway budget for this key or organization', + 'Continue in a few seconds, or choose another model.', + ), + recoveries: ['continue', 'model'], + }; + } + // The gateway's limit reply pairs these two; a provider reply relayed through it names its own type. + const gatewayLimit = code === GATEWAY_RATE_LIMITED && reply?.type === 'rate_limit_error'; + if (gatewayLimit || reply?.type === 'gateway_error') { + // The gateway's own limit on the key or organization, not the provider account's. + return { + title: 'Mastra Gateway rate limit reached', + message: said( + 'The gateway’s rate limit for this key or organization was reached', + 'Continue once it resets, or choose another model.', + ), + recoveries: ['continue', 'model'], + }; + } + // A provider's own limit relayed through the gateway: the provider account is the gateway's route, + // not one of this session's credentials, and the relayed text names no one. + return { + title: 'Model provider rate limit reached', + message: + 'The model provider behind the Mastra Gateway is limiting requests. Continue shortly, or choose another model.', + recoveries: ['continue', 'model'], + }; +} + +/** + * The Mastra Gateway answered: a `mastra/…` model, a request sent to its host (production, or the + * configured base URL), a v1 billing reply (a billing `type` with a `help_url` on a mastra.ai host, or + * from older gateways a message naming `gateway.mastra.ai`), or a v2 reply naming itself a gateway + * error or carrying a reason code only the gateway sends. The request reaches the + * gateway without the `mastra/` prefix, and history keeps no request URL, so the web UI rebuilds a saved + * error from its request origin, when one was recorded, and otherwise from the reply body. + */ +function isMastraGatewayError( + error: RunErrorIdentity, + reply: GatewayReply | undefined, + options: DescribeRunErrorOptions, +): boolean { return ( providerModelId(error)?.startsWith(MASTRA_GATEWAY_PREFIX) === true || - calledMastraGateway(error) || - /gateway\.mastra\.ai/.test(providerErrorReason(error) ?? error.message) + calledMastraGateway(error, configuredGatewayOrigin(options.gatewayBaseUrl)) || + /gateway\.mastra\.ai/.test(providerErrorReason(error) ?? error.message) || + reply?.v1Billing === true || + reply?.type === 'gateway_error' || + (reply?.code !== undefined && onlyTheGatewaySends(reply.code)) ); } -/** Whether the request, or a provider error it wraps, went to the gateway's host. */ -function calledMastraGateway(error: unknown, depth = 0): boolean { - if (depth > 4 || typeof error !== 'object' || error === null) return false; - const url = 'url' in error ? error.url : undefined; - const cause = 'cause' in error ? error.cause : undefined; - return (typeof url === 'string' && MASTRA_GATEWAY_HOST.test(hostOf(url))) || calledMastraGateway(cause, depth + 1); +/** + * The configured gateway's origin: scheme, host and port. A gateway served under a path prefix shares + * its origin with anything else on that host, so a provider at the same origin would also match. + */ +function configuredGatewayOrigin(baseUrl: string | undefined): string | undefined { + if (!baseUrl) return undefined; + try { + const { origin } = new URL(baseUrl); + return origin === 'null' ? undefined : origin; + } catch { + return undefined; + } } -function hostOf(url: string): string { +/** + * Whether the request, or a provider error it wraps, went to the gateway's host. A saved error part + * keeps no URL, only the request's origin as `requestOrigin` on versions of `@mastra/core` that record it. + */ +function calledMastraGateway(error: unknown, configuredOrigin: string | undefined, depth = 0): boolean { + if (depth > 4 || typeof error !== 'object' || error === null) return false; + const url = 'url' in error ? error.url : 'requestOrigin' in error ? error.requestOrigin : undefined; + const cause = 'cause' in error ? error.cause : undefined; + return ( + (typeof url === 'string' && isGatewayUrl(url, configuredOrigin)) || + calledMastraGateway(cause, configuredOrigin, depth + 1) + ); +} + +function isGatewayUrl(url: string, configuredOrigin: string | undefined): boolean { try { - return new URL(url).hostname; + const parsed = new URL(url); + return ( + MASTRA_GATEWAY_HOST.test(parsed.hostname) || + (configuredOrigin !== undefined && parsed.origin === configuredOrigin) + ); } catch { - return ''; + return false; } } +/** + * The gateway's error object from the response body, on the error or a cause it wraps, with the codes + * a saved error part keeps as a fallback. The Messages route sends no `code` and repeats the code as + * the message, so a code-shaped message is read as the code. + */ +function gatewayReply(error: unknown, depth = 0): GatewayReply | undefined { + if (depth > 4 || typeof error !== 'object' || error === null) return undefined; + const fromBody = 'responseBody' in error ? replyFromBody(error.responseBody) : undefined; + if (fromBody) return fromBody; + const fromCause = gatewayReply('cause' in error ? error.cause : undefined, depth + 1); + if (fromCause) return fromCause; + const codes = 'codes' in error && Array.isArray(error.codes) ? error.codes.filter(isString) : []; + const code = codes.find(candidate => GATEWAY_CODES.has(candidate)); + if (code || codes.includes('gateway_error')) { + return { ...(codes.includes('gateway_error') ? { type: 'gateway_error' } : {}), ...(code ? { code } : {}) }; + } + return undefined; +} + +const CODE_SHAPED = /^[a-z][a-z0-9_]*$/; + +function replyFromBody(body: unknown): GatewayReply | undefined { + if (typeof body !== 'string') return undefined; + let parsed: unknown; + try { + parsed = JSON.parse(body); + } catch { + return undefined; + } + const inner = typeof parsed === 'object' && parsed !== null && 'error' in parsed ? parsed.error : undefined; + if (typeof inner !== 'object' || inner === null) return undefined; + const type = 'type' in inner && isString(inner.type) ? inner.type : undefined; + const rawMessage = 'message' in inner && isString(inner.message) ? inner.message.trim() : undefined; + const code = + 'code' in inner && isString(inner.code) + ? inner.code + : type === 'gateway_error' && rawMessage && CODE_SHAPED.test(rawMessage) + ? rawMessage + : undefined; + const sentence = rawMessage && rawMessage !== code && !CODE_SHAPED.test(rawMessage) ? rawMessage : undefined; + const message = + sentence && sentence.length > MAX_GATEWAY_MESSAGE_LENGTH + ? `${sentence.slice(0, MAX_GATEWAY_MESSAGE_LENGTH - 1)}…` + : sentence; + if (!type && !code) return undefined; + const helpUrl = 'help_url' in inner && isString(inner.help_url) ? inner.help_url : undefined; + const v1Billing = type !== undefined && V1_BILLING_TYPES.has(type) && helpUrl !== undefined && onMastraHost(helpUrl); + // The v1 spend limit names itself only by its type; read it as the v2 code of the same meaning. + const reason = code ?? (v1Billing && type === 'spend_limit_reached' ? type : undefined); + return { + ...(type ? { type } : {}), + ...(reason ? { code: reason } : {}), + ...(message ? { message } : {}), + ...(v1Billing ? { v1Billing: true as const } : {}), + }; +} + +function onMastraHost(url: string): boolean { + try { + const parsed = new URL(url); + return parsed.protocol === 'https:' && MASTRA_HOST.test(parsed.hostname); + } catch { + return false; + } +} + +function isString(value: unknown): value is string { + return typeof value === 'string' && value.trim().length > 0; +} + function afterProviderReason(error: RunErrorIdentity, next: string, fallback?: string): string { const reason = providerErrorReason(error) ?? fallback; return reason ? `${reason.replace(/\.?$/, '.')} ${next}` : next; diff --git a/mastracode/factory/src/session/session-row-view.test.ts b/mastracode/factory/src/session/session-row-view.test.ts index 964a9e35589..14a057b9f16 100644 --- a/mastracode/factory/src/session/session-row-view.test.ts +++ b/mastracode/factory/src/session/session-row-view.test.ts @@ -84,23 +84,14 @@ describe('session order', () => { it('orders activity as live work, then idle, then done, across factory and user rows whatever their age', () => { const rows = [ - row('done', { status: 'done', updatedAt: '2026-09-04T12:00:00.000Z' }), - row('idle', { updatedAt: '2026-09-04T11:00:00.000Z' }), - userRow('running', { status: 'working', updatedAt: '2026-09-04T08:00:00.000Z' }), + row('done', { status: 'done' }, { createdAt: '2026-09-04T12:00:00.000Z' }), + row('idle', {}, { createdAt: '2026-09-04T11:00:00.000Z' }), + userRow('running', { status: 'working' }, { createdAt: '2026-09-04T08:00:00.000Z' }), ]; expect(sessionIds(rows, { sort: 'activity' })).toEqual(['running', 'idle', 'done']); }); - it('orders activity within a status by last update, so an old session updated since beats a new one left alone', () => { - const rows = [ - userRow('new-untouched', { updatedAt: '2026-09-04T11:00:00.000Z' }, { createdAt: '2026-09-04T11:00:00.000Z' }), - userRow('old-updated', { updatedAt: '2026-09-04T11:30:00.000Z' }, { createdAt: '2026-09-01T08:00:00.000Z' }), - ]; - - expect(sessionIds(rows, { sort: 'activity' })).toEqual(['old-updated', 'new-untouched']); - }); - it('orders by last update even when creation order disagrees', () => { const rows = [ userRow('created-last', { updatedAt: '2026-09-04T10:00:00.000Z' }, { createdAt: '2026-09-04T12:00:00.000Z' }), @@ -225,7 +216,7 @@ describe('a card with its sessions revealed', () => { it('sorts a card by what its sessions carry, so newer idle rows do not push it out of the window', () => { const newerIdle = Array.from({ length: 5 }, (_, index) => - row(`idle-${index}`, { updatedAt: '2026-09-04T11:00:00.000Z' }), + row(`idle-${index}`, {}, { createdAt: '2026-09-04T11:00:00.000Z' }), ); expect(sessionIds([...newerIdle, ...revealed], { sort: 'activity' })).toEqual([ @@ -294,7 +285,7 @@ describe('group window', () => { it('lists the first five rows of each group and counts the rest', () => { const otherBoard = Array.from({ length: 6 }, (_, index) => row(`release-${index}`, { board: 'release' })); - const answer = listed([...rows, ...otherBoard], { groupBy: 'board', sort: 'created' }); + const answer = listed([...rows, ...otherBoard], { groupBy: 'board' }); expect(answer.groups.map(group => [group.key, group.rows.length, group.total])).toEqual([ ['board:release', 5, 6], @@ -304,7 +295,7 @@ describe('group window', () => { it('lists a group as deep as the reader asked, and other groups at five', () => { const otherBoard = Array.from({ length: 6 }, (_, index) => row(`release-${index}`, { board: 'release' })); - const answer = listed([...rows, ...otherBoard], { groupBy: 'board', sort: 'created', window: ['board:work:7'] }); + const answer = listed([...rows, ...otherBoard], { groupBy: 'board', window: ['board:work:7'] }); expect(answer.groups.map(group => [group.key, group.rows.length])).toEqual([ ['board:release', 5], diff --git a/mastracode/factory/src/session/session-row-view.ts b/mastracode/factory/src/session/session-row-view.ts index a55ccb7e710..019bdad10bd 100644 --- a/mastracode/factory/src/session/session-row-view.ts +++ b/mastracode/factory/src/session/session-row-view.ts @@ -35,7 +35,7 @@ const newestFirst = (a: string, b: string) => (a < b ? 1 : a > b ? -1 : 0); const SESSION_ROW_ORDER: Record number> = { activity: (a, b) => ACTIVITY_RANK[a.cardStatus ?? a.status] - ACTIVITY_RANK[b.cardStatus ?? b.status] || - newestFirst(a.updatedAt, b.updatedAt), + newestFirst(a.session.createdAt, b.session.createdAt), updated: (a, b) => newestFirst(a.updatedAt, b.updatedAt), created: (a, b) => newestFirst(a.session.createdAt, b.session.createdAt), }; diff --git a/mastracode/factory/src/skills/app-skills.ts b/mastracode/factory/src/skills/app-skills.ts index b118eb4c596..191bcc3346f 100644 --- a/mastracode/factory/src/skills/app-skills.ts +++ b/mastracode/factory/src/skills/app-skills.ts @@ -28,19 +28,15 @@ export function assertFactorySkills(skills: unknown): readonly InlineSkill[] { return Object.freeze([...skills]); } -const NO_PROJECT_SKILLS: ReadonlySet = new Set(); - /** * Problems with the skills board phases name in `runner.skill`, found at * startup instead of when a card first enters the phase. A skill is found when - * it is a code skill, a folder skill in the app's `factory-skills/`, bundled, - * or one of `projectSkills`, the skills a project created for its own boards. + * it is a code skill, a folder skill in the app's `factory-skills/`, or bundled. */ export function findBoardSkillProblems( boards: BoardRegistry, codeSkills: readonly InlineSkill[], localSkillsPath: string | undefined = resolveLocalFactorySkillsPath(), - projectSkills: ReadonlySet = NO_PROJECT_SKILLS, ): string[] { const codeNames = new Set(codeSkills.map(skill => skill.name)); const problems: string[] = []; @@ -52,11 +48,10 @@ export function findBoardSkillProblems( const found = codeNames.has(skill) || FACTORY_SKILL_NAMES.has(skill) || - projectSkills.has(skill) || (localSkillsPath !== undefined && existsSync(join(localSkillsPath, skill, 'SKILL.md'))); if (!found) { problems.push( - `${where} runs skill '${skill}', but no such skill exists. Pass it in MastraFactory({ skills }), add factory-skills/${skill}/SKILL.md, or create it in Settings › Skills.`, + `${where} runs skill '${skill}', but no such skill exists. Pass it in MastraFactory({ skills }) or add factory-skills/${skill}/SKILL.md.`, ); } else if (REVIEW_ONLY_FACTORY_SKILLS.has(skill) && context !== 'review') { problems.push( diff --git a/mastracode/factory/src/skills/catalog.ts b/mastracode/factory/src/skills/catalog.ts index 6b0f8979189..f33895c2768 100644 --- a/mastracode/factory/src/skills/catalog.ts +++ b/mastracode/factory/src/skills/catalog.ts @@ -16,9 +16,7 @@ import type { InlineSkill } from '@mastra/core/skills'; import { validateSkillContent } from '@mastra/core/skills'; import type { SkillSource } from '@mastra/core/workspace'; -import type { ProjectSkillNames } from '../boards/project-boards.js'; -import type { StoredBoardScope } from '../storage/domains/boards/base.js'; -import type { SkillOverrideRecord, SkillOverridesStorage } from '../storage/domains/skill-overrides/base.js'; +import type { SkillOverrideRecord } from '../storage/domains/skill-overrides/base.js'; import { FACTORY_SKILL_NAMES, FACTORY_SKILLS_MOUNT, @@ -29,9 +27,6 @@ import { /** Where a skill comes from: shipped with Factory, the app's `factory-skills/` folder, or `MastraFactory({ skills })`. */ export type FactorySkillOrigin = 'bundled' | 'folder' | 'code'; -/** Where a listed skill comes from: an original's origin, or `project` for a skill the project created. */ -export type FactorySkillCatalogOrigin = FactorySkillOrigin | 'project'; - export interface FactorySkillInfo { name: string; description: string; @@ -39,15 +34,13 @@ export interface FactorySkillInfo { content: string; /** Frontmatter fields besides `name` and `description` (license, user-invocable, …), so an editor can keep them. */ frontmatter?: Record; - origin: FactorySkillCatalogOrigin; + origin: FactorySkillOrigin; /** True for the skills Factory ships, including when the app overrides one. */ builtIn: boolean; /** Set when the SKILL.md fails the runtime's parsing/validation, so the agent will not be able to load it. */ error?: string; /** Set when the project has an edited copy; `description` and `content` then come from the edit. */ edited?: { updatedBy: string; updatedAt: string }; - /** Set for a skill the project created (`origin: 'project'`): who saved it last, and when. */ - created?: { updatedBy: string; updatedAt: string }; /** True when the code, folder, or bundled SKILL.md changed since the project's edit was made. */ originalChanged?: boolean; } @@ -127,73 +120,33 @@ export async function readFactorySkillOriginals( return originals; } -/** The catalog entry of a skill the project created, from its stored row. */ -export function createdSkillInfo(created: SkillOverrideRecord): FactorySkillInfo { - return { - name: created.skillName, - ...parseSkillMarkdown(created.skillName, created.content), - origin: 'project', - builtIn: false, - created: { updatedBy: created.updatedBy, updatedAt: created.updatedAt.toISOString() }, - }; -} - -/** The catalog entry of a code, folder, or bundled skill, showing the project's `edit` of it when it has one. */ -export function originalSkillInfo( - name: string, - { raw, origin }: FactorySkillOriginal, - edit?: SkillOverrideRecord, -): FactorySkillInfo { - const builtIn = FACTORY_SKILL_NAMES.has(name); - if (!edit) return { name, ...parseSkillMarkdown(name, raw), origin, builtIn }; - return { - name, - ...parseSkillMarkdown(name, edit.content), - origin, - builtIn, - edited: { updatedBy: edit.updatedBy, updatedAt: edit.updatedAt.toISOString() }, - originalChanged: hashSkillContent(raw) !== edit.baseHash, - }; -} - /** * List the skills the Factory skill mount serves, sorted by name. With a * project's `overrides`, edited skills show the edited text, who edited them, - * and whether the original changed since, and the project's created skills - * are listed with origin `project`. Edits of skills that no longer exist are - * not listed, matching what sessions load. A created skill whose name an app - * skill later takes is listed as that skill's edit. + * and whether the original changed since. Edits of skills that no longer + * exist are not listed, matching what sessions load. */ export async function listFactorySkills( codeSkills: readonly InlineSkill[] = [], overrides: readonly SkillOverrideRecord[] = [], ): Promise { const edits = new Map(overrides.map(override => [override.skillName, override])); - const originals = await readFactorySkillOriginals(codeSkills); - const created = overrides.filter(override => override.kind === 'created' && !originals.has(override.skillName)); - return [ - ...created.map(createdSkillInfo), - ...[...originals].map(([name, original]) => originalSkillInfo(name, original, edits.get(name))), - ].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); -} - -/** - * Reads the skills each project created, for its boards' runners. A created skill an app skill later - * shadows still counts: a runner naming it finds the app's skill. - */ -export function projectSkillNamesOf( - storage: Pick, -): ProjectSkillNames { - const projectScope = (scope: StoredBoardScope) => ({ orgId: scope.orgId, projectId: scope.factoryProjectId }); - return { - revision: async scope => { - await storage.ensureReady(); - return storage.revision(projectScope(scope)); - }, - names: async scope => { - await storage.ensureReady(); - const overrides = await storage.list(projectScope(scope)); - return new Set(overrides.filter(override => override.kind === 'created').map(override => override.skillName)); - }, - }; + const skills: FactorySkillInfo[] = []; + for (const [name, { raw, origin }] of await readFactorySkillOriginals(codeSkills)) { + const edit = edits.get(name); + const builtIn = FACTORY_SKILL_NAMES.has(name); + if (!edit) { + skills.push({ name, ...parseSkillMarkdown(name, raw), origin, builtIn }); + continue; + } + skills.push({ + name, + ...parseSkillMarkdown(name, edit.content), + origin, + builtIn, + edited: { updatedBy: edit.updatedBy, updatedAt: edit.updatedAt.toISOString() }, + originalChanged: hashSkillContent(raw) !== edit.baseHash, + }); + } + return skills; } diff --git a/mastracode/factory/src/storage/domains/audit/actions.ts b/mastracode/factory/src/storage/domains/audit/actions.ts index 6327c6116b9..37749afbcbe 100644 --- a/mastracode/factory/src/storage/domains/audit/actions.ts +++ b/mastracode/factory/src/storage/domains/audit/actions.ts @@ -11,7 +11,7 @@ export const AUDIT_ACTIONS = { intake_order: ['updated', 'evaluator_updated'], session: ['owner_transferred'], board: ['created', 'updated', 'deleted', 'reset'], - skill: ['created', 'updated', 'reverted', 'deleted'], + skill: ['updated', 'reverted'], intake_route: ['created', 'updated', 'deleted', 'reordered', 'rerouted'], sandbox_env: ['set', 'updated', 'deleted'], } as const; diff --git a/mastracode/factory/src/storage/domains/skill-overrides/base.test.ts b/mastracode/factory/src/storage/domains/skill-overrides/base.test.ts index b473d137660..c1f82448eae 100644 --- a/mastracode/factory/src/storage/domains/skill-overrides/base.test.ts +++ b/mastracode/factory/src/storage/domains/skill-overrides/base.test.ts @@ -60,84 +60,6 @@ describe.each(['libsql', ...(postgresUrl ? ['postgres'] : [])])('SkillOverridesS expect(await overrides.revision(scope)).toBe(3); }); - it('creates a skill once per project, replacing only an edit stored under its name', async () => { - const { overrides, orgId } = await makeStorage(); - const scope = { orgId, projectId: 'project-a' }; - const create = (content: string) => - overrides.create({ ...scope, skillName: 'release-notes', content, updatedBy: 'user-1' }); - - const first = await create('first'); - expect(first).toMatchObject({ skillName: 'release-notes', content: 'first', kind: 'created', baseHash: '' }); - expect(await overrides.revision(scope)).toBe(1); - expect(await create('second')).toBeNull(); - expect(await overrides.revision(scope)).toBe(1); - expect(await overrides.get({ ...scope, skillName: 'release-notes' })).toEqual(first); - // Saving it keeps it a created skill when asked to. - await overrides.upsert({ - ...scope, - skillName: 'release-notes', - content: 'third', - baseHash: '', - kind: 'created', - updatedBy: 'user-1', - }); - expect(await overrides.get({ ...scope, skillName: 'release-notes' })).toMatchObject({ - kind: 'created', - content: 'third', - }); - - // An edit left behind by a removed app skill gives way to a created skill. - await save(overrides, scope, 'old-app-skill', 'edited'); - expect((await overrides.get({ ...scope, skillName: 'old-app-skill' }))?.kind).toBe('edit'); - expect( - await overrides.create({ ...scope, skillName: 'old-app-skill', content: 'mine', updatedBy: 'user-2' }), - ).toMatchObject({ - kind: 'created', - content: 'mine', - updatedBy: 'user-2', - }); - }); - - it('updates a created skill only while it exists, and never turns an edit into one', async () => { - const { overrides, orgId } = await makeStorage(); - const scope = { orgId, projectId: 'project-a' }; - const update = (skillName: string, content: string) => - overrides.updateCreated({ ...scope, skillName, content, updatedBy: 'user-2' }); - - expect(await update('release-notes', 'nothing yet')).toBeNull(); - await overrides.create({ ...scope, skillName: 'release-notes', content: 'first', updatedBy: 'user-1' }); - expect(await update('release-notes', 'second')).toMatchObject({ - kind: 'created', - content: 'second', - updatedBy: 'user-2', - }); - expect(await overrides.revision(scope)).toBe(2); - - // Deleted first, a late save finds nothing and stores nothing. - await overrides.delete({ ...scope, skillName: 'release-notes' }); - expect(await update('release-notes', 'late')).toBeNull(); - expect(await overrides.get({ ...scope, skillName: 'release-notes' })).toBeNull(); - - await save(overrides, scope, 'factory-plan', 'edited'); - expect(await update('factory-plan', 'not mine')).toBeNull(); - expect(await overrides.get({ ...scope, skillName: 'factory-plan' })).toMatchObject({ - kind: 'edit', - content: 'edited', - }); - }); - - it('creates one skill when the same name is created concurrently', async () => { - const { overrides, orgId } = await makeStorage(); - const scope = { orgId, projectId: 'project-a' }; - const results = await Promise.all( - Array.from({ length: 6 }, (_, i) => - overrides.create({ ...scope, skillName: 'release-notes', content: `content ${i}`, updatedBy: 'user-1' }), - ), - ); - expect(results.filter(result => result !== null)).toHaveLength(1); - expect(await overrides.revision(scope)).toBe(1); - }); - it('counts every concurrent save once', async () => { const { overrides, orgId } = await makeStorage(); const scope = { orgId, projectId: 'project-a' }; diff --git a/mastracode/factory/src/storage/domains/skill-overrides/base.ts b/mastracode/factory/src/storage/domains/skill-overrides/base.ts index 786d9abbc63..5b51029f5dd 100644 --- a/mastracode/factory/src/storage/domains/skill-overrides/base.ts +++ b/mastracode/factory/src/storage/domains/skill-overrides/base.ts @@ -1,22 +1,15 @@ import { FactoryStorageDomain } from '@mastra/core/storage'; import type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage'; -/** - * `edit` replaces a skill the app serves and stops applying when that skill is removed. `created` is a skill - * the project added itself, served even when the app has no skill of that name. - */ -export type SkillOverrideKind = 'edit' | 'created'; - -/** A project's SKILL.md for one Factory skill: an edited copy of an app skill, or a skill the project created. */ +/** A project's edited copy of one Factory skill's SKILL.md. */ export interface SkillOverrideRecord { orgId: string; projectId: string; skillName: string; - /** The full SKILL.md, frontmatter included. */ + /** The full edited SKILL.md, frontmatter included. */ content: string; - /** sha256 of the original SKILL.md an edit was made against; empty for a created skill. */ + /** sha256 of the original SKILL.md the edit was made against. */ baseHash: string; - kind: SkillOverrideKind; updatedBy: string; updatedAt: Date; } @@ -45,8 +38,6 @@ export const SKILL_OVERRIDES_SCHEMA: CollectionSchema = { skill_name: { type: 'text' }, content: { type: 'text' }, base_hash: { type: 'text' }, - // Added after the first release; rows stored before it are edits. - kind: { type: 'text', default: 'edit' }, updated_by: { type: 'text' }, updated_at: { type: 'timestamp' }, }, @@ -78,7 +69,6 @@ interface SkillOverrideDbRow extends Record { skill_name: string; content: string; base_hash: string; - kind: string; updated_by: string; updated_at: Date; } @@ -98,7 +88,6 @@ function toRecord(row: SkillOverrideDbRow): SkillOverrideRecord { skillName: row.skill_name, content: row.content, baseHash: row.base_hash, - kind: row.kind === 'created' ? 'created' : 'edit', updatedBy: row.updated_by, updatedAt: row.updated_at, }; @@ -154,20 +143,13 @@ export class SkillOverridesStorage extends FactoryStorageDomain { return row ? toRecord(row) : null; } - /** Saves the project's SKILL.md for a skill, replacing any stored one. `kind` defaults to `edit`. */ async upsert({ content, baseHash, - kind = 'edit', updatedBy, skillName, ...scope - }: SkillScope & { - content: string; - baseHash: string; - kind?: SkillOverrideKind; - updatedBy: string; - }): Promise { + }: SkillScope & { content: string; baseHash: string; updatedBy: string }): Promise { await this.#ensureRevisionRow(scope); return this.storage.withTransaction(async ops => { const now = await this.#bumpRevision(ops, scope); @@ -179,7 +161,6 @@ export class SkillOverridesStorage extends FactoryStorageDomain { skill_name: skillName, content, base_hash: baseHash, - kind, updated_by: updatedBy, updated_at: now, }, @@ -188,46 +169,6 @@ export class SkillOverridesStorage extends FactoryStorageDomain { }); } - /** - * Stores a skill the project created, or returns `null` when the project already created one by that name. - * An edit stored under the name is replaced: its skill is gone from the app, so nothing served it. - */ - create(input: SkillScope & { content: string; updatedBy: string }): Promise { - return this.#writeCreated(input, existing => existing?.kind !== 'created'); - } - - /** - * Saves a new SKILL.md for a skill the project created, or returns `null` when it has no created skill by - * that name, so a save that loses a race with a delete doesn't create the skill again. - */ - updateCreated(input: SkillScope & { content: string; updatedBy: string }): Promise { - return this.#writeCreated(input, existing => existing?.kind === 'created'); - } - - /** Writes a created skill when `canWrite` accepts the row stored under its name, else returns `null`. */ - async #writeCreated( - { content, updatedBy, skillName, ...scope }: SkillScope & { content: string; updatedBy: string }, - canWrite: (existing: SkillOverrideDbRow | null) => boolean, - ): Promise { - await this.#ensureRevisionRow(scope); - return this.storage.withTransaction(async ops => { - // Lock the revision row first, so concurrent writes of one name serialize and each sees the last. - const result: { written?: SkillOverrideDbRow } = {}; - await ops.updateAtomic('factory_skill_override_revisions', projectWhere(scope), async row => { - const skill = { ...projectWhere(scope), skill_name: skillName }; - if (!canWrite(await ops.findOne('factory_skill_overrides', skill))) return null; - const now = new Date(); - result.written = await ops.upsertOne( - 'factory_skill_overrides', - ['org_id', 'factory_project_id', 'skill_name'], - { ...skill, content, base_hash: '', kind: 'created', updated_by: updatedBy, updated_at: now }, - ); - return { revision: row.revision + 1, updated_at: now }; - }); - return result.written ? toRecord(result.written) : null; - }); - } - /** False when the skill had no override; the revision only moves when a row was removed. */ async delete({ skillName, ...scope }: SkillScope): Promise { await this.#ensureRevisionRow(scope); diff --git a/mastracode/factory/src/tools/read-tools.test.ts b/mastracode/factory/src/tools/read-tools.test.ts index 7cc892b56ae..a26333523e9 100644 --- a/mastracode/factory/src/tools/read-tools.test.ts +++ b/mastracode/factory/src/tools/read-tools.test.ts @@ -246,16 +246,16 @@ describe('factory_list_work_items', () => { expect(result.items.find(row => row.id === 'a')?.number).toBe(12); }); - it('links each card to the page that opens its session when a public URL is configured', async () => { + it('links each card on its board when a public URL is configured', async () => { vi.stubEnv('MASTRACODE_PUBLIC_URL', 'https://factory.example.com'); try { const { run } = setup({ items: rows }); const result = await run<{ items: Array<{ id: string; url: string | null }> }>('factory_list_work_items', {}); expect(result.items.find(row => row.id === 'a')?.url).toBe( - 'https://factory.example.com/factories/project-1/cards/a', + 'https://factory.example.com/factories/project-1/work?item=a', ); expect(result.items.find(row => row.id === 'c')?.url).toBe( - 'https://factory.example.com/factories/project-1/cards/c', + 'https://factory.example.com/factories/project-1/boards/release?item=c', ); } finally { vi.unstubAllEnvs(); diff --git a/mastracode/factory/src/tools/read-tools.ts b/mastracode/factory/src/tools/read-tools.ts index 2d1720e2222..d11749ab36b 100644 --- a/mastracode/factory/src/tools/read-tools.ts +++ b/mastracode/factory/src/tools/read-tools.ts @@ -169,6 +169,7 @@ function workItemUrl(item: Card) { return ( factoryWorkItemUrl({ factoryProjectId: item.factoryProjectId, + board: boardForWorkItem(item), workItemId: item.id, }) ?? null ); diff --git a/mastracode/factory/src/tools/work-item-tools.test.ts b/mastracode/factory/src/tools/work-item-tools.test.ts index 9de9d8b0fdf..c6d52fb1758 100644 --- a/mastracode/factory/src/tools/work-item-tools.test.ts +++ b/mastracode/factory/src/tools/work-item-tools.test.ts @@ -815,7 +815,7 @@ describe("a card's work requested from a chat", () => { env.run('factory_transition_work_item', { workItem: PULL_REQUEST_URL, stage: 'pr-review', rerun: true }), ).resolves.toMatchObject({ workItemId: card.id, - url: `https://factory.example.com/factories/project-1/cards/${card.id}`, + url: `https://factory.example.com/factories/project-1/work?item=${card.id}`, stage: 'pr-review', reran: true, }); @@ -885,7 +885,7 @@ describe("a card's work requested from a chat", () => { ).resolves.toMatchObject({ workItemId: card.id, status: 'pending', - url: `https://factory.example.com/factories/project-1/cards/${card.id}`, + url: `https://factory.example.com/factories/project-1/work?item=${card.id}`, }); // Who the card's review session reports to when its run ends. diff --git a/mastracode/factory/src/tools/work-item-tools.ts b/mastracode/factory/src/tools/work-item-tools.ts index 8074a59f5f0..f3f1f341cf4 100644 --- a/mastracode/factory/src/tools/work-item-tools.ts +++ b/mastracode/factory/src/tools/work-item-tools.ts @@ -72,6 +72,7 @@ function briefItem(item: Card) { url: factoryWorkItemUrl({ factoryProjectId: item.factoryProjectId, + board: boardForWorkItem(item), workItemId: item.id, }) ?? null, }; @@ -165,6 +166,7 @@ export function createFactoryWorkItemTools( url = factoryWorkItemUrl({ factoryProjectId: item.factoryProjectId, + board: boardForWorkItem(item), workItemId: item.id, }) ?? null; await follow(item, 'started'); @@ -285,6 +287,7 @@ export function createFactoryWorkItemTools( const url = factoryWorkItemUrl({ factoryProjectId: item.factoryProjectId, + board: boardForWorkItem(item), workItemId: item.id, }) ?? null; const sameStage = item.stages.length === 1 && item.stages[0] === stage; diff --git a/mastracode/factory/src/workspace.test.ts b/mastracode/factory/src/workspace.test.ts index 59d54cd4d48..bde9fcb7bac 100644 --- a/mastracode/factory/src/workspace.test.ts +++ b/mastracode/factory/src/workspace.test.ts @@ -158,7 +158,6 @@ import type { SkillOverridesStorage } from './storage/domains/skill-overrides/ba import { createFactoryStorageForTests } from './storage/test-utils.js'; import { createWorkspaceFactory, - FACTORY_SKILLS_MOUNT, FactorySkillSource, REVIEW_ONLY_FACTORY_SKILLS, FactoryWorkspaceRegistry, @@ -1724,50 +1723,6 @@ describe('GitHub session workspace preparation', () => { expect(await workspace.skills?.get('removed-app-skill')).toBeFalsy(); }); - it('gives sessions in the project that created a skill that skill, and drops it once deleted', async () => { - const { skillOverrides } = await createFactoryStorageForTests(); - const { resolver } = await createLocalFactory(undefined, undefined, skillOverrides); - addProject(); - addProject({ id: 'project-2', repoFullName: 'octocat/other' }); - for (const id of ['session-reused', 'session-1', 'session-2']) addSession({ id }); - addSession({ id: 'session-other', projectRepositoryId: 'project-2' }); - const reusedContext = createGithubRequestContext('project-1', 'session-reused'); - const reused = (await resolver({ requestContext: reusedContext }))!; - await reused.skills?.maybeRefresh(); - // Prime the reuse record, as a session's first turn does. - await resolver({ requestContext: reusedContext }); - const notesIn = async (workspace: Awaited>>) => { - await workspace!.skills?.maybeRefresh(); - return workspace!.skills?.get('release-notes'); - }; - - const created = await skillOverrides.create({ - orgId: 'org-1', - projectId: 'project-1', - skillName: 'release-notes', - content: '---\nname: release-notes\ndescription: Write release notes\n---\n\n# Release notes\n', - updatedBy: 'admin-1', - }); - expect(created?.kind).toBe('created'); - - const session = await resolver({ requestContext: createGithubRequestContext('project-1', 'session-1') }); - const notes = await notesIn(session); - expect(notes?.description).toBe('Write release notes'); - expect(notes?.instructions).toContain('# Release notes'); - expect((await session!.skills?.list())?.map(skill => skill.name)).toContain('release-notes'); - expect(await resolver({ requestContext: reusedContext })).toBe(reused); - expect((await reused.skills?.get('release-notes'))?.instructions).toContain('# Release notes'); - const other = await resolver({ requestContext: createGithubRequestContext('project-2', 'session-other') }); - expect(await notesIn(other)).toBeFalsy(); - - await skillOverrides.delete({ orgId: 'org-1', projectId: 'project-1', skillName: 'release-notes' }); - expect( - await notesIn(await resolver({ requestContext: createGithubRequestContext('project-1', 'session-2') })), - ).toBeFalsy(); - expect(await resolver({ requestContext: reusedContext })).toBe(reused); - expect(await reused.skills?.get('release-notes')).toBeFalsy(); - }); - it('serves the original skills while edits cannot be read, and the edit once they can', async () => { const { skillOverrides } = await createFactoryStorageForTests(); const { resolver } = await createLocalFactory(undefined, undefined, skillOverrides); @@ -3944,81 +3899,6 @@ describe('FactorySkillSource layering', () => { expect(names).toEqual(['repo-only-skill', 'README.md']); }); - it("hides a repository skill named after a skill the project created, and not after another's edit", async () => { - const overrides = new Map([ - [ - 'release-notes', - { content: '---\nname: release-notes\ndescription: notes\n---\n', updatedAt: new Date(), created: true }, - ], - // An edit of an app skill the app no longer has serves nothing, so it reserves nothing. - [ - 'removed-app-skill', - { content: '---\nname: removed-app-skill\ndescription: gone\n---\n', updatedAt: new Date() }, - ], - ]); - const source = new FactorySkillSource( - repoFallback(['release-notes', 'removed-app-skill', 'repo-only-skill']), - [repoRoot], - undefined, - async () => true, - [], - async () => overrides, - ); - - expect((await source.readdir(repoRoot)).map(entry => entry.name)).toEqual([ - 'removed-app-skill', - 'repo-only-skill', - ]); - expect((await source.readdir(FACTORY_SKILLS_MOUNT)).map(entry => entry.name)).toContain('release-notes'); - expect(String(await source.readFile(path.join(FACTORY_SKILLS_MOUNT, 'release-notes', 'SKILL.md')))).toContain( - 'name: release-notes', - ); - }); - - it('serves a created skill whose name only a folder without a SKILL.md uses', async () => { - const localRoot = await makeLocalRoot({}); - // The app removed its release-notes skill but left the folder behind. - await fs.mkdir(path.join(localRoot, 'release-notes', 'references'), { recursive: true }); - const content = '---\nname: release-notes\ndescription: notes\n---\n\n# Ours\n'; - const source = new FactorySkillSource( - repoFallback([]), - [repoRoot], - localRoot, - async () => true, - [], - async () => new Map([['release-notes', { content, updatedAt: new Date(), created: true }]]), - ); - const skillDir = path.join(FACTORY_SKILLS_MOUNT, 'release-notes'); - - expect((await source.readdir(FACTORY_SKILLS_MOUNT)).map(entry => entry.name)).toContain('release-notes'); - expect((await source.readdir(skillDir)).map(entry => entry.name).sort()).toEqual(['SKILL.md', 'references']); - expect(await source.exists(path.join(skillDir, 'SKILL.md'))).toBe(true); - expect(String(await source.readFile(path.join(skillDir, 'SKILL.md')))).toBe(content); - }); - - it('serves a created skill whose name a stray file in the app skills folder uses', async () => { - const localRoot = await makeLocalRoot({}); - await fs.writeFile(path.join(localRoot, 'release-notes'), 'not a skill'); - const content = '---\nname: release-notes\ndescription: notes\n---\n\n# Ours\n'; - const source = new FactorySkillSource( - repoFallback([]), - [repoRoot], - localRoot, - async () => true, - [], - async () => new Map([['release-notes', { content, updatedAt: new Date(), created: true }]]), - ); - const skillDir = path.join(FACTORY_SKILLS_MOUNT, 'release-notes'); - - expect((await source.readdir(FACTORY_SKILLS_MOUNT)).find(entry => entry.name === 'release-notes')).toEqual({ - name: 'release-notes', - type: 'directory', - }); - expect(await source.readdir(skillDir)).toEqual([{ name: 'SKILL.md', type: 'file' }]); - expect((await source.stat(skillDir)).type).toBe('directory'); - expect(String(await source.readFile(path.join(skillDir, 'SKILL.md')))).toBe(content); - }); - it('picks up app-local skills added after the source was created', async () => { const localRoot = await makeLocalRoot({}); const source = new FactorySkillSource(repoFallback(['late-skill']), [repoRoot], localRoot); diff --git a/mastracode/factory/src/workspace.ts b/mastracode/factory/src/workspace.ts index 3d164fafedf..a2b0c81e867 100644 --- a/mastracode/factory/src/workspace.ts +++ b/mastracode/factory/src/workspace.ts @@ -203,14 +203,10 @@ class CodeSkillSource implements SkillSource { } } -/** - * A project's SKILL.md for one skill: an edit served in place of the original's, or, with `created`, a skill - * the project added that is served even when the app has no skill of that name. - */ +/** A project's edited SKILL.md, served in place of the original's. */ export interface FactorySkillOverride { content: string; updatedAt: Date; - created?: boolean; } const NO_SKILL_OVERRIDES: ReadonlyMap = new Map(); @@ -269,8 +265,8 @@ export class FactorySkillSource implements SkillSource { /** * The edit replacing this path, when it is a skill's SKILL.md. Only the instructions are - * edited; the skill's other files still come from its layer. `exists` and `readdir` only - * consult created skills, so an edit whose skill was removed from the app is never discovered. + * edited; the skill's other files still come from its layer. `exists` and `readdir` never + * consult edits, so an edit whose skill was removed from the app is never discovered. */ async #overrideFor(relativePath: string): Promise { const [skillName, file, ...rest] = relativePath.split(path.sep); @@ -278,57 +274,13 @@ export class FactorySkillSource implements SkillSource { return (await this.skillOverrides()).get(skillName); } - /** - * True when a code, folder, or bundled skill has this name, so a created skill of the name is its edit - * instead. Only a SKILL.md makes a skill, as for the catalog: a folder left without one serves nothing. - */ - async #servedByLayer(skillName: string): Promise { - const skillFile = path.join(skillName, 'SKILL.md'); - if (this.#codeSource && (await this.#codeSource.exists(skillName))) return true; - if (this.#localSource && (await this.#localSource.exists(skillFile))) return true; - return this.#bundledSource.exists(skillFile); - } - - /** Names of the skills the project created that no layer serves; each is a directory holding only its SKILL.md. */ - async #createdSkillNames(): Promise { - const names: string[] = []; - for (const [name, override] of await this.skillOverrides()) { - if (override.created && !(await this.#servedByLayer(name))) names.push(name); - } - return names; - } - - /** The created skill this mount-relative path is in (its directory or its SKILL.md), when no layer serves it. */ - async #createdSkillAt(relativePath: string): Promise<{ file: boolean; override: FactorySkillOverride } | undefined> { - const [skillName, file, ...rest] = relativePath.split(path.sep); - if (!skillName || rest.length > 0 || (file !== undefined && file !== 'SKILL.md')) return undefined; - const override = (await this.skillOverrides()).get(skillName); - if (!override?.created || (await this.#servedByLayer(skillName))) return undefined; - return { file: file !== undefined, override }; - } - - /** A created skill's folder: its SKILL.md, plus whatever an app skill left in a folder of the same name. */ - async #createdSkillEntries(relativePath: string): Promise { - const entries = new Map(); - for (const source of [this.#bundledSource, this.#localSource]) { - try { - for (const entry of (await source?.readdir(relativePath)) ?? []) entries.set(entry.name, entry); - } catch { - // Nothing under the name in this layer, or a file rather than a folder. - } - } - entries.set('SKILL.md', { name: 'SKILL.md', type: 'file' }); - return [...entries.values()]; - } - async exists(skillPath: string): Promise { if (!this.#isFactoryPath(skillPath)) return this.fallback.exists(skillPath); const relative = this.#factoryPath(skillPath); if (await this.#isHiddenReviewPath(relative)) return false; if (await this.#ownedByCode(relative)) return this.#codeSource!.exists(relative); if (this.#localSource && (await this.#localSource.exists(relative))) return true; - if (await this.#bundledSource.exists(relative)) return true; - return (await this.#createdSkillAt(relative)) !== undefined; + return this.#bundledSource.exists(relative); } async stat(skillPath: string): Promise { @@ -345,16 +297,6 @@ export class FactorySkillSource implements SkillSource { modifiedAt: override.updatedAt, }; } - const created = await this.#createdSkillAt(relative); - if (created) { - return { - name: relative, - type: 'directory', - size: 0, - createdAt: created.override.updatedAt, - modifiedAt: created.override.updatedAt, - }; - } return (await this.#layerFor(relative)).stat(relative); } @@ -372,11 +314,6 @@ export class FactorySkillSource implements SkillSource { const relative = this.#factoryPath(skillPath); if (await this.#isHiddenReviewPath(relative)) throw skillSourceEnoent(skillPath); if (relative !== '' && (await this.#ownedByCode(relative))) return this.#codeSource!.readdir(relative); - const created = relative === '' ? undefined : await this.#createdSkillAt(relative); - if (created) { - if (created.file) throw skillSourceEnoent(skillPath); - return this.#createdSkillEntries(relative); - } const [bundledExists, localExists] = await Promise.all([ this.#bundledSource.exists(relative), this.#localSource?.exists(relative) ?? Promise.resolve(false), @@ -384,21 +321,16 @@ export class FactorySkillSource implements SkillSource { if (!bundledExists && !localExists && !(relative === '' && this.#codeSource)) { throw skillSourceEnoent(skillPath); } - const [bundledEntries, localEntries, codeEntries, createdNames] = await Promise.all([ + const [bundledEntries, localEntries, codeEntries] = await Promise.all([ bundledExists ? this.#bundledSource.readdir(relative) : [], localExists ? this.#localSource!.readdir(relative) : [], relative === '' && this.#codeSource ? this.#codeSource.readdir('') : [], - relative === '' ? this.#createdSkillNames() : [], ]); const merged = new Map(); for (const entry of bundledEntries) merged.set(entry.name, entry); // Local entries override bundled names; code skills override both. for (const entry of localEntries) merged.set(entry.name, entry); for (const entry of codeEntries) merged.set(entry.name, entry); - // Created skills only fill names no layer serves a skill under; a stray file of that name doesn't hide one. - for (const name of createdNames) { - if (merged.get(name)?.type !== 'directory') merged.set(name, { name, type: 'directory' }); - } const entries = [...merged.values()]; if (relative !== '' || (await this.isReviewSession())) return entries; return entries.filter(entry => !REVIEW_ONLY_FACTORY_SKILLS.has(entry.name)); @@ -412,14 +344,13 @@ export class FactorySkillSource implements SkillSource { } /** - * Names the Factory mount serves: bundled skills plus the app's code and local skills and the - * project's created skills. Repository skills with these names are hidden so they cannot collide - * with Factory's copy. Recomputed per scan so skill refreshes pick up local changes. + * Names the Factory mount serves: bundled skills plus the app's code and local skills. + * Repository skills with these names are hidden so they cannot collide with + * Factory's copy. Recomputed per scan so skill refreshes pick up local changes. */ async #reservedNames(): Promise> { const reserved = new Set(FACTORY_SKILL_NAMES); for (const entry of (await this.#codeSource?.readdir('')) ?? []) reserved.add(entry.name); - for (const name of await this.#createdSkillNames()) reserved.add(name); if (!this.#localSource) return reserved; try { for (const entry of await this.#localSource.readdir('')) { @@ -1334,13 +1265,7 @@ export function createWorkspaceFactory(options: CreateWorkspaceFactoryOptions = return { revision: snapshot.revision, overrides: new Map( - snapshot.overrides.map( - o => - [ - o.skillName, - { content: o.content, updatedAt: o.updatedAt, ...(o.kind === 'created' ? { created: true } : {}) }, - ] as const, - ), + snapshot.overrides.map(o => [o.skillName, { content: o.content, updatedAt: o.updatedAt }] as const), ), }; })(); diff --git a/mastracode/mastra-factory/CHANGELOG.md b/mastracode/mastra-factory/CHANGELOG.md index b938042f061..6caff9ab30c 100644 --- a/mastracode/mastra-factory/CHANGELOG.md +++ b/mastracode/mastra-factory/CHANGELOG.md @@ -1,31 +1,5 @@ # create-factory -## 0.5.0-alpha.6 - -### Patch Changes - -- Updated dependencies [[`bfcb0f7`](https://github.com/mastra-ai/mastra/commit/bfcb0f738dc0891014c0802d4d0fc5982fca83ee), [`383a19d`](https://github.com/mastra-ai/mastra/commit/383a19d0474ea150b8e209e20963ee6f6206393e)]: - - mastra@1.40.0-alpha.6 - -## 0.5.0-alpha.5 - -### Minor Changes - -- Added a `--tag ` option to `create-factory`. It pins the scaffolded template's `mastra` and `@mastra/*` dependencies to the exact versions published under that npm dist-tag, so you can try a new Factory on prerelease packages: ([#30598](https://github.com/mastra-ai/mastra/pull/30598)) - - ```sh - npx create-factory@latest my-factory --tag alpha - ``` - - When the pinned versions include prereleases and the project uses npm, `create-factory` also writes `legacy-peer-deps=true` to the project's `.npmrc`, because npm otherwise rejects the prerelease peer ranges. - -### Patch Changes - -- `create-factory --tag` now stops before installing when the npm registry lookup for a Mastra package fails, instead of keeping that package's template version and producing a project that mixes release channels. A package that simply has no release under the tag still keeps its template version with a warning. ([#30614](https://github.com/mastra-ai/mastra/pull/30614)) - -- Updated dependencies [[`c638825`](https://github.com/mastra-ai/mastra/commit/c638825c83d0f81196cfdede24c13a95e398717a), [`a6dbd29`](https://github.com/mastra-ai/mastra/commit/a6dbd29a4ebbba1f1f5ec31770d82a536e1cd48b), [`3c7c003`](https://github.com/mastra-ai/mastra/commit/3c7c00383d22fbfb02e844e599151ec153d2f281), [`b90d0ec`](https://github.com/mastra-ai/mastra/commit/b90d0ecd413b9955e63438aef6b3ef9b1ad6eb09), [`e22c5a7`](https://github.com/mastra-ai/mastra/commit/e22c5a7035b8a85f4258dabf8d2c2930b28f0774)]: - - mastra@1.40.0-alpha.5 - ## 0.4.4-alpha.4 ### Patch Changes diff --git a/mastracode/mastra-factory/package.json b/mastracode/mastra-factory/package.json index 30939f36c00..7eedf27f4ba 100644 --- a/mastracode/mastra-factory/package.json +++ b/mastracode/mastra-factory/package.json @@ -1,6 +1,6 @@ { "name": "create-factory", - "version": "0.5.0-alpha.6", + "version": "0.4.4-alpha.4", "description": "Create a Mastra Factory project: an agent-powered software delivery environment built on Mastra. Run `npm create factory` to scaffold and get started.", "type": "module", "license": "Apache-2.0", diff --git a/mastracode/sdk/CHANGELOG.md b/mastracode/sdk/CHANGELOG.md index f8ab5314ff4..e1641e0b838 100644 --- a/mastracode/sdk/CHANGELOG.md +++ b/mastracode/sdk/CHANGELOG.md @@ -1,32 +1,5 @@ # @mastra/code-sdk -## 1.19.1-alpha.7 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/client-js@1.60.1-alpha.6 - -## 1.19.1-alpha.6 - -### Patch Changes - -- Fixed custom OpenAI-compatible providers so they only ever authenticate with the API key saved on the provider itself. ([#29879](https://github.com/mastra-ai/mastra/pull/29879)) - - - A custom provider is no longer given the saved credential of another provider when their names match (for example a custom provider called "OpenAI"). - - A Mastra Gateway model (`mastra/...`) never runs on a custom provider that shares its id, with or without a gateway key. - - Requests to a custom provider no longer follow redirects, so its API key is never sent on to another address. - - A custom provider without an API key now works when sign-in is enabled, instead of failing with a missing credential error. - - If a custom provider in `settings.json` has no `apiKey` and relied on a key you saved for the provider it is named after (for example with `/api-keys`), set `apiKey` on the custom provider itself. - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938), [`464810d`](https://github.com/mastra-ai/mastra/commit/464810dcf84b942fbcc34e9171585b3d01f36ce2)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/pg@1.37.0-alpha.3 - - @mastra/client-js@1.60.1-alpha.5 - - @mastra/libsql@1.31.0-alpha.2 - ## 1.19.1-alpha.5 ### Patch Changes diff --git a/mastracode/sdk/package.json b/mastracode/sdk/package.json index d2e5e6c32e1..5fd20c6c01e 100644 --- a/mastracode/sdk/package.json +++ b/mastracode/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/code-sdk", - "version": "1.19.1-alpha.7", + "version": "1.19.1-alpha.5", "description": "Mastra Code SDK: the agent core behind Mastra Code (everything except the TUI) — build your own UIs and surfaces on top of it", "type": "module", "publishConfig": { diff --git a/mastracode/tui/CHANGELOG.md b/mastracode/tui/CHANGELOG.md index 50052a8f505..b3ceb011ae6 100644 --- a/mastracode/tui/CHANGELOG.md +++ b/mastracode/tui/CHANGELOG.md @@ -1,33 +1,5 @@ # mastracode -## 0.50.1-alpha.7 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/code-sdk@1.19.1-alpha.7 - -## 0.50.1-alpha.6 - -### Patch Changes - -- Added an ESM-only `mastracode/run-tui` export so a launcher can start the Mastra Code TUI with extra session options, such as Knowledge and its scopes: ([#30371](https://github.com/mastra-ai/mastra/pull/30371)) - - ```ts - import { runTui } from 'mastracode/run-tui'; - - await runTui({ createMastraCode: { knowledge: { key: 'team', instance: knowledge }, scopes: ['org:acme'] } }); - ``` - - Options given here replace the values Mastra Code would pass for the same keys, and apply to the interactive local TUI only. The `mastracode` command behaves as before. - -- Updated dependencies [[`944bb3a`](https://github.com/mastra-ai/mastra/commit/944bb3ab0fdcd23debbc4090d50c7abdcfacc874), [`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938), [`464810d`](https://github.com/mastra-ai/mastra/commit/464810dcf84b942fbcc34e9171585b3d01f36ce2)]: - - @mastra/code-sdk@1.19.1-alpha.6 - - @mastra/core@1.84.0-alpha.5 - - @mastra/pg@1.37.0-alpha.3 - - @mastra/libsql@1.31.0-alpha.2 - ## 0.50.1-alpha.5 ### Patch Changes diff --git a/mastracode/tui/package.json b/mastracode/tui/package.json index 7eac0c32e71..afc9f4bc0a8 100644 --- a/mastracode/tui/package.json +++ b/mastracode/tui/package.json @@ -1,6 +1,6 @@ { "name": "mastracode", - "version": "0.50.1-alpha.7", + "version": "0.50.1-alpha.5", "description": "", "type": "module", "files": [ diff --git a/observability/arize/CHANGELOG.md b/observability/arize/CHANGELOG.md index 09af94a92f1..b0392000498 100644 --- a/observability/arize/CHANGELOG.md +++ b/observability/arize/CHANGELOG.md @@ -1,15 +1,5 @@ # @mastra/arize -## 1.3.31-alpha.1 - -### Patch Changes - -- Raised the minimum versions of the OpenTelemetry SDK and OTLP exporter dependencies (`@opentelemetry/sdk-trace-base` and `@opentelemetry/core` `^2.12.1`, OTLP exporters `^0.223.1`) so they no longer resolve to releases that pin `@opentelemetry/resources` 2.12.0, which is affected by security advisory GHSA-qrww-3xmv-qhgm. If your project also depends on OpenTelemetry packages directly, check that they resolve `@opentelemetry/resources` 2.12.1 or later on the 2.x line, or 3.1.1 or later on the 3.x line. ([#30580](https://github.com/mastra-ai/mastra/pull/30580)) - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`93b823a`](https://github.com/mastra-ai/mastra/commit/93b823a8472ddf30176e39606ab5ffbab6e01fb8), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/otel-exporter@1.5.3-alpha.1 - ## 1.3.31-alpha.0 ### Patch Changes diff --git a/observability/arize/package.json b/observability/arize/package.json index 1270d405d4a..611fd7df72d 100644 --- a/observability/arize/package.json +++ b/observability/arize/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/arize", - "version": "1.3.31-alpha.1", + "version": "1.3.31-alpha.0", "description": "Arize observability provider for Mastra - includes tracing and future observability features", "type": "module", "main": "dist/index.js", diff --git a/observability/arthur/CHANGELOG.md b/observability/arthur/CHANGELOG.md index 5708fdaf7d6..cedb85f7405 100644 --- a/observability/arthur/CHANGELOG.md +++ b/observability/arthur/CHANGELOG.md @@ -1,15 +1,5 @@ # @mastra/arthur -## 0.4.31-alpha.1 - -### Patch Changes - -- Raised the minimum versions of the OpenTelemetry SDK and OTLP exporter dependencies (`@opentelemetry/sdk-trace-base` and `@opentelemetry/core` `^2.12.1`, OTLP exporters `^0.223.1`) so they no longer resolve to releases that pin `@opentelemetry/resources` 2.12.0, which is affected by security advisory GHSA-qrww-3xmv-qhgm. If your project also depends on OpenTelemetry packages directly, check that they resolve `@opentelemetry/resources` 2.12.1 or later on the 2.x line, or 3.1.1 or later on the 3.x line. ([#30580](https://github.com/mastra-ai/mastra/pull/30580)) - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`93b823a`](https://github.com/mastra-ai/mastra/commit/93b823a8472ddf30176e39606ab5ffbab6e01fb8), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/otel-exporter@1.5.3-alpha.1 - ## 0.4.31-alpha.0 ### Patch Changes diff --git a/observability/arthur/package.json b/observability/arthur/package.json index eb62117e858..d0e787c2aab 100644 --- a/observability/arthur/package.json +++ b/observability/arthur/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/arthur", - "version": "0.4.31-alpha.1", + "version": "0.4.31-alpha.0", "description": "Arthur AI observability provider for Mastra - exports traces using OpenInference semantic conventions", "type": "module", "main": "dist/index.js", diff --git a/observability/laminar/CHANGELOG.md b/observability/laminar/CHANGELOG.md index b1354873c9a..568ecebe7a5 100644 --- a/observability/laminar/CHANGELOG.md +++ b/observability/laminar/CHANGELOG.md @@ -1,14 +1,5 @@ # @mastra/laminar -## 1.3.33-alpha.1 - -### Patch Changes - -- Raised the minimum versions of the OpenTelemetry SDK and OTLP exporter dependencies (`@opentelemetry/sdk-trace-base` and `@opentelemetry/core` `^2.12.1`, OTLP exporters `^0.223.1`) so they no longer resolve to releases that pin `@opentelemetry/resources` 2.12.0, which is affected by security advisory GHSA-qrww-3xmv-qhgm. If your project also depends on OpenTelemetry packages directly, check that they resolve `@opentelemetry/resources` 2.12.1 or later on the 2.x line, or 3.1.1 or later on the 3.x line. ([#30580](https://github.com/mastra-ai/mastra/pull/30580)) - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - ## 1.3.33-alpha.0 ### Patch Changes diff --git a/observability/laminar/package.json b/observability/laminar/package.json index 25082b33b61..b5e656b17c6 100644 --- a/observability/laminar/package.json +++ b/observability/laminar/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/laminar", - "version": "1.3.33-alpha.1", + "version": "1.3.33-alpha.0", "description": "Laminar observability provider for Mastra - tracing + scoring export", "type": "module", "main": "dist/index.js", diff --git a/observability/langfuse/CHANGELOG.md b/observability/langfuse/CHANGELOG.md index 36b6fbd755d..a19a82681b9 100644 --- a/observability/langfuse/CHANGELOG.md +++ b/observability/langfuse/CHANGELOG.md @@ -1,13 +1,5 @@ # @mastra/langfuse -## 1.6.7-alpha.1 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`93b823a`](https://github.com/mastra-ai/mastra/commit/93b823a8472ddf30176e39606ab5ffbab6e01fb8), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/otel-exporter@1.5.3-alpha.1 - ## 1.6.7-alpha.0 ### Patch Changes diff --git a/observability/langfuse/package.json b/observability/langfuse/package.json index de7e4e125ee..eae00c78464 100644 --- a/observability/langfuse/package.json +++ b/observability/langfuse/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/langfuse", - "version": "1.6.7-alpha.1", + "version": "1.6.7-alpha.0", "description": "Langfuse observability provider for Mastra - uses official Langfuse v5 SDK", "type": "module", "main": "dist/index.js", diff --git a/observability/otel-bridge/CHANGELOG.md b/observability/otel-bridge/CHANGELOG.md index fd6f97aa720..d44ca1bb824 100644 --- a/observability/otel-bridge/CHANGELOG.md +++ b/observability/otel-bridge/CHANGELOG.md @@ -1,13 +1,5 @@ # @mastra/otel-bridge -## 1.5.23-alpha.1 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`93b823a`](https://github.com/mastra-ai/mastra/commit/93b823a8472ddf30176e39606ab5ffbab6e01fb8), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/otel-exporter@1.5.3-alpha.1 - ## 1.5.23-alpha.0 ### Patch Changes diff --git a/observability/otel-bridge/package.json b/observability/otel-bridge/package.json index 3916dc2993b..12139543a10 100644 --- a/observability/otel-bridge/package.json +++ b/observability/otel-bridge/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/otel-bridge", - "version": "1.5.23-alpha.1", + "version": "1.5.23-alpha.0", "description": "OpenTelemetry observability bridge for Mastra", "type": "module", "main": "dist/index.js", diff --git a/observability/otel-bridge/src/bridge.test.ts b/observability/otel-bridge/src/bridge.test.ts index c63d1d8fa21..6a622a29f79 100644 --- a/observability/otel-bridge/src/bridge.test.ts +++ b/observability/otel-bridge/src/bridge.test.ts @@ -15,7 +15,7 @@ import { InternalSpans, SamplingStrategyType, SpanType, TracingEventType } from import { InMemoryStore } from '@mastra/core/storage'; import { createTool } from '@mastra/core/tools'; import { DefaultObservabilityInstance, Observability, TestExporter } from '@mastra/observability'; -import { context, isSpanContextValid, logs as coreLogs, trace } from '@opentelemetry/api'; +import { context, isSpanContextValid, trace } from '@opentelemetry/api'; import { logs as otelLogs, SeverityNumber } from '@opentelemetry/api-logs'; import { InMemoryLogRecordExporter, LoggerProvider, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs'; import { BasicTracerProvider, InMemorySpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'; @@ -1010,88 +1010,6 @@ describe('OtelBridge', () => { }); }); - // An app on OpenTelemetry JS SDK 3 registers its LoggerProvider with `logs` - // from `@opentelemetry/api`. That registry is separate from the one in - // `@opentelemetry/api-logs`, which SDK 2 apps use. (#29695) - describe('LoggerProvider registered through @opentelemetry/api', () => { - function makeLogEvent(message: string): LogEvent { - return { type: 'log', log: { logId: 'log-1', timestamp: new Date(), level: 'info', message } }; - } - - function makeProvider() { - const exporter = new InMemoryLogRecordExporter(); - const provider = new LoggerProvider({ processors: [new SimpleLogRecordProcessor({ exporter })] }); - return { exporter, provider }; - } - - /** Runs `fn` with nothing in the api-logs registry, as in an app that only has SDK 3. */ - async function withOnlyCoreRegistry(fn: () => Promise): Promise { - otelLogs.disable(); - try { - await fn(); - } finally { - coreLogs.disable(); - otelLogs.setGlobalLoggerProvider(loggerProvider); - } - } - - it('delivers Mastra logs to the app log exporter (#29695)', async () => { - await withOnlyCoreRegistry(async () => { - const { exporter, provider } = makeProvider(); - coreLogs.setGlobalLoggerProvider(provider); - - const bridge = new OtelBridge(); - await bridge.onLogEvent(makeLogEvent('from an SDK 3 app')); - - expect(exporter.getFinishedLogRecords().map(record => record.body)).toEqual(['from an SDK 3 app']); - await bridge.shutdown(); - }); - }); - - it('delivers Mastra logs when the provider is registered after the bridge is constructed', async () => { - await withOnlyCoreRegistry(async () => { - const bridge = new OtelBridge(); - await bridge.onLogEvent(makeLogEvent('before registration')); - - const { exporter, provider } = makeProvider(); - coreLogs.setGlobalLoggerProvider(provider); - await bridge.onLogEvent(makeLogEvent('after registration')); - - expect(exporter.getFinishedLogRecords().map(record => record.body)).toEqual(['after registration']); - await bridge.shutdown(); - }); - }); - - it('flushes the provider on flush()', async () => { - await withOnlyCoreRegistry(async () => { - const { provider } = makeProvider(); - const forceFlush = vi.spyOn(provider, 'forceFlush'); - coreLogs.setGlobalLoggerProvider(provider); - - const bridge = new OtelBridge(); - await bridge.flush(); - - expect(forceFlush).toHaveBeenCalledTimes(1); - await bridge.shutdown(); - }); - }); - - it('says once at debug level that logs are not exported when no provider is registered anywhere', async () => { - await withOnlyCoreRegistry(async () => { - const debug = vi.fn(); - const bridge = new OtelBridge(); - bridge.__setLogger({ debug, info: vi.fn(), warn: vi.fn(), error: vi.fn() } as any); - - await bridge.onLogEvent(makeLogEvent('dropped')); - await bridge.onLogEvent(makeLogEvent('dropped again')); - - const notes = debug.mock.calls.filter(([message]) => String(message).includes('logger provider')); - expect(notes).toHaveLength(1); - await bridge.shutdown(); - }); - }); - }); - describe('custom providers', () => { it('should use a custom tracerProvider to create spans without touching the global', async () => { trace.disable(); diff --git a/observability/otel-bridge/src/bridge.ts b/observability/otel-bridge/src/bridge.ts index 57292ac9fa3..eb4337a0efd 100644 --- a/observability/otel-bridge/src/bridge.ts +++ b/observability/otel-bridge/src/bridge.ts @@ -26,7 +26,6 @@ import { TracingEventType } from '@mastra/core/observability'; import { BaseExporter, getExternalParentId } from '@mastra/observability'; import type { BaseExporterConfig } from '@mastra/observability'; import { SpanConverter, convertLog, getSpanKind } from '@mastra/otel-exporter'; -import * as otelApi from '@opentelemetry/api'; import { trace as otelTrace, context as otelContext, isSpanContextValid, TraceFlags } from '@opentelemetry/api'; import type { Span as OtelSpan, Context as OtelContext, Link, TracerProvider, Tracer } from '@opentelemetry/api'; import { logs as otelLogs } from '@opentelemetry/api-logs'; @@ -44,41 +43,6 @@ function toOtelLinks(links: SpanLink[]): Link[] { .map(context => ({ context })); } -type LogsApi = { getLoggerProvider(): LoggerProvider }; - -/** - * The global logs registries an app can register its LoggerProvider with. - * - * OpenTelemetry JS SDK 3 registers through `logs` from `@opentelemetry/api` - * (1.10 and later). SDK 2 registers through `logs` from `@opentelemetry/api-logs`. - * The two registries do not see each other, so the bridge has to look at both. - * - * `logs` is read off the namespace because `@opentelemetry/api` below 1.10 does - * not export it, and a named import would fail to link there. - */ -function globalLogsApis(): LogsApi[] { - const coreLogs = (otelApi as { logs?: LogsApi }).logs; - return coreLogs ? [coreLogs, otelLogs] : [otelLogs]; -} - -/** With no provider registered, both logs APIs return their own proxy, which drops every record. */ -function isUnregisteredProxy(provider: LoggerProvider): boolean { - return typeof (provider as { _setDelegate?: unknown })._setDelegate === 'function'; -} - -/** - * The LoggerProvider the app registered globally, from whichever registry holds one. - * `registered` is false when neither does, and `provider` is then a no-op proxy. - */ -function getGlobalLoggerProvider(): { provider: LoggerProvider; registered: boolean } { - const apis = globalLogsApis(); - for (const api of apis) { - const provider = api.getLoggerProvider(); - if (!isUnregisteredProxy(provider)) return { provider, registered: true }; - } - return { provider: apis[0]!.getLoggerProvider(), registered: false }; -} - const SETUP_DOCS_URL = 'https://mastra.ai/reference/observability/tracing/bridges/otel#setup-requirements'; export type OtelBridgeConfig = BaseExporterConfig & { @@ -113,7 +77,6 @@ export type OtelBridgeConfig = BaseExporterConfig & { export class OtelBridge extends BaseExporter implements ObservabilityBridge { name = 'otel'; private tracerProvider: TracerProvider; - /** The provider passed in config, or the global one the current `otelLogger` came from. */ private loggerProvider: LoggerProvider; private otelTracer: Tracer; private otelLogger: OtelLogger; @@ -123,7 +86,6 @@ export class OtelBridge extends BaseExporter implements ObservabilityBridge { private hasCustomTracerProvider: boolean; private hasCustomLoggerProvider: boolean; private warnedNoTracerProvider = false; - private notedNoLoggerProvider = false; constructor(config: OtelBridgeConfig = {}) { super(config); @@ -131,37 +93,10 @@ export class OtelBridge extends BaseExporter implements ObservabilityBridge { this.hasCustomLoggerProvider = config.loggerProvider !== undefined; this.tracerProvider = config.tracerProvider ?? otelTrace.getTracerProvider(); this.otelTracer = this.tracerProvider.getTracer('@mastra/otel-bridge', '1.0.0'); - this.loggerProvider = config.loggerProvider ?? getGlobalLoggerProvider().provider; + this.loggerProvider = config.loggerProvider ?? otelLogs.getLoggerProvider(); this.otelLogger = this.loggerProvider.getLogger('@mastra/otel-bridge', '1.0.0'); } - /** - * The logger to emit through. - * - * Without a `loggerProvider` in config, the global provider is looked up on - * every call: the OTEL SDK is often registered after the bridge is constructed, - * and which registry it lands in depends on the SDK line the app is on. - */ - private resolveLogger(): OtelLogger { - if (this.hasCustomLoggerProvider) return this.otelLogger; - - const { provider, registered } = getGlobalLoggerProvider(); - if (provider !== this.loggerProvider) { - this.loggerProvider = provider; - this.otelLogger = provider.getLogger('@mastra/otel-bridge', '1.0.0'); - } - if (!registered && !this.notedNoLoggerProvider) { - this.notedNoLoggerProvider = true; - this.logger.debug( - '[OtelBridge] No OpenTelemetry logger provider is registered globally, so Mastra logs will not be ' + - 'exported through OpenTelemetry. Register one (for example with `logRecordProcessors` on `NodeSDK`, or ' + - '`logs.setGlobalLoggerProvider(provider)`), or pass it directly with `new OtelBridge({ loggerProvider })`. ' + - `See ${SETUP_DOCS_URL}`, - ); - } - return this.otelLogger; - } - /** * Handle Mastra tracing events * @@ -181,7 +116,7 @@ export class OtelBridge extends BaseExporter implements ObservabilityBridge { * * If the user has not registered a LoggerProvider (e.g. via @opentelemetry/sdk-logs * or NodeSDK's logRecordProcessor option), the API returns a no-op logger and - * emit() is a no-op — the bridge degrades gracefully, with one debug line. + * emit() is a silent no-op — the bridge degrades gracefully. * * Trace correlation: * - If the log carries a spanId we have an OTEL span for, emit under that span's @@ -202,7 +137,7 @@ export class OtelBridge extends BaseExporter implements ObservabilityBridge { const logContext = this.resolveLogContext(params.traceId, params.spanId); - this.resolveLogger().emit({ + this.otelLogger.emit({ timestamp: params.timestamp, severityNumber: params.severityNumber, severityText: params.severityText, @@ -540,10 +475,10 @@ export class OtelBridge extends BaseExporter implements ObservabilityBridge { */ async flush(): Promise { // Re-resolve the global providers on every flush: the OTEL SDK is often - // registered after the bridge is constructed, and the logs API only returns - // the real provider once one has been registered. + // registered after the bridge is constructed, and `otelLogs.getLoggerProvider()` + // only returns the real provider once one has been registered. const tracerProvider = this.hasCustomTracerProvider ? this.tracerProvider : otelTrace.getTracerProvider(); - const loggerProvider = this.hasCustomLoggerProvider ? this.loggerProvider : getGlobalLoggerProvider().provider; + const loggerProvider = this.hasCustomLoggerProvider ? this.loggerProvider : otelLogs.getLoggerProvider(); await this.flushProvider(tracerProvider, 'tracer'); await this.flushProvider(loggerProvider, 'logger'); } diff --git a/observability/otel-exporter/CHANGELOG.md b/observability/otel-exporter/CHANGELOG.md index 2e216b66868..a5d857c4950 100644 --- a/observability/otel-exporter/CHANGELOG.md +++ b/observability/otel-exporter/CHANGELOG.md @@ -1,14 +1,5 @@ # @mastra/otel-exporter -## 1.5.3-alpha.1 - -### Patch Changes - -- Raised the minimum versions of the OpenTelemetry SDK and OTLP exporter dependencies (`@opentelemetry/sdk-trace-base` and `@opentelemetry/core` `^2.12.1`, OTLP exporters `^0.223.1`) so they no longer resolve to releases that pin `@opentelemetry/resources` 2.12.0, which is affected by security advisory GHSA-qrww-3xmv-qhgm. If your project also depends on OpenTelemetry packages directly, check that they resolve `@opentelemetry/resources` 2.12.1 or later on the 2.x line, or 3.1.1 or later on the 3.x line. ([#30580](https://github.com/mastra-ai/mastra/pull/30580)) - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - ## 1.5.3-alpha.0 ### Patch Changes diff --git a/observability/otel-exporter/package.json b/observability/otel-exporter/package.json index cf4a30c3668..a6e7821160b 100644 --- a/observability/otel-exporter/package.json +++ b/observability/otel-exporter/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/otel-exporter", - "version": "1.5.3-alpha.1", + "version": "1.5.3-alpha.0", "description": "OpenTelemetry observability exporter for Mastra - supports OTLP traces and logs with multiple cloud providers", "type": "module", "main": "dist/index.js", diff --git a/observability/sentry/CHANGELOG.md b/observability/sentry/CHANGELOG.md index ecdef95be1e..c947ef767fc 100644 --- a/observability/sentry/CHANGELOG.md +++ b/observability/sentry/CHANGELOG.md @@ -1,13 +1,5 @@ # @mastra/sentry -## 1.2.33-alpha.1 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`93b823a`](https://github.com/mastra-ai/mastra/commit/93b823a8472ddf30176e39606ab5ffbab6e01fb8), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/otel-exporter@1.5.3-alpha.1 - ## 1.2.33-alpha.0 ### Patch Changes diff --git a/observability/sentry/package.json b/observability/sentry/package.json index 5da21117d8b..58b31cb8309 100644 --- a/observability/sentry/package.json +++ b/observability/sentry/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/sentry", - "version": "1.2.33-alpha.1", + "version": "1.2.33-alpha.0", "description": "Sentry AI observability exporter for Mastra", "type": "module", "main": "dist/index.js", diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 724c31ede6d..f7bee79ad69 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -1,35 +1,5 @@ # mastra -## 1.40.0-alpha.6 - -### Patch Changes - -- The Factory sidebar now groups sessions by board and shows a second line under each session by default, with when it last changed and its pull request. Turn on **Compact view** or set **Group** to **None** in the sidebar's properties menu to get one line per session or a single list back. Settings you already changed keep their values; the rest follow the new defaults. ([#30656](https://github.com/mastra-ai/mastra/pull/30656)) - -- Factory **Settings** now shows theme and completion sound on **My account**, next to your profile and log out, instead of on a separate **Preferences** page. Settings opens on **My account**, and old Preferences links go there. ([#30658](https://github.com/mastra-ai/mastra/pull/30658)) - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/deployer@1.84.0-alpha.6 - -## 1.40.0-alpha.5 - -### Patch Changes - -- The Factory **Settings › Tools** page shows how many tools sessions get from each Mastra Connect connection. Expand one to see its tools with their descriptions, which ones ask for approval, and which ones Factory leaves out. With a `tools` option, a connection the code doesn't use shows no tools, and the code's other tools are listed under **Other tools from code**. ([#30610](https://github.com/mastra-ai/mastra/pull/30610)) - -- The Factory **Settings › Tools** page lists a project's Mastra Connect connections when the Factory sets its session tools in code, with a note that the `tools` option decides which of their tools sessions get. When Connect isn't set up, it names the missing Platform credentials or `MASTRA_PROJECT_ID` (#30579). ([#30607](https://github.com/mastra-ai/mastra/pull/30607)) - -- Added `mastra api factory work-item session-repository `. It shows the repository a session on a Factory card starts in, or why the card has none. ([#30609](https://github.com/mastra-ai/mastra/pull/30609)) - -- Fixed board cards showing a different session status than the sidebar. A card with a suggested run and a running session now shows it waits on you on the board too, and a card with one working and one starting session shows it working. ([#30624](https://github.com/mastra-ai/mastra/pull/30624)) - -- Fixed the session status in Factory's sidebar and board. A person's own session now shows "Waiting on you" while its agent waits for their answer, instead of "Working". A session now shows "Working" while it runs on a thread opened after its first one, such as a new thread or a Slack conversation. A session shows "Initializing" only while a run waits on its first setup, so a session whose setup never finished, or that never ran, no longer stays stuck on "Initializing". ([#30627](https://github.com/mastra-ai/mastra/pull/30627)) - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/deployer@1.84.0-alpha.5 - ## 1.40.0-alpha.4 ### Minor Changes diff --git a/packages/cli/package.json b/packages/cli/package.json index a0c4ce4afa6..3677a058061 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "mastra", - "version": "1.40.0-alpha.6", + "version": "1.40.0-alpha.4", "license": "Apache-2.0", "description": "cli for mastra", "type": "module", diff --git a/packages/cli/src/commands/api/descriptors.test.ts b/packages/cli/src/commands/api/descriptors.test.ts index 36f4faeb37b..64b77cad46a 100644 --- a/packages/cli/src/commands/api/descriptors.test.ts +++ b/packages/cli/src/commands/api/descriptors.test.ts @@ -151,7 +151,6 @@ describe('api command descriptors', () => { factoryBoardDelete: ['boardDelete', ['id', 'boardKey'], true, true, false], factoryBoardReset: ['boardReset', ['id', 'boardKey'], true, true, false], factorySkills: ['skillList', [], true, false, false], - factorySkillCreate: ['skillCreate', ['id'], true, true, false], factorySkillUpdate: ['skillOverrideSave', ['id', 'name'], true, true, false], factorySkillRevert: ['skillOverrideRevert', ['id', 'name'], false, false, false], 'factoryIntake-routeList': ['intakeRouteList', ['id'], true, false, false], diff --git a/packages/cli/src/commands/api/factory-route-metadata.generated.ts b/packages/cli/src/commands/api/factory-route-metadata.generated.ts index 3d2e09a68ba..c9ef27e8c5b 100644 --- a/packages/cli/src/commands/api/factory-route-metadata.generated.ts +++ b/packages/cli/src/commands/api/factory-route-metadata.generated.ts @@ -76,7 +76,7 @@ export const FACTORY_API_ROUTE_METADATA = { "contractKey": "skillOverrideRevert", "method": "DELETE", "path": "/web/factory/projects/:id/skills/:name", - "description": "Revert a project's edited Factory skill to its original SKILL.md, or delete a skill the project created", + "description": "Revert a project's edited Factory skill to its original SKILL.md", "pathParams": [ "id", "name" @@ -1111,25 +1111,6 @@ export const FACTORY_API_ROUTE_METADATA = { "kind": "record" } }, - "POST /web/factory/projects/:id/skills": { - "contractKey": "skillCreate", - "method": "POST", - "path": "/web/factory/projects/:id/skills", - "description": "Create a skill for one Factory project", - "pathParams": [ - "id" - ], - "queryParams": [], - "bodyParams": [ - "content", - "name" - ], - "hasQuery": false, - "hasBody": true, - "responseShape": { - "kind": "single" - } - }, "POST /web/factory/projects/:id/work-items": { "contractKey": "workItemCreate", "method": "POST", @@ -1245,7 +1226,7 @@ export const FACTORY_API_ROUTE_METADATA = { "contractKey": "skillOverrideSave", "method": "PUT", "path": "/web/factory/projects/:id/skills/:name", - "description": "Save a project's SKILL.md for a Factory skill: an edit of an app skill, or a skill it created", + "description": "Save a project's edited SKILL.md for a Factory skill", "pathParams": [ "id", "name" @@ -1433,18 +1414,11 @@ export const FACTORY_API_ROUTE_SCHEMAS = { "type": "object", "properties": { "skill": { - "anyOf": [ - { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": {} - }, - { - "type": "null" - } - ] + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": {} } }, "required": [ @@ -12564,66 +12538,6 @@ export const FACTORY_API_ROUTE_SCHEMAS = { "additionalProperties": {} } }, - "POST /web/factory/projects/:id/skills": { - "path": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "id": { - "type": "string", - "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" - } - }, - "required": [ - "id" - ] - }, - "body": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "name": { - "$ref": "#/$defs/__schema0" - }, - "content": { - "$ref": "#/$defs/__schema1" - } - }, - "required": [ - "name", - "content" - ], - "additionalProperties": false, - "$defs": { - "__schema0": { - "type": "string", - "maxLength": 64, - "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" - }, - "__schema1": { - "type": "string", - "minLength": 1, - "maxLength": 200000 - } - } - }, - "response": { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "type": "object", - "properties": { - "skill": { - "type": "object", - "propertyNames": { - "type": "string" - }, - "additionalProperties": {} - } - }, - "required": [ - "skill" - ] - } - }, "POST /web/factory/projects/:id/work-items": { "path": { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -13445,7 +13359,6 @@ export const FACTORY_API_ROUTE_CATALOG = { "intakeRouteAgain": "POST /web/factory/projects/:id/intake/not-routed/:decisionId/route-again", "intakeTest": "POST /web/factory/projects/:id/intake/test", "workItemStart": "POST /web/factory/projects/:id/runs/start", - "skillCreate": "POST /web/factory/projects/:id/skills", "workItemCreate": "POST /web/factory/projects/:id/work-items", "workItemAutomationRun": "POST /web/factory/projects/:id/work-items/:workItemId/automation-runs", "workItemTransition": "POST /web/factory/projects/:id/work-items/:workItemId/transition", diff --git a/packages/cli/src/commands/api/index.ts b/packages/cli/src/commands/api/index.ts index 2ab6bcc3aea..7a75ca36e00 100644 --- a/packages/cli/src/commands/api/index.ts +++ b/packages/cli/src/commands/api/index.ts @@ -873,21 +873,9 @@ export function registerApiCommand(program: CommanderCommand): void { const factorySkill = factory .command('skill') - .description("Create and edit a Factory project's skills; organization admins only"); - addAction(factorySkill, 'create', FACTORY_API_ROUTE_CATALOG.skillCreate, { - description: 'Create a skill for one Factory project; the frontmatter name must match the skill name', - input: 'required', - routePlacement: 'origin', - examples: [ - { - description: 'Create a release-notes skill for one project', - command: `mastra api factory skill create '{"name":"release-notes","content":"---\\nname: release-notes\\ndescription: Write release notes for a merged change\\n---\\n\\n# Release notes\\n"}'`, - }, - ], - }); + .description("Edit a Factory project's skills; organization admins only"); addAction(factorySkill, 'update', FACTORY_API_ROUTE_CATALOG.skillOverrideSave, { - description: - 'Save a SKILL.md for one Factory project: an edit of an app skill, or a skill the project created; the frontmatter name must match the skill name', + description: 'Save an edited SKILL.md for one Factory project; the frontmatter name must match the skill name', input: 'required', routePlacement: 'origin', examples: [ @@ -898,8 +886,7 @@ export function registerApiCommand(program: CommanderCommand): void { ], }); addAction(factorySkill, 'revert', FACTORY_API_ROUTE_CATALOG.skillOverrideRevert, { - description: - "Revert a Factory project's edit so the skill uses its original SKILL.md, or delete a skill the project created", + description: "Revert a Factory project's edit so the skill uses its original SKILL.md", routePlacement: 'origin', }); diff --git a/packages/connect/CHANGELOG.md b/packages/connect/CHANGELOG.md index 9d0b74a7595..062c6d50c75 100644 --- a/packages/connect/CHANGELOG.md +++ b/packages/connect/CHANGELOG.md @@ -1,14 +1,5 @@ # @mastra/connect -## 1.4.1-alpha.2 - -### Patch Changes - -- Fixed `posthog_run_query` failing provider-response validation whenever PostHog returned column types, which it does for every query with columns, even `select 1`. PostHog returns column types as `[columnName, clickhouseType]` pairs, such as `[["count()", "UInt64"]]`, and the tool now accepts them and returns them in that shape. The inferred type of `types` in the tool's output changes from `string[]` to `[string, string][]`, and a plain string entry, which PostHog never sends, is now rejected. Fixes [#30528](https://github.com/mastra-ai/mastra/issues/30528). ([#30541](https://github.com/mastra-ai/mastra/pull/30541)) - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - ## 1.4.1-alpha.1 ### Patch Changes diff --git a/packages/connect/package.json b/packages/connect/package.json index 91157ea17d3..1a93eb9b851 100644 --- a/packages/connect/package.json +++ b/packages/connect/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/connect", - "version": "1.4.1-alpha.2", + "version": "1.4.1-alpha.1", "description": "Use Mastra platform integration connections as agent toolsets", "type": "module", "main": "./dist/index.js", diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index d110e1b9408..4518455f77d 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -1,57 +1,5 @@ # @mastra/core -## 1.84.0-alpha.6 - -### Minor Changes - -- Knowledge storage can supply scope declarations, access rules included. ([#29428](https://github.com/mastra-ai/mastra/pull/29428)) - - A store returns declarations from `getScopeDeclarations()` (none by default). Knowledge merges them under its config's: the config wins on a key both declare, and a declaration that doesn't compile is skipped with a warning. When stored scopes come from a skipped declaration, the declaration check's error names that declaration and why it was skipped, so it can be fixed in the store. The store's answer is reused for 30 seconds and read again after `renameScopeDeclaration`, so a declaration the store adds, removes or changes (access rules included) applies within that window without a store read on every call. Revoking access through the store can therefore take up to 30 seconds to take effect. - - ```ts - class ImportingKnowledgeStorage extends InMemoryKnowledgeStorage { - override async getScopeDeclarations() { - return { - 'imports:$name': {}, - 'linear:$account:$connection': { access: [{ principal: 'imports:all', role: 'viewer' }] }, - }; - } - } - ``` - - Runs that hold `imports:all` then read every Linear connection's pages. - -## 1.84.0-alpha.5 - -### Minor Changes - -- Added `knowledge.movePage()` to move a page, with its child pages, to a new parent or scope from your app. The page keeps its ID, notes, pins and embeddings, and links by path follow it, so a sync that sees a page move at its source no longer has to remove and re-create it. ([#30631](https://github.com/mastra-ai/mastra/pull/30631)) - - ```ts - await knowledge.movePage({ scope: 'docs:acme', path: 'inbox/plan', parent: 'projects/q4' }); - ``` - - Links by name now stay correct when a page moves or a new page takes a name. A page moved to another scope, and every page under it, re-resolves its `[[Name]]` links in the new scope. A link that pointed at one page by name stops resolving once a second page answers to that name. When more than 99 pages share that name, the write logs a warning and `knowledge.reindexLinks()` repairs the rest. - -- Added `knowledge.reembed()` to embed Knowledge pages and notes that already exist, such as content written before `vector` and `embedder` were configured or after switching embedders. It runs in batches with a resumable cursor, doesn't change the pages, lists failures and pages over the chunk cap, and stops early with a cursor when the embedder keeps rate limiting. ([#30603](https://github.com/mastra-ai/mastra/pull/30603)) - - ```ts - let cursor: string | undefined; - do { - const result = await knowledge.reembed({ scope: 'org:acme', cursor }); - if (result.rateLimited) await new Promise(resolve => setTimeout(resolve, 60_000)); - cursor = result.nextCursor; - } while (cursor); - ``` - -### Patch Changes - -- Fixed slow handling of Gateway base URLs and Supabase URLs that contain very long runs of `/`. The resulting URLs are unchanged. ([#30577](https://github.com/mastra-ai/mastra/pull/30577)) - -- Fixed `run.restart()` running a step again when the workflow run finished or suspended after `restart()` read it but before `restart()` took it over from the process running it. Restarting a run that finished now returns its stored result, and restarting a run that suspended fails with the usual "This workflow run was not active" error. ([#30399](https://github.com/mastra-ai/mastra/pull/30399)) - -- Fixed workflow `.sleep()` and `.sleepUntil()` waits longer than about 24.8 days ending almost immediately. The next step now runs only after the full wait, on the default and evented engines. ([#30395](https://github.com/mastra-ai/mastra/pull/30395)) - ## 1.84.0-alpha.4 ### Minor Changes diff --git a/packages/core/package.json b/packages/core/package.json index 949cfe5b907..120edca6535 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/core", - "version": "1.84.0-alpha.6", + "version": "1.84.0-alpha.4", "license": "Apache-2.0", "type": "module", "main": "dist/index.js", diff --git a/packages/core/src/agent/__tests__/mastra-gateway-duck-typing.test.ts b/packages/core/src/agent/__tests__/mastra-gateway-duck-typing.test.ts index caf26e4fc3d..4802fafdf11 100644 --- a/packages/core/src/agent/__tests__/mastra-gateway-duck-typing.test.ts +++ b/packages/core/src/agent/__tests__/mastra-gateway-duck-typing.test.ts @@ -1,4 +1,5 @@ -import { describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { ModelRouterLanguageModel } from '../../llm/model/router'; import { Agent } from '../agent'; describe('mastra gateway duck typing', () => { @@ -71,4 +72,106 @@ describe('mastra gateway duck typing', () => { expect.anything(), ); }); + + describe('with a Mastra gateway router model', () => { + const WARNING = 'No memory is configured but resourceId and threadId were passed in args'; + + afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + }); + + function routerModel(apiKey: string) { + vi.stubEnv('MASTRA_GATEWAY_API_KEY', apiKey); + const model = new ModelRouterLanguageModel('mastra/openai/gpt-4o'); + expect(model.gatewayId).toBe('mastra'); + const respond = async () => + ({ + stream: new ReadableStream({ + start(controller) { + controller.enqueue({ type: 'text-start', id: 'text-1' }); + controller.enqueue({ type: 'text-delta', id: 'text-1', delta: 'ok' }); + controller.enqueue({ type: 'text-end', id: 'text-1' }); + controller.enqueue({ + type: 'finish', + finishReason: 'stop', + usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 }, + }); + controller.close(); + }, + }), + rawCall: { rawPrompt: null, rawSettings: {} }, + warnings: [], + }) as any; + vi.spyOn(model, 'doStream').mockImplementation(respond); + vi.spyOn(model, 'doGenerate').mockImplementation(respond); + return model; + } + + async function run(model: ModelRouterLanguageModel) { + const warn = vi.fn(); + const debug = vi.fn(); + const agent = new Agent({ + id: 'test-agent', + name: 'test-agent', + instructions: 'You are a helpful assistant.', + model, + }); + agent.__setLogger({ debug, info: vi.fn(), warn, error: vi.fn(), trace: vi.fn() } as any); + const result = await agent.generate('hello', { + memory: { thread: { id: 'thread-1' }, resource: 'resource-1' }, + }); + return { result, warn, debug }; + } + + const settle = () => new Promise(resolve => setTimeout(resolve, 0)); + + it('warns for an organization key, whose memory stays local', async () => { + const { result, warn } = await run(routerModel('mskv2_org-key')); + + expect(result.text).toBe('ok'); + await vi.waitFor(() => expect(warn).toHaveBeenCalledWith(WARNING, { agent: 'test-agent' })); + }); + + it('does not warn for a project key, whose memory the gateway keeps', async () => { + const model = routerModel('msk_0123456789abcdef0123456789abcdef'); + const check = vi.spyOn(model, 'isGatewayMemoryManaged'); + const { warn } = await run(model); + + await vi.waitFor(() => expect(check).toHaveBeenCalled()); + await expect(check.mock.results[0]!.value).resolves.toBe(true); + await settle(); + expect(warn).not.toHaveBeenCalledWith(WARNING, expect.anything()); + }); + + it('finishes the run and does not warn when the check fails', async () => { + const model = routerModel('mskv2_org-key'); + const check = vi.spyOn(model, 'isGatewayMemoryManaged').mockRejectedValue(new Error('credential unavailable')); + const { result, warn, debug } = await run(model); + + expect(result.text).toBe('ok'); + await vi.waitFor(() => expect(check).toHaveBeenCalled()); + await settle(); + expect(warn).not.toHaveBeenCalledWith(WARNING, expect.anything()); + expect(debug).toHaveBeenCalledWith('Could not tell whether the gateway manages memory for this model', { + agent: 'test-agent', + error: expect.objectContaining({ message: 'credential unavailable' }), + }); + }); + + it('does not wait for a slow check before running the model', async () => { + const model = routerModel('mskv2_org-key'); + let release: ((value: boolean) => void) | undefined; + vi.spyOn(model, 'isGatewayMemoryManaged').mockImplementation( + () => new Promise(resolve => (release = resolve)), + ); + const { result, warn } = await run(model); + + expect(result.text).toBe('ok'); + expect(warn).not.toHaveBeenCalledWith(WARNING, expect.anything()); + expect(release).toBeDefined(); + release!(false); + await vi.waitFor(() => expect(warn).toHaveBeenCalledWith(WARNING, { agent: 'test-agent' })); + }); + }); }); diff --git a/packages/core/src/agent/agent.ts b/packages/core/src/agent/agent.ts index df77b6d89be..de2431c2328 100644 --- a/packages/core/src/agent/agent.ts +++ b/packages/core/src/agent/agent.ts @@ -9281,14 +9281,31 @@ export class Agent< // Only warn for ids the caller passed in `memory` args. Reserved request-context ids are set // per request (auth middleware, AgentController) and inherited by every agent in that request, // including internal memory-less agents such as the OM Observer and Reflector. - if ( - options.memory?.resource && - options.memory?.thread && - !this.hasOwnMemory() && - !this.#knowledge && - !isGatewayModel - ) { - this.logger.warn('No memory is configured but resourceId and threadId were passed in args', { agent: this.name }); + if (options.memory?.resource && options.memory?.thread && !this.hasOwnMemory() && !this.#knowledge) { + const warnMissingMemory = () => + this.logger.warn('No memory is configured but resourceId and threadId were passed in args', { + agent: this.name, + }); + const gatewayModel = resolvedModel as unknown as { isGatewayMemoryManaged?: () => Promise }; + if (!isGatewayModel) { + warnMissingMemory(); + } else if (typeof gatewayModel.isGatewayMemoryManaged === 'function') { + // The gateway keeps memory only for some credentials, so ask the model. The check may + // resolve a credential, so it runs in the background and never delays or fails the run. + // A check that fails leaves the warning out, as it was before the model could answer. + void Promise.resolve() + .then(() => gatewayModel.isGatewayMemoryManaged!()) + .then( + managed => { + if (!managed) warnMissingMemory(); + }, + error => + this.logger.debug('Could not tell whether the gateway manages memory for this model', { + agent: this.name, + error, + }), + ); + } } // Apply null→undefined transform for OpenAI structured output validation. diff --git a/packages/core/src/agent/message-list/state/types.ts b/packages/core/src/agent/message-list/state/types.ts index dfda172a0e8..3ca9a47cf9e 100644 --- a/packages/core/src/agent/message-list/state/types.ts +++ b/packages/core/src/agent/message-list/state/types.ts @@ -40,7 +40,7 @@ export type MastraStepStartPart = { // surfaces (stream chunk, onError, result.error) and are never written to // thread history. Provider HTTP failures (AI SDK `APICallError`) also keep the // status code, a bounded copy of the response body, the provider request id, -// the model the request named and the provider facts a reload classifies by +// the model the request named, the origin it was sent to and the provider facts a reload classifies by // (every code, the provider's own reason sentence), because their `message` is // often just the HTTP status text. export type MastraErrorPart = { @@ -51,6 +51,12 @@ export type MastraErrorPart = { responseBody?: string; requestId?: string; modelId?: string; + /** + * Origin (scheme, host and port, e.g. `https://gateway-api.mastra.ai`) the failed model + * request was sent to, so a reader can tell which service answered. Never the path, query + * string or credentials. Absent on messages saved before it was recorded. + */ + requestOrigin?: string; } & ProviderErrorFacts; } & MastraPartExtensions; diff --git a/packages/core/src/error/index.ts b/packages/core/src/error/index.ts index 0ecc2116bfd..36c14665a39 100644 --- a/packages/core/src/error/index.ts +++ b/packages/core/src/error/index.ts @@ -15,5 +15,6 @@ export { providerErrorReason, providerModelId, providerRequestId, + providerRequestOrigin, } from './provider-error'; export type { ProviderFailureKind } from './provider-error'; diff --git a/packages/core/src/error/provider-error.test.ts b/packages/core/src/error/provider-error.test.ts index 9a3fc9ade42..3faefc74332 100644 --- a/packages/core/src/error/provider-error.test.ts +++ b/packages/core/src/error/provider-error.test.ts @@ -474,6 +474,7 @@ describe('toPersistedErrorIdentity', () => { message: 'Model call failed', statusCode: 400, reason: 'prompt is too long: 1 > 0 maximum', + requestOrigin: 'https://api.example.com', }); }); diff --git a/packages/core/src/error/provider-error.ts b/packages/core/src/error/provider-error.ts index 78f651dbf60..4387aff060b 100644 --- a/packages/core/src/error/provider-error.ts +++ b/packages/core/src/error/provider-error.ts @@ -1,4 +1,9 @@ -import { capPersistedText, readRequestedModel, readRequestId } from '../loop/shared/provider-error-details'; +import { + capPersistedText, + readRequestedModel, + readRequestId, + readRequestOrigin, +} from '../loop/shared/provider-error-details'; export type ProviderFailureKind = | 'auth' @@ -235,6 +240,15 @@ export function providerModelId(error: unknown): string | undefined { return firstAlongCauses(error, modelIdOf, 0); } +/** + * The origin (scheme, host and port) a failed model request was sent to, so a reader can tell + * which service answered. Read only from an AI SDK API call error, whose `url` is the request it + * made; a `url` on any other error may name some other resource. + */ +export function providerRequestOrigin(error: unknown): string | undefined { + return firstAlongCauses(error, requestOriginOf, 0); +} + function firstAlongCauses( error: unknown, read: (error: object) => string | undefined, @@ -248,6 +262,12 @@ function requestIdOf(error: object): string | undefined { return nonBlank(readField(error, 'requestId')) ?? readRequestId(readField(error, 'responseHeaders')); } +function requestOriginOf(error: object): string | undefined { + const isApiCallError = + readField(error, 'name') === 'AI_APICallError' || readField(error, 'requestBodyValues') !== undefined; + return isApiCallError ? readRequestOrigin(readField(error, 'url')) : undefined; +} + function modelIdOf(error: object): string | undefined { return nonBlank(readField(error, 'modelId')) ?? readRequestedModel(readField(error, 'requestBodyValues')); } diff --git a/packages/core/src/knowledge/__tests__/store-scopes.test.ts b/packages/core/src/knowledge/__tests__/store-scopes.test.ts deleted file mode 100644 index 8198323839a..00000000000 --- a/packages/core/src/knowledge/__tests__/store-scopes.test.ts +++ /dev/null @@ -1,322 +0,0 @@ -import { describe, expect, it, onTestFinished, vi } from 'vitest'; -import { setRunAgentScopes } from '../../agent/scopes'; -import { RequestContext } from '../../request-context'; -import { InMemoryStore } from '../../storage'; -import type { KnowledgeStorage } from '../../storage'; -import { KnowledgeDeclarationError, knowledgeMemoryScopes } from '../declarations'; -import type { KnowledgeScopeDeclarations } from '../declarations'; -import { Knowledge } from '../index'; -import { KNOWLEDGE_STORE_DECLARATIONS_TTL_MS, KnowledgeScopeRuntime } from '../scope-runtime'; - -const host = { author: 'host' }; -const imports = [{ principal: 'imports:all', role: 'viewer' as const }]; -/** What a hosted store's Linear importer declares: runs holding `imports:all` read its scopes. */ -const LINEAR: KnowledgeScopeDeclarations = { - 'imports:$name': {}, - 'linear:$account:$connection': { - displayLabel: 'Linear', - access: imports, - children: [{ name: 'archive', access: imports }], - }, -}; - -/** A store that declares Linear scopes it imported, next to a project's own `docs` scopes. */ -async function setup( - stored: KnowledgeScopeDeclarations = LINEAR, - config: KnowledgeScopeDeclarations = {}, - held: string[] = ['docs:eng', 'imports:all'], -) { - const store = new InMemoryStore(); - const knowledge = new Knowledge({ - storage: store, - tools: true, - scopes: { ...knowledgeMemoryScopes(), 'docs:$team': { access: [{ principal: 'self', role: 'owner' }] }, ...config }, - }); - const storage = await knowledge.getStorage(); - const declaring = vi.spyOn(storage, 'getScopeDeclarations').mockResolvedValue(stored); - const { scope: linear } = await storage.materializeScope({ - address: 'linear:acme:conn_1', - declaration: 'linear:$account:$connection', - name: 'Linear (acme)', - provenance: host, - children: [ - { address: 'linear:acme:conn_1/archive', declaration: 'linear:$account:$connection/archive', name: 'Archive' }, - ], - }); - await storage.createPage({ parentId: linear.id, key: 'roadmap', name: 'Roadmap', body: 'Ship Q3', provenance: host }); - const tools = knowledge.createTools({ write: true }); - const call = (tool: string, input: Record) => { - const requestContext = new RequestContext(); - setRunAgentScopes(requestContext, held); - return tools[tool]!.execute!(input as never, { requestContext, agent: { agentId: 'a' } } as never) as Promise; - }; - return { knowledge, storage, call, declaring }; -} - -const names = (result: any) => result.results.map((hit: any) => hit.page.name); - -describe('Knowledge scope declarations a store supplies', () => { - it("gives a run holding a rule's principal its role: search, read by ref and address, narrow and list", async () => { - const { call } = await setup(); - const [hit] = (await call('knowledge_search', { query: 'Roadmap' })).results; - expect(hit.page.ref).toBe('linear:acme:conn_1#roadmap'); - expect((await call('knowledge_read', { page: hit.page.ref })).page.name).toBe('Roadmap'); - expect((await call('knowledge_read', { page: 'linear:acme:conn_1' })).page.name).toBe('Linear (acme)'); - expect((await call('knowledge_read', { page: 'linear:acme:conn_1/archive' })).page.name).toBe('Archive'); - expect(names(await call('knowledge_search', { query: 'Roadmap', scope: ['linear:acme:conn_1'] }))).toEqual([ - 'Roadmap', - ]); - const { entries } = await call('knowledge_list', { from: 'linear:acme:conn_1' }); - expect(entries.map((entry: any) => entry.ref)).toEqual( - expect.arrayContaining(['linear:acme:conn_1/archive', 'linear:acme:conn_1#roadmap']), - ); - }); - - it("gives a run that doesn't hold the principal nothing, and lists only held scopes at the root", async () => { - const { call } = await setup(LINEAR, {}, ['docs:eng']); - await call('knowledge_page', { op: 'write', scope: 'docs:eng', name: 'Plan', body: 'x' }); - expect((await call('knowledge_search', { query: 'Roadmap' })).results).toEqual([]); - expect((await call('knowledge_list', {})).entries.map((entry: any) => entry.ref)).toEqual(['docs:eng']); - expect((await call('knowledge_read', {})).scopes.map((scope: any) => scope.address)).toEqual(['docs:eng']); - }); - - it('reads the store once for calls inside the reuse window, and again after a rename', async () => { - const { knowledge, call, declaring } = await setup(); - await call('knowledge_search', { query: 'Roadmap' }); - await call('knowledge_read', { page: 'linear:acme:conn_1#roadmap' }); - await knowledge.readScopeFor(['imports:all']); - expect(declaring).toHaveBeenCalledTimes(1); - await expect(knowledge.renameScopeDeclaration('gone:$id', 'docs:$team')).resolves.toBe(0); - await call('knowledge_search', { query: 'Roadmap' }); - expect(declaring).toHaveBeenCalledTimes(2); - }); - - it("doesn't let a read started before invalidate() publish its answer after it", async () => { - let finishOld!: (declarations: KnowledgeScopeDeclarations) => void; - const reads: Array> = [ - new Promise(resolve => (finishOld = resolve)), - Promise.resolve({}), - ]; - const getScopeDeclarations = vi.fn(() => reads.shift()!); - const storage = { getScopeDeclarations } as unknown as KnowledgeStorage; - const runtime = new KnowledgeScopeRuntime( - knowledgeMemoryScopes(), - async () => storage, - () => {}, - ); - const old = runtime.resolve(); - await vi.waitFor(() => expect(getScopeDeclarations).toHaveBeenCalledTimes(1)); - runtime.invalidate(); - await runtime.resolve(); - finishOld(LINEAR); - await old; - expect(runtime.compiled.match('linear:acme:conn_1')).toBeFalsy(); - expect(getScopeDeclarations).toHaveBeenCalledTimes(2); - }); - - it("doesn't let a read the TTL replaced publish its expired answer after the newer one", async () => { - vi.useFakeTimers(); - onTestFinished(() => { - vi.useRealTimers(); - }); - let finishOld!: (declarations: KnowledgeScopeDeclarations) => void; - const reads: Array> = [ - new Promise(resolve => (finishOld = resolve)), - Promise.resolve({}), - ]; - const getScopeDeclarations = vi.fn(() => reads.shift()!); - const storage = { getScopeDeclarations } as unknown as KnowledgeStorage; - const runtime = new KnowledgeScopeRuntime( - knowledgeMemoryScopes(), - async () => storage, - () => {}, - ); - // The first read hangs past the window; the next call starts a fresh read that revokes Linear. - const old = runtime.resolve(); - await vi.waitFor(() => expect(getScopeDeclarations).toHaveBeenCalledTimes(1)); - vi.advanceTimersByTime(KNOWLEDGE_STORE_DECLARATIONS_TTL_MS); - await runtime.resolve(); - expect(getScopeDeclarations).toHaveBeenCalledTimes(2); - finishOld(LINEAR); - await old; - expect(runtime.compiled.match('linear:acme:conn_1')).toBeFalsy(); - }); - - it('reads the store again after a failed read', async () => { - const { knowledge, declaring } = await setup(); - declaring.mockRejectedValueOnce(new Error('service down')); - await expect(knowledge.readScopeFor(['imports:all'])).rejects.toThrow('service down'); - await expect(knowledge.readScopeFor(['imports:all'])).resolves.toMatchObject({ addresses: [] }); - expect(declaring).toHaveBeenCalledTimes(2); - }); - - it('reads the store again once the reuse window passes, so a declaration it adds later applies', async () => { - vi.useFakeTimers({ toFake: ['Date'] }); - onTestFinished(() => void vi.useRealTimers()); - const { storage, call, declaring } = await setup(); - expect((await call('knowledge_search', { query: 'Spec' })).results).toEqual([]); - // An importer added after the project started: declared on the store, then written. - declaring.mockResolvedValue({ ...LINEAR, 'notion:$account:$connection': { access: imports } }); - const { scope } = await storage.materializeScope({ - address: 'notion:acme:conn_2', - declaration: 'notion:$account:$connection', - name: 'Notion (acme)', - provenance: host, - }); - await storage.createPage({ parentId: scope.id, key: 'spec', name: 'Spec', provenance: host }); - expect((await call('knowledge_search', { query: 'Spec' })).results).toEqual([]); - vi.advanceTimersByTime(KNOWLEDGE_STORE_DECLARATIONS_TTL_MS); - expect((await call('knowledge_search', { query: 'Spec' })).results.map((hit: any) => hit.page.ref)).toEqual([ - 'notion:acme:conn_2#spec', - ]); - }); - - it('keeps a store declaration whose rule names a type the store declares after it', async () => { - const { knowledge, call } = await setup({ - 'linear:$account:$connection': { - access: [{ principal: 'crew:$account', role: 'viewer' }, ...imports], - children: [{ name: 'archive', access: imports }], - }, - 'crew:$account': {}, - 'imports:$name': {}, - }); - const warn = vi.spyOn((knowledge as unknown as { logger: { warn: (message: string) => void } }).logger, 'warn'); - expect(names(await call('knowledge_search', { query: 'Roadmap' }))).toEqual(['Roadmap']); - expect(warn).not.toHaveBeenCalled(); - }); - - it('keeps store declarations that only compile together, next to one that never does', async () => { - const { knowledge, call } = await setup({ - 'linear:$account:$connection': { - access: [{ principal: 'crew:$account', role: 'viewer' }, ...imports], - children: [{ name: 'archive', access: imports }], - }, - 'crew:$account': { access: [{ principal: 'team:$account', role: 'viewer' }] }, - 'team:$account': { access: [{ principal: 'crew:$account', role: 'viewer' }] }, - 'ticket:$id': { access: [{ principal: 'nowhere:$id', role: 'viewer' }] }, - 'imports:$name': {}, - }); - const warn = vi.spyOn((knowledge as unknown as { logger: { warn: (message: string) => void } }).logger, 'warn'); - expect(names(await call('knowledge_search', { query: 'Roadmap' }))).toEqual(['Roadmap']); - expect(warn).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('"ticket:$id"')); - }); - - it('keeps a pair of store declarations that name each other', async () => { - const { knowledge } = await setup({ - ...LINEAR, - 'crew:$account': { access: [{ principal: 'team:$account', role: 'viewer' }] }, - 'team:$account': { access: [{ principal: 'crew:$account', role: 'viewer' }] }, - }); - const warn = vi.spyOn((knowledge as unknown as { logger: { warn: (message: string) => void } }).logger, 'warn'); - await expect(knowledge.readScopeFor(['crew:acme', 'team:acme'])).resolves.toMatchObject({ - addresses: expect.arrayContaining(['crew:acme', 'team:acme']), - }); - expect(warn).not.toHaveBeenCalled(); - }); - - it('passes the declaration check for stored scopes the store declares, and only those', async () => { - await expect((await setup()).knowledge.readScopeFor(['docs:eng', 'imports:all'])).resolves.toMatchObject({ - addresses: ['docs:eng'], - prefixes: [ - { declaration: 'linear:$account:$connection', prefix: 'linear:' }, - { declaration: 'linear:$account:$connection/archive', prefix: 'linear:' }, - ], - }); - await expect((await setup({})).knowledge.readScopeFor(['docs:eng'])).rejects.toThrow(KnowledgeDeclarationError); - }); - - it('moves a page in a store-declared scope as the first call, before anything else reads the store', async () => { - const { knowledge, storage } = await setup(); - const [linear] = await storage.getScopesByAddress(['linear:acme:conn_1']); - await storage.createPage({ parentId: linear!.id, key: 'archive-plans', name: 'Plans', body: '', provenance: host }); - const moved = await knowledge.movePage({ scope: 'linear:acme:conn_1', path: 'roadmap', parent: 'archive-plans' }); - expect(moved.name).toBe('Roadmap'); - }); - - it('reads nothing a store declaration gives no rule, and writes only with the role a rule gives', async () => { - const closed = await setup({ - 'imports:$name': {}, - 'linear:$account:$connection': { children: [{ name: 'archive' }] }, - }); - expect((await closed.call('knowledge_search', { query: 'Roadmap' })).results).toEqual([]); - - const viewer = await setup(); - await expect(viewer.call('knowledge_page', { op: 'write', page: 'Roadmap', body: 'Changed' })).rejects.toThrow( - /needs editor on "linear:acme:conn_1"; this run has viewer/, - ); - - const editor = await setup({ - 'imports:$name': {}, - 'linear:$account:$connection': { - access: [{ principal: 'imports:all', role: 'editor' }], - children: [{ name: 'archive' }], - }, - }); - await editor.call('knowledge_page', { op: 'write', page: 'Roadmap', body: 'Changed' }); - expect((await editor.call('knowledge_read', { page: 'linear:acme:conn_1#roadmap' })).page.body).toBe('Changed'); - }); - - it("keeps the config's declaration of a key both declare", async () => { - const { call } = await setup(LINEAR, { 'linear:$account:$connection': { children: [{ name: 'archive' }] } }); - expect((await call('knowledge_search', { query: 'Roadmap' })).results).toEqual([]); - }); - - it("skips a store declaration that doesn't compile, with a warning, and keeps the rest", async () => { - const { knowledge, call } = await setup({ - ...LINEAR, - 'ticket:$id': { access: [{ principal: 'team:$id', role: 'viewer' }] }, - }); - const warn = vi.spyOn((knowledge as unknown as { logger: { warn: (message: string) => void } }).logger, 'warn'); - expect(names(await call('knowledge_search', { query: 'Roadmap' }))).toEqual(['Roadmap']); - expect(warn).toHaveBeenCalledWith(expect.stringContaining('"ticket:$id"')); - }); - - it('names the skipped store declaration, and why, when its stored scopes fail the declaration check', async () => { - const { knowledge } = await setup({ - 'imports:$name': {}, - 'linear:$account:$connection': { access: [{ principal: '*', role: 'viewer' }], children: [{ name: 'archive' }] }, - }); - const error = await knowledge.readScopeFor(['docs:eng']).catch((e: unknown) => e); - expect(error).toBeInstanceOf(KnowledgeDeclarationError); - const message = (error as Error).message; - expect(message).toMatch( - /^Knowledge skipped the store's scope declaration "linear:\$account:\$connection", so its stored scopes have none: "linear:\$account:\$connection" \(1 scope\), "linear:\$account:\$connection\/archive" \(1 scope\)\. .*"\*".* Fix that declaration in the store, or declare the key, with its children, in scopes to override it\.$/, - ); - expect(message.match(/Knowledge skipped/g)).toHaveLength(1); - expect(message).not.toContain("this config doesn't declare"); - - const mixed = await setup({ - 'linear:$account:$connection': { access: [{ principal: '*', role: 'viewer' }], children: [{ name: 'archive' }] }, - }); - await mixed.storage.materializeScope({ - address: 'notion:acme:conn_2', - declaration: 'notion:$account:$connection', - name: 'Notion (acme)', - provenance: host, - }); - const both = ((await mixed.knowledge.readScopeFor(['docs:eng']).catch((e: unknown) => e)) as Error).message; - expect(both).toMatch(/this config doesn't declare: "notion:\$account:\$connection" \(1 scope\)\. /); - expect(both).toMatch( - /Knowledge skipped the store's scope declaration "linear:\$account:\$connection", so its stored scopes have none: "linear:\$account:\$connection" \(1 scope\), "linear:\$account:\$connection\/archive" \(1 scope\)\./, - ); - expect(both.match(/notion:\$account/g)).toHaveLength(1); - - const undeclared = await (await setup({})).knowledge.readScopeFor(['docs:eng']).catch((e: unknown) => e); - expect((undeclared as Error).message).toContain("this config doesn't declare"); - expect((undeclared as Error).message).not.toContain('Knowledge skipped'); - }); - - it('explains a grant and lists it in scope grants', async () => { - const { knowledge } = await setup(); - const explained = await knowledge.explainAccess(['docs:eng', 'imports:all'], { - page: 'linear:acme:conn_1#roadmap', - }); - expect(explained).toMatchObject({ - role: 'viewer', - reasons: [{ principal: 'imports:all', role: 'viewer', rule: 'linear:$account:$connection', via: 'rule' }], - }); - expect(knowledge.scopeGrants({ address: 'linear:acme:conn_1' })).toEqual([ - { principal: 'imports:all', role: 'viewer' }, - ]); - }); -}); diff --git a/packages/core/src/knowledge/access.ts b/packages/core/src/knowledge/access.ts index c7ce942c3df..01200df48f4 100644 --- a/packages/core/src/knowledge/access.ts +++ b/packages/core/src/knowledge/access.ts @@ -53,7 +53,7 @@ export async function knowledgeReadScopeFor( compiled: CompiledKnowledgeScopes, principals: readonly string[], lookupScopes: KnowledgeScopeLookup, -): Promise> { +): Promise { const addresses = new Set(); const prefixes = new Map(); const parents = new Map>(); diff --git a/packages/core/src/knowledge/host-writes.ts b/packages/core/src/knowledge/host-writes.ts index 64c59e64250..a463f88544c 100644 --- a/packages/core/src/knowledge/host-writes.ts +++ b/packages/core/src/knowledge/host-writes.ts @@ -182,7 +182,6 @@ export async function upsertKnowledgePage( host: KnowledgeHostWriter, input: KnowledgeUpsertPageInput, ): Promise { - await host.runtime.resolve(); const keys = splitPath(input.path); const provenance: KnowledgeProvenance = { author: input.author ?? 'host' }; // No principals: the host is trusted, and the scope is placed (belongsTo) by the first run that holds it. @@ -223,7 +222,6 @@ export async function removeKnowledgePage( host: KnowledgeHostWriter, input: KnowledgeRemovePageInput, ): Promise { - await host.runtime.resolve(); const keys = splitPath(input.path); await host.runtime.checkDeclarations(); const storage = await host.getStorage(); @@ -280,7 +278,6 @@ export async function moveKnowledgePage( host: KnowledgeHostWriter, input: KnowledgeMovePageInput, ): Promise { - await host.runtime.resolve(); const keys = splitPath(input.path); const ref = `${input.scope}#${keys.join('/')}`; await host.runtime.checkDeclarations(); @@ -349,7 +346,6 @@ export async function addKnowledgeNote( host: KnowledgeHostWriter, input: KnowledgeAddNoteInput, ): Promise { - await host.runtime.resolve(); const keys = splitPath(input.path); const provenance: KnowledgeProvenance = { author: input.author ?? 'host' }; const storage = await host.getStorage(); @@ -373,7 +369,6 @@ export async function updateKnowledgeNote( host: KnowledgeHostWriter, input: KnowledgeUpdateNoteInput, ): Promise { - await host.runtime.resolve(); assertKnowledgeNoteTextWithinBound(input.text); const provenance: KnowledgeProvenance = { author: input.author ?? 'host' }; const storage = await host.getStorage(); @@ -413,7 +408,6 @@ export async function removeKnowledgeNote( host: KnowledgeHostWriter, input: { id: string; author?: string }, ): Promise { - await host.runtime.resolve(); const author = input.author ?? 'host'; const storage = await host.getStorage(); const note = await storage.getNote({ id: input.id, read: 'all' }); diff --git a/packages/core/src/knowledge/index.ts b/packages/core/src/knowledge/index.ts index dead8e57c10..db82529d8c1 100644 --- a/packages/core/src/knowledge/index.ts +++ b/packages/core/src/knowledge/index.ts @@ -148,8 +148,7 @@ export class Knowledge extends MastraBase { * rules reach in one hop. Undeclared principals throw; an empty list reads nothing. Never `'all'`. * Pass the result as `read` to the store's read methods. */ - async readScopeFor(principals: readonly string[]): Promise { - await this.#runtime.resolve(); + readScopeFor(principals: readonly string[]): Promise { return this.#runtime.readScopeFor(principals); } @@ -163,19 +162,18 @@ export class Knowledge extends MastraBase { * * @experimental */ - async explainAccess( + explainAccess( runScopes: readonly string[], target: { scope: string } | { page: string }, ): Promise { - await this.#runtime.resolve(); return this.#runtime.explainAccess(runScopes, target); } /** * Who the declared rules give a role on one scope: each principal scope address (bound for this - * scope's params) with its strongest role, `self` rules left out. `parentAddress` is the - * address of the scope page's tree parent, needed for rules that bind through `belongsTo`. Reads the - * declarations as last resolved, not storage. For browsing UIs that draw access between scopes. + * scope's params) with its strongest role, `self` rules left out. `parentAddress` is the address of + * the scope page's tree parent, needed for rules that bind through `belongsTo`. Declared config + * only; it reads no storage. For browsing UIs that draw access between scopes. * * @experimental */ @@ -200,8 +198,7 @@ export class Knowledge extends MastraBase { * * @experimental */ - async renameScopeDeclaration(from: string, to: string): Promise { - await this.#runtime.resolve(); + renameScopeDeclaration(from: string, to: string): Promise { return this.#runtime.renameScopeDeclaration(from, to); } diff --git a/packages/core/src/knowledge/run.ts b/packages/core/src/knowledge/run.ts index 64592f274fd..ef85fcff6c9 100644 --- a/packages/core/src/knowledge/run.ts +++ b/packages/core/src/knowledge/run.ts @@ -56,7 +56,6 @@ export class KnowledgeRun { context: KnowledgeRunContext | undefined, options: { write?: boolean } = {}, ): Promise { - await runtime.resolve(); const principals = knowledgeRunPrincipals(runtime, context); const author = context?.agent?.agentId ? `agent:${context.agent.agentId}` : 'agent'; const provenance: KnowledgeProvenance = { diff --git a/packages/core/src/knowledge/scope-runtime.ts b/packages/core/src/knowledge/scope-runtime.ts index c615e44fecf..91455a73fd3 100644 --- a/packages/core/src/knowledge/scope-runtime.ts +++ b/packages/core/src/knowledge/scope-runtime.ts @@ -34,117 +34,17 @@ type HeldPrincipals = Map; byAddress: Map; byId: Map }; type MaterializeRun = { held: HeldPrincipals; known?: KnownScopes }; -/** How long the store's scope declarations are reused before {@link KnowledgeScopeRuntime.resolve} reads them again. */ -export const KNOWLEDGE_STORE_DECLARATIONS_TTL_MS = 30_000; - /** Declaration-backed access and lazy scope creation shared by the Knowledge lifecycle and tools. @internal */ export class KnowledgeScopeRuntime { - readonly #config: KnowledgeScopeDeclarations; - readonly #configCompiled: CompiledKnowledgeScopes; - /** The last resolved declarations, keyed by what the store supplied. */ - #resolved: { stored: string; compiled: CompiledKnowledgeScopes; skipped: Map }; + readonly compiled: CompiledKnowledgeScopes; #declarationsChecked?: Promise; - /** The store's declarations as last read, shared by concurrent calls until they expire. */ - #stored?: { readAt: number; declarations: Promise }; constructor( declarations: KnowledgeScopeDeclarations, private readonly getStorage: () => Promise, private readonly warn: (message: string) => void, ) { - this.#config = structuredClone(declarations); - this.#configCompiled = compileKnowledgeScopes(structuredClone(declarations)); - this.#resolved = { stored: '{}', compiled: this.#configCompiled, skipped: new Map() }; - } - - /** The declarations as last resolved: the config's, plus the store's from the latest {@link resolve}. */ - get compiled(): CompiledKnowledgeScopes { - return this.#resolved.compiled; - } - - /** - * Reads the store's scope declarations and merges them under the config's: a key the config - * declares keeps the config's declaration. Called once at the start of every call. The store's - * answer is reused for {@link KNOWLEDGE_STORE_DECLARATIONS_TTL_MS}, so a declaration the store adds - * or changes applies within that window, and right away after {@link invalidate}. A store - * declaration that doesn't compile next to the others is skipped with a warning. Recompiles only - * when the store's answer changes. - */ - async resolve(): Promise { - const entry = this.#readStored(); - const stored = await entry.declarations; - // Replaced while this read was in flight, by invalidate() or a newer read once the window - // passed: its answer may predate the change, so take the current one instead. - if (this.#stored !== entry) return this.resolve(); - const key = JSON.stringify(stored); - if (key === this.#resolved.stored) return this.#resolved.compiled; - let merged = this.#config; - let compiled = this.#configCompiled; - // Declarations can name types declared after them, or each other, so the whole record is tried - // first. When that fails, ones that compile on their own are added until a pass adds none, then - // the rest without each one in turn, which keeps a group that only compiles together next to one - // that doesn't compile. - let pending = Object.entries(stored).filter(([name]) => !Object.hasOwn(this.#config, name)); - const failures = new Map(); - const skippedReasons = new Map(); - const add = (entries: typeof pending, failed?: string) => { - const next = { ...merged, ...Object.fromEntries(entries) }; - try { - compiled = compileKnowledgeScopes(structuredClone(next)); - merged = next; - return true; - } catch (error) { - if (failed) failures.set(failed, error); - return false; - } - }; - if (!add(pending)) { - while (pending.length) { - const skipped = pending.filter(entry => !add([entry], entry[0])); - if (skipped.length < pending.length) { - pending = skipped; - continue; - } - const left = skipped.findIndex((_, i) => skipped.length > 1 && add(skipped.filter((__, j) => j !== i))); - if (left !== -1) { - pending = [skipped[left]!]; - continue; - } - for (const [name] of skipped) { - const error = failures.get(name); - const reason = error instanceof Error ? error.message : String(error); - skippedReasons.set(name, reason); - this.warn(`Knowledge skipped the store's scope declaration "${name}": ${reason}`); - } - break; - } - } - this.#resolved = { stored: key, compiled, skipped: skippedReasons }; - this.#declarationsChecked = undefined; - return compiled; - } - - /** Makes the next {@link resolve} read the store's declarations again. */ - invalidate(): void { - this.#stored = undefined; - } - - #readStored(): { readAt: number; declarations: Promise } { - const now = Date.now(); - // `now >= readAt` keeps a clock that moved backwards from extending the window. - if (this.#stored && now >= this.#stored.readAt && now - this.#stored.readAt < KNOWLEDGE_STORE_DECLARATIONS_TTL_MS) { - return this.#stored; - } - const entry = { - readAt: now, - declarations: this.getStorage().then(storage => storage.getScopeDeclarations()), - }; - this.#stored = entry; - // A failed read isn't kept, so the next call tries again. - entry.declarations.catch(() => { - if (this.#stored === entry) this.#stored = undefined; - }); - return entry; + this.compiled = compileKnowledgeScopes(structuredClone(declarations)); } validatePrincipals(principals: readonly string[]): void { @@ -156,10 +56,9 @@ export class KnowledgeScopeRuntime { } /** - * Fails when stored scope pages carry declaration keys neither the config nor the store declares: a - * renamed or removed key would otherwise silently cut those scopes off from prefix and `belongsTo` - * reach. Checked once per set of resolved declarations; only a pass is remembered, so a store error - * is retried next time. + * Fails when stored scope pages carry declaration keys this config doesn't declare: a renamed or + * removed key would otherwise silently cut those scopes off from prefix and `belongsTo` reach. + * Checked once per instance; only a pass is remembered, so a store error is retried next time. */ checkDeclarations(): Promise { if (!this.#declarationsChecked) { @@ -178,33 +77,14 @@ export class KnowledgeScopeRuntime { ({ declaration }) => !this.compiled.declarations.has(declaration), ); if (orphans.length === 0) return; - const list = (entries: typeof orphans) => - entries - .map(({ declaration, scopes }) => `"${declaration}" (${scopes} scope${scopes === 1 ? '' : 's'})`) - .join(', '); - // A store declaration that didn't compile leaves its stored scopes, its children's included, - // without a declaration too. Name it and why, since the fix is in the store, not the config. - const skippedKey = (declaration: string) => { - const key = declaration.split('/')[0]!; - return this.#resolved.skipped.has(key) ? key : undefined; - }; - const undeclared = orphans.filter(({ declaration }) => !skippedKey(declaration)); - const messages: string[] = []; - if (undeclared.length) { - messages.push( - `Knowledge storage has scopes created from declarations this config doesn't declare: ${list(undeclared)}. ` + - 'Restore each key in scopes, rename it with knowledge.renameScopeDeclaration(from, to), ' + - 'or keep the key with no access rules to retire it.', - ); - } - for (const key of new Set(orphans.map(({ declaration }) => skippedKey(declaration)).filter(k => k !== undefined))) { - const stranded = orphans.filter(({ declaration }) => skippedKey(declaration) === key); - messages.push( - `Knowledge skipped the store's scope declaration "${key}", so its stored scopes have none: ${list(stranded)}. ` + - `${this.#resolved.skipped.get(key)} Fix that declaration in the store, or declare the key, with its children, in scopes to override it.`, - ); - } - throw new KnowledgeDeclarationError(messages.join(' ')); + const listed = orphans + .map(({ declaration, scopes }) => `"${declaration}" (${scopes} scope${scopes === 1 ? '' : 's'})`) + .join(', '); + throw new KnowledgeDeclarationError( + `Knowledge storage has scopes created from declarations this config doesn't declare: ${listed}. ` + + 'Restore each key in scopes, rename it with knowledge.renameScopeDeclaration(from, to), ' + + 'or keep the key with no access rules to retire it.', + ); } /** Re-keys stored scopes from declaration `from` to `to`. See {@link Knowledge.renameScopeDeclaration}. */ @@ -236,7 +116,6 @@ export class KnowledgeScopeRuntime { }, }); this.#declarationsChecked = undefined; - this.invalidate(); return renamed; } @@ -258,7 +137,7 @@ export class KnowledgeScopeRuntime { ); } - async readScopeFor(principals: readonly string[]): Promise> { + async readScopeFor(principals: readonly string[]): Promise { this.validatePrincipals(principals); await this.checkDeclarations(); const storage = await this.getStorage(); @@ -266,7 +145,7 @@ export class KnowledgeScopeRuntime { const read = await knowledgeReadScopeFor(this.compiled, principals, async addresses => (await storage.getScopesByAddress(addresses)).filter(scope => this.#isCurrent(scope)), ); - if (read.addresses.length === 0) return read; + if (read === 'all' || read.addresses.length === 0) return read; const stale = new Set( (await storage.getScopesByAddress(read.addresses)) .filter(scope => !this.#isCurrent(scope)) diff --git a/packages/core/src/llm/model/gateways/mastra.test.ts b/packages/core/src/llm/model/gateways/mastra.test.ts index 3fc7745c284..0d9e25ba49c 100644 --- a/packages/core/src/llm/model/gateways/mastra.test.ts +++ b/packages/core/src/llm/model/gateways/mastra.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { MastraGateway } from './mastra.js'; +import { _resetMastraGatewayCatalogCache, MastraGateway } from './mastra.js'; vi.mock('../provider-registry.js', () => ({ PROVIDER_REGISTRY: { openrouter: { models: ['openai/test-model'] } }, @@ -10,14 +10,22 @@ describe('MastraGateway', () => { beforeEach(() => { delete process.env.MASTRA_GATEWAY_API_KEY; delete process.env.MASTRA_GATEWAY_VERSION; + _resetMastraGatewayCatalogCache(); }); afterEach(() => { delete process.env.MASTRA_GATEWAY_API_KEY; delete process.env.MASTRA_GATEWAY_VERSION; vi.restoreAllMocks(); + vi.unstubAllGlobals(); }); + /** A v2 gateway whose catalogue request is answered by `gatewayFetch` in place of the global fetch. */ + function gatewayWith(apiKey: string, gatewayFetch: (...args: any[]) => Promise) { + vi.stubGlobal('fetch', gatewayFetch); + return new MastraGateway({ apiKey }); + } + it('reports disabled when MASTRA_GATEWAY_API_KEY is not set', () => { const gateway = new MastraGateway(); @@ -62,18 +70,15 @@ describe('MastraGateway', () => { { status: 200, headers: { 'content-type': 'application/json' } }, ), ); - const gateway = new MastraGateway({ - apiKey: 'deployment-key', - baseUrl: 'https://gateway.example/v1', - customFetch: gatewayFetch, - }); + vi.stubGlobal('fetch', gatewayFetch); + const gateway = new MastraGateway({ apiKey: 'deployment-key', baseUrl: 'https://gateway.example/v1' }); const providers = await gateway.fetchProviders(); expect(gatewayFetch).toHaveBeenCalledWith( 'https://gateway.example/v1/models', expect.objectContaining({ - headers: expect.objectContaining({ 'X-Memory-Gateway-Authorization': 'Bearer deployment-key' }), + headers: { Authorization: 'Bearer deployment-key' }, signal: expect.any(AbortSignal), }), ); @@ -87,38 +92,41 @@ describe('MastraGateway', () => { ['https://gateway.example/api/', 'https://gateway.example/api/v1/models'], ])('normalizes the base URL %s', async (baseUrl, expected) => { process.env.MASTRA_GATEWAY_VERSION = 'v2'; - const customFetch = vi.fn(async () => new Response(JSON.stringify({ data: [] }), { status: 200 })); - await new MastraGateway({ apiKey: 'deployment-key', baseUrl, customFetch }).fetchProviders(); - expect(customFetch).toHaveBeenCalledWith(expected, expect.anything()); + const gatewayFetch = vi.fn(async () => new Response(JSON.stringify({ data: [] }), { status: 200 })); + vi.stubGlobal('fetch', gatewayFetch); + await new MastraGateway({ apiKey: 'deployment-key', baseUrl }).fetchProviders(); + expect(gatewayFetch).toHaveBeenCalledWith(expected, expect.anything()); }); it('normalizes a base URL with a pathological run of slashes in linear time', async () => { process.env.MASTRA_GATEWAY_VERSION = 'v2'; - const customFetch = vi.fn(async () => new Response(JSON.stringify({ data: [] }), { status: 200 })); + const gatewayFetch = vi.fn(async () => new Response(JSON.stringify({ data: [] }), { status: 200 })); + vi.stubGlobal('fetch', gatewayFetch); const slashes = '/'.repeat(100_000); const baseUrl = `https://gateway.example${slashes}api${slashes}`; const started = performance.now(); - await new MastraGateway({ apiKey: 'deployment-key', baseUrl, customFetch }).fetchProviders(); + await new MastraGateway({ apiKey: 'deployment-key', baseUrl }).fetchProviders(); expect(performance.now() - started).toBeLessThan(500); - expect(customFetch).toHaveBeenCalledWith(`https://gateway.example${slashes}api/v1/models`, expect.anything()); + expect(gatewayFetch).toHaveBeenCalledWith(`https://gateway.example${slashes}api/v1/models`, expect.anything()); }); - it('preserves the Gateway key when customFetch replaces Authorization with OAuth', async () => { + it('sends the v2 catalog request with the key in Authorization, not through a custom fetch', async () => { process.env.MASTRA_GATEWAY_VERSION = 'v2'; - const customFetch = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => { - const headers = new Headers(init?.headers); - headers.set('Authorization', 'Bearer oauth-token'); - expect(headers.get('Authorization')).toBe('Bearer oauth-token'); - expect(headers.get('X-Memory-Gateway-Authorization')).toBe('Bearer deployment-key'); - return new Response(JSON.stringify({ data: [{ id: 'openai/chat-model', endpoints: ['chat'] }] }), { - status: 200, - }); - }); + const customFetch = vi.fn(async () => new Response('{}', { status: 200 })); + const globalFetch = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response(JSON.stringify({ data: [{ id: 'openai/chat-model', endpoints: ['chat'] }] }), { status: 200 }), + ); + vi.stubGlobal('fetch', globalFetch); const gateway = new MastraGateway({ apiKey: 'deployment-key', customFetch }); const providers = await gateway.fetchProviders(); - expect(customFetch).toHaveBeenCalledOnce(); + expect(customFetch).not.toHaveBeenCalled(); + expect(globalFetch).toHaveBeenCalledOnce(); + const headers = new Headers(globalFetch.mock.calls[0]![1]?.headers); + expect(headers.get('Authorization')).toBe('Bearer deployment-key'); + expect(headers.get('X-Memory-Gateway-Authorization')).toBeNull(); expect(providers.mastra?.models).toEqual(['openai/chat-model']); }); @@ -126,16 +134,16 @@ describe('MastraGateway', () => { process.env.MASTRA_GATEWAY_VERSION = 'v2'; const controller = new AbortController(); const timeout = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(controller.signal); - const customFetch = vi.fn( + const gatewayFetch = vi.fn( (_input: RequestInfo | URL, init?: RequestInit) => new Promise((_resolve, reject) => { init?.signal?.addEventListener('abort', () => reject(init.signal?.reason), { once: true }); }), ); - const gateway = new MastraGateway({ apiKey: 'deployment-key', customFetch }); + const gateway = gatewayWith('deployment-key', gatewayFetch); const pending = gateway.fetchProviders(); - await vi.waitFor(() => expect(customFetch).toHaveBeenCalledOnce()); + await vi.waitFor(() => expect(gatewayFetch).toHaveBeenCalledOnce()); controller.abort(new DOMException('catalog deadline', 'TimeoutError')); await expect(pending).rejects.toThrow('catalog deadline'); @@ -147,7 +155,7 @@ describe('MastraGateway', () => { async () => new Response(JSON.stringify({ data: [{ id: 'openai/chat-model', endpoints: ['chat'] }] }), { status: 200 }), ); - const gateway = new MastraGateway({ apiKey: 'mskv2_org-key', customFetch: gatewayFetch }); + const gateway = gatewayWith('mskv2_org-key', gatewayFetch); const providers = await gateway.fetchProviders(); @@ -156,15 +164,353 @@ describe('MastraGateway', () => { expect(providers.mastra?.modelReleaseDates).toBeUndefined(); }); + describe('isV2', () => { + it.each([ + { version: undefined, key: 'msk_0123456789abcdef0123456789abcdef', expected: false }, + { version: 'v2', key: 'msk_0123456789abcdef0123456789abcdef', expected: false }, + { version: 'v2', key: 'deployment-key', expected: true }, + { version: 'v2', key: undefined, expected: true }, + { version: undefined, key: 'mskv2_org-key', expected: true }, + { version: undefined, key: 'msk-gateway-org-key', expected: true }, + { version: undefined, key: 'other-key', expected: false }, + ])('with MASTRA_GATEWAY_VERSION=$version and key $key is $expected', ({ version, key, expected }) => { + if (version) process.env.MASTRA_GATEWAY_VERSION = version; + expect(new MastraGateway({ apiKey: key }).isV2()).toBe(expected); + }); + + it('lets a v1 config key win over a v2 env key and MASTRA_GATEWAY_VERSION', () => { + process.env.MASTRA_GATEWAY_VERSION = 'v2'; + process.env.MASTRA_GATEWAY_API_KEY = 'mskv2_org-key'; + expect(new MastraGateway({ apiKey: 'msk_0123456789abcdef0123456789abcdef' }).isV2()).toBe(false); + }); + }); + it('does not show a static v1 model list if v2 catalog loading fails', async () => { process.env.MASTRA_GATEWAY_VERSION = 'v2'; - const gateway = new MastraGateway({ - apiKey: 'deployment-key', - customFetch: vi.fn(async () => new Response('unavailable', { status: 503 })), - }); + const gateway = gatewayWith( + 'deployment-key', + vi.fn(async () => new Response('unavailable', { status: 503 })), + ); await expect(gateway.fetchProviders()).rejects.toThrow('Gateway model catalog unavailable (503)'); }); + describe('v2 catalog cache', () => { + const catalog = (ids: string[]) => + new Response(JSON.stringify({ data: ids.map(id => ({ id, endpoints: ['chat'] })) }), { status: 200 }); + + beforeEach(() => { + process.env.MASTRA_GATEWAY_VERSION = 'v2'; + }); + + it('reuses the catalog for a minute, then fetches it again', async () => { + const now = vi.spyOn(Date, 'now').mockReturnValue(1_000_000); + const gatewayFetch = vi.fn(async () => catalog(['openai/chat-model'])); + const gateway = gatewayWith('deployment-key', gatewayFetch); + + await gateway.fetchProviders(); + now.mockReturnValue(1_000_000 + 59_000); + await gateway.fetchProviders(); + expect(gatewayFetch).toHaveBeenCalledOnce(); + + now.mockReturnValue(1_000_000 + 61_000); + await gateway.fetchProviders(); + expect(gatewayFetch).toHaveBeenCalledTimes(2); + }); + + it('shares one request between concurrent callers', async () => { + let respond!: (response: Response) => void; + const gatewayFetch = vi.fn(() => new Promise(resolve => (respond = resolve))); + const gateway = gatewayWith('deployment-key', gatewayFetch); + + const first = gateway.fetchProviders(); + const second = gatewayWith('deployment-key', gatewayFetch).fetchProviders(); + await vi.waitFor(() => expect(gatewayFetch).toHaveBeenCalledOnce()); + respond(catalog(['openai/chat-model'])); + + expect((await first).mastra?.models).toEqual(['openai/chat-model']); + expect((await second).mastra?.models).toEqual(['openai/chat-model']); + expect(gatewayFetch).toHaveBeenCalledOnce(); + }); + + it('keeps catalogs for different keys apart', async () => { + const gatewayFetch = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => { + const key = new Headers(init?.headers).get('Authorization'); + return catalog([key === 'Bearer key-a' ? 'openai/model-a' : 'openai/model-b']); + }); + + const a = await gatewayWith('key-a', gatewayFetch).fetchProviders(); + const b = await gatewayWith('key-b', gatewayFetch).fetchProviders(); + + expect(a.mastra?.models).toEqual(['openai/model-a']); + expect(b.mastra?.models).toEqual(['openai/model-b']); + }); + + it('serves the last good catalog for up to ten minutes when a refresh fails', async () => { + const now = vi.spyOn(Date, 'now').mockReturnValue(1_000_000); + const gatewayFetch = vi.fn(async () => catalog(['openai/chat-model'])); + const gateway = gatewayWith('deployment-key', gatewayFetch); + await gateway.fetchProviders(); + + gatewayFetch.mockImplementation(async () => new Response('unavailable', { status: 503 })); + now.mockReturnValue(1_000_000 + 9 * 60_000); + expect((await gateway.fetchProviders()).mastra?.models).toEqual(['openai/chat-model']); + + now.mockReturnValue(1_000_000 + 11 * 60_000); + await expect(gateway.fetchProviders()).rejects.toThrow('Gateway model catalog unavailable (503)'); + }); + + it.each([401, 403])('drops the cached catalog when the key is rejected with %i', async status => { + const now = vi.spyOn(Date, 'now').mockReturnValue(1_000_000); + const gatewayFetch = vi.fn(async () => catalog(['openai/chat-model'])); + const gateway = gatewayWith('deployment-key', gatewayFetch); + await gateway.fetchProviders(); + + gatewayFetch.mockImplementation(async () => new Response('rejected', { status })); + now.mockReturnValue(1_000_000 + 61_000); + await expect(gateway.fetchProviders()).rejects.toThrow(`Gateway model catalog unavailable (${status})`); + + gatewayFetch.mockImplementation(async () => catalog(['openai/other-model'])); + expect((await gateway.fetchProviders()).mastra?.models).toEqual(['openai/other-model']); + }); + + it('serves the last good catalog after a network error', async () => { + const now = vi.spyOn(Date, 'now').mockReturnValue(1_000_000); + const gatewayFetch = vi.fn(async () => catalog(['openai/chat-model'])); + const gateway = gatewayWith('deployment-key', gatewayFetch); + await gateway.fetchProviders(); + + gatewayFetch.mockRejectedValue(new TypeError('fetch failed')); + now.mockReturnValue(1_000_000 + 61_000); + expect((await gateway.fetchProviders()).mastra?.models).toEqual(['openai/chat-model']); + }); + + it('waits before retrying after a failed refresh', async () => { + const now = vi.spyOn(Date, 'now').mockReturnValue(1_000_000); + const gatewayFetch = vi.fn(async () => catalog(['openai/chat-model'])); + const gateway = gatewayWith('deployment-key', gatewayFetch); + await gateway.fetchProviders(); + + gatewayFetch.mockImplementation(async () => new Response('unavailable', { status: 503 })); + now.mockReturnValue(1_000_000 + 61_000); + await gateway.fetchProviders(); + expect(gatewayFetch).toHaveBeenCalledTimes(2); + + now.mockReturnValue(1_000_000 + 61_000 + 14_000); + expect((await gateway.fetchProviders()).mastra?.models).toEqual(['openai/chat-model']); + expect(gatewayFetch).toHaveBeenCalledTimes(2); + + now.mockReturnValue(1_000_000 + 61_000 + 16_000); + expect((await gateway.fetchProviders()).mastra?.models).toEqual(['openai/chat-model']); + expect(gatewayFetch).toHaveBeenCalledTimes(3); + }); + + it('keeps catalogs fetched through different global fetch implementations apart', async () => { + const firstFetch = vi.fn(async () => catalog(['openai/model-a'])); + const secondFetch = vi.fn(async () => catalog(['openai/model-b'])); + + const a = await gatewayWith('same-key', firstFetch).fetchProviders(); + const b = await gatewayWith('same-key', secondFetch).fetchProviders(); + + expect(a.mastra?.models).toEqual(['openai/model-a']); + expect(b.mastra?.models).toEqual(['openai/model-b']); + expect(secondFetch).toHaveBeenCalledOnce(); + }); + + it('keeps at most 100 catalogs, dropping the oldest', async () => { + const gatewayFetch = vi.fn(async () => catalog(['openai/chat-model'])); + for (let i = 0; i <= 100; i++) { + await gatewayWith(`key-${i}`, gatewayFetch).fetchProviders(); + } + expect(gatewayFetch).toHaveBeenCalledTimes(101); + + await gatewayWith('key-100', gatewayFetch).fetchProviders(); + expect(gatewayFetch).toHaveBeenCalledTimes(101); + await gatewayWith('key-0', gatewayFetch).fetchProviders(); + expect(gatewayFetch).toHaveBeenCalledTimes(102); + }); + + it('remembers a failure with no earlier catalog for 15 seconds', async () => { + const now = vi.spyOn(Date, 'now').mockReturnValue(1_000_000); + const gatewayFetch = vi.fn(async () => new Response('unavailable', { status: 503 })); + const gateway = gatewayWith('deployment-key', gatewayFetch); + + await expect(gateway.fetchProviders()).rejects.toThrow('Gateway model catalog unavailable (503)'); + expect(gatewayFetch).toHaveBeenCalledOnce(); + + now.mockReturnValue(1_000_000 + 14_000); + await expect(gateway.fetchProviders()).rejects.toThrow('Gateway model catalog unavailable (503)'); + expect(gatewayFetch).toHaveBeenCalledOnce(); + + now.mockReturnValue(1_000_000 + 16_000); + await expect(gateway.fetchProviders()).rejects.toThrow('Gateway model catalog unavailable (503)'); + expect(gatewayFetch).toHaveBeenCalledTimes(2); + }); + + it('remembers a network error with no earlier catalog', async () => { + const now = vi.spyOn(Date, 'now').mockReturnValue(1_000_000); + const gatewayFetch = vi.fn(async () => { + throw new TypeError('fetch failed'); + }); + const gateway = gatewayWith('deployment-key', gatewayFetch); + + await expect(gateway.fetchProviders()).rejects.toThrow('fetch failed'); + now.mockReturnValue(1_000_000 + 5_000); + await expect(gateway.fetchProviders()).rejects.toThrow('fetch failed'); + expect(gatewayFetch).toHaveBeenCalledOnce(); + }); + + it('clears a remembered failure on success, and the next failure starts a new window', async () => { + const now = vi.spyOn(Date, 'now').mockReturnValue(1_000_000); + const gatewayFetch = vi.fn(async () => new Response('unavailable', { status: 503 })); + const gateway = gatewayWith('deployment-key', gatewayFetch); + await expect(gateway.fetchProviders()).rejects.toThrow('(503)'); + + gatewayFetch.mockImplementation(async () => catalog(['openai/chat-model'])); + now.mockReturnValue(1_000_000 + 16_000); + expect((await gateway.fetchProviders()).mastra?.models).toEqual(['openai/chat-model']); + expect(gatewayFetch).toHaveBeenCalledTimes(2); + + // Past the stale window there is no list to fall back on, so a failure is remembered again. + gatewayFetch.mockImplementation(async () => new Response('unavailable', { status: 503 })); + now.mockReturnValue(1_000_000 + 16_000 + 11 * 60_000); + await expect(gateway.fetchProviders()).rejects.toThrow('(503)'); + expect(gatewayFetch).toHaveBeenCalledTimes(3); + now.mockReturnValue(1_000_000 + 16_000 + 11 * 60_000 + 14_000); + await expect(gateway.fetchProviders()).rejects.toThrow('(503)'); + expect(gatewayFetch).toHaveBeenCalledTimes(3); + now.mockReturnValue(1_000_000 + 16_000 + 11 * 60_000 + 16_000); + await expect(gateway.fetchProviders()).rejects.toThrow('(503)'); + expect(gatewayFetch).toHaveBeenCalledTimes(4); + }); + + it.each([401, 403])('asks the gateway again on every call after a %i', async status => { + vi.spyOn(Date, 'now').mockReturnValue(1_000_000); + const gatewayFetch = vi.fn(async () => new Response('rejected', { status })); + const gateway = gatewayWith('deployment-key', gatewayFetch); + + await expect(gateway.fetchProviders()).rejects.toThrow(`(${status})`); + await expect(gateway.fetchProviders()).rejects.toThrow(`(${status})`); + expect(gatewayFetch).toHaveBeenCalledTimes(2); + + gatewayFetch.mockImplementation(async () => catalog(['openai/chat-model'])); + expect((await gateway.fetchProviders()).mastra?.models).toEqual(['openai/chat-model']); + }); + + it('shares one failing request between concurrent callers', async () => { + let respond!: (response: Response) => void; + const gatewayFetch = vi.fn(() => new Promise(resolve => (respond = resolve))); + const gateway = gatewayWith('deployment-key', gatewayFetch); + + const first = gateway.fetchProviders(); + const second = gateway.fetchProviders(); + await vi.waitFor(() => expect(gatewayFetch).toHaveBeenCalledOnce()); + respond(new Response('unavailable', { status: 503 })); + + await expect(first).rejects.toThrow('(503)'); + await expect(second).rejects.toThrow('(503)'); + expect(gatewayFetch).toHaveBeenCalledOnce(); + }); + + it('counts remembered failures toward the 100 catalog limit', async () => { + const gatewayFetch = vi.fn(async () => new Response('unavailable', { status: 503 })); + for (let i = 0; i <= 100; i++) { + await expect(gatewayWith(`key-${i}`, gatewayFetch).fetchProviders()).rejects.toThrow('(503)'); + } + expect(gatewayFetch).toHaveBeenCalledTimes(101); + + await expect(gatewayWith('key-100', gatewayFetch).fetchProviders()).rejects.toThrow('(503)'); + expect(gatewayFetch).toHaveBeenCalledTimes(101); + await expect(gatewayWith('key-0', gatewayFetch).fetchProviders()).rejects.toThrow('(503)'); + expect(gatewayFetch).toHaveBeenCalledTimes(102); + }); + + it('forgets remembered failures when the cache is reset', async () => { + const gatewayFetch = vi.fn(async () => new Response('unavailable', { status: 503 })); + const gateway = gatewayWith('deployment-key', gatewayFetch); + await expect(gateway.fetchProviders()).rejects.toThrow('(503)'); + + _resetMastraGatewayCatalogCache(); + await expect(gateway.fetchProviders()).rejects.toThrow('(503)'); + expect(gatewayFetch).toHaveBeenCalledTimes(2); + }); + }); + + describe('resolveLanguageModel streaming usage', () => { + const prompt = [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }]; + + function captureBodies() { + const bodies: Record[] = []; + const fetchImpl = vi.fn(async (_input: any, init: any) => { + bodies.push(JSON.parse(String(init?.body))); + return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } }); + }); + return { bodies, fetchImpl }; + } + + async function send(model: any) { + await model.doStream({ prompt }).catch(() => {}); + await model.doGenerate({ prompt }).catch(() => {}); + } + + it('asks for usage on streaming requests only with an API key', async () => { + const { bodies, fetchImpl } = captureBodies(); + vi.stubGlobal('fetch', fetchImpl); + try { + const model = new MastraGateway({ apiKey: 'gateway-key' }).resolveLanguageModel({ + modelId: 'gpt-4o', + providerId: 'openai', + apiKey: 'gateway-key', + }); + await send(model); + } finally { + vi.unstubAllGlobals(); + } + + expect(bodies).toHaveLength(2); + expect(bodies[0]).toMatchObject({ stream: true, stream_options: { include_usage: true } }); + expect(bodies[1]).not.toHaveProperty('stream_options'); + expect(bodies[1]).not.toHaveProperty('usage'); + }); + + it('reports usage sent in a separate final chunk', async () => { + const frames = [ + { id: 'c1', choices: [{ index: 0, delta: { role: 'assistant', content: 'ok' } }] }, + { id: 'c1', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }, + { id: 'c1', choices: [], usage: { prompt_tokens: 7, completion_tokens: 3, total_tokens: 10 } }, + ]; + const body = frames.map(frame => `data: ${JSON.stringify(frame)}\n\n`).join('') + 'data: [DONE]\n\n'; + const customFetch = vi.fn( + async () => new Response(body, { status: 200, headers: { 'content-type': 'text/event-stream' } }), + ); + const model: any = new MastraGateway({ + apiKey: 'gateway-key', + customFetch: customFetch as any, + }).resolveLanguageModel({ modelId: 'gpt-4o', providerId: 'openai', apiKey: 'gateway-key' }); + + const { stream } = await model.doStream({ prompt }); + const parts: any[] = []; + for await (const part of stream) parts.push(part); + + const finish = parts.find(part => part.type === 'finish'); + expect(finish?.usage).toMatchObject({ inputTokens: { total: 7 }, outputTokens: { total: 3 } }); + }); + + it('asks for usage on streaming requests only with a custom fetch', async () => { + const { bodies, fetchImpl } = captureBodies(); + const model = new MastraGateway({ apiKey: 'gateway-key', customFetch: fetchImpl as any }).resolveLanguageModel({ + modelId: 'gpt-4o', + providerId: 'openai', + apiKey: 'gateway-key', + }); + await send(model); + + expect(bodies).toHaveLength(2); + expect(bodies[0]).toMatchObject({ stream: true, stream_options: { include_usage: true } }); + expect(bodies[1]).not.toHaveProperty('stream_options'); + expect(bodies[1]).not.toHaveProperty('usage'); + }); + }); + describe('resolveLanguageModel gateway authorization header', () => { const GATEWAY_AUTH_HEADER = 'X-Memory-Gateway-Authorization'; diff --git a/packages/core/src/llm/model/gateways/mastra.ts b/packages/core/src/llm/model/gateways/mastra.ts index c1a84285d0d..12c75be77dd 100644 --- a/packages/core/src/llm/model/gateways/mastra.ts +++ b/packages/core/src/llm/model/gateways/mastra.ts @@ -1,3 +1,4 @@ +import { createHash } from 'node:crypto'; import { createAnthropic } from '@ai-sdk/anthropic-v6'; import { createOpenRouter } from '@openrouter/ai-sdk-provider-v6'; import { MastraError } from '../../../error/index.js'; @@ -67,15 +68,19 @@ export class MastraGateway extends MastraModelGateway { /** * Gateway v2 deployments are signaled by MASTRA_GATEWAY_VERSION=v2 (set by the platform) - * or by a v2 (organization) API key prefix, which predates the env var signal. + * or by a v2 (organization) API key prefix, which predates the env var signal. A v1 project + * key (`msk_`) is always served by v1, so it wins over the env var. * Keep in sync with isGatewayV2 in @mastra/server's gateway-memory-client. * Public so the server can ask a registered gateway instance for its - * effective v2 state (the instance may carry a v2 key via config.apiKey + * effective v2 state (the instance may carry a key via config.apiKey * that env-only checks cannot see). */ isV2(): boolean { - if (process.env['MASTRA_GATEWAY_VERSION'] === 'v2') return true; const key = this.config?.apiKey ?? process.env['MASTRA_GATEWAY_API_KEY']; + // A v1 project key (`msk_`) is always served by v1, so it wins over the env var. + // The v2 prefixes (`msk-gateway-`, `mskv2_`) do not start with `msk_`. + if (key?.startsWith('msk_')) return false; + if (process.env['MASTRA_GATEWAY_VERSION'] === 'v2') return true; return !!key && (key.startsWith('msk-gateway-') || key.startsWith('mskv2_')); } @@ -85,27 +90,12 @@ export class MastraGateway extends MastraModelGateway { let models = openrouterConfig?.models ?? []; if (isV2) { const apiKey = await this.getApiKey(); - const response = await (this.config?.customFetch ?? fetch)(`${this.getBaseUrl()}/v1/models`, { - headers: this.config?.customFetch ? withGatewayAuthHeader(apiKey) : { Authorization: `Bearer ${apiKey}` }, - signal: AbortSignal.timeout(10_000), - }); - if (!response.ok) throw new Error(`Gateway model catalog unavailable (${response.status})`); - const body: unknown = await response.json(); - if (!body || typeof body !== 'object' || !('data' in body) || !Array.isArray(body.data)) { - throw new Error('Gateway model catalog has an invalid response'); - } - // The Mastra gateway model uses the OpenAI-compatible chat transport. - // Models offered only through another endpoint cannot be selected here. - models = body.data - .filter( - (item): item is { id: string; endpoints: string[] } => - !!item && - typeof item === 'object' && - typeof item.id === 'string' && - Array.isArray(item.endpoints) && - item.endpoints.includes('chat'), - ) - .map(item => item.id); + // Gateway v2 reads the key only from Authorization or x-api-key. A custom fetch is a v1 + // pass-through that owns Authorization, so the catalogue request uses the plain global fetch. + const fetchImpl = globalThis.fetch; + models = await loadCachedV2Catalog(fetchImpl, `${this.getBaseUrl()}\n${hashApiKey(apiKey)}`, () => + this.fetchV2Catalog(fetchImpl, apiKey), + ); } const providers = { @@ -124,6 +114,32 @@ export class MastraGateway extends MastraModelGateway { return providers; } + private async fetchV2Catalog(fetchImpl: typeof fetch, apiKey: string): Promise { + const response = await fetchImpl(`${this.getBaseUrl()}/v1/models`, { + headers: { Authorization: `Bearer ${apiKey}` }, + signal: AbortSignal.timeout(10_000), + }); + if (!response.ok) { + throw new GatewayCatalogError(`Gateway model catalog unavailable (${response.status})`, response.status); + } + const body: unknown = await response.json(); + if (!body || typeof body !== 'object' || !('data' in body) || !Array.isArray(body.data)) { + throw new Error('Gateway model catalog has an invalid response'); + } + // The Mastra gateway model uses the OpenAI-compatible chat transport. + // Models offered only through another endpoint cannot be selected here. + return body.data + .filter( + (item): item is { id: string; endpoints: string[] } => + !!item && + typeof item === 'object' && + typeof item.id === 'string' && + Array.isArray(item.endpoints) && + item.endpoints.includes('chat'), + ) + .map(item => item.id); + } + async buildUrl(_modelId: string): Promise { return `${this.getBaseUrl()}/v1`; } @@ -172,6 +188,9 @@ export class MastraGateway extends MastraModelGateway { baseURL, headers: withGatewayAuthHeader(apiKey, headers), fetch: this.config.customFetch, + // Strict mode adds stream_options.include_usage to streaming requests only, + // so routes that report usage in a separate final chunk still return it. + compatibility: 'strict', }).chat(fullModelId) as unknown as GatewayLanguageModel; } @@ -183,6 +202,146 @@ export class MastraGateway extends MastraModelGateway { 'User-Agent': MASTRA_USER_AGENT, ...headers, }, + // Strict mode adds stream_options.include_usage to streaming requests only. + compatibility: 'strict', }).chat(fullModelId) as unknown as GatewayLanguageModel; } } + +/** How long a v2 model catalogue is reused before it is fetched again. */ +const V2_CATALOG_TTL_MS = 60_000; +/** How long the last good v2 catalogue is still served while refreshes fail. */ +const V2_CATALOG_STALE_IF_ERROR_MS = 10 * 60_000; +/** + * How long to wait after a failed request before trying again: the last good catalogue is served + * meanwhile, or, when there is none, the failure is thrown again. + */ +const V2_CATALOG_RETRY_AFTER_ERROR_MS = 15_000; +/** Most catalogues kept per fetch implementation. */ +const V2_CATALOG_MAX_ENTRIES = 100; + +/** A catalogue request that got an HTTP error status. */ +class GatewayCatalogError extends Error { + constructor( + message: string, + readonly status: number, + ) { + super(message); + this.name = 'GatewayCatalogError'; + } +} + +interface V2CatalogEntry { + models?: string[]; + fetchedAt?: number; + retryAt?: number; + pending?: Promise; + /** A failure with no list to fall back on, rethrown until `failedUntil` without a new request. */ + failure?: unknown; + failedUntil?: number; +} + +/** + * v2 model catalogues, first by the global fetch in effect when the request was made, then by + * base URL and API key hash. A replaced global fetch (instrumentation, test doubles) gets its own + * entries, so a list from one is never served through another. The raw key is never stored. + */ +let v2CatalogCaches = new WeakMap>(); + +/** Only an in-memory cache key, so the raw key is not held. Not a password hash. */ +function hashApiKey(apiKey: string): string { + return createHash('sha256').update(apiKey).digest('hex'); +} + +/** A 401 or 403 means the key was rejected, so a list cached for it must not be served. */ +function isRejectedKey(error: unknown): boolean { + return error instanceof GatewayCatalogError && (error.status === 401 || error.status === 403); +} + +/** + * Drops settled entries past the stale window (keeping a failure that is still remembered), then + * the oldest settled ones over the size cap. + */ +function pruneV2Catalogs(cache: Map, now: number): void { + for (const [key, entry] of cache) { + const failureRemembered = entry.failedUntil !== undefined && now < entry.failedUntil; + const listExpired = entry.fetchedAt === undefined || now - entry.fetchedAt >= V2_CATALOG_STALE_IF_ERROR_MS; + if (!entry.pending && !failureRemembered && listExpired) cache.delete(key); + } + for (const [key, entry] of cache) { + if (cache.size <= V2_CATALOG_MAX_ENTRIES) break; + if (!entry.pending) cache.delete(key); + } +} + +/** + * Returns the cached v2 catalogue for `cacheKey`, fetching it when it is missing or older than + * the TTL. Concurrent callers share one request. When a refresh fails with a timeout, a network + * error or a server error, the last good catalogue is returned for a bounded time, and the next + * attempt waits a short while. Without a catalogue to fall back on, the error is thrown, and the + * same error is thrown again without a new request for that short while, so callers during an + * outage do not each wait for the request timeout. A rejected key (401 or 403) drops the cached + * catalogue and is never remembered, so every call asks the gateway again. + */ +function loadCachedV2Catalog( + fetchImpl: typeof fetch, + cacheKey: string, + load: () => Promise, +): Promise { + let cache = v2CatalogCaches.get(fetchImpl); + if (!cache) { + cache = new Map(); + v2CatalogCaches.set(fetchImpl, cache); + } + const entries = cache; + const entry = entries.get(cacheKey); + const now = Date.now(); + if (entry?.models && entry.fetchedAt !== undefined) { + const age = now - entry.fetchedAt; + const fresh = age < V2_CATALOG_TTL_MS; + const backingOff = entry.retryAt !== undefined && now < entry.retryAt && age < V2_CATALOG_STALE_IF_ERROR_MS; + if (fresh || backingOff) return Promise.resolve(entry.models); + } + if (entry?.failedUntil !== undefined && now < entry.failedUntil) return Promise.reject(entry.failure); + if (entry?.pending) return entry.pending; + + const pending = load().then( + models => { + const settledAt = Date.now(); + entries.delete(cacheKey); + entries.set(cacheKey, { models, fetchedAt: settledAt }); + pruneV2Catalogs(entries, settledAt); + return models; + }, + error => { + const previous = entries.get(cacheKey); + const settledAt = Date.now(); + if ( + !isRejectedKey(error) && + previous?.models && + previous.fetchedAt !== undefined && + settledAt - previous.fetchedAt < V2_CATALOG_STALE_IF_ERROR_MS + ) { + entries.set(cacheKey, { + models: previous.models, + fetchedAt: previous.fetchedAt, + retryAt: settledAt + V2_CATALOG_RETRY_AFTER_ERROR_MS, + }); + return previous.models; + } + entries.delete(cacheKey); + if (!isRejectedKey(error)) { + entries.set(cacheKey, { failure: error, failedUntil: settledAt + V2_CATALOG_RETRY_AFTER_ERROR_MS }); + pruneV2Catalogs(entries, settledAt); + } + throw error; + }, + ); + entries.set(cacheKey, { ...entry, pending }); + return pending; +} + +/** @internal Clear the cached v2 model catalogues. For testing only. */ +export function _resetMastraGatewayCatalogCache(): void { + v2CatalogCaches = new WeakMap(); +} diff --git a/packages/core/src/llm/model/provider-registry.test.ts b/packages/core/src/llm/model/provider-registry.test.ts index 3af1f3b27aa..1674bf3271c 100644 --- a/packages/core/src/llm/model/provider-registry.test.ts +++ b/packages/core/src/llm/model/provider-registry.test.ts @@ -933,6 +933,95 @@ describe('GatewayRegistry Auto-Refresh', () => { fs.rmSync(tmpDir, { recursive: true, force: true }); }); + describe('Mastra gateway in the shared cache', () => { + const envKeys = ['MASTRA_GATEWAY_VERSION', 'MASTRA_GATEWAY_API_KEY'] as const; + let savedEnv: Record = {}; + + beforeEach(() => { + savedEnv = Object.fromEntries(envKeys.map(key => [key, process.env[key]])); + for (const key of envKeys) delete process.env[key]; + }); + + afterEach(() => { + for (const key of envKeys) { + if (savedEnv[key] === undefined) delete process.env[key]; + else process.env[key] = savedEnv[key]; + } + GatewayRegistry.getInstance({ useDynamicLoading: true }).registerCustomGateways([]); + }); + + async function sync(mastraCatalog: () => Promise>) { + const registry = GatewayRegistry.getInstance({ useDynamicLoading: true }); + const writtenFiles: string[] = []; + vi.spyOn(fs.promises, 'writeFile').mockImplementation(async (filePath: any, data: any) => { + writtenFiles.push(`${filePath.toString()}\n${String(data)}`); + }); + vi.spyOn(fs.promises, 'rename').mockResolvedValue(); + vi.spyOn(fs.promises, 'copyFile').mockResolvedValue(); + vi.spyOn(fs, 'mkdirSync').mockReturnValue(undefined); + vi.spyOn(ModelsDevGateway.prototype, 'fetchProviders').mockResolvedValue({ + 'test-provider': { + name: 'Test Provider', + models: ['model-a'], + apiKeyEnvVar: 'TEST_API_KEY', + gateway: 'models-dev', + } as ProviderConfig, + }); + vi.spyOn(NetlifyGateway.prototype, 'fetchProviders').mockResolvedValue({}); + const mastraFetchProvidersSpy = vi + .spyOn(MastraGateway.prototype, 'fetchProviders') + .mockImplementation(mastraCatalog); + + await registry.syncGateways(true); + + const registryWrites = writtenFiles.filter(entry => entry.includes('provider-registry.json')); + expect(registryWrites.length).toBeGreaterThan(0); + for (const entry of registryWrites) expect(entry).toContain('test-provider'); + return { mastraFetchProvidersSpy, registryWrites }; + } + + const failingCatalog = async () => { + throw new Error('Gateway model catalog unavailable (401)'); + }; + + it('does not sync the default Mastra gateway in v2 mode', async () => { + process.env.MASTRA_GATEWAY_VERSION = 'v2'; + process.env.MASTRA_GATEWAY_API_KEY = 'deployment-key'; + + const { mastraFetchProvidersSpy, registryWrites } = await sync(failingCatalog); + + expect(mastraFetchProvidersSpy).not.toHaveBeenCalled(); + for (const entry of registryWrites) expect(entry).not.toContain('"mastra"'); + }); + + it('does not sync a registered Mastra gateway that holds an organization key', async () => { + GatewayRegistry.getInstance({ useDynamicLoading: true }).registerCustomGateways([ + new MastraGateway({ apiKey: 'mskv2_org-key' }), + ]); + + const { mastraFetchProvidersSpy, registryWrites } = await sync(failingCatalog); + + expect(mastraFetchProvidersSpy).not.toHaveBeenCalled(); + for (const entry of registryWrites) expect(entry).not.toContain('"mastra"'); + }); + + it('still syncs the Mastra gateway with a v1 project key', async () => { + process.env.MASTRA_GATEWAY_API_KEY = 'msk_0123456789abcdef0123456789abcdef'; + + const { mastraFetchProvidersSpy, registryWrites } = await sync(async () => ({ + mastra: { + name: 'Gateway', + models: ['openai/chat-model'], + apiKeyEnvVar: 'MASTRA_GATEWAY_API_KEY', + gateway: 'mastra', + } as ProviderConfig, + })); + + expect(mastraFetchProvidersSpy).toHaveBeenCalled(); + for (const entry of registryWrites) expect(entry).toContain('"mastra"'); + }); + }); + it('should skip syncGateways when MASTRA_OFFLINE is set to true', async () => { process.env.MASTRA_OFFLINE = 'true'; diff --git a/packages/core/src/llm/model/provider-registry.ts b/packages/core/src/llm/model/provider-registry.ts index fd8b562ff60..1ed63815f1a 100644 --- a/packages/core/src/llm/model/provider-registry.ts +++ b/packages/core/src/llm/model/provider-registry.ts @@ -866,8 +866,13 @@ export class GatewayRegistry { ...(writeToSrc ? [] : [new MastraGateway()]), ]; - // Combine default and custom gateways - const gateways = [...defaultGateways, ...this.customGateways]; + // Combine default and custom gateways. A Mastra gateway in v2 mode, default or registered, + // lists models for one organization's key, so it is not written to the machine-wide cache, + // and its failures cannot stop the rest of the refresh. + const gateways = [...defaultGateways, ...this.customGateways].filter(gateway => { + const candidate = gateway as { id?: string; isV2?: () => boolean }; + return !(candidate.id === 'mastra' && typeof candidate.isV2 === 'function' && candidate.isV2()); + }); // Fetch provider data const { diff --git a/packages/core/src/loop/shared/provider-error-details.test.ts b/packages/core/src/loop/shared/provider-error-details.test.ts index c67a533319d..acbd5cf9345 100644 --- a/packages/core/src/loop/shared/provider-error-details.test.ts +++ b/packages/core/src/loop/shared/provider-error-details.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { MAX_PERSISTED_RESPONSE_BODY_LENGTH, describeProviderError } from './provider-error-details'; +import { MAX_PERSISTED_RESPONSE_BODY_LENGTH, describeProviderError, readRequestOrigin } from './provider-error-details'; function providerError(responseBody: string, requestId = 'req_123') { return Object.assign(new Error('Bad Request'), { @@ -44,3 +44,21 @@ describe('describeProviderError', () => { expect(describeProviderError('boom', new Error('boom'), 1000)).toBeUndefined(); }); }); + +describe('readRequestOrigin', () => { + it.each([ + ['https://gateway-api.mastra.ai/v1/chat/completions', 'https://gateway-api.mastra.ai'], + ['http://127.0.0.1:4180/v1/chat/completions?x=1', 'http://127.0.0.1:4180'], + ['https://user:pass@api.example.com:443/path', 'https://api.example.com'], + [' https://api.example.com/v1 ', 'https://api.example.com'], + ])('keeps only the origin of %s', (url, origin) => { + expect(readRequestOrigin(url)).toBe(origin); + }); + + it.each([undefined, null, 42, '', ' ', 'not a url', '/relative', 'file:///etc/passwd', 'data:text/plain,hi'])( + 'gives undefined for %s', + url => { + expect(readRequestOrigin(url)).toBeUndefined(); + }, + ); +}); diff --git a/packages/core/src/loop/shared/provider-error-details.ts b/packages/core/src/loop/shared/provider-error-details.ts index 83b505f9799..ec570f0f317 100644 --- a/packages/core/src/loop/shared/provider-error-details.ts +++ b/packages/core/src/loop/shared/provider-error-details.ts @@ -42,6 +42,23 @@ export function readRequestId(headers: unknown): string | undefined { return undefined; } +/** + * The origin (scheme, host and port) of a request URL. The path, query string and any + * credentials in the URL are never kept. Anything that is not an absolute http or https URL + * gives undefined. + */ +export function readRequestOrigin(url: unknown): string | undefined { + if (typeof url !== 'string' || !url.trim()) return undefined; + let parsed: URL; + try { + parsed = new URL(url.trim()); + } catch { + return undefined; + } + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return undefined; + return parsed.origin; +} + export function readRequestedModel(requestBody: unknown): string | undefined { if (!requestBody || typeof requestBody !== 'object') return undefined; const model = readField(requestBody, 'model'); diff --git a/packages/core/src/loop/shared/record-terminal-error-message.test.ts b/packages/core/src/loop/shared/record-terminal-error-message.test.ts index 28e5f9411e2..2cbde067586 100644 --- a/packages/core/src/loop/shared/record-terminal-error-message.test.ts +++ b/packages/core/src/loop/shared/record-terminal-error-message.test.ts @@ -46,6 +46,7 @@ describe('toPersistedErrorIdentity', () => { responseBody: '{"error":{"code":"insufficient_quota"}}', modelId: 'claude-opus-4-5', codes: ['insufficient_quota'], + requestOrigin: 'https://api.example.com', }); expect(Object.keys(toPersistedErrorIdentity(new Error('boom')))).toEqual(['name', 'message']); expect( @@ -58,6 +59,50 @@ describe('toPersistedErrorIdentity', () => { ).toMatchObject({ statusCode: 400, reason: 'prompt is too long' }); }); + it('keeps only the origin of the URL a failed model request was sent to', () => { + const error = Object.assign(new Error('Too Many Requests'), { + name: 'AI_APICallError', + statusCode: 429, + url: 'http://user:secret@127.0.0.1:4180/v1/chat/completions?api_key=secret#frag', + requestBodyValues: { model: 'stub/ok' }, + }); + + const identity = toPersistedErrorIdentity(error); + + expect(identity.requestOrigin).toBe('http://127.0.0.1:4180'); + expect(JSON.stringify(identity)).not.toContain('secret'); + expect(JSON.stringify(identity)).not.toContain('/v1/chat/completions'); + }); + + it('reads the request origin from a model request error wrapped as a cause', () => { + const apiCallError = Object.assign(new Error('Service Unavailable'), { + name: 'AI_APICallError', + statusCode: 503, + url: 'https://gateway-api.mastra.ai/v1/chat/completions', + requestBodyValues: {}, + }); + const wrapped = new Error('Model call failed', { cause: apiCallError }); + + expect(toPersistedErrorIdentity(wrapped).requestOrigin).toBe('https://gateway-api.mastra.ai'); + }); + + it.each([ + ['a malformed URL', 'not a url'], + ['a relative URL', '/v1/chat/completions'], + ['a non-http scheme', 'file:///etc/passwd'], + ['a non-string URL', 42], + ])('leaves the request origin out for %s', (_label, url) => { + const error = Object.assign(new Error('Bad Request'), { statusCode: 400, url, requestBodyValues: {} }); + + expect(toPersistedErrorIdentity(error)).not.toHaveProperty('requestOrigin'); + }); + + it('ignores a url on an error that is not a model request error', () => { + const error = Object.assign(new Error('Not Found'), { url: 'https://internal.example/resource' }); + + expect(toPersistedErrorIdentity(error)).not.toHaveProperty('requestOrigin'); + }); + it('keeps a bounded response body and the provider request id', () => { const error = Object.assign(new Error('Bad Request'), { statusCode: 400, diff --git a/packages/core/src/loop/shared/record-terminal-error-message.ts b/packages/core/src/loop/shared/record-terminal-error-message.ts index 2e33daeada8..edc0b14a82d 100644 --- a/packages/core/src/loop/shared/record-terminal-error-message.ts +++ b/packages/core/src/loop/shared/record-terminal-error-message.ts @@ -16,6 +16,7 @@ * * Only `{ name, message }` is persisted, plus `statusCode`, a bounded * `responseBody`, the provider `requestId`, the `modelId` the request named, + * the `requestOrigin` the request was sent to (scheme, host and port only), * every provider code and the innermost `reason` for provider failures — * without those, an `APICallError` whose message is just "Bad Request" cannot * be diagnosed or classified after the fact. The rest of the request body, @@ -26,7 +27,7 @@ */ import type { MastraDBMessage, MastraErrorPart, MessageList } from '../../agent/message-list'; -import { providerErrorFacts } from '../../error/provider-error'; +import { providerErrorFacts, providerRequestOrigin } from '../../error/provider-error'; import { readProviderErrorDetails } from './provider-error-details'; const FALLBACK_ERROR_NAME = 'Error'; @@ -58,11 +59,13 @@ export function toPersistedErrorIdentity(error: unknown): MastraErrorPart['error return { name: FALLBACK_ERROR_NAME, message: FALLBACK_ERROR_MESSAGE }; } + const requestOrigin = providerRequestOrigin(error); return { name: readErrorField(error, 'name') ?? FALLBACK_ERROR_NAME, message: readErrorField(error, 'message') ?? FALLBACK_ERROR_MESSAGE, ...readProviderErrorDetails(error), ...providerErrorFacts(error), + ...(requestOrigin ? { requestOrigin } : {}), }; } diff --git a/packages/core/src/loop/test-utils/aimock/scenarios/persistence-failed-turns.scenario.test.ts b/packages/core/src/loop/test-utils/aimock/scenarios/persistence-failed-turns.scenario.test.ts index fb579d76728..2e7d2140598 100644 --- a/packages/core/src/loop/test-utils/aimock/scenarios/persistence-failed-turns.scenario.test.ts +++ b/packages/core/src/loop/test-utils/aimock/scenarios/persistence-failed-turns.scenario.test.ts @@ -95,7 +95,10 @@ describeForAllEngines('AIMock loop scenario: persistence of failed turns', engin .poll(async () => (await memory.recall({ threadId, resourceId })).messages.map(m => m.role)) .toEqual(['user', 'assistant']); const [errorPart] = errorParts((await memory.recall({ threadId, resourceId })).messages); - expect(errorPart).toMatchObject({ type: 'error', error: { statusCode: 400 } }); + expect(errorPart).toMatchObject({ + type: 'error', + error: { statusCode: 400, requestOrigin: new URL(getMock().url).origin }, + }); expect(JSON.parse((errorPart as { error: { responseBody: string } }).error.responseBody)).toMatchObject({ error: { message: 'PROVIDER_400_EXPLANATION', type: 'invalid_request_error' }, }); diff --git a/packages/core/src/storage/domains/knowledge/base.ts b/packages/core/src/storage/domains/knowledge/base.ts index dd8a542f076..ae271ed6171 100644 --- a/packages/core/src/storage/domains/knowledge/base.ts +++ b/packages/core/src/storage/domains/knowledge/base.ts @@ -1,4 +1,3 @@ -import type { KnowledgeScopeDeclarations } from '../../../knowledge/declarations'; import { StorageDomain } from '../base'; import type { KnowledgePageStore } from './pages'; @@ -191,18 +190,6 @@ export abstract class KnowledgeStorage extends StorageDomain implements Knowledg throw new Error('This Knowledge storage adapter does not support an explicit Knowledge-only reset.'); } - /** - * Scope declarations the store supplies itself, such as the scopes a hosted store's importers write - * to, with their access rules. Knowledge merges them under its config's, reusing the answer for a - * short window, so a declaration the store adds, removes or changes (revoking access included) - * applies within it; a key the config declares keeps the config's declaration. None by default. - * - * @experimental - */ - async getScopeDeclarations(): Promise { - return {}; - } - // Schema-4 page store (see ./pages.ts). Adapters override every method; the defaults refuse, so an // adapter that hasn't moved to schema 4 fails loudly instead of returning empty results. materializeScope( diff --git a/packages/create-mastra/CHANGELOG.md b/packages/create-mastra/CHANGELOG.md index dc0f5119c2d..0aead6b7f04 100644 --- a/packages/create-mastra/CHANGELOG.md +++ b/packages/create-mastra/CHANGELOG.md @@ -1,9 +1,5 @@ # create-mastra -## 1.40.0-alpha.6 - -## 1.40.0-alpha.5 - ## 1.40.0-alpha.4 ## 1.39.1-alpha.3 diff --git a/packages/create-mastra/package.json b/packages/create-mastra/package.json index 8b7e2a925cf..16ad5b20a47 100644 --- a/packages/create-mastra/package.json +++ b/packages/create-mastra/package.json @@ -1,6 +1,6 @@ { "name": "create-mastra", - "version": "1.40.0-alpha.6", + "version": "1.40.0-alpha.4", "description": "Create Mastra apps with one command", "license": "Apache-2.0", "type": "module", diff --git a/packages/deployer/CHANGELOG.md b/packages/deployer/CHANGELOG.md index 72d55907ebf..c4b9bcb3c57 100644 --- a/packages/deployer/CHANGELOG.md +++ b/packages/deployer/CHANGELOG.md @@ -1,21 +1,5 @@ # @mastra/deployer -## 1.84.0-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/server@1.84.0-alpha.6 - -## 1.84.0-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`0ed63d7`](https://github.com/mastra-ai/mastra/commit/0ed63d73084c92075b729fc2a25a66b8cea6f9bc), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/server@1.84.0-alpha.5 - ## 1.84.0-alpha.4 ### Patch Changes diff --git a/packages/deployer/package.json b/packages/deployer/package.json index abc382ff30c..d54167096c8 100644 --- a/packages/deployer/package.json +++ b/packages/deployer/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/deployer", - "version": "1.84.0-alpha.6", + "version": "1.84.0-alpha.4", "description": "", "type": "module", "files": [ diff --git a/packages/mcp-docs-server/CHANGELOG.md b/packages/mcp-docs-server/CHANGELOG.md index 2307b3d0e56..4041c0c18d7 100644 --- a/packages/mcp-docs-server/CHANGELOG.md +++ b/packages/mcp-docs-server/CHANGELOG.md @@ -1,19 +1,5 @@ # @mastra/mcp-docs-server -## 1.3.14-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - -## 1.3.14-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - ## 1.3.14-alpha.4 ### Patch Changes diff --git a/packages/mcp-docs-server/package.json b/packages/mcp-docs-server/package.json index 36fc0ac104d..9ad1c49b7e7 100644 --- a/packages/mcp-docs-server/package.json +++ b/packages/mcp-docs-server/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/mcp-docs-server", - "version": "1.3.14-alpha.6", + "version": "1.3.14-alpha.4", "description": "MCP server for accessing Mastra.ai documentation, changelogs, and news.", "type": "module", "main": "dist/index.js", diff --git a/packages/platform/CHANGELOG.md b/packages/platform/CHANGELOG.md deleted file mode 100644 index 34736d81589..00000000000 --- a/packages/platform/CHANGELOG.md +++ /dev/null @@ -1,35 +0,0 @@ -# @mastra/platform - -## 0.1.0-alpha.1 - -### Minor Changes - -- Added `PlatformBrowser`, a Stagehand browser backed by a Mastra Platform browser session. By default it provisions a session with `POST /v1/browsers/sessions` on the Platform and connects to the returned CDP URL; pass `cdpUrl` to connect to a session you already provisioned, with no token or API call. The access token falls back to `MASTRA_PLATFORM_ACCESS_TOKEN` / `MASTRA_PLATFORM_SECRET_KEY`, the project to `MASTRA_PROJECT_ID`, and the API URL to `MASTRA_BROWSER_API_URL`. `@mastra/platform` now depends on `@mastra/stagehand` at runtime. ([#29428](https://github.com/mastra-ai/mastra/pull/29428)) - - ```ts - import { PlatformBrowser } from '@mastra/platform'; - - const agent = new Agent({ name: 'browser-agent', model, browser: new PlatformBrowser() }); - ``` - -- Added `@mastra/platform`: hosted Mastra Platform Memory and Knowledge clients, with Platform Sandbox and Filesystem re-exported from `@mastra/platform-workspace`. `PlatformMemory` is a drop-in `memory` for `Agent` that loads observations and recent messages from a Platform Memory instance and saves each turn back; observation and reflection run on the Platform. `PlatformMemoryClient` exposes the same API directly. Credentials fall back to `MASTRA_PLATFORM_ACCESS_TOKEN` / `MASTRA_PLATFORM_SECRET_KEY`. `PlatformMemory` uses `MASTRA_MEMORY_INSTANCE_ID`; `PlatformKnowledge` uses `MASTRA_KNOWLEDGE_INSTANCE_ID`. `PlatformKnowledge` takes every scope declaration and access rule from its instance, Memory's and Platform importers' included, and has no `scopes` option. Agents read imported pages when their runs hold the scope an importer's rule grants (for now `imports:all`). ([#29428](https://github.com/mastra-ai/mastra/pull/29428)) - - ```ts - import { PlatformMemory, PlatformKnowledge, PlatformSandbox, PlatformFilesystem } from '@mastra/platform'; - - const agent = new Agent({ name: 'assistant', model, memory: new PlatformMemory() }); - ``` - -### Patch Changes - -- `PlatformKnowledge` now supports listing pins: `knowledge_pin` with `kind: 'list'` pins a page's listing on hosted Knowledge instead of refusing it as an old storage adapter. ([#29428](https://github.com/mastra-ai/mastra/pull/29428)) - -- `PlatformMemory` fixes for read-only runs and working memory: ([#29428](https://github.com/mastra-ai/mastra/pull/29428)) - - - A read-only run (`memory: { options: { readOnly: true } }`) now sees the thread's observations and unobserved messages, read through the Memory instance's read-only context route. Before, it got no stored context at all. It still saves nothing and starts no observation. - - The `workingMemory` option now delivers what it says: `readonly` and `tool` add the resource's stored working memory to each run's prompt, read fresh each run; `tool` also tells the agent to update it with `updateWorkingMemory`; `off` leaves it out. Before, stored working memory never reached the prompt in any mode. - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - -See [release notes](https://github.com/mastra-ai/mastra/releases) for published changes. diff --git a/packages/platform/README.md b/packages/platform/README.md deleted file mode 100644 index 4d7b238ee84..00000000000 --- a/packages/platform/README.md +++ /dev/null @@ -1,76 +0,0 @@ -# @mastra/platform (experimental) - -Hosted Mastra Platform clients for Memory, Knowledge, and Browser, with Sandbox and Filesystem re-exported from the `@mastra/platform-workspace` dependency. - -## Installation - -```sh -npm install @mastra/platform -``` - -## Usage - -Set `MASTRA_PLATFORM_ACCESS_TOKEN` (or `MASTRA_PLATFORM_SECRET_KEY`). `PlatformMemory` also needs `MASTRA_MEMORY_INSTANCE_ID` and `PlatformKnowledge` needs `MASTRA_KNOWLEDGE_INSTANCE_ID`; the example below uses both, so set both IDs. Obtain your instance IDs and credentials from Mastra Platform. - -```ts -import { Agent } from '@mastra/core/agent'; -import { PlatformMemory, PlatformKnowledge } from '@mastra/platform'; - -const model = 'openai/gpt-4o-mini'; -const agent = new Agent({ - name: 'assistant', - model, - memory: new PlatformMemory(), -}); -const knowledge = new PlatformKnowledge(); -``` - -`PlatformSandbox` and `PlatformFilesystem` are also available from `@mastra/platform`. - -### Hosted browser - -Create a hosted browser from your Mastra Platform project's browser page, then pass its CDP URL to `PlatformBrowser`. Treat the CDP URL as a secret: anyone holding it can connect to that browser. Keep it server-side, do not commit it, and use a secure environment variable such as `MASTRA_BROWSER_CDP_URL`. - -```ts -import { Agent } from '@mastra/core/agent'; -import { PlatformBrowser } from '@mastra/platform'; - -const agent = new Agent({ - name: 'browser-agent', - model: 'openai/gpt-4o-mini', - browser: new PlatformBrowser({ cdpUrl: process.env.MASTRA_BROWSER_CDP_URL! }), -}); -``` - -Alternatively, provide a Mastra Platform project ID and access token to provision a new Browserbase-backed session on demand. Browserbase credentials stay on the Platform server. - -```ts -const browser = new PlatformBrowser({ projectId: 'your-project-id' }); -``` - -`PlatformBrowser` uses `MASTRA_PLATFORM_ACCESS_TOKEN` or `MASTRA_PLATFORM_SECRET_KEY` and `MASTRA_PROJECT_ID` when the corresponding options are omitted for on-demand provisioning. It POSTs `{ projectId }` to `https://platform.mastra.ai/v1/browsers/sessions` (overridable with `apiUrl` or `MASTRA_BROWSER_API_URL`) and connects to the returned CDP URL with shared browser scope. A project access token must be authorized for that project. Supplying `cdpUrl` skips provisioning and does not require a Platform token or project ID. - -### Knowledge transport contract - -- `POST {apiUrl}/v1/knowledge/{instanceId}/operations/{operation}` with `Authorization: Bearer {accessToken}` and JSON body `{ input }`; returns `{ result }`. -- `instanceId` and `apiUrl` come from options or `MASTRA_KNOWLEDGE_INSTANCE_ID` and `MASTRA_KNOWLEDGE_API_URL`; `apiUrl` defaults to `https://knowledge-api.mastra.ai`. The service derives the authorized project from the instance and credential; `projectId` is accepted for compatibility but is not sent. -- `renameScopeDeclaration` is not forwarded and rejects with `KnowledgeUnsupportedCapabilityError`: its `check` callback cannot be sent to the hosted store. -- Credential priority: option `accessToken`, `MASTRA_PLATFORM_ACCESS_TOKEN`, `MASTRA_PLATFORM_SECRET_KEY`. -- The server checks that the instance belongs to the credential's organization and, for project-bound tokens, its project; it allowlists page-store operations and never accepts a connection string from the caller. -- Hosted Knowledge requires a core and PostgreSQL adapter release implementing the Knowledge pages-v4 contract; production release alignment remains pending. - -## Documentation - -`PlatformKnowledge` extends core `Knowledge` and delegates schema-v4 page-store operations to the hosted service. The provider, connection string, importer, and sync scheduler belong to Platform rather than this client. For general API concepts, see [Mastra documentation](https://mastra.ai/docs). - -### Verification matrix - -The same scenarios must run once with core `Knowledge` on local PostgreSQL and again with `PlatformKnowledge` against Compose-backed Platform: scope materialization and discovery; nested page create/update/move/delete; search and read; notes and links; pin visibility; editor/viewer access; agent tool attachment, including denial across scopes. Connect-backed source provisioning, import, and incremental re-sync require a separate linked-source scenario; host page writes alone do not prove this integration. - -## Changelog - -See the [package changelog](https://github.com/mastra-ai/mastra/blob/main/packages/platform/CHANGELOG.md). - -## Support - -We have an [open community Discord](https://discord.gg/mastra-ai). Come and say hello and let us know if you have any questions or need any help getting things running. diff --git a/packages/platform/package.json b/packages/platform/package.json deleted file mode 100644 index ca690d37ca0..00000000000 --- a/packages/platform/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "name": "@mastra/platform", - "version": "0.1.0-alpha.1", - "description": "Mastra Platform hosted Memory, Knowledge, Browser, and workspace clients", - "type": "module", - "main": "dist/index.js", - "types": "dist/index.d.ts", - "exports": { - ".": { - "import": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - }, - "require": { - "types": "./dist/index.d.ts", - "default": "./dist/index.cjs" - } - }, - "./package.json": "./package.json" - }, - "scripts": { - "build": "tsdown --silent --config tsdown.config.ts", - "build:lib": "pnpm build", - "build:watch": "pnpm build --watch", - "test:unit": "vitest run", - "test": "pnpm test:unit", - "lint": "oxlint --type-aware .", - "lint:fix": "oxlint --type-aware --fix ." - }, - "license": "Apache-2.0", - "devDependencies": { - "@internal/ai-sdk-v5": "workspace:*", - "@internal/types-builder": "workspace:*", - "@mastra/core": "workspace:*", - "@mastra/memory": "workspace:*", - "@types/node": "22.20.1", - "@vitest/coverage-v8": "catalog:", - "@vitest/ui": "catalog:", - "tsdown": "0.22.9", - "typescript": "catalog:", - "vitest": "catalog:", - "zod": "catalog:", - "@mastra/pg": "workspace:*", - "@mastra/platform-workspace": "workspace:*" - }, - "peerDependencies": { - "@mastra/core": ">=1.82.0-0 <2.0.0-0", - "zod": "^3.25.0 || ^4.0.0" - }, - "files": [ - "dist" - ], - "homepage": "https://mastra.ai", - "repository": { - "type": "git", - "url": "git+https://github.com/mastra-ai/mastra.git", - "directory": "packages/platform" - }, - "bugs": { - "url": "https://github.com/mastra-ai/mastra/issues" - }, - "engines": { - "node": ">=22.13.0" - }, - "dependencies": { - "@mastra/platform-workspace": "workspace:*", - "@mastra/stagehand": "workspace:*" - } -} diff --git a/packages/platform/src/browser/index.ts b/packages/platform/src/browser/index.ts deleted file mode 100644 index e22d09b5cee..00000000000 --- a/packages/platform/src/browser/index.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { StagehandBrowser } from '@mastra/stagehand'; -import type { StagehandBrowserConfig } from '@mastra/stagehand'; - -export interface PlatformBrowserOptions extends Omit< - StagehandBrowserConfig, - 'cdpUrl' | 'scope' | 'env' | 'apiKey' | 'projectId' -> { - /** Existing Platform-provisioned CDP URL. When supplied, no API request or access token is needed. */ - cdpUrl?: string; - /** Platform access token. Falls back to `MASTRA_PLATFORM_ACCESS_TOKEN`, then `MASTRA_PLATFORM_SECRET_KEY`. */ - accessToken?: string; - /** Mastra Platform project ID. Falls back to `MASTRA_PROJECT_ID`. */ - projectId?: string; - /** Browser provisioning API URL. Falls back to `MASTRA_BROWSER_API_URL`. */ - apiUrl?: string; - fetch?: typeof fetch; -} - -const DEFAULT_API_URL = 'https://platform.mastra.ai'; - -function trimTrailingSlashes(url: string): string { - let end = url.length; - while (end > 0 && url[end - 1] === '/') end--; - return url.slice(0, end); -} - -/** A Stagehand browser connected to a Platform-provisioned Browserbase session. */ -export class PlatformBrowser extends StagehandBrowser { - constructor(options: PlatformBrowserOptions = {}) { - const { - cdpUrl, - accessToken = process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY, - projectId = process.env.MASTRA_PROJECT_ID, - apiUrl = process.env.MASTRA_BROWSER_API_URL ?? DEFAULT_API_URL, - fetch: fetchImpl = fetch, - ...stagehandOptions - } = options; - if (!cdpUrl && !accessToken) throw new Error('PlatformBrowser: accessToken is required'); - if (!cdpUrl && !projectId) throw new Error('PlatformBrowser: projectId is required'); - - super({ - ...stagehandOptions, - scope: 'shared', - cdpUrl: - cdpUrl || - (async () => { - const response = await fetchImpl(`${trimTrailingSlashes(apiUrl)}/v1/browsers/sessions`, { - method: 'POST', - headers: { - authorization: `Bearer ${accessToken}`, - 'content-type': 'application/json', - }, - body: JSON.stringify({ projectId }), - signal: AbortSignal.timeout(30_000), - }); - if (!response.ok) throw new Error(`PlatformBrowser: browser provisioning failed (${response.status})`); - const result: unknown = await response.json(); - if ( - !result || - typeof result !== 'object' || - !('connectUrl' in result) || - typeof result.connectUrl !== 'string' - ) { - throw new Error('PlatformBrowser: browser provisioning returned no connectUrl'); - } - return result.connectUrl; - }), - }); - } -} diff --git a/packages/platform/src/browser/platform-browser.test.ts b/packages/platform/src/browser/platform-browser.test.ts deleted file mode 100644 index fa818551d80..00000000000 --- a/packages/platform/src/browser/platform-browser.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest'; - -vi.mock('@mastra/stagehand', () => ({ - StagehandBrowser: class { - constructor(private readonly config: { cdpUrl: string | (() => Promise); scope: string }) {} - async ensureReady() { - return typeof this.config.cdpUrl === 'string' ? this.config.cdpUrl : this.config.cdpUrl(); - } - }, -})); - -import { PlatformBrowser } from './index'; - -const originalEnv = { ...process.env }; -afterEach(() => { - process.env = { ...originalEnv }; -}); - -describe('PlatformBrowser provisioning', () => { - it('connects to a supplied CDP URL without provisioning or Platform credentials', async () => { - delete process.env.MASTRA_PLATFORM_SECRET_KEY; - delete process.env.MASTRA_PLATFORM_ACCESS_TOKEN; - delete process.env.MASTRA_PROJECT_ID; - const fetchImpl = vi.fn(); - const browser = new PlatformBrowser({ cdpUrl: 'wss://connect.browserbase.com/session-existing', fetch: fetchImpl }); - expect(await browser.ensureReady()).toBe('wss://connect.browserbase.com/session-existing'); - expect(fetchImpl).not.toHaveBeenCalled(); - }); - - it('provisions a shared remote browser through Platform without sending Browserbase credentials to the client', async () => { - const fetchImpl = vi.fn(async (url, init) => { - expect(url).toBe('https://platform.mastra.ai/v1/browsers/sessions'); - expect(init?.method).toBe('POST'); - expect(new Headers(init?.headers).get('authorization')).toBe('Bearer org-secret'); - expect(JSON.parse(String(init?.body))).toEqual({ projectId: 'project-1' }); - return Response.json({ connectUrl: 'wss://connect.browserbase.com/session-1' }); - }); - const browser = new PlatformBrowser({ accessToken: 'org-secret', projectId: 'project-1', fetch: fetchImpl }); - expect(await browser.ensureReady()).toBe('wss://connect.browserbase.com/session-1'); - expect(fetchImpl).toHaveBeenCalledOnce(); - }); - - it('drops trailing slashes from the API URL before adding the sessions path', async () => { - const fetchImpl = vi.fn(async () => Response.json({ connectUrl: 'wss://connect.browserbase.com/s' })); - const browser = new PlatformBrowser({ - accessToken: 'org-secret', - projectId: 'project-1', - apiUrl: 'https://platform.staging.mastra.ai///', - fetch: fetchImpl, - }); - await browser.ensureReady(); - expect(fetchImpl.mock.calls[0]?.[0]).toBe('https://platform.staging.mastra.ai/v1/browsers/sessions'); - }); - - it('reports provisioning errors without exposing the access token', async () => { - const browser = new PlatformBrowser({ - accessToken: 'org-secret', - projectId: 'project-1', - fetch: async () => new Response('Browserbase credentials leaked', { status: 502 }), - }); - await expect(browser.ensureReady()).rejects.toThrow('PlatformBrowser: browser provisioning failed (502)'); - }); - - it('uses environment credentials and refuses to create a session without a project', async () => { - process.env.MASTRA_PLATFORM_SECRET_KEY = 'env-secret'; - delete process.env.MASTRA_PLATFORM_ACCESS_TOKEN; - delete process.env.MASTRA_PROJECT_ID; - expect(() => new PlatformBrowser()).toThrow('PlatformBrowser: projectId is required'); - }); -}); diff --git a/packages/platform/src/index.ts b/packages/platform/src/index.ts deleted file mode 100644 index 37591ecff85..00000000000 --- a/packages/platform/src/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -export * from './memory/index'; -export { PlatformBrowser } from './browser/index'; -export type { PlatformBrowserOptions } from './browser/index'; -export { PlatformKnowledge } from './knowledge/index'; -export type { PlatformKnowledgeOptions } from './knowledge/index'; -export * from '@mastra/platform-workspace'; diff --git a/packages/platform/src/knowledge/errors.test.ts b/packages/platform/src/knowledge/errors.test.ts deleted file mode 100644 index 6095a41d560..00000000000 --- a/packages/platform/src/knowledge/errors.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { createServer } from 'node:http'; -import { - KnowledgeConflictError, - KnowledgeNotFoundError, - KnowledgePageHasChildrenError, - KnowledgePageKeyConflictError, -} from '@mastra/core/storage'; -import { afterEach, expect, it } from 'vitest'; - -import { PlatformKnowledge } from './index'; - -const servers: ReturnType[] = []; -afterEach(async () => { - await Promise.all(servers.splice(0).map(server => new Promise(resolve => server.close(() => resolve())))); -}); - -it.each([ - { status: 404, name: 'KnowledgeNotFoundError', type: KnowledgeNotFoundError }, - { status: 409, name: 'KnowledgeConflictError', type: KnowledgeConflictError }, - { status: 409, name: 'KnowledgePageKeyConflictError', type: KnowledgePageKeyConflictError }, - { status: 409, name: 'KnowledgePageHasChildrenError', type: KnowledgePageHasChildrenError }, -])('preserves $name from problem+json responses', async ({ status, name, type }) => { - const server = createServer((_req, res) => { - res.writeHead(status, { 'content-type': 'application/problem+json' }); - res.end(JSON.stringify({ name, detail: 'specific knowledge failure', title: 'Generic failure' })); - }); - servers.push(server); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const address = server.address(); - if (!address || typeof address === 'string') throw new Error('Expected a TCP port'); - const storage = await new PlatformKnowledge({ - apiUrl: `http://127.0.0.1:${address.port}`, - instanceId: 'instance', - accessToken: 'token', - }).getStorage(); - await expect(storage.listPages({ read: 'all' })).rejects.toThrow(type); - await expect(storage.listPages({ read: 'all' })).rejects.toThrow('specific knowledge failure'); -}); - -it('prefers the nested error message over a generic title', async () => { - const server = createServer((_req, res) => { - res.writeHead(400, { 'content-type': 'application/json' }); - res.end(JSON.stringify({ title: 'Bad Request', error: { message: 'pageKey is required' } })); - }); - servers.push(server); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const address = server.address(); - if (!address || typeof address === 'string') throw new Error('Expected a TCP port'); - const storage = await new PlatformKnowledge({ - apiUrl: `http://127.0.0.1:${address.port}`, - instanceId: 'instance', - accessToken: 'token', - }).getStorage(); - await expect(storage.listPages({ read: 'all' })).rejects.toThrow('pageKey is required'); -}); - -it('returns an HTTP status error rather than a SyntaxError for non-JSON gateway failures', async () => { - const server = createServer((_req, res) => { - res.writeHead(502, { 'content-type': 'text/html' }); - res.end('Bad gateway'); - }); - servers.push(server); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const address = server.address(); - if (!address || typeof address === 'string') throw new Error('Expected a TCP port'); - const storage = await new PlatformKnowledge({ - apiUrl: `http://127.0.0.1:${address.port}`, - instanceId: 'instance', - accessToken: 'token', - }).getStorage(); - await expect(storage.listPages({ read: 'all' })).rejects.toThrow( - 'Knowledge request failed (502): Bad gateway', - ); -}); - -it('keeps the HTTP status when the error body is JSON null', async () => { - const server = createServer((_req, res) => { - res.writeHead(500, { 'content-type': 'application/json' }); - res.end('null'); - }); - servers.push(server); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const address = server.address(); - if (!address || typeof address === 'string') throw new Error('Expected a TCP port'); - const storage = await new PlatformKnowledge({ - apiUrl: `http://127.0.0.1:${address.port}`, - instanceId: 'instance', - accessToken: 'token', - }).getStorage(); - await expect(storage.listPages({ read: 'all' })).rejects.toThrow('Knowledge request failed (500): null'); -}); - -async function storageAnswering(status: number, body: unknown) { - const server = createServer((_req, res) => { - res.writeHead(status, { 'content-type': 'application/problem+json' }); - res.end(JSON.stringify(body)); - }); - servers.push(server); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const address = server.address(); - if (!address || typeof address === 'string') throw new Error('Expected a TCP port'); - return new PlatformKnowledge({ - apiUrl: `http://127.0.0.1:${address.port}`, - instanceId: 'instance', - accessToken: 'token', - }).getStorage(); -} - -it('reads no scope declarations from a service without the getScopeDeclarations operation', async () => { - const storage = await storageAnswering(404, { title: 'Not Found', detail: 'Knowledge operation not found' }); - await expect(storage.getScopeDeclarations()).resolves.toEqual({}); -}); - -it('still fails getScopeDeclarations for a missing instance, any other 404, or a server error', async () => { - const missing = await storageAnswering(404, { title: 'Not Found', detail: 'Knowledge instance not found' }); - await expect(missing.getScopeDeclarations()).rejects.toThrow('Knowledge instance not found'); - const elsewhere = await storageAnswering(404, { title: 'Not Found' }); - await expect(elsewhere.getScopeDeclarations()).rejects.toThrow('Not Found'); - const broken = await storageAnswering(500, { title: 'Internal Server Error' }); - await expect(broken.getScopeDeclarations()).rejects.toThrow('Internal Server Error'); -}); diff --git a/packages/platform/src/knowledge/index.ts b/packages/platform/src/knowledge/index.ts deleted file mode 100644 index 7eef8d9baac..00000000000 --- a/packages/platform/src/knowledge/index.ts +++ /dev/null @@ -1,237 +0,0 @@ -import { Knowledge } from '@mastra/core/knowledge'; -import type { KnowledgeConfig, KnowledgeScopeDeclarations } from '@mastra/core/knowledge'; -import { - MastraCompositeStore, - KnowledgeStorage, - KnowledgeConflictError, - KnowledgeNotFoundError, - KnowledgePageHasChildrenError, - KnowledgePageKeyConflictError, -} from '@mastra/core/storage'; -import type { KnowledgePageStore } from '@mastra/core/storage'; - -export interface PlatformKnowledgeOptions extends Omit< - KnowledgeConfig, - 'storage' | 'vector' | 'embedder' | 'embedderOptions' | 'scopes' -> { - accessToken?: string; - projectId?: string; - instanceId?: string; - /** - * Knowledge API URL. Falls back to `MASTRA_KNOWLEDGE_API_URL`, then `https://knowledge-api.mastra.ai`. - */ - apiUrl?: string; -} - -// These are the schema-v4 page-store methods, not arbitrary object properties or storage lifecycle methods. -// `renameScopeDeclaration` is left to the base class, which rejects it: its `check` callback can't be -// serialized, so the hosted store couldn't validate affected scopes before re-keying them. -const operations = [ - 'materializeScope', - 'getScopesByAddress', - 'listScopeDeclarations', - 'listChildScopes', - 'countChildScopes', - 'getPage', - 'getPages', - 'getPageByPath', - 'findPagesByName', - 'listChildPages', - 'countChildPages', - 'listPages', - 'createPage', - 'updatePage', - 'movePage', - 'mergePages', - 'deletePage', - 'getNote', - 'countNotes', - 'listNotes', - 'listNotesMentioning', - 'addNote', - 'restampNote', - 'removeNote', - 'restoreNote', - 'searchPages', - 'listPageActivity', - 'addPinAudience', - 'removePinAudience', - 'listPins', - 'countPageLinks', - 'listPageLinks', - 'replacePageBodyLinks', - 'listPageBodyLinkSources', -] as const satisfies readonly (keyof KnowledgePageStore)[]; - -// Fails to compile when a page-store method is neither forwarded nor deliberately left to the base class. -type UnforwardedOperation = Exclude; -const operationsAreExhaustive: [UnforwardedOperation] extends ['renameScopeDeclaration'] - ? ['renameScopeDeclaration'] extends [UnforwardedOperation] - ? true - : never - : never = true; -void operationsAreExhaustive; - -function encode(value: unknown): string { - return JSON.stringify(value, function (key, item: unknown) { - const original: unknown = key ? (this as Record)[key] : item; - return original instanceof Date ? { __knowledgeDate: original.toISOString() } : item; - }); -} - -function decode(text: string): T { - return JSON.parse(text, (_key, value: unknown) => { - if (value && typeof value === 'object' && '__knowledgeDate' in value) { - return new Date((value as { __knowledgeDate: string }).__knowledgeDate); - } - return value; - }) as T; -} - -class RemoteKnowledgeStorage extends KnowledgeStorage { - constructor( - private readonly endpoint: string, - private readonly token: string, - ) { - super({ storageIsolationKey: endpoint }); - return new Proxy(this, { - get(target, key) { - if (typeof key === 'string' && operations.includes(key as (typeof operations)[number])) { - return (input?: unknown) => target.request(key, input); - } - const value: unknown = Reflect.get(target, key, target); - return typeof value === 'function' ? value.bind(target) : value; - }, - }); - } - - private async request(operation: string, input?: unknown): Promise { - const response = await fetch(`${this.endpoint}/operations/${operation}`, { - method: 'POST', - headers: { - authorization: `Bearer ${this.token}`, - 'content-type': 'application/json', - // This client merges the instance's scope declarations (`getScopeDeclarations`) into its own, so - // the service leaves its read views as they are rather than widening them for older clients. - 'x-mastra-knowledge-store-declarations': 'merged', - }, - body: encode({ input }), - signal: AbortSignal.timeout(30_000), - }); - const text = await response.text(); - if (!response.ok) { - let body: { name?: string; detail?: string; title?: string; error?: { name?: string; message?: string } } = {}; - try { - const parsed: unknown = JSON.parse(text); - if (parsed && typeof parsed === 'object') body = parsed; - } catch { - // Gateways can return non-JSON error pages. - } - const message = - body.detail || - body.error?.message || - body.title || - (text - ? `Knowledge request failed (${response.status}): ${text}` - : `Knowledge request failed (${response.status})`); - const name = body.name ?? body.error?.name; - if (name === 'KnowledgeNotFoundError') { - const error = new KnowledgeNotFoundError('record', operation); - error.message = message; - throw error; - } - if (name === 'KnowledgeConflictError') { - const error = new KnowledgeConflictError(operation); - error.message = message; - throw error; - } - if (name === 'KnowledgePageKeyConflictError') { - const error = new KnowledgePageKeyConflictError('', ''); - error.message = message; - throw error; - } - if (name === 'KnowledgePageHasChildrenError') { - const error = new KnowledgePageHasChildrenError(''); - error.message = message; - throw error; - } - throw Object.assign(new Error(message), { status: response.status }); - } - return decode<{ result?: unknown }>(text).result; - } - - /** - * The scope declarations the instance supplies, such as the ones its importers write to, with their - * access rules. A service that doesn't have the operation yet answers 404 "Knowledge operation not - * found" and supplies none. Any other failure, including another 404 (a missing instance, a wrong - * URL), and anything but a declaration record is a broken response, not "none". - */ - override async getScopeDeclarations(): Promise { - let result: unknown; - try { - result = await this.request('getScopeDeclarations'); - } catch (error) { - const status = (error as { status?: unknown }).status; - if (status === 404 && (error as Error).message === 'Knowledge operation not found') return {}; - throw error; - } - if (!result || typeof result !== 'object' || Array.isArray(result)) { - throw new Error('Knowledge service answered getScopeDeclarations without a declaration record'); - } - return result as KnowledgeScopeDeclarations; - } - - override getCapabilities() { - return { - contractVersion: 4, - schemaVersion: 4, - supportsSchemaInspection: false, - supportsExplicitReset: false, - // The service's stores keep a pin's kind and depth, so listing pins round-trip. - supportsPinKinds: true, - } as const; - } - - override async dangerouslyClearAll(): Promise { - throw new Error('Hosted Knowledge cannot be cleared from the client'); - } -} - -const DEFAULT_API_URL = 'https://knowledge-api.mastra.ai'; - -export class PlatformKnowledge extends Knowledge { - constructor(options: PlatformKnowledgeOptions = {}) { - const token = - options.accessToken ?? process.env.MASTRA_PLATFORM_ACCESS_TOKEN ?? process.env.MASTRA_PLATFORM_SECRET_KEY; - const instanceId = options.instanceId ?? process.env.MASTRA_KNOWLEDGE_INSTANCE_ID; - const apiUrl = options.apiUrl ?? (process.env.MASTRA_KNOWLEDGE_API_URL?.trim() || undefined) ?? DEFAULT_API_URL; - if (!token || !instanceId) { - throw new Error('PlatformKnowledge requires a Platform access token and Knowledge instance ID'); - } - const { - accessToken: _accessToken, - projectId: _projectId, - instanceId: _instanceId, - apiUrl: _apiUrl, - ...config - } = options; - const endpoint = `${apiUrl.replace(/\/$/, '')}/v1/knowledge/${encodeURIComponent(instanceId)}`; - const storage = new MastraCompositeStore({ - id: `platform-knowledge-${instanceId}`, - domains: { knowledge: new RemoteKnowledgeStorage(endpoint, token) }, - }); - super({ - ...config, - tools: config.tools ?? { read: true }, - // Platform owns every scope declaration and access grant: the instance serves them all through - // `getScopeDeclarations`, so there is one place to change who reads what. Declaring scopes here - // too would conflict with the instance's (a key both declare silently takes the code's rules, - // and overlapping patterns break every call), so PlatformKnowledge takes no `scopes` option. - scopes: {}, - storage, - }); - } -} - -export { encode as encodeKnowledgeTransport, decode as decodeKnowledgeTransport }; -export { operations as knowledgeOperations }; diff --git a/packages/platform/src/knowledge/parity.integration.test.ts b/packages/platform/src/knowledge/parity.integration.test.ts deleted file mode 100644 index 7bcf17c2867..00000000000 --- a/packages/platform/src/knowledge/parity.integration.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { MockLanguageModelV2 } from '@internal/ai-sdk-v5/test'; -import { Agent } from '@mastra/core/agent'; -import { Knowledge, knowledgeMemoryScopes } from '@mastra/core/knowledge'; -import { PostgresStore } from '@mastra/pg'; -import { describe, expect, it } from 'vitest'; -import { PlatformKnowledge } from './index'; - -const apiUrl = process.env.KNOWLEDGE_TEST_API_URL; -const databaseUrl = process.env.KNOWLEDGE_TEST_DATABASE_URL; -const instanceId = process.env.MASTRA_KNOWLEDGE_INSTANCE_ID; -const token = process.env.MASTRA_PLATFORM_ACCESS_TOKEN; - -function searchModel() { - let step = 0; - return new MockLanguageModelV2({ - doGenerate: async () => ({ - rawCall: { rawPrompt: null, rawSettings: {} }, - finishReason: (step++ === 0 ? 'tool-calls' : 'stop') as 'tool-calls' | 'stop', - usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 }, - content: - step === 1 - ? [ - { - type: 'tool-call' as const, - toolCallId: 'search-1', - toolName: 'knowledge_search', - input: JSON.stringify({ query: 'integration' }), - }, - ] - : [{ type: 'text' as const, text: 'Done.' }], - warnings: [], - }), - }); -} - -describe.runIf(apiUrl && databaseUrl && instanceId && token)('Postgres and PlatformKnowledge public API parity', () => { - const runId = randomUUID(); - const scope = `resource:${runId}`; - const scopes = { ...knowledgeMemoryScopes(), 'docs:$instanceId': { access: [] } }; - it('matches host writes, discovery, search, reads, and agent scope denial', async () => { - const directStore = new PostgresStore({ id: `direct-knowledge-${runId}`, connectionString: databaseUrl! }); - const direct = new Knowledge({ scopes, storage: directStore, tools: true }); - // The instance serves the declarations, Memory's among them; PlatformKnowledge declares none. - const remote = new PlatformKnowledge({ tools: true, apiUrl, instanceId, accessToken: token }); - try { - for (const knowledge of [direct, remote]) { - const rootScope = `org:${randomUUID()}`; - const page = await knowledge.upsertPage({ - scope: rootScope, - path: 'integration-guide', - name: 'Integration guide', - body: 'Knowledge integration works', - author: 'host', - }); - expect(page.page.name).toBe('Integration guide'); - const store = await knowledge.getStorage(); - const read = await knowledge.readScopeFor([rootScope]); - expect((await store.listPages({ read })).pages.map(p => p.name)).toContain('Integration guide'); - expect((await store.searchPages({ query: 'integration', read })).map(hit => hit.page.name)).toContain( - 'Integration guide', - ); - expect((await store.getPage({ id: page.page.id, read }))?.body).toBe('Knowledge integration works'); - const unchanged = await knowledge.upsertPage({ - scope: rootScope, - path: 'integration-guide', - name: 'Integration guide', - body: 'Knowledge integration works', - }); - expect(unchanged.status).toBe('unchanged'); - const updated = await knowledge.upsertPage({ - scope: rootScope, - path: 'integration-guide', - name: 'Integration guide', - body: 'Knowledge integration works again', - }); - expect(updated.status).toBe('updated'); - const when = new Date('2026-01-02T03:04:05Z'); - const note = await knowledge.addNote({ - scope: rootScope, - path: 'integration-guide', - text: 'Confirmed by host', - when, - }); - expect((await store.getNote({ id: note.id, read }))?.when).toEqual(when); - const agent = new Agent({ - id: `reader-${randomUUID()}`, - name: 'Reader', - instructions: 'Search knowledge.', - model: searchModel(), - knowledge, - scopes: [rootScope], - }); - const result = await agent.generate('Find the integration guide.', { - maxSteps: 2, - memory: { thread: 'thread-1', resource: runId }, - }); - expect(JSON.stringify(result.steps.flatMap(step => step.toolResults))).toContain('Integration guide'); - const denied = await knowledge.readScopeFor([scope]); - expect(await store.searchPages({ query: 'integration', read: denied })).toHaveLength(0); - } - } finally { - await directStore.close(); - } - }); - - it('rejects invalid project credentials and foreign instances before storage access', async () => { - for (const options of [ - { accessToken: 'wrong', instanceId }, - { accessToken: token, instanceId: 'foreign-instance' }, - ]) { - const knowledge = new PlatformKnowledge({ apiUrl, ...options }); - await expect(knowledge.getStorage().then(store => store.listPages({ read: 'all' }))).rejects.toThrow(); - } - }); -}); diff --git a/packages/platform/src/knowledge/route.test.ts b/packages/platform/src/knowledge/route.test.ts deleted file mode 100644 index 009aef71432..00000000000 --- a/packages/platform/src/knowledge/route.test.ts +++ /dev/null @@ -1,242 +0,0 @@ -import { createServer } from 'node:http'; -import { - InMemoryStore, - KnowledgeConflictError, - KnowledgeNotFoundError, - KnowledgeUnsupportedCapabilityError, -} from '@mastra/core/storage'; -import type { KnowledgeStorage } from '@mastra/core/storage'; -import { afterEach, expect, it, vi } from 'vitest'; -import { PlatformKnowledge } from './index'; - -const servers: ReturnType[] = []; -afterEach(async () => { - await Promise.all(servers.splice(0).map(server => new Promise(resolve => server.close(() => resolve())))); -}); - -it('uses the project-scoped operation route with bearer auth', async () => { - const requests: { url?: string; authorization?: string; declarations?: string | string[]; body: string }[] = []; - const server = createServer(async (req, res) => { - let body = ''; - for await (const chunk of req) body += chunk; - requests.push({ - url: req.url, - authorization: req.headers.authorization, - declarations: req.headers['x-mastra-knowledge-store-declarations'], - body, - }); - res.setHeader('content-type', 'application/json'); - res.end(JSON.stringify({ result: { pages: [] } })); - }); - servers.push(server); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const address = server.address(); - if (!address || typeof address === 'string') throw new Error('Expected a TCP port'); - const knowledge = new PlatformKnowledge({ - apiUrl: `http://127.0.0.1:${address.port}`, - projectId: 'project/one', - instanceId: 'instance two', - accessToken: 'token', - }); - const store = await knowledge.getStorage(); - expect(await store.listPages({ read: 'all' })).toEqual({ pages: [] }); - expect(requests).toEqual([ - { - url: '/v1/knowledge/instance%20two/operations/listPages', - authorization: 'Bearer token', - // Tells the service this client reads the instance's declarations, so it doesn't widen reads. - declarations: 'merged', - body: JSON.stringify({ input: { read: 'all' } }), - }, - ]); -}); - -it('asks the hosted store for the scope declarations its instance supplies', async () => { - const urls: string[] = []; - const declarations = { 'linear:$account:$connection': { access: [{ principal: 'imports:all', role: 'viewer' }] } }; - vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { - urls.push(String(input)); - return new Response(JSON.stringify({ result: declarations })); - }); - const store = (await new PlatformKnowledge({ - apiUrl: 'http://localhost', - instanceId: 'kn_1', - accessToken: 'token', - }).getStorage())!; - try { - expect(await store.getScopeDeclarations()).toEqual(declarations); - expect(urls).toEqual(['http://localhost/v1/knowledge/kn_1/operations/getScopeDeclarations']); - } finally { - vi.restoreAllMocks(); - } -}); - -it.each([{}, { result: null }, { result: ['linear:$account:$connection'] }])( - 'rejects a hosted answer without a declaration record: %j', - async body => { - vi.spyOn(globalThis, 'fetch').mockImplementation(async () => new Response(JSON.stringify(body))); - const store = (await new PlatformKnowledge({ - apiUrl: 'http://localhost', - instanceId: 'kn_1', - accessToken: 'token', - }).getStorage())!; - try { - await expect(store.getScopeDeclarations()).rejects.toThrow(/without a declaration record/); - } finally { - vi.restoreAllMocks(); - } - }, -); - -it('allows the project to be derived from the instance and credential', () => { - expect( - () => new PlatformKnowledge({ apiUrl: 'http://localhost', instanceId: 'instance', accessToken: 'token' }), - ).not.toThrow(); -}); - -it('defaults to the hosted Knowledge API and accepts an env or explicit URL override', async () => { - const urls: string[] = []; - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { - urls.push(String(input)); - return new Response(JSON.stringify({ result: { pages: [] } }), { headers: { 'content-type': 'application/json' } }); - }); - const previousUrl = process.env.MASTRA_KNOWLEDGE_API_URL; - const previousServiceUrl = process.env.MASTRA_KNOWLEDGE_SERVICE_URL; - try { - delete process.env.MASTRA_KNOWLEDGE_API_URL; - delete process.env.MASTRA_KNOWLEDGE_SERVICE_URL; - const options = { instanceId: 'kn_1', accessToken: 'token' }; - await (await new PlatformKnowledge(options).getStorage()).listPages({ read: 'all' }); - process.env.MASTRA_KNOWLEDGE_SERVICE_URL = 'http://injected.local/'; - await (await new PlatformKnowledge(options).getStorage()).listPages({ read: 'all' }); - process.env.MASTRA_KNOWLEDGE_API_URL = 'http://localhost:3062/'; - await (await new PlatformKnowledge(options).getStorage()).listPages({ read: 'all' }); - await ( - await new PlatformKnowledge({ ...options, apiUrl: 'http://localhost:8080/' }).getStorage() - ).listPages({ read: 'all' }); - } finally { - if (previousUrl === undefined) delete process.env.MASTRA_KNOWLEDGE_API_URL; - else process.env.MASTRA_KNOWLEDGE_API_URL = previousUrl; - if (previousServiceUrl === undefined) delete process.env.MASTRA_KNOWLEDGE_SERVICE_URL; - else process.env.MASTRA_KNOWLEDGE_SERVICE_URL = previousServiceUrl; - fetchSpy.mockRestore(); - } - expect(urls).toEqual([ - 'https://knowledge-api.mastra.ai/v1/knowledge/kn_1/operations/listPages', - 'https://knowledge-api.mastra.ai/v1/knowledge/kn_1/operations/listPages', - 'http://localhost:3062/v1/knowledge/kn_1/operations/listPages', - 'http://localhost:8080/v1/knowledge/kn_1/operations/listPages', - ]); -}); - -it('forwards the page-link and child-scope operations instead of rejecting them locally', async () => { - const operations: { operation: string; body: string }[] = []; - const server = createServer(async (req, res) => { - let body = ''; - for await (const chunk of req) body += chunk; - operations.push({ operation: req.url!.split('/').pop()!, body }); - res.setHeader('content-type', 'application/json'); - res.end(JSON.stringify({ result: [] })); - }); - servers.push(server); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const address = server.address(); - if (!address || typeof address === 'string') throw new Error('Expected a TCP port'); - const store = await new PlatformKnowledge({ - apiUrl: `http://127.0.0.1:${address.port}`, - instanceId: 'instance', - accessToken: 'token', - }).getStorage(); - await store.countChildScopes({ parentIds: ['a'], read: 'all' }); - await store.countPageLinks({ pageIds: ['a'], read: 'all' }); - await store.listPageLinks({ pageIds: ['a'], read: 'all' }); - await store.replacePageBodyLinks({ pageId: 'a', links: [] }); - await store.listPageBodyLinkSources({ refs: ['b'], toPageIds: ['a'] }); - expect(operations).toEqual([ - { operation: 'countChildScopes', body: JSON.stringify({ input: { parentIds: ['a'], read: 'all' } }) }, - { operation: 'countPageLinks', body: JSON.stringify({ input: { pageIds: ['a'], read: 'all' } }) }, - { operation: 'listPageLinks', body: JSON.stringify({ input: { pageIds: ['a'], read: 'all' } }) }, - { operation: 'replacePageBodyLinks', body: JSON.stringify({ input: { pageId: 'a', links: [] } }) }, - { operation: 'listPageBodyLinkSources', body: JSON.stringify({ input: { refs: ['b'], toPageIds: ['a'] } }) }, - ]); -}); - -it('rejects scope declaration renames locally because the rename check cannot cross the wire', async () => { - const fetchSpy = vi.spyOn(globalThis, 'fetch'); - try { - const knowledge = new PlatformKnowledge({ - apiUrl: 'http://localhost', - instanceId: 'instance', - accessToken: 'token', - }); - const store = await knowledge.getStorage(); - const check = vi.fn(); - await expect(store.renameScopeDeclaration({ from: 'a', to: 'b', check })).rejects.toBeInstanceOf( - KnowledgeUnsupportedCapabilityError, - ); - expect(check).not.toHaveBeenCalled(); - expect(fetchSpy).not.toHaveBeenCalled(); - } finally { - fetchSpy.mockRestore(); - } -}); - -it('keeps page and listing pins apart on the same page through the hosted operation route', async () => { - // A stand-in for the Knowledge service: each operation runs on a real in-memory store. - const backing = (await new InMemoryStore().getStore('knowledge')) as KnowledgeStorage; - const revive = (_key: string, value: unknown) => - value && typeof value === 'object' && '__knowledgeDate' in value - ? new Date((value as { __knowledgeDate: string }).__knowledgeDate) - : value; - const server = createServer(async (req, res) => { - let body = ''; - for await (const chunk of req) body += chunk; - const operation = req.url!.split('/').pop()!; - const { input } = JSON.parse(body, revive) as { input: unknown }; - const result = await (backing as unknown as Record Promise>)[operation]!( - input, - ); - res.setHeader('content-type', 'application/json'); - res.end(JSON.stringify({ result: result ?? null })); - }); - servers.push(server); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const address = server.address(); - if (!address || typeof address === 'string') throw new Error('Expected a TCP port'); - const store = await new PlatformKnowledge({ - apiUrl: `http://127.0.0.1:${address.port}`, - instanceId: 'instance', - accessToken: 'token', - }).getStorage(); - - // knowledge_pin refuses `kind: 'list'` before writing unless the store says it keeps pin kinds. - expect(store.getCapabilities().supportsPinKinds).toBe(true); - - const provenance = { author: 'host' }; - const { scope } = await store.materializeScope({ - address: 'org:acme', - declaration: 'org:$orgId', - name: 'Acme', - provenance, - }); - const page = await store.createPage({ - parentId: scope.id, - key: 'handbook', - name: 'Handbook', - body: 'Hi.', - provenance, - }); - await store.addPinAudience({ pageId: page.id, audience: ['org:acme'], createdBy: 'agent' }); - await store.addPinAudience({ pageId: page.id, kind: 'list', depth: 2, audience: ['org:acme'], createdBy: 'agent' }); - - const pins = async (kind?: 'page' | 'list') => - (await store.listPins({ audience: 'all', read: 'all', kind })).pins.map(pin => ({ - kind: pin.kind, - depth: pin.depth, - })); - expect(await pins('page')).toEqual([{ kind: 'page', depth: undefined }]); - expect(await pins('list')).toEqual([{ kind: 'list', depth: 2 }]); - - await store.removePinAudience({ pageId: page.id, kind: 'list', audience: ['org:acme'], removedBy: 'agent' }); - expect(await pins()).toEqual([{ kind: 'page', depth: undefined }]); -}); diff --git a/packages/platform/src/memory/client.ts b/packages/platform/src/memory/client.ts deleted file mode 100644 index 4296b163b48..00000000000 --- a/packages/platform/src/memory/client.ts +++ /dev/null @@ -1,358 +0,0 @@ -export interface PlatformMemoryClientOptions { - /** Platform access token. Falls back to `MASTRA_PLATFORM_ACCESS_TOKEN`, then `MASTRA_PLATFORM_SECRET_KEY`. */ - accessToken?: string; - /** Memory instance id. Falls back to `MASTRA_MEMORY_INSTANCE_ID`. */ - instanceId?: string; - /** Falls back to `MASTRA_PROJECT_ID`. Sent as a hint; ownership is enforced server-side from the token. */ - projectId?: string; - /** Falls back to `MASTRA_ENVIRONMENT_ID`. */ - environmentId?: string; - /** Sent as `x-acting-user-id`, used by the API when the token is not tied to a user. */ - actingUserId?: string; - /** - * Memory API URL. Falls back to `MASTRA_MEMORY_API_URL`, then `https://memory-api.mastra.ai`. - */ - apiUrl?: string; - fetch?: typeof fetch; -} - -export interface MemoryThread { - id: string; - resourceId: string; - title: string | null; - metadata: Record | null; - createdAt: string; - updatedAt: string; -} - -export type MemoryMessagePart = { type: string; [key: string]: unknown }; - -export interface MemoryMessage { - id: string; - role: string; - content: string; - /** Mastra V2 parts (text, tool-invocation, reasoning, file, …), stored verbatim. */ - parts: MemoryMessagePart[]; - createdAt: string; -} - -export interface MemoryMessageInput { - id?: string; - role: 'user' | 'assistant'; - /** Text content. Optional when `parts` is set. */ - content?: string; - parts?: MemoryMessagePart[]; - createdAt?: string; -} - -export interface MemoryContext { - /** Rendered observations, ready to use as a system message. */ - system: string | null; - /** - * User-role reminder that goes before `messages` once observations exist, so the model - * continues the conversation instead of treating the observations as a new prompt. - * Older servers omit it. - */ - continuation?: string | null; - /** Messages not yet folded into observations, oldest first. */ - messages: MemoryMessage[]; - /** - * Ready-to-send prefix in `@mastra/memory` order: system (`om-system`), continuation - * (`om-continuation`), then `messages`. Older servers omit it; use `promptOf`. - */ - prompt?: MemoryMessage[]; - observedAt: string | null; -} - -export interface MemoryObservationRecord { - activeObservations: string | null; - lastObservedAt: string | null; - [key: string]: unknown; -} - -type SerializedMessageList = ReturnType; - -export type RunMemoryProcessorsInput = - | { - phase: 'inputStep'; - resourceId: string; - stepNumber: number; - messageList: SerializedMessageList; - model?: { provider: string; modelId: string }; - } - | { phase: 'output'; resourceId: string; messageList: SerializedMessageList; finishReason?: string }; - -export interface MemoryProcessorsResult { - /** Null when a processor aborted the run. */ - messageList: SerializedMessageList | null; - chunks: unknown[]; - rotations: number; - aborted: string | null; -} - -export interface MemoryObservationMatch { - text: string; - threadId: string | null; - observedAt: string | null; -} - -export interface MemoryThreadConfigUpdate { - observationTokens?: number | null; - reflectionTokens?: number | null; -} - -export interface MemoryThreadConfig { - observationTokens: number; - reflectionTokens: number; - overrides: { observationTokens: number | null; reflectionTokens: number | null }; -} - -export interface MemoryObservationRun { - id: string; - threadId: string; - resourceId: string; - startedAt: string; - durationMs: number; - observed: boolean; - reflected: boolean; - tokensBefore: number; - tokensAfter: number | null; - error: string | null; -} - -const DEFAULT_API_URL = 'https://memory-api.mastra.ai'; -const REQUEST_TIMEOUT_MS = 30_000; -// Processor runs execute the hosted observer/reflector (LLM calls) inside the request. -const PROCESSOR_TIMEOUT_MS = 5 * 60_000; - -function env(name: string): string | undefined { - return process.env[name]?.trim() || undefined; -} - -function required(value: string | undefined, name: string): string { - if (!value) throw new Error(`PlatformMemory: ${name} is required`); - return value; -} - -export function resolvePlatformMemoryOptions(options: PlatformMemoryClientOptions = {}) { - return { - accessToken: required( - options.accessToken ?? env('MASTRA_PLATFORM_ACCESS_TOKEN') ?? env('MASTRA_PLATFORM_SECRET_KEY'), - 'accessToken', - ), - instanceId: required(options.instanceId ?? env('MASTRA_MEMORY_INSTANCE_ID'), 'instanceId'), - projectId: options.projectId ?? env('MASTRA_PROJECT_ID'), - environmentId: options.environmentId ?? env('MASTRA_ENVIRONMENT_ID'), - actingUserId: options.actingUserId, - apiUrl: (options.apiUrl ?? env('MASTRA_MEMORY_API_URL') ?? DEFAULT_API_URL).replace(/\/$/, ''), - fetch: options.fetch ?? fetch, - }; -} - -export class PlatformMemoryApiError extends Error { - constructor( - readonly status: number, - readonly body: string, - ) { - super(`Platform Memory request failed with ${status}${body ? `: ${body}` : ''}`); - this.name = 'PlatformMemoryApiError'; - } -} - -type Query = Record; - -/** Typed client for the Platform Memory API (`/v1/memory/:instanceId/*`). */ -export class PlatformMemoryClient { - readonly instanceId: string; - private readonly opts: ReturnType; - - constructor(options: PlatformMemoryClientOptions = {}) { - this.opts = resolvePlatformMemoryOptions(options); - this.instanceId = this.opts.instanceId; - } - - /** MCP endpoint for this instance, for clients that speak MCP directly. */ - get mcpUrl(): string { - return `${this.base}/mcp`; - } - - listThreads(query: { resourceId?: string; page?: number; perPage?: number } = {}) { - return this.request<{ threads: MemoryThread[]; hasMore: boolean }>('GET', '/threads', { query }); - } - - createThread(body: { id?: string; resourceId: string; title?: string; metadata?: Record }) { - return this.request('POST', '/threads', { body }); - } - - /** Returns null when the thread does not exist. */ - async getThread(threadId: string): Promise { - try { - return await this.request('GET', `/threads/${encodeURIComponent(threadId)}`); - } catch (error) { - if (error instanceof PlatformMemoryApiError && error.status === 404) return null; - throw error; - } - } - - updateThread(threadId: string, body: { title?: string; metadata?: Record }) { - return this.request('PATCH', `/threads/${encodeURIComponent(threadId)}`, { body }); - } - - async deleteThread(threadId: string): Promise { - await this.request('DELETE', `/threads/${encodeURIComponent(threadId)}`); - } - - listMessages(threadId: string, query: { page?: number; perPage?: number } = {}) { - return this.request<{ messages: MemoryMessage[]; hasMore: boolean }>( - 'GET', - `/threads/${encodeURIComponent(threadId)}/messages`, - { query }, - ); - } - - /** Saves messages and schedules observation in the background. Creates the thread if needed. */ - saveMessages(threadId: string, body: { resourceId: string; messages: MemoryMessageInput[] }) { - return this.request<{ messages: MemoryMessage[] }>('POST', `/threads/${encodeURIComponent(threadId)}/messages`, { - body, - }); - } - - getContext(threadId: string, resourceId: string, opts: { workingMemory?: 'readonly' | 'tool' | 'off' } = {}) { - return this.request('GET', `/threads/${encodeURIComponent(threadId)}/context`, { - query: { resourceId, ...(opts.workingMemory ? { workingMemory: opts.workingMemory } : {}) }, - }); - } - - async getWorkingMemory(resourceId: string): Promise { - const res = await this.request<{ workingMemory: string | null }>('GET', '/working-memory', { - query: { resourceId }, - }); - return res.workingMemory; - } - - async updateWorkingMemory(resourceId: string, workingMemory: string): Promise { - await this.request('PUT', '/working-memory', { body: { resourceId, workingMemory } }); - } - - /** Omit resourceId to search the instance's most recently active threads. */ - async search(body: { resourceId?: string; threadId?: string; query: string; limit?: number }) { - const res = await this.request<{ matches: MemoryObservationMatch[] }>('POST', '/search', { body }); - return res.matches; - } - - /** Current observational-memory record for the thread, or null before the first observation. */ - async getObservations(threadId: string): Promise { - const res = await this.request<{ record: MemoryObservationRecord | null }>( - 'GET', - `/threads/${encodeURIComponent(threadId)}/observations`, - ); - return res.record; - } - - /** Runs the instance's memory processors for one agent phase on a serialized message list. */ - runProcessors(threadId: string, body: RunMemoryProcessorsInput, signal?: AbortSignal) { - return this.request('POST', `/threads/${encodeURIComponent(threadId)}/processors`, { - body, - signal, - timeoutMs: PROCESSOR_TIMEOUT_MS, - }); - } - - async listObservationRuns(query: { threadId?: string; limit?: number } = {}) { - const res = await this.request<{ runs: MemoryObservationRun[] }>('GET', '/runs', { query }); - return res.runs; - } - - /** Effective observation thresholds for the thread and which ones it overrides. */ - getThreadConfig(threadId: string) { - return this.request('GET', `/threads/${encodeURIComponent(threadId)}/config`); - } - - /** Overrides thresholds for one thread. Pass `null` to fall back to the instance value. */ - updateThreadConfig(threadId: string, config: MemoryThreadConfigUpdate) { - return this.request('PATCH', `/threads/${encodeURIComponent(threadId)}/config`, { - body: config, - }); - } - - /** Copies a thread, its messages, and its observations. */ - cloneThread( - threadId: string, - body: { newThreadId?: string; title?: string; metadata?: Record; messageLimit?: number } = {}, - ) { - return this.request<{ thread: MemoryThread; clonedMessageCount: number }>( - 'POST', - `/threads/${encodeURIComponent(threadId)}/clone`, - { body }, - ); - } - - /** Deletes messages from a thread. Ids that belong to other threads are ignored. */ - async deleteMessages(threadId: string, messageIds: string[]): Promise { - const res = await this.request<{ deleted: number }>( - 'POST', - `/threads/${encodeURIComponent(threadId)}/messages/delete`, - { body: { messageIds } }, - ); - return res.deleted; - } - - /** Everything stored for one resource (user): working memory and threads. */ - getResource(resourceId: string, query: { page?: number; perPage?: number } = {}) { - return this.request<{ - resourceId: string; - workingMemory: string | null; - threads: MemoryThread[]; - totalThreads: number; - hasMore: boolean; - }>('GET', `/resources/${encodeURIComponent(resourceId)}`, { query }); - } - - /** Resources (users) in the instance, most recently active first. */ - listResources(query: { page?: number; perPage?: number } = {}) { - return this.request<{ - resources: { resourceId: string; threadCount: number; lastActiveAt: string }[]; - hasMore: boolean; - }>('GET', '/resources', { query }); - } - - /** Deletes every thread, message, observation and the working memory for a resource. */ - async deleteResource(resourceId: string): Promise { - const res = await this.request<{ deletedThreads: number }>( - 'DELETE', - `/resources/${encodeURIComponent(resourceId)}`, - ); - return res.deletedThreads; - } - - private get base(): string { - return `${this.opts.apiUrl}/v1/memory/${encodeURIComponent(this.opts.instanceId)}`; - } - - private async request( - method: string, - path: string, - init: { query?: Query; body?: unknown; signal?: AbortSignal; timeoutMs?: number } = {}, - ): Promise { - const url = new URL(this.base + path); - for (const [key, value] of Object.entries(init.query ?? {})) { - if (value !== undefined) url.searchParams.set(key, String(value)); - } - const headers: Record = { authorization: `Bearer ${this.opts.accessToken}` }; - if (this.opts.actingUserId) headers['x-acting-user-id'] = this.opts.actingUserId; - if (this.opts.projectId) headers['x-mastra-project-id'] = this.opts.projectId; - if (this.opts.environmentId) headers['x-mastra-environment-id'] = this.opts.environmentId; - if (init.body !== undefined) headers['content-type'] = 'application/json'; - - const deadline = AbortSignal.timeout(init.timeoutMs ?? REQUEST_TIMEOUT_MS); - const res = await this.opts.fetch(url, { - method, - headers, - body: init.body === undefined ? undefined : JSON.stringify(init.body), - signal: init.signal ? AbortSignal.any([init.signal, deadline]) : deadline, - }); - if (!res.ok) throw new PlatformMemoryApiError(res.status, await res.text().catch(() => '')); - if (res.status === 204) return undefined as T; - return (await res.json()) as T; - } -} diff --git a/packages/platform/src/memory/index.ts b/packages/platform/src/memory/index.ts deleted file mode 100644 index 8481a5085a4..00000000000 --- a/packages/platform/src/memory/index.ts +++ /dev/null @@ -1,14 +0,0 @@ -export { PlatformMemoryClient, PlatformMemoryApiError, resolvePlatformMemoryOptions } from './client'; -export type { - PlatformMemoryClientOptions, - MemoryThread, - MemoryMessage, - MemoryMessageInput, - MemoryContext, - MemoryObservationMatch, - MemoryObservationRun, - MemoryThreadConfig, - MemoryThreadConfigUpdate, -} from './client'; -export { PlatformMemory } from './platform-memory'; -export type { PlatformMemoryOptions } from './platform-memory'; diff --git a/packages/platform/src/memory/parity.live.test.ts b/packages/platform/src/memory/parity.live.test.ts deleted file mode 100644 index ae4a240c21a..00000000000 --- a/packages/platform/src/memory/parity.live.test.ts +++ /dev/null @@ -1,624 +0,0 @@ -import { readFileSync, writeFileSync } from 'node:fs'; -import { createServer } from 'node:http'; -import type { Server } from 'node:http'; -import { tmpdir } from 'node:os'; -import path from 'node:path'; - -import { MockLanguageModelV2, convertArrayToReadableStream } from '@internal/ai-sdk-v5/test'; -import { Agent, MessageList } from '@mastra/core/agent'; -import type { MastraMemory } from '@mastra/core/memory'; -import { InMemoryStore } from '@mastra/core/storage'; -import { createTool } from '@mastra/core/tools'; -import { Memory } from '@mastra/memory'; -import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; -import { z } from 'zod'; - -import { PlatformMemoryClient } from './client'; -import { PlatformMemory } from './platform-memory'; - -/** - * Agent-level parity between @mastra/memory's `Memory` and `PlatformMemory` against a locally - * running Platform memory server. Every scenario runs on both backends with the same scripted - * agent model and the same scripted observer, and asserts only what a user can see: the prompts - * the agent model receives, the stored messages, and the loaded context. - * - * Start the server from the platform repo (it provisions an instance, writes PLATFORM_MEMORY_LIVE, - * points the observer at this file's scripted model and lowers the threshold to 50 tokens): - * - * pnpm --filter @platform/memory-server parity:serve - * - * Then: PLATFORM_MEMORY_LIVE=1 pnpm vitest run src/parity.live.test.ts - * (or set it to the env file path if PARITY_ENV_FILE was overridden). - */ -const liveFlag = process.env.PLATFORM_MEMORY_LIVE; -const live = !!liveFlag; -const envFile = liveFlag && liveFlag !== '1' ? liveFlag : path.join(tmpdir(), 'platform-memory-parity.json'); -const MODEL_PORT = Number(process.env.PARITY_MODEL_PORT ?? 4555); - -/** Matches the harness; use a separate low-threshold run to exercise reflection. */ -const reflectionTokens = process.env.PARITY_REFLECTION_TOKENS; -const THRESHOLDS = { messageTokens: 50, observationTokens: reflectionTokens ? Number(reflectionTokens) : 100_000 }; -// Set PARITY_BUFFER_TOKENS (and start the harness with the same value) to run with async buffering on. -const BUFFER_TOKENS: number | false = process.env.PARITY_BUFFER_TOKENS - ? Number(process.env.PARITY_BUFFER_TOKENS) - : false; - -const BODY = `Date: Jan 1, 2026 -* 🔴 User's name is Ada and she lives in Kyoto.`; -const TAIL = `Chatting with Ada. -Greet Ada by name.`; -/** Every prompt the observer received, from the server (HTTP) and the local backends. */ -const observerSeen: string[] = []; -const observerOutput = (reflecting = false) => - reflecting - ? '\n* 🔴 Ada lives in Kyoto (reflected).\n' - : `\n${BODY}\n\n${TAIL}`; - -/** OpenAI-compatible observer the Platform server calls through its Gateway URL. */ -function scriptedObserver(port: number): Promise { - const server = createServer((req, res) => { - let raw = ''; - req.on('data', c => (raw += c)); - req.on('end', async () => { - // Slow observer: background buffering outlives the request, so the next step can reach - // another replica while it is still running. - await new Promise(r => setTimeout(r, Number(process.env.PARITY_OBSERVER_DELAY_MS ?? 0))); - observerSeen.push(raw); - const text = observerOutput(raw.includes('observation reflector')); - const base = { id: 'x', created: 0, model: 'scripted' }; - const usage = { prompt_tokens: 10, completion_tokens: 10, total_tokens: 20 }; - if (!JSON.parse(raw).stream) { - res.setHeader('content-type', 'application/json'); - res.end( - JSON.stringify({ - ...base, - object: 'chat.completion', - choices: [{ index: 0, message: { role: 'assistant', content: text }, finish_reason: 'stop' }], - usage, - }), - ); - return; - } - res.setHeader('content-type', 'text/event-stream'); - const send = (d: unknown) => res.write(`data: ${JSON.stringify(d)}\n\n`); - const chunk = { ...base, object: 'chat.completion.chunk' }; - send({ ...chunk, choices: [{ index: 0, delta: { role: 'assistant', content: text } }] }); - send({ ...chunk, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage }); - res.end('data: [DONE]\n\n'); - }); - }); - return new Promise(r => server.listen(port, () => r(server))); -} - -const streamOf = (parts: unknown[]) => ({ stream: convertArrayToReadableStream(parts as never[]) }); - -const textParts = (text: string) => [ - { type: 'stream-start', warnings: [] }, - { type: 'text-start', id: 't' }, - { type: 'text-delta', id: 't', delta: text }, - { type: 'text-end', id: 't' }, - { type: 'finish', finishReason: 'stop', usage: { inputTokens: 10, outputTokens: 10, totalTokens: 20 } }, -]; - -/** Same observer for the local backend, in-process. */ -const localObserver = () => - new MockLanguageModelV2({ - doStream: async ({ prompt }) => { - const text = JSON.stringify(prompt); - observerSeen.push(text); - return streamOf(textParts(observerOutput(text.includes('observation reflector')))); - }, - }); - -const reply = - 'I understand your request completely. Here is a comprehensive and detailed response covering every aspect of what you asked, with thoughts and recommendations based on the information you provided.'; -const usage = { inputTokens: 10, outputTokens: 10, totalTokens: 20 }; - -/** Calls the `test` tool once per turn, then answers. Records every prompt it receives. */ -function agentModel(prompts: string[]) { - return new MockLanguageModelV2({ - doGenerate: async ({ prompt }) => { - prompts.push(JSON.stringify(prompt)); - const toolTurn = prompt.at(-1)?.role !== 'tool'; - return { - rawCall: { rawPrompt: null, rawSettings: {} }, - warnings: [], - usage, - finishReason: toolTurn ? 'tool-calls' : 'stop', - content: toolTurn - ? [{ type: 'tool-call', toolCallId: 'call-1', toolName: 'test', input: '{"action":"trigger"}' }] - : [{ type: 'text', text: reply }], - } as never; - }, - doStream: async ({ prompt }) => { - prompts.push(JSON.stringify(prompt)); - if (prompt.at(-1)?.role === 'tool') return streamOf(textParts(reply)); - return streamOf([ - { type: 'stream-start', warnings: [] }, - { type: 'tool-input-start', id: 'call-1', toolName: 'test' }, - { type: 'tool-input-delta', id: 'call-1', delta: '{"action":"trigger"}' }, - { type: 'tool-input-end', id: 'call-1' }, - { type: 'tool-call', toolCallId: 'call-1', toolName: 'test', input: '{"action":"trigger"}' }, - { type: 'finish', finishReason: 'tool-calls', usage }, - ]); - }, - }); -} - -/** Calls the `bulk` tool `calls` times in one turn, then answers. */ -function loopModel(prompts: string[], calls: number) { - return new MockLanguageModelV2({ - doGenerate: async ({ prompt }) => { - prompts.push(JSON.stringify(prompt)); - const step = prompts.length; - return { - rawCall: { rawPrompt: null, rawSettings: {} }, - warnings: [], - usage, - finishReason: step <= calls ? 'tool-calls' : 'stop', - content: - step <= calls - ? [{ type: 'tool-call', toolCallId: `call-${step}`, toolName: 'bulk', input: '{}' }] - : [{ type: 'text', text: reply }], - } as never; - }, - }); -} - -const testTool = createTool({ - id: 'test', - description: 'Trigger tool for OM testing', - inputSchema: z.object({ action: z.string().optional() }), - execute: async () => ({ success: true, message: 'Tool executed' }), -}); - -let bulkBatch = 0; -const bulkTool = createTool({ - id: 'bulk', - description: 'Returns a large payload', - inputSchema: z.object({}), - execute: async () => ({ batch: `batch${++bulkBatch}x`, rows: 'lorem ipsum dolor sit amet '.repeat(40) }), -}); - -interface StoredMessage { - id: string; - role: string; - createdAt: string | Date; - text: string; -} - -interface Backend { - memory: MastraMemory; - /** The observations block the next turn would load, or null before the first observation. */ - observations(threadId: string, resourceId: string): Promise; - messages(threadId: string): Promise; -} - -/** - * With buffering on, OM's background work races the next step, so even `Memory` disagrees with - * itself run to run. Settle it after every processor call, as the harness server does - * (MEMORY_OM_TEST_SETTLE), so any remaining prompt difference is a real one. - */ -function settling(memory: M): M { - if (BUFFER_TOKENS === false) return memory; - const settle = async () => (await memory.omEngine)?.settled(); - const wrap = (p: any) => ({ - ...p, - id: p.id, - name: p.name, - ...(p.processInputStep && { - processInputStep: async (a: any) => { - const out = await p.processInputStep.call(p, a); - await settle(); - return out; - }, - }), - ...(p.processOutputResult && { - processOutputResult: async (a: any) => { - const out = await p.processOutputResult.call(p, a); - await settle(); - return out; - }, - }), - }); - const input = memory.getInputProcessors.bind(memory); - const output = memory.getOutputProcessors.bind(memory); - memory.getInputProcessors = (async (...a: any[]) => (await (input as any)(...a)).map(wrap)) as never; - memory.getOutputProcessors = (async (...a: any[]) => (await (output as any)(...a)).map(wrap)) as never; - return memory; -} - -function localBackend(): Backend { - const store = new InMemoryStore(); - const memory = settling( - new Memory({ - storage: store, - options: { - observationalMemory: { - enabled: true, - observation: { - model: localObserver() as never, - messageTokens: THRESHOLDS.messageTokens, - bufferTokens: BUFFER_TOKENS, - }, - reflection: { model: localObserver() as never, observationTokens: THRESHOLDS.observationTokens }, - }, - }, - }), - ); - return { - memory, - observations: async (threadId, resourceId) => - (await memory.getContext({ threadId, resourceId })).systemMessage ?? null, - messages: async threadId => { - const memoryStore = (await store.getStore('memory'))!; - const { messages } = await memoryStore.listMessages({ - threadId, - orderBy: { field: 'createdAt', direction: 'ASC' }, - perPage: false, - }); - return messages.map(m => ({ id: m.id, role: m.role, createdAt: m.createdAt, text: JSON.stringify(m.content) })); - }, - }; -} - -type OMProcessor = { - processInputStep(args: any): Promise; -}; - -/** - * What the memory server will do for each step: a fresh OM processor with no carried state, - * run against a MessageList rebuilt from its serialized form. If this matches `Memory` on every - * prompt, the server can run the real processor statelessly behind HTTP. - */ -class StatelessStepMemory extends Memory { - private async freshOM(requestContext: unknown): Promise { - const processors = await super.getInputProcessors([], requestContext as never); - return processors.find(p => p.id === 'observational-memory') as unknown as OMProcessor; - } - - override async getInputProcessors(...args: Parameters) { - const processors = await super.getInputProcessors(...args); - return processors.map(p => { - if (p.id !== 'observational-memory') return p; - return { - id: p.id, - name: p.name, - processInputStep: async (stepArgs: any) => { - const list = new MessageList().deserialize(structuredClone(stepArgs.messageList.serialize())); - await ( - await this.freshOM(stepArgs.requestContext) - ).processInputStep({ - ...stepArgs, - messageList: list, - state: {}, - }); - return stepArgs.messageList.deserialize(structuredClone(list.serialize())); - }, - } as typeof p; - }); - } - - override async getOutputProcessors(...args: Parameters) { - const processors = await super.getOutputProcessors(...args); - return processors.map(p => { - if (p.id !== 'observational-memory') return p; - return { - id: p.id, - name: p.name, - processOutputResult: async (outArgs: any) => { - const list = new MessageList().deserialize(structuredClone(outArgs.messageList.serialize())); - const fresh = (await super.getOutputProcessors([], outArgs.requestContext)).find( - q => q.id === 'observational-memory', - ) as any; - await fresh.processOutputResult({ ...outArgs, messageList: list, state: {} }); - return outArgs.messageList.deserialize(structuredClone(list.serialize())); - }, - } as unknown as typeof p; - }); - } -} - -function statelessBackend(): Backend { - const store = new InMemoryStore(); - const memory = settling( - new StatelessStepMemory({ - storage: store, - options: { - observationalMemory: { - enabled: true, - observation: { - model: localObserver() as never, - messageTokens: THRESHOLDS.messageTokens, - bufferTokens: BUFFER_TOKENS, - }, - reflection: { model: localObserver() as never, observationTokens: THRESHOLDS.observationTokens }, - }, - }, - }), - ); - return { - memory, - observations: async (threadId, resourceId) => - (await memory.getContext({ threadId, resourceId })).systemMessage ?? null, - messages: async threadId => { - const memoryStore = (await store.getStore('memory'))!; - const { messages } = await memoryStore.listMessages({ - threadId, - orderBy: { field: 'createdAt', direction: 'ASC' }, - perPage: false, - }); - return messages.map(m => ({ id: m.id, role: m.role, createdAt: m.createdAt, text: JSON.stringify(m.content) })); - }, - }; -} - -function platformBackend(): Backend { - const { apiUrl, instanceId, token } = JSON.parse(readFileSync(envFile, 'utf8')); - const client = new PlatformMemoryClient({ apiUrl, accessToken: token, instanceId }); - return { - memory: new PlatformMemory({ client, workingMemory: 'off' }), - observations: async (threadId, resourceId) => (await client.getContext(threadId, resourceId)).system, - messages: async threadId => { - const { messages } = await client.listMessages(threadId, { perPage: 100 }); - return messages.map(m => ({ id: m.id, role: m.role, createdAt: m.createdAt, text: JSON.stringify(m) })); - }, - }; -} - -const BACKENDS = [ - ['Memory', localBackend], - ['StatelessSteps', statelessBackend], - ['PlatformMemory', platformBackend], -] as const; - -function expectOrdered(messages: StoredMessage[]) { - expect(new Set(messages.map(m => m.id)).size).toBe(messages.length); - for (let i = 1; i < messages.length; i++) { - expect(new Date(messages[i]!.createdAt).getTime()).toBeGreaterThanOrEqual( - new Date(messages[i - 1]!.createdAt).getTime(), - ); - } -} - -/** Strips ids and timestamps so prompts from both backends can be compared verbatim. */ -// Token-count cache @mastra/memory stamps under providerOptions.mastra on messages and parts it -// has counted (`tokenEstimate`, `tool-call-args-json:`, ...). Providers never see it. -function stripTokenCache(value: unknown): unknown { - if (Array.isArray(value)) return value.map(stripTokenCache); - if (!value || typeof value !== 'object') return value; - const out: Record = {}; - for (const [key, child] of Object.entries(value)) { - if (key === 'tokenEstimate' || /^tool-(call-args|result)-json:/.test(key)) continue; - const stripped = stripTokenCache(child); - if (stripped && typeof stripped === 'object' && !Array.isArray(stripped) && !Object.keys(stripped).length) { - if (key === 'mastra' || key === 'providerOptions') continue; - } - out[key] = stripped; - } - return out; -} - -function normalize(prompt: string, run: string): string { - return ( - JSON.stringify(stripTokenCache(JSON.parse(prompt))) - .replaceAll(run, 'RUN') - .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, 'UUID') - .replace(/\d{4}-\d{2}-\d{2}T[\d:.]+Z/g, 'ISO') - // Epoch-ms stamps Mastra puts in providerOptions; they differ between any two runs. - .replace(/"createdAt":\d{13}/g, '"createdAt":"EPOCH"') - .replace(/\b(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*,? [A-Z][a-z]+ \d{1,2},? \d{4}\b/g, 'DATE') - .replace(/\b[A-Z][a-z]{2} \d{1,2}, \d{4}\b/g, 'DATE') - .replace(/\b\d{1,2}:\d{2}( ?[AP]M)?\b/g, 'TIME') - ); -} - -let observer: Server; -beforeAll(async () => { - if (live) observer = await scriptedObserver(MODEL_PORT); -}); -afterAll(() => observer?.close()); - -describe.skipIf(!live || !!reflectionTokens).each(BACKENDS)('OM agent (%s)', (_name, makeBackend) => { - const run = `${Date.now()}`; - const ids = (name: string) => ({ thread: `${name}-${run}`, resource: `res-${name}-${run}` }); - const setup = () => { - const backend = makeBackend(); - const prompts: string[] = []; - const agent = new Agent({ - id: 'parity', - name: 'parity', - instructions: 'You are a helpful assistant. Always use the test tool first.', - model: agentModel(prompts) as never, - tools: { test: testTool }, - memory: backend.memory, - }); - return { backend, agent, prompts }; - }; - - it('runs a multi-step turn: tool call on step 0, text on step 1', async () => { - const { agent } = setup(); - const result = await agent.generate('Help me with this task.', { memory: ids('multi') }); - expect(result.text).toContain('I understand your request'); - expect(result.steps.length).toBeGreaterThanOrEqual(2); - expect((result.steps[0]?.toolCalls?.[0] as any)?.payload?.toolName).toBe('test'); - }); - - it('streams', async () => { - const { agent } = setup(); - const response = await agent.stream('Tell me about the weather.', { memory: ids('stream') }); - let text = ''; - for await (const chunk of response.textStream) text += chunk; - expect(text).toContain('I understand your request'); - }); - - it('observes once the turn crosses the threshold', async () => { - const { agent, backend } = setup(); - const { thread, resource } = ids('observe'); - await agent.generate('Help me with this task.', { memory: { thread, resource } }); - expect(await backend.observations(thread, resource)).toContain('lives in Kyoto'); - }); - - it('persists every message of a multi-step turn, in order', async () => { - const { agent, backend } = setup(); - const { thread, resource } = ids('order'); - await agent.generate('Tell me something useful.', { memory: { thread, resource } }); - const messages = await backend.messages(thread); - const user = messages.findIndex(m => m.role === 'user'); - expect(user).toBeGreaterThanOrEqual(0); - expect(messages.findIndex(m => m.role === 'assistant')).toBeGreaterThan(user); - expect(messages.some(m => m.text.includes('"toolName":"test"'))).toBe(true); - expectOrdered(messages); - }); - - it('loads observations and the continuation reminder on the next turn', async () => { - const { agent, backend, prompts } = setup(); - const memory = ids('next'); - await agent.generate('First message', { memory }); - await agent.generate('Second message', { memory }); - const messages = await backend.messages(memory.thread); - expect(messages.filter(m => m.role === 'user')).toHaveLength(2); - expectOrdered(messages); - const secondTurn = prompts.find(p => p.includes('Second message'))!; - expect(secondTurn).toContain('lives in Kyoto'); - expect(secondTurn).toContain(''); - }); - - it('observes mid-turn in a long tool loop so the prompt stays bounded', async () => { - const backend = makeBackend(); - const prompts: string[] = []; - const agent = new Agent({ - id: 'loop', - name: 'loop', - instructions: 'Use the bulk tool repeatedly.', - model: loopModel(prompts, 6) as never, - tools: { bulk: bulkTool }, - memory: backend.memory, - }); - const { thread, resource } = ids('loop'); - const result = await agent.generate('Collect all the rows.', { memory: { thread, resource }, maxSteps: 10 }); - expect(result.text).toContain('I understand your request'); - expect(prompts.at(-1)).toContain('lives in Kyoto'); - expect(prompts.at(-1)!.split('lorem ipsum').length).toBeLessThan(6 * 40); - const stored = JSON.stringify(await backend.messages(thread)); - const callIds = [...stored.matchAll(/toolCallId\\*":\\*"([^"\\]+)/g)].map(m => m[1]); - expect(new Set(callIds).size).toBe(6); - }); - it('never drops a message from the prompt that the observer has not seen', async () => { - // Freeze the clock so MessageList spaces every message exactly 1ms apart, as it does when - // messages arrive within the same millisecond (fast tools, fast models). - vi.useFakeTimers({ toFake: ['Date'], now: new Date('2026-10-14T00:00:00.000Z') }); - try { - observerSeen.length = 0; - const backend = makeBackend(); - const prompts: string[] = []; - const agent = new Agent({ - id: 'drop', - name: 'drop', - instructions: 'Use the bulk tool repeatedly.', - model: loopModel(prompts, 6) as never, - tools: { bulk: bulkTool }, - memory: backend.memory, - }); - const memory = ids('drop'); - const before = bulkBatch; - await agent.generate('Collect all the rows.', { memory, maxSteps: 10 }); - expect(bulkBatch - before).toBe(6); - const firstTurn = prompts.length; - await agent.generate('Thanks, anything else?', { memory, maxSteps: 10 }); - const nextTurn = prompts.slice(firstTurn).join(); - const seen = observerSeen.join('\n'); - const batches = Array.from({ length: 6 }, (_, i) => `batch${before + i + 1}x`); - const lost = batches.filter(b => !nextTurn.includes(b) && !seen.includes(b)); - expect(lost).toEqual([]); - } finally { - vi.useRealTimers(); - } - }); -}); - -describe.skipIf(!live || !!reflectionTokens)('what the agent model sees', () => { - // No accepted differences: every step of every turn must reach the model identically. - it('is identical on every step of every turn for Memory and PlatformMemory', async () => { - // Distinct thread per backend: OM keeps process-wide state keyed by thread, which would leak - // from one in-process backend's run into the next. normalize() maps each run id to RUN. - const stamp = Date.now(); - const turns = [ - 'Hi, my name is Ada and I live in Kyoto.', - 'I work as a ceramicist and I love tea ceremonies.', - 'What should I cook tonight?', - 'Remind me what you know about me.', - 'Thanks, talk soon.', - ]; - const seen: Record = {}; - for (const [name, make] of BACKENDS) { - const backend = make(); - const prompts: string[] = []; - const agent = new Agent({ - id: 'parity', - name: 'parity', - instructions: 'You are a helpful assistant. Always use the test tool first.', - model: agentModel(prompts) as never, - tools: { test: testTool }, - memory: backend.memory, - }); - const run = `eq${stamp}${name}`; - seen[name] = []; - for (const turn of turns) { - prompts.length = 0; - await agent.generate(turn, { memory: { thread: `eq-${run}`, resource: `res-eq-${run}` } }); - seen[name].push(prompts.map(p => normalize(p, run))); - } - } - if (process.env.PARITY_DUMP) writeFileSync(process.env.PARITY_DUMP, JSON.stringify(seen, null, 2)); - for (const [name] of BACKENDS.slice(1)) { - for (let i = 0; i < turns.length; i++) { - expect({ backend: name, turn: i, steps: seen[name]![i] }).toEqual({ - backend: name, - turn: i, - steps: seen.Memory![i], - }); - } - } - }, 120_000); -}); - -describe.skipIf(!live || !reflectionTokens)('Observer and Reflector lifecycle', () => { - it.each([ - ['Memory', localBackend], - ['PlatformMemory', platformBackend], - ] as const)( - '%s persists reflected observations and replays them on a later Agent turn', - async (_name, createBackend) => { - const backend = createBackend(); - const prompts: string[] = []; - const agent = new Agent({ - id: 'reflection-parity', - name: 'reflection-parity', - instructions: 'Always use the test tool first.', - model: agentModel(prompts) as never, - tools: { test: testTool }, - memory: backend.memory, - }); - const stamp = `${_name}-${Date.now()}`; - const thread = `reflection-${stamp}`; - const resource = `resource-${stamp}`; - const start = observerSeen.length; - for (let turn = 0; turn < 5; turn++) { - await agent.generate(`Ada's Kyoto conversation turn ${turn}`, { memory: { thread, resource } }); - if ((await backend.observations(thread, resource))?.includes('(reflected)')) break; - } - const inference = observerSeen.slice(start); - expect(inference.some(prompt => prompt.includes('observation reflector'))).toBe(true); - expect(await backend.observations(thread, resource)).toContain('Ada lives in Kyoto (reflected)'); - if (_name === 'PlatformMemory') { - expect(await platformBackend().observations(thread, resource)).toContain('Ada lives in Kyoto (reflected)'); - } - prompts.length = 0; - await agent.generate('What did we discuss?', { memory: { thread, resource } }); - expect(prompts[0]).toContain('Ada lives in Kyoto (reflected)'); - expect((await backend.messages(thread)).filter(m => m.role === 'user').length).toBeGreaterThanOrEqual(2); - }, - 120_000, - ); -}); diff --git a/packages/platform/src/memory/platform-memory.test.ts b/packages/platform/src/memory/platform-memory.test.ts deleted file mode 100644 index 725cddcf5b5..00000000000 --- a/packages/platform/src/memory/platform-memory.test.ts +++ /dev/null @@ -1,506 +0,0 @@ -import { Agent } from '@mastra/core/agent'; -import { createMockModel } from '@mastra/core/test-utils/llm-mock'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; - -import { PlatformMemoryClient } from './client'; -import { PlatformMemory } from './platform-memory'; - -type StoredMessage = { - id: string; - role: string; - content: string; - parts?: { type: string; text?: string }[]; - createdAt: string; -}; - -/** In-memory stand-in for `/v1/memory/:instanceId/*`, with the server's observation already applied. */ -function fakeMemoryApi() { - const threads = new Map(); - const messages = new Map(); - const requests: { method: string; path: string; headers: Headers; body?: any }[] = []; - let observations: string | null = null; - const workingMemory = new Map(); - - const fetchImpl: typeof fetch = async (input, init) => { - const url = new URL(String(input)); - const path = url.pathname.replace(/^\/v1\/memory\/mem_1/, ''); - const method = init?.method ?? 'GET'; - const body = init?.body ? JSON.parse(String(init.body)) : undefined; - requests.push({ method, path, headers: new Headers(init?.headers), body }); - const json = (data: unknown, status = 200) => new Response(JSON.stringify(data), { status }); - const now = new Date().toISOString(); - const thread = (id: string) => { - const t = threads.get(id); - return t && { ...t, createdAt: now, updatedAt: now }; - }; - - let m: RegExpMatchArray | null; - if ((m = path.match(/^\/threads\/([^/]+)\/messages$/)) && method === 'POST') { - const id = decodeURIComponent(m[1]!); - if (!threads.has(id)) threads.set(id, { id, resourceId: body.resourceId, title: '', metadata: {} }); - const list = messages.get(id) ?? []; - for (const msg of body.messages) { - const idx = list.findIndex(x => x.id === msg.id); - if (idx >= 0) list[idx] = msg; - else list.push(msg); - } - messages.set(id, list); - return json({ messages: body.messages }, 201); - } - if (path === '/working-memory' && method === 'PUT') { - workingMemory.set(body.resourceId, body.workingMemory); - return json({ ok: true }); - } - if (path === '/working-memory' && method === 'GET') { - return json({ workingMemory: workingMemory.get(url.searchParams.get('resourceId')!) ?? null }); - } - if ((m = path.match(/^\/threads\/([^/]+)\/processors$/)) && method === 'POST') { - const id = decodeURIComponent(m[1]!); - const list = body.messageList; - if (body.phase === 'inputStep') { - const saved = messages.get(id) ?? []; - list.messages = [ - ...saved.map(msg => ({ - ...msg, - threadId: id, - resourceId: body.resourceId, - content: { format: 2, parts: msg.parts ?? [{ type: 'text', text: msg.content }] }, - })), - ...list.messages, - ]; - if (observations) list.systemMessages.push({ role: 'system', content: observations }); - } else if (body.phase === 'output') { - const saved = messages.get(id) ?? []; - for (const msg of list.messages) { - if (msg.role !== 'user' && msg.role !== 'assistant') continue; - const stored = { - id: msg.id, - role: msg.role, - content: - msg.content.content ?? - msg.content.parts - ?.filter((part: { type: string }) => part.type === 'text') - .map((part: { text: string }) => part.text) - .join('\n') ?? - '', - parts: msg.content.parts, - createdAt: msg.createdAt, - }; - const index = saved.findIndex(existing => existing.id === msg.id); - if (index < 0) saved.push(stored); - else saved[index] = stored; - } - messages.set(id, saved); - } - return json({ aborted: null, chunks: [], rotations: 0, messageList: list }); - } - if ((m = path.match(/^\/threads\/([^/]+)\/context$/))) { - const id = decodeURIComponent(m[1]!); - // Like the service: read-only, observations first as `om-system`, then unobserved messages. - const unobserved = messages.get(id) ?? []; - const system = observations - ? [{ id: 'om-system', role: 'system', content: observations, parts: [], createdAt: new Date(0).toISOString() }] - : []; - return json({ system: observations, messages: unobserved, prompt: [...system, ...unobserved], observedAt: null }); - } - if ((m = path.match(/^\/threads\/([^/]+)\/messages$/))) { - const all = messages.get(decodeURIComponent(m[1]!)) ?? []; - const page = Number(url.searchParams.get('page') ?? 0); - const perPage = Number(url.searchParams.get('perPage') ?? 40); - return json({ - messages: all.slice(page * perPage, (page + 1) * perPage), - hasMore: (page + 1) * perPage < all.length, - }); - } - if ((m = path.match(/^\/threads\/([^/]+)$/))) { - const t = thread(decodeURIComponent(m[1]!)); - return t ? json(t) : json({ title: 'Not found' }, 404); - } - if (path === '/threads' && method === 'GET') { - const page = Number(url.searchParams.get('page') ?? 0); - const perPage = Number(url.searchParams.get('perPage') ?? 100); - const all = [...threads.keys()] - .map(id => thread(id)!) - .filter(t => !url.searchParams.has('resourceId') || t.resourceId === url.searchParams.get('resourceId')); - return json({ - threads: all.slice(page * perPage, (page + 1) * perPage), - hasMore: (page + 1) * perPage < all.length, - }); - } - if (path === '/threads' && method === 'POST') { - threads.set(body.id, { - id: body.id, - resourceId: body.resourceId, - title: body.title ?? '', - metadata: body.metadata ?? {}, - }); - return json(thread(body.id), 201); - } - return json({ title: `unhandled ${method} ${path}` }, 500); - }; - - return { - fetchImpl, - requests, - messages, - observe(text: string) { - observations = text; - }, - }; -} - -describe('PlatformMemory', () => { - let api: ReturnType; - - beforeEach(() => { - api = fakeMemoryApi(); - }); - - function agentWith(prompts: unknown[], options: { workingMemory?: 'readonly' | 'tool' | 'off' } = {}) { - const memory = new PlatformMemory({ - ...options, - accessToken: 'tok_1', - instanceId: 'mem_1', - apiUrl: 'https://platform.test', - fetch: api.fetchImpl, - }); - const agent = new Agent({ - id: 'assistant', - name: 'assistant', - instructions: 'You are helpful.', - model: createMockModel({ mockText: 'Noted.', spyGenerate: props => prompts.push(props.prompt) }), - memory, - }); - return { agent, memory }; - } - - it('paginates across multiple threads and reports full message counts', async () => { - const { memory } = agentWith([]); - await memory.client.createThread({ id: 'thread_1', resourceId: 'user' }); - await memory.client.createThread({ id: 'thread_2', resourceId: 'user' }); - const messages = Array.from({ length: 205 }, (_, i) => ({ - id: `msg_${i}`, - role: 'user', - content: `message ${i}`, - createdAt: new Date(2024, 0, 1, 0, i).toISOString(), - })); - api.messages.set('thread_1', messages); - api.messages.set('thread_2', [ - { id: 'other', role: 'user', content: 'other thread', createdAt: new Date(2025, 0, 1).toISOString() }, - ]); - const all = await memory.recall({ threadId: ['thread_1', 'thread_2'], perPage: false }); - expect(all.messages).toHaveLength(206); - expect(all.total).toBe(206); - expect(all.messages.at(-1)?.id).toBe('other'); - const recent = await memory.recall({ - threadId: ['thread_1', 'thread_2'], - perPage: 2, - orderBy: { field: 'createdAt', direction: 'DESC' }, - }); - expect(recent.messages.map(m => m.id)).toEqual(['other', 'msg_204']); - expect(recent.total).toBe(206); - expect(recent.hasMore).toBe(true); - const filtered = await memory.recall({ - threadId: ['thread_1', 'thread_2'], - filter: { dateRange: { start: new Date(2025, 0, 1) } }, - }); - expect(filtered.messages.map(m => m.id)).toEqual(['other']); - expect(filtered.total).toBe(1); - }); - - it('reports full thread totals and applies metadata filtering', async () => { - const { memory } = agentWith([]); - for (let i = 0; i < 205; i++) { - await memory.client.createThread({ - id: `thread_${i}`, - resourceId: 'user', - metadata: { group: i % 2 ? 'odd' : 'even' }, - }); - } - const all = await memory.listThreads({ perPage: false }); - expect(all.threads).toHaveLength(205); - expect(all.total).toBe(205); - const filtered = await memory.listThreads({ perPage: 2, page: 1, filter: { metadata: { group: 'even' } } }); - expect(filtered.total).toBe(103); - expect(filtered.threads).toHaveLength(2); - }); - - it('saves each turn and replays the thread on the next one', async () => { - const prompts: any[] = []; - const { agent } = agentWith(prompts); - const memory = { thread: 'thread_1', resource: 'user_1' }; - - await agent.generate('My name is Ada.', { memory }); - await agent.generate('What is my name?', { memory }); - expect(api.messages.get('thread_1')!.map(m => [m.role, m.content])).toEqual([ - ['user', 'My name is Ada.'], - ['assistant', 'Noted.'], - ['user', 'What is my name?'], - ['assistant', 'Noted.'], - ]); - const secondPrompt = JSON.stringify(prompts[1]); - expect(secondPrompt).toContain('My name is Ada.'); - expect(api.requests.every(r => r.headers.get('authorization') === 'Bearer tok_1')).toBe(true); - }); - - it('cancels an in-flight processor request when the run is aborted', async () => { - const controller = new AbortController(); - let abortedInFlight: boolean | undefined; - const fetchImpl = api.fetchImpl; - api.fetchImpl = async (input, init) => { - if ( - new URL(String(input)).pathname.endsWith('/processors') && - JSON.parse(String(init?.body)).phase === 'inputStep' - ) { - controller.abort(); - abortedInFlight = init?.signal?.aborted; - } - return fetchImpl(input, init); - }; - const { agent } = agentWith([]); - - await agent - .generate('Hello', { memory: { thread: 'thread_1', resource: 'user_1' }, abortSignal: controller.signal }) - .catch(() => {}); - expect(abortedInFlight).toBe(true); - }); - - it('times out a hosted request that never responds', async () => { - const deadline = new AbortController(); - const timeout = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(deadline.signal); - try { - const client = new PlatformMemoryClient({ - accessToken: 'tok_1', - instanceId: 'mem_1', - apiUrl: 'https://platform.test', - fetch: (_input, init) => - new Promise((_resolve, reject) => init?.signal?.addEventListener('abort', () => reject(init.signal!.reason))), - }); - const pending = client.getThread('thread_1'); - expect(timeout).toHaveBeenCalledWith(30_000); - deadline.abort(new DOMException('timed out', 'TimeoutError')); - await expect(pending).rejects.toThrow('timed out'); - } finally { - timeout.mockRestore(); - } - }); - - it('gives processor runs a 5-minute bound and never aborts the output-phase save', async () => { - const timeout = vi.spyOn(AbortSignal, 'timeout'); - const controller = new AbortController(); - const outputSignals: AbortSignal[] = []; - const fetchImpl = api.fetchImpl; - api.fetchImpl = async (input, init) => { - if ( - new URL(String(input)).pathname.endsWith('/processors') && - JSON.parse(String(init?.body)).phase === 'output' - ) { - controller.abort(); - outputSignals.push(init!.signal!); - } - return fetchImpl(input, init); - }; - try { - const { agent } = agentWith([]); - await agent - .generate('Hello', { memory: { thread: 'thread_1', resource: 'user_1' }, abortSignal: controller.signal }) - .catch(() => {}); - expect(timeout).toHaveBeenCalledWith(5 * 60_000); - timeout.mockClear(); - await new PlatformMemoryClient({ - accessToken: 'tok_1', - instanceId: 'mem_1', - apiUrl: 'https://platform.test', - fetch: async () => new Response('{}'), - }).runProcessors('thread_1', { phase: 'output', resourceId: 'user_1', messageList: {} as never }); - expect(timeout.mock.calls).toEqual([[5 * 60_000]]); - expect(outputSignals).toHaveLength(1); - expect(outputSignals[0]!.aborted).toBe(false); - expect(api.messages.get('thread_1')?.length).toBeGreaterThan(0); - } finally { - timeout.mockRestore(); - } - }); - - it('injects server-side observations as a system message', async () => { - const prompts: any[] = []; - const { agent } = agentWith(prompts); - api.observe('\n* User prefers TypeScript.\n'); - - await agent.generate('Pick a language for me.', { memory: { thread: 'thread_2', resource: 'user_1' } }); - - const system = prompts[0].filter((m: any) => m.role === 'system').map((m: any) => m.content); - expect(system.join('\n')).toContain('User prefers TypeScript.'); - expect(api.requests.some(r => r.path === '/threads/thread_2/processors' && r.body.phase === 'inputStep')).toBe( - true, - ); - }); - - it('maps thread lookups and recall onto the API', async () => { - const { agent, memory } = agentWith([]); - expect(await memory.getThreadById({ threadId: 'missing' })).toBeNull(); - - await agent.generate('hello', { memory: { thread: 'thread_3', resource: 'user_9' } }); - - expect((await memory.getThreadById({ threadId: 'thread_3' }))?.resourceId).toBe('user_9'); - const recalled = await memory.recall({ threadId: 'thread_3' }); - expect(recalled.messages.map(m => m.role)).toEqual(['user', 'assistant']); - expect(recalled.messages.map(m => m.resourceId)).toEqual(['user_9', 'user_9']); - const unfiltered = await memory.recall({ threadId: 'thread_3', filter: { metadata: {} } }); - expect(unfiltered.messages).toHaveLength(2); - await expect(memory.recall({ threadId: 'thread_3', filter: { metadata: { k: 'v' } } })).rejects.toThrow( - 'does not support metadata filters', - ); - expect((await memory.recall({ threadId: 'missing' })).messages).toEqual([]); - }); - - it('lets the agent update working memory in tool mode', async () => { - const opts = { accessToken: 'tok_1', instanceId: 'mem_1', apiUrl: 'https://platform.test', fetch: api.fetchImpl }; - expect(Object.keys(new PlatformMemory(opts).listTools())).toEqual([]); - const memory = new PlatformMemory({ ...opts, workingMemory: 'tool' }); - expect(Object.keys(memory.listTools({ readOnly: true }))).toEqual([]); - - const tool = memory.listTools().updateWorkingMemory!; - await tool.execute!({ memory: '# User\n- Name: Ada' }, { agent: { threadId: 't', resourceId: 'user_1' } } as never); - - const put = api.requests.find(r => r.path === '/working-memory')!; - expect(put.body).toEqual({ resourceId: 'user_1', workingMemory: '# User\n- Name: Ada' }); - }); - - it("keeps a read-only run read-only but still gives it the thread's stored context", async () => { - const prompts: any[] = []; - const { agent } = agentWith(prompts); - await agent.generate('My name is Ada.', { memory: { thread: 'thread_ro', resource: 'user_1' } }); - api.observe('\n* User prefers TypeScript.\n'); - const stored = structuredClone(api.messages.get('thread_ro')); - const before = api.requests.length; - - await agent.generate('What do you know about me?', { - memory: { thread: 'thread_ro', resource: 'user_1', options: { readOnly: true } }, - }); - - const prompt = JSON.stringify(prompts.at(-1)); - expect(prompt).toContain('User prefers TypeScript.'); - expect(prompt).toContain('My name is Ada.'); - const writes = api.requests.slice(before).filter(r => r.method !== 'GET'); - expect(writes).toEqual([]); - expect(api.messages.get('thread_ro')).toEqual(stored); - }); - - it.each([ - ['readonly', true, false], - ['tool', true, true], - ['off', false, false], - ] as const)('delivers working memory in %s mode as configured', async (mode, delivered, hasTool) => { - const prompts: any[] = []; - const { agent, memory } = agentWith(prompts, { workingMemory: mode }); - const memoryArg = { thread: `thread_wm_${mode}`, resource: 'user_wm' }; - const systemOf = (prompt: any) => - prompt - .filter((m: any) => m.role === 'system') - .map((m: any) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content))) - .join('\n'); - - await memory.updateWorkingMemory({ - threadId: memoryArg.thread, - resourceId: 'user_wm', - workingMemory: '- Name: Ada', - }); - await agent.generate('Hi.', { memory: memoryArg }); - // A second turn after the memo changes, so a stale first read can't pass. - await memory.updateWorkingMemory({ - threadId: memoryArg.thread, - resourceId: 'user_wm', - workingMemory: '- Name: Grace', - }); - await agent.generate('Hi again.', { memory: memoryArg }); - - expect(systemOf(prompts[0]).includes('- Name: Ada')).toBe(delivered); - expect(systemOf(prompts[1]).includes('- Name: Grace')).toBe(delivered); - expect(systemOf(prompts[1]).includes('- Name: Ada')).toBe(false); - expect('updateWorkingMemory' in memory.listTools()).toBe(hasTool); - expect(memory.listTools({ readOnly: true })).toEqual({}); - - // A read-only run still sees the memo (unless off) but is told it can't change it. - await agent.generate('Read only.', { memory: { ...memoryArg, options: { readOnly: true } } }); - const readOnlySystem = systemOf(prompts[2]); - expect(readOnlySystem.includes('- Name: Grace')).toBe(delivered); - expect(readOnlySystem).not.toContain('updateWorkingMemory'); - }); - - it('rejects thread-scoped working memory instead of sharing it across threads', async () => { - const opts = { accessToken: 'tok_1', instanceId: 'mem_1', apiUrl: 'https://platform.test', fetch: api.fetchImpl }; - const memory = new PlatformMemory({ ...opts, workingMemory: 'tool' }); - const threadScope = { workingMemory: { enabled: true, scope: 'thread' as const } }; - const before = api.requests.length; - - expect(() => memory.listTools(threadScope)).toThrow('thread-scoped working memory'); - await expect( - memory.getWorkingMemory({ threadId: 't', resourceId: 'u', memoryConfig: threadScope }), - ).rejects.toThrow('thread-scoped working memory'); - await expect( - memory.updateWorkingMemory({ threadId: 't', resourceId: 'u', workingMemory: 'x', memoryConfig: threadScope }), - ).rejects.toThrow('thread-scoped working memory'); - expect(api.requests.length).toBe(before); - - const resourceScope = { workingMemory: { enabled: true, scope: 'resource' as const } }; - await memory.updateWorkingMemory({ - threadId: 't', - resourceId: 'u', - workingMemory: 'x', - memoryConfig: resourceScope, - }); - expect(api.requests.at(-1)!.body).toEqual({ resourceId: 'u', workingMemory: 'x' }); - }); -}); - -describe('PlatformMemoryClient', () => { - const envNames = [ - 'MASTRA_PLATFORM_ACCESS_TOKEN', - 'MASTRA_PLATFORM_SECRET_KEY', - 'MASTRA_MEMORY_INSTANCE_ID', - 'MASTRA_MEMORY_API_URL', - 'MASTRA_MEMORY_SERVICE_URL', - 'MASTRA_PROJECT_ID', - 'MASTRA_ENVIRONMENT_ID', - ]; - beforeEach(() => { - for (const name of envNames) vi.stubEnv(name, ''); - }); - afterEach(() => { - vi.unstubAllEnvs(); - }); - - it('falls back to Platform env vars', () => { - vi.stubEnv('MASTRA_PLATFORM_SECRET_KEY', 'sk_env'); - vi.stubEnv('MASTRA_MEMORY_INSTANCE_ID', 'mem_env'); - vi.stubEnv('MASTRA_MEMORY_API_URL', 'https://api.example/'); - const client = new PlatformMemoryClient(); - expect(client.instanceId).toBe('mem_env'); - expect(client.mcpUrl).toBe('https://api.example/v1/memory/mem_env/mcp'); - expect(new PlatformMemoryClient({ apiUrl: 'http://localhost:8080/' }).mcpUrl).toBe( - 'http://localhost:8080/v1/memory/mem_env/mcp', - ); - }); - - it('ignores MASTRA_MEMORY_SERVICE_URL; only MASTRA_MEMORY_API_URL overrides the default', () => { - vi.stubEnv('MASTRA_MEMORY_SERVICE_URL', 'http://injected.local/'); - expect(new PlatformMemoryClient({ accessToken: 't', instanceId: 'mem_1' }).mcpUrl).toBe( - 'https://memory-api.mastra.ai/v1/memory/mem_1/mcp', - ); - vi.stubEnv('MASTRA_MEMORY_API_URL', 'https://api.example/'); - expect(new PlatformMemoryClient({ accessToken: 't', instanceId: 'mem_1' }).mcpUrl).toBe( - 'https://api.example/v1/memory/mem_1/mcp', - ); - }); - - it('defaults to the hosted Memory API', () => { - const client = new PlatformMemoryClient({ accessToken: 't', instanceId: 'mem_1' }); - expect(client.mcpUrl).toBe('https://memory-api.mastra.ai/v1/memory/mem_1/mcp'); - }); - - it('requires an access token and instance id', () => { - expect(() => new PlatformMemoryClient({ instanceId: 'mem_1' })).toThrow(/accessToken/); - expect(() => new PlatformMemoryClient({ accessToken: 't' })).toThrow(/instanceId/); - }); -}); diff --git a/packages/platform/src/memory/platform-memory.ts b/packages/platform/src/memory/platform-memory.ts deleted file mode 100644 index 7385a654db5..00000000000 --- a/packages/platform/src/memory/platform-memory.ts +++ /dev/null @@ -1,476 +0,0 @@ -import type { MastraDBMessage } from '@mastra/core/agent'; -import { MastraMemory, parseMemoryRequestContext } from '@mastra/core/memory'; -import type { MemoryConfig, MemoryConfigInternal, StorageThreadType, WorkingMemoryTemplate } from '@mastra/core/memory'; -import type { - InputProcessor, - OutputProcessor, - ProcessInputArgs, - ProcessInputStepArgs, - ProcessOutputResultArgs, -} from '@mastra/core/processors'; -import type { RequestContext } from '@mastra/core/request-context'; -import type { - StorageCloneThreadInput, - StorageCloneThreadOutput, - StorageListMessagesInput, - StorageListThreadsInput, - StorageListThreadsOutput, -} from '@mastra/core/storage'; -import { createTool } from '@mastra/core/tools'; -import type { ToolAction } from '@mastra/core/tools'; - -import { z } from 'zod'; - -import { PlatformMemoryClient } from './client'; -import type { - MemoryMessage, - MemoryMessageInput, - MemoryProcessorsResult, - MemoryThread, - PlatformMemoryClientOptions, -} from './client'; - -export type PlatformMemoryOptions = PlatformMemoryClientOptions & { - id?: string; - /** Use a preconfigured client instead of building one from the options above. */ - client?: PlatformMemoryClient; - /** - * How working memory is shown to the model. Defaults to `readonly`: the resource's stored - * working memory is added to each run's prompt. `tool` also gives the agent an - * `updateWorkingMemory` tool (not in read-only runs); `off` leaves working memory out. - */ - workingMemory?: 'readonly' | 'tool' | 'off'; -}; - -type MessageListLike = ProcessInputArgs['messageList']; - -function threadFromApi(thread: MemoryThread): StorageThreadType { - return { - id: thread.id, - resourceId: thread.resourceId, - title: thread.title ?? undefined, - metadata: thread.metadata ?? undefined, - createdAt: new Date(thread.createdAt), - updatedAt: new Date(thread.updatedAt), - }; -} - -function messageFromApi(message: MemoryMessage, threadId: string, resourceId?: string): MastraDBMessage { - return { - id: message.id, - role: message.role === 'assistant' ? 'assistant' : 'user', - createdAt: new Date(message.createdAt), - threadId, - resourceId, - content: { - format: 2, - parts: (message.parts?.length - ? message.parts - : [{ type: 'text', text: message.content }]) as MastraDBMessage['content']['parts'], - }, - }; -} - -function textOf(message: MastraDBMessage): string { - const parts = message.content.parts ?? []; - const text = parts - .filter((part): part is { type: 'text'; text: string } => part.type === 'text') - .map(part => part.text) - .join('\n'); - return text || message.content.content || ''; -} - -/** User/assistant messages with all their parts (tool calls, reasoning, files). System messages are skipped. */ -function toApiMessages(messages: MastraDBMessage[]): MemoryMessageInput[] { - return messages.flatMap((message): MemoryMessageInput[] => { - if (message.role !== 'user' && message.role !== 'assistant') return []; - const parts = message.content.parts ?? []; - const createdAt = new Date(message.createdAt).toISOString(); - const content = textOf(message) || undefined; - if (!parts.length && !content) return []; - return [{ id: message.id, role: message.role, content, parts: parts.length ? parts : undefined, createdAt }]; - }); -} - -function memoryContext(requestContext: RequestContext | undefined, messageList: MessageListLike) { - const ctx = parseMemoryRequestContext(requestContext); - if (ctx?.thread?.id) { - return { - threadId: ctx.thread.id, - resourceId: ctx.resourceId ?? ctx.thread.id, - readOnly: ctx.memoryConfig?.readOnly, - }; - } - const info = messageList.serialize().memoryInfo; - if (info?.threadId) return { threadId: info.threadId, resourceId: info.resourceId ?? info.threadId, readOnly: false }; - return null; -} - -const WORKING_MEMORY_TAG = 'platform-working-memory'; - -/** - * Adds the resource's stored working memory as a system message. The hosted processors don't - * deliver it, so the client reads it on the first step of every run: a fresh read each run, so an - * update between runs shows up on the next one. - */ -async function addWorkingMemory( - client: PlatformMemoryClient, - messageList: MessageListLike, - resourceId: string, - canUpdate: boolean, -) { - const data = await client.getWorkingMemory(resourceId); - messageList.clearSystemMessages(WORKING_MEMORY_TAG); - if (canUpdate) { - messageList.addSystem( - `WORKING_MEMORY_SYSTEM_INSTRUCTION: -Store and update any conversation-relevant information about the user by calling the updateWorkingMemory tool. Pass the whole memory each time: anything you leave out is removed. - - -${data ?? ''} -`, - WORKING_MEMORY_TAG, - ); - } else if (data) { - messageList.addSystem( - `WORKING_MEMORY_SYSTEM_INSTRUCTION (READ-ONLY): -The following is what is remembered about the user. Use it for context; you cannot change it. - - -${data} -`, - WORKING_MEMORY_TAG, - ); - } -} - -/** - * What a read-only run sees of the thread, read through the context route, which writes nothing: - * observations, the continuation reminder, then the messages not yet observed. Running the hosted - * processors instead would save messages and start observation. - */ -async function addReadOnlyContext( - client: PlatformMemoryClient, - messageList: MessageListLike, - threadId: string, - resourceId: string, -) { - const context = await client.getContext(threadId, resourceId, { workingMemory: 'off' }); - const prompt = context.prompt ?? [ - ...(context.system - ? [{ id: 'om-system', role: 'system', content: context.system, parts: [], createdAt: new Date(0).toISOString() }] - : []), - ...(context.continuation - ? [ - { - id: 'om-continuation', - role: 'user', - content: context.continuation, - parts: [], - createdAt: new Date(0).toISOString(), - }, - ] - : []), - ...context.messages, - ]; - for (const message of prompt) { - if (message.role === 'system') messageList.addSystem(message.content, 'memory'); - else messageList.add(messageFromApi(message, threadId, resourceId), 'memory'); - } -} - -async function applyResult( - result: MemoryProcessorsResult, - agent: Pick, -) { - for (const chunk of result.chunks) await agent.writer?.custom(chunk as never); - for (let i = 0; i < result.rotations; i++) agent.rotateResponseMessageId?.(); - if (result.aborted !== null || !result.messageList) return agent.abort(result.aborted ?? undefined); - return agent.messageList.deserialize(result.messageList); -} - -/** - * Mastra memory backed by a hosted Platform Memory instance. - * - * Observation and reflection run on the Platform: on each input step and on the final output this - * class sends the serialized message list to the instance's memory processors and applies the - * result. Messages are stored with all their parts (text, tool calls, reasoning, files). - */ -export class PlatformMemory extends MastraMemory { - readonly client: PlatformMemoryClient; - private readonly workingMemoryMode: 'readonly' | 'tool' | 'off'; - - constructor(options: PlatformMemoryOptions = {}) { - super({ id: options.id ?? 'platform-memory', name: 'PlatformMemory' }); - this.client = options.client ?? new PlatformMemoryClient(options); - this.workingMemoryMode = options.workingMemory ?? 'readonly'; - } - - listTools(config?: MemoryConfig): Record> { - if (this.workingMemoryMode !== 'tool' || config?.readOnly) return {}; - this.assertResourceScopedWorkingMemory(config); - const client = this.client; - return { - updateWorkingMemory: createTool({ - id: 'update-working-memory', - description: - 'Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.', - inputSchema: z.object({ - memory: z.string().describe('The Markdown formatted working memory content to store.'), - }), - execute: async ({ memory }, context) => { - const resourceId = context?.agent?.resourceId ?? context?.agent?.threadId; - if (!resourceId) throw new Error('updateWorkingMemory needs a thread or resource'); - await client.updateWorkingMemory(resourceId, memory); - return { success: true }; - }, - }), - }; - } - - // The instance runs the real @mastra/memory processors; these only ship the message list - // there and apply what comes back (list, stream parts, message-id rotations, abort). - async getInputProcessors(): Promise { - const client = this.client; - const workingMemoryMode = this.workingMemoryMode; - return [ - { - id: 'platform-memory', - name: 'Platform Memory', - async processInputStep({ - messageList, - requestContext, - stepNumber, - model, - writer, - abort, - abortSignal, - rotateResponseMessageId, - }: ProcessInputStepArgs) { - const ctx = memoryContext(requestContext, messageList); - if (!ctx) return messageList; - if (ctx.readOnly) { - if (stepNumber === 0) { - await addReadOnlyContext(client, messageList, ctx.threadId, ctx.resourceId); - if (workingMemoryMode !== 'off') await addWorkingMemory(client, messageList, ctx.resourceId, false); - } - return messageList; - } - const result = await client.runProcessors( - ctx.threadId, - { - phase: 'inputStep', - resourceId: ctx.resourceId, - stepNumber, - messageList: messageList.serialize(), - model: model ? { provider: model.provider, modelId: model.modelId } : undefined, - }, - abortSignal, - ); - const list = await applyResult(result, { messageList, writer, abort, rotateResponseMessageId }); - if (stepNumber === 0 && workingMemoryMode !== 'off') { - await addWorkingMemory(client, messageList, ctx.resourceId, workingMemoryMode === 'tool'); - } - return list; - }, - }, - ]; - } - - async getOutputProcessors(): Promise { - const client = this.client; - return [ - { - id: 'platform-memory', - name: 'Platform Memory', - async processOutputResult({ messageList, requestContext, result, writer, abort }: ProcessOutputResultArgs) { - const ctx = memoryContext(requestContext, messageList); - if (!ctx || ctx.readOnly) return messageList; - // No abortSignal here: this call saves the turn's messages, and aborting mid-save can lose them. - const res = await client.runProcessors(ctx.threadId, { - phase: 'output', - resourceId: ctx.resourceId, - messageList: messageList.serialize(), - finishReason: result?.finishReason, - }); - return applyResult(res, { messageList, writer, abort }); - }, - }, - ]; - } - - async getThreadById({ threadId }: { threadId: string }): Promise { - const thread = await this.client.getThread(threadId); - return thread ? threadFromApi(thread) : null; - } - - async listThreads(args: StorageListThreadsInput): Promise { - const page = args.page ?? 0; - const perPage = args.perPage === false ? 200 : (args.perPage ?? 100); - const threads: StorageThreadType[] = []; - for (let next = 0; ; next++) { - const res = await this.client.listThreads({ resourceId: args.filter?.resourceId, page: next, perPage: 200 }); - threads.push(...res.threads.map(threadFromApi)); - if (!res.hasMore) break; - } - const filtered = threads.filter(thread => - Object.entries(args.filter?.metadata ?? {}).every(([key, value]) => thread.metadata?.[key] === value), - ); - const field = args.orderBy?.field ?? 'updatedAt'; - const direction = args.orderBy?.direction === 'ASC' ? 1 : -1; - filtered.sort((a, b) => direction * (a[field].getTime() - b[field].getTime())); - const selected = args.perPage === false ? filtered : filtered.slice(page * perPage, (page + 1) * perPage); - return { - threads: selected, - hasMore: args.perPage === false ? false : (page + 1) * perPage < filtered.length, - page, - perPage: args.perPage === false ? (false as const) : perPage, - total: filtered.length, - }; - } - - async saveThread({ thread }: { thread: StorageThreadType }): Promise { - const existing = await this.client.getThread(thread.id); - const saved = existing - ? await this.client.updateThread(thread.id, { title: thread.title, metadata: thread.metadata }) - : await this.client.createThread({ - id: thread.id, - resourceId: thread.resourceId, - title: thread.title, - metadata: thread.metadata, - }); - return threadFromApi(saved); - } - - async updateThread({ - id, - title, - metadata, - }: { - id: string; - title?: string; - metadata?: Record; - memoryConfig?: MemoryConfigInternal; - }): Promise { - return threadFromApi(await this.client.updateThread(id, { title, metadata })); - } - - async deleteThread(threadId: string): Promise { - await this.client.deleteThread(threadId); - } - - async saveMessages(args: { - messages: MastraDBMessage[]; - memoryConfig?: MemoryConfig; - }): Promise<{ messages: MastraDBMessage[] }> { - const byThread = new Map(); - for (const message of args.messages) { - if (!message.threadId) continue; - byThread.set(message.threadId, [...(byThread.get(message.threadId) ?? []), message]); - } - for (const [threadId, messages] of byThread) { - const apiMessages = toApiMessages(messages); - if (!apiMessages.length) continue; - const resourceId = messages[0]!.resourceId ?? threadId; - await this.client.saveMessages(threadId, { resourceId, messages: apiMessages }); - } - return { messages: args.messages }; - } - - async recall(args: StorageListMessagesInput) { - const threadIds = Array.isArray(args.threadId) ? args.threadId : [args.threadId]; - if (!threadIds.length || threadIds.some(id => !id)) throw new Error('PlatformMemory.recall requires a threadId'); - if (Object.keys(args.filter?.metadata ?? {}).length || args.include?.length) { - throw new Error('PlatformMemory.recall does not support metadata filters or include windows'); - } - const page = args.page ?? 0; - const perPage = args.perPage === false ? 200 : (args.perPage ?? 40); - const messages: MastraDBMessage[] = []; - for (const threadId of threadIds) { - const thread = await this.client.getThread(threadId); - if (!thread || (args.resourceId && thread.resourceId !== args.resourceId)) continue; - const resourceId = thread.resourceId; - for (let next = 0; ; next++) { - const res = await this.client.listMessages(threadId, { page: next, perPage: 200 }); - messages.push(...res.messages.map(message => messageFromApi(message, threadId, resourceId))); - if (!res.hasMore) break; - } - } - const { start, end, startExclusive, endExclusive } = args.filter?.dateRange ?? {}; - const filtered = messages.filter(message => { - const timestamp = message.createdAt.getTime(); - return ( - (!start || (startExclusive ? timestamp > start.getTime() : timestamp >= start.getTime())) && - (!end || (endExclusive ? timestamp < end.getTime() : timestamp <= end.getTime())) - ); - }); - const direction = args.orderBy?.direction === 'DESC' ? -1 : 1; - filtered.sort((a, b) => direction * (a.createdAt.getTime() - b.createdAt.getTime())); - const selected = args.perPage === false ? filtered : filtered.slice(page * perPage, (page + 1) * perPage); - return { - messages: selected, - total: filtered.length, - page, - perPage: args.perPage === false ? (false as const) : perPage, - hasMore: args.perPage === false ? false : (page + 1) * perPage < filtered.length, - }; - } - - // Hosted working memory is keyed by resource only, so thread scope would silently be shared - // across every thread of the same resource. - private assertResourceScopedWorkingMemory(config?: MemoryConfig | MemoryConfigInternal): void { - if (this.getMergedThreadConfig(config ?? {}).workingMemory?.scope === 'thread') { - throw new Error('PlatformMemory does not support thread-scoped working memory'); - } - } - - async getWorkingMemory({ - threadId, - resourceId, - memoryConfig, - }: { - threadId: string; - resourceId?: string; - memoryConfig?: MemoryConfigInternal; - }): Promise { - this.assertResourceScopedWorkingMemory(memoryConfig); - return this.client.getWorkingMemory(resourceId ?? threadId); - } - - async getWorkingMemoryTemplate(): Promise { - return null; - } - - async updateWorkingMemory({ - threadId, - resourceId, - workingMemory, - memoryConfig, - }: { - threadId: string; - resourceId?: string; - workingMemory: string; - memoryConfig?: MemoryConfigInternal; - }): Promise { - this.assertResourceScopedWorkingMemory(memoryConfig); - await this.client.updateWorkingMemory(resourceId ?? threadId, workingMemory); - } - - async __experimental_updateWorkingMemoryVNext(args: { - threadId: string; - resourceId?: string; - workingMemory: string; - memoryConfig?: MemoryConfigInternal; - }): Promise<{ success: boolean; reason: string }> { - await this.updateWorkingMemory(args); - return { success: true, reason: 'replaced' }; - } - - async deleteMessages(): Promise { - throw new Error('PlatformMemory does not support deleting individual messages yet'); - } - - async cloneThread(_args: StorageCloneThreadInput): Promise { - throw new Error('PlatformMemory does not support cloning threads yet'); - } -} diff --git a/packages/platform/src/memory/scale.live.test.ts b/packages/platform/src/memory/scale.live.test.ts deleted file mode 100644 index 98609a0587b..00000000000 --- a/packages/platform/src/memory/scale.live.test.ts +++ /dev/null @@ -1,202 +0,0 @@ -import { readFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import path from 'node:path'; - -import { MockLanguageModelV2, convertArrayToReadableStream } from '@internal/ai-sdk-v5/test'; -import { Agent } from '@mastra/core/agent'; -import type { MastraMemory } from '@mastra/core/memory'; -import { InMemoryStore } from '@mastra/core/storage'; -import { createTool } from '@mastra/core/tools'; -import { Memory } from '@mastra/memory'; -import { describe, expect, it } from 'vitest'; -import { z } from 'zod'; - -import { PlatformMemoryClient } from './client'; -import { PlatformMemory } from './platform-memory'; - -/** - * Scale run for PlatformMemory: many threads at once, multi-step turns, real observer/reflector - * (OpenAI through the harness's Gateway shim), several replicas behind a round-robin proxy. - * The same workload runs on local `Memory` as the baseline for how much the observer remembers. - * - * Reports step latency, errors (lease-busy 503s included) and recall of per-turn code words, - * then writes a manifest for the SQL invariant check. Knobs: SCALE_THREADS, SCALE_TURNS, - * SCALE_AGENT_DELAY_MS (simulated agent model latency), SCALE_BACKENDS (comma list), - * SCALE_THRESHOLDS (JSON, must match the server's PARITY_THRESHOLDS). - */ -const live = !!process.env.PLATFORM_MEMORY_LIVE; -const envFile = process.env.PARITY_ENV_FILE ?? path.join(tmpdir(), 'platform-memory-parity.json'); -const THREADS = Number(process.env.SCALE_THREADS ?? 20); -const TURNS = Number(process.env.SCALE_TURNS ?? 6); -const AGENT_DELAY_MS = Number(process.env.SCALE_AGENT_DELAY_MS ?? 0); -const THRESHOLDS = JSON.parse( - process.env.SCALE_THRESHOLDS ?? '{"messageTokens":600,"observationTokens":1500,"bufferTokens":200}', -); -const BACKENDS = (process.env.SCALE_BACKENDS ?? 'Memory,PlatformMemory').split(','); -const RUN = process.env.SCALE_RUN ?? `scale-${Date.now()}`; -const MANIFEST = process.env.SCALE_MANIFEST ?? path.join(tmpdir(), 'platform-memory-scale.json'); - -const usage = { inputTokens: 10, outputTokens: 10, totalTokens: 20 }; -const sleep = (ms: number) => new Promise(r => setTimeout(r, ms)); -const codeWord = (thread: number, turn: number) => `zx${thread}q${turn}k`; - -const FILLER = - 'I spend weekends restoring an old sailboat, I am training for a half marathon, and my team ' + - 'is migrating a billing system off a legacy database while keeping invoices accurate. '; - -/** Tool call on the first step of each turn, then a reply that echoes the turn. */ -function agentModel() { - return new MockLanguageModelV2({ - doStream: async ({ prompt }) => { - if (AGENT_DELAY_MS) await sleep(AGENT_DELAY_MS * (0.5 + Math.random())); - const parts: unknown[] = - prompt.at(-1)?.role === 'tool' - ? [ - { type: 'stream-start', warnings: [] }, - { type: 'text-start', id: 't' }, - { type: 'text-delta', id: 't', delta: `Noted. ${FILLER}` }, - { type: 'text-end', id: 't' }, - { type: 'finish', finishReason: 'stop', usage }, - ] - : [ - { type: 'stream-start', warnings: [] }, - { type: 'tool-call', toolCallId: `c${Math.random()}`, toolName: 'lookup', input: '{"q":"notes"}' }, - { type: 'finish', finishReason: 'tool-calls', usage }, - ]; - return { stream: convertArrayToReadableStream(parts as never[]) }; - }, - }); -} - -const lookup = createTool({ - id: 'lookup', - description: 'Looks up notes', - inputSchema: z.object({ q: z.string() }), - execute: async () => ({ notes: 'The user prefers concise answers. '.repeat(10) }), -}); - -function makeMemory(name: string): { memory: MastraMemory; observations: (t: string, r: string) => Promise } { - if (name === 'PlatformMemory') { - const { apiUrl, instanceId, token } = JSON.parse(readFileSync(envFile, 'utf8')); - const client = new PlatformMemoryClient({ apiUrl, accessToken: token, instanceId }); - return { - memory: new PlatformMemory({ client, workingMemory: 'off' }), - observations: async (t, r) => (await client.getContext(t, r)).system ?? '', - }; - } - const memory = new Memory({ - storage: new InMemoryStore(), - options: { - observationalMemory: { - enabled: true, - observation: { - model: 'openai/gpt-4o-mini', - messageTokens: THRESHOLDS.messageTokens, - bufferTokens: THRESHOLDS.bufferTokens, - }, - reflection: { model: 'openai/gpt-4o-mini', observationTokens: THRESHOLDS.observationTokens }, - }, - }, - }); - return { - memory, - observations: async (t, r) => { - await (await memory.omEngine)?.settled(); - return (await memory.getContext({ threadId: t, resourceId: r })).systemMessage ?? ''; - }, - }; -} - -const pct = (xs: number[], p: number) => { - const s = [...xs].sort((a, b) => a - b); - return s.length ? s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))]! : 0; -}; - -const results: Record = {}; - -describe.skipIf(!live).each(BACKENDS)('scale (%s)', name => { - it(`${THREADS} threads x ${TURNS} turns`, { timeout: 30 * 60_000 }, async () => { - const { memory, observations } = makeMemory(name); - const agent = new Agent({ - id: 'scale', - name: 'scale', - instructions: 'You are a helpful assistant.', - model: agentModel() as never, - tools: { lookup }, - memory, - }); - const turnMs: number[] = []; - const errors: string[] = []; - const threads = Array.from({ length: THREADS }, (_, i) => ({ - threadId: `${RUN}-${name}-t${i}`, - resourceId: `${RUN}-${name}-r${i}`, - })); - - const started = Date.now(); - await Promise.all( - threads.map(async ({ threadId, resourceId }, i) => { - for (let turn = 0; turn < TURNS; turn++) { - const t0 = Date.now(); - try { - const text = `Turn ${turn}. Please remember my code word for today is ${codeWord(i, turn)}. ${FILLER}`; - // SCALE_RESEND=1 models a chat UI that loads the thread from storage and resends all of it. - const history = - process.env.SCALE_RESEND === '1' && turn > 0 - ? (await memory.recall({ threadId, resourceId, perPage: false })).messages - : []; - const out = await agent.stream([...history, { role: 'user', content: text }] as never, { - memory: { thread: threadId, resource: resourceId }, - maxSteps: 3, - }); - await out.consumeStream(); - const err = (await out.error) as Error | undefined; - if (err) errors.push(`${threadId}#${turn}: ${err.message}`); - } catch (err) { - errors.push(`${threadId}#${turn}: ${(err as Error).message}`); - } - turnMs.push(Date.now() - t0); - } - }), - ); - const wallMs = Date.now() - started; - - // Recall: code words the next turn's context still carries (observations, or raw messages - // not yet observed are not counted, so this measures what the observer kept). - let remembered = 0; - for (const [i, { threadId, resourceId }] of threads.entries()) { - const text = await observations(threadId, resourceId); - for (let turn = 0; turn < TURNS; turn++) if (text.includes(codeWord(i, turn))) remembered++; - } - - let markerOnly = 0; - let sealed = 0; - let withMarkers = 0; - if (name !== 'PlatformMemory') { - for (const { threadId, resourceId } of threads) { - const { messages } = await memory.recall({ threadId, resourceId, perPage: false }); - sealed += messages.filter(m => (m.content.metadata as any)?.mastra?.sealed === true).length; - withMarkers += messages.filter(m => m.content.parts.some(p => p.type.startsWith('data-om-'))).length; - markerOnly += messages.filter( - m => m.content.parts.length > 0 && m.content.parts.every(p => p.type.startsWith('data-om-')), - ).length; - } - } - - const summary = { - markerOnly, - sealed, - withMarkers, - turns: turnMs.length, - errors: errors.length, - sampleErrors: errors.slice(0, 5), - turnMs: { p50: pct(turnMs, 50), p95: pct(turnMs, 95), max: pct(turnMs, 100) }, - wallMs, - recallPct: Math.round((remembered / (THREADS * TURNS)) * 100), - }; - results[name] = { ...summary, threads }; - console.log(`SCALE ${name} ${JSON.stringify(summary)}`); - const { writeFileSync } = await import('node:fs'); - writeFileSync(MANIFEST, JSON.stringify({ run: RUN, turns: TURNS, results }, null, 2)); - expect(errors).toEqual([]); - }); -}); diff --git a/packages/platform/tsconfig.build.json b/packages/platform/tsconfig.build.json deleted file mode 100644 index caa0c57cf19..00000000000 --- a/packages/platform/tsconfig.build.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": ["./tsconfig.json", "../../tsconfig.build.json"], - "compilerOptions": { - "outDir": "./dist", - "rootDir": "./src" - }, - "include": ["src/**/*"], - "exclude": ["node_modules", "**/*.test.ts"] -} diff --git a/packages/platform/tsconfig.json b/packages/platform/tsconfig.json deleted file mode 100644 index d03c10c18a3..00000000000 --- a/packages/platform/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": "../../tsconfig.node.json", - "include": ["src/**/*", "tsdown.config.ts"], - "exclude": ["node_modules", "**/*.test.ts"] -} diff --git a/packages/platform/tsdown.config.ts b/packages/platform/tsdown.config.ts deleted file mode 100644 index d05542f49a4..00000000000 --- a/packages/platform/tsdown.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { generateTypes } from '@internal/types-builder'; -import { defineConfig } from 'tsdown'; - -export default defineConfig({ - entry: ['src/index.ts'], - format: ['esm', 'cjs'], - fixedExtension: false, - nodeProtocol: 'strip', - clean: true, - dts: false, - treeshake: true, - sourcemap: true, - deps: { - neverBundle: ['@mastra/core', '@mastra/platform-workspace', '@mastra/stagehand'], - }, - onSuccess: async () => { - await generateTypes(process.cwd()); - }, -}); diff --git a/packages/platform/vitest.config.ts b/packages/platform/vitest.config.ts deleted file mode 100644 index 8e730d5055c..00000000000 --- a/packages/platform/vitest.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { defineConfig } from 'vitest/config'; - -export default defineConfig({ - test: { - globals: true, - environment: 'node', - }, -}); diff --git a/packages/playground-ui/CHANGELOG.md b/packages/playground-ui/CHANGELOG.md index 5ba7925a391..5bb85a3a248 100644 --- a/packages/playground-ui/CHANGELOG.md +++ b/packages/playground-ui/CHANGELOG.md @@ -1,23 +1,5 @@ # @mastra/playground-ui -## 69.1.0-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/client-js@1.60.1-alpha.6 - - @mastra/react@1.15.1-alpha.6 - -## 69.1.0-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/client-js@1.60.1-alpha.5 - - @mastra/react@1.15.1-alpha.5 - ## 69.1.0-alpha.4 ### Minor Changes diff --git a/packages/playground-ui/package.json b/packages/playground-ui/package.json index 6c1b54a190e..d432ec42498 100644 --- a/packages/playground-ui/package.json +++ b/packages/playground-ui/package.json @@ -1,7 +1,7 @@ { "name": "@mastra/playground-ui", "type": "module", - "version": "69.1.0-alpha.6", + "version": "69.1.0-alpha.4", "description": "Mastra Playground components", "sideEffects": [ "**/*.css" diff --git a/packages/playground-ui/src/ds/components/CodeDiff/code-diff.css b/packages/playground-ui/src/ds/components/CodeDiff/code-diff.css index e1a83211f0d..f7ddb710e59 100644 --- a/packages/playground-ui/src/ds/components/CodeDiff/code-diff.css +++ b/packages/playground-ui/src/ds/components/CodeDiff/code-diff.css @@ -12,10 +12,3 @@ --diffs-bg-separator-override: var(--muted); --diffs-fg-number-override: var(--placeholder); } - -/* Under a file header the lines run flush from the header to the card's bottom edge, like a pull request. - The horizontal scrollbar only takes room when lines overflow. */ -.code-diff[data-header] { - --diffs-gap-block: 0px; - --diffs-overflow-override: auto; -} diff --git a/packages/playground-ui/src/ds/components/CodeDiff/code-diff.tsx b/packages/playground-ui/src/ds/components/CodeDiff/code-diff.tsx index f469a21ce05..69ebe8f8d51 100644 --- a/packages/playground-ui/src/ds/components/CodeDiff/code-diff.tsx +++ b/packages/playground-ui/src/ds/components/CodeDiff/code-diff.tsx @@ -97,11 +97,7 @@ export function CodeDiff({ className, layout, overflow = 'wrap', header, ref, .. }; return ( -
+
{header ? ( { } } }); + + it('uses a Mastra gateway model when only MASTRA_GATEWAY_API_KEY is set', async () => { + vi.stubEnv('OPENAI_API_KEY', ''); + vi.stubEnv('MASTRA_GATEWAY_API_KEY', 'test-gateway-key'); + onTestFinished(() => vi.unstubAllEnvs()); + const mastra = makeMastraMock({ + agents: { 'gateway-agent': makeMockAgent({ name: 'gateway-agent', model: 'mastra/openai/gpt-5-mini' }) }, + }); + const generateSpy = vi + .spyOn(Agent.prototype, 'generate') + .mockResolvedValue({ object: { explanation: 'Clearer.', new_prompt: 'Be clear.' } } as any); + onTestFinished(() => generateSpy.mockRestore()); + + const result = await ENHANCE_INSTRUCTIONS_ROUTE.handler({ + ...createTestServerContext({ mastra }), + agentId: 'gateway-agent', + instructions: 'Be helpful.', + }); + + expect(result).toEqual({ explanation: 'Clearer.', new_prompt: 'Be clear.' }); + expect(generateSpy).toHaveBeenCalledOnce(); + }); + + it('skips a gateway model without credentials and uses a later connected model', async () => { + vi.stubEnv('OPENAI_API_KEY', ''); + vi.stubEnv('NETLIFY_TOKEN', ''); + vi.stubEnv('NETLIFY_SITE_ID', ''); + vi.stubEnv('GOOGLE_GENERATIVE_AI_API_KEY', 'test-google-key'); + onTestFinished(() => vi.unstubAllEnvs()); + const mastra = makeMastraMock({ + agents: { + 'fallback-agent': makeMockAgent({ + name: 'fallback-agent', + model: [{ model: 'netlify/openai/gpt-4o' }, { model: 'google/gemini-2.5-flash' }], + }), + }, + }); + const generateSpy = vi + .spyOn(Agent.prototype, 'generate') + .mockResolvedValue({ object: { explanation: 'Clearer.', new_prompt: 'Be clear.' } } as any); + onTestFinished(() => generateSpy.mockRestore()); + + await ENHANCE_INSTRUCTIONS_ROUTE.handler({ + ...createTestServerContext({ mastra }), + agentId: 'fallback-agent', + instructions: 'Be helpful.', + }); + + const enhancer = generateSpy.mock.contexts[0] as Agent; + const chosen = (await enhancer.getModel()) as { provider: string; modelId: string }; + expect(chosen.provider).toBe('google'); + expect(chosen.modelId).toBe('gemini-2.5-flash'); + }); + + it('does not treat a lab provider key as the credential for a gateway model', async () => { + vi.stubEnv('OPENAI_API_KEY', 'test-openai-key'); + vi.stubEnv('NETLIFY_TOKEN', ''); + vi.stubEnv('NETLIFY_SITE_ID', ''); + vi.stubEnv('GOOGLE_GENERATIVE_AI_API_KEY', 'test-google-key'); + onTestFinished(() => vi.unstubAllEnvs()); + const mastra = makeMastraMock({ + agents: { + 'fallback-agent': makeMockAgent({ + name: 'fallback-agent', + model: [{ model: 'netlify/openai/gpt-4o' }, { model: 'google/gemini-2.5-flash' }], + }), + }, + }); + const generateSpy = vi + .spyOn(Agent.prototype, 'generate') + .mockResolvedValue({ object: { explanation: 'Clearer.', new_prompt: 'Be clear.' } } as any); + onTestFinished(() => generateSpy.mockRestore()); + + await ENHANCE_INSTRUCTIONS_ROUTE.handler({ + ...createTestServerContext({ mastra }), + agentId: 'fallback-agent', + instructions: 'Be helpful.', + }); + + const enhancer = generateSpy.mock.contexts[0] as Agent; + const chosen = (await enhancer.getModel()) as { provider: string; modelId: string }; + expect(chosen.provider).toBe('google'); + expect(chosen.modelId).toBe('gemini-2.5-flash'); + }); + + it('returns 400 for a Mastra gateway model when no gateway key is set', async () => { + vi.stubEnv('OPENAI_API_KEY', ''); + vi.stubEnv('MASTRA_GATEWAY_API_KEY', ''); + onTestFinished(() => vi.unstubAllEnvs()); + const mastra = makeMastraMock({ + agents: { 'gateway-agent': makeMockAgent({ name: 'gateway-agent', model: 'mastra/openai/gpt-5-mini' }) }, + }); + + await expect( + ENHANCE_INSTRUCTIONS_ROUTE.handler({ + ...createTestServerContext({ mastra }), + agentId: 'gateway-agent', + instructions: 'Be helpful.', + }), + ).rejects.toMatchObject({ status: 400 }); + }); }); }); diff --git a/packages/server/src/server/handlers/agents.test.ts b/packages/server/src/server/handlers/agents.test.ts index de07cd56444..f6612d4467e 100644 --- a/packages/server/src/server/handlers/agents.test.ts +++ b/packages/server/src/server/handlers/agents.test.ts @@ -526,7 +526,7 @@ describe('getProvidersHandler', () => { expect(result.providers.find(provider => provider.id === 'mastra')?.models).toEqual(['live-chat-model']); }); - it('does not fall back to cached Mastra models when the v2 catalog fails', async () => { + it('keeps the Mastra gateway listed with no models when the v2 catalog fails', async () => { process.env.MASTRA_GATEWAY_VERSION = 'v2'; process.env.MASTRA_GATEWAY_API_KEY = 'test-key'; Object.assign(globalThis, { @@ -552,7 +552,9 @@ describe('getProvidersHandler', () => { requestContext: new RequestContext(), }); - expect(result.providers.find(provider => provider.id === 'mastra')).toBeUndefined(); + const gateway = result.providers.find(provider => provider.id === 'mastra'); + expect(gateway).toMatchObject({ name: 'Gateway', envVar: 'MASTRA_GATEWAY_API_KEY', connected: true }); + expect(gateway?.models).toEqual([]); expect(result.providers.find(provider => provider.id === 'openai')).toBeDefined(); }); }); diff --git a/packages/server/src/server/handlers/agents.ts b/packages/server/src/server/handlers/agents.ts index 8594cf14b16..1f3cc90f28b 100644 --- a/packages/server/src/server/handlers/agents.ts +++ b/packages/server/src/server/handlers/agents.ts @@ -2093,6 +2093,18 @@ export async function buildProvidersList(mastra: Context['mastra']): Promise>): Promise { + const router = model as { gatewayId?: unknown; resolveApiProviderId?: () => Promise }; + if ( + typeof router.gatewayId === 'string' && + router.gatewayId !== 'models.dev' && + typeof router.resolveApiProviderId === 'function' + ) { + return (await router.resolveApiProviderId()) !== undefined; + } + return isProviderConnected(model.provider); +} + // Helper to find the first model with a connected provider async function findConnectedModel(agent: Agent): Promise> | null> { const modelList = await agent.getModelList(); @@ -4383,7 +4415,7 @@ async function findConnectedModel(agent: Agent): Promise Record | undefined }): boolean { - if (process.env.MASTRA_GATEWAY_VERSION === 'v2') return true; - const key = process.env.MASTRA_GATEWAY_API_KEY; - if (!!key && isV2GatewayKey(key)) return true; - // A user-registered MastraGateway can hold a v2 key in its config rather - // than the environment; ask the instance for its effective v2 state. const gateways = mastra?.listGateways?.() ?? {}; for (const gateway of Object.values(gateways)) { const candidate = gateway as { id?: string; isV2?: () => boolean }; - if (candidate?.id === 'mastra' && typeof candidate.isV2 === 'function' && candidate.isV2()) return true; + if (candidate?.id === 'mastra' && typeof candidate.isV2 === 'function') return candidate.isV2(); } - return false; + return isGatewayV2ByEnvironment(); +} + +/** Whether the environment alone (MASTRA_GATEWAY_API_KEY and MASTRA_GATEWAY_VERSION) says v2. */ +function isGatewayV2ByEnvironment(): boolean { + const key = process.env.MASTRA_GATEWAY_API_KEY; + if (key?.startsWith('msk_')) return false; + if (process.env.MASTRA_GATEWAY_VERSION === 'v2') return true; + return !!key && isV2GatewayKey(key); } // Singleton-ish lazy instance @@ -320,10 +325,14 @@ let _gatewayClient: GatewayMemoryClient | null | undefined; * Get a GatewayMemoryClient instance, or null if gateway is not configured. * Pass `mastra` so a registered v2 gateway configuration takes precedence * over a v1 environment key. + * + * The client is built from MASTRA_GATEWAY_API_KEY and MASTRA_GATEWAY_URL, so it is built only when + * the environment itself says v1. A registered gateway that is v1 only because of a key in its own + * config, which the server cannot use here, does not make the environment key a v1 key. */ export function getGatewayClient(mastra?: Parameters[0]): GatewayMemoryClient | null { // Gateway v2 has no memory REST API; Studio must use the agent's own memory configuration. - if (isGatewayV2(mastra)) return null; + if (isGatewayV2(mastra) || isGatewayV2ByEnvironment()) return null; if (_gatewayClient !== undefined) return _gatewayClient; const url = process.env.MASTRA_GATEWAY_URL || 'https://gateway-api.mastra.ai'; const key = process.env.MASTRA_GATEWAY_API_KEY; diff --git a/packages/server/src/server/handlers/gateway-memory-client.v2.test.ts b/packages/server/src/server/handlers/gateway-memory-client.v2.test.ts index 9cb5398dd88..d5222583dd0 100644 --- a/packages/server/src/server/handlers/gateway-memory-client.v2.test.ts +++ b/packages/server/src/server/handlers/gateway-memory-client.v2.test.ts @@ -1,3 +1,4 @@ +import { MastraGateway } from '@mastra/core/llm'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { getGatewayClient, isGatewayV2 } from './gateway-memory-client.js'; @@ -21,6 +22,18 @@ describe('Gateway memory client in v2 deployments', () => { expect(isGatewayV2()).toBe(false); }); + it('is not v2 for a v1 key even when MASTRA_GATEWAY_VERSION is v2', () => { + vi.stubEnv('MASTRA_GATEWAY_VERSION', 'v2'); + vi.stubEnv('MASTRA_GATEWAY_API_KEY', 'msk_v1-key'); + expect(isGatewayV2()).toBe(false); + }); + + it('is v2 when MASTRA_GATEWAY_VERSION is v2 and the key has no v1 prefix', () => { + vi.stubEnv('MASTRA_GATEWAY_VERSION', 'v2'); + vi.stubEnv('MASTRA_GATEWAY_API_KEY', 'deployment-key'); + expect(isGatewayV2()).toBe(true); + }); + it('detects v2 from a registered Mastra gateway instance carrying a v2 config key', () => { vi.stubEnv('MASTRA_GATEWAY_VERSION', ''); vi.stubEnv('MASTRA_GATEWAY_API_KEY', ''); @@ -35,6 +48,24 @@ describe('Gateway memory client in v2 deployments', () => { expect(getGatewayClient(mastra)).toBeNull(); }); + it('agrees with a registered gateway whose v1 config key wins over MASTRA_GATEWAY_VERSION', () => { + vi.stubEnv('MASTRA_GATEWAY_VERSION', 'v2'); + vi.stubEnv('MASTRA_GATEWAY_API_KEY', ''); + const gateway = new MastraGateway({ apiKey: 'msk_0123456789abcdef0123456789abcdef' }); + const mastra = { listGateways: () => ({ mastra: gateway }) }; + expect(gateway.isV2()).toBe(false); + expect(isGatewayV2(mastra)).toBe(false); + }); + + it('does not build a v1 memory client from an organization env key', () => { + vi.stubEnv('MASTRA_GATEWAY_VERSION', ''); + vi.stubEnv('MASTRA_GATEWAY_API_KEY', 'mskv2_org-key'); + const gateway = new MastraGateway({ apiKey: 'msk_0123456789abcdef0123456789abcdef' }); + const mastra = { listGateways: () => ({ mastra: gateway }) }; + expect(isGatewayV2(mastra)).toBe(false); + expect(getGatewayClient(mastra)).toBeNull(); + }); + it('is not v2 when the registered Mastra gateway instance reports v1', () => { vi.stubEnv('MASTRA_GATEWAY_VERSION', ''); vi.stubEnv('MASTRA_GATEWAY_API_KEY', ''); @@ -42,3 +73,67 @@ describe('Gateway memory client in v2 deployments', () => { expect(isGatewayV2(mastra)).toBe(false); }); }); + +describe('v2 detection and the v1 memory client across configurations', () => { + afterEach(() => vi.unstubAllEnvs()); + + const envKeys = { + none: '', + project: 'msk_0123456789abcdef0123456789abcdef', + organization: 'mskv2_org-key', + unprefixed: 'deployment-key', + } as const; + const registeredKeys = { + none: undefined, + v1: 'msk_fedcba9876543210fedcba9876543210', + v2: 'mskv2_registered', + } as const; + + // [env key, MASTRA_GATEWAY_VERSION, registered gateway key, isGatewayV2, v1 memory client built] + const table: Array<[keyof typeof envKeys, 'unset' | 'v2', keyof typeof registeredKeys, boolean, boolean]> = [ + ['none', 'unset', 'none', false, false], + ['none', 'v2', 'none', true, false], + ['none', 'unset', 'v1', false, false], + ['none', 'v2', 'v1', false, false], + ['none', 'unset', 'v2', true, false], + ['none', 'v2', 'v2', true, false], + ['project', 'unset', 'none', false, true], + ['project', 'v2', 'none', false, true], + ['project', 'unset', 'v1', false, true], + ['project', 'v2', 'v1', false, true], + ['project', 'unset', 'v2', true, false], + ['project', 'v2', 'v2', true, false], + ['organization', 'unset', 'none', true, false], + ['organization', 'v2', 'none', true, false], + ['organization', 'unset', 'v1', false, false], + ['organization', 'v2', 'v1', false, false], + ['organization', 'unset', 'v2', true, false], + ['organization', 'v2', 'v2', true, false], + ['unprefixed', 'unset', 'none', false, true], + ['unprefixed', 'v2', 'none', true, false], + ['unprefixed', 'unset', 'v1', false, true], + ['unprefixed', 'v2', 'v1', false, false], + ['unprefixed', 'unset', 'v2', true, false], + ['unprefixed', 'v2', 'v2', true, false], + ]; + + it.each(table)( + 'env key %s, MASTRA_GATEWAY_VERSION %s, registered key %s: v2 is %s, v1 memory client built is %s', + async (envKey, version, registeredKey, expectedV2, expectedClient) => { + vi.stubEnv('MASTRA_GATEWAY_API_KEY', envKeys[envKey]); + vi.stubEnv('MASTRA_GATEWAY_VERSION', version === 'v2' ? 'v2' : ''); + const registered = registeredKeys[registeredKey]; + // Mastra always lists a Mastra gateway: the registered one, or a default one without a config key. + const gateway = registered ? new MastraGateway({ apiKey: registered }) : new MastraGateway(); + const mastra = { listGateways: () => ({ mastra: gateway }) }; + + // A fresh module, so the cached client from one case cannot answer for another. + vi.resetModules(); + const client = await import('./gateway-memory-client.js'); + + expect(client.isGatewayV2(mastra)).toBe(expectedV2); + expect(client.getGatewayClient(mastra) !== null).toBe(expectedClient); + if (!registered) expect(client.isGatewayV2()).toBe(expectedV2); + }, + ); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7dff438958e..07761400baa 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5775,52 +5775,6 @@ importers: specifier: 'catalog:' version: 5.1.0(@opentelemetry/api@1.10.0)(@types/node@22.19.15)(@vitest/coverage-v8@5.1.0)(@vitest/ui@5.1.0)(jsdom@30.1.3(@noble/hashes@2.4.0))(msw@2.15.0(@types/node@22.19.15)(typescript@6.0.3))(vite@8.3.5(@types/node@22.19.15)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) - packages/platform: - dependencies: - '@mastra/platform-workspace': - specifier: workspace:* - version: link:../../workspaces/platform-workspace - '@mastra/stagehand': - specifier: workspace:* - version: link:../../browser/stagehand - devDependencies: - '@internal/ai-sdk-v5': - specifier: workspace:* - version: link:../_vendored/ai_v5 - '@internal/types-builder': - specifier: workspace:* - version: link:../_types-builder - '@mastra/core': - specifier: workspace:* - version: link:../core - '@mastra/memory': - specifier: workspace:* - version: link:../memory - '@mastra/pg': - specifier: workspace:* - version: link:../../stores/pg - '@types/node': - specifier: 22.19.15 - version: 22.19.15 - '@vitest/coverage-v8': - specifier: 'catalog:' - version: 5.1.0(vitest@5.1.0) - '@vitest/ui': - specifier: 'catalog:' - version: 5.1.0(vitest@5.1.0) - tsdown: - specifier: 0.22.9 - version: 0.22.9(oxc-resolver@11.21.2)(tsx@4.23.15)(typescript@7.0.2) - typescript: - specifier: 'catalog:' - version: 7.0.2 - vitest: - specifier: 'catalog:' - version: 5.1.0(@opentelemetry/api@1.10.0)(@types/node@22.19.15)(@vitest/coverage-v8@5.1.0)(@vitest/ui@5.1.0)(jsdom@30.1.3(@noble/hashes@2.4.0))(msw@2.15.0(@types/node@22.19.15)(typescript@7.0.2))(vite@8.3.5(@types/node@22.19.15)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) - zod: - specifier: 'catalog:' - version: 4.6.7 - packages/playground: dependencies: '@autoform/core': @@ -22467,84 +22421,6 @@ packages: '@xyflow/system@0.0.84': resolution: {integrity: sha512-96zfGFjH3oZ3T0MRdH4gJ0SlXuCIxbBuHVevZ4xry5UTxqjzjt010+LRdholgepq7jhrcaz1JNtzrETscwnkEA==} - '@yuku-codegen/binding-android-arm64@0.8.7': - resolution: {integrity: sha512-C/0zV5IhgVdYhGJTwrY0v8dknxlhiKwtVJkMUaexu9/QvRmzlV4vfU3hZlUSgqc2BxQHntL1mCVbDq8j0FRFDw==} - cpu: [arm64] - os: [android] - deprecated: yuku-codegen is pure JavaScript since 0.14 - - '@yuku-codegen/binding-darwin-arm64@0.8.7': - resolution: {integrity: sha512-/u+REDMI4a0/lsJXTM4c53/w31OGZLOReZIyg62uhgLs0kc8NHsj/nOcxTdlQjq5gi0zhdkccD9LaLTXcdzPvw==} - cpu: [arm64] - os: [darwin] - deprecated: yuku-codegen is pure JavaScript since 0.14 - - '@yuku-codegen/binding-darwin-x64@0.8.7': - resolution: {integrity: sha512-sMMzFOwCo4WXR+/6zIBThOocSC50iIIZZdfiIDbaLvj0Ax/rWt/iavyfEAqajyvzydLyCqR/ZItdLWSRlu1umw==} - cpu: [x64] - os: [darwin] - deprecated: yuku-codegen is pure JavaScript since 0.14 - - '@yuku-codegen/binding-freebsd-x64@0.8.7': - resolution: {integrity: sha512-MpdpKXix9P+Y1rKgjvcNeNtGjXeL1CmttNhYINrWls8kRpm4xM/oBGTmn6w7to8lAlwj5jm8q03dQPl5mRv4Qw==} - cpu: [x64] - os: [freebsd] - deprecated: yuku-codegen is pure JavaScript since 0.14 - - '@yuku-codegen/binding-linux-arm-gnu@0.8.7': - resolution: {integrity: sha512-rr1srFLlPAmC1vtxfc9C1YLDe3iH09YjfSeeIidBqKhzx1MATjOAq4mjlRUOnhr/L27MotWIYOFKwVsd5JZFOg==} - cpu: [arm] - os: [linux] - libc: [glibc] - deprecated: yuku-codegen is pure JavaScript since 0.14 - - '@yuku-codegen/binding-linux-arm-musl@0.8.7': - resolution: {integrity: sha512-eAufXh8qBRpiSO6ueaMDL+yyoXIGLhpUce72YbcACtZU2qhExwBIJyEtQf5kH2Ki0X2aqkSjSfog4OPtKXan3Q==} - cpu: [arm] - os: [linux] - libc: [musl] - deprecated: yuku-codegen is pure JavaScript since 0.14 - - '@yuku-codegen/binding-linux-arm64-gnu@0.8.7': - resolution: {integrity: sha512-gw4w6wPoHObBrdIC4duVWLmJOvpdE25j5D7yrM5mACNlK4klRz/lv8hK+ssQk9EJHBgZjSaqZIJVFgqNYbfv7A==} - cpu: [arm64] - os: [linux] - libc: [glibc] - deprecated: yuku-codegen is pure JavaScript since 0.14 - - '@yuku-codegen/binding-linux-arm64-musl@0.8.7': - resolution: {integrity: sha512-L68N6Y4XkqcIaKo3Ra88JEvBEH4AHff44A4INcrxeVWZ8CZtu2tCpfVxe3hR8qQQMcvBSQlDn24KpkCKEhVvfA==} - cpu: [arm64] - os: [linux] - libc: [musl] - deprecated: yuku-codegen is pure JavaScript since 0.14 - - '@yuku-codegen/binding-linux-x64-gnu@0.8.7': - resolution: {integrity: sha512-dzyAbltJmf3Cqlb8HcFuYIf5Yn0fl1vTr3XJ9HiVNNvOlhqPSArOqtw9vI1p6/VTXTjrMLXlU+s+/kNHiIy/Cw==} - cpu: [x64] - os: [linux] - libc: [glibc] - deprecated: yuku-codegen is pure JavaScript since 0.14 - - '@yuku-codegen/binding-linux-x64-musl@0.8.7': - resolution: {integrity: sha512-Otw4MH3404q0Bbvl+YTdW9aoUV5vXmUw8260bWvt1XlaoIX/ceSgI4ygheRDMfBPoHt6FDayQaO9OLVUZAgkFA==} - cpu: [x64] - os: [linux] - libc: [musl] - deprecated: yuku-codegen is pure JavaScript since 0.14 - - '@yuku-codegen/binding-win32-arm64@0.8.7': - resolution: {integrity: sha512-qo/jyrzryiBuKEsFiuWaBCBe3tRMynQ0qFWFgOEjcCMQeZfBm+wKiVEUEFXXLc7bh8YezguAWp0Mtnhq4ARNyA==} - cpu: [arm64] - os: [win32] - deprecated: yuku-codegen is pure JavaScript since 0.14 - - '@yuku-codegen/binding-win32-x64@0.8.7': - resolution: {integrity: sha512-D5lDsVDx6m00E6bWySlWdH72Ca4TPSaphDqB6QjU6MpuNLIJqoGoatYyq2rOmBE8Zv/kunot/o58KGL03P3eiA==} - cpu: [x64] - os: [win32] - deprecated: yuku-codegen is pure JavaScript since 0.14 - '@yuku-core/binding-android-arm64@0.19.0': resolution: {integrity: sha512-wdL2XmTiZixAOaHk9Z0JJZ8u9Qm8d333Zjpc6gaxXFX+UR5BlsfxZ7a2+2Rm71pamppsPYGUGFq2oVLbh6DISw==} cpu: [arm64] @@ -22611,90 +22487,9 @@ packages: cpu: [x64] os: [win32] - '@yuku-parser/binding-android-arm64@0.8.7': - resolution: {integrity: sha512-eGKYiUDX7Y0V7tDTmg+JTVnXnjMqfXXsorZ+EDf5kxwchQ3Or1HS14MzI2fw+jFhHR85fCWt+mtX33Yao73hIQ==} - cpu: [arm64] - os: [android] - deprecated: yuku-parser runs on yuku-core since 0.14 - - '@yuku-parser/binding-darwin-arm64@0.8.7': - resolution: {integrity: sha512-Re0RHelKLnjEURulY2/KxW+Ngb8zuNA4BRZuMwgGQNzVumT6u4U2N2hc01oeYVNVof0i7GrXE4UCNBgbpRRnjQ==} - cpu: [arm64] - os: [darwin] - deprecated: yuku-parser runs on yuku-core since 0.14 - - '@yuku-parser/binding-darwin-x64@0.8.7': - resolution: {integrity: sha512-Hn8DROtQkjlA1ACbPgj4a7eP9IuVOI504oiTwpkWPbpaDWD9KdmnVYCqW+1LfenNK/g7O9NhWGpXEdaCNX7lIA==} - cpu: [x64] - os: [darwin] - deprecated: yuku-parser runs on yuku-core since 0.14 - - '@yuku-parser/binding-freebsd-x64@0.8.7': - resolution: {integrity: sha512-bAP2OV8wRuzplX/jYxv9+vvqQT8JxyNphI8fLfXGL054Xs+4/J5u33cIm3y4rxY8rdoLmmdiJs2Tq7r7lrDRfA==} - cpu: [x64] - os: [freebsd] - deprecated: yuku-parser runs on yuku-core since 0.14 - - '@yuku-parser/binding-linux-arm-gnu@0.8.7': - resolution: {integrity: sha512-kTYwJQQgmZeAWdDIWabiReIZMpmfLueIj1tCmjStUtFGhR1Z0qwxonKVfUC4N7h/VhGGzLZ//7O1kgt1QKqgCg==} - cpu: [arm] - os: [linux] - libc: [glibc] - deprecated: yuku-parser runs on yuku-core since 0.14 - - '@yuku-parser/binding-linux-arm-musl@0.8.7': - resolution: {integrity: sha512-uL4jE8HPT2BLlxAXyD10LqgPuXa9eDa0BKpCdSANmzIJghq/2eZo3/gQNtaxPZMupWoxjYzSad9IXrwu7aYPXQ==} - cpu: [arm] - os: [linux] - libc: [musl] - deprecated: yuku-parser runs on yuku-core since 0.14 - - '@yuku-parser/binding-linux-arm64-gnu@0.8.7': - resolution: {integrity: sha512-3gVN4pWSKZmXiNX7cU164dR9MPvesCHnlH6nPfpK+yQsCuYphjKKplcb4SnZBrhiqmXbgb2HR0c2TS0IZUPhgA==} - cpu: [arm64] - os: [linux] - libc: [glibc] - deprecated: yuku-parser runs on yuku-core since 0.14 - - '@yuku-parser/binding-linux-arm64-musl@0.8.7': - resolution: {integrity: sha512-S0mwfEjoLpxzXeZw802Wa4RaELsQiPtWqG6INcy8j4GtvNFtl4LCX3eGO1XLn9pyLAISLzTRyU3zUCBUPin8lg==} - cpu: [arm64] - os: [linux] - libc: [musl] - deprecated: yuku-parser runs on yuku-core since 0.14 - - '@yuku-parser/binding-linux-x64-gnu@0.8.7': - resolution: {integrity: sha512-lnbWdPmerE5D1uH1G4IEZKnPzCrWCStRGrtgpSIe1RibAo5bZIjDbbbPYXmMHCEh4F+x/JaJpElh26a3r+BPbg==} - cpu: [x64] - os: [linux] - libc: [glibc] - deprecated: yuku-parser runs on yuku-core since 0.14 - - '@yuku-parser/binding-linux-x64-musl@0.8.7': - resolution: {integrity: sha512-769uwndMvMzUvATWbAcEvyLHKA+DzhHSCl/obBUrRdYfRo26yxui6S8y3z7uJ+Naup7UKrDxrpK7OnQkxkl9KQ==} - cpu: [x64] - os: [linux] - libc: [musl] - deprecated: yuku-parser runs on yuku-core since 0.14 - - '@yuku-parser/binding-win32-arm64@0.8.7': - resolution: {integrity: sha512-mEB/9PlaAkisJ6KWGz0zvywXoU6+80dTlR2LwS7s/jcXXoU6fm2+sitBZXtqu3+Q4DcDgPxM45uWMCzPs0TSRw==} - cpu: [arm64] - os: [win32] - deprecated: yuku-parser runs on yuku-core since 0.14 - - '@yuku-parser/binding-win32-x64@0.8.7': - resolution: {integrity: sha512-8vNB2DP0ou61nGb8tc/qfi41gfyDXz1MHr2zqL3nR+cJ6CEbiuWV/l/a/vv151gCgiZLLAyGkQGENpozdg716w==} - cpu: [x64] - os: [win32] - deprecated: yuku-parser runs on yuku-core since 0.14 - '@yuku-toolchain/types@0.19.0': resolution: {integrity: sha512-tFkNbsP4WXX9UMUC5syJGdK9dPMLK0PPaIuXCcCYH75sZ8MrebfBZ2XvCILRTw8AgLivSSCfDa4R67iYBDa4Kg==} - '@yuku-toolchain/types@0.8.7': - resolution: {integrity: sha512-2Z53dNxAJL6UvFoIrDZvYf3zlO8s4VJK4O2hhaB4mXVwwpX/7ajtss3cmfqKvamlNLWyt9FSWs4eoYdlbxpnHA==} - '@zip.js/zip.js@2.24.0': resolution: {integrity: sha512-WlaVKzdqBK+RF3bdiXZWbdCnvGB6PdO4IHC1mn/2Yfl3bASgqUNegnU3+PNg61iecwoPfUi5BgLUPqBukXpyWw==} engines: {bun: '>=0.7.0', deno: '>=1.0.0', node: '>=18.0.0'} @@ -22912,10 +22707,6 @@ packages: resolution: {integrity: sha512-0qWUglt9JEqLFr3w1I1pbrChn1grhaiAR2ocX1PP/flRmxgtwTzPFFFnfIlD6aMOLQZgSuCRlidD70lvx8yhzg==} engines: {node: '>=14'} - ansis@4.5.0: - resolution: {integrity: sha512-KwIVkfFfJSSzBmZhDGuTmkhWqTdyB5oNVzzznBJbBZ5bZtHiqSrcugRF0RKJKT4Ss3d7ZrcjnlFVDlQNmtWfWw==} - engines: {node: '>=14'} - any-promise@1.3.0: resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} @@ -25836,10 +25627,6 @@ packages: get-tsconfig@4.14.3: resolution: {integrity: sha512-++QEw4DIY7WGoukz+/+A/8dGYPT9l9yIadnmSgZ8Rjr3YVSVDipQSO9CdnJo9ePqFqUUqh+wk9uIaoiAwsiPkA==} - get-tsconfig@5.0.0-beta.5: - resolution: {integrity: sha512-/6gFNr0N04nob252sTQxyFLi3eKFRqIg1I87YcqAMT1i6SQrSF6KujUEQrtrjMV0H/eejTCltLdDSTEMzHbnsQ==} - engines: {node: '>=20.20.0'} - get-tsconfig@5.0.0-beta.6: resolution: {integrity: sha512-X6fBC0pmImC70gvX2zm56go9hx0MyoGVdG0tUCkg/D+Xnh5TJsOZ7iDbOdI3PvmtrDxnu1YdDufpK2QJX1Meqw==} engines: {node: '>=20.20.0'} @@ -28309,10 +28096,6 @@ packages: obuf@1.1.2: resolution: {integrity: sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg==} - obug@2.2.1: - resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} - engines: {node: '>=12.20.0'} - obug@3.0.0: resolution: {integrity: sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==} engines: {node: '>=12.20.0'} @@ -30355,25 +30138,6 @@ packages: robust-predicates@3.0.3: resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==} - rolldown-plugin-dts@0.27.14: - resolution: {integrity: sha512-ZvuDDwoIpRK9RPxDXratCpklFO9QZZWndf/sd0VBFb4LEj0jj07UcHK9OCh7V4XiFz2Z89ziyBC2K6tJiDjrbw==} - engines: {node: ^22.18.0 || >=24.11.0} - peerDependencies: - '@typescript/native-preview': '*' - '@volar/typescript': ~2.4.0 - rolldown: ^1.0.0 - typescript: ^5.0.0 || ^6.0.0 || ~7.0.0 - vue-tsc: ~3.2.0 || ~3.3.0 - peerDependenciesMeta: - '@typescript/native-preview': - optional: true - '@volar/typescript': - optional: true - typescript: - optional: true - vue-tsc: - optional: true - rolldown-plugin-dts@0.28.8: resolution: {integrity: sha512-FVhfqxorCWcc20BVT5eVRfRjzLLl6mgzjcMR4gSBf0K4oQMXT0qoHhhzfXy0L7y83fQy7Ug5ZDNk90xM3/LiCQ==} engines: {node: ^22.18.0 || ^24.11.0 || >=26.0.0} @@ -31517,40 +31281,6 @@ packages: resolution: {integrity: sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg==} engines: {node: '>=6'} - tsdown@0.22.9: - resolution: {integrity: sha512-/0QEjQEhOU1t1YxOIAGzFN7bIssd8P0pBpkOmNLCQi3c5UtrcMF5bvq3f30xHJNW9QCA9aUNcNAorMr2CTd6Lg==} - engines: {node: ^22.18.0 || >=24.11.0} - hasBin: true - peerDependencies: - '@arethetypeswrong/core': ^0.18.1 - '@tsdown/css': 0.22.9 - '@tsdown/exe': 0.22.9 - '@vitejs/devtools': '*' - publint: ^0.3.8 - tsx: '*' - typescript: ^5.0.0 || ^6.0.0 || ^7.0.0 - unplugin-unused: ^0.5.0 - unrun: '*' - peerDependenciesMeta: - '@arethetypeswrong/core': - optional: true - '@tsdown/css': - optional: true - '@tsdown/exe': - optional: true - '@vitejs/devtools': - optional: true - publint: - optional: true - tsx: - optional: true - typescript: - optional: true - unplugin-unused: - optional: true - unrun: - optional: true - tsdown@0.23.1: resolution: {integrity: sha512-MSC2WSOts3in95J334/VIS7KPfor3eCSvndJ6KdoVj9Aak9Kh1aNfz9ws5owhdukuTNSXRdfkPEzA/ihpDD6SA==} engines: {node: ^22.18.0 || ^24.11.0 || >=26.0.0} @@ -32669,16 +32399,10 @@ packages: resolution: {integrity: sha512-PyCsiScaelhxBGzL8dyeJkLqvRZycoh78R31Vrt/WqYrm0hMFoKwIw/X7Dx5mBKLWAMlV9I9HEyBOHnj2gZVyw==} engines: {node: '>=14.18.0'} - yuku-ast@0.8.7: - resolution: {integrity: sha512-h6+4bDfyootiMB9vckk5uKo5r5j0GHrkr17FQTDNfEsFT3DWlN9uu1HJwQwc64pgmLCI945fWM3lbTIqxjT3GQ==} - yuku-codegen@0.19.0: resolution: {integrity: sha512-uymAKHjDuaP4BEpkXC/BSLz4DUEF5oArZ5AuD3888nb2miChjWSgpPdojEJxm3pjpXkgUaCRJQyNAbnMN33wHg==} engines: {node: '>=14.18.0'} - yuku-codegen@0.8.7: - resolution: {integrity: sha512-adwDZSh8oVDzhE6Du9PwVWxcOxeV0e2EVhUuMKWfhSY4wkrDq9eqixlxFF3l/XGUV1E7UFzhpz9393MUumkyNw==} - yuku-core@0.19.0: resolution: {integrity: sha512-kYK9e1XdfirNhkipzW0wmMcSWcVF/CWnuugodfVYRCUwvoBefweL9HzB96OiKEhsx78V5WbUxbJqlizMX869Qg==} engines: {node: '>=14.18.0'} @@ -32687,9 +32411,6 @@ packages: resolution: {integrity: sha512-XrBh9ZiQK5mJVRxZBAvD6LwRyAYrK3MFtH3+onyuxFL5hFD44EC3QOmIC1FjTj6H2MMwq46/NAI+NZxLZPZgxg==} engines: {node: '>=14.18.0'} - yuku-parser@0.8.7: - resolution: {integrity: sha512-vRD9nwt4L3aYpxNqeSC4WqLv58xrXef0Ong1Mc45CTXTIpvLafx7JO05sczmQZwdLEZvywrLOGdNC5+Rp5N1BQ==} - zeroentropy@0.1.0-alpha.7: resolution: {integrity: sha512-T17yfhO0pJZ0yj7P9STEn1/b6e+yiPdxRgHuFOjU/vXdivpOv96vmadbfYbKJoBMgoDIo/WmPXxUIcS29/Ui0w==} @@ -46553,42 +46274,6 @@ snapshots: d3-selection: 3.0.1 d3-zoom: 3.0.1 - '@yuku-codegen/binding-android-arm64@0.8.7': - optional: true - - '@yuku-codegen/binding-darwin-arm64@0.8.7': - optional: true - - '@yuku-codegen/binding-darwin-x64@0.8.7': - optional: true - - '@yuku-codegen/binding-freebsd-x64@0.8.7': - optional: true - - '@yuku-codegen/binding-linux-arm-gnu@0.8.7': - optional: true - - '@yuku-codegen/binding-linux-arm-musl@0.8.7': - optional: true - - '@yuku-codegen/binding-linux-arm64-gnu@0.8.7': - optional: true - - '@yuku-codegen/binding-linux-arm64-musl@0.8.7': - optional: true - - '@yuku-codegen/binding-linux-x64-gnu@0.8.7': - optional: true - - '@yuku-codegen/binding-linux-x64-musl@0.8.7': - optional: true - - '@yuku-codegen/binding-win32-arm64@0.8.7': - optional: true - - '@yuku-codegen/binding-win32-x64@0.8.7': - optional: true - '@yuku-core/binding-android-arm64@0.19.0': optional: true @@ -46625,46 +46310,8 @@ snapshots: '@yuku-core/binding-win32-x64@0.19.0': optional: true - '@yuku-parser/binding-android-arm64@0.8.7': - optional: true - - '@yuku-parser/binding-darwin-arm64@0.8.7': - optional: true - - '@yuku-parser/binding-darwin-x64@0.8.7': - optional: true - - '@yuku-parser/binding-freebsd-x64@0.8.7': - optional: true - - '@yuku-parser/binding-linux-arm-gnu@0.8.7': - optional: true - - '@yuku-parser/binding-linux-arm-musl@0.8.7': - optional: true - - '@yuku-parser/binding-linux-arm64-gnu@0.8.7': - optional: true - - '@yuku-parser/binding-linux-arm64-musl@0.8.7': - optional: true - - '@yuku-parser/binding-linux-x64-gnu@0.8.7': - optional: true - - '@yuku-parser/binding-linux-x64-musl@0.8.7': - optional: true - - '@yuku-parser/binding-win32-arm64@0.8.7': - optional: true - - '@yuku-parser/binding-win32-x64@0.8.7': - optional: true - '@yuku-toolchain/types@0.19.0': {} - '@yuku-toolchain/types@0.8.7': {} - '@zip.js/zip.js@2.24.0': {} JSONStream@1.3.5: @@ -46885,8 +46532,6 @@ snapshots: ansis@3.17.0: {} - ansis@4.5.0: {} - any-promise@1.3.0: {} anymatch@3.1.3: @@ -50232,10 +49877,6 @@ snapshots: dependencies: resolve-pkg-maps: 1.0.0 - get-tsconfig@5.0.0-beta.5: - dependencies: - resolve-pkg-maps: 1.0.0 - get-tsconfig@5.0.0-beta.6: dependencies: resolve-pkg-maps: 1.0.0 @@ -53309,8 +52950,6 @@ snapshots: obuf@1.1.2: {} - obug@2.2.1: {} - obug@3.0.0: {} ofetch@1.5.1: @@ -56070,20 +55709,6 @@ snapshots: robust-predicates@3.0.3: {} - rolldown-plugin-dts@0.27.14(oxc-resolver@11.21.2)(rolldown@1.2.16)(typescript@7.0.2): - dependencies: - dts-resolver: 3.0.0(oxc-resolver@11.21.2) - get-tsconfig: 5.0.0-beta.5 - obug: 2.2.1 - rolldown: 1.2.16 - yuku-ast: 0.8.7 - yuku-codegen: 0.8.7 - yuku-parser: 0.8.7 - optionalDependencies: - typescript: 7.0.2 - transitivePeerDependencies: - - oxc-resolver - rolldown-plugin-dts@0.28.8(oxc-resolver@11.21.2)(rolldown@1.2.16)(typescript@6.0.3): dependencies: dts-resolver: 3.0.0(oxc-resolver@11.21.2) @@ -57435,32 +57060,6 @@ snapshots: minimist: 1.2.8 strip-bom: 3.0.0 - tsdown@0.22.9(oxc-resolver@11.21.2)(tsx@4.23.15)(typescript@7.0.2): - dependencies: - ansis: 4.5.0 - cac: 7.1.0 - defu: 6.1.7 - empathic: 2.1.0 - hookable: 6.1.2 - import-without-cache: 0.4.1 - obug: 2.2.1 - picomatch: 4.0.7 - rolldown: 1.2.16 - rolldown-plugin-dts: 0.27.14(oxc-resolver@11.21.2)(rolldown@1.2.16)(typescript@7.0.2) - semver: 7.8.6 - tinyexec: 1.3.1 - tinyglobby: 0.2.17 - tree-kill: 1.2.2 - unconfig-core: 7.5.0 - optionalDependencies: - tsx: 4.23.15 - typescript: 7.0.2 - transitivePeerDependencies: - - '@typescript/native-preview' - - '@volar/typescript' - - oxc-resolver - - vue-tsc - tsdown@0.23.1(oxc-resolver@11.21.2)(tsx@4.23.15)(typescript@6.0.3): dependencies: cac: 7.1.0 @@ -58900,31 +58499,10 @@ snapshots: dependencies: '@yuku-toolchain/types': 0.19.0 - yuku-ast@0.8.7: - dependencies: - '@yuku-toolchain/types': 0.8.7 - yuku-codegen@0.19.0: dependencies: '@yuku-toolchain/types': 0.19.0 - yuku-codegen@0.8.7: - dependencies: - '@yuku-toolchain/types': 0.8.7 - optionalDependencies: - '@yuku-codegen/binding-android-arm64': 0.8.7 - '@yuku-codegen/binding-darwin-arm64': 0.8.7 - '@yuku-codegen/binding-darwin-x64': 0.8.7 - '@yuku-codegen/binding-freebsd-x64': 0.8.7 - '@yuku-codegen/binding-linux-arm-gnu': 0.8.7 - '@yuku-codegen/binding-linux-arm-musl': 0.8.7 - '@yuku-codegen/binding-linux-arm64-gnu': 0.8.7 - '@yuku-codegen/binding-linux-arm64-musl': 0.8.7 - '@yuku-codegen/binding-linux-x64-gnu': 0.8.7 - '@yuku-codegen/binding-linux-x64-musl': 0.8.7 - '@yuku-codegen/binding-win32-arm64': 0.8.7 - '@yuku-codegen/binding-win32-x64': 0.8.7 - yuku-core@0.19.0: dependencies: '@yuku-toolchain/types': 0.19.0 @@ -58947,24 +58525,6 @@ snapshots: '@yuku-toolchain/types': 0.19.0 yuku-core: 0.19.0 - yuku-parser@0.8.7: - dependencies: - '@yuku-toolchain/types': 0.8.7 - yuku-ast: 0.8.7 - optionalDependencies: - '@yuku-parser/binding-android-arm64': 0.8.7 - '@yuku-parser/binding-darwin-arm64': 0.8.7 - '@yuku-parser/binding-darwin-x64': 0.8.7 - '@yuku-parser/binding-freebsd-x64': 0.8.7 - '@yuku-parser/binding-linux-arm-gnu': 0.8.7 - '@yuku-parser/binding-linux-arm-musl': 0.8.7 - '@yuku-parser/binding-linux-arm64-gnu': 0.8.7 - '@yuku-parser/binding-linux-arm64-musl': 0.8.7 - '@yuku-parser/binding-linux-x64-gnu': 0.8.7 - '@yuku-parser/binding-linux-x64-musl': 0.8.7 - '@yuku-parser/binding-win32-arm64': 0.8.7 - '@yuku-parser/binding-win32-x64': 0.8.7 - zeroentropy@0.1.0-alpha.7(encoding@0.1.14): dependencies: '@types/node': 22.19.15 diff --git a/server-adapters/elysia/CHANGELOG.md b/server-adapters/elysia/CHANGELOG.md index 51b1981b5ab..de519be010b 100644 --- a/server-adapters/elysia/CHANGELOG.md +++ b/server-adapters/elysia/CHANGELOG.md @@ -1,21 +1,5 @@ # @mastra/elysia -## 0.1.24-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/server@1.84.0-alpha.6 - -## 0.1.24-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`0ed63d7`](https://github.com/mastra-ai/mastra/commit/0ed63d73084c92075b729fc2a25a66b8cea6f9bc), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/server@1.84.0-alpha.5 - ## 0.1.24-alpha.4 ### Patch Changes diff --git a/server-adapters/elysia/package.json b/server-adapters/elysia/package.json index 8b516d8edcd..7c02a1437c7 100644 --- a/server-adapters/elysia/package.json +++ b/server-adapters/elysia/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/elysia", - "version": "0.1.24-alpha.6", + "version": "0.1.24-alpha.4", "description": "Mastra Elysia adapter for the server", "type": "module", "main": "dist/index.js", diff --git a/server-adapters/express/CHANGELOG.md b/server-adapters/express/CHANGELOG.md index fa765b58d08..ec804cc74da 100644 --- a/server-adapters/express/CHANGELOG.md +++ b/server-adapters/express/CHANGELOG.md @@ -1,21 +1,5 @@ # @mastra/express -## 1.5.28-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/server@1.84.0-alpha.6 - -## 1.5.28-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`0ed63d7`](https://github.com/mastra-ai/mastra/commit/0ed63d73084c92075b729fc2a25a66b8cea6f9bc), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/server@1.84.0-alpha.5 - ## 1.5.28-alpha.4 ### Patch Changes diff --git a/server-adapters/express/package.json b/server-adapters/express/package.json index f10d040ae80..1b84ea71dd5 100644 --- a/server-adapters/express/package.json +++ b/server-adapters/express/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/express", - "version": "1.5.28-alpha.6", + "version": "1.5.28-alpha.4", "description": "Mastra Express adapter for the server", "type": "module", "main": "dist/index.js", diff --git a/server-adapters/fastify/CHANGELOG.md b/server-adapters/fastify/CHANGELOG.md index 67023f326b9..81494929b07 100644 --- a/server-adapters/fastify/CHANGELOG.md +++ b/server-adapters/fastify/CHANGELOG.md @@ -1,21 +1,5 @@ # @mastra/fastify -## 1.5.28-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/server@1.84.0-alpha.6 - -## 1.5.28-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`0ed63d7`](https://github.com/mastra-ai/mastra/commit/0ed63d73084c92075b729fc2a25a66b8cea6f9bc), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/server@1.84.0-alpha.5 - ## 1.5.28-alpha.4 ### Patch Changes diff --git a/server-adapters/fastify/package.json b/server-adapters/fastify/package.json index a766a9424f2..b36975581b4 100644 --- a/server-adapters/fastify/package.json +++ b/server-adapters/fastify/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/fastify", - "version": "1.5.28-alpha.6", + "version": "1.5.28-alpha.4", "description": "Mastra Fastify adapter for the server", "type": "module", "main": "dist/index.js", diff --git a/server-adapters/hono/CHANGELOG.md b/server-adapters/hono/CHANGELOG.md index 6f9ec96a3cf..fc18e6418a5 100644 --- a/server-adapters/hono/CHANGELOG.md +++ b/server-adapters/hono/CHANGELOG.md @@ -1,21 +1,5 @@ # @mastra/hono -## 1.7.26-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/server@1.84.0-alpha.6 - -## 1.7.26-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`0ed63d7`](https://github.com/mastra-ai/mastra/commit/0ed63d73084c92075b729fc2a25a66b8cea6f9bc), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/server@1.84.0-alpha.5 - ## 1.7.26-alpha.4 ### Patch Changes diff --git a/server-adapters/hono/package.json b/server-adapters/hono/package.json index 9830388d641..10eff5bd2bc 100644 --- a/server-adapters/hono/package.json +++ b/server-adapters/hono/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/hono", - "version": "1.7.26-alpha.6", + "version": "1.7.26-alpha.4", "description": "Mastra Hono adapter for the server", "type": "module", "main": "dist/index.js", diff --git a/server-adapters/koa/CHANGELOG.md b/server-adapters/koa/CHANGELOG.md index 7c60fdb352a..6119580a94c 100644 --- a/server-adapters/koa/CHANGELOG.md +++ b/server-adapters/koa/CHANGELOG.md @@ -1,21 +1,5 @@ # @mastra/koa -## 1.7.28-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/server@1.84.0-alpha.6 - -## 1.7.28-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`0ed63d7`](https://github.com/mastra-ai/mastra/commit/0ed63d73084c92075b729fc2a25a66b8cea6f9bc), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/server@1.84.0-alpha.5 - ## 1.7.28-alpha.4 ### Patch Changes diff --git a/server-adapters/koa/package.json b/server-adapters/koa/package.json index 58a55e6a787..e37c37d99de 100644 --- a/server-adapters/koa/package.json +++ b/server-adapters/koa/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/koa", - "version": "1.7.28-alpha.6", + "version": "1.7.28-alpha.4", "description": "Mastra Koa adapter for the server", "type": "module", "main": "dist/index.js", diff --git a/server-adapters/nestjs/CHANGELOG.md b/server-adapters/nestjs/CHANGELOG.md index 27c3b1a5387..3ff7c891150 100644 --- a/server-adapters/nestjs/CHANGELOG.md +++ b/server-adapters/nestjs/CHANGELOG.md @@ -1,21 +1,5 @@ # @mastra/nestjs -## 0.3.1-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/server@1.84.0-alpha.6 - -## 0.3.1-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`0ed63d7`](https://github.com/mastra-ai/mastra/commit/0ed63d73084c92075b729fc2a25a66b8cea6f9bc), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/server@1.84.0-alpha.5 - ## 0.3.1-alpha.4 ### Patch Changes diff --git a/server-adapters/nestjs/package.json b/server-adapters/nestjs/package.json index 81cbb1a62f7..3d8e2ce91b2 100644 --- a/server-adapters/nestjs/package.json +++ b/server-adapters/nestjs/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/nestjs", - "version": "0.3.1-alpha.6", + "version": "0.3.1-alpha.4", "description": "Mastra NestJS adapter for the server", "type": "module", "main": "dist/index.js", diff --git a/server-adapters/next/CHANGELOG.md b/server-adapters/next/CHANGELOG.md index 06eb07c5be4..66870ee8d1f 100644 --- a/server-adapters/next/CHANGELOG.md +++ b/server-adapters/next/CHANGELOG.md @@ -1,23 +1,5 @@ # @mastra/next -## 0.2.42-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/hono@1.7.26-alpha.6 - - @mastra/server@1.84.0-alpha.6 - -## 0.2.42-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`0ed63d7`](https://github.com/mastra-ai/mastra/commit/0ed63d73084c92075b729fc2a25a66b8cea6f9bc), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/server@1.84.0-alpha.5 - - @mastra/hono@1.7.26-alpha.5 - ## 0.2.42-alpha.4 ### Patch Changes diff --git a/server-adapters/next/package.json b/server-adapters/next/package.json index ba541839c08..f05190c98dc 100644 --- a/server-adapters/next/package.json +++ b/server-adapters/next/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/next", - "version": "0.2.42-alpha.6", + "version": "0.2.42-alpha.4", "description": "Mastra Next.js server adapter — drop your Mastra instance into a Next.js app", "type": "module", "main": "dist/index.js", diff --git a/server-adapters/tanstack-start/CHANGELOG.md b/server-adapters/tanstack-start/CHANGELOG.md index 02000e37004..820077cc882 100644 --- a/server-adapters/tanstack-start/CHANGELOG.md +++ b/server-adapters/tanstack-start/CHANGELOG.md @@ -1,23 +1,5 @@ # @mastra/tanstack-start -## 0.2.42-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/hono@1.7.26-alpha.6 - - @mastra/server@1.84.0-alpha.6 - -## 0.2.42-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`0ed63d7`](https://github.com/mastra-ai/mastra/commit/0ed63d73084c92075b729fc2a25a66b8cea6f9bc), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/server@1.84.0-alpha.5 - - @mastra/hono@1.7.26-alpha.5 - ## 0.2.42-alpha.4 ### Patch Changes diff --git a/server-adapters/tanstack-start/package.json b/server-adapters/tanstack-start/package.json index f32450fe05b..5834c4e095d 100644 --- a/server-adapters/tanstack-start/package.json +++ b/server-adapters/tanstack-start/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/tanstack-start", - "version": "0.2.42-alpha.6", + "version": "0.2.42-alpha.4", "description": "Mastra TanStack Start server adapter — drop your Mastra instance into a TanStack Start app", "type": "module", "main": "dist/index.js", diff --git a/stores/pg/CHANGELOG.md b/stores/pg/CHANGELOG.md index 30b24b9d3a2..ff0fc686029 100644 --- a/stores/pg/CHANGELOG.md +++ b/stores/pg/CHANGELOG.md @@ -1,14 +1,5 @@ # @mastra/pg -## 1.37.0-alpha.3 - -### Patch Changes - -- Fixed `PgVector` calls failing with "Vector table ... does not exist" after an index was deleted with `deleteIndex()` and created again while that `PgVector` instance was still starting up. Also fixed `createIndex()` on that instance keeping the previous metric when the index was deleted and recreated, or rebuilt, during that time. ([#30578](https://github.com/mastra-ai/mastra/pull/30578)) - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - ## 1.37.0-alpha.2 ### Minor Changes diff --git a/stores/pg/package.json b/stores/pg/package.json index 9e876557d1e..e9cda761edd 100644 --- a/stores/pg/package.json +++ b/stores/pg/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/pg", - "version": "1.37.0-alpha.3", + "version": "1.37.0-alpha.2", "description": "Postgres provider for Mastra - includes both vector and db storage capabilities", "type": "module", "main": "dist/index.js", diff --git a/workflows/temporal/CHANGELOG.md b/workflows/temporal/CHANGELOG.md index be709b24670..1d51345d3c6 100644 --- a/workflows/temporal/CHANGELOG.md +++ b/workflows/temporal/CHANGELOG.md @@ -1,21 +1,5 @@ # @mastra/temporal -## 0.6.1-alpha.6 - -### Patch Changes - -- Updated dependencies [[`0eb407e`](https://github.com/mastra-ai/mastra/commit/0eb407ebcce9d87e96cb399df5a3afb265fc2806)]: - - @mastra/core@1.84.0-alpha.6 - - @mastra/deployer@1.84.0-alpha.6 - -## 0.6.1-alpha.5 - -### Patch Changes - -- Updated dependencies [[`7518c05`](https://github.com/mastra-ai/mastra/commit/7518c05d6f24d37ccebed2a0667e6fe189c3c368), [`b07dd23`](https://github.com/mastra-ai/mastra/commit/b07dd2371304f688a117c441501130853293a14f), [`33fba78`](https://github.com/mastra-ai/mastra/commit/33fba789314c27a9c610095e75f3131ca92831c9), [`e110fa6`](https://github.com/mastra-ai/mastra/commit/e110fa681a156277eed427ecea7a7bf488b02d37), [`d0a2fa4`](https://github.com/mastra-ai/mastra/commit/d0a2fa4e34473a05a582af70270173747c93a938)]: - - @mastra/core@1.84.0-alpha.5 - - @mastra/deployer@1.84.0-alpha.5 - ## 0.6.1-alpha.4 ### Patch Changes diff --git a/workflows/temporal/package.json b/workflows/temporal/package.json index 0b9cd72857a..87544e13798 100644 --- a/workflows/temporal/package.json +++ b/workflows/temporal/package.json @@ -1,6 +1,6 @@ { "name": "@mastra/temporal", - "version": "0.6.1-alpha.6", + "version": "0.6.1-alpha.4", "description": "Mastra Temporal workflows integration - run Mastra workflows on the Temporal durable execution platform", "type": "module", "main": "dist/index.js",