Files
buzz/desktop/src-tauri/src/managed_agents/runtime/instance_reaper.rs
Will Pfleger 95fdf97880 feat(acp): bring your own harness (BYOH) — generic ACP runtime seam + settings gallery (#2773)
## What

Implements a "bring your own harness" (BYOH) generic ACP mechanism —
replacing per-harness backend code with a data-driven 3-tier system:

- **Tier 1 (compiled-in builtins):** goose, claude, codex, buzz-agent —
unchanged behavior
- **Tier 2 (bundled presets):** cursor, omp, grok, opencode, kimi, amp,
hermes, openclaw, and any future additions — defined in
`PRESET_HARNESSES`, no code duplication, icons stay
TerminalSquare/bundled-asset-only
- **Tier 3 (user-defined custom):** JSON definitions saved to
`custom_harnesses/` under app data; managed via Settings → Agents UI

## Changes

### Core data model
- `HarnessDefinition` — id, label, command, args, env, install URL/hint
- `PRESET_HARNESSES` static table — single source of truth for all
presets; `preset_harness_ids()` derives reserved IDs (D-11: no
hand-maintained copy)
- `source: "builtin" | "preset" | "custom"` tagging on every catalog
entry

### Persistence (B-4, B-6)
- `save_custom_harness_to_dir(dir, definition, rename_old_id)` —
backup-swap atomic write (backs up target → .bak, commits temp → target,
restores .bak on failure, removes .bak on success); safe on Windows
where `fs::rename` over an existing file is "access denied"
- `save_and_warm` / `delete_and_warm` — hold `PERSIST_MUTEX` for the
write + registry-warm pair, eliminating the lost-update race (B-6) where
two concurrent saves could interleave their warm calls and leave a stale
registry snapshot
- Validate-before-mutate: both IDs and env validated before any
filesystem mutation

### Env validation boundary (B-3)
- `validate_harness_definition_pub` calls `validate_user_env_keys` on
definition env at save AND load
- Rejects malformed keys (BUZZ_AUTH_TAG=x forgery shape), reserved keys
(BUZZ_MANAGED_AGENT etc.), NUL bytes, oversized values

### TypeScript boundary (B-2 / Thufir CRITICAL)
- `RawAcpRuntimeCatalogEntry` now declares `definition_env?:
Record<string,string>` and `source: "builtin" | "preset" | "custom"`
- `fromRawAcpRuntimeCatalogEntry` maps `definition_env → definitionEnv`
(camelCase); absent field defaults to `{}`
- Edit form reads `entry.definitionEnv` — env no longer erased on
save-then-edit cycle

### Unified descriptor (Phase A / Thufir F4)
- `EffectiveHarnessDescriptor { command, args, env }` in `readiness.rs`
- `resolve_effective_harness_descriptor()` — single resolver used by
spawn, spawn_hash, summary, get_agent_models (both saved and unsaved),
and readiness
- No competing arg-resolution forms

### Other fixes
- B-5: stop freezing `runtime.defaultArgs` into `record.agent_args` on
normal create paths
- B-7: readiness exec-check — `MissingBinary` variant for custom
commands not found on PATH
- B-8: onboarding transition — `setTimeout(0)` removed, parent-owned
route intent via `navigateAfterComplete` prop
- C-9: collector-discriminating sweep tests with injectable filters
- C-10: `HarnessManagementCard` uses `harnessGalleryLogic` helpers
(killed duplicate filter/sort)
- D-11: `BUILTIN_IDS` derived from `PRESET_HARNESSES` (no
hand-maintained copy)
- D-12: `mobile/pubspec.lock` churn reverted
- D-13: false ownership fast-path comment fixed
- D-14: URL scheme validation for `installInstructionsUrl`
- D-15: OpenClaw Gateway env-locus README line

### Tests added
**B-4 persistence (6 tests):**
`save_to_dir_create_writes_file_and_loads_back`,
`save_to_dir_same_id_edit_replaces_content`,
`save_to_dir_backup_is_cleaned_up_after_same_id_edit`,
`save_to_dir_rename_removes_old_file_and_creates_new`,
`save_to_dir_rename_nonexistent_old_id_is_non_fatal`,
`save_to_dir_roundtrip_with_env_preserves_values`

**B-3 env validation (6 tests):**
`validate_rejects_malformed_key_with_equals_sign`,
`validate_rejects_reserved_key_buzz_managed_agent`,
`validate_rejects_reserved_key_case_insensitive`,
`validate_rejects_nul_byte_in_value`,
`validate_rejects_value_over_per_value_size_limit`,
`validate_accepts_well_formed_env`

**B-2 API boundary (4 TS tests in tauri.test.mjs):**
`fromRawAcpRuntimeCatalogEntry maps definition_env to definitionEnv`,
`defaults definitionEnv to {} when absent`, `preserves source preset`,
`env round-trips through edit payload shape`

## Preset catalog

| ID | Label | Command |
|----|-------|---------|
| `cursor` | Cursor | `cursor-agent acp` |
| `omp` | Oh My Pi | `omp acp` |
| `grok` | Grok Build | `grok agent --always-approve stdio` |
| `opencode` | OpenCode | `opencode acp` |
| `kimi` | Kimi Code | `kimi acp` |
| `amp` | Amp | `amp-acp` |
| `hermes` | Hermes Agent | `hermes-acp` |
| `openclaw` | OpenClaw | `openclaw acp` |

## Review-fix pass (2026-07-26, Eva)

Fixes from the three-way review (Wren / Dawn / Eva) in the
buzz-generic-acp-harnesses thread, pushed as new commits (no rewrite):

1. **installHint edit round-trip** — form seeding extracted to
`formValuesFromCatalogEntry` (single source of truth), input rendered,
full-definition lossless round-trip regression.
2. **Dangling-delete coherence** — delete allowed; confirm counts
referencing agents (direct pin + persona-inherited); summary rows render
`harness (deleted): <id>`; spawn errors become actionable sentences
(`user_facing_harness_error`); composed delete→summary→start test.
3. **Comma-in-args** — rejected at `validate_harness_definition` (shared
by save AND disk load), mirrored inline in the form.
4. **Registry publish race** — collision/dup filtering moved into
`load_custom_harnesses` (both loaders inherit shadowing rules);
discovery publishes by re-reading the dir under `persist_mutex` (lock
scoped to publish only); deterministic interleaving regressions for
save-during-discovery and delete-during-discovery.
5. **Mechanical** — discarded `belongs_to_us` sweep arg deleted,
`load_global_agent_config` hoisted out of the per-record summary loop,
duplicated doc paragraph + stray SAFETY comment removed.
6. **PGID test de-flaked** — leader kept alive through the assertion.

Known follow-up (filed in review, not blocking): file-size split-outs
queued in `check-file-sizes.mjs` entries.

## Gate table — head `bf53f1d60`

| Gate | Result |
|------|--------|
| `cargo test --lib` (desktop/src-tauri) | **1701 passed**, 0 failed, 14
ignored |
| desktop JS suite (`pnpm test`) | **3605 passed**, 0 failed |
| `tsc --noEmit` | clean |
| `biome check` + file-size/px/pubkey checks | clean |
| `cargo clippy --lib -- -D warnings` | clean |
| `cargo fmt --check` | clean |

PR head: `bf53f1d60e3cbd07392e1287b83bb37ba90d0d33` — includes merge of
origin/main (`c2a4ee711`, conflicts in agent_models composed with
#2890's live Databricks discovery)

---------

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: tlongwell-block <109685178+tlongwell-block@users.noreply.github.com>
Signed-off-by: Tyler Longwell <tlongwell@block.xyz>
Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Co-authored-by: tlongwell-block <109685178+tlongwell-block@users.noreply.github.com>
Co-authored-by: Dawn (sprout agent) <c6237ef84fa537c78dcee78efd2d4e59f728859c7f194da42ac51ededfa0be05@sprout-oss.stage.blox.sqprod.co>
Co-authored-by: Tyler Longwell <tlongwell@block.xyz>
Co-authored-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz>
2026-07-26 20:06:20 -04:00

360 lines
12 KiB
Rust

use super::*;
/// Binary names for the Buzz desktop/Tauri process. Used by dead-instance
/// detection to confirm the owning desktop is still alive.
const DESKTOP_BINARY_NAMES: &[&str] = &[
"Buzz",
"buzz-desktop",
"buzz_desktop",
// Linux limits /proc/<pid>/comm to 15 visible bytes, truncating the
// AppImage shim's real executable name, `buzz-desktop.bin`.
"buzz-desktop.bi",
];
/// Check if a process name matches a known Buzz desktop binary.
pub(super) fn is_desktop_binary(name: &str) -> bool {
DESKTOP_BINARY_NAMES.contains(&name)
}
/// Check whether `buf` contains `id` as a complete identifier — not as a
/// prefix of a longer dotted name. The identifier appears in the Tauri config
/// JSON as `"identifier":"xyz.block.buzz.app.dev"` and in environment entries
/// as `KEY=...app.dev\0`, so a valid match is followed by a non-identifier byte
/// (not `[A-Za-z0-9._-]`) or sits at the end of the buffer. This prevents
/// `xyz.block.buzz.app` from matching inside `xyz.block.buzz.app.dev`.
pub(super) fn buffer_contains_identifier(buf: &[u8], id: &[u8]) -> bool {
if id.is_empty() {
return false;
}
buf.windows(id.len()).enumerate().any(|(i, w)| {
if w != id {
return false;
}
// Boundary check on the byte immediately after the match: end-of-buffer
// or any byte that can't continue a dotted reverse-DNS identifier.
match buf.get(i + id.len()) {
None => true,
Some(&next) => {
!next.is_ascii_alphanumeric() && next != b'.' && next != b'_' && next != b'-'
}
}
})
}
/// Extract the `BUZZ_MANAGED_AGENT` value from a process's environment.
/// Returns `None` if the process doesn't have the marker or can't be read.
#[cfg(target_os = "macos")]
fn extract_buzz_marker_value(pid: u32) -> Option<String> {
let prefix = b"BUZZ_MANAGED_AGENT=";
let buf = sweep::procargs2_buffer(pid)?;
if buf.len() < std::mem::size_of::<libc::c_int>() {
return None;
}
let mut n_args: libc::c_int = 0;
unsafe {
std::ptr::copy_nonoverlapping(
buf.as_ptr(),
&mut n_args as *mut libc::c_int as *mut u8,
std::mem::size_of::<libc::c_int>(),
);
}
let mut pos = std::mem::size_of::<libc::c_int>();
// Skip exec path.
while pos < buf.len() && buf[pos] != 0 {
pos += 1;
}
while pos < buf.len() && buf[pos] == 0 {
pos += 1;
}
// Skip argc argument strings.
let mut args_remaining = n_args;
while args_remaining > 0 && pos < buf.len() {
while pos < buf.len() && buf[pos] != 0 {
pos += 1;
}
while pos < buf.len() && buf[pos] == 0 {
pos += 1;
}
args_remaining -= 1;
}
// Search environment entries for our marker.
for entry in buf[pos..].split(|&b| b == 0) {
if entry.starts_with(prefix) {
return String::from_utf8(entry[prefix.len()..].to_vec()).ok();
}
}
None
}
#[cfg(all(unix, not(target_os = "macos")))]
fn extract_buzz_marker_value(pid: u32) -> Option<String> {
let prefix = b"BUZZ_MANAGED_AGENT=";
let data = std::fs::read(format!("/proc/{pid}/environ")).ok()?;
for entry in data.split(|&b| b == 0) {
if entry.starts_with(prefix) {
return String::from_utf8(entry[prefix.len()..].to_vec()).ok();
}
}
None
}
#[cfg(not(unix))]
fn extract_buzz_marker_value(_pid: u32) -> Option<String> {
None
}
/// Check if a Buzz desktop process is still alive for the given instance ID.
/// Scans all user-owned processes named "Buzz" or "buzz-desktop" and checks
/// whether any has the identifier in its command-line args (KERN_PROCARGS2 buffer
/// includes both argv and environ — the `--config` JSON from `tauri dev` contains
/// the identifier string).
#[cfg(target_os = "macos")]
fn desktop_is_alive_for_instance(instance_id: &str) -> bool {
extern "C" {
fn proc_name(pid: libc::c_int, buffer: *mut libc::c_void, buffersize: u32) -> libc::c_int;
}
let my_uid = unsafe { libc::getuid() };
let identifier_bytes = instance_id.as_bytes();
let pids = sweep::collect_all_pids();
if pids.is_empty() {
return false;
}
for &pid in &pids {
if pid <= 0 {
continue;
}
// Check binary name — only look at desktop binaries.
let mut name_buf = [0u8; 1024];
let len = unsafe {
proc_name(
pid,
name_buf.as_mut_ptr() as *mut libc::c_void,
name_buf.len() as u32,
)
};
if len <= 0 {
continue;
}
let name = String::from_utf8_lossy(&name_buf[..len as usize]);
if !is_desktop_binary(&name) {
continue;
}
// Verify UID.
let mut info = std::mem::MaybeUninit::<BSDInfo>::zeroed();
let ret = unsafe {
proc_pidinfo(
pid,
PROC_PIDTBSDINFO,
0,
info.as_mut_ptr() as *mut libc::c_void,
std::mem::size_of::<BSDInfo>() as libc::c_int,
)
};
if ret <= 0 {
continue;
}
let info = unsafe { info.assume_init() };
if info.pbi_uid != my_uid {
continue;
}
// Check if this desktop process's args/env contain the identifier.
// The KERN_PROCARGS2 buffer holds argv + environ as null-delimited strings.
let Some(args_buf) = sweep::procargs2_buffer(pid as u32) else {
continue;
};
// Boundary-anchored search: the identifier in the config JSON is
// followed by a non-identifier char (typically `"`). A raw substring
// match would let `...app` match inside `...app.dev`.
if buffer_contains_identifier(&args_buf, identifier_bytes) {
return true;
}
}
false
}
#[cfg(all(unix, not(target_os = "macos")))]
fn desktop_is_alive_for_instance(instance_id: &str) -> bool {
let my_uid = unsafe { libc::getuid() };
let Ok(entries) = std::fs::read_dir("/proc") else {
return false;
};
for entry in entries.flatten() {
let name = entry.file_name();
let Some(name_str) = name.to_str() else {
continue;
};
let Ok(pid) = name_str.parse::<u32>() else {
continue;
};
// Check ownership.
let Ok(meta) = entry.metadata() else {
continue;
};
use std::os::unix::fs::MetadataExt;
if meta.uid() != my_uid {
continue;
}
// Check binary name via /proc/<pid>/comm.
let Ok(comm) = std::fs::read_to_string(format!("/proc/{pid}/comm")) else {
continue;
};
if !is_desktop_binary(comm.trim()) {
continue;
}
// Check cmdline for the identifier with boundary anchoring.
let Ok(cmdline) = std::fs::read(format!("/proc/{pid}/cmdline")) else {
continue;
};
if buffer_contains_identifier(&cmdline, instance_id.as_bytes()) {
return true;
}
}
false
}
#[cfg(not(unix))]
fn desktop_is_alive_for_instance(_instance_id: &str) -> bool {
false
}
/// Reap agent processes belonging to dead Buzz desktop instances.
///
/// Scans all user processes for `BUZZ_MANAGED_AGENT=*`, groups them by
/// instance ID, and for each foreign instance (≠ `our_instance_id`) checks
/// whether a Buzz desktop binary is still alive for that instance. If not,
/// all agents from that dead instance are reaped.
#[cfg(target_os = "macos")]
pub(crate) fn reap_dead_instance_agents(our_instance_id: &str, skip_pids: &[u32]) {
let my_uid = unsafe { libc::getuid() };
let my_pid = std::process::id() as i32;
let pids = sweep::collect_all_pids();
if pids.is_empty() {
return;
}
// Collect (pid, instance_id) for all foreign agent processes.
let mut foreign_agents: HashMap<String, Vec<i32>> = HashMap::new();
for &pid in &pids {
if pid <= 0 || pid == my_pid {
continue;
}
let upid = pid as u32;
if skip_pids.contains(&upid) {
continue;
}
// Verify UID and PPID via proc_pidinfo before the more expensive env scan.
let mut info = std::mem::MaybeUninit::<BSDInfo>::zeroed();
let ret = unsafe {
proc_pidinfo(
pid,
PROC_PIDTBSDINFO,
0,
info.as_mut_ptr() as *mut libc::c_void,
std::mem::size_of::<BSDInfo>() as libc::c_int,
)
};
if ret <= 0 {
continue;
}
let info = unsafe { info.assume_init() };
if info.pbi_uid != my_uid {
continue;
}
// Extract the instance ID from this agent's env.
// Do NOT name-gate via process_belongs_to_us — custom harnesses use
// arbitrary binary names and BUZZ_MANAGED_AGENT is the authoritative
// ownership proof.
let Some(agent_instance_id) = extract_buzz_marker_value(upid) else {
continue;
};
// Skip agents belonging to our own instance (handled by sweep_system_agent_processes).
if agent_instance_id == our_instance_id {
continue;
}
foreign_agents
.entry(agent_instance_id)
.or_default()
.push(pid);
}
// For each foreign instance, check if its desktop is still alive.
for (instance_id, agent_pids) in &foreign_agents {
if desktop_is_alive_for_instance(instance_id) {
continue;
}
eprintln!(
"buzz-desktop: reaping {} orphaned agent(s) from dead instance '{instance_id}'",
agent_pids.len()
);
resolve_pgids_and_kill(agent_pids);
}
}
#[cfg(all(unix, not(target_os = "macos")))]
pub(crate) fn reap_dead_instance_agents(our_instance_id: &str, skip_pids: &[u32]) {
let my_uid = unsafe { libc::getuid() };
let my_pid = std::process::id() as i32;
let mut foreign_agents: HashMap<String, Vec<i32>> = HashMap::new();
let Ok(entries) = std::fs::read_dir("/proc") else {
return;
};
for entry in entries.flatten() {
let name = entry.file_name();
let Some(name_str) = name.to_str() else {
continue;
};
let Ok(pid) = name_str.parse::<i32>() else {
continue;
};
if pid <= 0 || pid == my_pid {
continue;
}
let upid = pid as u32;
if skip_pids.contains(&upid) {
continue;
}
let Ok(meta) = entry.metadata() else {
continue;
};
use std::os::unix::fs::MetadataExt;
if meta.uid() != my_uid {
continue;
}
// Do NOT name-gate via process_belongs_to_us — custom harnesses use
// arbitrary binary names and BUZZ_MANAGED_AGENT is the authoritative
// ownership proof.
let Some(agent_instance_id) = extract_buzz_marker_value(upid) else {
continue;
};
if agent_instance_id == our_instance_id {
continue;
}
foreign_agents
.entry(agent_instance_id)
.or_default()
.push(pid);
}
for (instance_id, agent_pids) in &foreign_agents {
if desktop_is_alive_for_instance(instance_id) {
continue;
}
eprintln!(
"buzz-desktop: reaping {} orphaned agent(s) from dead instance '{instance_id}'",
agent_pids.len()
);
resolve_pgids_and_kill(agent_pids);
}
}
#[cfg(not(unix))]
pub(crate) fn reap_dead_instance_agents(_our_instance_id: &str, _skip_pids: &[u32]) {}