@2434addy/agentledger-sdk 0.2.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/README.md +120 -0
- package/dist/index.d.mts +106 -0
- package/dist/index.d.ts +106 -0
- package/dist/index.js +161 -0
- package/dist/index.mjs +131 -0
- package/package.json +47 -0
package/README.md
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# @agentledger/sdk
|
|
2
|
+
|
|
3
|
+
TypeScript SDK for AgentLedger — track, audit, and monitor your AI agents.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @agentledger/sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { AgentLedger } from '@agentledger/sdk'
|
|
15
|
+
|
|
16
|
+
const al = new AgentLedger({ apiKey: 'al_live_sk_...' })
|
|
17
|
+
|
|
18
|
+
// Create an agent
|
|
19
|
+
const agent = await al.createAgent({
|
|
20
|
+
name: 'My Assistant',
|
|
21
|
+
description: 'Customer support bot',
|
|
22
|
+
modelProvider: 'anthropic',
|
|
23
|
+
modelId: 'claude-sonnet-4-6',
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
// Create a session
|
|
27
|
+
const session = await al.createSession({ agentId: agent.id })
|
|
28
|
+
|
|
29
|
+
// Track events (batched automatically)
|
|
30
|
+
al.track({
|
|
31
|
+
agentId: agent.id,
|
|
32
|
+
sessionId: session.id,
|
|
33
|
+
category: 'llm_call',
|
|
34
|
+
level: 'info',
|
|
35
|
+
message: 'Called Claude API',
|
|
36
|
+
metadata: { prompt: 'Hello world' },
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
// Send all queued events now
|
|
40
|
+
await al.flush()
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## API
|
|
44
|
+
|
|
45
|
+
### `new AgentLedger(config)`
|
|
46
|
+
|
|
47
|
+
| Option | Type | Default | Description |
|
|
48
|
+
| --------------- | -------- | ------------------------------------------ | ------------------------ |
|
|
49
|
+
| `apiKey` | `string` | *required* | Your API key |
|
|
50
|
+
| `baseUrl` | `string` | `https://api.agentledger.io/api/v1` | API base URL |
|
|
51
|
+
| `timeout` | `number` | `5000` | Request timeout (ms) |
|
|
52
|
+
| `flushInterval` | `number` | `5000` | Auto-flush interval (ms) |
|
|
53
|
+
| `maxBatchSize` | `number` | `50` | Max events per batch |
|
|
54
|
+
| `debug` | `boolean`| `false` | Log warnings to console |
|
|
55
|
+
|
|
56
|
+
### `al.createAgent(input)`
|
|
57
|
+
|
|
58
|
+
Create a registered agent.
|
|
59
|
+
|
|
60
|
+
```typescript
|
|
61
|
+
const agent = await al.createAgent({
|
|
62
|
+
name: 'Email Agent',
|
|
63
|
+
modelProvider: 'openai',
|
|
64
|
+
modelId: 'gpt-4o',
|
|
65
|
+
})
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### `al.createSession(input)`
|
|
69
|
+
|
|
70
|
+
Start a new session for an agent.
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
const session = await al.createSession({ agentId: agent.id })
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### `al.track(event)`
|
|
77
|
+
|
|
78
|
+
Queue an event for batched sending. Fires immediately when the batch reaches `maxBatchSize`.
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
al.track({
|
|
82
|
+
agentId: agent.id,
|
|
83
|
+
sessionId: session.id,
|
|
84
|
+
category: 'llm_call',
|
|
85
|
+
level: 'info',
|
|
86
|
+
message: 'Generated response',
|
|
87
|
+
metadata: { model: 'claude-sonnet-4-6' },
|
|
88
|
+
tokensInput: 150,
|
|
89
|
+
tokensOutput: 420,
|
|
90
|
+
latencyMs: 1200,
|
|
91
|
+
})
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### `al.flush()`
|
|
95
|
+
|
|
96
|
+
Send all queued events immediately. Returns the created events.
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
const events = await al.flush()
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### `al.shutdown()`
|
|
103
|
+
|
|
104
|
+
Stop the auto-flush timer and send remaining events. Call before process exit.
|
|
105
|
+
|
|
106
|
+
```typescript
|
|
107
|
+
process.on('beforeExit', () => al.shutdown())
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Event Categories
|
|
111
|
+
|
|
112
|
+
`agent_lifecycle` | `llm_call` | `tool_invocation` | `user_action` | `system` | `security` | `guardrail`
|
|
113
|
+
|
|
114
|
+
## Event Levels
|
|
115
|
+
|
|
116
|
+
`debug` | `info` | `warn` | `error` | `fatal`
|
|
117
|
+
|
|
118
|
+
## License
|
|
119
|
+
|
|
120
|
+
MIT
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
interface AgentLedgerConfig {
|
|
2
|
+
apiKey: string;
|
|
3
|
+
baseUrl?: string;
|
|
4
|
+
timeout?: number;
|
|
5
|
+
flushInterval?: number;
|
|
6
|
+
maxBatchSize?: number;
|
|
7
|
+
debug?: boolean;
|
|
8
|
+
}
|
|
9
|
+
type EventCategory = 'agent_lifecycle' | 'llm_call' | 'tool_invocation' | 'user_action' | 'system' | 'security' | 'guardrail';
|
|
10
|
+
type EventLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal';
|
|
11
|
+
interface CreateAgentInput {
|
|
12
|
+
name: string;
|
|
13
|
+
description?: string;
|
|
14
|
+
modelProvider: string;
|
|
15
|
+
modelId: string;
|
|
16
|
+
metadata?: Record<string, unknown>;
|
|
17
|
+
}
|
|
18
|
+
interface Agent {
|
|
19
|
+
id: string;
|
|
20
|
+
name: string;
|
|
21
|
+
description: string | null;
|
|
22
|
+
modelProvider: string;
|
|
23
|
+
modelId: string;
|
|
24
|
+
status: string;
|
|
25
|
+
metadata: Record<string, unknown> | null;
|
|
26
|
+
createdAt: string;
|
|
27
|
+
updatedAt: string;
|
|
28
|
+
}
|
|
29
|
+
interface CreateSessionInput {
|
|
30
|
+
agentId: string;
|
|
31
|
+
metadata?: Record<string, unknown>;
|
|
32
|
+
}
|
|
33
|
+
interface Session {
|
|
34
|
+
id: string;
|
|
35
|
+
agentId: string;
|
|
36
|
+
status: string;
|
|
37
|
+
metadata: Record<string, unknown> | null;
|
|
38
|
+
startedAt: string;
|
|
39
|
+
}
|
|
40
|
+
interface TrackEventInput {
|
|
41
|
+
agentId: string;
|
|
42
|
+
sessionId?: string;
|
|
43
|
+
category: EventCategory;
|
|
44
|
+
level: EventLevel;
|
|
45
|
+
message: string;
|
|
46
|
+
metadata?: Record<string, unknown>;
|
|
47
|
+
tokensInput?: number;
|
|
48
|
+
tokensOutput?: number;
|
|
49
|
+
costUsd?: number;
|
|
50
|
+
latencyMs?: number;
|
|
51
|
+
}
|
|
52
|
+
interface TrackedEvent {
|
|
53
|
+
id: string;
|
|
54
|
+
agentId: string;
|
|
55
|
+
sessionId: string | null;
|
|
56
|
+
category: EventCategory;
|
|
57
|
+
level: EventLevel;
|
|
58
|
+
message: string;
|
|
59
|
+
hash: string;
|
|
60
|
+
prevHash: string | null;
|
|
61
|
+
createdAt: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
declare class AgentLedger {
|
|
65
|
+
private readonly baseUrl;
|
|
66
|
+
private readonly apiKey;
|
|
67
|
+
private readonly timeout;
|
|
68
|
+
private readonly maxBatchSize;
|
|
69
|
+
private readonly debug;
|
|
70
|
+
private queue;
|
|
71
|
+
private flushTimer;
|
|
72
|
+
constructor(config: AgentLedgerConfig);
|
|
73
|
+
createAgent(input: CreateAgentInput): Promise<Agent>;
|
|
74
|
+
createSession(input: CreateSessionInput): Promise<Session>;
|
|
75
|
+
/**
|
|
76
|
+
* Queue an event for batched sending. Events are auto-flushed at
|
|
77
|
+
* the configured `flushInterval` or when the batch reaches `maxBatchSize`.
|
|
78
|
+
* Returns immediately — call `flush()` to send synchronously.
|
|
79
|
+
*/
|
|
80
|
+
track(event: TrackEventInput): void;
|
|
81
|
+
/**
|
|
82
|
+
* Send all queued events to the server immediately.
|
|
83
|
+
* Resolves with the created events, or an empty array if the queue was empty.
|
|
84
|
+
*/
|
|
85
|
+
flush(): Promise<TrackedEvent[]>;
|
|
86
|
+
/**
|
|
87
|
+
* Stop the auto-flush timer and send remaining events.
|
|
88
|
+
* Call this before your process exits.
|
|
89
|
+
*/
|
|
90
|
+
shutdown(): Promise<void>;
|
|
91
|
+
private request;
|
|
92
|
+
private withRetry;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
declare class AgentLedgerError extends Error {
|
|
96
|
+
code: string;
|
|
97
|
+
constructor(message: string, code: string);
|
|
98
|
+
}
|
|
99
|
+
declare class AuthenticationError extends AgentLedgerError {
|
|
100
|
+
constructor();
|
|
101
|
+
}
|
|
102
|
+
declare class NetworkError extends AgentLedgerError {
|
|
103
|
+
constructor(message: string);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export { type Agent, AgentLedger, type AgentLedgerConfig, AgentLedgerError, AuthenticationError, type CreateAgentInput, type CreateSessionInput, type EventCategory, type EventLevel, NetworkError, type Session, type TrackEventInput, type TrackedEvent };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
interface AgentLedgerConfig {
|
|
2
|
+
apiKey: string;
|
|
3
|
+
baseUrl?: string;
|
|
4
|
+
timeout?: number;
|
|
5
|
+
flushInterval?: number;
|
|
6
|
+
maxBatchSize?: number;
|
|
7
|
+
debug?: boolean;
|
|
8
|
+
}
|
|
9
|
+
type EventCategory = 'agent_lifecycle' | 'llm_call' | 'tool_invocation' | 'user_action' | 'system' | 'security' | 'guardrail';
|
|
10
|
+
type EventLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal';
|
|
11
|
+
interface CreateAgentInput {
|
|
12
|
+
name: string;
|
|
13
|
+
description?: string;
|
|
14
|
+
modelProvider: string;
|
|
15
|
+
modelId: string;
|
|
16
|
+
metadata?: Record<string, unknown>;
|
|
17
|
+
}
|
|
18
|
+
interface Agent {
|
|
19
|
+
id: string;
|
|
20
|
+
name: string;
|
|
21
|
+
description: string | null;
|
|
22
|
+
modelProvider: string;
|
|
23
|
+
modelId: string;
|
|
24
|
+
status: string;
|
|
25
|
+
metadata: Record<string, unknown> | null;
|
|
26
|
+
createdAt: string;
|
|
27
|
+
updatedAt: string;
|
|
28
|
+
}
|
|
29
|
+
interface CreateSessionInput {
|
|
30
|
+
agentId: string;
|
|
31
|
+
metadata?: Record<string, unknown>;
|
|
32
|
+
}
|
|
33
|
+
interface Session {
|
|
34
|
+
id: string;
|
|
35
|
+
agentId: string;
|
|
36
|
+
status: string;
|
|
37
|
+
metadata: Record<string, unknown> | null;
|
|
38
|
+
startedAt: string;
|
|
39
|
+
}
|
|
40
|
+
interface TrackEventInput {
|
|
41
|
+
agentId: string;
|
|
42
|
+
sessionId?: string;
|
|
43
|
+
category: EventCategory;
|
|
44
|
+
level: EventLevel;
|
|
45
|
+
message: string;
|
|
46
|
+
metadata?: Record<string, unknown>;
|
|
47
|
+
tokensInput?: number;
|
|
48
|
+
tokensOutput?: number;
|
|
49
|
+
costUsd?: number;
|
|
50
|
+
latencyMs?: number;
|
|
51
|
+
}
|
|
52
|
+
interface TrackedEvent {
|
|
53
|
+
id: string;
|
|
54
|
+
agentId: string;
|
|
55
|
+
sessionId: string | null;
|
|
56
|
+
category: EventCategory;
|
|
57
|
+
level: EventLevel;
|
|
58
|
+
message: string;
|
|
59
|
+
hash: string;
|
|
60
|
+
prevHash: string | null;
|
|
61
|
+
createdAt: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
declare class AgentLedger {
|
|
65
|
+
private readonly baseUrl;
|
|
66
|
+
private readonly apiKey;
|
|
67
|
+
private readonly timeout;
|
|
68
|
+
private readonly maxBatchSize;
|
|
69
|
+
private readonly debug;
|
|
70
|
+
private queue;
|
|
71
|
+
private flushTimer;
|
|
72
|
+
constructor(config: AgentLedgerConfig);
|
|
73
|
+
createAgent(input: CreateAgentInput): Promise<Agent>;
|
|
74
|
+
createSession(input: CreateSessionInput): Promise<Session>;
|
|
75
|
+
/**
|
|
76
|
+
* Queue an event for batched sending. Events are auto-flushed at
|
|
77
|
+
* the configured `flushInterval` or when the batch reaches `maxBatchSize`.
|
|
78
|
+
* Returns immediately — call `flush()` to send synchronously.
|
|
79
|
+
*/
|
|
80
|
+
track(event: TrackEventInput): void;
|
|
81
|
+
/**
|
|
82
|
+
* Send all queued events to the server immediately.
|
|
83
|
+
* Resolves with the created events, or an empty array if the queue was empty.
|
|
84
|
+
*/
|
|
85
|
+
flush(): Promise<TrackedEvent[]>;
|
|
86
|
+
/**
|
|
87
|
+
* Stop the auto-flush timer and send remaining events.
|
|
88
|
+
* Call this before your process exits.
|
|
89
|
+
*/
|
|
90
|
+
shutdown(): Promise<void>;
|
|
91
|
+
private request;
|
|
92
|
+
private withRetry;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
declare class AgentLedgerError extends Error {
|
|
96
|
+
code: string;
|
|
97
|
+
constructor(message: string, code: string);
|
|
98
|
+
}
|
|
99
|
+
declare class AuthenticationError extends AgentLedgerError {
|
|
100
|
+
constructor();
|
|
101
|
+
}
|
|
102
|
+
declare class NetworkError extends AgentLedgerError {
|
|
103
|
+
constructor(message: string);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export { type Agent, AgentLedger, type AgentLedgerConfig, AgentLedgerError, AuthenticationError, type CreateAgentInput, type CreateSessionInput, type EventCategory, type EventLevel, NetworkError, type Session, type TrackEventInput, type TrackedEvent };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
AgentLedger: () => AgentLedger,
|
|
24
|
+
AgentLedgerError: () => AgentLedgerError,
|
|
25
|
+
AuthenticationError: () => AuthenticationError,
|
|
26
|
+
NetworkError: () => NetworkError
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(index_exports);
|
|
29
|
+
|
|
30
|
+
// src/errors.ts
|
|
31
|
+
var AgentLedgerError = class extends Error {
|
|
32
|
+
constructor(message, code) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.code = code;
|
|
35
|
+
this.name = "AgentLedgerError";
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
var AuthenticationError = class extends AgentLedgerError {
|
|
39
|
+
constructor() {
|
|
40
|
+
super("Invalid API key. Check your apiKey in config.", "AUTH_ERROR");
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
var NetworkError = class extends AgentLedgerError {
|
|
44
|
+
constructor(message) {
|
|
45
|
+
super(`Network error: ${message}`, "NETWORK_ERROR");
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
// src/client.ts
|
|
50
|
+
var AgentLedger = class {
|
|
51
|
+
constructor(config) {
|
|
52
|
+
this.queue = [];
|
|
53
|
+
this.flushTimer = null;
|
|
54
|
+
if (!config.apiKey) throw new Error("AgentLedger: apiKey is required");
|
|
55
|
+
this.apiKey = config.apiKey;
|
|
56
|
+
this.baseUrl = (config.baseUrl || "https://api.agentledger.io/api/v1").replace(/\/$/, "");
|
|
57
|
+
this.timeout = config.timeout ?? 5e3;
|
|
58
|
+
this.maxBatchSize = config.maxBatchSize ?? 50;
|
|
59
|
+
this.debug = config.debug ?? false;
|
|
60
|
+
const flushInterval = config.flushInterval ?? 5e3;
|
|
61
|
+
if (flushInterval > 0) {
|
|
62
|
+
this.flushTimer = setInterval(() => this.flush().catch(() => {
|
|
63
|
+
}), flushInterval);
|
|
64
|
+
if (typeof this.flushTimer === "object" && "unref" in this.flushTimer) {
|
|
65
|
+
this.flushTimer.unref();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
// ── Agents ──────────────────────────────────────────────────────
|
|
70
|
+
async createAgent(input) {
|
|
71
|
+
return this.request("POST", "/agents", input);
|
|
72
|
+
}
|
|
73
|
+
// ── Sessions ────────────────────────────────────────────────────
|
|
74
|
+
async createSession(input) {
|
|
75
|
+
return this.request("POST", "/sessions", input);
|
|
76
|
+
}
|
|
77
|
+
// ── Events ──────────────────────────────────────────────────────
|
|
78
|
+
/**
|
|
79
|
+
* Queue an event for batched sending. Events are auto-flushed at
|
|
80
|
+
* the configured `flushInterval` or when the batch reaches `maxBatchSize`.
|
|
81
|
+
* Returns immediately — call `flush()` to send synchronously.
|
|
82
|
+
*/
|
|
83
|
+
track(event) {
|
|
84
|
+
this.queue.push(event);
|
|
85
|
+
if (this.queue.length >= this.maxBatchSize) {
|
|
86
|
+
this.flush().catch(() => {
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Send all queued events to the server immediately.
|
|
92
|
+
* Resolves with the created events, or an empty array if the queue was empty.
|
|
93
|
+
*/
|
|
94
|
+
async flush() {
|
|
95
|
+
if (this.queue.length === 0) return [];
|
|
96
|
+
const batch = this.queue.splice(0);
|
|
97
|
+
try {
|
|
98
|
+
return await this.request("POST", "/events", { events: batch });
|
|
99
|
+
} catch (err) {
|
|
100
|
+
this.queue.unshift(...batch);
|
|
101
|
+
throw err;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Stop the auto-flush timer and send remaining events.
|
|
106
|
+
* Call this before your process exits.
|
|
107
|
+
*/
|
|
108
|
+
async shutdown() {
|
|
109
|
+
if (this.flushTimer) {
|
|
110
|
+
clearInterval(this.flushTimer);
|
|
111
|
+
this.flushTimer = null;
|
|
112
|
+
}
|
|
113
|
+
await this.flush();
|
|
114
|
+
}
|
|
115
|
+
// ── HTTP helper ─────────────────────────────────────────────────
|
|
116
|
+
async request(method, path, body) {
|
|
117
|
+
return this.withRetry(async () => {
|
|
118
|
+
const controller = new AbortController();
|
|
119
|
+
const timer = setTimeout(() => controller.abort(), this.timeout);
|
|
120
|
+
try {
|
|
121
|
+
const res = await fetch(`${this.baseUrl}${path}`, {
|
|
122
|
+
method,
|
|
123
|
+
headers: {
|
|
124
|
+
"Content-Type": "application/json",
|
|
125
|
+
"x-api-key": this.apiKey
|
|
126
|
+
},
|
|
127
|
+
body: body ? JSON.stringify(body) : void 0,
|
|
128
|
+
signal: controller.signal
|
|
129
|
+
});
|
|
130
|
+
if (res.status === 401) throw new AuthenticationError();
|
|
131
|
+
if (!res.ok) {
|
|
132
|
+
const text = await res.text().catch(() => "");
|
|
133
|
+
throw new NetworkError(`HTTP ${res.status}: ${text}`);
|
|
134
|
+
}
|
|
135
|
+
return await res.json();
|
|
136
|
+
} finally {
|
|
137
|
+
clearTimeout(timer);
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
async withRetry(fn, attempts = 3) {
|
|
142
|
+
for (let i = 0; i < attempts; i++) {
|
|
143
|
+
try {
|
|
144
|
+
return await fn();
|
|
145
|
+
} catch (err) {
|
|
146
|
+
if (err instanceof AuthenticationError) throw err;
|
|
147
|
+
if (i === attempts - 1) throw err;
|
|
148
|
+
if (this.debug) console.warn(`[AgentLedger] Retry ${i + 1}/${attempts - 1}`, err);
|
|
149
|
+
await new Promise((r) => setTimeout(r, Math.pow(2, i) * 500));
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
throw new AgentLedgerError("Unreachable", "INTERNAL");
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
156
|
+
0 && (module.exports = {
|
|
157
|
+
AgentLedger,
|
|
158
|
+
AgentLedgerError,
|
|
159
|
+
AuthenticationError,
|
|
160
|
+
NetworkError
|
|
161
|
+
});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var AgentLedgerError = class extends Error {
|
|
3
|
+
constructor(message, code) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.code = code;
|
|
6
|
+
this.name = "AgentLedgerError";
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
var AuthenticationError = class extends AgentLedgerError {
|
|
10
|
+
constructor() {
|
|
11
|
+
super("Invalid API key. Check your apiKey in config.", "AUTH_ERROR");
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
var NetworkError = class extends AgentLedgerError {
|
|
15
|
+
constructor(message) {
|
|
16
|
+
super(`Network error: ${message}`, "NETWORK_ERROR");
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// src/client.ts
|
|
21
|
+
var AgentLedger = class {
|
|
22
|
+
constructor(config) {
|
|
23
|
+
this.queue = [];
|
|
24
|
+
this.flushTimer = null;
|
|
25
|
+
if (!config.apiKey) throw new Error("AgentLedger: apiKey is required");
|
|
26
|
+
this.apiKey = config.apiKey;
|
|
27
|
+
this.baseUrl = (config.baseUrl || "https://api.agentledger.io/api/v1").replace(/\/$/, "");
|
|
28
|
+
this.timeout = config.timeout ?? 5e3;
|
|
29
|
+
this.maxBatchSize = config.maxBatchSize ?? 50;
|
|
30
|
+
this.debug = config.debug ?? false;
|
|
31
|
+
const flushInterval = config.flushInterval ?? 5e3;
|
|
32
|
+
if (flushInterval > 0) {
|
|
33
|
+
this.flushTimer = setInterval(() => this.flush().catch(() => {
|
|
34
|
+
}), flushInterval);
|
|
35
|
+
if (typeof this.flushTimer === "object" && "unref" in this.flushTimer) {
|
|
36
|
+
this.flushTimer.unref();
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
// ── Agents ──────────────────────────────────────────────────────
|
|
41
|
+
async createAgent(input) {
|
|
42
|
+
return this.request("POST", "/agents", input);
|
|
43
|
+
}
|
|
44
|
+
// ── Sessions ────────────────────────────────────────────────────
|
|
45
|
+
async createSession(input) {
|
|
46
|
+
return this.request("POST", "/sessions", input);
|
|
47
|
+
}
|
|
48
|
+
// ── Events ──────────────────────────────────────────────────────
|
|
49
|
+
/**
|
|
50
|
+
* Queue an event for batched sending. Events are auto-flushed at
|
|
51
|
+
* the configured `flushInterval` or when the batch reaches `maxBatchSize`.
|
|
52
|
+
* Returns immediately — call `flush()` to send synchronously.
|
|
53
|
+
*/
|
|
54
|
+
track(event) {
|
|
55
|
+
this.queue.push(event);
|
|
56
|
+
if (this.queue.length >= this.maxBatchSize) {
|
|
57
|
+
this.flush().catch(() => {
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Send all queued events to the server immediately.
|
|
63
|
+
* Resolves with the created events, or an empty array if the queue was empty.
|
|
64
|
+
*/
|
|
65
|
+
async flush() {
|
|
66
|
+
if (this.queue.length === 0) return [];
|
|
67
|
+
const batch = this.queue.splice(0);
|
|
68
|
+
try {
|
|
69
|
+
return await this.request("POST", "/events", { events: batch });
|
|
70
|
+
} catch (err) {
|
|
71
|
+
this.queue.unshift(...batch);
|
|
72
|
+
throw err;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Stop the auto-flush timer and send remaining events.
|
|
77
|
+
* Call this before your process exits.
|
|
78
|
+
*/
|
|
79
|
+
async shutdown() {
|
|
80
|
+
if (this.flushTimer) {
|
|
81
|
+
clearInterval(this.flushTimer);
|
|
82
|
+
this.flushTimer = null;
|
|
83
|
+
}
|
|
84
|
+
await this.flush();
|
|
85
|
+
}
|
|
86
|
+
// ── HTTP helper ─────────────────────────────────────────────────
|
|
87
|
+
async request(method, path, body) {
|
|
88
|
+
return this.withRetry(async () => {
|
|
89
|
+
const controller = new AbortController();
|
|
90
|
+
const timer = setTimeout(() => controller.abort(), this.timeout);
|
|
91
|
+
try {
|
|
92
|
+
const res = await fetch(`${this.baseUrl}${path}`, {
|
|
93
|
+
method,
|
|
94
|
+
headers: {
|
|
95
|
+
"Content-Type": "application/json",
|
|
96
|
+
"x-api-key": this.apiKey
|
|
97
|
+
},
|
|
98
|
+
body: body ? JSON.stringify(body) : void 0,
|
|
99
|
+
signal: controller.signal
|
|
100
|
+
});
|
|
101
|
+
if (res.status === 401) throw new AuthenticationError();
|
|
102
|
+
if (!res.ok) {
|
|
103
|
+
const text = await res.text().catch(() => "");
|
|
104
|
+
throw new NetworkError(`HTTP ${res.status}: ${text}`);
|
|
105
|
+
}
|
|
106
|
+
return await res.json();
|
|
107
|
+
} finally {
|
|
108
|
+
clearTimeout(timer);
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
async withRetry(fn, attempts = 3) {
|
|
113
|
+
for (let i = 0; i < attempts; i++) {
|
|
114
|
+
try {
|
|
115
|
+
return await fn();
|
|
116
|
+
} catch (err) {
|
|
117
|
+
if (err instanceof AuthenticationError) throw err;
|
|
118
|
+
if (i === attempts - 1) throw err;
|
|
119
|
+
if (this.debug) console.warn(`[AgentLedger] Retry ${i + 1}/${attempts - 1}`, err);
|
|
120
|
+
await new Promise((r) => setTimeout(r, Math.pow(2, i) * 500));
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
throw new AgentLedgerError("Unreachable", "INTERNAL");
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
export {
|
|
127
|
+
AgentLedger,
|
|
128
|
+
AgentLedgerError,
|
|
129
|
+
AuthenticationError,
|
|
130
|
+
NetworkError
|
|
131
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@2434addy/agentledger-sdk",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "TypeScript SDK for AgentLedger — track, audit, and monitor your AI agents.",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"module": "dist/index.mjs",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.mjs",
|
|
12
|
+
"require": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsup src/index.ts --format cjs,esm --dts",
|
|
20
|
+
"dev": "tsup src/index.ts --format cjs,esm --dts --watch",
|
|
21
|
+
"lint": "tsc --noEmit"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"ai-agents",
|
|
25
|
+
"audit-trail",
|
|
26
|
+
"compliance",
|
|
27
|
+
"observability",
|
|
28
|
+
"monitoring",
|
|
29
|
+
"langchain",
|
|
30
|
+
"openai",
|
|
31
|
+
"crewai"
|
|
32
|
+
],
|
|
33
|
+
"author": "AgentLedger",
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"tsup": "^8.0.0",
|
|
37
|
+
"typescript": "^5.0.0"
|
|
38
|
+
},
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=18.0.0"
|
|
41
|
+
},
|
|
42
|
+
"repository": {
|
|
43
|
+
"type": "git",
|
|
44
|
+
"url": "https://github.com/2434addy/AgentLedger.git",
|
|
45
|
+
"directory": "sdk"
|
|
46
|
+
}
|
|
47
|
+
}
|