From da2b61fbe21955d9a14b0d5a5d8da0871beaed9b Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:27:24 -0500 Subject: [PATCH 01/33] feat(flow): flight recorder for third-party agents openadapt flight -- CMD starts a loopback proxy in front of the model API the agent calls: it scrubs every screenshot and text block before it is sent (502 and nothing sent when it can't), meters and prices each call (unpriced models are recorded as unknown), enforces --max-cost-usd, and logs each computer action. GatedComputer and GatedComputerCall are one-line executor swaps that hold each commit-class click or key for a person (terminal, item-approval request, or refuse). Writes flight.json (openadapt.flight-run/v1), a scrubbed timeline and timeline.html. --- CAPABILITIES.md | 2 + llms-full.txt | 2 + openadapt/cli.py | 62 ++ packages/flow/benchmark/flight/README.md | 19 + packages/flow/docs/FLIGHT_RECORDER.md | 218 +++++ .../flight.md | 1 + packages/flow/openadapt_flow/__main__.py | 6 +- .../flow/openadapt_flow/flight/__init__.py | 55 ++ packages/flow/openadapt_flow/flight/cli.py | 318 +++++++ .../flow/openadapt_flow/flight/computer.py | 754 ++++++++++++++++ packages/flow/openadapt_flow/flight/gate.py | 251 ++++++ packages/flow/openadapt_flow/flight/proxy.py | 845 ++++++++++++++++++ .../flow/openadapt_flow/flight/timeline.py | 527 +++++++++++ packages/flow/tests/e2e/test_flight_e2e.py | 140 +++ .../flow/tests/e2e/test_flight_real_model.py | 148 +++ .../tests/fixtures/flight/fake_provider.py | 259 ++++++ .../tests/fixtures/flight/mockmed_agent.py | 134 +++ packages/flow/tests/test_flight_computer.py | 398 +++++++++ packages/flow/tests/test_flight_proxy.py | 476 ++++++++++ packages/flow/tests/test_flight_timeline.py | 159 ++++ tests/test_cli_flight.py | 62 ++ 21 files changed, 4833 insertions(+), 3 deletions(-) create mode 100644 packages/flow/benchmark/flight/README.md create mode 100644 packages/flow/docs/FLIGHT_RECORDER.md create mode 100644 packages/flow/docs/commands/11-guard-an-agent-you-already-run/flight.md create mode 100644 packages/flow/openadapt_flow/flight/__init__.py create mode 100644 packages/flow/openadapt_flow/flight/cli.py create mode 100644 packages/flow/openadapt_flow/flight/computer.py create mode 100644 packages/flow/openadapt_flow/flight/gate.py create mode 100644 packages/flow/openadapt_flow/flight/proxy.py create mode 100644 packages/flow/openadapt_flow/flight/timeline.py create mode 100644 packages/flow/tests/e2e/test_flight_e2e.py create mode 100644 packages/flow/tests/e2e/test_flight_real_model.py create mode 100644 packages/flow/tests/fixtures/flight/fake_provider.py create mode 100644 packages/flow/tests/fixtures/flight/mockmed_agent.py create mode 100644 packages/flow/tests/test_flight_computer.py create mode 100644 packages/flow/tests/test_flight_proxy.py create mode 100644 packages/flow/tests/test_flight_timeline.py create mode 100644 tests/test_cli_flight.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 77cb5b857c..89cfabba4e 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -324,6 +324,7 @@ improvising or retrying when something is off. | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](packages/flow/docs/AGENT_FRAMEWORKS.md) | | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | | Guard an agent you already run: attach to its own Chromium over CDP (one added line), hold each save until the record on screen is the one the task names, block it and tell the agent why when it isn't, read the save back; a run that reads back correctly becomes a draft program with a record check from scaffold-verifier, which a person confirms and admits, then a `taught_*` tool with no model calls. `--observe-only` never blocks | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](packages/flow/docs/GUARD_AN_AGENT.md) | +| Flight recorder for an agent you already run: `openadapt flight -- CMD` puts a loopback proxy in front of the model API the agent calls (`ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL`), scrubs every screenshot and text block on this machine before it is sent (a request that can't be scrubbed is answered 502 and never sent), meters and prices each call (an unpriced model's cost is recorded as unknown), honours a `--max-cost-usd` cap, and logs each computer action. A one-line executor swap (`GatedComputer` for the Anthropic computer tool, `GatedComputerCall` for an OpenAI `computer_call` loop) holds every click or Enter on a Save, Submit, Send... target, or on a target it can't read, for a person (terminal y/N, or an item-approval request Desktop or a phone answers). Writes `flight.json` (`openadapt.flight-run/v1`), a scrubbed timeline and `timeline.html`. Image scrubbing covers text in the image, not faces | On main | Synthetic (fake provider, scripted agent loop on MockMed) | `openadapt-flow flight`, `openadapt_flow.flight`, [FLIGHT_RECORDER.md](packages/flow/docs/FLIGHT_RECORDER.md) | | Check a coding agent's writes to declared systems of record: `openadapt hooks install --agent claude-code` (or `codex`) writes project-local hooks (Claude Code `PreToolUse`/`PostToolUse`/`PostToolUseFailure`/`Stop`, Codex `PreToolUse`/`PostToolUse`/`Stop`). For a call that writes to a database, HTTP API or MCP tool declared in `openadapt.systems.yaml`, the pre-check allows, asks or blocks it by the write's approval mode (Codex can't ask from a hook, so `ask` is a deny until `openadapt hooks approve`); an undeclared write to a declared system is blocked or asked about; the read-back uses the verifier's contract (`openadapt.verify/v1`), a failed read-back is `UNCERTAIN` and the same call is then held; every outcome gets a signed `record/run/v1` receipt. Advisory: hooks see tool calls, so an agent with its own credentials and shell can bypass them; `--strict` (credential broker) is refused until a broker exists for these systems | Experimental, PR [#2411](https://github.com/OpenAdaptAI/OpenAdapt/pull/2411) | Synthetic (a scripted harness sends each agent's documented hook input to the installed hook command; one run of live headless Claude Code 2.1.305 and Codex CLI 0.144.4 sessions, both against a local SQLite file and HTTP API: declared writes VERIFIED, an out-of-scope delete blocked, a broken read-back UNCERTAIN, and a Python write that builds the path at run time not seen, [hooks_live](packages/flow/benchmark/hooks_live/README.md)) | `openadapt hooks`, `openadapt_flow/hooks/`, [HOOKS.md](packages/flow/docs/HOOKS.md) | | Task ledger per job: rules locked when the job opens and enforced on every run, item status set only from OpenAdapt's own results, and yes-or-no questions a person answers on the phone or in Desktop, including when a run stops | Released ([#1332](https://github.com/OpenAdaptAI/OpenAdapt/pull/1332)) | Synthetic (30-item MockMed worklist, scripted agent, no model calls) | MCP tools `open_job`, `get_job`, `add_items`, `record_evidence`, `ask_user`, `get_answer`, `change_constraint`, `close_job`; [Track a long job](packages/agent/README.md#track-a-long-job) | | Limit a teaching agent to the declared task on every teach path (`compile_agent`, `compile-agent`, teach over MCP, the airbag guard): typed text must be a declared value, links and browser requests to other origins are refused, writes are checked before they are sent, and the record is read back before a draft exists. Injected instructions in record notes, banners, tooltips, alt text and server responses are blocked or caught on MockMed through each path (scripted agent; a live-model mode is off by default). Self-repair refuses a control that leaves the app | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359), [#1386](https://github.com/OpenAdaptAI/OpenAdapt/pull/1386)) | Synthetic | `openadapt_flow.teach_scope`, [THREAT_MODEL.md](packages/flow/docs/THREAT_MODEL.md) | @@ -486,6 +487,7 @@ A test fails when a command has no file or this list is out of date. **Guard an agent you already run:** +- `flight`: Record any agent you already run: meter and price its model calls through a loopback proxy, scrub its screenshots and text before they leave the machine, log its actions, and hold each Save, Submit or Send for a person. - `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, and hands a verified run to the teach dir. - `hooks`: Writes `openadapt.systems.yaml` checks into Claude Code or Codex hooks: each write to a declared database, HTTP API or MCP tool is pre-checked, read back and given a signed receipt (advisory). - `learn`: Learn the app's own per-request writes from a shadow run, propose excuses, and approve them into the contracts. diff --git a/llms-full.txt b/llms-full.txt index cfb52865db..f7c121a871 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -764,6 +764,7 @@ improvising or retrying when something is off. | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/AGENT_FRAMEWORKS.md) | | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | | Guard an agent you already run: attach to its own Chromium over CDP (one added line), hold each save until the record on screen is the one the task names, block it and tell the agent why when it isn't, read the save back; a run that reads back correctly becomes a draft program with a record check from scaffold-verifier, which a person confirms and admits, then a `taught_*` tool with no model calls. `--observe-only` never blocks | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/GUARD_AN_AGENT.md) | +| Flight recorder for an agent you already run: `openadapt flight -- CMD` puts a loopback proxy in front of the model API the agent calls (`ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL`), scrubs every screenshot and text block on this machine before it is sent (a request that can't be scrubbed is answered 502 and never sent), meters and prices each call (an unpriced model's cost is recorded as unknown), honours a `--max-cost-usd` cap, and logs each computer action. A one-line executor swap (`GatedComputer` for the Anthropic computer tool, `GatedComputerCall` for an OpenAI `computer_call` loop) holds every click or Enter on a Save, Submit, Send... target, or on a target it can't read, for a person (terminal y/N, or an item-approval request Desktop or a phone answers). Writes `flight.json` (`openadapt.flight-run/v1`), a scrubbed timeline and `timeline.html`. Image scrubbing covers text in the image, not faces | On main | Synthetic (fake provider, scripted agent loop on MockMed) | `openadapt-flow flight`, `openadapt_flow.flight`, [FLIGHT_RECORDER.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FLIGHT_RECORDER.md) | | Check a coding agent's writes to declared systems of record: `openadapt hooks install --agent claude-code` (or `codex`) writes project-local hooks (Claude Code `PreToolUse`/`PostToolUse`/`PostToolUseFailure`/`Stop`, Codex `PreToolUse`/`PostToolUse`/`Stop`). For a call that writes to a database, HTTP API or MCP tool declared in `openadapt.systems.yaml`, the pre-check allows, asks or blocks it by the write's approval mode (Codex can't ask from a hook, so `ask` is a deny until `openadapt hooks approve`); an undeclared write to a declared system is blocked or asked about; the read-back uses the verifier's contract (`openadapt.verify/v1`), a failed read-back is `UNCERTAIN` and the same call is then held; every outcome gets a signed `record/run/v1` receipt. Advisory: hooks see tool calls, so an agent with its own credentials and shell can bypass them; `--strict` (credential broker) is refused until a broker exists for these systems | Experimental, PR [#2411](https://github.com/OpenAdaptAI/OpenAdapt/pull/2411) | Synthetic (a scripted harness sends each agent's documented hook input to the installed hook command; one run of live headless Claude Code 2.1.305 and Codex CLI 0.144.4 sessions, both against a local SQLite file and HTTP API: declared writes VERIFIED, an out-of-scope delete blocked, a broken read-back UNCERTAIN, and a Python write that builds the path at run time not seen, [hooks_live](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/hooks_live/README.md)) | `openadapt hooks`, `openadapt_flow/hooks/`, [HOOKS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HOOKS.md) | | Task ledger per job: rules locked when the job opens and enforced on every run, item status set only from OpenAdapt's own results, and yes-or-no questions a person answers on the phone or in Desktop, including when a run stops | Released ([#1332](https://github.com/OpenAdaptAI/OpenAdapt/pull/1332)) | Synthetic (30-item MockMed worklist, scripted agent, no model calls) | MCP tools `open_job`, `get_job`, `add_items`, `record_evidence`, `ask_user`, `get_answer`, `change_constraint`, `close_job`; [Track a long job](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md#track-a-long-job) | | Limit a teaching agent to the declared task on every teach path (`compile_agent`, `compile-agent`, teach over MCP, the airbag guard): typed text must be a declared value, links and browser requests to other origins are refused, writes are checked before they are sent, and the record is read back before a draft exists. Injected instructions in record notes, banners, tooltips, alt text and server responses are blocked or caught on MockMed through each path (scripted agent; a live-model mode is off by default). Self-repair refuses a control that leaves the app | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359), [#1386](https://github.com/OpenAdaptAI/OpenAdapt/pull/1386)) | Synthetic | `openadapt_flow.teach_scope`, [THREAT_MODEL.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/THREAT_MODEL.md) | @@ -926,6 +927,7 @@ A test fails when a command has no file or this list is out of date. **Guard an agent you already run:** +- `flight`: Record any agent you already run: meter and price its model calls through a loopback proxy, scrub its screenshots and text before they leave the machine, log its actions, and hold each Save, Submit or Send for a person. - `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, and hands a verified run to the teach dir. - `hooks`: Writes `openadapt.systems.yaml` checks into Claude Code or Codex hooks: each write to a declared database, HTTP API or MCP tool is pre-checked, read back and given a signed receipt (advisory). - `learn`: Learn the app's own per-request writes from a shadow run, propose excuses, and approve them into the contracts. diff --git a/openadapt/cli.py b/openadapt/cli.py index c983f86934..9fc6930e03 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -2015,6 +2015,68 @@ def shadow(command_ctx: click.Context) -> None: _run_flow(["shadow", *command_ctx.args]) +#: `openadapt flow flight` options that take a value, and flags. Click drops +#: the "--" before CMD, so the launcher puts it back after these. +FLIGHT_VALUE_OPTIONS = frozenset( + { + "--task-id", + "--out", + "--label", + "--gate", + "--approval-timeout", + "--cdp", + "--guard-config", + "--guard-task", + "--max-cost-usd", + } +) +FLIGHT_FLAGS = frozenset({"--no-scrub", "--i-accept-unscrubbed", "--json", "-h", "--help"}) + + +def _flight_argv(args: list[str]) -> list[str]: + """``args`` with "--" restored before CMD, so CMD's options stay CMD's.""" + out: list[str] = [] + index = 0 + while index < len(args): + token = args[index] + if token in FLIGHT_VALUE_OPTIONS: + out.extend(args[index : index + 2]) + index += 2 + elif token in FLIGHT_FLAGS or token.split("=", 1)[0] in FLIGHT_VALUE_OPTIONS: + out.append(token) + index += 1 + else: + return [*out, "--", *args[index:]] + return out + + +@main.command( + "flight", + context_settings={ + "ignore_unknown_options": True, + "allow_extra_args": True, + "help_option_names": [], + }, +) +@click.pass_context +def flight(command_ctx: click.Context) -> None: + """Record any agent you already run, and hold its saves for a person. + + `openadapt flight [OPTIONS] -- CMD ...` meters and prices the agent's + model calls, scrubs its screenshots before they leave the machine, logs + its actions and writes flight.json. Every argument passes to + `openadapt flow flight`; its options are listed by + `openadapt flight --help`. + """ + if "flight" not in _flow_verbs(): + click.echo( + "Error: the installed openadapt-flow has no flight command.", err=True + ) + click.echo("Upgrade with: pip install --upgrade openadapt", err=True) + sys.exit(2) + _run_flow(["flight", *_flight_argv(list(command_ctx.args))]) + + def _optional_engine_entrypoint(command_ctx: click.Context, modules: tuple[str, ...]): """Show pure help for absent commands; preserve installed-engine failures.""" targets = { diff --git a/packages/flow/benchmark/flight/README.md b/packages/flow/benchmark/flight/README.md new file mode 100644 index 0000000000..9384fbc2aa --- /dev/null +++ b/packages/flow/benchmark/flight/README.md @@ -0,0 +1,19 @@ +# Flight recorder evidence + +`real_model_smoke.json` is written by +`tests/e2e/test_flight_real_model.py` when it runs with `ANTHROPIC_API_KEY` +in the environment and `OPENADAPT_FLIGHT_EVIDENCE=1`: + +```bash +OPENADAPT_FLIGHT_EVIDENCE=1 pytest packages/flow/tests/e2e/test_flight_real_model.py +``` + +The test sends one synthetic screen (a rendered intake form with a planted +synthetic name and a Save button) to the real Claude API through the flight +proxy, with the real openadapt-privacy scrubber. It records: + +- the run's `flight.json` fields (calls, tokens, priced cost, gate events); +- how many computer actions Claude asked for, and how many were held; +- that the executor performed none of them. + +No real patient data is used. The evidence holds no screenshot and no key. diff --git a/packages/flow/docs/FLIGHT_RECORDER.md b/packages/flow/docs/FLIGHT_RECORDER.md new file mode 100644 index 0000000000..6d11534811 --- /dev/null +++ b/packages/flow/docs/FLIGHT_RECORDER.md @@ -0,0 +1,218 @@ +# Flight recorder + +`openadapt flight` records a run of a computer-use agent you already have, +without rewriting its action layer. It works with a Claude computer-use loop, +an OpenAI computer-use (CUA) loop, Browser-Use, or any other process that +calls a model API. + +```bash +openadapt flight --task-id referral-0042 -- python my_agent.py +``` + +For that one run you get: + +- **Model cost metering.** Each model call goes through a loopback proxy. The + proxy counts input, output and cache tokens and prices them from the price + table in `openadapt_flow.compile_agent.agents.PRICES_PER_MTOK`. A model with + no price gets a cost of `null` with `cost_source: "unknown"`; the proxy + never guesses a price. +- **Scrubbing before anything leaves the machine.** The proxy redacts every + base64 screenshot with openadapt-privacy's image redaction, and scrubs every + content text block with its text scrubber, before it forwards the request. +- **A redacted timeline.** `timeline.jsonl` lists each model call, each + computer action the model asked for, each action your executor performed + and each gate decision. Frames are written as scrubbed thumbnails. + `timeline.html` is a static page you open locally. +- **A pre-commit gate.** If you swap one line in your loop, every click or + Enter on a Save, Submit or Send control is held for a person before it + happens. + +## How it works + +1. `flight` starts a server on `127.0.0.1` on a random port, with a random + token in the path. +2. It runs your command with `ANTHROPIC_BASE_URL` and `OPENAI_BASE_URL` set to + that server. The Anthropic and OpenAI SDKs read these variables. If they + were already set (a company gateway, for example), that URL stays the + provider the proxy forwards to. +3. For each request, the proxy: + 1. scrubs the request body; + 2. checks the spend cap; + 3. forwards the body over HTTPS with your agent's own headers, including + its API key. The key is never logged or written. + 4. passes the response back, streamed or not, and reads the usage from it. +4. Your command also gets `OPENADAPT_FLIGHT_GATE_URL`. A `GatedComputer` or + `GatedComputerCall` in your process uses it to log actions and to ask the + gate. +5. When the command exits, `flight` writes `flight.json`, prints the run + directory, and exits with the command's exit status. + +The proxy sends nothing anywhere except to the provider your agent already +targets. Anything that leaves the machine is scrubbed first. + +## Failing closed + +| Situation | What happens | +| --- | --- | +| openadapt-privacy is not installed | `flight` exits 2 before it starts your command | +| An image can't be decoded, an image or file is sent by URL, the body is compressed or isn't JSON, or the scrubber raises | The request is answered with HTTP 502 and a clear message, and is not forwarded | +| The spend cap is reached, or a cap is set and the model has no price | HTTP 429, and the request is not forwarded | +| The gate can't read the target under the pointer | The action counts as commit-class and goes to the gate | +| The gate errors, or the gate URL can't be reached | The action is refused and not performed | +| No scrubber is available for a local frame or value | The frame is not written, and the value is written as `[withheld]` | + +`--no-scrub` turns scrubbing off. It only works with `--i-accept-unscrubbed`, +and each use is recorded in `flight.json` and in the local +`~/.openadapt/unscrubbed-sends.jsonl` ledger. + +Some fields are passed on byte for byte, because the provider must get them +unchanged: thinking and reasoning blocks (their signatures must verify), tool +definitions, ids and model names. A thinking block holds only what the model +wrote from input that was already scrubbed. + +Image redaction finds text in a screenshot (OCR, then named-entity +recognition) and covers it. It does not detect faces. + +## The pre-commit gate + +The gate checks clicks, double clicks, Enter and Space keys, Ctrl+S or Cmd+S, +and typed text that ends a line. For each one, the wrapper reads the label of +the target: + +1. from your executor's accessibility hook (`label_at(x, y)`, or + `focused_label()` for keys) when it has one; +2. otherwise, by OCR of a fresh screenshot near the pointer. + +The action is commit-class when the label holds one of these words: Save, +Submit, Send, Sign, Approve, Confirm, Post, Pay, File, Finalize. It is also +commit-class when no label can be read. An action the JIT translators can't +classify, such as a triple click or a separate mouse-down, is commit-class +too. + +A commit-class action goes to the gate, which allows, holds or refuses it. +Unless the gate allows it, your executor is never called. The agent gets back +"held for a person: not performed". + +| `--gate` | Who decides | +| --- | --- | +| `terminal` (default) | `y/N` on the terminal that runs `flight`. With no terminal, the action is refused. | +| `file` | An item-approval request (`openadapt.item-approval-request/v1`) in the run directory. Desktop's Run it or a paired phone answers it; only a person's signed answer counts. If no one answers within `--approval-timeout`, the action stays held. | +| `refuse` | Nobody. Every commit-class action is held. Use this for unattended runs. | + +Because "unknown" counts as commit-class, a click on a control with no +readable text (an icon button, an empty field) is held when your executor has +no accessibility hook. Add `label_at` to your executor to avoid that. + +## The one-line swap + +### Anthropic computer-use reference loop + +In the reference implementation's `loop.py`, wrap the computer tool: + +```python +from openadapt_flow.flight import GatedComputer + +tool_collection = ToolCollection( + GatedComputer(ComputerTool(), held=lambda msg: ToolResult(error=msg)), + BashTool(), + EditTool(), +) +``` + +`GatedComputer` is async when the tool is. It passes `name`, `to_params()` +and other attributes through. With the `computer_toolset_20260801` toolset, +the tool name is the action, so call it as `computer(action=name, **input)`. + +### OpenAI CUA sample loop + +```python +from openadapt_flow.flight import GatedComputerCall + +with LocalPlaywrightBrowser() as computer: + agent = Agent(computer=GatedComputerCall(computer)) +``` + +Every method passes through. A held action is not performed. The next +`screenshot()` has a red banner at the top saying so, because a +`computer_call_output` returns only a screenshot. + +### Browser-Use + +Browser-Use drives Chromium through CDP. Start Chromium with a DevTools port, +point the LLM at the proxy, and give `flight` the existing guard's config: + +```python +import os +from browser_use import Agent, Browser, ChatAnthropic + +browser = Browser(cdp_url="http://127.0.0.1:9222") +llm = ChatAnthropic(model="claude-opus-5-5", base_url=os.environ["ANTHROPIC_BASE_URL"]) +agent = Agent(task="...", llm=llm, browser=browser) +``` + +```bash +openadapt flight --cdp http://127.0.0.1:9222 \ + --guard-config guard.yaml --guard-task task.json -- python browser_agent.py +``` + +With `--cdp`, `flight` also runs `openadapt-flow guard`, which holds each save +until the right record is on screen and reads it back. See +[GUARD_AN_AGENT.md](GUARD_AN_AGENT.md). If the command starts Chromium itself +with `--remote-debugging-port=N`, `flight` uses that port. Without +`--guard-config` and `--guard-task`, it prints a reminder and runs without +the guard. + +### Your own loop + +```python +from openadapt_flow.flight import GatedComputer, TerminalGate, Timeline + +timeline = Timeline("runs/flight-1", task_id="t1", executor_label="my-loop") +computer = GatedComputer(my_executor, TerminalGate(), timeline) +... +timeline.finish() +``` + +## `flight.json` + +```json +{ + "schema": "openadapt.flight-run/v1", + "task_id": "referral-0042", + "executor_label": "python", + "started_at": "2026-11-21T10:00:00.000Z", + "ended_at": "2026-11-21T10:03:12.512Z", + "model": { + "calls": 7, + "input_tokens": 8400, + "output_tokens": 560, + "cost_usd": 0.0476, + "cost_source": "price_table" + }, + "actions_count": 6, + "gate_events": [ + {"at": "2026-11-21T10:03:10.004Z", "kind": "held", "reason": "the target reads 'button Save Encounter' (save)"} + ], + "timeline_path": "timeline.jsonl", + "details": {"scrub": {"mode": "on"}, "exit_code": 0} +} +``` + +The top-level keys are exactly the ones the run ledger collects. `details` is +optional and a reader may ignore it. It holds the scrub mode, cache tokens, +the priced part of the cost when some model had no price, the command's exit +code, the gate used and the guard's result. `cost_source` is `price_table`, +`unknown` (some call had no price, so `cost_usd` is `null`) or `no_calls`. +`actions_count` is the larger of the actions the model asked for and the +actions the executor reported. + +## Limits + +- The proxy only sees calls that use `ANTHROPIC_BASE_URL` or `OPENAI_BASE_URL`. + A client built with a hard-coded base URL bypasses it, and `flight` warns + when no call came through. +- Function-call `arguments` strings are forwarded as they are. Content text, + typed text in computer actions, tool results and images are scrubbed. +- OpenAI models are not in the price table, so their cost is recorded as + unknown. +- `flight` does not run agents; it records the agent you run. diff --git a/packages/flow/docs/commands/11-guard-an-agent-you-already-run/flight.md b/packages/flow/docs/commands/11-guard-an-agent-you-already-run/flight.md new file mode 100644 index 0000000000..b8ae2503cb --- /dev/null +++ b/packages/flow/docs/commands/11-guard-an-agent-you-already-run/flight.md @@ -0,0 +1 @@ +Record any agent you already run: meter and price its model calls through a loopback proxy, scrub its screenshots and text before they leave the machine, log its actions, and hold each Save, Submit or Send for a person. diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 5de90f3d77..e230dfb306 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13192,13 +13192,13 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: _add_jit_parser(sub) + from openadapt_flow.agent_guard.cli import add_parser as _add_guard_parser from openadapt_flow.compile_agent.cli import add_parser as _add_compile_agent_parser + from openadapt_flow.flight.cli import add_parser as _add_flight_parser _add_compile_agent_parser(sub) - - from openadapt_flow.agent_guard.cli import add_parser as _add_guard_parser - _add_guard_parser(sub) + _add_flight_parser(sub) from openadapt_flow.hooks.cli import add_parser as _add_hooks_parser diff --git a/packages/flow/openadapt_flow/flight/__init__.py b/packages/flow/openadapt_flow/flight/__init__.py new file mode 100644 index 0000000000..12bc6e5efe --- /dev/null +++ b/packages/flow/openadapt_flow/flight/__init__.py @@ -0,0 +1,55 @@ +"""Flight recorder for a computer-use agent you already run. + +``openadapt-flow flight -- CMD`` starts a loopback proxy in front of the +model API that ``CMD`` calls. The proxy meters and prices each call, scrubs +every screenshot and text block before it leaves the machine, and logs each +computer action the model asks for. A one-line executor swap +(:class:`GatedComputer` for the Anthropic computer tool, +:class:`GatedComputerCall` for an OpenAI ``computer_call`` loop) holds each +commit-class action (a click on Save, Submit, Send...) for a person. + +The run directory holds ``flight.json`` (``openadapt.flight-run/v1``), +``timeline.jsonl``, scrubbed frame thumbnails and ``timeline.html``. +See ``docs/FLIGHT_RECORDER.md``. +""" + +from __future__ import annotations + +from typing import Any + +__all__ = [ + "COMMIT_VERBS", + "FLIGHT_SCHEMA", + "FileGate", + "FlightProxy", + "GateAction", + "GatedComputer", + "GatedComputerCall", + "PreCommitGate", + "RefuseGate", + "TerminalGate", + "Timeline", +] + +_LAZY = { + "COMMIT_VERBS": "openadapt_flow.flight.computer", + "GateAction": "openadapt_flow.flight.gate", + "GatedComputer": "openadapt_flow.flight.computer", + "GatedComputerCall": "openadapt_flow.flight.computer", + "PreCommitGate": "openadapt_flow.flight.gate", + "TerminalGate": "openadapt_flow.flight.gate", + "FileGate": "openadapt_flow.flight.gate", + "RefuseGate": "openadapt_flow.flight.gate", + "FlightProxy": "openadapt_flow.flight.proxy", + "Timeline": "openadapt_flow.flight.timeline", + "FLIGHT_SCHEMA": "openadapt_flow.flight.timeline", +} + + +def __getattr__(name: str) -> Any: + module = _LAZY.get(name) + if module is None: + raise AttributeError(name) + import importlib + + return getattr(importlib.import_module(module), name) diff --git a/packages/flow/openadapt_flow/flight/cli.py b/packages/flow/openadapt_flow/flight/cli.py new file mode 100644 index 0000000000..d5477afc48 --- /dev/null +++ b/packages/flow/openadapt_flow/flight/cli.py @@ -0,0 +1,318 @@ +"""``openadapt-flow flight``: record any agent's run, gate its commits. + + openadapt-flow flight [--task-id ID] [--cdp URL] [--max-cost-usd N] -- CMD ... + +Starts a loopback proxy in front of the model API and runs CMD with +ANTHROPIC_BASE_URL and OPENAI_BASE_URL pointing at it, so every model call +is metered and priced, and every screenshot and text block is scrubbed of +personal data on this machine before it is sent. The provider the agent +already targets (its own *_BASE_URL, else the provider's API) is the only +place anything is sent; the agent's key passes through untouched and is +never logged. + +CMD also gets OPENADAPT_FLIGHT_GATE_URL: an executor wrapped with +GatedComputer or GatedComputerCall (one line, see FLIGHT_RECORDER.md) logs +its actions here and holds each click on Save, Submit, Send... (or on a +target it can't read) for a person: --gate terminal asks y/N on this +terminal, --gate file writes an item-approval request Desktop or a paired +phone answers, --gate refuse holds every one. + +With --cdp (or when CMD starts Chromium with --remote-debugging-port), the +existing `openadapt-flow guard` also attaches to the browser, given +--guard-config and --guard-task. + +Writes flight.json (openadapt.flight-run/v1), timeline.jsonl, scrubbed frame +thumbnails and timeline.html in the run directory, and prints its path. +Exit status: CMD's own; 2 when the run could not start (no scrubber, a bad +option, CMD not found). +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import secrets +import signal +import subprocess +import sys +import time +from pathlib import Path +from typing import Any, Optional + +__all__ = ["add_parser", "cmd_flight"] + +_UNSCRUBBED_PURPOSE = "flight: model API requests" +_PORT_FLAG = re.compile(r"^--remote-debugging-port=(\d+)$") + + +def add_parser(sub: argparse._SubParsersAction) -> None: + p = sub.add_parser( + "flight", + help=( + "Record any agent you already run: meter and price its model calls, " + "scrub its screenshots before they leave the machine, log its actions, " + "and hold each Save/Submit/Send for a person" + ), + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + allow_abbrev=False, + ) + p.add_argument("--task-id", help="the task this run does (default: generated)") + p.add_argument("--out", help="the run directory (default: flight-runs/