robokit402
v1.1.0
Published
Decentralized P2P Mesh Network library for robot task execution and payments
Maintainers
Readme
RoboKit402
RoboKit402 is a critical network layer and transaction protocol designed to facilitate trustless, delegated task execution among specialized robots operating on a local network. It enables a decentralized service market where robots can advertise capabilities, request services, and engage in guaranteed machine-to-machine payment using Solana (x402).
Features
- Decentralized Identity: UUID-based persistent identity for robots.
- Service Discovery: Interfaces for DHT-based capability discovery and IP resolution.
- Task Execution: Standardized HTTP protocol for task submission, polling, and status updates.
- Payment Integration: Built-in support for Solana x402 payments, handling 402 Payment Required responses and retries.
- Real-Time Logging (v1.1.0): WebSocket-based streaming of task execution logs from Worker to Delegator.
- Group Coordination (v1.1.0): Multi-robot coordination primitives for synchronized task execution.
- TypeScript Support: Fully typed for better developer experience.
Installation
npm install robokit402What's New in v1.1.0
Real-Time Logging 📝
Workers can now stream real-time, structured logs to Delegators during task execution via WebSocket connections:
- Continuous Feedback: Workers send diagnostic, status, and event logs in real-time
- Flexible Format: JSON logs with required
levelfield and custom additional fields - Immediate Alerting: Critical issues are pushed instantly without polling delays
- Decentralized Auditing: All logs are recorded for Proof-of-Delivery validation
Group Coordination 🤝
Coordinate multiple robots for synchronized task execution:
- Rendezvous Pattern: Wait for all workers to signal readiness before starting
- Atomic Commands: Broadcast START, PAUSE, RESUME, STOP commands to worker groups
- Emergency Stop: Instantly halt all workers in a group for safety
- Barrier Synchronization: Coordinate workers at specific checkpoints
Usage
Worker (Provider) - Basic HTTP Mode
import { HttpServer, IdentityManager, TaskManager, InMemoryDiscovery } from 'robokit402';
const identity = new IdentityManager('./.robokit/worker');
const discovery = new InMemoryDiscovery();
const taskManager = new TaskManager();
const server = new HttpServer(3000, identity, taskManager);
server.start();
// Advertise capabilities
discovery.advertise({
name: 'compute-hash',
tags: ['compute', 'hash'],
description: 'Computes SHA256 hash',
price: 1000,
estimatedTime: 1000
});Worker with Real-Time Logging (v1.1.0)
import { HttpServer, IdentityManager, TaskManager } from 'robokit402';
const identity = new IdentityManager('./.robokit/worker');
const taskManager = new TaskManager();
// Register handler with logging support
taskManager.registerHandler('process-data', async (params, logFn) => {
if (logFn) {
logFn({ level: 'INFO', message: 'Starting data processing' });
logFn({ level: 'DEBUG', message: `Processing ${params.count} items` });
}
// Do work...
if (logFn) {
logFn({ level: 'INFO', message: 'Processing complete', itemsProcessed: params.count });
}
return { status: 'success' };
});
// Enable WebSocket logging by providing Delegator's WebSocket URL
const server = new HttpServer(
3000,
identity,
taskManager,
'ws://delegator-host:8080' // Delegator WebSocket URL
);
server.start();Delegator (Client) - Basic HTTP Mode
import { HttpClient, SolanaPayment } from 'robokit402';
import { Connection, Keypair } from '@solana/web3.js';
const client = new HttpClient();
const connection = new Connection('https://api.devnet.solana.com', 'confirmed');
const payer = Keypair.fromSecretKey(...); // Load your wallet
const payment = new SolanaPayment({ connection, payer });
const taskData = {
description: 'Compute hash',
subtasks: []
};
// Post task with payment handling
await client.postTask('http://localhost:3000/task', taskData, async () => {
return await payment.createPaymentTransaction('RECIPIENT_ADDRESS', 1000);
});Delegator with Real-Time Logging (v1.1.0)
import { HttpClient, WebSocketServer } from 'robokit402';
// Start WebSocket server to receive logs
const wsServer = new WebSocketServer(8080);
wsServer.start();
// Listen for real-time logs
wsServer.onTaskLog('*', (taskId, log) => {
console.log(`[${log.level}] ${log.message}`);
});
// Send task (Worker will connect via WebSocket)
const client = new HttpClient();
const response = await client.postTask('http://worker:3000/task', taskData, paymentHandler);Group Coordination (v1.1.0)
import { WebSocketServer, GroupTaskManager, HttpClient } from 'robokit402';
const wsServer = new WebSocketServer(8080);
wsServer.start();
const groupManager = new GroupTaskManager(wsServer);
// Send tasks to multiple workers
const taskIds = [];
for (const workerUrl of workerUrls) {
const response = await client.postTask(workerUrl, taskData, paymentHandler);
taskIds.push(response.taskId);
}
// Create group task with rendezvous coordination
const groupTask = groupManager.createGroupTask(
'Coordinated Area Scan',
taskIds,
'RENDEZVOUS'
);
// Wait for all workers to signal readiness
const ready = await groupManager.waitForRendezvous(groupTask.id);
if (ready) {
// Broadcast START command to all workers simultaneously
groupManager.broadcastStart(groupTask.id);
}Examples
Check the examples/ directory for complete demonstrations:
- simple-interaction.ts: Basic HTTP-based task execution (v1.0.0)
- realtime-logging.ts: Real-time WebSocket log streaming (v1.1.0)
- group-coordination.ts: Multi-robot rendezvous coordination (v1.1.0)
To run the examples:
Build the project:
npm run buildRun an example:
npm run example # Basic HTTP mode npm run example:logging # Real-time logging demo npm run example:group # Group coordination demo
API Reference (v1.1.0)
LogMessage Interface
interface LogMessage {
level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'CRITICAL';
message: string;
timestamp?: string;
[key: string]: any; // Custom fields
}GroupCommand Interface
interface GroupCommand {
type: 'START' | 'PAUSE' | 'RESUME' | 'STOP' | 'E_STOP' | 'CUSTOM';
payload?: any;
timestamp: string;
}WebSocketServer
onTaskLog(taskId: string, callback: (taskId, log) => void): Listen for logssendCommand(taskId: string, command: GroupCommand): Send command to workerbroadcastCommand(taskIds: string[], command: GroupCommand): Broadcast to multiple workers
GroupTaskManager
createGroupTask(description, workerTaskIds, mode): Create coordinated group taskwaitForRendezvous(groupTaskId, timeout?): Wait for all workers to be readybroadcastStart(groupTaskId): Start all workers simultaneouslyemergencyStop(groupTaskId, reason?): Emergency stop all workers
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT License - see the LICENSE file for details.
