use std::{
error::Error,
fmt::{self, Display, Formatter},
num::NonZeroU64,
};
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum Outcome {
Completed,
Stopped,
Cancelled,
Failed,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum CoordError {
EmptySessionId,
EmptyRunId,
#[non_exhaustive]
StepExceedsStepInRun {
step: NonZeroU64,
step_in_run: NonZeroU64,
},
EmptyCallId,
EmptyToolName,
}
impl Display for CoordError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::EmptySessionId => formatter.write_str("session ID must not be empty"),
Self::EmptyRunId => formatter.write_str("run ID must not be empty"),
Self::StepExceedsStepInRun { step, step_in_run } => write!(
formatter,
"step {step} must not exceed run-wide step {step_in_run}"
),
Self::EmptyCallId => formatter.write_str("tool-call ID must not be empty"),
Self::EmptyToolName => formatter.write_str("tool name must not be empty"),
}
}
}
impl Error for CoordError {}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct StepIndex {
turn: NonZeroU64,
step: NonZeroU64,
step_in_run: NonZeroU64,
}
impl StepIndex {
pub fn new(
turn: NonZeroU64,
step: NonZeroU64,
step_in_run: NonZeroU64,
) -> Result<Self, CoordError> {
if step > step_in_run {
return Err(CoordError::StepExceedsStepInRun { step, step_in_run });
}
Ok(Self {
turn,
step,
step_in_run,
})
}
#[must_use]
pub const fn turn(self) -> NonZeroU64 {
self.turn
}
#[must_use]
pub const fn step_in_turn(self) -> NonZeroU64 {
self.step
}
#[must_use]
pub const fn step_in_run(self) -> NonZeroU64 {
self.step_in_run
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct GenerationPosition {
step: StepIndex,
generation: NonZeroU64,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct ToolCallPosition {
generation: GenerationPosition,
call_id: String,
tool_name: String,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
enum Layer {
Run,
Turn(NonZeroU64),
Step(StepIndex),
Generation(GenerationPosition),
ToolCall(ToolCallPosition),
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Coord {
session_id: String,
run_id: String,
layer: Layer,
}
impl Coord {
pub fn at_run(session_id: String, run_id: String) -> Result<Self, CoordError> {
Self::from_parts(session_id, run_id, Layer::Run)
}
pub fn at_turn(
session_id: String,
run_id: String,
turn: NonZeroU64,
) -> Result<Self, CoordError> {
Self::from_parts(session_id, run_id, Layer::Turn(turn))
}
pub fn at_step(
session_id: String,
run_id: String,
step: StepIndex,
) -> Result<Self, CoordError> {
Self::from_parts(session_id, run_id, Layer::Step(step))
}
pub fn at_generation(
session_id: String,
run_id: String,
step: StepIndex,
generation: NonZeroU64,
) -> Result<Self, CoordError> {
let position = GenerationPosition { step, generation };
Self::from_parts(session_id, run_id, Layer::Generation(position))
}
pub fn at_tool_call(
session_id: String,
run_id: String,
step: StepIndex,
generation: NonZeroU64,
call_id: String,
tool_name: String,
) -> Result<Self, CoordError> {
if call_id.is_empty() {
return Err(CoordError::EmptyCallId);
}
if tool_name.is_empty() {
return Err(CoordError::EmptyToolName);
}
let position = ToolCallPosition {
generation: GenerationPosition { step, generation },
call_id,
tool_name,
};
Self::from_parts(session_id, run_id, Layer::ToolCall(position))
}
fn from_parts(session_id: String, run_id: String, layer: Layer) -> Result<Self, CoordError> {
if session_id.is_empty() {
return Err(CoordError::EmptySessionId);
}
if run_id.is_empty() {
return Err(CoordError::EmptyRunId);
}
Ok(Self {
session_id,
run_id,
layer,
})
}
#[must_use]
pub fn session_id(&self) -> &str {
&self.session_id
}
#[must_use]
pub fn run_id(&self) -> &str {
&self.run_id
}
#[must_use]
pub const fn turn(&self) -> u64 {
match &self.layer {
Layer::Run => 0,
Layer::Turn(turn) => turn.get(),
Layer::Step(step) => step.turn.get(),
Layer::Generation(generation) => generation.step.turn.get(),
Layer::ToolCall(tool_call) => tool_call.generation.step.turn.get(),
}
}
#[must_use]
pub const fn step_in_turn(&self) -> u64 {
match &self.layer {
Layer::Run | Layer::Turn(_) => 0,
Layer::Step(step) => step.step.get(),
Layer::Generation(generation) => generation.step.step.get(),
Layer::ToolCall(tool_call) => tool_call.generation.step.step.get(),
}
}
#[must_use]
pub const fn step_in_run(&self) -> u64 {
match &self.layer {
Layer::Run | Layer::Turn(_) => 0,
Layer::Step(step) => step.step_in_run.get(),
Layer::Generation(generation) => generation.step.step_in_run.get(),
Layer::ToolCall(tool_call) => tool_call.generation.step.step_in_run.get(),
}
}
#[must_use]
pub const fn generation(&self) -> u64 {
match &self.layer {
Layer::Run | Layer::Turn(_) | Layer::Step(_) => 0,
Layer::Generation(generation) => generation.generation.get(),
Layer::ToolCall(tool_call) => tool_call.generation.generation.get(),
}
}
#[must_use]
pub fn call_id(&self) -> &str {
match &self.layer {
Layer::ToolCall(tool_call) => &tool_call.call_id,
_ => "",
}
}
#[must_use]
pub fn tool_name(&self) -> &str {
match &self.layer {
Layer::ToolCall(tool_call) => &tool_call.tool_name,
_ => "",
}
}
}
impl Display for Coord {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.run_id)?;
if self.turn() > 0 {
write!(formatter, "/turn-{}", self.turn())?;
}
if self.step_in_turn() > 0 {
write!(formatter, "/step-{}", self.step_in_turn())?;
}
if self.generation() > 0 {
write!(formatter, "/gen-{}", self.generation())?;
}
if !self.call_id().is_empty() {
write!(formatter, "/call-{}", self.call_id())?;
}
Ok(())
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use std::fmt::{self, Formatter};
use std::num::NonZeroU64;
use serde_core::de::{
Deserialize, Deserializer, EnumAccess, Error as DeError, MapAccess, SeqAccess,
VariantAccess, Visitor,
};
use serde_core::ser::{Serialize, SerializeStruct, Serializer};
use super::{Coord, Outcome, StepIndex};
use crate::wire::{self, IdentifierSeed};
const OUTCOME_NAME: &str = "Outcome";
const OUTCOME_VARIANTS: &[&str] = &["completed", "stopped", "canceled", "failed"];
const COORD_FIELDS: &[&str] = &[
"session_id",
"run_id",
"turn",
"step",
"step_in_run",
"generation",
"call_id",
"tool_name",
];
struct InvalidLayer;
impl fmt::Display for InvalidLayer {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(
"coordinate layer values do not describe a run, turn, step, generation or tool call",
)
}
}
impl Serialize for Outcome {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let (index, tag) = match self {
Self::Completed => (0, "completed"),
Self::Stopped => (1, "stopped"),
Self::Cancelled => (2, "canceled"),
Self::Failed => (3, "failed"),
};
serializer.serialize_unit_variant(OUTCOME_NAME, index, tag)
}
}
impl<'de> Deserialize<'de> for Outcome {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_enum(OUTCOME_NAME, OUTCOME_VARIANTS, OutcomeVisitor)
}
}
struct OutcomeVisitor;
impl<'de> Visitor<'de> for OutcomeVisitor {
type Value = Outcome;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str("a lifecycle outcome")
}
fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
where
A: EnumAccess<'de>,
{
let (tag, variant) = data.variant_seed(IdentifierSeed(OUTCOME_VARIANTS))?;
variant.unit_variant()?;
match tag.0.as_str() {
"completed" => Ok(Outcome::Completed),
"stopped" => Ok(Outcome::Stopped),
"canceled" => Ok(Outcome::Cancelled),
"failed" => Ok(Outcome::Failed),
unknown => Err(A::Error::unknown_variant(unknown, OUTCOME_VARIANTS)),
}
}
}
impl Serialize for Coord {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut record = serializer.serialize_struct("Coord", 8)?;
record.serialize_field("session_id", self.session_id())?;
record.serialize_field("run_id", self.run_id())?;
record.serialize_field("turn", &self.turn())?;
record.serialize_field("step", &self.step_in_turn())?;
record.serialize_field("step_in_run", &self.step_in_run())?;
record.serialize_field("generation", &self.generation())?;
record.serialize_field("call_id", self.call_id())?;
record.serialize_field("tool_name", self.tool_name())?;
record.end()
}
}
impl<'de> Deserialize<'de> for Coord {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_struct("Coord", COORD_FIELDS, CoordVisitor)
}
}
struct Flat {
session_id: String,
run_id: String,
turn: u64,
step: u64,
step_in_run: u64,
generation: u64,
call_id: String,
tool_name: String,
}
impl Flat {
fn build<E>(self) -> Result<Coord, E>
where
E: DeError,
{
let Self {
session_id,
run_id,
turn,
step,
step_in_run,
generation,
call_id,
tool_name,
} = self;
let built = match (
NonZeroU64::new(turn),
NonZeroU64::new(step),
NonZeroU64::new(step_in_run),
NonZeroU64::new(generation),
call_id.is_empty(),
tool_name.is_empty(),
) {
(None, None, None, None, true, true) => Coord::at_run(session_id, run_id),
(Some(turn), None, None, None, true, true) => {
Coord::at_turn(session_id, run_id, turn)
}
(Some(turn), Some(step), Some(step_in_run), None, true, true) => {
StepIndex::new(turn, step, step_in_run)
.and_then(|index| Coord::at_step(session_id, run_id, index))
}
(Some(turn), Some(step), Some(step_in_run), Some(generation), true, true) => {
StepIndex::new(turn, step, step_in_run).and_then(|index| {
Coord::at_generation(session_id, run_id, index, generation)
})
}
(Some(turn), Some(step), Some(step_in_run), Some(generation), false, false) => {
StepIndex::new(turn, step, step_in_run).and_then(|index| {
Coord::at_tool_call(
session_id, run_id, index, generation, call_id, tool_name,
)
})
}
_ => return Err(E::custom(InvalidLayer)),
};
built.map_err(E::custom)
}
}
struct CoordVisitor;
impl<'de> Visitor<'de> for CoordVisitor {
type Value = Coord;
fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str("a lifecycle coordinate")
}
fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let session_id = wire::element(&mut sequence, 0)?;
let run_id = wire::element(&mut sequence, 1)?;
let turn = wire::element(&mut sequence, 2)?;
let step = wire::element(&mut sequence, 3)?;
let step_in_run = wire::element(&mut sequence, 4)?;
let generation = wire::element(&mut sequence, 5)?;
let call_id = wire::element(&mut sequence, 6)?;
let tool_name = wire::element(&mut sequence, 7)?;
wire::end(&mut sequence, 8)?;
Flat {
session_id,
run_id,
turn,
step,
step_in_run,
generation,
call_id,
tool_name,
}
.build()
}
fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut session_id = None;
let mut run_id = None;
let mut turn = None;
let mut step = None;
let mut step_in_run = None;
let mut generation = None;
let mut call_id = None;
let mut tool_name = None;
while let Some(field) = entries.next_key_seed(IdentifierSeed(COORD_FIELDS))? {
match field.0.as_str() {
"session_id" => {
wire::accept(&mut session_id, entries.next_value()?, "session_id")?;
}
"run_id" => wire::accept(&mut run_id, entries.next_value()?, "run_id")?,
"turn" => wire::accept(&mut turn, entries.next_value()?, "turn")?,
"step" => wire::accept(&mut step, entries.next_value()?, "step")?,
"step_in_run" => {
wire::accept(&mut step_in_run, entries.next_value()?, "step_in_run")?;
}
"generation" => {
wire::accept(&mut generation, entries.next_value()?, "generation")?;
}
"call_id" => wire::accept(&mut call_id, entries.next_value()?, "call_id")?,
"tool_name" => {
wire::accept(&mut tool_name, entries.next_value()?, "tool_name")?;
}
unknown => return Err(A::Error::unknown_field(unknown, COORD_FIELDS)),
}
}
Flat {
session_id: wire::require(session_id, "session_id")?,
run_id: wire::require(run_id, "run_id")?,
turn: wire::require(turn, "turn")?,
step: wire::require(step, "step")?,
step_in_run: wire::require(step_in_run, "step_in_run")?,
generation: wire::require(generation, "generation")?,
call_id: wire::require(call_id, "call_id")?,
tool_name: wire::require(tool_name, "tool_name")?,
}
.build()
}
}
}