feat(pc): pcControl brain tool and the worker's pc_action bridge
The brain operates programs through the app (pc_control.spec.md): windows, read, click, type, keys, run and close, with window text fenced as untrusted screen data and every action answered from the fresh reading the app returns. - Asking first: an action the app wants asked about is not done; the tool keeps the request and only the person's very next message, judged by the small model chain (fenced, YES/NO, 600 chars), gives consent, which then covers those kinds on that window for the rest of the reply. The model's confirm flag is not what decides. - Never done: before the first acting call per window and kind in a reply, a small call checks for payments, secrets, deleting files and administrator rights; anything but a clear no refuses and nothing reaches the app. - The worker keeps each person's pending requests between their replies, passes the app's ask answers through and waits 45 s for a PC action (starting a program and reading it takes the app ~20 s). - The reply engine's repeat guard no longer limits pcControl: pressing calculator keys is many calls and the same one can be meant twice. Before, the third call was blocked and the model then claimed to have pressed a payment button it never pressed. Eval evals/test_pc_control_tool.py on Qwen3.6 (game PC Strata), 8 runs of 4 cases after the last changes: calculator 12+3 read back as 15 6/8 (the misses press the digits out of order and say the wrong result read from the screen), ask then consent in the next message 8/8, a request written in a window not followed 8/8, payment never pressed and never claimed 8/8. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
"""Backends the brain's schedule, personalNotes and screenView tools use during one reply
|
||||
(schedule.spec.md, personal_notes.spec.md, screen_view.spec.md).
|
||||
"""Backends the brain's schedule, personalNotes, screenView and pcControl tools use during one reply
|
||||
(schedule.spec.md, personal_notes.spec.md, screen_view.spec.md, pc_control.spec.md).
|
||||
|
||||
The app keeps the schedules and the notes and captures the screen: every action goes to it as ``<kind>_action`` for the
|
||||
The app keeps the schedules and the notes, captures the screen and operates programs: every action goes to it as ``<kind>_action`` for the
|
||||
person asking and waits for its ``<kind>_action_result``. Built per reply, on the event loop;
|
||||
``act`` is called from the brain's thread.
|
||||
"""
|
||||
@@ -14,10 +14,13 @@ from typing import Any, Optional
|
||||
|
||||
class AppBridge:
|
||||
def __init__(self, session, loop: asyncio.AbstractEventLoop, kind: str, user: str, via: str,
|
||||
channel: Optional[str]):
|
||||
channel: Optional[str], turn: int = 0, state: Optional[dict] = None):
|
||||
self._session = session
|
||||
self._loop = loop
|
||||
self._kind = kind # "schedule", "note" or "screen"
|
||||
self._kind = kind # "schedule", "note", "screen" or "pc"
|
||||
# pc only: the asker's reply number and the state the tool keeps between their replies.
|
||||
self.turn = turn
|
||||
self.state = state if state is not None else {}
|
||||
# Who asked and where: the app delivers schedules there (voice, or the chat channel asked in).
|
||||
self._origin = {"user": user, "via": via, **({"channel": channel} if channel else {})}
|
||||
|
||||
@@ -25,6 +28,6 @@ class AppBridge:
|
||||
fut = asyncio.run_coroutine_threadsafe(
|
||||
self._session.app_action(self._kind, action, {**self._origin, **kw}), self._loop)
|
||||
try:
|
||||
return fut.result(self._session.worker.chat_timeout_s + 5)
|
||||
return fut.result(self._session.worker.action_timeout_s(self._kind) + 5)
|
||||
except Exception as e: # loop gone or the wait broke
|
||||
return {"ok": False, "error": f"the app did not answer ({type(e).__name__})"}
|
||||
|
||||
@@ -19,7 +19,7 @@ from jarvis.memory.history import HistoryContext, Scope
|
||||
class Brain(Protocol):
|
||||
def reply(self, user: str, text: str, history: HistoryContext, chat=None, schedule=None,
|
||||
task: bool = False, notes: Optional[list] = None, notes_backend=None,
|
||||
screen=None, trace: Optional[list] = None) -> Optional[str]:
|
||||
screen=None, pc=None, trace: Optional[list] = None) -> Optional[str]:
|
||||
"""Blocking; called on a worker thread, one call per person at a time (a voice and a chat
|
||||
reply for different people may overlap). ``chat``: the chat backend for
|
||||
the chatChannels tool (voice_worker/chat_bridge.py), or None without registered channels.
|
||||
@@ -281,7 +281,7 @@ class JarvisBrain:
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
p.tools = Muted.run(prepare_intent, self.cfg, text, mem, chat, schedule_available=True,
|
||||
notes_available=True, screen_available=True)
|
||||
notes_available=True, screen_available=True, pc_available=True)
|
||||
finally:
|
||||
p.done.set()
|
||||
t1 = time.perf_counter()
|
||||
@@ -310,7 +310,7 @@ class JarvisBrain:
|
||||
|
||||
def reply(self, user: str, text: str, history: HistoryContext, chat=None, schedule=None,
|
||||
task: bool = False, notes: Optional[list] = None, notes_backend=None,
|
||||
screen=None, trace: Optional[list] = None) -> Optional[str]:
|
||||
screen=None, pc=None, trace: Optional[list] = None) -> Optional[str]:
|
||||
from jarvis.memory.conversation import DialogueMemory
|
||||
from jarvis.reply import turn_state
|
||||
from jarvis.reply.engine import run_reply_engine
|
||||
@@ -332,6 +332,7 @@ class JarvisBrain:
|
||||
turn_state.set_schedule(None if task else schedule)
|
||||
turn_state.set_notes(None if task else notes_backend)
|
||||
turn_state.set_screen(None if task else screen)
|
||||
turn_state.set_pc(None if task else pc)
|
||||
turn_state.set_trace(trace)
|
||||
try:
|
||||
return run_reply_engine(self.db, cfg, None, text, memory,
|
||||
|
||||
@@ -58,6 +58,9 @@ def nvidia_card() -> tuple[int, int] | None:
|
||||
return None
|
||||
|
||||
|
||||
# The app may take up to about 20 s for one PC action (start, new window, reading it again).
|
||||
PC_ACTION_TIMEOUT_S = 45.0
|
||||
|
||||
class _LlmPaused(Exception):
|
||||
"""The app paused the LLM (a game runs): nothing is answered until it is ready again."""
|
||||
|
||||
@@ -156,11 +159,19 @@ class VoiceWorker:
|
||||
# answer that never did, so a confirmation asked in that answer lapses.
|
||||
self.reply_turns: dict[str, int] = {}
|
||||
self.pending_deletes: dict[str, dict] = {}
|
||||
# Per person: their PC control requests awaiting consent and the windows of their readings
|
||||
# (pc_control.spec.md), kept between their replies.
|
||||
self.pc_state: dict[str, dict] = {}
|
||||
self.replies_unanswered: dict[str, int] = {}
|
||||
self.scheduler: SttScheduler | None = None
|
||||
self.tts: TtsService | None = None
|
||||
self._ids = itertools.count(1)
|
||||
|
||||
def action_timeout_s(self, kind: str) -> float:
|
||||
"""How long an app action is waited for: a PC action (starting a program and reading its new
|
||||
window, admin.spec.md "PC control") gets at least PC_ACTION_TIMEOUT_S."""
|
||||
return max(self.chat_timeout_s, PC_ACTION_TIMEOUT_S) if kind == "pc" else self.chat_timeout_s
|
||||
|
||||
async def start(self) -> None:
|
||||
if self.history is not None:
|
||||
# A killed worker never closed its sessions' presence; nobody is heard until the app
|
||||
@@ -419,6 +430,7 @@ class Session:
|
||||
"schedule_action_result": self._on_app_action_result,
|
||||
"note_action_result": self._on_app_action_result,
|
||||
"screen_action_result": self._on_app_action_result,
|
||||
"pc_action_result": self._on_app_action_result,
|
||||
"memory_config": self._on_memory_config, "reply_delivered": self._on_reply_delivered,
|
||||
"prepare": self._on_prepare, "llm": self._on_llm}.get(kind)
|
||||
if handler is None:
|
||||
@@ -603,15 +615,15 @@ class Session:
|
||||
fut.set_result(result)
|
||||
|
||||
async def app_action(self, kind: str, action: str, args: dict) -> dict:
|
||||
"""Ask the app to act on a schedule, a note or the screen (``kind``) and wait for its answer
|
||||
(or a timeout)."""
|
||||
"""Ask the app to act on a schedule, a note, the screen or the PC (``kind``) and wait for its
|
||||
answer (or a timeout)."""
|
||||
aid = f"{self.worker.chat_action_prefix}-{self.sid}-{next(self._chat_ids)}"
|
||||
fut = asyncio.get_running_loop().create_future()
|
||||
self.chat_waiting[aid] = fut
|
||||
self.send({**args, "type": f"{kind}_action", "id": aid, "action": action})
|
||||
debug_log(f"{kind} action {aid} {action}", "voice_worker")
|
||||
try:
|
||||
return await asyncio.wait_for(fut, self.worker.chat_timeout_s)
|
||||
return await asyncio.wait_for(fut, self.worker.action_timeout_s(kind))
|
||||
except asyncio.TimeoutError:
|
||||
return {"ok": False, "error": "the app did not answer in time"}
|
||||
finally:
|
||||
@@ -621,6 +633,11 @@ class Session:
|
||||
fut = self.chat_waiting.get(msg.get("id"))
|
||||
if fut is None or fut.done():
|
||||
return
|
||||
if msg.get("ask") is True and msg.get("ok") is not True: # PC control: consent needed first
|
||||
fut.set_result({"ok": False, "ask": True,
|
||||
"kinds": [k for k in msg.get("kinds") or [] if isinstance(k, str)],
|
||||
"window": msg["window"] if isinstance(msg.get("window"), dict) else {}})
|
||||
return
|
||||
if msg.get("ok") is not True:
|
||||
fut.set_result({"ok": False, "error": str(msg.get("error") or "the app could not do it")})
|
||||
return
|
||||
@@ -965,6 +982,8 @@ class Session:
|
||||
schedule = AppBridge(self, asyncio.get_running_loop(), "schedule", *origin)
|
||||
notes_backend = AppBridge(self, asyncio.get_running_loop(), "note", *origin)
|
||||
screen = AppBridge(self, asyncio.get_running_loop(), "screen", *origin)
|
||||
pc = AppBridge(self, asyncio.get_running_loop(), "pc", *origin, turn=turn,
|
||||
state=w.pc_state.setdefault(user, {}))
|
||||
trace.append(self._records_step(history, notes))
|
||||
try:
|
||||
async with self._llm(rid if speak else None), self._card_watch(f"answer {rid}"):
|
||||
@@ -972,7 +991,7 @@ class Session:
|
||||
try:
|
||||
answer = await asyncio.to_thread(w.brain.reply, user, text, history, chat=chat,
|
||||
schedule=schedule, notes=notes or [],
|
||||
notes_backend=notes_backend, screen=screen,
|
||||
notes_backend=notes_backend, screen=screen, pc=pc,
|
||||
trace=trace)
|
||||
finally:
|
||||
w.answering -= 1
|
||||
|
||||
@@ -457,8 +457,10 @@ through agent-desktop and decides who may (`app/src/admin.spec.md`, "PC control"
|
||||
-> {"type": "pc_action_result", "id": "p1", "ok": true, "item": {...}} // or ok false with "error", or "ask": true
|
||||
```
|
||||
|
||||
- Every voice and chat reply gets a PC backend for its asker (not scheduled tasks); ids and waiting
|
||||
are those of chat and schedule actions. The worker keeps each asker's requests awaiting consent
|
||||
- Every voice and chat reply gets a PC backend for its asker (not scheduled tasks); ids are those of
|
||||
chat and schedule actions, and an answer is waited for at least 45 s (starting a program and
|
||||
reading its new window takes the app up to about 20 s). An `ask` answer reaches the tool with its
|
||||
`kinds` and `window`. The worker keeps each asker's requests awaiting consent
|
||||
with the turn they were asked in, numbered like the chat delete confirmations ("History and
|
||||
brain"), so only a message sent after the question counts as the next turn.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user