@aaac/runtime 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,129 @@
1
+ import { S as SdkAdapter, C as CacheConfig, A as AdapterSendOptions, a as AgentExecutionRequest, M as MemoryRef } from '../task-runner-CNj3Ujy0.js';
2
+ import { G as GuardrailHooks } from '../guardrail-hooks-C8G5NGsj.js';
3
+ import 'zod';
4
+ import '@aaac/observability';
5
+
6
+ /**
7
+ * Google ADK Adapter — implements SdkAdapter for @google/adk (ADK-TS / adk-js)
8
+ *
9
+ * Replaces the raw @google/genai adapter. ADK provides a native subagent
10
+ * mechanism (`LlmAgent.subAgents` + description-based agent transfer), which is
11
+ * required for model B (LLM-internal routing): the entry agent's LLM delegates
12
+ * to candidate sub-agents registered in the agent tree.
13
+ *
14
+ * Supports:
15
+ * - send() — build a root LlmAgent (+ candidate subAgents), run once,
16
+ * return the final response text
17
+ * - sendExecution() — rich path using full contract context
18
+ *
19
+ * No followUp(): ADK's InMemoryRunner uses ephemeral sessions, so the runtime's
20
+ * recovery loop falls back to a fresh send() with reconstructed context.
21
+ *
22
+ * API used (verified against the installed package's type definitions under
23
+ * node_modules/@google/adk/dist/types):
24
+ * - class LlmAgent (agents/llm_agent.d.ts): constructor(config) where config
25
+ * extends BaseAgentConfig { name; description?; subAgents?: BaseAgent[] }
26
+ * and adds { model?: string | BaseLlm; instruction?: string; tools? }.
27
+ * - class InMemoryRunner (runner/in_memory_runner.d.ts): constructor({ agent,
28
+ * appName? }); inherits runEphemeral({ userId, newMessage: Content })
29
+ * returning AsyncGenerator<Event> (runner/runner.d.ts).
30
+ * - isFinalResponse(event) / stringifyContent(event) (events/event.d.ts).
31
+ * - class Gemini (models/google_llm.d.ts): constructor({ model, apiKey })
32
+ * — used to inject an explicit API key; otherwise ADK reads
33
+ * GOOGLE_GENAI_API_KEY / GEMINI_API_KEY from the environment.
34
+ */
35
+
36
+ type AdkContentPart = {
37
+ text?: string;
38
+ functionCall?: {
39
+ name?: string;
40
+ args?: Record<string, unknown>;
41
+ };
42
+ functionResponse?: {
43
+ name?: string;
44
+ response?: unknown;
45
+ };
46
+ };
47
+ type AdkContent = {
48
+ role?: string;
49
+ parts?: AdkContentPart[];
50
+ };
51
+ type AdkEvent = {
52
+ author?: string;
53
+ content?: AdkContent;
54
+ [key: string]: unknown;
55
+ };
56
+ type LlmAgentConfig = {
57
+ name: string;
58
+ description?: string;
59
+ model?: string | object;
60
+ instruction?: string;
61
+ tools?: unknown[];
62
+ subAgents?: unknown[];
63
+ };
64
+ type LlmAgentInstance = object;
65
+ type LlmAgentConstructor = new (config: LlmAgentConfig) => LlmAgentInstance;
66
+ type RunnerInstance = {
67
+ runEphemeral(params: {
68
+ userId: string;
69
+ newMessage: AdkContent;
70
+ stateDelta?: Record<string, unknown>;
71
+ }): AsyncGenerator<AdkEvent, void, unknown>;
72
+ };
73
+ type InMemoryRunnerConstructor = new (params: {
74
+ agent: LlmAgentInstance;
75
+ appName?: string;
76
+ }) => RunnerInstance;
77
+ type GeminiConstructor = new (params: {
78
+ model?: string;
79
+ apiKey?: string;
80
+ }) => object;
81
+ interface AdkSdk {
82
+ LlmAgent: LlmAgentConstructor;
83
+ InMemoryRunner: InMemoryRunnerConstructor;
84
+ isFinalResponse: (event: AdkEvent) => boolean;
85
+ stringifyContent: (event: AdkEvent) => string;
86
+ Gemini: GeminiConstructor;
87
+ }
88
+ interface AdkSdkAdapterConfig {
89
+ /** API key for the Gemini API. Falls back to GOOGLE_GENAI_API_KEY / GEMINI_API_KEY env. */
90
+ apiKey?: string;
91
+ /** Gemini model identifier (e.g. "gemini-2.5-flash", "gemini-2.5-pro"). */
92
+ model?: string;
93
+ /** Root agent name (must be a JS identifier). Defaults to "root_agent". */
94
+ rootAgentName?: string;
95
+ /** Runtime guardrail hooks. Applied as input-level checks before agent execution. */
96
+ guardrailHooks?: GuardrailHooks;
97
+ /** Prompt caching configuration. Enabled by default. */
98
+ cacheConfig?: CacheConfig;
99
+ }
100
+ declare class AdkSdkAdapter implements SdkAdapter {
101
+ private apiKey;
102
+ private model;
103
+ private rootAgentName;
104
+ private guardrailHooks;
105
+ private cacheConfig;
106
+ private lastMemoryRef;
107
+ private runCounter;
108
+ private sdk;
109
+ constructor(config?: AdkSdkAdapterConfig);
110
+ private resolveSdk;
111
+ /** Resolve the `model` field for LlmAgent — a Gemini instance when an explicit
112
+ * API key is supplied, otherwise the bare model id (ADK reads env keys). */
113
+ private resolveModel;
114
+ /** Build the root LlmAgent with candidate sub-agents registered for transfer. */
115
+ private buildRootAgent;
116
+ private runAgent;
117
+ private nextMemoryRef;
118
+ send(prompt: string, options: AdapterSendOptions): Promise<string>;
119
+ sendExecution(request: AgentExecutionRequest): Promise<string>;
120
+ getLastMemoryRef(): MemoryRef | null;
121
+ isCompatible(compat: string): boolean;
122
+ /**
123
+ * Inject the resolved ADK SDK surface for testing.
124
+ * Bypasses the dynamic import of @google/adk and the API key requirement.
125
+ */
126
+ static withSdk(sdk: AdkSdk, config?: AdkSdkAdapterConfig): AdkSdkAdapter;
127
+ }
128
+
129
+ export { AdkSdkAdapter, type AdkSdkAdapterConfig };
@@ -0,0 +1,185 @@
1
+ import {
2
+ getBlockingViolations
3
+ } from "../chunk-MGRZBGQL.js";
4
+
5
+ // src/adapters/adk-sdk.ts
6
+ function sanitizeAgentName(name) {
7
+ let id = name.replace(/[^a-zA-Z0-9_]/g, "_");
8
+ if (id.length === 0 || /^[0-9]/.test(id)) id = `agent_${id}`;
9
+ if (id === "user") id = "user_agent";
10
+ return id;
11
+ }
12
+ function extractEventText(event) {
13
+ const parts = event.content?.parts;
14
+ if (!parts) return "";
15
+ return parts.map((p) => p.text ?? "").join("");
16
+ }
17
+ var AdkSdkAdapter = class _AdkSdkAdapter {
18
+ apiKey;
19
+ model;
20
+ rootAgentName;
21
+ guardrailHooks;
22
+ cacheConfig;
23
+ lastMemoryRef = null;
24
+ runCounter = 0;
25
+ sdk = null;
26
+ constructor(config = {}) {
27
+ this.apiKey = config.apiKey;
28
+ this.model = config.model ?? "gemini-2.5-flash";
29
+ this.rootAgentName = config.rootAgentName ?? "root_agent";
30
+ this.guardrailHooks = config.guardrailHooks;
31
+ this.cacheConfig = config.cacheConfig ?? { enabled: true };
32
+ }
33
+ // -------------------------------------------------------------------------
34
+ // Internal helpers
35
+ // -------------------------------------------------------------------------
36
+ async resolveSdk() {
37
+ if (this.sdk) return this.sdk;
38
+ const mod = await import("@google/adk");
39
+ this.sdk = {
40
+ LlmAgent: mod.LlmAgent,
41
+ InMemoryRunner: mod.InMemoryRunner,
42
+ isFinalResponse: mod.isFinalResponse,
43
+ stringifyContent: mod.stringifyContent,
44
+ Gemini: mod.Gemini
45
+ };
46
+ return this.sdk;
47
+ }
48
+ /** Resolve the `model` field for LlmAgent — a Gemini instance when an explicit
49
+ * API key is supplied, otherwise the bare model id (ADK reads env keys). */
50
+ resolveModel(sdk) {
51
+ if (this.apiKey) {
52
+ return new sdk.Gemini({ model: this.model, apiKey: this.apiKey });
53
+ }
54
+ return this.model;
55
+ }
56
+ /** Build the root LlmAgent with candidate sub-agents registered for transfer. */
57
+ buildRootAgent(sdk, instruction, agents) {
58
+ const subAgents = (agents ?? []).map((a) => {
59
+ const config = {
60
+ name: sanitizeAgentName(a.name),
61
+ description: a.description,
62
+ instruction: a.prompt,
63
+ model: a.model ?? this.resolveModel(sdk)
64
+ };
65
+ if (a.tools) config.tools = a.tools;
66
+ return new sdk.LlmAgent(config);
67
+ });
68
+ const rootConfig = {
69
+ name: sanitizeAgentName(this.rootAgentName),
70
+ instruction,
71
+ model: this.resolveModel(sdk)
72
+ };
73
+ if (subAgents.length > 0) rootConfig.subAgents = subAgents;
74
+ return new sdk.LlmAgent(rootConfig);
75
+ }
76
+ async runAgent(instruction, userMessage, agents, onProgress) {
77
+ if (this.guardrailHooks) {
78
+ const results = this.guardrailHooks.runChecks({ command: userMessage });
79
+ const blocking = getBlockingViolations(results);
80
+ if (blocking.length > 0) {
81
+ const msg = blocking.map((r) => `[${r.guardrail_id}] ${r.message}`).join("\n");
82
+ throw new Error(msg);
83
+ }
84
+ }
85
+ const sdk = await this.resolveSdk();
86
+ const root = this.buildRootAgent(sdk, instruction, agents);
87
+ const runner = new sdk.InMemoryRunner({ agent: root });
88
+ let finalText = "";
89
+ const stream = runner.runEphemeral({
90
+ userId: "agent-runtime",
91
+ newMessage: { role: "user", parts: [{ text: userMessage }] }
92
+ });
93
+ for await (const event of stream) {
94
+ if (onProgress) emitProgressFromAdkEvent(event, onProgress);
95
+ const ev = event;
96
+ if (ev.errorCode || ev.errorMessage) {
97
+ throw new Error(
98
+ `Gemini API error (${ev.errorCode ?? "unknown"}): ${ev.errorMessage ?? "no details"}`
99
+ );
100
+ }
101
+ if (sdk.isFinalResponse(event) && event.content) {
102
+ const text = sdk.stringifyContent(event) || extractEventText(event);
103
+ if (text) finalText = text;
104
+ }
105
+ }
106
+ return finalText;
107
+ }
108
+ nextMemoryRef() {
109
+ return {
110
+ id: `adk-run-${++this.runCounter}-${Date.now()}`,
111
+ provider: "google-adk",
112
+ compat: `google-adk@${this.model}`,
113
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
114
+ };
115
+ }
116
+ // -------------------------------------------------------------------------
117
+ // SdkAdapter interface
118
+ // -------------------------------------------------------------------------
119
+ async send(prompt, options) {
120
+ this.lastMemoryRef = null;
121
+ const split = options.splitPrompt;
122
+ let instruction = "";
123
+ let userMessage;
124
+ if (split && this.cacheConfig.enabled !== false) {
125
+ instruction = split.system.join("\n\n---\n\n");
126
+ userMessage = split.user;
127
+ } else {
128
+ userMessage = prompt;
129
+ }
130
+ const text = await this.runAgent(instruction, userMessage, options.agents, options.onProgress);
131
+ this.lastMemoryRef = this.nextMemoryRef();
132
+ return text;
133
+ }
134
+ async sendExecution(request) {
135
+ this.lastMemoryRef = null;
136
+ const split = request.splitPrompt;
137
+ let instruction = "";
138
+ let userMessage;
139
+ if (split && this.cacheConfig.enabled !== false) {
140
+ instruction = split.system.join("\n\n---\n\n");
141
+ userMessage = split.user;
142
+ } else {
143
+ userMessage = request.prompt;
144
+ }
145
+ const agents = request.options.agents ?? request.agents;
146
+ const text = await this.runAgent(instruction, userMessage, agents, request.options.onProgress);
147
+ this.lastMemoryRef = this.nextMemoryRef();
148
+ return text;
149
+ }
150
+ getLastMemoryRef() {
151
+ return this.lastMemoryRef;
152
+ }
153
+ isCompatible(compat) {
154
+ return compat.startsWith("google-adk@");
155
+ }
156
+ // -------------------------------------------------------------------------
157
+ // Test support
158
+ // -------------------------------------------------------------------------
159
+ /**
160
+ * Inject the resolved ADK SDK surface for testing.
161
+ * Bypasses the dynamic import of @google/adk and the API key requirement.
162
+ */
163
+ static withSdk(sdk, config) {
164
+ const adapter = new _AdkSdkAdapter(config);
165
+ adapter.sdk = sdk;
166
+ return adapter;
167
+ }
168
+ };
169
+ function emitProgressFromAdkEvent(event, onProgress) {
170
+ const parts = event.content?.parts;
171
+ if (!parts) return;
172
+ for (const part of parts) {
173
+ if (part.functionCall?.name) {
174
+ onProgress({ type: "tool_use", tool_name: part.functionCall.name, input: part.functionCall.args });
175
+ } else if (part.functionResponse?.name) {
176
+ onProgress({ type: "tool_result", tool_name: part.functionResponse.name });
177
+ } else if (part.text) {
178
+ onProgress({ type: "text", message: part.text });
179
+ }
180
+ }
181
+ }
182
+ export {
183
+ AdkSdkAdapter
184
+ };
185
+ //# sourceMappingURL=adk-sdk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/adapters/adk-sdk.ts"],"sourcesContent":["/**\n * Google ADK Adapter — implements SdkAdapter for @google/adk (ADK-TS / adk-js)\n *\n * Replaces the raw @google/genai adapter. ADK provides a native subagent\n * mechanism (`LlmAgent.subAgents` + description-based agent transfer), which is\n * required for model B (LLM-internal routing): the entry agent's LLM delegates\n * to candidate sub-agents registered in the agent tree.\n *\n * Supports:\n * - send() — build a root LlmAgent (+ candidate subAgents), run once,\n * return the final response text\n * - sendExecution() — rich path using full contract context\n *\n * No followUp(): ADK's InMemoryRunner uses ephemeral sessions, so the runtime's\n * recovery loop falls back to a fresh send() with reconstructed context.\n *\n * API used (verified against the installed package's type definitions under\n * node_modules/@google/adk/dist/types):\n * - class LlmAgent (agents/llm_agent.d.ts): constructor(config) where config\n * extends BaseAgentConfig { name; description?; subAgents?: BaseAgent[] }\n * and adds { model?: string | BaseLlm; instruction?: string; tools? }.\n * - class InMemoryRunner (runner/in_memory_runner.d.ts): constructor({ agent,\n * appName? }); inherits runEphemeral({ userId, newMessage: Content })\n * returning AsyncGenerator<Event> (runner/runner.d.ts).\n * - isFinalResponse(event) / stringifyContent(event) (events/event.d.ts).\n * - class Gemini (models/google_llm.d.ts): constructor({ model, apiKey })\n * — used to inject an explicit API key; otherwise ADK reads\n * GOOGLE_GENAI_API_KEY / GEMINI_API_KEY from the environment.\n */\n\nimport type {\n SdkAdapter,\n AdapterSendOptions,\n AgentExecutionRequest,\n AgentProgressEvent,\n CacheConfig,\n CandidateAgent,\n} from \"../lib/task-runner.js\";\nimport { getBlockingViolations, type GuardrailHooks } from \"../lib/guardrail-hooks.js\";\nimport type { MemoryRef } from \"../lib/memory-store.js\";\n\n// ---------------------------------------------------------------------------\n// Duck-typed SDK surface (avoid a hard compile-time dependency on @google/adk)\n// ---------------------------------------------------------------------------\n\ntype AdkContentPart = {\n text?: string;\n functionCall?: { name?: string; args?: Record<string, unknown> };\n functionResponse?: { name?: string; response?: unknown };\n};\n\ntype AdkContent = {\n role?: string;\n parts?: AdkContentPart[];\n};\n\ntype AdkEvent = {\n author?: string;\n content?: AdkContent;\n [key: string]: unknown;\n};\n\ntype LlmAgentConfig = {\n name: string;\n description?: string;\n model?: string | object;\n instruction?: string;\n tools?: unknown[];\n subAgents?: unknown[];\n};\n\ntype LlmAgentInstance = object;\ntype LlmAgentConstructor = new (config: LlmAgentConfig) => LlmAgentInstance;\n\ntype RunnerInstance = {\n runEphemeral(params: {\n userId: string;\n newMessage: AdkContent;\n stateDelta?: Record<string, unknown>;\n }): AsyncGenerator<AdkEvent, void, unknown>;\n};\n\ntype InMemoryRunnerConstructor = new (params: {\n agent: LlmAgentInstance;\n appName?: string;\n}) => RunnerInstance;\n\ntype GeminiConstructor = new (params: { model?: string; apiKey?: string }) => object;\n\ninterface AdkSdk {\n LlmAgent: LlmAgentConstructor;\n InMemoryRunner: InMemoryRunnerConstructor;\n isFinalResponse: (event: AdkEvent) => boolean;\n stringifyContent: (event: AdkEvent) => string;\n Gemini: GeminiConstructor;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * ADK requires agent names to be valid JS identifiers, unique within the tree,\n * and not \"user\". DSL agent ids may contain hyphens, so sanitize to identifiers.\n */\nfunction sanitizeAgentName(name: string): string {\n let id = name.replace(/[^a-zA-Z0-9_]/g, \"_\");\n if (id.length === 0 || /^[0-9]/.test(id)) id = `agent_${id}`;\n if (id === \"user\") id = \"user_agent\";\n return id;\n}\n\n/** Concatenate text parts from an event's content. */\nfunction extractEventText(event: AdkEvent): string {\n const parts = event.content?.parts;\n if (!parts) return \"\";\n return parts.map((p) => p.text ?? \"\").join(\"\");\n}\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\nexport interface AdkSdkAdapterConfig {\n /** API key for the Gemini API. Falls back to GOOGLE_GENAI_API_KEY / GEMINI_API_KEY env. */\n apiKey?: string;\n /** Gemini model identifier (e.g. \"gemini-2.5-flash\", \"gemini-2.5-pro\"). */\n model?: string;\n /** Root agent name (must be a JS identifier). Defaults to \"root_agent\". */\n rootAgentName?: string;\n /** Runtime guardrail hooks. Applied as input-level checks before agent execution. */\n guardrailHooks?: GuardrailHooks;\n /** Prompt caching configuration. Enabled by default. */\n cacheConfig?: CacheConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\nexport class AdkSdkAdapter implements SdkAdapter {\n private apiKey: string | undefined;\n private model: string;\n private rootAgentName: string;\n private guardrailHooks: GuardrailHooks | undefined;\n private cacheConfig: CacheConfig;\n private lastMemoryRef: MemoryRef | null = null;\n private runCounter = 0;\n\n private sdk: AdkSdk | null = null;\n\n constructor(config: AdkSdkAdapterConfig = {}) {\n this.apiKey = config.apiKey;\n this.model = config.model ?? \"gemini-2.5-flash\";\n this.rootAgentName = config.rootAgentName ?? \"root_agent\";\n this.guardrailHooks = config.guardrailHooks;\n this.cacheConfig = config.cacheConfig ?? { enabled: true };\n }\n\n // -------------------------------------------------------------------------\n // Internal helpers\n // -------------------------------------------------------------------------\n\n private async resolveSdk(): Promise<AdkSdk> {\n if (this.sdk) return this.sdk;\n\n const mod = (await import(\"@google/adk\")) as unknown as AdkSdk;\n this.sdk = {\n LlmAgent: mod.LlmAgent,\n InMemoryRunner: mod.InMemoryRunner,\n isFinalResponse: mod.isFinalResponse,\n stringifyContent: mod.stringifyContent,\n Gemini: mod.Gemini,\n };\n return this.sdk;\n }\n\n /** Resolve the `model` field for LlmAgent — a Gemini instance when an explicit\n * API key is supplied, otherwise the bare model id (ADK reads env keys). */\n private resolveModel(sdk: AdkSdk): string | object {\n if (this.apiKey) {\n return new sdk.Gemini({ model: this.model, apiKey: this.apiKey });\n }\n return this.model;\n }\n\n /** Build the root LlmAgent with candidate sub-agents registered for transfer. */\n private buildRootAgent(\n sdk: AdkSdk,\n instruction: string,\n agents?: CandidateAgent[],\n ): LlmAgentInstance {\n const subAgents = (agents ?? []).map((a) => {\n const config: LlmAgentConfig = {\n name: sanitizeAgentName(a.name),\n description: a.description,\n instruction: a.prompt,\n model: a.model ?? this.resolveModel(sdk),\n };\n if (a.tools) config.tools = a.tools;\n return new sdk.LlmAgent(config);\n });\n\n const rootConfig: LlmAgentConfig = {\n name: sanitizeAgentName(this.rootAgentName),\n instruction,\n model: this.resolveModel(sdk),\n };\n if (subAgents.length > 0) rootConfig.subAgents = subAgents;\n\n return new sdk.LlmAgent(rootConfig);\n }\n\n private async runAgent(\n instruction: string,\n userMessage: string,\n agents: CandidateAgent[] | undefined,\n onProgress?: (event: AgentProgressEvent) => void,\n ): Promise<string> {\n if (this.guardrailHooks) {\n const results = this.guardrailHooks.runChecks({ command: userMessage });\n const blocking = getBlockingViolations(results);\n if (blocking.length > 0) {\n const msg = blocking.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n throw new Error(msg);\n }\n }\n\n const sdk = await this.resolveSdk();\n const root = this.buildRootAgent(sdk, instruction, agents);\n const runner = new sdk.InMemoryRunner({ agent: root });\n\n let finalText = \"\";\n const stream = runner.runEphemeral({\n userId: \"agent-runtime\",\n newMessage: { role: \"user\", parts: [{ text: userMessage }] },\n });\n\n for await (const event of stream) {\n if (onProgress) emitProgressFromAdkEvent(event, onProgress);\n\n const ev = event as Record<string, unknown>;\n if (ev.errorCode || ev.errorMessage) {\n throw new Error(\n `Gemini API error (${ev.errorCode ?? \"unknown\"}): ${ev.errorMessage ?? \"no details\"}`,\n );\n }\n\n if (sdk.isFinalResponse(event) && event.content) {\n const text = sdk.stringifyContent(event) || extractEventText(event);\n if (text) finalText = text;\n }\n }\n\n return finalText;\n }\n\n private nextMemoryRef(): MemoryRef {\n return {\n id: `adk-run-${++this.runCounter}-${Date.now()}`,\n provider: \"google-adk\",\n compat: `google-adk@${this.model}`,\n created_at: new Date().toISOString(),\n };\n }\n\n // -------------------------------------------------------------------------\n // SdkAdapter interface\n // -------------------------------------------------------------------------\n\n async send(prompt: string, options: AdapterSendOptions): Promise<string> {\n this.lastMemoryRef = null;\n\n const split = options.splitPrompt;\n let instruction = \"\";\n let userMessage: string;\n\n if (split && this.cacheConfig.enabled !== false) {\n instruction = split.system.join(\"\\n\\n---\\n\\n\");\n userMessage = split.user;\n } else {\n userMessage = prompt;\n }\n\n const text = await this.runAgent(instruction, userMessage, options.agents, options.onProgress);\n this.lastMemoryRef = this.nextMemoryRef();\n return text;\n }\n\n async sendExecution(request: AgentExecutionRequest): Promise<string> {\n this.lastMemoryRef = null;\n\n const split = request.splitPrompt;\n let instruction = \"\";\n let userMessage: string;\n\n if (split && this.cacheConfig.enabled !== false) {\n instruction = split.system.join(\"\\n\\n---\\n\\n\");\n userMessage = split.user;\n } else {\n userMessage = request.prompt;\n }\n\n const agents = request.options.agents ?? request.agents;\n const text = await this.runAgent(instruction, userMessage, agents, request.options.onProgress);\n this.lastMemoryRef = this.nextMemoryRef();\n return text;\n }\n\n getLastMemoryRef(): MemoryRef | null {\n return this.lastMemoryRef;\n }\n\n isCompatible(compat: string): boolean {\n return compat.startsWith(\"google-adk@\");\n }\n\n // -------------------------------------------------------------------------\n // Test support\n // -------------------------------------------------------------------------\n\n /**\n * Inject the resolved ADK SDK surface for testing.\n * Bypasses the dynamic import of @google/adk and the API key requirement.\n */\n static withSdk(sdk: AdkSdk, config?: AdkSdkAdapterConfig): AdkSdkAdapter {\n const adapter = new AdkSdkAdapter(config);\n adapter.sdk = sdk;\n return adapter;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Progress event mapping\n// ---------------------------------------------------------------------------\n\nfunction emitProgressFromAdkEvent(\n event: AdkEvent,\n onProgress: (event: AgentProgressEvent) => void,\n): void {\n const parts = event.content?.parts;\n if (!parts) return;\n for (const part of parts) {\n if (part.functionCall?.name) {\n onProgress({ type: \"tool_use\", tool_name: part.functionCall.name, input: part.functionCall.args });\n } else if (part.functionResponse?.name) {\n onProgress({ type: \"tool_result\", tool_name: part.functionResponse.name });\n } else if (part.text) {\n onProgress({ type: \"text\", message: part.text });\n }\n }\n}\n"],"mappings":";;;;;AAyGA,SAAS,kBAAkB,MAAsB;AAC/C,MAAI,KAAK,KAAK,QAAQ,kBAAkB,GAAG;AAC3C,MAAI,GAAG,WAAW,KAAK,SAAS,KAAK,EAAE,EAAG,MAAK,SAAS,EAAE;AAC1D,MAAI,OAAO,OAAQ,MAAK;AACxB,SAAO;AACT;AAGA,SAAS,iBAAiB,OAAyB;AACjD,QAAM,QAAQ,MAAM,SAAS;AAC7B,MAAI,CAAC,MAAO,QAAO;AACnB,S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;AACpC,WAAO,OAAO,WAAW,aAAa;AAAA,EACxC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,OAAO,QAAQ,KAAa,QAA6C;AACvE,UAAM,UAAU,IAAI,eAAc,MAAM;AACxC,YAAQ,MAAM;AACd,WAAO;AAAA,EACT;AACF;AAMA,SAAS,yBACP,OACA,YACM;AACN,QAAM,QAAQ,MAAM,SAAS;AAC7B,MAAI,CAAC,MAAO;AACZ,aAAW,QAAQ,OAAO;AACxB,QAAI,KAAK,cAAc,MAAM;AAC3B,iBAAW,EAAE,MAAM,YAAY,WAAW,KAAK,aAAa,MAAM,OAAO,KAAK,aAAa,KAAK,CAAC;AAAA,IACnG,WAAW,KAAK,kBAAkB,MAAM;AACtC,iBAAW,EAAE,MAAM,eAAe,WAAW,KAAK,iBAAiB,KAAK,CAAC;AAAA,IAC3E,WAAW,KAAK,MAAM;AACpB,iBAAW,EAAE,MAAM,QAAQ,SAAS,KAAK,KAAK,CAAC;AAAA,IACjD;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,97 @@
1
+ import { S as SdkAdapter, C as CacheConfig, A as AdapterSendOptions, a as AgentExecutionRequest, M as MemoryRef } from '../task-runner-CNj3Ujy0.js';
2
+ import { G as GuardrailHooks } from '../guardrail-hooks-C8G5NGsj.js';
3
+ import 'zod';
4
+ import '@aaac/observability';
5
+
6
+ /**
7
+ * Claude Agent SDK Adapter — implements SdkAdapter for @anthropic-ai/claude-agent-sdk
8
+ *
9
+ * Uses the `query()` function from the Claude Agent SDK to run Claude as a
10
+ * stateful coding agent with tool execution (Read, Edit, Bash, etc.).
11
+ *
12
+ * Supports:
13
+ * - send() — start a new query session and return the result text
14
+ * - followUp() — resume the same session for output-format corrections
15
+ * - sendExecution() — rich path using full contract context
16
+ *
17
+ * The SDK returns an AsyncGenerator of SDKMessage events. The adapter iterates
18
+ * the stream, extracts the final result text from the SDKResultSuccess message,
19
+ * and captures the session_id for followUp via `resume`.
20
+ *
21
+ * GuardrailHooks are mapped to the SDK's PreToolUse hook system.
22
+ */
23
+
24
+ type SDKContentBlock = {
25
+ type: string;
26
+ name?: string;
27
+ text?: string;
28
+ input?: unknown;
29
+ };
30
+ type SDKBetaMessage = {
31
+ content?: SDKContentBlock[];
32
+ };
33
+ type SDKMessage = {
34
+ type: string;
35
+ subtype?: string;
36
+ result?: string;
37
+ error?: string;
38
+ session_id?: string;
39
+ tool_name?: string;
40
+ summary?: string;
41
+ message?: SDKBetaMessage;
42
+ };
43
+ type QueryOptions = Record<string, unknown>;
44
+ type QueryFn = (params: {
45
+ prompt: string;
46
+ options?: QueryOptions;
47
+ }) => AsyncGenerator<SDKMessage, void>;
48
+ interface ClaudeAgentSdkAdapterConfig {
49
+ /** Working directory for the agent. Defaults to process.cwd(). */
50
+ cwd?: string;
51
+ /** Model identifier (e.g. "claude-sonnet-4-20250514"). Uses SDK default if omitted. */
52
+ model?: string;
53
+ /**
54
+ * Available tools. Defaults to read-only or read-write set based on AdapterSendOptions.
55
+ * Set to `{ type: 'preset', preset: 'claude_code' }` for all Claude Code tools.
56
+ */
57
+ tools?: string[] | {
58
+ type: "preset";
59
+ preset: "claude_code";
60
+ };
61
+ /** Permission mode. Defaults to "bypassPermissions" for automated workflows. */
62
+ permissionMode?: "default" | "acceptEdits" | "bypassPermissions" | "plan";
63
+ /** Max turns before stopping. */
64
+ maxTurns?: number;
65
+ /** Runtime guardrail hooks enforced via PreToolUse SDK hooks. */
66
+ guardrailHooks?: GuardrailHooks;
67
+ /** Prompt caching configuration. Enabled by default. */
68
+ cacheConfig?: CacheConfig;
69
+ }
70
+ declare class ClaudeAgentSdkAdapter implements SdkAdapter {
71
+ private cwd;
72
+ private model;
73
+ private tools;
74
+ private permissionMode;
75
+ private maxTurns;
76
+ private guardrailHooks;
77
+ private cacheConfig;
78
+ private lastSessionId;
79
+ private lastMemoryRef;
80
+ private queryFn;
81
+ constructor(config?: ClaudeAgentSdkAdapterConfig);
82
+ private resolveQueryFn;
83
+ private buildOptions;
84
+ private runQuery;
85
+ send(prompt: string, options: AdapterSendOptions): Promise<string>;
86
+ followUp(message: string): Promise<string>;
87
+ sendExecution(request: AgentExecutionRequest): Promise<string>;
88
+ getLastMemoryRef(): MemoryRef | null;
89
+ isCompatible(compat: string): boolean;
90
+ /**
91
+ * Inject a custom query function for testing.
92
+ * Bypasses the dynamic import of @anthropic-ai/claude-agent-sdk.
93
+ */
94
+ static withQueryFn(queryFn: QueryFn, config?: ClaudeAgentSdkAdapterConfig): ClaudeAgentSdkAdapter;
95
+ }
96
+
97
+ export { ClaudeAgentSdkAdapter, type ClaudeAgentSdkAdapterConfig };