risicare 0.5.0 → 0.6.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 +44 -6
- package/dist/frameworks/instructor.cjs +9 -0
- package/dist/frameworks/instructor.cjs.map +1 -1
- package/dist/frameworks/instructor.js +9 -0
- package/dist/frameworks/instructor.js.map +1 -1
- package/dist/frameworks/langchain.cjs +9 -0
- package/dist/frameworks/langchain.cjs.map +1 -1
- package/dist/frameworks/langchain.js +9 -0
- package/dist/frameworks/langchain.js.map +1 -1
- package/dist/frameworks/langgraph.cjs +9 -0
- package/dist/frameworks/langgraph.cjs.map +1 -1
- package/dist/frameworks/langgraph.js +9 -0
- package/dist/frameworks/langgraph.js.map +1 -1
- package/dist/frameworks/llamaindex.cjs +9 -0
- package/dist/frameworks/llamaindex.cjs.map +1 -1
- package/dist/frameworks/llamaindex.js +9 -0
- package/dist/frameworks/llamaindex.js.map +1 -1
- package/dist/index.cjs +685 -313
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +38 -2
- package/dist/index.d.ts +38 -2
- package/dist/index.js +685 -313
- package/dist/index.js.map +1 -1
- package/dist/providers/anthropic/index.cjs +9 -0
- package/dist/providers/anthropic/index.cjs.map +1 -1
- package/dist/providers/anthropic/index.js +9 -0
- package/dist/providers/anthropic/index.js.map +1 -1
- package/dist/providers/bedrock/index.cjs +9 -0
- package/dist/providers/bedrock/index.cjs.map +1 -1
- package/dist/providers/bedrock/index.js +9 -0
- package/dist/providers/bedrock/index.js.map +1 -1
- package/dist/providers/cerebras/index.cjs +9 -0
- package/dist/providers/cerebras/index.cjs.map +1 -1
- package/dist/providers/cerebras/index.js +9 -0
- package/dist/providers/cerebras/index.js.map +1 -1
- package/dist/providers/cohere/index.cjs +9 -0
- package/dist/providers/cohere/index.cjs.map +1 -1
- package/dist/providers/cohere/index.js +9 -0
- package/dist/providers/cohere/index.js.map +1 -1
- package/dist/providers/google/index.cjs +9 -0
- package/dist/providers/google/index.cjs.map +1 -1
- package/dist/providers/google/index.js +9 -0
- package/dist/providers/google/index.js.map +1 -1
- package/dist/providers/groq/index.cjs +9 -0
- package/dist/providers/groq/index.cjs.map +1 -1
- package/dist/providers/groq/index.js +9 -0
- package/dist/providers/groq/index.js.map +1 -1
- package/dist/providers/huggingface/index.cjs +9 -0
- package/dist/providers/huggingface/index.cjs.map +1 -1
- package/dist/providers/huggingface/index.js +9 -0
- package/dist/providers/huggingface/index.js.map +1 -1
- package/dist/providers/mistral/index.cjs +9 -0
- package/dist/providers/mistral/index.cjs.map +1 -1
- package/dist/providers/mistral/index.js +9 -0
- package/dist/providers/mistral/index.js.map +1 -1
- package/dist/providers/ollama/index.cjs +9 -0
- package/dist/providers/ollama/index.cjs.map +1 -1
- package/dist/providers/ollama/index.js +9 -0
- package/dist/providers/ollama/index.js.map +1 -1
- package/dist/providers/openai/index.cjs +9 -0
- package/dist/providers/openai/index.cjs.map +1 -1
- package/dist/providers/openai/index.js +9 -0
- package/dist/providers/openai/index.js.map +1 -1
- package/dist/providers/together/index.cjs +9 -0
- package/dist/providers/together/index.cjs.map +1 -1
- package/dist/providers/together/index.js +9 -0
- package/dist/providers/together/index.js.map +1 -1
- package/dist/providers/vercel-ai/index.cjs +9 -0
- package/dist/providers/vercel-ai/index.cjs.map +1 -1
- package/dist/providers/vercel-ai/index.js +9 -0
- package/dist/providers/vercel-ai/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -129,6 +129,59 @@ function applyMask(span, mask, onError) {
|
|
|
129
129
|
}
|
|
130
130
|
markMasked(span);
|
|
131
131
|
}
|
|
132
|
+
var CONTENT_KEYS_EXACT = /* @__PURE__ */ new Set([
|
|
133
|
+
"gen_ai.system_prompt",
|
|
134
|
+
"gen_ai.prompt.message"
|
|
135
|
+
]);
|
|
136
|
+
var CONTENT_OMITTED_MARKER = "<risicare:content-omitted>";
|
|
137
|
+
function isContentKey(key) {
|
|
138
|
+
if (CONTENT_KEYS_EXACT.has(key)) return true;
|
|
139
|
+
const lastSegment = key.slice(key.lastIndexOf(".") + 1);
|
|
140
|
+
if (lastSegment === "content") return true;
|
|
141
|
+
return key.endsWith("_content");
|
|
142
|
+
}
|
|
143
|
+
function stripAttributes(attrs) {
|
|
144
|
+
let n = 0;
|
|
145
|
+
for (const k of Object.keys(attrs)) {
|
|
146
|
+
if (isContentKey(k)) {
|
|
147
|
+
attrs[k] = CONTENT_OMITTED_MARKER;
|
|
148
|
+
n++;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return n;
|
|
152
|
+
}
|
|
153
|
+
function stripContent(span) {
|
|
154
|
+
let stripped = 0;
|
|
155
|
+
if (span.attributes && typeof span.attributes === "object") {
|
|
156
|
+
stripped += stripAttributes(span.attributes);
|
|
157
|
+
}
|
|
158
|
+
if (Array.isArray(span.events)) {
|
|
159
|
+
for (const event of span.events) {
|
|
160
|
+
if (event?.attributes && typeof event.attributes === "object") {
|
|
161
|
+
stripped += stripAttributes(event.attributes);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (Array.isArray(span.links)) {
|
|
166
|
+
for (const link of span.links) {
|
|
167
|
+
if (link?.attributes && typeof link.attributes === "object") {
|
|
168
|
+
stripped += stripAttributes(link.attributes);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return stripped;
|
|
173
|
+
}
|
|
174
|
+
function stripContentBatch(spans) {
|
|
175
|
+
let total = 0;
|
|
176
|
+
for (const span of spans) {
|
|
177
|
+
try {
|
|
178
|
+
total += stripContent(span);
|
|
179
|
+
} catch {
|
|
180
|
+
debug("Could not strip content from a span");
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return total;
|
|
184
|
+
}
|
|
132
185
|
function applyMaskBatch(spans, mask, onError) {
|
|
133
186
|
let errors = 0;
|
|
134
187
|
let firstKey;
|
|
@@ -241,7 +294,14 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
|
|
|
241
294
|
_batchSize;
|
|
242
295
|
_batchTimeoutMs;
|
|
243
296
|
_maxQueueSize;
|
|
244
|
-
_debug
|
|
297
|
+
// ⚠ NO `_debug` FIELD. It existed, was assigned, and was read by NOTHING —
|
|
298
|
+
// `tsc --noEmit` had been RED on this package at HEAD for it (TS6133), which
|
|
299
|
+
// survived because `ci-local.sh` runs this package's vitest and never its
|
|
300
|
+
// typecheck, and `prepublishOnly` runs `build && test` — also no typecheck.
|
|
301
|
+
// Filed F-SDKJSTYPECHECK-001. Debug output here is gated globally by
|
|
302
|
+
// `setDebug()` in `../utils/log.ts`, so a per-processor flag was always
|
|
303
|
+
// redundant; Python's `self._debug` exists because `logging` has no such
|
|
304
|
+
// global switch.
|
|
245
305
|
_queue = [];
|
|
246
306
|
_timer = null;
|
|
247
307
|
_started = false;
|
|
@@ -253,6 +313,12 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
|
|
|
253
313
|
_lastRefusalWarnAt = Number.NEGATIVE_INFINITY;
|
|
254
314
|
// ── Masking (see `../masking.ts`) ──────────────────────────────────────────
|
|
255
315
|
_mask;
|
|
316
|
+
// ── Content capture gate (see `../masking.ts`) ─────────────────────────────
|
|
317
|
+
// Fail-closed: an unspecified value means "do not capture". This is the ONE
|
|
318
|
+
// place the gate runs for BOTH content paths — provider capture AND hand-set
|
|
319
|
+
// attributes — so it must not be conditional on anything a caller might
|
|
320
|
+
// forget to pass. Python twin: `BatchSpanProcessor._trace_content`.
|
|
321
|
+
_traceContent;
|
|
256
322
|
_lastMaskWarnAt = Number.NEGATIVE_INFINITY;
|
|
257
323
|
_lastSlowMaskWarnAt = Number.NEGATIVE_INFINITY;
|
|
258
324
|
// Metrics
|
|
@@ -290,8 +356,8 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
|
|
|
290
356
|
this._batchSize = clampedBatchSize;
|
|
291
357
|
this._batchTimeoutMs = options.batchTimeoutMs ?? 1e3;
|
|
292
358
|
this._maxQueueSize = options.maxQueueSize ?? 1e4;
|
|
293
|
-
this._debug = options.debug ?? false;
|
|
294
359
|
this._mask = options.mask;
|
|
360
|
+
this._traceContent = options.traceContent ?? false;
|
|
295
361
|
}
|
|
296
362
|
start() {
|
|
297
363
|
if (this._started) return;
|
|
@@ -488,6 +554,14 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
|
|
|
488
554
|
}
|
|
489
555
|
const batch = this._queue.splice(0, take);
|
|
490
556
|
if (batch.length === 0) return 0 /* Empty */;
|
|
557
|
+
if (!this._traceContent) {
|
|
558
|
+
const stripped = stripContentBatch(batch);
|
|
559
|
+
if (stripped > 0) {
|
|
560
|
+
debug(
|
|
561
|
+
`traceContent is off \u2014 omitted ${stripped} content field(s) from ${batch.length} span(s)`
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
491
565
|
if (this._mask !== void 0) {
|
|
492
566
|
this._applyMask(batch);
|
|
493
567
|
}
|
|
@@ -561,7 +635,7 @@ function resolveConfig(config) {
|
|
|
561
635
|
const environment = config?.environment ?? env.RISICARE_ENVIRONMENT ?? "development";
|
|
562
636
|
const serviceName = config?.serviceName ?? env.RISICARE_SERVICE_NAME;
|
|
563
637
|
const serviceVersion = config?.serviceVersion ?? env.RISICARE_SERVICE_VERSION;
|
|
564
|
-
const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT,
|
|
638
|
+
const traceContent = config?.traceContent ?? parseBool(env.RISICARE_TRACE_CONTENT, false);
|
|
565
639
|
const sampleRateRaw = config?.sampleRate ?? parseFloat(env.RISICARE_SAMPLE_RATE ?? "1.0");
|
|
566
640
|
const debug2 = config?.debug ?? parseBool(env.RISICARE_DEBUG, false);
|
|
567
641
|
const compress = config?.compress ?? parseBool(env.RISICARE_COMPRESS, false);
|
|
@@ -569,6 +643,11 @@ function resolveConfig(config) {
|
|
|
569
643
|
const batchTimeoutMsRaw = config?.batchTimeoutMs ?? parseNumericEnv(env.RISICARE_BATCH_TIMEOUT_MS, 1e3);
|
|
570
644
|
const maxQueueSizeRaw = config?.maxQueueSize ?? parseNumericEnv(env.RISICARE_MAX_QUEUE_SIZE, 1e4);
|
|
571
645
|
const sampleRate = validateSampleRate(sampleRateRaw);
|
|
646
|
+
if (sampleRate < 1) {
|
|
647
|
+
console.warn(
|
|
648
|
+
`[risicare] sampleRate=${sampleRate} \u2014 head sampling is applied in-process and the rate is NOT transmitted to the platform. Trace counts, error rates and cost figures in the dashboard will describe the sampled subset only, and cannot be scaled back to totals. Sampling is trace-coherent: a dropped trace drops whole.`
|
|
649
|
+
);
|
|
650
|
+
}
|
|
572
651
|
const batchSize = validatePositiveInt("batchSize", batchSizeRaw, DEFAULT_BATCH_SIZE, 1, 1e4);
|
|
573
652
|
const batchTimeoutMs = validatePositiveInt("batchTimeoutMs", batchTimeoutMsRaw, 1e3, 1, 6e5);
|
|
574
653
|
const maxQueueSize = validatePositiveInt("maxQueueSize", maxQueueSizeRaw, 1e4, 1, 1e6);
|
|
@@ -1008,6 +1087,444 @@ function shouldSample(traceId, sampleRate) {
|
|
|
1008
1087
|
return hash / 4294967295 < sampleRate;
|
|
1009
1088
|
}
|
|
1010
1089
|
|
|
1090
|
+
// src/runtime/config.ts
|
|
1091
|
+
function resolveFixRuntimeConfig(config) {
|
|
1092
|
+
return {
|
|
1093
|
+
apiEndpoint: config.apiEndpoint,
|
|
1094
|
+
apiKey: config.apiKey,
|
|
1095
|
+
enabled: config.enabled ?? true,
|
|
1096
|
+
cacheEnabled: config.cacheEnabled ?? true,
|
|
1097
|
+
cacheTtlMs: config.cacheTtlMs ?? 3e5,
|
|
1098
|
+
cacheMaxEntries: config.cacheMaxEntries ?? 1e3,
|
|
1099
|
+
autoRefresh: config.autoRefresh ?? true,
|
|
1100
|
+
refreshIntervalMs: config.refreshIntervalMs ?? 6e4,
|
|
1101
|
+
dryRun: config.dryRun ?? false,
|
|
1102
|
+
abTestingEnabled: config.abTestingEnabled ?? true,
|
|
1103
|
+
timeoutMs: config.timeoutMs ?? 1e3,
|
|
1104
|
+
debug: config.debug ?? false
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
function matchesError(fix, errorCode) {
|
|
1108
|
+
if (fix.errorCode === errorCode) {
|
|
1109
|
+
return true;
|
|
1110
|
+
}
|
|
1111
|
+
if (fix.errorCode.endsWith("*")) {
|
|
1112
|
+
const prefix = fix.errorCode.slice(0, -1);
|
|
1113
|
+
return errorCode.startsWith(prefix);
|
|
1114
|
+
}
|
|
1115
|
+
return false;
|
|
1116
|
+
}
|
|
1117
|
+
function shouldApply(fix, sessionHash) {
|
|
1118
|
+
if (fix.trafficPercentage >= 100) return true;
|
|
1119
|
+
if (fix.trafficPercentage <= 0) return false;
|
|
1120
|
+
const bucket = sessionHash % 100;
|
|
1121
|
+
return bucket < fix.trafficPercentage;
|
|
1122
|
+
}
|
|
1123
|
+
function activeFixFromApiResponse(item) {
|
|
1124
|
+
return {
|
|
1125
|
+
fixId: item.id ?? item.fix_id ?? item.fixId ?? "",
|
|
1126
|
+
deploymentId: item.deployment_id ?? item.deploymentId ?? "",
|
|
1127
|
+
errorCode: item.error_code ?? item.errorCode ?? "",
|
|
1128
|
+
fixType: item.fix_type ?? item.fixType ?? "prompt",
|
|
1129
|
+
config: item.config ?? {},
|
|
1130
|
+
trafficPercentage: item.traffic_percentage ?? item.trafficPercentage ?? 100,
|
|
1131
|
+
version: item.version ?? 1
|
|
1132
|
+
};
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
// src/runtime/taxonomy.generated.ts
|
|
1136
|
+
var CANONICAL_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
1137
|
+
"COMMUNICATION.CONTENT.AMBIGUOUS",
|
|
1138
|
+
"COMMUNICATION.CONTENT.CORRUPTED",
|
|
1139
|
+
"COMMUNICATION.CONTENT.INCOMPATIBLE",
|
|
1140
|
+
"COMMUNICATION.CONTENT.MALFORMED",
|
|
1141
|
+
"COMMUNICATION.CONTENT.TOO_LARGE",
|
|
1142
|
+
"COMMUNICATION.DELIVERY.DELAYED",
|
|
1143
|
+
"COMMUNICATION.DELIVERY.DUPLICATED",
|
|
1144
|
+
"COMMUNICATION.DELIVERY.EXPIRED",
|
|
1145
|
+
"COMMUNICATION.DELIVERY.OUT_OF_ORDER",
|
|
1146
|
+
"COMMUNICATION.DELIVERY.UNDELIVERABLE",
|
|
1147
|
+
"COMMUNICATION.ROUTING.BROADCAST_STORM",
|
|
1148
|
+
"COMMUNICATION.ROUTING.LOOP",
|
|
1149
|
+
"COMMUNICATION.ROUTING.NO_ROUTE",
|
|
1150
|
+
"COMMUNICATION.ROUTING.PARTITION",
|
|
1151
|
+
"COMMUNICATION.ROUTING.WRONG_ROUTE",
|
|
1152
|
+
"CONSENSUS.AGREEMENT.INCONSISTENT",
|
|
1153
|
+
"CONSENSUS.AGREEMENT.QUORUM_FAILED",
|
|
1154
|
+
"CONSENSUS.AGREEMENT.REJECTED",
|
|
1155
|
+
"CONSENSUS.AGREEMENT.STALE_VOTE",
|
|
1156
|
+
"CONSENSUS.AGREEMENT.TIMEOUT",
|
|
1157
|
+
"CONSENSUS.CONFLICT.BIAS",
|
|
1158
|
+
"CONSENSUS.CONFLICT.CASCADING",
|
|
1159
|
+
"CONSENSUS.CONFLICT.DEADLOCK",
|
|
1160
|
+
"CONSENSUS.CONFLICT.RESOLUTION_REJECTED",
|
|
1161
|
+
"CONSENSUS.CONFLICT.UNRESOLVED",
|
|
1162
|
+
"CONSENSUS.VOTING.ABSTENTION_FLOOD",
|
|
1163
|
+
"CONSENSUS.VOTING.COERCED_VOTE",
|
|
1164
|
+
"CONSENSUS.VOTING.DUPLICATE_VOTE",
|
|
1165
|
+
"CONSENSUS.VOTING.INVALID_VOTE",
|
|
1166
|
+
"CONSENSUS.VOTING.SPLIT_VOTE",
|
|
1167
|
+
"COORDINATION.HANDOFF.DELAYED",
|
|
1168
|
+
"COORDINATION.HANDOFF.DUPLICATED",
|
|
1169
|
+
"COORDINATION.HANDOFF.INCOMPLETE",
|
|
1170
|
+
"COORDINATION.HANDOFF.LOST",
|
|
1171
|
+
"COORDINATION.HANDOFF.WRONG_RECIPIENT",
|
|
1172
|
+
"COORDINATION.SYNCHRONIZATION.CLOCK_SKEW",
|
|
1173
|
+
"COORDINATION.SYNCHRONIZATION.OUT_OF_ORDER",
|
|
1174
|
+
"COORDINATION.SYNCHRONIZATION.RACE_CONDITION",
|
|
1175
|
+
"COORDINATION.SYNCHRONIZATION.SPLIT_BRAIN",
|
|
1176
|
+
"COORDINATION.SYNCHRONIZATION.VERSION_MISMATCH",
|
|
1177
|
+
"COORDINATION.WORKFLOW.CYCLE",
|
|
1178
|
+
"COORDINATION.WORKFLOW.DEADLOCK",
|
|
1179
|
+
"COORDINATION.WORKFLOW.LIVELOCK",
|
|
1180
|
+
"COORDINATION.WORKFLOW.ORPHANED",
|
|
1181
|
+
"COORDINATION.WORKFLOW.STARVATION",
|
|
1182
|
+
"MEMORY.CONTEXT_WINDOW.DROPPED",
|
|
1183
|
+
"MEMORY.CONTEXT_WINDOW.EXCEEDED",
|
|
1184
|
+
"MEMORY.CONTEXT_WINDOW.FRAGMENTED",
|
|
1185
|
+
"MEMORY.CONTEXT_WINDOW.PRIORITY_ERROR",
|
|
1186
|
+
"MEMORY.RETRIEVAL.INCOMPLETE",
|
|
1187
|
+
"MEMORY.RETRIEVAL.NOT_FOUND",
|
|
1188
|
+
"MEMORY.RETRIEVAL.OUTDATED",
|
|
1189
|
+
"MEMORY.RETRIEVAL.TOO_MANY",
|
|
1190
|
+
"MEMORY.RETRIEVAL.WRONG_MATCH",
|
|
1191
|
+
"MEMORY.STATE.CORRUPTED",
|
|
1192
|
+
"MEMORY.STATE.INCONSISTENT",
|
|
1193
|
+
"MEMORY.STATE.LOST",
|
|
1194
|
+
"MEMORY.STATE.OVERFLOW",
|
|
1195
|
+
"MEMORY.STATE.STALE",
|
|
1196
|
+
"ORCHESTRATION.DELEGATION.CAPABILITY_MISMATCH",
|
|
1197
|
+
"ORCHESTRATION.DELEGATION.CIRCULAR_DELEGATION",
|
|
1198
|
+
"ORCHESTRATION.DELEGATION.EXCESSIVE_DEPTH",
|
|
1199
|
+
"ORCHESTRATION.DELEGATION.NO_AVAILABLE_AGENT",
|
|
1200
|
+
"ORCHESTRATION.DELEGATION.OVERLOADED_AGENT",
|
|
1201
|
+
"ORCHESTRATION.LIFECYCLE.CLEANUP_FAILED",
|
|
1202
|
+
"ORCHESTRATION.LIFECYCLE.CRASHED",
|
|
1203
|
+
"ORCHESTRATION.LIFECYCLE.HUNG",
|
|
1204
|
+
"ORCHESTRATION.LIFECYCLE.SPAWN_FAILED",
|
|
1205
|
+
"ORCHESTRATION.LIFECYCLE.ZOMBIE",
|
|
1206
|
+
"ORCHESTRATION.SCALING.OVERLOADED",
|
|
1207
|
+
"ORCHESTRATION.SCALING.QUOTA_EXCEEDED",
|
|
1208
|
+
"ORCHESTRATION.SCALING.SCALE_DOWN_FAILED",
|
|
1209
|
+
"ORCHESTRATION.SCALING.SCALE_UP_FAILED",
|
|
1210
|
+
"ORCHESTRATION.SCALING.UNDERUTILIZED",
|
|
1211
|
+
"OUTPUT.FORMAT.ENCODING",
|
|
1212
|
+
"OUTPUT.FORMAT.INVALID_JSON",
|
|
1213
|
+
"OUTPUT.FORMAT.MALFORMED",
|
|
1214
|
+
"OUTPUT.FORMAT.SCHEMA_VIOLATION",
|
|
1215
|
+
"OUTPUT.FORMAT.TRUNCATED",
|
|
1216
|
+
"OUTPUT.QUALITY.INCOMPLETE",
|
|
1217
|
+
"OUTPUT.QUALITY.IRRELEVANT",
|
|
1218
|
+
"OUTPUT.QUALITY.REPETITIVE",
|
|
1219
|
+
"OUTPUT.QUALITY.UNCLEAR",
|
|
1220
|
+
"OUTPUT.QUALITY.VERBOSE",
|
|
1221
|
+
"OUTPUT.SAFETY.BIAS",
|
|
1222
|
+
"OUTPUT.SAFETY.COPYRIGHT",
|
|
1223
|
+
"OUTPUT.SAFETY.HARMFUL_CONTENT",
|
|
1224
|
+
"OUTPUT.SAFETY.PII_LEAK",
|
|
1225
|
+
"OUTPUT.SAFETY.POLICY_VIOLATION",
|
|
1226
|
+
"PERCEPTION.CONTEXT.CONFLICTING",
|
|
1227
|
+
"PERCEPTION.CONTEXT.IRRELEVANT",
|
|
1228
|
+
"PERCEPTION.CONTEXT.MISSING",
|
|
1229
|
+
"PERCEPTION.CONTEXT.OVERFLOW",
|
|
1230
|
+
"PERCEPTION.CONTEXT.STALE",
|
|
1231
|
+
"PERCEPTION.INPUT.ENCODING",
|
|
1232
|
+
"PERCEPTION.INPUT.INJECTION",
|
|
1233
|
+
"PERCEPTION.INPUT.MALFORMED",
|
|
1234
|
+
"PERCEPTION.INPUT.SCHEMA_MISMATCH",
|
|
1235
|
+
"PERCEPTION.INPUT.TRUNCATED",
|
|
1236
|
+
"PERCEPTION.PARSING.DATE_FORMAT",
|
|
1237
|
+
"PERCEPTION.PARSING.JSON_INVALID",
|
|
1238
|
+
"PERCEPTION.PARSING.NUMBER_FORMAT",
|
|
1239
|
+
"PERCEPTION.PARSING.REFERENCE_BROKEN",
|
|
1240
|
+
"PERCEPTION.PARSING.XML_INVALID",
|
|
1241
|
+
"REASONING.DECISION.BIASED",
|
|
1242
|
+
"REASONING.DECISION.INDECISIVE",
|
|
1243
|
+
"REASONING.DECISION.OSCILLATING",
|
|
1244
|
+
"REASONING.DECISION.OVERCONFIDENT",
|
|
1245
|
+
"REASONING.DECISION.PREMATURE",
|
|
1246
|
+
"REASONING.HALLUCINATION.CAPABILITY",
|
|
1247
|
+
"REASONING.HALLUCINATION.CITATION",
|
|
1248
|
+
"REASONING.HALLUCINATION.ENTITY",
|
|
1249
|
+
"REASONING.HALLUCINATION.FACTUAL",
|
|
1250
|
+
"REASONING.HALLUCINATION.TEMPORAL",
|
|
1251
|
+
"REASONING.LOGIC.CIRCULAR",
|
|
1252
|
+
"REASONING.LOGIC.CONTRADICTION",
|
|
1253
|
+
"REASONING.LOGIC.INCOMPLETE",
|
|
1254
|
+
"REASONING.LOGIC.INVALID_INFERENCE",
|
|
1255
|
+
"REASONING.LOGIC.MISSING_PREMISE",
|
|
1256
|
+
"REASONING.PLANNING.INCOMPLETE",
|
|
1257
|
+
"REASONING.PLANNING.INFEASIBLE",
|
|
1258
|
+
"REASONING.PLANNING.SCOPE_CREEP",
|
|
1259
|
+
"REASONING.PLANNING.SUBOPTIMAL",
|
|
1260
|
+
"REASONING.PLANNING.UNSAFE",
|
|
1261
|
+
"RESOURCES.ACCESS.DENIED",
|
|
1262
|
+
"RESOURCES.ACCESS.EXPIRED",
|
|
1263
|
+
"RESOURCES.ACCESS.LOCKED",
|
|
1264
|
+
"RESOURCES.ACCESS.NOT_FOUND",
|
|
1265
|
+
"RESOURCES.ACCESS.REVOKED",
|
|
1266
|
+
"RESOURCES.CONTENTION.DEADLOCK",
|
|
1267
|
+
"RESOURCES.CONTENTION.OVERFLOW",
|
|
1268
|
+
"RESOURCES.CONTENTION.PRIORITY_INVERSION",
|
|
1269
|
+
"RESOURCES.CONTENTION.STARVATION",
|
|
1270
|
+
"RESOURCES.CONTENTION.THRASHING",
|
|
1271
|
+
"RESOURCES.QUOTA.ALLOCATION_FAILED",
|
|
1272
|
+
"RESOURCES.QUOTA.EXCEEDED",
|
|
1273
|
+
"RESOURCES.QUOTA.LEAK",
|
|
1274
|
+
"RESOURCES.QUOTA.STALE",
|
|
1275
|
+
"RESOURCES.QUOTA.UNFAIR_DISTRIBUTION",
|
|
1276
|
+
"TOOL.EXECUTION.CRASHED",
|
|
1277
|
+
"TOOL.EXECUTION.DEPENDENCY_FAILED",
|
|
1278
|
+
"TOOL.EXECUTION.RATE_LIMITED",
|
|
1279
|
+
"TOOL.EXECUTION.RESOURCE_EXHAUSTED",
|
|
1280
|
+
"TOOL.EXECUTION.TIMEOUT",
|
|
1281
|
+
"TOOL.INVOCATION.INVALID_ARGS",
|
|
1282
|
+
"TOOL.INVOCATION.MISSING_REQUIRED",
|
|
1283
|
+
"TOOL.INVOCATION.NOT_FOUND",
|
|
1284
|
+
"TOOL.INVOCATION.PERMISSION_DENIED",
|
|
1285
|
+
"TOOL.INVOCATION.TYPE_MISMATCH",
|
|
1286
|
+
"TOOL.RESULT.EMPTY",
|
|
1287
|
+
"TOOL.RESULT.ERROR_IN_RESULT",
|
|
1288
|
+
"TOOL.RESULT.PARTIAL",
|
|
1289
|
+
"TOOL.RESULT.UNEXPECTED_FORMAT",
|
|
1290
|
+
"TOOL.RESULT.UNPARSEABLE"
|
|
1291
|
+
]);
|
|
1292
|
+
var SUPPLEMENTAL_RULES = [
|
|
1293
|
+
{ re: new RegExp("timeout|timedout|aborted", "i"), code: "TOOL.EXECUTION.TIMEOUT" },
|
|
1294
|
+
{ re: new RegExp("rate.?limit|\\b429\\b|too many requests", "i"), code: "TOOL.EXECUTION.RATE_LIMITED" },
|
|
1295
|
+
{ re: new RegExp("connection|econnrefused|econnreset|enotfound|fetch failed|unreachable|broken pipe", "i"), code: "TOOL.EXECUTION.DEPENDENCY_FAILED" },
|
|
1296
|
+
{ re: new RegExp("\\bauth|unauthorized|forbidden|permission|\\b401\\b|\\b403\\b", "i"), code: "TOOL.INVOCATION.PERMISSION_DENIED" },
|
|
1297
|
+
{ re: new RegExp("json|syntaxerror|unexpected token|decodeerror", "i"), code: "PERCEPTION.PARSING.JSON_INVALID" }
|
|
1298
|
+
];
|
|
1299
|
+
var GENERIC_FALLBACK = "TOOL.EXECUTION.CRASHED";
|
|
1300
|
+
|
|
1301
|
+
// src/runtime/interceptors.ts
|
|
1302
|
+
var GuardRejectedError = class extends Error {
|
|
1303
|
+
guardId;
|
|
1304
|
+
reason;
|
|
1305
|
+
phase;
|
|
1306
|
+
constructor(guardId, reason, phase) {
|
|
1307
|
+
super(`Risicare guard rejected operation: ${guardId} (${phase}) \u2014 ${reason}`);
|
|
1308
|
+
this.name = "GuardRejectedError";
|
|
1309
|
+
this.guardId = guardId;
|
|
1310
|
+
this.reason = reason;
|
|
1311
|
+
this.phase = phase;
|
|
1312
|
+
}
|
|
1313
|
+
};
|
|
1314
|
+
function createInterceptContext(operationType, operationName, options) {
|
|
1315
|
+
return {
|
|
1316
|
+
operationType,
|
|
1317
|
+
operationName,
|
|
1318
|
+
sessionId: options?.sessionId,
|
|
1319
|
+
traceId: options?.traceId,
|
|
1320
|
+
errorCode: options?.errorCode,
|
|
1321
|
+
attempt: 1,
|
|
1322
|
+
appliedFixes: []
|
|
1323
|
+
};
|
|
1324
|
+
}
|
|
1325
|
+
var DefaultFixInterceptor = class {
|
|
1326
|
+
_config;
|
|
1327
|
+
_cache;
|
|
1328
|
+
_applier;
|
|
1329
|
+
constructor(config, cache, applier) {
|
|
1330
|
+
this._config = resolveFixRuntimeConfig(config);
|
|
1331
|
+
this._cache = cache;
|
|
1332
|
+
this._applier = applier;
|
|
1333
|
+
}
|
|
1334
|
+
/**
|
|
1335
|
+
* Apply pre-call fixes.
|
|
1336
|
+
*
|
|
1337
|
+
* - If retrying after error: look up fix by error_code, apply
|
|
1338
|
+
* prompt/parameter/fallback fixes
|
|
1339
|
+
* - Runs input guard fixes on all message content
|
|
1340
|
+
*/
|
|
1341
|
+
preCall(ctx, messages, params) {
|
|
1342
|
+
try {
|
|
1343
|
+
if (!this._config.enabled) {
|
|
1344
|
+
return { messages, params };
|
|
1345
|
+
}
|
|
1346
|
+
let modifiedMessages = messages;
|
|
1347
|
+
let modifiedParams = { ...params };
|
|
1348
|
+
if (ctx.errorCode) {
|
|
1349
|
+
const fix = this._applier.getFixForError(ctx.errorCode, ctx.sessionId);
|
|
1350
|
+
if (fix) {
|
|
1351
|
+
debug(`Applying fix ${fix.fixId} for ${ctx.errorCode}`);
|
|
1352
|
+
if (fix.fixType === "prompt" && messages) {
|
|
1353
|
+
const msgRecords = messages;
|
|
1354
|
+
const { messages: newMessages, result } = this._applier.applyPromptFix(fix, msgRecords);
|
|
1355
|
+
modifiedMessages = newMessages;
|
|
1356
|
+
ctx.appliedFixes.push(result);
|
|
1357
|
+
this._applier.logApplication(result);
|
|
1358
|
+
} else if (fix.fixType === "parameter") {
|
|
1359
|
+
const { params: newParams, result } = this._applier.applyParameterFix(fix, modifiedParams);
|
|
1360
|
+
modifiedParams = newParams;
|
|
1361
|
+
ctx.appliedFixes.push(result);
|
|
1362
|
+
this._applier.logApplication(result);
|
|
1363
|
+
} else if (fix.fixType === "fallback") {
|
|
1364
|
+
const { params: newParams, result } = this._applier.applyFallbackFix(fix, modifiedParams);
|
|
1365
|
+
modifiedParams = newParams;
|
|
1366
|
+
ctx.appliedFixes.push(result);
|
|
1367
|
+
this._applier.logApplication(result);
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
if (modifiedMessages && this._config.enabled) {
|
|
1372
|
+
for (const msg of modifiedMessages) {
|
|
1373
|
+
const content = msg.content;
|
|
1374
|
+
if (typeof content === "string") {
|
|
1375
|
+
for (const fix of this._cache.getAll()) {
|
|
1376
|
+
if (fix.fixType === "guard") {
|
|
1377
|
+
const { passed, result } = this._applier.applyGuardFix(
|
|
1378
|
+
fix,
|
|
1379
|
+
content,
|
|
1380
|
+
true
|
|
1381
|
+
);
|
|
1382
|
+
if (result.applied) {
|
|
1383
|
+
ctx.appliedFixes.push(result);
|
|
1384
|
+
this._applier.logApplication(result);
|
|
1385
|
+
}
|
|
1386
|
+
if (!passed) {
|
|
1387
|
+
throw new GuardRejectedError(
|
|
1388
|
+
fix.fixId ?? "unknown",
|
|
1389
|
+
result.reason ?? "guard rejected input",
|
|
1390
|
+
"pre_call"
|
|
1391
|
+
);
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
return { messages: modifiedMessages, params: modifiedParams };
|
|
1399
|
+
} catch (e) {
|
|
1400
|
+
if (e instanceof GuardRejectedError) throw e;
|
|
1401
|
+
debug(`DefaultFixInterceptor.preCall error: ${e}`);
|
|
1402
|
+
return { messages, params };
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
/**
|
|
1406
|
+
* Apply post-call fixes (output validation).
|
|
1407
|
+
*
|
|
1408
|
+
* Runs output guard fixes on response content.
|
|
1409
|
+
*/
|
|
1410
|
+
postCall(ctx, response) {
|
|
1411
|
+
try {
|
|
1412
|
+
if (!this._config.enabled) {
|
|
1413
|
+
return { response, shouldContinue: true };
|
|
1414
|
+
}
|
|
1415
|
+
for (const fix of this._cache.getAll()) {
|
|
1416
|
+
if (fix.fixType !== "guard") continue;
|
|
1417
|
+
const content = this._extractResponseContent(response);
|
|
1418
|
+
if (!content) continue;
|
|
1419
|
+
const { passed, result } = this._applier.applyGuardFix(
|
|
1420
|
+
fix,
|
|
1421
|
+
content,
|
|
1422
|
+
false
|
|
1423
|
+
);
|
|
1424
|
+
if (result.applied) {
|
|
1425
|
+
ctx.appliedFixes.push(result);
|
|
1426
|
+
this._applier.logApplication(result);
|
|
1427
|
+
}
|
|
1428
|
+
if (!passed) {
|
|
1429
|
+
warn(`Output guard failed for fix ${fix.fixId}: ${result.reason ?? "unknown"}`);
|
|
1430
|
+
throw new GuardRejectedError(
|
|
1431
|
+
fix.fixId ?? "unknown",
|
|
1432
|
+
result.reason ?? "guard rejected output",
|
|
1433
|
+
"post_call"
|
|
1434
|
+
);
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
return { response, shouldContinue: true };
|
|
1438
|
+
} catch (e) {
|
|
1439
|
+
if (e instanceof GuardRejectedError) throw e;
|
|
1440
|
+
debug(`DefaultFixInterceptor.postCall error: ${e}`);
|
|
1441
|
+
return { response, shouldContinue: true };
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
/**
|
|
1445
|
+
* Handle errors and decide whether to retry.
|
|
1446
|
+
*
|
|
1447
|
+
* Classifies the error, looks up retry/fallback fixes, and returns
|
|
1448
|
+
* whether the caller should retry.
|
|
1449
|
+
*/
|
|
1450
|
+
onError(ctx, error) {
|
|
1451
|
+
try {
|
|
1452
|
+
if (!this._config.enabled) {
|
|
1453
|
+
return { shouldRetry: false, modifiedParams: null };
|
|
1454
|
+
}
|
|
1455
|
+
const errorCode = classifyError(error);
|
|
1456
|
+
ctx.errorCode = errorCode;
|
|
1457
|
+
ctx.errorMessage = error.message;
|
|
1458
|
+
const fix = this._applier.getFixForError(errorCode, ctx.sessionId);
|
|
1459
|
+
if (!fix) {
|
|
1460
|
+
return { shouldRetry: false, modifiedParams: null };
|
|
1461
|
+
}
|
|
1462
|
+
if (fix.fixType === "retry") {
|
|
1463
|
+
const maxRetries = fix.config.max_retries ?? fix.config.maxRetries ?? 3;
|
|
1464
|
+
if (ctx.attempt <= maxRetries) {
|
|
1465
|
+
debug(
|
|
1466
|
+
`Retry fix ${fix.fixId}: attempt ${ctx.attempt}/${maxRetries}`
|
|
1467
|
+
);
|
|
1468
|
+
const result = {
|
|
1469
|
+
applied: true,
|
|
1470
|
+
fixId: fix.fixId,
|
|
1471
|
+
deploymentId: fix.deploymentId,
|
|
1472
|
+
fixType: "retry",
|
|
1473
|
+
modifications: { attempt: ctx.attempt }
|
|
1474
|
+
};
|
|
1475
|
+
ctx.appliedFixes.push(result);
|
|
1476
|
+
this._applier.logApplication(result);
|
|
1477
|
+
return { shouldRetry: true, modifiedParams: null };
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
if (fix.fixType === "fallback") {
|
|
1481
|
+
const { params: modifiedParams, result } = this._applier.applyFallbackFix(fix, {});
|
|
1482
|
+
if (result.applied) {
|
|
1483
|
+
ctx.appliedFixes.push(result);
|
|
1484
|
+
this._applier.logApplication(result);
|
|
1485
|
+
return { shouldRetry: true, modifiedParams };
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
return { shouldRetry: false, modifiedParams: null };
|
|
1489
|
+
} catch (e) {
|
|
1490
|
+
debug(`DefaultFixInterceptor.onError error: ${e}`);
|
|
1491
|
+
return { shouldRetry: false, modifiedParams: null };
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
// ─── Private ────────────────────────────────────────────────────────────
|
|
1495
|
+
/** Extract text content from a response object. */
|
|
1496
|
+
_extractResponseContent(response) {
|
|
1497
|
+
if (typeof response === "string") return response;
|
|
1498
|
+
if (response && typeof response === "object") {
|
|
1499
|
+
const resp = response;
|
|
1500
|
+
const choices = resp.choices;
|
|
1501
|
+
if (Array.isArray(choices) && choices.length > 0) {
|
|
1502
|
+
const first = choices[0];
|
|
1503
|
+
const message = first?.message;
|
|
1504
|
+
if (typeof message?.content === "string") {
|
|
1505
|
+
return message.content;
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
const content = resp.content;
|
|
1509
|
+
if (typeof content === "string") return content;
|
|
1510
|
+
if (Array.isArray(content) && content.length > 0) {
|
|
1511
|
+
const first = content[0];
|
|
1512
|
+
if (typeof first?.text === "string") return first.text;
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
return null;
|
|
1516
|
+
}
|
|
1517
|
+
};
|
|
1518
|
+
function classifyError(error) {
|
|
1519
|
+
const haystack = `${error?.constructor?.name ?? "Error"} ${error?.message ?? ""}`;
|
|
1520
|
+
for (const rule of SUPPLEMENTAL_RULES) {
|
|
1521
|
+
if (rule.re.test(haystack)) {
|
|
1522
|
+
return CANONICAL_ERROR_CODES.has(rule.code) ? rule.code : GENERIC_FALLBACK;
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
return CANONICAL_ERROR_CODES.has(GENERIC_FALLBACK) ? GENERIC_FALLBACK : "";
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1011
1528
|
// src/context/storage.ts
|
|
1012
1529
|
function storage() {
|
|
1013
1530
|
return getContextStorage();
|
|
@@ -1069,16 +1586,30 @@ function getCurrentContext() {
|
|
|
1069
1586
|
}
|
|
1070
1587
|
|
|
1071
1588
|
// src/tracer.ts
|
|
1589
|
+
function attachErrorCode(span, error) {
|
|
1590
|
+
try {
|
|
1591
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1592
|
+
const code = classifyError(err);
|
|
1593
|
+
if (code) {
|
|
1594
|
+
span.setAttribute("error.code", code);
|
|
1595
|
+
}
|
|
1596
|
+
} catch {
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1072
1599
|
var Tracer = class {
|
|
1073
1600
|
_onSpanEnd;
|
|
1074
1601
|
_sampleRate;
|
|
1075
1602
|
_enabled;
|
|
1076
1603
|
_traceContent;
|
|
1604
|
+
_serviceName;
|
|
1605
|
+
_serviceVersion;
|
|
1077
1606
|
constructor(config) {
|
|
1078
1607
|
this._onSpanEnd = config.onSpanEnd;
|
|
1079
1608
|
this._sampleRate = config.sampleRate ?? 1;
|
|
1080
1609
|
this._enabled = config.enabled ?? true;
|
|
1081
|
-
this._traceContent = config.traceContent ??
|
|
1610
|
+
this._traceContent = config.traceContent ?? false;
|
|
1611
|
+
this._serviceName = config.serviceName || void 0;
|
|
1612
|
+
this._serviceVersion = config.serviceVersion || void 0;
|
|
1082
1613
|
}
|
|
1083
1614
|
get enabled() {
|
|
1084
1615
|
return this._enabled;
|
|
@@ -1112,10 +1643,16 @@ var Tracer = class {
|
|
|
1112
1643
|
const phase = getCurrentPhase();
|
|
1113
1644
|
const ctx = getContext();
|
|
1114
1645
|
const traceId = opts.traceId ?? parentSpan?.traceId ?? ctx._rootTraceId ?? generateTraceId();
|
|
1115
|
-
if (!parentSpan
|
|
1116
|
-
if (
|
|
1646
|
+
if (!parentSpan) {
|
|
1647
|
+
if (ctx._traceSampled === false) {
|
|
1117
1648
|
return fn(NOOP_SPAN);
|
|
1118
1649
|
}
|
|
1650
|
+
if (this._sampleRate < 1 && !shouldSample(traceId, this._sampleRate)) {
|
|
1651
|
+
return runWithContext(
|
|
1652
|
+
{ _traceSampled: false },
|
|
1653
|
+
() => fn(NOOP_SPAN)
|
|
1654
|
+
);
|
|
1655
|
+
}
|
|
1119
1656
|
}
|
|
1120
1657
|
const parentSpanId = opts.parentSpanId ?? parentSpan?.spanId;
|
|
1121
1658
|
const spanOptions = {
|
|
@@ -1128,7 +1665,12 @@ var Tracer = class {
|
|
|
1128
1665
|
// Propagate context fields as attributes (matching Python SDK tracer.py:497-511)
|
|
1129
1666
|
...agent2?.agentRole ? { "agent.role": agent2.agentRole } : {},
|
|
1130
1667
|
...agent2?.parentAgentId ? { "parent_agent_id": agent2.parentAgentId } : {},
|
|
1131
|
-
...session2?.userId ? { "session.user_id": session2.userId } : {}
|
|
1668
|
+
...session2?.userId ? { "session.user_id": session2.userId } : {},
|
|
1669
|
+
// F-SDKJSSVCNAME-001 — `service.name` is suppressed when an agent
|
|
1670
|
+
// identity is present (the agent takes priority), matching Python;
|
|
1671
|
+
// `service.version` never is.
|
|
1672
|
+
...this._serviceName && !agent2 ? { "service.name": this._serviceName } : {},
|
|
1673
|
+
...this._serviceVersion ? { "service.version": this._serviceVersion } : {}
|
|
1132
1674
|
},
|
|
1133
1675
|
sessionId: session2?.sessionId,
|
|
1134
1676
|
agentId: agent2?.agentId,
|
|
@@ -1147,6 +1689,7 @@ var Tracer = class {
|
|
|
1147
1689
|
},
|
|
1148
1690
|
(error) => {
|
|
1149
1691
|
span.recordException(error instanceof Error ? error : String(error));
|
|
1692
|
+
attachErrorCode(span, error);
|
|
1150
1693
|
span.end();
|
|
1151
1694
|
throw error;
|
|
1152
1695
|
}
|
|
@@ -1156,6 +1699,7 @@ var Tracer = class {
|
|
|
1156
1699
|
return result;
|
|
1157
1700
|
} catch (error) {
|
|
1158
1701
|
span.recordException(error instanceof Error ? error : String(error));
|
|
1702
|
+
attachErrorCode(span, error);
|
|
1159
1703
|
span.end();
|
|
1160
1704
|
throw error;
|
|
1161
1705
|
}
|
|
@@ -1176,8 +1720,11 @@ var Tracer = class {
|
|
|
1176
1720
|
const agent2 = getCurrentAgent();
|
|
1177
1721
|
const phase = getCurrentPhase();
|
|
1178
1722
|
const traceId = opts.traceId ?? parentSpan?.traceId ?? generateTraceId();
|
|
1179
|
-
if (!parentSpan
|
|
1180
|
-
if (
|
|
1723
|
+
if (!parentSpan) {
|
|
1724
|
+
if (getContext()._traceSampled === false) {
|
|
1725
|
+
return NOOP_SPAN;
|
|
1726
|
+
}
|
|
1727
|
+
if (this._sampleRate < 1 && !shouldSample(traceId, this._sampleRate)) {
|
|
1181
1728
|
return NOOP_SPAN;
|
|
1182
1729
|
}
|
|
1183
1730
|
}
|
|
@@ -1193,7 +1740,10 @@ var Tracer = class {
|
|
|
1193
1740
|
// Propagate context fields as attributes (matching Python SDK tracer.py:497-511)
|
|
1194
1741
|
...agent2?.agentRole ? { "agent.role": agent2.agentRole } : {},
|
|
1195
1742
|
...agent2?.parentAgentId ? { "parent_agent_id": agent2.parentAgentId } : {},
|
|
1196
|
-
...session2?.userId ? { "session.user_id": session2.userId } : {}
|
|
1743
|
+
...session2?.userId ? { "session.user_id": session2.userId } : {},
|
|
1744
|
+
// F-SDKJSSVCNAME-001 — see the sibling site above.
|
|
1745
|
+
...this._serviceName && !agent2 ? { "service.name": this._serviceName } : {},
|
|
1746
|
+
...this._serviceVersion ? { "service.version": this._serviceVersion } : {}
|
|
1197
1747
|
},
|
|
1198
1748
|
sessionId: session2?.sessionId,
|
|
1199
1749
|
agentId: agent2?.agentId,
|
|
@@ -1207,9 +1757,13 @@ var Tracer = class {
|
|
|
1207
1757
|
};
|
|
1208
1758
|
|
|
1209
1759
|
// src/version.ts
|
|
1210
|
-
var SDK_VERSION = "0.
|
|
1760
|
+
var SDK_VERSION = "0.6.0";
|
|
1211
1761
|
|
|
1212
1762
|
// src/exporters/http.ts
|
|
1763
|
+
var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
|
|
1764
|
+
var RETRY_AFTER_CEILING_MS = 1e4;
|
|
1765
|
+
var REFUSAL_BACKOFF_BASE_MS = 1e3;
|
|
1766
|
+
var REFUSAL_NO_HINT = -1;
|
|
1213
1767
|
var HttpExporter = class {
|
|
1214
1768
|
name = "http";
|
|
1215
1769
|
_endpoint;
|
|
@@ -1225,6 +1779,18 @@ var HttpExporter = class {
|
|
|
1225
1779
|
// cooldown gives the gateway time to come back before the half-open
|
|
1226
1780
|
// probe fires. Lower numbers (was 3@30s) tripped on transient blips.
|
|
1227
1781
|
_consecutiveFailures = 0;
|
|
1782
|
+
/**
|
|
1783
|
+
* F-SDK503-001. Set by `_sendRequest` when a response is a CAPACITY REFUSAL, read by the
|
|
1784
|
+
* retry loop and the breaker. `null` = not a refusal; `REFUSAL_NO_HINT` = refused with no
|
|
1785
|
+
* `Retry-After`; otherwise the honoured delay in ms.
|
|
1786
|
+
*
|
|
1787
|
+
* ⚠ Node has ONE thread and `export()` is `async`, so two concurrent exports interleave on
|
|
1788
|
+
* this field at every `await`. It is written immediately after the awaited `fetch` resolves
|
|
1789
|
+
* and read on the very next statement, with no `await` between — so the value cannot be
|
|
1790
|
+
* clobbered mid-decision. The Python twin carries the same per-call state on `self` for the
|
|
1791
|
+
* same reason (its `_send_request` signature is pin-locked).
|
|
1792
|
+
*/
|
|
1793
|
+
_lastRefusalAfterMs = null;
|
|
1228
1794
|
_circuitOpenUntil = 0;
|
|
1229
1795
|
_circuitBreakerThreshold = 5;
|
|
1230
1796
|
_circuitBreakerCooldownMs = 6e4;
|
|
@@ -1254,15 +1820,26 @@ var HttpExporter = class {
|
|
|
1254
1820
|
if (this._environment) body.environment = this._environment;
|
|
1255
1821
|
const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
|
|
1256
1822
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1823
|
+
this._lastRefusalAfterMs = null;
|
|
1257
1824
|
const result = await this._sendRequest(body);
|
|
1258
1825
|
if (result === "success" /* SUCCESS */) {
|
|
1259
1826
|
this._consecutiveFailures = 0;
|
|
1260
1827
|
return result;
|
|
1261
1828
|
}
|
|
1262
1829
|
if (attempt < maxAttempts - 1) {
|
|
1263
|
-
|
|
1830
|
+
const refusal = this._lastRefusalAfterMs;
|
|
1831
|
+
const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
|
|
1832
|
+
await sleep(delay);
|
|
1264
1833
|
}
|
|
1265
1834
|
}
|
|
1835
|
+
const refusedForCapacity = this._lastRefusalAfterMs !== null;
|
|
1836
|
+
this._lastRefusalAfterMs = null;
|
|
1837
|
+
if (refusedForCapacity) {
|
|
1838
|
+
warn(
|
|
1839
|
+
`Risicare: the ingest endpoint refused this batch for capacity (HTTP 429/503) after ${maxAttempts} attempt(s). This is a healthy server shedding load, not an outage \u2014 the batch is dropped but the exporter keeps sending. Reduce batch size or export rate if it persists.`
|
|
1840
|
+
);
|
|
1841
|
+
return "failure" /* FAILURE */;
|
|
1842
|
+
}
|
|
1266
1843
|
this._consecutiveFailures++;
|
|
1267
1844
|
if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
|
|
1268
1845
|
this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
|
|
@@ -1272,11 +1849,37 @@ var HttpExporter = class {
|
|
|
1272
1849
|
}
|
|
1273
1850
|
return "failure" /* FAILURE */;
|
|
1274
1851
|
}
|
|
1852
|
+
/**
|
|
1853
|
+
* Record a CAPACITY REFUSAL for the retry loop. Returns true if it was one.
|
|
1854
|
+
*
|
|
1855
|
+
* `Retry-After` is honoured only in its delta-seconds form (RFC 9110 §10.2.3 also permits an
|
|
1856
|
+
* HTTP-date); anything else falls back to our own backoff rather than guessing at a date
|
|
1857
|
+
* parse.
|
|
1858
|
+
*/
|
|
1859
|
+
_noteRefusal(status, retryAfterRaw) {
|
|
1860
|
+
if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
|
|
1861
|
+
let delay = REFUSAL_NO_HINT;
|
|
1862
|
+
if (retryAfterRaw) {
|
|
1863
|
+
const secs = Number(retryAfterRaw);
|
|
1864
|
+
if (Number.isFinite(secs) && secs >= 0) {
|
|
1865
|
+
delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
this._lastRefusalAfterMs = delay;
|
|
1869
|
+
debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${retryAfterRaw})`);
|
|
1870
|
+
return true;
|
|
1871
|
+
}
|
|
1275
1872
|
async _sendRequest(body) {
|
|
1276
1873
|
const url = `${this._endpoint}/v1/spans`;
|
|
1277
1874
|
const headers = {
|
|
1278
1875
|
"Content-Type": "application/json",
|
|
1279
|
-
"User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}
|
|
1876
|
+
"User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`,
|
|
1877
|
+
// F-SDKVER-001 parity. Python's ingest exporter has always sent
|
|
1878
|
+
// `X-Risicare-SDK-Version`; JS sent only a User-Agent, so the two SDKs
|
|
1879
|
+
// disagreed about how a client identifies itself. A parser-free header is
|
|
1880
|
+
// strictly easier for the gateway to consume than picking a version out of
|
|
1881
|
+
// a UA string.
|
|
1882
|
+
"X-Risicare-SDK-Version": SDK_VERSION
|
|
1280
1883
|
};
|
|
1281
1884
|
if (this._apiKey) {
|
|
1282
1885
|
headers["Authorization"] = `Bearer ${this._apiKey}`;
|
|
@@ -1302,11 +1905,12 @@ var HttpExporter = class {
|
|
|
1302
1905
|
});
|
|
1303
1906
|
clearTimeout(timeoutId);
|
|
1304
1907
|
if (response.status < 300) {
|
|
1305
|
-
return
|
|
1908
|
+
return await checkAck(response);
|
|
1306
1909
|
} else if (response.status === 408 || response.status === 504) {
|
|
1307
1910
|
debug(`HTTP export timeout: ${response.status}`);
|
|
1308
1911
|
return "timeout" /* TIMEOUT */;
|
|
1309
1912
|
}
|
|
1913
|
+
this._noteRefusal(response.status, response.headers.get("Retry-After"));
|
|
1310
1914
|
debug(`HTTP export failed: ${response.status}`);
|
|
1311
1915
|
return "failure" /* FAILURE */;
|
|
1312
1916
|
} catch (e) {
|
|
@@ -1320,6 +1924,39 @@ var HttpExporter = class {
|
|
|
1320
1924
|
function sleep(ms) {
|
|
1321
1925
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1322
1926
|
}
|
|
1927
|
+
function asCount(v) {
|
|
1928
|
+
return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
|
|
1929
|
+
}
|
|
1930
|
+
async function checkAck(response) {
|
|
1931
|
+
let payload;
|
|
1932
|
+
try {
|
|
1933
|
+
payload = await response.json();
|
|
1934
|
+
} catch {
|
|
1935
|
+
return "success" /* SUCCESS */;
|
|
1936
|
+
}
|
|
1937
|
+
if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
|
|
1938
|
+
return "success" /* SUCCESS */;
|
|
1939
|
+
}
|
|
1940
|
+
const body = payload;
|
|
1941
|
+
const accepted = asCount(body.accepted);
|
|
1942
|
+
const rejected = asCount(body.rejected);
|
|
1943
|
+
if (accepted === void 0 || rejected === void 0 || rejected <= 0) {
|
|
1944
|
+
return "success" /* SUCCESS */;
|
|
1945
|
+
}
|
|
1946
|
+
const errors = body.errors;
|
|
1947
|
+
const detail = typeof body.errorMessage === "string" && body.errorMessage || typeof body.error_message === "string" && body.error_message || (Array.isArray(errors) && errors.length > 0 ? JSON.stringify(errors[0]) : "") || "No reason was returned.";
|
|
1948
|
+
const total = accepted + rejected;
|
|
1949
|
+
if (accepted === 0) {
|
|
1950
|
+
warn(
|
|
1951
|
+
`Risicare: the backend accepted 0 of ${total} span(s) and rejected ${rejected} \u2014 this batch was NOT stored. ${detail}`
|
|
1952
|
+
);
|
|
1953
|
+
return "failure" /* FAILURE */;
|
|
1954
|
+
}
|
|
1955
|
+
warn(
|
|
1956
|
+
`Risicare: the backend rejected ${rejected} of ${total} span(s); the remaining ${accepted} were stored. Those ${rejected} are permanently lost and are NOT retried. ${detail}`
|
|
1957
|
+
);
|
|
1958
|
+
return "success" /* SUCCESS */;
|
|
1959
|
+
}
|
|
1323
1960
|
|
|
1324
1961
|
// src/exporters/console.ts
|
|
1325
1962
|
var ConsoleExporter = class {
|
|
@@ -1328,59 +1965,14 @@ var ConsoleExporter = class {
|
|
|
1328
1965
|
for (const span of spans) {
|
|
1329
1966
|
const payload = span.toPayload();
|
|
1330
1967
|
const line = JSON.stringify(payload);
|
|
1331
|
-
process.stderr.write(`[risicare] ${line}
|
|
1332
|
-
`);
|
|
1333
|
-
}
|
|
1334
|
-
return "success" /* SUCCESS */;
|
|
1335
|
-
}
|
|
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;
|
|
1968
|
+
process.stderr.write(`[risicare] ${line}
|
|
1969
|
+
`);
|
|
1970
|
+
}
|
|
1971
|
+
return "success" /* SUCCESS */;
|
|
1360
1972
|
}
|
|
1361
|
-
|
|
1362
|
-
const prefix = fix.errorCode.slice(0, -1);
|
|
1363
|
-
return errorCode.startsWith(prefix);
|
|
1973
|
+
shutdown() {
|
|
1364
1974
|
}
|
|
1365
|
-
|
|
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
|
-
}
|
|
1975
|
+
};
|
|
1384
1976
|
|
|
1385
1977
|
// src/runtime/cache.ts
|
|
1386
1978
|
var FixCache = class {
|
|
@@ -2145,247 +2737,6 @@ var FixLoader = class _FixLoader {
|
|
|
2145
2737
|
}
|
|
2146
2738
|
};
|
|
2147
2739
|
|
|
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
2740
|
// src/runtime/runtime.ts
|
|
2390
2741
|
var G2 = globalThis;
|
|
2391
2742
|
var RUNTIME_KEY = "__risicare_fix_runtime";
|
|
@@ -2684,13 +3035,24 @@ var RisicareClient = class {
|
|
|
2684
3035
|
// anywhere downstream (in the HTTP exporter, say) would leave a hole for
|
|
2685
3036
|
// any other exporter; masking upstream would put customer code on the
|
|
2686
3037
|
// span-end call path.
|
|
2687
|
-
mask: this.config.mask
|
|
3038
|
+
mask: this.config.mask,
|
|
3039
|
+
// Same argument as `mask`: the processor is the ONE choke point every
|
|
3040
|
+
// exporter is behind, and the only place BOTH content paths — provider
|
|
3041
|
+
// capture and hand-set attributes — can be gated together. The Tracer
|
|
3042
|
+
// still carries `traceContent` for the provider patches to read; that is
|
|
3043
|
+
// now a convenience, not the enforcement point.
|
|
3044
|
+
traceContent: this.config.traceContent
|
|
2688
3045
|
});
|
|
2689
3046
|
this.tracer = new Tracer({
|
|
2690
3047
|
onSpanEnd: (span) => this.processor.onSpanEnd(span),
|
|
2691
3048
|
sampleRate: this.config.sampleRate,
|
|
2692
3049
|
enabled: this.config.enabled,
|
|
2693
|
-
traceContent: this.config.traceContent
|
|
3050
|
+
traceContent: this.config.traceContent,
|
|
3051
|
+
// F-SDKJSSVCNAME-001 — these were resolved into `config` and then read by
|
|
3052
|
+
// nothing. The Tracer is where Python emits them, so JS emits them there
|
|
3053
|
+
// too rather than inventing a second site.
|
|
3054
|
+
serviceName: this.config.serviceName,
|
|
3055
|
+
serviceVersion: this.config.serviceVersion
|
|
2694
3056
|
});
|
|
2695
3057
|
this.processor.start();
|
|
2696
3058
|
if (this.config.apiKey && this.config.enabled) {
|
|
@@ -2888,7 +3250,7 @@ function getTracer2() {
|
|
|
2888
3250
|
}
|
|
2889
3251
|
function getTraceContent() {
|
|
2890
3252
|
const tracer = getTracer();
|
|
2891
|
-
return tracer?.traceContent ??
|
|
3253
|
+
return tracer?.traceContent ?? false;
|
|
2892
3254
|
}
|
|
2893
3255
|
function getMetrics() {
|
|
2894
3256
|
const client = getClient();
|
|
@@ -2956,6 +3318,7 @@ function reportError(error, options) {
|
|
|
2956
3318
|
span.setAttribute("error.message", err.message.slice(0, 2e3));
|
|
2957
3319
|
if (err.stack) span.setAttribute("error.stack", err.stack.slice(0, 4e3));
|
|
2958
3320
|
span.setAttribute("risicare.reported_error", true);
|
|
3321
|
+
attachErrorCode(span, err);
|
|
2959
3322
|
if (options?.attributes) {
|
|
2960
3323
|
for (const [k, v] of Object.entries(options.attributes)) {
|
|
2961
3324
|
span.setAttribute(k, v);
|
|
@@ -2996,7 +3359,14 @@ function score(traceId, name, value, options) {
|
|
|
2996
3359
|
method: "POST",
|
|
2997
3360
|
headers: {
|
|
2998
3361
|
"Content-Type": "application/json",
|
|
2999
|
-
"Authorization": `Bearer ${client.config.apiKey}
|
|
3362
|
+
"Authorization": `Bearer ${client.config.apiKey}`,
|
|
3363
|
+
// F-SDKVER-001 — see the Python twin. `score()` reaches the FastAPI
|
|
3364
|
+
// server under /v1/, which `main.py::audit_logging_middleware` audits
|
|
3365
|
+
// into `audit_logs.user_agent`; ingest reaches the Rust gateway, which
|
|
3366
|
+
// discards it. This is the one client-identity visible with no gateway
|
|
3367
|
+
// change.
|
|
3368
|
+
"User-Agent": `risicare-js/${SDK_VERSION} node/${process.version}`,
|
|
3369
|
+
"X-Risicare-SDK-Version": SDK_VERSION
|
|
3000
3370
|
},
|
|
3001
3371
|
body
|
|
3002
3372
|
}).catch((err) => debug(`score: send failed: ${err}`));
|
|
@@ -3118,12 +3488,14 @@ function withSessionEndMarker(body) {
|
|
|
3118
3488
|
// src/decorators/agent.ts
|
|
3119
3489
|
function _wrapAgent(options, fn) {
|
|
3120
3490
|
const spanName = `agent:${options.name ?? "agent"}`;
|
|
3491
|
+
const agentId = options.agentId ?? generateAgentId(options.name ?? "agent");
|
|
3492
|
+
const boundOptions = { ...options, agentId };
|
|
3121
3493
|
return (...args) => {
|
|
3122
3494
|
const tracer = getTracer2();
|
|
3123
3495
|
if (!tracer) {
|
|
3124
3496
|
return fn(...args);
|
|
3125
3497
|
}
|
|
3126
|
-
return withAgent(
|
|
3498
|
+
return withAgent(boundOptions, () => {
|
|
3127
3499
|
return tracer.startSpan(
|
|
3128
3500
|
{ name: spanName, kind: "agent" /* AGENT */ },
|
|
3129
3501
|
(span) => withEndMarker(span, "agent", () => fn(...args))
|
|
@@ -3147,14 +3519,14 @@ function withSession(options, fn) {
|
|
|
3147
3519
|
parentSessionId: options.parentSessionId,
|
|
3148
3520
|
turnNumber: options.turnNumber ?? 1
|
|
3149
3521
|
};
|
|
3150
|
-
return runWithContext({ session: session2 }, fn);
|
|
3522
|
+
return runWithContext({ session: session2 }, () => withSessionEndMarker(fn));
|
|
3151
3523
|
}
|
|
3152
3524
|
|
|
3153
3525
|
// src/decorators/session.ts
|
|
3154
3526
|
function _wrapSession(optionsOrResolver, fn) {
|
|
3155
3527
|
return (...args) => {
|
|
3156
3528
|
const options = typeof optionsOrResolver === "function" ? optionsOrResolver(...args) : optionsOrResolver;
|
|
3157
|
-
return withSession(options, () =>
|
|
3529
|
+
return withSession(options, () => fn(...args));
|
|
3158
3530
|
};
|
|
3159
3531
|
}
|
|
3160
3532
|
function session(optionsOrResolver, fn) {
|