risicare 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -0
- package/dist/frameworks/instructor.cjs +93 -73
- package/dist/frameworks/instructor.cjs.map +1 -1
- package/dist/frameworks/instructor.d.cts +19 -7
- package/dist/frameworks/instructor.d.ts +19 -7
- package/dist/frameworks/instructor.js +85 -67
- package/dist/frameworks/instructor.js.map +1 -1
- package/dist/frameworks/langchain.cjs +192 -94
- package/dist/frameworks/langchain.cjs.map +1 -1
- package/dist/frameworks/langchain.d.cts +97 -3
- package/dist/frameworks/langchain.d.ts +97 -3
- package/dist/frameworks/langchain.js +190 -88
- package/dist/frameworks/langchain.js.map +1 -1
- package/dist/frameworks/langgraph.cjs +192 -94
- package/dist/frameworks/langgraph.cjs.map +1 -1
- package/dist/frameworks/langgraph.js +190 -88
- package/dist/frameworks/langgraph.js.map +1 -1
- package/dist/frameworks/llamaindex.cjs +94 -69
- package/dist/frameworks/llamaindex.cjs.map +1 -1
- package/dist/frameworks/llamaindex.d.cts +33 -17
- package/dist/frameworks/llamaindex.d.ts +33 -17
- package/dist/frameworks/llamaindex.js +85 -62
- package/dist/frameworks/llamaindex.js.map +1 -1
- package/dist/index.cjs +2684 -1934
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +234 -46
- package/dist/index.d.ts +234 -46
- package/dist/index.js +2492 -1762
- package/dist/index.js.map +1 -1
- package/dist/providers/anthropic/index.cjs +33 -34
- package/dist/providers/anthropic/index.cjs.map +1 -1
- package/dist/providers/anthropic/index.js +25 -28
- package/dist/providers/anthropic/index.js.map +1 -1
- package/dist/providers/bedrock/index.cjs +56 -44
- package/dist/providers/bedrock/index.cjs.map +1 -1
- package/dist/providers/bedrock/index.d.cts +13 -1
- package/dist/providers/bedrock/index.d.ts +13 -1
- package/dist/providers/bedrock/index.js +47 -38
- package/dist/providers/bedrock/index.js.map +1 -1
- package/dist/providers/cerebras/index.cjs +33 -34
- package/dist/providers/cerebras/index.cjs.map +1 -1
- package/dist/providers/cerebras/index.js +25 -28
- package/dist/providers/cerebras/index.js.map +1 -1
- package/dist/providers/cohere/index.cjs +35 -36
- package/dist/providers/cohere/index.cjs.map +1 -1
- package/dist/providers/cohere/index.js +27 -30
- package/dist/providers/cohere/index.js.map +1 -1
- package/dist/providers/google/index.cjs +33 -34
- package/dist/providers/google/index.cjs.map +1 -1
- package/dist/providers/google/index.js +25 -28
- package/dist/providers/google/index.js.map +1 -1
- package/dist/providers/groq/index.cjs +33 -34
- package/dist/providers/groq/index.cjs.map +1 -1
- package/dist/providers/groq/index.js +25 -28
- package/dist/providers/groq/index.js.map +1 -1
- package/dist/providers/huggingface/index.cjs +33 -34
- package/dist/providers/huggingface/index.cjs.map +1 -1
- package/dist/providers/huggingface/index.js +25 -28
- package/dist/providers/huggingface/index.js.map +1 -1
- package/dist/providers/mistral/index.cjs +37 -38
- package/dist/providers/mistral/index.cjs.map +1 -1
- package/dist/providers/mistral/index.js +29 -32
- package/dist/providers/mistral/index.js.map +1 -1
- package/dist/providers/ollama/index.cjs +41 -34
- package/dist/providers/ollama/index.cjs.map +1 -1
- package/dist/providers/ollama/index.js +33 -28
- package/dist/providers/ollama/index.js.map +1 -1
- package/dist/providers/openai/index.cjs +36 -35
- package/dist/providers/openai/index.cjs.map +1 -1
- package/dist/providers/openai/index.js +28 -29
- package/dist/providers/openai/index.js.map +1 -1
- package/dist/providers/together/index.cjs +33 -34
- package/dist/providers/together/index.cjs.map +1 -1
- package/dist/providers/together/index.js +25 -28
- package/dist/providers/together/index.js.map +1 -1
- package/dist/providers/vercel-ai/index.cjs +27 -35
- package/dist/providers/vercel-ai/index.cjs.map +1 -1
- package/dist/providers/vercel-ai/index.js +19 -29
- package/dist/providers/vercel-ai/index.js.map +1 -1
- package/package.json +94 -33
package/dist/index.js
CHANGED
|
@@ -1,32 +1,17 @@
|
|
|
1
|
-
var __defProp = Object.defineProperty;
|
|
2
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
1
|
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
6
2
|
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
7
3
|
}) : x)(function(x) {
|
|
8
4
|
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
9
5
|
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
10
6
|
});
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
};
|
|
14
|
-
var __export = (target, all) => {
|
|
15
|
-
for (var name in all)
|
|
16
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
17
|
-
};
|
|
18
|
-
var __copyProps = (to, from, except, desc) => {
|
|
19
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
20
|
-
for (let key of __getOwnPropNames(from))
|
|
21
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
22
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
23
|
-
}
|
|
24
|
-
return to;
|
|
25
|
-
};
|
|
26
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
7
|
+
|
|
8
|
+
// src/client.ts
|
|
9
|
+
import { createHash as createHash2 } from "crypto";
|
|
27
10
|
|
|
28
11
|
// src/globals.ts
|
|
29
12
|
import { AsyncLocalStorage } from "async_hooks";
|
|
13
|
+
var G = globalThis;
|
|
14
|
+
var PREFIX = "__risicare_";
|
|
30
15
|
function getClient() {
|
|
31
16
|
return G[PREFIX + "client"];
|
|
32
17
|
}
|
|
@@ -63,14 +48,6 @@ function getDebug() {
|
|
|
63
48
|
function setDebugFlag(enabled) {
|
|
64
49
|
G[PREFIX + "debug"] = enabled;
|
|
65
50
|
}
|
|
66
|
-
var G, PREFIX;
|
|
67
|
-
var init_globals = __esm({
|
|
68
|
-
"src/globals.ts"() {
|
|
69
|
-
"use strict";
|
|
70
|
-
G = globalThis;
|
|
71
|
-
PREFIX = "__risicare_";
|
|
72
|
-
}
|
|
73
|
-
});
|
|
74
51
|
|
|
75
52
|
// src/utils/log.ts
|
|
76
53
|
function setDebug(enabled) {
|
|
@@ -86,1386 +63,598 @@ function warn(msg) {
|
|
|
86
63
|
process.stderr.write(`[risicare] WARNING: ${msg}
|
|
87
64
|
`);
|
|
88
65
|
}
|
|
89
|
-
var init_log = __esm({
|
|
90
|
-
"src/utils/log.ts"() {
|
|
91
|
-
"use strict";
|
|
92
|
-
init_globals();
|
|
93
|
-
}
|
|
94
|
-
});
|
|
95
66
|
|
|
96
|
-
// src/
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
cacheTtlMs: config.cacheTtlMs ?? 3e5,
|
|
104
|
-
cacheMaxEntries: config.cacheMaxEntries ?? 1e3,
|
|
105
|
-
autoRefresh: config.autoRefresh ?? true,
|
|
106
|
-
refreshIntervalMs: config.refreshIntervalMs ?? 6e4,
|
|
107
|
-
dryRun: config.dryRun ?? false,
|
|
108
|
-
abTestingEnabled: config.abTestingEnabled ?? true,
|
|
109
|
-
timeoutMs: config.timeoutMs ?? 1e3,
|
|
110
|
-
debug: config.debug ?? false
|
|
111
|
-
};
|
|
67
|
+
// src/masking.ts
|
|
68
|
+
var MASK_ERROR_MARKER = "<risicare:mask-error>";
|
|
69
|
+
var MASK_BUDGET_MS_PER_SPAN = 1;
|
|
70
|
+
var MASK_WARN_WINDOW_MS = 3e5;
|
|
71
|
+
var SCORE_COMMENT_KEY = "score.comment";
|
|
72
|
+
function maskText(mask, key, value, onError) {
|
|
73
|
+
return maskString(mask, key, value, onError);
|
|
112
74
|
}
|
|
113
|
-
function
|
|
114
|
-
|
|
115
|
-
return
|
|
75
|
+
function maskOne(mask, key, value, onError) {
|
|
76
|
+
try {
|
|
77
|
+
return mask(key, value);
|
|
78
|
+
} catch (e) {
|
|
79
|
+
onError?.(key, e);
|
|
80
|
+
return MASK_ERROR_MARKER;
|
|
116
81
|
}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
82
|
+
}
|
|
83
|
+
function maskString(mask, key, value, onError) {
|
|
84
|
+
const masked = maskOne(mask, key, value, onError);
|
|
85
|
+
if (typeof masked === "string") return masked;
|
|
86
|
+
try {
|
|
87
|
+
return String(masked);
|
|
88
|
+
} catch (e) {
|
|
89
|
+
onError?.(key, e);
|
|
90
|
+
return MASK_ERROR_MARKER;
|
|
120
91
|
}
|
|
121
|
-
return false;
|
|
122
92
|
}
|
|
123
|
-
function
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
return bucket < fix.trafficPercentage;
|
|
93
|
+
function maskAttributes(mask, prefix, attrs, onError) {
|
|
94
|
+
for (const k of Object.keys(attrs)) {
|
|
95
|
+
attrs[k] = maskOne(mask, prefix + k, attrs[k], onError);
|
|
96
|
+
}
|
|
128
97
|
}
|
|
129
|
-
function
|
|
130
|
-
return
|
|
131
|
-
fixId: item.id ?? item.fix_id ?? item.fixId ?? "",
|
|
132
|
-
deploymentId: item.deployment_id ?? item.deploymentId ?? "",
|
|
133
|
-
errorCode: item.error_code ?? item.errorCode ?? "",
|
|
134
|
-
fixType: item.fix_type ?? item.fixType ?? "prompt",
|
|
135
|
-
config: item.config ?? {},
|
|
136
|
-
trafficPercentage: item.traffic_percentage ?? item.trafficPercentage ?? 100,
|
|
137
|
-
version: item.version ?? 1
|
|
138
|
-
};
|
|
98
|
+
function isMasked(span) {
|
|
99
|
+
return span._risicareMasked === true;
|
|
139
100
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
101
|
+
function markMasked(span) {
|
|
102
|
+
try {
|
|
103
|
+
span._risicareMasked = true;
|
|
104
|
+
} catch {
|
|
105
|
+
debug("Could not mark span as masked; a re-queue may re-mask it");
|
|
143
106
|
}
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
_cache;
|
|
158
|
-
_stats;
|
|
159
|
-
constructor(config) {
|
|
160
|
-
this._enabled = config?.cacheEnabled ?? true;
|
|
161
|
-
this._ttlMs = config?.cacheTtlMs ?? 3e5;
|
|
162
|
-
this._maxEntries = config?.cacheMaxEntries ?? 1e3;
|
|
163
|
-
this._cache = /* @__PURE__ */ new Map();
|
|
164
|
-
this._stats = {
|
|
165
|
-
hits: 0,
|
|
166
|
-
misses: 0,
|
|
167
|
-
evictions: 0,
|
|
168
|
-
size: 0,
|
|
169
|
-
lastRefresh: null
|
|
170
|
-
};
|
|
171
|
-
}
|
|
172
|
-
/** Whether caching is enabled. */
|
|
173
|
-
get enabled() {
|
|
174
|
-
return this._enabled;
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
|
-
* Get a fix by error code.
|
|
178
|
-
*
|
|
179
|
-
* Checks exact match first, then scans for wildcard matches.
|
|
180
|
-
* Expired entries are evicted on access.
|
|
181
|
-
*/
|
|
182
|
-
get(errorCode) {
|
|
183
|
-
try {
|
|
184
|
-
if (!this._enabled) return null;
|
|
185
|
-
const now = Date.now();
|
|
186
|
-
const exactEntry = this._cache.get(errorCode);
|
|
187
|
-
if (exactEntry) {
|
|
188
|
-
if (exactEntry.expiresAt > now) {
|
|
189
|
-
this._stats.hits++;
|
|
190
|
-
return exactEntry.fix;
|
|
191
|
-
}
|
|
192
|
-
this._cache.delete(errorCode);
|
|
193
|
-
this._stats.evictions++;
|
|
194
|
-
}
|
|
195
|
-
for (const [key, entry] of this._cache) {
|
|
196
|
-
if (entry.expiresAt <= now) {
|
|
197
|
-
this._cache.delete(key);
|
|
198
|
-
this._stats.evictions++;
|
|
199
|
-
continue;
|
|
200
|
-
}
|
|
201
|
-
if (matchesError(entry.fix, errorCode)) {
|
|
202
|
-
this._stats.hits++;
|
|
203
|
-
return entry.fix;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
this._stats.misses++;
|
|
207
|
-
return null;
|
|
208
|
-
} catch (e) {
|
|
209
|
-
debug(`FixCache.get error: ${e}`);
|
|
210
|
-
return null;
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
/**
|
|
214
|
-
* Add a single fix to the cache.
|
|
215
|
-
*
|
|
216
|
-
* Evicts the oldest entry if at capacity.
|
|
217
|
-
*/
|
|
218
|
-
set(fix) {
|
|
219
|
-
try {
|
|
220
|
-
if (!this._enabled) return;
|
|
221
|
-
if (this._cache.size >= this._maxEntries) {
|
|
222
|
-
this._evictOldest();
|
|
223
|
-
}
|
|
224
|
-
const now = Date.now();
|
|
225
|
-
this._cache.set(fix.errorCode, {
|
|
226
|
-
fix,
|
|
227
|
-
createdAt: now,
|
|
228
|
-
expiresAt: now + this._ttlMs
|
|
229
|
-
});
|
|
230
|
-
this._stats.size = this._cache.size;
|
|
231
|
-
} catch (e) {
|
|
232
|
-
debug(`FixCache.set error: ${e}`);
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
/**
|
|
236
|
-
* Replace all cached fixes (bulk refresh).
|
|
237
|
-
*
|
|
238
|
-
* Clears the cache and populates with the given fixes.
|
|
239
|
-
*/
|
|
240
|
-
setAll(fixes) {
|
|
241
|
-
try {
|
|
242
|
-
if (!this._enabled) return;
|
|
243
|
-
this._cache.clear();
|
|
244
|
-
const now = Date.now();
|
|
245
|
-
for (const fix of fixes) {
|
|
246
|
-
if (this._cache.size >= this._maxEntries) break;
|
|
247
|
-
this._cache.set(fix.errorCode, {
|
|
248
|
-
fix,
|
|
249
|
-
createdAt: now,
|
|
250
|
-
expiresAt: now + this._ttlMs
|
|
251
|
-
});
|
|
252
|
-
}
|
|
253
|
-
this._stats.size = this._cache.size;
|
|
254
|
-
this._stats.lastRefresh = now;
|
|
255
|
-
} catch (e) {
|
|
256
|
-
debug(`FixCache.setAll error: ${e}`);
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
/**
|
|
260
|
-
* Get all non-expired fixes.
|
|
261
|
-
*/
|
|
262
|
-
getAll() {
|
|
263
|
-
try {
|
|
264
|
-
const now = Date.now();
|
|
265
|
-
const valid = [];
|
|
266
|
-
const expired = [];
|
|
267
|
-
for (const [key, entry] of this._cache) {
|
|
268
|
-
if (entry.expiresAt > now) {
|
|
269
|
-
valid.push(entry.fix);
|
|
270
|
-
} else {
|
|
271
|
-
expired.push(key);
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
for (const key of expired) {
|
|
275
|
-
this._cache.delete(key);
|
|
276
|
-
this._stats.evictions++;
|
|
277
|
-
}
|
|
278
|
-
this._stats.size = this._cache.size;
|
|
279
|
-
return valid;
|
|
280
|
-
} catch (e) {
|
|
281
|
-
debug(`FixCache.getAll error: ${e}`);
|
|
282
|
-
return [];
|
|
283
|
-
}
|
|
107
|
+
}
|
|
108
|
+
function applyMask(span, mask, onError) {
|
|
109
|
+
if (isMasked(span)) return;
|
|
110
|
+
if (span.attributes && typeof span.attributes === "object") {
|
|
111
|
+
maskAttributes(mask, "", span.attributes, onError);
|
|
112
|
+
}
|
|
113
|
+
if (span.statusMessage !== void 0) {
|
|
114
|
+
span.statusMessage = maskString(mask, "statusMessage", span.statusMessage, onError);
|
|
115
|
+
}
|
|
116
|
+
if (Array.isArray(span.events)) {
|
|
117
|
+
span.events.forEach((event, i) => {
|
|
118
|
+
if (event?.attributes && typeof event.attributes === "object") {
|
|
119
|
+
maskAttributes(mask, `events.${i}.attributes.`, event.attributes, onError);
|
|
284
120
|
}
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
}
|
|
292
|
-
/** Get cache statistics. */
|
|
293
|
-
get stats() {
|
|
294
|
-
this._stats.size = this._cache.size;
|
|
295
|
-
return { ...this._stats };
|
|
296
|
-
}
|
|
297
|
-
/** Evict the oldest cache entry. */
|
|
298
|
-
_evictOldest() {
|
|
299
|
-
if (this._cache.size === 0) return;
|
|
300
|
-
let oldestKey = null;
|
|
301
|
-
let oldestTime = Infinity;
|
|
302
|
-
for (const [key, entry] of this._cache) {
|
|
303
|
-
if (entry.createdAt < oldestTime) {
|
|
304
|
-
oldestTime = entry.createdAt;
|
|
305
|
-
oldestKey = key;
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
if (oldestKey !== null) {
|
|
309
|
-
this._cache.delete(oldestKey);
|
|
310
|
-
this._stats.evictions++;
|
|
311
|
-
}
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
if (Array.isArray(span.links)) {
|
|
124
|
+
span.links.forEach((link, i) => {
|
|
125
|
+
if (link?.attributes && typeof link.attributes === "object") {
|
|
126
|
+
maskAttributes(mask, `links.${i}.attributes.`, link.attributes, onError);
|
|
312
127
|
}
|
|
313
|
-
};
|
|
128
|
+
});
|
|
314
129
|
}
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
130
|
+
markMasked(span);
|
|
131
|
+
}
|
|
132
|
+
function applyMaskBatch(spans, mask, onError) {
|
|
133
|
+
let errors = 0;
|
|
134
|
+
let firstKey;
|
|
135
|
+
let firstError;
|
|
136
|
+
const report = (key, error) => {
|
|
137
|
+
errors++;
|
|
138
|
+
if (firstKey === void 0) {
|
|
139
|
+
firstKey = key;
|
|
140
|
+
firstError = error;
|
|
141
|
+
}
|
|
142
|
+
onError?.(key, error);
|
|
326
143
|
};
|
|
144
|
+
const started = Date.now();
|
|
145
|
+
for (const span of spans) {
|
|
146
|
+
applyMask(span, mask, report);
|
|
147
|
+
}
|
|
148
|
+
const elapsedMs = Date.now() - started;
|
|
149
|
+
if (errors > 0 && firstKey !== void 0) {
|
|
150
|
+
debug(`mask threw on ${errors} field(s); first: key=${firstKey} ${String(firstError)}`);
|
|
151
|
+
}
|
|
152
|
+
return { errors, elapsedMs };
|
|
327
153
|
}
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
154
|
+
function warnMaskErrors(batchErrors, totalErrors) {
|
|
155
|
+
warn(
|
|
156
|
+
`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.`
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
function warnMaskSlow(spanCount, elapsedMs) {
|
|
160
|
+
warn(
|
|
161
|
+
`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.`
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// src/exporters/batch.ts
|
|
166
|
+
var SHUTDOWN_RESERVE_MS = 100;
|
|
167
|
+
var SHUTDOWN_BUDGET_MS = 5e3;
|
|
168
|
+
var REFUSAL_WARN_WINDOW_MS = 3e5;
|
|
169
|
+
var DEFAULT_BATCH_SIZE = 500;
|
|
170
|
+
var MAX_ATTRIBUTE_PAIRS_PER_BATCH = 24e3;
|
|
171
|
+
var MAX_BATCH_BYTES = 8 * 1024 * 1024;
|
|
172
|
+
var SPAN_ENVELOPE_BYTES = 512;
|
|
173
|
+
var CHILD_ENVELOPE_BYTES = 128;
|
|
174
|
+
var SCALAR_BYTES = 24;
|
|
175
|
+
var LITERAL_BYTES = 5;
|
|
176
|
+
var EST_MAX_DEPTH = 4;
|
|
177
|
+
var EST_OPAQUE_VALUE_BYTES = 4096;
|
|
178
|
+
var utf8ByteLength = typeof Buffer !== "undefined" && typeof Buffer.byteLength === "function" ? (s) => Buffer.byteLength(s, "utf8") : (s) => s.length * 3;
|
|
179
|
+
function estStringBytes(s) {
|
|
180
|
+
return 2 + utf8ByteLength(s);
|
|
181
|
+
}
|
|
182
|
+
function estValueBytes(v, depth = 0) {
|
|
183
|
+
if (typeof v === "string") return estStringBytes(v);
|
|
184
|
+
if (v === null || v === void 0 || typeof v === "boolean") return LITERAL_BYTES;
|
|
185
|
+
if (typeof v === "number" || typeof v === "bigint") return SCALAR_BYTES;
|
|
186
|
+
if (Array.isArray(v) && depth < EST_MAX_DEPTH) {
|
|
187
|
+
let total = 2 + Math.max(0, v.length - 1);
|
|
188
|
+
for (const item of v) total += estValueBytes(item, depth + 1);
|
|
189
|
+
return total;
|
|
190
|
+
}
|
|
191
|
+
if (typeof v === "object" && depth < EST_MAX_DEPTH && Object.getPrototypeOf(v) === Object.prototype) {
|
|
192
|
+
let total = 2;
|
|
193
|
+
for (const [k, val] of Object.entries(v)) {
|
|
194
|
+
total += estStringBytes(k) + 2 + estValueBytes(val, depth + 1);
|
|
195
|
+
}
|
|
196
|
+
return total;
|
|
197
|
+
}
|
|
198
|
+
return EST_OPAQUE_VALUE_BYTES;
|
|
199
|
+
}
|
|
200
|
+
function estMappingBytes(m) {
|
|
201
|
+
let total = 0;
|
|
202
|
+
for (const [k, v] of Object.entries(m)) total += estStringBytes(k) + 2 + estValueBytes(v);
|
|
203
|
+
return total;
|
|
204
|
+
}
|
|
205
|
+
function spanBytesEstimate(span) {
|
|
206
|
+
try {
|
|
207
|
+
const s = span;
|
|
208
|
+
let total = SPAN_ENVELOPE_BYTES;
|
|
209
|
+
for (const field of ["name", "statusMessage"]) {
|
|
210
|
+
if (typeof s[field] === "string") total += estStringBytes(s[field]);
|
|
211
|
+
}
|
|
212
|
+
const attrs = s.attributes;
|
|
213
|
+
if (attrs != null && typeof attrs === "object" && !Array.isArray(attrs)) {
|
|
214
|
+
total += estMappingBytes(attrs);
|
|
215
|
+
}
|
|
216
|
+
for (const key of ["events", "links"]) {
|
|
217
|
+
const coll = s[key];
|
|
218
|
+
if (!Array.isArray(coll)) continue;
|
|
219
|
+
for (const child of coll) {
|
|
220
|
+
total += CHILD_ENVELOPE_BYTES;
|
|
221
|
+
const ca = child?.attributes;
|
|
222
|
+
if (ca != null && typeof ca === "object" && !Array.isArray(ca)) {
|
|
223
|
+
total += estMappingBytes(ca);
|
|
368
224
|
}
|
|
369
225
|
}
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
226
|
+
}
|
|
227
|
+
return total;
|
|
228
|
+
} catch {
|
|
229
|
+
return SPAN_ENVELOPE_BYTES;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
function spanAttrCount(span) {
|
|
233
|
+
const attrs = span.attributes;
|
|
234
|
+
if (attrs == null) return 0;
|
|
235
|
+
if (attrs instanceof Map) return attrs.size;
|
|
236
|
+
if (typeof attrs === "object") return Object.keys(attrs).length;
|
|
237
|
+
return 0;
|
|
238
|
+
}
|
|
239
|
+
var BatchSpanProcessor = class _BatchSpanProcessor {
|
|
240
|
+
_exporters;
|
|
241
|
+
_batchSize;
|
|
242
|
+
_batchTimeoutMs;
|
|
243
|
+
_maxQueueSize;
|
|
244
|
+
_debug;
|
|
245
|
+
_queue = [];
|
|
246
|
+
_timer = null;
|
|
247
|
+
_started = false;
|
|
248
|
+
_flushing = false;
|
|
249
|
+
_beforeExitHandler = null;
|
|
250
|
+
// Retry tracking for failed batches (Audit #5)
|
|
251
|
+
_retryCounts = /* @__PURE__ */ new Map();
|
|
252
|
+
static MAX_RETRIES = 3;
|
|
253
|
+
_lastRefusalWarnAt = Number.NEGATIVE_INFINITY;
|
|
254
|
+
// ── Masking (see `../masking.ts`) ──────────────────────────────────────────
|
|
255
|
+
_mask;
|
|
256
|
+
_lastMaskWarnAt = Number.NEGATIVE_INFINITY;
|
|
257
|
+
_lastSlowMaskWarnAt = Number.NEGATIVE_INFINITY;
|
|
258
|
+
// Metrics
|
|
259
|
+
/** DEPRECATED flat total. Retained as the exact SUM of
|
|
260
|
+
* `droppedSpansByReason` so existing readers keep working (RULING §5
|
|
261
|
+
* back-compat — the same deprecate-and-alias shape this codebase used for
|
|
262
|
+
* `complete`->`settled` and `spans_flushed_total`). Prefer the labelled
|
|
263
|
+
* record: one integer cannot tell an under-provisioned queue from a dead
|
|
264
|
+
* gateway from a redeploy. */
|
|
265
|
+
droppedSpans = 0;
|
|
266
|
+
droppedSpansByReason = {
|
|
267
|
+
queue_full: 0,
|
|
268
|
+
transport_refused: 0,
|
|
269
|
+
shutdown_residue: 0
|
|
270
|
+
};
|
|
271
|
+
exportedSpans = 0;
|
|
272
|
+
/** Export ATTEMPTS, not a span count. */
|
|
273
|
+
failedExports = 0;
|
|
274
|
+
/**
|
|
275
|
+
* Fields whose mask callback threw and were replaced with
|
|
276
|
+
* `MASK_ERROR_MARKER`. A FIELD count, not a span count — one span can
|
|
277
|
+
* contribute several. Non-zero means those fields carry a marker instead of
|
|
278
|
+
* data: a customer-code bug, not a transport one.
|
|
279
|
+
*/
|
|
280
|
+
maskErrors = 0;
|
|
281
|
+
constructor(options) {
|
|
282
|
+
this._exporters = [...options.exporters];
|
|
283
|
+
const requestedBatchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;
|
|
284
|
+
const clampedBatchSize = Math.max(1, Math.min(requestedBatchSize, 1e4));
|
|
285
|
+
if (clampedBatchSize !== requestedBatchSize) {
|
|
286
|
+
warn(
|
|
287
|
+
`batchSize=${requestedBatchSize} is outside the allowed range [1, 10000]; clamping to ${clampedBatchSize}`
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
this._batchSize = clampedBatchSize;
|
|
291
|
+
this._batchTimeoutMs = options.batchTimeoutMs ?? 1e3;
|
|
292
|
+
this._maxQueueSize = options.maxQueueSize ?? 1e4;
|
|
293
|
+
this._debug = options.debug ?? false;
|
|
294
|
+
this._mask = options.mask;
|
|
295
|
+
}
|
|
296
|
+
start() {
|
|
297
|
+
if (this._started) return;
|
|
298
|
+
this._started = true;
|
|
299
|
+
this._timer = setInterval(() => {
|
|
300
|
+
void this._exportBatch();
|
|
301
|
+
}, this._batchTimeoutMs);
|
|
302
|
+
this._timer.unref();
|
|
303
|
+
this._beforeExitHandler = () => {
|
|
304
|
+
void this.shutdown();
|
|
305
|
+
};
|
|
306
|
+
process.once("beforeExit", this._beforeExitHandler);
|
|
307
|
+
}
|
|
308
|
+
/** Record `count` discarded spans under `reason`.
|
|
309
|
+
*
|
|
310
|
+
* `droppedSpans` is maintained as the exact sum of the labelled counters
|
|
311
|
+
* (RULING §5 back-compat), so the locked pins — which read the flat
|
|
312
|
+
* integer — stay meaningful. */
|
|
313
|
+
_recordDropped(reason, count = 1) {
|
|
314
|
+
this.droppedSpans += count;
|
|
315
|
+
this.droppedSpansByReason[reason] += count;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Run the customer mask over a batch, in place. Never throws.
|
|
319
|
+
*
|
|
320
|
+
* Failure semantics are ruled in `../masking.ts`: a field whose mask throws
|
|
321
|
+
* becomes `MASK_ERROR_MARKER` and the span is kept. The counter is per FIELD;
|
|
322
|
+
* both warnings are rate-limited to one per window so a mask that throws on
|
|
323
|
+
* every span cannot flood the customer's logs — the same shape as the
|
|
324
|
+
* transport-refusal warning above.
|
|
325
|
+
*/
|
|
326
|
+
_applyMask(batch) {
|
|
327
|
+
const mask = this._mask;
|
|
328
|
+
if (mask === void 0) return;
|
|
329
|
+
const { errors, elapsedMs } = applyMaskBatch(batch, mask);
|
|
330
|
+
const now = Date.now();
|
|
331
|
+
if (errors > 0) {
|
|
332
|
+
this.maskErrors += errors;
|
|
333
|
+
if (now - this._lastMaskWarnAt > MASK_WARN_WINDOW_MS) {
|
|
334
|
+
this._lastMaskWarnAt = now;
|
|
335
|
+
warnMaskErrors(errors, this.maskErrors);
|
|
441
336
|
}
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
337
|
+
}
|
|
338
|
+
if (elapsedMs > MASK_BUDGET_MS_PER_SPAN * batch.length && now - this._lastSlowMaskWarnAt > MASK_WARN_WINDOW_MS) {
|
|
339
|
+
this._lastSlowMaskWarnAt = now;
|
|
340
|
+
warnMaskSlow(batch.length, elapsedMs);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Drain what we hold, or name what we could not (F-SDKDRAIN-001).
|
|
345
|
+
*
|
|
346
|
+
* Per RULING §4 (option E, hard-bounded) the drain loops until ONE of: the
|
|
347
|
+
* queue is empty; the deadline expires; or a full round completes with no
|
|
348
|
+
* exporter returning SUCCESS.
|
|
349
|
+
*
|
|
350
|
+
* ⚠ The `_flushing` handling is load-bearing, and `SDKDRAIN_JS_004` exists
|
|
351
|
+
* to catch its absence. `_exportBatch()` returns immediately when an export
|
|
352
|
+
* is already in flight (`:171`), so a loop that merely calls it again makes
|
|
353
|
+
* NO progress and abandons the queue exactly as before — measured at 900 of
|
|
354
|
+
* 1,000. We await a tick instead, the shape `flush()` already models.
|
|
355
|
+
*
|
|
356
|
+
* Anything still queued when the loop stops is COUNTED as `shutdown_residue`
|
|
357
|
+
* and announced with a WARNING. The warning is the primary signal, not the
|
|
358
|
+
* counter: a counter incremented inside `shutdown()` is written to memory
|
|
359
|
+
* about to be freed and has no reader (RULING §2 / §8.2).
|
|
360
|
+
*/
|
|
361
|
+
async shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
|
|
362
|
+
if (!this._started) return;
|
|
363
|
+
this._started = false;
|
|
364
|
+
if (this._timer) {
|
|
365
|
+
clearInterval(this._timer);
|
|
366
|
+
this._timer = null;
|
|
367
|
+
}
|
|
368
|
+
if (this._beforeExitHandler) {
|
|
369
|
+
process.removeListener("beforeExit", this._beforeExitHandler);
|
|
370
|
+
this._beforeExitHandler = null;
|
|
371
|
+
}
|
|
372
|
+
const reserveMs = Math.min(SHUTDOWN_RESERVE_MS, timeoutMs / 2);
|
|
373
|
+
const drainDeadline = Date.now() + Math.max(0, timeoutMs - reserveMs);
|
|
374
|
+
while (this._queue.length > 0 || this._flushing) {
|
|
375
|
+
if (Date.now() >= drainDeadline) break;
|
|
376
|
+
const outcome = await this._exportBatch();
|
|
377
|
+
if (outcome === 3 /* Busy */) {
|
|
378
|
+
await new Promise((r) => setTimeout(r, 1));
|
|
379
|
+
continue;
|
|
473
380
|
}
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
477
|
-
/**
|
|
478
|
-
* Apply a retry fix to an async operation.
|
|
479
|
-
*
|
|
480
|
-
* Retries with exponential backoff + jitter using
|
|
481
|
-
* `await new Promise(r => setTimeout(r, delay))`.
|
|
482
|
-
*/
|
|
483
|
-
async applyRetryFix(fix, operation) {
|
|
484
|
-
const cfg = fix.config;
|
|
485
|
-
const maxRetries = cfg.max_retries ?? cfg.maxRetries ?? 3;
|
|
486
|
-
const initialDelayMs = cfg.initial_delay_ms ?? cfg.initialDelayMs ?? 1e3;
|
|
487
|
-
const maxDelayMs = cfg.max_delay_ms ?? cfg.maxDelayMs ?? 3e4;
|
|
488
|
-
const exponentialBase = cfg.exponential_base ?? cfg.exponentialBase ?? 2;
|
|
489
|
-
const jitter = cfg.jitter ?? true;
|
|
490
|
-
const retryOn = cfg.retry_on ?? cfg.retryOn ?? [];
|
|
491
|
-
const result = emptyResult(fix, "retry");
|
|
492
|
-
if (this._config.dryRun) {
|
|
493
|
-
result.modifications = { maxRetries, initialDelayMs };
|
|
494
|
-
const value = await operation();
|
|
495
|
-
return { value, result };
|
|
496
|
-
}
|
|
497
|
-
let lastError = null;
|
|
498
|
-
let attempts = 0;
|
|
499
|
-
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
500
|
-
attempts++;
|
|
501
|
-
try {
|
|
502
|
-
const value = await operation();
|
|
503
|
-
result.applied = true;
|
|
504
|
-
result.modifications = { attempts };
|
|
505
|
-
return { value, result };
|
|
506
|
-
} catch (e) {
|
|
507
|
-
lastError = e instanceof Error ? e : new Error(String(e));
|
|
508
|
-
const errorType = lastError.constructor.name;
|
|
509
|
-
if (retryOn.length > 0 && !retryOn.includes(errorType)) {
|
|
510
|
-
throw lastError;
|
|
511
|
-
}
|
|
512
|
-
if (attempt < maxRetries) {
|
|
513
|
-
let delayMs = Math.min(
|
|
514
|
-
initialDelayMs * Math.pow(exponentialBase, attempt),
|
|
515
|
-
maxDelayMs
|
|
516
|
-
);
|
|
517
|
-
if (jitter) {
|
|
518
|
-
delayMs *= 0.5 + Math.random();
|
|
519
|
-
}
|
|
520
|
-
debug(
|
|
521
|
-
`Retry ${attempt + 1}/${maxRetries} after ${Math.round(delayMs)}ms`
|
|
522
|
-
);
|
|
523
|
-
await new Promise((r) => setTimeout(r, delayMs));
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
}
|
|
527
|
-
result.applied = true;
|
|
528
|
-
result.error = lastError?.message;
|
|
529
|
-
result.modifications = { attempts, exhausted: true };
|
|
530
|
-
throw lastError;
|
|
531
|
-
}
|
|
532
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
533
|
-
// 4. Fallback Fix
|
|
534
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
535
|
-
/**
|
|
536
|
-
* Apply a fallback fix.
|
|
537
|
-
*
|
|
538
|
-
* - 'model': Replace params.model with the fallback model
|
|
539
|
-
* - 'default': Set params._fallbackResponse for the caller to use
|
|
540
|
-
*/
|
|
541
|
-
applyFallbackFix(fix, params) {
|
|
542
|
-
try {
|
|
543
|
-
const cfg = fix.config;
|
|
544
|
-
const fallbackType = cfg.fallback_type ?? cfg.fallbackType ?? "model";
|
|
545
|
-
const fallbackConfig = cfg.fallback_config ?? cfg.fallbackConfig ?? {};
|
|
546
|
-
const result = emptyResult(fix, "fallback");
|
|
547
|
-
if (this._config.dryRun) {
|
|
548
|
-
result.modifications = { fallbackType, fallbackConfig };
|
|
549
|
-
return { params, result };
|
|
550
|
-
}
|
|
551
|
-
const modified = { ...params };
|
|
552
|
-
if (fallbackType === "model") {
|
|
553
|
-
const fallbackModel = fallbackConfig.model;
|
|
554
|
-
if (fallbackModel) {
|
|
555
|
-
modified.model = fallbackModel;
|
|
556
|
-
result.applied = true;
|
|
557
|
-
result.modifications = { model: fallbackModel };
|
|
558
|
-
}
|
|
559
|
-
} else if (fallbackType === "default") {
|
|
560
|
-
const defaultResponse = fallbackConfig.response;
|
|
561
|
-
if (defaultResponse !== void 0) {
|
|
562
|
-
modified._fallbackResponse = defaultResponse;
|
|
563
|
-
result.applied = true;
|
|
564
|
-
result.modifications = { defaultResponse: true };
|
|
565
|
-
}
|
|
566
|
-
}
|
|
567
|
-
return { params: modified, result };
|
|
568
|
-
} catch (e) {
|
|
569
|
-
debug(`applyFallbackFix error: ${e}`);
|
|
570
|
-
return {
|
|
571
|
-
params,
|
|
572
|
-
result: {
|
|
573
|
-
applied: false,
|
|
574
|
-
fixId: fix.fixId,
|
|
575
|
-
fixType: "fallback",
|
|
576
|
-
modifications: {},
|
|
577
|
-
error: String(e)
|
|
578
|
-
}
|
|
579
|
-
};
|
|
580
|
-
}
|
|
381
|
+
if (outcome !== 1 /* Delivered */) {
|
|
382
|
+
break;
|
|
581
383
|
}
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
const guardType = cfg.guard_type ?? cfg.guardType ?? "output_validation";
|
|
597
|
-
const guardConfig = cfg.guard_config ?? cfg.guardConfig ?? {};
|
|
598
|
-
const result = emptyResult(fix, "guard");
|
|
599
|
-
if (isInput && guardType !== "input_validation" && guardType !== "content_filter") {
|
|
600
|
-
return { content, passed: true, result };
|
|
601
|
-
}
|
|
602
|
-
if (!isInput && guardType !== "output_validation" && guardType !== "format_check") {
|
|
603
|
-
return { content, passed: true, result };
|
|
604
|
-
}
|
|
605
|
-
if (this._config.dryRun) {
|
|
606
|
-
result.modifications = { guardType };
|
|
607
|
-
return { content, passed: true, result };
|
|
608
|
-
}
|
|
609
|
-
let passed = true;
|
|
610
|
-
if (guardType === "content_filter") {
|
|
611
|
-
const blockedPatterns = guardConfig.blocked_patterns ?? guardConfig.blockedPatterns ?? [];
|
|
612
|
-
for (const pattern of blockedPatterns) {
|
|
613
|
-
const regex = this._safeCompileRegex(pattern);
|
|
614
|
-
if (regex && regex.test(content)) {
|
|
615
|
-
passed = false;
|
|
616
|
-
break;
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
} else if (guardType === "format_check") {
|
|
620
|
-
const requiredFormat = guardConfig.format;
|
|
621
|
-
if (requiredFormat === "json") {
|
|
622
|
-
try {
|
|
623
|
-
JSON.parse(content);
|
|
624
|
-
} catch {
|
|
625
|
-
passed = false;
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
} else if (guardType === "input_validation" || guardType === "output_validation") {
|
|
629
|
-
const minLength = guardConfig.min_length ?? guardConfig.minLength ?? 0;
|
|
630
|
-
const maxLength = guardConfig.max_length ?? guardConfig.maxLength ?? Infinity;
|
|
631
|
-
if (content.length < minLength || content.length > maxLength) {
|
|
632
|
-
passed = false;
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
result.applied = true;
|
|
636
|
-
result.modifications = { passed, guardType };
|
|
637
|
-
return { content, passed, result };
|
|
638
|
-
} catch (e) {
|
|
639
|
-
debug(`applyGuardFix error: ${e}`);
|
|
640
|
-
return {
|
|
641
|
-
content,
|
|
642
|
-
passed: true,
|
|
643
|
-
result: {
|
|
644
|
-
applied: false,
|
|
645
|
-
fixId: fix.fixId,
|
|
646
|
-
fixType: "guard",
|
|
647
|
-
modifications: {},
|
|
648
|
-
error: String(e)
|
|
649
|
-
}
|
|
650
|
-
};
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
654
|
-
// Application Log
|
|
655
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
656
|
-
/** Log a fix application result. */
|
|
657
|
-
logApplication(result) {
|
|
658
|
-
this._applicationLog.push(result);
|
|
659
|
-
if (this._applicationLog.length > 1e3) {
|
|
660
|
-
this._applicationLog = this._applicationLog.slice(-500);
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
/** Get the application log. */
|
|
664
|
-
getApplicationLog() {
|
|
665
|
-
return [...this._applicationLog];
|
|
666
|
-
}
|
|
667
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
668
|
-
// Private Helpers
|
|
669
|
-
// ═══════════════════════════════════════════════════════════════════════════
|
|
670
|
-
/**
|
|
671
|
-
* Safely compile a regex pattern from untrusted input.
|
|
672
|
-
* Returns null if invalid or too long.
|
|
673
|
-
*/
|
|
674
|
-
_safeCompileRegex(pattern, maxLength = 500) {
|
|
675
|
-
if (!pattern || pattern.length > maxLength) return null;
|
|
676
|
-
try {
|
|
677
|
-
return new RegExp(pattern, "i");
|
|
678
|
-
} catch {
|
|
679
|
-
debug(`Invalid regex pattern (length=${pattern.length})`);
|
|
680
|
-
return null;
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
/** Prepend content to the first message matching the target role. */
|
|
684
|
-
_prependToTarget(messages, target, content) {
|
|
685
|
-
return messages.map((msg) => {
|
|
686
|
-
if (msg.role === target) {
|
|
687
|
-
return {
|
|
688
|
-
...msg,
|
|
689
|
-
content: content + "\n\n" + (msg.content ?? "")
|
|
690
|
-
};
|
|
691
|
-
}
|
|
692
|
-
return msg;
|
|
693
|
-
});
|
|
694
|
-
}
|
|
695
|
-
/** Append content to the first message matching the target role. */
|
|
696
|
-
_appendToTarget(messages, target, content) {
|
|
697
|
-
return messages.map((msg) => {
|
|
698
|
-
if (msg.role === target) {
|
|
699
|
-
return {
|
|
700
|
-
...msg,
|
|
701
|
-
content: (msg.content ?? "") + "\n\n" + content
|
|
702
|
-
};
|
|
703
|
-
}
|
|
704
|
-
return msg;
|
|
705
|
-
});
|
|
384
|
+
}
|
|
385
|
+
const residue = this._queue.length;
|
|
386
|
+
if (residue > 0) {
|
|
387
|
+
this._queue.length = 0;
|
|
388
|
+
this._recordDropped("shutdown_residue", residue);
|
|
389
|
+
warn(
|
|
390
|
+
`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.`
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
for (const exporter of this._exporters) {
|
|
394
|
+
try {
|
|
395
|
+
await exporter.shutdown();
|
|
396
|
+
} catch (e) {
|
|
397
|
+
debug(`Error shutting down ${exporter.name}: ${e}`);
|
|
706
398
|
}
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
return msg;
|
|
720
|
-
});
|
|
399
|
+
}
|
|
400
|
+
this._retryCounts.clear();
|
|
401
|
+
debug(
|
|
402
|
+
`BatchSpanProcessor shutdown. Exported: ${this.exportedSpans}, Dropped: ${this.droppedSpans}, Failed: ${this.failedExports}`
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
onSpanEnd(span) {
|
|
406
|
+
if (!this._started) return;
|
|
407
|
+
if (this._queue.length >= this._maxQueueSize) {
|
|
408
|
+
this._recordDropped("queue_full");
|
|
409
|
+
if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
|
|
410
|
+
warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
|
|
721
411
|
}
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
this._queue.push(span);
|
|
415
|
+
if (this._queue.length >= this._batchSize) {
|
|
416
|
+
void this._exportBatch();
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Flush pending spans.
|
|
421
|
+
*
|
|
422
|
+
* @returns `true` only if everything queued at entry was DELIVERED.
|
|
423
|
+
*
|
|
424
|
+
* RULING §6. This used to answer a different question — "is the queue
|
|
425
|
+
* empty?" — and those two diverge in exactly one case: when spans left the
|
|
426
|
+
* queue WITHOUT reaching the transport. That case is the entire finding. A
|
|
427
|
+
* customer who calls `flush()` before exit and gets `true` has done
|
|
428
|
+
* everything right; silence lets them discover the problem, a false
|
|
429
|
+
* affirmative forecloses it.
|
|
430
|
+
*
|
|
431
|
+
* Returns `false` when (a) the deadline expires with spans still queued,
|
|
432
|
+
* (b) any span was discarded during the window — breaker refusal or retry
|
|
433
|
+
* exhaustion — or (c) it is called after `shutdown()` and the shutdown
|
|
434
|
+
* residue was non-zero.
|
|
435
|
+
*
|
|
436
|
+
* ⚠ (b) reads the flat total, so a concurrent `queue_full` drop of a span
|
|
437
|
+
* that arrived DURING the window also answers `false`. That is the
|
|
438
|
+
* conservative direction on purpose: a false negative costs a caller one
|
|
439
|
+
* more flush, a false positive is the defect being fixed.
|
|
440
|
+
*/
|
|
441
|
+
async flush(timeoutMs = SHUTDOWN_BUDGET_MS) {
|
|
442
|
+
if (!this._started) {
|
|
443
|
+
return this._queue.length === 0 && this.droppedSpansByReason.shutdown_residue === 0;
|
|
444
|
+
}
|
|
445
|
+
const start = Date.now();
|
|
446
|
+
const discardedAtEntry = this.droppedSpans;
|
|
447
|
+
while (this._queue.length > 0 || this._flushing) {
|
|
448
|
+
if (!this._flushing && this._queue.length > 0) {
|
|
449
|
+
await this._exportBatch();
|
|
450
|
+
} else {
|
|
451
|
+
await new Promise((r) => setTimeout(r, 1));
|
|
741
452
|
}
|
|
453
|
+
if (Date.now() - start > timeoutMs) return false;
|
|
454
|
+
}
|
|
455
|
+
return this.droppedSpans === discardedAtEntry;
|
|
456
|
+
}
|
|
457
|
+
getMetrics() {
|
|
458
|
+
return {
|
|
459
|
+
exportedSpans: this.exportedSpans,
|
|
460
|
+
droppedSpans: this.droppedSpans,
|
|
461
|
+
droppedSpansByReason: { ...this.droppedSpansByReason },
|
|
462
|
+
failedExports: this.failedExports,
|
|
463
|
+
maskErrors: this.maskErrors,
|
|
464
|
+
queueSize: this._queue.length,
|
|
465
|
+
queueCapacity: this._maxQueueSize,
|
|
466
|
+
queueUtilization: this._queue.length / this._maxQueueSize
|
|
742
467
|
};
|
|
743
468
|
}
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
_lastLoadTime = null;
|
|
760
|
-
_consecutiveFailures = 0;
|
|
761
|
-
_circuitOpenUntil = 0;
|
|
762
|
-
_onLoadCallbacks = [];
|
|
763
|
-
// Circuit breaker settings
|
|
764
|
-
static CIRCUIT_BREAKER_THRESHOLD = 3;
|
|
765
|
-
static CIRCUIT_BREAKER_COOLDOWN_MS = 3e4;
|
|
766
|
-
constructor(config, cache) {
|
|
767
|
-
this._config = resolveFixRuntimeConfig(config);
|
|
768
|
-
this._cache = cache;
|
|
769
|
-
}
|
|
770
|
-
/** Timestamp of last successful load. */
|
|
771
|
-
get lastLoadTime() {
|
|
772
|
-
return this._lastLoadTime;
|
|
773
|
-
}
|
|
774
|
-
/**
|
|
775
|
-
* Start the loader: perform initial load and start background refresh.
|
|
776
|
-
*
|
|
777
|
-
* Never throws — failures are logged and the runtime degrades gracefully.
|
|
778
|
-
*/
|
|
779
|
-
start() {
|
|
780
|
-
try {
|
|
781
|
-
if (!this._config.enabled) {
|
|
782
|
-
debug("Fix runtime disabled, skipping loader start");
|
|
783
|
-
return;
|
|
784
|
-
}
|
|
785
|
-
if (!this._config.apiKey) {
|
|
786
|
-
warn("No API key configured, fixes will not be loaded");
|
|
787
|
-
return;
|
|
788
|
-
}
|
|
789
|
-
this.loadSync().catch((e) => {
|
|
790
|
-
debug(`Initial fix load failed: ${e}`);
|
|
791
|
-
});
|
|
792
|
-
if (this._config.autoRefresh) {
|
|
793
|
-
this._startRefreshInterval();
|
|
794
|
-
}
|
|
795
|
-
} catch (e) {
|
|
796
|
-
debug(`FixLoader.start error: ${e}`);
|
|
469
|
+
async _exportBatch() {
|
|
470
|
+
if (this._flushing) return 3 /* Busy */;
|
|
471
|
+
if (this._queue.length === 0) return 0 /* Empty */;
|
|
472
|
+
this._flushing = true;
|
|
473
|
+
try {
|
|
474
|
+
let take = 0;
|
|
475
|
+
let pairs = 0;
|
|
476
|
+
let nbytes = 0;
|
|
477
|
+
const limit = Math.min(this._batchSize, this._queue.length);
|
|
478
|
+
while (take < limit) {
|
|
479
|
+
const head = this._queue[take];
|
|
480
|
+
const spanPairs = spanAttrCount(head);
|
|
481
|
+
const spanBytes = spanBytesEstimate(head);
|
|
482
|
+
if (take > 0 && (pairs + spanPairs > MAX_ATTRIBUTE_PAIRS_PER_BATCH || nbytes + spanBytes > MAX_BATCH_BYTES)) {
|
|
483
|
+
break;
|
|
797
484
|
}
|
|
485
|
+
pairs += spanPairs;
|
|
486
|
+
nbytes += spanBytes;
|
|
487
|
+
take++;
|
|
798
488
|
}
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
clearInterval(this._refreshTimer);
|
|
804
|
-
this._refreshTimer = null;
|
|
805
|
-
}
|
|
806
|
-
} catch (e) {
|
|
807
|
-
debug(`FixLoader.stop error: ${e}`);
|
|
808
|
-
}
|
|
489
|
+
const batch = this._queue.splice(0, take);
|
|
490
|
+
if (batch.length === 0) return 0 /* Empty */;
|
|
491
|
+
if (this._mask !== void 0) {
|
|
492
|
+
this._applyMask(batch);
|
|
809
493
|
}
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
onLoad(callback) {
|
|
814
|
-
this._onLoadCallbacks.push(callback);
|
|
815
|
-
}
|
|
816
|
-
/**
|
|
817
|
-
* Load fixes from the API.
|
|
818
|
-
*
|
|
819
|
-
* Name kept as "loadSync" for parity with the Python SDK, but this
|
|
820
|
-
* returns a Promise in JS (there's no synchronous fetch in Node.js).
|
|
821
|
-
*/
|
|
822
|
-
async loadSync() {
|
|
823
|
-
if (!this._config.apiKey) {
|
|
824
|
-
return [];
|
|
825
|
-
}
|
|
826
|
-
const now = Date.now();
|
|
827
|
-
if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && now < this._circuitOpenUntil) {
|
|
828
|
-
debug("Fix loader circuit breaker open \u2014 skipping load");
|
|
829
|
-
return this._cache.getAll();
|
|
830
|
-
}
|
|
494
|
+
debug(`Exporting batch of ${batch.length} spans`);
|
|
495
|
+
let batchExported = false;
|
|
496
|
+
for (const exporter of this._exporters) {
|
|
831
497
|
try {
|
|
832
|
-
const
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
"Content-Type": "application/json",
|
|
844
|
-
"X-Risicare-SDK-Version": SDK_VERSION2
|
|
845
|
-
},
|
|
846
|
-
signal: controller.signal
|
|
847
|
-
});
|
|
848
|
-
clearTimeout(timeoutId);
|
|
849
|
-
if (!response.ok) {
|
|
850
|
-
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
498
|
+
const result = await exporter.export(batch);
|
|
499
|
+
if (result === "success" /* SUCCESS */) {
|
|
500
|
+
if (!batchExported) {
|
|
501
|
+
this.exportedSpans += batch.length;
|
|
502
|
+
batchExported = true;
|
|
503
|
+
for (const span of batch) {
|
|
504
|
+
this._retryCounts.delete(span.spanId);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
} else {
|
|
508
|
+
this.failedExports++;
|
|
851
509
|
}
|
|
852
|
-
const data = await response.json();
|
|
853
|
-
const fixes = this._parseResponse(data);
|
|
854
|
-
this._onLoadSuccess(fixes);
|
|
855
|
-
return fixes;
|
|
856
510
|
} catch (e) {
|
|
857
|
-
this.
|
|
858
|
-
|
|
511
|
+
this.failedExports++;
|
|
512
|
+
debug(`Export to ${exporter.name} failed: ${e}`);
|
|
859
513
|
}
|
|
860
514
|
}
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
for (const item of items) {
|
|
871
|
-
try {
|
|
872
|
-
if (item && typeof item === "object") {
|
|
873
|
-
fixes.push(activeFixFromApiResponse(item));
|
|
874
|
-
}
|
|
875
|
-
} catch (e) {
|
|
876
|
-
debug(`Failed to parse fix item: ${e}`);
|
|
515
|
+
if (!batchExported) {
|
|
516
|
+
let dropped = 0;
|
|
517
|
+
const retryable = batch.filter((span) => {
|
|
518
|
+
const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;
|
|
519
|
+
if (count > _BatchSpanProcessor.MAX_RETRIES) {
|
|
520
|
+
this._retryCounts.delete(span.spanId);
|
|
521
|
+
this._recordDropped("transport_refused");
|
|
522
|
+
dropped++;
|
|
523
|
+
return false;
|
|
877
524
|
}
|
|
525
|
+
this._retryCounts.set(span.spanId, count);
|
|
526
|
+
return true;
|
|
527
|
+
});
|
|
528
|
+
if (retryable.length > 0) {
|
|
529
|
+
this._queue.unshift(...retryable);
|
|
530
|
+
debug(`Re-queued ${retryable.length} spans for retry (${batch.length - retryable.length} dropped after max retries)`);
|
|
878
531
|
}
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
try {
|
|
887
|
-
callback(fixes);
|
|
888
|
-
} catch (e) {
|
|
889
|
-
debug(`Load callback error: ${e}`);
|
|
532
|
+
if (dropped > 0) {
|
|
533
|
+
const now = Date.now();
|
|
534
|
+
if (now - this._lastRefusalWarnAt > REFUSAL_WARN_WINDOW_MS) {
|
|
535
|
+
this._lastRefusalWarnAt = now;
|
|
536
|
+
warn(
|
|
537
|
+
`${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.`
|
|
538
|
+
);
|
|
890
539
|
}
|
|
891
540
|
}
|
|
892
|
-
debug(`Loaded ${fixes.length} active fixes`);
|
|
893
|
-
}
|
|
894
|
-
_onLoadFailure(error) {
|
|
895
|
-
this._consecutiveFailures++;
|
|
896
|
-
if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD) {
|
|
897
|
-
this._circuitOpenUntil = Date.now() + _FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS;
|
|
898
|
-
warn(
|
|
899
|
-
`Fix loader circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${_FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS / 1e3}s`
|
|
900
|
-
);
|
|
901
|
-
} else {
|
|
902
|
-
debug(
|
|
903
|
-
`Fix load failed (attempt ${this._consecutiveFailures}): ${error.message}`
|
|
904
|
-
);
|
|
905
|
-
}
|
|
906
541
|
}
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
});
|
|
912
|
-
};
|
|
913
|
-
this._refreshTimer = setInterval(
|
|
914
|
-
() => {
|
|
915
|
-
if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && Date.now() < this._circuitOpenUntil) {
|
|
916
|
-
return;
|
|
917
|
-
}
|
|
918
|
-
tick();
|
|
919
|
-
},
|
|
920
|
-
this._config.refreshIntervalMs
|
|
921
|
-
);
|
|
922
|
-
this._refreshTimer.unref();
|
|
923
|
-
debug("Started fix refresh interval");
|
|
924
|
-
}
|
|
925
|
-
};
|
|
542
|
+
return batchExported ? 1 /* Delivered */ : 2 /* Failed */;
|
|
543
|
+
} finally {
|
|
544
|
+
this._flushing = false;
|
|
545
|
+
}
|
|
926
546
|
}
|
|
927
|
-
}
|
|
547
|
+
};
|
|
928
548
|
|
|
929
|
-
// src/
|
|
930
|
-
|
|
549
|
+
// src/config.ts
|
|
550
|
+
var DEFAULT_ENDPOINT = "https://app.risicare.ai";
|
|
551
|
+
function resolveConfig(config) {
|
|
552
|
+
const env = process.env;
|
|
553
|
+
const apiKey = config?.apiKey ?? env.RISICARE_API_KEY;
|
|
554
|
+
const endpoint = config?.endpoint ?? env.RISICARE_ENDPOINT ?? DEFAULT_ENDPOINT;
|
|
555
|
+
const projectId = config?.projectId ?? env.RISICARE_PROJECT_ID;
|
|
556
|
+
if (config?.projectId || env.RISICARE_PROJECT_ID) {
|
|
557
|
+
console.warn(
|
|
558
|
+
"[risicare] projectId is deprecated and ignored by the gateway. Your API key determines the project. Use serviceName and environment for within-project organization. projectId will be removed in v1.0."
|
|
559
|
+
);
|
|
560
|
+
}
|
|
561
|
+
const environment = config?.environment ?? env.RISICARE_ENVIRONMENT ?? "development";
|
|
562
|
+
const serviceName = config?.serviceName ?? env.RISICARE_SERVICE_NAME;
|
|
563
|
+
const serviceVersion = config?.serviceVersion ?? env.RISICARE_SERVICE_VERSION;
|
|
564
|
+
const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, true);
|
|
565
|
+
const sampleRateRaw = config?.sampleRate ?? parseFloat(env.RISICARE_SAMPLE_RATE ?? "1.0");
|
|
566
|
+
const debug2 = config?.debug ?? parseBool(env.RISICARE_DEBUG, false);
|
|
567
|
+
const compress = config?.compress ?? parseBool(env.RISICARE_COMPRESS, false);
|
|
568
|
+
const batchSizeRaw = config?.batchSize ?? parseNumericEnv(env.RISICARE_BATCH_SIZE, DEFAULT_BATCH_SIZE);
|
|
569
|
+
const batchTimeoutMsRaw = config?.batchTimeoutMs ?? parseNumericEnv(env.RISICARE_BATCH_TIMEOUT_MS, 1e3);
|
|
570
|
+
const maxQueueSizeRaw = config?.maxQueueSize ?? parseNumericEnv(env.RISICARE_MAX_QUEUE_SIZE, 1e4);
|
|
571
|
+
const sampleRate = validateSampleRate(sampleRateRaw);
|
|
572
|
+
const batchSize = validatePositiveInt("batchSize", batchSizeRaw, DEFAULT_BATCH_SIZE, 1, 1e4);
|
|
573
|
+
const batchTimeoutMs = validatePositiveInt("batchTimeoutMs", batchTimeoutMsRaw, 1e3, 1, 6e5);
|
|
574
|
+
const maxQueueSize = validatePositiveInt("maxQueueSize", maxQueueSizeRaw, 1e4, 1, 1e6);
|
|
575
|
+
let enabled;
|
|
576
|
+
if (config?.enabled !== void 0) {
|
|
577
|
+
enabled = config.enabled;
|
|
578
|
+
} else if (env.RISICARE_TRACING !== void 0) {
|
|
579
|
+
enabled = parseBool(env.RISICARE_TRACING, false);
|
|
580
|
+
} else {
|
|
581
|
+
enabled = !!apiKey;
|
|
582
|
+
}
|
|
931
583
|
return {
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
584
|
+
apiKey: apiKey ?? "",
|
|
585
|
+
endpoint,
|
|
586
|
+
projectId: projectId ?? "",
|
|
587
|
+
environment,
|
|
588
|
+
serviceName: serviceName ?? "",
|
|
589
|
+
serviceVersion: serviceVersion ?? "",
|
|
590
|
+
enabled,
|
|
591
|
+
traceContent,
|
|
592
|
+
sampleRate,
|
|
593
|
+
batchSize,
|
|
594
|
+
batchTimeoutMs,
|
|
595
|
+
maxQueueSize,
|
|
596
|
+
debug: debug2,
|
|
597
|
+
compress,
|
|
598
|
+
metadata: config?.metadata ?? {},
|
|
599
|
+
// No env fallback — see the field's note on RisicareConfig.
|
|
600
|
+
mask: config?.mask
|
|
939
601
|
};
|
|
940
602
|
}
|
|
941
|
-
function
|
|
942
|
-
|
|
943
|
-
const
|
|
944
|
-
|
|
945
|
-
|
|
603
|
+
function parseBool(value, defaultValue) {
|
|
604
|
+
if (value === void 0) return defaultValue;
|
|
605
|
+
const lower = value.toLowerCase();
|
|
606
|
+
return lower === "true" || lower === "1" || lower === "yes";
|
|
607
|
+
}
|
|
608
|
+
function parseNumericEnv(value, defaultValue) {
|
|
609
|
+
if (value === void 0) return defaultValue;
|
|
610
|
+
const n = Number(value);
|
|
611
|
+
return Number.isFinite(n) ? n : defaultValue;
|
|
612
|
+
}
|
|
613
|
+
function validateSampleRate(value) {
|
|
614
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1) {
|
|
615
|
+
return value;
|
|
946
616
|
}
|
|
947
|
-
if (
|
|
948
|
-
|
|
617
|
+
if (typeof value === "string") {
|
|
618
|
+
const n = Number(value);
|
|
619
|
+
if (Number.isFinite(n) && n >= 0 && n <= 1) return n;
|
|
949
620
|
}
|
|
950
|
-
|
|
951
|
-
|
|
621
|
+
console.warn(
|
|
622
|
+
`[risicare] sampleRate must be a finite number in [0, 1], got ${typeof value}=${JSON.stringify(value)}; defaulting to 1.0`
|
|
623
|
+
);
|
|
624
|
+
return 1;
|
|
625
|
+
}
|
|
626
|
+
function validatePositiveInt(name, value, defaultValue, min, max) {
|
|
627
|
+
let n;
|
|
628
|
+
if (typeof value === "number") {
|
|
629
|
+
n = value;
|
|
630
|
+
} else if (typeof value === "string") {
|
|
631
|
+
n = Number(value);
|
|
632
|
+
if (Number.isFinite(n)) {
|
|
633
|
+
console.warn(
|
|
634
|
+
`[risicare] ${name} was a string ("${value}"); coerced to ${n}. Pass a number to avoid this warning.`
|
|
635
|
+
);
|
|
636
|
+
}
|
|
637
|
+
} else {
|
|
638
|
+
console.warn(
|
|
639
|
+
`[risicare] ${name} must be a positive integer, got ${typeof value}; defaulting to ${defaultValue}`
|
|
640
|
+
);
|
|
641
|
+
return defaultValue;
|
|
952
642
|
}
|
|
953
|
-
if (
|
|
954
|
-
|
|
643
|
+
if (!Number.isFinite(n) || n <= 0) {
|
|
644
|
+
console.warn(
|
|
645
|
+
`[risicare] ${name} must be > 0, got ${value}; defaulting to ${defaultValue}`
|
|
646
|
+
);
|
|
647
|
+
return defaultValue;
|
|
955
648
|
}
|
|
956
|
-
if (
|
|
957
|
-
|
|
649
|
+
if (n < min) {
|
|
650
|
+
console.warn(`[risicare] ${name}=${n} below floor; clamping to ${min}`);
|
|
651
|
+
return min;
|
|
958
652
|
}
|
|
959
|
-
if (
|
|
960
|
-
|
|
653
|
+
if (n > max) {
|
|
654
|
+
console.warn(`[risicare] ${name}=${n} above ceiling; clamping to ${max}`);
|
|
655
|
+
return max;
|
|
961
656
|
}
|
|
962
|
-
return
|
|
963
|
-
}
|
|
964
|
-
var DefaultFixInterceptor;
|
|
965
|
-
var init_interceptors = __esm({
|
|
966
|
-
"src/runtime/interceptors.ts"() {
|
|
967
|
-
"use strict";
|
|
968
|
-
init_config();
|
|
969
|
-
init_log();
|
|
970
|
-
DefaultFixInterceptor = class {
|
|
971
|
-
_config;
|
|
972
|
-
_cache;
|
|
973
|
-
_applier;
|
|
974
|
-
constructor(config, cache, applier) {
|
|
975
|
-
this._config = resolveFixRuntimeConfig(config);
|
|
976
|
-
this._cache = cache;
|
|
977
|
-
this._applier = applier;
|
|
978
|
-
}
|
|
979
|
-
/**
|
|
980
|
-
* Apply pre-call fixes.
|
|
981
|
-
*
|
|
982
|
-
* - If retrying after error: look up fix by error_code, apply
|
|
983
|
-
* prompt/parameter/fallback fixes
|
|
984
|
-
* - Runs input guard fixes on all message content
|
|
985
|
-
*/
|
|
986
|
-
preCall(ctx, messages, params) {
|
|
987
|
-
try {
|
|
988
|
-
if (!this._config.enabled) {
|
|
989
|
-
return { messages, params };
|
|
990
|
-
}
|
|
991
|
-
let modifiedMessages = messages;
|
|
992
|
-
let modifiedParams = { ...params };
|
|
993
|
-
if (ctx.errorCode) {
|
|
994
|
-
const fix = this._applier.getFixForError(ctx.errorCode, ctx.sessionId);
|
|
995
|
-
if (fix) {
|
|
996
|
-
debug(`Applying fix ${fix.fixId} for ${ctx.errorCode}`);
|
|
997
|
-
if (fix.fixType === "prompt" && messages) {
|
|
998
|
-
const msgRecords = messages;
|
|
999
|
-
const { messages: newMessages, result } = this._applier.applyPromptFix(fix, msgRecords);
|
|
1000
|
-
modifiedMessages = newMessages;
|
|
1001
|
-
ctx.appliedFixes.push(result);
|
|
1002
|
-
this._applier.logApplication(result);
|
|
1003
|
-
} else if (fix.fixType === "parameter") {
|
|
1004
|
-
const { params: newParams, result } = this._applier.applyParameterFix(fix, modifiedParams);
|
|
1005
|
-
modifiedParams = newParams;
|
|
1006
|
-
ctx.appliedFixes.push(result);
|
|
1007
|
-
this._applier.logApplication(result);
|
|
1008
|
-
} else if (fix.fixType === "fallback") {
|
|
1009
|
-
const { params: newParams, result } = this._applier.applyFallbackFix(fix, modifiedParams);
|
|
1010
|
-
modifiedParams = newParams;
|
|
1011
|
-
ctx.appliedFixes.push(result);
|
|
1012
|
-
this._applier.logApplication(result);
|
|
1013
|
-
}
|
|
1014
|
-
}
|
|
1015
|
-
}
|
|
1016
|
-
if (modifiedMessages && this._config.enabled) {
|
|
1017
|
-
for (const msg of modifiedMessages) {
|
|
1018
|
-
const content = msg.content;
|
|
1019
|
-
if (typeof content === "string") {
|
|
1020
|
-
for (const fix of this._cache.getAll()) {
|
|
1021
|
-
if (fix.fixType === "guard") {
|
|
1022
|
-
const { result } = this._applier.applyGuardFix(
|
|
1023
|
-
fix,
|
|
1024
|
-
content,
|
|
1025
|
-
true
|
|
1026
|
-
);
|
|
1027
|
-
if (result.applied) {
|
|
1028
|
-
ctx.appliedFixes.push(result);
|
|
1029
|
-
this._applier.logApplication(result);
|
|
1030
|
-
}
|
|
1031
|
-
}
|
|
1032
|
-
}
|
|
1033
|
-
}
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
return { messages: modifiedMessages, params: modifiedParams };
|
|
1037
|
-
} catch (e) {
|
|
1038
|
-
debug(`DefaultFixInterceptor.preCall error: ${e}`);
|
|
1039
|
-
return { messages, params };
|
|
1040
|
-
}
|
|
1041
|
-
}
|
|
1042
|
-
/**
|
|
1043
|
-
* Apply post-call fixes (output validation).
|
|
1044
|
-
*
|
|
1045
|
-
* Runs output guard fixes on response content.
|
|
1046
|
-
*/
|
|
1047
|
-
postCall(ctx, response) {
|
|
1048
|
-
try {
|
|
1049
|
-
if (!this._config.enabled) {
|
|
1050
|
-
return { response, shouldContinue: true };
|
|
1051
|
-
}
|
|
1052
|
-
for (const fix of this._cache.getAll()) {
|
|
1053
|
-
if (fix.fixType !== "guard") continue;
|
|
1054
|
-
const content = this._extractResponseContent(response);
|
|
1055
|
-
if (!content) continue;
|
|
1056
|
-
const { passed, result } = this._applier.applyGuardFix(
|
|
1057
|
-
fix,
|
|
1058
|
-
content,
|
|
1059
|
-
false
|
|
1060
|
-
);
|
|
1061
|
-
if (result.applied) {
|
|
1062
|
-
ctx.appliedFixes.push(result);
|
|
1063
|
-
this._applier.logApplication(result);
|
|
1064
|
-
}
|
|
1065
|
-
if (!passed) {
|
|
1066
|
-
warn(`Output guard failed for fix ${fix.fixId}`);
|
|
1067
|
-
}
|
|
1068
|
-
}
|
|
1069
|
-
return { response, shouldContinue: true };
|
|
1070
|
-
} catch (e) {
|
|
1071
|
-
debug(`DefaultFixInterceptor.postCall error: ${e}`);
|
|
1072
|
-
return { response, shouldContinue: true };
|
|
1073
|
-
}
|
|
1074
|
-
}
|
|
1075
|
-
/**
|
|
1076
|
-
* Handle errors and decide whether to retry.
|
|
1077
|
-
*
|
|
1078
|
-
* Classifies the error, looks up retry/fallback fixes, and returns
|
|
1079
|
-
* whether the caller should retry.
|
|
1080
|
-
*/
|
|
1081
|
-
onError(ctx, error) {
|
|
1082
|
-
try {
|
|
1083
|
-
if (!this._config.enabled) {
|
|
1084
|
-
return { shouldRetry: false, modifiedParams: null };
|
|
1085
|
-
}
|
|
1086
|
-
const errorCode = classifyError(error);
|
|
1087
|
-
ctx.errorCode = errorCode;
|
|
1088
|
-
ctx.errorMessage = error.message;
|
|
1089
|
-
const fix = this._applier.getFixForError(errorCode, ctx.sessionId);
|
|
1090
|
-
if (!fix) {
|
|
1091
|
-
return { shouldRetry: false, modifiedParams: null };
|
|
1092
|
-
}
|
|
1093
|
-
if (fix.fixType === "retry") {
|
|
1094
|
-
const maxRetries = fix.config.max_retries ?? fix.config.maxRetries ?? 3;
|
|
1095
|
-
if (ctx.attempt <= maxRetries) {
|
|
1096
|
-
debug(
|
|
1097
|
-
`Retry fix ${fix.fixId}: attempt ${ctx.attempt}/${maxRetries}`
|
|
1098
|
-
);
|
|
1099
|
-
const result = {
|
|
1100
|
-
applied: true,
|
|
1101
|
-
fixId: fix.fixId,
|
|
1102
|
-
deploymentId: fix.deploymentId,
|
|
1103
|
-
fixType: "retry",
|
|
1104
|
-
modifications: { attempt: ctx.attempt }
|
|
1105
|
-
};
|
|
1106
|
-
ctx.appliedFixes.push(result);
|
|
1107
|
-
this._applier.logApplication(result);
|
|
1108
|
-
return { shouldRetry: true, modifiedParams: null };
|
|
1109
|
-
}
|
|
1110
|
-
}
|
|
1111
|
-
if (fix.fixType === "fallback") {
|
|
1112
|
-
const { params: modifiedParams, result } = this._applier.applyFallbackFix(fix, {});
|
|
1113
|
-
if (result.applied) {
|
|
1114
|
-
ctx.appliedFixes.push(result);
|
|
1115
|
-
this._applier.logApplication(result);
|
|
1116
|
-
return { shouldRetry: true, modifiedParams };
|
|
1117
|
-
}
|
|
1118
|
-
}
|
|
1119
|
-
return { shouldRetry: false, modifiedParams: null };
|
|
1120
|
-
} catch (e) {
|
|
1121
|
-
debug(`DefaultFixInterceptor.onError error: ${e}`);
|
|
1122
|
-
return { shouldRetry: false, modifiedParams: null };
|
|
1123
|
-
}
|
|
1124
|
-
}
|
|
1125
|
-
// ─── Private ────────────────────────────────────────────────────────────
|
|
1126
|
-
/** Extract text content from a response object. */
|
|
1127
|
-
_extractResponseContent(response) {
|
|
1128
|
-
if (typeof response === "string") return response;
|
|
1129
|
-
if (response && typeof response === "object") {
|
|
1130
|
-
const resp = response;
|
|
1131
|
-
const choices = resp.choices;
|
|
1132
|
-
if (Array.isArray(choices) && choices.length > 0) {
|
|
1133
|
-
const first = choices[0];
|
|
1134
|
-
const message = first?.message;
|
|
1135
|
-
if (typeof message?.content === "string") {
|
|
1136
|
-
return message.content;
|
|
1137
|
-
}
|
|
1138
|
-
}
|
|
1139
|
-
const content = resp.content;
|
|
1140
|
-
if (typeof content === "string") return content;
|
|
1141
|
-
if (Array.isArray(content) && content.length > 0) {
|
|
1142
|
-
const first = content[0];
|
|
1143
|
-
if (typeof first?.text === "string") return first.text;
|
|
1144
|
-
}
|
|
1145
|
-
}
|
|
1146
|
-
return null;
|
|
1147
|
-
}
|
|
1148
|
-
};
|
|
1149
|
-
}
|
|
1150
|
-
});
|
|
1151
|
-
|
|
1152
|
-
// src/runtime/runtime.ts
|
|
1153
|
-
var runtime_exports = {};
|
|
1154
|
-
__export(runtime_exports, {
|
|
1155
|
-
FixRuntime: () => FixRuntime,
|
|
1156
|
-
getFixRuntime: () => getFixRuntime,
|
|
1157
|
-
initFixRuntime: () => initFixRuntime,
|
|
1158
|
-
setFixRuntime: () => setFixRuntime,
|
|
1159
|
-
shutdownFixRuntime: () => shutdownFixRuntime
|
|
1160
|
-
});
|
|
1161
|
-
function getFixRuntime() {
|
|
1162
|
-
return G2[RUNTIME_KEY];
|
|
1163
|
-
}
|
|
1164
|
-
function setFixRuntime(runtime) {
|
|
1165
|
-
G2[RUNTIME_KEY] = runtime;
|
|
1166
|
-
}
|
|
1167
|
-
function initFixRuntime(config) {
|
|
1168
|
-
try {
|
|
1169
|
-
const existing = G2[RUNTIME_KEY];
|
|
1170
|
-
if (existing) {
|
|
1171
|
-
debug("Fix runtime already initialized");
|
|
1172
|
-
return existing;
|
|
1173
|
-
}
|
|
1174
|
-
const runtime = new FixRuntime(config);
|
|
1175
|
-
runtime.start();
|
|
1176
|
-
G2[RUNTIME_KEY] = runtime;
|
|
1177
|
-
return runtime;
|
|
1178
|
-
} catch (e) {
|
|
1179
|
-
warn(`initFixRuntime failed: ${e}`);
|
|
1180
|
-
const fallback = new FixRuntime({ ...config, enabled: false });
|
|
1181
|
-
G2[RUNTIME_KEY] = fallback;
|
|
1182
|
-
return fallback;
|
|
1183
|
-
}
|
|
1184
|
-
}
|
|
1185
|
-
function shutdownFixRuntime() {
|
|
1186
|
-
try {
|
|
1187
|
-
const runtime = G2[RUNTIME_KEY];
|
|
1188
|
-
if (runtime) {
|
|
1189
|
-
runtime.stop();
|
|
1190
|
-
}
|
|
1191
|
-
G2[RUNTIME_KEY] = void 0;
|
|
1192
|
-
} catch (e) {
|
|
1193
|
-
debug(`shutdownFixRuntime error: ${e}`);
|
|
1194
|
-
G2[RUNTIME_KEY] = void 0;
|
|
1195
|
-
}
|
|
1196
|
-
}
|
|
1197
|
-
var G2, RUNTIME_KEY, FixRuntime;
|
|
1198
|
-
var init_runtime = __esm({
|
|
1199
|
-
"src/runtime/runtime.ts"() {
|
|
1200
|
-
"use strict";
|
|
1201
|
-
init_cache();
|
|
1202
|
-
init_config();
|
|
1203
|
-
init_applier();
|
|
1204
|
-
init_loader();
|
|
1205
|
-
init_interceptors();
|
|
1206
|
-
init_log();
|
|
1207
|
-
G2 = globalThis;
|
|
1208
|
-
RUNTIME_KEY = "__risicare_fix_runtime";
|
|
1209
|
-
FixRuntime = class {
|
|
1210
|
-
_config;
|
|
1211
|
-
_cache;
|
|
1212
|
-
_loader;
|
|
1213
|
-
_applier;
|
|
1214
|
-
_interceptor;
|
|
1215
|
-
_started = false;
|
|
1216
|
-
// Effectiveness tracking
|
|
1217
|
-
_fixApplications = /* @__PURE__ */ new Map();
|
|
1218
|
-
_fixSuccesses = /* @__PURE__ */ new Map();
|
|
1219
|
-
constructor(config) {
|
|
1220
|
-
this._config = resolveFixRuntimeConfig(config);
|
|
1221
|
-
this._cache = new FixCache(this._config);
|
|
1222
|
-
this._loader = new FixLoader(config, this._cache);
|
|
1223
|
-
this._applier = new FixApplier(config, this._cache);
|
|
1224
|
-
this._interceptor = new DefaultFixInterceptor(
|
|
1225
|
-
config,
|
|
1226
|
-
this._cache,
|
|
1227
|
-
this._applier
|
|
1228
|
-
);
|
|
1229
|
-
}
|
|
1230
|
-
// ─── Accessors ──────────────────────────────────────────────────────────
|
|
1231
|
-
/** Runtime configuration (with defaults resolved). */
|
|
1232
|
-
get config() {
|
|
1233
|
-
return this._config;
|
|
1234
|
-
}
|
|
1235
|
-
/** Whether the runtime is enabled and started. */
|
|
1236
|
-
get isEnabled() {
|
|
1237
|
-
return this._config.enabled && this._started;
|
|
1238
|
-
}
|
|
1239
|
-
/** The fix cache. */
|
|
1240
|
-
get cache() {
|
|
1241
|
-
return this._cache;
|
|
1242
|
-
}
|
|
1243
|
-
/** The fix loader. */
|
|
1244
|
-
get loader() {
|
|
1245
|
-
return this._loader;
|
|
1246
|
-
}
|
|
1247
|
-
/** The fix applier. */
|
|
1248
|
-
get applier() {
|
|
1249
|
-
return this._applier;
|
|
1250
|
-
}
|
|
1251
|
-
/** The interceptor. */
|
|
1252
|
-
get interceptor() {
|
|
1253
|
-
return this._interceptor;
|
|
1254
|
-
}
|
|
1255
|
-
// ─── Lifecycle ──────────────────────────────────────────────────────────
|
|
1256
|
-
/**
|
|
1257
|
-
* Start the runtime.
|
|
1258
|
-
*
|
|
1259
|
-
* Triggers initial fix load and starts background refresh.
|
|
1260
|
-
* Never throws — failures degrade gracefully.
|
|
1261
|
-
*/
|
|
1262
|
-
start() {
|
|
1263
|
-
try {
|
|
1264
|
-
if (this._started) return;
|
|
1265
|
-
if (!this._config.enabled) {
|
|
1266
|
-
debug("Fix runtime disabled");
|
|
1267
|
-
return;
|
|
1268
|
-
}
|
|
1269
|
-
debug("Starting fix runtime...");
|
|
1270
|
-
this._loader.start();
|
|
1271
|
-
this._started = true;
|
|
1272
|
-
debug("Fix runtime started");
|
|
1273
|
-
} catch (e) {
|
|
1274
|
-
warn(`Fix runtime start failed: ${e}`);
|
|
1275
|
-
}
|
|
1276
|
-
}
|
|
1277
|
-
/**
|
|
1278
|
-
* Stop the runtime.
|
|
1279
|
-
*
|
|
1280
|
-
* Stops background refresh and clears the cache.
|
|
1281
|
-
* Never throws.
|
|
1282
|
-
*/
|
|
1283
|
-
stop() {
|
|
1284
|
-
try {
|
|
1285
|
-
if (!this._started) return;
|
|
1286
|
-
debug("Stopping fix runtime...");
|
|
1287
|
-
this._loader.stop();
|
|
1288
|
-
this._cache.clear();
|
|
1289
|
-
this._started = false;
|
|
1290
|
-
debug("Fix runtime stopped");
|
|
1291
|
-
} catch (e) {
|
|
1292
|
-
debug(`Fix runtime stop error: ${e}`);
|
|
1293
|
-
}
|
|
1294
|
-
}
|
|
1295
|
-
// ─── Intercept API ──────────────────────────────────────────────────────
|
|
1296
|
-
/**
|
|
1297
|
-
* Intercept a call: create context and run preCall fixes.
|
|
1298
|
-
*
|
|
1299
|
-
* Returns modified messages/params and the InterceptContext for
|
|
1300
|
-
* use in subsequent interceptResponse / interceptError calls.
|
|
1301
|
-
*/
|
|
1302
|
-
interceptCall(operationType, operationName, messages, params, options) {
|
|
1303
|
-
const ctx = createInterceptContext(operationType, operationName, options);
|
|
1304
|
-
try {
|
|
1305
|
-
if (!this.isEnabled) {
|
|
1306
|
-
return { messages, params, ctx };
|
|
1307
|
-
}
|
|
1308
|
-
const result = this._interceptor.preCall(ctx, messages, params);
|
|
1309
|
-
return { messages: result.messages, params: result.params, ctx };
|
|
1310
|
-
} catch (e) {
|
|
1311
|
-
debug(`interceptCall error: ${e}`);
|
|
1312
|
-
return { messages, params, ctx };
|
|
1313
|
-
}
|
|
1314
|
-
}
|
|
1315
|
-
/**
|
|
1316
|
-
* Intercept a response: run postCall fixes (output validation).
|
|
1317
|
-
*/
|
|
1318
|
-
interceptResponse(ctx, response) {
|
|
1319
|
-
try {
|
|
1320
|
-
if (!this.isEnabled) {
|
|
1321
|
-
return { response, shouldContinue: true };
|
|
1322
|
-
}
|
|
1323
|
-
const result = this._interceptor.postCall(ctx, response);
|
|
1324
|
-
this._trackSuccess(ctx);
|
|
1325
|
-
return result;
|
|
1326
|
-
} catch (e) {
|
|
1327
|
-
debug(`interceptResponse error: ${e}`);
|
|
1328
|
-
return { response, shouldContinue: true };
|
|
1329
|
-
}
|
|
1330
|
-
}
|
|
1331
|
-
/**
|
|
1332
|
-
* Intercept an error: decide on retry/fallback.
|
|
1333
|
-
*/
|
|
1334
|
-
interceptError(ctx, error) {
|
|
1335
|
-
try {
|
|
1336
|
-
if (!this.isEnabled) {
|
|
1337
|
-
return { shouldRetry: false, modifiedParams: null };
|
|
1338
|
-
}
|
|
1339
|
-
ctx.attempt++;
|
|
1340
|
-
const result = this._interceptor.onError(ctx, error);
|
|
1341
|
-
if (!result.shouldRetry) {
|
|
1342
|
-
this._trackFailure(ctx);
|
|
1343
|
-
}
|
|
1344
|
-
return result;
|
|
1345
|
-
} catch (e) {
|
|
1346
|
-
debug(`interceptError error: ${e}`);
|
|
1347
|
-
return { shouldRetry: false, modifiedParams: null };
|
|
1348
|
-
}
|
|
1349
|
-
}
|
|
1350
|
-
// ─── Direct Fix Access ──────────────────────────────────────────────────
|
|
1351
|
-
/**
|
|
1352
|
-
* Get applicable fix for an error code.
|
|
1353
|
-
*/
|
|
1354
|
-
getFix(errorCode, sessionId) {
|
|
1355
|
-
try {
|
|
1356
|
-
if (!this.isEnabled) return null;
|
|
1357
|
-
return this._applier.getFixForError(errorCode, sessionId);
|
|
1358
|
-
} catch (e) {
|
|
1359
|
-
debug(`getFix error: ${e}`);
|
|
1360
|
-
return null;
|
|
1361
|
-
}
|
|
1362
|
-
}
|
|
1363
|
-
/**
|
|
1364
|
-
* Manually refresh fixes from the API.
|
|
1365
|
-
*/
|
|
1366
|
-
async refreshFixes() {
|
|
1367
|
-
try {
|
|
1368
|
-
return await this._loader.loadSync();
|
|
1369
|
-
} catch (e) {
|
|
1370
|
-
debug(`refreshFixes error: ${e}`);
|
|
1371
|
-
return [];
|
|
1372
|
-
}
|
|
1373
|
-
}
|
|
1374
|
-
// ─── Effectiveness ──────────────────────────────────────────────────────
|
|
1375
|
-
/** Get effectiveness statistics for all fixes. */
|
|
1376
|
-
getEffectivenessStats() {
|
|
1377
|
-
const stats = {};
|
|
1378
|
-
for (const [fixId, applications] of this._fixApplications) {
|
|
1379
|
-
const successes = this._fixSuccesses.get(fixId) ?? 0;
|
|
1380
|
-
stats[fixId] = {
|
|
1381
|
-
applications,
|
|
1382
|
-
successes,
|
|
1383
|
-
successRate: applications > 0 ? successes / applications : 0
|
|
1384
|
-
};
|
|
1385
|
-
}
|
|
1386
|
-
return stats;
|
|
1387
|
-
}
|
|
1388
|
-
// ─── Private ────────────────────────────────────────────────────────────
|
|
1389
|
-
_trackSuccess(ctx) {
|
|
1390
|
-
for (const result of ctx.appliedFixes) {
|
|
1391
|
-
if (result.applied && result.fixId) {
|
|
1392
|
-
this._fixApplications.set(
|
|
1393
|
-
result.fixId,
|
|
1394
|
-
(this._fixApplications.get(result.fixId) ?? 0) + 1
|
|
1395
|
-
);
|
|
1396
|
-
this._fixSuccesses.set(
|
|
1397
|
-
result.fixId,
|
|
1398
|
-
(this._fixSuccesses.get(result.fixId) ?? 0) + 1
|
|
1399
|
-
);
|
|
1400
|
-
}
|
|
1401
|
-
}
|
|
1402
|
-
}
|
|
1403
|
-
_trackFailure(ctx) {
|
|
1404
|
-
for (const result of ctx.appliedFixes) {
|
|
1405
|
-
if (result.applied && result.fixId) {
|
|
1406
|
-
this._fixApplications.set(
|
|
1407
|
-
result.fixId,
|
|
1408
|
-
(this._fixApplications.get(result.fixId) ?? 0) + 1
|
|
1409
|
-
);
|
|
1410
|
-
}
|
|
1411
|
-
}
|
|
1412
|
-
}
|
|
1413
|
-
};
|
|
1414
|
-
}
|
|
1415
|
-
});
|
|
1416
|
-
|
|
1417
|
-
// src/config.ts
|
|
1418
|
-
var DEFAULT_ENDPOINT = "https://app.risicare.ai";
|
|
1419
|
-
function resolveConfig(config) {
|
|
1420
|
-
const env = process.env;
|
|
1421
|
-
const apiKey = config?.apiKey ?? env.RISICARE_API_KEY;
|
|
1422
|
-
const endpoint = config?.endpoint ?? env.RISICARE_ENDPOINT ?? DEFAULT_ENDPOINT;
|
|
1423
|
-
const projectId = config?.projectId ?? env.RISICARE_PROJECT_ID;
|
|
1424
|
-
if (config?.projectId || env.RISICARE_PROJECT_ID) {
|
|
1425
|
-
console.warn(
|
|
1426
|
-
"[risicare] projectId is deprecated and ignored by the gateway. Your API key determines the project. Use serviceName and environment for within-project organization. projectId will be removed in v1.0."
|
|
1427
|
-
);
|
|
1428
|
-
}
|
|
1429
|
-
const environment = config?.environment ?? env.RISICARE_ENVIRONMENT ?? "development";
|
|
1430
|
-
const serviceName = config?.serviceName ?? env.RISICARE_SERVICE_NAME;
|
|
1431
|
-
const serviceVersion = config?.serviceVersion ?? env.RISICARE_SERVICE_VERSION;
|
|
1432
|
-
const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, true);
|
|
1433
|
-
const sampleRate = config?.sampleRate ?? parseFloat(env.RISICARE_SAMPLE_RATE ?? "1.0");
|
|
1434
|
-
const debug2 = config?.debug ?? parseBool(env.RISICARE_DEBUG, false);
|
|
1435
|
-
const compress = config?.compress ?? parseBool(env.RISICARE_COMPRESS, false);
|
|
1436
|
-
const batchSize = config?.batchSize ?? 100;
|
|
1437
|
-
const batchTimeoutMs = config?.batchTimeoutMs ?? 1e3;
|
|
1438
|
-
const maxQueueSize = config?.maxQueueSize ?? 1e4;
|
|
1439
|
-
let enabled;
|
|
1440
|
-
if (config?.enabled !== void 0) {
|
|
1441
|
-
enabled = config.enabled;
|
|
1442
|
-
} else if (env.RISICARE_TRACING !== void 0) {
|
|
1443
|
-
enabled = parseBool(env.RISICARE_TRACING, false);
|
|
1444
|
-
} else {
|
|
1445
|
-
enabled = !!apiKey;
|
|
1446
|
-
}
|
|
1447
|
-
return {
|
|
1448
|
-
apiKey: apiKey ?? "",
|
|
1449
|
-
endpoint,
|
|
1450
|
-
projectId: projectId ?? "",
|
|
1451
|
-
environment,
|
|
1452
|
-
serviceName: serviceName ?? "",
|
|
1453
|
-
serviceVersion: serviceVersion ?? "",
|
|
1454
|
-
enabled,
|
|
1455
|
-
traceContent,
|
|
1456
|
-
sampleRate: Math.max(0, Math.min(1, sampleRate)),
|
|
1457
|
-
batchSize,
|
|
1458
|
-
batchTimeoutMs,
|
|
1459
|
-
maxQueueSize,
|
|
1460
|
-
debug: debug2,
|
|
1461
|
-
compress,
|
|
1462
|
-
metadata: config?.metadata ?? {}
|
|
1463
|
-
};
|
|
1464
|
-
}
|
|
1465
|
-
function parseBool(value, defaultValue) {
|
|
1466
|
-
if (value === void 0) return defaultValue;
|
|
1467
|
-
const lower = value.toLowerCase();
|
|
1468
|
-
return lower === "true" || lower === "1" || lower === "yes";
|
|
657
|
+
return Math.floor(n);
|
|
1469
658
|
}
|
|
1470
659
|
|
|
1471
660
|
// src/ids.ts
|
|
@@ -1820,7 +1009,6 @@ function shouldSample(traceId, sampleRate) {
|
|
|
1820
1009
|
}
|
|
1821
1010
|
|
|
1822
1011
|
// src/context/storage.ts
|
|
1823
|
-
init_globals();
|
|
1824
1012
|
function storage() {
|
|
1825
1013
|
return getContextStorage();
|
|
1826
1014
|
}
|
|
@@ -2018,234 +1206,77 @@ var Tracer = class {
|
|
|
2018
1206
|
}
|
|
2019
1207
|
};
|
|
2020
1208
|
|
|
2021
|
-
// src/
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
//
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
//
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
1209
|
+
// src/version.ts
|
|
1210
|
+
var SDK_VERSION = "0.5.0";
|
|
1211
|
+
|
|
1212
|
+
// src/exporters/http.ts
|
|
1213
|
+
var HttpExporter = class {
|
|
1214
|
+
name = "http";
|
|
1215
|
+
_endpoint;
|
|
1216
|
+
_apiKey;
|
|
1217
|
+
_projectId;
|
|
1218
|
+
_environment;
|
|
1219
|
+
_timeoutMs;
|
|
1220
|
+
_maxRetries;
|
|
1221
|
+
_compress;
|
|
1222
|
+
// Circuit breaker (CON-201 / B-16). Threshold and cooldown sized for
|
|
1223
|
+
// a "30-second prod restart" scenario: with default 1s batch flush a
|
|
1224
|
+
// 5-failure threshold opens the circuit ~5s into an outage and the 60s
|
|
1225
|
+
// cooldown gives the gateway time to come back before the half-open
|
|
1226
|
+
// probe fires. Lower numbers (was 3@30s) tripped on transient blips.
|
|
1227
|
+
_consecutiveFailures = 0;
|
|
1228
|
+
_circuitOpenUntil = 0;
|
|
1229
|
+
_circuitBreakerThreshold = 5;
|
|
1230
|
+
_circuitBreakerCooldownMs = 6e4;
|
|
2041
1231
|
constructor(options) {
|
|
2042
|
-
this.
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
1232
|
+
this._endpoint = options.endpoint.replace(/\/+$/, "");
|
|
1233
|
+
this._apiKey = options.apiKey;
|
|
1234
|
+
this._projectId = options.projectId;
|
|
1235
|
+
this._environment = options.environment;
|
|
1236
|
+
this._timeoutMs = options.timeoutMs ?? 5e3;
|
|
1237
|
+
this._maxRetries = options.maxRetries ?? 3;
|
|
1238
|
+
this._compress = options.compress ?? false;
|
|
1239
|
+
}
|
|
1240
|
+
async export(spans) {
|
|
1241
|
+
if (spans.length === 0) return "success" /* SUCCESS */;
|
|
1242
|
+
const now = Date.now();
|
|
1243
|
+
let isHalfOpen = false;
|
|
1244
|
+
if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
|
|
1245
|
+
if (now < this._circuitOpenUntil) {
|
|
1246
|
+
return "failure" /* FAILURE */;
|
|
1247
|
+
}
|
|
1248
|
+
isHalfOpen = true;
|
|
1249
|
+
}
|
|
1250
|
+
const body = {
|
|
1251
|
+
spans: spans.map((s) => s.toPayload())
|
|
1252
|
+
};
|
|
1253
|
+
if (this._projectId) body.projectId = this._projectId;
|
|
1254
|
+
if (this._environment) body.environment = this._environment;
|
|
1255
|
+
const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
|
|
1256
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1257
|
+
const result = await this._sendRequest(body);
|
|
1258
|
+
if (result === "success" /* SUCCESS */) {
|
|
1259
|
+
this._consecutiveFailures = 0;
|
|
1260
|
+
return result;
|
|
1261
|
+
}
|
|
1262
|
+
if (attempt < maxAttempts - 1) {
|
|
1263
|
+
await sleep(100 * Math.pow(2, attempt));
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
this._consecutiveFailures++;
|
|
1267
|
+
if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
|
|
1268
|
+
this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
|
|
2046
1269
|
warn(
|
|
2047
|
-
`
|
|
1270
|
+
`HTTP exporter circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${this._circuitBreakerCooldownMs / 1e3}s`
|
|
2048
1271
|
);
|
|
2049
1272
|
}
|
|
2050
|
-
|
|
2051
|
-
this._batchTimeoutMs = options.batchTimeoutMs ?? 1e3;
|
|
2052
|
-
this._maxQueueSize = options.maxQueueSize ?? 1e4;
|
|
2053
|
-
this._debug = options.debug ?? false;
|
|
1273
|
+
return "failure" /* FAILURE */;
|
|
2054
1274
|
}
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
}, this._batchTimeoutMs);
|
|
2061
|
-
this._timer.unref();
|
|
2062
|
-
this._beforeExitHandler = () => {
|
|
2063
|
-
void this.shutdown();
|
|
2064
|
-
};
|
|
2065
|
-
process.once("beforeExit", this._beforeExitHandler);
|
|
2066
|
-
}
|
|
2067
|
-
async shutdown(timeoutMs = 5e3) {
|
|
2068
|
-
if (!this._started) return;
|
|
2069
|
-
this._started = false;
|
|
2070
|
-
if (this._timer) {
|
|
2071
|
-
clearInterval(this._timer);
|
|
2072
|
-
this._timer = null;
|
|
2073
|
-
}
|
|
2074
|
-
if (this._beforeExitHandler) {
|
|
2075
|
-
process.removeListener("beforeExit", this._beforeExitHandler);
|
|
2076
|
-
this._beforeExitHandler = null;
|
|
2077
|
-
}
|
|
2078
|
-
const flushPromise = this._exportBatch();
|
|
2079
|
-
const timeoutPromise = new Promise((resolve) => setTimeout(resolve, timeoutMs));
|
|
2080
|
-
await Promise.race([flushPromise, timeoutPromise]);
|
|
2081
|
-
for (const exporter of this._exporters) {
|
|
2082
|
-
try {
|
|
2083
|
-
await exporter.shutdown();
|
|
2084
|
-
} catch (e) {
|
|
2085
|
-
debug(`Error shutting down ${exporter.name}: ${e}`);
|
|
2086
|
-
}
|
|
2087
|
-
}
|
|
2088
|
-
this._retryCounts.clear();
|
|
2089
|
-
debug(
|
|
2090
|
-
`BatchSpanProcessor shutdown. Exported: ${this.exportedSpans}, Dropped: ${this.droppedSpans}, Failed: ${this.failedExports}`
|
|
2091
|
-
);
|
|
2092
|
-
}
|
|
2093
|
-
onSpanEnd(span) {
|
|
2094
|
-
if (!this._started) return;
|
|
2095
|
-
if (this._queue.length >= this._maxQueueSize) {
|
|
2096
|
-
this.droppedSpans++;
|
|
2097
|
-
if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
|
|
2098
|
-
warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
|
|
2099
|
-
}
|
|
2100
|
-
return;
|
|
2101
|
-
}
|
|
2102
|
-
this._queue.push(span);
|
|
2103
|
-
if (this._queue.length >= this._batchSize) {
|
|
2104
|
-
void this._exportBatch();
|
|
2105
|
-
}
|
|
2106
|
-
}
|
|
2107
|
-
async flush(timeoutMs = 5e3) {
|
|
2108
|
-
if (!this._started) return true;
|
|
2109
|
-
const start = Date.now();
|
|
2110
|
-
while (this._queue.length > 0 || this._flushing) {
|
|
2111
|
-
if (!this._flushing && this._queue.length > 0) {
|
|
2112
|
-
await this._exportBatch();
|
|
2113
|
-
} else {
|
|
2114
|
-
await new Promise((r) => setTimeout(r, 1));
|
|
2115
|
-
}
|
|
2116
|
-
if (Date.now() - start > timeoutMs) return false;
|
|
2117
|
-
}
|
|
2118
|
-
return true;
|
|
2119
|
-
}
|
|
2120
|
-
getMetrics() {
|
|
2121
|
-
return {
|
|
2122
|
-
exportedSpans: this.exportedSpans,
|
|
2123
|
-
droppedSpans: this.droppedSpans,
|
|
2124
|
-
failedExports: this.failedExports,
|
|
2125
|
-
queueSize: this._queue.length,
|
|
2126
|
-
queueCapacity: this._maxQueueSize,
|
|
2127
|
-
queueUtilization: this._queue.length / this._maxQueueSize
|
|
2128
|
-
};
|
|
2129
|
-
}
|
|
2130
|
-
async _exportBatch() {
|
|
2131
|
-
if (this._flushing || this._queue.length === 0) return;
|
|
2132
|
-
this._flushing = true;
|
|
2133
|
-
try {
|
|
2134
|
-
const batch = this._queue.splice(0, this._batchSize);
|
|
2135
|
-
if (batch.length === 0) return;
|
|
2136
|
-
debug(`Exporting batch of ${batch.length} spans`);
|
|
2137
|
-
let batchExported = false;
|
|
2138
|
-
for (const exporter of this._exporters) {
|
|
2139
|
-
try {
|
|
2140
|
-
const result = await exporter.export(batch);
|
|
2141
|
-
if (result === "success" /* SUCCESS */) {
|
|
2142
|
-
if (!batchExported) {
|
|
2143
|
-
this.exportedSpans += batch.length;
|
|
2144
|
-
batchExported = true;
|
|
2145
|
-
for (const span of batch) {
|
|
2146
|
-
this._retryCounts.delete(span.spanId);
|
|
2147
|
-
}
|
|
2148
|
-
}
|
|
2149
|
-
} else {
|
|
2150
|
-
this.failedExports++;
|
|
2151
|
-
}
|
|
2152
|
-
} catch (e) {
|
|
2153
|
-
this.failedExports++;
|
|
2154
|
-
debug(`Export to ${exporter.name} failed: ${e}`);
|
|
2155
|
-
}
|
|
2156
|
-
}
|
|
2157
|
-
if (!batchExported) {
|
|
2158
|
-
const retryable = batch.filter((span) => {
|
|
2159
|
-
const count = (this._retryCounts.get(span.spanId) ?? 0) + 1;
|
|
2160
|
-
if (count > _BatchSpanProcessor.MAX_RETRIES) {
|
|
2161
|
-
this._retryCounts.delete(span.spanId);
|
|
2162
|
-
this.droppedSpans++;
|
|
2163
|
-
return false;
|
|
2164
|
-
}
|
|
2165
|
-
this._retryCounts.set(span.spanId, count);
|
|
2166
|
-
return true;
|
|
2167
|
-
});
|
|
2168
|
-
if (retryable.length > 0) {
|
|
2169
|
-
this._queue.unshift(...retryable);
|
|
2170
|
-
debug(`Re-queued ${retryable.length} spans for retry (${batch.length - retryable.length} dropped after max retries)`);
|
|
2171
|
-
}
|
|
2172
|
-
}
|
|
2173
|
-
} finally {
|
|
2174
|
-
this._flushing = false;
|
|
2175
|
-
}
|
|
2176
|
-
}
|
|
2177
|
-
};
|
|
2178
|
-
|
|
2179
|
-
// src/exporters/http.ts
|
|
2180
|
-
init_log();
|
|
2181
|
-
var SDK_VERSION = "0.1.1";
|
|
2182
|
-
var HttpExporter = class {
|
|
2183
|
-
name = "http";
|
|
2184
|
-
_endpoint;
|
|
2185
|
-
_apiKey;
|
|
2186
|
-
_projectId;
|
|
2187
|
-
_environment;
|
|
2188
|
-
_timeoutMs;
|
|
2189
|
-
_maxRetries;
|
|
2190
|
-
_compress;
|
|
2191
|
-
// Circuit breaker (CON-201 / B-16). Threshold and cooldown sized for
|
|
2192
|
-
// a "30-second prod restart" scenario: with default 1s batch flush a
|
|
2193
|
-
// 5-failure threshold opens the circuit ~5s into an outage and the 60s
|
|
2194
|
-
// cooldown gives the gateway time to come back before the half-open
|
|
2195
|
-
// probe fires. Lower numbers (was 3@30s) tripped on transient blips.
|
|
2196
|
-
_consecutiveFailures = 0;
|
|
2197
|
-
_circuitOpenUntil = 0;
|
|
2198
|
-
_circuitBreakerThreshold = 5;
|
|
2199
|
-
_circuitBreakerCooldownMs = 6e4;
|
|
2200
|
-
constructor(options) {
|
|
2201
|
-
this._endpoint = options.endpoint.replace(/\/+$/, "");
|
|
2202
|
-
this._apiKey = options.apiKey;
|
|
2203
|
-
this._projectId = options.projectId;
|
|
2204
|
-
this._environment = options.environment;
|
|
2205
|
-
this._timeoutMs = options.timeoutMs ?? 5e3;
|
|
2206
|
-
this._maxRetries = options.maxRetries ?? 3;
|
|
2207
|
-
this._compress = options.compress ?? false;
|
|
2208
|
-
}
|
|
2209
|
-
async export(spans) {
|
|
2210
|
-
if (spans.length === 0) return "success" /* SUCCESS */;
|
|
2211
|
-
const now = Date.now();
|
|
2212
|
-
let isHalfOpen = false;
|
|
2213
|
-
if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
|
|
2214
|
-
if (now < this._circuitOpenUntil) {
|
|
2215
|
-
return "failure" /* FAILURE */;
|
|
2216
|
-
}
|
|
2217
|
-
isHalfOpen = true;
|
|
2218
|
-
}
|
|
2219
|
-
const body = {
|
|
2220
|
-
spans: spans.map((s) => s.toPayload())
|
|
2221
|
-
};
|
|
2222
|
-
if (this._projectId) body.projectId = this._projectId;
|
|
2223
|
-
if (this._environment) body.environment = this._environment;
|
|
2224
|
-
const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
|
|
2225
|
-
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
2226
|
-
const result = await this._sendRequest(body);
|
|
2227
|
-
if (result === "success" /* SUCCESS */) {
|
|
2228
|
-
this._consecutiveFailures = 0;
|
|
2229
|
-
return result;
|
|
2230
|
-
}
|
|
2231
|
-
if (attempt < maxAttempts - 1) {
|
|
2232
|
-
await sleep(100 * Math.pow(2, attempt));
|
|
2233
|
-
}
|
|
2234
|
-
}
|
|
2235
|
-
this._consecutiveFailures++;
|
|
2236
|
-
if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
|
|
2237
|
-
this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
|
|
2238
|
-
warn(
|
|
2239
|
-
`HTTP exporter circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${this._circuitBreakerCooldownMs / 1e3}s`
|
|
2240
|
-
);
|
|
2241
|
-
}
|
|
2242
|
-
return "failure" /* FAILURE */;
|
|
2243
|
-
}
|
|
2244
|
-
async _sendRequest(body) {
|
|
2245
|
-
const url = `${this._endpoint}/v1/spans`;
|
|
2246
|
-
const headers = {
|
|
2247
|
-
"Content-Type": "application/json",
|
|
2248
|
-
"User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`
|
|
1275
|
+
async _sendRequest(body) {
|
|
1276
|
+
const url = `${this._endpoint}/v1/spans`;
|
|
1277
|
+
const headers = {
|
|
1278
|
+
"Content-Type": "application/json",
|
|
1279
|
+
"User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`
|
|
2249
1280
|
};
|
|
2250
1281
|
if (this._apiKey) {
|
|
2251
1282
|
headers["Authorization"] = `Bearer ${this._apiKey}`;
|
|
@@ -2302,17 +1333,1318 @@ var ConsoleExporter = class {
|
|
|
2302
1333
|
}
|
|
2303
1334
|
return "success" /* SUCCESS */;
|
|
2304
1335
|
}
|
|
2305
|
-
shutdown() {
|
|
1336
|
+
shutdown() {
|
|
1337
|
+
}
|
|
1338
|
+
};
|
|
1339
|
+
|
|
1340
|
+
// src/runtime/config.ts
|
|
1341
|
+
function resolveFixRuntimeConfig(config) {
|
|
1342
|
+
return {
|
|
1343
|
+
apiEndpoint: config.apiEndpoint,
|
|
1344
|
+
apiKey: config.apiKey,
|
|
1345
|
+
enabled: config.enabled ?? true,
|
|
1346
|
+
cacheEnabled: config.cacheEnabled ?? true,
|
|
1347
|
+
cacheTtlMs: config.cacheTtlMs ?? 3e5,
|
|
1348
|
+
cacheMaxEntries: config.cacheMaxEntries ?? 1e3,
|
|
1349
|
+
autoRefresh: config.autoRefresh ?? true,
|
|
1350
|
+
refreshIntervalMs: config.refreshIntervalMs ?? 6e4,
|
|
1351
|
+
dryRun: config.dryRun ?? false,
|
|
1352
|
+
abTestingEnabled: config.abTestingEnabled ?? true,
|
|
1353
|
+
timeoutMs: config.timeoutMs ?? 1e3,
|
|
1354
|
+
debug: config.debug ?? false
|
|
1355
|
+
};
|
|
1356
|
+
}
|
|
1357
|
+
function matchesError(fix, errorCode) {
|
|
1358
|
+
if (fix.errorCode === errorCode) {
|
|
1359
|
+
return true;
|
|
1360
|
+
}
|
|
1361
|
+
if (fix.errorCode.endsWith("*")) {
|
|
1362
|
+
const prefix = fix.errorCode.slice(0, -1);
|
|
1363
|
+
return errorCode.startsWith(prefix);
|
|
1364
|
+
}
|
|
1365
|
+
return false;
|
|
1366
|
+
}
|
|
1367
|
+
function shouldApply(fix, sessionHash) {
|
|
1368
|
+
if (fix.trafficPercentage >= 100) return true;
|
|
1369
|
+
if (fix.trafficPercentage <= 0) return false;
|
|
1370
|
+
const bucket = sessionHash % 100;
|
|
1371
|
+
return bucket < fix.trafficPercentage;
|
|
1372
|
+
}
|
|
1373
|
+
function activeFixFromApiResponse(item) {
|
|
1374
|
+
return {
|
|
1375
|
+
fixId: item.id ?? item.fix_id ?? item.fixId ?? "",
|
|
1376
|
+
deploymentId: item.deployment_id ?? item.deploymentId ?? "",
|
|
1377
|
+
errorCode: item.error_code ?? item.errorCode ?? "",
|
|
1378
|
+
fixType: item.fix_type ?? item.fixType ?? "prompt",
|
|
1379
|
+
config: item.config ?? {},
|
|
1380
|
+
trafficPercentage: item.traffic_percentage ?? item.trafficPercentage ?? 100,
|
|
1381
|
+
version: item.version ?? 1
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
// src/runtime/cache.ts
|
|
1386
|
+
var FixCache = class {
|
|
1387
|
+
_ttlMs;
|
|
1388
|
+
_maxEntries;
|
|
1389
|
+
_enabled;
|
|
1390
|
+
_cache;
|
|
1391
|
+
_stats;
|
|
1392
|
+
constructor(config) {
|
|
1393
|
+
this._enabled = config?.cacheEnabled ?? true;
|
|
1394
|
+
this._ttlMs = config?.cacheTtlMs ?? 3e5;
|
|
1395
|
+
this._maxEntries = config?.cacheMaxEntries ?? 1e3;
|
|
1396
|
+
this._cache = /* @__PURE__ */ new Map();
|
|
1397
|
+
this._stats = {
|
|
1398
|
+
hits: 0,
|
|
1399
|
+
misses: 0,
|
|
1400
|
+
evictions: 0,
|
|
1401
|
+
size: 0,
|
|
1402
|
+
lastRefresh: null
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
/** Whether caching is enabled. */
|
|
1406
|
+
get enabled() {
|
|
1407
|
+
return this._enabled;
|
|
1408
|
+
}
|
|
1409
|
+
/**
|
|
1410
|
+
* Get a fix by error code.
|
|
1411
|
+
*
|
|
1412
|
+
* Checks exact match first, then scans for wildcard matches.
|
|
1413
|
+
* Expired entries are evicted on access.
|
|
1414
|
+
*/
|
|
1415
|
+
get(errorCode) {
|
|
1416
|
+
try {
|
|
1417
|
+
if (!this._enabled) return null;
|
|
1418
|
+
const now = Date.now();
|
|
1419
|
+
const exactEntry = this._cache.get(errorCode);
|
|
1420
|
+
if (exactEntry) {
|
|
1421
|
+
if (exactEntry.expiresAt > now) {
|
|
1422
|
+
this._stats.hits++;
|
|
1423
|
+
return exactEntry.fix;
|
|
1424
|
+
}
|
|
1425
|
+
this._cache.delete(errorCode);
|
|
1426
|
+
this._stats.evictions++;
|
|
1427
|
+
}
|
|
1428
|
+
for (const [key, entry] of this._cache) {
|
|
1429
|
+
if (entry.expiresAt <= now) {
|
|
1430
|
+
this._cache.delete(key);
|
|
1431
|
+
this._stats.evictions++;
|
|
1432
|
+
continue;
|
|
1433
|
+
}
|
|
1434
|
+
if (matchesError(entry.fix, errorCode)) {
|
|
1435
|
+
this._stats.hits++;
|
|
1436
|
+
return entry.fix;
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
this._stats.misses++;
|
|
1440
|
+
return null;
|
|
1441
|
+
} catch (e) {
|
|
1442
|
+
debug(`FixCache.get error: ${e}`);
|
|
1443
|
+
return null;
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
/**
|
|
1447
|
+
* Add a single fix to the cache.
|
|
1448
|
+
*
|
|
1449
|
+
* Evicts the oldest entry if at capacity.
|
|
1450
|
+
*/
|
|
1451
|
+
set(fix) {
|
|
1452
|
+
try {
|
|
1453
|
+
if (!this._enabled) return;
|
|
1454
|
+
if (this._cache.size >= this._maxEntries) {
|
|
1455
|
+
this._evictOldest();
|
|
1456
|
+
}
|
|
1457
|
+
const now = Date.now();
|
|
1458
|
+
this._cache.set(fix.errorCode, {
|
|
1459
|
+
fix,
|
|
1460
|
+
createdAt: now,
|
|
1461
|
+
expiresAt: now + this._ttlMs
|
|
1462
|
+
});
|
|
1463
|
+
this._stats.size = this._cache.size;
|
|
1464
|
+
} catch (e) {
|
|
1465
|
+
debug(`FixCache.set error: ${e}`);
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
/**
|
|
1469
|
+
* Replace all cached fixes (bulk refresh).
|
|
1470
|
+
*
|
|
1471
|
+
* Clears the cache and populates with the given fixes.
|
|
1472
|
+
*/
|
|
1473
|
+
setAll(fixes) {
|
|
1474
|
+
try {
|
|
1475
|
+
if (!this._enabled) return;
|
|
1476
|
+
this._cache.clear();
|
|
1477
|
+
const now = Date.now();
|
|
1478
|
+
for (const fix of fixes) {
|
|
1479
|
+
if (this._cache.size >= this._maxEntries) break;
|
|
1480
|
+
this._cache.set(fix.errorCode, {
|
|
1481
|
+
fix,
|
|
1482
|
+
createdAt: now,
|
|
1483
|
+
expiresAt: now + this._ttlMs
|
|
1484
|
+
});
|
|
1485
|
+
}
|
|
1486
|
+
this._stats.size = this._cache.size;
|
|
1487
|
+
this._stats.lastRefresh = now;
|
|
1488
|
+
} catch (e) {
|
|
1489
|
+
debug(`FixCache.setAll error: ${e}`);
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
/**
|
|
1493
|
+
* Get all non-expired fixes.
|
|
1494
|
+
*/
|
|
1495
|
+
getAll() {
|
|
1496
|
+
try {
|
|
1497
|
+
const now = Date.now();
|
|
1498
|
+
const valid = [];
|
|
1499
|
+
const expired = [];
|
|
1500
|
+
for (const [key, entry] of this._cache) {
|
|
1501
|
+
if (entry.expiresAt > now) {
|
|
1502
|
+
valid.push(entry.fix);
|
|
1503
|
+
} else {
|
|
1504
|
+
expired.push(key);
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
for (const key of expired) {
|
|
1508
|
+
this._cache.delete(key);
|
|
1509
|
+
this._stats.evictions++;
|
|
1510
|
+
}
|
|
1511
|
+
this._stats.size = this._cache.size;
|
|
1512
|
+
return valid;
|
|
1513
|
+
} catch (e) {
|
|
1514
|
+
debug(`FixCache.getAll error: ${e}`);
|
|
1515
|
+
return [];
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
/** Clear all cache entries. Returns the number of entries cleared. */
|
|
1519
|
+
clear() {
|
|
1520
|
+
const count = this._cache.size;
|
|
1521
|
+
this._cache.clear();
|
|
1522
|
+
this._stats.size = 0;
|
|
1523
|
+
return count;
|
|
1524
|
+
}
|
|
1525
|
+
/** Get cache statistics. */
|
|
1526
|
+
get stats() {
|
|
1527
|
+
this._stats.size = this._cache.size;
|
|
1528
|
+
return { ...this._stats };
|
|
1529
|
+
}
|
|
1530
|
+
/** Evict the oldest cache entry. */
|
|
1531
|
+
_evictOldest() {
|
|
1532
|
+
if (this._cache.size === 0) return;
|
|
1533
|
+
let oldestKey = null;
|
|
1534
|
+
let oldestTime = Infinity;
|
|
1535
|
+
for (const [key, entry] of this._cache) {
|
|
1536
|
+
if (entry.createdAt < oldestTime) {
|
|
1537
|
+
oldestTime = entry.createdAt;
|
|
1538
|
+
oldestKey = key;
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
if (oldestKey !== null) {
|
|
1542
|
+
this._cache.delete(oldestKey);
|
|
1543
|
+
this._stats.evictions++;
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
};
|
|
1547
|
+
|
|
1548
|
+
// src/runtime/applier.ts
|
|
1549
|
+
import { createHash } from "crypto";
|
|
1550
|
+
var MAX_FIX_CONTENT_LENGTH = 1e4;
|
|
1551
|
+
function emptyResult(fix, fixType) {
|
|
1552
|
+
return {
|
|
1553
|
+
applied: false,
|
|
1554
|
+
fixId: fix.fixId,
|
|
1555
|
+
deploymentId: fix.deploymentId,
|
|
1556
|
+
fixType,
|
|
1557
|
+
modifications: {}
|
|
1558
|
+
};
|
|
1559
|
+
}
|
|
1560
|
+
var FixApplier = class {
|
|
1561
|
+
_config;
|
|
1562
|
+
_cache;
|
|
1563
|
+
_applicationLog = [];
|
|
1564
|
+
constructor(config, cache) {
|
|
1565
|
+
this._config = resolveFixRuntimeConfig(config);
|
|
1566
|
+
this._cache = cache;
|
|
1567
|
+
}
|
|
1568
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1569
|
+
// Fix Lookup
|
|
1570
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1571
|
+
/**
|
|
1572
|
+
* Get applicable fix for an error code.
|
|
1573
|
+
*
|
|
1574
|
+
* Considers A/B testing bucket if sessionId is provided. Uses
|
|
1575
|
+
* crypto.createHash('md5') for deterministic bucketing across restarts.
|
|
1576
|
+
*/
|
|
1577
|
+
getFixForError(errorCode, sessionId) {
|
|
1578
|
+
try {
|
|
1579
|
+
const fix = this._cache.get(errorCode);
|
|
1580
|
+
if (!fix) return null;
|
|
1581
|
+
if (sessionId && this._config.abTestingEnabled) {
|
|
1582
|
+
const hashHex = createHash("md5").update(sessionId).digest("hex").substring(0, 8);
|
|
1583
|
+
const sessionHash = parseInt(hashHex, 16);
|
|
1584
|
+
if (!shouldApply(fix, sessionHash)) {
|
|
1585
|
+
debug(`Fix ${fix.fixId} not applied (A/B control group)`);
|
|
1586
|
+
return null;
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
return fix;
|
|
1590
|
+
} catch (e) {
|
|
1591
|
+
debug(`getFixForError error: ${e}`);
|
|
1592
|
+
return null;
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1596
|
+
// 1. Prompt Fix
|
|
1597
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1598
|
+
/**
|
|
1599
|
+
* Apply a prompt fix to messages.
|
|
1600
|
+
*
|
|
1601
|
+
* Supports 4 modification types:
|
|
1602
|
+
* - prepend: Add content before first system message
|
|
1603
|
+
* - append: Add content after first system message
|
|
1604
|
+
* - replace: Regex replace across all messages
|
|
1605
|
+
* - few_shot: Insert user/assistant example pairs after system message
|
|
1606
|
+
*/
|
|
1607
|
+
applyPromptFix(fix, messages) {
|
|
1608
|
+
try {
|
|
1609
|
+
const cfg = fix.config;
|
|
1610
|
+
const modificationType = cfg.modification_type ?? cfg.modificationType ?? "append";
|
|
1611
|
+
const target = cfg.target ?? "system";
|
|
1612
|
+
let content = cfg.content ?? "";
|
|
1613
|
+
if (content.length > MAX_FIX_CONTENT_LENGTH) {
|
|
1614
|
+
warn(
|
|
1615
|
+
`Fix ${fix.fixId} content truncated from ${content.length} to ${MAX_FIX_CONTENT_LENGTH} chars`
|
|
1616
|
+
);
|
|
1617
|
+
content = content.slice(0, MAX_FIX_CONTENT_LENGTH);
|
|
1618
|
+
}
|
|
1619
|
+
const result = emptyResult(fix, "prompt");
|
|
1620
|
+
if (this._config.dryRun) {
|
|
1621
|
+
result.modifications = {
|
|
1622
|
+
type: modificationType,
|
|
1623
|
+
target,
|
|
1624
|
+
contentPreview: content.slice(0, 100)
|
|
1625
|
+
};
|
|
1626
|
+
return { messages, result };
|
|
1627
|
+
}
|
|
1628
|
+
let modified = messages.map((m) => ({ ...m }));
|
|
1629
|
+
if (modificationType === "prepend") {
|
|
1630
|
+
modified = this._prependToTarget(modified, target, content);
|
|
1631
|
+
result.applied = true;
|
|
1632
|
+
result.modifications = { type: "prepend", target };
|
|
1633
|
+
} else if (modificationType === "append") {
|
|
1634
|
+
modified = this._appendToTarget(modified, target, content);
|
|
1635
|
+
result.applied = true;
|
|
1636
|
+
result.modifications = { type: "append", target };
|
|
1637
|
+
} else if (modificationType === "replace") {
|
|
1638
|
+
const pattern = cfg.pattern ?? "";
|
|
1639
|
+
if (pattern) {
|
|
1640
|
+
modified = this._replaceInMessages(modified, pattern, content);
|
|
1641
|
+
result.applied = true;
|
|
1642
|
+
result.modifications = { type: "replace", pattern };
|
|
1643
|
+
}
|
|
1644
|
+
} else if (modificationType === "few_shot") {
|
|
1645
|
+
const examples = cfg.examples ?? [];
|
|
1646
|
+
if (examples.length > 0) {
|
|
1647
|
+
modified = this._addFewShotExamples(modified, examples);
|
|
1648
|
+
result.applied = true;
|
|
1649
|
+
result.modifications = { type: "few_shot", count: examples.length };
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
return { messages: modified, result };
|
|
1653
|
+
} catch (e) {
|
|
1654
|
+
debug(`applyPromptFix error: ${e}`);
|
|
1655
|
+
return {
|
|
1656
|
+
messages,
|
|
1657
|
+
result: {
|
|
1658
|
+
applied: false,
|
|
1659
|
+
fixId: fix.fixId,
|
|
1660
|
+
fixType: "prompt",
|
|
1661
|
+
modifications: {},
|
|
1662
|
+
error: String(e)
|
|
1663
|
+
}
|
|
1664
|
+
};
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1668
|
+
// 2. Parameter Fix
|
|
1669
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1670
|
+
/**
|
|
1671
|
+
* Apply a parameter fix — merge config.parameters into params.
|
|
1672
|
+
*/
|
|
1673
|
+
applyParameterFix(fix, params) {
|
|
1674
|
+
try {
|
|
1675
|
+
const newParams = fix.config.parameters ?? {};
|
|
1676
|
+
const result = emptyResult(fix, "parameter");
|
|
1677
|
+
if (this._config.dryRun) {
|
|
1678
|
+
result.modifications = { parameters: newParams };
|
|
1679
|
+
return { params, result };
|
|
1680
|
+
}
|
|
1681
|
+
const modified = { ...params, ...newParams };
|
|
1682
|
+
result.applied = true;
|
|
1683
|
+
result.modifications = { parameters: newParams };
|
|
1684
|
+
return { params: modified, result };
|
|
1685
|
+
} catch (e) {
|
|
1686
|
+
debug(`applyParameterFix error: ${e}`);
|
|
1687
|
+
return {
|
|
1688
|
+
params,
|
|
1689
|
+
result: {
|
|
1690
|
+
applied: false,
|
|
1691
|
+
fixId: fix.fixId,
|
|
1692
|
+
fixType: "parameter",
|
|
1693
|
+
modifications: {},
|
|
1694
|
+
error: String(e)
|
|
1695
|
+
}
|
|
1696
|
+
};
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1700
|
+
// 3. Retry Fix (async — uses setTimeout for sleeping)
|
|
1701
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1702
|
+
/**
|
|
1703
|
+
* Apply a retry fix to an async operation.
|
|
1704
|
+
*
|
|
1705
|
+
* Retries with exponential backoff + jitter using
|
|
1706
|
+
* `await new Promise(r => setTimeout(r, delay))`.
|
|
1707
|
+
*/
|
|
1708
|
+
async applyRetryFix(fix, operation) {
|
|
1709
|
+
const cfg = fix.config;
|
|
1710
|
+
const maxRetries = cfg.max_retries ?? cfg.maxRetries ?? 3;
|
|
1711
|
+
const initialDelayMs = cfg.initial_delay_ms ?? cfg.initialDelayMs ?? 1e3;
|
|
1712
|
+
const maxDelayMs = cfg.max_delay_ms ?? cfg.maxDelayMs ?? 3e4;
|
|
1713
|
+
const exponentialBase = cfg.exponential_base ?? cfg.exponentialBase ?? 2;
|
|
1714
|
+
const jitter = cfg.jitter ?? true;
|
|
1715
|
+
const retryOn = cfg.retry_on ?? cfg.retryOn ?? [];
|
|
1716
|
+
const result = emptyResult(fix, "retry");
|
|
1717
|
+
if (this._config.dryRun) {
|
|
1718
|
+
result.modifications = { maxRetries, initialDelayMs };
|
|
1719
|
+
const value = await operation();
|
|
1720
|
+
return { value, result };
|
|
1721
|
+
}
|
|
1722
|
+
let lastError = null;
|
|
1723
|
+
let attempts = 0;
|
|
1724
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
1725
|
+
attempts++;
|
|
1726
|
+
try {
|
|
1727
|
+
const value = await operation();
|
|
1728
|
+
result.applied = true;
|
|
1729
|
+
result.modifications = { attempts };
|
|
1730
|
+
return { value, result };
|
|
1731
|
+
} catch (e) {
|
|
1732
|
+
lastError = e instanceof Error ? e : new Error(String(e));
|
|
1733
|
+
const errorType = lastError.constructor.name;
|
|
1734
|
+
if (retryOn.length > 0 && !retryOn.includes(errorType)) {
|
|
1735
|
+
throw lastError;
|
|
1736
|
+
}
|
|
1737
|
+
if (attempt < maxRetries) {
|
|
1738
|
+
let delayMs = Math.min(
|
|
1739
|
+
initialDelayMs * Math.pow(exponentialBase, attempt),
|
|
1740
|
+
maxDelayMs
|
|
1741
|
+
);
|
|
1742
|
+
if (jitter) {
|
|
1743
|
+
delayMs *= 0.5 + Math.random();
|
|
1744
|
+
}
|
|
1745
|
+
debug(
|
|
1746
|
+
`Retry ${attempt + 1}/${maxRetries} after ${Math.round(delayMs)}ms`
|
|
1747
|
+
);
|
|
1748
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
result.applied = true;
|
|
1753
|
+
result.error = lastError?.message;
|
|
1754
|
+
result.modifications = { attempts, exhausted: true };
|
|
1755
|
+
throw lastError;
|
|
1756
|
+
}
|
|
1757
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1758
|
+
// 4. Fallback Fix
|
|
1759
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1760
|
+
/**
|
|
1761
|
+
* Apply a fallback fix.
|
|
1762
|
+
*
|
|
1763
|
+
* - 'model': Replace params.model with the fallback model
|
|
1764
|
+
* - 'default': Set params._fallbackResponse for the caller to use
|
|
1765
|
+
*/
|
|
1766
|
+
applyFallbackFix(fix, params) {
|
|
1767
|
+
try {
|
|
1768
|
+
const cfg = fix.config;
|
|
1769
|
+
const fallbackType = cfg.fallback_type ?? cfg.fallbackType ?? "model";
|
|
1770
|
+
const fallbackConfig = cfg.fallback_config ?? cfg.fallbackConfig ?? {};
|
|
1771
|
+
const result = emptyResult(fix, "fallback");
|
|
1772
|
+
if (this._config.dryRun) {
|
|
1773
|
+
result.modifications = { fallbackType, fallbackConfig };
|
|
1774
|
+
return { params, result };
|
|
1775
|
+
}
|
|
1776
|
+
const modified = { ...params };
|
|
1777
|
+
if (fallbackType === "model") {
|
|
1778
|
+
const fallbackModel = fallbackConfig.model;
|
|
1779
|
+
if (fallbackModel) {
|
|
1780
|
+
modified.model = fallbackModel;
|
|
1781
|
+
result.applied = true;
|
|
1782
|
+
result.modifications = { model: fallbackModel };
|
|
1783
|
+
}
|
|
1784
|
+
} else if (fallbackType === "default") {
|
|
1785
|
+
const defaultResponse = fallbackConfig.response;
|
|
1786
|
+
if (defaultResponse !== void 0) {
|
|
1787
|
+
modified._fallbackResponse = defaultResponse;
|
|
1788
|
+
result.applied = true;
|
|
1789
|
+
result.modifications = { defaultResponse: true };
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
return { params: modified, result };
|
|
1793
|
+
} catch (e) {
|
|
1794
|
+
debug(`applyFallbackFix error: ${e}`);
|
|
1795
|
+
return {
|
|
1796
|
+
params,
|
|
1797
|
+
result: {
|
|
1798
|
+
applied: false,
|
|
1799
|
+
fixId: fix.fixId,
|
|
1800
|
+
fixType: "fallback",
|
|
1801
|
+
modifications: {},
|
|
1802
|
+
error: String(e)
|
|
1803
|
+
}
|
|
1804
|
+
};
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1808
|
+
// 5. Guard Fix
|
|
1809
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1810
|
+
/**
|
|
1811
|
+
* Apply a guard fix (validation).
|
|
1812
|
+
*
|
|
1813
|
+
* Guard types:
|
|
1814
|
+
* - content_filter: Regex-based blocked patterns
|
|
1815
|
+
* - format_check: JSON.parse() validity
|
|
1816
|
+
* - input_validation / output_validation: min/max length
|
|
1817
|
+
*/
|
|
1818
|
+
applyGuardFix(fix, content, isInput = true) {
|
|
1819
|
+
try {
|
|
1820
|
+
const cfg = fix.config;
|
|
1821
|
+
const guardType = cfg.guard_type ?? cfg.guardType ?? "output_validation";
|
|
1822
|
+
const guardConfig = cfg.guard_config ?? cfg.guardConfig ?? {};
|
|
1823
|
+
const result = emptyResult(fix, "guard");
|
|
1824
|
+
if (isInput && guardType !== "input_validation" && guardType !== "content_filter") {
|
|
1825
|
+
return { content, passed: true, result };
|
|
1826
|
+
}
|
|
1827
|
+
if (!isInput && guardType !== "output_validation" && guardType !== "format_check") {
|
|
1828
|
+
return { content, passed: true, result };
|
|
1829
|
+
}
|
|
1830
|
+
if (this._config.dryRun) {
|
|
1831
|
+
result.modifications = { guardType };
|
|
1832
|
+
return { content, passed: true, result };
|
|
1833
|
+
}
|
|
1834
|
+
let passed = true;
|
|
1835
|
+
let reason;
|
|
1836
|
+
if (guardType === "content_filter") {
|
|
1837
|
+
const blockedPatterns = guardConfig.blocked_patterns ?? guardConfig.blockedPatterns ?? [];
|
|
1838
|
+
for (const pattern of blockedPatterns) {
|
|
1839
|
+
const regex = this._safeCompileRegex(pattern);
|
|
1840
|
+
if (regex && regex.test(content)) {
|
|
1841
|
+
passed = false;
|
|
1842
|
+
reason = `blocked pattern matched: ${pattern.slice(0, 80)}`;
|
|
1843
|
+
break;
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
} else if (guardType === "format_check") {
|
|
1847
|
+
const requiredFormat = guardConfig.format;
|
|
1848
|
+
if (requiredFormat === "json") {
|
|
1849
|
+
try {
|
|
1850
|
+
JSON.parse(content);
|
|
1851
|
+
} catch {
|
|
1852
|
+
passed = false;
|
|
1853
|
+
reason = "format_check: invalid JSON";
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
} else if (guardType === "input_validation" || guardType === "output_validation") {
|
|
1857
|
+
const minLength = guardConfig.min_length ?? guardConfig.minLength ?? 0;
|
|
1858
|
+
const maxLength = guardConfig.max_length ?? guardConfig.maxLength ?? Infinity;
|
|
1859
|
+
if (content.length < minLength || content.length > maxLength) {
|
|
1860
|
+
passed = false;
|
|
1861
|
+
reason = `${guardType}: length ${content.length} outside [${minLength}, ${maxLength}]`;
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
result.applied = true;
|
|
1865
|
+
result.modifications = { passed, guardType };
|
|
1866
|
+
if (reason !== void 0) result.reason = reason;
|
|
1867
|
+
return { content, passed, result };
|
|
1868
|
+
} catch (e) {
|
|
1869
|
+
warn(`applyGuardFix error (failing CLOSED): ${e}`);
|
|
1870
|
+
return {
|
|
1871
|
+
content,
|
|
1872
|
+
passed: false,
|
|
1873
|
+
result: {
|
|
1874
|
+
applied: true,
|
|
1875
|
+
fixId: fix.fixId,
|
|
1876
|
+
fixType: "guard",
|
|
1877
|
+
modifications: { passed: false, reason: "guard_exception" },
|
|
1878
|
+
error: String(e),
|
|
1879
|
+
reason: "guard_exception"
|
|
1880
|
+
}
|
|
1881
|
+
};
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1885
|
+
// Application Log
|
|
1886
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1887
|
+
/** Log a fix application result. */
|
|
1888
|
+
logApplication(result) {
|
|
1889
|
+
this._applicationLog.push(result);
|
|
1890
|
+
if (this._applicationLog.length > 1e3) {
|
|
1891
|
+
this._applicationLog = this._applicationLog.slice(-500);
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
/** Get the application log. */
|
|
1895
|
+
getApplicationLog() {
|
|
1896
|
+
return [...this._applicationLog];
|
|
1897
|
+
}
|
|
1898
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1899
|
+
// Private Helpers
|
|
1900
|
+
// ═══════════════════════════════════════════════════════════════════════════
|
|
1901
|
+
/**
|
|
1902
|
+
* Safely compile a regex pattern from untrusted input.
|
|
1903
|
+
* Returns null if invalid or too long.
|
|
1904
|
+
*/
|
|
1905
|
+
_safeCompileRegex(pattern, maxLength = 500) {
|
|
1906
|
+
if (!pattern || pattern.length > maxLength) return null;
|
|
1907
|
+
try {
|
|
1908
|
+
return new RegExp(pattern, "i");
|
|
1909
|
+
} catch {
|
|
1910
|
+
debug(`Invalid regex pattern (length=${pattern.length})`);
|
|
1911
|
+
return null;
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
/** Prepend content to the first message matching the target role. */
|
|
1915
|
+
_prependToTarget(messages, target, content) {
|
|
1916
|
+
return messages.map((msg) => {
|
|
1917
|
+
if (msg.role === target) {
|
|
1918
|
+
return {
|
|
1919
|
+
...msg,
|
|
1920
|
+
content: content + "\n\n" + (msg.content ?? "")
|
|
1921
|
+
};
|
|
1922
|
+
}
|
|
1923
|
+
return msg;
|
|
1924
|
+
});
|
|
1925
|
+
}
|
|
1926
|
+
/** Append content to the first message matching the target role. */
|
|
1927
|
+
_appendToTarget(messages, target, content) {
|
|
1928
|
+
return messages.map((msg) => {
|
|
1929
|
+
if (msg.role === target) {
|
|
1930
|
+
return {
|
|
1931
|
+
...msg,
|
|
1932
|
+
content: (msg.content ?? "") + "\n\n" + content
|
|
1933
|
+
};
|
|
1934
|
+
}
|
|
1935
|
+
return msg;
|
|
1936
|
+
});
|
|
1937
|
+
}
|
|
1938
|
+
/** Regex replace across all messages. */
|
|
1939
|
+
_replaceInMessages(messages, pattern, replacement) {
|
|
1940
|
+
const regex = this._safeCompileRegex(pattern);
|
|
1941
|
+
if (!regex) {
|
|
1942
|
+
debug("Skipping invalid regex pattern in prompt fix");
|
|
1943
|
+
return messages;
|
|
1944
|
+
}
|
|
1945
|
+
return messages.map((msg) => {
|
|
1946
|
+
const msgContent = msg.content;
|
|
1947
|
+
if (typeof msgContent === "string") {
|
|
1948
|
+
return { ...msg, content: msgContent.replace(regex, replacement) };
|
|
1949
|
+
}
|
|
1950
|
+
return msg;
|
|
1951
|
+
});
|
|
1952
|
+
}
|
|
1953
|
+
/** Add few-shot examples after the first system message. */
|
|
1954
|
+
_addFewShotExamples(messages, examples) {
|
|
1955
|
+
const result = [];
|
|
1956
|
+
let systemFound = false;
|
|
1957
|
+
for (const msg of messages) {
|
|
1958
|
+
result.push(msg);
|
|
1959
|
+
if (msg.role === "system" && !systemFound) {
|
|
1960
|
+
systemFound = true;
|
|
1961
|
+
for (const example of examples) {
|
|
1962
|
+
if (example.user) {
|
|
1963
|
+
result.push({ role: "user", content: example.user });
|
|
1964
|
+
}
|
|
1965
|
+
if (example.assistant) {
|
|
1966
|
+
result.push({ role: "assistant", content: example.assistant });
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
return result;
|
|
1972
|
+
}
|
|
1973
|
+
};
|
|
1974
|
+
|
|
1975
|
+
// src/runtime/loader.ts
|
|
1976
|
+
var FixLoader = class _FixLoader {
|
|
1977
|
+
_config;
|
|
1978
|
+
_cache;
|
|
1979
|
+
_refreshTimer = null;
|
|
1980
|
+
_lastLoadTime = null;
|
|
1981
|
+
_consecutiveFailures = 0;
|
|
1982
|
+
_circuitOpenUntil = 0;
|
|
1983
|
+
_onLoadCallbacks = [];
|
|
1984
|
+
// Circuit breaker settings
|
|
1985
|
+
static CIRCUIT_BREAKER_THRESHOLD = 3;
|
|
1986
|
+
static CIRCUIT_BREAKER_COOLDOWN_MS = 3e4;
|
|
1987
|
+
constructor(config, cache) {
|
|
1988
|
+
this._config = resolveFixRuntimeConfig(config);
|
|
1989
|
+
this._cache = cache;
|
|
1990
|
+
}
|
|
1991
|
+
/** Timestamp of last successful load. */
|
|
1992
|
+
get lastLoadTime() {
|
|
1993
|
+
return this._lastLoadTime;
|
|
1994
|
+
}
|
|
1995
|
+
/**
|
|
1996
|
+
* Start the loader: perform initial load and start background refresh.
|
|
1997
|
+
*
|
|
1998
|
+
* Never throws — failures are logged and the runtime degrades gracefully.
|
|
1999
|
+
*/
|
|
2000
|
+
start() {
|
|
2001
|
+
try {
|
|
2002
|
+
if (!this._config.enabled) {
|
|
2003
|
+
debug("Fix runtime disabled, skipping loader start");
|
|
2004
|
+
return;
|
|
2005
|
+
}
|
|
2006
|
+
if (!this._config.apiKey) {
|
|
2007
|
+
warn("No API key configured, fixes will not be loaded");
|
|
2008
|
+
return;
|
|
2009
|
+
}
|
|
2010
|
+
this.loadSync().catch((e) => {
|
|
2011
|
+
debug(`Initial fix load failed: ${e}`);
|
|
2012
|
+
});
|
|
2013
|
+
if (this._config.autoRefresh) {
|
|
2014
|
+
this._startRefreshInterval();
|
|
2015
|
+
}
|
|
2016
|
+
} catch (e) {
|
|
2017
|
+
debug(`FixLoader.start error: ${e}`);
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
/** Stop the loader: clear the refresh interval. */
|
|
2021
|
+
stop() {
|
|
2022
|
+
try {
|
|
2023
|
+
if (this._refreshTimer !== null) {
|
|
2024
|
+
clearInterval(this._refreshTimer);
|
|
2025
|
+
this._refreshTimer = null;
|
|
2026
|
+
}
|
|
2027
|
+
} catch (e) {
|
|
2028
|
+
debug(`FixLoader.stop error: ${e}`);
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
/**
|
|
2032
|
+
* Register a callback invoked after each successful load.
|
|
2033
|
+
*/
|
|
2034
|
+
onLoad(callback) {
|
|
2035
|
+
this._onLoadCallbacks.push(callback);
|
|
2036
|
+
}
|
|
2037
|
+
/**
|
|
2038
|
+
* Load fixes from the API.
|
|
2039
|
+
*
|
|
2040
|
+
* Name kept as "loadSync" for parity with the Python SDK, but this
|
|
2041
|
+
* returns a Promise in JS (there's no synchronous fetch in Node.js).
|
|
2042
|
+
*/
|
|
2043
|
+
async loadSync() {
|
|
2044
|
+
if (!this._config.apiKey) {
|
|
2045
|
+
return [];
|
|
2046
|
+
}
|
|
2047
|
+
const now = Date.now();
|
|
2048
|
+
if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && now < this._circuitOpenUntil) {
|
|
2049
|
+
debug("Fix loader circuit breaker open \u2014 skipping load");
|
|
2050
|
+
return this._cache.getAll();
|
|
2051
|
+
}
|
|
2052
|
+
try {
|
|
2053
|
+
const endpoint = this._config.apiEndpoint.replace(/\/+$/, "");
|
|
2054
|
+
const url = `${endpoint}/api/v1/fixes/active`;
|
|
2055
|
+
const controller = new AbortController();
|
|
2056
|
+
const timeoutId = setTimeout(
|
|
2057
|
+
() => controller.abort(),
|
|
2058
|
+
this._config.timeoutMs
|
|
2059
|
+
);
|
|
2060
|
+
const response = await fetch(url, {
|
|
2061
|
+
method: "GET",
|
|
2062
|
+
headers: {
|
|
2063
|
+
"Authorization": `Bearer ${this._config.apiKey}`,
|
|
2064
|
+
"Content-Type": "application/json",
|
|
2065
|
+
"X-Risicare-SDK-Version": SDK_VERSION
|
|
2066
|
+
},
|
|
2067
|
+
signal: controller.signal
|
|
2068
|
+
});
|
|
2069
|
+
clearTimeout(timeoutId);
|
|
2070
|
+
if (!response.ok) {
|
|
2071
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
2072
|
+
}
|
|
2073
|
+
const data = await response.json();
|
|
2074
|
+
const fixes = this._parseResponse(data);
|
|
2075
|
+
this._onLoadSuccess(fixes);
|
|
2076
|
+
return fixes;
|
|
2077
|
+
} catch (e) {
|
|
2078
|
+
this._onLoadFailure(e);
|
|
2079
|
+
throw e;
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
/** Get currently cached fixes without hitting the API. */
|
|
2083
|
+
getCached() {
|
|
2084
|
+
return this._cache.getAll();
|
|
2085
|
+
}
|
|
2086
|
+
// ─── Private ────────────────────────────────────────────────────────────
|
|
2087
|
+
_parseResponse(data) {
|
|
2088
|
+
const fixes = [];
|
|
2089
|
+
const items = data.fixes ?? data.data ?? [];
|
|
2090
|
+
if (!Array.isArray(items)) return fixes;
|
|
2091
|
+
for (const item of items) {
|
|
2092
|
+
try {
|
|
2093
|
+
if (item && typeof item === "object") {
|
|
2094
|
+
fixes.push(activeFixFromApiResponse(item));
|
|
2095
|
+
}
|
|
2096
|
+
} catch (e) {
|
|
2097
|
+
debug(`Failed to parse fix item: ${e}`);
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
return fixes;
|
|
2101
|
+
}
|
|
2102
|
+
_onLoadSuccess(fixes) {
|
|
2103
|
+
this._lastLoadTime = Date.now();
|
|
2104
|
+
this._consecutiveFailures = 0;
|
|
2105
|
+
this._cache.setAll(fixes);
|
|
2106
|
+
for (const callback of this._onLoadCallbacks) {
|
|
2107
|
+
try {
|
|
2108
|
+
callback(fixes);
|
|
2109
|
+
} catch (e) {
|
|
2110
|
+
debug(`Load callback error: ${e}`);
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
debug(`Loaded ${fixes.length} active fixes`);
|
|
2114
|
+
}
|
|
2115
|
+
_onLoadFailure(error) {
|
|
2116
|
+
this._consecutiveFailures++;
|
|
2117
|
+
if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD) {
|
|
2118
|
+
this._circuitOpenUntil = Date.now() + _FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS;
|
|
2119
|
+
warn(
|
|
2120
|
+
`Fix loader circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${_FixLoader.CIRCUIT_BREAKER_COOLDOWN_MS / 1e3}s`
|
|
2121
|
+
);
|
|
2122
|
+
} else {
|
|
2123
|
+
debug(
|
|
2124
|
+
`Fix load failed (attempt ${this._consecutiveFailures}): ${error.message}`
|
|
2125
|
+
);
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
_startRefreshInterval() {
|
|
2129
|
+
const tick = () => {
|
|
2130
|
+
this.loadSync().catch((e) => {
|
|
2131
|
+
debug(`Background fix refresh failed: ${e}`);
|
|
2132
|
+
});
|
|
2133
|
+
};
|
|
2134
|
+
this._refreshTimer = setInterval(
|
|
2135
|
+
() => {
|
|
2136
|
+
if (this._consecutiveFailures >= _FixLoader.CIRCUIT_BREAKER_THRESHOLD && Date.now() < this._circuitOpenUntil) {
|
|
2137
|
+
return;
|
|
2138
|
+
}
|
|
2139
|
+
tick();
|
|
2140
|
+
},
|
|
2141
|
+
this._config.refreshIntervalMs
|
|
2142
|
+
);
|
|
2143
|
+
this._refreshTimer.unref();
|
|
2144
|
+
debug("Started fix refresh interval");
|
|
2145
|
+
}
|
|
2146
|
+
};
|
|
2147
|
+
|
|
2148
|
+
// src/runtime/interceptors.ts
|
|
2149
|
+
var GuardRejectedError = class extends Error {
|
|
2150
|
+
guardId;
|
|
2151
|
+
reason;
|
|
2152
|
+
phase;
|
|
2153
|
+
constructor(guardId, reason, phase) {
|
|
2154
|
+
super(`Risicare guard rejected operation: ${guardId} (${phase}) \u2014 ${reason}`);
|
|
2155
|
+
this.name = "GuardRejectedError";
|
|
2156
|
+
this.guardId = guardId;
|
|
2157
|
+
this.reason = reason;
|
|
2158
|
+
this.phase = phase;
|
|
2159
|
+
}
|
|
2160
|
+
};
|
|
2161
|
+
function createInterceptContext(operationType, operationName, options) {
|
|
2162
|
+
return {
|
|
2163
|
+
operationType,
|
|
2164
|
+
operationName,
|
|
2165
|
+
sessionId: options?.sessionId,
|
|
2166
|
+
traceId: options?.traceId,
|
|
2167
|
+
errorCode: options?.errorCode,
|
|
2168
|
+
attempt: 1,
|
|
2169
|
+
appliedFixes: []
|
|
2170
|
+
};
|
|
2171
|
+
}
|
|
2172
|
+
var DefaultFixInterceptor = class {
|
|
2173
|
+
_config;
|
|
2174
|
+
_cache;
|
|
2175
|
+
_applier;
|
|
2176
|
+
constructor(config, cache, applier) {
|
|
2177
|
+
this._config = resolveFixRuntimeConfig(config);
|
|
2178
|
+
this._cache = cache;
|
|
2179
|
+
this._applier = applier;
|
|
2180
|
+
}
|
|
2181
|
+
/**
|
|
2182
|
+
* Apply pre-call fixes.
|
|
2183
|
+
*
|
|
2184
|
+
* - If retrying after error: look up fix by error_code, apply
|
|
2185
|
+
* prompt/parameter/fallback fixes
|
|
2186
|
+
* - Runs input guard fixes on all message content
|
|
2187
|
+
*/
|
|
2188
|
+
preCall(ctx, messages, params) {
|
|
2189
|
+
try {
|
|
2190
|
+
if (!this._config.enabled) {
|
|
2191
|
+
return { messages, params };
|
|
2192
|
+
}
|
|
2193
|
+
let modifiedMessages = messages;
|
|
2194
|
+
let modifiedParams = { ...params };
|
|
2195
|
+
if (ctx.errorCode) {
|
|
2196
|
+
const fix = this._applier.getFixForError(ctx.errorCode, ctx.sessionId);
|
|
2197
|
+
if (fix) {
|
|
2198
|
+
debug(`Applying fix ${fix.fixId} for ${ctx.errorCode}`);
|
|
2199
|
+
if (fix.fixType === "prompt" && messages) {
|
|
2200
|
+
const msgRecords = messages;
|
|
2201
|
+
const { messages: newMessages, result } = this._applier.applyPromptFix(fix, msgRecords);
|
|
2202
|
+
modifiedMessages = newMessages;
|
|
2203
|
+
ctx.appliedFixes.push(result);
|
|
2204
|
+
this._applier.logApplication(result);
|
|
2205
|
+
} else if (fix.fixType === "parameter") {
|
|
2206
|
+
const { params: newParams, result } = this._applier.applyParameterFix(fix, modifiedParams);
|
|
2207
|
+
modifiedParams = newParams;
|
|
2208
|
+
ctx.appliedFixes.push(result);
|
|
2209
|
+
this._applier.logApplication(result);
|
|
2210
|
+
} else if (fix.fixType === "fallback") {
|
|
2211
|
+
const { params: newParams, result } = this._applier.applyFallbackFix(fix, modifiedParams);
|
|
2212
|
+
modifiedParams = newParams;
|
|
2213
|
+
ctx.appliedFixes.push(result);
|
|
2214
|
+
this._applier.logApplication(result);
|
|
2215
|
+
}
|
|
2216
|
+
}
|
|
2217
|
+
}
|
|
2218
|
+
if (modifiedMessages && this._config.enabled) {
|
|
2219
|
+
for (const msg of modifiedMessages) {
|
|
2220
|
+
const content = msg.content;
|
|
2221
|
+
if (typeof content === "string") {
|
|
2222
|
+
for (const fix of this._cache.getAll()) {
|
|
2223
|
+
if (fix.fixType === "guard") {
|
|
2224
|
+
const { passed, result } = this._applier.applyGuardFix(
|
|
2225
|
+
fix,
|
|
2226
|
+
content,
|
|
2227
|
+
true
|
|
2228
|
+
);
|
|
2229
|
+
if (result.applied) {
|
|
2230
|
+
ctx.appliedFixes.push(result);
|
|
2231
|
+
this._applier.logApplication(result);
|
|
2232
|
+
}
|
|
2233
|
+
if (!passed) {
|
|
2234
|
+
throw new GuardRejectedError(
|
|
2235
|
+
fix.fixId ?? "unknown",
|
|
2236
|
+
result.reason ?? "guard rejected input",
|
|
2237
|
+
"pre_call"
|
|
2238
|
+
);
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
}
|
|
2245
|
+
return { messages: modifiedMessages, params: modifiedParams };
|
|
2246
|
+
} catch (e) {
|
|
2247
|
+
if (e instanceof GuardRejectedError) throw e;
|
|
2248
|
+
debug(`DefaultFixInterceptor.preCall error: ${e}`);
|
|
2249
|
+
return { messages, params };
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
/**
|
|
2253
|
+
* Apply post-call fixes (output validation).
|
|
2254
|
+
*
|
|
2255
|
+
* Runs output guard fixes on response content.
|
|
2256
|
+
*/
|
|
2257
|
+
postCall(ctx, response) {
|
|
2258
|
+
try {
|
|
2259
|
+
if (!this._config.enabled) {
|
|
2260
|
+
return { response, shouldContinue: true };
|
|
2261
|
+
}
|
|
2262
|
+
for (const fix of this._cache.getAll()) {
|
|
2263
|
+
if (fix.fixType !== "guard") continue;
|
|
2264
|
+
const content = this._extractResponseContent(response);
|
|
2265
|
+
if (!content) continue;
|
|
2266
|
+
const { passed, result } = this._applier.applyGuardFix(
|
|
2267
|
+
fix,
|
|
2268
|
+
content,
|
|
2269
|
+
false
|
|
2270
|
+
);
|
|
2271
|
+
if (result.applied) {
|
|
2272
|
+
ctx.appliedFixes.push(result);
|
|
2273
|
+
this._applier.logApplication(result);
|
|
2274
|
+
}
|
|
2275
|
+
if (!passed) {
|
|
2276
|
+
warn(`Output guard failed for fix ${fix.fixId}: ${result.reason ?? "unknown"}`);
|
|
2277
|
+
throw new GuardRejectedError(
|
|
2278
|
+
fix.fixId ?? "unknown",
|
|
2279
|
+
result.reason ?? "guard rejected output",
|
|
2280
|
+
"post_call"
|
|
2281
|
+
);
|
|
2282
|
+
}
|
|
2283
|
+
}
|
|
2284
|
+
return { response, shouldContinue: true };
|
|
2285
|
+
} catch (e) {
|
|
2286
|
+
if (e instanceof GuardRejectedError) throw e;
|
|
2287
|
+
debug(`DefaultFixInterceptor.postCall error: ${e}`);
|
|
2288
|
+
return { response, shouldContinue: true };
|
|
2289
|
+
}
|
|
2290
|
+
}
|
|
2291
|
+
/**
|
|
2292
|
+
* Handle errors and decide whether to retry.
|
|
2293
|
+
*
|
|
2294
|
+
* Classifies the error, looks up retry/fallback fixes, and returns
|
|
2295
|
+
* whether the caller should retry.
|
|
2296
|
+
*/
|
|
2297
|
+
onError(ctx, error) {
|
|
2298
|
+
try {
|
|
2299
|
+
if (!this._config.enabled) {
|
|
2300
|
+
return { shouldRetry: false, modifiedParams: null };
|
|
2301
|
+
}
|
|
2302
|
+
const errorCode = classifyError(error);
|
|
2303
|
+
ctx.errorCode = errorCode;
|
|
2304
|
+
ctx.errorMessage = error.message;
|
|
2305
|
+
const fix = this._applier.getFixForError(errorCode, ctx.sessionId);
|
|
2306
|
+
if (!fix) {
|
|
2307
|
+
return { shouldRetry: false, modifiedParams: null };
|
|
2308
|
+
}
|
|
2309
|
+
if (fix.fixType === "retry") {
|
|
2310
|
+
const maxRetries = fix.config.max_retries ?? fix.config.maxRetries ?? 3;
|
|
2311
|
+
if (ctx.attempt <= maxRetries) {
|
|
2312
|
+
debug(
|
|
2313
|
+
`Retry fix ${fix.fixId}: attempt ${ctx.attempt}/${maxRetries}`
|
|
2314
|
+
);
|
|
2315
|
+
const result = {
|
|
2316
|
+
applied: true,
|
|
2317
|
+
fixId: fix.fixId,
|
|
2318
|
+
deploymentId: fix.deploymentId,
|
|
2319
|
+
fixType: "retry",
|
|
2320
|
+
modifications: { attempt: ctx.attempt }
|
|
2321
|
+
};
|
|
2322
|
+
ctx.appliedFixes.push(result);
|
|
2323
|
+
this._applier.logApplication(result);
|
|
2324
|
+
return { shouldRetry: true, modifiedParams: null };
|
|
2325
|
+
}
|
|
2326
|
+
}
|
|
2327
|
+
if (fix.fixType === "fallback") {
|
|
2328
|
+
const { params: modifiedParams, result } = this._applier.applyFallbackFix(fix, {});
|
|
2329
|
+
if (result.applied) {
|
|
2330
|
+
ctx.appliedFixes.push(result);
|
|
2331
|
+
this._applier.logApplication(result);
|
|
2332
|
+
return { shouldRetry: true, modifiedParams };
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
return { shouldRetry: false, modifiedParams: null };
|
|
2336
|
+
} catch (e) {
|
|
2337
|
+
debug(`DefaultFixInterceptor.onError error: ${e}`);
|
|
2338
|
+
return { shouldRetry: false, modifiedParams: null };
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
// ─── Private ────────────────────────────────────────────────────────────
|
|
2342
|
+
/** Extract text content from a response object. */
|
|
2343
|
+
_extractResponseContent(response) {
|
|
2344
|
+
if (typeof response === "string") return response;
|
|
2345
|
+
if (response && typeof response === "object") {
|
|
2346
|
+
const resp = response;
|
|
2347
|
+
const choices = resp.choices;
|
|
2348
|
+
if (Array.isArray(choices) && choices.length > 0) {
|
|
2349
|
+
const first = choices[0];
|
|
2350
|
+
const message = first?.message;
|
|
2351
|
+
if (typeof message?.content === "string") {
|
|
2352
|
+
return message.content;
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
const content = resp.content;
|
|
2356
|
+
if (typeof content === "string") return content;
|
|
2357
|
+
if (Array.isArray(content) && content.length > 0) {
|
|
2358
|
+
const first = content[0];
|
|
2359
|
+
if (typeof first?.text === "string") return first.text;
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
return null;
|
|
2363
|
+
}
|
|
2364
|
+
};
|
|
2365
|
+
function classifyError(error) {
|
|
2366
|
+
const errorType = error.constructor.name.toLowerCase();
|
|
2367
|
+
const errorMsg = error.message.toLowerCase();
|
|
2368
|
+
if (errorType.includes("timeout") || errorMsg.includes("timeout") || errorMsg.includes("aborted")) {
|
|
2369
|
+
return "TOOL.EXECUTION.TIMEOUT";
|
|
2370
|
+
}
|
|
2371
|
+
if (errorMsg.includes("rate") && errorMsg.includes("limit")) {
|
|
2372
|
+
return "TOOL.EXECUTION.RATE_LIMIT";
|
|
2373
|
+
}
|
|
2374
|
+
if (errorMsg.includes("429") || errorMsg.includes("too many requests")) {
|
|
2375
|
+
return "TOOL.EXECUTION.RATE_LIMIT";
|
|
2376
|
+
}
|
|
2377
|
+
if (errorType.includes("connection") || errorMsg.includes("connection") || errorMsg.includes("econnrefused") || errorMsg.includes("econnreset") || errorMsg.includes("fetch failed")) {
|
|
2378
|
+
return "TOOL.EXECUTION.CONNECTION_ERROR";
|
|
2379
|
+
}
|
|
2380
|
+
if (errorMsg.includes("auth") || errorMsg.includes("401") || errorMsg.includes("403") || errorMsg.includes("unauthorized") || errorMsg.includes("forbidden")) {
|
|
2381
|
+
return "TOOL.EXECUTION.AUTH_ERROR";
|
|
2382
|
+
}
|
|
2383
|
+
if (errorType.includes("syntaxerror") || errorType.includes("json") || errorMsg.includes("json") || errorMsg.includes("unexpected token")) {
|
|
2384
|
+
return "OUTPUT.FORMAT.JSON_INVALID";
|
|
2385
|
+
}
|
|
2386
|
+
return "TOOL.EXECUTION.FAILURE";
|
|
2387
|
+
}
|
|
2388
|
+
|
|
2389
|
+
// src/runtime/runtime.ts
|
|
2390
|
+
var G2 = globalThis;
|
|
2391
|
+
var RUNTIME_KEY = "__risicare_fix_runtime";
|
|
2392
|
+
var FixRuntime = class {
|
|
2393
|
+
_config;
|
|
2394
|
+
_cache;
|
|
2395
|
+
_loader;
|
|
2396
|
+
_applier;
|
|
2397
|
+
_interceptor;
|
|
2398
|
+
_started = false;
|
|
2399
|
+
// Effectiveness tracking
|
|
2400
|
+
_fixApplications = /* @__PURE__ */ new Map();
|
|
2401
|
+
_fixSuccesses = /* @__PURE__ */ new Map();
|
|
2402
|
+
constructor(config) {
|
|
2403
|
+
this._config = resolveFixRuntimeConfig(config);
|
|
2404
|
+
this._cache = new FixCache(this._config);
|
|
2405
|
+
this._loader = new FixLoader(config, this._cache);
|
|
2406
|
+
this._applier = new FixApplier(config, this._cache);
|
|
2407
|
+
this._interceptor = new DefaultFixInterceptor(
|
|
2408
|
+
config,
|
|
2409
|
+
this._cache,
|
|
2410
|
+
this._applier
|
|
2411
|
+
);
|
|
2412
|
+
}
|
|
2413
|
+
// ─── Accessors ──────────────────────────────────────────────────────────
|
|
2414
|
+
/** Runtime configuration (with defaults resolved). */
|
|
2415
|
+
get config() {
|
|
2416
|
+
return this._config;
|
|
2417
|
+
}
|
|
2418
|
+
/** Whether the runtime is enabled and started. */
|
|
2419
|
+
get isEnabled() {
|
|
2420
|
+
return this._config.enabled && this._started;
|
|
2421
|
+
}
|
|
2422
|
+
/** The fix cache. */
|
|
2423
|
+
get cache() {
|
|
2424
|
+
return this._cache;
|
|
2425
|
+
}
|
|
2426
|
+
/** The fix loader. */
|
|
2427
|
+
get loader() {
|
|
2428
|
+
return this._loader;
|
|
2429
|
+
}
|
|
2430
|
+
/** The fix applier. */
|
|
2431
|
+
get applier() {
|
|
2432
|
+
return this._applier;
|
|
2433
|
+
}
|
|
2434
|
+
/** The interceptor. */
|
|
2435
|
+
get interceptor() {
|
|
2436
|
+
return this._interceptor;
|
|
2437
|
+
}
|
|
2438
|
+
// ─── Lifecycle ──────────────────────────────────────────────────────────
|
|
2439
|
+
/**
|
|
2440
|
+
* Start the runtime.
|
|
2441
|
+
*
|
|
2442
|
+
* Triggers initial fix load and starts background refresh.
|
|
2443
|
+
* Never throws — failures degrade gracefully.
|
|
2444
|
+
*/
|
|
2445
|
+
start() {
|
|
2446
|
+
try {
|
|
2447
|
+
if (this._started) return;
|
|
2448
|
+
if (!this._config.enabled) {
|
|
2449
|
+
debug("Fix runtime disabled");
|
|
2450
|
+
return;
|
|
2451
|
+
}
|
|
2452
|
+
debug("Starting fix runtime...");
|
|
2453
|
+
this._loader.start();
|
|
2454
|
+
this._started = true;
|
|
2455
|
+
debug("Fix runtime started");
|
|
2456
|
+
} catch (e) {
|
|
2457
|
+
warn(`Fix runtime start failed: ${e}`);
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
/**
|
|
2461
|
+
* Stop the runtime.
|
|
2462
|
+
*
|
|
2463
|
+
* Stops background refresh and clears the cache.
|
|
2464
|
+
* Never throws.
|
|
2465
|
+
*/
|
|
2466
|
+
stop() {
|
|
2467
|
+
try {
|
|
2468
|
+
if (!this._started) return;
|
|
2469
|
+
debug("Stopping fix runtime...");
|
|
2470
|
+
this._loader.stop();
|
|
2471
|
+
this._cache.clear();
|
|
2472
|
+
this._started = false;
|
|
2473
|
+
debug("Fix runtime stopped");
|
|
2474
|
+
} catch (e) {
|
|
2475
|
+
debug(`Fix runtime stop error: ${e}`);
|
|
2476
|
+
}
|
|
2477
|
+
}
|
|
2478
|
+
// ─── Intercept API ──────────────────────────────────────────────────────
|
|
2479
|
+
/**
|
|
2480
|
+
* Intercept a call: create context and run preCall fixes.
|
|
2481
|
+
*
|
|
2482
|
+
* Returns modified messages/params and the InterceptContext for
|
|
2483
|
+
* use in subsequent interceptResponse / interceptError calls.
|
|
2484
|
+
*/
|
|
2485
|
+
interceptCall(operationType, operationName, messages, params, options) {
|
|
2486
|
+
const ctx = createInterceptContext(operationType, operationName, options);
|
|
2487
|
+
try {
|
|
2488
|
+
if (!this.isEnabled) {
|
|
2489
|
+
return { messages, params, ctx };
|
|
2490
|
+
}
|
|
2491
|
+
const result = this._interceptor.preCall(ctx, messages, params);
|
|
2492
|
+
return { messages: result.messages, params: result.params, ctx };
|
|
2493
|
+
} catch (e) {
|
|
2494
|
+
if (e instanceof GuardRejectedError) throw e;
|
|
2495
|
+
debug(`interceptCall error: ${e}`);
|
|
2496
|
+
return { messages, params, ctx };
|
|
2497
|
+
}
|
|
2498
|
+
}
|
|
2499
|
+
/**
|
|
2500
|
+
* Intercept a response: run postCall fixes (output validation).
|
|
2501
|
+
*/
|
|
2502
|
+
interceptResponse(ctx, response) {
|
|
2503
|
+
try {
|
|
2504
|
+
if (!this.isEnabled) {
|
|
2505
|
+
return { response, shouldContinue: true };
|
|
2506
|
+
}
|
|
2507
|
+
const result = this._interceptor.postCall(ctx, response);
|
|
2508
|
+
this._trackSuccess(ctx);
|
|
2509
|
+
return result;
|
|
2510
|
+
} catch (e) {
|
|
2511
|
+
if (e instanceof GuardRejectedError) throw e;
|
|
2512
|
+
debug(`interceptResponse error: ${e}`);
|
|
2513
|
+
return { response, shouldContinue: true };
|
|
2514
|
+
}
|
|
2515
|
+
}
|
|
2516
|
+
/**
|
|
2517
|
+
* Intercept an error: decide on retry/fallback.
|
|
2518
|
+
*/
|
|
2519
|
+
interceptError(ctx, error) {
|
|
2520
|
+
try {
|
|
2521
|
+
if (!this.isEnabled) {
|
|
2522
|
+
return { shouldRetry: false, modifiedParams: null };
|
|
2523
|
+
}
|
|
2524
|
+
ctx.attempt++;
|
|
2525
|
+
const result = this._interceptor.onError(ctx, error);
|
|
2526
|
+
if (!result.shouldRetry) {
|
|
2527
|
+
this._trackFailure(ctx);
|
|
2528
|
+
}
|
|
2529
|
+
return result;
|
|
2530
|
+
} catch (e) {
|
|
2531
|
+
debug(`interceptError error: ${e}`);
|
|
2532
|
+
return { shouldRetry: false, modifiedParams: null };
|
|
2533
|
+
}
|
|
2534
|
+
}
|
|
2535
|
+
// ─── Direct Fix Access ──────────────────────────────────────────────────
|
|
2536
|
+
/**
|
|
2537
|
+
* Get applicable fix for an error code.
|
|
2538
|
+
*/
|
|
2539
|
+
getFix(errorCode, sessionId) {
|
|
2540
|
+
try {
|
|
2541
|
+
if (!this.isEnabled) return null;
|
|
2542
|
+
return this._applier.getFixForError(errorCode, sessionId);
|
|
2543
|
+
} catch (e) {
|
|
2544
|
+
debug(`getFix error: ${e}`);
|
|
2545
|
+
return null;
|
|
2546
|
+
}
|
|
2547
|
+
}
|
|
2548
|
+
/**
|
|
2549
|
+
* Manually refresh fixes from the API.
|
|
2550
|
+
*/
|
|
2551
|
+
async refreshFixes() {
|
|
2552
|
+
try {
|
|
2553
|
+
return await this._loader.loadSync();
|
|
2554
|
+
} catch (e) {
|
|
2555
|
+
debug(`refreshFixes error: ${e}`);
|
|
2556
|
+
return [];
|
|
2557
|
+
}
|
|
2558
|
+
}
|
|
2559
|
+
// ─── Effectiveness ──────────────────────────────────────────────────────
|
|
2560
|
+
/** Get effectiveness statistics for all fixes. */
|
|
2561
|
+
getEffectivenessStats() {
|
|
2562
|
+
const stats = {};
|
|
2563
|
+
for (const [fixId, applications] of this._fixApplications) {
|
|
2564
|
+
const successes = this._fixSuccesses.get(fixId) ?? 0;
|
|
2565
|
+
stats[fixId] = {
|
|
2566
|
+
applications,
|
|
2567
|
+
successes,
|
|
2568
|
+
successRate: applications > 0 ? successes / applications : 0
|
|
2569
|
+
};
|
|
2570
|
+
}
|
|
2571
|
+
return stats;
|
|
2572
|
+
}
|
|
2573
|
+
// ─── Private ────────────────────────────────────────────────────────────
|
|
2574
|
+
_trackSuccess(ctx) {
|
|
2575
|
+
for (const result of ctx.appliedFixes) {
|
|
2576
|
+
if (result.applied && result.fixId) {
|
|
2577
|
+
this._fixApplications.set(
|
|
2578
|
+
result.fixId,
|
|
2579
|
+
(this._fixApplications.get(result.fixId) ?? 0) + 1
|
|
2580
|
+
);
|
|
2581
|
+
this._fixSuccesses.set(
|
|
2582
|
+
result.fixId,
|
|
2583
|
+
(this._fixSuccesses.get(result.fixId) ?? 0) + 1
|
|
2584
|
+
);
|
|
2585
|
+
}
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
_trackFailure(ctx) {
|
|
2589
|
+
for (const result of ctx.appliedFixes) {
|
|
2590
|
+
if (result.applied && result.fixId) {
|
|
2591
|
+
this._fixApplications.set(
|
|
2592
|
+
result.fixId,
|
|
2593
|
+
(this._fixApplications.get(result.fixId) ?? 0) + 1
|
|
2594
|
+
);
|
|
2595
|
+
}
|
|
2596
|
+
}
|
|
2597
|
+
}
|
|
2598
|
+
};
|
|
2599
|
+
function getFixRuntime() {
|
|
2600
|
+
return G2[RUNTIME_KEY];
|
|
2601
|
+
}
|
|
2602
|
+
function initFixRuntime(config) {
|
|
2603
|
+
try {
|
|
2604
|
+
const existing = G2[RUNTIME_KEY];
|
|
2605
|
+
if (existing) {
|
|
2606
|
+
debug("Fix runtime already initialized");
|
|
2607
|
+
return existing;
|
|
2608
|
+
}
|
|
2609
|
+
const runtime = new FixRuntime(config);
|
|
2610
|
+
runtime.start();
|
|
2611
|
+
G2[RUNTIME_KEY] = runtime;
|
|
2612
|
+
return runtime;
|
|
2613
|
+
} catch (e) {
|
|
2614
|
+
warn(`initFixRuntime failed: ${e}`);
|
|
2615
|
+
const fallback = new FixRuntime({ ...config, enabled: false });
|
|
2616
|
+
G2[RUNTIME_KEY] = fallback;
|
|
2617
|
+
return fallback;
|
|
2618
|
+
}
|
|
2619
|
+
}
|
|
2620
|
+
function shutdownFixRuntime() {
|
|
2621
|
+
try {
|
|
2622
|
+
const runtime = G2[RUNTIME_KEY];
|
|
2623
|
+
if (runtime) {
|
|
2624
|
+
runtime.stop();
|
|
2625
|
+
}
|
|
2626
|
+
G2[RUNTIME_KEY] = void 0;
|
|
2627
|
+
} catch (e) {
|
|
2628
|
+
debug(`shutdownFixRuntime error: ${e}`);
|
|
2629
|
+
G2[RUNTIME_KEY] = void 0;
|
|
2306
2630
|
}
|
|
2307
|
-
}
|
|
2631
|
+
}
|
|
2308
2632
|
|
|
2309
2633
|
// src/client.ts
|
|
2310
|
-
|
|
2311
|
-
|
|
2634
|
+
var TERMINATING_SIGNALS = [
|
|
2635
|
+
["SIGTERM", 15],
|
|
2636
|
+
["SIGINT", 2]
|
|
2637
|
+
];
|
|
2638
|
+
var BACKSTOP_MARGIN_MS = 500;
|
|
2639
|
+
var _finalMetrics;
|
|
2312
2640
|
var RisicareClient = class {
|
|
2313
2641
|
config;
|
|
2314
2642
|
processor;
|
|
2315
2643
|
tracer;
|
|
2644
|
+
/** RULING §5. The signal path does NOT clear the global client, so without
|
|
2645
|
+
* this flag `getMetrics()` would keep reporting `"running"` over a processor
|
|
2646
|
+
* that has already been torn down. */
|
|
2647
|
+
isShutdown = false;
|
|
2316
2648
|
_shutdownPromise;
|
|
2317
2649
|
_shutdownHandlers = [];
|
|
2318
2650
|
constructor(config) {
|
|
@@ -2332,14 +2664,27 @@ var RisicareClient = class {
|
|
|
2332
2664
|
compress: this.config.compress
|
|
2333
2665
|
});
|
|
2334
2666
|
} else {
|
|
2335
|
-
exporter =
|
|
2667
|
+
exporter = void 0;
|
|
2668
|
+
if (this.config.enabled) {
|
|
2669
|
+
try {
|
|
2670
|
+
console.warn(
|
|
2671
|
+
`[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.`
|
|
2672
|
+
);
|
|
2673
|
+
} catch {
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2336
2676
|
}
|
|
2337
2677
|
this.processor = new BatchSpanProcessor({
|
|
2338
|
-
exporters: [exporter],
|
|
2678
|
+
exporters: exporter ? [exporter] : [],
|
|
2339
2679
|
batchSize: this.config.batchSize,
|
|
2340
2680
|
batchTimeoutMs: this.config.batchTimeoutMs,
|
|
2341
2681
|
maxQueueSize: this.config.maxQueueSize,
|
|
2342
|
-
debug: this.config.debug
|
|
2682
|
+
debug: this.config.debug,
|
|
2683
|
+
// The processor is the ONE choke point every exporter is behind. Masking
|
|
2684
|
+
// anywhere downstream (in the HTTP exporter, say) would leave a hole for
|
|
2685
|
+
// any other exporter; masking upstream would put customer code on the
|
|
2686
|
+
// span-end call path.
|
|
2687
|
+
mask: this.config.mask
|
|
2343
2688
|
});
|
|
2344
2689
|
this.tracer = new Tracer({
|
|
2345
2690
|
onSpanEnd: (span) => this.processor.onSpanEnd(span),
|
|
@@ -2350,8 +2695,7 @@ var RisicareClient = class {
|
|
|
2350
2695
|
this.processor.start();
|
|
2351
2696
|
if (this.config.apiKey && this.config.enabled) {
|
|
2352
2697
|
try {
|
|
2353
|
-
|
|
2354
|
-
initFixRuntime2({
|
|
2698
|
+
initFixRuntime({
|
|
2355
2699
|
apiEndpoint: this.config.endpoint,
|
|
2356
2700
|
apiKey: this.config.apiKey,
|
|
2357
2701
|
enabled: true,
|
|
@@ -2394,37 +2738,126 @@ var RisicareClient = class {
|
|
|
2394
2738
|
}
|
|
2395
2739
|
this._shutdownHandlers = [];
|
|
2396
2740
|
await this.processor.shutdown();
|
|
2741
|
+
this.isShutdown = true;
|
|
2742
|
+
_finalMetrics = this.processor.getMetrics();
|
|
2397
2743
|
}
|
|
2744
|
+
/**
|
|
2745
|
+
* Flush pending spans.
|
|
2746
|
+
*
|
|
2747
|
+
* @returns `true` only if everything queued at entry was DELIVERED.
|
|
2748
|
+
*
|
|
2749
|
+
* RULING §6: this used to discard the processor's boolean and return
|
|
2750
|
+
* `Promise<void>`, which resolves without throwing and reads to a caller
|
|
2751
|
+
* exactly like success. A discarded answer is not meaningfully better than a
|
|
2752
|
+
* false one — both leave the customer unable to tell *drained* from
|
|
2753
|
+
* *discarded*.
|
|
2754
|
+
*/
|
|
2398
2755
|
async flush() {
|
|
2399
|
-
|
|
2756
|
+
return this.processor.flush();
|
|
2400
2757
|
}
|
|
2758
|
+
/**
|
|
2759
|
+
* SDK-RELEASE-RULING.md §3 — who decides whether the process dies.
|
|
2760
|
+
*
|
|
2761
|
+
* The contract, and it is the same one the Python SDK now satisfies:
|
|
2762
|
+
*
|
|
2763
|
+
* the SDK's signal handler never CHANGES whether the signal
|
|
2764
|
+
* terminates the process.
|
|
2765
|
+
*
|
|
2766
|
+
* Registering ANY listener for SIGTERM/SIGINT displaces Node's default
|
|
2767
|
+
* terminate. Before this, the SDK registered one unconditionally, and on the
|
|
2768
|
+
* success path `clearTimeout` removed the 5 s `process.exit(1)` backstop —
|
|
2769
|
+
* so a JS app with a live event loop drained, cleared its own only exit, and
|
|
2770
|
+
* **ran forever**. The orchestrator waited out the whole grace period and
|
|
2771
|
+
* SIGKILLed, which exits **137** and reads as OOM-killed in every dashboard.
|
|
2772
|
+
* Measured >25 s alive on both 0.5.0 and a clean-rebuilt 0.4.2, so this is
|
|
2773
|
+
* PRE-EXISTING (`F-SDKJSEXIT-001`), not a regression of the data-loss fix.
|
|
2774
|
+
*
|
|
2775
|
+
* The rule splits on one question — did the signal already have an owner?
|
|
2776
|
+
*
|
|
2777
|
+
* * **No prior listener.** Node's default was termination and OUR
|
|
2778
|
+
* registration displaced it. We owe the process that death.
|
|
2779
|
+
* * **A prior listener exists.** The application took ownership before the
|
|
2780
|
+
* SDK loaded. We drain and RETURN; termination was never ours to decide,
|
|
2781
|
+
* and forcing it would cut off the app's own graceful shutdown.
|
|
2782
|
+
*
|
|
2783
|
+
* ⚠ `beforeExit` is deliberately NOT in that logic. It is not a signal and
|
|
2784
|
+
* carries no termination the SDK could displace — the loop has already
|
|
2785
|
+
* drained and the process is leaving on its own.
|
|
2786
|
+
*/
|
|
2401
2787
|
_registerShutdownHooks() {
|
|
2402
|
-
const
|
|
2403
|
-
const timeout = setTimeout(() => process.exit(1), 5e3);
|
|
2404
|
-
timeout.unref();
|
|
2788
|
+
const onBeforeExit = () => {
|
|
2405
2789
|
this.shutdown().catch(() => {
|
|
2406
|
-
})
|
|
2790
|
+
});
|
|
2407
2791
|
};
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2792
|
+
process.once("beforeExit", onBeforeExit);
|
|
2793
|
+
this._shutdownHandlers.push({ signal: "beforeExit", handler: onBeforeExit });
|
|
2794
|
+
for (const [signal, signum] of TERMINATING_SIGNALS) {
|
|
2795
|
+
const weDisplacedDefault = process.listenerCount(signal) === 0;
|
|
2796
|
+
const handler = () => {
|
|
2797
|
+
const backstop = setTimeout(
|
|
2798
|
+
() => process.exit(128 + signum),
|
|
2799
|
+
SHUTDOWN_BUDGET_MS + BACKSTOP_MARGIN_MS
|
|
2800
|
+
);
|
|
2801
|
+
backstop.unref();
|
|
2802
|
+
this.shutdown().catch(() => {
|
|
2803
|
+
}).finally(() => {
|
|
2804
|
+
clearTimeout(backstop);
|
|
2805
|
+
if (!weDisplacedDefault) return;
|
|
2806
|
+
try {
|
|
2807
|
+
process.kill(process.pid, signal);
|
|
2808
|
+
} catch {
|
|
2809
|
+
process.exit(128 + signum);
|
|
2810
|
+
}
|
|
2811
|
+
const failsafe = setTimeout(() => process.exit(128 + signum), 100);
|
|
2812
|
+
failsafe.unref();
|
|
2813
|
+
});
|
|
2814
|
+
};
|
|
2815
|
+
process.once(signal, handler);
|
|
2816
|
+
this._shutdownHandlers.push({ signal, handler });
|
|
2412
2817
|
}
|
|
2413
2818
|
}
|
|
2414
2819
|
};
|
|
2415
2820
|
function init(config) {
|
|
2416
|
-
|
|
2417
|
-
|
|
2821
|
+
const existing = getClient();
|
|
2822
|
+
if (existing) {
|
|
2823
|
+
if (config) {
|
|
2824
|
+
const incoming = resolveConfig(config);
|
|
2825
|
+
const diffs = [];
|
|
2826
|
+
const checkedKeys = [
|
|
2827
|
+
"apiKey",
|
|
2828
|
+
"endpoint",
|
|
2829
|
+
"environment",
|
|
2830
|
+
"serviceName",
|
|
2831
|
+
"serviceVersion",
|
|
2832
|
+
"sampleRate"
|
|
2833
|
+
];
|
|
2834
|
+
for (const k of checkedKeys) {
|
|
2835
|
+
if (incoming[k] !== existing.config[k]) {
|
|
2836
|
+
const newRender = k === "apiKey" ? "<redacted>" : JSON.stringify(incoming[k]);
|
|
2837
|
+
const oldRender = k === "apiKey" ? "<redacted>" : JSON.stringify(existing.config[k]);
|
|
2838
|
+
diffs.push(`${String(k)}: ${oldRender} \u2192 ${newRender}`);
|
|
2839
|
+
}
|
|
2840
|
+
}
|
|
2841
|
+
if (diffs.length > 0) {
|
|
2842
|
+
console.warn(
|
|
2843
|
+
"[risicare] init() called twice with different config; the FIRST call wins. Call shutdown() before re-initializing. Differences ignored: " + diffs.join(", ")
|
|
2844
|
+
);
|
|
2845
|
+
} else {
|
|
2846
|
+
debug("init() called twice with identical config; no-op");
|
|
2847
|
+
}
|
|
2848
|
+
} else {
|
|
2849
|
+
debug("init() called twice; no-op");
|
|
2850
|
+
}
|
|
2418
2851
|
return;
|
|
2419
2852
|
}
|
|
2853
|
+
_finalMetrics = void 0;
|
|
2420
2854
|
const client = new RisicareClient(config);
|
|
2421
2855
|
setClient(client);
|
|
2422
2856
|
setTracer(client.tracer);
|
|
2423
2857
|
}
|
|
2424
2858
|
async function shutdown() {
|
|
2425
2859
|
try {
|
|
2426
|
-
|
|
2427
|
-
shutdownFixRuntime2();
|
|
2860
|
+
shutdownFixRuntime();
|
|
2428
2861
|
} catch {
|
|
2429
2862
|
}
|
|
2430
2863
|
const client = getClient();
|
|
@@ -2435,8 +2868,8 @@ async function shutdown() {
|
|
|
2435
2868
|
}
|
|
2436
2869
|
async function flush() {
|
|
2437
2870
|
const client = getClient();
|
|
2438
|
-
if (!client) return;
|
|
2439
|
-
|
|
2871
|
+
if (!client) return true;
|
|
2872
|
+
return client.flush();
|
|
2440
2873
|
}
|
|
2441
2874
|
function enable() {
|
|
2442
2875
|
const client = getClient();
|
|
@@ -2459,13 +2892,29 @@ function getTraceContent() {
|
|
|
2459
2892
|
}
|
|
2460
2893
|
function getMetrics() {
|
|
2461
2894
|
const client = getClient();
|
|
2462
|
-
|
|
2895
|
+
if (client && !client.isShutdown) {
|
|
2896
|
+
return { ...client.processor.getMetrics(), sdkState: "running" };
|
|
2897
|
+
}
|
|
2898
|
+
if (_finalMetrics) {
|
|
2899
|
+
return {
|
|
2900
|
+
..._finalMetrics,
|
|
2901
|
+
droppedSpansByReason: { ..._finalMetrics.droppedSpansByReason },
|
|
2902
|
+
sdkState: "shutdown"
|
|
2903
|
+
};
|
|
2904
|
+
}
|
|
2905
|
+
return {
|
|
2463
2906
|
exportedSpans: 0,
|
|
2464
2907
|
droppedSpans: 0,
|
|
2908
|
+
droppedSpansByReason: {
|
|
2909
|
+
queue_full: 0,
|
|
2910
|
+
transport_refused: 0,
|
|
2911
|
+
shutdown_residue: 0
|
|
2912
|
+
},
|
|
2465
2913
|
failedExports: 0,
|
|
2466
2914
|
queueSize: 0,
|
|
2467
2915
|
queueCapacity: 0,
|
|
2468
|
-
queueUtilization: 0
|
|
2916
|
+
queueUtilization: 0,
|
|
2917
|
+
sdkState: "uninitialised"
|
|
2469
2918
|
};
|
|
2470
2919
|
}
|
|
2471
2920
|
var _ERROR_DEDUP_TTL_MS = 5 * 60 * 1e3;
|
|
@@ -2473,7 +2922,6 @@ var _ERROR_DEDUP_MAX = 1e3;
|
|
|
2473
2922
|
var _recentErrors = /* @__PURE__ */ new Map();
|
|
2474
2923
|
function _errorFingerprint(err) {
|
|
2475
2924
|
const raw = `${err.constructor?.name ?? "Error"}:${String(err.message ?? "").slice(0, 200)}`;
|
|
2476
|
-
const { createHash: createHash2 } = __require("crypto");
|
|
2477
2925
|
return createHash2("sha256").update(raw).digest("hex").slice(0, 16);
|
|
2478
2926
|
}
|
|
2479
2927
|
function _isDuplicateError(fingerprint) {
|
|
@@ -2532,13 +2980,17 @@ function score(traceId, name, value, options) {
|
|
|
2532
2980
|
if (!client?.enabled || !client.config.apiKey) return;
|
|
2533
2981
|
const endpoint = client.config.endpoint.replace(/\/$/, "");
|
|
2534
2982
|
const url = `${endpoint}/api/v1/scores`;
|
|
2983
|
+
let comment = options?.comment;
|
|
2984
|
+
if (comment !== void 0 && client.config.mask) {
|
|
2985
|
+
comment = maskText(client.config.mask, SCORE_COMMENT_KEY, comment);
|
|
2986
|
+
}
|
|
2535
2987
|
const body = JSON.stringify({
|
|
2536
2988
|
trace_id: traceId,
|
|
2537
2989
|
name,
|
|
2538
2990
|
score: value,
|
|
2539
2991
|
source: "sdk",
|
|
2540
2992
|
...options?.spanId && { span_id: options.spanId },
|
|
2541
|
-
...
|
|
2993
|
+
...comment && { comment }
|
|
2542
2994
|
});
|
|
2543
2995
|
fetch(url, {
|
|
2544
2996
|
method: "POST",
|
|
@@ -2569,6 +3021,100 @@ function withAgent(options, fn) {
|
|
|
2569
3021
|
return runWithContext({ agent: agent2 }, fn);
|
|
2570
3022
|
}
|
|
2571
3023
|
|
|
3024
|
+
// src/lifecycle.ts
|
|
3025
|
+
var LIFECYCLE_EVENT = "risicare.lifecycle.event";
|
|
3026
|
+
var LIFECYCLE_ENTITY = "risicare.lifecycle.entity";
|
|
3027
|
+
var LIFECYCLE_STATUS = "risicare.lifecycle.status";
|
|
3028
|
+
var STATUS_MESSAGE_MAX = 500;
|
|
3029
|
+
function excSummary(error) {
|
|
3030
|
+
if (error instanceof Error) {
|
|
3031
|
+
return `${error.constructor.name}: ${error.message}`.slice(0, STATUS_MESSAGE_MAX);
|
|
3032
|
+
}
|
|
3033
|
+
return String(error).slice(0, STATUS_MESSAGE_MAX);
|
|
3034
|
+
}
|
|
3035
|
+
function stampEndMarker(span, entity, error) {
|
|
3036
|
+
try {
|
|
3037
|
+
const statusValue = error !== void 0 ? "error" : "ok";
|
|
3038
|
+
span.setAttribute(LIFECYCLE_EVENT, "end");
|
|
3039
|
+
span.setAttribute(LIFECYCLE_ENTITY, entity);
|
|
3040
|
+
span.setAttribute(LIFECYCLE_STATUS, statusValue);
|
|
3041
|
+
if (error !== void 0) {
|
|
3042
|
+
span.setStatus("error" /* ERROR */, excSummary(error));
|
|
3043
|
+
}
|
|
3044
|
+
} catch {
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
function withEndMarker(span, entity, body) {
|
|
3048
|
+
let result;
|
|
3049
|
+
try {
|
|
3050
|
+
result = body();
|
|
3051
|
+
} catch (error) {
|
|
3052
|
+
stampEndMarker(span, entity, error);
|
|
3053
|
+
throw error;
|
|
3054
|
+
}
|
|
3055
|
+
if (result instanceof Promise) {
|
|
3056
|
+
return result.then(
|
|
3057
|
+
(value) => {
|
|
3058
|
+
stampEndMarker(span, entity, void 0);
|
|
3059
|
+
return value;
|
|
3060
|
+
},
|
|
3061
|
+
(error) => {
|
|
3062
|
+
stampEndMarker(span, entity, error);
|
|
3063
|
+
throw error;
|
|
3064
|
+
}
|
|
3065
|
+
);
|
|
3066
|
+
}
|
|
3067
|
+
stampEndMarker(span, entity, void 0);
|
|
3068
|
+
return result;
|
|
3069
|
+
}
|
|
3070
|
+
function emitSessionEndMarker(error) {
|
|
3071
|
+
try {
|
|
3072
|
+
const tracer = getTracer2();
|
|
3073
|
+
if (!tracer) return;
|
|
3074
|
+
const statusValue = error !== void 0 ? "error" : "ok";
|
|
3075
|
+
tracer.startSpan(
|
|
3076
|
+
{
|
|
3077
|
+
name: "session.end",
|
|
3078
|
+
kind: "internal" /* INTERNAL */,
|
|
3079
|
+
attributes: {
|
|
3080
|
+
[LIFECYCLE_EVENT]: "end",
|
|
3081
|
+
[LIFECYCLE_ENTITY]: "session",
|
|
3082
|
+
[LIFECYCLE_STATUS]: statusValue
|
|
3083
|
+
}
|
|
3084
|
+
},
|
|
3085
|
+
(span) => {
|
|
3086
|
+
if (error !== void 0) {
|
|
3087
|
+
span.setStatus("error" /* ERROR */, excSummary(error));
|
|
3088
|
+
}
|
|
3089
|
+
}
|
|
3090
|
+
);
|
|
3091
|
+
} catch {
|
|
3092
|
+
}
|
|
3093
|
+
}
|
|
3094
|
+
function withSessionEndMarker(body) {
|
|
3095
|
+
let result;
|
|
3096
|
+
try {
|
|
3097
|
+
result = body();
|
|
3098
|
+
} catch (error) {
|
|
3099
|
+
emitSessionEndMarker(error);
|
|
3100
|
+
throw error;
|
|
3101
|
+
}
|
|
3102
|
+
if (result instanceof Promise) {
|
|
3103
|
+
return result.then(
|
|
3104
|
+
(value) => {
|
|
3105
|
+
emitSessionEndMarker(void 0);
|
|
3106
|
+
return value;
|
|
3107
|
+
},
|
|
3108
|
+
(error) => {
|
|
3109
|
+
emitSessionEndMarker(error);
|
|
3110
|
+
throw error;
|
|
3111
|
+
}
|
|
3112
|
+
);
|
|
3113
|
+
}
|
|
3114
|
+
emitSessionEndMarker(void 0);
|
|
3115
|
+
return result;
|
|
3116
|
+
}
|
|
3117
|
+
|
|
2572
3118
|
// src/decorators/agent.ts
|
|
2573
3119
|
function _wrapAgent(options, fn) {
|
|
2574
3120
|
const spanName = `agent:${options.name ?? "agent"}`;
|
|
@@ -2578,9 +3124,10 @@ function _wrapAgent(options, fn) {
|
|
|
2578
3124
|
return fn(...args);
|
|
2579
3125
|
}
|
|
2580
3126
|
return withAgent(options, () => {
|
|
2581
|
-
return tracer.startSpan(
|
|
2582
|
-
|
|
2583
|
-
|
|
3127
|
+
return tracer.startSpan(
|
|
3128
|
+
{ name: spanName, kind: "agent" /* AGENT */ },
|
|
3129
|
+
(span) => withEndMarker(span, "agent", () => fn(...args))
|
|
3130
|
+
);
|
|
2584
3131
|
});
|
|
2585
3132
|
};
|
|
2586
3133
|
}
|
|
@@ -2607,7 +3154,7 @@ function withSession(options, fn) {
|
|
|
2607
3154
|
function _wrapSession(optionsOrResolver, fn) {
|
|
2608
3155
|
return (...args) => {
|
|
2609
3156
|
const options = typeof optionsOrResolver === "function" ? optionsOrResolver(...args) : optionsOrResolver;
|
|
2610
|
-
return withSession(options, () => fn(...args));
|
|
3157
|
+
return withSession(options, () => withSessionEndMarker(() => fn(...args)));
|
|
2611
3158
|
};
|
|
2612
3159
|
}
|
|
2613
3160
|
function session(optionsOrResolver, fn) {
|
|
@@ -2630,7 +3177,10 @@ function phaseWrapper(phase, kind, name, fn) {
|
|
|
2630
3177
|
return fn(...args);
|
|
2631
3178
|
}
|
|
2632
3179
|
return withPhase(phase, () => {
|
|
2633
|
-
return tracer.startSpan(
|
|
3180
|
+
return tracer.startSpan(
|
|
3181
|
+
{ name, kind },
|
|
3182
|
+
(span) => withEndMarker(span, "trace", () => fn(...args))
|
|
3183
|
+
);
|
|
2634
3184
|
});
|
|
2635
3185
|
};
|
|
2636
3186
|
}
|
|
@@ -2680,7 +3230,8 @@ function traceMessage(options, fn) {
|
|
|
2680
3230
|
"message.target_agent_id": options.to
|
|
2681
3231
|
}
|
|
2682
3232
|
},
|
|
2683
|
-
|
|
3233
|
+
// F-B-012: multi-agent decorators are @trace-family — entity="trace".
|
|
3234
|
+
(span) => withEndMarker(span, "trace", () => fn(...args))
|
|
2684
3235
|
);
|
|
2685
3236
|
};
|
|
2686
3237
|
}
|
|
@@ -2699,7 +3250,8 @@ function traceDelegate(options, fn) {
|
|
|
2699
3250
|
"message.target_agent_id": options.to
|
|
2700
3251
|
}
|
|
2701
3252
|
},
|
|
2702
|
-
|
|
3253
|
+
// F-B-012: multi-agent decorators are @trace-family — entity="trace".
|
|
3254
|
+
(span) => withEndMarker(span, "trace", () => fn(...args))
|
|
2703
3255
|
);
|
|
2704
3256
|
};
|
|
2705
3257
|
}
|
|
@@ -2717,7 +3269,8 @@ function traceCoordinate(options, fn) {
|
|
|
2717
3269
|
"message.type": "coordinate" /* COORDINATE */
|
|
2718
3270
|
}
|
|
2719
3271
|
},
|
|
2720
|
-
|
|
3272
|
+
// F-B-012: multi-agent decorators are @trace-family — entity="trace".
|
|
3273
|
+
(span) => withEndMarker(span, "trace", () => fn(...args))
|
|
2721
3274
|
);
|
|
2722
3275
|
};
|
|
2723
3276
|
}
|
|
@@ -2810,7 +3363,6 @@ function extractTraceContext(headers) {
|
|
|
2810
3363
|
}
|
|
2811
3364
|
|
|
2812
3365
|
// src/context/registry.ts
|
|
2813
|
-
init_globals();
|
|
2814
3366
|
var DEFAULT_TTL_MS = 6e4;
|
|
2815
3367
|
var MAX_ENTRIES = 1e4;
|
|
2816
3368
|
var CLEANUP_INTERVAL = 100;
|
|
@@ -2889,9 +3441,61 @@ function isProviderInstrumentationSuppressed() {
|
|
|
2889
3441
|
}
|
|
2890
3442
|
|
|
2891
3443
|
// src/frameworks/langchain.ts
|
|
2892
|
-
|
|
3444
|
+
function resolveBaseCallbackHandler() {
|
|
3445
|
+
try {
|
|
3446
|
+
const { createRequire } = __require("module");
|
|
3447
|
+
const req = createRequire(import.meta.url);
|
|
3448
|
+
const mod = req("@langchain/core/callbacks/base");
|
|
3449
|
+
if (mod?.BaseCallbackHandler) {
|
|
3450
|
+
return mod.BaseCallbackHandler;
|
|
3451
|
+
}
|
|
3452
|
+
} catch {
|
|
3453
|
+
}
|
|
3454
|
+
try {
|
|
3455
|
+
const mod = __require("@langchain/core/callbacks/base");
|
|
3456
|
+
if (mod?.BaseCallbackHandler) {
|
|
3457
|
+
return mod.BaseCallbackHandler;
|
|
3458
|
+
}
|
|
3459
|
+
} catch {
|
|
3460
|
+
debug("RisicareCallbackHandler: @langchain/core not installed; handler will not satisfy LangChain v0.2+ instanceof check");
|
|
3461
|
+
}
|
|
3462
|
+
return Object;
|
|
3463
|
+
}
|
|
3464
|
+
var _BaseCallbackHandler = resolveBaseCallbackHandler();
|
|
3465
|
+
var RisicareCallbackHandler = class _RisicareCallbackHandler extends _BaseCallbackHandler {
|
|
3466
|
+
// PR-4+5 review B1: duck-type markers that LangChain v0.3's
|
|
3467
|
+
// `isBaseCallbackHandler(x)` checks. This is the ONLY reliable way to be
|
|
3468
|
+
// recognised across the CJS↔ESM identity split — `instanceof` cannot work
|
|
3469
|
+
// when our `createRequire`-loaded BaseCallbackHandler is a different
|
|
3470
|
+
// class object from the customer's ESM-imported BaseCallbackHandler.
|
|
3471
|
+
// Keep these as instance properties (not prototype) so they survive any
|
|
3472
|
+
// Object-fallback path when @langchain/core is absent.
|
|
2893
3473
|
name = "RisicareCallbackHandler";
|
|
3474
|
+
awaitHandlers = true;
|
|
3475
|
+
ignoreLLM = false;
|
|
3476
|
+
ignoreChain = false;
|
|
3477
|
+
ignoreAgent = false;
|
|
3478
|
+
ignoreRetriever = false;
|
|
3479
|
+
ignoreCustomEvent = false;
|
|
3480
|
+
raiseError = false;
|
|
3481
|
+
lc_serializable = false;
|
|
3482
|
+
lc_kwargs = {};
|
|
2894
3483
|
_spans = /* @__PURE__ */ new Map();
|
|
3484
|
+
constructor() {
|
|
3485
|
+
super();
|
|
3486
|
+
}
|
|
3487
|
+
/**
|
|
3488
|
+
* Required by LangChain's `isBaseCallbackHandler(x)` duck-type check
|
|
3489
|
+
* (`typeof x.copy === 'function'`). When @langchain/core is installed
|
|
3490
|
+
* BaseCallbackHandler's prototype provides its own `copy()`; this
|
|
3491
|
+
* declaration overrides with a Risicare-aware copy that re-instantiates
|
|
3492
|
+
* — sufficient for the handler-cloning paths LangChain uses internally
|
|
3493
|
+
* (e.g., per-run isolation in concurrent chains). Spans map starts empty
|
|
3494
|
+
* because a fresh handler should not share span state with its parent.
|
|
3495
|
+
*/
|
|
3496
|
+
copy() {
|
|
3497
|
+
return new _RisicareCallbackHandler();
|
|
3498
|
+
}
|
|
2895
3499
|
/**
|
|
2896
3500
|
* Run a function with provider instrumentation suppressed.
|
|
2897
3501
|
*
|
|
@@ -2908,57 +3512,75 @@ var RisicareCallbackHandler = class {
|
|
|
2908
3512
|
withSuppression(fn) {
|
|
2909
3513
|
return suppressProviderInstrumentation(fn);
|
|
2910
3514
|
}
|
|
2911
|
-
// ──
|
|
2912
|
-
|
|
3515
|
+
// ── Internal helpers ──────────────────────────────────────────────────────
|
|
3516
|
+
_startSpan(runId, parentRunId, name, kind, extraAttrs = {}) {
|
|
2913
3517
|
const tracer = getTracer2();
|
|
2914
3518
|
if (!tracer?.enabled) return;
|
|
2915
3519
|
const parentEntry = parentRunId ? this._spans.get(parentRunId) : void 0;
|
|
2916
3520
|
const span = tracer.createSpan({
|
|
2917
|
-
name
|
|
2918
|
-
kind
|
|
3521
|
+
name,
|
|
3522
|
+
kind,
|
|
2919
3523
|
parentSpanId: parentEntry?.span.spanId,
|
|
2920
3524
|
traceId: parentEntry?.span.traceId,
|
|
2921
3525
|
attributes: {
|
|
2922
|
-
|
|
3526
|
+
framework: "langchain",
|
|
2923
3527
|
"langchain.run_id": runId,
|
|
2924
3528
|
...parentRunId ? { "langchain.parent_run_id": parentRunId } : {},
|
|
2925
|
-
...
|
|
3529
|
+
...extraAttrs
|
|
2926
3530
|
}
|
|
2927
3531
|
});
|
|
2928
3532
|
this._spans.set(runId, { span, startTime: Date.now() });
|
|
2929
3533
|
}
|
|
2930
|
-
|
|
3534
|
+
_endSpan(runId, extraAttrs = {}) {
|
|
2931
3535
|
const entry = this._spans.get(runId);
|
|
2932
3536
|
if (!entry) return;
|
|
3537
|
+
for (const [k, v] of Object.entries(extraAttrs)) {
|
|
3538
|
+
entry.span.setAttribute(k, v);
|
|
3539
|
+
}
|
|
2933
3540
|
entry.span.setAttribute("gen_ai.latency_ms", Date.now() - entry.startTime);
|
|
2934
3541
|
entry.span.end();
|
|
2935
3542
|
this._spans.delete(runId);
|
|
2936
3543
|
}
|
|
2937
|
-
|
|
3544
|
+
_errorSpan(runId, error) {
|
|
2938
3545
|
const entry = this._spans.get(runId);
|
|
2939
3546
|
if (!entry) return;
|
|
2940
3547
|
entry.span.recordException(error);
|
|
2941
3548
|
entry.span.end();
|
|
2942
3549
|
this._spans.delete(runId);
|
|
2943
3550
|
}
|
|
3551
|
+
// ── Chain lifecycle ────────────────────────────────────────────────────────
|
|
3552
|
+
handleChainStart(chain, _inputs, runId, parentRunId) {
|
|
3553
|
+
this._startSpan(runId, parentRunId, chain.name || chain._type || "chain", "internal" /* INTERNAL */, {
|
|
3554
|
+
...chain._type ? { "langchain.chain_type": chain._type } : {}
|
|
3555
|
+
});
|
|
3556
|
+
}
|
|
3557
|
+
handleChainEnd(_outputs, runId) {
|
|
3558
|
+
this._endSpan(runId);
|
|
3559
|
+
}
|
|
3560
|
+
handleChainError(error, runId) {
|
|
3561
|
+
this._errorSpan(runId, error);
|
|
3562
|
+
}
|
|
2944
3563
|
// ── LLM lifecycle ─────────────────────────────────────────────────────────
|
|
2945
3564
|
handleLLMStart(llm, _prompts, runId, parentRunId) {
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
|
|
2958
|
-
|
|
2959
|
-
|
|
3565
|
+
this._startSpan(runId, parentRunId, llm.name || llm._type || "llm", "llm_call" /* LLM_CALL */, {
|
|
3566
|
+
"gen_ai.system": "langchain",
|
|
3567
|
+
"gen_ai.prompt.count": _prompts.length
|
|
3568
|
+
});
|
|
3569
|
+
}
|
|
3570
|
+
/**
|
|
3571
|
+
* F-882: chat-model lifecycle — LangChain v0.2+ emits this for any
|
|
3572
|
+
* ChatModel (which is EVERY production LLM today). Without this method,
|
|
3573
|
+
* not a single `langchain` LLM span fires when used via LCEL.
|
|
3574
|
+
*
|
|
3575
|
+
* The messages payload is an array-of-arrays (one inner array per prompt);
|
|
3576
|
+
* we just count rather than materialize content (PII boundary).
|
|
3577
|
+
*/
|
|
3578
|
+
handleChatModelStart(llm, messages, runId, parentRunId) {
|
|
3579
|
+
const messageCount = Array.isArray(messages) ? messages.reduce((sum, arr) => sum + (Array.isArray(arr) ? arr.length : 0), 0) : 0;
|
|
3580
|
+
this._startSpan(runId, parentRunId, llm.name || llm._type || "chat_model", "llm_call" /* LLM_CALL */, {
|
|
3581
|
+
"gen_ai.system": "langchain",
|
|
3582
|
+
"gen_ai.message.count": messageCount
|
|
2960
3583
|
});
|
|
2961
|
-
this._spans.set(runId, { span, startTime: Date.now() });
|
|
2962
3584
|
}
|
|
2963
3585
|
handleLLMEnd(output, runId) {
|
|
2964
3586
|
const entry = this._spans.get(runId);
|
|
@@ -2980,73 +3602,105 @@ var RisicareCallbackHandler = class {
|
|
|
2980
3602
|
this._spans.delete(runId);
|
|
2981
3603
|
}
|
|
2982
3604
|
handleLLMError(error, runId) {
|
|
3605
|
+
this._errorSpan(runId, error);
|
|
3606
|
+
}
|
|
3607
|
+
/**
|
|
3608
|
+
* F-883: streaming-token event. We do NOT create a new span (the LLM span
|
|
3609
|
+
* already exists from handleLLMStart/handleChatModelStart) — just count tokens
|
|
3610
|
+
* on the existing span. This is a HIGH-FREQUENCY event; do the cheap work only.
|
|
3611
|
+
*/
|
|
3612
|
+
handleLLMNewToken(_token, _idx, runId) {
|
|
2983
3613
|
const entry = this._spans.get(runId);
|
|
2984
3614
|
if (!entry) return;
|
|
2985
|
-
entry.span.
|
|
2986
|
-
entry.span.
|
|
2987
|
-
this._spans.delete(runId);
|
|
3615
|
+
const prior = entry.span.attributes?.["gen_ai.stream.token_count"] ?? 0;
|
|
3616
|
+
entry.span.setAttribute("gen_ai.stream.token_count", prior + 1);
|
|
2988
3617
|
}
|
|
2989
3618
|
// ── Tool lifecycle ────────────────────────────────────────────────────────
|
|
2990
3619
|
handleToolStart(tool, input, runId, parentRunId) {
|
|
3620
|
+
this._startSpan(runId, parentRunId, tool.name || "tool", "tool_call" /* TOOL_CALL */, {
|
|
3621
|
+
"tool.name": tool.name || "unknown",
|
|
3622
|
+
"tool.input_length": input?.length ?? 0
|
|
3623
|
+
});
|
|
3624
|
+
}
|
|
3625
|
+
handleToolEnd(output, runId) {
|
|
3626
|
+
this._endSpan(runId, { "tool.output_length": output?.length ?? 0 });
|
|
3627
|
+
}
|
|
3628
|
+
handleToolError(error, runId) {
|
|
3629
|
+
this._errorSpan(runId, error);
|
|
3630
|
+
}
|
|
3631
|
+
// ── Retriever lifecycle ───────────────────────────────────────────────────
|
|
3632
|
+
handleRetrieverStart(retriever, _query, runId, parentRunId) {
|
|
3633
|
+
this._startSpan(runId, parentRunId, retriever.name || "retriever", "retrieval" /* RETRIEVAL */);
|
|
3634
|
+
}
|
|
3635
|
+
handleRetrieverEnd(documents, runId) {
|
|
3636
|
+
this._endSpan(runId, { "retriever.document_count": documents?.length ?? 0 });
|
|
3637
|
+
}
|
|
3638
|
+
handleRetrieverError(error, runId) {
|
|
3639
|
+
this._errorSpan(runId, error);
|
|
3640
|
+
}
|
|
3641
|
+
// ── Agent lifecycle (F-882) ───────────────────────────────────────────────
|
|
3642
|
+
/**
|
|
3643
|
+
* Agent decided to take an action (call a tool). LangChain v0.2 agents emit
|
|
3644
|
+
* this between LLM calls. Cheap span, no parent change.
|
|
3645
|
+
*/
|
|
3646
|
+
handleAgentAction(action, runId, parentRunId) {
|
|
2991
3647
|
const tracer = getTracer2();
|
|
2992
3648
|
if (!tracer?.enabled) return;
|
|
2993
3649
|
const parentEntry = parentRunId ? this._spans.get(parentRunId) : void 0;
|
|
2994
3650
|
const span = tracer.createSpan({
|
|
2995
|
-
name: tool
|
|
2996
|
-
kind: "
|
|
3651
|
+
name: `agent.action:${action.tool ?? "unknown"}`,
|
|
3652
|
+
kind: "internal" /* INTERNAL */,
|
|
2997
3653
|
parentSpanId: parentEntry?.span.spanId,
|
|
2998
3654
|
traceId: parentEntry?.span.traceId,
|
|
2999
3655
|
attributes: {
|
|
3000
|
-
|
|
3656
|
+
framework: "langchain",
|
|
3001
3657
|
"langchain.run_id": runId,
|
|
3002
|
-
"tool
|
|
3003
|
-
"tool.input_length": input?.length ?? 0
|
|
3658
|
+
"agent.action.tool": action.tool ?? ""
|
|
3004
3659
|
}
|
|
3005
3660
|
});
|
|
3006
|
-
|
|
3007
|
-
}
|
|
3008
|
-
handleToolEnd(output, runId) {
|
|
3009
|
-
const entry = this._spans.get(runId);
|
|
3010
|
-
if (!entry) return;
|
|
3011
|
-
entry.span.setAttribute("tool.output_length", output?.length ?? 0);
|
|
3012
|
-
entry.span.setAttribute("gen_ai.latency_ms", Date.now() - entry.startTime);
|
|
3013
|
-
entry.span.end();
|
|
3014
|
-
this._spans.delete(runId);
|
|
3015
|
-
}
|
|
3016
|
-
handleToolError(error, runId) {
|
|
3017
|
-
const entry = this._spans.get(runId);
|
|
3018
|
-
if (!entry) return;
|
|
3019
|
-
entry.span.recordException(error);
|
|
3020
|
-
entry.span.end();
|
|
3021
|
-
this._spans.delete(runId);
|
|
3661
|
+
span.end();
|
|
3022
3662
|
}
|
|
3023
|
-
|
|
3024
|
-
|
|
3663
|
+
/**
|
|
3664
|
+
* Agent finished (final answer produced). Mirror of handleAgentAction.
|
|
3665
|
+
*/
|
|
3666
|
+
handleAgentEnd(action, runId, parentRunId) {
|
|
3025
3667
|
const tracer = getTracer2();
|
|
3026
3668
|
if (!tracer?.enabled) return;
|
|
3027
3669
|
const parentEntry = parentRunId ? this._spans.get(parentRunId) : void 0;
|
|
3028
3670
|
const span = tracer.createSpan({
|
|
3029
|
-
name:
|
|
3030
|
-
kind: "
|
|
3671
|
+
name: "agent.end",
|
|
3672
|
+
kind: "internal" /* INTERNAL */,
|
|
3031
3673
|
parentSpanId: parentEntry?.span.spanId,
|
|
3032
3674
|
traceId: parentEntry?.span.traceId,
|
|
3033
3675
|
attributes: {
|
|
3034
|
-
|
|
3035
|
-
"langchain.run_id": runId
|
|
3676
|
+
framework: "langchain",
|
|
3677
|
+
"langchain.run_id": runId,
|
|
3678
|
+
"agent.return_keys": action.returnValues ? Object.keys(action.returnValues).length : 0
|
|
3036
3679
|
}
|
|
3037
3680
|
});
|
|
3038
|
-
|
|
3681
|
+
span.end();
|
|
3039
3682
|
}
|
|
3040
|
-
|
|
3683
|
+
// ── Misc (F-882) ──────────────────────────────────────────────────────────
|
|
3684
|
+
/**
|
|
3685
|
+
* Free-text emission (logging-style). Used by ConversationalRetrievalChain
|
|
3686
|
+
* and verbose prints. Adds an event to the current chain span if one exists.
|
|
3687
|
+
*/
|
|
3688
|
+
handleText(text, runId, _parentRunId) {
|
|
3041
3689
|
const entry = this._spans.get(runId);
|
|
3042
3690
|
if (!entry) return;
|
|
3043
|
-
entry.span.
|
|
3044
|
-
"
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
|
|
3049
|
-
|
|
3691
|
+
entry.span.addEvent("langchain.text", {
|
|
3692
|
+
"text.length": text?.length ?? 0
|
|
3693
|
+
});
|
|
3694
|
+
}
|
|
3695
|
+
/**
|
|
3696
|
+
* Custom event hook (introduced in @langchain/core 0.2.14). Customer code can
|
|
3697
|
+
* `dispatchCustomEvent(name, payload)` from inside a runnable. We surface as
|
|
3698
|
+
* a span event on the closest enclosing run so it shows up in the trace.
|
|
3699
|
+
*/
|
|
3700
|
+
handleCustomEvent(eventName, _payload, runId, _tags, _metadata) {
|
|
3701
|
+
const entry = this._spans.get(runId);
|
|
3702
|
+
if (!entry) return;
|
|
3703
|
+
entry.span.addEvent("langchain.custom_event", { name: eventName });
|
|
3050
3704
|
}
|
|
3051
3705
|
};
|
|
3052
3706
|
|
|
@@ -3084,52 +3738,88 @@ function instrumentLangGraph(graph) {
|
|
|
3084
3738
|
});
|
|
3085
3739
|
}
|
|
3086
3740
|
|
|
3741
|
+
// src/utils/assert-client.ts
|
|
3742
|
+
function assertClient(patcherName, client) {
|
|
3743
|
+
if (client === null || client === void 0) {
|
|
3744
|
+
throw new TypeError(
|
|
3745
|
+
`${patcherName} requires a client object, got ${client === null ? "null" : "undefined"}`
|
|
3746
|
+
);
|
|
3747
|
+
}
|
|
3748
|
+
const t = typeof client;
|
|
3749
|
+
if (t !== "object" && t !== "function") {
|
|
3750
|
+
throw new TypeError(
|
|
3751
|
+
`${patcherName} requires a client object, got ${t}`
|
|
3752
|
+
);
|
|
3753
|
+
}
|
|
3754
|
+
}
|
|
3755
|
+
|
|
3087
3756
|
// src/frameworks/instructor.ts
|
|
3088
|
-
|
|
3757
|
+
function makePatchedCreate(originalCreate) {
|
|
3758
|
+
return function patchedCreate(...args) {
|
|
3759
|
+
const tracer = getTracer2();
|
|
3760
|
+
if (!tracer?.enabled) {
|
|
3761
|
+
debug("Tracer not initialized \u2014 call init() before using patchInstructor()");
|
|
3762
|
+
return originalCreate.apply(this, args);
|
|
3763
|
+
}
|
|
3764
|
+
const params = args[0] ?? {};
|
|
3765
|
+
const responseModel = params.response_model ?? params.responseModel;
|
|
3766
|
+
let modelName = "unknown";
|
|
3767
|
+
if (responseModel && typeof responseModel === "function") {
|
|
3768
|
+
modelName = responseModel.name || "unknown";
|
|
3769
|
+
} else if (responseModel && typeof responseModel === "object") {
|
|
3770
|
+
const rm = responseModel;
|
|
3771
|
+
modelName = rm.name ?? rm.description ?? rm.schema?.name ?? "schema";
|
|
3772
|
+
} else if (typeof responseModel === "string") {
|
|
3773
|
+
modelName = responseModel;
|
|
3774
|
+
}
|
|
3775
|
+
return tracer.startSpan(
|
|
3776
|
+
{
|
|
3777
|
+
name: "instructor.create",
|
|
3778
|
+
kind: "llm_call" /* LLM_CALL */,
|
|
3779
|
+
attributes: {
|
|
3780
|
+
framework: "instructor",
|
|
3781
|
+
"framework.span_kind": "extraction",
|
|
3782
|
+
"instructor.response_model": modelName,
|
|
3783
|
+
...params.max_retries != null ? { "instructor.max_retries": params.max_retries } : {},
|
|
3784
|
+
...params.model != null ? { "gen_ai.request.model": params.model } : {}
|
|
3785
|
+
}
|
|
3786
|
+
},
|
|
3787
|
+
(_span) => {
|
|
3788
|
+
const result = originalCreate.apply(this, args);
|
|
3789
|
+
if (result && typeof result.then === "function") {
|
|
3790
|
+
return result.then((r) => r);
|
|
3791
|
+
}
|
|
3792
|
+
return result;
|
|
3793
|
+
}
|
|
3794
|
+
);
|
|
3795
|
+
};
|
|
3796
|
+
}
|
|
3089
3797
|
function patchInstructor(client) {
|
|
3798
|
+
assertClient("patchInstructor", client);
|
|
3090
3799
|
return new Proxy(client, {
|
|
3091
3800
|
get(target, prop, receiver) {
|
|
3092
3801
|
const value = Reflect.get(target, prop, receiver);
|
|
3093
3802
|
if (prop === "create" && typeof value === "function") {
|
|
3094
|
-
return
|
|
3095
|
-
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
);
|
|
3100
|
-
|
|
3101
|
-
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
|
|
3105
|
-
|
|
3106
|
-
|
|
3107
|
-
|
|
3108
|
-
|
|
3109
|
-
|
|
3110
|
-
modelName = responseModel;
|
|
3111
|
-
}
|
|
3112
|
-
return tracer.startSpan(
|
|
3113
|
-
{
|
|
3114
|
-
name: "instructor.create",
|
|
3115
|
-
kind: "llm_call" /* LLM_CALL */,
|
|
3116
|
-
attributes: {
|
|
3117
|
-
framework: "instructor",
|
|
3118
|
-
"framework.span_kind": "extraction",
|
|
3119
|
-
"instructor.response_model": modelName,
|
|
3120
|
-
...params.max_retries != null ? { "instructor.max_retries": params.max_retries } : {},
|
|
3121
|
-
...params.model != null ? { "gen_ai.request.model": params.model } : {}
|
|
3122
|
-
}
|
|
3123
|
-
},
|
|
3124
|
-
(_span) => {
|
|
3125
|
-
const result = value.apply(this, args);
|
|
3126
|
-
if (result && typeof result.then === "function") {
|
|
3127
|
-
return result.then((r) => r);
|
|
3128
|
-
}
|
|
3129
|
-
return result;
|
|
3803
|
+
return makePatchedCreate(value.bind(target));
|
|
3804
|
+
}
|
|
3805
|
+
if (prop === "chat" && value && typeof value === "object") {
|
|
3806
|
+
return new Proxy(value, {
|
|
3807
|
+
get(chatTarget, chatProp, chatReceiver) {
|
|
3808
|
+
const chatValue = Reflect.get(chatTarget, chatProp, chatReceiver);
|
|
3809
|
+
if (chatProp === "completions" && chatValue && typeof chatValue === "object") {
|
|
3810
|
+
return new Proxy(chatValue, {
|
|
3811
|
+
get(compTarget, compProp, compReceiver) {
|
|
3812
|
+
const compValue = Reflect.get(compTarget, compProp, compReceiver);
|
|
3813
|
+
if (compProp === "create" && typeof compValue === "function") {
|
|
3814
|
+
return makePatchedCreate(compValue.bind(compTarget));
|
|
3815
|
+
}
|
|
3816
|
+
return compValue;
|
|
3817
|
+
}
|
|
3818
|
+
});
|
|
3130
3819
|
}
|
|
3131
|
-
|
|
3132
|
-
|
|
3820
|
+
return chatValue;
|
|
3821
|
+
}
|
|
3822
|
+
});
|
|
3133
3823
|
}
|
|
3134
3824
|
return value;
|
|
3135
3825
|
}
|
|
@@ -3137,89 +3827,129 @@ function patchInstructor(client) {
|
|
|
3137
3827
|
}
|
|
3138
3828
|
|
|
3139
3829
|
// src/frameworks/llamaindex.ts
|
|
3830
|
+
var EVENT_PHASE = {
|
|
3831
|
+
// LLM
|
|
3832
|
+
"llm-start": "start",
|
|
3833
|
+
"llm-end": "end",
|
|
3834
|
+
"llm-error": "error",
|
|
3835
|
+
"llm-tool-call": "start",
|
|
3836
|
+
"llm-tool-result": "end",
|
|
3837
|
+
"llm-stream": "end",
|
|
3838
|
+
// Chat
|
|
3839
|
+
"chat-start": "start",
|
|
3840
|
+
"chat-end": "end",
|
|
3841
|
+
// Embeddings
|
|
3842
|
+
"embedding-start": "start",
|
|
3843
|
+
"embedding-end": "end",
|
|
3844
|
+
// Retrieval
|
|
3845
|
+
"retrieve-start": "start",
|
|
3846
|
+
"retrieve-end": "end",
|
|
3847
|
+
// Query / synthesis
|
|
3848
|
+
"query-start": "start",
|
|
3849
|
+
"query-end": "end",
|
|
3850
|
+
"synthesize-start": "start",
|
|
3851
|
+
"synthesize-end": "end",
|
|
3852
|
+
// Agent
|
|
3853
|
+
"agent-start": "start",
|
|
3854
|
+
"agent-end": "end",
|
|
3855
|
+
"agent-step-start": "start",
|
|
3856
|
+
"agent-step-end": "end"
|
|
3857
|
+
};
|
|
3140
3858
|
var RisicareLlamaIndexHandler = class {
|
|
3859
|
+
/**
|
|
3860
|
+
* Public, iterable list of all event names this handler responds to.
|
|
3861
|
+
* Customers should subscribe to each on the LlamaIndex callback manager:
|
|
3862
|
+
* for (const n of RisicareLlamaIndexHandler.EVENT_NAMES) Settings.callbackManager.on(n, ...)
|
|
3863
|
+
*/
|
|
3864
|
+
static EVENT_NAMES = Object.keys(EVENT_PHASE);
|
|
3141
3865
|
_spans = /* @__PURE__ */ new Map();
|
|
3142
3866
|
/**
|
|
3143
3867
|
* Handle a LlamaIndex lifecycle event.
|
|
3144
|
-
*
|
|
3145
|
-
* Events follow the convention:
|
|
3146
|
-
* - `*.start` / `*.begin` -- component starts
|
|
3147
|
-
* - `*.end` / `*.complete` -- component finishes
|
|
3148
|
-
* - `*.error` -- component failed
|
|
3149
3868
|
*/
|
|
3150
3869
|
onEvent(event) {
|
|
3151
3870
|
const tracer = getTracer2();
|
|
3152
3871
|
if (!tracer?.enabled) return;
|
|
3153
|
-
|
|
3154
|
-
|
|
3155
|
-
|
|
3156
|
-
|
|
3157
|
-
|
|
3158
|
-
|
|
3872
|
+
const payload = event.detail ?? event.data ?? {};
|
|
3873
|
+
let phase = EVENT_PHASE[event.type];
|
|
3874
|
+
if (!phase) {
|
|
3875
|
+
if (event.type.endsWith(".start") || event.type.endsWith(".begin")) {
|
|
3876
|
+
phase = "start";
|
|
3877
|
+
} else if (event.type.endsWith(".end") || event.type.endsWith(".complete")) {
|
|
3878
|
+
phase = "end";
|
|
3879
|
+
} else if (event.type.endsWith(".error")) {
|
|
3880
|
+
phase = "error";
|
|
3881
|
+
}
|
|
3882
|
+
}
|
|
3883
|
+
if (!phase) return;
|
|
3884
|
+
const id = payload.id ?? event.id ?? "";
|
|
3885
|
+
const parentId = payload.parentId ?? event.parentId;
|
|
3886
|
+
if (!id) return;
|
|
3887
|
+
if (phase === "start") {
|
|
3888
|
+
this._handleStart(event.type, id, parentId, payload);
|
|
3889
|
+
} else if (phase === "end") {
|
|
3890
|
+
this._handleEnd(id, payload);
|
|
3891
|
+
} else {
|
|
3892
|
+
this._handleError(id, payload);
|
|
3159
3893
|
}
|
|
3160
3894
|
}
|
|
3161
3895
|
/**
|
|
3162
3896
|
* Run a function with provider instrumentation suppressed.
|
|
3163
|
-
*
|
|
3164
|
-
* LlamaIndex handler creates its own LLM spans, so provider spans
|
|
3165
|
-
* (patchOpenAI, patchAnthropic, etc.) should be suppressed to avoid
|
|
3166
|
-
* double-tracing.
|
|
3167
3897
|
*/
|
|
3168
3898
|
withSuppression(fn) {
|
|
3169
3899
|
return suppressProviderInstrumentation(fn);
|
|
3170
3900
|
}
|
|
3171
3901
|
// ── Internal event handlers ───────────────────────────────────────────────
|
|
3172
|
-
_handleStart(
|
|
3902
|
+
_handleStart(eventType, id, parentId, payload) {
|
|
3173
3903
|
const tracer = getTracer2();
|
|
3174
3904
|
if (!tracer?.enabled) return;
|
|
3175
|
-
const componentKind = this._classifyComponent(
|
|
3176
|
-
const parentEntry =
|
|
3905
|
+
const componentKind = this._classifyComponent(eventType);
|
|
3906
|
+
const parentEntry = parentId ? this._spans.get(parentId) : void 0;
|
|
3177
3907
|
const spanKind = componentKind === "llm" ? "llm_call" /* LLM_CALL */ : componentKind === "retrieval" ? "retrieval" /* RETRIEVAL */ : componentKind === "embedding" ? "llm_call" /* LLM_CALL */ : "internal" /* INTERNAL */;
|
|
3908
|
+
const spanName = eventType.replace(/\.(start|begin)$/, "").replace(/-(start|begin)$/, "");
|
|
3178
3909
|
const span = tracer.createSpan({
|
|
3179
|
-
name:
|
|
3910
|
+
name: spanName,
|
|
3180
3911
|
kind: spanKind,
|
|
3181
3912
|
parentSpanId: parentEntry?.span.spanId,
|
|
3182
3913
|
traceId: parentEntry?.span.traceId,
|
|
3183
3914
|
attributes: {
|
|
3184
3915
|
framework: "llamaindex",
|
|
3185
3916
|
"framework.span_kind": componentKind,
|
|
3186
|
-
...
|
|
3917
|
+
...payload.model ? { "gen_ai.request.model": payload.model } : {}
|
|
3187
3918
|
}
|
|
3188
3919
|
});
|
|
3189
|
-
this._spans.set(
|
|
3920
|
+
this._spans.set(id, { span, startTime: Date.now(), componentKind });
|
|
3190
3921
|
}
|
|
3191
|
-
_handleEnd(
|
|
3192
|
-
const entry = this._spans.get(
|
|
3922
|
+
_handleEnd(id, payload) {
|
|
3923
|
+
const entry = this._spans.get(id);
|
|
3193
3924
|
if (!entry) return;
|
|
3194
|
-
entry.span.setAttribute(
|
|
3195
|
-
|
|
3196
|
-
Date.now() - entry.startTime
|
|
3197
|
-
);
|
|
3198
|
-
const usage = event.data?.usage;
|
|
3925
|
+
entry.span.setAttribute("gen_ai.latency_ms", Date.now() - entry.startTime);
|
|
3926
|
+
const usage = payload.usage;
|
|
3199
3927
|
if (usage) {
|
|
3200
3928
|
entry.span.setLlmFields({
|
|
3201
3929
|
promptTokens: usage.promptTokens ?? usage.prompt_tokens,
|
|
3202
3930
|
completionTokens: usage.completionTokens ?? usage.completion_tokens
|
|
3203
3931
|
});
|
|
3204
3932
|
}
|
|
3205
|
-
if (
|
|
3933
|
+
if (payload.documentCount != null) {
|
|
3206
3934
|
entry.span.setAttribute(
|
|
3207
3935
|
"retriever.document_count",
|
|
3208
|
-
|
|
3936
|
+
payload.documentCount
|
|
3209
3937
|
);
|
|
3938
|
+
} else if (Array.isArray(payload.nodes)) {
|
|
3939
|
+
entry.span.setAttribute("retriever.document_count", payload.nodes.length);
|
|
3210
3940
|
}
|
|
3211
3941
|
entry.span.end();
|
|
3212
|
-
this._spans.delete(
|
|
3942
|
+
this._spans.delete(id);
|
|
3213
3943
|
}
|
|
3214
|
-
_handleError(
|
|
3215
|
-
const entry = this._spans.get(
|
|
3944
|
+
_handleError(id, payload) {
|
|
3945
|
+
const entry = this._spans.get(id);
|
|
3216
3946
|
if (!entry) return;
|
|
3217
|
-
const error =
|
|
3947
|
+
const error = payload.error;
|
|
3218
3948
|
entry.span.recordException(
|
|
3219
3949
|
error instanceof Error ? error : String(error ?? "Unknown error")
|
|
3220
3950
|
);
|
|
3221
3951
|
entry.span.end();
|
|
3222
|
-
this._spans.delete(
|
|
3952
|
+
this._spans.delete(id);
|
|
3223
3953
|
}
|
|
3224
3954
|
/**
|
|
3225
3955
|
* Classify a LlamaIndex event type into a component kind.
|
|
@@ -3231,13 +3961,11 @@ var RisicareLlamaIndexHandler = class {
|
|
|
3231
3961
|
if (lower.includes("retriev") || lower.includes("vector")) return "retrieval";
|
|
3232
3962
|
if (lower.includes("synth") || lower.includes("response")) return "synthesis";
|
|
3233
3963
|
if (lower.includes("query")) return "query";
|
|
3964
|
+
if (lower.includes("agent")) return "agent";
|
|
3234
3965
|
return "component";
|
|
3235
3966
|
}
|
|
3236
3967
|
};
|
|
3237
3968
|
|
|
3238
|
-
// src/index.ts
|
|
3239
|
-
init_runtime();
|
|
3240
|
-
|
|
3241
3969
|
// src/webhooks.ts
|
|
3242
3970
|
import { createHmac, timingSafeEqual } from "crypto";
|
|
3243
3971
|
import { Buffer as Buffer2 } from "buffer";
|
|
@@ -3404,6 +4132,8 @@ function verifyWebhookSignature(payload, headers, secret, opts = {}) {
|
|
|
3404
4132
|
export {
|
|
3405
4133
|
AgentRole,
|
|
3406
4134
|
DEFAULT_TIMESTAMP_TOLERANCE_S,
|
|
4135
|
+
GuardRejectedError,
|
|
4136
|
+
MASK_ERROR_MARKER,
|
|
3407
4137
|
MessageType,
|
|
3408
4138
|
RisicareCallbackHandler,
|
|
3409
4139
|
RisicareLlamaIndexHandler,
|