Write Safety#

The records and verdicts a write passes before anything is put: the read-only run, the write switch, a program’s bounded write authorization, held sessions, the refusal words, which machine a write lands on, and waiting for a readback to settle. Safety Chain describes how they fit together.

The read-only run, as the environment carries it.

A deployment started read-only, and the python executor’s sandbox subprocess for a run submitted with execution_mode="readonly", both set POSTURE_ENV_VAR to SANDBOX_MODE on every process they own. This module spells that variable and the one value that sandboxes, and answers the question every write path asks first: is_readonly_run().

It is a leaf: it imports nothing from this package or the framework, so the control-system connectors, the posture store, the connector host and the framework’s audit and executor layers can all ask it without importing each other. The stdlib-only PreToolUse hooks cannot import it at all and restate it in osprey_target_state; a parity test holds that copy equal to this one.

It is not osprey_connectors.posture_store, although that module’s write_verdict() asks it first: the posture store reads the deployment’s record from the agent-data root, while this answers from the environment alone, so it can be asked before any config or file is read, and from processes (the connector host, the executor’s sandbox) that must not load the record reader to know they are read-only. An operator’s narrowing of ONE control target is deliberately not here: it never lived in the environment.

osprey_connectors.posture_env.POSTURE_ENV_VAR = 'OSPREY_EXECUTION_MODE'#

The variable that carries the session posture into every child process of a run, MCP servers included.

osprey_connectors.posture_env.SANDBOX_MODE = 'readonly'#

The one value of POSTURE_ENV_VAR that sandboxes a process. A value comparison, never a presence check: the writes posture (readwrite) sets the same variable.

osprey_connectors.posture_env.is_readonly_run()[source]#

True when this process must refuse control-system writes, whatever it is.

Two things set OSPREY_EXECUTION_MODE=readonly, and this answers yes to both:

  • the deployment, when the whole run is started read-only — the variable is on every process the deployment owns, the MCP servers included, so a channel write is refused by the connector itself rather than only by the (best-effort) hook chain;

  • the python executor, onto the sandbox subprocess of a run submitted with execution_mode="readonly" — so the per-run claim is enforceable at runtime, independent of the pre-execution pattern scan.

Both are refusals; only the operator-facing wording differs, and the control-system base class decides that by which process is asking, because the two are the same variable at the same value.

This is the first term of osprey_connectors.posture_store.write_verdict() (readonly_run). Outside these two the variable is unset or readwrite, and the answer is still not “writes” by itself: the deployment’s control_system section and the control-context record both apply, through the rest of that verdict.

The comparison is by VALUE, never presence: readwrite is the writes posture, and a stale or misspelled value must not silently sandbox anything.

Return type:

bool

The write-switch reader — one field of one record, one verdict.

An operator sets one control target’s writes to off, asked or allowed from the header chip: “writes on for the stand-in, leave the virtual accelerator alone”. That switch is one field of the control-context record (osprey_connectors.control_context) and is enforced at write time rather than delivered by respawning the agent, which is what lets a flip land on a session already mid-conversation.

This module is the canonical reader of that field. Two others answer from the same file and must agree with it: the controls MCP server (which imports this one) and the stdlib-only PreToolUse hook in osprey/templates/claude_code/claude/hooks/osprey_target_state.py, which cannot import anything and therefore restates the contract below. Treat the following five rules as the contract; a change here is a change there.

1. Where the file is. One directory per identity: acting_identity() under STATE_DIR_NAME under the agent-data root, so one directory answers “control state for whoever this process is acting as”. The switch is one operator’s, not the deployment’s, and a single shared directory would make one user’s chip decide every other user’s writes. The directory resolves by ONE ladder, used by every writer and every reader:

  • CONTROL_CONTEXT_DIR_ENV_VAR when it names a non-blank path — the container’s own state directory, bound in by compose. It is already the per-identity directory, so nothing is appended to it: a container sees its own dir at a path that has nothing to do with the host’s tree, and deriving the identity hop inside it would name a directory nobody binds;

  • otherwise _AGENT_DATA_ROOT_ENV_VAR when it names a non-blank path — the stamp a session child carries — else resolve_shared_data_root(), the config derivation the state file has always used; and then the two fixed hops, STATE_DIR_NAME and the acting identity.

There is no third path and no fallback. A root that resolves to nothing makes state_dir() None, which a route surfaces as store_unavailable rather than quietly writing somewhere a reader will never look, and which write_verdict() refuses as record_unavailable.

2. What the shapes mean. The record’s switch field is a per-target map of positions, and switch_position() is its one reader: a machine is armed only at "asked" or "allowed", and a stored "on" from an older release reads as "asked". Everything else — no record, a record that does not name the machine, any other value — is that machine’s writes off. The record’s posture field is a mirror of the switch kept for readers that predate it, and no verdict reads it. parse_posture_value() is the grammar of that mirror, applied by parse_record() rather than restated there.

3. How a write is decided. write_verdict() is the whole rule: one total order of terms — read-only run, tier, target, owner, owner tier, record, switch, launch pin — and the first that refuses names the reason. Its order is shared with the hook’s stdlib twin, so a write is refused for the same reason on both sides. An allowed verdict carries the effective position: the stored one, capped by the ceiling the environment’s verdict already evaluates — the section’s tier on a host, the owner’s rung under a bound tree. A position above the ceiling refuses nothing and stays on disk. backstop_verdict() is the floor for a write no target or owner can be named for: its first two terms and nothing else, so it reports no position.

Both are blind to a session’s hold, because they also choose the gateway a connector child connects on. The hold is decided where a write executes: session_hold_refusal() asks it alone, and execution_verdict() is write_verdict() with the hold placed after its first two terms.

The switch is a property of one OWNER’s record, not of a process tree: no session key indexes it, and a process that belongs to no session — a dispatch worker, a CLI run — is decided by the same field as one that does. OSPREY_POSTURE_SESSION remains the audit session id and nothing more.

Inside an executor sandbox one further term is read, and only there: LAUNCH_POSTURE_ENV_VAR, the switch state the run was LAUNCHED under (launch_posture_stamp() writes it, _launch_pin_term() reads it). Its job is asymmetry: a machine switched off mid-run is refused by the record read, while a machine switched ON never reaches a run that started with it off, which would otherwise hand a running script write access the operator had not given it when the run began.

4. When a change is seen. Every read re-stats the record and re-parses on (st_mtime_ns, st_size, st_ino) — the cache lives in control_context, and its invalidate_cache() is the hook a process that moved roots (or a test) drops it through. A missing record is every switch off, not an error.

This module reads no config for the switch, holds no cache of its own, and imports nothing from osprey: it runs inside the connector-host child and the executor sandbox, where the dependency budget is the lean connector chain. The record reader is imported inside the functions that need it, because the import direction between the two modules is one-way — the record module imports THIS one at module scope for the root and the grammar.

5. Whose switch decides. A chip is one person’s, so a verdict needs a name as well as a target. That name is the OWNER, and it is resolved by one ladder here — current_owner(), with NO_OWNER for work that belongs to nobody — so that the write monitor and the queue never disagree about whose switch a plan runs under. The owner of a queued plan rides on the item as RESERVED_OWNER_KWARG and is bound for the wrapper’s body by bind_owner().

A container that holds no chip of its own — a lane’s queueserver, the dispatch worker — reads that owner’s record out of a read-only bind of the WHOLE tree, CONTROL_CONTEXT_TREE_ENV_VAR, rather than out of a directory of its own. That read fails CLOSED: an unprovisioned mount, a group the container could not join and a record written 0600 must not be answered as an operator who switched nothing on, nor as one whose switch nobody could read being on. So the tree reader separates the one absence that is an answer — no record for this owner, every switch off — from every failure on a path that is THERE, which refuses as record_unavailable. CONTROL_TREE_MARKER_NAME is what makes the first question answerable at all: a bind whose source does not exist is created empty by the container runtime, and an empty directory says nothing about whether it was ever built.

The invariant that binding rests on: the owner variable is read on the connector’s async path, never after a thread or executor hop. A context is copied into a task when the task is created, so the binding reaches everything a RunEngine schedules from the wrapper’s context. An offload is where that stops being true, and which helper made it decides whether it does: asyncio.to_thread copies the context and carries the binding into the thread, while loop.run_in_executor, a raw executor submit and a bare threading.Thread do not. No gate may depend on the carrying one having been chosen. A verdict taken behind such a hop would read NO_OWNER; every verdict is therefore taken before the offload.

class osprey_connectors.posture_store.NoOwner[source]#

Bases: object

The absence of an owner: one instance, compared by identity and nothing else.

None cannot carry this meaning, because current_owner() already uses None for “the caller named nobody, so walk the ladder” — a different question from “the ladder ran out”. A string cannot carry it either: every string is a name some deployment may legitimately give an account, so an owner spelled "" or "none" would be indistinguishable from a real one at the directory a verdict reads.

There is deliberately no parse in the other direction: nothing turns "<no owner>" back into this value. The string form exists so that a warning line about an owner-less plan can print it — a raising __str__ would cost the one line that says the plan ran for nobody — and printing is all it is for. Callers ask owner is NO_OWNER, never truthiness (a real name can be falsey only by being empty, which this module never produces) and never equality with the text.

osprey_connectors.posture_store.CONTROL_CONTEXT_DIR_ENV_VAR = 'OSPREY_CONTROL_CONTEXT_DIR'#

The container’s OWN state directory, bound in by compose and named in the environment of every container that holds a chip: the terminal’s web-<user>. Top rung of rule 1, and already the per-identity directory — a container’s bind target has nothing to do with the host tree’s shape, so the two fixed hops are the host derivation’s business and never appended to this. Distinct from CONTROL_CONTEXT_TREE_ENV_VAR, the read-only bind of every identity’s directory, which names no single one of them.

It belongs in NON_PINNABLE_AUDIT_MARKERS for the same reason the audit identity does: a spec that could pin it could point one user’s writes at another user’s switch.

osprey_connectors.posture_store.CONTROL_CONTEXT_TREE_ENV_VAR = 'OSPREY_CONTROL_CONTEXT_TREE'#

The read-only bind of the whole per-user control-state tree, named in the environment of a container that holds no chip of its own: a lane’s queueserver, the dispatch worker. Only its PRESENCE is read here; the tree is read by the verdict.

Presence is what makes such a container owned-or-nothing. The account it runs as names nobody whose chip anyone ever set, so falling through to acting_identity() there would read a record directory that does not exist, so a plan would be decided by nobody’s switch rather than its owner’s.

osprey_connectors.posture_store.CONTROL_OWNER_ENV_VAR = 'OSPREY_CONTROL_OWNER'#

The stamped owner of the work a process is doing, exported into a dispatch job’s environment by the dispatch worker’s sdk_runner — the one export site — and read back as the third rung of current_owner(). Always a str when it is set at all: the absence of an owner is NO_OWNER, which has no spelling, so a blank value here is the unset case and not a nameless owner.

It belongs in NON_PINNABLE_AUDIT_MARKERS for the same reason the audit identity does: a spec that could pin the owner could hand a plan another user’s switch — or take one away.

osprey_connectors.posture_store.CONTROL_TREE_MARKER_NAME = '.osprey-control-tree'#

The marker file at the root of the control-context tree, written by osprey build. Its PRESENCE is the tree reader’s first question, because a read-only bind whose host source does not exist is created empty by the container runtime — after which an unprovisioned tree is indistinguishable from a tree in which nobody has switched anything on, and a provisioning fault reads as an operator’s answer on exactly the deployment that never provisioned it.

Restated here rather than imported from osprey.deployment.compose_generator, which declares it for the writing side: this package is the lean connector chain and may not import the deployment layer. The two spellings are pinned together by a test that imports both — a drift between them is a tree that reads as unprovisioned in every container.

osprey_connectors.posture_store.DISPATCH_RUN_ENV_VAR = 'OSPREY_DISPATCH_RUN'#

a scheduled or triggered job, started by no login at a terminal. Only the value "1" marks a dispatch run; anything else, "0" included, is no dispatch. A dispatch run that names no owner resolves NO_OWNER and is refused owner_unscheduled (write_verdict()): the process account it runs as is no login whose switch could cover it.

Type:

The mark the dispatch worker’s sdk_runner sets on every job it runs

osprey_connectors.posture_store.LAUNCH_POSTURE_ENV_VAR = 'OSPREY_LAUNCH_POSTURE'#

The launch-time pin, stamped into an executor sandbox’s environment by osprey.mcp_server.python_executor.executor._apply_target_stamp and read back HERE, inside that sandbox, by _launch_pin_term().

The wire format is one "<target>=<posture>" pair and nothing else:

  • <target> is the control target the run was stamped against — a member of CONTROL_TARGETS — or _LAUNCH_POSTURE_ALL_TARGETS when the executor could not identify one, in which case the pin covers every target;

  • <posture> is POSTURE_SANDBOX or POSTURE_WRITES.

sandbox is the only value that does anything: writes is recorded so the in-flight marker states what the run launched under, and is inert here: a stamp can refuse and never grant. A missing or blank stamp is inert too, which is what makes every process that is not an executor sandbox unaffected by this term; an unparseable one refuses (_launch_pin_term()).

Spelled here rather than imported because this is the reading side and the reading side runs in the lean connector chain; registry/mcp.py and the executor import the name from this module, and it is stripped from every rendered .mcp.json env block (NON_PINNABLE_AUDIT_MARKERS) — a spec that could pin it could hand a run launched with writes off the writes it was denied.

osprey_connectors.posture_store.NO_OWNER: Final = <no owner>#

The answer every owner-less path gives. See NoOwner.

osprey_connectors.posture_store.POSTURE_SANDBOX = 'sandbox'#

the run started with the machine’s writes off. The only posture value that ever refuses anything.

Type:

The launch-pin value

osprey_connectors.posture_store.POSTURE_WRITES = 'writes'#

The run started with the machine’s writes on. Recorded so a stamp states what the run launched under; it never grants anything.

osprey_connectors.posture_store.RESERVED_OWNER_KWARG = '_osprey_owner'#

The plan kwarg an owner rides on into a queueserver worker, popped by bind_owner() before the plan’s own signature is validated against it. Reserved: it is never a plan parameter and never appears in a relayed view of a queue item.

Spelled here rather than in the bridge because the import direction between the two is one-way — the bridge imports this name; nothing in this package may import the bridge — and a reserved key restated on the far side is a key one end strips while the other leaks it into a plan’s arguments.

osprey_connectors.posture_store.STATE_DIR_NAME = 'control_target'#

Subdirectory of the agent-data root holding one directory per identity, each with that identity’s control-context record, per-server reports and request files. The same tree target_state.state_dir() resolves, spelled here because a record the writer puts in one directory and a reader looks for in another is a switch that silently never applies.

class osprey_connectors.posture_store.WriteVerdict(allowed, reason, target, kind, position=None, detail=None, authorization=None)[source]#

Bases: object

Whether one write may go ahead, and the one reason when it may not.

Variables:
  • allowed (bool) – True only when every term of write_verdict() passed.

  • reason (str | None) – None when allowed; otherwise a member of REASONS, the first term that refused. refusal_phrase() turns it, with kind, into the words an operator reads.

  • target (str | None) – The control target the caller asked about, verbatim when it was a string, else None.

  • kind (Literal['real', 'rehearsal', 'simulator'] | None) – The kind of machine target names here — real, rehearsal or simulator — or None when the target does not resolve.

  • position (Literal['asked', 'allowed'] | None) – The effective switch position when allowed — asked or allowed, the stored position capped by the environment’s ceiling — and None on every refusal and from backstop_verdict().

  • detail (str | None) – Words the refusal adds after its phrase, such as what raised a session’s hold. Not part of the decision, so verdicts compare without it.

  • authorization (str | None) – The id of the program’s write authorization the verdict was decided by (write_authorization), or None for a verdict no authorization took part in. An authorized write carries no position: the switch did not decide it.

allowed: bool#
reason: str | None#
target: str | None#
kind: Literal['real', 'rehearsal', 'simulator'] | None#
position: Literal['asked', 'allowed'] | None = None#
detail: str | None = None#
authorization: str | None = None#
__init__(allowed, reason, target, kind, position=None, detail=None, authorization=None)#
osprey_connectors.posture_store.backstop_verdict(section)[source]#

The verdict for a write no target or owner can be named for.

The floor under every write path that cannot be traced to one machine: it refuses readonly_run (OSPREY_EXECUTION_MODE), then tier_never (tier_allows()), in the same order as the first two terms of write_verdict(), and otherwise allows. It is blind by design — it resolves no target, asks no owner and opens no record, so a switch position never changes its answer and it reports none.

Parameters:

section (object) – The control_system section of the resolved config.

Returns:

A WriteVerdict whose target, kind and position are always None. Never raises: a tier that cannot be read refuses as tier_never.

Return type:

WriteVerdict

osprey_connectors.posture_store.bind_owner(kwargs)[source]#

Bind the owner riding on kwargs for the body, yielding the kwargs without it.

The one way an owner enters a queueserver worker: the bridge puts it on the item as RESERVED_OWNER_KWARG, the worker hands those kwargs to the plan wrapper, and the wrapper runs its body inside this block. The yielded mapping is what the plan’s own signature is validated against — the reserved key is gone by then, so a plan never sees an argument it does not declare.

kwargs itself is not mutated. The caller keeps whatever it was handed, and two wrappers reading the same mapping cannot race over who pops the key.

A missing key, a blank one, or one carrying anything that is not a string binds NO_OWNER: the plan reached the queue without a name, and no login’s switch can cover its writes.

The reset is an assignment to NO_OWNER, not a token restore. Plan wrappers are generators, so the set and the finally can run in different contexts, and a token from one context cannot be reset in another. There is nothing to restore in any case: owners do not nest — a run belongs to one person or to nobody — so the floor is the only correct value to leave behind, and leaving it is what stops one run’s owner from gating the next run’s writes.

Return type:

Iterator[dict[str, object]]

osprey_connectors.posture_store.bound_owner()[source]#

The owner bind_owner() bound for the running plan, and nothing else.

Rung 2 of current_owner() alone: no caller argument, no environment stamp, no process account. This is the question an attribution asks — whose queued plan is this — and the ladder’s lower rungs answer a different one: whose switch governs a write here. A record attributed through them would name the account the worker runs as rather than the person who queued the run, so outside a bind_owner() block this answers NO_OWNER.

Never raises.

Return type:

str | NoOwner

osprey_connectors.posture_store.bound_state_dir()[source]#

The CONTROL_CONTEXT_DIR_ENV_VAR bind as a path, or None unset.

The top rung of rule 1 on its own, so that the three seams resolving this directory cannot read one environment variable three different ways. Blank, whitespace-only and non-absolute values all name no bind, and a ~ is expanded — _absolute_bind() is that rule, shared with the tree bind beside it.

osprey.mcp_server.control_system.target_state.state_dir calls this rather than restating it, exactly as it calls stamped_agent_data_root().

Return type:

Path | None

osprey_connectors.posture_store.current_owner(owner=None)[source]#

The owner whose switch decides a write, by a five-rung ladder.

Most specific first:

  1. owner when the caller named one, stripped — the same normalisation the two rungs below apply, so a padded name and a bare one address one person’s directory rather than two. Passing NO_OWNER explicitly is naming one — it says “this work belongs to nobody”, which a verdict refuses — which is why the “unnamed” spelling is None and not the sentinel. A caller that names an owner with no name ("", or only spaces) is answered with that empty name rather than falling through to the rungs below: the fall-through is for a caller that named nobody, and a name no directory can hold is a lookup that fails rather than one that is not attempted.

  2. The bound context variable, set by bind_owner() from the reserved kwarg a queued plan carried. This is the rung that makes a lane’s plan obey the chip of the person who queued it.

  3. CONTROL_OWNER_ENV_VAR, the stamp a dispatch job’s environment carries. Always answered as a str; a blank or whitespace-only value is the unset case spelled differently — a rendered-but-empty environment: entry — and falls through rather than naming an owner with no name.

  4. NO_OWNER for a dispatch run (DISPATCH_RUN_ENV_VAR is "1") that none of the rungs above named an owner for. The account a scheduled job runs as is not a person, so it never stands in for one.

  5. Otherwise: NO_OWNER when a tree is bound (_tree_is_bound(), the one spelling of that question), else acting_identity(). A container holding the tree holds no chip of its own, so the account it runs as is not an answer; anywhere else the process account is the person whose chip the record was written from.

Never raises: this is read on a write path, and a lookup that cannot name an owner must produce a verdict rather than an exception.

Return type:

str | NoOwner

osprey_connectors.posture_store.execution_verdict(section, target, *, owner=None, ignore_launch_pin=False, session_keys=None)[source]#

The verdict on one write about to execute: write_verdict() plus the hold.

The terms are readonly_run, tier_never, session_held (session_hold_refusal()), then the rest of write_verdict() in its order, so a held session with its switch off refuses session_held. Its order is shared with the hook’s stdlib twin.

Parameters:
  • section (object) – The control_system section of the resolved config.

  • target (str | None) – The control target the write lands on.

  • owner (str | NoOwner | None) – As for write_verdict().

  • ignore_launch_pin (bool) – As for write_verdict().

  • session_keys (Sequence[str] | None) – As for session_hold_refusal(): the sessions the write belongs to, held while any one is; None is the environment’s session.

Returns:

A WriteVerdict with the target and kind of write_verdict(). Never raises.

Return type:

WriteVerdict

osprey_connectors.posture_store.launch_posture_stamp(target, launch_posture)[source]#

Compose the LAUNCH_POSTURE_ENV_VAR value for one launch.

The one place the wire format is written, so the executor that stamps it and _launch_pin_term() which reads it cannot disagree about the separator or about how “no target” is spelled.

Parameters:
  • target (str | None) – The control target the run is stamped against, or None when the executor could not identify one — spelled _LAUNCH_POSTURE_ALL_TARGETS, which covers every target.

  • launch_posture (str) – POSTURE_SANDBOX or POSTURE_WRITES — the recorded answer for that target at the moment of launch.

Return type:

str

osprey_connectors.posture_store.owner_tier_term(section, owner)[source]#

The owner’s tier out of control_system.login_tiers — the verdict’s owner rung.

section is the control_system section; owner the login whose record governs the write. The rung applies when the section carries the map (any value) or a control-context tree is bound (_tree_is_bound(), the one marker of a process that reads other logins’ records). Answers:

  • "skip" — the rung does not apply: no map and no tree;

  • "never" / "asked" / "allowed" — the owner’s entry;

  • "unknown" — the rung applies and the owner’s tier cannot be read: a tree with no map, a map that is not a mapping, a map with any key that is not a non-empty string or any value other than the three tier words (unreadable as a whole — it is one render’s output), an owner that is not a non-empty string, or an owner the map does not name. The verdict refuses it as owner_unknown; never refuses as tier_never.

Logins match exactly: no case folding, no trimming. Never raises.

Return type:

Literal[‘skip’, ‘never’, ‘asked’, ‘allowed’, ‘unknown’]

osprey_connectors.posture_store.parse_posture_value(value)[source]#

The record’s posture mirror as {target: "sandbox"} — the switched-off targets.

The grammar of the mirror field (rule 2), in one place: parse_record() reaches this filter rather than restating it. No verdict reads the result — the switch decides every write — so this is the shape a reader that predates the switch sees, and nothing more.

Never raises. Anything that is not a "sandbox" entry — a bare "writes", an unknown string, a non-string target key, a hand-edited or future-version shape — is dropped, so a field nobody can repair from the browser never fails a read.

Return type:

dict[str, str]

osprey_connectors.posture_store.session_hold_refusal(*, root=None, session_keys=None)[source]#

The session_held refusal for this process’s session, or None.

The session is _SESSION_KEY_ENV_VAR; a process without one belongs to no session and is never held. A process that serves several sessions at once — a panel’s data process, which starts before any conversation exists and answers a terminal’s every session — names them in session_keys instead, and is held while any one of them is. The store is root, else the stamped HOLD_DIR_ENV_VAR; without either nothing is held. Under a store, a record that cannot be read refuses.

Parameters:
  • root (Path | str | None) – The hold root, for a caller that resolved it itself.

  • session_keys (Sequence[str] | None) – The sessions to ask about, in place of the environment’s one key. An empty sequence belongs to no session; an empty key in it names none. None reads the environment.

Returns:

None when no named session is held; otherwise the first held session’s refusal, in the order given: target and kind are None and detail names that session’s open flags’ sources, each once in the order opened. An unsafe session key has no flags to name. Never raises.

Return type:

WriteVerdict | None

osprey_connectors.posture_store.stamped_agent_data_root()[source]#

The _AGENT_DATA_ROOT_ENV_VAR stamp as a path, or None unstamped.

The stamp half of rule 1 on its own, so that the files under this root cannot read one environment variable two different ways. A blank or whitespace-only stamp is no stamp, and a ~ in it is expanded: a reader that took either literally would look in a directory no writer ever creates, which is the silently-ignored-switch failure rule 1 exists to prevent. The expansion is os.path.expanduser(), for the reason _absolute_bind() uses it: the Path method raises for a ~ naming a user this process cannot resolve, and this is read on a write path.

Unlike a bind, a stamp is not required to be absolute: it is written by a process that shares this one’s working directory rather than by a compose file describing another host’s layout.

osprey.mcp_server.control_system.target_state.state_dir calls this rather than restating it. The CONFIG half below is deliberately not shared: that module raises where this one answers None, and a route turns its raise into a store_unavailable 503.

Return type:

Path | None

osprey_connectors.posture_store.state_dir()[source]#

This identity’s control-state directory, or None.

Rule 1 of the module contract: the bound_state_dir() bind when a container carries one, else the acting identity under STATE_DIR_NAME under _agent_data_root().

The identity is resolved on every call rather than once at import, because acting_identity() reads an environment that compose and the entrypoint set per process; a value frozen at import would be whatever the first importer happened to see. It never fails — an unresolvable identity is UNKNOWN_IDENTITY, a real directory holding the state of whoever could not be named, which is a switch that applies rather than one that silently does not.

A None here is what a route reports as store_unavailable: there is nowhere to record a switch that any reader would find.

Return type:

Path | None

osprey_connectors.posture_store.write_ceiling(section, owner, *, tree_bound=None)[source]#

The highest position a write by owner runs at: the verdict’s ceiling.

Under a bound tree the owner’s rung (owner_tier_term()), otherwise tier_writes() of section. The ceiling caps an allowed verdict’s position and refuses nothing itself; the tier and rung terms of write_verdict() do that. tree_bound answers for a process other than this one (None: _tree_is_bound()). Never raises.

Return type:

Literal[‘never’, ‘asked’, ‘allowed’, ‘unknown’]

osprey_connectors.posture_store.write_verdict(section, target, *, owner=None, ignore_launch_pin=False)[source]#

The verdict on one write to target: one total order, first refusal wins.

The terms, in order — the order is shared with the hook’s stdlib twin, so a write is refused for the same reason on both sides:

  1. readonly_run — the run is read-only (OSPREY_EXECUTION_MODE).

  2. tier_never — the section’s tier does not allow writes (tier_allows()).

  3. target_unknown — target does not resolve in this deployment.

  4. owner_unknown — the owner ladder (current_owner()) yields NO_OWNER or anything that is not a non-empty name. A write with no owner is refused; nothing is governed by the ceiling alone here. owner_unscheduled in its place for a dispatch run (DISPATCH_RUN_ENV_VAR), whether the caller passed NO_OWNER or the ladder resolved it: a scheduled or triggered job that runs for no login has no switch to follow. owner_foreign — with no tree bound, an owner that is not acting_identity(): a host holds only its own login’s switch and never lends it to another owner.

  5. The owner rung (owner_tier_term()): a login the map does not name, or a map that cannot be read where the rung applies, is owner_unknown; a login mapped never is tier_never.

  6. record_unavailable — the record governing the write could not be read. Under a bound tree that is the owner’s record, through the no-follow, fail-closed tree reader; a bind that is set but unusable refuses rather than falls back to the host. Otherwise it is this host’s own record, through the status reader, which fails closed too: a corrupt file, a foreign schema or an unresolvable root refuses. A record that is simply absent is not unavailable — it is every switch off.

  7. switch_off — the record’s stored position for target (switch_position()) is off. The record’s posture field is not read: it mirrors the switch, and an old sandbox value left in a file does not refuse.

  8. launch_pinned — the launch pin (_launch_pin_term()) is pinned or unreadable for target; skipped when ignore_launch_pin, for a caller that reports the pin on its own.

An allowed verdict’s position is the lower of the stored position and write_ceiling(): tier_writes() of section on a host (term 2), the owner’s rung under a bound tree (term 5). The ceiling adds no refusal.

Tier and owner rung come before the record, so a demoted login’s position stays on disk, inert, and arms again if the tier is restored. This function reads and never writes. It never answers switching or stopped_since: those belong to the callers that hold the record’s lock.

Parameters:
  • section (object) – The control_system section of the resolved config.

  • target (str | None) – The control target the write lands on.

  • owner (str | NoOwner | None) – Whose record governs the write; None asks current_owner().

  • ignore_launch_pin (bool) – Skip the last term.

Returns:

an exception anywhere in the terms refuses rather than allows.

Return type:

A WriteVerdict. Never raises

A program’s bounded write authorization: which channels, which values, how many writes.

The write switch is a person’s gesture over a whole machine. A program such as an optimizer needs less than that and must get no more: an authorization (a grant) names one machine, the login whose switch it stands in for (the owner), the identity that may use it (the holder), a closed range per channel, a budget of write steps, a hard expiry, a lease the holder renews, and who approved it. Every write the holder makes is checked against it; it ends at an exhausted budget, an expiry, a lapsed lease or a stop, and nothing renews the budget. The machine’s switch may stay off throughout.

This module owns the two files, their readers and their writers, and the verdict. The write guard of every control-system connector (ControlSystemConnector) asks authorized_execution_verdict() for every write call of a process that names an authorization (AUTHORIZATION_ENV_VAR), spending its step, and the connector-host pool sets that variable for a child whose key names one; a gateway choice and a child’s report take authorized_write_verdict().

1. Two files, two writers. The grant is <authorizations dir>/<id>.json, written once by the approver’s process and afterwards only to mark it revoked (_issue_grant(), revoke_grants()). The authorizations directory is the owner’s: AUTHORIZATIONS_DIR_NAME inside the owner’s directory of the read-only control-context tree when one is bound, else inside this host’s state_dir(). The ledger is <ledger dir>/<id>.ledger.json, written only by the holder: the holder opens it with its lease (start_lease()), its heartbeat renews the lease (renew_lease()), and the connector child appends one step per write call (_spend()). The ledger directory is LEDGER_DIR_ENV_VAR, else, on a host with no tree bound, the host’s authorizations directory; under a bound tree with no ledger directory there is none, and every write refuses. The control-context record is not touched: control_context.json keeps its schema and its seven fields.

2. Reads fail closed. Both files are read the way the posture store reads the tree (_read_tree_context()): no symbolic link is followed at any directory below the root or at the file (the file is opened O_NOFOLLOW), the read is bounded, the file must be a regular file, and the payload must be exactly this schema — every field present, of its type, no other field, no repeated key, every number finite. A grant that is absent is no authorization (switch_off); every failure on a path that is there refuses (auth_unreadable), and so do a missing or unusable ledger directory and a ledger that cannot be read. A ledger that is absent has no lease, and refuses auth_lease_lapsed.

3. The verdict. _verdict() judges one write call — a whole batch of (channel, value) operations — in one total order: the launch pin (_launch_pin_term(), read here because the switch verdict reaches it only with the switch on), the owner, the record, the grant, its holder and owner, its machine, a stop, its expiry, the switch position for a self-issued grant, every channel listed and every value a finite number in its range, the lease, and a step left. It does not repeat the switch verdict’s earlier terms; authorized_execution_verdict() is the composition a write path takes: the execution verdict first, and for a process that names an authorization, whenever that verdict allows or refuses only switch_off, this one in its place. An authorization never lifts a tier, an unknown owner, an unreadable record, a pin or a hold, and a person turning the switch on mid-run never lifts the bounds.

4. One write call is one step. _spend() takes the ledger’s lock (an exclusive flock on <ledger>.lock beside it, as session_hold takes its record’s), re-judges the whole verdict against the ledger it read under that lock, and appends the step through atomic_replace() before it answers. The caller writes only after an allowed answer, so a crash between the two costs the step and never writes unbudgeted. Concurrent appenders in any number of processes on one kernel are serialised by the lock.

A step is spent before the connector’s own checks run: a write the limits database then refuses has still spent it, and so has one whose put fails. Both fail closed. A stop that lands after a write call’s verdict and before its put does not reach that one call, which goes out as judged; the next call is refused. The switch’s own verdict has the same window.

5. The lease. The holder renews lease_until_ns; a lease that lapses ends the authorization for good — renew_lease() refuses once it has lapsed. Where the reader shares the holder’s PID namespace, the holder’s PID, its start time and its state are also asked (_pid_namespace(), _process_start_time()): a dead, reused or zombie PID lapses the lease before its time. From another namespace the lease time alone decides.

6. Self-issue at ``allowed``. A holder whose owner’s switch stands at allowed for the machine may write its own grant into its ledger directory (self_issue()), with approver surface write_switch. Such a grant is honoured only while the position stays allowed: the first write after it leaves allowed is refused and lapses the lease, so the switch coming back does not revive it. A grant found in the ledger directory that claims any other surface is not honoured at all, because the holder can write there.

7. Overlap. Two programs steering one channel of one machine is never what an approver meant: _auth_overlap() finds the live grant of another holder sharing a channel, and _issue_grant() refuses auth_overlap under the directory’s lock, so two approvals cannot both pass the check. A grant whose every ledger in sight shows its lease time passed, by a grace for clock skew, does not count: no write may use it. This assumes a holder keeps one ledger directory per authorization; start_lease() refuses only a ledger already in its own directory, so a second lease under the same id elsewhere is not covered. The check reads the owner’s own directory and the holders’ self-issued grants in the ledger directories this process sees (self_issued_directories()); another owner’s directory is not read. A grant file that cannot be read is logged and left out of the check: it refuses every write under it already, and a file nobody can clear from the chip must not veto every approval.

8. Requests, approval and the stop. A holder asks with a request, <ledger dir>/requests/<id>.json (write_request()), read the way a grant is read (_parse_request(), list_requests()); a web terminal reads the holders’ requests from a read-only bind, REQUESTS_DIR_ENV_VAR. A person acting as the owner approves it (approve_request()): under the owner’s record lock, then the grants directory’s — the one lock order every writer of both keeps — the grant is written under the request’s own id, so the holder waits for exactly that id (approved_grant()). The switch’s own writer, set_switch(), revokes every grant on the machines a stop names inside its record lock (revoke_grants()), so a stop is one gesture and refuses the next write; a stop whose marks cannot be written moves the record’s epoch instead, which ends every grant of that owner. Every lock here is created at 0o660 whatever the umask, because a grants directory is written by several uids through its group. A listing removes grants that ended more than _PRUNE_AFTER_S ago (prune_grants()).

This module imports nothing from osprey and sits above the record and the posture store, which it reads.

osprey_connectors.write_authorization.AUTHORIZATIONS_DIR_NAME: Final = 'authorizations'#

The directory under an identity’s control-state directory holding its grants.

osprey_connectors.write_authorization.AUTHORIZATION_ENV_VAR: Final = 'OSPREY_WRITE_AUTHORIZATION'#

the id of the authorization its writes are judged by.

Type:

The environment variable a holder’s connector child carries

osprey_connectors.write_authorization.LEDGER_DIR_ENV_VAR: Final = 'OSPREY_WRITE_LEDGER_DIR'#

The environment variable naming the holder’s ledger directory, a path in the holder’s own filesystem that it can write.

osprey_connectors.write_authorization.LEDGER_VIEW_DIR_ENV_VAR: Final = 'OSPREY_WRITE_LEDGER_VIEW_DIR'#

a read-only bind of the holders’ ledger directory, where their self-issued grants are, so an approval there checks overlap against them and the chip lists them. Never LEDGER_DIR_ENV_VAR: the terminal is not a holder and writes nothing there.

Type:

The environment variable a web terminal carries

osprey_connectors.write_authorization.MAX_EXPIRES_S: Final = 86400.0#

The longest a grant may stand from its issue, or a request from its asking: a day, three times the optimizer’s eight-hour default.

osprey_connectors.write_authorization.MAX_STEPS: Final = 100000#

far above any run’s evaluations, so no plan, typo or forged file asks for an unbounded budget.

Type:

The most write calls one grant or request may allow

osprey_connectors.write_authorization.REQUESTS_DIR_ENV_VAR: Final = 'OSPREY_WRITE_REQUESTS_DIR'#

The environment variable naming the directory a web terminal reads holders’ requests from: a read-only bind of <ledger dir>/requests.

osprey_connectors.write_authorization.REQUESTS_DIR_NAME: Final = 'requests'#

The directory under a holder’s ledger directory its requests are written to.

osprey_connectors.write_authorization.SELF_ISSUE_SURFACE: Final = 'write_switch'#

The surface of a self-issued grant.

class osprey_connectors.write_authorization.Approver(identity, surface, at_ns)[source]#

Bases: object

Who recorded the approval, from which surface, and when.

identity: str#
surface: Literal['chip', 'cli', 'write_switch']#
at_ns: int#
__init__(identity, surface, at_ns)#
exception osprey_connectors.write_authorization.AuthorizationRefused(reason, detail=None)[source]#

Bases: Exception

A writer of this module refused, for one of the refusal reasons.

Variables:
  • reason – A member of REASONS.

  • detail – What the refusal adds after its phrase, or None.

__init__(reason, detail=None)[source]#
class osprey_connectors.write_authorization.ChannelRange(min, max)[source]#

Bases: object

The closed range of values one channel may be written with.

min: float#
max: float#
holds(value)[source]#

Whether value is a finite real number inside the range.

Return type:

bool

__init__(min, max)#
class osprey_connectors.write_authorization.Grant(id, owner, holder, target, switch_epoch, channels, steps, issued_at_ns, expires_at_ns, lease_s, approver, label='', revoked=None)[source]#

Bases: object

One authorization, as its file states it. Treat as immutable.

Variables:
  • id (str) – uuid4().hex; the file is <id>.json.

  • owner (str) – The login whose switch the grant stands in for.

  • holder (str) – The acting identity that may write under it.

  • target (str) – The control target it covers.

  • switch_epoch (int) – The owner’s record’s switch_epoch at issue; a record whose epoch has moved since (a stop of every machine) ends it.

  • channels (collections.abc.Mapping[str, osprey_connectors.write_authorization.ChannelRange]) – {address: ChannelRange}, at least one.

  • steps (int) – How many write calls it allows, at least one.

  • issued_at_ns (int) – When it was written.

  • expires_at_ns (int) – When it ends whatever else happens.

  • lease_s (float) – How long one renewal of the holder’s lease lasts.

  • approver (osprey_connectors.write_authorization.Approver) – Who approved it.

  • label (str) – The run it was approved for, free text.

  • revoked (osprey_connectors.write_authorization.Revocation | None) – The stop that ended it, or None.

id: str#
owner: str#
holder: str#
target: str#
switch_epoch: int#
channels: Mapping[str, ChannelRange]#
steps: int#
issued_at_ns: int#
expires_at_ns: int#
lease_s: float#
approver: Approver#
label: str = ''#
revoked: Revocation | None = None#
to_payload()[source]#

This grant as the JSON object its file holds.

Return type:

Mapping[str, object]

live_at(now_ns)[source]#

Not revoked and not expired at now_ns. The lease is the ledger’s.

Return type:

bool

__init__(id, owner, holder, target, switch_epoch, channels, steps, issued_at_ns, expires_at_ns, lease_s, approver, label='', revoked=None)#
class osprey_connectors.write_authorization.GrantStanding(grant, in_force, used, ledger)[source]#

Bases: object

One grant as a listing shows it: whether it stands, and what its holder spent.

Variables:
  • grant (osprey_connectors.write_authorization.Grant) – The grant.

  • in_force (bool) – _grant_in_force(), and the holder’s ledger has not ended it: a grant whose lease lapsed or whose every step is spent refuses the next write, so it is not shown standing.

  • used (int | None) – The steps the ledger counts; 0 while there is no ledger yet, None when it cannot be read.

  • ledger (osprey_connectors.write_authorization.Ledger | None) – The ledger read, or None.

grant: Grant#
in_force: bool#
used: int | None#
ledger: Ledger | None#
__init__(grant, in_force, used, ledger)#
class osprey_connectors.write_authorization.Ledger(authorization, holder_pid, holder_start, pid_ns, lease_until_ns, steps=<factory>)[source]#

Bases: object

The holder’s consumption of one authorization. Treat as immutable.

Variables:
  • authorization (str) – The grant’s id.

  • holder_pid (int | None) – The PID of the process that renews the lease, or None to rely on the lease time alone.

  • holder_start (str | None) – That process’s start time as the kernel states it, so a reused PID is not taken for it; None where nothing states it.

  • pid_ns (str | None) – That process’s PID namespace (_pid_namespace()), so a reader in another namespace does not look its PID up.

  • lease_until_ns (int) – When the lease lapses unless renewed first.

  • steps (tuple[osprey_connectors.write_authorization.LedgerStep, ...]) – Every write call spent, in order, numbered from 1.

authorization: str#
holder_pid: int | None#
holder_start: str | None#
pid_ns: str | None#
lease_until_ns: int#
steps: tuple[LedgerStep, ...]#
to_payload()[source]#

This ledger as the JSON object its file holds.

Return type:

Mapping[str, object]

__init__(authorization, holder_pid, holder_start, pid_ns, lease_until_ns, steps=<factory>)#
class osprey_connectors.write_authorization.LedgerStep(n, at_ns, channels)[source]#

Bases: object

One write call spent: its number, when, and the channels it named.

n: int#
at_ns: int#
channels: tuple[str, ...]#
__init__(n, at_ns, channels)#
class osprey_connectors.write_authorization.Revocation(at_ns, by)[source]#

Bases: object

A stop that ended a grant: when, and whose gesture.

at_ns: int#
by: str#
__init__(at_ns, by)#
class osprey_connectors.write_authorization.WriteRequest(id, owner, holder, target, channels, steps, requested_at_ns, expires_at_ns, lease_s, label='', completion='none')[source]#

Bases: object

A holder asking for an authorization: what a person approves. Treat as immutable.

The holder writes it into <ledger dir>/requests/<id>.json; an approval issues the grant under the same id, so the holder knows which authorization to wait for and name.

Variables:
  • id (str) – uuid4().hex; the grant approved from it has the same id.

  • owner (str) – The login whose switch the run stands in for, who approves.

  • holder (str) – The acting identity that will write.

  • target (str) – The control target.

  • channels (collections.abc.Mapping[str, osprey_connectors.write_authorization.ChannelRange]) – {address: ChannelRange}, each address spelled exactly as the holder will write it.

  • steps (int) – The write calls the run will make, its completion’s included.

  • requested_at_ns (int) – When the request was written.

  • expires_at_ns (int) – When the authorization is to end whatever happens.

  • lease_s (float) – How long one renewal of the holder’s lease lasts.

  • label (str) – The run, free text.

  • completion (Literal['none', 'apply_best', 'restore']) – Which completion the run will perform (_COMPLETIONS).

id: str#
owner: str#
holder: str#
target: str#
channels: Mapping[str, ChannelRange]#
steps: int#
requested_at_ns: int#
expires_at_ns: int#
lease_s: float#
label: str = ''#
completion: Literal['none', 'apply_best', 'restore'] = 'none'#
to_payload()[source]#

This request as the JSON object its file holds.

Return type:

Mapping[str, object]

grant(*, switch_epoch, approver, issued_at_ns)[source]#

The grant approving this request exactly as asked, under its id.

Return type:

Grant

__init__(id, owner, holder, target, channels, steps, requested_at_ns, expires_at_ns, lease_s, label='', completion='none')#
osprey_connectors.write_authorization.approve_request(request, *, surface, record_file=None, peers=None, approver=None)[source]#

Issue the grant for request, as the person acting as its owner approves it.

The approver’s one writer, for the chip and the CLI. record_file is the owner’s control-context record — on a host, record_path() when the owner is this process’s identity; under a deployment, the owner’s file in the tree. The grant is written into the authorizations directory beside it.

Inside one hold of the record lock (the lock order every writer of both keeps: the record, then the grants directory): the record is read — one that cannot be read refuses, one that is not there is created on the request’s machine with every switch off, and one with no epoch is given one — the grant is stamped with that epoch, and _issue_grant() checks it against every grant in the directory and the self-issued ones in peers (default: self_issued_directories()) before writing. A stop of every machine moving the epoch after this ends the grant; a stop of this machine that lands after it marks it revoked.

The caller checks what this module cannot: that the acting person is the owner, the owner’s tier, and the limits database.

Parameters:
  • request (WriteRequest) – What the holder asked for; the grant is exactly that.

  • surface (Literal['chip', 'cli']) – chip or cli.

  • record_file (Path | None) – The owner’s record; None is this host’s own, which only the owner’s own process may use.

  • peers (Iterable[Path] | None) – The ledger directories whose self-issued grants are checked for overlap.

  • approver (str | None) – Who approves; None is this process’s acting identity.

Returns:

The grant written.

Raises:
  • ValueError – surface is not an approval surface, or the grant is past a ceiling (_within_ceilings()); nothing is written.

  • AuthorizationRefused – record_unavailable for an unreadable record; auth_expired for a request whose expiry has passed; auth_overlap from the issue; owner_foreign for no record_file and an owner who is not this process.

  • FileExistsError – The request is approved already.

  • RuntimeError – A lock was not acquired in time, or no record path resolves.

  • OSError – A write failed.

Return type:

Grant

osprey_connectors.write_authorization.approved_grant(authorization, *, owner=None)[source]#

The grant issued for authorization, still in force, or None while there is none.

The holder’s wait after write_request(): an approval issues the grant under the request’s own id, so the holder polls this with the id it asked under, then opens its lease (start_lease()) and names the id (AUTHORIZATION_ENV_VAR).

Raises:
  • ValueError – authorization is not an id.

  • AuthorizationRefused – The grant is there and does not stand — unreadable, another holder’s, revoked or expired — or the owner’s record cannot be read.

Return type:

Grant | None

osprey_connectors.write_authorization.authorizations_dir(owner=None)[source]#

The directory owner’s grants live in, as this process reaches it.

owner None is this process’s acting identity. None when this process reaches no such directory: a host asked about another login, an unusable tree bind or an owner that is not one path segment.

Return type:

Path | None

osprey_connectors.write_authorization.authorized_execution_verdict(section, target, operations, *, authorization, owner=None, session_keys=None, spend=False)[source]#

The verdict on one write call about to execute, for a process that may hold a grant.

execution_verdict() first. A process naming no authorization gets that verdict unchanged. One that names one gets it whenever it refuses for any reason but switch_off — an authorization lifts no tier, owner, record, pin or hold — and otherwise, whether the switch allowed or was off, the authorization’s verdict in its place: a person turning the switch on mid-run does not lift the bounds.

Parameters:
  • section (object) – The control_system section of the resolved config.

  • target (str | None) – The control target the write lands on.

  • operations (Sequence[tuple[str, object]] | Mapping[str, object]) – The write call’s (channel, value) pairs.

  • authorization (str | None) – The id the process names, or None.

  • owner (str | NoOwner | None) – As for _verdict().

  • session_keys (Sequence[str] | None) – As for execution_verdict().

  • spend (bool) – Spend the step (_spend()) rather than only judge.

Return type:

WriteVerdict

The record is read once: the authorization’s terms are judged on the record the switch verdict read, and a self-issued grant’s position on that verdict’s own answer.

Returns:

A WriteVerdict. Never raises.

Return type:

WriteVerdict

osprey_connectors.write_authorization.authorized_write_verdict(section, target, *, authorization, owner=None)[source]#

Whether a process may write to target at all: the gateway’s and the report’s answer.

write_verdict() for a process naming no authorization. For one that names one, composed as authorized_execution_verdict() composes the execution verdict, with the authorization judged on every term but the channels and values: the grant in force, the lease live and a step left. It names no hold, as the switch verdict names none, because the gateway a connector selects must not follow a session’s hold. It reads and never spends.

Returns:

A WriteVerdict. Never raises.

Return type:

WriteVerdict

osprey_connectors.write_authorization.grant_standing(grant, record, ledger_dirs, *, now_ns=None)[source]#

Whether grant still stands for a listing, its holder’s ledger asked.

The ledger is the first one found in ledger_dirs (the holder’s ledger directory as this process sees it); a directory that is not there is skipped. Every surface that lists grants — the chip, its listing, the CLI and osprey status — answers through this, so they agree.

Return type:

GrantStanding

osprey_connectors.write_authorization.ledger_dir()[source]#

This process’s ledger directory, or None when it has none (rule 1).

Return type:

Path | None

osprey_connectors.write_authorization.list_grants(directory)[source]#

Every grant file in directory: the grants read, and the paths that could not be.

A file is a grant file by its name, <id>.json; ledgers and locks beside them are not. A missing directory holds none.

Raises:

OSError – The directory is a link or cannot be listed.

Return type:

tuple[tuple[Grant, …], tuple[Path, …]]

osprey_connectors.write_authorization.list_requests(directory)[source]#

Every request file in directory: the requests read, and the paths that could not be.

A missing directory holds none.

Raises:

OSError – The directory is a link, not a directory, or cannot be listed.

Return type:

tuple[tuple[WriteRequest, …], tuple[Path, …]]

osprey_connectors.write_authorization.listed_grants(owner_dirs, ledger_dirs)[source]#

Every grant in owner_dirs and every self-issued one in ledger_dirs, each once.

Each with the directory it was found in, and the paths that could not be read: a grant file, or a directory that cannot be listed. Nothing is written and nothing pruned.

Return type:

tuple[list[tuple[Grant, Path]], list[Path]]

osprey_connectors.write_authorization.named_authorization()[source]#

The authorization AUTHORIZATION_ENV_VAR names, or None.

Blank is unset. A value that is not a well-formed id is returned as it is, so the verdict refuses it rather than treating the process as naming none.

Return type:

str | None

osprey_connectors.write_authorization.prune_grants(directory, *, now_ns=None, after_s=_PRUNE_AFTER_S)[source]#

Remove the grants in directory that ended more than after_s ago; the ids removed.

A grant has ended once it is revoked or expired; a grant still in force, and one that cannot be read, are left alone (an unreadable file refuses every write already, and its owner should see it). Under the directory’s lock, so an issue in flight is not overtaken. A missing directory holds none. Never removes a ledger, which is the holder’s.

Raises:
  • RuntimeError – The lock was not acquired in time.

  • OSError – The directory is not a plain directory, or a removal failed.

Return type:

tuple[str, …]

osprey_connectors.write_authorization.read_request(path)[source]#

The request at path, read the fail-closed way.

The file is opened O_NOFOLLOW, must be a regular file under the read limit, must parse, and must be named for its own id (<id>.json).

Raises:
  • FileNotFoundError – Nothing is at path.

  • OSError – A link, not a regular file, too long, or unreadable.

  • ValueError – Not a request this version can read, or named for another id.

Return type:

WriteRequest

osprey_connectors.write_authorization.renew_lease(authorization, *, owner=None)[source]#

Move the lease on by the grant’s lease_s, if this process holds it and it is live.

A compare-and-swap under the ledger’s lock. False writes nothing: the ledger is absent or unreadable, another process holds the lease, the lease has lapsed (a lapsed lease never comes back), or the grant is no longer in force. Never raises.

Return type:

bool

osprey_connectors.write_authorization.requests_dir()[source]#

Where this process reads requests: REQUESTS_DIR_ENV_VAR, else its ledger’s.

A web terminal is handed the holders’ request directory read-only; a holder, or a host with no bind, reads <ledger dir>/requests. None when neither is reachable.

Return type:

Path | None

osprey_connectors.write_authorization.revoke_grants(*, by, targets=None, directory=None, ids=None)[source]#

Mark every unrevoked grant in directory on targets revoked; the ids marked.

The stop’s half in the grants directory: targets None is every machine. ids, when given, narrows the mark to those grants: a person revoking one authorization from a list. The mark is {"at_ns", "by"} and is never removed, so the next write under any of these refuses auth_revoked. A grant file that cannot be read is left as it is — it already refuses every write. directory defaults to this process’s own authorizations directory.

Raises:
  • RuntimeError – No directory is reachable, or the lock was not acquired.

  • OSError – The directory is not a plain directory, or a write failed.

Return type:

tuple[str, …]

osprey_connectors.write_authorization.self_issue(section, target, channels, *, steps, expires_at_ns, lease_s, label='', owner=None)[source]#

Write this holder’s own grant while its owner’s switch stands at allowed.

The switch verdict for target must allow at allowed (launch pin included), and the owner’s record must carry an epoch. The grant is written into this process’s ledger directory with approver surface write_switch, then the verdict is taken again: if the switch moved or a stop came in between, the grant is removed and the issue refused. It is honoured afterwards only while the position stays allowed; the first write after it leaves allowed ends it for good (_spend()).

Raises:
  • ValueError – The channels, steps, expiry or lease are malformed, or past a ceiling (_within_ceilings()).

  • AuthorizationRefused – The switch verdict’s reason; auth_revoked when it allows below allowed or moved during the issue; record_unavailable for a record with no epoch; auth_unreadable for no usable ledger directory.

  • RuntimeError – The lock was not acquired in time.

  • OSError – The write failed.

Return type:

Grant

osprey_connectors.write_authorization.self_issued_directories()[source]#

Where self-issued grants are, as this process sees them.

This process’s own ledger directory (ledger_dir()), and the holders’ ledger directory a web terminal carries read-only (LEDGER_VIEW_DIR_ENV_VAR); either may be absent.

Return type:

tuple[Path, …]

osprey_connectors.write_authorization.start_lease(authorization, *, owner=None)[source]#

Open the ledger for authorization, with this process as the lease’s holder.

Called once, by the process that will renew the lease. It records this process’s PID, start time and PID namespace and a lease of the grant’s lease_s from now, with no step spent. A ledger is opened once: one that exists already — a lease started before, live or lapsed — refuses, so a holder that crashed does not come back under the same authorization.

Raises:
  • ValueError – authorization is not an id.

  • AuthorizationRefused – The grant is absent, unreadable, not this holder’s, revoked or expired (its reason), there is no usable ledger directory (auth_unreadable), or the ledger exists (auth_lease_lapsed).

  • RuntimeError – The ledger stayed locked past the bounded wait.

  • OSError – The write failed.

Return type:

Ledger

osprey_connectors.write_authorization.withdraw_request(request_id)[source]#

Remove this holder’s request request_id; whether a file was removed.

For the holder once its grant is issued, or when its run ends without one. The grant, if any, is untouched.

Raises:
  • ValueError – request_id is not an id.

  • AuthorizationRefused – auth_unreadable for no usable ledger directory.

Return type:

bool

osprey_connectors.write_authorization.write_request(target, channels, *, steps, expires_at_ns, lease_s, label='', completion='none', owner=None)[source]#

Ask for an authorization: write a request into this holder’s ledger directory.

The holder is this process’s acting identity, the owner the login the owner ladder names (current_owner()). The file is <ledger dir>/requests/<id>.json; the directory is created there when absent. Nothing is approved by writing it: a person approves it from the chip or the CLI, which issues the grant under the same id (approved_grant() waits for it), or the holder self-issues at allowed (self_issue()).

Raises:
  • ValueError – The channels, steps, expiry, lease or completion are malformed, or the steps, expiry or lease are past a ceiling (_within_ceilings()); nothing is written.

  • AuthorizationRefused – owner_unknown; auth_unreadable for no usable ledger directory.

  • OSError – The write failed.

Return type:

WriteRequest

Why a write is refused, and who can lift the refusal, as one importable contract.

A refusal carries a reason (a member of REASONS) and a phrase that says what stopped the write and ends with who can lift it. refusal_text() is the phrase plus a trailer line [osprey-refusal: <reason>]; every refusal a write path returns to the agent ends with it, so a reader recovers the reason without parsing the words. The package’s verdict, the connector monitor and the stdlib-only hook twin all speak these words; the hook twin restates the tables and a parity test pins them to this module.

No phrase names a config key, a file, an environment variable or a build command: the reader of a refusal is an operator or an agent, not the person who edits the deployment. STORE_PATH_MARKERS holds the path spellings of the posture store (the directory part and the record’s file name) so that a text meant for an agent can be scanned for them.

Reasons are added by the phase that first consumes them; none is speculative.

osprey_connectors.refusals.KIND_WORDS: dict[str, str] = {'real': 'the live machine', 'rehearsal': 'the rehearsal machine', 'simulator': 'the simulator'}#

The words a machine kind adds to a phrase.

osprey_connectors.refusals.REASONS: tuple[str, ...] = ('readonly_run', 'tier_never', 'session_held', 'target_unknown', 'owner_unknown', 'owner_unscheduled', 'owner_foreign', 'record_unavailable', 'switch_off', 'launch_pinned', 'switching', 'stopped_since', 'auth_unreadable', 'auth_holder', 'auth_channel', 'auth_range', 'auth_exhausted', 'auth_lease_lapsed', 'auth_expired', 'auth_revoked', 'auth_overlap')#

The closed set of refusal reasons.

osprey_connectors.refusals.STORE_PATH_MARKERS: tuple[str, ...] = ('control_target', 'control_context.json')#

the state directory part and the record file.

Type:

Path spellings of the posture store

osprey_connectors.refusals.refusal_phrase(reason, kind=None)[source]#

The phrase for reason; a known kind names the machine it concerns.

Raises ValueError for a reason outside REASONS. An unknown or absent kind leaves the phrase as it is.

Return type:

str

osprey_connectors.refusals.refusal_text(reason, kind=None, *, detail=None)[source]#

The refusal a write path returns: the phrase, then [osprey-refusal: <reason>].

detail — what the refusing surface adds, such as which tool was refused — follows the phrase on its line. The trailer is its own last line, so it ends the text whatever the caller adds. Raises ValueError for a reason outside REASONS, as refusal_phrase() does.

Return type:

str

The session hold record: one durable file per session that holds its writes.

A hold is a set of open flags on one session. While any flag is open the session is held, and every write execution site refuses the session’s writes (session_held). A flag is closed only by an answer that names it. This module owns the record’s format, its reader and its writer; it knows nothing about who opens a flag — a flag carries an opaque source and reason.

The store. Every call takes root; None reads HOLD_DIR_ENV_VAR (OSPREY_SESSION_HOLD_DIR). An unset or empty root is no hold store: nothing is written and nothing is ever held. Under a root, one session’s record is <root>/<session_key>/record.json.

Fail closed under a root. is_held() answers True for an open flag, and equally for a missing session directory, a missing record, a record that cannot be read or parsed, a record of another schema, a symbolic link at the session directory or the record, and an unsafe session key. It never raises. open_flags() reports an unreadable record as the one synthetic flag UNREADABLE_FLAG_ID; answering that flag rewrites a fresh record (with the synthetic flag kept, closed, for audit). Nothing else rewrites an unreadable record: ensure_session() is create-if-absent and leaves an existing file alone, readable or not.

Writes. Every write is a read-modify-write under an exclusive flock on <session dir>/record.json.lock and lands through atomic_replace(), so a reader sees the old record or the new one and two writers in two processes never lose each other’s flag. Answered flags stay in the record, closed, with the answer, the operator and the time.

Reads follow no symbolic link: the session directory is checked with os.lstat() and the record is opened O_NOFOLLOW and bounded, the same reader the posture store uses for its tree.

This module imports only safety_file from the package, so the posture store can import it.

osprey_connectors.session_hold.HOLD_DIR_ENV_VAR: Final = 'OSPREY_SESSION_HOLD_DIR'#

The environment variable naming the hold root when no root is passed.

osprey_connectors.session_hold.RECORD_NAME: Final = 'record.json'#

The record’s file name inside a session’s directory.

osprey_connectors.session_hold.UNREADABLE_FLAG_ID: Final = 'hold-record-unreadable'#

The id of the one flag reported for a missing or unreadable record.

class osprey_connectors.session_hold.HoldFlag(flag_id, source, reason, prompt_ref, prompt_excerpt, opened_at, stop_unconfirmed=False, started=())[source]#

Bases: object

One open flag on a session, as open_flags() reports it.

flag_id: str#
source: str#
reason: str#
prompt_ref: str#
prompt_excerpt: str#
opened_at: str#
stop_unconfirmed: bool = False#
started: tuple[str, ...] = ()#
__init__(flag_id, source, reason, prompt_ref, prompt_excerpt, opened_at, stop_unconfirmed=False, started=())#
osprey_connectors.session_hold.answer_flags(session_key, flag_ids, *, answer, operator, root=None)[source]#

Close the named open flags with answer; the ids released, in record order.

Unknown and already-closed ids are ignored. Against a missing or unreadable record only UNREADABLE_FLAG_ID can be answered, and answering it writes a fresh record holding that flag, closed. No root: ().

Raises:
  • ValueError – An unsafe session_key, or an answer that is neither "stop" nor "continue".

  • TypeError – flag_ids is a single string.

  • OSError – The session directory is a link, or the write failed.

  • RuntimeError – The lock was not acquired in time.

Return type:

tuple[str, …]

osprey_connectors.session_hold.ensure_session(session_key, *, root=None)[source]#

Create the session’s empty record when none exists. No root: nothing.

Never rewrites an existing file, readable or not.

Raises:
  • ValueError – session_key is not a safe file name.

  • OSError – The session directory is a link or could not be created.

  • RuntimeError – The lock was not acquired in time.

osprey_connectors.session_hold.has_no_record(session_key, *, root=None)[source]#

Whether nothing at all is on disk for this session under a root.

The one question is_held() and open_flags() deliberately do not separate from an unreadable record: a caller that knows no session runs under this key can tell “never started” from “lost”. It changes no answer of theirs. A session directory of any kind, even empty or a dangling link, is False, and so is a path that cannot be examined.

Raises:

ValueError – session_key is not a safe file name.

Return type:

bool

osprey_connectors.session_hold.hold_root(root=None)[source]#

The hold root: root when given, else HOLD_DIR_ENV_VAR; None is no store.

Return type:

Path | None

osprey_connectors.session_hold.is_held(session_key, *, root=None)[source]#

Whether session_key is held. Never raises.

No root: False. Under a root: True for an open flag and for every way the record can fail to be read (see the module doc), including an unsafe key.

Return type:

bool

osprey_connectors.session_hold.is_safe_session_key(session_key)[source]#

Whether session_key is one safe path segment (no separator, no dot-name).

Return type:

TypeGuard[str]

osprey_connectors.session_hold.mark_stop_unconfirmed(session_key, flag_ids, *, operator, started, root=None)[source]#

Mark the named open flags as stopped-but-unconfirmed; the ids marked.

The flags stay open — the turn did not stop — and record started, the commands still running, with the operator and the time. Closed and unknown ids are ignored; an unreadable record marks nothing. No root: ().

Raises:
  • ValueError – session_key is not a safe file name.

  • TypeError – flag_ids is a single string.

  • OSError – The session directory is a link, or the write failed.

  • RuntimeError – The lock was not acquired in time.

Return type:

tuple[str, …]

osprey_connectors.session_hold.open_flag(session_key, *, flag_id, source, reason, prompt_ref, prompt_excerpt, root=None)[source]#

Open one flag; True when it was opened.

False when there is no root, when a flag with the same (source, prompt_ref) or the same flag_id exists (open or closed), or when the record exists and is unreadable — that session is already held by the synthetic flag, and only its answer rewrites the record. A missing record is created with the flag.

Raises:
  • ValueError – session_key is not a safe file name.

  • OSError – The session directory is a link, or the write failed.

  • RuntimeError – The lock was not acquired in time.

Return type:

bool

osprey_connectors.session_hold.open_flags(session_key, *, root=None)[source]#

The session’s open flags, in the order they were opened.

No root: []. A missing or unreadable record under a root: the one synthetic UNREADABLE_FLAG_ID flag.

Raises:

ValueError – session_key is not a safe file name.

Return type:

list[HoldFlag]

The control-context record — one file per identity.

Which machine a deployment is pointed at, how many times that has moved, and what one operator has narrowed are properties of the deployment as that operator holds it, not of any process tree inside it. They live in a single JSON file, RECORD_FILENAME inside the acting identity’s directory under STATE_DIR_NAME (the state directory, state_dir()), and this module is where it is written and read.

The file has exactly one writer at a time — its owner: the web terminal when one is running, otherwise a controls MCP server. Everything else is a reader: every chat session, every notebook kernel, every executor sandbox, every sibling MCP server, and the stdlib-only hooks, which cannot import this module and therefore restate the rules below. Treat them as the contract; a change here is a change there.

1. Where the file is. record_path() — the record sits in the same directory as the posture store, and the root resolves by that store’s rule 1 (osprey_connectors.posture_store.state_dir()) rather than by a second derivation here: a record one process writes and another looks for somewhere else is worse than no record at all. An unresolvable root makes record_path() None, which reads as “no record” and makes write_record() raise — a route surfaces that as store_unavailable rather than writing where no reader will look.

2. What a payload must carry. schema (exactly _SCHEMA_VERSION), target (a member of CONTROL_TARGETS) and generation (a non-negative integer) are the record’s identity. If any of the three is absent, of the wrong type, or unrecognised, there is no record: this is a file that decides whether a real machine is written to, so a hand-edited or future-version payload must not be honoured in part.

The other fields are annotations on that identity and degrade on their own, because each has a meaningful “not stated” value that a reader can act on safely:

  • owner → None, which is ownerless — the state a claim is for. An owner that does not name one of _OWNER_KINDS and a live PID is not an owner anybody should defer to, so reading it as ownerless is what lets the next process take the file over instead of stalling behind a ghost.

  • posture → {}. A mirror of switch kept for old readers, never an input: ControlContext.to_payload() writes sandbox for every machine in CONTROL_TARGETS whose position is off (_posture_mirror()), whatever the record it was built from carried, and no write decision reads it back. A file written before the mirror may still hold an old narrowing; it is parsed by the posture store’s grammar (rule 2 there) and ignored by the verdict.

  • last_switch → None. It is the terminus of the last switch request — applied or refused — and it is carried verbatim. This module owns the block’s shape, because a requester polls it for its own request_id (terminus() builds it, write_terminus() stores it and reads it back); the switch machinery owns what one says. A refusal is a record write that moves nothing else: the same target, the same generation, the same posture, a new last_switch. That is the whole of how a refusal is reported.

  • switch → {}, every machine’s writes off. A per-target map of which only "asked" and "allowed" leaves survive, and a target absent from it is off. The legacy "on" reads as "asked", and any write stores the whole map in the new spelling; any other value is dropped on parse, so a degraded switch can only refuse. switch_position() is the one reader of the map.

  • switch_epoch → None, a record written before epochs existed. An epoch is a time.time_ns() stamp that only moves forward; the person who widens a switch names the epoch they saw, so a stop or a lost record in between makes their gesture stale. None is never “older” than anything.

The schema stays _SCHEMA_VERSION with the two switch fields added: every pre-existing reader, the stdlib hooks included, ignores keys it does not know, so a record written by this version reads unchanged through them.

3. How it is written. write_json_atomic() replaces a file rather than rewriting it, whole through safety_file.atomic_replace, so no reader ever sees half of one and two writers never interleave into one. Every file in this directory is written through it, the record (write_record()) and the per-server reports and requests alike.

The record is written only under its lock: an exclusive fcntl.flock on the sibling file <record path>.lock, derived from the path being written (so path= moves the lock with the file), waited on for a bounded time and then refused with RuntimeError. Inside the lock write_record() re-reads the file on disk and writes the caller’s record with the on-disk switch and switch_epoch substituted: whatever a caller read earlier, no writer but the person’s own switch gesture (set_switch(), which reads, compares and writes in one hold) moves either field, so a target switch or a refusal terminus racing a stop cannot turn a machine back on. A write that finds the record missing or unreadable writes the switch empty and stamps a fresh epoch, never 0. What a caller changes in the other fields, and whether it is still entitled to, remains the owner’s business.

The exclusion holds among processes sharing one kernel — one host, or containers on a Linux host over a bind mount. Across a macOS host and a VM file share flock is not guaranteed to exclude anything; that residual is closed by the sandboxed connector host, not here.

4. When a change is seen. Every read re-stats the file and re-parses on (st_mtime_ns, st_size, st_ino), the same signature the posture store uses and for the same reason: writes arrive as temp+rename, so two of them inside one filesystem clock tick differ by inode when mtime and size do not.

5. Who else lives in that directory. The record says what the deployment is pointed at; it does not say what any one controls server has managed to do about it. That is the per-server report, server_<pid>.json, one file per controls server, written by that server through its publishers and read here (read_report(), live_reports()). A report is an observation, so it degrades field by field around its one identity, server_pid, and a report nobody can parse is skipped rather than fatal — the readers of these files describe a fleet, and one bad file must not blank the others.

6. Whether anything may act. The record says where the deployment is pointed; the reports say who has got there. converged() is the one place those two are compared, and it is what the executor’s stamp, a notebook cell and a controls server’s write tools ask before they touch a machine: a swap in flight stops everyone, a server acquiring its first connector stops only its own session, a server that could not follow stops only its own session, and nothing else stops anybody.

Every file in that directory is named for the process that owns it, which is what lets a reader judge one without opening it: is_process_alive() and sweep_dead() are that rule and its consequence. Liveness lives here, at the bottom, because the record’s owner, the reports’ authors and the request files’ addressees are all judged by it and there must be one answer.

This module imports nothing from osprey and holds no config: it runs inside connector-host children, executor sandboxes and notebook kernels, where the dependency budget is the lean connector chain. The import direction is one-way — the posture store below it, never the reverse at module scope.

osprey_connectors.control_context.claimed(record, baseline)[source]#

record as a process claiming it holds it, given the deployment’s baseline.

A record nobody has switched follows the deployment’s baseline; every applied switch mints generation + 1, so generation 0 is a claim and never a switch. An unswitched record on another target moves to baseline and keeps its generation, owner and last switch terminus. A switched record, or one already on baseline, is returned as it is.

Return type:

ControlContext

osprey_connectors.control_context.REPORT_APPLYING = 'applying'#

How far one controls server has got through the switch the record names. applying is a swap in flight and stops every session while its bound holds; applied is arrival, which the binding states as well; failed is a swap that will not land without an operator, and stops only the session whose server it is. Distinct from the record’s SWITCH_APPLIED / SWITCH_REFUSED, which are a request’s terminus rather than a server’s progress.

osprey_connectors.control_context.OWNER_WEB_TERMINAL = 'web_terminal'#

The two kinds of process that can own the record. A web terminal outranks a controls server — it is the one an operator is looking at.

osprey_connectors.control_context.RECORD_FILENAME = 'control_context.json'#

The record’s filename inside the state directory. The stdlib hooks restate this literal.

osprey_connectors.control_context.REPORT_FILE_PREFIX = 'server_'#

One report file per controls server, in the state directory beside the record. The PID in the name is the address and is what makes a report left behind by a killed server sweepable without opening it.

osprey_connectors.control_context.STATE_DIR_NAME = 'control_target'#

The tree of per-identity directories the record shares with the posture store, the per-server reports and the request files — one directory per identity, each holding every one of those families. Taken from the store rather than re-spelled so one directory cannot be two directories.

osprey_connectors.control_context.SWITCH_APPLIED = 'applied'#

The two termini a switch request can reach in the record. applied moved the target and minted a generation; refused moved nothing.

osprey_connectors.control_context.SWITCH_POSITIONS: tuple[Literal['off'], Literal['asked'], Literal['allowed']] = ('off', 'asked', 'allowed')#

a later one widens an earlier one. The gesture’s words and every reader’s order. "off" is not stored (rule 2).

Type:

A machine’s three positions, narrowest first

class osprey_connectors.control_context.ControlContext(target, generation, owner=None, posture=<factory>, last_switch=None, switch=<factory>, switch_epoch=None)[source]#

Bases: object

One deployment’s control context. Treat an instance as immutable.

read_record() hands back the cached instance, so a caller that needs a changed record builds one with dataclasses.replace() rather than editing this one — an in-place edit would reach every other reader in the process.

Variables:
  • target (str) – The control target the deployment is pointed at.

  • generation (int) – How many times that has moved. Minted by the owner and by nobody else; a reader pins its work to it.

  • owner (osprey_connectors.control_context.Owner | None) – The process allowed to write this file, or None when the record is ownerless and free to be claimed.

  • posture (dict[str, str]) – The posture field as read off disk — the mirror of switch (_posture_mirror()), or an old narrowing in a file written before it. A reading only: to_payload() ignores it and derives the field from switch, so nothing set here is ever stored, and no write decision reads it.

  • last_switch (dict[str, object] | None) – The terminus of the last switch request, verbatim, or None when no request has reached one.

  • switch (collections.abc.Mapping[str, str]) – The position the person has put each machine at, {target: "asked" | "allowed"}; an absent target is off, and switch_position() is how it is read. write_record() never changes it — it keeps whatever the file on disk says.

  • switch_epoch (int | None) – The time.time_ns() stamp of the last stop or loss of the record, or None for a record written before epochs existed. Kept by write_record() like switch.

target: str#
generation: int#
owner: Owner | None = None#
posture: dict[str, str]#
last_switch: dict[str, object] | None = None#
switch: Mapping[str, str]#
switch_epoch: int | None = None#
to_payload()[source]#

This record as the JSON object write_record() stores.

The seven contract fields and the schema, and nothing else: a payload round-trips through parse_record() unchanged, and a key some future version added does not survive a rewrite by this one. The posture field is the mirror of switch (_posture_mirror()), never posture: a narrowing is not something a writer can store.

Return type:

dict[str, object]

__init__(target, generation, owner=None, posture=<factory>, last_switch=None, switch=<factory>, switch_epoch=None)#
class osprey_connectors.control_context.Owner(kind, pid, port=None)[source]#

Bases: object

The process currently allowed to write the record.

Variables:
  • kind (str) – One of _OWNER_KINDS.

  • pid (int) – The owning process’s PID — how every other process decides whether the owner is still alive.

  • port (int | None) – The web terminal’s port, so a follower can name where the owner is in a refusal an operator has to act on. None for a controls server, which serves nothing an operator can open.

kind: str#
pid: int#
port: int | None = None#
to_payload()[source]#

This owner as the record’s owner object.

Return type:

dict[str, object]

__init__(kind, pid, port=None)#
class osprey_connectors.control_context.ServerReport(server_pid, session=None, applied_target=None, applied_generation=None, children=(), reachability=<factory>, last_switch=None, last_posture_realign=None, targets=<factory>, updated_at=None, statement=None)[source]#

Bases: object

What one controls server says about itself. Treat an instance as immutable.

Rule 5 of the module contract. Every field but server_pid is an observation that can be absent — a server that has just started has answered nothing yet — so each degrades on its own to a value a reader can act on rather than invalidating the report.

Variables:
  • server_pid (int) – The reporting server. Its identity, and how a reader knows whether the report still describes anything.

  • session (str | None) – The server’s OSPREY_POSTURE_SESSION, or None for a bare claude that was never stamped with one.

  • applied_target (str | None) – The target its connector host is actually on, or None until the first child has answered its init frame. Null is not “baseline”: it is “this server has not got there yet”.

  • applied_generation (int | None) – The generation that target was reached at, on the same terms.

  • children (tuple[int, ...]) – The connector-host PIDs it spawned, so a later server can reap them if this one is killed.

  • reachability (dict[str, object]) – Its last probe per target, {} when it has not probed.

  • last_switch (dict[str, object] | None) – Its progress through the current switch — applying, applied or failed, with the expires_at bound only this process could compute — or None.

  • last_posture_realign (dict[str, object] | None) – Its last posture realignment, or None.

  • targets (dict[str, object]) – Per-target display metadata, {} when it has none.

  • updated_at (str | None) – When it last wrote, ISO-8601, or None.

  • statement (dict[str, dict[str, object] | None] | None) – The machine statement a process that displays the machine (a panel backend) writes in place of controlling it, None on a controls server’s report. {"reachable": ..., "writes": ...}, each axis None until stated: reachable is {"state", "since", "reason"} with state one of _REACHABLE_STATES, and writes is write_statement() of the session’s execution verdict. A statement that does not have this shape states nothing, and the report is then an ordinary one.

server_pid: int#
session: str | None = None#
applied_target: str | None = None#
applied_generation: int | None = None#
children: tuple[int, ...] = ()#
reachability: dict[str, object]#
last_switch: dict[str, object] | None = None#
last_posture_realign: dict[str, object] | None = None#
targets: dict[str, object]#
updated_at: str | None = None#
statement: dict[str, dict[str, object] | None] | None = None#
property display_only: bool#

it carries a statement.

Such a process shows the machine rather than controlling it, so the fleet readers leave its report out (live_reports()); a view that shows the machine reads it with read_report().

Type:

Whether this report is a display process’s

to_payload()[source]#

This report as the JSON object its file holds.

The ten contract fields, plus statement as the eleventh for a display-only report and only then, so a payload round-trips through _parse_report() unchanged and a controls server’s report never reads back as display-only.

Return type:

dict[str, object]

__init__(server_pid, session=None, applied_target=None, applied_generation=None, children=(), reachability=<factory>, last_switch=None, last_posture_realign=None, targets=<factory>, updated_at=None, statement=None)#
exception osprey_connectors.control_context.StoppedSince(*, epoch, stamped=False)[source]#

Bases: Exception

A widening refused because a stop, or a lost record, came after it began.

Rule 3: a person widening a machine names the epoch they saw. A record whose epoch differs from it — newer or older —, a gesture that names none, a record that has no epoch, and no record at all each mean that what they saw is no longer what is on disk, so nothing is armed. The chip retries on its own, with epoch, only when stamped; otherwise it re-renders and needs a new click, so a widening that raced a stop stays off.

Not a RuntimeError: a caller that answers RuntimeError with “the store is unavailable” must not answer a stale gesture the same way.

Variables:
  • epoch – The record’s epoch now — the one a retried gesture names — or None when there is no usable record to retry against.

  • stamped – True only when this refusal just stamped an epoch on an epoch-less record — nothing was stopped, so a retry is safe.

  • reason – Always "stopped_since", a member of osprey_connectors.refusals.REASONS.

__init__(*, epoch, stamped=False)[source]#
osprey_connectors.control_context.applied_detail(target, generation)[source]#

The detail for a switch that happened. generation is the new one.

The companion to unchanged_detail(), written by the same four surfaces and for the same reason.

Return type:

str

osprey_connectors.control_context.blocking_pids(record, reports, session, *, now=None)[source]#

The controls servers that stop session acting on record, PID order.

Empty when there is nothing in the way — which is what converged() reports. The PIDs are the refusal text: switch_in_progress names them so an operator can find the process that has to finish or be killed, and the two callers that refuse (the executor’s stamp and the kernel’s cell gate) both say which.

Parameters:
  • record (ControlContext) – The deployment’s control context. The generation in it is what the fleet coordinates on.

  • reports (Iterable[ServerReport]) – The reports of the servers that are still running, as live_reports() returns them. A report of a dead server describes nobody and is filtered out there, not here: this function opens no file and asks the kernel nothing.

  • session (str | None) – The reader’s OSPREY_POSTURE_SESSION. None (and the empty string) for a reader that owns no report — a bare claude, a notebook kernel’s kernel:<id>, and the owner asking whether the fleet as a whole has settled.

  • now (float | None) – Epoch seconds to age the applying bounds against; the wall clock when omitted.

Return type:

tuple[int, …]

osprey_connectors.control_context.invalidate_cache()[source]#

Forget every parsed file. For tests and for a process that moved roots.

osprey_connectors.control_context.is_process_alive(pid)[source]#

Whether pid names a running process.

os.kill(pid, 0) sends no signal and only asks the kernel whether the process exists — the osprey web PID-file check does the same. A PermissionError means the process exists but belongs to another user, so it counts as ALIVE: sweeping a file whose owner is merely unreachable would delete live state. Non-positive PIDs are rejected without calling os.kill at all, because 0 and negatives address process groups.

os.kill also answers for a thread id, which is no process: a PID kept in a record that outlived its container can land on a thread of the process reading it, which would then follow itself for ever (_is_thread_id()). A real process on that PID is not told apart.

Anything that is not an int names no process and is False without a call either, so a field read off a file can be handed over unconverted. That includes bool: True is 1 to os.kill, and PID 1 is always alive, so a report carrying "server_pid": true would otherwise read as a running server forever.

Return type:

bool

osprey_connectors.control_context.live_owner(record)[source]#

record’s owner while its process still runs, else None.

The one question every would-be claimant asks first: an owner whose process is gone holds nothing, and its record is free. None covers every way of having no live owner — no record, no owner, a dead one — so a caller that only wants to know whether to claim need not tell them apart.

A PID that is running under another user is not the owner either (_is_foreign_process()). The record outlives the container that wrote it, and the PID it names is then handed out again: a record written by a terminal that ran as PID 1 names, in the next container, whatever runs as PID 1 there — an init process owned by root, alive for as long as the container is. Read as a live owner, that process would be followed by every terminal for ever, and nobody could switch the target again.

Return type:

Owner | None

osprey_connectors.control_context.live_reports(entries=None, *, is_alive=is_process_alive)[source]#

Every report of a running controls server, parsed.

The fleet as a reader sees it: what each live server is on, at which generation, and how far through a switch it has got. Display-only reports are left out here, at the source, so no fleet reader ever counts a process that only shows the machine (read_report() reads one, and its ServerReport.display_only says which it is).

Parameters:
  • entries (Iterable[Path] | None) – Report paths; report_paths() when omitted.

  • is_alive (Callable[[object], bool]) – The liveness predicate, so one pass over a fleet asks the same question the same way throughout.

Return type:

list[ServerReport]

osprey_connectors.control_context.write_statement(verdict)[source]#

The writes half of a machine statement, from one execution verdict.

The verdict’s own terms and nothing else: allowed, position (whether a person is asked, never a boolean “on”), reason (a REASONS member when refused) and kind. A reader renders the refusal with refusal_phrase(); no surface words it again.

Parameters:

verdict (WriteVerdict) – execution_verdict() for the session’s target, so a held session states session_held.

Return type:

dict[str, object]

osprey_connectors.control_context.owned_here(record)[source]#

Whether THIS process owns record, and may therefore write it.

PID equality and nothing else: the record names one owning process, and a second rule about the owner’s kind would let two processes disagree about who writes one file. An ownerless record is owned by nobody, so it is not owned here either — it is claimed first, and claiming is a write.

Return type:

bool

osprey_connectors.control_context.converged(record, reports, session, *, now=None)[source]#

Whether session may act on record — rule 6 of the module contract.

False in exactly two situations, and the arguments are the same in both: blocking_pids() names the servers behind them.

A swap is in flight. Any live server reporting applying for the record’s generation, within the expires_at bound it wrote, stops every session: that server is between two targets, and a launch admitted now would reach whichever one it happens to be holding. Past the bound the server is stuck rather than working, and it stops only its own session — a process killed mid-swap must not refuse a deployment for ever. A server that reports applying while it holds no connector at all — no children, nothing bound — is acquiring its first rather than swapping one, and stops only its own session.

The reader’s own server is not there. A live report carrying this session that is bound somewhere other than the record’s (target, generation), or that reports failed at that generation, stops that session and nothing else. That is the whole of what a failed swap costs: the session whose server could not follow is refused, its own MCP writes with it, while every other session, every notebook kernel and every bare claude carries on.

A session that owns no report — None, the empty string, a kernel’s kernel:<id> — is therefore blocked only by the first situation. So is the owner’s own check before it consumes a switch request, which passes None deliberately: it is asking whether the fleet has settled, not whether some session has.

This is a judgement over parsed data and nothing else. It opens no file, signals no process and imports nothing from osprey, because the executor stamps every sandbox with it and a notebook kernel gates every cell on it.

Return type:

bool

osprey_connectors.control_context.file_signature(path)[source]#

(mtime_ns, size, inode) for path, or None when it is absent.

Rule 4 of the module contract, and the same answer for everything that watches one of these files: the cache below re-parses on it, and the reconciler wakes on it. The inode is the third element because write_json_atomic() replaces the file rather than rewriting it, so two switches inside one filesystem clock tick differ there and nowhere else. An unresolvable path has no signature, which reads as “no file”.

Return type:

tuple[int, int, int] | None

osprey_connectors.control_context.parse_record(raw)[source]#

Decode a record, or None when it states no usable context.

Accepts the decoded JSON object or the raw text/bytes of one, so a reader that has already read the file and one that has not share this filter. Never raises: rule 2 of the module contract says every degraded outcome — missing, unparseable, wrong schema, unusable identity — arrives as the one value, because readers act on “no record” and must not have to tell the failures apart.

Return type:

ControlContext | None

osprey_connectors.control_context.read_record(*, path=None)[source]#

The deployment’s control context, or None when there is none.

None for every degraded outcome (rule 2): no agent-data root, no file, an unreadable or corrupt file, a payload from another schema, or one whose target or generation cannot be used. Callers fall back to the deployment baseline or refuse, and none of them has to tell those cases apart.

Re-stats on every call and re-parses only when the signature moved (rule 4). The returned record is the cached instance — treat it as immutable.

Parameters:

path (Path | None) – Read this file instead of record_path(). For a caller that has already resolved a root, and for tests.

Return type:

ControlContext | None

osprey_connectors.control_context.read_record_status(*, path=None)[source]#

The record and how reading it ended — for a caller that must tell why.

read_record() answers None for “nobody has written one yet” and for “something broke it” alike; a write verdict refuses both but names them differently. "missing" is no file at the path; "unreadable" is every other way of having no usable record — an unresolvable agent-data root, an OS or decode failure, invalid JSON, a foreign schema, an unusable identity. "ok" comes with the record. Cached like read_record() (rule 4); never raises.

Parameters:

path (Path | None) – Read this file instead of record_path().

Return type:

tuple[ControlContext | None, Literal[‘ok’, ‘missing’, ‘unreadable’]]

osprey_connectors.control_context.read_report(path)[source]#

One server’s report, or None when the file states no usable one.

Return type:

ServerReport | None

osprey_connectors.control_context.record_path()[source]#

The record’s path, or None when the agent-data root is unresolvable.

None is not an error: for a reader it is indistinguishable from an empty deployment, and for a writer it is what a route reports as store_unavailable.

Return type:

Path | None

osprey_connectors.control_context.report_path(server_pid)[source]#

The report path of server_pid, or None without an agent-data root.

Return type:

Path | None

osprey_connectors.control_context.report_paths()[source]#

Every report file in the state directory, sorted. Empty when there is none.

Never raises: no agent-data root, no directory and an unreadable one all answer “no reports”, the same as an empty deployment, because a caller describing a fleet has the same nothing to say in each case.

Return type:

list[Path]

osprey_connectors.control_context.set_switch(targets, state, *, epoch=None, path=None, by=None)[source]#

The person’s switch gesture — the one writer of switch. Rule 3.

Reads, compares and writes in one hold of the record lock, through the same private writer write_record() uses, so no other write lands between what this compared and what it stored.

Each named target’s move is classified inside the lock, against the map on disk, so a move believed to be a narrowing that raced a stop is judged a widening and refused.

  • A widening (one name moving up off → asked → allowed gates the whole call) requires epoch, the switch_epoch the person saw, and succeeds only when it equals the record’s epoch — a compare-and-swap. It raises StoppedSince carrying the on-disk epoch when the two differ (newer or older) or epoch is None, when the record has no epoch (one is stamped and stamped is set, so the retried gesture succeeds), or when there is no usable record.

  • A narrowing or a no-op applies unconditionally and never refuses. "off" clears each named key, known target or not.

  • "all" (with "off") clears every key and moves the epoch to max(old + 1, time.time_ns()), which makes every widening begun before it stale.

Only a stop moves an existing epoch; a gesture on an epoch-less record stamps a fresh time.time_ns(). Every other field is kept as on disk.

A stop also ends every program authorization (a grant of write_authorization) on the machines it names, or on every machine for "all": inside the same hold of the record lock, after the record is stored, each grant in the authorizations directory beside the record is marked revoked, so the holder’s next write refuses. "all" also moves the epoch, which ends every grant issued under the old one whatever its file says. The marks are written even when no record is there.

A stop fails closed on its marks: when they cannot be written (the grants directory locked past the wait, a lock or a grant file this process cannot open), a stop of named machines moves the epoch as well, in the same hold, so every grant on every machine of this record ends — wider than asked, never narrower — and the stop is taken. Raising instead would report the stop not taken with the switch already stored and the grant still in force; revoking before storing would leave the switch on as well. A stop with no record needs no fallback: no grant stands without an epoch.

Parameters:
  • targets (Sequence[str] | Literal['all']) – The machines, or "all".

  • state (Literal['off', 'on', 'asked', 'allowed']) – "off", "asked" or "allowed"; the legacy "on" is taken as "asked" and never stored.

  • epoch (int | None) – The epoch the gesture was begun against. Ignored when nothing widens.

  • path (Path | None) – Write this file instead of record_path().

  • by (str | None) – Whose stop a revocation names; None is this process’s acting_identity().

Returns:

The record as stored, or None when a non-widening gesture found no usable record — nothing is on, so no record was written.

Raises:
  • ValueError – "all" with anything but "off", an unknown state, malformed targets, or an epoch that is neither None nor an integer. Nothing is written.

  • StoppedSince – A widening that is stale, as above.

  • RuntimeError – The agent-data root does not resolve, or the record stayed locked past the bounded wait.

  • OSError – The write itself failed.

Return type:

ControlContext | None

osprey_connectors.control_context.sweep_dead(directory, *, prefix, suffix, keep=None, is_alive=is_process_alive)[source]#

Unlink every prefix<pid>suffix file in directory whose PID is gone.

A process that is killed rather than asked to stop leaves its file behind, and a later process that happens to reuse the PID would otherwise inherit it. The name is the whole judgement — a file whose name encodes no PID encodes no owner either, and goes the same way.

Parameters:
  • directory (Path) – Where to look. A missing or unreadable one sweeps nothing.

  • prefix (str) – Filename prefix of the family to sweep.

  • suffix (str) – Filename suffix of the family to sweep.

  • keep (str | None) – A filename to leave alone without probing it. This is how a process spares its own file: asking whether oneself is alive is a way to get it wrong.

  • is_alive (Callable[[object], bool]) – The liveness predicate.

Returns:

The paths removed, in discovery order.

Return type:

list[Path]

osprey_connectors.control_context.switch_position(record, target)[source]#

Where the person has put target — the one reader of the switch map.

Never raises. No record, a target absent from the map and an unknown value all read as off; a hand-built record still spelling "on" reads as asked, as a parsed one does.

Parameters:
  • record (ControlContext | None) – The record, or None when there is none.

  • target (str) – The machine.

Return type:

Literal[‘off’, ‘asked’, ‘allowed’]

osprey_connectors.control_context.terminus(record, *, request_id, target, requested_at, requested_by, status, reason, detail, generation)[source]#

record as it will be once a switch request has been answered.

Every answer to a switch gesture ends here, whoever writes it: the owning server answering its own agent, and the reconciler answering a request another process filed. The block is what a requester polls for — it looks for its own request_id and reads the outcome beside it — so the shape is fixed here rather than at each terminus.

generation is what the record carries AFTER the answer, and None is what makes the answer a refusal: a refusal moves neither target nor generation, and its block names no binding because there is none.

Parameters:
  • record (ControlContext) – The record being answered against. Not modified.

  • request_id (str) – The id the requester is waiting on.

  • target (str) – The target that was asked for — recorded whether or not the deployment went there, because a refusal has to say what it refused.

  • requested_at (object) – The request’s own stamp, copied verbatim.

  • requested_by (str) – Who to name in the block: an audit session where the requester has one, pid:<n> where it does not.

  • status (str) – SWITCH_APPLIED or SWITCH_REFUSED.

  • reason (str | None) – The refusal’s machine-readable reason, None when applied.

  • detail (str) – The sentence an operator reads.

  • generation (int | None) – The record’s generation after the answer, or None for a refusal.

Return type:

ControlContext

osprey_connectors.control_context.write_json_atomic(path, payload)[source]#

Write payload to path as JSON, replacing any existing file. Rule 3.

The file is replaced whole through safety_file.atomic_replace, so a failed write leaves neither half a file nor litter beside it.

Every file in the state directory is written this way, the record and the per-server reports and requests alike: they are read by processes that never coordinate with the writer, so a reader must never be able to see half of one.

The mode is load-bearing, not a preference: those readers run under other uids — a dispatch worker at uid 1000 reading what the host account wrote — and reach the file through the setgid group of the state directory, so the file is given 0640 whatever the umask: under umask 077 a record only the owner can read makes every owned lane write refuse control_context_unavailable, while CI at umask 022 stays green and never sees it. Every directory this writer creates — the levels above the leaf as much as the leaf — is set to exactly 0o2770 rather than merely widened, because a directory left at the umask 0755 would let other list the identity names (safety_file.ensure_shared_dir).

Raises:

OSError – The write itself failed.

osprey_connectors.control_context.unchanged_detail(target, generation)[source]#

The detail for a request that asked for the target of record.

One sentence with one spelling, because four surfaces write it into the same field: the terminal owner’s request half, the controls server’s reconciler, the HTTP switch route and the agent’s own control_target_set. A record whose terminus read differently depending on which surface answered would be two vocabularies in one place, and the chip resolves a pending switch against what it finds there.

It is an APPLIED terminus and mints no generation: the deployment is where the request asked for it to be, and a generation bumped for a switch that did not happen would refuse every write bound to the old one, for nothing.

Return type:

str

osprey_connectors.control_context.write_record(record, *, path=None)[source]#

Store record, replacing any existing one atomically. Rule 3.

Under the record lock, this re-reads the file on disk and stores record with the on-disk switch and switch_epoch in place of its own: no caller of this function changes either, whatever it read before. A file that is missing or unreadable is replaced with the switch empty and a fresh time.time_ns() epoch, never 0, so a widening begun before the record was lost names an older epoch and is refused.

It does not check who owns the record: the owner decides what it is changing and whether it is still entitled to, around this call.

Parameters:
Returns:

The path written.

Raises:
  • RuntimeError – The agent-data root does not resolve, so there is nowhere a reader would look for what this call would write; or the record stayed locked past the bounded wait.

  • OSError – The write itself failed.

Return type:

Path

osprey_connectors.control_context.write_terminus(updated, request_id)[source]#

Write updated, read it back, and say whether the answer stuck.

Read-verified because the record has one owner but two processes reach for it: a server answers its own agent in one place and consumes other processes’ requests in another, and this call can also lose the record outright to a new owner between the write and the read. A lost update has to be discovered here rather than reported to an agent as a switch that happened.

The write goes through write_record(), so it holds the record lock and keeps the on-disk switch: a terminus never turns a machine on or off.

Three things have to hold for the answer to be believed: the record is still readable, this process still owns it, and the block in it is the one just written. The caller decides what a False means for it — the owner refuses its agent, the reconciler leaves the request file for the next pass — and neither may treat the switch as done.

Return type:

bool

osprey_connectors.control_context.held_epoch(path, target)[source]#

Hold the record lock at path and yield the record’s switch_epoch. Rule 3.

For a writer that issues something standing on the epoch — an approval of a program’s authorization — and must not have a stop land between reading it and writing what it stamps: the block runs inside the lock, and any lock the block takes comes after this one. A record that is not there is created on target with every switch off and a fresh epoch, and an epoch-less record is given one, so that a later stop of every machine has an epoch to move past.

Raises:
  • RecordUnavailable – The record is there and cannot be read.

  • RuntimeError – The record stayed locked past the bounded wait.

  • OSError – The stamp could not be written.

Return type:

Iterator[int]

exception osprey_connectors.control_context.RecordUnavailable[source]#

Bases: Exception

The record is there and cannot be read, so nothing can be stood on it.

Which machine a write tool call writes to, as the hooks place it.

The hooks place every hooked call before they judge it: the stdlib twin’s hook_write_target (osprey_target_state.py) answers None for a call that writes nothing, the session’s target for an application tool, the real machine for a facility write tool, the lane’s target for a lane-addressed tool, and the session’s target for every other framework write tool. write_target_for_tool() is the package restatement of that placement, for a surface that has to name the machine before the hook has run — the operator chat’s approval card (C-FRAME). A parity test (tests/hooks/test_write_target_parity.py) pins the two against each other for every write tool.

The placement is not the gateway role: which gateway a connector writes through is the connector’s own choice and says nothing about which machine’s switch covers the call.

KIND_BANNERS holds the owner-facing banner for each machine kind (C-WORDS), the words a card or chip shows beside the machine. They are not KIND_WORDS, which a refusal phrase uses.

osprey_connectors.write_target.KIND_BANNERS: dict[str, str] = {'real': 'Live — writes move hardware', 'rehearsal': 'Rehearsal — nothing moves', 'simulator': 'Simulator — nothing moves'}#

The banner an owner reads beside each kind of machine (C-WORDS).

osprey_connectors.write_target.UNRESOLVED = <unresolved>#

The answer for a write whose machine cannot be placed.

class osprey_connectors.write_target.Unresolved[source]#

Bases: object

A write whose machine could not be placed: one instance, compared by identity.

Distinct from None, which write_target_for_tool() keeps for a call that writes nothing. A write nobody can place is refused by the hooks, never waved through as a read.

osprey_connectors.write_target.frame_target(target, *, state_dir=None)[source]#

C-FRAME’s target: {key, machine_kind, kind_words}, or None.

None for a call that writes nothing and for one that cannot be placed. The kind is the published one (C-KIND), so a standin the controls server has not vouched for reads as the real machine.

Parameters:
  • target (str | None | Unresolved) – An answer of write_target_for_tool().

  • state_dir (str | PathLike[str] | None) – The servers’ report directory; None reads this process’s.

Return type:

dict[str, str] | None

osprey_connectors.write_target.write_target_for_tool(config, tool_name, tool_input, *, hook_config, short_name=None, record_path=None, stamped=None)[source]#

The machine a call writes to, placed as the hooks place it. Never raises.

  • None for a call that writes nothing: a tool outside the render’s write_tools (the fallback list when the render names none), or a readonly execution.

  • The session’s target for an application tool (app_approvals).

  • live for a facility write tool the deployment declared.

  • The lane’s target for a lane-addressed tool.

  • The session’s target for every other framework write tool.

UNRESOLVED wherever a write cannot be placed, including any failure while answering.

Parameters:
  • config (object) – The loaded config.yml mapping, for the lane map and baseline.

  • tool_name (str) – The full tool name.

  • tool_input (object) – The call’s arguments.

  • hook_config (Mapping[str, object] | None) – The render’s .claude/hooks/hook_config.json mapping; None or {} reads as an empty one.

  • short_name (str | None) – tool_name without its server prefix; None resolves it from hook_config’s prefix lists.

  • record_path (Path | None) – The control-context record to read; None reads this process’s own (osprey_connectors.control_context.record_path()).

  • stamped (bool | None) – Whether the agent-data root of the process that will run the call is stamped; None asks this process’s environment.

Return type:

str | None | Unresolved

Wait for a written setpoint’s readback to come within the bound its facility states.

Every caller that waits for a readback after a write uses this one step: the Bluesky worker for a plan’s moves, the sandbox runtime for a script’s or a measurement’s steps. The bound has one rule (settle_bound()): the setpoint’s tolerance (absolute, or relative times the demand’s magnitude); with none stated, on the simulator only, the readback’s motion band; a caller’s floor raises the bound and never lowers it. settle() polls each readback through the connector until it is within its bound, and fails closed with SettleTimeoutError when the time runs out. A readback that cannot be reached, is not a channel, or times out raises SettleReadError, which names it, as does one that answers no value; a lost connector raises its own error.

This module imports only the std-lib and osprey_connectors.errors, and takes any connector with an awaitable read_channel(address) whose result carries .value.

class osprey_connectors.settle.Landing(setpoint, readback, demand, bound)[source]#

Bases: object

One written setpoint, the readback that reports it, its demand and its bound.

setpoint: str#
readback: str#
demand: float#
bound: float#
__init__(setpoint, readback, demand, bound)#
exception osprey_connectors.settle.SettleReadError(landing, cause)[source]#

Bases: ChannelReadFailedError

A readback could not be read while settling, or answered no value.

Variables:
  • landing – The landing whose readback could not be read.

  • addresses – The readback, the one failed channel.

  • causes (dict[str, BaseException]) – The readback to the exception its read raised; empty when the read answered no value.

__init__(landing, cause)[source]#
exception osprey_connectors.settle.SettleTimeoutError(landing, last, timeout_s)[source]#

Bases: TimeoutError

A readback did not come within its bound of the demand in time.

Variables:
  • landing – The first landing that did not settle.

  • last – Its readback’s last reading.

__init__(landing, last, timeout_s)[source]#
osprey_connectors.settle.declared_tolerance(record, demand)[source]#

The bound a tolerance record states for a move to demand.

Parameters:
  • record (Mapping[str, object] | None) – The setpoint’s tolerance record, {absolute: x} in the channel’s unit or {relative: f}, a fraction of the demand.

  • demand (float) – The value the setpoint is driven to.

Returns:

|absolute|, or |relative| x |demand|; None when the record states neither.

Return type:

float | None

async osprey_connectors.settle.settle(connector, landings, *, timeout_s, clock=time.monotonic, sleep=asyncio.sleep)[source]#

Poll each landing’s readback until it is within its bound of its demand.

Every landing is read once per poll until it is inside; a settled landing is not read again. A reading with no value is a failed read; any other reading that is not a finite number is never inside.

Parameters:
  • connector (Any) – Reads each readback with await connector.read_channel(address).

  • landings (Sequence[Landing]) – The landings to wait for.

  • timeout_s (float) – Seconds from the call after which an unsettled landing fails.

  • clock (Callable[[], float]) – The clock the deadline is measured on.

  • sleep (Callable[[float], Awaitable[None]]) – The pause between two polls.

Raises:
  • SettleTimeoutError – A landing was not inside its bound once timeout_s had passed, naming the first such landing in landings order.

  • SettleReadError – A readback read failed with a ChannelError (it cannot be reached, is not a channel, or timed out) or answered no value, naming that readback. Any other failure, a lost connector among them, propagates as itself.

osprey_connectors.settle.settle_bound(tolerance, demand, *, motion=0.0, simulated=False, floor=None)[source]#

How close a readback must come to demand for the move to count as settled.

Parameters:
  • tolerance (Mapping[str, object] | None) – The setpoint’s tolerance record, or None.

  • demand (float) – The value the setpoint is driven to.

  • motion (float) – The readback’s motion band.

  • simulated (bool) – Whether the machine is the simulator; only there does the motion band stand in for a tolerance that is not stated.

  • floor (float | None) – The caller’s floor, or None.

Returns:

The larger of floor and the declared bound; None when nothing is declared and the caller gives no floor, so there is nothing to wait for.

Return type:

float | None