Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(agent): use macro_env_var crate correctly (#4153)
Will Hutchinson9bdd341412a0
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex dd1f0d6c7e..553c3bb9cb 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -7,6 +7,7 @@"ai_usage","attachment","cowlike",+ "macro_env_var","macro_user_id","macro_uuid","model-entity",@@ -256,6 +257,7 @@"filter_ast","frecency","item_filters",+ "macro_env_var","macro_user_id","macro_uuid","model",@@ -577,6 +579,7 @@"filter_ast","frecency","item_filters",+ "macro_env_var","macro_user_id","macro_uuid","model",@@ -605,6 +608,7 @@"filter_ast","frecency","item_filters",+ "macro_env_var","macro_user_id","macro_uuid","model",@@ -631,6 +635,7 @@"filter_ast","frecency","item_filters",+ "macro_env_var","macro_user_id","macro_uuid","model",@@ -659,6 +664,7 @@"filter_ast","frecency","item_filters",+ "macro_env_var","macro_user_id","macro_uuid","model",@@ -906,6 +912,7 @@"filter_ast","frecency","item_filters",+ "macro_env_var","macro_user_id","macro_uuid","model",@@ -1235,6 +1242,7 @@"filter_ast","frecency","item_filters",+ "macro_env_var","macro_user_id","macro_uuid","model",@@ -1503,6 +1511,7 @@"filter_ast","frecency","item_filters",+ "macro_env_var","macro_user_id","macro_uuid","model",@@ -1723,6 +1732,7 @@"filter_ast","frecency","item_filters",+ "macro_env_var","macro_user_id","macro_uuid","model",@@ -1841,6 +1851,7 @@"filter_ast","frecency","item_filters",+ "macro_env_var","macro_user_id","macro_uuid","model",@@ -1894,6 +1905,7 @@"foreign_entity","frecency","item_filters",+ "macro_env_var","macro_user_id","macro_uuid","model",@@ -2238,6 +2250,7 @@"frecency","item_filters","macro_db_client",+ "macro_env_var","macro_user_id","macro_uuid","model",@@ -2342,6 +2355,7 @@"filter_ast","frecency","item_filters",+ "macro_env_var","macro_sha_count_client","macro_user_id","macro_uuid",@@ -2614,6 +2628,7 @@"filter_ast","frecency","item_filters",+ "macro_env_var","macro_user_id","macro_uuid","model",@@ -3764,6 +3779,7 @@"filter_ast","frecency","item_filters",+ "macro_env_var","macro_user_id","macro_uuid","model",@@ -3869,6 +3885,7 @@"filter_ast","frecency","item_filters",+ "macro_env_var","macro_user_id","macro_uuid","model",diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 14c384240c..e982d19374 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -55,6 +55,7 @@ dependencies = ["async-trait","attachment","futures",+ "macro_env_var","macro_user_id","model-entity","non_empty",diff --git a/rust/cloud-storage/agent/Cargo.toml b/rust/cloud-storage/agent/Cargo.tomlindex 480ed0b069..02244fac94 100644--- a/rust/cloud-storage/agent/Cargo.toml+++ b/rust/cloud-storage/agent/Cargo.toml@@ -28,6 +28,7 @@ tracing = { workspace = true }ai_usage = { path = "../ai_usage" }ai_toolset = { path = "../ai_toolset" }attachment = { path = "../attachment" }+macro_env_var = { path = "../macro_env_var" }macro_user_id = { path = "../macro_user_id" }workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/rust/cloud-storage/agent/src/agent_loop.rs b/rust/cloud-storage/agent/src/agent_loop.rsindex 26f1f85c16..a6bb2218c9 100644--- a/rust/cloud-storage/agent/src/agent_loop.rs+++ b/rust/cloud-storage/agent/src/agent_loop.rs@@ -4,13 +4,13 @@ use crate::hook::{StreamBridge, ToolRouter};use crate::model::AgentModel;use crate::model::router::{AllModelsRouter, RoutedModel};use crate::model::types::Model;+use crate::provider_env;use crate::stream::{ChatCompletionStream, StreamPart};use crate::tool_adapter::DynToolSetAdapter;use ai_toolset::{RequestContext, ToolSet as AiToolSet};use ai_usage::{UsageContext, UsageRecorder};use futures::StreamExt;use rig_core::agent::{Agent, MultiTurnStreamItem};-use rig_core::client::ProviderClient;use rig_core::completion::{CompletionModel, GetTokenUsage};use rig_core::message::Message;use rig_core::providers::{anthropic, openai};@@ -39,7 +39,7 @@ pub struct AgentLoop {}impl AgentLoop {- /// Create an `AgentLoop` with provider clients from the environment and+ /// Create an `AgentLoop` with provider clients from `APP_SECRETS_JSON` or the environment and/// the default model (Opus 4.7).////// `recorder` is the [`UsageRecorder`] every session created from this loop@@ -47,9 +47,11 @@ impl AgentLoop {////// `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` are required.pub fn new(recorder: Arc<dyn UsageRecorder>) -> Self {- let anthropic =- Arc::new(anthropic::Client::from_env().expect("ANTHROPIC_API_KEY must be set"));- let openai = Arc::new(openai::Client::from_env().expect("OPENAI_API_KEY must be set"));+ let anthropic = Arc::new(+ provider_env::anthropic_client_from_env().expect("ANTHROPIC_API_KEY must be set"),+ );+ let openai =+ Arc::new(provider_env::openai_client_from_env().expect("OPENAI_API_KEY must be set"));Self {anthropic,openai,diff --git a/rust/cloud-storage/agent/src/completion.rs b/rust/cloud-storage/agent/src/completion.rsindex de46102ecb..d05567a14e 100644--- a/rust/cloud-storage/agent/src/completion.rs+++ b/rust/cloud-storage/agent/src/completion.rs@@ -1,20 +1,19 @@/// One-shot completion — send a prompt and get a string response.use crate::model::router::{AllModelsRouter, RoutedModel};use crate::model::types::Model;+use crate::provider_env;use ai_usage::{UsageContext, UsageRecorder};use rig_core::agent::PromptResponse;-use rig_core::client::ProviderClient;use rig_core::completion::{CompletionModel, Prompt};use rig_core::message::Message;-use rig_core::providers::{anthropic, openai};use std::sync::Arc;-/// Build a router over provider clients from the environment.+/// Build a router over provider clients from `APP_SECRETS_JSON` or the environment.////// `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` are required.fn env_router() -> anyhow::Result<AllModelsRouter> {- let anthropic = Arc::new(anthropic::Client::from_env()?);- let openai = Arc::new(openai::Client::from_env()?);+ let anthropic = Arc::new(provider_env::anthropic_client_from_env()?);+ let openai = Arc::new(provider_env::openai_client_from_env()?);Ok(AllModelsRouter::new(anthropic, openai))}diff --git a/rust/cloud-storage/agent/src/lib.rs b/rust/cloud-storage/agent/src/lib.rsindex 445cd96696..8e67b69e75 100644--- a/rust/cloud-storage/agent/src/lib.rs+++ b/rust/cloud-storage/agent/src/lib.rs@@ -9,6 +9,7 @@ mod convert;mod error;mod hook;mod model;+mod provider_env;mod stream;/// Structured output via prompted JSON generation.pub mod structured_output;diff --git a/rust/cloud-storage/agent/src/provider_env.rs b/rust/cloud-storage/agent/src/provider_env.rsnew file mode 100644index 0000000000..722cc8691d--- /dev/null+++ b/rust/cloud-storage/agent/src/provider_env.rs@@ -0,0 +1,39 @@+use rig_core::client::{ProviderClientError, ProviderClientResult};+use rig_core::providers::{anthropic, openai};++// TODO: remove this shim once our rig fork's client env helpers call macro_env_var directly.+/// Mirror rig-core's required env var helper, but with macro_env_var's APP_SECRETS_JSON support.+pub(crate) fn required_env_var(name: &'static str) -> ProviderClientResult<String> {+ macro_env_var::read_env_var(name)+ .map_err(|source| ProviderClientError::EnvironmentVariable { name, source })+}++/// Mirror rig-core's optional env var helper, but with macro_env_var's APP_SECRETS_JSON support.+pub(crate) fn optional_env_var(name: &'static str) -> ProviderClientResult<Option<String>> {+ macro_env_var::optional_read_env_var(name)+ .map_err(|source| ProviderClientError::EnvironmentVariable { name, source })+}++/// Create an Anthropic client from APP_SECRETS_JSON-aware environment values.+pub(crate) fn anthropic_client_from_env() -> ProviderClientResult<anthropic::Client> {+ let api_key = required_env_var("ANTHROPIC_API_KEY")?;++ anthropic::Client::builder()+ .api_key(api_key)+ .build()+ .map_err(Into::into)+}++/// Create an OpenAI client from APP_SECRETS_JSON-aware environment values.+pub(crate) fn openai_client_from_env() -> ProviderClientResult<openai::Client> {+ let base_url = optional_env_var("OPENAI_BASE_URL")?;+ let api_key = required_env_var("OPENAI_API_KEY")?;++ let mut builder = openai::Client::builder().api_key(api_key);++ if let Some(base_url) = base_url {+ builder = builder.base_url(base_url);+ }++ builder.build().map_err(Into::into)+}diff --git a/rust/cloud-storage/macro_env_var/src/lib.rs b/rust/cloud-storage/macro_env_var/src/lib.rsindex 752529329c..c1d7bf4fa6 100644--- a/rust/cloud-storage/macro_env_var/src/lib.rs+++ b/rust/cloud-storage/macro_env_var/src/lib.rs@@ -24,21 +24,42 @@ where}}-fn read_env_with<F>(s: &'static str, read_var: F) -> Result<String, VarNameErr>+fn read_env_var_with<F>(s: &'static str, read_var: F) -> Result<String, std::env::VarError>whereF: Fn(&'static str) -> Result<String, std::env::VarError>,{match read_from_app_secrets_json_with(s, &read_var) {Some(value) => Ok(value),- None => read_var(s).map_err(|err| VarNameErr { var_name: s, err }),+ None => read_var(s),+ }+}++fn optional_read_env_var_with<F>(+ s: &'static str,+ read_var: F,+) -> Result<Option<String>, std::env::VarError>+where+ F: Fn(&'static str) -> Result<String, std::env::VarError>,+{+ match read_env_var_with(s, read_var) {+ Ok(value) => Ok(Some(value)),+ Err(std::env::VarError::NotPresent) => Ok(None),+ Err(err) => Err(err),}}+fn read_env_with<F>(s: &'static str, read_var: F) -> Result<String, VarNameErr>+where+ F: Fn(&'static str) -> Result<String, std::env::VarError>,+{+ read_env_var_with(s, read_var).map_err(|err| VarNameErr { var_name: s, err })+}+fn maybe_read_env_with<F>(s: &'static str, read_var: F) -> Option<String>whereF: Fn(&'static str) -> Result<String, std::env::VarError>,{- read_from_app_secrets_json_with(s, &read_var).or_else(|| read_var(s).ok())+ optional_read_env_var_with(s, read_var).ok().flatten()}#[cfg(test)]@@ -46,7 +67,10 @@ mod tests;#[cfg(test)]mod testing_harness {- use super::{VarNameErr, maybe_read_env_with, read_env_with};+ use super::{+ VarNameErr, maybe_read_env_with, optional_read_env_var_with, read_env_var_with,+ read_env_with,+ };use std::cell::Cell;type MockValue = Cell<Option<Box<dyn Fn(&'static str) -> Result<String, std::env::VarError>>>>;@@ -82,6 +106,16 @@ mod testing_harness {maybe_read_env_with(s, get_env)}+ pub(crate) fn read_env_var(s: &'static str) -> Result<String, std::env::VarError> {+ read_env_var_with(s, get_env)+ }++ pub(crate) fn optional_read_env_var(+ s: &'static str,+ ) -> Result<Option<String>, std::env::VarError> {+ optional_read_env_var_with(s, get_env)+ }+pub(crate) fn with_mock_env<F, Cb, U>(f: F, cb: Cb) -> UwhereF: Fn(&'static str) -> Result<String, std::env::VarError> + 'static,@@ -96,13 +130,35 @@ mod testing_harness {#[cfg(test)]pub(crate) use testing_harness::maybe_read_env;#[cfg(test)]+pub(crate) use testing_harness::optional_read_env_var;+#[cfg(test)]pub(crate) use testing_harness::read_env;+#[cfg(test)]+pub(crate) use testing_harness::read_env_var;#[cfg(not(test))]pub fn read_env(s: &'static str) -> Result<String, VarNameErr> {read_env_with(s, read_std_env)}+/// Read an environment variable from `APP_SECRETS_JSON` or the process environment.+///+/// This uses the same lookup order as generated [`env_var!`] types, but returns the raw+/// [`std::env::VarError`] so callers can map errors into their own error types.+#[cfg(not(test))]+pub fn read_env_var(s: &'static str) -> Result<String, std::env::VarError> {+ read_env_var_with(s, read_std_env)+}++/// Read an optional environment variable from `APP_SECRETS_JSON` or the process environment.+///+/// Missing variables return `Ok(None)`. Values present in `APP_SECRETS_JSON` take precedence over+/// process environment variables. Non-Unicode process environment values are returned as errors.+#[cfg(not(test))]+pub fn optional_read_env_var(s: &'static str) -> Result<Option<String>, std::env::VarError> {+ optional_read_env_var_with(s, read_std_env)+}+/// Read an environment variable, returning `None` if it is not present.#[cfg(not(test))]pub fn maybe_read_env(s: &'static str) -> Option<String> {diff --git a/rust/cloud-storage/macro_env_var/src/tests.rs b/rust/cloud-storage/macro_env_var/src/tests.rsindex 780b3ebc89..43b347b40e 100644--- a/rust/cloud-storage/macro_env_var/src/tests.rs+++ b/rust/cloud-storage/macro_env_var/src/tests.rs@@ -69,6 +69,28 @@ fn required_env_reads_from_app_secrets_json_when_key_exists() {assert_eq!(value, "from-json");}+#[test]+fn read_env_var_exposes_std_var_error_for_missing_values() {+ let result = with_mock_env(mock_no_env, || read_env_var("FOO"));++ assert!(matches!(result, Err(std::env::VarError::NotPresent)));+}++#[test]+fn read_env_var_reads_from_app_secrets_json_when_key_exists() {+ let value = with_mock_env(+ |k| match k {+ "APP_SECRETS_JSON" => Ok(r#"{"FOO":"from-json"}"#.to_string()),+ "FOO" => Ok("from-env".to_string()),+ _ => Err(std::env::VarError::NotPresent),+ },+ || read_env_var("FOO"),+ )+ .unwrap();++ assert_eq!(value, "from-json");+}+#[test]fn required_env_falls_back_to_env_when_json_is_missing() {let value = with_mock_env(@@ -292,6 +314,28 @@ fn optional_env_returns_some_from_app_secrets_json_when_key_exists() {assert_eq!(value.as_deref(), Some("from-json"));}+#[test]+fn optional_read_env_var_returns_some_from_app_secrets_json_when_key_exists() {+ let value = with_mock_env(+ |k| match k {+ "APP_SECRETS_JSON" => Ok(r#"{"FOO":"from-json"}"#.to_string()),+ "FOO" => Ok("from-env".to_string()),+ _ => Err(std::env::VarError::NotPresent),+ },+ || optional_read_env_var("FOO"),+ )+ .unwrap();++ assert_eq!(value.as_deref(), Some("from-json"));+}++#[test]+fn optional_read_env_var_returns_none_when_neither_source_contains_key() {+ let value = with_mock_env(mock_no_env, || optional_read_env_var("FOO")).unwrap();++ assert_eq!(value, None);+}+#[test]fn optional_env_falls_back_to_env_when_json_is_missing() {let value = with_mock_env(