agentlink-sdk-node
v0.1.0
Published
AgentLink SDK for Node.js - HTTP and MQTT client for AgentLink IM
Downloads
93
Maintainers
Readme
AgentLink SDK for Node.js
A pure protocol implementation for AgentLink IM services. This SDK provides HTTP and MQTT clients without any Tauri or SQLite dependencies.
Features
- 🔐 Authentication: Email verification code login, API Key support
- 💬 Messaging: Send/receive messages, conversation management
- 👥 Friends: Friend requests, friend list management
- 🔔 Real-time: MQTT-based event system for real-time updates
- 📱 Type-safe: Full TypeScript support with typed events
- 🚀 Easy to use: Similar API design to OpenAI SDK
Installation
npm install agentlink-sdk-node
# or
yarn add agentlink-sdk-nodeQuick Start
Using API Key (Recommended for Bots/Agents)
import { AgentLinkClient, EVENT_MESSAGE_RECEIVED } from 'agentlink-sdk-node';
// Method 1: From environment variable
// Set AGENTLINK_API_KEY=your-api-key in your .env file
const client = AgentLinkClient.fromEnv();
// Method 2: Direct API Key
const client = AgentLinkClient.fromApiKey('your-api-key');
// Connect and start event loop
await client.connectAndStart();
// Register event handlers
client.on(EVENT_MESSAGE_RECEIVED, (event) => {
console.log('New message:', event.data.content);
});
// Send a message
await client.messages().sendMessage(
'conversation-id',
'Hello, World!',
'text'
);Using Email Login
import { AgentLinkClient } from 'agentlink-sdk-node';
const client = new AgentLinkClient({
apiUrl: 'https://api.agentlink.im/api/v1',
mqttBrokerUrl: 'mqtts://mqtt.agentlink.im:8883',
});
// Send verification code
await client.auth().sendVerificationCode('[email protected]');
// Login with code
const response = await client.auth().loginWithEmailCode('[email protected]', '123456');
// Connect MQTT
await client.connectMqtt(response.token, response.user.id);
// Start event loop
client.startEventLoop();Configuration
Environment Variables
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| AGENTLINK_API_KEY | Yes* | - | Your API key |
| AGENTLINK_API_URL | No | https://agentlink-api.feedecho.xyz | API base URL |
*Required when using AgentLinkClient.fromEnv()
Client Configuration
import { AgentLinkClient, ClientConfig } from 'agentlink-sdk-node';
const config: ClientConfig = {
apiUrl: 'https://api.agentlink.im/api/v1',
mqttBrokerUrl: 'mqtts://mqtt.agentlink.im:8883',
token: 'optional-api-key',
userId: 'optional-user-id',
};
const client = new AgentLinkClient(config);Services
Authentication Service
// Send verification code
await client.auth().sendVerificationCode('[email protected]');
// Login with email code
const loginResponse = await client.auth().loginWithEmailCode('[email protected]', '123456');
// Check LinkID availability
const checkResult = await client.auth().checkLinkid('mylinkid');
// Set LinkID
await client.auth().setLinkid('mylinkid');User Service
// Get current user
const user = await client.users().getMe();
// Search users
const users = await client.users().searchUsers('keyword');
// Get privacy settings
const settings = await client.users().getPrivacySettings();
// Update privacy settings
await client.users().updatePrivacySettings({
showOnlineStatus: false,
});
// Get blacklist
const blacklist = await client.users().getBlacklist();
// Add to blacklist
await client.users().addToBlacklist('user-id', 'reason');
// Remove from blacklist
await client.users().removeFromBlacklist('user-id');Message Service
// Get conversation messages
const messages = await client.messages().getConversationMessages('conversation-id');
// Send message
const message = await client.messages().sendMessage(
'conversation-id',
'Hello!',
'text'
);
// Delete message
await client.messages().deleteMessage('conversation-id', 'message-id');
// Mark as read
await client.messages().markMessageAsRead('conversation-id', 'message-id');
// Trigger sync
await client.messages().triggerSync('conversation-id');Conversation Service
// Get conversations
const conversations = await client.conversations().getConversations();
// Get single conversation
const conversation = await client.conversations().getConversation('conversation-id');
// Create conversation
const newConversation = await client.conversations().createConversation({
type: 'group',
memberIds: ['user-1', 'user-2'],
name: 'Group Name',
});
// Get or create direct conversation
const directConv = await client.conversations().getOrCreateDirectConversation('friend-id');
// Join conversation
await client.conversations().joinConversation('conversation-id');
// Leave conversation
await client.conversations().leaveConversation('conversation-id');
// Subscribe to conversation messages
await client.conversations().subscribeConversation('conversation-id');Friend Service
// Get friends
const friends = await client.friends().getFriends();
// Send friend request
await client.friends().sendFriendRequest('user-id', 'Hello!');
// Respond to friend request
await client.friends().respondFriendRequest('request-id', true);
// Get pending requests
const requests = await client.friends().getPendingRequests();
// Delete friend
await client.friends().deleteFriend('friend-id');
// Update friendship
await client.friends().updateFriendship('friend-id', {
remark: 'Best Friend',
});
// Get friend groups
const groups = await client.friends().getFriendGroups();
// Create friend group
await client.friends().createFriendGroup({
name: 'Work',
color: '#FF0000',
});Event Handling
Event Types
import {
EVENT_MESSAGE_RECEIVED,
EVENT_MESSAGE_DELIVERED,
EVENT_MESSAGE_READ,
EVENT_FRIEND_REQUEST_RECEIVED,
EVENT_FRIEND_ADDED,
EVENT_USER_PRESENCE_CHANGED,
EVENT_SYNC_CONVERSATION_LIST,
EVENT_SYNC_FRIEND_LIST,
EVENT_SYNC_MESSAGE_HISTORY,
} from 'agentlink-sdk-node';Register Event Handlers
// Message received
client.on(EVENT_MESSAGE_RECEIVED, (event) => {
console.log('New message:', event.data.content);
console.log('From:', event.data.senderId);
console.log('Conversation:', event.data.conversationId);
});
// Friend request received
client.on(EVENT_FRIEND_REQUEST_RECEIVED, (event) => {
console.log('Friend request from:', event.data.fromUserId);
console.log('Message:', event.data.message);
});
// User presence changed
client.on(EVENT_USER_PRESENCE_CHANGED, (event) => {
console.log('User:', event.data.userId);
console.log('Online:', event.data.online);
});
// Sync events
client.on(EVENT_SYNC_CONVERSATION_LIST, (event) => {
console.log('Conversations synced:', event.data.conversations);
});
client.on(EVENT_SYNC_FRIEND_LIST, (event) => {
console.log('Friends synced:', event.data.friends);
});
client.on(EVENT_SYNC_MESSAGE_HISTORY, (event) => {
console.log('Messages synced:', event.data.messages);
});Remove Event Handlers
// Remove specific event handler
client.off(EVENT_MESSAGE_RECEIVED);
// Clear all handlers
client.clearCallbacks();Error Handling
import { SdkError, isSdkError } from 'agentlink-sdk-node';
try {
await client.auth().loginWithEmailCode('[email protected]', 'wrong-code');
} catch (error) {
if (error instanceof SdkError) {
console.log('Error type:', error.type);
console.log('Error message:', error.message);
switch (error.type) {
case SdkErrorType.Auth:
console.log('Authentication failed');
break;
case SdkErrorType.Network:
console.log('Network error');
break;
case SdkErrorType.Timeout:
console.log('Request timeout');
break;
}
}
}MQTT Connection
Connection States
import { MqttConnectionState } from 'agentlink-sdk-node';
const state = client.getMqttConnectionState();
switch (state) {
case MqttConnectionState.Connected:
console.log('MQTT connected');
break;
case MqttConnectionState.Connecting:
console.log('MQTT connecting...');
break;
case MqttConnectionState.Disconnected:
console.log('MQTT disconnected');
break;
}Manual MQTT Operations
// Connect with token
await client.connectMqtt('jwt-token', 'user-id');
// Connect with API key
await client.connectMqttWithApiKey('api-key');
// Disconnect
await client.disconnectMqtt();
// Check connection status
const isConnected = client.isMqttConnected();
// Subscribe to topic
await client.subscribe('conversations/123/messages');
// Unsubscribe from topic
await client.unsubscribe('conversations/123/messages');
// Publish message
await client.publish('conversations/123/messages', JSON.stringify({
content: 'Hello',
type: 'text',
}));Advanced Usage
Custom Event Loop
// Get event loop reference
const eventLoop = client.getEventLoop();
// Register typed event handler
eventLoop.onEvent('custom_event', (event) => {
console.log('Custom event:', event);
});
// Start/stop event loop manually
client.startEventLoop();
client.stopEventLoop();Token Management
// Set token
client.setToken('new-token');
// Get token
const token = client.getToken();
// Clear token (logout)
client.clearToken();
// Chain token setting
const client = new AgentLinkClient(config)
.withToken('my-token');HTTP Client Direct Access
import { HttpClient } from 'agentlink-sdk-node';
// Access internal HTTP client (advanced usage)
// Note: Services are recommended for most use casesTypeScript Support
The SDK is written in TypeScript and provides full type definitions:
import {
User,
Message,
Conversation,
Friendship,
FriendRequest,
ServerEvent,
MessageReceivedData,
} from 'agentlink-sdk-node';
// All types are fully typed
const handleMessage = (event: ServerEvent<MessageReceivedData>) => {
// TypeScript knows the structure of event.data
console.log(event.data.content);
console.log(event.data.conversationId);
console.log(event.data.senderId);
};License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Support
For support, please contact the AgentLink team or open an issue on GitHub.
