Skip to content

fix: enable resolving of langgraph agents when cpk starts - #2029

Merged
ranst91 merged 5 commits into
mainfrom
fix/resolve-agui-agents-on-init
Jun 20, 2025
Merged

ranst91 merged 5 commits into
mainfrom
fix/resolve-agui-agents-on-init

Conversation

@ranst91

@ranst91 ranst91 commented Jun 20, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Unified support for discovering and managing agents from both remote endpoints and local AGUI agents.
    • Enhanced agent state loading, now compatible with multiple agent sources.
  • Improvements

    • Improved error handling and extensibility when loading agent states.
    • Added warnings for deprecated remote endpoint usage.

@vercel

vercel Bot commented Jun 20, 2025 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
copilotkit-feature-viewer 🛑 Canceled (Inspect) Jun 20, 2025 1:13pm
demo-viewer 🛑 Canceled (Inspect) Jun 20, 2025 1:13pm
docs 🛑 Canceled (Inspect) Jun 20, 2025 1:13pm
examples-coagents-ai-travel-app 🛑 Canceled (Inspect) Jun 20, 2025 1:13pm
examples-coagents-research-canvas-ui 🛑 Canceled (Inspect) Jun 20, 2025 1:13pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
examples-coagents-ai-researcher-ui ⬜️ Ignored (Inspect) Visit Preview Jun 20, 2025 1:13pm

@coderabbitai

coderabbitai Bot commented Jun 20, 2025 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@ranst91 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 14 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 1e8d184 and 065c7a3.

📒 Files selected for processing (7)
  • CopilotKit/.changeset/hip-ghosts-drum.md (1 hunks)
  • CopilotKit/packages/runtime/src/graphql/resolvers/state.resolver.ts (1 hunks)
  • CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts (6 hunks)
  • docs/content/docs/reference/classes/CopilotRuntime.mdx (1 hunks)
  • docs/content/docs/reference/components/chat/CopilotChat.mdx (1 hunks)
  • docs/content/docs/reference/components/chat/CopilotPopup.mdx (1 hunks)
  • docs/content/docs/reference/components/chat/CopilotSidebar.mdx (1 hunks)
## Walkthrough

The changes unify agent discovery and state loading in the CopilotRuntime, enabling support for both remote endpoints and local AGUI agents. New methods for agent discovery are introduced, and the state loading logic is refactored to handle various agent types consistently. Internal logic in the resolver is updated to use the new unified agent retrieval.

## Changes

| File(s)                                                                                  | Change Summary                                                                                                                        |
|------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------|
| .../runtime/src/graphql/resolvers/state.resolver.ts                                      | Refactored `loadAgentState` usage to utilize unified agent discovery via `getAllAgents`, updated agent existence check logic.         |
| .../runtime/src/lib/runtime/copilot-runtime.ts                                           | Added `getAllAgents` and `discoverAgentsFromAgui` methods, refactored `loadAgentState` for unified agent state loading and error handling. |

## Sequence Diagram(s)

```mermaid
sequenceDiagram
  participant Client
  participant StateResolver
  participant CopilotRuntime
  participant RemoteEndpoint
  participant AGUIAgent

  Client->>StateResolver: Request agent state (agentName, threadId)
  StateResolver->>CopilotRuntime: getAllAgents()
  CopilotRuntime->>RemoteEndpoint: discoverAgentsFromEndpoints()
  CopilotRuntime->>AGUIAgent: discoverAgentsFromAgui()
  CopilotRuntime-->>StateResolver: Combined agents list
  StateResolver->>CopilotRuntime: loadAgentState(threadId, agentName)
  CopilotRuntime->>CopilotRuntime: Find agent in combined list
  alt Agent is remote endpoint
    CopilotRuntime->>RemoteEndpoint: Fetch state (HTTP POST)
  else Agent is AGUI agent
    CopilotRuntime->>AGUIAgent: Fetch thread state
  end
  CopilotRuntime-->>StateResolver: Agent state
  StateResolver-->>Client: Return state

Possibly related PRs

Suggested labels

preview

Suggested reviewers

  • mme
  • suhasdeshpande
  • ataibarkai

<!-- walkthrough_end -->
<!-- internal state start -->


<!-- DwQgtGAEAqAWCWBnSTIEMB26CuAXA9mAOYCmGJATmriQCaQDG+Ats2bgFyQAOFk+AIwBWJBrngA3EsgEBPRvlqU0AgfFwA6NPEgQAfACgjoCEejqANiS4AzeAA8uZFVcgVp+CxPgYi/G5AWmEREVNyw6KQYuMgA7rBkjNwA1pCIuGgUMQYActjMApRcAEwADMUAnAYAqohFbpjpFQCMRvrG4FBk9PgBaHiEUco09Eys7Fy8/MKi4lIy8kxKVKrqWjrtJlBwqKiYOATEZMN0CuPRXFSxafnMmfJyCssqapraumCGHaYGAML43HgFnwuAA0uoAPTcNAMZJoUiICEUbDReBsCGICgMCGhNDhACOFiRHi8lER6WoJA07kQnikFA0MQ4BgARGyDABiDmQACCAEkjuQqCMbqx7v5GLBgtIzAlIGxcLBFJAAAbAtC0HlRXAAZQyNBVKCwipIqr1lIASiT6YaGEFEHE0MhmIp4HZTgRJdLIErrvD2MhMqb3LgKPASFJ6JhRglYXQNJAAArubz4bCICyyAA0KFwkHTpxVtCQTHpWoDADEKCwAKIYWjcfA+GIACjE9gAlIbPaQ8/7ooH65ATVg6pkGAl6DZ8Hx9v283dcBOfH4i9Q0FptTk0GxDemV6q7PWVQm4KbsNxaJTRopgyRuEEGNJhwg4uoIirezyLBZywO27gnbdvgbgkKG4ZSJEAboEOBbICqtK7sOIETqIqRujB8jzvK1CofBV4ZJu7Dbrup5ypQ1Z8Iq1axFg8SJBgIGLsuvhQdEKDINOKL0O4dw+MgJppDuJA5gIeAvqaEiZPALimhgO4HhO0pTtWzCqvOwGqlKiB/rgmnuDYVhiBJkACPgngkPsqGwmRd7pBKgkKkqtA5j4drYMWrHqp5fiCdhFI0DBPFgdgFAYAe6g5rx2gYMgKJKb48ZGEYXK8hYNDCvA+CxchJ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IEpqaR4zh0OsUEv8utidfoBCCL4WjERP70WNHKC74q2wpCfm96pWRPHaMZu62g+AV74NOPrepGPylAnZT4YsC6oEZAoL2IXDhcqOzfYCuUPh1rJ3gAALwzoUKUqY+DuD7fQT0JuQieyfaB4maUMrwe6aaAahVDcIbKhVZD1VUPLQwy1DaRhOrkABmyImwMvhbDcRKfohxqfXjOPgy4aBrh07uAz0yixbwrFeOsD4hgB9jE27gAA+vAWgiAt8pnDLEOgW+KRZFX98KAAAOWgAgACsAAWYoAA2VQAB2GwpQ0Bv4AMwMFoAwM0D/s0BUG/iQHfnfs/mgK/g/m/nflfg/gIMUG/s/gEJsJ0JAM0CQDfs0AgRULQM0CAV/g/j/mgCQKUBUI/iQD/sULQQIC0DYDYLQMUFfjYAIFfs0M/hfgYOvvXOoDvnvgfhGEfift0KvkAA=== -->

<!-- internal state end -->
<!-- finishing_touch_checkbox_start -->

<details open="true">
<summary>✨ Finishing Touches</summary>

- [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate Docstrings

</details>

<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->

---

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.

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=CopilotKit/CopilotKit&utm_content=2029):

> ‼️ **IMPORTANT**
> Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.
- 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](https://www.coderabbit.ai/contact-us/support) 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](https://docs.coderabbit.ai/finishing-touches/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.

### Documentation and Community

- Visit our [Documentation](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8db5426 and 1e8d184.

📒 Files selected for processing (3)
  • CopilotKit/.changeset/hip-ghosts-drum.md (1 hunks)
  • CopilotKit/packages/runtime/src/graphql/resolvers/state.resolver.ts (1 hunks)
  • CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts (5 hunks)
✅ Files skipped from review due to trivial changes (1)
  • CopilotKit/.changeset/hip-ghosts-drum.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • CopilotKit/packages/runtime/src/graphql/resolvers/state.resolver.ts
🧰 Additional context used
🪛 Biome (1.9.4)
CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts

[error] 1010-1010: This code is unreachable

... because either this statement will throw an exception, ...

... this statement will throw an exception, ...

... this statement will throw an exception, ...

... this statement will return from the function, ...

... this statement will throw an exception, ...

... this statement will throw an exception, ...

... this statement will throw an exception, ...

... this statement will return from the function, ...

... or this statement will return from the function beforehand

(lint/correctness/noUnreachable)

🪛 GitHub Actions: Quality
CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts

[warning] 1-1: Prettier formatting check failed. Run Prettier with --write to fix code style issues.

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test (20.x)
  • GitHub Check: Test (18.x)
🔇 Additional comments (6)
CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts (6)

87-87: LGTM: Clean import addition

The import for LangGraphAgent is properly added to support the new unified agent discovery functionality.


331-342: Good deprecation handling with clear migration guidance

The deprecation warning provides clear guidance to users about migrating from LangGraph Platform remote endpoints to the new agents property. The commented TODO section suggests future work for validating agent imports.


783-790: Excellent unified agent discovery implementation

The method efficiently uses Promise.all for concurrent execution and properly combines results from both endpoint-based and AGUI-based agent discovery.


919-925: Improved agent discovery using unified method

Good refactoring to use the new getAllAgents method for consistent agent discovery across different agent types.


926-966: Clean CopilotKit endpoint handling

The refactored logic for handling CopilotKit endpoints is well-structured with proper error handling and response formatting.


968-1009: Well-structured LangGraph client initialization and state handling

The unified approach to handle both LangGraphPlatform endpoints and AGUI agents through a common client interface is a good architectural improvement. The error handling and response formatting are consistent.

};
}

throw new Error(`Agent: ${agent.name} could not be resolved`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unreachable code

Static analysis correctly identified this line as unreachable. All code paths above either return or throw exceptions, making this statement unreachable.

-   throw new Error(`Agent: ${agent.name} could not be resolved`);

This line should be removed as it's unreachable due to the preceding conditional logic that handles all possible cases.

📝 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.

Suggested change
throw new Error(`Agent: ${agent.name} could not be resolved`);
🧰 Tools
🪛 Biome (1.9.4)

[error] 1010-1010: This code is unreachable

... because either this statement will throw an exception, ...

... this statement will throw an exception, ...

... this statement will throw an exception, ...

... this statement will return from the function, ...

... this statement will throw an exception, ...

... this statement will throw an exception, ...

... this statement will throw an exception, ...

... this statement will return from the function, ...

... or this statement will return from the function beforehand

(lint/correctness/noUnreachable)

🤖 Prompt for AI Agents
In CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts at line 1010,
the throw statement is unreachable because all preceding code paths either
return or throw exceptions. Remove this unreachable throw statement to clean up
the code and avoid confusion.

Comment on lines +980 to +991
const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name] as LangGraphAgent
if (!aguiAgent) {
throw new Error(`Agent: ${agent.name} could not be resolved`)
}
// @ts-expect-error -- both clients are the same
client = aguiAgent.client
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve type safety in agent resolution

The current implementation uses type casting and accessing potentially undefined properties, which could lead to runtime errors.

-     const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name] as LangGraphAgent
-     if (!aguiAgent) {
-       throw new Error(`Agent: ${agent.name} could not be resolved`)
-     }
-     // @ts-expect-error -- both clients are the same
-     client = aguiAgent.client
+     const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name];
+     if (!aguiAgent || !(aguiAgent instanceof LangGraphAgent)) {
+       throw new Error(`Agent: ${agent.name} could not be resolved or is not a LangGraphAgent`)
+     }
+     client = aguiAgent.client;
📝 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.

Suggested change
const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name] as LangGraphAgent
if (!aguiAgent) {
throw new Error(`Agent: ${agent.name} could not be resolved`)
}
// @ts-expect-error -- both clients are the same
client = aguiAgent.client
}
const aguiAgent = graphqlContext._copilotkit.runtime.agents[agent.name];
if (!aguiAgent || !(aguiAgent instanceof LangGraphAgent)) {
throw new Error(`Agent: ${agent.name} could not be resolved or is not a LangGraphAgent`);
}
client = aguiAgent.client;
}
🤖 Prompt for AI Agents
In CopilotKit/packages/runtime/src/lib/runtime/copilot-runtime.ts around lines
980 to 986, the code uses type casting and directly accesses properties that
might be undefined, risking runtime errors. To fix this, add explicit type
checks to ensure graphqlContext._copilotkit.runtime.agents and the specific
agent exist before accessing them. Replace the type cast with safer type guards
or conditional checks, and handle the case where the agent or client is
undefined by throwing a clear error or returning early. This will improve type
safety and prevent potential runtime exceptions.

@ranst91
ranst91 force-pushed the fix/resolve-agui-agents-on-init branch from fb4f047 to 065c7a3 Compare June 20, 2025 13:03
@changesets-bot-copilotkit

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 065c7a3

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 7 packages
Name Type
@copilotkit/runtime Patch
@copilotkit/runtime-client-gql Patch
@copilotkit/react-core Patch
@copilotkit/react-textarea Patch
@copilotkit/react-ui Patch
@copilotkit/sdk-js Patch
@copilotkit/shared Patch

Click here if you're a maintainer who wants to add another changeset to this PR

@github-actions

github-actions Bot commented Jun 20, 2025 •

Copy link
Copy Markdown
Contributor

Preview environments destroyed for this pull request.

@github-actions

github-actions Bot commented Jun 20, 2025 •

Copy link
Copy Markdown
Contributor

Test Results

Status: ✅ Passed (View Run)

Commit: 97d2b40

Duration: 243.8s

Total Tests: 20

Pass Rate: 100.0%

Failed Tests: 0

🔍 Detailed Results

coagents-research-canvas

CoAgents Research Canvas (UI) - Local Depenencies

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -
CrewAI chromium ✅ PASSED -

coagents-qa-native

CoAgents QA Native (UI) - Local

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -

coagents-qa-text

CoAgents QA Text (UI) - Local

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -
OpenAI (LGC Python) chromium ✅ PASSED -
Anthropic (LGC Python) chromium ✅ PASSED -
OpenAI (LGC JS) chromium ✅ PASSED -
Anthropic (LGC JS) chromium ✅ PASSED -

coagents-routing

CoAgents Routing (UI) - Local

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -

next-openai

Next OpenAI - Self Hosted

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -
Google Generative AI chromium ✅ PASSED -
LangChain (OpenAI) chromium ✅ PASSED -
LangChain (Anthropic) chromium ✅ PASSED -
LangChain (Gemini) chromium ✅ PASSED -
Groq chromium ✅ PASSED -

This branch was successfully deployed

5 active deployments
Preview – demo-viewer — 065c7a3b Deployed Jun 20, 2025 by vercel[bot]
Preview – copilotkit-feature-viewer — 065c7a3b Deployed Jun 20, 2025 by vercel[bot]
Preview – docs — 065c7a3b Deployed Jun 20, 2025 by vercel[bot]
Preview – examples-coagents-ai-travel-app — 065c7a3b Deployed Jun 20, 2025 by vercel[bot]
Preview – examples-coagents-research-canvas-ui — 065c7a3b Deployed Jun 20, 2025 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant