120 lines
4.0 KiB
Python
120 lines
4.0 KiB
Python
from __future__ import annotations
|
||
import json
|
||
import subprocess
|
||
import time
|
||
from pathlib import Path
|
||
|
||
STATE_FILE = Path('/srv/prime-core/state/chat-mode.json')
|
||
PENDING_FILE = Path('/srv/prime-core/state/pending-actions.json')
|
||
|
||
DEFAULT_MODE = {'chat_enabled': True, 'strict_mode': False}
|
||
|
||
|
||
def load_mode() -> dict:
|
||
if not STATE_FILE.exists():
|
||
save_mode(DEFAULT_MODE)
|
||
return dict(DEFAULT_MODE)
|
||
try:
|
||
return json.loads(STATE_FILE.read_text())
|
||
except Exception:
|
||
return dict(DEFAULT_MODE)
|
||
|
||
|
||
def save_mode(mode: dict):
|
||
STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||
STATE_FILE.write_text(json.dumps(mode, indent=2))
|
||
|
||
|
||
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 interpret_text(text: str) -> dict:
|
||
"""
|
||
OpenAI/Codex-backed lightweight intent interpreter.
|
||
Returns JSON with:
|
||
intent: chat|ask|action-request|approval|unknown
|
||
task_type: planning|coding|refactor|fix|other
|
||
task: string
|
||
risk_hint: low|medium|high
|
||
needs_confirmation: bool
|
||
reply: natural language assistant response
|
||
"""
|
||
prompt = f'''You are Prime intent interpreter.
|
||
Message: {text!r}
|
||
Return strict JSON only with keys:
|
||
intent, task_type, task, risk_hint, needs_confirmation, reply.
|
||
Rules:
|
||
- If user is greeting/chatting, intent=chat.
|
||
- If user asks a question, intent=ask.
|
||
- If user requests an action, intent=action-request.
|
||
- If message is approval like yes/approve/do it, intent=approval.
|
||
- Keep reply concise and human.
|
||
'''
|
||
code, out, err = _run(['codex', 'exec', '--skip-git-repo-check', '--json', prompt])
|
||
if code != 0:
|
||
return {
|
||
'intent': 'unknown',
|
||
'task_type': 'planning',
|
||
'task': text,
|
||
'risk_hint': 'medium',
|
||
'needs_confirmation': True,
|
||
'reply': "I can help with that. Want me to propose a concrete plan first?"
|
||
}
|
||
|
||
# codex --json emits event stream; parse last json object with required keys if present
|
||
parsed = None
|
||
for line in out.splitlines()[::-1]:
|
||
line = line.strip()
|
||
if not line.startswith('{'):
|
||
continue
|
||
try:
|
||
obj = json.loads(line)
|
||
# sometimes nested payloads; try direct
|
||
if all(k in obj for k in ['intent','task_type','task','risk_hint','needs_confirmation','reply']):
|
||
parsed = obj
|
||
break
|
||
except Exception:
|
||
continue
|
||
|
||
if not parsed:
|
||
# fallback heuristic
|
||
low = text.lower().strip()
|
||
if low in {'yes','y','approve','do it','proceed','go ahead'}:
|
||
return {'intent':'approval','task_type':'planning','task':'','risk_hint':'low','needs_confirmation':False,'reply':'Approval received.'}
|
||
if any(k in low for k in ['build','create','fix','set up','setup','do ','please']):
|
||
return {'intent':'action-request','task_type':'planning','task':text,'risk_hint':'medium','needs_confirmation':True,'reply':'I can do that. I’ll propose actions first.'}
|
||
if low.endswith('?'):
|
||
return {'intent':'ask','task_type':'planning','task':text,'risk_hint':'low','needs_confirmation':False,'reply':'Good question — here’s what I think.'}
|
||
return {'intent':'chat','task_type':'planning','task':'','risk_hint':'low','needs_confirmation':False,'reply':'Got it.'}
|
||
|
||
return parsed
|
||
|
||
|
||
def load_pending() -> dict:
|
||
if not PENDING_FILE.exists():
|
||
return {}
|
||
try:
|
||
return json.loads(PENDING_FILE.read_text())
|
||
except Exception:
|
||
return {}
|
||
|
||
|
||
def save_pending(p: dict):
|
||
PENDING_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||
PENDING_FILE.write_text(json.dumps(p, indent=2))
|
||
|
||
|
||
def set_pending(user_id: str, task_type: str, task: str):
|
||
p = load_pending()
|
||
p[user_id] = {'task_type': task_type, 'task': task, 'ts': int(time.time())}
|
||
save_pending(p)
|
||
|
||
|
||
def pop_pending(user_id: str):
|
||
p = load_pending()
|
||
it = p.pop(user_id, None)
|
||
save_pending(p)
|
||
return it
|