Skip to content
37 changes: 11 additions & 26 deletions packages/flow/openadapt_flow/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13402,43 +13402,28 @@ def _cmd_serve_execute(args: argparse.Namespace) -> int:
from importlib.util import find_spec

missing = [
name
for name in ("fastapi", "uvicorn", "openadapt_types")
if find_spec(name) is None
n for n in ("fastapi", "uvicorn", "openadapt_types") if find_spec(n) is None
]
if missing:
raise SystemExit(
f"serve-execute needs {', '.join(missing)} — install the "
"execute extra: pip install 'openadapt-flow[execute]'"
)
from openadapt_flow.execute import SELF_SIGNED_NOTICE
from openadapt_flow.execute.app import serve
from openadapt_flow.execute.service import ExecuteService, default_data_dir
from openadapt_flow.execute.app import run_serve_execute

data_dir = Path(args.data_dir) if args.data_dir else default_data_dir()
store = ExecuteService(
data_dir,
token=args.token,
seed_mockmed=bool(args.seed_mockmed),
deployment=getattr(args, "config", None),
)
print("openadapt-flow reference Execute")
print(f" http://{args.host}:{args.port}")
print(f" data dir {data_dir}")
print(f" token {store.token}")
print(" issuer self_signed")
print(f" fingerprint {store.fingerprint}")
print(f" {SELF_SIGNED_NOTICE}")
seeded = ()
if args.seed_mockmed:
print(" seeded MockMed admissions (ok + banner-lie)")
serve(
data_dir,
from openadapt_flow.mockmed.execute_seed import demo_admissions

seeded = demo_admissions()
return run_serve_execute(
data_dir=Path(args.data_dir) if args.data_dir else None,
host=args.host,
port=args.port,
token=store.token,
service=store,
token=args.token,
seed_admissions=seeded,
deployment=getattr(args, "config", None),
)
return 0


def _cmd_serve_reward(args: argparse.Namespace) -> int:
Expand Down
5 changes: 2 additions & 3 deletions packages/flow/openadapt_flow/compile_agent/code_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,8 @@ class LeftTheApp(RuntimeError):


def _shown_url(url: Any) -> str:
"""A page URL without its query string, which can hold session tokens
(OpenEMR's ``token_main``). The path and fragment stay: they say where the
agent is."""
"""A page URL without its query string, which can hold session tokens.
The path and fragment stay: they say where the agent is."""

parts = urlsplit(str(url or ""))
if not parts.scheme:
Expand Down
12 changes: 6 additions & 6 deletions packages/flow/openadapt_flow/ensure_record.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ class AuditRead(BaseModel):
actor_path: str = "agent.who.reference"
entity_path: str = "entity.what.reference"
action_path: str = "action"
#: An empty window proves nothing when the server isn't logging (Medplum
#: answers an empty search, not an error, with ``saveAuditEvents`` off).
#: An empty window proves nothing when the server isn't logging (some
#: servers answer an empty search, not an error, when audit logging is off).
#: With ``heartbeat``, a found record counts only when the verifier's own
#: read of it shows up in the trail; set it where reads by id are logged.
heartbeat: bool = True
Expand All @@ -134,8 +134,8 @@ class ChangeFeed(BaseModel):
#: Read each written resource's ``_history`` for its window versions.
history: bool = True
#: Whether the server returns ``meta.author`` on each version, a second
#: witness to who wrote it. Medplum 5.2 doesn't, so its contract sets
#: false and attribution rests on the audit trail alone.
#: witness to who wrote it. When a server does not populate it, the
#: contract sets false and attribution rests on the audit trail alone.
history_author: bool = True
#: Resource types searched by ``_lastUpdated`` as a second source.
sweep_types: list[str] = Field(default_factory=list)
Expand Down Expand Up @@ -270,8 +270,8 @@ class EnsureContract(BaseModel):
#: a value the list misses still matches, which stops for review instead
#: of missing a duplicate.
void: list[str] = Field(default_factory=list)
#: The audit trail is written a little after the save (Medplum: up to
#: about 0.1 s). The change feed is read until two reads ``settle_s``
#: The audit trail may be written asynchronously after the save.
#: The change feed is read until two reads ``settle_s``
#: apart agree, at most ``stable_reads`` times; a feed still changing
#: then reads as unreadable.
settle_s: float = Field(default=2.0, ge=0, le=120)
Expand Down
48 changes: 43 additions & 5 deletions packages/flow/openadapt_flow/execute/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import hmac
import html
import json
from collections.abc import Iterable
from pathlib import Path
from typing import Any, Optional

Expand All @@ -13,7 +14,7 @@

from openadapt_flow import __version__
from openadapt_flow.execute.dispatch import Runner
from openadapt_flow.execute.models import SelfSignedSealV1
from openadapt_flow.execute.models import AdmittedBundle, SelfSignedSealV1
from openadapt_flow.execute.service import ExecuteService, ExecuteServiceError

_JSON = "application/json"
Expand All @@ -26,7 +27,7 @@ def create_app(
token: str | None = None,
runner: Runner | None = None,
process_inline: bool = True,
seed_mockmed: bool = False,
seed_admissions: Iterable[AdmittedBundle] = (),
service: ExecuteService | None = None,
) -> FastAPI:
"""Build the one-process HTTP+MCP app over a local data directory."""
Expand All @@ -36,7 +37,7 @@ def create_app(
token=token,
runner=runner,
process_inline=process_inline,
seed_mockmed=seed_mockmed,
seed_admissions=seed_admissions,
)
app = FastAPI(
title="OpenAdapt reference Execute",
Expand Down Expand Up @@ -138,7 +139,7 @@ def serve(
host: str = "127.0.0.1",
port: int = 8787,
token: str | None = None,
seed_mockmed: bool = False,
seed_admissions: Iterable[AdmittedBundle] = (),
service: ExecuteService | None = None,
) -> None:
"""Block on uvicorn. Caller prints the banner before this."""
Expand All @@ -148,12 +149,49 @@ def serve(
app = create_app(
data_dir,
token=token,
seed_mockmed=seed_mockmed,
seed_admissions=seed_admissions,
service=service,
)
uvicorn.run(app, host=host, port=port, log_level="info")


def run_serve_execute(
*,
data_dir: Path | None,
host: str,
port: int,
token: str | None,
seed_admissions: Iterable[AdmittedBundle] = (),
deployment: Path | str | None = None,
) -> int:
"""Create the reference Execute store, print its startup banner, and serve."""

from openadapt_flow.execute import SELF_SIGNED_NOTICE
from openadapt_flow.execute.service import default_data_dir

resolved_dir = data_dir if data_dir is not None else default_data_dir()
seeded = tuple(seed_admissions)
store = ExecuteService(
resolved_dir,
token=token,
seed_admissions=seeded,
deployment=deployment,
)
print(
f"openadapt-flow reference Execute\n"
f" http://{host}:{port}\n"
f" data dir {resolved_dir}\n"
f" token {store.token}\n"
f" issuer self_signed\n"
f" fingerprint {store.fingerprint}\n"
f" {SELF_SIGNED_NOTICE}"
)
if seeded:
print(" seeded demo admissions (ok + banner-lie)")
serve(resolved_dir, host=host, port=port, token=store.token, service=store)
return 0


def _require_bearer(store: ExecuteService, authorization: Optional[str]) -> None:
scheme, separator, token = (authorization or "").partition(" ")
if separator != " " or scheme.lower() != "bearer":
Expand Down
59 changes: 30 additions & 29 deletions packages/flow/openadapt_flow/execute/dispatch.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""Dispatch an admitted Execute request to the local openadapt-flow runner.

The customer runner is this process. Synthetic MockMed admissions (the test
and ``--seed-mockmed`` path) never launch a browser. A digest-pinned compiled
bundle is replayed in-process under the standard profile.
The customer runner is this process. Synthetic admissions (used by tests and
demo seeding) never launch a browser. A digest-pinned compiled bundle is
replayed in-process or via the governed deployment config under the standard
profile.
"""

from __future__ import annotations
Expand Down Expand Up @@ -66,10 +67,10 @@ def default_runner(
*,
deployment: Optional[Path] = None,
) -> DispatchResult:
"""Run synthetic MockMed or local governed replay.
"""Run synthetic projection or local governed replay.

``deployment`` is the deployment file (``serve-execute --config``) a
bundle recorded off the web runs under when its admission names none.
bundle runs under when its admission names none.
"""

if admission.synthetic and admission.target_url:
Expand All @@ -78,15 +79,20 @@ def default_runner(
"a synthetic admission can't name a target_url; nothing was executed",
pre_effect=True,
)
if admission.synthetic or not admission.bundle_dir:
return synthetic_mockmed(admission, request)
if admission.synthetic:
return synthetic_runner(admission, request)
if not admission.bundle_dir:
raise DispatchError(
"non-synthetic admission is missing bundle_dir; nothing was executed",
pre_effect=True,
)
return live_replay(admission, request, run_dir, deployment=deployment)


def synthetic_mockmed(
def synthetic_runner(
admission: AdmittedBundle, request: ExecuteRequestV1
) -> DispatchResult:
"""Project the MockMed tutorial outcomes without a browser.
"""Project synthetic tutorial outcomes without a browser.

Honest environment: ``verified`` at independent-system strength.
Banner-lie / ``break_it`` environment: the screen postcondition passes,
Expand All @@ -107,7 +113,7 @@ def synthetic_mockmed(
observed_effect_strength=None,
delivery_uncertain=True,
workflow_digest=request.workflow_digest,
evidence_tag="mockmed-banner-lie",
evidence_tag="synthetic-banner-lie",
)
return _result(
outcome=ExecuteTerminalOutcomeV1.VERIFIED,
Expand All @@ -119,7 +125,7 @@ def synthetic_mockmed(
observed_effect_strength=EffectStrengthV1.INDEPENDENT_SYSTEM_OF_RECORD,
delivery_uncertain=False,
workflow_digest=request.workflow_digest,
evidence_tag="mockmed-verified",
evidence_tag="synthetic-verified",
)


Expand Down Expand Up @@ -161,12 +167,7 @@ def live_replay(

from openadapt_flow.ir import Workflow
from openadapt_flow.jit.lifecycle import DraftNotAdmitted, ensure_runnable
from openadapt_flow.mockmed.fault_server import serve as serve_mockmed
from openadapt_flow.tutorial import (
TUTORIAL_BREAK_ENTRY_QUERY,
TUTORIAL_ENTRY_QUERY,
run_tutorial_workflow,
)
from openadapt_flow.tutorial import run_demo_workflow_replay

try:
# A JIT draft is refused before anything runs. Replayer.run checks
Expand Down Expand Up @@ -196,26 +197,26 @@ def live_replay(
run_dir,
authority=admission.qualification_authority_file,
)
stop: Optional[Callable[[], None]] = None
try:
base_url, _db, stop = serve_mockmed(port=0)
entry_query = (
TUTORIAL_BREAK_ENTRY_QUERY if admission.break_it else TUTORIAL_ENTRY_QUERY
if admission.deployment is not None:
return _surface_replay(
bundle,
workflow,
surface,
Path(admission.deployment),
request,
run_dir,
authority=admission.qualification_authority_file,
)
report = run_tutorial_workflow(
base_url=base_url,
try:
report = run_demo_workflow_replay(
workflow=workflow,
bundle_dir=bundle,
run_dir=run_dir,
headed=False,
entry_query=entry_query,
break_it=admission.break_it,
)
except Exception as exc:
# The replay may have dispatched a write before it failed.
raise DispatchError(f"local replay failed: {exc}", pre_effect=False) from exc
finally:
if stop is not None:
stop()
return project_run_report(report, workflow_digest=request.workflow_digest)


Expand Down
40 changes: 9 additions & 31 deletions packages/flow/openadapt_flow/execute/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,11 @@
from __future__ import annotations

import json
from collections.abc import Iterable
from pathlib import Path

from openadapt_flow.execute.models import AdmittedBundle

# Well-known MockMed / tutorial admissions used by tests and ``--seed-mockmed``.
MOCKMED_QUALIFICATION_ID = "qualification_mockmed01"
MOCKMED_WORKFLOW_VERSION = "workflow_tutorial1"
MOCKMED_WORKFLOW_DIGEST = "sha256:" + "c" * 64
MOCKMED_ENVIRONMENT_OK = "environment_mockmed_ok"
MOCKMED_ENVIRONMENT_LIE = "environment_mockmed_lie"
MOCKMED_EFFECT_STRENGTH = "independent_system_of_record"


class AdmissionError(ValueError):
"""The request does not match an admitted bundle exactly."""
Expand Down Expand Up @@ -78,27 +71,12 @@ def write_admission(data_dir: Path, admission: AdmittedBundle) -> Path:
return path


def seed_mockmed_admissions(data_dir: Path) -> tuple[AdmittedBundle, AdmittedBundle]:
"""Write the synthetic MockMed ok + banner-lie admissions."""
def seed_admissions(
data_dir: Path, admissions: Iterable[AdmittedBundle]
) -> tuple[AdmittedBundle, ...]:
"""Write caller-supplied admissions into the registry directory."""

honest = AdmittedBundle(
qualification_id=MOCKMED_QUALIFICATION_ID,
workflow_version=MOCKMED_WORKFLOW_VERSION,
workflow_digest=MOCKMED_WORKFLOW_DIGEST,
environment_id=MOCKMED_ENVIRONMENT_OK,
minimum_effect_strength=MOCKMED_EFFECT_STRENGTH,
synthetic=True,
break_it=False,
)
lie = AdmittedBundle(
qualification_id=MOCKMED_QUALIFICATION_ID,
workflow_version=MOCKMED_WORKFLOW_VERSION,
workflow_digest=MOCKMED_WORKFLOW_DIGEST,
environment_id=MOCKMED_ENVIRONMENT_LIE,
minimum_effect_strength=MOCKMED_EFFECT_STRENGTH,
synthetic=True,
break_it=True,
)
write_admission(data_dir, honest)
write_admission(data_dir, lie)
return honest, lie
seeded = tuple(admissions)
for admission in seeded:
write_admission(data_dir, admission)
return seeded
Loading
Loading