proef 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- proef/__init__.py +25 -0
- proef/acquisition.py +244 -0
- proef/ad.py +159 -0
- proef/adapters/__init__.py +0 -0
- proef/adapters/admet.py +196 -0
- proef/adapters/bio/__init__.py +0 -0
- proef/adapters/bio/rdkit_ops.py +52 -0
- proef/adapters/bio/safety_rules.json +146 -0
- proef/adapters/bio/seq_alerts.py +79 -0
- proef/adapters/bio/structure_score.py +85 -0
- proef/adapters/bio/tox_alerts.py +99 -0
- proef/adapters/data/__init__.py +0 -0
- proef/adapters/data/admet.py +62 -0
- proef/adapters/data/chembl.py +110 -0
- proef/adapters/data/frozen/admet/MANIFEST.json +48 -0
- proef/adapters/data/frozen/admet/bbb_martins/test.csv +407 -0
- proef/adapters/data/frozen/admet/bbb_martins/train_val.csv +1625 -0
- proef/adapters/data/frozen/admet/caco2_wang/test.csv +183 -0
- proef/adapters/data/frozen/admet/caco2_wang/train_val.csv +729 -0
- proef/adapters/data/frozen/admet/hia_hou/test.csv +118 -0
- proef/adapters/data/frozen/admet/hia_hou/train_val.csv +462 -0
- proef/adapters/data/moleculenet.py +60 -0
- proef/adapters/databases/__init__.py +0 -0
- proef/adapters/databases/chembl_gates.py +121 -0
- proef/adapters/databases/chembl_lookup.py +35 -0
- proef/adapters/databases/open_targets.py +102 -0
- proef/adapters/databases/pubmed.py +94 -0
- proef/adapters/devices/__init__.py +0 -0
- proef/adapters/devices/ezo_ph.py +251 -0
- proef/adapters/devices/hcs_microscope.py +143 -0
- proef/adapters/devices/lcms.py +123 -0
- proef/adapters/devices/scheduler.py +84 -0
- proef/adapters/devices/sila2.py +134 -0
- proef/adapters/genomics/alphagenome.py +146 -0
- proef/adapters/lab/__init__.py +0 -0
- proef/adapters/lab/bioprocess.py +32 -0
- proef/adapters/lab/devices.py +170 -0
- proef/adapters/lab/imaging.py +226 -0
- proef/adapters/lab/mhs_driver.py +124 -0
- proef/adapters/lab/opentrons.py +222 -0
- proef/adapters/lab/ot2_sim.py +174 -0
- proef/adapters/lab/plate_reader_share.py +108 -0
- proef/adapters/lab/protein_design.py +199 -0
- proef/adapters/lab/recording.py +119 -0
- proef/adapters/lab/replay.py +107 -0
- proef/adapters/lab/simulator.py +282 -0
- proef/adapters/lab/synthesis.py +92 -0
- proef/adapters/models/__init__.py +0 -0
- proef/adapters/models/anthropic_provider.py +157 -0
- proef/adapters/models/assayloop_ranker.py +67 -0
- proef/adapters/models/from_env.py +93 -0
- proef/adapters/models/gp_policy.py +93 -0
- proef/adapters/models/gp_policy_gp.py +36 -0
- proef/adapters/models/llm_policy.py +187 -0
- proef/adapters/models/openai_compat.py +150 -0
- proef/adapters/models/sklearn_policy.py +65 -0
- proef/adapters/retrosynthesis.py +247 -0
- proef/adapters/sandbox/__init__.py +20 -0
- proef/adapters/sandbox/agentenv.py +145 -0
- proef/adapters/sandbox/docker.py +217 -0
- proef/adapters/sandbox/local.py +164 -0
- proef/adapters/sandbox/opensandbox.py +122 -0
- proef/adapters/store/__init__.py +0 -0
- proef/adapters/store/sqlite.py +207 -0
- proef/adaptive.py +108 -0
- proef/advisory.py +76 -0
- proef/analysis_profiles/__init__.py +8 -0
- proef/analysis_profiles/measurements.py +266 -0
- proef/analysis_profiles/plate_assay.py +316 -0
- proef/analysis_report.py +195 -0
- proef/analysis_store.py +183 -0
- proef/anchor.py +154 -0
- proef/api/app.py +107 -0
- proef/api/launch.py +170 -0
- proef/api/v1/__init__.py +29 -0
- proef/api/v1/analyses.py +367 -0
- proef/api/v1/campaigns.py +802 -0
- proef/api/v1/deps.py +10 -0
- proef/api/v1/evals.py +16 -0
- proef/api/v1/evidence.py +132 -0
- proef/api/v1/governance.py +35 -0
- proef/api/v1/inbox.py +119 -0
- proef/api/v1/lab.py +110 -0
- proef/api/v1/pauses.py +77 -0
- proef/api/v1/programs.py +397 -0
- proef/api/v1/results.py +147 -0
- proef/api/v1/schemas.py +932 -0
- proef/api/v1/system.py +79 -0
- proef/api/v1/trees.py +216 -0
- proef/api/wizard_sessions.py +253 -0
- proef/approvals.py +102 -0
- proef/assays/__init__.py +15 -0
- proef/assays/dls.py +114 -0
- proef/assays/dsf.py +81 -0
- proef/assays/elisa.py +58 -0
- proef/assays/properties.py +65 -0
- proef/assays/simulate.py +157 -0
- proef/audit.py +152 -0
- proef/autoloop.py +1620 -0
- proef/benchmark.py +442 -0
- proef/campaign_fsm.py +151 -0
- proef/citations.py +141 -0
- proef/cli.py +1249 -0
- proef/connect.py +74 -0
- proef/core/__init__.py +0 -0
- proef/core/contracts/__init__.py +35 -0
- proef/core/contracts/analysis.py +100 -0
- proef/core/contracts/models.py +395 -0
- proef/core/device_card.py +125 -0
- proef/core/hypothesis.py +720 -0
- proef/core/interfaces.py +164 -0
- proef/core/registry.py +123 -0
- proef/core/safety.py +324 -0
- proef/core/workflow.py +159 -0
- proef/critic.py +62 -0
- proef/demo.py +164 -0
- proef/derivation.py +128 -0
- proef/diary.py +301 -0
- proef/eln.py +87 -0
- proef/evals/__init__.py +1 -0
- proef/evals/hallucination.py +86 -0
- proef/evals/harness.py +358 -0
- proef/evals/orchestration.py +254 -0
- proef/evals/tasks.py +1010 -0
- proef/evals/toolcalls.py +425 -0
- proef/experiment.py +172 -0
- proef/experiment_analysis.py +114 -0
- proef/experiments/__init__.py +0 -0
- proef/experiments/grounding_exp.py +689 -0
- proef/figures.py +218 -0
- proef/fitting.py +309 -0
- proef/fixtures.py +140 -0
- proef/flywheel.py +125 -0
- proef/followup.py +126 -0
- proef/governance.py +290 -0
- proef/groundedness.py +361 -0
- proef/grounding.py +202 -0
- proef/hypothesis_agent.py +369 -0
- proef/ingest.py +157 -0
- proef/instruments.json +173 -0
- proef/interpret.py +95 -0
- proef/kinetic.py +102 -0
- proef/labread/__init__.py +45 -0
- proef/labread/analysis.py +428 -0
- proef/labread/common.py +153 -0
- proef/labread/formats.py +190 -0
- proef/labread/layout.py +168 -0
- proef/labread/pubchem.py +179 -0
- proef/labselect.py +431 -0
- proef/materials.py +140 -0
- proef/mcp_instrument.py +396 -0
- proef/mcp_server.py +283 -0
- proef/modality.py +111 -0
- proef/model_guard.py +245 -0
- proef/output_blocks.py +183 -0
- proef/paths.py +32 -0
- proef/physfail.py +55 -0
- proef/plan.py +160 -0
- proef/plots.py +123 -0
- proef/predictors.py +217 -0
- proef/probes.py +79 -0
- proef/problem_tree.py +581 -0
- proef/program.py +308 -0
- proef/protocol_design.py +42 -0
- proef/proxy.py +78 -0
- proef/readiness.py +259 -0
- proef/reliability.py +49 -0
- proef/report.py +117 -0
- proef/reproduce.py +310 -0
- proef/reviewer.py +254 -0
- proef/sandbox_session.py +247 -0
- proef/sandboxd.py +109 -0
- proef/scaffold.py +195 -0
- proef/series.py +327 -0
- proef/skills.py +203 -0
- proef/sweep.py +83 -0
- proef/taste.py +177 -0
- proef/templates/confirmatory-followup.json +34 -0
- proef/templates/dose-response-screen.json +39 -0
- proef/templates/sar-exploration.json +38 -0
- proef/templates.py +124 -0
- proef/toolkit.py +433 -0
- proef/toolloop.py +133 -0
- proef/tools.py +441 -0
- proef/tpp.py +185 -0
- proef/views/__init__.py +14 -0
- proef/views/counts.py +102 -0
- proef/views/experiment.py +154 -0
- proef/views/ids.py +49 -0
- proef/views/narrative.py +294 -0
- proef/views/pipeline.py +370 -0
- proef/vision.py +165 -0
- proef/watch.py +790 -0
- proef/wizard_chain.py +25 -0
- proef/wizard_store.py +373 -0
- proef-0.2.0.dist-info/METADATA +662 -0
- proef-0.2.0.dist-info/RECORD +200 -0
- proef-0.2.0.dist-info/WHEEL +4 -0
- proef-0.2.0.dist-info/entry_points.txt +14 -0
- proef-0.2.0.dist-info/licenses/LICENSE +202 -0
proef/sandbox_session.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""SandboxSession — the opt-in execution boundary for one experiment (S-T3).
|
|
2
|
+
|
|
3
|
+
cfg: sandbox: {mode: off|per_experiment, type: local|docker}
|
|
4
|
+
mode=off (default) changes nothing: registries execute in-process.
|
|
5
|
+
mode=per_experiment wraps ONE sandbox around the experiment; every BioTool
|
|
6
|
+
invocation routed through session.registry() executes INSIDE the sandbox
|
|
7
|
+
via `proef sandboxd` (see sandboxd.py), with create/exec/fork/destroy
|
|
8
|
+
provenance recorded by the adapters on the experiment branch.
|
|
9
|
+
|
|
10
|
+
Failure policy: a sandboxed tool call that cannot be transported returns
|
|
11
|
+
a FAILED ToolResult (visible in the chain) — never a silent in-process
|
|
12
|
+
fallback, and never an exception that kills the campaign.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import sys
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from proef.core.contracts import ToolResult
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class SandboxSession:
|
|
24
|
+
def __init__(self, mode: str = "per_experiment", sandbox: str = "local",
|
|
25
|
+
branch_id: str = "campaign", store: Any = None,
|
|
26
|
+
actor: Any = None, image: str | None = None,
|
|
27
|
+
python: str | None = None, runner: Any = None):
|
|
28
|
+
"""Config validated eagerly; the sandbox itself is created on
|
|
29
|
+
start() — the owner (e.g. run_campaign) binds the final branch."""
|
|
30
|
+
self.mode = mode
|
|
31
|
+
self.kind = sandbox
|
|
32
|
+
self.branch_id = branch_id
|
|
33
|
+
self.store = store
|
|
34
|
+
self.actor = actor
|
|
35
|
+
self.image = image
|
|
36
|
+
self.runner = runner
|
|
37
|
+
self.python = python
|
|
38
|
+
self.sandbox = None
|
|
39
|
+
if mode == "off":
|
|
40
|
+
return
|
|
41
|
+
if mode != "per_experiment":
|
|
42
|
+
raise ValueError(f"unknown sandbox mode '{mode}' "
|
|
43
|
+
"(off | per_experiment; per_run is roadmap)")
|
|
44
|
+
if sandbox not in ("local", "docker"):
|
|
45
|
+
raise ValueError(
|
|
46
|
+
f"sandbox type '{sandbox}' not supported for execution "
|
|
47
|
+
"(local | docker; agentenv is lifecycle-only, opensandbox "
|
|
48
|
+
"needs a live server) — loud refusal, no silent fallback")
|
|
49
|
+
|
|
50
|
+
def start(self, branch_id: str | None = None):
|
|
51
|
+
"""Create the sandbox (once); branch defaults to the configured
|
|
52
|
+
one. Returns the session for chaining."""
|
|
53
|
+
if self.mode == "off" or self.sandbox is not None:
|
|
54
|
+
return self
|
|
55
|
+
branch = branch_id or self.branch_id
|
|
56
|
+
if self.kind == "local":
|
|
57
|
+
from proef.adapters.sandbox.local import LocalSandbox
|
|
58
|
+
self.sandbox = LocalSandbox(branch_id=branch, store=self.store,
|
|
59
|
+
actor=self.actor)
|
|
60
|
+
self.python = self.python or sys.executable
|
|
61
|
+
else:
|
|
62
|
+
from proef.adapters.sandbox.docker import DockerSandbox
|
|
63
|
+
self.sandbox = DockerSandbox(
|
|
64
|
+
image=self.image or "python:3.12-slim", branch_id=branch,
|
|
65
|
+
store=self.store, actor=self.actor, runner=self.runner)
|
|
66
|
+
self.python = self.python or "python3"
|
|
67
|
+
return self
|
|
68
|
+
|
|
69
|
+
# ------------------------------------------------------------- routing
|
|
70
|
+
|
|
71
|
+
def registry(self, inner: Any = None):
|
|
72
|
+
"""Facade over Registry: same surface, invoke() routed through
|
|
73
|
+
the sandbox when enabled."""
|
|
74
|
+
from proef.core.registry import Registry
|
|
75
|
+
inner = inner or Registry()
|
|
76
|
+
session = self
|
|
77
|
+
|
|
78
|
+
class _SessionRegistry:
|
|
79
|
+
def invoke(self, invocation):
|
|
80
|
+
if session.sandbox is None:
|
|
81
|
+
return inner.invoke(invocation)
|
|
82
|
+
return session.invoke(invocation,
|
|
83
|
+
tools=inner.tool_paths())
|
|
84
|
+
|
|
85
|
+
def __getattr__(self, item):
|
|
86
|
+
return getattr(inner, item)
|
|
87
|
+
|
|
88
|
+
return _SessionRegistry()
|
|
89
|
+
|
|
90
|
+
def invoke(self, invocation, tools: list[str] | None = None) -> ToolResult:
|
|
91
|
+
req: dict = {"invocation": invocation.model_dump(mode="json")}
|
|
92
|
+
if tools:
|
|
93
|
+
req["tools"] = tools # the host's tool set, rebuilt in-sandbox
|
|
94
|
+
data = self.call(req, timeout=invocation.timeout_secs + 15)
|
|
95
|
+
if "error" in data:
|
|
96
|
+
return ToolResult(
|
|
97
|
+
envelope=invocation.envelope,
|
|
98
|
+
invocation_id=invocation.invocation_id,
|
|
99
|
+
status="failed",
|
|
100
|
+
rejection_reason=data["error"])
|
|
101
|
+
try:
|
|
102
|
+
return ToolResult.model_validate(data)
|
|
103
|
+
except Exception as e:
|
|
104
|
+
return ToolResult(
|
|
105
|
+
envelope=invocation.envelope,
|
|
106
|
+
invocation_id=invocation.invocation_id,
|
|
107
|
+
status="failed",
|
|
108
|
+
rejection_reason=f"sandbox transport: bad response ({e})")
|
|
109
|
+
|
|
110
|
+
def call(self, request: dict, timeout: float = 75.0) -> dict:
|
|
111
|
+
"""One transport round-trip: JSON request on stdin -> sandbox
|
|
112
|
+
worker -> JSON response on stdout. The payload rides STDIN, not
|
|
113
|
+
argv, so growing lab-state can never hit ARG_MAX. Returns an
|
|
114
|
+
{'error': ...} dict on ANY transport failure (never raises), so
|
|
115
|
+
callers degrade visibly and the campaign survives."""
|
|
116
|
+
self.start()
|
|
117
|
+
try:
|
|
118
|
+
out = self.sandbox.exec(f"{self.python} -m proef.sandboxd",
|
|
119
|
+
timeout=timeout,
|
|
120
|
+
stdin_data=json.dumps(request))
|
|
121
|
+
return json.loads(out)
|
|
122
|
+
except Exception as e: # loud FAILED, never a
|
|
123
|
+
return {"error": f"sandbox transport: {type(e).__name__}: "
|
|
124
|
+
f"{str(e)[:200]}"} # silent fallback
|
|
125
|
+
|
|
126
|
+
# ----------------------------------------------------------- lifecycle
|
|
127
|
+
|
|
128
|
+
def snapshot(self) -> str | None:
|
|
129
|
+
return self.sandbox.snapshot() if self.sandbox else None
|
|
130
|
+
|
|
131
|
+
def fork(self) -> "SandboxSession":
|
|
132
|
+
"""per_run mode (roadmap): child experiment runs from this state;
|
|
133
|
+
writes never flow back."""
|
|
134
|
+
self.start()
|
|
135
|
+
if not self.sandbox:
|
|
136
|
+
raise RuntimeError("cannot fork an off-mode session")
|
|
137
|
+
return SandboxSession._adopted(self.sandbox.fork(), kind=self.kind,
|
|
138
|
+
python=self.python, store=self.store,
|
|
139
|
+
actor=self.actor)
|
|
140
|
+
|
|
141
|
+
@classmethod
|
|
142
|
+
def _adopted(cls, sandbox, *, kind, python, store, actor) -> "SandboxSession":
|
|
143
|
+
"""Internal: a session wrapping an EXISTING sandbox (fork child).
|
|
144
|
+
Private API — validation stays in the single constructor path."""
|
|
145
|
+
s = cls.__new__(cls)
|
|
146
|
+
s.mode, s.kind = "per_experiment", kind
|
|
147
|
+
s.branch_id = getattr(sandbox, "branch_id", "fork")
|
|
148
|
+
s.store, s.actor, s.python, s.sandbox = store, actor, python, sandbox
|
|
149
|
+
s.image, s.runner = None, None
|
|
150
|
+
return s
|
|
151
|
+
|
|
152
|
+
def destroy(self) -> None:
|
|
153
|
+
if self.sandbox:
|
|
154
|
+
self.sandbox.destroy()
|
|
155
|
+
self.sandbox = None
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class SandboxedLab:
|
|
159
|
+
"""LabAdapter facade (S-T3 1c): every protocol op executes INSIDE the
|
|
160
|
+
session's sandbox via the sandboxd worker. State (seed, queued runs,
|
|
161
|
+
property gate) is carried by the caller between calls, so each op runs
|
|
162
|
+
fresh in-sandbox; results come back as identical pydantic models.
|
|
163
|
+
|
|
164
|
+
Supported inner labs: the simulator today. Anything else raises —
|
|
165
|
+
a real robot behind a gateway is the gateway's (physical) trust
|
|
166
|
+
boundary question, not this transport's."""
|
|
167
|
+
|
|
168
|
+
def __init__(self, session: SandboxSession, seed: int = 7,
|
|
169
|
+
lab: Any = None):
|
|
170
|
+
"""Pass the campaign's actual lab: its FULL configuration (seed,
|
|
171
|
+
replicates, interference, gates) transfers as initial state, so
|
|
172
|
+
sandboxed execution is a transport, not a re-defaulting. A lab
|
|
173
|
+
without state export is refused — silently swapping in a fresh
|
|
174
|
+
simulator would be the worst kind of lie."""
|
|
175
|
+
session.start()
|
|
176
|
+
if session.sandbox is None:
|
|
177
|
+
raise ValueError("SandboxedLab needs an active session "
|
|
178
|
+
"(mode=off has no sandbox)")
|
|
179
|
+
if lab is not None and not hasattr(lab, "export_state"):
|
|
180
|
+
raise NotImplementedError(
|
|
181
|
+
f"sandboxed execution for lab "
|
|
182
|
+
f"'{getattr(lab, 'name', type(lab).__name__)}' is not "
|
|
183
|
+
"wired (needs export_state; see ROADMAP S-T3) — refusing "
|
|
184
|
+
"to substitute a different instrument")
|
|
185
|
+
self.session = session
|
|
186
|
+
self.seed = getattr(lab, "seed", seed)
|
|
187
|
+
self.name = "sandboxed:simulator"
|
|
188
|
+
self._state = lab.export_state() if lab is not None else None
|
|
189
|
+
|
|
190
|
+
def _op(self, op: str, payload: dict | None = None):
|
|
191
|
+
req = {"kind": "lab", "seed": self.seed, "op": op,
|
|
192
|
+
"payload": payload or {}, "lab_state": self._state}
|
|
193
|
+
data = self.session.call(req)
|
|
194
|
+
if "error" in data:
|
|
195
|
+
raise RuntimeError(
|
|
196
|
+
f"sandboxed lab op '{op}' failed: {data['error']}")
|
|
197
|
+
self._state = data["lab_state"]
|
|
198
|
+
return data["result"]
|
|
199
|
+
|
|
200
|
+
# -- LabAdapter protocol ---------------------------------------------------
|
|
201
|
+
|
|
202
|
+
def list_capabilities(self) -> dict:
|
|
203
|
+
return self._op("caps")
|
|
204
|
+
|
|
205
|
+
def submit_protocol(self, protocol) -> str:
|
|
206
|
+
return self._op("submit",
|
|
207
|
+
{"protocol": protocol.model_dump(mode="json")})
|
|
208
|
+
|
|
209
|
+
def get_status(self, run_id: str) -> str:
|
|
210
|
+
return self._op("status", {"run_id": run_id})
|
|
211
|
+
|
|
212
|
+
def fetch_results(self, run_id: str):
|
|
213
|
+
from proef.core.contracts import AssayResult
|
|
214
|
+
return AssayResult.model_validate(
|
|
215
|
+
self._op("fetch", {"run_id": run_id}))
|
|
216
|
+
|
|
217
|
+
def set_property_gate(self, metric: str, direction: str,
|
|
218
|
+
threshold: float) -> None:
|
|
219
|
+
self._op("set_property_gate", {"metric": metric,
|
|
220
|
+
"direction": direction,
|
|
221
|
+
"threshold": float(threshold)})
|
|
222
|
+
|
|
223
|
+
def cancel(self, run_id: str) -> None:
|
|
224
|
+
self._op("cancel", {"run_id": run_id})
|
|
225
|
+
|
|
226
|
+
# -- autoloop-visible lab traits (the campaign reads these; mirroring
|
|
227
|
+
# SimulatorLab's duck-typed surface keeps fidelity inside the box) --
|
|
228
|
+
|
|
229
|
+
@property
|
|
230
|
+
def _property_gate(self) -> dict | None:
|
|
231
|
+
return (self._state or {}).get("property_gate")
|
|
232
|
+
|
|
233
|
+
@property
|
|
234
|
+
def replicates(self) -> int:
|
|
235
|
+
return (self._state or {}).get("replicates", 3)
|
|
236
|
+
|
|
237
|
+
def true_ic50_um(self, run_id: str, sample_id: str) -> float:
|
|
238
|
+
return self._op("true_ic50",
|
|
239
|
+
{"run_id": run_id, "sample_id": sample_id})
|
|
240
|
+
|
|
241
|
+
def _property_true_value(self, run_id: str, sample_id: str) -> float:
|
|
242
|
+
return self._op("prop_true",
|
|
243
|
+
{"run_id": run_id, "sample_id": sample_id})
|
|
244
|
+
|
|
245
|
+
def is_interferer(self, run_id: str, sample_id: str) -> bool:
|
|
246
|
+
return self._op("interferer",
|
|
247
|
+
{"run_id": run_id, "sample_id": sample_id})
|
proef/sandboxd.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""proef sandboxd — the in-sandbox tool worker (S-T3).
|
|
2
|
+
|
|
3
|
+
Reads one ToolInvocation request, executes the resolved BioTool INSIDE
|
|
4
|
+
this process (and therefore inside the sandbox), and writes one ToolResult
|
|
5
|
+
JSON line to stdout. The transport (request b64, output stdout) is
|
|
6
|
+
shell-safe across LocalSandbox.exec and DockerSandbox.exec alike.
|
|
7
|
+
|
|
8
|
+
Request JSON: {"invocation": <ToolInvocation model_dump>}
|
|
9
|
+
Response JSON: <ToolResult model_dump>, or {"error": ...} on protocol
|
|
10
|
+
failure (never a partial success dressed up as a result).
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import base64
|
|
15
|
+
import json
|
|
16
|
+
import sys
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _build_registry(tool_paths: list[str] | None = None):
|
|
20
|
+
"""Entry-point tools + the descriptor tool + whatever tool classes the
|
|
21
|
+
host says it has registered (so sandboxed and in-process runs see the
|
|
22
|
+
same tools). A path that cannot be built here is skipped; the invoke
|
|
23
|
+
then fails loudly as 'no tool registered'."""
|
|
24
|
+
from proef.core.registry import Registry, import_string
|
|
25
|
+
reg = Registry()
|
|
26
|
+
reg.load_entry_points()
|
|
27
|
+
from proef.adapters.bio.rdkit_ops import MoleculeDescriptors
|
|
28
|
+
reg.register_tool(MoleculeDescriptors())
|
|
29
|
+
have = set(reg.tool_paths())
|
|
30
|
+
for path in tool_paths or []:
|
|
31
|
+
if path in have:
|
|
32
|
+
continue
|
|
33
|
+
try:
|
|
34
|
+
reg.register_tool(import_string(path)())
|
|
35
|
+
except Exception:
|
|
36
|
+
continue
|
|
37
|
+
return reg
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _lab(req: dict) -> str:
|
|
41
|
+
"""Kind 'lab': stateless-by-handoff execution of one simulator op.
|
|
42
|
+
Caller carries lab_state between calls (SandboxedLab), so every op
|
|
43
|
+
still runs FRESH inside the sandbox."""
|
|
44
|
+
from proef.adapters.lab.simulator import SimulatorLab
|
|
45
|
+
from proef.core.contracts import ProtocolSubmission
|
|
46
|
+
try:
|
|
47
|
+
st = req.get("lab_state")
|
|
48
|
+
lab = (SimulatorLab.import_state(st) if st
|
|
49
|
+
else SimulatorLab(seed=req.get("seed", 7)))
|
|
50
|
+
op, pl = req["op"], req.get("payload", {})
|
|
51
|
+
if op == "caps":
|
|
52
|
+
result: object = lab.list_capabilities()
|
|
53
|
+
elif op == "submit":
|
|
54
|
+
result = lab.submit_protocol(
|
|
55
|
+
ProtocolSubmission.model_validate(pl["protocol"]))
|
|
56
|
+
elif op == "status":
|
|
57
|
+
result = lab.get_status(pl["run_id"])
|
|
58
|
+
elif op == "fetch":
|
|
59
|
+
result = lab.fetch_results(pl["run_id"]).model_dump(mode="json")
|
|
60
|
+
elif op == "cancel":
|
|
61
|
+
result = lab.cancel(pl["run_id"])
|
|
62
|
+
elif op == "true_ic50":
|
|
63
|
+
result = lab.true_ic50_um(pl["run_id"], pl["sample_id"])
|
|
64
|
+
elif op == "prop_true":
|
|
65
|
+
result = lab._property_true_value(pl["run_id"], pl["sample_id"])
|
|
66
|
+
elif op == "interferer":
|
|
67
|
+
result = lab.is_interferer(pl["run_id"], pl["sample_id"])
|
|
68
|
+
elif op == "set_property_gate":
|
|
69
|
+
result = lab.set_property_gate(pl["metric"], pl["direction"],
|
|
70
|
+
pl["threshold"])
|
|
71
|
+
else:
|
|
72
|
+
return json.dumps({"error": f"unknown lab op '{op}'"})
|
|
73
|
+
return json.dumps({"result": result,
|
|
74
|
+
"lab_state": lab.export_state()})
|
|
75
|
+
except Exception as e:
|
|
76
|
+
return json.dumps({"error": f"{type(e).__name__}: {e}"})
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def run(request_json: str) -> str:
|
|
80
|
+
try:
|
|
81
|
+
req = json.loads(request_json)
|
|
82
|
+
if req.get("kind") == "lab":
|
|
83
|
+
return _lab(req)
|
|
84
|
+
from proef.core.contracts import ToolInvocation, ToolResult
|
|
85
|
+
inv = ToolInvocation.model_validate(req["invocation"])
|
|
86
|
+
try:
|
|
87
|
+
result = _build_registry(req.get("tools")).invoke(inv)
|
|
88
|
+
except LookupError as e:
|
|
89
|
+
result = ToolResult(envelope=inv.envelope,
|
|
90
|
+
invocation_id=inv.invocation_id,
|
|
91
|
+
status="rejected",
|
|
92
|
+
rejection_reason=str(e))
|
|
93
|
+
return result.model_dump_json()
|
|
94
|
+
except Exception as e: # protocol-level failure stays loud
|
|
95
|
+
return json.dumps({"error": f"{type(e).__name__}: {e}"})
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def main(argv: list[str] | None = None) -> int:
|
|
99
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
100
|
+
if len(argv) >= 2 and argv[0] == "--request-b64":
|
|
101
|
+
request = base64.b64decode(argv[1]).decode()
|
|
102
|
+
else:
|
|
103
|
+
request = sys.stdin.read()
|
|
104
|
+
sys.stdout.write(run(request))
|
|
105
|
+
return 0
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
if __name__ == "__main__":
|
|
109
|
+
sys.exit(main())
|
proef/scaffold.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""`proef new-adapter` — scaffold a tested adapter package in one command.
|
|
2
|
+
|
|
3
|
+
proef new-adapter lab my_robot --dir adapters-contrib
|
|
4
|
+
proef new-adapter tool my_docking --dir adapters-contrib
|
|
5
|
+
|
|
6
|
+
Generates a ready-to-run module + pytest file implementing the chosen
|
|
7
|
+
interface, following docs/ADAPTERS.md rules.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import re
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
TEMPLATES: dict[str, dict[str, str]] = {
|
|
16
|
+
"lab": {
|
|
17
|
+
"module": '''"""{name_human} — LabAdapter (IAL contract). Generated by proef new-adapter.
|
|
18
|
+
|
|
19
|
+
Rules (docs/ADAPTERS.md): agents reach this ONLY through LabGateway; declare
|
|
20
|
+
exactly the capabilities you implement; never perform unsafe actions here.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from proef.core.contracts import (
|
|
27
|
+
AssayResult, Envelope, InstrumentInfo, ProtocolSubmission, RunStatus,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class {class_name}:
|
|
32
|
+
name = "{snake_name}"
|
|
33
|
+
|
|
34
|
+
def __init__(self, seed: int = 0):
|
|
35
|
+
self.seed = seed
|
|
36
|
+
self._runs: dict[str, ProtocolSubmission] = {{}}
|
|
37
|
+
|
|
38
|
+
def list_capabilities(self) -> dict[str, Any]:
|
|
39
|
+
# TODO: declare your instrument's real capabilities
|
|
40
|
+
return {{"assays": ["binding"], "throughput": {{"plates_per_day": 8}}, "bsl_max": 1}}
|
|
41
|
+
|
|
42
|
+
def submit_protocol(self, protocol: ProtocolSubmission) -> str:
|
|
43
|
+
# TODO: compile protocol to your instrument's script and enqueue it
|
|
44
|
+
run_id = f"{{self.name}}-{{protocol.protocol_id[:8]}}"
|
|
45
|
+
self._runs[run_id] = protocol
|
|
46
|
+
return run_id
|
|
47
|
+
|
|
48
|
+
def get_status(self, run_id: str) -> str:
|
|
49
|
+
return "done" if run_id in self._runs else "failed"
|
|
50
|
+
|
|
51
|
+
def fetch_results(self, run_id: str) -> AssayResult:
|
|
52
|
+
# TODO: normalize your instrument's raw output into the AssayResult contract
|
|
53
|
+
protocol = self._runs[run_id]
|
|
54
|
+
return AssayResult(
|
|
55
|
+
envelope=Envelope(experiment_branch_id=self.name),
|
|
56
|
+
protocol_id=protocol.protocol_id,
|
|
57
|
+
instrument=InstrumentInfo(adapter=self.name, instrument_id="{snake_name}-01"),
|
|
58
|
+
status=RunStatus.completed,
|
|
59
|
+
measurements=[], # TODO
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
def cancel(self, run_id: str) -> None:
|
|
63
|
+
self._runs.pop(run_id, None)
|
|
64
|
+
''',
|
|
65
|
+
"test": '''import pytest
|
|
66
|
+
|
|
67
|
+
from proef.core.contracts import (
|
|
68
|
+
Envelope, ProtocolOp, ProtocolStep, ProtocolSubmission,
|
|
69
|
+
ReagentSpec, SampleKind, SampleSpec,
|
|
70
|
+
)
|
|
71
|
+
from proef.core.safety import LabGateway, SafetyEngine
|
|
72
|
+
from proef.adapters.store.sqlite import SqliteProvenanceStore
|
|
73
|
+
from proef.core.interfaces import system_actor
|
|
74
|
+
from {module_name} import {class_name}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def make_protocol():
|
|
78
|
+
return ProtocolSubmission(
|
|
79
|
+
envelope=Envelope(experiment_branch_id="test"),
|
|
80
|
+
title="smoke", assay_type="binding",
|
|
81
|
+
steps=[ProtocolStep(seq=1, op=ProtocolOp.dispense, params={{"volume_ul": 10}})],
|
|
82
|
+
samples=[SampleSpec(sample_id="C1", kind=SampleKind.compound, concentration="10uM")],
|
|
83
|
+
reagents=[ReagentSpec(name="buffer", amount="1 mL", bsl_level=1)],
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_adapter_contract():
|
|
88
|
+
store = SqliteProvenanceStore()
|
|
89
|
+
from proef.governance import execution_governance
|
|
90
|
+
gateway = LabGateway({class_name}(), SafetyEngine(), store,
|
|
91
|
+
system_actor(),
|
|
92
|
+
governance=execution_governance())
|
|
93
|
+
run_id, rejection = gateway.submit(make_protocol())
|
|
94
|
+
assert rejection is None and run_id
|
|
95
|
+
assert gateway.lab.get_status(run_id) == "done"
|
|
96
|
+
result = gateway.results(Envelope(experiment_branch_id="test"), run_id)
|
|
97
|
+
assert result.instrument.adapter == "{snake_name}"
|
|
98
|
+
''',
|
|
99
|
+
},
|
|
100
|
+
"tool": {
|
|
101
|
+
"module": '''"""{name_human} — BioTool. Generated by proef new-adapter.
|
|
102
|
+
|
|
103
|
+
BioTools are pure computation: no physical actions, no network required.
|
|
104
|
+
"""
|
|
105
|
+
from __future__ import annotations
|
|
106
|
+
|
|
107
|
+
from typing import Any
|
|
108
|
+
|
|
109
|
+
from proef.core.contracts import ToolInvocation, ToolName, ToolResult
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class {class_name}:
|
|
113
|
+
name = "{snake_name}"
|
|
114
|
+
capabilities = (ToolName("{cap}"),)
|
|
115
|
+
|
|
116
|
+
def invoke(self, invocation: ToolInvocation) -> ToolResult:
|
|
117
|
+
try:
|
|
118
|
+
output = self._compute(invocation.args)
|
|
119
|
+
except Exception as exc: # narrow this for production use
|
|
120
|
+
return ToolResult(envelope=invocation.envelope.model_copy(),
|
|
121
|
+
invocation_id=invocation.invocation_id,
|
|
122
|
+
status="failed", rejection_reason=str(exc))
|
|
123
|
+
return ToolResult(envelope=invocation.envelope.model_copy(),
|
|
124
|
+
invocation_id=invocation.invocation_id,
|
|
125
|
+
status="succeeded", output=output)
|
|
126
|
+
|
|
127
|
+
def _compute(self, args: dict[str, Any]) -> dict[str, Any]:
|
|
128
|
+
# TODO: your computation here
|
|
129
|
+
return {{"echo": args}}
|
|
130
|
+
''',
|
|
131
|
+
"test": '''from proef.core.contracts import Envelope, ToolInvocation
|
|
132
|
+
from {module_name} import {class_name}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def test_tool_contract():
|
|
136
|
+
tool = {class_name}()
|
|
137
|
+
inv = ToolInvocation(envelope=Envelope(experiment_branch_id="test"),
|
|
138
|
+
tool="{cap}", args={{"hello": "world"}})
|
|
139
|
+
result = tool.invoke(inv)
|
|
140
|
+
assert result.status == "succeeded"
|
|
141
|
+
assert result.output["echo"]["hello"] == "world"
|
|
142
|
+
''',
|
|
143
|
+
},
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
TOOL_CAP_CHOICES = ["c.fm.predict_property", "c.evals.benchmark_batch",
|
|
147
|
+
"e.sim.docking", "c.kb.search_literature"]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def snake(name: str) -> str:
|
|
151
|
+
s = re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
|
|
152
|
+
return re.sub(r"[^a-z0-9_]", "_", s)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def scaffold(kind: str, name: str, out_dir: Path, cap: str | None = None) -> Path:
|
|
156
|
+
if kind not in TEMPLATES:
|
|
157
|
+
raise SystemExit(f"unknown adapter kind '{kind}' (choose: {', '.join(TEMPLATES)})")
|
|
158
|
+
class_name = "".join(p.capitalize() for p in snake(name).split("_"))
|
|
159
|
+
module_name = name if "." not in name else name.rsplit(".", 1)[-1]
|
|
160
|
+
if kind == "tool":
|
|
161
|
+
if cap is None:
|
|
162
|
+
cap = TOOL_CAP_CHOICES[0]
|
|
163
|
+
if not cap.startswith("c.") and not cap.startswith("e."):
|
|
164
|
+
raise SystemExit("tool capability must be a registered ToolName (see contracts)")
|
|
165
|
+
t = TEMPLATES[kind]
|
|
166
|
+
fmt = dict(name_human=name.replace("_", " ").replace("-", " "),
|
|
167
|
+
class_name=class_name, snake_name=snake(name),
|
|
168
|
+
module_name=f"{module_name}_adapter", cap=cap or "")
|
|
169
|
+
target = out_dir / f"{snake(name)}_adapter"
|
|
170
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
171
|
+
(target / f"{snake(name)}_adapter.py").write_text(t["module"].format(**fmt))
|
|
172
|
+
(target / f"test_{snake(name)}_adapter.py").write_text(t["test"].format(**fmt))
|
|
173
|
+
return target
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def main(argv: list[str] | None = None) -> int:
|
|
177
|
+
parser = argparse.ArgumentParser(prog="proef new-adapter")
|
|
178
|
+
parser.add_argument("kind", choices=sorted(TEMPLATES), help="adapter interface")
|
|
179
|
+
parser.add_argument("name", help="adapter name, e.g. my_robot")
|
|
180
|
+
parser.add_argument("--dir", default="adapters-contrib", help="output directory")
|
|
181
|
+
parser.add_argument("--cap", default=None,
|
|
182
|
+
help=f"tool capability (tools only); e.g. {TOOL_CAP_CHOICES[0]}")
|
|
183
|
+
args = parser.parse_args(argv)
|
|
184
|
+
try:
|
|
185
|
+
path = scaffold(args.kind, args.name, Path(args.dir), args.cap)
|
|
186
|
+
except SystemExit as exc:
|
|
187
|
+
print(exc)
|
|
188
|
+
return 2
|
|
189
|
+
print(f"scaffolded {args.kind} adapter: {path}")
|
|
190
|
+
print(f"run tests: .venv/bin/python -m pytest {path}")
|
|
191
|
+
return 0
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
if __name__ == "__main__": # pragma: no cover
|
|
195
|
+
raise SystemExit(main())
|