-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathtask_loop.py
More file actions
executable file
·415 lines (360 loc) · 13.6 KB
/
task_loop.py
File metadata and controls
executable file
·415 lines (360 loc) · 13.6 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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#!/usr/bin/env python3
"""
Task Loop - Fetch tasks from AGFS QueueFS and execute with Claude Code
"""
import argparse
import json
import subprocess
import sys
import time
from datetime import datetime
from typing import Any, Dict, Optional
from pyagfs import AGFSClient
class TaskQueue:
"""AGFS QueueFS task queue client"""
def __init__(
self,
queue_path,
agfs_api_baseurl: Optional[str] = "http://localhost:8080",
):
"""
Initialize task queue client
Args:
queue_path: QueueFS mount path
agfs_api_baseurl: AGFS API server URL (optional)
"""
self.queue_path = queue_path
self.agfs_api_baseurl = agfs_api_baseurl
self.dequeue_path = f"{queue_path}/dequeue"
self.size_path = f"{queue_path}/size"
self.peek_path = f"{queue_path}/peek"
self.client = AGFSClient(agfs_api_baseurl)
def ensure_queue_exists(self) -> bool:
"""
Ensure queue directory exists, create if not
Returns:
True if queue exists or was created successfully, False otherwise
"""
try:
# Try to create the queue directory
# QueueFS requires explicit mkdir to create queues
self.client.mkdir(self.queue_path)
print(f"Successfully created queue: {self.queue_path}", file=sys.stderr)
return True
except Exception as e:
# If mkdir fails, check if it's because queue already exists
error_msg = str(e).lower()
if "exists" in error_msg or "already" in error_msg:
# Queue already exists, this is fine
return True
else:
# Other error occurred
print(f"Failed to create queue: {self.queue_path}: {e}", file=sys.stderr)
return False
def get_queue_size(self) -> Optional[int]:
"""
Get queue size
Returns:
Number of messages in queue, None if failed
"""
try:
content = self.client.cat(self.size_path)
output = content.decode('utf-8').strip()
return int(output)
except ValueError:
print(f"Warning: Cannot parse queue size: {output}", file=sys.stderr)
return None
except Exception:
return None
def peek_task(self) -> Optional[Dict[str, Any]]:
"""
Peek at next task without removing it
Returns:
Task data dictionary, None if failed
"""
try:
content = self.client.cat(self.peek_path)
output = content.decode('utf-8')
return json.loads(output)
except json.JSONDecodeError:
print(f"Warning: Cannot parse JSON: {output}", file=sys.stderr)
return None
except Exception:
return None
def dequeue_task(self) -> Optional[Dict[str, Any]]:
"""
Get a task from queue (removes it)
Returns:
Task data dictionary with format: {"id": "...", "data": "...", "timestamp": "..."}
Returns None if queue is empty or operation failed
"""
try:
content = self.client.cat(self.dequeue_path)
output = content.decode('utf-8')
return json.loads(output)
except json.JSONDecodeError:
print(f"Warning: Cannot parse JSON: {output}", file=sys.stderr)
return None
except Exception:
return None
class ClaudeCodeExecutor:
"""Execute tasks using Claude Code in headless mode"""
def __init__(
self,
timeout: int = 600,
allowed_tools: Optional[list[str]] = None,
name: str = "",
):
"""
Initialize Claude Code executor
Args:
timeout: Maximum execution time in seconds (default: 600)
allowed_tools: List of allowed tools (None = all tools allowed)
"""
self.timeout = timeout
self.allowed_tools = allowed_tools
self.agent_name = name
def execute_task(
self, task_prompt: str, working_dir: Optional[str] = None
) -> Dict[str, Any]:
"""
Execute a task using Claude Code in headless mode
Args:
task_prompt: The task prompt to send to Claude Code
working_dir: Working directory for Claude Code (optional)
Returns:
Dictionary with execution results including:
- success: bool
- result: str (Claude's response)
- error: str (error message if failed)
- duration_ms: int
- total_cost_usd: float
- session_id: str
"""
cmd = [
"claude",
"-p",
task_prompt,
"--output-format",
"json",
"--permission-mode=bypassPermissions",
]
# Add allowed tools if specified
if self.allowed_tools:
cmd.extend(["--allowedTools", ",".join(self.allowed_tools)])
try:
print(f"\n[Executing Claude Code with streaming output...]")
print("-" * 80)
start_time = time.time()
# Use Popen to enable streaming output
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
cwd=working_dir,
)
# Stream stderr to console in real-time (Claude Code outputs logs to stderr)
stdout_lines = []
stderr_lines = []
try:
# Read stderr line by line and print to console
while True:
stderr_line = process.stderr.readline()
if stderr_line:
print(stderr_line.rstrip(), file=sys.stderr)
stderr_lines.append(stderr_line)
# Check if process has finished
if process.poll() is not None:
# Read any remaining output
remaining_stderr = process.stderr.read()
if remaining_stderr:
print(remaining_stderr.rstrip(), file=sys.stderr)
stderr_lines.append(remaining_stderr)
break
# Read all stdout (JSON output)
stdout_data = process.stdout.read()
stdout_lines.append(stdout_data)
except KeyboardInterrupt:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
raise
execution_time = (time.time() - start_time) * 1000 # Convert to ms
print("-" * 80)
stdout_output = ''.join(stdout_lines)
stderr_output = ''.join(stderr_lines)
if process.returncode == 0:
try:
output = json.loads(stdout_output)
return {
"success": True,
"result": output.get("result", ""),
"error": None,
"duration_ms": output.get("duration_ms", execution_time),
"total_cost_usd": output.get("total_cost_usd", 0.0),
"session_id": output.get("session_id", ""),
}
except json.JSONDecodeError as e:
return {
"success": False,
"result": stdout_output,
"error": f"Failed to parse JSON output: {e}",
"duration_ms": execution_time,
"total_cost_usd": 0.0,
"session_id": "",
}
else:
return {
"success": False,
"result": "",
"error": f"Claude Code exited with code {process.returncode}: {stderr_output}",
"duration_ms": execution_time,
"total_cost_usd": 0.0,
"session_id": "",
}
except FileNotFoundError:
return {
"success": False,
"result": "",
"error": "'claude' command not found. Please ensure Claude Code is installed.",
"duration_ms": 0,
"total_cost_usd": 0.0,
"session_id": "",
}
except Exception as e:
return {
"success": False,
"result": "",
"error": f"Unexpected error: {e}",
"duration_ms": 0,
"total_cost_usd": 0.0,
"session_id": "",
}
def main():
"""Main function: loop to fetch tasks and output to console"""
# Parse command line arguments
parser = argparse.ArgumentParser(
description="Fetch tasks from AGFS QueueFS and execute with Claude Code"
)
parser.add_argument(
"--queue-path",
type=str,
default="/queuefs/agent",
help="QueueFS mount path (default: /queuefs/agent)",
)
parser.add_argument(
"--api-url", type=str, default="http://localhost:8080", help="AGFS API server URL (default: http://localhost:8080)"
)
parser.add_argument(
"--poll-interval",
type=int,
default=2,
help="Poll interval in seconds when queue is empty (default: 2)",
)
parser.add_argument(
"--claude-timeout",
type=int,
default=600,
help="Claude Code execution timeout in seconds (default: 600)",
)
parser.add_argument(
"--allowed-tools",
type=str,
default=None,
help="Comma-separated list of allowed tools for Claude Code (default: all tools)",
)
parser.add_argument(
"--working-dir",
type=str,
default=None,
help="Working directory for Claude Code execution (default: current directory)",
)
parser.add_argument("--name", type=str, default=None, help="agent name")
args = parser.parse_args()
# Parse allowed tools if specified
allowed_tools = None
if args.allowed_tools:
allowed_tools = [tool.strip() for tool in args.allowed_tools.split(",")]
# Create task queue client
queue = TaskQueue(queue_path=args.queue_path, agfs_api_baseurl=args.api_url)
# Ensure queue exists before starting
if not queue.ensure_queue_exists():
print(f"Error: Failed to ensure queue exists at {queue.queue_path}", file=sys.stderr)
sys.exit(1)
# Create Claude Code executor
executor = ClaudeCodeExecutor(
timeout=args.claude_timeout, allowed_tools=allowed_tools
)
print("=== AGFS Task Loop with Claude Code ===")
print(f"Monitoring queue: {queue.queue_path}")
if args.api_url:
print(f"AGFS API URL: {args.api_url}")
print(f"Poll interval: {args.poll_interval}s")
print(f"Claude timeout: {args.claude_timeout}s")
if allowed_tools:
print(f"Allowed tools: {', '.join(allowed_tools)}")
if args.working_dir:
print(f"Working directory: {args.working_dir}")
print("Press Ctrl+C to exit\n")
try:
while True:
# Check queue size
size = queue.get_queue_size()
if size is not None and size > 0:
print(f"[Queue size: {size}]")
# Fetch task
task = queue.dequeue_task()
if task:
task_id = task.get("id", "N/A")
task_data = task.get("data", "")
task_timestamp = task.get("timestamp", "N/A")
print("\n" + "=" * 80)
print(f"📥 NEW TASK RECEIVED")
print("=" * 80)
print(f"Task ID: {task_id}")
print(f"Timestamp: {task_timestamp}")
print(f"Prompt: {task_data}")
print("=" * 80)
# Build complete prompt with task information and result upload instruction
full_prompt = f"""Task ID: {task_id}
Task: {task_data}
Your name is: {args.name}"""
# Execute task with Claude Code
result = executor.execute_task(
task_prompt=full_prompt, working_dir=args.working_dir
)
# Display results
print("\n" + "=" * 80)
print(f"📤 TASK EXECUTION RESULT")
print("=" * 80)
print(f"Task ID: {task_id}")
print(
f"Status: {'✅ SUCCESS' if result['success'] else '❌ FAILED'}"
)
print(f"Duration: {result['duration_ms']:.0f}ms")
if result["total_cost_usd"] > 0:
print(f"Cost: ${result['total_cost_usd']:.4f}")
if result["session_id"]:
print(f"Session ID: {result['session_id']}")
print("-" * 80)
if result["success"]:
print("Result:")
print(result["result"])
else:
print(f"Error: {result['error']}")
print("=" * 80)
print()
else:
# Queue is empty, wait before retrying
print(
f"[{datetime.now().strftime('%H:%M:%S')}] Queue is empty, waiting for new tasks..."
)
time.sleep(args.poll_interval)
except KeyboardInterrupt:
print("\n\n⏹️ Program stopped by user")
sys.exit(0)
if __name__ == "__main__":
main()