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(crate::constants::MIME_TEXT.to_string()),
44            vec![],
45        );
46    }
47
48    /// Send a CBOR-encoded content event (buffered).
49    pub fn send_cbor<T: serde::Serialize>(&mut self, value: &T) {
50        let mut buf = Vec::new();
51        ciborium::into_writer(value, &mut buf).expect("CBOR serialization should not fail");
52        self.send_content(buf, Some(crate::constants::MIME_CBOR.to_string()), vec![]);
53    }
54
55    /// Send a JSON-encoded content event (buffered).
56    pub fn send_json<T: serde::Serialize>(&mut self, value: &T) {
57        let data = serde_json::to_vec(value).unwrap_or_default();
58        self.send_content(data, Some(crate::constants::MIME_JSON.to_string()), vec![]);
59    }
60
61    /// Send a content event with explicit data, MIME type, and metadata (buffered).
62    pub fn send_content(
63        &mut self,
64        data: Vec<u8>,
65        mime_type: Option<String>,
66        metadata: Vec<(String, Vec<u8>)>,
67    ) {
68        self.events.push(RawStreamEvent::Content {
69            data,
70            mime_type,
71            metadata,
72        });
73    }
74
75    /// Drain all buffered events. Called by generated code.
76    #[doc(hidden)]
77    pub fn __take_events(&mut self) -> Vec<RawStreamEvent> {
78        std::mem::take(&mut self.events)
79    }
80}