raindrop-ai 1.0.5 → 1.0.6

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.
@@ -39,7 +39,36 @@ module.exports = __toCommonJS(tracing_exports);
39
39
  var import_api6 = require("@opentelemetry/api");
40
40
  var import_exporter_trace_otlp_http = require("@opentelemetry/exporter-trace-otlp-http");
41
41
 
42
- // ../core/dist/chunk-BYBMRLZM.js
42
+ // ../core/dist/chunk-ZCB62SIO.js
43
+ var __create2 = Object.create;
44
+ var __defProp2 = Object.defineProperty;
45
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
46
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
47
+ var __getProtoOf2 = Object.getPrototypeOf;
48
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
49
+ var __commonJS = (cb, mod) => function __require() {
50
+ try {
51
+ return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
52
+ } catch (e) {
53
+ throw mod = 0, e;
54
+ }
55
+ };
56
+ var __copyProps2 = (to, from, except, desc) => {
57
+ if (from && typeof from === "object" || typeof from === "function") {
58
+ for (let key of __getOwnPropNames2(from))
59
+ if (!__hasOwnProp2.call(to, key) && key !== except)
60
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
61
+ }
62
+ return to;
63
+ };
64
+ var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
65
+ // If the importer is in node compatibility mode or this is not an ESM
66
+ // file that has been converted to a CommonJS file using a Babel-
67
+ // compatible transform (i.e. "__esModule" has not been set), then set
68
+ // "default" to the CommonJS "module.exports" for node compatibility.
69
+ isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
70
+ mod
71
+ ));
43
72
  var EVAL_CORRELATION_ID_ATTRIBUTE = "raindrop.eval_correlation_id";
44
73
  var PROBE_SCOPE = { correlationId: "" };
45
74
  var EvalScopeStorage = class {
@@ -101,21 +130,246 @@ function evalScopeAttributes() {
101
130
  return { [EVAL_CORRELATION_ID_ATTRIBUTE]: scope.correlationId };
102
131
  }
103
132
 
104
- // ../core/dist/chunk-QH6U6QYP.js
133
+ // ../core/dist/chunk-AX36JKJL.js
134
+ var require_NameRedactor = __commonJS({
135
+ "../redact-pii/dist/built-ins/NameRedactor.js"(exports2) {
136
+ Object.defineProperty(exports2, "__esModule", { value: true });
137
+ exports2.NameRedactor = void 0;
138
+ var greetingRegex = /(^|\.\s+)(dear|hi|hello|greetings|hey|hey there)/gi;
139
+ var closingRegex = /(thx|thanks|thank you|regards|best|[a-z]{1,30}ly|[a-z]{1,30} regards|all the best|happy [a-z]{1,30}ing|take care|have a [a-z]{1,30} (weekend|night|day))/gi;
140
+ var greetingOrClosing = new RegExp("(((" + greetingRegex.source + ")|(" + closingRegex.source + "\\s*[,.!]*))[\\s-]*)", "gi");
141
+ var genericName = new RegExp("( ?(([A-Z][a-z]{1,30})|([A-Z]\\.))){1,10}([,.]|[,.]?$)", "my");
142
+ var NameRedactor = class {
143
+ constructor(replaceWith = "PERSON_NAME") {
144
+ this.replaceWith = replaceWith;
145
+ }
146
+ redact(textToRedact) {
147
+ var _a;
148
+ greetingOrClosing.lastIndex = 0;
149
+ genericName.lastIndex = 0;
150
+ const pieces = [];
151
+ let copiedThrough = 0;
152
+ let changed = false;
153
+ let greetingOrClosingMatch = greetingOrClosing.exec(textToRedact);
154
+ while (greetingOrClosingMatch !== null) {
155
+ genericName.lastIndex = greetingOrClosing.lastIndex;
156
+ const genericNameMatch = genericName.exec(textToRedact);
157
+ if (genericNameMatch !== null && genericNameMatch.index === greetingOrClosing.lastIndex) {
158
+ const suffix = (_a = genericNameMatch[5]) !== null && _a !== void 0 ? _a : "";
159
+ const end = genericNameMatch.index + genericNameMatch[0].length;
160
+ pieces.push(textToRedact.slice(copiedThrough, genericNameMatch.index), this.replaceWith, suffix);
161
+ copiedThrough = end;
162
+ changed = true;
163
+ greetingOrClosing.lastIndex = end - suffix.length;
164
+ }
165
+ greetingOrClosingMatch = greetingOrClosing.exec(textToRedact);
166
+ }
167
+ if (!changed)
168
+ return textToRedact;
169
+ pieces.push(textToRedact.slice(copiedThrough));
170
+ return pieces.join("");
171
+ }
172
+ };
173
+ exports2.NameRedactor = NameRedactor;
174
+ }
175
+ });
176
+ var require_simple_regexp_patterns = __commonJS({
177
+ "../redact-pii/dist/built-ins/simple-regexp-patterns.js"(exports2) {
178
+ Object.defineProperty(exports2, "__esModule", { value: true });
179
+ exports2.url = exports2.digits = exports2.credentials = exports2.password = exports2.username = exports2.emailAddress = exports2.usSocialSecurityNumber = exports2.ipAddress = exports2.phoneNumber = exports2.zipcode = exports2.streetAddress = exports2.creditCardNumber = void 0;
180
+ var aptRegex = /(apt|bldg|dept|fl|hngr|lot|pier|rm|ste|slip|trlr|unit|#)\.? *[a-z0-9-]+\b/gi;
181
+ var poBoxRegex = /P\.? ?O\.? *Box +\d+/gi;
182
+ var roadRegex = /(street|st|road|rd|avenue|ave|drive|dr|loop|court|ct|circle|cir|lane|ln|boulevard|blvd|way)\.?\b/gi;
183
+ exports2.creditCardNumber = /\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}|\d{4}[ -]?\d{6}[ -]?\d{4}\d?/g;
184
+ exports2.streetAddress = new RegExp("(\\d{1,10}\\s*(\\w{1,30} ){1,2}" + roadRegex.source + "(\\s+" + aptRegex.source + ")?)|(" + poBoxRegex.source + ")", "gi");
185
+ exports2.zipcode = /\b\d{5}\b(-\d{4})?\b/g;
186
+ exports2.phoneNumber = /(\(?\+?[0-9]{1,2}\)?[-. ]?)?(\(?[0-9]{3}\)?|[0-9]{3})[-. ]?([0-9]{3}[-. ]?[0-9]{4}|\b[A-Z0-9]{7}\b)/g;
187
+ exports2.ipAddress = /(\d{1,3}(\.\d{1,3}){3}|[0-9A-F]{4}(:[0-9A-F]{4}){5}(::|(:0000)+))/gi;
188
+ exports2.usSocialSecurityNumber = /\b\d{3}[ -.]\d{2}[ -.]\d{4}\b/g;
189
+ exports2.emailAddress = /([a-z0-9_\-.+]{1,64})@\w+(\.\w+)*/gi;
190
+ exports2.username = /(user( ?name)?|login): \S+/gi;
191
+ exports2.password = /(pass(word|phrase)?|secret): \S+/gi;
192
+ exports2.credentials = /(login( cred(ential)?s| info(rmation)?)?|cred(ential)?s) ?:\s*\S+\s+\/?\s*\S+/gi;
193
+ exports2.digits = /\b\d{4,}\b/g;
194
+ exports2.url = /([^\s:/?#]{1,64}):\/\/([^/?#\s]*)([^?#\s]*)(\?([^#\s]*))?(#([^\s]*))?/g;
195
+ }
196
+ });
197
+ var require_utils = __commonJS({
198
+ "../redact-pii/dist/utils.js"(exports2) {
199
+ Object.defineProperty(exports2, "__esModule", { value: true });
200
+ exports2.snakeCase = exports2.isSyncRedactor = exports2.isSimpleRegexpCustomRedactorConfig = void 0;
201
+ function isSimpleRegexpCustomRedactorConfig(redactor2) {
202
+ return typeof redactor2.regexpPattern !== "undefined";
203
+ }
204
+ exports2.isSimpleRegexpCustomRedactorConfig = isSimpleRegexpCustomRedactorConfig;
205
+ function isSyncRedactor(redactor2) {
206
+ return typeof redactor2.redact === "function";
207
+ }
208
+ exports2.isSyncRedactor = isSyncRedactor;
209
+ function snakeCase(input = "") {
210
+ var _a;
211
+ const words = (_a = input.match(/[A-Z]{2,}(?=[A-Z][a-z]|[0-9]|\b)|[A-Z]?[a-z]+|[A-Z]+|[0-9]+/g)) !== null && _a !== void 0 ? _a : [];
212
+ return words.map((word) => word.toLowerCase()).join("_");
213
+ }
214
+ exports2.snakeCase = snakeCase;
215
+ }
216
+ });
217
+ var require_SimpleRegexpRedactor = __commonJS({
218
+ "../redact-pii/dist/built-ins/SimpleRegexpRedactor.js"(exports2) {
219
+ Object.defineProperty(exports2, "__esModule", { value: true });
220
+ exports2.SimpleRegexpRedactor = void 0;
221
+ var utils_1 = require_utils();
222
+ var SimpleRegexpRedactor = class {
223
+ constructor({ replaceWith = (0, utils_1.snakeCase)().toUpperCase(), regexpPattern: regexpMatcher }) {
224
+ this.replaceWith = replaceWith;
225
+ this.regexpMatcher = regexpMatcher;
226
+ }
227
+ redact(textToRedact) {
228
+ return textToRedact.replace(this.regexpMatcher, this.replaceWith);
229
+ }
230
+ };
231
+ exports2.SimpleRegexpRedactor = SimpleRegexpRedactor;
232
+ }
233
+ });
234
+ var require_composition = __commonJS({
235
+ "../redact-pii/dist/composition.js"(exports2) {
236
+ Object.defineProperty(exports2, "__esModule", { value: true });
237
+ exports2.composeChildRedactors = void 0;
238
+ var NameRedactor_1 = require_NameRedactor();
239
+ var simpleRegexpBuiltIns = require_simple_regexp_patterns();
240
+ var SimpleRegexpRedactor_1 = require_SimpleRegexpRedactor();
241
+ var utils_1 = require_utils();
242
+ function normalizeCustomRedactorConfig(redactorConfig) {
243
+ return (0, utils_1.isSimpleRegexpCustomRedactorConfig)(redactorConfig) ? new SimpleRegexpRedactor_1.SimpleRegexpRedactor({
244
+ regexpPattern: redactorConfig.regexpPattern,
245
+ replaceWith: redactorConfig.replaceWith
246
+ }) : redactorConfig;
247
+ }
248
+ function composeChildRedactors(opts = {}) {
249
+ var _a, _b, _c, _d;
250
+ const childRedactors = [];
251
+ if (opts.customRedactors && opts.customRedactors.before) {
252
+ opts.customRedactors.before.map(normalizeCustomRedactorConfig).forEach((redactor2) => childRedactors.push(redactor2));
253
+ }
254
+ for (const regexpName of Object.keys(simpleRegexpBuiltIns)) {
255
+ if (!opts.builtInRedactors || !opts.builtInRedactors[regexpName] || opts.builtInRedactors[regexpName].enabled !== false) {
256
+ childRedactors.push(new SimpleRegexpRedactor_1.SimpleRegexpRedactor({
257
+ regexpPattern: simpleRegexpBuiltIns[regexpName],
258
+ replaceWith: ((_b = (_a = opts.builtInRedactors) === null || _a === void 0 ? void 0 : _a[regexpName]) === null || _b === void 0 ? void 0 : _b.replaceWith) || opts.globalReplaceWith || (0, utils_1.snakeCase)(regexpName).toUpperCase()
259
+ }));
260
+ }
261
+ }
262
+ if (!opts.builtInRedactors || !opts.builtInRedactors.names || opts.builtInRedactors.names.enabled !== false) {
263
+ childRedactors.push(new NameRedactor_1.NameRedactor(((_d = (_c = opts.builtInRedactors) === null || _c === void 0 ? void 0 : _c.names) === null || _d === void 0 ? void 0 : _d.replaceWith) || opts.globalReplaceWith));
264
+ }
265
+ if (opts.customRedactors && opts.customRedactors.after) {
266
+ opts.customRedactors.after.map(normalizeCustomRedactorConfig).forEach((redactor2) => childRedactors.push(redactor2));
267
+ }
268
+ return childRedactors;
269
+ }
270
+ exports2.composeChildRedactors = composeChildRedactors;
271
+ }
272
+ });
273
+ var require_AsyncCompositeRedactor = __commonJS({
274
+ "../redact-pii/dist/AsyncCompositeRedactor.js"(exports2) {
275
+ var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
276
+ function adopt(value) {
277
+ return value instanceof P ? value : new P(function(resolve) {
278
+ resolve(value);
279
+ });
280
+ }
281
+ return new (P || (P = Promise))(function(resolve, reject) {
282
+ function fulfilled(value) {
283
+ try {
284
+ step(generator.next(value));
285
+ } catch (e) {
286
+ reject(e);
287
+ }
288
+ }
289
+ function rejected(value) {
290
+ try {
291
+ step(generator["throw"](value));
292
+ } catch (e) {
293
+ reject(e);
294
+ }
295
+ }
296
+ function step(result) {
297
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
298
+ }
299
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
300
+ });
301
+ };
302
+ Object.defineProperty(exports2, "__esModule", { value: true });
303
+ exports2.AsyncCompositeRedactor = void 0;
304
+ var composition_1 = require_composition();
305
+ var utils_1 = require_utils();
306
+ var AsyncCompositeRedactor = class {
307
+ constructor(opts) {
308
+ this.childRedactors = [];
309
+ this.redactAsync = (textToRedact) => __awaiter(this, void 0, void 0, function* () {
310
+ for (const redactor2 of this.childRedactors) {
311
+ if ((0, utils_1.isSyncRedactor)(redactor2)) {
312
+ textToRedact = redactor2.redact(textToRedact);
313
+ } else {
314
+ textToRedact = yield redactor2.redactAsync(textToRedact);
315
+ }
316
+ }
317
+ return textToRedact;
318
+ });
319
+ this.childRedactors = (0, composition_1.composeChildRedactors)(opts);
320
+ }
321
+ };
322
+ exports2.AsyncCompositeRedactor = AsyncCompositeRedactor;
323
+ }
324
+ });
325
+ var require_SyncCompositeRedactor = __commonJS({
326
+ "../redact-pii/dist/SyncCompositeRedactor.js"(exports2) {
327
+ Object.defineProperty(exports2, "__esModule", { value: true });
328
+ exports2.SyncCompositeRedactor = void 0;
329
+ var composition_1 = require_composition();
330
+ var SyncCompositeRedactor = class {
331
+ constructor(opts) {
332
+ this.childRedactors = [];
333
+ this.redact = (textToRedact) => {
334
+ for (const redactor2 of this.childRedactors) {
335
+ textToRedact = redactor2.redact(textToRedact);
336
+ }
337
+ return textToRedact;
338
+ };
339
+ this.childRedactors = (0, composition_1.composeChildRedactors)(opts);
340
+ }
341
+ };
342
+ exports2.SyncCompositeRedactor = SyncCompositeRedactor;
343
+ }
344
+ });
345
+ var require_dist = __commonJS({
346
+ "../redact-pii/dist/index.js"(exports2) {
347
+ Object.defineProperty(exports2, "__esModule", { value: true });
348
+ exports2.SyncRedactor = exports2.AsyncRedactor = void 0;
349
+ var AsyncCompositeRedactor_1 = require_AsyncCompositeRedactor();
350
+ Object.defineProperty(exports2, "AsyncRedactor", { enumerable: true, get: function() {
351
+ return AsyncCompositeRedactor_1.AsyncCompositeRedactor;
352
+ } });
353
+ var SyncCompositeRedactor_1 = require_SyncCompositeRedactor();
354
+ Object.defineProperty(exports2, "SyncRedactor", { enumerable: true, get: function() {
355
+ return SyncCompositeRedactor_1.SyncCompositeRedactor;
356
+ } });
357
+ }
358
+ });
105
359
  var STATE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.replayTraceRoutingState");
106
360
  function state() {
107
361
  const holder = globalThis;
108
362
  let current = holder[STATE_KEY];
109
363
  if (!current) {
110
- let storage = null;
364
+ let storage2 = null;
111
365
  try {
112
366
  const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
113
- if (Ctor) storage = new Ctor();
367
+ if (Ctor) storage2 = new Ctor();
114
368
  } catch (e) {
115
- storage = null;
369
+ storage2 = null;
116
370
  }
117
371
  current = {
118
- storage,
372
+ storage: storage2,
119
373
  syncDestination: void 0,
120
374
  spanDestinations: /* @__PURE__ */ new WeakMap()
121
375
  };
@@ -268,12 +522,12 @@ var NO_AMBIENT_ATTRIBUTE_BIND_WARNING = "[raindrop] This runtime's AsyncLocalSto
268
522
  var ROUTING_STORAGE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.routingContextStorage");
269
523
  function routingStorage() {
270
524
  const holder = globalThis;
271
- let storage = holder[ROUTING_STORAGE_KEY];
272
- if (!storage) {
273
- storage = new ContextStackStorage(NO_AMBIENT_ROUTING_BIND_WARNING);
274
- holder[ROUTING_STORAGE_KEY] = storage;
525
+ let storage2 = holder[ROUTING_STORAGE_KEY];
526
+ if (!storage2) {
527
+ storage2 = new ContextStackStorage(NO_AMBIENT_ROUTING_BIND_WARNING);
528
+ holder[ROUTING_STORAGE_KEY] = storage2;
275
529
  }
276
- return storage;
530
+ return storage2;
277
531
  }
278
532
  function makeBoundContext(binding, owner) {
279
533
  const WeakRefCtor = owner !== void 0 ? getWeakRefCtor() : void 0;
@@ -328,12 +582,12 @@ function isBoundContext(value) {
328
582
  var ATTRIBUTE_STORAGE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.spanAttributeStorage");
329
583
  function attributeStorage() {
330
584
  const holder = globalThis;
331
- let storage = holder[ATTRIBUTE_STORAGE_KEY];
332
- if (!storage) {
333
- storage = new ContextStackStorage(NO_AMBIENT_ATTRIBUTE_BIND_WARNING);
334
- holder[ATTRIBUTE_STORAGE_KEY] = storage;
585
+ let storage2 = holder[ATTRIBUTE_STORAGE_KEY];
586
+ if (!storage2) {
587
+ storage2 = new ContextStackStorage(NO_AMBIENT_ATTRIBUTE_BIND_WARNING);
588
+ holder[ATTRIBUTE_STORAGE_KEY] = storage2;
335
589
  }
336
- return storage;
590
+ return storage2;
337
591
  }
338
592
  function makeAttributeFrame(attributes, owner) {
339
593
  const snapshot = { ...attributes };
@@ -763,11 +1017,91 @@ function runWithTracingSuppressed(fn) {
763
1017
  return fn();
764
1018
  }
765
1019
  }
1020
+ var MAX_QUOTED_ITEMS = 3;
1021
+ function isRecord(value) {
1022
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1023
+ }
1024
+ function itemLabel(item) {
1025
+ if (typeof item.event_id === "string" && item.event_id) return `event ${item.event_id}`;
1026
+ if (typeof item.index === "number") return `item ${item.index}`;
1027
+ return "item";
1028
+ }
1029
+ function describeRejected(item) {
1030
+ const issues = Array.isArray(item.issues) ? item.issues : [];
1031
+ const text = issues.filter(isRecord).map((issue) => {
1032
+ const path = typeof issue.path === "string" && issue.path ? `${issue.path}: ` : "";
1033
+ return `${path}${typeof issue.message === "string" ? issue.message : "invalid"}`;
1034
+ }).join("; ");
1035
+ return `${itemLabel(item)} (${text || "invalid"})`;
1036
+ }
1037
+ function describeWarning(item) {
1038
+ if (typeof item.message === "string" && item.message) return `${itemLabel(item)}: ${item.message}`;
1039
+ const fields = Array.isArray(item.fields) ? item.fields.filter((f) => typeof f === "string") : [];
1040
+ return `${itemLabel(item)}: ignored ${fields.join(", ") || "input"}`;
1041
+ }
1042
+ function summarize(items, describe) {
1043
+ const quoted = items.slice(0, MAX_QUOTED_ITEMS).map(describe).join(" | ");
1044
+ const more = items.length > MAX_QUOTED_ITEMS ? ` (+${items.length - MAX_QUOTED_ITEMS} more)` : "";
1045
+ return `${quoted}${more}`;
1046
+ }
1047
+ function reportIngestResponse(bodyText, prefix, opName) {
1048
+ if (!bodyText) return;
1049
+ let body;
1050
+ try {
1051
+ body = JSON.parse(bodyText);
1052
+ } catch (e) {
1053
+ return;
1054
+ }
1055
+ if (!isRecord(body)) return;
1056
+ const rejected = Array.isArray(body.rejected) ? body.rejected.filter(isRecord) : [];
1057
+ if (rejected.length > 0) {
1058
+ rateLimitedLog(
1059
+ `${prefix}.ingest_rejected`,
1060
+ () => console.warn(
1061
+ `${prefix} ${opName}: ingest rejected ${rejected.length} item(s), which were not stored: ${summarize(rejected, describeRejected)}`
1062
+ )
1063
+ );
1064
+ }
1065
+ const warnings = Array.isArray(body.warnings) ? body.warnings.filter(isRecord) : [];
1066
+ if (warnings.length > 0) {
1067
+ rateLimitedLog(
1068
+ `${prefix}.ingest_warnings`,
1069
+ () => console.warn(
1070
+ `${prefix} ${opName}: ingest accepted ${warnings.length} item(s) with changes: ${summarize(warnings, describeWarning)}`
1071
+ )
1072
+ );
1073
+ }
1074
+ }
1075
+ var DEFAULT_FLUSH_TIMEOUT_MS = 1e4;
766
1076
  var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
767
1077
  var MAX_RETRY_DELAY_MS = 3e4;
768
1078
  function wait(ms) {
769
1079
  return new Promise((resolve) => setTimeout(resolve, ms));
770
1080
  }
1081
+ function waitUnlessAborted(ms, signal) {
1082
+ if (!signal) return wait(ms);
1083
+ if (signal.aborted) return Promise.resolve();
1084
+ return new Promise((resolve) => {
1085
+ const done = () => {
1086
+ clearTimeout(timer);
1087
+ signal.removeEventListener("abort", done);
1088
+ resolve();
1089
+ };
1090
+ const timer = setTimeout(done, ms);
1091
+ signal.addEventListener("abort", done, { once: true });
1092
+ });
1093
+ }
1094
+ function eitherSignal(a, b) {
1095
+ if (!b) return a;
1096
+ const any = AbortSignal.any;
1097
+ if (typeof any === "function") return any([a, b]);
1098
+ const controller = new AbortController();
1099
+ const abort = () => controller.abort();
1100
+ if (a.aborted || b.aborted) abort();
1101
+ a.addEventListener("abort", abort, { once: true });
1102
+ b.addEventListener("abort", abort, { once: true });
1103
+ return controller.signal;
1104
+ }
771
1105
  function formatEndpoint(endpoint) {
772
1106
  if (!endpoint) return void 0;
773
1107
  return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
@@ -812,6 +1146,26 @@ async function raceWithTimeout(promise, timeoutMs) {
812
1146
  if (timer) clearTimeout(timer);
813
1147
  return settledInTime;
814
1148
  }
1149
+ var InFlightCutOff = class {
1150
+ constructor() {
1151
+ this.controller = new AbortController();
1152
+ }
1153
+ get signal() {
1154
+ return this.controller.signal;
1155
+ }
1156
+ cut() {
1157
+ this.controller.abort();
1158
+ this.controller = new AbortController();
1159
+ }
1160
+ };
1161
+ async function awaitEarlierSends(earlier, deadlineAt, cutOff, isRunning) {
1162
+ if (earlier.length === 0) return { settled: true, stillRunning: 0 };
1163
+ const settled = await raceWithTimeout(Promise.allSettled(earlier), deadlineAt - Date.now());
1164
+ if (settled) return { settled, stillRunning: 0 };
1165
+ const stillRunning = earlier.filter(isRunning).length;
1166
+ if (stillRunning > 0) cutOff.cut();
1167
+ return { settled: stillRunning === 0, stillRunning };
1168
+ }
815
1169
  function parseRetryAfter(headers) {
816
1170
  var _a;
817
1171
  const value = (_a = headers.get("Retry-After")) != null ? _a : headers.get("retry-after");
@@ -835,45 +1189,80 @@ function getRetryDelayMs(attemptNumber, previousError) {
835
1189
  const factor = Math.pow(2, attemptNumber - 2);
836
1190
  return Math.min(base * factor, MAX_RETRY_DELAY_MS);
837
1191
  }
838
- async function withRetry(operation, opName, opts) {
839
- const prefix = opts.sdkName ? `[raindrop-ai/${opts.sdkName}]` : "[raindrop-ai/core]";
840
- let lastError = void 0;
841
- for (let attemptNumber = 1; attemptNumber <= opts.maxAttempts; attemptNumber++) {
842
- if (attemptNumber > 1) {
843
- const delay = getRetryDelayMs(attemptNumber, lastError);
844
- if (opts.debug) {
845
- console.warn(
846
- `${prefix} ${opName} retry ${attemptNumber}/${opts.maxAttempts} in ${delay}ms`
847
- );
848
- }
849
- if (delay > 0) await wait(delay);
850
- } else if (opts.debug) {
851
- console.log(`${prefix} ${opName} attempt ${attemptNumber}/${opts.maxAttempts}`);
852
- }
853
- try {
854
- return await operation();
855
- } catch (err) {
856
- lastError = err;
857
- if (opts.debug) {
858
- const msg = err instanceof Error ? err.message : String(err);
859
- console.warn(
860
- `${prefix} ${opName} attempt ${attemptNumber} failed: ${msg}${attemptNumber === opts.maxAttempts ? " (no more retries)" : ""}`
861
- );
862
- }
863
- if (lastError && typeof lastError === "object" && "retryable" in lastError && !lastError.retryable)
864
- break;
865
- if (attemptNumber === opts.maxAttempts) break;
866
- }
1192
+ var sendPausedUntil = /* @__PURE__ */ new Map();
1193
+ function originOf(url) {
1194
+ try {
1195
+ return new URL(url).origin;
1196
+ } catch (e) {
1197
+ return url;
1198
+ }
1199
+ }
1200
+ function noteSendPause(url, status, retryAfterMs) {
1201
+ var _a;
1202
+ if (status !== 429 && status !== 503 || typeof retryAfterMs !== "number") return;
1203
+ const until = Date.now() + Math.min(Math.max(0, retryAfterMs), MAX_RETRY_DELAY_MS);
1204
+ const origin = originOf(url);
1205
+ sendPausedUntil.set(origin, Math.max((_a = sendPausedUntil.get(origin)) != null ? _a : 0, until));
1206
+ }
1207
+ function pausedUntil(url) {
1208
+ const until = sendPausedUntil.get(originOf(url));
1209
+ if (until === void 0) return void 0;
1210
+ if (until <= Date.now()) {
1211
+ sendPausedUntil.delete(originOf(url));
1212
+ return void 0;
867
1213
  }
868
- throw lastError instanceof Error ? lastError : new Error(String(lastError));
1214
+ return Math.min(until, Date.now() + MAX_RETRY_DELAY_MS);
1215
+ }
1216
+ function prefixFor(opts) {
1217
+ return opts.sdkName ? `[raindrop-ai/${opts.sdkName}]` : "[raindrop-ai/core]";
869
1218
  }
870
1219
  async function postJson(url, body, headers, opts) {
1220
+ var _a;
1221
+ const outcome = await sendJson(url, body, headers, { ...opts, deadlineAt: void 0 });
1222
+ if (outcome.status === "delivered") return;
1223
+ throw (_a = outcome.error) != null ? _a : new Error(`${redactUrlForLog(url)}: not sent (${outcome.status})`);
1224
+ }
1225
+ async function sendJson(url, body, headers, opts) {
871
1226
  var _a;
872
1227
  const opName = `POST ${redactUrlForLog(url)}`;
1228
+ const prefix = prefixFor(opts);
873
1229
  const timeoutMs = (_a = opts.timeoutMs) != null ? _a : DEFAULT_REQUEST_TIMEOUT_MS;
874
- await withRetry(
875
- async () => {
876
- const resp = await runWithTracingSuppressed(
1230
+ const deadlineAt = opts.deadlineAt;
1231
+ const remaining = () => deadlineAt === void 0 ? Infinity : deadlineAt - Date.now();
1232
+ let lastError;
1233
+ const cutOff = opts.cutOff;
1234
+ for (let attempt = 1; attempt <= opts.maxAttempts; attempt++) {
1235
+ if (cutOff == null ? void 0 : cutOff.aborted) return { status: "deferred", error: lastError };
1236
+ if (attempt > 1) {
1237
+ const delay = getRetryDelayMs(attempt, lastError);
1238
+ if (delay >= remaining()) {
1239
+ return { status: "deferred", retryAtMs: Date.now() + delay, error: lastError };
1240
+ }
1241
+ if (opts.debug) {
1242
+ console.warn(`${prefix} ${opName} retry ${attempt}/${opts.maxAttempts} in ${delay}ms`);
1243
+ }
1244
+ if (delay > 0) await waitUnlessAborted(delay, cutOff);
1245
+ if (cutOff == null ? void 0 : cutOff.aborted) return { status: "deferred", error: lastError };
1246
+ } else if (opts.debug) {
1247
+ console.log(`${prefix} ${opName} attempt ${attempt}/${opts.maxAttempts}`);
1248
+ }
1249
+ const pauseEnd = pausedUntil(url);
1250
+ if (pauseEnd !== void 0) {
1251
+ if (deadlineAt !== void 0 && pauseEnd >= deadlineAt) {
1252
+ return { status: "deferred", retryAtMs: pauseEnd, error: lastError };
1253
+ }
1254
+ await waitUnlessAborted(Math.max(0, pauseEnd - Date.now()), cutOff);
1255
+ if (cutOff == null ? void 0 : cutOff.aborted) return { status: "deferred", retryAtMs: pauseEnd, error: lastError };
1256
+ }
1257
+ const left = remaining();
1258
+ if (left <= 0) return { status: "deferred", error: lastError };
1259
+ const attemptTimeoutMs = Math.min(timeoutMs, left);
1260
+ const clampedByDeadline = attemptTimeoutMs < timeoutMs;
1261
+ const timeoutSignal = AbortSignal.timeout(attemptTimeoutMs);
1262
+ const signal = eitherSignal(timeoutSignal, cutOff);
1263
+ let resp;
1264
+ try {
1265
+ resp = await runWithTracingSuppressed(
877
1266
  () => fetch(url, {
878
1267
  method: "POST",
879
1268
  redirect: headers["X-Raindrop-Replay-Id"] !== void 0 ? "error" : "follow",
@@ -882,24 +1271,98 @@ async function postJson(url, body, headers, opts) {
882
1271
  ...headers
883
1272
  },
884
1273
  body: JSON.stringify(body),
885
- signal: AbortSignal.timeout(timeoutMs)
1274
+ signal
886
1275
  })
887
1276
  );
888
- if (!resp.ok) {
889
- const text = await resp.text().catch(() => "");
890
- const err = new Error(
891
- `HTTP ${resp.status} ${resp.statusText}${text ? `: ${text}` : ""}`
892
- );
893
- const retryAfterMs = parseRetryAfter(resp.headers);
894
- if (typeof retryAfterMs === "number") err.retryAfterMs = retryAfterMs;
895
- err.retryable = resp.status === 429 || resp.status >= 500;
896
- throw err;
1277
+ } catch (err) {
1278
+ const error = err instanceof Error ? err : new Error(String(err));
1279
+ if ((cutOff == null ? void 0 : cutOff.aborted) || timeoutSignal.aborted && clampedByDeadline) {
1280
+ return { status: "cut_off", error };
897
1281
  }
898
- },
899
- opName,
900
- opts
1282
+ lastError = error;
1283
+ logAttemptFailure(opts, prefix, opName, attempt, error);
1284
+ continue;
1285
+ }
1286
+ if (!resp.ok) {
1287
+ const text = await resp.text().catch(() => "");
1288
+ const error = new Error(
1289
+ `HTTP ${resp.status} ${resp.statusText}${text ? `: ${text}` : ""}`
1290
+ );
1291
+ const retryAfterMs = parseRetryAfter(resp.headers);
1292
+ if (typeof retryAfterMs === "number") error.retryAfterMs = retryAfterMs;
1293
+ noteSendPause(url, resp.status, retryAfterMs);
1294
+ error.retryable = resp.status === 408 || resp.status === 429 || resp.status >= 500;
1295
+ if (!error.retryable) return { status: "rejected", error };
1296
+ lastError = error;
1297
+ logAttemptFailure(opts, prefix, opName, attempt, error);
1298
+ continue;
1299
+ }
1300
+ try {
1301
+ reportIngestResponse(await resp.text(), prefix, opName);
1302
+ } catch (e) {
1303
+ }
1304
+ return { status: "delivered" };
1305
+ }
1306
+ return { status: "failed", error: lastError != null ? lastError : new Error(`${opName}: no attempts`) };
1307
+ }
1308
+ function logAttemptFailure(opts, prefix, opName, attempt, error) {
1309
+ if (!opts.debug) return;
1310
+ console.warn(
1311
+ `${prefix} ${opName} attempt ${attempt} failed: ${error.message}${attempt === opts.maxAttempts ? " (no more retries)" : ""}`
1312
+ );
1313
+ }
1314
+ function asCompat(result) {
1315
+ return result;
1316
+ }
1317
+ var DELIVERED = Object.freeze({
1318
+ delivered: true,
1319
+ timedOut: false,
1320
+ dropped: 0,
1321
+ queued: 0,
1322
+ inFlight: 0
1323
+ });
1324
+ function fateOf(outcome, shuttingDown) {
1325
+ switch (outcome.status) {
1326
+ case "delivered":
1327
+ case "rejected":
1328
+ return "delivered";
1329
+ case "deferred":
1330
+ return shuttingDown ? "dropped" : "queued";
1331
+ default:
1332
+ return "dropped";
1333
+ }
1334
+ }
1335
+ function summarize2(fates, inFlight, timedOut) {
1336
+ const dropped = fates.filter((fate) => fate === "dropped").length;
1337
+ const queued = fates.filter((fate) => fate === "queued").length;
1338
+ return {
1339
+ delivered: dropped === 0 && queued === 0 && inFlight === 0,
1340
+ timedOut: timedOut || queued > 0 || inFlight > 0,
1341
+ dropped,
1342
+ queued,
1343
+ inFlight
1344
+ };
1345
+ }
1346
+ function combineResults(...results) {
1347
+ return results.reduce(
1348
+ (acc, r) => ({
1349
+ delivered: acc.delivered && r.delivered,
1350
+ timedOut: acc.timedOut || r.timedOut,
1351
+ dropped: acc.dropped + r.dropped,
1352
+ queued: acc.queued + r.queued,
1353
+ inFlight: acc.inFlight + r.inFlight
1354
+ }),
1355
+ { ...DELIVERED }
901
1356
  );
902
1357
  }
1358
+ function describeUndelivered(what, result) {
1359
+ const parts = [
1360
+ result.dropped > 0 ? `${result.dropped} dropped` : "",
1361
+ result.queued > 0 ? `${result.queued} still queued` : "",
1362
+ result.inFlight > 0 ? `${result.inFlight} still sending` : ""
1363
+ ].filter(Boolean);
1364
+ return `${what} returned before everything was delivered: ${parts.join(", ")}`;
1365
+ }
903
1366
  var DEFAULT_MAX_TEXT_FIELD_CHARS = 1e6;
904
1367
  var TRUNCATION_MARKER = "...[truncated by raindrop]";
905
1368
  var BOUNDED_CLONE_MAX_DEPTH = 12;
@@ -1109,8 +1572,23 @@ var PROJECT_ID_HEADER = "X-Raindrop-Project-Id";
1109
1572
  function projectIdHeaders(projectId) {
1110
1573
  return projectId ? { [PROJECT_ID_HEADER]: projectId } : {};
1111
1574
  }
1112
- var SHUTDOWN_DEADLINE_MS = 1e4;
1575
+ var import_redact_pii = __toESM2(require_dist(), 1);
1576
+ var PROTECTED_LOCATIONS = new Set(
1577
+ [
1578
+ ["event_id"],
1579
+ ["user_id"],
1580
+ ["ai_data", "convo_id"],
1581
+ ["event"],
1582
+ ["timestamp"],
1583
+ ["is_pending"],
1584
+ ["signal_name"],
1585
+ ["signal_type"]
1586
+ ].map((keys) => JSON.stringify(keys))
1587
+ );
1113
1588
  var POST_SHUTDOWN_TIMEOUT_MS = 5e3;
1589
+ function resolveFlushTimeoutMs(value) {
1590
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : DEFAULT_FLUSH_TIMEOUT_MS;
1591
+ }
1114
1592
  var MODEL_USAGE_ATTRIBUTES = {
1115
1593
  usageSource: "raindrop.usage.source",
1116
1594
  providerName: "gen_ai.provider.name",
@@ -1170,6 +1648,21 @@ function buildRawModelUsageAttributes(usage) {
1170
1648
  attrDouble(MODEL_USAGE_ATTRIBUTES.providerReportedCost, providerReportedCost)
1171
1649
  ].filter((attribute) => attribute !== void 0);
1172
1650
  }
1651
+ var KNOWN_MODEL_PROVIDERS = /* @__PURE__ */ new Set([
1652
+ ...MODEL_PROVIDER_NAMES.map(([, family]) => family),
1653
+ "vercel",
1654
+ // Further vendors Dawn's pricing resolves (apps/dawn/lib/spend).
1655
+ "deepseek",
1656
+ "fireworks-ai",
1657
+ "groq",
1658
+ "inception",
1659
+ "mistral",
1660
+ "moonshotai",
1661
+ "perplexity",
1662
+ "togetherai",
1663
+ "xai",
1664
+ "zai"
1665
+ ]);
1173
1666
  var STRING_ALIASES = {
1174
1667
  [MODEL_USAGE_ATTRIBUTES.requestModel]: ["ai.model.id", "ai.model"]
1175
1668
  };
@@ -1245,8 +1738,15 @@ var DEFAULT_REDACT_ATTRIBUTE_KEYS = [
1245
1738
  "ai.response.providerMetadata"
1246
1739
  ];
1247
1740
  var REDACT_JSON_ATTRIBUTE_KEYS = new Set(DEFAULT_REDACT_ATTRIBUTE_KEYS);
1741
+ var UNDELIVERED = Object.freeze({
1742
+ delivered: false,
1743
+ timedOut: false,
1744
+ dropped: 0,
1745
+ queued: 0,
1746
+ inFlight: 0
1747
+ });
1248
1748
  var PROMPT_TOOLS_ATTRIBUTE = "ai.prompt.tools";
1249
- function isRecord(value) {
1749
+ function isRecord3(value) {
1250
1750
  return typeof value === "object" && value !== null && !Array.isArray(value);
1251
1751
  }
1252
1752
  var JSON_SCHEMA_KEYS = [
@@ -1264,17 +1764,17 @@ var JSON_SCHEMA_KEYS = [
1264
1764
  "required"
1265
1765
  ];
1266
1766
  function isJsonSchema(value) {
1267
- if (!isRecord(value)) return false;
1767
+ if (!isRecord3(value)) return false;
1268
1768
  if (typeof value["~standard"] === "object") return false;
1269
- if (isRecord(value._def) || isRecord(value._zod)) return false;
1769
+ if (isRecord3(value._def) || isRecord3(value._zod)) return false;
1270
1770
  if (Object.keys(value).length === 0) return true;
1271
1771
  return JSON_SCHEMA_KEYS.some((key) => key in value);
1272
1772
  }
1273
1773
  function toJsonSchema(value, options) {
1274
1774
  if (value === void 0 || value === null) return void 0;
1275
1775
  if (isJsonSchema(value)) return value;
1276
- if (isRecord(value) && isJsonSchema(value.jsonSchema)) return value.jsonSchema;
1277
- if (isRecord(value) && isJsonSchema(value.json)) return value.json;
1776
+ if (isRecord3(value) && isJsonSchema(value.jsonSchema)) return value.jsonSchema;
1777
+ if (isRecord3(value) && isJsonSchema(value.json)) return value.json;
1278
1778
  if (options == null ? void 0 : options.schema) {
1279
1779
  try {
1280
1780
  return options.schema(value);
@@ -1297,23 +1797,23 @@ function functionTool(name, description, schema, options) {
1297
1797
  }
1298
1798
  function normalizeToolDeclaration(tool, options, fallbackName) {
1299
1799
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
1300
- if (!isRecord(tool)) return void 0;
1800
+ if (!isRecord3(tool)) return void 0;
1301
1801
  if (tool.type === "provider-defined" || tool.type === "provider") {
1302
1802
  const name2 = (_b = (_a = pickString(tool.name)) != null ? _a : pickString(tool.id)) != null ? _b : fallbackName;
1303
1803
  if (name2 === void 0) return void 0;
1304
1804
  const declaration = { type: "provider-defined", name: name2 };
1305
1805
  const id = pickString(tool.id);
1306
1806
  if (id !== void 0) declaration.id = id;
1307
- if (isRecord(tool.args)) declaration.args = tool.args;
1807
+ if (isRecord3(tool.args)) declaration.args = tool.args;
1308
1808
  return declaration;
1309
1809
  }
1310
- if (isRecord(tool.toolSpec)) {
1810
+ if (isRecord3(tool.toolSpec)) {
1311
1811
  const spec = tool.toolSpec;
1312
1812
  const name2 = (_c = pickString(spec.name)) != null ? _c : fallbackName;
1313
1813
  if (name2 === void 0) return void 0;
1314
1814
  return functionTool(name2, spec.description, spec.inputSchema, options);
1315
1815
  }
1316
- if (isRecord(tool.function)) {
1816
+ if (isRecord3(tool.function)) {
1317
1817
  const fn = tool.function;
1318
1818
  const name2 = (_d = pickString(fn.name)) != null ? _d : fallbackName;
1319
1819
  if (name2 === void 0) return void 0;
@@ -1339,7 +1839,7 @@ function isGeminiToolGroup(tool) {
1339
1839
  if (Array.isArray(tool.functionDeclarations)) return true;
1340
1840
  const keys = Object.keys(tool);
1341
1841
  if (keys.length === 0 || NOT_A_GEMINI_GROUP_KEYS.some((key) => key in tool)) return false;
1342
- return keys.every((key) => isRecord(tool[key]));
1842
+ return keys.every((key) => isRecord3(tool[key]));
1343
1843
  }
1344
1844
  function expandGeminiTool(tool, options) {
1345
1845
  const declarations = [];
@@ -1349,7 +1849,7 @@ function expandGeminiTool(tool, options) {
1349
1849
  const normalized = normalizeToolDeclaration(declaration, options);
1350
1850
  if (normalized) declarations.push(normalized);
1351
1851
  }
1352
- } else if (isRecord(value)) {
1852
+ } else if (isRecord3(value)) {
1353
1853
  declarations.push({ type: "provider-defined", id: key, name: key, args: value });
1354
1854
  }
1355
1855
  }
@@ -1359,14 +1859,14 @@ function normalizeToolDeclarations(tools, options) {
1359
1859
  if (tools === void 0 || tools === null) return void 0;
1360
1860
  if (Array.isArray(tools)) {
1361
1861
  return tools.flatMap((tool) => {
1362
- if (isRecord(tool) && isGeminiToolGroup(tool)) {
1862
+ if (isRecord3(tool) && isGeminiToolGroup(tool)) {
1363
1863
  return expandGeminiTool(tool, options);
1364
1864
  }
1365
1865
  const declaration = normalizeToolDeclaration(tool, options);
1366
1866
  return declaration ? [declaration] : [];
1367
1867
  });
1368
1868
  }
1369
- if (!isRecord(tools)) return void 0;
1869
+ if (!isRecord3(tools)) return void 0;
1370
1870
  return Object.entries(tools).flatMap(([key, tool]) => {
1371
1871
  const declaration = normalizeToolDeclaration(tool, options, key);
1372
1872
  return declaration ? [declaration] : [];
@@ -1468,97 +1968,10 @@ if (!globalThis.RAINDROP_ASYNC_LOCAL_STORAGE) {
1468
1968
  }
1469
1969
 
1470
1970
  // src/tracing/direct/http.ts
1471
- function wait2(ms) {
1472
- return new Promise((resolve) => setTimeout(resolve, ms));
1473
- }
1474
1971
  function formatEndpoint2(endpoint) {
1475
1972
  if (!endpoint) return void 0;
1476
1973
  return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
1477
1974
  }
1478
- function parseRetryAfter2(headers) {
1479
- var _a;
1480
- const value = (_a = headers.get("Retry-After")) != null ? _a : headers.get("retry-after");
1481
- if (!value) return void 0;
1482
- const asNumber = Number(value);
1483
- if (!Number.isNaN(asNumber)) return asNumber * 1e3;
1484
- const asDate = new Date(value).getTime();
1485
- if (!Number.isNaN(asDate)) {
1486
- const delta = asDate - Date.now();
1487
- return delta > 0 ? delta : 0;
1488
- }
1489
- return void 0;
1490
- }
1491
- function getRetryDelayMs2(attemptNumber, previousError) {
1492
- if (previousError && typeof previousError === "object" && previousError !== null && "retryAfterMs" in previousError) {
1493
- const v = previousError.retryAfterMs;
1494
- if (typeof v === "number") return Math.min(Math.max(0, v), MAX_RETRY_DELAY_MS);
1495
- }
1496
- if (attemptNumber <= 1) return 0;
1497
- const base = 500;
1498
- const factor = Math.pow(2, attemptNumber - 2);
1499
- return Math.min(base * factor, MAX_RETRY_DELAY_MS);
1500
- }
1501
- async function withRetry2(operation, opName, opts) {
1502
- let lastError = void 0;
1503
- for (let attemptNumber = 1; attemptNumber <= opts.maxAttempts; attemptNumber++) {
1504
- if (attemptNumber > 1) {
1505
- const delay = getRetryDelayMs2(attemptNumber, lastError);
1506
- if (opts.debug) {
1507
- console.warn(
1508
- `[raindrop] ${opName} retry ${attemptNumber}/${opts.maxAttempts} in ${delay}ms`
1509
- );
1510
- }
1511
- if (delay > 0) await wait2(delay);
1512
- } else if (opts.debug) {
1513
- console.log(`[raindrop] ${opName} attempt ${attemptNumber}/${opts.maxAttempts}`);
1514
- }
1515
- try {
1516
- return await operation();
1517
- } catch (err) {
1518
- lastError = err;
1519
- if (opts.debug) {
1520
- const msg = err instanceof Error ? err.message : String(err);
1521
- console.warn(
1522
- `[raindrop] ${opName} attempt ${attemptNumber} failed: ${msg}${attemptNumber === opts.maxAttempts ? " (no more retries)" : ""}`
1523
- );
1524
- }
1525
- if (attemptNumber === opts.maxAttempts) break;
1526
- }
1527
- }
1528
- throw lastError instanceof Error ? lastError : new Error(String(lastError));
1529
- }
1530
- async function postJson2(url, body, headers, opts) {
1531
- var _a;
1532
- const opName = `POST ${redactUrlForLog(url)}`;
1533
- const timeoutMs = (_a = opts.timeoutMs) != null ? _a : DEFAULT_REQUEST_TIMEOUT_MS;
1534
- await withRetry2(
1535
- async () => {
1536
- const resp = await runWithTracingSuppressed(
1537
- () => fetch(url, {
1538
- method: "POST",
1539
- redirect: headers["X-Raindrop-Replay-Id"] !== void 0 ? "error" : "follow",
1540
- headers: {
1541
- "Content-Type": "application/json",
1542
- ...headers
1543
- },
1544
- body: JSON.stringify(body),
1545
- signal: AbortSignal.timeout(timeoutMs)
1546
- })
1547
- );
1548
- if (!resp.ok) {
1549
- const text = await resp.text().catch(() => "");
1550
- const err = new Error(
1551
- `HTTP ${resp.status} ${resp.statusText}${text ? `: ${text}` : ""}`
1552
- );
1553
- const retryAfterMs = parseRetryAfter2(resp.headers);
1554
- if (typeof retryAfterMs === "number") err.retryAfterMs = retryAfterMs;
1555
- throw err;
1556
- }
1557
- },
1558
- opName,
1559
- opts
1560
- );
1561
- }
1562
1975
 
1563
1976
  // src/tracing/direct/ids.ts
1564
1977
  function getCrypto2() {
@@ -1624,7 +2037,7 @@ function base64ToHex2(base64) {
1624
2037
  // package.json
1625
2038
  var package_default = {
1626
2039
  name: "raindrop-ai",
1627
- version: "1.0.5",
2040
+ version: "1.0.6",
1628
2041
  main: "dist/index.js",
1629
2042
  module: "dist/index.mjs",
1630
2043
  types: "dist/index.d.ts",
@@ -1845,6 +2258,17 @@ function getActiveTraceContext() {
1845
2258
  parentSpanIdB64: spanIdHex !== INVALID_SPAN_ID ? hexToBase64(spanIdHex) : void 0
1846
2259
  };
1847
2260
  }
2261
+ function savedParentContext(traceId, parentSpanId) {
2262
+ if (!traceId || !parentSpanId || !(0, import_api.isValidTraceId)(traceId) || !(0, import_api.isValidSpanId)(parentSpanId)) {
2263
+ return void 0;
2264
+ }
2265
+ return import_api.trace.setSpanContext(import_api.context.active(), {
2266
+ traceId,
2267
+ spanId: parentSpanId,
2268
+ traceFlags: import_api.TraceFlags.SAMPLED,
2269
+ isRemote: true
2270
+ });
2271
+ }
1848
2272
 
1849
2273
  // src/tracing/multi-project.ts
1850
2274
  var import_node_crypto = require("crypto");
@@ -2207,6 +2631,8 @@ var DirectTraceShipper = class {
2207
2631
  constructor(opts) {
2208
2632
  this.queue = [];
2209
2633
  this.inFlight = /* @__PURE__ */ new Set();
2634
+ /** Cuts off sends still running at a flush or shutdown deadline. */
2635
+ this.cutOff = new InFlightCutOff();
2210
2636
  /**
2211
2637
  * Set once `shutdown()` begins and never cleared. Sends issued after the
2212
2638
  * drain window (stragglers, or flush work the deadline abandoned
@@ -2225,6 +2651,7 @@ var DirectTraceShipper = class {
2225
2651
  this.flushIntervalMs = (_d = opts.flushIntervalMs) != null ? _d : 1e3;
2226
2652
  this.maxBatchSize = (_e = opts.maxBatchSize) != null ? _e : 50;
2227
2653
  this.maxQueueSize = (_f = opts.maxQueueSize) != null ? _f : 5e3;
2654
+ this.flushTimeoutMs = resolveFlushTimeoutMs(opts.flushTimeoutMs);
2228
2655
  const resolved = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl);
2229
2656
  if (resolved && resolved !== this.baseUrl) {
2230
2657
  this.localDebuggerUrl = resolved;
@@ -2353,28 +2780,56 @@ var DirectTraceShipper = class {
2353
2780
  }
2354
2781
  this.queue.push(queued);
2355
2782
  if (this.queue.length >= this.maxBatchSize) {
2356
- void this.flush().catch(() => {
2783
+ void this.drain().catch(() => {
2357
2784
  });
2358
2785
  return;
2359
2786
  }
2360
- if (!this.timer) {
2361
- this.timer = setTimeout(() => {
2362
- this.timer = void 0;
2363
- void this.flush().catch(() => {
2364
- });
2365
- }, this.flushIntervalMs);
2366
- }
2787
+ this.scheduleDrain(this.flushIntervalMs);
2367
2788
  }
2789
+ scheduleDrain(delayMs) {
2790
+ if (this.timer) return;
2791
+ this.timer = setTimeout(() => {
2792
+ this.timer = void 0;
2793
+ void this.drain().catch(() => {
2794
+ });
2795
+ }, delayMs);
2796
+ }
2797
+ /**
2798
+ * Send every queued span within `flushTimeoutMs` (CONTRACT 1.2.1). Resolves,
2799
+ * never rejects; spans not yet sent at the deadline stay queued.
2800
+ */
2368
2801
  async flush() {
2802
+ const result = await this.drainWithin(Date.now() + this.flushTimeoutMs);
2803
+ if (!result.delivered && this.shutdownDeadlineAt === void 0) {
2804
+ rateLimitedLog(
2805
+ "js-sdk.direct.flush_undelivered",
2806
+ () => console.warn(`[raindrop] direct: ${describeUndelivered("flush()", result)}`)
2807
+ );
2808
+ }
2809
+ return asCompat(result);
2810
+ }
2811
+ async drainWithin(deadlineAt) {
2812
+ const earlier = [...this.inFlight];
2813
+ const fates = this.enabled ? await this.drain(deadlineAt) : [];
2814
+ const { settled, stillRunning } = await awaitEarlierSends(
2815
+ earlier,
2816
+ deadlineAt,
2817
+ this.cutOff,
2818
+ (p) => this.inFlight.has(p)
2819
+ );
2820
+ return summarize2(fates, stillRunning, !settled);
2821
+ }
2822
+ async drain(deadlineAt) {
2369
2823
  var _a;
2370
- if (!this.enabled) return;
2824
+ const fates = [];
2825
+ if (!this.enabled) return fates;
2371
2826
  if (this.timer) {
2372
2827
  clearTimeout(this.timer);
2373
2828
  this.timer = void 0;
2374
2829
  }
2375
2830
  while (this.queue.length > 0) {
2376
2831
  const batch = this.queue.splice(0, this.maxBatchSize);
2377
- const opts = this.requestOpts();
2832
+ const opts = this.requestOpts(deadlineAt);
2378
2833
  if (!opts) {
2379
2834
  rateLimitedLog(
2380
2835
  "js-sdk.direct.shutdown_deadline",
@@ -2382,84 +2837,108 @@ var DirectTraceShipper = class {
2382
2837
  `[raindrop] direct: shutdown flush deadline exceeded; dropping ${batch.length} spans`
2383
2838
  )
2384
2839
  );
2840
+ fates.push("dropped");
2385
2841
  continue;
2386
2842
  }
2387
2843
  const groups = /* @__PURE__ */ new Map();
2388
2844
  for (const queued of batch) {
2389
2845
  const spans = groups.get(queued.replayDestination);
2390
- if (spans) spans.push(queued.span);
2391
- else groups.set(queued.replayDestination, [queued.span]);
2846
+ if (spans) spans.push(queued);
2847
+ else groups.set(queued.replayDestination, [queued]);
2392
2848
  }
2393
- for (const [replayDestination, spans] of groups) {
2849
+ const requeue = [];
2850
+ let retryAtMs;
2851
+ for (const [replayDestination, queuedSpans] of groups) {
2394
2852
  if (!replayDestination && !this.cloudEnabled) continue;
2395
2853
  if ((replayDestination == null ? void 0 : replayDestination.kind) === "workshop") continue;
2396
- const body = buildExportTraceServiceRequest2(spans);
2854
+ const body = buildExportTraceServiceRequest2(queuedSpans.map((q) => q.span));
2397
2855
  const url = replayDestination ? replayTraceUrl(replayDestination.url) : `${this.baseUrl}traces`;
2398
2856
  const headers = replayDestination ? {
2399
2857
  Authorization: `Bearer ${replayDestination.apiKey}`,
2400
2858
  "X-Raindrop-Replay-Id": replayDestination.replayId,
2401
2859
  "X-Raindrop-Project-Id": (_a = replayDestination.projectId) != null ? _a : "default"
2402
2860
  } : { Authorization: `Bearer ${this.writeKey}`, ...projectIdHeaders(this.projectId) };
2403
- const p = postJson2(url, body, headers, opts);
2404
- this.inFlight.add(p);
2861
+ const sending = sendJson(url, body, headers, opts);
2862
+ const tracked = sending.then(() => void 0);
2863
+ this.inFlight.add(tracked);
2864
+ let outcome;
2405
2865
  try {
2406
- try {
2407
- await p;
2408
- if (this.debug) console.log(`[raindrop] direct: sent ${spans.length} spans`);
2409
- } catch (err) {
2410
- if (this.debug) {
2411
- const msg = err instanceof Error ? err.message : String(err);
2412
- console.warn(`[raindrop] direct: failed to send spans (dropping): ${msg}`);
2413
- }
2414
- }
2866
+ outcome = await sending;
2415
2867
  } finally {
2416
- this.inFlight.delete(p);
2868
+ this.inFlight.delete(tracked);
2869
+ }
2870
+ const fate = fateOf(outcome, this.shutdownDeadlineAt !== void 0 || this.hasShutdown);
2871
+ fates.push(fate);
2872
+ if (fate === "queued") {
2873
+ requeue.push(...queuedSpans);
2874
+ if (outcome.status === "deferred" && outcome.retryAtMs !== void 0) {
2875
+ retryAtMs = Math.max(retryAtMs != null ? retryAtMs : 0, outcome.retryAtMs);
2876
+ }
2877
+ } else if (fate === "dropped") {
2878
+ const reason = outcome.status === "cut_off" ? "cut off at the flush deadline (not resent: it may have reached ingest)" : outcome.status === "deferred" ? "not sent before the shutdown deadline" : "error" in outcome && outcome.error ? outcome.error.message : outcome.status;
2879
+ rateLimitedLog(
2880
+ "js-sdk.direct.send_failed",
2881
+ () => console.warn(`[raindrop] direct: failed to send ${queuedSpans.length} spans (dropping): ${reason}`)
2882
+ );
2883
+ } else if (this.debug) {
2884
+ console.log(`[raindrop] direct: sent ${queuedSpans.length} spans`);
2417
2885
  }
2418
2886
  }
2887
+ if (requeue.length > 0) {
2888
+ this.queue.unshift(...requeue);
2889
+ if (this.queue.length > this.maxQueueSize) this.queue.splice(this.maxQueueSize);
2890
+ this.scheduleDrain(Math.max(this.flushIntervalMs, (retryAtMs != null ? retryAtMs : 0) - Date.now()));
2891
+ break;
2892
+ }
2419
2893
  }
2894
+ return fates;
2420
2895
  }
2421
2896
  /**
2422
- * Retry/timeout options for one batch POST, honoring the shutdown budget:
2423
- * outside shutdown, the normal 3-attempt schedule; during shutdown, a
2424
- * single attempt clamped to the remaining window; `null` once the window
2425
- * is exhausted (caller drops the batch). After shutdown() returns,
2426
- * stragglers run as a single short attempt.
2897
+ * Retry/timeout options for one batch POST: the normal 3-attempt schedule,
2898
+ * bounded by a flush deadline when given; during shutdown, retries within
2899
+ * the shutdown window; `null` once the window is spent (caller drops the
2900
+ * batch). After shutdown() returns, stragglers run as a single short attempt.
2427
2901
  */
2428
- requestOpts() {
2902
+ requestOpts(deadlineAt) {
2903
+ const opts = this.scheduleFor(deadlineAt);
2904
+ return opts && { ...opts, cutOff: this.cutOff.signal };
2905
+ }
2906
+ scheduleFor(deadlineAt) {
2429
2907
  if (this.shutdownDeadlineAt !== void 0) {
2430
- const remainingMs = this.shutdownDeadlineAt - Date.now();
2431
- if (remainingMs <= 0) return null;
2908
+ if (this.shutdownDeadlineAt - Date.now() <= 0) return null;
2432
2909
  return {
2433
- maxAttempts: 1,
2910
+ maxAttempts: 3,
2434
2911
  debug: this.debug,
2435
- timeoutMs: Math.min(DEFAULT_REQUEST_TIMEOUT_MS, remainingMs)
2912
+ deadlineAt: Math.min(this.shutdownDeadlineAt, deadlineAt != null ? deadlineAt : Infinity)
2436
2913
  };
2437
2914
  }
2438
2915
  if (this.hasShutdown) {
2439
2916
  return { maxAttempts: 1, debug: this.debug, timeoutMs: POST_SHUTDOWN_TIMEOUT_MS };
2440
2917
  }
2441
- return { maxAttempts: 3, debug: this.debug };
2918
+ return { maxAttempts: 3, debug: this.debug, deadlineAt };
2442
2919
  }
2920
+ /** Flush within `flushTimeoutMs` and stop; spans left at the deadline are dropped. */
2443
2921
  async shutdown() {
2444
2922
  this.hasShutdown = true;
2445
- this.shutdownDeadlineAt = Date.now() + SHUTDOWN_DEADLINE_MS;
2923
+ const deadlineAt = Date.now() + this.flushTimeoutMs;
2924
+ this.shutdownDeadlineAt = deadlineAt;
2925
+ let result = { ...DELIVERED };
2446
2926
  try {
2447
2927
  if (this.timer) {
2448
2928
  clearTimeout(this.timer);
2449
2929
  this.timer = void 0;
2450
2930
  }
2451
- const drain = async () => {
2452
- await this.flush();
2453
- await Promise.all([...this.inFlight].map((p) => p.catch(() => {
2454
- })));
2455
- };
2456
- const settled = await raceWithTimeout(drain(), SHUTDOWN_DEADLINE_MS);
2457
- if (!settled && this.debug) {
2458
- console.warn("[raindrop] direct: shutdown deadline exceeded; abandoning in-flight spans");
2931
+ result = await this.drainWithin(deadlineAt);
2932
+ if (!result.delivered) {
2933
+ rateLimitedLog(
2934
+ "js-sdk.direct.shutdown_deadline",
2935
+ () => console.warn(`[raindrop] direct: ${describeUndelivered("shutdown()", result)}`)
2936
+ );
2459
2937
  }
2460
2938
  } finally {
2461
2939
  this.shutdownDeadlineAt = void 0;
2462
2940
  }
2941
+ return asCompat(result);
2463
2942
  }
2464
2943
  };
2465
2944
 
@@ -2953,6 +3432,21 @@ async function flushAll() {
2953
3432
  // src/tracing/liveInteraction.ts
2954
3433
  var import_api4 = require("@opentelemetry/api");
2955
3434
 
3435
+ // src/tracing/tool-timing.ts
3436
+ function toMs(value) {
3437
+ return value instanceof Date ? value.getTime() : value;
3438
+ }
3439
+ function resolveToolTiming(input, now = Date.now()) {
3440
+ var _a, _b, _c;
3441
+ if (input.endTime !== void 0) {
3442
+ const endTimeMs = toMs(input.endTime);
3443
+ const startTimeMs2 = input.startTime !== void 0 ? toMs(input.startTime) : endTimeMs - ((_a = input.durationMs) != null ? _a : 0);
3444
+ return { startTimeMs: startTimeMs2, endTimeMs, durationMs: endTimeMs - startTimeMs2 };
3445
+ }
3446
+ const startTimeMs = input.startTime !== void 0 ? toMs(input.startTime) : now - ((_b = input.durationMs) != null ? _b : 0);
3447
+ return { startTimeMs, endTimeMs: startTimeMs + ((_c = input.durationMs) != null ? _c : 0), durationMs: input.durationMs };
3448
+ }
3449
+
2956
3450
  // src/tracing/subagents.ts
2957
3451
  var import_api3 = require("@opentelemetry/api");
2958
3452
  var DEFAULT_SUBAGENT_NAME = "subagent";
@@ -4041,15 +4535,12 @@ var LiveInteraction = class {
4041
4535
  name,
4042
4536
  input,
4043
4537
  output,
4044
- durationMs,
4045
- startTime,
4046
4538
  error,
4047
4539
  properties = {},
4048
4540
  traceId: explicitTraceId,
4049
4541
  parentSpanId: explicitParentSpanId
4050
4542
  } = params;
4051
- const startTimeMs = startTime instanceof Date ? startTime.getTime() : typeof startTime === "number" ? startTime : Date.now() - (durationMs != null ? durationMs : 0);
4052
- const endTimeMs = startTimeMs + (durationMs != null ? durationMs : 0);
4543
+ const { startTimeMs, endTimeMs, durationMs } = resolveToolTiming(params);
4053
4544
  if (this.directShipper) {
4054
4545
  const activeContext = (_a = getExplicitTraceContext(explicitTraceId, explicitParentSpanId)) != null ? _a : getActiveTraceContext();
4055
4546
  const traceIdB64 = this.ensureTraceId(activeContext.traceIdB64);
@@ -4095,9 +4586,14 @@ var LiveInteraction = class {
4095
4586
  });
4096
4587
  return;
4097
4588
  }
4098
- const span = this.tracer.startSpan(name, {
4099
- startTime: startTimeMs
4100
- });
4589
+ const savedParent = savedParentContext(explicitTraceId, explicitParentSpanId);
4590
+ const span = this.tracer.startSpan(
4591
+ name,
4592
+ {
4593
+ startTime: startTimeMs
4594
+ },
4595
+ savedParent
4596
+ );
4101
4597
  const contextProperties = getPropertiesFromContext(this.context);
4102
4598
  setAssociationProperties(span, contextProperties);
4103
4599
  span.setAttribute("traceloop.span.kind", "tool");
@@ -4207,15 +4703,12 @@ var LiveTracer = class {
4207
4703
  name,
4208
4704
  input,
4209
4705
  output,
4210
- durationMs,
4211
- startTime,
4212
4706
  error,
4213
4707
  properties = {},
4214
4708
  traceId: explicitTraceId,
4215
4709
  parentSpanId: explicitParentSpanId
4216
4710
  } = params;
4217
- const startTimeMs = startTime instanceof Date ? startTime.getTime() : typeof startTime === "number" ? startTime : Date.now() - (durationMs != null ? durationMs : 0);
4218
- const endTimeMs = startTimeMs + (durationMs != null ? durationMs : 0);
4711
+ const { startTimeMs, endTimeMs, durationMs } = resolveToolTiming(params);
4219
4712
  if (this.directShipper) {
4220
4713
  const { traceIdB64, parentSpanIdB64 } = (_a = getExplicitTraceContext(explicitTraceId, explicitParentSpanId)) != null ? _a : getActiveTraceContext();
4221
4714
  const spanIdB64 = base64Encode2(randomBytes2(8));
@@ -4253,9 +4746,13 @@ var LiveTracer = class {
4253
4746
  }
4254
4747
  return;
4255
4748
  }
4256
- const span = this.tracer.startSpan(name, {
4257
- startTime: startTimeMs
4258
- });
4749
+ const span = this.tracer.startSpan(
4750
+ name,
4751
+ {
4752
+ startTime: startTimeMs
4753
+ },
4754
+ savedParentContext(explicitTraceId, explicitParentSpanId)
4755
+ );
4259
4756
  this.stampRouting(span);
4260
4757
  Object.entries(this.globalProperties).forEach(([key, value]) => {
4261
4758
  span.setAttribute("traceloop.association.properties." + key, String(value));
@@ -4812,6 +5309,7 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
4812
5309
  localDebuggerUrl,
4813
5310
  cloudEnabled,
4814
5311
  projectId,
5312
+ flushTimeoutMs,
4815
5313
  ...otherOptions
4816
5314
  } = options;
4817
5315
  const cloudEnabledResolved = cloudEnabled != null ? cloudEnabled : true;
@@ -4843,7 +5341,8 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
4843
5341
  enabled: tracingEnabled !== false,
4844
5342
  localDebuggerUrl,
4845
5343
  cloudEnabled: cloudEnabledResolved,
4846
- projectId
5344
+ projectId,
5345
+ flushTimeoutMs
4847
5346
  }) : void 0;
4848
5347
  let traceloopInitialized = false;
4849
5348
  let claimedPipeline = false;
@@ -5296,30 +5795,49 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
5296
5795
  * Safe to call when nothing is in flight; never throws.
5297
5796
  */
5298
5797
  async forceFlush() {
5798
+ const deadlineAt = Date.now() + resolveFlushTimeoutMs(flushTimeoutMs);
5799
+ let result = { ...DELIVERED };
5299
5800
  if (directShipper) {
5300
5801
  try {
5301
- await directShipper.flush();
5802
+ result = await directShipper.flush();
5302
5803
  } catch (e) {
5303
5804
  }
5304
5805
  }
5305
5806
  if (traceloopInitialized) {
5306
- try {
5307
- await forceFlush();
5308
- } catch (e) {
5807
+ const settled = await raceWithTimeout(
5808
+ forceFlush().catch(() => {
5809
+ }),
5810
+ deadlineAt - Date.now()
5811
+ );
5812
+ if (!settled) {
5813
+ result = combineResults(result, {
5814
+ ...DELIVERED,
5815
+ delivered: false,
5816
+ timedOut: true,
5817
+ inFlight: 1
5818
+ });
5309
5819
  }
5310
5820
  }
5821
+ return asCompat(result);
5311
5822
  },
5823
+ /** Drain and stop; resolves (never rejects) to the direct shipper's result. */
5312
5824
  async close() {
5825
+ var _a2;
5313
5826
  deregisterExitFlusher == null ? void 0 : deregisterExitFlusher();
5314
5827
  activeInteractions.clear();
5315
5828
  activeInteractionsByEventId.clear();
5316
- await (directShipper == null ? void 0 : directShipper.shutdown());
5829
+ let result = { ...DELIVERED };
5830
+ try {
5831
+ result = (_a2 = await (directShipper == null ? void 0 : directShipper.shutdown())) != null ? _a2 : result;
5832
+ } catch (e) {
5833
+ }
5317
5834
  if (traceloopInitialized) {
5318
5835
  try {
5319
5836
  await forceFlush();
5320
5837
  } catch (e) {
5321
5838
  }
5322
5839
  }
5840
+ return result;
5323
5841
  }
5324
5842
  };
5325
5843
  };