Configuration#

Loading a deployment’s configuration: where a process finds it, the env chain it reads, and the YAML loader underneath.

Configuration system.

Loads a single YAML config file, resolves environment variables, and provides dot-path access to values.

Importing this module does not read ``.env`` and does not touch ``os.environ``. Building a ConfigBuilder does (see its load_env argument), and that is deliberate — but it must be an application that asks for a config, never the mere act of importing an osprey module. Loading .env at import time made a library consumer’s environment depend on which directory the process happened to start in, gave non-credential keys override=True semantics they were never scoped for, and silently undid callers’ own os.environ writes depending on import order.

Applications load .env explicitly at startup: the CLI in osprey.cli.main, MCP servers via osprey.mcp_env.load_dotenv_from_project(), and the Claude Code launch paths via osprey.agent_runner.provider_env.inject_provider_env().

class osprey_connectors.config.ConfigBuilder(config_path=None, *, load_env=True)[source]#

Bases: object

Loads a YAML config, resolves ${VAR} env-var placeholders, and pre-computes a configurable dict for framework and standalone use.

Singleton access: use get_config_builder() or _get_config().

Initialize configuration builder.

Parameters:
  • config_path (str | Path | None) – Path to the config.yml file. If None, the file osprey_connectors.workspace.resolve_config_path() names: OSPREY_CONFIG, else build/config.yml under the current directory, else config.yml in it.

  • load_env (bool) – When True (the default), load the env chain from the current working directory into os.environ. This env → environ passthrough is load-bearing: it feeds the ${VAR} references Claude Code expands in .mcp.json at MCP server launch time. Pass False only when the caller has already populated the environment (or must not mutate it) and wants a config load with no side effects on os.environ.

Raises:
  • FileNotFoundError – If config.yml is not found and no path is provided.

  • ValueError – If a connector block still spells its call bound timeout instead of timeout_s.

__init__(config_path=None, *, load_env=True)[source]#

Initialize configuration builder.

Parameters:
  • config_path (str | Path | None) – Path to the config.yml file. If None, the file osprey_connectors.workspace.resolve_config_path() names: OSPREY_CONFIG, else build/config.yml under the current directory, else config.yml in it.

  • load_env (bool) – When True (the default), load the env chain from the current working directory into os.environ. This env → environ passthrough is load-bearing: it feeds the ${VAR} references Claude Code expands in .mcp.json at MCP server launch time. Pass False only when the caller has already populated the environment (or must not mutate it) and wants a config load with no side effects on os.environ.

Raises:
  • FileNotFoundError – If config.yml is not found and no path is provided.

  • ValueError – If a connector block still spells its call bound timeout instead of timeout_s.

get_unexpanded_config()[source]#

Get configuration with environment variable placeholders preserved.

Returns the configuration as loaded from YAML, without expanding ${VAR_NAME} placeholders. This is useful for deployment scenarios where secrets should NOT be written to disk - instead, the placeholders are preserved and resolved at container runtime.

Returns:

Configuration with ${VAR} placeholders intact

Return type:

dict

get(path, default=None)[source]#

Get configuration value using dot notation path.

Return type:

object

osprey_connectors.config.apply_env_chain(environ, paths, *, override=True)[source]#

Apply env-chain files to environ, except the shell-only launch variables.

paths is in ascending precedence (.env.shared before .env); a path that is not a file is skipped. Each file is read with python-dotenv’s dotenv_values and written into environ in turn, so a later file wins on a key both set. Every key is applied except those _is_shell_only_env_var() names: for those environ keeps exactly what it held (set, or absent), and one warning per file names the ignored keys — never their values.

With override=False a name environ held when the call began is never written, while a later file may still replace a value this call wrote, so the local file outranks the shared one and the shell outranks both.

Returns:

The sorted names written into environ.

Return type:

list[str]

osprey_connectors.config.config_anchored_at(config_path)[source]#

Answer this process’s unqualified config lookups from config_path.

Every get_config_value() and get_facility_timezone() call that names no config resolves the default singleton, which looks at CONFIG_FILE and then where osprey_connectors.workspace.resolve_config_path() does: OSPREY_CONFIG, and the render under the working directory. A container is handed the variables or starts in its project directory, and a host verb standing at the repo root finds build/config.yml there. A verb pointed at another deployment with --repo stands in neither, and every lookup it makes would degrade to a default. Silently: a degraded answer (UTC, an empty dict) is indistinguishable from a configured one at the call site, which is how a whole archive can be synthesized against the wrong clock without anything failing.

This is the host’s half of that contract, and it is deliberately in-process rather than an exported CONFIG_FILE. The attached start path os.execvpe-replaces itself with the container runtime, and an exported variable would ride into that process’s interpolation environment; the anchor has no business outliving the verb that set it.

Scoped for the same reason — the previous default is restored on exit, so a verb pointed at one deployment with --repo cannot leave the next lookup in this process answering for it.

Never raises. A config that will not load leaves the previous default in place and warns: this makes lookups honest, and an anchor that aborted its caller would turn a degraded lookup into a failed deploy.

Parameters:

config_path (str | Path) – The rendered config this process is acting on — normally <repo>/build/config.yml (see osprey_connectors.workspace.rendered_config_path()).

Return type:

Iterator[None]

osprey_connectors.config.config_flag(value, *, key)[source]#

Read an on/off config value for what it spells.

resolve_env_vars() substitutes text, so ${USE_NS:-false} reaches a consumer as the string "false" — and bool("false") is True. Every consumer of such a switch reads it through here, so they all agree on one rule: a bool is itself, None is off, 0/1 are off/on, and a string is matched case-insensitively against true/yes/on/1 and false/no/off/0 (blank is off). Anything else — an unresolved ${VAR}, a typo, another number — is refused rather than guessed, since either guess would silently pick a behaviour nobody configured.

Parameters:
  • value (object) – The raw config value.

  • key (str) – The dotted config key, named in the refusal.

Returns:

The switch’s state.

Raises:

ValueError – When the value spells neither on nor off.

Return type:

bool

osprey_connectors.config.default_config_path()[source]#

Path of the config file the default singleton actually loaded, if any.

This answers “which config is this process’s unqualified lookups reading from” — the CONFIG_FILE target, the resolved rendered config, or a config_anchored_at() anchor, whichever produced the singleton. Callers that resolve paths relative to the config in use (e.g. LimitsValidator.resolve_database_path) anchor on this rather than re-deriving the location from the environment, which can disagree with what was actually loaded.

Side-effect free: no singleton is created and no .env chain is loaded. Returns None until something initializes the default configuration.

Return type:

str | None

osprey_connectors.config.dotenv_shell_overrides()[source]#

The shell’s own values for variables the .env entry-load overrode.

Only variables whose exported value differed from the file’s are recorded: a key the shell never set, or set to the same value, was not shadowed. Overlaying this onto os.environ reconstructs the environment the operator’s shell actually provided, which is what compose interpolation is documented against.

Return type:

dict[str, str]

osprey_connectors.config.get_agent_dir(sub_dir, host_path=False)[source]#

Get the target directory path within the agent data directory using absolute paths.

The root comes from agent_data.base_dir — the single key naming this directory — while file_paths supplies the subdirectory names. A subdirectory key absent from file_paths falls back to its own name.

Parameters:
  • sub_dir (str) – Subdirectory name (e.g., ‘registry_exports_dir’)

  • host_path (bool) – If True, force return of host filesystem path even when running in container

Returns:

Absolute path to the target directory

Return type:

str

osprey_connectors.config.get_config_builder(config_path=None, set_as_default=False)[source]#

Get configuration builder instance for full config access.

This is the primary public API for accessing the configuration system. Returns a ConfigBuilder instance that provides access to both raw configuration data and pre-computed configurable structures.

Parameters:
  • config_path (str | None) – Optional explicit path to configuration file. If provided, loads configuration from this path. If None, uses the default singleton (CONFIG_FILE env var, else the resolved rendered config).

  • set_as_default (bool) – If True and config_path is provided, also set this config as the default singleton for future calls without config_path.

Returns:

  • .raw_config: The raw YAML configuration dictionary

  • .configurable: Pre-computed configuration for framework

  • .get(path, default): Dot-notation access to config values

Return type:

ConfigBuilder instance with access to

Examples

>>> # Default configuration
>>> config = get_config_builder()
>>> timeout = config.get("execution.timeout", 30)
>>> # Load from specific path
>>> config = get_config_builder("/path/to/config.yml")
>>> raw = config.raw_config
>>> # Load and set as default for subsequent calls
>>> config = get_config_builder("/path/to/config.yml", set_as_default=True)
osprey_connectors.config.get_config_value(path, default=None, config_path=None)[source]#

Get a specific configuration value by dot-separated path.

This function provides context-aware access to configuration values, working both inside and outside framework execution contexts. Optionally, an explicit configuration file path can be provided.

Parameters:
  • path (str) – Dot-separated configuration path (e.g., “execution.timeout”)

  • default (object) – Default value to return if path is not found

  • config_path (str | None) – Optional explicit path to configuration file

Returns:

The configuration value at the specified path, or default if not found. It is typed object because the YAML decides its shape: a caller checks for the shape it needs before using it.

Raises:

ValueError – If path is empty or None

Return type:

object

Examples

>>> timeout = get_config_value("execution.timeout", 30)
>>> debug_mode = get_config_value("development.debug", False)
>>> # With explicit config path
>>> timeout = get_config_value("execution.timeout", 30, "/path/to/config.yml")
osprey_connectors.config.get_configurable(config_path=None, set_as_default=False)[source]#

Get configurable dict with automatic context detection.

This function supports both framework execution contexts and standalone execution, with optional explicit configuration path support.

Parameters:
  • config_path (str | None) – Optional explicit path to configuration file

  • set_as_default (bool) – If True and config_path is provided, set as default config

Returns:

Complete configuration dictionary with all configurable values

Return type:

dict[str, object]

osprey_connectors.config.get_facility_timezone()[source]#

Get the facility timezone from config as a ZoneInfo object.

This is the safe default resolver for every simulation synthesis primitive and timestamp render site, so it must never raise: an unloaded config (no config.yml and no CONFIG_FILE) or a misconfigured/typo’d zone name degrades to UTC with a logged warning rather than propagating to callers.

The fallback warns once per process, not once per call. Synthesis calls this per channel per chunk — thousands of times to seed one archive — and a failed load is never cached (only a successful one is), so the fallback is re-taken on every one of them. Repeating the multi-line “no config.yml found” remedy that often buries every other line of the deploy and makes a seed that is working normally read as a hung terminal. Once is deliberate rather than none: a process resolving the wrong config still has to be diagnosable from its own log.

Returns:

ZoneInfo for the configured facility timezone, defaulting to UTC.

Return type:

ZoneInfo

osprey_connectors.config.get_full_configuration(config_path=None)[source]#

Get the complete configuration dictionary.

This function provides access to the entire configurable dictionary, working both inside and outside framework execution contexts. Optionally, an explicit configuration file path can be provided.

When an explicit config_path is provided, it is also set as the default configuration so that subsequent config access without explicit path will use this configuration.

Parameters:

config_path (str | None) – Optional explicit path to configuration file. If provided, loads configuration from this path and sets it as the default.

Returns:

Complete configuration dictionary with all configurable values

Return type:

dict[str, object]

Examples

>>> # Default configuration (backward compatible)
>>> config = get_full_configuration()
>>> project_root = config.get("project_root")
>>> models = config.get("model_configs", {})
>>> # Explicit configuration path (also becomes default)
>>> config = get_full_configuration("/path/to/my-config.yml")
>>> models = config.get("model_configs", {})
>>> # Subsequent calls without path use this config
>>> other_value = get_config_value("some.setting")
osprey_connectors.config.is_unresolved_placeholder(value)[source]#

Whether value is an env-var reference resolve_env_vars() left alone.

The counterpart to resolve_env_vars(): it keeps ${VAR} verbatim when VAR is unset, so a consumer that treats what it reads as data sees the literal string "${VAR}" where a URL or a key belongs. This is the one producer of that test, so a caller never has to re-state the syntax the resolver accepts.

Parameters:

value (object) – A config value, of any type. Only a str can be a placeholder.

Returns:

True when the value is exactly one unsubstituted reference.

Return type:

bool

osprey_connectors.config.load_config(config_path=None)[source]#

Load raw configuration dictionary from YAML file.

Convenience function that returns the raw configuration dictionary as loaded from the YAML file, with environment variables resolved.

Parameters:

config_path (str | None) – Optional path to configuration file. If None, uses the default configuration (CONFIG_FILE env var, else the resolved rendered config).

Returns:

Raw configuration dictionary with all values from the YAML file.

Return type:

dict[str, object]

Examples

>>> # Load default configuration
>>> config = load_config()
>>> api_key = config.get("api", {}).get("key")
>>> # Load from specific path
>>> config = load_config("/path/to/config.yml")
>>> channels = config.get("channel_finder", {})
osprey_connectors.config.load_project_config(config_path, *, wrap_errors=False)[source]#

Load a built project’s config.yml the way the deploy path loads it.

The single entry point every project-facing command and deployment step uses to read a project’s effective config: ConfigBuilder, with the loader’s own INFO chatter quieted. Going through one function is what keeps those consumers agreeing on what the config says — a caller that hand-rolled yaml.safe_load would resolve ${VAR} without the .env passthrough ConfigBuilder performs (see load_project_dotenv()), and would miss the module flags and derived fields ConfigBuilder computes. It could then report on — or render from — a config the deploy would never have produced.

This lives here, next to ConfigBuilder, rather than in a CLI helper module: the deployment layer is one of its consumers and imports nothing from osprey.cli at module scope, so a CLI home would have made this the first such edge.

Existence checks stay at the call site. ConfigBuilder’s own FileNotFoundError advises setting CONFIG_FILE, which is the wrong instruction for a --project verb, so a caller that needs its own “no project here” message must check before calling (see osprey.cli.scaffold_cmd._load_config()).

Parameters:
  • config_path (str | Path) – Path to the project’s config.yml.

  • wrap_errors (bool) – When True, re-raise any load failure as RuntimeError naming the config path. Deployment entry points use this so an operator sees which file failed rather than a bare YAML error.

Returns:

The env-var-expanded config mapping (ConfigBuilder.raw_config).

Raises:

RuntimeError – If the load fails and wrap_errors is True.

Return type:

dict[str, Any]

osprey_connectors.config.load_project_dotenv()[source]#

Load the cwd’s env chain into os.environ, overriding existing values.

This is the env → environ passthrough the framework depends on: it feeds the ${VAR} references Claude Code expands in .mcp.json at MCP server launch time (EPICS_CA_ADDR_LIST, PHOEBUS_BRIDGE_URL, BLUESKY_*), and it makes the chain the source of truth for API keys over a stale shell export. Every key in the files is passed through, not a declared subset — narrowing it would drop Channel Access addressing with no error. The one exception is the shell-only launch variables (_is_shell_only_env_var()): apply_env_chain() leaves them as the shell set them and warns.

The chain is .env.shared then .env (osprey_connectors.dotenv.ENV_CHAIN_FILENAMES), each applied with override, so the host-local .env wins over the committed defaults on a key both set — the same local-wins precedence every other delivery path applies. A project with no .env.shared behaves exactly as it did when .env was the whole chain.

What the override replaces is not discarded: the shell’s own differing values are recorded (dotenv_shell_overrides()) so the deploy path can still see — and warn about — an export that disagrees with the store, and hand compose an environment with the shell’s precedence intact. The record is taken once per key against the merged chain, before any file is loaded: the value a key ends up with is the local file’s, so that is the value the shell’s export is judged against, and a key both files set is recorded once rather than twice.

override=True and the breadth of the copy are exactly why this must be called deliberately. Call it from process entry points only; never at import time, and never from library code that a host application merely imports. Missing files and an unreadable file are non-fatal.

A process stamped with ENV_CHAIN_APPLIED_ENV was handed its environment by a parent that chose it, and this returns without loading anything: reloading the chain would put back what the parent withheld.

osprey_connectors.config.localize_facility(dt: datetime) → datetime[source]#
osprey_connectors.config.localize_facility(dt: None) → None

Read a naive datetime as facility-local wall-clock; pass an aware one through.

A naive datetime is stamped with the facility zone – never the box $TZ, which astimezone would silently impose. get_facility_timezone() degrades to UTC when the zone is unset or unreadable.

Parameters:

dt (datetime | None) – A datetime in either state, or None.

Returns:

The same instant, timezone-aware, or None for None input.

Return type:

datetime | None

osprey_connectors.config.mapping_or_empty(value, path, source)[source]#

Return a config section as a mapping: None reads as {}, a non-mapping is refused.

Return type:

dict[str, object]

osprey_connectors.config.resolve_env_vars(data, *, environ=None)[source]#

Recursively resolve environment variables in configuration data.

Supports both simple and bash-style default value syntax: - ${VAR_NAME} — simple substitution - ${VAR_NAME:-default_value} — with default value - $VAR_NAME — simple substitution without braces

Placeholders inside claude_code.servers.*.env blocks are preserved verbatim: Claude Code expands ${VAR} in .mcp.json env at MCP server launch time, so expanding here would bake either secrets or empty strings (when vars are unset, e.g. in CI image builds) into build artifacts.

This is the public, standalone version of ConfigBuilder._resolve_env_vars. Use it when you need env-var resolution without a full ConfigBuilder instance (e.g., after a raw yaml.safe_load).

Parameters:
  • data (object) – The config data (dict/list/str/scalar) to resolve.

  • environ (Mapping[str, str] | None) – Optional mapping to resolve ${VAR} against instead of the process environment. Lets callers expand against an os.environ + .env overlay without mutating global state (e.g. the Claude Code provider loader). Defaults to os.environ.

Return type:

Any

osprey_connectors.config.unresolved_placeholders(value)[source]#

Every placeholder left in value, depth-first.

Where is_unresolved_placeholder() asks whether a value is exactly one reference, this finds every reference anywhere in a string, and in every string nested in mappings, lists and tuples — so a block a supervisor is about to hand a connector can be refused whole when any part of it is still unresolved.

Parameters:

value (object) – A config value, of any type, after resolve_env_vars().

Returns:

The placeholders found, in order, repeats included; empty when none.

Return type:

list[str]

Where a process finds its config and its agent data.

The rendered config.yml, the repo root it belongs to, and the agent-data root under it — resolved once here, for the connectors and for every framework layer that loads the same config. The rest of the deployment repo’s layout (layer directories, the image staging area, the audit and archive zones) is the framework’s, in osprey.utils.workspace.

osprey_connectors.workspace.BUILD_DIR_NAME = 'build'#

The render zone inside a deployment repo, re-created wholesale by every osprey build. The rendered config lives in it (RENDERED_CONFIG_RELPATH), which is how repo_root_for_config() tells a host’s render from a container’s project directory.

osprey_connectors.workspace.DEFAULT_AGENT_DATA_BASE_DIR = 'var/agent_data'#

Agent-data root used when a config declares no agent_data.base_dir. Under var/ rather than beside the render: memory, sessions, and artifacts have to survive rm -rf build/, which is the one guarantee the build zone does not offer.

osprey_connectors.workspace.RENDERED_CONFIG_RELPATH = 'build/config.yml'#

the source of truth is profile.yml at the repo root, and this file is what a build derives from it. Every producer and consumer of that path spells it through this constant so the two cannot drift.

Type:

The rendered config, relative to the repo root. It is an output

osprey_connectors.workspace.SIMULATION_STATE_DIR_CONFIG_KEY = 'simulation.state_dir'#

Config key naming that directory explicitly (relative paths resolve against the project root). Unset — the normal case — puts it under the agent-data root. osprey_connectors.config.ConfigBuilder’s runtime-write advisory and resolve_simulation_state_dir() read this one spelling.

osprey_connectors.workspace.SIMULATOR_LOG_DIR_RELPATH = 'var/simulator'#

the composite appends one <model>.log per served physics model here, from whichever process serves it. Durable, like the agent-data root beside it.

Type:

The simulator’s model-log directory, relative to the repo root

osprey_connectors.workspace.agent_data_base_dir(config)[source]#

Read the agent-data root out of an already-loaded config mapping.

agent_data.base_dir is the only key that names this directory. Callers holding a config dict read it through here and anchor the result themselves (the health checks and the compose generator anchor on project_root); callers with no config in hand use resolve_agent_data_root(), which loads the config and anchors on the same project_root.

Parameters:

config (Mapping[str, object] | None) – Loaded config.yml mapping, or None.

Returns:

The configured base directory, possibly relative to the caller’s anchor.

Return type:

str

osprey_connectors.workspace.anchored_path(value, project_root)[source]#

Expand ~ in a configured path and anchor a relative one at the project.

The other half of dotted_config_str(): a configured path is absolute, home-relative, or project-relative, and every consumer has to make the same three-way choice before comparing paths or creating directories.

Return type:

Path

osprey_connectors.workspace.dotted_config_str(config, key)[source]#

Read a dotted config key, or None if it does not name a real string.

None is returned for every way the key can fail to answer — a missing segment, a segment that is not a mapping, a non-string value, or an empty one — because each of those means the same thing to every caller: the key is unset, use the default. A mistyped key therefore falls through to the default rather than raising.

The single reader for the path-shaped config keys, so the checks that reject a value and the resolvers that use it cannot disagree about what the config says — including on dict versus Mapping, a difference that stays invisible only while every config arrives straight from the YAML loader.

Parameters:
  • config (Mapping[str, object] | None) – Loaded config mapping, or None.

  • key (str) – Dotted path, e.g. simulation.state_dir.

Return type:

str | None

osprey_connectors.workspace.load_osprey_config()[source]#

Load OSPREY configuration (delegates to ConfigBuilder singleton).

Delegates to the framework’s ConfigBuilder so that ${VAR:-default} environment-variable placeholders are resolved consistently.

The file is the one resolve_config_path() names.

Returns:

Parsed YAML dict (with env vars resolved), or empty dict if the file is missing.

Return type:

dict[str, Any]

osprey_connectors.workspace.rendered_config_path(repo_root)[source]#

Path to the rendered config.yml of the repo rooted at repo_root.

The one place the build/config.yml spelling is assembled, so that a caller holding a repo root never has to know which zone the render lands in.

Return type:

Path

osprey_connectors.workspace.repo_root_for_config(config_path)[source]#

The repo root that a config file at config_path belongs to.

The rendered config lives at <repo>/build/config.yml, so the repo is two levels up — except in a container, whose project directory is the render and holds config.yml at its root. One helper for both, so the “is this the build zone?” question is asked in exactly one place.

Known non-goal: a FLAT project whose own directory is literally named build is read as a render, and its parent is returned. Accepted — every runtime path derives the root through this helper, so a regen or a status check agreeing with the runtime beats a special case that would make the two disagree.

Return type:

Path

osprey_connectors.workspace.reset_config_cache()[source]#

Clear all config caches — used between tests.

The warn-once latch on the facility-timezone fallback is cleared with them. It is process state in exactly the way a cache is: left set, whichever test happened to run first would consume the single warning and every later test asserting on it would see none — an order-dependent pass that says nothing about the code.

osprey_connectors.workspace.resolve_agent_data_root()[source]#

Resolve the agent data root directory from config.

Uses agent_data.base_dir from config.yml, anchored on the repo root that resolve_project_root() resolves. Falls back to DEFAULT_AGENT_DATA_BASE_DIR relative to that root when the config declares no base directory.

Return type:

Path

osprey_connectors.workspace.resolve_config_path()[source]#

Resolve the path to the rendered config.yml.

Resolution order:
  1. OSPREY_CONFIG environment variable (with shell variable expansion). The CLI sets it on the host, every framework MCP server definition sets it, and so does the compose service of every container whose working directory does not hold the render: the Bluesky bridge, its queueserver and the Bluesky sidecar run from /app with the config mounted at /app/project/config.yml.

  2. build/config.yml under the current working directory — standing in a repo root with a render in it.

  3. config.yml under the current working directory — a container project directory, whose root is the render, and the path reported when nothing exists at all.

This is also where a lookup that names no config reads from (osprey_connectors.config.get_config_value() and the connector factory’s no-argument forms), once CONFIG_FILE is ruled out, so a process has one answer however it asks.

CONFIG_FILE is deliberately NOT read here, even though osprey.agent_runner.artifact_resolve.deployed_config_path() reads it ahead of OSPREY_CONFIG. That helper answers for one deployed process whose compose service sets the variable; this one answers for the framework everywhere, and CONFIG_FILE is a name generic enough that honoring it globally would let an unrelated export redirect every OSPREY process on the host. Where a container is handed both, they agree by construction rather than by precedence. The Bluesky compose services set both to the one mounted path. The dispatch worker’s sets CONFIG_FILE to /app/<project>/build/config.yml, and the image’s WORKDIR is /app/<project>, so step 2 above finds that same file.

Return type:

Path

osprey_connectors.workspace.resolve_path(path_str)[source]#

Resolve a path relative to the project root from config.

Absolute paths are returned as-is. Relative paths are resolved against project_root from the active configuration.

Parameters:

path_str (str) – Path string (absolute or relative to project root)

Returns:

Resolved absolute Path object

Return type:

Path

osprey_connectors.workspace.resolve_project_root(config=None)[source]#

Resolve the repo root that relative configured paths anchor against.

project_root names the deployment repo — the directory holding profile.yml — and not the directory holding config.yml: the render lives one level down, in build/, so anchoring on the config file’s own parent would put every relative path inside the disposable zone.

Resolution order:
  1. The config’s own project_root key, when it names a directory that exists here. That qualifier is what makes it right inside a container, where the repo was built at one path and runs at another: a deployed service reads a config STAGED on the host — the compose generator flattens the host render into build/services/<svc>/config.yml, and the service’s compose file bind-mounts that over the one in the image — so its project_root is a host path that names nothing in here. Anchoring on it would put the agent-data root, and every other relative path, outside the mounted volume. Same rule and same reason as osprey.deployment.compose_generator.resolve_repo_root().

  2. The repo the resolved config path sits in — its parent, or that parent’s parent when the config is in the build/ zone. Filesystem truth, and correct in every container layout: the mount target names the render, so unwrapping it names the repo.

  3. The nearest ancestor of the working directory holding profile.yml, the marker every OSPREY verb walks up to. Reached only when no config file exists, so it can never out-vote one; without it a process started in an unbuilt render would anchor every relative path inside build/.

  4. The configured value after all, when there is no config file and no marker to derive from — a build rendered with --runtime-root records a path that exists only on the machine it will run on, and has nothing better.

  5. The current working directory, when there is neither. CLAUDE_PROJECT_DIR is not an input: this resolver serves processes outside any agent session as well, and a harness variable must not redirect them.

Parameters:

config (Mapping[str, object] | None) – Loaded config.yml mapping, or None to consult only the config path (callers that have not loaded one).

Return type:

Path

osprey_connectors.workspace.resolve_shared_data_root(config=None)[source]#

Resolve the agent data root WITHOUT session-path isolation.

Use for stores whose data must be visible to long-lived daemons (gallery, ARIEL) that run outside any specific session. Logical session isolation is handled at the index level via entry metadata (e.g. ArtifactEntry.session_id).

Parameters:

config (Mapping[str, object] | None) – An already-loaded config mapping; None loads the config. One derivation serves both a store’s writer and a reader that already holds a config.

Return type:

Path

osprey_connectors.workspace.resolve_simulation_state_dir(config, project_root)[source]#

Resolve the directory holding the mutable active_scenarios state file.

The state file is the one piece of simulation state that changes after a build, so it lives under the agent-data root rather than in data/: everything in a project’s data/ tree is build-owned and checksummed (see osprey.cli.templates.manifest.calculate_file_checksums()), and a scenario switch is not project drift.

The one spelling serves config, the compose generator that renders the container’s bind-mount source, and the build injector that pre-creates it, so all three resolve the same directory.

A mistyped SIMULATION_STATE_DIR_CONFIG_KEY (anything but a non-empty string) falls through to the default rather than raising, matching how osprey_connectors.config.ConfigBuilder’s runtime-write advisory reads the same key.

Parameters:
  • config (Mapping[str, object] | None) – Loaded config.yml mapping, or None.

  • project_root (Path) – Root the relative paths above resolve against.

Returns:

Absolute path to the state directory (not created here).

Return type:

Path

The deployment’s env chain: which files it is, and how they are read.

A tiny dependency-free parser (no python-dotenv import) and the chain it reads — .env.shared then .env at the repo root, later file wins. Every OSPREY process loads that chain on start-up (osprey_connectors.config.load_project_dotenv()), so the reading half lives here. Writing the files is the framework’s deployment layer’s (osprey.deployment.dotenv).

osprey_connectors.dotenv.ENV_CHAIN_APPLIED_ENV = 'OSPREY_ENV_CHAIN_APPLIED'#

Set by a parent that already applied the env chain and hands its child a resolved environment it chose. A process that carries it does not load the chain again: reloading would put back what the parent withheld.

osprey_connectors.dotenv.ENV_CHAIN_FILENAMES: tuple[str, ...] = ('.env.shared', '.env')#

every mechanism that delivers these files must end up with .env winning over .env.shared on a key both set. Spelled here, once, because the mechanics of “later wins” differ per delivery path — a compose env_file: list is read in this order, an override=True loader loads in this order, and an override=False (first-loaded-wins) loader must load it REVERSED to reach the same answer. Membership is fixed: a chain member is a file the deployment knows by name, not a directory scan.

Type:

The env chain in ASCENDING precedence order

osprey_connectors.dotenv.ENV_LOCAL_FILENAME = '.env'#

the deployment’s one secret store, hand-edited and written back to by osprey up.

Type:

The host-local half of the env chain, at the repo root

osprey_connectors.dotenv.ENV_SHARED_FILENAME = '.env.shared'#

The committed, non-secret defaults half of the env chain, at the repo root.

osprey_connectors.dotenv.chain_files(repo_root)[source]#

The env-chain files that exist under repo_root, ascending precedence.

Returns the existing members of ENV_CHAIN_FILENAMES in that order — .env.shared before .env — so a caller can hand the list straight to whatever consumes it (a compose env_file: list, an override=True loader, a $-scan) and get local-over-shared precedence from the order alone. Missing members are skipped rather than reported: a project with neither file, only defaults, or only local settings are all valid shapes, and the list is empty/short accordingly.

Parameters:

repo_root (Path) – Directory the chain lives in (the deployment repo root).

Returns:

Existing chain files, lowest precedence first.

Return type:

list[Path]

osprey_connectors.dotenv.merge_chain(repo_root)[source]#

Parse the env chain under repo_root into one dict; later file wins.

The chain is read in chain_files() order, each file’s entries laid over the previous file’s, so a key set in both .env.shared and .env ends up with the .env value — the single in-process answer to “what does this deployment’s env chain say?”.

Key order in the result is first-seen: the shared defaults in file order, then keys only the local file introduces. A key both files set keeps its shared-file position and takes the local value, so the merged view reads like the defaults file with the local overrides applied in place.

Nothing is written to os.environ here — the caller decides whether these values overlay a subprocess environment, a compose file, or nothing at all.

Parameters:

repo_root (Path) – Directory the chain lives in (the deployment repo root).

Returns:

Merged KEY=VALUE pairs; empty when no chain file exists.

Return type:

dict[str, str]

osprey_connectors.dotenv.parse_dotenv_file(path)[source]#

Parse a .env file into a dict of environment variables.

Handles KEY=VALUE lines, # comments, blank lines, an optional export prefix, and quoted values (single or double quotes stripped from the value boundaries).

Return type:

dict[str, str]

osprey_connectors.dotenv.parse_dotenv_text(text)[source]#

Parse .env text into a dict of environment variables.

The in-memory half of parse_dotenv_file(), for callers holding the file’s contents already (a locked read-modify-write, a rendered template).

Return type:

dict[str, str]

PyYAML safe loading and dumping on libyaml when it is installed.

yaml.safe_load always runs PyYAML’s pure-Python scanner, even when the yaml wheel shipped the libyaml bindings — the C scanner is only reached by naming yaml.CSafeLoader explicitly. The two loaders share the constructor and the resolver, so a document parses to the same objects either way; only the scanning speed differs, by an order of magnitude. Every hot parse of a deployment’s YAML (osprey build re-reads its rendered config.yml many times per build) goes through safe_load() here rather than through yaml.safe_load directly. The emitter is the same story: yaml.safe_dump never reaches libyaml, and the two emitters write the same bytes for the block-style documents a build writes, so every hot write goes through safe_dump().

osprey_connectors.yaml_loader.safe_dump(data: object, stream: None = None, **kwargs: Any) → str[source]#
osprey_connectors.yaml_loader.safe_dump(data: object, stream: IO[str], **kwargs: Any) → None

Emit one YAML document the way yaml.safe_dump does, on the fastest dumper.

Parameters:
  • data (object) – Plain Python objects; anything else is refused, as yaml.safe_dump refuses it.

  • stream (IO[str] | None) – An open text file to write to; None returns the text.

  • **kwargs (Any) – The emitter options yaml.safe_dump takes (sort_keys, default_flow_style, allow_unicode, width, …).

Returns:

The document text when stream is None, else None.

Raises:

yaml.representer.RepresenterError – On an object the safe dumper cannot represent.

Return type:

str | None

osprey_connectors.yaml_loader.safe_load(stream)[source]#

Parse one YAML document the way yaml.safe_load does, on the fastest loader.

Parameters:

stream (str | bytes | IO[str] | IO[bytes]) – The document — a string, bytes, or an open file.

Returns:

The document as plain Python objects; None for an empty document.

Raises:

yaml.YAMLError – On a document that does not parse.

Return type:

Any

osprey_connectors.yaml_loader.safe_loader()[source]#

The safe loader class to parse with: libyaml’s when present, else PyYAML’s.

Resolved at call time rather than at import, so a build that runs without the C bindings falls back on the same code path a test can exercise by removing yaml.CSafeLoader.

Return type:

type[CSafeLoader] | type[SafeLoader]