Skip to main content

act_sdk/
context.rs

1/// Raw stream event before conversion to WIT types.
2/// Used internally by ActContext; the generated code converts to WIT StreamEvent.
3pub enum RawStreamEvent {
4    Content {
5        data: Vec<u8>,
6        mime_type: Option<String>,
7        metadata: Vec<(String, Vec<u8>)>,
8    },
9    Error {
10        kind: String,
11        message: String,
12        default_language: String,
13    },
14}
15
16/// Context passed to tool functions. Provides metadata access and stream writing.
17///
18/// Events are buffered in memory via `send_text()`/`send_content()` and
19/// written to the WIT stream after the tool function returns.
20pub struct ActContext<C = ()> {
21    metadata: C,
22    events: Vec<RawStreamEvent>,
23}
24
25impl<C> ActContext<C> {
26    #[doc(hidden)]
27    pub fn __new(metadata: C) -> Self {
28        Self {
29            metadata,
30            events: Vec::new(),
31        }
32    }
33
34    /// Access the deserialized metadata.
35    pub fn metadata(&self) -> &C {
36        &self.metadata
37    }
38
39    /// Send a text content event (buffered).
40    pub fn send_text(&mut self, text: impl Into<String>) {
41        self.send_content(
42            text.into().into_bytes(),
43            Some("text/plain".to_string()),
44            vec![],
45        );
46    }
47
48    /// Send a content event with explicit data, MIME type, and metadata (buffered).
49    pub fn send_content(
50        &mut self,
51        data: Vec<u8>,
52        mime_type: Option<String>,
53        metadata: Vec<(String, Vec<u8>)>,
54    ) {
55        self.events.push(RawStreamEvent::Content {
56            data,
57            mime_type,
58            metadata,
59        });
60    }
61
62    /// Drain all buffered events. Called by generated code.
63    #[doc(hidden)]
64    pub fn __take_events(&mut self) -> Vec<RawStreamEvent> {
65        std::mem::take(&mut self.events)
66    }
67}