Skip to main content

act_sdk/
context.rs

1use crate::types::ActResult;
2use act_types::cbor::to_cbor;
3use act_types::constants::*;
4
5/// Raw stream event before conversion to WIT types.
6/// Used internally by ActContext; the generated code converts to WIT StreamEvent.
7pub enum RawStreamEvent {
8    Content {
9        data: Vec<u8>,
10        mime_type: Option<String>,
11        metadata: Vec<(String, Vec<u8>)>,
12    },
13    Error {
14        kind: String,
15        message: String,
16        default_language: String,
17    },
18}
19
20/// Context passed to tool functions. Provides config access and stream writing.
21#[allow(dead_code)]
22pub struct ActContext<C = ()> {
23    config: C,
24    events: Vec<RawStreamEvent>,
25    default_language: String,
26}
27
28impl<C> ActContext<C> {
29    #[doc(hidden)]
30    pub fn __new(config: C, default_language: String) -> Self {
31        Self {
32            config,
33            events: Vec::new(),
34            default_language,
35        }
36    }
37
38    /// Access the deserialized config.
39    pub fn config(&self) -> &C {
40        &self.config
41    }
42
43    /// Send a text content event.
44    pub async fn send_text(&mut self, text: impl Into<String>) -> ActResult<()> {
45        self.events.push(RawStreamEvent::Content {
46            data: text.into().into_bytes(),
47            mime_type: Some("text/plain".to_string()),
48            metadata: vec![],
49        });
50        Ok(())
51    }
52
53    /// Send a content part with explicit data, MIME type, and metadata.
54    pub async fn send_content(
55        &mut self,
56        data: Vec<u8>,
57        mime_type: Option<String>,
58        metadata: Vec<(String, Vec<u8>)>,
59    ) -> ActResult<()> {
60        self.events.push(RawStreamEvent::Content {
61            data,
62            mime_type,
63            metadata,
64        });
65        Ok(())
66    }
67
68    /// Send a text event with progress metadata.
69    pub async fn send_progress(
70        &mut self,
71        current: u64,
72        total: u64,
73        text: impl Into<String>,
74    ) -> ActResult<()> {
75        self.events.push(RawStreamEvent::Content {
76            data: text.into().into_bytes(),
77            mime_type: Some("text/plain".to_string()),
78            metadata: vec![
79                (META_PROGRESS.to_string(), to_cbor(&current)),
80                (META_PROGRESS_TOTAL.to_string(), to_cbor(&total)),
81            ],
82        });
83        Ok(())
84    }
85
86    /// Drain all buffered events. Called by generated code.
87    #[doc(hidden)]
88    pub fn __take_events(&mut self) -> Vec<RawStreamEvent> {
89        std::mem::take(&mut self.events)
90    }
91}