feat(intent): conversational filesystem intents + humanized queue replies
This commit is contained in:
@@ -0,0 +1,106 @@
|
|||||||
|
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.'
|
||||||
@@ -11,6 +11,7 @@ from pathlib import Path
|
|||||||
from .queue import list_blocked
|
from .queue import list_blocked
|
||||||
from .guardrails import get_cfg, set_cfg
|
from .guardrails import get_cfg, set_cfg
|
||||||
from .chat_mode import load_mode, save_mode, interpret_text, set_pending, pop_pending
|
from .chat_mode import load_mode, save_mode, interpret_text, set_pending, pop_pending
|
||||||
|
from .intent_actions import interpret_conversation, filesystem_action
|
||||||
from .risk import classify, needs_approval
|
from .risk import classify, needs_approval
|
||||||
from .audit import log_event
|
from .audit import log_event
|
||||||
|
|
||||||
@@ -179,6 +180,7 @@ def help_text() -> str:
|
|||||||
"- goals add <text>\n"
|
"- goals add <text>\n"
|
||||||
"- guardrails show\n"
|
"- guardrails show\n"
|
||||||
"- guardrails set max_tasks_per_hour <n>\n"
|
"- guardrails set max_tasks_per_hour <n>\n"
|
||||||
|
"- (conversational filesystem intent: check/read/list/search files)\n"
|
||||||
"- help"
|
"- help"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -372,6 +374,12 @@ def parse_and_handle(chat_id: int, msg_id: int, text: str) -> str:
|
|||||||
if mode.get('chat_enabled', True):
|
if mode.get('chat_enabled', True):
|
||||||
uid = str(chat_id)
|
uid = str(chat_id)
|
||||||
owner = str(chat_id) == owner_id()
|
owner = str(chat_id) == owner_id()
|
||||||
|
|
||||||
|
# conversational filesystem/file-intent handling
|
||||||
|
ci = interpret_conversation(raw)
|
||||||
|
if (ci.get('intent') or '').lower() == 'filesystem':
|
||||||
|
return filesystem_action(ci.get('action',''), ci.get('path','.'), ci.get('query',''))
|
||||||
|
|
||||||
interp = interpret_text(raw)
|
interp = interpret_text(raw)
|
||||||
intent = (interp.get('intent') or 'unknown').lower()
|
intent = (interp.get('intent') or 'unknown').lower()
|
||||||
|
|
||||||
@@ -379,17 +387,16 @@ def parse_and_handle(chat_id: int, msg_id: int, text: str) -> str:
|
|||||||
pending = pop_pending(uid)
|
pending = pop_pending(uid)
|
||||||
if pending:
|
if pending:
|
||||||
code, out = run_prime(['queue','add', pending.get('task_type','planning'), pending.get('task','')])
|
code, out = run_prime(['queue','add', pending.get('task_type','planning'), pending.get('task','')])
|
||||||
return f"Approved. Queued action.\n{out[:3000]}"
|
return _format_queue_add_human(out)
|
||||||
return 'No pending action to approve.'
|
return 'No pending action to approve.'
|
||||||
|
|
||||||
if intent == 'action-request':
|
if intent == 'action-request':
|
||||||
task_type = interp.get('task_type') or 'planning'
|
task_type = interp.get('task_type') or 'planning'
|
||||||
task = interp.get('task') or raw
|
task = interp.get('task') or raw
|
||||||
strict = bool(mode.get('strict_mode', False))
|
# owner fast-lane: planning/analysis can auto-queue unless strict mode is on
|
||||||
# owner fast-lane: planning/analysis can auto-queue unless strict mode is on
|
|
||||||
if owner and task_type in {'planning','other'} and not strict:
|
if owner and task_type in {'planning','other'} and not strict:
|
||||||
code, out = run_prime(['queue','add', 'planning', task])
|
code, out = run_prime(['queue','add', 'planning', task])
|
||||||
return f"Got it — I'll work on that.\nQueued planning task:\n{out[:2800]}"
|
return _format_queue_add_human(out)
|
||||||
|
|
||||||
if strict or bool(interp.get('needs_confirmation', True)):
|
if strict or bool(interp.get('needs_confirmation', True)):
|
||||||
set_pending(uid, task_type, task)
|
set_pending(uid, task_type, task)
|
||||||
@@ -397,7 +404,7 @@ def parse_and_handle(chat_id: int, msg_id: int, text: str) -> str:
|
|||||||
f"Task: {task}\n"
|
f"Task: {task}\n"
|
||||||
"Reply 'approve' to execute or 'deny' to cancel.")
|
"Reply 'approve' to execute or 'deny' to cancel.")
|
||||||
code, out = run_prime(['queue','add', task_type, task])
|
code, out = run_prime(['queue','add', task_type, task])
|
||||||
return f"Queued and moving.\n{out[:3000]}"
|
return _format_queue_add_human(out)
|
||||||
|
|
||||||
if intent in {'chat','ask','unknown'}:
|
if intent in {'chat','ask','unknown'}:
|
||||||
r = (interp.get('reply') or '').strip()
|
r = (interp.get('reply') or '').strip()
|
||||||
|
|||||||
Reference in New Issue
Block a user