1use std::{
4 error::Error,
5 fmt::{self, Display, Formatter},
6 num::NonZeroU64,
7};
8
9#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
11#[non_exhaustive]
12pub enum Outcome {
13 Completed,
15 Stopped,
17 Cancelled,
19 Failed,
29}
30
31#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
33#[non_exhaustive]
34pub enum CoordError {
35 EmptySessionId,
37 EmptyRunId,
39 #[non_exhaustive]
41 StepExceedsStepInRun {
42 step: NonZeroU64,
44 step_in_run: NonZeroU64,
46 },
47 EmptyCallId,
49 EmptyToolName,
51}
52
53impl Display for CoordError {
54 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
55 match self {
56 Self::EmptySessionId => formatter.write_str("session ID must not be empty"),
57 Self::EmptyRunId => formatter.write_str("run ID must not be empty"),
58 Self::StepExceedsStepInRun { step, step_in_run } => write!(
59 formatter,
60 "step {step} must not exceed run-wide step {step_in_run}"
61 ),
62 Self::EmptyCallId => formatter.write_str("tool-call ID must not be empty"),
63 Self::EmptyToolName => formatter.write_str("tool name must not be empty"),
64 }
65 }
66}
67
68impl Error for CoordError {}
69
70#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
83pub struct StepIndex {
84 turn: NonZeroU64,
85 step: NonZeroU64,
86 step_in_run: NonZeroU64,
87}
88
89impl StepIndex {
90 pub fn new(
97 turn: NonZeroU64,
98 step: NonZeroU64,
99 step_in_run: NonZeroU64,
100 ) -> Result<Self, CoordError> {
101 if step > step_in_run {
102 return Err(CoordError::StepExceedsStepInRun { step, step_in_run });
103 }
104 Ok(Self {
105 turn,
106 step,
107 step_in_run,
108 })
109 }
110
111 #[must_use]
113 pub const fn turn(self) -> NonZeroU64 {
114 self.turn
115 }
116
117 #[must_use]
119 pub const fn step_in_turn(self) -> NonZeroU64 {
120 self.step
121 }
122
123 #[must_use]
125 pub const fn step_in_run(self) -> NonZeroU64 {
126 self.step_in_run
127 }
128}
129
130#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
131struct GenerationPosition {
132 step: StepIndex,
133 generation: NonZeroU64,
134}
135
136#[derive(Clone, Debug, Eq, Hash, PartialEq)]
137struct ToolCallPosition {
138 generation: GenerationPosition,
139 call_id: String,
140 tool_name: String,
141}
142
143#[derive(Clone, Debug, Eq, Hash, PartialEq)]
144enum Layer {
145 Run,
146 Turn(NonZeroU64),
147 Step(StepIndex),
148 Generation(GenerationPosition),
149 ToolCall(ToolCallPosition),
150}
151
152#[derive(Clone, Debug, Eq, Hash, PartialEq)]
186pub struct Coord {
187 session_id: String,
188 run_id: String,
189 layer: Layer,
190}
191
192impl Coord {
193 pub fn at_run(session_id: String, run_id: String) -> Result<Self, CoordError> {
200 Self::from_parts(session_id, run_id, Layer::Run)
201 }
202
203 pub fn at_turn(
209 session_id: String,
210 run_id: String,
211 turn: NonZeroU64,
212 ) -> Result<Self, CoordError> {
213 Self::from_parts(session_id, run_id, Layer::Turn(turn))
214 }
215
216 pub fn at_step(
222 session_id: String,
223 run_id: String,
224 step: StepIndex,
225 ) -> Result<Self, CoordError> {
226 Self::from_parts(session_id, run_id, Layer::Step(step))
227 }
228
229 pub fn at_generation(
235 session_id: String,
236 run_id: String,
237 step: StepIndex,
238 generation: NonZeroU64,
239 ) -> Result<Self, CoordError> {
240 let position = GenerationPosition { step, generation };
241 Self::from_parts(session_id, run_id, Layer::Generation(position))
242 }
243
244 pub fn at_tool_call(
251 session_id: String,
252 run_id: String,
253 step: StepIndex,
254 generation: NonZeroU64,
255 call_id: String,
256 tool_name: String,
257 ) -> Result<Self, CoordError> {
258 if call_id.is_empty() {
259 return Err(CoordError::EmptyCallId);
260 }
261 if tool_name.is_empty() {
262 return Err(CoordError::EmptyToolName);
263 }
264 let position = ToolCallPosition {
265 generation: GenerationPosition { step, generation },
266 call_id,
267 tool_name,
268 };
269 Self::from_parts(session_id, run_id, Layer::ToolCall(position))
270 }
271
272 fn from_parts(session_id: String, run_id: String, layer: Layer) -> Result<Self, CoordError> {
273 if session_id.is_empty() {
274 return Err(CoordError::EmptySessionId);
275 }
276 if run_id.is_empty() {
277 return Err(CoordError::EmptyRunId);
278 }
279 Ok(Self {
280 session_id,
281 run_id,
282 layer,
283 })
284 }
285
286 #[must_use]
288 pub fn session_id(&self) -> &str {
289 &self.session_id
290 }
291
292 #[must_use]
294 pub fn run_id(&self) -> &str {
295 &self.run_id
296 }
297
298 #[must_use]
300 pub const fn turn(&self) -> u64 {
301 match &self.layer {
302 Layer::Run => 0,
303 Layer::Turn(turn) => turn.get(),
304 Layer::Step(step) => step.turn.get(),
305 Layer::Generation(generation) => generation.step.turn.get(),
306 Layer::ToolCall(tool_call) => tool_call.generation.step.turn.get(),
307 }
308 }
309
310 #[must_use]
312 pub const fn step_in_turn(&self) -> u64 {
313 match &self.layer {
314 Layer::Run | Layer::Turn(_) => 0,
315 Layer::Step(step) => step.step.get(),
316 Layer::Generation(generation) => generation.step.step.get(),
317 Layer::ToolCall(tool_call) => tool_call.generation.step.step.get(),
318 }
319 }
320
321 #[must_use]
323 pub const fn step_in_run(&self) -> u64 {
324 match &self.layer {
325 Layer::Run | Layer::Turn(_) => 0,
326 Layer::Step(step) => step.step_in_run.get(),
327 Layer::Generation(generation) => generation.step.step_in_run.get(),
328 Layer::ToolCall(tool_call) => tool_call.generation.step.step_in_run.get(),
329 }
330 }
331
332 #[must_use]
334 pub const fn generation(&self) -> u64 {
335 match &self.layer {
336 Layer::Run | Layer::Turn(_) | Layer::Step(_) => 0,
337 Layer::Generation(generation) => generation.generation.get(),
338 Layer::ToolCall(tool_call) => tool_call.generation.generation.get(),
339 }
340 }
341
342 #[must_use]
344 pub fn call_id(&self) -> &str {
345 match &self.layer {
346 Layer::ToolCall(tool_call) => &tool_call.call_id,
347 _ => "",
348 }
349 }
350
351 #[must_use]
353 pub fn tool_name(&self) -> &str {
354 match &self.layer {
355 Layer::ToolCall(tool_call) => &tool_call.tool_name,
356 _ => "",
357 }
358 }
359}
360
361impl Display for Coord {
362 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
363 formatter.write_str(&self.run_id)?;
364 if self.turn() > 0 {
365 write!(formatter, "/turn-{}", self.turn())?;
366 }
367 if self.step_in_turn() > 0 {
368 write!(formatter, "/step-{}", self.step_in_turn())?;
369 }
370 if self.generation() > 0 {
371 write!(formatter, "/gen-{}", self.generation())?;
372 }
373 if !self.call_id().is_empty() {
374 write!(formatter, "/call-{}", self.call_id())?;
375 }
376 Ok(())
377 }
378}
379
380#[cfg(feature = "serde")]
398mod serde_impl {
399 use std::fmt::{self, Formatter};
400 use std::num::NonZeroU64;
401
402 use serde_core::de::{
403 Deserialize, Deserializer, EnumAccess, Error as DeError, MapAccess, SeqAccess,
404 VariantAccess, Visitor,
405 };
406 use serde_core::ser::{Serialize, SerializeStruct, Serializer};
407
408 use super::{Coord, Outcome, StepIndex};
409 use crate::wire::{self, IdentifierSeed};
410
411 const OUTCOME_NAME: &str = "Outcome";
412 const OUTCOME_VARIANTS: &[&str] = &["completed", "stopped", "canceled", "failed"];
413 const COORD_FIELDS: &[&str] = &[
414 "session_id",
415 "run_id",
416 "turn",
417 "step",
418 "step_in_run",
419 "generation",
420 "call_id",
421 "tool_name",
422 ];
423
424 struct InvalidLayer;
427
428 impl fmt::Display for InvalidLayer {
429 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
430 formatter.write_str(
431 "coordinate layer values do not describe a run, turn, step, generation or tool call",
432 )
433 }
434 }
435
436 impl Serialize for Outcome {
439 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
440 where
441 S: Serializer,
442 {
443 let (index, tag) = match self {
444 Self::Completed => (0, "completed"),
445 Self::Stopped => (1, "stopped"),
446 Self::Cancelled => (2, "canceled"),
447 Self::Failed => (3, "failed"),
448 };
449 serializer.serialize_unit_variant(OUTCOME_NAME, index, tag)
450 }
451 }
452
453 impl<'de> Deserialize<'de> for Outcome {
454 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
455 where
456 D: Deserializer<'de>,
457 {
458 deserializer.deserialize_enum(OUTCOME_NAME, OUTCOME_VARIANTS, OutcomeVisitor)
459 }
460 }
461
462 struct OutcomeVisitor;
463
464 impl<'de> Visitor<'de> for OutcomeVisitor {
465 type Value = Outcome;
466
467 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
468 formatter.write_str("a lifecycle outcome")
469 }
470
471 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
472 where
473 A: EnumAccess<'de>,
474 {
475 let (tag, variant) = data.variant_seed(IdentifierSeed(OUTCOME_VARIANTS))?;
476 variant.unit_variant()?;
477 match tag.0.as_str() {
478 "completed" => Ok(Outcome::Completed),
479 "stopped" => Ok(Outcome::Stopped),
480 "canceled" => Ok(Outcome::Cancelled),
481 "failed" => Ok(Outcome::Failed),
482 unknown => Err(A::Error::unknown_variant(unknown, OUTCOME_VARIANTS)),
483 }
484 }
485 }
486
487 impl Serialize for Coord {
490 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
491 where
492 S: Serializer,
493 {
494 let mut record = serializer.serialize_struct("Coord", 8)?;
495 record.serialize_field("session_id", self.session_id())?;
496 record.serialize_field("run_id", self.run_id())?;
497 record.serialize_field("turn", &self.turn())?;
498 record.serialize_field("step", &self.step_in_turn())?;
499 record.serialize_field("step_in_run", &self.step_in_run())?;
500 record.serialize_field("generation", &self.generation())?;
501 record.serialize_field("call_id", self.call_id())?;
502 record.serialize_field("tool_name", self.tool_name())?;
503 record.end()
504 }
505 }
506
507 impl<'de> Deserialize<'de> for Coord {
508 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
509 where
510 D: Deserializer<'de>,
511 {
512 deserializer.deserialize_struct("Coord", COORD_FIELDS, CoordVisitor)
513 }
514 }
515
516 struct Flat {
518 session_id: String,
519 run_id: String,
520 turn: u64,
521 step: u64,
522 step_in_run: u64,
523 generation: u64,
524 call_id: String,
525 tool_name: String,
526 }
527
528 impl Flat {
529 fn build<E>(self) -> Result<Coord, E>
537 where
538 E: DeError,
539 {
540 let Self {
541 session_id,
542 run_id,
543 turn,
544 step,
545 step_in_run,
546 generation,
547 call_id,
548 tool_name,
549 } = self;
550 let built = match (
551 NonZeroU64::new(turn),
552 NonZeroU64::new(step),
553 NonZeroU64::new(step_in_run),
554 NonZeroU64::new(generation),
555 call_id.is_empty(),
556 tool_name.is_empty(),
557 ) {
558 (None, None, None, None, true, true) => Coord::at_run(session_id, run_id),
559 (Some(turn), None, None, None, true, true) => {
560 Coord::at_turn(session_id, run_id, turn)
561 }
562 (Some(turn), Some(step), Some(step_in_run), None, true, true) => {
563 StepIndex::new(turn, step, step_in_run)
564 .and_then(|index| Coord::at_step(session_id, run_id, index))
565 }
566 (Some(turn), Some(step), Some(step_in_run), Some(generation), true, true) => {
567 StepIndex::new(turn, step, step_in_run).and_then(|index| {
568 Coord::at_generation(session_id, run_id, index, generation)
569 })
570 }
571 (Some(turn), Some(step), Some(step_in_run), Some(generation), false, false) => {
572 StepIndex::new(turn, step, step_in_run).and_then(|index| {
573 Coord::at_tool_call(
574 session_id, run_id, index, generation, call_id, tool_name,
575 )
576 })
577 }
578 _ => return Err(E::custom(InvalidLayer)),
579 };
580 built.map_err(E::custom)
581 }
582 }
583
584 struct CoordVisitor;
585
586 impl<'de> Visitor<'de> for CoordVisitor {
587 type Value = Coord;
588
589 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
590 formatter.write_str("a lifecycle coordinate")
591 }
592
593 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
594 where
595 A: SeqAccess<'de>,
596 {
597 let session_id = wire::element(&mut sequence, 0)?;
598 let run_id = wire::element(&mut sequence, 1)?;
599 let turn = wire::element(&mut sequence, 2)?;
600 let step = wire::element(&mut sequence, 3)?;
601 let step_in_run = wire::element(&mut sequence, 4)?;
602 let generation = wire::element(&mut sequence, 5)?;
603 let call_id = wire::element(&mut sequence, 6)?;
604 let tool_name = wire::element(&mut sequence, 7)?;
605 wire::end(&mut sequence, 8)?;
606 Flat {
607 session_id,
608 run_id,
609 turn,
610 step,
611 step_in_run,
612 generation,
613 call_id,
614 tool_name,
615 }
616 .build()
617 }
618
619 fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
620 where
621 A: MapAccess<'de>,
622 {
623 let mut session_id = None;
624 let mut run_id = None;
625 let mut turn = None;
626 let mut step = None;
627 let mut step_in_run = None;
628 let mut generation = None;
629 let mut call_id = None;
630 let mut tool_name = None;
631 while let Some(field) = entries.next_key_seed(IdentifierSeed(COORD_FIELDS))? {
632 match field.0.as_str() {
633 "session_id" => {
634 wire::accept(&mut session_id, entries.next_value()?, "session_id")?;
635 }
636 "run_id" => wire::accept(&mut run_id, entries.next_value()?, "run_id")?,
637 "turn" => wire::accept(&mut turn, entries.next_value()?, "turn")?,
638 "step" => wire::accept(&mut step, entries.next_value()?, "step")?,
639 "step_in_run" => {
640 wire::accept(&mut step_in_run, entries.next_value()?, "step_in_run")?;
641 }
642 "generation" => {
643 wire::accept(&mut generation, entries.next_value()?, "generation")?;
644 }
645 "call_id" => wire::accept(&mut call_id, entries.next_value()?, "call_id")?,
646 "tool_name" => {
647 wire::accept(&mut tool_name, entries.next_value()?, "tool_name")?;
648 }
649 unknown => return Err(A::Error::unknown_field(unknown, COORD_FIELDS)),
650 }
651 }
652 Flat {
653 session_id: wire::require(session_id, "session_id")?,
654 run_id: wire::require(run_id, "run_id")?,
655 turn: wire::require(turn, "turn")?,
656 step: wire::require(step, "step")?,
657 step_in_run: wire::require(step_in_run, "step_in_run")?,
658 generation: wire::require(generation, "generation")?,
659 call_id: wire::require(call_id, "call_id")?,
660 tool_name: wire::require(tool_name, "tool_name")?,
661 }
662 .build()
663 }
664 }
665}