forked from Ishabdullah/Codey-v2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodey2
More file actions
executable file
·430 lines (362 loc) · 11.5 KB
/
codey2
File metadata and controls
executable file
·430 lines (362 loc) · 11.5 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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#!/usr/bin/env bash
#
# codey2 - Codey-v2 CLI Client
#
# If daemon is running, connects via Unix socket.
# Otherwise, spawns direct mode.
#
CODEY_V2_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DAEMON_DIR="$HOME/.codey-v2"
PID_FILE="$DAEMON_DIR/codey-v2.pid"
SOCKET_FILE="$DAEMON_DIR/codey-v2.sock"
# Ensure daemon directory exists
mkdir -p "$DAEMON_DIR"
# Check if daemon is running
is_daemon_running() {
if [ ! -f "$PID_FILE" ]; then
return 1
fi
PID=$(cat "$PID_FILE" 2>/dev/null || echo "")
if [ -z "$PID" ]; then
return 1
fi
# Check if process exists
if ! kill -0 "$PID" 2>/dev/null; then
return 1
fi
# Check if socket exists (use -S for socket, not -f)
if [ ! -S "$SOCKET_FILE" ]; then
return 1
fi
return 0
}
# Send command to daemon via socket
send_to_daemon() {
local prompt="$1"
local yolo="$2"
TMPSCRIPT="$(mktemp "$DAEMON_DIR/socket_XXXX.py")"
cat > "$TMPSCRIPT" << PYEOF
import sys
import json
import socket
SOCKET_FILE = "$SOCKET_FILE"
def send_command(cmd, data):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(30.0)
try:
sock.connect(str(SOCKET_FILE))
request = {"cmd": cmd, "data": data}
sock.sendall(json.dumps(request).encode('utf-8'))
response_data = b""
while True:
chunk = sock.recv(65536)
if not chunk:
break
response_data += chunk
if not response_data:
print("[ERROR] No response from daemon", file=sys.stderr)
sys.exit(1)
response = json.loads(response_data.decode('utf-8'))
if response.get("status") == "error":
print(f"[ERROR] {response.get('message', 'Unknown error')}", file=sys.stderr)
sys.exit(1)
return response
except socket.timeout:
print("[ERROR] Connection timed out. Daemon may be busy.", file=sys.stderr)
sys.exit(1)
except socket.error as e:
print(f"[ERROR] Socket error: {e}", file=sys.stderr)
sys.exit(1)
except json.JSONDecodeError as e:
print(f"[ERROR] Invalid response from daemon: {e}", file=sys.stderr)
sys.exit(1)
finally:
try:
sock.close()
except:
pass
# Send the prompt to daemon
result = send_command("command", {"prompt": """$prompt""", "yolo": $yolo})
print(json.dumps(result, indent=2))
PYEOF
python3 "$TMPSCRIPT"
rm -f "$TMPSCRIPT"
}
# Check for daemon-specific commands
if [ "$1" = "--daemon" ]; then
# Pass through to main.py with daemon flag
TMPSCRIPT="$(mktemp "$DAEMON_DIR/run_XXXX.py")"
cat > "$TMPSCRIPT" << PYEOF
import sys
sys.path.insert(0, '$CODEY_V2_DIR')
from main import main
main()
PYEOF
python3 "$TMPSCRIPT" "\$@"
rm -f "$TMPSCRIPT"
exit $?
fi
# Check for status command
if [ "$1" = "status" ]; then
if is_daemon_running; then
TMPSCRIPT="$(mktemp "$DAEMON_DIR/status_XXXX.py")"
cat > "$TMPSCRIPT" << PYEOF
import sys
import json
import socket
SOCKET_FILE = "$SOCKET_FILE"
def send_command(cmd, data):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(5.0)
try:
sock.connect(str(SOCKET_FILE))
request = {"cmd": cmd, "data": data}
sock.sendall(json.dumps(request).encode('utf-8'))
response_data = b""
while True:
chunk = sock.recv(65536)
if not chunk:
break
response_data += chunk
if not response_data:
print("[ERROR] No response from daemon", file=sys.stderr)
sys.exit(1)
response = json.loads(response_data.decode('utf-8'))
if response.get("status") == "error":
print(f"[ERROR] {response.get('message', 'Unknown error')}", file=sys.stderr)
sys.exit(1)
return response
except socket.timeout:
print("[ERROR] Connection timed out", file=sys.stderr)
sys.exit(1)
except socket.error as e:
print(f"[ERROR] Socket error: {e}", file=sys.stderr)
sys.exit(1)
except json.JSONDecodeError as e:
print(f"[ERROR] Invalid response: {e}", file=sys.stderr)
sys.exit(1)
finally:
try:
sock.close()
except:
pass
try:
# Get health and status
health = send_command("health", {})
# Format output
print("Codey-v2 Daemon Status")
print("=" * 40)
print(f"PID: {health.get('pid', 'N/A')}")
print(f"Status: Running")
print(f"Uptime: {health.get('uptime_seconds', 0)} seconds")
print(f"Memory: {health.get('memory_mb', 0)} MB")
print()
print("Task Queue:")
tasks = health.get('tasks', {})
print(f" Pending: {tasks.get('pending', 0)}")
stuck = tasks.get('stuck', [])
if stuck:
print(f" Stuck: {', '.join(map(str, stuck))}")
else:
print(f" Stuck: None")
print()
print(f"Recent Actions: {health.get('recent_actions', 0)} logged")
print()
print(f"State Database: $DAEMON_DIR/state.db")
except SystemExit:
raise
except Exception as e:
print(f"[ERROR] Failed to get status: {e}", file=sys.stderr)
sys.exit(1)
PYEOF
python3 "$TMPSCRIPT"
EXIT_CODE=$?
rm -f "$TMPSCRIPT"
exit $EXIT_CODE
else
echo "Codey-v2 daemon is not running"
echo "Use 'codeyd2 start' to start the daemon"
exit 1
fi
fi
# Check for task command
if [ "$1" = "task" ]; then
if ! is_daemon_running; then
echo "Codey-v2 daemon is not running"
exit 1
fi
shift # Remove 'task' from args
if [ $# -eq 0 ]; then
echo "Usage: codey2 task <id>|list"
echo " codey2 task <id> - Get task by ID"
echo " codey2 task list - List recent tasks"
exit 1
fi
TMPSCRIPT="$(mktemp "$DAEMON_DIR/task_XXXX.py")"
if [ "$1" = "list" ]; then
cat > "$TMPSCRIPT" << PYEOF
import sys
import json
import socket
SOCKET_FILE = "$SOCKET_FILE"
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(10.0)
sock.connect(str(SOCKET_FILE))
request = {"cmd": "task", "data": {"limit": 20}}
sock.sendall(json.dumps(request).encode('utf-8'))
response_data = b""
while True:
chunk = sock.recv(65536)
if not chunk:
break
response_data += chunk
sock.close()
result = json.loads(response_data.decode('utf-8'))
if result.get("status") == "ok":
print("Tasks:")
for t in result.get("tasks", []):
status_icon = {"done": "✓", "running": "⟳", "pending": "○", "failed": "✗"}.get(t["status"], "?")
desc = t["description"][:50].replace("\n", " ")
print(f" [{t['id']}] {status_icon} {desc}")
else:
print(f"Error: {result.get('message', 'Unknown error')}", file=sys.stderr)
sys.exit(1)
PYEOF
else
TASK_ID="$1"
cat > "$TMPSCRIPT" << PYEOF
import sys
import json
import socket
SOCKET_FILE = "$SOCKET_FILE"
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(10.0)
sock.connect(str(SOCKET_FILE))
request = {"cmd": "task", "data": {"id": $TASK_ID}}
sock.sendall(json.dumps(request).encode('utf-8'))
response_data = b""
while True:
chunk = sock.recv(65536)
if not chunk:
break
response_data += chunk
sock.close()
result = json.loads(response_data.decode('utf-8'))
if result.get("status") == "ok":
t = result.get("task", {})
status_icon = {"done": "✓", "running": "⟳", "pending": "○", "failed": "✗"}.get(t["status"], "?")
print(f"Task {t['id']}: {t['description']}")
print(f"Status: {status_icon} {t['status']}")
if t.get("result"):
print(f"Result: {t['result'][:200]}")
if t.get("created_at"):
import datetime
print(f"Created: {datetime.datetime.fromtimestamp(t['created_at'])}")
if t.get("completed_at"):
print(f"Completed: {datetime.datetime.fromtimestamp(t['completed_at'])}")
else:
print(f"Error: {result.get('message', 'Unknown error')}", file=sys.stderr)
sys.exit(1)
PYEOF
fi
python3 "$TMPSCRIPT"
rm -f "$TMPSCRIPT"
exit $?
fi
# Check for cancel command
if [ "$1" = "cancel" ]; then
if ! is_daemon_running; then
echo "Codey-v2 daemon is not running"
exit 1
fi
shift # Remove 'cancel' from args
if [ $# -eq 0 ]; then
echo "Usage: codey2 cancel <task_id>"
exit 1
fi
TASK_ID="$1"
TMPSCRIPT="$(mktemp "$DAEMON_DIR/cancel_XXXX.py")"
cat > "$TMPSCRIPT" << PYEOF
import sys
import json
import socket
SOCKET_FILE = "$SOCKET_FILE"
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(10.0)
sock.connect(str(SOCKET_FILE))
request = {"cmd": "cancel", "data": {"id": $TASK_ID}}
sock.sendall(json.dumps(request).encode('utf-8'))
response_data = b""
while True:
chunk = sock.recv(65536)
if not chunk:
break
response_data += chunk
sock.close()
result = json.loads(response_data.decode('utf-8'))
if result.get("status") == "ok":
print(result.get("message", "Cancelled"))
else:
print(f"Error: {result.get('message', 'Unknown error')}", file=sys.stderr)
sys.exit(1)
PYEOF
python3 "$TMPSCRIPT"
rm -f "$TMPSCRIPT"
exit $?
fi
# Detect --bg / --background flag to opt into daemon background queuing.
# All other prompts always run interactively via direct Python (even when
# the daemon is running) so the user gets a real-time streamed response.
BG_MODE="false"
for arg in "$@"; do
if [ "$arg" = "--bg" ] || [ "$arg" = "--background" ]; then
BG_MODE="true"
break
fi
done
if [ "$BG_MODE" = "true" ]; then
# Background mode: queue task in the running daemon
if ! is_daemon_running; then
echo "Error: Daemon is not running. Start it with: codeyd2 start"
exit 1
fi
YOLO="False"
PROMPT_PARTS=()
for arg in "$@"; do
if [ "$arg" = "--yolo" ]; then
YOLO="True"
elif [ "$arg" != "--bg" ] && [ "$arg" != "--background" ]; then
PROMPT_PARTS+=("$arg")
fi
done
send_to_daemon "${PROMPT_PARTS[*]}" "$YOLO"
else
# ── Start GUI server if not already running ────────────────────────────
GUI_PORT="${CODEY_GUI_PORT:-8888}"
GUI_PID_FILE="$DAEMON_DIR/gui-server.pid"
GUI_STARTED_HERE="false"
if [ -f "$GUI_PID_FILE" ] && kill -0 "$(cat "$GUI_PID_FILE" 2>/dev/null)" 2>/dev/null; then
echo " GUI → http://localhost:${GUI_PORT} (already running)"
elif [ -f "$CODEY_V2_DIR/gui/server.py" ]; then
export PYTHONUNBUFFERED=1
export CODEY_GUI_PORT="$GUI_PORT"
python3 "$CODEY_V2_DIR/gui/server.py" &
echo $! > "$GUI_PID_FILE"
GUI_STARTED_HERE="true"
echo " GUI → http://localhost:${GUI_PORT}"
fi
# Kill GUI server on exit only if we started it this session
[ "$GUI_STARTED_HERE" = "true" ] && \
trap 'kill "$(cat "$GUI_PID_FILE" 2>/dev/null)" 2>/dev/null; rm -f "$GUI_PID_FILE"' EXIT INT TERM
# Direct mode: always spawn Python interactively (foreground, streamed output).
# Daemon running or not — interactive prompts never go to the socket.
TMPSCRIPT="$(mktemp "$DAEMON_DIR/run_XXXX.py")"
cat > "$TMPSCRIPT" << PYEOF
import sys
sys.path.insert(0, '$CODEY_V2_DIR')
from main import main
main()
PYEOF
python3 "$TMPSCRIPT" "$@"
rm -f "$TMPSCRIPT"
fi