-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic-usage.js
More file actions
703 lines (629 loc) Β· 20.2 KB
/
basic-usage.js
File metadata and controls
703 lines (629 loc) Β· 20.2 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
/**
* Basic JavaScript/Node.js examples for The Passport for AI Agents
*/
const https = require("https");
// Configuration
const API_BASE_URL = process.env.API_URL || "https://api.aport.io";
const ADMIN_TOKEN = process.env.ADMIN_TOKEN || "your-admin-token";
/**
* Make HTTP request helper
*/
function makeRequest(url, options = {}) {
return new Promise((resolve, reject) => {
const req = https.request(url, options, (res) => {
let data = "";
res.on("data", (chunk) => (data += chunk));
res.on("end", () => {
try {
const jsonData = JSON.parse(data);
resolve({
status: res.statusCode,
data: jsonData,
headers: res.headers,
});
} catch (e) {
resolve({ status: res.statusCode, data: data, headers: res.headers });
}
});
});
req.on("error", reject);
if (options.body) {
req.write(options.body);
}
req.end();
});
}
/**
* Verify an agent passport
*/
async function verifyPassport(agentId) {
console.log(`\nπ Verifying passport for agent: ${agentId}`);
try {
const response = await makeRequest(`${API_BASE_URL}/api/verify/${agentId}`);
if (response.status === 200) {
console.log("β
Passport verified successfully:");
console.log(JSON.stringify(response.data, null, 2));
// Check rate limit headers
console.log("\nπ Rate Limit Info:");
console.log(`Limit: ${response.headers["x-ratelimit-limit"]}`);
console.log(`Remaining: ${response.headers["x-ratelimit-remaining"]}`);
console.log(
`Reset: ${new Date(
parseInt(response.headers["x-ratelimit-reset"]) * 1000
)}`
);
} else {
console.log(`β Verification failed (${response.status}):`);
console.log(JSON.stringify(response.data, null, 2));
}
} catch (error) {
console.error("β Error verifying passport:", error.message);
}
}
/**
* Create a new agent passport
*/
async function createPassport(passportData) {
console.log("\nπ Creating new passport...");
try {
const response = await makeRequest(`${API_BASE_URL}/api/admin/create`, {
method: "POST",
headers: {
Authorization: `Bearer ${ADMIN_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify(passportData),
});
if (response.status === 201) {
console.log("β
Passport created successfully:");
console.log(JSON.stringify(response.data, null, 2));
} else {
console.log(`β Creation failed (${response.status}):`);
console.log(JSON.stringify(response.data, null, 2));
}
} catch (error) {
console.error("β Error creating passport:", error.message);
}
}
/**
* List all agents (admin only)
*/
async function listAgents() {
console.log("\nπ Listing all agents...");
try {
const response = await makeRequest(`${API_BASE_URL}/api/admin/agents`, {
headers: {
Authorization: `Bearer ${ADMIN_TOKEN}`,
},
});
if (response.status === 200) {
console.log("β
Agents retrieved successfully:");
console.log(JSON.stringify(response.data, null, 2));
} else {
console.log(`β Failed to list agents (${response.status}):`);
console.log(JSON.stringify(response.data, null, 2));
}
} catch (error) {
console.error("β Error listing agents:", error.message);
}
}
/**
* Update agent status
*/
async function updateAgentStatus(agentId, status, reason = "") {
console.log(`\nπ Updating agent ${agentId} status to ${status}...`);
try {
const response = await makeRequest(`${API_BASE_URL}/api/admin/status`, {
method: "POST",
headers: {
Authorization: `Bearer ${ADMIN_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
agent_id: agentId,
status: status,
reason: reason,
}),
});
if (response.status === 200) {
console.log("β
Status updated successfully:");
console.log(JSON.stringify(response.data, null, 2));
} else {
console.log(`β Status update failed (${response.status}):`);
console.log(JSON.stringify(response.data, null, 2));
}
} catch (error) {
console.error("β Error updating status:", error.message);
}
}
/**
* Verify a policy decision
*
* Note: Policy verification automatically verifies the passport - no need to call verifyPassport() first
*/
async function verifyPolicy(
packId,
agentId,
policyId,
context,
idempotencyKey = null
) {
console.log(`\nπ‘οΈ Verifying policy: ${packId} for agent: ${agentId}`);
try {
const requestBody = {
context: {
agent_id: agentId,
policy_id: policyId,
context: context,
},
};
if (idempotencyKey) {
requestBody.context.idempotency_key = idempotencyKey;
}
const response = await makeRequest(
`${API_BASE_URL}/api/verify/policy/${packId}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
}
);
if (response.status === 200) {
const decision = response.data.decision || {};
console.log("β
Policy verification successful:");
console.log(` Decision ID: ${decision.decision_id || "N/A"}`);
console.log(` Allowed: ${decision.allow || false}`);
if (decision.reasons) {
console.log(` Reasons:`, JSON.stringify(decision.reasons, null, 2));
}
if (decision.assurance_level) {
console.log(` Assurance Level: ${decision.assurance_level}`);
}
} else {
console.log(`β Policy verification failed (${response.status}):`);
console.log(JSON.stringify(response.data, null, 2));
}
} catch (error) {
console.error("β Error verifying policy:", error.message);
}
}
/**
* Get system metrics
*/
async function getMetrics() {
console.log("\nπ Getting system metrics...");
try {
const response = await makeRequest(`${API_BASE_URL}/api/metrics`, {
headers: {
Authorization: `Bearer ${ADMIN_TOKEN}`,
},
});
if (response.status === 200) {
console.log("β
Metrics retrieved successfully:");
console.log(JSON.stringify(response.data, null, 2));
} else {
console.log(`β Failed to get metrics (${response.status}):`);
console.log(JSON.stringify(response.data, null, 2));
}
} catch (error) {
console.error("β Error getting metrics:", error.message);
}
}
/**
* Handle rate limiting with exponential backoff
*/
async function verifyWithRetry(agentId, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await makeRequest(
`${API_BASE_URL}/api/verify/${agentId}`
);
if (response.status === 200) {
return response.data;
} else if (response.status === 429) {
// Rate limited
const retryAfter = response.data.retryAfter || Math.pow(2, attempt);
console.log(
`β³ Rate limited. Retrying in ${retryAfter} seconds... (attempt ${attempt}/${maxRetries})`
);
if (attempt < maxRetries) {
await new Promise((resolve) =>
setTimeout(resolve, retryAfter * 1000)
);
continue;
}
}
throw new Error(`Request failed with status ${response.status}`);
} catch (error) {
if (attempt === maxRetries) {
throw error;
}
console.log(`β οΈ Attempt ${attempt} failed: ${error.message}`);
}
}
}
/**
* Demonstrate capabilities and limits enforcement
*/
async function demonstrateCapabilitiesAndLimits(agentId) {
console.log(
`\nπ Demonstrating capabilities and limits for agent: ${agentId}`
);
try {
const response = await makeRequest(`${API_BASE_URL}/api/verify/${agentId}`);
if (response.status === 200) {
const passport = response.data;
console.log("β
Passport retrieved successfully");
// Check capabilities
console.log("\nπ Capabilities:");
if (passport.capabilities && passport.capabilities.length > 0) {
passport.capabilities.forEach((cap) => {
console.log(
` - ${cap.id}${
cap.params ? ` (params: ${JSON.stringify(cap.params)})` : ""
}`
);
});
} else {
console.log(" No capabilities defined");
}
// Check limits
console.log("\nβοΈ Limits:");
if (passport.limits) {
Object.entries(passport.limits).forEach(([key, value]) => {
console.log(` - ${key}: ${value}`);
});
} else {
console.log(" No limits defined");
}
// Demonstrate enforcement examples
console.log("\nπ‘οΈ Enforcement Examples:");
// Refund capability check
if (
passport.capabilities?.some(
(cap) => cap.id === "finance.payment.refund"
)
) {
console.log(" β
Agent has refund capability");
// Check refund limits
if (passport.limits?.refund_amount_max_per_tx) {
const refundAmount = 5000; // $50.00 in cents
if (refundAmount <= passport.limits.refund_amount_max_per_tx) {
console.log(
` β
Refund amount $${
refundAmount / 100
} is within per-transaction limit of $${
passport.limits.refund_amount_max_per_tx / 100
}`
);
} else {
console.log(
` β Refund amount $${
refundAmount / 100
} exceeds per-transaction limit of $${
passport.limits.refund_amount_max_per_tx / 100
}`
);
}
}
} else {
console.log(" β Agent does not have refund capability");
}
// Data export capability check
if (passport.capabilities?.some((cap) => cap.id === "data.export")) {
console.log(" β
Agent has data export capability");
// Check export limits
if (passport.limits?.max_export_rows) {
const requestedRows = 5000;
if (requestedRows <= passport.limits.max_export_rows) {
console.log(
` β
Export request for ${requestedRows} rows is within limit of ${passport.limits.max_export_rows}`
);
} else {
console.log(
` β Export request for ${requestedRows} rows exceeds limit of ${passport.limits.max_export_rows}`
);
}
}
// Check PII access
if (passport.limits?.allow_pii !== undefined) {
console.log(
` ${passport.limits.allow_pii ? "β
" : "β"} PII access is ${
passport.limits.allow_pii ? "allowed" : "not allowed"
}`
);
}
} else {
console.log(" β Agent does not have data export capability");
}
// Messaging capability check
if (passport.capabilities?.some((cap) => cap.id === "messaging.send")) {
console.log(" β
Agent has messaging capability");
// Check message rate limits
if (passport.limits?.msgs_per_min) {
console.log(
` β
Message rate limit: ${passport.limits.msgs_per_min} per minute`
);
}
if (passport.limits?.msgs_per_day) {
console.log(
` β
Daily message limit: ${passport.limits.msgs_per_day} per day`
);
}
// Check channel allowlist
const messagingCap = passport.capabilities.find(
(cap) => cap.id === "messaging.send"
);
if (messagingCap?.params?.channels_allowlist) {
console.log(
` β
Allowed channels: ${messagingCap.params.channels_allowlist.join(
", "
)}`
);
}
if (messagingCap?.params?.mention_policy) {
console.log(
` β
Mention policy: ${messagingCap.params.mention_policy}`
);
}
} else {
console.log(" β Agent does not have messaging capability");
}
// Repository PR creation capability check
if (passport.capabilities?.some((cap) => cap.id === "repo.pr.create")) {
console.log(" β
Agent has PR creation capability");
if (passport.limits?.max_prs_per_day) {
console.log(
` β
Daily PR limit: ${passport.limits.max_prs_per_day} per day`
);
}
const prCap = passport.capabilities.find(
(cap) => cap.id === "repo.pr.create"
);
if (prCap?.params?.allowed_repos) {
console.log(
` β
Allowed repositories: ${prCap.params.allowed_repos.join(
", "
)}`
);
}
if (prCap?.params?.allowed_base_branches) {
console.log(
` β
Allowed base branches: ${prCap.params.allowed_base_branches.join(
", "
)}`
);
}
} else {
console.log(" β Agent does not have PR creation capability");
}
// Repository merge capability check
if (passport.capabilities?.some((cap) => cap.id === "repo.merge")) {
console.log(" β
Agent has merge capability");
if (passport.limits?.max_merges_per_day) {
console.log(
` β
Daily merge limit: ${passport.limits.max_merges_per_day} per day`
);
}
if (passport.limits?.max_pr_size_kb) {
console.log(` β
Max PR size: ${passport.limits.max_pr_size_kb} KB`);
}
const mergeCap = passport.capabilities.find(
(cap) => cap.id === "repo.merge"
);
if (mergeCap?.params?.required_reviews) {
console.log(
` β
Required reviews: ${mergeCap.params.required_reviews}`
);
}
if (mergeCap?.params?.required_labels) {
console.log(
` β
Required labels: ${mergeCap.params.required_labels.join(
", "
)}`
);
}
} else {
console.log(" β Agent does not have merge capability");
}
// Assurance level check
if (passport.assurance_level) {
console.log(`\nπ‘οΈ Assurance Level: ${passport.assurance_level}`);
console.log(` Method: ${passport.assurance_method || "N/A"}`);
console.log(` Verified: ${passport.assurance_verified_at || "N/A"}`);
// Example assurance requirements
const requiredLevels = {
refunds: "L2",
payouts: "L3",
admin: "L4KYC",
};
console.log("\nπ Route Access Requirements:");
Object.entries(requiredLevels).forEach(([route, requiredLevel]) => {
const hasAccess = compareAssuranceLevels(
passport.assurance_level,
requiredLevel
);
console.log(
` ${route}: ${
hasAccess ? "β
" : "β"
} (requires ${requiredLevel}, has ${passport.assurance_level})`
);
});
}
// Taxonomy information
if (passport.categories || passport.framework) {
console.log("\nπ·οΈ Taxonomy:");
if (passport.categories && passport.categories.length > 0) {
console.log(` Categories: ${passport.categories.join(", ")}`);
}
if (passport.framework && passport.framework.length > 0) {
console.log(` Frameworks: ${passport.framework.join(", ")}`);
}
}
} else {
console.log(`β Failed to retrieve passport (${response.status}):`);
console.log(JSON.stringify(response.data, null, 2));
}
} catch (error) {
console.error(
"β Error demonstrating capabilities and limits:",
error.message
);
}
}
/**
* Simple assurance level comparison helper
*/
function compareAssuranceLevels(current, required) {
const levels = ["L0", "L1", "L2", "L3", "L4KYC", "L4FIN"];
const currentIndex = levels.indexOf(current);
const requiredIndex = levels.indexOf(required);
return currentIndex >= requiredIndex;
}
// Example usage
async function main() {
console.log("π The Passport for AI Agents - JavaScript Examples\n");
// Verify existing passports
await verifyPassport("ap_a2d10232c6534523812423eec8a1425c");
await verifyPassport("ap_a2d10232c6534523812423eec8a1425c");
// Demonstrate capabilities and limits enforcement
await demonstrateCapabilitiesAndLimits("ap_a2d10232c6534523812423eec8a1425c");
// Create a new passport
const newPassport = {
agent_id: "ap_js_example",
owner: "JavaScript Example",
role: "Tier-1",
permissions: ["read:data", "create:reports"],
limits: {
api_calls_per_hour: 500,
ticket_creation_daily: 25,
},
regions: ["US-CA"],
status: "active",
contact: "example@javascript.com",
version: "1.0.0",
};
await createPassport(newPassport);
// Create a passport with new capabilities
const newCapabilitiesPassport = {
agent_id: "ap_js_new_caps",
owner: "JavaScript New Capabilities Example",
role: "agent",
capabilities: [
{
id: "messaging.send",
params: {
channels_allowlist: ["slack", "discord", "email"],
mention_policy: "limited",
},
},
{
id: "repo.pr.create",
params: {
allowed_repos: ["company/public-repo", "company/docs"],
allowed_base_branches: ["main", "develop"],
path_allowlist: ["src/**", "docs/**"],
max_files_changed: 20,
max_total_added_lines: 500,
},
},
{
id: "repo.merge",
params: {
allowed_repos: ["company/public-repo"],
allowed_base_branches: ["develop"],
required_labels: ["approved", "tested"],
required_reviews: 2,
},
},
],
limits: {
msgs_per_min: 30,
msgs_per_day: 1000,
max_prs_per_day: 10,
max_merges_per_day: 5,
max_pr_size_kb: 512,
},
regions: ["global"],
status: "active",
contact: "newcaps@javascript.com",
version: "1.0.0",
};
await createPassport(newCapabilitiesPassport);
// List all agents
await listAgents();
// Update agent status
await updateAgentStatus("ap_js_example", "suspended", "Testing suspension");
// Get metrics
await getMetrics();
// Example with rate limiting
console.log("\nπ Testing rate limiting with retry...");
try {
const result = await verifyWithRetry("ap_a2d10232c6534523812423eec8a1425c");
console.log("β
Verification with retry successful:", result);
} catch (error) {
console.log("β Verification with retry failed:", error.message);
}
// Policy verification examples
console.log("\n" + "=".repeat(60));
console.log("π‘οΈ Policy Verification Examples");
console.log("=".repeat(60));
console.log("Note: Policy verification automatically verifies the passport");
console.log(" No need to call verifyPassport() first\n");
// Example 1: Refund policy verification
console.log("Example 1: Refund policy verification");
await verifyPolicy(
"finance.payment.refund.v1",
"ap_a2d10232c6534523812423eec8a1425c",
"finance.payment.refund.v1",
{
amount: 5000, // $50.00 in cents
currency: "USD",
customer_id: "cust_123",
reason: "Customer request",
}
);
// Example 2: Data export policy verification
console.log("\nExample 2: Data export policy verification");
await verifyPolicy(
"data.export.create.v1",
"ap_a2d10232c6534523812423eec8a1425c",
"data.export.create.v1",
{
table_name: "users",
row_limit: 1000,
include_pii: false,
}
);
// Example 3: Repository merge policy verification
console.log("\nExample 3: Repository merge policy verification");
await verifyPolicy(
"code.repository.merge.v1",
"ap_a2d10232c6534523812423eec8a1425c",
"code.repository.merge.v1",
{
repo: "company/my-repo",
base_branch: "main",
files_changed: 5,
lines_added: 100,
labels: ["approved", "tested"],
reviews: 2,
}
);
console.log("\n⨠Examples completed!");
}
// Run examples if this file is executed directly
if (require.main === module) {
main().catch(console.error);
}
module.exports = {
verifyPassport,
createPassport,
listAgents,
updateAgentStatus,
getMetrics,
verifyWithRetry,
verifyPolicy,
};