feat(chat): add conversational chat mode with intent parsing and plan/confirm flow
This commit is contained in:
@@ -98,3 +98,15 @@ Behavior:
|
||||
- Asks for goal/task direction when queue is clear
|
||||
- Quiet hours enforced: 11:00 PM–6:00 AM America/New_York
|
||||
- Personality: calm, strategic, concise (`prime_core/personality.py`)
|
||||
|
||||
## 13) Chat Mode v1 (conversational control)
|
||||
Prime can now interpret natural-language messages and not just strict commands.
|
||||
|
||||
New controls:
|
||||
- `mode chat on|off`
|
||||
- `mode strict on|off`
|
||||
|
||||
Behavior:
|
||||
- Interprets intent via OpenAI/Codex (`prime_core/chat_mode.py`)
|
||||
- For action requests: proposes plan and asks for explicit approval (`approve`) when strict/confirm needed
|
||||
- Keeps pending user action context in `state/pending-actions.json`
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
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
|
||||
@@ -9,6 +9,7 @@ import urllib.request
|
||||
from pathlib import Path
|
||||
from .queue import list_blocked
|
||||
from .guardrails import get_cfg, set_cfg
|
||||
from .chat_mode import load_mode, save_mode, interpret_text, set_pending, pop_pending
|
||||
from .risk import classify, needs_approval
|
||||
from .audit import log_event
|
||||
|
||||
@@ -115,6 +116,8 @@ def help_text() -> str:
|
||||
"- queue deny <task_id> [reason] (or /deny <task_id> [reason])\n"
|
||||
"- run once\n"
|
||||
"- mode autonomous on|off\n"
|
||||
"- mode chat on|off\n"
|
||||
"- mode strict on|off\n"
|
||||
"- goals show\n"
|
||||
"- goals add <text>\n"
|
||||
"- guardrails show\n"
|
||||
@@ -258,6 +261,18 @@ def parse_and_handle(chat_id: int, msg_id: int, text: str) -> str:
|
||||
cfg = get_cfg(); cfg['max_tasks_per_hour'] = int(parts[3]); set_cfg(cfg)
|
||||
return 'guardrails updated'
|
||||
|
||||
if parts[:2] == ['mode', 'chat']:
|
||||
if len(parts) != 3 or parts[2] not in {'on','off'}:
|
||||
return 'Usage: mode chat on|off'
|
||||
m = load_mode(); m['chat_enabled'] = (parts[2]=='on'); save_mode(m)
|
||||
return f"chat mode set to {parts[2]}"
|
||||
|
||||
if parts[:2] == ['mode', 'strict']:
|
||||
if len(parts) != 3 or parts[2] not in {'on','off'}:
|
||||
return 'Usage: mode strict on|off'
|
||||
m = load_mode(); m['strict_mode'] = (parts[2]=='on'); save_mode(m)
|
||||
return f"strict mode set to {parts[2]}"
|
||||
|
||||
if parts[:2] == ['goals', 'show']:
|
||||
goals = load_goals()
|
||||
return json.dumps(goals, indent=2)[:3500] if goals else 'No goals set.'
|
||||
@@ -270,6 +285,33 @@ def parse_and_handle(chat_id: int, msg_id: int, text: str) -> str:
|
||||
save_goals(goals)
|
||||
return 'Goal added.'
|
||||
|
||||
# conversational mode fallback (non-command chat)
|
||||
mode = load_mode()
|
||||
if mode.get('chat_enabled', True):
|
||||
uid = str(chat_id)
|
||||
interp = interpret_text(raw)
|
||||
intent = (interp.get('intent') or 'unknown').lower()
|
||||
|
||||
if intent == 'approval':
|
||||
pending = pop_pending(uid)
|
||||
if pending:
|
||||
code, out = run_prime(['queue','add', pending.get('task_type','planning'), pending.get('task','')])
|
||||
return f"Approved. Queued action.\n{out[:3000]}"
|
||||
return 'No pending action to approve.'
|
||||
|
||||
if intent == 'action-request':
|
||||
task_type = interp.get('task_type') or 'planning'
|
||||
task = interp.get('task') or raw
|
||||
strict = bool(mode.get('strict_mode', False))
|
||||
if strict or bool(interp.get('needs_confirmation', True)):
|
||||
set_pending(uid, task_type, task)
|
||||
return f"Plan: I can execute this as {task_type}.\nTask: {task}\nReply 'approve' to proceed or 'deny' to cancel."
|
||||
code, out = run_prime(['queue','add', task_type, task])
|
||||
return f"Queued.\n{out[:3000]}"
|
||||
|
||||
if intent in {'chat','ask','unknown'}:
|
||||
return interp.get('reply') or 'I'm here. What would you like to do next?'
|
||||
|
||||
return "Unknown command.\n" + help_text()
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user