1use std::{borrow::Cow, fmt, sync::Arc};
14
15use serde::{Deserialize, Serialize};
16
17use crate::{
18 completion::{CompletionRequest, CompletionResponse, ModelRef, ProviderCapabilities},
19 embeddings::EmbeddingResponse,
20 error::ErrorReport,
21 operation::RerankRequest,
22 rerank::RerankResponse,
23 streaming::StreamRecord,
24 tool::ToolResult,
25 vector_store::request::{Filter, VectorSearchRequest},
26 wasm_compat::WasmCompatSend,
27};
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
34#[serde(transparent)]
35pub struct EffectId(u64);
36
37impl EffectId {
38 pub const fn from_raw(raw: u64) -> Self {
40 Self(raw)
41 }
42
43 pub const fn as_u64(self) -> u64 {
45 self.0
46 }
47}
48
49impl fmt::Display for EffectId {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 write!(f, "effect:{}", self.0)
52 }
53}
54
55#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
57#[serde(transparent)]
58pub struct HandlerKey(Arc<str>);
59
60impl HandlerKey {
61 pub fn new(key: impl Into<Arc<str>>) -> Self {
63 Self(key.into())
64 }
65
66 pub fn as_str(&self) -> &str {
68 &self.0
69 }
70
71 pub fn parts(&self) -> KeyParts {
74 KeyParts::parse(&self.0)
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq, Hash)]
94pub struct KeyParts {
95 pub owner: Option<Arc<str>>,
97 pub kind: Option<Arc<str>>,
99 pub label: Arc<str>,
101 pub generation: Option<u64>,
105}
106
107impl KeyParts {
108 pub fn parse(key: &str) -> Self {
110 let (owner, rest) = match key.split_once('/') {
111 Some((owner, rest)) if !owner.is_empty() && !rest.is_empty() => {
112 (Some(Arc::from(owner)), rest)
113 }
114 _ => (None, key),
115 };
116 let (rest, generation) = match rest.rsplit_once('#') {
117 Some((head, digits))
118 if !digits.is_empty()
119 && (digits.len() == 1 || !digits.starts_with('0'))
120 && digits.bytes().all(|b| b.is_ascii_digit()) =>
121 {
122 match digits.parse::<u64>() {
123 Ok(generation) => (head, Some(generation)),
124 Err(_) => (rest, None),
125 }
126 }
127 _ => (rest, None),
128 };
129 let (kind, label) = match rest.split_once(':') {
130 Some((kind, label)) if !kind.is_empty() && !label.is_empty() => {
131 (Some(Arc::from(kind)), label)
132 }
133 _ => (None, rest),
134 };
135 Self {
136 owner,
137 kind,
138 label: Arc::from(label),
139 generation,
140 }
141 }
142}
143
144impl fmt::Display for KeyParts {
145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146 if let Some(owner) = &self.owner {
147 write!(f, "{owner}/")?;
148 }
149 if let Some(kind) = &self.kind {
150 write!(f, "{kind}:")?;
151 }
152 f.write_str(&self.label)?;
153 if let Some(generation) = self.generation {
154 write!(f, "#{generation}")?;
155 }
156 Ok(())
157 }
158}
159
160impl fmt::Debug for HandlerKey {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 write!(f, "HandlerKey({:?})", &*self.0)
163 }
164}
165
166impl fmt::Display for HandlerKey {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 f.write_str(&self.0)
169 }
170}
171
172impl From<&str> for HandlerKey {
173 fn from(key: &str) -> Self {
174 Self(Arc::from(key))
175 }
176}
177
178impl From<String> for HandlerKey {
179 fn from(key: String) -> Self {
180 Self(Arc::from(key))
181 }
182}
183
184impl AsRef<str> for HandlerKey {
185 fn as_ref(&self) -> &str {
186 &self.0
187 }
188}
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
192#[serde(rename_all = "snake_case")]
193pub enum EffectFamily {
194 Completion,
196 Tool,
198 Embed,
200 Rerank,
202 Retrieve,
204 Custom,
206}
207
208impl EffectFamily {
209 pub const fn name(self) -> &'static str {
211 match self {
212 Self::Completion => "completion",
213 Self::Tool => "tool_call",
214 Self::Embed => "embed",
215 Self::Rerank => "rerank",
216 Self::Retrieve => "retrieve",
217 Self::Custom => "custom",
218 }
219 }
220}
221
222impl fmt::Display for EffectFamily {
223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224 f.write_str(self.name())
225 }
226}
227
228pub trait Family: sealed::Sealed + Clone + Copy + Send + Sync + 'static {
232 const FAMILY: EffectFamily;
234 type Request: WasmCompatSend + 'static;
236 type Answer: WasmCompatSend + 'static;
238 fn wrap(request: Self::Request) -> Result<EffectKind, ErrorReport>;
243 fn unwrap(outcome: Answered) -> Result<Self::Answer, ErrorReport>;
245 fn mismatch(outcome: &Answered) -> ErrorReport {
247 ErrorReport::new(
248 crate::error::ErrorKind::Internal,
249 format!(
250 "expected a {} outcome, the handler answered {}",
251 Self::FAMILY,
252 outcome.family()
253 ),
254 )
255 }
256}
257
258mod sealed {
259 pub trait Sealed {}
260}
261
262pub trait Served: sealed::Sealed + 'static {
265 const SERVED: Option<EffectFamily>;
267}
268
269#[diagnostic::do_not_recommend]
272impl<F: Family> Served for F {
273 const SERVED: Option<EffectFamily> = Some(F::FAMILY);
274}
275
276#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
282pub struct ToolCallRequest {
283 pub name: String,
285 pub args: String,
287}
288
289pub trait CustomEffect: Serialize + serde::de::DeserializeOwned + WasmCompatSend + 'static {
294 const KIND: &'static str;
297 type Answer: Serialize + serde::de::DeserializeOwned + WasmCompatSend + 'static;
299}
300
301mod key;
302
303pub use key::Key;
304
305pub fn model_key(label: &str) -> HandlerKey {
307 HandlerKey::from(format!("model:{label}"))
308}
309
310pub fn tool_key(name: &str) -> HandlerKey {
312 HandlerKey::from(format!("tool:{name}"))
313}
314
315pub fn embed_key(label: &str) -> HandlerKey {
317 HandlerKey::from(format!("embed:{label}"))
318}
319
320pub fn rerank_key(label: &str) -> HandlerKey {
322 HandlerKey::from(format!("rerank:{label}"))
323}
324
325pub fn retrieve_key(label: &str) -> HandlerKey {
328 HandlerKey::from(format!("retrieve:{label}"))
329}
330
331pub mod family {
338 use std::marker::PhantomData;
339
340 use super::{
341 Answered, CustomEffect, EffectFamily, EffectKind, EmbedInputs, EmbedOutputs, Family,
342 RetrieveQuery, RetrievedDocuments, ToolCallRequest, sealed::Sealed,
343 };
344 use crate::{
345 completion::{CompletionRequest, CompletionResponse},
346 error::{ErrorKind, ErrorReport},
347 operation::RerankRequest,
348 rerank::RerankResponse,
349 tool::ToolResult,
350 };
351
352 macro_rules! marker {
353 ($($(#[$doc:meta])* $name:ident => $family:ident, $request:ty, $answer:ty, $wrap:expr, $unwrap:expr;)+) => {$(
354 $(#[$doc])*
355 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
356 pub struct $name;
357
358 impl Sealed for $name {}
359
360 impl Family for $name {
361 const FAMILY: EffectFamily = EffectFamily::$family;
362 type Request = $request;
363 type Answer = $answer;
364
365 fn wrap(request: Self::Request) -> Result<EffectKind, ErrorReport> {
366 let wrap: fn(Self::Request) -> EffectKind = $wrap;
367 Ok(wrap(request))
368 }
369
370 fn unwrap(outcome: Answered) -> Result<Self::Answer, ErrorReport> {
371 let unwrap: fn(Answered) -> Result<Self::Answer, ErrorReport> = $unwrap;
372 unwrap(outcome)
373 }
374 }
375 )+};
376 }
377
378 marker! {
379 Completion => Completion, CompletionRequest, CompletionResponse,
382 |request| EffectKind::Completion { request: std::sync::Arc::new(request), stream: false },
383 |outcome| match outcome {
384 Answered::Completion(response) => Ok(std::sync::Arc::unwrap_or_clone(response)),
385 other => Err(Completion::mismatch(&other)),
386 };
387 Tool => Tool, ToolCallRequest, ToolResult,
389 |request| EffectKind::ToolCall { name: request.name, args: request.args },
390 |outcome| match outcome {
391 Answered::ToolResult { result } => Ok(result),
392 other => Err(Tool::mismatch(&other)),
393 };
394 Embed => Embed, EmbedInputs, EmbedOutputs,
396 |inputs| EffectKind::Embed { inputs },
397 |outcome| match outcome {
398 Answered::Embeddings(outputs) => Ok(outputs),
399 other => Err(Embed::mismatch(&other)),
400 };
401 Rerank => Rerank, RerankRequest, RerankResponse,
403 |request| EffectKind::Rerank { request },
404 |outcome| match outcome {
405 Answered::Reranked(response) => Ok(response),
406 other => Err(Rerank::mismatch(&other)),
407 };
408 Retrieve => Retrieve, RetrieveQuery, RetrievedDocuments,
410 |query| EffectKind::Retrieve { query },
411 |outcome| match outcome {
412 Answered::Documents(documents) => Ok(documents),
413 other => Err(Retrieve::mismatch(&other)),
414 };
415 }
416
417 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
420 pub struct Dynamic;
421
422 impl Sealed for Dynamic {}
423
424 impl super::Served for Dynamic {
425 const SERVED: Option<EffectFamily> = None;
426 }
427
428 pub struct Custom<E: CustomEffect>(PhantomData<fn() -> E>);
431
432 impl<E: CustomEffect> Clone for Custom<E> {
435 fn clone(&self) -> Self {
436 *self
437 }
438 }
439 impl<E: CustomEffect> Copy for Custom<E> {}
440
441 impl<E: CustomEffect> Sealed for Custom<E> {}
442
443 impl<E: CustomEffect> Family for Custom<E> {
444 const FAMILY: EffectFamily = EffectFamily::Custom;
445 type Request = E;
446 type Answer = E::Answer;
447
448 fn wrap(request: E) -> Result<EffectKind, ErrorReport> {
449 serde_json::to_value(&request)
452 .map(|payload| EffectKind::Custom {
453 kind: std::sync::Arc::from(E::KIND),
454 payload,
455 })
456 .map_err(|error| {
457 ErrorReport::new(
458 ErrorKind::Request,
459 format!("the `{}` effect did not serialize: {error}", E::KIND),
460 )
461 })
462 }
463
464 fn unwrap(outcome: Answered) -> Result<E::Answer, ErrorReport> {
465 match outcome {
466 Answered::Custom { payload: value } => crate::json_utils::from_value(&value)
467 .map_err(|error| {
468 ErrorReport::new(
469 ErrorKind::Internal,
470 format!(
471 "the answer to the `{}` effect did not deserialize: {error}",
472 E::KIND
473 ),
474 )
475 }),
476 other => Err(Self::mismatch(&other)),
477 }
478 }
479 }
480}
481
482#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
484pub struct HandlerDescriptor {
485 pub key: HandlerKey,
487 pub family: FamilyDescriptor,
489 #[serde(default, skip_serializing_if = "Vec::is_empty")]
492 pub layers: Vec<String>,
493}
494
495impl HandlerDescriptor {
496 pub fn tool(name: &str, description: impl Into<String>, parameters: serde_json::Value) -> Self {
499 Self {
500 key: tool_key(name),
501 family: FamilyDescriptor::Tool {
502 name: name.to_owned(),
503 description: description.into(),
504 parameters,
505 embedding: None,
506 },
507 layers: Vec::new(),
508 }
509 }
510}
511
512#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
516#[serde(tag = "family", rename_all = "snake_case")]
517pub enum FamilyDescriptor {
518 Completion {
520 model: ModelRef,
522 capabilities: ProviderCapabilities,
524 },
525 Tool {
527 name: String,
529 description: String,
531 parameters: serde_json::Value,
533 #[serde(default, skip_serializing_if = "Option::is_none")]
535 embedding: Option<ToolEmbeddingDescriptor>,
536 },
537 Embed {
539 model: String,
541 #[serde(default, skip_serializing_if = "Option::is_none")]
543 dims: Option<usize>,
544 max_documents: usize,
546 modality: EmbedModality,
548 },
549 Rerank {
551 model: String,
553 max_documents: usize,
555 },
556 Retrieve {},
558 Custom {
560 kind: String,
562 },
563}
564
565impl FamilyDescriptor {
566 pub const fn family(&self) -> EffectFamily {
568 match self {
569 Self::Completion { .. } => EffectFamily::Completion,
570 Self::Tool { .. } => EffectFamily::Tool,
571 Self::Embed { .. } => EffectFamily::Embed,
572 Self::Rerank { .. } => EffectFamily::Rerank,
573 Self::Retrieve {} => EffectFamily::Retrieve,
574 Self::Custom { .. } => EffectFamily::Custom,
575 }
576 }
577}
578
579#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
582pub struct ToolEmbeddingDescriptor {
583 pub context: serde_json::Value,
585 pub embedding_docs: Vec<String>,
587}
588
589#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
591#[serde(rename_all = "snake_case")]
592pub enum EmbedModality {
593 Text,
595 Image,
597}
598
599#[derive(Debug, Clone, Serialize, Deserialize)]
601#[serde(tag = "effect", rename_all = "snake_case")]
602pub enum EffectKind {
603 Completion {
605 request: Arc<CompletionRequest>,
607 stream: bool,
609 },
610 ToolCall {
613 name: String,
615 args: String,
617 },
618 Embed {
620 inputs: EmbedInputs,
622 },
623 Rerank {
625 request: RerankRequest,
627 },
628 Retrieve {
630 query: RetrieveQuery,
632 },
633 Custom {
635 kind: Arc<str>,
637 payload: serde_json::Value,
639 },
640}
641
642impl From<&crate::message::ToolCall> for EffectKind {
655 fn from(call: &crate::message::ToolCall) -> Self {
656 Self::ToolCall {
657 name: call.function.name.as_str().to_owned(),
658 args: call.function.raw_arguments(),
659 }
660 }
661}
662
663impl EffectKind {
664 pub const fn family(&self) -> EffectFamily {
666 match self {
667 Self::Completion { .. } => EffectFamily::Completion,
668 Self::ToolCall { .. } => EffectFamily::Tool,
669 Self::Embed { .. } => EffectFamily::Embed,
670 Self::Rerank { .. } => EffectFamily::Rerank,
671 Self::Retrieve { .. } => EffectFamily::Retrieve,
672 Self::Custom { .. } => EffectFamily::Custom,
673 }
674 }
675
676 pub fn name(&self) -> &str {
679 match self {
680 Self::Custom { kind, .. } => kind,
681 Self::Completion { .. }
682 | Self::ToolCall { .. }
683 | Self::Embed { .. }
684 | Self::Rerank { .. }
685 | Self::Retrieve { .. } => self.family().name(),
686 }
687 }
688
689 pub const fn streams(&self) -> bool {
692 match self {
693 Self::Completion { stream, .. } => *stream,
694 Self::ToolCall { .. }
695 | Self::Embed { .. }
696 | Self::Rerank { .. }
697 | Self::Retrieve { .. }
698 | Self::Custom { .. } => false,
699 }
700 }
701}
702
703#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
706#[serde(tag = "modality", content = "inputs", rename_all = "snake_case")]
707pub enum EmbedInputs {
708 Texts(Vec<String>),
710 Images(Vec<Vec<u8>>),
712}
713
714#[derive(Debug, Clone, Serialize, Deserialize)]
719#[serde(tag = "query", rename_all = "snake_case")]
720pub enum RetrieveQuery {
721 TopN {
723 req: VectorSearchRequest<Filter<serde_json::Value>>,
725 },
726 TopNIds {
728 req: VectorSearchRequest<Filter<serde_json::Value>>,
730 },
731}
732
733#[derive(Debug, Clone, Serialize, Deserialize)]
735#[serde(tag = "outcome", rename_all = "snake_case")]
736pub enum Answered {
737 Completion(Arc<CompletionResponse>),
739 ToolResult {
743 result: ToolResult,
745 },
746 Embeddings(EmbedOutputs),
748 Reranked(RerankResponse),
750 Documents(RetrievedDocuments),
752 Custom {
754 payload: serde_json::Value,
756 },
757}
758
759impl Answered {
760 pub const fn family(&self) -> EffectFamily {
762 match self {
763 Self::Completion(_) => EffectFamily::Completion,
764 Self::ToolResult { .. } => EffectFamily::Tool,
765 Self::Embeddings(_) => EffectFamily::Embed,
766 Self::Reranked(_) => EffectFamily::Rerank,
767 Self::Documents(_) => EffectFamily::Retrieve,
768 Self::Custom { .. } => EffectFamily::Custom,
769 }
770 }
771}
772
773#[derive(Debug, Clone, Serialize, Deserialize)]
775#[serde(tag = "modality", content = "response", rename_all = "snake_case")]
776pub enum EmbedOutputs {
777 Texts(EmbeddingResponse),
779 Images(EmbeddingResponse),
781}
782
783#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
785#[serde(tag = "retrieved", content = "results", rename_all = "snake_case")]
786pub enum RetrievedDocuments {
787 Scored(
789 #[serde(deserialize_with = "crate::json_utils::floats")]
790 Vec<(f64, String, serde_json::Value)>,
791 ),
792 Ids(#[serde(deserialize_with = "crate::json_utils::floats")] Vec<(f64, String)>),
794}
795
796#[derive(Debug, Clone, Serialize, Deserialize)]
798pub struct EffectRecord {
799 #[serde(rename = "tool_output", deserialize_with = "Option::deserialize")]
806 pub published: Option<crate::tool::ToolResultContext>,
807 pub id: EffectId,
809 pub key: HandlerKey,
811 pub kind: EffectKind,
813 pub outcome: Result<Answered, ErrorReport>,
815 #[serde(default, skip_serializing_if = "Option::is_none")]
821 pub events: Option<StreamRecord>,
822 #[serde(default, skip_serializing_if = "Option::is_none")]
826 pub stream_origin: Option<crate::message::Origin>,
827 #[serde(default, skip_serializing_if = "Option::is_none")]
829 pub parent: Option<EffectId>,
830 #[serde(default, skip_serializing_if = "Option::is_none")]
833 pub scope: Option<std::sync::Arc<str>>,
834 #[serde(default, skip_serializing_if = "Option::is_none")]
838 pub purpose: Option<std::borrow::Cow<'static, str>>,
839 #[serde(default, skip_serializing_if = "Option::is_none")]
843 pub turn: Option<u64>,
844 #[serde(default, skip_serializing_if = "Option::is_none")]
846 pub call: Option<crate::conversation::CallRef>,
847 #[serde(default, skip_serializing_if = "Option::is_none")]
851 pub started_ms: Option<u64>,
852 #[serde(default, skip_serializing_if = "Option::is_none")]
858 pub first_item_ms: Option<u64>,
859 #[serde(default, skip_serializing_if = "Option::is_none")]
862 pub finished_ms: Option<u64>,
863 #[serde(default, skip_serializing_if = "Option::is_none")]
868 pub reviewed: Option<Result<Answered, ErrorReport>>,
869 #[serde(default, skip_serializing_if = "Disposition::is_ran")]
871 pub disposition: Disposition,
872 #[serde(default, skip_serializing_if = "Option::is_none")]
876 pub decided_by: Option<Decider>,
877}
878
879#[non_exhaustive]
881#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
882#[serde(rename_all = "snake_case")]
883pub enum Decider {
884 Person,
886 Plugin(Cow<'static, str>),
888}
889
890impl Decider {
891 pub fn plugin(name: impl Into<Cow<'static, str>>) -> Self {
893 Self::Plugin(name.into())
894 }
895}
896
897#[non_exhaustive]
901#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
902#[serde(rename_all = "snake_case")]
903pub enum Disposition {
904 #[default]
906 Ran,
907 AnsweredBeforeStart,
910 AnsweredWhileRunning,
913 Superseded,
915 Cancelled,
917}
918
919impl EffectRecord {
920 pub fn new(
926 id: EffectId,
927 key: HandlerKey,
928 kind: EffectKind,
929 outcome: Result<Answered, ErrorReport>,
930 ) -> Self {
931 Self {
932 published: None,
933 id,
934 key,
935 kind,
936 outcome,
937 events: None,
938 stream_origin: None,
939 parent: None,
940 scope: None,
941 purpose: None,
942 turn: None,
943 call: None,
944 started_ms: None,
945 first_item_ms: None,
946 finished_ms: None,
947 reviewed: None,
948 disposition: Disposition::Ran,
949 decided_by: None,
950 }
951 }
952}
953
954impl Disposition {
955 fn is_ran(&self) -> bool {
957 *self == Self::Ran
958 }
959}
960
961#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
964#[serde(transparent)]
965pub struct EffectRow(std::collections::BTreeMap<HandlerKey, EffectFamily>);
966
967#[derive(Debug, Clone, PartialEq, Eq)]
970pub struct RowGap {
971 pub key: HandlerKey,
973 pub needed: EffectFamily,
975 pub served: Option<EffectFamily>,
977}
978
979impl std::fmt::Display for RowGap {
980 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
981 match self.served {
982 Some(served) => write!(
983 f,
984 "`{}` is needed as {} but served as {served}",
985 self.key, self.needed
986 ),
987 None => write!(f, "`{}` ({}) is not served", self.key, self.needed),
988 }
989 }
990}
991
992#[derive(Debug, Clone, PartialEq, Eq)]
994pub enum RowDiff {
995 Missing {
997 key: HandlerKey,
999 family: EffectFamily,
1001 },
1002 Extra {
1004 key: HandlerKey,
1006 family: EffectFamily,
1008 },
1009 Family {
1011 key: HandlerKey,
1013 this: EffectFamily,
1015 other: EffectFamily,
1016 },
1017}
1018
1019impl std::fmt::Display for RowDiff {
1020 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1021 match self {
1022 Self::Missing { key, family } => write!(f, "`{key}` ({family}) is missing"),
1023 Self::Extra { key, family } => write!(f, "`{key}` ({family}) is extra"),
1024 Self::Family { key, this, other } => {
1025 write!(f, "`{key}` is {this} here and {other} there")
1026 }
1027 }
1028 }
1029}
1030
1031impl EffectRow {
1032 pub fn new() -> Self {
1034 Self::default()
1035 }
1036
1037 pub fn insert(&mut self, key: HandlerKey, family: EffectFamily) -> Option<EffectFamily> {
1039 self.0.insert(key, family)
1040 }
1041
1042 pub fn insert_if_absent(&mut self, key: HandlerKey, family: EffectFamily) {
1044 self.0.entry(key).or_insert(family);
1045 }
1046
1047 pub fn remove(&mut self, key: &HandlerKey) -> Option<EffectFamily> {
1049 self.0.remove(key)
1050 }
1051
1052 pub fn get(&self, key: &HandlerKey) -> Option<&EffectFamily> {
1054 self.0.get(key)
1055 }
1056
1057 pub fn contains_key(&self, key: &HandlerKey) -> bool {
1059 self.0.contains_key(key)
1060 }
1061
1062 pub fn keys(&self) -> impl Iterator<Item = &HandlerKey> {
1064 self.0.keys()
1065 }
1066
1067 pub fn iter(&self) -> impl Iterator<Item = (&HandlerKey, &EffectFamily)> {
1069 self.0.iter()
1070 }
1071
1072 pub fn len(&self) -> usize {
1074 self.0.len()
1075 }
1076
1077 pub fn is_empty(&self) -> bool {
1079 self.0.is_empty()
1080 }
1081
1082 pub fn is_subset_of(&self, handlers: &[HandlerDescriptor]) -> Result<(), RowGap> {
1085 for (key, needed) in &self.0 {
1086 let served = handlers
1087 .iter()
1088 .find(|descriptor| &descriptor.key == key)
1089 .map(|descriptor| descriptor.family.family());
1090 match served {
1091 Some(served) if served == *needed => {}
1092 served => {
1093 return Err(RowGap {
1094 key: key.clone(),
1095 needed: *needed,
1096 served,
1097 });
1098 }
1099 }
1100 }
1101 Ok(())
1102 }
1103
1104 pub fn diff(&self, other: &EffectRow) -> Vec<RowDiff> {
1107 let mut diffs = Vec::new();
1108 for (key, family) in &self.0 {
1109 match other.0.get(key) {
1110 None => diffs.push(RowDiff::Missing {
1111 key: key.clone(),
1112 family: *family,
1113 }),
1114 Some(theirs) if theirs != family => diffs.push(RowDiff::Family {
1115 key: key.clone(),
1116 this: *family,
1117 other: *theirs,
1118 }),
1119 Some(_) => {}
1120 }
1121 }
1122 for (key, family) in &other.0 {
1123 if !self.0.contains_key(key) {
1124 diffs.push(RowDiff::Extra {
1125 key: key.clone(),
1126 family: *family,
1127 });
1128 }
1129 }
1130 diffs
1131 }
1132}
1133
1134impl FromIterator<(HandlerKey, EffectFamily)> for EffectRow {
1135 fn from_iter<I: IntoIterator<Item = (HandlerKey, EffectFamily)>>(iter: I) -> Self {
1136 Self(iter.into_iter().collect())
1137 }
1138}
1139
1140impl<'a> IntoIterator for &'a EffectRow {
1141 type Item = (&'a HandlerKey, &'a EffectFamily);
1142 type IntoIter = std::collections::btree_map::Iter<'a, HandlerKey, EffectFamily>;
1143
1144 fn into_iter(self) -> Self::IntoIter {
1145 self.0.iter()
1146 }
1147}
1148
1149impl IntoIterator for EffectRow {
1150 type Item = (HandlerKey, EffectFamily);
1151 type IntoIter = std::collections::btree_map::IntoIter<HandlerKey, EffectFamily>;
1152
1153 fn into_iter(self) -> Self::IntoIter {
1154 self.0.into_iter()
1155 }
1156}
1157
1158const _: fn() = || {
1160 fn assert_wire<T: Clone + Send + Sync + 'static + Serialize + serde::de::DeserializeOwned>() {}
1161 assert_wire::<EffectId>();
1162 assert_wire::<HandlerKey>();
1163 assert_wire::<EffectFamily>();
1164 assert_wire::<HandlerDescriptor>();
1165 assert_wire::<FamilyDescriptor>();
1166 assert_wire::<ToolEmbeddingDescriptor>();
1167 assert_wire::<EmbedModality>();
1168 assert_wire::<EffectKind>();
1169 assert_wire::<EmbedInputs>();
1170 assert_wire::<RerankRequest>();
1171 assert_wire::<RetrieveQuery>();
1172 assert_wire::<Answered>();
1173 assert_wire::<EmbedOutputs>();
1174 assert_wire::<RetrievedDocuments>();
1175 assert_wire::<EffectRecord>();
1176 assert_wire::<Decider>();
1177 assert_wire::<EffectRow>();
1178 assert_wire::<StreamRecord>();
1179};
1180
1181#[cfg(test)]
1182mod tests;