diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 462d157c9d..078d46e646 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -214,6 +214,7 @@ improvising or retrying when something is off. | Admit once, then stop only on problems | Released ([#1212](https://github.com/OpenAdaptAI/OpenAdapt/pull/1212)), behind a readiness gate | Synthetic | [APPROVAL_MODES.md](packages/flow/docs/APPROVAL_MODES.md) | | Show the field values a save writes on the phone | Released ([#1257](https://github.com/OpenAdaptAI/OpenAdapt/pull/1257)) | Unit tests | `console/save_approvals.py` | | Show why an agent asked for a save: who asked, its own reason (as a quote), the screen text it saw, and any of that text that reads like an instruction to an agent | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359)) | Unit tests, synthetic | `ApprovalProvenance` in `approval_mode/item_approval.py`; the phone card in openadapt-desktop `portal/shell` | +| Let any agent stop and ask a person, with one closed question and one signed answer: seven kinds (`second_factor`, `unexpected_dialog`, `session_expired`, `timeout_or_stall`, `possible_duplicate`, `ambiguous_record`, `cannot_complete`), five answers, a `raise_exception` MCP tool that blocks until answered, detectors that say when to ask, and `exceptions watch`, which reads a Chromium agent's page over CDP, raises `second_factor`, `unexpected_dialog`, `session_expired` and (opt-in) `timeout_or_stall` cards without the agent, and blocks the page's saves while a card is open. Only a verified `continue` or `done_by_person` lets the run go on; a decline, an expiry or an unverifiable answer stops it before any write. The MCP tool can't make an agent that ignores it stop; the watch must start after the guard attaches, and doesn't cover non-browser agents, WebSocket saves, other tabs, a save sent before its next look at the page, `possible_duplicate`, or a run with no watch running. Cards in Desktop's stop queue and on a paired phone ship with openadapt-desktop 0.31.0 in [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492). The share of cases that need a person is unmeasured | In PR [#2494](https://github.com/OpenAdaptAI/OpenAdapt/pull/2494) | Unit tests and synthetic end-to-end tests: a scripted agent on a one-time-code page over real MCP stdio (one write after `done_by_person`, zero after `abort`, `skip`, an expiry or a key off the roster, read from the app's own state); and, in headless Chromium on MockMed with the guard attached, an agent that never calls the tool hits a synthetic code prompt, the watch raises the card and blocks its save, and after `done_by_person` one save lands and reads back VERIFIED | `openadapt-flow exceptions`, [EXCEPTION_QUEUE.md](packages/flow/docs/EXCEPTION_QUEUE.md) | ## Branching work, not one linear path @@ -423,6 +424,7 @@ A test fails when a command has no file or this list is out of date. - `business-decisions` - `console` - `deferred` +- `exceptions`: Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `watch` raises cards from a Chromium agent's page without the agent and blocks its saves while one is open, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See `packages/flow/docs/EXCEPTION_QUEUE.md`. - `explain` - `item-approval` - `replay` diff --git a/llms-full.txt b/llms-full.txt index 5d3446e884..9b4f0f96c5 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -674,6 +674,7 @@ improvising or retrying when something is off. | Admit once, then stop only on problems | Released ([#1212](https://github.com/OpenAdaptAI/OpenAdapt/pull/1212)), behind a readiness gate | Synthetic | [APPROVAL_MODES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/APPROVAL_MODES.md) | | Show the field values a save writes on the phone | Released ([#1257](https://github.com/OpenAdaptAI/OpenAdapt/pull/1257)) | Unit tests | `console/save_approvals.py` | | Show why an agent asked for a save: who asked, its own reason (as a quote), the screen text it saw, and any of that text that reads like an instruction to an agent | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359)) | Unit tests, synthetic | `ApprovalProvenance` in `approval_mode/item_approval.py`; the phone card in openadapt-desktop `portal/shell` | +| Let any agent stop and ask a person, with one closed question and one signed answer: seven kinds (`second_factor`, `unexpected_dialog`, `session_expired`, `timeout_or_stall`, `possible_duplicate`, `ambiguous_record`, `cannot_complete`), five answers, a `raise_exception` MCP tool that blocks until answered, detectors that say when to ask, and `exceptions watch`, which reads a Chromium agent's page over CDP, raises `second_factor`, `unexpected_dialog`, `session_expired` and (opt-in) `timeout_or_stall` cards without the agent, and blocks the page's saves while a card is open. Only a verified `continue` or `done_by_person` lets the run go on; a decline, an expiry or an unverifiable answer stops it before any write. The MCP tool can't make an agent that ignores it stop; the watch must start after the guard attaches, and doesn't cover non-browser agents, WebSocket saves, other tabs, a save sent before its next look at the page, `possible_duplicate`, or a run with no watch running. Cards in Desktop's stop queue and on a paired phone ship with openadapt-desktop 0.31.0 in [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492). The share of cases that need a person is unmeasured | In PR [#2494](https://github.com/OpenAdaptAI/OpenAdapt/pull/2494) | Unit tests and synthetic end-to-end tests: a scripted agent on a one-time-code page over real MCP stdio (one write after `done_by_person`, zero after `abort`, `skip`, an expiry or a key off the roster, read from the app's own state); and, in headless Chromium on MockMed with the guard attached, an agent that never calls the tool hits a synthetic code prompt, the watch raises the card and blocks its save, and after `done_by_person` one save lands and reads back VERIFIED | `openadapt-flow exceptions`, [EXCEPTION_QUEUE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EXCEPTION_QUEUE.md) | ## Branching work, not one linear path @@ -883,6 +884,7 @@ A test fails when a command has no file or this list is out of date. - `business-decisions` - `console` - `deferred` +- `exceptions`: Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `watch` raises cards from a Chromium agent's page without the agent and blocks its saves while one is open, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See `packages/flow/docs/EXCEPTION_QUEUE.md`. - `explain` - `item-approval` - `replay` diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index 298ac8056b..0754e3fa1b 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -61,6 +61,7 @@ "disambiguate": "compile --disambiguate", "emit-mcp": "workflow emit-mcp", "emit-skill": "workflow emit-skill", + "exceptions": "approve exceptions", "explain": "inspect explain", "fleet": "services fleet", "for-each": "run --for-each", diff --git a/packages/flow/docs/EXCEPTION_QUEUE.md b/packages/flow/docs/EXCEPTION_QUEUE.md new file mode 100644 index 0000000000..1860af3aa7 --- /dev/null +++ b/packages/flow/docs/EXCEPTION_QUEUE.md @@ -0,0 +1,236 @@ +# The exception queue + +Any agent can stop and ask a person, and wait for one closed answer. The agent +can be a compiled program, Claude computer use, an OpenAI CUA harness, +Browser-Use, or a person's own script. A person answers from the terminal, from +Desktop's stop queue, or from a paired phone. A run that gets no answer, or an +answer it can't verify, stops before any write. + +The share of cases that need a person has not been measured. Any figure, such +as "about 10%", is an estimate until a deployment measures it. + +## The kinds + +`kind` is a closed set. Nothing else validates. + +| Kind | When | Usual answer | +| --- | --- | --- | +| `second_factor` | The app asks for a one-time code. | `done_by_person`: the person types the code in the live browser. | +| `unexpected_dialog` | A modal the run didn't expect covers the target. | `done_by_person` or `continue` | +| `session_expired` | A sign-in page appears after the run reached a screen where it could save. | `done_by_person`: the person signs in again. | +| `timeout_or_stall` | No action and no screen change for N seconds. | `continue` | +| `possible_duplicate` | A row already in the app matches the record on `record.duplicate_key`. | `skip` or `continue` | +| `ambiguous_record` | The agent can't tell which record is the right one. | `done_by_person` | +| `cannot_complete` | The agent can't finish the item. | `done_by_person` | + +`answer` is also closed: `continue`, `skip`, `decline`, `done_by_person` and +`abort`. Each kind offers only some of them (`openadapt_flow/exceptions/registry.py`, +`CHOICES`). Only `continue` and `done_by_person` let a run go on. + +The one-time code is never relayed through OpenAdapt. The card asks the person +to type it into the live browser, and the agent goes on from the same screen. + +## For an agent: the MCP tool + +```bash +openadapt-flow exceptions serve --run-ref intake-0412 --task-id intake +``` + +This starts a stdio MCP server with one tool: + +```text +raise_exception(kind, summary, screenshot_path?) +``` + +The tool opens a card and blocks until a person answers or the card expires +(15 minutes by default, `--deadline-s` to change it). It returns: + +```json +{"card_id": "sha256:...", "kind": "second_factor", "answer": "done_by_person", + "proceed": true, "reason": null, "opened_at": "...", "decided_at": "...", + "instruction": "A person answered done_by_person. Go on from the current screen."} +``` + +Go on only when `proceed` is `true`. Otherwise stop and write nothing. + +The tool can tell an agent to stop. It can't make an agent that ignores the +result stop, and an agent that never calls it never asks anyone. For a browser +agent, run the watch below: it raises cards without the agent and holds its +saves. + +## Without the agent: the browser watch + +```bash +openadapt-flow exceptions watch --cdp http://127.0.0.1:9222 \ + --config guard.yaml --run-dir runs/intake-0412 +``` + +`watch` attaches to the agent's Chromium over CDP, the same endpoint +`openadapt-flow guard` attaches to, and reads the guard's `guard.yaml` for the +app's origin and its `not_saves`. Every half second (`--poll-s`) it reads the +page (its inputs, dialogs and text, with their positions) and runs the +detectors. When one fires, it opens a card itself, with the kind's own +sentence as the summary: nothing from the page goes on the card. + +While the card is open, the watch blocks every save the page sends, whatever +the agent does. The page gets a `409` with an `X-OpenAdapt-Exception` header, +and nothing reaches the app. A save is what the guard calls one: a write to +the app's origin that `not_saves` doesn't list, or a write to another origin. +Reads go through, and so does a write `not_saves` lists, so list the form a +person submits a code or a sign-in with, and they can do it in the live +browser. A verified `continue` or `done_by_person` lifts the hold. Any other +outcome (a stop answer, an expiry, an answer off the roster) makes the watch +block every later save for as long as it runs, and it exits 3 when it ends. +A watch that ends (`--max-s` or a signal) with a card still unanswered exits +6. + +The watch holds saves only while it is attached. A request the page aborts +while it is paused, or a block the browser refuses, is logged +(`request_decision_failed`) and the watch goes on. If the watch loses its own +DevTools session while the tab is still open, it says so on stderr, writes +`watch_lost` to `exceptions_watch.jsonl`, reports `"lost"` in its output and +exits 4 when it was holding saves (a card open or a stop) or 5 otherwise. +If the watch's own code fails (a detector, opening a card on a full disk or +an unwritable registry, reading an answer), it keeps running and refuses +every paused and later write with a `409` until the tab closes, its session +is lost, a signal arrives or `--max-s` passes. It logs `watch_lost` with +reason `watch_failed` and exits 4. Before it detaches, it decides every +paused request, even when the browser refuses one of those decisions. A request it can't classify is refused, not let +through. A +dead watch blocks nothing from then on, so run it beside the guard +(`openadapt-flow guard`): the guard still holds each save until the record on +screen is the right one, and reads it back. + +The watch and the guard each pause requests in their own DevTools session, +and Chromium hands a paused request to the session that attached last first. +Start the watch after the guard has attached (`guard: attached` on its +stderr), so the watch decides a save before the guard sees it. In the other +order a save the watch blocks is still never sent, but the guard has already +let it go: it reads back no write, ends the run unconfirmed, and refuses the +agent's later save. Only the guard-first order is tested. + +The run's folder in the registry is `--run-ref`, or else the `--run-dir` +folder's name. `--run-dir` also gets `exceptions_watch.jsonl`: each card +opened, each answer and each blocked save, with no values. + +What the watch sees and raises: + +| Kind | Raised by the watch | +| --- | --- | +| `second_factor` | Yes | +| `unexpected_dialog` | Yes. The watch can't tell a dialog the task expects (a confirm box) from one it doesn't, so it asks about both | +| `session_expired` | Yes, once the watch has seen a save | +| `timeout_or_stall` | Only with `--stall-s N`: no request and no screen change for N seconds | +| `possible_duplicate` | No: it needs a read of the app's records | +| `ambiguous_record`, `cannot_complete` | No: only the agent knows | + +Not covered: agents that don't drive a Chromium, saves over a WebSocket (CDP +`Fetch` doesn't see them), tabs other than the one the watch picked (the +first on the app's origin, or `--page-url`), a save sent in the moment +between a prompt appearing and the watch's next look at the page +(`--poll-s`), and a run with no watch running. The watch is not a +sandbox: an agent with another way to reach the app, or that stops the watch, +gets past it. Tested in headless Chromium on MockMed with the guard attached: +an agent that never calls the tool hits a synthetic code prompt, its save is +blocked while the card is open, and after `done_by_person` its next save +lands once and reads back VERIFIED. + +## For a person: answering + +```bash +openadapt-flow exceptions list +openadapt-flow exceptions answer sha256:... done_by_person +``` + +`answer` signs with an approver key on the pinned approver roster +(`openadapt-flow jit approver init|add`). By default it reads the key file +Desktop keeps, `~/.openadapt/approver/desktop-approver.pem`, with +`OPENADAPT_JIT_KEY_PASSPHRASE`. Pass `--key` for another key. The roster's +root comes from `--approver-root` or `OPENADAPT_APPROVER_ROOT`, and its folder +from `--key-dir` (default `~/.openadapt/jit`). `answer` refuses to write an +answer the waiting run wouldn't accept. + +Desktop lists every open card from every run on the computer in its stop +queue, beside the saves and stops of its own runs, and shows each one on a +paired phone. (Desktop's part ships with openadapt-desktop 0.31.0, in +[#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492).) An answer from Desktop is signed with the same approver key as +its other stop answers (Touch ID on a Mac). An answer from the phone is signed +with the decision portal's key. Exception cards are answered one at a time, +never in a batch. + +## The files + +Each run has one folder, `$OPENADAPT_HOME/exceptions//` +(`~/.openadapt/exceptions` by default): + +| File | Written by | +| --- | --- | +| `card-.json` | The run, when it asks (`openadapt.exception-card/v1`) | +| `screenshot-.png` | The run, as a scrubbed copy, only when a scrubber could redact it | +| `answer-.json` | A person's signed answer, or the registry when the card expires (`openadapt.exception-answer/v1`) | +| `consumed-.json` | The run, when it acts on the answer | + +Every file is created once (a temporary file, then a hard link), owner read and +write only, and never replaced. The schemas are in +`openadapt_types.exception_card`. `card_id` is the SHA-256 of the card's other +fields, so an answer names exactly the card a person saw. + +An answer records `opened_at` and `decided_at`: how long a person held the run. +An expiry record has `answer` `decline`, `decided_at` `null`, +`approver_kind` `expiry` and `reason` `expired`. + +## What the run checks + +The waiting run checks every answer itself. It goes on only when all of these +hold: + +- the answer names this card's id, kind and open time; +- it is one of the card's choices; +- it was decided after the card opened and before its deadline; +- it is signed by a key on the approver roster the run pins; +- it hasn't been used before (`consumed-.json` is created exclusively). + +Anything else (`decline`, `skip`, `abort`, an expiry, a file that can't be +read, an unregistered key, a bad signature, a late answer, a reused answer) +means stop before any write. When the registry's expiry and a person's answer +land at the same moment, whichever file is created first is the answer, and +the run checks it like any other. + +## Privacy + +The summary can reach a paired phone, so it follows Flow's outbound rule. With +a working scrubber (the `privacy` extra), the agent's text is scrubbed, digit +runs, dates and email addresses are masked, and the result is cut to 200 +characters. Without one, the card shows only the kind's own sentence and drops +the agent's text. A screenshot is kept only as a redacted copy, and only when a +scrubber can redact images. The path an agent passes is read only as a regular +PNG file under 8 MB, never through a link. Nothing in the registry is sent +anywhere. + +## Detectors + +`openadapt_flow.exceptions.detectors` is a library of pure functions over the +screen's text, an accessibility snapshot, a DOM snapshot when there is one, and +timing. Each returns a kind or `None`. They use general signals only: + +- an input with `autocomplete=one-time-code`, or a short numeric input near a + word like *code* or *verification*, is `second_factor`; +- a password field after the first save-eligible screen is `session_expired`; +- a modal on top of the target is `unexpected_dialog`; +- no action and no screen change for N seconds is `timeout_or_stall`; +- a row matching the proposed record on every field of verify.yaml's + `record.duplicate_key` is `possible_duplicate`. + +A detector that can't tell (a dialog with no geometry, a failed read, a clock +with no last event) returns its kind: uncertain means ask. The detectors read +nothing and name no app. A caller passes in what it already saw. + +## Not in this release + +- Relaying a second-factor code through OpenAdapt. A follow-up can seal and + type the code through the existing second-factor handoff, so the agent never + sees it. +- `raise_exception` on the `openadapt wrap -- COMMAND` MCP surface. +- Calling the detectors from the flight gate (`openadapt-flow flight`). The + browser watch covers a Chromium agent, with or without the guard. +- A Cloud intake for exception cards and web push. diff --git a/packages/flow/docs/commands/03-run-and-answer/exceptions.md b/packages/flow/docs/commands/03-run-and-answer/exceptions.md new file mode 100644 index 0000000000..441819d1de --- /dev/null +++ b/packages/flow/docs/commands/03-run-and-answer/exceptions.md @@ -0,0 +1 @@ +Let any agent stop and ask a person: `serve` runs the `raise_exception` MCP tool, `watch` raises cards from a Chromium agent's page without the agent and blocks its saves while one is open, `list` shows waiting cards, and `answer` writes one closed answer signed with an approver key. A run goes on only after a verified `continue` or `done_by_person`. See `packages/flow/docs/EXCEPTION_QUEUE.md`. diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 7e74f59283..0245f2b192 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -9368,6 +9368,7 @@ def build_parser() -> argparse.ArgumentParser: sub = parser.add_subparsers( dest="command", required=True, parser_class=argparse.ArgumentParser ) + __import__("openadapt_flow.exceptions.cli", fromlist=["register"]).register(sub) p = sub.add_parser( "demo", diff --git a/packages/flow/openadapt_flow/cli_tasks.py b/packages/flow/openadapt_flow/cli_tasks.py index a0bac30176..c21263442f 100644 --- a/packages/flow/openadapt_flow/cli_tasks.py +++ b/packages/flow/openadapt_flow/cli_tasks.py @@ -60,6 +60,7 @@ "disambiguate": "compile --disambiguate", "emit-mcp": "workflow emit-mcp", "emit-skill": "workflow emit-skill", + "exceptions": "approve exceptions", "explain": "inspect explain", "fleet": "services fleet", "for-each": "run --for-each", diff --git a/packages/flow/openadapt_flow/exceptions/__init__.py b/packages/flow/openadapt_flow/exceptions/__init__.py new file mode 100644 index 0000000000..f8252d0f62 --- /dev/null +++ b/packages/flow/openadapt_flow/exceptions/__init__.py @@ -0,0 +1,13 @@ +"""The exception queue: any agent stops, a person answers, the run goes on +or stops before any write. + +- :mod:`.registry`: the local file protocol (cards, answers, expiry, consume). +- :mod:`.detectors`: pure checks that say when to ask (no app names). +- :mod:`.mcp_server`: the ``raise_exception`` MCP tool. +- :mod:`.watch`: raise cards from a browser agent's page without the agent, + and block its saves while one is open. +- :mod:`.cli`: ``openadapt-flow exceptions serve|watch|list|answer``. + +The schemas live in :mod:`openadapt_types.exception_card`. See +``docs/EXCEPTION_QUEUE.md``. +""" diff --git a/packages/flow/openadapt_flow/exceptions/cli.py b/packages/flow/openadapt_flow/exceptions/cli.py new file mode 100644 index 0000000000..24d935a127 --- /dev/null +++ b/packages/flow/openadapt_flow/exceptions/cli.py @@ -0,0 +1,366 @@ +"""CLI: ``openadapt-flow exceptions serve|watch|list|answer``. See +``docs/EXCEPTION_QUEUE.md``. + + openadapt-flow exceptions serve --run-ref intake-0412 + openadapt-flow exceptions watch --cdp http://127.0.0.1:9222 --config guard.yaml + openadapt-flow exceptions list + openadapt-flow exceptions answer sha256:… done_by_person + +``answer`` signs with an approver key on the pinned roster (by default the +key file Desktop keeps, ``~/.openadapt/approver/desktop-approver.pem``, opened +with ``OPENADAPT_JIT_KEY_PASSPHRASE``; read only). It refuses to write an +answer the waiting run wouldn't accept. Exit 0 on success, 2 when refused. +""" + +from __future__ import annotations + +import argparse +import json +import sys +import uuid +from pathlib import Path +from typing import Optional + +KEY_DEFAULT = Path.home() / ".openadapt" / "approver" / "desktop-approver.pem" + + +def _common(p: argparse.ArgumentParser) -> None: + p.add_argument( + "--registry", + help="the exceptions folder (default: $OPENADAPT_HOME/exceptions)", + ) + + +def _roster(p: argparse.ArgumentParser) -> None: + p.add_argument( + "--key-dir", help="the approver roster's folder (default: ~/.openadapt/jit)" + ) + p.add_argument( + "--approver-root", + help="the roster's root public key (default: OPENADAPT_APPROVER_ROOT)", + ) + + +def register(sub: argparse._SubParsersAction) -> None: + p = sub.add_parser( + "exceptions", + allow_abbrev=False, + help="Let any agent stop and ask a person (2FA, a dialog, a sign-in, a " + "stall, a possible duplicate), and answer from here, Desktop or a phone", + ) + ops = p.add_subparsers(dest="exceptions_command", required=True) + + s = ops.add_parser( + "serve", + allow_abbrev=False, + help="Serve the raise_exception MCP tool over stdio", + ) + s.add_argument("--run-ref", help="this run's folder name (default: a new one)") + s.add_argument("--task-id", help="the task the cards belong to") + s.add_argument( + "--deadline-s", + type=float, + default=None, + help="how long a card waits for a person (default 900)", + ) + _roster(s) + _common(s) + s.set_defaults(func=cmd_serve) + + w = ops.add_parser( + "watch", + allow_abbrev=False, + help="Watch the agent's Chromium, raise cards without the agent, and " + "block its saves while a card is open", + ) + w.add_argument( + "--cdp", + required=True, + help="the agent's DevTools endpoint (start the watch after the guard " + "has attached to it)", + ) + w.add_argument( + "--config", + required=True, + help="the guard's guard.yaml: the app's origin and its not_saves", + ) + w.add_argument("--page-url", help="watch the tab whose URL starts with this") + w.add_argument( + "--run-dir", + help="write exceptions_watch.jsonl here (the guard's --out)", + ) + w.add_argument( + "--run-ref", + help="this run's folder name in the registry (default: --run-dir's " + "name, else a new one)", + ) + w.add_argument("--task-id", help="the task the cards belong to") + w.add_argument("--deadline-s", type=float, default=None, help="default 900") + w.add_argument( + "--stall-s", + type=float, + default=None, + help="raise timeout_or_stall after this long with no request and no " + "screen change (default: off)", + ) + w.add_argument("--poll-s", type=float, default=0.5, help="look every N seconds") + w.add_argument("--max-s", type=float, default=None, help="stop after N seconds") + _roster(w) + _common(w) + w.set_defaults(func=cmd_watch) + + ls = ops.add_parser( + "list", allow_abbrev=False, help="Show cards waiting for a person" + ) + ls.add_argument("--run-ref", help="only this run's cards") + ls.add_argument("--json", action="store_true", help="print JSON") + _common(ls) + ls.set_defaults(func=cmd_list) + + a = ops.add_parser( + "answer", + allow_abbrev=False, + help="Answer a card, signed with your approver key", + ) + a.add_argument("card_id", metavar="CARD_ID") + a.add_argument( + "choice", + metavar="CHOICE", + choices=["continue", "skip", "decline", "done_by_person", "abort"], + ) + a.add_argument("--key", help=f"the encrypted approver key (default: {KEY_DEFAULT})") + a.add_argument("--json", action="store_true", help="print JSON") + _roster(a) + _common(a) + a.set_defaults(func=cmd_answer) + + +def _registry(args: argparse.Namespace): + from openadapt_flow.exceptions.registry import ExceptionRegistry + + return ExceptionRegistry(args.registry) + + +def _pin(args: argparse.Namespace) -> tuple[Path, Optional[str]]: + from openadapt_flow.approval_mode.approver_roster import RosterError, pinned_root + from openadapt_flow.jit.lifecycle import default_key_dir + + try: + root = pinned_root(args.approver_root) + except RosterError as exc: + raise SystemExit(f"REFUSED ({exc.code}): {exc}. Nothing changed.") from None + return (Path(args.key_dir) if args.key_dir else default_key_dir()), root + + +def cmd_serve(args: argparse.Namespace) -> int: + from openadapt_flow.exceptions.mcp_server import RaiseException, serve + from openadapt_flow.exceptions.registry import DEFAULT_DEADLINE_S, roster_verifier + + key_dir, root = _pin(args) + run_ref = args.run_ref or f"mcp-{uuid.uuid4().hex[:16]}" + registry = _registry(args) + registry.run_dir(run_ref) # refuse a bad name before serving + print( + f"exceptions: serving raise_exception for run {run_ref}; " + f"cards in {registry.root / run_ref}", + file=sys.stderr, + ) + serve( + RaiseException( + registry, + run_ref=run_ref, + verify=roster_verifier(key_dir, root), + task_id=args.task_id, + deadline_s=args.deadline_s or DEFAULT_DEADLINE_S, + ) + ) + return 0 + + +def _watch_run_ref(args: argparse.Namespace) -> str: + import re + + from openadapt_flow.exceptions.registry import RUN_REF_PATTERN + + if args.run_ref: + return str(args.run_ref) + name = Path(args.run_dir).name if args.run_dir else "" + if name and re.fullmatch(RUN_REF_PATTERN, name): + return name + return f"watch-{uuid.uuid4().hex[:16]}" + + +def cmd_watch(args: argparse.Namespace) -> int: + from openadapt_flow.agent_guard.config import ConfigError, load_config + from openadapt_flow.exceptions.registry import ( + DEFAULT_DEADLINE_S, + ExceptionRegistryError, + roster_verifier, + ) + from openadapt_flow.exceptions.watch import ( + WATCH_EVENTS, + ExceptionWatch, + WatchAttachError, + watch_browser, + ) + + key_dir, root = _pin(args) + try: + cfg = load_config(args.config) + except ConfigError as exc: + print(f"exceptions: {getattr(exc, 'message', exc)}", file=sys.stderr) + return 2 + run_ref = _watch_run_ref(args) + try: + watch = ExceptionWatch( + _registry(args), + run_ref=run_ref, + verify=roster_verifier(key_dir, root), + app_origin=cfg.app_origin, + not_saves=cfg.not_saves, + task_id=args.task_id, + deadline_s=args.deadline_s or DEFAULT_DEADLINE_S, + stall_s=args.stall_s, + events_path=Path(args.run_dir) / WATCH_EVENTS if args.run_dir else None, + ) + except ExceptionRegistryError as exc: + print(f"exceptions: REFUSED ({exc.code}): {exc}", file=sys.stderr) + return 2 + import signal + + stopping: list[int] = [] + + def _stop(signum: int, _frame: object) -> None: + stopping.append(signum) # the loop ends; paused saves are decided first + + for signum in (signal.SIGINT, signal.SIGTERM): + signal.signal(signum, _stop) + try: + code = watch_browser( + watch, + cdp_endpoint=args.cdp, + page_url=args.page_url, + poll_s=args.poll_s, + max_s=args.max_s, + stop=lambda: bool(stopping), + on_attached=lambda: print( + f"exceptions: watching for run {run_ref}; saves are blocked " + "while a card is open", + file=sys.stderr, + flush=True, + ), + ) + except WatchAttachError as exc: + print(f"exceptions: {exc}", file=sys.stderr) + return 2 + except KeyboardInterrupt: + # An interrupt ends the watch like a signal: paused saves were + # decided on the way out; 6 when a card is still unanswered. + code = watch.stop_code() + except Exception as exc: # noqa: BLE001 - any failure is loud, never 1 + watch.fail(exc) + code = watch.stop_code() + print( + json.dumps( + { + "run_ref": run_ref, + "stopped": watch.stopped, + "lost": watch.lost, + "failed": watch.failed, + "outcomes": [o.wire() for o in watch.outcomes], + } + ) + ) + return code + + +def cmd_list(args: argparse.Namespace) -> int: + from openadapt_flow.exceptions.registry import ExceptionRegistryError + + try: + cards = _registry(args).open_cards(args.run_ref) + except ExceptionRegistryError as exc: + print(f"REFUSED ({exc.code}): {exc}", file=sys.stderr) + return 2 + if args.json: + print(json.dumps({"cards": [c.wire() for c in cards]}, indent=2)) + return 0 + if not cards: + print("Nothing is waiting for a person.") + return 0 + for card in cards: + print( + f"{card.card_id} {card.kind} run {card.run_ref} until {card.deadline_at}" + ) + print(f" {card.summary}") + for choice in card.choices: + print(f" - {choice.id}: {choice.label}. {choice.consequence}") + return 0 + + +def cmd_answer(args: argparse.Namespace) -> int: + from openadapt_types.exception_card import ExceptionAnswerV1, answer_message + + from openadapt_flow.exceptions.registry import ( + ExceptionRegistryError, + parse_time, + roster_verifier, + ) + from openadapt_flow.execute.keys import sign_bytes + from openadapt_flow.jit.authority import ( + AuthorityError, + load_encrypted_key, + public_hex, + ) + + def refuse(code: str, message: str) -> int: + if args.json: + print(json.dumps({"ok": False, "code": code, "error": message})) + else: + print(f"REFUSED ({code}): {message} Nothing changed.", file=sys.stderr) + return 2 + + registry = _registry(args) + card_id = ( + args.card_id if args.card_id.startswith("sha256:") else f"sha256:{args.card_id}" + ) + try: + found = registry.card(card_id) + except ExceptionRegistryError as exc: + return refuse(exc.code, str(exc)) + if found is None: + return refuse("card_not_found", "No card has that id.") + _run_ref, card = found + try: + unsigned = registry.unsigned_answer(card, args.choice, route="cli") + except ExceptionRegistryError as exc: + return refuse(exc.code, str(exc)) + if parse_time(unsigned["decided_at"]) > parse_time(card.deadline_at): + return refuse("card_expired", "The card expired.") + key_dir, root = _pin(args) + try: + key = load_encrypted_key(args.key or KEY_DEFAULT) + except (AuthorityError, OSError, ValueError) as exc: + return refuse("approver_key_unusable", str(exc)) + signed = { + **unsigned, + "public_key": public_hex(key), + "signature": sign_bytes(key, answer_message(unsigned)), + } + del key + answer = ExceptionAnswerV1.model_validate(signed) + refusal = roster_verifier(key_dir, root)(answer) + if refusal is not None: + return refuse(refusal, "The waiting run wouldn't accept this key's answer.") + try: + registry.write_answer(card, answer.wire()) + except ExceptionRegistryError as exc: + return refuse(exc.code, str(exc)) + if args.json: + print(json.dumps({"ok": True, "answer": answer.wire()})) + else: + print(f"Answered {card.card_id}: {args.choice}.") + return 0 + + +__all__ = ["register"] diff --git a/packages/flow/openadapt_flow/exceptions/detectors.py b/packages/flow/openadapt_flow/exceptions/detectors.py new file mode 100644 index 0000000000..49afb81c04 --- /dev/null +++ b/packages/flow/openadapt_flow/exceptions/detectors.py @@ -0,0 +1,519 @@ +"""Detectors: should this run stop and ask a person? + +Pure functions over what an agent can already see: the screen's text, an +accessibility snapshot, a DOM snapshot when there is one, and timing. Each +detector returns an exception kind (``openadapt_types.exception_card``) or +``None``. Nothing here reads an app, names an app, or drives anything; a +caller (a guard, a harness, the agent itself through ``raise_exception``) +decides what to do with the kind. + +The signals are general: + +* ``second_factor``: an input marked ``autocomplete=one-time-code``, or a + short numeric input labelled with a word like *code* or *verification*. +* ``session_expired``: a password field after the run has reached a screen + where it could save (the caller says when that happened). +* ``unexpected_dialog``: a modal on top of the page, covering the target. +* ``timeout_or_stall``: no action and no screen change for N seconds. +* ``possible_duplicate``: a row already read from the app matches the + proposed record on every field of ``record.duplicate_key`` (verify.yaml). + +Uncertain means ask, not go on. A detector that can't tell (a modal with no +geometry, a duplicate read that failed, a stall clock with no last event) +returns its kind. + +Elements are plain dicts, so any snapshot can be mapped to them: +``tag``, ``type``, ``role``, ``name``, ``id``, ``label``, ``placeholder``, +``autocomplete``, ``inputmode``, ``pattern``, ``maxlength``, ``context`` +(text just before the element), ``visible`` (default true), ``modal``, +``bbox`` (``[x, y, width, height]``) and ``z``. :func:`elements_from_html` +and :func:`elements_from_accessibility` build them. +""" + +from __future__ import annotations + +import re +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from html.parser import HTMLParser +from typing import Any, Optional + +Element = Mapping[str, Any] + +#: Words that make a short input a second-factor code (any language a deployer +#: adds goes in ``code_words``; these are the defaults). +CODE_WORDS = ( + "code", + "verification", + "verify", + "passcode", + "one-time", + "one time", + "otp", + "2fa", + "two-factor", + "two factor", + "authenticator", + "security key", +) +#: Screen text that says a code was sent, whatever the field looks like. +CODE_PHRASES = ( + "verification code", + "one-time code", + "one-time password", + "enter the code", + "two-factor", + "authentication code", + "security code", +) +SESSION_PHRASES = ( + "session expired", + "session has expired", + "signed out", + "sign in again", + "log in again", + "please log in", + "please sign in", +) +DIALOG_ROLES = frozenset({"dialog", "alertdialog"}) +_TEXT_INPUT_TYPES = frozenset({"", "text", "tel", "number", "search"}) +_VOID = frozenset( + { + "input", + "br", + "img", + "meta", + "link", + "hr", + "area", + "base", + "col", + "embed", + "source", + "wbr", + } +) +DEFAULT_STALL_S = 120.0 + + +def _s(value: Any) -> str: + return " ".join(str(value or "").split()).casefold() + + +def _visible(element: Element) -> bool: + return element.get("visible", True) is not False + + +def _words(element: Element) -> str: + return " ".join( + _s(element.get(key)) + for key in ("label", "name", "id", "placeholder", "context", "aria_label") + ) + + +def _is_input(element: Element) -> bool: + tag = _s(element.get("tag")) + role = _s(element.get("role")) + return tag in {"input", "textarea"} or role in {"textbox", "spinbutton"} + + +def _is_password(element: Element) -> bool: + role = _s(element.get("role")) + return ( + (_s(element.get("tag")) == "input" and _s(element.get("type")) == "password") + or role in {"password", "securetextfield", "axsecuretextfield", "password text"} + or element.get("protected") is True + ) + + +def _short_numeric(element: Element) -> bool: + if _s(element.get("type")) not in _TEXT_INPUT_TYPES: + return False + inputmode = _s(element.get("inputmode")) + pattern = str(element.get("pattern") or "") + try: + maxlength = int(element.get("maxlength") or 0) + except (TypeError, ValueError): + maxlength = 0 + numeric = ( + inputmode == "numeric" + or _s(element.get("type")) in {"number", "tel"} + or bool(re.search(r"\\d|\[0-9\]", pattern)) + ) + short = 3 <= maxlength <= 10 + return numeric or short + + +# -- detectors ----------------------------------------------------------------- + + +def second_factor( + elements: Sequence[Element] = (), + screen_text: str = "", + *, + code_words: Iterable[str] = CODE_WORDS, +) -> Optional[str]: + """``second_factor`` when the screen asks for a one-time code.""" + + words = tuple(_s(w) for w in code_words) + inputs = [e for e in elements if _visible(e) and _is_input(e)] + for element in inputs: + if _s(element.get("autocomplete")) == "one-time-code": + return "second_factor" + if _short_numeric(element) and any(w in _words(element) for w in words): + return "second_factor" + text = _s(screen_text) + if any(phrase in text for phrase in CODE_PHRASES): + # The screen says a code is wanted. A visible text input, or no + # structure to look at, is enough: uncertain means ask. + if not elements or any(not _is_password(e) for e in inputs): + return "second_factor" + return None + + +def session_expired( + elements: Sequence[Element] = (), + screen_text: str = "", + *, + save_eligible_seen: bool, +) -> Optional[str]: + """``session_expired`` when a sign-in appears after a save-eligible screen. + + Before the run reached a screen where it could save, a password field is + the ordinary start of a task, not an exception. + """ + + if not save_eligible_seen: + return None + if any(_visible(e) and _is_password(e) for e in elements): + return "session_expired" + text = _s(screen_text) + if any(phrase in text for phrase in SESSION_PHRASES): + return "session_expired" + return None + + +def _covers(outer: Sequence[float], inner: Sequence[float]) -> bool: + ox, oy, ow, oh = (float(v) for v in outer) + ix, iy, iw, ih = (float(v) for v in inner) + cx, cy = ix + iw / 2, iy + ih / 2 + return ox <= cx <= ox + ow and oy <= cy <= oy + oh + + +def _bbox(element: Element) -> Optional[Sequence[float]]: + box = element.get("bbox") + if isinstance(box, (list, tuple)) and len(box) == 4: + try: + values = [float(v) for v in box] + except (TypeError, ValueError): + return None + if values[2] > 0 and values[3] > 0: + return values + return None + + +def unexpected_dialog( + elements: Sequence[Element] = (), + *, + target: Optional[Element] = None, + expected_dialog: bool = False, +) -> Optional[str]: + """``unexpected_dialog`` when a modal sits on top of the target. + + A modal (``aria-modal``, an open ````, a ``dialog`` or + ``alertdialog`` role) blocks the page. With geometry for both, a modal + that doesn't cover the target's centre is not in the way. Without + geometry the detector can't tell, so it asks. ``expected_dialog`` is the + caller saying this step opens one (a confirm box it means to answer). + """ + + if expected_dialog: + return None + dialogs = [ + e + for e in elements + if _visible(e) + and ( + e.get("modal") is True + or _s(e.get("role")) in DIALOG_ROLES + or (_s(e.get("tag")) == "dialog" and e.get("open") is True) + ) + ] + if not dialogs: + return None + target_box = _bbox(target) if target is not None else None + target_z = float((target or {}).get("z") or 0) + for dialog in dialogs: + if dialog.get("modal") is True: + return "unexpected_dialog" # a modal blocks everything under it + box = _bbox(dialog) + if box is None or target_box is None: + return "unexpected_dialog" + if _covers(box, target_box) and float(dialog.get("z") or 0) >= target_z: + return "unexpected_dialog" + return None + + +def timeout_or_stall( + *, + now: float, + last_action_at: Optional[float], + last_change_at: Optional[float], + stall_s: float = DEFAULT_STALL_S, +) -> Optional[str]: + """``timeout_or_stall`` when neither an action nor a screen change happened + for ``stall_s`` seconds. A clock with no last event can't show progress.""" + + events = [t for t in (last_action_at, last_change_at) if t is not None] + if not events: + return "timeout_or_stall" + if now - max(events) >= stall_s: + return "timeout_or_stall" + return None + + +def _key_fields(duplicate_key: Any) -> Optional[list[str]]: + if duplicate_key is None: + return None + if isinstance(duplicate_key, str): + return [duplicate_key] if duplicate_key.strip() else [] + if isinstance(duplicate_key, (list, tuple)): + return [str(name) for name in duplicate_key] + return [] # a key spec of another shape can't be checked + + +def duplicate_key_from_config(config: Mapping[str, Any]) -> Any: + """``record.duplicate_key`` from a loaded verify.yaml, or ``None``.""" + + record = config.get("record") if isinstance(config, Mapping) else None + return record.get("duplicate_key") if isinstance(record, Mapping) else None + + +def possible_duplicate( + duplicate_key: Any, + proposed: Mapping[str, Any], + existing: Optional[Sequence[Mapping[str, Any]]], +) -> Optional[str]: + """``possible_duplicate`` when a row already in the app has the same key. + + ``duplicate_key`` is ``record.duplicate_key`` (one field or a list). + ``existing`` is what the caller already read (``None`` when the read + failed). This function reads nothing. A key with no fields, a proposed + record without a key value, a failed read, or a row missing a key field + can't rule a duplicate out, so it asks. + """ + + fields = _key_fields(duplicate_key) + if fields is None: + return None + if not fields or existing is None: + return "possible_duplicate" + wanted = {} + for name in fields: + value = _s(proposed.get(name)) + if not value: + return "possible_duplicate" + wanted[name] = value + for row in existing: + if not isinstance(row, Mapping): + return "possible_duplicate" + if any(name not in row for name in fields): + return "possible_duplicate" + if all(_s(row.get(name)) == wanted[name] for name in fields): + return "possible_duplicate" + return None + + +# -- all of them ----------------------------------------------------------------- + + +@dataclass(frozen=True) +class Observation: + """One look at the run: what's on screen, and when things last happened.""" + + screen_text: str = "" + elements: Sequence[Element] = () + target: Optional[Element] = None + save_eligible_seen: bool = False + expected_dialog: bool = False + #: Seconds on one clock. ``now`` None means "don't check for a stall". + now: Optional[float] = None + last_action_at: Optional[float] = None + last_change_at: Optional[float] = None + stall_s: float = DEFAULT_STALL_S + #: The duplicate check, when the caller has one: key spec, the proposed + #: record, and the rows it read (None when the read failed). + duplicate_key: Any = None + proposed: Mapping[str, Any] = field(default_factory=dict) + existing: Optional[Sequence[Mapping[str, Any]]] = () + + +def detect_all(observation: Observation) -> list[str]: + """Every kind the observation shows, most urgent first.""" + + found: list[str] = [] + o = observation + for kind in ( + second_factor(o.elements, o.screen_text), + session_expired( + o.elements, o.screen_text, save_eligible_seen=o.save_eligible_seen + ), + unexpected_dialog( + o.elements, target=o.target, expected_dialog=o.expected_dialog + ), + None + if o.now is None + else timeout_or_stall( + now=o.now, + last_action_at=o.last_action_at, + last_change_at=o.last_change_at, + stall_s=o.stall_s, + ), + possible_duplicate(o.duplicate_key, o.proposed, o.existing) + if o.duplicate_key is not None + else None, + ): + if kind is not None and kind not in found: + found.append(kind) + return found + + +def detect(observation: Observation) -> Optional[str]: + """The most urgent kind, or ``None`` when nothing calls for a person.""" + + found = detect_all(observation) + return found[0] if found else None + + +# -- snapshots --------------------------------------------------------------------- + + +class _Snapshot(HTMLParser): + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.elements: list[dict[str, Any]] = [] + self.labels: dict[str, str] = {} + self._label_for: Optional[str] = None + self._label_text: list[str] = [] + self._hidden: list[bool] = [] + self._text: list[str] = [] + + def _hidden_now(self) -> bool: + return any(self._hidden) + + def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None: + a = {k.lower(): (v if v is not None else "") for k, v in attrs} + style = _s(a.get("style")).replace(" ", "") + hidden = ( + "hidden" in a + or a.get("aria-hidden") == "true" + or "display:none" in style + or "visibility:hidden" in style + ) + visible = not (hidden or self._hidden_now()) + if tag == "label": + self._label_for = a.get("for") or "" + self._label_text = [] + role = a.get("role", "") + if tag in {"input", "textarea", "select", "button", "dialog"} or role: + context = " ".join(self._text)[-160:] + element = { + "tag": tag, + "type": a.get("type", "text" if tag == "input" else ""), + "role": role, + "id": a.get("id", ""), + "name": a.get("name", ""), + "placeholder": a.get("placeholder", ""), + "autocomplete": a.get("autocomplete", ""), + "inputmode": a.get("inputmode", ""), + "pattern": a.get("pattern", ""), + "maxlength": a.get("maxlength", ""), + "aria_label": a.get("aria-label", ""), + "context": context, + "visible": visible and a.get("type") != "hidden", + "modal": a.get("aria-modal") == "true", + "open": "open" in a, + } + self.elements.append(element) + if tag not in _VOID: + self._hidden.append(hidden) + + def handle_endtag(self, tag: str) -> None: + if tag == "label" and self._label_for is not None: + if self._label_for: + self.labels[self._label_for] = " ".join(self._label_text) + self._label_for = None + if tag not in _VOID and self._hidden: + self._hidden.pop() + + def handle_data(self, data: str) -> None: + text = " ".join(data.split()) + if not text: + return + if self._label_for is not None: + self._label_text.append(text) + if not self._hidden_now(): + self._text.append(text) + + +def elements_from_html(html: str) -> tuple[list[dict[str, Any]], str]: + """A DOM snapshot's elements and its visible text, from HTML. + + No geometry: an HTML string has none, so a non-modal dialog found this + way counts as covering the target (uncertain means ask). + """ + + parser = _Snapshot() + parser.feed(html) + parser.close() + for element in parser.elements: + element["label"] = parser.labels.get(str(element.get("id") or ""), "") + return parser.elements, " ".join(parser._text) + + +def elements_from_accessibility( + nodes: Iterable[Mapping[str, Any]], +) -> list[dict[str, Any]]: + """Accessibility nodes (``role``, ``name``, optional ``bbox``, ``modal``, + ``protected``, ``autocomplete``) as detector elements.""" + + out = [] + for node in nodes: + role = _s(node.get("role")) + out.append( + { + "tag": "input" + if role in {"textbox", "textfield", "axtextfield"} + else "", + "type": "password" if node.get("protected") is True else "text", + "role": "textbox" if role in {"textfield", "axtextfield"} else role, + "name": node.get("name", ""), + "label": node.get("name", ""), + "autocomplete": node.get("autocomplete", ""), + "maxlength": node.get("maxlength", ""), + "inputmode": node.get("inputmode", ""), + "visible": node.get("visible", True), + "modal": node.get("modal") is True, + "bbox": node.get("bbox"), + "z": node.get("z", 0), + "protected": node.get("protected") is True, + } + ) + return out + + +__all__ = [ + "CODE_WORDS", + "DEFAULT_STALL_S", + "Observation", + "detect", + "detect_all", + "duplicate_key_from_config", + "elements_from_accessibility", + "elements_from_html", + "possible_duplicate", + "second_factor", + "session_expired", + "timeout_or_stall", + "unexpected_dialog", +] diff --git a/packages/flow/openadapt_flow/exceptions/mcp_server.py b/packages/flow/openadapt_flow/exceptions/mcp_server.py new file mode 100644 index 0000000000..cd2b7c7825 --- /dev/null +++ b/packages/flow/openadapt_flow/exceptions/mcp_server.py @@ -0,0 +1,224 @@ +"""``openadapt-flow exceptions serve``: one MCP tool any agent can call. + +``raise_exception(kind, summary, screenshot_path?)`` opens a card in the +local registry (:mod:`openadapt_flow.exceptions.registry`), blocks until a +person answers it or it expires, and returns the closed answer: + + {"card_id": "sha256:…", "kind": "second_factor", "answer": "done_by_person", + "proceed": true, "reason": null, "opened_at": "…", "decided_at": "…", + "instruction": "A person answered done_by_person. Go on from the current screen."} + +``proceed`` is true only for a signed ``continue`` or ``done_by_person``. +Anything else tells the agent to stop before any write. The tool can tell an +agent to stop; it can't make a foreign agent stop. Wrap the agent with a +guard for that. + +The server speaks MCP over stdio. Heartbeats go to stderr, never stdout. +""" + +from __future__ import annotations + +import functools +import json +from importlib import import_module +from typing import Any, Optional + +from openadapt_types.exception_card import EXCEPTION_KINDS + +from openadapt_flow.exceptions.registry import ( + DEFAULT_DEADLINE_S, + AnswerVerifier, + ExceptionRegistry, + ExceptionRegistryError, +) + +TOOL_NAME = "raise_exception" + +INPUT_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": { + "kind": {"type": "string", "enum": list(EXCEPTION_KINDS)}, + "summary": { + "type": "string", + "minLength": 1, + "maxLength": 2000, + "description": ( + "What you see, in a sentence. It is scrubbed and cut to 200 " + "characters before a person sees it; never put a code, a " + "password or a record's values here." + ), + }, + "screenshot_path": { + "type": "string", + "maxLength": 4096, + "description": "A local PNG of the screen. Kept only as a scrubbed copy.", + }, + }, + "required": ["kind", "summary"], + "additionalProperties": False, +} + +DESCRIPTION = ( + "Ask a person, then wait for the answer. Call it when you hit a one-time " + "code prompt (second_factor), a dialog you didn't expect (unexpected_dialog), " + "a sign-in page partway through (session_expired), no progress " + "(timeout_or_stall), a record that may already exist (possible_duplicate), " + "two records you can't tell apart (ambiguous_record), or a task you can't " + "finish (cannot_complete). Never type a code or password yourself. Go on " + "only when the result says proceed=true; otherwise stop and write nothing." +) + + +class RaiseException: + """The tool's work, without the protocol (used by tests and the server).""" + + def __init__( + self, + registry: ExceptionRegistry, + *, + run_ref: str, + verify: AnswerVerifier, + task_id: Optional[str] = None, + deadline_s: float = DEFAULT_DEADLINE_S, + poll_s: float = 0.5, + ) -> None: + self.registry = registry + self.run_ref = run_ref + self.verify = verify + self.task_id = task_id + self.deadline_s = deadline_s + self.poll_s = poll_s + + def __call__( + self, kind: str, summary: str, screenshot_path: Optional[str] = None + ) -> dict[str, Any]: + card = self.registry.open( + self.run_ref, + kind, + summary, + task_id=self.task_id, + screenshot_path=screenshot_path, + deadline_s=self.deadline_s, + ) + return self.registry.wait(card, verify=self.verify, poll_s=self.poll_s).wire() + + +def _error(types: Any, error_field: str, code: str) -> Any: + body = { + "error": code, + "proceed": False, + "instruction": "Stop now. Make no further writes for this task.", + } + return types.CallToolResult( + content=[types.TextContent(type="text", text=json.dumps(body))], + **{error_field: True}, + ) + + +def build_server(tool: RaiseException) -> Any: + """The MCP server (MCP 1 decorator API or MCP 2 callbacks).""" + + import anyio + from jsonschema import ValidationError, validate + from mcp.server.lowlevel import Server + + types: Any + try: + types = import_module("mcp.types") + except ModuleNotFoundError as error: + if error.name != "mcp.types": + raise + types = import_module("mcp_types") + modern = types.__name__ == "mcp_types" + input_schema_field = "input_schema" if modern else "inputSchema" + error_field = "is_error" if modern else "isError" + structured_field = "structured_content" if modern else "structuredContent" + + async def list_tools() -> list[Any]: + return [ + types.Tool( + name=TOOL_NAME, + description=DESCRIPTION, + **{input_schema_field: INPUT_SCHEMA}, + ) + ] + + async def call_tool(name: str, arguments: Optional[dict[str, Any]]) -> Any: + if name != TOOL_NAME: + return _error(types, error_field, "unknown_tool") + try: + validate(arguments, INPUT_SCHEMA) + except ValidationError: + return _error(types, error_field, "invalid_arguments") + assert arguments is not None + try: + result = await anyio.to_thread.run_sync( + functools.partial( + tool, + arguments["kind"], + arguments["summary"], + arguments.get("screenshot_path"), + ), + abandon_on_cancel=False, + ) + except ExceptionRegistryError as exc: + return _error(types, error_field, exc.code) + except Exception: # noqa: BLE001 - no raw exception text on the wire + return _error(types, error_field, "registry_unavailable") + return types.CallToolResult( + content=[types.TextContent(type="text", text=json.dumps(result))], + **{structured_field: result}, + ) + + instructions = ( + "One tool, raise_exception, asks a person and waits. Go on only when its " + "result has proceed=true. Never relay a code or a password through it." + ) + if hasattr(Server, "list_tools"): + server = Server("openadapt-exceptions", version="1", instructions=instructions) + server.list_tools()(list_tools) + server.call_tool(validate_input=False)(call_tool) + return server + + async def list_v2(context: Any, params: Any) -> Any: + return types.ListToolsResult(tools=await list_tools()) + + async def call_v2(context: Any, params: Any) -> Any: + return await call_tool(params.name, params.arguments) + + callback_server: Any = Server + return callback_server( + "openadapt-exceptions", + version="1", + instructions=instructions, + on_list_tools=list_v2, + on_call_tool=call_v2, + ) + + +def serve(tool: RaiseException) -> None: + """Serve over stdio, keeping every log line off the protocol.""" + + import anyio + from mcp.server.stdio import stdio_server + + from openadapt_flow.agent.mcp import _protected_stdout + + async def run() -> None: + server = build_server(tool) + with _protected_stdout() as wire: + kwargs = {"stdout": wire} if wire is not None else {} + async with stdio_server(**kwargs) as (reader, writer): + await server.run(reader, writer, server.create_initialization_options()) + + anyio.run(run) + + +__all__ = [ + "DESCRIPTION", + "INPUT_SCHEMA", + "TOOL_NAME", + "RaiseException", + "build_server", + "serve", +] diff --git a/packages/flow/openadapt_flow/exceptions/registry.py b/packages/flow/openadapt_flow/exceptions/registry.py new file mode 100644 index 0000000000..8392cf917f --- /dev/null +++ b/packages/flow/openadapt_flow/exceptions/registry.py @@ -0,0 +1,797 @@ +"""The local exception registry: one folder of small files per run. + +``$OPENADAPT_HOME/exceptions//`` (``~/.openadapt`` by default) +holds, for each card: + +- ``card-.json``: the :class:`~openadapt_types.exception_card.ExceptionCardV1` + the run opened, written by :meth:`ExceptionRegistry.open`; +- ``screenshot-.png``: the scrubbed copy the card names, when a + scrubber could redact it; +- ``answer-.json``: the one answer, written by a person's signed answer + (``openadapt-flow exceptions answer``, Desktop, the paired phone) or by the + registry itself when the card expires; +- ``consumed-.json``: written once by the waiting run when it acts on + the answer. An answer is never used twice. + +Files are created exclusively (a temporary file, then a hard link), owner +read and write only (0600), and never replaced. It mirrors the item-approval +folder (``approval_mode/item_approval.py``) without sharing its code. + +The run re-checks every answer itself (:meth:`ExceptionRegistry.wait`). +``continue`` and ``done_by_person`` let it go on only when the answer is +signed by a key on the pinned approver roster, names this exact card, is one +of the card's choices and was decided before the deadline. Everything else +(decline, skip, abort, expiry, an answer that can't be read, verified or +matched) means stop before any write. + +Nothing here is sent anywhere. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import stat +import sys +import time +import uuid +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Any, Optional + +from openadapt_types.exception_card import ( + EXCEPTION_KINDS, + RUN_REF_PATTERN, + SUMMARY_MAX, + ExceptionAnswerV1, + ExceptionCardV1, + ExceptionChoice, + answer_message, + card_digest, +) + +from openadapt_flow.private_file import open_binary + +#: How long a card waits for a person by default, and at most. +DEFAULT_DEADLINE_S = 15 * 60 +MAX_DEADLINE_S = 24 * 60 * 60 +HEARTBEAT_S = 30.0 +_MAX_FILE_BYTES = 256 * 1024 +_MAX_SCREENSHOT_BYTES = 8 * 1024 * 1024 +_PNG = b"\x89PNG\r\n\x1a\n" +_RUN_REF = re.compile(RUN_REF_PATTERN) +_HEX_ID = re.compile(r"^[0-9a-f]{64}$") + + +def _c(answer: str, label: str, consequence: str) -> ExceptionChoice: + return ExceptionChoice(id=answer, label=label, consequence=consequence) # type: ignore[arg-type] + + +_SKIP = _c( + "skip", "Skip this item", "Nothing is saved. The run moves to the next item." +) +_ABORT = _c("abort", "Stop the run", "Nothing more is saved. The whole run stops.") + +#: Each kind's choices, in the order a card shows them. The first is the +#: usual answer; no card offers a choice that writes on its own. +CHOICES: dict[str, tuple[ExceptionChoice, ...]] = { + "second_factor": ( + _c( + "done_by_person", + "I entered the code in the browser", + "You type the code in the live browser yourself. The run then goes on " + "from the same screen. OpenAdapt never sees the code.", + ), + _SKIP, + _ABORT, + ), + "unexpected_dialog": ( + _c( + "done_by_person", + "I dealt with the dialog", + "You close or answer the dialog yourself. The run then goes on.", + ), + _c( + "continue", + "It's harmless, go on", + "The run goes on with the dialog as it is, and every check still runs.", + ), + _SKIP, + _ABORT, + ), + "session_expired": ( + _c( + "done_by_person", + "I signed in again", + "You sign in yourself in the live browser. The run then goes on. " + "OpenAdapt never sees the password.", + ), + _SKIP, + _ABORT, + ), + "timeout_or_stall": ( + _c( + "continue", + "Keep waiting", + "The run tries the step again, with every check.", + ), + _SKIP, + _ABORT, + ), + "possible_duplicate": ( + _c( + "skip", + "Same record: don't add it", + "Nothing is saved. The item closes as skipped.", + ), + _c( + "continue", + "Different record: go on", + "The run goes on to fill the form. The save still needs every check.", + ), + _c( + "done_by_person", + "I'll do this one by hand", + "Nothing is saved by OpenAdapt. The item closes as done by a person.", + ), + _ABORT, + ), + "ambiguous_record": ( + _c( + "done_by_person", + "I opened the right record", + "You open the right record yourself. The run then goes on from there.", + ), + _SKIP, + _c( + "decline", + "This item shouldn't be done", + "Nothing is saved. The item closes as declined.", + ), + ), + "cannot_complete": ( + _c( + "done_by_person", + "I did it by hand", + "Nothing is saved by OpenAdapt. The item closes as done by a person.", + ), + _SKIP, + _ABORT, + ), +} + +#: What a card says when the agent's own words can't be scrubbed first. +GENERIC_SUMMARIES: dict[str, str] = { + "second_factor": "The app is asking for a one-time code. Enter it in the browser.", + "unexpected_dialog": "A dialog the run didn't expect is covering the page.", + "session_expired": "The app is asking to sign in again partway through the task.", + "timeout_or_stall": "The run has made no progress for a while.", + "possible_duplicate": "The app may already have this record.", + "ambiguous_record": "The run can't tell which record is the right one.", + "cannot_complete": "The run can't finish this item on its own.", +} + +assert set(CHOICES) == set(EXCEPTION_KINDS) == set(GENERIC_SUMMARIES) + + +class ExceptionRegistryError(ValueError): + def __init__(self, code: str, message: str) -> None: + super().__init__(message) + self.code = code + + +# -- time and text --------------------------------------------------------------- + + +def _now() -> datetime: + return datetime.now(timezone.utc) + + +def iso(value: datetime) -> str: + return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + + +def parse_time(value: str) -> datetime: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + if parsed.tzinfo is None: + raise ValueError("no time zone") + return parsed.astimezone(timezone.utc) + + +_EMAIL = re.compile(r"[\w.+-]+@[\w-]+(\.[\w-]+)+") +_DATE = re.compile(r"\b\d{1,4}[-/.]\d{1,2}[-/.]\d{1,4}\b") +#: Any token holding four or more digits: record numbers, phone numbers, +#: account numbers, codes. +_DIGITS = re.compile(r"\S*(?:\d\S*){4,}") + + +def _pattern_scrub(text: str) -> str: + text = _EMAIL.sub("[email]", text) + text = _DATE.sub("[date]", text) + return _DIGITS.sub("[number]", text) + + +def scrub_summary(kind: str, text: Optional[str]) -> tuple[str, str]: + """``(summary, source)``: the agent's words scrubbed, or the kind's own. + + The summary can reach a paired phone, so this follows the outbound rule + (``openadapt_flow.privacy``): without a working scrubber the agent's text + is dropped and the card says the kind's generic sentence + (``source="generic"``). Digit runs, dates and email addresses are masked + on top of the scrubber either way. + """ + + from openadapt_flow import privacy + + generic = GENERIC_SUMMARIES[kind] + raw = " ".join(str(text or "").split()) + if not raw: + return generic, "generic" + scrubber = privacy.get_scrubber() + if scrubber is None: + return generic, "generic" + try: + scrubbed = scrubber.scrub_text(raw) + except Exception: # noqa: BLE001 - a broken provider scrubs nothing + return generic, "generic" + cleaned = " ".join(_pattern_scrub(str(scrubbed or "")).split()) + if not cleaned: + return generic, "generic" + if len(cleaned) > SUMMARY_MAX: + cleaned = cleaned[: SUMMARY_MAX - 1].rstrip() + "…" + return cleaned, "scrubbed" + + +# -- files ----------------------------------------------------------------------- + + +def _flags(base: int) -> int: + for name in ("O_NOFOLLOW", "O_CLOEXEC"): + base |= getattr(os, name, 0) + return base + + +def _read_regular(path: Path, *, limit: int = _MAX_FILE_BYTES) -> Optional[bytes]: + """The file's bytes, ``None`` when it doesn't exist. Raises ``OSError`` + for a link, a non-regular file or one over ``limit``.""" + + try: + fd = open_binary(path, _flags(os.O_RDONLY)) + except FileNotFoundError: + return None + try: + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + raise OSError("not a small regular file") + data = b"" + while len(data) <= limit: + chunk = os.read(fd, 65536) + if not chunk: + break + data += chunk + if len(data) > limit: + raise OSError("file too large") + return data + finally: + os.close(fd) + + +def _write_exclusive(path: Path, payload: bytes) -> None: + """Create ``path`` once, 0600. Raises ``FileExistsError`` if it's there.""" + + tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp") + fd = open_binary(tmp, _flags(os.O_WRONLY | os.O_CREAT | os.O_EXCL), 0o600) + try: + view = memoryview(payload) + while view: + view = view[os.write(fd, view) :] + os.fsync(fd) + finally: + os.close(fd) + try: + os.link(tmp, path) + finally: + try: + os.unlink(tmp) + except OSError: + pass + try: + dfd = open_binary(path.parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) + except OSError: + return + try: + os.fsync(dfd) + except OSError: + pass + finally: + os.close(dfd) + + +def _json(value: Mapping[str, Any]) -> bytes: + return (json.dumps(value, sort_keys=True, indent=2) + "\n").encode("utf-8") + + +def default_root() -> Path: + home = os.environ.get("OPENADAPT_HOME") + return (Path(home) if home else Path.home() / ".openadapt") / "exceptions" + + +def _hex(card_id: str) -> str: + value = card_id.removeprefix("sha256:") + if not _HEX_ID.fullmatch(value): + raise ExceptionRegistryError("card_id_invalid", "that isn't a card id") + return value + + +# -- outcome --------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Outcome: + """What the waiting run does now.""" + + card_id: str + kind: str + answer: str + #: True only for a verified ``continue`` or ``done_by_person``. + proceed: bool + #: Why the run stops when the answer alone doesn't say: ``expired``, or + #: a closed refusal code for an answer that couldn't be used. + reason: Optional[str] + opened_at: str + decided_at: Optional[str] + + def wire(self) -> dict[str, Any]: + return { + "card_id": self.card_id, + "kind": self.kind, + "answer": self.answer, + "proceed": self.proceed, + "reason": self.reason, + "opened_at": self.opened_at, + "decided_at": self.decided_at, + "instruction": ( + f"A person answered {self.answer}. Go on from the current screen." + if self.proceed + else "Stop now. Make no further writes for this task." + ), + } + + +#: ``verify(answer)`` returns ``None`` for a valid signature by a key on the +#: pinned approver roster, or a closed refusal code. +AnswerVerifier = Callable[[ExceptionAnswerV1], Optional[str]] + + +def roster_verifier(key_dir: Optional[Path], root: Optional[str]) -> AnswerVerifier: + """Check answers against Flow's signed approver roster (``jit approver``). + + Without a key directory or a pinned root no person's answer counts. + """ + + def verify(answer: ExceptionAnswerV1) -> Optional[str]: + from openadapt_flow.approval_mode.human_attestation import ( + AttestationRefused, + approvers, + ) + from openadapt_flow.execute.keys import verify_signature + from openadapt_flow.jit.authority import _public + + if key_dir is None: + return "human_answer_unverifiable" + try: + known = approvers(key_dir, root) + except AttestationRefused as exc: + return exc.code + if not answer.public_key or answer.public_key not in set(known.values()): + return "human_approver_unregistered" + try: + public = _public(answer.public_key) + except ValueError: + return "human_answer_signature_invalid" + if not verify_signature( + public, answer_message(answer.wire()), str(answer.signature or "") + ): + return "human_answer_signature_invalid" + return None + + return verify + + +def _stop(card: ExceptionCardV1, reason: str, answer: str = "decline") -> Outcome: + return Outcome(card.card_id, card.kind, answer, False, reason, card.opened_at, None) + + +# -- the registry ---------------------------------------------------------------- + + +class ExceptionRegistry: + """The exceptions folder: open cards, list them, answer them, wait.""" + + def __init__(self, root: Optional[Path | str] = None) -> None: + self.root = Path(root) if root is not None else default_root() + + def run_dir(self, run_ref: str) -> Path: + if not _RUN_REF.fullmatch(run_ref or ""): + raise ExceptionRegistryError( + "run_ref_invalid", "a run reference is letters, digits, '.', '_' or '-'" + ) + return self.root / run_ref + + def _ensure(self, path: Path) -> None: + for directory in (self.root, path): + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + info = os.lstat(directory) + if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode): + raise ExceptionRegistryError( + "registry_unsafe", f"{directory} isn't a plain folder" + ) + if hasattr(os, "getuid") and info.st_uid != os.getuid(): + raise ExceptionRegistryError( + "registry_unsafe", f"{directory} belongs to another user" + ) + + # -- opening ----------------------------------------------------------- + + def _copy_screenshot(self, folder: Path, source: Optional[str]) -> Optional[str]: + """A scrubbed copy of the agent's screenshot, or ``None``. + + The path is the agent's: only a regular PNG file under the size cap + is read, never through a link. Without a scrubber that can redact + it, no image is kept. + """ + + if not source: + return None + from openadapt_flow import privacy + + try: + data = _read_regular(Path(source), limit=_MAX_SCREENSHOT_BYTES) + except OSError: + return None + if not data or not data.startswith(_PNG): + return None + if privacy.get_scrubber() is None: + return None + try: + redacted = privacy.scrub_image_bytes(data, force=True) + except Exception: # noqa: BLE001 - no redaction, no image + return None + if not redacted.startswith(_PNG): + return None + name = f"screenshot-{hashlib.sha256(redacted).hexdigest()[:32]}.png" + try: + _write_exclusive(folder / name, redacted) + except FileExistsError: + pass + return name + + def open( + self, + run_ref: str, + kind: str, + summary: Optional[str], + *, + task_id: Optional[str] = None, + screenshot_path: Optional[str] = None, + deadline_s: float = DEFAULT_DEADLINE_S, + now: Optional[datetime] = None, + ) -> ExceptionCardV1: + """Write a new card and return it. Raises ``ExceptionRegistryError``.""" + + if kind not in CHOICES: + raise ExceptionRegistryError( + "kind_unknown", "kind is one of " + ", ".join(EXCEPTION_KINDS) + ) + folder = self.run_dir(run_ref) + self._ensure(folder) + opened = now or _now() + seconds = max(1.0, min(float(deadline_s), MAX_DEADLINE_S)) + text, _source = scrub_summary(kind, summary) + if task_id is not None: + task_id = _pattern_scrub(" ".join(str(task_id).split()))[:128] or None + body = { + "schema": "openadapt.exception-card/v1", + "run_ref": run_ref, + "task_id": task_id, + "kind": kind, + "opened_at": iso(opened), + "deadline_at": iso(opened + timedelta(seconds=seconds)), + "screenshot_ref": self._copy_screenshot(folder, screenshot_path), + "summary": text, + "choices": [c.model_dump(mode="json") for c in CHOICES[kind]], + } + for _attempt in range(3): + card = ExceptionCardV1.model_validate( + {**body, "card_id": card_digest(body)} + ) + try: + _write_exclusive( + folder / f"card-{_hex(card.card_id)}.json", _json(card.wire()) + ) + return card + except FileExistsError: + opened = opened + timedelta(microseconds=1) + body["opened_at"] = iso(opened) + body["deadline_at"] = iso(opened + timedelta(seconds=seconds)) + raise ExceptionRegistryError("card_exists", "could not open a new card") + + # -- reading ----------------------------------------------------------- + + def _load(self, path: Path, model: Any) -> Any: + data = _read_regular(path) + if data is None: + return None + return model.model_validate(json.loads(data)) + + def card(self, card_id: str) -> Optional[tuple[str, ExceptionCardV1]]: + """``(run_ref, card)`` for an id, searching every run's folder.""" + + name = f"card-{_hex(card_id)}.json" + if not self.root.is_dir(): + return None + for folder in sorted(self.root.iterdir()): + if not _RUN_REF.fullmatch(folder.name) or not (folder / name).exists(): + continue + try: + card = self._load(folder / name, ExceptionCardV1) + except (OSError, ValueError): + return None + if card is not None and card.run_ref == folder.name: + return folder.name, card + return None + + def read_answer(self, card: ExceptionCardV1) -> Optional[ExceptionAnswerV1]: + """The card's answer, ``None`` if there isn't one. Raises on a bad file.""" + + return self._load( + self.run_dir(card.run_ref) / f"answer-{_hex(card.card_id)}.json", + ExceptionAnswerV1, + ) + + def open_cards(self, run_ref: Optional[str] = None) -> list[ExceptionCardV1]: + """Cards with no answer yet, oldest first. Unreadable files are skipped.""" + + if not self.root.is_dir(): + return [] + folders = [self.run_dir(run_ref)] if run_ref else sorted(self.root.iterdir()) + cards = [] + for folder in folders: + if not folder.is_dir() or not _RUN_REF.fullmatch(folder.name): + continue + for path in sorted(folder.glob("card-*.json")): + try: + card = self._load(path, ExceptionCardV1) + except (OSError, ValueError): + continue + if card is None or card.run_ref != folder.name: + continue + if path.name != f"card-{_hex(card.card_id)}.json": + continue + if (folder / f"answer-{_hex(card.card_id)}.json").exists(): + continue + cards.append(card) + return sorted(cards, key=lambda c: c.opened_at) + + # -- answering --------------------------------------------------------- + + def unsigned_answer( + self, + card: ExceptionCardV1, + answer: str, + *, + route: str, + now: Optional[datetime] = None, + ) -> dict[str, Any]: + """The answer a person's key signs (no key or signature yet).""" + + if not card.offers(answer): + raise ExceptionRegistryError( + "choice_not_offered", "that answer isn't one of the card's choices" + ) + return { + "schema": "openadapt.exception-answer/v1", + "card_id": card.card_id, + "kind": card.kind, + "opened_at": card.opened_at, + "decided_at": iso(now or _now()), + "answer": answer, + "approver_kind": "person", + "route": route, + "reason": None, + } + + def write_answer( + self, card: ExceptionCardV1, answer: Mapping[str, Any] + ) -> ExceptionAnswerV1: + """Write the card's one answer. Raises ``ExceptionRegistryError``.""" + + model = ExceptionAnswerV1.model_validate(dict(answer)) + if model.card_id != card.card_id or model.kind != card.kind: + raise ExceptionRegistryError( + "answer_mismatch", "the answer names another card" + ) + folder = self.run_dir(card.run_ref) + self._ensure(folder) + try: + _write_exclusive( + folder / f"answer-{_hex(card.card_id)}.json", _json(model.wire()) + ) + except FileExistsError: + raise ExceptionRegistryError( + "already_answered", "this card already has an answer" + ) from None + return model + + def _expire(self, card: ExceptionCardV1) -> None: + record = ExceptionAnswerV1.model_validate( + { + "schema": "openadapt.exception-answer/v1", + "card_id": card.card_id, + "kind": card.kind, + "opened_at": card.opened_at, + "decided_at": None, + "answer": "decline", + "approver_kind": "expiry", + "route": "registry", + "reason": "expired", + } + ) + _write_exclusive( + self.run_dir(card.run_ref) / f"answer-{_hex(card.card_id)}.json", + _json(record.wire()), + ) + + def _settle( + self, card: ExceptionCardV1, answer: ExceptionAnswerV1, verify: AnswerVerifier + ) -> Outcome: + if answer.card_id != card.card_id or answer.kind != card.kind: + return _stop(card, "answer_mismatch") + if answer.opened_at != card.opened_at: + return _stop(card, "answer_mismatch") + if answer.approver_kind == "expiry": + outcome = _stop(card, "expired") + else: + if not card.offers(answer.answer): + return _stop(card, "choice_not_offered") + try: + decided = parse_time(str(answer.decided_at)) + except ValueError: + return _stop(card, "answer_time_invalid") + if decided < parse_time(card.opened_at): + return _stop(card, "answer_time_invalid") + if decided > parse_time(card.deadline_at): + return _stop(card, "answer_late") + refusal = verify(answer) + if refusal is not None: + return _stop(card, refusal) + outcome = Outcome( + card.card_id, + card.kind, + answer.answer, + answer.proceeds, + None, + card.opened_at, + answer.decided_at, + ) + consumed = { + "card_id": card.card_id, + "answer": outcome.answer, + "proceed": outcome.proceed, + "reason": outcome.reason, + "consumed_at": iso(_now()), + } + try: + _write_exclusive( + self.run_dir(card.run_ref) / f"consumed-{_hex(card.card_id)}.json", + _json(consumed), + ) + except FileExistsError: + return _stop(card, "answer_already_used", outcome.answer) + return outcome + + def poll( + self, + card: ExceptionCardV1, + *, + verify: AnswerVerifier, + deadline: Optional[datetime] = None, + clock: Callable[[], datetime] = _now, + now: Optional[datetime] = None, + ) -> Optional[Outcome]: + """One look at the card: what to do once it is answered or expired, + ``None`` while it is still open. Never blocks; :meth:`wait` loops on + it, and a caller with its own loop (the browser watch) calls it.""" + + end = parse_time(card.deadline_at) + if deadline is not None: + end = min(end, deadline.astimezone(timezone.utc)) + for _attempt in range(3): + try: + answer = self.read_answer(card) + except (OSError, ValueError): + return _stop(card, "answer_unreadable") + if answer is not None: + return self._settle(card, answer, verify) + if (now if now is not None else clock()) < end: + return None + try: + self._expire(card) + except FileExistsError: + continue # a person's answer won the race: read it + except OSError: + return _stop(card, "expired") + return _stop(card, "answer_unreadable") + + def wait( + self, + card: ExceptionCardV1, + *, + verify: AnswerVerifier, + deadline: Optional[datetime] = None, + poll_s: float = 0.5, + heartbeat_s: float = HEARTBEAT_S, + heartbeat: Optional[Callable[[str, float], None]] = None, + clock: Callable[[], datetime] = _now, + sleep: Callable[[float], None] = time.sleep, + ) -> Outcome: + """Block until the card is answered or expires; return what to do. + + ``deadline`` (default the card's ``deadline_at``) can only shorten the + wait. On expiry the registry writes an ``answer=decline``, + ``decided_at=null``, ``reason=expired`` record, unless a person's + answer got there first, which is then checked like any other. + ``heartbeat(card_id, seconds_left)`` is called every ``heartbeat_s`` + (default: a line on stderr, never stdout). + """ + + end = parse_time(card.deadline_at) + if deadline is not None: + end = min(end, deadline.astimezone(timezone.utc)) + beat = heartbeat or _stderr_heartbeat + next_beat = 0.0 + started = time.monotonic() + while True: + try: + answered = self.read_answer(card) is not None + except (OSError, ValueError): + answered = True # poll() reports the unreadable answer + now = None if answered else clock() + outcome = self.poll(card, verify=verify, deadline=deadline, now=now) + if outcome is not None: + return outcome + assert now is not None + elapsed = time.monotonic() - started + if elapsed >= next_beat: + beat(card.card_id, (end - now).total_seconds()) + next_beat = elapsed + heartbeat_s + sleep(poll_s) + + +def _stderr_heartbeat(card_id: str, seconds_left: float) -> None: + print( + f"exceptions: waiting for a person on {card_id[:19]}… " + f"({int(seconds_left)} s left)", + file=sys.stderr, + flush=True, + ) + + +__all__ = [ + "CHOICES", + "DEFAULT_DEADLINE_S", + "GENERIC_SUMMARIES", + "AnswerVerifier", + "ExceptionRegistry", + "ExceptionRegistryError", + "Outcome", + "default_root", + "iso", + "parse_time", + "roster_verifier", + "scrub_summary", +] diff --git a/packages/flow/openadapt_flow/exceptions/watch.py b/packages/flow/openadapt_flow/exceptions/watch.py new file mode 100644 index 0000000000..5a9542b238 --- /dev/null +++ b/packages/flow/openadapt_flow/exceptions/watch.py @@ -0,0 +1,596 @@ +"""Raise exception cards from the agent's browser, without the agent. + +``raise_exception`` (:mod:`.mcp_server`) only works when the agent calls it. +An agent that never calls it never asks anyone. :class:`ExceptionWatch` asks +on its own: it attaches to the agent's Chromium over CDP (the same endpoint +``openadapt-flow guard`` attaches to), looks at the page every ``poll_s``, +runs the :mod:`.detectors`, and when one fires it opens a card in the +registry. While the card is open it holds the run at the browser: every save +the page sends is blocked (CDP ``Fetch``), whatever the agent does. A verified +``continue`` or ``done_by_person`` lifts the hold. Any other outcome (a stop +answer, an expiry, an answer off the roster) keeps every later save blocked +for the rest of the run. + + openadapt-flow exceptions watch --cdp http://127.0.0.1:9222 \\ + --config guard.yaml --run-dir runs/intake-0412 + +What is a save comes from the guard's own config and rules +(:func:`openadapt_flow.agent_guard.requests.classify`): a write to the app's +origin that ``not_saves`` doesn't list, and any write to another origin. A +write ``not_saves`` lists (a sign-in form, the code form a person submits +for a second factor) goes through, so a person can type the code in the live +browser. Reads always go through. + +The watch and the guard each pause requests in their own DevTools session. +Chromium hands a paused request to the session that attached last first, so +start the watch after the guard: it then decides a save before the guard +sees it. (In the other order a blocked save is still never sent, but the +guard has already let it go and ends the run unconfirmed.) + +Covered, from what the page shows: ``second_factor``, ``unexpected_dialog``, +``session_expired`` (a password field after the watch has seen a save) and, +with ``stall_s``, ``timeout_or_stall`` (no request and no screen change). +Not covered: ``possible_duplicate`` (it needs a read of the app's records), +``ambiguous_record`` and ``cannot_complete`` (only the agent knows), +non-browser agents, saves over a WebSocket (``Fetch`` doesn't see them), +tabs other than the one watched, a save sent before the next look at the page +(``poll_s``), and a run with no watch running. The watch is not a sandbox: it can't stop an +agent that has its own way to the app, or one that kills the watch. A watch +that loses its DevTools session exits 4 (holding) or 5 and blocks nothing +from then on; the guard remains the backstop. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from collections.abc import Callable, Mapping, Sequence +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Optional + +from openadapt_flow.exceptions.detectors import DEFAULT_STALL_S, Observation, detect_all +from openadapt_flow.exceptions.registry import ( + DEFAULT_DEADLINE_S, + AnswerVerifier, + ExceptionRegistry, + Outcome, +) + +__all__ = [ + "BLOCK_HEADER", + "SNAPSHOT_JS", + "WATCH_EVENTS", + "ExceptionWatch", + "WatchAttachError", + "drain", + "run_loop", + "watch_browser", +] + +#: The watch's log in the run folder: what it raised and blocked, no values. +WATCH_EVENTS = "exceptions_watch.jsonl" +#: Set on every response the watch makes up for a blocked save. +BLOCK_HEADER = "X-OpenAdapt-Exception" +_PAUSED_TYPES = ("Document", "XHR", "Fetch", "Ping", "Other") + +#: The page, as detector elements (see :mod:`.detectors`), with geometry. +SNAPSHOT_JS = r""" +() => { + const sel = 'input, textarea, select, button, dialog, [role], [aria-modal]'; + const out = []; + const text = (el) => ((el && (el.innerText || el.textContent)) || '').replace(/\s+/g, ' ').trim(); + for (const el of Array.from(document.querySelectorAll(sel)).slice(0, 500)) { + if (el.closest('[data-openadapt-guard]')) continue; + const r = el.getBoundingClientRect(); + const st = getComputedStyle(el); + const visible = r.width > 0 && r.height > 0 && st.visibility !== 'hidden' + && st.display !== 'none' && el.type !== 'hidden'; + let label = ''; + if (el.labels && el.labels.length) label = text(el.labels[0]); + const prev = el.previousElementSibling; + const parent = el.parentElement; + out.push({ + tag: el.tagName.toLowerCase(), + type: (el.getAttribute('type') || (el.tagName === 'INPUT' ? 'text' : '')).toLowerCase(), + role: el.getAttribute('role') || '', + id: el.id || '', + name: el.getAttribute('name') || '', + label: label.slice(0, 160), + aria_label: el.getAttribute('aria-label') || '', + placeholder: el.getAttribute('placeholder') || '', + autocomplete: el.getAttribute('autocomplete') || '', + inputmode: el.getAttribute('inputmode') || '', + pattern: el.getAttribute('pattern') || '', + maxlength: el.getAttribute('maxlength') || '', + context: (prev ? text(prev) : text(parent)).slice(-160), + visible: visible, + modal: el.getAttribute('aria-modal') === 'true' + || (el.tagName === 'DIALOG' && el.matches(':modal')), + open: el.tagName === 'DIALOG' ? el.open : false, + bbox: [r.x, r.y, r.width, r.height], + z: parseInt(st.zIndex, 10) || 0, + }); + } + return {text: text(document.body).slice(0, 20000), elements: out}; +} +""" + + +def _iso(value: datetime) -> str: + return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + + +class ExceptionWatch: + """The watch's decisions, without a browser (the loop is :func:`watch_browser`). + + ``observe`` takes one page snapshot (``{"text", "elements"}``) and opens + a card when a detector fires and none is open. ``on_request`` says + whether a paused request goes on (``None``) or is blocked (a code). + ``poll`` settles an open card without blocking. + """ + + def __init__( + self, + registry: ExceptionRegistry, + *, + run_ref: str, + verify: AnswerVerifier, + app_origin: str, + not_saves: Sequence[Any] = (), + task_id: Optional[str] = None, + deadline_s: float = DEFAULT_DEADLINE_S, + stall_s: Optional[float] = None, + events_path: Optional[Path] = None, + clock: Callable[[], float] = time.monotonic, + ) -> None: + from openadapt_flow.agent_guard.requests import origin_of + + registry.run_dir(run_ref) # refuse a bad name before anything runs + self.registry = registry + self.run_ref = run_ref + self.verify = verify + self.app_origin = origin_of(app_origin) or app_origin + self.not_saves = tuple(not_saves) + self.task_id = task_id + self.deadline_s = deadline_s + self.stall_s = stall_s + self.events_path = events_path + self._clock = clock + self.card: Any = None + #: Why every later save is blocked (a stop outcome), or None. + self.stopped: Optional[str] = None + self.outcomes: list[Outcome] = [] + #: Kinds answered "go on" that the page still shows: not asked again + #: until the page stops showing them. + self._settled: set[str] = set() + self._save_seen = False + #: Why the watch lost the tab (``session_lost``, ``browser_lost``, + #: ``watch_failed``). + self.lost: Optional[str] = None + #: The watch's own error (detection, opening a card, polling): from + #: then on every write is refused until the process exits. + self.failed: Optional[str] = None + self._screen: Optional[str] = None + self._last_change: Optional[float] = None + self._last_request: Optional[float] = None + self._log("watch_started", run_ref=run_ref) + + # -- the log ------------------------------------------------------------- + + def _log(self, event: str, **fields: Any) -> None: + if self.events_path is None: + return + line = {"t": round(self._clock(), 3), "event": event, **fields} + try: + self.events_path.parent.mkdir(parents=True, exist_ok=True) + with self.events_path.open("a", encoding="utf-8") as fh: + fh.write(json.dumps(line, sort_keys=True) + "\n") + except OSError: + pass # the log is lost, never the hold + + # -- decisions ----------------------------------------------------------- + + @property + def holding(self) -> bool: + """Saves are blocked right now.""" + + return ( + self.card is not None or self.stopped is not None or self.failed is not None + ) + + def on_request(self, request: Any) -> Optional[str]: + """``None``: let the paused request go on; else the block's code.""" + + from openadapt_flow.agent_guard.requests import classify + + self._last_request = self._clock() + kind = classify(request, app_origin=self.app_origin, not_saves=self.not_saves) + if kind == "save": + self._save_seen = True + if self.failed is not None and kind != "read": + code = "watch_failed" # the watch broke: no write goes on + elif kind not in ("save", "other_origin") or not self.holding: + return None + else: + code = "exception_open" if self.card is not None else "exception_stopped" + self._log( + "request_blocked", + code=code, + kind=kind, + method=request.method, + resource_type=request.resource_type, + ) + return code + + def observe(self, snapshot: Mapping[str, Any]) -> Optional[str]: + """Look at one snapshot; open a card when it calls for a person. + + Returns the kind of the card opened, or None. + """ + + now = self._clock() + text = str(snapshot.get("text") or "") + raw = snapshot.get("elements") + elements = ( + [e for e in raw if isinstance(e, Mapping)] if isinstance(raw, list) else [] + ) + digest = hashlib.sha256( + (text + json.dumps(elements, sort_keys=True, default=str)).encode("utf-8") + ).hexdigest() + if digest != self._screen: + self._screen, self._last_change = digest, now + kinds = detect_all( + Observation( + screen_text=text, + elements=elements, + save_eligible_seen=self._save_seen, + now=now if self.stall_s else None, + last_action_at=self._last_request, + last_change_at=self._last_change, + stall_s=self.stall_s or DEFAULT_STALL_S, + ) + ) + self._settled &= set(kinds) # a kind the page stopped showing may ask again + if self.holding: + return None + fresh = [k for k in kinds if k not in self._settled] + if not fresh: + return None + kind = fresh[0] + self.card = self.registry.open( + self.run_ref, + kind, + None, # the kind's own sentence: nothing from the page is relayed + task_id=self.task_id, + deadline_s=self.deadline_s, + ) + self._log("card_opened", kind=kind, card_id=self.card.card_id) + return kind + + def poll(self) -> Optional[Outcome]: + """Settle the open card if it was answered or expired.""" + + if self.card is None: + return None + outcome = self.registry.poll(self.card, verify=self.verify) + if outcome is None: + return None + self.outcomes.append(outcome) + self._log( + "answer", + card_id=outcome.card_id, + answer=outcome.answer, + proceed=outcome.proceed, + reason=outcome.reason, + ) + if outcome.proceed: + self._settled.add(outcome.kind) + else: + self.stopped = outcome.reason or outcome.answer + self.card = None + return outcome + + def note_decision_failed(self, code: Optional[str], error: str) -> None: + """The browser refused a continue or a block (logged, not fatal).""" + + self._log("request_decision_failed", code=code, error=error[:64]) + + def mark_lost(self, reason: str) -> None: + """The watch can no longer see or hold the tab. From here it blocks + nothing: the guard (``openadapt-flow guard``) is the backstop.""" + + self.lost = reason + self._log( + "watch_lost", + reason=reason, + card_open=self.card is not None, + stopped=self.stopped, + ) + import sys + + what = ( + "every write is refused until the watch exits; after that the " + "watch holds nothing" + if self.failed is not None + else "saves are no longer held by the watch" + ) + held = ( + "; a card was open" + if self.card is not None + else "; the run was stopped" + if self.stopped is not None + else "" + ) + print( + f"exceptions: WATCH LOST ({reason}): {what}{held}", + file=sys.stderr, + flush=True, + ) + + def fail(self, error: BaseException) -> None: + """The watch's own code failed: refuse every write from here on.""" + + if self.failed is not None: + return + self.failed = type(error).__name__ + self.mark_lost("watch_failed") + + def stop_code(self) -> int: + """The watch's exit code: + + * 0: the tab closed or the watch was stopped with nothing open; + * 3: an answer stopped the run; + * 4: the watch failed or lost the tab's session while holding saves + (a card open, a stop, or its own error); + * 5: it lost the session with nothing held; + * 6: it ended (``max_s``, a signal) with a card still unanswered. + """ + + if self.lost is not None: + return 4 if self.holding else 5 + if self.stopped is not None: + return 3 + return 6 if self.card is not None else 0 + + +# -- the browser loop ------------------------------------------------------------ + + +class WatchAttachError(RuntimeError): + """The watch found no tab to watch (nothing was held).""" + + +def _blocked_body(code: str) -> str: + import base64 + + message = ( + "OpenAdapt is holding this run: a person is answering an exception card. " + "Nothing was sent. Wait, then save again." + if code == "exception_open" + else "A person stopped this run. Nothing was sent; write nothing more." + if code == "exception_stopped" + else "OpenAdapt can't check this request. Nothing was sent; stop and " + "tell a person." + ) + payload = json.dumps({"error": code, "message": message}) + return base64.b64encode(payload.encode("utf-8")).decode("ascii") + + +def _decide(cdp: Any, watch: ExceptionWatch, params: Mapping[str, Any]) -> bool: + """Continue or block one paused request. False when the browser refused + the decision (the page aborted the request, or the session is gone): the + caller checks the session. A request the page aborted was never sent.""" + + from openadapt_flow.agent_guard.requests import HeldRequest + + request_id = str(params.get("requestId") or "") + try: + code = watch.on_request(HeldRequest.from_cdp(params)) + except Exception: # noqa: BLE001 - can't tell what it is: refuse it + code = "request_unclassified" + try: + if code is None: + cdp.send("Fetch.continueRequest", {"requestId": request_id}) + else: + cdp.send( + "Fetch.fulfillRequest", + { + "requestId": request_id, + "responseCode": 409, + "responseHeaders": [ + {"name": "Content-Type", "value": "application/json"}, + {"name": BLOCK_HEADER, "value": f"blocked; code={code}"}, + ], + "body": _blocked_body(code), + }, + ) + except Exception as exc: # noqa: BLE001 - one request must not end the watch + watch.note_decision_failed(code, type(exc).__name__) + return False + return True + + +def drain(cdp: Any, watch: ExceptionWatch, paused: list[Mapping[str, Any]]) -> None: + """Decide every paused request before the session detaches. A decision + the browser refuses is skipped; the rest are still decided.""" + + while paused: + try: + _decide(cdp, watch, paused.pop(0)) + except Exception: # noqa: BLE001 - one request never stops the rest + continue + + +def _alive(cdp: Any) -> bool: + """The watch's own DevTools session still answers.""" + + try: + cdp.send("Runtime.evaluate", {"expression": "1", "returnByValue": True}) + return True + except Exception: # noqa: BLE001 - detached or the browser is gone + return False + + +def run_loop( + watch: ExceptionWatch, + page: Any, + cdp: Any, + paused: list[Mapping[str, Any]], + *, + poll_s: float = 0.5, + max_s: Optional[float] = None, + stop: Optional[Callable[[], bool]] = None, +) -> None: + """The watch's loop over an attached tab and its own Fetch session. + + Ends when the tab closes, ``stop()`` or ``max_s``, or when the session is + lost while the tab is still open (:meth:`ExceptionWatch.mark_lost`). + """ + + started = time.monotonic() + next_look = 0.0 + while not page.is_closed(): + while paused: + if not _decide(cdp, watch, paused.pop(0)) and not _alive(cdp): + watch.mark_lost("session_lost") + return + if time.monotonic() >= next_look: + if not _alive(cdp): + if page.is_closed(): + return + watch.mark_lost("session_lost") + return + snapshot = None + if watch.failed is None: + try: + snapshot = page.evaluate(SNAPSHOT_JS) + except Exception: # noqa: BLE001 - navigating: look again + snapshot = None + if watch.failed is None: + try: + if isinstance(snapshot, Mapping): + watch.observe(snapshot) + watch.poll() + except Exception as exc: # noqa: BLE001 - fail closed + # Detection, the card, or its answer broke (a full disk, + # an unwritable registry). The loop goes on, refusing + # every write, until the tab closes, the session is + # lost, a signal or max_s ends it. + watch.fail(exc) + next_look = time.monotonic() + poll_s + if stop is not None and stop(): + return + if max_s is not None and time.monotonic() - started >= max_s: + return + try: + page.wait_for_timeout(50) # delivers CDP events + except Exception: # noqa: BLE001 - the browser went away + if not page.is_closed(): + watch.mark_lost("browser_lost") + return + + +def _page(browser: Any, app_origin: str, page_url: Optional[str]) -> Any: + from openadapt_flow.agent_guard.requests import origin_of + + for context in browser.contexts: + for page in context.pages: + url = page.url or "" + if page_url and url.startswith(page_url): + return page + if not page_url and origin_of(url) == app_origin: + return page + return None + + +def watch_browser( + watch: ExceptionWatch, + *, + cdp_endpoint: str, + page_url: Optional[str] = None, + poll_s: float = 0.5, + attach_wait_s: float = 30.0, + max_s: Optional[float] = None, + on_attached: Optional[Callable[[], None]] = None, + stop: Optional[Callable[[], bool]] = None, +) -> int: + """Attach to the agent's Chromium and run the watch until the tab or the + browser closes, ``max_s`` passes or ``stop()`` says so. Returns the exit + code (:meth:`ExceptionWatch.stop_code`).""" + + from playwright.sync_api import sync_playwright + + from openadapt_flow._browser_readiness import require_rendering_ready + + pw = sync_playwright().start() + try: + deadline = time.monotonic() + attach_wait_s + browser = page = None + while page is None: + try: + browser = pw.chromium.connect_over_cdp(cdp_endpoint) + page = _page(browser, watch.app_origin, page_url) + if page is not None: + # The tab must render before its screen is trusted, as + # for every other CDP attach (the guard's included). + require_rendering_ready(browser, attached_page=page) + except Exception: # noqa: BLE001 - not up or not rendering yet + page = None + if page is None: + if browser is not None: + browser.close() + browser = None + if time.monotonic() >= deadline: + raise WatchAttachError("no tab on the app's origin to watch") + time.sleep(0.25) + cdp = page.context.new_cdp_session(page) + paused: list[Mapping[str, Any]] = [] + cdp.on("Fetch.requestPaused", lambda params: paused.append(params)) + cdp.send( + "Fetch.enable", + { + "patterns": [ + {"urlPattern": "*", "resourceType": t, "requestStage": "Request"} + for t in _PAUSED_TYPES + ] + }, + ) + if on_attached is not None: + on_attached() + started = time.monotonic() + try: + try: + run_loop( + watch, page, cdp, paused, poll_s=poll_s, max_s=max_s, stop=stop + ) + except Exception as exc: # noqa: BLE001 - fail closed, then exit 4 + watch.fail(exc) + # Keep refusing writes in the failed state until the run ends. + left = ( + None + if max_s is None + else max(0.0, max_s - (time.monotonic() - started)) + ) + try: + run_loop( + watch, page, cdp, paused, poll_s=poll_s, max_s=left, stop=stop + ) + except Exception: # noqa: BLE001 - the tab or session is gone + pass + finally: + # Paused requests go on when the session detaches: decide them first. + drain(cdp, watch, paused) + try: + cdp.detach() + except Exception: # noqa: BLE001 - the tab is gone + pass + try: + if browser is not None: + browser.close() + except Exception: # noqa: BLE001 - already closed + pass + finally: + pw.stop() + return watch.stop_code() diff --git a/packages/flow/tests/e2e/test_exception_mcp_e2e.py b/packages/flow/tests/e2e/test_exception_mcp_e2e.py new file mode 100644 index 0000000000..e6bb30e265 --- /dev/null +++ b/packages/flow/tests/e2e/test_exception_mcp_e2e.py @@ -0,0 +1,421 @@ +"""End to end: a scripted agent hits a code prompt, asks through MCP, a +person answers, and the agent goes on or stops. + +The app is a synthetic two-step site on 127.0.0.1: a one-time-code page +until the session is verified, then a form whose saves the app keeps in +memory (read back from ``/api/records``). The "agent" is a script that reads +each page as HTML, runs the exception detectors on it, and talks to +``openadapt-flow exceptions serve`` over real MCP stdio in a subprocess. The +"person" types the code into the app directly (as in the live browser), +then answers with ``openadapt-flow exceptions answer`` in another +subprocess, signed with a synthetic approver key on a fresh roster. When the +monorepo's Desktop package is on disk, Desktop's stop queue is checked to +show the same card. + +Asserted: the agent writes once after ``done_by_person`` and zero times +after a decline or an expiry (read from the app's own state), both answer +timestamps are present, and no planted identifier is in the registry, the +MCP result or Desktop's card. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import threading +import time +import urllib.parse +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any, Callable + +import pytest + +pytest.importorskip("mcp") +import anyio # noqa: E402 +from cryptography.hazmat.primitives import serialization # noqa: E402 +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # noqa: E402 +from mcp import ClientSession, StdioServerParameters # noqa: E402 +from mcp.client.stdio import stdio_client # noqa: E402 + +from openadapt_flow.approval_mode.approver_roster import ( # noqa: E402 + ROOT_ENV, + file_key_signer, + init_root, +) +from openadapt_flow.exceptions.detectors import Observation, detect, elements_from_html # noqa: E402 +from openadapt_flow.jit.authority import public_hex # noqa: E402 + +PLANTED = ("Maribel Quintanilla", "1961-04-09", "88812345") +SUMMARY = "The sign-in for Maribel Quintanilla (1961-04-09, MRN 88812345) wants a code" +CODE = "482913" # synthetic; the person types it into the app, never through OpenAdapt +PASSPHRASE = "synthetic-e2e-passphrase" +REPO = Path(__file__).resolve().parents[4] +DESKTOP = REPO / "packages" / "desktop" + +CODE_PAGE = """

Check your phone

+
+ +
""" +FORM_PAGE = """

New note

+
+
""" + + +class SyntheticApp: + """A code gate, then a form. State lives here, read back by the test.""" + + def __init__(self) -> None: + self.verified = False + self.records: list[dict[str, str]] = [] + self.lock = threading.Lock() + + def handler(self) -> type[BaseHTTPRequestHandler]: + app = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_args: object) -> None: + return None + + def _send(self, status: int, body: str, kind: str = "text/html") -> None: + data = body.encode() + self.send_response(status) + self.send_header("Content-Type", kind) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def _form(self) -> dict[str, str]: + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length).decode() + return {k: v[0] for k, v in urllib.parse.parse_qs(raw).items()} + + def do_GET(self) -> None: # noqa: N802 + if self.path == "/api/records": + with app.lock: + self._send(200, json.dumps(app.records), "application/json") + return + self._send(200, FORM_PAGE if app.verified else CODE_PAGE) + + def do_POST(self) -> None: # noqa: N802 + form = self._form() + if self.path == "/verify": + app.verified = form.get("otc") == CODE + self._send(200, FORM_PAGE if app.verified else CODE_PAGE) + return + if self.path == "/save" and app.verified: + with app.lock: + app.records.append({"note": form.get("note", "")}) + self._send(200, "

Saved

") + return + self._send(403, "

Not signed in

") + + return Handler + + +@pytest.fixture +def app(): + state = SyntheticApp() + server = ThreadingHTTPServer(("127.0.0.1", 0), state.handler()) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + yield f"http://127.0.0.1:{server.server_address[1]}", state + server.shutdown() + server.server_close() + + +@pytest.fixture +def env(tmp_path: Path) -> dict[str, str]: + """A fresh OPENADAPT_HOME, roster and encrypted approver key.""" + + key_dir = tmp_path / "keys" + key = Ed25519PrivateKey.generate() + init_root( + key_dir, + principal="front-desk", + public_key=public_hex(key), + sign=file_key_signer(key), + ) + pem = tmp_path / "approver.pem" + pem.write_bytes( + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.BestAvailableEncryption(PASSPHRASE.encode()), + ) + ) + pem.chmod(0o600) + home = tmp_path / "home" + home.mkdir() + out = { + k: v + for k, v in os.environ.items() + if k not in {ROOT_ENV, "OPENADAPT_JIT_KEY_DIR", "OPENADAPT_HOME"} + } + out.update( + { + "OPENADAPT_HOME": str(home), + "OPENADAPT_JIT_KEY_DIR": str(key_dir), + ROOT_ENV: public_hex(key), + "OPENADAPT_JIT_KEY_PASSPHRASE": PASSPHRASE, + "OPENADAPT_TEST_KEY_PEM": str(pem), + "HOME": str(tmp_path), + } + ) + return out + + +def _get(url: str) -> str: + with urllib.request.urlopen(url, timeout=10) as response: # noqa: S310 - 127.0.0.1 + return response.read().decode() + + +def _post(url: str, data: dict[str, str]) -> str: + body = urllib.parse.urlencode(data).encode() + with urllib.request.urlopen(url, data=body, timeout=10) as response: # noqa: S310 + return response.read().decode() + + +def _registry(env: dict[str, str]) -> Path: + return Path(env["OPENADAPT_HOME"]) / "exceptions" + + +def _wait_for_card(env: dict[str, str], timeout: float = 60) -> dict[str, Any]: + end = time.monotonic() + timeout + while time.monotonic() < end: + for path in _registry(env).rglob("card-*.json"): + answer = path.with_name(path.name.replace("card-", "answer-")) + if not answer.exists(): + return json.loads(path.read_text()) + time.sleep(0.2) + raise AssertionError("no card appeared") + + +def _desktop_cards(env: dict[str, str]) -> list[dict[str, Any]] | None: + """Desktop's stop queue for the registry, when Desktop's source is here.""" + + if not (DESKTOP / "openadapt_desktop" / "exception_queue.py").is_file(): + return None + if str(DESKTOP) not in sys.path: + sys.path.insert(0, str(DESKTOP)) + from openadapt_desktop import exception_queue, stop_queue + + cards = [ + stop_queue.card_for_exception(raw) + for raw in exception_queue.open_cards(_registry(env)) + ] + return [c for c in cards if c is not None] + + +def _answer( + env: dict[str, str], card_id: str, choice: str +) -> subprocess.CompletedProcess: + return subprocess.run( + [ + sys.executable, + "-m", + "openadapt_flow", + "exceptions", + "answer", + card_id, + choice, + "--key", + env["OPENADAPT_TEST_KEY_PEM"], + "--json", + ], + env=env, + capture_output=True, + text=True, + timeout=120, + ) + + +async def _agent(base: str, env: dict[str, str], deadline_s: float) -> dict[str, Any]: + """The scripted agent: look, ask when a detector fires, write only if told.""" + + params = StdioServerParameters( + command=sys.executable, + args=[ + "-m", + "openadapt_flow", + "exceptions", + "serve", + "--run-ref", + "e2e-run", + "--task-id", + "note-intake", + "--deadline-s", + str(deadline_s), + ], + env=env, + ) + log: dict[str, Any] = {"asked": [], "wrote": False} + async with stdio_client(params) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + tools = await session.list_tools() + assert [t.name for t in tools.tools] == ["raise_exception"] + for _step in range(4): + page = await anyio.to_thread.run_sync(_get, base + "/") + elements, text = elements_from_html(page) + kind = detect(Observation(screen_text=text, elements=elements)) + if kind is not None: + result = await session.call_tool( + "raise_exception", {"kind": kind, "summary": SUMMARY} + ) + body = json.loads(result.content[0].text) + log["asked"].append(body) + if not body.get("proceed"): + return log # stop before any write + continue + if "Save" in page: + await anyio.to_thread.run_sync( + _post, base + "/save", {"note": "synthetic note"} + ) + log["wrote"] = True + return log + return log + + +def _run_agent( + base: str, env: dict[str, str], deadline_s: float, person: Callable[[], None] +): + result: dict[str, Any] = {} + + def agent() -> None: + result.update(anyio.run(_agent, base, env, deadline_s)) + + thread = threading.Thread(target=agent) + thread.start() + person() + thread.join(timeout=180) + assert not thread.is_alive(), "the agent never finished" + return result + + +def _no_planted(*blobs: bytes) -> None: + for blob in blobs: + for planted in PLANTED: + assert planted.encode() not in blob + + +def _registry_bytes(env: dict[str, str]) -> bytes: + return b"".join(p.read_bytes() for p in _registry(env).rglob("*") if p.is_file()) + + +def test_done_by_person_after_a_code_prompt_lets_the_agent_save_once(app, env): + base, state = app + seen: dict[str, Any] = {} + + def person() -> None: + card = _wait_for_card(env) + seen["card"] = card + seen["desktop"] = _desktop_cards(env) + _post(base + "/verify", {"otc": CODE}) # typed in the live app by the person + done = _answer(env, card["card_id"], "done_by_person") + assert done.returncode == 0, done.stderr + + log = _run_agent(base, env, 120, person) + + assert seen["card"]["kind"] == "second_factor" + if seen["desktop"] is not None: + (desktop_card,) = seen["desktop"] + assert desktop_card["exception_kind"] == "second_factor" + assert desktop_card["source"]["id"] == seen["card"]["card_id"] + assert [c["id"] for c in desktop_card["choices"]] == [ + "done_by_person", + "skip", + "abort", + "leave", + ] + _no_planted(json.dumps(desktop_card).encode()) + (asked,) = log["asked"] + assert asked["answer"] == "done_by_person" and asked["proceed"] is True + assert asked["opened_at"] and asked["decided_at"] + assert log["wrote"] is True + assert json.loads(_get(base + "/api/records")) == [{"note": "synthetic note"}] + answer = json.loads(next(_registry(env).rglob("answer-*.json")).read_text()) + assert answer["opened_at"] and answer["decided_at"] + _no_planted(_registry_bytes(env), json.dumps(log).encode()) + assert CODE.encode() not in _registry_bytes(env) + + +@pytest.mark.parametrize("choice", ["abort", "skip"]) +def test_a_stop_answer_means_no_write(app, env, choice): + base, state = app + + def person() -> None: + card = _wait_for_card(env) + done = _answer(env, card["card_id"], choice) + assert done.returncode == 0, done.stderr + + log = _run_agent(base, env, 120, person) + + (asked,) = log["asked"] + assert asked["proceed"] is False and asked["answer"] == choice + assert asked["opened_at"] and asked["decided_at"] + assert log["wrote"] is False + assert json.loads(_get(base + "/api/records")) == [] + _no_planted(_registry_bytes(env), json.dumps(log).encode()) + + +def test_an_expired_card_is_a_decline_and_no_write(app, env): + base, state = app + + def person() -> None: + _wait_for_card(env) # nobody answers + + log = _run_agent(base, env, 2, person) + + (asked,) = log["asked"] + assert asked["proceed"] is False + assert asked["answer"] == "decline" and asked["reason"] == "expired" + assert asked["opened_at"] and asked["decided_at"] is None + assert log["wrote"] is False + assert json.loads(_get(base + "/api/records")) == [] + record = json.loads(next(_registry(env).rglob("answer-*.json")).read_text()) + assert record["approver_kind"] == "expiry" and record["decided_at"] is None + + +def test_an_answer_from_a_key_off_the_roster_is_refused_and_nothing_is_written( + app, env, tmp_path +): + base, state = app + stranger = tmp_path / "stranger.pem" + stranger.write_bytes( + Ed25519PrivateKey.generate().private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.BestAvailableEncryption(PASSPHRASE.encode()), + ) + ) + seen: dict[str, Any] = {} + + def person() -> None: + card = _wait_for_card(env) + forged = _answer( + {**env, "OPENADAPT_TEST_KEY_PEM": str(stranger)}, + card["card_id"], + "done_by_person", + ) + seen["forged"] = forged + # Refused before anything is written: the card is still open, so the + # run never saw an answer from the stranger. + seen["answers_after_forged"] = list(_registry(env).rglob("answer-*.json")) + # A rostered person then stops the run (not an expiry race: the card's + # deadline is long enough that a loaded machine can't expire it first). + done = _answer(env, card["card_id"], "abort") + assert done.returncode == 0, done.stderr + + log = _run_agent(base, env, 600, person) + + assert seen["forged"].returncode == 2, seen["forged"].stderr + assert "human_approver_unregistered" in seen["forged"].stdout + assert seen["answers_after_forged"] == [] + (asked,) = log["asked"] + assert asked["proceed"] is False and asked["answer"] == "abort" + assert log["wrote"] is False + assert json.loads(_get(base + "/api/records")) == [] diff --git a/packages/flow/tests/e2e/test_exception_watch_e2e.py b/packages/flow/tests/e2e/test_exception_watch_e2e.py new file mode 100644 index 0000000000..4709ebafea --- /dev/null +++ b/packages/flow/tests/e2e/test_exception_watch_e2e.py @@ -0,0 +1,268 @@ +"""End to end: an agent that never asks is held at a code prompt anyway. + +Real headless Chromium. The scripted Playwright agent +(``benchmark/agent_guard/agent.py``) works in MockMed and never calls +``raise_exception``. ``openadapt-flow guard`` attaches to its browser over +CDP, and so does ``openadapt-flow exceptions watch``, each in its own +process. A synthetic one-time-code dialog appears on the agent's page. The +watch raises a ``second_factor`` card by itself and blocks the save the agent +tries while the card is open. A person clears the code prompt in the live +page and answers ``done_by_person`` with a registered test key; the agent's +next save goes through the guard and reads back VERIFIED. + +Asserted from the app's own store: no write while the card was open, exactly +one write after the answer. + +Synthetic MockMed in front of the ``effect_e2e`` record store; localhost only. +""" + +from __future__ import annotations + +import json +import os +import queue +import socket +import subprocess +import sys +import threading +import time +from pathlib import Path +from typing import Any + +import pytest + +pytest.importorskip("playwright") + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # noqa: E402 +from openadapt_types.exception_card import answer_message # noqa: E402 + +from benchmark.agent_guard import run as bench # noqa: E402 +from benchmark.agent_guard.agent import ScriptedAgent # noqa: E402 +from benchmark.agent_guard.app import serve # noqa: E402 +from openadapt_flow.approval_mode.approver_roster import ( # noqa: E402 + ROOT_ENV, + file_key_signer, + init_root, +) +from openadapt_flow.exceptions.registry import ExceptionRegistry # noqa: E402 +from openadapt_flow.execute.keys import sign_bytes # noqa: E402 +from openadapt_flow.jit.authority import public_hex # noqa: E402 + +pytestmark = pytest.mark.timeout(600) + +#: A synthetic code prompt laid over the page, as a sign-in service shows one. +CODE_PROMPT = """() => { + const box = document.createElement('div'); + box.id = 'synthetic-code-prompt'; + box.setAttribute('role', 'dialog'); + box.setAttribute('aria-modal', 'true'); + box.style.cssText = 'position:fixed;left:30%;top:30%;width:40%;height:20%;' + + 'background:#fff;border:1px solid #000;z-index:1000'; + box.innerHTML = '

Check your phone

' + + ''; + document.body.appendChild(box); +}""" +#: The agent's save while the prompt is up: MockMed's own write, sent from +#: its page. It ignores the prompt and never asks anyone. +AGENT_SAVE = """async (note) => { + const r = await fetch('/api/encounter?fault=ok', {method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({patient_id: 'p1', type: 'Triage', note: note})}); + return {status: r.status, header: r.headers.get('X-OpenAdapt-Exception')}; +}""" + + +def _port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return int(sock.getsockname()[1]) + + +def _chromium_or_skip() -> None: + from playwright.sync_api import sync_playwright + + try: + with sync_playwright() as pw: + pw.chromium.launch(headless=True).close() + except Exception as exc: # noqa: BLE001 + pytest.skip(f"chromium unavailable: {exc}") + + +class _Watch: + """``openadapt-flow exceptions watch`` in its own process.""" + + def __init__(self, args: list[str]) -> None: + self.proc = subprocess.Popen( + [sys.executable, "-m", "openadapt_flow", "exceptions", "watch", *args], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=os.environ.copy(), + ) + self.lines: "queue.Queue[str]" = queue.Queue() + self.stderr: list[str] = [] + threading.Thread(target=self._read, daemon=True).start() + + def _read(self) -> None: + assert self.proc.stderr is not None + for line in self.proc.stderr: + self.stderr.append(line) + self.lines.put(line) + + def wait_attached(self, timeout_s: float = 90.0) -> None: + end = time.monotonic() + timeout_s + while time.monotonic() < end: + try: + line = self.lines.get(timeout=0.2) + except queue.Empty: + if self.proc.poll() is not None: + break + continue + if "exceptions: watching" in line: + return + raise RuntimeError("the watch did not attach:\n" + "".join(self.stderr)) + + def finish(self) -> dict[str, Any]: + try: + out, _ = self.proc.communicate(timeout=120) + except subprocess.TimeoutExpired: + self.proc.kill() + out, _ = self.proc.communicate() + return { + "exit": self.proc.returncode, + **json.loads(out.strip().splitlines()[-1]), + } + + +def _until(check, timeout_s: float = 60.0, what: str = "") -> Any: + end = time.monotonic() + timeout_s + while time.monotonic() < end: + value = check() + if value: + return value + time.sleep(0.1) + raise AssertionError(f"timed out waiting for {what}") + + +def test_the_watch_holds_an_agent_that_never_asks( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _chromium_or_skip() + home = tmp_path / "home" + key_dir = tmp_path / "keys" + key = Ed25519PrivateKey.generate() + init_root( + key_dir, + principal="front-desk", + public_key=public_hex(key), + sign=file_key_signer(key), + ) + monkeypatch.setenv("OPENADAPT_HOME", str(home)) + monkeypatch.setenv("OPENADAPT_JIT_KEY_DIR", str(key_dir)) + monkeypatch.setenv(ROOT_ENV, public_hex(key)) + registry = ExceptionRegistry(home / "exceptions") + + app = serve(tmp_path / "app.sqlite") + port = _port() + work = tmp_path / "run" + agent = guard = watch = None + try: + bench._post( + app.base_url, "/api/reset", {"seed_concurrent": None, "fault": None} + ) + files = bench.write_setup(tmp_path / "setup", app.base_url, teach_dir=None) + agent = ScriptedAgent(port=port, think_s=0.2) + agent.open(f"{app.base_url}/?fault=ok&idempotency=demo#tasks") + guard = bench._GuardProcess( + [ + "--cdp", + f"http://127.0.0.1:{port}", + "--config", + str(files["guard"]), + "--task", + str(files["task"]), + "--out", + str(work), + "--timeout", + "120", + "--no-teach", + ] + ) + guard.wait_attached() + watch = _Watch( + [ + "--cdp", + f"http://127.0.0.1:{port}", + "--config", + str(files["guard"]), + "--run-dir", + str(work), + "--run-ref", + "watch-e2e", + "--task-id", + "triage-p1-0001", + "--poll-s", + "0.2", + "--max-s", + "240", + ] + ) + watch.wait_attached() + writes_before = app.writes + + # A code prompt appears. The agent doesn't ask anyone. + agent.page.evaluate(CODE_PROMPT) + card = _until( + lambda: next(iter(registry.open_cards("watch-e2e")), None), what="a card" + ) + assert card.kind == "second_factor" + # It saves anyway: the watch blocks it at the browser. + tried = agent.page.evaluate(AGENT_SAVE, bench.NOTE) + assert tried["status"] == 409, tried + assert tried["header"] == "blocked; code=exception_open" + assert app.writes == writes_before + + # A person clears the prompt in the live page, then answers. + agent.page.evaluate( + "() => document.getElementById('synthetic-code-prompt').remove()" + ) + unsigned = registry.unsigned_answer(card, "done_by_person", route="cli") + registry.write_answer( + card, + { + **unsigned, + "public_key": public_hex(key), + "signature": sign_bytes(key, answer_message(unsigned)), + }, + ) + log = work / "exceptions_watch.jsonl" + _until( + lambda: log.exists() and '"proceed": true' in log.read_text(), + what="the watch to settle the card", + ) + + # The agent saves the ordinary way: the guard checks it, it lands once. + acted = agent.add_triage_note(patient="p1", note=bench.NOTE) + result = guard.finish(wait_s=30) + assert result["run"]["verdict"] == "VERIFIED", (acted, result) + assert app.writes == writes_before + 1 + + watch.proc.terminate() + done = watch.finish() + assert done["run_ref"] == "watch-e2e" and done["stopped"] is None + [outcome] = done["outcomes"] + assert outcome["answer"] == "done_by_person" and outcome["proceed"] is True + events = [json.loads(line) for line in log.read_text().splitlines()] + kinds = [e["event"] for e in events] + assert kinds.count("card_opened") == 1 + assert {"event": "request_blocked", "code": "exception_open"}.items() <= next( + e for e in events if e["event"] == "request_blocked" + ).items() + assert bench.NOTE.encode() not in log.read_bytes() + finally: + for proc in (watch, guard): + if proc is not None and proc.proc.poll() is None: + proc.proc.kill() + if agent is not None: + agent.close() + app.stop() diff --git a/packages/flow/tests/e2e/test_exception_watch_faults_e2e.py b/packages/flow/tests/e2e/test_exception_watch_faults_e2e.py new file mode 100644 index 0000000000..05e89f6a63 --- /dev/null +++ b/packages/flow/tests/e2e/test_exception_watch_faults_e2e.py @@ -0,0 +1,222 @@ +"""The exception watch under browser faults, in a real headless Chromium. + +* A save the page aborts while the watch holds it paused: the browser refuses + the watch's decision. The watch logs it and keeps going, and the next save + is still blocked while the card is open. +* The watch's own DevTools session is dropped while a card is open: the + watch says so, logs ``watch_lost`` and ends with exit code 4. + +Synthetic page on 127.0.0.1; nothing is sent anywhere else. +""" + +from __future__ import annotations + +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any + +import pytest + +pytest.importorskip("playwright") + +from cryptography.hazmat.primitives.asymmetric.ed25519 import ( # noqa: E402 + Ed25519PrivateKey, +) + +from openadapt_flow.approval_mode.approver_roster import ( # noqa: E402 + ROOT_ENV, + file_key_signer, + init_root, +) +from openadapt_flow.exceptions.registry import ( # noqa: E402 + ExceptionRegistry, + roster_verifier, +) +from openadapt_flow.exceptions.watch import ( # noqa: E402 + _PAUSED_TYPES, + WATCH_EVENTS, + ExceptionWatch, + run_loop, +) +from openadapt_flow.jit.authority import public_hex # noqa: E402 + +pytestmark = pytest.mark.timeout(300) + +PAGE = b"

New note

" +CODE_SCREEN = { + "text": "Verification code", + "elements": [ + { + "tag": "input", + "autocomplete": "one-time-code", + "visible": True, + "bbox": [1, 1, 50, 10], + } + ], +} +#: A save the page gives up on after ``ms``, recorded in window.saveResult. +SAVE = """(ms) => { + window.saveResult = null; + const c = new AbortController(); + fetch('/save', {method: 'POST', body: 'x', signal: c.signal}) + .then(r => { window.saveResult = r.status; }) + .catch(() => { window.saveResult = 'aborted'; }); + if (ms > 0) { setTimeout(() => c.abort(), ms); } +}""" + + +@pytest.fixture +def site(): + hits: list[str] = [] + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_a: Any) -> None: + return None + + def do_GET(self) -> None: # noqa: N802 + self.send_response(200) + self.send_header("Content-Type", "text/html") + self.send_header("Content-Length", str(len(PAGE))) + self.end_headers() + self.wfile.write(PAGE) + + def do_POST(self) -> None: # noqa: N802 + hits.append(self.path) + self.send_response(200) + self.send_header("Content-Length", "0") + self.end_headers() + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + yield f"http://127.0.0.1:{server.server_address[1]}", hits + server.shutdown() + server.server_close() + + +@pytest.fixture +def tab(site): + from playwright.sync_api import sync_playwright + + pw = sync_playwright().start() + try: + browser = pw.chromium.launch(headless=True) + except Exception as exc: # noqa: BLE001 + pw.stop() + pytest.skip(f"chromium unavailable: {exc}") + page = browser.new_page() + page.goto(site[0] + "/") + cdp = page.context.new_cdp_session(page) + paused: list[Any] = [] + cdp.on("Fetch.requestPaused", lambda params: paused.append(params)) + cdp.send( + "Fetch.enable", + { + "patterns": [ + {"urlPattern": "*", "resourceType": t, "requestStage": "Request"} + for t in _PAUSED_TYPES + ] + }, + ) + yield page, cdp, paused + browser.close() + pw.stop() + + +@pytest.fixture +def watch(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, site) -> ExceptionWatch: + key_dir = tmp_path / "keys" + key = Ed25519PrivateKey.generate() + init_root( + key_dir, + principal="front-desk", + public_key=public_hex(key), + sign=file_key_signer(key), + ) + monkeypatch.setenv(ROOT_ENV, public_hex(key)) + return ExceptionWatch( + ExceptionRegistry(tmp_path / "registry"), + run_ref="faults", + verify=roster_verifier(key_dir, public_hex(key)), + app_origin=site[0], + events_path=tmp_path / "run" / WATCH_EVENTS, + ) + + +def _events(tmp_path: Path) -> list[dict]: + path = tmp_path / "run" / WATCH_EVENTS + return [json.loads(line) for line in path.read_text().splitlines()] + + +def _until(page: Any, check: Any, what: str) -> None: + for _ in range(100): + if check(): + return + page.wait_for_timeout(50) + raise AssertionError(f"timed out waiting for {what}") + + +def _ticks(n: int) -> Any: + count = [0] + + def stop() -> bool: + count[0] += 1 + return count[0] >= n + + return stop + + +def test_an_aborted_paused_save_does_not_end_the_watch( + tmp_path: Path, site, tab, watch: ExceptionWatch +) -> None: + _base, hits = site + page, cdp, paused = tab + assert watch.observe(CODE_SCREEN) == "second_factor" + + # The page gives up on a save while the watch holds it paused. + page.evaluate(SAVE, 100) + _until(page, lambda: bool(paused), "the save to be paused") + _until( + page, + lambda: page.evaluate("() => window.saveResult") == "aborted", + "the page to abort", + ) + # The watch decides it late: the browser refuses, the loop goes on. + run_loop(watch, page, cdp, paused, poll_s=0.05, stop=_ticks(5)) + assert watch.lost is None + assert "request_decision_failed" in [e["event"] for e in _events(tmp_path)] + + # The next save is still blocked while the card is open. + page.evaluate(SAVE, 0) + _until(page, lambda: bool(paused), "the second save to be paused") + run_loop(watch, page, cdp, paused, poll_s=0.05, stop=_ticks(5)) + _until( + page, + lambda: page.evaluate("() => window.saveResult") == 409, + "the block", + ) + assert hits == [] + assert watch.lost is None + assert watch.stop_code() == 6 # it would end with the card unanswered + + +def test_a_dropped_session_while_a_card_is_open_exits_loudly( + tmp_path: Path, tab, watch: ExceptionWatch, capsys: pytest.CaptureFixture +) -> None: + page, cdp, paused = tab + assert watch.observe(CODE_SCREEN) == "second_factor" + dropped = [False] + + def drop_then_go_on() -> bool: + if not dropped[0]: + cdp.detach() # the watch's own DevTools session goes away + dropped[0] = True + return False + + run_loop(watch, page, cdp, paused, poll_s=0.05, max_s=30, stop=drop_then_go_on) + assert watch.lost == "session_lost" + assert watch.stop_code() == 4 + [lost] = [e for e in _events(tmp_path) if e["event"] == "watch_lost"] + assert lost["card_open"] is True + assert "WATCH LOST" in capsys.readouterr().err diff --git a/packages/flow/tests/fixtures/exception_card_second_factor.json b/packages/flow/tests/fixtures/exception_card_second_factor.json new file mode 100644 index 0000000000..2cd32341c9 --- /dev/null +++ b/packages/flow/tests/fixtures/exception_card_second_factor.json @@ -0,0 +1,28 @@ +{ + "card_id": "sha256:789e54fd7198a18087709380c8db637b843b28fb2d1d04f1247e5ac8026097ce", + "choices": [ + { + "consequence": "You type the code in the live browser yourself. The run then goes on from the same screen. OpenAdapt never sees the code.", + "id": "done_by_person", + "label": "I entered the code in the browser" + }, + { + "consequence": "Nothing is saved. The run moves to the next item.", + "id": "skip", + "label": "Skip this item" + }, + { + "consequence": "Nothing more is saved. The whole run stops.", + "id": "abort", + "label": "Stop the run" + } + ], + "deadline_at": "2026-11-21T12:15:00Z", + "kind": "second_factor", + "opened_at": "2026-11-21T12:00:00Z", + "run_ref": "fixture-run", + "schema": "openadapt.exception-card/v1", + "screenshot_ref": null, + "summary": "The sign-in page asks for a six-digit code", + "task_id": "intake" +} diff --git a/packages/flow/tests/test_binary_file_descriptors.py b/packages/flow/tests/test_binary_file_descriptors.py index d81c3ca8fd..e356e7c70d 100644 --- a/packages/flow/tests/test_binary_file_descriptors.py +++ b/packages/flow/tests/test_binary_file_descriptors.py @@ -100,6 +100,7 @@ def test_raw_descriptor_entry_points_cannot_fall_back_to_text_open(): covered = raw_descriptor_owners(source) assert "approval_mode/item_approval.py" in covered assert "write_ledger.py" in covered + assert "exceptions/registry.py" in covered def test_binary_open_refuses_an_explicit_text_mode( diff --git a/packages/flow/tests/test_browser_readiness.py b/packages/flow/tests/test_browser_readiness.py index 4617488ce0..1fc92a5a2b 100644 --- a/packages/flow/tests/test_browser_readiness.py +++ b/packages/flow/tests/test_browser_readiness.py @@ -321,6 +321,7 @@ def test_all_cdp_acquisitions_check_their_selected_page() -> None: "cli_worklist_pool.py": "_open", "agent_guard/session.py": "_connect", "copilot_runtime.py": "main", + "exceptions/watch.py": "watch_browser", } observed = {} for path in root.rglob("*.py"): diff --git a/packages/flow/tests/test_exception_detectors.py b/packages/flow/tests/test_exception_detectors.py new file mode 100644 index 0000000000..2f8a0edf5b --- /dev/null +++ b/packages/flow/tests/test_exception_detectors.py @@ -0,0 +1,238 @@ +"""Exception detectors on synthetic pages: a code prompt, a mid-task sign-in, +a modal, a stall and a duplicate, plus the weak signal for each (it must +still ask) and ordinary pages (they must not).""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from openadapt_flow.exceptions import detectors as d +from openadapt_flow.exceptions.detectors import Observation, detect, elements_from_html + +FORM = """

New entry

+ + +
""" + +OTP_MARKED = """

Check your phone

+ + +
""" + +OTP_WEAK = """

We sent you a message.

+ +
""" + +OTP_TEXT_ONLY = "

Enter the code we sent to your phone.

" + +SIGN_IN = """

Sign in

+ + +
""" + +MODAL = ( + """""" + + FORM + + """ +

Your changes may be lost.

+""" +) + +HIDDEN_MODAL = ( + """""" + + FORM + + """ +""" +) + + +def _obs(html: str, **fields) -> Observation: + elements, text = elements_from_html(html) + return Observation(screen_text=text, elements=elements, **fields) + + +# -- second factor ------------------------------------------------------------------ + + +@pytest.mark.parametrize("page", [OTP_MARKED, OTP_WEAK, OTP_TEXT_ONLY]) +def test_a_code_prompt_is_a_second_factor(page): + assert detect(_obs(page)) == "second_factor" + + +def test_screen_text_alone_still_asks(): + assert ( + d.second_factor((), "Two-factor authentication: enter the code") + == "second_factor" + ) + + +def test_an_ordinary_form_is_not_a_second_factor(): + assert d.second_factor(*elements_from_html(FORM)) is None + assert detect(_obs(FORM)) is None + + +def test_a_hidden_code_field_is_not_on_screen(): + page = "
" + assert d.second_factor(*elements_from_html(page)) is None + + +# -- session expired ---------------------------------------------------------------- + + +def test_a_sign_in_page_before_any_save_screen_is_the_tasks_start(): + assert detect(_obs(SIGN_IN, save_eligible_seen=False)) is None + + +def test_a_sign_in_page_after_a_save_screen_is_a_session_expiry(): + assert detect(_obs(SIGN_IN, save_eligible_seen=True)) == "session_expired" + + +def test_words_alone_after_a_save_screen_still_ask(): + page = "

Your session has expired.

" + assert detect(_obs(page, save_eligible_seen=True)) == "session_expired" + + +def test_accessibility_secure_field_counts_as_a_password(): + nodes = [{"role": "AXSecureTextField", "name": "Password"}] + elements = d.elements_from_accessibility(nodes) + assert d.session_expired(elements, save_eligible_seen=True) == "session_expired" + + +# -- dialogs ------------------------------------------------------------------------ + + +def test_a_modal_over_the_form_is_an_unexpected_dialog(): + assert detect(_obs(MODAL)) == "unexpected_dialog" + + +def test_a_hidden_modal_is_not_in_the_way(): + assert detect(_obs(HIDDEN_MODAL)) is None + + +def test_a_dialog_the_step_expects_is_not_an_exception(): + assert detect(_obs(MODAL, expected_dialog=True)) is None + + +def test_a_non_modal_dialog_away_from_the_target_is_not_in_the_way(): + dialog = {"role": "dialog", "bbox": [900, 0, 200, 100], "z": 5} + target = {"tag": "button", "bbox": [10, 500, 80, 30], "z": 0} + assert d.unexpected_dialog([dialog], target=target) is None + + +def test_a_non_modal_dialog_covering_the_target_is_in_the_way(): + dialog = {"role": "dialog", "bbox": [0, 400, 400, 300], "z": 5} + target = {"tag": "button", "bbox": [10, 500, 80, 30], "z": 0} + assert d.unexpected_dialog([dialog], target=target) == "unexpected_dialog" + + +def test_a_dialog_with_no_geometry_asks(): + assert d.unexpected_dialog( + [{"role": "alertdialog"}], target={"bbox": [1, 1, 1, 1]} + ) == ("unexpected_dialog") + + +# -- stalls ------------------------------------------------------------------------- + + +def test_no_action_and_no_change_for_too_long_is_a_stall(): + assert detect( + Observation(now=1000.0, last_action_at=700.0, last_change_at=800.0, stall_s=120) + ) == ("timeout_or_stall") + + +def test_a_recent_change_is_not_a_stall(): + assert ( + d.timeout_or_stall( + now=1000.0, last_action_at=700.0, last_change_at=950.0, stall_s=120 + ) + is None + ) + + +def test_a_clock_with_no_last_event_asks(): + assert ( + d.timeout_or_stall(now=5.0, last_action_at=None, last_change_at=None) + == "timeout_or_stall" + ) + + +def test_no_clock_means_no_stall_check(): + assert detect(Observation()) is None + + +# -- duplicates --------------------------------------------------------------------- + +ROWS = [ + {"last_name": "Okafor", "dob": "1950-01-01"}, + {"last_name": "Vance", "dob": "1972-03-04"}, +] + + +def test_a_row_with_the_same_key_is_a_possible_duplicate(): + observation = Observation( + duplicate_key=["last_name", "dob"], + proposed={"last_name": " vance ", "dob": "1972-03-04", "note": "x"}, + existing=ROWS, + ) + assert detect(observation) == "possible_duplicate" + + +def test_no_matching_row_is_not_a_duplicate(): + assert d.possible_duplicate("last_name", {"last_name": "Nobody"}, ROWS) is None + + +@pytest.mark.parametrize( + "key,proposed,rows", + [ + (["last_name", "dob"], {"last_name": "Vance"}, ROWS), # no key value + ("last_name", {"last_name": "Vance"}, None), # the read failed + ( + "last_name", + {"last_name": "Nobody"}, + [{"dob": "1950-01-01"}], + ), # row lacks key + ([], {"last_name": "Vance"}, ROWS), # a key with no fields + ({"weird": 1}, {"last_name": "Vance"}, ROWS), # a key shape we can't check + ], +) +def test_a_duplicate_check_that_cant_rule_it_out_asks(key, proposed, rows): + assert d.possible_duplicate(key, proposed, rows) == "possible_duplicate" + + +def test_no_duplicate_key_configured_means_no_duplicate_check(): + assert d.possible_duplicate(None, {"a": "b"}, ROWS) is None + + +def test_the_key_comes_from_verify_yaml_record_duplicate_key(): + config = {"record": {"duplicate_key": ["last_name", "dob"]}, "verifier": {}} + assert d.duplicate_key_from_config(config) == ["last_name", "dob"] + assert d.duplicate_key_from_config({"verifier": {}}) is None + + +# -- general mechanisms only -------------------------------------------------------- + + +def test_the_detectors_name_no_app(): + source = Path(d.__file__).read_text(encoding="utf-8").casefold() + for name in ( + "openemr", + "mockmed", + "epic", + "cerner", + "salesforce", + "okta", + "google", + "microsoft", + ): + assert name not in source + + +def test_every_detector_returns_a_closed_kind_or_none(): + from openadapt_types.exception_card import EXCEPTION_KINDS + + pages = [FORM, OTP_MARKED, OTP_WEAK, SIGN_IN, MODAL] + for page in pages: + for kind in d.detect_all(_obs(page, save_eligible_seen=True)): + assert kind in EXCEPTION_KINDS diff --git a/packages/flow/tests/test_exception_registry.py b/packages/flow/tests/test_exception_registry.py new file mode 100644 index 0000000000..67b484fe01 --- /dev/null +++ b/packages/flow/tests/test_exception_registry.py @@ -0,0 +1,630 @@ +"""The exception registry: cards, signed answers, expiry, and what never proceeds. + +Synthetic data only. The approver roster is a fresh one in a temporary +folder, with a root key made here; nothing reads the real ~/.openadapt. +""" + +from __future__ import annotations + +import json +import os +import stat +import struct +import zlib +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from openadapt_types.exception_card import ( + EXCEPTION_KINDS, + ExceptionAnswerV1, + ExceptionCardV1, + answer_message, +) + +from openadapt_flow import privacy +from openadapt_flow.approval_mode.approver_roster import ( + ROOT_ENV, + file_key_signer, + init_root, +) +from openadapt_flow.exceptions import cli as exceptions_cli +from openadapt_flow.exceptions.registry import ( + CHOICES, + GENERIC_SUMMARIES, + ExceptionRegistry, + ExceptionRegistryError, + iso, + roster_verifier, +) +from openadapt_flow.execute.keys import sign_bytes +from openadapt_flow.jit.authority import public_hex + +#: Made-up identifiers planted in what an agent says; none may reach a card. +PLANTED = ("Maribel Quintanilla", "1961-04-09", "MRN 88812345", "maribel@example.test") +SUMMARY = ( + "Code prompt for Maribel Quintanilla, born 1961-04-09, MRN 88812345, " + "mail maribel@example.test" +) + + +def _png_1x1() -> bytes: + """A valid one-pixel RGB PNG, built without an imaging library.""" + + def chunk(tag: bytes, data: bytes) -> bytes: + body = tag + data + return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body)) + + header = struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0) + pixels = zlib.compress(b"\x00\xff\xff\xff") + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", header) + + chunk(b"IDAT", pixels) + + chunk(b"IEND", b"") + ) + + +PNG = _png_1x1() + + +class FakeScrubber: + """Replaces the planted name; the registry masks digits and dates itself.""" + + def scrub_text(self, text: str) -> str: + return text.replace("Maribel Quintanilla", "") + + def scrub_image(self, image, fill_color=None): # noqa: ARG002 + return image + + +@pytest.fixture(autouse=True) +def _scrubber(): + privacy.set_text_scrubber(FakeScrubber()) + yield + privacy.reset_scrubbers() + + +@pytest.fixture +def registry(tmp_path: Path) -> ExceptionRegistry: + return ExceptionRegistry(tmp_path / "exceptions") + + +@pytest.fixture +def roster(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + key_dir = tmp_path / "keys" + key = Ed25519PrivateKey.generate() + init_root( + key_dir, + principal="front-desk", + public_key=public_hex(key), + sign=file_key_signer(key), + ) + monkeypatch.setenv(ROOT_ENV, public_hex(key)) + return key_dir, key + + +def _signed(registry, card, answer: str, key, *, now=None) -> dict: + unsigned = registry.unsigned_answer(card, answer, route="cli", now=now) + return { + **unsigned, + "public_key": public_hex(key), + "signature": sign_bytes(key, answer_message(unsigned)), + } + + +def _verify(roster): + key_dir, key = roster + return roster_verifier(key_dir, public_hex(key)) + + +def _no_sleep(_s: float) -> None: + return None + + +# -- cards ----------------------------------------------------------------------- + + +def test_a_card_is_sealed_private_and_names_closed_choices(registry): + card = registry.open("run-1", "second_factor", "A code prompt appeared") + + path = registry.root / "run-1" / f"card-{card.card_id[7:]}.json" + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + on_disk = ExceptionCardV1.model_validate(json.loads(path.read_text())) + assert on_disk == card + assert [c.id for c in card.choices] == ["done_by_person", "skip", "abort"] + assert card.kind == "second_factor" + assert registry.open_cards() == [card] + + +def test_every_kind_has_choices_and_no_card_offers_a_write_on_its_own(): + assert set(CHOICES) == set(EXCEPTION_KINDS) + for kind, choices in CHOICES.items(): + assert choices, kind + assert len(choices) <= 5 + + +@pytest.mark.parametrize("kind", ["unknown", "SECOND_FACTOR", ""]) +def test_an_unknown_kind_is_refused(registry, kind): + with pytest.raises(ExceptionRegistryError) as err: + registry.open("run-1", kind, "x") + assert err.value.code == "kind_unknown" + + +@pytest.mark.parametrize("run_ref", ["../escape", "a/b", "", ".hidden", "x" * 200]) +def test_a_run_reference_never_becomes_a_path_outside_the_registry(registry, run_ref): + with pytest.raises(ExceptionRegistryError) as err: + registry.open(run_ref, "cannot_complete", "x") + assert err.value.code == "run_ref_invalid" + + +def test_a_tampered_card_is_not_listed(registry): + card = registry.open("run-1", "cannot_complete", "Stuck") + path = registry.root / "run-1" / f"card-{card.card_id[7:]}.json" + data = json.loads(path.read_text()) + data["summary"] = "Something else" + os.chmod(path, 0o600) + path.unlink() + path.write_text(json.dumps(data)) + assert registry.open_cards() == [] + + +# -- scrubbing -------------------------------------------------------------------- + + +def _bytes_under(root: Path) -> bytes: + return b"".join(p.read_bytes() for p in root.rglob("*") if p.is_file()) + + +def test_the_summary_is_scrubbed_and_cut(registry): + card = registry.open( + "run-1", "second_factor", SUMMARY + " " + "x" * 400, task_id="T-12345678" + ) + + assert len(card.summary) <= 200 + blob = _bytes_under(registry.root) + for planted in PLANTED: + assert planted.encode() not in blob + assert b"" in blob + # A token holding four or more digits is masked whole. + assert card.task_id == "[number]" + + +def test_without_a_scrubber_the_card_says_only_the_kinds_own_words(registry): + privacy.set_text_scrubber(None) + card = registry.open("run-1", "session_expired", SUMMARY) + + assert card.summary == GENERIC_SUMMARIES["session_expired"] + blob = _bytes_under(registry.root) + for planted in PLANTED: + assert planted.encode() not in blob + + +def test_a_broken_scrubber_is_no_scrubber(registry): + class Broken: + def scrub_text(self, text): + raise RuntimeError("model missing") + + privacy.set_text_scrubber(Broken()) + card = registry.open("run-1", "cannot_complete", SUMMARY) + assert card.summary == GENERIC_SUMMARIES["cannot_complete"] + + +def test_a_screenshot_is_kept_only_as_a_scrubbed_private_copy(registry, tmp_path): + shot = tmp_path / "screen.png" + shot.write_bytes(PNG) + card = registry.open( + "run-1", "unexpected_dialog", "A dialog", screenshot_path=str(shot) + ) + + assert card.screenshot_ref is not None + copy = registry.root / "run-1" / card.screenshot_ref + assert copy.read_bytes().startswith(b"\x89PNG") + assert stat.S_IMODE(copy.stat().st_mode) == 0o600 + + +def test_no_screenshot_without_a_scrubber_a_png_or_a_plain_file(registry, tmp_path): + shot = tmp_path / "screen.png" + shot.write_bytes(PNG) + link = tmp_path / "link.png" + link.symlink_to(shot) + text = tmp_path / "notes.png" + text.write_text("not an image") + + assert ( + registry.open( + "r", "cannot_complete", "x", screenshot_path=str(link) + ).screenshot_ref + is None + ) + assert ( + registry.open( + "r", "cannot_complete", "y", screenshot_path=str(text) + ).screenshot_ref + is None + ) + assert ( + registry.open( + "r", "cannot_complete", "z", screenshot_path=str(tmp_path) + ).screenshot_ref + is None + ) + privacy.set_text_scrubber(None) + assert ( + registry.open( + "r", "cannot_complete", "w", screenshot_path=str(shot) + ).screenshot_ref + is None + ) + + +# -- answers ----------------------------------------------------------------------- + + +def test_a_signed_done_by_person_lets_the_run_go_on(registry, roster): + _key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt") + registry.write_answer(card, _signed(registry, card, "done_by_person", key)) + + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + + assert outcome.proceed is True + assert outcome.answer == "done_by_person" + assert outcome.opened_at == card.opened_at + assert outcome.decided_at is not None + assert (registry.root / "run-1" / f"consumed-{card.card_id[7:]}.json").exists() + assert registry.open_cards() == [] + + +@pytest.mark.parametrize("answer", ["skip", "abort"]) +def test_a_signed_stop_answer_stops_the_run(registry, roster, answer): + _key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt") + registry.write_answer(card, _signed(registry, card, answer, key)) + + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is False + assert outcome.answer == answer + + +def test_an_answer_from_a_key_off_the_roster_never_proceeds(registry, roster): + card = registry.open("run-1", "second_factor", "A code prompt") + stranger = Ed25519PrivateKey.generate() + registry.write_answer(card, _signed(registry, card, "done_by_person", stranger)) + + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is False + assert outcome.reason == "human_approver_unregistered" + + +def test_a_forged_signature_never_proceeds(registry, roster): + _key_dir, key = roster + card = registry.open("run-1", "timeout_or_stall", "Nothing moves") + answer = _signed(registry, card, "skip", key) + answer["answer"] = "continue" # the signature covered "skip" + registry.write_answer(card, answer) + + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is False + assert outcome.reason == "human_answer_signature_invalid" + + +def test_without_a_pinned_root_no_answer_counts(registry, roster): + key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt") + registry.write_answer(card, _signed(registry, card, "done_by_person", key)) + + outcome = registry.wait( + card, verify=roster_verifier(key_dir, None), sleep=_no_sleep + ) + assert outcome.proceed is False + + +def test_a_choice_the_card_doesnt_offer_never_proceeds(registry, roster): + _key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt") + with pytest.raises(ExceptionRegistryError): + registry.unsigned_answer(card, "continue", route="cli") + unsigned = { + "schema": "openadapt.exception-answer/v1", + "card_id": card.card_id, + "kind": card.kind, + "opened_at": card.opened_at, + "decided_at": iso(datetime.now(timezone.utc)), + "answer": "continue", + "approver_kind": "person", + "route": "cli", + "reason": None, + } + registry.write_answer( + card, + { + **unsigned, + "public_key": public_hex(key), + "signature": sign_bytes(key, answer_message(unsigned)), + }, + ) + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is False + assert outcome.reason == "choice_not_offered" + + +def test_an_answer_decided_after_the_deadline_never_proceeds(registry, roster): + _key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt", deadline_s=5) + late = datetime.now(timezone.utc) + timedelta(seconds=60) + registry.write_answer( + card, _signed(registry, card, "done_by_person", key, now=late) + ) + + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is False + assert outcome.reason == "answer_late" + + +def test_an_answer_is_used_once(registry, roster): + _key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt") + registry.write_answer(card, _signed(registry, card, "done_by_person", key)) + assert registry.wait(card, verify=_verify(roster), sleep=_no_sleep).proceed is True + + again = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert again.proceed is False + assert again.reason == "answer_already_used" + + +def test_a_card_has_one_answer(registry, roster): + _key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt") + registry.write_answer(card, _signed(registry, card, "abort", key)) + with pytest.raises(ExceptionRegistryError) as err: + registry.write_answer(card, _signed(registry, card, "done_by_person", key)) + assert err.value.code == "already_answered" + + +def test_an_unreadable_answer_stops_the_run(registry, roster): + card = registry.open("run-1", "second_factor", "A code prompt") + (registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").write_text( + "{not json" + ) + + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is False + assert outcome.reason == "answer_unreadable" + + +def test_an_unsigned_answer_that_claims_to_be_a_persons_is_unreadable(registry, roster): + card = registry.open("run-1", "second_factor", "A code prompt") + answer = { + "schema": "openadapt.exception-answer/v1", + "card_id": card.card_id, + "kind": card.kind, + "opened_at": card.opened_at, + "decided_at": iso(datetime.now(timezone.utc)), + "answer": "done_by_person", + "approver_kind": "person", + "route": "cli", + } + (registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").write_text( + json.dumps(answer) + ) + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is False + + +# -- expiry ------------------------------------------------------------------------ + + +def test_expiry_writes_a_decline_with_no_decision_time(registry, roster): + card = registry.open("run-1", "second_factor", "A code prompt", deadline_s=60) + after = datetime.now(timezone.utc) + timedelta(seconds=61) + beats: list[float] = [] + + outcome = registry.wait( + card, + verify=_verify(roster), + clock=lambda: after, + sleep=_no_sleep, + heartbeat=lambda _id, left: beats.append(left), + ) + + assert outcome.proceed is False + assert outcome.answer == "decline" + assert outcome.reason == "expired" + assert outcome.decided_at is None + record = ExceptionAnswerV1.model_validate( + json.loads( + (registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").read_text() + ) + ) + assert record.approver_kind == "expiry" + assert record.decided_at is None + assert record.reason == "expired" + assert record.opened_at == card.opened_at + + +def test_the_wait_beats_and_then_expires(registry, roster): + card = registry.open("run-1", "timeout_or_stall", "Stalled", deadline_s=60) + times = iter( + [datetime.now(timezone.utc)] * 3 + + [datetime.now(timezone.utc) + timedelta(seconds=120)] * 5 + ) + beats: list[float] = [] + outcome = registry.wait( + card, + verify=_verify(roster), + clock=lambda: next(times), + sleep=_no_sleep, + heartbeat_s=0, + heartbeat=lambda _id, left: beats.append(left), + ) + assert outcome.reason == "expired" + assert beats and all(b > 0 for b in beats) + + +def test_a_person_who_answers_at_the_deadline_wins_the_race( + registry, roster, monkeypatch +): + _key_dir, key = roster + card = registry.open("run-1", "second_factor", "A code prompt", deadline_s=60) + answer = _signed(registry, card, "done_by_person", key) + original = registry._expire + + def expire_after_the_person(c): + registry.write_answer(c, answer) # lands first + original(c) # then the registry's expiry link fails + + monkeypatch.setattr(registry, "_expire", expire_after_the_person) + after = datetime.now(timezone.utc) + timedelta(seconds=61) + outcome = registry.wait( + card, verify=_verify(roster), clock=lambda: after, sleep=_no_sleep + ) + assert outcome.proceed is True + + +def test_the_heartbeat_goes_to_stderr_never_stdout(registry, roster, capsys): + card = registry.open("run-1", "timeout_or_stall", "Stalled", deadline_s=60) + times = iter( + [datetime.now(timezone.utc), datetime.now(timezone.utc) + timedelta(seconds=99)] + * 3 + ) + registry.wait( + card, verify=_verify(roster), clock=lambda: next(times), sleep=_no_sleep + ) + out, err = capsys.readouterr() + assert out == "" + assert "waiting for a person" in err + + +# -- CLI --------------------------------------------------------------------------- + + +def _encrypted(tmp_path: Path, key: Ed25519PrivateKey, passphrase: str) -> Path: + path = tmp_path / "approver.pem" + path.write_bytes( + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.BestAvailableEncryption(passphrase.encode()), + ) + ) + path.chmod(0o600) + return path + + +def _parse(argv: list[str]): + import argparse + + parser = argparse.ArgumentParser() + sub = parser.add_subparsers(dest="command", required=True) + exceptions_cli.register(sub) + return parser.parse_args(argv) + + +def test_the_cli_answers_with_a_key_on_the_roster( + registry, roster, tmp_path, monkeypatch, capsys +): + key_dir, key = roster + monkeypatch.setenv("OPENADAPT_JIT_KEY_PASSPHRASE", "synthetic-passphrase") + pem = _encrypted(tmp_path, key, "synthetic-passphrase") + card = registry.open("run-1", "second_factor", "A code prompt") + + args = _parse(["exceptions", "list", "--registry", str(registry.root), "--json"]) + assert args.func(args) == 0 + listed = json.loads(capsys.readouterr().out) + assert [c["card_id"] for c in listed["cards"]] == [card.card_id] + + args = _parse( + [ + "exceptions", + "answer", + card.card_id, + "done_by_person", + "--registry", + str(registry.root), + "--key", + str(pem), + "--key-dir", + str(key_dir), + ] + ) + assert args.func(args) == 0 + outcome = registry.wait(card, verify=_verify(roster), sleep=_no_sleep) + assert outcome.proceed is True + + +def test_the_cli_refuses_a_key_off_the_roster( + registry, roster, tmp_path, monkeypatch, capsys +): + key_dir, _key = roster + monkeypatch.setenv("OPENADAPT_JIT_KEY_PASSPHRASE", "synthetic-passphrase") + pem = _encrypted(tmp_path, Ed25519PrivateKey.generate(), "synthetic-passphrase") + card = registry.open("run-1", "second_factor", "A code prompt") + + args = _parse( + [ + "exceptions", + "answer", + card.card_id, + "done_by_person", + "--registry", + str(registry.root), + "--key", + str(pem), + "--key-dir", + str(key_dir), + ] + ) + assert args.func(args) == 2 + assert "human_approver_unregistered" in capsys.readouterr().err + assert not (registry.root / "run-1" / f"answer-{card.card_id[7:]}.json").exists() + + +def test_the_cli_refuses_a_choice_the_card_doesnt_offer( + registry, roster, tmp_path, monkeypatch +): + key_dir, key = roster + monkeypatch.setenv("OPENADAPT_JIT_KEY_PASSPHRASE", "synthetic-passphrase") + pem = _encrypted(tmp_path, key, "synthetic-passphrase") + card = registry.open("run-1", "second_factor", "A code prompt") + args = _parse( + [ + "exceptions", + "answer", + card.card_id, + "continue", + "--registry", + str(registry.root), + "--key", + str(pem), + "--key-dir", + str(key_dir), + ] + ) + assert args.func(args) == 2 + + +# -- the file Desktop reads --------------------------------------------------------- + +FIXTURE = Path(__file__).parent / "fixtures" / "exception_card_second_factor.json" + + +def test_the_desktop_fixture_is_what_flow_writes(registry): + """Desktop's suite reads this file; Flow must still write exactly it.""" + + opened = datetime(2026, 11, 21, 12, 0, 0, tzinfo=timezone.utc) + card = registry.open( + "fixture-run", + "second_factor", + "The sign-in page asks for a six-digit code", + task_id="intake", + now=opened, + ) + written = json.loads( + (registry.root / "fixture-run" / f"card-{card.card_id[7:]}.json").read_text() + ) + if os.environ.get("OPENADAPT_REGENERATE_FIXTURES") == "1": + FIXTURE.write_text(json.dumps(written, sort_keys=True, indent=2) + "\n") + assert written == json.loads(FIXTURE.read_text()) diff --git a/packages/flow/tests/test_exception_watch.py b/packages/flow/tests/test_exception_watch.py new file mode 100644 index 0000000000..eb1c7398d3 --- /dev/null +++ b/packages/flow/tests/test_exception_watch.py @@ -0,0 +1,491 @@ +"""The exception watch raises cards and holds saves without the agent. + +No browser: page snapshots are the dicts :data:`SNAPSHOT_JS` returns, and +requests are :class:`HeldRequest` as the guard's CDP layer builds them. +Synthetic screens and keys only. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from openadapt_types.exception_card import answer_message + +from openadapt_flow.agent_guard.requests import HeldRequest, NotASave +from openadapt_flow.approval_mode.approver_roster import ( + ROOT_ENV, + file_key_signer, + init_root, +) +from openadapt_flow.exceptions.registry import ExceptionRegistry, roster_verifier +from openadapt_flow.exceptions.watch import WATCH_EVENTS, ExceptionWatch +from openadapt_flow.execute.keys import sign_bytes +from openadapt_flow.jit.authority import public_hex + +APP = "http://127.0.0.1:8123" +CODE_SCREEN = { + "text": "Check your phone. Verification code", + "elements": [ + { + "tag": "input", + "type": "text", + "id": "otc", + "label": "Verification code", + "autocomplete": "one-time-code", + "inputmode": "numeric", + "maxlength": "6", + "visible": True, + "bbox": [10, 10, 100, 20], + } + ], +} +FORM_SCREEN = { + "text": "New note", + "elements": [ + { + "tag": "input", + "type": "text", + "id": "note", + "label": "Note", + "visible": True, + }, + {"tag": "button", "type": "", "id": "save", "visible": True}, + ], +} +SIGN_IN_SCREEN = { + "text": "Sign in", + "elements": [{"tag": "input", "type": "password", "id": "pw", "visible": True}], +} + + +@pytest.fixture +def roster(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + key_dir = tmp_path / "keys" + key = Ed25519PrivateKey.generate() + init_root( + key_dir, + principal="front-desk", + public_key=public_hex(key), + sign=file_key_signer(key), + ) + monkeypatch.setenv(ROOT_ENV, public_hex(key)) + return key_dir, key + + +class _Clock: + def __init__(self) -> None: + self.t = 100.0 + + def __call__(self) -> float: + return self.t + + +def _watch(tmp_path: Path, roster, **kw) -> ExceptionWatch: + key_dir, key = roster + return ExceptionWatch( + ExceptionRegistry(tmp_path / "registry"), + run_ref="watch-run", + verify=roster_verifier(key_dir, public_hex(key)), + app_origin=APP, + events_path=tmp_path / "run" / WATCH_EVENTS, + **kw, + ) + + +def _save(path: str = "/api/encounter", method: str = "POST") -> HeldRequest: + return HeldRequest( + request_id="r1", + method=method, + url=APP + path, + resource_type="Fetch", + post_data=json.dumps({"note": "synthetic"}), + ) + + +def _answer(watch: ExceptionWatch, key, choice: str) -> None: + card = watch.card + unsigned = watch.registry.unsigned_answer(card, choice, route="cli") + watch.registry.write_answer( + card, + { + **unsigned, + "public_key": public_hex(key), + "signature": sign_bytes(key, answer_message(unsigned)), + }, + ) + + +def _events(tmp_path: Path) -> list[dict]: + return [ + json.loads(line) + for line in (tmp_path / "run" / WATCH_EVENTS).read_text().splitlines() + ] + + +def test_a_code_screen_opens_a_card_and_blocks_saves_until_a_person_answers( + tmp_path: Path, roster +) -> None: + watch = _watch(tmp_path, roster) + assert watch.on_request(_save()) is None # nothing open: the save goes on + assert watch.observe(CODE_SCREEN) == "second_factor" + assert watch.card is not None and watch.card.kind == "second_factor" + # The agent never asked; it saves anyway. Blocked, whatever it does. + assert watch.on_request(_save()) == "exception_open" + # Reads still go through, and so does a write the guard config lists + # as not a save (the code form a person submits in the live browser). + assert watch.on_request(_save(method="GET")) is None + assert watch.poll() is None # nobody has answered + _answer(watch, roster[1], "done_by_person") + outcome = watch.poll() + assert outcome is not None and outcome.proceed is True + assert watch.card is None and not watch.holding + assert watch.on_request(_save()) is None + # The page still shows the code screen: not asked again until it goes. + assert watch.observe(CODE_SCREEN) is None + assert watch.observe(FORM_SCREEN) is None + assert watch.observe(CODE_SCREEN) == "second_factor" + # Ending now would leave that new card unanswered: not a clean exit. + assert watch.stop_code() == 6 + events = [e["event"] for e in _events(tmp_path)] + assert events[:5] == [ + "watch_started", + "card_opened", + "request_blocked", + "answer", + "card_opened", + ] + + +def test_a_not_a_save_write_goes_through_while_a_card_is_open( + tmp_path: Path, roster +) -> None: + watch = _watch(tmp_path, roster, not_saves=(NotASave("POST", "/verify"),)) + watch.observe(CODE_SCREEN) + assert watch.on_request(_save("/verify")) is None + assert watch.on_request(_save("/api/encounter")) == "exception_open" + + +@pytest.mark.parametrize("choice", ["abort", "skip"]) +def test_a_stop_answer_blocks_every_later_save( + tmp_path: Path, roster, choice: str +) -> None: + watch = _watch(tmp_path, roster) + watch.observe(CODE_SCREEN) + _answer(watch, roster[1], choice) + outcome = watch.poll() + assert outcome is not None and outcome.proceed is False + assert watch.stopped == choice + assert watch.on_request(_save()) == "exception_stopped" + # No new card after a stop: the run is over. + assert watch.observe(SIGN_IN_SCREEN) is None + assert watch.stop_code() == 3 + + +def test_an_answer_off_the_roster_keeps_the_run_stopped(tmp_path: Path, roster) -> None: + watch = _watch(tmp_path, roster) + watch.observe(CODE_SCREEN) + _answer(watch, Ed25519PrivateKey.generate(), "done_by_person") + outcome = watch.poll() + assert outcome is not None and outcome.proceed is False + assert outcome.reason == "human_approver_unregistered" + assert watch.on_request(_save()) == "exception_stopped" + + +def test_an_expired_card_stops_the_run(tmp_path: Path, roster) -> None: + watch = _watch(tmp_path, roster, deadline_s=1) + watch.observe(CODE_SCREEN) + card = watch.card + from datetime import timedelta + + from openadapt_flow.exceptions.registry import parse_time + + later = parse_time(card.deadline_at) + timedelta(seconds=1) + outcome = watch.registry.poll(card, verify=watch.verify, now=later) + assert outcome is not None and outcome.reason == "expired" + # The watch reads the same record on its next look. + assert watch.poll() is not None + assert watch.on_request(_save()) == "exception_stopped" + + +def test_a_sign_in_counts_only_after_a_save(tmp_path: Path, roster) -> None: + watch = _watch(tmp_path, roster) + assert watch.observe(SIGN_IN_SCREEN) is None # the ordinary start of a task + watch.on_request(_save()) + assert watch.observe(SIGN_IN_SCREEN) == "session_expired" + + +def test_a_stall_is_raised_only_when_asked_for(tmp_path: Path, roster) -> None: + clock = _Clock() + off = _watch(tmp_path / "off", roster, clock=clock) + on = _watch(tmp_path / "on", roster, clock=clock, stall_s=30) + for watch in (off, on): + watch.observe(FORM_SCREEN) + clock.t += 31 + assert off.observe(FORM_SCREEN) is None + assert on.observe(FORM_SCREEN) == "timeout_or_stall" + + +def test_the_card_carries_nothing_from_the_page(tmp_path: Path, roster) -> None: + planted = dict( + CODE_SCREEN, text="Verification code for Maribel Quintanilla 88812345" + ) + watch = _watch(tmp_path, roster) + watch.observe(planted) + blob = b"".join( + p.read_bytes() for p in (tmp_path / "registry").rglob("*") if p.is_file() + ) + blob += (tmp_path / "run" / WATCH_EVENTS).read_bytes() + assert b"Maribel" not in blob and b"88812345" not in blob + + +def test_a_bad_run_ref_is_refused_before_anything_runs(tmp_path: Path, roster) -> None: + from openadapt_flow.exceptions.registry import ExceptionRegistryError + + key_dir, key = roster + with pytest.raises(ExceptionRegistryError): + ExceptionWatch( + ExceptionRegistry(tmp_path / "registry"), + run_ref="../elsewhere", + verify=roster_verifier(key_dir, public_hex(key)), + app_origin=APP, + ) + + +class _Page: + def __init__(self, snapshot: dict) -> None: + self.snapshot = snapshot + + def is_closed(self) -> bool: + return False + + def evaluate(self, _js: str) -> dict: + return self.snapshot + + def wait_for_timeout(self, _ms: int) -> None: + return None + + +class _Cdp: + def __init__(self) -> None: + self.sent: list[tuple[str, dict]] = [] + + def send(self, method: str, params: dict | None = None) -> dict: + self.sent.append((method, params or {})) + return {} + + +def _paused(path: str = "/api/encounter", rid: str = "1") -> dict: + return { + "requestId": rid, + "request": {"url": APP + path, "method": "POST", "headers": {}}, + "resourceType": "Fetch", + } + + +def _decisions(cdp: _Cdp) -> list[str]: + return [m for m, _ in cdp.sent if m.startswith("Fetch.")] + + +def test_a_registry_it_cannot_write_refuses_every_write_and_exits_4( + tmp_path: Path, roster +) -> None: + """The reviewer's probe: the card can't be written (an unwritable folder + stands in for a full disk). Nothing paused or later goes on.""" + + import os + + from openadapt_flow.exceptions.watch import run_loop + + key_dir, key = roster + root = tmp_path / "registry" + root.mkdir() + os.chmod(root, 0o500) + try: + watch = ExceptionWatch( + ExceptionRegistry(root), + run_ref="watch-run", + verify=roster_verifier(key_dir, public_hex(key)), + app_origin=APP, + events_path=tmp_path / "run" / WATCH_EVENTS, + ) + cdp = _Cdp() + paused: list[dict] = [] + ticks = [0] + + class _Arrives(_Page): + """Saves the agent sends after the failure, as CDP delivers them.""" + + def wait_for_timeout(self, _ms: int) -> None: + ticks[0] += 1 + if watch.failed is not None and ticks[0] in (3, 6): + paused.append(_paused(rid=str(ticks[0]))) + + def stop() -> bool: + return ticks[0] >= 10 + + # The real loop: the card write fails on the first look, and the loop + # stays, refusing the two saves that arrive afterwards. + run_loop(watch, _Arrives(CODE_SCREEN), cdp, paused, poll_s=0.01, stop=stop) + assert watch.failed is not None and watch.lost == "watch_failed" + assert watch.stop_code() == 4 + assert paused == [] + assert _decisions(cdp) == ["Fetch.fulfillRequest", "Fetch.fulfillRequest"] + assert all( + p["responseCode"] == 409 for m, p in cdp.sent if m.startswith("Fetch.") + ) + lost = [e for e in _events(tmp_path) if e["event"] == "watch_lost"] + assert lost and lost[0]["reason"] == "watch_failed" + finally: + os.chmod(root, 0o700) + + +def test_a_request_it_cannot_classify_is_refused(tmp_path: Path, roster) -> None: + from openadapt_flow.exceptions.watch import _decide + + watch = _watch(tmp_path, roster) + cdp = _Cdp() + assert _decide(cdp, watch, {"requestId": "1", "request": "not a request"}) is True + [(method, params)] = cdp.sent + assert method == "Fetch.fulfillRequest" and params["responseCode"] == 409 + + +def test_ending_with_a_card_open_is_not_a_clean_exit(tmp_path: Path, roster) -> None: + from openadapt_flow.exceptions.watch import run_loop + + watch = _watch(tmp_path, roster) + run_loop(watch, _Page(CODE_SCREEN), _Cdp(), [], poll_s=0.01, max_s=0.2) + assert watch.card is not None and watch.lost is None + assert watch.stop_code() == 6 + + +def test_cmd_watch_turns_any_failure_into_a_documented_code( + tmp_path: Path, roster, monkeypatch: pytest.MonkeyPatch, capsys +) -> None: + import argparse + + from openadapt_flow.exceptions import cli, watch + + config = tmp_path / "guard.yaml" + (tmp_path / "verify.yaml").write_text( + "schema_version: openadapt.verify/v1\n" + "verifier: {kind: rest, base_url: 'http://127.0.0.1:8123'," + " records_path: /api/records}\n" + "effects: [{kind: record_written, match: {note: {param: note}}}]\n" + ) + config.write_text( + "schema_version: openadapt.agent-guard/v1\n" + f"app_url: {APP}/\n" + "verify: verify.yaml\n" + ) + + def broken(w: ExceptionWatch, **_kw: object) -> int: + w.observe(CODE_SCREEN) # a card is open ... + raise ValueError("something the loop didn't expect") # ... and it breaks + + monkeypatch.setattr(watch, "watch_browser", broken) + key_dir, key = roster + args = argparse.Namespace( + approver_root=public_hex(key), + key_dir=str(key_dir), + config=str(config), + run_ref="watch-run", + run_dir=str(tmp_path / "run"), + registry=str(tmp_path / "registry"), + task_id=None, + deadline_s=None, + stall_s=None, + cdp="http://127.0.0.1:9", + page_url=None, + poll_s=0.5, + max_s=None, + ) + assert cli.cmd_watch(args) == 4 + out = json.loads(capsys.readouterr().out.strip().splitlines()[-1]) + assert out["lost"] == "watch_failed" and out["failed"] == "ValueError" + + +def test_cleanup_decides_every_paused_save_when_one_is_refused( + tmp_path: Path, roster +) -> None: + """Paused saves go on when the session detaches, so each one is decided + first; a decision the browser refuses doesn't stop the rest.""" + + from openadapt_flow.exceptions.watch import drain + + class _Refuses(_Cdp): + def send(self, method: str, params: dict | None = None) -> dict: + self.sent.append((method, params or {})) + if (params or {}).get("requestId") == "2": + raise RuntimeError("Invalid InterceptionId") + return {} + + watch = _watch(tmp_path, roster) + watch.observe(CODE_SCREEN) # a card is open: every save is refused + cdp = _Refuses() + paused = [_paused(rid=r) for r in ("1", "2", "3")] + drain(cdp, watch, paused) + assert paused == [] + assert [(m, p["requestId"]) for m, p in cdp.sent] == [ + ("Fetch.fulfillRequest", "1"), + ("Fetch.fulfillRequest", "2"), + ("Fetch.fulfillRequest", "3"), + ] + + +def test_an_interrupt_with_a_card_open_exits_6( + tmp_path: Path, roster, monkeypatch: pytest.MonkeyPatch, capsys +) -> None: + import argparse + + from openadapt_flow.exceptions import cli, watch + + (tmp_path / "verify.yaml").write_text( + "schema_version: openadapt.verify/v1\n" + "verifier: {kind: rest, base_url: 'http://127.0.0.1:8123'," + " records_path: /api/records}\n" + "effects: [{kind: record_written, match: {note: {param: note}}}]\n" + ) + config = tmp_path / "guard.yaml" + config.write_text( + "schema_version: openadapt.agent-guard/v1\n" + f"app_url: {APP}/\n" + "verify: verify.yaml\n" + ) + + def interrupted(w: ExceptionWatch, **_kw: object) -> int: + w.observe(CODE_SCREEN) + raise KeyboardInterrupt + + monkeypatch.setattr(watch, "watch_browser", interrupted) + key_dir, key = roster + args = argparse.Namespace( + approver_root=public_hex(key), + key_dir=str(key_dir), + config=str(config), + run_ref="watch-run", + run_dir=str(tmp_path / "run"), + registry=str(tmp_path / "registry"), + task_id=None, + deadline_s=None, + stall_s=None, + cdp="http://127.0.0.1:9", + page_url=None, + poll_s=0.5, + max_s=None, + ) + assert cli.cmd_watch(args) == 6 + out = json.loads(capsys.readouterr().out.strip().splitlines()[-1]) + assert out["lost"] is None and out["failed"] is None + + +def test_the_lost_message_names_no_card_when_none_was_open( + tmp_path: Path, roster, capsys +) -> None: + watch = _watch(tmp_path, roster) + watch.fail(OSError("disk full")) + err = capsys.readouterr().err + assert "every write is refused until the watch exits" in err + assert "card was open" not in err and "run was stopped" not in err diff --git a/packages/types/openadapt_types/exception_card.py b/packages/types/openadapt_types/exception_card.py new file mode 100644 index 0000000000..398fdb252b --- /dev/null +++ b/packages/types/openadapt_types/exception_card.py @@ -0,0 +1,227 @@ +"""Exception cards: the closed question a run asks a person, and the answer. + +Any agent (a compiled program, Claude computer use, a CUA harness, a person's +own script) can stop at a moment it can't get past alone: a second-factor +prompt, a dialog it didn't expect, a sign-in page mid-task, a stall, a +possible duplicate, a record it can't tell apart from another, or a task it +can't finish. It opens one :class:`ExceptionCardV1`, and a person answers it +with one :class:`ExceptionAnswerV1`. + +Both sets are closed. ``kind`` is one of :data:`EXCEPTION_KINDS` and +``answer`` is one of :data:`EXCEPTION_ANSWERS`; nothing else validates. Only +``continue`` and ``done_by_person`` let a run go on +(:data:`PROCEED_ANSWERS`). Every other answer, an expired card and an answer +that can't be read or verified mean the run stops before any write. + +The card carries no raw values. ``summary`` is scrubbed text of at most +:data:`SUMMARY_MAX` characters, and ``screenshot_ref`` names a local, scrubbed +copy, never the original frame. ``card_id`` is the digest of everything else +on the card (:func:`card_digest`), so an answer names exactly the card a +person saw. + +``opened_at`` and ``decided_at`` on the answer are the intervention interval: +how long a person held the run. An expiry answer has ``decided_at`` ``None``, +``approver_kind`` ``expiry``, ``answer`` ``decline`` and ``reason`` +``expired``. + +This module is imported by its submodule path +(``openadapt_types.exception_card``); it is not re-exported from the package. +""" + +from __future__ import annotations + +import hashlib +import json +from typing import Any, Literal, Optional, get_args + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + +EXCEPTION_CARD_SCHEMA = "openadapt.exception-card/v1" +EXCEPTION_ANSWER_SCHEMA = "openadapt.exception-answer/v1" +#: What an approver key signs for an answer: these bytes, then the canonical +#: JSON of :func:`answer_signing_payload`. +EXCEPTION_ANSWER_DOMAIN = b"openadapt.exception-answer/v1\x00" + +ExceptionKind = Literal[ + "second_factor", + "unexpected_dialog", + "session_expired", + "timeout_or_stall", + "possible_duplicate", + "ambiguous_record", + "cannot_complete", +] +EXCEPTION_KINDS: tuple[str, ...] = get_args(ExceptionKind) + +ExceptionAnswerValue = Literal["continue", "skip", "decline", "done_by_person", "abort"] +EXCEPTION_ANSWERS: tuple[str, ...] = get_args(ExceptionAnswerValue) +#: The only answers that let a run go on. Anything else stops before a write. +PROCEED_ANSWERS = frozenset({"continue", "done_by_person"}) + +ApproverKind = Literal["person", "expiry"] +#: Where a person's answer came from. +AnswerRoute = Literal["cli", "desktop", "portal", "registry"] + +SUMMARY_MAX = 200 +_DIGEST = r"^sha256:[0-9a-f]{64}$" +#: A run reference is opaque: it becomes a directory name. +RUN_REF_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$" +_TIME = r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$" +_SIGNATURE = r"^ed25519:[0-9a-f]{128}$" +_PUBLIC_KEY = r"^[0-9a-f]{64}$" + + +def canonical(value: Any) -> bytes: + """The canonical JSON bytes every digest and signature here covers.""" + + return json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + + +class ExceptionChoice(BaseModel): + """One button: the closed answer, its label, and what it does.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + id: ExceptionAnswerValue + label: str = Field(min_length=1, max_length=80) + consequence: str = Field(min_length=1, max_length=200) + + +class ExceptionCardV1(BaseModel): + """The question one run asks a person.""" + + model_config = ConfigDict(extra="forbid", frozen=True, populate_by_name=True) + + schema_: Literal["openadapt.exception-card/v1"] = Field( + default=EXCEPTION_CARD_SCHEMA, alias="schema" + ) + card_id: str = Field(pattern=_DIGEST) + run_ref: str = Field(pattern=RUN_REF_PATTERN) + task_id: Optional[str] = Field(default=None, max_length=128) + kind: ExceptionKind + opened_at: str = Field(pattern=_TIME) + deadline_at: str = Field(pattern=_TIME) + #: A file name inside the card's own folder (a scrubbed copy), or None. + screenshot_ref: Optional[str] = Field( + default=None, pattern=r"^screenshot-[0-9a-f]{16,64}\.png$" + ) + summary: str = Field(min_length=1, max_length=SUMMARY_MAX) + choices: tuple[ExceptionChoice, ...] = Field(min_length=1, max_length=5) + + @field_validator("choices") + @classmethod + def _distinct(cls, value: tuple[ExceptionChoice, ...]) -> tuple[ExceptionChoice, ...]: + ids = [choice.id for choice in value] + if len(set(ids)) != len(ids): + raise ValueError("a card offers each answer once") + return value + + @model_validator(mode="after") + def _sealed(self) -> "ExceptionCardV1": + if card_digest(self.body()) != self.card_id: + raise ValueError("card_id is not the digest of the card") + return self + + def body(self) -> dict[str, Any]: + """Everything on the card except its id (what ``card_id`` digests).""" + + data = self.model_dump(mode="json", by_alias=True) + data.pop("card_id") + return data + + def wire(self) -> dict[str, Any]: + return self.model_dump(mode="json", by_alias=True) + + def offers(self, answer: str) -> bool: + return any(choice.id == answer for choice in self.choices) + + +class ExceptionAnswerV1(BaseModel): + """A person's answer to one card, or the registry's expiry record.""" + + model_config = ConfigDict(extra="forbid", frozen=True, populate_by_name=True) + + schema_: Literal["openadapt.exception-answer/v1"] = Field( + default=EXCEPTION_ANSWER_SCHEMA, alias="schema" + ) + card_id: str = Field(pattern=_DIGEST) + kind: ExceptionKind + opened_at: str = Field(pattern=_TIME) + decided_at: Optional[str] = Field(default=None, pattern=_TIME) + answer: ExceptionAnswerValue + approver_kind: ApproverKind + route: AnswerRoute + #: The closed reason for a registry-written answer. + reason: Optional[Literal["expired"]] = None + #: The approver key that signed (hex Ed25519), not part of what it signs. + public_key: Optional[str] = Field(default=None, pattern=_PUBLIC_KEY) + signature: Optional[str] = Field(default=None, pattern=_SIGNATURE) + + @model_validator(mode="after") + def _shape(self) -> "ExceptionAnswerV1": + if self.approver_kind == "expiry": + if ( + self.answer != "decline" + or self.decided_at is not None + or self.reason != "expired" + or self.signature is not None + or self.route != "registry" + ): + raise ValueError( + "an expiry record is answer=decline, decided_at=null, " + "reason=expired, unsigned, written by the registry" + ) + else: + if self.decided_at is None or self.signature is None or self.public_key is None: + raise ValueError("a person's answer is timed and signed") + if self.reason is not None or self.route == "registry": + raise ValueError("a person's answer carries no registry reason") + return self + + def wire(self) -> dict[str, Any]: + return self.model_dump(mode="json", by_alias=True) + + @property + def proceeds(self) -> bool: + return self.approver_kind == "person" and self.answer in PROCEED_ANSWERS + + +def card_digest(body: dict[str, Any]) -> str: + """``sha256:`` of the canonical card body (the card without ``card_id``).""" + + return "sha256:" + hashlib.sha256(canonical(body)).hexdigest() + + +def answer_signing_payload(answer: dict[str, Any]) -> dict[str, Any]: + """What an approver key signs: the answer without its key and signature.""" + + return {k: v for k, v in answer.items() if k not in {"signature", "public_key"}} + + +def answer_message(answer: dict[str, Any]) -> bytes: + """The exact bytes an approver key signs for ``answer``.""" + + return EXCEPTION_ANSWER_DOMAIN + canonical(answer_signing_payload(answer)) + + +__all__ = [ + "EXCEPTION_ANSWERS", + "EXCEPTION_ANSWER_DOMAIN", + "EXCEPTION_ANSWER_SCHEMA", + "EXCEPTION_CARD_SCHEMA", + "EXCEPTION_KINDS", + "PROCEED_ANSWERS", + "RUN_REF_PATTERN", + "SUMMARY_MAX", + "AnswerRoute", + "ApproverKind", + "ExceptionAnswerV1", + "ExceptionAnswerValue", + "ExceptionCardV1", + "ExceptionChoice", + "ExceptionKind", + "answer_message", + "answer_signing_payload", + "canonical", + "card_digest", +] diff --git a/packages/types/tests/test_exception_card.py b/packages/types/tests/test_exception_card.py new file mode 100644 index 0000000000..680681ab28 --- /dev/null +++ b/packages/types/tests/test_exception_card.py @@ -0,0 +1,165 @@ +"""The exception card and answer contracts: closed sets, sealed ids, expiry shape.""" + +from __future__ import annotations + +import pytest +from pydantic import ValidationError + +from openadapt_types import exception_card as ec + +OPENED = "2026-11-21T12:00:00Z" +DEADLINE = "2026-11-21T12:15:00Z" + + +def _body(**overrides): + body = { + "schema": ec.EXCEPTION_CARD_SCHEMA, + "run_ref": "run-1", + "task_id": None, + "kind": "second_factor", + "opened_at": OPENED, + "deadline_at": DEADLINE, + "screenshot_ref": None, + "summary": "The app is asking for a one-time code.", + "choices": [ + {"id": "done_by_person", "label": "I entered it", "consequence": "The run goes on."}, + {"id": "abort", "label": "Stop", "consequence": "Nothing more is saved."}, + ], + } + body.update(overrides) + return body + + +def _card(**overrides): + body = _body(**overrides) + return ec.ExceptionCardV1.model_validate({**body, "card_id": ec.card_digest(body)}) + + +def test_the_closed_sets(): + assert ec.EXCEPTION_KINDS == ( + "second_factor", + "unexpected_dialog", + "session_expired", + "timeout_or_stall", + "possible_duplicate", + "ambiguous_record", + "cannot_complete", + ) + assert ec.EXCEPTION_ANSWERS == ("continue", "skip", "decline", "done_by_person", "abort") + assert ec.PROCEED_ANSWERS == {"continue", "done_by_person"} + + +def test_a_card_round_trips_with_its_schema_name(): + card = _card() + wire = card.wire() + assert wire["schema"] == "openadapt.exception-card/v1" + assert ec.ExceptionCardV1.model_validate(wire) == card + assert card.offers("abort") and not card.offers("continue") + + +@pytest.mark.parametrize( + "overrides", + [ + {"kind": "captcha"}, + {"summary": "x" * 201}, + {"summary": ""}, + {"run_ref": "../up"}, + {"opened_at": "yesterday"}, + {"screenshot_ref": "/etc/passwd"}, + {"choices": [{"id": "approve", "label": "x", "consequence": "y"}]}, + {"choices": []}, + ], +) +def test_anything_outside_the_contract_is_refused(overrides): + with pytest.raises(ValidationError): + _card(**overrides) + + +def test_a_card_whose_id_isnt_its_digest_is_refused(): + body = _body() + with pytest.raises(ValidationError): + ec.ExceptionCardV1.model_validate({**body, "card_id": "sha256:" + "0" * 64}) + + +def test_a_card_offers_each_answer_once(): + twice = [{"id": "abort", "label": "a", "consequence": "b"}] * 2 + with pytest.raises(ValidationError): + _card(choices=twice) + + +def test_an_unknown_field_is_refused(): + body = _body() + body["raw_values"] = {"name": "x"} + with pytest.raises(ValidationError): + ec.ExceptionCardV1.model_validate({**body, "card_id": ec.card_digest(body)}) + + +def _answer(**overrides): + base = { + "schema": ec.EXCEPTION_ANSWER_SCHEMA, + "card_id": "sha256:" + "a" * 64, + "kind": "second_factor", + "opened_at": OPENED, + "decided_at": "2026-11-21T12:01:00Z", + "answer": "done_by_person", + "approver_kind": "person", + "route": "cli", + "reason": None, + "public_key": "b" * 64, + "signature": "ed25519:" + "c" * 128, + } + base.update(overrides) + return ec.ExceptionAnswerV1.model_validate(base) + + +def test_a_persons_answer_is_timed_and_signed(): + answer = _answer() + assert answer.proceeds + with pytest.raises(ValidationError): + _answer(signature=None) + with pytest.raises(ValidationError): + _answer(decided_at=None) + with pytest.raises(ValidationError): + _answer(reason="expired") + + +def test_an_expiry_is_an_unsigned_decline_with_no_decision_time(): + expiry = _answer( + decided_at=None, + answer="decline", + approver_kind="expiry", + route="registry", + reason="expired", + public_key=None, + signature=None, + ) + assert not expiry.proceeds + with pytest.raises(ValidationError): # an expiry can't say continue + _answer( + decided_at=None, + answer="continue", + approver_kind="expiry", + route="registry", + reason="expired", + public_key=None, + signature=None, + ) + + +@pytest.mark.parametrize("value", ["skip", "decline", "abort"]) +def test_only_continue_and_done_by_person_proceed(value): + assert not _answer(answer=value).proceeds + + +def test_the_signed_bytes_leave_out_the_key_and_signature(): + wire = _answer().wire() + message = ec.answer_message(wire) + assert message.startswith(ec.EXCEPTION_ANSWER_DOMAIN) + assert b"signature" not in message and b"public_key" not in message + assert b'"answer":"done_by_person"' in message + + +def test_not_exported_from_the_package_root(): + import openadapt_types + + assert not hasattr(openadapt_types, "ExceptionCardV1")