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 projection_placement: None,
360 }
361 }
362
363 fn bp_with_label(id: &str, version_label: Option<&str>) -> Blueprint {
364 Blueprint {
365 schema_version: current_schema_version(),
366 id: id.into(),
367 flow: FlowNode::Seq { children: vec![] },
368 agents: vec![],
369 operators: vec![],
370 metas: vec![],
371 hints: CompilerHints::default(),
372 strategy: CompilerStrategy::default(),
373 metadata: BlueprintMetadata {
374 description: None,
375 origin: Default::default(),
376 tags: vec![],
377 version_label: version_label.map(|s| s.to_string()),
378 project_name_alias: None,
379 default_run_ttl_secs: None,
380 },
381 spawner_hints: Default::default(),
382 default_agent_kind: AgentKind::Operator,
383 default_operator_kind: None,
384 default_init_ctx: None,
385 default_agent_ctx: None,
386 default_context_policy: None,
387 projection_placement: None,
388 }
389 }
390
391 fn build_app_with_store() -> (TaskApplication, Arc<dyn BlueprintStore>) {
392 let reg = SpawnerRegistry::new();
393 let compiler = Compiler::new(reg);
394 let engine = Engine::new(EngineCfg::default());
395 let launch = Arc::new(TaskLaunchService::new(engine, compiler));
396 let store: Arc<dyn BlueprintStore> = Arc::new(InMemoryBlueprintStore::new());
397 (TaskApplication::new(launch, store.clone()), store)
398 }
399
400 fn build_app_inline_only() -> TaskApplication {
401 let reg = SpawnerRegistry::new();
402 let compiler = Compiler::new(reg);
403 let engine = Engine::new(EngineCfg::default());
404 let launch = Arc::new(TaskLaunchService::new(engine, compiler));
405 TaskApplication::new_inline_only(launch)
406 }
407
408 async fn seed(store: &Arc<dyn BlueprintStore>, bp: &Blueprint) -> BlueprintVersion {
409 let id = bp.id.clone();
410 let v = blueprint_version(bp).expect("hash");
411 store
412 .write_new(&id, bp, &[], CommitMetadata::seed(id.clone(), v, 0))
413 .await
414 .expect("seed");
415 v
416 }
417
418 #[test]
419 fn automate_helper_sets_defaults() {
420 let input = TaskApplicationInput::automate(
421 BlueprintRef::Inline {
422 value: Box::new(empty_bp()),
423 },
424 "op-1",
425 Role::Operator,
426 Duration::from_secs(10),
427 serde_json::json!({}),
428 );
429 assert!(
430 input.operator_kind.is_none(),
431 "automate() leaves the Runtime Global tier unspecified (None), \
432 not an explicit Some(Automate) override"
433 );
434 assert!(input.bridge_id.is_none());
435 assert!(input.hook_id.is_none());
436 assert_eq!(input.operator_id, "op-1");
437 }
438
439 #[test]
440 fn struct_literal_allows_callback_ids() {
441 let input = TaskApplicationInput {
442 blueprint: BlueprintRef::Inline {
443 value: Box::new(empty_bp()),
444 },
445 operator_id: "op-2".into(),
446 role: Role::Operator,
447 ttl: Duration::from_secs(5),
448 init_ctx: serde_json::json!({}),
449 operator_kind: Some(OperatorKind::MainAi),
450 bridge_id: Some("br-x".into()),
451 hook_id: Some("hk-y".into()),
452 operator_backend_id: None,
453 operator_kind_overrides: HashMap::new(),
454 task_input: None,
455 };
456 assert!(matches!(input.operator_kind, Some(OperatorKind::MainAi)));
457 assert_eq!(input.bridge_id.as_deref(), Some("br-x"));
458 assert_eq!(input.hook_id.as_deref(), Some("hk-y"));
459 }
460
461 #[tokio::test]
466 async fn resolve_inline_returns_bp_and_no_version() {
467 let app = build_app_inline_only();
468 let bp = empty_bp();
469 let (got, ver) = app
470 .resolve(&BlueprintRef::Inline {
471 value: Box::new(bp.clone()),
472 })
473 .await
474 .expect("resolve inline ok");
475 assert_eq!(got.id, bp.id);
476 assert!(ver.is_none(), "the Inline path yields bound_version=None");
477 }
478
479 #[tokio::test]
480 async fn resolve_id_latest_returns_bp_and_version() {
481 let (app, store) = build_app_with_store();
482 let bp = bp_with_label("rid-latest", Some("0.1.0"));
483 let v = seed(&store, &bp).await;
484 let (got, ver) = app
485 .resolve(&BlueprintRef::Id {
486 id: bp.id.clone(),
487 version: VersionSelector::Latest,
488 })
489 .await
490 .expect("resolve id latest ok");
491 assert_eq!(got.id, bp.id);
492 assert_eq!(ver, Some(v), "Latest = seed version");
493 }
494
495 #[tokio::test]
496 async fn resolve_id_fixed_picks_exact_version() {
497 let (app, store) = build_app_with_store();
498 let id = "rid-fixed";
499 let bp1 = bp_with_label(id, Some("1.0.0"));
500 let bp2 = bp_with_label(id, Some("2.0.0"));
501 let v1 = seed(&store, &bp1).await;
502 let _v2 = seed(&store, &bp2).await;
503 let (got, ver) = app
504 .resolve(&BlueprintRef::Id {
505 id: BlueprintId::new(id),
506 version: VersionSelector::Fixed { value: v1 },
507 })
508 .await
509 .expect("resolve id fixed ok");
510 assert_eq!(ver, Some(v1));
511 assert_eq!(
512 got.metadata.version_label.as_deref(),
513 Some("1.0.0"),
514 "Fixed{{v1}} resolves to v1 = 1.0.0"
515 );
516 }
517
518 #[tokio::test]
519 async fn resolve_id_semver_picks_highest_matching() {
520 let (app, store) = build_app_with_store();
521 let id = "rid-semver";
522 let _ = seed(&store, &bp_with_label(id, Some("1.0.0"))).await;
523 let _ = seed(&store, &bp_with_label(id, Some("1.2.0"))).await;
524 let _ = seed(&store, &bp_with_label(id, Some("2.0.0"))).await;
525 let req = semver::VersionReq::parse("^1").expect("req");
526 let (got, ver) = app
527 .resolve(&BlueprintRef::Id {
528 id: BlueprintId::new(id),
529 version: VersionSelector::SemverReq { req },
530 })
531 .await
532 .expect("resolve semver ok");
533 assert!(ver.is_some());
534 assert_eq!(
535 got.metadata.version_label.as_deref(),
536 Some("1.2.0"),
537 "^1 max = 1.2.0 (2.0.0 is out of range; 1.0.0 is lower)"
538 );
539 }
540
541 #[tokio::test]
542 async fn resolve_id_semver_no_match_errs() {
543 let (app, store) = build_app_with_store();
544 let id = "rid-semver-nomatch";
545 let _ = seed(&store, &bp_with_label(id, Some("1.0.0"))).await;
546 let req = semver::VersionReq::parse("^3").expect("req");
547 let err = app
548 .resolve(&BlueprintRef::Id {
549 id: BlueprintId::new(id),
550 version: VersionSelector::SemverReq { req },
551 })
552 .await
553 .expect_err("expected NoMatchingVersion");
554 match err {
555 TaskApplicationError::NoMatchingVersion { req } => {
556 assert!(req.contains("^3"), "req string carry: {req}");
557 }
558 other => panic!("expected NoMatchingVersion, got {other:?}"),
559 }
560 }
561
562 #[tokio::test]
563 async fn resolve_id_semver_invalid_label_errs() {
564 let (app, store) = build_app_with_store();
565 let id = "rid-semver-bad";
566 let _ = seed(&store, &bp_with_label(id, Some("not-semver"))).await;
567 let req = semver::VersionReq::parse("^1").expect("req");
568 let err = app
569 .resolve(&BlueprintRef::Id {
570 id: BlueprintId::new(id),
571 version: VersionSelector::SemverReq { req },
572 })
573 .await
574 .expect_err("expected InvalidSemver");
575 match err {
576 TaskApplicationError::InvalidSemver { label, .. } => {
577 assert_eq!(label, "not-semver");
578 }
579 other => panic!("expected InvalidSemver, got {other:?}"),
580 }
581 }
582
583 #[tokio::test]
584 async fn resolve_id_without_store_errs_no_store() {
585 let app = build_app_inline_only();
586 let err = app
587 .resolve(&BlueprintRef::Id {
588 id: BlueprintId::new("anything"),
589 version: VersionSelector::Latest,
590 })
591 .await
592 .expect_err("expected NoStore");
593 assert!(matches!(err, TaskApplicationError::NoStore), "got {err:?}");
594 }
595
596 #[tokio::test]
597 async fn resolve_id_not_found_errs_store() {
598 let (app, _store) = build_app_with_store();
599 let err = app
600 .resolve(&BlueprintRef::Id {
601 id: BlueprintId::new("never-seeded"),
602 version: VersionSelector::Latest,
603 })
604 .await
605 .expect_err("expected Store(IdNotFound|HeadEmpty)");
606 match err {
607 TaskApplicationError::Store(
608 BlueprintStoreError::IdNotFound(_) | BlueprintStoreError::HeadEmpty(_),
609 ) => {}
610 other => panic!("expected Store(IdNotFound|HeadEmpty), got {other:?}"),
611 }
612 }
613}