risicare 0.4.2 → 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 +63 -0
  2. package/dist/frameworks/instructor.cjs +34 -18
  3. package/dist/frameworks/instructor.cjs.map +1 -1
  4. package/dist/frameworks/instructor.js +34 -18
  5. package/dist/frameworks/instructor.js.map +1 -1
  6. package/dist/frameworks/langchain.cjs +40 -24
  7. package/dist/frameworks/langchain.cjs.map +1 -1
  8. package/dist/frameworks/langchain.js +40 -24
  9. package/dist/frameworks/langchain.js.map +1 -1
  10. package/dist/frameworks/langgraph.cjs +40 -24
  11. package/dist/frameworks/langgraph.cjs.map +1 -1
  12. package/dist/frameworks/langgraph.js +40 -24
  13. package/dist/frameworks/langgraph.js.map +1 -1
  14. package/dist/frameworks/llamaindex.cjs +29 -13
  15. package/dist/frameworks/llamaindex.cjs.map +1 -1
  16. package/dist/frameworks/llamaindex.js +29 -13
  17. package/dist/frameworks/llamaindex.js.map +1 -1
  18. package/dist/index.cjs +1555 -761
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +237 -47
  21. package/dist/index.d.ts +237 -47
  22. package/dist/index.js +1704 -911
  23. package/dist/index.js.map +1 -1
  24. package/dist/providers/anthropic/index.cjs +40 -24
  25. package/dist/providers/anthropic/index.cjs.map +1 -1
  26. package/dist/providers/anthropic/index.js +40 -24
  27. package/dist/providers/anthropic/index.js.map +1 -1
  28. package/dist/providers/bedrock/index.cjs +40 -24
  29. package/dist/providers/bedrock/index.cjs.map +1 -1
  30. package/dist/providers/bedrock/index.js +40 -24
  31. package/dist/providers/bedrock/index.js.map +1 -1
  32. package/dist/providers/cerebras/index.cjs +40 -24
  33. package/dist/providers/cerebras/index.cjs.map +1 -1
  34. package/dist/providers/cerebras/index.js +40 -24
  35. package/dist/providers/cerebras/index.js.map +1 -1
  36. package/dist/providers/cohere/index.cjs +40 -24
  37. package/dist/providers/cohere/index.cjs.map +1 -1
  38. package/dist/providers/cohere/index.js +40 -24
  39. package/dist/providers/cohere/index.js.map +1 -1
  40. package/dist/providers/google/index.cjs +40 -24
  41. package/dist/providers/google/index.cjs.map +1 -1
  42. package/dist/providers/google/index.js +40 -24
  43. package/dist/providers/google/index.js.map +1 -1
  44. package/dist/providers/groq/index.cjs +40 -24
  45. package/dist/providers/groq/index.cjs.map +1 -1
  46. package/dist/providers/groq/index.js +40 -24
  47. package/dist/providers/groq/index.js.map +1 -1
  48. package/dist/providers/huggingface/index.cjs +40 -24
  49. package/dist/providers/huggingface/index.cjs.map +1 -1
  50. package/dist/providers/huggingface/index.js +40 -24
  51. package/dist/providers/huggingface/index.js.map +1 -1
  52. package/dist/providers/mistral/index.cjs +40 -24
  53. package/dist/providers/mistral/index.cjs.map +1 -1
  54. package/dist/providers/mistral/index.js +40 -24
  55. package/dist/providers/mistral/index.js.map +1 -1
  56. package/dist/providers/ollama/index.cjs +40 -24
  57. package/dist/providers/ollama/index.cjs.map +1 -1
  58. package/dist/providers/ollama/index.js +40 -24
  59. package/dist/providers/ollama/index.js.map +1 -1
  60. package/dist/providers/openai/index.cjs +40 -24
  61. package/dist/providers/openai/index.cjs.map +1 -1
  62. package/dist/providers/openai/index.js +40 -24
  63. package/dist/providers/openai/index.js.map +1 -1
  64. package/dist/providers/together/index.cjs +40 -24
  65. package/dist/providers/together/index.cjs.map +1 -1
  66. package/dist/providers/together/index.js +40 -24
  67. package/dist/providers/together/index.js.map +1 -1
  68. package/dist/providers/vercel-ai/index.cjs +34 -18
  69. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  70. package/dist/providers/vercel-ai/index.js +34 -18
  71. package/dist/providers/vercel-ai/index.js.map +1 -1
  72. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -5,183 +5,805 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
5
5
  throw Error('Dynamic require of "' + x + '" is not supported');
6
6
  });
7
7
 
8
- // src/config.ts
9
- var DEFAULT_ENDPOINT = "https://app.risicare.ai";
10
- function resolveConfig(config) {
11
- const env = process.env;
12
- const apiKey = config?.apiKey ?? env.RISICARE_API_KEY;
13
- const endpoint = config?.endpoint ?? env.RISICARE_ENDPOINT ?? DEFAULT_ENDPOINT;
14
- const projectId = config?.projectId ?? env.RISICARE_PROJECT_ID;
15
- if (config?.projectId || env.RISICARE_PROJECT_ID) {
16
- console.warn(
17
- "[risicare] projectId is deprecated and ignored by the gateway. Your API key determines the project. Use serviceName and environment for within-project organization. projectId will be removed in v1.0."
18
- );
8
+ // src/client.ts
9
+ import { createHash as createHash2 } from "crypto";
10
+
11
+ // src/globals.ts
12
+ import { AsyncLocalStorage } from "async_hooks";
13
+ var G = globalThis;
14
+ var PREFIX = "__risicare_";
15
+ function getClient() {
16
+ return G[PREFIX + "client"];
17
+ }
18
+ function setClient(client) {
19
+ G[PREFIX + "client"] = client;
20
+ }
21
+ function getTracer() {
22
+ return G[PREFIX + "tracer"];
23
+ }
24
+ function setTracer(tracer) {
25
+ G[PREFIX + "tracer"] = tracer;
26
+ }
27
+ function getContextStorage() {
28
+ if (!G[PREFIX + "ctx"]) {
29
+ G[PREFIX + "ctx"] = new AsyncLocalStorage();
19
30
  }
20
- const environment = config?.environment ?? env.RISICARE_ENVIRONMENT ?? "development";
21
- const serviceName = config?.serviceName ?? env.RISICARE_SERVICE_NAME;
22
- const serviceVersion = config?.serviceVersion ?? env.RISICARE_SERVICE_VERSION;
23
- const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, true);
24
- const sampleRateRaw = config?.sampleRate ?? parseFloat(env.RISICARE_SAMPLE_RATE ?? "1.0");
25
- const debug2 = config?.debug ?? parseBool(env.RISICARE_DEBUG, false);
26
- const compress = config?.compress ?? parseBool(env.RISICARE_COMPRESS, false);
27
- const batchSizeRaw = config?.batchSize ?? parseNumericEnv(env.RISICARE_BATCH_SIZE, 100);
28
- const batchTimeoutMsRaw = config?.batchTimeoutMs ?? parseNumericEnv(env.RISICARE_BATCH_TIMEOUT_MS, 1e3);
29
- const maxQueueSizeRaw = config?.maxQueueSize ?? parseNumericEnv(env.RISICARE_MAX_QUEUE_SIZE, 1e4);
30
- const sampleRate = validateSampleRate(sampleRateRaw);
31
- const batchSize = validatePositiveInt("batchSize", batchSizeRaw, 100, 1, 1e4);
32
- const batchTimeoutMs = validatePositiveInt("batchTimeoutMs", batchTimeoutMsRaw, 1e3, 1, 6e5);
33
- const maxQueueSize = validatePositiveInt("maxQueueSize", maxQueueSizeRaw, 1e4, 1, 1e6);
34
- let enabled;
35
- if (config?.enabled !== void 0) {
36
- enabled = config.enabled;
37
- } else if (env.RISICARE_TRACING !== void 0) {
38
- enabled = parseBool(env.RISICARE_TRACING, false);
39
- } else {
40
- enabled = !!apiKey;
31
+ return G[PREFIX + "ctx"];
32
+ }
33
+ function getRegistry() {
34
+ if (!G[PREFIX + "registry"]) {
35
+ G[PREFIX + "registry"] = /* @__PURE__ */ new Map();
41
36
  }
42
- return {
43
- apiKey: apiKey ?? "",
44
- endpoint,
45
- projectId: projectId ?? "",
46
- environment,
47
- serviceName: serviceName ?? "",
48
- serviceVersion: serviceVersion ?? "",
49
- enabled,
50
- traceContent,
51
- sampleRate,
52
- batchSize,
53
- batchTimeoutMs,
54
- maxQueueSize,
55
- debug: debug2,
56
- compress,
57
- metadata: config?.metadata ?? {}
58
- };
37
+ return G[PREFIX + "registry"];
59
38
  }
60
- function parseBool(value, defaultValue) {
61
- if (value === void 0) return defaultValue;
62
- const lower = value.toLowerCase();
63
- return lower === "true" || lower === "1" || lower === "yes";
39
+ function getOpCount() {
40
+ return G[PREFIX + "opcount"] ?? 0;
64
41
  }
65
- function parseNumericEnv(value, defaultValue) {
66
- if (value === void 0) return defaultValue;
67
- const n = Number(value);
68
- return Number.isFinite(n) ? n : defaultValue;
42
+ function setOpCount(n) {
43
+ G[PREFIX + "opcount"] = n;
69
44
  }
70
- function validateSampleRate(value) {
71
- if (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1) {
72
- return value;
45
+ function getDebug() {
46
+ return G[PREFIX + "debug"] ?? false;
47
+ }
48
+ function setDebugFlag(enabled) {
49
+ G[PREFIX + "debug"] = enabled;
50
+ }
51
+
52
+ // src/utils/log.ts
53
+ function setDebug(enabled) {
54
+ setDebugFlag(enabled);
55
+ }
56
+ function debug(msg) {
57
+ if (getDebug()) {
58
+ process.stderr.write(`[risicare] ${msg}
59
+ `);
73
60
  }
74
- if (typeof value === "string") {
75
- const n = Number(value);
76
- if (Number.isFinite(n) && n >= 0 && n <= 1) return n;
61
+ }
62
+ function warn(msg) {
63
+ process.stderr.write(`[risicare] WARNING: ${msg}
64
+ `);
65
+ }
66
+
67
+ // src/masking.ts
68
+ var MASK_ERROR_MARKER = "<risicare:mask-error>";
69
+ var MASK_BUDGET_MS_PER_SPAN = 1;
70
+ var MASK_WARN_WINDOW_MS = 3e5;
71
+ var SCORE_COMMENT_KEY = "score.comment";
72
+ function maskText(mask, key, value, onError) {
73
+ return maskString(mask, key, value, onError);
74
+ }
75
+ function maskOne(mask, key, value, onError) {
76
+ try {
77
+ return mask(key, value);
78
+ } catch (e) {
79
+ onError?.(key, e);
80
+ return MASK_ERROR_MARKER;
77
81
  }
78
- console.warn(
79
- `[risicare] sampleRate must be a finite number in [0, 1], got ${typeof value}=${JSON.stringify(value)}; defaulting to 1.0`
80
- );
81
- return 1;
82
82
  }
83
- function validatePositiveInt(name, value, defaultValue, min, max) {
84
- let n;
85
- if (typeof value === "number") {
86
- n = value;
87
- } else if (typeof value === "string") {
88
- n = Number(value);
89
- if (Number.isFinite(n)) {
90
- console.warn(
91
- `[risicare] ${name} was a string ("${value}"); coerced to ${n}. Pass a number to avoid this warning.`
92
- );
83
+ function maskString(mask, key, value, onError) {
84
+ const masked = maskOne(mask, key, value, onError);
85
+ if (typeof masked === "string") return masked;
86
+ try {
87
+ return String(masked);
88
+ } catch (e) {
89
+ onError?.(key, e);
90
+ return MASK_ERROR_MARKER;
91
+ }
92
+ }
93
+ function maskAttributes(mask, prefix, attrs, onError) {
94
+ for (const k of Object.keys(attrs)) {
95
+ attrs[k] = maskOne(mask, prefix + k, attrs[k], onError);
96
+ }
97
+ }
98
+ function isMasked(span) {
99
+ return span._risicareMasked === true;
100
+ }
101
+ function markMasked(span) {
102
+ try {
103
+ span._risicareMasked = true;
104
+ } catch {
105
+ debug("Could not mark span as masked; a re-queue may re-mask it");
106
+ }
107
+ }
108
+ function applyMask(span, mask, onError) {
109
+ if (isMasked(span)) return;
110
+ if (span.attributes && typeof span.attributes === "object") {
111
+ maskAttributes(mask, "", span.attributes, onError);
112
+ }
113
+ if (span.statusMessage !== void 0) {
114
+ span.statusMessage = maskString(mask, "statusMessage", span.statusMessage, onError);
115
+ }
116
+ if (Array.isArray(span.events)) {
117
+ span.events.forEach((event, i) => {
118
+ if (event?.attributes && typeof event.attributes === "object") {
119
+ maskAttributes(mask, `events.${i}.attributes.`, event.attributes, onError);
120
+ }
121
+ });
122
+ }
123
+ if (Array.isArray(span.links)) {
124
+ span.links.forEach((link, i) => {
125
+ if (link?.attributes && typeof link.attributes === "object") {
126
+ maskAttributes(mask, `links.${i}.attributes.`, link.attributes, onError);
127
+ }
128
+ });
129
+ }
130
+ markMasked(span);
131
+ }
132
+ var CONTENT_KEYS_EXACT = /* @__PURE__ */ new Set([
133
+ "gen_ai.system_prompt",
134
+ "gen_ai.prompt.message"
135
+ ]);
136
+ var CONTENT_OMITTED_MARKER = "<risicare:content-omitted>";
137
+ function isContentKey(key) {
138
+ if (CONTENT_KEYS_EXACT.has(key)) return true;
139
+ const lastSegment = key.slice(key.lastIndexOf(".") + 1);
140
+ if (lastSegment === "content") return true;
141
+ return key.endsWith("_content");
142
+ }
143
+ function stripAttributes(attrs) {
144
+ let n = 0;
145
+ for (const k of Object.keys(attrs)) {
146
+ if (isContentKey(k)) {
147
+ attrs[k] = CONTENT_OMITTED_MARKER;
148
+ n++;
93
149
  }
94
- } else {
95
- console.warn(
96
- `[risicare] ${name} must be a positive integer, got ${typeof value}; defaulting to ${defaultValue}`
97
- );
98
- return defaultValue;
99
150
  }
100
- if (!Number.isFinite(n) || n <= 0) {
101
- console.warn(
102
- `[risicare] ${name} must be > 0, got ${value}; defaulting to ${defaultValue}`
103
- );
104
- return defaultValue;
151
+ return n;
152
+ }
153
+ function stripContent(span) {
154
+ let stripped = 0;
155
+ if (span.attributes && typeof span.attributes === "object") {
156
+ stripped += stripAttributes(span.attributes);
157
+ }
158
+ if (Array.isArray(span.events)) {
159
+ for (const event of span.events) {
160
+ if (event?.attributes && typeof event.attributes === "object") {
161
+ stripped += stripAttributes(event.attributes);
162
+ }
163
+ }
105
164
  }
106
- if (n < min) {
107
- console.warn(`[risicare] ${name}=${n} below floor; clamping to ${min}`);
108
- return min;
165
+ if (Array.isArray(span.links)) {
166
+ for (const link of span.links) {
167
+ if (link?.attributes && typeof link.attributes === "object") {
168
+ stripped += stripAttributes(link.attributes);
169
+ }
170
+ }
109
171
  }
110
- if (n > max) {
111
- console.warn(`[risicare] ${name}=${n} above ceiling; clamping to ${max}`);
112
- return max;
172
+ return stripped;
173
+ }
174
+ function stripContentBatch(spans) {
175
+ let total = 0;
176
+ for (const span of spans) {
177
+ try {
178
+ total += stripContent(span);
179
+ } catch {
180
+ debug("Could not strip content from a span");
181
+ }
113
182
  }
114
- return Math.floor(n);
183
+ return total;
184
+ }
185
+ function applyMaskBatch(spans, mask, onError) {
186
+ let errors = 0;
187
+ let firstKey;
188
+ let firstError;
189
+ const report = (key, error) => {
190
+ errors++;
191
+ if (firstKey === void 0) {
192
+ firstKey = key;
193
+ firstError = error;
194
+ }
195
+ onError?.(key, error);
196
+ };
197
+ const started = Date.now();
198
+ for (const span of spans) {
199
+ applyMask(span, mask, report);
200
+ }
201
+ const elapsedMs = Date.now() - started;
202
+ if (errors > 0 && firstKey !== void 0) {
203
+ debug(`mask threw on ${errors} field(s); first: key=${firstKey} ${String(firstError)}`);
204
+ }
205
+ return { errors, elapsedMs };
206
+ }
207
+ function warnMaskErrors(batchErrors, totalErrors) {
208
+ warn(
209
+ `the mask callback threw on ${batchErrors} field(s) in this batch (${totalErrors} since start). Those fields were replaced with "${MASK_ERROR_MARKER}" and the spans were exported intact \u2014 no span was dropped. Fix the callback; until then those fields carry no data.`
210
+ );
211
+ }
212
+ function warnMaskSlow(spanCount, elapsedMs) {
213
+ warn(
214
+ `masking ${spanCount} span(s) took ${elapsedMs} ms (budget ${MASK_BUDGET_MS_PER_SPAN * spanCount} ms, ${MASK_BUDGET_MS_PER_SPAN} ms/span). Node is single-threaded: this time is taken from your event loop, so it delays your application as well as the export drain, and a queue that cannot drain drops spans (reason=queue_full). Keep the callback CPU-only: no I/O, no network, no unbounded retries.`
215
+ );
115
216
  }
116
217
 
117
- // src/ids.ts
118
- import { randomBytes } from "crypto";
119
- var HEX_REGEX_32 = /^[0-9a-f]{32}$/;
120
- var HEX_REGEX_16 = /^[0-9a-f]{16}$/;
121
- function generateTraceId() {
122
- return randomBytes(16).toString("hex");
218
+ // src/exporters/batch.ts
219
+ var SHUTDOWN_RESERVE_MS = 100;
220
+ var SHUTDOWN_BUDGET_MS = 5e3;
221
+ var REFUSAL_WARN_WINDOW_MS = 3e5;
222
+ var DEFAULT_BATCH_SIZE = 500;
223
+ var MAX_ATTRIBUTE_PAIRS_PER_BATCH = 24e3;
224
+ var MAX_BATCH_BYTES = 8 * 1024 * 1024;
225
+ var SPAN_ENVELOPE_BYTES = 512;
226
+ var CHILD_ENVELOPE_BYTES = 128;
227
+ var SCALAR_BYTES = 24;
228
+ var LITERAL_BYTES = 5;
229
+ var EST_MAX_DEPTH = 4;
230
+ var EST_OPAQUE_VALUE_BYTES = 4096;
231
+ var utf8ByteLength = typeof Buffer !== "undefined" && typeof Buffer.byteLength === "function" ? (s) => Buffer.byteLength(s, "utf8") : (s) => s.length * 3;
232
+ function estStringBytes(s) {
233
+ return 2 + utf8ByteLength(s);
123
234
  }
124
- function generateSpanId() {
125
- return randomBytes(8).toString("hex");
235
+ function estValueBytes(v, depth = 0) {
236
+ if (typeof v === "string") return estStringBytes(v);
237
+ if (v === null || v === void 0 || typeof v === "boolean") return LITERAL_BYTES;
238
+ if (typeof v === "number" || typeof v === "bigint") return SCALAR_BYTES;
239
+ if (Array.isArray(v) && depth < EST_MAX_DEPTH) {
240
+ let total = 2 + Math.max(0, v.length - 1);
241
+ for (const item of v) total += estValueBytes(item, depth + 1);
242
+ return total;
243
+ }
244
+ if (typeof v === "object" && depth < EST_MAX_DEPTH && Object.getPrototypeOf(v) === Object.prototype) {
245
+ let total = 2;
246
+ for (const [k, val] of Object.entries(v)) {
247
+ total += estStringBytes(k) + 2 + estValueBytes(val, depth + 1);
248
+ }
249
+ return total;
250
+ }
251
+ return EST_OPAQUE_VALUE_BYTES;
126
252
  }
127
- function generateAgentId(prefix) {
128
- const suffix = randomBytes(8).toString("hex");
129
- return prefix ? `${prefix}-${suffix}` : suffix;
253
+ function estMappingBytes(m) {
254
+ let total = 0;
255
+ for (const [k, v] of Object.entries(m)) total += estStringBytes(k) + 2 + estValueBytes(v);
256
+ return total;
130
257
  }
131
- function validateTraceId(id) {
132
- return HEX_REGEX_32.test(id);
258
+ function spanBytesEstimate(span) {
259
+ try {
260
+ const s = span;
261
+ let total = SPAN_ENVELOPE_BYTES;
262
+ for (const field of ["name", "statusMessage"]) {
263
+ if (typeof s[field] === "string") total += estStringBytes(s[field]);
264
+ }
265
+ const attrs = s.attributes;
266
+ if (attrs != null && typeof attrs === "object" && !Array.isArray(attrs)) {
267
+ total += estMappingBytes(attrs);
268
+ }
269
+ for (const key of ["events", "links"]) {
270
+ const coll = s[key];
271
+ if (!Array.isArray(coll)) continue;
272
+ for (const child of coll) {
273
+ total += CHILD_ENVELOPE_BYTES;
274
+ const ca = child?.attributes;
275
+ if (ca != null && typeof ca === "object" && !Array.isArray(ca)) {
276
+ total += estMappingBytes(ca);
277
+ }
278
+ }
279
+ }
280
+ return total;
281
+ } catch {
282
+ return SPAN_ENVELOPE_BYTES;
283
+ }
133
284
  }
134
- function validateSpanId(id) {
135
- return HEX_REGEX_16.test(id);
285
+ function spanAttrCount(span) {
286
+ const attrs = span.attributes;
287
+ if (attrs == null) return 0;
288
+ if (attrs instanceof Map) return attrs.size;
289
+ if (typeof attrs === "object") return Object.keys(attrs).length;
290
+ return 0;
136
291
  }
137
-
138
- // src/types.ts
139
- var SpanKind = /* @__PURE__ */ ((SpanKind2) => {
140
- SpanKind2["INTERNAL"] = "internal";
141
- SpanKind2["CLIENT"] = "client";
142
- SpanKind2["SERVER"] = "server";
143
- SpanKind2["PRODUCER"] = "producer";
144
- SpanKind2["CONSUMER"] = "consumer";
145
- SpanKind2["AGENT"] = "agent";
146
- SpanKind2["LLM_CALL"] = "llm_call";
147
- SpanKind2["TOOL_CALL"] = "tool_call";
148
- SpanKind2["RETRIEVAL"] = "retrieval";
149
- SpanKind2["DECISION"] = "decision";
150
- SpanKind2["MESSAGE"] = "message";
151
- SpanKind2["DELEGATION"] = "delegation";
152
- SpanKind2["COORDINATION"] = "coordination";
153
- SpanKind2["THINK"] = "think";
154
- SpanKind2["DECIDE"] = "decide";
155
- SpanKind2["OBSERVE"] = "observe";
156
- SpanKind2["REFLECT"] = "reflect";
157
- return SpanKind2;
158
- })(SpanKind || {});
159
- var SpanStatus = /* @__PURE__ */ ((SpanStatus2) => {
160
- SpanStatus2["UNSET"] = "unset";
161
- SpanStatus2["OK"] = "ok";
162
- SpanStatus2["ERROR"] = "error";
163
- return SpanStatus2;
164
- })(SpanStatus || {});
165
- var SemanticPhase = /* @__PURE__ */ ((SemanticPhase2) => {
166
- SemanticPhase2["THINK"] = "think";
167
- SemanticPhase2["DECIDE"] = "decide";
168
- SemanticPhase2["ACT"] = "act";
169
- SemanticPhase2["OBSERVE"] = "observe";
170
- SemanticPhase2["REFLECT"] = "reflect";
171
- SemanticPhase2["COMMUNICATE"] = "communicate";
172
- SemanticPhase2["COORDINATE"] = "coordinate";
173
- return SemanticPhase2;
174
- })(SemanticPhase || {});
175
- var AgentRole = /* @__PURE__ */ ((AgentRole2) => {
176
- AgentRole2["ORCHESTRATOR"] = "orchestrator";
177
- AgentRole2["WORKER"] = "worker";
178
- AgentRole2["SUPERVISOR"] = "supervisor";
179
- AgentRole2["SPECIALIST"] = "specialist";
180
- AgentRole2["ROUTER"] = "router";
181
- AgentRole2["AGGREGATOR"] = "aggregator";
182
- AgentRole2["BROADCASTER"] = "broadcaster";
183
- AgentRole2["CRITIC"] = "critic";
184
- AgentRole2["PLANNER"] = "planner";
292
+ var BatchSpanProcessor = class _BatchSpanProcessor {
293
+ _exporters;
294
+ _batchSize;
295
+ _batchTimeoutMs;
296
+ _maxQueueSize;
297
+ // ⚠ NO `_debug` FIELD. It existed, was assigned, and was read by NOTHING —
298
+ // `tsc --noEmit` had been RED on this package at HEAD for it (TS6133), which
299
+ // survived because `ci-local.sh` runs this package's vitest and never its
300
+ // typecheck, and `prepublishOnly` runs `build && test` — also no typecheck.
301
+ // Filed F-SDKJSTYPECHECK-001. Debug output here is gated globally by
302
+ // `setDebug()` in `../utils/log.ts`, so a per-processor flag was always
303
+ // redundant; Python's `self._debug` exists because `logging` has no such
304
+ // global switch.
305
+ _queue = [];
306
+ _timer = null;
307
+ _started = false;
308
+ _flushing = false;
309
+ _beforeExitHandler = null;
310
+ // Retry tracking for failed batches (Audit #5)
311
+ _retryCounts = /* @__PURE__ */ new Map();
312
+ static MAX_RETRIES = 3;
313
+ _lastRefusalWarnAt = Number.NEGATIVE_INFINITY;
314
+ // ── Masking (see `../masking.ts`) ──────────────────────────────────────────
315
+ _mask;
316
+ // ── Content capture gate (see `../masking.ts`) ─────────────────────────────
317
+ // Fail-closed: an unspecified value means "do not capture". This is the ONE
318
+ // place the gate runs for BOTH content paths — provider capture AND hand-set
319
+ // attributes — so it must not be conditional on anything a caller might
320
+ // forget to pass. Python twin: `BatchSpanProcessor._trace_content`.
321
+ _traceContent;
322
+ _lastMaskWarnAt = Number.NEGATIVE_INFINITY;
323
+ _lastSlowMaskWarnAt = Number.NEGATIVE_INFINITY;
324
+ // Metrics
325
+ /** DEPRECATED flat total. Retained as the exact SUM of
326
+ * `droppedSpansByReason` so existing readers keep working (RULING §5
327
+ * back-compat — the same deprecate-and-alias shape this codebase used for
328
+ * `complete`->`settled` and `spans_flushed_total`). Prefer the labelled
329
+ * record: one integer cannot tell an under-provisioned queue from a dead
330
+ * gateway from a redeploy. */
331
+ droppedSpans = 0;
332
+ droppedSpansByReason = {
333
+ queue_full: 0,
334
+ transport_refused: 0,
335
+ shutdown_residue: 0
336
+ };
337
+ exportedSpans = 0;
338
+ /** Export ATTEMPTS, not a span count. */
339
+ failedExports = 0;
340
+ /**
341
+ * Fields whose mask callback threw and were replaced with
342
+ * `MASK_ERROR_MARKER`. A FIELD count, not a span count — one span can
343
+ * contribute several. Non-zero means those fields carry a marker instead of
344
+ * data: a customer-code bug, not a transport one.
345
+ */
346
+ maskErrors = 0;
347
+ constructor(options) {
348
+ this._exporters = [...options.exporters];
349
+ const requestedBatchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;
350
+ const clampedBatchSize = Math.max(1, Math.min(requestedBatchSize, 1e4));
351
+ if (clampedBatchSize !== requestedBatchSize) {
352
+ warn(
353
+ `batchSize=${requestedBatchSize} is outside the allowed range [1, 10000]; clamping to ${clampedBatchSize}`
354
+ );
355
+ }
356
+ this._batchSize = clampedBatchSize;
357
+ this._batchTimeoutMs = options.batchTimeoutMs ?? 1e3;
358
+ this._maxQueueSize = options.maxQueueSize ?? 1e4;
359
+ this._mask = options.mask;
360
+ this._traceContent = options.traceContent ?? false;
361
+ }
362
+ start() {
363
+ if (this._started) return;
364
+ this._started = true;
365
+ this._timer = setInterval(() => {
366
+ void this._exportBatch();
367
+ }, this._batchTimeoutMs);
368
+ this._timer.unref();
369
+ this._beforeExitHandler = () => {
370
+ void this.shutdown();
371
+ };
372
+ process.once("beforeExit", this._beforeExitHandler);
373
+ }
374
+ /** Record `count` discarded spans under `reason`.
375
+ *
376
+ * `droppedSpans` is maintained as the exact sum of the labelled counters
377
+ * (RULING §5 back-compat), so the locked pins — which read the flat
378
+ * integer — stay meaningful. */
379
+ _recordDropped(reason, count = 1) {
380
+ this.droppedSpans += count;
381
+ this.droppedSpansByReason[reason] += count;
382
+ }
383
+ /**
384
+ * Run the customer mask over a batch, in place. Never throws.
385
+ *
386
+ * Failure semantics are ruled in `../masking.ts`: a field whose mask throws
387
+ * becomes `MASK_ERROR_MARKER` and the span is kept. The counter is per FIELD;
388
+ * both warnings are rate-limited to one per window so a mask that throws on
389
+ * every span cannot flood the customer's logs — the same shape as the
390
+ * transport-refusal warning above.
391
+ */
392
+ _applyMask(batch) {
393
+ const mask = this._mask;
394
+ if (mask === void 0) return;
395
+ const { errors, elapsedMs } = applyMaskBatch(batch, mask);
396
+ const now = Date.now();
397
+ if (errors > 0) {
398
+ this.maskErrors += errors;
399
+ if (now - this._lastMaskWarnAt > MASK_WARN_WINDOW_MS) {
400
+ this._lastMaskWarnAt = now;
401
+ warnMaskErrors(errors, this.maskErrors);
402
+ }
403
+ }
404
+ if (elapsedMs > MASK_BUDGET_MS_PER_SPAN * batch.length && now - this._lastSlowMaskWarnAt > MASK_WARN_WINDOW_MS) {
405
+ this._lastSlowMaskWarnAt = now;
406
+ warnMaskSlow(batch.length, elapsedMs);
407
+ }
408
+ }
409
+ /**
410
+ * Drain what we hold, or name what we could not (F-SDKDRAIN-001).
411
+ *
412
+ * Per RULING §4 (option E, hard-bounded) the drain loops until ONE of: the
413
+ * queue is empty; the deadline expires; or a full round completes with no
414
+ * exporter returning SUCCESS.
415
+ *
416
+ * ⚠ The `_flushing` handling is load-bearing, and `SDKDRAIN_JS_004` exists
417
+ * to catch its absence. `_exportBatch()` returns immediately when an export
418
+ * is already in flight (`:171`), so a loop that merely calls it again makes
419
+ * NO progress and abandons the queue exactly as before — measured at 900 of
420
+ * 1,000. We await a tick instead, the shape `flush()` already models.
421
+ *
422
+ * Anything still queued when the loop stops is COUNTED as `shutdown_residue`
423
+ * and announced with a WARNING. The warning is the primary signal, not the
424
+ * counter: a counter incremented inside `shutdown()` is written to memory
425
+ * about to be freed and has no reader (RULING §2 / §8.2).
426
+ */
427
+ async shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
428
+ if (!this._started) return;
429
+ this._started = false;
430
+ if (this._timer) {
431
+ clearInterval(this._timer);
432
+ this._timer = null;
433
+ }
434
+ if (this._beforeExitHandler) {
435
+ process.removeListener("beforeExit", this._beforeExitHandler);
436
+ this._beforeExitHandler = null;
437
+ }
438
+ const reserveMs = Math.min(SHUTDOWN_RESERVE_MS, timeoutMs / 2);
439
+ const drainDeadline = Date.now() + Math.max(0, timeoutMs - reserveMs);
440
+ while (this._queue.length > 0 || this._flushing) {
441
+ if (Date.now() >= drainDeadline) break;
442
+ const outcome = await this._exportBatch();
443
+ if (outcome === 3 /* Busy */) {
444
+ await new Promise((r) => setTimeout(r, 1));
445
+ continue;
446
+ }
447
+ if (outcome !== 1 /* Delivered */) {
448
+ break;
449
+ }
450
+ }
451
+ const residue = this._queue.length;
452
+ if (residue > 0) {
453
+ this._queue.length = 0;
454
+ this._recordDropped("shutdown_residue", residue);
455
+ warn(
456
+ `shutdown() gave up with ${residue} span(s) still queued (reason=shutdown_residue) \u2014 they were NOT delivered. The ${timeoutMs} ms shutdown budget expired or the transport stopped accepting. Raise the shutdown timeout, or your container's termination grace period, to lose less.`
457
+ );
458
+ }
459
+ for (const exporter of this._exporters) {
460
+ try {
461
+ await exporter.shutdown();
462
+ } catch (e) {
463
+ debug(`Error shutting down ${exporter.name}: ${e}`);
464
+ }
465
+ }
466
+ this._retryCounts.clear();
467
+ debug(
468
+ `BatchSpanProcessor shutdown. Exported: ${this.exportedSpans}, Dropped: ${this.droppedSpans}, Failed: ${this.failedExports}`
469
+ );
470
+ }
471
+ onSpanEnd(span) {
472
+ if (!this._started) return;
473
+ if (this._queue.length >= this._maxQueueSize) {
474
+ this._recordDropped("queue_full");
475
+ if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
476
+ warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
477
+ }
478
+ return;
479
+ }
480
+ this._queue.push(span);
481
+ if (this._queue.length >= this._batchSize) {
482
+ void this._exportBatch();
483
+ }
484
+ }
485
+ /**
486
+ * Flush pending spans.
487
+ *
488
+ * @returns `true` only if everything queued at entry was DELIVERED.
489
+ *
490
+ * RULING §6. This used to answer a different question — "is the queue
491
+ * empty?" — and those two diverge in exactly one case: when spans left the
492
+ * queue WITHOUT reaching the transport. That case is the entire finding. A
493
+ * customer who calls `flush()` before exit and gets `true` has done
494
+ * everything right; silence lets them discover the problem, a false
495
+ * affirmative forecloses it.
496
+ *
497
+ * Returns `false` when (a) the deadline expires with spans still queued,
498
+ * (b) any span was discarded during the window — breaker refusal or retry
499
+ * exhaustion — or (c) it is called after `shutdown()` and the shutdown
500
+ * residue was non-zero.
501
+ *
502
+ * ⚠ (b) reads the flat total, so a concurrent `queue_full` drop of a span
503
+ * that arrived DURING the window also answers `false`. That is the
504
+ * conservative direction on purpose: a false negative costs a caller one
505
+ * more flush, a false positive is the defect being fixed.
506
+ */
507
+ async flush(timeoutMs = SHUTDOWN_BUDGET_MS) {
508
+ if (!this._started) {
509
+ return this._queue.length === 0 && this.droppedSpansByReason.shutdown_residue === 0;
510
+ }
511
+ const start = Date.now();
512
+ const discardedAtEntry = this.droppedSpans;
513
+ while (this._queue.length > 0 || this._flushing) {
514
+ if (!this._flushing && this._queue.length > 0) {
515
+ await this._exportBatch();
516
+ } else {
517
+ await new Promise((r) => setTimeout(r, 1));
518
+ }
519
+ if (Date.now() - start > timeoutMs) return false;
520
+ }
521
+ return this.droppedSpans === discardedAtEntry;
522
+ }
523
+ getMetrics() {
524
+ return {
525
+ exportedSpans: this.exportedSpans,
526
+ droppedSpans: this.droppedSpans,
527
+ droppedSpansByReason: { ...this.droppedSpansByReason },
528
+ failedExports: this.failedExports,
529
+ maskErrors: this.maskErrors,
530
+ queueSize: this._queue.length,
531
+ queueCapacity: this._maxQueueSize,
532
+ queueUtilization: this._queue.length / this._maxQueueSize
533
+ };
534
+ }
535
+ async _exportBatch() {
536
+ if (this._flushing) return 3 /* Busy */;
537
+ if (this._queue.length === 0) return 0 /* Empty */;
538
+ this._flushing = true;
539
+ try {
540
+ let take = 0;
541
+ let pairs = 0;
542
+ let nbytes = 0;
543
+ const limit = Math.min(this._batchSize, this._queue.length);
544
+ while (take < limit) {
545
+ const head = this._queue[take];
546
+ const spanPairs = spanAttrCount(head);
547
+ const spanBytes = spanBytesEstimate(head);
548
+ if (take > 0 && (pairs + spanPairs > MAX_ATTRIBUTE_PAIRS_PER_BATCH || nbytes + spanBytes > MAX_BATCH_BYTES)) {
549
+ break;
550
+ }
551
+ pairs += spanPairs;
552
+ nbytes += spanBytes;
553
+ take++;
554
+ }
555
+ const batch = this._queue.splice(0, take);
556
+ if (batch.length === 0) return 0 /* Empty */;
557
+ if (!this._traceContent) {
558
+ const stripped = stripContentBatch(batch);
559
+ if (stripped > 0) {
560
+ debug(
561
+ `traceContent is off \u2014 omitted ${stripped} content field(s) from ${batch.length} span(s)`
562
+ );
563
+ }
564
+ }
565
+ if (this._mask !== void 0) {
566
+ this._applyMask(batch);
567
+ }
568
+ debug(`Exporting batch of ${batch.length} spans`);
569
+ let batchExported = false;
570
+ for (const exporter of this._exporters) {
571
+ try {
572
+ const result = await exporter.export(batch);
573
+ if (result === "success" /* SUCCESS */) {
574
+ if (!batchExported) {
575
+ this.exportedSpans += batch.length;
576
+ batchExported = true;
577
+ for (const span of batch) {
578
+ this._retryCounts.delete(span.spanId);
579
+ }
580
+ }
581
+ } else {
582
+ this.failedExports++;
583
+ }
584
+ } catch (e) {
585
+ this.failedExports++;
586
+ debug(`Export to ${exporter.name} failed: ${e}`);
587
+ }
588
+ }
589
+ if (!batchExported) {
590
+ let dropped = 0;
591
+ const retryable = batch.filter((span) => {
592
+ const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;
593
+ if (count > _BatchSpanProcessor.MAX_RETRIES) {
594
+ this._retryCounts.delete(span.spanId);
595
+ this._recordDropped("transport_refused");
596
+ dropped++;
597
+ return false;
598
+ }
599
+ this._retryCounts.set(span.spanId, count);
600
+ return true;
601
+ });
602
+ if (retryable.length > 0) {
603
+ this._queue.unshift(...retryable);
604
+ debug(`Re-queued ${retryable.length} spans for retry (${batch.length - retryable.length} dropped after max retries)`);
605
+ }
606
+ if (dropped > 0) {
607
+ const now = Date.now();
608
+ if (now - this._lastRefusalWarnAt > REFUSAL_WARN_WINDOW_MS) {
609
+ this._lastRefusalWarnAt = now;
610
+ warn(
611
+ `${dropped} span(s) DISCARDED (reason=transport_refused) after ${_BatchSpanProcessor.MAX_RETRIES} failed export attempts each \u2014 the endpoint is not accepting spans and the retry budget is spent. ${this.droppedSpansByReason.transport_refused} span(s) discarded this way so far in this process. This data is gone; check the apiKey and the endpoint.`
612
+ );
613
+ }
614
+ }
615
+ }
616
+ return batchExported ? 1 /* Delivered */ : 2 /* Failed */;
617
+ } finally {
618
+ this._flushing = false;
619
+ }
620
+ }
621
+ };
622
+
623
+ // src/config.ts
624
+ var DEFAULT_ENDPOINT = "https://app.risicare.ai";
625
+ function resolveConfig(config) {
626
+ const env = process.env;
627
+ const apiKey = config?.apiKey ?? env.RISICARE_API_KEY;
628
+ const endpoint = config?.endpoint ?? env.RISICARE_ENDPOINT ?? DEFAULT_ENDPOINT;
629
+ const projectId = config?.projectId ?? env.RISICARE_PROJECT_ID;
630
+ if (config?.projectId || env.RISICARE_PROJECT_ID) {
631
+ console.warn(
632
+ "[risicare] projectId is deprecated and ignored by the gateway. Your API key determines the project. Use serviceName and environment for within-project organization. projectId will be removed in v1.0."
633
+ );
634
+ }
635
+ const environment = config?.environment ?? env.RISICARE_ENVIRONMENT ?? "development";
636
+ const serviceName = config?.serviceName ?? env.RISICARE_SERVICE_NAME;
637
+ const serviceVersion = config?.serviceVersion ?? env.RISICARE_SERVICE_VERSION;
638
+ const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, false);
639
+ const sampleRateRaw = config?.sampleRate ?? parseFloat(env.RISICARE_SAMPLE_RATE ?? "1.0");
640
+ const debug2 = config?.debug ?? parseBool(env.RISICARE_DEBUG, false);
641
+ const compress = config?.compress ?? parseBool(env.RISICARE_COMPRESS, false);
642
+ const batchSizeRaw = config?.batchSize ?? parseNumericEnv(env.RISICARE_BATCH_SIZE, DEFAULT_BATCH_SIZE);
643
+ const batchTimeoutMsRaw = config?.batchTimeoutMs ?? parseNumericEnv(env.RISICARE_BATCH_TIMEOUT_MS, 1e3);
644
+ const maxQueueSizeRaw = config?.maxQueueSize ?? parseNumericEnv(env.RISICARE_MAX_QUEUE_SIZE, 1e4);
645
+ const sampleRate = validateSampleRate(sampleRateRaw);
646
+ if (sampleRate < 1) {
647
+ console.warn(
648
+ `[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.`
649
+ );
650
+ }
651
+ const batchSize = validatePositiveInt("batchSize", batchSizeRaw, DEFAULT_BATCH_SIZE, 1, 1e4);
652
+ const batchTimeoutMs = validatePositiveInt("batchTimeoutMs", batchTimeoutMsRaw, 1e3, 1, 6e5);
653
+ const maxQueueSize = validatePositiveInt("maxQueueSize", maxQueueSizeRaw, 1e4, 1, 1e6);
654
+ let enabled;
655
+ if (config?.enabled !== void 0) {
656
+ enabled = config.enabled;
657
+ } else if (env.RISICARE_TRACING !== void 0) {
658
+ enabled = parseBool(env.RISICARE_TRACING, false);
659
+ } else {
660
+ enabled = !!apiKey;
661
+ }
662
+ return {
663
+ apiKey: apiKey ?? "",
664
+ endpoint,
665
+ projectId: projectId ?? "",
666
+ environment,
667
+ serviceName: serviceName ?? "",
668
+ serviceVersion: serviceVersion ?? "",
669
+ enabled,
670
+ traceContent,
671
+ sampleRate,
672
+ batchSize,
673
+ batchTimeoutMs,
674
+ maxQueueSize,
675
+ debug: debug2,
676
+ compress,
677
+ metadata: config?.metadata ?? {},
678
+ // No env fallback — see the field's note on RisicareConfig.
679
+ mask: config?.mask
680
+ };
681
+ }
682
+ function parseBool(value, defaultValue) {
683
+ if (value === void 0) return defaultValue;
684
+ const lower = value.toLowerCase();
685
+ return lower === "true" || lower === "1" || lower === "yes";
686
+ }
687
+ function parseNumericEnv(value, defaultValue) {
688
+ if (value === void 0) return defaultValue;
689
+ const n = Number(value);
690
+ return Number.isFinite(n) ? n : defaultValue;
691
+ }
692
+ function validateSampleRate(value) {
693
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1) {
694
+ return value;
695
+ }
696
+ if (typeof value === "string") {
697
+ const n = Number(value);
698
+ if (Number.isFinite(n) && n >= 0 && n <= 1) return n;
699
+ }
700
+ console.warn(
701
+ `[risicare] sampleRate must be a finite number in [0, 1], got ${typeof value}=${JSON.stringify(value)}; defaulting to 1.0`
702
+ );
703
+ return 1;
704
+ }
705
+ function validatePositiveInt(name, value, defaultValue, min, max) {
706
+ let n;
707
+ if (typeof value === "number") {
708
+ n = value;
709
+ } else if (typeof value === "string") {
710
+ n = Number(value);
711
+ if (Number.isFinite(n)) {
712
+ console.warn(
713
+ `[risicare] ${name} was a string ("${value}"); coerced to ${n}. Pass a number to avoid this warning.`
714
+ );
715
+ }
716
+ } else {
717
+ console.warn(
718
+ `[risicare] ${name} must be a positive integer, got ${typeof value}; defaulting to ${defaultValue}`
719
+ );
720
+ return defaultValue;
721
+ }
722
+ if (!Number.isFinite(n) || n <= 0) {
723
+ console.warn(
724
+ `[risicare] ${name} must be > 0, got ${value}; defaulting to ${defaultValue}`
725
+ );
726
+ return defaultValue;
727
+ }
728
+ if (n < min) {
729
+ console.warn(`[risicare] ${name}=${n} below floor; clamping to ${min}`);
730
+ return min;
731
+ }
732
+ if (n > max) {
733
+ console.warn(`[risicare] ${name}=${n} above ceiling; clamping to ${max}`);
734
+ return max;
735
+ }
736
+ return Math.floor(n);
737
+ }
738
+
739
+ // src/ids.ts
740
+ import { randomBytes } from "crypto";
741
+ var HEX_REGEX_32 = /^[0-9a-f]{32}$/;
742
+ var HEX_REGEX_16 = /^[0-9a-f]{16}$/;
743
+ function generateTraceId() {
744
+ return randomBytes(16).toString("hex");
745
+ }
746
+ function generateSpanId() {
747
+ return randomBytes(8).toString("hex");
748
+ }
749
+ function generateAgentId(prefix) {
750
+ const suffix = randomBytes(8).toString("hex");
751
+ return prefix ? `${prefix}-${suffix}` : suffix;
752
+ }
753
+ function validateTraceId(id) {
754
+ return HEX_REGEX_32.test(id);
755
+ }
756
+ function validateSpanId(id) {
757
+ return HEX_REGEX_16.test(id);
758
+ }
759
+
760
+ // src/types.ts
761
+ var SpanKind = /* @__PURE__ */ ((SpanKind2) => {
762
+ SpanKind2["INTERNAL"] = "internal";
763
+ SpanKind2["CLIENT"] = "client";
764
+ SpanKind2["SERVER"] = "server";
765
+ SpanKind2["PRODUCER"] = "producer";
766
+ SpanKind2["CONSUMER"] = "consumer";
767
+ SpanKind2["AGENT"] = "agent";
768
+ SpanKind2["LLM_CALL"] = "llm_call";
769
+ SpanKind2["TOOL_CALL"] = "tool_call";
770
+ SpanKind2["RETRIEVAL"] = "retrieval";
771
+ SpanKind2["DECISION"] = "decision";
772
+ SpanKind2["MESSAGE"] = "message";
773
+ SpanKind2["DELEGATION"] = "delegation";
774
+ SpanKind2["COORDINATION"] = "coordination";
775
+ SpanKind2["THINK"] = "think";
776
+ SpanKind2["DECIDE"] = "decide";
777
+ SpanKind2["OBSERVE"] = "observe";
778
+ SpanKind2["REFLECT"] = "reflect";
779
+ return SpanKind2;
780
+ })(SpanKind || {});
781
+ var SpanStatus = /* @__PURE__ */ ((SpanStatus2) => {
782
+ SpanStatus2["UNSET"] = "unset";
783
+ SpanStatus2["OK"] = "ok";
784
+ SpanStatus2["ERROR"] = "error";
785
+ return SpanStatus2;
786
+ })(SpanStatus || {});
787
+ var SemanticPhase = /* @__PURE__ */ ((SemanticPhase2) => {
788
+ SemanticPhase2["THINK"] = "think";
789
+ SemanticPhase2["DECIDE"] = "decide";
790
+ SemanticPhase2["ACT"] = "act";
791
+ SemanticPhase2["OBSERVE"] = "observe";
792
+ SemanticPhase2["REFLECT"] = "reflect";
793
+ SemanticPhase2["COMMUNICATE"] = "communicate";
794
+ SemanticPhase2["COORDINATE"] = "coordinate";
795
+ return SemanticPhase2;
796
+ })(SemanticPhase || {});
797
+ var AgentRole = /* @__PURE__ */ ((AgentRole2) => {
798
+ AgentRole2["ORCHESTRATOR"] = "orchestrator";
799
+ AgentRole2["WORKER"] = "worker";
800
+ AgentRole2["SUPERVISOR"] = "supervisor";
801
+ AgentRole2["SPECIALIST"] = "specialist";
802
+ AgentRole2["ROUTER"] = "router";
803
+ AgentRole2["AGGREGATOR"] = "aggregator";
804
+ AgentRole2["BROADCASTER"] = "broadcaster";
805
+ AgentRole2["CRITIC"] = "critic";
806
+ AgentRole2["PLANNER"] = "planner";
185
807
  AgentRole2["EXECUTOR"] = "executor";
186
808
  AgentRole2["RETRIEVER"] = "retriever";
187
809
  AgentRole2["VALIDATOR"] = "validator";
@@ -465,45 +1087,442 @@ function shouldSample(traceId, sampleRate) {
465
1087
  return hash / 4294967295 < sampleRate;
466
1088
  }
467
1089
 
468
- // src/globals.ts
469
- import { AsyncLocalStorage } from "async_hooks";
470
- var G = globalThis;
471
- var PREFIX = "__risicare_";
472
- function getClient() {
473
- return G[PREFIX + "client"];
1090
+ // src/runtime/config.ts
1091
+ function resolveFixRuntimeConfig(config) {
1092
+ return {
1093
+ apiEndpoint: config.apiEndpoint,
1094
+ apiKey: config.apiKey,
1095
+ enabled: config.enabled ?? true,
1096
+ cacheEnabled: config.cacheEnabled ?? true,
1097
+ cacheTtlMs: config.cacheTtlMs ?? 3e5,
1098
+ cacheMaxEntries: config.cacheMaxEntries ?? 1e3,
1099
+ autoRefresh: config.autoRefresh ?? true,
1100
+ refreshIntervalMs: config.refreshIntervalMs ?? 6e4,
1101
+ dryRun: config.dryRun ?? false,
1102
+ abTestingEnabled: config.abTestingEnabled ?? true,
1103
+ timeoutMs: config.timeoutMs ?? 1e3,
1104
+ debug: config.debug ?? false
1105
+ };
474
1106
  }
475
- function setClient(client) {
476
- G[PREFIX + "client"] = client;
1107
+ function matchesError(fix, errorCode) {
1108
+ if (fix.errorCode === errorCode) {
1109
+ return true;
1110
+ }
1111
+ if (fix.errorCode.endsWith("*")) {
1112
+ const prefix = fix.errorCode.slice(0, -1);
1113
+ return errorCode.startsWith(prefix);
1114
+ }
1115
+ return false;
477
1116
  }
478
- function getTracer() {
479
- return G[PREFIX + "tracer"];
1117
+ function shouldApply(fix, sessionHash) {
1118
+ if (fix.trafficPercentage >= 100) return true;
1119
+ if (fix.trafficPercentage <= 0) return false;
1120
+ const bucket = sessionHash % 100;
1121
+ return bucket < fix.trafficPercentage;
480
1122
  }
481
- function setTracer(tracer) {
482
- G[PREFIX + "tracer"] = tracer;
1123
+ function activeFixFromApiResponse(item) {
1124
+ return {
1125
+ fixId: item.id ?? item.fix_id ?? item.fixId ?? "",
1126
+ deploymentId: item.deployment_id ?? item.deploymentId ?? "",
1127
+ errorCode: item.error_code ?? item.errorCode ?? "",
1128
+ fixType: item.fix_type ?? item.fixType ?? "prompt",
1129
+ config: item.config ?? {},
1130
+ trafficPercentage: item.traffic_percentage ?? item.trafficPercentage ?? 100,
1131
+ version: item.version ?? 1
1132
+ };
483
1133
  }
484
- function getContextStorage() {
485
- if (!G[PREFIX + "ctx"]) {
486
- G[PREFIX + "ctx"] = new AsyncLocalStorage();
1134
+
1135
+ // src/runtime/taxonomy.generated.ts
1136
+ var CANONICAL_ERROR_CODES = /* @__PURE__ */ new Set([
1137
+ "COMMUNICATION.CONTENT.AMBIGUOUS",
1138
+ "COMMUNICATION.CONTENT.CORRUPTED",
1139
+ "COMMUNICATION.CONTENT.INCOMPATIBLE",
1140
+ "COMMUNICATION.CONTENT.MALFORMED",
1141
+ "COMMUNICATION.CONTENT.TOO_LARGE",
1142
+ "COMMUNICATION.DELIVERY.DELAYED",
1143
+ "COMMUNICATION.DELIVERY.DUPLICATED",
1144
+ "COMMUNICATION.DELIVERY.EXPIRED",
1145
+ "COMMUNICATION.DELIVERY.OUT_OF_ORDER",
1146
+ "COMMUNICATION.DELIVERY.UNDELIVERABLE",
1147
+ "COMMUNICATION.ROUTING.BROADCAST_STORM",
1148
+ "COMMUNICATION.ROUTING.LOOP",
1149
+ "COMMUNICATION.ROUTING.NO_ROUTE",
1150
+ "COMMUNICATION.ROUTING.PARTITION",
1151
+ "COMMUNICATION.ROUTING.WRONG_ROUTE",
1152
+ "CONSENSUS.AGREEMENT.INCONSISTENT",
1153
+ "CONSENSUS.AGREEMENT.QUORUM_FAILED",
1154
+ "CONSENSUS.AGREEMENT.REJECTED",
1155
+ "CONSENSUS.AGREEMENT.STALE_VOTE",
1156
+ "CONSENSUS.AGREEMENT.TIMEOUT",
1157
+ "CONSENSUS.CONFLICT.BIAS",
1158
+ "CONSENSUS.CONFLICT.CASCADING",
1159
+ "CONSENSUS.CONFLICT.DEADLOCK",
1160
+ "CONSENSUS.CONFLICT.RESOLUTION_REJECTED",
1161
+ "CONSENSUS.CONFLICT.UNRESOLVED",
1162
+ "CONSENSUS.VOTING.ABSTENTION_FLOOD",
1163
+ "CONSENSUS.VOTING.COERCED_VOTE",
1164
+ "CONSENSUS.VOTING.DUPLICATE_VOTE",
1165
+ "CONSENSUS.VOTING.INVALID_VOTE",
1166
+ "CONSENSUS.VOTING.SPLIT_VOTE",
1167
+ "COORDINATION.HANDOFF.DELAYED",
1168
+ "COORDINATION.HANDOFF.DUPLICATED",
1169
+ "COORDINATION.HANDOFF.INCOMPLETE",
1170
+ "COORDINATION.HANDOFF.LOST",
1171
+ "COORDINATION.HANDOFF.WRONG_RECIPIENT",
1172
+ "COORDINATION.SYNCHRONIZATION.CLOCK_SKEW",
1173
+ "COORDINATION.SYNCHRONIZATION.OUT_OF_ORDER",
1174
+ "COORDINATION.SYNCHRONIZATION.RACE_CONDITION",
1175
+ "COORDINATION.SYNCHRONIZATION.SPLIT_BRAIN",
1176
+ "COORDINATION.SYNCHRONIZATION.VERSION_MISMATCH",
1177
+ "COORDINATION.WORKFLOW.CYCLE",
1178
+ "COORDINATION.WORKFLOW.DEADLOCK",
1179
+ "COORDINATION.WORKFLOW.LIVELOCK",
1180
+ "COORDINATION.WORKFLOW.ORPHANED",
1181
+ "COORDINATION.WORKFLOW.STARVATION",
1182
+ "MEMORY.CONTEXT_WINDOW.DROPPED",
1183
+ "MEMORY.CONTEXT_WINDOW.EXCEEDED",
1184
+ "MEMORY.CONTEXT_WINDOW.FRAGMENTED",
1185
+ "MEMORY.CONTEXT_WINDOW.PRIORITY_ERROR",
1186
+ "MEMORY.RETRIEVAL.INCOMPLETE",
1187
+ "MEMORY.RETRIEVAL.NOT_FOUND",
1188
+ "MEMORY.RETRIEVAL.OUTDATED",
1189
+ "MEMORY.RETRIEVAL.TOO_MANY",
1190
+ "MEMORY.RETRIEVAL.WRONG_MATCH",
1191
+ "MEMORY.STATE.CORRUPTED",
1192
+ "MEMORY.STATE.INCONSISTENT",
1193
+ "MEMORY.STATE.LOST",
1194
+ "MEMORY.STATE.OVERFLOW",
1195
+ "MEMORY.STATE.STALE",
1196
+ "ORCHESTRATION.DELEGATION.CAPABILITY_MISMATCH",
1197
+ "ORCHESTRATION.DELEGATION.CIRCULAR_DELEGATION",
1198
+ "ORCHESTRATION.DELEGATION.EXCESSIVE_DEPTH",
1199
+ "ORCHESTRATION.DELEGATION.NO_AVAILABLE_AGENT",
1200
+ "ORCHESTRATION.DELEGATION.OVERLOADED_AGENT",
1201
+ "ORCHESTRATION.LIFECYCLE.CLEANUP_FAILED",
1202
+ "ORCHESTRATION.LIFECYCLE.CRASHED",
1203
+ "ORCHESTRATION.LIFECYCLE.HUNG",
1204
+ "ORCHESTRATION.LIFECYCLE.SPAWN_FAILED",
1205
+ "ORCHESTRATION.LIFECYCLE.ZOMBIE",
1206
+ "ORCHESTRATION.SCALING.OVERLOADED",
1207
+ "ORCHESTRATION.SCALING.QUOTA_EXCEEDED",
1208
+ "ORCHESTRATION.SCALING.SCALE_DOWN_FAILED",
1209
+ "ORCHESTRATION.SCALING.SCALE_UP_FAILED",
1210
+ "ORCHESTRATION.SCALING.UNDERUTILIZED",
1211
+ "OUTPUT.FORMAT.ENCODING",
1212
+ "OUTPUT.FORMAT.INVALID_JSON",
1213
+ "OUTPUT.FORMAT.MALFORMED",
1214
+ "OUTPUT.FORMAT.SCHEMA_VIOLATION",
1215
+ "OUTPUT.FORMAT.TRUNCATED",
1216
+ "OUTPUT.QUALITY.INCOMPLETE",
1217
+ "OUTPUT.QUALITY.IRRELEVANT",
1218
+ "OUTPUT.QUALITY.REPETITIVE",
1219
+ "OUTPUT.QUALITY.UNCLEAR",
1220
+ "OUTPUT.QUALITY.VERBOSE",
1221
+ "OUTPUT.SAFETY.BIAS",
1222
+ "OUTPUT.SAFETY.COPYRIGHT",
1223
+ "OUTPUT.SAFETY.HARMFUL_CONTENT",
1224
+ "OUTPUT.SAFETY.PII_LEAK",
1225
+ "OUTPUT.SAFETY.POLICY_VIOLATION",
1226
+ "PERCEPTION.CONTEXT.CONFLICTING",
1227
+ "PERCEPTION.CONTEXT.IRRELEVANT",
1228
+ "PERCEPTION.CONTEXT.MISSING",
1229
+ "PERCEPTION.CONTEXT.OVERFLOW",
1230
+ "PERCEPTION.CONTEXT.STALE",
1231
+ "PERCEPTION.INPUT.ENCODING",
1232
+ "PERCEPTION.INPUT.INJECTION",
1233
+ "PERCEPTION.INPUT.MALFORMED",
1234
+ "PERCEPTION.INPUT.SCHEMA_MISMATCH",
1235
+ "PERCEPTION.INPUT.TRUNCATED",
1236
+ "PERCEPTION.PARSING.DATE_FORMAT",
1237
+ "PERCEPTION.PARSING.JSON_INVALID",
1238
+ "PERCEPTION.PARSING.NUMBER_FORMAT",
1239
+ "PERCEPTION.PARSING.REFERENCE_BROKEN",
1240
+ "PERCEPTION.PARSING.XML_INVALID",
1241
+ "REASONING.DECISION.BIASED",
1242
+ "REASONING.DECISION.INDECISIVE",
1243
+ "REASONING.DECISION.OSCILLATING",
1244
+ "REASONING.DECISION.OVERCONFIDENT",
1245
+ "REASONING.DECISION.PREMATURE",
1246
+ "REASONING.HALLUCINATION.CAPABILITY",
1247
+ "REASONING.HALLUCINATION.CITATION",
1248
+ "REASONING.HALLUCINATION.ENTITY",
1249
+ "REASONING.HALLUCINATION.FACTUAL",
1250
+ "REASONING.HALLUCINATION.TEMPORAL",
1251
+ "REASONING.LOGIC.CIRCULAR",
1252
+ "REASONING.LOGIC.CONTRADICTION",
1253
+ "REASONING.LOGIC.INCOMPLETE",
1254
+ "REASONING.LOGIC.INVALID_INFERENCE",
1255
+ "REASONING.LOGIC.MISSING_PREMISE",
1256
+ "REASONING.PLANNING.INCOMPLETE",
1257
+ "REASONING.PLANNING.INFEASIBLE",
1258
+ "REASONING.PLANNING.SCOPE_CREEP",
1259
+ "REASONING.PLANNING.SUBOPTIMAL",
1260
+ "REASONING.PLANNING.UNSAFE",
1261
+ "RESOURCES.ACCESS.DENIED",
1262
+ "RESOURCES.ACCESS.EXPIRED",
1263
+ "RESOURCES.ACCESS.LOCKED",
1264
+ "RESOURCES.ACCESS.NOT_FOUND",
1265
+ "RESOURCES.ACCESS.REVOKED",
1266
+ "RESOURCES.CONTENTION.DEADLOCK",
1267
+ "RESOURCES.CONTENTION.OVERFLOW",
1268
+ "RESOURCES.CONTENTION.PRIORITY_INVERSION",
1269
+ "RESOURCES.CONTENTION.STARVATION",
1270
+ "RESOURCES.CONTENTION.THRASHING",
1271
+ "RESOURCES.QUOTA.ALLOCATION_FAILED",
1272
+ "RESOURCES.QUOTA.EXCEEDED",
1273
+ "RESOURCES.QUOTA.LEAK",
1274
+ "RESOURCES.QUOTA.STALE",
1275
+ "RESOURCES.QUOTA.UNFAIR_DISTRIBUTION",
1276
+ "TOOL.EXECUTION.CRASHED",
1277
+ "TOOL.EXECUTION.DEPENDENCY_FAILED",
1278
+ "TOOL.EXECUTION.RATE_LIMITED",
1279
+ "TOOL.EXECUTION.RESOURCE_EXHAUSTED",
1280
+ "TOOL.EXECUTION.TIMEOUT",
1281
+ "TOOL.INVOCATION.INVALID_ARGS",
1282
+ "TOOL.INVOCATION.MISSING_REQUIRED",
1283
+ "TOOL.INVOCATION.NOT_FOUND",
1284
+ "TOOL.INVOCATION.PERMISSION_DENIED",
1285
+ "TOOL.INVOCATION.TYPE_MISMATCH",
1286
+ "TOOL.RESULT.EMPTY",
1287
+ "TOOL.RESULT.ERROR_IN_RESULT",
1288
+ "TOOL.RESULT.PARTIAL",
1289
+ "TOOL.RESULT.UNEXPECTED_FORMAT",
1290
+ "TOOL.RESULT.UNPARSEABLE"
1291
+ ]);
1292
+ var SUPPLEMENTAL_RULES = [
1293
+ { re: new RegExp("timeout|timedout|aborted", "i"), code: "TOOL.EXECUTION.TIMEOUT" },
1294
+ { re: new RegExp("rate.?limit|\\b429\\b|too many requests", "i"), code: "TOOL.EXECUTION.RATE_LIMITED" },
1295
+ { re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "i"), code: "TOOL.EXECUTION.DEPENDENCY_FAILED" },
1296
+ { re: new RegExp("\\bauth|unauthorized|forbidden|permission|\\b401\\b|\\b403\\b", "i"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
1297
+ { re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "i"), code: "PERCEPTION.PARSING.JSON_INVALID" }
1298
+ ];
1299
+ var GENERIC_FALLBACK = "TOOL.EXECUTION.CRASHED";
1300
+
1301
+ // src/runtime/interceptors.ts
1302
+ var GuardRejectedError = class extends Error {
1303
+ guardId;
1304
+ reason;
1305
+ phase;
1306
+ constructor(guardId, reason, phase) {
1307
+ super(`Risicare guard rejected operation: ${guardId} (${phase}) \u2014 ${reason}`);
1308
+ this.name = "GuardRejectedError";
1309
+ this.guardId = guardId;
1310
+ this.reason = reason;
1311
+ this.phase = phase;
1312
+ }
1313
+ };
1314
+ function createInterceptContext(operationType, operationName, options) {
1315
+ return {
1316
+ operationType,
1317
+ operationName,
1318
+ sessionId: options?.sessionId,
1319
+ traceId: options?.traceId,
1320
+ errorCode: options?.errorCode,
1321
+ attempt: 1,
1322
+ appliedFixes: []
1323
+ };
1324
+ }
1325
+ var DefaultFixInterceptor = class {
1326
+ _config;
1327
+ _cache;
1328
+ _applier;
1329
+ constructor(config, cache, applier) {
1330
+ this._config = resolveFixRuntimeConfig(config);
1331
+ this._cache = cache;
1332
+ this._applier = applier;
1333
+ }
1334
+ /**
1335
+ * Apply pre-call fixes.
1336
+ *
1337
+ * - If retrying after error: look up fix by error_code, apply
1338
+ * prompt/parameter/fallback fixes
1339
+ * - Runs input guard fixes on all message content
1340
+ */
1341
+ preCall(ctx, messages, params) {
1342
+ try {
1343
+ if (!this._config.enabled) {
1344
+ return { messages, params };
1345
+ }
1346
+ let modifiedMessages = messages;
1347
+ let modifiedParams = { ...params };
1348
+ if (ctx.errorCode) {
1349
+ const fix = this._applier.getFixForError(ctx.errorCode, ctx.sessionId);
1350
+ if (fix) {
1351
+ debug(`Applying fix ${fix.fixId} for ${ctx.errorCode}`);
1352
+ if (fix.fixType === "prompt" && messages) {
1353
+ const msgRecords = messages;
1354
+ const { messages: newMessages, result } = this._applier.applyPromptFix(fix, msgRecords);
1355
+ modifiedMessages = newMessages;
1356
+ ctx.appliedFixes.push(result);
1357
+ this._applier.logApplication(result);
1358
+ } else if (fix.fixType === "parameter") {
1359
+ const { params: newParams, result } = this._applier.applyParameterFix(fix, modifiedParams);
1360
+ modifiedParams = newParams;
1361
+ ctx.appliedFixes.push(result);
1362
+ this._applier.logApplication(result);
1363
+ } else if (fix.fixType === "fallback") {
1364
+ const { params: newParams, result } = this._applier.applyFallbackFix(fix, modifiedParams);
1365
+ modifiedParams = newParams;
1366
+ ctx.appliedFixes.push(result);
1367
+ this._applier.logApplication(result);
1368
+ }
1369
+ }
1370
+ }
1371
+ if (modifiedMessages && this._config.enabled) {
1372
+ for (const msg of modifiedMessages) {
1373
+ const content = msg.content;
1374
+ if (typeof content === "string") {
1375
+ for (const fix of this._cache.getAll()) {
1376
+ if (fix.fixType === "guard") {
1377
+ const { passed, result } = this._applier.applyGuardFix(
1378
+ fix,
1379
+ content,
1380
+ true
1381
+ );
1382
+ if (result.applied) {
1383
+ ctx.appliedFixes.push(result);
1384
+ this._applier.logApplication(result);
1385
+ }
1386
+ if (!passed) {
1387
+ throw new GuardRejectedError(
1388
+ fix.fixId ?? "unknown",
1389
+ result.reason ?? "guard rejected input",
1390
+ "pre_call"
1391
+ );
1392
+ }
1393
+ }
1394
+ }
1395
+ }
1396
+ }
1397
+ }
1398
+ return { messages: modifiedMessages, params: modifiedParams };
1399
+ } catch (e) {
1400
+ if (e instanceof GuardRejectedError) throw e;
1401
+ debug(`DefaultFixInterceptor.preCall error: ${e}`);
1402
+ return { messages, params };
1403
+ }
1404
+ }
1405
+ /**
1406
+ * Apply post-call fixes (output validation).
1407
+ *
1408
+ * Runs output guard fixes on response content.
1409
+ */
1410
+ postCall(ctx, response) {
1411
+ try {
1412
+ if (!this._config.enabled) {
1413
+ return { response, shouldContinue: true };
1414
+ }
1415
+ for (const fix of this._cache.getAll()) {
1416
+ if (fix.fixType !== "guard") continue;
1417
+ const content = this._extractResponseContent(response);
1418
+ if (!content) continue;
1419
+ const { passed, result } = this._applier.applyGuardFix(
1420
+ fix,
1421
+ content,
1422
+ false
1423
+ );
1424
+ if (result.applied) {
1425
+ ctx.appliedFixes.push(result);
1426
+ this._applier.logApplication(result);
1427
+ }
1428
+ if (!passed) {
1429
+ warn(`Output guard failed for fix ${fix.fixId}: ${result.reason ?? "unknown"}`);
1430
+ throw new GuardRejectedError(
1431
+ fix.fixId ?? "unknown",
1432
+ result.reason ?? "guard rejected output",
1433
+ "post_call"
1434
+ );
1435
+ }
1436
+ }
1437
+ return { response, shouldContinue: true };
1438
+ } catch (e) {
1439
+ if (e instanceof GuardRejectedError) throw e;
1440
+ debug(`DefaultFixInterceptor.postCall error: ${e}`);
1441
+ return { response, shouldContinue: true };
1442
+ }
1443
+ }
1444
+ /**
1445
+ * Handle errors and decide whether to retry.
1446
+ *
1447
+ * Classifies the error, looks up retry/fallback fixes, and returns
1448
+ * whether the caller should retry.
1449
+ */
1450
+ onError(ctx, error) {
1451
+ try {
1452
+ if (!this._config.enabled) {
1453
+ return { shouldRetry: false, modifiedParams: null };
1454
+ }
1455
+ const errorCode = classifyError(error);
1456
+ ctx.errorCode = errorCode;
1457
+ ctx.errorMessage = error.message;
1458
+ const fix = this._applier.getFixForError(errorCode, ctx.sessionId);
1459
+ if (!fix) {
1460
+ return { shouldRetry: false, modifiedParams: null };
1461
+ }
1462
+ if (fix.fixType === "retry") {
1463
+ const maxRetries = fix.config.max_retries ?? fix.config.maxRetries ?? 3;
1464
+ if (ctx.attempt <= maxRetries) {
1465
+ debug(
1466
+ `Retry fix ${fix.fixId}: attempt ${ctx.attempt}/${maxRetries}`
1467
+ );
1468
+ const result = {
1469
+ applied: true,
1470
+ fixId: fix.fixId,
1471
+ deploymentId: fix.deploymentId,
1472
+ fixType: "retry",
1473
+ modifications: { attempt: ctx.attempt }
1474
+ };
1475
+ ctx.appliedFixes.push(result);
1476
+ this._applier.logApplication(result);
1477
+ return { shouldRetry: true, modifiedParams: null };
1478
+ }
1479
+ }
1480
+ if (fix.fixType === "fallback") {
1481
+ const { params: modifiedParams, result } = this._applier.applyFallbackFix(fix, {});
1482
+ if (result.applied) {
1483
+ ctx.appliedFixes.push(result);
1484
+ this._applier.logApplication(result);
1485
+ return { shouldRetry: true, modifiedParams };
1486
+ }
1487
+ }
1488
+ return { shouldRetry: false, modifiedParams: null };
1489
+ } catch (e) {
1490
+ debug(`DefaultFixInterceptor.onError error: ${e}`);
1491
+ return { shouldRetry: false, modifiedParams: null };
1492
+ }
487
1493
  }
488
- return G[PREFIX + "ctx"];
489
- }
490
- function getRegistry() {
491
- if (!G[PREFIX + "registry"]) {
492
- G[PREFIX + "registry"] = /* @__PURE__ */ new Map();
1494
+ // ─── Private ────────────────────────────────────────────────────────────
1495
+ /** Extract text content from a response object. */
1496
+ _extractResponseContent(response) {
1497
+ if (typeof response === "string") return response;
1498
+ if (response && typeof response === "object") {
1499
+ const resp = response;
1500
+ const choices = resp.choices;
1501
+ if (Array.isArray(choices) && choices.length > 0) {
1502
+ const first = choices[0];
1503
+ const message = first?.message;
1504
+ if (typeof message?.content === "string") {
1505
+ return message.content;
1506
+ }
1507
+ }
1508
+ const content = resp.content;
1509
+ if (typeof content === "string") return content;
1510
+ if (Array.isArray(content) && content.length > 0) {
1511
+ const first = content[0];
1512
+ if (typeof first?.text === "string") return first.text;
1513
+ }
1514
+ }
1515
+ return null;
493
1516
  }
494
- return G[PREFIX + "registry"];
495
- }
496
- function getOpCount() {
497
- return G[PREFIX + "opcount"] ?? 0;
498
- }
499
- function setOpCount(n) {
500
- G[PREFIX + "opcount"] = n;
501
- }
502
- function getDebug() {
503
- return G[PREFIX + "debug"] ?? false;
504
- }
505
- function setDebugFlag(enabled) {
506
- G[PREFIX + "debug"] = enabled;
1517
+ };
1518
+ function classifyError(error) {
1519
+ const haystack = `${error?.constructor?.name ?? "Error"} ${error?.message ?? ""}`;
1520
+ for (const rule of SUPPLEMENTAL_RULES) {
1521
+ if (rule.re.test(haystack)) {
1522
+ return CANONICAL_ERROR_CODES.has(rule.code) ? rule.code : GENERIC_FALLBACK;
1523
+ }
1524
+ }
1525
+ return CANONICAL_ERROR_CODES.has(GENERIC_FALLBACK) ? GENERIC_FALLBACK : "";
507
1526
  }
508
1527
 
509
1528
  // src/context/storage.ts
@@ -567,16 +1586,30 @@ function getCurrentContext() {
567
1586
  }
568
1587
 
569
1588
  // src/tracer.ts
1589
+ function attachErrorCode(span, error) {
1590
+ try {
1591
+ const err = error instanceof Error ? error : new Error(String(error));
1592
+ const code = classifyError(err);
1593
+ if (code) {
1594
+ span.setAttribute("error.code", code);
1595
+ }
1596
+ } catch {
1597
+ }
1598
+ }
570
1599
  var Tracer = class {
571
1600
  _onSpanEnd;
572
1601
  _sampleRate;
573
1602
  _enabled;
574
1603
  _traceContent;
1604
+ _serviceName;
1605
+ _serviceVersion;
575
1606
  constructor(config) {
576
1607
  this._onSpanEnd = config.onSpanEnd;
577
1608
  this._sampleRate = config.sampleRate ?? 1;
578
1609
  this._enabled = config.enabled ?? true;
579
- this._traceContent = config.traceContent ?? true;
1610
+ this._traceContent = config.traceContent ?? false;
1611
+ this._serviceName = config.serviceName || void 0;
1612
+ this._serviceVersion = config.serviceVersion || void 0;
580
1613
  }
581
1614
  get enabled() {
582
1615
  return this._enabled;
@@ -610,10 +1643,16 @@ var Tracer = class {
610
1643
  const phase = getCurrentPhase();
611
1644
  const ctx = getContext();
612
1645
  const traceId = opts.traceId ?? parentSpan?.traceId ?? ctx._rootTraceId ?? generateTraceId();
613
- if (!parentSpan && this._sampleRate < 1) {
614
- if (!shouldSample(traceId, this._sampleRate)) {
1646
+ if (!parentSpan) {
1647
+ if (ctx._traceSampled === false) {
615
1648
  return fn(NOOP_SPAN);
616
1649
  }
1650
+ if (this._sampleRate < 1 && !shouldSample(traceId, this._sampleRate)) {
1651
+ return runWithContext(
1652
+ { _traceSampled: false },
1653
+ () => fn(NOOP_SPAN)
1654
+ );
1655
+ }
617
1656
  }
618
1657
  const parentSpanId = opts.parentSpanId ?? parentSpan?.spanId;
619
1658
  const spanOptions = {
@@ -626,7 +1665,12 @@ var Tracer = class {
626
1665
  // Propagate context fields as attributes (matching Python SDK tracer.py:497-511)
627
1666
  ...agent2?.agentRole ? { "agent.role": agent2.agentRole } : {},
628
1667
  ...agent2?.parentAgentId ? { "parent_agent_id": agent2.parentAgentId } : {},
629
- ...session2?.userId ? { "session.user_id": session2.userId } : {}
1668
+ ...session2?.userId ? { "session.user_id": session2.userId } : {},
1669
+ // F-SDKJSSVCNAME-001 — `service.name` is suppressed when an agent
1670
+ // identity is present (the agent takes priority), matching Python;
1671
+ // `service.version` never is.
1672
+ ...this._serviceName && !agent2 ? { "service.name": this._serviceName } : {},
1673
+ ...this._serviceVersion ? { "service.version": this._serviceVersion } : {}
630
1674
  },
631
1675
  sessionId: session2?.sessionId,
632
1676
  agentId: agent2?.agentId,
@@ -645,6 +1689,7 @@ var Tracer = class {
645
1689
  },
646
1690
  (error) => {
647
1691
  span.recordException(error instanceof Error ? error : String(error));
1692
+ attachErrorCode(span, error);
648
1693
  span.end();
649
1694
  throw error;
650
1695
  }
@@ -654,6 +1699,7 @@ var Tracer = class {
654
1699
  return result;
655
1700
  } catch (error) {
656
1701
  span.recordException(error instanceof Error ? error : String(error));
1702
+ attachErrorCode(span, error);
657
1703
  span.end();
658
1704
  throw error;
659
1705
  }
@@ -674,8 +1720,11 @@ var Tracer = class {
674
1720
  const agent2 = getCurrentAgent();
675
1721
  const phase = getCurrentPhase();
676
1722
  const traceId = opts.traceId ?? parentSpan?.traceId ?? generateTraceId();
677
- if (!parentSpan && this._sampleRate < 1) {
678
- if (!shouldSample(traceId, this._sampleRate)) {
1723
+ if (!parentSpan) {
1724
+ if (getContext()._traceSampled === false) {
1725
+ return NOOP_SPAN;
1726
+ }
1727
+ if (this._sampleRate < 1 && !shouldSample(traceId, this._sampleRate)) {
679
1728
  return NOOP_SPAN;
680
1729
  }
681
1730
  }
@@ -691,7 +1740,10 @@ var Tracer = class {
691
1740
  // Propagate context fields as attributes (matching Python SDK tracer.py:497-511)
692
1741
  ...agent2?.agentRole ? { "agent.role": agent2.agentRole } : {},
693
1742
  ...agent2?.parentAgentId ? { "parent_agent_id": agent2.parentAgentId } : {},
694
- ...session2?.userId ? { "session.user_id": session2.userId } : {}
1743
+ ...session2?.userId ? { "session.user_id": session2.userId } : {},
1744
+ // F-SDKJSSVCNAME-001 — see the sibling site above.
1745
+ ...this._serviceName && !agent2 ? { "service.name": this._serviceName } : {},
1746
+ ...this._serviceVersion ? { "service.version": this._serviceVersion } : {}
695
1747
  },
696
1748
  sessionId: session2?.sessionId,
697
1749
  agentId: agent2?.agentId,
@@ -704,182 +1756,14 @@ var Tracer = class {
704
1756
  }
705
1757
  };
706
1758
 
707
- // src/utils/log.ts
708
- function setDebug(enabled) {
709
- setDebugFlag(enabled);
710
- }
711
- function debug(msg) {
712
- if (getDebug()) {
713
- process.stderr.write(`[risicare] ${msg}
714
- `);
715
- }
716
- }
717
- function warn(msg) {
718
- process.stderr.write(`[risicare] WARNING: ${msg}
719
- `);
720
- }
721
-
722
- // src/exporters/batch.ts
723
- var BatchSpanProcessor = class _BatchSpanProcessor {
724
- _exporters;
725
- _batchSize;
726
- _batchTimeoutMs;
727
- _maxQueueSize;
728
- _debug;
729
- _queue = [];
730
- _timer = null;
731
- _started = false;
732
- _flushing = false;
733
- _beforeExitHandler = null;
734
- // Retry tracking for failed batches (Audit #5)
735
- _retryCounts = /* @__PURE__ */ new Map();
736
- static MAX_RETRIES = 3;
737
- // Metrics
738
- droppedSpans = 0;
739
- exportedSpans = 0;
740
- failedExports = 0;
741
- constructor(options) {
742
- this._exporters = [...options.exporters];
743
- const requestedBatchSize = options.batchSize ?? 100;
744
- const clampedBatchSize = Math.max(1, Math.min(requestedBatchSize, 1e4));
745
- if (clampedBatchSize !== requestedBatchSize) {
746
- warn(
747
- `batchSize=${requestedBatchSize} is outside the allowed range [1, 10000]; clamping to ${clampedBatchSize}`
748
- );
749
- }
750
- this._batchSize = clampedBatchSize;
751
- this._batchTimeoutMs = options.batchTimeoutMs ?? 1e3;
752
- this._maxQueueSize = options.maxQueueSize ?? 1e4;
753
- this._debug = options.debug ?? false;
754
- }
755
- start() {
756
- if (this._started) return;
757
- this._started = true;
758
- this._timer = setInterval(() => {
759
- void this._exportBatch();
760
- }, this._batchTimeoutMs);
761
- this._timer.unref();
762
- this._beforeExitHandler = () => {
763
- void this.shutdown();
764
- };
765
- process.once("beforeExit", this._beforeExitHandler);
766
- }
767
- async shutdown(timeoutMs = 5e3) {
768
- if (!this._started) return;
769
- this._started = false;
770
- if (this._timer) {
771
- clearInterval(this._timer);
772
- this._timer = null;
773
- }
774
- if (this._beforeExitHandler) {
775
- process.removeListener("beforeExit", this._beforeExitHandler);
776
- this._beforeExitHandler = null;
777
- }
778
- const flushPromise = this._exportBatch();
779
- const timeoutPromise = new Promise((resolve) => setTimeout(resolve, timeoutMs));
780
- await Promise.race([flushPromise, timeoutPromise]);
781
- for (const exporter of this._exporters) {
782
- try {
783
- await exporter.shutdown();
784
- } catch (e) {
785
- debug(`Error shutting down ${exporter.name}: ${e}`);
786
- }
787
- }
788
- this._retryCounts.clear();
789
- debug(
790
- `BatchSpanProcessor shutdown. Exported: ${this.exportedSpans}, Dropped: ${this.droppedSpans}, Failed: ${this.failedExports}`
791
- );
792
- }
793
- onSpanEnd(span) {
794
- if (!this._started) return;
795
- if (this._queue.length >= this._maxQueueSize) {
796
- this.droppedSpans++;
797
- if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
798
- warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
799
- }
800
- return;
801
- }
802
- this._queue.push(span);
803
- if (this._queue.length >= this._batchSize) {
804
- void this._exportBatch();
805
- }
806
- }
807
- async flush(timeoutMs = 5e3) {
808
- if (!this._started) return true;
809
- const start = Date.now();
810
- while (this._queue.length > 0 || this._flushing) {
811
- if (!this._flushing && this._queue.length > 0) {
812
- await this._exportBatch();
813
- } else {
814
- await new Promise((r) => setTimeout(r, 1));
815
- }
816
- if (Date.now() - start > timeoutMs) return false;
817
- }
818
- return true;
819
- }
820
- getMetrics() {
821
- return {
822
- exportedSpans: this.exportedSpans,
823
- droppedSpans: this.droppedSpans,
824
- failedExports: this.failedExports,
825
- queueSize: this._queue.length,
826
- queueCapacity: this._maxQueueSize,
827
- queueUtilization: this._queue.length / this._maxQueueSize
828
- };
829
- }
830
- async _exportBatch() {
831
- if (this._flushing || this._queue.length === 0) return;
832
- this._flushing = true;
833
- try {
834
- const batch = this._queue.splice(0, this._batchSize);
835
- if (batch.length === 0) return;
836
- debug(`Exporting batch of ${batch.length} spans`);
837
- let batchExported = false;
838
- for (const exporter of this._exporters) {
839
- try {
840
- const result = await exporter.export(batch);
841
- if (result === "success" /* SUCCESS */) {
842
- if (!batchExported) {
843
- this.exportedSpans += batch.length;
844
- batchExported = true;
845
- for (const span of batch) {
846
- this._retryCounts.delete(span.spanId);
847
- }
848
- }
849
- } else {
850
- this.failedExports++;
851
- }
852
- } catch (e) {
853
- this.failedExports++;
854
- debug(`Export to ${exporter.name} failed: ${e}`);
855
- }
856
- }
857
- if (!batchExported) {
858
- const retryable = batch.filter((span) => {
859
- const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;
860
- if (count > _BatchSpanProcessor.MAX_RETRIES) {
861
- this._retryCounts.delete(span.spanId);
862
- this.droppedSpans++;
863
- return false;
864
- }
865
- this._retryCounts.set(span.spanId, count);
866
- return true;
867
- });
868
- if (retryable.length > 0) {
869
- this._queue.unshift(...retryable);
870
- debug(`Re-queued ${retryable.length} spans for retry (${batch.length - retryable.length} dropped after max retries)`);
871
- }
872
- }
873
- } finally {
874
- this._flushing = false;
875
- }
876
- }
877
- };
878
-
879
1759
  // src/version.ts
880
- var SDK_VERSION = "0.4.2";
1760
+ var SDK_VERSION = "0.5.2";
881
1761
 
882
1762
  // src/exporters/http.ts
1763
+ var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
1764
+ var RETRY_AFTER_CEILING_MS = 1e4;
1765
+ var REFUSAL_BACKOFF_BASE_MS = 1e3;
1766
+ var REFUSAL_NO_HINT = -1;
883
1767
  var HttpExporter = class {
884
1768
  name = "http";
885
1769
  _endpoint;
@@ -895,6 +1779,18 @@ var HttpExporter = class {
895
1779
  // cooldown gives the gateway time to come back before the half-open
896
1780
  // probe fires. Lower numbers (was 3@30s) tripped on transient blips.
897
1781
  _consecutiveFailures = 0;
1782
+ /**
1783
+ * F-SDK503-001. Set by `_sendRequest` when a response is a CAPACITY REFUSAL, read by the
1784
+ * retry loop and the breaker. `null` = not a refusal; `REFUSAL_NO_HINT` = refused with no
1785
+ * `Retry-After`; otherwise the honoured delay in ms.
1786
+ *
1787
+ * ⚠ Node has ONE thread and `export()` is `async`, so two concurrent exports interleave on
1788
+ * this field at every `await`. It is written immediately after the awaited `fetch` resolves
1789
+ * and read on the very next statement, with no `await` between — so the value cannot be
1790
+ * clobbered mid-decision. The Python twin carries the same per-call state on `self` for the
1791
+ * same reason (its `_send_request` signature is pin-locked).
1792
+ */
1793
+ _lastRefusalAfterMs = null;
898
1794
  _circuitOpenUntil = 0;
899
1795
  _circuitBreakerThreshold = 5;
900
1796
  _circuitBreakerCooldownMs = 6e4;
@@ -924,15 +1820,26 @@ var HttpExporter = class {
924
1820
  if (this._environment) body.environment = this._environment;
925
1821
  const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
926
1822
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1823
+ this._lastRefusalAfterMs = null;
927
1824
  const result = await this._sendRequest(body);
928
1825
  if (result === "success" /* SUCCESS */) {
929
1826
  this._consecutiveFailures = 0;
930
1827
  return result;
931
1828
  }
932
1829
  if (attempt < maxAttempts - 1) {
933
- await sleep(100 * Math.pow(2, attempt));
1830
+ const refusal = this._lastRefusalAfterMs;
1831
+ const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
1832
+ await sleep(delay);
934
1833
  }
935
1834
  }
1835
+ const refusedForCapacity = this._lastRefusalAfterMs !== null;
1836
+ this._lastRefusalAfterMs = null;
1837
+ if (refusedForCapacity) {
1838
+ warn(
1839
+ `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.`
1840
+ );
1841
+ return "failure" /* FAILURE */;
1842
+ }
936
1843
  this._consecutiveFailures++;
937
1844
  if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
938
1845
  this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
@@ -942,6 +1849,26 @@ var HttpExporter = class {
942
1849
  }
943
1850
  return "failure" /* FAILURE */;
944
1851
  }
1852
+ /**
1853
+ * Record a CAPACITY REFUSAL for the retry loop. Returns true if it was one.
1854
+ *
1855
+ * `Retry-After` is honoured only in its delta-seconds form (RFC 9110 §10.2.3 also permits an
1856
+ * HTTP-date); anything else falls back to our own backoff rather than guessing at a date
1857
+ * parse.
1858
+ */
1859
+ _noteRefusal(status, retryAfterRaw) {
1860
+ if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
1861
+ let delay = REFUSAL_NO_HINT;
1862
+ if (retryAfterRaw) {
1863
+ const secs = Number(retryAfterRaw);
1864
+ if (Number.isFinite(secs) && secs >= 0) {
1865
+ delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
1866
+ }
1867
+ }
1868
+ this._lastRefusalAfterMs = delay;
1869
+ debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${retryAfterRaw})`);
1870
+ return true;
1871
+ }
945
1872
  async _sendRequest(body) {
946
1873
  const url = `${this._endpoint}/v1/spans`;
947
1874
  const headers = {
@@ -972,11 +1899,12 @@ var HttpExporter = class {
972
1899
  });
973
1900
  clearTimeout(timeoutId);
974
1901
  if (response.status < 300) {
975
- return "success" /* SUCCESS */;
1902
+ return await checkAck(response);
976
1903
  } else if (response.status === 408 || response.status === 504) {
977
1904
  debug(`HTTP export timeout: ${response.status}`);
978
1905
  return "timeout" /* TIMEOUT */;
979
1906
  }
1907
+ this._noteRefusal(response.status, response.headers.get("Retry-After"));
980
1908
  debug(`HTTP export failed: ${response.status}`);
981
1909
  return "failure" /* FAILURE */;
982
1910
  } catch (e) {
@@ -986,9 +1914,42 @@ var HttpExporter = class {
986
1914
  }
987
1915
  shutdown() {
988
1916
  }
989
- };
990
- function sleep(ms) {
991
- return new Promise((resolve) => setTimeout(resolve, ms));
1917
+ };
1918
+ function sleep(ms) {
1919
+ return new Promise((resolve) => setTimeout(resolve, ms));
1920
+ }
1921
+ function asCount(v) {
1922
+ return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
1923
+ }
1924
+ async function checkAck(response) {
1925
+ let payload;
1926
+ try {
1927
+ payload = await response.json();
1928
+ } catch {
1929
+ return "success" /* SUCCESS */;
1930
+ }
1931
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
1932
+ return "success" /* SUCCESS */;
1933
+ }
1934
+ const body = payload;
1935
+ const accepted = asCount(body.accepted);
1936
+ const rejected = asCount(body.rejected);
1937
+ if (accepted === void 0 || rejected === void 0 || rejected <= 0) {
1938
+ return "success" /* SUCCESS */;
1939
+ }
1940
+ const errors = body.errors;
1941
+ 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.";
1942
+ const total = accepted + rejected;
1943
+ if (accepted === 0) {
1944
+ warn(
1945
+ `Risicare: the backend accepted 0 of ${total} span(s) and rejected ${rejected} \u2014 this batch was NOT stored. ${detail}`
1946
+ );
1947
+ return "failure" /* FAILURE */;
1948
+ }
1949
+ warn(
1950
+ `Risicare: the backend rejected ${rejected} of ${total} span(s); the remaining ${accepted} were stored. Those ${rejected} are permanently lost and are NOT retried. ${detail}`
1951
+ );
1952
+ return "success" /* SUCCESS */;
992
1953
  }
993
1954
 
994
1955
  // src/exporters/console.ts
@@ -1007,51 +1968,6 @@ var ConsoleExporter = class {
1007
1968
  }
1008
1969
  };
1009
1970
 
1010
- // src/runtime/config.ts
1011
- function resolveFixRuntimeConfig(config) {
1012
- return {
1013
- apiEndpoint: config.apiEndpoint,
1014
- apiKey: config.apiKey,
1015
- enabled: config.enabled ?? true,
1016
- cacheEnabled: config.cacheEnabled ?? true,
1017
- cacheTtlMs: config.cacheTtlMs ?? 3e5,
1018
- cacheMaxEntries: config.cacheMaxEntries ?? 1e3,
1019
- autoRefresh: config.autoRefresh ?? true,
1020
- refreshIntervalMs: config.refreshIntervalMs ?? 6e4,
1021
- dryRun: config.dryRun ?? false,
1022
- abTestingEnabled: config.abTestingEnabled ?? true,
1023
- timeoutMs: config.timeoutMs ?? 1e3,
1024
- debug: config.debug ?? false
1025
- };
1026
- }
1027
- function matchesError(fix, errorCode) {
1028
- if (fix.errorCode === errorCode) {
1029
- return true;
1030
- }
1031
- if (fix.errorCode.endsWith("*")) {
1032
- const prefix = fix.errorCode.slice(0, -1);
1033
- return errorCode.startsWith(prefix);
1034
- }
1035
- return false;
1036
- }
1037
- function shouldApply(fix, sessionHash) {
1038
- if (fix.trafficPercentage >= 100) return true;
1039
- if (fix.trafficPercentage <= 0) return false;
1040
- const bucket = sessionHash % 100;
1041
- return bucket < fix.trafficPercentage;
1042
- }
1043
- function activeFixFromApiResponse(item) {
1044
- return {
1045
- fixId: item.id ?? item.fix_id ?? item.fixId ?? "",
1046
- deploymentId: item.deployment_id ?? item.deploymentId ?? "",
1047
- errorCode: item.error_code ?? item.errorCode ?? "",
1048
- fixType: item.fix_type ?? item.fixType ?? "prompt",
1049
- config: item.config ?? {},
1050
- trafficPercentage: item.traffic_percentage ?? item.trafficPercentage ?? 100,
1051
- version: item.version ?? 1
1052
- };
1053
- }
1054
-
1055
1971
  // src/runtime/cache.ts
1056
1972
  var FixCache = class {
1057
1973
  _ttlMs;
@@ -1540,521 +2456,280 @@ var FixApplier = class {
1540
2456
  return {
1541
2457
  content,
1542
2458
  passed: false,
1543
- result: {
1544
- applied: true,
1545
- fixId: fix.fixId,
1546
- fixType: "guard",
1547
- modifications: { passed: false, reason: "guard_exception" },
1548
- error: String(e),
1549
- reason: "guard_exception"
1550
- }
1551
- };
1552
- }
1553
- }
1554
- // ═══════════════════════════════════════════════════════════════════════════
1555
- // Application Log
1556
- // ═══════════════════════════════════════════════════════════════════════════
1557
- /** Log a fix application result. */
1558
- logApplication(result) {
1559
- this._applicationLog.push(result);
1560
- if (this._applicationLog.length > 1e3) {
1561
- this._applicationLog = this._applicationLog.slice(-500);
1562
- }
1563
- }
1564
- /** Get the application log. */
1565
- getApplicationLog() {
1566
- return [...this._applicationLog];
1567
- }
1568
- // ═══════════════════════════════════════════════════════════════════════════
1569
- // Private Helpers
1570
- // ═══════════════════════════════════════════════════════════════════════════
1571
- /**
1572
- * Safely compile a regex pattern from untrusted input.
1573
- * Returns null if invalid or too long.
1574
- */
1575
- _safeCompileRegex(pattern, maxLength = 500) {
1576
- if (!pattern || pattern.length > maxLength) return null;
1577
- try {
1578
- return new RegExp(pattern, "i");
1579
- } catch {
1580
- debug(`Invalid regex pattern (length=${pattern.length})`);
1581
- return null;
1582
- }
1583
- }
1584
- /** Prepend content to the first message matching the target role. */
1585
- _prependToTarget(messages, target, content) {
1586
- return messages.map((msg) => {
1587
- if (msg.role === target) {
1588
- return {
1589
- ...msg,
1590
- content: content + "\n\n" + (msg.content ?? "")
1591
- };
1592
- }
1593
- return msg;
1594
- });
1595
- }
1596
- /** Append content to the first message matching the target role. */
1597
- _appendToTarget(messages, target, content) {
1598
- return messages.map((msg) => {
1599
- if (msg.role === target) {
1600
- return {
1601
- ...msg,
1602
- content: (msg.content ?? "") + "\n\n" + content
1603
- };
1604
- }
1605
- return msg;
1606
- });
1607
- }
1608
- /** Regex replace across all messages. */
1609
- _replaceInMessages(messages, pattern, replacement) {
1610
- const regex = this._safeCompileRegex(pattern);
1611
- if (!regex) {
1612
- debug("Skipping invalid regex pattern in prompt fix");
1613
- return messages;
1614
- }
1615
- return messages.map((msg) => {
1616
- const msgContent = msg.content;
1617
- if (typeof msgContent === "string") {
1618
- return { ...msg, content: msgContent.replace(regex, replacement) };
1619
- }
1620
- return msg;
1621
- });
1622
- }
1623
- /** Add few-shot examples after the first system message. */
1624
- _addFewShotExamples(messages, examples) {
1625
- const result = [];
1626
- let systemFound = false;
1627
- for (const msg of messages) {
1628
- result.push(msg);
1629
- if (msg.role === "system" && !systemFound) {
1630
- systemFound = true;
1631
- for (const example of examples) {
1632
- if (example.user) {
1633
- result.push({ role: "user", content: example.user });
1634
- }
1635
- if (example.assistant) {
1636
- result.push({ role: "assistant", content: example.assistant });
1637
- }
1638
- }
1639
- }
1640
- }
1641
- return result;
1642
- }
1643
- };
1644
-
1645
- // src/runtime/loader.ts
1646
- var FixLoader = class _FixLoader {
1647
- _config;
1648
- _cache;
1649
- _refreshTimer = null;
1650
- _lastLoadTime = null;
1651
- _consecutiveFailures = 0;
1652
- _circuitOpenUntil = 0;
1653
- _onLoadCallbacks = [];
1654
- // Circuit breaker settings
1655
- static CIRCUIT_BREAKER_THRESHOLD = 3;
1656
- static CIRCUIT_BREAKER_COOLDOWN_MS = 3e4;
1657
- constructor(config, cache) {
1658
- this._config = resolveFixRuntimeConfig(config);
1659
- this._cache = cache;
1660
- }
1661
- /** Timestamp of last successful load. */
1662
- get lastLoadTime() {
1663
- return this._lastLoadTime;
1664
- }
1665
- /**
1666
- * Start the loader: perform initial load and start background refresh.
1667
- *
1668
- * Never throws — failures are logged and the runtime degrades gracefully.
1669
- */
1670
- start() {
1671
- try {
1672
- if (!this._config.enabled) {
1673
- debug("Fix runtime disabled, skipping loader start");
1674
- return;
1675
- }
1676
- if (!this._config.apiKey) {
1677
- warn("No API key configured, fixes will not be loaded");
1678
- return;
1679
- }
1680
- this.loadSync().catch((e) => {
1681
- debug(`Initial fix load failed: ${e}`);
1682
- });
1683
- if (this._config.autoRefresh) {
1684
- this._startRefreshInterval();
1685
- }
1686
- } catch (e) {
1687
- debug(`FixLoader.start error: ${e}`);
1688
- }
1689
- }
1690
- /** Stop the loader: clear the refresh interval. */
1691
- stop() {
1692
- try {
1693
- if (this._refreshTimer !== null) {
1694
- clearInterval(this._refreshTimer);
1695
- this._refreshTimer = null;
1696
- }
1697
- } catch (e) {
1698
- debug(`FixLoader.stop error: ${e}`);
1699
- }
1700
- }
1701
- /**
1702
- * Register a callback invoked after each successful load.
1703
- */
1704
- onLoad(callback) {
1705
- this._onLoadCallbacks.push(callback);
1706
- }
1707
- /**
1708
- * Load fixes from the API.
1709
- *
1710
- * Name kept as "loadSync" for parity with the Python SDK, but this
1711
- * returns a Promise in JS (there's no synchronous fetch in Node.js).
1712
- */
1713
- async loadSync() {
1714
- if (!this._config.apiKey) {
1715
- return [];
1716
- }
1717
- const now = Date.now();
1718
- if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && now < this._circuitOpenUntil) {
1719
- debug("Fix loader circuit breaker open \u2014 skipping load");
1720
- return this._cache.getAll();
1721
- }
1722
- try {
1723
- const endpoint = this._config.apiEndpoint.replace(/\/+$/, "");
1724
- const url = `${endpoint}/api/v1/fixes/active`;
1725
- const controller = new AbortController();
1726
- const timeoutId = setTimeout(
1727
- () => controller.abort(),
1728
- this._config.timeoutMs
1729
- );
1730
- const response = await fetch(url, {
1731
- method: "GET",
1732
- headers: {
1733
- "Authorization": `Bearer ${this._config.apiKey}`,
1734
- "Content-Type": "application/json",
1735
- "X-Risicare-SDK-Version": SDK_VERSION
1736
- },
1737
- signal: controller.signal
1738
- });
1739
- clearTimeout(timeoutId);
1740
- if (!response.ok) {
1741
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1742
- }
1743
- const data = await response.json();
1744
- const fixes = this._parseResponse(data);
1745
- this._onLoadSuccess(fixes);
1746
- return fixes;
1747
- } catch (e) {
1748
- this._onLoadFailure(e);
1749
- throw e;
2459
+ result: {
2460
+ applied: true,
2461
+ fixId: fix.fixId,
2462
+ fixType: "guard",
2463
+ modifications: { passed: false, reason: "guard_exception" },
2464
+ error: String(e),
2465
+ reason: "guard_exception"
2466
+ }
2467
+ };
1750
2468
  }
1751
2469
  }
1752
- /** Get currently cached fixes without hitting the API. */
1753
- getCached() {
1754
- return this._cache.getAll();
2470
+ // ═══════════════════════════════════════════════════════════════════════════
2471
+ // Application Log
2472
+ // ═══════════════════════════════════════════════════════════════════════════
2473
+ /** Log a fix application result. */
2474
+ logApplication(result) {
2475
+ this._applicationLog.push(result);
2476
+ if (this._applicationLog.length > 1e3) {
2477
+ this._applicationLog = this._applicationLog.slice(-500);
2478
+ }
1755
2479
  }
1756
- // ─── Private ────────────────────────────────────────────────────────────
1757
- _parseResponse(data) {
1758
- const fixes = [];
1759
- const items = data.fixes ?? data.data ?? [];
1760
- if (!Array.isArray(items)) return fixes;
1761
- for (const item of items) {
1762
- try {
1763
- if (item && typeof item === "object") {
1764
- fixes.push(activeFixFromApiResponse(item));
1765
- }
1766
- } catch (e) {
1767
- debug(`Failed to parse fix item: ${e}`);
1768
- }
2480
+ /** Get the application log. */
2481
+ getApplicationLog() {
2482
+ return [...this._applicationLog];
2483
+ }
2484
+ // ═══════════════════════════════════════════════════════════════════════════
2485
+ // Private Helpers
2486
+ // ═══════════════════════════════════════════════════════════════════════════
2487
+ /**
2488
+ * Safely compile a regex pattern from untrusted input.
2489
+ * Returns null if invalid or too long.
2490
+ */
2491
+ _safeCompileRegex(pattern, maxLength = 500) {
2492
+ if (!pattern || pattern.length > maxLength) return null;
2493
+ try {
2494
+ return new RegExp(pattern, "i");
2495
+ } catch {
2496
+ debug(`Invalid regex pattern (length=${pattern.length})`);
2497
+ return null;
1769
2498
  }
1770
- return fixes;
1771
2499
  }
1772
- _onLoadSuccess(fixes) {
1773
- this._lastLoadTime = Date.now();
1774
- this._consecutiveFailures = 0;
1775
- this._cache.setAll(fixes);
1776
- for (const callback of this._onLoadCallbacks) {
1777
- try {
1778
- callback(fixes);
1779
- } catch (e) {
1780
- debug(`Load callback error: ${e}`);
2500
+ /** Prepend content to the first message matching the target role. */
2501
+ _prependToTarget(messages, target, content) {
2502
+ return messages.map((msg) => {
2503
+ if (msg.role === target) {
2504
+ return {
2505
+ ...msg,
2506
+ content: content + "\n\n" + (msg.content ?? "")
2507
+ };
1781
2508
  }
1782
- }
1783
- debug(`Loaded ${fixes.length} active fixes`);
2509
+ return msg;
2510
+ });
1784
2511
  }
1785
- _onLoadFailure(error) {
1786
- this._consecutiveFailures++;
1787
- if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD) {
1788
- this._circuitOpenUntil = Date.now() + _FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS;
1789
- warn(
1790
- `Fix loader circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${_FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS / 1e3}s`
1791
- );
1792
- } else {
1793
- debug(
1794
- `Fix load failed (attempt ${this._consecutiveFailures}): ${error.message}`
1795
- );
2512
+ /** Append content to the first message matching the target role. */
2513
+ _appendToTarget(messages, target, content) {
2514
+ return messages.map((msg) => {
2515
+ if (msg.role === target) {
2516
+ return {
2517
+ ...msg,
2518
+ content: (msg.content ?? "") + "\n\n" + content
2519
+ };
2520
+ }
2521
+ return msg;
2522
+ });
2523
+ }
2524
+ /** Regex replace across all messages. */
2525
+ _replaceInMessages(messages, pattern, replacement) {
2526
+ const regex = this._safeCompileRegex(pattern);
2527
+ if (!regex) {
2528
+ debug("Skipping invalid regex pattern in prompt fix");
2529
+ return messages;
1796
2530
  }
2531
+ return messages.map((msg) => {
2532
+ const msgContent = msg.content;
2533
+ if (typeof msgContent === "string") {
2534
+ return { ...msg, content: msgContent.replace(regex, replacement) };
2535
+ }
2536
+ return msg;
2537
+ });
1797
2538
  }
1798
- _startRefreshInterval() {
1799
- const tick = () => {
1800
- this.loadSync().catch((e) => {
1801
- debug(`Background fix refresh failed: ${e}`);
1802
- });
1803
- };
1804
- this._refreshTimer = setInterval(
1805
- () => {
1806
- if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && Date.now() < this._circuitOpenUntil) {
1807
- return;
2539
+ /** Add few-shot examples after the first system message. */
2540
+ _addFewShotExamples(messages, examples) {
2541
+ const result = [];
2542
+ let systemFound = false;
2543
+ for (const msg of messages) {
2544
+ result.push(msg);
2545
+ if (msg.role === "system" && !systemFound) {
2546
+ systemFound = true;
2547
+ for (const example of examples) {
2548
+ if (example.user) {
2549
+ result.push({ role: "user", content: example.user });
2550
+ }
2551
+ if (example.assistant) {
2552
+ result.push({ role: "assistant", content: example.assistant });
2553
+ }
1808
2554
  }
1809
- tick();
1810
- },
1811
- this._config.refreshIntervalMs
1812
- );
1813
- this._refreshTimer.unref();
1814
- debug("Started fix refresh interval");
2555
+ }
2556
+ }
2557
+ return result;
1815
2558
  }
1816
2559
  };
1817
2560
 
1818
- // src/runtime/interceptors.ts
1819
- var GuardRejectedError = class extends Error {
1820
- guardId;
1821
- reason;
1822
- phase;
1823
- constructor(guardId, reason, phase) {
1824
- super(`Risicare guard rejected operation: ${guardId} (${phase}) \u2014 ${reason}`);
1825
- this.name = "GuardRejectedError";
1826
- this.guardId = guardId;
1827
- this.reason = reason;
1828
- this.phase = phase;
1829
- }
1830
- };
1831
- function createInterceptContext(operationType, operationName, options) {
1832
- return {
1833
- operationType,
1834
- operationName,
1835
- sessionId: options?.sessionId,
1836
- traceId: options?.traceId,
1837
- errorCode: options?.errorCode,
1838
- attempt: 1,
1839
- appliedFixes: []
1840
- };
1841
- }
1842
- var DefaultFixInterceptor = class {
2561
+ // src/runtime/loader.ts
2562
+ var FixLoader = class _FixLoader {
1843
2563
  _config;
1844
2564
  _cache;
1845
- _applier;
1846
- constructor(config, cache, applier) {
2565
+ _refreshTimer = null;
2566
+ _lastLoadTime = null;
2567
+ _consecutiveFailures = 0;
2568
+ _circuitOpenUntil = 0;
2569
+ _onLoadCallbacks = [];
2570
+ // Circuit breaker settings
2571
+ static CIRCUIT_BREAKER_THRESHOLD = 3;
2572
+ static CIRCUIT_BREAKER_COOLDOWN_MS = 3e4;
2573
+ constructor(config, cache) {
1847
2574
  this._config = resolveFixRuntimeConfig(config);
1848
2575
  this._cache = cache;
1849
- this._applier = applier;
1850
2576
  }
1851
- /**
1852
- * Apply pre-call fixes.
1853
- *
1854
- * - If retrying after error: look up fix by error_code, apply
1855
- * prompt/parameter/fallback fixes
1856
- * - Runs input guard fixes on all message content
1857
- */
1858
- preCall(ctx, messages, params) {
1859
- try {
1860
- if (!this._config.enabled) {
1861
- return { messages, params };
1862
- }
1863
- let modifiedMessages = messages;
1864
- let modifiedParams = { ...params };
1865
- if (ctx.errorCode) {
1866
- const fix = this._applier.getFixForError(ctx.errorCode, ctx.sessionId);
1867
- if (fix) {
1868
- debug(`Applying fix ${fix.fixId} for ${ctx.errorCode}`);
1869
- if (fix.fixType === "prompt" && messages) {
1870
- const msgRecords = messages;
1871
- const { messages: newMessages, result } = this._applier.applyPromptFix(fix, msgRecords);
1872
- modifiedMessages = newMessages;
1873
- ctx.appliedFixes.push(result);
1874
- this._applier.logApplication(result);
1875
- } else if (fix.fixType === "parameter") {
1876
- const { params: newParams, result } = this._applier.applyParameterFix(fix, modifiedParams);
1877
- modifiedParams = newParams;
1878
- ctx.appliedFixes.push(result);
1879
- this._applier.logApplication(result);
1880
- } else if (fix.fixType === "fallback") {
1881
- const { params: newParams, result } = this._applier.applyFallbackFix(fix, modifiedParams);
1882
- modifiedParams = newParams;
1883
- ctx.appliedFixes.push(result);
1884
- this._applier.logApplication(result);
1885
- }
1886
- }
1887
- }
1888
- if (modifiedMessages && this._config.enabled) {
1889
- for (const msg of modifiedMessages) {
1890
- const content = msg.content;
1891
- if (typeof content === "string") {
1892
- for (const fix of this._cache.getAll()) {
1893
- if (fix.fixType === "guard") {
1894
- const { passed, result } = this._applier.applyGuardFix(
1895
- fix,
1896
- content,
1897
- true
1898
- );
1899
- if (result.applied) {
1900
- ctx.appliedFixes.push(result);
1901
- this._applier.logApplication(result);
1902
- }
1903
- if (!passed) {
1904
- throw new GuardRejectedError(
1905
- fix.fixId ?? "unknown",
1906
- result.reason ?? "guard rejected input",
1907
- "pre_call"
1908
- );
1909
- }
1910
- }
1911
- }
1912
- }
1913
- }
1914
- }
1915
- return { messages: modifiedMessages, params: modifiedParams };
1916
- } catch (e) {
1917
- if (e instanceof GuardRejectedError) throw e;
1918
- debug(`DefaultFixInterceptor.preCall error: ${e}`);
1919
- return { messages, params };
1920
- }
2577
+ /** Timestamp of last successful load. */
2578
+ get lastLoadTime() {
2579
+ return this._lastLoadTime;
1921
2580
  }
1922
2581
  /**
1923
- * Apply post-call fixes (output validation).
2582
+ * Start the loader: perform initial load and start background refresh.
1924
2583
  *
1925
- * Runs output guard fixes on response content.
2584
+ * Never throws — failures are logged and the runtime degrades gracefully.
1926
2585
  */
1927
- postCall(ctx, response) {
2586
+ start() {
1928
2587
  try {
1929
2588
  if (!this._config.enabled) {
1930
- return { response, shouldContinue: true };
2589
+ debug("Fix runtime disabled, skipping loader start");
2590
+ return;
1931
2591
  }
1932
- for (const fix of this._cache.getAll()) {
1933
- if (fix.fixType !== "guard") continue;
1934
- const content = this._extractResponseContent(response);
1935
- if (!content) continue;
1936
- const { passed, result } = this._applier.applyGuardFix(
1937
- fix,
1938
- content,
1939
- false
1940
- );
1941
- if (result.applied) {
1942
- ctx.appliedFixes.push(result);
1943
- this._applier.logApplication(result);
1944
- }
1945
- if (!passed) {
1946
- warn(`Output guard failed for fix ${fix.fixId}: ${result.reason ?? "unknown"}`);
1947
- throw new GuardRejectedError(
1948
- fix.fixId ?? "unknown",
1949
- result.reason ?? "guard rejected output",
1950
- "post_call"
1951
- );
1952
- }
2592
+ if (!this._config.apiKey) {
2593
+ warn("No API key configured, fixes will not be loaded");
2594
+ return;
2595
+ }
2596
+ this.loadSync().catch((e) => {
2597
+ debug(`Initial fix load failed: ${e}`);
2598
+ });
2599
+ if (this._config.autoRefresh) {
2600
+ this._startRefreshInterval();
1953
2601
  }
1954
- return { response, shouldContinue: true };
1955
2602
  } catch (e) {
1956
- if (e instanceof GuardRejectedError) throw e;
1957
- debug(`DefaultFixInterceptor.postCall error: ${e}`);
1958
- return { response, shouldContinue: true };
2603
+ debug(`FixLoader.start error: ${e}`);
2604
+ }
2605
+ }
2606
+ /** Stop the loader: clear the refresh interval. */
2607
+ stop() {
2608
+ try {
2609
+ if (this._refreshTimer !== null) {
2610
+ clearInterval(this._refreshTimer);
2611
+ this._refreshTimer = null;
2612
+ }
2613
+ } catch (e) {
2614
+ debug(`FixLoader.stop error: ${e}`);
1959
2615
  }
1960
2616
  }
1961
2617
  /**
1962
- * Handle errors and decide whether to retry.
2618
+ * Register a callback invoked after each successful load.
2619
+ */
2620
+ onLoad(callback) {
2621
+ this._onLoadCallbacks.push(callback);
2622
+ }
2623
+ /**
2624
+ * Load fixes from the API.
1963
2625
  *
1964
- * Classifies the error, looks up retry/fallback fixes, and returns
1965
- * whether the caller should retry.
2626
+ * Name kept as "loadSync" for parity with the Python SDK, but this
2627
+ * returns a Promise in JS (there's no synchronous fetch in Node.js).
1966
2628
  */
1967
- onError(ctx, error) {
2629
+ async loadSync() {
2630
+ if (!this._config.apiKey) {
2631
+ return [];
2632
+ }
2633
+ const now = Date.now();
2634
+ if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && now < this._circuitOpenUntil) {
2635
+ debug("Fix loader circuit breaker open \u2014 skipping load");
2636
+ return this._cache.getAll();
2637
+ }
1968
2638
  try {
1969
- if (!this._config.enabled) {
1970
- return { shouldRetry: false, modifiedParams: null };
1971
- }
1972
- const errorCode = classifyError(error);
1973
- ctx.errorCode = errorCode;
1974
- ctx.errorMessage = error.message;
1975
- const fix = this._applier.getFixForError(errorCode, ctx.sessionId);
1976
- if (!fix) {
1977
- return { shouldRetry: false, modifiedParams: null };
1978
- }
1979
- if (fix.fixType === "retry") {
1980
- const maxRetries = fix.config.max_retries ?? fix.config.maxRetries ?? 3;
1981
- if (ctx.attempt <= maxRetries) {
1982
- debug(
1983
- `Retry fix ${fix.fixId}: attempt ${ctx.attempt}/${maxRetries}`
1984
- );
1985
- const result = {
1986
- applied: true,
1987
- fixId: fix.fixId,
1988
- deploymentId: fix.deploymentId,
1989
- fixType: "retry",
1990
- modifications: { attempt: ctx.attempt }
1991
- };
1992
- ctx.appliedFixes.push(result);
1993
- this._applier.logApplication(result);
1994
- return { shouldRetry: true, modifiedParams: null };
1995
- }
1996
- }
1997
- if (fix.fixType === "fallback") {
1998
- const { params: modifiedParams, result } = this._applier.applyFallbackFix(fix, {});
1999
- if (result.applied) {
2000
- ctx.appliedFixes.push(result);
2001
- this._applier.logApplication(result);
2002
- return { shouldRetry: true, modifiedParams };
2003
- }
2639
+ const endpoint = this._config.apiEndpoint.replace(/\/+$/, "");
2640
+ const url = `${endpoint}/api/v1/fixes/active`;
2641
+ const controller = new AbortController();
2642
+ const timeoutId = setTimeout(
2643
+ () => controller.abort(),
2644
+ this._config.timeoutMs
2645
+ );
2646
+ const response = await fetch(url, {
2647
+ method: "GET",
2648
+ headers: {
2649
+ "Authorization": `Bearer ${this._config.apiKey}`,
2650
+ "Content-Type": "application/json",
2651
+ "X-Risicare-SDK-Version": SDK_VERSION
2652
+ },
2653
+ signal: controller.signal
2654
+ });
2655
+ clearTimeout(timeoutId);
2656
+ if (!response.ok) {
2657
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
2004
2658
  }
2005
- return { shouldRetry: false, modifiedParams: null };
2659
+ const data = await response.json();
2660
+ const fixes = this._parseResponse(data);
2661
+ this._onLoadSuccess(fixes);
2662
+ return fixes;
2006
2663
  } catch (e) {
2007
- debug(`DefaultFixInterceptor.onError error: ${e}`);
2008
- return { shouldRetry: false, modifiedParams: null };
2664
+ this._onLoadFailure(e);
2665
+ throw e;
2009
2666
  }
2010
2667
  }
2668
+ /** Get currently cached fixes without hitting the API. */
2669
+ getCached() {
2670
+ return this._cache.getAll();
2671
+ }
2011
2672
  // ─── Private ────────────────────────────────────────────────────────────
2012
- /** Extract text content from a response object. */
2013
- _extractResponseContent(response) {
2014
- if (typeof response === "string") return response;
2015
- if (response && typeof response === "object") {
2016
- const resp = response;
2017
- const choices = resp.choices;
2018
- if (Array.isArray(choices) && choices.length > 0) {
2019
- const first = choices[0];
2020
- const message = first?.message;
2021
- if (typeof message?.content === "string") {
2022
- return message.content;
2673
+ _parseResponse(data) {
2674
+ const fixes = [];
2675
+ const items = data.fixes ?? data.data ?? [];
2676
+ if (!Array.isArray(items)) return fixes;
2677
+ for (const item of items) {
2678
+ try {
2679
+ if (item && typeof item === "object") {
2680
+ fixes.push(activeFixFromApiResponse(item));
2023
2681
  }
2024
- }
2025
- const content = resp.content;
2026
- if (typeof content === "string") return content;
2027
- if (Array.isArray(content) && content.length > 0) {
2028
- const first = content[0];
2029
- if (typeof first?.text === "string") return first.text;
2682
+ } catch (e) {
2683
+ debug(`Failed to parse fix item: ${e}`);
2030
2684
  }
2031
2685
  }
2032
- return null;
2033
- }
2034
- };
2035
- function classifyError(error) {
2036
- const errorType = error.constructor.name.toLowerCase();
2037
- const errorMsg = error.message.toLowerCase();
2038
- if (errorType.includes("timeout") || errorMsg.includes("timeout") || errorMsg.includes("aborted")) {
2039
- return "TOOL.EXECUTION.TIMEOUT";
2040
- }
2041
- if (errorMsg.includes("rate") && errorMsg.includes("limit")) {
2042
- return "TOOL.EXECUTION.RATE_LIMIT";
2043
- }
2044
- if (errorMsg.includes("429") || errorMsg.includes("too many requests")) {
2045
- return "TOOL.EXECUTION.RATE_LIMIT";
2686
+ return fixes;
2046
2687
  }
2047
- if (errorType.includes("connection") || errorMsg.includes("connection") || errorMsg.includes("econnrefused") || errorMsg.includes("econnreset") || errorMsg.includes("fetch failed")) {
2048
- return "TOOL.EXECUTION.CONNECTION_ERROR";
2688
+ _onLoadSuccess(fixes) {
2689
+ this._lastLoadTime = Date.now();
2690
+ this._consecutiveFailures = 0;
2691
+ this._cache.setAll(fixes);
2692
+ for (const callback of this._onLoadCallbacks) {
2693
+ try {
2694
+ callback(fixes);
2695
+ } catch (e) {
2696
+ debug(`Load callback error: ${e}`);
2697
+ }
2698
+ }
2699
+ debug(`Loaded ${fixes.length} active fixes`);
2049
2700
  }
2050
- if (errorMsg.includes("auth") || errorMsg.includes("401") || errorMsg.includes("403") || errorMsg.includes("unauthorized") || errorMsg.includes("forbidden")) {
2051
- return "TOOL.EXECUTION.AUTH_ERROR";
2701
+ _onLoadFailure(error) {
2702
+ this._consecutiveFailures++;
2703
+ if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD) {
2704
+ this._circuitOpenUntil = Date.now() + _FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS;
2705
+ warn(
2706
+ `Fix loader circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${_FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS / 1e3}s`
2707
+ );
2708
+ } else {
2709
+ debug(
2710
+ `Fix load failed (attempt ${this._consecutiveFailures}): ${error.message}`
2711
+ );
2712
+ }
2052
2713
  }
2053
- if (errorType.includes("syntaxerror") || errorType.includes("json") || errorMsg.includes("json") || errorMsg.includes("unexpected token")) {
2054
- return "OUTPUT.FORMAT.JSON_INVALID";
2714
+ _startRefreshInterval() {
2715
+ const tick = () => {
2716
+ this.loadSync().catch((e) => {
2717
+ debug(`Background fix refresh failed: ${e}`);
2718
+ });
2719
+ };
2720
+ this._refreshTimer = setInterval(
2721
+ () => {
2722
+ if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && Date.now() < this._circuitOpenUntil) {
2723
+ return;
2724
+ }
2725
+ tick();
2726
+ },
2727
+ this._config.refreshIntervalMs
2728
+ );
2729
+ this._refreshTimer.unref();
2730
+ debug("Started fix refresh interval");
2055
2731
  }
2056
- return "TOOL.EXECUTION.FAILURE";
2057
- }
2732
+ };
2058
2733
 
2059
2734
  // src/runtime/runtime.ts
2060
2735
  var G2 = globalThis;
@@ -2301,10 +2976,20 @@ function shutdownFixRuntime() {
2301
2976
  }
2302
2977
 
2303
2978
  // src/client.ts
2979
+ var TERMINATING_SIGNALS = [
2980
+ ["SIGTERM", 15],
2981
+ ["SIGINT", 2]
2982
+ ];
2983
+ var BACKSTOP_MARGIN_MS = 500;
2984
+ var _finalMetrics;
2304
2985
  var RisicareClient = class {
2305
2986
  config;
2306
2987
  processor;
2307
2988
  tracer;
2989
+ /** RULING §5. The signal path does NOT clear the global client, so without
2990
+ * this flag `getMetrics()` would keep reporting `"running"` over a processor
2991
+ * that has already been torn down. */
2992
+ isShutdown = false;
2308
2993
  _shutdownPromise;
2309
2994
  _shutdownHandlers = [];
2310
2995
  constructor(config) {
@@ -2324,20 +3009,44 @@ var RisicareClient = class {
2324
3009
  compress: this.config.compress
2325
3010
  });
2326
3011
  } else {
2327
- exporter = new ConsoleExporter();
3012
+ exporter = void 0;
3013
+ if (this.config.enabled) {
3014
+ try {
3015
+ console.warn(
3016
+ `[risicare] tracing is enabled but NO API key is configured \u2014 spans are created and then DROPPED, not sent to ${this.config.endpoint}. Pass apiKey to init() (or set the RISICARE_API_KEY env var). Span data is NOT written to the console: it would be unredacted. Pass debug:true if you want console output for local development.`
3017
+ );
3018
+ } catch {
3019
+ }
3020
+ }
2328
3021
  }
2329
3022
  this.processor = new BatchSpanProcessor({
2330
- exporters: [exporter],
3023
+ exporters: exporter ? [exporter] : [],
2331
3024
  batchSize: this.config.batchSize,
2332
3025
  batchTimeoutMs: this.config.batchTimeoutMs,
2333
3026
  maxQueueSize: this.config.maxQueueSize,
2334
- debug: this.config.debug
3027
+ debug: this.config.debug,
3028
+ // The processor is the ONE choke point every exporter is behind. Masking
3029
+ // anywhere downstream (in the HTTP exporter, say) would leave a hole for
3030
+ // any other exporter; masking upstream would put customer code on the
3031
+ // span-end call path.
3032
+ mask: this.config.mask,
3033
+ // Same argument as `mask`: the processor is the ONE choke point every
3034
+ // exporter is behind, and the only place BOTH content paths — provider
3035
+ // capture and hand-set attributes — can be gated together. The Tracer
3036
+ // still carries `traceContent` for the provider patches to read; that is
3037
+ // now a convenience, not the enforcement point.
3038
+ traceContent: this.config.traceContent
2335
3039
  });
2336
3040
  this.tracer = new Tracer({
2337
3041
  onSpanEnd: (span) => this.processor.onSpanEnd(span),
2338
3042
  sampleRate: this.config.sampleRate,
2339
3043
  enabled: this.config.enabled,
2340
- traceContent: this.config.traceContent
3044
+ traceContent: this.config.traceContent,
3045
+ // F-SDKJSSVCNAME-001 — these were resolved into `config` and then read by
3046
+ // nothing. The Tracer is where Python emits them, so JS emits them there
3047
+ // too rather than inventing a second site.
3048
+ serviceName: this.config.serviceName,
3049
+ serviceVersion: this.config.serviceVersion
2341
3050
  });
2342
3051
  this.processor.start();
2343
3052
  if (this.config.apiKey && this.config.enabled) {
@@ -2385,21 +3094,82 @@ var RisicareClient = class {
2385
3094
  }
2386
3095
  this._shutdownHandlers = [];
2387
3096
  await this.processor.shutdown();
3097
+ this.isShutdown = true;
3098
+ _finalMetrics = this.processor.getMetrics();
2388
3099
  }
3100
+ /**
3101
+ * Flush pending spans.
3102
+ *
3103
+ * @returns `true` only if everything queued at entry was DELIVERED.
3104
+ *
3105
+ * RULING §6: this used to discard the processor's boolean and return
3106
+ * `Promise<void>`, which resolves without throwing and reads to a caller
3107
+ * exactly like success. A discarded answer is not meaningfully better than a
3108
+ * false one — both leave the customer unable to tell *drained* from
3109
+ * *discarded*.
3110
+ */
2389
3111
  async flush() {
2390
- await this.processor.flush();
3112
+ return this.processor.flush();
2391
3113
  }
3114
+ /**
3115
+ * SDK-RELEASE-RULING.md §3 — who decides whether the process dies.
3116
+ *
3117
+ * The contract, and it is the same one the Python SDK now satisfies:
3118
+ *
3119
+ * the SDK's signal handler never CHANGES whether the signal
3120
+ * terminates the process.
3121
+ *
3122
+ * Registering ANY listener for SIGTERM/SIGINT displaces Node's default
3123
+ * terminate. Before this, the SDK registered one unconditionally, and on the
3124
+ * success path `clearTimeout` removed the 5 s `process.exit(1)` backstop —
3125
+ * so a JS app with a live event loop drained, cleared its own only exit, and
3126
+ * **ran forever**. The orchestrator waited out the whole grace period and
3127
+ * SIGKILLed, which exits **137** and reads as OOM-killed in every dashboard.
3128
+ * Measured >25 s alive on both 0.5.0 and a clean-rebuilt 0.4.2, so this is
3129
+ * PRE-EXISTING (`F-SDKJSEXIT-001`), not a regression of the data-loss fix.
3130
+ *
3131
+ * The rule splits on one question — did the signal already have an owner?
3132
+ *
3133
+ * * **No prior listener.** Node's default was termination and OUR
3134
+ * registration displaced it. We owe the process that death.
3135
+ * * **A prior listener exists.** The application took ownership before the
3136
+ * SDK loaded. We drain and RETURN; termination was never ours to decide,
3137
+ * and forcing it would cut off the app's own graceful shutdown.
3138
+ *
3139
+ * ⚠ `beforeExit` is deliberately NOT in that logic. It is not a signal and
3140
+ * carries no termination the SDK could displace — the loop has already
3141
+ * drained and the process is leaving on its own.
3142
+ */
2392
3143
  _registerShutdownHooks() {
2393
- const onShutdown = () => {
2394
- const timeout = setTimeout(() => process.exit(1), 5e3);
2395
- timeout.unref();
3144
+ const onBeforeExit = () => {
2396
3145
  this.shutdown().catch(() => {
2397
- }).finally(() => clearTimeout(timeout));
3146
+ });
2398
3147
  };
2399
- const signals = ["beforeExit", "SIGTERM", "SIGINT"];
2400
- for (const signal of signals) {
2401
- process.once(signal, onShutdown);
2402
- this._shutdownHandlers.push({ signal, handler: onShutdown });
3148
+ process.once("beforeExit", onBeforeExit);
3149
+ this._shutdownHandlers.push({ signal: "beforeExit", handler: onBeforeExit });
3150
+ for (const [signal, signum] of TERMINATING_SIGNALS) {
3151
+ const weDisplacedDefault = process.listenerCount(signal) === 0;
3152
+ const handler = () => {
3153
+ const backstop = setTimeout(
3154
+ () => process.exit(128 + signum),
3155
+ SHUTDOWN_BUDGET_MS + BACKSTOP_MARGIN_MS
3156
+ );
3157
+ backstop.unref();
3158
+ this.shutdown().catch(() => {
3159
+ }).finally(() => {
3160
+ clearTimeout(backstop);
3161
+ if (!weDisplacedDefault) return;
3162
+ try {
3163
+ process.kill(process.pid, signal);
3164
+ } catch {
3165
+ process.exit(128 + signum);
3166
+ }
3167
+ const failsafe = setTimeout(() => process.exit(128 + signum), 100);
3168
+ failsafe.unref();
3169
+ });
3170
+ };
3171
+ process.once(signal, handler);
3172
+ this._shutdownHandlers.push({ signal, handler });
2403
3173
  }
2404
3174
  }
2405
3175
  };
@@ -2436,6 +3206,7 @@ function init(config) {
2436
3206
  }
2437
3207
  return;
2438
3208
  }
3209
+ _finalMetrics = void 0;
2439
3210
  const client = new RisicareClient(config);
2440
3211
  setClient(client);
2441
3212
  setTracer(client.tracer);
@@ -2453,8 +3224,8 @@ async function shutdown() {
2453
3224
  }
2454
3225
  async function flush() {
2455
3226
  const client = getClient();
2456
- if (!client) return;
2457
- await client.flush();
3227
+ if (!client) return true;
3228
+ return client.flush();
2458
3229
  }
2459
3230
  function enable() {
2460
3231
  const client = getClient();
@@ -2473,17 +3244,33 @@ function getTracer2() {
2473
3244
  }
2474
3245
  function getTraceContent() {
2475
3246
  const tracer = getTracer();
2476
- return tracer?.traceContent ?? true;
3247
+ return tracer?.traceContent ?? false;
2477
3248
  }
2478
3249
  function getMetrics() {
2479
3250
  const client = getClient();
2480
- return client?.processor.getMetrics() ?? {
3251
+ if (client && !client.isShutdown) {
3252
+ return { ...client.processor.getMetrics(), sdkState: "running" };
3253
+ }
3254
+ if (_finalMetrics) {
3255
+ return {
3256
+ ..._finalMetrics,
3257
+ droppedSpansByReason: { ..._finalMetrics.droppedSpansByReason },
3258
+ sdkState: "shutdown"
3259
+ };
3260
+ }
3261
+ return {
2481
3262
  exportedSpans: 0,
2482
3263
  droppedSpans: 0,
3264
+ droppedSpansByReason: {
3265
+ queue_full: 0,
3266
+ transport_refused: 0,
3267
+ shutdown_residue: 0
3268
+ },
2483
3269
  failedExports: 0,
2484
3270
  queueSize: 0,
2485
3271
  queueCapacity: 0,
2486
- queueUtilization: 0
3272
+ queueUtilization: 0,
3273
+ sdkState: "uninitialised"
2487
3274
  };
2488
3275
  }
2489
3276
  var _ERROR_DEDUP_TTL_MS = 5 * 60 * 1e3;
@@ -2491,7 +3278,6 @@ var _ERROR_DEDUP_MAX = 1e3;
2491
3278
  var _recentErrors = /* @__PURE__ */ new Map();
2492
3279
  function _errorFingerprint(err) {
2493
3280
  const raw = `${err.constructor?.name ?? "Error"}:${String(err.message ?? "").slice(0, 200)}`;
2494
- const { createHash: createHash2 } = __require("crypto");
2495
3281
  return createHash2("sha256").update(raw).digest("hex").slice(0, 16);
2496
3282
  }
2497
3283
  function _isDuplicateError(fingerprint) {
@@ -2550,13 +3336,17 @@ function score(traceId, name, value, options) {
2550
3336
  if (!client?.enabled || !client.config.apiKey) return;
2551
3337
  const endpoint = client.config.endpoint.replace(/\/$/, "");
2552
3338
  const url = `${endpoint}/api/v1/scores`;
3339
+ let comment = options?.comment;
3340
+ if (comment !== void 0 && client.config.mask) {
3341
+ comment = maskText(client.config.mask, SCORE_COMMENT_KEY, comment);
3342
+ }
2553
3343
  const body = JSON.stringify({
2554
3344
  trace_id: traceId,
2555
3345
  name,
2556
3346
  score: value,
2557
3347
  source: "sdk",
2558
3348
  ...options?.spanId && { span_id: options.spanId },
2559
- ...options?.comment && { comment: options.comment }
3349
+ ...comment && { comment }
2560
3350
  });
2561
3351
  fetch(url, {
2562
3352
  method: "POST",
@@ -2684,12 +3474,14 @@ function withSessionEndMarker(body) {
2684
3474
  // src/decorators/agent.ts
2685
3475
  function _wrapAgent(options, fn) {
2686
3476
  const spanName = `agent:${options.name ?? "agent"}`;
3477
+ const agentId = options.agentId ?? generateAgentId(options.name ?? "agent");
3478
+ const boundOptions = { ...options, agentId };
2687
3479
  return (...args) => {
2688
3480
  const tracer = getTracer2();
2689
3481
  if (!tracer) {
2690
3482
  return fn(...args);
2691
3483
  }
2692
- return withAgent(options, () => {
3484
+ return withAgent(boundOptions, () => {
2693
3485
  return tracer.startSpan(
2694
3486
  { name: spanName, kind: "agent" /* AGENT */ },
2695
3487
  (span) => withEndMarker(span, "agent", () => fn(...args))
@@ -3699,6 +4491,7 @@ export {
3699
4491
  AgentRole,
3700
4492
  DEFAULT_TIMESTAMP_TOLERANCE_S,
3701
4493
  GuardRejectedError,
4494
+ MASK_ERROR_MARKER,
3702
4495
  MessageType,
3703
4496
  RisicareCallbackHandler,
3704
4497
  RisicareLlamaIndexHandler,