behest-context 0.5.5

Layered context system for the behest agent runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! Concrete implementations of the layered context traits.
//!
//! These structs provide the actual backing storage and behavior for each
//! context level. They are designed to be composed hierarchically:
//!
//! ```text
//! AppContext → SessionContextImpl → RunContextImpl → ToolContextImpl
//! ```

use std::time::Instant;

use behest_core::id::RunId;
use behest_core::message::Message;
use behest_core::run::RunState;
use behest_core::tool_types::ToolCall;
use tokio_util::sync::CancellationToken;

use crate::{
    EventSink, HookContext, MemoryContext, ReadonlyContext, RunBudget, RunContext, RunSnapshot,
    SessionContext, SessionState, ToolContext,
};

/// Application-level context: global configuration and identity.
#[derive(Debug, Clone)]
pub struct AppContext {
    /// Unique invocation identifier.
    pub invocation_id: String,
    /// Session identifier.
    pub session_id: String,
    /// Authenticated user identifier.
    pub user_id: String,
    /// Application name.
    pub app_name: String,
}

impl ReadonlyContext for AppContext {
    fn invocation_id(&self) -> &str {
        &self.invocation_id
    }

    fn session_id(&self) -> &str {
        &self.session_id
    }

    fn user_id(&self) -> &str {
        &self.user_id
    }

    fn app_name(&self) -> &str {
        &self.app_name
    }
}

/// Session-level context with mutable state.
#[derive(Debug)]
pub struct SessionContextImpl {
    /// The underlying application context.
    pub app: AppContext,
    /// Mutable session state (key-value store).
    pub state: SessionState,
}

impl ReadonlyContext for SessionContextImpl {
    fn invocation_id(&self) -> &str {
        self.app.invocation_id()
    }

    fn session_id(&self) -> &str {
        self.app.session_id()
    }

    fn user_id(&self) -> &str {
        self.app.user_id()
    }

    fn app_name(&self) -> &str {
        self.app.app_name()
    }
}

impl SessionContext for SessionContextImpl {
    fn session_state(&self) -> &SessionState {
        &self.state
    }

    fn session_state_mut(&mut self) -> &mut SessionState {
        &mut self.state
    }
}

/// Run-level context with cancellation, deadline, event sink, and budget.
#[derive(Debug)]
pub struct RunContextImpl {
    /// The underlying session context.
    pub session: SessionContextImpl,
    /// The unique run identifier.
    pub run_id: RunId,
    /// Cancellation token for cooperative cancellation.
    pub cancel: CancellationToken,
    /// Deadline for this run, if any.
    pub deadline: Option<Instant>,
    /// Event sink for emitting structured events.
    pub sink: EventSink,
    /// Token budget tracker.
    pub budget: RunBudget,
}

impl ReadonlyContext for RunContextImpl {
    fn invocation_id(&self) -> &str {
        self.session.invocation_id()
    }

    fn session_id(&self) -> &str {
        self.session.session_id()
    }

    fn user_id(&self) -> &str {
        self.session.user_id()
    }

    fn app_name(&self) -> &str {
        self.session.app_name()
    }
}

impl SessionContext for RunContextImpl {
    fn session_state(&self) -> &SessionState {
        self.session.session_state()
    }

    fn session_state_mut(&mut self) -> &mut SessionState {
        self.session.session_state_mut()
    }
}

impl RunContext for RunContextImpl {
    fn run_id(&self) -> &RunId {
        &self.run_id
    }

    fn cancellation_token(&self) -> &CancellationToken {
        &self.cancel
    }

    fn deadline(&self) -> Option<Instant> {
        self.deadline
    }

    fn event_sink(&self) -> &EventSink {
        &self.sink
    }

    fn budget(&self) -> &RunBudget {
        &self.budget
    }
}

/// Tool execution context.
#[derive(Debug)]
pub struct ToolContextImpl {
    /// The underlying run context.
    pub run: RunContextImpl,
    /// The tool call being executed.
    pub tool_call: ToolCall,
}

impl ReadonlyContext for ToolContextImpl {
    fn invocation_id(&self) -> &str {
        self.run.invocation_id()
    }

    fn session_id(&self) -> &str {
        self.run.session_id()
    }

    fn user_id(&self) -> &str {
        self.run.user_id()
    }

    fn app_name(&self) -> &str {
        self.run.app_name()
    }
}

impl SessionContext for ToolContextImpl {
    fn session_state(&self) -> &SessionState {
        self.run.session_state()
    }

    fn session_state_mut(&mut self) -> &mut SessionState {
        self.run.session_state_mut()
    }
}

impl RunContext for ToolContextImpl {
    fn run_id(&self) -> &RunId {
        self.run.run_id()
    }

    fn cancellation_token(&self) -> &CancellationToken {
        self.run.cancellation_token()
    }

    fn deadline(&self) -> Option<Instant> {
        self.run.deadline()
    }

    fn event_sink(&self) -> &EventSink {
        self.run.event_sink()
    }

    fn budget(&self) -> &RunBudget {
        self.run.budget()
    }
}

impl ToolContext for ToolContextImpl {
    fn tool_call(&self) -> &ToolCall {
        &self.tool_call
    }
}

/// Memory context implementation with active window management.
pub struct MemoryContextImpl {
    /// The underlying session context.
    pub session: SessionContextImpl,
    /// Short-term active window messages.
    pub window: Vec<Message>,
}

impl ReadonlyContext for MemoryContextImpl {
    fn invocation_id(&self) -> &str {
        self.session.invocation_id()
    }

    fn session_id(&self) -> &str {
        self.session.session_id()
    }

    fn user_id(&self) -> &str {
        self.session.user_id()
    }

    fn app_name(&self) -> &str {
        self.session.app_name()
    }
}

impl SessionContext for MemoryContextImpl {
    fn session_state(&self) -> &SessionState {
        self.session.session_state()
    }

    fn session_state_mut(&mut self) -> &mut SessionState {
        self.session.session_state_mut()
    }
}

impl MemoryContext for MemoryContextImpl {
    fn active_window(&self) -> &[Message] {
        &self.window
    }

    fn demote(&self, messages: Vec<Message>) -> Result<(), String> {
        let count = messages.len();
        if count == 0 {
            return Ok(());
        }
        // Default: demotion stores messages as JSON in session state
        let mut state = self.session_state().clone();
        let key = format!("memory:demoted:{}", chrono::Utc::now().timestamp());
        let value = serde_json::to_value(&messages).map_err(|e| e.to_string())?;
        state.set(key, value);
        Ok(())
    }

    fn compact(&self, _messages: Vec<Message>) -> Result<String, String> {
        // Default: no-op compaction. Implementations should override this
        // with LLM-based summarization.
        Ok(String::new())
    }
}

/// Hook context implementation for observing run state.
pub struct HookContextImpl {
    /// The application context for identity.
    pub app: AppContext,
    /// The current run state.
    pub state: RunState,
    /// The run identifier.
    pub run_id: RunId,
    /// Current iteration count.
    pub iteration: usize,
    /// Current token usage.
    pub tokens_used: usize,
}

impl ReadonlyContext for HookContextImpl {
    fn invocation_id(&self) -> &str {
        &self.app.invocation_id
    }

    fn session_id(&self) -> &str {
        &self.app.session_id
    }

    fn user_id(&self) -> &str {
        &self.app.user_id
    }

    fn app_name(&self) -> &str {
        &self.app.app_name
    }
}

impl HookContext for HookContextImpl {
    fn current_state(&self) -> &RunState {
        &self.state
    }

    fn snapshot(&self) -> RunSnapshot {
        RunSnapshot {
            state: self.state.clone(),
            run_id: self.run_id,
            session_id: self.session_id().to_string(),
            iteration: self.iteration,
            tokens_used: self.tokens_used,
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use serde_json::Value;

    #[test]
    fn session_state_set_and_get() {
        let mut state = SessionState::new();
        state.set("user:name", Value::String("Alice".to_string()));
        assert_eq!(
            state.get("user:name"),
            Some(&Value::String("Alice".to_string()))
        );
        assert!(state.get("nonexistent").is_none());
    }

    #[test]
    fn session_state_remove() {
        let mut state = SessionState::new();
        state.set("temp:key", Value::Bool(true));
        assert!(state.remove("temp:key").is_some());
        assert!(state.get("temp:key").is_none());
    }

    #[test]
    fn run_budget_tracking() {
        let mut budget = RunBudget::new(Some(1000));
        assert_eq!(budget.remaining(), Some(1000));
        budget.consume(300);
        assert_eq!(budget.remaining(), Some(700));
        assert_eq!(budget.used(), 300);
    }

    #[test]
    fn run_budget_unlimited() {
        let budget = RunBudget::new(None);
        assert_eq!(budget.remaining(), None);
        assert_eq!(budget.used(), 0);
    }

    #[test]
    fn event_sink_emit_and_subscribe() {
        let sink = EventSink::new();
        let mut rx = sink.subscribe();
        sink.emit(serde_json::json!({"type": "test"}));
        // The receiver should have the latest value
        let val = rx.borrow_and_update().clone();
        assert!(val.is_some());
    }

    #[test]
    fn tool_context_emits_progress() {
        let app = AppContext {
            invocation_id: "inv-1".to_string(),
            session_id: "sess-1".to_string(),
            user_id: "user-1".to_string(),
            app_name: "test".to_string(),
        };
        let session = SessionContextImpl {
            app,
            state: SessionState::new(),
        };
        let sink = EventSink::new();
        let mut sub = sink.subscribe();
        let run = RunContextImpl {
            session,
            run_id: RunId::new(),
            cancel: CancellationToken::new(),
            deadline: None,
            sink,
            budget: RunBudget::new(None),
        };
        let ctx = ToolContextImpl {
            run,
            tool_call: ToolCall::new("call_1", "test_tool", Value::Null),
        };

        ctx.emit_progress("working", serde_json::json!({"percent": 50}));

        let emitted = sub.borrow_and_update().clone();
        assert!(emitted.is_some());
        let event = emitted.unwrap();
        assert_eq!(event["type"], "tool_progress");
        assert_eq!(event["call_id"], "call_1");
    }
}