//! Application entry of durable background Tasks (Story 4.2, FR-22/FR-23). //! //! The entry takes an already authenticated principal (a verified machine credential, or an //! administrator identity verified by the calling admin surface), resolves the exact published Tool, //! repeats the caller's authorization, pins the Published Version/policy/deadline and delegates the //! durable acceptance to the runtime Task service. The repository owns the transaction, so the //! returned Task ID exists only after Task + dispatch intent + queue slot committed. //! //! Deliberately not wired: the public MCP `tools/call`/Tasks wire (Story 4.7) and the worker/leases //! (Story 4.3). The existing synchronous/unsupported `tools/call` path is unchanged, and this entry //! never spawns an ephemeral execution future. use std::sync::Arc; use std::time::{Duration, Instant}; use crank_core::{ CorrelationContext, PlatformApiKeyId, TaskAcceptance, TaskAccess, TaskError, TaskId, TaskOwnerKind, TaskRecord, ToolExecutionMode, }; use crank_registry::{PostgresRegistry, PublishedAgentTool}; use crank_runtime::{TaskAcceptDraft, TaskOutcome, TaskService}; use serde_json::Value; use crate::access::credential_allows_security_level; use crate::catalog::PublishedToolCatalog; /// Authenticated principal of one Task operation. The authorization scope identity is derived here /// from the verified credential/admin identity, never from a caller-supplied request string. #[derive(Clone, Debug)] pub enum TaskPrincipal { Agent { workspace_slug: String, agent_slug: String, credential: crank_core::VerifiedMachineCredential, }, /// Administrator identity that the admin surface already authenticated. It is never a wildcard: /// owner, workspace and authorization scope all participate in the stored predicate. Admin { workspace_slug: String, agent_slug: String, user_id: String, }, } impl TaskPrincipal { fn workspace_slug(&self) -> &str { match self { Self::Agent { workspace_slug, .. } | Self::Admin { workspace_slug, .. } => { workspace_slug } } } fn agent_slug(&self) -> &str { match self { Self::Agent { agent_slug, .. } | Self::Admin { agent_slug, .. } => agent_slug, } } fn owner(&self, tool: &PublishedAgentTool) -> (TaskOwnerKind, String) { match self { Self::Agent { .. } => (TaskOwnerKind::Agent, tool.agent_id.as_str().to_owned()), Self::Admin { user_id, .. } => (TaskOwnerKind::Admin, user_id.clone()), } } /// Typed immutable Platform API key identity of this principal. A verified agent credential /// without a key ID cannot be revalidated by a worker, so it is refused instead of accepted; /// an administrator has no machine key and is stored as `None` (the worker fails closed). fn platform_api_key_id(&self) -> Result, TaskApplicationError> { match self { Self::Agent { credential, .. } => credential .platform_api_key_id .clone() .map(Some) .ok_or(TaskApplicationError::Denied), Self::Admin { .. } => Ok(None), } } /// Bounded server-derived authorization scope identity of this principal. fn authorization_scope(&self) -> String { let identity = match self { Self::Agent { credential, .. } => { let mut scopes = credential .scopes .iter() .map(|scope| format!("{scope:?}")) .collect::>(); scopes.sort(); format!( "key:{}|mode:{:?}|level:{:?}|scopes:{}", credential .platform_api_key_id .as_ref() .map(|id| id.as_str().to_owned()) .unwrap_or_else(|| "-".to_owned()), credential.machine_access_mode, credential.max_security_level, scopes.join(",") ) } Self::Admin { user_id, .. } => format!("admin:{user_id}"), }; identity.chars().take(160).collect() } } /// Typed refusal of the application entry. `NotFound`/`Denied` never reveal whether a foreign Task /// exists, and no variant carries Task payload or fingerprint. #[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] pub enum TaskApplicationError { #[error("task request was not found")] NotFound, #[error("task request is not authorized")] Denied, #[error("the published Tool policy does not accept durable background work")] NotBackground, #[error("the requested published Tool version is not available")] VersionUnavailable, #[error("this Tool requires a verified approval before acceptance")] ApprovalRequired, #[error(transparent)] Task(#[from] TaskError), } #[derive(Clone)] pub struct TaskApplication { catalog: PublishedToolCatalog, service: TaskService, } impl TaskApplication { /// Production construction of the application entry over the process registry, the published /// catalog and the durable Task service. pub fn new( registry: PostgresRegistry, refresh_interval: Duration, coordination_store: Arc, service: TaskService, ) -> Self { Self { catalog: PublishedToolCatalog::new(registry, refresh_interval, coordination_store), service, } } /// Runtime task service carrying encrypted executable input. pub fn task_service(&self) -> TaskService { self.service.clone() } /// Published catalog of the same application entry, for the durable Task worker's pre-dispatch /// revalidation. pub(super) fn catalog(&self) -> PublishedToolCatalog { self.catalog.clone() } /// Readiness of the durable Task store this entry depends on. pub async fn health(&self) -> Result<(), TaskError> { self.service.health().await } /// Accepts one background request for an already authenticated principal. /// /// `expected_version` is the caller's explicit Published Version pin. Without it the current /// publication is pinned for new work and a retry of the same scoped key returns the stored Task /// even after a newer publication. An explicit pin may only retry the Task accepted with that /// exact version: a different pin is a typed conflict, never a rebind. pub async fn accept_background( &self, principal: &TaskPrincipal, tool_name: &str, expected_version: Option, scoped_key: &str, input: &Value, correlation: &CorrelationContext, ) -> Result { let tool = self.resolve_authorized_tool(principal, tool_name).await?; let current_version = tool.operation.version; let Some(policy) = tool.operation.execution_config.execution_policy else { return Err(TaskApplicationError::NotBackground); }; if policy.mode == ToolExecutionMode::Synchronous { return Err(TaskApplicationError::NotBackground); } if tool .operation .execution_config .approval_policy .as_ref() .is_some_and(|approval| approval.required) { // Without a verified, non-consuming approval reference this entry fails closed instead // of accepting work a worker could never safely execute. return Err(TaskApplicationError::ApprovalRequired); } let platform_api_key_id = principal.platform_api_key_id()?; let draft = |operation_version: u32| { let (owner_kind, owner_id) = principal.owner(&tool); TaskAcceptDraft { workspace_id: tool.workspace_id.as_str().to_owned(), owner_kind, owner_id, authorization_scope: principal.authorization_scope(), platform_api_key_id: platform_api_key_id.clone(), operation_id: tool.operation.id.as_str().to_owned(), operation_version, policy_mode: policy.mode, scoped_key: scoped_key.to_owned(), input: input.clone(), correlation: correlation.clone(), deadline: Instant::now() + Duration::from_millis(policy.deadline_ms.max(1)), retention_ms: TaskService::default_retention_ms(), approval_reference: None, retry: task_retry_policy(&tool), } }; let Some(requested) = expected_version else { return Ok(self.service.accept(draft(current_version)).await?); }; let draft = draft(requested); match self.service.lookup(&draft).await? { Some(record) => { if record.input_fingerprint != TaskService::input_fingerprint(input)? { return Err(TaskApplicationError::Task(TaskError::FingerprintConflict)); } if record.pins.operation_version != requested { return Err(TaskApplicationError::VersionUnavailable); } Ok(TaskAcceptance { task_id: record.task_id, state: record.state, operation_version: record.pins.operation_version, support: record.support, created_at_unix_ms: record.created_at_unix_ms, retain_until_unix_ms: record.pins.retain_until_unix_ms, replayed: true, }) } None if requested == current_version => Ok(self.service.accept(draft).await?), // A new Task can only be accepted against the currently published version. None => Err(TaskApplicationError::VersionUnavailable), } } /// Owner-scoped status read of one Task of the addressed published Tool. pub async fn status( &self, principal: &TaskPrincipal, tool_name: &str, task_id: TaskId, ) -> Result { let access = self.task_access(principal, tool_name).await?; match self.service.status(&access, task_id).await { Ok(record) => Ok(record), Err(TaskError::NotFound) => Err(TaskApplicationError::NotFound), Err(error) => Err(TaskApplicationError::Task(error)), } } /// Owner-scoped result projection of one Task of the addressed published Tool. pub async fn result( &self, principal: &TaskPrincipal, tool_name: &str, task_id: TaskId, ) -> Result { let access = self.task_access(principal, tool_name).await?; match self.service.result(&access, task_id).await { Ok(outcome) => Ok(outcome), Err(TaskError::NotFound) => Err(TaskApplicationError::NotFound), Err(error) => Err(TaskApplicationError::Task(error)), } } /// Owner-scoped cancellation of one Task of the addressed published Tool (Story 4.4). /// /// Cancellation is decided by the durable store under a row lock: before the dispatch checkpoint /// it is an honest cancellation with zero outbound calls, after it the Task becomes the /// non-terminal uncertain outcome instead of a plain cancel or a retry. pub async fn cancel( &self, principal: &TaskPrincipal, tool_name: &str, task_id: TaskId, expected_version: Option, ) -> Result { let access = self.task_access(principal, tool_name).await?; match self .service .cancel(&access, task_id, expected_version, "user_cancelled") .await { Ok(outcome) => Ok(outcome), Err(TaskError::NotFound) => Err(TaskApplicationError::NotFound), Err(error) => Err(TaskApplicationError::Task(error)), } } /// Applies one additional validated input to a waiting Task (Story 4.5). /// /// This is the server-internal application entry: the public Task MCP API stays Story 4.7. The /// principal is already authenticated here, the owner scope is derived from the verified /// credential and the durable transaction revalidates the same key before any receipt lookup. /// An identical authorized replay returns the committed outcome; a conflicting or stale answer is /// typed, and an elapsed TTL never revives the Task. #[allow(clippy::too_many_arguments)] pub async fn update_input( &self, principal: &TaskPrincipal, tool_name: &str, task_id: TaskId, wait_id: &str, expected_version: u32, update_key: &str, input: &Value, ) -> Result { let access = self.task_access(principal, tool_name).await?; match self .service .update_input( &access, task_id, wait_id, expected_version, update_key, input, ) .await { Ok(outcome) => Ok(outcome), Err(TaskError::NotFound) => Err(TaskApplicationError::NotFound), Err(error) => Err(TaskApplicationError::Task(error)), } } /// Owner-scoped attempt history of one Task of the addressed published Tool. pub async fn attempts( &self, principal: &TaskPrincipal, tool_name: &str, task_id: TaskId, ) -> Result, TaskApplicationError> { let access = self.task_access(principal, tool_name).await?; match self.service.attempts(&access, task_id).await { Ok(attempts) => Ok(attempts), Err(TaskError::NotFound) => Err(TaskApplicationError::NotFound), Err(error) => Err(TaskApplicationError::Task(error)), } } async fn task_access( &self, principal: &TaskPrincipal, tool_name: &str, ) -> Result { let tool = self.resolve_authorized_tool(principal, tool_name).await?; let (owner_kind, owner_id) = principal.owner(&tool); Ok(TaskAccess { workspace_id: tool.workspace_id.as_str().to_owned(), owner_kind, owner_id, authorization_scope: principal.authorization_scope(), }) } /// Resolves the addressed Tool of the principal's published catalog and repeats its authorization /// check. A foreign workspace, an unknown Tool and an insufficient security level are typed /// refusals without metadata. async fn resolve_authorized_tool( &self, principal: &TaskPrincipal, tool_name: &str, ) -> Result { let catalog = self .catalog .get_catalog(principal.workspace_slug(), principal.agent_slug()) .await .map_err(|_| TaskApplicationError::NotFound)?; let tool = catalog .tools .into_iter() .find(|tool| tool.tool_name == tool_name) .ok_or(TaskApplicationError::NotFound)?; if let TaskPrincipal::Admin { workspace_slug, .. } = principal && tool.workspace_slug != *workspace_slug { return Err(TaskApplicationError::Denied); } if let TaskPrincipal::Agent { credential, .. } = principal && !credential_allows_security_level(credential, tool.operation.security_level) { return Err(TaskApplicationError::Denied); } Ok(tool) } } /// Bounded retry snapshot pinned from the exact published operation at acceptance. A later /// publication, a restart or a new binary never changes the numbers an accepted Task was admitted /// with; a missing or oversized policy is clamped to the closed story bound. fn task_retry_policy(tool: &PublishedAgentTool) -> crank_core::TaskRetryPolicy { let max_attempts = tool .operation .execution_config .retry_policy .as_ref() .map_or(1, |policy| { policy.max_attempts.clamp(1, crank_core::TASK_MAX_ATTEMPTS) }); crank_core::TaskRetryPolicy::new(max_attempts, 1) }