foxfire-acp 0.1.4

Agent Client Protocol (ACP) client utilities and Aether protocol extensions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
mod activity;
mod items;
mod tool_calls;
mod turn;

pub use activity::Activity;
pub use items::{
    ConversationContent, ConversationId, ConversationItem, ConversationItemId, ItemState, Notice, NoticeLevel, Revision,
};
pub use tool_calls::{SubAgent, ToolCall, ToolStatus, diff_change_label};
pub use turn::{TurnFinished, TurnPhase};

use crate::aether::{AetherMeta, SubAgentMeta};
use crate::artifact::Artifact;
use crate::client::AcpEvent;
use agent_client_protocol::{schema::MaybeUndefined, v2::schema as acp};
use items::MessageRole;
use std::collections::{HashMap, HashSet};
use turn::WorkState;

/// One session's conversation items and state of the current turn.
#[derive(Debug, Clone, PartialEq)]
pub struct Conversation {
    session_id: acp::SessionId,
    id: ConversationId,
    revision: Revision,
    items: Vec<ConversationItem>,
    tool_index: HashMap<String, usize>,
    message_index: HashMap<acp::MessageId, usize>,
    next_item_id: u64,
    work: WorkState,
    activity: Activity,
    compactions: HashSet<acp::CompactionId>,
    context_usage: Option<acp::UsageUpdate>,
    plan: Option<acp::PlanItems>,
}

pub fn is_plan_entry_finished(status: &acp::PlanEntryStatus) -> bool {
    matches!(status, acp::PlanEntryStatus::Completed | acp::PlanEntryStatus::Cancelled)
}

impl Conversation {
    pub fn new(session_id: impl Into<acp::SessionId>) -> Self {
        Self {
            session_id: session_id.into(),
            id: ConversationId::default(),
            revision: Revision::default(),
            items: Vec::new(),
            tool_index: HashMap::new(),
            message_index: HashMap::new(),
            next_item_id: 0,
            work: WorkState::default(),
            activity: Activity::default(),
            compactions: HashSet::new(),
            context_usage: None,
            plan: None,
        }
    }

    pub fn apply_event(&mut self, event: &AcpEvent) -> Option<TurnFinished> {
        if let Some(session_id) = event.session_id()
            && *session_id != self.session_id
        {
            self.apply_sub_agent_event(session_id, event);
            return None;
        }
        match event {
            AcpEvent::SessionUpdate(notification) => return self.apply_update(&notification.update),
            AcpEvent::ContextCleared(_) => self.clear(),
            AcpEvent::ConnectionClosed => self.unconfirm(),
            AcpEvent::Artifact(payload) => self.show_artifact(&payload.artifact),
            AcpEvent::AuthStatusUpdated(_)
            | AcpEvent::McpNotification(_)
            | AcpEvent::GitDiffEvent(_)
            | AcpEvent::ChatChannelEvent(_)
            | AcpEvent::ElicitationRequest { .. }
            | AcpEvent::PermissionRequest { .. } => {}
        }
        None
    }

    pub fn clear(&mut self) {
        self.reset(self.session_id.clone());
    }

    pub fn reset(&mut self, session_id: impl Into<acp::SessionId>) {
        *self = Self { revision: self.revision, ..Self::new(session_id) };
        self.advance();
    }

    pub fn unconfirm_sub_agents(&mut self) {
        for index in 0..self.items.len() {
            if self.items[index].is_open() {
                self.update_tool(index, ToolCall::unconfirm_sub_agents);
            }
        }
    }

    pub fn append_notice(&mut self, level: NoticeLevel, text: impl Into<String>) -> ConversationItemId {
        self.push(ItemState::Sealed, ConversationContent::Notice(Notice { level, text: text.into() }))
    }

    pub fn session_id(&self) -> &acp::SessionId {
        &self.session_id
    }

    pub fn id(&self) -> ConversationId {
        self.id
    }

    pub fn revision(&self) -> Revision {
        self.revision
    }

    pub fn items(&self) -> &[ConversationItem] {
        &self.items
    }

    pub fn tracks(&self, session_id: &acp::SessionId) -> bool {
        *session_id == self.session_id || self.sub_agent_tool(session_id).is_some()
    }

    pub fn turn(&self) -> TurnPhase {
        self.work.phase()
    }

    pub fn activity(&self) -> Activity {
        if self.compactions.is_empty() { self.activity } else { Activity::Compacting }
    }

    pub fn plan(&self) -> Option<&acp::PlanItems> {
        self.plan.as_ref()
    }

    pub fn context_usage(&self) -> Option<&acp::UsageUpdate> {
        self.context_usage.as_ref()
    }

    pub fn any_running(&self) -> bool {
        self.items.iter().any(|item| match item.content() {
            ConversationContent::Tool(tool_call) => tool_call.is_running(),
            _ => false,
        })
    }

    fn seal(&mut self, status: ToolStatus) {
        if !self.work.is_idle() {
            self.work = WorkState::Idle(status);
        }
        self.compactions.clear();
        self.activity = Activity::Idle;
        let revision = self.advance();
        for item in self.items.iter_mut().filter(|item| item.is_open()) {
            if let ConversationContent::Tool(tool_call) = &mut item.content {
                if status == ToolStatus::Success && tool_call.runs_in_background() {
                    continue;
                }
                tool_call.finalize(status);
            }
            item.state = ItemState::Sealed;
            item.touch(revision, false);
        }
    }

    fn apply_update(&mut self, update: &acp::SessionUpdate) -> Option<TurnFinished> {
        let running = self.work == WorkState::Running;
        if matches!(update, acp::SessionUpdate::StateUpdate(acp::StateUpdate::Running(_))) && !running {
            self.begin_turn();
        } else if running && let Some(activity) = Activity::after(update) {
            self.set_activity(activity);
        }
        match update {
            acp::SessionUpdate::CompactionUpdate(update) => {
                if !self.work.is_idle() {
                    self.apply_compaction(update);
                }
            }
            acp::SessionUpdate::StateUpdate(acp::StateUpdate::Idle(idle)) if running => {
                return Some(self.finish_turn(idle.stop_reason.clone()));
            }
            acp::SessionUpdate::StateUpdate(acp::StateUpdate::Idle(idle)) => {
                self.settle(ToolStatus::from(idle.stop_reason.as_ref()));
            }
            acp::SessionUpdate::StateUpdate(acp::StateUpdate::Unknown(_)) => self.forget_work(),
            acp::SessionUpdate::UserMessage(message) => {
                self.upsert_message(MessageRole::User, &message.message_id, &message.content);
            }
            acp::SessionUpdate::AgentMessage(message) => {
                self.upsert_message(MessageRole::Assistant, &message.message_id, &message.content);
            }
            acp::SessionUpdate::AgentThought(message) => {
                self.upsert_message(MessageRole::Thought, &message.message_id, &message.content);
            }
            acp::SessionUpdate::SessionMessage(message) => {
                self.upsert_message(MessageRole::User, &message.message_id, &message.content);
            }
            acp::SessionUpdate::UserMessageChunk(chunk) => {
                self.append_message_chunk(MessageRole::User, &chunk.message_id, &chunk.content);
            }
            acp::SessionUpdate::AgentMessageChunk(chunk) => {
                self.append_message_chunk(MessageRole::Assistant, &chunk.message_id, &chunk.content);
            }
            acp::SessionUpdate::AgentThoughtChunk(chunk) => {
                self.append_message_chunk(MessageRole::Thought, &chunk.message_id, &chunk.content);
            }
            acp::SessionUpdate::SessionMessageChunk(chunk) => {
                self.append_message_chunk(MessageRole::User, &chunk.message_id, &chunk.content);
            }
            acp::SessionUpdate::ToolCallUpdate(update) => {
                let index = self.tool_slot(&update.tool_call_id);
                self.update_tool(index, |tool_call| tool_call.apply_update(update));
            }
            acp::SessionUpdate::ToolCallContentChunk(chunk) => {
                let index = self.tool_slot(&chunk.tool_call_id);
                self.update_tool(index, |tool_call| {
                    tool_call.append_content(chunk.content.clone());
                    true
                });
            }
            acp::SessionUpdate::PlanUpdate(update) => {
                if let acp::PlanUpdateContent::Items(items) = &update.plan
                    && self.plan.as_ref() != Some(items)
                {
                    self.plan = Some(items.clone());
                    self.advance();
                }
            }
            acp::SessionUpdate::UsageUpdate(usage) => self.update_usage(usage.clone()),
            acp::SessionUpdate::SubagentUpdate(update) => self.announce_sub_agent(update),
            _ => {}
        }
        None
    }

    fn update_usage(&mut self, mut usage: acp::UsageUpdate) {
        if usage.cost.is_undefined()
            && let Some(previous) = &self.context_usage
        {
            usage.cost = previous.cost.clone();
        }
        if self.context_usage.as_ref() != Some(&usage) {
            self.context_usage = Some(usage);
            self.advance();
        }
    }

    fn announce_sub_agent(&mut self, update: &acp::SubagentUpdate) {
        let spawning_tool = || {
            let tool_call_id = SubAgentMeta::from_meta(update.meta.value()).tool_call_id?;
            self.tool_index.get(tool_call_id.0.as_ref()).copied()
        };
        if let Some(index) = self.sub_agent_tool(&update.session_id).or_else(spawning_tool)
            && self.items[index].is_open()
        {
            self.update_tool(index, |tool_call| tool_call.announce_sub_agent(update));
        }
    }

    fn is_settled(&self) -> bool {
        self.work.is_idle()
            && self.items.iter().all(|item| match item.content() {
                ConversationContent::Tool(tool_call) => tool_call.is_settled(),
                _ => true,
            })
    }

    fn show_artifact(&mut self, artifact: &Artifact) {
        let shown = self.items.iter().position(
            |item| matches!(&item.content, ConversationContent::Artifact(shown) if shown.slot == artifact.slot),
        );
        let Some(index) = shown else {
            self.push(ItemState::Sealed, ConversationContent::Artifact(artifact.clone()));
            return;
        };
        let content = ConversationContent::Artifact(artifact.clone());
        if self.items[index].content != content {
            self.items[index].content = content;
            self.touch(index, true);
        }
    }

    fn apply_sub_agent_event(&mut self, session_id: &acp::SessionId, event: &AcpEvent) {
        if let Some(index) = self.sub_agent_tool(session_id)
            && self.items[index].is_open()
        {
            self.update_tool(index, |tool_call| tool_call.apply_sub_agent_event(session_id, event));
        }
    }

    fn sub_agent_tool(&self, session_id: &acp::SessionId) -> Option<usize> {
        self.items.iter().position(|item| match item.content() {
            ConversationContent::Tool(tool_call) => tool_call.tracks(session_id),
            _ => false,
        })
    }

    fn unconfirm(&mut self) {
        if self.work == WorkState::Running {
            self.forget_work();
        }
        self.unconfirm_sub_agents();
    }

    fn forget_work(&mut self) {
        if self.work != WorkState::Unconfirmed {
            self.work = WorkState::Unconfirmed;
            self.advance();
        }
        self.set_activity(Activity::Idle);
    }

    fn begin_turn(&mut self) {
        self.work = WorkState::Running;
        self.activity = Activity::Thinking;
        self.advance();
    }

    fn set_activity(&mut self, activity: Activity) {
        if self.activity != activity {
            self.activity = activity;
            self.advance();
        }
    }

    fn finish_turn(&mut self, stop_reason: Option<acp::StopReason>) -> TurnFinished {
        self.seal(ToolStatus::from(stop_reason.as_ref()));
        TurnFinished { stop_reason }
    }

    fn settle(&mut self, status: ToolStatus) {
        if status == ToolStatus::Cancelled && self.any_running() {
            self.seal(status);
        }
        if self.work != WorkState::Idle(status) {
            self.work = WorkState::Idle(status);
            self.advance();
        }
    }

    fn apply_compaction(&mut self, update: &acp::CompactionUpdate) {
        let changed = match update.status {
            acp::CompactionStatus::InProgress => self.compactions.insert(update.compaction_id.clone()),
            acp::CompactionStatus::Completed | acp::CompactionStatus::Failed | acp::CompactionStatus::Cancelled => {
                self.compactions.remove(&update.compaction_id)
            }
            _ => false,
        };
        if changed {
            self.advance();
        }
    }

    fn upsert_message(
        &mut self,
        role: MessageRole,
        message_id: &acp::MessageId,
        content: &MaybeUndefined<Vec<acp::ContentBlock>>,
    ) {
        let blocks = match content {
            MaybeUndefined::Value(blocks) => blocks.clone(),
            MaybeUndefined::Null if self.message_index.contains_key(message_id) => Vec::new(),
            MaybeUndefined::Null | MaybeUndefined::Undefined => return,
        };
        let index = self.message_slot(role, message_id.clone());
        let item = &mut self.items[index];
        let content = role.content(blocks);
        if item.content != content {
            item.content = content;
            self.touch(index, true);
        }
    }

    fn append_message_chunk(&mut self, role: MessageRole, message_id: &acp::MessageId, content: &acp::ContentBlock) {
        let index = self.message_slot(role, message_id.clone());
        let item = &mut self.items[index];
        let rewrites = !item.is_open() || role == MessageRole::User;
        if role.blocks_mut(&mut item.content).is_some_and(|blocks| items::append_block(blocks, content)) {
            self.touch(index, rewrites);
        }
    }

    fn message_slot(&mut self, role: MessageRole, message_id: acp::MessageId) -> usize {
        if let Some(&index) = self.message_index.get(&message_id) {
            return index;
        }
        let index = self.items.len();
        self.push(ItemState::Open, role.content(Vec::new()));
        self.items[index].message_id = Some(message_id.clone());
        self.message_index.insert(message_id, index);
        index
    }

    fn tool_slot(&mut self, id: &acp::ToolCallId) -> usize {
        if let Some(&index) = self.tool_index.get(id.0.as_ref()) {
            return index;
        }
        let index = self.items.len();
        self.push(
            ItemState::Open,
            ConversationContent::Tool(ToolCall::from_update(&acp::ToolCallUpdate::new(id.clone()))),
        );
        self.tool_index.insert(id.to_string(), index);
        index
    }

    fn push(&mut self, state: ItemState, content: ConversationContent) -> ConversationItemId {
        let id = ConversationItemId(self.next_item_id);
        self.next_item_id = self.next_item_id.saturating_add(1);
        let revision = self.advance();
        self.items.push(ConversationItem::new(id, revision, state, content));
        id
    }

    fn update_tool(&mut self, index: usize, apply: impl FnOnce(&mut ToolCall) -> bool) {
        let item = &mut self.items[index];
        let rewrites = !item.is_open();
        let ConversationContent::Tool(tool_call) = &mut item.content else {
            return;
        };
        if !apply(tool_call) {
            return;
        }
        item.state = if tool_call.rendering_final() { ItemState::Sealed } else { ItemState::Open };
        self.touch(index, rewrites);
    }

    fn touch(&mut self, index: usize, rewrites: bool) {
        let revision = self.advance();
        self.items[index].touch(revision, rewrites);
    }

    fn advance(&mut self) -> Revision {
        self.revision.advance()
    }
}