1use super::semver_resolve::SemverResolveError;
9use super::Application;
10use crate::blueprint::store::{BlueprintId, BlueprintStore, BlueprintStoreError, BlueprintVersion};
11use crate::blueprint::Blueprint;
12use crate::core::ctx::OperatorKind;
13use crate::service::{
14 TaskInputSpec, TaskLaunchError, TaskLaunchInput, TaskLaunchOutput, TaskLaunchService,
15};
16use crate::store::run::RunContext;
17use crate::types::{CapToken, Role};
18use async_trait::async_trait;
19use serde::{Deserialize, Serialize};
20use serde_json::Value;
21use std::collections::HashMap;
22use std::sync::Arc;
23use std::time::Duration;
24use thiserror::Error;
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
28#[serde(tag = "kind", rename_all = "snake_case")]
29pub enum BlueprintRef {
30 Inline {
33 value: Box<Blueprint>,
35 },
36 Id {
38 id: BlueprintId,
40 #[serde(default)]
42 version: VersionSelector,
43 },
44}
45
46#[derive(Debug, Clone, Default, Serialize, Deserialize)]
48#[serde(tag = "kind", rename_all = "snake_case")]
49pub enum VersionSelector {
50 #[default]
52 Latest,
53 Fixed {
55 value: BlueprintVersion,
57 },
58 SemverReq {
61 req: semver::VersionReq,
64 },
65}
66
67#[derive(Debug, Clone)]
70pub struct TaskApplicationInput {
71 pub blueprint: BlueprintRef,
74 pub operator_id: String,
76 pub role: Role,
78 pub ttl: Duration,
80 pub init_ctx: Value,
82 pub operator_kind: Option<crate::core::ctx::OperatorKind>,
91 pub bridge_id: Option<String>,
95 pub hook_id: Option<String>,
98 pub operator_backend_id: Option<String>,
101 pub operator_kind_overrides: HashMap<String, OperatorKind>,
106 pub task_input: Option<TaskInputSpec>,
114}
115
116impl TaskApplicationInput {
117 pub fn automate(
125 blueprint: BlueprintRef,
126 operator_id: impl Into<String>,
127 role: Role,
128 ttl: Duration,
129 init_ctx: Value,
130 ) -> Self {
131 Self {
132 blueprint,
133 operator_id: operator_id.into(),
134 role,
135 ttl,
136 init_ctx,
137 operator_kind: None,
138 bridge_id: None,
139 hook_id: None,
140 operator_backend_id: None,
141 operator_kind_overrides: HashMap::new(),
142 task_input: None,
143 }
144 }
145}
146
147#[derive(Debug, Clone)]
149pub struct TaskApplicationOutput {
150 pub token: CapToken,
152 pub final_ctx: Value,
154 pub bound_version: Option<BlueprintVersion>,
157}
158
159#[derive(Debug, Error)]
162pub enum TaskApplicationError {
163 #[error("store not configured (BlueprintRef::Id requires store)")]
166 NoStore,
167 #[error("store: {0}")]
169 Store(#[from] BlueprintStoreError),
170 #[error("launch: {0}")]
172 Launch(#[from] TaskLaunchError),
173 #[error("invalid semver version_label {label:?}: {source}")]
175 InvalidSemver {
176 label: String,
178 #[source]
180 source: semver::Error,
181 },
182 #[error("no version matches semver req: {req}")]
184 NoMatchingVersion {
185 req: String,
187 },
188}
189
190impl From<SemverResolveError> for TaskApplicationError {
191 fn from(e: SemverResolveError) -> Self {
192 match e {
193 SemverResolveError::Store(e) => TaskApplicationError::Store(e),
194 SemverResolveError::InvalidSemver { label, source } => {
195 TaskApplicationError::InvalidSemver { label, source }
196 }
197 SemverResolveError::NoMatchingVersion { req } => {
198 TaskApplicationError::NoMatchingVersion { req }
199 }
200 }
201 }
202}
203
204pub struct TaskApplication {
207 launch: Arc<TaskLaunchService>,
208 store: Option<Arc<dyn BlueprintStore>>,
211}
212
213impl TaskApplication {
214 pub fn new(launch: Arc<TaskLaunchService>, store: Arc<dyn BlueprintStore>) -> Self {
217 Self {
218 launch,
219 store: Some(store),
220 }
221 }
222
223 pub fn new_inline_only(launch: Arc<TaskLaunchService>) -> Self {
227 Self {
228 launch,
229 store: None,
230 }
231 }
232
233 pub async fn resolve(
236 &self,
237 bp_ref: &BlueprintRef,
238 ) -> Result<(Blueprint, Option<BlueprintVersion>), TaskApplicationError> {
239 match bp_ref {
240 BlueprintRef::Inline { value } => Ok((value.as_ref().clone(), None)),
241 BlueprintRef::Id { id, version } => {
242 let store = self.store.as_ref().ok_or(TaskApplicationError::NoStore)?;
243 let bp_id = id.clone();
244 let traced = match version {
245 VersionSelector::Latest => store.read_head(&bp_id).await?,
246 VersionSelector::Fixed { value } => store.read_version(&bp_id, *value).await?,
247 VersionSelector::SemverReq { req } => {
248 let v = super::semver_resolve::resolve_semver(store.as_ref(), &bp_id, req)
249 .await?;
250 store.read_version(&bp_id, v).await?
251 }
252 };
253 let ver = traced.trace.version;
254 Ok((traced.value, Some(ver)))
255 }
256 }
257 }
258
259 pub async fn handle_with_run(
271 &self,
272 input: TaskApplicationInput,
273 run_ctx: Option<RunContext>,
274 ) -> Result<TaskApplicationOutput, TaskApplicationError> {
275 let (blueprint, bound_version) = self.resolve(&input.blueprint).await?;
276 let TaskLaunchOutput { token, final_ctx } = self
277 .launch
278 .launch(TaskLaunchInput {
279 blueprint,
280 operator_id: input.operator_id,
281 role: input.role,
282 ttl: input.ttl,
283 operator_kind: input.operator_kind,
284 bridge_id: input.bridge_id,
285 hook_id: input.hook_id,
286 operator_backend_id: input.operator_backend_id,
287 operator_kind_overrides: input.operator_kind_overrides,
288 init_ctx: input.init_ctx,
289 run_ctx,
290 task_input: input.task_input,
291 })
292 .await?;
293 Ok(TaskApplicationOutput {
294 token,
295 final_ctx,
296 bound_version,
297 })
298 }
299}
300
301#[async_trait]
302impl Application for TaskApplication {
303 type Input = TaskApplicationInput;
304 type Output = TaskApplicationOutput;
305 type Error = TaskApplicationError;
306
307 fn name(&self) -> &str {
308 "task"
309 }
310
311 async fn handle(&self, input: Self::Input) -> Result<Self::Output, Self::Error> {
317 self.handle_with_run(input, None).await
318 }
319}
320
321#[cfg(test)]
326mod tests {
327 use super::*;
328 use crate::blueprint::compiler::{Compiler, SpawnerRegistry};
329 use crate::blueprint::store::{
330 blueprint_version, BlueprintId, BlueprintStore, BlueprintStoreError, CommitMetadata,
331 InMemoryBlueprintStore,
332 };
333 use crate::blueprint::{
334 current_schema_version, AgentKind, Blueprint, BlueprintMetadata, CompilerHints,
335 CompilerStrategy,
336 };
337 use crate::core::config::EngineCfg;
338 use crate::core::ctx::OperatorKind;
339 use crate::core::engine::Engine;
340 use mlua_flow_ir::Node as FlowNode;
341
342 fn empty_bp() -> Blueprint {
343 Blueprint {
344 schema_version: current_schema_version(),
345 id: "ut-bp".into(),
346 flow: FlowNode::Seq { children: vec![] },
347 agents: vec![],
348 operators: vec![],
349 metas: vec![],
350 hints: CompilerHints::default(),
351 strategy: CompilerStrategy::default(),
352 metadata: BlueprintMetadata::default(),
353 spawner_hints: Default::default(),
354 default_agent_kind: AgentKind::Operator,
355 default_operator_kind: None,
356 default_init_ctx: None,
357 default_agent_ctx: None,
358 default_context_policy: None,
359 }
360 }
361
362 fn bp_with_label(id: &str, version_label: Option<&str>) -> Blueprint {
363 Blueprint {
364 schema_version: current_schema_version(),
365 id: id.into(),
366 flow: FlowNode::Seq { children: vec![] },
367 agents: vec![],
368 operators: vec![],
369 metas: vec![],
370 hints: CompilerHints::default(),
371 strategy: CompilerStrategy::default(),
372 metadata: BlueprintMetadata {
373 description: None,
374 origin: Default::default(),
375 tags: vec![],
376 version_label: version_label.map(|s| s.to_string()),
377 project_name_alias: None,
378 default_run_ttl_secs: None,
379 },
380 spawner_hints: Default::default(),
381 default_agent_kind: AgentKind::Operator,
382 default_operator_kind: None,
383 default_init_ctx: None,
384 default_agent_ctx: None,
385 default_context_policy: None,
386 }
387 }
388
389 fn build_app_with_store() -> (TaskApplication, Arc<dyn BlueprintStore>) {
390 let reg = SpawnerRegistry::new();
391 let compiler = Compiler::new(reg);
392 let engine = Engine::new(EngineCfg::default());
393 let launch = Arc::new(TaskLaunchService::new(engine, compiler));
394 let store: Arc<dyn BlueprintStore> = Arc::new(InMemoryBlueprintStore::new());
395 (TaskApplication::new(launch, store.clone()), store)
396 }
397
398 fn build_app_inline_only() -> TaskApplication {
399 let reg = SpawnerRegistry::new();
400 let compiler = Compiler::new(reg);
401 let engine = Engine::new(EngineCfg::default());
402 let launch = Arc::new(TaskLaunchService::new(engine, compiler));
403 TaskApplication::new_inline_only(launch)
404 }
405
406 async fn seed(store: &Arc<dyn BlueprintStore>, bp: &Blueprint) -> BlueprintVersion {
407 let id = bp.id.clone();
408 let v = blueprint_version(bp).expect("hash");
409 store
410 .write_new(&id, bp, &[], CommitMetadata::seed(id.clone(), v, 0))
411 .await
412 .expect("seed");
413 v
414 }
415
416 #[test]
417 fn automate_helper_sets_defaults() {
418 let input = TaskApplicationInput::automate(
419 BlueprintRef::Inline {
420 value: Box::new(empty_bp()),
421 },
422 "op-1",
423 Role::Operator,
424 Duration::from_secs(10),
425 serde_json::json!({}),
426 );
427 assert!(
428 input.operator_kind.is_none(),
429 "automate() leaves the Runtime Global tier unspecified (None), \
430 not an explicit Some(Automate) override"
431 );
432 assert!(input.bridge_id.is_none());
433 assert!(input.hook_id.is_none());
434 assert_eq!(input.operator_id, "op-1");
435 }
436
437 #[test]
438 fn struct_literal_allows_callback_ids() {
439 let input = TaskApplicationInput {
440 blueprint: BlueprintRef::Inline {
441 value: Box::new(empty_bp()),
442 },
443 operator_id: "op-2".into(),
444 role: Role::Operator,
445 ttl: Duration::from_secs(5),
446 init_ctx: serde_json::json!({}),
447 operator_kind: Some(OperatorKind::MainAi),
448 bridge_id: Some("br-x".into()),
449 hook_id: Some("hk-y".into()),
450 operator_backend_id: None,
451 operator_kind_overrides: HashMap::new(),
452 task_input: None,
453 };
454 assert!(matches!(input.operator_kind, Some(OperatorKind::MainAi)));
455 assert_eq!(input.bridge_id.as_deref(), Some("br-x"));
456 assert_eq!(input.hook_id.as_deref(), Some("hk-y"));
457 }
458
459 #[tokio::test]
464 async fn resolve_inline_returns_bp_and_no_version() {
465 let app = build_app_inline_only();
466 let bp = empty_bp();
467 let (got, ver) = app
468 .resolve(&BlueprintRef::Inline {
469 value: Box::new(bp.clone()),
470 })
471 .await
472 .expect("resolve inline ok");
473 assert_eq!(got.id, bp.id);
474 assert!(ver.is_none(), "the Inline path yields bound_version=None");
475 }
476
477 #[tokio::test]
478 async fn resolve_id_latest_returns_bp_and_version() {
479 let (app, store) = build_app_with_store();
480 let bp = bp_with_label("rid-latest", Some("0.1.0"));
481 let v = seed(&store, &bp).await;
482 let (got, ver) = app
483 .resolve(&BlueprintRef::Id {
484 id: bp.id.clone(),
485 version: VersionSelector::Latest,
486 })
487 .await
488 .expect("resolve id latest ok");
489 assert_eq!(got.id, bp.id);
490 assert_eq!(ver, Some(v), "Latest = seed version");
491 }
492
493 #[tokio::test]
494 async fn resolve_id_fixed_picks_exact_version() {
495 let (app, store) = build_app_with_store();
496 let id = "rid-fixed";
497 let bp1 = bp_with_label(id, Some("1.0.0"));
498 let bp2 = bp_with_label(id, Some("2.0.0"));
499 let v1 = seed(&store, &bp1).await;
500 let _v2 = seed(&store, &bp2).await;
501 let (got, ver) = app
502 .resolve(&BlueprintRef::Id {
503 id: BlueprintId::new(id),
504 version: VersionSelector::Fixed { value: v1 },
505 })
506 .await
507 .expect("resolve id fixed ok");
508 assert_eq!(ver, Some(v1));
509 assert_eq!(
510 got.metadata.version_label.as_deref(),
511 Some("1.0.0"),
512 "Fixed{{v1}} resolves to v1 = 1.0.0"
513 );
514 }
515
516 #[tokio::test]
517 async fn resolve_id_semver_picks_highest_matching() {
518 let (app, store) = build_app_with_store();
519 let id = "rid-semver";
520 let _ = seed(&store, &bp_with_label(id, Some("1.0.0"))).await;
521 let _ = seed(&store, &bp_with_label(id, Some("1.2.0"))).await;
522 let _ = seed(&store, &bp_with_label(id, Some("2.0.0"))).await;
523 let req = semver::VersionReq::parse("^1").expect("req");
524 let (got, ver) = app
525 .resolve(&BlueprintRef::Id {
526 id: BlueprintId::new(id),
527 version: VersionSelector::SemverReq { req },
528 })
529 .await
530 .expect("resolve semver ok");
531 assert!(ver.is_some());
532 assert_eq!(
533 got.metadata.version_label.as_deref(),
534 Some("1.2.0"),
535 "^1 max = 1.2.0 (2.0.0 is out of range; 1.0.0 is lower)"
536 );
537 }
538
539 #[tokio::test]
540 async fn resolve_id_semver_no_match_errs() {
541 let (app, store) = build_app_with_store();
542 let id = "rid-semver-nomatch";
543 let _ = seed(&store, &bp_with_label(id, Some("1.0.0"))).await;
544 let req = semver::VersionReq::parse("^3").expect("req");
545 let err = app
546 .resolve(&BlueprintRef::Id {
547 id: BlueprintId::new(id),
548 version: VersionSelector::SemverReq { req },
549 })
550 .await
551 .expect_err("expected NoMatchingVersion");
552 match err {
553 TaskApplicationError::NoMatchingVersion { req } => {
554 assert!(req.contains("^3"), "req string carry: {req}");
555 }
556 other => panic!("expected NoMatchingVersion, got {other:?}"),
557 }
558 }
559
560 #[tokio::test]
561 async fn resolve_id_semver_invalid_label_errs() {
562 let (app, store) = build_app_with_store();
563 let id = "rid-semver-bad";
564 let _ = seed(&store, &bp_with_label(id, Some("not-semver"))).await;
565 let req = semver::VersionReq::parse("^1").expect("req");
566 let err = app
567 .resolve(&BlueprintRef::Id {
568 id: BlueprintId::new(id),
569 version: VersionSelector::SemverReq { req },
570 })
571 .await
572 .expect_err("expected InvalidSemver");
573 match err {
574 TaskApplicationError::InvalidSemver { label, .. } => {
575 assert_eq!(label, "not-semver");
576 }
577 other => panic!("expected InvalidSemver, got {other:?}"),
578 }
579 }
580
581 #[tokio::test]
582 async fn resolve_id_without_store_errs_no_store() {
583 let app = build_app_inline_only();
584 let err = app
585 .resolve(&BlueprintRef::Id {
586 id: BlueprintId::new("anything"),
587 version: VersionSelector::Latest,
588 })
589 .await
590 .expect_err("expected NoStore");
591 assert!(matches!(err, TaskApplicationError::NoStore), "got {err:?}");
592 }
593
594 #[tokio::test]
595 async fn resolve_id_not_found_errs_store() {
596 let (app, _store) = build_app_with_store();
597 let err = app
598 .resolve(&BlueprintRef::Id {
599 id: BlueprintId::new("never-seeded"),
600 version: VersionSelector::Latest,
601 })
602 .await
603 .expect_err("expected Store(IdNotFound|HeadEmpty)");
604 match err {
605 TaskApplicationError::Store(
606 BlueprintStoreError::IdNotFound(_) | BlueprintStoreError::HeadEmpty(_),
607 ) => {}
608 other => panic!("expected Store(IdNotFound|HeadEmpty), got {other:?}"),
609 }
610 }
611}