atp-sdk
Version:
Official TypeScript SDK for Agent Trust Protocol™ - Build secure, verifiable, and trustworthy applications with decentralized identity, verifiable credentials, and robust access control
261 lines • 8.85 kB
JavaScript
/**
* Simplified Agent API for ATP™
*
* Provides a 3-line quick start experience for developers
* while maintaining full quantum-safe security features.
*/
import { ATPClient } from './client/atp.js';
import { CryptoUtils } from './utils/crypto.js';
export class Agent {
constructor(name, options) {
this.did = null;
this.privateKey = null;
this.initialized = false;
this.name = name;
// Default to local services (overridable via options or env). Audit defaults to 3006 to match mocks.
const baseUrl = options?.serverUrl || process.env.ATP_SERVER_URL || 'http://localhost';
const identityUrl = process.env.ATP_IDENTITY_URL || `${baseUrl}:3001`;
const credentialsUrl = process.env.ATP_CREDENTIALS_URL || `${baseUrl}:3002`;
const permissionsUrl = process.env.ATP_PERMISSIONS_URL || `${baseUrl}:3003`;
const auditUrl = process.env.ATP_AUDIT_URL || `${baseUrl}:3006`;
const gatewayUrl = process.env.ATP_GATEWAY_URL || `${baseUrl}:3000`;
const config = {
baseUrl,
services: {
identity: identityUrl,
credentials: credentialsUrl,
permissions: permissionsUrl,
audit: auditUrl,
gateway: gatewayUrl,
}
};
this.client = new ATPClient(config);
if (options?.did && options?.privateKey) {
this.did = options.did;
this.privateKey = options.privateKey;
}
}
/**
* Create a new agent with quantum-safe identity
*
* @example
* ```typescript
* const agent = await Agent.create('MyBot');
* ```
*/
static async create(name, options) {
const agent = new Agent(name, options);
await agent.initialize();
return agent;
}
async initialize() {
if (this.initialized)
return;
try {
// If no DID provided, create a new quantum-safe identity
if (!this.did || !this.privateKey) {
// Generate Ed25519 keypair (will be hybrid with Dilithium soon)
const keyPair = await CryptoUtils.generateKeyPair();
const identity = await this.client.identity.registerDID({
publicKey: keyPair.publicKey,
metadata: { name: this.name }
});
if (identity.data) {
this.did = identity.data.did;
this.privateKey = keyPair.privateKey;
}
else {
throw new Error('Failed to register DID');
}
}
// Set up authentication
this.client.setAuthentication({
did: this.did,
privateKey: this.privateKey
});
this.initialized = true;
}
catch (error) {
throw new Error(`Failed to initialize agent: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Send a secure message to another agent
*
* @example
* ```typescript
* await agent.send(otherAgentDid, 'Hello, quantum world!');
* ```
*/
async send(recipientDid, message) {
if (!this.initialized) {
throw new Error('Agent not initialized');
}
// In the future, this will use the gateway's WebSocket connection
// For now, it's a placeholder that demonstrates the API
const payload = typeof message === 'string' ? { text: message } : message;
// This would normally send through the gateway
await this.client.audit.logEvent({
source: 'agent-sdk',
action: 'message.sent',
resource: recipientDid,
actor: this.did,
details: {
from: this.did,
to: recipientDid,
timestamp: new Date().toISOString(),
// Message would be encrypted in production
preview: JSON.stringify(payload).substring(0, 50) + '...'
}
});
}
/**
* Get the trust score for another agent
*
* @example
* ```typescript
* const trustScore = await agent.getTrustScore(otherAgentDid);
* console.log(`Trust level: ${trustScore}`);
* ```
*/
async getTrustScore(agentDid) {
if (!this.initialized) {
throw new Error('Agent not initialized');
}
try {
// Check if we have any interaction history
const events = await this.client.audit.queryEvents({
actor: this.did,
resource: agentDid,
limit: 10
});
// Simple trust scoring based on interaction count
// In production, this would use advanced ML models
const interactionCount = events.data?.events?.length || 0;
if (interactionCount === 0)
return 0; // UNKNOWN
if (interactionCount < 5)
return 0.25; // BASIC
if (interactionCount < 20)
return 0.5; // VERIFIED
if (interactionCount < 50)
return 0.75; // TRUSTED
return 1.0; // PRIVILEGED
}
catch {
// Default to unknown trust level if query fails
return 0;
}
}
/**
* Grant a capability to another agent
*
* @example
* ```typescript
* await agent.grantCapability(otherAgentDid, 'read:data');
* ```
*/
async grantCapability(agentDid, capability) {
if (!this.initialized) {
throw new Error('Agent not initialized');
}
await this.client.permissions.grantPermission({
subject: agentDid,
resource: `${this.did}:*`,
action: capability,
conditions: {},
expiresAt: new Date(Date.now() + 86400000).toISOString() // 24 hours
});
}
/**
* Issue a verifiable credential to another agent
*
* @example
* ```typescript
* await agent.issueCredential(otherAgentDid, 'verified-partner', { level: 'gold' });
* ```
*/
async issueCredential(subjectDid, credentialType, claims) {
if (!this.initialized) {
throw new Error('Agent not initialized');
}
const credential = await this.client.credentials.issueCredential({
subjectDID: subjectDid,
credentialType: credentialType,
claims,
expirationDate: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString() // 1 year
});
return credential.data?.id || 'credential-id';
}
/**
* Get the agent's DID (Decentralized Identifier)
*/
getDID() {
if (!this.did) {
throw new Error('Agent not initialized');
}
return this.did;
}
/**
* Get the agent's name
*/
getName() {
return this.name;
}
/**
* Check if the agent is initialized
*/
isInitialized() {
return this.initialized;
}
/**
* Subscribe to events (coming soon)
*
* @example
* ```typescript
* agent.on('message', (msg) => console.log('Received:', msg));
* ```
*/
on(event, _handler) {
// This will be implemented when WebSocket gateway is integrated
console.warn(`Event subscription not yet implemented. Event: ${event}`);
}
/**
* Establish trust with another agent
*
* @example
* ```typescript
* const trust = await agent.establishTrust(otherAgentDid);
* if (trust.established) {
* console.log('Trust established!');
* }
* ```
*/
async establishTrust(agentDid, minTrustLevel = 0.5) {
if (!this.initialized) {
throw new Error('Agent not initialized');
}
const currentTrust = await this.getTrustScore(agentDid);
if (currentTrust >= minTrustLevel) {
return { established: true, level: currentTrust };
}
// In production, this would initiate a trust establishment protocol
// For now, we'll just log the attempt
await this.client.audit.logEvent({
source: 'agent-sdk',
action: 'trust.establish.attempted',
resource: agentDid,
actor: this.did,
details: {
from: this.did,
to: agentDid,
currentLevel: currentTrust,
requiredLevel: minTrustLevel
}
});
return { established: false, level: currentTrust };
}
}
// Re-export the Agent class as default for cleaner imports
export default Agent;
//# sourceMappingURL=simple-agent.js.map