bamboo-engine 2026.10.22

Execution engine and orchestration for the Bamboo agent framework
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! Session creation use case.
//!
//! Pure business logic for constructing a new session from request
//! parameters and configuration defaults. The handler builds the
//! value types from HTTP request / AppState, then delegates here.

use bamboo_agent_core::{Message, Session};
use bamboo_domain::reasoning::ReasoningEffort;
use bamboo_domain::ProviderModelRef;

use super::provider_model::{persist_legacy_model_provider, persist_model_ref};
use crate::model_config_helper::GOLD_CONFIG_METADATA_KEY;

/// Request-level input for session creation.
pub struct CreateSessionInput {
    pub id: String,
    /// Stable Project membership for this root session.
    pub project_id: Option<bamboo_domain::ProjectId>,
    pub title: Option<String>,
    /// Explicit title lifecycle supplied by the client. When omitted, an
    /// explicit non-empty title is treated as finalized for backwards
    /// compatibility, while a default server title remains pending.
    pub title_generated: Option<bool>,
    pub system_prompt: Option<String>,
    pub model: Option<String>,
    pub model_ref: Option<ProviderModelRef>,
    pub reasoning_effort: Option<ReasoningEffort>,
    pub gold_config_json: Option<String>,
    /// Optional workspace path, same semantics as `ChatTurnInput::workspace_path`
    /// (#480: connect bridge sets workspace at session-creation; an external
    /// connector using `POST /sessions` should be able to as well). Only the
    /// metadata write happens here — syncing the runtime workspace directory
    /// on disk (`ensure_session_workspace`) is a handler-layer concern, same
    /// split as the chat turn use case.
    pub workspace_path: Option<String>,
    /// Initial session-scoped permission mode, already resolved by the caller
    /// (explicit request value wins over the durable permission-policy
    /// default). `None` leaves the runtime default (Default) untouched so
    /// callers without permission context keep the old behavior.
    pub permission_mode: Option<bamboo_domain::SessionPermissionMode>,
}

/// Configuration defaults for session creation.
///
/// Captured from server `Config` as plain values so the crate stays
/// decoupled from `bamboo-infrastructure-config`.
pub struct CreateSessionConfig {
    pub default_model: Option<String>,
    pub default_reasoning_effort: Option<ReasoningEffort>,
    pub global_default_prompt: String,
    pub builtin_fallback_prompt: &'static str,
}

/// Build a new session from request input and config defaults.
pub fn build_new_session(input: &CreateSessionInput, config: &CreateSessionConfig) -> Session {
    let model = input
        .model_ref
        .as_ref()
        .map(|model_ref| model_ref.model.clone())
        .unwrap_or_else(|| resolve_model(input.model.as_deref(), config.default_model.as_deref()));
    let mut session = Session::new(input.id.clone(), model);
    if let Some(model_ref) = input.model_ref.as_ref() {
        persist_model_ref(&mut session, model_ref);
    } else {
        persist_legacy_model_provider(&mut session, input.model.as_deref(), None);
    }
    session.reasoning_effort = resolve_reasoning_effort(
        input.reasoning_effort,
        input
            .model_ref
            .as_ref()
            .and_then(|model_ref| model_ref.reasoning_effort)
            .or(config.default_reasoning_effort),
    );
    if let Some(gold_config_json) = trimmed_non_empty(input.gold_config_json.as_deref()) {
        session
            .metadata
            .insert(GOLD_CONFIG_METADATA_KEY.to_string(), gold_config_json);
    }
    if let Some(workspace_path) = trimmed_non_empty(input.workspace_path.as_deref()) {
        session.set_workspace_path_meta(workspace_path);
        session.metadata.insert(
            crate::project_context::WORKSPACE_SOURCE_METADATA_KEY.to_string(),
            crate::project_context::WorkspaceSource::Explicit
                .as_str()
                .to_string(),
        );
        session.metadata.insert(
            crate::project_context::WORKSPACE_BINDING_STATUS_METADATA_KEY.to_string(),
            crate::project_context::WorkspaceBindingStatus::Unregistered
                .as_str()
                .to_string(),
        );
    }
    if let Some(project_id) = input.project_id.as_ref() {
        session.set_project_id_meta(project_id.to_string());
    }
    // Stamp the resolved initial permission mode exactly once at creation.
    // `set_permission_mode` keeps the typed mode and legacy boolean mirror
    // consistent; later changes flow through the CAS-guarded PATCH contract.
    if let Some(mode) = input.permission_mode {
        session
            .agent_runtime_state
            .get_or_insert_with(bamboo_domain::AgentRuntimeState::default)
            .set_permission_mode(mode);
    }

    let explicit_title = trimmed_non_empty(input.title.as_deref());
    if let Some(title) = explicit_title.as_ref() {
        session.title = title.clone();
    }
    session.title_generated = input
        .title_generated
        .unwrap_or_else(|| explicit_title.is_some());
    let explicit_prompt = trimmed_non_empty(input.system_prompt.as_deref());
    let has_explicit_prompt = explicit_prompt.is_some();
    let base_prompt = explicit_prompt.unwrap_or_else(|| {
        let trimmed = config.global_default_prompt.trim();
        if trimmed.is_empty() {
            config.builtin_fallback_prompt.to_string()
        } else {
            trimmed.to_string()
        }
    });
    session
        .metadata
        .insert("base_system_prompt".to_string(), base_prompt.clone());

    if has_explicit_prompt {
        session.add_message(Message::system(base_prompt));
        crate::runner::refresh_prompt_snapshot(&mut session);
    }

    session
}

/// Resolve the model from request → config → fallback.
pub fn resolve_model(request_model: Option<&str>, config_model: Option<&str>) -> String {
    trimmed_non_empty(request_model)
        .or_else(|| config_model.map(ToString::to_string))
        .unwrap_or_else(|| "unknown".to_string())
}

/// Resolve reasoning effort from request → config.
pub fn resolve_reasoning_effort(
    request_effort: Option<ReasoningEffort>,
    config_effort: Option<ReasoningEffort>,
) -> Option<ReasoningEffort> {
    request_effort.or(config_effort)
}

/// Trim whitespace and return `None` for empty strings.
pub fn trimmed_non_empty(value: Option<&str>) -> Option<String> {
    value
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(ToString::to_string)
}

#[cfg(test)]
mod tests {
    use super::*;

    const BUILTIN_FALLBACK: &str = "You are a helpful assistant.";

    fn default_config() -> CreateSessionConfig {
        CreateSessionConfig {
            default_model: None,
            default_reasoning_effort: None,
            global_default_prompt: "Global fallback".to_string(),
            builtin_fallback_prompt: BUILTIN_FALLBACK,
        }
    }

    #[test]
    fn resolve_model_uses_request_model_when_present() {
        assert_eq!(resolve_model(Some("  gpt-5  "), None), "gpt-5");
    }

    #[test]
    fn resolve_model_falls_back_to_config() {
        assert_eq!(resolve_model(None, Some("gpt-4")), "gpt-4");
    }

    #[test]
    fn resolve_model_falls_back_to_unknown() {
        assert_eq!(resolve_model(None, None), "unknown");
    }

    #[test]
    fn resolve_model_ignores_blank_request() {
        assert_eq!(resolve_model(Some("   "), Some("gpt-4")), "gpt-4");
    }

    #[test]
    fn resolve_reasoning_effort_prefers_request() {
        assert_eq!(
            resolve_reasoning_effort(Some(ReasoningEffort::High), Some(ReasoningEffort::Low)),
            Some(ReasoningEffort::High)
        );
    }

    #[test]
    fn resolve_reasoning_effort_falls_back_to_config() {
        assert_eq!(
            resolve_reasoning_effort(None, Some(ReasoningEffort::Medium)),
            Some(ReasoningEffort::Medium)
        );
    }

    #[test]
    fn build_new_session_applies_title_and_system_prompt() {
        let input = CreateSessionInput {
            id: "session-1".to_string(),
            project_id: None,
            title: Some("  Sprint Session  ".to_string()),
            title_generated: None,
            system_prompt: Some("  You are helpful  ".to_string()),
            model: Some("gpt-5".to_string()),
            model_ref: None,
            reasoning_effort: Some(ReasoningEffort::High),
            gold_config_json: None,
            workspace_path: None,
            permission_mode: None,
        };
        let session = build_new_session(&input, &default_config());

        assert_eq!(session.title, "Sprint Session");
        assert!(session.title_generated);
        assert_eq!(
            session
                .metadata
                .get("base_system_prompt")
                .map(String::as_str),
            Some("You are helpful")
        );
        assert_eq!(session.reasoning_effort, Some(ReasoningEffort::High));
        assert_eq!(
            session.messages.first().map(|m| m.content.as_str()),
            Some("You are helpful")
        );
    }

    #[test]
    fn build_new_session_keeps_explicit_placeholder_title_pending() {
        let input = CreateSessionInput {
            id: "session-placeholder".to_string(),
            project_id: None,
            title: Some("Any UI Placeholder".to_string()),
            title_generated: Some(false),
            system_prompt: None,
            model: Some("gpt-5".to_string()),
            model_ref: None,
            reasoning_effort: None,
            gold_config_json: None,
            workspace_path: None,
            permission_mode: None,
        };

        let session = build_new_session(&input, &default_config());
        assert_eq!(session.title, "Any UI Placeholder");
        assert!(!session.title_generated);
    }

    #[test]
    fn build_new_session_uses_global_default_when_no_explicit_prompt() {
        let input = CreateSessionInput {
            id: "session-2".to_string(),
            project_id: None,
            title: None,
            title_generated: None,
            system_prompt: None,
            model: Some("gpt-5".to_string()),
            model_ref: None,
            reasoning_effort: None,
            gold_config_json: None,
            workspace_path: None,
            permission_mode: None,
        };
        let session = build_new_session(&input, &default_config());

        assert!(!session.title_generated);
        assert_eq!(
            session
                .metadata
                .get("base_system_prompt")
                .map(String::as_str),
            Some("Global fallback")
        );
        assert!(session.messages.is_empty());
    }

    #[test]
    fn build_new_session_uses_builtin_fallback_when_global_is_empty() {
        let config = CreateSessionConfig {
            global_default_prompt: "   ".to_string(),
            ..default_config()
        };
        let input = CreateSessionInput {
            id: "session-3".to_string(),
            project_id: None,
            title: None,
            title_generated: None,
            system_prompt: None,
            model: Some("gpt-5".to_string()),
            model_ref: None,
            reasoning_effort: None,
            gold_config_json: None,
            workspace_path: None,
            permission_mode: None,
        };
        let session = build_new_session(&input, &config);

        assert_eq!(
            session
                .metadata
                .get("base_system_prompt")
                .map(String::as_str),
            Some(BUILTIN_FALLBACK)
        );
    }

    #[test]
    fn build_new_session_with_explicit_prompt_generates_snapshot() {
        let input = CreateSessionInput {
            id: "session-4".to_string(),
            project_id: None,
            title: None,
            title_generated: None,
            system_prompt: Some("Custom prompt".to_string()),
            model: Some("gpt-5".to_string()),
            model_ref: None,
            reasoning_effort: None,
            gold_config_json: None,
            workspace_path: None,
            permission_mode: None,
        };
        let session = build_new_session(&input, &default_config());

        let snapshot =
            crate::runner::read_prompt_snapshot(&session).expect("prompt snapshot should exist");
        assert_eq!(snapshot.base_system_prompt, "Custom prompt");
        assert_eq!(snapshot.effective_system_prompt, "Custom prompt");
    }

    #[test]
    fn build_new_session_with_model_ref_persists_bare_model_and_provider_metadata() {
        let input = CreateSessionInput {
            id: "session-5".to_string(),
            project_id: None,
            title: None,
            title_generated: None,
            system_prompt: None,
            model: Some("ignored-compat-model".to_string()),
            model_ref: Some(
                ProviderModelRef::new("anthropic", "claude-3-7-sonnet")
                    .with_reasoning_effort(ReasoningEffort::High),
            ),
            reasoning_effort: None,
            gold_config_json: None,
            workspace_path: None,
            permission_mode: None,
        };
        let session = build_new_session(&input, &default_config());

        assert_eq!(session.model, "claude-3-7-sonnet");
        assert_eq!(
            session.model_ref,
            Some(
                ProviderModelRef::new("anthropic", "claude-3-7-sonnet")
                    .with_reasoning_effort(ReasoningEffort::High)
            )
        );
        assert_eq!(session.reasoning_effort, Some(ReasoningEffort::High));
        assert_eq!(
            session.metadata.get("provider_name").map(String::as_str),
            Some("anthropic")
        );
    }

    /// #480: `POST /sessions` gets the same `workspace_path` semantics as
    /// `POST /chat`'s `ChatTurnInput.workspace_path` — set at session creation.
    #[test]
    fn build_new_session_with_workspace_path_sets_workspace_metadata() {
        let input = CreateSessionInput {
            id: "session-6".to_string(),
            project_id: None,
            title: None,
            title_generated: None,
            system_prompt: None,
            model: Some("gpt-5".to_string()),
            model_ref: None,
            reasoning_effort: None,
            gold_config_json: None,
            workspace_path: Some("  /tmp/my-workspace  ".to_string()),
            permission_mode: None,
        };
        let session = build_new_session(&input, &default_config());

        assert_eq!(
            session.workspace_path_meta().as_deref(),
            Some("/tmp/my-workspace")
        );
    }

    #[test]
    fn build_new_session_without_workspace_path_leaves_metadata_unset() {
        let input = CreateSessionInput {
            id: "session-7".to_string(),
            project_id: None,
            title: None,
            title_generated: None,
            system_prompt: None,
            model: Some("gpt-5".to_string()),
            model_ref: None,
            reasoning_effort: None,
            gold_config_json: None,
            workspace_path: None,
            permission_mode: None,
        };
        let session = build_new_session(&input, &default_config());

        assert!(session.workspace_path_meta().is_none());
    }

    #[test]
    fn build_new_session_stamps_permission_mode_with_legacy_mirror() {
        let input = CreateSessionInput {
            id: "session-permission".to_string(),
            project_id: None,
            title: None,
            title_generated: None,
            system_prompt: None,
            model: Some("gpt-5".to_string()),
            model_ref: None,
            reasoning_effort: None,
            gold_config_json: None,
            workspace_path: None,
            permission_mode: Some(bamboo_domain::SessionPermissionMode::Auto),
        };
        let session = build_new_session(&input, &default_config());
        let runtime = session.agent_runtime_state.as_ref().expect("runtime state");
        assert_eq!(
            runtime.effective_permission_mode(),
            bamboo_domain::SessionPermissionMode::Auto
        );
        // The legacy boolean mirror keeps old clients conservative.
        assert!(runtime.bypass_permissions);

        // None leaves the runtime state untouched — no state is created and
        // persisted sessions stay byte-compatible with the pre-field format.
        let unset = build_new_session(
            &CreateSessionInput {
                id: "session-permission-unset".to_string(),
                project_id: None,
                title: None,
                title_generated: None,
                system_prompt: None,
                model: Some("gpt-5".to_string()),
                model_ref: None,
                reasoning_effort: None,
                gold_config_json: None,
                workspace_path: None,
                permission_mode: None,
            },
            &default_config(),
        );
        assert!(unset.agent_runtime_state.is_none());
    }
}