Metadata-Version: 2.4
Name: damaros
Version: 0.2.2
Summary: Client for Damaros Worlds: practice, Evaluations, and offline checks of signed records. Not a certification, not clinical validation, and not a physician sign-off. Customer outputs are never reused.
Author: Damaros
License-Expression: Apache-2.0
Project-URL: Homepage, https://damaros.ai
Project-URL: Documentation, https://damaros.ai/worlds
Keywords: damaros,simulation,evaluation,agents,robotics,healthcare,benchmark
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: rl
Requires-Dist: gymnasium==1.4.0; extra == "rl"
Provides-Extra: isaac
Requires-Dist: usd-core==26.11; extra == "isaac"
Provides-Extra: test
Requires-Dist: coverage==7.16.0; extra == "test"
Provides-Extra: gymnasium
Requires-Dist: gymnasium==1.4.0; extra == "gymnasium"
Provides-Extra: openenv
Requires-Dist: openenv-core==0.3.0; extra == "openenv"
Requires-Dist: fastmcp==4.1.1; extra == "openenv"
Provides-Extra: verifiers
Requires-Dist: verifiers==0.3.1; extra == "verifiers"
Requires-Dist: datasets==5.1.0; extra == "verifiers"
Provides-Extra: verifiers-v1
Requires-Dist: verifiers==0.4.0; extra == "verifiers-v1"
Provides-Extra: nemo-gym
Requires-Dist: nemo-gym==0.4.0; extra == "nemo-gym"
Requires-Dist: httpx==0.28.1; extra == "nemo-gym"
Provides-Extra: inspect
Requires-Dist: inspect-ai==0.3.280; extra == "inspect"
Provides-Extra: usd
Requires-Dist: usd-core==26.11; extra == "usd"
Provides-Extra: dev
Requires-Dist: coverage==7.16.0; extra == "dev"
Dynamic: license-file

# damaros

Damaros Worlds are simulated worlds, in medicine and the field, where agents, robots and devices (Residents) practice and are measured in Damaros Evaluations, and every result comes back as a signed record anyone can verify. This is the client: it holds no world content, which stays on the server, and it has no dependencies. It is not a certification, not clinical validation, and not a physician sign-off. Customer outputs are never reused.

Nothing runs without a Damaros Worlds account token. Request a license at team@damaros.ai and Damaros sends your token; then:

```bash
pip install damaros
damaros login        # paste the account token at the prompt; it does not echo
damaros first-run                    # a practice result in a few minutes: the three numbers, apart, nothing signed
```

With no token stored, `damaros first-run` says how to request one and contacts no server. To see the ICU world before a license, the recorded demo at https://app.damaros.ai/001/demo runs nothing. The practice result is in simulation: software behavior in a model, not a patient. Documentation: https://damaros.ai/worlds. The rest of this page is the reference.

Paths below that name files outside this release (tools, tests, documents) are in the Damaros source repository and are for a source checkout.

The ICU's seats and Resident hosts from Python, over the hosted server Damaros runs for you or the local servers the `damaros` CLI runs. Nothing is reimplemented: the tools, the clock, the reward and the harm cost are
the TypeScript harness's, read from the server. **No runtime dependencies** (`pip install damaros`); Gymnasium and the lab stacks are optional extras (one lab extra per environment: see below). The `damaros` command also carries `damaros connect` (a Resident to a run, the old `damaros-connect`), `damaros whoami`, `damaros verify` and `damaros pull`. `damaros run` / `evaluate` / `check` hand over to a pulled engine under `~/.damaros/bin` (no Node); if none is pulled they print a permanent `damaros pull` handoff that works from the wheel. A Node `damaros` (or `DAMAROS_CLI`) is optional.

**Engine platforms.** Pulled engines exist only for macOS arm64, Linux x64 and Linux arm64. There is no darwin-x64 or Windows engine. This Python package is OS Independent; only the engine binary is platform-bound.

## Trauma Chain from Python

`damaros.trauma.TraumaClient` (standard library only) is the client for the Trauma Chain Evaluation server: `evaluate(vehicle_file=text, name="my_ugv", version=1, size=10)` plays one Evaluation (asynchronously, with an Idempotency-Key, so a retried job finds its run), `evaluate(..., paired_with="RN-...")` plays the same missions as an earlier one of yours, `verify(result)` checks the signed record on this computer against the server's key history, and `calibrate(kind, name, data)` records a measurement and returns the server's signed receipt (`damaros verify-calibration` checks it). `verify-record.py` in this folder is the same verifier as a single file with no install.

```python
from damaros.trauma import TraumaClient
c = TraumaClient("https://<your server>", token="<your token>")
first = c.evaluate(vehicle_file=open("my_vehicle.yaml").read(), name="my_ugv", version=1, size=10)
second = c.evaluate(vehicle_file=open("my_vehicle_v2.yaml").read(), name="my_ugv", version=2, size=10, paired_with=first["run"])
print(c.verify(first))   # ok, or raises VerifyFailed
print(c.world()["name"], c.world()["version"])   # the world this server plays: id, name, version, numbers_digest
```

The console's reads are the client's reads: `evaluations(machine=None, limit=None, after=None)` (newest first, paged by the server's `next`; a finished vehicle-file row says `litter`: `measured` or `design_mount`), `all_evaluations()`, `machines()`, `machine(name)` and `compare(a, b)` (a refusal, 409 `not_comparable`, carries the server's sentence). Nothing in them is ranked or summed.

`check_file(text)` asks the server what it would do with a vehicle file without playing or counting anything: the digest, what the machine is simulated as, what is modelled and not, and `litter`, which says whether the litter's transfer is the modelled mount or your own measured transmissibility, and whether a Field Check log digest accompanies it (`digest_given`; the server has not seen the log and cannot check the digest). `damaros check-ride run.mcap --vehicle <floor sensor> --seat <litter sensor> --into my_vehicle.yaml` writes such a file from a ride log on your computer. A CI job that should not play a machine whose litter is not measured calls `c.check_file(text, require_log_digest=True)`, which raises before anything is played.

## Train a policy

`damaros.trauma_env.TraumaChainEnv` is a Gymnasium environment for World 002: `reset(seed="train:17")`, then `step([share_of_speed_cap])` until the mission ends. The client finds the engine by itself, in this order: `DAMAROS_TRAUMA_ENV` (a command line), a source checkout's `worlds/002/src/env/server.ts`, the engine from `damaros pull 002` under `$DAMAROS_HOME/bin` (or `~/.damaros/bin`), then the Node `damaros` command on PATH (`damaros trauma-env`). If none is found the error names what it looked for and which to use.

```bash
PYTHONPATH=clients/python python3 my_training_script.py
```

With numpy installed `reset` and `step` return float32 arrays; without it, lists of numbers. The observation, the reward and what it does not mean, the seeds, and the baselines are in the release README, section "Train a policy (reset and step)".

### The same envs on the server

`damaros.hosted_env.make_vec(world, n)` runs the envs on the server instead of this machine, behind the same shape as the local ones (`reset`, `step`, the Gymnasium vector convention: an env whose episode ends is reset at once, the finished episode's last observation and info in `info["final_observation"]` and `info["final_info"]`). Nothing needs Node or a checkout, and every env-step that runs is one compute unit on your account's ledger (`vec.units()`); it is never a tested version and never a score.

```python
from damaros.hosted_env import make_vec
vec = make_vec("trauma", 8, action_repeat=5)        # eight Trauma Chain envs on the public seeds train:0 to train:7
obs = vec.reset()
obs, rewards, terminated, truncated, infos = vec.step([1.0] * 8)
icu = make_vec("icu", 4)                            # Intensive Care: the action is the physician's tool call, {"name": "get_vitals"}; {"name": "end_case"} hands the patient back
```

The server holds the envs and refuses any seed that is not `train:<n>` or `val:<n>`: a Damaros Evaluation is drawn on the server from a key you do not hold. The same seeds and the same actions give the same bytes. `HostedTraumaVecEnv.from_plan(plan)` plays the plan `POST /v1/train/from-failures` returns: a public sibling seed, of the same scenario, ground family and event kinds, for each mission that failed in one of your Evaluations.

### The daily seed

`python3 -m damaros.daily` (and `damaros daily`) plays the guideline arm and the reference arms on the day's public seeds, `val:<n>`, worked out from the UTC day with no network, and prints what each earns; `python3 -m damaros.daily --world trauma` plays Trauma Chain. `damaros.daily.hosted_vec("trauma", 2)` plays the same seeds on the hosted lane. No customer is ranked, and nothing here is a Damaros Evaluation.

## Your first hour

Damaros hands you two values: the server's address and your account token, and the client itself: the `clients/python` directory of this repository, sent with your account (no package index carries it). Everything below runs against
them, and nothing else is needed: no key of ours, no model, no GPU.

```bash
export DAMAROS_URL=https://app.damaros.ai          # the address Damaros gave you
read -rs DAMAROS_TOKEN && export DAMAROS_TOKEN      # paste the account token: it is not echoed and not kept in your history
```

Every block marked below is a whole program, run as it is: a shell block in your shell, from the directory that holds `clients/python`; a Python block saved to a file and run with the Python you installed
into (or pasted into `python3 -`). Under each is what it prints; `…` stands for what differs from run to run. `test/first-hour.test.ts` runs every one of them, unedited, against a hosted server booted the way
the operator boots it.

**Steps 5 and 6 spend two of the test versions your licence gives you for the quarter**: an evaluation run of a first version, then a paired second version. Steps 1 to 4 spend none, and a sample run never does.

Two things to know before you start. An evaluation run is **scored on the server by replaying every patient**, which takes minutes on a full panel: `run.analysis()` waits for it and says on stderr every half minute that it is,
so a quiet terminal is not a hung one. Opening a run waits first while the server draws its panel, and says on stderr at every poll how many seconds it has been drawing (the server's own `preparing_s`). The draw alone, measured on one core of a 32 vCPU cloud machine: 7.3 s for a sample run's 21 cases, 108.5 s for an evaluation run's 360. Your run opens when its draw is written, and a busy server takes longer. And a version you test for the first time uses one of your licence's **test versions** for the quarter (step 2 shows how many you have; steps 5 and 6 use two, and step 8 a third).

A slow first connect is retried for you. The Python and JavaScript clients, `damaros connect` and the `damaros` CLI (and the CI action, which calls it) each wait a few seconds for a connection and try again up to three times after a short, jittered pause, and never send a request twice; the long wait above applies only after the connection is made. If a call cannot connect at all, `damaros doctor --server $DAMAROS_URL` (with DAMAROS_TOKEN set) prints one line each for the connect time, the server's `/healthz` (status, world hash, release) and whether your token is accepted, and exits 1 if any of them fails.

If `run.analysis()` or any call fails with `could not verify the certificate`, the address is right and the Python on this machine has no root certificates to check it against (python.org Python on a Mac): run `Install Certificates.command` in your Python folder under Applications, or `pip install certifi` and `export SSL_CERT_FILE=$(python3 -c 'import certifi; print(certifi.where())')`.

Five words, used the same way throughout. A **panel** is the set of patients a run plays. A **cluster** is a kind of ICU case (sepsis, a look-alike that is not sepsis, and so on); a **seed** is one draw of a cluster, one patient.
**pass^k** counts a case as right only if the agent gets it right on all *k* seeds of its cluster. A **lane** is a hosted training slot: a train run holds one while it is open, and your licence says how many you have.

**1. Install the client**, into the Python environment you will use (a fresh virtual environment is best). It carries `damaros.connect`, the WebSocket that connects a robot or other Resident host to a run (step 8), and imports it only when you play a host. (Its wait-only physician is a demo that measures nothing; step 8 uses the server's guideline physician instead.) In a source checkout the line is `pip install clients/python`.

```bash first-hour
pip install clients/python
```

```text
Successfully installed damaros-0.2.2
```

**2. Your token: who you are and what your licence allows** (`GET /v1/usage`).

```python first-hour
from damaros.server import Server

server = Server.from_env()                 # DAMAROS_URL and DAMAROS_TOKEN
u = server.usage()
lic = u["licence"]                         # None on an account without a licence
print(f"account {u['account']['id']} ({u['account']['name']})")
status = u["licence_status"]               # None with no licence; else status in_force, grace, ended or not_started, and the sentence to show
if status:
    print(status["sentence"])
if lic is None:
    print("no licence on this account: ask team@damaros.ai for one; the sample run (step 3) works without it")
else:
    print(f"licence {lic['world']}@{lic['world_version']}, {lic['starts']} to {lic['ends']}")
    print(f"{u['quarter']}: {u['evaluation_versions_used']} of {u['evaluation_versions_allowed']} agent versions tested; {u['train_lanes_open']} of {u['lanes_hosted']} hosted training lanes open")
```

```text
account AC-… (…)
In force from … to … (UTC days).
licence intensive-care-unit@…, … to …
…: 0 of … agent versions tested; 0 of … hosted training lanes open
```

**3. A sample patient.** A sample run is free and needs no licence. Your agent sits in the physician's seat over the server's MCP door with the run's own token; here a five-call scripted policy stands in
for it. Sample and train show each patient's outcome when it is handed back: `died` (1 or 0, the drawn outcome), the chance of death, the harms, the reward and the harm cost (two fields, never added), and the credit,
what each acting call did to the chance of death. `credit` lists the acting calls (orders); `examine` and `wait` are not acting calls, and an effect of `+0.000` means that call changed nothing for this patient, as it does for one whose chance of death is already 1.
`strict=True` makes a refused call (a misspelt tool, a bad argument) raise `ToolRefused` instead of returning `ok: false`; a refused call still costs the patient a simulated minute, so a script should not ignore one.

```python first-hour
from damaros.server import Server

POLICY = [("examine", {}), ("order_lab", {"test": "lactate", "priority": "stat"}), ("order_lab", {"test": "blood_culture_x2", "priority": "stat"}),
          ("order_med", {"drug": "cefepime", "priority": "stat"}), ("wait", {"minutes": 60})]

server = Server.from_env()
run = server.open_run("sample")            # waits while the server draws the panel, saying the seconds
seat = run.seat()                          # MCP, with the run's token
patient = seat.next_case()
print(f"{run.id}: patient {patient['case']}")
for tool, args in POLICY:
    if patient.get("ended") or seat.call(tool, args, strict=True).get("ended"):   # the patient died or left the unit (one can be gone as the chart opens: `ended` on the next_case answer): the rest of the script is for a patient who is not there
        break
out = seat.end_case()                      # hand the patient back: the server follows them to the horizon
print(f"died {out['died']}, p_death {out['p_death']}, harms {out['harms']}, reward {out['reward']}, cost {out['cost']}")
print("credit: " + ", ".join(f"{c['tool']} {c['effect']['p_death']:+.3f}" for c in out["credit"]))
run.stop()                                 # one patient is enough; the run is scored on what it played
```

```text
RN-…: patient 1 of …
died …, p_death …, harms …, reward …, cost {'severe': …, 'other': …, 'by_kind': {…}}
credit: …
```

**4. A training session.** A train run holds one of your licence's hosted lanes while it is open (`episodes` sets its size, 48 to 400: a panel always holds a fixed set of control cases and one patient of every cluster, so a smaller one cannot cover them, and the server's refusal for fewer names the least). Play every patient; after a patient is handed back,
`branch` plays that patient again from a minute with something else done, on the same case and seed, so only what you changed differs. The **trunk** is the run as you played it; the **branch** is the same patient with your change.
Every field of `difference` is the branch minus the trunk (`p_death` the chance of death, `harms` the number of harms, `severe` whether a severe harm happened as 1 or 0, `cost_usd` the harm cost in dollars), so a negative `p_death` means the change helped. Asking for a patient after the last one closes the run.

```python first-hour
from damaros.server import Server

POLICY = [("examine", {}), ("order_lab", {"test": "lactate", "priority": "stat"}), ("order_lab", {"test": "blood_culture_x2", "priority": "stat"}),
          ("order_med", {"drug": "cefepime", "priority": "stat"}), ("wait", {"minutes": 60})]

server = Server.from_env()
run = server.open_run("train", episodes=48)
seat = run.seat()
rewards = []
while (patient := seat.next_case()) is not None:
    for tool, args in POLICY:
        if patient.get("ended") or seat.call(tool, args, strict=True).get("ended"):   # the patient died or left the unit (one can be gone as the chart opens: `ended` on the next_case answer): the rest of the script is for a patient who is not there
            break
    rewards.append(seat.end_case()["reward"])
    if len(rewards) == 1:                  # the first patient again from minute 0, with meropenem ordered as well
        b = seat.branch(0, [{"name": "order_med", "args": {"drug": "meropenem", "priority": "stat"}}])
        print(f"branch at minute {b['minute']}: p_death {b['trunk']['p_death']} -> {b['branch']['p_death']}, difference {b['difference']}")
print(f"{run.id}: {len(rewards)} patients, mean reward {sum(rewards) / len(rewards):.3f}; the run is {run.status()['status']}")
```

```text
branch at minute 0: p_death … -> …, difference {'p_death': …, 'harms': …, 'severe': …, 'cost_usd': …}
RN-…: … patients, mean reward …; the run is …
```

**5. An evaluation run.** An evaluation run measures a registered version of your agent: register `name@version` first (the server refuses an unregistered one and says how). The server draws a fresh panel for
the run and holds it; the agent plays blind (`end_case` says only how many patients remain), and you read the run analysis once the server has scored it: the three default rules (expected deaths against
the guideline policy, harms per case, cases right on every seed) and the verdict. You have sent no thresholds, so the run is read against Damaros's shipped defaults and the verdict says so in its label (a
verdict's "your limit" is the default's until you send your own file: `POST /v1/runs/:id/check`). The third rule is not measured on a single seed, and its sentence says why. This step uses one of your licence's test versions.

```python first-hour
from damaros.server import Server

POLICY = [("examine", {}), ("order_lab", {"test": "lactate", "priority": "stat"}), ("order_lab", {"test": "blood_culture_x2", "priority": "stat"}),
          ("order_med", {"drug": "cefepime", "priority": "stat"}), ("wait", {"minutes": 60})]

server = Server.from_env()
server.register("first-hour@1", "the five-call scripted policy in clients/python/README.md")
run = server.open_run("evaluation", agent="first-hour@1")
seat = run.seat()
while (patient := seat.next_case()) is not None:
    for tool, args in POLICY:
        if patient.get("ended") or seat.call(tool, args, strict=True).get("ended"):   # the patient died or left the unit (one can be gone as the chart opens: `ended` on the next_case answer): the rest of the script is for a patient who is not there
            break
    seat.end_case()                        # {"ok": true, "remaining": n}: nothing about the patient
analysis = run.analysis()                  # GET /v1/runs/:id/analysis, once the server has scored the run
for rule in analysis["verdict"]["rules"]:
    if rule["id"] in ("max_deaths_vs_guideline", "max_harms_per_case", "min_pass_hat_k"):
        print(rule["sentence"])
print(f"thresholds: {analysis['verdict']['thresholds']['label']}")
print(f"{run.id}: {analysis['verdict']['sentence']}")
```

```text
expected deaths …× the guideline policy's (your limit: …)
… harms per case (your limit: … per case)
cases right on every seed (pass^k): not measured (…)
thresholds: shipped defaults, unsourced: design numbers, not a standard
RN-…: …
```

**6. Two versions, paired.** A second version is tested on the first run's panel and seed (`pair=`), so every difference between the two is what the agents did. `compare` takes them case for
case: wins, losses and ties by rank, and each paired difference with its 95% interval. It names no case. A case's rank runs from 1 (best) to 5 (death), so "better" counts cases whose rank improved; expected deaths is
the average chance of death, so the two can disagree, and the interval says whether a difference is more than the draw. Version 2 is a new version, so this step uses a second test version.
`pair="previous"` names the run for you: the version is played on the same patients as the latest complete evaluation of another version of the same agent, and `run.paired_with` says which (a first version has none and is opened on its own patients). Pairing a version with its own earlier run is allowed too: its comparison is labelled `noise`, keeps its intervals and calls no case flipped, because it shows how far one version moves between runs.

```python first-hour
from damaros.server import Server

POLICY = [("examine", {}), ("order_lab", {"test": "lactate", "priority": "stat"}), ("order_lab", {"test": "blood_culture_x2", "priority": "stat"}), ("wait", {"minutes": 60})]  # no antibiotic

server = Server.from_env()
first = server.latest_run("first-hour@1")   # the step 5 run, once it is scored; else the sentence that says what to play first
server.register("first-hour@2", "version 1 without the antibiotic")
run = server.open_run("evaluation", agent="first-hour@2", pair=first.id)
seat = run.seat()
while (patient := seat.next_case()) is not None:
    for tool, args in POLICY:
        if patient.get("ended") or seat.call(tool, args, strict=True).get("ended"):   # the patient died or left the unit (one can be gone as the chart opens: `ended` on the next_case answer): the rest of the script is for a patient who is not there
            break
    seat.end_case()
run.analysis()                             # waits until the server has scored it
c = server.compare(first.id, run.id)
d = c["differences"]["expected_deaths_per_100"]
print(f"{c['b']['agent']} against {c['a']['agent']} on {c['cases']} paired cases: {c['ranks']['wins']} better, {c['ranks']['losses']} worse, {c['ranks']['ties']} tied by rank")
print(f"expected deaths per 100: {d['a']} -> {d['b']} ({d['diff']:+}, 95% {d['lo']} to {d['hi']})")
```

```text
first-hour@2 against first-hour@1 on … paired cases: … better, … worse, … tied by rank
expected deaths per 100: … -> … (…, 95% … to …)
```

**7. Verify a run.** The server replays the run from its record (`POST /v1/runs/:id/verify`): the hash chain, each evaluation case against the commitment the record holds, and the score recomputed
against the one recorded.

```python first-hour
from damaros.server import Server

server = Server.from_env()
first = server.latest_run("first-hour@1")
v = first.verify()                          # waits while the run is still being scored
print(f"{first.id}: verified {v['verified']}; chain of {v['chain']['length']} events; cases match {v['cases_match']}; score hash the same {v['score_hash']['same']}")
```

```text
RN-…: verified True; chain of … events; cases match True; score hash the same True
```

**8. A robot release check.** A robot or any other Resident host takes the same path in three calls: open an evaluation run whose Residents your host plays, play the shift, read the run analysis. The run is a measurement on the Damaros
Evaluation cases, scored on the server, so it uses a test version like step 5 (a robot is registered as `name@version` too), and the analysis is private to your account. **The server plays the physician**: `open_robot_evaluation_run` opens the run
with `physician="guideline"`, so the guideline policy takes each patient, places the orders it would place and hands them back, the same for every Resident, and what varies between two runs is your robot. (The run says `physician: "guideline"`, and its
MCP, FHIR and HL7 doors refuse your calls: a second hand on the seat would make the measurement yours to steer. The guideline's care sets the floor of what is measured; it is not a claim that the guideline is a good physician. `physician="mine"` leaves the seat to
your own agent over `run.seat()`, and then nothing keeps the physician the same between runs.) `play_host` connects the host to the run's socket and answers the server's question once a simulated minute until the shift ends.
A host is a `damaros.ResidentHost` (here `damaros.host_stub.StubNurse`, the reference host, with a spec for a robot that can `transport`: no model, no GPU) or a `damaros.connect` policy (`residents` and `infer(scene) -> {"actions": [...]}`).
How long your host takes to answer in real time changes no result. The three numbers come first, the robot section after them: what it did (deliveries, each harm kind, each contact band) with its line, `supporting evidence, not certification`:
the numbers describe software in a model, and nothing in the analysis says a robot is safe or ready.

```python first-hour
from damaros.host_stub import StubNurse
from damaros.server import Server

ROBOT = {"id": "robot-1", "seat": "porter", "kind": "robot", "capabilities": ["transport"], "bays": "all", "fallback": "world", "timeout_min": 25}

server = Server.from_env()
run = server.open_robot_evaluation_run("first-hour-robot@1", "the stub robot host in clients/python/README.md")   # registers the version, opens the run; the server plays the physician
end = run.play_host(StubNurse(ROBOT))                                  # connects the host and plays every case; raises HostStopped if the host goes mid-shift
print(f"{run.id}: the shift is {end['status']} at minute {end['minute']}")
analysis = run.analysis()                                              # waits while the server scores the run
numbers = analysis["score"]["numbers"]
for name, n in (("performance", numbers["performance"]["expected_deaths_per_100"]), ("safety", numbers["safety"]["severe_harm_cases_per_100"]), ("cost", numbers["cost"]["care_usd_per_case"])):
    print(f"{name}: {n['value']} {n['unit']} (95% {n['lo']} to {n['hi']})")
robot = analysis["robot"]
d = robot["deliveries"]
print(f"{', '.join(robot['residents'])}: {d['done']} of {d['offered']} deliveries done, {d['on_time']} on time, {d['late']} late, {d['wrong_location']} in the wrong place; {robot['resident_minutes']} Resident minutes")
print(f"harms by the robot: {sum(k['count'] for k in robot['harm_kinds'])} across {len(robot['harm_kinds'])} kinds; contact: " + ", ".join(f"{b['count']} {b['band']}" for b in robot["contact_bands"]["bands"]))
print(robot["line"])
print(f"thresholds: {analysis['verdict']['thresholds']['label']}")
```

```text
RN-…: the shift is complete at minute …
performance: … expected deaths per 100 cases (95% … to …)
safety: … cases with a severe harm per 100 (95% … to …)
cost: … care USD per case (95% … to …)
robot-1: … of … deliveries done, … on time, … late, … in the wrong place; … Resident minutes
harms by the robot: … across 7 kinds; contact: … light, … moderate, … heavy, … severe
supporting evidence, not certification
thresholds: shipped defaults, unsourced: design numbers, not a standard
```

Your own host replaces `StubNurse(ROBOT)` and nothing else changes. If you open the run with `physician="mine"`, the seat is yours over `run.seat()` from another thread or process (the host is asked before each of its calls); `play_host`'s own physician there is a wait-only demo that
places no order and **measures nothing**, for seeing a host connect and never for a result you quote. If the host goes (it closes the socket, or does not answer a scene in time), the server stops the run and `play_host`
raises `HostStopped`, which names the minute the run was stopped at: that run is over and is scored on what it played (a partial shift is not a pass), so open a new one. `server.run(id).status()` carries `host` (`waiting` or `connected`, while the run is open) and `host_lost`.
From a terminal, the same release check (the server plays the guideline physician unless you pass `--physician mine`) is `damaros check --server https://app.damaros.ai --agent name@version --residents remote -- <host command...>` (see "A Resident host").

That is the whole path. A failure on it ends in one sentence from the server that says what to do next: a missing or refused token, a licence not in force, an unregistered version, a run still
being drawn or scored, two runs that were not paired, a robot host that went before its shift ended.

**If a call times out.** A call that gets no answer in `seat.timeout` seconds (120 by default) raises `CallTimedOut` (a tool call, `seat.fhir` and `seat.hl7` alike), which says the run is still open and the call may have landed; it is not "could not reach the server", which is a different message for a different fault. Nothing is lost on the server: read where the run stands, free of simulated time, with `seat.session()` (`GET /v1/session` with the run's token), then carry on.

```python
from damaros.server import CallTimedOut

try:
    patient = seat.next_case()
except CallTimedOut:
    where = seat.session()      # {"case": 3, "of": 16, "patient_in_hand": True, "minute": 0, "since_last": [...], "call_in_flight": False, "next": "..."}
    patient = seat.next_case()  # if the timed-out next_case had landed, this returns {"recovered": True, "case": "3 of 16", "t": 0, ...} and the chart is get_chart
```

The client does most of this for you. Every call on the seat is numbered (`seq`) and `open_run` sends an `Idempotency-Key`; a call or an open that gets no answer is sent once more under the same number or key, and the server answers it from what it recorded if the first one landed, so an order is never placed twice and a retried open is the run the first one opened (with a token of its own; nothing is counted twice). `CallTimedOut` is what you see when the retry gets no answer either.

A patient in hand after a timed-out `next_case` is not an error: `next_case` reads `/v1/session` and returns where the patient stands. `since_last` is what reached the physician with the last recorded call, so an answer that was lost can be read again.

### Without our client

The MCP door is JSON-RPC over HTTP; any MCP client that can send a bearer token can sit in the seat (`claude mcp add --transport http damaros <mcp url> --header "Authorization: Bearer <run token>"`).
The REST form of the same door is `POST /v1/session/next_case`, `/v1/session/call` (`{"tool": ..., "args": {...}, "seq": n}`) and `/v1/session/end_case`, with the same run token. Two tokens, two jobs: the **account token** (`DAMAROS_TOKEN`) opens and reads runs
(`/v1/runs...`); the **run token** that `POST /v1/runs` returns once, with the run, plays the patients (`/mcp`, `/v1/session...`, `/fhir`, `/hl7`) and ends with the run.

Here is a whole run with the standard library alone: open a sample run, number every call (`_meta` `damaros/seq`), take each patient, read the chart, order a lab and a drug, let an hour pass, hand the patient back, and read the verdict when the last patient is back.
A call carries `params._meta["damaros/seq"]`, one more than the last (a new run starts at `last_seq` 0, read from `GET /v1/session`). Send a call again under the same number when no answer came and the server answers it from what it recorded if the first landed, so an order is never placed twice;
a call with no `_meta` is played as it always was, and a retry then could play it twice. The panel is over when `next_case` answers `{"done": true}`; the server then scores the run, and the verdict is in `GET /v1/runs/:id/analysis` (a `409` while it scores).

```python first-hour
import json, os, socket, time, urllib.error, urllib.request

def call(url, token, body=None, method="POST"):
    req = urllib.request.Request(url, data=None if body is None else json.dumps(body).encode(), method=method, headers={"authorization": f"Bearer {token}", "content-type": "application/json"})
    for attempt in (1, 2):
        try:
            with urllib.request.urlopen(req, timeout=120) as res:
                return json.loads(res.read() or "null")
        except urllib.error.HTTPError as e:                 # the server's refusal is one sentence that says what to do next
            raise SystemExit(f"{e.code}: {json.loads(e.read()).get('error')}")
        except (TimeoutError, socket.timeout):              # no answer: the same body again, with the same seq, so the call is never played twice
            if attempt == 2:
                raise

base, account = os.environ["DAMAROS_URL"], os.environ["DAMAROS_TOKEN"]
opened = call(f"{base}/v1/runs", account, {"kind": "sample"})          # the run, its MCP address and its own token (shown once)
run, mcp, token = opened["run"]["id"], opened["mcp"]["url"], opened["token"]
while call(f"{base}/v1/runs/{run}", account, method="GET")["run"]["status"] == "preparing":
    time.sleep(2)

ids = iter(range(1, 10**9))
rpc = lambda method, params: call(mcp, token, {"jsonrpc": "2.0", "id": next(ids), "method": method, "params": params})["result"]
seq = call(f"{base}/v1/session", token, method="GET")["last_seq"]      # 0 on a new run; a client that restarts carries on from here

def tool(name, args=None):
    global seq
    seq += 1
    result = rpc("tools/call", {"name": name, "arguments": args or {}, "_meta": {"damaros/seq": seq}})
    body = json.loads(result["content"][0]["text"])
    if result.get("isError"):                                         # a refused call: the tool's own sentence
        raise SystemExit(f"{name}: {body.get('error')}")
    return body

rpc("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "curl-like", "version": "1"}})
print(f"{run}: {len(rpc('tools/list', {})['tools'])} tools")
played, shown = 0, False
while not (patient := tool("next_case")).get("done"):                  # {"case": "1 of 21", ...}, or {"done": true} after the last patient
    ended = patient.get("ended")                                       # the patient died or left the unit as the chart opened
    if not ended:
        chart = tool("get_chart")                                      # one look costs the minute it costs
        if not shown:
            print(f"chart fields: {', '.join(sorted(chart))}")
            shown = True
    for name, args in (("order_lab", {"test": "lactate", "priority": "stat"}), ("order_med", {"drug": "cefepime", "priority": "stat"}), ("wait", {"minutes": 60})):
        if ended:
            break
        ended = tool(name, args).get("ended")
    tool("end_case")                                                   # hand the patient back; a sample run answers with how it ended
    played += 1
while call(f"{base}/v1/runs/{run}", account, method="GET")["run"]["status"] in ("open", "scoring"):
    time.sleep(2)                                                      # the server replays every case to score the run
analysis = call(f"{base}/v1/runs/{run}/analysis", account, method="GET")["analysis"]
print(f"{run}: {played} patients played; {analysis['verdict']['sentence']}")
```

```text
RN-…: 28 tools
chart fields: …
RN-…: … patients played; …
```

The 28 tools are the 25 physician tools plus the three control tools `next_case`, `end_case` and `branch`.

### Your lab stack, on a hosted run

Each adapter takes `server=` (the address) and plays the run whose token is `run_token=`, or `DAMAROS_RUN_TOKEN` in the environment where the adapter is built from a config (so the config never holds
the token): each reset, rollout, session or sample is the run's next patient, and the run's panel decides the patients. Install one lab extra per environment (below), then each block opens a run, plays one
patient through the adapter with a scripted policy in the model's place (two orders, then waits to the horizon: a wait stops at every page and alarm, so that can take a few hundred), and stops
the run. Your model goes where the policy is.

```python first-hour openenv
from damaros.adapters.openenv import IcuEnvironment, ToolCall
from damaros.server import Server

server = Server.from_env()
run = server.open_run("train", episodes=48)
env = IcuEnvironment(server=server.base, run_token=run.token)
obs = env.reset()
for name, args in [("order_lab", {"test": "blood_culture_x2", "priority": "stat"}), ("order_med", {"drug": "cefepime", "priority": "stat"})] + [("wait", {"minutes": 240})] * 500:
    obs = env.step(ToolCall(name=name, arguments=args))
    if obs.done:
        break
print(f"openenv on {run.id}: done {obs.done}, reward {obs.reward}, cost {obs.cost}")
run.stop()
```

```text
openenv on RN-…: done True, reward …, cost {'severe': …
```

```python first-hour openenv_mcp
from openenv.core.env_server.mcp_types import CallToolAction, ListToolsAction
from damaros.adapters.openenv_mcp import IcuMCPEnvironment
from damaros.server import Server

server = Server.from_env()
run = server.open_run("train", episodes=48)
env = IcuMCPEnvironment(server=server.base, run_token=run.token)
env.reset()
tools = env.step(ListToolsAction()).tools
for name, args in [("order_lab", {"test": "blood_culture_x2", "priority": "stat"}), ("order_med", {"drug": "cefepime", "priority": "stat"})] + [("wait", {"minutes": 240})] * 500:
    obs = env.step(CallToolAction(tool_name=name, arguments=args))
    if obs.done:
        break
print(f"openenv_mcp on {run.id}: {len(tools)} tools; done {obs.done}, reward {obs.reward}, cost {obs.metadata['cost']}")
run.stop()
```

```text
openenv_mcp on RN-…: 25 tools; done True, reward …, cost {'severe': …
```

```python first-hour verifiers
import asyncio, json
from damaros.adapters.verifiers import IcuEnv
from damaros.server import Server

server = Server.from_env()
run = server.open_run("train", episodes=48)
env = IcuEnv(seeds=[0], server=server.base, run_token=run.token)    # one rollout: the run's next patient
state = asyncio.run(env.setup_state({"info": {"seed": "0"}}))
for i, (name, args) in enumerate([("order_lab", {"test": "blood_culture_x2", "priority": "stat"}), ("order_med", {"drug": "cefepime", "priority": "stat"})] + [("wait", {"minutes": 240})] * 500):
    reply = {"role": "assistant", "content": "", "tool_calls": [{"id": f"c{i}", "type": "function", "function": {"name": name, "arguments": json.dumps(args)}}]}
    asyncio.run(env.env_response([reply], state))                      # what vf.MultiTurnEnv does with each model turn
    if state["server_reward"] is not None:
        break
print(f"verifiers on {run.id}: reward {state['server_reward']}, cost {state['cost']}")
run.stop()
```

```text
verifiers on RN-…: reward …, cost {'severe': …
```

```python first-hour verifiers_v1
import asyncio, os
from damaros.adapters.__main__ import scripted_agents
from damaros.adapters.verifiers_v1 import IcuEnv, IcuEnvConfig
from damaros.server import Server

server = Server.from_env()
run = server.open_run("train", episodes=48)
os.environ["DAMAROS_RUN_TOKEN"] = run.token                            # the config names the server, never the token
env = IcuEnv(IcuEnvConfig(taskset={"id": "damaros_verifiers", "seeds": ["0"], "server": server.base}, max_turns=600))
(task,) = list(env.taskset)
agents, trace = scripted_agents([("order_lab", {"test": "blood_culture_x2", "priority": "stat"}), ("order_med", {"drug": "cefepime", "priority": "stat"})] + [("wait", {"minutes": 240})] * 500)
asyncio.run(env.run(task, agents))                                       # your vf player in place of scripted_agents
print(f"verifiers_v1 on {run.id}: damaros_reward {trace.rewards['damaros_reward']}, damaros_cost_severe {trace.metrics['damaros_cost_severe']}")
run.stop()
```

```text
verifiers_v1 on RN-…: damaros_reward …, damaros_cost_severe …
```

```python first-hour nemo_gym
import os
from unittest.mock import MagicMock
from fastapi.testclient import TestClient
from nemo_gym.server_utils import ServerClient
from damaros.adapters.nemo_gym import IcuResourcesServer, IcuResourcesServerConfig
from damaros.server import Server

server = Server.from_env()
run = server.open_run("train", episodes=48)
os.environ["DAMAROS_RUN_TOKEN"] = run.token                            # the config names the server, never the token
config = IcuResourcesServerConfig(host="127.0.0.1", port=8080, entrypoint="", name="damaros", server=server.base)
# Called in process with FastAPI's TestClient here; a NeMo Gym rollout calls the same routes. Its head-server link is not used by this server.
http = TestClient(IcuResourcesServer(config=config, server_client=MagicMock(spec=ServerClient)).setup_webserver())
http.post("/seed_session", json={})                                      # the run's next patient
for name, args in [("order_lab", {"test": "blood_culture_x2", "priority": "stat"}), ("order_med", {"drug": "cefepime", "priority": "stat"})] + [("wait", {"minutes": 240})] * 500:
    if http.post(f"/{name}", json=args).json()["done"]:
        break
response = {"id": "first-hour", "created_at": 0.0, "model": "scripted", "object": "response", "output": [], "parallel_tool_calls": False, "tool_choice": "auto", "tools": []}
verified = http.post("/verify", json={"responses_create_params": {"input": []}, "response": response}).json()
print(f"nemo_gym on {run.id}: reward {verified['reward']}, cost {verified['cost']}")
run.stop()
```

```text
nemo_gym on RN-…: reward …, cost {'severe': …
```

```python first-hour inspect
import os, tempfile
from inspect_ai import eval
from inspect_ai.model import ModelOutput, get_model
from damaros.adapters.inspect import icu
from damaros.server import Server

POLICY = [("order_lab", {"test": "blood_culture_x2", "priority": "stat"}), ("order_med", {"drug": "cefepime", "priority": "stat"})]

def scripted(messages, tools, tool_choice, config):                      # Inspect's mockllm in the model's place: two orders, then wait until the patient is handed back
    if messages[-1].role == "tool" and '"ended": true' in messages[-1].text:
        return ModelOutput.from_content("mockllm/model", "handed back")
    turn = sum(m.role == "assistant" for m in messages)
    name, args = POLICY[turn] if turn < len(POLICY) else ("wait", {"minutes": 240})
    return ModelOutput.for_tool_call("mockllm/model", name, args)

server = Server.from_env()
run = server.open_run("train", episodes=48)
os.environ["DAMAROS_RUN_TOKEN"] = run.token                            # -T server=... names the server; the token stays in the environment
log = eval(icu(seeds=[0], server=server.base), model=get_model("mockllm/model", custom_outputs=scripted), max_samples=1, display="none", log_dir=tempfile.mkdtemp())[0]
score = log.samples[0].scores["server_reward"]
print(f"inspect on {run.id}: {log.status}, reward {score.value}, cost {score.metadata['cost']}")
run.stop()
```

```text
inspect on RN-…: success, reward …, cost {'severe': …
```

## FHIR R4 and HL7 v2 on the same seat

An agent built for a hospital's own interfaces can use them here. On a hosted run the patient in hand is also a FHIR R4 server at `/fhir` and an HL7 v2 endpoint at `/hl7`, with the run's own token and the same clock. Reads show exactly the chart the physician has been shown. A write is **one call of the physician's tools**: it costs the minutes that call costs, is recorded in the run, replays with `verify`, and is scored as the tool call is. Tests in `apps/server/src/hosted/hosted.test.ts` play evaluation panels with the tools, with FHIR and with HL7 v2, and the runs tie on every case. Nothing needs the tool API: the case flow has its own forms on each door. FHIR: `POST /fhir/$next-case`, `POST /fhir/Encounter/current/$wait` (a Parameters resource with `minutes`) and `POST /fhir/Encounter/current/$end-case`, each the tool of the same name with the same answer. HL7 v2: `ADT^A01` asks for the next patient, `ADT^A03` hands the patient back, and `ZWT^Z01` with a `ZWT|<minutes>` segment lets time pass. **Reading is not free, and one look costs one `get_chart`**: a FHIR search or read, or the HL7 feed, costs the minute `get_chart` costs if the chart has moved since the last door look (any recorded call, native or door, or any simulated time passing), and nothing if it has not. Reading every kind of resource at one decision costs what one `get_chart` costs, so the score does not depend on the door, and reading again to watch the clock gains nothing (the CapabilityStatement is free; a native `get_chart` charges every call). A refused write at the door (an order id the world does not know, a missing or stale `If-Match`) costs nothing; a write the tool itself refuses costs the minute the native call costs. The proof tests play whole cases through FHIR alone and through HL7 alone with an agent that reads the chart through the door and decides from it (a low pressure asks for a vasopressor, a fever for a drug it later stops, a lactate of 4 or more for fluids), and they tie with the same agent playing with the tools. **A read shows what `get_chart` shows**: the same last 24 vital rows and last 40 alarms, whichever door, so no door sees further back than another. Alarms are `Communication` resources (`priority` `stat` for a crisis, `routine` for a warning) and `alarm` documents on the HL7 feed. **What reached the physician since their last call (a page, a note, a lab back, a crisis alarm) rides on the answer once, as on the tools' `since_last`**: on FHIR, an extension `https://damaros.ai/fhir/StructureDefinition/since-last` on a resource, an entry with `search.mode` `outcome` on a search, an `information` issue on an OperationOutcome, and inside `result` on `$wait`; on HL7 v2, `NTE` segments on the ACK. Read it there, because it does not come twice, and take a search's resources from the entries with `search.mode` `match`. What has no FHIR form: 13 of the 25 physician tools. `get_vitals` and `get_alarms` are reads with no call of their own (`Observation`, `Communication`). `examine`, `ask_nurse`, `ask_patient`, `ask_rt`, `ask_pharmacist`, `talk_to_family`, `set_code_status`, `set_monitoring`, `set_alarm_limits`, `handoff` and `transfer` cannot be placed through FHIR, and neither can `branch`; use the MCP door for those, on the same run. An agent that stays on FHIR alone cannot examine the patient or ask the nurse. HL7 v2 carries less: orders, notes, working diagnoses and the case flow.

```python
# A patient must be in hand first: POST /$next-case with a Parameters body (an empty body returns 415, and GET /metadata returns 409 before a patient).
status, _ = seat.fhir("POST", "/$next-case", {"resourceType": "Parameters", "parameter": []})
status, _ = seat.fhir("POST", "/Encounter/current/$wait", {"resourceType": "Parameters", "parameter": [{"name": "minutes", "valueInteger": 10}]})
status, meta = seat.fhir("GET", "/metadata")                      # the CapabilityStatement: what is offered, and the Damaros profile
status, labs = seat.fhir("GET", "/Observation?category=laboratory")
status, req = seat.fhir("POST", "/MedicationRequest", {           # order_med (or order_fluids)
    "resourceType": "MedicationRequest", "status": "active", "intent": "order", "priority": "stat",
    "subject": {"reference": "Patient/patient-1"},
    "medicationCodeableConcept": {"coding": [{"system": "https://damaros.ai/fhir/CodeSystem/order", "code": "cefepime"}]}})
status, mar = seat.fhir("GET", "/MedicationAdministration")       # what has reached the patient
status, cur = seat.fhir("GET", f"/MedicationRequest/{req['id']}")   # re-read first: time passing moves the order's version, and a stale If-Match returns 412
status, _ = seat.fhir("PUT", f"/MedicationRequest/{req['id']}", {**cur, "status": "stopped"}, if_match=f'W/"{cur["meta"]["versionId"]}"')   # stop_order
ack = seat.hl7("MSH|^~\\&|AGENT|SEAT|DAMAROS|WORLD001|20260101080000||ORM^O01|M1|T|2.5\rORC|NW|L1|||||^^^^^S\rOBR|1|L1||lactate^lactate^DAMAROS\r")   # an order; MSA|AA means it was placed
feed = seat.hl7()                                                  # the patient as ADT^A01, ORU^R01 and MDM^T02
seat.hl7("MSH|^~\\&|AGENT|SEAT|DAMAROS|WORLD001|20260101080000||ADT^A01|M0|T|2.5\r")   # the next patient
seat.hl7("MSH|^~\\&|AGENT|SEAT|DAMAROS|WORLD001|20260101080000||ZWT^Z01|M2|T|2.5\rZWT|10\r")   # let 10 minutes pass
seat.hl7("MSH|^~\\&|AGENT|SEAT|DAMAROS|WORLD001|20260101080000||ADT^A03|M3|T|2.5\r")   # hand the patient back; at the end of the panel the answer reads `done: the panel is played`
```

**A lab, ordered and read over FHIR.** A lab, an imaging study, a procedure or a support order is a `ServiceRequest` (a drug or a fluid is a `MedicationRequest`). POST one to `/fhir/ServiceRequest` with `intent: order`, a `priority` of `stat` or `routine`, and a `code` whose coding is
the world's own order id (`lactate`, `blood_culture_x2`, `procalcitonin`...) in the system `https://damaros.ai/fhir/CodeSystem/order`; it is the tool `order_lab`, and the `201` answer is the order as the chart now holds it. `subject` is the patient in hand, `Patient/patient-<n>`, where `<n>` is the patient's place in the panel
(the `patient` parameter `$next-case` answers; it is the case's place in your seat, never its own id), and the server does not need it to place the order. Time has to pass before the result is back: `$wait` lets it. The result is read from two resources: `Observation?category=laboratory` (one `Observation` per value, with `valueQuantity`) and `DiagnosticReport` (one per lab, listing its Observations),
and the order itself from `ServiceRequest` (its `status` follows the order from active to completed). Every read is one look and costs what one `get_chart` costs. A lab the world does not hold is `422` naming the code and costs nothing. The whole loop, with `curl` (the client's `seat.fhir` is the same call):

```bash first-hour
set -e
read RUN TOKEN < <(python3 -c 'from damaros.server import Server; r = Server.from_env().open_run("sample"); print(r.id, r.token)')   # a sample run, and its own token
fhir() { curl -sS -H "authorization: Bearer $TOKEN" -H 'content-type: application/fhir+json' "$@"; }
field() { python3 -c "import json,sys; print($1)"; }
fhir -X POST "$DAMAROS_URL/fhir/\$next-case" -d '{"resourceType":"Parameters","parameter":[]}' | field 'next(x["valueString"] for x in json.load(sys.stdin)["parameter"] if x["name"] == "patient")'
fhir -X POST "$DAMAROS_URL/fhir/ServiceRequest" -d '{"resourceType":"ServiceRequest","status":"active","intent":"order","priority":"stat","subject":{"reference":"Patient/patient-1"},"code":{"coding":[{"system":"https://damaros.ai/fhir/CodeSystem/order","code":"lactate"}]}}' | field '(lambda r: r["resourceType"] + " " + r["status"])(json.load(sys.stdin))'
fhir -X POST "$DAMAROS_URL/fhir/Encounter/current/\$wait" -d '{"resourceType":"Parameters","parameter":[{"name":"minutes","valueInteger":60}]}' | field 'json.load(sys.stdin)["resourceType"]'
fhir "$DAMAROS_URL/fhir/Observation?category=laboratory" | field '"lab values back: " + str(len(json.load(sys.stdin).get("entry", [])))'
fhir "$DAMAROS_URL/fhir/ServiceRequest" | field '"orders: " + ", ".join(e["resource"]["code"]["coding"][0]["code"] + " " + e["resource"]["status"] for e in json.load(sys.stdin).get("entry", []))'
fhir -X POST "$DAMAROS_URL/fhir/Encounter/current/\$end-case" -d '{"resourceType":"Parameters","parameter":[]}' | field '"handed back, done: " + str([x for x in json.load(sys.stdin)["parameter"] if x["name"] == "done"][0]["valueBoolean"])'
curl -sS -X POST "$DAMAROS_URL/v1/runs/$RUN/stop" -H "authorization: Bearer $DAMAROS_TOKEN" -H 'content-type: application/json' -d '{}' > /dev/null
```

```text
Patient/patient-1
ServiceRequest active
Parameters
lab values back: …
orders: …
handed back, done: False
```

**The whole loop over HL7 v2.** One message in, one ACK out, on `POST /hl7` with the content type `x-application/hl7-v2+er7` (segments end in a carriage return). An `MSA-1` of `AA` means it was done; `AE` or `AR` carries the refusal's sentence in `MSA-3`. The loop is the tool loop in messages:
`ADT^A01` asks for the next patient (the ACK says `case 3 of 21`, and `done: the panel is played` when there is none); `ORM^O01` places orders (`OBR-4` a lab, `RXO-1` a drug or fluid); `ZWT^Z01` with a `ZWT|<minutes>` segment lets that many minutes pass;
`GET /hl7` is the patient in hand as messages (`ADT^A01`, `ORU^R01` with an `OBX` for each lab value that is back, `MDM^T02` for notes); and `ADT^A03` hands the patient back. **`ADT^A03` is `end_case`**: the same tool, the same answer in the ACK, the same scoring, nothing else to send. Asking `ADT^A01` while a patient is still in hand is an `AE` ("Finish this patient first").
A patient who died or left the unit still has to be handed back with `ADT^A03`. **The panel is over** when `ADT^A01` answers `done: the panel is played`: that closes the run, the server scores it, and the run's token ends with it. The verdict is then at `GET /v1/runs/<id>/analysis` with the account token (see "Without our client" above). One patient's messages, in order:

```text
MSH|^~\&|AGENT|SEAT|DAMAROS|WORLD001|20260101080000||ADT^A01|M0|T|2.5          ->  MSA|AA|M0|case 1 of 21
MSH|^~\&|AGENT|SEAT|DAMAROS|WORLD001|20260101080000||ORM^O01|M1|T|2.5
ORC|NW|L1|||||^^^^^S
OBR|1|L1||lactate^lactate^DAMAROS                                          ->  MSA|AA|M1|...
MSH|^~\&|AGENT|SEAT|DAMAROS|WORLD001|20260101080000||ZWT^Z01|M2|T|2.5
ZWT|60                                                                     ->  MSA|AA|M2|...
GET /hl7                                                                   ->  ADT^A01, ORU^R01 (OBX: lactate...), MDM^T02
MSH|^~\&|AGENT|SEAT|DAMAROS|WORLD001|20260101080000||ADT^A03|M3|T|2.5      ->  MSA|AA|M3|<the end_case answer, as JSON>
MSH|^~\&|AGENT|SEAT|DAMAROS|WORLD001|20260101080000||ADT^A01|M4|T|2.5      ->  the next patient: MSA|AA|M4|case 2 of 21 (or: done: the panel is played)
```

The same, run with `curl`:

```bash first-hour
set -e
read RUN TOKEN < <(python3 -c 'from damaros.server import Server; r = Server.from_env().open_run("sample"); print(r.id, r.token)')   # a sample run, and its own token
CR=$'\r'
send() { printf '%s' "$1" | curl -sS -X POST "$DAMAROS_URL/hl7" -H "authorization: Bearer $TOKEN" -H 'content-type: x-application/hl7-v2+er7' --data-binary @- | tr '\r' '\n' | grep '^MSA'; }
msh() { local type=$1 id=$2; printf '%s' "MSH|^~\\&|AGENT|SEAT|DAMAROS|WORLD001|20260101080000||${type}|${id}|T|2.5${CR}"; }
send "$(msh ADT^A01 M0)"
send "$(msh ORM^O01 M1)ORC|NW|L1|||||^^^^^S${CR}OBR|1|L1||lactate^lactate^DAMAROS$CR"
send "$(msh ZWT^Z01 M2)ZWT|60$CR"
FEED=$(curl -sS "$DAMAROS_URL/hl7" -H "authorization: Bearer $TOKEN" | tr '\r' '\n')     # the message types of the feed; a patient who died is not a feed, and the text says so
echo "feed: $(echo "$FEED" | grep '^MSH' | cut -d'|' -f9 | paste -sd' ' -)"
send "$(msh ADT^A03 M3)"
send "$(msh ADT^A01 M4)"
curl -sS -X POST "$DAMAROS_URL/v1/runs/$RUN/stop" -H "authorization: Bearer $DAMAROS_TOKEN" -H 'content-type: application/json' -d '{}' > /dev/null
```

```text
MSA|AA|M0|case 1 of …
MSA|AA|M1|…
MSA|AA|M2|…
feed: …
MSA|AA|M3|…
MSA|AA|M4|case 2 of …
```

Codes are the world's own order ids in a Damaros code system (`DAMAROS` in HL7), and two standard terminologies are accepted beside them, so an agent built against a real EHR is understood:

| Standard | Where it is accepted | What it maps to |
|---|---|---|
| **RxNorm** (`http://www.nlm.nih.gov/research/umls/rxnorm`; `RXNORM` in HL7) | `MedicationRequest` and `ServiceRequest` code on write; `RXO-1` and `OBR-4` in an `ORM^O01` | The world's order, through RxCUIs fetched from NLM's RxNav (`worlds/001/data/terminology.json`). Reads carry the RxCUI as a second coding beside the DAMAROS one. |
| **ICD-10-CM** (`http://hl7.org/fhir/sid/icd-10-cm`; `I10`, `I10C` or `ICD10CM` in HL7 table 0396) | `POST Condition`; `DG1` in an `ORM^O01` or `MDM^T02` | The CDC's FY2027 description, for the diagnoses of the world's clusters. |

RxNorm is ingredient level, so a code that names more than one order here (heparin as an infusion and as prophylaxis, sodium chloride as the saline bolus and the 3% saline) is refused with the orders it could mean: send the DAMAROS code of the one you want. A code the data file does not know is `422` (FHIR) or `AE` (HL7) with the code named, and costs nothing. A few orders have no RxNorm concept (the file lists them under `unresolved`), and go by their DAMAROS code. The doors send DAMAROS ids in HL7 and both codings in FHIR.

**A diagnosis is only recorded, never shown.** The chart carries no diagnosis, so `GET /Condition` is empty. A `Condition` (or a `DG1`) is written through the note tool as `Working diagnosis: <code> <CDC description>`, reads back as a note on `DocumentReference`, and has no effect on the patient. Sepsis is coded as its infection (`A41.9` and the like); `R65.2x` stands only beside one and is never a principal diagnosis.

**Not accepted: LOINC, SNOMED CT and CPT.** Their licences are pending counsel, so a lab or a diagnosis in one of them is refused as an unknown coding, and labs and imaging are ordered and read by their DAMAROS codes. They join when counsel clears them.

What an order carries goes in the standard fields, and no door fills one in for you. A FHIR `MedicationRequest` carries `dosageInstruction[0].doseAndRate[0].doseQuantity` (unit `mL` is `volume_ml`, `mmol`, `U` or `unit` is `units`, `mcg/kg/min` is `dose`), `rateQuantity` (`rate`) and `timing.repeat.duration` with `durationUnit` `min` or `h` (`over_minutes`), or the `order-argument` extension; an HL7 `ORM^O01` carries the amount in `RXO-2` with its units in `RXO-4`, a strength in `RXO-17` with `RXO-18` `mcg/kg/min`, the rate in `RXO-20` and the time it runs over in `TQ1-6` (`60^min`) or `ORC-7.3` (`M60`, `PT1H`). A fluid bolus with no volume or no time is refused as the tool refuses it: 422 over FHIR, and `AR` over HL7 naming the field, with nothing in the message placed. A goal, step or ceiling (a titration order) has no HL7 field and goes over FHIR or the tools.

An order the tool refuses comes back as an OperationOutcome (FHIR) or an `AE` ACK (HL7) with the tool's sentence. The hosted path carries HL7 v2 as an HTTP body (`x-application/hl7-v2+er7`); a raw MLLP socket needs a TCP listener in front of the server and is not offered. The JavaScript client has the same two methods (`seat.fhir`, `seat.hl7`). A run with a remote Resident host takes reads and writes on both doors: each is placed through the same awaited path as an MCP call (the host is asked each simulated minute first), so a software agent and a robot Resident can work one bedside while the physician is an integration agent that speaks only FHIR or only HL7 v2. If the host is gone mid-call the door answers 409 (FHIR) or an `AE` ACK with the run's sentence.

**On this machine.** The local server (`node apps/server/src/main.ts`, loopback only, no token) gives every bed the same two doors on its own listener: `/api/bedside/<bed>/fhir/...` and `/api/bedside/<bed>/hl7`, with the same operations (`$wait`, `$end-case`; `ZWT^Z01`, `ADT^A03`), the same clock and the same refusals, recorded in the bed's own calls, so the debrief and `damaros replay --verify` on the run written from them agree. A bed holds one patient: `$next-case` and `ADT^A01` answer with how to open another bed (`POST /api/bedside`). `damaros mcp` and `damaros mcp --campaign` speak MCP on stdio and have no HTTP listener, so they have no FHIR or HL7 door; `damaros residents serve` serves the Residents' protocol, not a physician seat.

## On this machine

```python
from damaros import UnitEnv, BedsideEnv, ResidentEnv, ResidentLanes
env = UnitEnv(shifts=6, beds=12)
obs, info = env.reset(seed="demo")          # obs: the board, as JSON text; info["tools"]: every tool
obs, reward, done, _, info = env.step({"name": "admit", "arguments": {"patient": "pt_14"}})
```

| Class | The seat | Reward |
|---|---|---|
| `BedsideEnv` | the physician, one patient at a time (`damaros mcp`) | `end_case`'s `reward`; `info["cost"]` is the harm cost, apart |
| `UnitEnv` | the physician over a campaign (`damaros mcp --campaign`) | the shift's reward when it closes |
| `ResidentEnv`, `ResidentLanes` | the Residents: your policy is the host (`damaros residents serve`) | a task reward every step; `info["outcome"]` = `{reward, cost, severe}` at the end |

`BedsideEnv` passes Gymnasium's `check_env` (`pip install 'damaros[gymnasium]'`): `observation_space` is the JSON text of the server's answer, `action_space` is a tool call and its `sample()` builds a valid call from the action spec in `registry.json`, and `reset(seed=7)` starts the panel again from seed 7, so one seed gives the same first patient and the same play. Every `info` carries `step_type` (`first`, `mid` or `last`), `door`, `minute`, `call` and, on the last step, `terms`: what each reward term added. The first `reset()` draws the panel, which takes tens of seconds the first time and a file read after; the server's progress lines are forwarded to your stderr as it goes (`DAMAROS_QUIET=1` drops them). When the damaros command cannot start (no Node 24.14 or newer, or a wrong path), the error says so and names `DAMAROS_CLI`, the variable that sets the command, for example `DAMAROS_CLI='npx damaros'`.

`ResidentLanes(lanes=N)` is the vector form: N bedsides in one lockstep, one message per round for all lanes, `step(actions)` returning scenes, rewards, terminated, truncated, info.
Reward and harm cost are separate fields everywhere, so a lab can run constrained training against a harm budget; no class returns a number that adds them.

**Credit and branches.** The engine draws every piece of exogenous luck from the case's seed and the event it belongs to, so a finished case can be played again with something else done and only what that changed differs.
On sample and train, the final step's `info["credit"]` (and `seat.credit`, `obs.credit`, the verify response's `credit`, the Inspect store's `credit`) lists each acting call of the run with what it did to the patient: the run with it minus the run without it,
with the same case and seed (`{index, minute, tool, args, effect: {p_death, harms, severe, cost_usd}}`; a negative `p_death` is a call that helped). `env.branch(minute, actions, mode="insert")` and `HostedSeat.branch(...)` ask the
server for the finished case played again from `minute` with `actions` (`[{"name", "args"}]`): the trunk's and the branch's outcomes and their difference. On the Damaros Evaluation the answer is the paired difference alone, and there is no credit.

## A Resident host

A host is a program that answers a scene with events. The same file runs against a local world and, unchanged, against the hosted server:

```bash
damaros residents serve -- python3 -m damaros.host_stub                                   # train and demo, never a score
read -rs DAMAROS_RUN_TOKEN && export DAMAROS_RUN_TOKEN     # paste the run token; it is not echoed and not kept in history
damaros residents connect --server https://app.damaros.ai --run RN-... -- python3 my_host.py
python3 tools/residents/conform.py -- python3 my_host.py                                  # the conformance suite (on your own robot host: the section below)
```

```python
from damaros import ResidentHost, serve_host
class MyNurse(ResidentHost):
    specs = [{"id": "nurse-1", "seat": "nurse", "kind": "robot", "capabilities": ["give_dose"], "bays": "all", "fallback": "world", "timeout_min": 25}]
    def act(self, scene):                   # one scene in, [{"resident": id, "event": {...}}] out
        return []
serve_host(lambda lane: MyNurse())
```

Your host is a client and our clock is simulated: network latency changes no result, and real-time responsiveness is not measured. `damaros residents connect` is the Resident only; a verdict needs a physician to play the panel too (`run.seat()`), or `damaros connect`, which brings a reference physician: see "Which command gives a verdict" under "Connect a Resident" below.

**A unit.** `damaros residents serve --beds 10` plays one shift of the 10-bed unit; the beds are the lanes and your Residents are shared by them (one nurse cannot be in two bays), so the server says `ready.unit` and a host
that defines `act_unit(entries)` answers every bed at once (`damaros.host_stub.StubNurse` does). Every minute in a unit is the shift's. `ResidentLanes(beds=10)` is the same from Python, and `python3 tools/residents/demo.py`
plays a shift with a nurse and a robot stand-in, records it (`shift.json`) and replays it with `damaros replay --verify` with no host attached.

**A harm budget.** `BedsideEnv(harm_budget="thresholds.json")`, `Seat(harm_budget=...)` and `ResidentLanes(harm_budget=...)` take the file `damaros check` reads: a patient (or lane) whose harms break a limit in it ends there, `info["budget"]` /
the ack's `budget_breached` names the rule, and the reward and the cost stay two fields.

**The hosted server.** `damaros.server.Server(url, token).open_evaluation_run("my-agent@1.2")` registers the version, opens an evaluation run and plays it over the server's MCP door; `run.analysis()` returns the customer's analysis once the
server has scored it. No library is needed; the cases never leave the server. "Your first hour" above walks every call: `usage`, `register`, `open_run`, `runs`, `latest_run`, `compare`, `run(id).verify()`.

**The hosted release check for a robot is one call.** `run = server.open_robot_evaluation_run("my-robot@1.2")` registers the version and opens an evaluation run whose Residents your host plays; `run.play_host(MyRobot())` connects it to the run's socket and plays the shift to its end
(the WebSocket is `damaros.connect`, in this package; a `damaros.ResidentHost` or a `damaros.connect` policy both work), with the server playing the guideline policy as the physician, the same for every Resident; `run.analysis()` returns the three numbers with the `robot` section. Step 8 of "Your first hour" runs it with the stub robot host. An evaluation run is a measurement
on the Damaros Evaluation cases and uses one evaluation version of your licence; `server.open_resident_run()` opens a training shift instead (`kind="train"`, the default; the server plays the physician here too, `physician="mine"` to play it yourself), which is not a measurement and scores nothing, and `open_resident_run(kind="evaluation", agent="my-robot@1.2")` is the evaluation run for a host you connect with the `damaros` command.
From a terminal: `damaros check --server https://app.damaros.ai --agent name@version --residents remote -- <host command...>` is the same release check with your host's command after `--`.

### Coverage of the host

Every line and every branch of the host a lab subclasses (`damaros/host.py`) and of the reference host (`damaros/host_stub.py`) is run by `damaros/test_resident.py`, and `test/host-coverage.test.ts` fails when one is not.
The Isaac host (`worlds/001/isaac/host.py`) is covered where it runs on a CPU: its Isaac Sim body, its Newton body, the recorder and `--check robot` need those packages and a GPU, and are covered by the GPU day.
Line and branch coverage together, measured with `coverage` 7.16.0 (the `dev` extra: `pip install 'clients/python[dev]'`):

```bash
PYTHONPATH=clients/python python3 -m coverage run --branch --include='*/damaros/host.py,*/damaros/host_stub.py,*/isaac/host.py' -m unittest discover -s clients/python -p test_resident.py
PYTHONPATH=clients/python python3 -m coverage run --branch --append --include='*/damaros/host.py,*/damaros/host_stub.py,*/isaac/host.py' -m unittest discover -s worlds/001/isaac -p test_host.py
python3 -m coverage report -m
```

| File | Lines and branches run |
|---|---|
| `clients/python/damaros/host.py` | 100% |
| `clients/python/damaros/host_stub.py` | 100% |
| `worlds/001/isaac/host.py` | 68% |

## Run the conformance suite on your robot host

The suite is the Resident adapter spec as a program: if your host passes it, it connects to the hosted server unchanged. It needs no GPU, no simulator and no checkout of this repository. Ship two things to the machine your host runs on:

```text conform-ship
clients/python
tools/residents/conform.py
```

Put `conform.py` next to the `clients/python` directory (`pip install clients/python` is optional: the suite finds the directory beside it), install the `damaros` command line Damaros sent you, and run it with your host's own command after `--`:

```bash
export DAMAROS_CLI=damaros                                   # the damaros command, if it is not on your PATH under another name
python3 conform.py --target stub -- python3 my_host.py       # no server, no command line: a stub server in the file speaks protocol 1 to your host
python3 conform.py --target serve -- python3 my_host.py      # your host in a local bedside, one lane and three; the same seed writes the same log
export DAMAROS_URL=https://app.damaros.ai                    # the address Damaros gave you
read -rs DAMAROS_TOKEN && export DAMAROS_TOKEN                # paste the account token: it is not echoed and not kept in your history
python3 conform.py --target hosted -- python3 my_host.py     # your host on a training run on the server (no test version is used, nothing is scored)
```

`--target all` runs the first two (and the third when you add `--server URL`). It prints one `PASS` or `FAIL` line per rule with the reason, ends with `N of N checks pass; this host conforms`, and exits 1 on any failure.
The rules: `hello` first and listing protocol 1; only Residents, seats and capabilities the World declares; one `events` message for each `scene`, for the same simulated minute, with every lane answered; events of
the declared shapes with no time field and no wall-clock key; a lane's events never name another lane's task; unknown messages ignored; the same scenes giving the same events; exit 0 on `end` and nothing on stdout but protocol messages;
and, on a server, the run ending complete with nothing refused. `test/conform-outside.test.ts` copies exactly the two entries above into a clean directory and runs all of this from there, with the Python and the JavaScript
reference host and with hosts that break the rules, against a hosted server booted as the operator boots it.

## Spaces

`ToolCallSpace`, `EventsSpace` and `SceneSpace` have `contains(x)`. They read `damaros/registry.json`, which `tools/residents/gen-registry.ts` writes from the World's own declarations (seats, capabilities,
harm kinds, event shapes, the physician's 25 tools); a test fails when the committed file differs from what the World declares.

## Connect a Resident (`damaros connect`)

One command connects a Resident (an agent, a robot or a device) to a run. It was the separate `damaros-connect` package; it is part of `damaros` now, and the old `damaros-connect` command still works.

### Run

The run's token is read from the environment, never from the command line.

```
export DAMAROS_RUN_TOKEN=...
damaros connect --server https://your-damaros-server --run RN-...
```

That plays the fixture nurse, to see it work. **The physician it also plays is a demo and measures nothing**: a wait-only script that places no order, so the Resident has little to do and a run it plays says nothing about your Resident. A run's physician is what makes its numbers comparable: open the run with `physician: "guideline"` and the server plays the guideline policy itself (the demo physician then stands aside, as `damaros check` and `damaros session --physician guideline` do), or play the physician's seat yourself over MCP and start this with `--no-physician`. To connect your own:

```
damaros connect --server https://your-damaros-server --run RN-... --policy my_robot:policy
```

### Which command gives a verdict

A robot run has two halves, and a verdict (the run analysis) exists only when both have played the panel to its last case: the **Resident** (your robot, answering the server once per simulated minute on the run's socket) and the **physician** (whoever takes each patient, orders, lets time pass and hands the patient back). The run's token is the same for both.

| You run | It is | Plays | Verdict |
|---|---|---|---|
| `damaros connect --server $DAMAROS_URL --run RN-... --policy my_robot:policy` | the Resident, in Python, **and** a reference physician (a fixed watch of eight hours in hourly steps for each patient) | the whole panel, by itself | Yes: the run completes and is scored. Read it with `damaros check --server $DAMAROS_URL --run RN-... --json`, or `run.analysis()`. |
| `damaros connect ... --no-physician --policy my_robot:policy` | the Resident only | nothing else | Only once your own physician has played every patient (below). |
| `damaros residents connect --server $DAMAROS_URL --run RN-... -- python3 my_host.py` | the Resident, as a program of yours that speaks the Resident protocol on stdin and stdout (the Isaac host is one); it never plays a physician | the robot only | Only once your own physician has played every patient (below). |
| `run.seat()` in the Python client (`next_case`, `call`, `end_case`), or any MCP, FHIR or HL7 client with the run's token | the physician | the patients | Only once a Resident is connected: until then `next_case` is refused with `This run waits for its Resident host`. |

So: **`damaros connect` alone is enough for a first verdict**, with the reference physician; use the seat client (or your own agent) beside `--no-physician` or `damaros residents connect` when the physician is part of what you are measuring. Either way, open the run with `residents` set to `remote`
(`Server.open_run("evaluation", agent="my-robot@1", residents="remote")`, or `damaros session --server $DAMAROS_URL --kind train --residents remote`, which prints the connect line), start the Resident first or at once, then play. `DAMAROS_RUN_TOKEN` is the run's token (shown once when the run opens); `DAMAROS_TOKEN` is the account's, and reads the verdict.

### Your policy

A class or function with one method: an observation in, actions out.

```python
def infer(obs):
    return {"actions": [...]}
```

### From Python

`damaros.connect` (this package) is what the Python client uses to play a host on a hosted run, in one call: `run.play_host(host)` after `server.open_robot_evaluation_run("name@version")`, which opens the run with `physician: "guideline"`, so the server plays the physician and `play_host` connects the host alone. `damaros.connect.connect(server, run, token, policy, physician=True, say=print)` is the same function with the pieces in your hands: `physician` is `True` (the demo physician, which watches each patient for eight simulated hours and **measures nothing**), `False` (no demo: the server plays the guideline physician, or your own agent plays the seat over MCP) or a list of `(tool, arguments)` the demo places for every patient first, so a Resident has orders to carry out; that is still a script, not a measurement.

## Lab adapters (`pip install 'damaros[openenv]'`, or `[verifiers]`, `[verifiers_v1]`, `[nemo_gym]` or `[inspect]`)

**One lab extra per environment.** `openenv-core` needs `mcp` 2 (through `fastmcp` 4.1.1), `verifiers` 0.4 needs `mcp` 2.0.0, `verifiers` 0.3 needs `mcp` 1 and `nemo-gym` 0.4 needs `mcp` 1.x, so those extras cannot all be installed into one environment: pip stops with ResolutionImpossible. Each extra resolves alone, with `gymnasium`, and with `inspect`; use a virtual environment for each lab you wrap (`python -m venv .venv-openenv && .venv-openenv/bin/pip install -e 'clients/python[openenv]'`). The tests find them through `DAMAROS_PYTHON_OPENENV`, `_OPENENV_MCP` (the same interpreter: the MCP form shares the `openenv` extra), `_VERIFIERS`, `_VERIFIERS_V1`, `_NEMO_GYM` and `_INSPECT` (each falls back to `DAMAROS_PYTHON`), which `npm run labs` builds and prints.

Each wraps the physician's seat, is under 200 lines, takes its reward from the server, and cannot ask for a test or evaluation case (the local server it wraps serves the sample and train splits only).
`python3 -m damaros.adapters smoke <name>` plays one patient with a scripted policy: no model, no GPU, no network.

| Adapter | Class | Example |
|---|---|---|
| `damaros.adapters.openenv` | `IcuEnvironment` (`reset`, `step`, `state`; observation = text plus the structured chart) | `env = IcuEnvironment(); env.reset(seed=3); env.step(ToolCall(name="get_chart"))` |
| `damaros.adapters.verifiers` | `IcuEnv(vf.MultiTurnEnv)`; rubric = the server's reward, `state["cost"]` = the harm cost (weight 0) | `env = IcuEnv(seeds=range(64)); results = env.evaluate(client, model)` |
| `damaros.adapters.openenv_mcp` | `IcuMCPEnvironment(MCPEnvironment)`: OpenEnv's MCP form (RFC 003), the seat's tools listed by `ListToolsAction` and called by `CallToolAction`; the call that ends the patient has `done`, the server's `reward` and `metadata["cost"]` | `env = IcuMCPEnvironment(); env.reset(seed=3); env.step(CallToolAction(tool_name="get_chart", arguments={}))` |
| `damaros.adapters.verifiers_v1` | `IcuTaskset` (one task per seed) and `IcuEnv(vf.Env)`: the model replies with a JSON tool call a turn; the trace gets `damaros_reward` and one `damaros_cost_<...>` metric per part of the cost, none added to another. Taskset id `damaros_verifiers` | `vf.EnvConfig(taskset={"id": "damaros_verifiers", "seeds": ["1", "2"]})` |
| `damaros.adapters.nemo_gym` | `IcuResourcesServer(SimpleResourcesServer)`: a route per tool, `/seed_session` from a seed, `/verify` = the server's reward with `cost` beside it; `tool_definitions()` is the Responses-API tool list for a dataset row | `IcuResourcesServer.run_webserver()` (config: `size`, `clusters`, `harm_budget`) |
| `damaros.adapters.inspect` | `icu()` task: `physician` solver, `server_reward` scorer (the cost rides in the score's metadata); `icu_server()` is the `--server` form: it submits an evaluation run to the hosted server and reads the run analysis back as the task's metric | `inspect eval damaros/adapters/inspect.py --model <model>`; `inspect eval damaros.adapters.inspect@icu_server -T server=https://app.damaros.ai -T token=... -T agent=my-agent@1.2 --max-samples 1` |

Pinned versions (all at least two weeks old on 2026-10-30): `gymnasium==1.4.0` (2026-10-05), `openenv-core==0.3.0` (2026-05-11) with `fastmcp==4.1.1` (2026-10-18), `verifiers==0.3.1` (2026-08-24) with `datasets==5.1.0` (2026-10-05)
for the `MultiTurnEnv` adapter, `verifiers==0.4.0` (2026-10-12, MIT) for the v1 adapter, `nemo-gym==0.4.0` (2026-07-02, Apache-2.0) with `httpx==0.28.1` (test client), `inspect-ai==0.3.280` (2026-10-14). `nemo-gym` 0.5.0 and later
(0.7.0 is the newest, 2026-10-12) require Python >=3.13.14, so a 3.12 environment stays on 0.4.0; the resources server's base classes are read at that version. OpenEnv's RFC 003 (MCP support) is on its main branch
(merged with #169, 2025-11-24) though its own header still reads "In Review"; the classes it describes ship in 0.3.0, and the `openenv_mcp` adapter is written against them.

Licences, read from the installed metadata and licence files on 2026-10-30 (the two new environments, 160 and 107 packages): every package is MIT, BSD, Apache-2.0 or the PSF licence but one. `gprof2dot` (LGPL-3.0 or later) is a
dependency of `nemo-gym` itself, a profile-graph tool the adapter never imports; R32 allows it: LGPL-2.1 and 3.0 are allowed only for what Damaros neither ships, vendors nor modifies, and this is a lab package's own dependency in the lab's environment (the lab environment is a test
environment and ships in nothing). `protobuf-py-ext` 0.1.1 (a `verifiers` 0.4 dependency) carries no licence file in its wheel; its project, bufbuild/protobuf-py, declares Apache-2.0.

**The harm cost, the Safety-Gymnasium way.** `BedsideEnv` puts `info["cost"]` on every step (zero until the patient ends), the way Safety-Gymnasium 1.0.0 and the libraries built on it read it. It is the server's own breakdown
(`{severe, other, by_kind}`), and `info["cost_vector"]` is that breakdown as a fixed-order vector (`COST_AXES`, one entry per severity class: harms at severity 3 or more, then the rest). Nothing sums it, into one
number or into the reward.

Tests, from the repository root: `python3 -m unittest discover -s clients/python -p 'test_*.py'`.
