agentid-sdk 0.1.40 → 0.1.41

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.
@@ -263,6 +263,7 @@ declare class AgentID {
263
263
  private localEnforcer;
264
264
  private injectionScanner;
265
265
  private recentGuardVerdicts;
266
+ private pendingGuardRequests;
266
267
  constructor(config?: AgentIDConfig);
267
268
  get piiMasking(): boolean | undefined;
268
269
  get secretMasking(): boolean | undefined;
@@ -263,6 +263,7 @@ declare class AgentID {
263
263
  private localEnforcer;
264
264
  private injectionScanner;
265
265
  private recentGuardVerdicts;
266
+ private pendingGuardRequests;
266
267
  constructor(config?: AgentIDConfig);
267
268
  get piiMasking(): boolean | undefined;
268
269
  get secretMasking(): boolean | undefined;
@@ -2290,7 +2290,7 @@ function getInjectionScanner() {
2290
2290
 
2291
2291
  // src/sdk-version.ts
2292
2292
  var FALLBACK_SDK_VERSION = "js-0.0.0-dev";
2293
- var AGENTID_SDK_VERSION_HEADER = "js-0.1.40".trim().length > 0 ? "js-0.1.40" : FALLBACK_SDK_VERSION;
2293
+ var AGENTID_SDK_VERSION_HEADER = "js-0.1.41".trim().length > 0 ? "js-0.1.41" : FALLBACK_SDK_VERSION;
2294
2294
 
2295
2295
  // src/local-security-enforcer.ts
2296
2296
  var DEFAULT_FAIL_OPEN_CONFIG = {
@@ -2708,7 +2708,7 @@ var GUARD_MAX_ATTEMPTS = 3;
2708
2708
  var GUARD_RETRY_DELAYS_MS = [250, 500];
2709
2709
  var INGEST_MAX_ATTEMPTS = 3;
2710
2710
  var INGEST_RETRY_DELAYS_MS = [250, 500];
2711
- var GUARD_VERDICT_CACHE_TTL_MS = 0;
2711
+ var GUARD_VERDICT_CACHE_TTL_MS = 1500;
2712
2712
  var MAX_INGEST_TEXT_CHARS = 32e3;
2713
2713
  var OPENAI_TELEMETRY_FIELD = "agentid_telemetry";
2714
2714
  function normalizeBaseUrl3(baseUrl) {
@@ -3556,6 +3556,7 @@ var AgentID = class {
3556
3556
  constructor(config = {}) {
3557
3557
  this.injectionScanner = getInjectionScanner();
3558
3558
  this.recentGuardVerdicts = /* @__PURE__ */ new Map();
3559
+ this.pendingGuardRequests = /* @__PURE__ */ new Map();
3559
3560
  this.apiKey = resolveConfiguredApiKey(config.apiKey);
3560
3561
  this.baseUrl = normalizeBaseUrl3(config.baseUrl ?? "https://app.getagentid.com/api/v1");
3561
3562
  this.configuredPiiMasking = typeof config.piiMasking === "boolean" ? config.piiMasking : null;
@@ -3646,13 +3647,14 @@ var AgentID = class {
3646
3647
  }
3647
3648
  return createEventId2();
3648
3649
  }
3649
- buildGuardCacheKey(params) {
3650
+ buildGuardCacheKey(params, apiKey) {
3650
3651
  if (!params.system_id || !params.input) {
3651
3652
  return null;
3652
3653
  }
3653
3654
  const userId = params.user_id?.trim() ?? "";
3654
- const normalizedInput = params.input.slice(0, 2048);
3655
- return `${params.system_id}|${userId}|${normalizedInput.length}|${normalizedInput}`;
3655
+ const normalizedInput = params.input.trim().replace(/\s+/g, " ").slice(0, 2048);
3656
+ const keyPrefix = apiKey?.slice(0, 24) ?? "";
3657
+ return `${keyPrefix}|${params.system_id}|${userId}|${normalizedInput.length}|${normalizedInput}`;
3656
3658
  }
3657
3659
  readCachedGuardVerdict(cacheKey) {
3658
3660
  if (!cacheKey) return null;
@@ -3665,7 +3667,7 @@ var AgentID = class {
3665
3667
  return cached.verdict;
3666
3668
  }
3667
3669
  cacheGuardVerdict(cacheKey, verdict) {
3668
- if (!cacheKey || !verdict.allowed || GUARD_VERDICT_CACHE_TTL_MS <= 0) {
3670
+ if (!cacheKey || GUARD_VERDICT_CACHE_TTL_MS <= 0) {
3669
3671
  return;
3670
3672
  }
3671
3673
  this.recentGuardVerdicts.set(cacheKey, {
@@ -4163,98 +4165,122 @@ var AgentID = class {
4163
4165
  ...params,
4164
4166
  client_capabilities: params.client_capabilities ?? this.buildClientCapabilities()
4165
4167
  };
4166
- const guardCacheKey = this.buildGuardCacheKey(payload);
4168
+ const guardCacheKey = this.buildGuardCacheKey(payload, effectiveApiKey);
4167
4169
  const cachedVerdict = this.readCachedGuardVerdict(guardCacheKey);
4168
4170
  if (cachedVerdict) {
4169
4171
  return withGuardLatency(cachedVerdict);
4170
4172
  }
4171
- const correlationId = createCorrelationId(payload.client_event_id);
4172
- let lastStatusCode = null;
4173
- let lastAbort = false;
4174
- let lastError = null;
4175
- for (let attempt = 0; attempt < GUARD_MAX_ATTEMPTS; attempt += 1) {
4176
- const controller = new AbortController();
4177
- const timeoutId = setTimeout(() => controller.abort(), this.guardTimeoutMs);
4178
- try {
4179
- const res = await fetch(`${this.baseUrl}/guard`, {
4180
- method: "POST",
4181
- headers: {
4182
- "Content-Type": "application/json",
4183
- "x-agentid-api-key": effectiveApiKey,
4184
- "X-AgentID-SDK-Version": AGENTID_SDK_VERSION_HEADER,
4185
- "x-correlation-id": correlationId
4186
- },
4187
- body: JSON.stringify(payload),
4188
- signal: controller.signal
4189
- });
4190
- lastStatusCode = res.status;
4191
- const responseBody = await safeReadJson2(res);
4192
- if (responseBody && typeof responseBody.allowed === "boolean") {
4193
- const rawVerdict = responseBody;
4194
- const transparency = coerceTransparencyMetadata(rawVerdict.transparency);
4195
- const verdict = {
4196
- ...rawVerdict,
4197
- ...transparency ? { transparency } : {}
4198
- };
4199
- const infrastructureFailure = verdict.allowed === false && (isInfrastructureGuardReason(verdict.reason) || !verdict.reason && res.status >= 500);
4200
- if (infrastructureFailure) {
4201
- if (attempt < GUARD_MAX_ATTEMPTS - 1) {
4202
- await waitForRetry(attempt);
4203
- continue;
4204
- }
4205
- if (effectiveStrictMode) {
4173
+ const pendingGuardRequest = guardCacheKey ? this.pendingGuardRequests.get(guardCacheKey) : void 0;
4174
+ if (pendingGuardRequest) {
4175
+ return withGuardLatency(await pendingGuardRequest.promise);
4176
+ }
4177
+ const executeGuardRequest = async () => {
4178
+ const correlationId = createCorrelationId(payload.client_event_id);
4179
+ let lastStatusCode = null;
4180
+ let lastAbort = false;
4181
+ let lastError = null;
4182
+ for (let attempt = 0; attempt < GUARD_MAX_ATTEMPTS; attempt += 1) {
4183
+ const controller = new AbortController();
4184
+ const timeoutId = setTimeout(() => controller.abort(), this.guardTimeoutMs);
4185
+ try {
4186
+ const res = await fetch(`${this.baseUrl}/guard`, {
4187
+ method: "POST",
4188
+ headers: {
4189
+ "Content-Type": "application/json",
4190
+ "x-agentid-api-key": effectiveApiKey,
4191
+ "X-AgentID-SDK-Version": AGENTID_SDK_VERSION_HEADER,
4192
+ "x-correlation-id": correlationId
4193
+ },
4194
+ body: JSON.stringify(payload),
4195
+ signal: controller.signal
4196
+ });
4197
+ lastStatusCode = res.status;
4198
+ const responseBody = await safeReadJson2(res);
4199
+ if (responseBody && typeof responseBody.allowed === "boolean") {
4200
+ const rawVerdict = responseBody;
4201
+ const transparency = coerceTransparencyMetadata(rawVerdict.transparency);
4202
+ const verdict = {
4203
+ ...rawVerdict,
4204
+ ...transparency ? { transparency } : {}
4205
+ };
4206
+ const infrastructureFailure = verdict.allowed === false && (isInfrastructureGuardReason(verdict.reason) || !verdict.reason && res.status >= 500);
4207
+ if (infrastructureFailure) {
4208
+ if (attempt < GUARD_MAX_ATTEMPTS - 1) {
4209
+ await waitForRetry(attempt);
4210
+ continue;
4211
+ }
4212
+ if (effectiveStrictMode) {
4213
+ console.warn(
4214
+ `[AgentID] Guard API infrastructure failure in strict mode (${verdict.reason ?? `http_${res.status}`}). Blocking request.`
4215
+ );
4216
+ return withGuardLatency({
4217
+ allowed: false,
4218
+ reason: verdict.reason ?? "network_error_strict_mode"
4219
+ });
4220
+ }
4206
4221
  console.warn(
4207
- `[AgentID] Guard API infrastructure failure in strict mode (${verdict.reason ?? `http_${res.status}`}). Blocking request.`
4222
+ `[AgentID] Guard API infrastructure fallback in fail-open mode (${verdict.reason ?? `http_${res.status}`}).`
4208
4223
  );
4209
- return withGuardLatency({
4210
- allowed: false,
4211
- reason: verdict.reason ?? "network_error_strict_mode"
4224
+ this.logGuardFallback({
4225
+ reason: verdict.reason ?? `http_${res.status}`,
4226
+ status: "upstream_error",
4227
+ guardParams: params,
4228
+ apiKey: effectiveApiKey
4212
4229
  });
4230
+ return withGuardLatency(
4231
+ this.buildFailOpenGuardVerdict(
4232
+ "system_failure_fail_open",
4233
+ params.input,
4234
+ { apiKey: effectiveApiKey }
4235
+ )
4236
+ );
4213
4237
  }
4214
- console.warn(
4215
- `[AgentID] Guard API infrastructure fallback in fail-open mode (${verdict.reason ?? `http_${res.status}`}).`
4216
- );
4238
+ this.cacheGuardVerdict(guardCacheKey, verdict);
4239
+ return withGuardLatency(verdict);
4240
+ }
4241
+ if (!res.ok) {
4242
+ if (res.status >= 500 && attempt < GUARD_MAX_ATTEMPTS - 1) {
4243
+ await waitForRetry(attempt);
4244
+ continue;
4245
+ }
4246
+ throw new Error(`API Error ${res.status}`);
4247
+ }
4248
+ throw new Error("Invalid guard response");
4249
+ } catch (error) {
4250
+ lastError = error;
4251
+ const isAbortError2 = Boolean(
4252
+ error && typeof error === "object" && error.name === "AbortError"
4253
+ );
4254
+ lastAbort = isAbortError2;
4255
+ if (attempt < GUARD_MAX_ATTEMPTS - 1) {
4256
+ await waitForRetry(attempt);
4257
+ continue;
4258
+ }
4259
+ if (isAbortError2) {
4260
+ const timeoutMessage = "AgentID API Warning: Connection timeout exceeded.";
4261
+ console.warn(timeoutMessage);
4217
4262
  this.logGuardFallback({
4218
- reason: verdict.reason ?? `http_${res.status}`,
4219
- status: "upstream_error",
4263
+ reason: "timeout_fallback",
4264
+ status: "latency_timeout",
4220
4265
  guardParams: params,
4221
4266
  apiKey: effectiveApiKey
4222
4267
  });
4268
+ if (effectiveStrictMode) {
4269
+ return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4270
+ }
4223
4271
  return withGuardLatency(
4224
- this.buildFailOpenGuardVerdict(
4225
- "system_failure_fail_open",
4226
- params.input,
4227
- { apiKey: effectiveApiKey }
4228
- )
4272
+ this.buildFailOpenGuardVerdict("timeout_fallback", params.input, {
4273
+ apiKey: effectiveApiKey
4274
+ })
4229
4275
  );
4230
4276
  }
4231
- this.cacheGuardVerdict(guardCacheKey, verdict);
4232
- return withGuardLatency(verdict);
4233
- }
4234
- if (!res.ok) {
4235
- if (res.status >= 500 && attempt < GUARD_MAX_ATTEMPTS - 1) {
4236
- await waitForRetry(attempt);
4237
- continue;
4238
- }
4239
- throw new Error(`API Error ${res.status}`);
4240
- }
4241
- throw new Error("Invalid guard response");
4242
- } catch (error) {
4243
- lastError = error;
4244
- const isAbortError2 = Boolean(
4245
- error && typeof error === "object" && error.name === "AbortError"
4246
- );
4247
- lastAbort = isAbortError2;
4248
- if (attempt < GUARD_MAX_ATTEMPTS - 1) {
4249
- await waitForRetry(attempt);
4250
- continue;
4251
- }
4252
- if (isAbortError2) {
4253
- const timeoutMessage = "AgentID API Warning: Connection timeout exceeded.";
4254
- console.warn(timeoutMessage);
4277
+ console.warn(
4278
+ effectiveStrictMode ? "[AgentID] Guard check failed (Strict mode active):" : "[AgentID] Guard check failed (Fail-Open active):",
4279
+ error
4280
+ );
4255
4281
  this.logGuardFallback({
4256
- reason: "timeout_fallback",
4257
- status: "latency_timeout",
4282
+ reason: "guard_unreachable",
4283
+ status: "guard_unreachable",
4258
4284
  guardParams: params,
4259
4285
  apiKey: effectiveApiKey
4260
4286
  });
@@ -4262,67 +4288,62 @@ var AgentID = class {
4262
4288
  return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4263
4289
  }
4264
4290
  return withGuardLatency(
4265
- this.buildFailOpenGuardVerdict("timeout_fallback", params.input, {
4291
+ this.buildFailOpenGuardVerdict("guard_unreachable", params.input, {
4266
4292
  apiKey: effectiveApiKey
4267
4293
  })
4268
4294
  );
4295
+ } finally {
4296
+ clearTimeout(timeoutId);
4269
4297
  }
4270
- console.warn(
4271
- effectiveStrictMode ? "[AgentID] Guard check failed (Strict mode active):" : "[AgentID] Guard check failed (Fail-Open active):",
4272
- error
4273
- );
4274
- this.logGuardFallback({
4275
- reason: "guard_unreachable",
4276
- status: "guard_unreachable",
4277
- guardParams: params,
4278
- apiKey: effectiveApiKey
4279
- });
4298
+ }
4299
+ if (lastAbort) {
4280
4300
  if (effectiveStrictMode) {
4281
4301
  return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4282
4302
  }
4283
4303
  return withGuardLatency(
4284
- this.buildFailOpenGuardVerdict("guard_unreachable", params.input, {
4304
+ this.buildFailOpenGuardVerdict("timeout_fallback", params.input, {
4285
4305
  apiKey: effectiveApiKey
4286
4306
  })
4287
4307
  );
4288
- } finally {
4289
- clearTimeout(timeoutId);
4290
4308
  }
4291
- }
4292
- if (lastAbort) {
4309
+ if (typeof lastStatusCode === "number" && lastStatusCode >= 500) {
4310
+ if (effectiveStrictMode) {
4311
+ return withGuardLatency({ allowed: false, reason: "server_error" });
4312
+ }
4313
+ return withGuardLatency(
4314
+ this.buildFailOpenGuardVerdict(
4315
+ "system_failure_fail_open",
4316
+ params.input,
4317
+ { apiKey: effectiveApiKey }
4318
+ )
4319
+ );
4320
+ }
4321
+ console.warn(
4322
+ effectiveStrictMode ? "[AgentID] Guard check failed (Strict mode active):" : "[AgentID] Guard check failed (Fail-Open active):",
4323
+ lastError
4324
+ );
4293
4325
  if (effectiveStrictMode) {
4294
4326
  return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4295
4327
  }
4296
4328
  return withGuardLatency(
4297
- this.buildFailOpenGuardVerdict("timeout_fallback", params.input, {
4329
+ this.buildFailOpenGuardVerdict("guard_unreachable", params.input, {
4298
4330
  apiKey: effectiveApiKey
4299
4331
  })
4300
4332
  );
4333
+ };
4334
+ if (!guardCacheKey) {
4335
+ return executeGuardRequest();
4301
4336
  }
4302
- if (typeof lastStatusCode === "number" && lastStatusCode >= 500) {
4303
- if (effectiveStrictMode) {
4304
- return withGuardLatency({ allowed: false, reason: "server_error" });
4337
+ const promise = executeGuardRequest();
4338
+ this.pendingGuardRequests.set(guardCacheKey, { promise });
4339
+ try {
4340
+ return await promise;
4341
+ } finally {
4342
+ const pending = this.pendingGuardRequests.get(guardCacheKey);
4343
+ if (pending?.promise === promise) {
4344
+ this.pendingGuardRequests.delete(guardCacheKey);
4305
4345
  }
4306
- return withGuardLatency(
4307
- this.buildFailOpenGuardVerdict(
4308
- "system_failure_fail_open",
4309
- params.input,
4310
- { apiKey: effectiveApiKey }
4311
- )
4312
- );
4313
4346
  }
4314
- console.warn(
4315
- effectiveStrictMode ? "[AgentID] Guard check failed (Strict mode active):" : "[AgentID] Guard check failed (Fail-Open active):",
4316
- lastError
4317
- );
4318
- if (effectiveStrictMode) {
4319
- return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4320
- }
4321
- return withGuardLatency(
4322
- this.buildFailOpenGuardVerdict("guard_unreachable", params.input, {
4323
- apiKey: effectiveApiKey
4324
- })
4325
- );
4326
4347
  }
4327
4348
  async sendIngest(params, options, internal) {
4328
4349
  const ingestStartedAt = Date.now();
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { P as PIIAnonymizeOptions, a as PIIManager } from './agentid-BWlN5KCq.mjs';
2
- export { A as AgentEventType, b as AgentID, c as AgentIDWorkflowRunHooks, d as AgentIDWorkflowStep, e as AgentIDWorkflowStepParams, f as AgentIDWorkflowTrail, g as AgentIDWorkflowTrailOptions, h as AgentOperationCategory, i as AgentOperationStatus, j as AgentTelemetryContext, D as DependencyError, G as GuardAttachment, k as GuardParams, l as GuardResponse, L as LogParams, O as OperationLogParams, m as PIIMapping, n as PreparedInput, R as RequestOptions, S as SecurityBlockError, T as TransparencyMetadata, W as WrapOpenAIOptions, o as createAgentIdCorrelationId, p as createAgentIdOperationLog, q as createAgentIdTelemetryContext, r as createAgentIdWorkflowTrail } from './agentid-BWlN5KCq.mjs';
1
+ import { P as PIIAnonymizeOptions, a as PIIManager } from './agentid-Mjh8rXn0.mjs';
2
+ export { A as AgentEventType, b as AgentID, c as AgentIDWorkflowRunHooks, d as AgentIDWorkflowStep, e as AgentIDWorkflowStepParams, f as AgentIDWorkflowTrail, g as AgentIDWorkflowTrailOptions, h as AgentOperationCategory, i as AgentOperationStatus, j as AgentTelemetryContext, D as DependencyError, G as GuardAttachment, k as GuardParams, l as GuardResponse, L as LogParams, O as OperationLogParams, m as PIIMapping, n as PreparedInput, R as RequestOptions, S as SecurityBlockError, T as TransparencyMetadata, W as WrapOpenAIOptions, o as createAgentIdCorrelationId, p as createAgentIdOperationLog, q as createAgentIdTelemetryContext, r as createAgentIdWorkflowTrail } from './agentid-Mjh8rXn0.mjs';
3
3
 
4
4
  type TokenUsage = Record<string, unknown>;
5
5
  type ExtractedGuardAttachment = {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { P as PIIAnonymizeOptions, a as PIIManager } from './agentid-BWlN5KCq.js';
2
- export { A as AgentEventType, b as AgentID, c as AgentIDWorkflowRunHooks, d as AgentIDWorkflowStep, e as AgentIDWorkflowStepParams, f as AgentIDWorkflowTrail, g as AgentIDWorkflowTrailOptions, h as AgentOperationCategory, i as AgentOperationStatus, j as AgentTelemetryContext, D as DependencyError, G as GuardAttachment, k as GuardParams, l as GuardResponse, L as LogParams, O as OperationLogParams, m as PIIMapping, n as PreparedInput, R as RequestOptions, S as SecurityBlockError, T as TransparencyMetadata, W as WrapOpenAIOptions, o as createAgentIdCorrelationId, p as createAgentIdOperationLog, q as createAgentIdTelemetryContext, r as createAgentIdWorkflowTrail } from './agentid-BWlN5KCq.js';
1
+ import { P as PIIAnonymizeOptions, a as PIIManager } from './agentid-Mjh8rXn0.js';
2
+ export { A as AgentEventType, b as AgentID, c as AgentIDWorkflowRunHooks, d as AgentIDWorkflowStep, e as AgentIDWorkflowStepParams, f as AgentIDWorkflowTrail, g as AgentIDWorkflowTrailOptions, h as AgentOperationCategory, i as AgentOperationStatus, j as AgentTelemetryContext, D as DependencyError, G as GuardAttachment, k as GuardParams, l as GuardResponse, L as LogParams, O as OperationLogParams, m as PIIMapping, n as PreparedInput, R as RequestOptions, S as SecurityBlockError, T as TransparencyMetadata, W as WrapOpenAIOptions, o as createAgentIdCorrelationId, p as createAgentIdOperationLog, q as createAgentIdTelemetryContext, r as createAgentIdWorkflowTrail } from './agentid-Mjh8rXn0.js';
3
3
 
4
4
  type TokenUsage = Record<string, unknown>;
5
5
  type ExtractedGuardAttachment = {
package/dist/index.js CHANGED
@@ -182,7 +182,7 @@ var OpenAIAdapter = class {
182
182
 
183
183
  // src/sdk-version.ts
184
184
  var FALLBACK_SDK_VERSION = "js-0.0.0-dev";
185
- var AGENTID_SDK_VERSION_HEADER = "js-0.1.40".trim().length > 0 ? "js-0.1.40" : FALLBACK_SDK_VERSION;
185
+ var AGENTID_SDK_VERSION_HEADER = "js-0.1.41".trim().length > 0 ? "js-0.1.41" : FALLBACK_SDK_VERSION;
186
186
 
187
187
  // src/pii-national-identifiers.ts
188
188
  var MAX_CANDIDATES_PER_RULE = 256;
@@ -2748,7 +2748,7 @@ var GUARD_MAX_ATTEMPTS = 3;
2748
2748
  var GUARD_RETRY_DELAYS_MS = [250, 500];
2749
2749
  var INGEST_MAX_ATTEMPTS = 3;
2750
2750
  var INGEST_RETRY_DELAYS_MS = [250, 500];
2751
- var GUARD_VERDICT_CACHE_TTL_MS = 0;
2751
+ var GUARD_VERDICT_CACHE_TTL_MS = 1500;
2752
2752
  var MAX_INGEST_TEXT_CHARS = 32e3;
2753
2753
  var OPENAI_TELEMETRY_FIELD = "agentid_telemetry";
2754
2754
  function normalizeBaseUrl3(baseUrl) {
@@ -3596,6 +3596,7 @@ var AgentID = class {
3596
3596
  constructor(config = {}) {
3597
3597
  this.injectionScanner = getInjectionScanner();
3598
3598
  this.recentGuardVerdicts = /* @__PURE__ */ new Map();
3599
+ this.pendingGuardRequests = /* @__PURE__ */ new Map();
3599
3600
  this.apiKey = resolveConfiguredApiKey(config.apiKey);
3600
3601
  this.baseUrl = normalizeBaseUrl3(config.baseUrl ?? "https://app.getagentid.com/api/v1");
3601
3602
  this.configuredPiiMasking = typeof config.piiMasking === "boolean" ? config.piiMasking : null;
@@ -3686,13 +3687,14 @@ var AgentID = class {
3686
3687
  }
3687
3688
  return createEventId2();
3688
3689
  }
3689
- buildGuardCacheKey(params) {
3690
+ buildGuardCacheKey(params, apiKey) {
3690
3691
  if (!params.system_id || !params.input) {
3691
3692
  return null;
3692
3693
  }
3693
3694
  const userId = params.user_id?.trim() ?? "";
3694
- const normalizedInput = params.input.slice(0, 2048);
3695
- return `${params.system_id}|${userId}|${normalizedInput.length}|${normalizedInput}`;
3695
+ const normalizedInput = params.input.trim().replace(/\s+/g, " ").slice(0, 2048);
3696
+ const keyPrefix = apiKey?.slice(0, 24) ?? "";
3697
+ return `${keyPrefix}|${params.system_id}|${userId}|${normalizedInput.length}|${normalizedInput}`;
3696
3698
  }
3697
3699
  readCachedGuardVerdict(cacheKey) {
3698
3700
  if (!cacheKey) return null;
@@ -3705,7 +3707,7 @@ var AgentID = class {
3705
3707
  return cached.verdict;
3706
3708
  }
3707
3709
  cacheGuardVerdict(cacheKey, verdict) {
3708
- if (!cacheKey || !verdict.allowed || GUARD_VERDICT_CACHE_TTL_MS <= 0) {
3710
+ if (!cacheKey || GUARD_VERDICT_CACHE_TTL_MS <= 0) {
3709
3711
  return;
3710
3712
  }
3711
3713
  this.recentGuardVerdicts.set(cacheKey, {
@@ -4203,98 +4205,122 @@ var AgentID = class {
4203
4205
  ...params,
4204
4206
  client_capabilities: params.client_capabilities ?? this.buildClientCapabilities()
4205
4207
  };
4206
- const guardCacheKey = this.buildGuardCacheKey(payload);
4208
+ const guardCacheKey = this.buildGuardCacheKey(payload, effectiveApiKey);
4207
4209
  const cachedVerdict = this.readCachedGuardVerdict(guardCacheKey);
4208
4210
  if (cachedVerdict) {
4209
4211
  return withGuardLatency(cachedVerdict);
4210
4212
  }
4211
- const correlationId = createCorrelationId(payload.client_event_id);
4212
- let lastStatusCode = null;
4213
- let lastAbort = false;
4214
- let lastError = null;
4215
- for (let attempt = 0; attempt < GUARD_MAX_ATTEMPTS; attempt += 1) {
4216
- const controller = new AbortController();
4217
- const timeoutId = setTimeout(() => controller.abort(), this.guardTimeoutMs);
4218
- try {
4219
- const res = await fetch(`${this.baseUrl}/guard`, {
4220
- method: "POST",
4221
- headers: {
4222
- "Content-Type": "application/json",
4223
- "x-agentid-api-key": effectiveApiKey,
4224
- "X-AgentID-SDK-Version": AGENTID_SDK_VERSION_HEADER,
4225
- "x-correlation-id": correlationId
4226
- },
4227
- body: JSON.stringify(payload),
4228
- signal: controller.signal
4229
- });
4230
- lastStatusCode = res.status;
4231
- const responseBody = await safeReadJson2(res);
4232
- if (responseBody && typeof responseBody.allowed === "boolean") {
4233
- const rawVerdict = responseBody;
4234
- const transparency = coerceTransparencyMetadata(rawVerdict.transparency);
4235
- const verdict = {
4236
- ...rawVerdict,
4237
- ...transparency ? { transparency } : {}
4238
- };
4239
- const infrastructureFailure = verdict.allowed === false && (isInfrastructureGuardReason(verdict.reason) || !verdict.reason && res.status >= 500);
4240
- if (infrastructureFailure) {
4241
- if (attempt < GUARD_MAX_ATTEMPTS - 1) {
4242
- await waitForRetry(attempt);
4243
- continue;
4244
- }
4245
- if (effectiveStrictMode) {
4213
+ const pendingGuardRequest = guardCacheKey ? this.pendingGuardRequests.get(guardCacheKey) : void 0;
4214
+ if (pendingGuardRequest) {
4215
+ return withGuardLatency(await pendingGuardRequest.promise);
4216
+ }
4217
+ const executeGuardRequest = async () => {
4218
+ const correlationId = createCorrelationId(payload.client_event_id);
4219
+ let lastStatusCode = null;
4220
+ let lastAbort = false;
4221
+ let lastError = null;
4222
+ for (let attempt = 0; attempt < GUARD_MAX_ATTEMPTS; attempt += 1) {
4223
+ const controller = new AbortController();
4224
+ const timeoutId = setTimeout(() => controller.abort(), this.guardTimeoutMs);
4225
+ try {
4226
+ const res = await fetch(`${this.baseUrl}/guard`, {
4227
+ method: "POST",
4228
+ headers: {
4229
+ "Content-Type": "application/json",
4230
+ "x-agentid-api-key": effectiveApiKey,
4231
+ "X-AgentID-SDK-Version": AGENTID_SDK_VERSION_HEADER,
4232
+ "x-correlation-id": correlationId
4233
+ },
4234
+ body: JSON.stringify(payload),
4235
+ signal: controller.signal
4236
+ });
4237
+ lastStatusCode = res.status;
4238
+ const responseBody = await safeReadJson2(res);
4239
+ if (responseBody && typeof responseBody.allowed === "boolean") {
4240
+ const rawVerdict = responseBody;
4241
+ const transparency = coerceTransparencyMetadata(rawVerdict.transparency);
4242
+ const verdict = {
4243
+ ...rawVerdict,
4244
+ ...transparency ? { transparency } : {}
4245
+ };
4246
+ const infrastructureFailure = verdict.allowed === false && (isInfrastructureGuardReason(verdict.reason) || !verdict.reason && res.status >= 500);
4247
+ if (infrastructureFailure) {
4248
+ if (attempt < GUARD_MAX_ATTEMPTS - 1) {
4249
+ await waitForRetry(attempt);
4250
+ continue;
4251
+ }
4252
+ if (effectiveStrictMode) {
4253
+ console.warn(
4254
+ `[AgentID] Guard API infrastructure failure in strict mode (${verdict.reason ?? `http_${res.status}`}). Blocking request.`
4255
+ );
4256
+ return withGuardLatency({
4257
+ allowed: false,
4258
+ reason: verdict.reason ?? "network_error_strict_mode"
4259
+ });
4260
+ }
4246
4261
  console.warn(
4247
- `[AgentID] Guard API infrastructure failure in strict mode (${verdict.reason ?? `http_${res.status}`}). Blocking request.`
4262
+ `[AgentID] Guard API infrastructure fallback in fail-open mode (${verdict.reason ?? `http_${res.status}`}).`
4248
4263
  );
4249
- return withGuardLatency({
4250
- allowed: false,
4251
- reason: verdict.reason ?? "network_error_strict_mode"
4264
+ this.logGuardFallback({
4265
+ reason: verdict.reason ?? `http_${res.status}`,
4266
+ status: "upstream_error",
4267
+ guardParams: params,
4268
+ apiKey: effectiveApiKey
4252
4269
  });
4270
+ return withGuardLatency(
4271
+ this.buildFailOpenGuardVerdict(
4272
+ "system_failure_fail_open",
4273
+ params.input,
4274
+ { apiKey: effectiveApiKey }
4275
+ )
4276
+ );
4253
4277
  }
4254
- console.warn(
4255
- `[AgentID] Guard API infrastructure fallback in fail-open mode (${verdict.reason ?? `http_${res.status}`}).`
4256
- );
4278
+ this.cacheGuardVerdict(guardCacheKey, verdict);
4279
+ return withGuardLatency(verdict);
4280
+ }
4281
+ if (!res.ok) {
4282
+ if (res.status >= 500 && attempt < GUARD_MAX_ATTEMPTS - 1) {
4283
+ await waitForRetry(attempt);
4284
+ continue;
4285
+ }
4286
+ throw new Error(`API Error ${res.status}`);
4287
+ }
4288
+ throw new Error("Invalid guard response");
4289
+ } catch (error) {
4290
+ lastError = error;
4291
+ const isAbortError2 = Boolean(
4292
+ error && typeof error === "object" && error.name === "AbortError"
4293
+ );
4294
+ lastAbort = isAbortError2;
4295
+ if (attempt < GUARD_MAX_ATTEMPTS - 1) {
4296
+ await waitForRetry(attempt);
4297
+ continue;
4298
+ }
4299
+ if (isAbortError2) {
4300
+ const timeoutMessage = "AgentID API Warning: Connection timeout exceeded.";
4301
+ console.warn(timeoutMessage);
4257
4302
  this.logGuardFallback({
4258
- reason: verdict.reason ?? `http_${res.status}`,
4259
- status: "upstream_error",
4303
+ reason: "timeout_fallback",
4304
+ status: "latency_timeout",
4260
4305
  guardParams: params,
4261
4306
  apiKey: effectiveApiKey
4262
4307
  });
4308
+ if (effectiveStrictMode) {
4309
+ return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4310
+ }
4263
4311
  return withGuardLatency(
4264
- this.buildFailOpenGuardVerdict(
4265
- "system_failure_fail_open",
4266
- params.input,
4267
- { apiKey: effectiveApiKey }
4268
- )
4312
+ this.buildFailOpenGuardVerdict("timeout_fallback", params.input, {
4313
+ apiKey: effectiveApiKey
4314
+ })
4269
4315
  );
4270
4316
  }
4271
- this.cacheGuardVerdict(guardCacheKey, verdict);
4272
- return withGuardLatency(verdict);
4273
- }
4274
- if (!res.ok) {
4275
- if (res.status >= 500 && attempt < GUARD_MAX_ATTEMPTS - 1) {
4276
- await waitForRetry(attempt);
4277
- continue;
4278
- }
4279
- throw new Error(`API Error ${res.status}`);
4280
- }
4281
- throw new Error("Invalid guard response");
4282
- } catch (error) {
4283
- lastError = error;
4284
- const isAbortError2 = Boolean(
4285
- error && typeof error === "object" && error.name === "AbortError"
4286
- );
4287
- lastAbort = isAbortError2;
4288
- if (attempt < GUARD_MAX_ATTEMPTS - 1) {
4289
- await waitForRetry(attempt);
4290
- continue;
4291
- }
4292
- if (isAbortError2) {
4293
- const timeoutMessage = "AgentID API Warning: Connection timeout exceeded.";
4294
- console.warn(timeoutMessage);
4317
+ console.warn(
4318
+ effectiveStrictMode ? "[AgentID] Guard check failed (Strict mode active):" : "[AgentID] Guard check failed (Fail-Open active):",
4319
+ error
4320
+ );
4295
4321
  this.logGuardFallback({
4296
- reason: "timeout_fallback",
4297
- status: "latency_timeout",
4322
+ reason: "guard_unreachable",
4323
+ status: "guard_unreachable",
4298
4324
  guardParams: params,
4299
4325
  apiKey: effectiveApiKey
4300
4326
  });
@@ -4302,67 +4328,62 @@ var AgentID = class {
4302
4328
  return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4303
4329
  }
4304
4330
  return withGuardLatency(
4305
- this.buildFailOpenGuardVerdict("timeout_fallback", params.input, {
4331
+ this.buildFailOpenGuardVerdict("guard_unreachable", params.input, {
4306
4332
  apiKey: effectiveApiKey
4307
4333
  })
4308
4334
  );
4335
+ } finally {
4336
+ clearTimeout(timeoutId);
4309
4337
  }
4310
- console.warn(
4311
- effectiveStrictMode ? "[AgentID] Guard check failed (Strict mode active):" : "[AgentID] Guard check failed (Fail-Open active):",
4312
- error
4313
- );
4314
- this.logGuardFallback({
4315
- reason: "guard_unreachable",
4316
- status: "guard_unreachable",
4317
- guardParams: params,
4318
- apiKey: effectiveApiKey
4319
- });
4338
+ }
4339
+ if (lastAbort) {
4320
4340
  if (effectiveStrictMode) {
4321
4341
  return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4322
4342
  }
4323
4343
  return withGuardLatency(
4324
- this.buildFailOpenGuardVerdict("guard_unreachable", params.input, {
4344
+ this.buildFailOpenGuardVerdict("timeout_fallback", params.input, {
4325
4345
  apiKey: effectiveApiKey
4326
4346
  })
4327
4347
  );
4328
- } finally {
4329
- clearTimeout(timeoutId);
4330
4348
  }
4331
- }
4332
- if (lastAbort) {
4349
+ if (typeof lastStatusCode === "number" && lastStatusCode >= 500) {
4350
+ if (effectiveStrictMode) {
4351
+ return withGuardLatency({ allowed: false, reason: "server_error" });
4352
+ }
4353
+ return withGuardLatency(
4354
+ this.buildFailOpenGuardVerdict(
4355
+ "system_failure_fail_open",
4356
+ params.input,
4357
+ { apiKey: effectiveApiKey }
4358
+ )
4359
+ );
4360
+ }
4361
+ console.warn(
4362
+ effectiveStrictMode ? "[AgentID] Guard check failed (Strict mode active):" : "[AgentID] Guard check failed (Fail-Open active):",
4363
+ lastError
4364
+ );
4333
4365
  if (effectiveStrictMode) {
4334
4366
  return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4335
4367
  }
4336
4368
  return withGuardLatency(
4337
- this.buildFailOpenGuardVerdict("timeout_fallback", params.input, {
4369
+ this.buildFailOpenGuardVerdict("guard_unreachable", params.input, {
4338
4370
  apiKey: effectiveApiKey
4339
4371
  })
4340
4372
  );
4373
+ };
4374
+ if (!guardCacheKey) {
4375
+ return executeGuardRequest();
4341
4376
  }
4342
- if (typeof lastStatusCode === "number" && lastStatusCode >= 500) {
4343
- if (effectiveStrictMode) {
4344
- return withGuardLatency({ allowed: false, reason: "server_error" });
4377
+ const promise = executeGuardRequest();
4378
+ this.pendingGuardRequests.set(guardCacheKey, { promise });
4379
+ try {
4380
+ return await promise;
4381
+ } finally {
4382
+ const pending = this.pendingGuardRequests.get(guardCacheKey);
4383
+ if (pending?.promise === promise) {
4384
+ this.pendingGuardRequests.delete(guardCacheKey);
4345
4385
  }
4346
- return withGuardLatency(
4347
- this.buildFailOpenGuardVerdict(
4348
- "system_failure_fail_open",
4349
- params.input,
4350
- { apiKey: effectiveApiKey }
4351
- )
4352
- );
4353
4386
  }
4354
- console.warn(
4355
- effectiveStrictMode ? "[AgentID] Guard check failed (Strict mode active):" : "[AgentID] Guard check failed (Fail-Open active):",
4356
- lastError
4357
- );
4358
- if (effectiveStrictMode) {
4359
- return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4360
- }
4361
- return withGuardLatency(
4362
- this.buildFailOpenGuardVerdict("guard_unreachable", params.input, {
4363
- apiKey: effectiveApiKey
4364
- })
4365
- );
4366
4387
  }
4367
4388
  async sendIngest(params, options, internal) {
4368
4389
  const ingestStartedAt = Date.now();
package/dist/index.mjs CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  createAgentIdWorkflowTrail,
14
14
  getInjectionScanner,
15
15
  scanWithRegex
16
- } from "./chunk-25SZBEYX.mjs";
16
+ } from "./chunk-L2WVWRAC.mjs";
17
17
 
18
18
  // src/message-history.ts
19
19
  function isPlainRecord(value) {
@@ -1,5 +1,5 @@
1
1
  import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
2
- import { b as AgentID, j as AgentTelemetryContext } from './agentid-BWlN5KCq.mjs';
2
+ import { b as AgentID, j as AgentTelemetryContext } from './agentid-Mjh8rXn0.mjs';
3
3
 
4
4
  /**
5
5
  * LangChainJS callback handler (dependency-free shape).
@@ -1,5 +1,5 @@
1
1
  import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
2
- import { b as AgentID, j as AgentTelemetryContext } from './agentid-BWlN5KCq.js';
2
+ import { b as AgentID, j as AgentTelemetryContext } from './agentid-Mjh8rXn0.js';
3
3
 
4
4
  /**
5
5
  * LangChainJS callback handler (dependency-free shape).
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.40".trim().length > 0 ? "js-0.1.40" : FALLBACK_SDK_VERSION;
30
+ var AGENTID_SDK_VERSION_HEADER = "js-0.1.41".trim().length > 0 ? "js-0.1.41" : FALLBACK_SDK_VERSION;
31
31
 
32
32
  // src/pii-national-identifiers.ts
33
33
  var MAX_CANDIDATES_PER_RULE = 256;
@@ -2,7 +2,7 @@ import {
2
2
  PIIManager,
3
3
  SecurityBlockError,
4
4
  createAgentIdTelemetryContext
5
- } from "./chunk-25SZBEYX.mjs";
5
+ } from "./chunk-L2WVWRAC.mjs";
6
6
 
7
7
  // src/langchain.ts
8
8
  import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
@@ -1,5 +1,5 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { T as TransparencyMetadata } from './agentid-BWlN5KCq.mjs';
2
+ import { T as TransparencyMetadata } from './agentid-Mjh8rXn0.mjs';
3
3
 
4
4
  type AgentIDTransparencyBadgeTelemetry = {
5
5
  systemId: string;
@@ -1,5 +1,5 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { T as TransparencyMetadata } from './agentid-BWlN5KCq.js';
2
+ import { T as TransparencyMetadata } from './agentid-Mjh8rXn0.js';
3
3
 
4
4
  type AgentIDTransparencyBadgeTelemetry = {
5
5
  systemId: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentid-sdk",
3
- "version": "0.1.40",
3
+ "version": "0.1.41",
4
4
  "description": "AgentID JavaScript/TypeScript SDK for guardrails, masking, workflow telemetry, and audit logging.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://agentid.ai",