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.
@@ -4,7 +4,36 @@ if (!globalThis.RAINDROP_ASYNC_LOCAL_STORAGE) {
4
4
  globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = AsyncLocalStorage;
5
5
  }
6
6
 
7
- // ../core/dist/chunk-BYBMRLZM.js
7
+ // ../core/dist/chunk-ZCB62SIO.js
8
+ var __create = Object.create;
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __getProtoOf = Object.getPrototypeOf;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __commonJS = (cb, mod) => function __require() {
15
+ try {
16
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
+ } catch (e) {
18
+ throw mod = 0, e;
19
+ }
20
+ };
21
+ var __copyProps = (to, from, except, desc) => {
22
+ if (from && typeof from === "object" || typeof from === "function") {
23
+ for (let key of __getOwnPropNames(from))
24
+ if (!__hasOwnProp.call(to, key) && key !== except)
25
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
26
+ }
27
+ return to;
28
+ };
29
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
30
+ // If the importer is in node compatibility mode or this is not an ESM
31
+ // file that has been converted to a CommonJS file using a Babel-
32
+ // compatible transform (i.e. "__esModule" has not been set), then set
33
+ // "default" to the CommonJS "module.exports" for node compatibility.
34
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
35
+ mod
36
+ ));
8
37
  var EVAL_CORRELATION_ID_ATTRIBUTE = "raindrop.eval_correlation_id";
9
38
  var PROBE_SCOPE = { correlationId: "" };
10
39
  var EvalScopeStorage = class {
@@ -79,21 +108,246 @@ function evalScopeAttributes() {
79
108
  return { [EVAL_CORRELATION_ID_ATTRIBUTE]: scope.correlationId };
80
109
  }
81
110
 
82
- // ../core/dist/chunk-QH6U6QYP.js
111
+ // ../core/dist/chunk-AX36JKJL.js
112
+ var require_NameRedactor = __commonJS({
113
+ "../redact-pii/dist/built-ins/NameRedactor.js"(exports) {
114
+ Object.defineProperty(exports, "__esModule", { value: true });
115
+ exports.NameRedactor = void 0;
116
+ var greetingRegex = /(^|\.\s+)(dear|hi|hello|greetings|hey|hey there)/gi;
117
+ 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;
118
+ var greetingOrClosing = new RegExp("(((" + greetingRegex.source + ")|(" + closingRegex.source + "\\s*[,.!]*))[\\s-]*)", "gi");
119
+ var genericName = new RegExp("( ?(([A-Z][a-z]{1,30})|([A-Z]\\.))){1,10}([,.]|[,.]?$)", "my");
120
+ var NameRedactor = class {
121
+ constructor(replaceWith = "PERSON_NAME") {
122
+ this.replaceWith = replaceWith;
123
+ }
124
+ redact(textToRedact) {
125
+ var _a;
126
+ greetingOrClosing.lastIndex = 0;
127
+ genericName.lastIndex = 0;
128
+ const pieces = [];
129
+ let copiedThrough = 0;
130
+ let changed = false;
131
+ let greetingOrClosingMatch = greetingOrClosing.exec(textToRedact);
132
+ while (greetingOrClosingMatch !== null) {
133
+ genericName.lastIndex = greetingOrClosing.lastIndex;
134
+ const genericNameMatch = genericName.exec(textToRedact);
135
+ if (genericNameMatch !== null && genericNameMatch.index === greetingOrClosing.lastIndex) {
136
+ const suffix = (_a = genericNameMatch[5]) !== null && _a !== void 0 ? _a : "";
137
+ const end = genericNameMatch.index + genericNameMatch[0].length;
138
+ pieces.push(textToRedact.slice(copiedThrough, genericNameMatch.index), this.replaceWith, suffix);
139
+ copiedThrough = end;
140
+ changed = true;
141
+ greetingOrClosing.lastIndex = end - suffix.length;
142
+ }
143
+ greetingOrClosingMatch = greetingOrClosing.exec(textToRedact);
144
+ }
145
+ if (!changed)
146
+ return textToRedact;
147
+ pieces.push(textToRedact.slice(copiedThrough));
148
+ return pieces.join("");
149
+ }
150
+ };
151
+ exports.NameRedactor = NameRedactor;
152
+ }
153
+ });
154
+ var require_simple_regexp_patterns = __commonJS({
155
+ "../redact-pii/dist/built-ins/simple-regexp-patterns.js"(exports) {
156
+ Object.defineProperty(exports, "__esModule", { value: true });
157
+ exports.url = exports.digits = exports.credentials = exports.password = exports.username = exports.emailAddress = exports.usSocialSecurityNumber = exports.ipAddress = exports.phoneNumber = exports.zipcode = exports.streetAddress = exports.creditCardNumber = void 0;
158
+ var aptRegex = /(apt|bldg|dept|fl|hngr|lot|pier|rm|ste|slip|trlr|unit|#)\.? *[a-z0-9-]+\b/gi;
159
+ var poBoxRegex = /P\.? ?O\.? *Box +\d+/gi;
160
+ var roadRegex = /(street|st|road|rd|avenue|ave|drive|dr|loop|court|ct|circle|cir|lane|ln|boulevard|blvd|way)\.?\b/gi;
161
+ exports.creditCardNumber = /\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}|\d{4}[ -]?\d{6}[ -]?\d{4}\d?/g;
162
+ exports.streetAddress = new RegExp("(\\d{1,10}\\s*(\\w{1,30} ){1,2}" + roadRegex.source + "(\\s+" + aptRegex.source + ")?)|(" + poBoxRegex.source + ")", "gi");
163
+ exports.zipcode = /\b\d{5}\b(-\d{4})?\b/g;
164
+ exports.phoneNumber = /(\(?\+?[0-9]{1,2}\)?[-. ]?)?(\(?[0-9]{3}\)?|[0-9]{3})[-. ]?([0-9]{3}[-. ]?[0-9]{4}|\b[A-Z0-9]{7}\b)/g;
165
+ exports.ipAddress = /(\d{1,3}(\.\d{1,3}){3}|[0-9A-F]{4}(:[0-9A-F]{4}){5}(::|(:0000)+))/gi;
166
+ exports.usSocialSecurityNumber = /\b\d{3}[ -.]\d{2}[ -.]\d{4}\b/g;
167
+ exports.emailAddress = /([a-z0-9_\-.+]{1,64})@\w+(\.\w+)*/gi;
168
+ exports.username = /(user( ?name)?|login): \S+/gi;
169
+ exports.password = /(pass(word|phrase)?|secret): \S+/gi;
170
+ exports.credentials = /(login( cred(ential)?s| info(rmation)?)?|cred(ential)?s) ?:\s*\S+\s+\/?\s*\S+/gi;
171
+ exports.digits = /\b\d{4,}\b/g;
172
+ exports.url = /([^\s:/?#]{1,64}):\/\/([^/?#\s]*)([^?#\s]*)(\?([^#\s]*))?(#([^\s]*))?/g;
173
+ }
174
+ });
175
+ var require_utils = __commonJS({
176
+ "../redact-pii/dist/utils.js"(exports) {
177
+ Object.defineProperty(exports, "__esModule", { value: true });
178
+ exports.snakeCase = exports.isSyncRedactor = exports.isSimpleRegexpCustomRedactorConfig = void 0;
179
+ function isSimpleRegexpCustomRedactorConfig(redactor2) {
180
+ return typeof redactor2.regexpPattern !== "undefined";
181
+ }
182
+ exports.isSimpleRegexpCustomRedactorConfig = isSimpleRegexpCustomRedactorConfig;
183
+ function isSyncRedactor(redactor2) {
184
+ return typeof redactor2.redact === "function";
185
+ }
186
+ exports.isSyncRedactor = isSyncRedactor;
187
+ function snakeCase(input = "") {
188
+ var _a;
189
+ 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 : [];
190
+ return words.map((word) => word.toLowerCase()).join("_");
191
+ }
192
+ exports.snakeCase = snakeCase;
193
+ }
194
+ });
195
+ var require_SimpleRegexpRedactor = __commonJS({
196
+ "../redact-pii/dist/built-ins/SimpleRegexpRedactor.js"(exports) {
197
+ Object.defineProperty(exports, "__esModule", { value: true });
198
+ exports.SimpleRegexpRedactor = void 0;
199
+ var utils_1 = require_utils();
200
+ var SimpleRegexpRedactor = class {
201
+ constructor({ replaceWith = (0, utils_1.snakeCase)().toUpperCase(), regexpPattern: regexpMatcher }) {
202
+ this.replaceWith = replaceWith;
203
+ this.regexpMatcher = regexpMatcher;
204
+ }
205
+ redact(textToRedact) {
206
+ return textToRedact.replace(this.regexpMatcher, this.replaceWith);
207
+ }
208
+ };
209
+ exports.SimpleRegexpRedactor = SimpleRegexpRedactor;
210
+ }
211
+ });
212
+ var require_composition = __commonJS({
213
+ "../redact-pii/dist/composition.js"(exports) {
214
+ Object.defineProperty(exports, "__esModule", { value: true });
215
+ exports.composeChildRedactors = void 0;
216
+ var NameRedactor_1 = require_NameRedactor();
217
+ var simpleRegexpBuiltIns = require_simple_regexp_patterns();
218
+ var SimpleRegexpRedactor_1 = require_SimpleRegexpRedactor();
219
+ var utils_1 = require_utils();
220
+ function normalizeCustomRedactorConfig(redactorConfig) {
221
+ return (0, utils_1.isSimpleRegexpCustomRedactorConfig)(redactorConfig) ? new SimpleRegexpRedactor_1.SimpleRegexpRedactor({
222
+ regexpPattern: redactorConfig.regexpPattern,
223
+ replaceWith: redactorConfig.replaceWith
224
+ }) : redactorConfig;
225
+ }
226
+ function composeChildRedactors(opts = {}) {
227
+ var _a, _b, _c, _d;
228
+ const childRedactors = [];
229
+ if (opts.customRedactors && opts.customRedactors.before) {
230
+ opts.customRedactors.before.map(normalizeCustomRedactorConfig).forEach((redactor2) => childRedactors.push(redactor2));
231
+ }
232
+ for (const regexpName of Object.keys(simpleRegexpBuiltIns)) {
233
+ if (!opts.builtInRedactors || !opts.builtInRedactors[regexpName] || opts.builtInRedactors[regexpName].enabled !== false) {
234
+ childRedactors.push(new SimpleRegexpRedactor_1.SimpleRegexpRedactor({
235
+ regexpPattern: simpleRegexpBuiltIns[regexpName],
236
+ 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()
237
+ }));
238
+ }
239
+ }
240
+ if (!opts.builtInRedactors || !opts.builtInRedactors.names || opts.builtInRedactors.names.enabled !== false) {
241
+ 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));
242
+ }
243
+ if (opts.customRedactors && opts.customRedactors.after) {
244
+ opts.customRedactors.after.map(normalizeCustomRedactorConfig).forEach((redactor2) => childRedactors.push(redactor2));
245
+ }
246
+ return childRedactors;
247
+ }
248
+ exports.composeChildRedactors = composeChildRedactors;
249
+ }
250
+ });
251
+ var require_AsyncCompositeRedactor = __commonJS({
252
+ "../redact-pii/dist/AsyncCompositeRedactor.js"(exports) {
253
+ var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
254
+ function adopt(value) {
255
+ return value instanceof P ? value : new P(function(resolve2) {
256
+ resolve2(value);
257
+ });
258
+ }
259
+ return new (P || (P = Promise))(function(resolve2, reject) {
260
+ function fulfilled(value) {
261
+ try {
262
+ step(generator.next(value));
263
+ } catch (e) {
264
+ reject(e);
265
+ }
266
+ }
267
+ function rejected(value) {
268
+ try {
269
+ step(generator["throw"](value));
270
+ } catch (e) {
271
+ reject(e);
272
+ }
273
+ }
274
+ function step(result) {
275
+ result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
276
+ }
277
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
278
+ });
279
+ };
280
+ Object.defineProperty(exports, "__esModule", { value: true });
281
+ exports.AsyncCompositeRedactor = void 0;
282
+ var composition_1 = require_composition();
283
+ var utils_1 = require_utils();
284
+ var AsyncCompositeRedactor = class {
285
+ constructor(opts) {
286
+ this.childRedactors = [];
287
+ this.redactAsync = (textToRedact) => __awaiter(this, void 0, void 0, function* () {
288
+ for (const redactor2 of this.childRedactors) {
289
+ if ((0, utils_1.isSyncRedactor)(redactor2)) {
290
+ textToRedact = redactor2.redact(textToRedact);
291
+ } else {
292
+ textToRedact = yield redactor2.redactAsync(textToRedact);
293
+ }
294
+ }
295
+ return textToRedact;
296
+ });
297
+ this.childRedactors = (0, composition_1.composeChildRedactors)(opts);
298
+ }
299
+ };
300
+ exports.AsyncCompositeRedactor = AsyncCompositeRedactor;
301
+ }
302
+ });
303
+ var require_SyncCompositeRedactor = __commonJS({
304
+ "../redact-pii/dist/SyncCompositeRedactor.js"(exports) {
305
+ Object.defineProperty(exports, "__esModule", { value: true });
306
+ exports.SyncCompositeRedactor = void 0;
307
+ var composition_1 = require_composition();
308
+ var SyncCompositeRedactor = class {
309
+ constructor(opts) {
310
+ this.childRedactors = [];
311
+ this.redact = (textToRedact) => {
312
+ for (const redactor2 of this.childRedactors) {
313
+ textToRedact = redactor2.redact(textToRedact);
314
+ }
315
+ return textToRedact;
316
+ };
317
+ this.childRedactors = (0, composition_1.composeChildRedactors)(opts);
318
+ }
319
+ };
320
+ exports.SyncCompositeRedactor = SyncCompositeRedactor;
321
+ }
322
+ });
323
+ var require_dist = __commonJS({
324
+ "../redact-pii/dist/index.js"(exports) {
325
+ Object.defineProperty(exports, "__esModule", { value: true });
326
+ exports.SyncRedactor = exports.AsyncRedactor = void 0;
327
+ var AsyncCompositeRedactor_1 = require_AsyncCompositeRedactor();
328
+ Object.defineProperty(exports, "AsyncRedactor", { enumerable: true, get: function() {
329
+ return AsyncCompositeRedactor_1.AsyncCompositeRedactor;
330
+ } });
331
+ var SyncCompositeRedactor_1 = require_SyncCompositeRedactor();
332
+ Object.defineProperty(exports, "SyncRedactor", { enumerable: true, get: function() {
333
+ return SyncCompositeRedactor_1.SyncCompositeRedactor;
334
+ } });
335
+ }
336
+ });
83
337
  var STATE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.replayTraceRoutingState");
84
338
  function state() {
85
339
  const holder = globalThis;
86
340
  let current = holder[STATE_KEY];
87
341
  if (!current) {
88
- let storage = null;
342
+ let storage2 = null;
89
343
  try {
90
344
  const Ctor = globalThis.RAINDROP_ASYNC_LOCAL_STORAGE;
91
- if (Ctor) storage = new Ctor();
345
+ if (Ctor) storage2 = new Ctor();
92
346
  } catch (e) {
93
- storage = null;
347
+ storage2 = null;
94
348
  }
95
349
  current = {
96
- storage,
350
+ storage: storage2,
97
351
  syncDestination: void 0,
98
352
  spanDestinations: /* @__PURE__ */ new WeakMap()
99
353
  };
@@ -257,12 +511,12 @@ var NO_AMBIENT_ATTRIBUTE_BIND_WARNING = "[raindrop] This runtime's AsyncLocalSto
257
511
  var ROUTING_STORAGE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.routingContextStorage");
258
512
  function routingStorage() {
259
513
  const holder = globalThis;
260
- let storage = holder[ROUTING_STORAGE_KEY];
261
- if (!storage) {
262
- storage = new ContextStackStorage(NO_AMBIENT_ROUTING_BIND_WARNING);
263
- holder[ROUTING_STORAGE_KEY] = storage;
514
+ let storage2 = holder[ROUTING_STORAGE_KEY];
515
+ if (!storage2) {
516
+ storage2 = new ContextStackStorage(NO_AMBIENT_ROUTING_BIND_WARNING);
517
+ holder[ROUTING_STORAGE_KEY] = storage2;
264
518
  }
265
- return storage;
519
+ return storage2;
266
520
  }
267
521
  function makeBoundContext(binding, owner) {
268
522
  const WeakRefCtor = owner !== void 0 ? getWeakRefCtor() : void 0;
@@ -317,12 +571,12 @@ function isBoundContext(value) {
317
571
  var ATTRIBUTE_STORAGE_KEY = /* @__PURE__ */ Symbol.for("raindrop.tracing.spanAttributeStorage");
318
572
  function attributeStorage() {
319
573
  const holder = globalThis;
320
- let storage = holder[ATTRIBUTE_STORAGE_KEY];
321
- if (!storage) {
322
- storage = new ContextStackStorage(NO_AMBIENT_ATTRIBUTE_BIND_WARNING);
323
- holder[ATTRIBUTE_STORAGE_KEY] = storage;
574
+ let storage2 = holder[ATTRIBUTE_STORAGE_KEY];
575
+ if (!storage2) {
576
+ storage2 = new ContextStackStorage(NO_AMBIENT_ATTRIBUTE_BIND_WARNING);
577
+ holder[ATTRIBUTE_STORAGE_KEY] = storage2;
324
578
  }
325
- return storage;
579
+ return storage2;
326
580
  }
327
581
  function makeAttributeFrame(attributes, owner) {
328
582
  const snapshot = { ...attributes };
@@ -641,6 +895,9 @@ var AppGitContextImpl = class {
641
895
  }
642
896
  };
643
897
  var AppGitContext = AppGitContextImpl;
898
+ function createAppGitContext(options, runtime = {}) {
899
+ return new AppGitContext(options, runtime);
900
+ }
644
901
  function withAppGitProperties(properties, snapshot) {
645
902
  try {
646
903
  const merged = { ...properties };
@@ -976,11 +1233,91 @@ function runWithTracingSuppressed(fn) {
976
1233
  return fn();
977
1234
  }
978
1235
  }
1236
+ var MAX_QUOTED_ITEMS = 3;
1237
+ function isRecord(value) {
1238
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1239
+ }
1240
+ function itemLabel(item) {
1241
+ if (typeof item.event_id === "string" && item.event_id) return `event ${item.event_id}`;
1242
+ if (typeof item.index === "number") return `item ${item.index}`;
1243
+ return "item";
1244
+ }
1245
+ function describeRejected(item) {
1246
+ const issues = Array.isArray(item.issues) ? item.issues : [];
1247
+ const text = issues.filter(isRecord).map((issue) => {
1248
+ const path = typeof issue.path === "string" && issue.path ? `${issue.path}: ` : "";
1249
+ return `${path}${typeof issue.message === "string" ? issue.message : "invalid"}`;
1250
+ }).join("; ");
1251
+ return `${itemLabel(item)} (${text || "invalid"})`;
1252
+ }
1253
+ function describeWarning(item) {
1254
+ if (typeof item.message === "string" && item.message) return `${itemLabel(item)}: ${item.message}`;
1255
+ const fields = Array.isArray(item.fields) ? item.fields.filter((f) => typeof f === "string") : [];
1256
+ return `${itemLabel(item)}: ignored ${fields.join(", ") || "input"}`;
1257
+ }
1258
+ function summarize(items, describe) {
1259
+ const quoted = items.slice(0, MAX_QUOTED_ITEMS).map(describe).join(" | ");
1260
+ const more = items.length > MAX_QUOTED_ITEMS ? ` (+${items.length - MAX_QUOTED_ITEMS} more)` : "";
1261
+ return `${quoted}${more}`;
1262
+ }
1263
+ function reportIngestResponse(bodyText, prefix, opName) {
1264
+ if (!bodyText) return;
1265
+ let body;
1266
+ try {
1267
+ body = JSON.parse(bodyText);
1268
+ } catch (e) {
1269
+ return;
1270
+ }
1271
+ if (!isRecord(body)) return;
1272
+ const rejected = Array.isArray(body.rejected) ? body.rejected.filter(isRecord) : [];
1273
+ if (rejected.length > 0) {
1274
+ rateLimitedLog(
1275
+ `${prefix}.ingest_rejected`,
1276
+ () => console.warn(
1277
+ `${prefix} ${opName}: ingest rejected ${rejected.length} item(s), which were not stored: ${summarize(rejected, describeRejected)}`
1278
+ )
1279
+ );
1280
+ }
1281
+ const warnings = Array.isArray(body.warnings) ? body.warnings.filter(isRecord) : [];
1282
+ if (warnings.length > 0) {
1283
+ rateLimitedLog(
1284
+ `${prefix}.ingest_warnings`,
1285
+ () => console.warn(
1286
+ `${prefix} ${opName}: ingest accepted ${warnings.length} item(s) with changes: ${summarize(warnings, describeWarning)}`
1287
+ )
1288
+ );
1289
+ }
1290
+ }
1291
+ var DEFAULT_FLUSH_TIMEOUT_MS = 1e4;
979
1292
  var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
980
1293
  var MAX_RETRY_DELAY_MS = 3e4;
981
1294
  function wait(ms) {
982
1295
  return new Promise((resolve2) => setTimeout(resolve2, ms));
983
1296
  }
1297
+ function waitUnlessAborted(ms, signal) {
1298
+ if (!signal) return wait(ms);
1299
+ if (signal.aborted) return Promise.resolve();
1300
+ return new Promise((resolve2) => {
1301
+ const done = () => {
1302
+ clearTimeout(timer);
1303
+ signal.removeEventListener("abort", done);
1304
+ resolve2();
1305
+ };
1306
+ const timer = setTimeout(done, ms);
1307
+ signal.addEventListener("abort", done, { once: true });
1308
+ });
1309
+ }
1310
+ function eitherSignal(a, b) {
1311
+ if (!b) return a;
1312
+ const any = AbortSignal.any;
1313
+ if (typeof any === "function") return any([a, b]);
1314
+ const controller = new AbortController();
1315
+ const abort = () => controller.abort();
1316
+ if (a.aborted || b.aborted) abort();
1317
+ a.addEventListener("abort", abort, { once: true });
1318
+ b.addEventListener("abort", abort, { once: true });
1319
+ return controller.signal;
1320
+ }
984
1321
  function formatEndpoint(endpoint) {
985
1322
  if (!endpoint) return void 0;
986
1323
  return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
@@ -1025,6 +1362,26 @@ async function raceWithTimeout(promise, timeoutMs) {
1025
1362
  if (timer) clearTimeout(timer);
1026
1363
  return settledInTime;
1027
1364
  }
1365
+ var InFlightCutOff = class {
1366
+ constructor() {
1367
+ this.controller = new AbortController();
1368
+ }
1369
+ get signal() {
1370
+ return this.controller.signal;
1371
+ }
1372
+ cut() {
1373
+ this.controller.abort();
1374
+ this.controller = new AbortController();
1375
+ }
1376
+ };
1377
+ async function awaitEarlierSends(earlier, deadlineAt, cutOff, isRunning) {
1378
+ if (earlier.length === 0) return { settled: true, stillRunning: 0 };
1379
+ const settled = await raceWithTimeout(Promise.allSettled(earlier), deadlineAt - Date.now());
1380
+ if (settled) return { settled, stillRunning: 0 };
1381
+ const stillRunning = earlier.filter(isRunning).length;
1382
+ if (stillRunning > 0) cutOff.cut();
1383
+ return { settled: stillRunning === 0, stillRunning };
1384
+ }
1028
1385
  function parseRetryAfter(headers) {
1029
1386
  var _a;
1030
1387
  const value = (_a = headers.get("Retry-After")) != null ? _a : headers.get("retry-after");
@@ -1048,45 +1405,80 @@ function getRetryDelayMs(attemptNumber, previousError) {
1048
1405
  const factor = Math.pow(2, attemptNumber - 2);
1049
1406
  return Math.min(base * factor, MAX_RETRY_DELAY_MS);
1050
1407
  }
1051
- async function withRetry(operation, opName, opts) {
1052
- const prefix = opts.sdkName ? `[raindrop-ai/${opts.sdkName}]` : "[raindrop-ai/core]";
1053
- let lastError = void 0;
1054
- for (let attemptNumber = 1; attemptNumber <= opts.maxAttempts; attemptNumber++) {
1055
- if (attemptNumber > 1) {
1056
- const delay = getRetryDelayMs(attemptNumber, lastError);
1057
- if (opts.debug) {
1058
- console.warn(
1059
- `${prefix} ${opName} retry ${attemptNumber}/${opts.maxAttempts} in ${delay}ms`
1060
- );
1061
- }
1062
- if (delay > 0) await wait(delay);
1063
- } else if (opts.debug) {
1064
- console.log(`${prefix} ${opName} attempt ${attemptNumber}/${opts.maxAttempts}`);
1065
- }
1066
- try {
1067
- return await operation();
1068
- } catch (err) {
1069
- lastError = err;
1070
- if (opts.debug) {
1071
- const msg = err instanceof Error ? err.message : String(err);
1072
- console.warn(
1073
- `${prefix} ${opName} attempt ${attemptNumber} failed: ${msg}${attemptNumber === opts.maxAttempts ? " (no more retries)" : ""}`
1074
- );
1075
- }
1076
- if (lastError && typeof lastError === "object" && "retryable" in lastError && !lastError.retryable)
1077
- break;
1078
- if (attemptNumber === opts.maxAttempts) break;
1079
- }
1408
+ var sendPausedUntil = /* @__PURE__ */ new Map();
1409
+ function originOf(url) {
1410
+ try {
1411
+ return new URL(url).origin;
1412
+ } catch (e) {
1413
+ return url;
1080
1414
  }
1081
- throw lastError instanceof Error ? lastError : new Error(String(lastError));
1415
+ }
1416
+ function noteSendPause(url, status, retryAfterMs) {
1417
+ var _a;
1418
+ if (status !== 429 && status !== 503 || typeof retryAfterMs !== "number") return;
1419
+ const until = Date.now() + Math.min(Math.max(0, retryAfterMs), MAX_RETRY_DELAY_MS);
1420
+ const origin = originOf(url);
1421
+ sendPausedUntil.set(origin, Math.max((_a = sendPausedUntil.get(origin)) != null ? _a : 0, until));
1422
+ }
1423
+ function pausedUntil(url) {
1424
+ const until = sendPausedUntil.get(originOf(url));
1425
+ if (until === void 0) return void 0;
1426
+ if (until <= Date.now()) {
1427
+ sendPausedUntil.delete(originOf(url));
1428
+ return void 0;
1429
+ }
1430
+ return Math.min(until, Date.now() + MAX_RETRY_DELAY_MS);
1431
+ }
1432
+ function prefixFor(opts) {
1433
+ return opts.sdkName ? `[raindrop-ai/${opts.sdkName}]` : "[raindrop-ai/core]";
1082
1434
  }
1083
1435
  async function postJson(url, body, headers, opts) {
1436
+ var _a;
1437
+ const outcome = await sendJson(url, body, headers, { ...opts, deadlineAt: void 0 });
1438
+ if (outcome.status === "delivered") return;
1439
+ throw (_a = outcome.error) != null ? _a : new Error(`${redactUrlForLog(url)}: not sent (${outcome.status})`);
1440
+ }
1441
+ async function sendJson(url, body, headers, opts) {
1084
1442
  var _a;
1085
1443
  const opName = `POST ${redactUrlForLog(url)}`;
1444
+ const prefix = prefixFor(opts);
1086
1445
  const timeoutMs = (_a = opts.timeoutMs) != null ? _a : DEFAULT_REQUEST_TIMEOUT_MS;
1087
- await withRetry(
1088
- async () => {
1089
- const resp = await runWithTracingSuppressed(
1446
+ const deadlineAt = opts.deadlineAt;
1447
+ const remaining = () => deadlineAt === void 0 ? Infinity : deadlineAt - Date.now();
1448
+ let lastError;
1449
+ const cutOff = opts.cutOff;
1450
+ for (let attempt = 1; attempt <= opts.maxAttempts; attempt++) {
1451
+ if (cutOff == null ? void 0 : cutOff.aborted) return { status: "deferred", error: lastError };
1452
+ if (attempt > 1) {
1453
+ const delay = getRetryDelayMs(attempt, lastError);
1454
+ if (delay >= remaining()) {
1455
+ return { status: "deferred", retryAtMs: Date.now() + delay, error: lastError };
1456
+ }
1457
+ if (opts.debug) {
1458
+ console.warn(`${prefix} ${opName} retry ${attempt}/${opts.maxAttempts} in ${delay}ms`);
1459
+ }
1460
+ if (delay > 0) await waitUnlessAborted(delay, cutOff);
1461
+ if (cutOff == null ? void 0 : cutOff.aborted) return { status: "deferred", error: lastError };
1462
+ } else if (opts.debug) {
1463
+ console.log(`${prefix} ${opName} attempt ${attempt}/${opts.maxAttempts}`);
1464
+ }
1465
+ const pauseEnd = pausedUntil(url);
1466
+ if (pauseEnd !== void 0) {
1467
+ if (deadlineAt !== void 0 && pauseEnd >= deadlineAt) {
1468
+ return { status: "deferred", retryAtMs: pauseEnd, error: lastError };
1469
+ }
1470
+ await waitUnlessAborted(Math.max(0, pauseEnd - Date.now()), cutOff);
1471
+ if (cutOff == null ? void 0 : cutOff.aborted) return { status: "deferred", retryAtMs: pauseEnd, error: lastError };
1472
+ }
1473
+ const left = remaining();
1474
+ if (left <= 0) return { status: "deferred", error: lastError };
1475
+ const attemptTimeoutMs = Math.min(timeoutMs, left);
1476
+ const clampedByDeadline = attemptTimeoutMs < timeoutMs;
1477
+ const timeoutSignal = AbortSignal.timeout(attemptTimeoutMs);
1478
+ const signal = eitherSignal(timeoutSignal, cutOff);
1479
+ let resp;
1480
+ try {
1481
+ resp = await runWithTracingSuppressed(
1090
1482
  () => fetch(url, {
1091
1483
  method: "POST",
1092
1484
  redirect: headers["X-Raindrop-Replay-Id"] !== void 0 ? "error" : "follow",
@@ -1095,24 +1487,98 @@ async function postJson(url, body, headers, opts) {
1095
1487
  ...headers
1096
1488
  },
1097
1489
  body: JSON.stringify(body),
1098
- signal: AbortSignal.timeout(timeoutMs)
1490
+ signal
1099
1491
  })
1100
1492
  );
1101
- if (!resp.ok) {
1102
- const text = await resp.text().catch(() => "");
1103
- const err = new Error(
1104
- `HTTP ${resp.status} ${resp.statusText}${text ? `: ${text}` : ""}`
1105
- );
1106
- const retryAfterMs = parseRetryAfter(resp.headers);
1107
- if (typeof retryAfterMs === "number") err.retryAfterMs = retryAfterMs;
1108
- err.retryable = resp.status === 429 || resp.status >= 500;
1109
- throw err;
1493
+ } catch (err) {
1494
+ const error = err instanceof Error ? err : new Error(String(err));
1495
+ if ((cutOff == null ? void 0 : cutOff.aborted) || timeoutSignal.aborted && clampedByDeadline) {
1496
+ return { status: "cut_off", error };
1110
1497
  }
1111
- },
1112
- opName,
1113
- opts
1498
+ lastError = error;
1499
+ logAttemptFailure(opts, prefix, opName, attempt, error);
1500
+ continue;
1501
+ }
1502
+ if (!resp.ok) {
1503
+ const text = await resp.text().catch(() => "");
1504
+ const error = new Error(
1505
+ `HTTP ${resp.status} ${resp.statusText}${text ? `: ${text}` : ""}`
1506
+ );
1507
+ const retryAfterMs = parseRetryAfter(resp.headers);
1508
+ if (typeof retryAfterMs === "number") error.retryAfterMs = retryAfterMs;
1509
+ noteSendPause(url, resp.status, retryAfterMs);
1510
+ error.retryable = resp.status === 408 || resp.status === 429 || resp.status >= 500;
1511
+ if (!error.retryable) return { status: "rejected", error };
1512
+ lastError = error;
1513
+ logAttemptFailure(opts, prefix, opName, attempt, error);
1514
+ continue;
1515
+ }
1516
+ try {
1517
+ reportIngestResponse(await resp.text(), prefix, opName);
1518
+ } catch (e) {
1519
+ }
1520
+ return { status: "delivered" };
1521
+ }
1522
+ return { status: "failed", error: lastError != null ? lastError : new Error(`${opName}: no attempts`) };
1523
+ }
1524
+ function logAttemptFailure(opts, prefix, opName, attempt, error) {
1525
+ if (!opts.debug) return;
1526
+ console.warn(
1527
+ `${prefix} ${opName} attempt ${attempt} failed: ${error.message}${attempt === opts.maxAttempts ? " (no more retries)" : ""}`
1114
1528
  );
1115
1529
  }
1530
+ function asCompat(result) {
1531
+ return result;
1532
+ }
1533
+ var DELIVERED = Object.freeze({
1534
+ delivered: true,
1535
+ timedOut: false,
1536
+ dropped: 0,
1537
+ queued: 0,
1538
+ inFlight: 0
1539
+ });
1540
+ function fateOf(outcome, shuttingDown) {
1541
+ switch (outcome.status) {
1542
+ case "delivered":
1543
+ case "rejected":
1544
+ return "delivered";
1545
+ case "deferred":
1546
+ return shuttingDown ? "dropped" : "queued";
1547
+ default:
1548
+ return "dropped";
1549
+ }
1550
+ }
1551
+ function summarize2(fates, inFlight, timedOut) {
1552
+ const dropped = fates.filter((fate) => fate === "dropped").length;
1553
+ const queued = fates.filter((fate) => fate === "queued").length;
1554
+ return {
1555
+ delivered: dropped === 0 && queued === 0 && inFlight === 0,
1556
+ timedOut: timedOut || queued > 0 || inFlight > 0,
1557
+ dropped,
1558
+ queued,
1559
+ inFlight
1560
+ };
1561
+ }
1562
+ function combineResults(...results) {
1563
+ return results.reduce(
1564
+ (acc, r) => ({
1565
+ delivered: acc.delivered && r.delivered,
1566
+ timedOut: acc.timedOut || r.timedOut,
1567
+ dropped: acc.dropped + r.dropped,
1568
+ queued: acc.queued + r.queued,
1569
+ inFlight: acc.inFlight + r.inFlight
1570
+ }),
1571
+ { ...DELIVERED }
1572
+ );
1573
+ }
1574
+ function describeUndelivered(what, result) {
1575
+ const parts = [
1576
+ result.dropped > 0 ? `${result.dropped} dropped` : "",
1577
+ result.queued > 0 ? `${result.queued} still queued` : "",
1578
+ result.inFlight > 0 ? `${result.inFlight} still sending` : ""
1579
+ ].filter(Boolean);
1580
+ return `${what} returned before everything was delivered: ${parts.join(", ")}`;
1581
+ }
1116
1582
  var DEFAULT_MAX_TEXT_FIELD_CHARS = 1e6;
1117
1583
  var TRUNCATION_MARKER = "...[truncated by raindrop]";
1118
1584
  var BOUNDED_CLONE_MAX_DEPTH = 12;
@@ -1239,130 +1705,1167 @@ function readEnvVar(name) {
1239
1705
  if (env && typeof env[name] === "string" && env[name].length > 0) {
1240
1706
  return env[name];
1241
1707
  }
1242
- } catch (e) {
1243
- }
1244
- return void 0;
1245
- }
1246
- function readWorkshopEnv() {
1247
- const raw = readEnvVar(WORKSHOP_ENV_VAR);
1248
- if (raw === void 0) return void 0;
1249
- const trimmed = raw.trim();
1250
- if (trimmed.length === 0) return void 0;
1251
- if (/^https?:\/\//i.test(trimmed)) return { url: trimmed };
1252
- if (/^(1|true|yes|on)$/i.test(trimmed)) return "enable";
1253
- if (/^(0|false|no|off)$/i.test(trimmed)) return "disable";
1254
- return void 0;
1255
- }
1256
- function isLocalDevHost(hostname) {
1257
- if (!hostname) return false;
1258
- if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "0.0.0.0" || hostname === "::1") {
1259
- return true;
1260
- }
1261
- if (hostname.endsWith(".localhost")) return true;
1262
- return false;
1263
- }
1264
- function readRuntimeHostname() {
1265
- try {
1266
- const loc = globalThis == null ? void 0 : globalThis.location;
1267
- if (loc && typeof loc.hostname === "string" && loc.hostname.length > 0) {
1268
- return loc.hostname;
1708
+ } catch (e) {
1709
+ }
1710
+ return void 0;
1711
+ }
1712
+ function readWorkshopEnv() {
1713
+ const raw = readEnvVar(WORKSHOP_ENV_VAR);
1714
+ if (raw === void 0) return void 0;
1715
+ const trimmed = raw.trim();
1716
+ if (trimmed.length === 0) return void 0;
1717
+ if (/^https?:\/\//i.test(trimmed)) return { url: trimmed };
1718
+ if (/^(1|true|yes|on)$/i.test(trimmed)) return "enable";
1719
+ if (/^(0|false|no|off)$/i.test(trimmed)) return "disable";
1720
+ return void 0;
1721
+ }
1722
+ function isLocalDevHost(hostname) {
1723
+ if (!hostname) return false;
1724
+ if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "0.0.0.0" || hostname === "::1") {
1725
+ return true;
1726
+ }
1727
+ if (hostname.endsWith(".localhost")) return true;
1728
+ return false;
1729
+ }
1730
+ function readRuntimeHostname() {
1731
+ try {
1732
+ const loc = globalThis == null ? void 0 : globalThis.location;
1733
+ if (loc && typeof loc.hostname === "string" && loc.hostname.length > 0) {
1734
+ return loc.hostname;
1735
+ }
1736
+ } catch (e) {
1737
+ }
1738
+ return void 0;
1739
+ }
1740
+ function shouldAutoEnableLocalWorkshop() {
1741
+ if (isLocalDevHost(readRuntimeHostname())) return true;
1742
+ if (readEnvVar("NODE_ENV") === "development") return true;
1743
+ return false;
1744
+ }
1745
+ function resolveLocalDebuggerBaseUrl(baseUrl) {
1746
+ var _a, _b, _c;
1747
+ if (baseUrl === null) return null;
1748
+ if (typeof baseUrl === "string" && baseUrl.length > 0) {
1749
+ return (_a = formatEndpoint(baseUrl)) != null ? _a : null;
1750
+ }
1751
+ const explicitUrlEnv = readEnvVar(LOCAL_DEBUGGER_ENV_VAR);
1752
+ if (explicitUrlEnv) return (_b = formatEndpoint(explicitUrlEnv)) != null ? _b : null;
1753
+ const workshopEnv = readWorkshopEnv();
1754
+ if (workshopEnv === "disable") return null;
1755
+ if (workshopEnv === "enable") return DEFAULT_LOCAL_WORKSHOP_URL;
1756
+ if (workshopEnv && "url" in workshopEnv) return (_c = formatEndpoint(workshopEnv.url)) != null ? _c : null;
1757
+ if (shouldAutoEnableLocalWorkshop()) return DEFAULT_LOCAL_WORKSHOP_URL;
1758
+ return null;
1759
+ }
1760
+ function localDebuggerEnabled(baseUrl) {
1761
+ return resolveLocalDebuggerBaseUrl(baseUrl) !== null;
1762
+ }
1763
+ var LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS = 2e3;
1764
+ function mirrorTraceExportToLocalDebugger(body, options = {}) {
1765
+ var _a;
1766
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
1767
+ if (!baseUrl) return Promise.resolve();
1768
+ return postJson(`${baseUrl}traces`, body, {}, {
1769
+ maxAttempts: 1,
1770
+ debug: (_a = options.debug) != null ? _a : false,
1771
+ sdkName: options.sdkName,
1772
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
1773
+ }).catch(() => {
1774
+ });
1775
+ }
1776
+ function mirrorPartialEventToLocalDebugger(event, options = {}) {
1777
+ var _a;
1778
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
1779
+ if (!baseUrl) return Promise.resolve();
1780
+ const headers = options.writeKey ? { Authorization: `Bearer ${options.writeKey}` } : {};
1781
+ return postJson(`${baseUrl}events/track_partial`, event, headers, {
1782
+ maxAttempts: 1,
1783
+ debug: (_a = options.debug) != null ? _a : false,
1784
+ sdkName: options.sdkName,
1785
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
1786
+ }).catch(() => {
1787
+ });
1788
+ }
1789
+ function sendLocalDebuggerLiveEvent(event, options = {}) {
1790
+ var _a, _b;
1791
+ const destination = currentReplayTraceDestination();
1792
+ if (destination && destination.kind !== "workshop") return;
1793
+ const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
1794
+ if (!baseUrl) return;
1795
+ void postJson(
1796
+ `${baseUrl}live`,
1797
+ {
1798
+ ...event,
1799
+ type: event.type,
1800
+ timestamp: (_a = event.timestamp) != null ? _a : Date.now()
1801
+ },
1802
+ {},
1803
+ {
1804
+ maxAttempts: 1,
1805
+ debug: (_b = options.debug) != null ? _b : false,
1806
+ sdkName: options.sdkName
1807
+ }
1808
+ ).catch(() => {
1809
+ });
1810
+ }
1811
+ var PROJECT_ID_HEADER = "X-Raindrop-Project-Id";
1812
+ var PROJECT_ID_SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
1813
+ function isValidProjectIdSlug(value) {
1814
+ return PROJECT_ID_SLUG_PATTERN.test(value);
1815
+ }
1816
+ function normalizeProjectId(raw, opts) {
1817
+ if (typeof raw !== "string") return void 0;
1818
+ const trimmed = raw.trim();
1819
+ if (!trimmed) return void 0;
1820
+ if (!isValidProjectIdSlug(trimmed) && opts.debug) {
1821
+ console.warn(
1822
+ `${opts.prefix} projectId "${trimmed}" does not match slug ${PROJECT_ID_SLUG_PATTERN.source}; sending anyway \u2014 backend may reject with HTTP 400`
1823
+ );
1824
+ }
1825
+ return trimmed;
1826
+ }
1827
+ function projectIdHeaders(projectId) {
1828
+ return projectId ? { [PROJECT_ID_HEADER]: projectId } : {};
1829
+ }
1830
+ var import_redact_pii = __toESM(require_dist(), 1);
1831
+ var DEFAULT_PII_REDACTION_OPTIONS = {
1832
+ builtInRedactors: {
1833
+ credentials: { replaceWith: "<REDACTED CREDENTIALS>" },
1834
+ creditCardNumber: { replaceWith: "<REDACTED CREDIT CARD NUMBER>" },
1835
+ // Any run of 4+ digits: too broad.
1836
+ digits: { enabled: false },
1837
+ emailAddress: { replaceWith: "<REDACTED EMAIL>" },
1838
+ ipAddress: { enabled: false },
1839
+ names: { enabled: false },
1840
+ // Matches (pass(word|phrase)|secret): \S+
1841
+ password: { replaceWith: "<REDACTED SECRET>" },
1842
+ phoneNumber: { replaceWith: "<REDACTED PHONE NUMBER>" },
1843
+ streetAddress: { replaceWith: "<REDACTED ADDRESS>" },
1844
+ url: { enabled: false },
1845
+ username: { enabled: false },
1846
+ usSocialSecurityNumber: { replaceWith: "<REDACTED SOCIAL SECURITY NUMBER>" },
1847
+ zipcode: { enabled: false }
1848
+ }
1849
+ };
1850
+ var redactor;
1851
+ function redactPiiText(text) {
1852
+ redactor != null ? redactor : redactor = new import_redact_pii.SyncRedactor(DEFAULT_PII_REDACTION_OPTIONS);
1853
+ return redactor.redact(text);
1854
+ }
1855
+ var KINDS = ["event", "signal", "identify"];
1856
+ var DEFAULT_PII_FIELDS = {
1857
+ event: ["ai_data.input", "ai_data.output"],
1858
+ signal: [],
1859
+ identify: []
1860
+ };
1861
+ var PROTECTED_LOCATIONS = new Set(
1862
+ [
1863
+ ["event_id"],
1864
+ ["user_id"],
1865
+ ["ai_data", "convo_id"],
1866
+ ["event"],
1867
+ ["timestamp"],
1868
+ ["is_pending"],
1869
+ ["signal_name"],
1870
+ ["signal_type"]
1871
+ ].map((keys) => JSON.stringify(keys))
1872
+ );
1873
+ var SIGNAL_PATH_ALIASES = {
1874
+ comment: "properties.comment",
1875
+ after: "properties.after"
1876
+ };
1877
+ function parsePiiFieldPath(path) {
1878
+ if (typeof path !== "string") return null;
1879
+ const segments = [];
1880
+ let i = 0;
1881
+ const n = path.length;
1882
+ let expectSeparator = false;
1883
+ while (i < n) {
1884
+ const ch = path[i];
1885
+ if (ch === "[") {
1886
+ const close = path.indexOf("]", i);
1887
+ if (path[i + 1] === '"') {
1888
+ let j2 = i + 2;
1889
+ let key = "";
1890
+ while (j2 < n && path[j2] !== '"') {
1891
+ if (path[j2] === "\\" && j2 + 1 < n) {
1892
+ key += path[j2 + 1];
1893
+ j2 += 2;
1894
+ } else {
1895
+ key += path[j2];
1896
+ j2 += 1;
1897
+ }
1898
+ }
1899
+ if (j2 >= n || path[j2 + 1] !== "]" || key === "") return null;
1900
+ segments.push({ kind: "key", key });
1901
+ i = j2 + 2;
1902
+ } else {
1903
+ if (close === -1) return null;
1904
+ const inner = path.slice(i + 1, close);
1905
+ if (inner === "") segments.push({ kind: "every" });
1906
+ else if (/^(0|[1-9]\d*)$/.test(inner))
1907
+ segments.push({ kind: "index", index: Number(inner) });
1908
+ else return null;
1909
+ i = close + 1;
1910
+ }
1911
+ expectSeparator = true;
1912
+ continue;
1913
+ }
1914
+ if (ch === ".") {
1915
+ if (!expectSeparator) return null;
1916
+ i += 1;
1917
+ expectSeparator = false;
1918
+ if (i >= n || path[i] === ".") return null;
1919
+ continue;
1920
+ }
1921
+ if (expectSeparator) return null;
1922
+ let j = i;
1923
+ while (j < n && path[j] !== "." && path[j] !== "[") j += 1;
1924
+ const token = path.slice(i, j);
1925
+ if (token === "*") segments.push({ kind: "any_key" });
1926
+ else if (token === "" || /[\]*"\s]/.test(token)) return null;
1927
+ else segments.push({ kind: "key", key: token });
1928
+ i = j;
1929
+ expectSeparator = true;
1930
+ }
1931
+ return segments.length > 0 && expectSeparator ? segments : null;
1932
+ }
1933
+ function mergePiiFieldMaps(...maps) {
1934
+ const out = { event: [], signal: [], identify: [] };
1935
+ for (const kind of KINDS) {
1936
+ const seen = /* @__PURE__ */ new Set();
1937
+ for (const map of maps) {
1938
+ const paths = map == null ? void 0 : map[kind];
1939
+ if (!Array.isArray(paths)) continue;
1940
+ for (const path of paths) {
1941
+ if (typeof path !== "string" || seen.has(path)) continue;
1942
+ seen.add(path);
1943
+ out[kind].push(path);
1944
+ }
1945
+ }
1946
+ }
1947
+ return out;
1948
+ }
1949
+ function isPlainObject(value) {
1950
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1951
+ const proto = Object.getPrototypeOf(value);
1952
+ return proto === Object.prototype || proto === null;
1953
+ }
1954
+ function isProtected(location) {
1955
+ return PROTECTED_LOCATIONS.has(JSON.stringify(location));
1956
+ }
1957
+ function redactAll(value, location) {
1958
+ if (location !== null && isProtected(location)) return value;
1959
+ if (typeof value === "string") return redactPiiText(value);
1960
+ if (Array.isArray(value)) return value.map((item) => redactAll(item, null));
1961
+ if (isPlainObject(value)) {
1962
+ const out = {};
1963
+ for (const [key, child] of Object.entries(value)) {
1964
+ out[key] = redactAll(child, location === null ? null : [...location, key]);
1965
+ }
1966
+ return out;
1967
+ }
1968
+ return value;
1969
+ }
1970
+ function applyPath(value, segments, location) {
1971
+ if (segments.length === 0) return redactAll(value, location);
1972
+ const [head, ...rest] = segments;
1973
+ if (head.kind === "key" || head.kind === "any_key") {
1974
+ if (!isPlainObject(value)) return value;
1975
+ const keys = head.kind === "key" ? [head.key] : Object.keys(value);
1976
+ let out2;
1977
+ for (const key of keys) {
1978
+ if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
1979
+ const child = value[key];
1980
+ const next = applyPath(child, rest, location === null ? null : [...location, key]);
1981
+ if (next !== child) {
1982
+ out2 != null ? out2 : out2 = { ...value };
1983
+ out2[key] = next;
1984
+ }
1985
+ }
1986
+ return out2 != null ? out2 : value;
1987
+ }
1988
+ if (!Array.isArray(value)) return value;
1989
+ const indices = head.kind === "index" ? head.index < value.length ? [head.index] : [] : value.keys();
1990
+ let out;
1991
+ for (const index of indices) {
1992
+ const child = value[index];
1993
+ const next = applyPath(child, rest, null);
1994
+ if (next !== child) {
1995
+ out != null ? out : out = [...value];
1996
+ out[index] = next;
1997
+ }
1998
+ }
1999
+ return out != null ? out : value;
2000
+ }
2001
+ var PiiFieldRedactor = class {
2002
+ constructor(options = {}) {
2003
+ var _a;
2004
+ this.startupMap = options.startupFieldMap;
2005
+ this.prefix = (_a = options.logPrefix) != null ? _a : "[raindrop-ai/core]";
2006
+ }
2007
+ /** Replace the server-provided layer (CONTRACT 11.2). Additive: it can only add fields. */
2008
+ setServerFieldMap(map) {
2009
+ this.serverMap = map;
2010
+ this.compiled = void 0;
2011
+ }
2012
+ /** The paths in effect for a kind, defaults first. */
2013
+ effectivePaths(kind) {
2014
+ return mergePiiFieldMaps(DEFAULT_PII_FIELDS, this.startupMap, this.serverMap)[kind];
2015
+ }
2016
+ compile() {
2017
+ if (this.compiled) return this.compiled;
2018
+ const out = { event: [], signal: [], identify: [] };
2019
+ for (const kind of KINDS) {
2020
+ for (const path of this.effectivePaths(kind)) {
2021
+ const variants = [path];
2022
+ if (kind === "signal" && SIGNAL_PATH_ALIASES[path])
2023
+ variants.push(SIGNAL_PATH_ALIASES[path]);
2024
+ for (const variant of variants) {
2025
+ const segments = parsePiiFieldPath(variant);
2026
+ if (segments) {
2027
+ out[kind].push(segments);
2028
+ } else {
2029
+ rateLimitedLog(
2030
+ `${this.prefix}.pii_field_path_invalid`,
2031
+ () => console.warn(
2032
+ `${this.prefix} redactPiiFields: ignoring invalid ${kind} path ${JSON.stringify(variant)}`
2033
+ )
2034
+ );
2035
+ }
2036
+ }
2037
+ }
2038
+ }
2039
+ this.compiled = out;
2040
+ return out;
2041
+ }
2042
+ /** The payload with every selected field redacted (a copy where changed). */
2043
+ redact(kind, payload) {
2044
+ let out = payload;
2045
+ for (const segments of this.compile()[kind]) out = applyPath(out, segments, []);
2046
+ return out;
2047
+ }
2048
+ };
2049
+ function detectRuntime() {
2050
+ if (typeof process === "object" && process && typeof process.env === "object" && process.env && typeof process.version === "string") {
2051
+ return "node";
2052
+ }
2053
+ if (typeof window === "object") return "browser";
2054
+ if (typeof WebSocketPair !== "undefined") return "cloudflare-worker";
2055
+ if (typeof EdgeRuntime === "string") return "vercel-edge";
2056
+ if (typeof WorkerGlobalScope !== "undefined" && typeof importScripts === "function") {
2057
+ return "web-worker";
2058
+ }
2059
+ return "unknown";
2060
+ }
2061
+ var PLACEHOLDER_USER_IDS = /* @__PURE__ */ new Set(["null", "undefined"]);
2062
+ function isMissingUserId(value) {
2063
+ if (value === void 0 || value === null) return true;
2064
+ if (typeof value !== "string") return false;
2065
+ const trimmed = value.trim();
2066
+ return trimmed === "" || PLACEHOLDER_USER_IDS.has(trimmed);
2067
+ }
2068
+ var MAX_DEFERRED_SENDS = 1e3;
2069
+ var POST_SHUTDOWN_TIMEOUT_MS = 5e3;
2070
+ function appGitOwnerId(prefix) {
2071
+ try {
2072
+ return `${prefix}:${randomUUID()}`;
2073
+ } catch (e) {
2074
+ return `${prefix}:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;
2075
+ }
2076
+ }
2077
+ function earliestIsoTimestamp(...values) {
2078
+ let earliest;
2079
+ for (const value of values) {
2080
+ if (value === void 0) continue;
2081
+ const date = new Date(value);
2082
+ if (Number.isNaN(date.getTime())) continue;
2083
+ if (earliest === void 0 || date < earliest) earliest = date;
2084
+ }
2085
+ return earliest == null ? void 0 : earliest.toISOString();
2086
+ }
2087
+ function isPlainObject2(value) {
2088
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
2089
+ const proto = Object.getPrototypeOf(value);
2090
+ return proto === Object.prototype || proto === null;
2091
+ }
2092
+ var UNSAFE_MERGE_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
2093
+ function deepMergeProperties(target, source) {
2094
+ const out = { ...target };
2095
+ for (const [key, value] of Object.entries(source)) {
2096
+ if (value === void 0 || UNSAFE_MERGE_KEYS.has(key)) continue;
2097
+ const existing = out[key];
2098
+ out[key] = isPlainObject2(existing) && isPlainObject2(value) ? deepMergeProperties(existing, value) : value;
2099
+ }
2100
+ return out;
2101
+ }
2102
+ function mergePatches(target, source) {
2103
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
2104
+ const defined2 = Object.fromEntries(
2105
+ Object.entries(source).filter(([, value]) => value !== void 0)
2106
+ );
2107
+ const out = { ...target, ...defined2 };
2108
+ if (target.properties || source.properties) {
2109
+ out.properties = deepMergeProperties((_a = target.properties) != null ? _a : {}, (_b = source.properties) != null ? _b : {});
2110
+ }
2111
+ if (target.callerProperties || source.callerProperties) {
2112
+ out.callerProperties = deepMergeProperties(
2113
+ (_c = target.callerProperties) != null ? _c : {},
2114
+ (_d = source.callerProperties) != null ? _d : {}
2115
+ );
2116
+ }
2117
+ if (target.usage || source.usage) {
2118
+ out.usage = { ...(_e = target.usage) != null ? _e : {} };
2119
+ if (((_f = source.usage) == null ? void 0 : _f.promptTokens) !== void 0) {
2120
+ out.usage.promptTokens = source.usage.promptTokens;
2121
+ }
2122
+ if (((_g = source.usage) == null ? void 0 : _g.completionTokens) !== void 0) {
2123
+ out.usage.completionTokens = source.usage.completionTokens;
2124
+ }
2125
+ }
2126
+ if (source.error === void 0) {
2127
+ out.error = target.error;
2128
+ }
2129
+ if (target.featureFlags || source.featureFlags) {
2130
+ out.featureFlags = { ...(_h = target.featureFlags) != null ? _h : {}, ...(_i = source.featureFlags) != null ? _i : {} };
2131
+ }
2132
+ if (target.attachments || source.attachments) {
2133
+ out.attachments = [...(_j = target.attachments) != null ? _j : [], ...(_k = source.attachments) != null ? _k : []];
2134
+ }
2135
+ return out;
2136
+ }
2137
+ function isErrorLike(value) {
2138
+ return value !== null && typeof value === "object";
2139
+ }
2140
+ function eventTelemetryProperties(patch) {
2141
+ var _a, _b;
2142
+ const properties = {};
2143
+ if (((_a = patch.usage) == null ? void 0 : _a.promptTokens) !== void 0 && Number.isFinite(patch.usage.promptTokens)) {
2144
+ properties["ai.usage.prompt_tokens"] = patch.usage.promptTokens;
2145
+ }
2146
+ if (((_b = patch.usage) == null ? void 0 : _b.completionTokens) !== void 0 && Number.isFinite(patch.usage.completionTokens)) {
2147
+ properties["ai.usage.completion_tokens"] = patch.usage.completionTokens;
2148
+ }
2149
+ if (patch.error !== void 0 && patch.error !== null) {
2150
+ const constructorName = patch.error instanceof Error && patch.error.constructor !== Error ? patch.error.constructor.name : void 0;
2151
+ const errorType = patch.error instanceof Error ? patch.error.name && patch.error.name !== "Error" ? patch.error.name : constructorName || patch.error.name || "Error" : isErrorLike(patch.error) && typeof patch.error.name === "string" && patch.error.name.length > 0 ? patch.error.name : "Error";
2152
+ const errorMessage = patch.error instanceof Error ? patch.error.message : isErrorLike(patch.error) && typeof patch.error.message === "string" ? patch.error.message : String(patch.error);
2153
+ properties["error.type"] = errorType;
2154
+ properties["error.message"] = errorMessage;
2155
+ }
2156
+ return properties;
2157
+ }
2158
+ var FINISHED_EVENT_MEMORY = 1e4;
2159
+ var MANUAL_UPDATES = /* @__PURE__ */ new WeakSet();
2160
+ var EventShipper = class {
2161
+ constructor(opts) {
2162
+ this.appGitOwner = appGitOwnerId("event");
2163
+ this.buffers = /* @__PURE__ */ new Map();
2164
+ this.sticky = /* @__PURE__ */ new Map();
2165
+ this.timers = /* @__PURE__ */ new Map();
2166
+ this.inFlight = /* @__PURE__ */ new Set();
2167
+ this.background = /* @__PURE__ */ new Set();
2168
+ this.backgroundDrops = 0;
2169
+ this.cutOff = new InFlightCutOff();
2170
+ this.finishedEventIds = /* @__PURE__ */ new Set();
2171
+ this.sendChains = /* @__PURE__ */ new Map();
2172
+ this.deferredSends = /* @__PURE__ */ new Set();
2173
+ this.hasShutdown = false;
2174
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
2175
+ this.appGitContext = (_a = opts.appGitContext) != null ? _a : createAppGitContext(opts.appGit);
2176
+ this.ownsAppGitContext = opts.appGitContext === void 0;
2177
+ this.writeKey = (_b = opts.writeKey) == null ? void 0 : _b.trim();
2178
+ this.baseUrl = (_c = formatEndpoint(opts.endpoint)) != null ? _c : "https://api.raindrop.ai/v1/";
2179
+ this.enabled = opts.enabled !== false;
2180
+ this.debug = opts.debug;
2181
+ this.partialFlushMs = (_d = opts.partialFlushMs) != null ? _d : 1e3;
2182
+ this.sdkName = (_e = opts.sdkName) != null ? _e : "core";
2183
+ this.prefix = `[raindrop-ai/${this.sdkName}]`;
2184
+ this.defaultEventName = (_f = opts.defaultEventName) != null ? _f : "ai_generation";
2185
+ this.maxTextFieldCharsOpt = opts.maxTextFieldChars;
2186
+ this.flushTimeoutMs = resolveFlushTimeoutMs(opts.flushTimeoutMs);
2187
+ this.localDebuggerUrl = (_g = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl)) != null ? _g : void 0;
2188
+ if (this.debug && this.localDebuggerUrl) {
2189
+ console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
2190
+ }
2191
+ this.projectId = normalizeProjectId(opts.projectId, {
2192
+ debug: this.debug,
2193
+ prefix: this.prefix
2194
+ });
2195
+ this.redactPii = opts.redactPii === true;
2196
+ this.piiFields = new PiiFieldRedactor({
2197
+ startupFieldMap: opts.redactPiiFields,
2198
+ logPrefix: this.prefix
2199
+ });
2200
+ if (opts.redactPiiFields && !this.redactPii) {
2201
+ rateLimitedLog(
2202
+ `${this.prefix}.pii_fields_without_redaction`,
2203
+ () => console.warn(
2204
+ `${this.prefix} redactPiiFields is set but redactPii is off; nothing is redacted. Set redactPii: true to use it.`
2205
+ )
2206
+ );
2207
+ }
2208
+ this.wizardSession = opts.wizardSession || void 0;
2209
+ const runtime = detectRuntime();
2210
+ this.context = {
2211
+ library: {
2212
+ name: (_h = opts.libraryName) != null ? _h : "@raindrop-ai/core",
2213
+ version: (_i = opts.libraryVersion) != null ? _i : "0.0.0"
2214
+ },
2215
+ metadata: {
2216
+ jsRuntime: runtime,
2217
+ ...runtime === "node" ? { nodeVersion: process.version } : {}
2218
+ }
2219
+ };
2220
+ }
2221
+ ownAppGitContextForShutdown() {
2222
+ this.ownsAppGitContext = true;
2223
+ }
2224
+ isDebugEnabled() {
2225
+ return this.debug;
2226
+ }
2227
+ authHeaders() {
2228
+ return this.writeKey ? { Authorization: `Bearer ${this.writeKey}` } : {};
2229
+ }
2230
+ requestHeaders() {
2231
+ return { ...this.authHeaders(), ...projectIdHeaders(this.projectId) };
2232
+ }
2233
+ /**
2234
+ * Retry/timeout options for one POST. While `shutdown()` drains, sends retry
2235
+ * within its window (deadline = the shutdown deadline); a flush passes its
2236
+ * own deadline. `null` when the shutdown window is spent: the caller drops
2237
+ * the payload with a warning. After `shutdown()` returns, late sends get a
2238
+ * single short attempt rather than the full retry schedule.
2239
+ */
2240
+ requestOpts(deadlineAt) {
2241
+ if (this.shutdownDeadlineAt !== void 0) {
2242
+ if (this.shutdownDeadlineAt - Date.now() <= 0) return null;
2243
+ return {
2244
+ maxAttempts: 3,
2245
+ debug: this.debug,
2246
+ sdkName: this.sdkName,
2247
+ deadlineAt: Math.min(this.shutdownDeadlineAt, deadlineAt != null ? deadlineAt : Infinity),
2248
+ cutOff: this.cutOff.signal
2249
+ };
2250
+ }
2251
+ if (this.hasShutdown) {
2252
+ return {
2253
+ maxAttempts: 1,
2254
+ debug: this.debug,
2255
+ sdkName: this.sdkName,
2256
+ timeoutMs: POST_SHUTDOWN_TIMEOUT_MS,
2257
+ cutOff: this.cutOff.signal
2258
+ };
2259
+ }
2260
+ return {
2261
+ maxAttempts: 3,
2262
+ debug: this.debug,
2263
+ sdkName: this.sdkName,
2264
+ deadlineAt,
2265
+ cutOff: this.cutOff.signal
2266
+ };
2267
+ }
2268
+ shuttingDown() {
2269
+ return this.shutdownDeadlineAt !== void 0 || this.hasShutdown;
2270
+ }
2271
+ async patch(eventId, patch) {
2272
+ await this.patchWithFate(eventId, patch);
2273
+ }
2274
+ /**
2275
+ * Queue an update without waiting for any network send: for integrations,
2276
+ * whose captured call must return as soon as the update is queued (rule C9,
2277
+ * hot path). A finishing update starts its send in the background; `flush()`
2278
+ * and `shutdown()` wait for it within their deadline and count it in their
2279
+ * result. Never throws or rejects.
2280
+ */
2281
+ enqueue(eventId, patch) {
2282
+ let op;
2283
+ try {
2284
+ op = this.patchWithFate(eventId, patch).catch((err) => {
2285
+ this.warnBackgroundFailure(eventId, err);
2286
+ return "dropped";
2287
+ }).then((fate) => {
2288
+ if (fate === "dropped") this.backgroundDrops += 1;
2289
+ return fate;
2290
+ });
2291
+ } catch (err) {
2292
+ this.warnBackgroundFailure(eventId, err);
2293
+ return;
2294
+ }
2295
+ this.background.add(op);
2296
+ void op.finally(() => this.background.delete(op));
2297
+ }
2298
+ /** `finish()` without waiting for the send; see `enqueue`. */
2299
+ enqueueFinish(eventId, patch = {}) {
2300
+ this.enqueue(eventId, { ...patch, isPending: false });
2301
+ }
2302
+ /**
2303
+ * Caller properties win over everything the integration derived (W6). A
2304
+ * clash is intended by the caller, so it is only logged in debug mode.
2305
+ */
2306
+ withCallerProperties(eventId, derived, caller) {
2307
+ if (!caller || Object.keys(caller).length === 0) return derived;
2308
+ if (this.debug) {
2309
+ try {
2310
+ const keys = overriddenKeys(derived, caller);
2311
+ if (keys.length > 0) {
2312
+ console.log(
2313
+ `${this.prefix} event ${eventId}: caller properties override the integration's value for ${keys.map((k) => `"${k}"`).join(", ")}`
2314
+ );
2315
+ }
2316
+ } catch (e) {
2317
+ }
2318
+ }
2319
+ return deepMergeProperties(derived, caller);
2320
+ }
2321
+ warnBackgroundFailure(eventId, err) {
2322
+ rateLimitedLog(
2323
+ `${this.prefix}.background_update`,
2324
+ () => console.warn(`${this.prefix} update for event ${eventId} failed:`, err)
2325
+ );
2326
+ }
2327
+ /**
2328
+ * Id of the last event an integration finished in this process (manual
2329
+ * events API finishes excluded): what integrations expose as `lastEventId`
2330
+ * (wrapper profile W10).
2331
+ */
2332
+ get lastFinishedEventId() {
2333
+ return this.lastFinished;
2334
+ }
2335
+ async patchWithFate(eventId, patch) {
2336
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
2337
+ const manual = MANUAL_UPDATES.has(patch);
2338
+ if (!this.enabled) return void 0;
2339
+ if (!eventId || !eventId.trim()) return void 0;
2340
+ if (patch.userId !== void 0 && isMissingUserId(patch.userId)) {
2341
+ const { userId: _placeholder, ...rest } = patch;
2342
+ patch = rest;
2343
+ }
2344
+ const capturedSticky = this.sticky.get(eventId);
2345
+ const eventAlreadyKnown = capturedSticky !== void 0 || this.buffers.has(eventId);
2346
+ const destination = currentReplayTraceDestination();
2347
+ const cloudReplay = destination !== void 0 && destination.kind !== "workshop";
2348
+ if ((capturedSticky == null ? void 0 : capturedSticky.replayOnly) === true || !eventAlreadyKnown && cloudReplay) {
2349
+ if (patch.isPending === false) this.sticky.delete(eventId);
2350
+ else this.sticky.set(eventId, { ...capturedSticky, replayOnly: true });
2351
+ return void 0;
2352
+ }
2353
+ const maxChars = resolveMaxTextFieldChars(this.maxTextFieldCharsOpt);
2354
+ if (typeof patch.input === "string" && patch.input.length > maxChars) {
2355
+ patch = { ...patch, input: capText(patch.input, maxChars) };
2356
+ }
2357
+ if (typeof patch.output === "string" && patch.output.length > maxChars) {
2358
+ patch = { ...patch, output: capText(patch.output, maxChars) };
2359
+ }
2360
+ if (this.debug) {
2361
+ console.log(`${this.prefix} queue patch`, {
2362
+ eventId,
2363
+ userId: patch.userId,
2364
+ convoId: patch.convoId,
2365
+ eventName: patch.eventName,
2366
+ hasInput: typeof patch.input === "string" && patch.input.length > 0,
2367
+ hasOutput: typeof patch.output === "string" && patch.output.length > 0,
2368
+ attachments: (_b = (_a = patch.attachments) == null ? void 0 : _a.length) != null ? _b : 0,
2369
+ isPending: patch.isPending
2370
+ });
2371
+ }
2372
+ const sticky = (_c = this.sticky.get(eventId)) != null ? _c : {};
2373
+ const existing = (_d = this.buffers.get(eventId)) != null ? _d : {};
2374
+ const explicitProperties = patch.callerProperties !== void 0 ? { ...patch.properties, ...patch.callerProperties } : patch.properties;
2375
+ patch = {
2376
+ ...patch,
2377
+ properties: withAppGitProperties(
2378
+ patch.properties,
2379
+ this.appGitContext.forOperation(eventId, explicitProperties, this.appGitOwner)
2380
+ )
2381
+ };
2382
+ const merged = mergePatches(existing, patch);
2383
+ merged.isPending = (_g = (_f = (_e = patch.isPending) != null ? _e : existing.isPending) != null ? _f : sticky.isPending) != null ? _g : true;
2384
+ this.buffers.set(eventId, merged);
2385
+ this.sticky.set(eventId, {
2386
+ userId: (_h = merged.userId) != null ? _h : sticky.userId,
2387
+ convoId: (_i = merged.convoId) != null ? _i : sticky.convoId,
2388
+ eventName: (_j = merged.eventName) != null ? _j : sticky.eventName,
2389
+ isPending: (_k = merged.isPending) != null ? _k : sticky.isPending,
2390
+ startedAt: (_l = earliestIsoTimestamp(sticky.startedAt, patch.timestamp)) != null ? _l : (/* @__PURE__ */ new Date()).toISOString(),
2391
+ resumed: sticky.resumed,
2392
+ hasContent: sticky.hasContent === true || patchHasContent(patch),
2393
+ callerProperties: patch.callerProperties !== void 0 ? deepMergeProperties((_m = sticky.callerProperties) != null ? _m : {}, patch.callerProperties) : sticky.callerProperties
2394
+ });
2395
+ const t = this.timers.get(eventId);
2396
+ if (t) clearTimeout(t);
2397
+ if (merged.isPending === false) {
2398
+ if (!manual) this.lastFinished = eventId;
2399
+ this.noteFinish(eventId);
2400
+ this.noteEmptyFinish(eventId);
2401
+ const fate = await this.flushOne(eventId);
2402
+ if (this.appGitContext.releaseOperation) this.appGitContext.releaseOperation(eventId, this.appGitOwner);
2403
+ else this.appGitContext.finishOperation(eventId);
2404
+ return fate;
2405
+ }
2406
+ const timeout = setTimeout(() => {
2407
+ void this.flushOne(eventId).catch(() => {
2408
+ });
2409
+ }, this.partialFlushMs);
2410
+ this.timers.set(eventId, timeout);
2411
+ return void 0;
2412
+ }
2413
+ /**
2414
+ * A second finish for an event is still sent (ingest finalizes once and
2415
+ * treats it as an update, CONTRACT §10.2), but it usually means several
2416
+ * calls share one event id by mistake, so it is warned about.
2417
+ */
2418
+ noteFinish(eventId) {
2419
+ if (this.finishedEventIds.has(eventId)) {
2420
+ rateLimitedLog(
2421
+ `${this.prefix}.repeated_finish`,
2422
+ () => console.warn(
2423
+ `${this.prefix} event ${eventId} was already finished in this process; sending the update anyway (ingest finalizes an event once). Use a separate event id per interaction, or keep the event pending until its last call.`
2424
+ )
2425
+ );
2426
+ return;
2427
+ }
2428
+ this.finishedEventIds.add(eventId);
2429
+ if (this.finishedEventIds.size > FINISHED_EVENT_MEMORY) {
2430
+ const oldest = this.finishedEventIds.values().next().value;
2431
+ if (oldest !== void 0) this.finishedEventIds.delete(oldest);
2432
+ }
2433
+ }
2434
+ /**
2435
+ * An event finished with no input, output or attachments is almost always a
2436
+ * caller bug (CONTRACT §14.2, rule C5); it is sent anyway and warned about.
2437
+ * Not for a resumed event: its content may have been sent by another process.
2438
+ */
2439
+ noteEmptyFinish(eventId) {
2440
+ const sticky = this.sticky.get(eventId);
2441
+ if ((sticky == null ? void 0 : sticky.resumed) === true || (sticky == null ? void 0 : sticky.hasContent) === true) return;
2442
+ rateLimitedLog(
2443
+ `${this.prefix}.empty_finish`,
2444
+ () => console.warn(
2445
+ `${this.prefix} event ${eventId} finished with no input, output or attachments; sending it anyway. Pass the interaction's input at begin or its output at finish.`
2446
+ )
2447
+ );
2448
+ }
2449
+ /**
2450
+ * Continue an event that was begun elsewhere (another process, a queue
2451
+ * worker, a later request) using only its id. No request is sent; later
2452
+ * `patch` / `finish` calls for this id are sent even without a `userId`,
2453
+ * and ingest keeps the user, conversation and start time it already has.
2454
+ * Pass `userId` / `convoId` / `eventName` if you have them.
2455
+ */
2456
+ resume(eventId, options = {}) {
2457
+ var _a, _b, _c;
2458
+ if (!this.enabled) return;
2459
+ if (!eventId || !eventId.trim()) return;
2460
+ const sticky = (_a = this.sticky.get(eventId)) != null ? _a : {};
2461
+ this.sticky.set(eventId, {
2462
+ ...sticky,
2463
+ userId: isMissingUserId(options.userId) ? sticky.userId : options.userId,
2464
+ convoId: (_b = options.convoId) != null ? _b : sticky.convoId,
2465
+ eventName: (_c = options.eventName) != null ? _c : sticky.eventName,
2466
+ resumed: true
2467
+ });
2468
+ }
2469
+ async finish(eventId, patch) {
2470
+ const update = { ...patch, isPending: false };
2471
+ if (MANUAL_UPDATES.has(patch)) MANUAL_UPDATES.add(update);
2472
+ await this.patch(eventId, update);
2473
+ }
2474
+ /**
2475
+ * Send everything buffered, open (pending) events included, within
2476
+ * `flushTimeoutMs` (CONTRACT 1.2.1). Resolves, never rejects, to whether it
2477
+ * all reached ingest; when it didn't, it also warns. At the deadline,
2478
+ * payloads not yet sent stay queued for a later send and a request cut off
2479
+ * mid-flight is dropped. Sends already running when it was called are
2480
+ * waited for up to the deadline and then cut off.
2481
+ */
2482
+ async flush() {
2483
+ const result = await this.drainAll(Date.now() + this.flushTimeoutMs);
2484
+ if (!result.delivered && this.shutdownDeadlineAt === void 0) {
2485
+ rateLimitedLog(
2486
+ `${this.prefix}.flush_undelivered`,
2487
+ () => console.warn(`${this.prefix} ${describeUndelivered("flush()", result)}`)
2488
+ );
2489
+ }
2490
+ return asCompat(result);
2491
+ }
2492
+ async drainAll(deadlineAt) {
2493
+ if (!this.enabled) return { ...DELIVERED };
2494
+ const deferred = [...this.deferredSends];
2495
+ this.deferredSends.clear();
2496
+ for (const entry of deferred) if (entry.timer) clearTimeout(entry.timer);
2497
+ const ids = [...this.buffers.keys()];
2498
+ const fates = await Promise.all([
2499
+ ...ids.map((id) => this.flushOne(id, deadlineAt)),
2500
+ ...deferred.map((entry) => entry.send(deadlineAt))
2501
+ ]);
2502
+ const background = [...this.background];
2503
+ if (background.length > 0) {
2504
+ await raceWithTimeout(Promise.all(background), deadlineAt - Date.now());
2505
+ }
2506
+ for (; this.backgroundDrops > 0; this.backgroundDrops -= 1) fates.push("dropped");
2507
+ const running = [...this.inFlight];
2508
+ const { settled, stillRunning } = await awaitEarlierSends(
2509
+ running,
2510
+ deadlineAt,
2511
+ this.cutOff,
2512
+ (p) => this.inFlight.has(p)
2513
+ );
2514
+ const unresolved = background.filter((op) => this.background.has(op)).length;
2515
+ return summarize2(
2516
+ fates.filter((fate) => fate !== void 0),
2517
+ Math.max(stillRunning, unresolved),
2518
+ !settled || unresolved > 0
2519
+ );
2520
+ }
2521
+ /**
2522
+ * Flush within `flushTimeoutMs` and stop. Sends retry while the window
2523
+ * allows; whatever is left at the deadline is dropped with a warning, so a
2524
+ * dead network can never wedge process exit. Resolves, never rejects.
2525
+ */
2526
+ async shutdown() {
2527
+ this.hasShutdown = true;
2528
+ const deadlineAt = Date.now() + this.flushTimeoutMs;
2529
+ this.shutdownDeadlineAt = deadlineAt;
2530
+ let result = { ...DELIVERED };
2531
+ try {
2532
+ for (const t of this.timers.values()) clearTimeout(t);
2533
+ this.timers.clear();
2534
+ for (const [eventId, sticky] of this.sticky) {
2535
+ if (sticky.replayOnly) this.sticky.delete(eventId);
2536
+ }
2537
+ result = await this.drainAll(deadlineAt);
2538
+ if (!result.delivered) {
2539
+ this.warnShutdownDrop(
2540
+ `${result.dropped + result.queued + result.inFlight} payload(s) not delivered`
2541
+ );
2542
+ }
2543
+ } finally {
2544
+ this.shutdownDeadlineAt = void 0;
2545
+ if (this.ownsAppGitContext) this.appGitContext.dispose();
2546
+ }
2547
+ return asCompat(result);
2548
+ }
2549
+ async trackSignal(signal) {
2550
+ var _a, _b;
2551
+ if (!this.enabled) return;
2552
+ const destination = currentReplayTraceDestination();
2553
+ if (destination && destination.kind !== "workshop") return;
2554
+ const body = [
2555
+ {
2556
+ event_id: signal.eventId,
2557
+ signal_name: signal.name,
2558
+ signal_type: (_a = signal.type) != null ? _a : "default",
2559
+ timestamp: signal.timestamp,
2560
+ sentiment: signal.sentiment,
2561
+ attachment_id: signal.attachmentId,
2562
+ properties: {
2563
+ ...(_b = signal.properties) != null ? _b : {},
2564
+ ...signal.comment ? { comment: signal.comment } : {},
2565
+ ...signal.after ? { after: signal.after } : {}
2566
+ }
2567
+ }
2568
+ ].map((item) => this.redactFields("signal", item));
2569
+ if (!this.writeKey) return;
2570
+ await this.sendDirect("signal", `${this.baseUrl}signals/track`, body);
2571
+ }
2572
+ async identify(users) {
2573
+ if (!this.enabled) return;
2574
+ const destination = currentReplayTraceDestination();
2575
+ if (destination && destination.kind !== "workshop") return;
2576
+ const list = Array.isArray(users) ? users : [users];
2577
+ const body = list.filter((user) => {
2578
+ if (!(user == null ? void 0 : user.userId) || !user.userId.trim()) {
2579
+ if (this.debug) {
2580
+ console.warn(`${this.prefix} skipping identify: missing userId`);
2581
+ }
2582
+ return false;
2583
+ }
2584
+ return true;
2585
+ }).map(
2586
+ (user) => {
2587
+ var _a;
2588
+ return this.redactFields("identify", {
2589
+ user_id: user.userId,
2590
+ traits: (_a = user.traits) != null ? _a : {}
2591
+ });
2592
+ }
2593
+ );
2594
+ if (!this.writeKey) return;
2595
+ if (body.length === 0) return;
2596
+ await this.sendDirect("identify", `${this.baseUrl}users/identify`, body);
2597
+ }
2598
+ /**
2599
+ * Send a signal or identify body. Tracked so `flush()` waits for it. A send
2600
+ * a flush deadline deferred is kept and retried later (outside shutdown).
2601
+ */
2602
+ async sendDirect(kind, url, body, deadlineAt) {
2603
+ const opts = this.requestOpts(deadlineAt);
2604
+ if (!opts) {
2605
+ this.warnShutdownDrop(kind);
2606
+ return "dropped";
2607
+ }
2608
+ const sending = sendJson(url, body, this.requestHeaders(), opts);
2609
+ const tracked = sending.then(() => void 0);
2610
+ this.inFlight.add(tracked);
2611
+ let outcome;
2612
+ try {
2613
+ outcome = await sending;
2614
+ } finally {
2615
+ this.inFlight.delete(tracked);
2616
+ }
2617
+ const fate = fateOf(outcome, this.shuttingDown());
2618
+ if (fate === "queued") {
2619
+ this.deferSend(
2620
+ (later) => this.sendDirect(kind, url, body, later),
2621
+ outcome.status === "deferred" ? outcome.retryAtMs : void 0
2622
+ );
2623
+ } else if (fate === "dropped") {
2624
+ this.warnSendDropped(kind, outcome);
2625
+ }
2626
+ return fate;
2627
+ }
2628
+ deferSend(send, retryAtMs) {
2629
+ var _a, _b;
2630
+ if (this.deferredSends.size >= MAX_DEFERRED_SENDS) {
2631
+ rateLimitedLog(
2632
+ `${this.prefix}.deferred_full`,
2633
+ () => console.warn(`${this.prefix} too many sends waiting for a retry; dropping one`)
2634
+ );
2635
+ return;
2636
+ }
2637
+ const entry = { send };
2638
+ const delay = Math.max(this.partialFlushMs, (retryAtMs != null ? retryAtMs : 0) - Date.now());
2639
+ entry.timer = setTimeout(() => {
2640
+ if (!this.deferredSends.delete(entry)) return;
2641
+ void send().catch(() => {
2642
+ });
2643
+ }, delay);
2644
+ (_b = (_a = entry.timer).unref) == null ? void 0 : _b.call(_a);
2645
+ this.deferredSends.add(entry);
2646
+ }
2647
+ warnSendDropped(what, outcome) {
2648
+ var _a, _b;
2649
+ if (outcome.status === "delivered" || outcome.status === "rejected") return;
2650
+ 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" : (_b = (_a = outcome.error) == null ? void 0 : _a.message) != null ? _b : outcome.status;
2651
+ rateLimitedLog(
2652
+ `${this.prefix}.send_${what}_dropped`,
2653
+ () => console.warn(`${this.prefix} failed to send ${what} (dropping): ${reason}`)
2654
+ );
2655
+ }
2656
+ /** The payload with its PII fields redacted when `redactPii` is on (CONTRACT 11.2). */
2657
+ redactFields(kind, payload) {
2658
+ return this.redactPii ? this.piiFields.redact(kind, payload) : payload;
2659
+ }
2660
+ warnShutdownDrop(what) {
2661
+ rateLimitedLog(
2662
+ `${this.prefix}.shutdown_deadline`,
2663
+ () => console.warn(`${this.prefix} shutdown flush deadline exceeded; dropping ${what}`)
2664
+ );
2665
+ }
2666
+ async flushOne(eventId, deadlineAt) {
2667
+ if (!this.enabled) return void 0;
2668
+ const timer = this.timers.get(eventId);
2669
+ if (timer) {
2670
+ clearTimeout(timer);
2671
+ this.timers.delete(eventId);
2672
+ }
2673
+ const accumulated = this.buffers.get(eventId);
2674
+ this.buffers.delete(eventId);
2675
+ if (!accumulated) return void 0;
2676
+ const previous = this.sendChains.get(eventId);
2677
+ let release = () => {
2678
+ };
2679
+ const current = new Promise((resolve2) => {
2680
+ release = resolve2;
2681
+ });
2682
+ this.sendChains.set(eventId, current);
2683
+ try {
2684
+ if (previous) {
2685
+ const ready = deadlineAt === void 0 ? (await previous, true) : await raceWithTimeout(previous, deadlineAt - Date.now());
2686
+ if (!ready) {
2687
+ return this.requeue(eventId, accumulated, void 0);
2688
+ }
2689
+ }
2690
+ return await this.sendAccumulated(eventId, accumulated, deadlineAt);
2691
+ } finally {
2692
+ release();
2693
+ if (this.sendChains.get(eventId) === current) this.sendChains.delete(eventId);
2694
+ }
2695
+ }
2696
+ /**
2697
+ * Put an unsent update back under any newer one and send it later
2698
+ * (CONTRACT 1.2.1). During shutdown it is dropped instead.
2699
+ */
2700
+ requeue(eventId, accumulated, retryAtMs) {
2701
+ var _a, _b;
2702
+ if (this.shuttingDown()) {
2703
+ this.warnShutdownDrop(`track_partial ${eventId}`);
2704
+ if (accumulated.isPending === false) this.sticky.delete(eventId);
2705
+ return "dropped";
2706
+ }
2707
+ const newer = this.buffers.get(eventId);
2708
+ const merged = newer ? mergePatches(accumulated, newer) : accumulated;
2709
+ merged.isPending = (_a = newer == null ? void 0 : newer.isPending) != null ? _a : accumulated.isPending;
2710
+ this.buffers.set(eventId, merged);
2711
+ const existing = this.timers.get(eventId);
2712
+ if (existing) clearTimeout(existing);
2713
+ const delay = Math.max(this.partialFlushMs, (retryAtMs != null ? retryAtMs : 0) - Date.now());
2714
+ const timeout = setTimeout(() => {
2715
+ void this.flushOne(eventId).catch(() => {
2716
+ });
2717
+ }, delay);
2718
+ (_b = timeout.unref) == null ? void 0 : _b.call(timeout);
2719
+ this.timers.set(eventId, timeout);
2720
+ return "queued";
2721
+ }
2722
+ async sendAccumulated(eventId, accumulated, deadlineAt) {
2723
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
2724
+ const sticky = (_a = this.sticky.get(eventId)) != null ? _a : {};
2725
+ const isPending = (_c = (_b = accumulated.isPending) != null ? _b : sticky.isPending) != null ? _c : true;
2726
+ const knownEventName = (_d = accumulated.eventName) != null ? _d : sticky.eventName;
2727
+ const eventName = knownEventName != null ? knownEventName : sticky.resumed ? void 0 : this.defaultEventName;
2728
+ const userId = (_e = accumulated.userId) != null ? _e : sticky.userId;
2729
+ if (!userId && !sticky.resumed) {
2730
+ rateLimitedLog(
2731
+ `${this.prefix}.track_partial_missing_user`,
2732
+ () => console.warn(
2733
+ `${this.prefix} skipping track_partial for ${eventId}: missing userId (pass userId, or call resume(eventId) to continue an event begun elsewhere)`
2734
+ )
2735
+ );
2736
+ this.sticky.delete(eventId);
2737
+ return void 0;
2738
+ }
2739
+ if (!userId) {
2740
+ rateLimitedLog(
2741
+ `${this.prefix}.track_partial_resumed_without_user`,
2742
+ () => console.warn(
2743
+ `${this.prefix} sending track_partial for ${eventId} without a userId; ingest will use the user stored for this event (pass userId to resume() to set it explicitly)`
2744
+ )
2745
+ );
2746
+ }
2747
+ const { wizardSession, ...restProperties } = (_f = accumulated.properties) != null ? _f : {};
2748
+ let telemetryProperties = {};
2749
+ try {
2750
+ telemetryProperties = eventTelemetryProperties(accumulated);
2751
+ } catch (e) {
2752
+ }
2753
+ const convoId = (_g = accumulated.convoId) != null ? _g : sticky.convoId;
2754
+ const sessionTag = wizardSession != null ? wizardSession : this.wizardSession;
2755
+ const unredacted = {
2756
+ event_id: eventId,
2757
+ ...userId ? { user_id: userId } : {},
2758
+ ...eventName ? { event: eventName } : {},
2759
+ timestamp: (_i = (_h = sticky.startedAt) != null ? _h : accumulated.timestamp) != null ? _i : (/* @__PURE__ */ new Date()).toISOString(),
2760
+ ai_data: {
2761
+ input: accumulated.input,
2762
+ output: accumulated.error !== void 0 && accumulated.error !== null ? void 0 : accumulated.output,
2763
+ model: accumulated.model,
2764
+ convo_id: convoId
2765
+ },
2766
+ properties: {
2767
+ ...this.withCallerProperties(
2768
+ eventId,
2769
+ { ...restProperties, ...telemetryProperties },
2770
+ (_j = sticky.callerProperties) != null ? _j : accumulated.callerProperties
2771
+ ),
2772
+ ...sessionTag ? { "raindrop.wizardSession": sessionTag } : {},
2773
+ $context: this.context
2774
+ },
2775
+ ...accumulated.featureFlags && Object.keys(accumulated.featureFlags).length > 0 ? { feature_flags: accumulated.featureFlags } : {},
2776
+ attachments: accumulated.attachments,
2777
+ is_pending: isPending
2778
+ };
2779
+ const payload = this.redactFields("event", unredacted);
2780
+ const url = `${this.baseUrl}events/track_partial`;
2781
+ if (this.debug) {
2782
+ const sent = payload;
2783
+ const preview = (v, n) => typeof v === "string" ? v.slice(0, n) : void 0;
2784
+ console.log(`${this.prefix} sending track_partial`, {
2785
+ eventId,
2786
+ eventName,
2787
+ userId,
2788
+ convoId,
2789
+ isPending,
2790
+ inputPreview: preview((_k = sent.ai_data) == null ? void 0 : _k.input, 120),
2791
+ outputPreview: preview((_l = sent.ai_data) == null ? void 0 : _l.output, 120),
2792
+ attachments: (_n = (_m = sent.attachments) == null ? void 0 : _m.length) != null ? _n : 0,
2793
+ attachmentKinds: (_p = (_o = sent.attachments) == null ? void 0 : _o.map((a) => ({
2794
+ type: a.type,
2795
+ role: a.role,
2796
+ name: a.name,
2797
+ valuePreview: preview(a.value, 60)
2798
+ }))) != null ? _p : [],
2799
+ endpoint: url
2800
+ });
2801
+ }
2802
+ const mirror = this.localDebuggerUrl ? mirrorPartialEventToLocalDebugger(payload, {
2803
+ baseUrl: this.localDebuggerUrl,
2804
+ writeKey: this.writeKey,
2805
+ debug: this.debug,
2806
+ sdkName: this.sdkName
2807
+ }) : void 0;
2808
+ if (!this.writeKey) {
2809
+ if (!isPending) this.sticky.delete(eventId);
2810
+ if (mirror) await mirror;
2811
+ return void 0;
1269
2812
  }
1270
- } catch (e) {
2813
+ const opts = this.requestOpts(deadlineAt);
2814
+ if (!opts) {
2815
+ this.warnShutdownDrop(`track_partial ${eventId}`);
2816
+ if (!isPending) this.sticky.delete(eventId);
2817
+ if (mirror) await mirror;
2818
+ return "dropped";
2819
+ }
2820
+ const sending = sendJson(url, payload, this.requestHeaders(), opts);
2821
+ const combined = Promise.all([mirror, sending.then(() => void 0)]).then(() => void 0);
2822
+ this.inFlight.add(combined);
2823
+ let outcome;
2824
+ try {
2825
+ outcome = await sending;
2826
+ if (mirror) await mirror.catch(() => {
2827
+ });
2828
+ } finally {
2829
+ this.inFlight.delete(combined);
2830
+ }
2831
+ const fate = fateOf(outcome, this.shuttingDown());
2832
+ if (fate === "queued") {
2833
+ return this.requeue(
2834
+ eventId,
2835
+ accumulated,
2836
+ outcome.status === "deferred" ? outcome.retryAtMs : void 0
2837
+ );
2838
+ }
2839
+ if (fate === "dropped") this.warnSendDropped("track_partial", outcome);
2840
+ else if (this.debug && outcome.status === "delivered") {
2841
+ console.log(`${this.prefix} sent track_partial ${eventId} (${eventName})`);
2842
+ }
2843
+ if (!isPending) {
2844
+ this.sticky.delete(eventId);
2845
+ }
2846
+ return fate;
1271
2847
  }
1272
- return void 0;
1273
- }
1274
- function shouldAutoEnableLocalWorkshop() {
1275
- if (isLocalDevHost(readRuntimeHostname())) return true;
1276
- if (readEnvVar("NODE_ENV") === "development") return true;
1277
- return false;
1278
- }
1279
- function resolveLocalDebuggerBaseUrl(baseUrl) {
1280
- var _a, _b, _c;
1281
- if (baseUrl === null) return null;
1282
- if (typeof baseUrl === "string" && baseUrl.length > 0) {
1283
- return (_a = formatEndpoint(baseUrl)) != null ? _a : null;
2848
+ };
2849
+ function overriddenKeys(derived, caller) {
2850
+ const keys = [];
2851
+ for (const [key, value] of Object.entries(caller)) {
2852
+ if (value === void 0 || !(key in derived)) continue;
2853
+ const existing = derived[key];
2854
+ if (isPlainObject2(existing) && isPlainObject2(value)) {
2855
+ if (overriddenKeys(existing, value).length > 0) keys.push(key);
2856
+ } else if (JSON.stringify(existing) !== JSON.stringify(value)) {
2857
+ keys.push(key);
2858
+ }
1284
2859
  }
1285
- const explicitUrlEnv = readEnvVar(LOCAL_DEBUGGER_ENV_VAR);
1286
- if (explicitUrlEnv) return (_b = formatEndpoint(explicitUrlEnv)) != null ? _b : null;
1287
- const workshopEnv = readWorkshopEnv();
1288
- if (workshopEnv === "disable") return null;
1289
- if (workshopEnv === "enable") return DEFAULT_LOCAL_WORKSHOP_URL;
1290
- if (workshopEnv && "url" in workshopEnv) return (_c = formatEndpoint(workshopEnv.url)) != null ? _c : null;
1291
- if (shouldAutoEnableLocalWorkshop()) return DEFAULT_LOCAL_WORKSHOP_URL;
1292
- return null;
1293
- }
1294
- function localDebuggerEnabled(baseUrl) {
1295
- return resolveLocalDebuggerBaseUrl(baseUrl) !== null;
1296
- }
1297
- var LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS = 2e3;
1298
- function mirrorTraceExportToLocalDebugger(body, options = {}) {
1299
- var _a;
1300
- const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
1301
- if (!baseUrl) return Promise.resolve();
1302
- return postJson(`${baseUrl}traces`, body, {}, {
1303
- maxAttempts: 1,
1304
- debug: (_a = options.debug) != null ? _a : false,
1305
- sdkName: options.sdkName,
1306
- timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
1307
- }).catch(() => {
1308
- });
1309
- }
1310
- function mirrorPartialEventToLocalDebugger(event, options = {}) {
1311
- var _a;
1312
- const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
1313
- if (!baseUrl) return Promise.resolve();
1314
- const headers = options.writeKey ? { Authorization: `Bearer ${options.writeKey}` } : {};
1315
- return postJson(`${baseUrl}events/track_partial`, event, headers, {
1316
- maxAttempts: 1,
1317
- debug: (_a = options.debug) != null ? _a : false,
1318
- sdkName: options.sdkName,
1319
- timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
1320
- }).catch(() => {
1321
- });
2860
+ return keys;
1322
2861
  }
1323
- function sendLocalDebuggerLiveEvent(event, options = {}) {
2862
+ function patchHasContent(patch) {
1324
2863
  var _a, _b;
1325
- const destination = currentReplayTraceDestination();
1326
- if (destination && destination.kind !== "workshop") return;
1327
- const baseUrl = resolveLocalDebuggerBaseUrl(options.baseUrl);
1328
- if (!baseUrl) return;
1329
- void postJson(
1330
- `${baseUrl}live`,
1331
- {
1332
- ...event,
1333
- type: event.type,
1334
- timestamp: (_a = event.timestamp) != null ? _a : Date.now()
1335
- },
1336
- {},
1337
- {
1338
- maxAttempts: 1,
1339
- debug: (_b = options.debug) != null ? _b : false,
1340
- sdkName: options.sdkName
1341
- }
1342
- ).catch(() => {
1343
- });
1344
- }
1345
- var PROJECT_ID_HEADER = "X-Raindrop-Project-Id";
1346
- var PROJECT_ID_SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
1347
- function isValidProjectIdSlug(value) {
1348
- return PROJECT_ID_SLUG_PATTERN.test(value);
1349
- }
1350
- function normalizeProjectId(raw, opts) {
1351
- if (typeof raw !== "string") return void 0;
1352
- const trimmed = raw.trim();
1353
- if (!trimmed) return void 0;
1354
- if (!isValidProjectIdSlug(trimmed) && opts.debug) {
1355
- console.warn(
1356
- `${opts.prefix} projectId "${trimmed}" does not match slug ${PROJECT_ID_SLUG_PATTERN.source}; sending anyway \u2014 backend may reject with HTTP 400`
1357
- );
1358
- }
1359
- return trimmed;
2864
+ return typeof patch.input === "string" && patch.input.length > 0 || typeof patch.output === "string" && patch.output.length > 0 || ((_b = (_a = patch.attachments) == null ? void 0 : _a.length) != null ? _b : 0) > 0;
1360
2865
  }
1361
- function projectIdHeaders(projectId) {
1362
- return projectId ? { [PROJECT_ID_HEADER]: projectId } : {};
2866
+ function resolveFlushTimeoutMs(value) {
2867
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : DEFAULT_FLUSH_TIMEOUT_MS;
1363
2868
  }
1364
- var SHUTDOWN_DEADLINE_MS = 1e4;
1365
- var POST_SHUTDOWN_TIMEOUT_MS = 5e3;
1366
2869
  var MODEL_USAGE_ATTRIBUTES = {
1367
2870
  usageSource: "raindrop.usage.source",
1368
2871
  providerName: "gen_ai.provider.name",
@@ -1422,6 +2925,21 @@ function buildRawModelUsageAttributes(usage) {
1422
2925
  attrDouble(MODEL_USAGE_ATTRIBUTES.providerReportedCost, providerReportedCost)
1423
2926
  ].filter((attribute) => attribute !== void 0);
1424
2927
  }
2928
+ var KNOWN_MODEL_PROVIDERS = /* @__PURE__ */ new Set([
2929
+ ...MODEL_PROVIDER_NAMES.map(([, family]) => family),
2930
+ "vercel",
2931
+ // Further vendors Dawn's pricing resolves (apps/dawn/lib/spend).
2932
+ "deepseek",
2933
+ "fireworks-ai",
2934
+ "groq",
2935
+ "inception",
2936
+ "mistral",
2937
+ "moonshotai",
2938
+ "perplexity",
2939
+ "togetherai",
2940
+ "xai",
2941
+ "zai"
2942
+ ]);
1425
2943
  var STRING_ALIASES = {
1426
2944
  [MODEL_USAGE_ATTRIBUTES.requestModel]: ["ai.model.id", "ai.model"]
1427
2945
  };
@@ -1497,8 +3015,15 @@ var DEFAULT_REDACT_ATTRIBUTE_KEYS = [
1497
3015
  "ai.response.providerMetadata"
1498
3016
  ];
1499
3017
  var REDACT_JSON_ATTRIBUTE_KEYS = new Set(DEFAULT_REDACT_ATTRIBUTE_KEYS);
3018
+ var UNDELIVERED = Object.freeze({
3019
+ delivered: false,
3020
+ timedOut: false,
3021
+ dropped: 0,
3022
+ queued: 0,
3023
+ inFlight: 0
3024
+ });
1500
3025
  var PROMPT_TOOLS_ATTRIBUTE = "ai.prompt.tools";
1501
- function isRecord(value) {
3026
+ function isRecord3(value) {
1502
3027
  return typeof value === "object" && value !== null && !Array.isArray(value);
1503
3028
  }
1504
3029
  var JSON_SCHEMA_KEYS = [
@@ -1516,17 +3041,17 @@ var JSON_SCHEMA_KEYS = [
1516
3041
  "required"
1517
3042
  ];
1518
3043
  function isJsonSchema(value) {
1519
- if (!isRecord(value)) return false;
3044
+ if (!isRecord3(value)) return false;
1520
3045
  if (typeof value["~standard"] === "object") return false;
1521
- if (isRecord(value._def) || isRecord(value._zod)) return false;
3046
+ if (isRecord3(value._def) || isRecord3(value._zod)) return false;
1522
3047
  if (Object.keys(value).length === 0) return true;
1523
3048
  return JSON_SCHEMA_KEYS.some((key) => key in value);
1524
3049
  }
1525
3050
  function toJsonSchema(value, options) {
1526
3051
  if (value === void 0 || value === null) return void 0;
1527
3052
  if (isJsonSchema(value)) return value;
1528
- if (isRecord(value) && isJsonSchema(value.jsonSchema)) return value.jsonSchema;
1529
- if (isRecord(value) && isJsonSchema(value.json)) return value.json;
3053
+ if (isRecord3(value) && isJsonSchema(value.jsonSchema)) return value.jsonSchema;
3054
+ if (isRecord3(value) && isJsonSchema(value.json)) return value.json;
1530
3055
  if (options == null ? void 0 : options.schema) {
1531
3056
  try {
1532
3057
  return options.schema(value);
@@ -1549,23 +3074,23 @@ function functionTool(name, description, schema, options) {
1549
3074
  }
1550
3075
  function normalizeToolDeclaration(tool, options, fallbackName) {
1551
3076
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
1552
- if (!isRecord(tool)) return void 0;
3077
+ if (!isRecord3(tool)) return void 0;
1553
3078
  if (tool.type === "provider-defined" || tool.type === "provider") {
1554
3079
  const name2 = (_b = (_a = pickString(tool.name)) != null ? _a : pickString(tool.id)) != null ? _b : fallbackName;
1555
3080
  if (name2 === void 0) return void 0;
1556
3081
  const declaration = { type: "provider-defined", name: name2 };
1557
3082
  const id = pickString(tool.id);
1558
3083
  if (id !== void 0) declaration.id = id;
1559
- if (isRecord(tool.args)) declaration.args = tool.args;
3084
+ if (isRecord3(tool.args)) declaration.args = tool.args;
1560
3085
  return declaration;
1561
3086
  }
1562
- if (isRecord(tool.toolSpec)) {
3087
+ if (isRecord3(tool.toolSpec)) {
1563
3088
  const spec = tool.toolSpec;
1564
3089
  const name2 = (_c = pickString(spec.name)) != null ? _c : fallbackName;
1565
3090
  if (name2 === void 0) return void 0;
1566
3091
  return functionTool(name2, spec.description, spec.inputSchema, options);
1567
3092
  }
1568
- if (isRecord(tool.function)) {
3093
+ if (isRecord3(tool.function)) {
1569
3094
  const fn = tool.function;
1570
3095
  const name2 = (_d = pickString(fn.name)) != null ? _d : fallbackName;
1571
3096
  if (name2 === void 0) return void 0;
@@ -1591,7 +3116,7 @@ function isGeminiToolGroup(tool) {
1591
3116
  if (Array.isArray(tool.functionDeclarations)) return true;
1592
3117
  const keys = Object.keys(tool);
1593
3118
  if (keys.length === 0 || NOT_A_GEMINI_GROUP_KEYS.some((key) => key in tool)) return false;
1594
- return keys.every((key) => isRecord(tool[key]));
3119
+ return keys.every((key) => isRecord3(tool[key]));
1595
3120
  }
1596
3121
  function expandGeminiTool(tool, options) {
1597
3122
  const declarations = [];
@@ -1601,7 +3126,7 @@ function expandGeminiTool(tool, options) {
1601
3126
  const normalized = normalizeToolDeclaration(declaration, options);
1602
3127
  if (normalized) declarations.push(normalized);
1603
3128
  }
1604
- } else if (isRecord(value)) {
3129
+ } else if (isRecord3(value)) {
1605
3130
  declarations.push({ type: "provider-defined", id: key, name: key, args: value });
1606
3131
  }
1607
3132
  }
@@ -1611,14 +3136,14 @@ function normalizeToolDeclarations(tools, options) {
1611
3136
  if (tools === void 0 || tools === null) return void 0;
1612
3137
  if (Array.isArray(tools)) {
1613
3138
  return tools.flatMap((tool) => {
1614
- if (isRecord(tool) && isGeminiToolGroup(tool)) {
3139
+ if (isRecord3(tool) && isGeminiToolGroup(tool)) {
1615
3140
  return expandGeminiTool(tool, options);
1616
3141
  }
1617
3142
  const declaration = normalizeToolDeclaration(tool, options);
1618
3143
  return declaration ? [declaration] : [];
1619
3144
  });
1620
3145
  }
1621
- if (!isRecord(tools)) return void 0;
3146
+ if (!isRecord3(tools)) return void 0;
1622
3147
  return Object.entries(tools).flatMap(([key, tool]) => {
1623
3148
  const declaration = normalizeToolDeclaration(tool, options, key);
1624
3149
  return declaration ? [declaration] : [];
@@ -1781,9 +3306,28 @@ var resolveLocal = (sourceDirectory, detectBranch, completed) => {
1781
3306
  }
1782
3307
  };
1783
3308
  };
1784
- function createAppGitContext(options, runtime = {}) {
3309
+ function createAppGitContext2(options, runtime = {}) {
1785
3310
  return new AppGitContext(options, { ...runtime, resolveLocal });
1786
3311
  }
3312
+ function hasDestination(options) {
3313
+ var _a;
3314
+ if (options.enabled === false) return false;
3315
+ return Boolean(((_a = options.writeKey) == null ? void 0 : _a.trim()) || resolveLocalDebuggerBaseUrl(options.localDebuggerUrl));
3316
+ }
3317
+ var EventShipper2 = class extends EventShipper {
3318
+ constructor(options) {
3319
+ var _a;
3320
+ const ownsAppGitContext = options.appGitContext === void 0;
3321
+ const appGitContext = (_a = options.appGitContext) != null ? _a : createAppGitContext2(options.appGit, { allowDiscovery: hasDestination(options) });
3322
+ try {
3323
+ super({ ...options, appGitContext });
3324
+ } catch (error) {
3325
+ if (ownsAppGitContext) appGitContext.dispose();
3326
+ throw error;
3327
+ }
3328
+ if (ownsAppGitContext) this.ownAppGitContextForShutdown();
3329
+ }
3330
+ };
1787
3331
  globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = AsyncLocalStorage2;
1788
3332
  var SUPPRESS_TRACING_KEY = /* @__PURE__ */ Symbol.for(
1789
3333
  "OpenTelemetry SDK Context Key SUPPRESS_TRACING"
@@ -1814,7 +3358,7 @@ installTracingSuppressionHook();
1814
3358
  // package.json
1815
3359
  var package_default = {
1816
3360
  name: "raindrop-ai",
1817
- version: "1.0.5",
3361
+ version: "1.0.6",
1818
3362
  main: "dist/index.js",
1819
3363
  module: "dist/index.mjs",
1820
3364
  types: "dist/index.d.ts",
@@ -2332,97 +3876,10 @@ import {
2332
3876
  import { WeakValueMap } from "weakref";
2333
3877
 
2334
3878
  // src/tracing/direct/http.ts
2335
- function wait2(ms) {
2336
- return new Promise((resolve2) => setTimeout(resolve2, ms));
2337
- }
2338
3879
  function formatEndpoint2(endpoint) {
2339
3880
  if (!endpoint) return void 0;
2340
3881
  return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
2341
3882
  }
2342
- function parseRetryAfter2(headers) {
2343
- var _a;
2344
- const value = (_a = headers.get("Retry-After")) != null ? _a : headers.get("retry-after");
2345
- if (!value) return void 0;
2346
- const asNumber = Number(value);
2347
- if (!Number.isNaN(asNumber)) return asNumber * 1e3;
2348
- const asDate = new Date(value).getTime();
2349
- if (!Number.isNaN(asDate)) {
2350
- const delta = asDate - Date.now();
2351
- return delta > 0 ? delta : 0;
2352
- }
2353
- return void 0;
2354
- }
2355
- function getRetryDelayMs2(attemptNumber, previousError) {
2356
- if (previousError && typeof previousError === "object" && previousError !== null && "retryAfterMs" in previousError) {
2357
- const v = previousError.retryAfterMs;
2358
- if (typeof v === "number") return Math.min(Math.max(0, v), MAX_RETRY_DELAY_MS);
2359
- }
2360
- if (attemptNumber <= 1) return 0;
2361
- const base = 500;
2362
- const factor = Math.pow(2, attemptNumber - 2);
2363
- return Math.min(base * factor, MAX_RETRY_DELAY_MS);
2364
- }
2365
- async function withRetry2(operation, opName, opts) {
2366
- let lastError = void 0;
2367
- for (let attemptNumber = 1; attemptNumber <= opts.maxAttempts; attemptNumber++) {
2368
- if (attemptNumber > 1) {
2369
- const delay = getRetryDelayMs2(attemptNumber, lastError);
2370
- if (opts.debug) {
2371
- console.warn(
2372
- `[raindrop] ${opName} retry ${attemptNumber}/${opts.maxAttempts} in ${delay}ms`
2373
- );
2374
- }
2375
- if (delay > 0) await wait2(delay);
2376
- } else if (opts.debug) {
2377
- console.log(`[raindrop] ${opName} attempt ${attemptNumber}/${opts.maxAttempts}`);
2378
- }
2379
- try {
2380
- return await operation();
2381
- } catch (err) {
2382
- lastError = err;
2383
- if (opts.debug) {
2384
- const msg = err instanceof Error ? err.message : String(err);
2385
- console.warn(
2386
- `[raindrop] ${opName} attempt ${attemptNumber} failed: ${msg}${attemptNumber === opts.maxAttempts ? " (no more retries)" : ""}`
2387
- );
2388
- }
2389
- if (attemptNumber === opts.maxAttempts) break;
2390
- }
2391
- }
2392
- throw lastError instanceof Error ? lastError : new Error(String(lastError));
2393
- }
2394
- async function postJson2(url, body, headers, opts) {
2395
- var _a;
2396
- const opName = `POST ${redactUrlForLog(url)}`;
2397
- const timeoutMs = (_a = opts.timeoutMs) != null ? _a : DEFAULT_REQUEST_TIMEOUT_MS;
2398
- await withRetry2(
2399
- async () => {
2400
- const resp = await runWithTracingSuppressed(
2401
- () => fetch(url, {
2402
- method: "POST",
2403
- redirect: headers["X-Raindrop-Replay-Id"] !== void 0 ? "error" : "follow",
2404
- headers: {
2405
- "Content-Type": "application/json",
2406
- ...headers
2407
- },
2408
- body: JSON.stringify(body),
2409
- signal: AbortSignal.timeout(timeoutMs)
2410
- })
2411
- );
2412
- if (!resp.ok) {
2413
- const text = await resp.text().catch(() => "");
2414
- const err = new Error(
2415
- `HTTP ${resp.status} ${resp.statusText}${text ? `: ${text}` : ""}`
2416
- );
2417
- const retryAfterMs = parseRetryAfter2(resp.headers);
2418
- if (typeof retryAfterMs === "number") err.retryAfterMs = retryAfterMs;
2419
- throw err;
2420
- }
2421
- },
2422
- opName,
2423
- opts
2424
- );
2425
- }
2426
3883
 
2427
3884
  // src/tracing/direct/ids.ts
2428
3885
  function getCrypto2() {
@@ -2530,7 +3987,7 @@ function buildExportTraceServiceRequest2(spans) {
2530
3987
  }
2531
3988
 
2532
3989
  // src/tracing/direct/context.ts
2533
- import { context, isValidSpanId, isValidTraceId, trace } from "@opentelemetry/api";
3990
+ import { TraceFlags, context, isValidSpanId, isValidTraceId, trace } from "@opentelemetry/api";
2534
3991
  var INVALID_TRACE_ID = "00000000000000000000000000000000";
2535
3992
  var INVALID_SPAN_ID = "0000000000000000";
2536
3993
  function hexToBase64(hex) {
@@ -2561,6 +4018,17 @@ function getActiveTraceContext() {
2561
4018
  parentSpanIdB64: spanIdHex !== INVALID_SPAN_ID ? hexToBase64(spanIdHex) : void 0
2562
4019
  };
2563
4020
  }
4021
+ function savedParentContext(traceId, parentSpanId) {
4022
+ if (!traceId || !parentSpanId || !isValidTraceId(traceId) || !isValidSpanId(parentSpanId)) {
4023
+ return void 0;
4024
+ }
4025
+ return trace.setSpanContext(context.active(), {
4026
+ traceId,
4027
+ spanId: parentSpanId,
4028
+ traceFlags: TraceFlags.SAMPLED,
4029
+ isRemote: true
4030
+ });
4031
+ }
2564
4032
 
2565
4033
  // src/tracing/direct/shipper.ts
2566
4034
  function serializeAssociationValue(value) {
@@ -2570,6 +4038,8 @@ var DirectTraceShipper = class {
2570
4038
  constructor(opts) {
2571
4039
  this.queue = [];
2572
4040
  this.inFlight = /* @__PURE__ */ new Set();
4041
+ /** Cuts off sends still running at a flush or shutdown deadline. */
4042
+ this.cutOff = new InFlightCutOff();
2573
4043
  /**
2574
4044
  * Set once `shutdown()` begins and never cleared. Sends issued after the
2575
4045
  * drain window (stragglers, or flush work the deadline abandoned
@@ -2588,6 +4058,7 @@ var DirectTraceShipper = class {
2588
4058
  this.flushIntervalMs = (_d = opts.flushIntervalMs) != null ? _d : 1e3;
2589
4059
  this.maxBatchSize = (_e = opts.maxBatchSize) != null ? _e : 50;
2590
4060
  this.maxQueueSize = (_f = opts.maxQueueSize) != null ? _f : 5e3;
4061
+ this.flushTimeoutMs = resolveFlushTimeoutMs(opts.flushTimeoutMs);
2591
4062
  const resolved = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl);
2592
4063
  if (resolved && resolved !== this.baseUrl) {
2593
4064
  this.localDebuggerUrl = resolved;
@@ -2716,28 +4187,56 @@ var DirectTraceShipper = class {
2716
4187
  }
2717
4188
  this.queue.push(queued);
2718
4189
  if (this.queue.length >= this.maxBatchSize) {
2719
- void this.flush().catch(() => {
4190
+ void this.drain().catch(() => {
2720
4191
  });
2721
4192
  return;
2722
4193
  }
2723
- if (!this.timer) {
2724
- this.timer = setTimeout(() => {
2725
- this.timer = void 0;
2726
- void this.flush().catch(() => {
2727
- });
2728
- }, this.flushIntervalMs);
2729
- }
4194
+ this.scheduleDrain(this.flushIntervalMs);
4195
+ }
4196
+ scheduleDrain(delayMs) {
4197
+ if (this.timer) return;
4198
+ this.timer = setTimeout(() => {
4199
+ this.timer = void 0;
4200
+ void this.drain().catch(() => {
4201
+ });
4202
+ }, delayMs);
2730
4203
  }
4204
+ /**
4205
+ * Send every queued span within `flushTimeoutMs` (CONTRACT 1.2.1). Resolves,
4206
+ * never rejects; spans not yet sent at the deadline stay queued.
4207
+ */
2731
4208
  async flush() {
4209
+ const result = await this.drainWithin(Date.now() + this.flushTimeoutMs);
4210
+ if (!result.delivered && this.shutdownDeadlineAt === void 0) {
4211
+ rateLimitedLog(
4212
+ "js-sdk.direct.flush_undelivered",
4213
+ () => console.warn(`[raindrop] direct: ${describeUndelivered("flush()", result)}`)
4214
+ );
4215
+ }
4216
+ return asCompat(result);
4217
+ }
4218
+ async drainWithin(deadlineAt) {
4219
+ const earlier = [...this.inFlight];
4220
+ const fates = this.enabled ? await this.drain(deadlineAt) : [];
4221
+ const { settled, stillRunning } = await awaitEarlierSends(
4222
+ earlier,
4223
+ deadlineAt,
4224
+ this.cutOff,
4225
+ (p) => this.inFlight.has(p)
4226
+ );
4227
+ return summarize2(fates, stillRunning, !settled);
4228
+ }
4229
+ async drain(deadlineAt) {
2732
4230
  var _a;
2733
- if (!this.enabled) return;
4231
+ const fates = [];
4232
+ if (!this.enabled) return fates;
2734
4233
  if (this.timer) {
2735
4234
  clearTimeout(this.timer);
2736
4235
  this.timer = void 0;
2737
4236
  }
2738
4237
  while (this.queue.length > 0) {
2739
4238
  const batch = this.queue.splice(0, this.maxBatchSize);
2740
- const opts = this.requestOpts();
4239
+ const opts = this.requestOpts(deadlineAt);
2741
4240
  if (!opts) {
2742
4241
  rateLimitedLog(
2743
4242
  "js-sdk.direct.shutdown_deadline",
@@ -2745,84 +4244,108 @@ var DirectTraceShipper = class {
2745
4244
  `[raindrop] direct: shutdown flush deadline exceeded; dropping ${batch.length} spans`
2746
4245
  )
2747
4246
  );
4247
+ fates.push("dropped");
2748
4248
  continue;
2749
4249
  }
2750
4250
  const groups = /* @__PURE__ */ new Map();
2751
4251
  for (const queued of batch) {
2752
4252
  const spans = groups.get(queued.replayDestination);
2753
- if (spans) spans.push(queued.span);
2754
- else groups.set(queued.replayDestination, [queued.span]);
4253
+ if (spans) spans.push(queued);
4254
+ else groups.set(queued.replayDestination, [queued]);
2755
4255
  }
2756
- for (const [replayDestination, spans] of groups) {
4256
+ const requeue = [];
4257
+ let retryAtMs;
4258
+ for (const [replayDestination, queuedSpans] of groups) {
2757
4259
  if (!replayDestination && !this.cloudEnabled) continue;
2758
4260
  if ((replayDestination == null ? void 0 : replayDestination.kind) === "workshop") continue;
2759
- const body = buildExportTraceServiceRequest2(spans);
4261
+ const body = buildExportTraceServiceRequest2(queuedSpans.map((q) => q.span));
2760
4262
  const url = replayDestination ? replayTraceUrl(replayDestination.url) : `${this.baseUrl}traces`;
2761
4263
  const headers = replayDestination ? {
2762
4264
  Authorization: `Bearer ${replayDestination.apiKey}`,
2763
4265
  "X-Raindrop-Replay-Id": replayDestination.replayId,
2764
4266
  "X-Raindrop-Project-Id": (_a = replayDestination.projectId) != null ? _a : "default"
2765
4267
  } : { Authorization: `Bearer ${this.writeKey}`, ...projectIdHeaders(this.projectId) };
2766
- const p = postJson2(url, body, headers, opts);
2767
- this.inFlight.add(p);
4268
+ const sending = sendJson(url, body, headers, opts);
4269
+ const tracked = sending.then(() => void 0);
4270
+ this.inFlight.add(tracked);
4271
+ let outcome;
2768
4272
  try {
2769
- try {
2770
- await p;
2771
- if (this.debug) console.log(`[raindrop] direct: sent ${spans.length} spans`);
2772
- } catch (err) {
2773
- if (this.debug) {
2774
- const msg = err instanceof Error ? err.message : String(err);
2775
- console.warn(`[raindrop] direct: failed to send spans (dropping): ${msg}`);
2776
- }
2777
- }
4273
+ outcome = await sending;
2778
4274
  } finally {
2779
- this.inFlight.delete(p);
4275
+ this.inFlight.delete(tracked);
4276
+ }
4277
+ const fate = fateOf(outcome, this.shutdownDeadlineAt !== void 0 || this.hasShutdown);
4278
+ fates.push(fate);
4279
+ if (fate === "queued") {
4280
+ requeue.push(...queuedSpans);
4281
+ if (outcome.status === "deferred" && outcome.retryAtMs !== void 0) {
4282
+ retryAtMs = Math.max(retryAtMs != null ? retryAtMs : 0, outcome.retryAtMs);
4283
+ }
4284
+ } else if (fate === "dropped") {
4285
+ 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;
4286
+ rateLimitedLog(
4287
+ "js-sdk.direct.send_failed",
4288
+ () => console.warn(`[raindrop] direct: failed to send ${queuedSpans.length} spans (dropping): ${reason}`)
4289
+ );
4290
+ } else if (this.debug) {
4291
+ console.log(`[raindrop] direct: sent ${queuedSpans.length} spans`);
2780
4292
  }
2781
4293
  }
4294
+ if (requeue.length > 0) {
4295
+ this.queue.unshift(...requeue);
4296
+ if (this.queue.length > this.maxQueueSize) this.queue.splice(this.maxQueueSize);
4297
+ this.scheduleDrain(Math.max(this.flushIntervalMs, (retryAtMs != null ? retryAtMs : 0) - Date.now()));
4298
+ break;
4299
+ }
2782
4300
  }
4301
+ return fates;
2783
4302
  }
2784
4303
  /**
2785
- * Retry/timeout options for one batch POST, honoring the shutdown budget:
2786
- * outside shutdown, the normal 3-attempt schedule; during shutdown, a
2787
- * single attempt clamped to the remaining window; `null` once the window
2788
- * is exhausted (caller drops the batch). After shutdown() returns,
2789
- * stragglers run as a single short attempt.
4304
+ * Retry/timeout options for one batch POST: the normal 3-attempt schedule,
4305
+ * bounded by a flush deadline when given; during shutdown, retries within
4306
+ * the shutdown window; `null` once the window is spent (caller drops the
4307
+ * batch). After shutdown() returns, stragglers run as a single short attempt.
2790
4308
  */
2791
- requestOpts() {
4309
+ requestOpts(deadlineAt) {
4310
+ const opts = this.scheduleFor(deadlineAt);
4311
+ return opts && { ...opts, cutOff: this.cutOff.signal };
4312
+ }
4313
+ scheduleFor(deadlineAt) {
2792
4314
  if (this.shutdownDeadlineAt !== void 0) {
2793
- const remainingMs = this.shutdownDeadlineAt - Date.now();
2794
- if (remainingMs <= 0) return null;
4315
+ if (this.shutdownDeadlineAt - Date.now() <= 0) return null;
2795
4316
  return {
2796
- maxAttempts: 1,
4317
+ maxAttempts: 3,
2797
4318
  debug: this.debug,
2798
- timeoutMs: Math.min(DEFAULT_REQUEST_TIMEOUT_MS, remainingMs)
4319
+ deadlineAt: Math.min(this.shutdownDeadlineAt, deadlineAt != null ? deadlineAt : Infinity)
2799
4320
  };
2800
4321
  }
2801
4322
  if (this.hasShutdown) {
2802
4323
  return { maxAttempts: 1, debug: this.debug, timeoutMs: POST_SHUTDOWN_TIMEOUT_MS };
2803
4324
  }
2804
- return { maxAttempts: 3, debug: this.debug };
4325
+ return { maxAttempts: 3, debug: this.debug, deadlineAt };
2805
4326
  }
4327
+ /** Flush within `flushTimeoutMs` and stop; spans left at the deadline are dropped. */
2806
4328
  async shutdown() {
2807
4329
  this.hasShutdown = true;
2808
- this.shutdownDeadlineAt = Date.now() + SHUTDOWN_DEADLINE_MS;
4330
+ const deadlineAt = Date.now() + this.flushTimeoutMs;
4331
+ this.shutdownDeadlineAt = deadlineAt;
4332
+ let result = { ...DELIVERED };
2809
4333
  try {
2810
4334
  if (this.timer) {
2811
4335
  clearTimeout(this.timer);
2812
4336
  this.timer = void 0;
2813
4337
  }
2814
- const drain = async () => {
2815
- await this.flush();
2816
- await Promise.all([...this.inFlight].map((p) => p.catch(() => {
2817
- })));
2818
- };
2819
- const settled = await raceWithTimeout(drain(), SHUTDOWN_DEADLINE_MS);
2820
- if (!settled && this.debug) {
2821
- console.warn("[raindrop] direct: shutdown deadline exceeded; abandoning in-flight spans");
4338
+ result = await this.drainWithin(deadlineAt);
4339
+ if (!result.delivered) {
4340
+ rateLimitedLog(
4341
+ "js-sdk.direct.shutdown_deadline",
4342
+ () => console.warn(`[raindrop] direct: ${describeUndelivered("shutdown()", result)}`)
4343
+ );
2822
4344
  }
2823
4345
  } finally {
2824
4346
  this.shutdownDeadlineAt = void 0;
2825
4347
  }
4348
+ return asCompat(result);
2826
4349
  }
2827
4350
  };
2828
4351
 
@@ -3329,13 +4852,28 @@ async function flushAll() {
3329
4852
  // src/tracing/liveInteraction.ts
3330
4853
  import {
3331
4854
  SpanStatusCode as SpanStatusCode3,
3332
- TraceFlags,
4855
+ TraceFlags as TraceFlags2,
3333
4856
  context as context4,
3334
4857
  isValidSpanId as isValidSpanId2,
3335
4858
  isValidTraceId as isValidTraceId2,
3336
4859
  trace as trace4
3337
4860
  } from "@opentelemetry/api";
3338
4861
 
4862
+ // src/tracing/tool-timing.ts
4863
+ function toMs(value) {
4864
+ return value instanceof Date ? value.getTime() : value;
4865
+ }
4866
+ function resolveToolTiming(input, now = Date.now()) {
4867
+ var _a, _b, _c;
4868
+ if (input.endTime !== void 0) {
4869
+ const endTimeMs = toMs(input.endTime);
4870
+ const startTimeMs2 = input.startTime !== void 0 ? toMs(input.startTime) : endTimeMs - ((_a = input.durationMs) != null ? _a : 0);
4871
+ return { startTimeMs: startTimeMs2, endTimeMs, durationMs: endTimeMs - startTimeMs2 };
4872
+ }
4873
+ const startTimeMs = input.startTime !== void 0 ? toMs(input.startTime) : now - ((_b = input.durationMs) != null ? _b : 0);
4874
+ return { startTimeMs, endTimeMs: startTimeMs + ((_c = input.durationMs) != null ? _c : 0), durationMs: input.durationMs };
4875
+ }
4876
+
3339
4877
  // src/tracing/subagents.ts
3340
4878
  import { SpanStatusCode as SpanStatusCode2, context as context3, trace as trace3 } from "@opentelemetry/api";
3341
4879
  var DEFAULT_SUBAGENT_NAME = "subagent";
@@ -3841,7 +5379,7 @@ var LiveInteraction = class {
3841
5379
  const spanContext = {
3842
5380
  traceId: base64ToHex2(traceIdB64),
3843
5381
  spanId: base64ToHex2(spanIdB64),
3844
- traceFlags: TraceFlags.SAMPLED
5382
+ traceFlags: TraceFlags2.SAMPLED
3845
5383
  };
3846
5384
  const wrappedContext = trace4.setSpan(context4.active(), trace4.wrapSpanContext(spanContext));
3847
5385
  const invoke = () => this.routing ? withRoutingContext(this.routing, () => fn.apply(thisArg, args)) : fn.apply(thisArg, args);
@@ -3933,7 +5471,7 @@ var LiveInteraction = class {
3933
5471
  const spanContext = {
3934
5472
  traceId: base64ToHex2(traceIdB64),
3935
5473
  spanId: base64ToHex2(spanIdB64),
3936
- traceFlags: TraceFlags.SAMPLED
5474
+ traceFlags: TraceFlags2.SAMPLED
3937
5475
  };
3938
5476
  const wrappedContext = trace4.setSpan(context4.active(), trace4.wrapSpanContext(spanContext));
3939
5477
  const invoke = () => this.routing ? withRoutingContext(this.routing, () => fn.apply(thisArg, args)) : fn.apply(thisArg, args);
@@ -4424,15 +5962,12 @@ var LiveInteraction = class {
4424
5962
  name,
4425
5963
  input,
4426
5964
  output,
4427
- durationMs,
4428
- startTime,
4429
5965
  error,
4430
5966
  properties = {},
4431
5967
  traceId: explicitTraceId,
4432
5968
  parentSpanId: explicitParentSpanId
4433
5969
  } = params;
4434
- const startTimeMs = startTime instanceof Date ? startTime.getTime() : typeof startTime === "number" ? startTime : Date.now() - (durationMs != null ? durationMs : 0);
4435
- const endTimeMs = startTimeMs + (durationMs != null ? durationMs : 0);
5970
+ const { startTimeMs, endTimeMs, durationMs } = resolveToolTiming(params);
4436
5971
  if (this.directShipper) {
4437
5972
  const activeContext = (_a = getExplicitTraceContext(explicitTraceId, explicitParentSpanId)) != null ? _a : getActiveTraceContext();
4438
5973
  const traceIdB64 = this.ensureTraceId(activeContext.traceIdB64);
@@ -4478,9 +6013,14 @@ var LiveInteraction = class {
4478
6013
  });
4479
6014
  return;
4480
6015
  }
4481
- const span = this.tracer.startSpan(name, {
4482
- startTime: startTimeMs
4483
- });
6016
+ const savedParent = savedParentContext(explicitTraceId, explicitParentSpanId);
6017
+ const span = this.tracer.startSpan(
6018
+ name,
6019
+ {
6020
+ startTime: startTimeMs
6021
+ },
6022
+ savedParent
6023
+ );
4484
6024
  const contextProperties = getPropertiesFromContext(this.context);
4485
6025
  setAssociationProperties(span, contextProperties);
4486
6026
  span.setAttribute("traceloop.span.kind", "tool");
@@ -4590,15 +6130,12 @@ var LiveTracer = class {
4590
6130
  name,
4591
6131
  input,
4592
6132
  output,
4593
- durationMs,
4594
- startTime,
4595
6133
  error,
4596
6134
  properties = {},
4597
6135
  traceId: explicitTraceId,
4598
6136
  parentSpanId: explicitParentSpanId
4599
6137
  } = params;
4600
- const startTimeMs = startTime instanceof Date ? startTime.getTime() : typeof startTime === "number" ? startTime : Date.now() - (durationMs != null ? durationMs : 0);
4601
- const endTimeMs = startTimeMs + (durationMs != null ? durationMs : 0);
6138
+ const { startTimeMs, endTimeMs, durationMs } = resolveToolTiming(params);
4602
6139
  if (this.directShipper) {
4603
6140
  const { traceIdB64, parentSpanIdB64 } = (_a = getExplicitTraceContext(explicitTraceId, explicitParentSpanId)) != null ? _a : getActiveTraceContext();
4604
6141
  const spanIdB64 = base64Encode2(randomBytes2(8));
@@ -4636,9 +6173,13 @@ var LiveTracer = class {
4636
6173
  }
4637
6174
  return;
4638
6175
  }
4639
- const span = this.tracer.startSpan(name, {
4640
- startTime: startTimeMs
4641
- });
6176
+ const span = this.tracer.startSpan(
6177
+ name,
6178
+ {
6179
+ startTime: startTimeMs
6180
+ },
6181
+ savedParentContext(explicitTraceId, explicitParentSpanId)
6182
+ );
4642
6183
  this.stampRouting(span);
4643
6184
  Object.entries(this.globalProperties).forEach(([key, value]) => {
4644
6185
  span.setAttribute("traceloop.association.properties." + key, String(value));
@@ -5195,6 +6736,7 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
5195
6736
  localDebuggerUrl,
5196
6737
  cloudEnabled,
5197
6738
  projectId,
6739
+ flushTimeoutMs,
5198
6740
  ...otherOptions
5199
6741
  } = options;
5200
6742
  const cloudEnabledResolved = cloudEnabled != null ? cloudEnabled : true;
@@ -5226,7 +6768,8 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
5226
6768
  enabled: tracingEnabled !== false,
5227
6769
  localDebuggerUrl,
5228
6770
  cloudEnabled: cloudEnabledResolved,
5229
- projectId
6771
+ projectId,
6772
+ flushTimeoutMs
5230
6773
  }) : void 0;
5231
6774
  let traceloopInitialized = false;
5232
6775
  let claimedPipeline = false;
@@ -5679,30 +7222,49 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
5679
7222
  * Safe to call when nothing is in flight; never throws.
5680
7223
  */
5681
7224
  async forceFlush() {
7225
+ const deadlineAt = Date.now() + resolveFlushTimeoutMs(flushTimeoutMs);
7226
+ let result = { ...DELIVERED };
5682
7227
  if (directShipper) {
5683
7228
  try {
5684
- await directShipper.flush();
7229
+ result = await directShipper.flush();
5685
7230
  } catch (e) {
5686
7231
  }
5687
7232
  }
5688
7233
  if (traceloopInitialized) {
5689
- try {
5690
- await forceFlush();
5691
- } catch (e) {
7234
+ const settled = await raceWithTimeout(
7235
+ forceFlush().catch(() => {
7236
+ }),
7237
+ deadlineAt - Date.now()
7238
+ );
7239
+ if (!settled) {
7240
+ result = combineResults(result, {
7241
+ ...DELIVERED,
7242
+ delivered: false,
7243
+ timedOut: true,
7244
+ inFlight: 1
7245
+ });
5692
7246
  }
5693
7247
  }
7248
+ return asCompat(result);
5694
7249
  },
7250
+ /** Drain and stop; resolves (never rejects) to the direct shipper's result. */
5695
7251
  async close() {
7252
+ var _a2;
5696
7253
  deregisterExitFlusher == null ? void 0 : deregisterExitFlusher();
5697
7254
  activeInteractions.clear();
5698
7255
  activeInteractionsByEventId.clear();
5699
- await (directShipper == null ? void 0 : directShipper.shutdown());
7256
+ let result = { ...DELIVERED };
7257
+ try {
7258
+ result = (_a2 = await (directShipper == null ? void 0 : directShipper.shutdown())) != null ? _a2 : result;
7259
+ } catch (e) {
7260
+ }
5700
7261
  if (traceloopInitialized) {
5701
7262
  try {
5702
7263
  await forceFlush();
5703
7264
  } catch (e) {
5704
7265
  }
5705
7266
  }
7267
+ return result;
5706
7268
  }
5707
7269
  };
5708
7270
  };
@@ -5725,22 +7287,31 @@ export {
5725
7287
  randomUUID,
5726
7288
  runWithTracingSuppressed,
5727
7289
  DEFAULT_REQUEST_TIMEOUT_MS,
5728
- MAX_RETRY_DELAY_MS,
5729
7290
  redactUrlForLog,
5730
7291
  rateLimitedLog,
5731
7292
  raceWithTimeout,
7293
+ InFlightCutOff,
7294
+ awaitEarlierSends,
7295
+ sendJson,
7296
+ asCompat,
7297
+ DELIVERED,
7298
+ fateOf,
7299
+ summarize2,
7300
+ combineResults,
7301
+ describeUndelivered,
5732
7302
  setDefaultMaxTextFieldChars,
5733
7303
  resolveMaxTextFieldChars,
5734
7304
  capText,
5735
- stringifyBounded,
5736
7305
  resolveLocalDebuggerBaseUrl,
5737
7306
  localDebuggerEnabled,
5738
- mirrorPartialEventToLocalDebugger,
5739
7307
  normalizeProjectId,
5740
7308
  projectIdHeaders,
5741
- SHUTDOWN_DEADLINE_MS,
7309
+ PiiFieldRedactor,
7310
+ isMissingUserId,
5742
7311
  POST_SHUTDOWN_TIMEOUT_MS,
5743
- createAppGitContext,
7312
+ resolveFlushTimeoutMs,
7313
+ createAppGitContext2 as createAppGitContext,
7314
+ EventShipper2,
5744
7315
  package_default,
5745
7316
  authHintForKey,
5746
7317
  withTask,