trusera-sdk 0.1.0
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 +69 -0
- package/README.md +410 -0
- package/dist/client.d.ts +31 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +135 -0
- package/dist/client.js.map +1 -0
- package/dist/events.d.ts +19 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +39 -0
- package/dist/events.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/integrations/langchain.d.ts +28 -0
- package/dist/integrations/langchain.d.ts.map +1 -0
- package/dist/integrations/langchain.js +132 -0
- package/dist/integrations/langchain.js.map +1 -0
- package/dist/interceptor.d.ts +23 -0
- package/dist/interceptor.d.ts.map +1 -0
- package/dist/interceptor.js +215 -0
- package/dist/interceptor.js.map +1 -0
- package/package.json +53 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
10
|
+
|
|
11
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
12
|
+
|
|
13
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
14
|
+
|
|
15
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
16
|
+
|
|
17
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
18
|
+
|
|
19
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
20
|
+
|
|
21
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
22
|
+
|
|
23
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
24
|
+
|
|
25
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
26
|
+
|
|
27
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
28
|
+
|
|
29
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
30
|
+
|
|
31
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
32
|
+
|
|
33
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
34
|
+
|
|
35
|
+
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
36
|
+
|
|
37
|
+
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
38
|
+
|
|
39
|
+
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
40
|
+
|
|
41
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
|
42
|
+
|
|
43
|
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
56
|
+
|
|
57
|
+
Copyright 2024-2026 Trusera
|
|
58
|
+
|
|
59
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
60
|
+
you may not use this file except in compliance with the License.
|
|
61
|
+
You may obtain a copy of the License at
|
|
62
|
+
|
|
63
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
64
|
+
|
|
65
|
+
Unless required by applicable law or agreed to in writing, software
|
|
66
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
67
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
68
|
+
See the License for the specific language governing permissions and
|
|
69
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
# Trusera SDK for JavaScript/TypeScript
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/trusera-sdk)
|
|
4
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
5
|
+
|
|
6
|
+
The official TypeScript/JavaScript SDK for monitoring AI agents with [Trusera](https://trusera.io). Provides transparent HTTP interception, policy enforcement, and comprehensive observability for AI agent applications.
|
|
7
|
+
|
|
8
|
+
## Key Features
|
|
9
|
+
|
|
10
|
+
- **Transparent HTTP Interception**: Zero-code instrumentation of all outbound HTTP calls
|
|
11
|
+
- **Policy Enforcement**: Runtime evaluation against Cedar policies with configurable enforcement modes
|
|
12
|
+
- **LangChain.js Integration**: First-class support for LangChain.js callbacks
|
|
13
|
+
- **Rich Event Tracking**: Track LLM calls, tool executions, data access, and custom events
|
|
14
|
+
- **Batched Transmission**: Automatic event batching and retry logic
|
|
15
|
+
- **Type-Safe**: Full TypeScript support with strict typing
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install trusera-sdk
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Quick Start
|
|
24
|
+
|
|
25
|
+
### Basic Usage (HTTP Interceptor)
|
|
26
|
+
|
|
27
|
+
The simplest way to get started is with the HTTP interceptor:
|
|
28
|
+
|
|
29
|
+
```typescript
|
|
30
|
+
import { TruseraClient, TruseraInterceptor } from "trusera-sdk";
|
|
31
|
+
|
|
32
|
+
// Create client
|
|
33
|
+
const client = new TruseraClient({
|
|
34
|
+
apiKey: "tsk_your_api_key_here",
|
|
35
|
+
agentId: "my-agent-123",
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// Install interceptor
|
|
39
|
+
const interceptor = new TruseraInterceptor();
|
|
40
|
+
interceptor.install(client, {
|
|
41
|
+
enforcement: "log", // or "warn" or "block"
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// All fetch calls are now automatically tracked
|
|
45
|
+
await fetch("https://api.github.com/repos/anthropics/claude");
|
|
46
|
+
await fetch("https://api.openai.com/v1/chat/completions", {
|
|
47
|
+
method: "POST",
|
|
48
|
+
headers: { "Content-Type": "application/json" },
|
|
49
|
+
body: JSON.stringify({ model: "gpt-4", messages: [] }),
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
// Cleanup
|
|
53
|
+
await client.close();
|
|
54
|
+
interceptor.uninstall();
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### LangChain.js Integration
|
|
58
|
+
|
|
59
|
+
Track LLM calls, tool executions, and chain steps automatically:
|
|
60
|
+
|
|
61
|
+
```typescript
|
|
62
|
+
import { ChatOpenAI } from "langchain/chat_models/openai";
|
|
63
|
+
import { TruseraClient, TruseraLangChainHandler } from "trusera-sdk";
|
|
64
|
+
|
|
65
|
+
const client = new TruseraClient({ apiKey: "tsk_xxx" });
|
|
66
|
+
const handler = new TruseraLangChainHandler(client);
|
|
67
|
+
|
|
68
|
+
const model = new ChatOpenAI({
|
|
69
|
+
callbacks: [handler],
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
await model.invoke("What are the top AI security risks?");
|
|
73
|
+
|
|
74
|
+
await client.close();
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### Manual Event Tracking
|
|
78
|
+
|
|
79
|
+
For custom instrumentation:
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
import { TruseraClient, EventType, createEvent } from "trusera-sdk";
|
|
83
|
+
|
|
84
|
+
const client = new TruseraClient({ apiKey: "tsk_xxx" });
|
|
85
|
+
|
|
86
|
+
// Track tool call
|
|
87
|
+
client.track(
|
|
88
|
+
createEvent(EventType.TOOL_CALL, "github.search_repos", {
|
|
89
|
+
query: "AI security",
|
|
90
|
+
language: "TypeScript",
|
|
91
|
+
})
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
// Track LLM invocation
|
|
95
|
+
client.track(
|
|
96
|
+
createEvent(EventType.LLM_INVOKE, "openai.gpt4", {
|
|
97
|
+
model: "gpt-4",
|
|
98
|
+
tokens: 150,
|
|
99
|
+
temperature: 0.7,
|
|
100
|
+
})
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
// Track data access
|
|
104
|
+
client.track(
|
|
105
|
+
createEvent(EventType.DATA_ACCESS, "database.users.read", {
|
|
106
|
+
table: "users",
|
|
107
|
+
query: "SELECT * FROM users WHERE id = ?",
|
|
108
|
+
})
|
|
109
|
+
);
|
|
110
|
+
|
|
111
|
+
await client.close();
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## Configuration
|
|
115
|
+
|
|
116
|
+
### TruseraClient Options
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
interface TruseraClientOptions {
|
|
120
|
+
/** API key for authenticating with Trusera (required) */
|
|
121
|
+
apiKey: string;
|
|
122
|
+
|
|
123
|
+
/** Base URL for Trusera API (default: https://api.trusera.io) */
|
|
124
|
+
baseUrl?: string;
|
|
125
|
+
|
|
126
|
+
/** Agent identifier (auto-registered if not provided) */
|
|
127
|
+
agentId?: string;
|
|
128
|
+
|
|
129
|
+
/** Interval in ms to auto-flush events (default: 5000) */
|
|
130
|
+
flushInterval?: number;
|
|
131
|
+
|
|
132
|
+
/** Max events per batch (default: 100) */
|
|
133
|
+
batchSize?: number;
|
|
134
|
+
|
|
135
|
+
/** Enable debug logging (default: false) */
|
|
136
|
+
debug?: boolean;
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### Interceptor Options
|
|
141
|
+
|
|
142
|
+
```typescript
|
|
143
|
+
interface InterceptorOptions {
|
|
144
|
+
/** How to handle policy violations (default: "log") */
|
|
145
|
+
enforcement?: "block" | "warn" | "log";
|
|
146
|
+
|
|
147
|
+
/** Cedar policy service URL for runtime policy checks */
|
|
148
|
+
policyUrl?: string;
|
|
149
|
+
|
|
150
|
+
/** URL patterns to exclude from interception (regex strings) */
|
|
151
|
+
excludePatterns?: string[];
|
|
152
|
+
|
|
153
|
+
/** Enable debug logging (default: false) */
|
|
154
|
+
debug?: boolean;
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Enforcement Modes
|
|
159
|
+
|
|
160
|
+
The interceptor supports three enforcement modes for policy violations:
|
|
161
|
+
|
|
162
|
+
### `log` (default)
|
|
163
|
+
|
|
164
|
+
Logs violations silently, allows all requests to proceed.
|
|
165
|
+
|
|
166
|
+
```typescript
|
|
167
|
+
interceptor.install(client, { enforcement: "log" });
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
### `warn`
|
|
171
|
+
|
|
172
|
+
Logs warnings to console but allows requests to proceed.
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
interceptor.install(client, { enforcement: "warn" });
|
|
176
|
+
// Outputs: [Trusera] Policy violation (allowed): Unauthorized API access
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
### `block`
|
|
180
|
+
|
|
181
|
+
Throws an error and blocks the request.
|
|
182
|
+
|
|
183
|
+
```typescript
|
|
184
|
+
interceptor.install(client, { enforcement: "block" });
|
|
185
|
+
// Throws: Error: [Trusera] Policy violation: Unauthorized API access
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
## Advanced Usage
|
|
189
|
+
|
|
190
|
+
### Policy-Based Enforcement
|
|
191
|
+
|
|
192
|
+
Connect to a Cedar policy service for runtime access control:
|
|
193
|
+
|
|
194
|
+
```typescript
|
|
195
|
+
interceptor.install(client, {
|
|
196
|
+
enforcement: "block",
|
|
197
|
+
policyUrl: "https://policy.trusera.io/evaluate",
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
// This request will be evaluated against Cedar policies
|
|
201
|
+
// If denied, an error will be thrown before the request executes
|
|
202
|
+
await fetch("https://api.stripe.com/v1/customers");
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
### Exclude Internal URLs
|
|
206
|
+
|
|
207
|
+
Prevent interception of internal or infrastructure URLs:
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
interceptor.install(client, {
|
|
211
|
+
excludePatterns: [
|
|
212
|
+
"^https://api\\.trusera\\.io/.*", // Exclude Trusera API
|
|
213
|
+
"^https://internal\\.company\\.com/.*", // Exclude internal services
|
|
214
|
+
"^http://localhost.*", // Exclude localhost
|
|
215
|
+
],
|
|
216
|
+
});
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
### Agent Registration
|
|
220
|
+
|
|
221
|
+
Register a new agent programmatically:
|
|
222
|
+
|
|
223
|
+
```typescript
|
|
224
|
+
const client = new TruseraClient({ apiKey: "tsk_xxx" });
|
|
225
|
+
|
|
226
|
+
const agentId = await client.registerAgent("my-chatbot", "langchain");
|
|
227
|
+
console.log(`Agent registered: ${agentId}`);
|
|
228
|
+
|
|
229
|
+
// Use the returned ID for future sessions
|
|
230
|
+
const client2 = new TruseraClient({
|
|
231
|
+
apiKey: "tsk_xxx",
|
|
232
|
+
agentId: agentId,
|
|
233
|
+
});
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
### Manual Flush Control
|
|
237
|
+
|
|
238
|
+
Control when events are sent:
|
|
239
|
+
|
|
240
|
+
```typescript
|
|
241
|
+
const client = new TruseraClient({
|
|
242
|
+
apiKey: "tsk_xxx",
|
|
243
|
+
flushInterval: 999999, // Disable auto-flush
|
|
244
|
+
batchSize: 50,
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
// Track events
|
|
248
|
+
client.track(createEvent(EventType.TOOL_CALL, "test"));
|
|
249
|
+
|
|
250
|
+
// Manually flush when ready
|
|
251
|
+
await client.flush();
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
## Event Types
|
|
255
|
+
|
|
256
|
+
The SDK tracks six core event types:
|
|
257
|
+
|
|
258
|
+
| Event Type | Description | Example Use Cases |
|
|
259
|
+
| -------------- | ---------------------------------------- | ------------------------------------ |
|
|
260
|
+
| `TOOL_CALL` | Tool or function call by the agent | API calls, file operations, searches |
|
|
261
|
+
| `LLM_INVOKE` | LLM inference invocation | OpenAI, Anthropic, local models |
|
|
262
|
+
| `DATA_ACCESS` | Data read/write operations | Database queries, file I/O |
|
|
263
|
+
| `API_CALL` | Outbound HTTP API calls | Third-party APIs, webhooks |
|
|
264
|
+
| `FILE_WRITE` | File write operations | Log files, cache writes |
|
|
265
|
+
| `DECISION` | Decision points or chain steps | Agent reasoning, workflow branches |
|
|
266
|
+
|
|
267
|
+
## API Reference
|
|
268
|
+
|
|
269
|
+
### `TruseraClient`
|
|
270
|
+
|
|
271
|
+
#### Methods
|
|
272
|
+
|
|
273
|
+
- `constructor(options: TruseraClientOptions)`: Create a new client
|
|
274
|
+
- `track(event: Event): void`: Queue an event for transmission
|
|
275
|
+
- `flush(): Promise<void>`: Immediately send all queued events
|
|
276
|
+
- `registerAgent(name: string, framework: string): Promise<string>`: Register a new agent
|
|
277
|
+
- `close(): Promise<void>`: Flush events and shutdown client
|
|
278
|
+
- `getQueueSize(): number`: Get current queue size
|
|
279
|
+
- `getAgentId(): string | undefined`: Get the current agent ID
|
|
280
|
+
|
|
281
|
+
### `TruseraInterceptor`
|
|
282
|
+
|
|
283
|
+
#### Methods
|
|
284
|
+
|
|
285
|
+
- `install(client: TruseraClient, options?: InterceptorOptions): void`: Install HTTP interceptor
|
|
286
|
+
- `uninstall(): void`: Restore original fetch and remove interceptor
|
|
287
|
+
|
|
288
|
+
### `TruseraLangChainHandler`
|
|
289
|
+
|
|
290
|
+
#### Methods
|
|
291
|
+
|
|
292
|
+
- `constructor(client: TruseraClient)`: Create handler for LangChain callbacks
|
|
293
|
+
- `getPendingEventCount(): number`: Get count of incomplete events
|
|
294
|
+
- `clearPendingEvents(): void`: Clear all pending events
|
|
295
|
+
|
|
296
|
+
### Utility Functions
|
|
297
|
+
|
|
298
|
+
- `createEvent(type: EventType, name: string, payload?, metadata?): Event`: Create a well-formed event
|
|
299
|
+
- `isValidEvent(obj: unknown): boolean`: Type guard to validate events
|
|
300
|
+
|
|
301
|
+
## Examples
|
|
302
|
+
|
|
303
|
+
### Example: Agent with Tools
|
|
304
|
+
|
|
305
|
+
```typescript
|
|
306
|
+
import { TruseraClient, TruseraInterceptor, EventType, createEvent } from "trusera-sdk";
|
|
307
|
+
|
|
308
|
+
const client = new TruseraClient({ apiKey: process.env.TRUSERA_API_KEY });
|
|
309
|
+
const interceptor = new TruseraInterceptor();
|
|
310
|
+
|
|
311
|
+
interceptor.install(client, {
|
|
312
|
+
enforcement: "warn",
|
|
313
|
+
excludePatterns: ["^http://localhost.*"],
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
// Tool execution wrapper
|
|
317
|
+
async function executeTool(name: string, input: any) {
|
|
318
|
+
const startTime = Date.now();
|
|
319
|
+
|
|
320
|
+
try {
|
|
321
|
+
// Tool logic here
|
|
322
|
+
const result = await fetch("https://api.example.com/tool", {
|
|
323
|
+
method: "POST",
|
|
324
|
+
body: JSON.stringify(input),
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
const duration = Date.now() - startTime;
|
|
328
|
+
|
|
329
|
+
client.track(
|
|
330
|
+
createEvent(EventType.TOOL_CALL, `tool.${name}.success`, {
|
|
331
|
+
input,
|
|
332
|
+
duration_ms: duration,
|
|
333
|
+
})
|
|
334
|
+
);
|
|
335
|
+
|
|
336
|
+
return result;
|
|
337
|
+
} catch (error) {
|
|
338
|
+
client.track(
|
|
339
|
+
createEvent(EventType.TOOL_CALL, `tool.${name}.error`, {
|
|
340
|
+
input,
|
|
341
|
+
error: error.message,
|
|
342
|
+
})
|
|
343
|
+
);
|
|
344
|
+
throw error;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
await executeTool("search", { query: "AI security" });
|
|
349
|
+
await client.close();
|
|
350
|
+
interceptor.uninstall();
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
### Example: Multi-Agent System
|
|
354
|
+
|
|
355
|
+
```typescript
|
|
356
|
+
const agent1 = new TruseraClient({
|
|
357
|
+
apiKey: "tsk_xxx",
|
|
358
|
+
agentId: "planner",
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
const agent2 = new TruseraClient({
|
|
362
|
+
apiKey: "tsk_xxx",
|
|
363
|
+
agentId: "executor",
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
// Track coordination events
|
|
367
|
+
agent1.track(
|
|
368
|
+
createEvent(EventType.DECISION, "coordination.delegate", {
|
|
369
|
+
target_agent: "executor",
|
|
370
|
+
task: "web_search",
|
|
371
|
+
})
|
|
372
|
+
);
|
|
373
|
+
|
|
374
|
+
agent2.track(
|
|
375
|
+
createEvent(EventType.TOOL_CALL, "search.execute", {
|
|
376
|
+
delegated_from: "planner",
|
|
377
|
+
})
|
|
378
|
+
);
|
|
379
|
+
|
|
380
|
+
await Promise.all([agent1.close(), agent2.close()]);
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
## Requirements
|
|
384
|
+
|
|
385
|
+
- Node.js >= 18.0.0
|
|
386
|
+
- TypeScript >= 5.0 (for TypeScript users)
|
|
387
|
+
|
|
388
|
+
## License
|
|
389
|
+
|
|
390
|
+
Apache 2.0 - see [LICENSE](LICENSE) for details.
|
|
391
|
+
|
|
392
|
+
## Support
|
|
393
|
+
|
|
394
|
+
- Documentation: [https://docs.trusera.io](https://docs.trusera.io)
|
|
395
|
+
- Issues: [GitHub Issues](https://github.com/Trusera/trusera-sdk-js/issues)
|
|
396
|
+
- Email: support@trusera.io
|
|
397
|
+
|
|
398
|
+
## Contributing
|
|
399
|
+
|
|
400
|
+
Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
|
|
401
|
+
|
|
402
|
+
## Related Projects
|
|
403
|
+
|
|
404
|
+
- [trusera-sdk-python](https://github.com/Trusera/trusera-sdk-python) - Python SDK
|
|
405
|
+
- [ai-bom](https://github.com/Trusera/ai-bom) - AI Bill of Materials scanner
|
|
406
|
+
- [trusera-platform](https://github.com/Trusera/trusera-platform) - Full monitoring platform
|
|
407
|
+
|
|
408
|
+
---
|
|
409
|
+
|
|
410
|
+
Built with care by the Trusera team. Making AI agents safe and observable.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Event } from "./events.js";
|
|
2
|
+
export interface TruseraClientOptions {
|
|
3
|
+
apiKey: string;
|
|
4
|
+
baseUrl?: string;
|
|
5
|
+
agentId?: string;
|
|
6
|
+
flushInterval?: number;
|
|
7
|
+
batchSize?: number;
|
|
8
|
+
debug?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export declare class TruseraClient {
|
|
11
|
+
private readonly apiKey;
|
|
12
|
+
private readonly baseUrl;
|
|
13
|
+
private readonly batchSize;
|
|
14
|
+
private readonly flushInterval;
|
|
15
|
+
private readonly debug;
|
|
16
|
+
private agentId;
|
|
17
|
+
private eventQueue;
|
|
18
|
+
private flushTimer;
|
|
19
|
+
private isClosed;
|
|
20
|
+
constructor(options: TruseraClientOptions);
|
|
21
|
+
registerAgent(name: string, framework: string): Promise<string>;
|
|
22
|
+
track(event: Event): void;
|
|
23
|
+
flush(): Promise<void>;
|
|
24
|
+
close(): Promise<void>;
|
|
25
|
+
getQueueSize(): number;
|
|
26
|
+
getAgentId(): string | undefined;
|
|
27
|
+
private startFlushTimer;
|
|
28
|
+
private stopFlushTimer;
|
|
29
|
+
private log;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAA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
+
baseUrl;
|
|
7
|
+
batchSize;
|
|
8
|
+
flushInterval;
|
|
9
|
+
debug;
|
|
10
|
+
agentId;
|
|
11
|
+
eventQueue = [];
|
|
12
|
+
flushTimer;
|
|
13
|
+
isClosed = false;
|
|
14
|
+
constructor(options) {
|
|
15
|
+
this.apiKey = options.apiKey;
|
|
16
|
+
this.baseUrl = options.baseUrl ?? "https://api.trusera.io";
|
|
17
|
+
this.agentId = options.agentId;
|
|
18
|
+
this.batchSize = options.batchSize ?? 100;
|
|
19
|
+
this.flushInterval = options.flushInterval ?? 5000;
|
|
20
|
+
this.debug = options.debug ?? false;
|
|
21
|
+
if (!this.apiKey.startsWith("tsk_")) {
|
|
22
|
+
throw new Error("Invalid API key format. Must start with 'tsk_'");
|
|
23
|
+
}
|
|
24
|
+
this.startFlushTimer();
|
|
25
|
+
this.log("TruseraClient initialized", { baseUrl: this.baseUrl, batchSize: this.batchSize });
|
|
26
|
+
}
|
|
27
|
+
async registerAgent(name, framework) {
|
|
28
|
+
this.log("Registering agent", { name, framework });
|
|
29
|
+
const response = await fetch(`${this.baseUrl}/api/v1/agents/register`, {
|
|
30
|
+
method: "POST",
|
|
31
|
+
headers: {
|
|
32
|
+
"Content-Type": "application/json",
|
|
33
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
34
|
+
},
|
|
35
|
+
body: JSON.stringify({
|
|
36
|
+
name,
|
|
37
|
+
framework,
|
|
38
|
+
metadata: {
|
|
39
|
+
sdk_version: "0.1.0",
|
|
40
|
+
runtime: "node",
|
|
41
|
+
node_version: process.version,
|
|
42
|
+
},
|
|
43
|
+
}),
|
|
44
|
+
});
|
|
45
|
+
if (!response.ok) {
|
|
46
|
+
const error = await response.text();
|
|
47
|
+
throw new Error(`Failed to register agent: ${response.status} ${error}`);
|
|
48
|
+
}
|
|
49
|
+
const data = (await response.json());
|
|
50
|
+
this.agentId = data.agent_id;
|
|
51
|
+
this.log("Agent registered", { agentId: this.agentId });
|
|
52
|
+
return this.agentId;
|
|
53
|
+
}
|
|
54
|
+
track(event) {
|
|
55
|
+
if (this.isClosed) {
|
|
56
|
+
throw new Error("Cannot track events on closed client");
|
|
57
|
+
}
|
|
58
|
+
const enrichedEvent = {
|
|
59
|
+
...event,
|
|
60
|
+
metadata: {
|
|
61
|
+
...event.metadata,
|
|
62
|
+
agent_id: this.agentId,
|
|
63
|
+
sdk_version: "0.1.0",
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
this.eventQueue.push(enrichedEvent);
|
|
67
|
+
this.log("Event tracked", { type: event.type, name: event.name, queueSize: this.eventQueue.length });
|
|
68
|
+
if (this.eventQueue.length >= this.batchSize) {
|
|
69
|
+
void this.flush();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async flush() {
|
|
73
|
+
if (this.eventQueue.length === 0) {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const batch = this.eventQueue.splice(0, this.batchSize);
|
|
77
|
+
this.log("Flushing events", { count: batch.length });
|
|
78
|
+
try {
|
|
79
|
+
const response = await fetch(`${this.baseUrl}/api/v1/events/batch`, {
|
|
80
|
+
method: "POST",
|
|
81
|
+
headers: {
|
|
82
|
+
"Content-Type": "application/json",
|
|
83
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
84
|
+
},
|
|
85
|
+
body: JSON.stringify({ events: batch }),
|
|
86
|
+
});
|
|
87
|
+
if (!response.ok) {
|
|
88
|
+
const error = await response.text();
|
|
89
|
+
console.error(`[Trusera] Failed to send events: ${response.status} ${error}`);
|
|
90
|
+
this.eventQueue.unshift(...batch);
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
this.log("Events flushed successfully", { count: batch.length });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
console.error("[Trusera] Network error sending events:", error);
|
|
98
|
+
this.eventQueue.unshift(...batch);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
async close() {
|
|
102
|
+
this.log("Closing client");
|
|
103
|
+
this.isClosed = true;
|
|
104
|
+
this.stopFlushTimer();
|
|
105
|
+
await this.flush();
|
|
106
|
+
this.log("Client closed");
|
|
107
|
+
}
|
|
108
|
+
getQueueSize() {
|
|
109
|
+
return this.eventQueue.length;
|
|
110
|
+
}
|
|
111
|
+
getAgentId() {
|
|
112
|
+
return this.agentId;
|
|
113
|
+
}
|
|
114
|
+
startFlushTimer() {
|
|
115
|
+
this.flushTimer = setInterval(() => {
|
|
116
|
+
void this.flush();
|
|
117
|
+
}, this.flushInterval);
|
|
118
|
+
if (this.flushTimer.unref) {
|
|
119
|
+
this.flushTimer.unref();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
stopFlushTimer() {
|
|
123
|
+
if (this.flushTimer) {
|
|
124
|
+
clearInterval(this.flushTimer);
|
|
125
|
+
this.flushTimer = undefined;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
log(message, data) {
|
|
129
|
+
if (this.debug) {
|
|
130
|
+
console.log(`[Trusera] ${message}`, data ?? "");
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
exports.TruseraClient = TruseraClient;
|
|
135
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;AA4CA,MAAa,aAAa;IACP,MAAM,CAAS;IACf,OAAO,CAAS;IAChB,SAAS,CAAS;IAClB,aAAa,CAAS;IACtB,KAAK,CAAU;IAExB,OAAO,CAAqB;IAC5B,UAAU,GAAY,EAAE,CAAC;IACzB,UAAU,CAA6B;IACvC,QAAQ,GAAG,KAAK,CAAC;IAEzB,YAAY,OAA6B;QACvC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,wBAAwB,CAAC;QAC3D,IAAI,CAAC,OAAO,GAA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K,EAAE,CAAC;QACnB,IAAI,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;IAC5B,CAAC;IAKD,YAAY;QACV,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC;IAChC,CAAC;IAKD,UAAU;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAEO,eAAe;QACrB,IAAI,CAAC,UAAU,GAAG,WAAW,CAAC,GAAG,EAAE;YACjC,KAAK,IAAI,CAAC,KAAK,EAAE,CAAC;QACpB,CAAC,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC;QAGvB,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;YAC1B,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QAC1B,CAAC;IACH,CAAC;IAEO,cAAc;QACpB,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACpB,aAAa,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAC/B,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC9B,CAAC;IACH,CAAC;IAEO,GAAG,CAAC,OAAe,EAAE,IAA8B;QACzD,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,GAAG,CAAC,aAAa,OAAO,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC;QAClD,CAAC;IACH,CAAC;CACF;AA5LD,sCA4LC"}
|
package/dist/events.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare enum EventType {
|
|
2
|
+
TOOL_CALL = "tool_call",
|
|
3
|
+
LLM_INVOKE = "llm_invoke",
|
|
4
|
+
DATA_ACCESS = "data_access",
|
|
5
|
+
API_CALL = "api_call",
|
|
6
|
+
FILE_WRITE = "file_write",
|
|
7
|
+
DECISION = "decision"
|
|
8
|
+
}
|
|
9
|
+
export interface Event {
|
|
10
|
+
id: string;
|
|
11
|
+
type: EventType;
|
|
12
|
+
name: string;
|
|
13
|
+
payload: Record<string, unknown>;
|
|
14
|
+
metadata: Record<string, unknown>;
|
|
15
|
+
timestamp: string;
|
|
16
|
+
}
|
|
17
|
+
export declare function createEvent(type: EventType, name: string, payload?: Record<string, unknown>, metadata?: Record<string, unknown>): Event;
|
|
18
|
+
export declare function isValidEvent(obj: unknown): obj is Event;
|
|
19
|
+
//# sourceMappingURL=events.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAIA,oBAAY,SAAS;IAEnB,SAAS,cAAc;IAEvB,UAAU,eAAe;IAEzB,WAAW,gBAAgB;IAE3B,QAAQ,aAAa;IAErB,UAAU,eAAe;IAEzB,QAAQ,aAAa;CACtB;AAMD,MAAM,WAAW,KAAK;IAEpB,EAAE,EAAE,MAAM,CAAC;IAEX,IAAI,EAAE,SAAS,CAAC;IAEhB,IAAI,EAAE,MAAM,CAAC;IAEb,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAEjC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAElC,SAAS,EAAE,MAAM,CAAC;CACnB;AAsBD,wBAAgB,WAAW,CACzB,IAAI,EAAE,SAAS,EACf,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,EACrC,QAAQ,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,GACrC,KAAK,CASP;AAMD,wBAAgB,YAAY,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,KAAK,CAcvD"}
|
package/dist/events.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.EventType = void 0;
|
|
4
|
+
exports.createEvent = createEvent;
|
|
5
|
+
exports.isValidEvent = isValidEvent;
|
|
6
|
+
var EventType;
|
|
7
|
+
(function (EventType) {
|
|
8
|
+
EventType["TOOL_CALL"] = "tool_call";
|
|
9
|
+
EventType["LLM_INVOKE"] = "llm_invoke";
|
|
10
|
+
EventType["DATA_ACCESS"] = "data_access";
|
|
11
|
+
EventType["API_CALL"] = "api_call";
|
|
12
|
+
EventType["FILE_WRITE"] = "file_write";
|
|
13
|
+
EventType["DECISION"] = "decision";
|
|
14
|
+
})(EventType || (exports.EventType = EventType = {}));
|
|
15
|
+
function createEvent(type, name, payload = {}, metadata = {}) {
|
|
16
|
+
return {
|
|
17
|
+
id: crypto.randomUUID(),
|
|
18
|
+
type,
|
|
19
|
+
name,
|
|
20
|
+
payload: { ...payload },
|
|
21
|
+
metadata: { ...metadata },
|
|
22
|
+
timestamp: new Date().toISOString(),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function isValidEvent(obj) {
|
|
26
|
+
if (typeof obj !== "object" || obj === null)
|
|
27
|
+
return false;
|
|
28
|
+
const e = obj;
|
|
29
|
+
return (typeof e.id === "string" &&
|
|
30
|
+
typeof e.type === "string" &&
|
|
31
|
+
Object.values(EventType).includes(e.type) &&
|
|
32
|
+
typeof e.name === "string" &&
|
|
33
|
+
typeof e.payload === "object" &&
|
|
34
|
+
e.payload !== null &&
|
|
35
|
+
typeof e.metadata === "object" &&
|
|
36
|
+
e.metadata !== null &&
|
|
37
|
+
typeof e.timestamp === "string");
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=events.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":";;;AA0DA,kCAcC;AAMD,oCAcC;AAxFD,IAAY,SAaX;AAbD,WAAY,SAAS;IAEnB,oCAAuB,CAAA;IAEvB,sCAAyB,CAAA;IAEzB,wCAA2B,CAAA;IAE3B,kCAAqB,CAAA;IAErB,sCAAyB,CAAA;IAEzB,kCAAqB,CAAA;AACvB,CAAC,EAbW,SAAS,yBAAT,SAAS,QAapB;AAyCD,SAAgB,WAAW,CACzB,IAAe,EACf,IAAY,EACZ,UAAmC,EAAE,EACrC,WAAoC,EAAE;IAEtC,OAAO;QACL,EAAE,EAAE,MAAM,CAAC,UAAU,EAAE;QACvB,IAAI;QACJ,IAAI;QACJ,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE;QACvB,QAAQ,EAAE,EAAE,GAAG,QAAQ,EAAE;QACzB,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KACpC,CAAC;AACJ,CAAC;AAMD,SAAgB,YAAY,CAAC,GAAY;IACvC,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC1D,MAAM,CAAC,GAAG,GAAqB,CAAC;IAChC,OAAO,CACL,OAAO,CAAC,CAAC,EAAE,KAAK,QAAQ;QACxB,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ;QAC1B,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAiB,CAAC;QACtD,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ;QAC1B,OAAO,CAAC,CAAC,OAAO,KAAK,QAAQ;QAC7B,CAAC,CAAC,OAAO,KAAK,IAAI;QAClB,OAAO,CAAC,CAAC,QAAQ,KAAK,QAAQ;QAC9B,CAAC,CAAC,QAAQ,KAAK,IAAI;QACnB,OAAO,CAAC,CAAC,SAAS,KAAK,QAAQ,CAChC,CAAC;AACJ,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { TruseraClient } from "./client.js";
|
|
2
|
+
export type { TruseraClientOptions } from "./client.js";
|
|
3
|
+
export { TruseraInterceptor } from "./interceptor.js";
|
|
4
|
+
export type { InterceptorOptions, EnforcementMode } from "./interceptor.js";
|
|
5
|
+
export { EventType, createEvent, isValidEvent } from "./events.js";
|
|
6
|
+
export type { Event } from "./events.js";
|
|
7
|
+
export { TruseraLangChainHandler } from "./integrations/langchain.js";
|
|
8
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAExD,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACtD,YAAY,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAE5E,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACnE,YAAY,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TruseraLangChainHandler = exports.isValidEvent = exports.createEvent = exports.EventType = exports.TruseraInterceptor = exports.TruseraClient = void 0;
|
|
4
|
+
var client_js_1 = require("./client.js");
|
|
5
|
+
Object.defineProperty(exports, "TruseraClient", { enumerable: true, get: function () { return client_js_1.TruseraClient; } });
|
|
6
|
+
var interceptor_js_1 = require("./interceptor.js");
|
|
7
|
+
Object.defineProperty(exports, "TruseraInterceptor", { enumerable: true, get: function () { return interceptor_js_1.TruseraInterceptor; } });
|
|
8
|
+
var events_js_1 = require("./events.js");
|
|
9
|
+
Object.defineProperty(exports, "EventType", { enumerable: true, get: function () { return events_js_1.EventType; } });
|
|
10
|
+
Object.defineProperty(exports, "createEvent", { enumerable: true, get: function () { return events_js_1.createEvent; } });
|
|
11
|
+
Object.defineProperty(exports, "isValidEvent", { enumerable: true, get: function () { return events_js_1.isValidEvent; } });
|
|
12
|
+
var langchain_js_1 = require("./integrations/langchain.js");
|
|
13
|
+
Object.defineProperty(exports, "TruseraLangChainHandler", { enumerable: true, get: function () { return langchain_js_1.TruseraLangChainHandler; } });
|
|
14
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAMA,yCAA4C;AAAnC,0GAAA,aAAa,OAAA;AAGtB,mDAAsD;AAA7C,oHAAA,kBAAkB,OAAA;AAG3B,yCAAmE;AAA1D,sGAAA,SAAS,OAAA;AAAE,wGAAA,WAAW,OAAA;AAAE,yGAAA,YAAY,OAAA;AAG7C,4DAAsE;AAA7D,uHAAA,uBAAuB,OAAA"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { TruseraClient } from "../client.js";
|
|
2
|
+
export declare class TruseraLangChainHandler {
|
|
3
|
+
private readonly client;
|
|
4
|
+
private readonly pendingEvents;
|
|
5
|
+
constructor(client: TruseraClient);
|
|
6
|
+
handleLLMStart(llm: {
|
|
7
|
+
name: string;
|
|
8
|
+
}, prompts: string[], runId: string, parentRunId?: string, extraParams?: Record<string, unknown>, tags?: string[], metadata?: Record<string, unknown>): void;
|
|
9
|
+
handleLLMEnd(output: {
|
|
10
|
+
generations: Array<Array<{
|
|
11
|
+
text: string;
|
|
12
|
+
}>>;
|
|
13
|
+
}, runId: string): void;
|
|
14
|
+
handleLLMError(error: Error, runId: string): void;
|
|
15
|
+
handleToolStart(tool: {
|
|
16
|
+
name: string;
|
|
17
|
+
}, input: string, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>): void;
|
|
18
|
+
handleToolEnd(output: string, runId: string): void;
|
|
19
|
+
handleToolError(error: Error, runId: string): void;
|
|
20
|
+
handleChainStart(chain: {
|
|
21
|
+
name: string;
|
|
22
|
+
}, inputs: Record<string, unknown>, runId: string, parentRunId?: string, tags?: string[], metadata?: Record<string, unknown>): void;
|
|
23
|
+
handleChainEnd(outputs: Record<string, unknown>, runId: string): void;
|
|
24
|
+
handleChainError(error: Error, runId: string): void;
|
|
25
|
+
getPendingEventCount(): number;
|
|
26
|
+
clearPendingEvents(): void;
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=langchain.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"langchain.d.ts","sourceRoot":"","sources":["../../src/integrations/langchain.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAyBlD,qBAAa,uBAAuB;IAClC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgB;IACvC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAA4B;gBAE9C,MAAM,EAAE,aAAa;IAOjC,cAAc,CACZ,GAAG,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,EACrB,OAAO,EAAE,MAAM,EAAE,EACjB,KAAK,EAAE,MAAM,EACb,WAAW,CAAC,EAAE,MAAM,EACpB,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACrC,IAAI,CAAC,EAAE,MAAM,EAAE,EACf,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACjC,IAAI;IAwBP,YAAY,CACV,MAAM,EAAE;QAAE,WAAW,EAAE,KAAK,CAAC,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC,CAAA;KAAE,EACvD,KAAK,EAAE,MAAM,GACZ,IAAI;IAwBP,cAAc,CACZ,KAAK,EAAE,KAAK,EACZ,KAAK,EAAE,MAAM,GACZ,IAAI;IAsBP,eAAe,CACb,IAAI,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,EACtB,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,WAAW,CAAC,EAAE,MAAM,EACpB,IAAI,CAAC,EAAE,MAAM,EAAE,EACf,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACjC,IAAI;IAuBP,aAAa,CACX,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,IAAI;IAsBP,eAAe,CACb,KAAK,EAAE,KAAK,EACZ,KAAK,EAAE,MAAM,GACZ,IAAI;IAsBP,gBAAgB,CACd,KAAK,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,EACvB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,KAAK,EAAE,MAAM,EACb,WAAW,CAAC,EAAE,MAAM,EACpB,IAAI,CAAC,EAAE,MAAM,EAAE,EACf,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACjC,IAAI;IAuBP,cAAc,CACZ,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,KAAK,EAAE,MAAM,GACZ,IAAI;IAsBP,gBAAgB,CACd,KAAK,EAAE,KAAK,EACZ,KAAK,EAAE,MAAM,GACZ,IAAI;IAuBP,oBAAoB,IAAI,MAAM;IAQ9B,kBAAkB,IAAI,IAAI;CAG3B"}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TruseraLangChainHandler = void 0;
|
|
4
|
+
const events_js_1 = require("../events.js");
|
|
5
|
+
class TruseraLangChainHandler {
|
|
6
|
+
client;
|
|
7
|
+
pendingEvents = new Map();
|
|
8
|
+
constructor(client) {
|
|
9
|
+
this.client = client;
|
|
10
|
+
}
|
|
11
|
+
handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata) {
|
|
12
|
+
const event = (0, events_js_1.createEvent)(events_js_1.EventType.LLM_INVOKE, `langchain.llm.${llm.name}`, {
|
|
13
|
+
prompts,
|
|
14
|
+
prompt_count: prompts.length,
|
|
15
|
+
invocation_params: extraParams ?? {},
|
|
16
|
+
}, {
|
|
17
|
+
run_id: runId,
|
|
18
|
+
parent_run_id: parentRunId,
|
|
19
|
+
tags: tags ?? [],
|
|
20
|
+
...metadata,
|
|
21
|
+
});
|
|
22
|
+
this.pendingEvents.set(runId, event);
|
|
23
|
+
this.client.track(event);
|
|
24
|
+
}
|
|
25
|
+
handleLLMEnd(output, runId) {
|
|
26
|
+
const startEvent = this.pendingEvents.get(runId);
|
|
27
|
+
if (!startEvent)
|
|
28
|
+
return;
|
|
29
|
+
const texts = output.generations.flatMap((gen) => gen.map((g) => g.text));
|
|
30
|
+
const event = (0, events_js_1.createEvent)(events_js_1.EventType.LLM_INVOKE, `${startEvent.name}.completed`, {
|
|
31
|
+
...startEvent.payload,
|
|
32
|
+
outputs: texts,
|
|
33
|
+
output_count: texts.length,
|
|
34
|
+
}, startEvent.metadata);
|
|
35
|
+
this.client.track(event);
|
|
36
|
+
this.pendingEvents.delete(runId);
|
|
37
|
+
}
|
|
38
|
+
handleLLMError(error, runId) {
|
|
39
|
+
const startEvent = this.pendingEvents.get(runId);
|
|
40
|
+
if (!startEvent)
|
|
41
|
+
return;
|
|
42
|
+
const event = (0, events_js_1.createEvent)(events_js_1.EventType.LLM_INVOKE, `${startEvent.name}.error`, {
|
|
43
|
+
...startEvent.payload,
|
|
44
|
+
error: error.message,
|
|
45
|
+
error_type: error.name,
|
|
46
|
+
}, startEvent.metadata);
|
|
47
|
+
this.client.track(event);
|
|
48
|
+
this.pendingEvents.delete(runId);
|
|
49
|
+
}
|
|
50
|
+
handleToolStart(tool, input, runId, parentRunId, tags, metadata) {
|
|
51
|
+
const event = (0, events_js_1.createEvent)(events_js_1.EventType.TOOL_CALL, `langchain.tool.${tool.name}`, {
|
|
52
|
+
input,
|
|
53
|
+
input_length: input.length,
|
|
54
|
+
}, {
|
|
55
|
+
run_id: runId,
|
|
56
|
+
parent_run_id: parentRunId,
|
|
57
|
+
tags: tags ?? [],
|
|
58
|
+
...metadata,
|
|
59
|
+
});
|
|
60
|
+
this.pendingEvents.set(runId, event);
|
|
61
|
+
this.client.track(event);
|
|
62
|
+
}
|
|
63
|
+
handleToolEnd(output, runId) {
|
|
64
|
+
const startEvent = this.pendingEvents.get(runId);
|
|
65
|
+
if (!startEvent)
|
|
66
|
+
return;
|
|
67
|
+
const event = (0, events_js_1.createEvent)(events_js_1.EventType.TOOL_CALL, `${startEvent.name}.completed`, {
|
|
68
|
+
...startEvent.payload,
|
|
69
|
+
output,
|
|
70
|
+
output_length: output.length,
|
|
71
|
+
}, startEvent.metadata);
|
|
72
|
+
this.client.track(event);
|
|
73
|
+
this.pendingEvents.delete(runId);
|
|
74
|
+
}
|
|
75
|
+
handleToolError(error, runId) {
|
|
76
|
+
const startEvent = this.pendingEvents.get(runId);
|
|
77
|
+
if (!startEvent)
|
|
78
|
+
return;
|
|
79
|
+
const event = (0, events_js_1.createEvent)(events_js_1.EventType.TOOL_CALL, `${startEvent.name}.error`, {
|
|
80
|
+
...startEvent.payload,
|
|
81
|
+
error: error.message,
|
|
82
|
+
error_type: error.name,
|
|
83
|
+
}, startEvent.metadata);
|
|
84
|
+
this.client.track(event);
|
|
85
|
+
this.pendingEvents.delete(runId);
|
|
86
|
+
}
|
|
87
|
+
handleChainStart(chain, inputs, runId, parentRunId, tags, metadata) {
|
|
88
|
+
const event = (0, events_js_1.createEvent)(events_js_1.EventType.DECISION, `langchain.chain.${chain.name}`, {
|
|
89
|
+
inputs,
|
|
90
|
+
input_keys: Object.keys(inputs),
|
|
91
|
+
}, {
|
|
92
|
+
run_id: runId,
|
|
93
|
+
parent_run_id: parentRunId,
|
|
94
|
+
tags: tags ?? [],
|
|
95
|
+
...metadata,
|
|
96
|
+
});
|
|
97
|
+
this.pendingEvents.set(runId, event);
|
|
98
|
+
this.client.track(event);
|
|
99
|
+
}
|
|
100
|
+
handleChainEnd(outputs, runId) {
|
|
101
|
+
const startEvent = this.pendingEvents.get(runId);
|
|
102
|
+
if (!startEvent)
|
|
103
|
+
return;
|
|
104
|
+
const event = (0, events_js_1.createEvent)(events_js_1.EventType.DECISION, `${startEvent.name}.completed`, {
|
|
105
|
+
...startEvent.payload,
|
|
106
|
+
outputs,
|
|
107
|
+
output_keys: Object.keys(outputs),
|
|
108
|
+
}, startEvent.metadata);
|
|
109
|
+
this.client.track(event);
|
|
110
|
+
this.pendingEvents.delete(runId);
|
|
111
|
+
}
|
|
112
|
+
handleChainError(error, runId) {
|
|
113
|
+
const startEvent = this.pendingEvents.get(runId);
|
|
114
|
+
if (!startEvent)
|
|
115
|
+
return;
|
|
116
|
+
const event = (0, events_js_1.createEvent)(events_js_1.EventType.DECISION, `${startEvent.name}.error`, {
|
|
117
|
+
...startEvent.payload,
|
|
118
|
+
error: error.message,
|
|
119
|
+
error_type: error.name,
|
|
120
|
+
}, startEvent.metadata);
|
|
121
|
+
this.client.track(event);
|
|
122
|
+
this.pendingEvents.delete(runId);
|
|
123
|
+
}
|
|
124
|
+
getPendingEventCount() {
|
|
125
|
+
return this.pendingEvents.size;
|
|
126
|
+
}
|
|
127
|
+
clearPendingEvents() {
|
|
128
|
+
this.pendingEvents.clear();
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
exports.TruseraLangChainHandler = TruseraLangChainHandler;
|
|
132
|
+
//# sourceMappingURL=langchain.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"langchain.js","sourceRoot":"","sources":["../../src/integrations/langchain.ts"],"names":[],"mappings":";;;AACA,4CAAkE;AAwBlE,MAAa,uBAAuB;IACjB,MAAM,CAAgB;IACtB,aAAa,GAAG,IAAI,GAAG,EAAiB,CAAC;IAE1D,YAAY,MAAqB;QAC/B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAKD,cAAc,CACZ,GAAqB,EACrB,OAAiB,EACjB,KAAa,EACb,WAAoB,EACpB,WAAqC,EACrC,IAAe,EACf,QAAkC;QAElC,MAAM,KAAK,GAAG,IAAA,uBAAW,EACvB,q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,KAAK,EAAE,CAAC;IAC7B,CAAC;CACF;AA3QD,0DA2QC"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { TruseraClient } from "./client.js";
|
|
2
|
+
export type EnforcementMode = "block" | "warn" | "log";
|
|
3
|
+
export interface InterceptorOptions {
|
|
4
|
+
enforcement?: EnforcementMode;
|
|
5
|
+
policyUrl?: string;
|
|
6
|
+
excludePatterns?: string[];
|
|
7
|
+
debug?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export declare class TruseraInterceptor {
|
|
10
|
+
private client;
|
|
11
|
+
private options;
|
|
12
|
+
private excludeRegexes;
|
|
13
|
+
private isInstalled;
|
|
14
|
+
install(client: TruseraClient, options?: InterceptorOptions): void;
|
|
15
|
+
uninstall(): void;
|
|
16
|
+
private createInterceptedFetch;
|
|
17
|
+
private shouldExclude;
|
|
18
|
+
private extractRequestData;
|
|
19
|
+
private evaluatePolicy;
|
|
20
|
+
private generateEventName;
|
|
21
|
+
private log;
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=interceptor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interceptor.d.ts","sourceRoot":"","sources":["../src/interceptor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAMjD,MAAM,MAAM,eAAe,GAAG,OAAO,GAAG,MAAM,GAAG,KAAK,CAAC;AAKvD,MAAM,WAAW,kBAAkB;IAEjC,WAAW,CAAC,EAAE,eAAe,CAAC;IAE9B,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAE3B,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAoDD,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,MAAM,CAA8B;IAC5C,OAAO,CAAC,OAAO,CAKb;IACF,OAAO,CAAC,cAAc,CAAgB;IACtC,OAAO,CAAC,WAAW,CAAS;IAU5B,OAAO,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,GAAE,kBAAuB,GAAG,IAAI;IAwCtE,SAAS,IAAI,IAAI;IAoBjB,OAAO,CAAC,sBAAsB;IA8H9B,OAAO,CAAC,aAAa;YAOP,kBAAkB;YAyClB,cAAc;IA0C5B,OAAO,CAAC,iBAAiB;IAWzB,OAAO,CAAC,GAAG;CAKZ"}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TruseraInterceptor = void 0;
|
|
4
|
+
const events_js_1 = require("./events.js");
|
|
5
|
+
let activeInterceptor = null;
|
|
6
|
+
let originalFetch = null;
|
|
7
|
+
class TruseraInterceptor {
|
|
8
|
+
client = null;
|
|
9
|
+
options = {
|
|
10
|
+
enforcement: "log",
|
|
11
|
+
policyUrl: "",
|
|
12
|
+
excludePatterns: [],
|
|
13
|
+
debug: false,
|
|
14
|
+
};
|
|
15
|
+
excludeRegexes = [];
|
|
16
|
+
isInstalled = false;
|
|
17
|
+
install(client, options = {}) {
|
|
18
|
+
if (activeInterceptor !== null && activeInterceptor !== this) {
|
|
19
|
+
throw new Error("Another TruseraInterceptor is already installed. Call uninstall() first.");
|
|
20
|
+
}
|
|
21
|
+
if (this.isInstalled) {
|
|
22
|
+
this.log("Interceptor already installed");
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
this.client = client;
|
|
26
|
+
this.options = {
|
|
27
|
+
enforcement: options.enforcement ?? "log",
|
|
28
|
+
policyUrl: options.policyUrl ?? "",
|
|
29
|
+
excludePatterns: options.excludePatterns ?? [],
|
|
30
|
+
debug: options.debug ?? false,
|
|
31
|
+
};
|
|
32
|
+
this.excludeRegexes = this.options.excludePatterns.map((pattern) => new RegExp(pattern));
|
|
33
|
+
if (originalFetch === null) {
|
|
34
|
+
originalFetch = globalThis.fetch;
|
|
35
|
+
}
|
|
36
|
+
globalThis.fetch = this.createInterceptedFetch();
|
|
37
|
+
activeInterceptor = this;
|
|
38
|
+
this.isInstalled = true;
|
|
39
|
+
this.log("Interceptor installed", {
|
|
40
|
+
enforcement: this.options.enforcement,
|
|
41
|
+
policyUrl: this.options.policyUrl,
|
|
42
|
+
excludePatterns: this.options.excludePatterns.length,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
uninstall() {
|
|
46
|
+
if (!this.isInstalled) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (originalFetch !== null) {
|
|
50
|
+
globalThis.fetch = originalFetch;
|
|
51
|
+
}
|
|
52
|
+
activeInterceptor = null;
|
|
53
|
+
this.isInstalled = false;
|
|
54
|
+
this.client = null;
|
|
55
|
+
this.log("Interceptor uninstalled");
|
|
56
|
+
}
|
|
57
|
+
createInterceptedFetch() {
|
|
58
|
+
const self = this;
|
|
59
|
+
return async function interceptedFetch(input, init) {
|
|
60
|
+
if (originalFetch === null) {
|
|
61
|
+
throw new Error("Original fetch not available");
|
|
62
|
+
}
|
|
63
|
+
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
64
|
+
const method = init?.method ?? "GET";
|
|
65
|
+
if (self.shouldExclude(url)) {
|
|
66
|
+
self.log("Skipping excluded URL", { url });
|
|
67
|
+
return originalFetch(input, init);
|
|
68
|
+
}
|
|
69
|
+
self.log("Intercepting request", { method, url });
|
|
70
|
+
const requestData = await self.extractRequestData(input, init);
|
|
71
|
+
const event = (0, events_js_1.createEvent)(events_js_1.EventType.API_CALL, self.generateEventName(url, method), {
|
|
72
|
+
method,
|
|
73
|
+
url,
|
|
74
|
+
headers: requestData.headers,
|
|
75
|
+
body: requestData.body,
|
|
76
|
+
}, {
|
|
77
|
+
interception_mode: self.options.enforcement,
|
|
78
|
+
});
|
|
79
|
+
if (self.options.policyUrl) {
|
|
80
|
+
const policyDecision = await self.evaluatePolicy(url, method, requestData);
|
|
81
|
+
if (policyDecision.decision === "Deny") {
|
|
82
|
+
self.log("Policy violation detected", { url, reasons: policyDecision.reasons });
|
|
83
|
+
const violationEvent = (0, events_js_1.createEvent)(events_js_1.EventType.API_CALL, `${self.generateEventName(url, method)}.policy_violation`, {
|
|
84
|
+
...event.payload,
|
|
85
|
+
policy_decision: "Deny",
|
|
86
|
+
policy_reasons: policyDecision.reasons,
|
|
87
|
+
});
|
|
88
|
+
self.client?.track(violationEvent);
|
|
89
|
+
if (self.options.enforcement === "block") {
|
|
90
|
+
throw new Error(`[Trusera] Policy violation: ${policyDecision.reasons?.join(", ") ?? "Request denied"}`);
|
|
91
|
+
}
|
|
92
|
+
else if (self.options.enforcement === "warn") {
|
|
93
|
+
console.warn(`[Trusera] Policy violation (allowed): ${policyDecision.reasons?.join(", ") ?? "Request denied"}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
self.log("Policy check passed", { url });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
self.client?.track(event);
|
|
101
|
+
const startTime = Date.now();
|
|
102
|
+
let response;
|
|
103
|
+
let error;
|
|
104
|
+
try {
|
|
105
|
+
response = await originalFetch(input, init);
|
|
106
|
+
}
|
|
107
|
+
catch (err) {
|
|
108
|
+
error = err;
|
|
109
|
+
self.log("Request failed", { url, error: error.message });
|
|
110
|
+
const errorEvent = (0, events_js_1.createEvent)(events_js_1.EventType.API_CALL, `${self.generateEventName(url, method)}.error`, {
|
|
111
|
+
...event.payload,
|
|
112
|
+
error: error.message,
|
|
113
|
+
duration_ms: Date.now() - startTime,
|
|
114
|
+
});
|
|
115
|
+
self.client?.track(errorEvent);
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
const responseEvent = (0, events_js_1.createEvent)(events_js_1.EventType.API_CALL, `${self.generateEventName(url, method)}.response`, {
|
|
119
|
+
...event.payload,
|
|
120
|
+
status: response.status,
|
|
121
|
+
status_text: response.statusText,
|
|
122
|
+
duration_ms: Date.now() - startTime,
|
|
123
|
+
response_headers: (() => { const h = {}; response.headers.forEach((v, k) => { h[k] = v; }); return h; })(),
|
|
124
|
+
});
|
|
125
|
+
self.client?.track(responseEvent);
|
|
126
|
+
return response;
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
shouldExclude(url) {
|
|
130
|
+
return this.excludeRegexes.some((regex) => regex.test(url));
|
|
131
|
+
}
|
|
132
|
+
async extractRequestData(_input, init) {
|
|
133
|
+
const headers = {};
|
|
134
|
+
if (init?.headers) {
|
|
135
|
+
if (init.headers instanceof Headers) {
|
|
136
|
+
init.headers.forEach((value, key) => {
|
|
137
|
+
headers[key] = value;
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
else if (Array.isArray(init.headers)) {
|
|
141
|
+
for (const [key, value] of init.headers) {
|
|
142
|
+
headers[key] = value;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
Object.assign(headers, init.headers);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
let body = null;
|
|
150
|
+
if (init?.body) {
|
|
151
|
+
if (typeof init.body === "string") {
|
|
152
|
+
body = init.body;
|
|
153
|
+
}
|
|
154
|
+
else if (init.body instanceof URLSearchParams) {
|
|
155
|
+
body = init.body.toString();
|
|
156
|
+
}
|
|
157
|
+
else if (init.body instanceof FormData) {
|
|
158
|
+
body = "[FormData]";
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
body = "[Binary data]";
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return { headers, body };
|
|
165
|
+
}
|
|
166
|
+
async evaluatePolicy(url, method, requestData) {
|
|
167
|
+
if (!this.options.policyUrl || !originalFetch) {
|
|
168
|
+
return { decision: "Allow" };
|
|
169
|
+
}
|
|
170
|
+
try {
|
|
171
|
+
const evaluationRequest = {
|
|
172
|
+
principal: this.client?.getAgentId() ?? "unknown-agent",
|
|
173
|
+
action: `http.${method.toLowerCase()}`,
|
|
174
|
+
resource: url,
|
|
175
|
+
context: {
|
|
176
|
+
headers: requestData.headers,
|
|
177
|
+
body_present: requestData.body !== null,
|
|
178
|
+
timestamp: new Date().toISOString(),
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
const response = await originalFetch(this.options.policyUrl, {
|
|
182
|
+
method: "POST",
|
|
183
|
+
headers: { "Content-Type": "application/json" },
|
|
184
|
+
body: JSON.stringify(evaluationRequest),
|
|
185
|
+
});
|
|
186
|
+
if (!response.ok) {
|
|
187
|
+
console.error(`[Trusera] Policy evaluation failed: ${response.status}`);
|
|
188
|
+
return { decision: "Allow" };
|
|
189
|
+
}
|
|
190
|
+
return (await response.json());
|
|
191
|
+
}
|
|
192
|
+
catch (error) {
|
|
193
|
+
console.error("[Trusera] Policy evaluation error:", error);
|
|
194
|
+
return { decision: "Allow" };
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
generateEventName(url, method) {
|
|
198
|
+
try {
|
|
199
|
+
const urlObj = new URL(url);
|
|
200
|
+
const hostname = urlObj.hostname.replace(/\./g, "_");
|
|
201
|
+
const path = urlObj.pathname.split("/").filter(Boolean).join("_") || "root";
|
|
202
|
+
return `http.${method.toLowerCase()}.${hostname}.${path}`;
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
return `http.${method.toLowerCase()}.invalid_url`;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
log(message, data) {
|
|
209
|
+
if (this.options.debug) {
|
|
210
|
+
console.log(`[Trusera Interceptor] ${message}`, data ?? "");
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
exports.TruseraInterceptor = TruseraInterceptor;
|
|
215
|
+
//# sourceMappingURL=interceptor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interceptor.js","sourceRoot":"","sources":["../src/interceptor.ts"],"names":[],"mappings":";;;AACA,2CAAqD;AA2CrD,IAAI,iBAAiB,GAA8B,IAAI,CAAC;AACxD,IAAI,aAAa,GAAmC,IAAI,CAAC;AA2BzD,MAAa,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AM,CAAC;YAC5E,OAAO,QAAQ,MAAM,CAAC,WAAW,EAAE,IAAI,QAAQ,IAAI,IAAI,EAAE,CAAC;QAC5D,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,QAAQ,MAAM,CAAC,WAAW,EAAE,cAAc,CAAC;QACpD,CAAC;IACH,CAAC;IAEO,GAAG,CAAC,OAAe,EAAE,IAA8B;QACzD,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;YACvB,OAAO,CAAC,GAAG,CAAC,yBAAyB,OAAO,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC;QAC9D,CAAC;IACH,CAAC;CACF;AAvTD,gDAuTC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "trusera-sdk",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "TypeScript SDK for monitoring AI agents with Trusera - intercept HTTP, evaluate policies",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"license": "Apache-2.0",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/Trusera/trusera-sdk-js"
|
|
11
|
+
},
|
|
12
|
+
"keywords": [
|
|
13
|
+
"ai",
|
|
14
|
+
"agents",
|
|
15
|
+
"monitoring",
|
|
16
|
+
"security",
|
|
17
|
+
"interceptor",
|
|
18
|
+
"observability",
|
|
19
|
+
"langchain",
|
|
20
|
+
"ai-security",
|
|
21
|
+
"agent-monitoring",
|
|
22
|
+
"policy-enforcement"
|
|
23
|
+
],
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=18.0.0"
|
|
26
|
+
},
|
|
27
|
+
"scripts": {
|
|
28
|
+
"build": "tsc",
|
|
29
|
+
"test": "vitest run",
|
|
30
|
+
"test:watch": "vitest",
|
|
31
|
+
"lint": "eslint src/",
|
|
32
|
+
"prepublishOnly": "npm run build"
|
|
33
|
+
},
|
|
34
|
+
"files": [
|
|
35
|
+
"dist",
|
|
36
|
+
"README.md",
|
|
37
|
+
"LICENSE"
|
|
38
|
+
],
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"langchain": ">=0.1.0"
|
|
41
|
+
},
|
|
42
|
+
"peerDependenciesMeta": {
|
|
43
|
+
"langchain": {
|
|
44
|
+
"optional": true
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@types/node": "^20.0.0",
|
|
49
|
+
"eslint": "^8.0.0",
|
|
50
|
+
"typescript": "^5.3.0",
|
|
51
|
+
"vitest": "^1.0.0"
|
|
52
|
+
}
|
|
53
|
+
}
|