MCPcopy
hub / github.com/rohitg00/agentmemory / AgentSDKProvider

Class AgentSDKProvider

src/providers/agent-sdk.ts:37–120  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

35type ClaudeAgentSdkModule = typeof import('@anthropic-ai/claude-agent-sdk')
36
37export class AgentSDKProvider implements MemoryProvider {
38 name = 'agent-sdk'
39
40 // Memoize the dynamic import so concurrent callers share one resolution
41 // instead of racing to resolve the specifier independently. Keeps the
42 // SDK out of the cold-start path for users on other providers.
43 private sdkPromise: Promise<ClaudeAgentSdkModule> | null = null
44
45 private loadSdk(): Promise<ClaudeAgentSdkModule> {
46 if (!this.sdkPromise) {
47 this.sdkPromise = import('@anthropic-ai/claude-agent-sdk')
48 }
49 return this.sdkPromise
50 }
51
52 async compress(systemPrompt: string, userPrompt: string): Promise<string> {
53 return this.query(systemPrompt, userPrompt)
54 }
55
56 async summarize(systemPrompt: string, userPrompt: string): Promise<string> {
57 return this.query(systemPrompt, userPrompt)
58 }
59
60 private async query(systemPrompt: string, userPrompt: string): Promise<string> {
61 // In-process recursion guard. Concurrent sibling calls (chunked
62 // summarize via Promise.all) each have their own ALS frame, so they
63 // do not poison each other.
64 if (sdkChildContext.getStore()) {
65 // We are already inside a Claude Agent SDK-spawned async call
66 // tree. Spawning another one would let its plugin-hook-driven
67 // Stop loop re-enter /agentmemory/summarize and cause unbounded
68 // recursion (#149 follow-up). Degrade to empty string so callers
69 // short-circuit. The chunk retry path in src/functions/summarize.ts
70 // treats "" as a parse failure but only the in-process re-entry
71 // path can reach this branch — legitimate concurrent siblings now
72 // run with their own ALS frames.
73 return ''
74 }
75
76 return sdkChildContext.run(true, async () => {
77 // Mark spawned subprocesses (the SDK's underlying Claude session
78 // + its hook scripts) as SDK children via process.env. Hook scripts
79 // run in separate processes and read process.env to short-circuit
80 // their REST callbacks. Reference-counted so overlapping calls
81 // don't race each other into restoring stale values.
82 if (sdkActiveCount === 0) {
83 sdkOriginalEnv = process.env.AGENTMEMORY_SDK_CHILD
84 process.env.AGENTMEMORY_SDK_CHILD = '1'
85 }
86 sdkActiveCount++
87
88 try {
89 const { query } = await this.loadSdk()
90
91 const messages = query({
92 prompt: userPrompt,
93 options: {
94 systemPrompt,

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected