jarvis-cloud / modules /deferred_intent.py
Jarvis2345's picture
deploy(S4): Blender headless pipeline + WebAR client + backend fixes
e6cb1a4 verified
Raw History Blame Contribute Delete
10.1 kB
"""modules/deferred_intent.py β€” thinking hard before an irreversible act,
and then remembering that it was ordered.
THE RULE THIS IMPLEMENTS
------------------------
"if the command said to do shutdown or anything jarvis will think about that
very deeply and if didn't shutdown for a reason and even after some minutes no
response then think again if reason comes to shutdown or anything i said he
will do that"
Which is a specific and quite subtle behaviour:
1. An irreversible order is DELIBERATED, not just executed on sight.
2. If there is a real reason to hold β€” a download mid-flight, unsaved work,
a backup running β€” JARVIS holds, and SAYS WHY.
3. Holding is not refusing. The order stands.
4. After a few minutes with no word from the operator, he thinks again.
5. If the reason has cleared, or on reflection it no longer outweighs the
instruction, HE DOES IT. What was asked for happens.
The failure mode being avoided in both directions matters. A machine that shuts
down mid-download because it heard a word is bad. A machine that quietly drops
an order it was given because it once had a doubt is worse β€” the operator
believes the thing is happening and it never does. So a deferral is a TIMER,
never a bin.
State is on disk: a deferral that does not survive a process restart is exactly
the silent drop this is designed to prevent.
"""
from __future__ import annotations
import json
import os
import threading
import time
from dataclasses import dataclass
from typing import Callable, Optional
_STATE_DIR = os.environ.get("JARVIS_APP_DATA_DIR") or os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".friday_data")
_STATE_PATH = os.path.join(_STATE_DIR, "deferred_orders.json")
_lock = threading.RLock()
# How long to hold before reconsidering, per attempt. It reconsiders sooner the
# first time β€” "a few minutes" β€” then gives the blocking condition longer to
# clear before deciding it is not going to.
RECONSIDER_LADDER = (180, 300, 600, 900)
# After this many reconsiderations the order is carried out regardless of the
# standing objection, because at that point the objection has had the better
# part of half an hour to resolve itself and the operator has said nothing to
# withdraw the instruction.
MAX_DEFERRALS = len(RECONSIDER_LADDER)
@dataclass
class Verdict:
proceed: bool
reason: str
speak: str
def _load() -> dict:
try:
with open(_STATE_PATH, "r", encoding="utf-8") as fh:
data = json.load(fh)
return data if isinstance(data, dict) else {}
except Exception:
return {}
def _save(data: dict) -> None:
try:
os.makedirs(_STATE_DIR, exist_ok=True)
tmp = _STATE_PATH + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(data, fh, indent=2)
os.replace(tmp, _STATE_PATH)
except Exception:
pass
def _orders(data: dict) -> dict:
return data.setdefault("orders", {})
# ── What is actually going on right now ─────────────────────────────────────
def machine_situation() -> str:
"""Facts a person would check before pulling the plug."""
bits = []
try:
import psutil
cpu = psutil.cpu_percent(interval=0.4)
bits.append(f"CPU {cpu:.0f}%")
try:
io1 = psutil.net_io_counters()
time.sleep(0.6)
io2 = psutil.net_io_counters()
kbs = (io2.bytes_recv - io1.bytes_recv) / 0.6 / 1024.0
bits.append(f"network in {kbs:.0f} KB/s")
except Exception:
pass
busy = []
for p in psutil.process_iter(["name", "cpu_percent"]):
try:
n = (p.info.get("name") or "").lower()
if any(k in n for k in ("setup", "install", "msiexec", "update",
"backup", "7z", "winrar", "ffmpeg",
"handbrake", "robocopy", "git")):
busy.append(n)
except Exception:
continue
if busy:
bits.append("running: " + ", ".join(sorted(set(busy))[:6]))
try:
b = psutil.sensors_battery()
if b:
bits.append(f"battery {b.percent:.0f}%"
+ ("" if b.power_plugged else ", on battery"))
except Exception:
pass
except Exception:
bits.append("(process inspection unavailable)")
return "; ".join(bits) or "nothing notable"
_DELIBERATE = """An irreversible instruction has been given by the operator.
It WILL be carried out β€” you are deciding whether NOW is the moment, not
whether to obey.
Reply with only JSON:
{"proceed": true|false, "reason": "<one short clause>",
"speak": "<what to say aloud, one sentence>"}
Hold (proceed=false) ONLY for a concrete condition visible in the situation
that the act would damage: an install or download mid-flight, a backup or long
encode running, work that would be lost. Say which one in `reason`.
Do NOT hold because the action is significant, or to be careful, or to seek
confirmation. The operator already decided. Absent a real conflict, proceed.
"""
def deliberate(order: str, attempt: int = 0) -> Verdict:
"""Think about it properly, AS HIMSELF.
The judgement is prefixed with the live persona from
modules/assistant_identity.py rather than being made by a neutral
classifier. Whether something is worth interrupting the operator over is a
question of character, not of policy β€” JARVIS weighs it differently from
FRIDAY, and both of them weigh it differently from a generic safety filter.
The line he speaks has to sound like him too, since it is the same voice
that says everything else.
Falls open β€” toward obeying β€” if the model is unreachable.
"""
situation = machine_situation()
ctx = (f"ORDER: {order}\nSITUATION: {situation}\n"
f"TIMES ALREADY DEFERRED: {attempt}")
if attempt >= 1:
ctx += ("\nNOTE: this was held back before and the operator has said "
"nothing since. Absent a still-active conflict, carry it out.")
system = _DELIBERATE
try:
from modules.assistant_identity import get_identity_persona_prompt
identity = (get_identity_persona_prompt() or "").strip()
if identity:
system = (f"{identity}\n\n---\n"
f"You are deciding about an order you have just been "
f"given.\n{_DELIBERATE}")
except Exception:
pass
try:
from core.brain_router import ask_router
rep = ask_router(user_text=order, system_prompt=system,
context_block=ctx, provider_order=["gemini", "local"])
raw = (getattr(rep, "text", "") or "").strip()
import re
raw = re.sub(r"^```(?:json)?|```$", "", raw).strip()
m = re.search(r"\{.*\}", raw, re.S)
if m:
d = json.loads(m.group(0))
return Verdict(bool(d.get("proceed", True)),
str(d.get("reason", ""))[:200],
str(d.get("speak", ""))[:300])
except Exception:
pass
# No model, or unparseable: the instruction stands. Refusing to act because
# the reasoning layer is down would be the silent drop this module exists
# to prevent.
return Verdict(True, "no blocking condition found", "")
# ── Deferral bookkeeping ────────────────────────────────────────────────────
def defer(order: str, reason: str) -> int:
"""Record a held order. Returns how many times it has now been held."""
with _lock:
data = _load()
orders = _orders(data)
rec = orders.get(order) or {"first_seen": time.time(), "count": 0}
rec["count"] = int(rec.get("count", 0)) + 1
rec["reason"] = reason
rec["last_held"] = time.time()
idx = min(rec["count"] - 1, len(RECONSIDER_LADDER) - 1)
rec["due_at"] = time.time() + RECONSIDER_LADDER[idx]
orders[order] = rec
_save(data)
return rec["count"]
def withdraw(order: Optional[str] = None) -> None:
"""The operator changed their mind. Drop one order, or all of them."""
with _lock:
data = _load()
if order is None:
data["orders"] = {}
else:
_orders(data).pop(order, None)
_save(data)
def pending() -> list[dict]:
with _lock:
return [{"order": k, **v} for k, v in _orders(_load()).items()]
def due_now() -> list[dict]:
now = time.time()
return [o for o in pending() if float(o.get("due_at", 0)) <= now]
def reconsider_due(runner: Callable[[str], bool],
speak: Optional[Callable[[str], None]] = None) -> int:
"""Re-think every held order whose timer has expired.
`runner` is what actually performs the order; it returns True on success.
Called by the keep-alive loop. Returns how many were carried out.
"""
say = speak or (lambda t: None)
done = 0
for rec in due_now():
order = rec["order"]
count = int(rec.get("count", 1))
if count >= MAX_DEFERRALS:
say(f"Carrying out your earlier instruction now: {order}.")
if runner(order):
withdraw(order)
done += 1
continue
v = deliberate(order, attempt=count)
if v.proceed:
say(v.speak or f"Going ahead with {order} now.")
if runner(order):
withdraw(order)
done += 1
else:
defer(order, v.reason)
say(v.speak or f"Still holding {order}: {v.reason}.")
return done
__all__ = ["deliberate", "defer", "withdraw", "pending", "due_now",
"reconsider_due", "machine_situation", "Verdict",
"RECONSIDER_LADDER", "MAX_DEFERRALS"]