-
Notifications
You must be signed in to change notification settings - Fork 11
Decaf debouncer #119
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nikomatsakis
wants to merge
4
commits into
agentclientprotocol:main
Choose a base branch
from
nikomatsakis:decaf-debouncer
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+460
−0
Open
Decaf debouncer #119
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
ea41aca
feat: add decaf crate - debouncing proxy for ACP
nikomatsakis 2478e44
feat(decaf): flush on prompt response and add integration test
nikomatsakis f685abb
chore(decaf): add keywords and categories for crates.io
nikomatsakis 76816a7
chore(decaf): set version to 1.0.0-alpha.1
nikomatsakis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,6 +10,7 @@ members = [ | |
| "src/sacp-test", | ||
| "src/yopo", | ||
| "src/sacp-trace-viewer", | ||
| "src/decaf", | ||
| ] | ||
| resolver = "2" | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| [package] | ||
| name = "decaf" | ||
| version = "1.0.0-alpha.1" | ||
| edition = "2024" | ||
| description = "Debouncing proxy for ACP - coalesces agent message chunks" | ||
| license = "MIT OR Apache-2.0" | ||
| repository = "https://github.com/symposium-dev/symposium-acp" | ||
| keywords = ["acp", "agent", "proxy", "debounce"] | ||
| categories = ["development-tools"] | ||
|
|
||
| [dependencies] | ||
| sacp = { version = "11.0.0-alpha.1", path = "../sacp" } | ||
| tokio.workspace = true | ||
| tracing.workspace = true | ||
|
|
||
| [dev-dependencies] | ||
| futures.workspace = true | ||
| sacp-conductor = { path = "../sacp-conductor" } | ||
| sacp-test = { path = "../sacp-test" } | ||
| tokio-util.workspace = true | ||
| tracing-subscriber.workspace = true |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,198 @@ | ||
| //! Debouncing proxy for ACP. | ||
| //! | ||
| //! Agents often send `AgentMessageChunk` notifications word-by-word, | ||
| //! creating a flood of tiny messages. Decaf coalesces these chunks, | ||
| //! forwarding a single combined chunk every N milliseconds instead. | ||
| //! | ||
| //! # Usage | ||
| //! | ||
| //! ```no_run | ||
| //! # use decaf::Decaf; | ||
| //! # use sacp::{Proxy, ConnectTo}; | ||
| //! # use std::time::Duration; | ||
| //! # async fn example(transport: impl ConnectTo<Proxy> + 'static) -> Result<(), sacp::Error> { | ||
| //! Decaf::new(Duration::from_millis(100)) | ||
| //! .run(transport) | ||
| //! .await?; | ||
| //! # Ok(()) | ||
| //! # } | ||
| //! ``` | ||
|
|
||
| use std::collections::HashMap; | ||
| use std::sync::Arc; | ||
| use std::time::Duration; | ||
|
|
||
| use sacp::schema::{ | ||
| ContentBlock, ContentChunk, PromptRequest, SessionId, SessionNotification, SessionUpdate, | ||
| }; | ||
| use sacp::util::MatchDispatch; | ||
| use sacp::{Agent, Client, Conductor, ConnectTo, Dispatch, Proxy}; | ||
| use tokio::sync::Mutex; | ||
|
|
||
| /// A debouncing proxy that coalesces `AgentMessageChunk` notifications. | ||
| /// | ||
| /// Instead of forwarding every individual chunk, Decaf buffers text | ||
| /// and flushes it at a configurable interval. | ||
| pub struct Decaf { | ||
| interval: Duration, | ||
| } | ||
|
|
||
| struct BufferedSession { | ||
| /// Accumulated text chunks. | ||
| text: String, | ||
|
|
||
| /// The most recent notification, used as a template when flushing | ||
| /// (preserves session_id, meta, annotations, etc). | ||
| template: SessionNotification, | ||
| } | ||
|
|
||
| type State = Arc<Mutex<HashMap<SessionId, BufferedSession>>>; | ||
|
|
||
| impl Decaf { | ||
| pub fn new(interval: Duration) -> Self { | ||
| Decaf { interval } | ||
| } | ||
|
|
||
| pub async fn run(self, transport: impl ConnectTo<Proxy> + 'static) -> Result<(), sacp::Error> { | ||
| let state: State = Arc::new(Mutex::new(HashMap::new())); | ||
| let interval = self.interval; | ||
|
|
||
| Proxy | ||
| .builder() | ||
| .name("decaf") | ||
| .on_receive_dispatch_from( | ||
| Agent, | ||
| { | ||
| let state = state.clone(); | ||
| async move |dispatch: Dispatch, cx| { | ||
| MatchDispatch::new(dispatch) | ||
| .if_notification(async |notification: SessionNotification| { | ||
| let is_text_chunk = matches!( | ||
| ¬ification.update, | ||
| SessionUpdate::AgentMessageChunk(ContentChunk { | ||
| content: ContentBlock::Text(_), | ||
| .. | ||
| }) | ||
| ); | ||
|
|
||
| if is_text_chunk { | ||
| // Buffer the text chunk | ||
| let mut sessions = state.lock().await; | ||
| let text = match ¬ification.update { | ||
| SessionUpdate::AgentMessageChunk(ContentChunk { | ||
| content: ContentBlock::Text(tc), | ||
| .. | ||
| }) => tc.text.clone(), | ||
| _ => unreachable!(), | ||
| }; | ||
|
|
||
| match sessions.get_mut(¬ification.session_id) { | ||
| Some(buffered) => { | ||
| buffered.text.push_str(&text); | ||
| buffered.template = notification; | ||
| } | ||
| None => { | ||
| sessions.insert( | ||
| notification.session_id.clone(), | ||
| BufferedSession { | ||
| text, | ||
| template: notification, | ||
| }, | ||
| ); | ||
| } | ||
| } | ||
| } else { | ||
| // Non-chunk message: flush buffer first, then forward | ||
| flush_session(&state, ¬ification.session_id, &cx).await?; | ||
| cx.send_notification_to(Client, notification)?; | ||
| } | ||
|
|
||
| Ok(()) | ||
| }) | ||
| .await | ||
| .if_response_to::<PromptRequest, _>(async |result, router| { | ||
| // Flush any remaining buffered text before | ||
| // the prompt response reaches the client. | ||
| flush_all(&state, &cx).await?; | ||
| router.respond_with_result(result) | ||
| }) | ||
| .await | ||
| .done() | ||
| } | ||
| }, | ||
| sacp::on_receive_dispatch!(), | ||
| ) | ||
| .with_spawned({ | ||
| let state = state.clone(); | ||
| move |cx| async move { | ||
| let mut ticker = tokio::time::interval(interval); | ||
| loop { | ||
| ticker.tick().await; | ||
| flush_all(&state, &cx).await?; | ||
| } | ||
| } | ||
| }) | ||
| .connect_to(transport) | ||
| .await | ||
| } | ||
| } | ||
|
|
||
| impl ConnectTo<Conductor> for Decaf { | ||
| async fn connect_to(self, transport: impl ConnectTo<Proxy>) -> Result<(), sacp::Error> { | ||
| self.run(transport).await | ||
| } | ||
| } | ||
|
|
||
| /// Flush a single session's buffer, sending a coalesced chunk to the client. | ||
| async fn flush_session( | ||
| state: &State, | ||
| session_id: &SessionId, | ||
| cx: &sacp::ConnectionTo<Conductor>, | ||
| ) -> Result<(), sacp::Error> { | ||
| let flushed = { | ||
| let mut sessions = state.lock().await; | ||
| match sessions.get_mut(session_id) { | ||
| Some(buffered) if !buffered.text.is_empty() => { | ||
| let text = std::mem::take(&mut buffered.text); | ||
| let mut notification = buffered.template.clone(); | ||
|
|
||
| // Replace the text content with the coalesced text | ||
| if let SessionUpdate::AgentMessageChunk(ContentChunk { | ||
| content: ContentBlock::Text(tc), | ||
| .. | ||
| }) = &mut notification.update | ||
| { | ||
| tc.text = text; | ||
| } | ||
|
|
||
| Some(notification) | ||
| } | ||
| _ => None, | ||
| } | ||
| }; | ||
|
|
||
| if let Some(notification) = flushed { | ||
| cx.send_notification_to(Client, notification)?; | ||
| } | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| /// Flush all sessions that have buffered data. | ||
| async fn flush_all(state: &State, cx: &sacp::ConnectionTo<Conductor>) -> Result<(), sacp::Error> { | ||
| // Collect session IDs that need flushing while holding the lock briefly | ||
| let session_ids: Vec<SessionId> = { | ||
| let sessions = state.lock().await; | ||
| sessions | ||
| .iter() | ||
| .filter(|(_, b)| !b.text.is_empty()) | ||
| .map(|(id, _)| id.clone()) | ||
| .collect() | ||
| }; | ||
|
|
||
| for session_id in session_ids { | ||
| flush_session(state, &session_id, cx).await?; | ||
| } | ||
|
|
||
| Ok(()) | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I guess we should really just
flush_sessionhereThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
But I'm not sure how easy that is to do, I don't think we have ready access to the session-id
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, sort of missing the initial request data.