-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcoder.js
More file actions
387 lines (333 loc) · 12.9 KB
/
coder.js
File metadata and controls
387 lines (333 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import { spawn } from 'child_process';
import { existsSync, writeFileSync, mkdirSync } from 'fs';
import { join } from 'path';
import { homedir } from 'os';
import { getLogger } from './utils/logger.js';
function ensureClaudeCodeSetup() {
const logger = getLogger();
const claudeJson = join(homedir(), '.claude.json');
const claudeDir = join(homedir(), '.claude');
if (!existsSync(claudeDir)) {
mkdirSync(claudeDir, { recursive: true });
logger.info('Created ~/.claude/ directory');
}
if (!existsSync(claudeJson)) {
const defaults = {
hasCompletedOnboarding: true,
theme: 'dark',
shiftEnterKeyBindingInstalled: true,
};
writeFileSync(claudeJson, JSON.stringify(defaults, null, 2));
logger.info('Created ~/.claude.json with default settings (skipping setup wizard)');
}
}
function extractText(event) {
// Try to find text in various possible event structures
// Format 1: { type: "message", role: "assistant", content: [{ type: "text", text: "..." }] }
// Format 2: { type: "assistant", message: { content: [{ type: "text", text: "..." }] } }
// Format 3: { type: "assistant", content: [{ type: "text", text: "..." }] }
const contentSources = [
event.content,
event.message?.content,
];
for (const content of contentSources) {
if (Array.isArray(content)) {
const texts = content
.filter((b) => b.type === 'text' && b.text?.trim())
.map((b) => b.text.trim());
if (texts.length > 0) return texts.join('\n');
}
}
// Direct text field
if (event.text?.trim()) return event.text.trim();
if (event.result?.trim()) return event.result.trim();
return null;
}
function extractToolUse(event) {
// Format 1: { type: "tool_use", name: "Bash", input: { command: "..." } }
// Format 2: content block with type tool_use
if (event.name && event.input) {
const input = event.input;
const summary = input.command || input.file_path || input.pattern || input.query || input.content?.slice(0, 80) || JSON.stringify(input).slice(0, 100);
return { name: event.name, summary: String(summary).slice(0, 150) };
}
// Check inside content array
const content = event.content || event.message?.content;
if (Array.isArray(content)) {
for (const block of content) {
if (block.type === 'tool_use' && block.name) {
const input = block.input || {};
const summary = input.command || input.file_path || input.pattern || input.query || JSON.stringify(input).slice(0, 100);
return { name: block.name, summary: String(summary).slice(0, 150) };
}
}
}
return null;
}
function processEvent(line, onOutput, logger) {
let event;
try {
event = JSON.parse(line);
} catch {
// Not JSON — send raw text if it looks meaningful
if (line.trim() && line.length > 3 && onOutput) {
logger.info(`Claude Code (raw): ${line.slice(0, 200)}`);
onOutput(`▹ ${line.trim()}`).catch(() => {});
}
return null;
}
const type = event.type || '';
// Assistant thinking/text
if (type === 'message' || type === 'assistant') {
const text = extractText(event);
if (text) {
logger.info(`Claude Code: ${text.slice(0, 200)}`);
if (onOutput) onOutput(`💬 *Claude Code:*\n${text}`).catch(() => {});
}
// Also check for tool_use inside the same message
const tool = extractToolUse(event);
if (tool) {
logger.info(`Claude Code tool: ${tool.name}: ${tool.summary}`);
if (onOutput) onOutput(`▸ ${tool.name}: ${tool.summary}`).catch(() => {});
}
return event;
}
// Standalone tool use event
if (type === 'tool_use') {
const tool = extractToolUse(event);
if (tool) {
logger.info(`Claude Code tool: ${tool.name}: ${tool.summary}`);
if (onOutput) onOutput(`▸ ${tool.name}: ${tool.summary}`).catch(() => {});
}
return event;
}
// Result / completion
if (type === 'result') {
const status = event.status || event.subtype || 'done';
const duration = event.duration_ms ? ` in ${(event.duration_ms / 1000).toFixed(1)}s` : '';
const cost = event.cost_usd ? ` ($${event.cost_usd.toFixed(3)})` : '';
logger.info(`Claude Code finished: ${status}${duration}${cost}`);
if (onOutput) onOutput(`▪ done (${status}${duration}${cost})`).catch(() => {});
return event;
}
// Log any other event type for debugging
logger.debug(`Claude Code event [${type}]: ${JSON.stringify(event).slice(0, 300)}`);
return event;
}
export class ClaudeCodeSpawner {
constructor(config) {
this.config = config;
this.maxTurns = config.claude_code?.max_turns || 50;
// Default 24 hours — background workers can legitimately run for extended periods.
// Stuck process detection is handled separately by idle/loop heuristics.
this.timeout = (config.claude_code?.timeout_seconds || 86400) * 1000;
}
_buildSpawnEnv() {
const authMode = this.config.claude_code?.auth_mode || 'system';
const env = { ...process.env, IS_SANDBOX: '1' };
if (authMode === 'api_key') {
const key = this.config.claude_code?.api_key || process.env.CLAUDE_CODE_API_KEY;
if (key) {
env.ANTHROPIC_API_KEY = key;
delete env.CLAUDE_CODE_OAUTH_TOKEN;
}
} else if (authMode === 'oauth_token') {
const token = this.config.claude_code?.oauth_token || process.env.CLAUDE_CODE_OAUTH_TOKEN;
if (token) {
env.CLAUDE_CODE_OAUTH_TOKEN = token;
// Remove ANTHROPIC_API_KEY so it doesn't override subscription auth
delete env.ANTHROPIC_API_KEY;
}
}
// authMode === 'system' — pass env as-is
// FIX: Ensure system auth uses local credentials, not the bot's API key
if (authMode === 'system') {
delete env.ANTHROPIC_API_KEY;
}
return env;
}
async run({ workingDirectory, prompt, maxTurns, timeoutMs, onOutput, signal }) {
const logger = getLogger();
const turns = maxTurns || this.maxTurns;
const effectiveTimeout = timeoutMs || this.timeout;
ensureClaudeCodeSetup();
// Read model dynamically from config (supports hot-reload via switchClaudeCodeModel)
const model = this.config.claude_code?.model || null;
const args = [
'-p', prompt,
'--max-turns', String(turns),
'--output-format', 'stream-json',
'--verbose',
'--dangerously-skip-permissions',
];
if (model) {
args.push('--model', model);
}
const cmd = `claude ${args.map((a) => a.includes(' ') ? `"${a}"` : a).join(' ')}`;
logger.info(`Spawning: ${cmd.slice(0, 300)}`);
logger.info(`CWD: ${workingDirectory} | Timeout: ${effectiveTimeout / 1000}s | Max turns: ${turns}`);
// --- Smart output: consolidate tool activity into one editable message ---
let statusMsgId = null;
let activityLines = [];
let flushTimer = null;
const MAX_VISIBLE = 15;
const buildStatusText = (finalState = null) => {
const visible = activityLines.slice(-MAX_VISIBLE);
const countInfo = activityLines.length > MAX_VISIBLE
? `\n_... ${activityLines.length} operations total_\n`
: '';
if (finalState === 'done') {
return `░▒▓ *Claude Code Done* — ${activityLines.length} ops\n${countInfo}\n${visible.join('\n')}`;
}
if (finalState === 'error') {
return `░▒▓ *Claude Code Failed* — ${activityLines.length} ops\n${countInfo}\n${visible.join('\n')}`;
}
return `░▒▓ *Claude Code Working...*\n${countInfo}\n${visible.join('\n')}`;
};
const flushStatus = async () => {
flushTimer = null;
if (!onOutput || activityLines.length === 0) return;
try {
if (statusMsgId) {
await onOutput(buildStatusText(), { editMessageId: statusMsgId });
} else {
statusMsgId = await onOutput(buildStatusText());
}
} catch (err) {
logger.debug(`flushStatus failed: ${err.message}`);
}
};
const addActivity = (line) => {
activityLines.push(line);
if (!statusMsgId && !flushTimer) {
// First activity — create the status message immediately
flushStatus();
} else if (!flushTimer) {
// Throttle subsequent edits to avoid Telegram rate limits
flushTimer = setTimeout(flushStatus, 1000);
}
};
const smartOutput = onOutput ? async (text) => {
// Tool calls, raw output, warnings, starting → accumulate in status message
if (text.startsWith('▸') || text.startsWith('▹') || text.startsWith('▪')) {
addActivity(text);
return;
}
// Everything else (💬 text, errors, timeout) → new message
await onOutput(text);
} : null;
if (smartOutput) smartOutput(`▸ Starting Claude Code...`).catch(() => {});
return new Promise((resolve, reject) => {
const child = spawn('claude', args, {
cwd: workingDirectory,
env: this._buildSpawnEnv(),
stdio: ['ignore', 'pipe', 'pipe'],
});
// Wire abort signal to kill the child process
let abortHandler = null;
if (signal) {
if (signal.aborted) {
child.kill('SIGTERM');
} else {
abortHandler = () => {
logger.info('Claude Code: abort signal received — killing child process');
child.kill('SIGTERM');
};
signal.addEventListener('abort', abortHandler, { once: true });
}
}
let fullOutput = '';
let stderr = '';
let buffer = '';
let resultText = '';
child.stdout.on('data', (data) => {
buffer += data.toString();
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) continue;
fullOutput += trimmed + '\n';
try {
const event = JSON.parse(trimmed);
if (event.type === 'result') {
resultText = event.result || resultText;
}
} catch {}
processEvent(trimmed, smartOutput, logger);
}
});
child.stderr.on('data', (data) => {
const chunk = data.toString().trim();
stderr += chunk + '\n';
logger.warn(`Claude Code stderr: ${chunk.slice(0, 300)}`);
if (smartOutput && chunk) {
smartOutput(`▹ ${chunk.slice(0, 300)}`).catch(() => {});
}
});
const timer = setTimeout(() => {
logger.warn(`Claude Code timed out after ${effectiveTimeout / 1000}s — sending SIGTERM`);
child.kill('SIGTERM');
if (smartOutput) smartOutput(`▸ Claude Code timed out after ${effectiveTimeout / 1000}s`).catch(() => {});
// Give it 10s to exit gracefully after SIGTERM, then force-kill
setTimeout(() => {
if (!child.killed) {
logger.warn('Claude Code did not exit after SIGTERM — sending SIGKILL');
child.kill('SIGKILL');
}
}, 10_000);
reject(new Error(`Claude Code timed out after ${effectiveTimeout / 1000}s`));
}, effectiveTimeout);
child.on('close', async (code) => {
clearTimeout(timer);
if (abortHandler && signal) signal.removeEventListener('abort', abortHandler);
if (buffer.trim()) {
fullOutput += buffer.trim();
try {
const event = JSON.parse(buffer.trim());
if (event.type === 'result') {
resultText = event.result || resultText;
}
} catch {}
processEvent(buffer.trim(), smartOutput, logger);
}
// Flush any pending status edits
if (flushTimer) {
clearTimeout(flushTimer);
flushTimer = null;
}
await flushStatus();
// Final status message update — show done/failed state
if (statusMsgId && onOutput) {
const finalState = code === 0 ? 'done' : 'error';
try {
await onOutput(buildStatusText(finalState), { editMessageId: statusMsgId });
} catch (err) {
logger.debug(`Final status update failed: ${err.message}`);
}
}
logger.info(`Claude Code exited with code ${code} | stdout: ${fullOutput.length} chars | stderr: ${stderr.length} chars`);
if (code !== 0) {
const errMsg = stderr.trim() || fullOutput.trim() || `exited with code ${code}`;
logger.error(`Claude Code failed: ${errMsg.slice(0, 500)}`);
reject(new Error(`Claude Code exited with code ${code}: ${errMsg.slice(0, 500)}`));
} else {
resolve({
output: resultText || fullOutput.trim(),
stderr: stderr.trim(),
exitCode: code,
});
}
});
child.on('error', (err) => {
clearTimeout(timer);
if (abortHandler && signal) signal.removeEventListener('abort', abortHandler);
if (err.code === 'ENOENT') {
reject(new Error('Claude Code CLI not found. Install with: npm i -g @anthropic-ai/claude-code'));
} else {
reject(err);
}
});
});
}
}