1mod materialize;
4mod observation;
5mod session_update;
6mod terminals;
7pub use materialize::*;
8pub use observation::*;
9use session_update::*;
10use terminals::*;
11
12mod api_events;
13
14use std::collections::{BTreeMap, BTreeSet, HashMap};
15use std::sync::Arc;
16
17use agent_client_protocol::schema::{
18 MaybeUndefined,
19 v1::{
20 ContentBlock, ContentChunk, Plan, PlanEntry, PlanEntryPriority, PlanEntryStatus,
21 SessionUpdate, TextContent, ToolCall, ToolCallContent, ToolCallStatus,
22 ToolCallUpdateFields,
23 },
24};
25use anyhow::{Context, Result, bail};
26use serde::Deserialize;
27use serde_json::Value;
28use sha2::{Digest, Sha256};
29
30use crate::transcript::{ChatEntry, ChatRole, PlanStatus, ToolStatus, tool_call_presentation};
31use mj_core::archive::{
32 CanonicalExecutionState, CanonicalQueuedCommandKind, CanonicalQueuedPrompt,
33 CanonicalSessionSnapshot, CanonicalSessionState, CanonicalTerminalOutput,
34 CanonicalTranscriptBody, CanonicalTranscriptItem,
35};
36use mj_core::relay::{
37 RELAY_EVENT_GENESIS_DIGEST, RelayCommand, RelayCommandKind, RelayEvent, RelayObservation,
38 SequencedEvent, WorkerEvent, WorkerPhase, validate_relay_event,
39};
40use mj_core::state::{
41 MaterializedExecutionState, MaterializedQueuedPrompt, MaterializedSession, MaterializedTurn,
42 MaterializedTurnOutcome, QueuedCommandKind, TerminalOutputRecord, TranscriptBody,
43 TranscriptItem, TurnOutcomeKind, config_command_text, normalize_session_title,
44 provisional_session_title,
45};
46use mj_core::storage::{MaterializedSessionMutation, ProjectionIntegrityError, TranscriptMutation};
47use mj_core::transcript::{coalesce_content_chunks, push_content_chunk};
48
49#[derive(Debug, Clone, PartialEq)]
50pub struct ProjectedRelayEvent {
51 pub mutation: MaterializedSessionMutation,
52}
53
54#[derive(Debug, Clone)]
59pub struct ProjectionIndex {
60 transcript: HashMap<String, Arc<TranscriptItem>>,
61 transcript_positions: HashMap<String, usize>,
62 open_agent_streams: BTreeSet<(u64, String)>,
63 open_thought_streams: BTreeSet<(u64, String)>,
64 terminal_referrers: HashMap<String, BTreeSet<String>>,
65}
66
67pub fn historical_references(events: &[RelayEvent]) -> Result<(Vec<String>, Vec<String>)> {
70 let mut ids = BTreeSet::new();
71 let mut terminals = BTreeSet::new();
72 for event in events {
73 match &event.observation {
74 RelayObservation::SessionUpdate { update } => {
75 let value = match update.as_ref() {
76 SessionUpdate::ToolCall(call) => {
77 ids.insert(format!("tool:{}", call.tool_call_id));
78 Some(serde_json::to_value(call)?)
79 }
80 SessionUpdate::ToolCallUpdate(update) => {
81 ids.insert(format!("tool:{}", update.tool_call_id));
82 Some(serde_json::to_value(&update.fields)?)
83 }
84 SessionUpdate::AgentMessageChunk(chunk) => {
85 if let Some(id) = &chunk.message_id {
86 ids.insert(format!("agent:{id}"));
87 }
88 None
89 }
90 SessionUpdate::AgentThoughtChunk(chunk) => {
91 if let Some(id) = &chunk.message_id {
92 ids.insert(format!("thought:{id}"));
93 }
94 None
95 }
96 _ => None,
97 };
98 if let Some(value) = value {
99 terminals.extend(tool_call_terminal_ids(&value));
100 }
101 }
102 RelayObservation::TerminalOutput { terminal_id, .. } => {
103 terminals.insert(terminal_id.clone());
104 }
105 RelayObservation::CommandStarted { command_id, .. }
106 | RelayObservation::CommandCompleted { command_id, .. }
107 | RelayObservation::CommandRejected { command_id, .. }
108 | RelayObservation::CommandInterrupted { command_id, .. }
109 | RelayObservation::UserShellOutput { command_id, .. } => {
110 ids.insert(user_shell_item_id(command_id));
111 ids.insert(format!("user:{command_id}"));
112 }
113 RelayObservation::Notice { .. } => {
114 if let Some(id) = &event.command_id {
115 ids.insert(format!("system:notice:{id}"));
116 }
117 }
118 RelayObservation::MailboxEventsDelivered {
119 event_keys,
120 events,
121 steering,
122 ..
123 } => {
124 ids.extend(
125 event_keys
126 .iter()
127 .chain(events.iter().map(|event| &event.key))
128 .map(|key| mj_core::transcript::message_item_id(key)),
129 );
130 ids.extend(observation::external_events_item_id(events));
131 if let Some(steering) = steering {
132 ids.insert(format!("user:{}", steering.queued_prompt_id));
133 ids.insert(format!("user:{}", steering.command_id));
134 }
135 }
136 RelayObservation::CommandQueued {
137 command: RelayCommand::MailboxWake { events },
138 ..
139 } => {
140 ids.extend(
141 events
142 .iter()
143 .map(|event| mj_core::transcript::message_item_id(&event.key)),
144 );
145 ids.extend(observation::external_events_item_id(events));
146 }
147 _ => {}
148 }
149 }
150 for terminal in &terminals {
151 ids.insert(terminal_item_id(terminal));
152 ids.insert(fallback_terminal_tool_item_id(terminal));
153 }
154 Ok((ids.into_iter().collect(), terminals.into_iter().collect()))
155}
156
157impl ProjectionIndex {
158 pub fn new(current: &MaterializedSession) -> Self {
159 let mut index = Self {
160 transcript: HashMap::with_capacity(current.transcript.len()),
161 transcript_positions: HashMap::with_capacity(current.transcript.len()),
162 open_agent_streams: BTreeSet::new(),
163 open_thought_streams: BTreeSet::new(),
164 terminal_referrers: HashMap::new(),
165 };
166 for (position, item) in current.transcript.iter().enumerate() {
167 index.insert_at(item.clone(), position);
168 }
169 index
170 }
171
172 fn get(&self, stable_id: &str) -> Option<&Arc<TranscriptItem>> {
173 self.transcript.get(stable_id)
174 }
175
176 fn position(&self, stable_id: &str) -> Option<usize> {
177 self.transcript_positions.get(stable_id).copied()
178 }
179
180 fn insert(&mut self, item: Arc<TranscriptItem>) {
181 let position = self
182 .remove(&item.stable_id)
183 .unwrap_or(self.transcript.len());
184 self.insert_at(item, position);
185 }
186
187 fn insert_at(&mut self, item: Arc<TranscriptItem>, position: usize) {
188 let stream = (item.position, item.stable_id.clone());
189 match &item.body {
190 TranscriptBody::Agent {
191 streaming: true, ..
192 } => {
193 self.open_agent_streams.insert(stream);
194 }
195 TranscriptBody::Thought {
196 streaming: true, ..
197 } => {
198 self.open_thought_streams.insert(stream);
199 }
200 TranscriptBody::Tool {
201 call,
202 terminal_refs,
203 ..
204 } => {
205 let mut terminal_ids = tool_call_terminal_ids(call);
206 terminal_ids.extend(terminal_refs.iter().cloned());
207 for terminal_id in terminal_ids {
208 self.terminal_referrers
209 .entry(terminal_id)
210 .or_default()
211 .insert(item.stable_id.clone());
212 }
213 }
214 _ => {}
215 }
216 self.transcript_positions
217 .insert(item.stable_id.clone(), position);
218 self.transcript.insert(item.stable_id.clone(), item);
219 }
220
221 fn remove(&mut self, stable_id: &str) -> Option<usize> {
222 let item = self.transcript.remove(stable_id)?;
223 let position = self.transcript_positions.remove(stable_id);
224 debug_assert!(position.is_some());
225 let stream = (item.position, item.stable_id.clone());
226 self.open_agent_streams.remove(&stream);
227 self.open_thought_streams.remove(&stream);
228 if let TranscriptBody::Tool {
229 call,
230 terminal_refs,
231 ..
232 } = &item.body
233 {
234 let mut terminal_ids = tool_call_terminal_ids(call);
235 terminal_ids.extend(terminal_refs.iter().cloned());
236 for terminal_id in terminal_ids {
237 if let Some(referrers) = self.terminal_referrers.get_mut(&terminal_id) {
238 referrers.remove(stable_id);
239 if referrers.is_empty() {
240 self.terminal_referrers.remove(&terminal_id);
241 }
242 }
243 }
244 }
245 position
246 }
247
248 fn reindex_after_removal(&mut self, transcript: &[Arc<TranscriptItem>], removed: usize) {
249 for (position, item) in transcript.iter().enumerate().skip(removed) {
250 self.transcript_positions
251 .insert(item.stable_id.clone(), position);
252 }
253 }
254
255 fn latest_open_stream(&self, agent: bool) -> Option<&Arc<TranscriptItem>> {
256 let streams = if agent {
257 &self.open_agent_streams
258 } else {
259 &self.open_thought_streams
260 };
261 streams
262 .last()
263 .and_then(|(_, stable_id)| self.transcript.get(stable_id))
264 }
265
266 fn open_streams(&self, agent: bool) -> impl Iterator<Item = &Arc<TranscriptItem>> {
267 let streams = if agent {
268 &self.open_agent_streams
269 } else {
270 &self.open_thought_streams
271 };
272 streams
273 .iter()
274 .filter_map(|(_, stable_id)| self.transcript.get(stable_id))
275 }
276
277 fn terminal_referrers(&self, terminal_id: &str) -> impl Iterator<Item = &Arc<TranscriptItem>> {
278 self.terminal_referrers
279 .get(terminal_id)
280 .into_iter()
281 .flatten()
282 .filter_map(|stable_id| self.transcript.get(stable_id))
283 }
284}
285
286pub fn project_relay_event(
290 current: &MaterializedSession,
291 event: &RelayEvent,
292) -> Result<ProjectedRelayEvent> {
293 let index = ProjectionIndex::new(current);
294 project_relay_event_indexed(current, &index, event)
295}
296
297pub fn project_relay_event_indexed(
298 current: &MaterializedSession,
299 index: &ProjectionIndex,
300 event: &RelayEvent,
301) -> Result<ProjectedRelayEvent> {
302 validate_relay_event(
303 current.applied_event_ordinal,
304 ¤t.applied_event_digest,
305 event,
306 )?;
307
308 let mut mutation = MaterializedSessionMutation {
309 last_activity_at_ms: Some(event.recorded_at_ms),
310 ..MaterializedSessionMutation::default()
311 };
312 project_observation(current, index, event, &mut mutation)?;
313 mutation.api_events = api_events::derive(current, event, &mutation);
314 Ok(ProjectedRelayEvent { mutation })
315}
316
317pub fn apply_committed_projection_event(
322 current: &mut MaterializedSession,
323 event: &RelayEvent,
324 mutation: MaterializedSessionMutation,
325) -> Result<()> {
326 apply_committed_projection_event_inner(current, event, mutation, None)
327}
328
329pub fn apply_committed_projection_event_indexed(
330 current: &mut MaterializedSession,
331 index: &mut ProjectionIndex,
332 event: &RelayEvent,
333 mutation: MaterializedSessionMutation,
334) -> Result<()> {
335 apply_committed_projection_event_inner(current, event, mutation, Some(index))
336}
337
338fn apply_committed_projection_event_inner(
339 current: &mut MaterializedSession,
340 event: &RelayEvent,
341 mutation: MaterializedSessionMutation,
342 mut index: Option<&mut ProjectionIndex>,
343) -> Result<()> {
344 validate_relay_event(
345 current.applied_event_ordinal,
346 ¤t.applied_event_digest,
347 event,
348 )?;
349 if let Some(execution) = mutation.execution {
350 current.execution = execution;
351 }
352 if let Some(title) = mutation.session_title {
353 current.session_title = title;
354 }
355 if let Some(configuration) = mutation.configuration {
356 current.configuration = configuration;
357 }
358 for item_mutation in mutation.transcript {
359 match item_mutation {
360 TranscriptMutation::Upsert(item) => {
361 item.validate(event.ordinal)?;
362 let existing_position = index
363 .as_deref()
364 .and_then(|index| index.position(&item.stable_id));
365 let existing = if let Some(position) = existing_position {
366 Some(current.transcript.get_mut(position).with_context(|| {
367 format!(
368 "transcript index position {position} for {:?} is out of bounds",
369 item.stable_id
370 )
371 })?)
372 } else if index.is_none() {
373 current
374 .transcript
375 .iter_mut()
376 .find(|existing| existing.stable_id == item.stable_id)
377 } else {
378 None
379 };
380 if let Some(existing) = existing {
381 if existing.stable_id != item.stable_id {
382 return Err(ProjectionIntegrityError(format!(
383 "transcript index for {:?} points to {:?}",
384 item.stable_id, existing.stable_id
385 ))
386 .into());
387 }
388 if existing.position != item.position
389 || existing.created_at_ms != item.created_at_ms
390 {
391 return Err(ProjectionIntegrityError(format!(
392 "transcript item {:?} changed immutable identity fields",
393 item.stable_id
394 ))
395 .into());
396 }
397 if item.last_changed_at_ms < existing.last_changed_at_ms {
398 return Err(ProjectionIntegrityError(format!(
399 "transcript item {:?} moved its changed timestamp backwards",
400 item.stable_id
401 ))
402 .into());
403 }
404 if existing
405 .latest_content_event_ordinal
406 .is_some_and(|existing| {
407 item.latest_content_event_ordinal
408 .is_none_or(|next| next < existing)
409 })
410 {
411 return Err(ProjectionIntegrityError(format!(
412 "transcript item {:?} moved its latest content ordinal backwards",
413 item.stable_id
414 ))
415 .into());
416 }
417 if let Some(owned) = Arc::get_mut(existing) {
421 *owned = item;
422 } else {
423 *existing = Arc::new(item);
424 }
425 if let Some(index) = index.as_deref_mut() {
426 index.insert(existing.clone());
427 }
428 } else {
429 let item = Arc::new(item);
430 if let Some(index) = index.as_deref_mut() {
431 index.insert(item.clone());
432 }
433 current.transcript.push(item);
434 }
435 }
436 TranscriptMutation::Remove { stable_id } => {
437 if let Some(index) = index.as_deref_mut() {
438 if let Some(position) = index.remove(&stable_id) {
439 let removed = current.transcript.remove(position);
440 if removed.stable_id != stable_id {
441 return Err(ProjectionIntegrityError(format!(
442 "transcript index for {stable_id:?} removed {:?}",
443 removed.stable_id
444 ))
445 .into());
446 }
447 index.reindex_after_removal(¤t.transcript, position);
448 }
449 } else {
450 current
451 .transcript
452 .retain(|item| item.stable_id != stable_id);
453 }
454 }
455 }
456 }
457 if let Some(queued_prompts) = mutation.queued_prompts {
458 current.queued_prompts = queued_prompts;
459 }
460 if let Some(pending_elicitations) = mutation.pending_elicitations {
461 current.pending_elicitations = pending_elicitations;
462 }
463 if let Some(active_turn) = mutation.active_turn {
464 current.active_turn = active_turn;
465 }
466 if mutation.clear_turn_outcome {
467 current.last_turn_outcome = None;
468 }
469 if let Some(last_turn_outcome) = mutation.last_turn_outcome {
470 current.last_turn_outcome = Some(last_turn_outcome);
471 }
472 if let Some(activity) = mutation.last_activity_at_ms {
473 current.last_activity_at_ms = Some(
474 current
475 .last_activity_at_ms
476 .map_or(activity, |existing| existing.max(activity)),
477 );
478 }
479 current.applied_event_ordinal = event.ordinal;
480 current.applied_event_digest.clone_from(&event.digest);
481 Ok(())
482}
483
484#[cfg(test)]
485mod tests;
486
487pub fn project_native_update(
491 current: &MaterializedSession,
492 event: &RelayEvent,
493 update: &agent_client_protocol::schema::v1::SessionUpdate,
494) -> Result<MaterializedSessionMutation> {
495 let mut mutation = MaterializedSessionMutation {
496 last_activity_at_ms: Some(event.recorded_at_ms),
497 ..Default::default()
498 };
499 if let agent_client_protocol::schema::v1::SessionUpdate::UserMessageChunk(chunk) = update {
500 mutation
501 .transcript
502 .push(TranscriptMutation::Upsert(TranscriptItem {
503 stable_id: format!("native-user:{}", event.ordinal),
504 position: event.ordinal,
505 latest_content_event_ordinal: None,
506 created_at_ms: event.recorded_at_ms,
507 last_changed_at_ms: event.recorded_at_ms,
508 body: TranscriptBody::User {
509 content: vec![serde_json::to_value(&chunk.content)?],
510 },
511 }));
512 return Ok(mutation);
513 }
514 let index = ProjectionIndex::new(current);
515 session_update::project_session_update(current, &index, event, update, &mut mutation)?;
516 Ok(mutation)
517}
518
519pub(crate) use terminals::tool_call_terminal_ids;