langchain 1.0.3 → 1.0.5
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/CHANGELOG.md +21 -0
- package/dist/agents/ReactAgent.cjs +15 -17
- package/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.d.cts +3 -3
- package/dist/agents/ReactAgent.d.cts.map +1 -1
- package/dist/agents/ReactAgent.d.ts +3 -3
- package/dist/agents/ReactAgent.d.ts.map +1 -1
- package/dist/agents/ReactAgent.js +15 -17
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/annotation.cjs +6 -4
- package/dist/agents/annotation.cjs.map +1 -1
- package/dist/agents/annotation.js +7 -5
- package/dist/agents/annotation.js.map +1 -1
- package/dist/agents/middleware/contextEditing.cjs +302 -33
- package/dist/agents/middleware/contextEditing.cjs.map +1 -1
- package/dist/agents/middleware/contextEditing.d.cts +125 -41
- package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
- package/dist/agents/middleware/contextEditing.d.ts +125 -41
- package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
- package/dist/agents/middleware/contextEditing.js +302 -33
- package/dist/agents/middleware/contextEditing.js.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
- package/dist/agents/middleware/hitl.d.cts.map +1 -1
- package/dist/agents/middleware/hitl.d.ts.map +1 -1
- package/dist/agents/middleware/index.cjs +2 -0
- package/dist/agents/middleware/index.js +2 -0
- package/dist/agents/middleware/modelCallLimit.cjs +6 -2
- package/dist/agents/middleware/modelCallLimit.cjs.map +1 -1
- package/dist/agents/middleware/modelCallLimit.d.cts +8 -8
- package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/modelCallLimit.d.ts +8 -8
- package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/modelCallLimit.js +6 -2
- package/dist/agents/middleware/modelCallLimit.js.map +1 -1
- package/dist/agents/middleware/modelFallback.cjs +2 -2
- package/dist/agents/middleware/modelFallback.cjs.map +1 -1
- package/dist/agents/middleware/modelFallback.d.cts +2 -2
- package/dist/agents/middleware/modelFallback.d.cts.map +1 -1
- package/dist/agents/middleware/modelFallback.d.ts +2 -2
- package/dist/agents/middleware/modelFallback.d.ts.map +1 -1
- package/dist/agents/middleware/modelFallback.js +2 -2
- package/dist/agents/middleware/modelFallback.js.map +1 -1
- package/dist/agents/middleware/pii.cjs +445 -0
- package/dist/agents/middleware/pii.cjs.map +1 -0
- package/dist/agents/middleware/pii.d.cts +216 -0
- package/dist/agents/middleware/pii.d.cts.map +1 -0
- package/dist/agents/middleware/pii.d.ts +216 -0
- package/dist/agents/middleware/pii.d.ts.map +1 -0
- package/dist/agents/middleware/pii.js +436 -0
- package/dist/agents/middleware/pii.js.map +1 -0
- package/dist/agents/middleware/piiRedaction.cjs +2 -1
- package/dist/agents/middleware/piiRedaction.cjs.map +1 -1
- package/dist/agents/middleware/piiRedaction.d.cts +4 -1
- package/dist/agents/middleware/piiRedaction.d.cts.map +1 -1
- package/dist/agents/middleware/piiRedaction.d.ts +4 -1
- package/dist/agents/middleware/piiRedaction.d.ts.map +1 -1
- package/dist/agents/middleware/piiRedaction.js +2 -1
- package/dist/agents/middleware/piiRedaction.js.map +1 -1
- package/dist/agents/middleware/promptCaching.d.cts.map +1 -1
- package/dist/agents/middleware/promptCaching.d.ts.map +1 -1
- package/dist/agents/middleware/summarization.cjs +263 -52
- package/dist/agents/middleware/summarization.cjs.map +1 -1
- package/dist/agents/middleware/summarization.d.cts +384 -26
- package/dist/agents/middleware/summarization.d.cts.map +1 -1
- package/dist/agents/middleware/summarization.d.ts +384 -26
- package/dist/agents/middleware/summarization.d.ts.map +1 -1
- package/dist/agents/middleware/summarization.js +263 -55
- package/dist/agents/middleware/summarization.js.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.cjs +36 -27
- package/dist/agents/middleware/toolCallLimit.cjs.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.cts +3 -1
- package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.ts +3 -1
- package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.js +36 -27
- package/dist/agents/middleware/toolCallLimit.js.map +1 -1
- package/dist/agents/middleware/toolEmulator.cjs +118 -0
- package/dist/agents/middleware/toolEmulator.cjs.map +1 -0
- package/dist/agents/middleware/toolEmulator.d.cts +76 -0
- package/dist/agents/middleware/toolEmulator.d.cts.map +1 -0
- package/dist/agents/middleware/toolEmulator.d.ts +76 -0
- package/dist/agents/middleware/toolEmulator.d.ts.map +1 -0
- package/dist/agents/middleware/toolEmulator.js +117 -0
- package/dist/agents/middleware/toolEmulator.js.map +1 -0
- package/dist/agents/middleware/utils.cjs +4 -0
- package/dist/agents/middleware/utils.cjs.map +1 -1
- package/dist/agents/middleware/utils.d.cts.map +1 -1
- package/dist/agents/middleware/utils.d.ts.map +1 -1
- package/dist/agents/middleware/utils.js +4 -0
- package/dist/agents/middleware/utils.js.map +1 -1
- package/dist/agents/nodes/AgentNode.cjs +1 -5
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +2 -6
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/responses.cjs +0 -1
- package/dist/agents/responses.js +1 -1
- package/dist/agents/runtime.d.cts +5 -5
- package/dist/agents/runtime.d.cts.map +1 -1
- package/dist/agents/runtime.d.ts +5 -5
- package/dist/agents/runtime.d.ts.map +1 -1
- package/dist/index.cjs +22 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -4
- package/dist/index.d.ts +6 -4
- package/dist/index.js +13 -1
- package/dist/index.js.map +1 -1
- package/package.json +10 -9
- package/dist/agents/middleware/callLimit.cjs +0 -130
- package/dist/agents/middleware/callLimit.cjs.map +0 -1
- package/dist/agents/middleware/callLimit.d.cts +0 -119
- package/dist/agents/middleware/callLimit.d.cts.map +0 -1
- package/dist/agents/middleware/callLimit.d.ts +0 -119
- package/dist/agents/middleware/callLimit.d.ts.map +0 -1
- package/dist/agents/middleware/callLimit.js +0 -129
- package/dist/agents/middleware/callLimit.js.map +0 -1
- package/dist/agents/middleware/index.d.cts +0 -15
- package/dist/agents/middleware/index.d.ts +0 -14
- package/dist/agents/tools.d.cts +0 -9
- package/dist/agents/tools.d.cts.map +0 -1
- package/dist/agents/tools.d.ts +0 -9
- package/dist/agents/tools.d.ts.map +0 -1
- package/dist/embeddings/cache_backed.cjs +0 -140
- package/dist/embeddings/cache_backed.cjs.map +0 -1
- package/dist/embeddings/cache_backed.d.cts +0 -107
- package/dist/embeddings/cache_backed.d.cts.map +0 -1
- package/dist/embeddings/cache_backed.d.ts +0 -107
- package/dist/embeddings/cache_backed.d.ts.map +0 -1
- package/dist/embeddings/cache_backed.js +0 -134
- package/dist/embeddings/cache_backed.js.map +0 -1
- package/dist/embeddings/fake.cjs +0 -22
- package/dist/embeddings/fake.cjs.map +0 -1
- package/dist/embeddings/fake.d.cts +0 -1
- package/dist/embeddings/fake.d.ts +0 -1
- package/dist/embeddings/fake.js +0 -12
- package/dist/embeddings/fake.js.map +0 -1
- package/dist/node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.cjs +0 -248
- package/dist/node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.cjs.map +0 -1
- package/dist/node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js +0 -244
- package/dist/node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/client.cjs +0 -3096
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/client.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/client.js +0 -3095
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/client.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/env.cjs +0 -12
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/env.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/env.js +0 -12
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/env.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/constants.cjs +0 -71
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/constants.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/constants.js +0 -38
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/constants.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/translator.cjs +0 -221
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/translator.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/translator.js +0 -221
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/translator.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/index.cjs +0 -11
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/index.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/index.js +0 -11
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/index.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/run_trees.cjs +0 -703
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/run_trees.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/run_trees.js +0 -702
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/run_trees.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/constants.cjs +0 -7
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/constants.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/constants.js +0 -6
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/constants.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/fetch.cjs +0 -29
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/fetch.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/fetch.js +0 -28
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/fetch.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/otel.cjs +0 -115
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/otel.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/otel.js +0 -113
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/otel.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/_uuid.cjs +0 -14
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/_uuid.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/_uuid.js +0 -13
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/_uuid.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/async_caller.cjs +0 -95
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/async_caller.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/async_caller.js +0 -95
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/async_caller.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/env.cjs +0 -136
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/env.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/env.js +0 -131
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/env.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/error.cjs +0 -102
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/error.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/error.js +0 -99
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/error.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/fast-safe-stringify/index.cjs +0 -140
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/fast-safe-stringify/index.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/fast-safe-stringify/index.js +0 -140
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/fast-safe-stringify/index.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/messages.cjs +0 -18
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/messages.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/messages.js +0 -16
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/messages.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/project.cjs +0 -10
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/project.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/project.js +0 -10
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/project.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/prompts.cjs +0 -30
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/prompts.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/prompts.js +0 -30
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/prompts.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/warn.cjs +0 -13
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/warn.cjs.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/warn.js +0 -12
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/warn.js.map +0 -1
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/index.cjs +0 -6
- package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/index.js +0 -6
- package/dist/node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.cjs +0 -27
- package/dist/node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.cjs.map +0 -1
- package/dist/node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.js +0 -23
- package/dist/node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.js.map +0 -1
- package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.cjs +0 -267
- package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.cjs.map +0 -1
- package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.js +0 -263
- package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.js.map +0 -1
- package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/lower-bound.cjs +0 -32
- package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/lower-bound.cjs.map +0 -1
- package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/lower-bound.js +0 -28
- package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/lower-bound.js.map +0 -1
- package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/priority-queue.cjs +0 -49
- package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/priority-queue.cjs.map +0 -1
- package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/priority-queue.js +0 -45
- package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/priority-queue.js.map +0 -1
- package/dist/node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.cjs +0 -83
- package/dist/node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.cjs.map +0 -1
- package/dist/node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.js +0 -79
- package/dist/node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.js.map +0 -1
- package/dist/node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.cjs +0 -52
- package/dist/node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.cjs.map +0 -1
- package/dist/node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.js +0 -48
- package/dist/node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.js.map +0 -1
- package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.cjs +0 -16
- package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.cjs.map +0 -1
- package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js +0 -13
- package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js.map +0 -1
- package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.cjs +0 -77
- package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.cjs.map +0 -1
- package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js +0 -74
- package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js.map +0 -1
- package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.cjs +0 -115
- package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.cjs.map +0 -1
- package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js +0 -112
- package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.cjs +0 -90
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.js +0 -86
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.cjs +0 -294
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.js +0 -290
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.cjs +0 -191
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js +0 -187
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.cjs +0 -24
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.js +0 -20
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.cjs +0 -51
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.js +0 -47
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.cjs +0 -48
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.js +0 -44
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.cjs +0 -25
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.js +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.cjs +0 -43
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.js +0 -39
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.cjs +0 -32
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.js +0 -28
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.cjs +0 -29
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.js +0 -25
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.cjs +0 -24
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.js +0 -20
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.cjs +0 -28
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.js +0 -24
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.cjs +0 -24
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js +0 -20
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.cjs +0 -146
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.js +0 -142
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.cjs +0 -41
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js +0 -37
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.cjs +0 -19
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js +0 -15
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.cjs +0 -32
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js +0 -28
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.cjs +0 -47
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.js +0 -43
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.cjs +0 -25
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.cjs +0 -94
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js +0 -90
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.cjs +0 -25
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.js +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.cjs +0 -41
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.js +0 -37
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.cjs +0 -41
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.js +0 -37
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.cjs +0 -55
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.js +0 -51
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.cjs +0 -74
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.js +0 -70
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.cjs +0 -48
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.js +0 -44
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.cjs +0 -112
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.js +0 -108
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.cjs +0 -21
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.js +0 -17
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.js.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.cjs +0 -27
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.cjs.map +0 -1
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.js +0 -23
- package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.js.map +0 -1
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
import { createMiddleware } from "../middleware.js";
|
|
2
|
+
import { AIMessage, HumanMessage, ToolMessage } from "@langchain/core/messages";
|
|
3
|
+
import { z } from "zod/v3";
|
|
4
|
+
import { sha256 } from "@langchain/core/utils/hash";
|
|
5
|
+
|
|
6
|
+
//#region src/agents/middleware/pii.ts
|
|
7
|
+
/**
|
|
8
|
+
* Error thrown when PII is detected and strategy is 'block'
|
|
9
|
+
*/
|
|
10
|
+
var PIIDetectionError = class extends Error {
|
|
11
|
+
constructor(piiType, matches) {
|
|
12
|
+
super(`PII detected: ${piiType} found ${matches.length} occurrence(s)`);
|
|
13
|
+
this.piiType = piiType;
|
|
14
|
+
this.matches = matches;
|
|
15
|
+
this.name = "PIIDetectionError";
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Email detection regex pattern
|
|
20
|
+
*/
|
|
21
|
+
const EMAIL_PATTERN = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
|
|
22
|
+
/**
|
|
23
|
+
* Credit card detection regex pattern (basic, will be validated with Luhn)
|
|
24
|
+
*/
|
|
25
|
+
const CREDIT_CARD_PATTERN = /\b(?:\d{4}[-\s]?){3}\d{4}\b/g;
|
|
26
|
+
/**
|
|
27
|
+
* IP address detection regex pattern
|
|
28
|
+
*/
|
|
29
|
+
const IP_PATTERN = /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g;
|
|
30
|
+
/**
|
|
31
|
+
* MAC address detection regex pattern
|
|
32
|
+
*/
|
|
33
|
+
const MAC_ADDRESS_PATTERN = /\b(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})\b/g;
|
|
34
|
+
/**
|
|
35
|
+
* URL detection regex pattern
|
|
36
|
+
*/
|
|
37
|
+
const URL_PATTERN = /(?:https?:\/\/|www\.)[^\s<>"{}|\\^`[\]]+/gi;
|
|
38
|
+
/**
|
|
39
|
+
* Luhn algorithm for credit card validation
|
|
40
|
+
*/
|
|
41
|
+
function luhnCheck(cardNumber) {
|
|
42
|
+
const digits = cardNumber.replace(/\D/g, "");
|
|
43
|
+
let sum = 0;
|
|
44
|
+
let isEven = false;
|
|
45
|
+
for (let i = digits.length - 1; i >= 0; i--) {
|
|
46
|
+
let digit = parseInt(digits[i], 10);
|
|
47
|
+
if (isEven) {
|
|
48
|
+
digit *= 2;
|
|
49
|
+
if (digit > 9) digit -= 9;
|
|
50
|
+
}
|
|
51
|
+
sum += digit;
|
|
52
|
+
isEven = !isEven;
|
|
53
|
+
}
|
|
54
|
+
return sum % 10 === 0;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Convert regex match to PIIMatch
|
|
58
|
+
*/
|
|
59
|
+
function regexMatchToPIIMatch(match) {
|
|
60
|
+
return {
|
|
61
|
+
text: match[0],
|
|
62
|
+
start: match.index ?? 0,
|
|
63
|
+
end: (match.index ?? 0) + match[0].length
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Detect email addresses in content
|
|
68
|
+
*/
|
|
69
|
+
function detectEmail(content) {
|
|
70
|
+
const matches = [];
|
|
71
|
+
const regex = new RegExp(EMAIL_PATTERN);
|
|
72
|
+
let match;
|
|
73
|
+
while ((match = regex.exec(content)) !== null) matches.push(regexMatchToPIIMatch(match));
|
|
74
|
+
return matches;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Detect credit card numbers in content (validated with Luhn algorithm)
|
|
78
|
+
*/
|
|
79
|
+
function detectCreditCard(content) {
|
|
80
|
+
const matches = [];
|
|
81
|
+
const regex = new RegExp(CREDIT_CARD_PATTERN);
|
|
82
|
+
let match;
|
|
83
|
+
while ((match = regex.exec(content)) !== null) {
|
|
84
|
+
const cardNumber = match[0].replace(/\D/g, "");
|
|
85
|
+
if (cardNumber.length >= 13 && cardNumber.length <= 19 && luhnCheck(cardNumber)) matches.push(regexMatchToPIIMatch(match));
|
|
86
|
+
}
|
|
87
|
+
return matches;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Detect IP addresses in content (validated)
|
|
91
|
+
*/
|
|
92
|
+
function detectIP(content) {
|
|
93
|
+
const matches = [];
|
|
94
|
+
const regex = new RegExp(IP_PATTERN);
|
|
95
|
+
let match;
|
|
96
|
+
while ((match = regex.exec(content)) !== null) {
|
|
97
|
+
const ip = match[0];
|
|
98
|
+
const parts = ip.split(".");
|
|
99
|
+
if (parts.length === 4 && parts.every((part) => {
|
|
100
|
+
const num = parseInt(part, 10);
|
|
101
|
+
return num >= 0 && num <= 255;
|
|
102
|
+
})) matches.push(regexMatchToPIIMatch(match));
|
|
103
|
+
}
|
|
104
|
+
return matches;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Detect MAC addresses in content
|
|
108
|
+
*/
|
|
109
|
+
function detectMacAddress(content) {
|
|
110
|
+
const matches = [];
|
|
111
|
+
const regex = new RegExp(MAC_ADDRESS_PATTERN);
|
|
112
|
+
let match;
|
|
113
|
+
while ((match = regex.exec(content)) !== null) matches.push(regexMatchToPIIMatch(match));
|
|
114
|
+
return matches;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Detect URLs in content
|
|
118
|
+
*/
|
|
119
|
+
function detectUrl(content) {
|
|
120
|
+
const matches = [];
|
|
121
|
+
const regex = new RegExp(URL_PATTERN);
|
|
122
|
+
let match;
|
|
123
|
+
while ((match = regex.exec(content)) !== null) matches.push(regexMatchToPIIMatch(match));
|
|
124
|
+
return matches;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Built-in detector map
|
|
128
|
+
*/
|
|
129
|
+
const BUILT_IN_DETECTORS = {
|
|
130
|
+
email: detectEmail,
|
|
131
|
+
credit_card: detectCreditCard,
|
|
132
|
+
ip: detectIP,
|
|
133
|
+
mac_address: detectMacAddress,
|
|
134
|
+
url: detectUrl
|
|
135
|
+
};
|
|
136
|
+
/**
|
|
137
|
+
* Resolve a redaction rule to a concrete detector function
|
|
138
|
+
*/
|
|
139
|
+
function resolveRedactionRule(config) {
|
|
140
|
+
let detector;
|
|
141
|
+
if (config.detector) if (typeof config.detector === "string") {
|
|
142
|
+
const regex = new RegExp(config.detector, "g");
|
|
143
|
+
detector = (content) => {
|
|
144
|
+
const matches = [];
|
|
145
|
+
let match;
|
|
146
|
+
const regexCopy = new RegExp(regex);
|
|
147
|
+
while ((match = regexCopy.exec(content)) !== null) matches.push(regexMatchToPIIMatch(match));
|
|
148
|
+
return matches;
|
|
149
|
+
};
|
|
150
|
+
} else if (config.detector instanceof RegExp) detector = (content) => {
|
|
151
|
+
if (!(config.detector instanceof RegExp)) throw new Error("Detector is required");
|
|
152
|
+
const matches = [];
|
|
153
|
+
let match;
|
|
154
|
+
while ((match = config.detector.exec(content)) !== null) matches.push(regexMatchToPIIMatch(match));
|
|
155
|
+
return matches;
|
|
156
|
+
};
|
|
157
|
+
else detector = config.detector;
|
|
158
|
+
else {
|
|
159
|
+
const builtInType = config.piiType;
|
|
160
|
+
if (!BUILT_IN_DETECTORS[builtInType]) throw new Error(`Unknown PII type: ${config.piiType}. Must be one of: ${Object.keys(BUILT_IN_DETECTORS).join(", ")}, or provide a custom detector.`);
|
|
161
|
+
detector = BUILT_IN_DETECTORS[builtInType];
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
piiType: config.piiType,
|
|
165
|
+
strategy: config.strategy,
|
|
166
|
+
detector
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Apply redact strategy: replace with [REDACTED_TYPE]
|
|
171
|
+
*/
|
|
172
|
+
function applyRedactStrategy(content, matches, piiType) {
|
|
173
|
+
let result = content;
|
|
174
|
+
for (let i = matches.length - 1; i >= 0; i--) {
|
|
175
|
+
const match = matches[i];
|
|
176
|
+
const replacement = `[REDACTED_${piiType.toUpperCase()}]`;
|
|
177
|
+
result = result.slice(0, match.start) + replacement + result.slice(match.end);
|
|
178
|
+
}
|
|
179
|
+
return result;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Apply mask strategy: partially mask PII (show last few characters)
|
|
183
|
+
*/
|
|
184
|
+
function applyMaskStrategy(content, matches, piiType) {
|
|
185
|
+
let result = content;
|
|
186
|
+
for (let i = matches.length - 1; i >= 0; i--) {
|
|
187
|
+
const match = matches[i];
|
|
188
|
+
const text = match.text;
|
|
189
|
+
let masked;
|
|
190
|
+
if (piiType === "credit_card") {
|
|
191
|
+
const digits = text.replace(/\D/g, "");
|
|
192
|
+
const last4 = digits.slice(-4);
|
|
193
|
+
masked = `****-****-****-${last4}`;
|
|
194
|
+
} else if (piiType === "email") {
|
|
195
|
+
const [local, domain] = text.split("@");
|
|
196
|
+
if (local && domain) masked = `${local[0]}***@${domain}`;
|
|
197
|
+
else masked = "***";
|
|
198
|
+
} else {
|
|
199
|
+
const visibleChars = Math.min(4, text.length);
|
|
200
|
+
masked = `${"*".repeat(Math.max(0, text.length - visibleChars))}${text.slice(-visibleChars)}`;
|
|
201
|
+
}
|
|
202
|
+
result = result.slice(0, match.start) + masked + result.slice(match.end);
|
|
203
|
+
}
|
|
204
|
+
return result;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Apply hash strategy: replace with deterministic hash
|
|
208
|
+
*/
|
|
209
|
+
function applyHashStrategy(content, matches, piiType) {
|
|
210
|
+
let result = content;
|
|
211
|
+
for (let i = matches.length - 1; i >= 0; i--) {
|
|
212
|
+
const match = matches[i];
|
|
213
|
+
const hash = sha256(match.text).slice(0, 8);
|
|
214
|
+
const replacement = `<${piiType}_hash:${hash}>`;
|
|
215
|
+
result = result.slice(0, match.start) + replacement + result.slice(match.end);
|
|
216
|
+
}
|
|
217
|
+
return result;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Apply strategy to content based on matches
|
|
221
|
+
*/
|
|
222
|
+
function applyStrategy(content, matches, strategy, piiType) {
|
|
223
|
+
if (matches.length === 0) return content;
|
|
224
|
+
switch (strategy) {
|
|
225
|
+
case "block": throw new PIIDetectionError(piiType, matches);
|
|
226
|
+
case "redact": return applyRedactStrategy(content, matches, piiType);
|
|
227
|
+
case "mask": return applyMaskStrategy(content, matches, piiType);
|
|
228
|
+
case "hash": return applyHashStrategy(content, matches, piiType);
|
|
229
|
+
default: throw new Error(`Unknown strategy: ${strategy}`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Configuration schema for PII middleware
|
|
234
|
+
*/
|
|
235
|
+
const contextSchema = z.object({
|
|
236
|
+
applyToInput: z.boolean().optional(),
|
|
237
|
+
applyToOutput: z.boolean().optional(),
|
|
238
|
+
applyToToolResults: z.boolean().optional()
|
|
239
|
+
});
|
|
240
|
+
/**
|
|
241
|
+
* Process content for PII detection and apply strategy
|
|
242
|
+
*/
|
|
243
|
+
function processContent(content, rule) {
|
|
244
|
+
const matches = rule.detector(content);
|
|
245
|
+
if (matches.length === 0) return {
|
|
246
|
+
content,
|
|
247
|
+
matches: []
|
|
248
|
+
};
|
|
249
|
+
const sanitized = applyStrategy(content, matches, rule.strategy, rule.piiType);
|
|
250
|
+
return {
|
|
251
|
+
content: sanitized,
|
|
252
|
+
matches
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Creates a middleware that detects and handles personally identifiable information (PII)
|
|
257
|
+
* in conversations.
|
|
258
|
+
*
|
|
259
|
+
* This middleware detects common PII types and applies configurable strategies to handle them.
|
|
260
|
+
* It can detect emails, credit cards, IP addresses, MAC addresses, and URLs in both user input
|
|
261
|
+
* and agent output.
|
|
262
|
+
*
|
|
263
|
+
* Built-in PII types:
|
|
264
|
+
* - `email`: Email addresses
|
|
265
|
+
* - `credit_card`: Credit card numbers (validated with Luhn algorithm)
|
|
266
|
+
* - `ip`: IP addresses (validated)
|
|
267
|
+
* - `mac_address`: MAC addresses
|
|
268
|
+
* - `url`: URLs (both `http`/`https` and bare URLs)
|
|
269
|
+
*
|
|
270
|
+
* Strategies:
|
|
271
|
+
* - `block`: Raise an exception when PII is detected
|
|
272
|
+
* - `redact`: Replace PII with `[REDACTED_TYPE]` placeholders
|
|
273
|
+
* - `mask`: Partially mask PII (e.g., `****-****-****-1234` for credit card)
|
|
274
|
+
* - `hash`: Replace PII with deterministic hash (e.g., `<email_hash:a1b2c3d4>`)
|
|
275
|
+
*
|
|
276
|
+
* Strategy Selection Guide:
|
|
277
|
+
* | Strategy | Preserves Identity? | Best For |
|
|
278
|
+
* | -------- | ------------------- | --------------------------------------- |
|
|
279
|
+
* | `block` | N/A | Avoid PII completely |
|
|
280
|
+
* | `redact` | No | General compliance, log sanitization |
|
|
281
|
+
* | `mask` | No | Human readability, customer service UIs |
|
|
282
|
+
* | `hash` | Yes (pseudonymous) | Analytics, debugging |
|
|
283
|
+
*
|
|
284
|
+
* @param piiType - Type of PII to detect. Can be a built-in type (`email`, `credit_card`, `ip`, `mac_address`, `url`) or a custom type name.
|
|
285
|
+
* @param options - Configuration options
|
|
286
|
+
* @param options.strategy - How to handle detected PII. Defaults to `"redact"`.
|
|
287
|
+
* @param options.detector - Custom detector function or regex pattern string. If not provided, uses built-in detector for the `piiType`.
|
|
288
|
+
* @param options.applyToInput - Whether to check user messages before model call. Defaults to `true`.
|
|
289
|
+
* @param options.applyToOutput - Whether to check AI messages after model call. Defaults to `false`.
|
|
290
|
+
* @param options.applyToToolResults - Whether to check tool result messages after tool execution. Defaults to `false`.
|
|
291
|
+
*
|
|
292
|
+
* @returns Middleware instance for use with `createAgent`
|
|
293
|
+
*
|
|
294
|
+
* @throws {PIIDetectionError} When PII is detected and strategy is `'block'`
|
|
295
|
+
* @throws {Error} If `piiType` is not built-in and no detector is provided
|
|
296
|
+
*
|
|
297
|
+
* @example Basic usage
|
|
298
|
+
* ```typescript
|
|
299
|
+
* import { piiMiddleware } from "langchain";
|
|
300
|
+
* import { createAgent } from "langchain";
|
|
301
|
+
*
|
|
302
|
+
* // Redact all emails in user input
|
|
303
|
+
* const agent = createAgent({
|
|
304
|
+
* model: "openai:gpt-4",
|
|
305
|
+
* middleware: [
|
|
306
|
+
* piiMiddleware("email", { strategy: "redact" }),
|
|
307
|
+
* ],
|
|
308
|
+
* });
|
|
309
|
+
* ```
|
|
310
|
+
*
|
|
311
|
+
* @example Different strategies for different PII types
|
|
312
|
+
* ```typescript
|
|
313
|
+
* const agent = createAgent({
|
|
314
|
+
* model: "openai:gpt-4o",
|
|
315
|
+
* middleware: [
|
|
316
|
+
* piiMiddleware("credit_card", { strategy: "mask" }),
|
|
317
|
+
* piiMiddleware("url", { strategy: "redact" }),
|
|
318
|
+
* piiMiddleware("ip", { strategy: "hash" }),
|
|
319
|
+
* ],
|
|
320
|
+
* });
|
|
321
|
+
* ```
|
|
322
|
+
*
|
|
323
|
+
* @example Custom PII type with regex
|
|
324
|
+
* ```typescript
|
|
325
|
+
* const agent = createAgent({
|
|
326
|
+
* model: "openai:gpt-4",
|
|
327
|
+
* middleware: [
|
|
328
|
+
* piiMiddleware("api_key", {
|
|
329
|
+
* detector: "sk-[a-zA-Z0-9]{32}",
|
|
330
|
+
* strategy: "block",
|
|
331
|
+
* }),
|
|
332
|
+
* ],
|
|
333
|
+
* });
|
|
334
|
+
* ```
|
|
335
|
+
*
|
|
336
|
+
* @public
|
|
337
|
+
*/
|
|
338
|
+
function piiMiddleware(piiType, options = {}) {
|
|
339
|
+
const { strategy = "redact", detector } = options;
|
|
340
|
+
const resolvedRule = resolveRedactionRule({
|
|
341
|
+
piiType,
|
|
342
|
+
strategy,
|
|
343
|
+
detector
|
|
344
|
+
});
|
|
345
|
+
const middlewareName = `PIIMiddleware[${resolvedRule.piiType}]`;
|
|
346
|
+
return createMiddleware({
|
|
347
|
+
name: middlewareName,
|
|
348
|
+
contextSchema,
|
|
349
|
+
beforeModel: async (state, runtime) => {
|
|
350
|
+
const applyToInput = runtime.context.applyToInput ?? options.applyToInput ?? true;
|
|
351
|
+
const applyToToolResults = runtime.context.applyToToolResults ?? options.applyToToolResults ?? false;
|
|
352
|
+
if (!applyToInput && !applyToToolResults) return;
|
|
353
|
+
const messages = state.messages;
|
|
354
|
+
if (!messages || messages.length === 0) return;
|
|
355
|
+
const newMessages = [...messages];
|
|
356
|
+
let anyModified = false;
|
|
357
|
+
if (applyToInput) {
|
|
358
|
+
let lastUserIdx = null;
|
|
359
|
+
for (let i = messages.length - 1; i >= 0; i--) if (HumanMessage.isInstance(messages[i])) {
|
|
360
|
+
lastUserIdx = i;
|
|
361
|
+
break;
|
|
362
|
+
}
|
|
363
|
+
if (lastUserIdx !== null) {
|
|
364
|
+
const lastUserMsg = messages[lastUserIdx];
|
|
365
|
+
if (lastUserMsg && lastUserMsg.content) {
|
|
366
|
+
const content = String(lastUserMsg.content);
|
|
367
|
+
const { content: newContent, matches } = processContent(content, resolvedRule);
|
|
368
|
+
if (matches.length > 0) {
|
|
369
|
+
newMessages[lastUserIdx] = new HumanMessage({
|
|
370
|
+
content: newContent,
|
|
371
|
+
id: lastUserMsg.id,
|
|
372
|
+
name: lastUserMsg.name
|
|
373
|
+
});
|
|
374
|
+
anyModified = true;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (applyToToolResults) {
|
|
380
|
+
let lastAiIdx = null;
|
|
381
|
+
for (let i = messages.length - 1; i >= 0; i--) if (AIMessage.isInstance(messages[i])) {
|
|
382
|
+
lastAiIdx = i;
|
|
383
|
+
break;
|
|
384
|
+
}
|
|
385
|
+
if (lastAiIdx !== null) for (let i = lastAiIdx + 1; i < messages.length; i++) {
|
|
386
|
+
const msg = messages[i];
|
|
387
|
+
if (ToolMessage.isInstance(msg)) {
|
|
388
|
+
if (!msg.content) continue;
|
|
389
|
+
const content = String(msg.content);
|
|
390
|
+
const { content: newContent, matches } = processContent(content, resolvedRule);
|
|
391
|
+
if (matches.length > 0) {
|
|
392
|
+
newMessages[i] = new ToolMessage({
|
|
393
|
+
content: newContent,
|
|
394
|
+
id: msg.id,
|
|
395
|
+
name: msg.name,
|
|
396
|
+
tool_call_id: msg.tool_call_id
|
|
397
|
+
});
|
|
398
|
+
anyModified = true;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (anyModified) return { messages: newMessages };
|
|
404
|
+
},
|
|
405
|
+
afterModel: async (state, runtime) => {
|
|
406
|
+
const applyToOutput = runtime.context.applyToOutput ?? options.applyToOutput ?? false;
|
|
407
|
+
if (!applyToOutput) return;
|
|
408
|
+
const messages = state.messages;
|
|
409
|
+
if (!messages || messages.length === 0) return;
|
|
410
|
+
let lastAiIdx = null;
|
|
411
|
+
let lastAiMsg = null;
|
|
412
|
+
for (let i = messages.length - 1; i >= 0; i--) if (AIMessage.isInstance(messages[i])) {
|
|
413
|
+
lastAiMsg = messages[i];
|
|
414
|
+
lastAiIdx = i;
|
|
415
|
+
break;
|
|
416
|
+
}
|
|
417
|
+
if (lastAiIdx === null || !lastAiMsg || !lastAiMsg.content) return;
|
|
418
|
+
const content = String(lastAiMsg.content);
|
|
419
|
+
const { content: newContent, matches } = processContent(content, resolvedRule);
|
|
420
|
+
if (matches.length === 0) return;
|
|
421
|
+
const updatedMessage = new AIMessage({
|
|
422
|
+
content: newContent,
|
|
423
|
+
id: lastAiMsg.id,
|
|
424
|
+
name: lastAiMsg.name,
|
|
425
|
+
tool_calls: lastAiMsg.tool_calls
|
|
426
|
+
});
|
|
427
|
+
const newMessages = [...messages];
|
|
428
|
+
newMessages[lastAiIdx] = updatedMessage;
|
|
429
|
+
return { messages: newMessages };
|
|
430
|
+
}
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
//#endregion
|
|
435
|
+
export { PIIDetectionError, applyStrategy, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, piiMiddleware, resolveRedactionRule };
|
|
436
|
+
//# sourceMappingURL=pii.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pii.js","names":["piiType: string","matches: PIIMatch[]","cardNumber: string","match: RegExpMatchArray","content: string","match: RegExpMatchArray | null","BUILT_IN_DETECTORS: Record<BuiltInPIIType, PIIDetector>","config: RedactionRuleConfig","detector: PIIDetector","masked: string","strategy: PIIStrategy","rule: ResolvedRedactionRule","piiType: BuiltInPIIType | string","options: {\n strategy?: PIIStrategy;\n detector?: Detector;\n applyToInput?: boolean;\n applyToOutput?: boolean;\n applyToToolResults?: boolean;\n }","lastUserIdx: number | null","lastAiIdx: number | null","lastAiMsg: AIMessage | null"],"sources":["../../../src/agents/middleware/pii.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { sha256 } from \"@langchain/core/utils/hash\";\nimport { AIMessage, HumanMessage, ToolMessage } from \"@langchain/core/messages\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Represents a detected PII match in content\n */\nexport interface PIIMatch {\n /**\n * The matched text\n */\n text: string;\n /**\n * The start index of the match\n */\n start: number;\n /**\n * The end index of the match\n */\n end: number;\n}\n\n/**\n * Error thrown when PII is detected and strategy is 'block'\n */\nexport class PIIDetectionError extends Error {\n constructor(\n public readonly piiType: string,\n public readonly matches: PIIMatch[]\n ) {\n super(`PII detected: ${piiType} found ${matches.length} occurrence(s)`);\n this.name = \"PIIDetectionError\";\n }\n}\n\n/**\n * Strategy for handling detected PII\n */\nexport type PIIStrategy = \"block\" | \"redact\" | \"mask\" | \"hash\";\n\n/**\n * Built-in PII types\n */\nexport type BuiltInPIIType =\n | \"email\"\n | \"credit_card\"\n | \"ip\"\n | \"mac_address\"\n | \"url\";\n\n/**\n * Custom detector function that takes content and returns matches\n */\nexport type PIIDetector = (content: string) => PIIMatch[];\nexport type Detector = PIIDetector | RegExp | string;\n\n/**\n * Configuration for a redaction rule\n */\nexport interface RedactionRuleConfig {\n /**\n * Type of PII to detect (built-in or custom name)\n */\n piiType: BuiltInPIIType | string;\n /**\n * Strategy for handling detected PII\n */\n strategy: PIIStrategy;\n /**\n * Custom detector function or regex pattern string\n */\n detector?: Detector;\n}\n\n/**\n * Resolved redaction rule with a concrete detector function\n */\nexport interface ResolvedRedactionRule {\n piiType: string;\n strategy: PIIStrategy;\n detector: PIIDetector;\n}\n\n/**\n * Email detection regex pattern\n */\nconst EMAIL_PATTERN = /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g;\n\n/**\n * Credit card detection regex pattern (basic, will be validated with Luhn)\n */\nconst CREDIT_CARD_PATTERN = /\\b(?:\\d{4}[-\\s]?){3}\\d{4}\\b/g;\n\n/**\n * IP address detection regex pattern\n */\nconst IP_PATTERN =\n /\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b/g;\n\n/**\n * MAC address detection regex pattern\n */\nconst MAC_ADDRESS_PATTERN = /\\b(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})\\b/g;\n\n/**\n * URL detection regex pattern\n */\nconst URL_PATTERN = /(?:https?:\\/\\/|www\\.)[^\\s<>\"{}|\\\\^`[\\]]+/gi;\n\n/**\n * Luhn algorithm for credit card validation\n */\nfunction luhnCheck(cardNumber: string): boolean {\n const digits = cardNumber.replace(/\\D/g, \"\");\n let sum = 0;\n let isEven = false;\n\n for (let i = digits.length - 1; i >= 0; i--) {\n let digit = parseInt(digits[i], 10);\n\n if (isEven) {\n digit *= 2;\n if (digit > 9) {\n digit -= 9;\n }\n }\n\n sum += digit;\n isEven = !isEven;\n }\n\n return sum % 10 === 0;\n}\n\n/**\n * Convert regex match to PIIMatch\n */\nfunction regexMatchToPIIMatch(match: RegExpMatchArray): PIIMatch {\n return {\n text: match[0],\n start: match.index ?? 0,\n end: (match.index ?? 0) + match[0].length,\n };\n}\n\n/**\n * Detect email addresses in content\n */\nexport function detectEmail(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(EMAIL_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n}\n\n/**\n * Detect credit card numbers in content (validated with Luhn algorithm)\n */\nexport function detectCreditCard(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(CREDIT_CARD_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n const cardNumber = match[0].replace(/\\D/g, \"\");\n // Credit cards are typically 13-19 digits\n if (\n cardNumber.length >= 13 &&\n cardNumber.length <= 19 &&\n luhnCheck(cardNumber)\n ) {\n matches.push(regexMatchToPIIMatch(match));\n }\n }\n\n return matches;\n}\n\n/**\n * Detect IP addresses in content (validated)\n */\nexport function detectIP(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(IP_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n const ip = match[0];\n // Additional validation: each octet should be 0-255\n const parts = ip.split(\".\");\n if (\n parts.length === 4 &&\n parts.every((part) => {\n const num = parseInt(part, 10);\n return num >= 0 && num <= 255;\n })\n ) {\n matches.push(regexMatchToPIIMatch(match));\n }\n }\n\n return matches;\n}\n\n/**\n * Detect MAC addresses in content\n */\nexport function detectMacAddress(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(MAC_ADDRESS_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n}\n\n/**\n * Detect URLs in content\n */\nexport function detectUrl(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(URL_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n}\n\n/**\n * Built-in detector map\n */\nconst BUILT_IN_DETECTORS: Record<BuiltInPIIType, PIIDetector> = {\n email: detectEmail,\n credit_card: detectCreditCard,\n ip: detectIP,\n mac_address: detectMacAddress,\n url: detectUrl,\n};\n\n/**\n * Resolve a redaction rule to a concrete detector function\n */\nexport function resolveRedactionRule(\n config: RedactionRuleConfig\n): ResolvedRedactionRule {\n let detector: PIIDetector;\n\n if (config.detector) {\n if (typeof config.detector === \"string\") {\n // Regex pattern string\n const regex = new RegExp(config.detector, \"g\");\n detector = (content: string) => {\n const matches: PIIMatch[] = [];\n let match: RegExpMatchArray | null;\n const regexCopy = new RegExp(regex);\n\n while ((match = regexCopy.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n };\n // eslint-disable-next-line no-instanceof/no-instanceof\n } else if (config.detector instanceof RegExp) {\n detector = (content: string) => {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (!(config.detector instanceof RegExp)) {\n throw new Error(\"Detector is required\");\n }\n const matches: PIIMatch[] = [];\n let match: RegExpMatchArray | null;\n while ((match = config.detector.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n };\n } else {\n detector = config.detector;\n }\n } else {\n // Use built-in detector\n const builtInType = config.piiType as BuiltInPIIType;\n if (!BUILT_IN_DETECTORS[builtInType]) {\n throw new Error(\n `Unknown PII type: ${config.piiType}. Must be one of: ${Object.keys(\n BUILT_IN_DETECTORS\n ).join(\", \")}, or provide a custom detector.`\n );\n }\n detector = BUILT_IN_DETECTORS[builtInType];\n }\n\n return {\n piiType: config.piiType,\n strategy: config.strategy,\n detector,\n };\n}\n\n/**\n * Apply redact strategy: replace with [REDACTED_TYPE]\n */\nfunction applyRedactStrategy(\n content: string,\n matches: PIIMatch[],\n piiType: string\n): string {\n let result = content;\n // Process matches in reverse order to preserve indices\n for (let i = matches.length - 1; i >= 0; i--) {\n const match = matches[i];\n const replacement = `[REDACTED_${piiType.toUpperCase()}]`;\n result =\n result.slice(0, match.start) + replacement + result.slice(match.end);\n }\n return result;\n}\n\n/**\n * Apply mask strategy: partially mask PII (show last few characters)\n */\nfunction applyMaskStrategy(\n content: string,\n matches: PIIMatch[],\n piiType: string\n): string {\n let result = content;\n // Process matches in reverse order to preserve indices\n for (let i = matches.length - 1; i >= 0; i--) {\n const match = matches[i];\n const text = match.text;\n let masked: string;\n\n if (piiType === \"credit_card\") {\n // Show last 4 digits: ****-****-****-1234\n const digits = text.replace(/\\D/g, \"\");\n const last4 = digits.slice(-4);\n masked = `****-****-****-${last4}`;\n } else if (piiType === \"email\") {\n // Show first char and domain: j***@example.com\n const [local, domain] = text.split(\"@\");\n if (local && domain) {\n masked = `${local[0]}***@${domain}`;\n } else {\n masked = \"***\";\n }\n } else {\n // Default: show last 4 characters\n const visibleChars = Math.min(4, text.length);\n masked = `${\"*\".repeat(\n Math.max(0, text.length - visibleChars)\n )}${text.slice(-visibleChars)}`;\n }\n\n result = result.slice(0, match.start) + masked + result.slice(match.end);\n }\n return result;\n}\n\n/**\n * Apply hash strategy: replace with deterministic hash\n */\nfunction applyHashStrategy(\n content: string,\n matches: PIIMatch[],\n piiType: string\n): string {\n let result = content;\n // Process matches in reverse order to preserve indices\n for (let i = matches.length - 1; i >= 0; i--) {\n const match = matches[i];\n const hash = sha256(match.text).slice(0, 8);\n const replacement = `<${piiType}_hash:${hash}>`;\n result =\n result.slice(0, match.start) + replacement + result.slice(match.end);\n }\n return result;\n}\n\n/**\n * Apply strategy to content based on matches\n */\nexport function applyStrategy(\n content: string,\n matches: PIIMatch[],\n strategy: PIIStrategy,\n piiType: string\n): string {\n if (matches.length === 0) {\n return content;\n }\n\n switch (strategy) {\n case \"block\":\n throw new PIIDetectionError(piiType, matches);\n case \"redact\":\n return applyRedactStrategy(content, matches, piiType);\n case \"mask\":\n return applyMaskStrategy(content, matches, piiType);\n case \"hash\":\n return applyHashStrategy(content, matches, piiType);\n default:\n throw new Error(`Unknown strategy: ${strategy}`);\n }\n}\n\n/**\n * Configuration schema for PII middleware\n */\nconst contextSchema = z.object({\n /**\n * Whether to check user messages before model call\n */\n applyToInput: z.boolean().optional(),\n /**\n * Whether to check AI messages after model call\n */\n applyToOutput: z.boolean().optional(),\n /**\n * Whether to check tool result messages after tool execution\n */\n applyToToolResults: z.boolean().optional(),\n});\n\nexport type PIIMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;\n\n/**\n * Process content for PII detection and apply strategy\n */\nfunction processContent(\n content: string,\n rule: ResolvedRedactionRule\n): { content: string; matches: PIIMatch[] } {\n const matches = rule.detector(content);\n if (matches.length === 0) {\n return { content, matches: [] };\n }\n\n const sanitized = applyStrategy(\n content,\n matches,\n rule.strategy,\n rule.piiType\n );\n return { content: sanitized, matches };\n}\n\n/**\n * Creates a middleware that detects and handles personally identifiable information (PII)\n * in conversations.\n *\n * This middleware detects common PII types and applies configurable strategies to handle them.\n * It can detect emails, credit cards, IP addresses, MAC addresses, and URLs in both user input\n * and agent output.\n *\n * Built-in PII types:\n * - `email`: Email addresses\n * - `credit_card`: Credit card numbers (validated with Luhn algorithm)\n * - `ip`: IP addresses (validated)\n * - `mac_address`: MAC addresses\n * - `url`: URLs (both `http`/`https` and bare URLs)\n *\n * Strategies:\n * - `block`: Raise an exception when PII is detected\n * - `redact`: Replace PII with `[REDACTED_TYPE]` placeholders\n * - `mask`: Partially mask PII (e.g., `****-****-****-1234` for credit card)\n * - `hash`: Replace PII with deterministic hash (e.g., `<email_hash:a1b2c3d4>`)\n *\n * Strategy Selection Guide:\n * | Strategy | Preserves Identity? | Best For |\n * | -------- | ------------------- | --------------------------------------- |\n * | `block` | N/A | Avoid PII completely |\n * | `redact` | No | General compliance, log sanitization |\n * | `mask` | No | Human readability, customer service UIs |\n * | `hash` | Yes (pseudonymous) | Analytics, debugging |\n *\n * @param piiType - Type of PII to detect. Can be a built-in type (`email`, `credit_card`, `ip`, `mac_address`, `url`) or a custom type name.\n * @param options - Configuration options\n * @param options.strategy - How to handle detected PII. Defaults to `\"redact\"`.\n * @param options.detector - Custom detector function or regex pattern string. If not provided, uses built-in detector for the `piiType`.\n * @param options.applyToInput - Whether to check user messages before model call. Defaults to `true`.\n * @param options.applyToOutput - Whether to check AI messages after model call. Defaults to `false`.\n * @param options.applyToToolResults - Whether to check tool result messages after tool execution. Defaults to `false`.\n *\n * @returns Middleware instance for use with `createAgent`\n *\n * @throws {PIIDetectionError} When PII is detected and strategy is `'block'`\n * @throws {Error} If `piiType` is not built-in and no detector is provided\n *\n * @example Basic usage\n * ```typescript\n * import { piiMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * // Redact all emails in user input\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * middleware: [\n * piiMiddleware(\"email\", { strategy: \"redact\" }),\n * ],\n * });\n * ```\n *\n * @example Different strategies for different PII types\n * ```typescript\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [\n * piiMiddleware(\"credit_card\", { strategy: \"mask\" }),\n * piiMiddleware(\"url\", { strategy: \"redact\" }),\n * piiMiddleware(\"ip\", { strategy: \"hash\" }),\n * ],\n * });\n * ```\n *\n * @example Custom PII type with regex\n * ```typescript\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * middleware: [\n * piiMiddleware(\"api_key\", {\n * detector: \"sk-[a-zA-Z0-9]{32}\",\n * strategy: \"block\",\n * }),\n * ],\n * });\n * ```\n *\n * @public\n */\nexport function piiMiddleware(\n piiType: BuiltInPIIType | string,\n options: {\n strategy?: PIIStrategy;\n detector?: Detector;\n applyToInput?: boolean;\n applyToOutput?: boolean;\n applyToToolResults?: boolean;\n } = {}\n): ReturnType<typeof createMiddleware> {\n const { strategy = \"redact\", detector } = options;\n const resolvedRule = resolveRedactionRule({\n piiType,\n strategy,\n detector,\n });\n\n const middlewareName = `PIIMiddleware[${resolvedRule.piiType}]`;\n\n return createMiddleware({\n name: middlewareName,\n contextSchema,\n beforeModel: async (state, runtime) => {\n const applyToInput =\n runtime.context.applyToInput ?? options.applyToInput ?? true;\n const applyToToolResults =\n runtime.context.applyToToolResults ??\n options.applyToToolResults ??\n false;\n\n if (!applyToInput && !applyToToolResults) {\n return;\n }\n\n const messages = state.messages;\n if (!messages || messages.length === 0) {\n return;\n }\n\n const newMessages = [...messages];\n let anyModified = false;\n\n // Check user input if enabled\n if (applyToInput) {\n // Get last user message\n let lastUserIdx: number | null = null;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (HumanMessage.isInstance(messages[i])) {\n lastUserIdx = i;\n break;\n }\n }\n\n if (lastUserIdx !== null) {\n const lastUserMsg = messages[lastUserIdx];\n if (lastUserMsg && lastUserMsg.content) {\n const content = String(lastUserMsg.content);\n const { content: newContent, matches } = processContent(\n content,\n resolvedRule\n );\n\n if (matches.length > 0) {\n newMessages[lastUserIdx] = new HumanMessage({\n content: newContent,\n id: lastUserMsg.id,\n name: lastUserMsg.name,\n });\n anyModified = true;\n }\n }\n }\n }\n\n // Check tool results if enabled\n if (applyToToolResults) {\n // Find the last AIMessage, then process all ToolMessage objects after it\n let lastAiIdx: number | null = null;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (AIMessage.isInstance(messages[i])) {\n lastAiIdx = i;\n break;\n }\n }\n\n if (lastAiIdx !== null) {\n // Get all tool messages after the last AI message\n for (let i = lastAiIdx + 1; i < messages.length; i++) {\n const msg = messages[i];\n if (ToolMessage.isInstance(msg)) {\n if (!msg.content) {\n continue;\n }\n\n const content = String(msg.content);\n const { content: newContent, matches } = processContent(\n content,\n resolvedRule\n );\n\n if (matches.length > 0) {\n newMessages[i] = new ToolMessage({\n content: newContent,\n id: msg.id,\n name: msg.name,\n tool_call_id: msg.tool_call_id,\n });\n anyModified = true;\n }\n }\n }\n }\n }\n\n if (anyModified) {\n return { messages: newMessages };\n }\n\n return;\n },\n afterModel: async (state, runtime) => {\n const applyToOutput =\n runtime.context.applyToOutput ?? options.applyToOutput ?? false;\n\n if (!applyToOutput) {\n return;\n }\n\n const messages = state.messages;\n if (!messages || messages.length === 0) {\n return;\n }\n\n // Get last AI message\n let lastAiIdx: number | null = null;\n let lastAiMsg: AIMessage | null = null;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (AIMessage.isInstance(messages[i])) {\n lastAiMsg = messages[i];\n lastAiIdx = i;\n break;\n }\n }\n\n if (lastAiIdx === null || !lastAiMsg || !lastAiMsg.content) {\n return;\n }\n\n // Detect PII in message content\n const content = String(lastAiMsg.content);\n const { content: newContent, matches } = processContent(\n content,\n resolvedRule\n );\n\n if (matches.length === 0) {\n return;\n }\n\n // Create updated message\n const updatedMessage = new AIMessage({\n content: newContent,\n id: lastAiMsg.id,\n name: lastAiMsg.name,\n tool_calls: lastAiMsg.tool_calls,\n });\n\n // Return updated messages\n const newMessages = [...messages];\n newMessages[lastAiIdx] = updatedMessage;\n return { messages: newMessages };\n },\n });\n}\n"],"mappings":";;;;;;;;;AA4BA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,YACkBA,SACAC,SAChB;EACA,MAAM,CAAC,cAAc,EAAE,QAAQ,OAAO,EAAE,QAAQ,OAAO,cAAc,CAAC,CAAC;EAHvD;EACA;EAGhB,KAAK,OAAO;CACb;AACF;;;;AAqDD,MAAM,gBAAgB;;;;AAKtB,MAAM,sBAAsB;;;;AAK5B,MAAM,aACJ;;;;AAKF,MAAM,sBAAsB;;;;AAK5B,MAAM,cAAc;;;;AAKpB,SAAS,UAAUC,YAA6B;CAC9C,MAAM,SAAS,WAAW,QAAQ,OAAO,GAAG;CAC5C,IAAI,MAAM;CACV,IAAI,SAAS;AAEb,MAAK,IAAI,IAAI,OAAO,SAAS,GAAG,KAAK,GAAG,KAAK;EAC3C,IAAI,QAAQ,SAAS,OAAO,IAAI,GAAG;AAEnC,MAAI,QAAQ;GACV,SAAS;AACT,OAAI,QAAQ,GACV,SAAS;EAEZ;EAED,OAAO;EACP,SAAS,CAAC;CACX;AAED,QAAO,MAAM,OAAO;AACrB;;;;AAKD,SAAS,qBAAqBC,OAAmC;AAC/D,QAAO;EACL,MAAM,MAAM;EACZ,OAAO,MAAM,SAAS;EACtB,MAAM,MAAM,SAAS,KAAK,MAAM,GAAG;CACpC;AACF;;;;AAKD,SAAgB,YAAYC,SAA6B;CACvD,MAAMH,UAAsB,CAAE;CAC9B,MAAM,QAAQ,IAAI,OAAO;CACzB,IAAII;AAEJ,SAAQ,QAAQ,MAAM,KAAK,QAAQ,MAAM,MACvC,QAAQ,KAAK,qBAAqB,MAAM,CAAC;AAG3C,QAAO;AACR;;;;AAKD,SAAgB,iBAAiBD,SAA6B;CAC5D,MAAMH,UAAsB,CAAE;CAC9B,MAAM,QAAQ,IAAI,OAAO;CACzB,IAAII;AAEJ,SAAQ,QAAQ,MAA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Y,SAAS,WAAW,EACnC;GAIF,IAAIA,YAA2B;GAC/B,IAAIC,YAA8B;AAClC,QAAK,IAAI,IAAI,SAAS,SAAS,GAAG,KAAK,GAAG,IACxC,KAAI,UAAU,WAAW,SAAS,GAAG,EAAE;IACrC,YAAY,SAAS;IACrB,YAAY;AACZ;GACD;AAGH,OAAI,cAAc,QAAQ,CAAC,aAAa,CAAC,UAAU,QACjD;GAIF,MAAM,UAAU,OAAO,UAAU,QAAQ;GACzC,MAAM,EAAE,SAAS,YAAY,SAAS,GAAG,eACvC,SACA,aACD;AAED,OAAI,QAAQ,WAAW,EACrB;GAIF,MAAM,iBAAiB,IAAI,UAAU;IACnC,SAAS;IACT,IAAI,UAAU;IACd,MAAM,UAAU;IAChB,YAAY,UAAU;GACvB;GAGD,MAAM,cAAc,CAAC,GAAG,QAAS;GACjC,YAAY,aAAa;AACzB,UAAO,EAAE,UAAU,YAAa;EACjC;CACF,EAAC;AACH"}
|
|
@@ -254,10 +254,11 @@ function restoreMessage(message, redactionMap) {
|
|
|
254
254
|
* // Generates markers like: [REDACTED_EMPLOYEE_ID_xyz789]
|
|
255
255
|
* ```
|
|
256
256
|
*
|
|
257
|
-
* @
|
|
257
|
+
* @deprecated
|
|
258
258
|
*/
|
|
259
259
|
function piiRedactionMiddleware(options = {}) {
|
|
260
260
|
const redactionMap = {};
|
|
261
|
+
console.warn("DEPRECATED: piiRedactionMiddleware is deprecated. Please use piiMiddleware instead, go to https://docs.langchain.com/oss/javascript/langchain/middleware/built-in#pii-detection for more information.");
|
|
261
262
|
return require_middleware.createMiddleware({
|
|
262
263
|
name: "PIIRedactionMiddleware",
|
|
263
264
|
contextSchema,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"piiRedaction.cjs","names":["z","text: string","rules: Record<string, RegExp>","redactionMap: RedactionMap","message: BaseMessage","config: ProcessHumanMessageConfig","HumanMessage","ToolMessage","SystemMessage","AIMessage","options: PIIRedactionMiddlewareConfig","createMiddleware","structuredResponse: Record<string, unknown> | undefined","structuredResponse","RemoveMessage"],"sources":["../../../src/agents/middleware/piiRedaction.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport {\n BaseMessage,\n AIMessage,\n HumanMessage,\n ToolMessage,\n RemoveMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Type for the redaction map that stores original values by ID\n */\ntype RedactionMap = Record<string, string>;\n\n/**\n * Configuration schema for the Input Guardrails middleware\n */\nconst contextSchema = z.object({\n /**\n * A record of PII detection rules to apply\n * @default DEFAULT_PII_RULES (with enabled rules only)\n */\n rules: z\n .record(\n z.string(),\n z.instanceof(RegExp).describe(\"Regular expression pattern to match PII\")\n )\n .optional(),\n});\n\nexport type PIIRedactionMiddlewareConfig = InferInteropZodInput<\n typeof contextSchema\n>;\n\n/**\n * Generate a unique ID for a redaction\n */\nfunction generateRedactionId(): string {\n return Math.random().toString(36).substring(2, 11);\n}\n\n/**\n * Apply PII detection rules to text with ID tracking\n */\nfunction applyPIIRules(\n text: string,\n rules: Record<string, RegExp>,\n redactionMap: RedactionMap\n): string {\n let processedText = text;\n\n for (const [name, pattern] of Object.entries(rules)) {\n const replacement = name.toUpperCase().replace(/[^a-zA-Z0-9_-]/g, \"\");\n processedText = processedText.replace(pattern, (match) => {\n const id = generateRedactionId();\n redactionMap[id] = match;\n // Create a trackable replacement like [REDACTED_SSN_abc123]\n return `[REDACTED_${replacement}_${id}]`;\n });\n }\n\n return processedText;\n}\n\ninterface ProcessHumanMessageConfig {\n rules: Record<string, RegExp>;\n redactionMap: RedactionMap;\n}\n\n/**\n * Process a single human message for PII detection and redaction\n */\nasync function processMessage(\n message: BaseMessage,\n config: ProcessHumanMessageConfig\n): Promise<BaseMessage> {\n /**\n * handle basic message types\n */\n if (\n HumanMessage.isInstance(message) ||\n ToolMessage.isInstance(message) ||\n SystemMessage.isInstance(message)\n ) {\n const content = message.content as string;\n const processedContent = await applyPIIRules(\n content,\n config.rules,\n config.redactionMap\n );\n\n if (processedContent !== content) {\n const MessageConstructor = Object.getPrototypeOf(message).constructor;\n return new MessageConstructor({\n ...message,\n content: processedContent,\n });\n }\n\n return message;\n }\n\n /**\n * Handle AI messages\n */\n if (AIMessage.isInstance(message)) {\n const content =\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content);\n const toolCalls = JSON.stringify(message.tool_calls);\n const processedContent = await applyPIIRules(\n content,\n config.rules,\n config.redactionMap\n );\n const processedToolCalls = await applyPIIRules(\n toolCalls,\n config.rules,\n config.redactionMap\n );\n\n if (processedContent !== content || processedToolCalls !== toolCalls) {\n return new AIMessage({\n ...message,\n content:\n typeof message.content === \"string\"\n ? processedContent\n : JSON.parse(processedContent),\n tool_calls: JSON.parse(processedToolCalls),\n });\n }\n\n return message;\n }\n\n throw new Error(`Unsupported message type: ${message.type}`);\n}\n\n/**\n * Restore original values from redacted text using the redaction map\n */\nfunction restoreRedactedValues(\n text: string,\n redactionMap: RedactionMap\n): string {\n let restoredText = text;\n\n // Pattern to match redacted values like [REDACTED_SSN_abc123]\n const redactionPattern = /\\[REDACTED_[A-Z_]+_(\\w+)\\]/g;\n\n restoredText = restoredText.replace(redactionPattern, (match, id) => {\n if (redactionMap[id]) {\n return redactionMap[id];\n }\n return match; // Keep original if no mapping found\n });\n\n return restoredText;\n}\n\n/**\n * Restore redacted values in a message (creates a new message object)\n */\nfunction restoreMessage(\n message: BaseMessage,\n redactionMap: RedactionMap\n): { message: BaseMessage; changed: boolean } {\n /**\n * handle basic message types\n */\n if (\n HumanMessage.isInstance(message) ||\n ToolMessage.isInstance(message) ||\n SystemMessage.isInstance(message)\n ) {\n const content = message.content as string;\n const restoredContent = restoreRedactedValues(content, redactionMap);\n if (restoredContent !== content) {\n const MessageConstructor = Object.getPrototypeOf(message).constructor;\n const newMessage = new MessageConstructor({\n ...message,\n content: restoredContent,\n });\n return { message: newMessage, changed: true };\n }\n return { message, changed: false };\n }\n\n /**\n * handle AI messages\n */\n if (AIMessage.isInstance(message)) {\n const content =\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content);\n const toolCalls = JSON.stringify(message.tool_calls);\n const processedContent = restoreRedactedValues(content, redactionMap);\n const processedToolCalls = restoreRedactedValues(toolCalls, redactionMap);\n if (processedContent !== content || processedToolCalls !== toolCalls) {\n return {\n message: new AIMessage({\n ...message,\n content:\n typeof message.content === \"string\"\n ? processedContent\n : JSON.parse(processedContent),\n tool_calls: JSON.parse(processedToolCalls),\n }),\n changed: true,\n };\n }\n\n return { message, changed: false };\n }\n\n throw new Error(`Unsupported message type: ${message.type}`);\n}\n\n/**\n * Creates a middleware that detects and redacts personally identifiable information (PII)\n * from messages before they are sent to model providers, and restores original values\n * in model responses for tool execution.\n *\n * ## Mechanism\n *\n * The middleware intercepts agent execution at two points:\n *\n * ### Request Phase (`wrapModelCall`)\n * - Applies regex-based pattern matching to all message content (HumanMessage, ToolMessage, SystemMessage, AIMessage)\n * - Processes both message text and AIMessage tool call arguments\n * - Each matched pattern generates:\n * - Unique identifier: `generateRedactionId()` → `\"abc123\"`\n * - Redaction marker: `[REDACTED_{RULE_NAME}_{ID}]` → `\"[REDACTED_SSN_abc123]\"`\n * - Redaction map entry: `{ \"abc123\": \"123-45-6789\" }`\n * - Returns modified request with redacted message content\n *\n * ### Response Phase (`afterModel`)\n * - Scans AIMessage responses for redaction markers matching pattern: `/\\[REDACTED_[A-Z_]+_(\\w+)\\]/g`\n * - Replaces markers with original values from redaction map\n * - Handles both standard responses and structured output (via tool calls or JSON content)\n * - For structured output, restores values in both the tool call arguments and the `structuredResponse` state field\n * - Returns new message instances via RemoveMessage/AIMessage to update state\n *\n * ## Data Flow\n *\n * ```\n * User Input: \"My SSN is 123-45-6789\"\n * ↓ [beforeModel]\n * Model Request: \"My SSN is [REDACTED_SSN_abc123]\"\n * ↓ [model invocation]\n * Model Response: tool_call({ \"ssn\": \"[REDACTED_SSN_abc123]\" })\n * ↓ [afterModel]\n * Tool Execution: tool({ \"ssn\": \"123-45-6789\" })\n * ```\n *\n * ## Limitations\n *\n * This middleware provides model provider isolation only. PII may still be present in:\n * - LangGraph state checkpoints (memory, databases)\n * - Network traffic between client and application server\n * - Application logs and trace data\n * - Tool execution arguments and responses\n * - Final agent output\n *\n * For comprehensive PII protection, implement additional controls at the application,\n * network, and storage layers.\n *\n * @param options - Configuration options\n * @param options.rules - Record of detection rules mapping rule names to regex patterns.\n * Rule names are normalized to uppercase and used in redaction markers.\n * Patterns must use the global flag (`/pattern/g`) to match all occurrences.\n *\n * @returns Middleware instance for use with `createAgent`\n *\n * @example Basic usage with custom rules\n * ```typescript\n * import { piiRedactionMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod/v3\";\n *\n * const PII_RULES = {\n * ssn: /\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g,\n * email: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n * phone: /\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b/g,\n * };\n *\n * const lookupUser = tool(async ({ ssn }) => {\n * // Receives original value: \"123-45-6789\"\n * return { name: \"John Doe\", account: \"active\" };\n * }, {\n * name: \"lookup_user\",\n * description: \"Look up user by SSN\",\n * schema: z.object({ ssn: z.string() })\n * });\n *\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4\" }),\n * tools: [lookupUser],\n * middleware: [piiRedactionMiddleware({ rules: PII_RULES })]\n * });\n *\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Look up SSN 123-45-6789\")]\n * });\n * // Model request: \"Look up SSN [REDACTED_SSN_abc123]\"\n * // Model response: tool_call({ \"ssn\": \"[REDACTED_SSN_abc123]\" })\n * // Tool receives: { \"ssn\": \"123-45-6789\" }\n * ```\n *\n * @example Runtime rule configuration via context\n * ```typescript\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4\" }),\n * tools: [someTool],\n * middleware: [piiRedactionMiddleware()]\n * });\n *\n * // Configure rules at runtime via middleware context\n * const result = await agent.invoke(\n * { messages: [new HumanMessage(\"...\")] },\n * {\n * configurable: {\n * PIIRedactionMiddleware: {\n * rules: {\n * ssn: /\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g,\n * email: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n * }\n * }\n * }\n * }\n * );\n * ```\n *\n * @example Custom rule patterns\n * ```typescript\n * const customRules = {\n * employee_id: /EMP-\\d{6}/g,\n * api_key: /sk-[a-zA-Z0-9]{32}/g,\n * credit_card: /\\b\\d{4}[- ]?\\d{4}[- ]?\\d{4}[- ]?\\d{4}\\b/g,\n * };\n *\n * const middleware = piiRedactionMiddleware({ rules: customRules });\n * // Generates markers like: [REDACTED_EMPLOYEE_ID_xyz789]\n * ```\n *\n * @public\n */\nexport function piiRedactionMiddleware(\n options: PIIRedactionMiddlewareConfig = {}\n): ReturnType<typeof createMiddleware> {\n const redactionMap: RedactionMap = {};\n\n return createMiddleware({\n name: \"PIIRedactionMiddleware\",\n contextSchema,\n wrapModelCall: async (request, handler) => {\n /**\n * Merge options with context, following bigTool.ts pattern\n */\n const rules = request.runtime.context.rules ?? options.rules ?? {};\n\n /**\n * If no rules are provided, skip processing\n */\n if (Object.keys(rules).length === 0) {\n return handler(request);\n }\n\n const processedMessages = await Promise.all(\n request.state.messages.map((message: BaseMessage) =>\n processMessage(message, {\n rules,\n redactionMap,\n })\n )\n );\n\n return handler({\n ...request,\n messages: processedMessages,\n });\n },\n afterModel: async (state) => {\n /**\n * If no redactions were made, skip processing\n */\n if (Object.keys(redactionMap).length === 0) {\n return;\n }\n\n const lastMessage = state.messages.at(-1);\n if (!AIMessage.isInstance(lastMessage)) {\n return;\n }\n\n /**\n * In cases where we do structured output via tool calls, we also have to look at the second last message\n * as we add a custom last message to the messages array.\n */\n const secondLastMessage = state.messages.at(-2);\n\n const { message: restoredLastMessage, changed } = restoreMessage(\n lastMessage,\n redactionMap\n );\n\n if (!changed) {\n return;\n }\n\n /**\n * Identify if the last message is a structured response and restore the values if so\n */\n let structuredResponse: Record<string, unknown> | undefined;\n if (\n AIMessage.isInstance(lastMessage) &&\n lastMessage?.tool_calls?.length === 0 &&\n typeof lastMessage.content === \"string\" &&\n lastMessage.content.startsWith(\"{\") &&\n lastMessage.content.endsWith(\"}\")\n ) {\n try {\n structuredResponse = JSON.parse(\n restoreRedactedValues(lastMessage.content, redactionMap)\n );\n } catch {\n // ignore\n }\n }\n\n /**\n * Check if the second last message is a structured response tool call\n */\n const isStructuredResponseToolCall =\n AIMessage.isInstance(secondLastMessage) &&\n secondLastMessage?.tool_calls?.length !== 0 &&\n secondLastMessage?.tool_calls?.some((call) =>\n call.name.startsWith(\"extract-\")\n );\n if (isStructuredResponseToolCall) {\n const {\n message: restoredSecondLastMessage,\n changed: changedSecondLastMessage,\n } = restoreMessage(secondLastMessage, redactionMap);\n const structuredResponseRedacted = secondLastMessage.tool_calls?.find(\n (call) => call.name.startsWith(\"extract-\")\n )?.args;\n const structuredResponse = structuredResponseRedacted\n ? JSON.parse(\n restoreRedactedValues(\n JSON.stringify(structuredResponseRedacted),\n redactionMap\n )\n )\n : undefined;\n if (changed || changedSecondLastMessage) {\n return {\n ...state,\n ...(structuredResponse ? { structuredResponse } : {}),\n messages: [\n new RemoveMessage({ id: secondLastMessage.id as string }),\n new RemoveMessage({ id: lastMessage.id as string }),\n restoredSecondLastMessage,\n restoredLastMessage,\n ],\n };\n }\n }\n\n return {\n ...state,\n ...(structuredResponse ? { structuredResponse } : {}),\n messages: [\n new RemoveMessage({ id: lastMessage.id as string }),\n restoredLastMessage,\n ],\n };\n },\n });\n}\n"],"mappings":";;;;;;;;;AAqBA,MAAM,gBAAgBA,SAAE,OAAO,EAK7B,OAAOA,SACJ,OACCA,SAAE,QAAQ,EAC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,CAEjC,KAAI;IACF,qBAAqB,KAAK,MACxB,sBAAsB,YAAY,SAAS,aAAa,CACzD;GACF,QAAO,CAEP;;;;GAMH,MAAM,+BACJA,oCAAU,WAAW,kBAAkB,IACvC,mBAAmB,YAAY,WAAW,KAC1C,mBAAmB,YAAY,KAAK,CAAC,SACnC,KAAK,KAAK,WAAW,WAAW,CACjC;AACH,OAAI,8BAA8B;IAChC,MAAM,EACJ,SAAS,2BACT,SAAS,0BACV,GAAG,eAAe,mBAAmB,aAAa;IACnD,MAAM,6BAA6B,kBAAkB,YAAY,KAC/D,CAAC,SAAS,KAAK,KAAK,WAAW,WAAW,CAC3C,EAAE;IACH,MAAMI,uBAAqB,6BACvB,KAAK,MACH,sBACE,KAAK,UAAU,2BAA2B,EAC1C,aACD,CACF,GACD;AACJ,QAAI,WAAW,yBACb,QAAO;KACL,GAAG;KACH,GAAIA,uBAAqB,EAAE,yCAAoB,IAAG,CAAE;KACpD,UAAU;MACR,IAAIC,wCAAc,EAAE,IAAI,kBAAkB,GAAc;MACxD,IAAIA,wCAAc,EAAE,IAAI,YAAY,GAAc;MAClD;MACA;KACD;IACF;GAEJ;AAED,UAAO;IACL,GAAG;IACH,GAAI,qBAAqB,EAAE,mBAAoB,IAAG,CAAE;IACpD,UAAU,CACR,IAAIA,wCAAc,EAAE,IAAI,YAAY,GAAc,IAClD,mBACD;GACF;EACF;CACF,EAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"piiRedaction.cjs","names":["z","text: string","rules: Record<string, RegExp>","redactionMap: RedactionMap","message: BaseMessage","config: ProcessHumanMessageConfig","HumanMessage","ToolMessage","SystemMessage","AIMessage","options: PIIRedactionMiddlewareConfig","createMiddleware","structuredResponse: Record<string, unknown> | undefined","structuredResponse","RemoveMessage"],"sources":["../../../src/agents/middleware/piiRedaction.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport {\n BaseMessage,\n AIMessage,\n HumanMessage,\n ToolMessage,\n RemoveMessage,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Type for the redaction map that stores original values by ID\n */\ntype RedactionMap = Record<string, string>;\n\n/**\n * Configuration schema for the Input Guardrails middleware\n */\nconst contextSchema = z.object({\n /**\n * A record of PII detection rules to apply\n * @default DEFAULT_PII_RULES (with enabled rules only)\n */\n rules: z\n .record(\n z.string(),\n z.instanceof(RegExp).describe(\"Regular expression pattern to match PII\")\n )\n .optional(),\n});\n\n/**\n * @deprecated\n */\nexport type PIIRedactionMiddlewareConfig = InferInteropZodInput<\n typeof contextSchema\n>;\n\n/**\n * Generate a unique ID for a redaction\n */\nfunction generateRedactionId(): string {\n return Math.random().toString(36).substring(2, 11);\n}\n\n/**\n * Apply PII detection rules to text with ID tracking\n */\nfunction applyPIIRules(\n text: string,\n rules: Record<string, RegExp>,\n redactionMap: RedactionMap\n): string {\n let processedText = text;\n\n for (const [name, pattern] of Object.entries(rules)) {\n const replacement = name.toUpperCase().replace(/[^a-zA-Z0-9_-]/g, \"\");\n processedText = processedText.replace(pattern, (match) => {\n const id = generateRedactionId();\n redactionMap[id] = match;\n // Create a trackable replacement like [REDACTED_SSN_abc123]\n return `[REDACTED_${replacement}_${id}]`;\n });\n }\n\n return processedText;\n}\n\ninterface ProcessHumanMessageConfig {\n rules: Record<string, RegExp>;\n redactionMap: RedactionMap;\n}\n\n/**\n * Process a single human message for PII detection and redaction\n */\nasync function processMessage(\n message: BaseMessage,\n config: ProcessHumanMessageConfig\n): Promise<BaseMessage> {\n /**\n * handle basic message types\n */\n if (\n HumanMessage.isInstance(message) ||\n ToolMessage.isInstance(message) ||\n SystemMessage.isInstance(message)\n ) {\n const content = message.content as string;\n const processedContent = await applyPIIRules(\n content,\n config.rules,\n config.redactionMap\n );\n\n if (processedContent !== content) {\n const MessageConstructor = Object.getPrototypeOf(message).constructor;\n return new MessageConstructor({\n ...message,\n content: processedContent,\n });\n }\n\n return message;\n }\n\n /**\n * Handle AI messages\n */\n if (AIMessage.isInstance(message)) {\n const content =\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content);\n const toolCalls = JSON.stringify(message.tool_calls);\n const processedContent = await applyPIIRules(\n content,\n config.rules,\n config.redactionMap\n );\n const processedToolCalls = await applyPIIRules(\n toolCalls,\n config.rules,\n config.redactionMap\n );\n\n if (processedContent !== content || processedToolCalls !== toolCalls) {\n return new AIMessage({\n ...message,\n content:\n typeof message.content === \"string\"\n ? processedContent\n : JSON.parse(processedContent),\n tool_calls: JSON.parse(processedToolCalls),\n });\n }\n\n return message;\n }\n\n throw new Error(`Unsupported message type: ${message.type}`);\n}\n\n/**\n * Restore original values from redacted text using the redaction map\n */\nfunction restoreRedactedValues(\n text: string,\n redactionMap: RedactionMap\n): string {\n let restoredText = text;\n\n // Pattern to match redacted values like [REDACTED_SSN_abc123]\n const redactionPattern = /\\[REDACTED_[A-Z_]+_(\\w+)\\]/g;\n\n restoredText = restoredText.replace(redactionPattern, (match, id) => {\n if (redactionMap[id]) {\n return redactionMap[id];\n }\n return match; // Keep original if no mapping found\n });\n\n return restoredText;\n}\n\n/**\n * Restore redacted values in a message (creates a new message object)\n */\nfunction restoreMessage(\n message: BaseMessage,\n redactionMap: RedactionMap\n): { message: BaseMessage; changed: boolean } {\n /**\n * handle basic message types\n */\n if (\n HumanMessage.isInstance(message) ||\n ToolMessage.isInstance(message) ||\n SystemMessage.isInstance(message)\n ) {\n const content = message.content as string;\n const restoredContent = restoreRedactedValues(content, redactionMap);\n if (restoredContent !== content) {\n const MessageConstructor = Object.getPrototypeOf(message).constructor;\n const newMessage = new MessageConstructor({\n ...message,\n content: restoredContent,\n });\n return { message: newMessage, changed: true };\n }\n return { message, changed: false };\n }\n\n /**\n * handle AI messages\n */\n if (AIMessage.isInstance(message)) {\n const content =\n typeof message.content === \"string\"\n ? message.content\n : JSON.stringify(message.content);\n const toolCalls = JSON.stringify(message.tool_calls);\n const processedContent = restoreRedactedValues(content, redactionMap);\n const processedToolCalls = restoreRedactedValues(toolCalls, redactionMap);\n if (processedContent !== content || processedToolCalls !== toolCalls) {\n return {\n message: new AIMessage({\n ...message,\n content:\n typeof message.content === \"string\"\n ? processedContent\n : JSON.parse(processedContent),\n tool_calls: JSON.parse(processedToolCalls),\n }),\n changed: true,\n };\n }\n\n return { message, changed: false };\n }\n\n throw new Error(`Unsupported message type: ${message.type}`);\n}\n\n/**\n * Creates a middleware that detects and redacts personally identifiable information (PII)\n * from messages before they are sent to model providers, and restores original values\n * in model responses for tool execution.\n *\n * ## Mechanism\n *\n * The middleware intercepts agent execution at two points:\n *\n * ### Request Phase (`wrapModelCall`)\n * - Applies regex-based pattern matching to all message content (HumanMessage, ToolMessage, SystemMessage, AIMessage)\n * - Processes both message text and AIMessage tool call arguments\n * - Each matched pattern generates:\n * - Unique identifier: `generateRedactionId()` → `\"abc123\"`\n * - Redaction marker: `[REDACTED_{RULE_NAME}_{ID}]` → `\"[REDACTED_SSN_abc123]\"`\n * - Redaction map entry: `{ \"abc123\": \"123-45-6789\" }`\n * - Returns modified request with redacted message content\n *\n * ### Response Phase (`afterModel`)\n * - Scans AIMessage responses for redaction markers matching pattern: `/\\[REDACTED_[A-Z_]+_(\\w+)\\]/g`\n * - Replaces markers with original values from redaction map\n * - Handles both standard responses and structured output (via tool calls or JSON content)\n * - For structured output, restores values in both the tool call arguments and the `structuredResponse` state field\n * - Returns new message instances via RemoveMessage/AIMessage to update state\n *\n * ## Data Flow\n *\n * ```\n * User Input: \"My SSN is 123-45-6789\"\n * ↓ [beforeModel]\n * Model Request: \"My SSN is [REDACTED_SSN_abc123]\"\n * ↓ [model invocation]\n * Model Response: tool_call({ \"ssn\": \"[REDACTED_SSN_abc123]\" })\n * ↓ [afterModel]\n * Tool Execution: tool({ \"ssn\": \"123-45-6789\" })\n * ```\n *\n * ## Limitations\n *\n * This middleware provides model provider isolation only. PII may still be present in:\n * - LangGraph state checkpoints (memory, databases)\n * - Network traffic between client and application server\n * - Application logs and trace data\n * - Tool execution arguments and responses\n * - Final agent output\n *\n * For comprehensive PII protection, implement additional controls at the application,\n * network, and storage layers.\n *\n * @param options - Configuration options\n * @param options.rules - Record of detection rules mapping rule names to regex patterns.\n * Rule names are normalized to uppercase and used in redaction markers.\n * Patterns must use the global flag (`/pattern/g`) to match all occurrences.\n *\n * @returns Middleware instance for use with `createAgent`\n *\n * @example Basic usage with custom rules\n * ```typescript\n * import { piiRedactionMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod/v3\";\n *\n * const PII_RULES = {\n * ssn: /\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g,\n * email: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n * phone: /\\b\\d{3}[-.]?\\d{3}[-.]?\\d{4}\\b/g,\n * };\n *\n * const lookupUser = tool(async ({ ssn }) => {\n * // Receives original value: \"123-45-6789\"\n * return { name: \"John Doe\", account: \"active\" };\n * }, {\n * name: \"lookup_user\",\n * description: \"Look up user by SSN\",\n * schema: z.object({ ssn: z.string() })\n * });\n *\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4\" }),\n * tools: [lookupUser],\n * middleware: [piiRedactionMiddleware({ rules: PII_RULES })]\n * });\n *\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Look up SSN 123-45-6789\")]\n * });\n * // Model request: \"Look up SSN [REDACTED_SSN_abc123]\"\n * // Model response: tool_call({ \"ssn\": \"[REDACTED_SSN_abc123]\" })\n * // Tool receives: { \"ssn\": \"123-45-6789\" }\n * ```\n *\n * @example Runtime rule configuration via context\n * ```typescript\n * const agent = createAgent({\n * model: new ChatOpenAI({ model: \"gpt-4\" }),\n * tools: [someTool],\n * middleware: [piiRedactionMiddleware()]\n * });\n *\n * // Configure rules at runtime via middleware context\n * const result = await agent.invoke(\n * { messages: [new HumanMessage(\"...\")] },\n * {\n * configurable: {\n * PIIRedactionMiddleware: {\n * rules: {\n * ssn: /\\b\\d{3}-?\\d{2}-?\\d{4}\\b/g,\n * email: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n * }\n * }\n * }\n * }\n * );\n * ```\n *\n * @example Custom rule patterns\n * ```typescript\n * const customRules = {\n * employee_id: /EMP-\\d{6}/g,\n * api_key: /sk-[a-zA-Z0-9]{32}/g,\n * credit_card: /\\b\\d{4}[- ]?\\d{4}[- ]?\\d{4}[- ]?\\d{4}\\b/g,\n * };\n *\n * const middleware = piiRedactionMiddleware({ rules: customRules });\n * // Generates markers like: [REDACTED_EMPLOYEE_ID_xyz789]\n * ```\n *\n * @deprecated\n */\nexport function piiRedactionMiddleware(\n options: PIIRedactionMiddlewareConfig = {}\n): ReturnType<typeof createMiddleware> {\n const redactionMap: RedactionMap = {};\n\n console.warn(\n \"DEPRECATED: piiRedactionMiddleware is deprecated. Please use piiMiddleware instead, go to https://docs.langchain.com/oss/javascript/langchain/middleware/built-in#pii-detection for more information.\"\n );\n\n return createMiddleware({\n name: \"PIIRedactionMiddleware\",\n contextSchema,\n wrapModelCall: async (request, handler) => {\n /**\n * Merge options with context, following bigTool.ts pattern\n */\n const rules = request.runtime.context.rules ?? options.rules ?? {};\n\n /**\n * If no rules are provided, skip processing\n */\n if (Object.keys(rules).length === 0) {\n return handler(request);\n }\n\n const processedMessages = await Promise.all(\n request.state.messages.map((message: BaseMessage) =>\n processMessage(message, {\n rules,\n redactionMap,\n })\n )\n );\n\n return handler({\n ...request,\n messages: processedMessages,\n });\n },\n afterModel: async (state) => {\n /**\n * If no redactions were made, skip processing\n */\n if (Object.keys(redactionMap).length === 0) {\n return;\n }\n\n const lastMessage = state.messages.at(-1);\n if (!AIMessage.isInstance(lastMessage)) {\n return;\n }\n\n /**\n * In cases where we do structured output via tool calls, we also have to look at the second last message\n * as we add a custom last message to the messages array.\n */\n const secondLastMessage = state.messages.at(-2);\n\n const { message: restoredLastMessage, changed } = restoreMessage(\n lastMessage,\n redactionMap\n );\n\n if (!changed) {\n return;\n }\n\n /**\n * Identify if the last message is a structured response and restore the values if so\n */\n let structuredResponse: Record<string, unknown> | undefined;\n if (\n AIMessage.isInstance(lastMessage) &&\n lastMessage?.tool_calls?.length === 0 &&\n typeof lastMessage.content === \"string\" &&\n lastMessage.content.startsWith(\"{\") &&\n lastMessage.content.endsWith(\"}\")\n ) {\n try {\n structuredResponse = JSON.parse(\n restoreRedactedValues(lastMessage.content, redactionMap)\n );\n } catch {\n // ignore\n }\n }\n\n /**\n * Check if the second last message is a structured response tool call\n */\n const isStructuredResponseToolCall =\n AIMessage.isInstance(secondLastMessage) &&\n secondLastMessage?.tool_calls?.length !== 0 &&\n secondLastMessage?.tool_calls?.some((call) =>\n call.name.startsWith(\"extract-\")\n );\n if (isStructuredResponseToolCall) {\n const {\n message: restoredSecondLastMessage,\n changed: changedSecondLastMessage,\n } = restoreMessage(secondLastMessage, redactionMap);\n const structuredResponseRedacted = secondLastMessage.tool_calls?.find(\n (call) => call.name.startsWith(\"extract-\")\n )?.args;\n const structuredResponse = structuredResponseRedacted\n ? JSON.parse(\n restoreRedactedValues(\n JSON.stringify(structuredResponseRedacted),\n redactionMap\n )\n )\n : undefined;\n if (changed || changedSecondLastMessage) {\n return {\n ...state,\n ...(structuredResponse ? { structuredResponse } : {}),\n messages: [\n new RemoveMessage({ id: secondLastMessage.id as string }),\n new RemoveMessage({ id: lastMessage.id as string }),\n restoredSecondLastMessage,\n restoredLastMessage,\n ],\n };\n }\n }\n\n return {\n ...state,\n ...(structuredResponse ? { structuredResponse } : {}),\n messages: [\n new RemoveMessage({ id: lastMessage.id as string }),\n restoredLastMessage,\n ],\n };\n },\n });\n}\n"],"mappings":";;;;;;;;;AAqBA,MAAM,gBAAgBA,SAAE,OAAO,EAK7B,OAAOA,SACJ,OACCA,SAAE,QAAQ,EACVA,SAAE,WAAW,OAAO,CAAC,SAAS,0CAA0C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F,qBAAqB,KAAK,MACxB,sBAAsB,YAAY,SAAS,aAAa,CACzD;GACF,QAAO,CAEP;;;;GAMH,MAAM,+BACJA,oCAAU,WAAW,kBAAkB,IACvC,mBAAmB,YAAY,WAAW,KAC1C,mBAAmB,YAAY,KAAK,CAAC,SACnC,KAAK,KAAK,WAAW,WAAW,CACjC;AACH,OAAI,8BAA8B;IAChC,MAAM,EACJ,SAAS,2BACT,SAAS,0BACV,GAAG,eAAe,mBAAmB,aAAa;IACnD,MAAM,6BAA6B,kBAAkB,YAAY,KAC/D,CAAC,SAAS,KAAK,KAAK,WAAW,WAAW,CAC3C,EAAE;IACH,MAAMI,uBAAqB,6BACvB,KAAK,MACH,sBACE,KAAK,UAAU,2BAA2B,EAC1C,aACD,CACF,GACD;AACJ,QAAI,WAAW,yBACb,QAAO;KACL,GAAG;KACH,GAAIA,uBAAqB,EAAE,yCAAoB,IAAG,CAAE;KACpD,UAAU;MACR,IAAIC,wCAAc,EAAE,IAAI,kBAAkB,GAAc;MACxD,IAAIA,wCAAc,EAAE,IAAI,YAAY,GAAc;MAClD;MACA;KACD;IACF;GAEJ;AAED,UAAO;IACL,GAAG;IACH,GAAI,qBAAqB,EAAE,mBAAoB,IAAG,CAAE;IACpD,UAAU,CACR,IAAIA,wCAAc,EAAE,IAAI,YAAY,GAAc,IAClD,mBACD;GACF;EACF;CACF,EAAC;AACH"}
|
|
@@ -18,6 +18,9 @@ declare const contextSchema: z.ZodObject<{
|
|
|
18
18
|
}, {
|
|
19
19
|
rules?: Record<string, RegExp> | undefined;
|
|
20
20
|
}>;
|
|
21
|
+
/**
|
|
22
|
+
* @deprecated
|
|
23
|
+
*/
|
|
21
24
|
type PIIRedactionMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;
|
|
22
25
|
/**
|
|
23
26
|
* Creates a middleware that detects and redacts personally identifiable information (PII)
|
|
@@ -147,7 +150,7 @@ type PIIRedactionMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;
|
|
|
147
150
|
* // Generates markers like: [REDACTED_EMPLOYEE_ID_xyz789]
|
|
148
151
|
* ```
|
|
149
152
|
*
|
|
150
|
-
* @
|
|
153
|
+
* @deprecated
|
|
151
154
|
*/
|
|
152
155
|
declare function piiRedactionMiddleware(options?: PIIRedactionMiddlewareConfig): ReturnType<typeof createMiddleware>;
|
|
153
156
|
//#endregion
|