Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(chat): a message answers the call a turn waits on, and the wait does not time out (RFC-0007 AP.4c)
trohitg9d43d7aafb5d
diff --git a/server/services/approvals/store.py b/server/services/approvals/store.pyindex cbc60936..3256c817 100644--- a/server/services/approvals/store.py+++ b/server/services/approvals/store.py@@ -274,9 +274,10 @@ async def list_approvals(run_id: Optional[str] = None,kind: Optional[str] = None,ids: Optional[Sequence[str]] = None,+ decision_key: Optional[str] = None,limit: int = 50,) -> List[ApprovalRequest]:- """Newest first."""+ """Newest first. ``decision_key``: the rows whose latest decision had it."""query = select(ApprovalRequest)if owner_id is not None:query = query.where(ApprovalRequest.owner_id == owner_id)@@ -292,6 +293,8 @@ async def list_approvals(query = query.where(or_(ApprovalRequest.kind == kind, ApprovalRequest.kind.is_(None)) if kind == "gate" else ApprovalRequest.kind == kind)if ids is not None:query = query.where(ApprovalRequest.id.in_(tuple(ids)))+ if decision_key is not None:+ query = query.where(ApprovalRequest.decision_key == decision_key)query = query.order_by(ApprovalRequest.created_at.desc()).limit(max(1, min(int(limit), 100)))async with database.get_session() as session:return list((await session.execute(query)).scalars().all())diff --git a/server/services/approvals/waiting.py b/server/services/approvals/waiting.pyindex 93390745..8bbd5892 100644--- a/server/services/approvals/waiting.py+++ b/server/services/approvals/waiting.py@@ -11,6 +11,13 @@ pending, waits for a ``nudge`` Signal or the row's expiry, then reads again.- ``reconcile.renudge_turns``, from the chat watchdog's round: a decidedrow its wait has not read yet is nudged again, in case the first nudgewas lost.+- :func:`decline_with_message`: a message the owner sends while the turn+ waits declines its calls, the message their note (RFC-0007 D3), and the+ turn reads that the owner wrote instead of answering.+- :func:`run_waited`: the chat watchdog does not count the wait toward the+ run's time, and the owner's answer starts the run's window again (D2).+- :func:`cancel_waits`: a Reset, or a run whose workflow closed, ends the+ rows nothing waits on any more.A nudge to a wait that has ended, or with no workflow engine, is dropped:the wait reads the row at its expiry in any case. Never imports ``nodes/``.@@ -19,7 +26,7 @@ the wait reads the row at its expiry in any case. Never imports ``nodes/``.from __future__ import annotationsfrom datetime import datetime, timedelta, timezone-from typing import Any, Dict+from typing import Any, Dict, List, Optional, Sequencefrom sqlalchemy import update@@ -34,6 +41,8 @@ logger = get_logger(__name__)WORKFLOW_NAME = "ApprovalWorkflow"#: The row's ``runtime`` when its turn waits on it.TURN = "turn"+#: The decision key prefix of a message that declined a waiting call.+MESSAGE_KEY = "chat:"def _utcnow() -> datetime:@@ -75,18 +84,62 @@ async def nudge_on_change(change: ApprovalChange) -> None:await nudge(change.approval_id, client)-async def cancel_waits(database: Any, workflow_id: str, generation: int) -> int:- """End the open rows a generation's turns wait on: a Reset terminated- those turns, and their waits with them (the approval gate's own rows- are its node's to end)."""- cancelled = await store.cancel_open(database, workflow_id=workflow_id, generation=generation, runtime=TURN)+async def cancel_waits(+ database: Any, workflow_id: str, generation: Optional[int] = None, *, run_ids: Optional[Sequence[str]] = None+) -> int:+ """End the open rows turns waited on when nothing waits on them any+ more: a Reset's generation (it terminated those turns, and their waits+ with them), or chat runs whose workflow closed (``run_ids``). The+ approval gate's own rows are its node's to end."""+ cancelled = await store.cancel_open(database, workflow_id=workflow_id, generation=generation, run_ids=run_ids, runtime=TURN)for row in cancelled:await notify_approval_changed(change_of(row, "cancelled"))if cancelled:- logger.info("Cancelled the calls a reset turn waited on", workflow_id=workflow_id, count=len(cancelled))+ logger.info("Cancelled the calls ended turns waited on", workflow_id=workflow_id, count=len(cancelled))return len(cancelled)+async def run_waited(database: Any, run_id: str, *, since: datetime) -> bool:+ """Whether a chat run's turn waits on the owner's answer to a call, or+ has had their answer since ``since``."""+ for row in await store.list_approvals(database, run_id=run_id, kind="tool_call", limit=100):+ decided = store.aware(row.decided_at)+ if row.runtime == TURN and (row.status == "pending" or (decided is not None and decided > since)):+ return True+ return False+++def message_key(message_uid: str) -> str:+ """The decision key a message declines waiting calls under: its id, so+ the same message sent again finds them (:func:`declined_with`)."""+ return f"{MESSAGE_KEY}{message_uid}"+++async def decline_with_message(database: Any, *, run_id: str, owner: str, message: str, decision_key: str) -> List[ApprovalRequest]:+ """Decline the calls a chat run's turn waits on, because the owner sent+ a message instead of answering: the message is their note, on the card+ and in what the turn reads. A row another decision settled first is left+ as it is."""+ from services.approvals.decisions import DecisionRefused, apply++ declined: List[ApprovalRequest] = []+ for row in await store.list_approvals(database, owner_id=owner, run_id=run_id, status="pending", kind="tool_call", limit=100):+ if row.runtime != TURN:+ continue+ try:+ moved, _ = await apply(database, row, decision="discard", decision_key=decision_key, actor=owner, note=message)+ except DecisionRefused:+ continue+ await notify_approval_changed(change_of(moved, "decided"))+ declined.append(moved)+ return declined+++async def declined_with(database: Any, decision_key: str) -> List[ApprovalRequest]:+ """The calls a message declined (:func:`decline_with_message`)."""+ return await store.list_approvals(database, decision_key=decision_key, status="discarded")++async def mark_read(database: Any, approval_id: str) -> None:"""The wait took the row's answer, or nothing waits for it any more:nothing nudges it again."""@@ -101,9 +154,10 @@ async def mark_read(database: Any, approval_id: str) -> None:async def read(database: Any, approval_id: str, *, cancel: bool = False) -> Dict[str, Any]:"""The answer a wait gets: ``{status, revision, expires_at}`` while the- row is pending, else ``{status, revision, note?}``. A row past its expiry- ends ``expired`` first; with ``cancel`` (the wait was cancelled) a- pending row ends ``cancelled``. A row that is gone reads as cancelled.+ row is pending, else ``{status, revision, note?, by_message?}``+ (``by_message``: a message the owner sent declined it). A row past its+ expiry ends ``expired`` first; with ``cancel`` (the wait was cancelled)+ a pending row ends ``cancelled``. A row that is gone reads as cancelled.An answer other than ``approved`` marks the row read; a claim marks anapproved one when its call runs."""from services.approvals.decisions import expire_if_due@@ -124,7 +178,25 @@ async def read(database: Any, approval_id: str, *, cancel: bool = False) -> Dictreturn {"status": "pending", "revision": row.revision, "expires_at": expires.isoformat()}if row.status != "approved":await mark_read(database, row.id)- return {"status": row.status, "revision": row.revision, **({"note": row.note} if row.note else {})}---__all__ = ["TURN", "WORKFLOW_NAME", "cancel_waits", "engine", "mark_read", "nudge", "nudge_on_change", "read", "wait_workflow_id"]+ answer = {"status": row.status, "revision": row.revision, **({"note": row.note} if row.note else {})}+ if row.status == "discarded" and (row.decision_key or "").startswith(MESSAGE_KEY):+ answer["by_message"] = True+ return answer+++__all__ = [+ "MESSAGE_KEY",+ "TURN",+ "WORKFLOW_NAME",+ "cancel_waits",+ "decline_with_message",+ "declined_with",+ "engine",+ "mark_read",+ "message_key",+ "nudge",+ "nudge_on_change",+ "read",+ "run_waited",+ "wait_workflow_id",+]diff --git a/server/services/chat/handlers.py b/server/services/chat/handlers.pyindex 13834804..7150f3f9 100644--- a/server/services/chat/handlers.py+++ b/server/services/chat/handlers.py@@ -228,6 +228,33 @@ async def _dispatch(logger.info("Chat message dispatched", session_id=session_id, run_id=run_id)+def _decline_key(session_id: str, client_message_id: Any) -> str:+ """The decision key a message declines waiting calls under: its message+ id, so the same message sent again finds what it declined."""+ from uuid import uuid4++ from services.approvals.waiting import message_key++ try:+ return message_key(ledger.client_message_uid(session_id, client_message_id))+ except ValueError:+ return message_key(f"m_{uuid4().hex}")+++def _declined(rows: List[Any], timestamp: str, delivery: Optional[str]) -> Dict[str, Any]:+ """The answer to a message that declined the calls its run waited on."""+ response: Dict[str, Any] = {+ "success": True,+ "timestamp": timestamp,+ "message_id": None,+ "run_id": None,+ "declined": {"run_id": rows[0].run_id, "approval_ids": [row.id for row in rows]},+ }+ if delivery is not None:+ response["delivery"] = delivery+ return response++# ``message`` is checked below: a message may be only files.@ws_handler()async def handle_send_chat_message(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:@@ -246,7 +273,14 @@ async def handle_send_chat_message(data: Dict[str, Any], websocket: WebSocket) -``uploads/`` (``services/chat/attachments.py``: rebuilt from the files,at most six; refused with ``attachment_rejected``); a message may beonly files. ``options.web: false`` keeps the employee off web search for- this message."""+ this message.++ While the session's run waits on the owner's answer to a call its turn+ holds, a plain message (no ``ui_event``, no files) answers that call:+ it declines it, the message its note (RFC-0007 D3,+ ``services/approvals/waiting.py``), saves no message, starts no run and+ answers ``{message_id: null, run_id: null, declined: {run_id,+ approval_ids}, delivery}``. Sent again, it answers the same."""message = data.get("message")raw_attachments = data.get("attachments")if not isinstance(message, str) or not (message.strip() or raw_attachments):@@ -299,6 +333,14 @@ async def handle_send_chat_message(data: Dict[str, Any], websocket: WebSocket) -except ValueError as exc:return {"success": False, "error": "invalid_request", "detail": str(exc)}+ decline_key = None+ if scope.workflow_id is not None and press is None and not attachments:+ from services.approvals.waiting import declined_with++ decline_key = _decline_key(session_id, data.get("client_message_id"))+ earlier = await declined_with(database, decline_key)+ if earlier:+ return _declined(earlier, timestamp, delivery)try:admission = await ledger.admit_message(database,@@ -316,6 +358,15 @@ async def handle_send_chat_message(data: Dict[str, Any], websocket: WebSocket) -attachments=attachments or None,)except ledger.RunInProgress as exc:+ if decline_key is not None:+ from services.approvals.waiting import decline_with_message+ from services.authz.ws_surface import execution_principal++ declined = await decline_with_message(+ database, run_id=exc.run.run_id, owner=execution_principal({}, websocket), message=message, decision_key=decline_key+ )+ if declined:+ return _declined(declined, timestamp, delivery)return {"success": False, "error": "run_in_progress", "run_id": exc.run.run_id}except ValueError as exc:return {"success": False, "error": "invalid_request", "detail": str(exc)}diff --git a/server/services/chat/ledger.py b/server/services/chat/ledger.pyindex 8c4c1b38..ff2efc4c 100644--- a/server/services/chat/ledger.py+++ b/server/services/chat/ledger.py@@ -30,6 +30,11 @@ was saved, ``interrupted`` otherwise.and its lane alive. The watchdog excludes intentionally suspended generationsand uses their successful Resume time for a fresh timeout window.+**A turn waiting for the owner's answer** to a call it holds (RFC-0007 D2,+``services/approvals/waiting.py``) is not timed out, and the answer starts a+fresh window. When the run's workflow closes, the calls it waited on are+cancelled.+**Legacy Stop** (``request_stop``) ends a run nothing has picked up at once(``stopped``, no reply) and moves a running run to ``stopping``. A runningrun stops itself: its agent's next model step returns what it has written so@@ -764,7 +769,10 @@ async def _sweep_one(if resumed is not None:started = max(started, resumed)if now - started > longest:- return await fail_run(database, run, code="timed_out", message="The employee took too long to answer.")+ from services.approvals.waiting import run_waited++ if not await run_waited(database, run.run_id, since=now - longest):+ return await fail_run(database, run, code="timed_out", message="The employee took too long to answer.")if temporal_status is None or not run.temporal_workflow_id or now - started < _CLOSED_GRACE:return Noneif await temporal_status(run.temporal_workflow_id, run.temporal_run_id) is not True:@@ -772,6 +780,10 @@ async def _sweep_one(current = await get_run(database, run.run_id)if current is None or current.state not in ("running", "stopping"):return None+ if current.workflow_id:+ from services.approvals.waiting import cancel_waits++ await cancel_waits(database, current.workflow_id, run_ids=[current.run_id])await _seal(database, current)if await _message_exists(database, current.reply_message_uid):return await _settle(database, current, await _success_values(database, current, "stopped" if current.state == "stopping" else "success"))diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.pyindex 9317987c..1e9558f2 100644--- a/server/services/temporal/agent_workflow.py+++ b/server/services/temporal/agent_workflow.py@@ -427,8 +427,14 @@ def _held_for_owner(result: Any) -> Optional[str]:def _owner_answer(answer: Dict[str, Any]) -> Dict[str, Any]:"""What the model reads when the owner's answer ran nothing (RFC-0007- §4.5). Never ``requires_user_action``: the turn goes on."""+ §4.5). Never ``requires_user_action``: the turn goes on. A message the+ owner sent instead of answering (D3) may ask for something else, so it+ says nothing about trying again."""status = answer.get("status")+ if status == "discarded" and answer.get("by_message"):+ message = answer.get("note")+ tail = f" Their message: {message}" if message else ""+ return {"success": False, "status": "declined", "error": "The owner sent a message instead of answering; nothing happened." + tail}if status == "discarded":note = answer.get("note")tail = f" Their note: {note}" if note else " Don't try to get the same outcome another way."diff --git a/server/tests/services/approvals/test_waiting.py b/server/tests/services/approvals/test_waiting.pyindex 0379a305..1ad108dd 100644--- a/server/tests/services/approvals/test_waiting.py+++ b/server/tests/services/approvals/test_waiting.py@@ -40,7 +40,7 @@ class FakeClient:return Handle()-async def held(harness, call_id="call_1"):+async def held(harness, call_id="call_1", run_id=None):await rules.set_mode(harness.database, "wf", "outside")context = {"node_id": "wf:whatsappSend:1",@@ -54,6 +54,7 @@ async def held(harness, call_id="call_1"):"tool_args": WHATSAPP,"approval_wait_version": 1,"approval_wait": True,+ **({"chat_run_id": run_id} if run_id else {}),}await tool_calls.check(context, get_node_class("whatsappSend"))return next(row for row in await store.list_approvals(harness.database, status="pending") if row.tool_call_id == call_id)@@ -82,6 +83,24 @@ async def test_a_wait_reads_a_pending_row_until_it_is_decided(harness):assert (await store.get(harness.database, row.id)).consumed_at is not None+async def test_a_message_the_owner_sent_instead_declines_what_its_turn_waits_on(harness):+ # RFC-0007 D3: the wait reads that a message, not the card, declined it.+ waited, elsewhere = await held(harness, run_id="r_1"), await held(harness, "call_2", run_id="r_2")+ key = waiting.message_key("m_1")+ declined = await waiting.decline_with_message(+ harness.database, run_id="r_1", owner="owner", message="Call her instead.", decision_key=key+ )+ assert [row.id for row in declined] == [waited.id]+ assert await waiting.read(harness.database, waited.id) == {+ "status": "discarded",+ "revision": waited.revision + 1,+ "note": "Call her instead.",+ "by_message": True,+ }+ assert [row.id for row in await waiting.declined_with(harness.database, key)] == [waited.id]+ assert (await store.get(harness.database, elsewhere.id)).status == "pending"++async def test_an_approved_row_is_left_for_its_claim(harness):row = await held(harness)await decide(row, "send", "s1")diff --git a/server/tests/services/chat/_helpers.py b/server/tests/services/chat/_helpers.pyindex 824976d8..ff1f23f2 100644--- a/server/tests/services/chat/_helpers.py+++ b/server/tests/services/chat/_helpers.py@@ -72,6 +72,31 @@ async def talking(database, workflow_id: str = "wf", status: str = "running", geawait add_control(database, workflow_id, status, generation=generation, nodes=[chat_trigger(workflow_id)])+async def held_call(database, approval_id: str, run_id: str, *, runtime: str = "turn") -> None:+ """A call the run's agent made, held for the owner: one its turn waits+ on (``turn``, RFC-0007), or a draft."""+ from models.approvals import ApprovalRequest++ async with database.get_session() as session:+ session.add(+ ApprovalRequest(+ id=approval_id,+ idempotency_key=f"k-{approval_id}",+ owner_id="owner",+ workflow_id="wf",+ node_id="wf:whatsappSend:1",+ kind="tool_call",+ channel="WhatsApp",+ action="WhatsApp message",+ recipient="447700900123",+ runtime=runtime,+ run_id=run_id,+ draft_text="On my way",+ )+ )+ await session.commit()++def chat_updates(frames) -> List[Dict[str, Any]]:return [frame["data"]["data"] for frame in frames if frame["type"] == "chat.updated"]diff --git a/server/tests/services/chat/test_handlers.py b/server/tests/services/chat/test_handlers.pyindex a1402f66..d2b9c36d 100644--- a/server/tests/services/chat/test_handlers.py+++ b/server/tests/services/chat/test_handlers.py@@ -15,6 +15,7 @@ from tests.services.chat._helpers import (add_control,chat_trigger,chat_updates,+ held_call,saved_workflow,talking,updates_at_dispatch,@@ -97,6 +98,44 @@ async def test_a_resent_message_returns_the_first_send_and_dispatches_once(chat)assert bad["error"] == "invalid_request"+async def test_a_message_while_the_turn_waits_on_a_call_declines_it(chat):+ # RFC-0007 D3: the message answers the call, as its note, on the card;+ # nothing is saved in the thread and no run starts.+ from services.approvals import store++ await talking(chat.database)+ first = await send(chat)+ await held_call(chat.database, "ap_1", first["run_id"])+ declined = await send(chat, "No, call her instead.", client_message_id="c-2")+ assert declined == {+ "success": True,+ "timestamp": "t",+ "message_id": None,+ "run_id": None,+ "delivery": "now",+ "declined": {"run_id": first["run_id"], "approval_ids": ["ap_1"]},+ }+ row = await store.get(chat.database, "ap_1")+ assert (row.status, row.note) == ("discarded", "No, call her instead.")+ assert [saved["message"] for saved in await chat.database.read_chat_messages("wf")] == ["Book Saturday"]+ assert len(chat.dispatched) == 1+ # Sent again, it answers the same, even once the run has ended.+ await ledger.fail_run(chat.database, await ledger.get_run(chat.database, first["run_id"]), code="interrupted", message="Ended.")+ assert await send(chat, "No, call her instead.", client_message_id="c-2") == declined+ assert len(chat.dispatched) == 1+++async def test_a_draft_is_no_call_a_message_answers(chat):+ # Only a call the turn waits on: a draft leaves the lane busy.+ from services.approvals import store++ await talking(chat.database)+ first = await send(chat)+ await held_call(chat.database, "ap_1", first["run_id"], runtime="temporal")+ assert await send(chat, "No.", client_message_id="c-2") == {"success": False, "error": "run_in_progress", "run_id": first["run_id"]}+ assert (await store.get(chat.database, "ap_1")).status == "pending"++async def test_no_run_when_no_deployed_chat_trigger_answers_the_session(chat):# A graph without a chat trigger, then one whose trigger listens to# another session, then a disabled one: the message is saved, no run.diff --git a/server/tests/services/chat/test_ledger.py b/server/tests/services/chat/test_ledger.pyindex 63894d97..8d1207ec 100644--- a/server/tests/services/chat/test_ledger.py+++ b/server/tests/services/chat/test_ledger.py@@ -13,7 +13,7 @@ from sqlalchemy import textfrom models.chat import ChatRunfrom services.chat import ledger-from tests.services.chat._helpers import add_control, chat_updates+from tests.services.chat._helpers import add_control, chat_updates, held_callasync def admit(database, session_id="wf", *, text_="Book Saturday", track=True, state="pending", client_message_id=None):@@ -356,6 +356,57 @@ async def test_a_run_past_its_longest_ends_as_timed_out(database, hub):assert (await ledger.get_run(database, admission.run.run_id)).error_code == "timed_out"+async def answered(database, approval_id, at):+ """The owner answered a held call at ``at``."""+ from sqlalchemy import update++ from models.approvals import ApprovalRequest++ async with database.get_session() as session:+ await session.execute(update(ApprovalRequest).where(ApprovalRequest.id == approval_id).values(status="discarded", decided_at=at))+ await session.commit()+++async def test_a_turn_waiting_for_the_owner_is_not_timed_out(database, hub):+ # RFC-0007 D2: the wait does not count, and the answer starts a fresh window.+ admission = await admit(database)+ run = await started(database, admission)+ await age(database, run.run_id, started_at=LONG_AGO)+ await held_call(database, "ap_1", run.run_id)+ assert await sweep(database) == []+ await answered(database, "ap_1", NOW - timedelta(hours=1))+ assert await sweep(database) == []+ await answered(database, "ap_1", LONG_AGO)+ assert await sweep(database) == [run.run_id]+ assert (await ledger.get_run(database, run.run_id)).error_code == "timed_out"+++async def test_a_draft_does_not_hold_a_run_past_its_longest(database, hub):+ admission = await admit(database)+ run = await started(database, admission)+ await age(database, run.run_id, started_at=LONG_AGO)+ await held_call(database, "ap_1", run.run_id, runtime="temporal")+ assert await sweep(database) == [run.run_id]+++async def test_a_run_whose_workflow_closed_cancels_the_calls_its_turn_waited_on(database, hub):+ from services.approvals import store++ admission = await admit(database)+ run = await started(database, admission)+ await age(database, run.run_id, started_at=NOW - timedelta(minutes=5))+ await held_call(database, "ap_wait", run.run_id)+ await held_call(database, "ap_draft", run.run_id, runtime="temporal")++ async def closed(*_):+ return True++ assert await sweep(database, temporal_status=closed) == [run.run_id]+ assert (await store.get(database, "ap_wait")).status == "cancelled"+ # A draft outlives its run: the owner can still send it.+ assert (await store.get(database, "ap_draft")).status == "pending"++@pytest.mark.parametrize(("replied", "state", "code"), [(True, "finished", None), (False, "error", "interrupted")])async def test_a_run_whose_workflow_closed_without_finishing_is_ended(database, hub, replied, state, code):admission = await admit(database)diff --git a/server/tests/temporal/test_agent_approval_wait_integration.py b/server/tests/temporal/test_agent_approval_wait_integration.pyindex 57bcc87b..cb0a2e41 100644--- a/server/tests/temporal/test_agent_approval_wait_integration.py+++ b/server/tests/temporal/test_agent_approval_wait_integration.py@@ -291,6 +291,15 @@ def test_the_flag_rides_a_generation_from_start_to_its_tool_calls() -> None:assert "approval_wait_version" in _INHERITED_SCOPE_KEYS+def test_the_turn_reads_a_message_the_owner_sent_instead_of_answering() -> None:+ # RFC-0007 D3: it may ask for something else, so nothing says don't retry.+ from services.temporal.agent_workflow import _owner_answer++ answer = _owner_answer({"status": "discarded", "note": "Call her instead.", "by_message": True})+ assert answer["error"] == "The owner sent a message instead of answering; nothing happened. Their message: Call her instead."+ assert answer["status"] == "declined" and answer["success"] is False++def test_a_turn_waits_for_the_owner_and_runs_the_allowed_call() -> None:result = subprocess.run([sys.executable, "-m", "tests.temporal.test_agent_approval_wait_integration"],