diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index afa54b0169..b6cdba13be 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -1240,6 +1240,7 @@ jobs: tests/e2e/test_browser_teach_write_guard_e2e.py \ tests/e2e/test_agent_guard_e2e.py \ tests/e2e/test_wrap_example_e2e.py \ + tests/e2e/test_wrap_command_e2e.py \ --basetemp=runs/ci-critical-e2e --junitxml=runs/critical-e2e-junit.xml - name: Golden runs (report, artifacts and actions unchanged) # docs/design/DECOMPOSITION.md, section 3.1. The baselines are Linux diff --git a/capabilities/10-computer-use-agents/0157-wrap-any-agent-process-openadapt-wrap-task-task.md b/capabilities/10-computer-use-agents/0157-wrap-any-agent-process-openadapt-wrap-task-task.md new file mode 100644 index 0000000000..1b9b245ed6 --- /dev/null +++ b/capabilities/10-computer-use-agents/0157-wrap-any-agent-process-openadapt-wrap-task-task.md @@ -0,0 +1 @@ +| Wrap any agent process: `openadapt wrap --task TASK --param ... -- COMMAND` starts the command for the first run with `OPENADAPT_MCP_URL` (a streamable-HTTP MCP endpoint on 127.0.0.1), `OPENADAPT_MCP_TOKEN` (a random per-run bearer token, compared in constant time, never printed) and `OPENADAPT_TASK`. The endpoint's tools (`observe`, `click`, `type_text`, `press_key`, `scroll`, `finish`) go through compile-agent's harness: the save gate, the read-back after every save, the task's origin limits and the recorder. The command gets no browser handle (no DevTools endpoint), so the draft carries the signed capture admission requires; the endpoint closes when the command exits, a nonzero exit makes no program and is passed through as wrap's exit status, and the command's process group is stopped after `--command-timeout`. Run 1's cost is reported as unknown (the command's model calls are its own). `openadapt wrap run --task TASK` runs only the admitted program, never an agent | In PR | Synthetic (an outside Python process with the `mcp` client SDK and no model does the bundled clinic task through the endpoint in headless Chromium: save gate, read-back, canary, admission by a registered admitter key under a signed teach authorization, then the emitted tool with no model calls; a failing command and a request without the token make no program) | [WRAP.md](packages/flow/docs/WRAP.md#wrap-your-own-agent), `openadapt_flow.wrap.process`, `packages/flow/examples/wrap_command/agent.py`, `packages/flow/tests/e2e/test_wrap_command_e2e.py` | diff --git a/openadapt/cli.py b/openadapt/cli.py index ad6e329212..f6e8f76fef 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -2286,7 +2286,26 @@ def wrap(command_ctx: click.Context) -> None: "Error: this openadapt-flow installation has no wrap command.", err=True ) sys.exit(2) - sys.exit(int(wrap_main(list(command_ctx.args)) or 0)) + sys.exit(int(wrap_main(_wrap_arguments(list(command_ctx.args))) or 0)) + + +def _wrap_arguments(parsed: list[str]) -> list[str]: + """``wrap``'s arguments with the ``--`` before a wrapped command kept. + + Click consumes ``--``, but ``openadapt wrap --task T -- CMD`` needs it to + tell wrap's options from the command's. The process's own argv is used + only when it holds exactly the same arguments apart from separators. + """ + + argv = list(sys.argv[1:]) + if "wrap" not in argv: + return parsed + raw = argv[argv.index("wrap") + 1 :] + if "--" in raw and [a for a in raw if a != "--"] == [ + a for a in parsed if a != "--" + ]: + return raw + return parsed @main.command( diff --git a/packages/flow/docs/WRAP.md b/packages/flow/docs/WRAP.md index b12d5627f0..9cb0651e09 100644 --- a/packages/flow/docs/WRAP.md +++ b/packages/flow/docs/WRAP.md @@ -68,6 +68,97 @@ recorded in `~/.openadapt/unscrubbed-sends.jsonl`. Without a model key the example stops before anything starts and names the variable to set (`[MISSING_MODEL_KEY]`). +## Wrap your own agent + +`openadapt wrap --task task.json --param NAME=VALUE -- COMMAND ...` runs your +agent, any program, for the first run instead of OpenAdapt's built-in agent. +OpenAdapt opens the task's app in its own headless browser and starts +`COMMAND` with three environment variables: + +| Variable | What it holds | +|---|---| +| `OPENADAPT_MCP_URL` | A Model Context Protocol endpoint (streamable HTTP) on `127.0.0.1` | +| `OPENADAPT_MCP_TOKEN` | A random token for this run. Send it as `Authorization: Bearer `; other requests get `401` | +| `OPENADAPT_TASK` | The task with its inputs, as the agent should read it | + +The endpoint has six tools: `observe` (the page as a listing, with refs such +as `e3` on its controls), `click`, `type_text`, `press_key`, `scroll` and +`finish`. They are the tools OpenAdapt's own agents use, with the same +checks: + +- Before a save, the record the task names must be on the screen, or the + save is refused and the run ends. +- Every save is read back from the system of record. A change to another + record, a second save or an unreadable store ends the run. +- An action that leaves the task's origins ends the run. +- Every action is recorded for the compiled program. + +The command gets no handle to the browser itself, so it can't act around +these checks. It also gets your environment without any `OPENADAPT_*` +variable and without any variable the task's `verify.yaml` reads (each +`${NAME}` reference and each `*_env` value, including every value of a +`secret_env` map, such as a database password or an API token), so +OpenAdapt's own keys and settings and the system of record's credentials +never reach it; its own variables, such as its model key, pass through. + +The command runs in its own process group. `--command-timeout` (default 600 +seconds) ends the whole group, and so do Ctrl-C and SIGTERM sent to +`openadapt wrap`. Without `--request-id`, the run's request ID is derived from +the task, the command and its inputs, so asking for the same run again +dedupes instead of saving twice. A deduped run prints its earlier result and +says so on stderr; to run it again (for example after a failure), pass a new +`--request-id`. If the earlier attempt was interrupted and may have saved +(`RECONCILIATION_REQUIRED`), check the record in the app first: a new +`--request-id` then could save twice. + +When the command exits, the endpoint closes. Then the run goes through the +same record check, proposed checks, canary and admission as any +`openadapt wrap --task` run (see [JIT_ADMISSION.md](JIT_ADMISSION.md)). Run it +in a terminal with `--person "Your Name"`: you confirm the proposed read-back +checks, review the steps and attend the canary there. Without `--person`, run 1 +stays a draft, and `wrap run` reports `[DRAFT_NOT_ADMITTED]`. + +```bash +openadapt wrap --task task.json --param note="Synthetic follow-up" \ + --person "Your Name" -- python my_agent.py +``` + +A nonzero exit makes no program, and `openadapt wrap` exits with the +command's status. The command is stopped after `--command-timeout` seconds +(default 600). + +When the privacy extra scrubs what the agent sees, the task's own values (its +record's identity and its inputs) appear as placeholders such as +`⟦task.identity_1⟧` in `OPENADAPT_TASK` and in every listing. Typing a +placeholder types its value. The endpoint's instructions say so too. + +[`examples/wrap_command/agent.py`](../examples/wrap_command/agent.py) is a +small agent with no model that does the sample clinic task through the +endpoint, with the `mcp` client SDK: + +```python +async with streamablehttp_client(url, headers=headers) as (read, write, _): + async with ClientSession(read, write) as session: + await session.initialize() + listing = await session.call_tool("observe", {}) +``` + +OpenAdapt can't see the model calls your command makes, so `openadapt wrap` +reports run 1's cost as unknown. + +The command runs as an ordinary process with your permissions. Only the +browser it drives belongs to OpenAdapt. + +### Later runs + +```bash +openadapt wrap run --task task.json --param note="Recheck knee in ten days" +``` + +`wrap run` runs the admitted program only: no command and no model calls, +and the save is read back. A task with no admitted program stops with +`[NO_ADMITTED_PROGRAM]` and runs nothing. + ## Wrap your own task Describe the task, its read-back and its record in a task file, then run diff --git a/packages/flow/examples/wrap_command/agent.py b/packages/flow/examples/wrap_command/agent.py new file mode 100644 index 0000000000..92b0efe631 --- /dev/null +++ b/packages/flow/examples/wrap_command/agent.py @@ -0,0 +1,91 @@ +"""A small outside agent for ``openadapt wrap -- COMMAND`` (no model). + +It connects to the MCP endpoint OpenAdapt gives it (``OPENADAPT_MCP_URL``, +with ``OPENADAPT_MCP_TOKEN``), reads ``OPENADAPT_TASK``, and does the sample +clinic task by reading each listing and choosing the next control, the way a +model-driven agent would. Its choices use the listing only. + +Run it under wrap:: + + openadapt wrap --task task.json --param note="..." -- python mcp_agent.py +""" + +from __future__ import annotations + +import asyncio +import os +import re +import sys + + +def _ref(listing: str, name: str, near: str | None = None) -> str: + for line in listing.splitlines(): + if near and near not in line: + continue + found = re.search(r"\[(e\d+)\] \S+ \"" + re.escape(name) + '"', line) + if found: + return found.group(1) + raise SystemExit(f"no control named {name!r} on the page") + + +async def main() -> int: + from mcp import ClientSession + from mcp.client.streamable_http import streamable_http_client + from mcp.shared._httpx_utils import create_mcp_http_client + + url = os.environ["OPENADAPT_MCP_URL"] + headers = {"Authorization": "Bearer " + os.environ["OPENADAPT_MCP_TOKEN"]} + task = os.environ["OPENADAPT_TASK"] + # The task names the record and the note either as values or, when the + # listings are scrubbed, as placeholders; the listings use the same form. + found = re.search(r"referral for (.+?), start", task) + if found is None: + raise SystemExit("the task names no referral") + record = found.group(1) + note = task.rsplit(": ", 1)[1].strip() + # The same calls work with the MCP 1 and MCP 2 client SDKs. + async with create_mcp_http_client(headers=headers) as http: + async with streamable_http_client(url, http_client=http) as streams: + read, write = streams[0], streams[1] + async with ClientSession(read, write) as session: + await session.initialize() + + async def call(name: str, **args: str) -> str: + result = await session.call_tool(name, args) + text = "".join(getattr(c, "text", "") for c in result.content) + if text.startswith("Stopped:"): + raise SystemExit(text) + return text + + listing = await call("observe") + triage_done = typed = False + for _ in range(20): + if "Encounter saved" in listing: + await call("finish", summary="saved the note") + return 0 + if "# Referral Tasks" in listing: + listing = await call("click", ref=_ref(listing, "Open", record)) + elif "# New Encounter" in listing: + if not triage_done: + triage_done = True + listing = await call("click", ref=_ref(listing, "Triage")) + elif not typed: + typed = True + listing = await call( + "type_text", text=note, ref=_ref(listing, "Note") + ) + else: + listing = await call( + "click", ref=_ref(listing, "Save Encounter") + ) + elif "New Encounter" in listing: + listing = await call( + "click", ref=_ref(listing, "New Encounter") + ) + else: + raise SystemExit("unexpected page") + return 1 + + +if __name__ == "__main__": + sys.exit(asyncio.run(main())) diff --git a/packages/flow/openadapt_flow/wrap/cli.py b/packages/flow/openadapt_flow/wrap/cli.py index 0665bdc441..29a8bdd9a3 100644 --- a/packages/flow/openadapt_flow/wrap/cli.py +++ b/packages/flow/openadapt_flow/wrap/cli.py @@ -3,10 +3,13 @@ from __future__ import annotations import argparse +import contextlib import json import math +import signal import sys -from collections.abc import Sequence +import threading +from collections.abc import Iterator, Sequence from typing import Any from openadapt_flow.wrap import TaskArgumentsError, WrappedTask @@ -16,6 +19,18 @@ WRAP_EXAMPLE_COMMAND = "uvx --python 3.12 'openadapt[wrap]@latest' wrap --example" +class NoAdmittedProgram(RuntimeError): + """``wrap run``: the task has no admitted program, so nothing ran. + + ``draft`` is the task folder when run 1 left a draft that was not + admitted, else None. + """ + + def __init__(self, draft: Any = None) -> None: + super().__init__("no admitted program") + self.draft = draft + + def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="openadapt wrap", @@ -23,6 +38,12 @@ def build_parser() -> argparse.ArgumentParser: epilog=( "openadapt wrap --example runs the whole loop on a bundled synthetic " "task (see its --help). " + "openadapt wrap --task TASK [--param ...] -- COMMAND runs your own " + "agent command for the first run: it gets OPENADAPT_MCP_URL, " + "OPENADAPT_MCP_TOKEN and OPENADAPT_TASK, and drives OpenAdapt's " + "browser through that endpoint (see docs/WRAP.md). " + "openadapt wrap run --task TASK [--param ...] runs the admitted " + "program only, with no model calls. " "openadapt wrap export --bundle BUNDLE --out NEW_DIR prepares an " "untrusted local candidate (see docs/WRAP_CANDIDATE.md). " "openadapt wrap publish --task TASK publishes the task's admitted " @@ -87,6 +108,12 @@ def build_parser() -> argparse.ArgumentParser: action="store_true", help="Expose this task as a local stdio MCP tool", ) + parser.add_argument( + "--command-timeout", + type=float, + default=600.0, + help="With -- COMMAND: seconds before the command is stopped (default 600)", + ) return parser @@ -145,7 +172,13 @@ def _prices(rows: Sequence[str]) -> dict[str, float] | None: return prices -def _task(args: argparse.Namespace, parser: argparse.ArgumentParser) -> WrappedTask: +def _task( + args: argparse.Namespace, + parser: argparse.ArgumentParser, + *, + command_agent: Any = None, + replay_only: bool = False, +) -> WrappedTask: from openadapt_flow.integrations.agents.recording import load_task options: dict[str, Any] = {} @@ -195,7 +228,19 @@ def _task(args: argparse.Namespace, parser: argparse.ArgumentParser) -> WrappedT cached = setup.cache.server(setup.instruction, names) halted = False agent = None - if cached is None and not halted: + if cached is None and not halted and replay_only: + compiler, _key = setup.cache._compiler(setup.instruction, names) + draft = compiler._jit().candidate() is not None + raise NoAdmittedProgram(compiler.dir if draft else None) + if command_agent is not None: + from openadapt_flow.wrap.process import verify_env_names + + # The system of record's credentials never reach the wrapped command. + command_agent.withheld_env = verify_env_names(setup.cache.common["verify"]) + if cached is None and not halted and command_agent is not None: + # The wrapped command brings its own model; OpenAdapt sends none. + agent = command_agent + elif cached is None and not halted: cap = args.max_cost_usd if cap is None or not math.isfinite(cap) or cap <= 0: parser.error("a cache miss requires a positive --max-cost-usd") @@ -378,6 +423,40 @@ def example_main(rows: Sequence[str], *, client: Any = None) -> int: return 2 +@contextlib.contextmanager +def _commands_stopped_on_signal(active: bool) -> Iterator[None]: + """End the wrapped command's process group on Ctrl-C, SIGTERM or any exit. + + The command runs in its own session, so a terminal's Ctrl-C and a SIGTERM + sent to OpenAdapt never reach it. The handlers stop the group themselves + before raising: the main thread may be inside a browser tool call whose + error handling keeps the interrupt from reaching this block, and the + command must still end. Every exit from this block stops what is left. + """ + + if not active: + yield + return + from openadapt_flow.wrap.process import stop_running_commands + + main_thread = threading.current_thread() is threading.main_thread() + previous: dict[signal.Signals, Any] = {} + + def on_signal(signum: int, frame: Any) -> None: + stop_running_commands() + raise KeyboardInterrupt + + if main_thread: + for caught in (signal.SIGINT, signal.SIGTERM): + previous[caught] = signal.signal(caught, on_signal) + try: + yield + finally: + stop_running_commands() + for caught, handler in previous.items(): + signal.signal(caught, handler) + + def main(argv: Sequence[str] | None = None) -> int: rows = list(sys.argv[1:] if argv is None else argv) head = rows[: rows.index("--")] if "--" in rows else rows @@ -391,25 +470,84 @@ def main(argv: Sequence[str] | None = None) -> int: from openadapt_flow.wrap.publish import main as publish_main return publish_main(rows[1:]) + command = rows[rows.index("--") + 1 :] if "--" in rows else None + replay_only = head[:1] == ["run"] + if replay_only: + head = head[1:] parser = build_parser() - args = parser.parse_args(rows) + if replay_only: + parser.prog = "openadapt wrap run" + args = parser.parse_args(head) + if command is not None and (replay_only or args.serve): + parser.error( + "-- COMMAND runs the first run; it can't be used with run or --serve" + ) + if command == []: + parser.error("-- needs a command to run") if args.serve and (args.param or args.request_id): parser.error("--serve takes request IDs and parameters from MCP calls") if not args.serve and not args.request_id: - parser.error("a run requires --request-id") + if command is None and not replay_only: + parser.error("a run requires --request-id") from openadapt_flow.jit.keys import PROVIDER_ENV, MissingModelKey + agent = None + derived_id = False try: values = _params(args.param) - task = _task(args, parser) + derived_id = not args.serve and not args.request_id + if derived_id: + from openadapt_flow.wrap.process import request_id_for + + # Never random: asking for the same run again must dedupe. + args.request_id = request_id_for(args.task, command or [], values) + if command is not None: + from openadapt_flow.wrap.process import ProcessAgent + + agent = ProcessAgent(command, timeout_s=args.command_timeout) + if agent is None and not replay_only: + task = _task(args, parser) + else: + task = _task(args, parser, command_agent=agent, replay_only=replay_only) + if agent is not None and task.agent is not agent: + print( + "openadapt wrap: this task has an admitted program; it runs " + "instead of the command, with no model calls", + file=sys.stderr, + ) if args.serve: from openadapt_flow.wrap.mcp import serve serve(task) return 0 - result = task.call(args.request_id, _with_secret_env(values, task.parameters)) + with _commands_stopped_on_signal(agent is not None): + result = task.call( + args.request_id, _with_secret_env(values, task.parameters) + ) + except KeyboardInterrupt: + print( + "openadapt wrap: interrupted; the wrapped command was stopped", + file=sys.stderr, + ) + return 130 except TaskArgumentsError as exc: parser.error(str(exc)) + except NoAdmittedProgram as exc: + if exc.draft is not None: + print( + "openadapt wrap run: run 1 left a draft that was not admitted, " + f"in {exc.draft}; nothing ran. A draft is admitted when a person " + "confirms it during run 1 (--person) [DRAFT_NOT_ADMITTED]", + file=sys.stderr, + ) + else: + print( + "openadapt wrap run: this task has no admitted program; nothing " + "ran. Do the first run with openadapt wrap --task TASK -- COMMAND " + "[NO_ADMITTED_PROGRAM]", + file=sys.stderr, + ) + return 2 except MissingModelKey: # Raised before the agent runs, so no run record exists yet. Name the # variable only; the message never carries a key value. @@ -428,7 +566,28 @@ def main(argv: Sequence[str] | None = None) -> int: file=sys.stderr, ) return 2 + if derived_id and result.get("status") == "RECONCILIATION_REQUIRED": + # An earlier attempt was interrupted after it may have saved: a new + # request ID now could save twice, so the record comes first. + print( + f"openadapt wrap: request {args.request_id} has an unfinished " + "earlier attempt; the earlier attempt may have saved; check the " + "record in the app before rerunning with a new --request-id", + file=sys.stderr, + ) + elif derived_id and result.get("replayed") is True: + # The default dedupes; say so instead of replaying silently. + print( + f"openadapt wrap: request {args.request_id} already ran with this " + "task, command and inputs; this is its earlier result and nothing " + "ran again. To run it again, pass a new --request-id", + file=sys.stderr, + ) print(json.dumps(result, sort_keys=True)) + exit_code = getattr(agent, "exit_code", None) + if isinstance(exit_code, int) and exit_code != 0: + # The wrapped command's own failure is its exit status. + return exit_code if 0 < exit_code < 256 else 1 return 0 if result.get("verified") is True else 1 diff --git a/packages/flow/openadapt_flow/wrap/process.py b/packages/flow/openadapt_flow/wrap/process.py new file mode 100644 index 0000000000..7fe6e230ed --- /dev/null +++ b/packages/flow/openadapt_flow/wrap/process.py @@ -0,0 +1,515 @@ +"""``openadapt wrap --task TASK -- COMMAND``: wrap any agent process. + +OpenAdapt opens the task's app in its own headless browser and starts +``COMMAND`` with three environment variables: + +``OPENADAPT_MCP_URL`` + A Model Context Protocol endpoint (streamable HTTP) on ``127.0.0.1``. +``OPENADAPT_MCP_TOKEN`` + A random token for this run only. Every request must send it as + ``Authorization: Bearer ``; it is compared in constant time. +``OPENADAPT_TASK`` + The task, with its inputs, as the agent should read it. + +The command gets the caller's environment without any ``OPENADAPT_*`` +variable and without any variable the task's ``verify.yaml`` reads (a +``${NAME}`` reference or a ``*_env`` value), so OpenAdapt's own keys and +settings and the system of record's credentials never reach the agent being +admitted. When the privacy extra scrubs listings, the task's own values +(its record's identity and its inputs) appear as placeholders such as +``⟦task.identity_1⟧`` in ``OPENADAPT_TASK`` and in every listing; typing a +placeholder types its value. + +The endpoint's tools are the skill cache's browser tools (``observe``, +``click``, ``type_text``, ``press_key``, ``scroll``, ``finish``). Each one goes +through compile-agent's harness, exactly as OpenAdapt's built-in agent does: +the save gate checks that the task's record is on screen before a save, every +save is read back from the system of record, an action outside the task's +origins ends the run, and the actions are recorded. The command never gets +the browser itself (no DevTools endpoint), so it cannot act around those +checks. When it exits, the endpoint closes and the run goes through the same +record check, proposed checks, canary and admission as ``openadapt wrap +--task``. Later calls (``openadapt wrap run``) run the admitted program with +no model calls. + +The command itself runs as an ordinary process with the user's permissions; +only the browser it drives is OpenAdapt's. +""" + +from __future__ import annotations + +import contextlib +import hashlib +import hmac +import json +import os +import re +import secrets +import signal +import socket +import subprocess +import threading +import time +from collections.abc import Iterable, Mapping, Sequence +from pathlib import Path +from typing import Any, Optional + +from openadapt_flow.integrations.agents.skills import BrowserTools, FrameworkAgent + +__all__ = [ + "ENV_TASK", + "ENV_TOKEN", + "ENV_URL", + "CommandFailed", + "ProcessAgent", + "ToolEndpoint", + "child_environment", + "request_id_for", + "stop_running_commands", + "verify_env_names", +] + +ENV_URL = "OPENADAPT_MCP_URL" +ENV_TOKEN = "OPENADAPT_MCP_TOKEN" +ENV_TASK = "OPENADAPT_TASK" +_PATH = "/mcp" +#: How long a killed command's process group gets to exit after SIGTERM. +_TERM_GRACE_S = 5.0 + + +class CommandFailed(RuntimeError): + """The wrapped command exited with a nonzero status or ran out of time.""" + + def __init__(self, exit_code: int) -> None: + super().__init__(f"the wrapped command exited with status {exit_code}") + self.exit_code = exit_code + + +def child_environment( + environ: Mapping[str, str], withheld: Iterable[str] = () +) -> dict[str, str]: + """The command's environment: the caller's, without OpenAdapt's own settings. + + The command is the agent whose run is being admitted, so it gets none of + OpenAdapt's configuration or credentials (``OPENADAPT_*``: the admission + key passphrase, ``OPENADAPT_FLOW_SECRET_`` sign-in values, Cloud + keys), and none of the ``withheld`` names (the variables the task's + verifier reads, such as its database password). Its own variables, such + as its model key, pass through. + """ + + drop = {name.upper() for name in withheld} + return { + k: v + for k, v in environ.items() + if not k.upper().startswith("OPENADAPT_") and k.upper() not in drop + } + + +_ENV_REF = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-[^}]*)?\}") + + +def verify_env_names(verify: Any) -> frozenset[str]: + """Every environment variable a ``verify.yaml`` reads. + + That is each ``${NAME}`` (or ``${NAME:-default}``) reference anywhere in + the file, and each value of a key ending in ``_env`` (for example + ``sql_password_env``, ``basic_env``, or every value of a + ``secret_env: {slot: VAR}`` map). An unreadable file raises, so a + wrapped command never starts with credentials that could not be checked. + """ + + import yaml + + text = Path(verify).read_text(encoding="utf-8") + names = set(_ENV_REF.findall(text)) + + def walk(node: Any) -> None: + if isinstance(node, Mapping): + for key, value in node.items(): + if isinstance(key, str) and key.endswith("_env"): + # One name, a list of names, or a map such as + # ``secret_env: {slot: VAR}``: every value is a variable. + if isinstance(value, Mapping): + values = list(value.values()) + elif isinstance(value, (list, tuple)): + values = list(value) + else: + values = [value] + names.update(v for v in values if isinstance(v, str) and v) + walk(value) + elif isinstance(node, (list, tuple)): + for item in node: + walk(item) + + walk(yaml.safe_load(text)) + return frozenset(names) + + +def request_id_for(task: str, command: Sequence[str], values: Mapping[str, str]) -> str: + """A request ID derived from the task, the command and its inputs. + + The same wrapped run asked again gets the same ID, so a retry dedupes + instead of saving twice. A different input is a different request. + """ + + material = json.dumps( + { + "task": str(Path(task).expanduser().resolve()), + "command": list(command), + "inputs": dict(sorted(values.items())), + }, + sort_keys=True, + separators=(",", ":"), + ) + return "wrap-" + hashlib.sha256(material.encode("utf-8")).hexdigest()[:32] + + +#: Wrapped commands still running, so a signal to OpenAdapt ends them too. +_RUNNING: set["subprocess.Popen[Any]"] = set() +# Re-entrant: the CLI's signal handlers call stop_running_commands() on the +# main thread, which may already hold the lock when the signal arrives. +_RUNNING_LOCK = threading.RLock() + + +def stop_running_commands() -> None: + """End every wrapped command still running, with its whole process group.""" + + with _RUNNING_LOCK: + running = list(_RUNNING) + for process in running: + with contextlib.suppress(Exception): + _stop_group(process) + + +def _run_group(command: Sequence[str], env: Mapping[str, str], timeout_s: float) -> int: + """Run ``command`` in its own process group and return its exit status. + + The group is ended on a timeout (``CommandFailed``), on any exception in + this thread, and by :func:`stop_running_commands` (which the CLI calls on + Ctrl-C and SIGTERM, since the group's own session gets neither). + """ + + process = subprocess.Popen( + list(command), env=dict(env), start_new_session=os.name == "posix" + ) + with _RUNNING_LOCK: + _RUNNING.add(process) + try: + try: + return process.wait(timeout=timeout_s) + except subprocess.TimeoutExpired: + _stop_group(process) + raise CommandFailed( + process.returncode if process.returncode else -9 + ) from None + except BaseException: + _stop_group(process) + raise + finally: + with _RUNNING_LOCK: + _RUNNING.discard(process) + + +def _tool_specs() -> list[dict[str, Any]]: + def obj(props: dict[str, Any], required: list[str]) -> dict[str, Any]: + return { + "type": "object", + "properties": props, + "required": required, + "additionalProperties": False, + } + + text = {"type": "string"} + return [ + { + "name": "observe", + "description": "Read the current page: one line per heading, text, row or " + "control. Controls carry refs such as e3.", + "schema": obj({}, []), + }, + { + "name": "click", + "description": "Click the control with this ref from the latest listing.", + "schema": obj({"ref": text}, ["ref"]), + }, + { + "name": "type_text", + "description": "Type text. With a ref, click that field first; without " + "one, type into the focused field. Typing appends to the field.", + "schema": obj({"text": text, "ref": text}, ["text"]), + }, + { + "name": "press_key", + "description": "Press one key, such as Enter, Tab or Escape.", + "schema": obj({"key": text}, ["key"]), + }, + { + "name": "scroll", + "description": "Scroll the page up or down by most of a screen.", + "schema": obj( + {"direction": {"type": "string", "enum": ["up", "down"]}}, [] + ), + }, + { + "name": "finish", + "description": "End the task, once, when it is done or cannot be done.", + "schema": obj({"summary": text}, ["summary"]), + }, + ] + + +def _call(tools: BrowserTools, name: str, args: Mapping[str, Any]) -> str: + if name == "observe": + return tools.observe() + if name == "click": + return tools.click(str(args["ref"])) + if name == "type_text": + return tools.type_text(str(args["text"]), str(args.get("ref") or "")) + if name == "press_key": + return tools.press_key(str(args["key"])) + if name == "scroll": + return tools.scroll(str(args.get("direction") or "down")) + if name == "finish": + return tools.finish(str(args["summary"])) + raise LookupError(name) + + +def _mcp_server(tools: BrowserTools) -> Any: + """A low-level MCP server over ``tools``. + + It follows ``openadapt_flow.wrap.mcp``'s adapter for both SDK generations; + the streamable-HTTP endpoint is tested with the locked MCP 1 SDK. + """ + + from importlib import import_module + + import anyio + from jsonschema import ValidationError, validate + from mcp.server.lowlevel import Server + + try: + types: Any = 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" + specs = {spec["name"]: spec for spec in _tool_specs()} + + async def list_tools() -> list[Any]: + return [ + types.Tool( + name=spec["name"], + description=spec["description"], + **{input_schema_field: spec["schema"]}, + ) + for spec in specs.values() + ] + + async def call_tool(name: str, arguments: Optional[dict[str, Any]]) -> Any: + spec = specs.get(name) + try: + if spec is None: + raise LookupError(name) + args = arguments or {} + validate(args, spec["schema"]) + # The browser belongs to the harness thread; BrowserTools hands + # the action to it and waits. + text = await anyio.to_thread.run_sync( + lambda: _call(tools, name, args), abandon_on_cancel=False + ) + except (ValidationError, LookupError): + return types.CallToolResult( + content=[types.TextContent(type="text", text="Not done: invalid call")], + **{error_field: True}, + ) + return types.CallToolResult(content=[types.TextContent(type="text", text=text)]) + + from openadapt_flow.privacy import PLACEHOLDER_HELP + + instructions = ( + "You operate a web application for the user. observe returns the page as " + "a listing; controls carry refs such as e3. Act with click, type_text, " + "press_key and scroll; each returns the new listing. Before a save the " + "right record must be on screen; every save is read back. Do exactly " + "the task in OPENADAPT_TASK and call finish once. " + PLACEHOLDER_HELP + ) + if hasattr(Server, "list_tools"): + server = Server( + "openadapt-wrap-process", 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-wrap-process", + version="1", + instructions=instructions, + on_list_tools=list_v2, + on_call_tool=call_v2, + ) + + +class ToolEndpoint: + """The browser tools as a token-guarded MCP endpoint on 127.0.0.1.""" + + def __init__(self, tools: BrowserTools) -> None: + self.token = secrets.token_urlsafe(32) + self._tools = tools + self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self._sock.bind(("127.0.0.1", 0)) + self.port = self._sock.getsockname()[1] + self.url = f"http://127.0.0.1:{self.port}{_PATH}" + self._server: Any = None + self._thread: Optional[threading.Thread] = None + + def _app(self) -> Any: + from mcp.server.streamable_http_manager import StreamableHTTPSessionManager + + manager = StreamableHTTPSessionManager(app=_mcp_server(self._tools)) + expected = ("Bearer " + self.token).encode("ascii") + + async def app(scope: dict[str, Any], receive: Any, send: Any) -> None: + if scope["type"] == "lifespan": + async with contextlib.AsyncExitStack() as stack: + message = await receive() + if message["type"] == "lifespan.startup": + await stack.enter_async_context(manager.run()) + await send({"type": "lifespan.startup.complete"}) + message = await receive() + await send({"type": "lifespan.shutdown.complete"}) + return + if scope["type"] != "http": + return + headers = dict(scope.get("headers") or []) + given = headers.get(b"authorization", b"") + if scope.get("path") != _PATH or not hmac.compare_digest(given, expected): + await send( + { + "type": "http.response.start", + "status": 401 if scope.get("path") == _PATH else 404, + "headers": [(b"content-type", b"text/plain")], + } + ) + await send({"type": "http.response.body", "body": b"refused"}) + return + await manager.handle_request(scope, receive, send) + + return app + + def start(self, timeout_s: float = 10.0) -> None: + import uvicorn + + config = uvicorn.Config( + self._app(), + log_level="error", + access_log=False, + lifespan="on", + ) + self._server = uvicorn.Server(config) + self._server.install_signal_handlers = lambda: None # type: ignore[method-assign] + self._thread = threading.Thread( + target=self._server.run, + kwargs={"sockets": [self._sock]}, + name="openadapt-wrap-mcp", + daemon=True, + ) + self._thread.start() + deadline = time.monotonic() + timeout_s + while not self._server.started: + if time.monotonic() > deadline or not self._thread.is_alive(): + raise RuntimeError("the local tool endpoint did not start") + time.sleep(0.02) + + def stop(self) -> None: + if self._server is not None: + self._server.should_exit = True + if self._thread is not None: + self._thread.join(timeout=10) + self._sock.close() + + +class ProcessAgent(FrameworkAgent): + """Run 1 by an outside command that drives OpenAdapt's browser over MCP. + + The command's model usage is its own and is not visible here, so run 1's + cost is reported as unknown, never as zero. + """ + + dialect = "generic" + requires_model_key = False + + def __init__( + self, + command: Sequence[str], + *, + timeout_s: float = 600.0, + principal_id: str = "agent:wrapped-process", + withheld_env: Iterable[str] = (), + ) -> None: + if not command or any(not isinstance(part, str) for part in command): + raise ValueError("the wrapped command is empty") + if not (timeout_s > 0): + raise ValueError("the command timeout must be positive") + super().__init__(self._run_command, principal_id=principal_id) + self.command = list(command) + self.timeout_s = timeout_s + #: Variables the task's verifier reads; the command never gets them. + self.withheld_env: frozenset[str] = frozenset(withheld_env) + #: The command's exit status, once it has exited (negative: a signal). + self.exit_code: Optional[int] = None + + def _run_command(self, task: str, tools: BrowserTools) -> None: + endpoint = ToolEndpoint(tools) + endpoint.start() + try: + env = child_environment(os.environ, self.withheld_env) + env.update( + {ENV_URL: endpoint.url, ENV_TOKEN: endpoint.token, ENV_TASK: task} + ) + try: + self.exit_code = _run_group(self.command, env, self.timeout_s) + except CommandFailed as failed: + self.exit_code = failed.exit_code + raise + finally: + endpoint.stop() + if self.exit_code != 0: + raise CommandFailed(self.exit_code) + if tools.summary is None and tools.stopped is None: + # A command that exits 0 without calling finish has finished. + tools.summary = "the wrapped command exited with status 0" + return None + + +def _stop_group(process: "subprocess.Popen[Any]") -> None: + """End the command and every process it started, by its own group only.""" + + if process.poll() is not None: + return + if os.name == "posix": + try: + os.killpg(process.pid, signal.SIGTERM) + except ProcessLookupError: + return + try: + process.wait(timeout=_TERM_GRACE_S) + return + except subprocess.TimeoutExpired: + with contextlib.suppress(ProcessLookupError): + os.killpg(process.pid, signal.SIGKILL) + else: + process.kill() + process.wait(timeout=_TERM_GRACE_S) diff --git a/packages/flow/tests/e2e/test_wrap_command_e2e.py b/packages/flow/tests/e2e/test_wrap_command_e2e.py new file mode 100644 index 0000000000..6e7dc6f5d3 --- /dev/null +++ b/packages/flow/tests/e2e/test_wrap_command_e2e.py @@ -0,0 +1,275 @@ +"""``openadapt wrap -- COMMAND`` end to end with a real outside process. + +The wrapped command is ``examples/wrap_command/agent.py``, a separate Python +process with no model. It reaches OpenAdapt only through the MCP endpoint in +``OPENADAPT_MCP_URL`` with the token in ``OPENADAPT_MCP_TOKEN``. Everything +else is real: the bundled clinic app over HTTP, headless Chromium, the save +gate, the read-back, compile, canary, admission by a registered admitter key +under a person-signed teach authorization, and a later run of the emitted MCP +tool with no model calls and no command. +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path +from typing import Any, Iterator + +import pytest + +pytest.importorskip("playwright") +pytest.importorskip("mcp") +pytest.importorskip("uvicorn") + +from openadapt_flow.integrations.agents.recording import load_task # noqa: E402 +from openadapt_flow.mockmed.fault_server import serve # noqa: E402 +from openadapt_flow.teach_authorization_fixture import demo_authority # noqa: E402 +from openadapt_flow.tutorial import _http_json # noqa: E402 +from openadapt_flow.wrap import WrappedTask # noqa: E402 +from openadapt_flow.wrap.process import CommandFailed, ProcessAgent # noqa: E402 + +pytestmark = pytest.mark.timeout(900) +AGENT = Path(__file__).resolve().parents[2] / "examples" / "wrap_command" / "agent.py" +INSTRUCTION = ( + "Open the referral for Jane Sample, start a Triage encounter, and save " + "this note: {note}" +) + + +@pytest.fixture() +def clinic() -> Iterator[str]: + base, _db, stop = serve() + yield base.rstrip("/") + stop() + + +def _setup(tmp_path: Path, base: str, monkeypatch: pytest.MonkeyPatch) -> Any: + from openadapt_flow.jit import authority + + monkeypatch.setenv(authority.KEY_PASSPHRASE_ENV, "e2e passphrase") + key_dir = tmp_path / "keys" + pem = tmp_path / "keyfiles" / "ci.pem" + authority.register_principal( + key_dir, + role="admitter_key", + principal_id="ci:wrap-command", + public_key_hex=authority.generate_encrypted_key(pem), + ) + admitter = authority.principal_from_key(authority.load_encrypted_key(pem), key_dir) + task_file = tmp_path / "task.json" + task_file.write_text( + json.dumps( + { + "schema": "openadapt.wrap-task/v1", + "instruction": INSTRUCTION, + "parameters": ["note"], + "url": f"{base}/?fault=ok&idempotency=demo#tasks", + "verifier": { + "kind": "rest", + "base_url": base, + "records_path": "/api/db", + "records_key": "records", + "records_complete": True, + }, + "expect": {"patient_id": "p1", "type": "Triage"}, + "on_screen": ["Jane Sample", "MRN P1"], + "canary_params": [{"note": "Synthetic canary note"}], + "cache_dir": str(tmp_path / "cache"), + } + ) + ) + reset = lambda: _http_json(f"{base}/api/reset", method="POST", body={}) # noqa: E731 + setup = load_task( + task_file, + offer=lambda proposal: "ci:wrap-command-reviewer", + admitter=admitter, + key_dir=key_dir, + reset=reset, + ) + return setup, reset + + +def _authorize(setup: Any, tmp_path: Path, url: str, note: str) -> None: + setup.cache.common["teach_authorization"] = demo_authority( + tmp_path, + task_id=setup.cache.task_id(setup.instruction, {"note": note}), + url=url, + record={"patient_id": "p1", "type": "Triage"}, + inputs={"note": note}, + constants=["Jane Sample", "MRN P1"], + ) + + +def test_an_outside_command_is_compiled_admitted_and_replayed( + clinic: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + setup, reset = _setup(tmp_path, clinic, monkeypatch) + note = "Synthetic follow-up in two weeks" + _authorize(setup, tmp_path, setup.cache.common["url"], note) + command = ProcessAgent([sys.executable, str(AGENT)], timeout_s=300) + task = WrappedTask( + cache=setup.cache, + agent=command, + instruction=setup.instruction, + parameters=setup.parameters, + runs_dir=tmp_path / "runs", + ) + reset() + first = task.call("first", {"note": note}) + assert command.exit_code == 0 + assert first["path"] == "agent" and first["status"] == "admitted", first + assert first["verified"] is True + # The command's model use is its own: unknown here, never reported as 0. + assert first["usage_known"] is False and first["cost_usd"] is None + + # A later run uses the admitted program, not the command. + reset() + later = WrappedTask( + cache=setup.cache, + agent=None, + instruction=setup.instruction, + parameters=setup.parameters, + runs_dir=tmp_path / "runs", + ) + second = later.call("second", {"note": "Recheck knee in ten days"}) + assert second["path"] == "skill" and second["status"] == "VERIFIED", second + assert second["model_calls"] == 0 and second["receipt_outcome"] == "VERIFIED" + rows = _http_json(f"{clinic}/api/db")["records"] + assert [r["note"] for r in rows if r["patient_id"] == "p1"] == [ + "Recheck knee in ten days" + ] + + +def test_a_failing_command_makes_no_program_and_keeps_its_exit_status( + clinic: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + setup, reset = _setup(tmp_path, clinic, monkeypatch) + note = "Synthetic follow-up in two weeks" + _authorize(setup, tmp_path, setup.cache.common["url"], note) + command = ProcessAgent([sys.executable, "-c", "raise SystemExit(7)"], timeout_s=60) + task = WrappedTask( + cache=setup.cache, + agent=command, + instruction=setup.instruction, + parameters=setup.parameters, + runs_dir=tmp_path / "runs", + ) + reset() + result = task.call("first", {"note": note}) + assert command.exit_code == 7 + # The run ends as a failed capture: no draft, no program. + assert result["status"] == "capture_failed" and result["verified"] is False + assert setup.cache.server(setup.instruction, {"note": note}) is None + assert _http_json(f"{clinic}/api/db")["records"] == [] + + +def test_the_endpoint_refuses_a_request_without_the_token( + clinic: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The child that probes without the token gets 401 and exits nonzero.""" + + setup, reset = _setup(tmp_path, clinic, monkeypatch) + note = "Synthetic follow-up in two weeks" + _authorize(setup, tmp_path, setup.cache.common["url"], note) + probe = ( + "import os, sys, urllib.request, urllib.error\n" + "req = urllib.request.Request(os.environ['OPENADAPT_MCP_URL'], data=b'{}'," + " method='POST', headers={'Authorization': 'Bearer wrong'," + " 'Content-Type': 'application/json'})\n" + "try:\n urllib.request.urlopen(req, timeout=10)\nexcept urllib.error.HTTPError as e:\n" + " sys.exit(0 if e.code == 401 else 3)\n" + "sys.exit(4)\n" + ) + command = ProcessAgent([sys.executable, "-c", probe], timeout_s=60) + task = WrappedTask( + cache=setup.cache, + agent=command, + instruction=setup.instruction, + parameters=setup.parameters, + runs_dir=tmp_path / "runs", + ) + reset() + result = task.call("first", {"note": note}) + # The probe saw 401 and exited 0; it saved nothing, so nothing compiles. + assert command.exit_code == 0 + assert result["verified"] is False + assert _http_json(f"{clinic}/api/db")["records"] == [] + + +def test_command_failed_carries_the_status() -> None: + assert CommandFailed(5).exit_code == 5 + + +def test_the_cli_runs_the_command_and_run_never_starts_an_agent( + clinic: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: Any +) -> None: + """The real ``openadapt wrap ... -- COMMAND`` path, with no person attending. + + Run 1 is guarded, read back and compiled, and stays a draft (only a + person at the terminal confirms checks). ``wrap run`` then refuses the + draft without starting anything. + """ + + from openadapt_flow.approval_mode.approver_roster import ROOT_ENV + from openadapt_flow.teach_authorization_fixture import LocalAuthorizer + from openadapt_flow.teach_scope import origin_of + from openadapt_flow.wrap import cli + + setup, reset = _setup(tmp_path, clinic, monkeypatch) + note = "Synthetic follow-up in two weeks" + key_dir = tmp_path / "keys" + signer = LocalAuthorizer(key_dir, "ci:wrap-command-approver") + monkeypatch.setenv(ROOT_ENV, signer.root) + statement = signer.issue( + tmp_path / "teach-authorization", + { + "task": { + "task_id": setup.cache.task_id(setup.instruction, {"note": note}), + "summary": "Save a note", + }, + "purposes": ["teach", "repair"], + "origins": [str(origin_of(setup.cache.common["url"]))], + "inputs": {"note": {"value": note}}, + "constants": [{"value": "Jane Sample"}, {"value": "MRN P1"}], + "writes": { + "record_kind": "encounter", + "identity": { + "patient_id": {"value": "p1"}, + "type": {"value": "Triage"}, + }, + "fields": {}, + }, + }, + ) + reset() + common = [ + "--task", + str(tmp_path / "task.json"), + "--param", + "note=" + note, + "--key-dir", + str(key_dir), + ] + code = cli.main( + [ + *common, + "--teach-authorization", + str(statement), + "--approver-root", + signer.root, + "--", + sys.executable, + str(AGENT), + ] + ) + out = capsys.readouterr().out + first = json.loads(out.strip().splitlines()[-1]) + # Run 1 was read back (verified), but it is a draft, not a program. + assert code == 0 and first["path"] == "agent", first + assert first["status"] == "draft", first + rows = _http_json(f"{clinic}/api/db")["records"] + assert [r["note"] for r in rows] == [note] + + assert cli.main(["run", *common]) == 2 + assert "DRAFT_NOT_ADMITTED" in capsys.readouterr().err diff --git a/packages/flow/tests/test_wrap_command_cli.py b/packages/flow/tests/test_wrap_command_cli.py new file mode 100644 index 0000000000..9c67b83d1d --- /dev/null +++ b/packages/flow/tests/test_wrap_command_cli.py @@ -0,0 +1,405 @@ +"""``openadapt wrap -- COMMAND`` and ``openadapt wrap run``: argument routing.""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any + +import pytest + +from openadapt_flow.wrap import cli +from openadapt_flow.wrap.process import ENV_TOKEN, ENV_URL, ProcessAgent + + +class _Task: + parameters = ("note",) + + def __init__(self, agent: Any, result: dict[str, Any]) -> None: + self.agent = agent + self.result = result + self.calls: list[tuple[str, dict[str, str]]] = [] + + def call(self, request_id: str, values: dict[str, str]) -> dict[str, Any]: + self.calls.append((request_id, values)) + if isinstance(self.agent, ProcessAgent): + self.agent.exit_code = self.result.pop("_exit", 0) + return self.result + + +def test_the_command_after_the_separator_becomes_the_first_run_agent(monkeypatch): + seen: dict[str, Any] = {} + + def task(args, parser, *, command_agent=None, replay_only=False): + seen.update(agent=command_agent, replay_only=replay_only) + seen["task"] = _Task(command_agent, {"verified": True}) + return seen["task"] + + monkeypatch.setattr(cli, "_task", task) + code = cli.main( + ["--task", "t.json", "--param", "note=x", "--", "my-agent", "--param", "y"] + ) + assert code == 0 + agent = seen["agent"] + assert isinstance(agent, ProcessAgent) + # Everything after -- is the command's, including its own flags. + assert agent.command == ["my-agent", "--param", "y"] + request_id, values = seen["task"].calls[0] + assert values == {"note": "x"} and request_id.startswith("wrap-") + + +def test_the_command_exit_status_is_passed_through(monkeypatch, capsys): + def task(args, parser, *, command_agent=None, replay_only=False): + return _Task(command_agent, {"verified": False, "_exit": 7}) + + monkeypatch.setattr(cli, "_task", task) + assert cli.main(["--task", "t.json", "--param", "note=x", "--", "agent"]) == 7 + + +def test_run_never_starts_an_agent(monkeypatch, capsys): + def task(args, parser, *, command_agent=None, replay_only=False): + assert replay_only and command_agent is None + raise cli.NoAdmittedProgram() + + monkeypatch.setattr(cli, "_task", task) + assert cli.main(["run", "--task", "t.json", "--param", "note=x"]) == 2 + assert "NO_ADMITTED_PROGRAM" in capsys.readouterr().err + + +@pytest.mark.parametrize( + "argv", + [ + ["--task", "t.json", "--"], + ["run", "--task", "t.json", "--", "agent"], + ["--task", "t.json", "--serve", "--", "agent"], + ], +) +def test_misused_separators_are_refused(argv): + with pytest.raises(SystemExit) as exit_info: + cli.main(argv) + assert exit_info.value.code == 2 + + +def test_example_flag_after_the_separator_belongs_to_the_command(monkeypatch): + seen: dict[str, Any] = {} + + def task(args, parser, *, command_agent=None, replay_only=False): + seen["agent"] = command_agent + return _Task(command_agent, {"verified": True}) + + monkeypatch.setattr(cli, "_task", task) + assert ( + cli.main(["--task", "t.json", "--param", "note=x", "--", "a", "--example"]) == 0 + ) + assert seen["agent"].command == ["a", "--example"] + + +def test_process_agent_needs_no_model_key_and_a_command(): + agent = ProcessAgent(["true"]) + assert agent.requires_model_key is False + with pytest.raises(ValueError): + ProcessAgent([]) + + +def test_the_command_gets_the_endpoint_and_the_server_closes_after(tmp_path): + """A real child: it sees the URL and token, and the endpoint stops after.""" + + import sys + import urllib.error + import urllib.request + + from openadapt_flow.integrations.agents.skills import BrowserTools + + out = tmp_path / "env.txt" + script = ( + "import os, pathlib\n" + f"pathlib.Path({str(out)!r}).write_text(" + f"os.environ[{ENV_URL!r}] + '\\n' + str(len(os.environ[{ENV_TOKEN!r}])))\n" + ) + agent = ProcessAgent([sys.executable, "-c", script], timeout_s=60) + tools = BrowserTools(SimpleNamespace()) + assert agent._run_command("Task: x", tools) is None + url, token_length = out.read_text().splitlines() + assert url.startswith("http://127.0.0.1:") and url.endswith("/mcp") + assert int(token_length) >= 32 + assert tools.summary is not None + with pytest.raises((urllib.error.URLError, ConnectionError, OSError)): + urllib.request.urlopen(url, timeout=2) + + +def test_the_command_gets_no_openadapt_settings_or_keys(): + from openadapt_flow.wrap.process import child_environment + + env = child_environment( + { + "PATH": "/bin", + "ANTHROPIC_API_KEY": "the agent's own key", + "OPENADAPT_JIT_KEY_PASSPHRASE": "admission key passphrase", + "OPENADAPT_FLOW_SECRET_PASSWORD": "a sign-in value", + "openadapt_api_key": "a cloud key", + } + ) + assert env == {"PATH": "/bin", "ANTHROPIC_API_KEY": "the agent's own key"} + + +def test_a_real_child_never_sees_the_admission_passphrase(tmp_path, monkeypatch): + import sys + + from openadapt_flow.integrations.agents.skills import BrowserTools + + monkeypatch.setenv("OPENADAPT_JIT_KEY_PASSPHRASE", "admission key passphrase") + out = tmp_path / "seen.txt" + script = ( + "import os, pathlib\n" + f"pathlib.Path({str(out)!r}).write_text(" + "repr(sorted(k for k in os.environ if k.startswith('OPENADAPT_'))))\n" + ) + ProcessAgent([sys.executable, "-c", script], timeout_s=60)._run_command( + "Task: x", BrowserTools(SimpleNamespace()) + ) + assert out.read_text() == repr(sorted([ENV_URL, ENV_TOKEN, "OPENADAPT_TASK"])) + + +def test_run_names_a_draft_that_was_not_admitted(monkeypatch, capsys, tmp_path): + def task(args, parser, *, command_agent=None, replay_only=False): + raise cli.NoAdmittedProgram(tmp_path / "task-dir") + + monkeypatch.setattr(cli, "_task", task) + assert cli.main(["run", "--task", "t.json", "--param", "note=x"]) == 2 + err = capsys.readouterr().err + assert "DRAFT_NOT_ADMITTED" in err and str(tmp_path / "task-dir") in err + + +def test_a_retried_wrapped_run_gets_the_same_request_id(monkeypatch): + ids: list[str] = [] + + def task(args, parser, *, command_agent=None, replay_only=False): + t = _Task(command_agent, {"verified": True}) + t.call = lambda request_id, values: ( + ids.append(request_id) + or { # type: ignore[method-assign] + "verified": True + } + ) + return t + + monkeypatch.setattr(cli, "_task", task) + argv = ["--task", "t.json", "--param", "note=x", "--", "my-agent"] + assert cli.main(argv) == 0 + assert cli.main(argv) == 0 + assert cli.main(["--task", "t.json", "--param", "note=y", "--", "my-agent"]) == 0 + assert ids[0] == ids[1] and ids[0] != ids[2] + assert all(i.startswith("wrap-") for i in ids) + # An explicit --request-id still wins. + assert cli.main(["--task", "t.json", "--request-id", "r1", "--", "my-agent"]) == 0 + assert ids[-1] == "r1" + + +def test_every_credential_the_verifier_reads_is_withheld_from_the_command(tmp_path): + from openadapt_flow.wrap.process import child_environment, verify_env_names + + verify = tmp_path / "verify.yaml" + verify.write_text( + "verifier:\n" + " base_url: ${APP_URL}\n" + " headers: {Authorization: 'Bearer ${APP_TOKEN:-none}'}\n" + " frame:\n" + " database:\n" + " read: {sql_password_env: DB_PASSWORD, dsn_env: [DB_DSN]}\n" + " auth: {basic_env: APP_BASIC}\n" + " api: {secret_env: {token: SOR_API_TOKEN, key: SOR_API_KEY}}\n", + encoding="utf-8", + ) + names = verify_env_names(verify) + assert names == { + "APP_URL", + "APP_TOKEN", + "DB_PASSWORD", + "DB_DSN", + "APP_BASIC", + "SOR_API_TOKEN", + "SOR_API_KEY", + } + env = child_environment( + { + "PATH": "/bin", + "ANTHROPIC_API_KEY": "the agent's own key", + "DB_PASSWORD": "s3cret", + "app_token": "tok", + "APP_BASIC": "u:p", + "DB_DSN": "postgres://x", + "APP_URL": "http://127.0.0.1", + "SOR_API_TOKEN": "sor-token", + "SOR_API_KEY": "sor-key", + }, + names, + ) + assert env == {"PATH": "/bin", "ANTHROPIC_API_KEY": "the agent's own key"} + + +def test_a_real_child_never_sees_a_verifier_credential(tmp_path, monkeypatch): + import sys + + from openadapt_flow.integrations.agents.skills import BrowserTools + + monkeypatch.setenv("DB_PASSWORD", "s3cret") + out = tmp_path / "seen.txt" + script = ( + "import os, pathlib\n" + f"pathlib.Path({str(out)!r}).write_text(repr(os.environ.get('DB_PASSWORD')))\n" + ) + ProcessAgent( + [sys.executable, "-c", script], timeout_s=60, withheld_env={"DB_PASSWORD"} + )._run_command("Task: x", BrowserTools(SimpleNamespace())) + assert out.read_text() == "None" + + +def _wait_gone(pid: int, timeout_s: float = 10.0) -> bool: + import os + import time + + deadline = time.monotonic() + timeout_s + while time.monotonic() < deadline: + try: + os.kill(pid, 0) + except ProcessLookupError: + return True + time.sleep(0.05) + return False + + +def _group_script(pid_file: Any) -> str: + # The command starts a grandchild in its own group and waits forever. + return ( + "import pathlib, subprocess, sys, time\n" + "child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(600)'])\n" + f"pathlib.Path({str(pid_file)!r}).write_text(str(child.pid))\n" + "time.sleep(600)\n" + ) + + +@pytest.mark.skipif(__import__("os").name != "posix", reason="process groups") +def test_the_command_timeout_ends_the_whole_process_group(tmp_path): + import sys + import time + + from openadapt_flow.wrap.process import CommandFailed, _run_group + + pid_file = tmp_path / "grandchild.pid" + started = time.monotonic() + with pytest.raises(CommandFailed): + _run_group([sys.executable, "-c", _group_script(pid_file)], {}, 2.0) + assert time.monotonic() - started < 30 + assert _wait_gone(int(pid_file.read_text())) + + +@pytest.mark.skipif(__import__("os").name != "posix", reason="process groups") +@pytest.mark.parametrize("how", ["SIGTERM", "SIGINT"]) +def test_a_signal_to_openadapt_ends_the_wrapped_command_group(tmp_path, how): + import os + import signal + import subprocess + import sys + import time + + pid_file = tmp_path / "grandchild.pid" + driver = tmp_path / "driver.py" + driver.write_text( + "import sys\n" + "from openadapt_flow.wrap import cli\n" + "from openadapt_flow.wrap.process import _run_group\n" + "with cli._commands_stopped_on_signal(True):\n" + f" _run_group([sys.executable, '-c', {_group_script(pid_file)!r}], {{}}, 600)\n", + encoding="utf-8", + ) + parent = subprocess.Popen( + [sys.executable, str(driver)], env=dict(os.environ), stderr=subprocess.PIPE + ) + deadline = time.monotonic() + 30 + while not pid_file.exists() and time.monotonic() < deadline: + time.sleep(0.05) + grandchild = int(pid_file.read_text()) + parent.send_signal(getattr(signal, how)) + parent.wait(timeout=30) + assert _wait_gone(grandchild) + + +def test_a_deduped_rerun_says_how_to_run_again(monkeypatch, capsys): + def task(args, parser, *, command_agent=None, replay_only=False): + t = _Task(command_agent, {"verified": False}) + t.call = lambda request_id, values: { # type: ignore[method-assign] + "verified": False, + "replayed": True, + "request_id": request_id, + } + return t + + monkeypatch.setattr(cli, "_task", task) + cli.main(["--task", "t.json", "--param", "note=x", "--", "my-agent"]) + err = capsys.readouterr().err + assert "already ran" in err and "pass a new --request-id" in err + # A named request that replays is the caller's choice: no notice. + cli.main(["--task", "t.json", "--request-id", "r1", "--", "my-agent"]) + assert "already ran" not in capsys.readouterr().err + + +def test_an_interrupted_earlier_attempt_never_suggests_a_new_request_id_first( + monkeypatch, capsys +): + def task(args, parser, *, command_agent=None, replay_only=False): + t = _Task(command_agent, {"verified": False}) + t.call = lambda request_id, values: { # type: ignore[method-assign] + "verified": False, + "replayed": True, + "status": "RECONCILIATION_REQUIRED", + "request_id": request_id, + } + return t + + monkeypatch.setattr(cli, "_task", task) + cli.main(["--task", "t.json", "--param", "note=x", "--", "my-agent"]) + err = capsys.readouterr().err + assert "the earlier attempt may have saved" in err + assert "check the record in the app before rerunning" in err + assert "already ran" not in err and "To run it again" not in err + + +@pytest.mark.skipif(__import__("os").name != "posix", reason="process groups") +@pytest.mark.parametrize("how", ["SIGTERM", "SIGINT"]) +def test_a_signal_during_a_browser_tool_call_still_ends_the_command(tmp_path, how): + # The real path: the command runs on serve_while's worker thread, and the + # main thread is inside a browser tool call whose error handling keeps + # the interrupt (serve_while hands every exception back to the caller). + import os + import signal + import subprocess + import sys + import time + + pid_file = tmp_path / "grandchild.pid" + driver = tmp_path / "driver.py" + driver.write_text( + "import sys, time\n" + "from concurrent.futures import Future\n" + "from types import SimpleNamespace\n" + "from openadapt_flow.integrations.agents.skills import BrowserTools\n" + "from openadapt_flow.wrap import cli\n" + "from openadapt_flow.wrap.process import _run_group\n" + "tools = BrowserTools(SimpleNamespace())\n" + "def work():\n" + " tools._jobs.put((lambda: time.sleep(600), Future()))\n" + f" _run_group([sys.executable, '-c', {_group_script(pid_file)!r}], {{}}, 600)\n" + "with cli._commands_stopped_on_signal(True):\n" + " tools.serve_while(work)\n", + encoding="utf-8", + ) + parent = subprocess.Popen( + [sys.executable, str(driver)], env=dict(os.environ), stderr=subprocess.PIPE + ) + deadline = time.monotonic() + 30 + while not pid_file.exists() and time.monotonic() < deadline: + time.sleep(0.05) + time.sleep(0.5) # let the main thread enter the tool call + grandchild = int(pid_file.read_text()) + parent.send_signal(getattr(signal, how)) + assert _wait_gone(grandchild) + parent.wait(timeout=30) diff --git a/tests/test_wrap_command.py b/tests/test_wrap_command.py index d6ea34f58e..7cf985ef51 100644 --- a/tests/test_wrap_command.py +++ b/tests/test_wrap_command.py @@ -56,3 +56,28 @@ def test_the_wrap_extra_brings_the_built_in_agent_sdk_and_the_base_stays_lean(): assert any( d.startswith("anthropic>=") for d in project["optional-dependencies"]["wrap"] ) + + +def test_wrap_keeps_the_separator_before_a_wrapped_command(monkeypatch): + calls = [] + module = types.ModuleType("openadapt_flow.wrap.cli") + module.main = lambda argv: calls.append(argv) or 0 + monkeypatch.setitem(sys.modules, "openadapt_flow.wrap.cli", module) + monkeypatch.setattr(cli, "_python_minor", lambda: cli._SUPPORTED_PYTHON[1]) + arguments = ["--task", "t.json", "--json", "--", "python", "agent.py", "--json"] + monkeypatch.setattr(sys, "argv", ["openadapt", "wrap", *arguments]) + result = CliRunner().invoke(cli.main, ["wrap", *arguments]) + assert result.exit_code == 0 + assert calls == [arguments] + + +def test_wrap_ignores_an_unrelated_process_argv(monkeypatch): + calls = [] + module = types.ModuleType("openadapt_flow.wrap.cli") + module.main = lambda argv: calls.append(argv) or 0 + monkeypatch.setitem(sys.modules, "openadapt_flow.wrap.cli", module) + monkeypatch.setattr(cli, "_python_minor", lambda: cli._SUPPORTED_PYTHON[1]) + monkeypatch.setattr(sys, "argv", ["openadapt", "wrap", "--", "other"]) + result = CliRunner().invoke(cli.main, ["wrap", "--example"]) + assert result.exit_code == 0 + assert calls == [["--example"]]