Add agent conversation runtime foundation

This commit is contained in:
klopez4212
2026-06-30 13:33:32 +01:00
parent 325b3fdb0d
commit aba7bdf45c
21 changed files with 661 additions and 423 deletions

View File

@@ -176,6 +176,7 @@ pub async fn get_agent_config_surface(
record.persona_id.as_deref(),
&personas,
record.agent_command_override.as_deref(),
Some(&record.agent_command),
);
let runtime_meta = known_acp_runtime(&effective_cmd);
let session_cache = state.get_session_cache(&pubkey);

View File

@@ -66,6 +66,7 @@ pub async fn get_agent_models(
record.persona_id.as_deref(),
&personas,
record.agent_command_override.as_deref(),
Some(&record.agent_command),
);
let args = normalize_agent_args(&effective_command, record.agent_args.clone());
@@ -929,6 +930,7 @@ pub async fn update_managed_agent(
record.persona_id.as_deref(),
&personas,
record.agent_command_override.as_deref(),
Some(&record.agent_command),
);
let avatar_url = record
.avatar_url

View File

@@ -0,0 +1,32 @@
use tauri::AppHandle;
use crate::{app_state::AppState, managed_agents::load_managed_agents};
use super::agents::ProfileReconcileData;
pub(super) fn refresh_auth_tag(
app: &AppHandle,
state: &AppState,
pubkey: &str,
data: &mut ProfileReconcileData,
) {
let result = (|| -> Result<(), String> {
let _store_guard = state
.managed_agents_store_lock
.lock()
.map_err(|error| error.to_string())?;
let records = load_managed_agents(app)?;
let record = records
.iter()
.find(|record| record.pubkey == pubkey)
.ok_or_else(|| format!("agent {pubkey} not found"))?;
data.auth_tag = record.auth_tag.clone();
Ok(())
})();
if let Err(error) = result {
eprintln!(
"buzz-desktop: profile reconciliation using pre-start auth tag for agent {pubkey}: {error}"
);
}
}

View File

@@ -241,6 +241,11 @@ async fn start_local_agent_with_preflight(
ensure_relay_mesh_for_record(app, &record_snapshot, allow_fresh_create_start).await?;
let refreshed_auth_tag = {
let owner_keys = state.keys.lock().map_err(|e| e.to_string())?;
crate::managed_agents::managed_agent_auth_tag_for_owner(&owner_keys, pubkey)?
};
let _store_guard = state
.managed_agents_store_lock
.lock()
@@ -254,6 +259,14 @@ async fn start_local_agent_with_preflight(
if record.backend != BackendKind::Local {
return Err(format!("agent {pubkey} is no longer a local agent"));
}
if !crate::managed_agents::auth_tag_matches_owner(
record.auth_tag.as_deref(),
&record.pubkey,
Some(owner_hex),
) {
record.auth_tag = refreshed_auth_tag;
record.updated_at = crate::util::now_iso();
}
// Re-snapshot the persona onto the record at every spawn so the agent always
// starts with the current persona config (system_prompt, model, provider,
// env_vars). This clears the "out of date" drift badge without requiring a
@@ -655,6 +668,7 @@ pub async fn create_managed_agent(
requested_persona_id.as_deref(),
&personas,
agent_command_override.as_deref(),
None,
);
let agent_args = normalize_agent_args(
&agent_command,
@@ -976,6 +990,10 @@ pub async fn start_managed_agent(
// Snapshot the workspace owner pubkey for the legacy auth_tag fallback.
// Read outside the records lock to keep lock ordering simple.
let owner_hex = workspace_owner_hex(&state)?;
let refreshed_auth_tag = {
let owner_keys = state.keys.lock().map_err(|error| error.to_string())?;
crate::managed_agents::managed_agent_auth_tag_for_owner(&owner_keys, &pubkey)?
};
enum StartTarget {
Local,
Provider {
@@ -986,8 +1004,7 @@ pub async fn start_managed_agent(
}
// Collect backend info under lock; async preflight/spawn happens below.
// Also snapshot profile reconciliation data for the background task.
let (target, reconcile_data) = {
let (target, mut reconcile_data) = {
let _store_guard = state
.managed_agents_store_lock
.lock()
@@ -1000,14 +1017,21 @@ pub async fn start_managed_agent(
let (sync_changed, exited_pubkeys) =
sync_managed_agent_processes(&mut records, &mut runtimes, &current_instance_id(&app));
if sync_changed {
save_managed_agents(&app, &records)?;
}
let mut records_changed = sync_changed;
for pubkey in &exited_pubkeys {
state.clear_session_cache(pubkey);
}
let record = find_managed_agent_mut(&mut records, &pubkey)?;
if !crate::managed_agents::auth_tag_matches_owner(
record.auth_tag.as_deref(),
&record.pubkey,
Some(&owner_hex),
) {
record.auth_tag = refreshed_auth_tag;
record.updated_at = crate::util::now_iso();
records_changed = true;
}
// Resolve the effective harness for the avatar-fallback derivation in
// profile reconcile (the create-time snapshot may be empty or stale for
@@ -1017,6 +1041,7 @@ pub async fn start_managed_agent(
record.persona_id.as_deref(),
&reconcile_personas,
record.agent_command_override.as_deref(),
Some(&record.agent_command),
);
let reconcile = ProfileReconcileData {
@@ -1040,6 +1065,10 @@ pub async fn start_managed_agent(
}
};
if records_changed {
save_managed_agents(&app, &records)?;
}
(target, reconcile)
};
@@ -1088,9 +1117,10 @@ pub async fn start_managed_agent(
// ── Profile reconciliation (fire-and-forget) ────────────────────────────
// On successful start, spawn a background task to ensure the agent's kind:0
// profile is published on the relay. This self-heals cases where the initial
// profile sync at creation time failed silently. For legacy records (pre-PR-921)
// with no persisted avatar, this also backfills the avatar from the relay.
// profile sync at creation time failed silently.
if result.is_ok() {
use super::agent_profile_reconcile as reconcile;
reconcile::refresh_auth_tag(&app, &state, &pubkey, &mut reconcile_data);
let reconcile_pubkey = pubkey.clone();
let reconcile_app = app.clone();
tauri::async_runtime::spawn(async move {

View File

@@ -283,6 +283,7 @@ pub async fn send_channel_message(
media_tags: Option<Vec<Vec<String>>>,
emoji_tags: Option<Vec<Vec<String>>>,
mention_tags: Option<Vec<Vec<String>>>,
client_tags: Option<Vec<Vec<String>>>,
mention_pubkeys: Option<Vec<String>>,
kind: Option<u32>,
state: State<'_, AppState>,
@@ -294,7 +295,11 @@ pub async fn send_channel_message(
let media = media_tags.unwrap_or_default();
let emoji = emoji_tags.unwrap_or_default();
let mention_refs_only = mention_tags.unwrap_or_default();
let client = client_tags.unwrap_or_default();
let kind_num = kind.unwrap_or(buzz_core_pkg::kind::KIND_STREAM_MESSAGE);
if kind_num != buzz_core_pkg::kind::KIND_STREAM_MESSAGE && !client.is_empty() {
return Err("client tags are only supported on stream messages".into());
}
let mut resolved_root: Option<String> = None;
@@ -330,7 +335,7 @@ pub async fn send_channel_message(
}
None => None,
};
events::build_message(
events::build_message_with_client_tags(
channel_uuid,
content.trim(),
thread_ref.as_ref(),
@@ -338,6 +343,7 @@ pub async fn send_channel_message(
&media,
&emoji,
&mention_refs_only,
&client,
)?
}
};

View File

@@ -1,6 +1,7 @@
mod agent_config;
mod agent_discovery;
mod agent_models;
mod agent_profile_reconcile;
mod agent_settings;
mod agents;
mod canvas;

View File

@@ -279,11 +279,14 @@ pub fn default_agent_command() -> String {
/// Resolution order:
/// 1. explicit override (non-empty) — a deliberate per-instance pin;
/// 2. the linked persona's `runtime` id mapped to its primary command;
/// 3. `default_agent_command()` — no persona/runtime, or persona deleted.
/// 3. the record's stored `agent_command` snapshot for legacy records whose
/// persona has no runtime field;
/// 4. `default_agent_command()` — no persona/runtime/snapshot, or persona deleted.
pub fn effective_agent_command(
persona_id: Option<&str>,
personas: &[crate::managed_agents::types::PersonaRecord],
agent_command_override: Option<&str>,
record_agent_command: Option<&str>,
) -> String {
if let Some(pin) = agent_command_override
.map(str::trim)
@@ -298,6 +301,12 @@ pub fn effective_agent_command(
.and_then(known_acp_runtime_exact)
.and_then(|r| r.commands.first().copied())
.map(str::to_string)
.or_else(|| {
record_agent_command
.map(str::trim)
.filter(|value| !value.is_empty())
.map(str::to_string)
})
.unwrap_or_else(default_agent_command)
}
@@ -320,7 +329,7 @@ pub fn divergent_agent_command_override(
let picked = picked_command
.map(str::trim)
.filter(|value| !value.is_empty())?;
let persona_command = effective_agent_command(persona_id, personas, None);
let persona_command = effective_agent_command(persona_id, personas, None, None);
let same_runtime = match (
known_acp_runtime(picked),
known_acp_runtime(&persona_command),
@@ -373,7 +382,7 @@ pub fn create_time_agent_command_override(
let picked = picked_command
.map(str::trim)
.filter(|value| !value.is_empty())?;
let inherited_command = effective_agent_command(persona_id, personas, None);
let inherited_command = effective_agent_command(persona_id, personas, None, None);
return (picked != inherited_command).then(|| picked.to_string());
}
@@ -927,7 +936,7 @@ mod tests {
// An explicit pin beats the persona's runtime.
let personas = vec![persona_with_runtime("p1", Some("claude"))];
assert_eq!(
effective_agent_command(Some("p1"), &personas, Some("codex-acp")),
effective_agent_command(Some("p1"), &personas, Some("codex-acp"), Some("goose")),
"codex-acp"
);
}
@@ -937,7 +946,7 @@ mod tests {
// No override → persona runtime id maps to its primary command.
let personas = vec![persona_with_runtime("p1", Some("claude"))];
assert_eq!(
effective_agent_command(Some("p1"), &personas, None),
effective_agent_command(Some("p1"), &personas, None, Some("goose")),
"claude-agent-acp"
);
}
@@ -947,26 +956,37 @@ mod tests {
// A blank/whitespace override is treated as "inherit", not a pin.
let personas = vec![persona_with_runtime("p1", Some("goose"))];
assert_eq!(
effective_agent_command(Some("p1"), &personas, Some(" ")),
effective_agent_command(Some("p1"), &personas, Some(" "), Some("buzz-agent")),
"goose"
);
}
#[test]
fn effective_agent_command_falls_back_to_record_snapshot() {
// Legacy records may predate persona runtime fields. Preserve their
// stored harness instead of silently changing them to the new default.
let personas = vec![persona_with_runtime("p1", None)];
assert_eq!(
effective_agent_command(Some("p1"), &personas, None, Some("goose")),
"goose"
);
}
#[test]
fn effective_agent_command_falls_back_to_default() {
// No override, no persona runtime, and a deleted persona all fall back
// to the bundled default.
// No override, no persona runtime, no record snapshot, and a deleted
// persona all fall back to the bundled default.
let personas = vec![persona_with_runtime("p1", None)];
assert_eq!(
effective_agent_command(Some("p1"), &personas, None),
effective_agent_command(Some("p1"), &personas, None, None),
default_agent_command()
);
assert_eq!(
effective_agent_command(Some("gone"), &personas, None),
effective_agent_command(Some("gone"), &personas, None, None),
default_agent_command()
);
assert_eq!(
effective_agent_command(None, &personas, None),
effective_agent_command(None, &personas, None, None),
default_agent_command()
);
}

View File

@@ -197,15 +197,46 @@ pub async fn restore_managed_agents_on_launch(
return Ok(());
}
// Snapshot the workspace owner pubkey once for the legacy auth_tag fallback.
// Read outside the per-agent spawn loop so all parallel spawns see the same
// value and we don't lock `state.keys` repeatedly.
let owner_hex: Option<String> = state
.keys
.lock()
.map_err(|e| e.to_string())
.ok()
.map(|k| k.public_key().to_hex());
// Snapshot the workspace owner once and refresh each restored agent's
// NIP-OA auth tag when the app identity changed since the record was
// created. Without this, owner-only agents can start successfully but ignore
// the current user's messages because the harness resolves an old owner.
let (owner_hex, auth_tag_updates): (Option<String>, Vec<(String, Option<String>, String)>) = {
let owner_keys = state.keys.lock().map_err(|e| e.to_string())?;
let owner_hex = owner_keys.public_key().to_hex();
let mut updates = Vec::new();
for record in &mut agents_to_start {
if super::auth_tag_matches_owner(
record.auth_tag.as_deref(),
&record.pubkey,
Some(&owner_hex),
) {
continue;
}
let refreshed_auth_tag =
super::managed_agent_auth_tag_for_owner(&owner_keys, &record.pubkey)?;
let updated_at = util::now_iso();
record.auth_tag = refreshed_auth_tag.clone();
record.updated_at = updated_at.clone();
updates.push((record.pubkey.clone(), refreshed_auth_tag, updated_at));
}
(Some(owner_hex), updates)
};
if !auth_tag_updates.is_empty() {
let _store_guard = state
.managed_agents_store_lock
.lock()
.map_err(|error| error.to_string())?;
let mut records = load_managed_agents(app)?;
for (pubkey, auth_tag, updated_at) in &auth_tag_updates {
if let Ok(record) = find_managed_agent_mut(&mut records, pubkey) {
record.auth_tag = auth_tag.clone();
record.updated_at = updated_at.clone();
}
}
save_managed_agents(app, &records)?;
}
#[cfg(feature = "mesh-llm")]
let agents_to_start = {
@@ -310,6 +341,7 @@ pub async fn restore_managed_agents_on_launch(
record.persona_id.as_deref(),
&reconcile_personas,
record.agent_command_override.as_deref(),
Some(&record.agent_command),
);
Some((
pubkey.clone(),

View File

@@ -1517,6 +1517,7 @@ pub fn build_managed_agent_summary(
record.persona_id.as_deref(),
personas,
record.agent_command_override.as_deref(),
Some(&record.agent_command),
);
let effective_args = normalize_agent_args(&effective_command, record.agent_args.clone());
let effective_mcp_command = known_acp_runtime(&effective_command)
@@ -1611,12 +1612,10 @@ pub(crate) fn build_respond_to_env(
remove.push("BUZZ_ACP_RESPOND_TO_ALLOWLIST");
}
// Legacy fallback: agents created before NIP-OA lack `auth_tag`. Without
// it the harness can't resolve the owner, and owner-dependent gate modes
// would drop every event. Forwarding the workspace owner pubkey via
// BUZZ_ACP_AGENT_OWNER keeps those records functional. Modern records
// (`auth_tag = Some(...)`) use `BUZZ_AUTH_TAG` as before.
if record.auth_tag.is_none() {
// Fallback: if the record has no usable NIP-OA `auth_tag` for the current
// workspace owner, forward the owner pubkey explicitly. This covers both
// pre-NIP-OA records and records restored after the local identity changed.
if !auth_tag_matches_owner(record.auth_tag.as_deref(), &record.pubkey, owner_hex) {
if let Some(owner) = owner_hex {
set.push(("BUZZ_ACP_AGENT_OWNER", owner.to_string()));
} else {
@@ -1629,6 +1628,53 @@ pub(crate) fn build_respond_to_env(
Ok((set, remove))
}
pub(crate) fn auth_tag_owner_hex(auth_tag: &str, agent_pubkey_hex: &str) -> Option<String> {
let trimmed = auth_tag.trim();
if trimmed.is_empty() {
return None;
}
let agent_pubkey = nostr::PublicKey::from_hex(agent_pubkey_hex).ok()?;
buzz_sdk_pkg::nip_oa::verify_auth_tag(trimmed, &agent_pubkey)
.ok()
.map(|owner| owner.to_hex().to_ascii_lowercase())
}
pub(crate) fn auth_tag_matches_owner(
auth_tag: Option<&str>,
agent_pubkey_hex: &str,
owner_hex: Option<&str>,
) -> bool {
let Some(tag) = auth_tag.map(str::trim).filter(|tag| !tag.is_empty()) else {
return false;
};
match owner_hex {
Some(owner) => auth_tag_owner_hex(tag, agent_pubkey_hex)
.is_some_and(|tag_owner| tag_owner.eq_ignore_ascii_case(owner)),
None => true,
}
}
pub(crate) fn managed_agent_auth_tag_for_owner(
owner_keys: &nostr::Keys,
agent_pubkey_hex: &str,
) -> Result<Option<String>, String> {
if owner_keys
.public_key()
.to_hex()
.eq_ignore_ascii_case(agent_pubkey_hex)
{
return Ok(None);
}
let compat_owner = nostr::Keys::parse(&owner_keys.secret_key().to_secret_hex())
.map_err(|error| format!("failed to bridge owner keys: {error}"))?;
let compat_agent = nostr::PublicKey::from_hex(agent_pubkey_hex)
.map_err(|error| format!("failed to bridge agent pubkey: {error}"))?;
buzz_sdk_pkg::nip_oa::compute_auth_tag(&compat_owner, &compat_agent, "")
.map(Some)
.map_err(|error| format!("failed to compute NIP-OA auth tag: {error}"))
}
/// Spawn an agent process without holding any locks on records or runtimes.
/// Returns the child process and log path on success. The caller is responsible
/// for updating `ManagedAgentRecord` fields and inserting into the runtimes map.
@@ -1668,6 +1714,7 @@ pub fn spawn_agent_child(
record.persona_id.as_deref(),
&personas,
record.agent_command_override.as_deref(),
Some(&record.agent_command),
);
let agent_args = normalize_agent_args(&effective_command, record.agent_args.clone());
let resolved_acp_command = resolve_command(&record.acp_command)
@@ -1822,7 +1869,13 @@ pub fn spawn_agent_child(
command.env_remove("BUZZ_ACP_API_TOKEN");
command.env_remove("BUZZ_API_TOKEN");
if let Some(ref auth_tag) = record.auth_tag {
let auth_tag_for_child = record
.auth_tag
.as_deref()
.map(str::trim)
.filter(|tag| !tag.is_empty())
.filter(|tag| auth_tag_matches_owner(Some(tag), &record.pubkey, owner_hex));
if let Some(auth_tag) = auth_tag_for_child {
command.env("BUZZ_AUTH_TAG", auth_tag);
} else {
command.env_remove("BUZZ_AUTH_TAG");

View File

@@ -159,8 +159,16 @@ fn fixture(
#[test]
fn build_env_owner_only_sets_mode_and_removes_others() {
let rec = fixture(RespondTo::OwnerOnly, vec![], Some("tag".into()));
let (set, remove) = build_respond_to_env(&rec, Some("owner")).unwrap();
let owner = nostr::Keys::generate();
let agent = nostr::Keys::generate();
let agent_pubkey = agent.public_key().to_hex();
let auth_tag = super::managed_agent_auth_tag_for_owner(&owner, &agent_pubkey)
.unwrap()
.unwrap();
let mut rec = fixture(RespondTo::OwnerOnly, vec![], Some(auth_tag));
rec.pubkey = agent_pubkey;
let owner_hex = owner.public_key().to_hex();
let (set, remove) = build_respond_to_env(&rec, Some(&owner_hex)).unwrap();
let set_map: std::collections::HashMap<_, _> = set.into_iter().collect();
assert_eq!(
set_map.get("BUZZ_ACP_RESPOND_TO").map(String::as_str),
@@ -172,6 +180,27 @@ fn build_env_owner_only_sets_mode_and_removes_others() {
assert!(remove.contains(&"BUZZ_ACP_AGENT_OWNER"));
}
#[test]
fn build_env_stale_auth_tag_emits_current_owner() {
let previous_owner = nostr::Keys::generate();
let current_owner = nostr::Keys::generate();
let agent = nostr::Keys::generate();
let agent_pubkey = agent.public_key().to_hex();
let stale_auth_tag = super::managed_agent_auth_tag_for_owner(&previous_owner, &agent_pubkey)
.unwrap()
.unwrap();
let mut rec = fixture(RespondTo::OwnerOnly, vec![], Some(stale_auth_tag));
rec.pubkey = agent_pubkey;
let current_owner_hex = current_owner.public_key().to_hex();
let (set, remove) = build_respond_to_env(&rec, Some(&current_owner_hex)).unwrap();
let set_map: std::collections::HashMap<_, _> = set.into_iter().collect();
assert_eq!(
set_map.get("BUZZ_ACP_AGENT_OWNER").map(String::as_str),
Some(current_owner_hex.as_str())
);
assert!(!remove.contains(&"BUZZ_ACP_AGENT_OWNER"));
}
#[test]
fn build_env_allowlist_sets_both_envs_and_joins() {
let a = "a".repeat(64);