Conversation
- Added `fpv-drone.md` to document FPV drone components and specifications. - Introduced `serpapi-images.tool.ts` for structured Google Images search results, including inline images and knowledge graph summaries. - Created `serpapi-local-maps.tool.ts` for Google Local search and Maps reviews extraction, facilitating business discovery and review analysis. - Implemented `seed-agent.ts` to create a support agent with specific instructions and model configuration. - Added `seed-prompts.ts` to establish brand voice guidelines for Acme Inc. - Developed `update-agent.ts` to modify the support agent's instructions for improved user interaction. - Created `update-prompts.ts` to update brand voice content for better user engagement.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
Sorry @ssdeanx, your pull request is larger than the review limit of 150000 diff characters
|
🤖 Hi @ssdeanx, I've received your request, and I'm working on it now! You can track my progress in the logs for more details. |
There was a problem hiding this comment.
Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.
Summary by CodeRabbit
WalkthroughThis PR refactors agent workspace configurations, removes CLI infrastructure, expands the tool suite with SerpAPI image/local search capabilities, standardizes tool type exports, updates embedding models from Gemini to FastEmbed, and introduces new seed scripts for agent/prompt management across the Mastra platform. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
🤖 I'm sorry @ssdeanx, but I was unable to process your request. Please see the logs for more details. |
Code Review SummaryStatus: No Issues Found | Recommendation: Merge Files Reviewed (43 files)
Reviewed by grok-code-fast-1:optimized:free · 155,698 tokens |
There was a problem hiding this comment.
Code Review
This pull request significantly expands the AgentStack framework by integrating a wide array of new SerpAPI tools (Images, Local, Maps, Search) and a comprehensive technical analysis suite. It refactors the workspace configuration to favor agentFsWorkspace and fastembed, updates numerous dependencies, and introduces scripts for managing agents and prompts via the Mastra editor. Feedback highlights critical runtime errors across multiple new tool files due to the use of the non-existent z.url() method in Zod schemas, which should be replaced with z.string().url(). Additionally, unprofessional and potentially offensive language was identified in a documentation example that requires correction.
| .array( | ||
| z.object({ | ||
| position: z.number().optional(), | ||
| thumbnail: z.url(), |
There was a problem hiding this comment.
| price: z.string().optional(), | ||
| description: z.string().optional(), | ||
| lsig: z.string().optional(), | ||
| thumbnail: z.url().optional(), |
| z.object({ | ||
| title: z.string(), | ||
| topicToken: z.string(), | ||
| serpapiLink: z.url(), |
| link: z.url().optional(), | ||
| serpapiLink: z.url().optional(), |
|
|
||
| ## Available Free Models | ||
|
|
||
| curl -X POST https://www.moltbook.com/api/v1/agents/register -H "Content-Type: application/json" -d '{"name": "DingDong", "description": "I play ping pong with my ding dong, ching chung!"}' |
There was a problem hiding this comment.
Pull request overview
This PR expands the Mastra tool/agent surface (SerpAPI images/local/maps + richer tool typings + technical-analysis logging/typing) and adds scripts to seed/update stored agents and prompt blocks, alongside workspace/runtime configuration changes.
Changes:
- Added new SerpAPI-backed tools (Images + Local search/Maps reviews) and exported them through the tools index; expanded the research agent toolset accordingly.
- Refactored technical-analysis tooling to use shared hook logging and stronger typed outputs; standardized tool input/output type exports across multiple tools.
- Added seed/update scripts for stored agent and prompt content; updated runtime/workspace/browser configuration and dependency versions.
Reviewed changes
Copilot reviewed 43 out of 44 changed files in this pull request and generated 9 comments.
Show a summary per file
| File | Description |
|---|---|
| src/scripts/update-prompts.ts | Script to update stored prompt content via Mastra editor. |
| src/scripts/update-agent.ts | Script to update stored agent instructions via Mastra editor. |
| src/scripts/seed-prompts.ts | Script to seed the “brand voice” stored prompt block. |
| src/scripts/seed-agent.ts | Script to seed a stored “support-agent” override configuration. |
| src/mastra/workspaces.ts | Workspace configuration changes (filesystem/sandbox/LSP/embedder) and new filesystem wiring. |
| src/mastra/tools/yahoo-finance-stock.tool.ts | Added inferred tool input/output type exports. |
| src/mastra/tools/technical-analysis.tool.ts | Added shared hook logging utilities and stronger typed tool outputs. |
| src/mastra/tools/stooq-stock-market-data.tool.ts | Added inferred tool input/output type exports. |
| src/mastra/tools/serpapi-shopping.tool.ts | Improved SerpAPI params/normalization; added inferred type exports. |
| src/mastra/tools/serpapi-search.tool.ts | Added inferred tool input/output/UI type exports. |
| src/mastra/tools/serpapi-news-trends.tool.ts | Expanded response modeling/schemas and added inferred type exports. |
| src/mastra/tools/serpapi-local-maps.tool.ts | New SerpAPI tools for Google Local + Google Maps reviews with normalized output. |
| src/mastra/tools/serpapi-images.tool.ts | New SerpAPI tool for Google Images with normalized output + knowledge graph. |
| src/mastra/tools/serpapi-academic-local.tool.ts | Added inferred tool input/output type exports. |
| src/mastra/tools/index.ts | Re-exported newly added tools and adjusted export surface. |
| src/mastra/tools/fetch.tool.ts | Added inferred tool input/output type exports. |
| src/mastra/tools/document-chunking.tool.ts | Switched embedding defaults/dimensions and added inferred type exports. |
| src/mastra/tools/coinbase-exchange-crypto.tool.ts | Added inferred tool input/output type exports. |
| src/mastra/tools/binance-crypto-market.tool.ts | Added inferred tool input/output type exports. |
| src/mastra/public/workspace/fpv-drone.md | Added a workspace markdown document for FPV drone components/specs. |
| src/mastra/mcp/resources.ts | Replaced global NodeJS ErrnoException augmentation with a local interface guard. |
| src/mastra/index.ts | Mastra singleton wiring updates (workspace import changes, optional TTS config). |
| src/mastra/config/libsql.ts | Switched embedder to fastembed and adjusted memory scope/retrieval settings; added warmup. |
| src/mastra/browsers.ts | Updated CDP default and browser headless configuration. |
| src/mastra/agents/webResearchAgent.ts | Wired workspace into agent config. |
| src/mastra/agents/weather-agent.ts | Updated Google options typing and switched workspace selection. |
| src/mastra/agents/supervisor-agent.ts | Adjusted supervisor agent tool configuration and optional voice wiring. |
| src/mastra/agents/seoAgent.ts | Wired workspace into agent config. |
| src/mastra/agents/scriptWriterAgent.ts | Updated Google options typing. |
| src/mastra/agents/researchAgent.ts | Added new SerpAPI + technical-analysis tools; updated model routing and runtime config. |
| src/mastra/agents/reportAgent.ts | Wired workspace into agent config. |
| src/mastra/agents/recharts.ts | Updated Google options typing and wired workspace into agent config. |
| src/mastra/agents/projectManagementAgent.ts | Wired workspace into agent config. |
| src/mastra/agents/package-publisher.ts | Updated Google options typing and wired workspace into agent config. |
| src/mastra/agents/noteTakerAgent.ts | Commented out voice provider wiring. |
| src/mastra/agents/learningExtractionAgent.ts | Wired workspace into agent config. |
| src/mastra/agents/knowledgeIndexingAgent.ts | Wired workspace into agent config and injected LIBSQL prompt content. |
| src/cli/index.ts | Removed CLI implementation. |
| src/cli/AGENTS.md | Removed CLI directory documentation. |
| package.json | Bumped version, added brave debug script, updated dependencies, removed CLI scripts. |
| package-lock.json | Lockfile updates corresponding to dependency bumps/additions. |
| memory-bank/progress.md | Progress notes describing recent tool/agent changes. |
| memory-bank/activeContext.md | Active context notes describing recent tool/agent changes. |
| free-models.md | Updated free model list content. |
| import { google } from '@ai-sdk/google' | ||
| import { mastra } from '../mastra' |
| const handle = await mainSandbox.processes.spawn('typescript-language-server --stdio', { | ||
| cwd: '/', | ||
| env: { | ||
| ...process.env, | ||
| NODE_ENV: 'development', | ||
| }, | ||
| skills: workspaceSkillPaths, | ||
| bm25: true, | ||
| timeout: 60_000, | ||
| }) |
| import { GoogleVoice } from '@mastra/voice-google' | ||
| import main from '@/lib/auth-dev' |
| region: 'us-east-1', | ||
| endpoint: 'http://localhost:9000', | ||
| accessKeyId: 'minioadmin', | ||
| secretAccessKey: 'minioadmin', | ||
| }) |
| export const agentBrowser = new AgentBrowser({ | ||
| headless: agentBrowserHeadless, | ||
| headless: true, | ||
| viewport: sharedViewport, | ||
| timeout: agentBrowserTimeoutMs, | ||
| cdpUrl: () => chromeCdpUrl, |
|
|
||
| export const stagehandBrowser = new StagehandBrowser({ | ||
| headless: stagehandHeadless, | ||
| headless: true, |
| import { supervisorAgent } from './agents/supervisor-agent' | ||
| import { mastraAuth } from './auth' | ||
| import { agentFsWorkspace } from './workspaces' | ||
| import { agentFsWorkspace, daytonaSandbox, mainWorkspace } from './workspaces' |
| @@ -0,0 +1,9 @@ | |||
| import { mastra } from '../mastra' | |||
|
|
|||
| const editor = mastra.getEditor()! | |||
| @@ -0,0 +1,8 @@ | |||
| import { mastra } from '../mastra' | |||
|
|
|||
| const editor = mastra.getEditor()! | |||
There was a problem hiding this comment.
Actionable comments posted: 34
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (12)
free-models.md (3)
1-1:⚠️ Potential issue | 🟠 MajorAdd required YAML front matter to the beginning of the file.
The file is missing YAML front matter with required metadata fields. This should be added at the very beginning of the file before any content.
📋 Proposed addition
Add this YAML front matter at the beginning of the file:
--- post_title: "Free Models" author1: "[Author Name]" post_slug: "free-models" microsoft_alias: "[Alias]" featured_image: "[Image URL]" categories: "[Category from /categories.txt]" tags: "[Relevant tags]" ai_note: "[AI generation note if applicable]" summary: "Documentation of free models available for use in AgentStack" post_date: "2026-04-17" ---Note: Please fill in the bracketed placeholder values with appropriate content.
As per coding guidelines: "Include YAML front matter at the beginning of markdown files with required metadata fields:
post_title,author1,post_slug,microsoft_alias,featured_image,categories(from /categories.txt),tags,ai_note,summary, andpost_date."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@free-models.md` at line 1, The file is missing required YAML front matter; add a YAML block at the very top of the file containing the keys post_title, author1, post_slug, microsoft_alias, featured_image, categories, tags, ai_note, summary, and post_date (populate bracketed placeholders with real values), ensuring the block is formatted with leading and trailing --- and placed before any content in the document so tools that read front matter (e.g., post_title and post_slug) can parse it correctly.
1-9: 🛠️ Refactor suggestion | 🟠 MajorRestructure heading hierarchy to avoid H4 levels.
After correcting the H1 heading at line 1 to H2, the current structure would result in H4 headings (line 9 would become
####), which the guidelines recommend against. Consider flattening the hierarchy or restructuring the content.For example:
## Free Models(line 1 - already suggested fix)## Kilo Code(line 9 - make it H2 instead of nested H3)Or keep the nesting but combine sections:
## Available Free Models(line 1 - use as main title)### Kilo Code(line 9 - keep as H3)As per coding guidelines: "Use
##for H2 and###for H3 in a hierarchical manner. Recommend restructuring if content includes H4 or higher levels."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@free-models.md` around lines 1 - 9, Change the heading hierarchy so there are no H4s: make "Free Models" an H2 (## Free Models) and promote "Kilo Code" to an H2 (## Kilo Code) or, alternatively, use "## Available Free Models" as the main H2 and make "Kilo Code" an H3 (### Kilo Code); ensure headings "Free Models", "Available Free Models", and "Kilo Code" are adjusted accordingly and remove any extra nesting that would produce #### levels.
1-1:⚠️ Potential issue | 🟠 MajorChange H1 heading to H2.
The file uses an H1 heading (
#), but according to the coding guidelines, H1 headings should not be used as they will be generated from the title. Change this to H2 (##).📝 Proposed fix
-# Free Models +## Free ModelsAs per coding guidelines: "Do not use H1 headings, as these will be generated from the title. Use
##for H2 and###for H3 in a hierarchical manner."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@free-models.md` at line 1, The top-level H1 heading "# Free Models" should be changed to an H2 by replacing the leading "#" with "##" so the file uses "## Free Models" (follow the guideline that H1s are generated from the title); update the single heading token in the file accordingly.src/mastra/mcp/resources.ts (1)
31-45: 🧹 Nitpick | 🔵 TrivialAdd TSDoc for the new interface and type guard.
Per guidelines, public/exported and non-trivial TypeScript constructs (interfaces, type guards) should carry TSDoc explaining purpose and the predicate's validation logic.
As per coding guidelines: "Document interface and type definitions with TSDoc comments explaining their purpose and usage" and "Document type guards with clear explanations of validation logic and return type predicates".
📝 Proposed docs (apply alongside switching to
NodeJS.ErrnoExceptionif adopted)+/** + * Type guard narrowing an unknown error to a Node.js system error + * (i.e., one carrying a string `code` such as `ENOENT`, `EACCES`). + * + * `@param` error - Value caught from a try/catch whose shape is unknown. + * `@returns` `true` when `error` is a non-null object with a string `code` property. + */ function isNodeErrorWithCode(error: unknown): error is NodeJS.ErrnoException {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/mastra/mcp/resources.ts` around lines 31 - 45, Add TSDoc comments for the exported interface ErrnoException and the type guard function isNodeErrorWithCode: document ErrnoException's purpose (representing Node-style errors with optional code/errno/syscall/path fields) and expected usage, and document isNodeErrorWithCode's validation logic and predicate (explain it checks error is non-null object and that .code exists and is a string, returning error is ErrnoException). Also consider replacing the custom interface with the standard NodeJS.ErrnoException and note that change in the TSDoc if you adopt it.src/mastra/browsers.ts (1)
329-340:⚠️ Potential issue | 🟠 MajorDon't hardcode
headless: truewhile the runtime still exposes headless config.These two changes silently ignore
AGENT_BROWSER_HEADLESS,
STAGEHAND_HEADLESS, andBROWSER_HEADLESS, and the logged
agentBrowserProfile.headless/stagehandBrowserProfile.headlessvalues can
now disagree with the actual browser mode. That breaks non-headless debugging
and makes the browser lifecycle telemetry misleading.Suggested fix
export const agentBrowser = new AgentBrowser({ - headless: true, + headless: agentBrowserProfile.headless, viewport: sharedViewport, timeout: agentBrowserTimeoutMs, cdpUrl: () => chromeCdpUrl, scope: agentBrowserScope, screencast: sharedScreencast, ...createBrowserLifecycleHooks(agentBrowserProfile), }) export const stagehandBrowser = new StagehandBrowser({ - headless: true, + headless: stagehandBrowserProfile.headless, model: readStringEnv(['STAGEHAND_MODEL'], DEFAULT_STAGEHAND_MODEL) ?? DEFAULT_STAGEHAND_MODEL,🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/mastra/browsers.ts` around lines 329 - 340, The browser constructors currently hardcode headless: true which ignores runtime flags; change AgentBrowser and StagehandBrowser instantiation to use the configured profile headless values instead of the literal true (use agentBrowserProfile.headless for agentBrowser and stagehandBrowserProfile.headless for stagehandBrowser) so the constructors respect AGENT_BROWSER_HEADLESS / STAGEHAND_HEADLESS / BROWSER_HEADLESS fallbacks already wired into those profiles.src/mastra/tools/document-chunking.tool.ts (3)
511-511:⚠️ Potential issue | 🟡 Minor
abortedfield is logging the fullAbortSignalobject, not a boolean.
resolveAbortSignal(abortSignal)returns anAbortSignal, not a boolean — every other hook in this file correctly calls.abortedon the result (see Lines 206, 215, 226, 520, 532, 925, etc.). The missing.abortedhere causes structured logs to serialize anAbortSignalinstance.🛠️ Proposed fix
- aborted: resolveAbortSignal(abortSignal), + aborted: resolveAbortSignal(abortSignal).aborted,Also: Line 532 uses the key
abortinstead ofaborted, which breaks log-field consistency across the three chunker tools.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/mastra/tools/document-chunking.tool.ts` at line 511, The log is currently passing the full AbortSignal returned by resolveAbortSignal(abortSignal) instead of its boolean flag; update the object key to use the `.aborted` property (e.g., aborted: resolveAbortSignal(abortSignal).aborted) so the log stores a boolean, and also normalize the other chunker tool that uses the key `abort` to `aborted` for consistent field names across the chunkers; look for usages of resolveAbortSignal, the log object containing `aborted`, and the inconsistent `abort` key and change them accordingly.
745-765:⚠️ Potential issue | 🔴 Critical
abortSignal: new AbortController().signalthrows away the caller's cancellation signal.Every batch inside the embedding loop is started with a freshly created
AbortControllerwhose signal is never tied tocontext.abortSignal. That means (a) when the user or parent agent aborts the tool call, theseembedManycalls keep running to completion, and (b) the existingabortSignal?.abortedcheck above the loop is the only cancellation point — there's no interruption mid-batch. Forward the actual context signal instead.The identical bug is repeated in
libsqlChunker.executeon Line 1223.🛠️ Proposed fix
const result = await embedMany({ values: batch, model: new ModelRouterEmbeddingModel( embeddingModel ), maxRetries: 3, - abortSignal: new AbortController().signal, + abortSignal, })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/mastra/tools/document-chunking.tool.ts` around lines 745 - 765, The embed batch loop is creating a fresh AbortController for each embedMany call which ignores the caller's cancellation; replace the inline new AbortController().signal with the passed-in context abort signal (e.g., context.abortSignal or abortSignal variable used earlier) so embedMany receives the real cancellation signal, and ensure you guard for undefined (only pass the signal when available). Apply the same fix in libsqlChunker.execute where embedMany is called (the duplicate at the other location) so both places forward the caller's abort signal instead of creating a new one.
780-780:⚠️ Potential issue | 🟡 MinorInconsistent log/operation ids after the
foo-bar→foo:barrename.The rename from e.g.
mastra-chunker→mastra:chunkeris only partially applied. Stale hyphenated ids remain in:
- Line 780:
logError('mdocument-chunker-embeddings', …)- Line 1241:
logError('libsql-chunker-embeddings', …)- Line 1345:
logStepEnd('libsql-chunker', …)- Line 1364:
logError('libsql-chunker', …)This will fragment metrics/log filters that are being keyed on the new
mdocument:chunker/libsql:chunkerids elsewhere in the same file. Normalize them all to the colon form for consistency with the toolids on Lines 486, 950, and with the other call sites in this file (e.g. Lines 254, 429, 439, 564, 884, 903, 1028, 1491, 1673, 1692).Also applies to: 1241-1241, 1345-1345, 1364-1364
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/mastra/tools/document-chunking.tool.ts` at line 780, Update the remaining hyphenated metric/log ids to use the colon form to match the renamed tool ids: replace logError('mdocument-chunker-embeddings', ...) with logError('mdocument:chunker-embeddings', ...), replace logError('libsql-chunker-embeddings', ...) with logError('libsql:chunker-embeddings', ...), and replace logStepEnd('libsql-chunker', ...) and logError('libsql-chunker', ...) with logStepEnd('libsql:chunker', ...) and logError('libsql:chunker', ...) respectively (search for calls to logError and logStepEnd to find and normalize all occurrences).src/mastra/agents/researchAgent.ts (1)
332-338:⚠️ Potential issue | 🟡 Minor
responseModalitiesconflict betweeninstructions.providerOptionsanddefaultOptions.providerOptions.
instructionsreturnsproviderOptions.google.responseModalities: ['TEXT'](Line 332) whiledefaultOptions.providerOptions.google.responseModalities: ['TEXT', 'IMAGE'](Line 406). Depending on how the agent merges these (the instruction-scoped provider options typically win for that turn), IMAGE modality may be silently dropped exactly when the agent is expected to emit/search images — which is the whole point of addinggoogleImagesToolin this PR.Either unify on
['TEXT', 'IMAGE']in both places, or intentionally document why generation should stay text-only while defaults advertise image support.Also applies to: 404-418
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/mastra/agents/researchAgent.ts` around lines 332 - 338, The provider options currently conflict: the instructions object sets providerOptions.google.responseModalities to ['TEXT'] while defaultOptions.providerOptions.google.responseModalities includes ['TEXT','IMAGE'], which can drop IMAGE when instruction-scoped options override defaults; update the instructions' providerOptions.google.responseModalities (in the instructions object used by the agent) to ['TEXT','IMAGE'] to match defaultOptions (or, if intentional, add a clear comment near the instructions object explaining why it must remain text-only), and ensure googleImagesTool usage/registration in the agent code (googleImagesTool) is consistent with the chosen modalities.src/mastra/tools/serpapi-news-trends.tool.ts (1)
560-567: 🧹 Nitpick | 🔵 TrivialStray indentation on
positionline.Line 563 is over-indented relative to the surrounding mapped object properties, which will fail Prettier/ESLint formatting checks and muddies the diff. Align it with the other keys.
🧹 Formatting
? parsed.data.news_results.map((article) => ({ - position: article.position, + position: article.position, title: article.title, link: article.link, source: article.source?.name ?? 'Unknown', }))As per coding guidelines: "Use a code formatter like Prettier to automatically format code on save".
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/mastra/tools/serpapi-news-trends.tool.ts` around lines 560 - 567, The mapped object inside the newsArticles assignment has a stray over-indented key: align article.position with the other properties (title, link, source) to fix formatting; update the mapping in the parsed.data.news_results.map callback (the anonymous arrow function that builds the object) so position, title, link, and source are consistently indented, then run Prettier/ESLint or save to ensure formatting rules pass.src/mastra/tools/index.ts (1)
48-89: 🧹 Nitpick | 🔵 TrivialRedundant re-exports duplicate the
export *block above.Every symbol on lines 54–89 (e.g.,
writeNoteTool,confirmationTool,colorChangeTool,mdocumentChunker,googleSearchTool,amazonSearchTool,technicalAnalysisTool, etc.) is already re-exported via theexport * from './…'lines at 1–46. Maintaining both lists means a future rename/removal in a source module will silently drop only the wildcard binding while leaving the explicit one dangling (TS error) or vice-versa.Pick one strategy — preferably keep only the
export *wildcard block and delete the explicit named re-exports, unless the goal is to curate the public surface (in which case remove the wildcards for those modules).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/mastra/tools/index.ts` around lines 48 - 89, The file contains redundant explicit re-exports that duplicate the earlier export * wildcards; choose one approach—preferably keep the export * blocks and remove the explicit named re-exports—so delete the explicit export statements for symbols such as writeNoteTool, confirmationTool, colorChangeTool, mdocumentChunker, libsqlChunker, documentRerankerTool, mastraChunker, editorTool, readPDF, calculatorTool, unitConverterTool, matrixCalculatorTool, dateTimeTool, timeZoneTool, gitStatusTool, gitDiffTool, gitCommitTool, gitLogTool, randomGeneratorTool, textAnalysisTool, textProcessingTool, urlValidationTool, urlManipulationTool, jsonToCsvTool, googleSearchTool, googleAiOverviewTool, googleTrendsTool, googleAutocompleteTool, googleScholarTool, googleFinanceTool, yelpSearchTool, googleImagesTool, googleLocalTool, googleMapsReviewsTool, amazonSearchTool, walmartSearchTool, ebaySearchTool, homeDepotSearchTool, spatialIndexTool, technicalAnalysisTool, binanceSpotMarketDataTool, coinbaseExchangeMarketDataTool, stooqStockQuotesTool, and yahooFinanceStockQuotesTool; alternatively, if you intend a curated public surface, remove the wildcard export * lines instead—then run the TypeScript build/tests to verify no dangling or missing exports remain.src/mastra/tools/technical-analysis.tool.ts (1)
386-410:⚠️ Potential issue | 🟠 MajorChikou span computation likely incorrect.
For Ichimoku, the Chikou Span is the current close plotted
displacementperiods backward (so at bart, chikouSpan = close[t] displayed against the price at t-displacement). The new code sets:chikouSpan: inputData.close[startIndex + index] ?? …With
startIndex = close.length - rawResults.length, this aligns the chikou value to each result's index in the present (the close at that bar) — i.e., you're effectively returning the close price of the same bar, not a displaced value. This loses the displacement semantics entirely and the fallback toresult.basefurther muddies interpretation.The
technicalindicatorslibrary'sIchimokuCloud.calculatedoes not emit achikoufield directly; the correct standalone computation is typicallyclose[i + displacement](future-looking in the source array) or, when plotting, shifting the close series backward bydisplacement. Please confirm the intended semantic and either reference a source (library/test fixture) or add a comment with the rationale.#!/bin/bash # Check library signature and any upstream tests that pinned expected chikou values rg -nP --type=ts -C5 'IchimokuCloud\.calculate|chikou' -g '!**/node_modules/**' rg -nP -C3 '\bchikou' -g '**/*.test.*' -g '**/*.spec.*'As per coding guidelines: "Comment non-obvious algorithms to explain the algorithm choice and why it was selected for the problem."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/mastra/tools/technical-analysis.tool.ts` around lines 386 - 410, The chikouSpan is computed incorrectly: instead of using inputData.close[startIndex + index] you should use the close value displaced by displacement (targetIdx = startIndex + index + displacement) so chikouSpan = inputData.close[targetIdx] when present (otherwise null/undefined), and remove the fallback to result.base; update the mapping in results (the map over rawResults that sets tenkanSen/kijunSen/.. and chikouSpan) to compute targetIdx and use that value, and add a short comment near the IchimokuCloud.calculate usage explaining that technicalindicators does not provide chikou and we compute it as close[t + displacement] to represent the close plotted displacement periods backward.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@free-models.md`:
- Around line 7-8: Remove the entire offending curl example that posts '{"name":
"DingDong", "description": "I play ping pong with my ding dong, ching chung!"}'
from the "Available Free Models" section; instead, if you must document agent
registration, move a neutral, professional example into an appropriate "Agent
Registration" section, replace the name/description with non-offensive sample
data (e.g., "name": "example-agent", "description": "Example agent for
demonstration"), and wrap the command in a proper fenced code block with a
language identifier (```bash) for syntax highlighting.
In `@memory-bank/progress.md`:
- Around line 534-537: The file memory-bank/progress.md is missing the required
YAML front matter and contains H1 headings; add the required YAML front matter
block at the top with the mandatory metadata fields (title, description, date,
etc.) per the markdown contract and remove or convert any top-level H1 headings
to lower-level headings (H2/H3) so the document follows the rule "Do not use H1
headings"; ensure the new "Recent completion" entry is appended only after the
front matter and that the file structure matches other files in the repository
(no leading H1, proper front matter keys).
In `@src/mastra/agents/knowledgeIndexingAgent.ts`:
- Line 75: The template literal contains a typo: `{$LIBSQL_PROMPT}` is used
literally instead of interpolating the imported constant; replace the literal
with proper JS template interpolation `${LIBSQL_PROMPT}` where the prompt is
injected (look for the template string surrounding `{$LIBSQL_PROMPT}` in the
code that builds the prompt inside knowledgeIndexingAgent.ts and update it to
use `${LIBSQL_PROMPT}` so the imported LIBSQL_PROMPT value is actually
included).
In `@src/mastra/agents/noteTakerAgent.ts`:
- Line 22: Remove the commented-out configuration lines in noteTakerAgent.ts
(e.g., the "voice: new GoogleVoice()," entry and any commented "tools: []"
lines) and replace them with a TODO or issue reference if voice/tools support is
planned; also remove the now-unused GoogleVoice import so there are no dead
imports left (search for GoogleVoice, the voice property and tools array in the
file to locate the spots to edit).
In `@src/mastra/agents/researchAgent.ts`:
- Line 275: The multi-import entry in the researchAgentTools array packs
amazonSearchTool, walmartSearchTool, ebaySearchTool, homeDepotSearchTool into
one line which reduces readability; update the researchAgentTools definition so
that each of those tool symbols (amazonSearchTool, walmartSearchTool,
ebaySearchTool, homeDepotSearchTool) appears on its own line consistent with the
surrounding entries to improve diffs and auditing.
- Around line 404-418: The Google provider options block uses an invalid
top-level field "threshold: 'OFF'" which is not part of
GoogleLanguageModelOptions; remove that field from providerOptions.google and
instead add a properly-formed safetySettings array inside providerOptions.google
with explicit category mappings and desired thresholds (e.g., safetySettings:
[{category: 'DANGEROUS', threshold: 'ALLOW' }, ...]) so safety configuration is
applied correctly; update the providerOptions.google object (the block with
responseModalities/thinkingConfig/mediaResolution) to replace the invalid
threshold property with a correctly typed safetySettings array per the
GoogleLanguageModelOptions schema.
In `@src/mastra/agents/supervisor-agent.ts`:
- Line 369: Remove the dead commented configuration and its unused import:
delete the commented-out "voice: new GoogleVoice()" line and the matching
"import { GoogleVoice } from '@mastra/voice-google'" import, and run a quick
search for any other references to GoogleVoice to ensure no remaining usages
break compilation (update imports/exports if needed in the surrounding class or
function that referenced the voice configuration).
In `@src/mastra/agents/weather-agent.ts`:
- Line 6: Remove the unused import mainWorkspace from the top of
weather-agent.ts: keep only agentFsWorkspace in the import from '../workspaces'
since mainWorkspace is never referenced (e.g., only agentFsWorkspace is used
later around the code that interacts with the filesystem). Update the import
statement to import just agentFsWorkspace to eliminate the unused symbol and any
linter warnings.
In `@src/mastra/config/libsql.ts`:
- Line 50: Replace the three bare fastembed uses with the 768-dim model constant
to match the LibSQL index: change embedder: fastembed (in the Memory config) and
the model: fastembed occurrences inside createGraphRAGTool and
createVectorQueryTool to use LIBSQL_EMBEDDING_MODEL (which should equal
fastembed.base), and remove the now-dead standalone LIBSQL_EMBEDDING_MODEL
definition or alternatively inline fastembed.base at those three call sites so
the embedding model and the index dimension (LIBSQL_EMBEDDING_DIMENSION) remain
consistent.
In `@src/mastra/index.ts`:
- Around line 360-363: The tts configuration block in the Mastra initializer is
empty and should be removed to avoid no-op noise or accidental override of
defaults; delete the entire tts: { ... } object from the Mastra options and also
remove the unused GoogleVoice import (referenced as GoogleVoice) that was added
around line ~192; if you intended to enable TTS instead, replace the empty block
with a real provider entry (e.g., google: new GoogleVoice()) rather than leaving
it commented out.
- Line 193: Remove the unused dev-only import "import main from
'@/lib/auth-dev'" (the identifier main and its import) from the file; delete
that import line, ensure there are no other references to main in the module,
and run the linter/type-checker to confirm no unused-import errors remain.
In `@src/mastra/mcp/resources.ts`:
- Around line 31-38: Remove the locally defined ErrnoException interface and
change the type guard signature for isNodeErrorWithCode to use the built-in
NodeJS.ErrnoException (i.e., function isNodeErrorWithCode(error: unknown): error
is NodeJS.ErrnoException). Delete the duplicate interface block and update any
references to ErrnoException in this file to NodeJS.ErrnoException so the code
uses the `@types/node` provided type instead of a local duplicate.
In `@src/mastra/public/workspace/fpv-drone.md`:
- Line 1: Replace the top-level H1 heading "# FPV Drone" with an H2 by changing
it to "## FPV Drone"; update any other headings in this file that incorrectly
use H1 so the document uses H2/H3 etc. per repo markdown conventions (look for
the heading text "FPV Drone" and any leading "#" markers to adjust).
- Line 1: The file currently lacks YAML front matter; add a YAML block at the
very top of src/mastra/public/workspace/fpv-drone.md before the "FPV Drone"
title containing the required metadata fields: post_title, author1, post_slug,
microsoft_alias, featured_image, categories (choose from /categories.txt), tags,
ai_note, summary, and post_date; ensure values are filled appropriately
(post_title should match "FPV Drone", post_slug is a URL-friendly slug,
post_date is ISO format) so the renderer can parse the document correctly.
- Around line 5-11: The listed markdown bullet items (e.g., the long lines
starting with "SoloGood F722 FPV Flight Controller Stack ICM42688P F722..." and
the other product lines like "AKK FX2-ultimate 5.8GHz VTX with MMCX Antenna..."
through "Racing Cam Analog 1800TVL FPV Camera with OSD...") exceed 80
characters; soft-wrap each bullet at ~80 characters preserving words and
markdown hyphen bullets so each logical item remains a single list entry but
uses line breaks to keep lines <=80 characters for readability.
In `@src/mastra/tools/binance-crypto-market.tool.ts`:
- Line 4: The import currently brings InferToolInput and InferToolOutput as
runtime imports; change the import to use type-only imports for the type symbols
(e.g., use "import type { InferToolInput, InferToolOutput }" while keeping
createTool and InferUITool as regular imports) so InferToolInput and
InferToolOutput are erased at runtime and match the other tools; update the
import line that references createTool, InferToolInput, InferToolOutput, and
InferUITool accordingly.
In `@src/mastra/tools/coinbase-exchange-crypto.tool.ts`:
- Around line 338-341: The file exposes two confusingly similar public types:
CoinbaseExchangeMarketDataInput (alias to CoinbaseInput) and
CoinbaseExchangeMarketDataToolInput (InferToolInput<typeof
coinbaseExchangeMarketDataTool>); remove the legacy alias
CoinbaseExchangeMarketDataInput and export only the canonical
InferToolInput/InferToolOutput names (CoinbaseExchangeMarketDataToolInput and
CoinbaseExchangeMarketDataToolOutput) or vice‑versa so there’s a single public
Input/Output per tool; update any local imports/usages that referenced
CoinbaseExchangeMarketDataInput to use CoinbaseExchangeMarketDataToolInput, and
keep coinbaseExchangeMarketDataTool as the source of truth for the InferTool
types.
In `@src/mastra/tools/document-chunking.tool.ts`:
- Line 94: The schema declares embeddingModel as z.string() but its default uses
the EmbeddingModel object fastembed.base (used elsewhere with embedMany({ model:
fastembed.base })), causing serialization/type errors and passing an invalid
string into ModelRouterEmbeddingModel; change the schema default and any
fallback values to a string identifier (e.g., 'fastembed/base' or the actual
model ID expected by ModelRouterEmbeddingModel) or refactor embedding-related
code so embeddingModel accepts the EmbeddingModel instance consistently; also
stop creating new AbortController().signal in places that build requests
(currently using new AbortController().signal at the call sites) and instead
pass through the existing abortSignal from the parent context to preserve
cancellation propagation.
In `@src/mastra/tools/serpapi-images.tool.ts`:
- Around line 161-326: The tool is missing the onInputStart and onInputDelta
lifecycle hooks, doesn't check/handle abortSignal during execute, and the tool
call span metadata lacks user.id/workspace.id; add onInputStart and onInputDelta
handlers that mirror onInputAvailable's structured logging (include toolCallId,
input partials, messageCount, aborted and hook name), and update the
getOrCreateSpan call (variable imagesSpan) to include 'user.id' and
'workspace.id' in metadata; in execute, read context?.abortSignal early, throw
immediately if aborted, and pass the signal to the network call (getJson) if
supported or wrap the call so that if abortSignal.aborted you call
imagesSpan?.error({ error: new Error('aborted'), endSpan: true }) and throw a
cancellation Error to fail fast and avoid wasting quota.
- Around line 98-100: The SerpAPI engine and output schema are mismatched: the
tool sets engine: 'google_images' but the output schema expects inlineImages and
knowledgeGraph which only exist on the 'google' engine. Fix by either (A) change
the engine string to 'google' where engine is set (so inlineImages.source as
z.url() and knowledgeGraph schemas match the 'google' response), or (B) if you
must keep 'google_images', remove/replace inlineImages and knowledgeGraph from
the output schema and instead parse images_results (with source and source_logo)
to match the google_images response; update parsing logic that consumes
inlineImages/knowledgeGraph accordingly.
In `@src/mastra/tools/serpapi-local-maps.tool.ts`:
- Around line 502-518: The googleCid field is incorrectly set to place_id in the
local results normalizer(s) (see the localResults mapping and the other similar
mapper later), causing duplication with placeId and losing the true CID; change
the assignment so googleCid = result.data_cid (and similarly in the other
normalizer that builds localResults) so the CID comes from data_cid while
placeId remains result.place_id.
- Around line 422-428: The new tools googleLocalTool and googleMapsReviewsTool
are missing the required lifecycle hooks; add onInputStart and onInputDelta to
each so all four hooks (onInputStart, onInputDelta, onInputAvailable, onOutput)
are implemented for streaming/observability parity, and ensure each hook uses
the Mastra logger for structured logs and is declared in the tool object ordered
before/after the execute property consistent with other tools; locate the tool
definitions by the symbols googleLocalTool and googleMapsReviewsTool and mirror
the logging/handler patterns used elsewhere in src/mastra/tools to implement
these hooks.
- Around line 443-495: Before calling SerpAPI (getJson) and before post-response
normalization, check context?.abortSignal for cancellation and fail fast: if
context?.abortSignal?.aborted, call localSpan?.error(new Error('Tool call
cancelled by abortSignal')) and throw an AbortError (or a generic Error
named/typed "Aborted" to propagate cancellation) so the function returns
immediately and no network call or normalization runs; apply the same check in
the other execute path that performs normalization (the second branch around the
normalization logic) and ensure both places reference the same symbols: execute,
context?.abortSignal, localSpan, and getJson.
In `@src/mastra/tools/serpapi-news-trends.tool.ts`:
- Around line 970-977: The current averageInterest calculation only uses
item.values[0]?.extractedValue, which drops all but the first series; update the
logic around interestOverTime to compute the average across all series by
summing every values[].extractedValue (defaulting to 0 when missing) and
dividing by the total number of value entries (totalCount) to produce
averageInterest, or alternatively rename averageInterest to
firstSeriesAverageInterest and update the schema.describe to document it; modify
the code that computes averageInterest (referencing averageInterest,
interestOverTime, values, and extractedValue) to implement the chosen fix.
In `@src/mastra/tools/serpapi-shopping.tool.ts`:
- Around line 641-672: The code silently drops eBay items that lack both
product_id and item_id when building products (see ebayResponse.organic_results
-> flatMap and the itemId extraction), so add telemetry: count the dropped
entries during the flatMap, emit a log (log.warn or log.debug) with the number
dropped and sample context, and set the span/tool metadata key
tool.output.droppedCount (or span.setAttribute('tool.output.droppedCount',
droppedCount)) so callers can detect schema changes; keep the existing return
behavior but ensure products variable construction still uses the counted filter
and logging.
In `@src/mastra/tools/technical-analysis.tool.ts`:
- Around line 247-311: The hook logging helpers (getHookMessageCount,
logToolHookStart, logToolHookDelta, logToolHookAvailable, logToolHookOutput) use
abortSignal?.aborted ?? false but should use the shared resolver; import
resolveAbortSignal from ./abort-signal.utils and replace all occurrences of
abortSignal?.aborted ?? false with resolveAbortSignal(abortSignal).aborted so
the helpers align with the PR's standardized abort-signal handling.
In `@src/mastra/workspaces.ts`:
- Line 105: workspaceSkillPaths was changed but other places still hard-code
different skill path lists, causing inconsistent resolution; update usages so
workspaceSkillPaths is the single source of truth: replace the hard-coded arrays
in mainWorkspace.skills and mainWorkspace.autoIndexPaths with references to
workspaceSkillPaths, and adjust
agentFsWorkspace.sandbox.nativeSandbox.readWritePaths to derive its whitelist
from workspaceSkillPaths (plus any intentional extras like '/' or
'.agents/skills' if required) so all three (workspaceSkillPaths,
mainWorkspace.skills, mainWorkspace.autoIndexPaths, and
agentFsWorkspace.sandbox.nativeSandbox.readWritePaths) are consistent and DRY.
- Line 4: Remove the commented-out imports and dead code fragments (e.g., the
commented identifiers "LSPServerDef", "createFilesystem",
"VersionedSkillSource", and "SandboxContent") from the file so only active
imports and code remain; simply delete those commented lines rather than leaving
them in place, then run a quick compile/TS check to ensure no missing references
and rely on VCS history for recovery if needed.
- Around line 93-99: The S3Filesystem instance (s3filesystem) currently contains
hardcoded credentials and config; update it to read bucket, region, endpoint,
accessKeyId and secretAccessKey from environment variables (e.g.,
process.env.S3_BUCKET, S3_REGION, S3_ENDPOINT, S3_ACCESS_KEY_ID,
S3_SECRET_ACCESS_KEY) instead of literals and construct the S3Filesystem with
those values; add a fail-fast check at module load (but skip in test env) that
throws a clear error if any required env var is missing so deployments don’t
silently use defaults; keep the symbol name s3filesystem and the S3Filesystem
constructor usage but replace literal values with the env-driven variables and
validation.
- Around line 357-370: This block creates a top-level await side-effect by
spawning typescript-language-server and calling connection.listen() with dead
bindings (handle, connection) and duplicates existing
spawnWorkspaceLspProcess(); remove the top-level spawn entirely and either (a)
delete this block, or (b) replace it with a lazy async entrypoint exported like
startTypescriptLsp that calls
spawnWorkspaceLspProcess('typescript-language-server --stdio', { cwd: '/', env:
{ ...process.env, NODE_ENV: 'development' }, timeout: 60_000 }) and returns the
handle/connection; ensure the spawn is wrapped in try/catch, connection.listen()
is called only after successful spawn, and provide a cleanup/stop method to kill
the process to avoid leaks.
In `@src/scripts/seed-agent.ts`:
- Around line 12-16: Update the model specification in the seeded agent: change
the model string value from 'gemini-3.0-flash-preview' to
'gemini-3.1-flash-lite-preview' (the model object containing provider/model/name
fields in seed-agent.ts, e.g., the model:{ provider:'google', model:...,
name:... } block) and update the corresponding name field to match
'google/gemini-3.1-flash-lite-preview' so both model and name use the 3.1
family; also remove the unused import symbol "google" from the top-level import
statement (import { google } from '@ai-sdk/google') to avoid an unused import.
In `@src/scripts/seed-prompts.ts`:
- Line 3: Replace the non-null assertion on mastra.getEditor() with an explicit
guard like in seed-agent.ts: call mastra.getEditor() and assign to the editor
variable, then if (!editor) throw new Error('Editor is not registered on
Mastra'); to surface a clear, actionable error instead of allowing a runtime
TypeError when later using editor.prompt or other methods; update the variable
usage that currently reads const editor = mastra.getEditor()! to follow this
pattern.
In `@src/scripts/update-agent.ts`:
- Around line 3-9: The code uses a non-null assertion on mastra.getEditor() and
a top-level await without error handling; change to first guard the editor by
calling mastra.getEditor() and throw or log a clear error if it returns
null/undefined, then wrap the asynchronous call to editor.agent.update({...}) in
a try..catch that logs a meaningful message (including the caught error) and
exits or returns appropriately; reference mastra.getEditor(), the local editor
variable, and editor.agent.update to locate the changes.
In `@src/scripts/update-prompts.ts`:
- Around line 5-8: The update replaces the seeded "brand-voice" prompt's
template variable with plain text, removing the runtime personalization hook and
likely breaking consumers expecting {{userName || "there"}}; restore the
original template form (use "Always address the user as {{userName ||
\"there\"}}." or confirm intentional removal) when calling
editor.prompt.update({ id: 'brand-voice', ... }) and ensure you keep the same
template syntax as in seed-prompts.ts; also wrap the top-level await in
update-prompts.ts (and similarly in update-agent.ts) with a try-catch and log or
handle errors so failures are reported instead of crashing silently.
---
Outside diff comments:
In `@free-models.md`:
- Line 1: The file is missing required YAML front matter; add a YAML block at
the very top of the file containing the keys post_title, author1, post_slug,
microsoft_alias, featured_image, categories, tags, ai_note, summary, and
post_date (populate bracketed placeholders with real values), ensuring the block
is formatted with leading and trailing --- and placed before any content in the
document so tools that read front matter (e.g., post_title and post_slug) can
parse it correctly.
- Around line 1-9: Change the heading hierarchy so there are no H4s: make "Free
Models" an H2 (## Free Models) and promote "Kilo Code" to an H2 (## Kilo Code)
or, alternatively, use "## Available Free Models" as the main H2 and make "Kilo
Code" an H3 (### Kilo Code); ensure headings "Free Models", "Available Free
Models", and "Kilo Code" are adjusted accordingly and remove any extra nesting
that would produce #### levels.
- Line 1: The top-level H1 heading "# Free Models" should be changed to an H2 by
replacing the leading "#" with "##" so the file uses "## Free Models" (follow
the guideline that H1s are generated from the title); update the single heading
token in the file accordingly.
In `@src/mastra/agents/researchAgent.ts`:
- Around line 332-338: The provider options currently conflict: the instructions
object sets providerOptions.google.responseModalities to ['TEXT'] while
defaultOptions.providerOptions.google.responseModalities includes
['TEXT','IMAGE'], which can drop IMAGE when instruction-scoped options override
defaults; update the instructions' providerOptions.google.responseModalities (in
the instructions object used by the agent) to ['TEXT','IMAGE'] to match
defaultOptions (or, if intentional, add a clear comment near the instructions
object explaining why it must remain text-only), and ensure googleImagesTool
usage/registration in the agent code (googleImagesTool) is consistent with the
chosen modalities.
In `@src/mastra/browsers.ts`:
- Around line 329-340: The browser constructors currently hardcode headless:
true which ignores runtime flags; change AgentBrowser and StagehandBrowser
instantiation to use the configured profile headless values instead of the
literal true (use agentBrowserProfile.headless for agentBrowser and
stagehandBrowserProfile.headless for stagehandBrowser) so the constructors
respect AGENT_BROWSER_HEADLESS / STAGEHAND_HEADLESS / BROWSER_HEADLESS fallbacks
already wired into those profiles.
In `@src/mastra/mcp/resources.ts`:
- Around line 31-45: Add TSDoc comments for the exported interface
ErrnoException and the type guard function isNodeErrorWithCode: document
ErrnoException's purpose (representing Node-style errors with optional
code/errno/syscall/path fields) and expected usage, and document
isNodeErrorWithCode's validation logic and predicate (explain it checks error is
non-null object and that .code exists and is a string, returning error is
ErrnoException). Also consider replacing the custom interface with the standard
NodeJS.ErrnoException and note that change in the TSDoc if you adopt it.
In `@src/mastra/tools/document-chunking.tool.ts`:
- Line 511: The log is currently passing the full AbortSignal returned by
resolveAbortSignal(abortSignal) instead of its boolean flag; update the object
key to use the `.aborted` property (e.g., aborted:
resolveAbortSignal(abortSignal).aborted) so the log stores a boolean, and also
normalize the other chunker tool that uses the key `abort` to `aborted` for
consistent field names across the chunkers; look for usages of
resolveAbortSignal, the log object containing `aborted`, and the inconsistent
`abort` key and change them accordingly.
- Around line 745-765: The embed batch loop is creating a fresh AbortController
for each embedMany call which ignores the caller's cancellation; replace the
inline new AbortController().signal with the passed-in context abort signal
(e.g., context.abortSignal or abortSignal variable used earlier) so embedMany
receives the real cancellation signal, and ensure you guard for undefined (only
pass the signal when available). Apply the same fix in libsqlChunker.execute
where embedMany is called (the duplicate at the other location) so both places
forward the caller's abort signal instead of creating a new one.
- Line 780: Update the remaining hyphenated metric/log ids to use the colon form
to match the renamed tool ids: replace logError('mdocument-chunker-embeddings',
...) with logError('mdocument:chunker-embeddings', ...), replace
logError('libsql-chunker-embeddings', ...) with
logError('libsql:chunker-embeddings', ...), and replace
logStepEnd('libsql-chunker', ...) and logError('libsql-chunker', ...) with
logStepEnd('libsql:chunker', ...) and logError('libsql:chunker', ...)
respectively (search for calls to logError and logStepEnd to find and normalize
all occurrences).
In `@src/mastra/tools/index.ts`:
- Around line 48-89: The file contains redundant explicit re-exports that
duplicate the earlier export * wildcards; choose one approach—preferably keep
the export * blocks and remove the explicit named re-exports—so delete the
explicit export statements for symbols such as writeNoteTool, confirmationTool,
colorChangeTool, mdocumentChunker, libsqlChunker, documentRerankerTool,
mastraChunker, editorTool, readPDF, calculatorTool, unitConverterTool,
matrixCalculatorTool, dateTimeTool, timeZoneTool, gitStatusTool, gitDiffTool,
gitCommitTool, gitLogTool, randomGeneratorTool, textAnalysisTool,
textProcessingTool, urlValidationTool, urlManipulationTool, jsonToCsvTool,
googleSearchTool, googleAiOverviewTool, googleTrendsTool,
googleAutocompleteTool, googleScholarTool, googleFinanceTool, yelpSearchTool,
googleImagesTool, googleLocalTool, googleMapsReviewsTool, amazonSearchTool,
walmartSearchTool, ebaySearchTool, homeDepotSearchTool, spatialIndexTool,
technicalAnalysisTool, binanceSpotMarketDataTool,
coinbaseExchangeMarketDataTool, stooqStockQuotesTool, and
yahooFinanceStockQuotesTool; alternatively, if you intend a curated public
surface, remove the wildcard export * lines instead—then run the TypeScript
build/tests to verify no dangling or missing exports remain.
In `@src/mastra/tools/serpapi-news-trends.tool.ts`:
- Around line 560-567: The mapped object inside the newsArticles assignment has
a stray over-indented key: align article.position with the other properties
(title, link, source) to fix formatting; update the mapping in the
parsed.data.news_results.map callback (the anonymous arrow function that builds
the object) so position, title, link, and source are consistently indented, then
run Prettier/ESLint or save to ensure formatting rules pass.
In `@src/mastra/tools/technical-analysis.tool.ts`:
- Around line 386-410: The chikouSpan is computed incorrectly: instead of using
inputData.close[startIndex + index] you should use the close value displaced by
displacement (targetIdx = startIndex + index + displacement) so chikouSpan =
inputData.close[targetIdx] when present (otherwise null/undefined), and remove
the fallback to result.base; update the mapping in results (the map over
rawResults that sets tenkanSen/kijunSen/.. and chikouSpan) to compute targetIdx
and use that value, and add a short comment near the IchimokuCloud.calculate
usage explaining that technicalindicators does not provide chikou and we compute
it as close[t + displacement] to represent the close plotted displacement
periods backward.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: 9a9e868e-5d6f-4050-ae4b-0e311f5f5bc5
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (43)
free-models.mdmemory-bank/activeContext.mdmemory-bank/progress.mdpackage.jsonsrc/cli/AGENTS.mdsrc/cli/index.tssrc/mastra/agents/knowledgeIndexingAgent.tssrc/mastra/agents/learningExtractionAgent.tssrc/mastra/agents/noteTakerAgent.tssrc/mastra/agents/package-publisher.tssrc/mastra/agents/projectManagementAgent.tssrc/mastra/agents/recharts.tssrc/mastra/agents/reportAgent.tssrc/mastra/agents/researchAgent.tssrc/mastra/agents/scriptWriterAgent.tssrc/mastra/agents/seoAgent.tssrc/mastra/agents/supervisor-agent.tssrc/mastra/agents/weather-agent.tssrc/mastra/agents/webResearchAgent.tssrc/mastra/browsers.tssrc/mastra/config/libsql.tssrc/mastra/index.tssrc/mastra/mcp/resources.tssrc/mastra/public/workspace/fpv-drone.mdsrc/mastra/tools/binance-crypto-market.tool.tssrc/mastra/tools/coinbase-exchange-crypto.tool.tssrc/mastra/tools/document-chunking.tool.tssrc/mastra/tools/fetch.tool.tssrc/mastra/tools/index.tssrc/mastra/tools/serpapi-academic-local.tool.tssrc/mastra/tools/serpapi-images.tool.tssrc/mastra/tools/serpapi-local-maps.tool.tssrc/mastra/tools/serpapi-news-trends.tool.tssrc/mastra/tools/serpapi-search.tool.tssrc/mastra/tools/serpapi-shopping.tool.tssrc/mastra/tools/stooq-stock-market-data.tool.tssrc/mastra/tools/technical-analysis.tool.tssrc/mastra/tools/yahoo-finance-stock.tool.tssrc/mastra/workspaces.tssrc/scripts/seed-agent.tssrc/scripts/seed-prompts.tssrc/scripts/update-agent.tssrc/scripts/update-prompts.ts
💤 Files with no reviewable changes (2)
- src/cli/AGENTS.md
- src/cli/index.ts
| curl -X POST https://www.moltbook.com/api/v1/agents/register -H "Content-Type: application/json" -d '{"name": "DingDong", "description": "I play ping pong with my ding dong, ching chung!"}' | ||
|
|
There was a problem hiding this comment.
Remove this curl command - it contains offensive language and is contextually inappropriate.
This content has multiple critical issues:
-
Offensive language: The description contains "ching chung," which is a racial slur. This is completely unacceptable in any codebase or documentation.
-
Context mismatch: This curl command registers an agent via API, but the section is titled "Available Free Models" and should list free models available for use. This content doesn't document any free model.
-
Missing code fence: Code snippets must use fenced code blocks with language identifiers. As per coding guidelines, use fenced code blocks (triple backticks) for code snippets and specify the language for syntax highlighting (e.g.,
```bash).
This content should be removed entirely. If agent registration needs to be documented, it should:
- Be placed in an appropriate section (not "Available Free Models")
- Use professional, respectful example data
- Be wrapped in proper fenced code blocks
As per coding guidelines: "Use fenced code blocks (triple backticks) for code snippets in markdown. Specify the language after the opening backticks for syntax highlighting."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@free-models.md` around lines 7 - 8, Remove the entire offending curl example
that posts '{"name": "DingDong", "description": "I play ping pong with my ding
dong, ching chung!"}' from the "Available Free Models" section; instead, if you
must document agent registration, move a neutral, professional example into an
appropriate "Agent Registration" section, replace the name/description with
non-offensive sample data (e.g., "name": "example-agent", "description":
"Example agent for demonstration"), and wrap the command in a proper fenced code
block with a language identifier (```bash) for syntax highlighting.
| ## Recent completion | ||
| - Corrected the SerpAPI shopping tool contracts so Amazon uses the documented `k`/`s` params, Walmart uses `product_page_url` as a fallback link source, and eBay accepts `product_id` with a safe fallback to `item_id`. | ||
| - Expanded `src/mastra/tools/serpapi-news-trends.tool.ts` to more closely match SerpApi's documented Google News and Google Trends response sections, including richer nested schemas and additional fields per section. | ||
| - Removed the stray `mathjs` import from the news/trends module and revalidated both edited SerpApi tool files with targeted ESLint. |
There was a problem hiding this comment.
Bring this file onto the required markdown contract before appending more entries.
This update extends a markdown file that still lacks the required YAML front
matter and continues the H1-based structure used throughout the file, so the
doc-lint/publishing checks will keep failing even though this new section is
otherwise valid. As per coding guidelines, **/*.md: "Do not use H1 headings,
as these will be generated from the title" and "Include YAML front matter at
the beginning of markdown files with required metadata fields..."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@memory-bank/progress.md` around lines 534 - 537, The file
memory-bank/progress.md is missing the required YAML front matter and contains
H1 headings; add the required YAML front matter block at the top with the
mandatory metadata fields (title, description, date, etc.) per the markdown
contract and remove or convert any top-level H1 headings to lower-level headings
(H2/H3) so the document follows the rule "Do not use H1 headings"; ensure the
new "Recent completion" entry is appended only after the front matter and that
the file structure matches other files in the repository (no leading H1, proper
front matter keys).
|
|
||
| ## Rules | ||
| - **Tool Efficiency**: Do NOT use the same tool repetitively or back-to-back for the same query. | ||
| {$LIBSQL_PROMPT} |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Confirm LIBSQL_PROMPT is a named export of `@mastra/libsql` and check for similar typos elsewhere.
fd -t f 'package.json' node_modules/@mastra/libsql | head -5 | xargs -I {} sh -c 'echo "--- {} ---"; cat {}' 2>/dev/null
rg -nP '\bLIBSQL_PROMPT\b' -C2
rg -nP '\{\$[A-Z_]+\}' --type=tsRepository: ssdeanx/AgentStack
Length of output: 1157
🏁 Script executed:
# Read the file context around line 75 to confirm template literal
cat -n src/mastra/agents/knowledgeIndexingAgent.ts | sed -n '45,80p'Repository: ssdeanx/AgentStack
Length of output: 1704
🏁 Script executed:
# Check if LIBSQL_PROMPT is exported from `@mastra/libsql` - search for it in the repo or check imports
rg 'LIBSQL_PROMPT' -A 2 -B 2Repository: ssdeanx/AgentStack
Length of output: 931
🏁 Script executed:
# Look for similar typo patterns {$ instead of ${ in TypeScript files
rg -t ts '\{\$[A-Z_]+\}' --no-headingRepository: ssdeanx/AgentStack
Length of output: 122
Template interpolation typo — LIBSQL_PROMPT is never injected.
Line 75 contains {$LIBSQL_PROMPT} as a literal string inside a template literal. The correct syntax for template interpolation is ${LIBSQL_PROMPT}. Without the $ prefix, the agent sends the literal text {$LIBSQL_PROMPT} to the model instead of the imported LibSQL guidance, defeating the purpose of the import on line 12.
🐛 Proposed fix
-{$LIBSQL_PROMPT}
+${LIBSQL_PROMPT}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| {$LIBSQL_PROMPT} | |
| ${LIBSQL_PROMPT} |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/mastra/agents/knowledgeIndexingAgent.ts` at line 75, The template literal
contains a typo: `{$LIBSQL_PROMPT}` is used literally instead of interpolating
the imported constant; replace the literal with proper JS template interpolation
`${LIBSQL_PROMPT}` where the prompt is injected (look for the template string
surrounding `{$LIBSQL_PROMPT}` in the code that builds the prompt inside
knowledgeIndexingAgent.ts and update it to use `${LIBSQL_PROMPT}` so the
imported LIBSQL_PROMPT value is actually included).
| }, | ||
| }, | ||
| voice: new GoogleVoice(), // Add OpenAI voice provider with default configuration | ||
| //voice: new GoogleVoice(), // Add OpenAI voice provider with default configuration |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Remove commented-out code.
Per coding guidelines: "Never comment out code; remove it instead and use version control history if needed." If voice support is planned, track it as a TODO or issue rather than leaving a dead configuration line (and note lines 15 tools: [] are similarly commented-out in this file).
Proposed fix
- //voice: new GoogleVoice(), // Add OpenAI voice provider with default configurationAlso drop the now-unused import:
-import { GoogleVoice } from '@mastra/voice-google'📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| //voice: new GoogleVoice(), // Add OpenAI voice provider with default configuration |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/mastra/agents/noteTakerAgent.ts` at line 22, Remove the commented-out
configuration lines in noteTakerAgent.ts (e.g., the "voice: new GoogleVoice(),"
entry and any commented "tools: []" lines) and replace them with a TODO or issue
reference if voice/tools support is planned; also remove the now-unused
GoogleVoice import so there are no dead imports left (search for GoogleVoice,
the voice property and tools array in the file to locate the spots to edit).
| marketSummaryTool, | ||
| candlestickPatternTool, | ||
| technicalAnalysisTool, | ||
| amazonSearchTool, walmartSearchTool, ebaySearchTool, homeDepotSearchTool, |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Multi-import line hurts readability for a public tool set.
amazonSearchTool, walmartSearchTool, ebaySearchTool, homeDepotSearchTool, is packed into a single line while every other entry in researchAgentTools gets its own line. Keeping them one-per-line makes diffs clean and tool registration easy to audit/grep.
♻️ Proposed tweak
- amazonSearchTool, walmartSearchTool, ebaySearchTool, homeDepotSearchTool,
+ amazonSearchTool,
+ walmartSearchTool,
+ ebaySearchTool,
+ homeDepotSearchTool,📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| amazonSearchTool, walmartSearchTool, ebaySearchTool, homeDepotSearchTool, | |
| amazonSearchTool, | |
| walmartSearchTool, | |
| ebaySearchTool, | |
| homeDepotSearchTool, |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/mastra/agents/researchAgent.ts` at line 275, The multi-import entry in
the researchAgentTools array packs amazonSearchTool, walmartSearchTool,
ebaySearchTool, homeDepotSearchTool into one line which reduces readability;
update the researchAgentTools definition so that each of those tool symbols
(amazonSearchTool, walmartSearchTool, ebaySearchTool, homeDepotSearchTool)
appears on its own line consistent with the surrounding entries to improve diffs
and auditing.
| const handle = await mainSandbox.processes.spawn('typescript-language-server --stdio', { | ||
| cwd: '/', | ||
| env: { | ||
| ...process.env, | ||
| NODE_ENV: 'development', | ||
| }, | ||
| skills: workspaceSkillPaths, | ||
| bm25: true, | ||
| timeout: 60_000, | ||
| }) | ||
|
|
||
| export const localLspWorkspace = new Workspace({ | ||
| id: 'local-lsp-workspace', | ||
| name: 'LocalLspWorkspace', | ||
| filesystem: new LocalFilesystem(mainFilesystemOptions), | ||
| sandbox: new LocalSandbox(mainSandboxOptions), | ||
| lsp: workspaceLspConfig, | ||
| skills: workspaceSkillPaths, | ||
| bm25: true, | ||
| }) | ||
|
|
||
| export const localTypescriptLspWorkspace = new Workspace({ | ||
| id: 'local-typescript-lsp-workspace', | ||
| name: 'LocalTypescriptLspWorkspace', | ||
| filesystem: new LocalFilesystem(mainFilesystemOptions), | ||
| sandbox: new LocalSandbox(mainSandboxOptions), | ||
| lsp: localTypescriptOnlyLspConfig, | ||
| skills: workspaceSkillPaths, | ||
| bm25: true, | ||
| }) | ||
|
|
||
| export const localEslintLspWorkspace = new Workspace({ | ||
| id: 'local-eslint-lsp-workspace', | ||
| name: 'LocalEslintLspWorkspace', | ||
| filesystem: new LocalFilesystem(mainFilesystemOptions), | ||
| sandbox: new LocalSandbox(mainSandboxOptions), | ||
| lsp: localEslintOnlyLspConfig, | ||
| skills: workspaceSkillPaths, | ||
| bm25: true, | ||
| }) | ||
| const connection = createMessageConnection( | ||
| new StreamMessageReader(handle.reader), | ||
| new StreamMessageWriter(handle.writer), | ||
| ) | ||
| connection.listen() |
There was a problem hiding this comment.
Top-level await spawning a language server at module load — fragile and duplicative.
Two problems here:
- Module-load side effect. Spawning
typescript-language-server --stdioat import time means every environment that importsworkspaces.ts(tests, CI bundlers, CLI tools, Docker image builds without Node tooling) will fail or hang iftypescript-language-serverisn't installed/reachable. There is no try/catch, no cleanup on process exit, and the spawned process plus itsconnection.listen()leak for the lifetime of the Node process. Also,const handle/const connectionare both dead bindings — never exported or used. - Duplicates existing abstraction. Lines 272–288 already define
spawnWorkspaceLspProcess()which does exactly this (spawn +createWorkspaceLspConnection+ return streams). Either remove this block entirely or move it inside a lazy, awaited initializer that callers opt into — e.g.,export async function startTypescriptLsp() { return spawnWorkspaceLspProcess('typescript-language-server --stdio', { cwd: '/', env: { …process.env, NODE_ENV: 'development' }, timeout: 60_000 }) }.
🧹 Suggested replacement
-const handle = await mainSandbox.processes.spawn('typescript-language-server --stdio', {
- cwd: '/',
- env: {
- ...process.env,
- NODE_ENV: 'development',
- },
- timeout: 60_000,
-})
-
-const connection = createMessageConnection(
- new StreamMessageReader(handle.reader),
- new StreamMessageWriter(handle.writer),
-)
-connection.listen()
+export async function startTypescriptLsp() {
+ return spawnWorkspaceLspProcess('typescript-language-server --stdio', {
+ cwd: '/',
+ env: {
+ PATH: sandboxPathEnv,
+ NODE_ENV: sandboxNodeEnv ?? 'development',
+ },
+ timeout: 60_000,
+ })
+}As per coding guidelines: "Avoid code duplication (DRY principle)" and "Avoid blocking the main thread with long-running synchronous operations".
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/mastra/workspaces.ts` around lines 357 - 370, This block creates a
top-level await side-effect by spawning typescript-language-server and calling
connection.listen() with dead bindings (handle, connection) and duplicates
existing spawnWorkspaceLspProcess(); remove the top-level spawn entirely and
either (a) delete this block, or (b) replace it with a lazy async entrypoint
exported like startTypescriptLsp that calls
spawnWorkspaceLspProcess('typescript-language-server --stdio', { cwd: '/', env:
{ ...process.env, NODE_ENV: 'development' }, timeout: 60_000 }) and returns the
handle/connection; ensure the spawn is wrapped in try/catch, connection.listen()
is called only after successful spawn, and provide a cleanup/stop method to kill
the process to avoid leaks.
| model: { | ||
| provider: 'google', | ||
| model: 'gemini-3.0-flash-preview', | ||
| name: 'google/gemini-3.0-flash-preview', | ||
| }, |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check which gemini model identifiers are referenced across the repo for consistency.
rg -nP "gemini-3\.[01]-[a-z-]+(-preview)?" --type=tsRepository: ssdeanx/AgentStack
Length of output: 6839
Update gemini-3.0-flash-preview to gemini-3.1-flash-lite-preview for consistency with repository standards.
The codebase exclusively uses gemini-3.1-* models (e.g., gemini-3.1-flash-lite-preview, gemini-3.1-flash-preview, gemini-3.1-pro-preview). The gemini-3.0-flash-preview identifier in seed-agent.ts is unique and inconsistent; using an outdated or invalid model will cause failures when this stored agent is invoked. Update to match the standardized 3.1 family.
Also note: The import { google } from '@ai-sdk/google' on line 1 is unused and can be removed.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/scripts/seed-agent.ts` around lines 12 - 16, Update the model
specification in the seeded agent: change the model string value from
'gemini-3.0-flash-preview' to 'gemini-3.1-flash-lite-preview' (the model object
containing provider/model/name fields in seed-agent.ts, e.g., the model:{
provider:'google', model:..., name:... } block) and update the corresponding
name field to match 'google/gemini-3.1-flash-lite-preview' so both model and
name use the 3.1 family; also remove the unused import symbol "google" from the
top-level import statement (import { google } from '@ai-sdk/google') to avoid an
unused import.
| @@ -0,0 +1,11 @@ | |||
| import { mastra } from '../mastra' | |||
|
|
|||
| const editor = mastra.getEditor()! | |||
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Align editor-null handling with seed-agent.ts for a clearer failure mode.
mastra.getEditor()! silently coerces a missing editor into a runtime TypeError: Cannot read properties of undefined (reading 'prompt') at line 5. The sibling script src/scripts/seed-agent.ts uses an explicit guard (if (!editor) throw new Error('Editor is not registered on Mastra')) which produces an actionable error. Mirroring that here keeps the two seed scripts consistent and easier to diagnose.
🧹 Proposed change
-const editor = mastra.getEditor()!
+const editor = mastra.getEditor()
+if (!editor) throw new Error('Editor is not registered on Mastra')📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const editor = mastra.getEditor()! | |
| const editor = mastra.getEditor() | |
| if (!editor) throw new Error('Editor is not registered on Mastra') |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/scripts/seed-prompts.ts` at line 3, Replace the non-null assertion on
mastra.getEditor() with an explicit guard like in seed-agent.ts: call
mastra.getEditor() and assign to the editor variable, then if (!editor) throw
new Error('Editor is not registered on Mastra'); to surface a clear, actionable
error instead of allowing a runtime TypeError when later using editor.prompt or
other methods; update the variable usage that currently reads const editor =
mastra.getEditor()! to follow this pattern.
| const editor = mastra.getEditor()! | ||
|
|
||
| await editor.agent.update({ | ||
| id: 'support-agent', | ||
| instructions: | ||
| "You are a friendly support agent for Acme Inc. Always respond in the user's language.", | ||
| }) |
There was a problem hiding this comment.
Add error handling and guard against a missing editor.
The non-null assertion on mastra.getEditor()! will produce a cryptic TypeError if the editor isn't configured, and the unhandled top-level await means any failure in editor.agent.update(...) surfaces as an unhandled rejection with no actionable context. Per coding guidelines, "Implement proper error handling at appropriate levels with meaningful error messages" and "Use try...catch blocks for handling errors in asynchronous operations".
Proposed fix
-import { mastra } from '../mastra'
-
-const editor = mastra.getEditor()!
-
-await editor.agent.update({
- id: 'support-agent',
- instructions:
- "You are a friendly support agent for Acme Inc. Always respond in the user's language.",
-})
+import { mastra } from '../mastra'
+
+const editor = mastra.getEditor()
+if (!editor) {
+ throw new Error('Mastra editor is not configured; cannot update support-agent.')
+}
+
+try {
+ await editor.agent.update({
+ id: 'support-agent',
+ instructions:
+ "You are a friendly support agent for Acme Inc. Always respond in the user's language.",
+ })
+} catch (err) {
+ console.error('Failed to update support-agent:', err)
+ process.exitCode = 1
+ throw err
+}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const editor = mastra.getEditor()! | |
| await editor.agent.update({ | |
| id: 'support-agent', | |
| instructions: | |
| "You are a friendly support agent for Acme Inc. Always respond in the user's language.", | |
| }) | |
| import { mastra } from '../mastra' | |
| const editor = mastra.getEditor() | |
| if (!editor) { | |
| throw new Error('Mastra editor is not configured; cannot update support-agent.') | |
| } | |
| try { | |
| await editor.agent.update({ | |
| id: 'support-agent', | |
| instructions: | |
| "You are a friendly support agent for Acme Inc. Always respond in the user's language.", | |
| }) | |
| } catch (err) { | |
| console.error('Failed to update support-agent:', err) | |
| process.exitCode = 1 | |
| throw err | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/scripts/update-agent.ts` around lines 3 - 9, The code uses a non-null
assertion on mastra.getEditor() and a top-level await without error handling;
change to first guard the editor by calling mastra.getEditor() and throw or log
a clear error if it returns null/undefined, then wrap the asynchronous call to
editor.agent.update({...}) in a try..catch that logs a meaningful message
(including the caught error) and exits or returns appropriately; reference
mastra.getEditor(), the local editor variable, and editor.agent.update to locate
the changes.
| await editor.prompt.update({ | ||
| id: 'brand-voice', | ||
| content: 'You write in a friendly, concise tone. Always greet the user by name when available.', | ||
| }) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -nP --type=ts -C2 '\{\{\s*userName'
rg -nP --type=ts -C2 "'brand-voice'|\"brand-voice\""Repository: ssdeanx/AgentStack
Length of output: 943
🏁 Script executed:
#!/bin/bash
# Find usages of brand-voice prompt to understand if consumers depend on template interpolation
rg -nP --type=ts 'brand-voice' -A 3 -B 3
# Check if there are any prompt rendering/evaluation functions that process templates
rg -nP --type=ts '\{\{' -l | head -20
# Look at the update-prompts.ts and update-agent.ts for error handling
echo "=== update-prompts.ts context ===" && rg -nP --type=ts -B 5 'await editor.prompt.update' src/scripts/update-prompts.ts
echo "=== update-agent.ts context ===" && fd -t f 'update-agent.ts' -x cat -n {}Repository: ssdeanx/AgentStack
Length of output: 1955
🏁 Script executed:
#!/bin/bash
# Search for where brand-voice prompt is consumed
rg -nP --type=ts 'prompt\s*\(' -A 5 -B 5 | grep -A 5 -B 5 'brand-voice'
# Look for any prompt usage/retrieval patterns
rg -nP --type=ts 'getPrompt|prompt\.get|prompt\s*:' -C 3
# Check if there's any template rendering logic
rg -nP --type=ts 'userName|template|render|interpolate' -C 2
# Search in the entire codebase for brand-voice references
fd -t f \( -name '*.ts' -o -name '*.tsx' -o -name '*.js' -o -name '*.json' \) -x rg -l 'brand-voice'Repository: ssdeanx/AgentStack
Length of output: 49976
🏁 Script executed:
#!/bin/bash
# Search for where prompts are actually used/consumed
rg -nP --type=ts 'prompt\.create|prompt\.update|\.prompt|instructions' -A 5 | grep -C 3 'brand-voice'
# Look for where brand-voice might be referenced as a string ID
rg -nP --type=ts 'instructions.*=' -C 2 | head -50
# Check if there's any template variable processing/rendering
rg -nP --type=ts '\{\{.*\}\}' -B 2 -A 2 | grep -C 3 'render\|interpolate\|process'
# List all files that reference brand-voice
fd -t f -x rg -l 'brand-voice' {}Repository: ssdeanx/AgentStack
Length of output: 5087
🏁 Script executed:
#!/bin/bash
# Search for any code that retrieves or uses prompts by ID
rg -nP --type=ts 'prompt\.get|getPrompt|prompts\[|prompts\.find'
# Look for any agent tool definitions or tool references
rg -nP --type=ts 'tools\s*:|tools\s*=' -A 10 | head -80
# Check the full update-prompts.ts and update-agent.ts files
echo "=== Full update-prompts.ts ===" && cat src/scripts/update-prompts.ts
echo "" && echo "=== Full update-agent.ts ===" && cat src/scripts/update-agent.tsRepository: ssdeanx/AgentStack
Length of output: 5367
Remove template variable dropout from brand-voice prompt or confirm intentional simplification.
src/scripts/seed-prompts.ts seeds brand-voice with Always address the user as {{userName || "there"}}., but src/scripts/update-prompts.ts replaces it with plain text Always greet the user by name when available. This removes the runtime personalization hook. If external consumers or downstream logic rely on the template variable for rendering user names at invocation time, the model will lose access to that data. Please confirm this simplification is intentional; if not:
Suggested fix
- content: 'You write in a friendly, concise tone. Always greet the user by name when available.',
+ content:
+ 'You write in a friendly, concise tone. Always address the user as {{userName || "there"}}.',Additionally, both update-prompts.ts and update-agent.ts execute top-level awaits without error handling. Wrap with try-catch and log/handle failures appropriately.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| await editor.prompt.update({ | |
| id: 'brand-voice', | |
| content: 'You write in a friendly, concise tone. Always greet the user by name when available.', | |
| }) | |
| await editor.prompt.update({ | |
| id: 'brand-voice', | |
| content: | |
| 'You write in a friendly, concise tone. Always address the user as {{userName || "there"}}.', | |
| }) |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/scripts/update-prompts.ts` around lines 5 - 8, The update replaces the
seeded "brand-voice" prompt's template variable with plain text, removing the
runtime personalization hook and likely breaking consumers expecting {{userName
|| "there"}}; restore the original template form (use "Always address the user
as {{userName || \"there\"}}." or confirm intentional removal) when calling
editor.prompt.update({ id: 'brand-voice', ... }) and ensure you keep the same
template syntax as in seed-prompts.ts; also wrap the top-level await in
update-prompts.ts (and similarly in update-agent.ts) with a try-catch and log or
handle errors so failures are reported instead of crashing silently.
fpv-drone.mdto document FPV drone components and specifications.serpapi-images.tool.tsfor structured Google Images search results, including inline images and knowledge graph summaries.serpapi-local-maps.tool.tsfor Google Local search and Maps reviews extraction, facilitating business discovery and review analysis.seed-agent.tsto create a support agent with specific instructions and model configuration.seed-prompts.tsto establish brand voice guidelines for Acme Inc.update-agent.tsto modify the support agent's instructions for improved user interaction.update-prompts.tsto update brand voice content for better user engagement.