-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude-code-executor.ts
More file actions
182 lines (156 loc) · 5.76 KB
/
claude-code-executor.ts
File metadata and controls
182 lines (156 loc) · 5.76 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
import { spawn } from 'node:child_process';
import { createInterface } from 'node:readline';
interface StdioMcpServerConfig {
type?: 'stdio';
command: string;
args: string[];
env?: Record<string, string>;
}
interface HttpMcpServerConfig {
type: 'http';
url: string;
headers?: Record<string, string>;
}
type McpServerConfig = StdioMcpServerConfig | HttpMcpServerConfig;
export interface ClaudeCodeOptions {
workspaceDir?: string;
model?: string;
mcpServers?: Record<string, McpServerConfig>;
systemPrompt?: string;
allowedTools?: string[];
timeoutMs?: number;
}
export interface ExecuteResult {
response: string;
sessionId?: string;
}
interface StreamMessage {
type: string;
subtype?: string;
result?: string;
content?: unknown;
session_id?: string;
[key: string]: unknown;
}
/**
* Executes Claude Code CLI as subprocess with streaming NDJSON output.
* Sets cwd to workspace directory so Claude Code loads CLAUDE.md and has fs access.
*/
export class ClaudeCodeExecutor {
constructor(private options: ClaudeCodeOptions) {}
/**
* Send a prompt to Claude Code and return the final response text.
* Handles the full agent loop internally (tool use, etc).
* @param sessionId - Optional session ID to resume a previous conversation
*/
async execute(prompt: string, sessionId?: string): Promise<ExecuteResult> {
const args = this.buildArgs(prompt, sessionId);
const startTime = Date.now();
const cwd = this.options.workspaceDir || process.cwd();
console.log(`[claude-code] Spawning subprocess in ${cwd}${sessionId ? ` (resuming session ${sessionId})` : ''}`);
console.log(`[claude-code] Prompt: "${prompt.substring(0, 100)}${prompt.length > 100 ? '...' : ''}"`);
return new Promise((resolve, reject) => {
const proc = spawn('claude', args, {
cwd,
env: {
...process.env,
CLAUDE_CODE_ENTRYPOINT: 'sdk-agentloop',
},
stdio: ['pipe', 'pipe', 'pipe'],
});
// Close stdin immediately - Claude Code waits for EOF before processing --print prompt
proc.stdin.end();
let result = '';
let capturedSessionId: string | undefined;
const stderrChunks: string[] = [];
let timeoutId: ReturnType<typeof setTimeout> | undefined;
let timedOut = false;
if (this.options.timeoutMs) {
timeoutId = setTimeout(() => {
timedOut = true;
console.warn(`[claude-code] Timeout after ${this.options.timeoutMs}ms, killing process`);
proc.kill('SIGTERM');
}, this.options.timeoutMs);
}
const rl = createInterface({ input: proc.stdout });
rl.on('line', (line) => {
if (!line.trim()) return;
try {
const msg: StreamMessage = JSON.parse(line);
if (msg.session_id) {
capturedSessionId = msg.session_id;
}
this.handleMessage(msg, (text) => { result = text; });
} catch {
// Ignore non-JSON lines (e.g., npm output)
}
});
proc.stderr.on('data', (chunk) => {
stderrChunks.push(chunk.toString());
});
proc.on('close', (code) => {
if (timeoutId) clearTimeout(timeoutId);
const elapsed = Date.now() - startTime;
if (timedOut) {
console.error(`[claude-code] Timed out after ${elapsed}ms`);
reject(new Error(`Claude Code timed out after ${this.options.timeoutMs}ms`));
return;
}
if (code !== 0 && code !== null) {
const stderr = stderrChunks.join('');
console.error(`[claude-code] Exited with code ${code} after ${elapsed}ms: ${stderr}`);
reject(new Error(`Claude Code exited with code ${code}: ${stderr}`));
return;
}
console.log(`[claude-code] Completed in ${elapsed}ms (response: ${result.length} chars, sessionId: ${capturedSessionId || 'none'})`);
resolve({ response: result, sessionId: capturedSessionId });
});
proc.on('error', (err) => {
if (timeoutId) clearTimeout(timeoutId);
console.error(`[claude-code] Failed to spawn:`, err);
reject(new Error(`Failed to spawn Claude Code: ${err.message}`));
});
});
}
private buildArgs(prompt: string, sessionId?: string): string[] {
const args: string[] = [
'--verbose',
'--output-format', 'stream-json',
'--print', prompt,
];
if (sessionId) {
// Resuming existing session - it already has system prompt, model, tools configured
args.push('--resume', sessionId);
} else {
// New session - pass all configuration
if (this.options.model) {
args.push('--model', this.options.model);
}
if (this.options.systemPrompt) {
args.push('--system-prompt', this.options.systemPrompt);
}
if (this.options.allowedTools?.length) {
args.push('--allowedTools', this.options.allowedTools.join(','));
}
if (this.options.mcpServers && Object.keys(this.options.mcpServers).length > 0) {
args.push('--mcp-config', JSON.stringify({ mcpServers: this.options.mcpServers }));
}
}
return args;
}
private handleMessage(msg: StreamMessage, onResult: (text: string) => void): void {
// The final result comes in a message with type 'result' or in assistant messages
if (msg.type === 'result' && typeof msg.result === 'string') {
onResult(msg.result);
}
// Also check for assistant text blocks
if (msg.type === 'assistant' && Array.isArray(msg.content)) {
const textBlocks = msg.content
.filter((b: unknown) => typeof b === 'object' && b !== null && (b as { type: string }).type === 'text')
.map((b: unknown) => (b as { text: string }).text);
if (textBlocks.length > 0) {
onResult(textBlocks.join('\n'));
}
}
}
}