Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions interface/src/routes/Overview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,22 @@ export function Overview({liveStates, activeLinks}: OverviewProps) {

return (
<div className="flex flex-col h-full">
{providersData && !providersData.has_any && agents.length > 0 && (
<div className="mx-6 mt-4 flex items-center justify-between gap-3 rounded-lg border border-amber-500/25 bg-amber-500/10 px-4 py-3">
<p className="text-sm text-amber-200">
Agents are configured, but no provider credentials are available. Add or unlock
secrets to bring agents online.
</p>
<Link
to="/settings"
search={{tab: "secrets"}}
className="shrink-0 text-sm font-medium text-amber-100 underline-offset-4 hover:underline"
>
Open Secrets Settings
</Link>
</div>
)}

{/* Full-screen topology */}
<div className="flex-1 overflow-hidden">
{overviewLoading ? (
Expand Down
10 changes: 10 additions & 0 deletions src/api/agents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1472,6 +1472,16 @@ pub(super) async fn instance_overview(
let agent_id = agent_config.id.clone();

let Some(pool) = pools.get(&agent_id) else {
agents.push(AgentSummary {
id: agent_id,
channel_count: 0,
memory_total: 0,
cron_job_count: 0,
activity_sparkline: vec![0; 14],
last_activity_at: None,
last_bulletin_at: None,
profile: None,
});
continue;
};

Expand Down
80 changes: 54 additions & 26 deletions src/api/providers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,13 @@ pub(super) async fn get_providers(
) -> Result<Json<ProvidersResponse>, StatusCode> {
let config_path = state.config_path.read().await.clone();
let instance_dir = (**state.instance_dir.load()).clone();
let secrets_store = state.secrets_store.load();
let openai_oauth_configured = crate::openai_auth::credentials_path(&instance_dir).exists();
let env_set = |name: &str| {
std::env::var(name)
.ok()
.is_some_and(|value| !value.trim().is_empty())
};
Comment on lines +353 to +357

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify env var reads that silently discard Result errors in Rust files
rg -nP 'std::env::var\([^)]*\)\s*\.ok\(\)' --type rust

Repository: spacedriveapp/spacebot

Length of output: 5004


🏁 Script executed:

cat -n src/api/providers.rs | sed -n '350,410p'

Repository: spacedriveapp/spacebot

Length of output: 2396


Environment variables should handle missing/invalid values explicitly instead of silently discarding errors with .ok().

Lines 353-357 and 403-405 use .ok() on std::env::var(), which suppresses error context (e.g., invalid UTF-8). Per coding guidelines, errors must be handled, logged, or propagated—.ok() is only permitted on channel sends where the receiver may be dropped.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/api/providers.rs` around lines 353 - 357, The env_set closure currently
swallows errors from std::env::var(...) via .ok(), so replace the
.ok().is_some_and(...) pattern with explicit Result handling: call
std::env::var(name) and match/if let on the Result, returning true only for
Ok(value) when !value.trim().is_empty(), and on Err(e) log or propagate the
error (e.g., log::warn! or return Err) and return false; apply the same change
to the other std::env::var(...) usage around lines 403-405 so errors (like
invalid UTF-8) are not silently discarded but are logged or propagated
consistently.


let (
anthropic,
Expand Down Expand Up @@ -381,17 +387,39 @@ pub(super) async fn get_providers(
.parse()
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

let resolve_value = |value: &str| -> Option<String> {
if let Some(alias) = value.strip_prefix("secret:") {
let store = secrets_store.as_ref().as_ref()?;
return match store.get(alias) {
Ok(secret) => Some(secret.expose().to_string()),
Err(error) => {
tracing::warn!(%error, alias, "failed to resolve secret reference");
None
}
};
}

if let Some(var_name) = value.strip_prefix("env:") {
return std::env::var(var_name)
.ok()
.filter(|resolved| !resolved.trim().is_empty());
}

if value.trim().is_empty() {
None
} else {
Some(value.to_string())
}
};

let has_value = |key: &str, env_var: &str| -> bool {
if let Some(llm) = doc.get("llm")
&& let Some(val) = llm.get(key)
&& let Some(s) = val.as_str()
{
if let Some(var_name) = s.strip_prefix("env:") {
return std::env::var(var_name).is_ok();
}
return !s.is_empty();
return resolve_value(s).is_some();
}
Comment on lines +390 to 421

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resolve_value currently allocates (and materializes secrets) just to answer a boolean. Might be safer/cheaper to keep this as a bool and avoid to_string().

Suggested change
let resolve_value = |value: &str| -> Option<String> {
if let Some(alias) = value.strip_prefix("secret:") {
let store = secrets_store.as_ref().as_ref()?;
return store
.get(alias)
.ok()
.map(|secret| secret.expose().to_string());
}
if let Some(var_name) = value.strip_prefix("env:") {
return std::env::var(var_name)
.ok()
.filter(|resolved| !resolved.trim().is_empty());
}
if value.trim().is_empty() {
None
} else {
Some(value.to_string())
}
};
let has_value = |key: &str, env_var: &str| -> bool {
if let Some(llm) = doc.get("llm")
&& let Some(val) = llm.get(key)
&& let Some(s) = val.as_str()
{
if let Some(var_name) = s.strip_prefix("env:") {
return std::env::var(var_name).is_ok();
}
return !s.is_empty();
return resolve_value(s).is_some();
}
let resolve_has_value = |value: &str| -> bool {
if let Some(alias) = value.strip_prefix("secret:") {
let Some(store) = secrets_store.as_ref().as_ref() else {
return false;
};
return store
.get(alias)
.ok()
.is_some_and(|secret| !secret.expose().trim().is_empty());
}
if let Some(var_name) = value.strip_prefix("env:") {
return std::env::var(var_name)
.ok()
.is_some_and(|resolved| !resolved.trim().is_empty());
}
!value.trim().is_empty()
};
let has_value = |key: &str, env_var: &str| -> bool {
if let Some(llm) = doc.get("llm")
&& let Some(val) = llm.get(key)
&& let Some(s) = val.as_str()
{
return resolve_has_value(s);
}

std::env::var(env_var).is_ok()
env_set(env_var)
};

(
Expand Down Expand Up @@ -421,28 +449,28 @@ pub(super) async fn get_providers(
)
} else {
(
std::env::var("ANTHROPIC_API_KEY").is_ok(),
std::env::var("OPENAI_API_KEY").is_ok(),
env_set("ANTHROPIC_API_KEY"),
env_set("OPENAI_API_KEY"),
openai_oauth_configured,
std::env::var("OPENROUTER_API_KEY").is_ok(),
std::env::var("KILO_API_KEY").is_ok(),
std::env::var("ZHIPU_API_KEY").is_ok(),
std::env::var("GROQ_API_KEY").is_ok(),
std::env::var("TOGETHER_API_KEY").is_ok(),
std::env::var("FIREWORKS_API_KEY").is_ok(),
std::env::var("DEEPSEEK_API_KEY").is_ok(),
std::env::var("XAI_API_KEY").is_ok(),
std::env::var("MISTRAL_API_KEY").is_ok(),
std::env::var("GEMINI_API_KEY").is_ok(),
std::env::var("OLLAMA_BASE_URL").is_ok() || std::env::var("OLLAMA_API_KEY").is_ok(),
std::env::var("OPENCODE_ZEN_API_KEY").is_ok(),
std::env::var("OPENCODE_GO_API_KEY").is_ok(),
std::env::var("NVIDIA_API_KEY").is_ok(),
std::env::var("MINIMAX_API_KEY").is_ok(),
std::env::var("MINIMAX_CN_API_KEY").is_ok(),
std::env::var("MOONSHOT_API_KEY").is_ok(),
std::env::var("ZAI_CODING_PLAN_API_KEY").is_ok(),
std::env::var("GITHUB_COPILOT_API_KEY").is_ok(),
env_set("OPENROUTER_API_KEY"),
env_set("KILO_API_KEY"),
env_set("ZHIPU_API_KEY"),
env_set("GROQ_API_KEY"),
env_set("TOGETHER_API_KEY"),
env_set("FIREWORKS_API_KEY"),
env_set("DEEPSEEK_API_KEY"),
env_set("XAI_API_KEY"),
env_set("MISTRAL_API_KEY"),
env_set("GEMINI_API_KEY"),
env_set("OLLAMA_BASE_URL") || env_set("OLLAMA_API_KEY"),
env_set("OPENCODE_ZEN_API_KEY"),
env_set("OPENCODE_GO_API_KEY"),
env_set("NVIDIA_API_KEY"),
env_set("MINIMAX_API_KEY"),
env_set("MINIMAX_CN_API_KEY"),
env_set("MOONSHOT_API_KEY"),
env_set("ZAI_CODING_PLAN_API_KEY"),
env_set("GITHUB_COPILOT_API_KEY"),
)
};

Expand Down
6 changes: 4 additions & 2 deletions src/api/secrets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,10 @@ pub async fn secrets_status(State(state): State<Arc<ApiState>>) -> impl IntoResp
Err(e) => return e.into_response(),
};

// TODO: detect platform_managed from deployment mode.
match store.status(false) {
let platform_managed = std::env::var("SPACEBOT_DEPLOYMENT")
.is_ok_and(|deployment| deployment.eq_ignore_ascii_case("hosted"));
Comment on lines +47 to +48

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: probably worth trimming here to avoid treating SPACEBOT_DEPLOYMENT="hosted\n" (or similar) as false.

Suggested change
let platform_managed = std::env::var("SPACEBOT_DEPLOYMENT")
.is_ok_and(|deployment| deployment.eq_ignore_ascii_case("hosted"));
let platform_managed = std::env::var("SPACEBOT_DEPLOYMENT")
.is_ok_and(|deployment| deployment.trim().eq_ignore_ascii_case("hosted"));


match store.status(platform_managed) {
Ok(status) => Json(status).into_response(),
Err(error) => (
StatusCode::INTERNAL_SERVER_ERROR,
Expand Down
131 changes: 109 additions & 22 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1344,31 +1344,91 @@ fn bootstrap_secrets_store(
// Try to auto-unlock if encrypted.
if store.is_encrypted() {
let keystore = spacebot::secrets::keystore::platform_keystore();
let tmpfs_paths = [
std::path::Path::new("/run/spacebot/master_key"),
std::path::Path::new("/run/secrets/master_key"),
];

// Hosted: check tmpfs-injected key.
let tmpfs_key_path = std::path::Path::new("/run/spacebot/master_key");
let master_key = if tmpfs_key_path.exists() {
std::fs::read(tmpfs_key_path).ok().inspect(|key| {
if let Err(error) = std::fs::remove_file(tmpfs_key_path) {
tracing::warn!(%error, "failed to remove tmpfs master key — key may remain accessible");
let tmpfs_master_key = tmpfs_paths.iter().find_map(|path| {
if !path.exists() {
return None;
}

let raw_key = match std::fs::read(path) {
Ok(key) => key,
Err(error) => {
tracing::warn!(%error, path = %path.display(), "failed to read tmpfs master key");
return None;
}
Comment on lines +1360 to 1363

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If reading the tmpfs key fails (for both paths), the injected key file(s) will be left on disk. Consider a best-effort remove on the error path too.

Suggested change
Err(error) => {
tracing::warn!(%error, path = %path.display(), "failed to read tmpfs master key");
return None;
}
Err(error) => {
tracing::warn!(%error, path = %path.display(), "failed to read tmpfs master key");
if let Err(remove_error) = std::fs::remove_file(path) {
tracing::warn!(
%remove_error,
path = %path.display(),
"failed to remove tmpfs master key — key may remain accessible"
);
}
return None;
}

if let Err(error) = keystore.store_key(KEYSTORE_INSTANCE_ID, key) {
tracing::warn!(%error, "failed to persist master key to OS credential store");
};

// Platform currently stores keys as 64-char hex strings. Decode
// those to raw bytes before unlock; otherwise treat as raw bytes.
if let Ok(text) = std::str::from_utf8(&raw_key) {
let trimmed = text.trim();
if trimmed.len() == 64 && trimmed.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return match hex::decode(trimmed) {
Ok(decoded) => Some(decoded),
Err(error) => {
tracing::warn!(
%error,
path = %path.display(),
"failed to decode hex tmpfs master key, falling back to raw bytes"
);
Some(raw_key)
}
};
}
})
} else {
}

Some(raw_key)
});

let mut unlocked = false;

if let Some(key) = tmpfs_master_key {
match store.unlock(&key) {
Ok(()) => {
unlocked = true;
if let Err(error) = keystore.store_key(KEYSTORE_INSTANCE_ID, &key) {
tracing::warn!(%error, "failed to persist master key to OS credential store");
}
// Clean up tmpfs key files only after a successful unlock.
for cleanup_path in tmpfs_paths {
if cleanup_path.exists()
&& let Err(error) = std::fs::remove_file(cleanup_path)
{
tracing::warn!(
%error,
path = %cleanup_path.display(),
"failed to remove tmpfs master key — key may remain accessible"
);
}
}
}
Err(error) => {
tracing::warn!(%error, "failed to unlock secret store with tmpfs key");
}
}
}
Comment on lines +1353 to +1414

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Try all tmpfs keys before deleting them.

The cleanup happens before the first store.unlock attempt. If /run/spacebot/master_key is stale/corrupt but /run/secrets/master_key is valid, the valid file is deleted and never tried, so hosted auto-unlock becomes path-order dependent. Move cleanup until after you've attempted all present tmpfs keys, or only delete the file that actually unlocked the store.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main.rs` around lines 1353 - 1415, The current logic reads the first
existing tmpfs file and immediately removes all tmpfs_paths before attempting to
unlock, which can delete a valid key if an earlier file is stale; change the
flow in tmpfs_master_key handling so you attempt to unlock with each candidate
key before deleting files (or alternatively only delete the specific
cleanup_path that successfully unlocked). Concretely, iterate tmpfs_paths
collecting decoded/raw keys (or keep the existing find_map but delay the for
cleanup_path in tmpfs_paths { remove_file } loop), call store.unlock(&key) for
each candidate and on successful unlock set unlocked = true and then call
keystore.store_key(KEYSTORE_INSTANCE_ID, &key) and perform cleanup (either
remove only the used file or remove all tmpfs_paths after a successful unlock);
ensure tracing::warn remains on removal failures and that removal is not done
prior to trying unlock.


if !unlocked {
// Try instance-level key first, then fall back to legacy agent keys.
keystore
let master_key = keystore
.load_key(KEYSTORE_INSTANCE_ID)
.ok()
.flatten()
.or_else(|| load_legacy_keystore_key(&instance_dir))
};
.or_else(|| load_legacy_keystore_key(&instance_dir));

if let Some(key) = master_key
&& let Err(error) = store.unlock(&key)
{
tracing::warn!(%error, "failed to unlock secret store — secrets will be inaccessible");
if let Some(key) = master_key
&& let Err(error) = store.unlock(&key)
{
tracing::warn!(
%error,
"failed to unlock secret store — secrets will be inaccessible"
);
}
}
}

Expand Down Expand Up @@ -1475,6 +1535,25 @@ fn has_provider_credentials(
|| spacebot::openai_auth::credentials_path(instance_dir).exists()
}

fn configured_agent_infos(config: &spacebot::config::Config) -> Vec<spacebot::api::AgentInfo> {
config
.resolve_agents()
.into_iter()
.map(|agent| spacebot::api::AgentInfo {
id: agent.id,
display_name: agent.display_name,
role: agent.role,
gradient_start: agent.gradient_start,
gradient_end: agent.gradient_end,
workspace: agent.workspace,
context_window: agent.context_window,
max_turns: agent.max_turns,
max_concurrent_branches: agent.max_concurrent_branches,
max_concurrent_workers: agent.max_concurrent_workers,
})
.collect()
}

async fn run(
config: spacebot::config::Config,
foreground: bool,
Expand Down Expand Up @@ -1519,6 +1598,12 @@ async fn run(
api_state.auth_token = config.api.auth_token.clone();
let api_state = Arc::new(api_state);

// Keep the secrets API available in setup mode so encrypted stores can be
// unlocked before providers/agents are initialized.
if let Some(store) = &bootstrapped_store {
api_state.set_secrets_store(store.clone());
}

// Start background update checker
spacebot::update::spawn_update_checker(api_state.update_status.clone());

Expand Down Expand Up @@ -1637,6 +1722,7 @@ async fn run(
api_state.set_agent_links((**agent_links.load()).clone());
api_state.set_agent_groups(config.groups.clone());
api_state.set_agent_humans(config.humans.clone());
api_state.set_agent_configs(configured_agent_infos(&config));

// Track whether agents have been initialized
let mut agents_initialized = false;
Expand Down Expand Up @@ -2217,9 +2303,10 @@ async fn run(
};

match new_config {
Ok(new_config)
if has_provider_credentials(&new_config.llm, &new_config.instance_dir) =>
{
Ok(new_config) => {
api_state.set_agent_configs(configured_agent_infos(&new_config));

if has_provider_credentials(&new_config.llm, &new_config.instance_dir) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like the body of this if block lost indentation in the diff (comments + match are flush-left). Probably just needs a cargo fmt pass to keep this section easy to read.

// Refresh in-memory defaults so newly created agents
// inherit the latest routing from the updated config.
api_state.set_defaults_config(new_config.defaults.clone()).await;
Expand Down Expand Up @@ -2296,9 +2383,9 @@ async fn run(
tracing::error!(%error, "failed to create LLM manager with new keys");
}
}
}
Ok(_) => {
tracing::warn!("config reloaded but still no providers configured");
} else {
tracing::warn!("config reloaded but still no providers configured");
}
}
Err(error) => {
tracing::error!(%error, "failed to reload config after provider setup");
Expand Down
Loading