clawbot-agent 0.1.0 → 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.
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  // ClawBot laptop agent: pairs with your ClawBot account, then runs tasks in Claude Code.
3
3
  import { spawn } from 'node:child_process';
4
- import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
4
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
5
5
  import { homedir, hostname } from 'node:os';
6
6
  import path from 'node:path';
7
7
  import { parseArgs } from 'node:util';
8
8
 
9
- const VERSION = '0.1.0';
9
+ const VERSION = '0.2.0';
10
10
  const DEFAULT_SERVER = process.env.CLAWBOT_SERVER || 'https://clawbot-indol.vercel.app';
11
11
 
12
12
  const { values: opts } = parseArgs({
@@ -91,6 +91,30 @@ async function pair() {
91
91
  }
92
92
  }
93
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
+
94
118
  // ---------- task runner ----------
95
119
  let current = null;
96
120
 
@@ -110,17 +134,26 @@ function describeTool(name, input = {}) {
110
134
  }
111
135
  }
112
136
 
113
- function runTask(task) {
137
+ function runTask(task, allowResume = true) {
114
138
  return new Promise((resolve) => {
115
139
  const startedAt = Date.now();
116
140
  const tokens = { input: 0, output: 0, cache: 0, total: 0 };
117
141
  const steps = [];
142
+ const transcript = [];
143
+ let claudeSessionId = task.resume || null;
118
144
  let activity = 'Thinking...', result = '', costUsd = 0, isError = false, stderr = '';
119
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
+ }
120
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);
121
154
  if (ALLOWED_TOOLS) args.push('--allowedTools', ALLOWED_TOOLS);
122
- console.log(`\n${c.bold('▶')} ${task.text}`);
123
- const proc = spawn(CLAUDE_BIN, args, { cwd: WORK_DIR, env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
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'] });
124
157
  current = { task, proc, cancelled: false };
125
158
 
126
159
  // Throttled progress reporting
@@ -129,7 +162,7 @@ function runTask(task) {
129
162
  if (r.cancel && current?.task.id === task.id && !current.cancelled) { current.cancelled = true; proc.kill('SIGTERM'); }
130
163
  }).catch(() => {});
131
164
  const progress = () => {
132
- const send = () => { lastSent = Date.now(); timer = null; report({ state: 'running', activity, tokens, costUsd, steps: steps.slice(-40), durationMs: Date.now() - startedAt }); };
165
+ const send = () => { lastSent = Date.now(); timer = null; report({ state: 'running', activity, tokens, costUsd, steps: steps.slice(-40), transcript, claudeSessionId, durationMs: Date.now() - startedAt }); };
133
166
  if (timer) return;
134
167
  const wait = 1500 - (Date.now() - lastSent);
135
168
  if (wait <= 0) send(); else timer = setTimeout(send, wait);
@@ -145,6 +178,7 @@ function runTask(task) {
145
178
  buf = buf.slice(nl + 1);
146
179
  if (!line) continue;
147
180
  let ev; try { ev = JSON.parse(line); } catch { continue; }
181
+ if (ev.session_id) claudeSessionId = ev.session_id;
148
182
  if (ev.type === 'assistant' && ev.message) {
149
183
  const u = ev.message.usage;
150
184
  if (u) {
@@ -154,8 +188,8 @@ function runTask(task) {
154
188
  tokens.total = tokens.input + tokens.cache + tokens.output;
155
189
  }
156
190
  for (const part of ev.message.content || []) {
157
- if (part.type === 'tool_use') activity = describeTool(part.name, part.input);
158
- else if (part.type === 'text' && part.text?.trim()) activity = part.text.trim().split('\n')[0].slice(0, 100);
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() }); }
159
193
  else continue;
160
194
  steps.push(activity);
161
195
  console.log(c.dim(' · ' + activity));
@@ -179,20 +213,27 @@ function runTask(task) {
179
213
  proc.on('close', async (code) => {
180
214
  clearInterval(heartbeat);
181
215
  clearTimeout(timer);
182
- const cancelled = current?.cancelled;
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
183
224
  const state = cancelled ? 'cancelled' : code === 0 && !isError ? 'done' : 'error';
184
225
  if (state === 'error' && !result) {
185
226
  result = stderr.trim().slice(-800) || `Claude exited with code ${code}`;
186
227
  if (/ENOENT/.test(stderr)) result = `Could not start "${CLAUDE_BIN}". Is Claude Code installed? https://docs.claude.com/en/docs/claude-code/setup`;
187
228
  }
188
229
  if (state === 'cancelled') result = result || 'Stopped from the dashboard';
189
- const final = { state, activity: state === 'done' ? 'Finished' : state, tokens, costUsd, result, steps: steps.slice(-40), durationMs: Date.now() - startedAt };
230
+ const final = { state, activity: state === 'done' ? 'Finished' : state, tokens, costUsd, result, steps: steps.slice(-40), transcript, claudeSessionId, durationMs: Date.now() - startedAt };
190
231
  for (let i = 0; i < 5; i++) {
191
232
  try { await api('POST', `/api/agent/tasks/${task.id}`, final); break; } catch { await sleep(2000 * (i + 1)); }
192
233
  }
193
234
  const mark = state === 'done' ? c.green('■ done') : c.red(`■ ${state}`);
194
235
  console.log(`${mark} in ${(final.durationMs / 1000).toFixed(1)}s · ${tokens.total.toLocaleString()} tokens`);
195
- current = null;
236
+ if (task.folder) hello().catch(() => {}); // a new folder may have been created
196
237
  resolve();
197
238
  });
198
239
  });
@@ -200,7 +241,7 @@ function runTask(task) {
200
241
 
201
242
  // ---------- main loop ----------
202
243
  async function hello(startup = false) {
203
- return api('POST', '/api/agent/hello', { host: hostname(), workDir: WORK_DIR, version: VERSION, startup });
244
+ return api('POST', '/api/agent/hello', { host: hostname(), workDir: WORK_DIR, version: VERSION, startup, folders: listFolders() });
204
245
  }
205
246
 
206
247
  async function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clawbot-agent",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Links your laptop to ClawBot so tasks from your phone or robot run in Claude Code.",
5
5
  "type": "module",
6
6
  "bin": { "clawbot-agent": "bin/clawbot-agent.js" },