返回 CodeWhale
mailbox.rs
根目录 / crates / engine / src / tools / subagent / mailbox.rs
1 //! Mailbox abstraction for sub-agent runtime coordination.
2 //!
3 //! Monotonic sequence numbers give every consumer a consistent ordering even
4 //! when multiple subscribers (e.g. UI card + parent agent) drain
5 //! independently; close-as-cancel lets a single signal both stop new mail and
6 //! propagate cancellation through nested children.
7
8 use std::collections::VecDeque;
9 use std::sync::Arc;
10 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
11 #[cfg(any(test, feature = "test-support"))]
12 use std::time::Duration;
13
14 use serde::{Deserialize, Serialize};
15 use tokio::sync::{mpsc, watch};
16 use tokio_util::sync::CancellationToken;
17
18 use crate::tools::todo::TodoListSnapshot;
19 #[cfg(test)]
20 use codewhale_config::ProviderKind;
21 use codewhale_models::Usage;
22
23 use codewhale_agent_contract::role::FleetRole;
24
25 /// Stable, structured progress envelope shared across the sub-agent surface.
26 ///
27 /// Tracks the lifecycle of a single agent (identified by `agent_id`) end to
28 /// end: spawn, per-step progress, tool execution, completion / failure /
29 /// cancellation, and parent → child topology so consumers can render trees.
30 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31 #[serde(tag = "kind", rename_all = "snake_case")]
32 pub enum MailboxMessage {
33 /// Agent has been started (background task is running).
34 Started {
35 agent_id: String,
36 agent_type: String,
37 },
38 /// Free-form human-readable progress (mirrors `Event::AgentProgress`).
39 Progress { agent_id: String, status: String },
40 /// A tool call inside the agent has started.
41 ToolCallStarted {
42 agent_id: String,
43 tool_name: String,
44 step: u32,
45 },
46 /// A tool call inside the agent has finished.
47 ToolCallCompleted {
48 agent_id: String,
49 tool_name: String,
50 step: u32,
51 ok: bool,
52 },
53 /// A child agent was spawned by this agent.
54 ChildSpawned { parent_id: String, child_id: String },
55 /// Agent completed successfully (carries the summary line shown in the
56 /// transcript; full result is still available through the transcript handle).
57 Completed { agent_id: String, summary: String },
58 /// Agent failed with the carried error message.
59 Failed { agent_id: String, error: String },
60 /// Agent stopped at an own or shared token, step, or wall-time budget.
61 BudgetExhausted { agent_id: String, summary: String },
62 /// Agent was interrupted (e.g. API timeout) with a continuable
63 /// checkpoint; the worker is parked waiting for continuation input.
64 Interrupted { agent_id: String, reason: String },
65 /// Cancellation propagated to this agent.
66 Cancelled { agent_id: String },
67 /// This agent's **own** bounded To-do snapshot (#4810).
68 ///
69 /// Published by the agent that owns the ledger, from its private list, so a
70 /// consumer keyed on `agent_id` can never attribute a parent's or a
71 /// sibling's work to this agent. Emitted only when the snapshot actually
72 /// changes; the payload is the canonical [`TodoListSnapshot`], not a second
73 /// ledger.
74 WorkState {
75 agent_id: String,
76 /// Absent in older persisted payloads, which predate per-agent Work
77 /// state; those deserialize to an empty (no work stated) snapshot.
78 #[serde(default)]
79 todo: TodoListSnapshot,
80 },
81 FileWrites {
82 agent_id: String,
83 #[serde(default)]
84 turn_seq: u64,
85 paths: Vec<String>,
86 },
87 /// Incremental token usage from a sub-agent's API call.
88 /// Published after each turn so the parent's cost counter updates live.
89 TokenUsage {
90 #[serde(default, skip_serializing_if = "Option::is_none")]
91 record: Option<Box<crate::cost_status::RuntimeUsageRecord>>,
92 agent_id: String,
93 /// Stable identity of the provider response. Runtime accounting uses
94 /// this across direct durability, mailbox replay, and restart dedupe.
95 source_id: String,
96 /// Immutable provider/model/billing evidence captured before the
97 /// child request was sent. Boxed: the envelope dwarfs every other
98 /// variant, and mailboxes queue many messages.
99 route: Box<crate::cost_status::EffectiveRouteEnvelope>,
100 /// Provider usage payload, including cache-hit/cache-miss fields.
101 usage: Usage,
102 },
103 }
104
105 impl MailboxMessage {
106 /// `agent_id` of the message subject (for `ChildSpawned` this is the
107 /// child, since that's the new lifecycle being announced).
108 #[must_use]
109 pub fn agent_id(&self) -> &str {
110 match self {
111 Self::Started { agent_id, .. }
112 | Self::Progress { agent_id, .. }
113 | Self::ToolCallStarted { agent_id, .. }
114 | Self::ToolCallCompleted { agent_id, .. }
115 | Self::FileWrites { agent_id, .. }
116 | Self::Completed { agent_id, .. }
117 | Self::Failed { agent_id, .. }
118 | Self::BudgetExhausted { agent_id, .. }
119 | Self::Interrupted { agent_id, .. }
120 | Self::Cancelled { agent_id }
121 | Self::WorkState { agent_id, .. }
122 | Self::TokenUsage { agent_id, .. } => agent_id,
123 Self::ChildSpawned { child_id, .. } => child_id,
124 }
125 }
126
127 pub fn started(agent_id: impl Into<String>, agent_type: FleetRole) -> Self {
128 Self::Started {
129 agent_id: agent_id.into(),
130 agent_type: agent_type.as_str().to_string(),
131 }
132 }
133
134 pub fn progress(agent_id: impl Into<String>, status: impl Into<String>) -> Self {
135 Self::Progress {
136 agent_id: agent_id.into(),
137 status: status.into(),
138 }
139 }
140
141 #[cfg(any(test, feature = "test-support"))]
142 pub fn work_state(agent_id: impl Into<String>, todo: TodoListSnapshot) -> Self {
143 Self::WorkState {
144 agent_id: agent_id.into(),
145 todo,
146 }
147 }
148
149 pub fn usage_record(
150 agent_id: impl Into<String>,
151 record: crate::cost_status::RuntimeUsageRecord,
152 ) -> Self {
153 Self::TokenUsage {
154 agent_id: agent_id.into(),
155 source_id: record.source_id.clone(),
156 route: Box::new(record.usage.route.clone()),
157 usage: record.usage.usage.clone(),
158 record: Some(Box::new(record)),
159 }
160 }
161
162 pub fn token_usage(
163 agent_id: impl Into<String>,
164 source_id: impl Into<String>,
165 route: crate::cost_status::EffectiveRouteEnvelope,
166 usage: Usage,
167 ) -> Self {
168 Self::TokenUsage {
169 record: None,
170 agent_id: agent_id.into(),
171 source_id: source_id.into(),
172 route: Box::new(route),
173 usage,
174 }
175 }
176 }
177
178 /// One delivery: a sequence number plus the message. The sequence is
179 /// monotonic across the entire mailbox (not per-agent) so a single ordering
180 /// is well-defined even when multiple sub-agents share one mailbox.
181 #[derive(Debug, Clone, PartialEq, Eq)]
182 pub struct MailboxEnvelope {
183 pub seq: u64,
184 pub message: MailboxMessage,
185 }
186
187 /// Sender side of the mailbox.
188 ///
189 /// Cheaply cloneable (everything inside is `Arc`/atomic). Cloning a
190 /// `Mailbox` shares the same delivery channel, sequence counter, watch
191 /// notifier, and close/cancel state — so a child runtime that clones its
192 /// parent's `Mailbox` participates in the same stream.
193 #[derive(Clone)]
194 pub struct Mailbox {
195 inner: Arc<MailboxInner>,
196 }
197
198 struct MailboxInner {
199 tx: mpsc::UnboundedSender<MailboxEnvelope>,
200 next_seq: AtomicU64,
201 seq_tx: watch::Sender<u64>,
202 closed: AtomicBool,
203 /// Linearizes publication against turn-end sealing. Without this gate a
204 /// producer could observe `closed = false`, lose the race to the turn
205 /// completion barrier, and enqueue usage after `TurnComplete`.
206 send_gate: std::sync::Mutex<()>,
207 #[cfg(any(test, feature = "test-support"))]
208 cancel_token: CancellationToken,
209 }
210
211 /// Receiver side of the mailbox. Not `Clone` — only the original creator
212 /// can drain. Use `Mailbox::subscribe()` for fanout (UI cards + parent both
213 /// observing the same stream).
214 pub struct MailboxReceiver {
215 rx: mpsc::UnboundedReceiver<MailboxEnvelope>,
216 pending: VecDeque<MailboxEnvelope>,
217 }
218
219 impl Mailbox {
220 /// Create a new mailbox bound to the given cancellation token. Closing
221 /// the mailbox (or dropping the last sender) cancels this token. Runtimes
222 /// that derive from the same token observe that cancellation; detached
223 /// background `agent` sessions use their own runtime token.
224 #[must_use]
225 pub fn new(cancel_token: CancellationToken) -> (Self, MailboxReceiver) {
226 #[cfg(not(any(test, feature = "test-support")))]
227 let _ = cancel_token;
228 let (tx, rx) = mpsc::unbounded_channel();
229 let (seq_tx, _) = watch::channel(0);
230 let inner = MailboxInner {
231 tx,
232 next_seq: AtomicU64::new(0),
233 seq_tx,
234 closed: AtomicBool::new(false),
235 send_gate: std::sync::Mutex::new(()),
236 #[cfg(any(test, feature = "test-support"))]
237 cancel_token,
238 };
239 (
240 Self {
241 inner: Arc::new(inner),
242 },
243 MailboxReceiver {
244 rx,
245 pending: VecDeque::new(),
246 },
247 )
248 }
249
250 /// Subscribe to seq-bump notifications. Each `recv()` returns when the
251 /// sequence counter advances, signaling new mail without copying it —
252 /// the consumer then calls `drain` (or `recv_one` on its own receiver).
253 /// Multiple subscribers may exist; this is the fanout primitive.
254 #[cfg(any(test, feature = "test-support"))]
255 #[must_use]
256 pub fn subscribe(&self) -> watch::Receiver<u64> {
257 self.inner.seq_tx.subscribe()
258 }
259
260 /// Send a message; returns `Some(seq)` on success, `None` if the
261 /// mailbox is already closed (callers should treat this as "the
262 /// receiver is gone, stop publishing").
263 pub fn send(&self, message: MailboxMessage) -> Option<u64> {
264 let _send_gate = self
265 .inner
266 .send_gate
267 .lock()
268 .unwrap_or_else(|error| error.into_inner());
269 if self.inner.closed.load(Ordering::Acquire) {
270 return None;
271 }
272 let seq = self.inner.next_seq.fetch_add(1, Ordering::Relaxed) + 1;
273 let envelope = MailboxEnvelope { seq, message };
274 if self.inner.tx.send(envelope).is_err() {
275 return None;
276 }
277 let _ = self.inner.seq_tx.send_replace(seq);
278 Some(seq)
279 }
280
281 /// Stop publication for this turn without cancelling detached workers.
282 ///
283 /// The engine seals, drains, and awaits the mailbox before it emits
284 /// `TurnComplete`. The send gate makes this a hard ordering boundary:
285 /// once this returns, every accepted envelope is already in the receiver
286 /// and no later worker message can attach itself to the completed turn.
287 pub fn seal(&self) {
288 let _send_gate = self
289 .inner
290 .send_gate
291 .lock()
292 .unwrap_or_else(|error| error.into_inner());
293 self.inner.closed.store(true, Ordering::Release);
294 }
295
296 /// Whether the mailbox has been closed.
297 #[cfg(any(test, feature = "test-support"))]
298 #[must_use]
299 pub fn is_closed(&self) -> bool {
300 self.inner.closed.load(Ordering::Acquire)
301 }
302
303 /// Close the mailbox AND cancel the bound cancellation token.
304 ///
305 /// "Close-as-cancel": there's no useful state where the consumer is gone
306 /// but producers bound to this mailbox token should keep publishing.
307 /// Closing cancels the bound token; directly derived `child_runtime()`
308 /// children observe it, while detached `agent` sessions rely on their
309 /// own explicit cancellation.
310 #[cfg(any(test, feature = "test-support"))]
311 pub fn close(&self) {
312 let was_closed = self.inner.closed.load(Ordering::Acquire);
313 self.seal();
314 if !was_closed {
315 self.inner.cancel_token.cancel();
316 }
317 }
318 }
319
320 impl MailboxReceiver {
321 #[cfg(any(test, feature = "test-support"))]
322 fn sync_pending(&mut self) {
323 while let Ok(env) = self.rx.try_recv() {
324 self.pending.push_back(env);
325 }
326 }
327
328 /// Whether any envelopes are buffered (or arrived since last check).
329 #[cfg(any(test, feature = "test-support"))]
330 pub fn has_pending(&mut self) -> bool {
331 self.sync_pending();
332 !self.pending.is_empty()
333 }
334
335 /// Drain all currently available envelopes, in delivery order.
336 #[cfg(any(test, feature = "test-support"))]
337 pub fn drain(&mut self) -> Vec<MailboxEnvelope> {
338 self.sync_pending();
339 self.pending.drain(..).collect()
340 }
341
342 /// Await the next envelope, with backpressure-aware blocking. Returns
343 /// `None` when every sender has been dropped and the buffer is drained.
344 pub async fn recv(&mut self) -> Option<MailboxEnvelope> {
345 if let Some(env) = self.pending.pop_front() {
346 return Some(env);
347 }
348 self.rx.recv().await
349 }
350
351 /// Drain all envelopes accepted before a mailbox was sealed.
352 pub fn drain_available(&mut self) -> Vec<MailboxEnvelope> {
353 while let Ok(envelope) = self.rx.try_recv() {
354 self.pending.push_back(envelope);
355 }
356 self.pending.drain(..).collect()
357 }
358
359 /// Awaits the next envelope with a timeout. Useful in tests.
360 #[cfg(any(test, feature = "test-support"))]
361 pub async fn recv_timeout(&mut self, timeout: Duration) -> Option<MailboxEnvelope> {
362 tokio::time::timeout(timeout, self.recv())
363 .await
364 .ok()
365 .flatten()
366 }
367 }
368
369 #[cfg(test)]
370 mod tests {
371 use super::*;
372 use tokio::time::Duration;
373
374 fn open() -> (Mailbox, MailboxReceiver, CancellationToken) {
375 let token = CancellationToken::new();
376 let (mb, rx) = Mailbox::new(token.clone());
377 (mb, rx, token)
378 }
379
380 fn test_route(
381 provider: ProviderKind,
382 model: &str,
383 ) -> crate::cost_status::EffectiveRouteEnvelope {
384 crate::cost_status::EffectiveRouteEnvelope::capture(
385 None,
386 provider,
387 provider.as_str(),
388 model,
389 Some(provider.provider().default_base_url()),
390 chrono::Utc::now(),
391 )
392 }
393
394 #[tokio::test]
395 async fn mailbox_assigns_monotonic_sequence_numbers() {
396 let (mb, _rx, _tok) = open();
397 let s1 = mb
398 .send(MailboxMessage::progress("a", "one"))
399 .expect("seq 1");
400 let s2 = mb
401 .send(MailboxMessage::progress("a", "two"))
402 .expect("seq 2");
403 let s3 = mb
404 .send(MailboxMessage::progress("b", "three"))
405 .expect("seq 3");
406 assert_eq!(s1, 1);
407 assert_eq!(s2, 2);
408 assert_eq!(s3, 3);
409 assert!(s2 > s1 && s3 > s2);
410 }
411
412 #[tokio::test]
413 async fn mailbox_drains_in_delivery_order() {
414 let (mb, mut rx, _tok) = open();
415 mb.send(MailboxMessage::progress("a", "first"));
416 mb.send(MailboxMessage::progress("a", "second"));
417 mb.send(MailboxMessage::Completed {
418 agent_id: "a".into(),
419 summary: "done".into(),
420 });
421 let drained = rx.drain();
422 assert_eq!(drained.len(), 3);
423 assert_eq!(drained[0].seq, 1);
424 assert_eq!(drained[1].seq, 2);
425 assert_eq!(drained[2].seq, 3);
426 assert!(matches!(
427 drained[0].message,
428 MailboxMessage::Progress { .. }
429 ));
430 assert!(matches!(
431 drained[2].message,
432 MailboxMessage::Completed { .. }
433 ));
434 assert!(!rx.has_pending());
435 }
436
437 #[tokio::test]
438 async fn subscribers_receive_seq_bumps_for_backpressure() {
439 let (mb, _rx, _tok) = open();
440 let mut sub_a = mb.subscribe();
441 let mut sub_b = mb.subscribe();
442 // Initial state: both at 0.
443 assert_eq!(*sub_a.borrow(), 0);
444 assert_eq!(*sub_b.borrow(), 0);
445
446 mb.send(MailboxMessage::progress("x", "tick"));
447 sub_a.changed().await.expect("subscriber a sees bump");
448 sub_b.changed().await.expect("subscriber b sees bump");
449 assert_eq!(*sub_a.borrow(), 1);
450 assert_eq!(*sub_b.borrow(), 1);
451
452 // A second send updates both subscribers' watch values too — even
453 // though they share a single watch channel, fanout is N-to-many.
454 mb.send(MailboxMessage::progress("x", "tick2"));
455 sub_a.changed().await.expect("a sees second bump");
456 assert_eq!(*sub_a.borrow(), 2);
457 }
458
459 #[tokio::test]
460 async fn close_cancels_bound_token_and_blocks_further_sends() {
461 let (mb, _rx, token) = open();
462 assert!(!token.is_cancelled());
463 mb.send(MailboxMessage::progress("a", "before close"));
464 mb.close();
465 assert!(token.is_cancelled(), "close-as-cancel: token must fire");
466 assert!(mb.is_closed());
467 // Further sends are no-ops, returning None instead of poisoning seq.
468 assert!(
469 mb.send(MailboxMessage::progress("a", "after close"))
470 .is_none()
471 );
472 }
473
474 #[test]
475 fn turn_end_seal_forms_a_flush_barrier_without_cancelling_worker() {
476 let (mb, mut rx, token) = open();
477 assert_eq!(
478 mb.send(MailboxMessage::progress("a", "accepted before barrier")),
479 Some(1)
480 );
481 mb.seal();
482
483 assert!(!token.is_cancelled(), "detached worker is not cancelled");
484 assert!(
485 mb.send(MailboxMessage::progress("a", "too late")).is_none(),
486 "no event may be accepted after the completion barrier"
487 );
488 let drained = rx.drain_available();
489 assert_eq!(drained.len(), 1);
490 assert_eq!(drained[0].seq, 1);
491 }
492
493 #[tokio::test]
494 async fn close_propagates_to_child_tokens_across_max_spawn_depth() {
495 // Mirror the runtime: root → child → grandchild (default depth 3).
496 let root = CancellationToken::new();
497 let child = root.child_token();
498 let grandchild = child.child_token();
499 let (mb, _rx) = Mailbox::new(root.clone());
500
501 assert!(!child.is_cancelled());
502 assert!(!grandchild.is_cancelled());
503 mb.close();
504 assert!(child.is_cancelled(), "child inherits root close");
505 assert!(
506 grandchild.is_cancelled(),
507 "grandchild inherits too — covers default max_spawn_depth = 3"
508 );
509 }
510
511 #[tokio::test]
512 async fn recv_returns_envelope_then_none_after_close_and_drop() {
513 let (mb, mut rx, _tok) = open();
514 mb.send(MailboxMessage::progress("a", "queued"));
515 let env = rx.recv().await.expect("buffered envelope");
516 assert_eq!(env.seq, 1);
517
518 // After closing AND dropping the sender, recv must yield None.
519 mb.close();
520 drop(mb);
521 let next = rx.recv_timeout(Duration::from_millis(100)).await;
522 assert!(next.is_none(), "drained + dropped → recv yields None");
523 }
524
525 #[tokio::test]
526 async fn cloned_mailbox_shares_sequence_and_close_state() {
527 let (mb, mut rx, token) = open();
528 let mb_clone = mb.clone();
529 let s1 = mb
530 .send(MailboxMessage::progress("a", "from original"))
531 .unwrap();
532 let s2 = mb_clone
533 .send(MailboxMessage::progress("a", "from clone"))
534 .unwrap();
535 assert_eq!(s1, 1);
536 assert_eq!(s2, 2, "clones share the seq counter");
537
538 let drained = rx.drain();
539 assert_eq!(drained.len(), 2);
540
541 // Closing through one clone closes them all (the AtomicBool is shared).
542 mb_clone.close();
543 assert!(mb.is_closed());
544 assert!(token.is_cancelled());
545 }
546
547 #[test]
548 fn work_state_payload_round_trips_and_tolerates_a_missing_snapshot() {
549 use crate::tools::todo::{TodoItem, TodoStatus};
550
551 let message = MailboxMessage::work_state(
552 "agent_child",
553 TodoListSnapshot {
554 items: vec![TodoItem {
555 id: 2,
556 content: "write the projection".to_string(),
557 status: TodoStatus::InProgress,
558 }],
559 completion_pct: 50,
560 in_progress_id: Some(2),
561 },
562 );
563 let encoded = serde_json::to_string(&message).expect("encode");
564 let decoded: MailboxMessage = serde_json::from_str(&encoded).expect("decode");
565 assert_eq!(decoded, message);
566
567 // An older payload that predates per-agent Work state decodes to an
568 // empty snapshot rather than failing the whole stream.
569 let legacy: MailboxMessage =
570 serde_json::from_str(r#"{"kind":"work_state","agent_id":"agent_old"}"#)
571 .expect("legacy");
572 assert_eq!(legacy.agent_id(), "agent_old");
573 match legacy {
574 MailboxMessage::WorkState { todo, .. } => assert!(todo.is_empty()),
575 other => panic!("expected work state, got {other:?}"),
576 }
577
578 // Every pre-existing variant still decodes unchanged.
579 let started: MailboxMessage =
580 serde_json::from_str(r#"{"kind":"started","agent_id":"a","agent_type":"worker"}"#)
581 .expect("started");
582 assert_eq!(started.agent_id(), "a");
583 }
584
585 #[tokio::test]
586 async fn agent_id_is_extractable_from_every_variant() {
587 let cases: Vec<(MailboxMessage, &str)> = vec![
588 (MailboxMessage::started("a1", FleetRole::Worker), "a1"),
589 (MailboxMessage::progress("a2", "x"), "a2"),
590 (
591 MailboxMessage::ToolCallStarted {
592 agent_id: "a3".into(),
593 tool_name: "read_file".into(),
594 step: 1,
595 },
596 "a3",
597 ),
598 (
599 MailboxMessage::ToolCallCompleted {
600 agent_id: "a4".into(),
601 tool_name: "read_file".into(),
602 step: 1,
603 ok: true,
604 },
605 "a4",
606 ),
607 (
608 MailboxMessage::ChildSpawned {
609 parent_id: "parent".into(),
610 child_id: "a5".into(),
611 },
612 "a5",
613 ),
614 (
615 MailboxMessage::Completed {
616 agent_id: "a6".into(),
617 summary: "done".into(),
618 },
619 "a6",
620 ),
621 (
622 MailboxMessage::Failed {
623 agent_id: "a7".into(),
624 error: "boom".into(),
625 },
626 "a7",
627 ),
628 (
629 MailboxMessage::BudgetExhausted {
630 agent_id: "a7b".into(),
631 summary: "step budget exhausted".into(),
632 },
633 "a7b",
634 ),
635 (
636 MailboxMessage::Cancelled {
637 agent_id: "a8".into(),
638 },
639 "a8",
640 ),
641 (
642 MailboxMessage::Interrupted {
643 agent_id: "a10".into(),
644 reason: "API call timed out".into(),
645 },
646 "a10",
647 ),
648 (
649 MailboxMessage::work_state("a11", TodoListSnapshot::default()),
650 "a11",
651 ),
652 (
653 MailboxMessage::TokenUsage {
654 record: None,
655 agent_id: "a9".into(),
656 source_id: "response-a9".into(),
657 route: Box::new(test_route(ProviderKind::Deepseek, "deepseek-v4-flash")),
658 usage: Usage {
659 input_tokens: 100,
660 output_tokens: 50,
661 ..Default::default()
662 },
663 },
664 "a9",
665 ),
666 ];
667 for (msg, expected) in cases {
668 assert_eq!(msg.agent_id(), expected, "extract failed for {msg:?}");
669 }
670 }
671
672 #[test]
673 fn token_usage_serde_round_trip_preserves_immutable_route_evidence() {
674 let route = crate::cost_status::EffectiveRouteEnvelope {
675 openrouter_vendor: None,
676 provider: ProviderKind::Moonshot,
677 provider_identity: ProviderKind::Moonshot.as_str().to_string(),
678 model: "k3".to_string(),
679 billing_surface: Some(crate::pricing::MOONSHOT_KIMI_CODE_BILLING_SURFACE.to_string()),
680 endpoint_fingerprint: Some("a".repeat(64)),
681 provider_live_pricing: None,
682 billing_mode: crate::cost_status::RouteBillingMode::Subscription,
683 dispatched_at: chrono::DateTime::<chrono::Utc>::from_timestamp(1_234, 0)
684 .expect("timestamp"),
685 };
686 let message =
687 MailboxMessage::token_usage("agent-k3", "response-k3", route, Usage::default());
688 let json = serde_json::to_string(&message).expect("serialize token usage");
689 let restored: MailboxMessage =
690 serde_json::from_str(&json).expect("deserialize token usage");
691 assert_eq!(restored, message);
692 }
693 }
694
694 lines RUST