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/core/interfaces.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Proef core interfaces (P2: interfaces, not implementations).
|
|
2
|
+
|
|
3
|
+
Five protocols define every block boundary. Core consumes only these; adapters
|
|
4
|
+
implement them. All results are provenance-wrapped (P5); physical lab actions
|
|
5
|
+
are dispatched through the SafetyEngine (P6); Sandbox exposes fork/snapshot as
|
|
6
|
+
first-class operations (P7).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, Protocol, runtime_checkable
|
|
11
|
+
|
|
12
|
+
from proef.core.contracts import (
|
|
13
|
+
Actor,
|
|
14
|
+
AssayResult,
|
|
15
|
+
Envelope,
|
|
16
|
+
EventType,
|
|
17
|
+
ProtocolSubmission,
|
|
18
|
+
ProvenanceRecord,
|
|
19
|
+
ToolInvocation,
|
|
20
|
+
ToolName,
|
|
21
|
+
ToolResult,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@runtime_checkable
|
|
26
|
+
class ModelProvider(Protocol):
|
|
27
|
+
"""Any foundation model (P3). Implementations must pin model+version so the
|
|
28
|
+
provenance chain can record exactly what produced an artifact."""
|
|
29
|
+
|
|
30
|
+
name: str
|
|
31
|
+
model_version: str
|
|
32
|
+
|
|
33
|
+
def generate(self, invocation: ToolInvocation, prompt: str, **kwargs: Any) -> ToolResult:
|
|
34
|
+
"""Text/completion generation (e.g. molecule proposals, reflections)."""
|
|
35
|
+
...
|
|
36
|
+
|
|
37
|
+
def predict(self, invocation: ToolInvocation, kind: ToolName, payload: dict[str, Any]) -> ToolResult:
|
|
38
|
+
"""Structured prediction (property, ADMET, structure). `kind` selects the task."""
|
|
39
|
+
...
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@runtime_checkable
|
|
43
|
+
class BioTool(Protocol):
|
|
44
|
+
"""A computational bio capability (RDKit, docking, ADMET...). Adapters declare
|
|
45
|
+
capabilities; the registry matches tool names to implementations (P2)."""
|
|
46
|
+
|
|
47
|
+
name: str
|
|
48
|
+
capabilities: tuple[ToolName, ...]
|
|
49
|
+
|
|
50
|
+
def invoke(self, invocation: ToolInvocation) -> ToolResult:
|
|
51
|
+
"""Run a local computation. Must not perform physical actions."""
|
|
52
|
+
...
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@runtime_checkable
|
|
56
|
+
class SafetyEngine(Protocol):
|
|
57
|
+
"""Policy layer in the physical-action path (P6). Outside any agent's trust
|
|
58
|
+
boundary: agents cannot register rules or mark protocols safe."""
|
|
59
|
+
|
|
60
|
+
def check(self, protocol: ProtocolSubmission) -> tuple[bool, str | None]:
|
|
61
|
+
"""Return (approved, rejection_reason)."""
|
|
62
|
+
...
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@runtime_checkable
|
|
66
|
+
class LabAdapter(Protocol):
|
|
67
|
+
"""The IAL: simulator, Opentrons, cloud lab — one contract (P4). Concrete
|
|
68
|
+
adapters must NOT expose this directly to agents; dispatch goes through
|
|
69
|
+
core's LabGateway which enforces SafetyEngine first (P6)."""
|
|
70
|
+
|
|
71
|
+
name: str
|
|
72
|
+
|
|
73
|
+
def list_capabilities(self) -> dict[str, Any]:
|
|
74
|
+
"""Instrument catalog: assays supported, throughput, constraints."""
|
|
75
|
+
...
|
|
76
|
+
|
|
77
|
+
def submit_protocol(self, protocol: ProtocolSubmission) -> str:
|
|
78
|
+
"""Queue a compiled protocol; returns run_id. Call only after safety approval."""
|
|
79
|
+
...
|
|
80
|
+
|
|
81
|
+
def get_status(self, run_id: str) -> str:
|
|
82
|
+
"""queued | running | done | failed | cancelled"""
|
|
83
|
+
...
|
|
84
|
+
|
|
85
|
+
def fetch_results(self, run_id: str) -> AssayResult:
|
|
86
|
+
"""Normalized AssayResult with QC flags and instrument lineage."""
|
|
87
|
+
...
|
|
88
|
+
|
|
89
|
+
def cancel(self, run_id: str) -> None: ...
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@runtime_checkable
|
|
93
|
+
class Sandbox(Protocol):
|
|
94
|
+
"""Experiment-branch lifecycle (P7): create/fork/snapshot/resume, plus
|
|
95
|
+
command execution inside the sandbox. Adapters may
|
|
96
|
+
degrade (e.g. local deep-copy forks, exec raising NotImplementedError)
|
|
97
|
+
but the interface must hold and degradation must be loud, not silent."""
|
|
98
|
+
|
|
99
|
+
sandbox_id: str
|
|
100
|
+
branch_id: str
|
|
101
|
+
|
|
102
|
+
def snapshot(self) -> str:
|
|
103
|
+
"""Freeze full state; returns snapshot_id usable by fork/restore."""
|
|
104
|
+
...
|
|
105
|
+
|
|
106
|
+
def fork(self, snapshot_id: str | None = None) -> "Sandbox":
|
|
107
|
+
"""New sandbox branching from this one (or a stored snapshot)."""
|
|
108
|
+
...
|
|
109
|
+
|
|
110
|
+
def exec(self, command: str, *, timeout: float = 60.0,
|
|
111
|
+
stdin_data: str | None = None) -> str:
|
|
112
|
+
"""Run a command INSIDE the sandbox; optional payload on stdin;
|
|
113
|
+
returns stdout. Every attempt is provenance-recorded BEFORE any
|
|
114
|
+
raise (TimeoutError/RuntimeError). Adapters that cannot execute —
|
|
115
|
+
or cannot honour a parameter — raise NotImplementedError (never
|
|
116
|
+
silently pretend)."""
|
|
117
|
+
...
|
|
118
|
+
|
|
119
|
+
def resume(self, snapshot_id: str | None = None) -> None: ...
|
|
120
|
+
|
|
121
|
+
def destroy(self) -> None: ...
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@runtime_checkable
|
|
125
|
+
class ProvenanceStore(Protocol):
|
|
126
|
+
"""Append-only, hash-chained lineage (P5). Ships with SQLite; Postgres and
|
|
127
|
+
WORM-bucket stores are roadmap. Records are immutable once written."""
|
|
128
|
+
|
|
129
|
+
def append(self, record: ProvenanceRecord) -> ProvenanceRecord:
|
|
130
|
+
"""Compute and stamp record_hash from prev chain; store; return final."""
|
|
131
|
+
...
|
|
132
|
+
|
|
133
|
+
def lineage(self, artifact_id: str) -> list[ProvenanceRecord]:
|
|
134
|
+
"""All records touching an artifact, root-first."""
|
|
135
|
+
...
|
|
136
|
+
|
|
137
|
+
def branch_records(self, branch_id: str) -> list[ProvenanceRecord]:
|
|
138
|
+
"""Every record within an experiment branch."""
|
|
139
|
+
...
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# ------------------------------------------------------------------ helpers
|
|
143
|
+
|
|
144
|
+
def make_envelope(branch_id: str, parent_branch_id: str | None = None) -> Envelope:
|
|
145
|
+
return Envelope(experiment_branch_id=branch_id, parent_branch_id=parent_branch_id)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def system_actor(name: str = "proef-core") -> Actor:
|
|
149
|
+
return Actor(kind="service", id=name)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def record_for(
|
|
153
|
+
envelope: Envelope,
|
|
154
|
+
event_type: EventType,
|
|
155
|
+
actor: Actor,
|
|
156
|
+
**kwargs: Any,
|
|
157
|
+
) -> ProvenanceRecord:
|
|
158
|
+
"""Convenience: build a ProvenanceRecord in this branch."""
|
|
159
|
+
return ProvenanceRecord(
|
|
160
|
+
envelope=envelope.model_copy(),
|
|
161
|
+
event_type=event_type,
|
|
162
|
+
actor=actor,
|
|
163
|
+
**kwargs,
|
|
164
|
+
)
|
proef/core/registry.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Plugin discovery + typed tool registry (P2).
|
|
2
|
+
|
|
3
|
+
Adapters register via entry points (see pyproject.toml) or directly in code.
|
|
4
|
+
The registry matches requested ToolNames to implementations with declared
|
|
5
|
+
capabilities.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import importlib
|
|
10
|
+
import logging
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from proef.core.contracts import ToolInvocation, ToolName, ToolResult
|
|
14
|
+
|
|
15
|
+
log = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Registry:
|
|
19
|
+
"""Holds BioTool implementations keyed by declared capability."""
|
|
20
|
+
|
|
21
|
+
def __init__(self) -> None:
|
|
22
|
+
self._tools: dict[ToolName, list[Any]] = {}
|
|
23
|
+
self._model_providers: dict[str, Any] = {}
|
|
24
|
+
self._default_provider: str | None = None
|
|
25
|
+
|
|
26
|
+
# ---- tools
|
|
27
|
+
|
|
28
|
+
def register_tool(self, tool: Any) -> None:
|
|
29
|
+
for cap in tool.capabilities:
|
|
30
|
+
self._tools.setdefault(ToolName(cap), []).append(tool)
|
|
31
|
+
|
|
32
|
+
def resolve(self, tool: ToolName) -> Any:
|
|
33
|
+
tools = self._tools.get(ToolName(tool))
|
|
34
|
+
if not tools:
|
|
35
|
+
raise LookupError(f"no tool registered for capability '{tool}'")
|
|
36
|
+
if len(tools) == 1:
|
|
37
|
+
return tools[0]
|
|
38
|
+
# several implementations: an explicit integer `priority` attribute
|
|
39
|
+
# (higher wins) decides; a tie falls back to registration order and
|
|
40
|
+
# says so — a silent first-wins hid which adapter actually ran
|
|
41
|
+
ranked = sorted(tools, key=lambda t: -int(getattr(t, "priority", 0)))
|
|
42
|
+
if int(getattr(ranked[0], "priority", 0)) == \
|
|
43
|
+
int(getattr(ranked[1], "priority", 0)):
|
|
44
|
+
log.warning("capability '%s' has %d implementations with equal "
|
|
45
|
+
"priority; using %s (first registered). Set a "
|
|
46
|
+
"`priority` attribute to choose explicitly.",
|
|
47
|
+
tool, len(tools), type(ranked[0]).__name__)
|
|
48
|
+
return ranked[0]
|
|
49
|
+
|
|
50
|
+
def tool_paths(self) -> list[str]:
|
|
51
|
+
"""'module:Class' of every registered tool, so a sandbox worker can
|
|
52
|
+
rebuild the SAME tool set (tools registered in code, not just entry
|
|
53
|
+
points, would otherwise vanish inside the sandbox)."""
|
|
54
|
+
seen: dict[str, None] = {}
|
|
55
|
+
for tools in self._tools.values():
|
|
56
|
+
for t in tools:
|
|
57
|
+
seen[f"{type(t).__module__}:{type(t).__qualname__}"] = None
|
|
58
|
+
return list(seen)
|
|
59
|
+
|
|
60
|
+
def invoke(self, invocation: ToolInvocation) -> ToolResult:
|
|
61
|
+
tool = self.resolve(invocation.tool)
|
|
62
|
+
return tool.invoke(invocation)
|
|
63
|
+
|
|
64
|
+
# ---- model providers
|
|
65
|
+
|
|
66
|
+
def register_model(self, provider: Any, default: bool = False) -> None:
|
|
67
|
+
self._model_providers[provider.name] = provider
|
|
68
|
+
if default or self._default_provider is None:
|
|
69
|
+
self._default_provider = provider.name
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def model(self) -> Any:
|
|
73
|
+
if self._default_provider is None:
|
|
74
|
+
raise LookupError("no model provider registered")
|
|
75
|
+
return self._model_providers[self._default_provider]
|
|
76
|
+
|
|
77
|
+
# ---- entry-point discovery
|
|
78
|
+
|
|
79
|
+
def load_entry_points(self, group_prefix: str = "proef") -> int:
|
|
80
|
+
"""Discover installed adapters. Returns count loaded. Optional deps
|
|
81
|
+
that aren't installed are skipped, never fatal."""
|
|
82
|
+
try:
|
|
83
|
+
from importlib.metadata import entry_points
|
|
84
|
+
except ImportError: # pragma: no cover
|
|
85
|
+
return 0
|
|
86
|
+
eps = entry_points()
|
|
87
|
+
loaded = 0
|
|
88
|
+
groups = [
|
|
89
|
+
(ep, f"{group_prefix}.models")
|
|
90
|
+
if hasattr(eps, "select")
|
|
91
|
+
else (ep, ep.group)
|
|
92
|
+
for ep in []
|
|
93
|
+
] # placeholder; real dispatch below
|
|
94
|
+
if hasattr(eps, "select"): # py3.10+
|
|
95
|
+
for group, setter in (
|
|
96
|
+
(f"{group_prefix}.models", self._ep_model),
|
|
97
|
+
(f"{group_prefix}.labs", self._ep_tool),
|
|
98
|
+
(f"{group_prefix}.tools", self._ep_tool),
|
|
99
|
+
):
|
|
100
|
+
for ep in eps.select(group=group):
|
|
101
|
+
try:
|
|
102
|
+
setter(ep)
|
|
103
|
+
loaded += 1
|
|
104
|
+
except Exception:
|
|
105
|
+
continue # optional dep missing — skip, never fatal
|
|
106
|
+
return loaded
|
|
107
|
+
|
|
108
|
+
def _ep_model(self, ep: Any) -> None:
|
|
109
|
+
cls = ep.load()
|
|
110
|
+
self.register_model(cls())
|
|
111
|
+
|
|
112
|
+
def _ep_tool(self, ep: Any) -> None:
|
|
113
|
+
cls = ep.load()
|
|
114
|
+
self.register_tool(cls())
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def import_string(path: str) -> Any:
|
|
118
|
+
"""Resolve 'module:attr' or 'module.attr' to an object."""
|
|
119
|
+
mod_path, _, attr = path.partition(":")
|
|
120
|
+
if not attr:
|
|
121
|
+
mod_path, _, attr = path.rpartition(".")
|
|
122
|
+
module = importlib.import_module(mod_path)
|
|
123
|
+
return getattr(module, attr)
|
proef/core/safety.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
"""Safety engine — the non-bypassable policy layer for physical actions (P6).
|
|
2
|
+
|
|
3
|
+
Agents never call a LabAdapter directly; core's LabGateway checks every
|
|
4
|
+
ProtocolSubmission against configured rules first. Rules are declarative and
|
|
5
|
+
registered by the operator, not by agents.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import fnmatch
|
|
10
|
+
from typing import Any, Protocol
|
|
11
|
+
|
|
12
|
+
from proef.core.contracts import ProtocolSubmission
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SafetyRule(Protocol):
|
|
16
|
+
"""A single declarative check. Returns None if approved, else a reason."""
|
|
17
|
+
|
|
18
|
+
name: str
|
|
19
|
+
|
|
20
|
+
def check(self, protocol: ProtocolSubmission) -> str | None: ...
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class MaxBslRule:
|
|
24
|
+
"""Reject protocols whose reagents exceed the allowed biosafety level."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, max_bsl: int = 2):
|
|
27
|
+
self.name = f"max_bsl_{max_bsl}"
|
|
28
|
+
self.max_bsl = max_bsl
|
|
29
|
+
|
|
30
|
+
def check(self, protocol: ProtocolSubmission) -> str | None:
|
|
31
|
+
for reagent in protocol.reagents:
|
|
32
|
+
if reagent.bsl_level > self.max_bsl:
|
|
33
|
+
return (
|
|
34
|
+
f"reagent '{reagent.name}' has BSL-{reagent.bsl_level} "
|
|
35
|
+
f"> allowed BSL-{self.max_bsl}"
|
|
36
|
+
)
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ForbiddenComboRule:
|
|
41
|
+
"""Reject protocols combining forbidden reagent pairs (glob patterns)."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, forbidden_pairs: list[tuple[str, str]]):
|
|
44
|
+
self.name = "forbidden_combos"
|
|
45
|
+
self.pairs = [(a.lower(), b.lower()) for a, b in forbidden_pairs]
|
|
46
|
+
|
|
47
|
+
def check(self, protocol: ProtocolSubmission) -> str | None:
|
|
48
|
+
names = [r.name.lower() for r in protocol.reagents]
|
|
49
|
+
for a_pat, b_pat in self.pairs:
|
|
50
|
+
for a in names:
|
|
51
|
+
for b in names:
|
|
52
|
+
if a == b:
|
|
53
|
+
continue
|
|
54
|
+
if fnmatch.fnmatch(a, a_pat) and fnmatch.fnmatch(b, b_pat):
|
|
55
|
+
return f"forbidden reagent combination: '{a}' + '{b}'"
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class MaxStepsRule:
|
|
60
|
+
"""Guard against runaway agent-generated protocols."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, max_steps: int = 100):
|
|
63
|
+
self.name = f"max_steps_{max_steps}"
|
|
64
|
+
self.max_steps = max_steps
|
|
65
|
+
|
|
66
|
+
def check(self, protocol: ProtocolSubmission) -> str | None:
|
|
67
|
+
if len(protocol.steps) > self.max_steps:
|
|
68
|
+
return f"protocol has {len(protocol.steps)} steps > max {self.max_steps}"
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class ToxicophoreRule:
|
|
73
|
+
"""Molecule-level safety: samples carrying a SMILES in
|
|
74
|
+
metadata['smiles'] are screened against curated structural alerts.
|
|
75
|
+
Hard alerts always refuse; medium alerts refuse unless the sample
|
|
76
|
+
declares matching intent (metadata['intent'], e.g. 'covalent warhead').
|
|
77
|
+
Without RDKit the rule reports 'unverified' honestly and does not block
|
|
78
|
+
(installation-gated depth, P1)."""
|
|
79
|
+
|
|
80
|
+
name = "toxicophores"
|
|
81
|
+
|
|
82
|
+
def check(self, protocol: ProtocolSubmission) -> str | None:
|
|
83
|
+
from proef.adapters.bio.tox_alerts import screen_smiles
|
|
84
|
+
for sample in protocol.samples:
|
|
85
|
+
smi = (sample.metadata or {}).get("smiles")
|
|
86
|
+
if not smi:
|
|
87
|
+
continue
|
|
88
|
+
out = screen_smiles(smi, (sample.metadata or {}).get("intent", ""))
|
|
89
|
+
if out["refuse"]:
|
|
90
|
+
from proef.adapters.bio.tox_alerts import RULES_VERSION
|
|
91
|
+
return (f"sample '{sample.sample_id}' carries "
|
|
92
|
+
f"{len(out['refuse'])} toxicophore alert(s) "
|
|
93
|
+
f"[rules {RULES_VERSION}]: "
|
|
94
|
+
+ "; ".join(f"{h['alert']} ({h['note']})"
|
|
95
|
+
for h in out["refuse"][:3]))
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
try:
|
|
100
|
+
from proef.adapters.bio.seq_alerts import SequenceScreenRule
|
|
101
|
+
except ImportError: # seq screening is optional like rdkit
|
|
102
|
+
SequenceScreenRule = None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class DurcTargetRule:
|
|
106
|
+
"""Dual-use screen on everything a protocol names: title, samples,
|
|
107
|
+
reagents. Text-level, always on, no dependencies."""
|
|
108
|
+
|
|
109
|
+
name = "durc_screen"
|
|
110
|
+
|
|
111
|
+
def check(self, protocol: ProtocolSubmission) -> str | None:
|
|
112
|
+
from proef.adapters.bio.tox_alerts import durc_screen
|
|
113
|
+
blob = " ".join([protocol.title]
|
|
114
|
+
+ [s.sample_id for s in protocol.samples]
|
|
115
|
+
+ [r.name for r in protocol.reagents]
|
|
116
|
+
# metadata is text too: descriptions must not be a
|
|
117
|
+
# DURC bypass channel
|
|
118
|
+
+ [str((s.metadata or {}).get("description", ""))
|
|
119
|
+
for s in protocol.samples])
|
|
120
|
+
hits = durc_screen(blob)
|
|
121
|
+
if hits:
|
|
122
|
+
return ("names a select agent / regulated toxin family: "
|
|
123
|
+
+ ", ".join(hits) + " — dual-use review required")
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class SafetyEngine:
|
|
128
|
+
"""Evaluates rules in order; first rejection wins. Operators compose rules;
|
|
129
|
+
agents can only ever receive (approved, reason)."""
|
|
130
|
+
|
|
131
|
+
def __init__(self, rules: list[Any] | None = None):
|
|
132
|
+
self.rules: list[Any] = list(rules) if rules else [
|
|
133
|
+
MaxBslRule(max_bsl=2),
|
|
134
|
+
MaxStepsRule(max_steps=100),
|
|
135
|
+
DurcTargetRule(),
|
|
136
|
+
ToxicophoreRule(),
|
|
137
|
+
*( [SequenceScreenRule()] if SequenceScreenRule else [] ),
|
|
138
|
+
]
|
|
139
|
+
|
|
140
|
+
def add_rule(self, rule: Any) -> None:
|
|
141
|
+
self.rules.append(rule)
|
|
142
|
+
|
|
143
|
+
def check(self, protocol: ProtocolSubmission) -> tuple[bool, str | None]:
|
|
144
|
+
for rule in self.rules:
|
|
145
|
+
reason = rule.check(protocol)
|
|
146
|
+
if reason is not None:
|
|
147
|
+
return False, f"[{rule.name}] {reason}"
|
|
148
|
+
return True, None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class LabGateway:
|
|
152
|
+
"""The ONLY path from agents to a LabAdapter. Enforces safety (P6), records
|
|
153
|
+
provenance for every run (P5). Agents see this, never the raw adapter."""
|
|
154
|
+
|
|
155
|
+
def __init__(self, lab: Any, safety: SafetyEngine, store: Any, actor: Any,
|
|
156
|
+
advisory: Any = None, governance: Any = None,
|
|
157
|
+
approver: Any = None):
|
|
158
|
+
self.lab = lab
|
|
159
|
+
self.safety = safety
|
|
160
|
+
self.store = store
|
|
161
|
+
self.actor = actor
|
|
162
|
+
self.advisory = advisory
|
|
163
|
+
self.governance = governance # {"matrix":..., "halt":..., "pause": PauseRegistry}
|
|
164
|
+
self.approver = approver
|
|
165
|
+
self.pause_poll = 1.0 # seconds between checks while a pause holds a submission
|
|
166
|
+
self.pause_timeout: float | None = None # None: wait until resumed
|
|
167
|
+
self.on_wait = None # told how long a pause held a submission, so a wall-clock budget can leave it out
|
|
168
|
+
|
|
169
|
+
def _hold_while_paused(self, protocol: ProtocolSubmission) -> str | None:
|
|
170
|
+
"""A pause HOLDS the submission and releases it on resume (recorded both ways). The global halt still wins
|
|
171
|
+
while held. Returns a rejection reason only if the halt engages or the wait times out."""
|
|
172
|
+
import os
|
|
173
|
+
import time
|
|
174
|
+
|
|
175
|
+
from proef.core.contracts import EventType
|
|
176
|
+
from proef.core.interfaces import record_for
|
|
177
|
+
pause = (self.governance or {}).get("pause")
|
|
178
|
+
if pause is None:
|
|
179
|
+
return None
|
|
180
|
+
pid = (protocol.envelope.experiment_branch_id or "").split("/", 1)[-1] or None
|
|
181
|
+
prog = os.environ.get("PROEF_PROGRAM")
|
|
182
|
+
if prog:
|
|
183
|
+
from proef.program import _slug
|
|
184
|
+
prog = _slug(prog)
|
|
185
|
+
held_at = None
|
|
186
|
+
while True:
|
|
187
|
+
blocking = pause.blocking(pid, prog)
|
|
188
|
+
if not blocking:
|
|
189
|
+
break
|
|
190
|
+
halt = self.governance["halt"].engaged()
|
|
191
|
+
if halt:
|
|
192
|
+
return f"[halt] operator stop-condition engaged while paused: {halt.get('reason', '')}"
|
|
193
|
+
if held_at is None:
|
|
194
|
+
held_at = time.monotonic()
|
|
195
|
+
self.store.append(record_for(
|
|
196
|
+
protocol.envelope, EventType.gate_decision, self.actor,
|
|
197
|
+
decision={"kind": "paused_hold", "scope": blocking.get("scope"), "reason": blocking.get("reason"),
|
|
198
|
+
"paused_by": blocking.get("by"), "title": protocol.title}))
|
|
199
|
+
if self.pause_timeout is not None and time.monotonic() - held_at >= self.pause_timeout:
|
|
200
|
+
return f"[paused] {blocking.get('scope')}: {blocking.get('reason') or 'no reason given'}"
|
|
201
|
+
time.sleep(self.pause_poll)
|
|
202
|
+
if held_at is not None:
|
|
203
|
+
if self.on_wait:
|
|
204
|
+
self.on_wait(time.monotonic() - held_at)
|
|
205
|
+
self.store.append(record_for(
|
|
206
|
+
protocol.envelope, EventType.gate_decision, self.actor,
|
|
207
|
+
decision={"kind": "pause_released", "title": protocol.title,
|
|
208
|
+
"held_seconds": round(time.monotonic() - held_at, 1)}))
|
|
209
|
+
return None
|
|
210
|
+
|
|
211
|
+
def submit(self, protocol: ProtocolSubmission) -> tuple[str | None, str | None]:
|
|
212
|
+
"""Returns (run_id, rejection_reason). run_id is None when rejected."""
|
|
213
|
+
from proef.core.contracts import EventType
|
|
214
|
+
from proef.core.interfaces import record_for
|
|
215
|
+
# halts are checked FIRST, before anything the agent can influence
|
|
216
|
+
if self.governance is not None:
|
|
217
|
+
halt = self.governance["halt"].engaged()
|
|
218
|
+
if halt:
|
|
219
|
+
self.store.append(record_for(
|
|
220
|
+
protocol.envelope, EventType.gate_decision, self.actor,
|
|
221
|
+
decision={"kind": "halt_refusal", "halt": halt,
|
|
222
|
+
"title": protocol.title}))
|
|
223
|
+
return None, ("[halt] operator stop-condition engaged: "
|
|
224
|
+
f"{halt.get('reason', '')} — all submissions "
|
|
225
|
+
"refused until cleared by a human")
|
|
226
|
+
held = self._hold_while_paused(protocol)
|
|
227
|
+
if held:
|
|
228
|
+
return None, held
|
|
229
|
+
approved, reason = self.safety.check(protocol)
|
|
230
|
+
if not approved:
|
|
231
|
+
self.store.append(record_for(
|
|
232
|
+
protocol.envelope, EventType.gate_decision, self.actor,
|
|
233
|
+
decision={"kind": "safety_refusal", "reason": reason,
|
|
234
|
+
"samples": sorted({sp.sample_id
|
|
235
|
+
for sp in protocol.samples})}))
|
|
236
|
+
return None, reason
|
|
237
|
+
# authorization matrix: three columns, enforced in code
|
|
238
|
+
if self.governance is not None:
|
|
239
|
+
column, why = self.governance["matrix"].classify(protocol)
|
|
240
|
+
if column != "autonomous" or "SOP" in why:
|
|
241
|
+
self.store.append(record_for(
|
|
242
|
+
protocol.envelope, EventType.gate_decision, self.actor,
|
|
243
|
+
decision={"kind": "authorization", "column": column,
|
|
244
|
+
"reason": why, "title": protocol.title,
|
|
245
|
+
"samples": sorted({sp.sample_id
|
|
246
|
+
for sp in protocol.samples})}))
|
|
247
|
+
if column == "never":
|
|
248
|
+
return None, f"[authorization: NEVER] {why}"
|
|
249
|
+
if column == "human":
|
|
250
|
+
ok = bool(self.approver(protocol.title)) if self.approver \
|
|
251
|
+
else False
|
|
252
|
+
if not ok:
|
|
253
|
+
return None, ("[authorization: HUMAN required] "
|
|
254
|
+
+ (f"declined: {why}" if ok is False and
|
|
255
|
+
self.approver else
|
|
256
|
+
f"no approver configured: {why}"))
|
|
257
|
+
# tighten-only advisory tier: runs solely on gate-passed protocols;
|
|
258
|
+
# may add flags or escalate to human review, never clears a refusal
|
|
259
|
+
if self.advisory is not None:
|
|
260
|
+
from proef.core.contracts import EventType
|
|
261
|
+
from proef.core.interfaces import record_for
|
|
262
|
+
adv = self.advisory.review(protocol)
|
|
263
|
+
if adv.get("flags") or adv.get("escalate"):
|
|
264
|
+
self.store.append(record_for(
|
|
265
|
+
protocol.envelope, EventType.gate_decision, self.actor,
|
|
266
|
+
decision={"kind": "advisory", "advisory": True,
|
|
267
|
+
"flags": adv["flags"],
|
|
268
|
+
"escalated": bool(adv.get("escalate"))}))
|
|
269
|
+
if adv.get("escalate"):
|
|
270
|
+
self.store.append(record_for(
|
|
271
|
+
protocol.envelope, EventType.gate_decision, self.actor,
|
|
272
|
+
decision={"kind": "advisory_escalation",
|
|
273
|
+
"reason": "escalated to human review",
|
|
274
|
+
"samples": sorted({f.get("sample", "?")
|
|
275
|
+
for f in adv["flags"]})}))
|
|
276
|
+
return None, ("[advisory] escalated to human review: "
|
|
277
|
+
+ "; ".join(f"{f['sample']}: {f['alert']}"
|
|
278
|
+
for f in adv["flags"][:2]))
|
|
279
|
+
run_id = self.lab.submit_protocol(protocol)
|
|
280
|
+
from proef.core.contracts import EventType, InstrumentInfo
|
|
281
|
+
from proef.core.interfaces import record_for
|
|
282
|
+
|
|
283
|
+
samples = [s for s in protocol.samples if not s.sample_id.startswith("ctrl")]
|
|
284
|
+
controls = [s for s in protocol.samples if s.sample_id.startswith("ctrl")]
|
|
285
|
+
def _conc_um(v: Any) -> float:
|
|
286
|
+
try:
|
|
287
|
+
return float(str(v).strip().rstrip("uMµ").strip())
|
|
288
|
+
except ValueError:
|
|
289
|
+
return 0.0
|
|
290
|
+
concs = sorted({_conc_um(s.concentration) for s in samples if s.concentration})
|
|
291
|
+
self.store.append(
|
|
292
|
+
record_for(
|
|
293
|
+
protocol.envelope,
|
|
294
|
+
EventType.lab_run,
|
|
295
|
+
self.actor,
|
|
296
|
+
artifact=None,
|
|
297
|
+
decision={
|
|
298
|
+
"run_id": run_id,
|
|
299
|
+
"protocol_id": protocol.protocol_id,
|
|
300
|
+
"title": protocol.title,
|
|
301
|
+
"assay": getattr(protocol.assay_type, "value",
|
|
302
|
+
str(protocol.assay_type)),
|
|
303
|
+
"instrument": getattr(self.lab, "name", "lab"),
|
|
304
|
+
"instrument_version": getattr(self.lab, "version", None),
|
|
305
|
+
"n_samples": len(samples),
|
|
306
|
+
"n_controls": len(controls),
|
|
307
|
+
"replicates": getattr(self.lab, "replicates", None),
|
|
308
|
+
"concentrations": concs,
|
|
309
|
+
},
|
|
310
|
+
)
|
|
311
|
+
)
|
|
312
|
+
return run_id, None
|
|
313
|
+
|
|
314
|
+
def results(self, envelope: Any, run_id: str) -> AssayResult:
|
|
315
|
+
result = self.lab.fetch_results(run_id)
|
|
316
|
+
result.envelope = envelope
|
|
317
|
+
# the result is the run that was ASKED FOR. Several adapters build an AssayResult with a fresh random id, and a verdict's evidence
|
|
318
|
+
# pointer comes from it, so the verdict would cite a run that never existed. The gateway is the one path to an adapter, so it is
|
|
319
|
+
# fixed here once for all of them.
|
|
320
|
+
result.run_id = run_id
|
|
321
|
+
return result
|
|
322
|
+
|
|
323
|
+
def capabilities(self) -> dict[str, Any]:
|
|
324
|
+
return self.lab.list_capabilities()
|