objectiveai_cli/context.rs
1//! Process-wide state threaded into every bare-naked `command::*::execute`.
2//!
3//! `Context` is constructed once in `main.rs` (or by a programmatic
4//! embedder) — synchronously and infallibly, no IO — then borrowed
5//! into the command tree. The three service clients are LAZY: the
6//! first `api_client()` / `viewer_client()` / `db_client()` call
7//! resolves the server's address (on-disk config, else the matching
8//! spawn flow, which itself short-circuits to the lock-published URL
9//! when the server is already up), builds the client, and memoizes it
10//! in a `tokio::sync::OnceCell` shared across `Context` clones (Arc).
11//! Concurrent callers coalesce on one initialization; a failed init
12//! is not cached, so the next call retries. Commands that never touch
13//! a service never spawn or connect to it.
14//!
15//! Identity hazard: the memoized API `HttpClient` snapshots
16//! `config.agent_instance_hierarchy` + `config.mcp_session_id` into
17//! headers. A clone that mutates those fields MUST call
18//! [`Context::reset_api_client`] afterwards — see that method's doc.
19
20use std::sync::Arc;
21
22use objectiveai_sdk::HttpClient;
23use tokio::sync::OnceCell;
24
25use crate::db;
26use crate::filesystem;
27use crate::plugin_path::PluginPath;
28use crate::run::Config;
29use crate::viewer_client::ViewerClient;
30
31#[derive(Clone)]
32pub struct Context {
33 pub config: Config,
34 pub filesystem: filesystem::Client,
35 /// The plugin a command is running on behalf of, when it was
36 /// invoked through a plugin's nested-command protocol. Assembled
37 /// from the `OBJECTIVEAI_PLUGIN_*` env vars (via `Config`).
38 pub plugin: Option<PluginPath>,
39 /// Lazily-built API `HttpClient` — see [`Context::api_client`].
40 api: Arc<OnceCell<HttpClient>>,
41 /// Lazily-built viewer client — see [`Context::viewer_client`].
42 /// No per-request identity; always shared across clones.
43 viewer: Arc<OnceCell<ViewerClient>>,
44 /// Lazily-connected db handle (pool + admin coordinates) — see
45 /// [`Context::db_handle`]. No per-request identity; always
46 /// shared across clones.
47 db: Arc<OnceCell<db::DbHandle>>,
48 /// Lazily-initialized WASI python runtime — see
49 /// [`Context::python`]. No per-request identity; always shared
50 /// across clones.
51 python: Arc<OnceCell<crate::python::Python>>,
52}
53
54impl Context {
55 pub fn new(config: Config) -> Self {
56 let filesystem = filesystem::Client::new(
57 config.objectiveai_dir.clone(),
58 config.objectiveai_state.clone(),
59 config.commit_author_name.clone(),
60 config.commit_author_email.clone(),
61 );
62 let plugin = PluginPath::from_parts(
63 config.plugin_owner.clone(),
64 config.plugin_repository.clone(),
65 config.plugin_version.clone(),
66 );
67 Self {
68 config,
69 filesystem,
70 plugin,
71 api: Arc::new(OnceCell::new()),
72 viewer: Arc::new(OnceCell::new()),
73 db: Arc::new(OnceCell::new()),
74 python: Arc::new(OnceCell::new()),
75 }
76 }
77
78 /// The WASI python runtime, initialized on first use and
79 /// memoized. First use machine-wide JIT-compiles the embedded
80 /// interpreter and publishes `<bin>/cache/rustpython-<hash>.cwasm`
81 /// under the bin lock; later uses deserialize that artifact in
82 /// milliseconds. Commands that never execute python never pay
83 /// either cost.
84 pub async fn python(&self) -> Result<&crate::python::Python, crate::error::Error> {
85 self.python
86 .get_or_try_init(|| crate::python::Python::initialize(self.filesystem.bin_dir()))
87 .await
88 }
89
90 /// The API `HttpClient`, built on first use and memoized.
91 ///
92 /// Address resolution: `api.address` from the merged (`--final`)
93 /// config view when set, else the `api spawn` flow — which
94 /// returns the lock-published URL of an already-running api
95 /// without spawning, or starts one and waits for its lock.
96 pub async fn api_client(&self) -> Result<&HttpClient, crate::error::Error> {
97 self.api
98 .get_or_try_init(|| async {
99 let mut config = self
100 .filesystem
101 .read_config_view(objectiveai_sdk::cli::command::GetScope::Final)
102 .await?;
103 let address = match config.api().get_address() {
104 Some(a) => ensure_scheme(a),
105 None => crate::command::api::spawn::spawn(self).await?,
106 };
107 Ok(build_http_client(&self.config, &mut config, address))
108 })
109 .await
110 }
111
112 /// Builds an `HttpClient` for direct GitHub reads (agents / swarms /
113 /// functions / profiles) — **without** spawning or contacting the
114 /// ObjectiveAI API. The `github_*` methods talk to github.com directly
115 /// and never use the base `address`, so we hand it a deliberately
116 /// invalid one: any accidental API call through this client fails loudly
117 /// instead of silently hitting a real server. `x_github_authorization`
118 /// (from config) authenticates the GitHub requests. Built fresh per
119 /// call — these commands are short-lived and don't memoize a client.
120 pub async fn github_http_client(
121 &self,
122 ) -> Result<HttpClient, crate::error::Error> {
123 let mut config = self
124 .filesystem
125 .read_config_view(objectiveai_sdk::cli::command::GetScope::Final)
126 .await?;
127 // Tripwire address — this client must only be used for github_* calls.
128 let address = "https://api.invalid.objectiveai-github-client-only/".to_string();
129 Ok(build_http_client(&self.config, &mut config, address))
130 }
131
132 /// The synchronous-response viewer client, built on first use and
133 /// memoized.
134 ///
135 /// Address resolution mirrors [`Self::api_client`]:
136 /// `viewer.address` from the merged config view when set, else
137 /// the `viewer spawn` flow. Signature: env `VIEWER_SIGNATURE`,
138 /// else `viewer.signature` from the same view.
139 pub async fn viewer_client(&self) -> Result<&ViewerClient, crate::error::Error> {
140 self.viewer
141 .get_or_try_init(|| async {
142 let mut config = self
143 .filesystem
144 .read_config_view(objectiveai_sdk::cli::command::GetScope::Final)
145 .await?;
146 let address = match config.viewer().get_address() {
147 Some(a) => ensure_scheme(a),
148 None => crate::command::viewer::spawn::spawn(self).await?,
149 };
150 let signature = env("VIEWER_SIGNATURE")
151 .or_else(|| config.viewer().get_signature().map(String::from));
152 Ok(ViewerClient::new(address, signature))
153 })
154 .await
155 }
156
157 /// The db pool, connected on first use and memoized — the
158 /// pool-only view of [`Self::db_handle`].
159 pub async fn db_client(&self) -> Result<&db::Pool, crate::error::Error> {
160 Ok(&self.db_handle().await?.pool)
161 }
162
163 /// The db handle — pool plus the admin coordinates it was built
164 /// from (address, admin user/password, database name), which
165 /// [`crate::db::compartment`] needs to mint derived per-plugin
166 /// connection strings. Connected on first use (ensuring the
167 /// application database + schema exist) and memoized. Must NOT
168 /// connect eagerly: commands like `db config ...` and `db spawn`
169 /// have to work before any database exists — they're how you
170 /// bring one up in the first place.
171 ///
172 /// URL resolution: when `db.address` is set in the merged config
173 /// view, a remote-postgres URL is composed from the `config db`
174 /// parts; otherwise the `db spawn` flow returns the local
175 /// cluster's lock-published `postgresql://` URL (starting the
176 /// objectiveai-db supervisor if needed), whose admin coordinates
177 /// are parsed back out of that URL (our own
178 /// `postgresql://postgres:{password}@{host}:{port}` shape).
179 pub async fn db_handle(&self) -> Result<&db::DbHandle, crate::error::Error> {
180 self.db
181 .get_or_try_init(|| async {
182 let mut config = self
183 .filesystem
184 .read_config_view(objectiveai_sdk::cli::command::GetScope::Final)
185 .await?;
186 let address = config.db().get_address().map(String::from);
187 let (url, address, admin_user, admin_password) = match address {
188 Some(address) => {
189 let db = config.db();
190 let user = db
191 .get_user()
192 .unwrap_or(crate::filesystem::config::DB_DEFAULT_USER)
193 .to_string();
194 let password = db
195 .get_password()
196 .unwrap_or(crate::filesystem::config::DB_DEFAULT_PASSWORD)
197 .to_string();
198 let url = db::config_url(&address, &user, &password);
199 (url, address, user, password)
200 }
201 None => {
202 let url = crate::command::db::spawn::spawn(self).await?;
203 let (address, user, password) =
204 parse_spawn_db_url(&url).ok_or_else(|| {
205 crate::error::Error::Instance(format!(
206 "db spawn published an unparseable URL: {url}"
207 ))
208 })?;
209 (url, address, user, password)
210 }
211 };
212 let database = config
213 .db()
214 .get_database()
215 .unwrap_or(crate::filesystem::config::DB_DEFAULT_DATABASE)
216 .to_string();
217 let pool = db::init(&url, &database).await?;
218 Ok(db::DbHandle {
219 pool,
220 address,
221 admin_user,
222 admin_password,
223 database,
224 })
225 })
226 .await
227 }
228
229 /// Detach this clone's API-client cell. MUST be called after
230 /// mutating `config.agent_instance_hierarchy` or
231 /// `config.mcp_session_id` on a cloned `Context`: the memoized
232 /// `HttpClient` snapshots those into headers, so a shared cell
233 /// would either serve the base identity to this clone or poison
234 /// the base context with this clone's identity. The viewer/db
235 /// cells stay shared — neither client carries identity.
236 pub fn reset_api_client(&mut self) {
237 self.api = Arc::new(OnceCell::new());
238 }
239}
240
241/// Build the SDK `HttpClient` for this cli process. `address` is the
242/// already-resolved API base URL; every other field's precedence is
243/// `env var → on-disk config (merged final view) → SDK default`. The
244/// SDK's `env` feature is still enabled in `Cargo.toml`, but every
245/// value we pass in is already resolved (Some/None) so the SDK never
246/// reaches its own env fallback — the precedence chain is ours.
247///
248/// The viewer-mirror headers (`x_viewer_signature`,
249/// `x_viewer_address`) are deliberately not set — viewer discovery is
250/// lock-based now and the API client no longer carries them.
251///
252/// Sourcing `agent_instance_hierarchy` and `mcp_session_id` from
253/// `cli_config` is deliberate: those are env-populated at startup by
254/// `EnvConfigBuilder` *and* mutated for per-request overrides at the
255/// MCP boundary (see the per-call `X-OBJECTIVEAI-AGENT-INSTANCE-
256/// HIERARCHY` header stamp in `objectiveai-mcp`). Re-reading the env
257/// here would silently drop those overrides.
258fn build_http_client(
259 cli_config: &Config,
260 config: &mut crate::filesystem::config::Config,
261 address: String,
262) -> HttpClient {
263 // Every header value comes from the FINAL merged config view — never
264 // re-read from process env here. The config layer is the single source
265 // of truth (env is already folded in at the appropriate precedence when
266 // the view is built), so reading env again would double-source values.
267 let authorization =
268 config.api().get_objectiveai_authorization().map(String::from);
269
270 let user_agent = config.api().get_user_agent().map(String::from);
271
272 let x_title = config.api().get_x_title().map(String::from);
273
274 let http_referer = config.api().get_http_referer().map(String::from);
275
276 let x_github_authorization =
277 config.api().get_github_authorization().map(String::from);
278
279 let x_openrouter_authorization =
280 config.api().get_openrouter_authorization().map(String::from);
281
282 let x_mcp_authorization: Option<std::collections::HashMap<String, String>> =
283 config
284 .api()
285 .get_mcp_authorization()
286 .map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect());
287
288 // From cli_config (env-populated at startup, mutable per request
289 // at the MCP boundary) — never re-read from env here.
290 let agent_instance_hierarchy = Some(cli_config.agent_instance_hierarchy.clone());
291 let mcp_session_id = cli_config.mcp_session_id.clone();
292
293 HttpClient::new(
294 reqwest::Client::new(),
295 Some(address),
296 authorization,
297 user_agent,
298 x_title,
299 http_referer,
300 x_github_authorization,
301 x_openrouter_authorization,
302 x_mcp_authorization,
303 None::<String>,
304 None::<String>,
305 agent_instance_hierarchy,
306 mcp_session_id,
307 )
308}
309
310/// Ensure an explicit scheme on a configured address: leave
311/// `http://`/`https://` untouched, otherwise prefix `http://` —
312/// regardless of whether the host is an IPv4, IPv6, or hostname.
313pub(crate) fn ensure_scheme(a: &str) -> String {
314 if a.starts_with("http://") || a.starts_with("https://") {
315 a.to_string()
316 } else {
317 format!("http://{a}")
318 }
319}
320
321/// Parse `(host:port, user, password)` out of the db spawn lock's
322/// published URL. The format is OUR OWN — `objectiveai-db` publishes
323/// exactly `postgresql://{user}:{percent-encoded password}@{host}:{port}`
324/// (see its `connection_string`) — so this is a structural split, not
325/// a general URL parser. `None` on any shape mismatch.
326fn parse_spawn_db_url(url: &str) -> Option<(String, String, String)> {
327 let rest = url
328 .strip_prefix("postgresql://")
329 .or_else(|| url.strip_prefix("postgres://"))?;
330 let (credentials, address) = rest.rsplit_once('@')?;
331 let (user, encoded_password) = credentials.split_once(':')?;
332 let password = percent_encoding::percent_decode_str(encoded_password)
333 .decode_utf8()
334 .ok()?
335 .into_owned();
336 Some((address.to_string(), user.to_string(), password))
337}
338
339fn env(name: &str) -> Option<String> {
340 std::env::var(name).ok()
341}
342
343#[cfg(test)]
344mod tests {
345 use super::ensure_scheme;
346
347 #[test]
348 fn ensure_scheme_cases() {
349 assert_eq!(ensure_scheme("127.0.0.1"), "http://127.0.0.1");
350 assert_eq!(ensure_scheme("127.0.0.1:8080"), "http://127.0.0.1:8080");
351 assert_eq!(ensure_scheme("::1"), "http://::1");
352 assert_eq!(ensure_scheme("api.x"), "http://api.x");
353 assert_eq!(ensure_scheme("http://api.x"), "http://api.x");
354 assert_eq!(ensure_scheme("https://api.x"), "https://api.x");
355 }
356}