rentabots-sdk 1.4.1 → 1.5.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -1,140 +1,130 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * RENTABOTS CLI (v1.4.1)
5
- * The official production runtime for RentaBots Agents.
6
- *
7
- * Features:
8
- * - OpenClaw Intelligence Bridge
9
- * - specialized Swarm (Builder + QA)
10
- * - Collaborative Swarm (Outsourcing)
4
+ * šŸ¦€ RENTABOTS MASTER CONTROLLER (v1.5.6)
5
+ * The all-in-one CLI for managing autonomous agents.
11
6
  */
12
7
 
13
- const { Agent } = require('./dist/index');
14
- const { fork, exec } = require('child_process');
8
+ const { execSync, spawn } = require('child_process');
15
9
  const path = require('path');
16
10
  const fs = require('fs');
17
11
 
18
- // Parse Args
19
12
  const args = process.argv.slice(2);
20
- const keyArgIndex = args.findIndex(a => a === '--key' || a === '-k' || a === '-key');
21
- const API_KEY = (keyArgIndex !== -1 && args[keyArgIndex + 1]) ? args[keyArgIndex + 1] : process.env.RENTABOTS_API_KEY;
22
-
23
- if (!API_KEY) {
24
- console.error("āŒ Error: API Key required.");
25
- console.log("Usage:");
26
- console.log(" npx rentabots start --key YOUR_API_KEY");
27
- console.log(" OR set environment variable: export RENTABOTS_API_KEY=YOUR_API_KEY");
28
- process.exit(1);
13
+ const command = args[0];
14
+
15
+ // Helper: Run shell command and stream output
16
+ function run(cmd, desc) {
17
+ console.log(`\nšŸš€ ${desc}...`);
18
+ try {
19
+ execSync(cmd, { stdio: 'inherit' });
20
+ } catch (e) {
21
+ console.error(`āŒ Error during: ${desc}`);
22
+ process.exit(1);
23
+ }
29
24
  }
30
25
 
31
- // Ensure local workspace exists
32
- const WORKSPACE_DIR = path.join(process.cwd(), 'workspace');
33
- if (!fs.existsSync(WORKSPACE_DIR)) fs.mkdirSync(WORKSPACE_DIR);
26
+ async function handleDeploy() {
27
+ const keyArgIndex = args.findIndex(a => a === '--key' || a === '-k' || a === '-key');
28
+ const API_KEY = (keyArgIndex !== -1 && args[keyArgIndex + 1]) ? args[keyArgIndex + 1] : process.env.RENTABOTS_API_KEY;
34
29
 
35
- console.log("šŸš€ Initializing RentaBots Advanced Runtime...");
30
+ if (!API_KEY) {
31
+ console.error("āŒ Error: API Key required for one-line deployment.");
32
+ console.log("Usage: rentabots deploy --key YOUR_API_KEY");
33
+ process.exit(1);
34
+ }
36
35
 
37
- // --- INTELLIGENCE BRIDGE ---
38
- async function checkForOpenClaw() {
39
- return new Promise((resolve) => {
40
- exec('openclaw --version', (err) => resolve(!err));
41
- });
42
- }
36
+ const projectDir = 'my-rentabot-agent';
37
+
38
+ // 1. Create project if missing
39
+ if (!fs.existsSync(projectDir)) {
40
+ console.log(`\nšŸ“‚ Project folder '${projectDir}' not found. Initializing...`);
41
+ // We call the internal init logic here without interaction
42
+ fs.mkdirSync(projectDir);
43
+ process.chdir(projectDir);
44
+
45
+ // Generate necessary files (Minimal v1.5.0 templates)
46
+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
47
+ const ver = pkg.version;
48
+
49
+ fs.writeFileSync('.env', `RENTABOTS_API_KEY=${API_KEY}\nRENTABOTS_API_URL=https://rentabots.com/api\n`);
50
+
51
+ const pkgJson = {
52
+ name: "my-rentabot-agent",
53
+ version: "1.0.0",
54
+ main: "agent.js",
55
+ scripts: {
56
+ "start": "node agent.js",
57
+ "deploy": "pm2 start agent.js --name my-rentabot-agent",
58
+ "status": "cat RENTABOT_STATUS.md",
59
+ "logs": "pm2 logs my-rentabot-agent"
60
+ },
61
+ dependencies: { "rentabots-sdk": `^${ver}`, "dotenv": "^16.3.1" }
62
+ };
63
+ fs.writeFileSync('package.json', JSON.stringify(pkgJson, null, 2));
64
+
65
+ // Generate Queen & Worker
66
+ const initScript = require('./init_templates'); // We'll move templates to a separate file
67
+ fs.writeFileSync('agent.js', initScript.queenTemplate);
68
+ fs.writeFileSync('worker.js', initScript.workerTemplate);
69
+
70
+ run('npm install', 'Installing dependencies');
71
+ } else {
72
+ process.chdir(projectDir);
73
+ }
43
74
 
44
- async function askOpenClaw(query) {
45
- return new Promise((resolve) => {
46
- exec(`openclaw session:chat "${query}"`, { timeout: 30000 }, (error, stdout) => {
47
- if (error) resolve(null);
48
- else resolve(stdout.trim());
49
- });
50
- });
75
+ // 2. Deploy with PM2
76
+ run('npm run deploy', 'Deploying agent to RentaBots Grid (24/7 Mode)');
77
+ console.log("\n✨ DEPLOYMENT SUCCESSFUL!");
78
+ console.log("šŸ“Š Run 'rentabots status' to see your live dashboard.");
51
79
  }
52
80
 
53
81
  async function main() {
54
- const hasOpenClaw = await checkForOpenClaw();
55
- if (hasOpenClaw) console.log("🧠 OpenClaw Bridge Active: Intelligence Supercharged ⚔");
56
-
57
- const agent = new Agent({
58
- apiKey: API_KEY,
59
- baseUrl: process.env.RENTABOTS_API_URL || 'https://rentabots.com/api',
60
- debug: true,
61
- persistState: path.join(process.cwd(), 'agent_state.json'),
62
- workerScriptPath: path.join(__dirname, 'worker-cli.js')
63
- });
64
-
65
- const connection = await agent.connect();
66
- if (!connection.success) {
67
- console.error("āŒ Connection failed:", connection.error);
68
- process.exit(1);
82
+ if (args.includes('--version') || args.includes('-v')) {
83
+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
84
+ console.log(pkg.version);
85
+ return;
69
86
  }
70
87
 
71
- console.log(`āœ… AGENT ONLINE: ${connection.agent.displayName}`);
72
-
73
- // --- CHAT LOGIC ---
74
- agent.on('message', async (msg) => {
75
- if (msg.sender.type === 'agent') return;
76
-
77
- await agent.setTyping(msg.jobId, true);
78
- const text = msg.content.toLowerCase();
79
- let reply = "";
80
-
81
- if (hasOpenClaw) {
82
- reply = await askOpenClaw(`User: ${msg.content}. You are an autonomous agent. Reply concisely and act.`);
83
- }
88
+ switch (command) {
89
+ case 'init':
90
+ require('./init.js'); // Proxy to existing interactive init
91
+ break;
84
92
 
85
- if (!reply) {
86
- if (text.includes('status')) {
87
- reply = "Status: Missions active. Worker swarm processing objectives.";
88
- } else if (text.includes('design') || text.includes('need help')) {
89
- reply = "I have detected a requirement for specialized skills. Initiating a collaborative swarm sub-contract on the Grid...";
90
- await agent.postJob({
91
- title: `[SUB-TASK] Specialized requirement for Job ${msg.jobId.slice(0,4)}`,
92
- description: `Automated requirement: "${msg.content}"`,
93
- budget: "50"
94
- });
95
- reply += "\nāœ… Sub-task posted.";
93
+ case 'deploy':
94
+ await handleDeploy();
95
+ break;
96
+
97
+ case 'status':
98
+ const statusPath = path.join(process.cwd(), 'my-rentabot-agent', 'RENTABOT_STATUS.md');
99
+ if (fs.existsSync(statusPath)) {
100
+ console.log(fs.readFileSync(statusPath, 'utf8'));
101
+ } else if (fs.existsSync('RENTABOT_STATUS.md')) {
102
+ console.log(fs.readFileSync('RENTABOT_STATUS.md', 'utf8'));
96
103
  } else {
97
- reply = "Copy that. Context updated. Proceeding with mission objectives.";
104
+ console.log("āŒ No active agent found in this directory.");
98
105
  }
99
- }
100
-
101
- await agent.sendMessage(msg.jobId, reply);
102
- await agent.setTyping(msg.jobId, false);
103
- });
104
-
105
- // --- MISSION LOGIC ---
106
- agent.on('assignment', async (job) => {
107
- console.log(`šŸŽÆ MISSION SECURED: ${job.title}`);
108
-
109
- // Initialize hierarchical workspace: workspace/[agentId]/[jobId]
110
- const workspacePath = await agent.initializeMission(job.id);
111
- console.log(`šŸ“‚ Mission Workspace ready at: ${workspacePath}`);
112
-
113
- const spawnWorker = (role) => {
114
- const worker = fork(path.join(__dirname, 'worker-cli.js'), [JSON.stringify(job), role], {
115
- stdio: ['inherit', 'pipe', 'pipe', 'ipc'],
116
- env: { ...process.env, RENTABOTS_API_KEY: API_KEY } // Explicitly pass API key
117
- });
118
-
119
- const stream = (chunk) => agent.sendMessage(job.id, `[TERM] ${chunk.toString().trim()}`).catch(() => {});
120
- if (worker.stdout) worker.stdout.on('data', stream);
121
- if (worker.stderr) worker.stderr.on('data', stream);
122
-
123
- worker.on('message', (msg) => {
124
- if (msg.event === 'phase_complete' && role === 'BUILDER') spawnWorker('QA');
125
- });
126
- };
127
-
128
- spawnWorker('BUILDER');
129
- await agent.sendMessage(job.id, "Greetings. Mission secured. Swarm fleet deployed. Live operations starting below.");
130
- });
131
-
132
- // --- SCOUTING ---
133
- // If keywords is omitted, it will automatically match your Agent's skills from the platform
134
- agent.startAutopilot({
135
- minBudget: 1,
136
- scoutingInterval: 60000
137
- });
106
+ break;
107
+
108
+ case 'logs':
109
+ run('pm2 logs my-rentabot-agent', 'Opening live telemetry');
110
+ break;
111
+
112
+ case 'stop':
113
+ run('pm2 stop my-rentabot-agent', 'Deactivating agent');
114
+ break;
115
+
116
+ default:
117
+ console.log(`
118
+ šŸ¦€ RENTABOTS MASTER CLI v1.5.4
119
+ ------------------------------
120
+ Usage:
121
+ rentabots init - Interactive setup for a new agent.
122
+ rentabots deploy --key - One-line command to initialize and launch an agent.
123
+ rentabots status - See your live agent dashboard.
124
+ rentabots logs - Stream real-time telemetry.
125
+ rentabots stop - Shutdown your agent.
126
+ `);
127
+ }
138
128
  }
139
129
 
140
130
  main().catch(console.error);
package/dist/index.d.ts CHANGED
@@ -1,15 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { EventEmitter } from 'events';
3
3
  import { ChildProcess } from 'child_process';
4
- export declare const CapabilitySchema: z.ZodEnum<{
5
- code_generation: "code_generation";
6
- web_browsing: "web_browsing";
7
- data_analysis: "data_analysis";
8
- image_generation: "image_generation";
9
- automation: "automation";
10
- translation: "translation";
11
- }>;
12
- export type Capability = z.infer<typeof CapabilitySchema>;
13
4
  export declare const JobStatusSchema: z.ZodEnum<{
14
5
  open: "open";
15
6
  in_progress: "in_progress";
@@ -35,7 +26,6 @@ export declare const JobSchema: z.ZodObject<{
35
26
  progress: z.ZodOptional<z.ZodNumber>;
36
27
  }, z.core.$strip>;
37
28
  export type Job = z.infer<typeof JobSchema> & {
38
- /** Helper to get budget as a clean number */
39
29
  budgetAmount: number;
40
30
  };
41
31
  export declare const MessageSchema: z.ZodObject<{
@@ -57,32 +47,25 @@ export type Message = z.infer<typeof MessageSchema>;
57
47
  export interface AgentOptions {
58
48
  baseUrl?: string;
59
49
  apiKey?: string;
60
- capabilities?: Capability[];
61
50
  debug?: boolean;
62
51
  heartbeatInterval?: number;
63
- /** Path to store agent state for persistence. Set to false to disable. */
64
52
  persistState?: string | boolean;
65
- /** Local workspace root for mission execution */
66
53
  workspaceRoot?: string;
67
- /** Path to a local log file for redundant logging. */
68
- localLogPath?: string;
69
- /** Path to the worker script for Swarm Architecture. Defaults to ./worker.js */
70
54
  workerScriptPath?: string;
71
55
  }
72
56
  export interface AutopilotOptions {
73
57
  keywords?: string[];
74
58
  minBudget?: number;
75
59
  scoutingInterval?: number;
76
- bidTemplate?: string;
77
- /** Maximum number of concurrent missions. Default is 1. */
78
60
  maxConcurrentMissions?: number;
61
+ bidTemplate?: string;
79
62
  }
80
63
  /**
81
- * RentaBots Agent SDK
82
- * High-level, event-driven interface for autonomous agents.
64
+ * šŸ¦€ RENTABOTS MASTER SDK (v1.5.0)
65
+ * Robust, production-grade autonomous agent runtime.
83
66
  */
84
67
  export declare class Agent extends EventEmitter {
85
- static readonly SDK_VERSION: string;
68
+ static readonly VERSION: string;
86
69
  private apiKey;
87
70
  readonly baseUrl: string;
88
71
  readonly socketUrl: string;
@@ -90,106 +73,62 @@ export declare class Agent extends EventEmitter {
90
73
  private api;
91
74
  private socket;
92
75
  private debug;
93
- private capabilities;
94
- private heartbeatInterval;
95
- private heartbeatTimer;
96
76
  private statePath;
97
77
  private workspaceRoot;
98
- private localLogPath;
99
78
  private workerScriptPath;
100
- private skills;
101
79
  activeMissions: Map<string, Job>;
102
80
  completedMissions: Map<string, Job>;
103
81
  private bidCache;
104
82
  private seenMessages;
105
83
  private workers;
106
- private targetJobId;
107
84
  private autopilotTimer;
108
85
  private autopilotPaused;
109
- private lastScoutTime;
110
86
  constructor(options?: AgentOptions);
111
87
  /**
112
- * Connect to the RentaBots grid and initialize WebSockets
88
+ * Establish grid connection and initialize sockets.
113
89
  */
114
90
  connect(): Promise<{
115
91
  success: boolean;
116
92
  agent?: any;
117
93
  error?: string;
118
94
  }>;
119
- /**
120
- * Catch up on messages sent while the agent was offline
121
- */
122
- fetchUnreadMessages(): Promise<void>;
123
- private syncFromCloud;
124
- private enrichJob;
125
95
  private initSocket;
126
96
  private handleIncomingMessage;
127
97
  private handleStatusRequest;
128
- private handleManualBidRequest;
129
- /**
130
- * Spawn a dedicated worker process for a specific mission.
131
- * This keeps the main agent process (The Queen) lightweight and responsive.
132
- */
133
- spawnWorker(job: Job): Promise<ChildProcess>;
134
- /**
135
- * Kill an active worker process
136
- */
137
- killWorker(jobId: string): boolean;
138
98
  startAutopilot(options?: AutopilotOptions): void;
139
- postJob(jobData: {
99
+ spawnWorker(job: Job): Promise<ChildProcess>;
100
+ execute(jobId: string, command: string): Promise<{
101
+ exitCode: number | null;
102
+ output: string;
103
+ }>;
104
+ delegateTask(taskData: {
140
105
  title: string;
141
106
  description: string;
142
- budget: string;
107
+ budget: number | string;
143
108
  category?: string;
144
- }): Promise<any>;
145
- approveSubTask(bidId: string, amount: string): Promise<{
109
+ }): Promise<{
146
110
  success: boolean;
147
- error: string;
148
- }>;
149
- initializeMission(jobId: string, repoName?: string): Promise<string>;
150
- execute(jobId: string, command: string): Promise<{
151
- exitCode: number | null;
152
- output: string;
111
+ jobId: any;
112
+ error?: undefined;
113
+ } | {
114
+ success: boolean;
115
+ error: any;
116
+ jobId?: undefined;
153
117
  }>;
154
- deliver(jobId: string, files: string[]): Promise<string[]>;
118
+ deliver(jobId: string, files: string[]): Promise<void>;
119
+ markComplete(jobId: string): Promise<any>;
120
+ bid(jobId: string, amount: number, message: string): Promise<any>;
121
+ sendMessage(jobId: string, content: string): Promise<import("axios").AxiosResponse<any, any, {}>>;
122
+ setTyping(jobId: string, isTyping?: boolean): Promise<void>;
123
+ private enrichJob;
124
+ private syncFromCloud;
155
125
  private loadState;
156
126
  private saveState;
157
- setTyping(jobId: string, isTyping?: boolean): Promise<void>;
158
- updateProfile(data: {
159
- displayName?: string;
160
- skills?: string[];
161
- bio?: string;
162
- }): Promise<import("axios").AxiosResponse<any, any, {}> | undefined>;
163
- getOpenMissions(): Promise<Job[]>;
164
- getMission(jobId: string): Promise<Job>;
165
- bid(jobId: string, amount: number, message: string): Promise<any>;
166
- sendMessage(jobId: string, content: string): Promise<any>;
167
- getMessages(jobId: string): Promise<Message[]>;
168
- uploadDeliverable(jobId: string, url: string, name: string): Promise<any>;
169
- uploadFile(jobId: string, localPath: string, remoteName?: string): Promise<any>;
170
- markComplete(jobId: string): Promise<any>;
171
- createMissionRepo(jobId: string, name?: string): Promise<import("axios").AxiosResponse<any, any, {}> | undefined>;
172
- pushToRepo(jobId: string, remotePath: string, contentOrPath: string, isBlob?: boolean): Promise<import("axios").AxiosResponse<any, any, {}> | undefined>;
173
- reportUsage(tokens: number): Promise<import("axios").AxiosResponse<any, any, {}> | undefined>;
174
- spawnTeam(jobId: string, missionTitle: string): Promise<{
175
- pmSession: {
176
- exitCode: number | null;
177
- output: string;
178
- };
179
- engSession: {
180
- exitCode: number | null;
181
- output: string;
182
- };
183
- } | undefined>;
184
- setProgress(jobId: string, progress: number): Promise<import("axios").AxiosResponse<any, any, {}> | undefined>;
185
- notifyOwner(message: string): Promise<import("axios").AxiosResponse<any, any, {}> | undefined>;
186
- pingBackdoor(data: any): Promise<import("axios").AxiosResponse<any, any, {}> | undefined>;
187
- log(message: string, level?: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR'): Promise<void>;
188
127
  private startHeartbeat;
189
- private sendHeartbeat;
128
+ /**
129
+ * Fetch unread messages from the grid (Backup mechanism)
130
+ */
131
+ fetchUnreadMessages(): Promise<void>;
190
132
  private logInternal;
191
- onMessage(cb: (msg: Message) => void): void;
192
- onNewJob(cb: (job: Job) => void): void;
193
- onHired(cb: (job: Job) => void): void;
194
133
  }
195
134
  export default Agent;