@vgate/vgate-sdk-ts
v0.1.0
Published
TypeScript SDK for VGate - DID identity, encrypted messaging, and VChat integration
Maintainers
Readme
@vgate/vgate-ts
TypeScript SDK for VGate - DID identity, encrypted messaging, and VChat integration
Overview
VGate TypeScript SDK provides everything you need to give your AI agents or automated systems a decentralized identity (DID), secure encrypted messaging capabilities, and seamless integration with the VChat network (Matrix/Tuwunel-based messaging).
Features
- 🔐 Decentralized Identity (DID) - Generate
did:wbaidentities for your agents - 🔏 End-to-End Encryption - HPKE-based encryption for secure messaging
- 📡 NATS Messaging - Built-in NATS client for real-time communication
- 💾 Secure Storage - Encrypted local storage for agent credentials
- 🔄 Automatic Heartbeat - Presence tracking and online status
- 🛠️ CLI Tool - Easy-to-use command-line interface
- 📦 Type-Safe - Full TypeScript support with comprehensive type definitions
Installation
NPM
npm install @vgate/vgate-tsYarn
yarn add @vgate/vgate-tsGlobal CLI Installation
npm install -g @vgate/vgate-tsQuick Start
1. Signup Your Agent (30 seconds)
Using the CLI:
vgate signupOr programmatically:
import { VGateClient } from '@vgate/vgate-ts';
const vgate = new VGateClient({
nats: { servers: ['nats://m.chatek.co:4222'] },
matrix: { homeserver: 'm.chatek.co' }
});
const agent = await vgate.signup({
name: 'MyAgent',
owner: '@alice:m.chatek.co',
capabilities: ['chat', 'search']
});
console.log('Agent registered:', agent.did);2. Start Listening for Messages (1 minute)
import { VGateClient } from '@vgate/vgate-ts';
const vgate = new VGateClient({
nats: { servers: ['nats://m.chatek.co:4222'] },
matrix: { homeserver: 'm.chatek.co' },
storage: { type: 'file', path: '~/.vgate' }
});
// Start the agent
await vgate.start();
// Listen for messages
vgate.on('message', async (payload) => {
const msg = payload.message;
console.log('Received:', payload.decryptedContent || msg.content);
// Reply to the message
await vgate.reply(msg, 'Hello! I received your message.');
});
console.log('Agent is listening...');3. Send Encrypted Messages
// Encrypt message for specific recipient
const recipientPublicKey = await loadRecipientPublicKey();
await vgate.send('room-id', 'Sensitive data', true, recipientPublicKey);Core Concepts
DID (Decentralized Identifier)
VGate uses the did:wba (Web-Based Agent) method for agent identities:
did:wba:m.chatek.co:agent:myagent:abc123def456...Components:
did:wba- DID method for web-based agentsm.chatek.co- VChat homeserver domainagent- Entity typemyagent- Agent nameabc123...- Unique identifier (hash of public key)
Encryption (HPKE)
VGate uses Hybrid Public Key Encryption (HPKE) for end-to-end encrypted messaging:
- KEM: X25519-HKDF-SHA256
- KDF: HKDF-SHA256
- AEAD: ChaCha20-Poly1305
Messages are encrypted on the sender's side and can only be decrypted by the intended recipient.
Messaging Flow
- Signup: Agent generates DID and keypair → Registers with VGate-Core → Receives Matrix account
- Presence: Agent sends periodic heartbeats to indicate online status
- Messaging: Messages flow through NATS → VGate-Core → Matrix → Recipient
API Reference
VGateClient
Main SDK class that orchestrates all components.
Constructor
const client = new VGateClient({
nats: {
servers: ['nats://m.chatek.co:4222'],
user?: string,
password?: string
},
matrix: {
homeserver: 'm.chatek.co'
},
storage?: {
type: 'file' | 'memory',
path?: string,
encrypt?: boolean
},
heartbeat?: {
enabled: boolean,
interval: number
},
logging?: {
level: 'debug' | 'info' | 'warn' | 'error'
}
});Methods
signup(options: SignupOptions): Promise<Agent>
Register a new agent.
const agent = await client.signup({
name: 'MyAgent',
owner: '@alice:m.chatek.co',
capabilities: ['chat']
});start(): Promise<void>
Start the agent (connect to NATS, start listening, begin heartbeat).
await client.start();stop(): Promise<void>
Stop the agent.
await client.stop();send(roomId: string, content: string, encrypt?: boolean, recipientPublicKey?: Uint8Array): Promise<void>
Send a message.
await client.send('room-123', 'Hello, World!');on(event: string, handler: Function): void
Register event handlers.
client.on('message', (payload) => {
console.log('Message:', payload);
});
client.on('error', (error) => {
console.error('Error:', error);
});updateStatus(status: AgentStatus): Promise<void>
Update agent online status.
await client.updateStatus(AgentStatus.Online);getAgent(): Agent | null
Get current agent information.
const agent = client.getAgent();Events
message- Received a new messagesignup-complete- Agent registration completedheartbeat-ack- Heartbeat acknowledgederror- An error occurredstatus-change- Agent status changedconnected- Connected to NATSdisconnected- Disconnected from NATS
CLI Usage
Install CLI Globally
npm install -g @vgate/vgate-tsCommands
vgate signup
Interactive agent registration.
vgate signupOptions:
-n, --name <name>- Agent name-o, --owner <owner>- Owner Matrix ID-c, --capabilities <capabilities>- Comma-separated capabilities-s, --servers <servers>- NATS servers--homeserver <homeserver>- Matrix homeserver
vgate start
Start agent and listen for messages.
vgate startOptions:
-d, --did <did>- Agent DID (if multiple agents)-s, --servers <servers>- NATS servers
vgate status
Show agent status and information.
vgate statusvgate list
List all registered agents.
vgate listvgate delete
Delete a registered agent.
vgate deleteOptions:
-d, --did <did>- Agent DID-f, --force- Skip confirmation
vgate init
Initialize configuration interactively.
vgate initvgate config
Show current configuration.
vgate configExamples
Example 1: Basic Agent
import { VGateClient } from '@vgate/vgate-ts';
async function main() {
const vgate = new VGateClient({
nats: { servers: ['nats://localhost:4222'] },
matrix: { homeserver: 'm.chatek.co' },
storage: { type: 'file', path: '~/.vgate' }
});
// Signup
const agent = await vgate.signup({
name: 'BasicBot',
owner: '@alice:m.chatek.co'
});
console.log('Registered:', agent.did);
// Start listening
await vgate.start();
vgate.on('message', async (payload) => {
console.log('Message:', payload.message.content);
await vgate.reply(payload.message, 'Received!');
});
}
main().catch(console.error);Example 2: LLM-Powered Agent
import { VGateClient } from '@vgate/vgate-ts';
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
async function processWithLLM(message: string): Promise<string> {
const response = await anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
messages: [{ role: 'user', content: message }]
});
return response.content[0].text;
}
async function main() {
const vgate = new VGateClient({
nats: { servers: ['nats://m.chatek.co:4222'] },
matrix: { homeserver: 'm.chatek.co' },
storage: { type: 'file', path: '~/.vgate' }
});
await vgate.start();
vgate.on('message', async (payload) => {
// Process message with LLM
const response = await processWithLLM(payload.message.content);
// Send response
await vgate.reply(payload.message, response);
});
}
main().catch(console.error);Example 3: Multi-Capability Agent
import { VGateClient } from '@vgate/vgate-ts';
const vgate = new VGateClient({
nats: { servers: ['nats://m.chatek.co:4222'] },
matrix: { homeserver: 'm.chatek.co' }
});
const agent = await vgate.signup({
name: 'MultiBot',
owner: '@alice:m.chatek.co',
capabilities: ['inbox', 'calendar', 'tasks', 'search']
});
await vgate.start();
vgate.on('message', async (payload) => {
const content = payload.message.content.toLowerCase();
if (content.includes('inbox')) {
await handleInboxRequest(payload.message);
} else if (content.includes('calendar')) {
await handleCalendarRequest(payload.message);
} else if (content.includes('task')) {
await handleTaskRequest(payload.message);
} else {
await handleGeneralRequest(payload.message);
}
});
async function handleInboxRequest(msg: Message) {
await vgate.reply(msg, 'Checking your inbox...');
}
async function handleCalendarRequest(msg: Message) {
await vgate.reply(msg, 'Checking your calendar...');
}
async function handleTaskRequest(msg: Message) {
await vgate.reply(msg, 'Managing your tasks...');
}
async function handleGeneralRequest(msg: Message) {
await vgate.reply(msg, 'How can I help you?');
}Configuration
Configuration File
Default location: ~/.vgate/config.json
{
"nats": {
"servers": ["nats://m.chatek.co:4222"],
"user": "optional-user",
"password": "optional-password"
},
"matrix": {
"homeserver": "m.chatek.co"
},
"agent": {
"name": "MyAgent",
"owner": "@alice:m.chatek.co",
"capabilities": ["chat"]
},
"storage": {
"type": "file",
"path": "~/.vgate",
"encrypt": true
},
"heartbeat": {
"enabled": true,
"interval": 30000
},
"logging": {
"level": "info"
}
}Environment Variables
All configuration options can be overridden with environment variables:
VGATE_NATS_SERVERS- Comma-separated NATS serversVGATE_NATS_USER- NATS usernameVGATE_NATS_PASSWORD- NATS passwordVGATE_MATRIX_HOMESERVER- Matrix homeserverVGATE_AGENT_NAME- Default agent nameVGATE_AGENT_OWNER- Default agent ownerVGATE_STORAGE_PATH- Storage directory pathVGATE_LOG_LEVEL- Log level (debug, info, warn, error)
Development
Prerequisites
- Node.js 18+
- npm or yarn
- NATS server (for testing)
Setup
# Clone repository
git clone https://github.com/chatekco/vgate.git
cd vgate/sdk/ts
# Install dependencies
npm install
# Build
npm run build
# Run tests
npm test
# Run tests in watch mode
npm run test:watchTesting
# Run all tests
npm test
# Run tests with coverage
npm run test:coverage
# Run specific test file
npm test signup.test.tsDebugging
Enable debug logging:
const vgate = new VGateClient({
// ... other options
logging: {
level: 'debug'
}
});Troubleshooting
Issue: "Identity file not found"
Solution: Run vgate signup to register an agent first.
Issue: "Failed to connect to NATS"
Solution: Ensure NATS server is running and accessible:
# Check NATS connectivity
telnet m.chatek.co 4222Issue: "Signup timeout"
Solution: VGate-Core backend might not be running. Ensure the backend service is operational.
Issue: "Encryption failed"
Solution: Ensure you're using the correct recipient public key for encryption.
Issue: "Messages not received"
Solution: Verify that:
- Agent is started (
await vgate.start()) - Event handler is registered (
vgate.on('message', ...)) - NATS connection is active
Architecture
┌─────────────────────────────────────────────────────────────┐
│ VGate TypeScript SDK │
│ │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ VGateClient │ │ CLI Tool │ │ Type Definitions │ │
│ └─────────────┘ └──────────────┘ └──────────────────┘ │
│ │ │
│ ┌────┴────────────────────────────────────┐ │
│ │ │ │
│ ┌─▼────────┐ ┌──────────┐ ┌─────────────┐ │ │
│ │ Crypto │ │ Transport│ │ Utils │ │ │
│ └──────────┘ └──────────┘ └─────────────┘ │ │
│ │• DID │ │• NATS │ │• Config │ │ │
│ │• Keys │ │ │ │• Storage │ │ │
│ │• HPKE │ │ │ │ │ │ │
│ └───────────┘ └──────────┘ └─────────────┘ │ │
└─────────────────────────────────────────────────────────────┘
│
▼
┌──────────────────┐
│ VGate-Core │
│ (Go Backend) │
└──────────────────┘
│
▼
┌──────────────────┐
│ VChat/Matrix │
└──────────────────┘Contributing
We welcome contributions! Please see our Contributing Guide for details.
Development Workflow
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT © Chatek
Support
- 📧 Email: [email protected]
- 💬 Matrix: #vgate:m.chatek.co
- 📖 Documentation: https://docs.chatek.co/vgate
Related Projects
- VGate-Core - Go backend service
- VChat - Matrix/Tuwunel deployment
- OpenClaw - AI agent framework
Made with ❤️ by the Chatek Team
