-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
572 lines (452 loc) · 16.2 KB
/
Copy pathclient.py
File metadata and controls
572 lines (452 loc) · 16.2 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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
"""vcc client - communicate with the daemon over JSON-RPC.
Simplified client using asyncio + Unix socket + JSON.
Replaces the complex msgspec + multiprocessing approach.
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import signal
import subprocess
import sys
import time
from collections.abc import Awaitable
from pathlib import Path
from typing import Any, TypeVar
from vectorless_code._runtime import (
daemon_log_path,
daemon_pid_path,
daemon_socket_path,
)
logger = logging.getLogger(__name__)
T = TypeVar("T")
# ---------------------------------------------------------------------------
# Exceptions
# ---------------------------------------------------------------------------
class DaemonError(RuntimeError):
"""Base exception for daemon errors."""
pass
class DaemonStartError(DaemonError):
"""Raised when the daemon fails to start."""
def __init__(self, message: str, log: str | None = None):
super().__init__(message)
self.log = log
class RPCError(DaemonError):
"""Raised when the daemon returns an error response."""
def __init__(self, code: int, message: str, data: Any = None):
super().__init__(message)
self.code = code
self.data = data
# ---------------------------------------------------------------------------
# Client
# ---------------------------------------------------------------------------
class DaemonClient:
"""Client for communicating with the vcc daemon.
Example:
```python
client = DaemonClient()
# Compile a project
result = await client.compile("/path/to/project")
print(f"Compiled {result['file_count']} files")
# Search
result = await client.ask("/path/to/project", "authentication logic")
for r in result['results']:
print(f"{r['file_path']}: {r['node_title']}")
```
"""
def __init__(self, socket_path: str | None = None):
"""Initialize the client.
Args:
socket_path: Path to the daemon Unix socket (default: from _runtime).
"""
self._socket_path = socket_path or daemon_socket_path()
self._request_id = 0
self._daemon_checked = False
def _next_id(self) -> int:
"""Get the next request ID."""
self._next_id.counter += 1
return self._next_id.counter
_next_id.counter = 0
# ------------------------------------------------------------------
# Low-level RPC
# ------------------------------------------------------------------
async def _call(
self,
method: str,
params: dict,
timeout: float = 120.0,
) -> Any:
"""Send a JSON-RPC request and return the result.
Args:
method: RPC method name.
params: Method parameters.
timeout: Request timeout in seconds.
Returns:
The result field from the response.
Raises:
RPCError: If the daemon returns an error.
DaemonError: For communication errors.
"""
# Ensure daemon is running
await self._ensure_daemon()
request = {
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": self._next_id(),
}
try:
reader, writer = await asyncio.wait_for(
asyncio.open_unix_connection(self._socket_path),
timeout=5.0,
)
except (FileNotFoundError, ConnectionRefusedError) as e:
raise DaemonError(f"Cannot connect to daemon at {self._socket_path}: {e}") from e
try:
# Send request
writer.write(json.dumps(request).encode() + b"\n")
await writer.drain()
# Read response
response_line = await asyncio.wait_for(
reader.readline(),
timeout=timeout,
)
if not response_line:
raise DaemonError("Connection closed by daemon")
response = json.loads(response_line.decode())
# Check for error
if "error" in response:
error = response["error"]
raise RPCError(
code=error["code"],
message=error["message"],
data=error.get("data"),
)
return response.get("result")
except TimeoutError:
raise DaemonError(f"Request timeout after {timeout}s") from None
except (json.JSONDecodeError, ValueError) as e:
raise DaemonError(f"Invalid response from daemon: {e}") from e
finally:
writer.close()
await writer.wait_closed()
# ------------------------------------------------------------------
# Daemon lifecycle
# ------------------------------------------------------------------
async def _ensure_daemon(self) -> None:
"""Ensure the daemon is running, starting it if necessary."""
if self._daemon_checked:
return
# Check if already running
if await self._ping():
self._daemon_checked = True
return
# Check if supervised (Docker, etc.)
if self._is_supervised():
# Wait for supervised daemon to become ready
logger.info("Waiting for supervised daemon...")
for _ in range(50): # 5 seconds
await asyncio.sleep(0.1)
if await self._ping():
self._daemon_checked = True
return
raise DaemonError("Supervised daemon did not start in time")
# Start the daemon
logger.info("Starting daemon...")
proc = self._start_daemon_process()
# Wait for daemon to become ready
deadline = time.monotonic() + 30.0
while time.monotonic() < deadline:
if proc.poll() is not None:
log = self._read_daemon_log()
msg = "Daemon process exited before it became ready."
if log:
msg += f"\n\nDaemon log:\n{log}"
raise DaemonStartError(msg, log=log)
await asyncio.sleep(0.2)
if await self._ping():
self._daemon_checked = True
return
raise DaemonStartError("Daemon did not start in time")
async def _ping(self) -> bool:
"""Check if the daemon is alive."""
try:
result = await self._call("ping", {}, timeout=1.0)
return isinstance(result, dict) and result.get("pong") is True
except Exception:
return False
def _is_supervised(self) -> bool:
"""Check if running in supervised mode (e.g., Docker)."""
return os.environ.get("VCC_DAEMON_SUPERVISED") == "1"
def _start_daemon_process(self) -> subprocess.Popen:
"""Start the daemon as a background process."""
runtime_dir = daemon_pid_path().parent
runtime_dir.mkdir(parents=True, exist_ok=True)
log_path = daemon_log_path()
# Find the vcc executable or use python -m
vcc_path = self._find_vcc_executable()
if vcc_path:
cmd = [vcc_path, "run-daemon"]
else:
cmd = [sys.executable, "-m", "vectorless_code.cli", "run-daemon"]
log_fd = open(log_path, "w")
if sys.platform == "win32":
create_no_window = 0x08000000
proc = subprocess.Popen(
cmd,
stdout=log_fd,
stderr=log_fd,
stdin=subprocess.DEVNULL,
creationflags=create_no_window,
)
else:
proc = subprocess.Popen(
cmd,
start_new_session=True,
stdout=log_fd,
stderr=log_fd,
stdin=subprocess.DEVNULL,
)
log_fd.close()
logger.info("Started daemon process with PID %d", proc.pid)
return proc
def _find_vcc_executable(self) -> str | None:
"""Find the vcc executable."""
python_dir = Path(sys.executable).parent
names = ["vcc.exe", "vcc"] if sys.platform == "win32" else ["vcc"]
for name in names:
vcc = python_dir / name
if vcc.exists():
return str(vcc)
return None
def _read_daemon_log(self) -> str | None:
"""Read the daemon log file."""
log_path = daemon_log_path()
try:
content = log_path.read_text().strip()
return content if content else None
except (FileNotFoundError, OSError):
return None
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
async def compile(
self,
project_root: str,
timeout: float = 300.0,
) -> dict:
"""Compile a project.
Args:
project_root: Path to the project root.
timeout: Request timeout in seconds.
Returns:
Dict with keys: success, doc_id, file_count, total_lines, etc.
"""
return await self._call(
"compile",
{"project_root": project_root},
timeout=timeout,
)
async def ask(
self,
project_root: str,
query: str,
limit: int = 10,
offset: int = 0,
timeout: float = 120.0,
) -> dict:
"""Ask a question about a project.
Args:
project_root: Path to the project root.
query: Search query.
limit: Maximum number of results.
offset: Number of results to skip.
timeout: Request timeout in seconds.
Returns:
Dict with keys: success, results, confidence, etc.
"""
return await self._call(
"ask",
{
"project_root": project_root,
"query": query,
"limit": limit,
"offset": offset,
},
timeout=timeout,
)
async def status(
self,
project_root: str,
timeout: float = 10.0,
) -> dict:
"""Get project status.
Args:
project_root: Path to the project root.
timeout: Request timeout in seconds.
Returns:
Dict with keys: indexed, indexing, file_count, etc.
"""
return await self._call(
"status",
{"project_root": project_root},
timeout=timeout,
)
async def daemon_status(self, timeout: float = 5.0) -> dict:
"""Get daemon status.
Args:
timeout: Request timeout in seconds.
Returns:
Dict with keys: version, uptime_seconds, projects
"""
return await self._call("daemon_status", {}, timeout=timeout)
async def project_status(
self,
project_root: str,
timeout: float = 10.0,
) -> dict:
"""Get project status (alias for status)."""
return await self.status(project_root, timeout=timeout)
async def stop(self, timeout: float = 5.0) -> dict:
"""Stop the daemon.
Args:
timeout: Request timeout in seconds.
Returns:
Dict with key: ok
"""
result = await self._call("stop", {}, timeout=timeout)
self._daemon_checked = False
return result
# ---------------------------------------------------------------------------
# Sync wrappers
# ---------------------------------------------------------------------------
def _run_async(coro: Awaitable[T]) -> T:
"""Run an async coroutine in a new event loop."""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(coro)
finally:
loop.close()
def compile(project_root: str) -> dict:
"""Compile a project (synchronous wrapper)."""
client = DaemonClient()
return _run_async(client.compile(project_root))
def ask(project_root: str, query: str, limit: int = 10) -> dict:
"""Ask a question (synchronous wrapper)."""
client = DaemonClient()
return _run_async(client.ask(project_root, query, limit))
def status(project_root: str) -> dict:
"""Get project status (synchronous wrapper)."""
client = DaemonClient()
return _run_async(client.status(project_root))
def stop() -> dict:
"""Stop the daemon (synchronous wrapper)."""
client = DaemonClient()
return _run_async(client.stop())
# ---------------------------------------------------------------------------
# Daemon lifecycle functions (for CLI)
# ---------------------------------------------------------------------------
def is_daemon_running() -> bool:
"""Check if the daemon is running by checking the PID file."""
pid_path = daemon_pid_path()
if not pid_path.exists():
return False
try:
pid_str = pid_path.read_text().strip()
pid = int(pid_str)
# Check if process is running
if sys.platform == "win32":
import psutil
return psutil.pid_exists(pid)
else:
try:
os.kill(pid, 0) # Send null signal
return True
except OSError:
return False
except (ValueError, OSError, ProcessLookupError):
return False
def start_daemon() -> subprocess.Popen:
"""Start the daemon as a background process.
Returns:
The subprocess.Popen object for the daemon process.
"""
runtime_dir = daemon_pid_path().parent
runtime_dir.mkdir(parents=True, exist_ok=True)
log_path = daemon_log_path()
# Find the vcc executable or use python -m
vcc_path = _find_vcc_executable_static()
if vcc_path:
cmd = [vcc_path, "run-daemon"]
else:
cmd = [sys.executable, "-m", "vectorless_code.cli", "run-daemon"]
log_fd = open(log_path, "w")
if sys.platform == "win32":
create_no_window = 0x08000000
proc = subprocess.Popen(
cmd,
stdout=log_fd,
stderr=log_fd,
stdin=subprocess.DEVNULL,
creationflags=create_no_window,
)
else:
proc = subprocess.Popen(
cmd,
start_new_session=True,
stdout=log_fd,
stderr=log_fd,
stdin=subprocess.DEVNULL,
)
log_fd.close()
logger.info("Started daemon process with PID %d", proc.pid)
return proc
def stop_daemon() -> None:
"""Stop the daemon by sending SIGTERM."""
pid_path = daemon_pid_path()
if not pid_path.exists():
logger.warning("Daemon PID file not found")
return
try:
pid_str = pid_path.read_text().strip()
pid = int(pid_str)
if sys.platform == "win32":
import psutil
proc = psutil.Process(pid)
proc.terminate()
else:
os.kill(pid, signal.SIGTERM)
logger.info("Sent SIGTERM to daemon PID %d", pid)
except (ValueError, OSError, ProcessLookupError) as e:
logger.warning("Failed to stop daemon: %s", e)
def _find_vcc_executable_static() -> str | None:
"""Find the vcc executable (static version for module-level functions)."""
python_dir = Path(sys.executable).parent
names = ["vcc.exe", "vcc"] if sys.platform == "win32" else ["vcc"]
for name in names:
vcc = python_dir / name
if vcc.exists():
return str(vcc)
return None
def _wait_for_daemon(proc: subprocess.Popen | None = None, timeout: float = 30.0) -> None:
"""Wait for the daemon to become ready.
Args:
proc: The subprocess.Popen object (optional, for early exit detection).
timeout: Maximum time to wait in seconds.
"""
start = time.monotonic()
client = DaemonClient()
while time.monotonic() - start < timeout:
if proc and proc.poll() is not None:
raise RuntimeError("Daemon process exited before becoming ready")
try:
result = asyncio.run(client._call("ping", {}, timeout=1.0))
if result.get("pong"):
logger.info("Daemon is ready")
return
except Exception:
pass
time.sleep(0.2)
raise RuntimeError(f"Daemon did not become ready within {timeout}s")