risicare 0.5.0 → 0.5.2

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 (72) hide show
  1. package/README.md +33 -0
  2. package/dist/frameworks/instructor.cjs +9 -0
  3. package/dist/frameworks/instructor.cjs.map +1 -1
  4. package/dist/frameworks/instructor.js +9 -0
  5. package/dist/frameworks/instructor.js.map +1 -1
  6. package/dist/frameworks/langchain.cjs +9 -0
  7. package/dist/frameworks/langchain.cjs.map +1 -1
  8. package/dist/frameworks/langchain.js +9 -0
  9. package/dist/frameworks/langchain.js.map +1 -1
  10. package/dist/frameworks/langgraph.cjs +9 -0
  11. package/dist/frameworks/langgraph.cjs.map +1 -1
  12. package/dist/frameworks/langgraph.js +9 -0
  13. package/dist/frameworks/langgraph.js.map +1 -1
  14. package/dist/frameworks/llamaindex.cjs +9 -0
  15. package/dist/frameworks/llamaindex.cjs.map +1 -1
  16. package/dist/frameworks/llamaindex.js +9 -0
  17. package/dist/frameworks/llamaindex.js.map +1 -1
  18. package/dist/index.cjs +667 -309
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +38 -2
  21. package/dist/index.d.ts +38 -2
  22. package/dist/index.js +667 -309
  23. package/dist/index.js.map +1 -1
  24. package/dist/providers/anthropic/index.cjs +9 -0
  25. package/dist/providers/anthropic/index.cjs.map +1 -1
  26. package/dist/providers/anthropic/index.js +9 -0
  27. package/dist/providers/anthropic/index.js.map +1 -1
  28. package/dist/providers/bedrock/index.cjs +9 -0
  29. package/dist/providers/bedrock/index.cjs.map +1 -1
  30. package/dist/providers/bedrock/index.js +9 -0
  31. package/dist/providers/bedrock/index.js.map +1 -1
  32. package/dist/providers/cerebras/index.cjs +9 -0
  33. package/dist/providers/cerebras/index.cjs.map +1 -1
  34. package/dist/providers/cerebras/index.js +9 -0
  35. package/dist/providers/cerebras/index.js.map +1 -1
  36. package/dist/providers/cohere/index.cjs +9 -0
  37. package/dist/providers/cohere/index.cjs.map +1 -1
  38. package/dist/providers/cohere/index.js +9 -0
  39. package/dist/providers/cohere/index.js.map +1 -1
  40. package/dist/providers/google/index.cjs +9 -0
  41. package/dist/providers/google/index.cjs.map +1 -1
  42. package/dist/providers/google/index.js +9 -0
  43. package/dist/providers/google/index.js.map +1 -1
  44. package/dist/providers/groq/index.cjs +9 -0
  45. package/dist/providers/groq/index.cjs.map +1 -1
  46. package/dist/providers/groq/index.js +9 -0
  47. package/dist/providers/groq/index.js.map +1 -1
  48. package/dist/providers/huggingface/index.cjs +9 -0
  49. package/dist/providers/huggingface/index.cjs.map +1 -1
  50. package/dist/providers/huggingface/index.js +9 -0
  51. package/dist/providers/huggingface/index.js.map +1 -1
  52. package/dist/providers/mistral/index.cjs +9 -0
  53. package/dist/providers/mistral/index.cjs.map +1 -1
  54. package/dist/providers/mistral/index.js +9 -0
  55. package/dist/providers/mistral/index.js.map +1 -1
  56. package/dist/providers/ollama/index.cjs +9 -0
  57. package/dist/providers/ollama/index.cjs.map +1 -1
  58. package/dist/providers/ollama/index.js +9 -0
  59. package/dist/providers/ollama/index.js.map +1 -1
  60. package/dist/providers/openai/index.cjs +9 -0
  61. package/dist/providers/openai/index.cjs.map +1 -1
  62. package/dist/providers/openai/index.js +9 -0
  63. package/dist/providers/openai/index.js.map +1 -1
  64. package/dist/providers/together/index.cjs +9 -0
  65. package/dist/providers/together/index.cjs.map +1 -1
  66. package/dist/providers/together/index.js +9 -0
  67. package/dist/providers/together/index.js.map +1 -1
  68. package/dist/providers/vercel-ai/index.cjs +9 -0
  69. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  70. package/dist/providers/vercel-ai/index.js +9 -0
  71. package/dist/providers/vercel-ai/index.js.map +1 -1
  72. package/package.json +2 -2
package/dist/index.cjs CHANGED
@@ -215,6 +215,59 @@ function applyMask(span, mask, onError) {
215
215
  }
216
216
  markMasked(span);
217
217
  }
218
+ var CONTENT_KEYS_EXACT = /* @__PURE__ */ new Set([
219
+ "gen_ai.system_prompt",
220
+ "gen_ai.prompt.message"
221
+ ]);
222
+ var CONTENT_OMITTED_MARKER = "<risicare:content-omitted>";
223
+ 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");
228
+ }
229
+ function stripAttributes(attrs) {
230
+ let n = 0;
231
+ for (const k of Object.keys(attrs)) {
232
+ if (isContentKey(k)) {
233
+ attrs[k] = CONTENT_OMITTED_MARKER;
234
+ n++;
235
+ }
236
+ }
237
+ return n;
238
+ }
239
+ function stripContent(span) {
240
+ let stripped = 0;
241
+ if (span.attributes && typeof span.attributes === "object") {
242
+ stripped += stripAttributes(span.attributes);
243
+ }
244
+ if (Array.isArray(span.events)) {
245
+ for (const event of span.events) {
246
+ if (event?.attributes && typeof event.attributes === "object") {
247
+ stripped += stripAttributes(event.attributes);
248
+ }
249
+ }
250
+ }
251
+ if (Array.isArray(span.links)) {
252
+ for (const link of span.links) {
253
+ if (link?.attributes && typeof link.attributes === "object") {
254
+ stripped += stripAttributes(link.attributes);
255
+ }
256
+ }
257
+ }
258
+ return stripped;
259
+ }
260
+ function stripContentBatch(spans) {
261
+ let total = 0;
262
+ for (const span of spans) {
263
+ try {
264
+ total += stripContent(span);
265
+ } catch {
266
+ debug("Could not strip content from a span");
267
+ }
268
+ }
269
+ return total;
270
+ }
218
271
  function applyMaskBatch(spans, mask, onError) {
219
272
  let errors = 0;
220
273
  let firstKey;
@@ -327,7 +380,14 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
327
380
  _batchSize;
328
381
  _batchTimeoutMs;
329
382
  _maxQueueSize;
330
- _debug;
383
+ // ⚠ NO `_debug` FIELD. It existed, was assigned, and was read by NOTHING —
384
+ // `tsc --noEmit` had been RED on this package at HEAD for it (TS6133), which
385
+ // survived because `ci-local.sh` runs this package's vitest and never its
386
+ // typecheck, and `prepublishOnly` runs `build && test` — also no typecheck.
387
+ // Filed F-SDKJSTYPECHECK-001. Debug output here is gated globally by
388
+ // `setDebug()` in `../utils/log.ts`, so a per-processor flag was always
389
+ // redundant; Python's `self._debug` exists because `logging` has no such
390
+ // global switch.
331
391
  _queue = [];
332
392
  _timer = null;
333
393
  _started = false;
@@ -339,6 +399,12 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
339
399
  _lastRefusalWarnAt = Number.NEGATIVE_INFINITY;
340
400
  // ── Masking (see `../masking.ts`) ──────────────────────────────────────────
341
401
  _mask;
402
+ // ── Content capture gate (see `../masking.ts`) ─────────────────────────────
403
+ // Fail-closed: an unspecified value means "do not capture". This is the ONE
404
+ // place the gate runs for BOTH content paths — provider capture AND hand-set
405
+ // attributes — so it must not be conditional on anything a caller might
406
+ // forget to pass. Python twin: `BatchSpanProcessor._trace_content`.
407
+ _traceContent;
342
408
  _lastMaskWarnAt = Number.NEGATIVE_INFINITY;
343
409
  _lastSlowMaskWarnAt = Number.NEGATIVE_INFINITY;
344
410
  // Metrics
@@ -376,8 +442,8 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
376
442
  this._batchSize = clampedBatchSize;
377
443
  this._batchTimeoutMs = options.batchTimeoutMs ?? 1e3;
378
444
  this._maxQueueSize = options.maxQueueSize ?? 1e4;
379
- this._debug = options.debug ?? false;
380
445
  this._mask = options.mask;
446
+ this._traceContent = options.traceContent ?? false;
381
447
  }
382
448
  start() {
383
449
  if (this._started) return;
@@ -574,6 +640,14 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
574
640
  }
575
641
  const batch = this._queue.splice(0, take);
576
642
  if (batch.length === 0) return 0 /* Empty */;
643
+ if (!this._traceContent) {
644
+ const stripped = stripContentBatch(batch);
645
+ if (stripped > 0) {
646
+ debug(
647
+ `traceContent is off \u2014 omitted ${stripped} content field(s) from ${batch.length} span(s)`
648
+ );
649
+ }
650
+ }
577
651
  if (this._mask !== void 0) {
578
652
  this._applyMask(batch);
579
653
  }
@@ -647,7 +721,7 @@ function resolveConfig(config) {
647
721
  const environment = config?.environment ?? env.RISICARE_ENVIRONMENT ?? "development";
648
722
  const serviceName = config?.serviceName ?? env.RISICARE_SERVICE_NAME;
649
723
  const serviceVersion = config?.serviceVersion ?? env.RISICARE_SERVICE_VERSION;
650
- const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, true);
724
+ const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, false);
651
725
  const sampleRateRaw = config?.sampleRate ?? parseFloat(env.RISICARE_SAMPLE_RATE ?? "1.0");
652
726
  const debug2 = config?.debug ?? parseBool(env.RISICARE_DEBUG, false);
653
727
  const compress = config?.compress ?? parseBool(env.RISICARE_COMPRESS, false);
@@ -655,6 +729,11 @@ function resolveConfig(config) {
655
729
  const batchTimeoutMsRaw = config?.batchTimeoutMs ?? parseNumericEnv(env.RISICARE_BATCH_TIMEOUT_MS, 1e3);
656
730
  const maxQueueSizeRaw = config?.maxQueueSize ?? parseNumericEnv(env.RISICARE_MAX_QUEUE_SIZE, 1e4);
657
731
  const sampleRate = validateSampleRate(sampleRateRaw);
732
+ if (sampleRate < 1) {
733
+ console.warn(
734
+ `[risicare] sampleRate=${sampleRate} \u2014 head sampling is applied in-process and the rate is NOT transmitted to the platform. Trace counts, error rates and cost figures in the dashboard will describe the sampled subset only, and cannot be scaled back to totals. Sampling is trace-coherent: a dropped trace drops whole.`
735
+ );
736
+ }
658
737
  const batchSize = validatePositiveInt("batchSize", batchSizeRaw, DEFAULT_BATCH_SIZE, 1, 1e4);
659
738
  const batchTimeoutMs = validatePositiveInt("batchTimeoutMs", batchTimeoutMsRaw, 1e3, 1, 6e5);
660
739
  const maxQueueSize = validatePositiveInt("maxQueueSize", maxQueueSizeRaw, 1e4, 1, 1e6);
@@ -1094,6 +1173,444 @@ function shouldSample(traceId, sampleRate) {
1094
1173
  return hash / 4294967295 < sampleRate;
1095
1174
  }
1096
1175
 
1176
+ // src/runtime/config.ts
1177
+ function resolveFixRuntimeConfig(config) {
1178
+ return {
1179
+ apiEndpoint: config.apiEndpoint,
1180
+ apiKey: config.apiKey,
1181
+ enabled: config.enabled ?? true,
1182
+ cacheEnabled: config.cacheEnabled ?? true,
1183
+ cacheTtlMs: config.cacheTtlMs ?? 3e5,
1184
+ cacheMaxEntries: config.cacheMaxEntries ?? 1e3,
1185
+ autoRefresh: config.autoRefresh ?? true,
1186
+ refreshIntervalMs: config.refreshIntervalMs ?? 6e4,
1187
+ dryRun: config.dryRun ?? false,
1188
+ abTestingEnabled: config.abTestingEnabled ?? true,
1189
+ timeoutMs: config.timeoutMs ?? 1e3,
1190
+ debug: config.debug ?? false
1191
+ };
1192
+ }
1193
+ function matchesError(fix, errorCode) {
1194
+ if (fix.errorCode === errorCode) {
1195
+ return true;
1196
+ }
1197
+ if (fix.errorCode.endsWith("*")) {
1198
+ const prefix = fix.errorCode.slice(0, -1);
1199
+ return errorCode.startsWith(prefix);
1200
+ }
1201
+ return false;
1202
+ }
1203
+ function shouldApply(fix, sessionHash) {
1204
+ if (fix.trafficPercentage >= 100) return true;
1205
+ if (fix.trafficPercentage <= 0) return false;
1206
+ const bucket = sessionHash % 100;
1207
+ return bucket < fix.trafficPercentage;
1208
+ }
1209
+ function activeFixFromApiResponse(item) {
1210
+ return {
1211
+ fixId: item.id ?? item.fix_id ?? item.fixId ?? "",
1212
+ deploymentId: item.deployment_id ?? item.deploymentId ?? "",
1213
+ errorCode: item.error_code ?? item.errorCode ?? "",
1214
+ fixType: item.fix_type ?? item.fixType ?? "prompt",
1215
+ config: item.config ?? {},
1216
+ trafficPercentage: item.traffic_percentage ?? item.trafficPercentage ?? 100,
1217
+ version: item.version ?? 1
1218
+ };
1219
+ }
1220
+
1221
+ // src/runtime/taxonomy.generated.ts
1222
+ var CANONICAL_ERROR_CODES = /* @__PURE__ */ new Set([
1223
+ "COMMUNICATION.CONTENT.AMBIGUOUS",
1224
+ "COMMUNICATION.CONTENT.CORRUPTED",
1225
+ "COMMUNICATION.CONTENT.INCOMPATIBLE",
1226
+ "COMMUNICATION.CONTENT.MALFORMED",
1227
+ "COMMUNICATION.CONTENT.TOO_LARGE",
1228
+ "COMMUNICATION.DELIVERY.DELAYED",
1229
+ "COMMUNICATION.DELIVERY.DUPLICATED",
1230
+ "COMMUNICATION.DELIVERY.EXPIRED",
1231
+ "COMMUNICATION.DELIVERY.OUT_OF_ORDER",
1232
+ "COMMUNICATION.DELIVERY.UNDELIVERABLE",
1233
+ "COMMUNICATION.ROUTING.BROADCAST_STORM",
1234
+ "COMMUNICATION.ROUTING.LOOP",
1235
+ "COMMUNICATION.ROUTING.NO_ROUTE",
1236
+ "COMMUNICATION.ROUTING.PARTITION",
1237
+ "COMMUNICATION.ROUTING.WRONG_ROUTE",
1238
+ "CONSENSUS.AGREEMENT.INCONSISTENT",
1239
+ "CONSENSUS.AGREEMENT.QUORUM_FAILED",
1240
+ "CONSENSUS.AGREEMENT.REJECTED",
1241
+ "CONSENSUS.AGREEMENT.STALE_VOTE",
1242
+ "CONSENSUS.AGREEMENT.TIMEOUT",
1243
+ "CONSENSUS.CONFLICT.BIAS",
1244
+ "CONSENSUS.CONFLICT.CASCADING",
1245
+ "CONSENSUS.CONFLICT.DEADLOCK",
1246
+ "CONSENSUS.CONFLICT.RESOLUTION_REJECTED",
1247
+ "CONSENSUS.CONFLICT.UNRESOLVED",
1248
+ "CONSENSUS.VOTING.ABSTENTION_FLOOD",
1249
+ "CONSENSUS.VOTING.COERCED_VOTE",
1250
+ "CONSENSUS.VOTING.DUPLICATE_VOTE",
1251
+ "CONSENSUS.VOTING.INVALID_VOTE",
1252
+ "CONSENSUS.VOTING.SPLIT_VOTE",
1253
+ "COORDINATION.HANDOFF.DELAYED",
1254
+ "COORDINATION.HANDOFF.DUPLICATED",
1255
+ "COORDINATION.HANDOFF.INCOMPLETE",
1256
+ "COORDINATION.HANDOFF.LOST",
1257
+ "COORDINATION.HANDOFF.WRONG_RECIPIENT",
1258
+ "COORDINATION.SYNCHRONIZATION.CLOCK_SKEW",
1259
+ "COORDINATION.SYNCHRONIZATION.OUT_OF_ORDER",
1260
+ "COORDINATION.SYNCHRONIZATION.RACE_CONDITION",
1261
+ "COORDINATION.SYNCHRONIZATION.SPLIT_BRAIN",
1262
+ "COORDINATION.SYNCHRONIZATION.VERSION_MISMATCH",
1263
+ "COORDINATION.WORKFLOW.CYCLE",
1264
+ "COORDINATION.WORKFLOW.DEADLOCK",
1265
+ "COORDINATION.WORKFLOW.LIVELOCK",
1266
+ "COORDINATION.WORKFLOW.ORPHANED",
1267
+ "COORDINATION.WORKFLOW.STARVATION",
1268
+ "MEMORY.CONTEXT_WINDOW.DROPPED",
1269
+ "MEMORY.CONTEXT_WINDOW.EXCEEDED",
1270
+ "MEMORY.CONTEXT_WINDOW.FRAGMENTED",
1271
+ "MEMORY.CONTEXT_WINDOW.PRIORITY_ERROR",
1272
+ "MEMORY.RETRIEVAL.INCOMPLETE",
1273
+ "MEMORY.RETRIEVAL.NOT_FOUND",
1274
+ "MEMORY.RETRIEVAL.OUTDATED",
1275
+ "MEMORY.RETRIEVAL.TOO_MANY",
1276
+ "MEMORY.RETRIEVAL.WRONG_MATCH",
1277
+ "MEMORY.STATE.CORRUPTED",
1278
+ "MEMORY.STATE.INCONSISTENT",
1279
+ "MEMORY.STATE.LOST",
1280
+ "MEMORY.STATE.OVERFLOW",
1281
+ "MEMORY.STATE.STALE",
1282
+ "ORCHESTRATION.DELEGATION.CAPABILITY_MISMATCH",
1283
+ "ORCHESTRATION.DELEGATION.CIRCULAR_DELEGATION",
1284
+ "ORCHESTRATION.DELEGATION.EXCESSIVE_DEPTH",
1285
+ "ORCHESTRATION.DELEGATION.NO_AVAILABLE_AGENT",
1286
+ "ORCHESTRATION.DELEGATION.OVERLOADED_AGENT",
1287
+ "ORCHESTRATION.LIFECYCLE.CLEANUP_FAILED",
1288
+ "ORCHESTRATION.LIFECYCLE.CRASHED",
1289
+ "ORCHESTRATION.LIFECYCLE.HUNG",
1290
+ "ORCHESTRATION.LIFECYCLE.SPAWN_FAILED",
1291
+ "ORCHESTRATION.LIFECYCLE.ZOMBIE",
1292
+ "ORCHESTRATION.SCALING.OVERLOADED",
1293
+ "ORCHESTRATION.SCALING.QUOTA_EXCEEDED",
1294
+ "ORCHESTRATION.SCALING.SCALE_DOWN_FAILED",
1295
+ "ORCHESTRATION.SCALING.SCALE_UP_FAILED",
1296
+ "ORCHESTRATION.SCALING.UNDERUTILIZED",
1297
+ "OUTPUT.FORMAT.ENCODING",
1298
+ "OUTPUT.FORMAT.INVALID_JSON",
1299
+ "OUTPUT.FORMAT.MALFORMED",
1300
+ "OUTPUT.FORMAT.SCHEMA_VIOLATION",
1301
+ "OUTPUT.FORMAT.TRUNCATED",
1302
+ "OUTPUT.QUALITY.INCOMPLETE",
1303
+ "OUTPUT.QUALITY.IRRELEVANT",
1304
+ "OUTPUT.QUALITY.REPETITIVE",
1305
+ "OUTPUT.QUALITY.UNCLEAR",
1306
+ "OUTPUT.QUALITY.VERBOSE",
1307
+ "OUTPUT.SAFETY.BIAS",
1308
+ "OUTPUT.SAFETY.COPYRIGHT",
1309
+ "OUTPUT.SAFETY.HARMFUL_CONTENT",
1310
+ "OUTPUT.SAFETY.PII_LEAK",
1311
+ "OUTPUT.SAFETY.POLICY_VIOLATION",
1312
+ "PERCEPTION.CONTEXT.CONFLICTING",
1313
+ "PERCEPTION.CONTEXT.IRRELEVANT",
1314
+ "PERCEPTION.CONTEXT.MISSING",
1315
+ "PERCEPTION.CONTEXT.OVERFLOW",
1316
+ "PERCEPTION.CONTEXT.STALE",
1317
+ "PERCEPTION.INPUT.ENCODING",
1318
+ "PERCEPTION.INPUT.INJECTION",
1319
+ "PERCEPTION.INPUT.MALFORMED",
1320
+ "PERCEPTION.INPUT.SCHEMA_MISMATCH",
1321
+ "PERCEPTION.INPUT.TRUNCATED",
1322
+ "PERCEPTION.PARSING.DATE_FORMAT",
1323
+ "PERCEPTION.PARSING.JSON_INVALID",
1324
+ "PERCEPTION.PARSING.NUMBER_FORMAT",
1325
+ "PERCEPTION.PARSING.REFERENCE_BROKEN",
1326
+ "PERCEPTION.PARSING.XML_INVALID",
1327
+ "REASONING.DECISION.BIASED",
1328
+ "REASONING.DECISION.INDECISIVE",
1329
+ "REASONING.DECISION.OSCILLATING",
1330
+ "REASONING.DECISION.OVERCONFIDENT",
1331
+ "REASONING.DECISION.PREMATURE",
1332
+ "REASONING.HALLUCINATION.CAPABILITY",
1333
+ "REASONING.HALLUCINATION.CITATION",
1334
+ "REASONING.HALLUCINATION.ENTITY",
1335
+ "REASONING.HALLUCINATION.FACTUAL",
1336
+ "REASONING.HALLUCINATION.TEMPORAL",
1337
+ "REASONING.LOGIC.CIRCULAR",
1338
+ "REASONING.LOGIC.CONTRADICTION",
1339
+ "REASONING.LOGIC.INCOMPLETE",
1340
+ "REASONING.LOGIC.INVALID_INFERENCE",
1341
+ "REASONING.LOGIC.MISSING_PREMISE",
1342
+ "REASONING.PLANNING.INCOMPLETE",
1343
+ "REASONING.PLANNING.INFEASIBLE",
1344
+ "REASONING.PLANNING.SCOPE_CREEP",
1345
+ "REASONING.PLANNING.SUBOPTIMAL",
1346
+ "REASONING.PLANNING.UNSAFE",
1347
+ "RESOURCES.ACCESS.DENIED",
1348
+ "RESOURCES.ACCESS.EXPIRED",
1349
+ "RESOURCES.ACCESS.LOCKED",
1350
+ "RESOURCES.ACCESS.NOT_FOUND",
1351
+ "RESOURCES.ACCESS.REVOKED",
1352
+ "RESOURCES.CONTENTION.DEADLOCK",
1353
+ "RESOURCES.CONTENTION.OVERFLOW",
1354
+ "RESOURCES.CONTENTION.PRIORITY_INVERSION",
1355
+ "RESOURCES.CONTENTION.STARVATION",
1356
+ "RESOURCES.CONTENTION.THRASHING",
1357
+ "RESOURCES.QUOTA.ALLOCATION_FAILED",
1358
+ "RESOURCES.QUOTA.EXCEEDED",
1359
+ "RESOURCES.QUOTA.LEAK",
1360
+ "RESOURCES.QUOTA.STALE",
1361
+ "RESOURCES.QUOTA.UNFAIR_DISTRIBUTION",
1362
+ "TOOL.EXECUTION.CRASHED",
1363
+ "TOOL.EXECUTION.DEPENDENCY_FAILED",
1364
+ "TOOL.EXECUTION.RATE_LIMITED",
1365
+ "TOOL.EXECUTION.RESOURCE_EXHAUSTED",
1366
+ "TOOL.EXECUTION.TIMEOUT",
1367
+ "TOOL.INVOCATION.INVALID_ARGS",
1368
+ "TOOL.INVOCATION.MISSING_REQUIRED",
1369
+ "TOOL.INVOCATION.NOT_FOUND",
1370
+ "TOOL.INVOCATION.PERMISSION_DENIED",
1371
+ "TOOL.INVOCATION.TYPE_MISMATCH",
1372
+ "TOOL.RESULT.EMPTY",
1373
+ "TOOL.RESULT.ERROR_IN_RESULT",
1374
+ "TOOL.RESULT.PARTIAL",
1375
+ "TOOL.RESULT.UNEXPECTED_FORMAT",
1376
+ "TOOL.RESULT.UNPARSEABLE"
1377
+ ]);
1378
+ var SUPPLEMENTAL_RULES = [
1379
+ { re: new RegExp("timeout|timedout|aborted", "i"), code: "TOOL.EXECUTION.TIMEOUT" },
1380
+ { re: new RegExp("rate.?limit|\\b429\\b|too many requests", "i"), code: "TOOL.EXECUTION.RATE_LIMITED" },
1381
+ { re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "i"), code: "TOOL.EXECUTION.DEPENDENCY_FAILED" },
1382
+ { re: new RegExp("\\bauth|unauthorized|forbidden|permission|\\b401\\b|\\b403\\b", "i"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
1383
+ { re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "i"), code: "PERCEPTION.PARSING.JSON_INVALID" }
1384
+ ];
1385
+ var GENERIC_FALLBACK = "TOOL.EXECUTION.CRASHED";
1386
+
1387
+ // src/runtime/interceptors.ts
1388
+ var GuardRejectedError = class extends Error {
1389
+ guardId;
1390
+ reason;
1391
+ phase;
1392
+ constructor(guardId, reason, phase) {
1393
+ super(`Risicare guard rejected operation: ${guardId} (${phase}) \u2014 ${reason}`);
1394
+ this.name = "GuardRejectedError";
1395
+ this.guardId = guardId;
1396
+ this.reason = reason;
1397
+ this.phase = phase;
1398
+ }
1399
+ };
1400
+ function createInterceptContext(operationType, operationName, options) {
1401
+ return {
1402
+ operationType,
1403
+ operationName,
1404
+ sessionId: options?.sessionId,
1405
+ traceId: options?.traceId,
1406
+ errorCode: options?.errorCode,
1407
+ attempt: 1,
1408
+ appliedFixes: []
1409
+ };
1410
+ }
1411
+ var DefaultFixInterceptor = class {
1412
+ _config;
1413
+ _cache;
1414
+ _applier;
1415
+ constructor(config, cache, applier) {
1416
+ this._config = resolveFixRuntimeConfig(config);
1417
+ this._cache = cache;
1418
+ this._applier = applier;
1419
+ }
1420
+ /**
1421
+ * Apply pre-call fixes.
1422
+ *
1423
+ * - If retrying after error: look up fix by error_code, apply
1424
+ * prompt/parameter/fallback fixes
1425
+ * - Runs input guard fixes on all message content
1426
+ */
1427
+ preCall(ctx, messages, params) {
1428
+ try {
1429
+ if (!this._config.enabled) {
1430
+ return { messages, params };
1431
+ }
1432
+ let modifiedMessages = messages;
1433
+ let modifiedParams = { ...params };
1434
+ if (ctx.errorCode) {
1435
+ const fix = this._applier.getFixForError(ctx.errorCode, ctx.sessionId);
1436
+ if (fix) {
1437
+ debug(`Applying fix ${fix.fixId} for ${ctx.errorCode}`);
1438
+ if (fix.fixType === "prompt" && messages) {
1439
+ const msgRecords = messages;
1440
+ const { messages: newMessages, result } = this._applier.applyPromptFix(fix, msgRecords);
1441
+ modifiedMessages = newMessages;
1442
+ ctx.appliedFixes.push(result);
1443
+ this._applier.logApplication(result);
1444
+ } else if (fix.fixType === "parameter") {
1445
+ const { params: newParams, result } = this._applier.applyParameterFix(fix, modifiedParams);
1446
+ modifiedParams = newParams;
1447
+ ctx.appliedFixes.push(result);
1448
+ this._applier.logApplication(result);
1449
+ } else if (fix.fixType === "fallback") {
1450
+ const { params: newParams, result } = this._applier.applyFallbackFix(fix, modifiedParams);
1451
+ modifiedParams = newParams;
1452
+ ctx.appliedFixes.push(result);
1453
+ this._applier.logApplication(result);
1454
+ }
1455
+ }
1456
+ }
1457
+ if (modifiedMessages && this._config.enabled) {
1458
+ for (const msg of modifiedMessages) {
1459
+ const content = msg.content;
1460
+ if (typeof content === "string") {
1461
+ for (const fix of this._cache.getAll()) {
1462
+ if (fix.fixType === "guard") {
1463
+ const { passed, result } = this._applier.applyGuardFix(
1464
+ fix,
1465
+ content,
1466
+ true
1467
+ );
1468
+ if (result.applied) {
1469
+ ctx.appliedFixes.push(result);
1470
+ this._applier.logApplication(result);
1471
+ }
1472
+ if (!passed) {
1473
+ throw new GuardRejectedError(
1474
+ fix.fixId ?? "unknown",
1475
+ result.reason ?? "guard rejected input",
1476
+ "pre_call"
1477
+ );
1478
+ }
1479
+ }
1480
+ }
1481
+ }
1482
+ }
1483
+ }
1484
+ return { messages: modifiedMessages, params: modifiedParams };
1485
+ } catch (e) {
1486
+ if (e instanceof GuardRejectedError) throw e;
1487
+ debug(`DefaultFixInterceptor.preCall error: ${e}`);
1488
+ return { messages, params };
1489
+ }
1490
+ }
1491
+ /**
1492
+ * Apply post-call fixes (output validation).
1493
+ *
1494
+ * Runs output guard fixes on response content.
1495
+ */
1496
+ postCall(ctx, response) {
1497
+ try {
1498
+ if (!this._config.enabled) {
1499
+ return { response, shouldContinue: true };
1500
+ }
1501
+ for (const fix of this._cache.getAll()) {
1502
+ if (fix.fixType !== "guard") continue;
1503
+ const content = this._extractResponseContent(response);
1504
+ if (!content) continue;
1505
+ const { passed, result } = this._applier.applyGuardFix(
1506
+ fix,
1507
+ content,
1508
+ false
1509
+ );
1510
+ if (result.applied) {
1511
+ ctx.appliedFixes.push(result);
1512
+ this._applier.logApplication(result);
1513
+ }
1514
+ if (!passed) {
1515
+ warn(`Output guard failed for fix ${fix.fixId}: ${result.reason ?? "unknown"}`);
1516
+ throw new GuardRejectedError(
1517
+ fix.fixId ?? "unknown",
1518
+ result.reason ?? "guard rejected output",
1519
+ "post_call"
1520
+ );
1521
+ }
1522
+ }
1523
+ return { response, shouldContinue: true };
1524
+ } catch (e) {
1525
+ if (e instanceof GuardRejectedError) throw e;
1526
+ debug(`DefaultFixInterceptor.postCall error: ${e}`);
1527
+ return { response, shouldContinue: true };
1528
+ }
1529
+ }
1530
+ /**
1531
+ * Handle errors and decide whether to retry.
1532
+ *
1533
+ * Classifies the error, looks up retry/fallback fixes, and returns
1534
+ * whether the caller should retry.
1535
+ */
1536
+ onError(ctx, error) {
1537
+ try {
1538
+ if (!this._config.enabled) {
1539
+ return { shouldRetry: false, modifiedParams: null };
1540
+ }
1541
+ const errorCode = classifyError(error);
1542
+ ctx.errorCode = errorCode;
1543
+ ctx.errorMessage = error.message;
1544
+ const fix = this._applier.getFixForError(errorCode, ctx.sessionId);
1545
+ if (!fix) {
1546
+ return { shouldRetry: false, modifiedParams: null };
1547
+ }
1548
+ if (fix.fixType === "retry") {
1549
+ const maxRetries = fix.config.max_retries ?? fix.config.maxRetries ?? 3;
1550
+ if (ctx.attempt <= maxRetries) {
1551
+ debug(
1552
+ `Retry fix ${fix.fixId}: attempt ${ctx.attempt}/${maxRetries}`
1553
+ );
1554
+ const result = {
1555
+ applied: true,
1556
+ fixId: fix.fixId,
1557
+ deploymentId: fix.deploymentId,
1558
+ fixType: "retry",
1559
+ modifications: { attempt: ctx.attempt }
1560
+ };
1561
+ ctx.appliedFixes.push(result);
1562
+ this._applier.logApplication(result);
1563
+ return { shouldRetry: true, modifiedParams: null };
1564
+ }
1565
+ }
1566
+ if (fix.fixType === "fallback") {
1567
+ const { params: modifiedParams, result } = this._applier.applyFallbackFix(fix, {});
1568
+ if (result.applied) {
1569
+ ctx.appliedFixes.push(result);
1570
+ this._applier.logApplication(result);
1571
+ return { shouldRetry: true, modifiedParams };
1572
+ }
1573
+ }
1574
+ return { shouldRetry: false, modifiedParams: null };
1575
+ } catch (e) {
1576
+ debug(`DefaultFixInterceptor.onError error: ${e}`);
1577
+ return { shouldRetry: false, modifiedParams: null };
1578
+ }
1579
+ }
1580
+ // ─── Private ────────────────────────────────────────────────────────────
1581
+ /** Extract text content from a response object. */
1582
+ _extractResponseContent(response) {
1583
+ if (typeof response === "string") return response;
1584
+ if (response && typeof response === "object") {
1585
+ const resp = response;
1586
+ const choices = resp.choices;
1587
+ if (Array.isArray(choices) && choices.length > 0) {
1588
+ const first = choices[0];
1589
+ const message = first?.message;
1590
+ if (typeof message?.content === "string") {
1591
+ return message.content;
1592
+ }
1593
+ }
1594
+ const content = resp.content;
1595
+ if (typeof content === "string") return content;
1596
+ if (Array.isArray(content) && content.length > 0) {
1597
+ const first = content[0];
1598
+ if (typeof first?.text === "string") return first.text;
1599
+ }
1600
+ }
1601
+ return null;
1602
+ }
1603
+ };
1604
+ function classifyError(error) {
1605
+ const haystack = `${error?.constructor?.name ?? "Error"} ${error?.message ?? ""}`;
1606
+ for (const rule of SUPPLEMENTAL_RULES) {
1607
+ if (rule.re.test(haystack)) {
1608
+ return CANONICAL_ERROR_CODES.has(rule.code) ? rule.code : GENERIC_FALLBACK;
1609
+ }
1610
+ }
1611
+ return CANONICAL_ERROR_CODES.has(GENERIC_FALLBACK) ? GENERIC_FALLBACK : "";
1612
+ }
1613
+
1097
1614
  // src/context/storage.ts
1098
1615
  function storage() {
1099
1616
  return getContextStorage();
@@ -1155,16 +1672,30 @@ function getCurrentContext() {
1155
1672
  }
1156
1673
 
1157
1674
  // src/tracer.ts
1675
+ function attachErrorCode(span, error) {
1676
+ try {
1677
+ const err = error instanceof Error ? error : new Error(String(error));
1678
+ const code = classifyError(err);
1679
+ if (code) {
1680
+ span.setAttribute("error.code", code);
1681
+ }
1682
+ } catch {
1683
+ }
1684
+ }
1158
1685
  var Tracer = class {
1159
1686
  _onSpanEnd;
1160
1687
  _sampleRate;
1161
1688
  _enabled;
1162
1689
  _traceContent;
1690
+ _serviceName;
1691
+ _serviceVersion;
1163
1692
  constructor(config) {
1164
1693
  this._onSpanEnd = config.onSpanEnd;
1165
1694
  this._sampleRate = config.sampleRate ?? 1;
1166
1695
  this._enabled = config.enabled ?? true;
1167
- this._traceContent = config.traceContent ?? true;
1696
+ this._traceContent = config.traceContent ?? false;
1697
+ this._serviceName = config.serviceName || void 0;
1698
+ this._serviceVersion = config.serviceVersion || void 0;
1168
1699
  }
1169
1700
  get enabled() {
1170
1701
  return this._enabled;
@@ -1198,10 +1729,16 @@ var Tracer = class {
1198
1729
  const phase = getCurrentPhase();
1199
1730
  const ctx = getContext();
1200
1731
  const traceId = opts.traceId ?? parentSpan?.traceId ?? ctx._rootTraceId ?? generateTraceId();
1201
- if (!parentSpan && this._sampleRate < 1) {
1202
- if (!shouldSample(traceId, this._sampleRate)) {
1732
+ if (!parentSpan) {
1733
+ if (ctx._traceSampled === false) {
1203
1734
  return fn(NOOP_SPAN);
1204
1735
  }
1736
+ if (this._sampleRate < 1 && !shouldSample(traceId, this._sampleRate)) {
1737
+ return runWithContext(
1738
+ { _traceSampled: false },
1739
+ () => fn(NOOP_SPAN)
1740
+ );
1741
+ }
1205
1742
  }
1206
1743
  const parentSpanId = opts.parentSpanId ?? parentSpan?.spanId;
1207
1744
  const spanOptions = {
@@ -1214,7 +1751,12 @@ var Tracer = class {
1214
1751
  // Propagate context fields as attributes (matching Python SDK tracer.py:497-511)
1215
1752
  ...agent2?.agentRole ? { "agent.role": agent2.agentRole } : {},
1216
1753
  ...agent2?.parentAgentId ? { "parent_agent_id": agent2.parentAgentId } : {},
1217
- ...session2?.userId ? { "session.user_id": session2.userId } : {}
1754
+ ...session2?.userId ? { "session.user_id": session2.userId } : {},
1755
+ // F-SDKJSSVCNAME-001 — `service.name` is suppressed when an agent
1756
+ // identity is present (the agent takes priority), matching Python;
1757
+ // `service.version` never is.
1758
+ ...this._serviceName && !agent2 ? { "service.name": this._serviceName } : {},
1759
+ ...this._serviceVersion ? { "service.version": this._serviceVersion } : {}
1218
1760
  },
1219
1761
  sessionId: session2?.sessionId,
1220
1762
  agentId: agent2?.agentId,
@@ -1233,6 +1775,7 @@ var Tracer = class {
1233
1775
  },
1234
1776
  (error) => {
1235
1777
  span.recordException(error instanceof Error ? error : String(error));
1778
+ attachErrorCode(span, error);
1236
1779
  span.end();
1237
1780
  throw error;
1238
1781
  }
@@ -1242,6 +1785,7 @@ var Tracer = class {
1242
1785
  return result;
1243
1786
  } catch (error) {
1244
1787
  span.recordException(error instanceof Error ? error : String(error));
1788
+ attachErrorCode(span, error);
1245
1789
  span.end();
1246
1790
  throw error;
1247
1791
  }
@@ -1262,8 +1806,11 @@ var Tracer = class {
1262
1806
  const agent2 = getCurrentAgent();
1263
1807
  const phase = getCurrentPhase();
1264
1808
  const traceId = opts.traceId ?? parentSpan?.traceId ?? generateTraceId();
1265
- if (!parentSpan && this._sampleRate < 1) {
1266
- if (!shouldSample(traceId, this._sampleRate)) {
1809
+ if (!parentSpan) {
1810
+ if (getContext()._traceSampled === false) {
1811
+ return NOOP_SPAN;
1812
+ }
1813
+ if (this._sampleRate < 1 && !shouldSample(traceId, this._sampleRate)) {
1267
1814
  return NOOP_SPAN;
1268
1815
  }
1269
1816
  }
@@ -1279,7 +1826,10 @@ var Tracer = class {
1279
1826
  // Propagate context fields as attributes (matching Python SDK tracer.py:497-511)
1280
1827
  ...agent2?.agentRole ? { "agent.role": agent2.agentRole } : {},
1281
1828
  ...agent2?.parentAgentId ? { "parent_agent_id": agent2.parentAgentId } : {},
1282
- ...session2?.userId ? { "session.user_id": session2.userId } : {}
1829
+ ...session2?.userId ? { "session.user_id": session2.userId } : {},
1830
+ // F-SDKJSSVCNAME-001 — see the sibling site above.
1831
+ ...this._serviceName && !agent2 ? { "service.name": this._serviceName } : {},
1832
+ ...this._serviceVersion ? { "service.version": this._serviceVersion } : {}
1283
1833
  },
1284
1834
  sessionId: session2?.sessionId,
1285
1835
  agentId: agent2?.agentId,
@@ -1293,9 +1843,13 @@ var Tracer = class {
1293
1843
  };
1294
1844
 
1295
1845
  // src/version.ts
1296
- var SDK_VERSION = "0.5.0";
1846
+ var SDK_VERSION = "0.5.2";
1297
1847
 
1298
1848
  // src/exporters/http.ts
1849
+ var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
1850
+ var RETRY_AFTER_CEILING_MS = 1e4;
1851
+ var REFUSAL_BACKOFF_BASE_MS = 1e3;
1852
+ var REFUSAL_NO_HINT = -1;
1299
1853
  var HttpExporter = class {
1300
1854
  name = "http";
1301
1855
  _endpoint;
@@ -1311,6 +1865,18 @@ var HttpExporter = class {
1311
1865
  // cooldown gives the gateway time to come back before the half-open
1312
1866
  // probe fires. Lower numbers (was 3@30s) tripped on transient blips.
1313
1867
  _consecutiveFailures = 0;
1868
+ /**
1869
+ * F-SDK503-001. Set by `_sendRequest` when a response is a CAPACITY REFUSAL, read by the
1870
+ * retry loop and the breaker. `null` = not a refusal; `REFUSAL_NO_HINT` = refused with no
1871
+ * `Retry-After`; otherwise the honoured delay in ms.
1872
+ *
1873
+ * ⚠ Node has ONE thread and `export()` is `async`, so two concurrent exports interleave on
1874
+ * this field at every `await`. It is written immediately after the awaited `fetch` resolves
1875
+ * and read on the very next statement, with no `await` between — so the value cannot be
1876
+ * clobbered mid-decision. The Python twin carries the same per-call state on `self` for the
1877
+ * same reason (its `_send_request` signature is pin-locked).
1878
+ */
1879
+ _lastRefusalAfterMs = null;
1314
1880
  _circuitOpenUntil = 0;
1315
1881
  _circuitBreakerThreshold = 5;
1316
1882
  _circuitBreakerCooldownMs = 6e4;
@@ -1340,15 +1906,26 @@ var HttpExporter = class {
1340
1906
  if (this._environment) body.environment = this._environment;
1341
1907
  const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
1342
1908
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1909
+ this._lastRefusalAfterMs = null;
1343
1910
  const result = await this._sendRequest(body);
1344
1911
  if (result === "success" /* SUCCESS */) {
1345
1912
  this._consecutiveFailures = 0;
1346
1913
  return result;
1347
1914
  }
1348
1915
  if (attempt < maxAttempts - 1) {
1349
- await sleep(100 * Math.pow(2, attempt));
1916
+ const refusal = this._lastRefusalAfterMs;
1917
+ const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
1918
+ await sleep(delay);
1350
1919
  }
1351
1920
  }
1921
+ const refusedForCapacity = this._lastRefusalAfterMs !== null;
1922
+ this._lastRefusalAfterMs = null;
1923
+ if (refusedForCapacity) {
1924
+ warn(
1925
+ `Risicare: the ingest endpoint refused this batch for capacity (HTTP 429/503) after ${maxAttempts} attempt(s). This is a healthy server shedding load, not an outage \u2014 the batch is dropped but the exporter keeps sending. Reduce batch size or export rate if it persists.`
1926
+ );
1927
+ return "failure" /* FAILURE */;
1928
+ }
1352
1929
  this._consecutiveFailures++;
1353
1930
  if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
1354
1931
  this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
@@ -1358,6 +1935,26 @@ var HttpExporter = class {
1358
1935
  }
1359
1936
  return "failure" /* FAILURE */;
1360
1937
  }
1938
+ /**
1939
+ * Record a CAPACITY REFUSAL for the retry loop. Returns true if it was one.
1940
+ *
1941
+ * `Retry-After` is honoured only in its delta-seconds form (RFC 9110 §10.2.3 also permits an
1942
+ * HTTP-date); anything else falls back to our own backoff rather than guessing at a date
1943
+ * parse.
1944
+ */
1945
+ _noteRefusal(status, retryAfterRaw) {
1946
+ if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
1947
+ let delay = REFUSAL_NO_HINT;
1948
+ if (retryAfterRaw) {
1949
+ const secs = Number(retryAfterRaw);
1950
+ if (Number.isFinite(secs) && secs >= 0) {
1951
+ delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
1952
+ }
1953
+ }
1954
+ this._lastRefusalAfterMs = delay;
1955
+ debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${retryAfterRaw})`);
1956
+ return true;
1957
+ }
1361
1958
  async _sendRequest(body) {
1362
1959
  const url = `${this._endpoint}/v1/spans`;
1363
1960
  const headers = {
@@ -1388,11 +1985,12 @@ var HttpExporter = class {
1388
1985
  });
1389
1986
  clearTimeout(timeoutId);
1390
1987
  if (response.status < 300) {
1391
- return "success" /* SUCCESS */;
1988
+ return await checkAck(response);
1392
1989
  } else if (response.status === 408 || response.status === 504) {
1393
1990
  debug(`HTTP export timeout: ${response.status}`);
1394
1991
  return "timeout" /* TIMEOUT */;
1395
1992
  }
1993
+ this._noteRefusal(response.status, response.headers.get("Retry-After"));
1396
1994
  debug(`HTTP export failed: ${response.status}`);
1397
1995
  return "failure" /* FAILURE */;
1398
1996
  } catch (e) {
@@ -1406,6 +2004,39 @@ var HttpExporter = class {
1406
2004
  function sleep(ms) {
1407
2005
  return new Promise((resolve) => setTimeout(resolve, ms));
1408
2006
  }
2007
+ function asCount(v) {
2008
+ return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
2009
+ }
2010
+ async function checkAck(response) {
2011
+ let payload;
2012
+ try {
2013
+ payload = await response.json();
2014
+ } catch {
2015
+ return "success" /* SUCCESS */;
2016
+ }
2017
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
2018
+ return "success" /* SUCCESS */;
2019
+ }
2020
+ const body = payload;
2021
+ const accepted = asCount(body.accepted);
2022
+ const rejected = asCount(body.rejected);
2023
+ if (accepted === void 0 || rejected === void 0 || rejected <= 0) {
2024
+ return "success" /* SUCCESS */;
2025
+ }
2026
+ const errors = body.errors;
2027
+ 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
+ const total = accepted + rejected;
2029
+ if (accepted === 0) {
2030
+ warn(
2031
+ `Risicare: the backend accepted 0 of ${total} span(s) and rejected ${rejected} \u2014 this batch was NOT stored. ${detail}`
2032
+ );
2033
+ return "failure" /* FAILURE */;
2034
+ }
2035
+ warn(
2036
+ `Risicare: the backend rejected ${rejected} of ${total} span(s); the remaining ${accepted} were stored. Those ${rejected} are permanently lost and are NOT retried. ${detail}`
2037
+ );
2038
+ return "success" /* SUCCESS */;
2039
+ }
1409
2040
 
1410
2041
  // src/exporters/console.ts
1411
2042
  var ConsoleExporter = class {
@@ -1414,59 +2045,14 @@ var ConsoleExporter = class {
1414
2045
  for (const span of spans) {
1415
2046
  const payload = span.toPayload();
1416
2047
  const line = JSON.stringify(payload);
1417
- process.stderr.write(`[risicare] ${line}
1418
- `);
1419
- }
1420
- return "success" /* SUCCESS */;
1421
- }
1422
- shutdown() {
1423
- }
1424
- };
1425
-
1426
- // src/runtime/config.ts
1427
- function resolveFixRuntimeConfig(config) {
1428
- return {
1429
- apiEndpoint: config.apiEndpoint,
1430
- apiKey: config.apiKey,
1431
- enabled: config.enabled ?? true,
1432
- cacheEnabled: config.cacheEnabled ?? true,
1433
- cacheTtlMs: config.cacheTtlMs ?? 3e5,
1434
- cacheMaxEntries: config.cacheMaxEntries ?? 1e3,
1435
- autoRefresh: config.autoRefresh ?? true,
1436
- refreshIntervalMs: config.refreshIntervalMs ?? 6e4,
1437
- dryRun: config.dryRun ?? false,
1438
- abTestingEnabled: config.abTestingEnabled ?? true,
1439
- timeoutMs: config.timeoutMs ?? 1e3,
1440
- debug: config.debug ?? false
1441
- };
1442
- }
1443
- function matchesError(fix, errorCode) {
1444
- if (fix.errorCode === errorCode) {
1445
- return true;
2048
+ process.stderr.write(`[risicare] ${line}
2049
+ `);
2050
+ }
2051
+ return "success" /* SUCCESS */;
1446
2052
  }
1447
- if (fix.errorCode.endsWith("*")) {
1448
- const prefix = fix.errorCode.slice(0, -1);
1449
- return errorCode.startsWith(prefix);
2053
+ shutdown() {
1450
2054
  }
1451
- return false;
1452
- }
1453
- function shouldApply(fix, sessionHash) {
1454
- if (fix.trafficPercentage >= 100) return true;
1455
- if (fix.trafficPercentage <= 0) return false;
1456
- const bucket = sessionHash % 100;
1457
- return bucket < fix.trafficPercentage;
1458
- }
1459
- function activeFixFromApiResponse(item) {
1460
- return {
1461
- fixId: item.id ?? item.fix_id ?? item.fixId ?? "",
1462
- deploymentId: item.deployment_id ?? item.deploymentId ?? "",
1463
- errorCode: item.error_code ?? item.errorCode ?? "",
1464
- fixType: item.fix_type ?? item.fixType ?? "prompt",
1465
- config: item.config ?? {},
1466
- trafficPercentage: item.traffic_percentage ?? item.trafficPercentage ?? 100,
1467
- version: item.version ?? 1
1468
- };
1469
- }
2055
+ };
1470
2056
 
1471
2057
  // src/runtime/cache.ts
1472
2058
  var FixCache = class {
@@ -2231,247 +2817,6 @@ var FixLoader = class _FixLoader {
2231
2817
  }
2232
2818
  };
2233
2819
 
2234
- // src/runtime/interceptors.ts
2235
- var GuardRejectedError = class extends Error {
2236
- guardId;
2237
- reason;
2238
- phase;
2239
- constructor(guardId, reason, phase) {
2240
- super(`Risicare guard rejected operation: ${guardId} (${phase}) \u2014 ${reason}`);
2241
- this.name = "GuardRejectedError";
2242
- this.guardId = guardId;
2243
- this.reason = reason;
2244
- this.phase = phase;
2245
- }
2246
- };
2247
- function createInterceptContext(operationType, operationName, options) {
2248
- return {
2249
- operationType,
2250
- operationName,
2251
- sessionId: options?.sessionId,
2252
- traceId: options?.traceId,
2253
- errorCode: options?.errorCode,
2254
- attempt: 1,
2255
- appliedFixes: []
2256
- };
2257
- }
2258
- var DefaultFixInterceptor = class {
2259
- _config;
2260
- _cache;
2261
- _applier;
2262
- constructor(config, cache, applier) {
2263
- this._config = resolveFixRuntimeConfig(config);
2264
- this._cache = cache;
2265
- this._applier = applier;
2266
- }
2267
- /**
2268
- * Apply pre-call fixes.
2269
- *
2270
- * - If retrying after error: look up fix by error_code, apply
2271
- * prompt/parameter/fallback fixes
2272
- * - Runs input guard fixes on all message content
2273
- */
2274
- preCall(ctx, messages, params) {
2275
- try {
2276
- if (!this._config.enabled) {
2277
- return { messages, params };
2278
- }
2279
- let modifiedMessages = messages;
2280
- let modifiedParams = { ...params };
2281
- if (ctx.errorCode) {
2282
- const fix = this._applier.getFixForError(ctx.errorCode, ctx.sessionId);
2283
- if (fix) {
2284
- debug(`Applying fix ${fix.fixId} for ${ctx.errorCode}`);
2285
- if (fix.fixType === "prompt" && messages) {
2286
- const msgRecords = messages;
2287
- const { messages: newMessages, result } = this._applier.applyPromptFix(fix, msgRecords);
2288
- modifiedMessages = newMessages;
2289
- ctx.appliedFixes.push(result);
2290
- this._applier.logApplication(result);
2291
- } else if (fix.fixType === "parameter") {
2292
- const { params: newParams, result } = this._applier.applyParameterFix(fix, modifiedParams);
2293
- modifiedParams = newParams;
2294
- ctx.appliedFixes.push(result);
2295
- this._applier.logApplication(result);
2296
- } else if (fix.fixType === "fallback") {
2297
- const { params: newParams, result } = this._applier.applyFallbackFix(fix, modifiedParams);
2298
- modifiedParams = newParams;
2299
- ctx.appliedFixes.push(result);
2300
- this._applier.logApplication(result);
2301
- }
2302
- }
2303
- }
2304
- if (modifiedMessages && this._config.enabled) {
2305
- for (const msg of modifiedMessages) {
2306
- const content = msg.content;
2307
- if (typeof content === "string") {
2308
- for (const fix of this._cache.getAll()) {
2309
- if (fix.fixType === "guard") {
2310
- const { passed, result } = this._applier.applyGuardFix(
2311
- fix,
2312
- content,
2313
- true
2314
- );
2315
- if (result.applied) {
2316
- ctx.appliedFixes.push(result);
2317
- this._applier.logApplication(result);
2318
- }
2319
- if (!passed) {
2320
- throw new GuardRejectedError(
2321
- fix.fixId ?? "unknown",
2322
- result.reason ?? "guard rejected input",
2323
- "pre_call"
2324
- );
2325
- }
2326
- }
2327
- }
2328
- }
2329
- }
2330
- }
2331
- return { messages: modifiedMessages, params: modifiedParams };
2332
- } catch (e) {
2333
- if (e instanceof GuardRejectedError) throw e;
2334
- debug(`DefaultFixInterceptor.preCall error: ${e}`);
2335
- return { messages, params };
2336
- }
2337
- }
2338
- /**
2339
- * Apply post-call fixes (output validation).
2340
- *
2341
- * Runs output guard fixes on response content.
2342
- */
2343
- postCall(ctx, response) {
2344
- try {
2345
- if (!this._config.enabled) {
2346
- return { response, shouldContinue: true };
2347
- }
2348
- for (const fix of this._cache.getAll()) {
2349
- if (fix.fixType !== "guard") continue;
2350
- const content = this._extractResponseContent(response);
2351
- if (!content) continue;
2352
- const { passed, result } = this._applier.applyGuardFix(
2353
- fix,
2354
- content,
2355
- false
2356
- );
2357
- if (result.applied) {
2358
- ctx.appliedFixes.push(result);
2359
- this._applier.logApplication(result);
2360
- }
2361
- if (!passed) {
2362
- warn(`Output guard failed for fix ${fix.fixId}: ${result.reason ?? "unknown"}`);
2363
- throw new GuardRejectedError(
2364
- fix.fixId ?? "unknown",
2365
- result.reason ?? "guard rejected output",
2366
- "post_call"
2367
- );
2368
- }
2369
- }
2370
- return { response, shouldContinue: true };
2371
- } catch (e) {
2372
- if (e instanceof GuardRejectedError) throw e;
2373
- debug(`DefaultFixInterceptor.postCall error: ${e}`);
2374
- return { response, shouldContinue: true };
2375
- }
2376
- }
2377
- /**
2378
- * Handle errors and decide whether to retry.
2379
- *
2380
- * Classifies the error, looks up retry/fallback fixes, and returns
2381
- * whether the caller should retry.
2382
- */
2383
- onError(ctx, error) {
2384
- try {
2385
- if (!this._config.enabled) {
2386
- return { shouldRetry: false, modifiedParams: null };
2387
- }
2388
- const errorCode = classifyError(error);
2389
- ctx.errorCode = errorCode;
2390
- ctx.errorMessage = error.message;
2391
- const fix = this._applier.getFixForError(errorCode, ctx.sessionId);
2392
- if (!fix) {
2393
- return { shouldRetry: false, modifiedParams: null };
2394
- }
2395
- if (fix.fixType === "retry") {
2396
- const maxRetries = fix.config.max_retries ?? fix.config.maxRetries ?? 3;
2397
- if (ctx.attempt <= maxRetries) {
2398
- debug(
2399
- `Retry fix ${fix.fixId}: attempt ${ctx.attempt}/${maxRetries}`
2400
- );
2401
- const result = {
2402
- applied: true,
2403
- fixId: fix.fixId,
2404
- deploymentId: fix.deploymentId,
2405
- fixType: "retry",
2406
- modifications: { attempt: ctx.attempt }
2407
- };
2408
- ctx.appliedFixes.push(result);
2409
- this._applier.logApplication(result);
2410
- return { shouldRetry: true, modifiedParams: null };
2411
- }
2412
- }
2413
- if (fix.fixType === "fallback") {
2414
- const { params: modifiedParams, result } = this._applier.applyFallbackFix(fix, {});
2415
- if (result.applied) {
2416
- ctx.appliedFixes.push(result);
2417
- this._applier.logApplication(result);
2418
- return { shouldRetry: true, modifiedParams };
2419
- }
2420
- }
2421
- return { shouldRetry: false, modifiedParams: null };
2422
- } catch (e) {
2423
- debug(`DefaultFixInterceptor.onError error: ${e}`);
2424
- return { shouldRetry: false, modifiedParams: null };
2425
- }
2426
- }
2427
- // ─── Private ────────────────────────────────────────────────────────────
2428
- /** Extract text content from a response object. */
2429
- _extractResponseContent(response) {
2430
- if (typeof response === "string") return response;
2431
- if (response && typeof response === "object") {
2432
- const resp = response;
2433
- const choices = resp.choices;
2434
- if (Array.isArray(choices) && choices.length > 0) {
2435
- const first = choices[0];
2436
- const message = first?.message;
2437
- if (typeof message?.content === "string") {
2438
- return message.content;
2439
- }
2440
- }
2441
- const content = resp.content;
2442
- if (typeof content === "string") return content;
2443
- if (Array.isArray(content) && content.length > 0) {
2444
- const first = content[0];
2445
- if (typeof first?.text === "string") return first.text;
2446
- }
2447
- }
2448
- return null;
2449
- }
2450
- };
2451
- function classifyError(error) {
2452
- const errorType = error.constructor.name.toLowerCase();
2453
- const errorMsg = error.message.toLowerCase();
2454
- if (errorType.includes("timeout") || errorMsg.includes("timeout") || errorMsg.includes("aborted")) {
2455
- return "TOOL.EXECUTION.TIMEOUT";
2456
- }
2457
- if (errorMsg.includes("rate") && errorMsg.includes("limit")) {
2458
- return "TOOL.EXECUTION.RATE_LIMIT";
2459
- }
2460
- if (errorMsg.includes("429") || errorMsg.includes("too many requests")) {
2461
- return "TOOL.EXECUTION.RATE_LIMIT";
2462
- }
2463
- if (errorType.includes("connection") || errorMsg.includes("connection") || errorMsg.includes("econnrefused") || errorMsg.includes("econnreset") || errorMsg.includes("fetch failed")) {
2464
- return "TOOL.EXECUTION.CONNECTION_ERROR";
2465
- }
2466
- if (errorMsg.includes("auth") || errorMsg.includes("401") || errorMsg.includes("403") || errorMsg.includes("unauthorized") || errorMsg.includes("forbidden")) {
2467
- return "TOOL.EXECUTION.AUTH_ERROR";
2468
- }
2469
- if (errorType.includes("syntaxerror") || errorType.includes("json") || errorMsg.includes("json") || errorMsg.includes("unexpected token")) {
2470
- return "OUTPUT.FORMAT.JSON_INVALID";
2471
- }
2472
- return "TOOL.EXECUTION.FAILURE";
2473
- }
2474
-
2475
2820
  // src/runtime/runtime.ts
2476
2821
  var G2 = globalThis;
2477
2822
  var RUNTIME_KEY = "__risicare_fix_runtime";
@@ -2770,13 +3115,24 @@ var RisicareClient = class {
2770
3115
  // anywhere downstream (in the HTTP exporter, say) would leave a hole for
2771
3116
  // any other exporter; masking upstream would put customer code on the
2772
3117
  // span-end call path.
2773
- mask: this.config.mask
3118
+ mask: this.config.mask,
3119
+ // Same argument as `mask`: the processor is the ONE choke point every
3120
+ // exporter is behind, and the only place BOTH content paths — provider
3121
+ // capture and hand-set attributes — can be gated together. The Tracer
3122
+ // still carries `traceContent` for the provider patches to read; that is
3123
+ // now a convenience, not the enforcement point.
3124
+ traceContent: this.config.traceContent
2774
3125
  });
2775
3126
  this.tracer = new Tracer({
2776
3127
  onSpanEnd: (span) => this.processor.onSpanEnd(span),
2777
3128
  sampleRate: this.config.sampleRate,
2778
3129
  enabled: this.config.enabled,
2779
- traceContent: this.config.traceContent
3130
+ traceContent: this.config.traceContent,
3131
+ // F-SDKJSSVCNAME-001 — these were resolved into `config` and then read by
3132
+ // nothing. The Tracer is where Python emits them, so JS emits them there
3133
+ // too rather than inventing a second site.
3134
+ serviceName: this.config.serviceName,
3135
+ serviceVersion: this.config.serviceVersion
2780
3136
  });
2781
3137
  this.processor.start();
2782
3138
  if (this.config.apiKey && this.config.enabled) {
@@ -2974,7 +3330,7 @@ function getTracer2() {
2974
3330
  }
2975
3331
  function getTraceContent() {
2976
3332
  const tracer = getTracer();
2977
- return tracer?.traceContent ?? true;
3333
+ return tracer?.traceContent ?? false;
2978
3334
  }
2979
3335
  function getMetrics() {
2980
3336
  const client = getClient();
@@ -3204,12 +3560,14 @@ function withSessionEndMarker(body) {
3204
3560
  // src/decorators/agent.ts
3205
3561
  function _wrapAgent(options, fn) {
3206
3562
  const spanName = `agent:${options.name ?? "agent"}`;
3563
+ const agentId = options.agentId ?? generateAgentId(options.name ?? "agent");
3564
+ const boundOptions = { ...options, agentId };
3207
3565
  return (...args) => {
3208
3566
  const tracer = getTracer2();
3209
3567
  if (!tracer) {
3210
3568
  return fn(...args);
3211
3569
  }
3212
- return withAgent(options, () => {
3570
+ return withAgent(boundOptions, () => {
3213
3571
  return tracer.startSpan(
3214
3572
  { name: spanName, kind: "agent" /* AGENT */ },
3215
3573
  (span) => withEndMarker(span, "agent", () => fn(...args))