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.
- package/README.md +63 -0
- package/dist/frameworks/instructor.cjs +34 -18
- package/dist/frameworks/instructor.cjs.map +1 -1
- package/dist/frameworks/instructor.js +34 -18
- package/dist/frameworks/instructor.js.map +1 -1
- package/dist/frameworks/langchain.cjs +40 -24
- package/dist/frameworks/langchain.cjs.map +1 -1
- package/dist/frameworks/langchain.js +40 -24
- package/dist/frameworks/langchain.js.map +1 -1
- package/dist/frameworks/langgraph.cjs +40 -24
- package/dist/frameworks/langgraph.cjs.map +1 -1
- package/dist/frameworks/langgraph.js +40 -24
- package/dist/frameworks/langgraph.js.map +1 -1
- package/dist/frameworks/llamaindex.cjs +29 -13
- package/dist/frameworks/llamaindex.cjs.map +1 -1
- package/dist/frameworks/llamaindex.js +29 -13
- package/dist/frameworks/llamaindex.js.map +1 -1
- package/dist/index.cjs +1555 -761
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +237 -47
- package/dist/index.d.ts +237 -47
- package/dist/index.js +1704 -911
- package/dist/index.js.map +1 -1
- package/dist/providers/anthropic/index.cjs +40 -24
- package/dist/providers/anthropic/index.cjs.map +1 -1
- package/dist/providers/anthropic/index.js +40 -24
- package/dist/providers/anthropic/index.js.map +1 -1
- package/dist/providers/bedrock/index.cjs +40 -24
- package/dist/providers/bedrock/index.cjs.map +1 -1
- package/dist/providers/bedrock/index.js +40 -24
- package/dist/providers/bedrock/index.js.map +1 -1
- package/dist/providers/cerebras/index.cjs +40 -24
- package/dist/providers/cerebras/index.cjs.map +1 -1
- package/dist/providers/cerebras/index.js +40 -24
- package/dist/providers/cerebras/index.js.map +1 -1
- package/dist/providers/cohere/index.cjs +40 -24
- package/dist/providers/cohere/index.cjs.map +1 -1
- package/dist/providers/cohere/index.js +40 -24
- package/dist/providers/cohere/index.js.map +1 -1
- package/dist/providers/google/index.cjs +40 -24
- package/dist/providers/google/index.cjs.map +1 -1
- package/dist/providers/google/index.js +40 -24
- package/dist/providers/google/index.js.map +1 -1
- package/dist/providers/groq/index.cjs +40 -24
- package/dist/providers/groq/index.cjs.map +1 -1
- package/dist/providers/groq/index.js +40 -24
- package/dist/providers/groq/index.js.map +1 -1
- package/dist/providers/huggingface/index.cjs +40 -24
- package/dist/providers/huggingface/index.cjs.map +1 -1
- package/dist/providers/huggingface/index.js +40 -24
- package/dist/providers/huggingface/index.js.map +1 -1
- package/dist/providers/mistral/index.cjs +40 -24
- package/dist/providers/mistral/index.cjs.map +1 -1
- package/dist/providers/mistral/index.js +40 -24
- package/dist/providers/mistral/index.js.map +1 -1
- package/dist/providers/ollama/index.cjs +40 -24
- package/dist/providers/ollama/index.cjs.map +1 -1
- package/dist/providers/ollama/index.js +40 -24
- package/dist/providers/ollama/index.js.map +1 -1
- package/dist/providers/openai/index.cjs +40 -24
- package/dist/providers/openai/index.cjs.map +1 -1
- package/dist/providers/openai/index.js +40 -24
- package/dist/providers/openai/index.js.map +1 -1
- package/dist/providers/together/index.cjs +40 -24
- package/dist/providers/together/index.cjs.map +1 -1
- package/dist/providers/together/index.js +40 -24
- package/dist/providers/together/index.js.map +1 -1
- package/dist/providers/vercel-ai/index.cjs +34 -18
- package/dist/providers/vercel-ai/index.cjs.map +1 -1
- package/dist/providers/vercel-ai/index.js +34 -18
- package/dist/providers/vercel-ai/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -33,6 +33,7 @@ __export(src_exports, {
|
|
|
33
33
|
AgentRole: () => AgentRole,
|
|
34
34
|
DEFAULT_TIMESTAMP_TOLERANCE_S: () => DEFAULT_TIMESTAMP_TOLERANCE_S,
|
|
35
35
|
GuardRejectedError: () => GuardRejectedError,
|
|
36
|
+
MASK_ERROR_MARKER: () => MASK_ERROR_MARKER,
|
|
36
37
|
MessageType: () => MessageType,
|
|
37
38
|
RisicareCallbackHandler: () => RisicareCallbackHandler,
|
|
38
39
|
RisicareLlamaIndexHandler: () => RisicareLlamaIndexHandler,
|
|
@@ -90,6 +91,621 @@ __export(src_exports, {
|
|
|
90
91
|
});
|
|
91
92
|
module.exports = __toCommonJS(src_exports);
|
|
92
93
|
|
|
94
|
+
// src/client.ts
|
|
95
|
+
var import_node_crypto3 = require("crypto");
|
|
96
|
+
|
|
97
|
+
// src/globals.ts
|
|
98
|
+
var import_node_async_hooks = require("async_hooks");
|
|
99
|
+
var G = globalThis;
|
|
100
|
+
var PREFIX = "__risicare_";
|
|
101
|
+
function getClient() {
|
|
102
|
+
return G[PREFIX + "client"];
|
|
103
|
+
}
|
|
104
|
+
function setClient(client) {
|
|
105
|
+
G[PREFIX + "client"] = client;
|
|
106
|
+
}
|
|
107
|
+
function getTracer() {
|
|
108
|
+
return G[PREFIX + "tracer"];
|
|
109
|
+
}
|
|
110
|
+
function setTracer(tracer) {
|
|
111
|
+
G[PREFIX + "tracer"] = tracer;
|
|
112
|
+
}
|
|
113
|
+
function getContextStorage() {
|
|
114
|
+
if (!G[PREFIX + "ctx"]) {
|
|
115
|
+
G[PREFIX + "ctx"] = new import_node_async_hooks.AsyncLocalStorage();
|
|
116
|
+
}
|
|
117
|
+
return G[PREFIX + "ctx"];
|
|
118
|
+
}
|
|
119
|
+
function getRegistry() {
|
|
120
|
+
if (!G[PREFIX + "registry"]) {
|
|
121
|
+
G[PREFIX + "registry"] = /* @__PURE__ */ new Map();
|
|
122
|
+
}
|
|
123
|
+
return G[PREFIX + "registry"];
|
|
124
|
+
}
|
|
125
|
+
function getOpCount() {
|
|
126
|
+
return G[PREFIX + "opcount"] ?? 0;
|
|
127
|
+
}
|
|
128
|
+
function setOpCount(n) {
|
|
129
|
+
G[PREFIX + "opcount"] = n;
|
|
130
|
+
}
|
|
131
|
+
function getDebug() {
|
|
132
|
+
return G[PREFIX + "debug"] ?? false;
|
|
133
|
+
}
|
|
134
|
+
function setDebugFlag(enabled) {
|
|
135
|
+
G[PREFIX + "debug"] = enabled;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// src/utils/log.ts
|
|
139
|
+
function setDebug(enabled) {
|
|
140
|
+
setDebugFlag(enabled);
|
|
141
|
+
}
|
|
142
|
+
function debug(msg) {
|
|
143
|
+
if (getDebug()) {
|
|
144
|
+
process.stderr.write(`[risicare] ${msg}
|
|
145
|
+
`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
function warn(msg) {
|
|
149
|
+
process.stderr.write(`[risicare] WARNING: ${msg}
|
|
150
|
+
`);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// src/masking.ts
|
|
154
|
+
var MASK_ERROR_MARKER = "<risicare:mask-error>";
|
|
155
|
+
var MASK_BUDGET_MS_PER_SPAN = 1;
|
|
156
|
+
var MASK_WARN_WINDOW_MS = 3e5;
|
|
157
|
+
var SCORE_COMMENT_KEY = "score.comment";
|
|
158
|
+
function maskText(mask, key, value, onError) {
|
|
159
|
+
return maskString(mask, key, value, onError);
|
|
160
|
+
}
|
|
161
|
+
function maskOne(mask, key, value, onError) {
|
|
162
|
+
try {
|
|
163
|
+
return mask(key, value);
|
|
164
|
+
} catch (e) {
|
|
165
|
+
onError?.(key, e);
|
|
166
|
+
return MASK_ERROR_MARKER;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
function maskString(mask, key, value, onError) {
|
|
170
|
+
const masked = maskOne(mask, key, value, onError);
|
|
171
|
+
if (typeof masked === "string") return masked;
|
|
172
|
+
try {
|
|
173
|
+
return String(masked);
|
|
174
|
+
} catch (e) {
|
|
175
|
+
onError?.(key, e);
|
|
176
|
+
return MASK_ERROR_MARKER;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function maskAttributes(mask, prefix, attrs, onError) {
|
|
180
|
+
for (const k of Object.keys(attrs)) {
|
|
181
|
+
attrs[k] = maskOne(mask, prefix + k, attrs[k], onError);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
function isMasked(span) {
|
|
185
|
+
return span._risicareMasked === true;
|
|
186
|
+
}
|
|
187
|
+
function markMasked(span) {
|
|
188
|
+
try {
|
|
189
|
+
span._risicareMasked = true;
|
|
190
|
+
} catch {
|
|
191
|
+
debug("Could not mark span as masked; a re-queue may re-mask it");
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function applyMask(span, mask, onError) {
|
|
195
|
+
if (isMasked(span)) return;
|
|
196
|
+
if (span.attributes && typeof span.attributes === "object") {
|
|
197
|
+
maskAttributes(mask, "", span.attributes, onError);
|
|
198
|
+
}
|
|
199
|
+
if (span.statusMessage !== void 0) {
|
|
200
|
+
span.statusMessage = maskString(mask, "statusMessage", span.statusMessage, onError);
|
|
201
|
+
}
|
|
202
|
+
if (Array.isArray(span.events)) {
|
|
203
|
+
span.events.forEach((event, i) => {
|
|
204
|
+
if (event?.attributes && typeof event.attributes === "object") {
|
|
205
|
+
maskAttributes(mask, `events.${i}.attributes.`, event.attributes, onError);
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
if (Array.isArray(span.links)) {
|
|
210
|
+
span.links.forEach((link, i) => {
|
|
211
|
+
if (link?.attributes && typeof link.attributes === "object") {
|
|
212
|
+
maskAttributes(mask, `links.${i}.attributes.`, link.attributes, onError);
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
markMasked(span);
|
|
217
|
+
}
|
|
218
|
+
var CONTENT_KEYS_EXACT = /* @__PURE__ */ new Set([
|
|
219
|
+
"gen_ai.system_prompt",
|
|
220
|
+
"gen_ai.prompt.message"
|
|
221
|
+
]);
|
|
222
|
+
var CONTENT_OMITTED_MARKER = "<risicare:content-omitted>";
|
|
223
|
+
function isContentKey(key) {
|
|
224
|
+
if (CONTENT_KEYS_EXACT.has(key)) return true;
|
|
225
|
+
const lastSegment = key.slice(key.lastIndexOf(".") + 1);
|
|
226
|
+
if (lastSegment === "content") return true;
|
|
227
|
+
return key.endsWith("_content");
|
|
228
|
+
}
|
|
229
|
+
function stripAttributes(attrs) {
|
|
230
|
+
let n = 0;
|
|
231
|
+
for (const k of Object.keys(attrs)) {
|
|
232
|
+
if (isContentKey(k)) {
|
|
233
|
+
attrs[k] = CONTENT_OMITTED_MARKER;
|
|
234
|
+
n++;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return n;
|
|
238
|
+
}
|
|
239
|
+
function stripContent(span) {
|
|
240
|
+
let stripped = 0;
|
|
241
|
+
if (span.attributes && typeof span.attributes === "object") {
|
|
242
|
+
stripped += stripAttributes(span.attributes);
|
|
243
|
+
}
|
|
244
|
+
if (Array.isArray(span.events)) {
|
|
245
|
+
for (const event of span.events) {
|
|
246
|
+
if (event?.attributes && typeof event.attributes === "object") {
|
|
247
|
+
stripped += stripAttributes(event.attributes);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (Array.isArray(span.links)) {
|
|
252
|
+
for (const link of span.links) {
|
|
253
|
+
if (link?.attributes && typeof link.attributes === "object") {
|
|
254
|
+
stripped += stripAttributes(link.attributes);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return stripped;
|
|
259
|
+
}
|
|
260
|
+
function stripContentBatch(spans) {
|
|
261
|
+
let total = 0;
|
|
262
|
+
for (const span of spans) {
|
|
263
|
+
try {
|
|
264
|
+
total += stripContent(span);
|
|
265
|
+
} catch {
|
|
266
|
+
debug("Could not strip content from a span");
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return total;
|
|
270
|
+
}
|
|
271
|
+
function applyMaskBatch(spans, mask, onError) {
|
|
272
|
+
let errors = 0;
|
|
273
|
+
let firstKey;
|
|
274
|
+
let firstError;
|
|
275
|
+
const report = (key, error) => {
|
|
276
|
+
errors++;
|
|
277
|
+
if (firstKey === void 0) {
|
|
278
|
+
firstKey = key;
|
|
279
|
+
firstError = error;
|
|
280
|
+
}
|
|
281
|
+
onError?.(key, error);
|
|
282
|
+
};
|
|
283
|
+
const started = Date.now();
|
|
284
|
+
for (const span of spans) {
|
|
285
|
+
applyMask(span, mask, report);
|
|
286
|
+
}
|
|
287
|
+
const elapsedMs = Date.now() - started;
|
|
288
|
+
if (errors > 0 && firstKey !== void 0) {
|
|
289
|
+
debug(`mask threw on ${errors} field(s); first: key=${firstKey} ${String(firstError)}`);
|
|
290
|
+
}
|
|
291
|
+
return { errors, elapsedMs };
|
|
292
|
+
}
|
|
293
|
+
function warnMaskErrors(batchErrors, totalErrors) {
|
|
294
|
+
warn(
|
|
295
|
+
`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.`
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
function warnMaskSlow(spanCount, elapsedMs) {
|
|
299
|
+
warn(
|
|
300
|
+
`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.`
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// src/exporters/batch.ts
|
|
305
|
+
var SHUTDOWN_RESERVE_MS = 100;
|
|
306
|
+
var SHUTDOWN_BUDGET_MS = 5e3;
|
|
307
|
+
var REFUSAL_WARN_WINDOW_MS = 3e5;
|
|
308
|
+
var DEFAULT_BATCH_SIZE = 500;
|
|
309
|
+
var MAX_ATTRIBUTE_PAIRS_PER_BATCH = 24e3;
|
|
310
|
+
var MAX_BATCH_BYTES = 8 * 1024 * 1024;
|
|
311
|
+
var SPAN_ENVELOPE_BYTES = 512;
|
|
312
|
+
var CHILD_ENVELOPE_BYTES = 128;
|
|
313
|
+
var SCALAR_BYTES = 24;
|
|
314
|
+
var LITERAL_BYTES = 5;
|
|
315
|
+
var EST_MAX_DEPTH = 4;
|
|
316
|
+
var EST_OPAQUE_VALUE_BYTES = 4096;
|
|
317
|
+
var utf8ByteLength = typeof Buffer !== "undefined" && typeof Buffer.byteLength === "function" ? (s) => Buffer.byteLength(s, "utf8") : (s) => s.length * 3;
|
|
318
|
+
function estStringBytes(s) {
|
|
319
|
+
return 2 + utf8ByteLength(s);
|
|
320
|
+
}
|
|
321
|
+
function estValueBytes(v, depth = 0) {
|
|
322
|
+
if (typeof v === "string") return estStringBytes(v);
|
|
323
|
+
if (v === null || v === void 0 || typeof v === "boolean") return LITERAL_BYTES;
|
|
324
|
+
if (typeof v === "number" || typeof v === "bigint") return SCALAR_BYTES;
|
|
325
|
+
if (Array.isArray(v) && depth < EST_MAX_DEPTH) {
|
|
326
|
+
let total = 2 + Math.max(0, v.length - 1);
|
|
327
|
+
for (const item of v) total += estValueBytes(item, depth + 1);
|
|
328
|
+
return total;
|
|
329
|
+
}
|
|
330
|
+
if (typeof v === "object" && depth < EST_MAX_DEPTH && Object.getPrototypeOf(v) === Object.prototype) {
|
|
331
|
+
let total = 2;
|
|
332
|
+
for (const [k, val] of Object.entries(v)) {
|
|
333
|
+
total += estStringBytes(k) + 2 + estValueBytes(val, depth + 1);
|
|
334
|
+
}
|
|
335
|
+
return total;
|
|
336
|
+
}
|
|
337
|
+
return EST_OPAQUE_VALUE_BYTES;
|
|
338
|
+
}
|
|
339
|
+
function estMappingBytes(m) {
|
|
340
|
+
let total = 0;
|
|
341
|
+
for (const [k, v] of Object.entries(m)) total += estStringBytes(k) + 2 + estValueBytes(v);
|
|
342
|
+
return total;
|
|
343
|
+
}
|
|
344
|
+
function spanBytesEstimate(span) {
|
|
345
|
+
try {
|
|
346
|
+
const s = span;
|
|
347
|
+
let total = SPAN_ENVELOPE_BYTES;
|
|
348
|
+
for (const field of ["name", "statusMessage"]) {
|
|
349
|
+
if (typeof s[field] === "string") total += estStringBytes(s[field]);
|
|
350
|
+
}
|
|
351
|
+
const attrs = s.attributes;
|
|
352
|
+
if (attrs != null && typeof attrs === "object" && !Array.isArray(attrs)) {
|
|
353
|
+
total += estMappingBytes(attrs);
|
|
354
|
+
}
|
|
355
|
+
for (const key of ["events", "links"]) {
|
|
356
|
+
const coll = s[key];
|
|
357
|
+
if (!Array.isArray(coll)) continue;
|
|
358
|
+
for (const child of coll) {
|
|
359
|
+
total += CHILD_ENVELOPE_BYTES;
|
|
360
|
+
const ca = child?.attributes;
|
|
361
|
+
if (ca != null && typeof ca === "object" && !Array.isArray(ca)) {
|
|
362
|
+
total += estMappingBytes(ca);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
return total;
|
|
367
|
+
} catch {
|
|
368
|
+
return SPAN_ENVELOPE_BYTES;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
function spanAttrCount(span) {
|
|
372
|
+
const attrs = span.attributes;
|
|
373
|
+
if (attrs == null) return 0;
|
|
374
|
+
if (attrs instanceof Map) return attrs.size;
|
|
375
|
+
if (typeof attrs === "object") return Object.keys(attrs).length;
|
|
376
|
+
return 0;
|
|
377
|
+
}
|
|
378
|
+
var BatchSpanProcessor = class _BatchSpanProcessor {
|
|
379
|
+
_exporters;
|
|
380
|
+
_batchSize;
|
|
381
|
+
_batchTimeoutMs;
|
|
382
|
+
_maxQueueSize;
|
|
383
|
+
// ⚠ NO `_debug` FIELD. It existed, was assigned, and was read by NOTHING —
|
|
384
|
+
// `tsc --noEmit` had been RED on this package at HEAD for it (TS6133), which
|
|
385
|
+
// survived because `ci-local.sh` runs this package's vitest and never its
|
|
386
|
+
// typecheck, and `prepublishOnly` runs `build && test` — also no typecheck.
|
|
387
|
+
// Filed F-SDKJSTYPECHECK-001. Debug output here is gated globally by
|
|
388
|
+
// `setDebug()` in `../utils/log.ts`, so a per-processor flag was always
|
|
389
|
+
// redundant; Python's `self._debug` exists because `logging` has no such
|
|
390
|
+
// global switch.
|
|
391
|
+
_queue = [];
|
|
392
|
+
_timer = null;
|
|
393
|
+
_started = false;
|
|
394
|
+
_flushing = false;
|
|
395
|
+
_beforeExitHandler = null;
|
|
396
|
+
// Retry tracking for failed batches (Audit #5)
|
|
397
|
+
_retryCounts = /* @__PURE__ */ new Map();
|
|
398
|
+
static MAX_RETRIES = 3;
|
|
399
|
+
_lastRefusalWarnAt = Number.NEGATIVE_INFINITY;
|
|
400
|
+
// ── Masking (see `../masking.ts`) ──────────────────────────────────────────
|
|
401
|
+
_mask;
|
|
402
|
+
// ── Content capture gate (see `../masking.ts`) ─────────────────────────────
|
|
403
|
+
// Fail-closed: an unspecified value means "do not capture". This is the ONE
|
|
404
|
+
// place the gate runs for BOTH content paths — provider capture AND hand-set
|
|
405
|
+
// attributes — so it must not be conditional on anything a caller might
|
|
406
|
+
// forget to pass. Python twin: `BatchSpanProcessor._trace_content`.
|
|
407
|
+
_traceContent;
|
|
408
|
+
_lastMaskWarnAt = Number.NEGATIVE_INFINITY;
|
|
409
|
+
_lastSlowMaskWarnAt = Number.NEGATIVE_INFINITY;
|
|
410
|
+
// Metrics
|
|
411
|
+
/** DEPRECATED flat total. Retained as the exact SUM of
|
|
412
|
+
* `droppedSpansByReason` so existing readers keep working (RULING §5
|
|
413
|
+
* back-compat — the same deprecate-and-alias shape this codebase used for
|
|
414
|
+
* `complete`->`settled` and `spans_flushed_total`). Prefer the labelled
|
|
415
|
+
* record: one integer cannot tell an under-provisioned queue from a dead
|
|
416
|
+
* gateway from a redeploy. */
|
|
417
|
+
droppedSpans = 0;
|
|
418
|
+
droppedSpansByReason = {
|
|
419
|
+
queue_full: 0,
|
|
420
|
+
transport_refused: 0,
|
|
421
|
+
shutdown_residue: 0
|
|
422
|
+
};
|
|
423
|
+
exportedSpans = 0;
|
|
424
|
+
/** Export ATTEMPTS, not a span count. */
|
|
425
|
+
failedExports = 0;
|
|
426
|
+
/**
|
|
427
|
+
* Fields whose mask callback threw and were replaced with
|
|
428
|
+
* `MASK_ERROR_MARKER`. A FIELD count, not a span count — one span can
|
|
429
|
+
* contribute several. Non-zero means those fields carry a marker instead of
|
|
430
|
+
* data: a customer-code bug, not a transport one.
|
|
431
|
+
*/
|
|
432
|
+
maskErrors = 0;
|
|
433
|
+
constructor(options) {
|
|
434
|
+
this._exporters = [...options.exporters];
|
|
435
|
+
const requestedBatchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;
|
|
436
|
+
const clampedBatchSize = Math.max(1, Math.min(requestedBatchSize, 1e4));
|
|
437
|
+
if (clampedBatchSize !== requestedBatchSize) {
|
|
438
|
+
warn(
|
|
439
|
+
`batchSize=${requestedBatchSize} is outside the allowed range [1, 10000]; clamping to ${clampedBatchSize}`
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
this._batchSize = clampedBatchSize;
|
|
443
|
+
this._batchTimeoutMs = options.batchTimeoutMs ?? 1e3;
|
|
444
|
+
this._maxQueueSize = options.maxQueueSize ?? 1e4;
|
|
445
|
+
this._mask = options.mask;
|
|
446
|
+
this._traceContent = options.traceContent ?? false;
|
|
447
|
+
}
|
|
448
|
+
start() {
|
|
449
|
+
if (this._started) return;
|
|
450
|
+
this._started = true;
|
|
451
|
+
this._timer = setInterval(() => {
|
|
452
|
+
void this._exportBatch();
|
|
453
|
+
}, this._batchTimeoutMs);
|
|
454
|
+
this._timer.unref();
|
|
455
|
+
this._beforeExitHandler = () => {
|
|
456
|
+
void this.shutdown();
|
|
457
|
+
};
|
|
458
|
+
process.once("beforeExit", this._beforeExitHandler);
|
|
459
|
+
}
|
|
460
|
+
/** Record `count` discarded spans under `reason`.
|
|
461
|
+
*
|
|
462
|
+
* `droppedSpans` is maintained as the exact sum of the labelled counters
|
|
463
|
+
* (RULING §5 back-compat), so the locked pins — which read the flat
|
|
464
|
+
* integer — stay meaningful. */
|
|
465
|
+
_recordDropped(reason, count = 1) {
|
|
466
|
+
this.droppedSpans += count;
|
|
467
|
+
this.droppedSpansByReason[reason] += count;
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Run the customer mask over a batch, in place. Never throws.
|
|
471
|
+
*
|
|
472
|
+
* Failure semantics are ruled in `../masking.ts`: a field whose mask throws
|
|
473
|
+
* becomes `MASK_ERROR_MARKER` and the span is kept. The counter is per FIELD;
|
|
474
|
+
* both warnings are rate-limited to one per window so a mask that throws on
|
|
475
|
+
* every span cannot flood the customer's logs — the same shape as the
|
|
476
|
+
* transport-refusal warning above.
|
|
477
|
+
*/
|
|
478
|
+
_applyMask(batch) {
|
|
479
|
+
const mask = this._mask;
|
|
480
|
+
if (mask === void 0) return;
|
|
481
|
+
const { errors, elapsedMs } = applyMaskBatch(batch, mask);
|
|
482
|
+
const now = Date.now();
|
|
483
|
+
if (errors > 0) {
|
|
484
|
+
this.maskErrors += errors;
|
|
485
|
+
if (now - this._lastMaskWarnAt > MASK_WARN_WINDOW_MS) {
|
|
486
|
+
this._lastMaskWarnAt = now;
|
|
487
|
+
warnMaskErrors(errors, this.maskErrors);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
if (elapsedMs > MASK_BUDGET_MS_PER_SPAN * batch.length && now - this._lastSlowMaskWarnAt > MASK_WARN_WINDOW_MS) {
|
|
491
|
+
this._lastSlowMaskWarnAt = now;
|
|
492
|
+
warnMaskSlow(batch.length, elapsedMs);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Drain what we hold, or name what we could not (F-SDKDRAIN-001).
|
|
497
|
+
*
|
|
498
|
+
* Per RULING §4 (option E, hard-bounded) the drain loops until ONE of: the
|
|
499
|
+
* queue is empty; the deadline expires; or a full round completes with no
|
|
500
|
+
* exporter returning SUCCESS.
|
|
501
|
+
*
|
|
502
|
+
* ⚠ The `_flushing` handling is load-bearing, and `SDKDRAIN_JS_004` exists
|
|
503
|
+
* to catch its absence. `_exportBatch()` returns immediately when an export
|
|
504
|
+
* is already in flight (`:171`), so a loop that merely calls it again makes
|
|
505
|
+
* NO progress and abandons the queue exactly as before — measured at 900 of
|
|
506
|
+
* 1,000. We await a tick instead, the shape `flush()` already models.
|
|
507
|
+
*
|
|
508
|
+
* Anything still queued when the loop stops is COUNTED as `shutdown_residue`
|
|
509
|
+
* and announced with a WARNING. The warning is the primary signal, not the
|
|
510
|
+
* counter: a counter incremented inside `shutdown()` is written to memory
|
|
511
|
+
* about to be freed and has no reader (RULING §2 / §8.2).
|
|
512
|
+
*/
|
|
513
|
+
async shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
|
|
514
|
+
if (!this._started) return;
|
|
515
|
+
this._started = false;
|
|
516
|
+
if (this._timer) {
|
|
517
|
+
clearInterval(this._timer);
|
|
518
|
+
this._timer = null;
|
|
519
|
+
}
|
|
520
|
+
if (this._beforeExitHandler) {
|
|
521
|
+
process.removeListener("beforeExit", this._beforeExitHandler);
|
|
522
|
+
this._beforeExitHandler = null;
|
|
523
|
+
}
|
|
524
|
+
const reserveMs = Math.min(SHUTDOWN_RESERVE_MS, timeoutMs / 2);
|
|
525
|
+
const drainDeadline = Date.now() + Math.max(0, timeoutMs - reserveMs);
|
|
526
|
+
while (this._queue.length > 0 || this._flushing) {
|
|
527
|
+
if (Date.now() >= drainDeadline) break;
|
|
528
|
+
const outcome = await this._exportBatch();
|
|
529
|
+
if (outcome === 3 /* Busy */) {
|
|
530
|
+
await new Promise((r) => setTimeout(r, 1));
|
|
531
|
+
continue;
|
|
532
|
+
}
|
|
533
|
+
if (outcome !== 1 /* Delivered */) {
|
|
534
|
+
break;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
const residue = this._queue.length;
|
|
538
|
+
if (residue > 0) {
|
|
539
|
+
this._queue.length = 0;
|
|
540
|
+
this._recordDropped("shutdown_residue", residue);
|
|
541
|
+
warn(
|
|
542
|
+
`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.`
|
|
543
|
+
);
|
|
544
|
+
}
|
|
545
|
+
for (const exporter of this._exporters) {
|
|
546
|
+
try {
|
|
547
|
+
await exporter.shutdown();
|
|
548
|
+
} catch (e) {
|
|
549
|
+
debug(`Error shutting down ${exporter.name}: ${e}`);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
this._retryCounts.clear();
|
|
553
|
+
debug(
|
|
554
|
+
`BatchSpanProcessor shutdown. Exported: ${this.exportedSpans}, Dropped: ${this.droppedSpans}, Failed: ${this.failedExports}`
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
onSpanEnd(span) {
|
|
558
|
+
if (!this._started) return;
|
|
559
|
+
if (this._queue.length >= this._maxQueueSize) {
|
|
560
|
+
this._recordDropped("queue_full");
|
|
561
|
+
if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
|
|
562
|
+
warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
|
|
563
|
+
}
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
this._queue.push(span);
|
|
567
|
+
if (this._queue.length >= this._batchSize) {
|
|
568
|
+
void this._exportBatch();
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Flush pending spans.
|
|
573
|
+
*
|
|
574
|
+
* @returns `true` only if everything queued at entry was DELIVERED.
|
|
575
|
+
*
|
|
576
|
+
* RULING §6. This used to answer a different question — "is the queue
|
|
577
|
+
* empty?" — and those two diverge in exactly one case: when spans left the
|
|
578
|
+
* queue WITHOUT reaching the transport. That case is the entire finding. A
|
|
579
|
+
* customer who calls `flush()` before exit and gets `true` has done
|
|
580
|
+
* everything right; silence lets them discover the problem, a false
|
|
581
|
+
* affirmative forecloses it.
|
|
582
|
+
*
|
|
583
|
+
* Returns `false` when (a) the deadline expires with spans still queued,
|
|
584
|
+
* (b) any span was discarded during the window — breaker refusal or retry
|
|
585
|
+
* exhaustion — or (c) it is called after `shutdown()` and the shutdown
|
|
586
|
+
* residue was non-zero.
|
|
587
|
+
*
|
|
588
|
+
* ⚠ (b) reads the flat total, so a concurrent `queue_full` drop of a span
|
|
589
|
+
* that arrived DURING the window also answers `false`. That is the
|
|
590
|
+
* conservative direction on purpose: a false negative costs a caller one
|
|
591
|
+
* more flush, a false positive is the defect being fixed.
|
|
592
|
+
*/
|
|
593
|
+
async flush(timeoutMs = SHUTDOWN_BUDGET_MS) {
|
|
594
|
+
if (!this._started) {
|
|
595
|
+
return this._queue.length === 0 && this.droppedSpansByReason.shutdown_residue === 0;
|
|
596
|
+
}
|
|
597
|
+
const start = Date.now();
|
|
598
|
+
const discardedAtEntry = this.droppedSpans;
|
|
599
|
+
while (this._queue.length > 0 || this._flushing) {
|
|
600
|
+
if (!this._flushing && this._queue.length > 0) {
|
|
601
|
+
await this._exportBatch();
|
|
602
|
+
} else {
|
|
603
|
+
await new Promise((r) => setTimeout(r, 1));
|
|
604
|
+
}
|
|
605
|
+
if (Date.now() - start > timeoutMs) return false;
|
|
606
|
+
}
|
|
607
|
+
return this.droppedSpans === discardedAtEntry;
|
|
608
|
+
}
|
|
609
|
+
getMetrics() {
|
|
610
|
+
return {
|
|
611
|
+
exportedSpans: this.exportedSpans,
|
|
612
|
+
droppedSpans: this.droppedSpans,
|
|
613
|
+
droppedSpansByReason: { ...this.droppedSpansByReason },
|
|
614
|
+
failedExports: this.failedExports,
|
|
615
|
+
maskErrors: this.maskErrors,
|
|
616
|
+
queueSize: this._queue.length,
|
|
617
|
+
queueCapacity: this._maxQueueSize,
|
|
618
|
+
queueUtilization: this._queue.length / this._maxQueueSize
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
async _exportBatch() {
|
|
622
|
+
if (this._flushing) return 3 /* Busy */;
|
|
623
|
+
if (this._queue.length === 0) return 0 /* Empty */;
|
|
624
|
+
this._flushing = true;
|
|
625
|
+
try {
|
|
626
|
+
let take = 0;
|
|
627
|
+
let pairs = 0;
|
|
628
|
+
let nbytes = 0;
|
|
629
|
+
const limit = Math.min(this._batchSize, this._queue.length);
|
|
630
|
+
while (take < limit) {
|
|
631
|
+
const head = this._queue[take];
|
|
632
|
+
const spanPairs = spanAttrCount(head);
|
|
633
|
+
const spanBytes = spanBytesEstimate(head);
|
|
634
|
+
if (take > 0 && (pairs + spanPairs > MAX_ATTRIBUTE_PAIRS_PER_BATCH || nbytes + spanBytes > MAX_BATCH_BYTES)) {
|
|
635
|
+
break;
|
|
636
|
+
}
|
|
637
|
+
pairs += spanPairs;
|
|
638
|
+
nbytes += spanBytes;
|
|
639
|
+
take++;
|
|
640
|
+
}
|
|
641
|
+
const batch = this._queue.splice(0, take);
|
|
642
|
+
if (batch.length === 0) return 0 /* Empty */;
|
|
643
|
+
if (!this._traceContent) {
|
|
644
|
+
const stripped = stripContentBatch(batch);
|
|
645
|
+
if (stripped > 0) {
|
|
646
|
+
debug(
|
|
647
|
+
`traceContent is off \u2014 omitted ${stripped} content field(s) from ${batch.length} span(s)`
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
if (this._mask !== void 0) {
|
|
652
|
+
this._applyMask(batch);
|
|
653
|
+
}
|
|
654
|
+
debug(`Exporting batch of ${batch.length} spans`);
|
|
655
|
+
let batchExported = false;
|
|
656
|
+
for (const exporter of this._exporters) {
|
|
657
|
+
try {
|
|
658
|
+
const result = await exporter.export(batch);
|
|
659
|
+
if (result === "success" /* SUCCESS */) {
|
|
660
|
+
if (!batchExported) {
|
|
661
|
+
this.exportedSpans += batch.length;
|
|
662
|
+
batchExported = true;
|
|
663
|
+
for (const span of batch) {
|
|
664
|
+
this._retryCounts.delete(span.spanId);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
} else {
|
|
668
|
+
this.failedExports++;
|
|
669
|
+
}
|
|
670
|
+
} catch (e) {
|
|
671
|
+
this.failedExports++;
|
|
672
|
+
debug(`Export to ${exporter.name} failed: ${e}`);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
if (!batchExported) {
|
|
676
|
+
let dropped = 0;
|
|
677
|
+
const retryable = batch.filter((span) => {
|
|
678
|
+
const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;
|
|
679
|
+
if (count > _BatchSpanProcessor.MAX_RETRIES) {
|
|
680
|
+
this._retryCounts.delete(span.spanId);
|
|
681
|
+
this._recordDropped("transport_refused");
|
|
682
|
+
dropped++;
|
|
683
|
+
return false;
|
|
684
|
+
}
|
|
685
|
+
this._retryCounts.set(span.spanId, count);
|
|
686
|
+
return true;
|
|
687
|
+
});
|
|
688
|
+
if (retryable.length > 0) {
|
|
689
|
+
this._queue.unshift(...retryable);
|
|
690
|
+
debug(`Re-queued ${retryable.length} spans for retry (${batch.length - retryable.length} dropped after max retries)`);
|
|
691
|
+
}
|
|
692
|
+
if (dropped > 0) {
|
|
693
|
+
const now = Date.now();
|
|
694
|
+
if (now - this._lastRefusalWarnAt > REFUSAL_WARN_WINDOW_MS) {
|
|
695
|
+
this._lastRefusalWarnAt = now;
|
|
696
|
+
warn(
|
|
697
|
+
`${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.`
|
|
698
|
+
);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
return batchExported ? 1 /* Delivered */ : 2 /* Failed */;
|
|
703
|
+
} finally {
|
|
704
|
+
this._flushing = false;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
};
|
|
708
|
+
|
|
93
709
|
// src/config.ts
|
|
94
710
|
var DEFAULT_ENDPOINT = "https://app.risicare.ai";
|
|
95
711
|
function resolveConfig(config) {
|
|
@@ -105,15 +721,20 @@ function resolveConfig(config) {
|
|
|
105
721
|
const environment = config?.environment ?? env.RISICARE_ENVIRONMENT ?? "development";
|
|
106
722
|
const serviceName = config?.serviceName ?? env.RISICARE_SERVICE_NAME;
|
|
107
723
|
const serviceVersion = config?.serviceVersion ?? env.RISICARE_SERVICE_VERSION;
|
|
108
|
-
const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT,
|
|
724
|
+
const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, false);
|
|
109
725
|
const sampleRateRaw = config?.sampleRate ?? parseFloat(env.RISICARE_SAMPLE_RATE ?? "1.0");
|
|
110
726
|
const debug2 = config?.debug ?? parseBool(env.RISICARE_DEBUG, false);
|
|
111
727
|
const compress = config?.compress ?? parseBool(env.RISICARE_COMPRESS, false);
|
|
112
|
-
const batchSizeRaw = config?.batchSize ?? parseNumericEnv(env.RISICARE_BATCH_SIZE,
|
|
728
|
+
const batchSizeRaw = config?.batchSize ?? parseNumericEnv(env.RISICARE_BATCH_SIZE, DEFAULT_BATCH_SIZE);
|
|
113
729
|
const batchTimeoutMsRaw = config?.batchTimeoutMs ?? parseNumericEnv(env.RISICARE_BATCH_TIMEOUT_MS, 1e3);
|
|
114
730
|
const maxQueueSizeRaw = config?.maxQueueSize ?? parseNumericEnv(env.RISICARE_MAX_QUEUE_SIZE, 1e4);
|
|
115
731
|
const sampleRate = validateSampleRate(sampleRateRaw);
|
|
116
|
-
|
|
732
|
+
if (sampleRate < 1) {
|
|
733
|
+
console.warn(
|
|
734
|
+
`[risicare] sampleRate=${sampleRate} \u2014 head sampling is applied in-process and the rate is NOT transmitted to the platform. Trace counts, error rates and cost figures in the dashboard will describe the sampled subset only, and cannot be scaled back to totals. Sampling is trace-coherent: a dropped trace drops whole.`
|
|
735
|
+
);
|
|
736
|
+
}
|
|
737
|
+
const batchSize = validatePositiveInt("batchSize", batchSizeRaw, DEFAULT_BATCH_SIZE, 1, 1e4);
|
|
117
738
|
const batchTimeoutMs = validatePositiveInt("batchTimeoutMs", batchTimeoutMsRaw, 1e3, 1, 6e5);
|
|
118
739
|
const maxQueueSize = validatePositiveInt("maxQueueSize", maxQueueSizeRaw, 1e4, 1, 1e6);
|
|
119
740
|
let enabled;
|
|
@@ -139,7 +760,9 @@ function resolveConfig(config) {
|
|
|
139
760
|
maxQueueSize,
|
|
140
761
|
debug: debug2,
|
|
141
762
|
compress,
|
|
142
|
-
metadata: config?.metadata ?? {}
|
|
763
|
+
metadata: config?.metadata ?? {},
|
|
764
|
+
// No env fallback — see the field's note on RisicareConfig.
|
|
765
|
+
mask: config?.mask
|
|
143
766
|
};
|
|
144
767
|
}
|
|
145
768
|
function parseBool(value, defaultValue) {
|
|
@@ -550,45 +1173,442 @@ function shouldSample(traceId, sampleRate) {
|
|
|
550
1173
|
return hash / 4294967295 < sampleRate;
|
|
551
1174
|
}
|
|
552
1175
|
|
|
553
|
-
// src/
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
1176
|
+
// src/runtime/config.ts
|
|
1177
|
+
function resolveFixRuntimeConfig(config) {
|
|
1178
|
+
return {
|
|
1179
|
+
apiEndpoint: config.apiEndpoint,
|
|
1180
|
+
apiKey: config.apiKey,
|
|
1181
|
+
enabled: config.enabled ?? true,
|
|
1182
|
+
cacheEnabled: config.cacheEnabled ?? true,
|
|
1183
|
+
cacheTtlMs: config.cacheTtlMs ?? 3e5,
|
|
1184
|
+
cacheMaxEntries: config.cacheMaxEntries ?? 1e3,
|
|
1185
|
+
autoRefresh: config.autoRefresh ?? true,
|
|
1186
|
+
refreshIntervalMs: config.refreshIntervalMs ?? 6e4,
|
|
1187
|
+
dryRun: config.dryRun ?? false,
|
|
1188
|
+
abTestingEnabled: config.abTestingEnabled ?? true,
|
|
1189
|
+
timeoutMs: config.timeoutMs ?? 1e3,
|
|
1190
|
+
debug: config.debug ?? false
|
|
1191
|
+
};
|
|
559
1192
|
}
|
|
560
|
-
function
|
|
561
|
-
|
|
1193
|
+
function matchesError(fix, errorCode) {
|
|
1194
|
+
if (fix.errorCode === errorCode) {
|
|
1195
|
+
return true;
|
|
1196
|
+
}
|
|
1197
|
+
if (fix.errorCode.endsWith("*")) {
|
|
1198
|
+
const prefix = fix.errorCode.slice(0, -1);
|
|
1199
|
+
return errorCode.startsWith(prefix);
|
|
1200
|
+
}
|
|
1201
|
+
return false;
|
|
562
1202
|
}
|
|
563
|
-
function
|
|
564
|
-
|
|
1203
|
+
function shouldApply(fix, sessionHash) {
|
|
1204
|
+
if (fix.trafficPercentage >= 100) return true;
|
|
1205
|
+
if (fix.trafficPercentage <= 0) return false;
|
|
1206
|
+
const bucket = sessionHash % 100;
|
|
1207
|
+
return bucket < fix.trafficPercentage;
|
|
565
1208
|
}
|
|
566
|
-
function
|
|
567
|
-
|
|
1209
|
+
function activeFixFromApiResponse(item) {
|
|
1210
|
+
return {
|
|
1211
|
+
fixId: item.id ?? item.fix_id ?? item.fixId ?? "",
|
|
1212
|
+
deploymentId: item.deployment_id ?? item.deploymentId ?? "",
|
|
1213
|
+
errorCode: item.error_code ?? item.errorCode ?? "",
|
|
1214
|
+
fixType: item.fix_type ?? item.fixType ?? "prompt",
|
|
1215
|
+
config: item.config ?? {},
|
|
1216
|
+
trafficPercentage: item.traffic_percentage ?? item.trafficPercentage ?? 100,
|
|
1217
|
+
version: item.version ?? 1
|
|
1218
|
+
};
|
|
568
1219
|
}
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
1220
|
+
|
|
1221
|
+
// src/runtime/taxonomy.generated.ts
|
|
1222
|
+
var CANONICAL_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
1223
|
+
"COMMUNICATION.CONTENT.AMBIGUOUS",
|
|
1224
|
+
"COMMUNICATION.CONTENT.CORRUPTED",
|
|
1225
|
+
"COMMUNICATION.CONTENT.INCOMPATIBLE",
|
|
1226
|
+
"COMMUNICATION.CONTENT.MALFORMED",
|
|
1227
|
+
"COMMUNICATION.CONTENT.TOO_LARGE",
|
|
1228
|
+
"COMMUNICATION.DELIVERY.DELAYED",
|
|
1229
|
+
"COMMUNICATION.DELIVERY.DUPLICATED",
|
|
1230
|
+
"COMMUNICATION.DELIVERY.EXPIRED",
|
|
1231
|
+
"COMMUNICATION.DELIVERY.OUT_OF_ORDER",
|
|
1232
|
+
"COMMUNICATION.DELIVERY.UNDELIVERABLE",
|
|
1233
|
+
"COMMUNICATION.ROUTING.BROADCAST_STORM",
|
|
1234
|
+
"COMMUNICATION.ROUTING.LOOP",
|
|
1235
|
+
"COMMUNICATION.ROUTING.NO_ROUTE",
|
|
1236
|
+
"COMMUNICATION.ROUTING.PARTITION",
|
|
1237
|
+
"COMMUNICATION.ROUTING.WRONG_ROUTE",
|
|
1238
|
+
"CONSENSUS.AGREEMENT.INCONSISTENT",
|
|
1239
|
+
"CONSENSUS.AGREEMENT.QUORUM_FAILED",
|
|
1240
|
+
"CONSENSUS.AGREEMENT.REJECTED",
|
|
1241
|
+
"CONSENSUS.AGREEMENT.STALE_VOTE",
|
|
1242
|
+
"CONSENSUS.AGREEMENT.TIMEOUT",
|
|
1243
|
+
"CONSENSUS.CONFLICT.BIAS",
|
|
1244
|
+
"CONSENSUS.CONFLICT.CASCADING",
|
|
1245
|
+
"CONSENSUS.CONFLICT.DEADLOCK",
|
|
1246
|
+
"CONSENSUS.CONFLICT.RESOLUTION_REJECTED",
|
|
1247
|
+
"CONSENSUS.CONFLICT.UNRESOLVED",
|
|
1248
|
+
"CONSENSUS.VOTING.ABSTENTION_FLOOD",
|
|
1249
|
+
"CONSENSUS.VOTING.COERCED_VOTE",
|
|
1250
|
+
"CONSENSUS.VOTING.DUPLICATE_VOTE",
|
|
1251
|
+
"CONSENSUS.VOTING.INVALID_VOTE",
|
|
1252
|
+
"CONSENSUS.VOTING.SPLIT_VOTE",
|
|
1253
|
+
"COORDINATION.HANDOFF.DELAYED",
|
|
1254
|
+
"COORDINATION.HANDOFF.DUPLICATED",
|
|
1255
|
+
"COORDINATION.HANDOFF.INCOMPLETE",
|
|
1256
|
+
"COORDINATION.HANDOFF.LOST",
|
|
1257
|
+
"COORDINATION.HANDOFF.WRONG_RECIPIENT",
|
|
1258
|
+
"COORDINATION.SYNCHRONIZATION.CLOCK_SKEW",
|
|
1259
|
+
"COORDINATION.SYNCHRONIZATION.OUT_OF_ORDER",
|
|
1260
|
+
"COORDINATION.SYNCHRONIZATION.RACE_CONDITION",
|
|
1261
|
+
"COORDINATION.SYNCHRONIZATION.SPLIT_BRAIN",
|
|
1262
|
+
"COORDINATION.SYNCHRONIZATION.VERSION_MISMATCH",
|
|
1263
|
+
"COORDINATION.WORKFLOW.CYCLE",
|
|
1264
|
+
"COORDINATION.WORKFLOW.DEADLOCK",
|
|
1265
|
+
"COORDINATION.WORKFLOW.LIVELOCK",
|
|
1266
|
+
"COORDINATION.WORKFLOW.ORPHANED",
|
|
1267
|
+
"COORDINATION.WORKFLOW.STARVATION",
|
|
1268
|
+
"MEMORY.CONTEXT_WINDOW.DROPPED",
|
|
1269
|
+
"MEMORY.CONTEXT_WINDOW.EXCEEDED",
|
|
1270
|
+
"MEMORY.CONTEXT_WINDOW.FRAGMENTED",
|
|
1271
|
+
"MEMORY.CONTEXT_WINDOW.PRIORITY_ERROR",
|
|
1272
|
+
"MEMORY.RETRIEVAL.INCOMPLETE",
|
|
1273
|
+
"MEMORY.RETRIEVAL.NOT_FOUND",
|
|
1274
|
+
"MEMORY.RETRIEVAL.OUTDATED",
|
|
1275
|
+
"MEMORY.RETRIEVAL.TOO_MANY",
|
|
1276
|
+
"MEMORY.RETRIEVAL.WRONG_MATCH",
|
|
1277
|
+
"MEMORY.STATE.CORRUPTED",
|
|
1278
|
+
"MEMORY.STATE.INCONSISTENT",
|
|
1279
|
+
"MEMORY.STATE.LOST",
|
|
1280
|
+
"MEMORY.STATE.OVERFLOW",
|
|
1281
|
+
"MEMORY.STATE.STALE",
|
|
1282
|
+
"ORCHESTRATION.DELEGATION.CAPABILITY_MISMATCH",
|
|
1283
|
+
"ORCHESTRATION.DELEGATION.CIRCULAR_DELEGATION",
|
|
1284
|
+
"ORCHESTRATION.DELEGATION.EXCESSIVE_DEPTH",
|
|
1285
|
+
"ORCHESTRATION.DELEGATION.NO_AVAILABLE_AGENT",
|
|
1286
|
+
"ORCHESTRATION.DELEGATION.OVERLOADED_AGENT",
|
|
1287
|
+
"ORCHESTRATION.LIFECYCLE.CLEANUP_FAILED",
|
|
1288
|
+
"ORCHESTRATION.LIFECYCLE.CRASHED",
|
|
1289
|
+
"ORCHESTRATION.LIFECYCLE.HUNG",
|
|
1290
|
+
"ORCHESTRATION.LIFECYCLE.SPAWN_FAILED",
|
|
1291
|
+
"ORCHESTRATION.LIFECYCLE.ZOMBIE",
|
|
1292
|
+
"ORCHESTRATION.SCALING.OVERLOADED",
|
|
1293
|
+
"ORCHESTRATION.SCALING.QUOTA_EXCEEDED",
|
|
1294
|
+
"ORCHESTRATION.SCALING.SCALE_DOWN_FAILED",
|
|
1295
|
+
"ORCHESTRATION.SCALING.SCALE_UP_FAILED",
|
|
1296
|
+
"ORCHESTRATION.SCALING.UNDERUTILIZED",
|
|
1297
|
+
"OUTPUT.FORMAT.ENCODING",
|
|
1298
|
+
"OUTPUT.FORMAT.INVALID_JSON",
|
|
1299
|
+
"OUTPUT.FORMAT.MALFORMED",
|
|
1300
|
+
"OUTPUT.FORMAT.SCHEMA_VIOLATION",
|
|
1301
|
+
"OUTPUT.FORMAT.TRUNCATED",
|
|
1302
|
+
"OUTPUT.QUALITY.INCOMPLETE",
|
|
1303
|
+
"OUTPUT.QUALITY.IRRELEVANT",
|
|
1304
|
+
"OUTPUT.QUALITY.REPETITIVE",
|
|
1305
|
+
"OUTPUT.QUALITY.UNCLEAR",
|
|
1306
|
+
"OUTPUT.QUALITY.VERBOSE",
|
|
1307
|
+
"OUTPUT.SAFETY.BIAS",
|
|
1308
|
+
"OUTPUT.SAFETY.COPYRIGHT",
|
|
1309
|
+
"OUTPUT.SAFETY.HARMFUL_CONTENT",
|
|
1310
|
+
"OUTPUT.SAFETY.PII_LEAK",
|
|
1311
|
+
"OUTPUT.SAFETY.POLICY_VIOLATION",
|
|
1312
|
+
"PERCEPTION.CONTEXT.CONFLICTING",
|
|
1313
|
+
"PERCEPTION.CONTEXT.IRRELEVANT",
|
|
1314
|
+
"PERCEPTION.CONTEXT.MISSING",
|
|
1315
|
+
"PERCEPTION.CONTEXT.OVERFLOW",
|
|
1316
|
+
"PERCEPTION.CONTEXT.STALE",
|
|
1317
|
+
"PERCEPTION.INPUT.ENCODING",
|
|
1318
|
+
"PERCEPTION.INPUT.INJECTION",
|
|
1319
|
+
"PERCEPTION.INPUT.MALFORMED",
|
|
1320
|
+
"PERCEPTION.INPUT.SCHEMA_MISMATCH",
|
|
1321
|
+
"PERCEPTION.INPUT.TRUNCATED",
|
|
1322
|
+
"PERCEPTION.PARSING.DATE_FORMAT",
|
|
1323
|
+
"PERCEPTION.PARSING.JSON_INVALID",
|
|
1324
|
+
"PERCEPTION.PARSING.NUMBER_FORMAT",
|
|
1325
|
+
"PERCEPTION.PARSING.REFERENCE_BROKEN",
|
|
1326
|
+
"PERCEPTION.PARSING.XML_INVALID",
|
|
1327
|
+
"REASONING.DECISION.BIASED",
|
|
1328
|
+
"REASONING.DECISION.INDECISIVE",
|
|
1329
|
+
"REASONING.DECISION.OSCILLATING",
|
|
1330
|
+
"REASONING.DECISION.OVERCONFIDENT",
|
|
1331
|
+
"REASONING.DECISION.PREMATURE",
|
|
1332
|
+
"REASONING.HALLUCINATION.CAPABILITY",
|
|
1333
|
+
"REASONING.HALLUCINATION.CITATION",
|
|
1334
|
+
"REASONING.HALLUCINATION.ENTITY",
|
|
1335
|
+
"REASONING.HALLUCINATION.FACTUAL",
|
|
1336
|
+
"REASONING.HALLUCINATION.TEMPORAL",
|
|
1337
|
+
"REASONING.LOGIC.CIRCULAR",
|
|
1338
|
+
"REASONING.LOGIC.CONTRADICTION",
|
|
1339
|
+
"REASONING.LOGIC.INCOMPLETE",
|
|
1340
|
+
"REASONING.LOGIC.INVALID_INFERENCE",
|
|
1341
|
+
"REASONING.LOGIC.MISSING_PREMISE",
|
|
1342
|
+
"REASONING.PLANNING.INCOMPLETE",
|
|
1343
|
+
"REASONING.PLANNING.INFEASIBLE",
|
|
1344
|
+
"REASONING.PLANNING.SCOPE_CREEP",
|
|
1345
|
+
"REASONING.PLANNING.SUBOPTIMAL",
|
|
1346
|
+
"REASONING.PLANNING.UNSAFE",
|
|
1347
|
+
"RESOURCES.ACCESS.DENIED",
|
|
1348
|
+
"RESOURCES.ACCESS.EXPIRED",
|
|
1349
|
+
"RESOURCES.ACCESS.LOCKED",
|
|
1350
|
+
"RESOURCES.ACCESS.NOT_FOUND",
|
|
1351
|
+
"RESOURCES.ACCESS.REVOKED",
|
|
1352
|
+
"RESOURCES.CONTENTION.DEADLOCK",
|
|
1353
|
+
"RESOURCES.CONTENTION.OVERFLOW",
|
|
1354
|
+
"RESOURCES.CONTENTION.PRIORITY_INVERSION",
|
|
1355
|
+
"RESOURCES.CONTENTION.STARVATION",
|
|
1356
|
+
"RESOURCES.CONTENTION.THRASHING",
|
|
1357
|
+
"RESOURCES.QUOTA.ALLOCATION_FAILED",
|
|
1358
|
+
"RESOURCES.QUOTA.EXCEEDED",
|
|
1359
|
+
"RESOURCES.QUOTA.LEAK",
|
|
1360
|
+
"RESOURCES.QUOTA.STALE",
|
|
1361
|
+
"RESOURCES.QUOTA.UNFAIR_DISTRIBUTION",
|
|
1362
|
+
"TOOL.EXECUTION.CRASHED",
|
|
1363
|
+
"TOOL.EXECUTION.DEPENDENCY_FAILED",
|
|
1364
|
+
"TOOL.EXECUTION.RATE_LIMITED",
|
|
1365
|
+
"TOOL.EXECUTION.RESOURCE_EXHAUSTED",
|
|
1366
|
+
"TOOL.EXECUTION.TIMEOUT",
|
|
1367
|
+
"TOOL.INVOCATION.INVALID_ARGS",
|
|
1368
|
+
"TOOL.INVOCATION.MISSING_REQUIRED",
|
|
1369
|
+
"TOOL.INVOCATION.NOT_FOUND",
|
|
1370
|
+
"TOOL.INVOCATION.PERMISSION_DENIED",
|
|
1371
|
+
"TOOL.INVOCATION.TYPE_MISMATCH",
|
|
1372
|
+
"TOOL.RESULT.EMPTY",
|
|
1373
|
+
"TOOL.RESULT.ERROR_IN_RESULT",
|
|
1374
|
+
"TOOL.RESULT.PARTIAL",
|
|
1375
|
+
"TOOL.RESULT.UNEXPECTED_FORMAT",
|
|
1376
|
+
"TOOL.RESULT.UNPARSEABLE"
|
|
1377
|
+
]);
|
|
1378
|
+
var SUPPLEMENTAL_RULES = [
|
|
1379
|
+
{ re: new RegExp("timeout|timedout|aborted", "i"), code: "TOOL.EXECUTION.TIMEOUT" },
|
|
1380
|
+
{ re: new RegExp("rate.?limit|\\b429\\b|too many requests", "i"), code: "TOOL.EXECUTION.RATE_LIMITED" },
|
|
1381
|
+
{ re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "i"), code: "TOOL.EXECUTION.DEPENDENCY_FAILED" },
|
|
1382
|
+
{ re: new RegExp("\\bauth|unauthorized|forbidden|permission|\\b401\\b|\\b403\\b", "i"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
|
|
1383
|
+
{ re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "i"), code: "PERCEPTION.PARSING.JSON_INVALID" }
|
|
1384
|
+
];
|
|
1385
|
+
var GENERIC_FALLBACK = "TOOL.EXECUTION.CRASHED";
|
|
1386
|
+
|
|
1387
|
+
// src/runtime/interceptors.ts
|
|
1388
|
+
var GuardRejectedError = class extends Error {
|
|
1389
|
+
guardId;
|
|
1390
|
+
reason;
|
|
1391
|
+
phase;
|
|
1392
|
+
constructor(guardId, reason, phase) {
|
|
1393
|
+
super(`Risicare guard rejected operation: ${guardId} (${phase}) \u2014 ${reason}`);
|
|
1394
|
+
this.name = "GuardRejectedError";
|
|
1395
|
+
this.guardId = guardId;
|
|
1396
|
+
this.reason = reason;
|
|
1397
|
+
this.phase = phase;
|
|
1398
|
+
}
|
|
1399
|
+
};
|
|
1400
|
+
function createInterceptContext(operationType, operationName, options) {
|
|
1401
|
+
return {
|
|
1402
|
+
operationType,
|
|
1403
|
+
operationName,
|
|
1404
|
+
sessionId: options?.sessionId,
|
|
1405
|
+
traceId: options?.traceId,
|
|
1406
|
+
errorCode: options?.errorCode,
|
|
1407
|
+
attempt: 1,
|
|
1408
|
+
appliedFixes: []
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
var DefaultFixInterceptor = class {
|
|
1412
|
+
_config;
|
|
1413
|
+
_cache;
|
|
1414
|
+
_applier;
|
|
1415
|
+
constructor(config, cache, applier) {
|
|
1416
|
+
this._config = resolveFixRuntimeConfig(config);
|
|
1417
|
+
this._cache = cache;
|
|
1418
|
+
this._applier = applier;
|
|
1419
|
+
}
|
|
1420
|
+
/**
|
|
1421
|
+
* Apply pre-call fixes.
|
|
1422
|
+
*
|
|
1423
|
+
* - If retrying after error: look up fix by error_code, apply
|
|
1424
|
+
* prompt/parameter/fallback fixes
|
|
1425
|
+
* - Runs input guard fixes on all message content
|
|
1426
|
+
*/
|
|
1427
|
+
preCall(ctx, messages, params) {
|
|
1428
|
+
try {
|
|
1429
|
+
if (!this._config.enabled) {
|
|
1430
|
+
return { messages, params };
|
|
1431
|
+
}
|
|
1432
|
+
let modifiedMessages = messages;
|
|
1433
|
+
let modifiedParams = { ...params };
|
|
1434
|
+
if (ctx.errorCode) {
|
|
1435
|
+
const fix = this._applier.getFixForError(ctx.errorCode, ctx.sessionId);
|
|
1436
|
+
if (fix) {
|
|
1437
|
+
debug(`Applying fix ${fix.fixId} for ${ctx.errorCode}`);
|
|
1438
|
+
if (fix.fixType === "prompt" && messages) {
|
|
1439
|
+
const msgRecords = messages;
|
|
1440
|
+
const { messages: newMessages, result } = this._applier.applyPromptFix(fix, msgRecords);
|
|
1441
|
+
modifiedMessages = newMessages;
|
|
1442
|
+
ctx.appliedFixes.push(result);
|
|
1443
|
+
this._applier.logApplication(result);
|
|
1444
|
+
} else if (fix.fixType === "parameter") {
|
|
1445
|
+
const { params: newParams, result } = this._applier.applyParameterFix(fix, modifiedParams);
|
|
1446
|
+
modifiedParams = newParams;
|
|
1447
|
+
ctx.appliedFixes.push(result);
|
|
1448
|
+
this._applier.logApplication(result);
|
|
1449
|
+
} else if (fix.fixType === "fallback") {
|
|
1450
|
+
const { params: newParams, result } = this._applier.applyFallbackFix(fix, modifiedParams);
|
|
1451
|
+
modifiedParams = newParams;
|
|
1452
|
+
ctx.appliedFixes.push(result);
|
|
1453
|
+
this._applier.logApplication(result);
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
if (modifiedMessages && this._config.enabled) {
|
|
1458
|
+
for (const msg of modifiedMessages) {
|
|
1459
|
+
const content = msg.content;
|
|
1460
|
+
if (typeof content === "string") {
|
|
1461
|
+
for (const fix of this._cache.getAll()) {
|
|
1462
|
+
if (fix.fixType === "guard") {
|
|
1463
|
+
const { passed, result } = this._applier.applyGuardFix(
|
|
1464
|
+
fix,
|
|
1465
|
+
content,
|
|
1466
|
+
true
|
|
1467
|
+
);
|
|
1468
|
+
if (result.applied) {
|
|
1469
|
+
ctx.appliedFixes.push(result);
|
|
1470
|
+
this._applier.logApplication(result);
|
|
1471
|
+
}
|
|
1472
|
+
if (!passed) {
|
|
1473
|
+
throw new GuardRejectedError(
|
|
1474
|
+
fix.fixId ?? "unknown",
|
|
1475
|
+
result.reason ?? "guard rejected input",
|
|
1476
|
+
"pre_call"
|
|
1477
|
+
);
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
return { messages: modifiedMessages, params: modifiedParams };
|
|
1485
|
+
} catch (e) {
|
|
1486
|
+
if (e instanceof GuardRejectedError) throw e;
|
|
1487
|
+
debug(`DefaultFixInterceptor.preCall error: ${e}`);
|
|
1488
|
+
return { messages, params };
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
/**
|
|
1492
|
+
* Apply post-call fixes (output validation).
|
|
1493
|
+
*
|
|
1494
|
+
* Runs output guard fixes on response content.
|
|
1495
|
+
*/
|
|
1496
|
+
postCall(ctx, response) {
|
|
1497
|
+
try {
|
|
1498
|
+
if (!this._config.enabled) {
|
|
1499
|
+
return { response, shouldContinue: true };
|
|
1500
|
+
}
|
|
1501
|
+
for (const fix of this._cache.getAll()) {
|
|
1502
|
+
if (fix.fixType !== "guard") continue;
|
|
1503
|
+
const content = this._extractResponseContent(response);
|
|
1504
|
+
if (!content) continue;
|
|
1505
|
+
const { passed, result } = this._applier.applyGuardFix(
|
|
1506
|
+
fix,
|
|
1507
|
+
content,
|
|
1508
|
+
false
|
|
1509
|
+
);
|
|
1510
|
+
if (result.applied) {
|
|
1511
|
+
ctx.appliedFixes.push(result);
|
|
1512
|
+
this._applier.logApplication(result);
|
|
1513
|
+
}
|
|
1514
|
+
if (!passed) {
|
|
1515
|
+
warn(`Output guard failed for fix ${fix.fixId}: ${result.reason ?? "unknown"}`);
|
|
1516
|
+
throw new GuardRejectedError(
|
|
1517
|
+
fix.fixId ?? "unknown",
|
|
1518
|
+
result.reason ?? "guard rejected output",
|
|
1519
|
+
"post_call"
|
|
1520
|
+
);
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
return { response, shouldContinue: true };
|
|
1524
|
+
} catch (e) {
|
|
1525
|
+
if (e instanceof GuardRejectedError) throw e;
|
|
1526
|
+
debug(`DefaultFixInterceptor.postCall error: ${e}`);
|
|
1527
|
+
return { response, shouldContinue: true };
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
/**
|
|
1531
|
+
* Handle errors and decide whether to retry.
|
|
1532
|
+
*
|
|
1533
|
+
* Classifies the error, looks up retry/fallback fixes, and returns
|
|
1534
|
+
* whether the caller should retry.
|
|
1535
|
+
*/
|
|
1536
|
+
onError(ctx, error) {
|
|
1537
|
+
try {
|
|
1538
|
+
if (!this._config.enabled) {
|
|
1539
|
+
return { shouldRetry: false, modifiedParams: null };
|
|
1540
|
+
}
|
|
1541
|
+
const errorCode = classifyError(error);
|
|
1542
|
+
ctx.errorCode = errorCode;
|
|
1543
|
+
ctx.errorMessage = error.message;
|
|
1544
|
+
const fix = this._applier.getFixForError(errorCode, ctx.sessionId);
|
|
1545
|
+
if (!fix) {
|
|
1546
|
+
return { shouldRetry: false, modifiedParams: null };
|
|
1547
|
+
}
|
|
1548
|
+
if (fix.fixType === "retry") {
|
|
1549
|
+
const maxRetries = fix.config.max_retries ?? fix.config.maxRetries ?? 3;
|
|
1550
|
+
if (ctx.attempt <= maxRetries) {
|
|
1551
|
+
debug(
|
|
1552
|
+
`Retry fix ${fix.fixId}: attempt ${ctx.attempt}/${maxRetries}`
|
|
1553
|
+
);
|
|
1554
|
+
const result = {
|
|
1555
|
+
applied: true,
|
|
1556
|
+
fixId: fix.fixId,
|
|
1557
|
+
deploymentId: fix.deploymentId,
|
|
1558
|
+
fixType: "retry",
|
|
1559
|
+
modifications: { attempt: ctx.attempt }
|
|
1560
|
+
};
|
|
1561
|
+
ctx.appliedFixes.push(result);
|
|
1562
|
+
this._applier.logApplication(result);
|
|
1563
|
+
return { shouldRetry: true, modifiedParams: null };
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
if (fix.fixType === "fallback") {
|
|
1567
|
+
const { params: modifiedParams, result } = this._applier.applyFallbackFix(fix, {});
|
|
1568
|
+
if (result.applied) {
|
|
1569
|
+
ctx.appliedFixes.push(result);
|
|
1570
|
+
this._applier.logApplication(result);
|
|
1571
|
+
return { shouldRetry: true, modifiedParams };
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
return { shouldRetry: false, modifiedParams: null };
|
|
1575
|
+
} catch (e) {
|
|
1576
|
+
debug(`DefaultFixInterceptor.onError error: ${e}`);
|
|
1577
|
+
return { shouldRetry: false, modifiedParams: null };
|
|
1578
|
+
}
|
|
572
1579
|
}
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
1580
|
+
// ─── Private ────────────────────────────────────────────────────────────
|
|
1581
|
+
/** Extract text content from a response object. */
|
|
1582
|
+
_extractResponseContent(response) {
|
|
1583
|
+
if (typeof response === "string") return response;
|
|
1584
|
+
if (response && typeof response === "object") {
|
|
1585
|
+
const resp = response;
|
|
1586
|
+
const choices = resp.choices;
|
|
1587
|
+
if (Array.isArray(choices) && choices.length > 0) {
|
|
1588
|
+
const first = choices[0];
|
|
1589
|
+
const message = first?.message;
|
|
1590
|
+
if (typeof message?.content === "string") {
|
|
1591
|
+
return message.content;
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
const content = resp.content;
|
|
1595
|
+
if (typeof content === "string") return content;
|
|
1596
|
+
if (Array.isArray(content) && content.length > 0) {
|
|
1597
|
+
const first = content[0];
|
|
1598
|
+
if (typeof first?.text === "string") return first.text;
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
return null;
|
|
578
1602
|
}
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
}
|
|
587
|
-
|
|
588
|
-
return G[PREFIX + "debug"] ?? false;
|
|
589
|
-
}
|
|
590
|
-
function setDebugFlag(enabled) {
|
|
591
|
-
G[PREFIX + "debug"] = enabled;
|
|
1603
|
+
};
|
|
1604
|
+
function classifyError(error) {
|
|
1605
|
+
const haystack = `${error?.constructor?.name ?? "Error"} ${error?.message ?? ""}`;
|
|
1606
|
+
for (const rule of SUPPLEMENTAL_RULES) {
|
|
1607
|
+
if (rule.re.test(haystack)) {
|
|
1608
|
+
return CANONICAL_ERROR_CODES.has(rule.code) ? rule.code : GENERIC_FALLBACK;
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
return CANONICAL_ERROR_CODES.has(GENERIC_FALLBACK) ? GENERIC_FALLBACK : "";
|
|
592
1612
|
}
|
|
593
1613
|
|
|
594
1614
|
// src/context/storage.ts
|
|
@@ -652,16 +1672,30 @@ function getCurrentContext() {
|
|
|
652
1672
|
}
|
|
653
1673
|
|
|
654
1674
|
// src/tracer.ts
|
|
1675
|
+
function attachErrorCode(span, error) {
|
|
1676
|
+
try {
|
|
1677
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1678
|
+
const code = classifyError(err);
|
|
1679
|
+
if (code) {
|
|
1680
|
+
span.setAttribute("error.code", code);
|
|
1681
|
+
}
|
|
1682
|
+
} catch {
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
655
1685
|
var Tracer = class {
|
|
656
1686
|
_onSpanEnd;
|
|
657
1687
|
_sampleRate;
|
|
658
1688
|
_enabled;
|
|
659
1689
|
_traceContent;
|
|
1690
|
+
_serviceName;
|
|
1691
|
+
_serviceVersion;
|
|
660
1692
|
constructor(config) {
|
|
661
1693
|
this._onSpanEnd = config.onSpanEnd;
|
|
662
1694
|
this._sampleRate = config.sampleRate ?? 1;
|
|
663
1695
|
this._enabled = config.enabled ?? true;
|
|
664
|
-
this._traceContent = config.traceContent ??
|
|
1696
|
+
this._traceContent = config.traceContent ?? false;
|
|
1697
|
+
this._serviceName = config.serviceName || void 0;
|
|
1698
|
+
this._serviceVersion = config.serviceVersion || void 0;
|
|
665
1699
|
}
|
|
666
1700
|
get enabled() {
|
|
667
1701
|
return this._enabled;
|
|
@@ -695,10 +1729,16 @@ var Tracer = class {
|
|
|
695
1729
|
const phase = getCurrentPhase();
|
|
696
1730
|
const ctx = getContext();
|
|
697
1731
|
const traceId = opts.traceId ?? parentSpan?.traceId ?? ctx._rootTraceId ?? generateTraceId();
|
|
698
|
-
if (!parentSpan
|
|
699
|
-
if (
|
|
1732
|
+
if (!parentSpan) {
|
|
1733
|
+
if (ctx._traceSampled === false) {
|
|
700
1734
|
return fn(NOOP_SPAN);
|
|
701
1735
|
}
|
|
1736
|
+
if (this._sampleRate < 1 && !shouldSample(traceId, this._sampleRate)) {
|
|
1737
|
+
return runWithContext(
|
|
1738
|
+
{ _traceSampled: false },
|
|
1739
|
+
() => fn(NOOP_SPAN)
|
|
1740
|
+
);
|
|
1741
|
+
}
|
|
702
1742
|
}
|
|
703
1743
|
const parentSpanId = opts.parentSpanId ?? parentSpan?.spanId;
|
|
704
1744
|
const spanOptions = {
|
|
@@ -711,7 +1751,12 @@ var Tracer = class {
|
|
|
711
1751
|
// Propagate context fields as attributes (matching Python SDK tracer.py:497-511)
|
|
712
1752
|
...agent2?.agentRole ? { "agent.role": agent2.agentRole } : {},
|
|
713
1753
|
...agent2?.parentAgentId ? { "parent_agent_id": agent2.parentAgentId } : {},
|
|
714
|
-
...session2?.userId ? { "session.user_id": session2.userId } : {}
|
|
1754
|
+
...session2?.userId ? { "session.user_id": session2.userId } : {},
|
|
1755
|
+
// F-SDKJSSVCNAME-001 — `service.name` is suppressed when an agent
|
|
1756
|
+
// identity is present (the agent takes priority), matching Python;
|
|
1757
|
+
// `service.version` never is.
|
|
1758
|
+
...this._serviceName && !agent2 ? { "service.name": this._serviceName } : {},
|
|
1759
|
+
...this._serviceVersion ? { "service.version": this._serviceVersion } : {}
|
|
715
1760
|
},
|
|
716
1761
|
sessionId: session2?.sessionId,
|
|
717
1762
|
agentId: agent2?.agentId,
|
|
@@ -730,6 +1775,7 @@ var Tracer = class {
|
|
|
730
1775
|
},
|
|
731
1776
|
(error) => {
|
|
732
1777
|
span.recordException(error instanceof Error ? error : String(error));
|
|
1778
|
+
attachErrorCode(span, error);
|
|
733
1779
|
span.end();
|
|
734
1780
|
throw error;
|
|
735
1781
|
}
|
|
@@ -739,6 +1785,7 @@ var Tracer = class {
|
|
|
739
1785
|
return result;
|
|
740
1786
|
} catch (error) {
|
|
741
1787
|
span.recordException(error instanceof Error ? error : String(error));
|
|
1788
|
+
attachErrorCode(span, error);
|
|
742
1789
|
span.end();
|
|
743
1790
|
throw error;
|
|
744
1791
|
}
|
|
@@ -759,8 +1806,11 @@ var Tracer = class {
|
|
|
759
1806
|
const agent2 = getCurrentAgent();
|
|
760
1807
|
const phase = getCurrentPhase();
|
|
761
1808
|
const traceId = opts.traceId ?? parentSpan?.traceId ?? generateTraceId();
|
|
762
|
-
if (!parentSpan
|
|
763
|
-
if (
|
|
1809
|
+
if (!parentSpan) {
|
|
1810
|
+
if (getContext()._traceSampled === false) {
|
|
1811
|
+
return NOOP_SPAN;
|
|
1812
|
+
}
|
|
1813
|
+
if (this._sampleRate < 1 && !shouldSample(traceId, this._sampleRate)) {
|
|
764
1814
|
return NOOP_SPAN;
|
|
765
1815
|
}
|
|
766
1816
|
}
|
|
@@ -776,7 +1826,10 @@ var Tracer = class {
|
|
|
776
1826
|
// Propagate context fields as attributes (matching Python SDK tracer.py:497-511)
|
|
777
1827
|
...agent2?.agentRole ? { "agent.role": agent2.agentRole } : {},
|
|
778
1828
|
...agent2?.parentAgentId ? { "parent_agent_id": agent2.parentAgentId } : {},
|
|
779
|
-
...session2?.userId ? { "session.user_id": session2.userId } : {}
|
|
1829
|
+
...session2?.userId ? { "session.user_id": session2.userId } : {},
|
|
1830
|
+
// F-SDKJSSVCNAME-001 — see the sibling site above.
|
|
1831
|
+
...this._serviceName && !agent2 ? { "service.name": this._serviceName } : {},
|
|
1832
|
+
...this._serviceVersion ? { "service.version": this._serviceVersion } : {}
|
|
780
1833
|
},
|
|
781
1834
|
sessionId: session2?.sessionId,
|
|
782
1835
|
agentId: agent2?.agentId,
|
|
@@ -789,182 +1842,14 @@ var Tracer = class {
|
|
|
789
1842
|
}
|
|
790
1843
|
};
|
|
791
1844
|
|
|
792
|
-
// src/utils/log.ts
|
|
793
|
-
function setDebug(enabled) {
|
|
794
|
-
setDebugFlag(enabled);
|
|
795
|
-
}
|
|
796
|
-
function debug(msg) {
|
|
797
|
-
if (getDebug()) {
|
|
798
|
-
process.stderr.write(`[risicare] ${msg}
|
|
799
|
-
`);
|
|
800
|
-
}
|
|
801
|
-
}
|
|
802
|
-
function warn(msg) {
|
|
803
|
-
process.stderr.write(`[risicare] WARNING: ${msg}
|
|
804
|
-
`);
|
|
805
|
-
}
|
|
806
|
-
|
|
807
|
-
// src/exporters/batch.ts
|
|
808
|
-
var BatchSpanProcessor = class _BatchSpanProcessor {
|
|
809
|
-
_exporters;
|
|
810
|
-
_batchSize;
|
|
811
|
-
_batchTimeoutMs;
|
|
812
|
-
_maxQueueSize;
|
|
813
|
-
_debug;
|
|
814
|
-
_queue = [];
|
|
815
|
-
_timer = null;
|
|
816
|
-
_started = false;
|
|
817
|
-
_flushing = false;
|
|
818
|
-
_beforeExitHandler = null;
|
|
819
|
-
// Retry tracking for failed batches (Audit #5)
|
|
820
|
-
_retryCounts = /* @__PURE__ */ new Map();
|
|
821
|
-
static MAX_RETRIES = 3;
|
|
822
|
-
// Metrics
|
|
823
|
-
droppedSpans = 0;
|
|
824
|
-
exportedSpans = 0;
|
|
825
|
-
failedExports = 0;
|
|
826
|
-
constructor(options) {
|
|
827
|
-
this._exporters = [...options.exporters];
|
|
828
|
-
const requestedBatchSize = options.batchSize ?? 100;
|
|
829
|
-
const clampedBatchSize = Math.max(1, Math.min(requestedBatchSize, 1e4));
|
|
830
|
-
if (clampedBatchSize !== requestedBatchSize) {
|
|
831
|
-
warn(
|
|
832
|
-
`batchSize=${requestedBatchSize} is outside the allowed range [1, 10000]; clamping to ${clampedBatchSize}`
|
|
833
|
-
);
|
|
834
|
-
}
|
|
835
|
-
this._batchSize = clampedBatchSize;
|
|
836
|
-
this._batchTimeoutMs = options.batchTimeoutMs ?? 1e3;
|
|
837
|
-
this._maxQueueSize = options.maxQueueSize ?? 1e4;
|
|
838
|
-
this._debug = options.debug ?? false;
|
|
839
|
-
}
|
|
840
|
-
start() {
|
|
841
|
-
if (this._started) return;
|
|
842
|
-
this._started = true;
|
|
843
|
-
this._timer = setInterval(() => {
|
|
844
|
-
void this._exportBatch();
|
|
845
|
-
}, this._batchTimeoutMs);
|
|
846
|
-
this._timer.unref();
|
|
847
|
-
this._beforeExitHandler = () => {
|
|
848
|
-
void this.shutdown();
|
|
849
|
-
};
|
|
850
|
-
process.once("beforeExit", this._beforeExitHandler);
|
|
851
|
-
}
|
|
852
|
-
async shutdown(timeoutMs = 5e3) {
|
|
853
|
-
if (!this._started) return;
|
|
854
|
-
this._started = false;
|
|
855
|
-
if (this._timer) {
|
|
856
|
-
clearInterval(this._timer);
|
|
857
|
-
this._timer = null;
|
|
858
|
-
}
|
|
859
|
-
if (this._beforeExitHandler) {
|
|
860
|
-
process.removeListener("beforeExit", this._beforeExitHandler);
|
|
861
|
-
this._beforeExitHandler = null;
|
|
862
|
-
}
|
|
863
|
-
const flushPromise = this._exportBatch();
|
|
864
|
-
const timeoutPromise = new Promise((resolve) => setTimeout(resolve, timeoutMs));
|
|
865
|
-
await Promise.race([flushPromise, timeoutPromise]);
|
|
866
|
-
for (const exporter of this._exporters) {
|
|
867
|
-
try {
|
|
868
|
-
await exporter.shutdown();
|
|
869
|
-
} catch (e) {
|
|
870
|
-
debug(`Error shutting down ${exporter.name}: ${e}`);
|
|
871
|
-
}
|
|
872
|
-
}
|
|
873
|
-
this._retryCounts.clear();
|
|
874
|
-
debug(
|
|
875
|
-
`BatchSpanProcessor shutdown. Exported: ${this.exportedSpans}, Dropped: ${this.droppedSpans}, Failed: ${this.failedExports}`
|
|
876
|
-
);
|
|
877
|
-
}
|
|
878
|
-
onSpanEnd(span) {
|
|
879
|
-
if (!this._started) return;
|
|
880
|
-
if (this._queue.length >= this._maxQueueSize) {
|
|
881
|
-
this.droppedSpans++;
|
|
882
|
-
if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
|
|
883
|
-
warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
|
|
884
|
-
}
|
|
885
|
-
return;
|
|
886
|
-
}
|
|
887
|
-
this._queue.push(span);
|
|
888
|
-
if (this._queue.length >= this._batchSize) {
|
|
889
|
-
void this._exportBatch();
|
|
890
|
-
}
|
|
891
|
-
}
|
|
892
|
-
async flush(timeoutMs = 5e3) {
|
|
893
|
-
if (!this._started) return true;
|
|
894
|
-
const start = Date.now();
|
|
895
|
-
while (this._queue.length > 0 || this._flushing) {
|
|
896
|
-
if (!this._flushing && this._queue.length > 0) {
|
|
897
|
-
await this._exportBatch();
|
|
898
|
-
} else {
|
|
899
|
-
await new Promise((r) => setTimeout(r, 1));
|
|
900
|
-
}
|
|
901
|
-
if (Date.now() - start > timeoutMs) return false;
|
|
902
|
-
}
|
|
903
|
-
return true;
|
|
904
|
-
}
|
|
905
|
-
getMetrics() {
|
|
906
|
-
return {
|
|
907
|
-
exportedSpans: this.exportedSpans,
|
|
908
|
-
droppedSpans: this.droppedSpans,
|
|
909
|
-
failedExports: this.failedExports,
|
|
910
|
-
queueSize: this._queue.length,
|
|
911
|
-
queueCapacity: this._maxQueueSize,
|
|
912
|
-
queueUtilization: this._queue.length / this._maxQueueSize
|
|
913
|
-
};
|
|
914
|
-
}
|
|
915
|
-
async _exportBatch() {
|
|
916
|
-
if (this._flushing || this._queue.length === 0) return;
|
|
917
|
-
this._flushing = true;
|
|
918
|
-
try {
|
|
919
|
-
const batch = this._queue.splice(0, this._batchSize);
|
|
920
|
-
if (batch.length === 0) return;
|
|
921
|
-
debug(`Exporting batch of ${batch.length} spans`);
|
|
922
|
-
let batchExported = false;
|
|
923
|
-
for (const exporter of this._exporters) {
|
|
924
|
-
try {
|
|
925
|
-
const result = await exporter.export(batch);
|
|
926
|
-
if (result === "success" /* SUCCESS */) {
|
|
927
|
-
if (!batchExported) {
|
|
928
|
-
this.exportedSpans += batch.length;
|
|
929
|
-
batchExported = true;
|
|
930
|
-
for (const span of batch) {
|
|
931
|
-
this._retryCounts.delete(span.spanId);
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
} else {
|
|
935
|
-
this.failedExports++;
|
|
936
|
-
}
|
|
937
|
-
} catch (e) {
|
|
938
|
-
this.failedExports++;
|
|
939
|
-
debug(`Export to ${exporter.name} failed: ${e}`);
|
|
940
|
-
}
|
|
941
|
-
}
|
|
942
|
-
if (!batchExported) {
|
|
943
|
-
const retryable = batch.filter((span) => {
|
|
944
|
-
const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;
|
|
945
|
-
if (count > _BatchSpanProcessor.MAX_RETRIES) {
|
|
946
|
-
this._retryCounts.delete(span.spanId);
|
|
947
|
-
this.droppedSpans++;
|
|
948
|
-
return false;
|
|
949
|
-
}
|
|
950
|
-
this._retryCounts.set(span.spanId, count);
|
|
951
|
-
return true;
|
|
952
|
-
});
|
|
953
|
-
if (retryable.length > 0) {
|
|
954
|
-
this._queue.unshift(...retryable);
|
|
955
|
-
debug(`Re-queued ${retryable.length} spans for retry (${batch.length - retryable.length} dropped after max retries)`);
|
|
956
|
-
}
|
|
957
|
-
}
|
|
958
|
-
} finally {
|
|
959
|
-
this._flushing = false;
|
|
960
|
-
}
|
|
961
|
-
}
|
|
962
|
-
};
|
|
963
|
-
|
|
964
1845
|
// src/version.ts
|
|
965
|
-
var SDK_VERSION = "0.
|
|
1846
|
+
var SDK_VERSION = "0.5.2";
|
|
966
1847
|
|
|
967
1848
|
// src/exporters/http.ts
|
|
1849
|
+
var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
|
|
1850
|
+
var RETRY_AFTER_CEILING_MS = 1e4;
|
|
1851
|
+
var REFUSAL_BACKOFF_BASE_MS = 1e3;
|
|
1852
|
+
var REFUSAL_NO_HINT = -1;
|
|
968
1853
|
var HttpExporter = class {
|
|
969
1854
|
name = "http";
|
|
970
1855
|
_endpoint;
|
|
@@ -980,6 +1865,18 @@ var HttpExporter = class {
|
|
|
980
1865
|
// cooldown gives the gateway time to come back before the half-open
|
|
981
1866
|
// probe fires. Lower numbers (was 3@30s) tripped on transient blips.
|
|
982
1867
|
_consecutiveFailures = 0;
|
|
1868
|
+
/**
|
|
1869
|
+
* F-SDK503-001. Set by `_sendRequest` when a response is a CAPACITY REFUSAL, read by the
|
|
1870
|
+
* retry loop and the breaker. `null` = not a refusal; `REFUSAL_NO_HINT` = refused with no
|
|
1871
|
+
* `Retry-After`; otherwise the honoured delay in ms.
|
|
1872
|
+
*
|
|
1873
|
+
* ⚠ Node has ONE thread and `export()` is `async`, so two concurrent exports interleave on
|
|
1874
|
+
* this field at every `await`. It is written immediately after the awaited `fetch` resolves
|
|
1875
|
+
* and read on the very next statement, with no `await` between — so the value cannot be
|
|
1876
|
+
* clobbered mid-decision. The Python twin carries the same per-call state on `self` for the
|
|
1877
|
+
* same reason (its `_send_request` signature is pin-locked).
|
|
1878
|
+
*/
|
|
1879
|
+
_lastRefusalAfterMs = null;
|
|
983
1880
|
_circuitOpenUntil = 0;
|
|
984
1881
|
_circuitBreakerThreshold = 5;
|
|
985
1882
|
_circuitBreakerCooldownMs = 6e4;
|
|
@@ -1009,15 +1906,26 @@ var HttpExporter = class {
|
|
|
1009
1906
|
if (this._environment) body.environment = this._environment;
|
|
1010
1907
|
const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
|
|
1011
1908
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1909
|
+
this._lastRefusalAfterMs = null;
|
|
1012
1910
|
const result = await this._sendRequest(body);
|
|
1013
1911
|
if (result === "success" /* SUCCESS */) {
|
|
1014
1912
|
this._consecutiveFailures = 0;
|
|
1015
1913
|
return result;
|
|
1016
1914
|
}
|
|
1017
1915
|
if (attempt < maxAttempts - 1) {
|
|
1018
|
-
|
|
1916
|
+
const refusal = this._lastRefusalAfterMs;
|
|
1917
|
+
const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
|
|
1918
|
+
await sleep(delay);
|
|
1019
1919
|
}
|
|
1020
1920
|
}
|
|
1921
|
+
const refusedForCapacity = this._lastRefusalAfterMs !== null;
|
|
1922
|
+
this._lastRefusalAfterMs = null;
|
|
1923
|
+
if (refusedForCapacity) {
|
|
1924
|
+
warn(
|
|
1925
|
+
`Risicare: the ingest endpoint refused this batch for capacity (HTTP 429/503) after ${maxAttempts} attempt(s). This is a healthy server shedding load, not an outage \u2014 the batch is dropped but the exporter keeps sending. Reduce batch size or export rate if it persists.`
|
|
1926
|
+
);
|
|
1927
|
+
return "failure" /* FAILURE */;
|
|
1928
|
+
}
|
|
1021
1929
|
this._consecutiveFailures++;
|
|
1022
1930
|
if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
|
|
1023
1931
|
this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
|
|
@@ -1027,6 +1935,26 @@ var HttpExporter = class {
|
|
|
1027
1935
|
}
|
|
1028
1936
|
return "failure" /* FAILURE */;
|
|
1029
1937
|
}
|
|
1938
|
+
/**
|
|
1939
|
+
* Record a CAPACITY REFUSAL for the retry loop. Returns true if it was one.
|
|
1940
|
+
*
|
|
1941
|
+
* `Retry-After` is honoured only in its delta-seconds form (RFC 9110 §10.2.3 also permits an
|
|
1942
|
+
* HTTP-date); anything else falls back to our own backoff rather than guessing at a date
|
|
1943
|
+
* parse.
|
|
1944
|
+
*/
|
|
1945
|
+
_noteRefusal(status, retryAfterRaw) {
|
|
1946
|
+
if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
|
|
1947
|
+
let delay = REFUSAL_NO_HINT;
|
|
1948
|
+
if (retryAfterRaw) {
|
|
1949
|
+
const secs = Number(retryAfterRaw);
|
|
1950
|
+
if (Number.isFinite(secs) && secs >= 0) {
|
|
1951
|
+
delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
this._lastRefusalAfterMs = delay;
|
|
1955
|
+
debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${retryAfterRaw})`);
|
|
1956
|
+
return true;
|
|
1957
|
+
}
|
|
1030
1958
|
async _sendRequest(body) {
|
|
1031
1959
|
const url = `${this._endpoint}/v1/spans`;
|
|
1032
1960
|
const headers = {
|
|
@@ -1057,11 +1985,12 @@ var HttpExporter = class {
|
|
|
1057
1985
|
});
|
|
1058
1986
|
clearTimeout(timeoutId);
|
|
1059
1987
|
if (response.status < 300) {
|
|
1060
|
-
return
|
|
1988
|
+
return await checkAck(response);
|
|
1061
1989
|
} else if (response.status === 408 || response.status === 504) {
|
|
1062
1990
|
debug(`HTTP export timeout: ${response.status}`);
|
|
1063
1991
|
return "timeout" /* TIMEOUT */;
|
|
1064
1992
|
}
|
|
1993
|
+
this._noteRefusal(response.status, response.headers.get("Retry-After"));
|
|
1065
1994
|
debug(`HTTP export failed: ${response.status}`);
|
|
1066
1995
|
return "failure" /* FAILURE */;
|
|
1067
1996
|
} catch (e) {
|
|
@@ -1071,9 +2000,42 @@ var HttpExporter = class {
|
|
|
1071
2000
|
}
|
|
1072
2001
|
shutdown() {
|
|
1073
2002
|
}
|
|
1074
|
-
};
|
|
1075
|
-
function sleep(ms) {
|
|
1076
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2003
|
+
};
|
|
2004
|
+
function sleep(ms) {
|
|
2005
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2006
|
+
}
|
|
2007
|
+
function asCount(v) {
|
|
2008
|
+
return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
|
|
2009
|
+
}
|
|
2010
|
+
async function checkAck(response) {
|
|
2011
|
+
let payload;
|
|
2012
|
+
try {
|
|
2013
|
+
payload = await response.json();
|
|
2014
|
+
} catch {
|
|
2015
|
+
return "success" /* SUCCESS */;
|
|
2016
|
+
}
|
|
2017
|
+
if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
|
|
2018
|
+
return "success" /* SUCCESS */;
|
|
2019
|
+
}
|
|
2020
|
+
const body = payload;
|
|
2021
|
+
const accepted = asCount(body.accepted);
|
|
2022
|
+
const rejected = asCount(body.rejected);
|
|
2023
|
+
if (accepted === void 0 || rejected === void 0 || rejected <= 0) {
|
|
2024
|
+
return "success" /* SUCCESS */;
|
|
2025
|
+
}
|
|
2026
|
+
const errors = body.errors;
|
|
2027
|
+
const detail = typeof body.errorMessage === "string" && body.errorMessage || typeof body.error_message === "string" && body.error_message || (Array.isArray(errors) && errors.length > 0 ? JSON.stringify(errors[0]) : "") || "No reason was returned.";
|
|
2028
|
+
const total = accepted + rejected;
|
|
2029
|
+
if (accepted === 0) {
|
|
2030
|
+
warn(
|
|
2031
|
+
`Risicare: the backend accepted 0 of ${total} span(s) and rejected ${rejected} \u2014 this batch was NOT stored. ${detail}`
|
|
2032
|
+
);
|
|
2033
|
+
return "failure" /* FAILURE */;
|
|
2034
|
+
}
|
|
2035
|
+
warn(
|
|
2036
|
+
`Risicare: the backend rejected ${rejected} of ${total} span(s); the remaining ${accepted} were stored. Those ${rejected} are permanently lost and are NOT retried. ${detail}`
|
|
2037
|
+
);
|
|
2038
|
+
return "success" /* SUCCESS */;
|
|
1077
2039
|
}
|
|
1078
2040
|
|
|
1079
2041
|
// src/exporters/console.ts
|
|
@@ -1092,51 +2054,6 @@ var ConsoleExporter = class {
|
|
|
1092
2054
|
}
|
|
1093
2055
|
};
|
|
1094
2056
|
|
|
1095
|
-
// src/runtime/config.ts
|
|
1096
|
-
function resolveFixRuntimeConfig(config) {
|
|
1097
|
-
return {
|
|
1098
|
-
apiEndpoint: config.apiEndpoint,
|
|
1099
|
-
apiKey: config.apiKey,
|
|
1100
|
-
enabled: config.enabled ?? true,
|
|
1101
|
-
cacheEnabled: config.cacheEnabled ?? true,
|
|
1102
|
-
cacheTtlMs: config.cacheTtlMs ?? 3e5,
|
|
1103
|
-
cacheMaxEntries: config.cacheMaxEntries ?? 1e3,
|
|
1104
|
-
autoRefresh: config.autoRefresh ?? true,
|
|
1105
|
-
refreshIntervalMs: config.refreshIntervalMs ?? 6e4,
|
|
1106
|
-
dryRun: config.dryRun ?? false,
|
|
1107
|
-
abTestingEnabled: config.abTestingEnabled ?? true,
|
|
1108
|
-
timeoutMs: config.timeoutMs ?? 1e3,
|
|
1109
|
-
debug: config.debug ?? false
|
|
1110
|
-
};
|
|
1111
|
-
}
|
|
1112
|
-
function matchesError(fix, errorCode) {
|
|
1113
|
-
if (fix.errorCode === errorCode) {
|
|
1114
|
-
return true;
|
|
1115
|
-
}
|
|
1116
|
-
if (fix.errorCode.endsWith("*")) {
|
|
1117
|
-
const prefix = fix.errorCode.slice(0, -1);
|
|
1118
|
-
return errorCode.startsWith(prefix);
|
|
1119
|
-
}
|
|
1120
|
-
return false;
|
|
1121
|
-
}
|
|
1122
|
-
function shouldApply(fix, sessionHash) {
|
|
1123
|
-
if (fix.trafficPercentage >= 100) return true;
|
|
1124
|
-
if (fix.trafficPercentage <= 0) return false;
|
|
1125
|
-
const bucket = sessionHash % 100;
|
|
1126
|
-
return bucket < fix.trafficPercentage;
|
|
1127
|
-
}
|
|
1128
|
-
function activeFixFromApiResponse(item) {
|
|
1129
|
-
return {
|
|
1130
|
-
fixId: item.id ?? item.fix_id ?? item.fixId ?? "",
|
|
1131
|
-
deploymentId: item.deployment_id ?? item.deploymentId ?? "",
|
|
1132
|
-
errorCode: item.error_code ?? item.errorCode ?? "",
|
|
1133
|
-
fixType: item.fix_type ?? item.fixType ?? "prompt",
|
|
1134
|
-
config: item.config ?? {},
|
|
1135
|
-
trafficPercentage: item.traffic_percentage ?? item.trafficPercentage ?? 100,
|
|
1136
|
-
version: item.version ?? 1
|
|
1137
|
-
};
|
|
1138
|
-
}
|
|
1139
|
-
|
|
1140
2057
|
// src/runtime/cache.ts
|
|
1141
2058
|
var FixCache = class {
|
|
1142
2059
|
_ttlMs;
|
|
@@ -1626,520 +2543,279 @@ var FixApplier = class {
|
|
|
1626
2543
|
content,
|
|
1627
2544
|
passed: false,
|
|
1628
2545
|
result: {
|
|
1629
|
-
applied: true,
|
|
1630
|
-
fixId: fix.fixId,
|
|
1631
|
-
fixType: "guard",
|
|
1632
|
-
modifications: { passed: false, reason: "guard_exception" },
|
|
1633
|
-
error: String(e),
|
|
1634
|
-
reason: "guard_exception"
|
|
1635
|
-
}
|
|
1636
|
-
};
|
|
1637
|
-
}
|
|
1638
|
-
}
|
|
1639
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
1640
|
-
// Application Log
|
|
1641
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
1642
|
-
/** Log a fix application result. */
|
|
1643
|
-
logApplication(result) {
|
|
1644
|
-
this._applicationLog.push(result);
|
|
1645
|
-
if (this._applicationLog.length > 1e3) {
|
|
1646
|
-
this._applicationLog = this._applicationLog.slice(-500);
|
|
1647
|
-
}
|
|
1648
|
-
}
|
|
1649
|
-
/** Get the application log. */
|
|
1650
|
-
getApplicationLog() {
|
|
1651
|
-
return [...this._applicationLog];
|
|
1652
|
-
}
|
|
1653
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
1654
|
-
// Private Helpers
|
|
1655
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
1656
|
-
/**
|
|
1657
|
-
* Safely compile a regex pattern from untrusted input.
|
|
1658
|
-
* Returns null if invalid or too long.
|
|
1659
|
-
*/
|
|
1660
|
-
_safeCompileRegex(pattern, maxLength = 500) {
|
|
1661
|
-
if (!pattern || pattern.length > maxLength) return null;
|
|
1662
|
-
try {
|
|
1663
|
-
return new RegExp(pattern, "i");
|
|
1664
|
-
} catch {
|
|
1665
|
-
debug(`Invalid regex pattern (length=${pattern.length})`);
|
|
1666
|
-
return null;
|
|
1667
|
-
}
|
|
1668
|
-
}
|
|
1669
|
-
/** Prepend content to the first message matching the target role. */
|
|
1670
|
-
_prependToTarget(messages, target, content) {
|
|
1671
|
-
return messages.map((msg) => {
|
|
1672
|
-
if (msg.role === target) {
|
|
1673
|
-
return {
|
|
1674
|
-
...msg,
|
|
1675
|
-
content: content + "\n\n" + (msg.content ?? "")
|
|
1676
|
-
};
|
|
1677
|
-
}
|
|
1678
|
-
return msg;
|
|
1679
|
-
});
|
|
1680
|
-
}
|
|
1681
|
-
/** Append content to the first message matching the target role. */
|
|
1682
|
-
_appendToTarget(messages, target, content) {
|
|
1683
|
-
return messages.map((msg) => {
|
|
1684
|
-
if (msg.role === target) {
|
|
1685
|
-
return {
|
|
1686
|
-
...msg,
|
|
1687
|
-
content: (msg.content ?? "") + "\n\n" + content
|
|
1688
|
-
};
|
|
1689
|
-
}
|
|
1690
|
-
return msg;
|
|
1691
|
-
});
|
|
1692
|
-
}
|
|
1693
|
-
/** Regex replace across all messages. */
|
|
1694
|
-
_replaceInMessages(messages, pattern, replacement) {
|
|
1695
|
-
const regex = this._safeCompileRegex(pattern);
|
|
1696
|
-
if (!regex) {
|
|
1697
|
-
debug("Skipping invalid regex pattern in prompt fix");
|
|
1698
|
-
return messages;
|
|
1699
|
-
}
|
|
1700
|
-
return messages.map((msg) => {
|
|
1701
|
-
const msgContent = msg.content;
|
|
1702
|
-
if (typeof msgContent === "string") {
|
|
1703
|
-
return { ...msg, content: msgContent.replace(regex, replacement) };
|
|
1704
|
-
}
|
|
1705
|
-
return msg;
|
|
1706
|
-
});
|
|
1707
|
-
}
|
|
1708
|
-
/** Add few-shot examples after the first system message. */
|
|
1709
|
-
_addFewShotExamples(messages, examples) {
|
|
1710
|
-
const result = [];
|
|
1711
|
-
let systemFound = false;
|
|
1712
|
-
for (const msg of messages) {
|
|
1713
|
-
result.push(msg);
|
|
1714
|
-
if (msg.role === "system" && !systemFound) {
|
|
1715
|
-
systemFound = true;
|
|
1716
|
-
for (const example of examples) {
|
|
1717
|
-
if (example.user) {
|
|
1718
|
-
result.push({ role: "user", content: example.user });
|
|
1719
|
-
}
|
|
1720
|
-
if (example.assistant) {
|
|
1721
|
-
result.push({ role: "assistant", content: example.assistant });
|
|
1722
|
-
}
|
|
1723
|
-
}
|
|
1724
|
-
}
|
|
1725
|
-
}
|
|
1726
|
-
return result;
|
|
1727
|
-
}
|
|
1728
|
-
};
|
|
1729
|
-
|
|
1730
|
-
// src/runtime/loader.ts
|
|
1731
|
-
var FixLoader = class _FixLoader {
|
|
1732
|
-
_config;
|
|
1733
|
-
_cache;
|
|
1734
|
-
_refreshTimer = null;
|
|
1735
|
-
_lastLoadTime = null;
|
|
1736
|
-
_consecutiveFailures = 0;
|
|
1737
|
-
_circuitOpenUntil = 0;
|
|
1738
|
-
_onLoadCallbacks = [];
|
|
1739
|
-
// Circuit breaker settings
|
|
1740
|
-
static CIRCUIT_BREAKER_THRESHOLD = 3;
|
|
1741
|
-
static CIRCUIT_BREAKER_COOLDOWN_MS = 3e4;
|
|
1742
|
-
constructor(config, cache) {
|
|
1743
|
-
this._config = resolveFixRuntimeConfig(config);
|
|
1744
|
-
this._cache = cache;
|
|
1745
|
-
}
|
|
1746
|
-
/** Timestamp of last successful load. */
|
|
1747
|
-
get lastLoadTime() {
|
|
1748
|
-
return this._lastLoadTime;
|
|
1749
|
-
}
|
|
1750
|
-
/**
|
|
1751
|
-
* Start the loader: perform initial load and start background refresh.
|
|
1752
|
-
*
|
|
1753
|
-
* Never throws — failures are logged and the runtime degrades gracefully.
|
|
1754
|
-
*/
|
|
1755
|
-
start() {
|
|
1756
|
-
try {
|
|
1757
|
-
if (!this._config.enabled) {
|
|
1758
|
-
debug("Fix runtime disabled, skipping loader start");
|
|
1759
|
-
return;
|
|
1760
|
-
}
|
|
1761
|
-
if (!this._config.apiKey) {
|
|
1762
|
-
warn("No API key configured, fixes will not be loaded");
|
|
1763
|
-
return;
|
|
1764
|
-
}
|
|
1765
|
-
this.loadSync().catch((e) => {
|
|
1766
|
-
debug(`Initial fix load failed: ${e}`);
|
|
1767
|
-
});
|
|
1768
|
-
if (this._config.autoRefresh) {
|
|
1769
|
-
this._startRefreshInterval();
|
|
1770
|
-
}
|
|
1771
|
-
} catch (e) {
|
|
1772
|
-
debug(`FixLoader.start error: ${e}`);
|
|
1773
|
-
}
|
|
1774
|
-
}
|
|
1775
|
-
/** Stop the loader: clear the refresh interval. */
|
|
1776
|
-
stop() {
|
|
1777
|
-
try {
|
|
1778
|
-
if (this._refreshTimer !== null) {
|
|
1779
|
-
clearInterval(this._refreshTimer);
|
|
1780
|
-
this._refreshTimer = null;
|
|
1781
|
-
}
|
|
1782
|
-
} catch (e) {
|
|
1783
|
-
debug(`FixLoader.stop error: ${e}`);
|
|
1784
|
-
}
|
|
1785
|
-
}
|
|
1786
|
-
/**
|
|
1787
|
-
* Register a callback invoked after each successful load.
|
|
1788
|
-
*/
|
|
1789
|
-
onLoad(callback) {
|
|
1790
|
-
this._onLoadCallbacks.push(callback);
|
|
1791
|
-
}
|
|
1792
|
-
/**
|
|
1793
|
-
* Load fixes from the API.
|
|
1794
|
-
*
|
|
1795
|
-
* Name kept as "loadSync" for parity with the Python SDK, but this
|
|
1796
|
-
* returns a Promise in JS (there's no synchronous fetch in Node.js).
|
|
1797
|
-
*/
|
|
1798
|
-
async loadSync() {
|
|
1799
|
-
if (!this._config.apiKey) {
|
|
1800
|
-
return [];
|
|
1801
|
-
}
|
|
1802
|
-
const now = Date.now();
|
|
1803
|
-
if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && now < this._circuitOpenUntil) {
|
|
1804
|
-
debug("Fix loader circuit breaker open \u2014 skipping load");
|
|
1805
|
-
return this._cache.getAll();
|
|
1806
|
-
}
|
|
1807
|
-
try {
|
|
1808
|
-
const endpoint = this._config.apiEndpoint.replace(/\/+$/, "");
|
|
1809
|
-
const url = `${endpoint}/api/v1/fixes/active`;
|
|
1810
|
-
const controller = new AbortController();
|
|
1811
|
-
const timeoutId = setTimeout(
|
|
1812
|
-
() => controller.abort(),
|
|
1813
|
-
this._config.timeoutMs
|
|
1814
|
-
);
|
|
1815
|
-
const response = await fetch(url, {
|
|
1816
|
-
method: "GET",
|
|
1817
|
-
headers: {
|
|
1818
|
-
"Authorization": `Bearer ${this._config.apiKey}`,
|
|
1819
|
-
"Content-Type": "application/json",
|
|
1820
|
-
"X-Risicare-SDK-Version": SDK_VERSION
|
|
1821
|
-
},
|
|
1822
|
-
signal: controller.signal
|
|
1823
|
-
});
|
|
1824
|
-
clearTimeout(timeoutId);
|
|
1825
|
-
if (!response.ok) {
|
|
1826
|
-
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
1827
|
-
}
|
|
1828
|
-
const data = await response.json();
|
|
1829
|
-
const fixes = this._parseResponse(data);
|
|
1830
|
-
this._onLoadSuccess(fixes);
|
|
1831
|
-
return fixes;
|
|
1832
|
-
} catch (e) {
|
|
1833
|
-
this._onLoadFailure(e);
|
|
1834
|
-
throw e;
|
|
2546
|
+
applied: true,
|
|
2547
|
+
fixId: fix.fixId,
|
|
2548
|
+
fixType: "guard",
|
|
2549
|
+
modifications: { passed: false, reason: "guard_exception" },
|
|
2550
|
+
error: String(e),
|
|
2551
|
+
reason: "guard_exception"
|
|
2552
|
+
}
|
|
2553
|
+
};
|
|
1835
2554
|
}
|
|
1836
2555
|
}
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
2556
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2557
|
+
// Application Log
|
|
2558
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2559
|
+
/** Log a fix application result. */
|
|
2560
|
+
logApplication(result) {
|
|
2561
|
+
this._applicationLog.push(result);
|
|
2562
|
+
if (this._applicationLog.length > 1e3) {
|
|
2563
|
+
this._applicationLog = this._applicationLog.slice(-500);
|
|
2564
|
+
}
|
|
1840
2565
|
}
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
2566
|
+
/** Get the application log. */
|
|
2567
|
+
getApplicationLog() {
|
|
2568
|
+
return [...this._applicationLog];
|
|
2569
|
+
}
|
|
2570
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2571
|
+
// Private Helpers
|
|
2572
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
2573
|
+
/**
|
|
2574
|
+
* Safely compile a regex pattern from untrusted input.
|
|
2575
|
+
* Returns null if invalid or too long.
|
|
2576
|
+
*/
|
|
2577
|
+
_safeCompileRegex(pattern, maxLength = 500) {
|
|
2578
|
+
if (!pattern || pattern.length > maxLength) return null;
|
|
2579
|
+
try {
|
|
2580
|
+
return new RegExp(pattern, "i");
|
|
2581
|
+
} catch {
|
|
2582
|
+
debug(`Invalid regex pattern (length=${pattern.length})`);
|
|
2583
|
+
return null;
|
|
1854
2584
|
}
|
|
1855
|
-
return fixes;
|
|
1856
2585
|
}
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
debug(`Load callback error: ${e}`);
|
|
2586
|
+
/** Prepend content to the first message matching the target role. */
|
|
2587
|
+
_prependToTarget(messages, target, content) {
|
|
2588
|
+
return messages.map((msg) => {
|
|
2589
|
+
if (msg.role === target) {
|
|
2590
|
+
return {
|
|
2591
|
+
...msg,
|
|
2592
|
+
content: content + "\n\n" + (msg.content ?? "")
|
|
2593
|
+
};
|
|
1866
2594
|
}
|
|
1867
|
-
|
|
1868
|
-
|
|
2595
|
+
return msg;
|
|
2596
|
+
});
|
|
1869
2597
|
}
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
2598
|
+
/** Append content to the first message matching the target role. */
|
|
2599
|
+
_appendToTarget(messages, target, content) {
|
|
2600
|
+
return messages.map((msg) => {
|
|
2601
|
+
if (msg.role === target) {
|
|
2602
|
+
return {
|
|
2603
|
+
...msg,
|
|
2604
|
+
content: (msg.content ?? "") + "\n\n" + content
|
|
2605
|
+
};
|
|
2606
|
+
}
|
|
2607
|
+
return msg;
|
|
2608
|
+
});
|
|
2609
|
+
}
|
|
2610
|
+
/** Regex replace across all messages. */
|
|
2611
|
+
_replaceInMessages(messages, pattern, replacement) {
|
|
2612
|
+
const regex = this._safeCompileRegex(pattern);
|
|
2613
|
+
if (!regex) {
|
|
2614
|
+
debug("Skipping invalid regex pattern in prompt fix");
|
|
2615
|
+
return messages;
|
|
1881
2616
|
}
|
|
2617
|
+
return messages.map((msg) => {
|
|
2618
|
+
const msgContent = msg.content;
|
|
2619
|
+
if (typeof msgContent === "string") {
|
|
2620
|
+
return { ...msg, content: msgContent.replace(regex, replacement) };
|
|
2621
|
+
}
|
|
2622
|
+
return msg;
|
|
2623
|
+
});
|
|
1882
2624
|
}
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
2625
|
+
/** Add few-shot examples after the first system message. */
|
|
2626
|
+
_addFewShotExamples(messages, examples) {
|
|
2627
|
+
const result = [];
|
|
2628
|
+
let systemFound = false;
|
|
2629
|
+
for (const msg of messages) {
|
|
2630
|
+
result.push(msg);
|
|
2631
|
+
if (msg.role === "system" && !systemFound) {
|
|
2632
|
+
systemFound = true;
|
|
2633
|
+
for (const example of examples) {
|
|
2634
|
+
if (example.user) {
|
|
2635
|
+
result.push({ role: "user", content: example.user });
|
|
2636
|
+
}
|
|
2637
|
+
if (example.assistant) {
|
|
2638
|
+
result.push({ role: "assistant", content: example.assistant });
|
|
2639
|
+
}
|
|
1893
2640
|
}
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
);
|
|
1898
|
-
this._refreshTimer.unref();
|
|
1899
|
-
debug("Started fix refresh interval");
|
|
2641
|
+
}
|
|
2642
|
+
}
|
|
2643
|
+
return result;
|
|
1900
2644
|
}
|
|
1901
2645
|
};
|
|
1902
2646
|
|
|
1903
|
-
// src/runtime/
|
|
1904
|
-
var
|
|
1905
|
-
guardId;
|
|
1906
|
-
reason;
|
|
1907
|
-
phase;
|
|
1908
|
-
constructor(guardId, reason, phase) {
|
|
1909
|
-
super(`Risicare guard rejected operation: ${guardId} (${phase}) \u2014 ${reason}`);
|
|
1910
|
-
this.name = "GuardRejectedError";
|
|
1911
|
-
this.guardId = guardId;
|
|
1912
|
-
this.reason = reason;
|
|
1913
|
-
this.phase = phase;
|
|
1914
|
-
}
|
|
1915
|
-
};
|
|
1916
|
-
function createInterceptContext(operationType, operationName, options) {
|
|
1917
|
-
return {
|
|
1918
|
-
operationType,
|
|
1919
|
-
operationName,
|
|
1920
|
-
sessionId: options?.sessionId,
|
|
1921
|
-
traceId: options?.traceId,
|
|
1922
|
-
errorCode: options?.errorCode,
|
|
1923
|
-
attempt: 1,
|
|
1924
|
-
appliedFixes: []
|
|
1925
|
-
};
|
|
1926
|
-
}
|
|
1927
|
-
var DefaultFixInterceptor = class {
|
|
2647
|
+
// src/runtime/loader.ts
|
|
2648
|
+
var FixLoader = class _FixLoader {
|
|
1928
2649
|
_config;
|
|
1929
2650
|
_cache;
|
|
1930
|
-
|
|
1931
|
-
|
|
2651
|
+
_refreshTimer = null;
|
|
2652
|
+
_lastLoadTime = null;
|
|
2653
|
+
_consecutiveFailures = 0;
|
|
2654
|
+
_circuitOpenUntil = 0;
|
|
2655
|
+
_onLoadCallbacks = [];
|
|
2656
|
+
// Circuit breaker settings
|
|
2657
|
+
static CIRCUIT_BREAKER_THRESHOLD = 3;
|
|
2658
|
+
static CIRCUIT_BREAKER_COOLDOWN_MS = 3e4;
|
|
2659
|
+
constructor(config, cache) {
|
|
1932
2660
|
this._config = resolveFixRuntimeConfig(config);
|
|
1933
2661
|
this._cache = cache;
|
|
1934
|
-
this._applier = applier;
|
|
1935
2662
|
}
|
|
1936
|
-
/**
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
* - If retrying after error: look up fix by error_code, apply
|
|
1940
|
-
* prompt/parameter/fallback fixes
|
|
1941
|
-
* - Runs input guard fixes on all message content
|
|
1942
|
-
*/
|
|
1943
|
-
preCall(ctx, messages, params) {
|
|
1944
|
-
try {
|
|
1945
|
-
if (!this._config.enabled) {
|
|
1946
|
-
return { messages, params };
|
|
1947
|
-
}
|
|
1948
|
-
let modifiedMessages = messages;
|
|
1949
|
-
let modifiedParams = { ...params };
|
|
1950
|
-
if (ctx.errorCode) {
|
|
1951
|
-
const fix = this._applier.getFixForError(ctx.errorCode, ctx.sessionId);
|
|
1952
|
-
if (fix) {
|
|
1953
|
-
debug(`Applying fix ${fix.fixId} for ${ctx.errorCode}`);
|
|
1954
|
-
if (fix.fixType === "prompt" && messages) {
|
|
1955
|
-
const msgRecords = messages;
|
|
1956
|
-
const { messages: newMessages, result } = this._applier.applyPromptFix(fix, msgRecords);
|
|
1957
|
-
modifiedMessages = newMessages;
|
|
1958
|
-
ctx.appliedFixes.push(result);
|
|
1959
|
-
this._applier.logApplication(result);
|
|
1960
|
-
} else if (fix.fixType === "parameter") {
|
|
1961
|
-
const { params: newParams, result } = this._applier.applyParameterFix(fix, modifiedParams);
|
|
1962
|
-
modifiedParams = newParams;
|
|
1963
|
-
ctx.appliedFixes.push(result);
|
|
1964
|
-
this._applier.logApplication(result);
|
|
1965
|
-
} else if (fix.fixType === "fallback") {
|
|
1966
|
-
const { params: newParams, result } = this._applier.applyFallbackFix(fix, modifiedParams);
|
|
1967
|
-
modifiedParams = newParams;
|
|
1968
|
-
ctx.appliedFixes.push(result);
|
|
1969
|
-
this._applier.logApplication(result);
|
|
1970
|
-
}
|
|
1971
|
-
}
|
|
1972
|
-
}
|
|
1973
|
-
if (modifiedMessages && this._config.enabled) {
|
|
1974
|
-
for (const msg of modifiedMessages) {
|
|
1975
|
-
const content = msg.content;
|
|
1976
|
-
if (typeof content === "string") {
|
|
1977
|
-
for (const fix of this._cache.getAll()) {
|
|
1978
|
-
if (fix.fixType === "guard") {
|
|
1979
|
-
const { passed, result } = this._applier.applyGuardFix(
|
|
1980
|
-
fix,
|
|
1981
|
-
content,
|
|
1982
|
-
true
|
|
1983
|
-
);
|
|
1984
|
-
if (result.applied) {
|
|
1985
|
-
ctx.appliedFixes.push(result);
|
|
1986
|
-
this._applier.logApplication(result);
|
|
1987
|
-
}
|
|
1988
|
-
if (!passed) {
|
|
1989
|
-
throw new GuardRejectedError(
|
|
1990
|
-
fix.fixId ?? "unknown",
|
|
1991
|
-
result.reason ?? "guard rejected input",
|
|
1992
|
-
"pre_call"
|
|
1993
|
-
);
|
|
1994
|
-
}
|
|
1995
|
-
}
|
|
1996
|
-
}
|
|
1997
|
-
}
|
|
1998
|
-
}
|
|
1999
|
-
}
|
|
2000
|
-
return { messages: modifiedMessages, params: modifiedParams };
|
|
2001
|
-
} catch (e) {
|
|
2002
|
-
if (e instanceof GuardRejectedError) throw e;
|
|
2003
|
-
debug(`DefaultFixInterceptor.preCall error: ${e}`);
|
|
2004
|
-
return { messages, params };
|
|
2005
|
-
}
|
|
2663
|
+
/** Timestamp of last successful load. */
|
|
2664
|
+
get lastLoadTime() {
|
|
2665
|
+
return this._lastLoadTime;
|
|
2006
2666
|
}
|
|
2007
2667
|
/**
|
|
2008
|
-
*
|
|
2668
|
+
* Start the loader: perform initial load and start background refresh.
|
|
2009
2669
|
*
|
|
2010
|
-
*
|
|
2670
|
+
* Never throws — failures are logged and the runtime degrades gracefully.
|
|
2011
2671
|
*/
|
|
2012
|
-
|
|
2672
|
+
start() {
|
|
2013
2673
|
try {
|
|
2014
2674
|
if (!this._config.enabled) {
|
|
2015
|
-
|
|
2675
|
+
debug("Fix runtime disabled, skipping loader start");
|
|
2676
|
+
return;
|
|
2016
2677
|
}
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
);
|
|
2026
|
-
if (result.applied) {
|
|
2027
|
-
ctx.appliedFixes.push(result);
|
|
2028
|
-
this._applier.logApplication(result);
|
|
2029
|
-
}
|
|
2030
|
-
if (!passed) {
|
|
2031
|
-
warn(`Output guard failed for fix ${fix.fixId}: ${result.reason ?? "unknown"}`);
|
|
2032
|
-
throw new GuardRejectedError(
|
|
2033
|
-
fix.fixId ?? "unknown",
|
|
2034
|
-
result.reason ?? "guard rejected output",
|
|
2035
|
-
"post_call"
|
|
2036
|
-
);
|
|
2037
|
-
}
|
|
2678
|
+
if (!this._config.apiKey) {
|
|
2679
|
+
warn("No API key configured, fixes will not be loaded");
|
|
2680
|
+
return;
|
|
2681
|
+
}
|
|
2682
|
+
this.loadSync().catch((e) => {
|
|
2683
|
+
debug(`Initial fix load failed: ${e}`);
|
|
2684
|
+
});
|
|
2685
|
+
if (this._config.autoRefresh) {
|
|
2686
|
+
this._startRefreshInterval();
|
|
2038
2687
|
}
|
|
2039
|
-
return { response, shouldContinue: true };
|
|
2040
2688
|
} catch (e) {
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2689
|
+
debug(`FixLoader.start error: ${e}`);
|
|
2690
|
+
}
|
|
2691
|
+
}
|
|
2692
|
+
/** Stop the loader: clear the refresh interval. */
|
|
2693
|
+
stop() {
|
|
2694
|
+
try {
|
|
2695
|
+
if (this._refreshTimer !== null) {
|
|
2696
|
+
clearInterval(this._refreshTimer);
|
|
2697
|
+
this._refreshTimer = null;
|
|
2698
|
+
}
|
|
2699
|
+
} catch (e) {
|
|
2700
|
+
debug(`FixLoader.stop error: ${e}`);
|
|
2044
2701
|
}
|
|
2045
2702
|
}
|
|
2046
2703
|
/**
|
|
2047
|
-
*
|
|
2704
|
+
* Register a callback invoked after each successful load.
|
|
2705
|
+
*/
|
|
2706
|
+
onLoad(callback) {
|
|
2707
|
+
this._onLoadCallbacks.push(callback);
|
|
2708
|
+
}
|
|
2709
|
+
/**
|
|
2710
|
+
* Load fixes from the API.
|
|
2048
2711
|
*
|
|
2049
|
-
*
|
|
2050
|
-
*
|
|
2712
|
+
* Name kept as "loadSync" for parity with the Python SDK, but this
|
|
2713
|
+
* returns a Promise in JS (there's no synchronous fetch in Node.js).
|
|
2051
2714
|
*/
|
|
2052
|
-
|
|
2715
|
+
async loadSync() {
|
|
2716
|
+
if (!this._config.apiKey) {
|
|
2717
|
+
return [];
|
|
2718
|
+
}
|
|
2719
|
+
const now = Date.now();
|
|
2720
|
+
if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && now < this._circuitOpenUntil) {
|
|
2721
|
+
debug("Fix loader circuit breaker open \u2014 skipping load");
|
|
2722
|
+
return this._cache.getAll();
|
|
2723
|
+
}
|
|
2053
2724
|
try {
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
const
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
deploymentId: fix.deploymentId,
|
|
2074
|
-
fixType: "retry",
|
|
2075
|
-
modifications: { attempt: ctx.attempt }
|
|
2076
|
-
};
|
|
2077
|
-
ctx.appliedFixes.push(result);
|
|
2078
|
-
this._applier.logApplication(result);
|
|
2079
|
-
return { shouldRetry: true, modifiedParams: null };
|
|
2080
|
-
}
|
|
2081
|
-
}
|
|
2082
|
-
if (fix.fixType === "fallback") {
|
|
2083
|
-
const { params: modifiedParams, result } = this._applier.applyFallbackFix(fix, {});
|
|
2084
|
-
if (result.applied) {
|
|
2085
|
-
ctx.appliedFixes.push(result);
|
|
2086
|
-
this._applier.logApplication(result);
|
|
2087
|
-
return { shouldRetry: true, modifiedParams };
|
|
2088
|
-
}
|
|
2725
|
+
const endpoint = this._config.apiEndpoint.replace(/\/+$/, "");
|
|
2726
|
+
const url = `${endpoint}/api/v1/fixes/active`;
|
|
2727
|
+
const controller = new AbortController();
|
|
2728
|
+
const timeoutId = setTimeout(
|
|
2729
|
+
() => controller.abort(),
|
|
2730
|
+
this._config.timeoutMs
|
|
2731
|
+
);
|
|
2732
|
+
const response = await fetch(url, {
|
|
2733
|
+
method: "GET",
|
|
2734
|
+
headers: {
|
|
2735
|
+
"Authorization": `Bearer ${this._config.apiKey}`,
|
|
2736
|
+
"Content-Type": "application/json",
|
|
2737
|
+
"X-Risicare-SDK-Version": SDK_VERSION
|
|
2738
|
+
},
|
|
2739
|
+
signal: controller.signal
|
|
2740
|
+
});
|
|
2741
|
+
clearTimeout(timeoutId);
|
|
2742
|
+
if (!response.ok) {
|
|
2743
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
2089
2744
|
}
|
|
2090
|
-
|
|
2745
|
+
const data = await response.json();
|
|
2746
|
+
const fixes = this._parseResponse(data);
|
|
2747
|
+
this._onLoadSuccess(fixes);
|
|
2748
|
+
return fixes;
|
|
2091
2749
|
} catch (e) {
|
|
2092
|
-
|
|
2093
|
-
|
|
2750
|
+
this._onLoadFailure(e);
|
|
2751
|
+
throw e;
|
|
2094
2752
|
}
|
|
2095
2753
|
}
|
|
2754
|
+
/** Get currently cached fixes without hitting the API. */
|
|
2755
|
+
getCached() {
|
|
2756
|
+
return this._cache.getAll();
|
|
2757
|
+
}
|
|
2096
2758
|
// ─── Private ────────────────────────────────────────────────────────────
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
if (
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
const message = first?.message;
|
|
2106
|
-
if (typeof message?.content === "string") {
|
|
2107
|
-
return message.content;
|
|
2759
|
+
_parseResponse(data) {
|
|
2760
|
+
const fixes = [];
|
|
2761
|
+
const items = data.fixes ?? data.data ?? [];
|
|
2762
|
+
if (!Array.isArray(items)) return fixes;
|
|
2763
|
+
for (const item of items) {
|
|
2764
|
+
try {
|
|
2765
|
+
if (item && typeof item === "object") {
|
|
2766
|
+
fixes.push(activeFixFromApiResponse(item));
|
|
2108
2767
|
}
|
|
2109
|
-
}
|
|
2110
|
-
|
|
2111
|
-
if (typeof content === "string") return content;
|
|
2112
|
-
if (Array.isArray(content) && content.length > 0) {
|
|
2113
|
-
const first = content[0];
|
|
2114
|
-
if (typeof first?.text === "string") return first.text;
|
|
2768
|
+
} catch (e) {
|
|
2769
|
+
debug(`Failed to parse fix item: ${e}`);
|
|
2115
2770
|
}
|
|
2116
2771
|
}
|
|
2117
|
-
return
|
|
2118
|
-
}
|
|
2119
|
-
};
|
|
2120
|
-
function classifyError(error) {
|
|
2121
|
-
const errorType = error.constructor.name.toLowerCase();
|
|
2122
|
-
const errorMsg = error.message.toLowerCase();
|
|
2123
|
-
if (errorType.includes("timeout") || errorMsg.includes("timeout") || errorMsg.includes("aborted")) {
|
|
2124
|
-
return "TOOL.EXECUTION.TIMEOUT";
|
|
2125
|
-
}
|
|
2126
|
-
if (errorMsg.includes("rate") && errorMsg.includes("limit")) {
|
|
2127
|
-
return "TOOL.EXECUTION.RATE_LIMIT";
|
|
2128
|
-
}
|
|
2129
|
-
if (errorMsg.includes("429") || errorMsg.includes("too many requests")) {
|
|
2130
|
-
return "TOOL.EXECUTION.RATE_LIMIT";
|
|
2772
|
+
return fixes;
|
|
2131
2773
|
}
|
|
2132
|
-
|
|
2133
|
-
|
|
2774
|
+
_onLoadSuccess(fixes) {
|
|
2775
|
+
this._lastLoadTime = Date.now();
|
|
2776
|
+
this._consecutiveFailures = 0;
|
|
2777
|
+
this._cache.setAll(fixes);
|
|
2778
|
+
for (const callback of this._onLoadCallbacks) {
|
|
2779
|
+
try {
|
|
2780
|
+
callback(fixes);
|
|
2781
|
+
} catch (e) {
|
|
2782
|
+
debug(`Load callback error: ${e}`);
|
|
2783
|
+
}
|
|
2784
|
+
}
|
|
2785
|
+
debug(`Loaded ${fixes.length} active fixes`);
|
|
2134
2786
|
}
|
|
2135
|
-
|
|
2136
|
-
|
|
2787
|
+
_onLoadFailure(error) {
|
|
2788
|
+
this._consecutiveFailures++;
|
|
2789
|
+
if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD) {
|
|
2790
|
+
this._circuitOpenUntil = Date.now() + _FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS;
|
|
2791
|
+
warn(
|
|
2792
|
+
`Fix loader circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${_FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS / 1e3}s`
|
|
2793
|
+
);
|
|
2794
|
+
} else {
|
|
2795
|
+
debug(
|
|
2796
|
+
`Fix load failed (attempt ${this._consecutiveFailures}): ${error.message}`
|
|
2797
|
+
);
|
|
2798
|
+
}
|
|
2137
2799
|
}
|
|
2138
|
-
|
|
2139
|
-
|
|
2800
|
+
_startRefreshInterval() {
|
|
2801
|
+
const tick = () => {
|
|
2802
|
+
this.loadSync().catch((e) => {
|
|
2803
|
+
debug(`Background fix refresh failed: ${e}`);
|
|
2804
|
+
});
|
|
2805
|
+
};
|
|
2806
|
+
this._refreshTimer = setInterval(
|
|
2807
|
+
() => {
|
|
2808
|
+
if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && Date.now() < this._circuitOpenUntil) {
|
|
2809
|
+
return;
|
|
2810
|
+
}
|
|
2811
|
+
tick();
|
|
2812
|
+
},
|
|
2813
|
+
this._config.refreshIntervalMs
|
|
2814
|
+
);
|
|
2815
|
+
this._refreshTimer.unref();
|
|
2816
|
+
debug("Started fix refresh interval");
|
|
2140
2817
|
}
|
|
2141
|
-
|
|
2142
|
-
}
|
|
2818
|
+
};
|
|
2143
2819
|
|
|
2144
2820
|
// src/runtime/runtime.ts
|
|
2145
2821
|
var G2 = globalThis;
|
|
@@ -2386,10 +3062,20 @@ function shutdownFixRuntime() {
|
|
|
2386
3062
|
}
|
|
2387
3063
|
|
|
2388
3064
|
// src/client.ts
|
|
3065
|
+
var TERMINATING_SIGNALS = [
|
|
3066
|
+
["SIGTERM", 15],
|
|
3067
|
+
["SIGINT", 2]
|
|
3068
|
+
];
|
|
3069
|
+
var BACKSTOP_MARGIN_MS = 500;
|
|
3070
|
+
var _finalMetrics;
|
|
2389
3071
|
var RisicareClient = class {
|
|
2390
3072
|
config;
|
|
2391
3073
|
processor;
|
|
2392
3074
|
tracer;
|
|
3075
|
+
/** RULING §5. The signal path does NOT clear the global client, so without
|
|
3076
|
+
* this flag `getMetrics()` would keep reporting `"running"` over a processor
|
|
3077
|
+
* that has already been torn down. */
|
|
3078
|
+
isShutdown = false;
|
|
2393
3079
|
_shutdownPromise;
|
|
2394
3080
|
_shutdownHandlers = [];
|
|
2395
3081
|
constructor(config) {
|
|
@@ -2409,20 +3095,44 @@ var RisicareClient = class {
|
|
|
2409
3095
|
compress: this.config.compress
|
|
2410
3096
|
});
|
|
2411
3097
|
} else {
|
|
2412
|
-
exporter =
|
|
3098
|
+
exporter = void 0;
|
|
3099
|
+
if (this.config.enabled) {
|
|
3100
|
+
try {
|
|
3101
|
+
console.warn(
|
|
3102
|
+
`[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.`
|
|
3103
|
+
);
|
|
3104
|
+
} catch {
|
|
3105
|
+
}
|
|
3106
|
+
}
|
|
2413
3107
|
}
|
|
2414
3108
|
this.processor = new BatchSpanProcessor({
|
|
2415
|
-
exporters: [exporter],
|
|
3109
|
+
exporters: exporter ? [exporter] : [],
|
|
2416
3110
|
batchSize: this.config.batchSize,
|
|
2417
3111
|
batchTimeoutMs: this.config.batchTimeoutMs,
|
|
2418
3112
|
maxQueueSize: this.config.maxQueueSize,
|
|
2419
|
-
debug: this.config.debug
|
|
3113
|
+
debug: this.config.debug,
|
|
3114
|
+
// The processor is the ONE choke point every exporter is behind. Masking
|
|
3115
|
+
// anywhere downstream (in the HTTP exporter, say) would leave a hole for
|
|
3116
|
+
// any other exporter; masking upstream would put customer code on the
|
|
3117
|
+
// span-end call path.
|
|
3118
|
+
mask: this.config.mask,
|
|
3119
|
+
// Same argument as `mask`: the processor is the ONE choke point every
|
|
3120
|
+
// exporter is behind, and the only place BOTH content paths — provider
|
|
3121
|
+
// capture and hand-set attributes — can be gated together. The Tracer
|
|
3122
|
+
// still carries `traceContent` for the provider patches to read; that is
|
|
3123
|
+
// now a convenience, not the enforcement point.
|
|
3124
|
+
traceContent: this.config.traceContent
|
|
2420
3125
|
});
|
|
2421
3126
|
this.tracer = new Tracer({
|
|
2422
3127
|
onSpanEnd: (span) => this.processor.onSpanEnd(span),
|
|
2423
3128
|
sampleRate: this.config.sampleRate,
|
|
2424
3129
|
enabled: this.config.enabled,
|
|
2425
|
-
traceContent: this.config.traceContent
|
|
3130
|
+
traceContent: this.config.traceContent,
|
|
3131
|
+
// F-SDKJSSVCNAME-001 — these were resolved into `config` and then read by
|
|
3132
|
+
// nothing. The Tracer is where Python emits them, so JS emits them there
|
|
3133
|
+
// too rather than inventing a second site.
|
|
3134
|
+
serviceName: this.config.serviceName,
|
|
3135
|
+
serviceVersion: this.config.serviceVersion
|
|
2426
3136
|
});
|
|
2427
3137
|
this.processor.start();
|
|
2428
3138
|
if (this.config.apiKey && this.config.enabled) {
|
|
@@ -2470,21 +3180,82 @@ var RisicareClient = class {
|
|
|
2470
3180
|
}
|
|
2471
3181
|
this._shutdownHandlers = [];
|
|
2472
3182
|
await this.processor.shutdown();
|
|
3183
|
+
this.isShutdown = true;
|
|
3184
|
+
_finalMetrics = this.processor.getMetrics();
|
|
2473
3185
|
}
|
|
3186
|
+
/**
|
|
3187
|
+
* Flush pending spans.
|
|
3188
|
+
*
|
|
3189
|
+
* @returns `true` only if everything queued at entry was DELIVERED.
|
|
3190
|
+
*
|
|
3191
|
+
* RULING §6: this used to discard the processor's boolean and return
|
|
3192
|
+
* `Promise<void>`, which resolves without throwing and reads to a caller
|
|
3193
|
+
* exactly like success. A discarded answer is not meaningfully better than a
|
|
3194
|
+
* false one — both leave the customer unable to tell *drained* from
|
|
3195
|
+
* *discarded*.
|
|
3196
|
+
*/
|
|
2474
3197
|
async flush() {
|
|
2475
|
-
|
|
3198
|
+
return this.processor.flush();
|
|
2476
3199
|
}
|
|
3200
|
+
/**
|
|
3201
|
+
* SDK-RELEASE-RULING.md §3 — who decides whether the process dies.
|
|
3202
|
+
*
|
|
3203
|
+
* The contract, and it is the same one the Python SDK now satisfies:
|
|
3204
|
+
*
|
|
3205
|
+
* the SDK's signal handler never CHANGES whether the signal
|
|
3206
|
+
* terminates the process.
|
|
3207
|
+
*
|
|
3208
|
+
* Registering ANY listener for SIGTERM/SIGINT displaces Node's default
|
|
3209
|
+
* terminate. Before this, the SDK registered one unconditionally, and on the
|
|
3210
|
+
* success path `clearTimeout` removed the 5 s `process.exit(1)` backstop —
|
|
3211
|
+
* so a JS app with a live event loop drained, cleared its own only exit, and
|
|
3212
|
+
* **ran forever**. The orchestrator waited out the whole grace period and
|
|
3213
|
+
* SIGKILLed, which exits **137** and reads as OOM-killed in every dashboard.
|
|
3214
|
+
* Measured >25 s alive on both 0.5.0 and a clean-rebuilt 0.4.2, so this is
|
|
3215
|
+
* PRE-EXISTING (`F-SDKJSEXIT-001`), not a regression of the data-loss fix.
|
|
3216
|
+
*
|
|
3217
|
+
* The rule splits on one question — did the signal already have an owner?
|
|
3218
|
+
*
|
|
3219
|
+
* * **No prior listener.** Node's default was termination and OUR
|
|
3220
|
+
* registration displaced it. We owe the process that death.
|
|
3221
|
+
* * **A prior listener exists.** The application took ownership before the
|
|
3222
|
+
* SDK loaded. We drain and RETURN; termination was never ours to decide,
|
|
3223
|
+
* and forcing it would cut off the app's own graceful shutdown.
|
|
3224
|
+
*
|
|
3225
|
+
* ⚠ `beforeExit` is deliberately NOT in that logic. It is not a signal and
|
|
3226
|
+
* carries no termination the SDK could displace — the loop has already
|
|
3227
|
+
* drained and the process is leaving on its own.
|
|
3228
|
+
*/
|
|
2477
3229
|
_registerShutdownHooks() {
|
|
2478
|
-
const
|
|
2479
|
-
const timeout = setTimeout(() => process.exit(1), 5e3);
|
|
2480
|
-
timeout.unref();
|
|
3230
|
+
const onBeforeExit = () => {
|
|
2481
3231
|
this.shutdown().catch(() => {
|
|
2482
|
-
})
|
|
3232
|
+
});
|
|
2483
3233
|
};
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
3234
|
+
process.once("beforeExit", onBeforeExit);
|
|
3235
|
+
this._shutdownHandlers.push({ signal: "beforeExit", handler: onBeforeExit });
|
|
3236
|
+
for (const [signal, signum] of TERMINATING_SIGNALS) {
|
|
3237
|
+
const weDisplacedDefault = process.listenerCount(signal) === 0;
|
|
3238
|
+
const handler = () => {
|
|
3239
|
+
const backstop = setTimeout(
|
|
3240
|
+
() => process.exit(128 + signum),
|
|
3241
|
+
SHUTDOWN_BUDGET_MS + BACKSTOP_MARGIN_MS
|
|
3242
|
+
);
|
|
3243
|
+
backstop.unref();
|
|
3244
|
+
this.shutdown().catch(() => {
|
|
3245
|
+
}).finally(() => {
|
|
3246
|
+
clearTimeout(backstop);
|
|
3247
|
+
if (!weDisplacedDefault) return;
|
|
3248
|
+
try {
|
|
3249
|
+
process.kill(process.pid, signal);
|
|
3250
|
+
} catch {
|
|
3251
|
+
process.exit(128 + signum);
|
|
3252
|
+
}
|
|
3253
|
+
const failsafe = setTimeout(() => process.exit(128 + signum), 100);
|
|
3254
|
+
failsafe.unref();
|
|
3255
|
+
});
|
|
3256
|
+
};
|
|
3257
|
+
process.once(signal, handler);
|
|
3258
|
+
this._shutdownHandlers.push({ signal, handler });
|
|
2488
3259
|
}
|
|
2489
3260
|
}
|
|
2490
3261
|
};
|
|
@@ -2521,6 +3292,7 @@ function init(config) {
|
|
|
2521
3292
|
}
|
|
2522
3293
|
return;
|
|
2523
3294
|
}
|
|
3295
|
+
_finalMetrics = void 0;
|
|
2524
3296
|
const client = new RisicareClient(config);
|
|
2525
3297
|
setClient(client);
|
|
2526
3298
|
setTracer(client.tracer);
|
|
@@ -2538,8 +3310,8 @@ async function shutdown() {
|
|
|
2538
3310
|
}
|
|
2539
3311
|
async function flush() {
|
|
2540
3312
|
const client = getClient();
|
|
2541
|
-
if (!client) return;
|
|
2542
|
-
|
|
3313
|
+
if (!client) return true;
|
|
3314
|
+
return client.flush();
|
|
2543
3315
|
}
|
|
2544
3316
|
function enable() {
|
|
2545
3317
|
const client = getClient();
|
|
@@ -2558,17 +3330,33 @@ function getTracer2() {
|
|
|
2558
3330
|
}
|
|
2559
3331
|
function getTraceContent() {
|
|
2560
3332
|
const tracer = getTracer();
|
|
2561
|
-
return tracer?.traceContent ??
|
|
3333
|
+
return tracer?.traceContent ?? false;
|
|
2562
3334
|
}
|
|
2563
3335
|
function getMetrics() {
|
|
2564
3336
|
const client = getClient();
|
|
2565
|
-
|
|
3337
|
+
if (client && !client.isShutdown) {
|
|
3338
|
+
return { ...client.processor.getMetrics(), sdkState: "running" };
|
|
3339
|
+
}
|
|
3340
|
+
if (_finalMetrics) {
|
|
3341
|
+
return {
|
|
3342
|
+
..._finalMetrics,
|
|
3343
|
+
droppedSpansByReason: { ..._finalMetrics.droppedSpansByReason },
|
|
3344
|
+
sdkState: "shutdown"
|
|
3345
|
+
};
|
|
3346
|
+
}
|
|
3347
|
+
return {
|
|
2566
3348
|
exportedSpans: 0,
|
|
2567
3349
|
droppedSpans: 0,
|
|
3350
|
+
droppedSpansByReason: {
|
|
3351
|
+
queue_full: 0,
|
|
3352
|
+
transport_refused: 0,
|
|
3353
|
+
shutdown_residue: 0
|
|
3354
|
+
},
|
|
2568
3355
|
failedExports: 0,
|
|
2569
3356
|
queueSize: 0,
|
|
2570
3357
|
queueCapacity: 0,
|
|
2571
|
-
queueUtilization: 0
|
|
3358
|
+
queueUtilization: 0,
|
|
3359
|
+
sdkState: "uninitialised"
|
|
2572
3360
|
};
|
|
2573
3361
|
}
|
|
2574
3362
|
var _ERROR_DEDUP_TTL_MS = 5 * 60 * 1e3;
|
|
@@ -2576,8 +3364,7 @@ var _ERROR_DEDUP_MAX = 1e3;
|
|
|
2576
3364
|
var _recentErrors = /* @__PURE__ */ new Map();
|
|
2577
3365
|
function _errorFingerprint(err) {
|
|
2578
3366
|
const raw = `${err.constructor?.name ?? "Error"}:${String(err.message ?? "").slice(0, 200)}`;
|
|
2579
|
-
|
|
2580
|
-
return createHash2("sha256").update(raw).digest("hex").slice(0, 16);
|
|
3367
|
+
return (0, import_node_crypto3.createHash)("sha256").update(raw).digest("hex").slice(0, 16);
|
|
2581
3368
|
}
|
|
2582
3369
|
function _isDuplicateError(fingerprint) {
|
|
2583
3370
|
const now = Date.now();
|
|
@@ -2635,13 +3422,17 @@ function score(traceId, name, value, options) {
|
|
|
2635
3422
|
if (!client?.enabled || !client.config.apiKey) return;
|
|
2636
3423
|
const endpoint = client.config.endpoint.replace(/\/$/, "");
|
|
2637
3424
|
const url = `${endpoint}/api/v1/scores`;
|
|
3425
|
+
let comment = options?.comment;
|
|
3426
|
+
if (comment !== void 0 && client.config.mask) {
|
|
3427
|
+
comment = maskText(client.config.mask, SCORE_COMMENT_KEY, comment);
|
|
3428
|
+
}
|
|
2638
3429
|
const body = JSON.stringify({
|
|
2639
3430
|
trace_id: traceId,
|
|
2640
3431
|
name,
|
|
2641
3432
|
score: value,
|
|
2642
3433
|
source: "sdk",
|
|
2643
3434
|
...options?.spanId && { span_id: options.spanId },
|
|
2644
|
-
...
|
|
3435
|
+
...comment && { comment }
|
|
2645
3436
|
});
|
|
2646
3437
|
fetch(url, {
|
|
2647
3438
|
method: "POST",
|
|
@@ -2769,12 +3560,14 @@ function withSessionEndMarker(body) {
|
|
|
2769
3560
|
// src/decorators/agent.ts
|
|
2770
3561
|
function _wrapAgent(options, fn) {
|
|
2771
3562
|
const spanName = `agent:${options.name ?? "agent"}`;
|
|
3563
|
+
const agentId = options.agentId ?? generateAgentId(options.name ?? "agent");
|
|
3564
|
+
const boundOptions = { ...options, agentId };
|
|
2772
3565
|
return (...args) => {
|
|
2773
3566
|
const tracer = getTracer2();
|
|
2774
3567
|
if (!tracer) {
|
|
2775
3568
|
return fn(...args);
|
|
2776
3569
|
}
|
|
2777
|
-
return withAgent(
|
|
3570
|
+
return withAgent(boundOptions, () => {
|
|
2778
3571
|
return tracer.startSpan(
|
|
2779
3572
|
{ name: spanName, kind: "agent" /* AGENT */ },
|
|
2780
3573
|
(span) => withEndMarker(span, "agent", () => fn(...args))
|
|
@@ -3619,7 +4412,7 @@ var RisicareLlamaIndexHandler = class {
|
|
|
3619
4412
|
};
|
|
3620
4413
|
|
|
3621
4414
|
// src/webhooks.ts
|
|
3622
|
-
var
|
|
4415
|
+
var import_node_crypto4 = require("crypto");
|
|
3623
4416
|
var import_node_buffer = require("buffer");
|
|
3624
4417
|
var DEFAULT_TIMESTAMP_TOLERANCE_S = 300;
|
|
3625
4418
|
var SIGNATURE_HEADER = "X-Risicare-Signature";
|
|
@@ -3732,7 +4525,7 @@ function safeHexEqual(computed, expected) {
|
|
|
3732
4525
|
if (a.length !== b.length) {
|
|
3733
4526
|
return false;
|
|
3734
4527
|
}
|
|
3735
|
-
return (0,
|
|
4528
|
+
return (0, import_node_crypto4.timingSafeEqual)(a, b);
|
|
3736
4529
|
}
|
|
3737
4530
|
function verifyWebhookSignature(payload, headers, secret, opts = {}) {
|
|
3738
4531
|
const toleranceS = opts.toleranceS ?? DEFAULT_TIMESTAMP_TOLERANCE_S;
|
|
@@ -3773,7 +4566,7 @@ function verifyWebhookSignature(payload, headers, secret, opts = {}) {
|
|
|
3773
4566
|
`Webhook timestamp outside tolerance: skew=${skew}s, max=${toleranceS}s`
|
|
3774
4567
|
);
|
|
3775
4568
|
}
|
|
3776
|
-
const hmac = (0,
|
|
4569
|
+
const hmac = (0, import_node_crypto4.createHmac)("sha256", secret);
|
|
3777
4570
|
hmac.update(`${tsInSig}.`);
|
|
3778
4571
|
hmac.update(payloadBytes);
|
|
3779
4572
|
const computed = hmac.digest("hex");
|
|
@@ -3786,6 +4579,7 @@ function verifyWebhookSignature(payload, headers, secret, opts = {}) {
|
|
|
3786
4579
|
AgentRole,
|
|
3787
4580
|
DEFAULT_TIMESTAMP_TOLERANCE_S,
|
|
3788
4581
|
GuardRejectedError,
|
|
4582
|
+
MASK_ERROR_MARKER,
|
|
3789
4583
|
MessageType,
|
|
3790
4584
|
RisicareCallbackHandler,
|
|
3791
4585
|
RisicareLlamaIndexHandler,
|