Skip to main content

stateknot_runtime/
agent_service.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Versioned, authorization-first public service boundary for durable Agents.
5
6use 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
38/// The stable major version of this service contract.
39pub const AGENT_SERVICE_API_VERSION: u16 = 1;
40
41/// An authenticated caller supplied by the embedding transport after token or
42/// mTLS verification.
43///
44/// Construction does not authenticate identity. The embedding service must
45/// derive this value from a verified credential and install an
46/// [`AgentServiceAuthorizer`] that independently evaluates every operation.
47#[derive(Clone, Debug, Eq, PartialEq)]
48pub struct AgentServiceCaller {
49    tenant_id: TenantId,
50    principal: PrincipalIdentity,
51}
52
53impl AgentServiceCaller {
54    /// Binds one authenticated principal to an exact tenant boundary.
55    #[must_use]
56    pub const fn new(tenant_id: TenantId, principal: PrincipalIdentity) -> Self {
57        Self {
58            tenant_id,
59            principal,
60        }
61    }
62
63    /// Returns the tenant selected by authenticated ingress policy.
64    #[must_use]
65    pub const fn tenant_id(&self) -> &TenantId {
66        &self.tenant_id
67    }
68
69    /// Returns the exact authenticated issuer/subject pair.
70    #[must_use]
71    pub const fn principal(&self) -> &PrincipalIdentity {
72        &self.principal
73    }
74}
75
76/// Complete trusted input to an Agent submission authorization decision.
77///
78/// The requested identity is carried instead of a resolved deployment so this
79/// decision can run before the service reveals whether that exact revision is
80/// installed.
81#[derive(Clone, Debug)]
82pub struct AgentServiceSubmissionAuthorization {
83    caller: AgentServiceCaller,
84    agent: CapabilityIdentity,
85    request: AgentRequest,
86}
87
88impl AgentServiceSubmissionAuthorization {
89    /// Returns the authenticated, tenant-bound caller.
90    #[must_use]
91    pub const fn caller(&self) -> &AgentServiceCaller {
92        &self.caller
93    }
94
95    /// Returns the exact Agent revision requested by the caller.
96    #[must_use]
97    pub const fn agent(&self) -> &CapabilityIdentity {
98        &self.agent
99    }
100
101    /// Returns the schema-bound request under consideration.
102    #[must_use]
103    pub const fn request(&self) -> &AgentRequest {
104        &self.request
105    }
106}
107
108/// Target form supplied to authorization without exposing a raw idempotency key.
109#[derive(Clone, Debug, Eq, PartialEq)]
110#[non_exhaustive]
111pub enum AgentServiceRunTarget {
112    /// A caller addressed one exact tenant-scoped run.
113    Run(RunId),
114    /// A caller addressed a tenant-scoped one-way submission-key digest.
115    Submission(Digest),
116}
117
118/// Run operation evaluated before any durable existence lookup.
119#[derive(Clone, Copy, Debug, Eq, PartialEq)]
120#[non_exhaustive]
121pub enum AgentServiceRunOperation {
122    /// Read the public, integrity-verified run snapshot.
123    Read,
124    /// Commit a durable cancellation request.
125    Cancel,
126}
127
128/// Complete trusted input to a run read or cancellation authorization decision.
129#[derive(Clone, Debug, Eq, PartialEq)]
130pub struct AgentServiceRunAuthorization {
131    caller: AgentServiceCaller,
132    target: AgentServiceRunTarget,
133    operation: AgentServiceRunOperation,
134}
135
136impl AgentServiceRunAuthorization {
137    /// Returns the authenticated, tenant-bound caller.
138    #[must_use]
139    pub const fn caller(&self) -> &AgentServiceCaller {
140        &self.caller
141    }
142
143    /// Returns the non-secret durable lookup target.
144    #[must_use]
145    pub const fn target(&self) -> &AgentServiceRunTarget {
146        &self.target
147    }
148
149    /// Returns the exact requested operation.
150    #[must_use]
151    pub const fn operation(&self) -> AgentServiceRunOperation {
152        self.operation
153    }
154}
155
156/// Granted submission policy snapshot returned by the trusted authorizer.
157#[derive(Clone, Debug)]
158pub struct AgentServiceSubmissionGrant {
159    authority: AgentAdmissionAuthority,
160    budget_layers: Vec<AgentAdmissionBudgetLayer>,
161}
162
163impl AgentServiceSubmissionGrant {
164    /// Constructs a granted admission snapshot and its restrictive policy layers.
165    #[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    /// Returns the immutable admission authority evidence.
177    #[must_use]
178    pub const fn authority(&self) -> &AgentAdmissionAuthority {
179        &self.authority
180    }
181
182    /// Returns policy-selected restrictive budget layers.
183    #[must_use]
184    pub fn budget_layers(&self) -> &[AgentAdmissionBudgetLayer] {
185        &self.budget_layers
186    }
187}
188
189/// Public-safe proof that a trusted policy granted run access.
190#[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    /// Constructs an exact run-access policy decision reference.
200    #[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    /// Returns the principal for which the policy decision was made.
216    #[must_use]
217    pub const fn principal(&self) -> &PrincipalIdentity {
218        &self.principal
219    }
220
221    /// Returns the exact policy implementation identity.
222    #[must_use]
223    pub const fn policy(&self) -> &CapabilityIdentity {
224        &self.policy
225    }
226
227    /// Returns the immutable policy artifact checksum.
228    #[must_use]
229    pub const fn policy_digest(&self) -> Digest {
230        self.policy_digest
231    }
232
233    /// Returns the immutable decision evidence checksum.
234    #[must_use]
235    pub const fn decision_digest(&self) -> Digest {
236        self.decision_digest
237    }
238}
239
240/// Closed authorization failure returned to the service boundary.
241#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
242#[non_exhaustive]
243pub enum AgentServiceAuthorizationError {
244    /// No authenticated identity was accepted for this operation.
245    #[error("Agent service authentication was not accepted")]
246    Unauthenticated,
247    /// Authenticated policy denied the exact operation.
248    #[error("Agent service authorization was denied")]
249    Denied,
250    /// The pinned policy implementation could not make a decision now.
251    #[error("Agent service authorization is temporarily unavailable")]
252    Unavailable,
253    /// The policy returned unverifiable decision evidence.
254    #[error("Agent service authorization evidence is invalid")]
255    InvalidEvidence,
256}
257
258/// Mandatory authorization boundary for every public Agent service operation.
259///
260/// Implementations run before database lookup. They must be deterministic for
261/// retained decision evidence, must not execute the Agent or its tools, and
262/// must never grant access solely because a run identifier is syntactically
263/// valid. Network policy engines require their own durable, bounded decision
264/// ledger outside this synchronous service facade.
265pub trait AgentServiceAuthorizer: Send + Sync + 'static {
266    /// Authorizes one exact Agent version and request before deployment lookup.
267    fn authorize_submission(
268        &self,
269        context: AgentServiceSubmissionAuthorization,
270    ) -> BoxFuture<'_, Result<AgentServiceSubmissionGrant, AgentServiceAuthorizationError>>;
271
272    /// Authorizes a read or cancellation before durable target lookup.
273    fn authorize_run(
274        &self,
275        context: AgentServiceRunAuthorization,
276    ) -> BoxFuture<'_, Result<AgentServiceRunGrant, AgentServiceAuthorizationError>>;
277}
278
279/// Executable Agent definition installed into the service registry.
280pub trait AgentServiceDeployment: Send + Sync + 'static {
281    /// Returns the immutable Agent descriptor selected at public ingress.
282    fn descriptor(&self) -> &AgentDescriptor;
283
284    /// Returns the exact executable graph pinned into durable admission.
285    fn graph(&self) -> &CompiledGraph;
286
287    /// Generates fresh bounded initial state for one candidate submission.
288    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/// Closed startup/runtime failure from an installed Agent definition.
307#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
308#[non_exhaustive]
309pub enum AgentServiceDeploymentError {
310    /// The installed implementation could not construct state matching its graph.
311    #[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/// Startup-only builder for immutable, exact-version Agent service bindings.
322#[derive(Default)]
323pub struct AgentServiceRegistryBuilder {
324    bindings: BTreeMap<CapabilityIdentity, AgentServiceBinding>,
325}
326
327impl AgentServiceRegistryBuilder {
328    /// Maximum exact Agent revisions installed in one service process.
329    pub const MAX_BINDINGS: usize = 4096;
330
331    /// Creates an empty service registry builder.
332    #[must_use]
333    pub fn new() -> Self {
334        Self::default()
335    }
336
337    /// Registers one exact executable Agent definition.
338    ///
339    /// # Errors
340    ///
341    /// Rejects capacity exhaustion, repeated identity, or descriptor/graph
342    /// input-output schema disagreement.
343    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    /// Freezes the startup snapshot.
376    #[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/// Immutable exact-version registry used by [`AgentServiceV1`].
394#[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    /// Returns the number of installed exact Agent revisions.
420    #[must_use]
421    pub fn len(&self) -> usize {
422        self.bindings.len()
423    }
424
425    /// Returns whether no Agent service deployment is installed.
426    #[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/// Exact service-deployment registry failure.
442#[derive(Clone, Debug, Eq, Error, PartialEq)]
443#[non_exhaustive]
444pub enum AgentServiceRegistryError {
445    /// The immutable process binding ceiling was reached.
446    #[error("Agent service registry contains too many bindings")]
447    TooManyBindings,
448    /// One exact owner/name/version identity was registered twice.
449    #[error("Agent service identity was registered more than once")]
450    DuplicateIdentity {
451        /// Repeated exact binding identity.
452        identity: Box<CapabilityIdentity>,
453    },
454    /// No installed service owns the requested exact Agent identity.
455    #[error("Agent service identity has no installed deployment")]
456    MissingBinding {
457        /// Missing exact binding identity.
458        identity: Box<CapabilityIdentity>,
459    },
460    /// An Agent descriptor and graph disagree about input or output schema.
461    #[error("Agent service descriptor and graph schemas do not match")]
462    SchemaMismatch,
463    /// An installed definition changed after the startup snapshot froze.
464    #[error("Agent service deployment differs from its startup snapshot")]
465    DeploymentDrift {
466        /// Drifted exact binding identity.
467        identity: Box<CapabilityIdentity>,
468    },
469}
470
471/// Stable caller-retained identities for one cancellation request.
472///
473/// The same value must be reused after timeout or lost acknowledgement. A new
474/// value represents a competing cancellation request rather than a retry.
475#[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    /// Binds caller-retained event and public failure identities.
484    #[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    /// Generates a fresh cancellation identity pair.
493    #[must_use]
494    pub fn generate() -> Self {
495        Self::new(EventId::generate(), FailureId::generate())
496    }
497
498    /// Returns the stable control-plane journal event identity.
499    #[must_use]
500    pub const fn event_id(self) -> EventId {
501        self.event_id
502    }
503
504    /// Returns the stable cancellation failure occurrence identity.
505    #[must_use]
506    pub const fn failure_id(self) -> FailureId {
507        self.failure_id
508    }
509}
510
511/// Result of a durable, idempotent public cancellation request.
512#[derive(Clone, Debug)]
513#[non_exhaustive]
514pub enum AgentCancellationOutcome {
515    /// A new cancellation intent committed atomically.
516    Committed(AgentRunSnapshot),
517    /// The same cancellation failure had already committed.
518    Idempotent(AgentRunSnapshot),
519}
520
521impl AgentCancellationOutcome {
522    /// Returns the fully revalidated current public snapshot.
523    #[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/// Production service facade for exact-version durable Agent submission,
532/// authorization-first reads, and two-phase cancellation.
533#[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    /// Binds one durable provider, executable deployment, public Agent registry,
545    /// and mandatory authorizer.
546    ///
547    /// # Errors
548    ///
549    /// Rejects malformed embedded schemas or a deployment registry that omitted
550    /// either the admission or service-control schema.
551    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    /// Authorizes and durably submits one exact Agent version under a
574    /// tenant-scoped idempotency key.
575    ///
576    /// Candidate run/checkpoint/event identities and initial state are generated
577    /// only after authorization grants the request. Lost acknowledgements are
578    /// recovered by calling this method again with the same key and content.
579    ///
580    /// # Errors
581    ///
582    /// Returns closed registry, authorization, state, admission, or storage
583    /// failures. No process-local execution path can bypass durable admission.
584    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    /// Authorizes before loading one tenant-scoped public run snapshot.
662    ///
663    /// # Errors
664    ///
665    /// Authorization failures precede and therefore hide not-found results.
666    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    /// Authorizes before resolving an opaque submission key to a public run.
684    ///
685    /// # Errors
686    ///
687    /// Authorization failures precede and therefore hide key existence.
688    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    /// Authorizes and atomically commits cancellation intent before workers
706    /// cooperatively stop and the durable lifecycle confirms cancellation.
707    ///
708    /// Waiting runs abandon every outstanding interrupt/timer in the same
709    /// transaction. Active runs append the request and lifecycle projection in
710    /// one transaction. A retry with the same [`AgentCancellationIds`] returns
711    /// idempotently after either request or final confirmation has committed.
712    ///
713    /// # Errors
714    ///
715    /// Returns authorization, terminal/conflicting cancellation, schema,
716    /// optimistic concurrency, integrity, or database failures.
717    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/// Startup failure for [`AgentServiceV1`].
883#[derive(Clone, Debug, Eq, Error, PartialEq)]
884#[non_exhaustive]
885pub enum AgentServiceBuildError {
886    /// The lower-level public durable run facade could not start.
887    #[error(transparent)]
888    Runs(#[from] DurableAgentRunsBuildError),
889    /// The embedded control event schema was malformed.
890    #[error(transparent)]
891    ControlEventSchema(#[from] StandardAgentServiceControlSchemaError),
892    /// The executable deployment omitted the standard service control schema.
893    #[error("standard Agent service control event schema is unavailable")]
894    ControlEventSchemaUnavailable,
895}
896
897/// Payload-redacted failure from the versioned Agent service boundary.
898#[derive(Debug, Error)]
899#[non_exhaustive]
900pub enum AgentServiceError {
901    /// Exact Agent service deployment selection failed.
902    #[error(transparent)]
903    Registry(#[from] AgentServiceRegistryError),
904    /// Mandatory ingress policy rejected or could not evaluate the operation.
905    #[error(transparent)]
906    Authorization(#[from] AgentServiceAuthorizationError),
907    /// Authorization evidence named a different authenticated principal.
908    #[error("Agent service authorization principal does not match the caller")]
909    AuthorizationPrincipalMismatch,
910    /// Installed initial-state generation failed closed.
911    #[error(transparent)]
912    Deployment(#[from] AgentServiceDeploymentError),
913    /// Durable admission request construction failed.
914    #[error(transparent)]
915    AdmissionRequest(#[from] DurableAgentAdmissionRequestError),
916    /// Public durable run admission or verification failed.
917    #[error(transparent)]
918    Runs(#[from] DurableAgentRunsError),
919    /// Durable provider mutation or integrity verification failed.
920    #[error(transparent)]
921    Store(#[from] StoreError),
922    /// Another cancellation occurrence already owns this lifecycle.
923    #[error("Agent run has a different committed cancellation request")]
924    ConflictingCancellation,
925    /// An idempotency key was reused for different logical submission content.
926    #[error("Agent submission key was reused with different content")]
927    SubmissionConflict,
928    /// A non-cancelled terminal run cannot accept cancellation.
929    #[error("terminal Agent run cannot accept cancellation")]
930    TerminalRun,
931    /// Durable facts formed a state unsupported by this service mutation.
932    #[error("Agent run is not in a cancellable durable state")]
933    InvalidRunState,
934    /// Framework-owned control event construction failed an invariant.
935    #[error("Agent service control event could not be constructed")]
936    ControlEventInvariant,
937    /// Framework-owned control event data failed its embedded schema.
938    #[error("Agent service control event schema validation failed: {source}")]
939    ControlEventSchema {
940        /// Closed schema validation result.
941        #[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}