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 MCP [`Backoff`](objectiveai_sdk::mcp::Backoff) bundle this CLI
133 /// process uses for ALL of its own MCP clients (the streaming
134 /// conduit, through which every CLI MCP connection flows). Built from
135 /// the single merged (`--final`) `api.mcp_timeout_ms` config value
136 /// (default 60000ms): that value sets the connect timeout, the
137 /// per-call timeout, AND the backoff max-elapsed-time; the remaining
138 /// exponential-backoff knobs keep [`Backoff::default`]'s values.
139 /// Callers that need to distinguish "configured" from "unset" (the
140 /// api spawn) use [`Self::resolve_mcp_timeout_ms_opt`] instead.
141 pub async fn resolve_mcp_backoff(
142 &self,
143 ) -> Result<objectiveai_sdk::mcp::Backoff, crate::error::Error> {
144 let timeout_ms = self.resolve_mcp_timeout_ms_opt().await?.unwrap_or(60000);
145 Ok(objectiveai_sdk::mcp::Backoff {
146 connect_timeout_ms: timeout_ms,
147 call_timeout_ms: timeout_ms,
148 max_elapsed_time_ms: timeout_ms,
149 ..Default::default()
150 })
151 }
152
153 /// The configured `api.mcp_timeout_ms`, or `None` when unset —
154 /// preserving the distinction [`Self::resolve_mcp_backoff`] erases.
155 ///
156 /// The api spawn uses this to project the `MCP_*` timeout env onto
157 /// the spawned (machine-wide, shared) server ONLY when the user
158 /// explicitly set a timeout. Leaving it unset lets the api resolve it
159 /// itself — `<OBJECTIVEAI_DIR>/.env`, then its built-in default. That
160 /// fallback is behaviorally identical to passing the canonical
161 /// default in production, and it's what the test `.env` (which sets
162 /// `MCP_BACKOFF_*=0` to fast-fail real MCP errors instead of masking
163 /// them with retry storms) relies on: unconditionally setting the
164 /// default here would clobber that `0` on the shared api.
165 pub async fn resolve_mcp_timeout_ms_opt(
166 &self,
167 ) -> Result<Option<u64>, crate::error::Error> {
168 let mut config = self
169 .filesystem
170 .read_config_view(objectiveai_sdk::cli::command::GetScope::Final)
171 .await?;
172 Ok(config.api().get_mcp_timeout_ms())
173 }
174
175 /// The synchronous-response viewer client, built on first use and
176 /// memoized.
177 ///
178 /// Address resolution mirrors [`Self::api_client`]:
179 /// `viewer.address` from the merged config view when set, else
180 /// the `viewer spawn` flow. Signature: env `VIEWER_SIGNATURE`,
181 /// else `viewer.signature` from the same view.
182 pub async fn viewer_client(&self) -> Result<&ViewerClient, crate::error::Error> {
183 self.viewer
184 .get_or_try_init(|| async {
185 let mut config = self
186 .filesystem
187 .read_config_view(objectiveai_sdk::cli::command::GetScope::Final)
188 .await?;
189 let address = match config.viewer().get_address() {
190 Some(a) => ensure_scheme(a),
191 None => crate::command::viewer::spawn::spawn(self).await?,
192 };
193 let signature = env("VIEWER_SIGNATURE")
194 .or_else(|| config.viewer().get_signature().map(String::from));
195 Ok(ViewerClient::new(address, signature))
196 })
197 .await
198 }
199
200 /// The db pool, connected on first use and memoized — the
201 /// pool-only view of [`Self::db_handle`].
202 pub async fn db_client(&self) -> Result<&db::Pool, crate::error::Error> {
203 Ok(&self.db_handle().await?.pool)
204 }
205
206 /// The db handle — pool plus the admin coordinates it was built
207 /// from (address, admin user/password, database name), which
208 /// [`crate::db::compartment`] needs to mint derived per-plugin
209 /// connection strings. Connected on first use (ensuring the
210 /// application database + schema exist) and memoized. Must NOT
211 /// connect eagerly: commands like `db config ...` and `db spawn`
212 /// have to work before any database exists — they're how you
213 /// bring one up in the first place.
214 ///
215 /// URL resolution: when `db.address` is set in the merged config
216 /// view, a remote-postgres URL is composed from the `config db`
217 /// parts; otherwise the `db spawn` flow returns the local
218 /// cluster's lock-published `postgresql://` URL (starting the
219 /// objectiveai-db supervisor if needed), whose admin coordinates
220 /// are parsed back out of that URL (our own
221 /// `postgresql://postgres:{password}@{host}:{port}` shape).
222 pub async fn db_handle(&self) -> Result<&db::DbHandle, crate::error::Error> {
223 self.db
224 .get_or_try_init(|| async {
225 let mut config = self
226 .filesystem
227 .read_config_view(objectiveai_sdk::cli::command::GetScope::Final)
228 .await?;
229 let address = config.db().get_address().map(String::from);
230 let (url, address, admin_user, admin_password) = match address {
231 Some(address) => {
232 let db = config.db();
233 let user = db
234 .get_user()
235 .unwrap_or(crate::filesystem::config::DB_DEFAULT_USER)
236 .to_string();
237 let password = db
238 .get_password()
239 .unwrap_or(crate::filesystem::config::DB_DEFAULT_PASSWORD)
240 .to_string();
241 let url = db::config_url(&address, &user, &password);
242 (url, address, user, password)
243 }
244 None => {
245 let url = crate::command::db::spawn::spawn(self).await?;
246 let (address, user, password) =
247 parse_spawn_db_url(&url).ok_or_else(|| {
248 crate::error::Error::Instance(format!(
249 "db spawn published an unparseable URL: {url}"
250 ))
251 })?;
252 (url, address, user, password)
253 }
254 };
255 let database = config
256 .db()
257 .get_database()
258 .unwrap_or(crate::filesystem::config::DB_DEFAULT_DATABASE)
259 .to_string();
260 let pool = db::init(&url, &database).await?;
261 Ok(db::DbHandle {
262 pool,
263 address,
264 admin_user,
265 admin_password,
266 database,
267 })
268 })
269 .await
270 }
271
272 /// Detach this clone's API-client cell. MUST be called after
273 /// mutating `config.agent_instance_hierarchy` or
274 /// `config.mcp_session_id` on a cloned `Context`: the memoized
275 /// `HttpClient` snapshots those into headers, so a shared cell
276 /// would either serve the base identity to this clone or poison
277 /// the base context with this clone's identity. The viewer/db
278 /// cells stay shared — neither client carries identity.
279 pub fn reset_api_client(&mut self) {
280 self.api = Arc::new(OnceCell::new());
281 }
282}
283
284/// Build the SDK `HttpClient` for this cli process. `address` is the
285/// already-resolved API base URL; every other field's precedence is
286/// `env var → on-disk config (merged final view) → SDK default`. The
287/// SDK's `env` feature is still enabled in `Cargo.toml`, but every
288/// value we pass in is already resolved (Some/None) so the SDK never
289/// reaches its own env fallback — the precedence chain is ours.
290///
291/// The viewer-mirror headers (`x_viewer_signature`,
292/// `x_viewer_address`) are deliberately not set — viewer discovery is
293/// lock-based now and the API client no longer carries them.
294///
295/// Sourcing `agent_instance_hierarchy` and `mcp_session_id` from
296/// `cli_config` is deliberate: those are env-populated at startup by
297/// `EnvConfigBuilder` *and* mutated for per-request overrides at the
298/// MCP boundary (see the per-call `X-OBJECTIVEAI-AGENT-INSTANCE-
299/// HIERARCHY` header stamp in `objectiveai-mcp`). Re-reading the env
300/// here would silently drop those overrides.
301fn build_http_client(
302 cli_config: &Config,
303 config: &mut crate::filesystem::config::Config,
304 address: String,
305) -> HttpClient {
306 // Every header value comes from the FINAL merged config view — never
307 // re-read from process env here. The config layer is the single source
308 // of truth (env is already folded in at the appropriate precedence when
309 // the view is built), so reading env again would double-source values.
310 let authorization =
311 config.api().get_objectiveai_authorization().map(String::from);
312
313 let user_agent = config.api().get_user_agent().map(String::from);
314
315 let x_title = config.api().get_x_title().map(String::from);
316
317 let http_referer = config.api().get_http_referer().map(String::from);
318
319 let x_github_authorization =
320 config.api().get_github_authorization().map(String::from);
321
322 let x_openrouter_authorization =
323 config.api().get_openrouter_authorization().map(String::from);
324
325 let x_mcp_authorization: Option<std::collections::HashMap<String, String>> =
326 config
327 .api()
328 .get_mcp_authorization()
329 .map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect());
330
331 // From cli_config (env-populated at startup, mutable per request
332 // at the MCP boundary) — never re-read from env here.
333 let agent_instance_hierarchy = Some(cli_config.agent_instance_hierarchy.clone());
334 let mcp_session_id = cli_config.mcp_session_id.clone();
335
336 HttpClient::new(
337 reqwest::Client::new(),
338 Some(address),
339 authorization,
340 user_agent,
341 x_title,
342 http_referer,
343 x_github_authorization,
344 x_openrouter_authorization,
345 x_mcp_authorization,
346 None::<String>,
347 None::<String>,
348 agent_instance_hierarchy,
349 mcp_session_id,
350 )
351}
352
353/// Ensure an explicit scheme on a configured address: leave
354/// `http://`/`https://` untouched, otherwise prefix `http://` —
355/// regardless of whether the host is an IPv4, IPv6, or hostname.
356pub(crate) fn ensure_scheme(a: &str) -> String {
357 if a.starts_with("http://") || a.starts_with("https://") {
358 a.to_string()
359 } else {
360 format!("http://{a}")
361 }
362}
363
364/// Parse `(host:port, user, password)` out of the db spawn lock's
365/// published URL. The format is OUR OWN — `objectiveai-db` publishes
366/// exactly `postgresql://{user}:{percent-encoded password}@{host}:{port}`
367/// (see its `connection_string`) — so this is a structural split, not
368/// a general URL parser. `None` on any shape mismatch.
369fn parse_spawn_db_url(url: &str) -> Option<(String, String, String)> {
370 let rest = url
371 .strip_prefix("postgresql://")
372 .or_else(|| url.strip_prefix("postgres://"))?;
373 let (credentials, address) = rest.rsplit_once('@')?;
374 let (user, encoded_password) = credentials.split_once(':')?;
375 let password = percent_encoding::percent_decode_str(encoded_password)
376 .decode_utf8()
377 .ok()?
378 .into_owned();
379 Some((address.to_string(), user.to_string(), password))
380}
381
382fn env(name: &str) -> Option<String> {
383 std::env::var(name).ok()
384}
385
386#[cfg(test)]
387mod tests {
388 use super::ensure_scheme;
389
390 #[test]
391 fn ensure_scheme_cases() {
392 assert_eq!(ensure_scheme("127.0.0.1"), "http://127.0.0.1");
393 assert_eq!(ensure_scheme("127.0.0.1:8080"), "http://127.0.0.1:8080");
394 assert_eq!(ensure_scheme("::1"), "http://::1");
395 assert_eq!(ensure_scheme("api.x"), "http://api.x");
396 assert_eq!(ensure_scheme("http://api.x"), "http://api.x");
397 assert_eq!(ensure_scheme("https://api.x"), "https://api.x");
398 }
399}