agentid-sdk 0.1.38 → 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/README.md CHANGED
@@ -111,6 +111,10 @@ console.log(response.choices[0]?.message?.content ?? "");
111
111
  By default, official AgentID SDK integrations inherit `enable_sdk_pii_masking`
112
112
  from the dashboard/runtime config. You only need to set `piiMasking: true` in
113
113
  code if you want to force local masking on even when the dashboard policy is off.
114
+ Starting with `agentid-sdk@0.1.40`, fail-open dependency fallback keeps local
115
+ deterministic PII and secret masking enabled when `/agent/config` or `/guard`
116
+ is unreachable. Fail-open can preserve availability, but official wrappers must
117
+ not treat it as permission to send raw sensitive text to the provider.
114
118
 
115
119
  When SDK-side masking is enabled, the wrapper now masks both classic PII and
116
120
  high-confidence secret material before the request leaves your process:
@@ -121,10 +125,86 @@ high-confidence secret material before the request leaves your process:
121
125
  - password / credential assignments, PEM private keys, Azure connection strings and SAS tokens
122
126
 
123
127
  The masked form is what gets sent to `/guard`, logged to AgentID ingest, and
124
- forwarded to the model provider. Placeholder mapping stays local to the SDK and
125
- can be deanonymized back to the caller after completion.
126
-
127
- Wrapped OpenAI calls persist telemetry for both regular and streamed completions. For `stream: true`, logging happens when the stream finishes.
128
+ forwarded to the model provider. The wrapper also protects returned completion
129
+ text before it is logged or returned from the wrapped call when SDK-side masking
130
+ is enabled.
131
+
132
+ Important: this applies only to the wrapped call. If your app sends raw prompt
133
+ or raw chat history through a separate direct provider call, AgentID cannot
134
+ protect that bypass.
135
+
136
+ Correct:
137
+
138
+ ```ts
139
+ const secured = agent.wrapOpenAI(openai, {
140
+ system_id: process.env.AGENTID_SYSTEM_ID!,
141
+ });
142
+
143
+ await secured.chat.completions.create({
144
+ model: "gpt-4o-mini",
145
+ messages: fullConversationHistory,
146
+ });
147
+ ```
148
+
149
+ Incorrect:
150
+
151
+ ```ts
152
+ // Raw history reaches the provider.
153
+ await openai.chat.completions.create({
154
+ model: "gpt-4o-mini",
155
+ messages: rawConversationHistory,
156
+ });
157
+
158
+ // Logging a masked copy later does not protect the model call above.
159
+ await agent.log({ system_id: systemId, input: maskedInput, output: maskedOutput });
160
+ ```
161
+
162
+ For chat apps and agent workflows, protect the full message history, not just
163
+ the latest text field. If a previous user/assistant/tool/memory message contains
164
+ raw PII, the model can still repeat it later.
165
+
166
+ If you cannot use `wrapOpenAI()` and need a manual integration, call
167
+ `protectMessageHistory()` on the exact history that will be sent to the
168
+ provider. Then pass `protected.messages` to the provider, not the raw
169
+ `body.messages`.
170
+
171
+ ```ts
172
+ import { AgentID, protectMessageHistory } from "agentid-sdk";
173
+
174
+ const agent = new AgentID();
175
+ const protectedHistory = protectMessageHistory(body.messages, {
176
+ pii: true,
177
+ secrets: true,
178
+ });
179
+
180
+ const latestUserInput = extractLatestUserInput(protectedHistory.messages);
181
+ const verdict = await agent.guard({
182
+ system_id: process.env.AGENTID_SYSTEM_ID!,
183
+ input: latestUserInput,
184
+ model: "gpt-4o-mini",
185
+ metadata: {
186
+ runtime_surface: "manual_provider_integration",
187
+ full_history_protected: true,
188
+ messages_count: Array.isArray(protectedHistory.messages)
189
+ ? protectedHistory.messages.length
190
+ : undefined,
191
+ protected_messages_count: Array.isArray(protectedHistory.messages)
192
+ ? protectedHistory.messages.length
193
+ : undefined,
194
+ prompt_text_parts_count: protectedHistory.textPartsCount,
195
+ transformed_prompt_text_parts_count:
196
+ protectedHistory.transformedTextPartsCount,
197
+ },
198
+ });
199
+ if (!verdict.allowed) throw new Error(`Blocked: ${verdict.reason}`);
200
+
201
+ const response = await openai.chat.completions.create({
202
+ model: "gpt-4o-mini",
203
+ messages: protectedHistory.messages,
204
+ });
205
+ ```
206
+
207
+ Wrapped OpenAI calls persist telemetry for both regular and streamed completions. For `stream: true`, logging happens when the stream finishes.
128
208
 
129
209
  > Scope note: AgentID compliance/risk controls apply to the specific SDK-wrapped LLM calls (`guard()`, `wrapOpenAI()`, LangChain callback-wrapped flows). They do not automatically classify unrelated code paths in your whole monolithic application.
130
210
 
@@ -198,17 +278,28 @@ import { AgentID } from "agentid-sdk";
198
278
 
199
279
  const agent = new AgentID();
200
280
 
201
- await agent.log({
202
- system_id: process.env.AGENTID_SYSTEM_ID!,
203
- event_type: "complete",
204
- severity: "info",
205
- model: "gpt-4o-mini",
206
- input: "Raw telemetry prompt",
207
- output: '{"ok": true}',
281
+ await agent.log({
282
+ system_id: process.env.AGENTID_SYSTEM_ID!,
283
+ event_type: "complete",
284
+ severity: "info",
285
+ model: "gpt-4o-mini",
286
+ input: "Raw telemetry prompt",
287
+ output: '{"ok": true}',
288
+ usage: {
289
+ prompt_tokens: 33,
290
+ completion_tokens: 9,
291
+ total_tokens: 42,
292
+ },
293
+ latency: 1450,
208
294
  metadata: { agent_role: "batch-worker", channel: "manual_ingest" },
209
295
  });
210
296
  ```
211
297
 
298
+ For manual integrations, preserve provider usage. Without `usage` or
299
+ normalized `tokens`, AgentID can store Activity but cannot compute token totals,
300
+ `cost_usd`, Total Spend, or ROI. ROI also requires the system business context
301
+ fields `human_hourly_rate` and `human_time_per_task_min`.
302
+
212
303
  ### Agent workflow and tool events
213
304
 
214
305
  Use `logOperation()` when an agent calls tools or performs operational work outside the wrapped LLM call. Reuse the same `workflowRunId` across steps.
@@ -281,6 +281,7 @@ declare class AgentID {
281
281
  private getCapabilityConfigWithTelemetry;
282
282
  private getCachedCapabilityConfig;
283
283
  private resolveEffectiveStrictMode;
284
+ private buildFailOpenGuardVerdict;
284
285
  private maybeRaiseStrictIngestDependencyError;
285
286
  private shouldRunLocalInjectionScan;
286
287
  private refreshCapabilityConfigBeforeClientControl;
@@ -396,4 +397,4 @@ declare class AgentIDWorkflowTrail {
396
397
  }
397
398
  declare function createAgentIdWorkflowTrail(options: AgentIDWorkflowTrailOptions): AgentIDWorkflowTrail;
398
399
 
399
- export { type AgentEventType as A, DependencyError as D, type GuardAttachment as G, type LogParams as L, type OperationLogParams as O, PIIManager as P, type RequestOptions as R, SecurityBlockError as S, type TransparencyMetadata as T, type WrapOpenAIOptions as W, AgentID as a, type AgentIDWorkflowRunHooks as b, AgentIDWorkflowStep as c, type AgentIDWorkflowStepParams as d, AgentIDWorkflowTrail as e, type AgentIDWorkflowTrailOptions as f, type AgentOperationCategory as g, type AgentOperationStatus as h, type AgentTelemetryContext as i, type GuardParams as j, type GuardResponse as k, type PIIAnonymizeOptions as l, type PIIMapping as m, type PreparedInput as n, createAgentIdCorrelationId as o, createAgentIdOperationLog as p, createAgentIdTelemetryContext as q, createAgentIdWorkflowTrail as r };
400
+ export { type AgentEventType as A, DependencyError as D, type GuardAttachment as G, type LogParams as L, type OperationLogParams as O, type PIIAnonymizeOptions as P, type RequestOptions as R, SecurityBlockError as S, type TransparencyMetadata as T, type WrapOpenAIOptions as W, PIIManager as a, AgentID as b, type AgentIDWorkflowRunHooks as c, AgentIDWorkflowStep as d, type AgentIDWorkflowStepParams as e, AgentIDWorkflowTrail as f, type AgentIDWorkflowTrailOptions as g, type AgentOperationCategory as h, type AgentOperationStatus as i, type AgentTelemetryContext as j, type GuardParams as k, type GuardResponse as l, type PIIMapping as m, type PreparedInput as n, createAgentIdCorrelationId as o, createAgentIdOperationLog as p, createAgentIdTelemetryContext as q, createAgentIdWorkflowTrail as r };
@@ -281,6 +281,7 @@ declare class AgentID {
281
281
  private getCapabilityConfigWithTelemetry;
282
282
  private getCachedCapabilityConfig;
283
283
  private resolveEffectiveStrictMode;
284
+ private buildFailOpenGuardVerdict;
284
285
  private maybeRaiseStrictIngestDependencyError;
285
286
  private shouldRunLocalInjectionScan;
286
287
  private refreshCapabilityConfigBeforeClientControl;
@@ -396,4 +397,4 @@ declare class AgentIDWorkflowTrail {
396
397
  }
397
398
  declare function createAgentIdWorkflowTrail(options: AgentIDWorkflowTrailOptions): AgentIDWorkflowTrail;
398
399
 
399
- export { type AgentEventType as A, DependencyError as D, type GuardAttachment as G, type LogParams as L, type OperationLogParams as O, PIIManager as P, type RequestOptions as R, SecurityBlockError as S, type TransparencyMetadata as T, type WrapOpenAIOptions as W, AgentID as a, type AgentIDWorkflowRunHooks as b, AgentIDWorkflowStep as c, type AgentIDWorkflowStepParams as d, AgentIDWorkflowTrail as e, type AgentIDWorkflowTrailOptions as f, type AgentOperationCategory as g, type AgentOperationStatus as h, type AgentTelemetryContext as i, type GuardParams as j, type GuardResponse as k, type PIIAnonymizeOptions as l, type PIIMapping as m, type PreparedInput as n, createAgentIdCorrelationId as o, createAgentIdOperationLog as p, createAgentIdTelemetryContext as q, createAgentIdWorkflowTrail as r };
400
+ export { type AgentEventType as A, DependencyError as D, type GuardAttachment as G, type LogParams as L, type OperationLogParams as O, type PIIAnonymizeOptions as P, type RequestOptions as R, SecurityBlockError as S, type TransparencyMetadata as T, type WrapOpenAIOptions as W, PIIManager as a, AgentID as b, type AgentIDWorkflowRunHooks as c, AgentIDWorkflowStep as d, type AgentIDWorkflowStepParams as e, AgentIDWorkflowTrail as f, type AgentIDWorkflowTrailOptions as g, type AgentOperationCategory as h, type AgentOperationStatus as i, type AgentTelemetryContext as j, type GuardParams as k, type GuardResponse as l, type PIIMapping as m, type PreparedInput as n, createAgentIdCorrelationId as o, createAgentIdOperationLog as p, createAgentIdTelemetryContext as q, createAgentIdWorkflowTrail as r };
@@ -1124,9 +1124,9 @@ var SDK_SECRET_PATTERN_DEFINITIONS = [
1124
1124
  {
1125
1125
  id: "password_assignment",
1126
1126
  placeholderType: "PASSWORD_ASSIGNMENT",
1127
- patternSource: `(?:\\b|["'])(?:password|passwd|pwd)(?:\\b|["'])\\s*(?:(?::|=|=>)|(?:is|are|was|were)\\b)\\s*(?:"[A-Za-z0-9._~!@#$%^&*+=\\/-]{8,}"|'[A-Za-z0-9._~!@#$%^&*+=\\/-]{8,}'|[A-Za-z0-9._~!@#$%^&*+=\\/-]{8,})`,
1127
+ 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,})`,
1128
1128
  flags: "iu",
1129
- prefilterTerms: ["password", "passwd", "pwd"]
1129
+ prefilterTerms: ["password", "passwd", "pwd", "heslo"]
1130
1130
  },
1131
1131
  {
1132
1132
  id: "private_key_material",
@@ -1228,6 +1228,8 @@ var PHONE_CONTEXT_KEYWORDS = [
1228
1228
  "call",
1229
1229
  "contact",
1230
1230
  "number",
1231
+ "cislo",
1232
+ "\u010D\xEDslo",
1231
1233
  "hotline",
1232
1234
  "support",
1233
1235
  "infoline",
@@ -2288,7 +2290,7 @@ function getInjectionScanner() {
2288
2290
 
2289
2291
  // src/sdk-version.ts
2290
2292
  var FALLBACK_SDK_VERSION = "js-0.0.0-dev";
2291
- var AGENTID_SDK_VERSION_HEADER = "js-0.1.38".trim().length > 0 ? "js-0.1.38" : FALLBACK_SDK_VERSION;
2293
+ var AGENTID_SDK_VERSION_HEADER = "js-0.1.40".trim().length > 0 ? "js-0.1.40" : FALLBACK_SDK_VERSION;
2292
2294
 
2293
2295
  // src/local-security-enforcer.ts
2294
2296
  var DEFAULT_FAIL_OPEN_CONFIG = {
@@ -2299,9 +2301,9 @@ var DEFAULT_FAIL_OPEN_CONFIG = {
2299
2301
  block_on_heuristic: false,
2300
2302
  inject_transparency_metadata: false,
2301
2303
  block_pii_leakage: false,
2302
- enable_sdk_pii_masking: false,
2304
+ enable_sdk_pii_masking: true,
2303
2305
  block_secret_leakage: false,
2304
- enable_sdk_secret_masking: false,
2306
+ enable_sdk_secret_masking: true,
2305
2307
  block_db_access: false,
2306
2308
  block_code_execution: false,
2307
2309
  block_toxicity: false
@@ -3711,6 +3713,23 @@ var AgentID = class {
3711
3713
  const config = await this.getCapabilityConfig(false, options);
3712
3714
  return config.strict_security_mode || config.failure_mode === "fail_close";
3713
3715
  }
3716
+ buildFailOpenGuardVerdict(reason, input, options) {
3717
+ const capabilityConfig = this.getCachedCapabilityConfig(options);
3718
+ const shouldMaskPii = capabilityConfig.block_pii_leakage || this.resolveEffectivePiiMasking(capabilityConfig);
3719
+ const shouldMaskSecrets = capabilityConfig.block_secret_leakage === true || this.resolveEffectiveSecretMasking(capabilityConfig);
3720
+ const response = { allowed: true, reason };
3721
+ if (input && (shouldMaskPii || shouldMaskSecrets)) {
3722
+ const masked = this.pii.anonymize(input, {
3723
+ pii: shouldMaskPii,
3724
+ secrets: shouldMaskSecrets
3725
+ });
3726
+ if (masked.maskedText !== input) {
3727
+ response.transformed_input = masked.maskedText;
3728
+ response.detected_pii = Object.keys(masked.mapping).length > 0;
3729
+ }
3730
+ }
3731
+ return response;
3732
+ }
3714
3733
  maybeRaiseStrictIngestDependencyError(params) {
3715
3734
  if (params.result.ok) {
3716
3735
  return;
@@ -3951,12 +3970,43 @@ var AgentID = class {
3951
3970
  })
3952
3971
  });
3953
3972
  }
3954
- withMaskedOpenAIRequest(req, maskedText) {
3973
+ withMaskedOpenAIRequest(req, maskedText, options) {
3955
3974
  const messages = Array.isArray(req?.messages) ? req.messages : null;
3956
3975
  if (!messages) {
3957
3976
  return req;
3958
3977
  }
3959
- const newMessages = [...messages];
3978
+ const newMessages = messages.map((message2) => {
3979
+ if (!message2 || typeof message2 !== "object") {
3980
+ return message2;
3981
+ }
3982
+ const typedMessage = message2;
3983
+ const currentContent2 = typedMessage.content;
3984
+ if (typeof currentContent2 === "string") {
3985
+ return {
3986
+ ...typedMessage,
3987
+ content: this.pii.anonymize(currentContent2, options).maskedText
3988
+ };
3989
+ }
3990
+ if (Array.isArray(currentContent2)) {
3991
+ return {
3992
+ ...typedMessage,
3993
+ content: currentContent2.map((part) => {
3994
+ if (!part || typeof part !== "object") {
3995
+ return part;
3996
+ }
3997
+ const typedPart = part;
3998
+ if (typeof typedPart.text !== "string") {
3999
+ return part;
4000
+ }
4001
+ return {
4002
+ ...typedPart,
4003
+ text: this.pii.anonymize(typedPart.text, options).maskedText
4004
+ };
4005
+ })
4006
+ };
4007
+ }
4008
+ return message2;
4009
+ });
3960
4010
  let lastUserIdx = null;
3961
4011
  for (let i = 0; i < newMessages.length; i += 1) {
3962
4012
  const msg = newMessages[i];
@@ -4170,7 +4220,13 @@ var AgentID = class {
4170
4220
  guardParams: params,
4171
4221
  apiKey: effectiveApiKey
4172
4222
  });
4173
- return withGuardLatency({ allowed: true, reason: "system_failure_fail_open" });
4223
+ return withGuardLatency(
4224
+ this.buildFailOpenGuardVerdict(
4225
+ "system_failure_fail_open",
4226
+ params.input,
4227
+ { apiKey: effectiveApiKey }
4228
+ )
4229
+ );
4174
4230
  }
4175
4231
  this.cacheGuardVerdict(guardCacheKey, verdict);
4176
4232
  return withGuardLatency(verdict);
@@ -4205,7 +4261,11 @@ var AgentID = class {
4205
4261
  if (effectiveStrictMode) {
4206
4262
  return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4207
4263
  }
4208
- return withGuardLatency({ allowed: true, reason: "timeout_fallback" });
4264
+ return withGuardLatency(
4265
+ this.buildFailOpenGuardVerdict("timeout_fallback", params.input, {
4266
+ apiKey: effectiveApiKey
4267
+ })
4268
+ );
4209
4269
  }
4210
4270
  console.warn(
4211
4271
  effectiveStrictMode ? "[AgentID] Guard check failed (Strict mode active):" : "[AgentID] Guard check failed (Fail-Open active):",
@@ -4220,7 +4280,11 @@ var AgentID = class {
4220
4280
  if (effectiveStrictMode) {
4221
4281
  return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4222
4282
  }
4223
- return withGuardLatency({ allowed: true, reason: "guard_unreachable" });
4283
+ return withGuardLatency(
4284
+ this.buildFailOpenGuardVerdict("guard_unreachable", params.input, {
4285
+ apiKey: effectiveApiKey
4286
+ })
4287
+ );
4224
4288
  } finally {
4225
4289
  clearTimeout(timeoutId);
4226
4290
  }
@@ -4229,13 +4293,23 @@ var AgentID = class {
4229
4293
  if (effectiveStrictMode) {
4230
4294
  return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4231
4295
  }
4232
- return withGuardLatency({ allowed: true, reason: "timeout_fallback" });
4296
+ return withGuardLatency(
4297
+ this.buildFailOpenGuardVerdict("timeout_fallback", params.input, {
4298
+ apiKey: effectiveApiKey
4299
+ })
4300
+ );
4233
4301
  }
4234
4302
  if (typeof lastStatusCode === "number" && lastStatusCode >= 500) {
4235
4303
  if (effectiveStrictMode) {
4236
4304
  return withGuardLatency({ allowed: false, reason: "server_error" });
4237
4305
  }
4238
- return withGuardLatency({ allowed: true, reason: "system_failure_fail_open" });
4306
+ return withGuardLatency(
4307
+ this.buildFailOpenGuardVerdict(
4308
+ "system_failure_fail_open",
4309
+ params.input,
4310
+ { apiKey: effectiveApiKey }
4311
+ )
4312
+ );
4239
4313
  }
4240
4314
  console.warn(
4241
4315
  effectiveStrictMode ? "[AgentID] Guard check failed (Strict mode active):" : "[AgentID] Guard check failed (Fail-Open active):",
@@ -4244,7 +4318,11 @@ var AgentID = class {
4244
4318
  if (effectiveStrictMode) {
4245
4319
  return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4246
4320
  }
4247
- return withGuardLatency({ allowed: true, reason: "guard_unreachable" });
4321
+ return withGuardLatency(
4322
+ this.buildFailOpenGuardVerdict("guard_unreachable", params.input, {
4323
+ apiKey: effectiveApiKey
4324
+ })
4325
+ );
4248
4326
  }
4249
4327
  async sendIngest(params, options, internal) {
4250
4328
  const ingestStartedAt = Date.now();
@@ -4749,6 +4827,7 @@ var AgentID = class {
4749
4827
  let mapping = {};
4750
4828
  let sdkConfigFetchMs = 0;
4751
4829
  let sdkLocalScanMs = 0;
4830
+ let providerMaskingOptions;
4752
4831
  if (hasGuardContent) {
4753
4832
  const prepared = await this.prepareInputForDispatch({
4754
4833
  input: userText ?? "",
@@ -4758,6 +4837,10 @@ var AgentID = class {
4758
4837
  telemetryMetadata
4759
4838
  }, requestOptions);
4760
4839
  capabilityConfig = prepared.capabilityConfig;
4840
+ providerMaskingOptions = {
4841
+ pii: !capabilityConfig.block_pii_leakage && this.resolveEffectivePiiMasking(capabilityConfig),
4842
+ secrets: !capabilityConfig.block_secret_leakage && this.resolveEffectiveSecretMasking(capabilityConfig)
4843
+ };
4761
4844
  maskedText = prepared.sanitizedInput;
4762
4845
  mapping = prepared.piiMapping ?? {};
4763
4846
  sdkConfigFetchMs = prepared.sdkConfigFetchMs ?? 0;
@@ -4765,7 +4848,8 @@ var AgentID = class {
4765
4848
  if (maskedText !== (userText ?? "")) {
4766
4849
  maskedReq = this.withMaskedOpenAIRequest(
4767
4850
  providerReq,
4768
- maskedText
4851
+ maskedText,
4852
+ providerMaskingOptions
4769
4853
  );
4770
4854
  const nextCreateArgs = [...createArgs];
4771
4855
  nextCreateArgs[0] = maskedReq;
@@ -4839,10 +4923,11 @@ var AgentID = class {
4839
4923
  }
4840
4924
  }
4841
4925
  const currentRequestInput = adapter.extractInput(maskedReq) ?? "";
4842
- if (maskedText !== currentRequestInput) {
4926
+ if (maskedText !== currentRequestInput || providerMaskingOptions?.pii === true || providerMaskingOptions?.secrets === true) {
4843
4927
  maskedReq = this.withMaskedOpenAIRequest(
4844
4928
  providerReq,
4845
- maskedText
4929
+ maskedText,
4930
+ providerMaskingOptions
4846
4931
  );
4847
4932
  const nextCreateArgs = [...createArgs];
4848
4933
  nextCreateArgs[0] = maskedReq;
@@ -4865,7 +4950,8 @@ var AgentID = class {
4865
4950
  maskedText = transformedInput;
4866
4951
  maskedReq = this.withMaskedOpenAIRequest(
4867
4952
  providerReq,
4868
- transformedInput
4953
+ transformedInput,
4954
+ providerMaskingOptions
4869
4955
  );
4870
4956
  const nextCreateArgs = [...createArgs];
4871
4957
  nextCreateArgs[0] = maskedReq;
@@ -4912,7 +4998,7 @@ var AgentID = class {
4912
4998
  void wrappedCompletion.done.then(async (result) => {
4913
4999
  const modelLatencyMs2 = Math.max(0, Date.now() - modelStartedAt2);
4914
5000
  const totalPipelineLatencyMs2 = Math.max(0, Date.now() - pipelineStartedAt);
4915
- const outputForLog = isShadowMode ? result.rawOutput : result.transformedOutput;
5001
+ const outputForLog = result.transformedOutput;
4916
5002
  const ingestResult = await this.sendIngest({
4917
5003
  event_id: canonicalClientEventId,
4918
5004
  system_id: systemId,
@@ -4986,7 +5072,7 @@ var AgentID = class {
4986
5072
  });
4987
5073
  const model = adapter.getModelName(maskedReq, res);
4988
5074
  const usage = adapter.getTokenUsage(res);
4989
- const outputForLog = isShadowMode ? wrappedCompletion.rawOutput : wrappedCompletion.transformedOutput;
5075
+ const outputForLog = wrappedCompletion.transformedOutput;
4990
5076
  const ingestResult = await this.sendIngest({
4991
5077
  event_id: canonicalClientEventId,
4992
5078
  system_id: systemId,
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { P as PIIManager } from './agentid-CxVUF_eo.mjs';
2
- export { A as AgentEventType, a as AgentID, b as AgentIDWorkflowRunHooks, c as AgentIDWorkflowStep, d as AgentIDWorkflowStepParams, e as AgentIDWorkflowTrail, f as AgentIDWorkflowTrailOptions, g as AgentOperationCategory, h as AgentOperationStatus, i as AgentTelemetryContext, D as DependencyError, G as GuardAttachment, j as GuardParams, k as GuardResponse, L as LogParams, O as OperationLogParams, l as PIIAnonymizeOptions, 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-CxVUF_eo.mjs';
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';
3
3
 
4
4
  type TokenUsage = Record<string, unknown>;
5
5
  type ExtractedGuardAttachment = {
@@ -24,6 +24,15 @@ declare class OpenAIAdapter implements LLMAdapter {
24
24
  isStream(req: any): boolean;
25
25
  }
26
26
 
27
+ type ProtectMessageHistoryOptions = PIIAnonymizeOptions;
28
+ type ProtectMessageHistoryResult<T> = {
29
+ messages: T;
30
+ transformed: boolean;
31
+ textPartsCount: number;
32
+ transformedTextPartsCount: number;
33
+ };
34
+ declare function protectMessageHistory<T>(messages: T, options?: ProtectMessageHistoryOptions): ProtectMessageHistoryResult<T>;
35
+
27
36
  type InjectionScanParams = {
28
37
  prompt: string;
29
38
  apiKey: string;
@@ -54,4 +63,4 @@ declare class InjectionScanner {
54
63
  }
55
64
  declare function getInjectionScanner(): InjectionScanner;
56
65
 
57
- export { type ExtractedGuardAttachment, type InjectionScanParams, InjectionScanner, type LLMAdapter, OpenAIAdapter, PIIManager, type TokenUsage, getInjectionScanner, scanWithRegex };
66
+ export { type ExtractedGuardAttachment, type InjectionScanParams, InjectionScanner, type LLMAdapter, OpenAIAdapter, PIIAnonymizeOptions, PIIManager, type ProtectMessageHistoryOptions, type ProtectMessageHistoryResult, type TokenUsage, getInjectionScanner, protectMessageHistory, scanWithRegex };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { P as PIIManager } from './agentid-CxVUF_eo.js';
2
- export { A as AgentEventType, a as AgentID, b as AgentIDWorkflowRunHooks, c as AgentIDWorkflowStep, d as AgentIDWorkflowStepParams, e as AgentIDWorkflowTrail, f as AgentIDWorkflowTrailOptions, g as AgentOperationCategory, h as AgentOperationStatus, i as AgentTelemetryContext, D as DependencyError, G as GuardAttachment, j as GuardParams, k as GuardResponse, L as LogParams, O as OperationLogParams, l as PIIAnonymizeOptions, 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-CxVUF_eo.js';
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';
3
3
 
4
4
  type TokenUsage = Record<string, unknown>;
5
5
  type ExtractedGuardAttachment = {
@@ -24,6 +24,15 @@ declare class OpenAIAdapter implements LLMAdapter {
24
24
  isStream(req: any): boolean;
25
25
  }
26
26
 
27
+ type ProtectMessageHistoryOptions = PIIAnonymizeOptions;
28
+ type ProtectMessageHistoryResult<T> = {
29
+ messages: T;
30
+ transformed: boolean;
31
+ textPartsCount: number;
32
+ transformedTextPartsCount: number;
33
+ };
34
+ declare function protectMessageHistory<T>(messages: T, options?: ProtectMessageHistoryOptions): ProtectMessageHistoryResult<T>;
35
+
27
36
  type InjectionScanParams = {
28
37
  prompt: string;
29
38
  apiKey: string;
@@ -54,4 +63,4 @@ declare class InjectionScanner {
54
63
  }
55
64
  declare function getInjectionScanner(): InjectionScanner;
56
65
 
57
- export { type ExtractedGuardAttachment, type InjectionScanParams, InjectionScanner, type LLMAdapter, OpenAIAdapter, PIIManager, type TokenUsage, getInjectionScanner, scanWithRegex };
66
+ export { type ExtractedGuardAttachment, type InjectionScanParams, InjectionScanner, type LLMAdapter, OpenAIAdapter, PIIAnonymizeOptions, PIIManager, type ProtectMessageHistoryOptions, type ProtectMessageHistoryResult, type TokenUsage, getInjectionScanner, protectMessageHistory, scanWithRegex };
package/dist/index.js CHANGED
@@ -33,6 +33,7 @@ __export(index_exports, {
33
33
  createAgentIdTelemetryContext: () => createAgentIdTelemetryContext,
34
34
  createAgentIdWorkflowTrail: () => createAgentIdWorkflowTrail,
35
35
  getInjectionScanner: () => getInjectionScanner,
36
+ protectMessageHistory: () => protectMessageHistory,
36
37
  scanWithRegex: () => scanWithRegex
37
38
  });
38
39
  module.exports = __toCommonJS(index_exports);
@@ -181,7 +182,7 @@ var OpenAIAdapter = class {
181
182
 
182
183
  // src/sdk-version.ts
183
184
  var FALLBACK_SDK_VERSION = "js-0.0.0-dev";
184
- var AGENTID_SDK_VERSION_HEADER = "js-0.1.38".trim().length > 0 ? "js-0.1.38" : FALLBACK_SDK_VERSION;
185
+ var AGENTID_SDK_VERSION_HEADER = "js-0.1.40".trim().length > 0 ? "js-0.1.40" : FALLBACK_SDK_VERSION;
185
186
 
186
187
  // src/pii-national-identifiers.ts
187
188
  var MAX_CANDIDATES_PER_RULE = 256;
@@ -1167,9 +1168,9 @@ var SDK_SECRET_PATTERN_DEFINITIONS = [
1167
1168
  {
1168
1169
  id: "password_assignment",
1169
1170
  placeholderType: "PASSWORD_ASSIGNMENT",
1170
- patternSource: `(?:\\b|["'])(?:password|passwd|pwd)(?:\\b|["'])\\s*(?:(?::|=|=>)|(?:is|are|was|were)\\b)\\s*(?:"[A-Za-z0-9._~!@#$%^&*+=\\/-]{8,}"|'[A-Za-z0-9._~!@#$%^&*+=\\/-]{8,}'|[A-Za-z0-9._~!@#$%^&*+=\\/-]{8,})`,
1171
+ 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,})`,
1171
1172
  flags: "iu",
1172
- prefilterTerms: ["password", "passwd", "pwd"]
1173
+ prefilterTerms: ["password", "passwd", "pwd", "heslo"]
1173
1174
  },
1174
1175
  {
1175
1176
  id: "private_key_material",
@@ -1271,6 +1272,8 @@ var PHONE_CONTEXT_KEYWORDS = [
1271
1272
  "call",
1272
1273
  "contact",
1273
1274
  "number",
1275
+ "cislo",
1276
+ "\u010D\xEDslo",
1274
1277
  "hotline",
1275
1278
  "support",
1276
1279
  "infoline",
@@ -1679,9 +1682,9 @@ var DEFAULT_FAIL_OPEN_CONFIG = {
1679
1682
  block_on_heuristic: false,
1680
1683
  inject_transparency_metadata: false,
1681
1684
  block_pii_leakage: false,
1682
- enable_sdk_pii_masking: false,
1685
+ enable_sdk_pii_masking: true,
1683
1686
  block_secret_leakage: false,
1684
- enable_sdk_secret_masking: false,
1687
+ enable_sdk_secret_masking: true,
1685
1688
  block_db_access: false,
1686
1689
  block_code_execution: false,
1687
1690
  block_toxicity: false
@@ -3750,6 +3753,23 @@ var AgentID = class {
3750
3753
  const config = await this.getCapabilityConfig(false, options);
3751
3754
  return config.strict_security_mode || config.failure_mode === "fail_close";
3752
3755
  }
3756
+ buildFailOpenGuardVerdict(reason, input, options) {
3757
+ const capabilityConfig = this.getCachedCapabilityConfig(options);
3758
+ const shouldMaskPii = capabilityConfig.block_pii_leakage || this.resolveEffectivePiiMasking(capabilityConfig);
3759
+ const shouldMaskSecrets = capabilityConfig.block_secret_leakage === true || this.resolveEffectiveSecretMasking(capabilityConfig);
3760
+ const response = { allowed: true, reason };
3761
+ if (input && (shouldMaskPii || shouldMaskSecrets)) {
3762
+ const masked = this.pii.anonymize(input, {
3763
+ pii: shouldMaskPii,
3764
+ secrets: shouldMaskSecrets
3765
+ });
3766
+ if (masked.maskedText !== input) {
3767
+ response.transformed_input = masked.maskedText;
3768
+ response.detected_pii = Object.keys(masked.mapping).length > 0;
3769
+ }
3770
+ }
3771
+ return response;
3772
+ }
3753
3773
  maybeRaiseStrictIngestDependencyError(params) {
3754
3774
  if (params.result.ok) {
3755
3775
  return;
@@ -3990,12 +4010,43 @@ var AgentID = class {
3990
4010
  })
3991
4011
  });
3992
4012
  }
3993
- withMaskedOpenAIRequest(req, maskedText) {
4013
+ withMaskedOpenAIRequest(req, maskedText, options) {
3994
4014
  const messages = Array.isArray(req?.messages) ? req.messages : null;
3995
4015
  if (!messages) {
3996
4016
  return req;
3997
4017
  }
3998
- const newMessages = [...messages];
4018
+ const newMessages = messages.map((message2) => {
4019
+ if (!message2 || typeof message2 !== "object") {
4020
+ return message2;
4021
+ }
4022
+ const typedMessage = message2;
4023
+ const currentContent2 = typedMessage.content;
4024
+ if (typeof currentContent2 === "string") {
4025
+ return {
4026
+ ...typedMessage,
4027
+ content: this.pii.anonymize(currentContent2, options).maskedText
4028
+ };
4029
+ }
4030
+ if (Array.isArray(currentContent2)) {
4031
+ return {
4032
+ ...typedMessage,
4033
+ content: currentContent2.map((part) => {
4034
+ if (!part || typeof part !== "object") {
4035
+ return part;
4036
+ }
4037
+ const typedPart = part;
4038
+ if (typeof typedPart.text !== "string") {
4039
+ return part;
4040
+ }
4041
+ return {
4042
+ ...typedPart,
4043
+ text: this.pii.anonymize(typedPart.text, options).maskedText
4044
+ };
4045
+ })
4046
+ };
4047
+ }
4048
+ return message2;
4049
+ });
3999
4050
  let lastUserIdx = null;
4000
4051
  for (let i = 0; i < newMessages.length; i += 1) {
4001
4052
  const msg = newMessages[i];
@@ -4209,7 +4260,13 @@ var AgentID = class {
4209
4260
  guardParams: params,
4210
4261
  apiKey: effectiveApiKey
4211
4262
  });
4212
- return withGuardLatency({ allowed: true, reason: "system_failure_fail_open" });
4263
+ return withGuardLatency(
4264
+ this.buildFailOpenGuardVerdict(
4265
+ "system_failure_fail_open",
4266
+ params.input,
4267
+ { apiKey: effectiveApiKey }
4268
+ )
4269
+ );
4213
4270
  }
4214
4271
  this.cacheGuardVerdict(guardCacheKey, verdict);
4215
4272
  return withGuardLatency(verdict);
@@ -4244,7 +4301,11 @@ var AgentID = class {
4244
4301
  if (effectiveStrictMode) {
4245
4302
  return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4246
4303
  }
4247
- return withGuardLatency({ allowed: true, reason: "timeout_fallback" });
4304
+ return withGuardLatency(
4305
+ this.buildFailOpenGuardVerdict("timeout_fallback", params.input, {
4306
+ apiKey: effectiveApiKey
4307
+ })
4308
+ );
4248
4309
  }
4249
4310
  console.warn(
4250
4311
  effectiveStrictMode ? "[AgentID] Guard check failed (Strict mode active):" : "[AgentID] Guard check failed (Fail-Open active):",
@@ -4259,7 +4320,11 @@ var AgentID = class {
4259
4320
  if (effectiveStrictMode) {
4260
4321
  return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4261
4322
  }
4262
- return withGuardLatency({ allowed: true, reason: "guard_unreachable" });
4323
+ return withGuardLatency(
4324
+ this.buildFailOpenGuardVerdict("guard_unreachable", params.input, {
4325
+ apiKey: effectiveApiKey
4326
+ })
4327
+ );
4263
4328
  } finally {
4264
4329
  clearTimeout(timeoutId);
4265
4330
  }
@@ -4268,13 +4333,23 @@ var AgentID = class {
4268
4333
  if (effectiveStrictMode) {
4269
4334
  return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4270
4335
  }
4271
- return withGuardLatency({ allowed: true, reason: "timeout_fallback" });
4336
+ return withGuardLatency(
4337
+ this.buildFailOpenGuardVerdict("timeout_fallback", params.input, {
4338
+ apiKey: effectiveApiKey
4339
+ })
4340
+ );
4272
4341
  }
4273
4342
  if (typeof lastStatusCode === "number" && lastStatusCode >= 500) {
4274
4343
  if (effectiveStrictMode) {
4275
4344
  return withGuardLatency({ allowed: false, reason: "server_error" });
4276
4345
  }
4277
- return withGuardLatency({ allowed: true, reason: "system_failure_fail_open" });
4346
+ return withGuardLatency(
4347
+ this.buildFailOpenGuardVerdict(
4348
+ "system_failure_fail_open",
4349
+ params.input,
4350
+ { apiKey: effectiveApiKey }
4351
+ )
4352
+ );
4278
4353
  }
4279
4354
  console.warn(
4280
4355
  effectiveStrictMode ? "[AgentID] Guard check failed (Strict mode active):" : "[AgentID] Guard check failed (Fail-Open active):",
@@ -4283,7 +4358,11 @@ var AgentID = class {
4283
4358
  if (effectiveStrictMode) {
4284
4359
  return withGuardLatency({ allowed: false, reason: "network_error_strict_mode" });
4285
4360
  }
4286
- return withGuardLatency({ allowed: true, reason: "guard_unreachable" });
4361
+ return withGuardLatency(
4362
+ this.buildFailOpenGuardVerdict("guard_unreachable", params.input, {
4363
+ apiKey: effectiveApiKey
4364
+ })
4365
+ );
4287
4366
  }
4288
4367
  async sendIngest(params, options, internal) {
4289
4368
  const ingestStartedAt = Date.now();
@@ -4788,6 +4867,7 @@ var AgentID = class {
4788
4867
  let mapping = {};
4789
4868
  let sdkConfigFetchMs = 0;
4790
4869
  let sdkLocalScanMs = 0;
4870
+ let providerMaskingOptions;
4791
4871
  if (hasGuardContent) {
4792
4872
  const prepared = await this.prepareInputForDispatch({
4793
4873
  input: userText ?? "",
@@ -4797,6 +4877,10 @@ var AgentID = class {
4797
4877
  telemetryMetadata
4798
4878
  }, requestOptions);
4799
4879
  capabilityConfig = prepared.capabilityConfig;
4880
+ providerMaskingOptions = {
4881
+ pii: !capabilityConfig.block_pii_leakage && this.resolveEffectivePiiMasking(capabilityConfig),
4882
+ secrets: !capabilityConfig.block_secret_leakage && this.resolveEffectiveSecretMasking(capabilityConfig)
4883
+ };
4800
4884
  maskedText = prepared.sanitizedInput;
4801
4885
  mapping = prepared.piiMapping ?? {};
4802
4886
  sdkConfigFetchMs = prepared.sdkConfigFetchMs ?? 0;
@@ -4804,7 +4888,8 @@ var AgentID = class {
4804
4888
  if (maskedText !== (userText ?? "")) {
4805
4889
  maskedReq = this.withMaskedOpenAIRequest(
4806
4890
  providerReq,
4807
- maskedText
4891
+ maskedText,
4892
+ providerMaskingOptions
4808
4893
  );
4809
4894
  const nextCreateArgs = [...createArgs];
4810
4895
  nextCreateArgs[0] = maskedReq;
@@ -4878,10 +4963,11 @@ var AgentID = class {
4878
4963
  }
4879
4964
  }
4880
4965
  const currentRequestInput = adapter.extractInput(maskedReq) ?? "";
4881
- if (maskedText !== currentRequestInput) {
4966
+ if (maskedText !== currentRequestInput || providerMaskingOptions?.pii === true || providerMaskingOptions?.secrets === true) {
4882
4967
  maskedReq = this.withMaskedOpenAIRequest(
4883
4968
  providerReq,
4884
- maskedText
4969
+ maskedText,
4970
+ providerMaskingOptions
4885
4971
  );
4886
4972
  const nextCreateArgs = [...createArgs];
4887
4973
  nextCreateArgs[0] = maskedReq;
@@ -4904,7 +4990,8 @@ var AgentID = class {
4904
4990
  maskedText = transformedInput;
4905
4991
  maskedReq = this.withMaskedOpenAIRequest(
4906
4992
  providerReq,
4907
- transformedInput
4993
+ transformedInput,
4994
+ providerMaskingOptions
4908
4995
  );
4909
4996
  const nextCreateArgs = [...createArgs];
4910
4997
  nextCreateArgs[0] = maskedReq;
@@ -4951,7 +5038,7 @@ var AgentID = class {
4951
5038
  void wrappedCompletion.done.then(async (result) => {
4952
5039
  const modelLatencyMs2 = Math.max(0, Date.now() - modelStartedAt2);
4953
5040
  const totalPipelineLatencyMs2 = Math.max(0, Date.now() - pipelineStartedAt);
4954
- const outputForLog = isShadowMode ? result.rawOutput : result.transformedOutput;
5041
+ const outputForLog = result.transformedOutput;
4955
5042
  const ingestResult = await this.sendIngest({
4956
5043
  event_id: canonicalClientEventId,
4957
5044
  system_id: systemId,
@@ -5025,7 +5112,7 @@ var AgentID = class {
5025
5112
  });
5026
5113
  const model = adapter.getModelName(maskedReq, res);
5027
5114
  const usage = adapter.getTokenUsage(res);
5028
- const outputForLog = isShadowMode ? wrappedCompletion.rawOutput : wrappedCompletion.transformedOutput;
5115
+ const outputForLog = wrappedCompletion.transformedOutput;
5029
5116
  const ingestResult = await this.sendIngest({
5030
5117
  event_id: canonicalClientEventId,
5031
5118
  system_id: systemId,
@@ -5267,6 +5354,58 @@ var AgentIDWorkflowTrail = class {
5267
5354
  function createAgentIdWorkflowTrail(options) {
5268
5355
  return new AgentIDWorkflowTrail(options);
5269
5356
  }
5357
+
5358
+ // src/message-history.ts
5359
+ function isPlainRecord(value) {
5360
+ if (!value || typeof value !== "object") return false;
5361
+ const proto = Object.getPrototypeOf(value);
5362
+ return proto === Object.prototype || proto === null;
5363
+ }
5364
+ function protectMessageHistory(messages, options = { pii: true, secrets: true }) {
5365
+ const piiManager = new PIIManager();
5366
+ let textPartsCount = 0;
5367
+ let transformedTextPartsCount = 0;
5368
+ const protectString = (value) => {
5369
+ textPartsCount += 1;
5370
+ const masked = piiManager.anonymize(value, options).maskedText;
5371
+ if (masked !== value) {
5372
+ transformedTextPartsCount += 1;
5373
+ }
5374
+ return masked;
5375
+ };
5376
+ const visit = (value, key) => {
5377
+ if (typeof value === "string") {
5378
+ return key === "content" || key === "text" ? protectString(value) : value;
5379
+ }
5380
+ if (Array.isArray(value)) {
5381
+ let changed = false;
5382
+ const next = value.map((item) => {
5383
+ const protectedItem = visit(item);
5384
+ if (protectedItem !== item) changed = true;
5385
+ return protectedItem;
5386
+ });
5387
+ return changed ? next : value;
5388
+ }
5389
+ if (isPlainRecord(value)) {
5390
+ let changed = false;
5391
+ const next = {};
5392
+ for (const [entryKey, entryValue] of Object.entries(value)) {
5393
+ const protectedValue = visit(entryValue, entryKey);
5394
+ next[entryKey] = protectedValue;
5395
+ if (protectedValue !== entryValue) changed = true;
5396
+ }
5397
+ return changed ? next : value;
5398
+ }
5399
+ return value;
5400
+ };
5401
+ const protectedMessages = visit(messages);
5402
+ return {
5403
+ messages: protectedMessages,
5404
+ transformed: protectedMessages !== messages,
5405
+ textPartsCount,
5406
+ transformedTextPartsCount
5407
+ };
5408
+ }
5270
5409
  // Annotate the CommonJS export names for ESM import in node:
5271
5410
  0 && (module.exports = {
5272
5411
  AgentID,
@@ -5282,5 +5421,6 @@ function createAgentIdWorkflowTrail(options) {
5282
5421
  createAgentIdTelemetryContext,
5283
5422
  createAgentIdWorkflowTrail,
5284
5423
  getInjectionScanner,
5424
+ protectMessageHistory,
5285
5425
  scanWithRegex
5286
5426
  });
package/dist/index.mjs CHANGED
@@ -13,7 +13,59 @@ import {
13
13
  createAgentIdWorkflowTrail,
14
14
  getInjectionScanner,
15
15
  scanWithRegex
16
- } from "./chunk-AIGMQSAV.mjs";
16
+ } from "./chunk-25SZBEYX.mjs";
17
+
18
+ // src/message-history.ts
19
+ function isPlainRecord(value) {
20
+ if (!value || typeof value !== "object") return false;
21
+ const proto = Object.getPrototypeOf(value);
22
+ return proto === Object.prototype || proto === null;
23
+ }
24
+ function protectMessageHistory(messages, options = { pii: true, secrets: true }) {
25
+ const piiManager = new PIIManager();
26
+ let textPartsCount = 0;
27
+ let transformedTextPartsCount = 0;
28
+ const protectString = (value) => {
29
+ textPartsCount += 1;
30
+ const masked = piiManager.anonymize(value, options).maskedText;
31
+ if (masked !== value) {
32
+ transformedTextPartsCount += 1;
33
+ }
34
+ return masked;
35
+ };
36
+ const visit = (value, key) => {
37
+ if (typeof value === "string") {
38
+ return key === "content" || key === "text" ? protectString(value) : value;
39
+ }
40
+ if (Array.isArray(value)) {
41
+ let changed = false;
42
+ const next = value.map((item) => {
43
+ const protectedItem = visit(item);
44
+ if (protectedItem !== item) changed = true;
45
+ return protectedItem;
46
+ });
47
+ return changed ? next : value;
48
+ }
49
+ if (isPlainRecord(value)) {
50
+ let changed = false;
51
+ const next = {};
52
+ for (const [entryKey, entryValue] of Object.entries(value)) {
53
+ const protectedValue = visit(entryValue, entryKey);
54
+ next[entryKey] = protectedValue;
55
+ if (protectedValue !== entryValue) changed = true;
56
+ }
57
+ return changed ? next : value;
58
+ }
59
+ return value;
60
+ };
61
+ const protectedMessages = visit(messages);
62
+ return {
63
+ messages: protectedMessages,
64
+ transformed: protectedMessages !== messages,
65
+ textPartsCount,
66
+ transformedTextPartsCount
67
+ };
68
+ }
17
69
  export {
18
70
  AgentID,
19
71
  AgentIDWorkflowStep,
@@ -28,5 +80,6 @@ export {
28
80
  createAgentIdTelemetryContext,
29
81
  createAgentIdWorkflowTrail,
30
82
  getInjectionScanner,
83
+ protectMessageHistory,
31
84
  scanWithRegex
32
85
  };
@@ -1,5 +1,5 @@
1
1
  import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
2
- import { a as AgentID, i as AgentTelemetryContext } from './agentid-CxVUF_eo.mjs';
2
+ import { b as AgentID, j as AgentTelemetryContext } from './agentid-BWlN5KCq.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 { a as AgentID, i as AgentTelemetryContext } from './agentid-CxVUF_eo.js';
2
+ import { b as AgentID, j as AgentTelemetryContext } from './agentid-BWlN5KCq.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.38".trim().length > 0 ? "js-0.1.38" : 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;
@@ -1013,9 +1013,9 @@ var SDK_SECRET_PATTERN_DEFINITIONS = [
1013
1013
  {
1014
1014
  id: "password_assignment",
1015
1015
  placeholderType: "PASSWORD_ASSIGNMENT",
1016
- patternSource: `(?:\\b|["'])(?:password|passwd|pwd)(?:\\b|["'])\\s*(?:(?::|=|=>)|(?:is|are|was|were)\\b)\\s*(?:"[A-Za-z0-9._~!@#$%^&*+=\\/-]{8,}"|'[A-Za-z0-9._~!@#$%^&*+=\\/-]{8,}'|[A-Za-z0-9._~!@#$%^&*+=\\/-]{8,})`,
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
1017
  flags: "iu",
1018
- prefilterTerms: ["password", "passwd", "pwd"]
1018
+ prefilterTerms: ["password", "passwd", "pwd", "heslo"]
1019
1019
  },
1020
1020
  {
1021
1021
  id: "private_key_material",
@@ -1117,6 +1117,8 @@ var PHONE_CONTEXT_KEYWORDS = [
1117
1117
  "call",
1118
1118
  "contact",
1119
1119
  "number",
1120
+ "cislo",
1121
+ "\u010D\xEDslo",
1120
1122
  "hotline",
1121
1123
  "support",
1122
1124
  "infoline",
@@ -2,7 +2,7 @@ import {
2
2
  PIIManager,
3
3
  SecurityBlockError,
4
4
  createAgentIdTelemetryContext
5
- } from "./chunk-AIGMQSAV.mjs";
5
+ } from "./chunk-25SZBEYX.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-CxVUF_eo.mjs';
2
+ import { T as TransparencyMetadata } from './agentid-BWlN5KCq.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-CxVUF_eo.js';
2
+ import { T as TransparencyMetadata } from './agentid-BWlN5KCq.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.38",
3
+ "version": "0.1.40",
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",