1use std::{collections::BTreeMap, fmt, sync::Arc};
7
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10use serde_json::json;
11use stateknot_core::{
12 AgentAdmissionAuthority, AgentAdmissionBudgetLayer, AgentDescriptor, AgentRequest,
13 AgentSubmissionKey, BoundedJson, BoxFuture, CapabilityIdentity, CheckpointState, CompiledGraph,
14 Digest, EventId, Failure, FailureCategory, FailureCode, FailureId, FailureMessage,
15 FailureOrigin, GraphReference, GraphSchemaValidationError, JournalAppend, JournalEventIntent,
16 JournalEventKind, JournalExpectation, JournalPayload, PrincipalIdentity, RetryAdvice,
17 RunCancellationRequest, RunId, RunStatus, RunTransition, TenantId,
18};
19use stateknot_store_postgres::{
20 AppendOutcome, PostgresStore, RunProjection, StoreError, WaitAbandonmentCommitOutcome,
21};
22use thiserror::Error;
23
24mod activity;
25pub mod policy;
26mod readiness;
27pub use activity::AgentRunActivityPage;
28pub use readiness::AgentServiceReadinessError;
29
30use crate::{
31 AgentRunAdmissionOutcome, AgentRunIds, AgentRunSnapshot, DurableAgentAdmissionError,
32 DurableAgentAdmissionRequest, DurableAgentAdmissionRequestError, DurableAgentRuns,
33 DurableAgentRunsBuildError, DurableAgentRunsError, ExecutableGraphRegistry,
34 ProviderNativeAgentGraph, StandardAgentServiceControlSchemaError,
35 standard_agent_service_control_event_schema,
36};
37
38pub const AGENT_SERVICE_API_VERSION: u16 = 1;
40
41#[derive(Clone, Debug, Eq, PartialEq)]
48pub struct AgentServiceCaller {
49 tenant_id: TenantId,
50 principal: PrincipalIdentity,
51}
52
53impl AgentServiceCaller {
54 #[must_use]
56 pub const fn new(tenant_id: TenantId, principal: PrincipalIdentity) -> Self {
57 Self {
58 tenant_id,
59 principal,
60 }
61 }
62
63 #[must_use]
65 pub const fn tenant_id(&self) -> &TenantId {
66 &self.tenant_id
67 }
68
69 #[must_use]
71 pub const fn principal(&self) -> &PrincipalIdentity {
72 &self.principal
73 }
74}
75
76#[derive(Clone, Debug)]
82pub struct AgentServiceSubmissionAuthorization {
83 caller: AgentServiceCaller,
84 agent: CapabilityIdentity,
85 request: AgentRequest,
86}
87
88impl AgentServiceSubmissionAuthorization {
89 #[must_use]
91 pub const fn caller(&self) -> &AgentServiceCaller {
92 &self.caller
93 }
94
95 #[must_use]
97 pub const fn agent(&self) -> &CapabilityIdentity {
98 &self.agent
99 }
100
101 #[must_use]
103 pub const fn request(&self) -> &AgentRequest {
104 &self.request
105 }
106}
107
108#[derive(Clone, Debug, Eq, PartialEq)]
110#[non_exhaustive]
111pub enum AgentServiceRunTarget {
112 Run(RunId),
114 Submission(Digest),
116}
117
118#[derive(Clone, Copy, Debug, Eq, PartialEq)]
120#[non_exhaustive]
121pub enum AgentServiceRunOperation {
122 Read,
124 Cancel,
126}
127
128#[derive(Clone, Debug, Eq, PartialEq)]
130pub struct AgentServiceRunAuthorization {
131 caller: AgentServiceCaller,
132 target: AgentServiceRunTarget,
133 operation: AgentServiceRunOperation,
134}
135
136impl AgentServiceRunAuthorization {
137 #[must_use]
139 pub const fn caller(&self) -> &AgentServiceCaller {
140 &self.caller
141 }
142
143 #[must_use]
145 pub const fn target(&self) -> &AgentServiceRunTarget {
146 &self.target
147 }
148
149 #[must_use]
151 pub const fn operation(&self) -> AgentServiceRunOperation {
152 self.operation
153 }
154}
155
156#[derive(Clone, Debug)]
158pub struct AgentServiceSubmissionGrant {
159 authority: AgentAdmissionAuthority,
160 budget_layers: Vec<AgentAdmissionBudgetLayer>,
161}
162
163impl AgentServiceSubmissionGrant {
164 #[must_use]
166 pub fn new(
167 authority: AgentAdmissionAuthority,
168 budget_layers: Vec<AgentAdmissionBudgetLayer>,
169 ) -> Self {
170 Self {
171 authority,
172 budget_layers,
173 }
174 }
175
176 #[must_use]
178 pub const fn authority(&self) -> &AgentAdmissionAuthority {
179 &self.authority
180 }
181
182 #[must_use]
184 pub fn budget_layers(&self) -> &[AgentAdmissionBudgetLayer] {
185 &self.budget_layers
186 }
187}
188
189#[derive(Clone, Debug, Eq, PartialEq)]
191pub struct AgentServiceRunGrant {
192 principal: PrincipalIdentity,
193 policy: CapabilityIdentity,
194 policy_digest: Digest,
195 decision_digest: Digest,
196}
197
198impl AgentServiceRunGrant {
199 #[must_use]
201 pub const fn new(
202 principal: PrincipalIdentity,
203 policy: CapabilityIdentity,
204 policy_digest: Digest,
205 decision_digest: Digest,
206 ) -> Self {
207 Self {
208 principal,
209 policy,
210 policy_digest,
211 decision_digest,
212 }
213 }
214
215 #[must_use]
217 pub const fn principal(&self) -> &PrincipalIdentity {
218 &self.principal
219 }
220
221 #[must_use]
223 pub const fn policy(&self) -> &CapabilityIdentity {
224 &self.policy
225 }
226
227 #[must_use]
229 pub const fn policy_digest(&self) -> Digest {
230 self.policy_digest
231 }
232
233 #[must_use]
235 pub const fn decision_digest(&self) -> Digest {
236 self.decision_digest
237 }
238}
239
240#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
242#[non_exhaustive]
243pub enum AgentServiceAuthorizationError {
244 #[error("Agent service authentication was not accepted")]
246 Unauthenticated,
247 #[error("Agent service authorization was denied")]
249 Denied,
250 #[error("Agent service authorization is temporarily unavailable")]
252 Unavailable,
253 #[error("Agent service authorization evidence is invalid")]
255 InvalidEvidence,
256}
257
258pub trait AgentServiceAuthorizer: Send + Sync + 'static {
266 fn authorize_submission(
268 &self,
269 context: AgentServiceSubmissionAuthorization,
270 ) -> BoxFuture<'_, Result<AgentServiceSubmissionGrant, AgentServiceAuthorizationError>>;
271
272 fn authorize_run(
274 &self,
275 context: AgentServiceRunAuthorization,
276 ) -> BoxFuture<'_, Result<AgentServiceRunGrant, AgentServiceAuthorizationError>>;
277}
278
279pub trait AgentServiceDeployment: Send + Sync + 'static {
281 fn descriptor(&self) -> &AgentDescriptor;
283
284 fn graph(&self) -> &CompiledGraph;
286
287 fn initial_state(&self) -> Result<CheckpointState, AgentServiceDeploymentError>;
289}
290
291impl AgentServiceDeployment for ProviderNativeAgentGraph {
292 fn descriptor(&self) -> &AgentDescriptor {
293 ProviderNativeAgentGraph::descriptor(self)
294 }
295
296 fn graph(&self) -> &CompiledGraph {
297 ProviderNativeAgentGraph::graph(self)
298 }
299
300 fn initial_state(&self) -> Result<CheckpointState, AgentServiceDeploymentError> {
301 ProviderNativeAgentGraph::initial_state(self)
302 .map_err(|_| AgentServiceDeploymentError::InvalidInitialState)
303 }
304}
305
306#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
308#[non_exhaustive]
309pub enum AgentServiceDeploymentError {
310 #[error("Agent service deployment produced invalid initial state")]
312 InvalidInitialState,
313}
314
315struct AgentServiceBinding {
316 descriptor: AgentDescriptor,
317 graph: GraphReference,
318 deployment: Arc<dyn AgentServiceDeployment>,
319}
320
321#[derive(Default)]
323pub struct AgentServiceRegistryBuilder {
324 bindings: BTreeMap<CapabilityIdentity, AgentServiceBinding>,
325}
326
327impl AgentServiceRegistryBuilder {
328 pub const MAX_BINDINGS: usize = 4096;
330
331 #[must_use]
333 pub fn new() -> Self {
334 Self::default()
335 }
336
337 pub fn register(
344 &mut self,
345 deployment: Arc<dyn AgentServiceDeployment>,
346 ) -> Result<(), AgentServiceRegistryError> {
347 if self.bindings.len() == Self::MAX_BINDINGS {
348 return Err(AgentServiceRegistryError::TooManyBindings);
349 }
350 let descriptor = deployment.descriptor().clone();
351 let graph = deployment.graph();
352 if descriptor.input_schema() != graph.input_schema()
353 || descriptor.output_schema() != graph.output_schema()
354 {
355 return Err(AgentServiceRegistryError::SchemaMismatch);
356 }
357 let graph = graph.reference();
358 let identity = descriptor.metadata().identity().clone();
359 if self.bindings.contains_key(&identity) {
360 return Err(AgentServiceRegistryError::DuplicateIdentity {
361 identity: Box::new(identity),
362 });
363 }
364 self.bindings.insert(
365 identity,
366 AgentServiceBinding {
367 descriptor,
368 graph,
369 deployment,
370 },
371 );
372 Ok(())
373 }
374
375 #[must_use]
377 pub fn build(self) -> AgentServiceRegistry {
378 AgentServiceRegistry {
379 bindings: Arc::new(self.bindings),
380 }
381 }
382}
383
384impl fmt::Debug for AgentServiceRegistryBuilder {
385 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
386 formatter
387 .debug_struct("AgentServiceRegistryBuilder")
388 .field("bindings", &self.bindings.len())
389 .finish_non_exhaustive()
390 }
391}
392
393#[derive(Clone)]
395pub struct AgentServiceRegistry {
396 bindings: Arc<BTreeMap<CapabilityIdentity, AgentServiceBinding>>,
397}
398
399impl AgentServiceRegistry {
400 fn resolve(
401 &self,
402 identity: &CapabilityIdentity,
403 ) -> Result<&AgentServiceBinding, AgentServiceRegistryError> {
404 let binding = self.bindings.get(identity).ok_or_else(|| {
405 AgentServiceRegistryError::MissingBinding {
406 identity: Box::new(identity.clone()),
407 }
408 })?;
409 if binding.deployment.descriptor() != &binding.descriptor
410 || binding.deployment.graph().reference() != binding.graph
411 {
412 return Err(AgentServiceRegistryError::DeploymentDrift {
413 identity: Box::new(identity.clone()),
414 });
415 }
416 Ok(binding)
417 }
418
419 #[must_use]
421 pub fn len(&self) -> usize {
422 self.bindings.len()
423 }
424
425 #[must_use]
427 pub fn is_empty(&self) -> bool {
428 self.bindings.is_empty()
429 }
430}
431
432impl fmt::Debug for AgentServiceRegistry {
433 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
434 formatter
435 .debug_struct("AgentServiceRegistry")
436 .field("bindings", &self.bindings.len())
437 .finish_non_exhaustive()
438 }
439}
440
441#[derive(Clone, Debug, Eq, Error, PartialEq)]
443#[non_exhaustive]
444pub enum AgentServiceRegistryError {
445 #[error("Agent service registry contains too many bindings")]
447 TooManyBindings,
448 #[error("Agent service identity was registered more than once")]
450 DuplicateIdentity {
451 identity: Box<CapabilityIdentity>,
453 },
454 #[error("Agent service identity has no installed deployment")]
456 MissingBinding {
457 identity: Box<CapabilityIdentity>,
459 },
460 #[error("Agent service descriptor and graph schemas do not match")]
462 SchemaMismatch,
463 #[error("Agent service deployment differs from its startup snapshot")]
465 DeploymentDrift {
466 identity: Box<CapabilityIdentity>,
468 },
469}
470
471#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
476#[serde(deny_unknown_fields)]
477pub struct AgentCancellationIds {
478 event_id: EventId,
479 failure_id: FailureId,
480}
481
482impl AgentCancellationIds {
483 #[must_use]
485 pub const fn new(event_id: EventId, failure_id: FailureId) -> Self {
486 Self {
487 event_id,
488 failure_id,
489 }
490 }
491
492 #[must_use]
494 pub fn generate() -> Self {
495 Self::new(EventId::generate(), FailureId::generate())
496 }
497
498 #[must_use]
500 pub const fn event_id(self) -> EventId {
501 self.event_id
502 }
503
504 #[must_use]
506 pub const fn failure_id(self) -> FailureId {
507 self.failure_id
508 }
509}
510
511#[derive(Clone, Debug)]
513#[non_exhaustive]
514pub enum AgentCancellationOutcome {
515 Committed(AgentRunSnapshot),
517 Idempotent(AgentRunSnapshot),
519}
520
521impl AgentCancellationOutcome {
522 #[must_use]
524 pub const fn snapshot(&self) -> &AgentRunSnapshot {
525 match self {
526 Self::Committed(snapshot) | Self::Idempotent(snapshot) => snapshot,
527 }
528 }
529}
530
531#[derive(Clone)]
534pub struct AgentServiceV1 {
535 store: PostgresStore,
536 runs: DurableAgentRuns,
537 deployments: AgentServiceRegistry,
538 authorizer: Arc<dyn AgentServiceAuthorizer>,
539 schemas: crate::JsonSchemaRegistry,
540 control_event_schema: stateknot_core::SchemaReference,
541}
542
543impl AgentServiceV1 {
544 pub fn new(
552 store: PostgresStore,
553 executable: ExecutableGraphRegistry,
554 deployments: AgentServiceRegistry,
555 authorizer: Arc<dyn AgentServiceAuthorizer>,
556 ) -> Result<Self, AgentServiceBuildError> {
557 let (control_event_schema, _) = standard_agent_service_control_event_schema()?;
558 if !executable.schemas().contains(&control_event_schema) {
559 return Err(AgentServiceBuildError::ControlEventSchemaUnavailable);
560 }
561 let schemas = executable.schemas().clone();
562 let runs = DurableAgentRuns::new(store.clone(), executable)?;
563 Ok(Self {
564 store,
565 runs,
566 deployments,
567 authorizer,
568 schemas,
569 control_event_schema,
570 })
571 }
572
573 pub fn submit<'service>(
585 &'service self,
586 caller: AgentServiceCaller,
587 key: &'service AgentSubmissionKey,
588 agent: &'service CapabilityIdentity,
589 request: AgentRequest,
590 ) -> BoxFuture<'service, Result<AgentRunAdmissionOutcome, AgentServiceError>> {
591 Box::pin(self.submit_inner(caller, key, agent, request))
592 }
593
594 async fn submit_inner(
595 &self,
596 caller: AgentServiceCaller,
597 key: &AgentSubmissionKey,
598 agent: &CapabilityIdentity,
599 request: AgentRequest,
600 ) -> Result<AgentRunAdmissionOutcome, AgentServiceError> {
601 let grant = self
602 .authorizer
603 .authorize_submission(AgentServiceSubmissionAuthorization {
604 caller: caller.clone(),
605 agent: agent.clone(),
606 request: request.clone(),
607 })
608 .await?;
609 if grant.authority().principal() != caller.principal() {
610 return Err(AgentServiceError::AuthorizationPrincipalMismatch);
611 }
612 let binding = self.deployments.resolve(agent)?;
613 if let Some(outcome) = self
614 .recover_submission(
615 &caller,
616 key,
617 &binding.descriptor,
618 &request,
619 &binding.graph,
620 &grant,
621 )
622 .await?
623 {
624 return Ok(outcome);
625 }
626 let initial_state = binding.deployment.initial_state()?;
627 if initial_state.schema() != binding.graph.state_schema() {
628 return Err(AgentServiceError::Deployment(
629 AgentServiceDeploymentError::InvalidInitialState,
630 ));
631 }
632 let durable = DurableAgentAdmissionRequest::new(
633 caller.tenant_id().clone(),
634 AgentRunIds::generate(),
635 binding.descriptor.clone(),
636 request.clone(),
637 grant.budget_layers.clone(),
638 binding.graph.clone(),
639 grant.authority.clone(),
640 initial_state,
641 )?;
642 match self.runs.submit(key, durable).await {
643 Ok(outcome) => Ok(outcome),
644 Err(DurableAgentRunsError::Admission(DurableAgentAdmissionError::Store(
645 StoreError::AgentSubmissionConflict,
646 ))) => self
647 .recover_submission(
648 &caller,
649 key,
650 &binding.descriptor,
651 &request,
652 &binding.graph,
653 &grant,
654 )
655 .await?
656 .ok_or(AgentServiceError::SubmissionConflict),
657 Err(error) => Err(error.into()),
658 }
659 }
660
661 pub async fn load(
667 &self,
668 caller: AgentServiceCaller,
669 run_id: RunId,
670 ) -> Result<AgentRunSnapshot, AgentServiceError> {
671 self.authorize_run(
672 &caller,
673 AgentServiceRunTarget::Run(run_id),
674 AgentServiceRunOperation::Read,
675 )
676 .await?;
677 self.runs
678 .load(caller.tenant_id(), run_id)
679 .await
680 .map_err(Into::into)
681 }
682
683 pub async fn load_by_key(
689 &self,
690 caller: AgentServiceCaller,
691 key: &AgentSubmissionKey,
692 ) -> Result<AgentRunSnapshot, AgentServiceError> {
693 self.authorize_run(
694 &caller,
695 AgentServiceRunTarget::Submission(key.digest_for(caller.tenant_id())),
696 AgentServiceRunOperation::Read,
697 )
698 .await?;
699 self.runs
700 .load_by_key(caller.tenant_id(), key)
701 .await
702 .map_err(Into::into)
703 }
704
705 pub async fn request_cancellation(
718 &self,
719 caller: AgentServiceCaller,
720 run_id: RunId,
721 ids: AgentCancellationIds,
722 ) -> Result<AgentCancellationOutcome, AgentServiceError> {
723 let grant = self
724 .authorize_run(
725 &caller,
726 AgentServiceRunTarget::Run(run_id),
727 AgentServiceRunOperation::Cancel,
728 )
729 .await?;
730 let stored = self
731 .store
732 .load_agent_admission(caller.tenant_id(), run_id)
733 .await?;
734 let lifecycle = stored.run().lifecycle();
735 if let Some(existing) = lifecycle.cancellation_request() {
736 if existing.failure().id() != ids.failure_id
737 || existing.failure().caused_by_event_id() != Some(ids.event_id)
738 {
739 return Err(AgentServiceError::ConflictingCancellation);
740 }
741 let snapshot = self.runs.load(caller.tenant_id(), run_id).await?;
742 return Ok(AgentCancellationOutcome::Idempotent(snapshot));
743 }
744 if lifecycle.status().is_terminal() {
745 return Err(AgentServiceError::TerminalRun);
746 }
747 if lifecycle.status() == RunStatus::Pending {
748 return Err(AgentServiceError::InvalidRunState);
749 }
750
751 let requested_at = self.store.observe_database_clock().await?;
752 let failure = cancellation_failure(ids.failure_id).with_caused_by_event(ids.event_id);
753 let request = RunCancellationRequest::new(failure, requested_at)
754 .map_err(|_| AgentServiceError::ControlEventInvariant)?;
755 let data = BoundedJson::try_from_value(json!({
756 "operation": "agent_cancellation_requested",
757 "admission_digest": digest_hex(stored.admission().digest()),
758 "policy_digest": digest_hex(grant.policy_digest()),
759 "decision_digest": digest_hex(grant.decision_digest()),
760 "failure_id": ids.failure_id.to_string()
761 }))
762 .map_err(|_| AgentServiceError::ControlEventInvariant)?;
763 self.runs_registry()
764 .validate_bounded(&self.control_event_schema, &data)
765 .map_err(AgentServiceError::control_schema)?;
766 let payload = JournalPayload::new(
767 self.control_event_schema.clone(),
768 JournalEventKind::new("agent-cancellation-requested")
769 .map_err(|_| AgentServiceError::ControlEventInvariant)?,
770 data,
771 )
772 .map_err(|_| AgentServiceError::ControlEventInvariant)?;
773 let intent = JournalEventIntent::control_plane(
774 caller.tenant_id().clone(),
775 run_id,
776 ids.event_id,
777 payload,
778 )
779 .map_err(|_| AgentServiceError::ControlEventInvariant)?;
780 let head = stored
781 .run()
782 .journal_head()
783 .cloned()
784 .ok_or(AgentServiceError::InvalidRunState)?;
785 let append = JournalAppend::new(JournalExpectation::exact(head), intent)
786 .map_err(|_| AgentServiceError::ControlEventInvariant)?;
787 let transition = RunTransition::RequestCancellation { request };
788 let committed = if lifecycle.status() == RunStatus::Waiting {
789 matches!(
790 self.store
791 .append_control_plane_abandon_waits(append, lifecycle.revision(), transition,)
792 .await?,
793 WaitAbandonmentCommitOutcome::Committed { .. }
794 )
795 } else {
796 matches!(
797 self.store
798 .append_control_plane(
799 append,
800 RunProjection::transition(lifecycle.revision(), transition),
801 )
802 .await?,
803 AppendOutcome::Committed(_)
804 )
805 };
806 let snapshot = self.runs.load(caller.tenant_id(), run_id).await?;
807 Ok(if committed {
808 AgentCancellationOutcome::Committed(snapshot)
809 } else {
810 AgentCancellationOutcome::Idempotent(snapshot)
811 })
812 }
813
814 async fn authorize_run(
815 &self,
816 caller: &AgentServiceCaller,
817 target: AgentServiceRunTarget,
818 operation: AgentServiceRunOperation,
819 ) -> Result<AgentServiceRunGrant, AgentServiceError> {
820 let grant = self
821 .authorizer
822 .authorize_run(AgentServiceRunAuthorization {
823 caller: caller.clone(),
824 target,
825 operation,
826 })
827 .await?;
828 if grant.principal() != caller.principal() {
829 return Err(AgentServiceError::AuthorizationPrincipalMismatch);
830 }
831 Ok(grant)
832 }
833
834 async fn recover_submission(
835 &self,
836 caller: &AgentServiceCaller,
837 key: &AgentSubmissionKey,
838 descriptor: &AgentDescriptor,
839 request: &AgentRequest,
840 graph: &GraphReference,
841 grant: &AgentServiceSubmissionGrant,
842 ) -> Result<Option<AgentRunAdmissionOutcome>, AgentServiceError> {
843 let stored = match self
844 .store
845 .load_agent_submission(caller.tenant_id(), key)
846 .await
847 {
848 Ok(stored) => stored,
849 Err(StoreError::AgentSubmissionNotFound) => return Ok(None),
850 Err(error) => return Err(error.into()),
851 };
852 let intent = stored.admission().admission().intent();
853 if intent.provenance().tenant_id() != caller.tenant_id()
854 || intent.descriptor() != descriptor
855 || intent.request() != request
856 || intent.budget_layers() != grant.budget_layers()
857 || intent.graph() != graph
858 || intent.authority() != grant.authority()
859 {
860 return Err(AgentServiceError::SubmissionConflict);
861 }
862 let snapshot = self.runs.load_by_key(caller.tenant_id(), key).await?;
863 Ok(Some(AgentRunAdmissionOutcome::Idempotent(snapshot)))
864 }
865
866 fn runs_registry(&self) -> &crate::JsonSchemaRegistry {
867 &self.schemas
868 }
869}
870
871impl fmt::Debug for AgentServiceV1 {
872 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
873 formatter
874 .debug_struct("AgentServiceV1")
875 .field("api_version", &AGENT_SERVICE_API_VERSION)
876 .field("deployments", &self.deployments)
877 .field("control_event_schema", &self.control_event_schema)
878 .finish_non_exhaustive()
879 }
880}
881
882#[derive(Clone, Debug, Eq, Error, PartialEq)]
884#[non_exhaustive]
885pub enum AgentServiceBuildError {
886 #[error(transparent)]
888 Runs(#[from] DurableAgentRunsBuildError),
889 #[error(transparent)]
891 ControlEventSchema(#[from] StandardAgentServiceControlSchemaError),
892 #[error("standard Agent service control event schema is unavailable")]
894 ControlEventSchemaUnavailable,
895}
896
897#[derive(Debug, Error)]
899#[non_exhaustive]
900pub enum AgentServiceError {
901 #[error(transparent)]
903 Registry(#[from] AgentServiceRegistryError),
904 #[error(transparent)]
906 Authorization(#[from] AgentServiceAuthorizationError),
907 #[error("Agent service authorization principal does not match the caller")]
909 AuthorizationPrincipalMismatch,
910 #[error(transparent)]
912 Deployment(#[from] AgentServiceDeploymentError),
913 #[error(transparent)]
915 AdmissionRequest(#[from] DurableAgentAdmissionRequestError),
916 #[error(transparent)]
918 Runs(#[from] DurableAgentRunsError),
919 #[error(transparent)]
921 Store(#[from] StoreError),
922 #[error("Agent run has a different committed cancellation request")]
924 ConflictingCancellation,
925 #[error("Agent submission key was reused with different content")]
927 SubmissionConflict,
928 #[error("terminal Agent run cannot accept cancellation")]
930 TerminalRun,
931 #[error("Agent run is not in a cancellable durable state")]
933 InvalidRunState,
934 #[error("Agent service control event could not be constructed")]
936 ControlEventInvariant,
937 #[error("Agent service control event schema validation failed: {source}")]
939 ControlEventSchema {
940 #[source]
942 source: GraphSchemaValidationError,
943 },
944}
945
946impl AgentServiceError {
947 const fn control_schema(source: GraphSchemaValidationError) -> Self {
948 Self::ControlEventSchema { source }
949 }
950}
951
952fn cancellation_failure(id: FailureId) -> Failure {
953 Failure::new(
954 id,
955 FailureCategory::Cancelled,
956 FailureCode::new("agent.service.cancelled_by_caller")
957 .expect("static cancellation failure code is valid"),
958 FailureOrigin::new("stateknot.runtime.agent_service")
959 .expect("static cancellation failure origin is valid"),
960 FailureMessage::new("The Agent run was cancelled by an authorized caller.")
961 .expect("static cancellation message is valid"),
962 RetryAdvice::Never,
963 )
964 .expect("static cancellation failure semantics are coherent")
965}
966
967fn digest_hex(digest: Digest) -> String {
968 const HEX: &[u8; 16] = b"0123456789abcdef";
969 let mut value = String::with_capacity(Digest::SHA256_LEN * 2);
970 for byte in digest.as_bytes() {
971 value.push(char::from(HEX[usize::from(byte >> 4)]));
972 value.push(char::from(HEX[usize::from(byte & 0x0f)]));
973 }
974 value
975}