@llumiverse/drivers 1.0.0-dev.20260202.145450Z → 1.0.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 (240) hide show
  1. package/lib/cjs/adobe/firefly.js +120 -0
  2. package/lib/cjs/adobe/firefly.js.map +1 -0
  3. package/lib/cjs/azure/azure_foundry.js +432 -0
  4. package/lib/cjs/azure/azure_foundry.js.map +1 -0
  5. package/lib/cjs/bedrock/converse.js +359 -0
  6. package/lib/cjs/bedrock/converse.js.map +1 -0
  7. package/lib/cjs/bedrock/index.js +1441 -0
  8. package/lib/cjs/bedrock/index.js.map +1 -0
  9. package/lib/cjs/bedrock/nova-image-payload.js +207 -0
  10. package/lib/cjs/bedrock/nova-image-payload.js.map +1 -0
  11. package/lib/cjs/bedrock/payloads.js +3 -0
  12. package/lib/cjs/bedrock/payloads.js.map +1 -0
  13. package/lib/cjs/bedrock/s3.js +107 -0
  14. package/lib/cjs/bedrock/s3.js.map +1 -0
  15. package/lib/cjs/bedrock/twelvelabs.js +87 -0
  16. package/lib/cjs/bedrock/twelvelabs.js.map +1 -0
  17. package/lib/cjs/groq/index.js +326 -0
  18. package/lib/cjs/groq/index.js.map +1 -0
  19. package/lib/cjs/huggingface_ie.js +201 -0
  20. package/lib/cjs/huggingface_ie.js.map +1 -0
  21. package/lib/cjs/index.js +31 -0
  22. package/lib/cjs/index.js.map +1 -0
  23. package/lib/cjs/mistral/index.js +176 -0
  24. package/lib/cjs/mistral/index.js.map +1 -0
  25. package/lib/cjs/mistral/types.js +83 -0
  26. package/lib/cjs/mistral/types.js.map +1 -0
  27. package/lib/cjs/openai/azure_openai.js +72 -0
  28. package/lib/cjs/openai/azure_openai.js.map +1 -0
  29. package/lib/cjs/openai/index.js +1100 -0
  30. package/lib/cjs/openai/index.js.map +1 -0
  31. package/lib/cjs/openai/openai.js +21 -0
  32. package/lib/cjs/openai/openai.js.map +1 -0
  33. package/lib/cjs/openai/openai_compatible.js +63 -0
  34. package/lib/cjs/openai/openai_compatible.js.map +1 -0
  35. package/lib/cjs/openai/openai_format.js +131 -0
  36. package/lib/cjs/openai/openai_format.js.map +1 -0
  37. package/lib/cjs/package.json +3 -0
  38. package/lib/cjs/replicate.js +275 -0
  39. package/lib/cjs/replicate.js.map +1 -0
  40. package/lib/cjs/test-driver/TestErrorCompletionStream.js +20 -0
  41. package/lib/cjs/test-driver/TestErrorCompletionStream.js.map +1 -0
  42. package/lib/cjs/test-driver/TestValidationErrorCompletionStream.js +24 -0
  43. package/lib/cjs/test-driver/TestValidationErrorCompletionStream.js.map +1 -0
  44. package/lib/cjs/test-driver/index.js +109 -0
  45. package/lib/cjs/test-driver/index.js.map +1 -0
  46. package/lib/cjs/test-driver/utils.js +30 -0
  47. package/lib/cjs/test-driver/utils.js.map +1 -0
  48. package/lib/cjs/togetherai/index.js +126 -0
  49. package/lib/cjs/togetherai/index.js.map +1 -0
  50. package/lib/cjs/togetherai/interfaces.js +3 -0
  51. package/lib/cjs/togetherai/interfaces.js.map +1 -0
  52. package/lib/cjs/vertexai/debug.js +12 -0
  53. package/lib/cjs/vertexai/debug.js.map +1 -0
  54. package/lib/cjs/vertexai/embeddings/embeddings-image.js +27 -0
  55. package/lib/cjs/vertexai/embeddings/embeddings-image.js.map +1 -0
  56. package/lib/cjs/vertexai/embeddings/embeddings-text.js +23 -0
  57. package/lib/cjs/vertexai/embeddings/embeddings-text.js.map +1 -0
  58. package/lib/cjs/vertexai/index.js +635 -0
  59. package/lib/cjs/vertexai/index.js.map +1 -0
  60. package/lib/cjs/vertexai/models/claude.js +842 -0
  61. package/lib/cjs/vertexai/models/claude.js.map +1 -0
  62. package/lib/cjs/vertexai/models/gemini.js +1110 -0
  63. package/lib/cjs/vertexai/models/gemini.js.map +1 -0
  64. package/lib/cjs/vertexai/models/imagen.js +303 -0
  65. package/lib/cjs/vertexai/models/imagen.js.map +1 -0
  66. package/lib/cjs/vertexai/models/llama.js +183 -0
  67. package/lib/cjs/vertexai/models/llama.js.map +1 -0
  68. package/lib/cjs/vertexai/models.js +35 -0
  69. package/lib/cjs/vertexai/models.js.map +1 -0
  70. package/lib/cjs/watsonx/index.js +161 -0
  71. package/lib/cjs/watsonx/index.js.map +1 -0
  72. package/lib/cjs/watsonx/interfaces.js +3 -0
  73. package/lib/cjs/watsonx/interfaces.js.map +1 -0
  74. package/lib/cjs/xai/index.js +65 -0
  75. package/lib/cjs/xai/index.js.map +1 -0
  76. package/lib/esm/adobe/firefly.js +116 -0
  77. package/lib/esm/adobe/firefly.js.map +1 -0
  78. package/lib/esm/azure/azure_foundry.js +426 -0
  79. package/lib/esm/azure/azure_foundry.js.map +1 -0
  80. package/lib/esm/bedrock/converse.js +352 -0
  81. package/lib/esm/bedrock/converse.js.map +1 -0
  82. package/lib/esm/bedrock/index.js +1434 -0
  83. package/lib/esm/bedrock/index.js.map +1 -0
  84. package/lib/esm/bedrock/nova-image-payload.js +203 -0
  85. package/lib/esm/bedrock/nova-image-payload.js.map +1 -0
  86. package/lib/esm/bedrock/payloads.js +2 -0
  87. package/lib/esm/bedrock/payloads.js.map +1 -0
  88. package/lib/esm/bedrock/s3.js +99 -0
  89. package/lib/esm/bedrock/s3.js.map +1 -0
  90. package/lib/esm/bedrock/twelvelabs.js +84 -0
  91. package/lib/esm/bedrock/twelvelabs.js.map +1 -0
  92. package/lib/esm/groq/index.js +319 -0
  93. package/lib/esm/groq/index.js.map +1 -0
  94. package/lib/esm/huggingface_ie.js +197 -0
  95. package/lib/esm/huggingface_ie.js.map +1 -0
  96. package/lib/esm/index.js +15 -0
  97. package/lib/esm/index.js.map +1 -0
  98. package/lib/esm/mistral/index.js +172 -0
  99. package/lib/esm/mistral/index.js.map +1 -0
  100. package/lib/esm/mistral/types.js +80 -0
  101. package/lib/esm/mistral/types.js.map +1 -0
  102. package/lib/esm/openai/azure_openai.js +68 -0
  103. package/lib/esm/openai/azure_openai.js.map +1 -0
  104. package/lib/esm/openai/index.js +1093 -0
  105. package/lib/esm/openai/index.js.map +1 -0
  106. package/lib/esm/openai/openai.js +14 -0
  107. package/lib/esm/openai/openai.js.map +1 -0
  108. package/lib/esm/openai/openai_compatible.js +56 -0
  109. package/lib/esm/openai/openai_compatible.js.map +1 -0
  110. package/lib/esm/openai/openai_format.js +127 -0
  111. package/lib/esm/openai/openai_format.js.map +1 -0
  112. package/lib/esm/replicate.js +268 -0
  113. package/lib/esm/replicate.js.map +1 -0
  114. package/lib/esm/test-driver/TestErrorCompletionStream.js +16 -0
  115. package/lib/esm/test-driver/TestErrorCompletionStream.js.map +1 -0
  116. package/lib/esm/test-driver/TestValidationErrorCompletionStream.js +20 -0
  117. package/lib/esm/test-driver/TestValidationErrorCompletionStream.js.map +1 -0
  118. package/lib/esm/test-driver/index.js +91 -0
  119. package/lib/esm/test-driver/index.js.map +1 -0
  120. package/lib/esm/test-driver/utils.js +25 -0
  121. package/lib/esm/test-driver/utils.js.map +1 -0
  122. package/lib/esm/togetherai/index.js +122 -0
  123. package/lib/esm/togetherai/index.js.map +1 -0
  124. package/lib/esm/togetherai/interfaces.js +2 -0
  125. package/lib/esm/togetherai/interfaces.js.map +1 -0
  126. package/lib/esm/vertexai/debug.js +6 -0
  127. package/lib/esm/vertexai/debug.js.map +1 -0
  128. package/lib/esm/vertexai/embeddings/embeddings-image.js +24 -0
  129. package/lib/esm/vertexai/embeddings/embeddings-image.js.map +1 -0
  130. package/lib/esm/vertexai/embeddings/embeddings-text.js +20 -0
  131. package/lib/esm/vertexai/embeddings/embeddings-text.js.map +1 -0
  132. package/lib/esm/vertexai/index.js +630 -0
  133. package/lib/esm/vertexai/index.js.map +1 -0
  134. package/lib/esm/vertexai/models/claude.js +833 -0
  135. package/lib/esm/vertexai/models/claude.js.map +1 -0
  136. package/lib/esm/vertexai/models/gemini.js +1104 -0
  137. package/lib/esm/vertexai/models/gemini.js.map +1 -0
  138. package/lib/esm/vertexai/models/imagen.js +299 -0
  139. package/lib/esm/vertexai/models/imagen.js.map +1 -0
  140. package/lib/esm/vertexai/models/llama.js +179 -0
  141. package/lib/esm/vertexai/models/llama.js.map +1 -0
  142. package/lib/esm/vertexai/models.js +32 -0
  143. package/lib/esm/vertexai/models.js.map +1 -0
  144. package/lib/esm/watsonx/index.js +157 -0
  145. package/lib/esm/watsonx/index.js.map +1 -0
  146. package/lib/esm/watsonx/interfaces.js +2 -0
  147. package/lib/esm/watsonx/interfaces.js.map +1 -0
  148. package/lib/esm/xai/index.js +58 -0
  149. package/lib/esm/xai/index.js.map +1 -0
  150. package/lib/types/adobe/firefly.d.ts +30 -0
  151. package/lib/types/adobe/firefly.d.ts.map +1 -0
  152. package/lib/types/azure/azure_foundry.d.ts +52 -0
  153. package/lib/types/azure/azure_foundry.d.ts.map +1 -0
  154. package/lib/types/bedrock/converse.d.ts +8 -0
  155. package/lib/types/bedrock/converse.d.ts.map +1 -0
  156. package/lib/types/bedrock/index.d.ts +135 -0
  157. package/lib/types/bedrock/index.d.ts.map +1 -0
  158. package/lib/types/bedrock/nova-image-payload.d.ts +74 -0
  159. package/lib/types/bedrock/nova-image-payload.d.ts.map +1 -0
  160. package/lib/types/bedrock/payloads.d.ts +12 -0
  161. package/lib/types/bedrock/payloads.d.ts.map +1 -0
  162. package/lib/types/bedrock/s3.d.ts +23 -0
  163. package/lib/types/bedrock/s3.d.ts.map +1 -0
  164. package/lib/types/bedrock/twelvelabs.d.ts +50 -0
  165. package/lib/types/bedrock/twelvelabs.d.ts.map +1 -0
  166. package/lib/types/groq/index.d.ts +27 -0
  167. package/lib/types/groq/index.d.ts.map +1 -0
  168. package/lib/types/huggingface_ie.d.ts +35 -0
  169. package/lib/types/huggingface_ie.d.ts.map +1 -0
  170. package/lib/types/index.d.ts +15 -0
  171. package/lib/types/index.d.ts.map +1 -0
  172. package/lib/types/mistral/index.d.ts +25 -0
  173. package/lib/types/mistral/index.d.ts.map +1 -0
  174. package/lib/types/mistral/types.d.ts +127 -0
  175. package/lib/types/mistral/types.d.ts.map +1 -0
  176. package/lib/types/openai/azure_openai.d.ts +25 -0
  177. package/lib/types/openai/azure_openai.d.ts.map +1 -0
  178. package/lib/types/openai/index.d.ts +126 -0
  179. package/lib/types/openai/index.d.ts.map +1 -0
  180. package/lib/types/openai/openai.d.ts +15 -0
  181. package/lib/types/openai/openai.d.ts.map +1 -0
  182. package/lib/types/openai/openai_compatible.d.ts +31 -0
  183. package/lib/types/openai/openai_compatible.d.ts.map +1 -0
  184. package/lib/types/openai/openai_format.d.ts +21 -0
  185. package/lib/types/openai/openai_format.d.ts.map +1 -0
  186. package/lib/types/replicate.d.ts +48 -0
  187. package/lib/types/replicate.d.ts.map +1 -0
  188. package/lib/types/test-driver/TestErrorCompletionStream.d.ts +9 -0
  189. package/lib/types/test-driver/TestErrorCompletionStream.d.ts.map +1 -0
  190. package/lib/types/test-driver/TestValidationErrorCompletionStream.d.ts +9 -0
  191. package/lib/types/test-driver/TestValidationErrorCompletionStream.d.ts.map +1 -0
  192. package/lib/types/test-driver/index.d.ts +24 -0
  193. package/lib/types/test-driver/index.d.ts.map +1 -0
  194. package/lib/types/test-driver/utils.d.ts +5 -0
  195. package/lib/types/test-driver/utils.d.ts.map +1 -0
  196. package/lib/types/togetherai/index.d.ts +23 -0
  197. package/lib/types/togetherai/index.d.ts.map +1 -0
  198. package/lib/types/togetherai/interfaces.d.ts +96 -0
  199. package/lib/types/togetherai/interfaces.d.ts.map +1 -0
  200. package/lib/types/vertexai/debug.d.ts +2 -0
  201. package/lib/types/vertexai/debug.d.ts.map +1 -0
  202. package/lib/types/vertexai/embeddings/embeddings-image.d.ts +11 -0
  203. package/lib/types/vertexai/embeddings/embeddings-image.d.ts.map +1 -0
  204. package/lib/types/vertexai/embeddings/embeddings-text.d.ts +10 -0
  205. package/lib/types/vertexai/embeddings/embeddings-text.d.ts.map +1 -0
  206. package/lib/types/vertexai/index.d.ts +79 -0
  207. package/lib/types/vertexai/index.d.ts.map +1 -0
  208. package/lib/types/vertexai/models/claude.d.ts +103 -0
  209. package/lib/types/vertexai/models/claude.d.ts.map +1 -0
  210. package/lib/types/vertexai/models/gemini.d.ts +78 -0
  211. package/lib/types/vertexai/models/gemini.d.ts.map +1 -0
  212. package/lib/types/vertexai/models/imagen.d.ts +75 -0
  213. package/lib/types/vertexai/models/imagen.d.ts.map +1 -0
  214. package/lib/types/vertexai/models/llama.d.ts +20 -0
  215. package/lib/types/vertexai/models/llama.d.ts.map +1 -0
  216. package/lib/types/vertexai/models.d.ts +20 -0
  217. package/lib/types/vertexai/models.d.ts.map +1 -0
  218. package/lib/types/watsonx/index.d.ts +27 -0
  219. package/lib/types/watsonx/index.d.ts.map +1 -0
  220. package/lib/types/watsonx/interfaces.d.ts +65 -0
  221. package/lib/types/watsonx/interfaces.d.ts.map +1 -0
  222. package/lib/types/xai/index.d.ts +18 -0
  223. package/lib/types/xai/index.d.ts.map +1 -0
  224. package/package.json +18 -18
  225. package/src/bedrock/converse.ts +85 -10
  226. package/src/bedrock/error-handling.test.ts +352 -0
  227. package/src/bedrock/index.ts +293 -16
  228. package/src/groq/index.ts +9 -4
  229. package/src/mistral/index.ts +25 -22
  230. package/src/mistral/types.ts +0 -5
  231. package/src/openai/error-handling.test.ts +567 -0
  232. package/src/openai/index.ts +513 -33
  233. package/src/openai/openai_compatible.ts +7 -0
  234. package/src/openai/openai_format.ts +1 -1
  235. package/src/vertexai/index.ts +61 -13
  236. package/src/vertexai/models/claude-error-handling.test.ts +432 -0
  237. package/src/vertexai/models/claude.ts +287 -10
  238. package/src/vertexai/models/gemini-error-handling.test.ts +353 -0
  239. package/src/vertexai/models/gemini.ts +329 -52
  240. package/src/vertexai/models.ts +7 -2
@@ -0,0 +1,833 @@
1
+ import { APIConnectionError, APIConnectionTimeoutError, APIError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, PermissionDeniedError, RateLimitError, UnprocessableEntityError, } from '@anthropic-ai/sdk/error';
2
+ import { getConversationMeta, getMaxTokensLimitVertexAi, incrementConversationTurn, LlumiverseError, ModelType, PromptRole, readStreamAsBase64, readStreamAsString, stripBase64ImagesFromConversation, stripHeartbeatsFromConversation, truncateLargeTextInConversation } from "@llumiverse/core";
3
+ import { asyncMap } from "@llumiverse/core/async";
4
+ export const ANTHROPIC_REGIONS = {
5
+ us: "us-east5",
6
+ europe: "europe-west1",
7
+ global: "global",
8
+ };
9
+ export const NON_GLOBAL_ANTHROPIC_MODELS = [
10
+ "claude-3-5",
11
+ "claude-3",
12
+ ];
13
+ function claudeFinishReason(reason) {
14
+ if (!reason)
15
+ return undefined;
16
+ switch (reason) {
17
+ case 'end_turn': return "stop";
18
+ case 'max_tokens': return "length";
19
+ default: return reason; //stop_sequence
20
+ }
21
+ }
22
+ export function collectTools(content) {
23
+ const out = [];
24
+ for (const block of content) {
25
+ if (block.type === "tool_use") {
26
+ out.push({
27
+ id: block.id,
28
+ tool_name: block.name,
29
+ tool_input: block.input,
30
+ });
31
+ }
32
+ }
33
+ return out.length > 0 ? out : undefined;
34
+ }
35
+ function collectAllTextContent(content, includeThoughts = false) {
36
+ const textParts = [];
37
+ // First pass: collect thinking blocks
38
+ if (includeThoughts) {
39
+ for (const block of content) {
40
+ if (block.type === 'thinking' && block.thinking) {
41
+ textParts.push(block.thinking);
42
+ }
43
+ else if (block.type === 'redacted_thinking' && block.data) {
44
+ textParts.push(`[Redacted thinking: ${block.data}]`);
45
+ }
46
+ }
47
+ if (textParts.length > 0) {
48
+ textParts.push(''); // Create a new line after thinking blocks
49
+ }
50
+ }
51
+ // Second pass: collect text blocks
52
+ for (const block of content) {
53
+ if (block.type === 'text' && block.text) {
54
+ textParts.push(block.text);
55
+ }
56
+ }
57
+ return textParts.join('\n');
58
+ }
59
+ //Used to get a max_token value when not specified in the model options. Claude requires it to be set.
60
+ function maxToken(option) {
61
+ const modelOptions = option.model_options;
62
+ if (modelOptions && typeof modelOptions.max_tokens === "number") {
63
+ return modelOptions.max_tokens;
64
+ }
65
+ else {
66
+ let maxSupportedTokens = getMaxTokensLimitVertexAi(option.model);
67
+ // Fallback to the default max tokens limit for the model
68
+ if (option.model.includes('claude-3-7-sonnet') && (modelOptions?.thinking_budget_tokens ?? 0) < 48000) {
69
+ maxSupportedTokens = 64000; // Claude 3.7 can go up to 128k with a beta header, but when no max tokens is specified, we default to 64k.
70
+ }
71
+ return maxSupportedTokens;
72
+ }
73
+ }
74
+ async function collectFileBlocks(segment, restrictedTypes = false) {
75
+ const contentBlocks = [];
76
+ for (const file of segment.files || []) {
77
+ if (file.mime_type?.startsWith("image/")) {
78
+ const allowedTypes = ["image/png", "image/jpeg", "image/gif", "image/webp"];
79
+ if (!allowedTypes.includes(file.mime_type)) {
80
+ throw new Error(`Unsupported image type: ${file.mime_type}`);
81
+ }
82
+ const mimeType = String(file.mime_type);
83
+ contentBlocks.push({
84
+ type: 'image',
85
+ source: {
86
+ type: 'base64',
87
+ data: await readStreamAsBase64(await file.getStream()),
88
+ media_type: mimeType
89
+ }
90
+ });
91
+ }
92
+ else if (!restrictedTypes) {
93
+ if (file.mime_type === "application/pdf") {
94
+ contentBlocks.push({
95
+ title: file.name,
96
+ type: 'document',
97
+ source: {
98
+ type: 'base64',
99
+ data: await readStreamAsBase64(await file.getStream()),
100
+ media_type: 'application/pdf'
101
+ }
102
+ });
103
+ }
104
+ else if (file.mime_type?.startsWith("text/")) {
105
+ contentBlocks.push({
106
+ title: file.name,
107
+ type: 'document',
108
+ source: {
109
+ type: 'text',
110
+ data: await readStreamAsString(await file.getStream()),
111
+ media_type: 'text/plain'
112
+ }
113
+ });
114
+ }
115
+ }
116
+ }
117
+ return contentBlocks;
118
+ }
119
+ export class ClaudeModelDefinition {
120
+ model;
121
+ constructor(modelId) {
122
+ this.model = {
123
+ id: modelId,
124
+ name: modelId,
125
+ provider: 'vertexai',
126
+ type: ModelType.Text,
127
+ can_stream: true,
128
+ };
129
+ }
130
+ async createPrompt(_driver, segments, options) {
131
+ // Convert the prompt to the format expected by the Claude API
132
+ let system = segments
133
+ .filter(segment => segment.role === PromptRole.system)
134
+ .map(segment => ({
135
+ text: segment.content,
136
+ type: 'text'
137
+ }));
138
+ if (options.result_schema) {
139
+ let schemaText = '';
140
+ if (options.tools && options.tools.length > 0) {
141
+ schemaText = "When not calling tools, the answer must be a JSON object using the following JSON Schema:\n" + JSON.stringify(options.result_schema);
142
+ }
143
+ else {
144
+ schemaText = "The answer must be a JSON object using the following JSON Schema:\n" + JSON.stringify(options.result_schema);
145
+ }
146
+ const schemaSegments = {
147
+ text: schemaText,
148
+ type: 'text'
149
+ };
150
+ system.push(schemaSegments);
151
+ }
152
+ let messages = [];
153
+ const safetyMessages = [];
154
+ for (const segment of segments) {
155
+ if (segment.role === PromptRole.system) {
156
+ continue;
157
+ }
158
+ if (segment.role === PromptRole.tool) {
159
+ if (!segment.tool_use_id) {
160
+ throw new Error("Tool prompt segment must have a tool use ID");
161
+ }
162
+ // Build content blocks for tool results (restricted types)
163
+ const contentBlocks = [];
164
+ if (segment.content) {
165
+ contentBlocks.push({
166
+ type: 'text',
167
+ text: segment.content
168
+ });
169
+ }
170
+ // Collect file blocks with type safety
171
+ const fileBlocks = await collectFileBlocks(segment, true);
172
+ contentBlocks.push(...fileBlocks);
173
+ messages.push({
174
+ role: 'user',
175
+ content: [{
176
+ type: 'tool_result',
177
+ tool_use_id: segment.tool_use_id,
178
+ content: contentBlocks,
179
+ }]
180
+ });
181
+ }
182
+ else {
183
+ // Build content blocks for regular messages (all types allowed)
184
+ const contentBlocks = [];
185
+ if (segment.content) {
186
+ contentBlocks.push({
187
+ type: 'text',
188
+ text: segment.content
189
+ });
190
+ }
191
+ // Collect file blocks without restrictions
192
+ const fileBlocks = await collectFileBlocks(segment, false);
193
+ contentBlocks.push(...fileBlocks);
194
+ if (contentBlocks.length === 0) {
195
+ continue; // skip empty segments
196
+ }
197
+ const messageParam = {
198
+ role: segment.role === PromptRole.assistant ? 'assistant' : 'user',
199
+ content: contentBlocks
200
+ };
201
+ if (segment.role === PromptRole.safety) {
202
+ safetyMessages.push(messageParam);
203
+ }
204
+ else {
205
+ messages.push(messageParam);
206
+ }
207
+ }
208
+ }
209
+ messages = messages.concat(safetyMessages);
210
+ if (system && system.length === 0) {
211
+ system = undefined; // If system is empty, set to undefined
212
+ }
213
+ return {
214
+ messages: messages,
215
+ system: system
216
+ };
217
+ }
218
+ async requestTextCompletion(driver, prompt, options) {
219
+ const splits = options.model.split("/");
220
+ let region = undefined;
221
+ if (splits[0] === "locations" && splits.length >= 2) {
222
+ region = splits[1];
223
+ }
224
+ const modelName = splits[splits.length - 1];
225
+ options = { ...options, model: modelName };
226
+ const client = await driver.getAnthropicClient(region);
227
+ options.model_options = options.model_options;
228
+ if (options.model_options?._option_id !== "vertexai-claude") {
229
+ driver.logger.warn({ options: options.model_options }, "Invalid model options");
230
+ }
231
+ let conversation = updateConversation(options.conversation, prompt);
232
+ const { payload, requestOptions } = getClaudePayload(options, conversation);
233
+ // disable streaming, the create function is overloaded so payload type matters.
234
+ const nonStreamingPayload = { ...payload, stream: false };
235
+ const result = await client.messages.create(nonStreamingPayload, requestOptions);
236
+ // Use the new function to collect text content, including thinking if enabled
237
+ const includeThoughts = options.model_options?.include_thoughts ?? false;
238
+ const text = collectAllTextContent(result.content, includeThoughts);
239
+ const tool_use = collectTools(result.content);
240
+ conversation = updateConversation(conversation, createPromptFromResponse(result));
241
+ // Increment turn counter and apply stripping (same pattern as other drivers)
242
+ conversation = incrementConversationTurn(conversation);
243
+ const currentTurn = getConversationMeta(conversation).turnNumber;
244
+ const stripOptions = {
245
+ keepForTurns: options.stripImagesAfterTurns ?? Infinity,
246
+ currentTurn,
247
+ textMaxTokens: options.stripTextMaxTokens,
248
+ };
249
+ let processedConversation = stripBase64ImagesFromConversation(conversation, stripOptions);
250
+ processedConversation = truncateLargeTextInConversation(processedConversation, stripOptions);
251
+ processedConversation = stripHeartbeatsFromConversation(processedConversation, {
252
+ keepForTurns: options.stripHeartbeatsAfterTurns ?? 1,
253
+ currentTurn,
254
+ });
255
+ return {
256
+ result: text ? [{ type: "text", value: text }] : [{ type: "text", value: '' }],
257
+ tool_use,
258
+ token_usage: {
259
+ prompt: result.usage.input_tokens,
260
+ result: result.usage.output_tokens,
261
+ total: result.usage.input_tokens + result.usage.output_tokens
262
+ },
263
+ // make sure we set finish_reason to the correct value (claude is normally setting this by itself)
264
+ finish_reason: tool_use ? "tool_use" : claudeFinishReason(result?.stop_reason ?? ''),
265
+ conversation: processedConversation
266
+ };
267
+ }
268
+ async requestTextCompletionStream(driver, prompt, options) {
269
+ const splits = options.model.split("/");
270
+ let region = undefined;
271
+ if (splits[0] === "locations" && splits.length >= 2) {
272
+ region = splits[1];
273
+ }
274
+ const modelName = splits[splits.length - 1];
275
+ options = { ...options, model: modelName };
276
+ const client = await driver.getAnthropicClient(region);
277
+ const model_options = options.model_options;
278
+ if (model_options?._option_id !== "vertexai-claude") {
279
+ driver.logger.warn({ options: options.model_options }, "Invalid model options");
280
+ }
281
+ // Include conversation history (same as non-streaming)
282
+ const conversation = updateConversation(options.conversation, prompt);
283
+ const { payload, requestOptions } = getClaudePayload(options, conversation);
284
+ const streamingPayload = { ...payload, stream: true };
285
+ const response_stream = await client.messages.stream(streamingPayload, requestOptions);
286
+ // Track current tool use being built from streaming
287
+ let currentToolUse = null;
288
+ const stream = asyncMap(response_stream, async (streamEvent) => {
289
+ switch (streamEvent.type) {
290
+ case "message_start":
291
+ return {
292
+ result: [{ type: "text", value: '' }],
293
+ token_usage: {
294
+ prompt: streamEvent.message.usage.input_tokens,
295
+ result: streamEvent.message.usage.output_tokens
296
+ }
297
+ };
298
+ case "message_delta":
299
+ return {
300
+ result: [{ type: "text", value: '' }],
301
+ token_usage: {
302
+ result: streamEvent.usage.output_tokens
303
+ },
304
+ finish_reason: claudeFinishReason(streamEvent.delta.stop_reason ?? undefined),
305
+ };
306
+ case "content_block_start":
307
+ // Handle tool_use blocks
308
+ if (streamEvent.content_block.type === "tool_use") {
309
+ currentToolUse = {
310
+ id: streamEvent.content_block.id,
311
+ name: streamEvent.content_block.name,
312
+ inputJson: ''
313
+ };
314
+ return {
315
+ result: [],
316
+ tool_use: [{
317
+ id: streamEvent.content_block.id,
318
+ tool_name: streamEvent.content_block.name,
319
+ tool_input: '' // Will be accumulated via input_json_delta
320
+ }]
321
+ };
322
+ }
323
+ // Handle redacted thinking blocks
324
+ if (streamEvent.content_block.type === "redacted_thinking" && model_options?.include_thoughts) {
325
+ return {
326
+ result: [{ type: "text", value: `[Redacted thinking: ${streamEvent.content_block.data}]` }]
327
+ };
328
+ }
329
+ break;
330
+ case "content_block_delta":
331
+ // Handle different delta types
332
+ switch (streamEvent.delta.type) {
333
+ case "text_delta":
334
+ return {
335
+ result: streamEvent.delta.text ? [{ type: "text", value: streamEvent.delta.text }] : []
336
+ };
337
+ case "input_json_delta":
338
+ // Accumulate tool input JSON
339
+ if (currentToolUse && streamEvent.delta.partial_json) {
340
+ return {
341
+ result: [],
342
+ tool_use: [{
343
+ id: currentToolUse.id,
344
+ tool_name: '', // Name already sent in content_block_start
345
+ tool_input: streamEvent.delta.partial_json
346
+ }]
347
+ };
348
+ }
349
+ break;
350
+ case "thinking_delta":
351
+ if (model_options?.include_thoughts) {
352
+ return {
353
+ result: streamEvent.delta.thinking ? [{ type: "text", value: streamEvent.delta.thinking }] : [],
354
+ };
355
+ }
356
+ break;
357
+ case "signature_delta":
358
+ // Signature deltas, signify the end of the thoughts.
359
+ if (model_options?.include_thoughts) {
360
+ return {
361
+ result: [{ type: "text", value: '\n\n' }], // Double newline for more spacing
362
+ };
363
+ }
364
+ break;
365
+ }
366
+ break;
367
+ case "content_block_stop":
368
+ // Reset current tool use tracking when block ends
369
+ if (currentToolUse) {
370
+ currentToolUse = null;
371
+ }
372
+ // Handle the end of content blocks, for redacted thinking blocks
373
+ if (model_options?.include_thoughts) {
374
+ return {
375
+ result: [{ type: "text", value: '\n\n' }] // Add double newline for spacing
376
+ };
377
+ }
378
+ break;
379
+ }
380
+ // Default case for all other event types
381
+ return {
382
+ result: []
383
+ };
384
+ });
385
+ return stream;
386
+ }
387
+ /**
388
+ * Format Anthropic API errors into LlumiverseError with proper status codes and retryability.
389
+ *
390
+ * Anthropic API errors have a specific structure:
391
+ * - APIError.status: HTTP status code (400, 401, 403, 404, 409, 422, 429, 500+)
392
+ * - APIError.error: Nested error object with type and message
393
+ * - APIError.requestID: Request ID for support (can be null)
394
+ *
395
+ * Common error types:
396
+ * - BadRequestError (400): Invalid request parameters
397
+ * - AuthenticationError (401): Authentication required
398
+ * - PermissionDeniedError (403): Insufficient permissions
399
+ * - NotFoundError (404): Resource not found
400
+ * - ConflictError (409): Resource conflict
401
+ * - UnprocessableEntityError (422): Validation error
402
+ * - RateLimitError (429): Rate limit exceeded
403
+ * - InternalServerError (500+): Server-side errors
404
+ * - APIConnectionError: Connection issues (no status code)
405
+ * - APIConnectionTimeoutError: Request timeout (no status code)
406
+ *
407
+ * @see https://docs.anthropic.com/en/api/errors
408
+ */
409
+ formatLlumiverseError(_driver, error, context) {
410
+ // Check if it's an Anthropic API error
411
+ const isAnthropicError = this.isAnthropicApiError(error);
412
+ if (!isAnthropicError) {
413
+ // Not an Anthropic API error, use default handling
414
+ throw error;
415
+ }
416
+ const apiError = error;
417
+ const httpStatusCode = apiError.status;
418
+ // Extract error message and nested error details
419
+ let message = apiError.message || String(error);
420
+ // Extract error type from nested error object if available
421
+ let errorType;
422
+ if (apiError.error && typeof apiError.error === 'object') {
423
+ const nestedError = apiError.error;
424
+ if (nestedError.error && typeof nestedError.error === 'object') {
425
+ errorType = nestedError.error.type;
426
+ // Use the nested error message if it's more specific
427
+ if (nestedError.error.message) {
428
+ message = nestedError.error.message;
429
+ }
430
+ }
431
+ }
432
+ // Build user-facing message with status code
433
+ let userMessage = message;
434
+ // Include status code in message (for end-user visibility)
435
+ if (httpStatusCode) {
436
+ userMessage = `[${httpStatusCode}] ${userMessage}`;
437
+ }
438
+ // Include error type if available
439
+ if (errorType && errorType !== 'error') {
440
+ userMessage = `${errorType}: ${userMessage}`;
441
+ }
442
+ // Add request ID if available (useful for Anthropic support)
443
+ if (apiError.requestID) {
444
+ userMessage += ` (Request ID: ${apiError.requestID})`;
445
+ }
446
+ // Determine retryability based on Anthropic error types
447
+ const retryable = this.isClaudeErrorRetryable(error, httpStatusCode, errorType);
448
+ // Use the error constructor name as the error name
449
+ const errorName = error.constructor?.name || 'AnthropicError';
450
+ return new LlumiverseError(`[${context.provider}] ${userMessage}`, retryable, context, error, httpStatusCode, errorName);
451
+ }
452
+ /**
453
+ * Type guard to check if error is an Anthropic API error.
454
+ */
455
+ isAnthropicApiError(error) {
456
+ return (error !== null &&
457
+ typeof error === 'object' &&
458
+ error instanceof APIError);
459
+ }
460
+ /**
461
+ * Determine if an Anthropic API error is retryable.
462
+ *
463
+ * Retryable errors:
464
+ * - RateLimitError (429): Rate limit exceeded, retry with backoff
465
+ * - InternalServerError (500+): Server-side errors
466
+ * - APIConnectionTimeoutError: Request timeout
467
+ * - 408 (Request Timeout): Request timeout
468
+ * - 529 (Overloaded): Service overloaded
469
+ *
470
+ * Non-retryable errors:
471
+ * - BadRequestError (400): Invalid request parameters
472
+ * - AuthenticationError (401): Authentication failure
473
+ * - PermissionDeniedError (403): Insufficient permissions
474
+ * - NotFoundError (404): Resource not found
475
+ * - ConflictError (409): Resource conflict
476
+ * - UnprocessableEntityError (422): Validation error
477
+ * - Other 4xx client errors
478
+ * - invalid_request_error: Invalid request structure
479
+ *
480
+ * @param error - The error object
481
+ * @param httpStatusCode - The HTTP status code if available
482
+ * @param errorType - The nested error type if available
483
+ * @returns True if retryable, false if not retryable, undefined if unknown
484
+ */
485
+ isClaudeErrorRetryable(error, httpStatusCode, errorType) {
486
+ // Check specific Anthropic error types by class
487
+ if (error instanceof RateLimitError)
488
+ return true;
489
+ if (error instanceof InternalServerError)
490
+ return true;
491
+ if (error instanceof APIConnectionTimeoutError)
492
+ return true;
493
+ // Non-retryable by error type
494
+ if (error instanceof BadRequestError)
495
+ return false;
496
+ if (error instanceof AuthenticationError)
497
+ return false;
498
+ if (error instanceof PermissionDeniedError)
499
+ return false;
500
+ if (error instanceof NotFoundError)
501
+ return false;
502
+ if (error instanceof ConflictError)
503
+ return false;
504
+ if (error instanceof UnprocessableEntityError)
505
+ return false;
506
+ // Check nested error type
507
+ if (errorType === 'invalid_request_error')
508
+ return false;
509
+ // Use HTTP status code
510
+ if (httpStatusCode !== undefined) {
511
+ if (httpStatusCode === 429)
512
+ return true; // Rate limit
513
+ if (httpStatusCode === 408)
514
+ return true; // Request timeout
515
+ if (httpStatusCode === 529)
516
+ return true; // Overloaded
517
+ if (httpStatusCode >= 500 && httpStatusCode < 600)
518
+ return true; // Server errors
519
+ if (httpStatusCode >= 400 && httpStatusCode < 500)
520
+ return false; // Client errors
521
+ }
522
+ // Connection errors without status codes
523
+ if (error instanceof APIConnectionError && !(error instanceof APIConnectionTimeoutError)) {
524
+ // Generic connection errors might be retryable (network issues)
525
+ return true;
526
+ }
527
+ // Unknown error type - let consumer decide retry strategy
528
+ return undefined;
529
+ }
530
+ }
531
+ function createPromptFromResponse(response) {
532
+ return {
533
+ messages: [{
534
+ role: response.role,
535
+ content: response.content,
536
+ }],
537
+ system: undefined
538
+ };
539
+ }
540
+ /**
541
+ * Merge consecutive user messages in the conversation.
542
+ * This is required because Anthropic's API expects all tool_result blocks
543
+ * from a single assistant turn to be in one user message.
544
+ * When multiple tool results are added as separate user messages,
545
+ * we need to merge them before sending to the API.
546
+ */
547
+ export function mergeConsecutiveUserMessages(messages) {
548
+ if (messages.length === 0)
549
+ return [];
550
+ // Check if any merging is needed
551
+ const needsMerging = messages.some((msg, i) => i < messages.length - 1 &&
552
+ msg.role === 'user' &&
553
+ messages[i + 1].role === 'user');
554
+ if (!needsMerging) {
555
+ return messages;
556
+ }
557
+ const result = [];
558
+ let i = 0;
559
+ while (i < messages.length) {
560
+ const current = messages[i];
561
+ if (current.role === 'user') {
562
+ // Collect all consecutive user messages
563
+ const mergedContent = [];
564
+ while (i < messages.length && messages[i].role === 'user') {
565
+ const userMsg = messages[i];
566
+ if (Array.isArray(userMsg.content)) {
567
+ mergedContent.push(...userMsg.content);
568
+ }
569
+ else if (typeof userMsg.content === 'string') {
570
+ mergedContent.push({ type: 'text', text: userMsg.content });
571
+ }
572
+ i++;
573
+ }
574
+ result.push({
575
+ role: 'user',
576
+ content: mergedContent
577
+ });
578
+ }
579
+ else {
580
+ result.push(current);
581
+ i++;
582
+ }
583
+ }
584
+ return result;
585
+ }
586
+ /**
587
+ * Update the conversation messages
588
+ * @param prompt
589
+ * @param response
590
+ * @returns
591
+ */
592
+ function updateConversation(conversation, prompt) {
593
+ const baseSystemMessages = conversation?.system || [];
594
+ const baseMessages = conversation?.messages || [];
595
+ const system = baseSystemMessages.concat(prompt.system || []);
596
+ // Merge consecutive user messages to ensure tool_result blocks are properly grouped
597
+ const mergedMessages = mergeConsecutiveUserMessages(baseMessages.concat(prompt.messages || []));
598
+ return {
599
+ messages: mergedMessages,
600
+ system: system.length > 0 ? system : undefined // If system is empty, set to undefined
601
+ };
602
+ }
603
+ /**
604
+ * Sanitize messages by removing empty text blocks.
605
+ * Claude API rejects messages with empty text content blocks ("text content blocks must be non-empty").
606
+ * This handles cases where streaming was interrupted and left empty text blocks.
607
+ *
608
+ * - Filters out empty text blocks from each message's content
609
+ * - Removes messages entirely if they have no content after filtering
610
+ */
611
+ function sanitizeMessages(messages) {
612
+ const result = [];
613
+ for (const message of messages) {
614
+ if (typeof message.content === 'string') {
615
+ // String content - keep only if non-empty
616
+ if (message.content.trim()) {
617
+ result.push(message);
618
+ }
619
+ continue;
620
+ }
621
+ // Array content - filter out empty text blocks
622
+ const filteredContent = message.content.filter(block => {
623
+ if (block.type === 'text') {
624
+ return block.text && block.text.trim().length > 0;
625
+ }
626
+ // Keep all non-text blocks (tool_use, tool_result, image, etc.)
627
+ return true;
628
+ });
629
+ // Only include message if it has content after filtering
630
+ if (filteredContent.length > 0) {
631
+ result.push({
632
+ ...message,
633
+ content: filteredContent
634
+ });
635
+ }
636
+ }
637
+ return result;
638
+ }
639
+ /**
640
+ * Fix orphaned tool_use blocks in the conversation.
641
+ * @exported for testing
642
+ *
643
+ * When an agent is stopped mid-tool-execution, the assistant message contains tool_use blocks
644
+ * but no corresponding tool_result was added. The Anthropic API requires that every tool_use
645
+ * must be followed by a tool_result in the next user message.
646
+ *
647
+ * This function detects such cases and injects synthetic tool_result blocks indicating
648
+ * the tools were interrupted, allowing the conversation to continue.
649
+ */
650
+ export function fixOrphanedToolUse(messages) {
651
+ if (messages.length < 2)
652
+ return messages;
653
+ const result = [];
654
+ for (let i = 0; i < messages.length; i++) {
655
+ const current = messages[i];
656
+ result.push(current);
657
+ // Check if this is an assistant message with tool_use blocks
658
+ if (current.role === 'assistant' && Array.isArray(current.content)) {
659
+ const toolUseBlocks = current.content.filter((block) => block.type === 'tool_use');
660
+ if (toolUseBlocks.length > 0) {
661
+ // Check if the next message is a user message with matching tool_results
662
+ const nextMessage = messages[i + 1];
663
+ if (nextMessage && nextMessage.role === 'user' && Array.isArray(nextMessage.content)) {
664
+ // Get tool_result IDs from the next message
665
+ const toolResultIds = new Set(nextMessage.content
666
+ .filter((block) => block.type === 'tool_result')
667
+ .map(block => block.tool_use_id));
668
+ // Find orphaned tool_use blocks (no matching tool_result)
669
+ const orphanedToolUse = toolUseBlocks.filter(block => !toolResultIds.has(block.id));
670
+ if (orphanedToolUse.length > 0) {
671
+ // Inject synthetic tool_results for orphaned tool_use
672
+ const syntheticResults = orphanedToolUse.map(block => ({
673
+ type: 'tool_result',
674
+ tool_use_id: block.id,
675
+ content: `[Tool interrupted: The user stopped the operation before "${block.name}" could execute.]`
676
+ }));
677
+ // Prepend synthetic results to the next user message
678
+ const updatedNextMessage = {
679
+ ...nextMessage,
680
+ content: [...syntheticResults, ...nextMessage.content]
681
+ };
682
+ // Replace the next message in our iteration
683
+ messages[i + 1] = updatedNextMessage;
684
+ }
685
+ }
686
+ else if (nextMessage && nextMessage.role === 'user') {
687
+ // Next message is a user message but not array content (plain text)
688
+ // We need to convert it and add tool_results
689
+ const syntheticResults = toolUseBlocks.map(block => ({
690
+ type: 'tool_result',
691
+ tool_use_id: block.id,
692
+ content: `[Tool interrupted: The user stopped the operation before "${block.name}" could execute.]`
693
+ }));
694
+ const textContent = typeof nextMessage.content === 'string'
695
+ ? { type: 'text', text: nextMessage.content }
696
+ : { type: 'text', text: '' };
697
+ const updatedNextMessage = {
698
+ role: 'user',
699
+ content: [...syntheticResults, textContent]
700
+ };
701
+ messages[i + 1] = updatedNextMessage;
702
+ }
703
+ // Note: If there's no nextMessage, we leave the conversation as-is.
704
+ // The tool_use blocks are expected to be there - the next turn will provide tool_results.
705
+ }
706
+ }
707
+ }
708
+ return result;
709
+ }
710
+ function getClaudePayload(options, prompt) {
711
+ const modelName = options.model; // Model name is already extracted in the calling methods
712
+ const model_options = options.model_options;
713
+ // Add beta header for Claude 3.7 models to enable 128k output tokens
714
+ let requestOptions = undefined;
715
+ if (modelName.includes('claude-3-7-sonnet') &&
716
+ ((model_options?.max_tokens ?? 0) > 64000 || (model_options?.thinking_budget_tokens ?? 0) > 64000)) {
717
+ requestOptions = {
718
+ headers: {
719
+ 'anthropic-beta': 'output-128k-2025-02-19'
720
+ }
721
+ };
722
+ }
723
+ // Fix orphaned tool_use blocks (can occur when agent is stopped mid-tool-execution)
724
+ const fixedMessages = fixOrphanedToolUse(prompt.messages);
725
+ // Sanitize messages to remove empty text blocks (can occur from interrupted streaming)
726
+ let sanitizedMessages = sanitizeMessages(fixedMessages);
727
+ // Validate tools have input_schema.type set to 'object' as required by the Anthropic SDK
728
+ if (options.tools) {
729
+ for (const tool of options.tools) {
730
+ if (tool.input_schema.type !== 'object') {
731
+ throw new Error(`Tool "${tool.name}" has invalid input_schema.type: expected "object", got "${tool.input_schema.type}"`);
732
+ }
733
+ }
734
+ }
735
+ // When no tools are provided but conversation contains tool_use/tool_result blocks
736
+ // (e.g. checkpoint summary calls), convert tool blocks to text to avoid API errors
737
+ const hasTools = options.tools && options.tools.length > 0;
738
+ if (!hasTools && claudeMessagesContainToolBlocks(sanitizedMessages)) {
739
+ sanitizedMessages = convertClaudeToolBlocksToText(sanitizedMessages);
740
+ }
741
+ const payload = {
742
+ messages: sanitizedMessages,
743
+ system: prompt.system,
744
+ tools: hasTools ? options.tools : undefined,
745
+ temperature: model_options?.temperature,
746
+ model: modelName,
747
+ max_tokens: maxToken(options),
748
+ top_p: model_options?.temperature != null ? undefined : model_options?.top_p,
749
+ top_k: model_options?.top_k,
750
+ stop_sequences: model_options?.stop_sequence,
751
+ thinking: model_options?.thinking_mode ?
752
+ {
753
+ budget_tokens: model_options?.thinking_budget_tokens ?? 1024,
754
+ type: "enabled"
755
+ } : {
756
+ type: "disabled"
757
+ }
758
+ };
759
+ return { payload, requestOptions };
760
+ }
761
+ /**
762
+ * Checks whether any Claude message contains tool_use or tool_result content blocks.
763
+ */
764
+ export function claudeMessagesContainToolBlocks(messages) {
765
+ for (const msg of messages) {
766
+ if (!Array.isArray(msg.content))
767
+ continue;
768
+ for (const block of msg.content) {
769
+ if (typeof block === 'object' && block !== null && 'type' in block) {
770
+ if (block.type === 'tool_use' || block.type === 'tool_result')
771
+ return true;
772
+ }
773
+ }
774
+ }
775
+ return false;
776
+ }
777
+ /**
778
+ * Converts tool_use and tool_result blocks to text in Claude messages.
779
+ * Preserves tool call information while removing structured blocks that
780
+ * require tools to be defined in the API request.
781
+ */
782
+ export function convertClaudeToolBlocksToText(messages) {
783
+ return messages.map(msg => {
784
+ if (!Array.isArray(msg.content))
785
+ return msg;
786
+ let hasToolBlocks = false;
787
+ for (const block of msg.content) {
788
+ if (typeof block === 'object' && block !== null && 'type' in block &&
789
+ (block.type === 'tool_use' || block.type === 'tool_result')) {
790
+ hasToolBlocks = true;
791
+ break;
792
+ }
793
+ }
794
+ if (!hasToolBlocks)
795
+ return msg;
796
+ const newContent = [];
797
+ for (const block of msg.content) {
798
+ if (typeof block === 'string') {
799
+ newContent.push(block);
800
+ continue;
801
+ }
802
+ if (block.type === 'tool_use') {
803
+ const inputStr = block.input ? JSON.stringify(block.input) : '';
804
+ const truncated = inputStr.length > 500 ? inputStr.substring(0, 500) + '...' : inputStr;
805
+ newContent.push({
806
+ type: 'text',
807
+ text: `[Tool call: ${block.name}(${truncated})]`,
808
+ });
809
+ }
810
+ else if (block.type === 'tool_result') {
811
+ let resultStr = 'No content';
812
+ if (typeof block.content === 'string') {
813
+ resultStr = block.content.length > 500 ? block.content.substring(0, 500) + '...' : block.content;
814
+ }
815
+ else if (Array.isArray(block.content)) {
816
+ const texts = block.content
817
+ .filter((c) => c.type === 'text')
818
+ .map(c => c.text.length > 500 ? c.text.substring(0, 500) + '...' : c.text);
819
+ resultStr = texts.join('\n') || 'No text content';
820
+ }
821
+ newContent.push({
822
+ type: 'text',
823
+ text: `[Tool result: ${resultStr}]`,
824
+ });
825
+ }
826
+ else {
827
+ newContent.push(block);
828
+ }
829
+ }
830
+ return { ...msg, content: newContent };
831
+ });
832
+ }
833
+ //# sourceMappingURL=claude.js.map