Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(computer): add script confirm and notify (#2645)

Max16b77647ec7c
diff --git a/core/computer_cli.py b/core/computer_cli.py
index 9492de0bd..419c82242 100644
--- a/core/computer_cli.py
+++ b/core/computer_cli.py
@@ -167,12 +167,20 @@ _COMPUTER_ERROR_I18N_KEYS = {
"application_not_found": "computer.cli.error.scriptTargetNotFound",
"computer_script_request_failed": "computer.cli.error.scriptControllerRejected",
"computer_script_request_too_large": "computer.cli.error.scriptRequestTooLarge",
+ "computer_script_message_too_large": "computer.cli.error.scriptMessageTooLarge",
+ "computer_script_notify_failed": "computer.cli.error.scriptNotifyFailed",
+ "invalid_computer_script_message": "computer.cli.error.scriptInvalidMessage",
"computer_script_descriptor_required": "computer.cli.error.scriptInvalidDescriptor",
"computer_script_protocol_error": "computer.cli.error.scriptRuntimeInvalid",
"computer_use_unavailable": "computer.cli.error.computerUseUnavailable",
"computer_use_error": "computer.cli.error.genericDriverError",
"controller_timeout": "computer.cli.error.scriptOperationTimedOut",
"controller_unavailable": "computer.cli.error.scriptControllerUnavailable",
+ "confirm_refused": "computer.cli.error.confirmRefused",
+ "confirm_already_pending": "computer.cli.error.confirmAlreadyPending",
+ "confirm_approver_unavailable": "computer.cli.error.confirmApproverUnavailable",
+ "confirm_prompt_failed": "computer.cli.error.confirmPromptFailed",
+ "confirm_unattended": "computer.cli.error.confirmUnattended",
"desktop_busy": "computer.cli.error.targetBusy",
"element_not_actionable": "computer.cli.error.scriptElementNotActionable",
"element_not_found": "computer.cli.error.scriptTargetNotFound",
@@ -181,6 +189,7 @@ _COMPUTER_ERROR_I18N_KEYS = {
"foreground_forbidden": "computer.cli.error.foregroundForbidden",
"invalid_arguments": "computer.cli.error.invalidDriverArguments",
"invalid_computer_use_request": "computer.cli.error.requestRejected",
+ "invalid_computer_script_interaction": "computer.cli.error.requestRejected",
"invalid_computer_use_response": "computer.cli.error.scriptInvalidControllerResponse",
"invalid_computer_script_descriptor": "computer.cli.error.scriptInvalidDescriptor",
"invalid_selector": "computer.cli.error.scriptInvalidSelector",
diff --git a/core/computer_script_interactions.py b/core/computer_script_interactions.py
new file mode 100644
index 000000000..33631014d
--- /dev/null
+++ b/core/computer_script_interactions.py
@@ -0,0 +1,337 @@
+"""Controller-owned notify and owner-confirm interactions for Computer Use scripts."""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+import logging
+import secrets
+from typing import Any
+
+from core.computer_script_sessions import (
+ ComputerScriptSessionError,
+ ComputerScriptSessionManager,
+)
+from core.delivery_target import routed_delivery_context
+from core.services.dispatch import SOURCE_SCHEDULED
+from modules.agents.question_ui import PendingQuestion, Question
+from modules.im import MessageContext
+from vibe.i18n import t as i18n_t
+
+logger = logging.getLogger(__name__)
+
+MAX_MESSAGE_BYTES = 64 * 1024
+# A request carries the message JSON-escaped (a control character becomes a
+# six-byte ``\uXXXX`` escape) plus the connection token and keys, so the transport cap
+# leaves room for the worst-case envelope around a message the limit admits.
+MAX_INTERACTION_REQUEST_BYTES = 6 * MAX_MESSAGE_BYTES + 4 * 1024
+_YES_ANSWERS = frozenset(
+ {
+ "y",
+ "yes",
+ "approve",
+ "approved",
+ "confirm",
+ "confirmed",
+ "ok",
+ "okay",
+ "是",
+ "确认",
+ "同意",
+ "可以",
+ "好",
+ "好的",
+ }
+)
+_ANSWER_TRAILING_PUNCTUATION = ".!。!"
+_NO_ANSWERS = frozenset(
+ {
+ "n",
+ "no",
+ "cancel",
+ "cancelled",
+ "canceled",
+ "decline",
+ "declined",
+ "拒绝",
+ "取消",
+ "否",
+ "不",
+ }
+)
+
+
+class ComputerScriptInteractionError(RuntimeError):
+ """A script-facing notify or confirm interaction failed."""
+
+ def __init__(
+ self,
+ code: str,
+ *,
+ status_code: int = 409,
+ params: dict[str, Any] | None = None,
+ ) -> None:
+ self.code = code
+ self.status_code = status_code
+ self.params = dict(params or {})
+ super().__init__(code)
+
+
+@dataclass
+class _PendingConfirm:
+ token: str
+ turn: Any
+ context: MessageContext
+ question: PendingQuestion
+ future: asyncio.Future[bool]
+ # Answerable only once the owner has been shown the prompt.
+ armed: bool = False
+
+
+class ComputerScriptInteractionManager:
+ """Own script notifications and confirms on the launching Turn's surface."""
+
+ def __init__(
+ self,
+ controller: Any,
+ script_sessions: ComputerScriptSessionManager,
+ ) -> None:
+ self._controller = controller
+ self._script_sessions = script_sessions
+ self._pending: dict[str, _PendingConfirm] = {}
+ self._pending_by_token: dict[str, str] = {}
+
+ async def notify(self, token: str, message: str) -> dict[str, Any]:
+ binding = self._admit_message(token, message)
+ context = routed_delivery_context(binding.turn.context)
+ message_id = await self._deliver(
+ context,
+ message,
+ failure_code="computer_script_notify_failed",
+ )
+ return {
+ "status": "confirmed",
+ "effect": "confirmed",
+ "route": "message_dispatcher",
+ "delivery": {
+ "mode": "foreground",
+ "delivered_count": 1,
+ },
+ "message_id": message_id,
+ }
+
+ async def confirm(self, token: str, message: str) -> dict[str, Any]:
+ binding = self._admit_message(token, message)
+ # No person launched an unattended Turn, so nobody is there to answer.
+ if getattr(binding.turn, "source", None) == SOURCE_SCHEDULED:
+ raise ComputerScriptInteractionError("confirm_unattended")
+ # A yes/no reply carries no prompt identity, so a Session may have only
+ # one question open; otherwise one answer could approve another action.
+ if any(
+ record.question.base_session_id == binding.session_id
+ for record in self._pending.values()
+ ):
+ raise ComputerScriptInteractionError("confirm_already_pending")
+
+ context = routed_delivery_context(binding.turn.context)
+ expected_approver_id = str(context.user_id or "").strip()
+ if not expected_approver_id:
+ raise ComputerScriptInteractionError(
+ "confirm_approver_unavailable",
+ status_code=409,
+ )
+ loop = asyncio.get_running_loop()
+ pending = PendingQuestion(
+ questions=[Question(question=message)],
+ prompt_text=message,
+ option_labels=[],
+ base_session_id=binding.session_id,
+ thread_id=context.thread_id,
+ expected_approver_id=expected_approver_id,
+ agent_data={"kind": "computer_script_confirm"},
+ )
+ record = _PendingConfirm(
+ token=token,
+ turn=binding.turn,
+ context=context,
+ question=pending,
+ future=loop.create_future(),
+ )
+ confirm_id = secrets.token_urlsafe(18)
+ # Registered before the prompt is sent so it holds the Session's single
+ # slot and observes invalidation, but not answerable until delivered.
+ self._pending[confirm_id] = record
+ self._pending_by_token[token] = confirm_id
+ try:
+ await self._deliver(
+ context,
+ self._translate("computer.cli.confirm.prompt", message=message),
+ failure_code="confirm_prompt_failed",
+ )
+ record.armed = True
+ approved = await record.future
+ finally:
+ self._remove(confirm_id)
+ if record.future.done() and not record.future.cancelled():
+ # Consume an invalidation that raced a failed prompt send.
+ record.future.exception()
+
+ # The answer itself is consumed before Turn admission, so this notice is
+ # the transcript's durable record of how the owner answered.
+ await self._best_effort_notify(
+ context,
+ self._translate(
+ "computer.cli.confirm.approved" if approved else "computer.cli.confirm.declined"
+ ),
+ )
+ if not approved:
+ raise ComputerScriptInteractionError("confirm_refused")
+ return {
+ "status": "confirmed",
+ "effect": "confirmed",
+ "route": "owner_confirm",
+ "delivery": {
+ "mode": "foreground",
+ "delivered_count": 1,
+ },
+ }
+
+ def match_answer(
+ self,
+ *,
+ session_id: str,
+ approver_id: str,
+ message: str,
+ ) -> tuple[str, bool] | None:
+ """Return the pending confirm this message answers, without resolving it.
+
+ Only the expected approver's yes/no reply to this Session's pending
+ confirm matches. Anything else stays an ordinary message.
+ """
+
+ normalized_session_id = str(session_id or "").strip()
+ normalized_approver_id = str(approver_id or "").strip()
+ if not normalized_session_id or not normalized_approver_id:
+ return None
+ answer = _parse_answer(message)
+ if answer is None:
+ return None
+ for confirm_id, record in self._pending.items():
+ if (
+ record.question.base_session_id == normalized_session_id
+ and record.question.expected_approver_id == normalized_approver_id
+ and record.armed
+ and not record.future.done()
+ ):
+ return confirm_id, answer
+ return None
+
+ def resolve_answer(self, confirm_id: str, approved: bool) -> bool:
+ """Resolve one matched confirm; ``False`` if it is no longer pending."""
+
+ record = self._pending.get(confirm_id)
+ self._remove(confirm_id)
+ if record is None or record.future.done():
+ return False
+ record.future.set_result(bool(approved))
+ return True
+
+ def pending_for_token(self, token: str) -> PendingQuestion | None:
+ confirm_id = self._pending_by_token.get(token)
+ record = self._pending.get(confirm_id) if confirm_id else None
+ return record.question if record is not None else None
+
+ def invalidate_token(self, token: str, code: str) -> None:
+ confirm_id = self._pending_by_token.get(token)
+ if confirm_id is None:
+ return
+ record = self._pending.get(confirm_id)
+ if record is None:
+ self._pending_by_token.pop(token, None)
+ return
+ self._remove(confirm_id)
+ if not record.future.done():
+ record.future.set_exception(
+ ComputerScriptInteractionError(code, status_code=409)
+ )
+
+ def invalidate_turn(self, turn: Any) -> None:
+ for token, confirm_id in tuple(self._pending_by_token.items()):
+ record = self._pending.get(confirm_id)
+ if record is not None and record.turn is turn:
+ self.invalidate_token(token, "script_turn_ended")
+
+ def close_all(self) -> None:
+ for token in tuple(self._pending_by_token):
+ self.invalidate_token(token, "script_connection_invalid")
+
+ def _admit_message(self, token: str, message: str) -> Any:
+ if not isinstance(message, str) or not message.strip():
+ raise ComputerScriptInteractionError(
+ "invalid_computer_script_message",
+ status_code=400,
+ )
+ if len(message.encode("utf-8")) > MAX_MESSAGE_BYTES:
+ raise ComputerScriptInteractionError(
+ "computer_script_message_too_large",
+ status_code=413,
+ params={"limit_bytes": MAX_MESSAGE_BYTES},
+ )
+ try:
+ return self._script_sessions.admit(token)
+ except ComputerScriptSessionError:
+ raise
+
+ async def _deliver(
+ self,
+ context: MessageContext,
+ message: str,
+ *,
+ failure_code: str,
+ ) -> str:
+ """Send one notify and return its id; a missing id means not delivered."""
+
+ try:
+ message_id = await self._controller.emit_agent_message(
+ context,
+ "notify",
+ message,
+ )
+ except Exception as exc:
+ logger.exception("Computer script message delivery failed")
+ raise ComputerScriptInteractionError(
+ failure_code,
+ status_code=503,
+ ) from exc
+ if message_id is None:
+ # The dispatcher reports a failed IM send by returning no id.
+ raise ComputerScriptInteractionError(failure_code, status_code=503)
+ return message_id
+
+ async def _best_effort_notify(self, context: MessageContext, message: str) -> None:
+ try:
+ await self._controller.emit_agent_message(context, "notify", message)
+ except Exception:
+ logger.debug("Could not send computer script confirm notice", exc_info=True)
+
+ def _remove(self, confirm_id: str) -> None:
+ record = self._pending.pop(confirm_id, None)
+ if record is not None:
+ self._pending_by_token.pop(record.token, None)
+
+ def _translate(self, key: str, **kwargs: Any) -> str:
+ translator = getattr(self._controller, "_t", None)
+ if callable(translator):
+ return str(translator(key, **kwargs))
+ language = getattr(getattr(self._controller, "config", None), "language", "en")
+ return str(i18n_t(key, language, **kwargs))
+
+
+def _parse_answer(message: str) -> bool | None:
+ normalized = " ".join(str(message or "").strip().lower().split())
+ normalized = normalized.rstrip(_ANSWER_TRAILING_PUNCTUATION)
+ if normalized in _YES_ANSWERS:
+ return True
+ if normalized in _NO_ANSWERS:
+ return False
+ return None
diff --git a/core/computer_script_sessions.py b/core/computer_script_sessions.py
index 3946e346e..b5eb42d97 100644
--- a/core/computer_script_sessions.py
+++ b/core/computer_script_sessions.py
@@ -10,7 +10,7 @@ from __future__ import annotations
import asyncio
from dataclasses import dataclass
import secrets
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, Callable
from core.computer_cli import COMPUTER_CLI_TOOLS
@@ -51,6 +51,16 @@ class ComputerScriptSessionManager:
def __init__(self, turn_manager: "SessionTurnManager") -> None:
self._turn_manager = turn_manager
self._bindings: dict[str, _ScriptBinding] = {}
+ self._invalidation_listeners: list[Callable[[str, str], None]] = []
+
+ def add_invalidation_listener(
+ self,
+ listener: Callable[[str, str], None],
+ ) -> None:
+ """Register one owner for state bound to a script connection."""
+
+ if listener not in self._invalidation_listeners:
+ self._invalidation_listeners.append(listener)
def open(self, caller_session_id: str, timeout_seconds: float) -> dict[str, Any]:
if (
@@ -147,6 +157,10 @@ class ComputerScriptSessionManager:
if binding is None:
return False
self._cancel_binding_handles(binding)
+ if binding.invalid_code is None:
+ # A normal close ends the connection too: state bound to it, such as
+ # a pending confirm, must not outlive the script.
+ self._notify_invalidation(token, "script_connection_invalid")
return True
def close_all(self) -> None:
@@ -172,6 +186,16 @@ class ComputerScriptSessionManager:
self.close,
token,
)
+ self._notify_invalidation(token, code)
+
+ def _notify_invalidation(self, token: str, code: str) -> None:
+ for listener in tuple(self._invalidation_listeners):
+ try:
+ listener(token, code)
+ except Exception:
+ # A secondary owner must not prevent the connection itself from
+ # becoming invalid. Its own tests and logs own that failure.
+ continue
@staticmethod
def _cancel_binding_handles(binding: _ScriptBinding) -> None:
diff --git a/core/controller.py b/core/controller.py
index 1d156d4af..4649a9d58 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -266,6 +266,7 @@ class Controller:
# create a driver process until an active Turn requests it.
self.computer_use_server = None
self.computer_script_sessions = None
+ self.computer_script_interactions = None
self.runtime_ownership = RuntimeOwnershipProvider(
self.session_turns._sqlite_engine()
)
@@ -2581,6 +2582,14 @@ class Controller:
self._internal_server_task = None
async def _close_computer_use_server() -> None:
+ script_interactions = getattr(
+ self,
+ "computer_script_interactions",
+ None,
+ )
+ self.computer_script_interactions = None
+ if script_interactions is not None:
+ script_interactions.close_all()
script_sessions = getattr(self, "computer_script_sessions", None)
self.computer_script_sessions = None
if script_sessions is not None:
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index d4b029571..83351b29a 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -959,7 +959,7 @@ class MessageHandler(BaseHandler):
raise RuntimeError("Could not reserve the Agent Session before delivery")
from core.message_priority import priority_for_delivery_intent
- from core.session_turns import DeliveryRequest
+ from core.session_turns import SCRIPT_CONFIRM_ANSWER_REASON, DeliveryRequest
from storage import message_deliveries, media_service, messages_service
from storage.agent_session_rows import reserve_write_lock
from storage.db import get_cached_sqlite_engine
@@ -1106,8 +1106,10 @@ class MessageHandler(BaseHandler):
# This is the only place that knows an input's admission outcome: a
# Delivery that did not start its own turn returns here and the caller
# stops, so without a receipt the user sees nothing at all for every
- # message sent while a turn is running.
- await self._ack_delivery_admission(context, result)
+ # message sent while a turn is running. A consumed confirm answer was
+ # delivered to its script, which acknowledges it on this surface.
+ if result.reason != SCRIPT_CONFIRM_ANSWER_REASON:
+ await self._ack_delivery_admission(context, result)
return True
@staticmethod
diff --git a/core/internal_server.py b/core/internal_server.py
index 6812ca9b1..a80f0ca91 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -199,11 +199,34 @@ def create_app(
ComputerScriptSessionError,
ComputerScriptSessionManager,
)
+ from core.computer_script_interactions import (
+ MAX_INTERACTION_REQUEST_BYTES,
+ MAX_MESSAGE_BYTES,
+ ComputerScriptInteractionError,
+ ComputerScriptInteractionManager,
+ )
computer_script_sessions = getattr(controller, "computer_script_sessions", None)
if not isinstance(computer_script_sessions, ComputerScriptSessionManager):
computer_script_sessions = ComputerScriptSessionManager(manager)
controller.computer_script_sessions = computer_script_sessions
+ computer_script_interactions = getattr(
+ controller,
+ "computer_script_interactions",
+ None,
+ )
+ if not isinstance(
+ computer_script_interactions,
+ ComputerScriptInteractionManager,
+ ):
+ computer_script_interactions = ComputerScriptInteractionManager(
+ controller,
+ computer_script_sessions,
+ )
+ controller.computer_script_interactions = computer_script_interactions
+ computer_script_sessions.add_invalidation_listener(
+ computer_script_interactions.invalidate_token,
+ )
# The turn registry (``session_id -> Turn``) is owned by the manager and tests
# inspect it via ``app.state``. Flush intents live on each ``Turn`` (set by
@@ -836,6 +859,20 @@ def create_app(
content=content,
)
+ def _computer_script_interaction_error(
+ exc: ComputerScriptSessionError | ComputerScriptInteractionError,
+ ) -> JSONResponse:
+ return JSONResponse(
+ status_code=exc.status_code,
+ content={
+ "ok": False,
+ "error": exc.code,
+ "params": dict(getattr(exc, "params", {})),
+ "ambiguous": False,
+ "dispatched": False,
+ },
+ )
+
@app.post("/internal/computer-script/open")
async def _computer_script_open(request: Request) -> Any:
payload = await _safe_json(request)
@@ -962,6 +999,80 @@ def create_app(
"result": result,
}
+ async def _computer_script_interaction(
+ request: Request,
+ operation: str,
+ ) -> Any:
+ try:
+ payload = await _bounded_json_object(
+ request,
+ limit=MAX_INTERACTION_REQUEST_BYTES,
+ )
+ except _RequestBodyTooLarge:
+ return JSONResponse(
+ status_code=413,
+ content={
+ "ok": False,
+ "error": "computer_script_message_too_large",
+ "params": {
+ # Only a message over its own limit can exceed this cap.
+ "limit_bytes": MAX_MESSAGE_BYTES,
+ },
+ "ambiguous": False,
+ "dispatched": False,
+ },
+ )
+ if set(payload) != {"connection_token", "message"}:
+ return JSONResponse(
+ status_code=400,
+ content={
+ "ok": False,
+ "error": "invalid_computer_script_interaction",
+ "params": {},
+ "ambiguous": False,
+ "dispatched": False,
+ },
+ )
+ connection_token = payload.get("connection_token")
+ message = payload.get("message")
+ if (
+ not isinstance(connection_token, str)
+ or not connection_token
+ or not isinstance(message, str)
+ ):
+ return JSONResponse(
+ status_code=400,
+ content={
+ "ok": False,
+ "error": "invalid_computer_script_interaction",
+ "params": {},
+ "ambiguous": False,
+ "dispatched": False,
+ },
+ )
+ try:
+ if operation == "notify":
+ result = await computer_script_interactions.notify(
+ connection_token,
+ message,
+ )
+ else:
+ result = await computer_script_interactions.confirm(
+ connection_token,
+ message,
+ )
+ except (ComputerScriptSessionError, ComputerScriptInteractionError) as exc:
+ return _computer_script_interaction_error(exc)
+ return {"ok": True, "result": result}
+
+ @app.post("/internal/computer-script/notify")
+ async def _computer_script_notify(request: Request) -> Any:
+ return await _computer_script_interaction(request, "notify")
+
+ @app.post("/internal/computer-script/confirm")
+ async def _computer_script_confirm(request: Request) -> Any:
+ return await _computer_script_interaction(request, "confirm")
+
@app.post("/internal/computer-script/close")
async def _computer_script_close(request: Request) -> Any:
payload = await _safe_json(request)
diff --git a/core/session_turns.py b/core/session_turns.py
index c5a6b331b..e098ffb4e 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -569,6 +569,9 @@ class Turn:
delivery_id: Optional[str] = None
terminal_is_error: bool = False
computer_use_admission_closed: bool = False
+ #: ``SOURCE_HUMAN`` or ``SOURCE_SCHEDULED``: whether a person launched this
+ #: Turn, so attended-only capabilities such as script confirms can refuse.
+ source: str = SOURCE_HUMAN
@dataclass(frozen=True)
@@ -580,6 +583,12 @@ class ComputerUseAdmission:
logical_turn_id: str | None = None
+# A human reply consumed as the answer to a pending Computer Use script confirm.
+SCRIPT_CONFIRM_ANSWER_REASON = "computer_confirm_answer"
+# Delivery metadata that binds an input to one specific earlier prompt.
+_PROMPT_TARGET_METADATA_KEYS = ("quick_reply_for",)
+
+
@dataclass(frozen=True)
class DeliveryRequest:
"""Private P0/P1/P3 admission contract owned by ``SessionTurnManager``."""
@@ -2920,6 +2929,9 @@ class SessionTurnManager:
and delivery_store.is_vibey_resume_payload(delivery_store.delivery_payload(delivery))
):
raise ValueError("P3 requires content")
+ confirm_answer = self._consume_script_confirm_answer(request, context)
+ if confirm_answer is not None:
+ return confirm_answer
backend, resolved_context = self._delivery_backend(
request.session_id,
context,
@@ -2930,6 +2942,60 @@ class SessionTurnManager:
return await self._admit_p1(request, backend, resolved_context)
return await self._admit_p0(request, backend, resolved_context)
+ def _consume_script_confirm_answer(
+ self,
+ request: DeliveryRequest,
+ context: Optional["MessageContext"],
+ ) -> DeliveryResult | None:
+ """Hand the approver's answer to a pending script confirm, before admission.
+
+ Web dispatch and IM ingress both reach here with a reserved human
+ Delivery. The script asking is blocking this Session's running Turn, so
+ a queued or steered answer could never reach it. A matched answer
+ retires its reservation instead of being admitted: it starts no Turn
+ and joins no queue. Every other input continues unchanged.
+ """
+
+ if request.source != "user" or context is None or not request.delivery_id:
+ return None
+ # A plain yes/no names no prompt, so only a direct original text reply
+ # may answer. Quick replies, forwards, edits, and anything aimed at
+ # another prompt stay ordinary messages.
+ if request.message_kind != "original" or getattr(context, "files", None):
+ return None
+ if any(key in (request.metadata or {}) for key in _PROMPT_TARGET_METADATA_KEYS):
+ return None
+ interactions = getattr(self.controller, "computer_script_interactions", None)
+ match_answer = getattr(interactions, "match_answer", None)
+ if not callable(match_answer):
+ return None
+ text = request.display_text if request.display_text is not None else request.content
+ matched = match_answer(
+ session_id=request.session_id,
+ approver_id=str(getattr(context, "user_id", None) or ""),
+ message=str(text or ""),
+ )
+ if matched is None:
+ return None
+ with self._sqlite_engine().begin() as conn:
+ reserve_write_lock(conn)
+ retired = delivery_store.retire_reserved(
+ conn,
+ request.session_id,
+ request.delivery_id,
+ reason=SCRIPT_CONFIRM_ANSWER_REASON,
+ )
+ if not retired:
+ return None
+ confirm_id, approved = matched
+ interactions.resolve_answer(confirm_id, approved)
+ return DeliveryResult(
+ delivery_id=request.delivery_id,
+ message_id=None,
+ state="retired",
+ reason=SCRIPT_CONFIRM_ANSWER_REASON,
+ )
+
async def _admit_p3(
self,
request: DeliveryRequest,
@@ -7949,6 +8015,7 @@ class SessionTurnManager:
started_at=_utc_now_iso(),
logical_turn_id=logical_turn_id,
delivery_id=delivery_id,
+ source=source,
)
# Make the DB row authoritative at ACCEPTANCE, not at dispatch start:
# ``update_session``'s backend lock re-checks ``agent_status`` inside
diff --git a/docs/plans/desktop-computer-use-js-sdk-design.md b/docs/plans/desktop-computer-use-js-sdk-design.md
index 35a6af77d..8d59ae8a4 100644
--- a/docs/plans/desktop-computer-use-js-sdk-design.md
+++ b/docs/plans/desktop-computer-use-js-sdk-design.md
@@ -127,9 +127,33 @@ answer. It is not currently a generic script-facing, Web/IM-neutral primitive.
The implementation should reuse that existing delivery and wait lifecycle,
extracting only the smallest Controller-owned `ask-and-wait` boundary needed
by `confirm`. This is a continuation primitive, not a new approval system.
-Whether the current Web surface can satisfy the same contract is **unverified**
-on `origin/master`; the implementation PR must verify it before claiming Web
-parity. See [`modules/agents/question_ui.py`](../../modules/agents/question_ui.py).
+See [`modules/agents/question_ui.py`](../../modules/agents/question_ui.py).
+
+The answer path runs before Turn admission, inside
+`SessionTurnManager.deliver`, which both Web dispatch and IM ingress reach with
+a reserved human Delivery. The script blocks its own running Turn, so an answer
+that queued or steered behind that Turn could never reach it. When the Session
+has a pending confirm and the sender is the expected approver (the user who
+launched the Turn) replying yes or no, the reservation is retired, the confirm
+resolves, and no Turn starts. Every other input, including another member's
+reply in a shared channel or any reply after the confirm was invalidated by the
+Turn ending or the script deadline, is admitted unchanged. The confirm then
+posts a short approved/declined notice on the launching surface, which is the
+transcript's record of the answer.
+
+A yes/no reply names no prompt, so a Session has at most one pending confirm;
+a second one fails with `confirm_already_pending`. A confirm becomes answerable
+only after its prompt is delivered; an undelivered prompt fails the confirm with
+`confirm_prompt_failed`, and an undelivered notify fails with
+`computer_script_notify_failed`. Closing the script connection, like the Turn
+ending or the script deadline, invalidates its pending confirm.
+
+Only a direct original text reply answers: a quick reply, a forward, an edit,
+or anything aimed at another prompt stays an ordinary message, and a confirm
+from an unattended (scheduled) Turn fails with `confirm_unattended` before any
+prompt is sent. Because the answer carries no prompt identity, an unrelated
+standalone "yes" from the approver while a confirm is pending is still taken
+as the answer; a prompt-bound answer identity is tracked in #2733.
## Execution and runtime
diff --git a/modules/agents/question_ui.py b/modules/agents/question_ui.py
index 25aaa85e2..7e8b8050f 100644
--- a/modules/agents/question_ui.py
+++ b/modules/agents/question_ui.py
@@ -86,6 +86,7 @@ class PendingQuestion:
# Session info
base_session_id: str
thread_id: Optional[str] = None
+ expected_approver_id: Optional[str] = None
# UI state
prompt_message_id: Optional[str] = None
diff --git a/skills/computer-use/SKILL.md b/skills/computer-use/SKILL.md
index bc2040bcc..6b67e5af2 100644
--- a/skills/computer-use/SKILL.md
+++ b/skills/computer-use/SKILL.md
@@ -31,7 +31,7 @@ vibe computer force-quit --arg pid=123
For multi-step work, write a normal ESM file and import the shipped SDK:
```js
-import { computer } from "@avibe/computer";
+import { avibe, computer } from "@avibe/computer";
export default async ({ mailbox, query }) => {
const mail = await computer.app({ bundleId: "com.apple.mail" });
@@ -64,6 +64,16 @@ primitive is unavailable, stop before the irreversible action and use an
interactive flow. Save a proven script as a reusable Skill only after the owner
explicitly approves saving it.
+For example:
+
+```js
+const send = draft.element({ role: "button", label: "Send" });
+await draft.expect({ role: "textbox", label: "To" }).toHaveValue(to);
+await avibe.confirm(`Send this message to ${to}?`);
+await draft.expect({ role: "textbox", label: "To" }).toHaveValue(to);
+await send.click();
+```
+
Every single-operation leaf accepts `--args-json OBJECT`, `--args-json @FILE`,
repeatable `--arg NAME=VALUE`, and `--json`. The two screenshot operations also
accept `--output PATH`; the CLI writes or confirms the caller-selected PNG and
diff --git a/tests/test_computer_script_interactions.py b/tests/test_computer_script_interactions.py
new file mode 100644
index 000000000..c7998bb76
--- /dev/null
+++ b/tests/test_computer_script_interactions.py
@@ -0,0 +1,337 @@
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import httpx
+import pytest
+
+from core import internal_server, session_turns
+from core.computer_script_interactions import (
+ MAX_INTERACTION_REQUEST_BYTES,
+ MAX_MESSAGE_BYTES,
+ ComputerScriptInteractionError,
+ ComputerScriptInteractionManager,
+)
+from core.computer_script_sessions import ComputerScriptSessionManager
+from core.services.dispatch import SOURCE_SCHEDULED
+from modules.im import MessageContext
+
+
+def _context(
+ *,
+ user_id: str = "owner",
+ platform: str = "avibe",
+ channel_id: str = "channel",
+ thread_id: str | None = "thread",
+) -> MessageContext:
+ return MessageContext(
+ user_id=user_id,
+ channel_id=channel_id,
+ platform=platform,
+ thread_id=thread_id,
+ platform_specific={},
+ )
+
+
+class _FakeScriptSessions:
+ def __init__(self, *bindings) -> None:
+ self.bindings = {binding.token: binding for binding in bindings}
+
+ def admit(self, token: str):
+ if token not in self.bindings:
+ raise AssertionError(f"unexpected token: {token}")
+ return self.bindings[token]
+
+
+class _FakeController:
+ def __init__(self, language: str = "en") -> None:
+ self.config = SimpleNamespace(language=language)
+ self.messages: list[tuple[MessageContext, str, str]] = []
+ # ``"none"`` mimics the dispatcher's failed IM send; ``"raise"`` an error.
+ self.delivery = "ok"
+ self.release: asyncio.Event | None = None
+
+ async def emit_agent_message(
+ self,
+ context: MessageContext,
+ message_type: str,
+ text: str,
+ ) -> str | None:
+ if self.release is not None:
+ await self.release.wait()
+ if self.delivery == "raise":
+ raise RuntimeError("adapter failed")
+ if self.delivery == "none":
+ return None
+ self.messages.append((context, message_type, text))
+ return f"message-{len(self.messages)}"
+
+
+def _manager(
+ *,
+ platform: str = "avibe",
+ owner_id: str = "owner",
+) -> tuple[ComputerScriptInteractionManager, _FakeController, SimpleNamespace]:
+ context = _context(user_id=owner_id, platform=platform)
+ turn = SimpleNamespace(context=context)
+ bindings = [
+ SimpleNamespace(token=token, session_id="session", turn=turn)
+ for token in ("script-token", "second-script-token")
+ ]
+ controller = _FakeController()
+ manager = ComputerScriptInteractionManager(
+ controller,
+ _FakeScriptSessions(*bindings),
+ )
+ return manager, controller, turn
+
+
[email protected]("platform", ["avibe", "slack"])
+def test_notify_reuses_the_launching_surface(platform: str) -> None:
+ async def exercise() -> dict:
+ manager, controller, _turn = _manager(platform=platform)
+ result = await manager.notify("script-token", "A progress update")
+ return {
+ "result": result,
+ "message": controller.messages[0],
+ }
+
+ observed = asyncio.run(exercise())
+ assert observed["result"] == {
+ "status": "confirmed",
+ "effect": "confirmed",
+ "route": "message_dispatcher",
+ "delivery": {
+ "mode": "foreground",
+ "delivered_count": 1,
+ },
+ "message_id": "message-1",
+ }
+ context, message_type, text = observed["message"]
+ assert context.platform == platform
+ assert message_type == "notify"
+ assert text == "A progress update"
+
+
+ ("operation", "delivery", "code"),
+ [
+ ("notify", "none", "computer_script_notify_failed"),
+ ("notify", "raise", "computer_script_notify_failed"),
+ ("confirm", "none", "confirm_prompt_failed"),
+ ("confirm", "raise", "confirm_prompt_failed"),
+ ],
+)
+def test_undelivered_interaction_fails_typed(
+ operation: str, delivery: str, code: str
+) -> None:
+ """A message the owner never received is never reported as delivered."""
+
+ async def exercise() -> tuple[str, bool]:
+ manager, controller, _turn = _manager(platform="slack")
+ controller.delivery = delivery
+ try:
+ await getattr(manager, operation)("script-token", "Send it?")
+ except ComputerScriptInteractionError as exc:
+ return exc.code, manager.pending_for_token("script-token") is None
+ raise AssertionError("undelivered interaction succeeded")
+
+ assert asyncio.run(exercise()) == (code, True)
+
+
+def test_confirm_is_answerable_only_after_its_prompt_is_delivered() -> None:
+ async def exercise() -> dict:
+ manager, controller, _turn = _manager(platform="slack")
+ controller.release = asyncio.Event()
+ pending = asyncio.create_task(manager.confirm("script-token", "Send it?"))
+ await asyncio.sleep(0)
+ answer = {"session_id": "session", "approver_id": "owner", "message": "yes"}
+ assert manager.pending_for_token("script-token") is not None
+ assert manager.match_answer(**answer) is None
+ controller.release.set()
+ for _ in range(3):
+ await asyncio.sleep(0)
+ matched = manager.match_answer(**answer)
+ assert matched is not None
+ manager.resolve_answer(*matched)
+ return await pending
+
+ assert asyncio.run(exercise())["effect"] == "confirmed"
+
+
+def test_confirm_from_an_unattended_turn_is_refused_before_any_prompt() -> None:
+ """Nobody launched a scheduled Turn, so nobody is there to answer."""
+
+ async def exercise() -> tuple[str, list]:
+ manager, controller, turn = _manager(platform="slack")
+ turn.source = SOURCE_SCHEDULED
+ try:
+ await manager.confirm("script-token", "Send it?")
+ except ComputerScriptInteractionError as exc:
+ return exc.code, controller.messages
+ raise AssertionError("unattended confirm was admitted")
+
+ assert asyncio.run(exercise()) == ("confirm_unattended", [])
+
+
+def test_a_session_has_at_most_one_pending_confirm() -> None:
+ """A yes/no reply names no prompt, so a second script cannot open another."""
+
+ async def exercise() -> tuple[str, bool]:
+ manager, _controller, _turn = _manager(platform="slack")
+ first = asyncio.create_task(manager.confirm("script-token", "Send A?"))
+ await asyncio.sleep(0)
+ try:
+ await manager.confirm("second-script-token", "Send B?")
+ except ComputerScriptInteractionError as exc:
+ code = exc.code
+ else:
+ raise AssertionError("second confirm was admitted")
+ still_waiting = not first.done()
+ first.cancel()
+ await asyncio.gather(first, return_exceptions=True)
+ return code, still_waiting
+
+ assert asyncio.run(exercise()) == ("confirm_already_pending", True)
+
+
[email protected]("invalidation_code", ["script_turn_ended", "script_timeout"])
+def test_pending_confirm_is_invalidated_with_the_script_connection(
+ invalidation_code: str,
+) -> None:
+ async def exercise() -> str:
+ manager, _controller, _turn = _manager()
+ pending = asyncio.create_task(manager.confirm("script-token", "Continue?"))
+ await asyncio.sleep(0)
+ manager.invalidate_token("script-token", invalidation_code)
+ try:
+ await pending
+ except ComputerScriptInteractionError as exc:
+ return exc.code
+ raise AssertionError("invalidated confirmation remained pending")
+
+ assert asyncio.run(exercise()) == invalidation_code
+
+
+ ("ending", "code"),
+ [("turn_ended", "script_turn_ended"), ("closed", "script_connection_invalid")],
+)
+def test_script_connection_end_wakes_a_pending_confirm(ending: str, code: str) -> None:
+ """No confirm outlives its script, whether the Turn ends or the script closes."""
+
+ async def exercise() -> tuple[str, bool]:
+ controller = _FakeController()
+ controller._session_id_from_context = lambda context: (
+ context.platform_specific or {}
+ ).get("agent_session_id")
+ turn_manager = session_turns.SessionTurnManager(controller)
+ task = asyncio.create_task(asyncio.sleep(60))
+ context = _context()
+ context.platform_specific = {"agent_session_id": "session"}
+ turn = session_turns.Turn(
+ task=task,
+ context=context,
+ logical_turn_id="turn-1",
+ )
+ turn_manager.in_flight["session"] = turn
+ script_sessions = ComputerScriptSessionManager(turn_manager)
+ interactions = ComputerScriptInteractionManager(
+ controller,
+ script_sessions,
+ )
+ script_sessions.add_invalidation_listener(interactions.invalidate_token)
+ token = script_sessions.open("session", 30)["connection_token"]
+ pending = asyncio.create_task(interactions.confirm(token, "Continue?"))
+ await asyncio.sleep(0)
+ if ending == "turn_ended":
+ script_sessions.invalidate_turn(turn)
+ else:
+ script_sessions.close(token)
+ try:
+ await pending
+ except ComputerScriptInteractionError as exc:
+ return exc.code, interactions.match_answer(
+ session_id="session", approver_id="owner", message="yes"
+ ) is None
+ finally:
+ script_sessions.close_all()
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ raise AssertionError("ended script left confirm pending")
+
+ assert asyncio.run(exercise()) == (code, True)
+
+
+def test_internal_routes_bound_interactions_and_reject_oversized_messages() -> None:
+ async def exercise() -> tuple[httpx.Response, ...]:
+ from tests.test_internal_server import _build_controller_double
+
+ controller = _build_controller_double()
+ messages: list[str] = []
+
+ async def emit_agent_message(_context, _message_type, text, **_kwargs):
+ messages.append(text)
+ return f"message-{len(messages)}"
+
+ controller.emit_agent_message = emit_agent_message
+ app = internal_server.create_app(controller)
+ task = asyncio.create_task(asyncio.sleep(60))
+ context = _context(
+ user_id="owner",
+ platform="avibe",
+ )
+ context.platform_specific = {"agent_session_id": "ses-script"}
+ turn = session_turns.Turn(
+ task=task,
+ context=context,
+ logical_turn_id="turn-1",
+ )
+ controller.session_turns.in_flight["ses-script"] = turn
+ token = controller.computer_script_sessions.open(
+ "ses-script",
+ 30,
+ )["connection_token"]
+ try:
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://test",
+ ) as client:
+ notify = await client.post(
+ "/internal/computer-script/notify",
+ json={
+ "connection_token": token,
+ "message": "Progress",
+ },
+ )
+ # The largest admitted message, nearly every byte JSON-escaped to six bytes.
+ escaped_limit = await client.post(
+ "/internal/computer-script/notify",
+ json={
+ "connection_token": token,
+ "message": "x" + "\x01" * (MAX_MESSAGE_BYTES - 1),
+ },
+ )
+ oversized = await client.post(
+ "/internal/computer-script/notify",
+ content=b"x" * (MAX_INTERACTION_REQUEST_BYTES + 1),
+ headers={"Content-Type": "application/json"},
+ )
+ return notify, escaped_limit, oversized, messages
+ finally:
+ controller.computer_script_sessions.close_all()
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+
+ notify, escaped_limit, oversized, messages = asyncio.run(exercise())
+ assert notify.status_code == 200
+ assert notify.json()["ok"] is True
+ assert notify.json()["result"]["route"] == "message_dispatcher"
+ assert escaped_limit.status_code == 200
+ assert escaped_limit.json()["ok"] is True
+ assert oversized.status_code == 413
+ assert oversized.json()["error"] == "computer_script_message_too_large"
+ assert oversized.json()["params"] == {"limit_bytes": MAX_MESSAGE_BYTES}
+ assert len(messages) == 2
diff --git a/tests/test_computer_script_sdk.py b/tests/test_computer_script_sdk.py
index 4a82fb4cf..f498d0a81 100644
--- a/tests/test_computer_script_sdk.py
+++ b/tests/test_computer_script_sdk.py
@@ -59,6 +59,11 @@ def _result(payload: dict, *, is_error: bool = False, image: bool = False) -> di
}
+# An interaction answer that arrives after the request was sent but cannot be
+# decoded, so the client cannot know whether the Controller acted on it.
+_GARBLED_RESPONSE = "<garbled-response>"
+
+
@contextmanager
def _fake_controller(
*,
@@ -71,6 +76,7 @@ def _fake_controller(
app_responses: list[list[dict]] | None = None,
windows: list[dict] | None = None,
launch_pid: int | None = 41,
+ interaction_errors: dict[str, str] | None = None,
) -> Iterator[tuple[ThreadingHTTPServer, list[dict]]]:
requests: list[dict] = []
observations = 0
@@ -95,6 +101,39 @@ def _fake_controller(
)
if self.path == "/internal/computer-script/close":
body = {"ok": True, "closed": True}
+ elif self.path in {
+ "/internal/computer-script/notify",
+ "/internal/computer-script/confirm",
+ }:
+ operation = self.path.rsplit("/", 1)[-1]
+ error = (interaction_errors or {}).get(operation)
+ if error == _GARBLED_RESPONSE:
+ body = None
+ elif error is not None:
+ body = {
+ "ok": False,
+ "error": error,
+ "params": {},
+ "ambiguous": False,
+ "dispatched": False,
+ }
+ else:
+ body = {
+ "ok": True,
+ "result": {
+ "status": "confirmed",
+ "effect": "confirmed",
+ "route": (
+ "owner_confirm"
+ if operation == "confirm"
+ else "message_dispatcher"
+ ),
+ "delivery": {
+ "mode": "foreground",
+ "delivered_count": 1,
+ },
+ },
+ }
else:
tool = payload["tool"]
delay = (response_delay_by_tool or {}).get(tool, 0)
@@ -320,7 +359,7 @@ def _fake_controller(
{"code": "unknown_tool", "params": {"tool": tool}},
is_error=True,
)
- encoded = json.dumps(body).encode()
+ encoded = b"{" if body is None else json.dumps(body).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(encoded)))
@@ -360,6 +399,7 @@ def _run_node_script(
app_responses: list[list[dict]] | None = None,
windows: list[dict] | None = None,
launch_pid: int | None = 41,
+ interaction_errors: dict[str, str] | None = None,
) -> tuple[dict, ThreadingHTTPServer, list[dict]]:
if NODE is None:
pytest.skip("Node.js is unavailable")
@@ -389,6 +429,7 @@ def _run_node_script(
app_responses=app_responses,
windows=windows,
launch_pid=launch_pid,
+ interaction_errors=interaction_errors,
) as (server, requests):
request = {
"script_url": script.resolve().as_uri(),
@@ -721,6 +762,119 @@ export default async ({ subject }) => {
assert len(server.connection_ids) == 1 # type: ignore[attr-defined]
+def test_avibe_notify_and_confirm_return_effects(tmp_path: Path) -> None:
+ payload, _server, requests = _run_node_script(
+ tmp_path,
+ """
+import { avibe } from "@avibe/computer";
+
+export default async () => ({
+ notify: await avibe.notify("Progress"),
+ confirm: await avibe.confirm("Continue?"),
+});
+""",
+ )
+
+ assert payload == {
+ "ok": True,
+ "result": {
+ "notify": {
+ "status": "confirmed",
+ "effect": "confirmed",
+ "route": "message_dispatcher",
+ "delivery": {
+ "mode": "foreground",
+ "delivered_count": 1,
+ },
+ },
+ "confirm": {
+ "status": "confirmed",
+ "effect": "confirmed",
+ "route": "owner_confirm",
+ "delivery": {
+ "mode": "foreground",
+ "delivered_count": 1,
+ },
+ },
+ },
+ }
+ assert [
+ request["path"]
+ for request in requests
+ if request["path"].startswith("/internal/computer-script/")
+ ] == [
+ "/internal/computer-script/notify",
+ "/internal/computer-script/confirm",
+ "/internal/computer-script/close",
+ ]
+
+
+def test_avibe_confirm_refusal_is_typed_and_unambiguous(tmp_path: Path) -> None:
+ payload, _server, _requests = _run_node_script(
+ tmp_path,
+ """
+import { ConfirmRefused, avibe } from "@avibe/computer";
+
+export default async () => {
+ try {
+ await avibe.confirm("Continue?");
+ } catch (error) {
+ return {
+ instance: error instanceof ConfirmRefused,
+ code: error.code,
+ ambiguous: error.ambiguous,
+ step: error.step,
+ };
+ }
+ throw new Error("confirmation unexpectedly succeeded");
+};
+""",
+ interaction_errors={"confirm": "confirm_refused"},
+ )
+
+ assert payload == {
+ "ok": True,
+ "result": {
+ "instance": True,
+ "code": "confirm_refused",
+ "ambiguous": False,
+ "step": "avibe.confirm",
+ },
+ }
+
+
+ ("operation", "ambiguous"),
+ [("notify", True), ("confirm", False)],
+)
+def test_avibe_interaction_lost_response_ambiguity(
+ tmp_path: Path, operation: str, ambiguous: bool
+) -> None:
+ """A notify may already be delivered; a lost confirm never approved anything."""
+
+ payload, _server, _requests = _run_node_script(
+ tmp_path,
+ f"""
+import {{ avibe }} from "@avibe/computer";
+
+export default async () => {{
+ try {{
+ await avibe.{operation}("Continue?");
+ }} catch (error) {{
+ return {{ code: error.code, ambiguous: error.ambiguous }};
+ }}
+ throw new Error("lost response was not raised");
+}};
+""",
+ interaction_errors={operation: _GARBLED_RESPONSE},
+ )
+
+ assert payload == {
+ "ok": True,
+ "result": {"code": "invalid_computer_use_response", "ambiguous": ambiguous},
+ }
+
+
def test_sdk_failure_reports_step_and_last_screenshot(tmp_path: Path) -> None:
payload, _server, _requests = _run_node_script(
tmp_path,
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 1dea9bf4b..06ab364c0 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -150,6 +150,9 @@ def _build_controller_double(handler=None):
# (a bare MagicMock would blow up ``json.dumps`` in ``_sse_event``).
controller._t = lambda key, **kwargs: key
controller.config = SimpleNamespace()
+ # Like ``Controller.__init__``: ``create_app`` installs the real owners.
+ controller.computer_script_sessions = None
+ controller.computer_script_interactions = None
return controller
@@ -228,6 +231,7 @@ def _reserve_submission(
metadata: dict | None = None,
native_message_id: str | None = None,
message_kind: str | None = None,
+ author_id: str | None = None,
):
delivery_id = message_deliveries.new_delivery_id()
row = message_deliveries.insert_delivery(
@@ -246,6 +250,7 @@ def _reserve_submission(
text=text,
content=content,
metadata=metadata,
+ author_id=author_id,
author_name=author_name,
native_message_id=native_message_id,
message_kind=message_kind,
@@ -1383,6 +1388,140 @@ def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):
assert transcript["messages"] == []
+ ("case", "message_kind", "metadata"),
+ [
+ ("answer", "original", None),
+ ("invalidated", "original", None),
+ ("quick_reply", "quick_reply", {"quick_reply_for": "msg_older_prompt"}),
+ ("forwarded", "forwarded", None),
+ ],
+)
+def test_dispatch_async_answers_a_pending_script_confirm_before_queuing(
+ monkeypatch, tmp_path, case, message_kind, metadata
+):
+ """A direct Web reply during the script's own Turn reaches ``avibe.confirm``.
+
+ The script blocks the running Turn, so an answer that queued behind it
+ would deadlock until the script deadline. A "yes" that is not a direct
+ original reply (a quick reply to another prompt, a forward), or any reply
+ after the confirm is gone, is an ordinary send-while-busy message.
+ """
+ from core.computer_script_interactions import ComputerScriptInteractionError
+ from core.services import sessions as sessions_service
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.settings_service import upsert_scope
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn, platform="avibe", scope_type="project", native_id="proj_confirm", now="2026-05-31T00:00:00Z"
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ session = sessions_service.create_session(
+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
+ )
+ owner = _reserve_submission(
+ conn, scope_id=scope_id, session_id=session["id"], text="run the script"
+ )
+ owner_turn_id = message_deliveries.new_turn_id()
+ message_deliveries.insert_turn(
+ conn,
+ turn_id=owner_turn_id,
+ session_id=session["id"],
+ initial_delivery_id=owner["id"],
+ state="active",
+ backend="claude",
+ )
+ reply = _reserve_submission(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ text="yes",
+ author_id="owner",
+ message_kind=message_kind,
+ metadata=metadata,
+ )
+ session_id = session["id"]
+
+ controller = _build_controller_double()
+ notices: list[str] = []
+
+ async def emit_agent_message(_context, _message_type, text, **_kwargs):
+ notices.append(text)
+ return f"notice-{len(notices)}"
+
+ controller.emit_agent_message = emit_agent_message
+ app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=app)
+
+ async def _go():
+ task = asyncio.create_task(asyncio.sleep(60))
+ controller.session_turns.in_flight[session_id] = session_turns.Turn(
+ task=task,
+ context=MessageContext(
+ user_id="owner",
+ channel_id=session_id,
+ platform="avibe",
+ platform_specific={"agent_session_id": session_id},
+ ),
+ logical_turn_id=owner_turn_id,
+ )
+ token = controller.computer_script_sessions.open(session_id, 30)["connection_token"]
+ confirm = asyncio.create_task(
+ controller.computer_script_interactions.confirm(token, "Send it?")
+ )
+ await asyncio.sleep(0)
+ if case == "invalidated":
+ controller.computer_script_interactions.invalidate_token(token, "script_turn_ended")
+ try:
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ resp = await asyncio.wait_for(
+ client.post(
+ "/internal/dispatch_async",
+ json={"session_id": session_id, "text": "yes", "user_message_id": reply["id"]},
+ ),
+ timeout=5,
+ )
+ if case in {"quick_reply", "forwarded"}:
+ await asyncio.sleep(0)
+ assert not confirm.done()
+ confirm.cancel()
+ outcome = await asyncio.wait_for(asyncio.gather(confirm, return_exceptions=True), 5)
+ finally:
+ controller.computer_script_sessions.close_all()
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ return resp, outcome[0]
+
+ resp, outcome = asyncio.run(_go())
+ assert resp.status_code == 202
+ controller.message_handler.handle_user_message.assert_not_awaited()
+ with engine.connect() as conn:
+ queued = [q["text"] for q in message_deliveries.list_queued(conn, session_id)]
+ delivery = message_deliveries.get_delivery(conn, reply["id"])
+ transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
+ assert transcript["messages"] == []
+ if case == "answer":
+ assert outcome["effect"] == "confirmed"
+ assert resp.json()["queued"] is False
+ assert delivery["state"] == "retired"
+ assert queued == []
+ assert notices[-1] == "computer.cli.confirm.approved"
+ else:
+ if case == "invalidated":
+ assert isinstance(outcome, ComputerScriptInteractionError)
+ assert outcome.code == "script_turn_ended"
+ else:
+ assert isinstance(outcome, asyncio.CancelledError)
+ assert resp.json()["queued"] is True
+ assert queued == ["yes"]
+
+
def test_dispatch_async_replay_of_queued_delivery_is_idempotent(monkeypatch, tmp_path):
from storage import message_deliveries, messages_service
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index f8ccf1a9b..0df05ab1d 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -3357,6 +3357,8 @@ def test_service_teardown_terminalizes_transferred_turn_without_starting_queued_
assert live_turn["state"] == "active"
assert session_id in manager.in_flight
assert not manager.in_flight[session_id].task.done()
+ # Attended-only capabilities (script confirms) read this provenance.
+ assert manager.in_flight[session_id].source == SOURCE_SCHEDULED
await service.stop()
assert service._service_teardown_task is not None
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 4778d2b25..17bd82af3 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -6093,6 +6093,126 @@ async def test_concurrent_im_attachment_retry_keeps_one_reserved_owner(
assert not retry_path.exists()
+ ("sender", "answer", "expected"),
+ [
+ ("U_OWNER", "yes", "confirmed"),
+ ("U_OWNER", "no", "confirm_refused"),
+ ("U_MEMBER", "yes", "pending"),
+ ],
+ ids=["approver-yes", "approver-no", "other-member"],
+)
+async def test_im_reply_answers_only_the_approvers_pending_script_confirm(
+ managers,
+ monkeypatch,
+ sender: str,
+ answer: str,
+ expected: str,
+) -> None:
+ """In a shared IM channel only the owner who launched the script answers it.
+
+ The answer is consumed before admission, so it neither queues behind nor
+ steers into the Turn the script is blocking. Another member's reply is an
+ ordinary message and leaves the confirm waiting.
+ """
+ from core.computer_script_interactions import (
+ ComputerScriptInteractionError,
+ ComputerScriptInteractionManager,
+ )
+
+ manager, _other, engine, _engine_b, starts = managers
+ await _activate(manager, text="run the script")
+ starts_before = list(starts)
+ acks = _record_admission_acks(manager)
+ notices: list[str] = []
+
+ async def emit_agent_message(_context, _message_type, text, **_kwargs):
+ notices.append(text)
+ return f"notice-{len(notices)}"
+
+ launching_context = MessageContext(
+ user_id="U_OWNER", channel_id="C1", thread_id="T1", platform="slack"
+ )
+ binding = SimpleNamespace(
+ token="script-token",
+ session_id="ses_fsm",
+ turn=SimpleNamespace(context=launching_context),
+ )
+ interactions = ComputerScriptInteractionManager(
+ SimpleNamespace(
+ config=SimpleNamespace(language="en"),
+ emit_agent_message=emit_agent_message,
+ ),
+ SimpleNamespace(admit=lambda _token: binding),
+ )
+ manager.controller.computer_script_interactions = interactions
+ confirm = asyncio.create_task(interactions.confirm("script-token", "Send it?"))
+ await asyncio.sleep(0)
+
+ handler = MessageHandler(
+ SimpleNamespace(
+ config=SimpleNamespace(language="en"),
+ im_client=SimpleNamespace(formatter=None),
+ settings_manager=SimpleNamespace(sessions=SimpleNamespace()),
+ session_manager=SimpleNamespace(),
+ receiver_tasks={},
+ processing_indicator=manager.controller.processing_indicator,
+ )
+ )
+ handler.set_session_handler(
+ SimpleNamespace(ensure_agent_session_id=lambda *_args, **_kwargs: "ses_fsm")
+ )
+ monkeypatch.setattr("storage.db.get_cached_sqlite_engine", lambda: engine)
+ reply_context = MessageContext(
+ user_id=sender,
+ channel_id="C1",
+ thread_id="T1",
+ message_id="native-reply-1",
+ platform="slack",
+ is_original_human_text=True,
+ )
+ await handler._admit_human_delivery(
+ manager=manager,
+ context=reply_context,
+ dispatch_text=answer,
+ display_text=answer,
+ processed_files=[],
+ session_key="slack::C1",
+ agent_name="codex",
+ session_anchor="base-session",
+ working_path="/tmp",
+ vibe_agent=None,
+ delivery_intent="queue",
+ downloaded_attachment_paths=[],
+ admission_context={},
+ )
+ delivery = _row(engine, reply_context.platform_specific["delivery_id"])
+ assert starts == starts_before
+
+ if expected == "pending":
+ assert confirm.done() is False
+ assert delivery["state"] == "queued"
+ assert [ack[2] for ack in acks] == ["queued"]
+ confirm.cancel()
+ await asyncio.gather(confirm, return_exceptions=True)
+ return
+
+ outcome = (await asyncio.wait_for(asyncio.gather(confirm, return_exceptions=True), 5))[0]
+ assert notices[0] == (
+ "Send it?\n\nReply yes or no. Only the person who started this task can answer."
+ )
+ assert delivery["state"] == "retired"
+ assert acks == []
+ if expected == "confirmed":
+ assert outcome["effect"] == "confirmed"
+ assert notices[-1] == "Confirmed. Continuing."
+ else:
+ assert isinstance(outcome, ComputerScriptInteractionError)
+ assert outcome.code == "confirm_refused"
+ assert notices[-1] == "Declined. The script will not take this step."
+
+
def test_reserved_attachment_only_submission_recovers_exact_dispatch_inputs(
managers,
tmp_path: Path,
diff --git a/vibe/computer_sdk/index.d.ts b/vibe/computer_sdk/index.d.ts
index 8749e43cb..e5f1566f6 100644
--- a/vibe/computer_sdk/index.d.ts
+++ b/vibe/computer_sdk/index.d.ts
@@ -139,5 +139,13 @@ export type DesktopBusy = TargetBusy;
export const DesktopBusy: typeof TargetBusy;
export class ForegroundConsentRequired extends ControllerError {}
export class Unavailable extends ControllerError {}
+export class ConfirmRefused extends ControllerError {}
export const computer: Computer;
+
+export interface Avibe {
+ notify(message: string): Promise<Effect>;
+ confirm(message: string): Promise<Effect>;
+}
+
+export const avibe: Avibe;
diff --git a/vibe/computer_sdk/index.mjs b/vibe/computer_sdk/index.mjs
index ce98baaff..36016b822 100644
--- a/vibe/computer_sdk/index.mjs
+++ b/vibe/computer_sdk/index.mjs
@@ -1,6 +1,7 @@
import {
ControllerFault,
callTool,
+ callScriptInteraction,
controllerFailureAmbiguous,
runStep,
sleepWithinDeadline,
@@ -164,6 +165,13 @@ export class Unavailable extends ControllerError {
}
}
+export class ConfirmRefused extends ControllerError {
+ constructor(message, options = {}) {
+ super(message, { ...options, code: options.code || "confirm_refused" });
+ this.name = "ConfirmRefused";
+ }
+}
+
function publicError(error) {
if (error instanceof ControllerError) {
return error;
@@ -204,6 +212,9 @@ function publicError(error) {
) {
return new Unavailable(error.message, options);
}
+ if (error.code === "confirm_refused") {
+ return new ConfirmRefused(error.message, options);
+ }
return new ControllerError(error.message, options);
}
@@ -235,6 +246,19 @@ function effectResult(result) {
return { ...payload, effect: status, status };
}
+function validateInteractionMessage(message) {
+ if (typeof message !== "string" || !message.trim()) {
+ throw new ControllerError(
+ "Computer script messages must be non-empty strings.",
+ {
+ code: "invalid_computer_script_message",
+ params: { field: "message" },
+ ambiguous: false,
+ },
+ );
+ }
+}
+
function publicObservation(result) {
return sanitizePublic(structured(result));
}
@@ -968,3 +992,19 @@ class ElementExpectation {
}
export const computer = Object.freeze(new Computer());
+
+export const avibe = Object.freeze({
+ notify(message) {
+ return sdkStep("avibe.notify", async () => {
+ validateInteractionMessage(message);
+ return effectResult(await callScriptInteraction("notify", message));
+ });
+ },
+
+ confirm(message) {
+ return sdkStep("avibe.confirm", async () => {
+ validateInteractionMessage(message);
+ return effectResult(await callScriptInteraction("confirm", message));
+ });
+ },
+});
diff --git a/vibe/computer_sdk/runtime.mjs b/vibe/computer_sdk/runtime.mjs
index da81bfcca..a9cc91c0f 100644
--- a/vibe/computer_sdk/runtime.mjs
+++ b/vibe/computer_sdk/runtime.mjs
@@ -205,6 +205,42 @@ export async function callTool(tool, argumentsValue, options = {}) {
);
}
+export async function callScriptInteraction(operation, message) {
+ let body;
+ try {
+ body = await postJson(`/internal/computer-script/${operation}`, {
+ connection_token: state.connectionToken,
+ message,
+ });
+ } catch (error) {
+ // Confirm has no desktop side effect, and a lost confirm never approved
+ // anything, so it is never ambiguous. A notify may already be delivered.
+ if (operation === "confirm" && error instanceof ControllerFault) {
+ error.ambiguous = false;
+ }
+ throw error;
+ }
+ if (body?.ok === false) {
+ const code =
+ typeof body.error === "string"
+ ? body.error
+ : "computer_script_request_failed";
+ throw controllerFault(code, controllerMessage(code, body), body.params, {
+ requestWasSent: false,
+ controllerPayload: body,
+ });
+ }
+ if (body?.ok === true && body.result && typeof body.result === "object") {
+ return { structuredContent: body.result };
+ }
+ throw controllerFault(
+ "invalid_computer_use_response",
+ "The Controller returned an invalid Computer Use response.",
+ {},
+ { requestWasSent: false },
+ );
+}
+
function controllerMessage(code, payload) {
if (payload && typeof payload.detail === "string" && payload.detail) {
return payload.detail;
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 177715198..2a6e36f19 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -923,6 +923,14 @@
"scriptConnectionInvalid": "The script's Controller connection is no longer valid.",
"scriptControllerRejected": "The Controller rejected the script request.",
"scriptRequestTooLarge": "The Computer Use script request exceeded the Controller size limit.",
+ "scriptMessageTooLarge": "The Computer Use script message exceeded the size limit.",
+ "scriptNotifyFailed": "The Computer Use notification could not be delivered.",
+ "scriptInvalidMessage": "Computer Use script messages must be non-empty text.",
+ "confirmRefused": "The owner refused the confirmation.",
+ "confirmAlreadyPending": "The script already has a confirmation waiting for an answer.",
+ "confirmApproverUnavailable": "The owner identity for this confirmation is unavailable.",
+ "confirmPromptFailed": "The confirmation question could not be delivered, so nothing was approved.",
+ "confirmUnattended": "This script asks for an owner confirmation, which an unattended run cannot give.",
"scriptControllerUnavailable": "The Controller is unavailable.",
"scriptDeadlineExpired": "The script deadline expired.",
"scriptElementNotActionable": "The matched element is not actionable.",
@@ -961,6 +969,11 @@
"upstreamUnavailable": "The Computer Use driver is unavailable. Observe again before retrying.",
"windowTargetRequired": "Input must target an exact observed window or element."
},
+ "confirm": {
+ "prompt": "{message}\n\nReply yes or no. Only the person who started this task can answer.",
+ "approved": "Confirmed. Continuing.",
+ "declined": "Declined. The script will not take this step."
+ },
"status": {
"off": "off",
"needsPermission": "permission is required",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 334525747..ff8fb21b7 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -923,6 +923,14 @@
"scriptConnectionInvalid": "脚本的 Controller 连接已失效。",
"scriptControllerRejected": "Controller 拒绝了脚本请求。",
"scriptRequestTooLarge": "Computer Use 脚本请求超过了 Controller 的大小上限。",
+ "scriptMessageTooLarge": "Computer Use 脚本消息超过大小上限。",
+ "scriptNotifyFailed": "Computer Use 通知未能送达。",
+ "scriptInvalidMessage": "Computer Use 脚本消息必须是非空文本。",
+ "confirmRefused": "所有者拒绝了这次确认。",
+ "confirmAlreadyPending": "脚本已经有一个等待回答的确认请求。",
+ "confirmApproverUnavailable": "无法确定这次确认的所有者身份。",
+ "confirmPromptFailed": "确认问题未能送达,因此没有任何操作获得批准。",
+ "confirmUnattended": "此脚本需要所有者确认,无人值守的运行无法给出确认。",
"scriptControllerUnavailable": "Controller 当前不可用。",
"scriptDeadlineExpired": "脚本截止时间已到。",
"scriptElementNotActionable": "匹配到的元素无法执行操作。",
@@ -961,6 +969,11 @@
"upstreamUnavailable": "Computer Use driver 不可用,请重新观察后再重试。",
"windowTargetRequired": "输入必须针对已观察的精确窗口或元素。"
},
+ "confirm": {
+ "prompt": "{message}\n\n请回复“是”或“否”。只有发起这项任务的人可以回答。",
+ "approved": "已确认,继续执行。",
+ "declined": "已拒绝,脚本不会执行这一步。"
+ },
"status": {
"off": "未开启",
"needsPermission": "需要系统权限",