mirror of
https://github.com/block/buzz.git
synced 2026-11-26 11:12:22 +00:00
feat(desktop): dynamic nest AGENTS.md regeneration
AGENTS.md in ~/.sprout is now dynamically regenerated whenever personas, agents, or workspace config changes. Agents discover their teammates on every fresh session via a managed section demarcated by HTML comment markers. User edits outside the markers are preserved across regenerations.
This commit is contained in:
@@ -8,8 +8,9 @@ use crate::{
|
||||
managed_agents::{
|
||||
build_managed_agent_summary, default_agent_workdir, find_managed_agent_mut,
|
||||
load_managed_agents, managed_agent_avatar_url, missing_command_message,
|
||||
normalize_agent_args, resolve_command, save_managed_agents, sync_managed_agent_processes,
|
||||
AgentModelInfo, AgentModelsResponse, UpdateManagedAgentRequest, UpdateManagedAgentResponse,
|
||||
normalize_agent_args, regenerate_nest_context, resolve_command, save_managed_agents,
|
||||
sync_managed_agent_processes, AgentModelInfo, AgentModelsResponse,
|
||||
UpdateManagedAgentRequest, UpdateManagedAgentResponse,
|
||||
},
|
||||
relay::{relay_ws_url_with_override, sync_managed_agent_profile},
|
||||
util::now_iso,
|
||||
@@ -246,6 +247,10 @@ pub async fn update_managed_agent(
|
||||
(summary, sync_params)
|
||||
}; // lock dropped here
|
||||
|
||||
if let Err(error) = regenerate_nest_context(&app) {
|
||||
eprintln!("sprout-desktop: nest context regeneration failed: {error}");
|
||||
}
|
||||
|
||||
// Phase 2: relay profile sync (async, best-effort, outside lock)
|
||||
let profile_sync_error =
|
||||
if let Some((agent_keys, relay_url, display_name, avatar_url, auth_tag)) = sync_params {
|
||||
|
||||
@@ -8,12 +8,13 @@ use crate::{
|
||||
build_managed_agent_summary, discover_provider_candidates, ensure_persona_is_active,
|
||||
find_managed_agent_mut, invoke_provider, load_managed_agents, load_personas,
|
||||
managed_agent_avatar_url, managed_agent_log_path, managed_agents_base_dir,
|
||||
normalize_agent_args, provider_deploy, read_log_tail, resolve_provider_binary,
|
||||
save_managed_agents, start_managed_agent_process, stop_managed_agent_process,
|
||||
sync_managed_agent_processes, validate_provider_config, BackendKind, BackendProviderInfo,
|
||||
CreateManagedAgentRequest, CreateManagedAgentResponse, ManagedAgentLogResponse,
|
||||
ManagedAgentRecord, ManagedAgentSummary, DEFAULT_ACP_COMMAND, DEFAULT_AGENT_COMMAND,
|
||||
DEFAULT_AGENT_PARALLELISM, DEFAULT_AGENT_TURN_TIMEOUT_SECONDS, DEFAULT_MCP_COMMAND,
|
||||
normalize_agent_args, provider_deploy, read_log_tail, regenerate_nest_context,
|
||||
resolve_provider_binary, save_managed_agents, start_managed_agent_process,
|
||||
stop_managed_agent_process, sync_managed_agent_processes, validate_provider_config,
|
||||
BackendKind, BackendProviderInfo, CreateManagedAgentRequest, CreateManagedAgentResponse,
|
||||
ManagedAgentLogResponse, ManagedAgentRecord, ManagedAgentSummary, DEFAULT_ACP_COMMAND,
|
||||
DEFAULT_AGENT_COMMAND, DEFAULT_AGENT_PARALLELISM, DEFAULT_AGENT_TURN_TIMEOUT_SECONDS,
|
||||
DEFAULT_MCP_COMMAND,
|
||||
},
|
||||
relay::{relay_ws_url_with_override, sync_managed_agent_profile},
|
||||
util::now_iso,
|
||||
@@ -453,6 +454,10 @@ pub async fn create_managed_agent(
|
||||
(agent, spawn_error)
|
||||
};
|
||||
|
||||
if let Err(error) = regenerate_nest_context(&app) {
|
||||
eprintln!("sprout-desktop: nest context regeneration failed: {error}");
|
||||
}
|
||||
|
||||
// ── Phase 4: sync agent profile on relay (async, outside lock) ───────────
|
||||
let avatar_url = input
|
||||
.avatar_url
|
||||
@@ -714,7 +719,11 @@ pub fn delete_managed_agent(
|
||||
if records.len() == initial_len {
|
||||
return Err(format!("agent {pubkey} not found"));
|
||||
}
|
||||
save_managed_agents(&app, &records)
|
||||
save_managed_agents(&app, &records)?;
|
||||
if let Err(error) = regenerate_nest_context(&app) {
|
||||
eprintln!("sprout-desktop: nest context regeneration failed: {error}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
||||
@@ -7,7 +7,7 @@ use crate::{
|
||||
managed_agents::{
|
||||
encode_persona_json, import_persona_pack, list_installed_packs, load_managed_agents,
|
||||
load_personas, load_teams, parse_json_persona, parse_md_persona, parse_png_persona,
|
||||
parse_zip_personas, save_managed_agents, save_personas,
|
||||
parse_zip_personas, regenerate_nest_context, save_managed_agents, save_personas,
|
||||
uninstall_persona_pack as do_uninstall_persona_pack, validate_persona_activation_change,
|
||||
validate_persona_deletion, CreatePersonaRequest, PackSummary, ParsePersonaFilesResult,
|
||||
PersonaRecord, UpdatePersonaRequest,
|
||||
@@ -85,6 +85,9 @@ pub fn create_persona(
|
||||
};
|
||||
personas.push(persona.clone());
|
||||
save_personas(&app, &personas)?;
|
||||
if let Err(error) = regenerate_nest_context(&app) {
|
||||
eprintln!("sprout-desktop: nest context regeneration failed: {error}");
|
||||
}
|
||||
Ok(persona)
|
||||
}
|
||||
|
||||
@@ -134,6 +137,9 @@ pub fn update_persona(
|
||||
persona.updated_at = now_iso();
|
||||
|
||||
save_personas(&app, &personas)?;
|
||||
if let Err(error) = regenerate_nest_context(&app) {
|
||||
eprintln!("sprout-desktop: nest context regeneration failed: {error}");
|
||||
}
|
||||
personas
|
||||
.into_iter()
|
||||
.find(|record| record.id == input.id)
|
||||
@@ -182,6 +188,9 @@ pub fn delete_persona(
|
||||
if changed_agents {
|
||||
save_managed_agents(&app, &agents)?;
|
||||
}
|
||||
if let Err(error) = regenerate_nest_context(&app) {
|
||||
eprintln!("sprout-desktop: nest context regeneration failed: {error}");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -230,6 +239,9 @@ pub fn set_persona_active(
|
||||
|
||||
let updated = persona.clone();
|
||||
save_personas(&app, &personas)?;
|
||||
if let Err(error) = regenerate_nest_context(&app) {
|
||||
eprintln!("sprout-desktop: nest context regeneration failed: {error}");
|
||||
}
|
||||
Ok(updated)
|
||||
}
|
||||
|
||||
@@ -383,7 +395,11 @@ pub fn install_persona_pack(
|
||||
if !source.is_dir() {
|
||||
return Err(format!("pack path is not a directory: {path}"));
|
||||
}
|
||||
import_persona_pack(&app, &source)
|
||||
let result = import_persona_pack(&app, &source)?;
|
||||
if let Err(error) = regenerate_nest_context(&app) {
|
||||
eprintln!("sprout-desktop: nest context regeneration failed: {error}");
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -396,7 +412,11 @@ pub fn uninstall_persona_pack(
|
||||
.managed_agents_store_lock
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?;
|
||||
do_uninstall_persona_pack(&app, &pack_id)
|
||||
do_uninstall_persona_pack(&app, &pack_id)?;
|
||||
if let Err(error) = regenerate_nest_context(&app) {
|
||||
eprintln!("sprout-desktop: nest context regeneration failed: {error}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use nostr::Keys;
|
||||
use serde::Serialize;
|
||||
use tauri::State;
|
||||
use tauri::{AppHandle, State};
|
||||
|
||||
use crate::app_state::AppState;
|
||||
use crate::managed_agents::regenerate_nest_context;
|
||||
use crate::relay;
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -30,6 +31,7 @@ pub fn get_active_workspace(state: State<'_, AppState>) -> Result<ActiveWorkspac
|
||||
pub fn apply_workspace(
|
||||
relay_url: String,
|
||||
nsec: Option<String>,
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
// ── Validate before mutating ──────────────────────────────────────────
|
||||
@@ -51,5 +53,11 @@ pub fn apply_workspace(
|
||||
*keys_guard = keys;
|
||||
}
|
||||
|
||||
if let Err(error) = regenerate_nest_context(&app) {
|
||||
eprintln!(
|
||||
"sprout-desktop: failed to regenerate nest context after workspace switch: {error}"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ use huddle::{
|
||||
speak_agent_message, start_huddle, start_stt_pipeline,
|
||||
};
|
||||
use managed_agents::{
|
||||
ensure_nest, kill_stale_tracked_processes, load_managed_agents,
|
||||
ensure_nest, kill_stale_tracked_processes, load_managed_agents, regenerate_nest_context,
|
||||
restore_managed_agents_on_launch, save_managed_agents, sync_managed_agent_processes,
|
||||
BackendKind, ManagedAgentProcess,
|
||||
};
|
||||
@@ -393,6 +393,10 @@ pub fn run() {
|
||||
eprintln!("sprout-desktop: failed to create nest: {error}");
|
||||
}
|
||||
|
||||
if let Err(error) = regenerate_nest_context(&app_handle) {
|
||||
eprintln!("sprout-desktop: failed to regenerate nest context: {error}");
|
||||
}
|
||||
|
||||
// Pre-download voice models in the background so they're ready
|
||||
// when the user starts their first huddle. Idempotent — no-op if
|
||||
// already downloaded. ~87 MB total (50 MB Moonshine + 87 MB Kokoro).
|
||||
|
||||
@@ -6,8 +6,15 @@
|
||||
//!
|
||||
//! Idempotent: existing files and directories are never overwritten.
|
||||
|
||||
use super::{
|
||||
load_managed_agents, load_personas, BackendKind, ManagedAgentRecord, PersonaRecord, RespondTo,
|
||||
};
|
||||
use crate::app_state::AppState;
|
||||
use crate::relay::relay_ws_url_with_override;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tauri::{AppHandle, Manager};
|
||||
|
||||
/// Subdirectories created inside the nest.
|
||||
const NEST_DIRS: &[&str] = &[
|
||||
@@ -122,6 +129,106 @@ pub fn ensure_nest_at(root: &Path) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const CLI_QUICK_REFERENCE: &str = "\
|
||||
## CLI Quick Reference
|
||||
`sprout messages send --channel <id> --content <text>` — send a message
|
||||
`sprout messages get --channel <id>` — read recent messages
|
||||
`sprout channels list` — list available channels
|
||||
`sprout workflows trigger --workflow <id>` — trigger a workflow
|
||||
Run `sprout --help` for the full command reference.";
|
||||
|
||||
pub fn render_dynamic_section(
|
||||
personas: &[PersonaRecord],
|
||||
agents: &[ManagedAgentRecord],
|
||||
relay_url: &str,
|
||||
) -> String {
|
||||
let active_agents = if agents.is_empty() {
|
||||
"## Active Agents\n\n*(No agents deployed yet. Add agents in the Sprout desktop app.)*"
|
||||
.to_string()
|
||||
} else {
|
||||
let mut table =
|
||||
"## Active Agents\n\n| Name | Role | How to address |\n|------|------|----------------|"
|
||||
.to_string();
|
||||
for agent in agents {
|
||||
let role = agent
|
||||
.persona_id
|
||||
.as_deref()
|
||||
.and_then(|pid| personas.iter().find(|p| p.id == pid))
|
||||
.map(|p| p.display_name.as_str())
|
||||
.unwrap_or("—");
|
||||
table.push_str(&format!(
|
||||
"\n| {} | {} | @{} |",
|
||||
agent.name, role, agent.name
|
||||
));
|
||||
}
|
||||
table
|
||||
};
|
||||
|
||||
format!("{active_agents}\n\n## Workspace\n- Relay: {relay_url}\n\n{CLI_QUICK_REFERENCE}")
|
||||
}
|
||||
|
||||
pub fn upsert_managed_section(file_path: &Path, new_section_content: &str) -> io::Result<()> {
|
||||
let current = fs::read_to_string(file_path)?;
|
||||
|
||||
const BEGIN: &str = "<!-- BEGIN SPROUT MANAGED";
|
||||
const END: &str = "<!-- END SPROUT MANAGED -->";
|
||||
|
||||
let replacement = format!(
|
||||
"<!-- BEGIN SPROUT MANAGED — regenerated automatically, do not edit below -->\n{new_section_content}\n<!-- END SPROUT MANAGED -->\n"
|
||||
);
|
||||
|
||||
let new_content =
|
||||
if let (Some(begin_pos), Some(end_pos)) = (current.find(BEGIN), current.find(END)) {
|
||||
// Find the start of the BEGIN marker's line.
|
||||
let line_start = current[..begin_pos].rfind('\n').map(|p| p + 1).unwrap_or(0);
|
||||
// END marker spans to the end of its content + the newline after it.
|
||||
let end_of_end = end_pos + END.len();
|
||||
let after_end = if current[end_of_end..].starts_with('\n') {
|
||||
end_of_end + 1
|
||||
} else {
|
||||
end_of_end
|
||||
};
|
||||
format!(
|
||||
"{}{}{}",
|
||||
¤t[..line_start],
|
||||
replacement,
|
||||
¤t[after_end..]
|
||||
)
|
||||
} else {
|
||||
format!("{}\n\n{}", current.trim_end_matches('\n'), replacement)
|
||||
};
|
||||
|
||||
let tmp_path = file_path.with_extension(
|
||||
file_path
|
||||
.extension()
|
||||
.map(|e| format!("{}.tmp", e.to_string_lossy()))
|
||||
.unwrap_or_else(|| "tmp".to_string()),
|
||||
);
|
||||
fs::write(&tmp_path, new_content)?;
|
||||
fs::rename(&tmp_path, file_path)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn regenerate_nest_context(app: &AppHandle) -> Result<(), String> {
|
||||
let nest = nest_dir().ok_or("cannot resolve home directory for nest")?;
|
||||
let agents_md = nest.join("AGENTS.md");
|
||||
|
||||
if !agents_md.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let personas = load_personas(app)?;
|
||||
let agents = load_managed_agents(app)?;
|
||||
let state = app.state::<AppState>();
|
||||
let relay_url = relay_ws_url_with_override(&state);
|
||||
let content = render_dynamic_section(&personas, &agents, &relay_url);
|
||||
upsert_managed_section(&agents_md, &content)
|
||||
.map_err(|e| format!("regenerate nest context: {e}"))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -230,4 +337,141 @@ mod tests {
|
||||
"symlinked child's target should not be chmod'd"
|
||||
);
|
||||
}
|
||||
|
||||
fn make_persona(id: &str, display_name: &str) -> PersonaRecord {
|
||||
PersonaRecord {
|
||||
id: id.to_string(),
|
||||
display_name: display_name.to_string(),
|
||||
avatar_url: None,
|
||||
system_prompt: String::new(),
|
||||
provider: None,
|
||||
model: None,
|
||||
name_pool: vec![],
|
||||
is_builtin: false,
|
||||
is_active: true,
|
||||
source_pack: None,
|
||||
source_pack_persona_slug: None,
|
||||
created_at: String::new(),
|
||||
updated_at: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn make_agent(name: &str, persona_id: Option<&str>) -> ManagedAgentRecord {
|
||||
ManagedAgentRecord {
|
||||
pubkey: String::new(),
|
||||
name: name.to_string(),
|
||||
persona_id: persona_id.map(|s| s.to_string()),
|
||||
private_key_nsec: String::new(),
|
||||
auth_tag: None,
|
||||
relay_url: String::new(),
|
||||
acp_command: String::new(),
|
||||
agent_command: String::new(),
|
||||
agent_args: vec![],
|
||||
mcp_command: String::new(),
|
||||
turn_timeout_seconds: 0,
|
||||
idle_timeout_seconds: None,
|
||||
max_turn_duration_seconds: None,
|
||||
parallelism: 1,
|
||||
system_prompt: None,
|
||||
model: None,
|
||||
mcp_toolsets: None,
|
||||
start_on_app_launch: false,
|
||||
runtime_pid: None,
|
||||
backend: BackendKind::default(),
|
||||
backend_agent_id: None,
|
||||
provider_binary_path: None,
|
||||
persona_pack_path: None,
|
||||
persona_name_in_pack: None,
|
||||
created_at: String::new(),
|
||||
updated_at: String::new(),
|
||||
last_started_at: None,
|
||||
last_stopped_at: None,
|
||||
last_exit_code: None,
|
||||
last_error: None,
|
||||
respond_to: RespondTo::default(),
|
||||
respond_to_allowlist: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_render_dynamic_section_with_agents() {
|
||||
let personas = vec![make_persona("p1", "Builder")];
|
||||
let agents = vec![make_agent("Kit", Some("p1"))];
|
||||
let output = render_dynamic_section(&personas, &agents, "ws://example.com:3000");
|
||||
assert!(output.contains("| Kit | Builder | @Kit |"));
|
||||
assert!(output.contains("## CLI Quick Reference"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_render_dynamic_section_empty() {
|
||||
let output = render_dynamic_section(&[], &[], "ws://example.com:3000");
|
||||
assert!(output.contains("No agents deployed yet"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_render_dynamic_section_agent_no_persona() {
|
||||
let personas = vec![make_persona("p1", "Builder")];
|
||||
let agents = vec![make_agent("Scout", Some("nonexistent"))];
|
||||
let output = render_dynamic_section(&personas, &agents, "ws://example.com:3000");
|
||||
assert!(output.contains("| Scout | — | @Scout |"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_upsert_managed_section_with_markers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let file = tmp.path().join("AGENTS.md");
|
||||
fs::write(
|
||||
&file,
|
||||
"# Header\n\nsome content\n\n<!-- BEGIN SPROUT MANAGED — regenerated automatically, do not edit below -->\nold section\n<!-- END SPROUT MANAGED -->\n\nafter\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
upsert_managed_section(&file, "new section").unwrap();
|
||||
|
||||
let result = fs::read_to_string(&file).unwrap();
|
||||
assert!(result.contains("<!-- BEGIN SPROUT MANAGED"));
|
||||
assert!(result.contains("<!-- END SPROUT MANAGED -->"));
|
||||
assert!(result.contains("new section"));
|
||||
assert!(!result.contains("old section"));
|
||||
assert!(result.contains("# Header"));
|
||||
assert!(result.contains("some content"));
|
||||
assert!(result.contains("after"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_upsert_managed_section_without_markers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let file = tmp.path().join("AGENTS.md");
|
||||
fs::write(&file, "# Header\n\nexisting content\n").unwrap();
|
||||
|
||||
upsert_managed_section(&file, "injected section").unwrap();
|
||||
|
||||
let result = fs::read_to_string(&file).unwrap();
|
||||
assert!(result.contains("# Header"));
|
||||
assert!(result.contains("existing content"));
|
||||
assert!(result.contains("<!-- BEGIN SPROUT MANAGED"));
|
||||
assert!(result.contains("<!-- END SPROUT MANAGED -->"));
|
||||
assert!(result.contains("injected section"));
|
||||
let begin_pos = result.find("<!-- BEGIN SPROUT MANAGED").unwrap();
|
||||
let header_pos = result.find("# Header").unwrap();
|
||||
assert!(
|
||||
header_pos < begin_pos,
|
||||
"original content should precede the managed section"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_upsert_managed_section_no_tmp_leftover() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let file = tmp.path().join("AGENTS.md");
|
||||
fs::write(&file, "# Header\n").unwrap();
|
||||
|
||||
upsert_managed_section(&file, "content").unwrap();
|
||||
|
||||
let tmp_path = file.with_extension("md.tmp");
|
||||
assert!(
|
||||
!tmp_path.exists(),
|
||||
".tmp file should not exist after successful upsert"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,3 +70,10 @@ created: 2026-01-15
|
||||
- **Never push without approval** — do not `git push` to any remote
|
||||
- **Stay on task** — only stage files relevant to your current work
|
||||
- **Tagging or @mentioning others** — you can mention other bots or users by simply @'ing them in your message, but you cannot bold, italicize, or otherwise format the mention text if you want them to actually be alerted
|
||||
|
||||
<!-- BEGIN SPROUT MANAGED — regenerated automatically, do not edit below -->
|
||||
## Active Agents
|
||||
|
||||
*(No agents deployed yet. Add agents in the Sprout desktop app.)*
|
||||
|
||||
<!-- END SPROUT MANAGED -->
|
||||
|
||||
Reference in New Issue
Block a user