107 lines
3.7 KiB
Python
107 lines
3.7 KiB
Python
from __future__ import annotations
|
|
import json
|
|
import shlex
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
BASE = Path('/srv/prime-core')
|
|
|
|
|
|
def _run(cmd: list[str]) -> tuple[int, str, str]:
|
|
p = subprocess.run(cmd, capture_output=True, text=True)
|
|
return p.returncode, (p.stdout or '').strip(), (p.stderr or '').strip()
|
|
|
|
|
|
def _safe_path(raw: str) -> Path | None:
|
|
p = (BASE / raw).resolve() if not raw.startswith('/') else Path(raw).resolve()
|
|
try:
|
|
p.relative_to(BASE)
|
|
return p
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def extract_json_events(raw: str) -> list[dict]:
|
|
out=[]
|
|
for line in raw.splitlines():
|
|
line=line.strip()
|
|
if not line.startswith('{'):
|
|
continue
|
|
try:
|
|
out.append(json.loads(line))
|
|
except Exception:
|
|
pass
|
|
return out
|
|
|
|
|
|
def interpret_conversation(text: str) -> dict:
|
|
prompt = f'''You are an intent classifier for Prime.
|
|
User message: {text!r}
|
|
Return strict JSON with keys:
|
|
intent, action, path, query, task_type, task, response_style.
|
|
Intent values: chat|question|action_request|filesystem.
|
|
Action values when filesystem: exists|read|search|list.
|
|
Rules:
|
|
- If user asks about files/directories/content, choose filesystem.
|
|
- If user asks to "check if exists", action=exists and include path.
|
|
- If user asks to "search/find/grep", action=search and include query/path if present.
|
|
- If user asks to read/show/cat file, action=read and include path.
|
|
- If user asks list directory/files, action=list and include path.
|
|
- Otherwise use action_request/chat/question.
|
|
'''
|
|
rc, out, err = _run(['codex', 'exec', '--skip-git-repo-check', '--json', prompt])
|
|
if rc != 0:
|
|
return {'intent':'chat','action':'','path':'','query':'','task_type':'planning','task':text,'response_style':'normal'}
|
|
|
|
# parse best JSON payload line
|
|
for line in out.splitlines()[::-1]:
|
|
line=line.strip()
|
|
if not line.startswith('{'):
|
|
continue
|
|
try:
|
|
obj=json.loads(line)
|
|
if 'intent' in obj:
|
|
return obj
|
|
except Exception:
|
|
continue
|
|
return {'intent':'chat','action':'','path':'','query':'','task_type':'planning','task':text,'response_style':'normal'}
|
|
|
|
|
|
def filesystem_action(action: str, path: str = '', query: str = '') -> str:
|
|
action=(action or '').lower().strip()
|
|
path=(path or '').strip() or '.'
|
|
query=(query or '').strip()
|
|
|
|
sp = _safe_path(path)
|
|
if not sp:
|
|
return 'I can only access paths under /srv/prime-core for safety.'
|
|
|
|
if action == 'exists':
|
|
return f"{'✅ exists' if sp.exists() else '❌ not found'}: {sp}"
|
|
|
|
if action == 'list':
|
|
if not sp.exists():
|
|
return f"Not found: {sp}"
|
|
if sp.is_file():
|
|
return f"That is a file, not a directory: {sp}"
|
|
items = sorted([x.name + ('/' if x.is_dir() else '') for x in sp.iterdir()])[:80]
|
|
return 'Directory listing:\n' + '\n'.join(f'- {i}' for i in items)
|
|
|
|
if action == 'read':
|
|
if not sp.exists() or not sp.is_file():
|
|
return f"File not found: {sp}"
|
|
txt = sp.read_text(errors='ignore')
|
|
if len(txt) > 3000:
|
|
txt = txt[:3000] + '\n... (truncated)'
|
|
return f"Contents of {sp}:\n{txt}"
|
|
|
|
if action == 'search':
|
|
if not query:
|
|
return 'Please provide a search query.'
|
|
rc, out, err = _run(['bash','-lc', f"rg -n {shlex.quote(query)} {shlex.quote(str(sp))} | head -n 50"])
|
|
if rc != 0 and not out:
|
|
return f"No matches for {query!r} in {sp}"
|
|
return out[:3200] if out else (err[:500] or 'No matches.')
|
|
|
|
return 'I understood this as a filesystem request, but could not map the exact action.'
|