@raindrop-ai/ai-sdk 0.0.2 → 0.0.4

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.
@@ -84,7 +84,7 @@ async function postJson(url, body, headers, opts) {
84
84
  // package.json
85
85
  var package_default = {
86
86
  name: "@raindrop-ai/ai-sdk",
87
- version: "0.0.2"};
87
+ version: "0.0.4"};
88
88
 
89
89
  // src/internal/version.ts
90
90
  var libraryName = package_default.name;
@@ -131,19 +131,30 @@ var EventShipper = class {
131
131
  return this.debug;
132
132
  }
133
133
  async patch(eventId, patch) {
134
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
134
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
135
135
  if (!this.enabled) return;
136
136
  if (!eventId) return;
137
- const sticky = (_a = this.sticky.get(eventId)) != null ? _a : {};
138
- const existing = (_b = this.buffers.get(eventId)) != null ? _b : {};
137
+ if (this.debug) {
138
+ console.log("[raindrop-ai/ai-sdk] queue patch", {
139
+ eventId,
140
+ userId: patch.userId,
141
+ eventName: patch.eventName,
142
+ hasInput: typeof patch.input === "string" && patch.input.length > 0,
143
+ hasOutput: typeof patch.output === "string" && patch.output.length > 0,
144
+ attachments: (_b = (_a = patch.attachments) == null ? void 0 : _a.length) != null ? _b : 0,
145
+ isPending: patch.isPending
146
+ });
147
+ }
148
+ const sticky = (_c = this.sticky.get(eventId)) != null ? _c : {};
149
+ const existing = (_d = this.buffers.get(eventId)) != null ? _d : {};
139
150
  const merged = mergePatches(existing, patch);
140
- merged.isPending = (_e = (_d = (_c = patch.isPending) != null ? _c : existing.isPending) != null ? _d : sticky.isPending) != null ? _e : true;
151
+ merged.isPending = (_g = (_f = (_e = patch.isPending) != null ? _e : existing.isPending) != null ? _f : sticky.isPending) != null ? _g : true;
141
152
  this.buffers.set(eventId, merged);
142
153
  this.sticky.set(eventId, {
143
- userId: (_f = merged.userId) != null ? _f : sticky.userId,
144
- convoId: (_g = merged.convoId) != null ? _g : sticky.convoId,
145
- eventName: (_h = merged.eventName) != null ? _h : sticky.eventName,
146
- isPending: (_i = merged.isPending) != null ? _i : sticky.isPending
154
+ userId: (_h = merged.userId) != null ? _h : sticky.userId,
155
+ convoId: (_i = merged.convoId) != null ? _i : sticky.convoId,
156
+ eventName: (_j = merged.eventName) != null ? _j : sticky.eventName,
157
+ isPending: (_k = merged.isPending) != null ? _k : sticky.isPending
147
158
  });
148
159
  const t = this.timers.get(eventId);
149
160
  if (t) clearTimeout(t);
@@ -240,7 +251,7 @@ var EventShipper = class {
240
251
  }
241
252
  }
242
253
  async flushOne(eventId) {
243
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
254
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
244
255
  if (!this.enabled) return;
245
256
  const timer = this.timers.get(eventId);
246
257
  if (timer) {
@@ -278,6 +289,24 @@ var EventShipper = class {
278
289
  is_pending: ((_i = (_h = accumulated.isPending) != null ? _h : sticky.isPending) != null ? _i : true) !== false
279
290
  };
280
291
  const url = `${this.baseUrl}events/track_partial`;
292
+ if (this.debug) {
293
+ console.log("[raindrop-ai/ai-sdk] sending track_partial", {
294
+ eventId,
295
+ eventName,
296
+ userId,
297
+ isPending: payload.is_pending,
298
+ inputPreview: typeof accumulated.input === "string" ? accumulated.input.slice(0, 120) : void 0,
299
+ outputPreview: typeof accumulated.output === "string" ? accumulated.output.slice(0, 120) : void 0,
300
+ attachments: (_k = (_j = accumulated.attachments) == null ? void 0 : _j.length) != null ? _k : 0,
301
+ attachmentKinds: (_m = (_l = accumulated.attachments) == null ? void 0 : _l.map((a) => ({
302
+ type: a.type,
303
+ role: a.role,
304
+ name: a.name,
305
+ valuePreview: a.value.slice(0, 60)
306
+ }))) != null ? _m : [],
307
+ endpoint: url
308
+ });
309
+ }
281
310
  const p = postJson(
282
311
  url,
283
312
  payload,
@@ -520,6 +549,12 @@ var TraceShipper = class {
520
549
  const batch = this.queue.splice(0, this.maxBatchSize);
521
550
  const body = buildExportTraceServiceRequest(batch);
522
551
  const url = `${this.baseUrl}traces`;
552
+ if (this.debug) {
553
+ console.log("[raindrop-ai/ai-sdk] sending traces batch", {
554
+ spans: batch.length,
555
+ endpoint: url
556
+ });
557
+ }
523
558
  const p = postJson(
524
559
  url,
525
560
  body,
@@ -847,7 +882,13 @@ function isAgentClass(value) {
847
882
  function extractModel(result) {
848
883
  if (!isRecord(result)) return void 0;
849
884
  const model = result["model"];
850
- return typeof model === "string" && model.length ? model : void 0;
885
+ if (typeof model === "string" && model.length) return model;
886
+ const response = result["response"];
887
+ if (isRecord(response)) {
888
+ const modelId = response["modelId"];
889
+ if (typeof modelId === "string" && modelId.length) return modelId;
890
+ }
891
+ return void 0;
851
892
  }
852
893
  function extractFinishReason(result) {
853
894
  if (!isRecord(result)) return void 0;
@@ -857,6 +898,174 @@ function extractFinishReason(result) {
857
898
  }
858
899
  return void 0;
859
900
  }
901
+ function bytesToBase64(bytes) {
902
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
903
+ let binary = "";
904
+ for (let i = 0; i < bytes.length; i++) {
905
+ binary += String.fromCharCode(bytes[i]);
906
+ }
907
+ if (typeof btoa === "function") return btoa(binary);
908
+ return "";
909
+ }
910
+ function asDataUrl(value, mediaType) {
911
+ if (value instanceof URL) return value.toString();
912
+ if (typeof value === "string") {
913
+ if (value.startsWith("data:")) return value;
914
+ if (value.startsWith("http://") || value.startsWith("https://")) return value;
915
+ return `data:${mediaType};base64,${value}`;
916
+ }
917
+ if (value instanceof Uint8Array) {
918
+ const base64 = bytesToBase64(value);
919
+ if (!base64) return void 0;
920
+ return `data:${mediaType};base64,${base64}`;
921
+ }
922
+ if (value instanceof ArrayBuffer) {
923
+ const base64 = bytesToBase64(new Uint8Array(value));
924
+ if (!base64) return void 0;
925
+ return `data:${mediaType};base64,${base64}`;
926
+ }
927
+ return void 0;
928
+ }
929
+ function dataPartToAttachmentValue(value) {
930
+ if (typeof value === "string") return value;
931
+ if (value instanceof URL) return value.toString();
932
+ if (value instanceof Uint8Array) return `[binary:${value.byteLength} bytes]`;
933
+ if (value instanceof ArrayBuffer) return `[binary:${value.byteLength} bytes]`;
934
+ return void 0;
935
+ }
936
+ function attachmentMediaType(part) {
937
+ if (typeof part["mediaType"] === "string") return part["mediaType"];
938
+ if (typeof part["mimeType"] === "string") return part["mimeType"];
939
+ const file = part["file"];
940
+ if (isRecord(file)) {
941
+ if (typeof file["mediaType"] === "string") return file["mediaType"];
942
+ if (typeof file["mimeType"] === "string") return file["mimeType"];
943
+ }
944
+ return void 0;
945
+ }
946
+ function attachmentName(part) {
947
+ if (typeof part["filename"] === "string") return part["filename"];
948
+ if (typeof part["name"] === "string") return part["name"];
949
+ const file = part["file"];
950
+ if (isRecord(file)) {
951
+ if (typeof file["filename"] === "string") return file["filename"];
952
+ if (typeof file["name"] === "string") return file["name"];
953
+ }
954
+ return void 0;
955
+ }
956
+ function attachmentData(part) {
957
+ if ("data" in part) return part["data"];
958
+ const file = part["file"];
959
+ if (isRecord(file)) {
960
+ if ("file_data" in file) return file["file_data"];
961
+ if ("data" in file) return file["data"];
962
+ }
963
+ return void 0;
964
+ }
965
+ function contentPartToAttachment(part, role) {
966
+ var _a, _b, _c;
967
+ const partType = part["type"];
968
+ if (typeof partType !== "string") return void 0;
969
+ if (partType === "image") {
970
+ const mediaType = (_a = attachmentMediaType(part)) != null ? _a : "image/png";
971
+ const value = asDataUrl(part["image"], mediaType);
972
+ if (!value) return void 0;
973
+ return { type: "image", role, value };
974
+ }
975
+ if (partType === "image_url") {
976
+ const imageUrlPart = part["image_url"];
977
+ const imageUrlValue = isRecord(imageUrlPart) ? imageUrlPart["url"] : imageUrlPart;
978
+ const value = asDataUrl(imageUrlValue, "image/png");
979
+ if (!value) return void 0;
980
+ return { type: "image", role, value };
981
+ }
982
+ if (partType === "file") {
983
+ const mediaType = attachmentMediaType(part);
984
+ const data = attachmentData(part);
985
+ const isImage = (mediaType == null ? void 0 : mediaType.startsWith("image/")) === true;
986
+ const value = isImage && mediaType ? asDataUrl(data, mediaType) : dataPartToAttachmentValue(data);
987
+ if (!value) return void 0;
988
+ const name = (_c = (_b = attachmentName(part)) != null ? _b : mediaType) != null ? _c : "file";
989
+ return { type: isImage ? "image" : "text", role, name, value };
990
+ }
991
+ return void 0;
992
+ }
993
+ function attachmentsFromContent(content, role) {
994
+ if (!Array.isArray(content)) return void 0;
995
+ const attachments = [];
996
+ for (const part of content) {
997
+ if (!isRecord(part)) continue;
998
+ const attachment = contentPartToAttachment(part, role);
999
+ if (attachment) attachments.push(attachment);
1000
+ }
1001
+ return attachments.length ? attachments : void 0;
1002
+ }
1003
+ function generatedFileToAttachment(file) {
1004
+ var _a, _b, _c, _d;
1005
+ const mediaType = typeof file["mediaType"] === "string" ? file["mediaType"] : typeof file["mimeType"] === "string" ? file["mimeType"] : void 0;
1006
+ const data = (_d = (_c = (_b = (_a = file["base64Data"]) != null ? _a : file["base64"]) != null ? _b : file["uint8ArrayData"]) != null ? _c : file["uint8Array"]) != null ? _d : file["data"];
1007
+ const isImage = (mediaType == null ? void 0 : mediaType.startsWith("image/")) === true;
1008
+ const value = isImage && mediaType ? asDataUrl(data, mediaType) : dataPartToAttachmentValue(data);
1009
+ if (!value) return void 0;
1010
+ const name = typeof file["filename"] === "string" ? file["filename"] : typeof file["name"] === "string" ? file["name"] : mediaType != null ? mediaType : "file";
1011
+ return {
1012
+ type: isImage ? "image" : "text",
1013
+ role: "output",
1014
+ name,
1015
+ value
1016
+ };
1017
+ }
1018
+ async function outputAttachmentsFromFiles(files) {
1019
+ let resolvedFiles = files;
1020
+ if (resolvedFiles && (typeof resolvedFiles === "object" || typeof resolvedFiles === "function") && typeof resolvedFiles.then === "function") {
1021
+ try {
1022
+ resolvedFiles = await resolvedFiles;
1023
+ } catch (e) {
1024
+ return void 0;
1025
+ }
1026
+ }
1027
+ if (!Array.isArray(resolvedFiles)) return void 0;
1028
+ const attachments = [];
1029
+ for (const file of resolvedFiles) {
1030
+ if (!isRecord(file)) continue;
1031
+ const attachment = generatedFileToAttachment(file);
1032
+ if (attachment) attachments.push(attachment);
1033
+ }
1034
+ return attachments.length ? attachments : void 0;
1035
+ }
1036
+ function extractTextFromMessageContent(content) {
1037
+ if (typeof content === "string") return content;
1038
+ if (!Array.isArray(content)) return void 0;
1039
+ let result = "";
1040
+ for (const part of content) {
1041
+ if (!isRecord(part) || part["type"] !== "text" || typeof part["text"] !== "string") continue;
1042
+ result += part["text"];
1043
+ }
1044
+ return result.length ? result : void 0;
1045
+ }
1046
+ function extractInputAttachmentsFromArgs(args) {
1047
+ if (!isRecord(args)) return void 0;
1048
+ const messages = args["messages"];
1049
+ if (!Array.isArray(messages)) return void 0;
1050
+ for (let i = messages.length - 1; i >= 0; i--) {
1051
+ const message = messages[i];
1052
+ if (!isRecord(message) || message["role"] !== "user") continue;
1053
+ return attachmentsFromContent(message["content"], "input");
1054
+ }
1055
+ return void 0;
1056
+ }
1057
+ async function extractOutputAttachmentsFromResult(result) {
1058
+ if (!isRecord(result)) return void 0;
1059
+ const fileAttachments = await outputAttachmentsFromFiles(result["files"]);
1060
+ if (fileAttachments == null ? void 0 : fileAttachments.length) return fileAttachments;
1061
+ const responseMessages = extractResponseMessages(result);
1062
+ for (let i = responseMessages.length - 1; i >= 0; i--) {
1063
+ const message = responseMessages[i];
1064
+ if (!isRecord(message) || message["role"] !== "assistant") continue;
1065
+ return attachmentsFromContent(message["content"], "output");
1066
+ }
1067
+ return attachmentsFromContent(result["content"], "output");
1068
+ }
860
1069
  function lastUserMessageTextFromArgs(args) {
861
1070
  var _a;
862
1071
  if (!isRecord(args)) return void 0;
@@ -866,7 +1075,8 @@ function lastUserMessageTextFromArgs(args) {
866
1075
  const message = messages[i];
867
1076
  if (!isRecord(message) || message["role"] !== "user") continue;
868
1077
  const content = message["content"];
869
- if (typeof content === "string") return content;
1078
+ const text = extractTextFromMessageContent(content);
1079
+ if (text !== void 0) return text;
870
1080
  return (_a = safeJsonWithUint8(content)) != null ? _a : String(content);
871
1081
  }
872
1082
  return void 0;
@@ -881,7 +1091,8 @@ function extractInputFromArgs(args) {
881
1091
  const last = messages[messages.length - 1];
882
1092
  if (isRecord(last)) {
883
1093
  const content = last["content"];
884
- if (typeof content === "string") return content;
1094
+ const text = extractTextFromMessageContent(content);
1095
+ if (text !== void 0) return text;
885
1096
  const asJson = safeJson(content);
886
1097
  if (asJson) return asJson;
887
1098
  }
@@ -915,7 +1126,9 @@ function extractResponseMessages(result) {
915
1126
  if (!isRecord(result)) return [];
916
1127
  const response = result["response"];
917
1128
  if (isRecord(response) && Array.isArray(response["messages"])) {
918
- return response["messages"].filter((message) => isRecord(message) && typeof message["role"] === "string" && "content" in message).map((message) => message);
1129
+ return response["messages"].filter(
1130
+ (message) => isRecord(message) && typeof message["role"] === "string" && "content" in message
1131
+ ).map((message) => message);
919
1132
  }
920
1133
  const steps = result["steps"];
921
1134
  if (Array.isArray(steps) && steps.length > 0) {
@@ -923,7 +1136,9 @@ function extractResponseMessages(result) {
923
1136
  if (isRecord(lastStep) && isRecord(lastStep["response"])) {
924
1137
  const responseMessages = lastStep["response"]["messages"];
925
1138
  if (Array.isArray(responseMessages)) {
926
- return responseMessages.filter((message) => isRecord(message) && typeof message["role"] === "string" && "content" in message).map((message) => message);
1139
+ return responseMessages.filter(
1140
+ (message) => isRecord(message) && typeof message["role"] === "string" && "content" in message
1141
+ ).map((message) => message);
927
1142
  }
928
1143
  }
929
1144
  }
@@ -973,9 +1188,11 @@ function opName(operationId, functionId) {
973
1188
  function toOtlpAttr(key, value) {
974
1189
  if (value === void 0 || value === null) return void 0;
975
1190
  if (typeof value === "string") return attrString(key, value);
976
- if (typeof value === "number") return Number.isInteger(value) ? attrInt(key, value) : attrDouble(key, value);
1191
+ if (typeof value === "number")
1192
+ return Number.isInteger(value) ? attrInt(key, value) : attrDouble(key, value);
977
1193
  if (typeof value === "boolean") return attrBool(key, value);
978
- if (Array.isArray(value) && value.every((v) => typeof v === "string")) return attrStringArray(key, value);
1194
+ if (Array.isArray(value) && value.every((v) => typeof v === "string"))
1195
+ return attrStringArray(key, value);
979
1196
  const asJson = safeJsonWithUint8(value);
980
1197
  return asJson ? attrString(key, asJson) : void 0;
981
1198
  }
@@ -1021,13 +1238,31 @@ function attrsFromSettings(args) {
1021
1238
  function attrsFromGenAiRequest(options) {
1022
1239
  if (!isRecord(options)) return [];
1023
1240
  return [
1024
- attrDouble("gen_ai.request.frequency_penalty", typeof options["frequencyPenalty"] === "number" ? options["frequencyPenalty"] : void 0),
1025
- attrInt("gen_ai.request.max_tokens", typeof options["maxOutputTokens"] === "number" ? options["maxOutputTokens"] : void 0),
1026
- attrDouble("gen_ai.request.presence_penalty", typeof options["presencePenalty"] === "number" ? options["presencePenalty"] : void 0),
1241
+ attrDouble(
1242
+ "gen_ai.request.frequency_penalty",
1243
+ typeof options["frequencyPenalty"] === "number" ? options["frequencyPenalty"] : void 0
1244
+ ),
1245
+ attrInt(
1246
+ "gen_ai.request.max_tokens",
1247
+ typeof options["maxOutputTokens"] === "number" ? options["maxOutputTokens"] : void 0
1248
+ ),
1249
+ attrDouble(
1250
+ "gen_ai.request.presence_penalty",
1251
+ typeof options["presencePenalty"] === "number" ? options["presencePenalty"] : void 0
1252
+ ),
1027
1253
  ...Array.isArray(options["stopSequences"]) && options["stopSequences"].every((x) => typeof x === "string") ? [attrStringArray("gen_ai.request.stop_sequences", options["stopSequences"])] : [],
1028
- attrDouble("gen_ai.request.temperature", typeof options["temperature"] === "number" ? options["temperature"] : void 0),
1029
- attrInt("gen_ai.request.top_k", typeof options["topK"] === "number" ? options["topK"] : void 0),
1030
- attrDouble("gen_ai.request.top_p", typeof options["topP"] === "number" ? options["topP"] : void 0)
1254
+ attrDouble(
1255
+ "gen_ai.request.temperature",
1256
+ typeof options["temperature"] === "number" ? options["temperature"] : void 0
1257
+ ),
1258
+ attrInt(
1259
+ "gen_ai.request.top_k",
1260
+ typeof options["topK"] === "number" ? options["topK"] : void 0
1261
+ ),
1262
+ attrDouble(
1263
+ "gen_ai.request.top_p",
1264
+ typeof options["topP"] === "number" ? options["topP"] : void 0
1265
+ )
1031
1266
  ];
1032
1267
  }
1033
1268
 
@@ -1075,6 +1310,7 @@ function wrapAISDK(aiSDK, deps) {
1075
1310
  const agentClasses = /* @__PURE__ */ new Set(["ToolLoopAgent"]);
1076
1311
  const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
1077
1312
  const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
1313
+ const autoAttachmentEnabled = deps.options.autoAttachment !== false;
1078
1314
  const proxyTarget = isModuleNamespace(aiSDK) ? Object.setPrototypeOf({}, aiSDK) : aiSDK;
1079
1315
  return new Proxy(proxyTarget, {
1080
1316
  get(target, prop, receiver) {
@@ -1128,14 +1364,27 @@ function wrapAISDK(aiSDK, deps) {
1128
1364
  ]
1129
1365
  }) : void 0;
1130
1366
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
1131
- const wrapCtx = { eventId, telemetry, sendTraces, traceShipper: deps.traceShipper, rootParentForChildren };
1367
+ const wrapCtx = {
1368
+ eventId,
1369
+ telemetry,
1370
+ sendTraces,
1371
+ traceShipper: deps.traceShipper,
1372
+ rootParentForChildren
1373
+ };
1132
1374
  const toolCalls = [];
1133
1375
  const argWithWrappedTools = wrapTools(arg, wrapCtx, toolCalls);
1134
- const argWithWrappedModel = wrapModel(argWithWrappedTools, aiSDK, outerOperationId, wrapCtx);
1376
+ const argWithWrappedModel = wrapModel(
1377
+ argWithWrappedTools,
1378
+ aiSDK,
1379
+ outerOperationId,
1380
+ wrapCtx
1381
+ );
1135
1382
  const finalize = async (result, error) => {
1136
1383
  var _a3, _b3, _c2;
1137
1384
  const usage = extractUsage(result);
1138
1385
  const model = extractModel(result);
1386
+ const inputAttachments = autoAttachmentEnabled ? extractInputAttachmentsFromArgs(arg) : void 0;
1387
+ const outputAttachments = autoAttachmentEnabled ? await extractOutputAttachmentsFromResult(result) : void 0;
1139
1388
  const baseMessages = coerceMessagesFromArgs(arg);
1140
1389
  const responseMessages = extractResponseMessages(result);
1141
1390
  const allMessages = [...baseMessages, ...responseMessages];
@@ -1148,7 +1397,7 @@ function wrapAISDK(aiSDK, deps) {
1148
1397
  output: defaultOutput,
1149
1398
  model,
1150
1399
  properties: ctx.properties,
1151
- attachments: ctx.attachments
1400
+ attachments: mergeAttachments(ctx.attachments, inputAttachments, outputAttachments)
1152
1401
  };
1153
1402
  const built = await maybeBuildEvent(deps.options.buildEvent, allMessages);
1154
1403
  const patch = mergeBuildEventPatch(defaultPatch, built);
@@ -1168,7 +1417,10 @@ function wrapAISDK(aiSDK, deps) {
1168
1417
  attrString("ai.response.finishReason", finishReason),
1169
1418
  operation === "generateObject" || operation === "streamObject" ? attrString("ai.response.object", output) : attrString("ai.response.text", output),
1170
1419
  attrString("ai.response.toolCalls", resultToolCalls),
1171
- attrString("ai.response.providerMetadata", safeJsonWithUint8(providerMetadata))
1420
+ attrString(
1421
+ "ai.response.providerMetadata",
1422
+ safeJsonWithUint8(providerMetadata)
1423
+ )
1172
1424
  ],
1173
1425
  attrInt("ai.usage.promptTokens", usage == null ? void 0 : usage.inputTokens),
1174
1426
  attrInt("ai.usage.completionTokens", usage == null ? void 0 : usage.outputTokens),
@@ -1178,7 +1430,12 @@ function wrapAISDK(aiSDK, deps) {
1178
1430
  attrInt("ai.usage.reasoningTokens", reasoningTokens),
1179
1431
  attrInt("ai.usage.cachedInputTokens", cachedInputTokens),
1180
1432
  attrInt("ai.toolCall.count", toolCalls.length),
1181
- ...error ? [attrString("error.message", error instanceof Error ? error.message : String(error))] : []
1433
+ ...error ? [
1434
+ attrString(
1435
+ "error.message",
1436
+ error instanceof Error ? error.message : String(error)
1437
+ )
1438
+ ] : []
1182
1439
  ]
1183
1440
  });
1184
1441
  }
@@ -1194,12 +1451,18 @@ function wrapAISDK(aiSDK, deps) {
1194
1451
  attachments: patch.attachments,
1195
1452
  isPending: false
1196
1453
  }).catch((err) => {
1197
- if (debug) console.warn(`[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`);
1454
+ if (debug)
1455
+ console.warn(
1456
+ `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
1457
+ );
1198
1458
  });
1199
1459
  }
1200
1460
  };
1201
1461
  const callOriginal = async (...args) => {
1202
- return await original.call(aiSDK, ...args);
1462
+ return await original.call(
1463
+ aiSDK,
1464
+ ...args
1465
+ );
1203
1466
  };
1204
1467
  const runWithContext = async (fn) => {
1205
1468
  if (!rootSpan) return await fn();
@@ -1213,7 +1476,10 @@ function wrapAISDK(aiSDK, deps) {
1213
1476
  try {
1214
1477
  await finalize(result);
1215
1478
  } catch (err) {
1216
- if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1479
+ if (debug)
1480
+ console.warn(
1481
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1482
+ );
1217
1483
  }
1218
1484
  });
1219
1485
  try {
@@ -1240,7 +1506,10 @@ function wrapAISDK(aiSDK, deps) {
1240
1506
  try {
1241
1507
  await finalize(void 0, error);
1242
1508
  } catch (err) {
1243
- if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1509
+ if (debug)
1510
+ console.warn(
1511
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1512
+ );
1244
1513
  }
1245
1514
  throw error;
1246
1515
  }
@@ -1254,14 +1523,20 @@ function wrapAISDK(aiSDK, deps) {
1254
1523
  try {
1255
1524
  await finalize(result);
1256
1525
  } catch (err) {
1257
- if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1526
+ if (debug)
1527
+ console.warn(
1528
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1529
+ );
1258
1530
  }
1259
1531
  return result;
1260
1532
  } catch (error) {
1261
1533
  try {
1262
1534
  await finalize(void 0, error);
1263
1535
  } catch (err) {
1264
- if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1536
+ if (debug)
1537
+ console.warn(
1538
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1539
+ );
1265
1540
  }
1266
1541
  throw error;
1267
1542
  }
@@ -1313,6 +1588,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1313
1588
  var _a, _b;
1314
1589
  const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
1315
1590
  const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
1591
+ const autoAttachmentEnabled = deps.options.autoAttachment !== false;
1316
1592
  return async (...callArgs) => {
1317
1593
  var _a2, _b2, _c, _d;
1318
1594
  const callParams = callArgs[0];
@@ -1356,13 +1632,28 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1356
1632
  ]
1357
1633
  }) : void 0;
1358
1634
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
1359
- const wrapCtx = { eventId, telemetry, sendTraces, traceShipper: deps.traceShipper, rootParentForChildren };
1635
+ const wrapCtx = {
1636
+ eventId,
1637
+ telemetry,
1638
+ sendTraces,
1639
+ traceShipper: deps.traceShipper,
1640
+ rootParentForChildren
1641
+ };
1360
1642
  const toolCalls = [];
1361
- const callParamsWithWrappedTools = callParams ? wrapTools(callParams, wrapCtx, toolCalls) : callParams;
1643
+ const mergedArgsWithWrappedTools = wrapTools(mergedArgs, wrapCtx, toolCalls);
1644
+ const mergedArgsWithWrappedModel = wrapModel(
1645
+ mergedArgsWithWrappedTools,
1646
+ aiSDK,
1647
+ outerOperationId,
1648
+ wrapCtx
1649
+ );
1650
+ const callParamsWithWrappedToolsAndModel = mergedArgsWithWrappedModel != null ? mergedArgsWithWrappedModel : {};
1362
1651
  const finalize = async (result, error) => {
1363
1652
  var _a3, _b3, _c2;
1364
1653
  const usage = extractUsage(result);
1365
1654
  const model = extractModel(result);
1655
+ const inputAttachments = autoAttachmentEnabled ? extractInputAttachmentsFromArgs(mergedArgs) : void 0;
1656
+ const outputAttachments = autoAttachmentEnabled ? await extractOutputAttachmentsFromResult(result) : void 0;
1366
1657
  const baseMessages = coerceMessagesFromArgs(mergedArgs);
1367
1658
  const responseMessages = extractResponseMessages(result);
1368
1659
  const allMessages = [...baseMessages, ...responseMessages];
@@ -1373,7 +1664,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1373
1664
  output: outputText,
1374
1665
  model,
1375
1666
  properties: ctx.properties,
1376
- attachments: ctx.attachments
1667
+ attachments: mergeAttachments(ctx.attachments, inputAttachments, outputAttachments)
1377
1668
  };
1378
1669
  const built = await maybeBuildEvent(deps.options.buildEvent, allMessages);
1379
1670
  const patch = mergeBuildEventPatch(defaultPatch, built);
@@ -1403,7 +1694,12 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1403
1694
  attrInt("ai.usage.reasoningTokens", reasoningTokens),
1404
1695
  attrInt("ai.usage.cachedInputTokens", cachedInputTokens),
1405
1696
  attrInt("ai.toolCall.count", toolCalls.length),
1406
- ...error ? [attrString("error.message", error instanceof Error ? error.message : String(error))] : []
1697
+ ...error ? [
1698
+ attrString(
1699
+ "error.message",
1700
+ error instanceof Error ? error.message : String(error)
1701
+ )
1702
+ ] : []
1407
1703
  ]
1408
1704
  });
1409
1705
  }
@@ -1427,7 +1723,10 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1427
1723
  attachments: patch.attachments,
1428
1724
  isPending: false
1429
1725
  }).catch((err) => {
1430
- if (debug) console.warn(`[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`);
1726
+ if (debug)
1727
+ console.warn(
1728
+ `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
1729
+ );
1431
1730
  });
1432
1731
  } else if (debug) {
1433
1732
  console.log(`[raindrop-ai/ai-sdk] Agent ${operation} sendEvents=false, skipping event`);
@@ -1449,7 +1748,7 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1449
1748
  }
1450
1749
  try {
1451
1750
  const result = await runWithContext(async () => {
1452
- return await generate.call(instance, callParamsWithWrappedTools);
1751
+ return await generate.call(instance, callParamsWithWrappedToolsAndModel);
1453
1752
  });
1454
1753
  if (debug) {
1455
1754
  console.log(`[raindrop-ai/ai-sdk] Agent ${operation} completed, finalizing...`);
@@ -1457,14 +1756,20 @@ function wrapAgentGenerate(generate, instance, agentSettings, className, aiSDK,
1457
1756
  try {
1458
1757
  await finalize(result);
1459
1758
  } catch (err) {
1460
- if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1759
+ if (debug)
1760
+ console.warn(
1761
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1762
+ );
1461
1763
  }
1462
1764
  return result;
1463
1765
  } catch (error) {
1464
1766
  try {
1465
1767
  await finalize(void 0, error);
1466
1768
  } catch (err) {
1467
- if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1769
+ if (debug)
1770
+ console.warn(
1771
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1772
+ );
1468
1773
  }
1469
1774
  throw error;
1470
1775
  }
@@ -1474,6 +1779,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1474
1779
  var _a, _b;
1475
1780
  const sendEvents = ((_a = deps.options.send) == null ? void 0 : _a.events) !== false;
1476
1781
  const sendTraces = ((_b = deps.options.send) == null ? void 0 : _b.traces) !== false;
1782
+ const autoAttachmentEnabled = deps.options.autoAttachment !== false;
1477
1783
  return async (...callArgs) => {
1478
1784
  var _a2, _b2, _c, _d;
1479
1785
  const callParams = callArgs[0];
@@ -1517,13 +1823,28 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1517
1823
  ]
1518
1824
  }) : void 0;
1519
1825
  const rootParentForChildren = rootSpan ? { traceIdB64: rootSpan.ids.traceIdB64, spanIdB64: rootSpan.ids.spanIdB64 } : inheritedParent;
1520
- const wrapCtx = { eventId, telemetry, sendTraces, traceShipper: deps.traceShipper, rootParentForChildren };
1826
+ const wrapCtx = {
1827
+ eventId,
1828
+ telemetry,
1829
+ sendTraces,
1830
+ traceShipper: deps.traceShipper,
1831
+ rootParentForChildren
1832
+ };
1521
1833
  const toolCalls = [];
1522
- const callParamsWithWrappedTools = callParams ? wrapTools(callParams, wrapCtx, toolCalls) : callParams;
1834
+ const mergedArgsWithWrappedTools = wrapTools(mergedArgs, wrapCtx, toolCalls);
1835
+ const mergedArgsWithWrappedModel = wrapModel(
1836
+ mergedArgsWithWrappedTools,
1837
+ aiSDK,
1838
+ outerOperationId,
1839
+ wrapCtx
1840
+ );
1841
+ const callParamsWithWrappedToolsAndModel = mergedArgsWithWrappedModel != null ? mergedArgsWithWrappedModel : {};
1523
1842
  const finalize = async (result, error) => {
1524
1843
  var _a3, _b3, _c2;
1525
1844
  const usage = extractUsage(result);
1526
1845
  const model = extractModel(result);
1846
+ const inputAttachments = autoAttachmentEnabled ? extractInputAttachmentsFromArgs(mergedArgs) : void 0;
1847
+ const outputAttachments = autoAttachmentEnabled ? await extractOutputAttachmentsFromResult(result) : void 0;
1527
1848
  const baseMessages = coerceMessagesFromArgs(mergedArgs);
1528
1849
  const responseMessages = extractResponseMessages(result);
1529
1850
  const allMessages = [...baseMessages, ...responseMessages];
@@ -1534,7 +1855,7 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1534
1855
  output: outputText,
1535
1856
  model,
1536
1857
  properties: ctx.properties,
1537
- attachments: ctx.attachments
1858
+ attachments: mergeAttachments(ctx.attachments, inputAttachments, outputAttachments)
1538
1859
  };
1539
1860
  const built = await maybeBuildEvent(deps.options.buildEvent, allMessages);
1540
1861
  const patch = mergeBuildEventPatch(defaultPatch, built);
@@ -1564,7 +1885,12 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1564
1885
  attrInt("ai.usage.reasoningTokens", reasoningTokens),
1565
1886
  attrInt("ai.usage.cachedInputTokens", cachedInputTokens),
1566
1887
  attrInt("ai.toolCall.count", toolCalls.length),
1567
- ...error ? [attrString("error.message", error instanceof Error ? error.message : String(error))] : []
1888
+ ...error ? [
1889
+ attrString(
1890
+ "error.message",
1891
+ error instanceof Error ? error.message : String(error)
1892
+ )
1893
+ ] : []
1568
1894
  ]
1569
1895
  });
1570
1896
  }
@@ -1588,7 +1914,10 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1588
1914
  attachments: patch.attachments,
1589
1915
  isPending: false
1590
1916
  }).catch((err) => {
1591
- if (debug) console.warn(`[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`);
1917
+ if (debug)
1918
+ console.warn(
1919
+ `[raindrop-ai/ai-sdk] event patch failed: ${err instanceof Error ? err.message : err}`
1920
+ );
1592
1921
  });
1593
1922
  } else if (debug) {
1594
1923
  console.log(`[raindrop-ai/ai-sdk] Agent ${operation} sendEvents=false, skipping event`);
@@ -1608,16 +1937,22 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1608
1937
  eventName: ctx.eventName
1609
1938
  });
1610
1939
  }
1611
- const callParamsWithOnFinish = wrapOnFinish(callParamsWithWrappedTools != null ? callParamsWithWrappedTools : {}, async (result) => {
1612
- if (debug) {
1613
- console.log(`[raindrop-ai/ai-sdk] Agent ${operation} onFinish callback, finalizing...`);
1614
- }
1615
- try {
1616
- await finalize(result);
1617
- } catch (err) {
1618
- if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1940
+ const callParamsWithOnFinish = wrapOnFinish(
1941
+ callParamsWithWrappedToolsAndModel != null ? callParamsWithWrappedToolsAndModel : {},
1942
+ async (result) => {
1943
+ if (debug) {
1944
+ console.log(`[raindrop-ai/ai-sdk] Agent ${operation} onFinish callback, finalizing...`);
1945
+ }
1946
+ try {
1947
+ await finalize(result);
1948
+ } catch (err) {
1949
+ if (debug)
1950
+ console.warn(
1951
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1952
+ );
1953
+ }
1619
1954
  }
1620
- });
1955
+ );
1621
1956
  try {
1622
1957
  const result = await runWithContext(async () => {
1623
1958
  return await stream.call(instance, callParamsWithOnFinish);
@@ -1627,7 +1962,10 @@ function wrapAgentStream(stream, instance, agentSettings, className, aiSDK, deps
1627
1962
  try {
1628
1963
  await finalize(void 0, error);
1629
1964
  } catch (err) {
1630
- if (debug) console.warn(`[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`);
1965
+ if (debug)
1966
+ console.warn(
1967
+ `[raindrop-ai/ai-sdk] finalize failed: ${err instanceof Error ? err.message : err}`
1968
+ );
1631
1969
  }
1632
1970
  throw error;
1633
1971
  }
@@ -1670,7 +2008,9 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
1670
2008
  if (!span) return;
1671
2009
  if (error) {
1672
2010
  ctx.traceShipper.endSpan(span, {
1673
- attributes: [attrString("error.message", error instanceof Error ? error.message : String(error))]
2011
+ attributes: [
2012
+ attrString("error.message", error instanceof Error ? error.message : String(error))
2013
+ ]
1674
2014
  });
1675
2015
  } else {
1676
2016
  ctx.traceShipper.endSpan(span, {
@@ -1727,7 +2067,11 @@ function wrapToolExecute(name, tool, ctx, toolCalls) {
1727
2067
  };
1728
2068
  if (!toolSpan) return await run();
1729
2069
  return await runWithParentSpanContext(
1730
- { traceIdB64: toolSpan.ids.traceIdB64, spanIdB64: toolSpan.ids.spanIdB64, eventId: ctx.eventId },
2070
+ {
2071
+ traceIdB64: toolSpan.ids.traceIdB64,
2072
+ spanIdB64: toolSpan.ids.spanIdB64,
2073
+ eventId: ctx.eventId
2074
+ },
1731
2075
  run
1732
2076
  );
1733
2077
  })();
@@ -1766,7 +2110,15 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
1766
2110
  if (span) endDoGenerateSpan(span, result, modelInfo, ctx);
1767
2111
  return result;
1768
2112
  } catch (error) {
1769
- if (span) ctx.traceShipper.endSpan(span, { attributes: [attrString("error.message", error instanceof Error ? error.message : String(error))] });
2113
+ if (span)
2114
+ ctx.traceShipper.endSpan(span, {
2115
+ attributes: [
2116
+ attrString(
2117
+ "error.message",
2118
+ error instanceof Error ? error.message : String(error)
2119
+ )
2120
+ ]
2121
+ });
1770
2122
  throw error;
1771
2123
  }
1772
2124
  };
@@ -1794,7 +2146,12 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
1794
2146
  } catch (error) {
1795
2147
  if (span)
1796
2148
  ctx.traceShipper.endSpan(span, {
1797
- attributes: [attrString("error.message", error instanceof Error ? error.message : String(error))]
2149
+ attributes: [
2150
+ attrString(
2151
+ "error.message",
2152
+ error instanceof Error ? error.message : String(error)
2153
+ )
2154
+ ]
1798
2155
  });
1799
2156
  throw error;
1800
2157
  }
@@ -1820,11 +2177,17 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
1820
2177
  ...((_a = ctx.telemetry) == null ? void 0 : _a.recordOutputs) === false ? [] : [
1821
2178
  attrString("ai.response.finishReason", finishReason),
1822
2179
  attrString("ai.response.text", activeText.length ? activeText : void 0),
1823
- attrString("ai.response.toolCalls", safeJsonWithUint8(toolCallsLocal.length ? toolCallsLocal : void 0)),
2180
+ attrString(
2181
+ "ai.response.toolCalls",
2182
+ safeJsonWithUint8(toolCallsLocal.length ? toolCallsLocal : void 0)
2183
+ ),
1824
2184
  attrString("ai.response.id", responseId),
1825
2185
  attrString("ai.response.model", responseModelId),
1826
2186
  attrString("ai.response.timestamp", responseTimestampIso),
1827
- attrString("ai.response.providerMetadata", safeJsonWithUint8(providerMetadata))
2187
+ attrString(
2188
+ "ai.response.providerMetadata",
2189
+ safeJsonWithUint8(providerMetadata)
2190
+ )
1828
2191
  ],
1829
2192
  attrInt("ai.usage.inputTokens", inputTokens),
1830
2193
  attrInt("ai.usage.outputTokens", outputTokens),
@@ -1836,7 +2199,12 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
1836
2199
  ...msToFirstChunk !== void 0 ? [attrInt("ai.stream.msToFirstChunk", msToFirstChunk)] : [],
1837
2200
  ...msToFinish !== void 0 ? [attrInt("ai.stream.msToFinish", msToFinish)] : [],
1838
2201
  ...avgOutTokensPerSecond !== void 0 ? [attrDouble("ai.stream.avgOutputTokensPerSecond", avgOutTokensPerSecond)] : [],
1839
- ...error ? [attrString("error.message", error instanceof Error ? error.message : String(error))] : []
2202
+ ...error ? [
2203
+ attrString(
2204
+ "error.message",
2205
+ error instanceof Error ? error.message : String(error)
2206
+ )
2207
+ ] : []
1840
2208
  ]
1841
2209
  });
1842
2210
  };
@@ -1853,15 +2221,20 @@ function wrapModel(args, aiSDK, outerOperationId, ctx) {
1853
2221
  if (firstChunkMs === void 0) firstChunkMs = Date.now();
1854
2222
  if (isRecord(value)) {
1855
2223
  const type = value["type"];
1856
- if (type === "text-delta" && typeof value["textDelta"] === "string") activeText += value["textDelta"];
1857
- if (type === "finish" && typeof value["finishReason"] === "string") finishReason = value["finishReason"];
2224
+ if (type === "text-delta" && typeof value["textDelta"] === "string")
2225
+ activeText += value["textDelta"];
2226
+ if (type === "finish" && typeof value["finishReason"] === "string")
2227
+ finishReason = value["finishReason"];
1858
2228
  if (type === "tool-call") toolCallsLocal.push(value);
1859
2229
  if ("response" in value && isRecord(value["response"])) {
1860
2230
  const response = value["response"];
1861
2231
  if (typeof response["id"] === "string") responseId = response["id"];
1862
- if (typeof response["modelId"] === "string") responseModelId = response["modelId"];
1863
- if (response["timestamp"] instanceof Date) responseTimestampIso = response["timestamp"].toISOString();
1864
- else if (typeof response["timestamp"] === "string") responseTimestampIso = response["timestamp"];
2232
+ if (typeof response["modelId"] === "string")
2233
+ responseModelId = response["modelId"];
2234
+ if (response["timestamp"] instanceof Date)
2235
+ responseTimestampIso = response["timestamp"].toISOString();
2236
+ else if (typeof response["timestamp"] === "string")
2237
+ responseTimestampIso = response["timestamp"];
1865
2238
  }
1866
2239
  if ("usage" in value) usage = value["usage"];
1867
2240
  if ("providerMetadata" in value) providerMetadata = value["providerMetadata"];
@@ -1903,7 +2276,11 @@ function startDoGenerateSpan(operationId, options, modelInfo, parent, ctx) {
1903
2276
  attrString("ai.telemetry.functionId", (_b = ctx.telemetry) == null ? void 0 : _b.functionId),
1904
2277
  attrString("ai.model.provider", modelInfo.provider),
1905
2278
  attrString("ai.model.id", modelInfo.modelId),
1906
- ...((_c = ctx.telemetry) == null ? void 0 : _c.recordInputs) === false ? [] : [attrString("ai.prompt.messages", promptJson), attrStringArray("ai.prompt.tools", toolsJson), attrString("ai.prompt.toolChoice", toolChoiceJson)],
2279
+ ...((_c = ctx.telemetry) == null ? void 0 : _c.recordInputs) === false ? [] : [
2280
+ attrString("ai.prompt.messages", promptJson),
2281
+ attrStringArray("ai.prompt.tools", toolsJson),
2282
+ attrString("ai.prompt.toolChoice", toolChoiceJson)
2283
+ ],
1907
2284
  attrString("gen_ai.system", modelInfo.provider),
1908
2285
  attrString("gen_ai.request.model", modelInfo.modelId),
1909
2286
  ...attrsFromGenAiRequest(options)
@@ -1944,7 +2321,10 @@ function endDoGenerateSpan(span, result, modelInfo, ctx) {
1944
2321
  ...((_a = ctx.telemetry) == null ? void 0 : _a.recordOutputs) === false ? [] : [
1945
2322
  attrString("ai.response.finishReason", finishReason),
1946
2323
  attrString("ai.response.text", extractTextFromLmContent(content)),
1947
- attrString("ai.response.toolCalls", safeJsonWithUint8(extractToolCallsFromLmContent(content))),
2324
+ attrString(
2325
+ "ai.response.toolCalls",
2326
+ safeJsonWithUint8(extractToolCallsFromLmContent(content))
2327
+ ),
1948
2328
  attrString("ai.response.id", responseId),
1949
2329
  attrString("ai.response.model", responseModelId),
1950
2330
  attrString("ai.response.timestamp", responseTimestampIso),
@@ -1978,7 +2358,11 @@ function startDoStreamSpan(operationId, options, modelInfo, parent, ctx) {
1978
2358
  attrString("ai.telemetry.functionId", (_b = ctx.telemetry) == null ? void 0 : _b.functionId),
1979
2359
  attrString("ai.model.provider", modelInfo.provider),
1980
2360
  attrString("ai.model.id", modelInfo.modelId),
1981
- ...((_c = ctx.telemetry) == null ? void 0 : _c.recordInputs) === false ? [] : [attrString("ai.prompt.messages", promptJson), attrStringArray("ai.prompt.tools", toolsJson), attrString("ai.prompt.toolChoice", toolChoiceJson)],
2361
+ ...((_c = ctx.telemetry) == null ? void 0 : _c.recordInputs) === false ? [] : [
2362
+ attrString("ai.prompt.messages", promptJson),
2363
+ attrStringArray("ai.prompt.tools", toolsJson),
2364
+ attrString("ai.prompt.toolChoice", toolChoiceJson)
2365
+ ],
1982
2366
  attrString("gen_ai.system", modelInfo.provider),
1983
2367
  attrString("gen_ai.request.model", modelInfo.modelId),
1984
2368
  ...attrsFromGenAiRequest(options)
@@ -2030,6 +2414,13 @@ function mergeBuildEventPatch(defaults, override) {
2030
2414
  attachments: override.attachments !== void 0 ? [...(_g = defaults.attachments) != null ? _g : [], ...(_h = override.attachments) != null ? _h : []] : defaults.attachments
2031
2415
  };
2032
2416
  }
2417
+ function mergeAttachments(...groups) {
2418
+ const merged = [];
2419
+ for (const group of groups) {
2420
+ if (group == null ? void 0 : group.length) merged.push(...group);
2421
+ }
2422
+ return merged.length ? merged : void 0;
2423
+ }
2033
2424
  function extractNestedTokens(usage, key) {
2034
2425
  if (!isRecord(usage)) return void 0;
2035
2426
  const val = usage[key];
@@ -2049,23 +2440,30 @@ function eventMetadata(options) {
2049
2440
  if (options.properties) result["raindrop.properties"] = JSON.stringify(options.properties);
2050
2441
  return result;
2051
2442
  }
2443
+ function envDebugEnabled() {
2444
+ var _a;
2445
+ if (typeof process === "undefined") return false;
2446
+ const flag = (_a = process.env) == null ? void 0 : _a.RAINDROP_AI_DEBUG;
2447
+ return flag === "1" || flag === "true";
2448
+ }
2052
2449
  function createRaindropAISDK(opts) {
2053
2450
  var _a, _b, _c, _d, _e, _f, _g, _h, _i;
2054
2451
  const eventsEnabled = ((_a = opts.events) == null ? void 0 : _a.enabled) !== false;
2055
2452
  const tracesEnabled = ((_b = opts.traces) == null ? void 0 : _b.enabled) !== false;
2453
+ const envDebug = envDebugEnabled();
2056
2454
  const eventShipper = new EventShipper({
2057
2455
  writeKey: opts.writeKey,
2058
2456
  endpoint: opts.endpoint,
2059
2457
  enabled: eventsEnabled,
2060
- debug: ((_c = opts.events) == null ? void 0 : _c.debug) === true,
2458
+ debug: ((_c = opts.events) == null ? void 0 : _c.debug) === true || envDebug,
2061
2459
  partialFlushMs: (_d = opts.events) == null ? void 0 : _d.partialFlushMs
2062
2460
  });
2063
2461
  const traceShipper = new TraceShipper({
2064
2462
  writeKey: opts.writeKey,
2065
2463
  endpoint: opts.endpoint,
2066
2464
  enabled: tracesEnabled,
2067
- debug: ((_e = opts.traces) == null ? void 0 : _e.debug) === true,
2068
- debugSpans: ((_f = opts.traces) == null ? void 0 : _f.debugSpans) === true,
2465
+ debug: ((_e = opts.traces) == null ? void 0 : _e.debug) === true || envDebug,
2466
+ debugSpans: ((_f = opts.traces) == null ? void 0 : _f.debugSpans) === true || envDebug,
2069
2467
  flushIntervalMs: (_g = opts.traces) == null ? void 0 : _g.flushIntervalMs,
2070
2468
  maxBatchSize: (_h = opts.traces) == null ? void 0 : _h.maxBatchSize,
2071
2469
  maxQueueSize: (_i = opts.traces) == null ? void 0 : _i.maxQueueSize