Skip to content

Commit c65989a

Browse files
wpfleger96npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
andauthored
feat(desktop): harness-agnostic config bridge (#887)
Signed-off-by: Will Pfleger <[email protected]> Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@sprout-oss.stage.blox.sqprod.co>
1 parent 401bb51 commit c65989a

48 files changed

Lines changed: 5352 additions & 109 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎crates/buzz-acp/src/acp.rs‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1535,6 +1535,43 @@ pub fn resolve_model_switch_method(
15351535
None
15361536
}
15371537

1538+
/// Whether `desired_model` appears in pre-extracted catalog halves.
1539+
///
1540+
/// Mirrors [`resolve_model_switch_method`]'s match, but operates on the
1541+
/// already-extracted `configOptions` (model category) and `models` state that
1542+
/// [`AgentModelCapabilities`](crate::pool::AgentModelCapabilities) caches — the
1543+
/// idle-path pre-cancel guard has those halves, not the full `session/new` JSON.
1544+
pub fn model_in_catalog(
1545+
config_options: &[serde_json::Value],
1546+
available_models: Option<&serde_json::Value>,
1547+
desired_model: &str,
1548+
) -> bool {
1549+
let in_config_options = config_options.iter().any(|config_opt| {
1550+
config_opt
1551+
.get("options")
1552+
.and_then(|v| v.as_array())
1553+
.is_some_and(|options| {
1554+
options
1555+
.iter()
1556+
.any(|opt| opt.get("value").and_then(|v| v.as_str()) == Some(desired_model))
1557+
})
1558+
});
1559+
if in_config_options {
1560+
return true;
1561+
}
1562+
1563+
available_models
1564+
.and_then(|models| models.get("availableModels"))
1565+
.and_then(|v| v.as_array())
1566+
.is_some_and(|available| {
1567+
available
1568+
.iter()
1569+
.any(|model| model.get("modelId").and_then(|v| v.as_str()) == Some(desired_model))
1570+
})
1571+
}
1572+
1573+
// ─── Drop: kill child process ─────────────────────────────────────────────────
1574+
15381575
impl Drop for AcpClient {
15391576
fn drop(&mut self) {
15401577
// Best-effort SIGKILL + reap. We cannot `await` in Drop (sync context).
@@ -2087,6 +2124,60 @@ mod tests {
20872124
);
20882125
}
20892126

2127+
// ── model_in_catalog tests ────────────────────────────────────────────
2128+
2129+
#[test]
2130+
fn model_in_catalog_true_when_in_config_options() {
2131+
let config_options = vec![serde_json::json!({
2132+
"configId": "model",
2133+
"category": "model",
2134+
"options": [
2135+
{ "value": "claude-sonnet-4-20250514" },
2136+
{ "value": "claude-opus-4-20250514" }
2137+
]
2138+
})];
2139+
assert!(super::model_in_catalog(
2140+
&config_options,
2141+
None,
2142+
"claude-opus-4-20250514"
2143+
));
2144+
}
2145+
2146+
#[test]
2147+
fn model_in_catalog_true_when_in_available_models() {
2148+
let available = serde_json::json!({
2149+
"currentModelId": "gpt-5",
2150+
"availableModels": [
2151+
{ "modelId": "gpt-5" },
2152+
{ "modelId": "o3-pro" }
2153+
]
2154+
});
2155+
assert!(super::model_in_catalog(&[], Some(&available), "o3-pro"));
2156+
}
2157+
2158+
#[test]
2159+
fn model_in_catalog_false_when_absent_from_both_halves() {
2160+
let config_options = vec![serde_json::json!({
2161+
"configId": "model",
2162+
"options": [{ "value": "claude-sonnet-4-20250514" }]
2163+
})];
2164+
let available = serde_json::json!({
2165+
"availableModels": [{ "modelId": "gpt-5" }]
2166+
});
2167+
assert!(!super::model_in_catalog(
2168+
&config_options,
2169+
Some(&available),
2170+
"nonexistent-model"
2171+
));
2172+
}
2173+
2174+
#[test]
2175+
fn model_in_catalog_false_when_both_halves_empty() {
2176+
assert!(!super::model_in_catalog(&[], None, "anything"));
2177+
}
2178+
2179+
// ── Error variant display ─────────────────────────────────────────────
2180+
20902181
#[test]
20912182
fn idle_timeout_error_includes_duration() {
20922183
let err = AcpError::IdleTimeout(std::time::Duration::from_secs(320));

‎crates/buzz-acp/src/lib.rs‎

Lines changed: 100 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ use filter::SubscriptionRule;
2929
use futures_util::FutureExt;
3030
use nostr::{PublicKey, ToBech32};
3131
use pool::{
32-
AgentPool, ControlSignal, OwnedAgent, PromptContext, PromptOutcome, PromptResult, PromptSource,
33-
SessionState,
32+
AgentPool, ControlSignal, IdleSwitchResult, OwnedAgent, PromptContext, PromptOutcome,
33+
PromptResult, PromptSource, SessionState,
3434
};
3535
use queue::{CancelReason, EventQueue, QueuedEvent, ThreadTags};
3636
use relay::{HarnessRelay, RelayEventPublisher};
@@ -710,11 +710,25 @@ fn handle_relay_observer_control_event(
710710
};
711711

712712
let command_type = payload.get("type").and_then(|value| value.as_str());
713-
if command_type != Some("cancel_turn") {
714-
tracing::debug!(payload = %payload, "ignoring unknown observer control frame");
715-
return;
713+
match command_type {
714+
Some("cancel_turn") => {
715+
handle_cancel_turn_control(&payload, pool, observer);
716+
}
717+
Some("switch_model") => {
718+
handle_switch_model_control(&payload, pool, observer);
719+
}
720+
_ => {
721+
tracing::debug!(payload = %payload, "ignoring unknown observer control frame");
722+
}
716723
}
724+
}
717725

726+
/// Handle a `cancel_turn` control frame: signal the in-flight task to cancel.
727+
fn handle_cancel_turn_control(
728+
payload: &serde_json::Value,
729+
pool: &mut AgentPool,
730+
observer: Option<&observer::ObserverHandle>,
731+
) {
718732
let Some(channel_id) = payload
719733
.get("channelId")
720734
.and_then(|value| value.as_str())
@@ -743,6 +757,83 @@ fn handle_relay_observer_control_event(
743757
}
744758
}
745759

760+
/// Handle a `switch_model` control frame (Phase 3a, Option ii).
761+
///
762+
/// Busy path: deliver `SwitchModel` over the in-flight task's oneshot — the
763+
/// task cancels the turn, sets `desired_model`, and requeues the batch so it
764+
/// re-runs on a fresh session under the new model. A catalog miss surfaces
765+
/// post-cancel via `create_session_and_apply_model` (the turn restarts on the
766+
/// unchanged model + an `unsupported_model` result).
767+
///
768+
/// Idle path: validate against the cached catalog *before* invalidating
769+
/// (pre-cancel guard), then set `desired_model` + invalidate. The override
770+
/// takes visible effect on the agent's next turn.
771+
fn handle_switch_model_control(
772+
payload: &serde_json::Value,
773+
pool: &mut AgentPool,
774+
observer: Option<&observer::ObserverHandle>,
775+
) {
776+
let Some(channel_id) = payload
777+
.get("channelId")
778+
.and_then(|value| value.as_str())
779+
.and_then(|value| value.parse::<Uuid>().ok())
780+
else {
781+
tracing::warn!("observer switch_model control frame missing valid channelId");
782+
return;
783+
};
784+
let Some(model_id) = payload.get("modelId").and_then(|value| value.as_str()) else {
785+
tracing::warn!("observer switch_model control frame missing modelId");
786+
return;
787+
};
788+
789+
// A turn is in flight for this channel iff a task_map entry exists. The
790+
// agent is moved out of the pool during a turn, so the control oneshot is
791+
// the only reachable lever; an idle channel has no such entry.
792+
let turn_in_flight = pool
793+
.task_map()
794+
.values()
795+
.any(|m| m.channel_id == Some(channel_id));
796+
797+
let status = if turn_in_flight {
798+
// Busy path: deliver over the oneshot. `false` means the oneshot was
799+
// already consumed this turn (a prior cancel/interrupt) — the turn is
800+
// already ending, so the switch cannot land on it.
801+
if signal_in_flight_task(
802+
pool,
803+
channel_id,
804+
ControlSignal::SwitchModel(model_id.to_string()),
805+
) {
806+
"sent"
807+
} else {
808+
"turn_ending"
809+
}
810+
} else {
811+
// Idle path: validate against the cached catalog before invalidating.
812+
match pool.switch_idle_agent_model(channel_id, model_id) {
813+
IdleSwitchResult::Switched => "switched",
814+
IdleSwitchResult::UnsupportedModel => "unsupported_model",
815+
IdleSwitchResult::NoIdleAgent => "no_active_turn",
816+
}
817+
};
818+
819+
if let Some(observer) = observer {
820+
observer.emit(
821+
"control_result",
822+
None,
823+
&observer::ObserverContext {
824+
channel_id: Some(channel_id.to_string()),
825+
session_id: None,
826+
turn_id: None,
827+
},
828+
serde_json::json!({
829+
"type": "switch_model",
830+
"status": status,
831+
"modelId": model_id,
832+
}),
833+
);
834+
}
835+
}
836+
746837
/// Maximum crashes in a 60-second window before a slot's circuit opens.
747838
const CIRCUIT_BREAKER_THRESHOLD: usize = 3;
748839
/// Window for circuit-breaker crash counting.
@@ -1068,6 +1159,7 @@ async fn tokio_main() -> Result<()> {
10681159
state: SessionState::default(),
10691160
model_capabilities: None,
10701161
desired_model: config.model.clone(),
1162+
model_overridden: false,
10711163
protocol_version,
10721164
}));
10731165
}
@@ -1502,6 +1594,7 @@ async fn tokio_main() -> Result<()> {
15021594
state: SessionState::default(),
15031595
model_capabilities: None,
15041596
desired_model: config.model.clone(),
1597+
model_overridden: false,
15051598
protocol_version,
15061599
};
15071600
pool.return_agent(agent);
@@ -2351,8 +2444,8 @@ fn signal_in_flight_task(
23512444

23522445
if let Some(meta) = entry {
23532446
if let Some(tx) = meta.control_tx.take() {
2354-
let _ = tx.send(mode);
23552447
tracing::info!(channel = %channel_id, ?mode, "control signal sent to in-flight task");
2448+
let _ = tx.send(mode);
23562449
return true;
23572450
}
23582451
}
@@ -3867,6 +3960,7 @@ mod error_outcome_emission_tests {
38673960
state: Default::default(),
38683961
model_capabilities: None,
38693962
desired_model: None,
3963+
model_overridden: false,
38703964
// Error branches under test never read this; 1 is the legacy
38713965
// non-systemPrompt path, the simplest valid value.
38723966
protocol_version: 1,

0 commit comments

Comments
 (0)