Skip to content

Conversation

@nnance
Copy link
Contributor

@nnance nnance commented May 23, 2025

Example deep research agent in TypeScript

Summary by CodeRabbit

  • New Features

    • Introduced a Node.js AI agent project with deep research, report authoring, orchestration, and web search agents.
    • Agents perform iterative web research, generate structured reports, and orchestrate multi-step workflows.
    • Integrated live web search and AI text generation capabilities with relevance evaluation.
    • Added robust input validation and structured data handling using TypeScript and Zod schemas.
    • Provided detailed system prompts and multi-agent collaboration for enhanced research accuracy.
  • Documentation

    • Added comprehensive README with setup, development, and deployment instructions.
    • Included detailed configuration and guideline files for agent development, SDK usage, and project structure.
  • Chores

    • Added configuration files for environment variables, code formatting, linting, TypeScript, and GitHub Actions CI/CD.
    • Provided example environment file and .gitignore for best practices.
    • Added project metadata and build scripts in package.json.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 23, 2025

Walkthrough

This update introduces a new Node.js project for AI agents under the "deep-research-js" directory. It includes configuration files, documentation, environment templates, and TypeScript source code for four agents—Orchestrator, Researcher, Author, and Web Search—along with shared schemas and prompts. The project is set up for development, deployment, and continuous integration.

Changes

File(s) Change Summary
.gitignore, .editorconfig, biome.json, tsconfig.json, .env.example, package.json Added project-level configuration: Git ignore rules, editor settings, Biome linter/formatter config, TypeScript config, example environment variables, and Node.js package manifest.
README.md Added a comprehensive README with setup, usage, development, deployment, and support instructions for the deep-research-js Agentuity project.
agentuity.yaml Introduced Agentuity project configuration defining metadata, development/deployment settings, bundler options, and agent declarations.
.github/workflows/agentuity.yaml Added GitHub Actions workflow for CI/CD, automating deployment on pushes to the main branch using Agentuity deploy action.
index.ts Added TypeScript entry script for the agent project, handling environment validation and invoking the Agentuity runner.
src/agents/orchestrator/index.ts Implemented an orchestration agent that coordinates research and report generation by invoking other agents and managing workflow logic.
src/agents/researcher/index.ts Added a deep research agent that performs recursive web-based research, query generation, and learning extraction using a language model and web-search agent.
src/agents/author/index.ts Added an authoring agent that generates structured markdown reports from research data using a language model and prompt templates.
src/agents/web-search/index.ts Implemented a web search agent that performs iterative searches via the Exa API, evaluates results using a language model, and accumulates relevant sources.
src/common/types.ts Introduced shared Zod schemas and TypeScript types for search results, research data, learning objects, and deep research requests.
src/common/prompts.ts Added a detailed system prompt constant for expert research assistant behavior, exported for use in agent prompts.
.cursor/rules/agent.mdc, .cursor/rules/agentuity.mdc, .cursor/rules/sdk.mdc Added markdown configuration and documentation files specifying agent development guidelines, Agentuity config file rules, and SDK API reference for consistent development practices.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant OrchestratorAgent
    participant ResearcherAgent
    participant WebSearchAgent
    participant AuthorAgent
    participant ExaAPI
    participant AnthropicModel

    User->>OrchestratorAgent: Submit research request
    OrchestratorAgent->>ResearcherAgent: Request deep research (query, depth, breadth)
    ResearcherAgent->>WebSearchAgent: Request web search (query)
    WebSearchAgent->>ExaAPI: Perform search
    ExaAPI-->>WebSearchAgent: Return search results
    WebSearchAgent->>AnthropicModel: Evaluate results
    AnthropicModel-->>WebSearchAgent: Evaluation feedback
    WebSearchAgent-->>ResearcherAgent: Return relevant results
    ResearcherAgent->>AnthropicModel: Generate learnings/follow-up
    AnthropicModel-->>ResearcherAgent: Learnings/questions
    ResearcherAgent-->>OrchestratorAgent: Return research data
    OrchestratorAgent->>AuthorAgent: Request report (research data)
    AuthorAgent->>AnthropicModel: Generate markdown report
    AnthropicModel-->>AuthorAgent: Report text
    AuthorAgent-->>OrchestratorAgent: Return report
    OrchestratorAgent-->>User: Return final report
Loading

Suggested reviewers

  • rblalock

Poem

In a warren of code, new agents awake,
With research and prompts, big leaps they take.
From search to report, they hop in a chain,
Gathering knowledge, again and again.
With configs and docs, the groundwork is laid—
A clever new system, by rabbits well-made!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 12

🧹 Nitpick comments (25)
agents/deep-research-js/.editorconfig (2)

11-11: Consider trimming trailing whitespace.
Enabling trim_trailing_whitespace = true helps prevent stray spaces in code reviews and diffs.


12-12: Insert final newline for POSIX compatibility.
Setting insert_final_newline = true ensures files end with a newline, avoiding linter or POSIX tool warnings.

agents/deep-research-js/src/common/prompts.ts (1)

1-12: Consider dynamic date evaluation and trimming indentation in the system prompt.
Currently, ${new Date().toISOString()} is resolved once at module load and leading spaces become part of the prompt. To ensure the timestamp is always current and avoid extra whitespace, wrap it in a function and trim the template literal:

-export const SYSTEM_PROMPT = `You are an expert researcher. Today is ${new Date().toISOString()}. Follow these instructions when responding:
-  - You may be asked to research subjects that is after your knowledge cutoff, assume the user is right when presented with news.
-  ...
-`;
+export function getSystemPrompt(): string {
+  return `You are an expert researcher. Today is ${new Date().toISOString()}. Follow these instructions when responding:
+  - You may be asked to research subjects that are beyond your knowledge cutoff; assume the user is correct.
+  ...
+`.trim();
+}
agents/deep-research-js/src/common/types.ts (1)

33-36: Add missing inferred types for completeness.
To enable full type-safe usage, export types for SearchResults and DeepResearch as well.

 export type Research = z.infer<typeof ResearchSchema>;
+export type SearchResults = z.infer<typeof SearchResultsSchema>;
+export type DeepResearch = z.infer<typeof DeepResearchSchema>;
agents/deep-research-js/.env.example (1)

1-3: Add inline documentation for environment variables.
Including comments in the example will guide users on what each key represents.

-AGENTUITY_SDK_KEY=##########
+# AGENTUITY_SDK_KEY: API key for authenticating with the Agentuity SDK
+AGENTUITY_SDK_KEY=##########
-AGENTUITY_PROJECT_KEY=##########
+# AGENTUITY_PROJECT_KEY: Project identifier used by the Agentuity platform
+AGENTUITY_PROJECT_KEY=##########
-EXA_API_KEY=#######
+# EXA_API_KEY: API key for the Exa web search service
+EXA_API_KEY=#######
agents/deep-research-js/.github/workflows/agentuity.yaml (3)

1-23: CI workflow looks good, but could benefit from some improvements

The GitHub Actions workflow is well-structured for deploying to the Agentuity platform.

Consider these improvements:

  1. Add a newline at the end of the file to satisfy linting rules
  2. Upgrade checkout action from v3 to v4 for consistency with your Node.js setup action
  3. Consider adding dependency caching to improve workflow performance
      - name: Deploy Agentuity Project
        uses: agentuity/deploy-action@v1
        with:
-          api_key: ${{ secrets.AGENTUITY_API_KEY }}
+          api_key: ${{ secrets.AGENTUITY_API_KEY }}
+
🧰 Tools
🪛 YAMLlint (1.37.1)

[error] 23-23: no new line character at the end of file

(new-line-at-end-of-file)


14-16: Consider upgrading the checkout action

      - name: Checkout
-        uses: actions/checkout@v3
+        uses: actions/checkout@v4

10-23: Add dependency caching for better performance

Consider adding dependency caching to improve the workflow performance:

  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Install NodeJS
        uses: actions/setup-node@v4
        with:
          node-version: '22.x'
+      - name: Cache dependencies
+        uses: actions/cache@v3
+        with:
+          path: '**/node_modules'
+          key: ${{ runner.os }}-modules-${{ hashFiles('**/package-lock.json') }}
+          restore-keys: |
+            ${{ runner.os }}-modules-
      - name: Deploy Agentuity Project
        uses: agentuity/deploy-action@v1
        with:
          api_key: ${{ secrets.AGENTUITY_API_KEY }}
🧰 Tools
🪛 YAMLlint (1.37.1)

[error] 23-23: no new line character at the end of file

(new-line-at-end-of-file)

agents/deep-research-js/package.json (1)

1-35: Package configuration looks good but lacks test implementation

The package.json is well-structured with appropriate dependencies and scripts for the project.

Consider these improvements:

  1. Fill in the "author" field with appropriate information
  2. Implement actual tests rather than using the placeholder script
  3. Consider pinning exact versions for production dependencies to ensure consistent builds
-  "author": "",
+  "author": "Your Name <your.email@example.com>",
-  "test": "echo \"Error: no test specified\" && exit 1"
+  "test": "node --test"
agents/deep-research-js/src/agents/author/index.ts (3)

1-5: Unused import detected

The AgentContext type is imported but not used in the function signature.

-import type { AgentRequest, AgentResponse, AgentContext } from '@agentuity/sdk';
+import type { AgentRequest, AgentResponse } from '@agentuity/sdk';

22-26: Consider making the model configurable

The specific model version "claude-3-5-sonnet-latest" is hardcoded, which reduces flexibility if you want to test with different models or if the model changes.

Consider making the model configurable either through environment variables or agent context:

+const MODEL = process.env.AUTHOR_MODEL || "claude-3-5-sonnet-latest";

const { text } = await generateText({
-  model: anthropic("claude-3-5-sonnet-latest"),
+  model: anthropic(MODEL),
  system: SYSTEM_PROMPT,
  prompt: AUTHOR_PROMPT(research),
});

7-17: Prompt formatting could be improved for clarity

The current template string has inconsistent indentation which may affect readability in the code.

Consider reformatting the prompt template for better readability:

-const AUTHOR_PROMPT = (
-	research: Research
-) => `Generate a report based on the following research data:\n\n 
-		${JSON.stringify(research, null, 2)}\n\n
-		Make sure to include the following sections:
-		- Summary
-		- Key Findings
-		- Recommendations
-		- Next Steps
-		- References
-		Write in markdown format.`;
+const AUTHOR_PROMPT = (research: Research) => `
+Generate a report based on the following research data:
+
+${JSON.stringify(research, null, 2)}
+
+Make sure to include the following sections:
+- Summary
+- Key Findings
+- Recommendations
+- Next Steps
+- References
+
+Write in markdown format.
+`;
agents/deep-research-js/README.md (2)

7-9: Use the official spelling “Node.js”

The correct trademark spelling is “Node.js” (lower-case “j” with a dot). Using “NodeJS” can look unpolished in public docs and may confuse style-checkers (see LanguageTool warning).

-# 🤖 NodeJS Agent Project
+# 🤖 Node.js Agent Project
🧰 Tools
🪛 LanguageTool

[uncategorized] ~7-~7: The official spelling of this programming framework is “Node.js”.
Context: ...ture

# 🤖 NodeJS Agent Project Welcome to your Agentuit...

(NODE_JS)


[uncategorized] ~9-~9: The official spelling of this programming framework is “Node.js”.
Context: ...gent Project Welcome to your Agentuity NodeJS Agent project! This README provides ess...

(NODE_JS)


61-66: Specify a language for fenced code blocks

markdownlint flags this block (MD040) because no language is declared. Adding bash (or none) improves syntax highlighting and lint compliance.

-```
+```bash
├── agents/             # Agent definitions and implementations
...
-```
+```
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

61-61: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)

agents/deep-research-js/src/agents/researcher/index.ts (1)

103-106: Overwriting instead of appending search queries

accumulatedResearch.queries = queries; replaces the previous array every recursion level. Similarly, the local variable queries is reused, shadowing the outer constant. This discards earlier queries and makes the research history incomplete.

-accumulatedResearch.queries = queries;
+accumulatedResearch.queries.push(...queries);

Also consider renaming the inner queries variable (e.g. completed) to avoid shadowing.

Also applies to: 118-119

agents/deep-research-js/index.ts (3)

3-14: Consider extracting environment validation into a helper function.

The environment validation logic could be extracted into a separate function to improve readability and maintainability. This would also make it easier to test this validation logic in isolation.

-if (!process.env.AGENTUITY_API_KEY && !process.env.AGENTUITY_SDK_KEY) {
-  console.error(
-    '\x1b[31m[ERROR] AGENTUITY_API_KEY or AGENTUITY_SDK_KEY is not set. This should have been set automatically by the Agentuity CLI or picked up from the .env file.\x1b[0m'
-  );
-  const cmd = process.env._ || '';
-  if (cmd.endsWith('node')) {
-    console.error(
-      '\x1b[31m[ERROR] Re-run the command with `node --env-file .env index.ts`\x1b[0m'
-    );
-  }
-  process.exit(1);
-}
+function validateEnvironment() {
+  if (!process.env.AGENTUITY_API_KEY && !process.env.AGENTUITY_SDK_KEY) {
+    console.error(
+      '\x1b[31m[ERROR] AGENTUITY_API_KEY or AGENTUITY_SDK_KEY is not set. This should have been set automatically by the Agentuity CLI or picked up from the .env file.\x1b[0m'
+    );
+    const cmd = process.env._ || '';
+    if (cmd.endsWith('node')) {
+      console.error(
+        '\x1b[31m[ERROR] Re-run the command with `node --env-file .env index.ts`\x1b[0m'
+      );
+    }
+    process.exit(1);
+  }
+  
+  if (!process.env.AGENTUITY_URL) {
+    console.warn(
+      '\x1b[31m[WARN] You are running this agent outside of the Agentuity environment. Any automatic Agentuity features will be disabled.\x1b[0m'
+    );
+    if (process.isBun) {
+      console.warn(
+        '\x1b[31m[WARN] Recommend running `agentuity dev` to run your project locally instead of bun run start.\x1b[0m'
+      );
+    } else {
+      console.warn(
+        '\x1b[31m[WARN] Recommend running `agentuity dev` to run your project locally instead of npm start.\x1b[0m'
+      );
+    }
+  }
+}
+
+validateEnvironment();

7-7: Consider using a more reliable method to detect the command.

Using process.env._ to detect the command might be unreliable across different environments. Consider using process.argv[0] or a more robust approach to detect the runtime environment.

-  const cmd = process.env._ || '';
+  const cmd = process.argv[0] || '';

31-39: Document the purpose of the boolean parameter for the runner function.

The first parameter to the runner function is a boolean true, but its purpose isn't clear from the code. Consider adding a comment or using a named parameter to clarify its meaning.

-runner(true, import.meta.dirname).catch((err) => {
+// The first parameter enables verbose logging
+runner(true, import.meta.dirname).catch((err) => {

Alternatively:

-runner(true, import.meta.dirname).catch((err) => {
+const enableVerboseLogging = true;
+runner(enableVerboseLogging, import.meta.dirname).catch((err) => {
agents/deep-research-js/agentuity.yaml (1)

8-15: Consider updating the version constraint.

The version constraint >=0.0.136 allows for potentially breaking changes in future versions. Consider using a more restrictive range to prevent unexpected breaking changes.

-version: '>=0.0.136'
+version: '>=0.0.136 <0.1.0'
agents/deep-research-js/.cursor/rules/sdk.mdc (2)

89-96: Consider adding specific examples for each best practice.

The best practices section would be more helpful with specific code examples for each recommendation, showing the proper implementation.

 ## Best Practices

 - Use TypeScript for better type safety and IDE support
+   ```typescript
+   // Example: Using TypeScript for type safety
+   import type { AgentRequest, AgentResponse, AgentContext } from '@agentuity/sdk';
+   
+   export default async function Agent(
+     req: AgentRequest,
+     resp: AgentResponse,
+     ctx: AgentContext
+   ) {
+     // Your agent code here
+   }
+   ```
 - Import types from `@agentuity/sdk`
 - Use structured error handling with try/catch blocks
+   ```typescript
+   // Example: Structured error handling
+   try {
+     const result = await someAsyncOperation();
+     return resp.json(result);
+   } catch (error) {
+     ctx.logger.error('Operation failed', error);
+     return resp.text(`Error: ${error.message}`, { status: 500 });
+   }
+   ```
 - Leverage the provided logger for consistent logging
+   ```typescript
+   // Example: Using the logger
+   ctx.logger.info('Operation started', { additionalContext: 'value' });
+   // ... operation code ...
+   ctx.logger.info('Operation completed successfully');
+   ```
 - Use the storage APIs for persisting data
+   ```typescript
+   // Example: Using KV storage
+   await ctx.kv.set('userPreferences', userId, preferences);
+   const storedPreferences = await ctx.kv.get('userPreferences', userId);
+   ```
 - Consider agent communication for complex workflows
+   ```typescript
+   // Example: Agent communication
+   const analyzerAgent = await ctx.getAgent({ name: 'analyzer' });
+   const analysisResult = await analyzerAgent.run({ data: { text: inputText } });
+   ```

25-38: Consider adding examples for AgentRequest methods.

Adding practical examples for each AgentRequest method would make the documentation more actionable and easier to understand.

 ### AgentRequest

 The `AgentRequest` interface provides methods for accessing request data:

 - `request.trigger`: Gets the trigger type of the request
+   ```typescript
+   // Example: Check if request was triggered by a webhook
+   if (request.trigger === 'webhook') {
+     // Handle webhook-specific logic
+   }
+   ```
 - `request.metadata(key, defaultValue)`: Gets metadata associated with the request
+   ```typescript
+   // Example: Get the source of the request
+   const source = request.metadata('source', 'unknown');
+   ```
 - `request.get(key, defaultValue)`: Gets the metadata value of the request
 - `request.data.contentType`: Gets the content type of the request payload
+   ```typescript
+   // Example: Check content type before processing
+   if (request.data.contentType.includes('application/json')) {
+     const jsonData = await request.data.json();
+   }
+   ```
 - `request.data.json(): Promise<Json>`: Gets the payload as a JSON object
 - `request.data.text(): Promise<string>`: Gets the payload as a string
 - `request.data.buffer(): Promise<ArrayBuffer>`: Gets the payload as a ArrayBuffer
 - `request.data.binary(): Promise<ArrayBuffer>`: Gets the payload as a ArrayBuffer
 - `request.data.object<T>: Promise<T>`: Gets the payload as a typed object
+   ```typescript
+   // Example: Parse payload as a typed object
+   interface QueryPayload {
+     query: string;
+     filters?: string[];
+   }
+   const payload = await request.data.object<QueryPayload>();
+   ```
agents/deep-research-js/.cursor/rules/agent.mdc (4)

9-14: Unify imperative phrasing and correct TypeScript casing. The list items mix “Prefer” and declarative statements, and “Typescript” should be capitalized as “TypeScript”. Consider refactoring the bullets for consistency and brevity:

- - Prefer using the `agentuity agent create` command to create a new Agent
- - Prefer loading types from the node modules package `@agentuity/sdk` in the node_modules folder
- - The file should export a default function
+ - Use `agentuity agent create` to scaffold a new agent under `**/src/agents/**/index.ts`.
+ - Load types from the `@agentuity/sdk` package.
+ - Export a default async function.
- - Prefer naming the default function Agent or the name of the Agent based on the context of the Agent description
+ - Name the default export `Agent` or another context-appropriate identifier.
- - All code should be in Typescript format
+ - All code must be in TypeScript.
- - Use the provided logger from the `AgentContext` interface such as `ctx.logger.info("my message: %s", "hello")`

26-29: Fix grammatical error in AgentRequest description. The sentence is awkward—replace with:

- The AgentRequest interface provides a set of helper methods and public variables which can be used for working with data has been passed to the Agent.
+ The `AgentRequest` interface provides helper methods and properties for working with data that has been passed to the agent.

30-33: Improve phrasing for response formats. Clarify supported formats:

- The AgentResponse interface provides a set of helper methods for responding with different data formats from the Agent.
+ The `AgentResponse` interface provides helper methods for returning data in various formats (JSON, text, streaming, etc.).

34-37: Clarify AgentContext description and ensure trailing newline. Consider updating to:

- The AgentContext has information specific to the incoming Agent request and a set of helper methods for accessing AI services like KeyValue storage and Vector storage.
+ The `AgentContext` provides request-specific metadata and helper methods for AI services (e.g., key-value stores and vector databases).
+

Also, ensure the file ends with a single newline.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7eb8007 and 9c6277c.

⛔ Files ignored due to path filters (1)
  • agents/deep-research-js/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (19)
  • agents/deep-research-js/.cursor/rules/agent.mdc (1 hunks)
  • agents/deep-research-js/.cursor/rules/agentuity.mdc (1 hunks)
  • agents/deep-research-js/.cursor/rules/sdk.mdc (1 hunks)
  • agents/deep-research-js/.editorconfig (1 hunks)
  • agents/deep-research-js/.env.example (1 hunks)
  • agents/deep-research-js/.github/workflows/agentuity.yaml (1 hunks)
  • agents/deep-research-js/.gitignore (1 hunks)
  • agents/deep-research-js/README.md (1 hunks)
  • agents/deep-research-js/agentuity.yaml (1 hunks)
  • agents/deep-research-js/biome.json (1 hunks)
  • agents/deep-research-js/index.ts (1 hunks)
  • agents/deep-research-js/package.json (1 hunks)
  • agents/deep-research-js/src/agents/author/index.ts (1 hunks)
  • agents/deep-research-js/src/agents/orchestrator/index.ts (1 hunks)
  • agents/deep-research-js/src/agents/researcher/index.ts (1 hunks)
  • agents/deep-research-js/src/agents/web-search/index.ts (1 hunks)
  • agents/deep-research-js/src/common/prompts.ts (1 hunks)
  • agents/deep-research-js/src/common/types.ts (1 hunks)
  • agents/deep-research-js/tsconfig.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
agents/deep-research-js/src/agents/web-search/index.ts (3)
agents/deep-research-js/src/common/types.ts (2)
  • SearchResultSchema (3-7)
  • SearchResult (33-33)
agents/deep-research-js/src/common/prompts.ts (1)
  • SYSTEM_PROMPT (1-12)
agents/deep-research-js/src/agents/researcher/index.ts (1)
  • Agent (131-151)
🪛 LanguageTool
agents/deep-research-js/README.md

[uncategorized] ~7-~7: The official spelling of this programming framework is “Node.js”.
Context: ...ture

# 🤖 NodeJS Agent Project Welcome to your Agentuit...

(NODE_JS)


[uncategorized] ~9-~9: The official spelling of this programming framework is “Node.js”.
Context: ...gent Project Welcome to your Agentuity NodeJS Agent project! This README provides ess...

(NODE_JS)

🪛 markdownlint-cli2 (0.17.2)
agents/deep-research-js/README.md

61-61: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)

🪛 YAMLlint (1.37.1)
agents/deep-research-js/.github/workflows/agentuity.yaml

[error] 23-23: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (18)
agents/deep-research-js/.editorconfig (2)

1-5: Well-structured EditorConfig header.
The root flag and the introductory comments align with best practices for a topmost .editorconfig.


7-8: Verify indentation consistency across configs.
You're using tabs with indent_size = 2; please ensure this matches the indentation settings in biome.json, Prettier, or any other formatter to avoid conflicting rules.

agents/deep-research-js/.gitignore (8)

1-2: Properly ignoring dependencies folder
Ignoring node_modules is essential for Node.js projects to avoid committing installed dependencies.


3-7: Ignoring build and package artifacts
Patterns out, dist, and *.tgz correctly exclude compiled output and package archives from version control.


8-11: Excluding code coverage reports
Ignoring coverage and *.lcov ensures coverage artifacts don’t clutter the repo.


17-23: Dotenv environment files are excluded
The various .env patterns correctly prevent environment-specific secrets from being committed.


24-28: Cache files are properly ignored
Entries for .eslintcache, .cache, and *.tsbuildinfo cover common tool cache files.


29-31: IDE-specific folder exclusion
Ignoring .idea ensures IntelliJ/JetBrains project settings aren’t tracked.


32-34: macOS metadata exclusion
.DS_Store is correctly ignored to avoid macOS folder metadata.


35-37: Ignoring Agentuity build artifacts
The .agentuity directory and crash reports are correctly excluded.

agents/deep-research-js/biome.json (1)

1-27: Biome configuration appears correct and comprehensive.
The settings align with the project’s .editorconfig, enforcing organized imports, linting, and formatting for JavaScript/TypeScript. No issues found.

agents/deep-research-js/.cursor/rules/agentuity.mdc (1)

1-10: Cursor rule metadata looks good.
The frontmatter correctly targets agentuity.yaml and enforces application. No edits needed.

agents/deep-research-js/tsconfig.json (1)

1-21: TypeScript configuration looks solid for modern development

The TypeScript configuration is well-structured for a modern Node.js project with appropriate strict type checking and ESNext targeting.

A few considerations:

  • noUnusedLocals and noUnusedParameters are disabled, which is common during early development but might be worth enabling later for code cleanliness
  • The configuration includes the DOM library which may be unnecessary for a pure Node.js project unless you're planning to use browser-specific APIs
agents/deep-research-js/agentuity.yaml (2)

64-79: LGTM! Agent configuration structure looks good.

The agent configuration is well structured with clear names and descriptions for each agent. The orchestrator, researcher, author, and web-search agents have unique IDs and descriptive names that match their functionality.


43-50:

Details

❓ Verification inconclusive

Consider adjusting resource allocations based on expected workload.

The current resource allocations (250Mi memory, 500M CPU, 100Mi disk) might be insufficient for deep research tasks, especially when dealing with large language models and multiple agents. Consider increasing these values based on expected workload.


🏁 Script executed:

#!/bin/bash
# Let's check if there are any hints about the expected resource usage in the documentation

echo "Checking for resource recommendations in README and documentation files..."
find . -type f -name "README.md" -o -name "*.md" | xargs grep -i "resource\|memory\|cpu\|disk" | grep -v "resources:"

Length of output: 274


No resource guidelines found—please benchmark and tune allocations

We didn’t find any existing recommendations in the docs for memory, CPU, or disk usage. The current defaults in agents/deep-research-js/agentuity.yaml (Lines 43–50: 250Mi memory, 500m CPU, 100Mi disk) may be insufficient for heavy LLM workloads or multi-agent coordination. Please:

  • Benchmark with representative deep-research tasks to determine actual resource needs
  • Update the values in agents/deep-research-js/agentuity.yaml accordingly
  • Document the agreed-upon resource requirements in your README or a dedicated guide
agents/deep-research-js/.cursor/rules/sdk.mdc (1)

15-23: LGTM! Clear documentation of the main handler function type.

The documentation for the AgentHandler type is clear and concise, showing the expected function signature and return type.

agents/deep-research-js/.cursor/rules/agent.mdc (2)

1-5: YAML front-matter is valid. The description, globs, and alwaysApply fields conform to the expected .cursor/rules format.


18-24: Example agent implementation aligns with guidelines. The snippet correctly imports types, exports a default async function, and returns a JSON response.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (2)
agents/deep-research-js/src/agents/orchestrator/index.ts (2)

25-25: Replace console.log with context logger for consistency.

The researcher tool still uses console.log while the author tool correctly uses ctx.logger. Use the context logger for consistent structured logging across all tools.

-			console.log("Starting research...");
+			ctx.logger.info("Starting research...");
-			console.log("Research completed!");
+			ctx.logger.info("Research completed!");

Also applies to: 34-34


14-15: 🛠️ Refactor suggestion

Add validation for depth and breadth parameters.

Consider adding validation to ensure depth and breadth values are within reasonable limits to prevent potential resource exhaustion or performance issues.

 	const depth = request.depth ?? 2;
 	const breadth = request.breadth ?? 3;
+
+	// Validate parameters to prevent excessive resource usage
+	if (depth > 5) {
+		ctx.logger.warn(`Depth value ${depth} exceeds recommended maximum. Limiting to 5.`);
+		depth = Math.min(depth, 5);
+	}
+	if (breadth > 10) {
+		ctx.logger.warn(`Breadth value ${breadth} exceeds recommended maximum. Limiting to 10.`);
+		breadth = Math.min(breadth, 10);
+	}
🧹 Nitpick comments (2)
agents/deep-research-js/src/agents/orchestrator/index.ts (2)

48-48: Remove misleading comment.

The comment suggests making a copy of the research object, but no copying operation is performed in the code below. This could confuse future maintainers.

-			// Make a copy of research with all properties defined

70-76: Improve error message formatting.

Using ${error} may not provide the most informative error message. Consider using error.message or error.stack for better debugging information.

 	} catch (error) {
 		ctx.logger.error("Error generating report", error);
-		return resp.text(`Failed to generate report: ${error}`, {
+		return resp.text(`Failed to generate report: ${error instanceof Error ? error.message : String(error)}`, {
 			status: 500,
 			statusText: "Report Generation Failed",
 		});
 	}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9c6277c and 490e3d1.

📒 Files selected for processing (5)
  • agents/deep-research-js/.gitignore (1 hunks)
  • agents/deep-research-js/src/agents/orchestrator/index.ts (1 hunks)
  • agents/deep-research-js/src/agents/researcher/index.ts (1 hunks)
  • agents/deep-research-js/src/agents/web-search/index.ts (1 hunks)
  • agents/deep-research-js/src/common/types.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • agents/deep-research-js/src/agents/researcher/index.ts
  • agents/deep-research-js/.gitignore
  • agents/deep-research-js/src/agents/web-search/index.ts
  • agents/deep-research-js/src/common/types.ts
🔇 Additional comments (2)
agents/deep-research-js/src/agents/orchestrator/index.ts (2)

22-24: Good implementation of consistent error handling.

Excellent work implementing the suggested error handling pattern using throw new Error() instead of returning response objects. This maintains consistency across tools and allows proper error propagation.

Also applies to: 44-46


57-77: Well-implemented error handling wrapper.

Great job adding the try-catch block around the generateText function call. This provides graceful error handling and proper logging as suggested in previous reviews.

nnance and others added 3 commits May 27, 2025 07:04
- Add project description and multi-agent architecture overview
- Document tech stack including Node.js, TypeScript, Vercel AI SDK, Claude 4, Exa API
- Include detailed getting started guide with environment setup
- Add API key configuration instructions for Agentuity and Exa
- Document project structure and development workflow
- Explain system operation from research request to report generation

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Update evaluateTool to return structured object with evaluation and pendingResult
- Remove finalSearchResults parameter from evaluateTool function signature
- Process generateText steps to extract relevant search results
- Destructure only steps from generateText result for efficiency
- Remove unnecessary message field from evaluation response

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
agents/deep-research-js/README.md (2)

1-6: Consider adding status badges to the header
Adding CI/build and package version badges improves visibility of the project’s health.

Proposed diff (insert above line 1):

+ <p align="center">
+   <a href="https://github.com/agentuity/examples/actions"><img src="https://github.com/agentuity/examples/workflows/CI/badge.svg" alt="CI status"/></a>
+   <a href="https://www.npmjs.com/package/deep-research-js"><img src="https://img.shields.io/npm/v/deep-research-js" alt="Package Version"/></a>
+ </p>

84-99: Add a concrete example for invoking the agent
To make “Testing the System” actionable, include a sample cURL or Agentuity CLI command showing how to submit the JSON payload to the orchestrator.

Example snippet:

curl -X POST https://<AGENTUITY_ENDPOINT>/orchestrator \
  -H "Authorization: Bearer $AGENTUITY_SDK_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "The impact of artificial intelligence on healthcare",
    "depth": 2,
    "breadth": 3
  }'
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 490e3d1 and 6e2ccca.

📒 Files selected for processing (5)
  • agents/deep-research-js/README.md (1 hunks)
  • agents/deep-research-js/src/agents/author/index.ts (1 hunks)
  • agents/deep-research-js/src/agents/orchestrator/index.ts (1 hunks)
  • agents/deep-research-js/src/agents/researcher/index.ts (1 hunks)
  • agents/deep-research-js/src/agents/web-search/index.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • agents/deep-research-js/src/agents/orchestrator/index.ts
  • agents/deep-research-js/src/agents/author/index.ts
  • agents/deep-research-js/src/agents/researcher/index.ts
  • agents/deep-research-js/src/agents/web-search/index.ts
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
agents/deep-research-js/README.md

110-110: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)

🔇 Additional comments (14)
agents/deep-research-js/README.md (14)

8-11: No changes needed.


12-20: No changes needed.


21-30: No changes needed.


31-37: No changes needed.


40-48: No changes needed.


49-54: No changes needed.


56-59: No changes needed.


60-65: No changes needed.


66-73: No changes needed.


74-82: No changes needed.


100-107: No changes needed.


126-143: Include test command if tests are available
Currently the Development Commands section omits a test step. If you have test suites, please add instructions (e.g., npm test).

Do you have automated tests in this project? If so, shall we include:

npm test

in this section?


145-154: No changes needed.


155-171: No changes needed.

Comment on lines +108 to +124
## 📁 Project Structure

```
├── src/
│ ├── agents/
│ │ ├── orchestrator/ # Main workflow coordinator
│ │ ├── researcher/ # Deep research logic
│ │ ├── web-search/ # Web search with evaluation
│ │ └── author/ # Report generation
│ └── common/
│ ├── types.ts # Shared TypeScript types
│ └── prompts.ts # System prompts
├── .env.example # Environment variables template
├── agentuity.yaml # Agentuity project configuration
├── package.json # Dependencies and scripts
└── biome.json # Code formatting configuration
```
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Correct the project structure listing and specify code-fence language
The README calls out .github/workflows/agentuity.yaml under Deployment but the project tree omits the .github directory. Also, the ASCII tree block lacks a fence language, triggering MD040.

Apply this diff:

- ```
+ ```text
  .
+ ├── .github/
+ │   └── workflows/
+ │       └── agentuity.yaml
  ├── src/
  │   ├── agents/
  │   │   ├── orchestrator/     # Main workflow coordinator
  │   │   ├── researcher/       # Deep research logic
  │   │   ├── web-search/       # Web search with evaluation
  │   │   └── author/           # Report generation
  │   └── common/
  │       ├── types.ts          # Shared TypeScript types
  │       └── prompts.ts        # System prompts
  ├── .env.example              # Environment variables template
  ├── agentuity.yaml           # Agentuity project configuration
  ├── package.json             # Dependencies and scripts
  └── biome.json              # Code formatting configuration

Ensure .github/workflows/agentuity.yaml is committed.

🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

110-110: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
In agents/deep-research-js/README.md around lines 108 to 124, update the project
structure listing to include the missing .github/workflows/agentuity.yaml path
as referenced elsewhere in the README. Also, add the language specifier "text"
to the code fence enclosing the ASCII tree to fix the markdown linting issue
MD040. Make sure the .github/workflows/agentuity.yaml file is present in the
repository.

@coderabbitai coderabbitai bot requested a review from rblalock June 3, 2025 13:34
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (4)
agents/deep-research-js/src/agents/orchestrator/index.ts (4)

15-15: Confirmed: The typo has been fixed.

The variable is now correctly named depth instead of the previously misspelled deepth.


22-22: Confirmed: Error handling has been improved.

Both agent retrieval checks now properly throw errors instead of returning response objects, which allows for consistent error handling by the outer try-catch block.

Also applies to: 44-45


24-27: Confirmed: Logging has been improved.

All logging now uses ctx.logger instead of console.log, providing better integration with the monitoring system and structured logging.

Also applies to: 36-38, 47-47, 51-51


56-66: Confirmed: Error handling has been added.

The main execution logic is now properly wrapped in a try-catch block with appropriate error logging and response handling.

🧹 Nitpick comments (2)
agents/deep-research-js/src/common/types.ts (1)

39-41: Consider adding inferred types for all schemas for consistency.

Currently only 3 out of 6 schemas have inferred types exported. For consistency and better developer experience, consider adding inferred types for the remaining schemas:

 export type SearchResult = z.infer<typeof SearchResultSchema>;
+export type SearchProcessParameters = z.infer<typeof SearchProcessParametersSchema>;
+export type SearchResults = z.infer<typeof SearchResultsSchema>;
 export type Learning = z.infer<typeof LearningSchema>;
 export type Research = z.infer<typeof ResearchSchema>;
+export type DeepResearch = z.infer<typeof DeepResearchSchema>;
agents/deep-research-js/src/agents/orchestrator/index.ts (1)

62-62: Improve error message formatting.

The error message might not display properly due to error object stringification. Consider extracting the error message:

-		return resp.text(`Failed to generate report: ${error}`, {
+		return resp.text(`Failed to generate report: ${error instanceof Error ? error.message : String(error)}`, {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6e2ccca and d5c31b0.

📒 Files selected for processing (5)
  • agents/deep-research-js/index.ts (1 hunks)
  • agents/deep-research-js/src/agents/orchestrator/index.ts (1 hunks)
  • agents/deep-research-js/src/agents/researcher/index.ts (1 hunks)
  • agents/deep-research-js/src/agents/web-search/index.ts (1 hunks)
  • agents/deep-research-js/src/common/types.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • agents/deep-research-js/index.ts
  • agents/deep-research-js/src/agents/web-search/index.ts
  • agents/deep-research-js/src/agents/researcher/index.ts
🔇 Additional comments (1)
agents/deep-research-js/src/common/types.ts (1)

32-37: LGTM! The typo has been fixed and schema validation looks robust.

The DeepResearchSchema now correctly uses depth instead of the previously misspelled deepth. The validation constraints are well-defined with sensible min/max values for depth (1-5), breadth (1-5), and maxResults (5-100).

@rblalock rblalock merged commit 260cd00 into agentuity:main Jun 3, 2025
1 check passed
@coderabbitai coderabbitai bot mentioned this pull request Jun 23, 2025
@coderabbitai coderabbitai bot mentioned this pull request Sep 11, 2025
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants