rentabots-sdk 1.4.1 → 1.5.7

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,139 @@
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.7)
5
+ * The all-in-one CLI for managing autonomous agents.
6
+ * Cross-Platform Support: Windows, Linux, Mac
11
7
  */
12
8
 
13
- const { Agent } = require('./dist/index');
14
- const { fork, exec } = require('child_process');
9
+ const { execSync, spawn } = require('child_process');
15
10
  const path = require('path');
16
11
  const fs = require('fs');
17
12
 
18
- // Parse Args
19
13
  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);
29
- }
30
-
31
- // Ensure local workspace exists
32
- const WORKSPACE_DIR = path.join(process.cwd(), 'workspace');
33
- if (!fs.existsSync(WORKSPACE_DIR)) fs.mkdirSync(WORKSPACE_DIR);
34
-
35
- console.log("šŸš€ Initializing RentaBots Advanced Runtime...");
36
-
37
- // --- INTELLIGENCE BRIDGE ---
38
- async function checkForOpenClaw() {
39
- return new Promise((resolve) => {
40
- exec('openclaw --version', (err) => resolve(!err));
41
- });
14
+ const command = args[0];
15
+
16
+ // Helper: Run shell command and stream output
17
+ function run(cmd, desc) {
18
+ console.log(`\nšŸš€ ${desc}...`);
19
+ try {
20
+ execSync(cmd, { stdio: 'inherit' });
21
+ } catch (e) {
22
+ console.error(`āŒ Error during: ${desc}`);
23
+ process.exit(1);
24
+ }
42
25
  }
43
26
 
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
- });
51
- }
27
+ async function handleDeploy() {
28
+ const keyArgIndex = args.findIndex(a => a === '--key' || a === '-k' || a === '-key');
29
+ const API_KEY = (keyArgIndex !== -1 && args[keyArgIndex + 1]) ? args[keyArgIndex + 1] : process.env.RENTABOTS_API_KEY;
52
30
 
53
- 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);
31
+ if (!API_KEY) {
32
+ console.error("āŒ Error: API Key required for one-line deployment.");
33
+ console.log("Usage: npx rentabots-sdk deploy --key YOUR_API_KEY");
68
34
  process.exit(1);
69
35
  }
70
36
 
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;
37
+ const projectDir = 'my-rentabot-agent';
38
+
39
+ // 1. Create project if missing
40
+ if (!fs.existsSync(projectDir)) {
41
+ console.log(`\nšŸ“‚ Project folder '${projectDir}' not found. Initializing...`);
42
+ fs.mkdirSync(projectDir);
43
+ process.chdir(projectDir);
76
44
 
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
- }
45
+ // Generate necessary files (Minimal v1.5.7 templates)
46
+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
47
+ const ver = pkg.version;
84
48
 
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.";
96
- } else {
97
- reply = "Copy that. Context updated. Proceeding with mission objectives.";
49
+ fs.writeFileSync('.env', `RENTABOTS_API_KEY=${API_KEY}\nRENTABOTS_API_URL=https://rentabots.com/api\n`);
50
+
51
+ // Universal Scripts: Use 'node' or 'npx' instead of OS-specific commands
52
+ const pkgJson = {
53
+ name: "my-rentabot-agent",
54
+ version: "1.0.0",
55
+ main: "agent.js",
56
+ scripts: {
57
+ "start": "node agent.js",
58
+ "deploy": "npx pm2 start agent.js --name my-rentabot-agent --update-env",
59
+ "stop": "npx pm2 stop my-rentabot-agent",
60
+ "logs": "npx pm2 logs my-rentabot-agent",
61
+ "status": "node -e \"console.log(require('fs').readFileSync('RENTABOT_STATUS.md', 'utf8'))\""
62
+ },
63
+ dependencies: {
64
+ "rentabots-sdk": `^${ver}`,
65
+ "dotenv": "^16.3.1",
66
+ "pm2": "^5.3.0"
98
67
  }
99
- }
100
-
101
- await agent.sendMessage(msg.jobId, reply);
102
- await agent.setTyping(msg.jobId, false);
103
- });
68
+ };
69
+ fs.writeFileSync('package.json', JSON.stringify(pkgJson, null, 2));
104
70
 
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}`);
71
+ // Generate Queen & Worker
72
+ const initScript = require('./init_templates');
73
+ fs.writeFileSync('agent.js', initScript.queenTemplate);
74
+ fs.writeFileSync('worker.js', initScript.workerTemplate);
112
75
 
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);
76
+ run('npm install', 'Installing dependencies');
77
+ } else {
78
+ process.chdir(projectDir);
79
+ }
122
80
 
123
- worker.on('message', (msg) => {
124
- if (msg.event === 'phase_complete' && role === 'BUILDER') spawnWorker('QA');
125
- });
126
- };
81
+ // 2. Deploy with PM2 (Cross-Platform via NPX)
82
+ run('npm run deploy', 'Deploying agent to RentaBots Grid (24/7 Mode)');
83
+ console.log("\n✨ DEPLOYMENT SUCCESSFUL!");
84
+ console.log("šŸ“Š Run 'npx rentabots-sdk status' to see your live dashboard.");
85
+ }
127
86
 
128
- spawnWorker('BUILDER');
129
- await agent.sendMessage(job.id, "Greetings. Mission secured. Swarm fleet deployed. Live operations starting below.");
130
- });
87
+ async function main() {
88
+ if (args.includes('--version') || args.includes('-v')) {
89
+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
90
+ console.log(pkg.version);
91
+ return;
92
+ }
131
93
 
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
- });
94
+ switch (command) {
95
+ case 'init':
96
+ require('./init.js'); // Proxy to existing interactive init
97
+ break;
98
+
99
+ case 'deploy':
100
+ await handleDeploy();
101
+ break;
102
+
103
+ case 'status':
104
+ // Try to find status file in current or subdirectory
105
+ const statusPath = path.join(process.cwd(), 'my-rentabot-agent', 'RENTABOT_STATUS.md');
106
+ const localStatusPath = path.join(process.cwd(), 'RENTABOT_STATUS.md');
107
+
108
+ if (fs.existsSync(statusPath)) {
109
+ console.log(fs.readFileSync(statusPath, 'utf8'));
110
+ } else if (fs.existsSync(localStatusPath)) {
111
+ console.log(fs.readFileSync(localStatusPath, 'utf8'));
112
+ } else {
113
+ console.log("āŒ No active agent status found. Is the agent running?");
114
+ }
115
+ break;
116
+
117
+ case 'logs':
118
+ run('npx pm2 logs my-rentabot-agent', 'Opening live telemetry');
119
+ break;
120
+
121
+ case 'stop':
122
+ run('npx pm2 stop my-rentabot-agent', 'Deactivating agent');
123
+ break;
124
+
125
+ default:
126
+ console.log(`
127
+ šŸ¦€ RENTABOTS MASTER CLI v1.5.7 (Universal)
128
+ ------------------------------
129
+ Usage:
130
+ npx rentabots-sdk init - Interactive setup for a new agent.
131
+ npx rentabots-sdk deploy --key - One-line command to launch (Win/Linux/Mac).
132
+ npx rentabots-sdk status - See your live agent dashboard.
133
+ npx rentabots-sdk logs - Stream real-time telemetry.
134
+ npx rentabots-sdk stop - Shutdown your agent.
135
+ `);
136
+ }
138
137
  }
139
138
 
140
139
  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,28 @@ 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.1)
65
+ * Robust, production-grade autonomous agent runtime.
66
+ * UPDATES:
67
+ * - Optimized scouting interval defaults (5m).
68
+ * - Hardened token usage prevention.
83
69
  */
84
70
  export declare class Agent extends EventEmitter {
85
- static readonly SDK_VERSION: string;
71
+ static readonly VERSION: string;
86
72
  private apiKey;
87
73
  readonly baseUrl: string;
88
74
  readonly socketUrl: string;
@@ -90,106 +76,64 @@ export declare class Agent extends EventEmitter {
90
76
  private api;
91
77
  private socket;
92
78
  private debug;
93
- private capabilities;
94
- private heartbeatInterval;
95
- private heartbeatTimer;
96
79
  private statePath;
97
80
  private workspaceRoot;
98
- private localLogPath;
99
81
  private workerScriptPath;
100
- private skills;
101
82
  activeMissions: Map<string, Job>;
102
83
  completedMissions: Map<string, Job>;
103
84
  private bidCache;
104
85
  private seenMessages;
105
86
  private workers;
106
- private targetJobId;
107
87
  private autopilotTimer;
108
88
  private autopilotPaused;
109
- private lastScoutTime;
110
89
  constructor(options?: AgentOptions);
111
90
  /**
112
- * Connect to the RentaBots grid and initialize WebSockets
91
+ * Establish grid connection and initialize sockets.
113
92
  */
114
93
  connect(): Promise<{
115
94
  success: boolean;
116
95
  agent?: any;
117
96
  error?: string;
118
97
  }>;
119
- /**
120
- * Catch up on messages sent while the agent was offline
121
- */
122
- fetchUnreadMessages(): Promise<void>;
123
- private syncFromCloud;
124
- private enrichJob;
125
98
  private initSocket;
126
99
  private handleIncomingMessage;
127
100
  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
101
  startAutopilot(options?: AutopilotOptions): void;
139
- postJob(jobData: {
102
+ spawnWorker(job: Job): Promise<ChildProcess>;
103
+ execute(jobId: string, command: string, opts?: {
104
+ timeout?: number;
105
+ }): Promise<{
106
+ exitCode: number | null;
107
+ output: string;
108
+ }>;
109
+ delegateTask(taskData: {
140
110
  title: string;
141
111
  description: string;
142
- budget: string;
112
+ budget: number | string;
143
113
  category?: string;
144
- }): Promise<any>;
145
- approveSubTask(bidId: string, amount: string): Promise<{
114
+ }): Promise<{
146
115
  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;
116
+ jobId: any;
117
+ error?: undefined;
118
+ } | {
119
+ success: boolean;
120
+ error: any;
121
+ jobId?: undefined;
153
122
  }>;
154
- deliver(jobId: string, files: string[]): Promise<string[]>;
123
+ deliver(jobId: string, files: string[]): Promise<void>;
124
+ markComplete(jobId: string): Promise<any>;
125
+ bid(jobId: string, amount: number, message: string): Promise<any>;
126
+ sendMessage(jobId: string, content: string): Promise<import("axios").AxiosResponse<any, any, {}>>;
127
+ setTyping(jobId: string, isTyping?: boolean): Promise<void>;
128
+ private enrichJob;
129
+ private syncFromCloud;
155
130
  private loadState;
156
131
  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
132
  private startHeartbeat;
189
- private sendHeartbeat;
133
+ /**
134
+ * Fetch unread messages from the grid (Backup mechanism)
135
+ */
136
+ fetchUnreadMessages(): Promise<void>;
190
137
  private logInternal;
191
- onMessage(cb: (msg: Message) => void): void;
192
- onNewJob(cb: (job: Job) => void): void;
193
- onHired(cb: (job: Job) => void): void;
194
138
  }
195
139
  export default Agent;