walkermanj's picture
Update app.py
01c1905 verified
Raw
History Blame Contribute Delete
64.5 kB
import gradio as gr
import re
import os
import requests
import threading
import time
from datetime import datetime
import os
import requests
import base64
import json
from pathlib import Path
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
GITHUB_OWNER = "kennyjov2020"
GITHUB_REPO = "lm-studioss-briefings"
GITHUB_FILE = "briefings.json"
# ==============================
# LM Studioss Tools.md Loader
# ==============================
def load_tools_md():
tools_path = Path("Tools.md")
if not tools_path.exists():
return "Tools.md not found. Tool governance layer unavailable."
try:
return tools_path.read_text(encoding="utf-8")
except Exception as e:
return f"Tools.md could not be loaded: {e}"
TOOLS_MD_CONTENT = load_tools_md()
# ==============================
# LiveDataFetcher Tool - Brave Search
# ==============================
BRAVE_API_KEY = os.getenv("BRAVE_API_KEY")
def live_data_fetcher(query, count=5):
if not BRAVE_API_KEY:
return {
"status": "error",
"message": "BRAVE_API_KEY is not configured."
}
try:
headers = {
"Accept": "application/json",
"X-Subscription-Token": BRAVE_API_KEY
}
response = requests.get(
"https://api.search.brave.com/res/v1/web/search",
headers=headers,
params={
"q": query,
"count": count
},
timeout=10
)
if response.status_code != 200:
return {
"status": "error",
"message": f"Brave Search failed with status code {response.status_code}",
"details": response.text
}
data = response.json()
results = data.get("web", {}).get("results", [])
if not results:
return {
"status": "not_found",
"message": "No live search results found."
}
return {
"status": "success",
"query": query,
"results": [
{
"title": item.get("title"),
"url": item.get("url"),
"description": item.get("description")
}
for item in results
]
}
except Exception as e:
return {
"status": "error",
"message": f"LiveDataFetcher failed: {e}"
}
def get_briefings():
url = f"https://api.github.com/repos/{GITHUB_OWNER}/{GITHUB_REPO}/contents/{GITHUB_FILE}"
headers = {"Authorization": f"Bearer {GITHUB_TOKEN}"}
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
content = base64.b64decode(data["content"]).decode("utf-8")
return json.loads(content), data["sha"]
return [], None
# ==============================
# MemoryReader Tool
# ==============================
def memory_reader(key=None):
briefings, sha = get_briefings()
if not briefings:
return {
"status": "not_found",
"message": "No memory entries available."
}
# Return all memory if no key supplied
if key is None:
return {
"status": "success",
"memory": briefings
}
# Search memory by keyword
filtered = [
item for item in briefings
if key.lower() in json.dumps(item).lower()
]
if filtered:
return {
"status": "success",
"memory": filtered
}
return {
"status": "not_found",
"message": f"No memory found for key: {key}"
}
def save_briefing(entry):
briefings, sha = get_briefings()
briefings.append(entry)
updated_content = json.dumps(briefings, indent=2)
encoded_content = base64.b64encode(updated_content.encode("utf-8")).decode("utf-8")
url = f"https://api.github.com/repos/{GITHUB_OWNER}/{GITHUB_REPO}/contents/{GITHUB_FILE}"
headers = {"Authorization": f"Bearer {GITHUB_TOKEN}"}
data = {
"message": "Update briefings",
"content": encoded_content,
"sha": sha
}
requests.put(url, headers=headers, json=data)
# Web Search Config
SEARCH_TOOL = "Brave Search API"
WEB_RESEARCH_MODEL = "google/gemini-3.1-pro"
WEB_SEARCH_ENABLED = True
BRAVE_API_KEY = os.getenv("BRAVE_SEARCH_API_KEY") or os.getenv("BRAVE_API_KEY")
from collections import deque
APP_TITLE = "LM Studioss Agent Architecture V3.2 - Multi-Model Routing Layer"
ANCHOR_LOCK = True
# Primary model routes
DEFAULT_MODEL = "openai/gpt-5.4"
COMPARE_MODEL = "anthropic/claude-sonnet-4.6"
RESEARCH_MODEL = "openai/gpt-5.4"
CODE_MODEL = "qwen/qwen3-coder"
FALLBACK_MODEL = "deepseek-v4-flash"
# Emergency backup route
LEGACY_FALLBACK = "openai/gpt-oss-20b:free"
# Web Search Function
def brave_web_search(query, count=5):
if not BRAVE_API_KEY:
return "WEB_SEARCH_UNAVAILABLE: Missing BRAVE_SEARCH_API_KEY."
url = "https://api.search.brave.com/res/v1/web/search"
headers = {
"Accept": "application/json",
"Accept-Encoding": "gzip",
"X-Subscription-Token": BRAVE_API_KEY,
}
params = {
"q": query,
"count": count,
"country": "us",
"search_lang": "en",
}
try:
response = requests.get(url, headers=headers, params=params, timeout=10)
response.raise_for_status()
data = response.json()
results = data.get("web", {}).get("results", [])
if not results:
return "No web results found."
formatted_results = []
for item in results[:count]:
title = item.get("title", "Untitled")
link = item.get("url", "")
description = item.get("description", "")
formatted_results.append(
f"- {title}\n {link}\n {description}"
)
return "\n\n".join(formatted_results)
except Exception as e:
return f"WEB_SEARCH_ERROR: {e}"
def is_live_query(user_input):
live_keywords = [
"latest",
"today",
"current",
"right now",
"news",
"recent",
"this week",
"this month",
"2026",
"weather",
"search the web",
"look up",
"find online",
]
text = user_input.lower()
return any(keyword in text for keyword in live_keywords)
# Persistent-ish session state
TASK_QUEUE = deque()
COMPLETED_TASKS = []
# Persistent-ish session state
# ----------------------------
TASK_QUEUE = deque()
COMPLETED_TASKS = []
LAST_PRIMARY = "No active subject"
LAST_DECISION_SUBJECT = "None"
LAST_REQUEST = ""
LAST_ANSWER = ""
# ----------------------------
# Control / Guard Rails
# ----------------------------
CONTROL_PHRASES = {
"do it",
"do this",
"same thing",
"same request",
"handle it",
"handle this",
"work on it",
"work on this",
"continue",
"continue that",
"keep going",
"next",
"next task",
"run next",
"move forward",
}
CONTINUE_PHRASES = {
"continue",
"continue that",
"keep going",
"next",
"next task",
"run next",
"move forward",
}
VAGUE_SUBJECTS = {
"it",
"this",
"that",
"thing",
"something",
"anything",
"task",
"request",
"same request",
}
# ----------------------------
# Daily Briefing Notifications
# ----------------------------
NOTIFICATIONS = []
BRIEFING_RUNS = set()
SCHEDULER_STARTED = False
def _clean_briefing_summary(model_output):
lines = (model_output or "").splitlines()
cleaned = []
for line in lines:
if line.startswith("Route:") or line.startswith("Model:"):
continue
cleaned.append(line)
return "\n".join(cleaned).strip()
def run_public_school_briefing():
web_results = brave_web_search(
"latest Mississippi public schools updates education news",
count=5,
)
summary_prompt = f"""
Use the web results below to prepare a daily briefing.
IMPORTANT:
- Focus ONLY on Mississippi public schools.
- Return the top 2 updates.
- Number the updates 1 and 2.
- Keep each update brief and practical.
Topic:
Mississippi Public Schools
Web Results:
{web_results}
"""
model_answer = call_openrouter(summary_prompt, "openai/gpt-5.4")
briefing_summary = _clean_briefing_summary(model_answer)
briefing = {
"time": "10:00 AM",
"topic": "Mississippi Public Schools",
"updates": briefing_summary,
"source_results": web_results,
}
notification = (
"DAILY BRIEFING READY β€” 10:00 AM\n"
"Mississippi Public Schools:\n"
f"{briefing_summary}"
)
NOTIFICATIONS.append(notification)
save_briefing({
"title": "Mississippi Public Schools Update",
"content": briefing_summary,
"timestamp": datetime.now().strftime("%Y-%m-%d %I:%M %p")
})
return briefing
def run_ai_briefing():
web_results = brave_web_search(
"latest AI news artificial intelligence updates",
count=5,
)
summary_prompt = f"""
Use the web results below to prepare a daily briefing.
IMPORTANT:
- Focus ONLY on AI-related updates.
- Return exactly 2 AI-related topics.
- Number the topics 1 and 2.
- Keep each topic brief and practical.
Topic:
AI-related topics
Web Results:
{web_results}
"""
model_answer = call_openrouter(summary_prompt, "openai/gpt-5.4")
briefing_summary = _clean_briefing_summary(model_answer)
briefing = {
"time": "11:00 AM",
"topic": "AI-related topics",
"updates": briefing_summary,
"source_results": web_results,
}
notification = (
"DAILY BRIEFING READY β€” 11:00 AM\n"
"AI-related topics:\n"
f"{briefing_summary}"
)
NOTIFICATIONS.append(notification)
save_briefing({
"title": "AI Briefing",
"content": briefing_summary,
"timestamp": datetime.now().strftime("%Y-%m-%d %I:%M %p")
})
return briefing
def get_notifications():
if not NOTIFICATIONS:
return "No briefing notifications are available yet."
return NOTIFICATIONS[-1]
def daily_briefing_scheduler():
while True:
now = datetime.now()
if now.weekday() < 5:
current_time = now.strftime("%H:%M")
run_key = now.strftime("%Y-%m-%d") + "-" + current_time
if current_time == "10:00" and run_key not in BRIEFING_RUNS:
BRIEFING_RUNS.add(run_key)
run_public_school_briefing()
if current_time == "11:00" and run_key not in BRIEFING_RUNS:
BRIEFING_RUNS.add(run_key)
run_ai_briefing()
time.sleep(30)
def start_daily_briefing_scheduler():
global SCHEDULER_STARTED
if SCHEDULER_STARTED:
return
SCHEDULER_STARTED = True
scheduler_thread = threading.Thread(
target=daily_briefing_scheduler,
daemon=True,
)
scheduler_thread.start()
# ----------------------------
# Helpers
# ----------------------------
def normalize(text):
return (text or "").strip()
def lower_clean(text):
return normalize(text).lower()
def is_continue_request(request):
return lower_clean(request) in CONTINUE_PHRASES
def is_control_phrase(request):
return lower_clean(request) in CONTROL_PHRASES
def should_log_task(task):
task_lower = lower_clean(task)
if not task_lower:
return False
if task_lower in CONTROL_PHRASES:
return False
if task_lower in VAGUE_SUBJECTS:
return False
return True
def split_tasks(request):
request = normalize(request)
if not request:
return []
parts = re.split(r"\s+and\s+|\s+then\s+|,", request, flags=re.IGNORECASE)
tasks = [p.strip() for p in parts if p.strip()]
return tasks if tasks else [request]
def clean_task_title(task):
task = normalize(task)
if not task:
return "None"
task = re.sub(
r"^(review|build|break|turn|plan|test|analyze|explain|improve|compare|summarize|research)\s+the\s+",
lambda m: m.group(1).capitalize() + " ",
task,
flags=re.IGNORECASE,
)
return task[0].upper() + task[1:] if task else "None"
def extract_subject(task):
task = normalize(task)
task_lower = task.lower()
known_subjects = {
"lm studios agent": "LM Studioss Agent",
"lm studioss agent": "LM Studioss Agent",
"sentiment detector": "Sentiment Detector",
"policy tracker": "Policy Tracker",
"power bi dashboard": "Power BI Dashboard",
"excel command center": "Excel Command Center",
"openrouter": "OpenRouter",
"ai": "AI",
}
for key, value in known_subjects.items():
if key in task_lower:
return value
patterns = [
r"build\s+(.*)",
r"review\s+(.*)",
r"break\s+(.*?)\s+into",
r"plan\s+(.*)",
r"test\s+(.*)",
r"analyze\s+(.*)",
r"explain\s+(.*)",
r"improve\s+(.*)",
r"compare\s+(.*)",
r"summarize\s+(.*)",
r"research\s+(.*)",
]
for pattern in patterns:
match = re.search(pattern, task, flags=re.IGNORECASE)
if match:
candidate = match.group(1).strip()
candidate = re.sub(r"^(the|a|an)\s+", "", candidate, flags=re.IGNORECASE)
if candidate and candidate.lower() not in VAGUE_SUBJECTS:
return candidate.title()
return "No active subject"
def detect_intent(task):
task_lower = lower_clean(task)
if any(word in task_lower for word in ["build", "create", "make"]):
return "BUILD"
if any(word in task_lower for word in ["review", "check", "validate", "inspect"]):
return "VALIDATE"
if any(word in task_lower for word in ["break", "steps", "plan", "organize"]):
return "STRUCTURE"
if any(word in task_lower for word in ["turn", "execute", "run", "action"]):
return "EXECUTE"
if any(word in task_lower for word in ["latest", "current", "today", "tonight", "game", "games", "score", "scores", "nba", "schedule"]):
return "SEARCH"
if any(word in task_lower for word in ["explain", "why", "how", "what", "improve", "compare", "summarize", "analyze", "research"]):
return "ANSWER"
return "GENERAL"
def priority_score(task, subject):
intent = detect_intent(task)
score = 3
if subject and subject != "No active subject":
score += 2
if intent == "BUILD":
score += 3
elif intent == "EXECUTE":
score += 3
elif intent == "VALIDATE":
score += 2
elif intent == "STRUCTURE":
score += 2
elif intent == "ANSWER":
score += 3
if len(task.split()) >= 5:
score += 1
return min(score, 10)
def recommended_step(task):
intent = detect_intent(task)
subject = extract_subject(task)
if intent == "BUILD":
return f"Define build objective for {subject}"
if intent == "VALIDATE":
return f"Review {subject} for weak points and missing scope"
if intent == "STRUCTURE":
return f"Break {subject} into ordered steps"
if intent == "EXECUTE":
return f"Turn {subject} into one actionable step"
if intent == "ANSWER":
return f"Provide a clear answer about {subject}"
return "Clarify intended outcome"
def smart_flow_recommendation(task, mode):
intent = detect_intent(task)
if mode == "ANSWER":
return "Answer directly while preserving governance"
if intent == "ANSWER":
return "Recommend ANSWER mode"
if intent == "VALIDATE":
return "Recommend VALIDATION path"
if intent == "BUILD" and mode != "DECISION":
return "Recommend DECISION first, then EXECUTION"
if intent == "STRUCTURE":
return "Recommend STRUCTURE before EXECUTION"
if intent == "GENERAL":
return "Clarify request before execution"
return "Proceed in current mode"
def clarity_gate(task):
task_lower = lower_clean(task)
if not task_lower:
return False
if task_lower in CONTROL_PHRASES:
return False
if len(task_lower.split()) < 2:
return False
return True
def completed_text():
if not COMPLETED_TASKS:
return "None"
return "\n".join(f"- {task}" for task in COMPLETED_TASKS)
def next_queue_text():
return clean_task_title(TASK_QUEUE[0]) if TASK_QUEUE else "None"
def queue_display():
if not TASK_QUEUE:
return "None"
return "\n".join(f"- {clean_task_title(task)}" for task in TASK_QUEUE)
def safe_return(primary, decision_subject, secondary, stack, clarity, next_task, rec_step, completed, output):
return (
primary,
decision_subject,
secondary,
stack,
clarity,
next_task,
rec_step,
completed,
output,
)
# ----------------------------
# OpenRouter Intelligence Layer
# ----------------------------
def detect_route(prompt):
p = lower_clean(prompt)
if any(x in p for x in ["difference between","compare"," vs "," versus "]):
return "comparison", COMPARE_MODEL
if any(x in p for x in ["code","python","debug","script"]):
return "code", CODE_MODEL
if any(x in p for x in ["research","analyze","study"]):
return "research", RESEARCH_MODEL
return "general", DEFAULT_MODEL
def call_openrouter(prompt, subject="No active subject"):
api_key = os.getenv("OPENROUTER_API_KEY")
if not api_key:
return fallback_answer(prompt, subject)
system_prompt = (
f"You are the model-backed reasoning layer for LM Studioss Agent. "
"Answer clearly, practically, and briefly. "
"Stay governed by clarity, honesty, truth, and ordered thinking. "
"When a request requires live or current data, attempt to use the available live-data path first. If live data cannot be retrieved, say so clearly and answer only what can be answered safely. "
"If more detail is needed, ask a short clarifying question.\n\n"
"Approved Tool Reference Layer:\n"
"Use these tools to assist the user. Do not let tool rules prevent helpful action when a safe available path exists.\n"
f"{TOOLS_MD_CONTENT}"
)
model_constants = {
DEFAULT_MODEL,
COMPARE_MODEL,
RESEARCH_MODEL,
CODE_MODEL,
FALLBACK_MODEL,
LEGACY_FALLBACK,
WEB_RESEARCH_MODEL,
}
is_exact_model = isinstance(subject, str) and ("/" in subject or subject in model_constants)
if is_exact_model:
model_name = subject
route_name = "web_search" if model_name == WEB_RESEARCH_MODEL else "exact_model"
else:
route_name, model_name = detect_route(prompt)
model_candidates = []
for candidate in [model_name, FALLBACK_MODEL, LEGACY_FALLBACK]:
if candidate and candidate not in model_candidates:
model_candidates.append(candidate)
for candidate in model_candidates:
try:
response = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"HTTP-Referer": "https://huggingface.co/spaces/walkermanj/LM-Studioss-Agent",
"X-Title": "LM Studioss Agent",
},
json={
"model": candidate,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt},
],
"temperature": 0.4,
"max_tokens": 700,
},
timeout=45,
)
if response.status_code != 200:
continue
data = response.json()
return "Route: " + route_name + "\nModel: " + candidate + "\n\n" + data["choices"][0]["message"]["content"]
except Exception:
continue
return fallback_answer(prompt, subject)
def fallback_answer(task, subject):
task_lower = lower_clean(task)
if subject == "Sentiment Detector":
return """Fallback Answer Layer:
The Sentiment Detector can be improved by strengthening three areas: input handling, confidence review, and result tracking.
1. Input handling β€” Add clearer example prompts so the user understands what kind of emotional text to enter.
2. Confidence review β€” Show confidence scores so weak predictions can be identified.
3. Result tracking β€” Save repeated outputs so patterns can be reviewed over time.
A good next step is to test it with a small set of emotional phrases and compare confidence levels across joy, anger, sadness, and neutral responses."""
if subject == "LM Studioss Agent":
return """Fallback Answer Layer:
The LM Studioss Agent is a governed assistant framework. Its strength is not only in answering, but in controlling how a request moves through structure, execution, validation, queue memory, and decision routing.
The strongest parts right now are the Hammer Guard, queue handling, Smart Flow recommendation, and the OpenRouter connection point. The next improvement is refining model selection so different roles can use different models."""
if "openrouter" in task_lower:
return """Fallback Answer Layer:
OpenRouter can serve as the model gateway for LM Studioss Agent. Hugging Face hosts the app, while OpenRouter provides access to reasoning models behind the scenes.
The architecture is:
Hugging Face Space β†’ LM Studioss Agent Logic β†’ OpenRouter API β†’ Selected Model β†’ Answer returned to the agent UI."""
return f"""Fallback Answer Layer:
Here is a clear response about {subject}.
The request appears to ask for explanation or guidance. The agent should identify the subject, confirm the intended outcome, and provide a structured answer. If the OpenRouter model is unavailable, this fallback keeps the agent functional."""
# ----------------------------
# Guard / Message Builders
# ----------------------------
def hammer_guard_message(primary="No active subject", decision_subject="None"):
return safe_return(
primary,
decision_subject,
"None",
"Retained",
"BLOCKED",
next_queue_text(),
"Clarify intent or use continue if a queue exists",
completed_text(),
"""Gemini:
HAMMER GUARD ACTIVE β€” Ambiguous Control Phrase Detected
This phrase is a control signal, not a task.
Choose one:
1. Type `continue` to run the next queued task.
2. Enter a clear task with a named subject.
3. Switch to VALIDATION and clarify the request.
No task was logged to memory.""",
)
def auto_continue_blocked():
return safe_return(
LAST_PRIMARY,
LAST_DECISION_SUBJECT,
"None",
"Retained",
"BLOCKED",
"None",
"Add a multi-task request first",
completed_text(),
"""Gemini:
AUTO-CONTINUE BLOCKED
Reason:
- No queued task is available.
- The system has nothing clear to continue.
Required:
1. Add a request with more than one task.
2. Run DECISION first.
3. Then run EXECUTION or type `continue`.""",
)
def build_output(role, mode, primary, decision_subject, selected_task, priority, rec_step, flow, queue):
return f"""{role}:
{mode} Decision
Primary Subject: {primary}
Decision Subject: {decision_subject}
Secondary Subject: None
Priority Score: {priority}/10
Selected Task:
{clean_task_title(selected_task)}
Next Best Action:
{rec_step}.
Smart Flow Recommendation:
{flow}
Queued Tasks:
{queue}
Task State:
{"In Progress" if queue != "None" else "Focused"}"""
# ----------------------------
# Chat Mode Interpretation Layer
# ----------------------------
def normalize_user_input(user_input):
"""
Clean and normalize user input for Chat Mode routing.
"""
if not user_input:
return ""
return user_input.strip()
def detect_chat_intent(user_input):
"""
Detect the best LMA mode based on natural language input.
"""
text = normalize_user_input(user_input).lower()
selected_tool = decide_tool(user_input)
if selected_tool == "LiveDataFetcher":
return "SEARCH_MODE"
if selected_tool == "MemoryReader":
return "MEMORY_MODE"
debug_terms = ["error", "bug", "fix", "debug", "traceback", "runtime", "indentation"]
execution_terms = ["run", "execute", "build", "generate", "create file", "update code"]
github_terms = [
"github",
"repo",
"repository",
"commit",
"file",
"log",
"stored",
"saved briefing",
"briefing history",
"memory file",
"system state",
]
memory_terms = ["remember", "save this", "store this", "log this", "recall"]
briefing_terms = ["briefing", "daily", "today's focus", "show my briefing"]
search_terms = [
"search", "look up", "latest", "current", "news", "web", "internet",
"right now", "today", "weather", "score", "scores", "winning",
"stock", "price", "crypto", "update", "updates", "playoffs", "game", "games", "tonight", "schedule"
]
triad_terms = ["triad", "lola", "gemini", "elliot"]
if any(term in text for term in debug_terms):
return "DEBUG_MODE"
if any(term in text for term in execution_terms):
return "EXECUTION_MODE"
if any(term in text for term in github_terms):
return "GITHUB_MODE"
if any(term in text for term in memory_terms):
return "MEMORY_MODE"
if any(term in text for term in briefing_terms):
return "DAILY_BRIEFING"
if any(term in text for term in search_terms):
return "SEARCH_MODE"
if any(term in text for term in triad_terms):
return "TRIAD_MODE"
if text:
return "GENERAL_CHAT"
return "SAFE_FALLBACK"
def should_use_brave_search(user_input):
"""
Decide whether Brave Search should be used.
"""
text = normalize_user_input(user_input).lower()
brave_terms = [
"latest",
"current",
"today",
"news",
"web",
"internet",
"search online",
"look up online",
"what's happening",
"game",
"games",
"tonight",
"schedule",
]
return any(term in text for term in brave_terms)
def should_use_github(user_input):
"""
Decide whether GitHub should be used as the data source.
"""
text = normalize_user_input(user_input).lower()
github_terms = [
"github",
"repo",
"repository",
"stored",
"saved",
"log",
"file",
"briefing history",
"memory file",
"system state",
]
return any(term in text for term in github_terms)
def should_use_openrouter(user_input):
"""
Decide whether OpenRouter should be used for model reasoning.
"""
text = normalize_user_input(user_input).lower()
return bool(text)
def _agent_output(agent_response):
"""
Extract the visible output field from the existing governed LMA response.
"""
if isinstance(agent_response, (list, tuple)) and agent_response:
return agent_response[-1]
return agent_response
def _format_briefings(briefings):
if not briefings:
return "No saved briefings were found in GitHub."
briefing_text = []
for item in briefings[-3:]:
title = item.get("title", "Untitled Briefing")
timestamp = item.get("timestamp", "No timestamp")
content = item.get("content", "")
briefing_text.append(
f"{title}\n"
f"{timestamp}\n\n"
f"{content}"
)
return "\n\n---\n\n".join(briefing_text)
def run_debug_mode(user_input):
"""
Route debug requests through the existing governed answer/code route.
"""
return _agent_output(run_agent(user_input, "ANSWER"))
def run_execution_mode(user_input):
"""
Route execution requests through the existing governed execution mode.
"""
return _agent_output(run_agent(user_input, "EXECUTION"))
def run_github_mode(user_input):
"""
Use the existing GitHub briefing access path for stored LMA data.
"""
try:
briefings, _ = get_briefings()
return _format_briefings(briefings)
except Exception as e:
return f"GITHUB_MODE unavailable through existing GitHub access path: {e}"
def run_memory_mode(user_input):
"""
TODO:
Connect this to the existing governed memory write/recall function when available.
"""
return (
"Memory Mode placeholder.\n\n"
"No memory write was performed because no governed memory write function is currently connected."
)
def run_daily_briefing(user_input):
"""
Route daily briefing requests through existing briefing notifications/storage.
"""
text = normalize_user_input(user_input).lower()
if should_use_github(user_input) or "saved" in text or "history" in text:
return run_github_mode(user_input)
return get_notifications()
# ==============================
# QueryRefiner Tool
# ==============================
def refine_search_query(user_input):
text = normalize_user_input(user_input).strip()
if not text:
return ""
lowered = text.lower()
# Live/current event shaping
if any(term in lowered for term in ["today", "tonight", "current", "latest", "live", "event", "events", "happening"]):
return f"{text} current live updated information"
# Local event shaping
if any(term in lowered for term in ["near me", "local", "around me"]):
return f"{text} local current events"
# News/current affairs shaping
if any(term in lowered for term in ["news", "breaking", "update", "updates"]):
return f"{text} latest verified news"
# Default refinement
return f"{text} current verified information"
def run_brave_search(user_input):
"""
Route live/current requests through the existing Brave Search function.
"""
refined_query = refine_search_query(user_input)
web_results = brave_web_search(refined_query, count=5)
if not should_use_openrouter(user_input):
return web_results
summary_prompt = f"""
Use the web results below to answer the user's request.
User Request:
{user_input}
Refined Search Query:
{refined_query}
Web Results:
{web_results}
Give a clear, practical answer based on the results.
"""
return call_openrouter(summary_prompt, WEB_RESEARCH_MODEL)
def run_general_search(user_input):
"""
Route non-live search-like requests through the existing governed answer route.
"""
return _agent_output(run_agent(user_input, "ANSWER"))
def run_triad_mode(user_input):
"""
Route Triad requests through the existing governed Triad mode.
"""
return _agent_output(run_agent(user_input, "TRIAD"))
def run_general_chat(user_input):
"""
Use the existing OpenRouter response function for natural language responses.
"""
return call_openrouter(user_input, DEFAULT_MODEL)
def chat_mode_router(user_input):
"""
Main Chat Mode router.
This function must not bypass LMA governance.
"""
mode = detect_chat_intent(user_input)
selected_tool = decide_tool(user_input)
if selected_tool == "LiveDataFetcher":
mode = "SEARCH_MODE"
elif selected_tool == "MemoryReader":
mode = "MEMORY_MODE"
if mode == "DEBUG_MODE":
result = run_debug_mode(user_input)
elif mode == "EXECUTION_MODE":
result = run_execution_mode(user_input)
elif mode == "GITHUB_MODE":
result = run_github_mode(user_input)
elif mode == "MEMORY_MODE":
result = run_memory_mode(user_input)
elif mode == "DAILY_BRIEFING":
result = run_daily_briefing(user_input)
elif mode == "SEARCH_MODE":
result = run_brave_search(user_input)
return result
elif mode == "TRIAD_MODE":
result = run_triad_mode(user_input)
elif mode == "GENERAL_CHAT":
result = run_general_chat(user_input)
else:
result = safe_fallback_response(user_input)
return format_chat_mode_response(result, mode)
def format_chat_mode_response(result, mode):
"""
Format Chat Mode output in LMA style.
"""
if not result:
return "LMA did not find a result for that request."
return f"Mode: {mode}\n\n{result}"
def safe_fallback_response(user_input):
"""
Safe fallback when LMA cannot clearly detect intent.
"""
return (
"LMA could not clearly determine the correct mode for this request.\n\n"
"Recommended next step:\n"
"Please restate the request with one clear action such as search, briefing, memory, debug, or GitHub."
)
# ==============================
# Model-Decides-Tool Layer
# ==============================
def decide_tool(user_input):
text = user_input.lower()
# Live/current information
if any(word in text for word in [
"latest", "current", "today", "news",
"game", "games", "score", "scores",
"weather", "search", "look up",
"nba", "sports", "schedule"
]):
return "LiveDataFetcher"
# Memory retrieval
if any(word in text for word in [
"remember", "memory", "saved",
"what did i say", "recall"
]):
return "MemoryReader"
# Default
return "GENERAL_CHAT"
# ----------------------------
# Core engine
# ----------------------------
USER_IDENTITY = {
"user_name": "Kenny",
"role": "owner_builder",
"system_name": "LMA",
"preferred_response_style": "structured, clear, controlled",
"core_purpose": "learning, building, and understanding AI behavior",
}
def build_user_identity_instruction():
return f"""
User Identity:
- User Name: {USER_IDENTITY["user_name"]}
- Role: {USER_IDENTITY["role"]}
- System Name: {USER_IDENTITY["system_name"]}
- Preferred Style: {USER_IDENTITY["preferred_response_style"]}
- Core Purpose: {USER_IDENTITY["core_purpose"]}
Instruction:
You are LMA, the LM Studios Agent.
You are interacting with Kenny, the owner-builder of LMA.
You may refer to the user as Kenny when appropriate.
You may refer to yourself as LMA when appropriate.
Do not fabricate additional personal details beyond this identity.
Do not claim to know anything beyond this identity card.
"""
def build_mode_instruction(mode):
return f"""
You are operating as the LM Studioss Agent.
ACTIVE MODE: {mode}
Mode Rules:
- CONTROLLED: Use verified sources only. If no verified source exists, do not guess.
- HYBRID: Use reasoning, but clearly separate facts from assumptions.
- AUTONOMOUS: Provide a short plan, use available tools or verified context, and confirm results.
- Never pretend to know private, live, financial, operational, or organization-specific data without a verified source.
- Clearly identify the source layer when responding.
"""
def select_mode(user_input, selected_mode=None):
if selected_mode in ["CONTROLLED", "HYBRID", "AUTONOMOUS"]:
return selected_mode
lowered = user_input.lower()
if "report" in lowered or "official" in lowered:
return "CONTROLLED"
if "build" in lowered or "execute" in lowered or "automate" in lowered:
return "AUTONOMOUS"
return "HYBRID"
def refine_web_query(user_input):
lowered = user_input.lower()
if "ai news" in lowered or "current ai" in lowered:
return "latest artificial intelligence news today Reuters AP MIT Technology Review OpenAI NVIDIA"
if "news" in lowered:
return f"latest news today {user_input}"
return user_input
def get_verified_web_context(user_input):
try:
web_query = refine_web_query(user_input)
web_results = brave_web_search(web_query, count=5)
if not web_results:
return ""
if (
"WEB_SEARCH_UNAVAILABLE" in web_results
or "WEB_SEARCH_ERROR" in web_results
or "No web results found." in web_results
):
return ""
return web_results.strip()
except Exception:
return ""
def truth_guard(mode, source_found):
if mode in ["CONTROLLED", "AUTONOMOUS"] and not source_found:
return (
"No verified data source is available for this request. "
"Please provide an approved file, database result, API output, or verified source."
)
return None
def run_agent(request, mode, selected_mode=None):
global LAST_PRIMARY, LAST_DECISION_SUBJECT, LAST_REQUEST, LAST_ANSWER
try:
request = normalize(request)
mode = normalize(mode).upper()
user_input = request
active_mode = select_mode(user_input, selected_mode)
source_found = False
retrieved_context = ""
mode_instruction = build_mode_instruction(active_mode)
if active_mode in ["CONTROLLED", "AUTONOMOUS"]:
retrieved_context = get_verified_web_context(user_input)
if retrieved_context.strip():
source_found = True
if not request:
return safe_return(
LAST_PRIMARY,
LAST_DECISION_SUBJECT,
"None",
"Retained",
"BLOCKED",
next_queue_text(),
"Enter a request",
completed_text(),
"Enter a request first.",
)
user_input = request
active_mode = select_mode(user_input, selected_mode)
source_found = False
retrieved_context = ""
mode_instruction = build_mode_instruction(active_mode)
user_identity_instruction = build_user_identity_instruction()
if active_mode in ["CONTROLLED", "AUTONOMOUS", "HYBRID"]:
retrieved_context = get_verified_web_context(user_input)
if retrieved_context.strip():
source_found = True
if (
"search for" in user_input.lower()
or "look up" in user_input.lower()
or "find the best" in user_input.lower()
or "best wireless" in user_input.lower()
):
if not retrieved_context:
retrieved_context = get_verified_web_context(user_input)
if retrieved_context.strip():
source_found = True
guard_message = truth_guard(active_mode, source_found)
if guard_message:
return safe_return(
LAST_PRIMARY,
LAST_DECISION_SUBJECT,
"None",
"Retained",
"BLOCKED",
next_queue_text(),
"Verified source required",
completed_text(),
f"[MODE: {active_mode}]\n\n{guard_message}",
)
verified_context_section = ""
if retrieved_context.strip():
verified_context_section = f"""
Verified Web Context:
{retrieved_context}
"""
search_prompt = f"""
{mode_instruction}
Use the web results below to answer the user's request.
User Request:
{user_input}
Source Layer:
{"web_search" if source_found else "model_memory"}
{verified_context_section}
Give a clear, practical answer based on the results.
"""
answer = call_openrouter(search_prompt, "openai/gpt-5.4")
return safe_return(
LAST_PRIMARY,
LAST_DECISION_SUBJECT,
"None",
"Retained",
"PASSED",
next_queue_text(),
"Web search completed",
completed_text(),
f"[MODE: {active_mode}]\n\n{answer}",
)
if "run school briefing" in user_input.lower():
briefing = run_public_school_briefing()
source_found = bool(briefing)
retrieved_context = json.dumps(briefing, indent=2) if source_found else ""
guard_message = truth_guard(active_mode, source_found)
if guard_message:
return safe_return(
LAST_PRIMARY,
LAST_DECISION_SUBJECT,
"None",
"Retained",
"BLOCKED",
next_queue_text(),
"Verified source required",
completed_text(),
f"[MODE: {active_mode}]\n\n{guard_message}",
)
return safe_return(
LAST_PRIMARY,
LAST_DECISION_SUBJECT,
"None",
"Retained",
"PASSED",
next_queue_text(),
"School briefing generated",
completed_text(),
f"[MODE: {active_mode}]\n\nSource Layer: web_search\n\n{retrieved_context}",
)
if "show my briefings" in user_input.lower():
briefings, _ = get_briefings()
source_found = bool(briefings)
retrieved_context = json.dumps(briefings[-3:], indent=2) if source_found else ""
guard_message = truth_guard(active_mode, source_found)
if guard_message:
return safe_return(
LAST_PRIMARY,
LAST_DECISION_SUBJECT,
"None",
"Retained",
"BLOCKED",
next_queue_text(),
"Verified source required",
completed_text(),
f"[MODE: {active_mode}]\n\n{guard_message}",
)
briefing_text = []
for item in briefings[-3:]:
title = item.get("title", "Untitled Briefing")
timestamp = item.get("timestamp", "No timestamp")
content = item.get("content", "")
briefing_text.append(
f"πŸ“Œ {title}\n"
f"πŸ•’ {timestamp}\n\n"
f"{content}"
)
formatted_briefings = "\n\n---\n\n".join(briefing_text)
return safe_return(
LAST_PRIMARY,
LAST_DECISION_SUBJECT,
"None",
"Retained",
"PASSED",
next_queue_text(),
"Latest saved briefings returned",
completed_text(),
f"[MODE: {active_mode}]\n\nSource Layer: internal_files\n\n{formatted_briefings}",
)
if "save briefing" in user_input.lower():
save_briefing({
"title": "Test Briefing",
"content": "This is a saved briefing from LM Studioss agent.",
"timestamp": datetime.now().strftime("%Y-%m-%d %I:%M %p")
})
source_found = True
retrieved_context = "GitHub briefing save request completed."
return safe_return(
LAST_PRIMARY,
LAST_DECISION_SUBJECT,
"None",
"Retained",
"PASSED",
next_queue_text(),
"Test briefing saved",
completed_text(),
f"[MODE: {active_mode}]\n\nSource Layer: internal_files\n\n{retrieved_context}",
)
if is_control_phrase(request) and not is_continue_request(request):
return hammer_guard_message(LAST_PRIMARY, LAST_DECISION_SUBJECT)
if is_continue_request(request):
if TASK_QUEUE:
request = TASK_QUEUE.popleft()
else:
return auto_continue_blocked()
tasks = split_tasks(request)
clean_tasks = [task for task in tasks if should_log_task(task)]
if not clean_tasks:
return hammer_guard_message(LAST_PRIMARY, LAST_DECISION_SUBJECT)
selected_task = clean_tasks[0]
if len(clean_tasks) > 1:
TASK_QUEUE.clear()
for task in clean_tasks[1:]:
TASK_QUEUE.append(task)
decision_subject = extract_subject(selected_task)
primary = decision_subject if decision_subject != "No active subject" else LAST_PRIMARY
if not primary or primary == "No active subject":
primary = decision_subject
LAST_PRIMARY = primary
LAST_DECISION_SUBJECT = decision_subject
LAST_REQUEST = selected_task
priority = priority_score(selected_task, decision_subject)
rec_step = recommended_step(selected_task)
flow = smart_flow_recommendation(selected_task, mode)
queue = queue_display()
gate = "PASSED" if clarity_gate(selected_task) else "BLOCKED"
if not (mode == "ANSWER" and WEB_SEARCH_ENABLED and is_live_query(selected_task)) and lower_clean(request) != "show my briefing":
guard_message = truth_guard(active_mode, source_found)
if guard_message:
return safe_return(
primary,
decision_subject,
"None",
"Retained",
"BLOCKED",
next_queue_text(),
"Verified source required",
completed_text(),
f"[MODE: {active_mode}]\n\n{guard_message}",
)
if gate == "BLOCKED" and mode in {"EXECUTION", "ANSWER"}:
return safe_return(
primary,
decision_subject,
"None",
"Retained",
"BLOCKED",
next_queue_text(),
"Clarify intended outcome",
completed_text(),
"""Gemini:
REQUEST BLOCKED β€” Clarity Gate Active
Reason:
- The request is too vague for this mode.
- The expected outcome is not clearly named.
- The first action or question is not clearly defined.
Required:
1. Name the subject.
2. Ask a clear question or state the exact outcome.
3. Run again.""",
)
if lower_clean(request) == "show my briefing":
latest_briefing = get_notifications()
source_found = bool(latest_briefing and latest_briefing != "No briefing notifications are available yet.")
retrieved_context = latest_briefing if source_found else ""
guard_message = truth_guard(active_mode, source_found)
if guard_message:
return safe_return(
LAST_PRIMARY,
LAST_DECISION_SUBJECT,
"None",
"Retained",
"BLOCKED",
next_queue_text(),
"Verified source required",
completed_text(),
f"[MODE: {active_mode}]\n\n{guard_message}",
)
LAST_ANSWER = latest_briefing
return safe_return(
LAST_PRIMARY,
LAST_DECISION_SUBJECT,
"None",
"Retained",
"PASSED",
next_queue_text(),
"Latest stored briefing returned",
completed_text(),
f"[MODE: {active_mode}]\n\nSource Layer: internal_files\n\n{retrieved_context}",
)
if mode != "ANSWER":
guard_message = truth_guard(active_mode, source_found)
if guard_message:
return safe_return(
primary,
decision_subject,
"None",
"Retained",
"BLOCKED",
next_queue_text(),
"Verified source required",
completed_text(),
f"[MODE: {active_mode}]\n\n{guard_message}",
)
if mode == "ANSWER":
display_route, display_model = detect_route(selected_task)
if WEB_SEARCH_ENABLED and is_live_query(selected_task):
if not retrieved_context:
retrieved_context = get_verified_web_context(selected_task)
if retrieved_context.strip():
source_found = True
guard_message = truth_guard(active_mode, source_found)
if guard_message:
return safe_return(
primary,
decision_subject,
"None",
"Retained",
"BLOCKED",
next_queue_text(),
"Verified source required",
completed_text(),
f"[MODE: {active_mode}]\n\n{guard_message}",
)
verified_context_section = ""
if retrieved_context.strip():
verified_context_section = f"""
Verified Web Context:
{retrieved_context}
"""
summary_prompt = f"""
{mode_instruction}
Use the web results below to answer the user's question.
IMPORTANT:
- Focus ONLY on the exact location mentioned
- Ignore other places with the same name
- If the question says "Clinton, MS", answer only for Clinton, Mississippi
- Give a direct answer (no multiple locations, no list)
User Question:
{selected_task}
Source Layer:
{"web_search" if source_found else "model_memory"}
{verified_context_section}
"""
model_answer = call_openrouter(summary_prompt, "openai/gpt-5.4")
display_route = "web_search"
display_model = "openai/gpt-5.4"
else:
guard_message = truth_guard(active_mode, source_found)
if guard_message:
return safe_return(
primary,
decision_subject,
"None",
"Retained",
"BLOCKED",
next_queue_text(),
"Verified source required",
completed_text(),
f"[MODE: {active_mode}]\n\n{guard_message}",
)
verified_context_section = ""
if retrieved_context.strip():
verified_context_section = f"""
Verified Web Context:
{retrieved_context}
"""
answer_prompt = f"""
{mode_instruction}
User Request:
{selected_task}
{verified_context_section}
"""
model_answer = call_openrouter(answer_prompt, decision_subject)
LAST_ANSWER = model_answer
output = f"""[MODE: {active_mode}]
Lola:
ANSWER MODE β€” V3.2 Multi-Model Routing Layer
Primary Subject: {primary}
Decision Subject: {decision_subject}
Clarity Gate: {gate}
Smart Flow Recommendation: {flow}
Route: {display_route}
Model: {display_model}
Source Layer: {"web_search" if source_found else "model_memory"}
User Request:
{selected_task}
Model Answer:
{model_answer}"""
elif mode == "STRUCTURE":
output = build_output("Lola", mode, primary, decision_subject, selected_task, priority, rec_step, flow, queue)
elif mode == "VALIDATION":
output = build_output("Gemini", mode, primary, decision_subject, selected_task, priority, rec_step, flow, queue)
elif mode == "DECISION":
output = build_output("Decision Layer", mode, primary, decision_subject, selected_task, priority, rec_step, flow, queue)
elif mode == "EXECUTION":
output = build_output("Elliot", mode, primary, decision_subject, selected_task, priority, rec_step, flow, queue)
elif mode == "TRIAD":
output = (
build_output("Lola", "STRUCTURE", primary, decision_subject, selected_task, priority, rec_step, flow, queue)
+ "\n\n"
+ build_output("Elliot", "EXECUTION", primary, decision_subject, selected_task, priority, rec_step, flow, queue)
+ "\n\n"
+ build_output("Gemini", "VALIDATION", primary, decision_subject, selected_task, priority, rec_step, flow, queue)
)
else:
output = build_output("Agent", mode, primary, decision_subject, selected_task, priority, rec_step, flow, queue)
if not output.startswith("[MODE:"):
output = f"[MODE: {active_mode}]\n\n{output}"
if mode in {"EXECUTION", "DECISION", "TRIAD", "ANSWER"}:
if should_log_task(selected_task):
logged_task = clean_task_title(selected_task)
if logged_task not in COMPLETED_TASKS:
COMPLETED_TASKS.append(logged_task)
return safe_return(
primary,
decision_subject,
"None",
"Updated" if queue != "None" else "Retained",
gate,
next_queue_text(),
rec_step,
completed_text(),
output,
)
except Exception as e:
return safe_return(
"Recovery Mode",
"Recovery Mode",
"None",
"Retained",
"BLOCKED",
"None",
"Inspect last request",
completed_text(),
f"Protected Recovery Triggered:\n{str(e)}",
)
if is_control_phrase(request) and not is_continue_request(request):
return hammer_guard_message(LAST_PRIMARY, LAST_DECISION_SUBJECT)
if is_continue_request(request):
if TASK_QUEUE:
request = TASK_QUEUE.popleft()
else:
return auto_continue_blocked()
tasks = split_tasks(request)
clean_tasks = [task for task in tasks if should_log_task(task)]
if not clean_tasks:
return hammer_guard_message(LAST_PRIMARY, LAST_DECISION_SUBJECT)
selected_task = clean_tasks[0]
if len(clean_tasks) > 1:
TASK_QUEUE.clear()
for task in clean_tasks[1:]:
TASK_QUEUE.append(task)
decision_subject = extract_subject(selected_task)
primary = decision_subject if decision_subject != "No active subject" else LAST_PRIMARY
if not primary or primary == "No active subject":
primary = decision_subject
LAST_PRIMARY = primary
LAST_DECISION_SUBJECT = decision_subject
LAST_REQUEST = selected_task
priority = priority_score(selected_task, decision_subject)
rec_step = recommended_step(selected_task)
flow = smart_flow_recommendation(selected_task, mode)
queue = queue_display()
gate = "PASSED" if clarity_gate(selected_task) else "BLOCKED"
if gate == "BLOCKED" and mode in {"EXECUTION", "ANSWER"}:
return safe_return(
primary,
decision_subject,
"None",
"Retained",
"BLOCKED",
next_queue_text(),
"Clarify intended outcome",
completed_text(),
"""Gemini:
REQUEST BLOCKED β€” Clarity Gate Active
Reason:
- The request is too vague for this mode.
- The expected outcome is not clearly named.
- The first action or question is not clearly defined.
Required:
1. Name the subject.
2. Ask a clear question or state the exact outcome.
3. Run again.""",
)
if lower_clean(request) == "show my briefing":
latest_briefing = get_notifications()
LAST_ANSWER = latest_briefing
return safe_return(
LAST_PRIMARY,
LAST_DECISION_SUBJECT,
"None",
"Retained",
"PASSED",
next_queue_text(),
"Latest stored briefing returned",
completed_text(),
latest_briefing,
)
if mode == "ANSWER":
display_route, display_model = detect_route(selected_task)
if WEB_SEARCH_ENABLED and is_live_query(selected_task):
web_results = brave_web_search(selected_task)
summary_prompt = f"""
Use the web results below to answer the user's question.
IMPORTANT:
- Focus ONLY on the exact location mentioned
- Ignore other places with the same name
- If the question says "Clinton, MS", answer only for Clinton, Mississippi
- Give a direct answer (no multiple locations, no list)
User Question:
{selected_task}
Web Results:
{web_results}
"""
model_answer = call_openrouter(summary_prompt, "openai/gpt-5.4")
display_route = "web_search"
display_model = "openai/gpt-5.4"
else:
model_answer = call_openrouter(selected_task, decision_subject)
LAST_ANSWER = model_answer
output = f"""Lola:
ANSWER MODE β€” V3.2 Multi-Model Routing Layer
Primary Subject: {primary}
Decision Subject: {decision_subject}
Clarity Gate: {gate}
Smart Flow Recommendation: {flow}
Route: {display_route}
Model: {display_model}
User Request:
{selected_task}
Model Answer:
{model_answer}"""
elif mode == "STRUCTURE":
output = build_output("Lola", mode, primary, decision_subject, selected_task, priority, rec_step, flow, queue)
elif mode == "VALIDATION":
output = build_output("Gemini", mode, primary, decision_subject, selected_task, priority, rec_step, flow, queue)
elif mode == "DECISION":
output = build_output("Decision Layer", mode, primary, decision_subject, selected_task, priority, rec_step, flow, queue)
elif mode == "EXECUTION":
output = build_output("Elliot", mode, primary, decision_subject, selected_task, priority, rec_step, flow, queue)
elif mode == "TRIAD":
output = (
build_output("Lola", "STRUCTURE", primary, decision_subject, selected_task, priority, rec_step, flow, queue)
+ "\n\n"
+ build_output("Elliot", "EXECUTION", primary, decision_subject, selected_task, priority, rec_step, flow, queue)
+ "\n\n"
+ build_output("Gemini", "VALIDATION", primary, decision_subject, selected_task, priority, rec_step, flow, queue)
)
else:
output = build_output("Agent", mode, primary, decision_subject, selected_task, priority, rec_step, flow, queue)
if mode in {"EXECUTION", "DECISION", "TRIAD", "ANSWER"}:
if should_log_task(selected_task):
logged_task = clean_task_title(selected_task)
if logged_task not in COMPLETED_TASKS:
COMPLETED_TASKS.append(logged_task)
return safe_return(
primary,
decision_subject,
"None",
"Updated" if queue != "None" else "Retained",
gate,
next_queue_text(),
rec_step,
completed_text(),
output,
)
except Exception as e:
return safe_return(
"Recovery Mode",
"Recovery Mode",
"None",
"Retained",
"BLOCKED",
"None",
"Inspect last request",
completed_text(),
f"Protected Recovery Triggered:\n{str(e)}",
)
def clear_all():
global TASK_QUEUE, COMPLETED_TASKS, LAST_PRIMARY, LAST_DECISION_SUBJECT, LAST_REQUEST, LAST_ANSWER
TASK_QUEUE.clear()
COMPLETED_TASKS.clear()
LAST_PRIMARY = "No active subject"
LAST_DECISION_SUBJECT = "None"
LAST_REQUEST = ""
LAST_ANSWER = ""
return safe_return(
"No active subject",
"None",
"None",
"Retained",
"BLOCKED",
"None",
"None",
"None",
"",
) + ("",)
# ----------------------------
# UI
# ----------------------------
with gr.Blocks(title=APP_TITLE) as demo:
gr.Markdown(f"# {APP_TITLE}")
gr.Markdown("""
Triad-enabled system with CCS (`///`) control.
- **STRUCTURE** β†’ Lola
- **EXECUTION** β†’ Elliot
- **VALIDATION** β†’ Gemini
- **TRIAD** β†’ Full governed sequence
- **DECISION** β†’ Priority routing
- **ANSWER** β†’ OpenRouter model-backed response
- **QUEUE** β†’ Next task memory
- **AUTO-CONTINUE** β†’ Continue runs next queued task
- **HAMMER GUARD** β†’ Blocks vague control phrases from becoming tasks
- **MEMORY SANITIZER** β†’ Prevents junk task memory
""")
with gr.Accordion("CCS Guide", open=True):
gr.Markdown("""
Examples:
- `Explain emotional drift in AI responses`
- `Research ways to improve my Sentiment Detector`
- `Build the Sentiment Detector and review the LM Studioss Agent`
- `continue`
- `do it` should trigger Hammer Guard
V3.1 adds **OpenRouter model-backed ANSWER mode**.
""")
primary_subject = gr.Textbox(label="Primary Subject", value="No active subject")
decision_subject = gr.Textbox(label="Decision Subject", value="None")
secondary_subject = gr.Textbox(label="Secondary Subject", value="None")
stack_box = gr.Textbox(label="Stack Status", value="Retained")
clarity_box = gr.Textbox(label="Clarity Gate Status", value="BLOCKED")
next_task_box = gr.Textbox(label="Next Queued Task", value="None")
rec_box = gr.Textbox(label="Recommended Next Step", value="None")
completed_box = gr.Textbox(label="Completed Tasks", value="None", lines=6)
request_box = gr.Textbox(
label="Structured Request (Full LMA Mode)",
placeholder="Explain emotional drift in AI responses"
)
mode_box = gr.Dropdown(
choices=["STRUCTURE", "EXECUTION", "VALIDATION", "DECISION", "TRIAD", "ANSWER"],
value="ANSWER",
label="Select Mode"
)
agent_mode_box = gr.Dropdown(
choices=["CONTROLLED", "HYBRID", "AUTONOMOUS"],
value="HYBRID",
label="Agent Mode"
)
output_box = gr.Textbox(label="Output", lines=24)
with gr.Row():
run_btn = gr.Button("Run")
clear_btn = gr.Button("Clear")
chat_mode_box = gr.Textbox(
label="Chat Mode (Natural Input)",
placeholder="Speak naturally to LMA"
)
chat_mode_output = gr.Textbox(label="Chat Mode Response", lines=18)
chat_mode_btn = gr.Button("Send to LMA")
run_btn.click(
fn=run_agent,
inputs=[request_box, mode_box, agent_mode_box],
outputs=[
primary_subject,
decision_subject,
secondary_subject,
stack_box,
clarity_box,
next_task_box,
rec_box,
completed_box,
output_box,
]
)
request_box.submit(
fn=run_agent,
inputs=[request_box, mode_box, agent_mode_box],
outputs=[
primary_subject,
decision_subject,
secondary_subject,
stack_box,
clarity_box,
next_task_box,
rec_box,
completed_box,
output_box,
]
)
clear_btn.click(
fn=clear_all,
inputs=[],
outputs=[
primary_subject,
decision_subject,
secondary_subject,
stack_box,
clarity_box,
next_task_box,
rec_box,
completed_box,
output_box,
request_box,
]
)
chat_mode_btn.click(
fn=chat_mode_router,
inputs=[chat_mode_box],
outputs=[chat_mode_output]
)
chat_mode_box.submit(
fn=chat_mode_router,
inputs=[chat_mode_box],
outputs=[chat_mode_output]
)
if __name__ == "__main__":
start_daily_briefing_scheduler()
demo.launch()