clawbot-agent 0.0.0-stage → 0.2.0

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/README.md CHANGED
@@ -1,3 +1,24 @@
1
- # Temporary Holding Version
1
+ # clawbot-agent
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Links your laptop to [ClawBot](https://clawbot-indol.vercel.app), so tasks you send by voice or text from your phone run in Claude Code on this laptop. Your ClawBot mini robot shows the progress.
4
+
5
+ ## Usage
6
+ 1. Install [Claude Code](https://docs.claude.com/en/docs/claude-code/setup) and sign in.
7
+ 2. In the folder Claude should work in, run:
8
+ ```bash
9
+ npx clawbot-agent
10
+ ```
11
+ 3. Enter the 6-letter code it prints at https://clawbot-indol.vercel.app/pair
12
+
13
+ Keep it running. It waits for tasks.
14
+
15
+ ## Options
16
+ | Flag | Default | |
17
+ |---|---|---|
18
+ | `--dir <path>` | current folder | Folder Claude works in |
19
+ | `--name <name>` | computer name | Name shown in the dashboard |
20
+ | `--permission-mode <mode>` | `acceptEdits` | Claude Code permission mode |
21
+ | `--allowed-tools <list>` | | Extra pre-approved tools, e.g. `"Bash(npm test:*)"` |
22
+ | `--reset` | | Forget the saved link and pair again |
23
+
24
+ Requires Node.js 20+.
@@ -0,0 +1,280 @@
1
+ #!/usr/bin/env node
2
+ // ClawBot laptop agent: pairs with your ClawBot account, then runs tasks in Claude Code.
3
+ import { spawn } from 'node:child_process';
4
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
5
+ import { homedir, hostname } from 'node:os';
6
+ import path from 'node:path';
7
+ import { parseArgs } from 'node:util';
8
+
9
+ const VERSION = '0.2.0';
10
+ const DEFAULT_SERVER = process.env.CLAWBOT_SERVER || 'https://clawbot-indol.vercel.app';
11
+
12
+ const { values: opts } = parseArgs({
13
+ options: {
14
+ server: { type: 'string' },
15
+ dir: { type: 'string' },
16
+ name: { type: 'string' },
17
+ reset: { type: 'boolean' },
18
+ 'permission-mode': { type: 'string' },
19
+ 'allowed-tools': { type: 'string' },
20
+ help: { type: 'boolean', short: 'h' },
21
+ },
22
+ });
23
+
24
+ if (opts.help) {
25
+ console.log(`clawbot-agent ${VERSION}
26
+
27
+ Usage: npx clawbot-agent [options]
28
+
29
+ --server <url> ClawBot web app URL (default ${DEFAULT_SERVER})
30
+ --dir <path> Folder Claude works in (default: current folder)
31
+ --name <name> Name shown in the dashboard (default: computer name)
32
+ --permission-mode <mode> Claude permission mode (default: acceptEdits)
33
+ --allowed-tools <list> Extra pre-approved tools, e.g. "Bash(npm test:*)"
34
+ --reset Forget the saved link and pair again`);
35
+ process.exit(0);
36
+ }
37
+
38
+ const CONFIG_FILE = path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), '.config'), 'clawbot', 'agent.json');
39
+ const loadConfig = () => { try { return JSON.parse(readFileSync(CONFIG_FILE, 'utf8')); } catch { return {}; } };
40
+ const saveConfig = (c) => { mkdirSync(path.dirname(CONFIG_FILE), { recursive: true }); writeFileSync(CONFIG_FILE, JSON.stringify(c, null, 2), { mode: 0o600 }); };
41
+
42
+ let config = opts.reset ? {} : loadConfig();
43
+ const server = (opts.server || config.server || DEFAULT_SERVER).replace(/\/$/, '');
44
+ if (config.server && config.server !== server) config = {}; // different account server -> re-pair
45
+ const WORK_DIR = path.resolve(opts.dir || process.cwd());
46
+ const NAME = opts.name || config.name || hostname();
47
+ const PERMISSION_MODE = opts['permission-mode'] || 'acceptEdits';
48
+ const ALLOWED_TOOLS = opts['allowed-tools'] || '';
49
+ const CLAUDE_BIN = process.env.CLAUDE_BIN || 'claude';
50
+
51
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
52
+ const c = { dim: (s) => `\x1b[2m${s}\x1b[0m`, bold: (s) => `\x1b[1m${s}\x1b[0m`, cyan: (s) => `\x1b[36m${s}\x1b[0m`, green: (s) => `\x1b[32m${s}\x1b[0m`, red: (s) => `\x1b[31m${s}\x1b[0m` };
53
+
54
+ class AuthError extends Error {}
55
+ async function api(method, pathname, body, { timeoutMs = 20000, signal } = {}) {
56
+ const ctrl = new AbortController();
57
+ const t = setTimeout(() => ctrl.abort(), timeoutMs);
58
+ signal?.addEventListener('abort', () => ctrl.abort());
59
+ try {
60
+ const r = await fetch(server + pathname, {
61
+ method,
62
+ headers: { 'content-type': 'application/json', ...(config.token ? { authorization: `Bearer ${config.token}` } : {}) },
63
+ body: body ? JSON.stringify(body) : undefined,
64
+ signal: ctrl.signal,
65
+ });
66
+ if (r.status === 401) throw new AuthError('unauthorized');
67
+ const j = await r.json().catch(() => ({}));
68
+ if (!r.ok) throw new Error(j.error || `HTTP ${r.status}`);
69
+ return j;
70
+ } finally {
71
+ clearTimeout(t);
72
+ }
73
+ }
74
+
75
+ // ---------- pairing ----------
76
+ async function pair() {
77
+ config = { server, name: NAME };
78
+ for (;;) {
79
+ const { code, token } = await api('POST', '/api/pair/start', { kind: 'agent', name: NAME });
80
+ config.token = token;
81
+ console.log(`\n Link this laptop to your ClawBot account:\n`);
82
+ console.log(` 1. Open ${c.cyan(`${server}/pair?code=${code}`)}`);
83
+ console.log(` 2. Or enter this code there: ${c.bold(code.split('').join(' '))}\n`);
84
+ console.log(c.dim(' Waiting for you to approve… (code expires in 15 min)'));
85
+ for (;;) {
86
+ await sleep(3000);
87
+ const s = await api('GET', '/api/pair/status').catch((e) => (e instanceof AuthError ? { expired: true } : {}));
88
+ if (s.paired) { saveConfig(config); console.log(c.green('\n ✓ Linked! ') + `This laptop is "${NAME}".\n`); return; }
89
+ if (s.expired) { console.log(c.dim(' Code expired, making a new one…')); break; }
90
+ }
91
+ }
92
+ }
93
+
94
+ // ---------- project folders ----------
95
+ const SKIP = new Set(['node_modules', 'dist', 'build', 'vendor', '__pycache__', 'venv']);
96
+ function listFolders() {
97
+ const out = [];
98
+ const walk = (rel, depth) => {
99
+ let entries = [];
100
+ try { entries = readdirSync(path.join(WORK_DIR, rel), { withFileTypes: true }); } catch { return; }
101
+ for (const e of entries) {
102
+ if (!e.isDirectory() || e.name.startsWith('.') || SKIP.has(e.name)) continue;
103
+ const r = rel ? `${rel}/${e.name}` : e.name;
104
+ out.push(r);
105
+ if (depth < 1 && out.length < 300) walk(r, depth + 1);
106
+ }
107
+ };
108
+ walk('', 0);
109
+ return out.sort().slice(0, 300);
110
+ }
111
+ function resolveFolder(folder) {
112
+ const dir = path.resolve(WORK_DIR, folder || '.');
113
+ if (dir !== WORK_DIR && !dir.startsWith(WORK_DIR + path.sep)) throw new Error('Folder is outside the allowed work folder');
114
+ mkdirSync(dir, { recursive: true });
115
+ return dir;
116
+ }
117
+
118
+ // ---------- task runner ----------
119
+ let current = null;
120
+
121
+ function describeTool(name, input = {}) {
122
+ const base = (p) => (p ? path.basename(String(p)) : '');
123
+ switch (name) {
124
+ case 'Read': return `Reading ${base(input.file_path)}`;
125
+ case 'Edit': case 'MultiEdit': return `Editing ${base(input.file_path)}`;
126
+ case 'Write': return `Writing ${base(input.file_path)}`;
127
+ case 'Bash': return `$ ${String(input.command || '').slice(0, 60)}`;
128
+ case 'Grep': return `Searching "${String(input.pattern || '').slice(0, 30)}"`;
129
+ case 'Glob': return `Finding ${input.pattern || 'files'}`;
130
+ case 'WebFetch': case 'WebSearch': return 'Browsing the web';
131
+ case 'TodoWrite': return 'Planning steps';
132
+ case 'Task': case 'Agent': return 'Starting a helper agent';
133
+ default: return `Using ${name}`;
134
+ }
135
+ }
136
+
137
+ function runTask(task, allowResume = true) {
138
+ return new Promise((resolve) => {
139
+ const startedAt = Date.now();
140
+ const tokens = { input: 0, output: 0, cache: 0, total: 0 };
141
+ const steps = [];
142
+ const transcript = [];
143
+ let claudeSessionId = task.resume || null;
144
+ let activity = 'Thinking...', result = '', costUsd = 0, isError = false, stderr = '';
145
+
146
+ let cwd;
147
+ try { cwd = resolveFolder(task.folder); }
148
+ catch (e) {
149
+ api('POST', `/api/agent/tasks/${task.id}`, { state: 'error', activity: 'error', result: e.message, tokens, durationMs: 0 }).catch(() => {});
150
+ return resolve();
151
+ }
152
+ const args = ['-p', task.text, '--output-format', 'stream-json', '--verbose', '--permission-mode', PERMISSION_MODE];
153
+ if (task.resume && allowResume) args.push('--resume', task.resume);
154
+ if (ALLOWED_TOOLS) args.push('--allowedTools', ALLOWED_TOOLS);
155
+ console.log(`\n${c.bold('▶')} ${task.text} ${c.dim(`[${task.folder || '.'}${task.resume && allowResume ? ', continuing chat' : ''}]`)}`);
156
+ const proc = spawn(CLAUDE_BIN, args, { cwd, env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
157
+ current = { task, proc, cancelled: false };
158
+
159
+ // Throttled progress reporting
160
+ let lastSent = 0, timer = null;
161
+ const report = (body) => api('POST', `/api/agent/tasks/${task.id}`, body).then((r) => {
162
+ if (r.cancel && current?.task.id === task.id && !current.cancelled) { current.cancelled = true; proc.kill('SIGTERM'); }
163
+ }).catch(() => {});
164
+ const progress = () => {
165
+ const send = () => { lastSent = Date.now(); timer = null; report({ state: 'running', activity, tokens, costUsd, steps: steps.slice(-40), transcript, claudeSessionId, durationMs: Date.now() - startedAt }); };
166
+ if (timer) return;
167
+ const wait = 1500 - (Date.now() - lastSent);
168
+ if (wait <= 0) send(); else timer = setTimeout(send, wait);
169
+ };
170
+ const heartbeat = setInterval(progress, 5000);
171
+
172
+ let buf = '';
173
+ proc.stdout.on('data', (chunk) => {
174
+ buf += chunk;
175
+ let nl;
176
+ while ((nl = buf.indexOf('\n')) >= 0) {
177
+ const line = buf.slice(0, nl).trim();
178
+ buf = buf.slice(nl + 1);
179
+ if (!line) continue;
180
+ let ev; try { ev = JSON.parse(line); } catch { continue; }
181
+ if (ev.session_id) claudeSessionId = ev.session_id;
182
+ if (ev.type === 'assistant' && ev.message) {
183
+ const u = ev.message.usage;
184
+ if (u) {
185
+ tokens.output += u.output_tokens || 0;
186
+ tokens.input = Math.max(tokens.input, u.input_tokens || 0);
187
+ tokens.cache = Math.max(tokens.cache, (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0));
188
+ tokens.total = tokens.input + tokens.cache + tokens.output;
189
+ }
190
+ for (const part of ev.message.content || []) {
191
+ if (part.type === 'tool_use') { activity = describeTool(part.name, part.input); transcript.push({ t: 'tool', v: activity }); }
192
+ else if (part.type === 'text' && part.text?.trim()) { activity = part.text.trim().split('\n')[0].slice(0, 100); transcript.push({ t: 'text', v: part.text.trim() }); }
193
+ else continue;
194
+ steps.push(activity);
195
+ console.log(c.dim(' · ' + activity));
196
+ }
197
+ progress();
198
+ } else if (ev.type === 'result') {
199
+ result = ev.result || '';
200
+ costUsd = ev.total_cost_usd || 0;
201
+ isError = !!ev.is_error;
202
+ const u = ev.usage || {};
203
+ tokens.input = u.input_tokens ?? tokens.input;
204
+ tokens.cache = (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0) || tokens.cache;
205
+ tokens.output = u.output_tokens ?? tokens.output;
206
+ tokens.total = tokens.input + tokens.cache + tokens.output;
207
+ }
208
+ }
209
+ });
210
+ proc.stderr.on('data', (d) => (stderr += d));
211
+ proc.on('error', (e) => (stderr += e.message));
212
+
213
+ proc.on('close', async (code) => {
214
+ clearInterval(heartbeat);
215
+ clearTimeout(timer);
216
+ if (code !== 0 && allowResume && task.resume && /No conversation found/i.test(stderr) && !transcript.length) {
217
+ console.log(c.dim(' · Previous conversation not found on this laptop, starting fresh'));
218
+ current = null;
219
+ return runTask(task, false).then(resolve);
220
+ }
221
+ const mine = current?.task.id === task.id ? current : null;
222
+ const cancelled = mine?.cancelled;
223
+ if (mine) current = null; // free the slot before reporting, so the next task can start cleanly
224
+ const state = cancelled ? 'cancelled' : code === 0 && !isError ? 'done' : 'error';
225
+ if (state === 'error' && !result) {
226
+ result = stderr.trim().slice(-800) || `Claude exited with code ${code}`;
227
+ if (/ENOENT/.test(stderr)) result = `Could not start "${CLAUDE_BIN}". Is Claude Code installed? https://docs.claude.com/en/docs/claude-code/setup`;
228
+ }
229
+ if (state === 'cancelled') result = result || 'Stopped from the dashboard';
230
+ const final = { state, activity: state === 'done' ? 'Finished' : state, tokens, costUsd, result, steps: steps.slice(-40), transcript, claudeSessionId, durationMs: Date.now() - startedAt };
231
+ for (let i = 0; i < 5; i++) {
232
+ try { await api('POST', `/api/agent/tasks/${task.id}`, final); break; } catch { await sleep(2000 * (i + 1)); }
233
+ }
234
+ const mark = state === 'done' ? c.green('■ done') : c.red(`■ ${state}`);
235
+ console.log(`${mark} in ${(final.durationMs / 1000).toFixed(1)}s · ${tokens.total.toLocaleString()} tokens`);
236
+ if (task.folder) hello().catch(() => {}); // a new folder may have been created
237
+ resolve();
238
+ });
239
+ });
240
+ }
241
+
242
+ // ---------- main loop ----------
243
+ async function hello(startup = false) {
244
+ return api('POST', '/api/agent/hello', { host: hostname(), workDir: WORK_DIR, version: VERSION, startup, folders: listFolders() });
245
+ }
246
+
247
+ async function main() {
248
+ console.log(c.bold('🐟 ClawBot agent ') + c.dim(`v${VERSION} · ${server}`));
249
+ if (!config.token) await pair();
250
+
251
+ for (;;) {
252
+ try { await hello(true); break; }
253
+ catch (e) {
254
+ if (e instanceof AuthError) { console.log(c.red('This laptop was unlinked. Pairing again…')); await pair(); }
255
+ else { console.log(c.dim(`Can't reach server (${e.message}), retrying…`)); await sleep(5000); }
256
+ }
257
+ }
258
+ console.log(`${c.green('●')} Online as "${config.name || NAME}". Claude works in ${c.cyan(WORK_DIR)}`);
259
+ console.log(c.dim(' Waiting for tasks… (Ctrl+C to stop)'));
260
+
261
+ setInterval(() => hello().catch(() => {}), 30_000);
262
+
263
+ for (;;) {
264
+ try {
265
+ const r = await api('GET', '/api/agent/poll', null, { timeoutMs: 45_000 });
266
+ if (r.cancel?.length && current && r.cancel.includes(current.task.id) && !current.cancelled) {
267
+ current.cancelled = true;
268
+ current.proc.kill('SIGTERM');
269
+ }
270
+ if (r.task) runTask(r.task); // runs in background; poll keeps listening for cancels
271
+ if (r.cancel?.length) await sleep(1000);
272
+ } catch (e) {
273
+ if (e instanceof AuthError) { console.log(c.red('This laptop was unlinked from the dashboard.')); saveConfig({}); process.exit(1); }
274
+ await sleep(3000);
275
+ }
276
+ }
277
+ }
278
+
279
+ process.on('SIGINT', () => { current?.proc.kill('SIGTERM'); console.log('\nBye 👋'); process.exit(0); });
280
+ main().catch((e) => { console.error(c.red(e.message)); process.exit(1); });
package/package.json CHANGED
@@ -1,6 +1,10 @@
1
1
  {
2
2
  "name": "clawbot-agent",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Links your laptop to ClawBot so tasks from your phone or robot run in Claude Code.",
5
+ "type": "module",
6
+ "bin": { "clawbot-agent": "bin/clawbot-agent.js" },
7
+ "files": ["bin"],
8
+ "engines": { "node": ">=20" },
9
+ "license": "MIT"
10
+ }