-
-
Notifications
You must be signed in to change notification settings - Fork 801
Migrate SDKAgent to Claude Agent SDK V2 API #518
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
Update import statements to use V2 session-based API (`unstable_v2_createSession`, `unstable_v2_resumeSession`) replacing V1 `query()` API. Add documentation clarifying that unstable_v2 APIs are production-ready despite naming. Phase 1 changes: - Update imports in SDKAgent.ts to V2 API - Add dont-be-an-idiot.md documenting V2 API reality Next phase will refactor SDKAgent class implementation to use new session-based pattern. Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Major architectural update replacing V1 streaming API with V2 session-based API: Core API Changes: - Replace query() with send()/receive() pattern for bidirectional communication - Migrate from createAgent() to unstable_v2_createSession()/resumeSession() - Implement 'await using' for automatic session resource cleanup - Add explicit session completion logging Message Handling: - Add 'summarize' message type support for session summaries - Improve token extraction from SDK messages (text/toolUse/toolResult) - Enhance turn tracking with detailed session state logging Code Cleanup: - Remove deprecated createMessageGenerator() streaming method - Remove unused findClaudeExecutable() helper - Clean up obsolete imports (Stream, createAgent, etc.) This refactoring modernizes the agent implementation to align with current SDK patterns while maintaining backward compatibility with existing features. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
PR Review: Migrate SDKAgent to Claude Agent SDK V2 APISummaryThis PR successfully migrates ✅ Strengths1. Critical Bug Fix: Resource ManagementThe use of await using sdkSession = session.memorySessionId
? unstable_v2_resumeSession(memorySessionId, { model: modelId })
: unstable_v2_createSession({ model: modelId });This ensures automatic resource cleanup when the session goes out of scope, preventing memory leaks. This is particularly important since alternate agents fall back to SDKAgent on API failures (as noted in the PR description). 2. Simplified Message HandlingThe V2 API's
3. Proper Token AccountingLines 88-90 and 122-124 correctly extract token counts from the V2 API's const tokensUsed = (msg.message.usage?.input_tokens || 0) + (msg.message.usage?.output_tokens || 0);
session.cumulativeInputTokens += msg.message.usage?.input_tokens || 0;
session.cumulativeOutputTokens += msg.message.usage?.output_tokens || 0;This preserves accurate token tracking across the migration. 4. Documentation QualityThe 5. Code ReductionRemoving ~230 lines of complex generator code while maintaining functionality is a strong signal of improved design.
|
Simplifies SDKAgent.ts by removing unnecessary defensive programming patterns following V2 API migration. Changes align with fail-fast principle and canonical SDK examples. Changes: - Removed token usage extraction (V2 API doesn't expose usage) - Hardcoded tokensUsed to 0 with TODO for future implementation - Removed defensive worker null checks, replaced with optional chaining - Removed empty set size checks (iteration over empty set is safe) - Removed deleted count guards (logging 0 is informative) - Fixed type safety: added minimal ?? '' fallbacks where type contracts require - Fixed field names: obs.text → obs.narrative, obs.files → obs.files_read - Removed findClaudeExecutable() dead code (16 lines) - Added explicit null handling for storeSummary fields Net change: -26 lines, cleaner fail-fast architecture 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Code Review: PR #518 - Migrate SDKAgent to Claude Agent SDK V2 APISummaryThis PR successfully migrates SDKAgent from the V1 Positive Aspects ✅
Issues & Concerns 🔴Critical Issues
High Priority Issues
Medium Priority Issues
Low Priority Issues
Security Considerations 🔒
Testing Coverage 📋Critical Gap: No tests were found for SDKAgent. Recommendation:
Performance Considerations ⚡
Breaking Changes
Recommendations Before MergeMust Fix
Should Fix
Nice to Have
ConclusionThis is a valuable refactor that modernizes the codebase and improves reliability. However, the hardcoded zero token usage is a significant regression that needs resolution before merging. The session resumption logic also appears buggy and should be verified. Recommendation: Request changes to address critical issues before merging. Overall assessment: Strong architecture improvement, but implementation needs refinement. |
…DK V2 migration; remove defensive programming patterns, streamline code, and enhance type safety across multiple files; add new test scripts for session interaction and validation.
PR Review: Migrate SDKAgent to Claude Agent SDK V2 APISummaryThis PR successfully migrates the SDKAgent from the deprecated V1 ✅ Strengths1. Excellent Documentation
2. Proper Resource Management
3. Code Simplification
4. Backward Compatibility
5. Test Coverage
|
…s and related code. Update documentation and examples for V2 API usage. Delete obsolete test file and add new examples for V2 session API.
PR Review: SDK V2 MigrationI've completed a comprehensive review of this PR. Overall, this is a significant architectural improvement that modernizes the codebase, but there are some critical concerns that need to be addressed before merging. 🚨 Critical Issues1. API Mismatch: Using V1
|
Summary
Migrates SDKAgent from the V1
query()API to the stable V2 session-based API (unstable_v2_createSession/unstable_v2_resumeSession). This migration improves resource management, reduces code complexity, and aligns with the current Claude Agent SDK patterns.Changes
Phase 1: Import Migration (7a094ae)
unstable_v2_createSession,unstable_v2_resumeSession)Agent,AgentSession)Phase 2: Core Refactor + Bug Fixes (dbef74d)
startSession()method: Now uses V2 session pattern withsend()/receive()instead of generator-based approachcreateMessageGenerator()(~120 lines) - replaced by V2 session APIfindClaudeExecutable()(~30 lines) - no longer needed with V2await usingfor automatic resource cleanup (prevents memory leaks)msg.message.usage(V2 API signature)summarizemessage typeoriginalTimestampin responsesDocumentation
docs/context/dont-be-an-idiot.mddocumenting V2 API stability and patternsImpact
Testing
Architecture Note
SDKAgent differs from OpenRouterAgent/GeminiAgent intentionally:
buildObservationPrompt/buildSummaryPromptThis V2 migration's improved resource cleanup is critical since alternate agents fall back to SDKAgent on API failures.