agentid-sdk 0.1.37 → 0.1.40

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/dist/langchain.js CHANGED
@@ -27,7 +27,7 @@ var import_base = require("@langchain/core/callbacks/base");
27
27
 
28
28
  // src/sdk-version.ts
29
29
  var FALLBACK_SDK_VERSION = "js-0.0.0-dev";
30
- var AGENTID_SDK_VERSION_HEADER = "js-0.1.37".trim().length > 0 ? "js-0.1.37" : FALLBACK_SDK_VERSION;
30
+ var AGENTID_SDK_VERSION_HEADER = "js-0.1.40".trim().length > 0 ? "js-0.1.40" : FALLBACK_SDK_VERSION;
31
31
 
32
32
  // src/pii-national-identifiers.ts
33
33
  var MAX_CANDIDATES_PER_RULE = 256;
@@ -891,8 +891,173 @@ function detectNationalIdentifiers(text, options = {}) {
891
891
  return results;
892
892
  }
893
893
 
894
+ // src/secret-patterns.ts
895
+ var SDK_SECRET_PATTERN_DEFINITIONS = [
896
+ {
897
+ id: "openai_api_key",
898
+ placeholderType: "OPENAI_API_KEY",
899
+ patternSource: "\\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}\\b",
900
+ flags: "iu",
901
+ prefilterTerms: ["sk-", "proj-", "openai"]
902
+ },
903
+ {
904
+ id: "aws_access_key",
905
+ placeholderType: "AWS_ACCESS_KEY",
906
+ patternSource: "\\b(?:AKIA|ASIA)[A-Z0-9]{16}\\b",
907
+ flags: "iu",
908
+ prefilterTerms: ["akia", "asia", "aws"]
909
+ },
910
+ {
911
+ id: "github_token",
912
+ placeholderType: "GITHUB_TOKEN",
913
+ patternSource: "\\b(?:gh[pousr]_[A-Za-z0-9]{24,255}|github_pat_[A-Za-z0-9_]{20,255})\\b",
914
+ flags: "iu",
915
+ prefilterTerms: ["ghp_", "gho_", "ghu_", "ghs_", "ghr_", "github_pat_"]
916
+ },
917
+ {
918
+ id: "slack_token",
919
+ placeholderType: "SLACK_TOKEN",
920
+ patternSource: "\\bxox(?:a|b|p|r|s)-[A-Za-z0-9-]{10,200}\\b",
921
+ flags: "iu",
922
+ prefilterTerms: ["xoxa-", "xoxb-", "xoxp-", "xoxr-", "xoxs-", "slack"]
923
+ },
924
+ {
925
+ id: "slack_webhook_url",
926
+ placeholderType: "SLACK_WEBHOOK_URL",
927
+ patternSource: "https:\\/\\/hooks\\.slack\\.com\\/services\\/[A-Za-z0-9/_-]{20,}",
928
+ flags: "iu",
929
+ prefilterTerms: ["hooks.slack.com/services", "slack"]
930
+ },
931
+ {
932
+ id: "discord_webhook_url",
933
+ placeholderType: "DISCORD_WEBHOOK_URL",
934
+ patternSource: "https:\\/\\/discord(?:app)?\\.com\\/api\\/webhooks\\/\\d+\\/[A-Za-z0-9_-]{16,}",
935
+ flags: "iu",
936
+ prefilterTerms: ["discord.com/api/webhooks", "discordapp.com/api/webhooks", "discord"]
937
+ },
938
+ {
939
+ id: "stripe_secret_key",
940
+ placeholderType: "STRIPE_SECRET_KEY",
941
+ patternSource: "\\b(?:sk|pk|ak|rk)_(?:live|test)_[A-Za-z0-9]+\\b",
942
+ flags: "iu",
943
+ prefilterTerms: [
944
+ "sk_live_",
945
+ "pk_live_",
946
+ "sk_test_",
947
+ "pk_test_",
948
+ "ak_live_",
949
+ "ak_test_",
950
+ "rk_live_",
951
+ "rk_test_",
952
+ "stripe"
953
+ ]
954
+ },
955
+ {
956
+ id: "google_api_key",
957
+ placeholderType: "GOOGLE_API_KEY",
958
+ patternSource: "\\bAIza[0-9A-Za-z_-]{35}\\b",
959
+ flags: "iu",
960
+ prefilterTerms: ["aiza", "google"]
961
+ },
962
+ {
963
+ id: "anthropic_api_key",
964
+ placeholderType: "ANTHROPIC_API_KEY",
965
+ patternSource: "\\bsk-ant-(?:api\\d{2}-)?[A-Za-z0-9_-]{20,}\\b",
966
+ flags: "iu",
967
+ prefilterTerms: ["sk-ant-", "anthropic"]
968
+ },
969
+ {
970
+ id: "evm_private_key",
971
+ placeholderType: "EVM_PRIVATE_KEY",
972
+ patternSource: "\\b0x[a-fA-F0-9]{64}\\b",
973
+ flags: "iu",
974
+ prefilterTerms: ["0x", "ethereum", "evm", "private key"]
975
+ },
976
+ {
977
+ id: "jwt_token",
978
+ placeholderType: "JWT_TOKEN",
979
+ patternSource: "\\beyJ[A-Za-z0-9_-]{6,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\b",
980
+ flags: "iu",
981
+ prefilterTerms: ["eyj", "jwt", "bearer"]
982
+ },
983
+ {
984
+ id: "bearer_token",
985
+ placeholderType: "BEARER_TOKEN",
986
+ patternSource: "\\bauthorization\\b\\s*[:=]\\s*bearer\\s+[A-Za-z0-9._~+\\/-]{16,}|\\bbearer\\s+[A-Za-z0-9._~+\\/-]{24,}",
987
+ flags: "iu",
988
+ prefilterTerms: ["authorization", "bearer"]
989
+ },
990
+ {
991
+ id: "api_key_header",
992
+ placeholderType: "API_KEY_HEADER",
993
+ patternSource: "\\bx[-_]?api[-_]?key\\b\\s*[:=]\\s*[A-Za-z0-9._~+\\/-]{16,}",
994
+ flags: "iu",
995
+ prefilterTerms: ["x-api-key", "api-key", "x_api_key", "api_key"]
996
+ },
997
+ {
998
+ id: "credential_assignment",
999
+ placeholderType: "CREDENTIAL_ASSIGNMENT",
1000
+ patternSource: `(?:\\b|["'])(?:api(?:[_-]?|\\s+)key|access(?:[_-]?|\\s+)token|auth(?:[_-]?|\\s+)token|client(?:[_-]?|\\s+)secret|private(?:[_-]?|\\s+)key)(?:\\b|["'])\\s*(?::|=|=>)\\s*(?:"[A-Za-z0-9._~+\\/=:-]{16,}"|'[A-Za-z0-9._~+\\/=:-]{16,}'|[A-Za-z0-9._~+\\/=:-]{16,})`,
1001
+ flags: "iu",
1002
+ prefilterTerms: [
1003
+ "api key",
1004
+ "apikey",
1005
+ "api_key",
1006
+ "access token",
1007
+ "access_token",
1008
+ "auth token",
1009
+ "client secret",
1010
+ "private key"
1011
+ ]
1012
+ },
1013
+ {
1014
+ id: "password_assignment",
1015
+ placeholderType: "PASSWORD_ASSIGNMENT",
1016
+ patternSource: `(?:\\b|["'])(?:password|passwd|pwd|heslo)(?:\\b|["'])\\s*(?:(?::|=|=>)|(?:is|are|was|were|je)\\b)?\\s*(?:"[A-Za-z0-9._~!@#$%^&*+=\\/-]{8,}"|'[A-Za-z0-9._~!@#$%^&*+=\\/-]{8,}'|[A-Za-z0-9._~!@#$%^&*+=\\/-]{8,})`,
1017
+ flags: "iu",
1018
+ prefilterTerms: ["password", "passwd", "pwd", "heslo"]
1019
+ },
1020
+ {
1021
+ id: "private_key_material",
1022
+ placeholderType: "PRIVATE_KEY_MATERIAL",
1023
+ patternSource: "-----BEGIN (?:(?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY|PGP PRIVATE KEY BLOCK|CERTIFICATE)-----[\\s\\S]{20,12000}(?:-----END (?:(?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY|PGP PRIVATE KEY BLOCK|CERTIFICATE)-----|$)",
1024
+ flags: "iu",
1025
+ prefilterTerms: ["begin private key", "begin pgp private key block", "private key"]
1026
+ },
1027
+ {
1028
+ id: "azure_connection_string",
1029
+ placeholderType: "AZURE_CONNECTION_STRING",
1030
+ patternSource: "\\bDefaultEndpointsProtocol=https;AccountName=[A-Za-z0-9.-]{3,};AccountKey=[A-Za-z0-9+/=]{20,}(?:;EndpointSuffix=[A-Za-z0-9.-]+)?\\b",
1031
+ flags: "iu",
1032
+ prefilterTerms: ["defaultendpointsprotocol", "accountname", "accountkey", "azure"]
1033
+ },
1034
+ {
1035
+ id: "azure_sas_token",
1036
+ placeholderType: "AZURE_SAS_TOKEN",
1037
+ patternSource: "\\bsv=[^\\s&]{2,}&[^\\s]{0,200}\\bsig=[A-Za-z0-9%/+_-]{16,}",
1038
+ flags: "iu",
1039
+ prefilterTerms: ["sv=", "sig=", "accountkey", "azure"]
1040
+ }
1041
+ ];
1042
+ function ensureGlobalFlag(flags) {
1043
+ const normalized = new Set(flags.split(""));
1044
+ normalized.add("g");
1045
+ return [...normalized].join("");
1046
+ }
1047
+ var COMPILED_SDK_SECRET_PATTERNS = SDK_SECRET_PATTERN_DEFINITIONS.map((definition) => ({
1048
+ ...definition,
1049
+ scanRegex: new RegExp(definition.patternSource, ensureGlobalFlag(definition.flags)),
1050
+ prefilterTermsLower: definition.prefilterTerms.map((term) => term.toLowerCase())
1051
+ }));
1052
+ function getSdkSecretDetectionMatchers() {
1053
+ return COMPILED_SDK_SECRET_PATTERNS;
1054
+ }
1055
+
894
1056
  // src/pii.ts
895
1057
  var defaultScanDeadlineMs = 100;
1058
+ var sdkSecretMatchers = getSdkSecretDetectionMatchers();
1059
+ var DISCORD_WEBHOOK_TOKEN_RE = /https:\/\/discord(?:app)?\.com\/api\/webhooks\/\d+\/([A-Za-z0-9_-]{16,})/giu;
1060
+ var BASIC_AUTH_PASSWORD_RE = /\/\/[^:\s/?#@]+:([^@\s/?#]+)@/giu;
896
1061
  function countDigits2(value) {
897
1062
  let count = 0;
898
1063
  for (const ch of value) {
@@ -917,15 +1082,32 @@ function luhnCheck(value) {
917
1082
  return sum % 10 === 0;
918
1083
  }
919
1084
  function normalizeDetections(text, detections) {
920
- const sorted = detections.filter((d) => d.start >= 0 && d.end > d.start && d.end <= text.length).sort((a, b) => a.start - b.start || b.end - b.start - (a.end - a.start));
1085
+ const sorted = detections.filter((d) => d.start >= 0 && d.end > d.start && d.end <= text.length).sort(
1086
+ (a, b) => detectionPriority(b.type) - detectionPriority(a.type) || a.start - b.start || b.end - b.start - (a.end - a.start)
1087
+ );
921
1088
  const kept = [];
922
- let cursor = 0;
923
1089
  for (const d of sorted) {
924
- if (d.start < cursor) continue;
1090
+ if (kept.some((candidate) => rangesOverlap(candidate, d))) continue;
925
1091
  kept.push(d);
926
- cursor = d.end;
927
1092
  }
928
- return kept;
1093
+ return kept.sort((a, b) => a.start - b.start || a.end - b.end);
1094
+ }
1095
+ function rangesOverlap(left, right) {
1096
+ return left.start < right.end && right.start < left.end;
1097
+ }
1098
+ function detectionPriority(type) {
1099
+ if (/^(?:OPENAI_API_KEY|AWS_ACCESS_KEY|GITHUB_TOKEN|SLACK_TOKEN|SLACK_WEBHOOK_URL|DISCORD_WEBHOOK_URL|STRIPE_SECRET_KEY|GOOGLE_API_KEY|ANTHROPIC_API_KEY|EVM_PRIVATE_KEY|JWT_TOKEN|BEARER_TOKEN|API_KEY_HEADER|AZURE_CONNECTION_STRING|AZURE_SAS_TOKEN)$/u.test(
1100
+ type
1101
+ )) {
1102
+ return 100;
1103
+ }
1104
+ if (/^(?:CREDENTIAL_ASSIGNMENT|PASSWORD_ASSIGNMENT|PRIVATE_KEY_MATERIAL|ENV_SECRET_ASSIGNMENT)$/u.test(type)) {
1105
+ return 80;
1106
+ }
1107
+ if (type === "PERSON_NAME" || type === "PERSON") {
1108
+ return 10;
1109
+ }
1110
+ return 50;
929
1111
  }
930
1112
  var PHONE_CONTEXT_KEYWORDS = [
931
1113
  "tel",
@@ -935,6 +1117,8 @@ var PHONE_CONTEXT_KEYWORDS = [
935
1117
  "call",
936
1118
  "contact",
937
1119
  "number",
1120
+ "cislo",
1121
+ "\u010D\xEDslo",
938
1122
  "hotline",
939
1123
  "support",
940
1124
  "infoline",
@@ -960,6 +1144,59 @@ var PHONE_CONTEXT_RE = new RegExp(
960
1144
  "iu"
961
1145
  );
962
1146
  var PERSON_NAME_STOPWORDS = /* @__PURE__ */ new Set([
1147
+ "name",
1148
+ "names",
1149
+ "namen",
1150
+ "firstname",
1151
+ "lastname",
1152
+ "first",
1153
+ "last",
1154
+ "forename",
1155
+ "surname",
1156
+ "family",
1157
+ "given",
1158
+ "jmeno",
1159
+ "jake",
1160
+ "jaky",
1161
+ "jaka",
1162
+ "jsem",
1163
+ "jsme",
1164
+ "napsal",
1165
+ "napsali",
1166
+ "napsala",
1167
+ "napsane",
1168
+ "pouzil",
1169
+ "pouzili",
1170
+ "prijmeni",
1171
+ "vorname",
1172
+ "nachname",
1173
+ "familienname",
1174
+ "what",
1175
+ "which",
1176
+ "whose",
1177
+ "did",
1178
+ "we",
1179
+ "write",
1180
+ "wrote",
1181
+ "written",
1182
+ "type",
1183
+ "typed",
1184
+ "use",
1185
+ "used",
1186
+ "wie",
1187
+ "welchen",
1188
+ "welche",
1189
+ "welches",
1190
+ "haben",
1191
+ "wir",
1192
+ "geschrieben",
1193
+ "getippt",
1194
+ "quel",
1195
+ "quelle",
1196
+ "nom",
1197
+ "que",
1198
+ "cual",
1199
+ "nombre",
963
1200
  "write",
964
1201
  "code",
965
1202
  "script",
@@ -986,6 +1223,52 @@ var PERSON_NAME_STOPWORDS = /* @__PURE__ */ new Set([
986
1223
  "security",
987
1224
  "instructions",
988
1225
  "instruction",
1226
+ "google",
1227
+ "form",
1228
+ "forms",
1229
+ "engineering",
1230
+ "leadership",
1231
+ "weekly",
1232
+ "daily",
1233
+ "monthly",
1234
+ "quarterly",
1235
+ "sync",
1236
+ "office",
1237
+ "updates",
1238
+ "update",
1239
+ "meeting",
1240
+ "meetings",
1241
+ "agenda",
1242
+ "minutes",
1243
+ "subject",
1244
+ "calendar",
1245
+ "roadmap",
1246
+ "platform",
1247
+ "product",
1248
+ "design",
1249
+ "operations",
1250
+ "business",
1251
+ "newsletter",
1252
+ "report",
1253
+ "reports",
1254
+ "amazon",
1255
+ "web",
1256
+ "services",
1257
+ "aws",
1258
+ "velka",
1259
+ "transformace",
1260
+ "project",
1261
+ "projekt",
1262
+ "program",
1263
+ "initiative",
1264
+ "iniciativa",
1265
+ "migration",
1266
+ "migrace",
1267
+ "test",
1268
+ "uuid",
1269
+ "fixture",
1270
+ "data",
1271
+ "firma",
989
1272
  "rules",
990
1273
  "rule",
991
1274
  "json",
@@ -998,10 +1281,22 @@ var PERSON_NAME_STOPWORDS = /* @__PURE__ */ new Set([
998
1281
  "agentid",
999
1282
  "risk",
1000
1283
  "score",
1001
- "summary"
1284
+ "summary",
1285
+ "hi",
1286
+ "hello",
1287
+ "hey",
1288
+ "dear",
1289
+ "team",
1290
+ "ahoj",
1291
+ "dobry",
1292
+ "dobryden",
1293
+ "zdravim"
1002
1294
  ]);
1003
1295
  var TECHNICAL_CONTEXT_WORD_REGEX = /\b(?:curl|http|https|import|python|javascript|typescript|sql|nosql|mongo|database|query|script|code|os\.system|eval|exec|node|npm|api|endpoint|regex|json|xml|yaml|bash|powershell)\b/i;
1004
1296
  var TECHNICAL_CONTEXT_SYMBOL_REGEX = /:\/\/|`|\{|\}|\[|\]|\(|\)|;|\$|=>|::|\/\//;
1297
+ var NAME_LABEL_QUESTION_CONTEXT_REGEX = /\b(?:jak(?:e|y|a|ou)|kter(?:e|y|a|ou)|co|what|which|whose|wie|welch(?:e|er|es|en|em)?|quel(?:le|s|les)?|que|cual(?:es)?|wat|welke|jaki|jakie|jaka)\b[\s\S]{0,80}\b(?:jmeno|prijmeni|name|names|namen|nom|nombre|nome|naam|imie|nazwisko|meno)\b[\s\S]{0,96}\b(?:napsal\p{L}*|napsan\p{L}*|psal\p{L}*|pouzil\p{L}*|pouzili\p{L}*|write|wrote|written|type|typed|enter(?:ed)?|use(?:d)?|say|said|geschrieben|getippt|eingetragen|ecrit|escrib\p{L}*|scritt\p{L}*)\b/iu;
1298
+ var NAME_VALUE_ASSIGNMENT_BEFORE_CANDIDATE_REGEX = /(?:[:=]|=>|-|\b(?:is|was|je|jsou|jmenuje|called|named|ist|sind|lautet|est|es)\b)\s*$/iu;
1299
+ var BIRTH_NUMBER_CONTEXT_RE = /\b(?:rodn[eé]\s*(?:č[ií]slo|cislo)|r\.?\s*c\.?|birth\s+number)\b[^0-9]{0,80}(\d{6}(?:\/?\d{3,4})?)\b/giu;
1005
1300
  function hasPhoneContext(text, matchStartIndex, windowSize = 50) {
1006
1301
  const start = Math.max(0, matchStartIndex - windowSize);
1007
1302
  const windowLower = text.slice(start, matchStartIndex).toLowerCase();
@@ -1018,6 +1313,16 @@ function buildContextWindow(source, index, length) {
1018
1313
  function isTechnicalContext(contextWindow) {
1019
1314
  return TECHNICAL_CONTEXT_WORD_REGEX.test(contextWindow) || TECHNICAL_CONTEXT_SYMBOL_REGEX.test(contextWindow);
1020
1315
  }
1316
+ function isNameLabelQuestionContext(contextWindow) {
1317
+ const normalized = normalizePersonWord(contextWindow);
1318
+ if (!normalized.trim()) {
1319
+ return false;
1320
+ }
1321
+ if (!NAME_LABEL_QUESTION_CONTEXT_REGEX.test(normalized)) {
1322
+ return false;
1323
+ }
1324
+ return !NAME_VALUE_ASSIGNMENT_BEFORE_CANDIDATE_REGEX.test(normalized.slice(-32));
1325
+ }
1021
1326
  function isLikelyPersonNameCandidate(candidate, contextWindow) {
1022
1327
  const words = candidate.trim().split(/\s+/);
1023
1328
  if (words.length !== 2) {
@@ -1026,6 +1331,9 @@ function isLikelyPersonNameCandidate(candidate, contextWindow) {
1026
1331
  if (isTechnicalContext(contextWindow)) {
1027
1332
  return false;
1028
1333
  }
1334
+ if (isNameLabelQuestionContext(contextWindow)) {
1335
+ return false;
1336
+ }
1029
1337
  for (const rawWord of words) {
1030
1338
  const normalized = normalizePersonWord(rawWord);
1031
1339
  if (normalized.length < 2) {
@@ -1046,63 +1354,135 @@ var PIIManager = class {
1046
1354
  *
1047
1355
  * Zero-dependency fallback with strict checksum validation for CEE national IDs.
1048
1356
  */
1049
- anonymize(text) {
1357
+ anonymize(text, options) {
1050
1358
  if (!text) return { maskedText: text, mapping: {} };
1051
1359
  try {
1052
1360
  const detections = [];
1053
- const emailRe = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi;
1054
- for (const m of text.matchAll(emailRe)) {
1055
- if (m.index == null) continue;
1056
- detections.push({ start: m.index, end: m.index + m[0].length, type: "EMAIL", text: m[0] });
1361
+ const loweredText = text.toLowerCase();
1362
+ const resolvedOptions = {
1363
+ pii: options?.pii !== false,
1364
+ secrets: options?.secrets !== false
1365
+ };
1366
+ if (!resolvedOptions.pii && !resolvedOptions.secrets) {
1367
+ return { maskedText: text, mapping: {} };
1057
1368
  }
1058
- const ibanRe = /\b[A-Z]{2}\d{2}[A-Z0-9]{11,30}\b/gi;
1059
- for (const m of text.matchAll(ibanRe)) {
1060
- if (m.index == null) continue;
1061
- detections.push({ start: m.index, end: m.index + m[0].length, type: "IBAN", text: m[0] });
1062
- }
1063
- const ccRe = /(?:\b\d[\d -]{10,22}\d\b)/g;
1064
- for (const m of text.matchAll(ccRe)) {
1065
- if (m.index == null) continue;
1066
- const digits = countDigits2(m[0]);
1067
- if (digits < 12 || digits > 19) continue;
1068
- if (!luhnCheck(m[0])) continue;
1069
- detections.push({ start: m.index, end: m.index + m[0].length, type: "CREDIT_CARD", text: m[0] });
1070
- }
1071
- const phoneRe = /(?<!\d)(?:\+?\d[\d\s().-]{7,}\d)(?!\d)/g;
1072
- for (const m of text.matchAll(phoneRe)) {
1073
- if (m.index == null) continue;
1074
- const candidate = m[0];
1075
- const digits = countDigits2(candidate);
1076
- if (digits < 9 || digits > 15) continue;
1077
- const isStrongInternational = candidate.startsWith("+") || candidate.startsWith("00");
1078
- if (!isStrongInternational) {
1079
- const hasContext = hasPhoneContext(text, m.index);
1080
- if (!hasContext) continue;
1369
+ if (resolvedOptions.pii) {
1370
+ const emailRe = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi;
1371
+ for (const m of text.matchAll(emailRe)) {
1372
+ if (m.index == null) continue;
1373
+ detections.push({ start: m.index, end: m.index + m[0].length, type: "EMAIL", text: m[0] });
1081
1374
  }
1082
- detections.push({ start: m.index, end: m.index + m[0].length, type: "PHONE", text: m[0] });
1083
- }
1084
- const personRe = /(?<!\p{L})\p{Lu}\p{Ll}{2,}\s+\p{Lu}\p{Ll}{2,}(?!\p{L})/gu;
1085
- for (const m of text.matchAll(personRe)) {
1086
- if (m.index == null) continue;
1087
- const candidate = m[0];
1088
- const contextWindow = buildContextWindow(text, m.index, candidate.length);
1089
- if (!isLikelyPersonNameCandidate(candidate, contextWindow)) {
1090
- continue;
1375
+ const ibanRe = /\b[A-Z]{2}\d{2}[A-Z0-9]{11,30}\b/gi;
1376
+ for (const m of text.matchAll(ibanRe)) {
1377
+ if (m.index == null) continue;
1378
+ detections.push({ start: m.index, end: m.index + m[0].length, type: "IBAN", text: m[0] });
1091
1379
  }
1092
- detections.push({ start: m.index, end: m.index + candidate.length, type: "PERSON", text: candidate });
1093
- }
1094
- const nationalIdMatches = detectNationalIdentifiers(text, {
1095
- deadlineMs: defaultScanDeadlineMs,
1096
- allowContextBirthNumberFallback: false
1097
- });
1098
- for (const match of nationalIdMatches) {
1099
- if (match.start < 0 || match.end <= match.start) continue;
1100
- detections.push({
1101
- start: match.start,
1102
- end: match.end,
1103
- type: "NATIONAL_ID",
1104
- text: text.slice(match.start, match.end)
1380
+ const ccRe = /(?:\b\d[\d -]{10,22}\d\b)/g;
1381
+ for (const m of text.matchAll(ccRe)) {
1382
+ if (m.index == null) continue;
1383
+ const digits = countDigits2(m[0]);
1384
+ if (digits < 12 || digits > 19) continue;
1385
+ if (!luhnCheck(m[0])) continue;
1386
+ detections.push({ start: m.index, end: m.index + m[0].length, type: "CREDIT_CARD", text: m[0] });
1387
+ }
1388
+ const phoneRe = /(?<!\d)(?:\+?\d[\d\s().-]{7,}\d)(?!\d)/g;
1389
+ for (const m of text.matchAll(phoneRe)) {
1390
+ if (m.index == null) continue;
1391
+ const candidate = m[0];
1392
+ const digits = countDigits2(candidate);
1393
+ if (digits < 9 || digits > 15) continue;
1394
+ const isStrongInternational = candidate.startsWith("+") || candidate.startsWith("00");
1395
+ if (!isStrongInternational) {
1396
+ const hasContext = hasPhoneContext(text, m.index);
1397
+ if (!hasContext) continue;
1398
+ }
1399
+ detections.push({ start: m.index, end: m.index + m[0].length, type: "PHONE", text: m[0] });
1400
+ }
1401
+ const personRe = /(?<!\p{L})\p{Lu}\p{Ll}{2,}\s+\p{Lu}\p{Ll}{2,}(?!\p{L})/gu;
1402
+ for (const m of text.matchAll(personRe)) {
1403
+ if (m.index == null) continue;
1404
+ const candidate = m[0];
1405
+ const contextWindow = buildContextWindow(text, m.index, candidate.length);
1406
+ if (!isLikelyPersonNameCandidate(candidate, contextWindow)) {
1407
+ continue;
1408
+ }
1409
+ detections.push({ start: m.index, end: m.index + candidate.length, type: "PERSON", text: candidate });
1410
+ }
1411
+ BIRTH_NUMBER_CONTEXT_RE.lastIndex = 0;
1412
+ for (const match of text.matchAll(BIRTH_NUMBER_CONTEXT_RE)) {
1413
+ if (match.index == null) continue;
1414
+ const value = match[1] ?? "";
1415
+ if (!/^\d{6}(?:\/?\d{3,4})?$/.test(value)) continue;
1416
+ const localIndex = match[0].lastIndexOf(value);
1417
+ const start = match.index + Math.max(0, localIndex);
1418
+ detections.push({
1419
+ start,
1420
+ end: start + value.length,
1421
+ type: "BIRTH_NUMBER",
1422
+ text: value
1423
+ });
1424
+ }
1425
+ const nationalIdMatches = detectNationalIdentifiers(text, {
1426
+ deadlineMs: defaultScanDeadlineMs,
1427
+ allowContextBirthNumberFallback: false
1105
1428
  });
1429
+ for (const match of nationalIdMatches) {
1430
+ if (match.start < 0 || match.end <= match.start) continue;
1431
+ detections.push({
1432
+ start: match.start,
1433
+ end: match.end,
1434
+ type: "NATIONAL_ID",
1435
+ text: text.slice(match.start, match.end)
1436
+ });
1437
+ }
1438
+ }
1439
+ if (resolvedOptions.secrets) {
1440
+ BASIC_AUTH_PASSWORD_RE.lastIndex = 0;
1441
+ for (const match of text.matchAll(BASIC_AUTH_PASSWORD_RE)) {
1442
+ if (match.index == null) continue;
1443
+ const password = match[1] ?? "";
1444
+ if (!password) continue;
1445
+ const localIndex = match[0].lastIndexOf(password);
1446
+ const start = match.index + Math.max(0, localIndex);
1447
+ detections.push({
1448
+ start,
1449
+ end: start + password.length,
1450
+ type: "BASIC_AUTH_PASSWORD",
1451
+ text: password
1452
+ });
1453
+ }
1454
+ DISCORD_WEBHOOK_TOKEN_RE.lastIndex = 0;
1455
+ for (const match of text.matchAll(DISCORD_WEBHOOK_TOKEN_RE)) {
1456
+ if (match.index == null) continue;
1457
+ const token = match[1] ?? "";
1458
+ if (!token) continue;
1459
+ const localIndex = match[0].lastIndexOf(token);
1460
+ const start = match.index + Math.max(0, localIndex);
1461
+ detections.push({
1462
+ start,
1463
+ end: start + token.length,
1464
+ type: "DISCORD_WEBHOOK_TOKEN",
1465
+ text: token
1466
+ });
1467
+ }
1468
+ for (const matcher of sdkSecretMatchers) {
1469
+ if (matcher.id === "discord_webhook_url") {
1470
+ continue;
1471
+ }
1472
+ if (matcher.prefilterTermsLower.length > 0 && !matcher.prefilterTermsLower.some((term) => loweredText.includes(term))) {
1473
+ continue;
1474
+ }
1475
+ matcher.scanRegex.lastIndex = 0;
1476
+ for (const match of text.matchAll(matcher.scanRegex)) {
1477
+ if (match.index == null) continue;
1478
+ detections.push({
1479
+ start: match.index,
1480
+ end: match.index + match[0].length,
1481
+ type: matcher.placeholderType,
1482
+ text: match[0]
1483
+ });
1484
+ }
1485
+ }
1106
1486
  }
1107
1487
  const kept = normalizeDetections(text, detections);
1108
1488
  if (!kept.length) return { maskedText: text, mapping: {} };
@@ -1143,6 +1523,109 @@ var CONFIG_TTL_MS = 15 * 1e3;
1143
1523
  var CONFIG_FAILURE_FALLBACK_TTL_MS = 2 * 1e3;
1144
1524
 
1145
1525
  // src/agentid.ts
1526
+ function getObjectString(value, ...keys) {
1527
+ for (const key of keys) {
1528
+ const candidate = value?.[key];
1529
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
1530
+ return candidate.trim();
1531
+ }
1532
+ }
1533
+ return void 0;
1534
+ }
1535
+ function getObjectNumber(value, ...keys) {
1536
+ for (const key of keys) {
1537
+ const candidate = value?.[key];
1538
+ if (typeof candidate === "number" && Number.isFinite(candidate)) {
1539
+ return candidate;
1540
+ }
1541
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
1542
+ const parsed = Number(candidate);
1543
+ if (Number.isFinite(parsed)) {
1544
+ return parsed;
1545
+ }
1546
+ }
1547
+ }
1548
+ return void 0;
1549
+ }
1550
+ function createAgentIdTelemetryContext(value) {
1551
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1552
+ return void 0;
1553
+ }
1554
+ const raw = { ...value };
1555
+ const normalized = {};
1556
+ const assignString = (key, ...aliases) => {
1557
+ const next = getObjectString(raw, key, ...aliases);
1558
+ if (next) {
1559
+ normalized[key] = next;
1560
+ }
1561
+ };
1562
+ const assignNumber = (key, ...aliases) => {
1563
+ const next = getObjectNumber(raw, key, ...aliases);
1564
+ if (typeof next === "number") {
1565
+ normalized[key] = next;
1566
+ }
1567
+ };
1568
+ assignString("workflow_id", "workflowId");
1569
+ assignString("workflow_run_id", "workflowRunId");
1570
+ assignString("workflow_step_id", "workflowStepId");
1571
+ assignString("workflow_name", "workflowName");
1572
+ assignString("workflow_step_name", "workflowStepName");
1573
+ assignNumber("workflow_step_index", "workflowStepIndex");
1574
+ assignString("parent_event_id", "parentEventId");
1575
+ assignString("tool_name", "toolName");
1576
+ assignString("tool_target", "toolTarget");
1577
+ assignString("tool_target_type", "toolTargetType");
1578
+ assignString("event_title", "eventTitle");
1579
+ assignString("event_status", "eventStatus");
1580
+ assignString("event_category", "eventCategory");
1581
+ assignString("event_subtype", "eventSubtype");
1582
+ const consumedKeys = /* @__PURE__ */ new Set([
1583
+ "workflow_id",
1584
+ "workflowId",
1585
+ "workflow_run_id",
1586
+ "workflowRunId",
1587
+ "workflow_step_id",
1588
+ "workflowStepId",
1589
+ "workflow_name",
1590
+ "workflowName",
1591
+ "workflow_step_name",
1592
+ "workflowStepName",
1593
+ "workflow_step_index",
1594
+ "workflowStepIndex",
1595
+ "parent_event_id",
1596
+ "parentEventId",
1597
+ "tool_name",
1598
+ "toolName",
1599
+ "tool_target",
1600
+ "toolTarget",
1601
+ "tool_target_type",
1602
+ "toolTargetType",
1603
+ "event_title",
1604
+ "eventTitle",
1605
+ "event_status",
1606
+ "eventStatus",
1607
+ "event_category",
1608
+ "eventCategory",
1609
+ "event_subtype",
1610
+ "eventSubtype"
1611
+ ]);
1612
+ for (const [key, entry] of Object.entries(raw)) {
1613
+ if (consumedKeys.has(key) || entry === void 0) {
1614
+ continue;
1615
+ }
1616
+ if (typeof entry === "string") {
1617
+ if (entry.trim().length > 0) {
1618
+ normalized[key] = entry.trim();
1619
+ }
1620
+ continue;
1621
+ }
1622
+ normalized[key] = entry;
1623
+ }
1624
+ if (typeof normalized.workflow_id !== "string" && typeof normalized.workflow_run_id === "string") {
1625
+ normalized.workflow_id = normalized.workflow_run_id;
1626
+ }
1627
+ return Object.keys(normalized).length > 0 ? normalized : void 0;
1628
+ }
1146
1629
  var SecurityBlockError = class extends Error {
1147
1630
  constructor(reason = "guard_denied") {
1148
1631
  super(`AgentID: Security Blocked (${reason})`);
@@ -1153,9 +1636,18 @@ var SecurityBlockError = class extends Error {
1153
1636
 
1154
1637
  // src/langchain.ts
1155
1638
  var piiManager = new PIIManager();
1639
+ var LANGCHAIN_TELEMETRY_FIELD = "agentid_telemetry";
1156
1640
  function safeString(val) {
1157
1641
  return typeof val === "string" ? val : "";
1158
1642
  }
1643
+ function firstNonEmptyString(...values) {
1644
+ for (const value of values) {
1645
+ if (typeof value === "string" && value.trim().length > 0) {
1646
+ return value.trim();
1647
+ }
1648
+ }
1649
+ return void 0;
1650
+ }
1159
1651
  function normalizeExpectedLanguages(value) {
1160
1652
  if (!Array.isArray(value)) {
1161
1653
  return void 0;
@@ -1165,6 +1657,121 @@ function normalizeExpectedLanguages(value) {
1165
1657
  )];
1166
1658
  return normalized.length > 0 ? normalized : void 0;
1167
1659
  }
1660
+ function isPlainRecord(value) {
1661
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
1662
+ }
1663
+ function hasKnownTelemetryField(record) {
1664
+ const knownKeys = [
1665
+ "workflow_id",
1666
+ "workflowId",
1667
+ "workflow_run_id",
1668
+ "workflowRunId",
1669
+ "workflow_step_id",
1670
+ "workflowStepId",
1671
+ "workflow_name",
1672
+ "workflowName",
1673
+ "workflow_step_name",
1674
+ "workflowStepName",
1675
+ "workflow_step_index",
1676
+ "workflowStepIndex",
1677
+ "parent_event_id",
1678
+ "parentEventId",
1679
+ "tool_name",
1680
+ "toolName",
1681
+ "tool_target",
1682
+ "toolTarget",
1683
+ "tool_target_type",
1684
+ "toolTargetType",
1685
+ "event_title",
1686
+ "eventTitle",
1687
+ "event_status",
1688
+ "eventStatus",
1689
+ "event_category",
1690
+ "eventCategory",
1691
+ "event_subtype",
1692
+ "eventSubtype"
1693
+ ];
1694
+ return knownKeys.some((key) => Object.prototype.hasOwnProperty.call(record, key));
1695
+ }
1696
+ function asTelemetryContext(value) {
1697
+ if (!isPlainRecord(value)) {
1698
+ return void 0;
1699
+ }
1700
+ return createAgentIdTelemetryContext(value);
1701
+ }
1702
+ function mergeTelemetryContexts(...contexts) {
1703
+ const merged = {};
1704
+ let hasValues = false;
1705
+ for (const context of contexts) {
1706
+ const normalized = createAgentIdTelemetryContext(context);
1707
+ if (!normalized) {
1708
+ continue;
1709
+ }
1710
+ Object.assign(merged, normalized);
1711
+ hasValues = true;
1712
+ }
1713
+ return hasValues ? createAgentIdTelemetryContext(merged) : void 0;
1714
+ }
1715
+ function extractTelemetryFromRecord(record) {
1716
+ const candidates = [];
1717
+ const add = (value) => {
1718
+ const telemetry = asTelemetryContext(value);
1719
+ if (telemetry) {
1720
+ candidates.push(telemetry);
1721
+ }
1722
+ };
1723
+ add(record[LANGCHAIN_TELEMETRY_FIELD]);
1724
+ add(record.agentidTelemetry);
1725
+ const agentid = record.agentid;
1726
+ if (isPlainRecord(agentid)) {
1727
+ add(agentid.telemetry);
1728
+ add(agentid.telemetryMetadata);
1729
+ }
1730
+ if (hasKnownTelemetryField(record)) {
1731
+ add(record);
1732
+ }
1733
+ return mergeTelemetryContexts(...candidates);
1734
+ }
1735
+ function extractLangChainTelemetryContext(extraParams) {
1736
+ if (!isPlainRecord(extraParams)) {
1737
+ return void 0;
1738
+ }
1739
+ const contexts = [];
1740
+ const addFromRecord = (record) => {
1741
+ if (!isPlainRecord(record)) {
1742
+ return;
1743
+ }
1744
+ const telemetry = extractTelemetryFromRecord(record);
1745
+ if (telemetry) {
1746
+ contexts.push(telemetry);
1747
+ }
1748
+ };
1749
+ addFromRecord(extraParams);
1750
+ addFromRecord(extraParams.metadata);
1751
+ addFromRecord(extraParams.options);
1752
+ if (isPlainRecord(extraParams.options)) {
1753
+ addFromRecord(extraParams.options.metadata);
1754
+ }
1755
+ addFromRecord(extraParams.invocation_params);
1756
+ if (isPlainRecord(extraParams.invocation_params)) {
1757
+ addFromRecord(extraParams.invocation_params.metadata);
1758
+ }
1759
+ addFromRecord(extraParams.kwargs);
1760
+ if (isPlainRecord(extraParams.kwargs)) {
1761
+ addFromRecord(extraParams.kwargs.metadata);
1762
+ }
1763
+ return mergeTelemetryContexts(...contexts);
1764
+ }
1765
+ function extractTelemetryFromValues(...values) {
1766
+ const contexts = [];
1767
+ for (const value of values) {
1768
+ const telemetry = extractLangChainTelemetryContext(value);
1769
+ if (telemetry) {
1770
+ contexts.push(telemetry);
1771
+ }
1772
+ }
1773
+ return mergeTelemetryContexts(...contexts);
1774
+ }
1168
1775
  function coerceTransparencyMetadata(value) {
1169
1776
  if (!value || typeof value !== "object" || Array.isArray(value)) {
1170
1777
  return void 0;
@@ -1335,6 +1942,40 @@ function extractModel(serialized, kwargs) {
1335
1942
  if (typeof name === "string" && name) return name;
1336
1943
  return void 0;
1337
1944
  }
1945
+ function extractToolName(serialized, extras, telemetry) {
1946
+ const serializedRecord = serialized && typeof serialized === "object" ? serialized : void 0;
1947
+ const extraName = extras.find(
1948
+ (value) => typeof value === "string" && value.trim().length > 0
1949
+ );
1950
+ return firstNonEmptyString(
1951
+ telemetry?.tool_name,
1952
+ telemetry?.toolName,
1953
+ serializedRecord?.name,
1954
+ serializedRecord?.id,
1955
+ serializedRecord?.tool_name,
1956
+ serializedRecord?.toolName,
1957
+ extraName
1958
+ );
1959
+ }
1960
+ function extractWorkflowName(serialized, extras, telemetry) {
1961
+ const serializedRecord = serialized && typeof serialized === "object" ? serialized : void 0;
1962
+ const extraName = extras.find(
1963
+ (value) => typeof value === "string" && value.trim().length > 0
1964
+ );
1965
+ return firstNonEmptyString(
1966
+ telemetry?.workflow_step_name,
1967
+ telemetry?.workflowStepName,
1968
+ telemetry?.workflow_name,
1969
+ telemetry?.workflowName,
1970
+ telemetry?.event_title,
1971
+ telemetry?.eventTitle,
1972
+ serializedRecord?.name,
1973
+ serializedRecord?.id,
1974
+ serializedRecord?.chain_name,
1975
+ serializedRecord?.chainName,
1976
+ extraName
1977
+ );
1978
+ }
1338
1979
  function extractModelFromOutput(output) {
1339
1980
  const llmOutput = output?.llmOutput ?? output?.llm_output;
1340
1981
  const llmModel = llmOutput?.model ?? llmOutput?.model_name ?? llmOutput?.modelName;
@@ -1485,22 +2126,28 @@ var AgentIDCallbackHandler = class extends import_base.BaseCallbackHandler {
1485
2126
  super();
1486
2127
  this.name = "agentid_callback_handler";
1487
2128
  this.runs = /* @__PURE__ */ new Map();
2129
+ this.toolRuns = /* @__PURE__ */ new Map();
2130
+ this.chainRuns = /* @__PURE__ */ new Map();
1488
2131
  this.agent = agent;
1489
2132
  this.systemId = options.system_id;
1490
2133
  this.expectedLanguages = normalizeExpectedLanguages(
1491
2134
  options.expected_languages ?? options.expectedLanguages
1492
2135
  );
1493
2136
  this.apiKeyOverride = options.apiKey?.trim() || options.api_key?.trim() || void 0;
2137
+ this.telemetry = createAgentIdTelemetryContext(options.telemetry);
1494
2138
  }
1495
2139
  get requestOptions() {
1496
2140
  return this.apiKeyOverride ? { apiKey: this.apiKeyOverride } : void 0;
1497
2141
  }
1498
- getLangchainCapabilities(piiMaskingEnabled) {
2142
+ getLangchainCapabilities(piiMaskingEnabled, secretMaskingEnabled) {
1499
2143
  const resolvedPiiMaskingEnabled = typeof piiMaskingEnabled === "boolean" ? piiMaskingEnabled : this.agent.getEffectivePiiMasking(this.requestOptions);
2144
+ const agentWithResolvedSecret = this.agent;
2145
+ const resolvedSecretMaskingEnabled = typeof secretMaskingEnabled === "boolean" ? secretMaskingEnabled : typeof agentWithResolvedSecret.getEffectiveSecretMaskingForConfig === "function" ? agentWithResolvedSecret.getEffectiveSecretMaskingForConfig() : false;
1500
2146
  return {
1501
2147
  capabilities: {
1502
2148
  has_feedback_handler: true,
1503
2149
  pii_masking_enabled: resolvedPiiMaskingEnabled,
2150
+ secret_masking_enabled: resolvedSecretMaskingEnabled,
1504
2151
  framework: "langchain"
1505
2152
  }
1506
2153
  };
@@ -1512,15 +2159,76 @@ var AgentIDCallbackHandler = class extends import_base.BaseCallbackHandler {
1512
2159
  }
1513
2160
  return this.agent.getEffectivePiiMasking(this.requestOptions);
1514
2161
  }
1515
- async preflight(input, stream, clientEventId) {
2162
+ resolvePreparedSecretMaskingEnabled(prepared) {
2163
+ const agentWithResolvedConfig = this.agent;
2164
+ if (typeof agentWithResolvedConfig.getEffectiveSecretMaskingForConfig === "function") {
2165
+ return agentWithResolvedConfig.getEffectiveSecretMaskingForConfig(
2166
+ prepared.capabilityConfig
2167
+ );
2168
+ }
2169
+ return false;
2170
+ }
2171
+ async preflight(input, stream, clientEventId, telemetryMetadata) {
1516
2172
  const prepared = await this.agent.prepareInputForDispatch({
1517
2173
  input,
1518
2174
  systemId: this.systemId,
1519
2175
  stream,
1520
- clientEventId
2176
+ clientEventId,
2177
+ telemetryMetadata
1521
2178
  }, this.requestOptions);
1522
2179
  return prepared;
1523
2180
  }
2181
+ resolveTelemetry(extraParams) {
2182
+ return mergeTelemetryContexts(
2183
+ this.telemetry,
2184
+ extractLangChainTelemetryContext(extraParams)
2185
+ );
2186
+ }
2187
+ resolveParentEventContext(parentRunId) {
2188
+ const parentId = String(parentRunId ?? "");
2189
+ const llmRun = this.runs.get(parentId);
2190
+ if (llmRun) {
2191
+ return {
2192
+ parentEventId: llmRun.clientEventId,
2193
+ piiMaskingEnabled: llmRun.piiMaskingEnabled,
2194
+ secretMaskingEnabled: llmRun.secretMaskingEnabled
2195
+ };
2196
+ }
2197
+ const toolRun = this.toolRuns.get(parentId);
2198
+ if (toolRun) {
2199
+ return {
2200
+ parentEventId: toolRun.startEventId,
2201
+ piiMaskingEnabled: toolRun.piiMaskingEnabled,
2202
+ secretMaskingEnabled: toolRun.secretMaskingEnabled
2203
+ };
2204
+ }
2205
+ const chainRun = this.chainRuns.get(parentId);
2206
+ if (chainRun) {
2207
+ return {
2208
+ parentEventId: chainRun.startEventId,
2209
+ piiMaskingEnabled: chainRun.piiMaskingEnabled,
2210
+ secretMaskingEnabled: chainRun.secretMaskingEnabled
2211
+ };
2212
+ }
2213
+ return {};
2214
+ }
2215
+ async logWorkflowOperation(params, capabilityHints) {
2216
+ const payload = this.agent.buildOperationLogParams({
2217
+ system_id: this.systemId,
2218
+ telemetry: params.telemetry,
2219
+ metadata: params.metadata,
2220
+ event_type: params.event_type,
2221
+ event_status: params.event_status,
2222
+ severity: params.severity,
2223
+ latency: params.latency,
2224
+ client_capabilities: this.getLangchainCapabilities(
2225
+ capabilityHints?.piiMaskingEnabled,
2226
+ capabilityHints?.secretMaskingEnabled
2227
+ )
2228
+ });
2229
+ await this.agent.log(payload, this.requestOptions);
2230
+ return payload;
2231
+ }
1524
2232
  async handleLLMStart(serialized, prompts, runId, _parentRunId, extraParams) {
1525
2233
  const input = extractPromptFromPrompts(prompts);
1526
2234
  const id = String(runId ?? "");
@@ -1530,9 +2238,16 @@ var AgentIDCallbackHandler = class extends import_base.BaseCallbackHandler {
1530
2238
  }
1531
2239
  const requestedClientEventId = isUuidLike(id) ? id.trim() : createClientEventId();
1532
2240
  const stream = extractStreamFlag(serialized, extraParams);
1533
- const prepared = await this.preflight(input, stream, requestedClientEventId);
2241
+ const telemetryMetadata = this.resolveTelemetry(extraParams);
2242
+ const prepared = await this.preflight(
2243
+ input,
2244
+ stream,
2245
+ requestedClientEventId,
2246
+ telemetryMetadata
2247
+ );
1534
2248
  const sanitizedInput = prepared.sanitizedInput;
1535
2249
  const piiMaskingEnabled = this.resolvePreparedPiiMaskingEnabled(prepared);
2250
+ const secretMaskingEnabled = this.resolvePreparedSecretMaskingEnabled(prepared);
1536
2251
  if (sanitizedInput !== input) {
1537
2252
  const mutated = setPromptInPrompts(prompts, sanitizedInput);
1538
2253
  if (!mutated) {
@@ -1549,7 +2264,11 @@ var AgentIDCallbackHandler = class extends import_base.BaseCallbackHandler {
1549
2264
  model: modelName,
1550
2265
  client_event_id: requestedClientEventId,
1551
2266
  expected_languages: this.expectedLanguages,
1552
- client_capabilities: this.getLangchainCapabilities(piiMaskingEnabled)
2267
+ metadata: telemetryMetadata,
2268
+ client_capabilities: this.getLangchainCapabilities(
2269
+ piiMaskingEnabled,
2270
+ secretMaskingEnabled
2271
+ )
1553
2272
  }, this.requestOptions);
1554
2273
  let transformedForRun = sanitizedInput;
1555
2274
  let sdkLocalScanMs = prepared.sdkLocalScanMs;
@@ -1564,7 +2283,8 @@ var AgentIDCallbackHandler = class extends import_base.BaseCallbackHandler {
1564
2283
  stream,
1565
2284
  clientEventId: requestedClientEventId,
1566
2285
  capabilityConfig: prepared.capabilityConfig,
1567
- sdkConfigFetchMs: prepared.sdkConfigFetchMs
2286
+ sdkConfigFetchMs: prepared.sdkConfigFetchMs,
2287
+ telemetryMetadata
1568
2288
  }, this.requestOptions);
1569
2289
  transformedForRun = fallback.sanitizedInput;
1570
2290
  sdkLocalScanMs = fallback.sdkLocalScanMs;
@@ -1603,12 +2323,14 @@ var AgentIDCallbackHandler = class extends import_base.BaseCallbackHandler {
1603
2323
  model: modelName,
1604
2324
  clientEventId: canonicalClientEventId,
1605
2325
  guardEventId,
2326
+ telemetryMetadata,
1606
2327
  transparency,
1607
2328
  piiMapping: normalizePiiMapping(prepared.piiMapping),
1608
2329
  shouldDeanonymize: prepared.shouldDeanonymize === true,
1609
2330
  responseStreamed: stream,
1610
2331
  sdkConfigVersion: prepared.capabilityConfig?.version ?? null,
1611
- piiMaskingEnabled
2332
+ piiMaskingEnabled,
2333
+ secretMaskingEnabled
1612
2334
  });
1613
2335
  logCallbackDebug("handleLLMStart state_set", {
1614
2336
  runId: id,
@@ -1625,9 +2347,16 @@ var AgentIDCallbackHandler = class extends import_base.BaseCallbackHandler {
1625
2347
  }
1626
2348
  const requestedClientEventId = isUuidLike(id) ? id.trim() : createClientEventId();
1627
2349
  const stream = extractStreamFlag(serialized, extraParams);
1628
- const prepared = await this.preflight(input, stream, requestedClientEventId);
2350
+ const telemetryMetadata = this.resolveTelemetry(extraParams);
2351
+ const prepared = await this.preflight(
2352
+ input,
2353
+ stream,
2354
+ requestedClientEventId,
2355
+ telemetryMetadata
2356
+ );
1629
2357
  const sanitizedInput = prepared.sanitizedInput;
1630
2358
  const piiMaskingEnabled = this.resolvePreparedPiiMaskingEnabled(prepared);
2359
+ const secretMaskingEnabled = this.resolvePreparedSecretMaskingEnabled(prepared);
1631
2360
  if (sanitizedInput !== input) {
1632
2361
  const mutated = setPromptInMessages(messages, sanitizedInput);
1633
2362
  if (!mutated) {
@@ -1644,7 +2373,11 @@ var AgentIDCallbackHandler = class extends import_base.BaseCallbackHandler {
1644
2373
  model: modelName,
1645
2374
  client_event_id: requestedClientEventId,
1646
2375
  expected_languages: this.expectedLanguages,
1647
- client_capabilities: this.getLangchainCapabilities(piiMaskingEnabled)
2376
+ metadata: telemetryMetadata,
2377
+ client_capabilities: this.getLangchainCapabilities(
2378
+ piiMaskingEnabled,
2379
+ secretMaskingEnabled
2380
+ )
1648
2381
  }, this.requestOptions);
1649
2382
  let transformedForRun = sanitizedInput;
1650
2383
  let sdkLocalScanMs = prepared.sdkLocalScanMs;
@@ -1659,7 +2392,8 @@ var AgentIDCallbackHandler = class extends import_base.BaseCallbackHandler {
1659
2392
  stream,
1660
2393
  clientEventId: requestedClientEventId,
1661
2394
  capabilityConfig: prepared.capabilityConfig,
1662
- sdkConfigFetchMs: prepared.sdkConfigFetchMs
2395
+ sdkConfigFetchMs: prepared.sdkConfigFetchMs,
2396
+ telemetryMetadata
1663
2397
  }, this.requestOptions);
1664
2398
  transformedForRun = fallback.sanitizedInput;
1665
2399
  sdkLocalScanMs = fallback.sdkLocalScanMs;
@@ -1698,12 +2432,14 @@ var AgentIDCallbackHandler = class extends import_base.BaseCallbackHandler {
1698
2432
  model: modelName,
1699
2433
  clientEventId: canonicalClientEventId,
1700
2434
  guardEventId,
2435
+ telemetryMetadata,
1701
2436
  transparency,
1702
2437
  piiMapping: normalizePiiMapping(prepared.piiMapping),
1703
2438
  shouldDeanonymize: prepared.shouldDeanonymize === true,
1704
2439
  responseStreamed: stream,
1705
2440
  sdkConfigVersion: prepared.capabilityConfig?.version ?? null,
1706
- piiMaskingEnabled
2441
+ piiMaskingEnabled,
2442
+ secretMaskingEnabled
1707
2443
  });
1708
2444
  logCallbackDebug("handleChatModelStart state_set", {
1709
2445
  runId: id,
@@ -1731,7 +2467,9 @@ var AgentIDCallbackHandler = class extends import_base.BaseCallbackHandler {
1731
2467
  }
1732
2468
  const clientOutputText = extractOutputText(output);
1733
2469
  const usage = extractTokenUsage(output);
1734
- const metadata = {};
2470
+ const metadata = {
2471
+ ...state.telemetryMetadata ?? {}
2472
+ };
1735
2473
  if (state.clientEventId) {
1736
2474
  metadata.client_event_id = state.clientEventId;
1737
2475
  }
@@ -1767,7 +2505,10 @@ var AgentIDCallbackHandler = class extends import_base.BaseCallbackHandler {
1767
2505
  usage,
1768
2506
  latency: modelLatencyMs,
1769
2507
  metadata: Object.keys(metadata).length > 0 ? metadata : void 0,
1770
- client_capabilities: this.getLangchainCapabilities(state.piiMaskingEnabled)
2508
+ client_capabilities: this.getLangchainCapabilities(
2509
+ state.piiMaskingEnabled,
2510
+ state.secretMaskingEnabled
2511
+ )
1771
2512
  }, this.requestOptions);
1772
2513
  logCallbackDebug("handleLLMEnd logged", {
1773
2514
  runId: id,
@@ -1781,6 +2522,7 @@ var AgentIDCallbackHandler = class extends import_base.BaseCallbackHandler {
1781
2522
  if (state) this.runs.delete(id);
1782
2523
  const message = err && typeof err === "object" && "message" in err ? String(err.message) : String(err ?? "");
1783
2524
  const metadata = {
2525
+ ...state?.telemetryMetadata ?? {},
1784
2526
  error_message: message
1785
2527
  };
1786
2528
  if (state?.clientEventId) {
@@ -1809,9 +2551,184 @@ var AgentIDCallbackHandler = class extends import_base.BaseCallbackHandler {
1809
2551
  event_type: "error",
1810
2552
  severity: "error",
1811
2553
  metadata,
1812
- client_capabilities: this.getLangchainCapabilities(state?.piiMaskingEnabled)
2554
+ client_capabilities: this.getLangchainCapabilities(
2555
+ state?.piiMaskingEnabled,
2556
+ state?.secretMaskingEnabled
2557
+ )
1813
2558
  }, this.requestOptions);
1814
2559
  }
2560
+ async handleToolStart(serialized, _input, runId, parentRunId, ...rest) {
2561
+ const id = String(runId ?? "");
2562
+ const parentContext = this.resolveParentEventContext(parentRunId);
2563
+ const baseTelemetry = extractTelemetryFromValues(...rest);
2564
+ const toolName = extractToolName(serialized, rest, baseTelemetry);
2565
+ const workflowStepId = firstNonEmptyString(baseTelemetry?.workflow_step_id, baseTelemetry?.workflowStepId) ?? createClientEventId();
2566
+ const telemetry = mergeTelemetryContexts(
2567
+ this.telemetry,
2568
+ baseTelemetry,
2569
+ createAgentIdTelemetryContext({
2570
+ workflow_step_id: workflowStepId,
2571
+ parent_event_id: parentContext.parentEventId,
2572
+ tool_name: toolName
2573
+ })
2574
+ );
2575
+ const startedAtMs = Date.now();
2576
+ const payload = await this.logWorkflowOperation(
2577
+ {
2578
+ telemetry,
2579
+ event_type: "start",
2580
+ event_status: "started"
2581
+ },
2582
+ parentContext
2583
+ );
2584
+ this.toolRuns.set(id, {
2585
+ startedAtMs,
2586
+ workflowStepId,
2587
+ startEventId: payload.event_id ?? createClientEventId(),
2588
+ telemetryMetadata: telemetry,
2589
+ piiMaskingEnabled: parentContext.piiMaskingEnabled,
2590
+ secretMaskingEnabled: parentContext.secretMaskingEnabled
2591
+ });
2592
+ }
2593
+ async handleToolEnd(_output, runId) {
2594
+ const id = String(runId ?? "");
2595
+ const state = this.toolRuns.get(id);
2596
+ if (!state) {
2597
+ return;
2598
+ }
2599
+ this.toolRuns.delete(id);
2600
+ await this.logWorkflowOperation(
2601
+ {
2602
+ telemetry: mergeTelemetryContexts(
2603
+ state.telemetryMetadata,
2604
+ createAgentIdTelemetryContext({
2605
+ workflow_step_id: state.workflowStepId,
2606
+ parent_event_id: state.startEventId
2607
+ })
2608
+ ),
2609
+ event_type: "complete",
2610
+ event_status: "completed",
2611
+ latency: Math.max(0, Date.now() - state.startedAtMs)
2612
+ },
2613
+ state
2614
+ );
2615
+ }
2616
+ async handleToolError(err, runId) {
2617
+ const id = String(runId ?? "");
2618
+ const state = this.toolRuns.get(id);
2619
+ if (!state) {
2620
+ return;
2621
+ }
2622
+ this.toolRuns.delete(id);
2623
+ const errorMessage = err instanceof Error ? err.message : typeof err === "undefined" ? "" : String(err);
2624
+ await this.logWorkflowOperation(
2625
+ {
2626
+ telemetry: mergeTelemetryContexts(
2627
+ state?.telemetryMetadata,
2628
+ createAgentIdTelemetryContext({
2629
+ workflow_step_id: state?.workflowStepId,
2630
+ parent_event_id: state?.startEventId
2631
+ })
2632
+ ),
2633
+ metadata: errorMessage.trim().length > 0 ? {
2634
+ error_message: errorMessage.trim(),
2635
+ ...err instanceof Error && err.name ? { error_name: err.name } : {}
2636
+ } : void 0,
2637
+ event_type: "error",
2638
+ event_status: "failed",
2639
+ severity: "error",
2640
+ latency: typeof state?.startedAtMs === "number" ? Math.max(0, Date.now() - state.startedAtMs) : void 0
2641
+ },
2642
+ state
2643
+ );
2644
+ }
2645
+ async handleChainStart(serialized, _inputs, runId, parentRunId, ...rest) {
2646
+ const id = String(runId ?? "");
2647
+ const parentContext = this.resolveParentEventContext(parentRunId);
2648
+ const baseTelemetry = extractTelemetryFromValues(...rest);
2649
+ const workflowName = extractWorkflowName(serialized, rest, baseTelemetry);
2650
+ const workflowStepId = firstNonEmptyString(baseTelemetry?.workflow_step_id, baseTelemetry?.workflowStepId) ?? createClientEventId();
2651
+ const resolvedCategory = firstNonEmptyString(baseTelemetry?.event_category, baseTelemetry?.eventCategory) ?? "workflow";
2652
+ const telemetry = mergeTelemetryContexts(
2653
+ this.telemetry,
2654
+ baseTelemetry,
2655
+ createAgentIdTelemetryContext({
2656
+ workflow_step_id: workflowStepId,
2657
+ workflow_step_name: workflowName,
2658
+ parent_event_id: parentContext.parentEventId,
2659
+ event_category: resolvedCategory
2660
+ })
2661
+ );
2662
+ const startedAtMs = Date.now();
2663
+ const payload = await this.logWorkflowOperation(
2664
+ {
2665
+ telemetry,
2666
+ event_type: "start",
2667
+ event_status: "started"
2668
+ },
2669
+ parentContext
2670
+ );
2671
+ this.chainRuns.set(id, {
2672
+ startedAtMs,
2673
+ workflowStepId,
2674
+ startEventId: payload.event_id ?? createClientEventId(),
2675
+ telemetryMetadata: telemetry,
2676
+ piiMaskingEnabled: parentContext.piiMaskingEnabled,
2677
+ secretMaskingEnabled: parentContext.secretMaskingEnabled
2678
+ });
2679
+ }
2680
+ async handleChainEnd(_outputs, runId) {
2681
+ const id = String(runId ?? "");
2682
+ const state = this.chainRuns.get(id);
2683
+ if (!state) {
2684
+ return;
2685
+ }
2686
+ this.chainRuns.delete(id);
2687
+ await this.logWorkflowOperation(
2688
+ {
2689
+ telemetry: mergeTelemetryContexts(
2690
+ state.telemetryMetadata,
2691
+ createAgentIdTelemetryContext({
2692
+ workflow_step_id: state.workflowStepId,
2693
+ parent_event_id: state.startEventId
2694
+ })
2695
+ ),
2696
+ event_type: "complete",
2697
+ event_status: "completed",
2698
+ latency: Math.max(0, Date.now() - state.startedAtMs)
2699
+ },
2700
+ state
2701
+ );
2702
+ }
2703
+ async handleChainError(err, runId) {
2704
+ const id = String(runId ?? "");
2705
+ const state = this.chainRuns.get(id);
2706
+ if (!state) {
2707
+ return;
2708
+ }
2709
+ this.chainRuns.delete(id);
2710
+ const errorMessage = err instanceof Error ? err.message : typeof err === "undefined" ? "" : String(err);
2711
+ await this.logWorkflowOperation(
2712
+ {
2713
+ telemetry: mergeTelemetryContexts(
2714
+ state.telemetryMetadata,
2715
+ createAgentIdTelemetryContext({
2716
+ workflow_step_id: state.workflowStepId,
2717
+ parent_event_id: state.startEventId
2718
+ })
2719
+ ),
2720
+ metadata: errorMessage.trim().length > 0 ? {
2721
+ error_message: errorMessage.trim(),
2722
+ ...err instanceof Error && err.name ? { error_name: err.name } : {}
2723
+ } : void 0,
2724
+ event_type: "error",
2725
+ event_status: "failed",
2726
+ severity: "error",
2727
+ latency: Math.max(0, Date.now() - state.startedAtMs)
2728
+ },
2729
+ state
2730
+ );
2731
+ }
1815
2732
  };
1816
2733
  // Annotate the CommonJS export names for ESM import in node:
1817
2734
  0 && (module.exports = {