risicare 0.5.2 → 0.7.0

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.
Files changed (41) hide show
  1. package/LICENSE +26 -0
  2. package/README.md +43 -10
  3. package/dist/frameworks/instructor.cjs.map +1 -1
  4. package/dist/frameworks/instructor.js.map +1 -1
  5. package/dist/frameworks/langchain.cjs.map +1 -1
  6. package/dist/frameworks/langchain.js.map +1 -1
  7. package/dist/frameworks/langgraph.cjs.map +1 -1
  8. package/dist/frameworks/langgraph.js.map +1 -1
  9. package/dist/frameworks/llamaindex.cjs.map +1 -1
  10. package/dist/frameworks/llamaindex.js.map +1 -1
  11. package/dist/index.cjs +185 -24
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.cts +16 -2
  14. package/dist/index.d.ts +16 -2
  15. package/dist/index.js +185 -24
  16. package/dist/index.js.map +1 -1
  17. package/dist/providers/anthropic/index.cjs.map +1 -1
  18. package/dist/providers/anthropic/index.js.map +1 -1
  19. package/dist/providers/bedrock/index.cjs.map +1 -1
  20. package/dist/providers/bedrock/index.js.map +1 -1
  21. package/dist/providers/cerebras/index.cjs.map +1 -1
  22. package/dist/providers/cerebras/index.js.map +1 -1
  23. package/dist/providers/cohere/index.cjs.map +1 -1
  24. package/dist/providers/cohere/index.js.map +1 -1
  25. package/dist/providers/google/index.cjs.map +1 -1
  26. package/dist/providers/google/index.js.map +1 -1
  27. package/dist/providers/groq/index.cjs.map +1 -1
  28. package/dist/providers/groq/index.js.map +1 -1
  29. package/dist/providers/huggingface/index.cjs.map +1 -1
  30. package/dist/providers/huggingface/index.js.map +1 -1
  31. package/dist/providers/mistral/index.cjs.map +1 -1
  32. package/dist/providers/mistral/index.js.map +1 -1
  33. package/dist/providers/ollama/index.cjs.map +1 -1
  34. package/dist/providers/ollama/index.js.map +1 -1
  35. package/dist/providers/openai/index.cjs.map +1 -1
  36. package/dist/providers/openai/index.js.map +1 -1
  37. package/dist/providers/together/index.cjs.map +1 -1
  38. package/dist/providers/together/index.js.map +1 -1
  39. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  40. package/dist/providers/vercel-ai/index.js.map +1 -1
  41. package/package.json +5 -12
package/dist/index.cjs CHANGED
@@ -216,15 +216,121 @@ function applyMask(span, mask, onError) {
216
216
  markMasked(span);
217
217
  }
218
218
  var CONTENT_KEYS_EXACT = /* @__PURE__ */ new Set([
219
+ // spec v1
219
220
  "gen_ai.system_prompt",
220
- "gen_ai.prompt.message"
221
+ // anthropic, bedrock
222
+ "gen_ai.prompt.message",
223
+ // cohere
224
+ "gen_ai.prompt",
225
+ // OTel GenAI (deprecated form)
226
+ "gen_ai.completion",
227
+ "gen_ai.input.messages",
228
+ // OTel GenAI
229
+ "gen_ai.output.messages",
230
+ "gen_ai.system_instructions",
231
+ "gen_ai.tool.call.arguments",
232
+ "gen_ai.tool.call.result",
233
+ "input.value",
234
+ // OpenInference
235
+ "output.value",
236
+ "llm.prompts",
237
+ "llm.prompt_template.template",
238
+ "llm.prompt_template.variables",
239
+ "task_description",
240
+ // CrewAI
241
+ // ⚠ EXTENSION to spec v1: content keys that the Python SDK's integrations emit
242
+ // and that no v1 rule strips. Kept here too, so the two SDKs agree on the rule.
243
+ "framework.crewai.task_description",
244
+ "framework.crewai.agent_goal",
245
+ "framework.crewai.agent_output",
246
+ "framework.crewai.result",
247
+ "framework.autogen.last_message",
248
+ "framework.autogen.reply",
249
+ "framework.autogen.response",
250
+ "framework.openai_agents.input",
251
+ "framework.openai_agents.output",
252
+ "framework.dspy.signature",
253
+ "gen_ai.request.messages",
254
+ "agent.action.input",
255
+ "agent.action.log",
256
+ "agent.finish.output",
257
+ "tool.input",
258
+ "tool.output",
259
+ "retriever.query",
260
+ "retriever.first_doc",
261
+ // ⚠ FAIL CLOSED: third-party content keys that no other rule strips.
262
+ "gen_ai.retrieval.query.text",
263
+ // OTel GenAI
264
+ "gen_ai.retrieval.documents",
265
+ "gen_ai.evaluation.explanation",
266
+ "llm.function_call",
267
+ // OpenInference
268
+ "llm.choices",
269
+ "reranker.query",
270
+ "audio.transcript",
271
+ "traceloop.entity.input",
272
+ // OpenLLMetry
273
+ "traceloop.entity.output"
221
274
  ]);
275
+ var CONTENT_LAST_SEGMENT_IN_CONTEXT = /* @__PURE__ */ new Map([
276
+ ["function_call_arguments_json", /* @__PURE__ */ new Set()],
277
+ // OpenInference `message.*`
278
+ ["data", /* @__PURE__ */ new Set(["message_content"])],
279
+ ["url", /* @__PURE__ */ new Set(["image"])],
280
+ // `image.url` can hold base64 data
281
+ ["metadata", /* @__PURE__ */ new Set(["document", "documents"])]
282
+ ]);
283
+ var CONTENT_CONTAINER_SEGMENTS = /* @__PURE__ */ new Set([
284
+ "message",
285
+ "messages",
286
+ "message_content",
287
+ "contents",
288
+ "embedding",
289
+ "embeddings",
290
+ "document",
291
+ "documents",
292
+ "tool_call",
293
+ "tool_calls",
294
+ "function"
295
+ ]);
296
+ var CONTENT_KEYS_KEEP_EXACT = /* @__PURE__ */ new Set([
297
+ "gen_ai.response.content_type",
298
+ "gen_ai.response.content_blocks",
299
+ "gen_ai.prompt.parts",
300
+ "gen_ai.prompt.count",
301
+ "gen_ai.response.choices",
302
+ "gen_ai.completion.tool_calls"
303
+ ]);
304
+ var KEEP_LAST_SEGMENTS = /* @__PURE__ */ new Set([
305
+ "role",
306
+ "name",
307
+ "id",
308
+ "type",
309
+ "count",
310
+ "index",
311
+ "model",
312
+ "finish_reason",
313
+ "mime_type"
314
+ ]);
315
+ var KEEP_LAST_SUFFIXES = ["_length", "_tokens", "_count"];
222
316
  var CONTENT_OMITTED_MARKER = "<risicare:content-omitted>";
223
317
  function isContentKey(key) {
224
- if (CONTENT_KEYS_EXACT.has(key)) return true;
225
- const lastSegment = key.slice(key.lastIndexOf(".") + 1);
226
- if (lastSegment === "content") return true;
227
- return key.endsWith("_content");
318
+ if (CONTENT_KEYS_KEEP_EXACT.has(key)) return false;
319
+ if (CONTENT_KEYS_EXACT.has(key) || key.endsWith("_content")) return true;
320
+ const segments = key.split(".");
321
+ const last = segments[segments.length - 1];
322
+ const context = CONTENT_LAST_SEGMENT_IN_CONTEXT.get(last);
323
+ if (context && (context.size === 0 || segments.slice(0, -1).some((s) => context.has(s)))) {
324
+ return true;
325
+ }
326
+ if (KEEP_LAST_SEGMENTS.has(last) || KEEP_LAST_SUFFIXES.some((x) => last.endsWith(x))) {
327
+ return false;
328
+ }
329
+ if (last === "content") return true;
330
+ if (last === "text" || last === "arguments") {
331
+ return segments.slice(0, -1).some((s) => CONTENT_CONTAINER_SEGMENTS.has(s));
332
+ }
333
+ return false;
228
334
  }
229
335
  function stripAttributes(attrs) {
230
336
  let n = 0;
@@ -707,11 +813,13 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
707
813
  };
708
814
 
709
815
  // src/config.ts
710
- var DEFAULT_ENDPOINT = "https://app.risicare.ai";
816
+ var DEFAULT_ENDPOINT = "https://ingest.risicare.ai";
817
+ var DEFAULT_API_ENDPOINT = "https://api.risicare.ai";
711
818
  function resolveConfig(config) {
712
819
  const env = process.env;
713
820
  const apiKey = config?.apiKey ?? env.RISICARE_API_KEY;
714
821
  const endpoint = config?.endpoint ?? env.RISICARE_ENDPOINT ?? DEFAULT_ENDPOINT;
822
+ const apiEndpoint = config?.apiEndpoint ?? env.RISICARE_API_ENDPOINT ?? config?.endpoint ?? env.RISICARE_ENDPOINT ?? DEFAULT_API_ENDPOINT;
715
823
  const projectId = config?.projectId ?? env.RISICARE_PROJECT_ID;
716
824
  if (config?.projectId || env.RISICARE_PROJECT_ID) {
717
825
  console.warn(
@@ -725,6 +833,7 @@ function resolveConfig(config) {
725
833
  const sampleRateRaw = config?.sampleRate ?? parseFloat(env.RISICARE_SAMPLE_RATE ?? "1.0");
726
834
  const debug2 = config?.debug ?? parseBool(env.RISICARE_DEBUG, false);
727
835
  const compress = config?.compress ?? parseBool(env.RISICARE_COMPRESS, false);
836
+ const fixRuntime = config?.fixRuntime ?? parseBool(env.RISICARE_FIX_RUNTIME, false);
728
837
  const batchSizeRaw = config?.batchSize ?? parseNumericEnv(env.RISICARE_BATCH_SIZE, DEFAULT_BATCH_SIZE);
729
838
  const batchTimeoutMsRaw = config?.batchTimeoutMs ?? parseNumericEnv(env.RISICARE_BATCH_TIMEOUT_MS, 1e3);
730
839
  const maxQueueSizeRaw = config?.maxQueueSize ?? parseNumericEnv(env.RISICARE_MAX_QUEUE_SIZE, 1e4);
@@ -748,6 +857,7 @@ function resolveConfig(config) {
748
857
  return {
749
858
  apiKey: apiKey ?? "",
750
859
  endpoint,
860
+ apiEndpoint,
751
861
  projectId: projectId ?? "",
752
862
  environment,
753
863
  serviceName: serviceName ?? "",
@@ -760,6 +870,7 @@ function resolveConfig(config) {
760
870
  maxQueueSize,
761
871
  debug: debug2,
762
872
  compress,
873
+ fixRuntime,
763
874
  metadata: config?.metadata ?? {},
764
875
  // No env fallback — see the field's note on RisicareConfig.
765
876
  mask: config?.mask
@@ -1843,13 +1954,14 @@ var Tracer = class {
1843
1954
  };
1844
1955
 
1845
1956
  // src/version.ts
1846
- var SDK_VERSION = "0.5.2";
1957
+ var SDK_VERSION = "0.7.0";
1847
1958
 
1848
1959
  // src/exporters/http.ts
1849
1960
  var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
1850
1961
  var RETRY_AFTER_CEILING_MS = 1e4;
1851
1962
  var REFUSAL_BACKOFF_BASE_MS = 1e3;
1852
1963
  var REFUSAL_NO_HINT = -1;
1964
+ var MISROUTE_WARN_WINDOW_MS = 3e5;
1853
1965
  var HttpExporter = class {
1854
1966
  name = "http";
1855
1967
  _endpoint;
@@ -1877,6 +1989,9 @@ var HttpExporter = class {
1877
1989
  * same reason (its `_send_request` signature is pin-locked).
1878
1990
  */
1879
1991
  _lastRefusalAfterMs = null;
1992
+ /** Set by `_sendRequest` on a MISROUTE: a short description of the answer. `null` = none. */
1993
+ _lastMisroute = null;
1994
+ _lastMisrouteWarnAt = -Infinity;
1880
1995
  _circuitOpenUntil = 0;
1881
1996
  _circuitBreakerThreshold = 5;
1882
1997
  _circuitBreakerCooldownMs = 6e4;
@@ -1907,11 +2022,13 @@ var HttpExporter = class {
1907
2022
  const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
1908
2023
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1909
2024
  this._lastRefusalAfterMs = null;
2025
+ this._lastMisroute = null;
1910
2026
  const result = await this._sendRequest(body);
1911
2027
  if (result === "success" /* SUCCESS */) {
1912
2028
  this._consecutiveFailures = 0;
1913
2029
  return result;
1914
2030
  }
2031
+ if (this._lastMisroute !== null) break;
1915
2032
  if (attempt < maxAttempts - 1) {
1916
2033
  const refusal = this._lastRefusalAfterMs;
1917
2034
  const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
@@ -1926,6 +2043,14 @@ var HttpExporter = class {
1926
2043
  );
1927
2044
  return "failure" /* FAILURE */;
1928
2045
  }
2046
+ const misroute = this._lastMisroute;
2047
+ this._lastMisroute = null;
2048
+ if (misroute !== null && Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
2049
+ this._lastMisrouteWarnAt = Date.now();
2050
+ warn(
2051
+ `Risicare: spans are NOT reaching ${this._endpoint}. It answered POST /v1/spans with ${misroute}. That is not the Risicare ingest gateway, so the endpoint is probably wrong (for example the dashboard URL instead of the ingest gateway URL). The SDK does not follow redirects, and this batch is counted as NOT delivered. Set endpoint or RISICARE_ENDPOINT to the ingest gateway URL.`
2052
+ );
2053
+ }
1929
2054
  this._consecutiveFailures++;
1930
2055
  if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
1931
2056
  this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
@@ -1935,6 +2060,12 @@ var HttpExporter = class {
1935
2060
  }
1936
2061
  return "failure" /* FAILURE */;
1937
2062
  }
2063
+ /** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */
2064
+ _noteMisroute(answer) {
2065
+ this._lastMisroute = answer.slice(0, 300);
2066
+ debug(`Ingest misroute: ${this._lastMisroute}`);
2067
+ return "failure" /* FAILURE */;
2068
+ }
1938
2069
  /**
1939
2070
  * Record a CAPACITY REFUSAL for the retry loop. Returns true if it was one.
1940
2071
  *
@@ -1959,7 +2090,13 @@ var HttpExporter = class {
1959
2090
  const url = `${this._endpoint}/v1/spans`;
1960
2091
  const headers = {
1961
2092
  "Content-Type": "application/json",
1962
- "User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`
2093
+ "User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`,
2094
+ // F-SDKVER-001 parity. Python's ingest exporter has always sent
2095
+ // `X-Risicare-SDK-Version`; JS sent only a User-Agent, so the two SDKs
2096
+ // disagreed about how a client identifies itself. A parser-free header is
2097
+ // strictly easier for the gateway to consume than picking a version out of
2098
+ // a UA string.
2099
+ "X-Risicare-SDK-Version": SDK_VERSION
1963
2100
  };
1964
2101
  if (this._apiKey) {
1965
2102
  headers["Authorization"] = `Bearer ${this._apiKey}`;
@@ -1981,11 +2118,23 @@ var HttpExporter = class {
1981
2118
  method: "POST",
1982
2119
  headers,
1983
2120
  body: payload,
1984
- signal: controller.signal
2121
+ signal: controller.signal,
2122
+ // Never follow: a redirect is a misroute (see MISROUTE_WARN_WINDOW_MS). Node returns
2123
+ // the 3xx itself; a browser-like runtime returns type 'opaqueredirect' with status 0.
2124
+ redirect: "manual"
1985
2125
  });
1986
2126
  clearTimeout(timeoutId);
1987
- if (response.status < 300) {
1988
- return await checkAck(response);
2127
+ const redirected = response.type === "opaqueredirect";
2128
+ if (redirected || response.status >= 300 && response.status < 400) {
2129
+ const location = response.headers?.get?.("Location");
2130
+ const target = location ? location.slice(0, 200) : "no Location header";
2131
+ return this._noteMisroute(`HTTP ${response.status || "3xx"}, a redirect to ${target}`);
2132
+ }
2133
+ if (response.status >= 200 && response.status < 300) {
2134
+ const ack = await checkAck(response);
2135
+ return ack === null ? this._noteMisroute(
2136
+ `HTTP ${response.status} and a body that is not a Risicare ack (content-type: ${response.headers?.get?.("Content-Type") || "none"})`
2137
+ ) : ack;
1989
2138
  } else if (response.status === 408 || response.status === 504) {
1990
2139
  debug(`HTTP export timeout: ${response.status}`);
1991
2140
  return "timeout" /* TIMEOUT */;
@@ -2012,17 +2161,16 @@ async function checkAck(response) {
2012
2161
  try {
2013
2162
  payload = await response.json();
2014
2163
  } catch {
2015
- return "success" /* SUCCESS */;
2164
+ return null;
2016
2165
  }
2017
2166
  if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
2018
- return "success" /* SUCCESS */;
2167
+ return null;
2019
2168
  }
2020
2169
  const body = payload;
2021
2170
  const accepted = asCount(body.accepted);
2022
2171
  const rejected = asCount(body.rejected);
2023
- if (accepted === void 0 || rejected === void 0 || rejected <= 0) {
2024
- return "success" /* SUCCESS */;
2025
- }
2172
+ if (accepted === void 0 || rejected === void 0) return null;
2173
+ if (rejected === 0) return "success" /* SUCCESS */;
2026
2174
  const errors = body.errors;
2027
2175
  const detail = typeof body.errorMessage === "string" && body.errorMessage || typeof body.error_message === "string" && body.error_message || (Array.isArray(errors) && errors.length > 0 ? JSON.stringify(errors[0]) : "") || "No reason was returned.";
2028
2176
  const total = accepted + rejected;
@@ -2723,7 +2871,7 @@ var FixLoader = class _FixLoader {
2723
2871
  }
2724
2872
  try {
2725
2873
  const endpoint = this._config.apiEndpoint.replace(/\/+$/, "");
2726
- const url = `${endpoint}/api/v1/fixes/active`;
2874
+ const url = `${endpoint}/v1/fixes/active`;
2727
2875
  const controller = new AbortController();
2728
2876
  const timeoutId = setTimeout(
2729
2877
  () => controller.abort(),
@@ -3135,10 +3283,10 @@ var RisicareClient = class {
3135
3283
  serviceVersion: this.config.serviceVersion
3136
3284
  });
3137
3285
  this.processor.start();
3138
- if (this.config.apiKey && this.config.enabled) {
3286
+ if (this.config.apiKey && this.config.enabled && this.config.fixRuntime) {
3139
3287
  try {
3140
3288
  initFixRuntime({
3141
- apiEndpoint: this.config.endpoint,
3289
+ apiEndpoint: this.config.apiEndpoint,
3142
3290
  apiKey: this.config.apiKey,
3143
3291
  enabled: true,
3144
3292
  debug: this.config.debug
@@ -3160,6 +3308,11 @@ var RisicareClient = class {
3160
3308
  this._registerShutdownHooks();
3161
3309
  setDebug(this.config.debug);
3162
3310
  debug(`Initialized: enabled=${this.config.enabled}, endpoint=${this.config.endpoint}`);
3311
+ if (!this.config.fixRuntime) {
3312
+ debug(
3313
+ "FixRuntime is off: nothing polls /fixes/active and no fix is applied. Opt in with fixRuntime: true or RISICARE_FIX_RUNTIME=true."
3314
+ );
3315
+ }
3163
3316
  }
3164
3317
  get enabled() {
3165
3318
  return this.tracer.enabled;
@@ -3398,6 +3551,7 @@ function reportError(error, options) {
3398
3551
  span.setAttribute("error.message", err.message.slice(0, 2e3));
3399
3552
  if (err.stack) span.setAttribute("error.stack", err.stack.slice(0, 4e3));
3400
3553
  span.setAttribute("risicare.reported_error", true);
3554
+ attachErrorCode(span, err);
3401
3555
  if (options?.attributes) {
3402
3556
  for (const [k, v] of Object.entries(options.attributes)) {
3403
3557
  span.setAttribute(k, v);
@@ -3420,8 +3574,8 @@ function score(traceId, name, value, options) {
3420
3574
  }
3421
3575
  const client = getClient();
3422
3576
  if (!client?.enabled || !client.config.apiKey) return;
3423
- const endpoint = client.config.endpoint.replace(/\/$/, "");
3424
- const url = `${endpoint}/api/v1/scores`;
3577
+ const endpoint = client.config.apiEndpoint.replace(/\/+$/, "");
3578
+ const url = `${endpoint}/v1/scores`;
3425
3579
  let comment = options?.comment;
3426
3580
  if (comment !== void 0 && client.config.mask) {
3427
3581
  comment = maskText(client.config.mask, SCORE_COMMENT_KEY, comment);
@@ -3438,7 +3592,14 @@ function score(traceId, name, value, options) {
3438
3592
  method: "POST",
3439
3593
  headers: {
3440
3594
  "Content-Type": "application/json",
3441
- "Authorization": `Bearer ${client.config.apiKey}`
3595
+ "Authorization": `Bearer ${client.config.apiKey}`,
3596
+ // F-SDKVER-001 — see the Python twin. `score()` reaches the FastAPI
3597
+ // server under /v1/, which `main.py::audit_logging_middleware` audits
3598
+ // into `audit_logs.user_agent`; ingest reaches the Rust gateway, which
3599
+ // discards it. This is the one client-identity visible with no gateway
3600
+ // change.
3601
+ "User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`,
3602
+ "X-Risicare-SDK-Version": SDK_VERSION
3442
3603
  },
3443
3604
  body
3444
3605
  }).catch((err) => debug(`score: send failed: ${err}`));
@@ -3591,14 +3752,14 @@ function withSession(options, fn) {
3591
3752
  parentSessionId: options.parentSessionId,
3592
3753
  turnNumber: options.turnNumber ?? 1
3593
3754
  };
3594
- return runWithContext({ session: session2 }, fn);
3755
+ return runWithContext({ session: session2 }, () => withSessionEndMarker(fn));
3595
3756
  }
3596
3757
 
3597
3758
  // src/decorators/session.ts
3598
3759
  function _wrapSession(optionsOrResolver, fn) {
3599
3760
  return (...args) => {
3600
3761
  const options = typeof optionsOrResolver === "function" ? optionsOrResolver(...args) : optionsOrResolver;
3601
- return withSession(options, () => withSessionEndMarker(() => fn(...args)));
3762
+ return withSession(options, () => fn(...args));
3602
3763
  };
3603
3764
  }
3604
3765
  function session(optionsOrResolver, fn) {