|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * NanoClaw — Barebones Agent REPL for Everything Claude Code |
| 4 | + * |
| 5 | + * A persistent, session-aware AI agent loop that delegates to `claude -p`. |
| 6 | + * Zero external dependencies. Markdown-as-database. Synchronous REPL. |
| 7 | + * |
| 8 | + * Usage: |
| 9 | + * node scripts/claw.js |
| 10 | + * CLAW_SESSION=my-project node scripts/claw.js |
| 11 | + * CLAW_SKILLS=tdd-workflow,security-review node scripts/claw.js |
| 12 | + */ |
| 13 | + |
| 14 | +'use strict'; |
| 15 | + |
| 16 | +const fs = require('fs'); |
| 17 | +const path = require('path'); |
| 18 | +const os = require('os'); |
| 19 | +const { spawnSync } = require('child_process'); |
| 20 | +const readline = require('readline'); |
| 21 | + |
| 22 | +// ─── Session name validation ──────────────────────────────────────────────── |
| 23 | + |
| 24 | +const SESSION_NAME_RE = /^[a-zA-Z0-9][-a-zA-Z0-9]*$/; |
| 25 | + |
| 26 | +function isValidSessionName(name) { |
| 27 | + return typeof name === 'string' && name.length > 0 && SESSION_NAME_RE.test(name); |
| 28 | +} |
| 29 | + |
| 30 | +// ─── Storage Adapter (Markdown-as-Database) ───────────────────────────────── |
| 31 | + |
| 32 | +function getClawDir() { |
| 33 | + return path.join(os.homedir(), '.claude', 'claw'); |
| 34 | +} |
| 35 | + |
| 36 | +function getSessionPath(name) { |
| 37 | + return path.join(getClawDir(), name + '.md'); |
| 38 | +} |
| 39 | + |
| 40 | +function listSessions(dir) { |
| 41 | + const clawDir = dir || getClawDir(); |
| 42 | + if (!fs.existsSync(clawDir)) { |
| 43 | + return []; |
| 44 | + } |
| 45 | + return fs.readdirSync(clawDir) |
| 46 | + .filter(f => f.endsWith('.md')) |
| 47 | + .map(f => f.replace(/\.md$/, '')); |
| 48 | +} |
| 49 | + |
| 50 | +function loadHistory(filePath) { |
| 51 | + try { |
| 52 | + return fs.readFileSync(filePath, 'utf8'); |
| 53 | + } catch (_err) { |
| 54 | + return ''; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +function appendTurn(filePath, role, content, timestamp) { |
| 59 | + const ts = timestamp || new Date().toISOString(); |
| 60 | + const entry = `### [${ts}] ${role}\n${content}\n---\n`; |
| 61 | + const dir = path.dirname(filePath); |
| 62 | + fs.mkdirSync(dir, { recursive: true }); |
| 63 | + fs.appendFileSync(filePath, entry, 'utf8'); |
| 64 | +} |
| 65 | + |
| 66 | +// ─── Context & Delegation Pipeline ────────────────────────────────────────── |
| 67 | + |
| 68 | +function loadECCContext(skillList) { |
| 69 | + const raw = skillList !== undefined ? skillList : (process.env.CLAW_SKILLS || ''); |
| 70 | + if (!raw.trim()) { |
| 71 | + return ''; |
| 72 | + } |
| 73 | + |
| 74 | + const names = raw.split(',').map(s => s.trim()).filter(Boolean); |
| 75 | + const chunks = []; |
| 76 | + |
| 77 | + for (const name of names) { |
| 78 | + const skillPath = path.join(process.cwd(), 'skills', name, 'SKILL.md'); |
| 79 | + try { |
| 80 | + const content = fs.readFileSync(skillPath, 'utf8'); |
| 81 | + chunks.push(content); |
| 82 | + } catch (_err) { |
| 83 | + // Gracefully skip missing skills |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + return chunks.join('\n\n'); |
| 88 | +} |
| 89 | + |
| 90 | +function buildPrompt(systemPrompt, history, userMessage) { |
| 91 | + const parts = []; |
| 92 | + if (systemPrompt) { |
| 93 | + parts.push('=== SYSTEM CONTEXT ===\n' + systemPrompt + '\n'); |
| 94 | + } |
| 95 | + if (history) { |
| 96 | + parts.push('=== CONVERSATION HISTORY ===\n' + history + '\n'); |
| 97 | + } |
| 98 | + parts.push('=== USER MESSAGE ===\n' + userMessage); |
| 99 | + return parts.join('\n'); |
| 100 | +} |
| 101 | + |
| 102 | +function askClaude(systemPrompt, history, userMessage) { |
| 103 | + const fullPrompt = buildPrompt(systemPrompt, history, userMessage); |
| 104 | + |
| 105 | + const result = spawnSync('claude', ['-p', fullPrompt], { |
| 106 | + encoding: 'utf8', |
| 107 | + stdio: ['pipe', 'pipe', 'pipe'], |
| 108 | + env: { ...process.env, CLAUDECODE: '' }, |
| 109 | + timeout: 300000 // 5 minute timeout |
| 110 | + }); |
| 111 | + |
| 112 | + if (result.error) { |
| 113 | + return '[Error: ' + result.error.message + ']'; |
| 114 | + } |
| 115 | + |
| 116 | + if (result.status !== 0 && result.stderr) { |
| 117 | + return '[Error: claude exited with code ' + result.status + ': ' + result.stderr.trim() + ']'; |
| 118 | + } |
| 119 | + |
| 120 | + return (result.stdout || '').trim(); |
| 121 | +} |
| 122 | + |
| 123 | +// ─── REPL Commands ────────────────────────────────────────────────────────── |
| 124 | + |
| 125 | +function handleClear(sessionPath) { |
| 126 | + fs.mkdirSync(path.dirname(sessionPath), { recursive: true }); |
| 127 | + fs.writeFileSync(sessionPath, '', 'utf8'); |
| 128 | + console.log('Session cleared.'); |
| 129 | +} |
| 130 | + |
| 131 | +function handleHistory(sessionPath) { |
| 132 | + const history = loadHistory(sessionPath); |
| 133 | + if (!history) { |
| 134 | + console.log('(no history)'); |
| 135 | + } else { |
| 136 | + console.log(history); |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +function handleSessions(dir) { |
| 141 | + const sessions = listSessions(dir); |
| 142 | + if (sessions.length === 0) { |
| 143 | + console.log('(no sessions)'); |
| 144 | + } else { |
| 145 | + console.log('Sessions:'); |
| 146 | + for (const s of sessions) { |
| 147 | + console.log(' - ' + s); |
| 148 | + } |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +function handleHelp() { |
| 153 | + console.log('NanoClaw REPL Commands:'); |
| 154 | + console.log(' /clear Clear current session history'); |
| 155 | + console.log(' /history Print full conversation history'); |
| 156 | + console.log(' /sessions List all saved sessions'); |
| 157 | + console.log(' /help Show this help message'); |
| 158 | + console.log(' exit Quit the REPL'); |
| 159 | +} |
| 160 | + |
| 161 | +// ─── Main REPL ────────────────────────────────────────────────────────────── |
| 162 | + |
| 163 | +function main() { |
| 164 | + const sessionName = process.env.CLAW_SESSION || 'default'; |
| 165 | + |
| 166 | + if (!isValidSessionName(sessionName)) { |
| 167 | + console.error('Error: Invalid session name "' + sessionName + '". Use alphanumeric characters and hyphens only.'); |
| 168 | + process.exit(1); |
| 169 | + } |
| 170 | + |
| 171 | + const clawDir = getClawDir(); |
| 172 | + fs.mkdirSync(clawDir, { recursive: true }); |
| 173 | + |
| 174 | + const sessionPath = getSessionPath(sessionName); |
| 175 | + const eccContext = loadECCContext(); |
| 176 | + |
| 177 | + const requestedSkills = (process.env.CLAW_SKILLS || '').split(',').map(s => s.trim()).filter(Boolean); |
| 178 | + const loadedCount = requestedSkills.filter(name => |
| 179 | + fs.existsSync(path.join(process.cwd(), 'skills', name, 'SKILL.md')) |
| 180 | + ).length; |
| 181 | + |
| 182 | + console.log('NanoClaw v1.0 — Session: ' + sessionName); |
| 183 | + if (loadedCount > 0) { |
| 184 | + console.log('Loaded ' + loadedCount + ' skill(s) as context.'); |
| 185 | + } |
| 186 | + console.log('Type /help for commands, exit to quit.\n'); |
| 187 | + |
| 188 | + const rl = readline.createInterface({ |
| 189 | + input: process.stdin, |
| 190 | + output: process.stdout |
| 191 | + }); |
| 192 | + |
| 193 | + const prompt = () => { |
| 194 | + rl.question('claw> ', (input) => { |
| 195 | + const line = input.trim(); |
| 196 | + |
| 197 | + if (!line) { |
| 198 | + prompt(); |
| 199 | + return; |
| 200 | + } |
| 201 | + |
| 202 | + if (line === 'exit') { |
| 203 | + console.log('Goodbye.'); |
| 204 | + rl.close(); |
| 205 | + return; |
| 206 | + } |
| 207 | + |
| 208 | + if (line === '/clear') { |
| 209 | + handleClear(sessionPath); |
| 210 | + prompt(); |
| 211 | + return; |
| 212 | + } |
| 213 | + |
| 214 | + if (line === '/history') { |
| 215 | + handleHistory(sessionPath); |
| 216 | + prompt(); |
| 217 | + return; |
| 218 | + } |
| 219 | + |
| 220 | + if (line === '/sessions') { |
| 221 | + handleSessions(); |
| 222 | + prompt(); |
| 223 | + return; |
| 224 | + } |
| 225 | + |
| 226 | + if (line === '/help') { |
| 227 | + handleHelp(); |
| 228 | + prompt(); |
| 229 | + return; |
| 230 | + } |
| 231 | + |
| 232 | + // Regular message — send to Claude |
| 233 | + const history = loadHistory(sessionPath); |
| 234 | + appendTurn(sessionPath, 'User', line); |
| 235 | + const response = askClaude(eccContext, history, line); |
| 236 | + console.log('\n' + response + '\n'); |
| 237 | + appendTurn(sessionPath, 'Assistant', response); |
| 238 | + |
| 239 | + prompt(); |
| 240 | + }); |
| 241 | + }; |
| 242 | + |
| 243 | + prompt(); |
| 244 | +} |
| 245 | + |
| 246 | +// ─── Exports & CLI Entry ──────────────────────────────────────────────────── |
| 247 | + |
| 248 | +module.exports = { |
| 249 | + getClawDir, |
| 250 | + getSessionPath, |
| 251 | + listSessions, |
| 252 | + loadHistory, |
| 253 | + appendTurn, |
| 254 | + loadECCContext, |
| 255 | + askClaude, |
| 256 | + buildPrompt, |
| 257 | + isValidSessionName, |
| 258 | + handleClear, |
| 259 | + handleHistory, |
| 260 | + handleSessions, |
| 261 | + handleHelp, |
| 262 | + main |
| 263 | +}; |
| 264 | + |
| 265 | +if (require.main === module) { |
| 266 | + main(); |
| 267 | +} |
0 commit comments