agentid-sdk 0.1.30 → 0.1.31

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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 AgentID
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AgentID
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
package/README.md CHANGED
@@ -1,337 +1,337 @@
1
- # agentid-sdk (Node.js / TypeScript)
2
-
3
- [![npm version](https://img.shields.io/npm/v/agentid-sdk.svg)](https://www.npmjs.com/package/agentid-sdk)
4
- [![Node](https://img.shields.io/node/v/agentid-sdk.svg)](https://www.npmjs.com/package/agentid-sdk)
5
- [![Node >=18](https://img.shields.io/badge/node-%3E%3D18-339933.svg)](https://nodejs.org/)
6
- [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
-
8
- ## 1. Introduction
9
-
10
- `agentid-sdk` is the official Node.js/TypeScript SDK for AgentID, an AI security and compliance System of Record. It allows you to gate LLM traffic through guard checks, enforce policy before execution, and capture durable telemetry for audit and governance workflows.
11
-
12
- ### The Mental Model
13
-
14
- AgentID sits between your application and the LLM runtime:
15
-
16
- ```text
17
- User Input -> guard() -> [AgentID Policy] -> verdict
18
- | allowed
19
- v
20
- LLM Provider
21
- v
22
- log() -> [Immutable Ledger]
23
- ```
24
-
25
- - `guard()`: evaluates prompt and context before model execution.
26
- - Model call: executes only if guard verdict is allowed.
27
- - `log()`: persists immutable telemetry (prompt, output, latency) for audit and compliance.
28
-
29
- ## 2. Installation
30
-
31
- ```bash
32
- npm install agentid-sdk
33
- ```
34
-
35
- ## 3. Prerequisites
36
-
37
- 1. Create an account at `https://app.getagentid.com`.
38
- 2. Create an AI system and copy:
39
- - `AGENTID_API_KEY` (for example `sk_live_...`)
40
- - `AGENTID_SYSTEM_ID` (UUID)
41
- 3. If using OpenAI/LangChain, set:
42
- - `OPENAI_API_KEY`
43
-
44
- ```bash
45
- export AGENTID_API_KEY="sk_live_..."
46
- export AGENTID_SYSTEM_ID="00000000-0000-0000-0000-000000000000"
47
- export OPENAI_API_KEY="sk-proj-..."
48
- ```
49
-
50
- ### Compatibility
51
-
52
- - **Node.js:** v18+ / **Python:** 3.9+ (cross-SDK matrix)
53
- - **Thread Safety:** AgentID clients are thread-safe and intended to be instantiated once and reused across concurrent requests.
54
- - **Latency:** async `log()` is non-blocking for model execution paths; sync `guard()` typically adds network latency (commonly ~50-100ms, environment-dependent).
55
-
56
- ## 4. Quickstart
57
-
58
- ```ts
59
- import { AgentID } from "agentid-sdk";
60
-
61
- const agent = new AgentID(); // auto-loads AGENTID_API_KEY
62
- const systemId = process.env.AGENTID_SYSTEM_ID!;
63
-
64
- const verdict = await agent.guard({
65
- system_id: systemId,
66
- input: "Summarize this ticket in one sentence.",
67
- model: "gpt-4o-mini",
68
- user_id: "quickstart-user",
69
- });
70
- if (!verdict.allowed) throw new Error(`Blocked: ${verdict.reason}`);
71
-
72
- await agent.log({
73
- system_id: systemId,
74
- event_id: verdict.client_event_id,
75
- model: "gpt-4o-mini",
76
- input: "Summarize this ticket in one sentence.",
77
- output: "Summary generated.",
78
- metadata: { agent_role: "support-assistant" },
79
- });
80
- ```
81
-
82
- ## 5. Core Integrations
83
-
84
- ### OpenAI Wrapper
85
-
86
- ```bash
87
- npm install agentid-sdk openai
88
- ```
89
-
90
- ```ts
91
- import OpenAI from "openai";
92
- import { AgentID } from "agentid-sdk";
93
-
94
- const agent = new AgentID({
95
- piiMasking: true,
96
- });
97
-
98
- const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY! });
99
- const secured = agent.wrapOpenAI(openai, {
100
- system_id: process.env.AGENTID_SYSTEM_ID!,
101
- user_id: "customer-123",
102
- expected_languages: ["en"],
103
- });
104
-
105
- const response = await secured.chat.completions.create({
106
- model: "gpt-4o-mini",
107
- messages: [{ role: "user", content: "What is the capital of the Czech Republic?" }],
108
- });
109
-
110
- console.log(response.choices[0]?.message?.content ?? "");
111
- ```
112
-
113
- Wrapped OpenAI calls persist telemetry for both regular and streamed completions. For `stream: true`, logging happens when the stream finishes.
114
-
115
- > Scope note: AgentID compliance/risk controls apply to the specific SDK-wrapped LLM calls (`guard()`, `wrapOpenAI()`, LangChain callback-wrapped flows). They do not automatically classify unrelated code paths in your whole monolithic application.
116
-
117
- ### Vercel AI SDK Wrapper
118
-
119
- If your app already uses Vercel AI SDK primitives such as `generateText()` or `streamText()`, prefer the dedicated wrapper package instead of rebuilding the lifecycle manually:
120
-
121
- ```bash
122
- npm install ai agentid-vercel-sdk @ai-sdk/openai
123
- ```
124
-
125
- `agentid-vercel-sdk` keeps AgentID backend-first by default, blocks before provider billing on denied prompts, and finalizes telemetry after completion or stream close.
126
-
127
- ### LangChain Integration
128
-
129
- ```bash
130
- npm install agentid-sdk openai @langchain/core @langchain/openai
131
- ```
132
-
133
- ```ts
134
- import { AgentID } from "agentid-sdk";
135
- import { AgentIDCallbackHandler } from "agentid-sdk/langchain";
136
- import { ChatOpenAI } from "@langchain/openai";
137
- import { ChatPromptTemplate } from "@langchain/core/prompts";
138
- import { StringOutputParser } from "@langchain/core/output_parsers";
139
-
140
- const agent = new AgentID();
141
- const handler = new AgentIDCallbackHandler(agent, {
142
- system_id: process.env.AGENTID_SYSTEM_ID!,
143
- expected_languages: ["en"],
144
- });
145
-
146
- const prompt = ChatPromptTemplate.fromTemplate("Answer in one sentence: {question}");
147
- const model = new ChatOpenAI({
148
- apiKey: process.env.OPENAI_API_KEY!,
149
- model: "gpt-4o-mini",
150
- });
151
- const chain = prompt.pipe(model).pipe(new StringOutputParser());
152
-
153
- const result = await chain.invoke(
154
- { question: "What is the capital of the Czech Republic?" },
155
- { callbacks: [handler] }
156
- );
157
- console.log(result);
158
- ```
159
-
160
- LangChain callbacks log on run completion. Token/cost telemetry for streamed chains depends on the provider exposing usage in the final LangChain result.
161
-
162
- ### Raw Ingest API (Telemetry Only)
163
-
164
- ```ts
165
- import { AgentID } from "agentid-sdk";
166
-
167
- const agent = new AgentID();
168
-
169
- await agent.log({
170
- system_id: process.env.AGENTID_SYSTEM_ID!,
171
- event_type: "complete",
172
- severity: "info",
173
- model: "gpt-4o-mini",
174
- input: "Raw telemetry prompt",
175
- output: '{"ok": true}',
176
- metadata: { agent_role: "batch-worker", channel: "manual_ingest" },
177
- });
178
- ```
179
-
180
- ### Transparency Badge (Article 50 UI Evidence)
181
-
182
- When rendering disclosure UI, log proof-of-render telemetry so you can demonstrate the end-user actually saw the badge.
183
-
184
- ```tsx
185
- import { AgentIDTransparencyBadge } from "agentid-sdk/transparency-badge";
186
-
187
- <AgentIDTransparencyBadge
188
- telemetry={{
189
- systemId: process.env.NEXT_PUBLIC_AGENTID_SYSTEM_ID!,
190
- // Prefer a backend relay endpoint so no secret key is exposed in browser code.
191
- ingestUrl: "/api/agentid/transparency-render",
192
- headers: { "x-agentid-system-id": process.env.NEXT_PUBLIC_AGENTID_SYSTEM_ID! },
193
- userId: "customer-123",
194
- }}
195
- placement="chat-header"
196
- />;
197
- ```
198
-
199
- On mount, the component asynchronously emits `event_type: "transparency_badge_rendered"` to the AgentID ingest endpoint.
200
-
201
- ## 6. Advanced Configuration
202
-
203
- ### Custom identity / role metadata
204
-
205
- ```ts
206
- await agent.guard({
207
- system_id: process.env.AGENTID_SYSTEM_ID!,
208
- input: "Process user request",
209
- user_id: "service:billing-agent",
210
- model: "gpt-4o-mini",
211
- });
212
-
213
- await agent.log({
214
- system_id: process.env.AGENTID_SYSTEM_ID!,
215
- model: "gpt-4o-mini",
216
- input: "Process user request",
217
- output: "Done",
218
- metadata: { agent_role: "billing-agent", environment: "prod" },
219
- });
220
- ```
221
-
222
- ### Strict mode and timeout tuning
223
-
224
- ```ts
225
- const agent = new AgentID({
226
- strictMode: true, // fail-closed on guard connectivity/timeouts
227
- guardTimeoutMs: 10000, // default guard timeout is 10000ms
228
- ingestTimeoutMs: 10000 // default ingest timeout is 10000ms
229
- });
230
- ```
231
-
232
- ### Optional client-side fast fail
233
-
234
- ```ts
235
- const agent = new AgentID({
236
- failureMode: "fail_close",
237
- clientFastFail: true, // opt-in local preflight before /guard
238
- });
239
- ```
240
-
241
- ### Error Handling & Strict Mode
242
-
243
- By default, AgentID is designed to keep your application running if the AgentID API has a timeout or is temporarily unreachable.
244
-
245
- | Mode | Connectivity Failure | LLM Execution | Best For |
246
- | :--- | :--- | :--- | :--- |
247
- | **Default** (Strict Off) | API Timeout / Unreachable | **Fail-Open** (continues) | Standard SaaS, chatbots |
248
- | **Strict Mode** (`strictMode: true`) | API Timeout / Unreachable | Direct `guard()` denies; wrapped flows can apply local fallback first | Healthcare, FinTech, high-risk |
249
-
250
- - `guard()` returns a verdict (`allowed`, `reason`); handle deny paths explicitly.
251
- - `wrapOpenAI()` and LangChain handlers throw `SecurityBlockError` when a prompt is blocked.
252
- - Backend `/guard` is the default authority for prompt injection, DB access, code execution, and PII leakage in SDK-wrapped flows.
253
- - `clientFastFail` / `client_fast_fail` is optional and disabled by default. Enable it only when you explicitly want local preflight before the backend call.
254
- - If backend guard is unreachable and the effective failure mode is `fail_close`, wrapped OpenAI/LangChain flows can run local fallback enforcement. Local hits still block; otherwise the request can continue with fallback telemetry attached.
255
- - If `strictMode` is not explicitly set in SDK code, runtime behavior follows the system configuration from AgentID (`strict_security_mode` / `failure_mode`).
256
- - Ingest retries transient failures (5xx/429) and logs warnings if persistence fails.
257
-
258
- ### Event Identity Model
259
-
260
- For consistent lifecycle correlation in Activity/Prompts, use this model:
261
-
262
- - `client_event_id`: external correlation ID for one end-to-end action.
263
- - `guard_event_id`: ID of the preflight guard event returned by `guard()`.
264
- - `event_id` on `log()`: idempotency key for ingest. In the JS SDK it is canonicalized to `client_event_id` for stable one-row lifecycle updates.
265
-
266
- SDK behavior:
267
-
268
- - `guard()` sends `client_event_id` and returns canonical `client_event_id` + `guard_event_id`.
269
- - `log()` sends:
270
- - `event_id = canonical client_event_id`
271
- - `metadata.client_event_id`
272
- - `metadata.guard_event_id` (when available from wrappers/callbacks)
273
- - `x-correlation-id = client_event_id`
274
- - after a successful primary ingest, SDK wrappers can call `/ingest/finalize` with the same `client_event_id` to attach `sdk_ingest_ms`
275
- - SDK requests include `x-agentid-sdk-version` for telemetry/version diagnostics.
276
-
277
- This keeps Guard + Complete linked under one correlation key while preserving internal event linkage in the dashboard.
278
-
279
- ### SDK Timing Telemetry
280
-
281
- SDK-managed metadata can include:
282
-
283
- - `sdk_config_fetch_ms`: capability/config fetch time before dispatch.
284
- - `sdk_local_scan_ms`: optional local enforcement time (`clientFastFail` or fail-close fallback path).
285
- - `sdk_guard_ms`: backend `/guard` round-trip time observed by the SDK wrapper.
286
- - `sdk_ingest_ms`: post-ingest transport timing finalized by the SDK through `/ingest/finalize` after a successful primary `/ingest`.
287
-
288
- ### Policy-Pack Runtime Telemetry
289
-
290
- When the backend uses compiled policy packs, runtime metadata includes:
291
-
292
- - `policy_pack_version`: active compiled artifact version.
293
- - `policy_pack_fallback`: `true` means fallback detector path was used.
294
- - `policy_pack_details`: optional diagnostic detail for fallback/decision trace.
295
-
296
- Latency interpretation:
297
-
298
- - Activity `Latency (ms)` maps to synchronous processing (`processing_time_ms`).
299
- - Async AI audit time is separate (`ai_audit_duration_ms`) and can be higher.
300
- - First request after warm-up boundaries can be slower than steady-state requests.
301
-
302
- ### Monorepo QA Commands (Maintainers)
303
-
304
- If you are validating runtime in the AgentID monorepo:
305
-
306
- ```bash
307
- npm run qa:policy-pack-bootstrap -- --base-url=http://127.0.0.1:3000/api/v1 --system-id=<SYSTEM_UUID>
308
- npm run bench:policy-pack-hotpath
309
- ```
310
-
311
- PowerShell diagnostics:
312
-
313
- ```powershell
314
- powershell -ExecutionPolicy Bypass -File .\scripts\qa\run-guard-diagnostic.ps1 -BaseUrl http://127.0.0.1:3000/api/v1 -ApiKey $env:AGENTID_API_KEY -SystemId $env:AGENTID_SYSTEM_ID -SkipBenchmark
315
- powershell -ExecutionPolicy Bypass -File .\scripts\qa\run-ai-label-audit-check.ps1 -BaseUrl http://127.0.0.1:3000/api/v1 -ApiKey $env:AGENTID_API_KEY -SystemId $env:AGENTID_SYSTEM_ID -Model gpt-4o-mini
316
- ```
317
-
318
- ## 7. Security & Compliance
319
-
320
- - Backend `/guard` remains the primary enforcement authority by default.
321
- - Optional local PII masking and opt-in `clientFastFail` are available for edge cases.
322
- - Guard checks run pre-execution; ingest + finalize telemetry captures prompt/output lifecycle and SDK timing breakdowns.
323
- - Safe for server and serverless runtimes (including async completion flows).
324
- - Supports compliance and forensics workflows with durable event records.
325
-
326
- ## 8. Support
327
-
328
- - Dashboard: `https://app.getagentid.com`
329
- - Repository: `https://github.com/ondrejsukac-rgb/agentid/tree/main/js-sdk`
330
- - Issues: `https://github.com/ondrejsukac-rgb/agentid/issues`
331
-
332
- ## 9. Publishing Notes (NPM)
333
-
334
- NPM automatically renders `README.md` from the package root during `npm publish`.
335
-
336
- - File location: next to `package.json` in `js-sdk/`.
337
- - No additional NPM config is required for README rendering.
1
+ # agentid-sdk (Node.js / TypeScript)
2
+
3
+ [![npm version](https://img.shields.io/npm/v/agentid-sdk.svg)](https://www.npmjs.com/package/agentid-sdk)
4
+ [![Node](https://img.shields.io/node/v/agentid-sdk.svg)](https://www.npmjs.com/package/agentid-sdk)
5
+ [![Node >=18](https://img.shields.io/badge/node-%3E%3D18-339933.svg)](https://nodejs.org/)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
+
8
+ ## 1. Introduction
9
+
10
+ `agentid-sdk` is the official Node.js/TypeScript SDK for AgentID, an AI security and compliance System of Record. It allows you to gate LLM traffic through guard checks, enforce policy before execution, and capture durable telemetry for audit and governance workflows.
11
+
12
+ ### The Mental Model
13
+
14
+ AgentID sits between your application and the LLM runtime:
15
+
16
+ ```text
17
+ User Input -> guard() -> [AgentID Policy] -> verdict
18
+ | allowed
19
+ v
20
+ LLM Provider
21
+ v
22
+ log() -> [Immutable Ledger]
23
+ ```
24
+
25
+ - `guard()`: evaluates prompt and context before model execution.
26
+ - Model call: executes only if guard verdict is allowed.
27
+ - `log()`: persists immutable telemetry (prompt, output, latency) for audit and compliance.
28
+
29
+ ## 2. Installation
30
+
31
+ ```bash
32
+ npm install agentid-sdk
33
+ ```
34
+
35
+ ## 3. Prerequisites
36
+
37
+ 1. Create an account at `https://app.getagentid.com`.
38
+ 2. Create an AI system and copy:
39
+ - `AGENTID_API_KEY` (for example `sk_live_...`)
40
+ - `AGENTID_SYSTEM_ID` (UUID)
41
+ 3. If using OpenAI/LangChain, set:
42
+ - `OPENAI_API_KEY`
43
+
44
+ ```bash
45
+ export AGENTID_API_KEY="sk_live_..."
46
+ export AGENTID_SYSTEM_ID="00000000-0000-0000-0000-000000000000"
47
+ export OPENAI_API_KEY="sk-proj-..."
48
+ ```
49
+
50
+ ### Compatibility
51
+
52
+ - **Node.js:** v18+ / **Python:** 3.9+ (cross-SDK matrix)
53
+ - **Thread Safety:** AgentID clients are thread-safe and intended to be instantiated once and reused across concurrent requests.
54
+ - **Latency:** async `log()` is non-blocking for model execution paths; sync `guard()` typically adds network latency (commonly ~50-100ms, environment-dependent).
55
+
56
+ ## 4. Quickstart
57
+
58
+ ```ts
59
+ import { AgentID } from "agentid-sdk";
60
+
61
+ const agent = new AgentID(); // auto-loads AGENTID_API_KEY
62
+ const systemId = process.env.AGENTID_SYSTEM_ID!;
63
+
64
+ const verdict = await agent.guard({
65
+ system_id: systemId,
66
+ input: "Summarize this ticket in one sentence.",
67
+ model: "gpt-4o-mini",
68
+ user_id: "quickstart-user",
69
+ });
70
+ if (!verdict.allowed) throw new Error(`Blocked: ${verdict.reason}`);
71
+
72
+ await agent.log({
73
+ system_id: systemId,
74
+ event_id: verdict.client_event_id,
75
+ model: "gpt-4o-mini",
76
+ input: "Summarize this ticket in one sentence.",
77
+ output: "Summary generated.",
78
+ metadata: { agent_role: "support-assistant" },
79
+ });
80
+ ```
81
+
82
+ ## 5. Core Integrations
83
+
84
+ ### OpenAI Wrapper
85
+
86
+ ```bash
87
+ npm install agentid-sdk openai
88
+ ```
89
+
90
+ ```ts
91
+ import OpenAI from "openai";
92
+ import { AgentID } from "agentid-sdk";
93
+
94
+ const agent = new AgentID({
95
+ piiMasking: true,
96
+ });
97
+
98
+ const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY! });
99
+ const secured = agent.wrapOpenAI(openai, {
100
+ system_id: process.env.AGENTID_SYSTEM_ID!,
101
+ user_id: "customer-123",
102
+ expected_languages: ["en"],
103
+ });
104
+
105
+ const response = await secured.chat.completions.create({
106
+ model: "gpt-4o-mini",
107
+ messages: [{ role: "user", content: "What is the capital of the Czech Republic?" }],
108
+ });
109
+
110
+ console.log(response.choices[0]?.message?.content ?? "");
111
+ ```
112
+
113
+ Wrapped OpenAI calls persist telemetry for both regular and streamed completions. For `stream: true`, logging happens when the stream finishes.
114
+
115
+ > Scope note: AgentID compliance/risk controls apply to the specific SDK-wrapped LLM calls (`guard()`, `wrapOpenAI()`, LangChain callback-wrapped flows). They do not automatically classify unrelated code paths in your whole monolithic application.
116
+
117
+ ### Vercel AI SDK Wrapper
118
+
119
+ If your app already uses Vercel AI SDK primitives such as `generateText()` or `streamText()`, prefer the dedicated wrapper package instead of rebuilding the lifecycle manually:
120
+
121
+ ```bash
122
+ npm install ai agentid-vercel-sdk @ai-sdk/openai
123
+ ```
124
+
125
+ `agentid-vercel-sdk` keeps AgentID backend-first by default, blocks before provider billing on denied prompts, and finalizes telemetry after completion or stream close.
126
+
127
+ ### LangChain Integration
128
+
129
+ ```bash
130
+ npm install agentid-sdk openai @langchain/core @langchain/openai
131
+ ```
132
+
133
+ ```ts
134
+ import { AgentID } from "agentid-sdk";
135
+ import { AgentIDCallbackHandler } from "agentid-sdk/langchain";
136
+ import { ChatOpenAI } from "@langchain/openai";
137
+ import { ChatPromptTemplate } from "@langchain/core/prompts";
138
+ import { StringOutputParser } from "@langchain/core/output_parsers";
139
+
140
+ const agent = new AgentID();
141
+ const handler = new AgentIDCallbackHandler(agent, {
142
+ system_id: process.env.AGENTID_SYSTEM_ID!,
143
+ expected_languages: ["en"],
144
+ });
145
+
146
+ const prompt = ChatPromptTemplate.fromTemplate("Answer in one sentence: {question}");
147
+ const model = new ChatOpenAI({
148
+ apiKey: process.env.OPENAI_API_KEY!,
149
+ model: "gpt-4o-mini",
150
+ });
151
+ const chain = prompt.pipe(model).pipe(new StringOutputParser());
152
+
153
+ const result = await chain.invoke(
154
+ { question: "What is the capital of the Czech Republic?" },
155
+ { callbacks: [handler] }
156
+ );
157
+ console.log(result);
158
+ ```
159
+
160
+ LangChain callbacks log on run completion. Token/cost telemetry for streamed chains depends on the provider exposing usage in the final LangChain result.
161
+
162
+ ### Raw Ingest API (Telemetry Only)
163
+
164
+ ```ts
165
+ import { AgentID } from "agentid-sdk";
166
+
167
+ const agent = new AgentID();
168
+
169
+ await agent.log({
170
+ system_id: process.env.AGENTID_SYSTEM_ID!,
171
+ event_type: "complete",
172
+ severity: "info",
173
+ model: "gpt-4o-mini",
174
+ input: "Raw telemetry prompt",
175
+ output: '{"ok": true}',
176
+ metadata: { agent_role: "batch-worker", channel: "manual_ingest" },
177
+ });
178
+ ```
179
+
180
+ ### Transparency Badge (Article 50 UI Evidence)
181
+
182
+ When rendering disclosure UI, log proof-of-render telemetry so you can demonstrate the end-user actually saw the badge.
183
+
184
+ ```tsx
185
+ import { AgentIDTransparencyBadge } from "agentid-sdk/transparency-badge";
186
+
187
+ <AgentIDTransparencyBadge
188
+ telemetry={{
189
+ systemId: process.env.NEXT_PUBLIC_AGENTID_SYSTEM_ID!,
190
+ // Prefer a backend relay endpoint so no secret key is exposed in browser code.
191
+ ingestUrl: "/api/agentid/transparency-render",
192
+ headers: { "x-agentid-system-id": process.env.NEXT_PUBLIC_AGENTID_SYSTEM_ID! },
193
+ userId: "customer-123",
194
+ }}
195
+ placement="chat-header"
196
+ />;
197
+ ```
198
+
199
+ On mount, the component asynchronously emits `event_type: "transparency_badge_rendered"` to the AgentID ingest endpoint.
200
+
201
+ ## 6. Advanced Configuration
202
+
203
+ ### Custom identity / role metadata
204
+
205
+ ```ts
206
+ await agent.guard({
207
+ system_id: process.env.AGENTID_SYSTEM_ID!,
208
+ input: "Process user request",
209
+ user_id: "service:billing-agent",
210
+ model: "gpt-4o-mini",
211
+ });
212
+
213
+ await agent.log({
214
+ system_id: process.env.AGENTID_SYSTEM_ID!,
215
+ model: "gpt-4o-mini",
216
+ input: "Process user request",
217
+ output: "Done",
218
+ metadata: { agent_role: "billing-agent", environment: "prod" },
219
+ });
220
+ ```
221
+
222
+ ### Strict mode and timeout tuning
223
+
224
+ ```ts
225
+ const agent = new AgentID({
226
+ strictMode: true, // fail-closed on guard connectivity/timeouts
227
+ guardTimeoutMs: 10000, // default guard timeout is 10000ms
228
+ ingestTimeoutMs: 10000 // default ingest timeout is 10000ms
229
+ });
230
+ ```
231
+
232
+ ### Optional client-side fast fail
233
+
234
+ ```ts
235
+ const agent = new AgentID({
236
+ failureMode: "fail_close",
237
+ clientFastFail: true, // opt-in local preflight before /guard
238
+ });
239
+ ```
240
+
241
+ ### Error Handling & Strict Mode
242
+
243
+ By default, AgentID is designed to keep your application running if the AgentID API has a timeout or is temporarily unreachable.
244
+
245
+ | Mode | Connectivity Failure | LLM Execution | Best For |
246
+ | :--- | :--- | :--- | :--- |
247
+ | **Default** (Strict Off) | API Timeout / Unreachable | **Fail-Open** (continues) | Standard SaaS, chatbots |
248
+ | **Strict Mode** (`strictMode: true`) | API Timeout / Unreachable | Direct `guard()` denies; wrapped flows can apply local fallback first | Healthcare, FinTech, high-risk |
249
+
250
+ - `guard()` returns a verdict (`allowed`, `reason`); handle deny paths explicitly.
251
+ - `wrapOpenAI()` and LangChain handlers throw `SecurityBlockError` when a prompt is blocked.
252
+ - Backend `/guard` is the default authority for prompt injection, DB access, code execution, and PII leakage in SDK-wrapped flows.
253
+ - `clientFastFail` / `client_fast_fail` is optional and disabled by default. Enable it only when you explicitly want local preflight before the backend call.
254
+ - If backend guard is unreachable and the effective failure mode is `fail_close`, wrapped OpenAI/LangChain flows can run local fallback enforcement. Local hits still block; otherwise the request can continue with fallback telemetry attached.
255
+ - If `strictMode` is not explicitly set in SDK code, runtime behavior follows the system configuration from AgentID (`strict_security_mode` / `failure_mode`).
256
+ - Ingest retries transient failures (5xx/429) and logs warnings if persistence fails.
257
+
258
+ ### Event Identity Model
259
+
260
+ For consistent lifecycle correlation in Activity/Prompts, use this model:
261
+
262
+ - `client_event_id`: external correlation ID for one end-to-end action.
263
+ - `guard_event_id`: ID of the preflight guard event returned by `guard()`.
264
+ - `event_id` on `log()`: idempotency key for ingest. In the JS SDK it is canonicalized to `client_event_id` for stable one-row lifecycle updates.
265
+
266
+ SDK behavior:
267
+
268
+ - `guard()` sends `client_event_id` and returns canonical `client_event_id` + `guard_event_id`.
269
+ - `log()` sends:
270
+ - `event_id = canonical client_event_id`
271
+ - `metadata.client_event_id`
272
+ - `metadata.guard_event_id` (when available from wrappers/callbacks)
273
+ - `x-correlation-id = client_event_id`
274
+ - after a successful primary ingest, SDK wrappers can call `/ingest/finalize` with the same `client_event_id` to attach `sdk_ingest_ms`
275
+ - SDK requests include `x-agentid-sdk-version` for telemetry/version diagnostics.
276
+
277
+ This keeps Guard + Complete linked under one correlation key while preserving internal event linkage in the dashboard.
278
+
279
+ ### SDK Timing Telemetry
280
+
281
+ SDK-managed metadata can include:
282
+
283
+ - `sdk_config_fetch_ms`: capability/config fetch time before dispatch.
284
+ - `sdk_local_scan_ms`: optional local enforcement time (`clientFastFail` or fail-close fallback path).
285
+ - `sdk_guard_ms`: backend `/guard` round-trip time observed by the SDK wrapper.
286
+ - `sdk_ingest_ms`: post-ingest transport timing finalized by the SDK through `/ingest/finalize` after a successful primary `/ingest`.
287
+
288
+ ### Policy-Pack Runtime Telemetry
289
+
290
+ When the backend uses compiled policy packs, runtime metadata includes:
291
+
292
+ - `policy_pack_version`: active compiled artifact version.
293
+ - `policy_pack_fallback`: `true` means fallback detector path was used.
294
+ - `policy_pack_details`: optional diagnostic detail for fallback/decision trace.
295
+
296
+ Latency interpretation:
297
+
298
+ - Activity `Latency (ms)` maps to synchronous processing (`processing_time_ms`).
299
+ - Async AI audit time is separate (`ai_audit_duration_ms`) and can be higher.
300
+ - First request after warm-up boundaries can be slower than steady-state requests.
301
+
302
+ ### Monorepo QA Commands (Maintainers)
303
+
304
+ If you are validating runtime in the AgentID monorepo:
305
+
306
+ ```bash
307
+ npm run qa:policy-pack-bootstrap -- --base-url=http://127.0.0.1:3000/api/v1 --system-id=<SYSTEM_UUID>
308
+ npm run bench:policy-pack-hotpath
309
+ ```
310
+
311
+ PowerShell diagnostics:
312
+
313
+ ```powershell
314
+ powershell -ExecutionPolicy Bypass -File .\scripts\qa\run-guard-diagnostic.ps1 -BaseUrl http://127.0.0.1:3000/api/v1 -ApiKey $env:AGENTID_API_KEY -SystemId $env:AGENTID_SYSTEM_ID -SkipBenchmark
315
+ powershell -ExecutionPolicy Bypass -File .\scripts\qa\run-ai-label-audit-check.ps1 -BaseUrl http://127.0.0.1:3000/api/v1 -ApiKey $env:AGENTID_API_KEY -SystemId $env:AGENTID_SYSTEM_ID -Model gpt-4o-mini
316
+ ```
317
+
318
+ ## 7. Security & Compliance
319
+
320
+ - Backend `/guard` remains the primary enforcement authority by default.
321
+ - Optional local PII masking and opt-in `clientFastFail` are available for edge cases.
322
+ - Guard checks run pre-execution; ingest + finalize telemetry captures prompt/output lifecycle and SDK timing breakdowns.
323
+ - Safe for server and serverless runtimes (including async completion flows).
324
+ - Supports compliance and forensics workflows with durable event records.
325
+
326
+ ## 8. Support
327
+
328
+ - Dashboard: `https://app.getagentid.com`
329
+ - Repository: `https://github.com/ondrejsukac-rgb/agentid/tree/main/js-sdk`
330
+ - Issues: `https://github.com/ondrejsukac-rgb/agentid/issues`
331
+
332
+ ## 9. Publishing Notes (NPM)
333
+
334
+ NPM automatically renders `README.md` from the package root during `npm publish`.
335
+
336
+ - File location: next to `package.json` in `js-sdk/`.
337
+ - No additional NPM config is required for README rendering.
@@ -1810,7 +1810,7 @@ function getInjectionScanner() {
1810
1810
 
1811
1811
  // src/sdk-version.ts
1812
1812
  var FALLBACK_SDK_VERSION = "js-0.0.0-dev";
1813
- var AGENTID_SDK_VERSION_HEADER = "js-0.1.30".trim().length > 0 ? "js-0.1.30" : FALLBACK_SDK_VERSION;
1813
+ var AGENTID_SDK_VERSION_HEADER = "js-0.1.31".trim().length > 0 ? "js-0.1.31" : FALLBACK_SDK_VERSION;
1814
1814
 
1815
1815
  // src/local-security-enforcer.ts
1816
1816
  var DEFAULT_FAIL_OPEN_CONFIG = {
@@ -1922,7 +1922,8 @@ var LocalSecurityEnforcer = class {
1922
1922
  };
1923
1923
 
1924
1924
  // src/capability-config.ts
1925
- var CONFIG_TTL_MS = 5 * 60 * 1e3;
1925
+ var CONFIG_TTL_MS = 15 * 1e3;
1926
+ var CONFIG_FAILURE_FALLBACK_TTL_MS = 2 * 1e3;
1926
1927
  var CONFIG_TIMEOUT_MS = 1500;
1927
1928
  var CONFIG_RETRY_DELAY_MS = 150;
1928
1929
  var MAX_CAPABILITY_CACHE_ENTRIES = 500;
@@ -2145,10 +2146,11 @@ async function ensureCapabilityConfig(params) {
2145
2146
  }).catch((error) => {
2146
2147
  const message = error instanceof Error ? error.message : String(error);
2147
2148
  const fallbackConfig = existing?.config ?? DEFAULT_FAIL_OPEN_CONFIG;
2149
+ const fallbackTtlMs = Math.min(ttlMs, CONFIG_FAILURE_FALLBACK_TTL_MS);
2148
2150
  console.warn("AgentID Config unreachable. Defaulting to FAIL-OPEN MODE.", message);
2149
2151
  cache.set(key, {
2150
2152
  config: fallbackConfig,
2151
- expiresAt: Date.now() + ttlMs,
2153
+ expiresAt: Date.now() + fallbackTtlMs,
2152
2154
  promise: null
2153
2155
  });
2154
2156
  enforceCacheBound(cache);
package/dist/index.js CHANGED
@@ -75,7 +75,7 @@ var OpenAIAdapter = class {
75
75
 
76
76
  // src/sdk-version.ts
77
77
  var FALLBACK_SDK_VERSION = "js-0.0.0-dev";
78
- var AGENTID_SDK_VERSION_HEADER = "js-0.1.30".trim().length > 0 ? "js-0.1.30" : FALLBACK_SDK_VERSION;
78
+ var AGENTID_SDK_VERSION_HEADER = "js-0.1.31".trim().length > 0 ? "js-0.1.31" : FALLBACK_SDK_VERSION;
79
79
 
80
80
  // src/pii-national-identifiers.ts
81
81
  var MAX_CANDIDATES_PER_RULE = 256;
@@ -1296,7 +1296,8 @@ var LocalSecurityEnforcer = class {
1296
1296
  };
1297
1297
 
1298
1298
  // src/capability-config.ts
1299
- var CONFIG_TTL_MS = 5 * 60 * 1e3;
1299
+ var CONFIG_TTL_MS = 15 * 1e3;
1300
+ var CONFIG_FAILURE_FALLBACK_TTL_MS = 2 * 1e3;
1300
1301
  var CONFIG_TIMEOUT_MS = 1500;
1301
1302
  var CONFIG_RETRY_DELAY_MS = 150;
1302
1303
  var MAX_CAPABILITY_CACHE_ENTRIES = 500;
@@ -1519,10 +1520,11 @@ async function ensureCapabilityConfig(params) {
1519
1520
  }).catch((error) => {
1520
1521
  const message = error instanceof Error ? error.message : String(error);
1521
1522
  const fallbackConfig = existing?.config ?? DEFAULT_FAIL_OPEN_CONFIG;
1523
+ const fallbackTtlMs = Math.min(ttlMs, CONFIG_FAILURE_FALLBACK_TTL_MS);
1522
1524
  console.warn("AgentID Config unreachable. Defaulting to FAIL-OPEN MODE.", message);
1523
1525
  cache.set(key, {
1524
1526
  config: fallbackConfig,
1525
- expiresAt: Date.now() + ttlMs,
1527
+ expiresAt: Date.now() + fallbackTtlMs,
1526
1528
  promise: null
1527
1529
  });
1528
1530
  enforceCacheBound(cache);
package/dist/index.mjs CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  SecurityBlockError,
8
8
  getInjectionScanner,
9
9
  scanWithRegex
10
- } from "./chunk-W3LROAHO.mjs";
10
+ } from "./chunk-WGJ7SVQB.mjs";
11
11
  export {
12
12
  AgentID,
13
13
  DependencyError,
package/dist/langchain.js CHANGED
@@ -27,7 +27,7 @@ var import_base = require("@langchain/core/callbacks/base");
27
27
 
28
28
  // src/sdk-version.ts
29
29
  var FALLBACK_SDK_VERSION = "js-0.0.0-dev";
30
- var AGENTID_SDK_VERSION_HEADER = "js-0.1.30".trim().length > 0 ? "js-0.1.30" : FALLBACK_SDK_VERSION;
30
+ var AGENTID_SDK_VERSION_HEADER = "js-0.1.31".trim().length > 0 ? "js-0.1.31" : FALLBACK_SDK_VERSION;
31
31
 
32
32
  // src/pii-national-identifiers.ts
33
33
  var REGION_ANCHORS = {
@@ -200,7 +200,8 @@ var PHONE_CONTEXT_RE = new RegExp(
200
200
  );
201
201
 
202
202
  // src/capability-config.ts
203
- var CONFIG_TTL_MS = 5 * 60 * 1e3;
203
+ var CONFIG_TTL_MS = 15 * 1e3;
204
+ var CONFIG_FAILURE_FALLBACK_TTL_MS = 2 * 1e3;
204
205
 
205
206
  // src/agentid.ts
206
207
  var SecurityBlockError = class extends Error {
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  SecurityBlockError
3
- } from "./chunk-W3LROAHO.mjs";
3
+ } from "./chunk-WGJ7SVQB.mjs";
4
4
 
5
5
  // src/langchain.ts
6
6
  import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
package/package.json CHANGED
@@ -1,69 +1,69 @@
1
- {
2
- "name": "agentid-sdk",
3
- "version": "0.1.30",
4
- "description": "AgentID JavaScript/TypeScript SDK for guard, ingest, tracing, and analytics.",
5
- "license": "MIT",
6
- "homepage": "https://agentid.ai",
7
- "repository": {
8
- "type": "git",
9
- "url": "git+https://github.com/ondrejsukac-rgb/agentid.git",
10
- "directory": "js-sdk"
11
- },
12
- "bugs": {
13
- "url": "https://github.com/ondrejsukac-rgb/agentid/issues"
14
- },
15
- "main": "dist/index.js",
16
- "module": "dist/index.mjs",
17
- "types": "dist/index.d.ts",
18
- "exports": {
19
- ".": {
20
- "types": "./dist/index.d.ts",
21
- "import": "./dist/index.mjs",
22
- "require": "./dist/index.js"
23
- },
24
- "./langchain": {
25
- "types": "./dist/langchain.d.ts",
26
- "import": "./dist/langchain.mjs",
27
- "require": "./dist/langchain.js"
28
- },
29
- "./transparency-badge": {
30
- "types": "./dist/transparency-badge.d.ts",
31
- "import": "./dist/transparency-badge.mjs",
32
- "require": "./dist/transparency-badge.js"
33
- },
34
- "./package.json": "./package.json"
35
- },
36
- "files": [
37
- "dist"
38
- ],
39
- "scripts": {
40
- "build": "tsup --config tsup.config.ts",
41
- "release:check": "npm run build && npm pack --dry-run",
42
- "prepublishOnly": "npm run build"
43
- },
44
- "publishConfig": {
45
- "access": "public"
46
- },
47
- "peerDependencies": {
48
- "@langchain/core": "^0.3.0 || ^1.0.0",
49
- "langchain": "^0.1.0",
50
- "openai": "^4.0.0 || ^5.0.0 || ^6.0.0",
51
- "react": "^18.0.0 || ^19.0.0"
52
- },
53
- "peerDependenciesMeta": {
54
- "@langchain/core": {
55
- "optional": true
56
- },
57
- "langchain": {
58
- "optional": true
59
- },
60
- "react": {
61
- "optional": true
62
- }
63
- },
64
- "devDependencies": {
65
- "@types/react": "^19.2.2",
66
- "tsup": "^8.3.5",
67
- "typescript": "^5.0.0"
68
- }
69
- }
1
+ {
2
+ "name": "agentid-sdk",
3
+ "version": "0.1.31",
4
+ "description": "AgentID JavaScript/TypeScript SDK for guard, ingest, tracing, and analytics.",
5
+ "license": "MIT",
6
+ "homepage": "https://agentid.ai",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/ondrejsukac-rgb/agentid.git",
10
+ "directory": "js-sdk"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/ondrejsukac-rgb/agentid/issues"
14
+ },
15
+ "main": "dist/index.js",
16
+ "module": "dist/index.mjs",
17
+ "types": "dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.mjs",
22
+ "require": "./dist/index.js"
23
+ },
24
+ "./langchain": {
25
+ "types": "./dist/langchain.d.ts",
26
+ "import": "./dist/langchain.mjs",
27
+ "require": "./dist/langchain.js"
28
+ },
29
+ "./transparency-badge": {
30
+ "types": "./dist/transparency-badge.d.ts",
31
+ "import": "./dist/transparency-badge.mjs",
32
+ "require": "./dist/transparency-badge.js"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "dist"
38
+ ],
39
+ "scripts": {
40
+ "build": "tsup --config tsup.config.ts",
41
+ "release:check": "npm run build && npm pack --dry-run",
42
+ "prepublishOnly": "npm run build"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "peerDependencies": {
48
+ "@langchain/core": "^0.3.0 || ^1.0.0",
49
+ "langchain": "^0.1.0 || ^1.0.0",
50
+ "openai": "^4.0.0 || ^5.0.0 || ^6.0.0",
51
+ "react": "^18.0.0 || ^19.0.0"
52
+ },
53
+ "peerDependenciesMeta": {
54
+ "@langchain/core": {
55
+ "optional": true
56
+ },
57
+ "langchain": {
58
+ "optional": true
59
+ },
60
+ "react": {
61
+ "optional": true
62
+ }
63
+ },
64
+ "devDependencies": {
65
+ "@types/react": "^19.2.2",
66
+ "tsup": "^8.3.5",
67
+ "typescript": "^5.0.0"
68
+ }
69
+ }