raindrop-ai 3.0.0 → 3.0.1

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.
@@ -102,7 +102,7 @@ function evalScopeAttributes() {
102
102
  return { [EVAL_CORRELATION_ID_ATTRIBUTE]: scope.correlationId };
103
103
  }
104
104
 
105
- // ../core/dist/chunk-5OUEKTIO.js
105
+ // ../core/dist/chunk-OPHDM4MC.js
106
106
  var require_NameRedactor = __commonJS({
107
107
  "../redact-pii/dist/built-ins/NameRedactor.js"(exports) {
108
108
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -603,14 +603,14 @@ function attributeStorage() {
603
603
  return storage2;
604
604
  }
605
605
  function makeAttributeFrame(attributes, owner) {
606
- const snapshot = { ...attributes };
606
+ const snapshot2 = { ...attributes };
607
607
  const WeakRefCtor = owner !== void 0 ? getWeakRefCtor() : void 0;
608
608
  const ref = WeakRefCtor && owner !== void 0 ? new WeakRefCtor(owner) : void 0;
609
609
  const owned = /* @__PURE__ */ new WeakSet();
610
610
  let dead = false;
611
611
  let sawError = false;
612
612
  return {
613
- attributes: snapshot,
613
+ attributes: snapshot2,
614
614
  sawErrorSpan: () => sawError,
615
615
  ownsSpan: (span) => owned.has(span),
616
616
  claimSpan(span) {
@@ -867,11 +867,11 @@ var AppGitContextImpl = class {
867
867
  }
868
868
  /** Existing replay branch reporting stays separate from opt-in event properties. */
869
869
  snapshotForReplay() {
870
- const snapshot = this.snapshot();
871
- if (this.replayBranch && !own(snapshot, APP_BRANCH) && snapshot[APP_COMMIT_SHA] === this.defaults[APP_COMMIT_SHA]) {
872
- return Object.freeze({ ...snapshot, [APP_BRANCH]: this.replayBranch });
870
+ const snapshot2 = this.snapshot();
871
+ if (this.replayBranch && !own(snapshot2, APP_BRANCH) && snapshot2[APP_COMMIT_SHA] === this.defaults[APP_COMMIT_SHA]) {
872
+ return Object.freeze({ ...snapshot2, [APP_BRANCH]: this.replayBranch });
873
873
  }
874
- return snapshot;
874
+ return snapshot2;
875
875
  }
876
876
  /** Merge a frozen span snapshot without losing client-authored provenance. */
877
877
  mergeSnapshot(base, properties, explicitKeys = this.explicitKeys) {
@@ -922,24 +922,24 @@ var AppGitContext = AppGitContextImpl;
922
922
  function createAppGitContext(options, runtime = {}) {
923
923
  return new AppGitContext(options, runtime);
924
924
  }
925
- function withAppGitProperties(properties, snapshot) {
925
+ function withAppGitProperties(properties, snapshot2) {
926
926
  try {
927
927
  const merged = { ...properties };
928
928
  for (const key of APP_GIT_KEYS)
929
- if (!own(merged, key) && own(snapshot, key)) merged[key] = snapshot[key];
929
+ if (!own(merged, key) && own(snapshot2, key)) merged[key] = snapshot2[key];
930
930
  return merged;
931
931
  } catch (e) {
932
932
  return properties != null ? properties : {};
933
933
  }
934
934
  }
935
- function withAppGitAttributes(attributes, snapshot) {
935
+ function withAppGitAttributes(attributes, snapshot2) {
936
936
  try {
937
937
  const present = new Set(attributes.flatMap((attr) => attr ? [attr.key] : []));
938
938
  const added = [];
939
939
  for (const key of APP_GIT_KEYS) {
940
940
  if (present.has(key) || present.has(`ai.telemetry.metadata.${key}`) || present.has(`traceloop.association.properties.${key}`))
941
941
  continue;
942
- const value = snapshot[key];
942
+ const value = snapshot2[key];
943
943
  if (typeof value === "string") added.push({ key, value: { stringValue: value } });
944
944
  else if (typeof value === "boolean") added.push({ key, value: { boolValue: value } });
945
945
  }
@@ -1532,7 +1532,7 @@ async function sendJson(url, body, headers, opts) {
1532
1532
  if (typeof retryAfterMs === "number") error.retryAfterMs = retryAfterMs;
1533
1533
  noteSendPause(url, resp.status, retryAfterMs);
1534
1534
  error.retryable = resp.status === 408 || resp.status === 429 || resp.status >= 500;
1535
- if (!error.retryable) return { status: "rejected", error };
1535
+ if (!error.retryable) return { status: "rejected", error, httpStatus: resp.status };
1536
1536
  lastError = error;
1537
1537
  logAttemptFailure(opts, prefix, opName, attempt, error);
1538
1538
  continue;
@@ -2753,6 +2753,7 @@ function needsLookup(local, remote, writeKey) {
2753
2753
  return local === void 0 && Boolean(remote) && Boolean(writeKey);
2754
2754
  }
2755
2755
  function piiRedactionNow(local, remote, endpoint, writeKey) {
2756
+ if (typeof writeKey === "function") return resolvePiiRedaction(local, remote, "unknown");
2756
2757
  if (!needsLookup(local, remote, writeKey)) return local === true;
2757
2758
  try {
2758
2759
  const answer = remotePiiAnswerNow(endpoint, writeKey);
@@ -2762,6 +2763,7 @@ function piiRedactionNow(local, remote, endpoint, writeKey) {
2762
2763
  }
2763
2764
  }
2764
2765
  async function piiRedaction(local, remote, endpoint, writeKey, deadlineAt) {
2766
+ if (typeof writeKey === "function") return resolvePiiRedaction(local, remote, "unknown");
2765
2767
  if (!needsLookup(local, remote, writeKey)) return local === true;
2766
2768
  try {
2767
2769
  return resolvePiiRedaction(local, remote, await remotePiiAnswer(endpoint, writeKey, deadlineAt));
@@ -2801,6 +2803,195 @@ function isMissingUserId(value) {
2801
2803
  const trimmed = value.trim();
2802
2804
  return trimmed === "" || PLACEHOLDER_USER_IDS.has(trimmed);
2803
2805
  }
2806
+ var WRITE_KEY_FUNCTION_TIMEOUT_MS = 1e4;
2807
+ function hasWriteKey(writeKey) {
2808
+ if (typeof writeKey === "function") return true;
2809
+ return typeof writeKey === "string" && writeKey.trim().length > 0;
2810
+ }
2811
+ var TIMED_OUT = /* @__PURE__ */ Symbol("timed out");
2812
+ var HEADER_SAFE = /^[\x21-\x7e]+$/;
2813
+ var ERROR_NAME = /^(?:[A-Z][A-Za-z]{0,39})?Error$/;
2814
+ var KNOWN_ERROR_CODES = /* @__PURE__ */ new Set([
2815
+ "ambiguous_resource",
2816
+ "forbidden",
2817
+ "invalid_resource",
2818
+ "invalid_role",
2819
+ "not_found",
2820
+ "request_failed",
2821
+ "resource_oidc_not_enabled",
2822
+ "ECONNREFUSED",
2823
+ "ECONNRESET",
2824
+ "ENOTFOUND",
2825
+ "ETIMEDOUT",
2826
+ "EAI_AGAIN"
2827
+ ]);
2828
+ function describeError(error) {
2829
+ try {
2830
+ if (typeof error !== "object" || error === null) return "a non-error value";
2831
+ const name = "name" in error ? error.name : void 0;
2832
+ const code = "code" in error ? error.code : void 0;
2833
+ const status = "status" in error ? error.status : void 0;
2834
+ const labels = [
2835
+ typeof name === "string" && ERROR_NAME.test(name) ? name : "an error",
2836
+ typeof code === "string" && KNOWN_ERROR_CODES.has(code) ? code : void 0,
2837
+ typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599 ? `(HTTP ${status})` : void 0
2838
+ ].filter((label) => label !== void 0);
2839
+ return labels.join(" ");
2840
+ } catch (e) {
2841
+ return "an error";
2842
+ }
2843
+ }
2844
+ async function callOnce(fn) {
2845
+ let timer;
2846
+ try {
2847
+ const value = await Promise.race([
2848
+ // SDK work, not the app's: keep the function's own requests out of host traces.
2849
+ Promise.resolve().then(() => runWithTracingSuppressed(fn)),
2850
+ // Unreferenced: the sends waiting on the call hold their own timers.
2851
+ new Promise((resolve2) => {
2852
+ var _a;
2853
+ timer = setTimeout(() => resolve2(TIMED_OUT), WRITE_KEY_FUNCTION_TIMEOUT_MS);
2854
+ (_a = timer.unref) == null ? void 0 : _a.call(timer);
2855
+ })
2856
+ ]);
2857
+ if (value === TIMED_OUT) {
2858
+ return { failure: `did not return within ${WRITE_KEY_FUNCTION_TIMEOUT_MS} ms` };
2859
+ }
2860
+ if (typeof value !== "string") return { failure: "returned a value that is not a string" };
2861
+ const key = value.trim();
2862
+ if (!key) return { failure: "returned an empty key" };
2863
+ if (!HEADER_SAFE.test(key)) {
2864
+ return { failure: "returned a key with characters an HTTP header cannot carry" };
2865
+ }
2866
+ return { key };
2867
+ } catch (error) {
2868
+ return { failure: `threw ${describeError(error)}` };
2869
+ } finally {
2870
+ clearTimeout(timer);
2871
+ }
2872
+ }
2873
+ var RUNNING_KEY = /* @__PURE__ */ Symbol.for("raindrop.writeKeyFunctionCalls.v1");
2874
+ function runningCalls() {
2875
+ var _a;
2876
+ const holder = globalThis;
2877
+ (_a = holder[RUNNING_KEY]) != null ? _a : holder[RUNNING_KEY] = /* @__PURE__ */ new WeakMap();
2878
+ return holder[RUNNING_KEY];
2879
+ }
2880
+ function callShared(fn) {
2881
+ const running = runningCalls();
2882
+ const current = running.get(fn);
2883
+ if (current) return current;
2884
+ const call = callOnce(fn);
2885
+ running.set(fn, call);
2886
+ void call.then(() => {
2887
+ if (running.get(fn) === call) running.delete(fn);
2888
+ });
2889
+ return call;
2890
+ }
2891
+ function waitUntil(promise, deadlineAt, cutOff) {
2892
+ const remaining = deadlineAt === void 0 ? Infinity : deadlineAt - Date.now();
2893
+ if (remaining <= 0 || (cutOff == null ? void 0 : cutOff.aborted)) return Promise.resolve(void 0);
2894
+ return new Promise((resolve2) => {
2895
+ let timer;
2896
+ const finish = (value) => {
2897
+ clearTimeout(timer);
2898
+ cutOff == null ? void 0 : cutOff.removeEventListener("abort", giveUp);
2899
+ resolve2(value);
2900
+ };
2901
+ const giveUp = () => finish(void 0);
2902
+ timer = setTimeout(giveUp, Math.min(remaining, WRITE_KEY_FUNCTION_TIMEOUT_MS + 1e3));
2903
+ cutOff == null ? void 0 : cutOff.addEventListener("abort", giveUp, { once: true });
2904
+ promise.then(finish, giveUp);
2905
+ });
2906
+ }
2907
+ var WriteKeySource = class {
2908
+ constructor(option, prefix) {
2909
+ this.prefix = prefix;
2910
+ if (typeof option === "function") this.fn = option;
2911
+ else if (typeof option === "string") this.staticKey = option.trim() || void 0;
2912
+ }
2913
+ /** Whether there is a key to send with. */
2914
+ get configured() {
2915
+ return this.fn !== void 0 || this.staticKey !== void 0;
2916
+ }
2917
+ /** The option as the org PII lookup (`piiRedaction`) takes it. */
2918
+ get lookupKey() {
2919
+ var _a;
2920
+ return (_a = this.fn) != null ? _a : this.staticKey;
2921
+ }
2922
+ /**
2923
+ * The key for one send. A failed call logs one rate-limited warning that
2924
+ * names the error but never its message. Never rejects.
2925
+ */
2926
+ async resolve(deadlineAt, cutOff) {
2927
+ if (this.staticKey !== void 0) return { status: "key", key: this.staticKey };
2928
+ const fn = this.fn;
2929
+ if (!fn) return { status: "failed" };
2930
+ if ((cutOff == null ? void 0 : cutOff.aborted) || deadlineAt !== void 0 && deadlineAt <= Date.now()) {
2931
+ return { status: "deferred" };
2932
+ }
2933
+ const result = await waitUntil(callShared(fn), deadlineAt, cutOff);
2934
+ if (result === void 0) return { status: "deferred" };
2935
+ if ("key" in result) return { status: "key", key: result.key };
2936
+ rateLimitedLog(
2937
+ `${this.prefix}.write_key_function_failed`,
2938
+ () => console.warn(
2939
+ `${this.prefix} writeKey function ${result.failure}; dropping this send (the next send calls it again)`
2940
+ )
2941
+ );
2942
+ return { status: "failed" };
2943
+ }
2944
+ };
2945
+ function prefixFor2(opts) {
2946
+ return opts.sdkName ? `[raindrop-ai/${opts.sdkName}]` : "[raindrop-ai/core]";
2947
+ }
2948
+ function snapshot(body) {
2949
+ try {
2950
+ const json = JSON.stringify(body);
2951
+ return json === void 0 ? body : JSON.parse(json);
2952
+ } catch (e) {
2953
+ return body;
2954
+ }
2955
+ }
2956
+ function sendJsonWithWriteKey(url, body, writeKey, headers, opts) {
2957
+ if (!writeKey.fn) {
2958
+ const auth = writeKey.staticKey ? { Authorization: `Bearer ${writeKey.staticKey}` } : {};
2959
+ return sendJson(url, body, { ...auth, ...headers }, opts);
2960
+ }
2961
+ return sendWithKeyFunction(url, body, writeKey, headers, opts);
2962
+ }
2963
+ async function sendWithKeyFunction(url, body, writeKey, headers, opts) {
2964
+ var _a;
2965
+ const payload = snapshot(body);
2966
+ const budgetEndsAt = opts.deadlineAt === void 0 && opts.timeoutMs !== void 0 ? Date.now() + opts.timeoutMs : void 0;
2967
+ const waitUntilAt = (_a = opts.deadlineAt) != null ? _a : budgetEndsAt;
2968
+ const sendOpts = () => budgetEndsAt === void 0 ? opts : { ...opts, timeoutMs: Math.max(1, budgetEndsAt - Date.now()) };
2969
+ const first = await writeKey.resolve(waitUntilAt, opts.cutOff);
2970
+ if (first.status === "deferred") return { status: "deferred" };
2971
+ if (first.status === "failed") {
2972
+ return {
2973
+ status: "failed",
2974
+ error: new Error("writeKey function did not return a key"),
2975
+ reported: true
2976
+ };
2977
+ }
2978
+ const outcome = await sendJson(
2979
+ url,
2980
+ payload,
2981
+ { Authorization: `Bearer ${first.key}`, ...headers },
2982
+ sendOpts()
2983
+ );
2984
+ if (outcome.status !== "rejected" || outcome.httpStatus !== 401 || opts.maxAttempts <= 1) {
2985
+ return outcome;
2986
+ }
2987
+ const fresh = await writeKey.resolve(waitUntilAt, opts.cutOff);
2988
+ if (fresh.status === "deferred") return { status: "deferred" };
2989
+ if (fresh.status !== "key" || fresh.key === first.key) return outcome;
2990
+ if (opts.debug) {
2991
+ console.log(`${prefixFor2(opts)} HTTP 401; resending with a new key from the writeKey function`);
2992
+ }
2993
+ return sendJson(url, payload, { Authorization: `Bearer ${fresh.key}`, ...headers }, sendOpts());
2994
+ }
2804
2995
  function snapshotPayload(payload) {
2805
2996
  try {
2806
2997
  const json = JSON.stringify(payload);
@@ -2914,22 +3105,23 @@ var EventShipper = class {
2914
3105
  this.finishedEventIds = /* @__PURE__ */ new Set();
2915
3106
  this.sendChains = /* @__PURE__ */ new Map();
2916
3107
  this.deferredSends = /* @__PURE__ */ new Set();
3108
+ this.keyDrops = 0;
2917
3109
  this.hasShutdown = false;
2918
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
3110
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
2919
3111
  this.appGitContext = (_a = opts.appGitContext) != null ? _a : createAppGitContext(opts.appGit);
2920
3112
  this.ownsAppGitContext = opts.appGitContext === void 0;
2921
- this.writeKey = (_b = opts.writeKey) == null ? void 0 : _b.trim();
2922
- this.baseUrl = (_c = formatEndpoint(opts.endpoint)) != null ? _c : "https://api.raindrop.ai/v1/";
3113
+ this.baseUrl = (_b = formatEndpoint(opts.endpoint)) != null ? _b : "https://api.raindrop.ai/v1/";
2923
3114
  this.enabled = opts.enabled !== false;
2924
3115
  this.debug = opts.debug;
2925
- this.partialFlushMs = (_d = opts.partialFlushMs) != null ? _d : 1e3;
2926
- this.sdkName = (_e = opts.sdkName) != null ? _e : "core";
3116
+ this.partialFlushMs = (_c = opts.partialFlushMs) != null ? _c : 1e3;
3117
+ this.sdkName = (_d = opts.sdkName) != null ? _d : "core";
2927
3118
  this.prefix = `[raindrop-ai/${this.sdkName}]`;
2928
- this.defaultEventName = (_f = opts.defaultEventName) != null ? _f : "ai_generation";
3119
+ this.writeKey = new WriteKeySource(opts.writeKey, this.prefix);
3120
+ this.defaultEventName = (_e = opts.defaultEventName) != null ? _e : "ai_generation";
2929
3121
  this.maxTextFieldCharsOpt = opts.maxTextFieldChars;
2930
3122
  this.flushTimeoutMs = resolveFlushTimeoutMs(opts.flushTimeoutMs);
2931
- this.localDebuggerUrl = (_g = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl)) != null ? _g : void 0;
2932
- this.localDebuggerFollowRedirects = (_h = opts.localDebuggerFollowRedirects) != null ? _h : true;
3123
+ this.localDebuggerUrl = (_f = resolveLocalDebuggerBaseUrl(opts.localDebuggerUrl)) != null ? _f : void 0;
3124
+ this.localDebuggerFollowRedirects = (_g = opts.localDebuggerFollowRedirects) != null ? _g : true;
2933
3125
  if (this.debug && this.localDebuggerUrl) {
2934
3126
  console.log(`${this.prefix} Local debugger mirroring: ${this.localDebuggerUrl}`);
2935
3127
  }
@@ -2958,8 +3150,8 @@ var EventShipper = class {
2958
3150
  const runtime = detectRuntime();
2959
3151
  this.context = {
2960
3152
  library: {
2961
- name: (_i = opts.libraryName) != null ? _i : "@raindrop-ai/core",
2962
- version: (_j = opts.libraryVersion) != null ? _j : "0.0.0"
3153
+ name: (_h = opts.libraryName) != null ? _h : "@raindrop-ai/core",
3154
+ version: (_i = opts.libraryVersion) != null ? _i : "0.0.0"
2963
3155
  },
2964
3156
  metadata: {
2965
3157
  jsRuntime: runtime,
@@ -2973,11 +3165,9 @@ var EventShipper = class {
2973
3165
  isDebugEnabled() {
2974
3166
  return this.debug;
2975
3167
  }
2976
- authHeaders() {
2977
- return this.writeKey ? { Authorization: `Bearer ${this.writeKey}` } : {};
2978
- }
2979
- requestHeaders() {
2980
- return { ...this.authHeaders(), ...projectIdHeaders(this.projectId) };
3168
+ /** POST to ingest with the write key (resolved for this send when it is a function). */
3169
+ post(url, body, opts) {
3170
+ return sendJsonWithWriteKey(url, body, this.writeKey, projectIdHeaders(this.projectId), opts);
2981
3171
  }
2982
3172
  /**
2983
3173
  * Retry/timeout options for one POST. While `shutdown()` drains, sends retry
@@ -3247,7 +3437,8 @@ var EventShipper = class {
3247
3437
  const ids = [...this.buffers.keys()];
3248
3438
  const fates = await Promise.all([
3249
3439
  ...ids.map((id) => this.flushOne(id, deadlineAt)),
3250
- ...deferred.map((entry) => entry.send(deadlineAt))
3440
+ // Counted here, so a key function failure in these is not counted again.
3441
+ ...deferred.map((entry) => entry.send(deadlineAt, true))
3251
3442
  ]);
3252
3443
  const background = [...this.background];
3253
3444
  if (background.length > 0) {
@@ -3261,6 +3452,7 @@ var EventShipper = class {
3261
3452
  this.cutOff,
3262
3453
  (p) => this.inFlight.has(p)
3263
3454
  );
3455
+ for (; this.keyDrops > 0; this.keyDrops -= 1) fates.push("dropped");
3264
3456
  const unresolved = background.filter((op) => this.background.has(op)).length;
3265
3457
  return summarize2(
3266
3458
  fates.filter((fate) => fate !== void 0),
@@ -3316,18 +3508,18 @@ var EventShipper = class {
3316
3508
  }
3317
3509
  }
3318
3510
  ];
3319
- const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
3511
+ const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey.lookupKey);
3320
3512
  if (known !== void 0) {
3321
3513
  const body = items.map((item) => this.outgoing("signal", item, known));
3322
- if (!this.writeKey) return;
3514
+ if (!this.writeKey.configured) return;
3323
3515
  await this.sendDirect("signal", `${this.baseUrl}signals/track`, body);
3324
3516
  return;
3325
3517
  }
3326
- const snapshot = items.map(snapshotPayload);
3518
+ const snapshot2 = items.map(snapshotPayload);
3327
3519
  await this.tracked(async () => {
3328
3520
  const redact = await this.shouldRedactPii();
3329
- const body = snapshot.map((item) => this.outgoing("signal", item, redact));
3330
- if (!this.writeKey) return;
3521
+ const body = snapshot2.map((item) => this.outgoing("signal", item, redact));
3522
+ if (!this.writeKey.configured) return;
3331
3523
  await this.sendDirect("signal", `${this.baseUrl}signals/track`, body, void 0, false);
3332
3524
  });
3333
3525
  }
@@ -3351,33 +3543,35 @@ var EventShipper = class {
3351
3543
  traits: (_a = user.traits) != null ? _a : {}
3352
3544
  };
3353
3545
  });
3354
- if (!this.writeKey) return;
3546
+ if (!this.writeKey.configured) return;
3355
3547
  if (rows.length === 0) return;
3356
- const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
3548
+ const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey.lookupKey);
3357
3549
  if (known !== void 0) {
3358
3550
  const body = rows.map((user) => this.outgoing("identify", user, known));
3359
3551
  await this.sendDirect("identify", `${this.baseUrl}users/identify`, body);
3360
3552
  return;
3361
3553
  }
3362
- const snapshot = rows.map(snapshotPayload);
3554
+ const snapshot2 = rows.map(snapshotPayload);
3363
3555
  await this.tracked(async () => {
3364
3556
  const redact = await this.shouldRedactPii();
3365
- const body = snapshot.map((user) => this.outgoing("identify", user, redact));
3557
+ const body = snapshot2.map((user) => this.outgoing("identify", user, redact));
3366
3558
  await this.sendDirect("identify", `${this.baseUrl}users/identify`, body, void 0, false);
3367
3559
  });
3368
3560
  }
3369
3561
  /**
3370
3562
  * Send a signal or identify body. Tracked so `flush()` waits for it, unless
3371
3563
  * the caller already tracks it (`track: false`). A send a flush deadline
3372
- * deferred is kept and retried later (outside shutdown).
3564
+ * deferred is kept and retried later (outside shutdown). `counted`: the
3565
+ * caller counts the returned fate (a flush draining deferred sends).
3373
3566
  */
3374
- async sendDirect(kind, url, body, deadlineAt, track = true) {
3567
+ async sendDirect(kind, url, body, deadlineAt, track = true, counted = false) {
3375
3568
  const opts = this.requestOpts(deadlineAt);
3376
3569
  if (!opts) {
3377
3570
  this.warnShutdownDrop(kind);
3378
3571
  return "dropped";
3379
3572
  }
3380
- const sending = sendJson(url, body, this.requestHeaders(), opts);
3573
+ const payload = this.writeKey.fn ? snapshotPayload(body) : body;
3574
+ const sending = this.post(url, payload, opts);
3381
3575
  const tracked = sending.then(() => void 0);
3382
3576
  if (track) this.inFlight.add(tracked);
3383
3577
  let outcome;
@@ -3389,11 +3583,12 @@ var EventShipper = class {
3389
3583
  const fate = fateOf(outcome, this.shuttingDown());
3390
3584
  if (fate === "queued") {
3391
3585
  this.deferSend(
3392
- (later) => this.sendDirect(kind, url, body, later),
3586
+ (later, laterCounted) => this.sendDirect(kind, url, payload, later, true, laterCounted),
3393
3587
  outcome.status === "deferred" ? outcome.retryAtMs : void 0
3394
3588
  );
3395
3589
  } else if (fate === "dropped") {
3396
3590
  this.warnSendDropped(kind, outcome);
3591
+ if (!counted && outcome.status === "failed" && outcome.reported) this.keyDrops += 1;
3397
3592
  }
3398
3593
  return fate;
3399
3594
  }
@@ -3419,6 +3614,7 @@ var EventShipper = class {
3419
3614
  warnSendDropped(what, outcome) {
3420
3615
  var _a, _b;
3421
3616
  if (outcome.status === "delivered" || outcome.status === "rejected") return;
3617
+ if (outcome.status === "failed" && outcome.reported) return;
3422
3618
  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;
3423
3619
  rateLimitedLog(
3424
3620
  `${this.prefix}.send_${what}_dropped`,
@@ -3441,7 +3637,7 @@ var EventShipper = class {
3441
3637
  this.redactPii,
3442
3638
  this.remotePiiConfig,
3443
3639
  this.baseUrl,
3444
- this.writeKey,
3640
+ this.writeKey.lookupKey,
3445
3641
  deadlineAt != null ? deadlineAt : this.shutdownDeadlineAt
3446
3642
  );
3447
3643
  }
@@ -3581,17 +3777,17 @@ var EventShipper = class {
3581
3777
  attachments: accumulated.attachments,
3582
3778
  is_pending: isPending
3583
3779
  };
3584
- const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey);
3780
+ const known = piiRedactionNow(this.redactPii, this.remotePiiConfig, this.baseUrl, this.writeKey.lookupKey);
3585
3781
  if (known !== void 0) {
3586
3782
  const payload = this.outgoing("event", unredacted, known);
3587
3783
  return this.shipPartial(eventId, accumulated, payload, { eventName, userId, convoId, isPending }, deadlineAt, true);
3588
3784
  }
3589
- const snapshot = snapshotPayload(unredacted);
3785
+ const snapshot2 = snapshotPayload(unredacted);
3590
3786
  const running = this.shouldRedactPii(deadlineAt).then(
3591
3787
  (redact) => this.shipPartial(
3592
3788
  eventId,
3593
3789
  accumulated,
3594
- this.outgoing("event", snapshot, redact),
3790
+ this.outgoing("event", snapshot2, redact),
3595
3791
  { eventName, userId, convoId, isPending },
3596
3792
  deadlineAt,
3597
3793
  false
@@ -3651,11 +3847,12 @@ var EventShipper = class {
3651
3847
  const mirror = this.localDebuggerUrl ? mirrorPartialEventToLocalDebugger(payload, {
3652
3848
  baseUrl: this.localDebuggerUrl,
3653
3849
  followRedirects: this.localDebuggerFollowRedirects,
3654
- writeKey: this.writeKey,
3850
+ // A key function's tokens are for ingest; the local mirror needs none.
3851
+ writeKey: this.writeKey.staticKey,
3655
3852
  debug: this.debug,
3656
3853
  sdkName: this.sdkName
3657
3854
  }) : void 0;
3658
- if (!this.writeKey) {
3855
+ if (!this.writeKey.configured) {
3659
3856
  if (!isPending) this.sticky.delete(eventId);
3660
3857
  if (mirror) await mirror;
3661
3858
  return void 0;
@@ -3667,7 +3864,7 @@ var EventShipper = class {
3667
3864
  if (mirror) await mirror;
3668
3865
  return "dropped";
3669
3866
  }
3670
- const sending = sendJson(url, payload, this.requestHeaders(), opts);
3867
+ const sending = this.post(url, payload, opts);
3671
3868
  const combined = Promise.all([mirror, sending.then(() => void 0)]).then(() => void 0);
3672
3869
  if (track) this.inFlight.add(combined);
3673
3870
  let outcome;
@@ -4160,9 +4357,8 @@ function createAppGitContext2(options, runtime = {}) {
4160
4357
  return new AppGitContext(options, { ...runtime, resolveLocal });
4161
4358
  }
4162
4359
  function hasDestination(options) {
4163
- var _a;
4164
4360
  if (options.enabled === false) return false;
4165
- return Boolean(((_a = options.writeKey) == null ? void 0 : _a.trim()) || resolveLocalDebuggerBaseUrl(options.localDebuggerUrl));
4361
+ return hasWriteKey(options.writeKey) || Boolean(resolveLocalDebuggerBaseUrl(options.localDebuggerUrl));
4166
4362
  }
4167
4363
  var EventShipper2 = class extends EventShipper {
4168
4364
  constructor(options) {
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  runWithTracingSuppressed
3
- } from "./chunk-CSH7U5JZ.mjs";
3
+ } from "./chunk-HKOAIPQF.mjs";
4
4
 
5
5
  // src/evals/generated/trace.ts
6
6
  import z from "zod/v4";
@@ -1842,7 +1842,7 @@ async function evaluatePortableEvaluator(evaluator, input) {
1842
1842
  if (new Set(input.traces.map((trace) => trace.event.id)).size !== input.traces.length) {
1843
1843
  throw new Error("Raindrop portable evaluator input trace ids must be unique");
1844
1844
  }
1845
- const { runPortableEvaluator } = await import("./portable-runtime-G27RYK6P.mjs");
1845
+ const { runPortableEvaluator } = await import("./portable-runtime-HVIGFQHE.mjs");
1846
1846
  const rows = (_a = input.rows) != null ? _a : [];
1847
1847
  if (rows.length > 0 && (rows.length !== input.traces.length || rows.some(
1848
1848
  (entry, index) => {
@@ -79,7 +79,7 @@ import {
79
79
  withAppGitProperties,
80
80
  withMetadataPrefix,
81
81
  withRoutingContext
82
- } from "./chunk-CSH7U5JZ.mjs";
82
+ } from "./chunk-HKOAIPQF.mjs";
83
83
 
84
84
  // src/lib/inject-als.ts
85
85
  import { AsyncLocalStorage } from "async_hooks";
@@ -90,7 +90,7 @@ if (!globalThis.RAINDROP_ASYNC_LOCAL_STORAGE) {
90
90
  // package.json
91
91
  var package_default = {
92
92
  name: "raindrop-ai",
93
- version: "3.0.0",
93
+ version: "3.0.1",
94
94
  main: "dist/index.js",
95
95
  module: "dist/index.mjs",
96
96
  types: "dist/index.d.ts",
@@ -3,7 +3,7 @@ import {
3
3
  package_default,
4
4
  tracing,
5
5
  withTask
6
- } from "./chunk-24GTHPYP.mjs";
6
+ } from "./chunk-RSUQ3BU2.mjs";
7
7
  import {
8
8
  DatasetRowSchema,
9
9
  EvalRowTracePairSchema,
@@ -23,7 +23,7 @@ import {
23
23
  traceOutput,
24
24
  traceToolCalls,
25
25
  validateEvaluatorOutput
26
- } from "./chunk-BU322D7Q.mjs";
26
+ } from "./chunk-Q2I2277O.mjs";
27
27
  import {
28
28
  APP_BRANCH,
29
29
  APP_COMMIT_DIRTY,
@@ -71,7 +71,7 @@ import {
71
71
  withEvalScope,
72
72
  withReplayTraceDestination,
73
73
  withRoutingContext
74
- } from "./chunk-CSH7U5JZ.mjs";
74
+ } from "./chunk-HKOAIPQF.mjs";
75
75
 
76
76
  // ../schemas/dist/chunk-IIYWNKAG.js
77
77
  var __defProp = Object.defineProperty;