alibabacloud-agentcore-sdk 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.
Files changed (221) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +189 -0
  3. package/dist/access-key-CkoHq3S8.d.cts +30 -0
  4. package/dist/access-key-CkoHq3S8.d.ts +30 -0
  5. package/dist/agent-sa-token-DD1Sb8P1.d.cts +14 -0
  6. package/dist/agent-sa-token-DD1Sb8P1.d.ts +14 -0
  7. package/dist/auth/index.cjs +36 -0
  8. package/dist/auth/index.cjs.map +1 -0
  9. package/dist/auth/index.d.cts +34 -0
  10. package/dist/auth/index.d.ts +34 -0
  11. package/dist/auth/index.js +36 -0
  12. package/dist/auth/index.js.map +1 -0
  13. package/dist/bound-credentials-C1fM0thh.d.cts +39 -0
  14. package/dist/bound-credentials-DqT64Q2s.d.ts +39 -0
  15. package/dist/chunk-2E5EWEDG.cjs +142 -0
  16. package/dist/chunk-2E5EWEDG.cjs.map +1 -0
  17. package/dist/chunk-55XZZRKO.js +220 -0
  18. package/dist/chunk-55XZZRKO.js.map +1 -0
  19. package/dist/chunk-5JXA7JPS.js +29 -0
  20. package/dist/chunk-5JXA7JPS.js.map +1 -0
  21. package/dist/chunk-5RKN46UU.cjs +139 -0
  22. package/dist/chunk-5RKN46UU.cjs.map +1 -0
  23. package/dist/chunk-5ZOLHQXO.js +296 -0
  24. package/dist/chunk-5ZOLHQXO.js.map +1 -0
  25. package/dist/chunk-7Y263YIW.js +298 -0
  26. package/dist/chunk-7Y263YIW.js.map +1 -0
  27. package/dist/chunk-A3PF2SPD.cjs +141 -0
  28. package/dist/chunk-A3PF2SPD.cjs.map +1 -0
  29. package/dist/chunk-A3WMLVJC.cjs +141 -0
  30. package/dist/chunk-A3WMLVJC.cjs.map +1 -0
  31. package/dist/chunk-BVZ7H2F5.cjs +582 -0
  32. package/dist/chunk-BVZ7H2F5.cjs.map +1 -0
  33. package/dist/chunk-EGUKJE3Z.cjs +24 -0
  34. package/dist/chunk-EGUKJE3Z.cjs.map +1 -0
  35. package/dist/chunk-EKXZKKJJ.js +24 -0
  36. package/dist/chunk-EKXZKKJJ.js.map +1 -0
  37. package/dist/chunk-GYLT23D3.js +110 -0
  38. package/dist/chunk-GYLT23D3.js.map +1 -0
  39. package/dist/chunk-IF7LMBXC.js +306 -0
  40. package/dist/chunk-IF7LMBXC.js.map +1 -0
  41. package/dist/chunk-IUCLCPVV.js +113 -0
  42. package/dist/chunk-IUCLCPVV.js.map +1 -0
  43. package/dist/chunk-JSP7ZROS.cjs +95 -0
  44. package/dist/chunk-JSP7ZROS.cjs.map +1 -0
  45. package/dist/chunk-JW62DVIC.js +238 -0
  46. package/dist/chunk-JW62DVIC.js.map +1 -0
  47. package/dist/chunk-K3TE7625.js +139 -0
  48. package/dist/chunk-K3TE7625.js.map +1 -0
  49. package/dist/chunk-LE5P3SJW.cjs +16 -0
  50. package/dist/chunk-LE5P3SJW.cjs.map +1 -0
  51. package/dist/chunk-LXHW6OT4.cjs +77 -0
  52. package/dist/chunk-LXHW6OT4.cjs.map +1 -0
  53. package/dist/chunk-MICRSJ6R.js +48 -0
  54. package/dist/chunk-MICRSJ6R.js.map +1 -0
  55. package/dist/chunk-MWAHO47B.cjs +220 -0
  56. package/dist/chunk-MWAHO47B.cjs.map +1 -0
  57. package/dist/chunk-MZ5UWGXS.js +95 -0
  58. package/dist/chunk-MZ5UWGXS.js.map +1 -0
  59. package/dist/chunk-NZL3VPJ2.js +16 -0
  60. package/dist/chunk-NZL3VPJ2.js.map +1 -0
  61. package/dist/chunk-PC4FM2RP.cjs +180 -0
  62. package/dist/chunk-PC4FM2RP.cjs.map +1 -0
  63. package/dist/chunk-PKYET77D.cjs +296 -0
  64. package/dist/chunk-PKYET77D.cjs.map +1 -0
  65. package/dist/chunk-PTJPB27L.js +31 -0
  66. package/dist/chunk-PTJPB27L.js.map +1 -0
  67. package/dist/chunk-QIZO3A4Y.cjs +306 -0
  68. package/dist/chunk-QIZO3A4Y.cjs.map +1 -0
  69. package/dist/chunk-RBAY4MO2.js +202 -0
  70. package/dist/chunk-RBAY4MO2.js.map +1 -0
  71. package/dist/chunk-RHY7Y43E.js +582 -0
  72. package/dist/chunk-RHY7Y43E.js.map +1 -0
  73. package/dist/chunk-RQRI6RCG.cjs +238 -0
  74. package/dist/chunk-RQRI6RCG.cjs.map +1 -0
  75. package/dist/chunk-RYXL25AI.js +141 -0
  76. package/dist/chunk-RYXL25AI.js.map +1 -0
  77. package/dist/chunk-RZNQGEGJ.cjs +113 -0
  78. package/dist/chunk-RZNQGEGJ.cjs.map +1 -0
  79. package/dist/chunk-S7PWSJNP.cjs +48 -0
  80. package/dist/chunk-S7PWSJNP.cjs.map +1 -0
  81. package/dist/chunk-TWEO5XVM.cjs +298 -0
  82. package/dist/chunk-TWEO5XVM.cjs.map +1 -0
  83. package/dist/chunk-UBP5CHU7.js +142 -0
  84. package/dist/chunk-UBP5CHU7.js.map +1 -0
  85. package/dist/chunk-ULJTQSLE.cjs +35 -0
  86. package/dist/chunk-ULJTQSLE.cjs.map +1 -0
  87. package/dist/chunk-UWPKFJYM.js +77 -0
  88. package/dist/chunk-UWPKFJYM.js.map +1 -0
  89. package/dist/chunk-WKZUYPDS.js +180 -0
  90. package/dist/chunk-WKZUYPDS.js.map +1 -0
  91. package/dist/chunk-YZP55W7S.cjs +29 -0
  92. package/dist/chunk-YZP55W7S.cjs.map +1 -0
  93. package/dist/chunk-ZELRQU4J.cjs +31 -0
  94. package/dist/chunk-ZELRQU4J.cjs.map +1 -0
  95. package/dist/chunk-ZLKYXRNM.js +141 -0
  96. package/dist/chunk-ZLKYXRNM.js.map +1 -0
  97. package/dist/chunk-ZLQ2IBTC.cjs +110 -0
  98. package/dist/chunk-ZLQ2IBTC.cjs.map +1 -0
  99. package/dist/chunk-ZTWLCHCO.cjs +202 -0
  100. package/dist/chunk-ZTWLCHCO.cjs.map +1 -0
  101. package/dist/chunk-ZWQBAJ5O.js +35 -0
  102. package/dist/chunk-ZWQBAJ5O.js.map +1 -0
  103. package/dist/client-DDU4-ygJ.d.cts +72 -0
  104. package/dist/client-pDzS7EZR.d.ts +72 -0
  105. package/dist/collaboration/index.cjs +44 -0
  106. package/dist/collaboration/index.cjs.map +1 -0
  107. package/dist/collaboration/index.d.cts +73 -0
  108. package/dist/collaboration/index.d.ts +73 -0
  109. package/dist/collaboration/index.js +44 -0
  110. package/dist/collaboration/index.js.map +1 -0
  111. package/dist/common-BSXkQfxI.d.cts +25 -0
  112. package/dist/common-BSXkQfxI.d.ts +25 -0
  113. package/dist/common-DRdI-75k.d.ts +8 -0
  114. package/dist/common-_vxreiEW.d.cts +8 -0
  115. package/dist/config-CMkmMtx1.d.cts +20 -0
  116. package/dist/config-CMkmMtx1.d.ts +20 -0
  117. package/dist/context-M9rOTifU.d.cts +12 -0
  118. package/dist/context-M9rOTifU.d.ts +12 -0
  119. package/dist/controller-DWs3Sy04.d.cts +9 -0
  120. package/dist/controller-DmI4L4sP.d.ts +9 -0
  121. package/dist/controlplane/index.cjs +13 -0
  122. package/dist/controlplane/index.cjs.map +1 -0
  123. package/dist/controlplane/index.d.cts +66 -0
  124. package/dist/controlplane/index.d.ts +66 -0
  125. package/dist/controlplane/index.js +13 -0
  126. package/dist/controlplane/index.js.map +1 -0
  127. package/dist/errors-BjGO6N10.d.ts +93 -0
  128. package/dist/errors-D9OtcR-o.d.cts +93 -0
  129. package/dist/event-converters-BIn8odqo.d.ts +38 -0
  130. package/dist/event-converters-Cn_NeGyQ.d.cts +38 -0
  131. package/dist/google-adk-model-N47R7GB2.js +208 -0
  132. package/dist/google-adk-model-N47R7GB2.js.map +1 -0
  133. package/dist/google-adk-model-PDBKY5YZ.cjs +208 -0
  134. package/dist/google-adk-model-PDBKY5YZ.cjs.map +1 -0
  135. package/dist/index.cjs +322 -0
  136. package/dist/index.cjs.map +1 -0
  137. package/dist/index.d.cts +78 -0
  138. package/dist/index.d.ts +78 -0
  139. package/dist/index.js +322 -0
  140. package/dist/index.js.map +1 -0
  141. package/dist/integrations/ai-sdk.cjs +15 -0
  142. package/dist/integrations/ai-sdk.cjs.map +1 -0
  143. package/dist/integrations/ai-sdk.d.cts +21 -0
  144. package/dist/integrations/ai-sdk.d.ts +21 -0
  145. package/dist/integrations/ai-sdk.js +15 -0
  146. package/dist/integrations/ai-sdk.js.map +1 -0
  147. package/dist/integrations/google-adk.cjs +90 -0
  148. package/dist/integrations/google-adk.cjs.map +1 -0
  149. package/dist/integrations/google-adk.d.cts +46 -0
  150. package/dist/integrations/google-adk.d.ts +46 -0
  151. package/dist/integrations/google-adk.js +90 -0
  152. package/dist/integrations/google-adk.js.map +1 -0
  153. package/dist/integrations/langchain.cjs +95 -0
  154. package/dist/integrations/langchain.cjs.map +1 -0
  155. package/dist/integrations/langchain.d.cts +52 -0
  156. package/dist/integrations/langchain.d.ts +52 -0
  157. package/dist/integrations/langchain.js +95 -0
  158. package/dist/integrations/langchain.js.map +1 -0
  159. package/dist/integrations/langgraph.cjs +30 -0
  160. package/dist/integrations/langgraph.cjs.map +1 -0
  161. package/dist/integrations/langgraph.d.cts +53 -0
  162. package/dist/integrations/langgraph.d.ts +53 -0
  163. package/dist/integrations/langgraph.js +30 -0
  164. package/dist/integrations/langgraph.js.map +1 -0
  165. package/dist/integrations/mastra.cjs +108 -0
  166. package/dist/integrations/mastra.cjs.map +1 -0
  167. package/dist/integrations/mastra.d.cts +47 -0
  168. package/dist/integrations/mastra.d.ts +47 -0
  169. package/dist/integrations/mastra.js +108 -0
  170. package/dist/integrations/mastra.js.map +1 -0
  171. package/dist/langchain-adapter-DFJdEX04.d.cts +47 -0
  172. package/dist/langchain-adapter-DJsyjm5V.d.ts +47 -0
  173. package/dist/langchain-provider-NF5GIDQV.cjs +227 -0
  174. package/dist/langchain-provider-NF5GIDQV.cjs.map +1 -0
  175. package/dist/langchain-provider-PHL4UWNF.js +227 -0
  176. package/dist/langchain-provider-PHL4UWNF.js.map +1 -0
  177. package/dist/loader-DrIQ37nm.d.ts +38 -0
  178. package/dist/loader-eWuJ2GSL.d.cts +38 -0
  179. package/dist/logging-C8GLLg1f.d.cts +9 -0
  180. package/dist/logging-C8GLLg1f.d.ts +9 -0
  181. package/dist/managed-CwLx9h4C.d.cts +32 -0
  182. package/dist/managed-D9eQK1ut.d.ts +32 -0
  183. package/dist/mcp/index.cjs +12 -0
  184. package/dist/mcp/index.cjs.map +1 -0
  185. package/dist/mcp/index.d.cts +62 -0
  186. package/dist/mcp/index.d.ts +62 -0
  187. package/dist/mcp/index.js +12 -0
  188. package/dist/mcp/index.js.map +1 -0
  189. package/dist/memory/index.cjs +12 -0
  190. package/dist/memory/index.cjs.map +1 -0
  191. package/dist/memory/index.d.cts +113 -0
  192. package/dist/memory/index.d.ts +113 -0
  193. package/dist/memory/index.js +12 -0
  194. package/dist/memory/index.js.map +1 -0
  195. package/dist/model/index.cjs +16 -0
  196. package/dist/model/index.cjs.map +1 -0
  197. package/dist/model/index.d.cts +129 -0
  198. package/dist/model/index.d.ts +129 -0
  199. package/dist/model/index.js +16 -0
  200. package/dist/model/index.js.map +1 -0
  201. package/dist/model-CkYHzHPk.d.cts +50 -0
  202. package/dist/model-CkYHzHPk.d.ts +50 -0
  203. package/dist/runtime/index.cjs +49 -0
  204. package/dist/runtime/index.cjs.map +1 -0
  205. package/dist/runtime/index.d.cts +73 -0
  206. package/dist/runtime/index.d.ts +73 -0
  207. package/dist/runtime/index.js +49 -0
  208. package/dist/runtime/index.js.map +1 -0
  209. package/dist/server/index.cjs +604 -0
  210. package/dist/server/index.cjs.map +1 -0
  211. package/dist/server/index.d.cts +69 -0
  212. package/dist/server/index.d.ts +69 -0
  213. package/dist/server/index.js +604 -0
  214. package/dist/server/index.js.map +1 -0
  215. package/dist/skill/index.cjs +14 -0
  216. package/dist/skill/index.cjs.map +1 -0
  217. package/dist/skill/index.d.cts +16 -0
  218. package/dist/skill/index.d.ts +16 -0
  219. package/dist/skill/index.js +14 -0
  220. package/dist/skill/index.js.map +1 -0
  221. package/package.json +292 -0
@@ -0,0 +1,208 @@
1
+ import {
2
+ languageModel
3
+ } from "./chunk-MICRSJ6R.js";
4
+ import "./chunk-WKZUYPDS.js";
5
+ import "./chunk-PTJPB27L.js";
6
+ import {
7
+ ConfigError,
8
+ InvocationError
9
+ } from "./chunk-MZ5UWGXS.js";
10
+
11
+ // src/integrations/google-adk-model.ts
12
+ import { BaseLlm } from "@google/adk";
13
+ import { FinishReason } from "@google/genai";
14
+ var AgentCoreLlm = class extends BaseLlm {
15
+ delegate;
16
+ constructor(client) {
17
+ super({ model: client.settings.model });
18
+ this.delegate = languageModel(client);
19
+ }
20
+ async connect() {
21
+ throw new ConfigError("AgentCore models do not implement ADK bidirectional live connections");
22
+ }
23
+ async *generateContentAsync(request, stream = false, abortSignal) {
24
+ const lifetime = new AbortController();
25
+ const signals = [lifetime.signal, abortSignal, request.config?.abortSignal].filter((value) => value !== void 0);
26
+ const options = requestOptions(request, AbortSignal.any(signals));
27
+ try {
28
+ if (!stream) {
29
+ const result2 = await this.delegate.doGenerate(options);
30
+ yield { content: { role: "model", parts: result2.content.flatMap(outputParts) }, ...completion(result2.finishReason, result2.usage) };
31
+ return;
32
+ }
33
+ const result = await this.delegate.doStream(options);
34
+ const reader = result.stream.getReader();
35
+ const parts = [];
36
+ const text = /* @__PURE__ */ new Map();
37
+ let finished = false;
38
+ try {
39
+ while (true) {
40
+ const next = await reader.read();
41
+ if (next.done) break;
42
+ const item = next.value;
43
+ if (item.type === "error") throw item.error;
44
+ if (item.type === "text-delta" || item.type === "reasoning-delta") {
45
+ const key = `${item.type}:${item.id}`;
46
+ let part = text.get(key);
47
+ if (!part) {
48
+ part = { text: "", ...item.type === "reasoning-delta" ? { thought: true } : {} };
49
+ text.set(key, part);
50
+ parts.push(part);
51
+ }
52
+ part.text += item.delta;
53
+ yield { content: { role: "model", parts: [{ text: item.delta, thought: part.thought }] }, partial: true, turnComplete: false };
54
+ } else if (item.type === "reasoning-end") {
55
+ const signature = item.providerMetadata?.anthropic?.signature;
56
+ const part = text.get(`reasoning-delta:${item.id}`);
57
+ if (part && typeof signature === "string") part.thoughtSignature = signature;
58
+ } else if (item.type === "tool-call" || item.type === "file") {
59
+ parts.push(...outputParts(item));
60
+ } else if (item.type === "finish") {
61
+ finished = true;
62
+ yield { content: { role: "model", parts }, partial: false, turnComplete: true, ...completion(item.finishReason, item.usage) };
63
+ }
64
+ }
65
+ if (!finished) throw new InvocationError("model stream ended without a completion event");
66
+ } finally {
67
+ lifetime.abort();
68
+ reader.releaseLock();
69
+ }
70
+ } finally {
71
+ lifetime.abort();
72
+ }
73
+ }
74
+ };
75
+ function prompt(contents) {
76
+ const result = [];
77
+ const pending = [];
78
+ for (const [index, content] of contents.entries()) {
79
+ const assistant = content.role === "model";
80
+ let group = [];
81
+ const flush = () => {
82
+ if (group.length) result.push(assistant ? { role: "assistant", content: group } : { role: "user", content: group });
83
+ group = [];
84
+ };
85
+ for (const [partIndex, part] of (content.parts ?? []).entries()) {
86
+ if (part.functionCall) {
87
+ const call = part.functionCall;
88
+ if (!assistant || !call.name) throw new ConfigError("ADK functionCall requires a model message and tool name");
89
+ const id = call.id ?? `call-${index}-${partIndex}`;
90
+ pending.push({ id, name: call.name });
91
+ group.push({ type: "tool-call", toolCallId: id, toolName: call.name, input: call.args ?? {} });
92
+ } else if (part.functionResponse) {
93
+ flush();
94
+ const response = part.functionResponse;
95
+ const match = pending.findIndex((call2) => response.id ? call2.id === response.id : call2.name === response.name);
96
+ if (match < 0) throw new ConfigError("ADK functionResponse has no matching functionCall");
97
+ const call = pending.splice(match, 1)[0];
98
+ result.push({ role: "tool", content: [{
99
+ type: "tool-result",
100
+ toolCallId: call.id,
101
+ toolName: call.name,
102
+ output: { type: "text", value: JSON.stringify(response.response ?? {}) }
103
+ }] });
104
+ } else if (part.text !== void 0) {
105
+ if (part.thought && assistant) group.push({
106
+ type: "reasoning",
107
+ text: part.text,
108
+ providerOptions: part.thoughtSignature ? { anthropic: { signature: part.thoughtSignature } } : void 0
109
+ });
110
+ else if (!part.thought) group.push({ type: "text", text: part.text });
111
+ } else if (part.inlineData?.data !== void 0 || part.fileData?.fileUri) {
112
+ const mediaType = part.inlineData?.mimeType ?? part.fileData?.mimeType;
113
+ if (!mediaType) throw new ConfigError("ADK file content requires mimeType");
114
+ group.push({ type: "file", mediaType, data: part.inlineData?.data ?? new URL(part.fileData.fileUri) });
115
+ } else throw new ConfigError("unsupported ADK content part for AgentCore models");
116
+ }
117
+ flush();
118
+ }
119
+ return result;
120
+ }
121
+ function systemText(value) {
122
+ if (typeof value === "string") return value;
123
+ if (Array.isArray(value)) return value.map(systemText).join("\n");
124
+ if ("parts" in value) return (value.parts ?? []).map(systemText).join("\n");
125
+ if ("text" in value && value.text !== void 0) return value.text;
126
+ throw new ConfigError("ADK system instruction must contain text");
127
+ }
128
+ function jsonSchema(value) {
129
+ const schema = structuredClone(value);
130
+ if (typeof schema.type === "string") schema.type = schema.type.toLowerCase();
131
+ for (const key of ["minItems", "maxItems", "minLength", "maxLength", "minProperties", "maxProperties"]) {
132
+ if (typeof schema[key] === "string") schema[key] = Number(schema[key]);
133
+ }
134
+ if (Array.isArray(schema.enum) && (schema.type === "integer" || schema.type === "number")) schema.enum = schema.enum.map(Number);
135
+ if (schema.properties) schema.properties = Object.fromEntries(Object.entries(schema.properties).map(([key, item]) => [key, jsonSchema(item)]));
136
+ if (schema.items) schema.items = jsonSchema(schema.items);
137
+ if (Array.isArray(schema.anyOf)) schema.anyOf = schema.anyOf.map(jsonSchema);
138
+ const nullable = schema.nullable;
139
+ delete schema.nullable;
140
+ delete schema.propertyOrdering;
141
+ return nullable ? { anyOf: [schema, { type: "null" }] } : schema;
142
+ }
143
+ function requestOptions(request, abortSignal) {
144
+ const config = request.config ?? {};
145
+ const messages = prompt(request.contents);
146
+ if (config.systemInstruction) messages.unshift({ role: "system", content: systemText(config.systemInstruction) });
147
+ const allowed = config.toolConfig?.functionCallingConfig?.allowedFunctionNames ?? request.allowedTools;
148
+ const declarations = (config.tools ?? []).flatMap((tool) => {
149
+ if (!("functionDeclarations" in tool)) throw new ConfigError("Gemini built-in tools are not supported by AgentCore model protocols");
150
+ return tool.functionDeclarations ?? [];
151
+ }).filter((tool) => !allowed || allowed.includes(tool.name));
152
+ const functions = declarations.map((tool) => {
153
+ if (!tool.name) throw new ConfigError("ADK function declaration requires a name");
154
+ return {
155
+ type: "function",
156
+ name: tool.name,
157
+ description: tool.description,
158
+ inputSchema: tool.parametersJsonSchema ? structuredClone(tool.parametersJsonSchema) : tool.parameters ? jsonSchema(tool.parameters) : { type: "object", properties: {} }
159
+ };
160
+ });
161
+ const mode = config.toolConfig?.functionCallingConfig?.mode;
162
+ const options = {
163
+ prompt: messages,
164
+ abortSignal,
165
+ maxOutputTokens: config.maxOutputTokens,
166
+ temperature: config.temperature,
167
+ topP: config.topP,
168
+ topK: config.topK,
169
+ stopSequences: config.stopSequences,
170
+ seed: config.seed,
171
+ presencePenalty: config.presencePenalty,
172
+ frequencyPenalty: config.frequencyPenalty,
173
+ tools: functions.length ? functions : void 0,
174
+ toolChoice: mode === "NONE" || allowed?.length === 0 ? { type: "none" } : mode === "ANY" ? { type: "required" } : { type: "auto" }
175
+ };
176
+ if (config.responseMimeType === "application/json" || config.responseJsonSchema || config.responseSchema) {
177
+ options.responseFormat = { type: "json", schema: config.responseJsonSchema ? structuredClone(config.responseJsonSchema) : config.responseSchema ? jsonSchema(config.responseSchema) : void 0 };
178
+ }
179
+ return options;
180
+ }
181
+ function outputParts(item) {
182
+ if (item.type === "text") return [{ text: item.text }];
183
+ if (item.type === "reasoning") {
184
+ const signature = item.providerMetadata?.anthropic?.signature;
185
+ return [{ text: item.text, thought: true, thoughtSignature: typeof signature === "string" ? signature : void 0 }];
186
+ }
187
+ if (item.type === "tool-call") return [{ functionCall: { id: item.toolCallId, name: item.toolName, args: JSON.parse(item.input) } }];
188
+ if (item.type === "file") return [{ inlineData: { mimeType: item.mediaType, data: typeof item.data === "string" ? item.data : Buffer.from(item.data).toString("base64") } }];
189
+ return [];
190
+ }
191
+ function completion(reason, usage) {
192
+ const input = usage.inputTokens.total, output = usage.outputTokens.total;
193
+ return {
194
+ finishReason: reason.unified === "length" ? FinishReason.MAX_TOKENS : reason.unified === "content-filter" ? FinishReason.SAFETY : reason.unified === "stop" || reason.unified === "tool-calls" ? FinishReason.STOP : FinishReason.OTHER,
195
+ ...reason.unified === "error" ? { errorCode: "MODEL_ERROR", errorMessage: "model generation failed" } : {},
196
+ usageMetadata: {
197
+ promptTokenCount: input,
198
+ candidatesTokenCount: output,
199
+ totalTokenCount: input !== void 0 && output !== void 0 ? input + output : void 0,
200
+ cachedContentTokenCount: usage.inputTokens.cacheRead,
201
+ thoughtsTokenCount: usage.outputTokens.reasoning
202
+ }
203
+ };
204
+ }
205
+ export {
206
+ AgentCoreLlm
207
+ };
208
+ //# sourceMappingURL=google-adk-model-N47R7GB2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/integrations/google-adk-model.ts"],"sourcesContent":["import { BaseLlm, type LlmRequest, type LlmResponse } from '@google/adk';\nimport { FinishReason, type Content, type ContentUnion, type Part } from '@google/genai';\nimport type { LanguageModelV3, LanguageModelV3CallOptions, LanguageModelV3Content, LanguageModelV3FinishReason,\n LanguageModelV3Message, LanguageModelV3Prompt, LanguageModelV3Usage } from '@ai-sdk/provider';\nimport type { ModelClient, ProviderModelClient } from '../model';\nimport { ConfigError, InvocationError } from '../errors';\nimport { languageModel } from './ai-sdk';\n\n/** ADK owns the agent loop; AI SDK normalizes native and direct provider models. */\nexport class AgentCoreLlm extends BaseLlm {\n private readonly delegate: LanguageModelV3;\n constructor(client: ModelClient | ProviderModelClient) { super({ model: client.settings.model }); this.delegate = languageModel(client); }\n async connect(): Promise<never> { throw new ConfigError('AgentCore models do not implement ADK bidirectional live connections'); }\n async *generateContentAsync(request: LlmRequest, stream = false, abortSignal?: AbortSignal): AsyncGenerator<LlmResponse> {\n const lifetime = new AbortController();\n const signals = [lifetime.signal, abortSignal, request.config?.abortSignal].filter((value): value is AbortSignal => value !== undefined);\n const options = requestOptions(request, AbortSignal.any(signals));\n try {\n if (!stream) {\n const result = await this.delegate.doGenerate(options);\n yield { content: { role: 'model', parts: result.content.flatMap(outputParts) }, ...completion(result.finishReason, result.usage) };\n return;\n }\n const result = await this.delegate.doStream(options);\n const reader = result.stream.getReader();\n const parts: Part[] = []; const text = new Map<string, Part>(); let finished = false;\n try {\n while (true) {\n const next = await reader.read(); if (next.done) break;\n const item = next.value;\n if (item.type === 'error') throw item.error;\n if (item.type === 'text-delta' || item.type === 'reasoning-delta') {\n const key = `${item.type}:${item.id}`; let part = text.get(key);\n if (!part) { part = { text: '', ...(item.type === 'reasoning-delta' ? { thought: true } : {}) }; text.set(key, part); parts.push(part); }\n part.text += item.delta;\n yield { content: { role: 'model', parts: [{ text: item.delta, thought: part.thought }] }, partial: true, turnComplete: false };\n } else if (item.type === 'reasoning-end') {\n const signature = item.providerMetadata?.anthropic?.signature;\n const part = text.get(`reasoning-delta:${item.id}`);\n if (part && typeof signature === 'string') part.thoughtSignature = signature;\n } else if (item.type === 'tool-call' || item.type === 'file') {\n parts.push(...outputParts(item));\n } else if (item.type === 'finish') {\n finished = true;\n yield { content: { role: 'model', parts }, partial: false, turnComplete: true, ...completion(item.finishReason, item.usage) };\n }\n }\n if (!finished) throw new InvocationError('model stream ended without a completion event');\n } finally { lifetime.abort(); reader.releaseLock(); }\n } finally { lifetime.abort(); }\n }\n}\n\ntype ChatPart = Extract<LanguageModelV3Message, { role: 'assistant' }>['content'][number];\ntype UserPart = Extract<LanguageModelV3Message, { role: 'user' }>['content'][number];\nfunction prompt(contents: Content[]): LanguageModelV3Prompt {\n const result: LanguageModelV3Prompt = []; const pending: { name: string; id: string }[] = [];\n for (const [index, content] of contents.entries()) {\n const assistant = content.role === 'model'; let group: ChatPart[] = [];\n const flush = () => {\n if (group.length) result.push(assistant ? { role: 'assistant', content: group } : { role: 'user', content: group as UserPart[] });\n group = [];\n };\n for (const [partIndex, part] of (content.parts ?? []).entries()) {\n if (part.functionCall) {\n const call = part.functionCall;\n if (!assistant || !call.name) throw new ConfigError('ADK functionCall requires a model message and tool name');\n const id = call.id ?? `call-${index}-${partIndex}`; pending.push({ id, name: call.name });\n group.push({ type: 'tool-call', toolCallId: id, toolName: call.name, input: call.args ?? {} });\n } else if (part.functionResponse) {\n flush(); const response = part.functionResponse;\n const match = pending.findIndex(call => response.id ? call.id === response.id : call.name === response.name);\n if (match < 0) throw new ConfigError('ADK functionResponse has no matching functionCall');\n const call = pending.splice(match, 1)[0]!;\n result.push({ role: 'tool', content: [{ type: 'tool-result', toolCallId: call.id, toolName: call.name,\n output: { type: 'text', value: JSON.stringify(response.response ?? {}) } }] });\n } else if (part.text !== undefined) {\n if (part.thought && assistant) group.push({ type: 'reasoning', text: part.text,\n providerOptions: part.thoughtSignature ? { anthropic: { signature: part.thoughtSignature } } : undefined });\n else if (!part.thought) group.push({ type: 'text', text: part.text });\n } else if (part.inlineData?.data !== undefined || part.fileData?.fileUri) {\n const mediaType = part.inlineData?.mimeType ?? part.fileData?.mimeType;\n if (!mediaType) throw new ConfigError('ADK file content requires mimeType');\n group.push({ type: 'file', mediaType, data: part.inlineData?.data ?? new URL(part.fileData!.fileUri!) });\n } else throw new ConfigError('unsupported ADK content part for AgentCore models');\n }\n flush();\n }\n return result;\n}\nfunction systemText(value: ContentUnion): string {\n if (typeof value === 'string') return value;\n if (Array.isArray(value)) return value.map(systemText).join('\\n');\n if ('parts' in value) return (value.parts ?? []).map(systemText).join('\\n');\n if ('text' in value && value.text !== undefined) return value.text;\n throw new ConfigError('ADK system instruction must contain text');\n}\n/** Translate GenAI's OpenAPI-style Schema; native parametersJsonSchema bypasses this. */\nfunction jsonSchema(value: unknown): Record<string, unknown> {\n const schema = structuredClone(value) as Record<string, unknown>;\n if (typeof schema.type === 'string') schema.type = schema.type.toLowerCase();\n for (const key of ['minItems', 'maxItems', 'minLength', 'maxLength', 'minProperties', 'maxProperties']) {\n if (typeof schema[key] === 'string') schema[key] = Number(schema[key]);\n }\n if (Array.isArray(schema.enum) && (schema.type === 'integer' || schema.type === 'number')) schema.enum = schema.enum.map(Number);\n if (schema.properties) schema.properties = Object.fromEntries(Object.entries(schema.properties).map(([key, item]) => [key, jsonSchema(item)]));\n if (schema.items) schema.items = jsonSchema(schema.items);\n if (Array.isArray(schema.anyOf)) schema.anyOf = schema.anyOf.map(jsonSchema);\n const nullable = schema.nullable; delete schema.nullable; delete schema.propertyOrdering;\n return nullable ? { anyOf: [schema, { type: 'null' }] } : schema;\n}\nfunction requestOptions(request: LlmRequest, abortSignal: AbortSignal): LanguageModelV3CallOptions {\n const config = request.config ?? {};\n const messages = prompt(request.contents);\n if (config.systemInstruction) messages.unshift({ role: 'system', content: systemText(config.systemInstruction) });\n const allowed = config.toolConfig?.functionCallingConfig?.allowedFunctionNames ?? request.allowedTools;\n const declarations = (config.tools ?? []).flatMap(tool => {\n if (!('functionDeclarations' in tool)) throw new ConfigError('Gemini built-in tools are not supported by AgentCore model protocols');\n return tool.functionDeclarations ?? [];\n }).filter(tool => !allowed || allowed.includes(tool.name!));\n const functions = declarations.map(tool => {\n if (!tool.name) throw new ConfigError('ADK function declaration requires a name');\n return { type: 'function' as const, name: tool.name, description: tool.description,\n inputSchema: tool.parametersJsonSchema ? structuredClone(tool.parametersJsonSchema) as Record<string, unknown>\n : tool.parameters ? jsonSchema(tool.parameters) : { type: 'object', properties: {} } };\n });\n const mode = config.toolConfig?.functionCallingConfig?.mode;\n const options: LanguageModelV3CallOptions = { prompt: messages, abortSignal,\n maxOutputTokens: config.maxOutputTokens, temperature: config.temperature, topP: config.topP, topK: config.topK,\n stopSequences: config.stopSequences, seed: config.seed, presencePenalty: config.presencePenalty, frequencyPenalty: config.frequencyPenalty,\n tools: functions.length ? functions : undefined,\n toolChoice: mode === 'NONE' || allowed?.length === 0 ? { type: 'none' } : mode === 'ANY' ? { type: 'required' } : { type: 'auto' },\n };\n if (config.responseMimeType === 'application/json' || config.responseJsonSchema || config.responseSchema) {\n options.responseFormat = { type: 'json', schema: config.responseJsonSchema ? structuredClone(config.responseJsonSchema) as Record<string, unknown>\n : config.responseSchema ? jsonSchema(config.responseSchema) : undefined };\n }\n return options;\n}\nfunction outputParts(item: LanguageModelV3Content): Part[] {\n if (item.type === 'text') return [{ text: item.text }];\n if (item.type === 'reasoning') {\n const signature = item.providerMetadata?.anthropic?.signature;\n return [{ text: item.text, thought: true, thoughtSignature: typeof signature === 'string' ? signature : undefined }];\n }\n if (item.type === 'tool-call') return [{ functionCall: { id: item.toolCallId, name: item.toolName, args: JSON.parse(item.input) } }];\n if (item.type === 'file') return [{ inlineData: { mimeType: item.mediaType, data: typeof item.data === 'string' ? item.data : Buffer.from(item.data).toString('base64') } }];\n return [];\n}\nfunction completion(reason: LanguageModelV3FinishReason, usage: LanguageModelV3Usage): Partial<LlmResponse> {\n const input = usage.inputTokens.total, output = usage.outputTokens.total;\n return { finishReason: reason.unified === 'length' ? FinishReason.MAX_TOKENS : reason.unified === 'content-filter' ? FinishReason.SAFETY\n : reason.unified === 'stop' || reason.unified === 'tool-calls' ? FinishReason.STOP : FinishReason.OTHER,\n ...(reason.unified === 'error' ? { errorCode: 'MODEL_ERROR', errorMessage: 'model generation failed' } : {}),\n usageMetadata: { promptTokenCount: input, candidatesTokenCount: output, totalTokenCount: input !== undefined && output !== undefined ? input + output : undefined,\n cachedContentTokenCount: usage.inputTokens.cacheRead, thoughtsTokenCount: usage.outputTokens.reasoning },\n };\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,eAAkD;AAC3D,SAAS,oBAAgE;AAQlE,IAAM,eAAN,cAA2B,QAAQ;AAAA,EACvB;AAAA,EACjB,YAAY,QAA2C;AAAE,UAAM,EAAE,OAAO,OAAO,SAAS,MAAM,CAAC;AAAG,SAAK,WAAW,cAAc,MAAM;AAAA,EAAG;AAAA,EACzI,MAAM,UAA0B;AAAE,UAAM,IAAI,YAAY,sEAAs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AO,YAAY,WAAW,aAAa,aAAa,OAAO,YAAY,mBAAmB,aAAa,SAC9H,OAAO,YAAY,UAAU,OAAO,YAAY,eAAe,aAAa,OAAO,aAAa;AAAA,IAClG,GAAI,OAAO,YAAY,UAAU,EAAE,WAAW,eAAe,cAAc,0BAA0B,IAAI,CAAC;AAAA,IAC1G,eAAe;AAAA,MAAE,kBAAkB;AAAA,MAAO,sBAAsB;AAAA,MAAQ,iBAAiB,UAAU,UAAa,WAAW,SAAY,QAAQ,SAAS;AAAA,MACtJ,yBAAyB,MAAM,YAAY;AAAA,MAAW,oBAAoB,MAAM,aAAa;AAAA,IAAU;AAAA,EAC3G;AACF;","names":["result","call"]}
@@ -0,0 +1,208 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+ var _chunkS7PWSJNPcjs = require('./chunk-S7PWSJNP.cjs');
4
+ require('./chunk-PC4FM2RP.cjs');
5
+ require('./chunk-ZELRQU4J.cjs');
6
+
7
+
8
+
9
+ var _chunkJSP7ZROScjs = require('./chunk-JSP7ZROS.cjs');
10
+
11
+ // src/integrations/google-adk-model.ts
12
+ var _adk = require('@google/adk');
13
+ var _genai = require('@google/genai');
14
+ var AgentCoreLlm = class extends _adk.BaseLlm {
15
+
16
+ constructor(client) {
17
+ super({ model: client.settings.model });
18
+ this.delegate = _chunkS7PWSJNPcjs.languageModel.call(void 0, client);
19
+ }
20
+ async connect() {
21
+ throw new (0, _chunkJSP7ZROScjs.ConfigError)("AgentCore models do not implement ADK bidirectional live connections");
22
+ }
23
+ async *generateContentAsync(request, stream = false, abortSignal) {
24
+ const lifetime = new AbortController();
25
+ const signals = [lifetime.signal, abortSignal, _optionalChain([request, 'access', _ => _.config, 'optionalAccess', _2 => _2.abortSignal])].filter((value) => value !== void 0);
26
+ const options = requestOptions(request, AbortSignal.any(signals));
27
+ try {
28
+ if (!stream) {
29
+ const result2 = await this.delegate.doGenerate(options);
30
+ yield { content: { role: "model", parts: result2.content.flatMap(outputParts) }, ...completion(result2.finishReason, result2.usage) };
31
+ return;
32
+ }
33
+ const result = await this.delegate.doStream(options);
34
+ const reader = result.stream.getReader();
35
+ const parts = [];
36
+ const text = /* @__PURE__ */ new Map();
37
+ let finished = false;
38
+ try {
39
+ while (true) {
40
+ const next = await reader.read();
41
+ if (next.done) break;
42
+ const item = next.value;
43
+ if (item.type === "error") throw item.error;
44
+ if (item.type === "text-delta" || item.type === "reasoning-delta") {
45
+ const key = `${item.type}:${item.id}`;
46
+ let part = text.get(key);
47
+ if (!part) {
48
+ part = { text: "", ...item.type === "reasoning-delta" ? { thought: true } : {} };
49
+ text.set(key, part);
50
+ parts.push(part);
51
+ }
52
+ part.text += item.delta;
53
+ yield { content: { role: "model", parts: [{ text: item.delta, thought: part.thought }] }, partial: true, turnComplete: false };
54
+ } else if (item.type === "reasoning-end") {
55
+ const signature = _optionalChain([item, 'access', _3 => _3.providerMetadata, 'optionalAccess', _4 => _4.anthropic, 'optionalAccess', _5 => _5.signature]);
56
+ const part = text.get(`reasoning-delta:${item.id}`);
57
+ if (part && typeof signature === "string") part.thoughtSignature = signature;
58
+ } else if (item.type === "tool-call" || item.type === "file") {
59
+ parts.push(...outputParts(item));
60
+ } else if (item.type === "finish") {
61
+ finished = true;
62
+ yield { content: { role: "model", parts }, partial: false, turnComplete: true, ...completion(item.finishReason, item.usage) };
63
+ }
64
+ }
65
+ if (!finished) throw new (0, _chunkJSP7ZROScjs.InvocationError)("model stream ended without a completion event");
66
+ } finally {
67
+ lifetime.abort();
68
+ reader.releaseLock();
69
+ }
70
+ } finally {
71
+ lifetime.abort();
72
+ }
73
+ }
74
+ };
75
+ function prompt(contents) {
76
+ const result = [];
77
+ const pending = [];
78
+ for (const [index, content] of contents.entries()) {
79
+ const assistant = content.role === "model";
80
+ let group = [];
81
+ const flush = () => {
82
+ if (group.length) result.push(assistant ? { role: "assistant", content: group } : { role: "user", content: group });
83
+ group = [];
84
+ };
85
+ for (const [partIndex, part] of (_nullishCoalesce(content.parts, () => ( []))).entries()) {
86
+ if (part.functionCall) {
87
+ const call = part.functionCall;
88
+ if (!assistant || !call.name) throw new (0, _chunkJSP7ZROScjs.ConfigError)("ADK functionCall requires a model message and tool name");
89
+ const id = _nullishCoalesce(call.id, () => ( `call-${index}-${partIndex}`));
90
+ pending.push({ id, name: call.name });
91
+ group.push({ type: "tool-call", toolCallId: id, toolName: call.name, input: _nullishCoalesce(call.args, () => ( {})) });
92
+ } else if (part.functionResponse) {
93
+ flush();
94
+ const response = part.functionResponse;
95
+ const match = pending.findIndex((call2) => response.id ? call2.id === response.id : call2.name === response.name);
96
+ if (match < 0) throw new (0, _chunkJSP7ZROScjs.ConfigError)("ADK functionResponse has no matching functionCall");
97
+ const call = pending.splice(match, 1)[0];
98
+ result.push({ role: "tool", content: [{
99
+ type: "tool-result",
100
+ toolCallId: call.id,
101
+ toolName: call.name,
102
+ output: { type: "text", value: JSON.stringify(_nullishCoalesce(response.response, () => ( {}))) }
103
+ }] });
104
+ } else if (part.text !== void 0) {
105
+ if (part.thought && assistant) group.push({
106
+ type: "reasoning",
107
+ text: part.text,
108
+ providerOptions: part.thoughtSignature ? { anthropic: { signature: part.thoughtSignature } } : void 0
109
+ });
110
+ else if (!part.thought) group.push({ type: "text", text: part.text });
111
+ } else if (_optionalChain([part, 'access', _6 => _6.inlineData, 'optionalAccess', _7 => _7.data]) !== void 0 || _optionalChain([part, 'access', _8 => _8.fileData, 'optionalAccess', _9 => _9.fileUri])) {
112
+ const mediaType = _nullishCoalesce(_optionalChain([part, 'access', _10 => _10.inlineData, 'optionalAccess', _11 => _11.mimeType]), () => ( _optionalChain([part, 'access', _12 => _12.fileData, 'optionalAccess', _13 => _13.mimeType])));
113
+ if (!mediaType) throw new (0, _chunkJSP7ZROScjs.ConfigError)("ADK file content requires mimeType");
114
+ group.push({ type: "file", mediaType, data: _nullishCoalesce(_optionalChain([part, 'access', _14 => _14.inlineData, 'optionalAccess', _15 => _15.data]), () => ( new URL(part.fileData.fileUri))) });
115
+ } else throw new (0, _chunkJSP7ZROScjs.ConfigError)("unsupported ADK content part for AgentCore models");
116
+ }
117
+ flush();
118
+ }
119
+ return result;
120
+ }
121
+ function systemText(value) {
122
+ if (typeof value === "string") return value;
123
+ if (Array.isArray(value)) return value.map(systemText).join("\n");
124
+ if ("parts" in value) return (_nullishCoalesce(value.parts, () => ( []))).map(systemText).join("\n");
125
+ if ("text" in value && value.text !== void 0) return value.text;
126
+ throw new (0, _chunkJSP7ZROScjs.ConfigError)("ADK system instruction must contain text");
127
+ }
128
+ function jsonSchema(value) {
129
+ const schema = structuredClone(value);
130
+ if (typeof schema.type === "string") schema.type = schema.type.toLowerCase();
131
+ for (const key of ["minItems", "maxItems", "minLength", "maxLength", "minProperties", "maxProperties"]) {
132
+ if (typeof schema[key] === "string") schema[key] = Number(schema[key]);
133
+ }
134
+ if (Array.isArray(schema.enum) && (schema.type === "integer" || schema.type === "number")) schema.enum = schema.enum.map(Number);
135
+ if (schema.properties) schema.properties = Object.fromEntries(Object.entries(schema.properties).map(([key, item]) => [key, jsonSchema(item)]));
136
+ if (schema.items) schema.items = jsonSchema(schema.items);
137
+ if (Array.isArray(schema.anyOf)) schema.anyOf = schema.anyOf.map(jsonSchema);
138
+ const nullable = schema.nullable;
139
+ delete schema.nullable;
140
+ delete schema.propertyOrdering;
141
+ return nullable ? { anyOf: [schema, { type: "null" }] } : schema;
142
+ }
143
+ function requestOptions(request, abortSignal) {
144
+ const config = _nullishCoalesce(request.config, () => ( {}));
145
+ const messages = prompt(request.contents);
146
+ if (config.systemInstruction) messages.unshift({ role: "system", content: systemText(config.systemInstruction) });
147
+ const allowed = _nullishCoalesce(_optionalChain([config, 'access', _16 => _16.toolConfig, 'optionalAccess', _17 => _17.functionCallingConfig, 'optionalAccess', _18 => _18.allowedFunctionNames]), () => ( request.allowedTools));
148
+ const declarations = (_nullishCoalesce(config.tools, () => ( []))).flatMap((tool) => {
149
+ if (!("functionDeclarations" in tool)) throw new (0, _chunkJSP7ZROScjs.ConfigError)("Gemini built-in tools are not supported by AgentCore model protocols");
150
+ return _nullishCoalesce(tool.functionDeclarations, () => ( []));
151
+ }).filter((tool) => !allowed || allowed.includes(tool.name));
152
+ const functions = declarations.map((tool) => {
153
+ if (!tool.name) throw new (0, _chunkJSP7ZROScjs.ConfigError)("ADK function declaration requires a name");
154
+ return {
155
+ type: "function",
156
+ name: tool.name,
157
+ description: tool.description,
158
+ inputSchema: tool.parametersJsonSchema ? structuredClone(tool.parametersJsonSchema) : tool.parameters ? jsonSchema(tool.parameters) : { type: "object", properties: {} }
159
+ };
160
+ });
161
+ const mode = _optionalChain([config, 'access', _19 => _19.toolConfig, 'optionalAccess', _20 => _20.functionCallingConfig, 'optionalAccess', _21 => _21.mode]);
162
+ const options = {
163
+ prompt: messages,
164
+ abortSignal,
165
+ maxOutputTokens: config.maxOutputTokens,
166
+ temperature: config.temperature,
167
+ topP: config.topP,
168
+ topK: config.topK,
169
+ stopSequences: config.stopSequences,
170
+ seed: config.seed,
171
+ presencePenalty: config.presencePenalty,
172
+ frequencyPenalty: config.frequencyPenalty,
173
+ tools: functions.length ? functions : void 0,
174
+ toolChoice: mode === "NONE" || _optionalChain([allowed, 'optionalAccess', _22 => _22.length]) === 0 ? { type: "none" } : mode === "ANY" ? { type: "required" } : { type: "auto" }
175
+ };
176
+ if (config.responseMimeType === "application/json" || config.responseJsonSchema || config.responseSchema) {
177
+ options.responseFormat = { type: "json", schema: config.responseJsonSchema ? structuredClone(config.responseJsonSchema) : config.responseSchema ? jsonSchema(config.responseSchema) : void 0 };
178
+ }
179
+ return options;
180
+ }
181
+ function outputParts(item) {
182
+ if (item.type === "text") return [{ text: item.text }];
183
+ if (item.type === "reasoning") {
184
+ const signature = _optionalChain([item, 'access', _23 => _23.providerMetadata, 'optionalAccess', _24 => _24.anthropic, 'optionalAccess', _25 => _25.signature]);
185
+ return [{ text: item.text, thought: true, thoughtSignature: typeof signature === "string" ? signature : void 0 }];
186
+ }
187
+ if (item.type === "tool-call") return [{ functionCall: { id: item.toolCallId, name: item.toolName, args: JSON.parse(item.input) } }];
188
+ if (item.type === "file") return [{ inlineData: { mimeType: item.mediaType, data: typeof item.data === "string" ? item.data : Buffer.from(item.data).toString("base64") } }];
189
+ return [];
190
+ }
191
+ function completion(reason, usage) {
192
+ const input = usage.inputTokens.total, output = usage.outputTokens.total;
193
+ return {
194
+ finishReason: reason.unified === "length" ? _genai.FinishReason.MAX_TOKENS : reason.unified === "content-filter" ? _genai.FinishReason.SAFETY : reason.unified === "stop" || reason.unified === "tool-calls" ? _genai.FinishReason.STOP : _genai.FinishReason.OTHER,
195
+ ...reason.unified === "error" ? { errorCode: "MODEL_ERROR", errorMessage: "model generation failed" } : {},
196
+ usageMetadata: {
197
+ promptTokenCount: input,
198
+ candidatesTokenCount: output,
199
+ totalTokenCount: input !== void 0 && output !== void 0 ? input + output : void 0,
200
+ cachedContentTokenCount: usage.inputTokens.cacheRead,
201
+ thoughtsTokenCount: usage.outputTokens.reasoning
202
+ }
203
+ };
204
+ }
205
+
206
+
207
+ exports.AgentCoreLlm = AgentCoreLlm;
208
+ //# sourceMappingURL=google-adk-model-PDBKY5YZ.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/zhuoguang/Documents/Code/collaborate/hiclaw/agentcore-sdk-nodejs/dist/google-adk-model-PDBKY5YZ.cjs","../src/integrations/google-adk-model.ts"],"names":["result"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC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ACI,IAAA;AAAoB,MAAA;AAAO,MAAA;AAA+C,MAAA;AACvF,MAAA;AAAsD,MAAA;AAAiD,IAAA;AAC3G,EAAA;AACF;AD+CyB;AACA;AACA","file":"/Users/zhuoguang/Documents/Code/collaborate/hiclaw/agentcore-sdk-nodejs/dist/google-adk-model-PDBKY5YZ.cjs","sourcesContent":[null,"import { BaseLlm, type LlmRequest, type LlmResponse } from '@google/adk';\nimport { FinishReason, type Content, type ContentUnion, type Part } from '@google/genai';\nimport type { LanguageModelV3, LanguageModelV3CallOptions, LanguageModelV3Content, LanguageModelV3FinishReason,\n LanguageModelV3Message, LanguageModelV3Prompt, LanguageModelV3Usage } from '@ai-sdk/provider';\nimport type { ModelClient, ProviderModelClient } from '../model';\nimport { ConfigError, InvocationError } from '../errors';\nimport { languageModel } from './ai-sdk';\n\n/** ADK owns the agent loop; AI SDK normalizes native and direct provider models. */\nexport class AgentCoreLlm extends BaseLlm {\n private readonly delegate: LanguageModelV3;\n constructor(client: ModelClient | ProviderModelClient) { super({ model: client.settings.model }); this.delegate = languageModel(client); }\n async connect(): Promise<never> { throw new ConfigError('AgentCore models do not implement ADK bidirectional live connections'); }\n async *generateContentAsync(request: LlmRequest, stream = false, abortSignal?: AbortSignal): AsyncGenerator<LlmResponse> {\n const lifetime = new AbortController();\n const signals = [lifetime.signal, abortSignal, request.config?.abortSignal].filter((value): value is AbortSignal => value !== undefined);\n const options = requestOptions(request, AbortSignal.any(signals));\n try {\n if (!stream) {\n const result = await this.delegate.doGenerate(options);\n yield { content: { role: 'model', parts: result.content.flatMap(outputParts) }, ...completion(result.finishReason, result.usage) };\n return;\n }\n const result = await this.delegate.doStream(options);\n const reader = result.stream.getReader();\n const parts: Part[] = []; const text = new Map<string, Part>(); let finished = false;\n try {\n while (true) {\n const next = await reader.read(); if (next.done) break;\n const item = next.value;\n if (item.type === 'error') throw item.error;\n if (item.type === 'text-delta' || item.type === 'reasoning-delta') {\n const key = `${item.type}:${item.id}`; let part = text.get(key);\n if (!part) { part = { text: '', ...(item.type === 'reasoning-delta' ? { thought: true } : {}) }; text.set(key, part); parts.push(part); }\n part.text += item.delta;\n yield { content: { role: 'model', parts: [{ text: item.delta, thought: part.thought }] }, partial: true, turnComplete: false };\n } else if (item.type === 'reasoning-end') {\n const signature = item.providerMetadata?.anthropic?.signature;\n const part = text.get(`reasoning-delta:${item.id}`);\n if (part && typeof signature === 'string') part.thoughtSignature = signature;\n } else if (item.type === 'tool-call' || item.type === 'file') {\n parts.push(...outputParts(item));\n } else if (item.type === 'finish') {\n finished = true;\n yield { content: { role: 'model', parts }, partial: false, turnComplete: true, ...completion(item.finishReason, item.usage) };\n }\n }\n if (!finished) throw new InvocationError('model stream ended without a completion event');\n } finally { lifetime.abort(); reader.releaseLock(); }\n } finally { lifetime.abort(); }\n }\n}\n\ntype ChatPart = Extract<LanguageModelV3Message, { role: 'assistant' }>['content'][number];\ntype UserPart = Extract<LanguageModelV3Message, { role: 'user' }>['content'][number];\nfunction prompt(contents: Content[]): LanguageModelV3Prompt {\n const result: LanguageModelV3Prompt = []; const pending: { name: string; id: string }[] = [];\n for (const [index, content] of contents.entries()) {\n const assistant = content.role === 'model'; let group: ChatPart[] = [];\n const flush = () => {\n if (group.length) result.push(assistant ? { role: 'assistant', content: group } : { role: 'user', content: group as UserPart[] });\n group = [];\n };\n for (const [partIndex, part] of (content.parts ?? []).entries()) {\n if (part.functionCall) {\n const call = part.functionCall;\n if (!assistant || !call.name) throw new ConfigError('ADK functionCall requires a model message and tool name');\n const id = call.id ?? `call-${index}-${partIndex}`; pending.push({ id, name: call.name });\n group.push({ type: 'tool-call', toolCallId: id, toolName: call.name, input: call.args ?? {} });\n } else if (part.functionResponse) {\n flush(); const response = part.functionResponse;\n const match = pending.findIndex(call => response.id ? call.id === response.id : call.name === response.name);\n if (match < 0) throw new ConfigError('ADK functionResponse has no matching functionCall');\n const call = pending.splice(match, 1)[0]!;\n result.push({ role: 'tool', content: [{ type: 'tool-result', toolCallId: call.id, toolName: call.name,\n output: { type: 'text', value: JSON.stringify(response.response ?? {}) } }] });\n } else if (part.text !== undefined) {\n if (part.thought && assistant) group.push({ type: 'reasoning', text: part.text,\n providerOptions: part.thoughtSignature ? { anthropic: { signature: part.thoughtSignature } } : undefined });\n else if (!part.thought) group.push({ type: 'text', text: part.text });\n } else if (part.inlineData?.data !== undefined || part.fileData?.fileUri) {\n const mediaType = part.inlineData?.mimeType ?? part.fileData?.mimeType;\n if (!mediaType) throw new ConfigError('ADK file content requires mimeType');\n group.push({ type: 'file', mediaType, data: part.inlineData?.data ?? new URL(part.fileData!.fileUri!) });\n } else throw new ConfigError('unsupported ADK content part for AgentCore models');\n }\n flush();\n }\n return result;\n}\nfunction systemText(value: ContentUnion): string {\n if (typeof value === 'string') return value;\n if (Array.isArray(value)) return value.map(systemText).join('\\n');\n if ('parts' in value) return (value.parts ?? []).map(systemText).join('\\n');\n if ('text' in value && value.text !== undefined) return value.text;\n throw new ConfigError('ADK system instruction must contain text');\n}\n/** Translate GenAI's OpenAPI-style Schema; native parametersJsonSchema bypasses this. */\nfunction jsonSchema(value: unknown): Record<string, unknown> {\n const schema = structuredClone(value) as Record<string, unknown>;\n if (typeof schema.type === 'string') schema.type = schema.type.toLowerCase();\n for (const key of ['minItems', 'maxItems', 'minLength', 'maxLength', 'minProperties', 'maxProperties']) {\n if (typeof schema[key] === 'string') schema[key] = Number(schema[key]);\n }\n if (Array.isArray(schema.enum) && (schema.type === 'integer' || schema.type === 'number')) schema.enum = schema.enum.map(Number);\n if (schema.properties) schema.properties = Object.fromEntries(Object.entries(schema.properties).map(([key, item]) => [key, jsonSchema(item)]));\n if (schema.items) schema.items = jsonSchema(schema.items);\n if (Array.isArray(schema.anyOf)) schema.anyOf = schema.anyOf.map(jsonSchema);\n const nullable = schema.nullable; delete schema.nullable; delete schema.propertyOrdering;\n return nullable ? { anyOf: [schema, { type: 'null' }] } : schema;\n}\nfunction requestOptions(request: LlmRequest, abortSignal: AbortSignal): LanguageModelV3CallOptions {\n const config = request.config ?? {};\n const messages = prompt(request.contents);\n if (config.systemInstruction) messages.unshift({ role: 'system', content: systemText(config.systemInstruction) });\n const allowed = config.toolConfig?.functionCallingConfig?.allowedFunctionNames ?? request.allowedTools;\n const declarations = (config.tools ?? []).flatMap(tool => {\n if (!('functionDeclarations' in tool)) throw new ConfigError('Gemini built-in tools are not supported by AgentCore model protocols');\n return tool.functionDeclarations ?? [];\n }).filter(tool => !allowed || allowed.includes(tool.name!));\n const functions = declarations.map(tool => {\n if (!tool.name) throw new ConfigError('ADK function declaration requires a name');\n return { type: 'function' as const, name: tool.name, description: tool.description,\n inputSchema: tool.parametersJsonSchema ? structuredClone(tool.parametersJsonSchema) as Record<string, unknown>\n : tool.parameters ? jsonSchema(tool.parameters) : { type: 'object', properties: {} } };\n });\n const mode = config.toolConfig?.functionCallingConfig?.mode;\n const options: LanguageModelV3CallOptions = { prompt: messages, abortSignal,\n maxOutputTokens: config.maxOutputTokens, temperature: config.temperature, topP: config.topP, topK: config.topK,\n stopSequences: config.stopSequences, seed: config.seed, presencePenalty: config.presencePenalty, frequencyPenalty: config.frequencyPenalty,\n tools: functions.length ? functions : undefined,\n toolChoice: mode === 'NONE' || allowed?.length === 0 ? { type: 'none' } : mode === 'ANY' ? { type: 'required' } : { type: 'auto' },\n };\n if (config.responseMimeType === 'application/json' || config.responseJsonSchema || config.responseSchema) {\n options.responseFormat = { type: 'json', schema: config.responseJsonSchema ? structuredClone(config.responseJsonSchema) as Record<string, unknown>\n : config.responseSchema ? jsonSchema(config.responseSchema) : undefined };\n }\n return options;\n}\nfunction outputParts(item: LanguageModelV3Content): Part[] {\n if (item.type === 'text') return [{ text: item.text }];\n if (item.type === 'reasoning') {\n const signature = item.providerMetadata?.anthropic?.signature;\n return [{ text: item.text, thought: true, thoughtSignature: typeof signature === 'string' ? signature : undefined }];\n }\n if (item.type === 'tool-call') return [{ functionCall: { id: item.toolCallId, name: item.toolName, args: JSON.parse(item.input) } }];\n if (item.type === 'file') return [{ inlineData: { mimeType: item.mediaType, data: typeof item.data === 'string' ? item.data : Buffer.from(item.data).toString('base64') } }];\n return [];\n}\nfunction completion(reason: LanguageModelV3FinishReason, usage: LanguageModelV3Usage): Partial<LlmResponse> {\n const input = usage.inputTokens.total, output = usage.outputTokens.total;\n return { finishReason: reason.unified === 'length' ? FinishReason.MAX_TOKENS : reason.unified === 'content-filter' ? FinishReason.SAFETY\n : reason.unified === 'stop' || reason.unified === 'tool-calls' ? FinishReason.STOP : FinishReason.OTHER,\n ...(reason.unified === 'error' ? { errorCode: 'MODEL_ERROR', errorMessage: 'model generation failed' } : {}),\n usageMetadata: { promptTokenCount: input, candidatesTokenCount: output, totalTokenCount: input !== undefined && output !== undefined ? input + output : undefined,\n cachedContentTokenCount: usage.inputTokens.cacheRead, thoughtsTokenCount: usage.outputTokens.reasoning },\n };\n}\n"]}