raindrop-ai 1.0.7 → 1.0.8

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.
@@ -130,7 +130,7 @@ function evalScopeAttributes() {
130
130
  return { [EVAL_CORRELATION_ID_ATTRIBUTE]: scope.correlationId };
131
131
  }
132
132
 
133
- // ../core/dist/chunk-AX36JKJL.js
133
+ // ../core/dist/chunk-R5EQZAA5.js
134
134
  var require_NameRedactor = __commonJS({
135
135
  "../redact-pii/dist/built-ins/NameRedactor.js"(exports2) {
136
136
  Object.defineProperty(exports2, "__esModule", { value: true });
@@ -761,9 +761,9 @@ var SUBAGENT_ABORT_OPERATION_ID = "ai.subagent.failed";
761
761
  var SUBAGENT_ABORT_SPAN_NAME = SUBAGENT_ABORT_OPERATION_ID;
762
762
  var DEFAULT_DISPATCH_SPAN_NAME = "launch_subagent";
763
763
  var HANDOFF_TERMINAL_PROPERTY_KEY = HANDOFF_ATTRIBUTE_SUFFIXES.terminal;
764
- function defined(entries) {
764
+ function defined(entries2) {
765
765
  const out = {};
766
- for (const [key, value] of Object.entries(entries)) {
766
+ for (const [key, value] of Object.entries(entries2)) {
767
767
  if (typeof value === "string" && value.trim().length > 0) out[key] = value;
768
768
  }
769
769
  return out;
@@ -837,8 +837,8 @@ function warnNonConformantIdsOnce(traceId, spanId) {
837
837
  var HANDOFF_HEADER = "x-raindrop-handoff";
838
838
  var LANGSMITH_TRACE_HEADER = "langsmith-trace";
839
839
  var LANGSMITH_METADATA_BAGGAGE_KEY = "langsmith-metadata";
840
- function encodeBaggage(entries) {
841
- return Object.entries(entries).filter((entry) => Boolean(entry[1])).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join(",");
840
+ function encodeBaggage(entries2) {
841
+ return Object.entries(entries2).filter((entry) => Boolean(entry[1])).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join(",");
842
842
  }
843
843
  function decodeBaggage(header) {
844
844
  if (!header) return {};
@@ -1265,7 +1265,7 @@ async function sendJson(url, body, headers, opts) {
1265
1265
  resp = await runWithTracingSuppressed(
1266
1266
  () => fetch(url, {
1267
1267
  method: "POST",
1268
- redirect: headers["X-Raindrop-Replay-Id"] !== void 0 ? "error" : "follow",
1268
+ redirect: headers["X-Raindrop-Replay-Id"] !== void 0 || opts.followRedirects === false ? "error" : "follow",
1269
1269
  headers: {
1270
1270
  "Content-Type": "application/json",
1271
1271
  ...headers
@@ -1542,7 +1542,8 @@ function mirrorTraceExportToLocalDebugger(body, options = {}) {
1542
1542
  maxAttempts: 1,
1543
1543
  debug: (_a = options.debug) != null ? _a : false,
1544
1544
  sdkName: options.sdkName,
1545
- timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS
1545
+ timeoutMs: LOCAL_DEBUGGER_MIRROR_TIMEOUT_MS,
1546
+ followRedirects: options.followRedirects
1546
1547
  }).catch(() => {
1547
1548
  });
1548
1549
  }
@@ -1563,7 +1564,8 @@ function sendLocalDebuggerLiveEvent(event, options = {}) {
1563
1564
  {
1564
1565
  maxAttempts: 1,
1565
1566
  debug: (_b = options.debug) != null ? _b : false,
1566
- sdkName: options.sdkName
1567
+ sdkName: options.sdkName,
1568
+ followRedirects: options.followRedirects
1567
1569
  }
1568
1570
  ).catch(() => {
1569
1571
  });
@@ -1573,6 +1575,30 @@ function projectIdHeaders(projectId) {
1573
1575
  return projectId ? { [PROJECT_ID_HEADER]: projectId } : {};
1574
1576
  }
1575
1577
  var import_redact_pii = __toESM2(require_dist(), 1);
1578
+ var DEFAULT_PII_REDACTION_OPTIONS = {
1579
+ builtInRedactors: {
1580
+ credentials: { replaceWith: "<REDACTED CREDENTIALS>" },
1581
+ creditCardNumber: { replaceWith: "<REDACTED CREDIT CARD NUMBER>" },
1582
+ // Any run of 4+ digits: too broad.
1583
+ digits: { enabled: false },
1584
+ emailAddress: { replaceWith: "<REDACTED EMAIL>" },
1585
+ ipAddress: { enabled: false },
1586
+ names: { enabled: false },
1587
+ // Matches (pass(word|phrase)|secret): \S+
1588
+ password: { replaceWith: "<REDACTED SECRET>" },
1589
+ phoneNumber: { replaceWith: "<REDACTED PHONE NUMBER>" },
1590
+ streetAddress: { replaceWith: "<REDACTED ADDRESS>" },
1591
+ url: { enabled: false },
1592
+ username: { enabled: false },
1593
+ usSocialSecurityNumber: { replaceWith: "<REDACTED SOCIAL SECURITY NUMBER>" },
1594
+ zipcode: { enabled: false }
1595
+ }
1596
+ };
1597
+ var redactor;
1598
+ function redactPiiText(text) {
1599
+ redactor != null ? redactor : redactor = new import_redact_pii.SyncRedactor(DEFAULT_PII_REDACTION_OPTIONS);
1600
+ return redactor.redact(text);
1601
+ }
1576
1602
  var PROTECTED_LOCATIONS = new Set(
1577
1603
  [
1578
1604
  ["event_id"],
@@ -1585,6 +1611,143 @@ var PROTECTED_LOCATIONS = new Set(
1585
1611
  ["signal_type"]
1586
1612
  ].map((keys) => JSON.stringify(keys))
1587
1613
  );
1614
+ var REMOTE_PII_LOOKUP_TIMEOUT_MS = 3e3;
1615
+ var REFRESH_AFTER_MS = 5 * 6e4;
1616
+ var RETRY_AFTER_MS = 3e4;
1617
+ var STATE_KEY2 = /* @__PURE__ */ Symbol.for("raindrop.remotePiiConfig");
1618
+ function entries() {
1619
+ const holder = globalThis;
1620
+ let current = holder[STATE_KEY2];
1621
+ if (!current) {
1622
+ current = /* @__PURE__ */ new Map();
1623
+ holder[STATE_KEY2] = current;
1624
+ }
1625
+ return current;
1626
+ }
1627
+ function isRecord2(value) {
1628
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1629
+ }
1630
+ function baseUrlOf(endpoint) {
1631
+ return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
1632
+ }
1633
+ function cacheKey(endpoint, writeKey) {
1634
+ return `${baseUrlOf(endpoint)}
1635
+ ${writeKey}`;
1636
+ }
1637
+ function parseAnswer(body) {
1638
+ if (!isRecord2(body)) return "unknown";
1639
+ if (!("pii" in body)) return "not_enrolled";
1640
+ const pii = body.pii;
1641
+ if (!isRecord2(pii)) return "unknown";
1642
+ return pii.redact === "on" || pii.redact === "off" ? pii.redact : "unknown";
1643
+ }
1644
+ async function lookup(baseUrl, writeKey) {
1645
+ if (typeof fetch !== "function") return void 0;
1646
+ const controller = typeof AbortController === "function" ? new AbortController() : void 0;
1647
+ const timer = setTimeout(() => controller == null ? void 0 : controller.abort(), REMOTE_PII_LOOKUP_TIMEOUT_MS);
1648
+ if (typeof timer === "object" && "unref" in timer) timer.unref();
1649
+ try {
1650
+ const response = await runWithTracingSuppressed(
1651
+ () => fetch(`${baseUrl}auth`, {
1652
+ method: "POST",
1653
+ headers: { Authorization: `Bearer ${writeKey}`, "Content-Type": "application/json" },
1654
+ body: "{}",
1655
+ signal: controller == null ? void 0 : controller.signal
1656
+ })
1657
+ );
1658
+ if (!response.ok) return void 0;
1659
+ const body = await response.json();
1660
+ return parseAnswer(body);
1661
+ } catch (e) {
1662
+ return void 0;
1663
+ } finally {
1664
+ clearTimeout(timer);
1665
+ }
1666
+ }
1667
+ function entryFor(endpoint, writeKey) {
1668
+ const key = cacheKey(endpoint, writeKey);
1669
+ const all = entries();
1670
+ let entry = all.get(key);
1671
+ if (!entry) {
1672
+ entry = { known: void 0, pending: void 0, nextLookupAt: 0, settled: false };
1673
+ all.set(key, entry);
1674
+ }
1675
+ if (!entry.pending && Date.now() >= entry.nextLookupAt) {
1676
+ const current = entry;
1677
+ current.pending = lookup(baseUrlOf(endpoint), writeKey).then((answer) => {
1678
+ if (answer !== void 0) current.known = answer;
1679
+ current.nextLookupAt = Date.now() + (answer === void 0 ? RETRY_AFTER_MS : REFRESH_AFTER_MS);
1680
+ current.pending = void 0;
1681
+ current.settled = true;
1682
+ });
1683
+ }
1684
+ return entry;
1685
+ }
1686
+ function remotePiiAnswerNow(endpoint, writeKey) {
1687
+ const entry = entryFor(endpoint, writeKey);
1688
+ if (entry.known !== void 0) return entry.known;
1689
+ return entry.settled ? "unknown" : void 0;
1690
+ }
1691
+ async function remotePiiAnswer(endpoint, writeKey, deadlineAt) {
1692
+ var _a;
1693
+ const entry = entryFor(endpoint, writeKey);
1694
+ const now = remotePiiAnswerNow(endpoint, writeKey);
1695
+ if (now !== void 0 || !entry.pending) return now != null ? now : "unknown";
1696
+ const waitMs = Math.min(
1697
+ REMOTE_PII_LOOKUP_TIMEOUT_MS,
1698
+ deadlineAt === void 0 ? Infinity : Math.max(0, deadlineAt - Date.now())
1699
+ );
1700
+ let timer;
1701
+ await Promise.race([
1702
+ entry.pending,
1703
+ new Promise((resolve) => {
1704
+ timer = setTimeout(resolve, waitMs);
1705
+ })
1706
+ ]);
1707
+ clearTimeout(timer);
1708
+ return (_a = entry.known) != null ? _a : "unknown";
1709
+ }
1710
+ function resolvePiiRedaction(local, remote, answer) {
1711
+ if (local !== void 0) return local;
1712
+ if (!remote) return false;
1713
+ if (answer === "on") return true;
1714
+ if (answer === "off" || answer === "not_enrolled") return false;
1715
+ const whenUnknown = typeof remote === "object" ? remote.whenUnknown : void 0;
1716
+ return whenUnknown !== "local";
1717
+ }
1718
+ function needsLookup(local, remote, writeKey) {
1719
+ return local === void 0 && Boolean(remote) && Boolean(writeKey);
1720
+ }
1721
+ function piiRedactionNow(local, remote, endpoint, writeKey) {
1722
+ if (!needsLookup(local, remote, writeKey)) return local === true;
1723
+ try {
1724
+ const answer = remotePiiAnswerNow(endpoint, writeKey);
1725
+ return answer === void 0 ? void 0 : resolvePiiRedaction(local, remote, answer);
1726
+ } catch (e) {
1727
+ return resolvePiiRedaction(local, remote, "unknown");
1728
+ }
1729
+ }
1730
+ async function piiRedaction(local, remote, endpoint, writeKey, deadlineAt) {
1731
+ if (!needsLookup(local, remote, writeKey)) return local === true;
1732
+ try {
1733
+ return resolvePiiRedaction(local, remote, await remotePiiAnswer(endpoint, writeKey, deadlineAt));
1734
+ } catch (e) {
1735
+ return resolvePiiRedaction(local, remote, "unknown");
1736
+ }
1737
+ }
1738
+ var LOCAL_TRACE_KEY = /* @__PURE__ */ Symbol.for("raindrop.localTracePiiRedaction");
1739
+ function localTraceKeys() {
1740
+ var _a;
1741
+ const holder = globalThis;
1742
+ (_a = holder[LOCAL_TRACE_KEY]) != null ? _a : holder[LOCAL_TRACE_KEY] = /* @__PURE__ */ new Set();
1743
+ return holder[LOCAL_TRACE_KEY];
1744
+ }
1745
+ function requestLocalTracePiiRedaction(endpoint, writeKey) {
1746
+ localTraceKeys().add(cacheKey(endpoint, writeKey != null ? writeKey : ""));
1747
+ }
1748
+ function localTracePiiRedactionRequested(endpoint, writeKey) {
1749
+ return localTraceKeys().has(cacheKey(endpoint, writeKey != null ? writeKey : ""));
1750
+ }
1588
1751
  var POST_SHUTDOWN_TIMEOUT_MS = 5e3;
1589
1752
  function resolveFlushTimeoutMs(value) {
1590
1753
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : DEFAULT_FLUSH_TIMEOUT_MS;
@@ -1738,6 +1901,211 @@ var DEFAULT_REDACT_ATTRIBUTE_KEYS = [
1738
1901
  "ai.response.providerMetadata"
1739
1902
  ];
1740
1903
  var REDACT_JSON_ATTRIBUTE_KEYS = new Set(DEFAULT_REDACT_ATTRIBUTE_KEYS);
1904
+ var CONTENT_KEY_SUFFIX = /(^|\.)(input|output|inputs|outputs|args|arguments|result|results|content|text|messages|prompt|completion|instructions|system_instructions|reasoning|reasoningText|thinking|toolCalls|tool_calls|object|value|values|intent|query|tool_input)$/;
1905
+ var CONTENT_KEYS = /* @__PURE__ */ new Set([
1906
+ "ai.prompt.system",
1907
+ "ai.subagent.result",
1908
+ "agent.session.title",
1909
+ // Failed tool calls carry the tool's output in their error text.
1910
+ "error.message",
1911
+ "exception.message",
1912
+ "exception.stacktrace"
1913
+ ]);
1914
+ var NON_CONTENT_PREFIXES = [
1915
+ "traceloop.association.properties.",
1916
+ "ai.telemetry.metadata.",
1917
+ "ai.settings.context.",
1918
+ "raindrop.app."
1919
+ ];
1920
+ var JSON_SIMPLE_ESCAPES = {
1921
+ '"': '"',
1922
+ "\\": "\\",
1923
+ "/": "/",
1924
+ b: "\b",
1925
+ f: "\f",
1926
+ n: "\n",
1927
+ r: "\r",
1928
+ t: " "
1929
+ };
1930
+ function decodeJsonEscapes(text) {
1931
+ if (!text.includes("\\")) return text;
1932
+ let out = "";
1933
+ for (let i = 0; i < text.length; i++) {
1934
+ const ch = text[i];
1935
+ if (ch !== "\\" || i + 1 >= text.length) {
1936
+ out += ch;
1937
+ continue;
1938
+ }
1939
+ const next = text[i + 1];
1940
+ const simple = JSON_SIMPLE_ESCAPES[next];
1941
+ if (simple !== void 0) {
1942
+ out += simple;
1943
+ i += 1;
1944
+ } else if (next === "u" && /^[0-9a-fA-F]{4}$/.test(text.slice(i + 2, i + 6))) {
1945
+ out += String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16));
1946
+ i += 5;
1947
+ } else {
1948
+ out += ch;
1949
+ }
1950
+ }
1951
+ return out;
1952
+ }
1953
+ function jsonStringBody(value) {
1954
+ return JSON.stringify(value).slice(1, -1);
1955
+ }
1956
+ function redactStringToken(token) {
1957
+ const decoded = decodeJsonEscapes(token.slice(1, -1));
1958
+ const redacted = redactPiiText(decoded);
1959
+ return redacted === decoded ? token : `"${jsonStringBody(redacted)}"`;
1960
+ }
1961
+ function redactLooseJsonText(text) {
1962
+ if (text.startsWith('"')) {
1963
+ const decoded2 = decodeJsonEscapes(text.slice(1));
1964
+ const redacted2 = redactPiiText(decoded2);
1965
+ return redacted2 === decoded2 ? text : `"${jsonStringBody(redacted2)}`;
1966
+ }
1967
+ const decoded = decodeJsonEscapes(text);
1968
+ const redacted = redactPiiText(decoded);
1969
+ return redacted === decoded ? text : redacted;
1970
+ }
1971
+ function stringTokenEnd(text, start) {
1972
+ for (let i = start + 1; i < text.length; i++) {
1973
+ const ch = text[i];
1974
+ if (ch === "\\") i += 1;
1975
+ else if (ch === '"') return i + 1;
1976
+ }
1977
+ return -1;
1978
+ }
1979
+ function redactJsonLike(text, complete) {
1980
+ let out = "";
1981
+ let looseStart = 0;
1982
+ const flushLoose = (end) => {
1983
+ if (end > looseStart) {
1984
+ const loose = text.slice(looseStart, end);
1985
+ out += complete ? loose : redactLooseJsonText(loose);
1986
+ }
1987
+ };
1988
+ let i = text.indexOf('"');
1989
+ while (i !== -1) {
1990
+ const end = stringTokenEnd(text, i);
1991
+ if (end === -1) break;
1992
+ flushLoose(i);
1993
+ let after = end;
1994
+ while (after < text.length && /\s/.test(text[after])) after += 1;
1995
+ const token = text.slice(i, end);
1996
+ out += complete && text[after] === ":" ? token : redactStringToken(token);
1997
+ looseStart = end;
1998
+ i = text.indexOf('"', end);
1999
+ }
2000
+ if (i === -1) {
2001
+ flushLoose(text.length);
2002
+ } else {
2003
+ flushLoose(i);
2004
+ looseStart = i;
2005
+ flushLoose(text.length);
2006
+ }
2007
+ return out;
2008
+ }
2009
+ function redactSpanContent(text) {
2010
+ const head = text.trimStart()[0];
2011
+ if (head !== "{" && head !== "[" && head !== '"') return redactPiiText(text);
2012
+ let complete = true;
2013
+ try {
2014
+ JSON.parse(text);
2015
+ } catch (e) {
2016
+ complete = false;
2017
+ }
2018
+ return redactJsonLike(text, complete);
2019
+ }
2020
+ var NO_SPAN_PII_FIELDS = { exact: /* @__PURE__ */ new Set(), prefixes: [] };
2021
+ function compileSpanPiiFields(names, logPrefix = "[raindrop-ai/core]") {
2022
+ if (!Array.isArray(names) || names.length === 0) return NO_SPAN_PII_FIELDS;
2023
+ const exact = /* @__PURE__ */ new Set();
2024
+ const prefixes = [];
2025
+ for (const name of names) {
2026
+ const valid = typeof name === "string" && !/\s/.test(name) && /^[^*]+\*?$/.test(name);
2027
+ if (!valid) {
2028
+ rateLimitedLog(
2029
+ `${logPrefix}.pii_span_field_invalid`,
2030
+ () => console.warn(
2031
+ `${logPrefix} redactPiiFields: ignoring invalid span attribute ${JSON.stringify(name)}`
2032
+ )
2033
+ );
2034
+ continue;
2035
+ }
2036
+ if (name.endsWith("*")) prefixes.push(name.slice(0, -1));
2037
+ else exact.add(name);
2038
+ }
2039
+ return { exact, prefixes };
2040
+ }
2041
+ function isCallerSelected(key, fields) {
2042
+ return fields.exact.has(key) || fields.prefixes.some((prefix) => key.startsWith(prefix));
2043
+ }
2044
+ function isSpanContentAttributeKey(key, fields = NO_SPAN_PII_FIELDS) {
2045
+ if (isCallerSelected(key, fields)) return true;
2046
+ if (NON_CONTENT_PREFIXES.some((prefix) => key.startsWith(prefix))) return false;
2047
+ return CONTENT_KEYS.has(key) || CONTENT_KEY_SUFFIX.test(key);
2048
+ }
2049
+ function redactOtlpValue(value) {
2050
+ var _a;
2051
+ if (typeof value.stringValue === "string") {
2052
+ const redacted = redactSpanContent(value.stringValue);
2053
+ return redacted === value.stringValue ? value : { ...value, stringValue: redacted };
2054
+ }
2055
+ const values = (_a = value.arrayValue) == null ? void 0 : _a.values;
2056
+ if (!values) return value;
2057
+ let changed = false;
2058
+ const next = values.map((item) => {
2059
+ const redacted = redactOtlpValue(item);
2060
+ if (redacted !== item) changed = true;
2061
+ return redacted;
2062
+ });
2063
+ return changed ? { ...value, arrayValue: { values: next } } : value;
2064
+ }
2065
+ function redactPiiInOtlpAttributes(attributes, fields = NO_SPAN_PII_FIELDS) {
2066
+ let next;
2067
+ for (let i = 0; i < attributes.length; i++) {
2068
+ const attr = attributes[i];
2069
+ if (!attr.value || !isSpanContentAttributeKey(attr.key, fields)) continue;
2070
+ const value = redactOtlpValue(attr.value);
2071
+ if (value === attr.value) continue;
2072
+ next != null ? next : next = attributes.slice();
2073
+ next[i] = { ...attr, value };
2074
+ }
2075
+ return next != null ? next : attributes;
2076
+ }
2077
+ function redactPiiInOtlpSpan(span, fields = NO_SPAN_PII_FIELDS) {
2078
+ var _a;
2079
+ const attributes = span.attributes && redactPiiInOtlpAttributes(span.attributes, fields);
2080
+ const message = (_a = span.status) == null ? void 0 : _a.message;
2081
+ const redactedMessage = message === void 0 ? void 0 : redactSpanContent(message);
2082
+ if (attributes === span.attributes && redactedMessage === message) return span;
2083
+ const status = span.status && redactedMessage !== message ? { ...span.status, message: redactedMessage } : span.status;
2084
+ return { ...span, attributes, status };
2085
+ }
2086
+ function redactPiiInAttributeMap(attributes, fields = NO_SPAN_PII_FIELDS) {
2087
+ let next;
2088
+ for (const [key, value] of Object.entries(attributes)) {
2089
+ if (!isSpanContentAttributeKey(key, fields)) continue;
2090
+ let redacted = value;
2091
+ if (typeof value === "string") {
2092
+ redacted = redactSpanContent(value);
2093
+ } else if (Array.isArray(value)) {
2094
+ let changed = false;
2095
+ const items = value.map((item) => {
2096
+ if (typeof item !== "string") return item;
2097
+ const out = redactSpanContent(item);
2098
+ if (out !== item) changed = true;
2099
+ return out;
2100
+ });
2101
+ if (changed) redacted = items;
2102
+ }
2103
+ if (redacted === value) continue;
2104
+ next != null ? next : next = { ...attributes };
2105
+ next[key] = redacted;
2106
+ }
2107
+ return next;
2108
+ }
1741
2109
  var UNDELIVERED = Object.freeze({
1742
2110
  delivered: false,
1743
2111
  timedOut: false,
@@ -1746,7 +2114,7 @@ var UNDELIVERED = Object.freeze({
1746
2114
  inFlight: 0
1747
2115
  });
1748
2116
  var PROMPT_TOOLS_ATTRIBUTE = "ai.prompt.tools";
1749
- function isRecord3(value) {
2117
+ function isRecord4(value) {
1750
2118
  return typeof value === "object" && value !== null && !Array.isArray(value);
1751
2119
  }
1752
2120
  var JSON_SCHEMA_KEYS = [
@@ -1764,17 +2132,17 @@ var JSON_SCHEMA_KEYS = [
1764
2132
  "required"
1765
2133
  ];
1766
2134
  function isJsonSchema(value) {
1767
- if (!isRecord3(value)) return false;
2135
+ if (!isRecord4(value)) return false;
1768
2136
  if (typeof value["~standard"] === "object") return false;
1769
- if (isRecord3(value._def) || isRecord3(value._zod)) return false;
2137
+ if (isRecord4(value._def) || isRecord4(value._zod)) return false;
1770
2138
  if (Object.keys(value).length === 0) return true;
1771
2139
  return JSON_SCHEMA_KEYS.some((key) => key in value);
1772
2140
  }
1773
2141
  function toJsonSchema(value, options) {
1774
2142
  if (value === void 0 || value === null) return void 0;
1775
2143
  if (isJsonSchema(value)) return value;
1776
- if (isRecord3(value) && isJsonSchema(value.jsonSchema)) return value.jsonSchema;
1777
- if (isRecord3(value) && isJsonSchema(value.json)) return value.json;
2144
+ if (isRecord4(value) && isJsonSchema(value.jsonSchema)) return value.jsonSchema;
2145
+ if (isRecord4(value) && isJsonSchema(value.json)) return value.json;
1778
2146
  if (options == null ? void 0 : options.schema) {
1779
2147
  try {
1780
2148
  return options.schema(value);
@@ -1797,23 +2165,23 @@ function functionTool(name, description, schema, options) {
1797
2165
  }
1798
2166
  function normalizeToolDeclaration(tool, options, fallbackName) {
1799
2167
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
1800
- if (!isRecord3(tool)) return void 0;
2168
+ if (!isRecord4(tool)) return void 0;
1801
2169
  if (tool.type === "provider-defined" || tool.type === "provider") {
1802
2170
  const name2 = (_b = (_a = pickString(tool.name)) != null ? _a : pickString(tool.id)) != null ? _b : fallbackName;
1803
2171
  if (name2 === void 0) return void 0;
1804
2172
  const declaration = { type: "provider-defined", name: name2 };
1805
2173
  const id = pickString(tool.id);
1806
2174
  if (id !== void 0) declaration.id = id;
1807
- if (isRecord3(tool.args)) declaration.args = tool.args;
2175
+ if (isRecord4(tool.args)) declaration.args = tool.args;
1808
2176
  return declaration;
1809
2177
  }
1810
- if (isRecord3(tool.toolSpec)) {
2178
+ if (isRecord4(tool.toolSpec)) {
1811
2179
  const spec = tool.toolSpec;
1812
2180
  const name2 = (_c = pickString(spec.name)) != null ? _c : fallbackName;
1813
2181
  if (name2 === void 0) return void 0;
1814
2182
  return functionTool(name2, spec.description, spec.inputSchema, options);
1815
2183
  }
1816
- if (isRecord3(tool.function)) {
2184
+ if (isRecord4(tool.function)) {
1817
2185
  const fn = tool.function;
1818
2186
  const name2 = (_d = pickString(fn.name)) != null ? _d : fallbackName;
1819
2187
  if (name2 === void 0) return void 0;
@@ -1839,7 +2207,7 @@ function isGeminiToolGroup(tool) {
1839
2207
  if (Array.isArray(tool.functionDeclarations)) return true;
1840
2208
  const keys = Object.keys(tool);
1841
2209
  if (keys.length === 0 || NOT_A_GEMINI_GROUP_KEYS.some((key) => key in tool)) return false;
1842
- return keys.every((key) => isRecord3(tool[key]));
2210
+ return keys.every((key) => isRecord4(tool[key]));
1843
2211
  }
1844
2212
  function expandGeminiTool(tool, options) {
1845
2213
  const declarations = [];
@@ -1849,7 +2217,7 @@ function expandGeminiTool(tool, options) {
1849
2217
  const normalized = normalizeToolDeclaration(declaration, options);
1850
2218
  if (normalized) declarations.push(normalized);
1851
2219
  }
1852
- } else if (isRecord3(value)) {
2220
+ } else if (isRecord4(value)) {
1853
2221
  declarations.push({ type: "provider-defined", id: key, name: key, args: value });
1854
2222
  }
1855
2223
  }
@@ -1859,14 +2227,14 @@ function normalizeToolDeclarations(tools, options) {
1859
2227
  if (tools === void 0 || tools === null) return void 0;
1860
2228
  if (Array.isArray(tools)) {
1861
2229
  return tools.flatMap((tool) => {
1862
- if (isRecord3(tool) && isGeminiToolGroup(tool)) {
2230
+ if (isRecord4(tool) && isGeminiToolGroup(tool)) {
1863
2231
  return expandGeminiTool(tool, options);
1864
2232
  }
1865
2233
  const declaration = normalizeToolDeclaration(tool, options);
1866
2234
  return declaration ? [declaration] : [];
1867
2235
  });
1868
2236
  }
1869
- if (!isRecord3(tools)) return void 0;
2237
+ if (!isRecord4(tools)) return void 0;
1870
2238
  return Object.entries(tools).flatMap(([key, tool]) => {
1871
2239
  const declaration = normalizeToolDeclaration(tool, options, key);
1872
2240
  return declaration ? [declaration] : [];
@@ -1967,388 +2335,85 @@ if (!globalThis.RAINDROP_ASYNC_LOCAL_STORAGE) {
1967
2335
  globalThis.RAINDROP_ASYNC_LOCAL_STORAGE = import_node_async_hooks.AsyncLocalStorage;
1968
2336
  }
1969
2337
 
1970
- // src/tracing/direct/http.ts
1971
- function formatEndpoint2(endpoint) {
1972
- if (!endpoint) return void 0;
1973
- return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
1974
- }
2338
+ // src/tracing/multi-project.ts
2339
+ var import_node_crypto = require("crypto");
2340
+ var import_exporter_trace_otlp_proto2 = require("@opentelemetry/exporter-trace-otlp-proto");
1975
2341
 
1976
- // src/tracing/direct/ids.ts
1977
- function getCrypto2() {
1978
- const c = globalThis.crypto;
1979
- return c;
1980
- }
1981
- function randomBytes2(length) {
1982
- const cryptoObj = getCrypto2();
1983
- const out = new Uint8Array(length);
1984
- if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
1985
- cryptoObj.getRandomValues(out);
1986
- return out;
2342
+ // src/tracing/replay-routing.ts
2343
+ var import_exporter_trace_otlp_proto = require("@opentelemetry/exporter-trace-otlp-proto");
2344
+ var EXPORT_SUCCESS = 0;
2345
+ var EXPORT_FAILED = 1;
2346
+ function recordExportedSpan(destination, span) {
2347
+ if (typeof span !== "object" && typeof span !== "function" || span === null) return;
2348
+ const spanContext = span.spanContext;
2349
+ if (typeof spanContext !== "function") return;
2350
+ const context7 = spanContext.call(span);
2351
+ if (typeof (context7 == null ? void 0 : context7.spanId) === "string" && typeof context7.traceId === "string") {
2352
+ recordReplayExportedSpan(destination, context7.spanId, context7.traceId);
1987
2353
  }
1988
- for (let i = 0; i < out.length; i++) out[i] = Math.floor(Math.random() * 256);
1989
- return out;
1990
2354
  }
1991
- function base64Encode2(bytes) {
1992
- const maybeBuffer = globalThis.Buffer;
1993
- if (maybeBuffer) {
1994
- return maybeBuffer.from(bytes).toString("base64");
1995
- }
1996
- let binary = "";
1997
- for (let i2 = 0; i2 < bytes.length; i2++) {
1998
- binary += String.fromCharCode(bytes[i2]);
1999
- }
2000
- const btoaFn = globalThis.btoa;
2001
- if (typeof btoaFn === "function") return btoaFn(binary);
2002
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2003
- let out = "";
2004
- let i = 0;
2005
- while (i < binary.length) {
2006
- const c1 = binary.charCodeAt(i++) & 255;
2007
- const c2 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
2008
- const c3 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
2009
- const e1 = c1 >> 2;
2010
- const e2 = (c1 & 3) << 4 | (Number.isNaN(c2) ? 0 : c2 >> 4);
2011
- const e3 = Number.isNaN(c2) ? 64 : (c2 & 15) << 2 | (Number.isNaN(c3) ? 0 : c3 >> 6);
2012
- const e4 = Number.isNaN(c3) ? 64 : c3 & 63;
2013
- out += alphabet.charAt(e1);
2014
- out += alphabet.charAt(e2);
2015
- out += e3 === 64 ? "=" : alphabet.charAt(e3);
2016
- out += e4 === 64 ? "=" : alphabet.charAt(e4);
2355
+ function createReplayExporter(destination) {
2356
+ var _a;
2357
+ if (destination.kind === "workshop") {
2358
+ return new import_exporter_trace_otlp_proto.OTLPTraceExporter({
2359
+ url: replayTraceUrl(destination.url)
2360
+ });
2017
2361
  }
2018
- return out;
2362
+ return new import_exporter_trace_otlp_proto.OTLPTraceExporter({
2363
+ url: replayTraceUrl(destination.url),
2364
+ headers: {
2365
+ Authorization: `Bearer ${destination.apiKey}`,
2366
+ "X-Raindrop-Replay-Id": destination.replayId,
2367
+ "X-Raindrop-Project-Id": (_a = destination.projectId) != null ? _a : "default"
2368
+ }
2369
+ });
2019
2370
  }
2020
- function base64ToHex2(base64) {
2021
- const maybeBuffer = globalThis.Buffer;
2022
- if (maybeBuffer) {
2023
- return maybeBuffer.from(base64, "base64").toString("hex");
2371
+ var ReplayRoutingSpanExporter = class {
2372
+ constructor(normal, replayExporter = createReplayExporter) {
2373
+ this.normal = normal;
2374
+ this.replayExporter = replayExporter;
2024
2375
  }
2025
- const atobFn = globalThis.atob;
2026
- if (typeof atobFn === "function") {
2027
- const binary = atobFn(base64);
2028
- let hex = "";
2029
- for (let i = 0; i < binary.length; i++) {
2030
- hex += binary.charCodeAt(i).toString(16).padStart(2, "0");
2376
+ export(spans, resultCallback) {
2377
+ const replayGroups = /* @__PURE__ */ new Map();
2378
+ const normalSpans = [];
2379
+ for (const span of spans) {
2380
+ const destination = replayTraceDestinationFor(span);
2381
+ if (!destination) {
2382
+ normalSpans.push(span);
2383
+ continue;
2384
+ }
2385
+ const group = replayGroups.get(destination);
2386
+ recordExportedSpan(destination, span);
2387
+ if (group) group.push(span);
2388
+ else replayGroups.set(destination, [span]);
2031
2389
  }
2032
- return hex;
2033
- }
2034
- throw new Error("No base64 decoder available in this runtime");
2035
- }
2036
-
2037
- // package.json
2038
- var package_default = {
2039
- name: "raindrop-ai",
2040
- version: "1.0.7",
2041
- main: "dist/index.js",
2042
- module: "dist/index.mjs",
2043
- types: "dist/index.d.ts",
2044
- bin: {
2045
- "raindrop-evals": "dist/evals/cli.js"
2046
- },
2047
- license: "MIT",
2048
- homepage: "https://www.raindrop.ai/docs/sdk/typescript/",
2049
- bugs: {
2050
- url: "https://www.raindrop.ai/docs/support/"
2051
- },
2052
- exports: {
2053
- ".": {
2054
- import: {
2055
- types: "./dist/index.d.mts",
2056
- default: "./dist/index.mjs"
2057
- },
2058
- require: {
2059
- types: "./dist/index.d.ts",
2060
- default: "./dist/index.js"
2061
- }
2062
- },
2063
- "./tracing": {
2064
- types: "./dist/tracing/index.d.ts",
2065
- node: "./dist/tracing/index.js",
2066
- import: "./dist/tracing/index.mjs",
2067
- require: "./dist/tracing/index.js"
2068
- },
2069
- "./otel": {
2070
- types: "./dist/otel/index.d.ts",
2071
- node: "./dist/otel/index.js",
2072
- import: "./dist/otel/index.mjs",
2073
- require: "./dist/otel/index.js"
2074
- }
2075
- },
2076
- files: [
2077
- "dist/**"
2078
- ],
2079
- scripts: {
2080
- build: "tsup",
2081
- dev: "tsup --watch",
2082
- clean: "rm -rf .turbo && rm -rf dist",
2083
- try: "tsx ./src/example/index.ts",
2084
- test: "vitest run",
2085
- smoke: "tsx ./scripts/smoke.ts",
2086
- "smoke:ai-sdk-self-diagnostics": "tsx ./scripts/smoke.ai-sdk-self-diagnostics.ts",
2087
- "smoke:self-diagnostics:v4": "pnpm build && cd tests/v4 && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
2088
- "smoke:self-diagnostics:v5": "pnpm build && cd tests/v5 && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
2089
- "smoke:self-diagnostics:v6": "pnpm build && cd tests/v6 && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
2090
- "smoke:self-diagnostics:ai-sdk:all": "pnpm smoke:self-diagnostics:v4 && pnpm smoke:self-diagnostics:v5 && pnpm smoke:self-diagnostics:v6",
2091
- "smoke:self-diagnostics:openai-sdk": "pnpm build && cd tests/openai && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
2092
- "smoke:self-diagnostics:anthropic-sdk": "pnpm build && cd tests/anthropic && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
2093
- "smoke:self-diagnostics:all": "pnpm smoke:self-diagnostics:ai-sdk:all && pnpm smoke:self-diagnostics:openai-sdk && pnpm smoke:self-diagnostics:anthropic-sdk",
2094
- "test:otelv1-local-debugger": "pnpm build && cd tests/otelv1-local-debugger && pnpm install --ignore-workspace --lockfile=false && pnpm test",
2095
- "test:otelv2-local-debugger": "pnpm build && cd tests/otelv2-local-debugger && pnpm install --ignore-workspace --lockfile=false && pnpm test"
2096
- },
2097
- devDependencies: {
2098
- "@raindrop-ai/core": "workspace:*",
2099
- "@raindrop-ai/redact-pii": "workspace:*",
2100
- "@raindrop-ai/schemas": "workspace:*",
2101
- "@types/node": "^20.11.17",
2102
- ai: "^6.0.214",
2103
- msw: "^2.12.8",
2104
- tsup: "^9.0.0",
2105
- tsx: "^4.22.0",
2106
- typescript: "^5.3.3",
2107
- vite: "^7.3.7",
2108
- vitest: "^4.1.12"
2109
- },
2110
- dependencies: {
2111
- "@jitl/quickjs-singlefile-cjs-release-sync": "0.32.0",
2112
- "@opentelemetry/api": "^1.9.0",
2113
- "@opentelemetry/core": "^1.30.1",
2114
- "@opentelemetry/exporter-trace-otlp-http": "^0.57.2",
2115
- "@opentelemetry/exporter-trace-otlp-proto": "^0.57.2",
2116
- "@opentelemetry/instrumentation": "^0.57.2",
2117
- "@opentelemetry/resources": "^1.30.1",
2118
- "@opentelemetry/sdk-trace-base": "^1.30.1",
2119
- "@opentelemetry/sdk-trace-node": "^1.30.1",
2120
- "@traceloop/ai-semantic-conventions": "0.19.0-otel-v1",
2121
- "@traceloop/instrumentation-anthropic": "0.19.0-otel-v1",
2122
- "@traceloop/instrumentation-bedrock": "0.19.0-otel-v1",
2123
- "@traceloop/instrumentation-chromadb": "0.19.0-otel-v1",
2124
- "@traceloop/instrumentation-cohere": "0.19.0-otel-v1",
2125
- "@traceloop/instrumentation-langchain": "0.19.0-otel-v1",
2126
- "@traceloop/instrumentation-llamaindex": "0.19.0-otel-v1",
2127
- "@traceloop/instrumentation-openai": "0.19.0-otel-v1",
2128
- "@traceloop/instrumentation-pinecone": "0.19.0-otel-v1",
2129
- "@traceloop/instrumentation-qdrant": "0.19.0-otel-v1",
2130
- "@traceloop/instrumentation-together": "0.19.0-otel-v1",
2131
- "@traceloop/instrumentation-vertexai": "0.19.0-otel-v1",
2132
- "quickjs-emscripten-core": "0.32.0",
2133
- weakref: "^0.2.1",
2134
- zod: "^3.23.8"
2135
- },
2136
- publishConfig: {
2137
- access: "public",
2138
- provenance: false
2139
- },
2140
- tsup: {
2141
- entry: [
2142
- "src/index.ts",
2143
- "src/evals/cli.ts",
2144
- "src/tracing/index.ts",
2145
- "src/otel/index.ts"
2146
- ],
2147
- format: [
2148
- "cjs",
2149
- "esm"
2150
- ],
2151
- external: [
2152
- "@traceloop/instrumentation-anthropic",
2153
- "@traceloop/instrumentation-openai",
2154
- "@traceloop/instrumentation-cohere",
2155
- "@traceloop/instrumentation-bedrock",
2156
- "@traceloop/instrumentation-vertexai",
2157
- "@traceloop/instrumentation-pinecone",
2158
- "@traceloop/instrumentation-chromadb",
2159
- "@traceloop/instrumentation-qdrant",
2160
- "@traceloop/instrumentation-together",
2161
- "@traceloop/instrumentation-langchain",
2162
- "@traceloop/instrumentation-llamaindex",
2163
- "@traceloop/ai-semantic-conventions",
2164
- "@opentelemetry/api",
2165
- "@opentelemetry/core",
2166
- "@opentelemetry/instrumentation",
2167
- "@opentelemetry/exporter-trace-otlp-http",
2168
- "@opentelemetry/exporter-trace-otlp-proto",
2169
- "@opentelemetry/resources",
2170
- "@opentelemetry/sdk-trace-base",
2171
- "@opentelemetry/sdk-trace-node"
2172
- ],
2173
- noExternal: [
2174
- "@raindrop-ai/core",
2175
- "@raindrop-ai/redact-pii",
2176
- "@raindrop-ai/schemas"
2177
- ],
2178
- dts: {
2179
- resolve: true
2180
- },
2181
- clean: true
2182
- }
2183
- };
2184
-
2185
- // src/tracing/direct/otlp.ts
2186
- var libraryVersion = package_default.version;
2187
- var SERVICE_NAME = "raindrop-ai";
2188
- function attrString2(key, value) {
2189
- if (value === void 0) return void 0;
2190
- return { key, value: { stringValue: value } };
2191
- }
2192
- function attrInt2(key, value) {
2193
- if (value === void 0) return void 0;
2194
- if (!Number.isFinite(value)) return void 0;
2195
- return { key, value: { intValue: String(Math.trunc(value)) } };
2196
- }
2197
- function buildOtlpSpan2(args) {
2198
- const attrs = args.attributes.filter((x) => x !== void 0);
2199
- const span = {
2200
- traceId: args.ids.traceIdB64,
2201
- spanId: args.ids.spanIdB64,
2202
- name: args.name,
2203
- startTimeUnixNano: args.startTimeUnixNano,
2204
- endTimeUnixNano: args.endTimeUnixNano
2205
- };
2206
- if (args.ids.parentSpanIdB64) span.parentSpanId = args.ids.parentSpanIdB64;
2207
- if (attrs.length) span.attributes = attrs;
2208
- if (args.status) span.status = args.status;
2209
- return span;
2210
- }
2211
- function buildExportTraceServiceRequest2(spans) {
2212
- return {
2213
- resourceSpans: [
2214
- {
2215
- resource: {
2216
- attributes: [{ key: "service.name", value: { stringValue: SERVICE_NAME } }]
2217
- },
2218
- scopeSpans: [
2219
- {
2220
- scope: { name: SERVICE_NAME, version: libraryVersion },
2221
- spans
2222
- }
2223
- ]
2224
- }
2225
- ]
2226
- };
2227
- }
2228
-
2229
- // src/tracing/direct/context.ts
2230
- var import_api = require("@opentelemetry/api");
2231
- var INVALID_TRACE_ID = "00000000000000000000000000000000";
2232
- var INVALID_SPAN_ID = "0000000000000000";
2233
- function hexToBase64(hex) {
2234
- const bytes = new Uint8Array(hex.length / 2);
2235
- for (let i = 0; i < hex.length; i += 2) {
2236
- bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
2237
- }
2238
- return base64Encode2(bytes);
2239
- }
2240
- function getExplicitTraceContext(traceId, parentSpanId) {
2241
- if (!traceId || !parentSpanId || !(0, import_api.isValidTraceId)(traceId) || !(0, import_api.isValidSpanId)(parentSpanId)) {
2242
- return void 0;
2243
- }
2244
- return {
2245
- traceIdB64: hexToBase64(traceId),
2246
- parentSpanIdB64: hexToBase64(parentSpanId)
2247
- };
2248
- }
2249
- function getActiveTraceContext() {
2250
- const activeSpan = import_api.trace.getSpan(import_api.context.active());
2251
- if (!activeSpan) return {};
2252
- const spanContext = activeSpan.spanContext();
2253
- const traceIdHex = spanContext.traceId;
2254
- const spanIdHex = spanContext.spanId;
2255
- if (traceIdHex === INVALID_TRACE_ID) return {};
2256
- return {
2257
- traceIdB64: hexToBase64(traceIdHex),
2258
- parentSpanIdB64: spanIdHex !== INVALID_SPAN_ID ? hexToBase64(spanIdHex) : void 0
2259
- };
2260
- }
2261
- function savedParentContext(traceId, parentSpanId) {
2262
- if (!traceId || !parentSpanId || !(0, import_api.isValidTraceId)(traceId) || !(0, import_api.isValidSpanId)(parentSpanId)) {
2263
- return void 0;
2264
- }
2265
- return import_api.trace.setSpanContext(import_api.context.active(), {
2266
- traceId,
2267
- spanId: parentSpanId,
2268
- traceFlags: import_api.TraceFlags.SAMPLED,
2269
- isRemote: true
2270
- });
2271
- }
2272
-
2273
- // src/tracing/multi-project.ts
2274
- var import_node_crypto = require("crypto");
2275
- var import_exporter_trace_otlp_proto2 = require("@opentelemetry/exporter-trace-otlp-proto");
2276
-
2277
- // src/tracing/replay-routing.ts
2278
- var import_exporter_trace_otlp_proto = require("@opentelemetry/exporter-trace-otlp-proto");
2279
- var EXPORT_SUCCESS = 0;
2280
- var EXPORT_FAILED = 1;
2281
- function recordExportedSpan(destination, span) {
2282
- if (typeof span !== "object" && typeof span !== "function" || span === null) return;
2283
- const spanContext = span.spanContext;
2284
- if (typeof spanContext !== "function") return;
2285
- const context7 = spanContext.call(span);
2286
- if (typeof (context7 == null ? void 0 : context7.spanId) === "string" && typeof context7.traceId === "string") {
2287
- recordReplayExportedSpan(destination, context7.spanId, context7.traceId);
2288
- }
2289
- }
2290
- function createReplayExporter(destination) {
2291
- var _a;
2292
- if (destination.kind === "workshop") {
2293
- return new import_exporter_trace_otlp_proto.OTLPTraceExporter({
2294
- url: replayTraceUrl(destination.url)
2295
- });
2296
- }
2297
- return new import_exporter_trace_otlp_proto.OTLPTraceExporter({
2298
- url: replayTraceUrl(destination.url),
2299
- headers: {
2300
- Authorization: `Bearer ${destination.apiKey}`,
2301
- "X-Raindrop-Replay-Id": destination.replayId,
2302
- "X-Raindrop-Project-Id": (_a = destination.projectId) != null ? _a : "default"
2303
- }
2304
- });
2305
- }
2306
- var ReplayRoutingSpanExporter = class {
2307
- constructor(normal, replayExporter = createReplayExporter) {
2308
- this.normal = normal;
2309
- this.replayExporter = replayExporter;
2310
- }
2311
- export(spans, resultCallback) {
2312
- const replayGroups = /* @__PURE__ */ new Map();
2313
- const normalSpans = [];
2314
- for (const span of spans) {
2315
- const destination = replayTraceDestinationFor(span);
2316
- if (!destination) {
2317
- normalSpans.push(span);
2318
- continue;
2319
- }
2320
- const group = replayGroups.get(destination);
2321
- recordExportedSpan(destination, span);
2322
- if (group) group.push(span);
2323
- else replayGroups.set(destination, [span]);
2324
- }
2325
- if (replayGroups.size === 0) {
2326
- this.normal.export(spans, resultCallback);
2327
- return;
2328
- }
2329
- let remaining = replayGroups.size + (normalSpans.length > 0 ? 1 : 0);
2330
- let failed = false;
2331
- let firstError;
2332
- const finish = (result) => {
2333
- if (result.code !== EXPORT_SUCCESS) {
2334
- failed = true;
2335
- firstError != null ? firstError : firstError = result.error;
2336
- }
2337
- remaining -= 1;
2338
- if (remaining === 0) {
2339
- resultCallback(
2340
- firstError ? { code: EXPORT_FAILED, error: firstError } : { code: failed ? EXPORT_FAILED : EXPORT_SUCCESS }
2341
- );
2342
- }
2343
- };
2344
- if (normalSpans.length > 0) {
2345
- try {
2346
- this.normal.export(normalSpans, finish);
2347
- } catch (cause) {
2348
- finish({
2349
- code: EXPORT_FAILED,
2350
- error: cause instanceof Error ? cause : new Error(String(cause))
2351
- });
2390
+ if (replayGroups.size === 0) {
2391
+ this.normal.export(spans, resultCallback);
2392
+ return;
2393
+ }
2394
+ let remaining = replayGroups.size + (normalSpans.length > 0 ? 1 : 0);
2395
+ let failed = false;
2396
+ let firstError;
2397
+ const finish = (result) => {
2398
+ if (result.code !== EXPORT_SUCCESS) {
2399
+ failed = true;
2400
+ firstError != null ? firstError : firstError = result.error;
2401
+ }
2402
+ remaining -= 1;
2403
+ if (remaining === 0) {
2404
+ resultCallback(
2405
+ firstError ? { code: EXPORT_FAILED, error: firstError } : { code: failed ? EXPORT_FAILED : EXPORT_SUCCESS }
2406
+ );
2407
+ }
2408
+ };
2409
+ if (normalSpans.length > 0) {
2410
+ try {
2411
+ this.normal.export(normalSpans, finish);
2412
+ } catch (cause) {
2413
+ finish({
2414
+ code: EXPORT_FAILED,
2415
+ error: cause instanceof Error ? cause : new Error(String(cause))
2416
+ });
2352
2417
  }
2353
2418
  }
2354
2419
  for (const [destination, replaySpans] of replayGroups) {
@@ -2396,10 +2461,10 @@ function authHintForKey(writeKey) {
2396
2461
  if (!writeKey) return void 0;
2397
2462
  return (0, import_node_crypto.createHash)("sha256").update(writeKey, "utf8").digest("hex").slice(0, 8);
2398
2463
  }
2399
- var STATE_KEY2 = /* @__PURE__ */ Symbol.for("raindrop.tracing.multiProjectState");
2464
+ var STATE_KEY3 = /* @__PURE__ */ Symbol.for("raindrop.tracing.multiProjectState");
2400
2465
  function getState() {
2401
2466
  const holder = globalThis;
2402
- let state2 = holder[STATE_KEY2];
2467
+ let state2 = holder[STATE_KEY3];
2403
2468
  if (!state2) {
2404
2469
  state2 = {
2405
2470
  foreignClientSeen: false,
@@ -2411,7 +2476,7 @@ function getState() {
2411
2476
  multiKeyWarned: false,
2412
2477
  pendingMultiKeyWarning: false
2413
2478
  };
2414
- holder[STATE_KEY2] = state2;
2479
+ holder[STATE_KEY3] = state2;
2415
2480
  }
2416
2481
  return state2;
2417
2482
  }
@@ -2578,49 +2643,354 @@ var GuardedSpanExporter = class {
2578
2643
  resultCallback({ code: EXPORT_SUCCESS2 });
2579
2644
  return;
2580
2645
  }
2581
- this.inner.export(allowed, resultCallback);
2582
- }
2583
- shutdown() {
2584
- return this.inner.shutdown();
2585
- }
2586
- forceFlush() {
2587
- return this.inner.forceFlush ? this.inner.forceFlush() : Promise.resolve();
2646
+ this.inner.export(allowed, resultCallback);
2647
+ }
2648
+ shutdown() {
2649
+ return this.inner.shutdown();
2650
+ }
2651
+ forceFlush() {
2652
+ return this.inner.forceFlush ? this.inner.forceFlush() : Promise.resolve();
2653
+ }
2654
+ };
2655
+ function buildGuardedExporter(baseUrl, headers, ownerAuthHint) {
2656
+ const inner = new import_exporter_trace_otlp_proto2.OTLPTraceExporter({
2657
+ url: `${baseUrl}/v1/traces`,
2658
+ headers
2659
+ });
2660
+ return new GuardedSpanExporter(inner, ownerAuthHint);
2661
+ }
2662
+ function pipelineOwnerHint() {
2663
+ return getState().ownerAuthHint;
2664
+ }
2665
+ function claimPipeline(authHint, projectId) {
2666
+ const state2 = getState();
2667
+ if (state2.pipelineClaimed) {
2668
+ return false;
2669
+ }
2670
+ state2.pipelineClaimed = true;
2671
+ state2.ownerAuthHint = authHint;
2672
+ state2.ownerProjectId = projectId;
2673
+ if (state2.foreignClientSeen && state2.pendingMultiKeyWarning) {
2674
+ emitMultiKeyWarningOnce();
2675
+ }
2676
+ return true;
2677
+ }
2678
+ function releasePipelineClaim() {
2679
+ const state2 = getState();
2680
+ state2.pipelineClaimed = false;
2681
+ state2.ownerAuthHint = void 0;
2682
+ state2.ownerProjectId = void 0;
2683
+ }
2684
+ function markTraceloopConfiguredWithoutClaim() {
2685
+ getState().traceloopConfiguredWithoutClaim = true;
2686
+ }
2687
+ function traceloopConfiguredWithoutClaim() {
2688
+ return getState().traceloopConfiguredWithoutClaim;
2689
+ }
2690
+
2691
+ // src/tracing/direct/context.ts
2692
+ var import_api = require("@opentelemetry/api");
2693
+
2694
+ // src/tracing/direct/ids.ts
2695
+ function getCrypto2() {
2696
+ const c = globalThis.crypto;
2697
+ return c;
2698
+ }
2699
+ function randomBytes2(length) {
2700
+ const cryptoObj = getCrypto2();
2701
+ const out = new Uint8Array(length);
2702
+ if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
2703
+ cryptoObj.getRandomValues(out);
2704
+ return out;
2705
+ }
2706
+ for (let i = 0; i < out.length; i++) out[i] = Math.floor(Math.random() * 256);
2707
+ return out;
2708
+ }
2709
+ function base64Encode2(bytes) {
2710
+ const maybeBuffer = globalThis.Buffer;
2711
+ if (maybeBuffer) {
2712
+ return maybeBuffer.from(bytes).toString("base64");
2713
+ }
2714
+ let binary = "";
2715
+ for (let i2 = 0; i2 < bytes.length; i2++) {
2716
+ binary += String.fromCharCode(bytes[i2]);
2717
+ }
2718
+ const btoaFn = globalThis.btoa;
2719
+ if (typeof btoaFn === "function") return btoaFn(binary);
2720
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2721
+ let out = "";
2722
+ let i = 0;
2723
+ while (i < binary.length) {
2724
+ const c1 = binary.charCodeAt(i++) & 255;
2725
+ const c2 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
2726
+ const c3 = i < binary.length ? binary.charCodeAt(i++) & 255 : NaN;
2727
+ const e1 = c1 >> 2;
2728
+ const e2 = (c1 & 3) << 4 | (Number.isNaN(c2) ? 0 : c2 >> 4);
2729
+ const e3 = Number.isNaN(c2) ? 64 : (c2 & 15) << 2 | (Number.isNaN(c3) ? 0 : c3 >> 6);
2730
+ const e4 = Number.isNaN(c3) ? 64 : c3 & 63;
2731
+ out += alphabet.charAt(e1);
2732
+ out += alphabet.charAt(e2);
2733
+ out += e3 === 64 ? "=" : alphabet.charAt(e3);
2734
+ out += e4 === 64 ? "=" : alphabet.charAt(e4);
2735
+ }
2736
+ return out;
2737
+ }
2738
+ function base64ToHex2(base64) {
2739
+ const maybeBuffer = globalThis.Buffer;
2740
+ if (maybeBuffer) {
2741
+ return maybeBuffer.from(base64, "base64").toString("hex");
2742
+ }
2743
+ const atobFn = globalThis.atob;
2744
+ if (typeof atobFn === "function") {
2745
+ const binary = atobFn(base64);
2746
+ let hex = "";
2747
+ for (let i = 0; i < binary.length; i++) {
2748
+ hex += binary.charCodeAt(i).toString(16).padStart(2, "0");
2749
+ }
2750
+ return hex;
2751
+ }
2752
+ throw new Error("No base64 decoder available in this runtime");
2753
+ }
2754
+
2755
+ // src/tracing/direct/context.ts
2756
+ var INVALID_TRACE_ID = "00000000000000000000000000000000";
2757
+ var INVALID_SPAN_ID = "0000000000000000";
2758
+ function hexToBase64(hex) {
2759
+ const bytes = new Uint8Array(hex.length / 2);
2760
+ for (let i = 0; i < hex.length; i += 2) {
2761
+ bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
2762
+ }
2763
+ return base64Encode2(bytes);
2764
+ }
2765
+ function getExplicitTraceContext(traceId, parentSpanId) {
2766
+ if (!traceId || !parentSpanId || !(0, import_api.isValidTraceId)(traceId) || !(0, import_api.isValidSpanId)(parentSpanId)) {
2767
+ return void 0;
2768
+ }
2769
+ return {
2770
+ traceIdB64: hexToBase64(traceId),
2771
+ parentSpanIdB64: hexToBase64(parentSpanId)
2772
+ };
2773
+ }
2774
+ function getActiveTraceContext() {
2775
+ const activeSpan = import_api.trace.getSpan(import_api.context.active());
2776
+ if (!activeSpan) return {};
2777
+ const spanContext = activeSpan.spanContext();
2778
+ const traceIdHex = spanContext.traceId;
2779
+ const spanIdHex = spanContext.spanId;
2780
+ if (traceIdHex === INVALID_TRACE_ID) return {};
2781
+ return {
2782
+ traceIdB64: hexToBase64(traceIdHex),
2783
+ parentSpanIdB64: spanIdHex !== INVALID_SPAN_ID ? hexToBase64(spanIdHex) : void 0
2784
+ };
2785
+ }
2786
+ function savedParentContext(traceId, parentSpanId) {
2787
+ if (!traceId || !parentSpanId || !(0, import_api.isValidTraceId)(traceId) || !(0, import_api.isValidSpanId)(parentSpanId)) {
2788
+ return void 0;
2789
+ }
2790
+ return import_api.trace.setSpanContext(import_api.context.active(), {
2791
+ traceId,
2792
+ spanId: parentSpanId,
2793
+ traceFlags: import_api.TraceFlags.SAMPLED,
2794
+ isRemote: true
2795
+ });
2796
+ }
2797
+
2798
+ // src/tracing/direct/http.ts
2799
+ function formatEndpoint2(endpoint) {
2800
+ if (!endpoint) return void 0;
2801
+ return endpoint.endsWith("/") ? endpoint : `${endpoint}/`;
2802
+ }
2803
+
2804
+ // package.json
2805
+ var package_default = {
2806
+ name: "raindrop-ai",
2807
+ version: "1.0.8",
2808
+ main: "dist/index.js",
2809
+ module: "dist/index.mjs",
2810
+ types: "dist/index.d.ts",
2811
+ bin: {
2812
+ "raindrop-evals": "dist/evals/cli.js"
2813
+ },
2814
+ license: "MIT",
2815
+ homepage: "https://www.raindrop.ai/docs/sdk/typescript/",
2816
+ bugs: {
2817
+ url: "https://www.raindrop.ai/docs/support/"
2818
+ },
2819
+ exports: {
2820
+ ".": {
2821
+ import: {
2822
+ types: "./dist/index.d.mts",
2823
+ default: "./dist/index.mjs"
2824
+ },
2825
+ require: {
2826
+ types: "./dist/index.d.ts",
2827
+ default: "./dist/index.js"
2828
+ }
2829
+ },
2830
+ "./tracing": {
2831
+ types: "./dist/tracing/index.d.ts",
2832
+ node: "./dist/tracing/index.js",
2833
+ import: "./dist/tracing/index.mjs",
2834
+ require: "./dist/tracing/index.js"
2835
+ },
2836
+ "./otel": {
2837
+ types: "./dist/otel/index.d.ts",
2838
+ node: "./dist/otel/index.js",
2839
+ import: "./dist/otel/index.mjs",
2840
+ require: "./dist/otel/index.js"
2841
+ }
2842
+ },
2843
+ files: [
2844
+ "dist/**"
2845
+ ],
2846
+ scripts: {
2847
+ build: "tsup",
2848
+ dev: "tsup --watch",
2849
+ clean: "rm -rf .turbo && rm -rf dist",
2850
+ try: "tsx ./src/example/index.ts",
2851
+ test: "vitest run",
2852
+ smoke: "tsx ./scripts/smoke.ts",
2853
+ "smoke:ai-sdk-self-diagnostics": "tsx ./scripts/smoke.ai-sdk-self-diagnostics.ts",
2854
+ "smoke:self-diagnostics:v4": "pnpm build && cd tests/v4 && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
2855
+ "smoke:self-diagnostics:v5": "pnpm build && cd tests/v5 && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
2856
+ "smoke:self-diagnostics:v6": "pnpm build && cd tests/v6 && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
2857
+ "smoke:self-diagnostics:ai-sdk:all": "pnpm smoke:self-diagnostics:v4 && pnpm smoke:self-diagnostics:v5 && pnpm smoke:self-diagnostics:v6",
2858
+ "smoke:self-diagnostics:openai-sdk": "pnpm build && cd tests/openai && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
2859
+ "smoke:self-diagnostics:anthropic-sdk": "pnpm build && cd tests/anthropic && pnpm install --ignore-workspace --lockfile=false && pnpm smoke",
2860
+ "smoke:self-diagnostics:all": "pnpm smoke:self-diagnostics:ai-sdk:all && pnpm smoke:self-diagnostics:openai-sdk && pnpm smoke:self-diagnostics:anthropic-sdk",
2861
+ "test:otelv1-local-debugger": "pnpm build && cd tests/otelv1-local-debugger && pnpm install --ignore-workspace --lockfile=false && pnpm test",
2862
+ "test:otelv2-local-debugger": "pnpm build && cd tests/otelv2-local-debugger && pnpm install --ignore-workspace --lockfile=false && pnpm test"
2863
+ },
2864
+ devDependencies: {
2865
+ "@raindrop-ai/core": "workspace:*",
2866
+ "@raindrop-ai/redact-pii": "workspace:*",
2867
+ "@raindrop-ai/schemas": "workspace:*",
2868
+ "@types/node": "^20.11.17",
2869
+ ai: "^6.0.214",
2870
+ msw: "^2.12.8",
2871
+ tsup: "^9.0.0",
2872
+ tsx: "^4.22.0",
2873
+ typescript: "^5.3.3",
2874
+ vite: "^7.3.7",
2875
+ vitest: "^4.1.12"
2876
+ },
2877
+ dependencies: {
2878
+ "@jitl/quickjs-singlefile-cjs-release-sync": "0.32.0",
2879
+ "@opentelemetry/api": "^1.9.0",
2880
+ "@opentelemetry/core": "^1.30.1",
2881
+ "@opentelemetry/exporter-trace-otlp-http": "^0.57.2",
2882
+ "@opentelemetry/exporter-trace-otlp-proto": "^0.57.2",
2883
+ "@opentelemetry/instrumentation": "^0.57.2",
2884
+ "@opentelemetry/resources": "^1.30.1",
2885
+ "@opentelemetry/sdk-trace-base": "^1.30.1",
2886
+ "@opentelemetry/sdk-trace-node": "^1.30.1",
2887
+ "@traceloop/ai-semantic-conventions": "0.19.0-otel-v1",
2888
+ "@traceloop/instrumentation-anthropic": "0.19.0-otel-v1",
2889
+ "@traceloop/instrumentation-bedrock": "0.19.0-otel-v1",
2890
+ "@traceloop/instrumentation-chromadb": "0.19.0-otel-v1",
2891
+ "@traceloop/instrumentation-cohere": "0.19.0-otel-v1",
2892
+ "@traceloop/instrumentation-langchain": "0.19.0-otel-v1",
2893
+ "@traceloop/instrumentation-llamaindex": "0.19.0-otel-v1",
2894
+ "@traceloop/instrumentation-openai": "0.19.0-otel-v1",
2895
+ "@traceloop/instrumentation-pinecone": "0.19.0-otel-v1",
2896
+ "@traceloop/instrumentation-qdrant": "0.19.0-otel-v1",
2897
+ "@traceloop/instrumentation-together": "0.19.0-otel-v1",
2898
+ "@traceloop/instrumentation-vertexai": "0.19.0-otel-v1",
2899
+ "quickjs-emscripten-core": "0.32.0",
2900
+ weakref: "^0.2.1",
2901
+ zod: "^3.23.8"
2902
+ },
2903
+ publishConfig: {
2904
+ access: "public",
2905
+ provenance: false
2906
+ },
2907
+ tsup: {
2908
+ entry: [
2909
+ "src/index.ts",
2910
+ "src/evals/cli.ts",
2911
+ "src/tracing/index.ts",
2912
+ "src/otel/index.ts"
2913
+ ],
2914
+ format: [
2915
+ "cjs",
2916
+ "esm"
2917
+ ],
2918
+ external: [
2919
+ "@traceloop/instrumentation-anthropic",
2920
+ "@traceloop/instrumentation-openai",
2921
+ "@traceloop/instrumentation-cohere",
2922
+ "@traceloop/instrumentation-bedrock",
2923
+ "@traceloop/instrumentation-vertexai",
2924
+ "@traceloop/instrumentation-pinecone",
2925
+ "@traceloop/instrumentation-chromadb",
2926
+ "@traceloop/instrumentation-qdrant",
2927
+ "@traceloop/instrumentation-together",
2928
+ "@traceloop/instrumentation-langchain",
2929
+ "@traceloop/instrumentation-llamaindex",
2930
+ "@traceloop/ai-semantic-conventions",
2931
+ "@opentelemetry/api",
2932
+ "@opentelemetry/core",
2933
+ "@opentelemetry/instrumentation",
2934
+ "@opentelemetry/exporter-trace-otlp-http",
2935
+ "@opentelemetry/exporter-trace-otlp-proto",
2936
+ "@opentelemetry/resources",
2937
+ "@opentelemetry/sdk-trace-base",
2938
+ "@opentelemetry/sdk-trace-node"
2939
+ ],
2940
+ noExternal: [
2941
+ "@raindrop-ai/core",
2942
+ "@raindrop-ai/redact-pii",
2943
+ "@raindrop-ai/schemas"
2944
+ ],
2945
+ dts: {
2946
+ resolve: true
2947
+ },
2948
+ clean: true
2588
2949
  }
2589
2950
  };
2590
- function buildGuardedExporter(baseUrl, headers, ownerAuthHint) {
2591
- const inner = new import_exporter_trace_otlp_proto2.OTLPTraceExporter({
2592
- url: `${baseUrl}/v1/traces`,
2593
- headers
2594
- });
2595
- return new GuardedSpanExporter(inner, ownerAuthHint);
2596
- }
2597
- function pipelineOwnerHint() {
2598
- return getState().ownerAuthHint;
2599
- }
2600
- function claimPipeline(authHint, projectId) {
2601
- const state2 = getState();
2602
- if (state2.pipelineClaimed) {
2603
- return false;
2604
- }
2605
- state2.pipelineClaimed = true;
2606
- state2.ownerAuthHint = authHint;
2607
- state2.ownerProjectId = projectId;
2608
- if (state2.foreignClientSeen && state2.pendingMultiKeyWarning) {
2609
- emitMultiKeyWarningOnce();
2610
- }
2611
- return true;
2951
+
2952
+ // src/tracing/direct/otlp.ts
2953
+ var libraryVersion = package_default.version;
2954
+ var SERVICE_NAME = "raindrop-ai";
2955
+ function attrString2(key, value) {
2956
+ if (value === void 0) return void 0;
2957
+ return { key, value: { stringValue: value } };
2612
2958
  }
2613
- function releasePipelineClaim() {
2614
- const state2 = getState();
2615
- state2.pipelineClaimed = false;
2616
- state2.ownerAuthHint = void 0;
2617
- state2.ownerProjectId = void 0;
2959
+ function attrInt2(key, value) {
2960
+ if (value === void 0) return void 0;
2961
+ if (!Number.isFinite(value)) return void 0;
2962
+ return { key, value: { intValue: String(Math.trunc(value)) } };
2618
2963
  }
2619
- function markTraceloopConfiguredWithoutClaim() {
2620
- getState().traceloopConfiguredWithoutClaim = true;
2964
+ function buildOtlpSpan2(args) {
2965
+ const attrs = args.attributes.filter((x) => x !== void 0);
2966
+ const span = {
2967
+ traceId: args.ids.traceIdB64,
2968
+ spanId: args.ids.spanIdB64,
2969
+ name: args.name,
2970
+ startTimeUnixNano: args.startTimeUnixNano,
2971
+ endTimeUnixNano: args.endTimeUnixNano
2972
+ };
2973
+ if (args.ids.parentSpanIdB64) span.parentSpanId = args.ids.parentSpanIdB64;
2974
+ if (attrs.length) span.attributes = attrs;
2975
+ if (args.status) span.status = args.status;
2976
+ return span;
2621
2977
  }
2622
- function traceloopConfiguredWithoutClaim() {
2623
- return getState().traceloopConfiguredWithoutClaim;
2978
+ function buildExportTraceServiceRequest2(spans) {
2979
+ return {
2980
+ resourceSpans: [
2981
+ {
2982
+ resource: {
2983
+ attributes: [{ key: "service.name", value: { stringValue: SERVICE_NAME } }]
2984
+ },
2985
+ scopeSpans: [
2986
+ {
2987
+ scope: { name: SERVICE_NAME, version: libraryVersion },
2988
+ spans
2989
+ }
2990
+ ]
2991
+ }
2992
+ ]
2993
+ };
2624
2994
  }
2625
2995
 
2626
2996
  // src/tracing/direct/shipper.ts
@@ -2648,6 +3018,9 @@ var DirectTraceShipper = class {
2648
3018
  this.cloudEnabled = (_c = opts.cloudEnabled) != null ? _c : true;
2649
3019
  this.debug = opts.debug;
2650
3020
  this.projectId = opts.projectId;
3021
+ this.redactTracePii = opts.redactTracePii;
3022
+ this.remotePiiConfig = opts.remotePiiConfig;
3023
+ this.spanPiiFields = opts.spanPiiFields;
2651
3024
  this.flushIntervalMs = (_d = opts.flushIntervalMs) != null ? _d : 1e3;
2652
3025
  this.maxBatchSize = (_e = opts.maxBatchSize) != null ? _e : 50;
2653
3026
  this.maxQueueSize = (_f = opts.maxQueueSize) != null ? _f : 5e3;
@@ -2752,8 +3125,9 @@ var DirectTraceShipper = class {
2752
3125
  base64ToHex2(span.traceId)
2753
3126
  );
2754
3127
  const mirrorUrl = (replayDestination == null ? void 0 : replayDestination.kind) === "workshop" ? replayDestination.url : replayDestination ? void 0 : this.localDebuggerUrl;
2755
- if (mirrorUrl) {
2756
- const body = buildExportTraceServiceRequest2([span]);
3128
+ const mirrored = mirrorUrl && this.redactsNow() ? this.redactSpanPii(span) : span;
3129
+ if (mirrorUrl && mirrored) {
3130
+ const body = buildExportTraceServiceRequest2([mirrored]);
2757
3131
  const mirror = mirrorTraceExportToLocalDebugger(body, {
2758
3132
  baseUrl: mirrorUrl,
2759
3133
  debug: false,
@@ -2767,6 +3141,23 @@ var DirectTraceShipper = class {
2767
3141
  console.log(`[raindrop] direct shipper: enqueued span "${params.name}"`);
2768
3142
  }
2769
3143
  }
3144
+ /**
3145
+ * Whether to redact, never waiting: a local mirror uses what is known now,
3146
+ * and a remote setting still being looked up counts as unknown.
3147
+ */
3148
+ redactsNow() {
3149
+ var _a;
3150
+ const writeKey = this.cloudEnabled ? this.writeKey : void 0;
3151
+ return (_a = piiRedactionNow(this.redactTracePii, this.remotePiiConfig, this.baseUrl, writeKey)) != null ? _a : resolvePiiRedaction(this.redactTracePii, this.remotePiiConfig, "unknown");
3152
+ }
3153
+ /** The span with PII redacted from its input and output; undefined if redaction failed. */
3154
+ redactSpanPii(span) {
3155
+ try {
3156
+ return redactPiiInOtlpSpan(span, this.spanPiiFields);
3157
+ } catch (e) {
3158
+ return void 0;
3159
+ }
3160
+ }
2770
3161
  sendToolSpan(params) {
2771
3162
  this.sendSpan({
2772
3163
  ...params,
@@ -2820,13 +3211,22 @@ var DirectTraceShipper = class {
2820
3211
  return summarize2(fates, stillRunning, !settled);
2821
3212
  }
2822
3213
  async drain(deadlineAt) {
2823
- var _a;
3214
+ var _a, _b;
2824
3215
  const fates = [];
2825
3216
  if (!this.enabled) return fates;
2826
3217
  if (this.timer) {
2827
3218
  clearTimeout(this.timer);
2828
3219
  this.timer = void 0;
2829
3220
  }
3221
+ if (this.queue.length === 0) return fates;
3222
+ const writeKey = this.cloudEnabled ? this.writeKey : void 0;
3223
+ const redactPii = (_a = piiRedactionNow(this.redactTracePii, this.remotePiiConfig, this.baseUrl, writeKey)) != null ? _a : await piiRedaction(
3224
+ this.redactTracePii,
3225
+ this.remotePiiConfig,
3226
+ this.baseUrl,
3227
+ writeKey,
3228
+ deadlineAt
3229
+ );
2830
3230
  while (this.queue.length > 0) {
2831
3231
  const batch = this.queue.splice(0, this.maxBatchSize);
2832
3232
  const opts = this.requestOpts(deadlineAt);
@@ -2851,12 +3251,18 @@ var DirectTraceShipper = class {
2851
3251
  for (const [replayDestination, queuedSpans] of groups) {
2852
3252
  if (!replayDestination && !this.cloudEnabled) continue;
2853
3253
  if ((replayDestination == null ? void 0 : replayDestination.kind) === "workshop") continue;
2854
- const body = buildExportTraceServiceRequest2(queuedSpans.map((q) => q.span));
3254
+ const spans = queuedSpans.map((q) => q.span);
3255
+ const outgoing = redactPii ? spans.flatMap((span) => {
3256
+ var _a2;
3257
+ return (_a2 = this.redactSpanPii(span)) != null ? _a2 : [];
3258
+ }) : spans;
3259
+ if (outgoing.length === 0) continue;
3260
+ const body = buildExportTraceServiceRequest2(outgoing);
2855
3261
  const url = replayDestination ? replayTraceUrl(replayDestination.url) : `${this.baseUrl}traces`;
2856
3262
  const headers = replayDestination ? {
2857
3263
  Authorization: `Bearer ${replayDestination.apiKey}`,
2858
3264
  "X-Raindrop-Replay-Id": replayDestination.replayId,
2859
- "X-Raindrop-Project-Id": (_a = replayDestination.projectId) != null ? _a : "default"
3265
+ "X-Raindrop-Project-Id": (_b = replayDestination.projectId) != null ? _b : "default"
2860
3266
  } : { Authorization: `Bearer ${this.writeKey}`, ...projectIdHeaders(this.projectId) };
2861
3267
  const sending = sendJson(url, body, headers, opts);
2862
3268
  const tracked = sending.then(() => void 0);
@@ -2878,7 +3284,9 @@ var DirectTraceShipper = class {
2878
3284
  const reason = outcome.status === "cut_off" ? "cut off at the flush deadline (not resent: it may have reached ingest)" : outcome.status === "deferred" ? "not sent before the shutdown deadline" : "error" in outcome && outcome.error ? outcome.error.message : outcome.status;
2879
3285
  rateLimitedLog(
2880
3286
  "js-sdk.direct.send_failed",
2881
- () => console.warn(`[raindrop] direct: failed to send ${queuedSpans.length} spans (dropping): ${reason}`)
3287
+ () => console.warn(
3288
+ `[raindrop] direct: failed to send ${queuedSpans.length} spans (dropping): ${reason}`
3289
+ )
2882
3290
  );
2883
3291
  } else if (this.debug) {
2884
3292
  console.log(`[raindrop] direct: sent ${queuedSpans.length} spans`);
@@ -2952,6 +3360,93 @@ var import_sdk_trace_base = require("@opentelemetry/sdk-trace-base");
2952
3360
  var import_sdk_trace_node = require("@opentelemetry/sdk-trace-node");
2953
3361
  var import_ai_semantic_conventions = require("@traceloop/ai-semantic-conventions");
2954
3362
  var ALL_INSTRUMENTATION_LIBRARIES = "all";
3363
+ function redactSpanPii(span, fields) {
3364
+ const attributes = redactPiiInAttributeMap(span.attributes, fields);
3365
+ const message = span.status.message;
3366
+ const redactedMessage = message === void 0 ? void 0 : redactSpanContent(message);
3367
+ let eventsChanged = false;
3368
+ const events = span.events.map((event) => {
3369
+ const eventAttributes = event.attributes && redactPiiInAttributeMap(event.attributes, fields);
3370
+ if (!eventAttributes) return event;
3371
+ eventsChanged = true;
3372
+ return { ...event, attributes: eventAttributes };
3373
+ });
3374
+ if (!attributes && redactedMessage === message && !eventsChanged) return span;
3375
+ const view = Object.create(span);
3376
+ if (attributes) {
3377
+ Object.defineProperty(view, "attributes", { value: attributes, enumerable: true });
3378
+ }
3379
+ if (redactedMessage !== message) {
3380
+ Object.defineProperty(view, "status", {
3381
+ value: { ...span.status, message: redactedMessage },
3382
+ enumerable: true
3383
+ });
3384
+ }
3385
+ if (eventsChanged) {
3386
+ Object.defineProperty(view, "events", { value: events, enumerable: true });
3387
+ }
3388
+ copyReplayTraceDestination(span, view);
3389
+ return view;
3390
+ }
3391
+ var PiiRedactingSpanExporter = class {
3392
+ constructor(inner, options) {
3393
+ this.inner = inner;
3394
+ this.options = options;
3395
+ /** Exports waiting for the org lookup; flush and shutdown wait for them. */
3396
+ this.pending = /* @__PURE__ */ new Set();
3397
+ }
3398
+ export(spans, resultCallback) {
3399
+ const { local, remote, apiUrl, writeKey, spanFields } = this.options;
3400
+ const exportContext = import_api2.context.active();
3401
+ const run = (redact) => {
3402
+ let outgoing = spans;
3403
+ if (redact) {
3404
+ outgoing = [];
3405
+ for (const span of spans) {
3406
+ try {
3407
+ outgoing.push(redactSpanPii(span, spanFields));
3408
+ } catch (e) {
3409
+ }
3410
+ }
3411
+ }
3412
+ try {
3413
+ import_api2.context.with(exportContext, () => this.inner.export(outgoing, resultCallback));
3414
+ } catch (e) {
3415
+ resultCallback({ code: 1 });
3416
+ }
3417
+ };
3418
+ const sharedRequest = localTracePiiRedactionRequested(apiUrl, writeKey);
3419
+ const known = sharedRequest || piiRedactionNow(local, remote, apiUrl, writeKey);
3420
+ if (known !== void 0) {
3421
+ run(known);
3422
+ return;
3423
+ }
3424
+ const handedOff = piiRedaction(local, remote, apiUrl, writeKey).then(
3425
+ (redact) => new Promise((resolve) => {
3426
+ const callback = resultCallback;
3427
+ resultCallback = (result) => {
3428
+ resolve();
3429
+ callback(result);
3430
+ };
3431
+ run(redact || localTracePiiRedactionRequested(apiUrl, writeKey));
3432
+ })
3433
+ );
3434
+ this.pending.add(handedOff);
3435
+ void handedOff.finally(() => this.pending.delete(handedOff));
3436
+ }
3437
+ async drainPending() {
3438
+ if (this.pending.size > 0) await Promise.allSettled([...this.pending]);
3439
+ }
3440
+ async shutdown() {
3441
+ await this.drainPending();
3442
+ return this.inner.shutdown();
3443
+ }
3444
+ async forceFlush() {
3445
+ var _a, _b, _c;
3446
+ await this.drainPending();
3447
+ return (_c = (_b = (_a = this.inner).forceFlush) == null ? void 0 : _b.call(_a)) != null ? _c : Promise.resolve();
3448
+ }
3449
+ };
2955
3450
  var TRACER_NAME = "@traceloop/node-server-sdk";
2956
3451
  var WORKFLOW_NAME_KEY = /* @__PURE__ */ Symbol.for("raindrop.otelCore.workflowName");
2957
3452
  var ENTITY_NAME_KEY = /* @__PURE__ */ Symbol.for("raindrop.otelCore.entityName");
@@ -2981,12 +3476,12 @@ var AI_PROMPT_MESSAGES = "ai.prompt.messages";
2981
3476
  var AI_PROMPT_TOKENS = "ai.usage.promptTokens";
2982
3477
  var AI_COMPLETION_TOKENS = "ai.usage.completionTokens";
2983
3478
  var AI_MODEL_PROVIDER = "ai.model.provider";
2984
- var STATE_KEY3 = /* @__PURE__ */ Symbol.for("raindrop.otelCore.state");
3479
+ var STATE_KEY4 = /* @__PURE__ */ Symbol.for("raindrop.otelCore.state");
2985
3480
  function getState2() {
2986
3481
  var _a;
2987
3482
  const holder = globalThis;
2988
- (_a = holder[STATE_KEY3]) != null ? _a : holder[STATE_KEY3] = {};
2989
- return holder[STATE_KEY3];
3483
+ (_a = holder[STATE_KEY4]) != null ? _a : holder[STATE_KEY4] = {};
3484
+ return holder[STATE_KEY4];
2990
3485
  }
2991
3486
  function parseHeaders(value) {
2992
3487
  const headers = {};
@@ -3187,7 +3682,8 @@ function createSpanProcessor(options) {
3187
3682
  const apiKey = options.apiKey || process.env.TRACELOOP_API_KEY;
3188
3683
  const resolvedHeaders = (_a = options.headers) != null ? _a : process.env.TRACELOOP_HEADERS ? parseHeaders(process.env.TRACELOOP_HEADERS) : { Authorization: `Bearer ${apiKey}` };
3189
3684
  const baseExporter = (_b = options.exporter) != null ? _b : new import_exporter_trace_otlp_proto3.OTLPTraceExporter({ url: `${baseUrl}/v1/traces`, headers: resolvedHeaders });
3190
- const exporter = options.routeReplayTraces ? new ReplayRoutingSpanExporter(baseExporter) : baseExporter;
3685
+ const routed = options.routeReplayTraces ? new ReplayRoutingSpanExporter(baseExporter) : baseExporter;
3686
+ const exporter = options.piiRedaction ? new PiiRedactingSpanExporter(routed, options.piiRedaction) : routed;
3191
3687
  const processor = options.disableBatch ? new import_sdk_trace_base.SimpleSpanProcessor(exporter) : new import_sdk_trace_base.BatchSpanProcessor(exporter);
3192
3688
  const originalOnStart = processor.onStart.bind(processor);
3193
3689
  const originalOnEnd = processor.onEnd.bind(processor);
@@ -3378,17 +3874,17 @@ function withTool(config, fn, ...args) {
3378
3874
  }
3379
3875
 
3380
3876
  // src/tracing/exit-flush.ts
3381
- var STATE_KEY4 = /* @__PURE__ */ Symbol.for("raindrop.tracing.exitFlushState");
3877
+ var STATE_KEY5 = /* @__PURE__ */ Symbol.for("raindrop.tracing.exitFlushState");
3382
3878
  function getState3() {
3383
3879
  const holder = globalThis;
3384
- let state2 = holder[STATE_KEY4];
3880
+ let state2 = holder[STATE_KEY5];
3385
3881
  if (!state2) {
3386
3882
  state2 = {
3387
3883
  clientFlushers: /* @__PURE__ */ new Set(),
3388
3884
  pipelineFlushNeeded: false,
3389
3885
  handlerRegistered: false
3390
3886
  };
3391
- holder[STATE_KEY4] = state2;
3887
+ holder[STATE_KEY5] = state2;
3392
3888
  }
3393
3889
  return state2;
3394
3890
  }
@@ -4967,6 +5463,7 @@ function createLocalDebuggerSpanProcessor(options) {
4967
5463
  disableBatch: options.disableBatching,
4968
5464
  exporter: localExporter,
4969
5465
  headers: {},
5466
+ piiRedaction: options.piiRedaction,
4970
5467
  allowedInstrumentationLibraries: options.allowedInstrumentationLibraries
4971
5468
  });
4972
5469
  } catch (error) {
@@ -5310,9 +5807,32 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
5310
5807
  cloudEnabled,
5311
5808
  projectId,
5312
5809
  flushTimeoutMs,
5810
+ redactTracePii,
5811
+ redactPiiFields,
5812
+ remotePiiConfig,
5313
5813
  ...otherOptions
5314
5814
  } = options;
5315
5815
  const cloudEnabledResolved = cloudEnabled != null ? cloudEnabled : true;
5816
+ const localTracePii = typeof redactTracePii === "boolean" ? redactTracePii : void 0;
5817
+ const spanPiiFields = compileSpanPiiFields(redactPiiFields == null ? void 0 : redactPiiFields.span, "[raindrop]");
5818
+ if ((redactPiiFields == null ? void 0 : redactPiiFields.span) && localTracePii !== true && !remotePiiConfig) {
5819
+ rateLimitedLog(
5820
+ "js-sdk.pii_span_fields_without_redaction",
5821
+ () => console.warn(
5822
+ "[raindrop] redactPiiFields.span is set but redactTracePii is off; no span is redacted. Set redactTracePii: true to use it."
5823
+ )
5824
+ );
5825
+ }
5826
+ const piiRedaction2 = {
5827
+ local: localTracePii,
5828
+ remote: remotePiiConfig,
5829
+ apiUrl: directEndpoint != null ? directEndpoint : apiUrl,
5830
+ writeKey: cloudEnabledResolved ? writeKey : void 0,
5831
+ spanFields: spanPiiFields
5832
+ };
5833
+ if (localTracePii === true) {
5834
+ requestLocalTracePiiRedaction(piiRedaction2.apiUrl, piiRedaction2.writeKey);
5835
+ }
5316
5836
  const authHint = authHintForKey(writeKey);
5317
5837
  const clientTracingExports = !useExternalOtel && cloudEnabledResolved && tracingEnabled !== false;
5318
5838
  registerClientKey(authHint, clientTracingExports);
@@ -5342,7 +5862,10 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
5342
5862
  localDebuggerUrl,
5343
5863
  cloudEnabled: cloudEnabledResolved,
5344
5864
  projectId,
5345
- flushTimeoutMs
5865
+ flushTimeoutMs,
5866
+ redactTracePii: localTracePii,
5867
+ remotePiiConfig,
5868
+ spanPiiFields
5346
5869
  }) : void 0;
5347
5870
  let traceloopInitialized = false;
5348
5871
  let claimedPipeline = false;
@@ -5381,7 +5904,8 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
5381
5904
  disableBatching,
5382
5905
  allowedInstrumentationLibraries: ALL_INSTRUMENTATION_LIBRARIES,
5383
5906
  localDebuggerUrlOpt: localDebuggerUrl,
5384
- routeReplayTraces: !cloudEnabledResolved
5907
+ routeReplayTraces: !cloudEnabledResolved,
5908
+ piiRedaction: piiRedaction2
5385
5909
  });
5386
5910
  if (!cloudEnabledResolved) {
5387
5911
  if (localDebuggerProcessor) {
@@ -5407,7 +5931,8 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
5407
5931
  exporter: new DropSpanExporter(),
5408
5932
  routeReplayTraces: true,
5409
5933
  disableBatch: disableBatching,
5410
- allowedInstrumentationLibraries: ALL_INSTRUMENTATION_LIBRARIES
5934
+ allowedInstrumentationLibraries: ALL_INSTRUMENTATION_LIBRARIES,
5935
+ piiRedaction: piiRedaction2
5411
5936
  });
5412
5937
  initialize({
5413
5938
  baseUrl: apiUrl,
@@ -5479,6 +6004,7 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
5479
6004
  disableBatch: disableBatching,
5480
6005
  processor,
5481
6006
  exporter: guardedExporter,
6007
+ piiRedaction: piiRedaction2,
5482
6008
  instrumentations: createConfiguredInstrumentations(otherOptions)
5483
6009
  });
5484
6010
  traceloopInitialized = true;
@@ -5720,7 +6246,8 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
5720
6246
  disableBatching,
5721
6247
  allowedInstrumentationLibraries: processorOptions == null ? void 0 : processorOptions.allowedInstrumentationLibraries,
5722
6248
  localDebuggerUrlOpt: localDebuggerUrl,
5723
- routeReplayTraces: true
6249
+ routeReplayTraces: true,
6250
+ piiRedaction: piiRedaction2
5724
6251
  });
5725
6252
  return withV2SpanCompat(
5726
6253
  localOnlyProcessor != null ? localOnlyProcessor : {
@@ -5742,13 +6269,15 @@ var tracing = (analytics, apiUrl, writeKey, options, isDebug = false) => {
5742
6269
  disableBatch: disableBatching,
5743
6270
  ...processorOptions != null ? processorOptions : {},
5744
6271
  routeReplayTraces: true,
5745
- ...headers ? { headers } : {}
6272
+ ...headers ? { headers } : {},
6273
+ piiRedaction: piiRedaction2
5746
6274
  });
5747
6275
  const localDebuggerProcessor = createLocalDebuggerSpanProcessor({
5748
6276
  writeKey,
5749
6277
  disableBatching,
5750
6278
  allowedInstrumentationLibraries: processorOptions == null ? void 0 : processorOptions.allowedInstrumentationLibraries,
5751
- localDebuggerUrlOpt: localDebuggerUrl
6279
+ localDebuggerUrlOpt: localDebuggerUrl,
6280
+ piiRedaction: piiRedaction2
5752
6281
  });
5753
6282
  const contextProcessor = new RaindropContextSpanProcessor((properties) => analytics.getAppGitSnapshot(properties));
5754
6283
  return withV2SpanCompat(