Skip to main content

kruxiaflow_worker/
types.rs

1//! Protocol types shared between workers and the Kruxia Flow server.
2//!
3//! These mirror the worker HTTP API contract (`/api/v1/workers/poll`,
4//! `/api/v1/activities/{id}/…`). Field names are frozen as part of the
5//! public worker-API contract.
6
7use rust_decimal::Decimal;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10use uuid::Uuid;
11
12/// Activity output type.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, Hash)]
14#[serde(rename_all = "lowercase")]
15pub enum OutputType {
16    /// Default: JSON value
17    #[default]
18    Value,
19
20    /// File reference
21    File,
22
23    /// Folder reference
24    Folder,
25}
26
27/// A single named activity output.
28#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
29pub struct ActivityOutput {
30    /// Output name
31    pub name: String,
32
33    /// Output type
34    #[serde(rename = "type")]
35    pub output_type: OutputType,
36
37    /// Output value
38    /// - For `Value`: JSON data
39    /// - For `File`: file reference string (e.g., `postgres://workflow_id/activity_key/filename`)
40    /// - For `Folder`: folder reference string
41    pub value: Value,
42}
43
44impl ActivityOutput {
45    /// Create a JSON-value output.
46    pub fn value(name: impl Into<String>, value: Value) -> Self {
47        Self {
48            name: name.into(),
49            output_type: OutputType::Value,
50            value,
51        }
52    }
53
54    /// Create a file-reference output.
55    pub fn file(name: impl Into<String>, reference: impl Into<String>) -> Self {
56        Self {
57            name: name.into(),
58            output_type: OutputType::File,
59            value: Value::String(reference.into()),
60        }
61    }
62
63    /// Create a folder-reference output.
64    pub fn folder(name: impl Into<String>, reference: impl Into<String>) -> Self {
65        Self {
66            name: name.into(),
67            output_type: OutputType::Folder,
68            value: Value::String(reference.into()),
69        }
70    }
71}
72
73/// An activity claimed from the queue, as returned by `POST /api/v1/workers/poll`.
74#[derive(Debug, Clone, Deserialize)]
75pub struct PendingActivity {
76    /// Unique identifier for this activity execution
77    pub activity_id: Uuid,
78    /// Workflow instance this activity belongs to
79    pub workflow_id: Uuid,
80    /// Activity key from the workflow definition
81    pub activity_key: String,
82    /// Worker type (the `worker:` field in the workflow definition)
83    pub worker: String,
84    /// Activity name (the `name:` field in the workflow definition)
85    pub activity_name: String,
86    /// Activity input parameters
87    pub parameters: Value,
88    /// Raw activity settings from the workflow definition
89    pub settings: Option<Value>,
90    /// Per-activity timeout override (seconds)
91    pub timeout_seconds: Option<i64>,
92    /// Declared output definitions (used for file outputs)
93    pub output_definitions: Option<Value>,
94    /// Signal data for activities that were waiting for an external signal
95    pub signal_data: Option<Value>,
96}
97
98/// Response envelope for `POST /api/v1/workers/poll`.
99#[derive(Debug, Deserialize)]
100pub struct PollActivitiesResponse {
101    /// Claimed activities
102    pub activities: Vec<PendingActivity>,
103    /// Number of activities claimed
104    pub count: usize,
105    /// When nothing was claimed: milliseconds until the earliest activity
106    /// scheduled for later (a delay, a retry backoff) becomes claimable.
107    /// Absent when there is none, and from servers older than 0.10.
108    #[serde(default)]
109    pub next_due_ms: Option<u64>,
110}
111
112/// The result of one poll: what was claimed, and when to look again.
113#[derive(Debug)]
114pub struct PollOutcome {
115    /// Claimed activities
116    pub activities: Vec<PendingActivity>,
117    /// When nothing was claimed and an activity is scheduled for later: how
118    /// long until it becomes claimable. Nothing announces that moment, so a
119    /// worker waiting for a wake should poll again no later than this.
120    pub next_due: Option<std::time::Duration>,
121}
122
123/// Per-LLM-call usage made inside an activity, reported on completion or
124/// failure so external activities appear in cost history/analytics and count
125/// against workflow budgets with the same fidelity as built-in LLM activities.
126///
127/// When `cost_usd` is omitted the server computes the cost from its
128/// `llm_models` pricing catalog (cache reads at the cached-input price, cache
129/// creation at the cache-write price, cache storage at the cache-storage
130/// price per million token-hours). An unknown provider/model records the
131/// entry at cost 0 with a warning — completion never fails because of usage
132/// metadata.
133///
134/// Time-based cache *storage* (e.g., Gemini explicit caching, billed per
135/// token-hour) is reported via `cache_storage_token_hours` (engine 0.8+;
136/// models without a catalog storage price record that component at 0 with a
137/// warning). Reporting the spend via explicit `cost_usd` instead remains
138/// fully supported.
139///
140/// Double-reporting rule: an entry's `cost_usd`, when set, is used verbatim
141/// and REPLACES all server-side computation for that entry — never report the
142/// same spend both ways.
143#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
144pub struct UsageEntry {
145    /// LLM provider name (matches the server's `llm_models` catalog, e.g. "anthropic")
146    pub provider: String,
147
148    /// Model name (matches the server's `llm_models` catalog)
149    pub model: String,
150
151    /// Prompt tokens, including cache reads
152    #[serde(default)]
153    pub input_tokens: u32,
154
155    /// Completion tokens
156    #[serde(default)]
157    pub output_tokens: u32,
158
159    /// Prompt tokens served from cache (billed at the cached-input price)
160    #[serde(default)]
161    pub cache_read_tokens: u32,
162
163    /// Tokens written to cache (billed at the catalog's cache-write price,
164    /// falling back to the input price for models without one)
165    #[serde(default)]
166    pub cache_creation_tokens: u32,
167
168    /// Context-cache storage consumed, in token-hours (tokens held x hours
169    /// held; fractional). Billed at the catalog's cache-storage price; models
170    /// without one record the component at 0 with a warning.
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub cache_storage_token_hours: Option<Decimal>,
173
174    /// Explicit cost for this call; overrides server-side computation
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub cost_usd: Option<Decimal>,
177}
178
179impl UsageEntry {
180    /// Create a usage entry for one LLM call with all token counts zero.
181    pub fn new(provider: impl Into<String>, model: impl Into<String>) -> Self {
182        Self {
183            provider: provider.into(),
184            model: model.into(),
185            input_tokens: 0,
186            output_tokens: 0,
187            cache_read_tokens: 0,
188            cache_creation_tokens: 0,
189            cache_storage_token_hours: None,
190            cost_usd: None,
191        }
192    }
193
194    /// Set prompt tokens (including cache reads).
195    pub fn input_tokens(mut self, tokens: u32) -> Self {
196        self.input_tokens = tokens;
197        self
198    }
199
200    /// Set completion tokens.
201    pub fn output_tokens(mut self, tokens: u32) -> Self {
202        self.output_tokens = tokens;
203        self
204    }
205
206    /// Set prompt tokens served from cache.
207    pub fn cache_read_tokens(mut self, tokens: u32) -> Self {
208        self.cache_read_tokens = tokens;
209        self
210    }
211
212    /// Set tokens written to cache.
213    pub fn cache_creation_tokens(mut self, tokens: u32) -> Self {
214        self.cache_creation_tokens = tokens;
215        self
216    }
217
218    /// Set context-cache storage consumed, in token-hours (tokens held x
219    /// hours held; fractional).
220    pub fn cache_storage_token_hours(mut self, token_hours: Decimal) -> Self {
221        self.cache_storage_token_hours = Some(token_hours);
222        self
223    }
224
225    /// Set an explicit cost, overriding server-side catalog pricing.
226    pub fn cost_usd(mut self, cost: Decimal) -> Self {
227        self.cost_usd = Some(cost);
228        self
229    }
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235    use serde_json::json;
236
237    #[test]
238    fn output_type_serde() {
239        assert_eq!(
240            serde_json::to_string(&OutputType::Value).unwrap(),
241            "\"value\""
242        );
243        assert_eq!(
244            serde_json::to_string(&OutputType::File).unwrap(),
245            "\"file\""
246        );
247        assert_eq!(
248            serde_json::to_string(&OutputType::Folder).unwrap(),
249            "\"folder\""
250        );
251    }
252
253    #[test]
254    fn activity_output_constructors() {
255        let v = ActivityOutput::value("result", json!({"ok": true}));
256        assert_eq!(v.output_type, OutputType::Value);
257
258        let f = ActivityOutput::file("doc", "postgres://wf/act/file.pdf");
259        assert_eq!(f.output_type, OutputType::File);
260        assert_eq!(f.value, json!("postgres://wf/act/file.pdf"));
261
262        let d = ActivityOutput::folder("out", "postgres://wf/act/out/");
263        assert_eq!(d.output_type, OutputType::Folder);
264    }
265
266    #[test]
267    fn pending_activity_deserializes() {
268        let activity: PendingActivity = serde_json::from_value(json!({
269            "activity_id": "01890a5d-ac96-774b-bcce-b302099a8057",
270            "workflow_id": "01890a5d-ac96-774b-bcce-b302099a8058",
271            "activity_key": "step_one",
272            "worker": "demo",
273            "activity_name": "echo",
274            "parameters": {"message": "hi"},
275            "settings": null,
276            "timeout_seconds": 120,
277            "output_definitions": null,
278            "signal_data": null
279        }))
280        .unwrap();
281        assert_eq!(activity.worker, "demo");
282        assert_eq!(activity.activity_name, "echo");
283        assert_eq!(activity.timeout_seconds, Some(120));
284    }
285
286    #[test]
287    fn usage_entry_builder_and_serde() {
288        use rust_decimal_macros::dec;
289
290        let entry = UsageEntry::new("anthropic", "claude-sonnet-5")
291            .input_tokens(12034)
292            .output_tokens(512)
293            .cache_read_tokens(9800);
294
295        let value = serde_json::to_value(&entry).unwrap();
296        assert_eq!(
297            value,
298            json!({
299                "provider": "anthropic",
300                "model": "claude-sonnet-5",
301                "input_tokens": 12034,
302                "output_tokens": 512,
303                "cache_read_tokens": 9800,
304                "cache_creation_tokens": 0
305            })
306        );
307
308        let priced = UsageEntry::new("google", "gemini-2.5-pro").cost_usd(dec!(0.015));
309        let value = serde_json::to_value(&priced).unwrap();
310        assert_eq!(value["cost_usd"], json!("0.015"));
311    }
312}