-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
272 lines (243 loc) · 9.66 KB
/
index.js
File metadata and controls
272 lines (243 loc) · 9.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
'use strict';
const DEFAULT_BASE_URL = 'https://trustloop-production.up.railway.app';
class TrustLoop {
/**
* @param {object} options
* @param {string} options.apiKey - Your TrustLoop API key (tl_...)
* @param {string} [options.baseUrl] - Override the API base URL (default: TrustLoop cloud)
*/
constructor({ apiKey, baseUrl = DEFAULT_BASE_URL } = {}) {
if (!apiKey) throw new Error('[TrustLoop] apiKey is required. Get yours at https://trustloop.live/signup');
this.apiKey = apiKey;
this.baseUrl = baseUrl.replace(/\/$/, '');
}
// ─── Internal ────────────────────────────────────────────────────────────
async _request(method, path, body) {
const url = `${this.baseUrl}${path}`;
const headers = { 'x-api-key': this.apiKey, 'Content-Type': 'application/json' };
const res = await fetch(url, {
method,
headers,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
if (!res.ok) {
let msg;
try { msg = (await res.json()).error || res.statusText; } catch { msg = res.statusText; }
throw new TrustLoopError(msg, res.status);
}
const ct = res.headers.get('content-type') || '';
if (ct.includes('text/csv')) return res.text();
return res.json();
}
// ─── Core Governance ─────────────────────────────────────────────────────
/**
* Intercept a tool call before executing it.
* Returns ALLOWED, BLOCKED, or PENDING (requires human approval).
*
* @param {string} toolName - The name of the tool being called
* @param {object} [args={}] - The arguments being passed to the tool
* @returns {Promise<InterceptResult>}
*
* @example
* const result = await tl.intercept('send_email', { to: 'ceo@bank.com', body: '...' });
* if (!result.allowed) throw new Error(result.message);
*/
async intercept(toolName, args = {}) {
return this._request('POST', '/api/intercept', { tool_name: toolName, arguments: args });
}
// ─── Audit Log ───────────────────────────────────────────────────────────
/**
* Fetch the audit log of all tool calls for your tenant.
*
* @param {object} [options]
* @param {number} [options.limit=50] - Max records to return
* @param {number} [options.offset=0] - Pagination offset
* @param {string} [options.status] - Filter by status: ALLOWED, BLOCKED, PENDING, APPROVED, DENIED
* @param {string} [options.toolName] - Filter by tool name
* @returns {Promise<ToolCall[]>}
*/
async getLogs({ limit = 50, offset = 0, status, toolName } = {}) {
const params = new URLSearchParams({ limit, offset });
if (status) params.set('status', status);
if (toolName) params.set('tool_name', toolName);
return this._request('GET', `/api/logs?${params}`);
}
/**
* Export the full audit log as a CSV string.
* @returns {Promise<string>} CSV content
*/
async exportLogs() {
return this._request('GET', '/api/logs/export');
}
/**
* Get dashboard stats: totals, breakdown by status, and monthly usage.
* @returns {Promise<Stats>}
*/
async getStats() {
return this._request('GET', '/api/stats');
}
// ─── Governance Rules ────────────────────────────────────────────────────
/**
* List all governance rules for your tenant.
* @returns {Promise<Rule[]>}
*/
async getRules() {
return this._request('GET', '/api/approval-rules');
}
/**
* Create a new governance rule in plain English.
*
* @param {object} rule
* @param {string} rule.rule_text - Plain English rule (e.g. "Block any delete operations")
* @param {'approve'|'block'} [rule.action='approve'] - What to do when rule matches
* @param {string} [rule.approver_email] - Who to notify for approval (overrides default)
* @returns {Promise<Rule>}
*
* @example
* await tl.createRule({
* rule_text: 'Any wire transfer over £10,000 requires human approval',
* action: 'approve',
* approver_email: 'cfo@mycompany.com'
* });
*/
async createRule({ rule_text, action = 'approve', approver_email } = {}) {
return this._request('POST', '/api/approval-rules', { rule_text, action, approver_email });
}
/**
* Delete a governance rule by ID.
* @param {string} ruleId
* @returns {Promise<{success: boolean}>}
*/
async deleteRule(ruleId) {
return this._request('DELETE', `/api/approval-rules/${ruleId}`);
}
// ─── Kill Switch ─────────────────────────────────────────────────────────
/**
* List all tools currently on the kill-switch (blocked) list.
* @returns {Promise<BlockedTool[]>}
*/
async getBlockedTools() {
return this._request('GET', '/api/blocked-tools');
}
/**
* Instantly block a tool by name. Any agent call to this tool will be
* rejected immediately, before any rule evaluation.
*
* @param {string} toolName - The tool name to block
* @param {string} [reason=''] - Why this tool is blocked (for audit trail)
* @returns {Promise<BlockedTool>}
*
* @example
* await tl.blockTool('drop_table', 'Emergency: destructive DB operations disabled');
*/
async blockTool(toolName, reason = '') {
return this._request('POST', '/api/blocked-tools', { tool_name: toolName, reason });
}
/**
* Remove a tool from the kill-switch list.
* @param {string} toolName
* @returns {Promise<{success: boolean}>}
*/
async unblockTool(toolName) {
return this._request('DELETE', `/api/blocked-tools/${encodeURIComponent(toolName)}`);
}
// ─── Human Approvals ─────────────────────────────────────────────────────
/**
* List all tool calls currently awaiting human approval.
* @returns {Promise<PendingApproval[]>}
*/
async getPendingApprovals() {
return this._request('GET', '/api/pending-approvals');
}
/**
* Programmatically approve or deny a pending tool call.
* (Approvers can also click the email link — this is for API-driven workflows.)
*
* @param {string} approvalId - The pending approval ID
* @param {'approved'|'denied'} action
* @returns {Promise<PendingApproval>}
*/
async decide(approvalId, action) {
return this._request('POST', `/api/pending-approvals/${approvalId}/decide`, { action });
}
// ─── Notifications ───────────────────────────────────────────────────────
/**
* Get current notification settings (email, Slack, Teams, Discord).
* @returns {Promise<NotificationSettings>}
*/
async getNotifications() {
return this._request('GET', '/api/notification-settings');
}
/**
* Update notification settings.
*
* @param {object} settings
* @param {string} [settings.notify_email] - Email to notify on pending approvals
* @param {string} [settings.slack_webhook_url]
* @param {string} [settings.teams_webhook_url]
* @param {string} [settings.discord_webhook_url]
* @returns {Promise<NotificationSettings>}
*/
async updateNotifications(settings) {
return this._request('PUT', '/api/notification-settings', settings);
}
// ─── Static Helpers ──────────────────────────────────────────────────────
/**
* Get the OpenAI client configuration to route through TrustLoop.
* Pass the returned config to the OpenAI constructor.
*
* @param {string} openaiApiKey - Your OpenAI API key
* @param {string} trustLoopApiKey - Your TrustLoop API key
* @param {object} [options]
* @param {string} [options.baseUrl] - Override TrustLoop base URL
* @returns {object} Config object for `new OpenAI(config)`
*
* @example
* import OpenAI from 'openai';
* import TrustLoop from 'trustloop';
*
* const client = new OpenAI(
* TrustLoop.openai('sk-your-openai-key', 'tl_your-trustloop-key')
* );
* // All tool calls are now governed automatically
*/
static openai(openaiApiKey, trustLoopApiKey, { baseUrl = DEFAULT_BASE_URL } = {}) {
return {
apiKey: openaiApiKey,
baseURL: `${baseUrl}/v1`,
defaultHeaders: { 'x-api-key': trustLoopApiKey },
};
}
/**
* Get the MCP server URL for use in Claude Desktop or Cline config.
*
* @param {string} trustLoopApiKey - Your TrustLoop API key
* @param {object} [options]
* @param {string} [options.baseUrl] - Override TrustLoop base URL
* @returns {string} The SSE URL to paste into your MCP client config
*
* @example
* // claude_desktop_config.json
* {
* "mcpServers": {
* "trustloop": {
* "url": TrustLoop.mcpUrl('tl_your-key')
* }
* }
* }
*/
static mcpUrl(trustLoopApiKey, { baseUrl = DEFAULT_BASE_URL } = {}) {
return `${baseUrl}/sse?api_key=${trustLoopApiKey}`;
}
}
class TrustLoopError extends Error {
constructor(message, status) {
super(message);
this.name = 'TrustLoopError';
this.status = status;
}
}
module.exports = TrustLoop;
module.exports.TrustLoop = TrustLoop;
module.exports.TrustLoopError = TrustLoopError;
module.exports.default = TrustLoop;