Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(approvals): turn rows and the decline note (RFC-0007 AP.2b, 1 of 2)
trohitg1ee6c0237bb4
diff --git a/server/core/database.py b/server/core/database.pyindex dd7e13d5..63d089ba 100644--- a/server/core/database.py+++ b/server/core/database.py@@ -655,8 +655,8 @@ class Database:async def _migrate_approvals(self):"""Give an older ``approval_requests`` table the columns approvals v2- added (held tool calls, Undo and Restore, outcomes), and an older- ``workflow_rules`` table its ``mode`` (RFC-0007). A draft approved+ added (held tool calls, Undo and Restore, outcomes; RFC-0007's decline+ ``note``), and an older ``workflow_rules`` table its ``mode``. A draft approvedbefore them was handed on when it was decided, so it gets that as``consumed_at`` and never reads as still undoable."""columns_added = {@@ -682,6 +682,7 @@ class Database:"outcome": "VARCHAR(20)","outcome_error": "VARCHAR(1000)","outcome_at": "DATETIME",+ "note": "VARCHAR(50000)",}try:async with self.engine.begin() as conn:diff --git a/server/models/approvals.py b/server/models/approvals.pyindex 35845304..5e95289f 100644--- a/server/models/approvals.py+++ b/server/models/approvals.py@@ -33,7 +33,9 @@ one of three kinds (``kind``):failed -> cancelled Dismiss (an effect row)pending | approved | discarded -> expired | cancelled-Every move is a compare-and-swap on ``revision``. ``ApprovalDecision`` keeps+A held call its agent's turn waits on (``runtime: turn``, RFC-0007 §4.6) has+no Undo or Restore; a Retry makes it a draft. A Discard keeps the owner's+``note``. Every move is a compare-and-swap on ``revision``. ``ApprovalDecision`` keepsthe owner's decisions; the same ``decision_key`` again is a no-op.``WorkflowRule`` is a workflow's Ask first rule, read when something would@@ -67,6 +69,8 @@ class ApprovalRequest(SQLModel, table=True):generation: int = Field(default=0)execution_id: Optional[str] = Field(default=None, max_length=255)#: ``temporal`` or ``local``: a local wait cannot outlive its process.+ #: ``turn``: a held call its agent's turn waits on (RFC-0007 §4.6); it+ #: has no Undo or Restore, and its turn hears how it went.runtime: str = Field(default="local", max_length=20)status: str = Field(default="pending", index=True, max_length=20)#: ``gate``, ``tool_call`` or ``effect`` (see the module docstring).@@ -116,6 +120,9 @@ class ApprovalRequest(SQLModel, table=True):# ---- the decision and what came of it ----#: ``owner``, or ``auto`` when Ask first was off.approved_by: Optional[str] = Field(default=None, max_length=20)+ #: What the owner told the employee on declining (the chat's message+ #: limit).+ note: Optional[str] = Field(default=None, max_length=50000)#: Undo works until this; then it goes.grace_until: Optional[datetime] = Field(default=None, sa_column=Column(DateTime(timezone=True), nullable=True))#: A discarded draft can be restored until this.diff --git a/server/services/approvals/decisions.py b/server/services/approvals/decisions.pyindex 7910cb34..965c9aa7 100644--- a/server/services/approvals/decisions.py+++ b/server/services/approvals/decisions.py@@ -16,6 +16,11 @@off midway and may have happened, once the owner has checked it. Nothingruns.+A discard may carry the owner's ``note`` for the employee. A held call its+agent's turn waits on (``runtime: turn``, RFC-0007 §4.6) gets no Undo grace+and no Restore: its turn runs it, or hears the decline, at once. A retry of+one makes it a draft again, since that turn is over.+Each decision is a compare-and-swap on the row's revision, recorded with its``decision_key`` in the same transaction (``approval_decisions``): the samekey again returns the row as it is. Never imports ``nodes/``.@@ -36,6 +41,8 @@ from services.approvals.contract import DEFAULT_TIMEOUT_HOURS, RESTORE_SECONDS,from services.approvals.listeners import change_of, notify_approval_changedDECISIONS = ("send", "undo", "discard", "restore", "retry", "dismiss")+#: The longest note a discard keeps (the chat's message limit).+MAX_NOTE = 50000#: Why a decision on a row that already moved on was refused.SETTLED_ERRORS = {"approved": "already_decided",@@ -126,23 +133,29 @@ async def decide(text: Any = None,subject: Any = None,confirm: bool = False,+ note: Any = None,now: Optional[datetime] = None,) -> Tuple[ApprovalRequest, bool]:"""Apply a decision. Returns ``(row, idempotent)``; raises:class:`DecisionRefused` when it does not apply."""- if decision not in DECISIONS or not decision_key:+ if decision not in DECISIONS or not decision_key or not (note is None or isinstance(note, str)):raise DecisionRefused("invalid_request")+ if note is not None and len(note.strip()) > MAX_NOTE:+ raise DecisionRefused("invalid_request", f"Keep the note under {MAX_NOTE} characters.")if await store.find_decision(database, row.id, decision_key) is not None:return (await store.get(database, row.id)) or row, Truenow = now or _utcnow()row = await expire_if_due(database, row, now)record = (decision, decision_key, actor)kind = row.kind or "gate"+ turn = row.runtime == "turn"if decision == "send":if row.status != "pending":raise _settled(row)values = _send_values(row, text, subject, now)values["decision_key"] = decision_key+ if turn:+ values["grace_until"] = Nonemoved = await _move(database, row, ("pending",), "approved", values, record)elif decision == "undo":grace = store.aware(row.grace_until)@@ -153,11 +166,13 @@ async def decide(elif decision == "discard":if row.status != "pending":raise _settled(row)- if kind == "gate":+ if turn:+ restore = None+ elif kind == "gate":restore = now + timedelta(seconds=RESTORE_SECONDS)else:restore = store.aware(row.expires_at) or now + timedelta(hours=DEFAULT_TIMEOUT_HOURS)- values = {"decided_at": now, "restore_until": restore, "decision_key": decision_key}+ values = {"decided_at": now, "restore_until": restore, "decision_key": decision_key, "note": (note or "").strip() or None}moved = await _move(database, row, ("pending",), "discarded", values, record)elif decision == "restore":restore = store.aware(row.restore_until)@@ -183,6 +198,8 @@ async def decide("decided_at": now,"approved_by": "owner",}+ if turn:+ values["runtime"] = "temporal"moved = await _move(database, row, ("failed",), "approved", values, record)return moved, Falsediff --git a/server/services/approvals/execution.py b/server/services/approvals/execution.pyindex e5d3a161..cb73a703 100644--- a/server/services/approvals/execution.py+++ b/server/services/approvals/execution.py@@ -208,14 +208,16 @@ def update_note(row: Any) -> Optional[str]:payload["edited_by_owner"] = Trueif row.status == "failed" and row.outcome_error:payload["error"] = row.outcome_error[:300]+ if row.status == "discarded" and row.note:+ payload["owner_note"] = row.notereturn f"[update]{json.dumps(payload, ensure_ascii=False, separators=(', ', ': '))}[/update]"async def tell_employee(database: Any, row: Any) -> None:"""Leave the outcome for the employee's next turn in the chat (its- session is the workflow's)."""+ session is the workflow's). A call its turn waits on hears it there."""text = update_note(row)- if text is None or not row.workflow_id:+ if text is None or not row.workflow_id or row.runtime == "turn":returntry:from services.chat.notes import upsert_notediff --git a/server/services/approvals/handlers.py b/server/services/approvals/handlers.pyindex 99a652e6..5c9a8337 100644--- a/server/services/approvals/handlers.py+++ b/server/services/approvals/handlers.py@@ -9,10 +9,12 @@ on its way) or ``recent`` (everything, newest first); default ``pending``.``get_approvals {approval_ids: [...]}`` -> ``{approvals, server_time}``.``decide_approval {approval_id, decision, decision_key, text?, subject?,-confirm?}`` -> ``{approval, idempotent?, will_send_on_resume}``. Decisions:-``send``, ``undo``, ``discard``, ``restore``, ``retry``, ``dismiss``-(services/approvals/decisions.py). Sending a held tool call starts its send-(services/approvals/execution.py). Errors: ``already_decided``,+confirm?, note?}`` -> ``{approval, idempotent?, will_send_on_resume}``.+Decisions: ``send``, ``undo``, ``discard`` (with the owner's ``note``),+``restore``, ``retry``, ``dismiss`` (services/approvals/decisions.py).+Sending a held tool call starts its send (services/approvals/execution.py),+unless its agent's turn waits on it (``runtime: turn``) and runs it itself.+Errors: ``already_decided``,``expired``, ``cancelled``, ``too_late``, ``confirm_required``,``approval_conflict``, ``send_unavailable``, ``not_found``,``invalid_request``.@@ -186,6 +188,7 @@ async def handle_decide_approval(data: Dict[str, Any], websocket: WebSocket) ->text=data.get("text"),subject=data.get("subject"),confirm=bool(data.get("confirm")),+ note=data.get("note"),)except decisions.DecisionRefused as refused:current = await store.get(database, approval_id) or row@@ -199,7 +202,7 @@ async def handle_decide_approval(data: Dict[str, Any], websocket: WebSocket) ->await notify_approval_changed(change_of(decided, _STAGES.get(decision, "decided")))if decided.status == "discarded":await execution.tell_employee(database, decided)- if (decided.kind or "gate") == "tool_call" and decision in ("send", "retry"):+ if (decided.kind or "gate") == "tool_call" and decision in ("send", "retry") and decided.runtime != "turn":try:decided = await _start_or_revert(database, decided, row)except execution.SendUnavailable:@@ -216,7 +219,9 @@ async def handle_decide_approval(data: Dict[str, Any], websocket: WebSocket) ->"success": True,"approval": store.summary(decided, deployment_state=state),# A paused employee's run holds the approved draft until Resume.- "will_send_on_resume": (decided.kind or "gate") == "gate" and decided.status == "approved" and state in ("paused", "pausing"),+ "will_send_on_resume": ((decided.kind or "gate") == "gate" or decided.runtime == "turn")+ and decided.status == "approved"+ and state in ("paused", "pausing"),}diff --git a/server/services/approvals/store.py b/server/services/approvals/store.pyindex ecfb4368..1c3ffea4 100644--- a/server/services/approvals/store.py+++ b/server/services/approvals/store.py@@ -419,6 +419,8 @@ def summary(row: ApprovalRequest, *, deployment_state: Optional[str] = None, nowout["context_excerpt"] = row.context_excerptif row.approved_by:out["approved_by"] = row.approved_by+ if row.note:+ out["note"] = row.noteif row.edited:out["edited"] = Truegrace = aware(row.grace_until)diff --git a/server/tests/services/approvals/test_turn_rows.py b/server/tests/services/approvals/test_turn_rows.pynew file mode 100644index 00000000..e94f6f2d--- /dev/null+++ b/server/tests/services/approvals/test_turn_rows.py@@ -0,0 +1,134 @@+"""Rows a turn waits on (``runtime: turn``, RFC-0007 §4.6 item 4): the turn+runs the call itself, so Send starts nothing and offers no Undo, Discard+offers no Restore, and the employee gets no ``[update]`` note, since its turn+hears the answer. A retried one becomes a draft again. A decline keeps the+owner's note, and a draft's note tells the employee."""++from __future__ import annotations++from datetime import timedelta+from types import SimpleNamespace++import pytest+from sqlalchemy import text++import nodes # noqa: F401 -- populate plugin registry+from services.approvals import execution, handlers, reconcile, rules, store, tool_calls+from services.chat import notes+from services.node_registry import get_node_class++pytestmark = pytest.mark.asyncio++SOCKET = SimpleNamespace(scope={"path": "/ws/status"}, state=SimpleNamespace(user_id="owner"))+WHATSAPP = {"recipient_type": "phone", "phone": "447700900123", "message": "On my way."}+++async def held(harness, *, waits=True):+ await rules.set_mode(harness.database, "wf", "outside")+ context = {+ "node_id": "wf:whatsappSend:1",+ "workflow_id": "wf",+ "execution_id": "wf:execution:1",+ "user_id": "owner",+ "parent_node_id": "wf:aiAgent:1",+ "tool_call_id": "call_1",+ "node_data": {"message_type": "text", **WHATSAPP},+ "tool_args": WHATSAPP,+ "approval_wait_version": 1,+ **({"approval_wait": True} if waits else {}),+ }+ await tool_calls.check(context, get_node_class("whatsappSend"))+ (row,) = await store.list_approvals(harness.database, status="pending")+ return row+++async def decide(row, decision, key, **extra):+ return await handlers.handle_decide_approval({"approval_id": row.id, "decision": decision, "decision_key": key, **extra}, SOCKET)+++async def left_notes(harness):+ return await notes.claim_notes(harness.database, session_id="wf", run_id="r_next")+++def sends(monkeypatch):+ started = []++ async def start_send(row):+ started.append(row.id)++ monkeypatch.setattr(execution, "start_send", start_send)+ return started+++async def test_send_on_a_turn_row_starts_nothing_and_offers_no_undo(harness, sends):+ row = await held(harness)+ answer = await decide(row, "send", "s1")+ assert answer["success"] and answer["approval"]["status"] == "approved"+ assert "undo_until" not in answer["approval"] and sends == []+ assert (await decide(row, "undo", "u1"))["error"] == "too_late"+ assert await left_notes(harness) == []+++async def test_a_turn_row_approved_while_paused_runs_on_resume(harness, sends, monkeypatch):+ async def paused(database, workflow_id):+ return "paused"++ monkeypatch.setattr(handlers, "_deployment_state", paused)+ row = await held(harness)+ assert (await decide(row, "send", "s1"))["will_send_on_resume"] is True+++async def test_discard_on_a_turn_row_keeps_the_note_and_offers_no_restore(harness):+ row = await held(harness)+ answer = await decide(row, "discard", "d1", note="Ask Sam first.")+ assert answer["approval"]["status"] == "discarded" and "restore_until" not in answer["approval"]+ assert (await store.get(harness.database, row.id)).note == "Ask Sam first."+ assert await left_notes(harness) == []+ assert (await decide(row, "discard", "d2", note=["not", "text"]))["error"] == "invalid_request"+++async def test_a_draft_keeps_its_undo(harness, sends):+ row = await held(harness, waits=False)+ assert "undo_until" in (await decide(row, "send", "s1"))["approval"] and sends == [row.id]+++async def test_a_draft_keeps_its_restore_and_its_note_tells_the_employee(harness):+ row = await held(harness, waits=False)+ answer = await decide(row, "discard", "d1", note="Not this week.")+ assert "restore_until" in answer["approval"]+ (note,) = await left_notes(harness)+ assert "discarded by the owner" in note.text and "Not this week." in note.text+++async def test_a_retried_turn_row_becomes_a_draft(harness, sends):+ row = await held(harness)+ approved = (await decide(row, "send", "s1"))["approval"]+ failed = await store.transition(+ harness.database,+ row.id,+ expected_revision=approved["revision"],+ from_statuses=("approved",),+ status="failed",+ values={"outcome": "not_sent", "outcome_error": "No connection."},+ )+ # Its turn heard the failure; the employee hears how a retry went.+ answer = await decide(failed, "retry", "r1")+ assert answer["approval"]["status"] == "approved" and "undo_until" in answer["approval"]+ assert (await store.get(harness.database, row.id)).runtime == "temporal" and sends == [row.id]+++async def test_an_expired_turn_row_leaves_no_note(harness):+ row = await held(harness)+ later = store.aware(row.expires_at) + timedelta(hours=1)+ assert await reconcile.expire_due(harness.database, now=later) == [row.id]+ assert await left_notes(harness) == []+++async def test_an_older_requests_table_gets_the_note_column(harness):+ async with harness.database.engine.begin() as conn:+ await conn.execute(text("ALTER TABLE approval_requests DROP COLUMN note"))+ await harness.database._migrate_approvals()+ await harness.database._migrate_approvals() # runs again at every startup; changes nothing+ row = await held(harness)+ assert (await decide(row, "discard", "d1", note="Later."))["success"] is True