everruns-core 0.9.0

Core agent abstractions for Everruns - agent loop, events, tools, LLM providers
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
// Feature flags system
//
// Decision: Feature flags are system-level, computed from env vars + deployment grade.
// Decision: Flags marked "experimental" auto-enable in dev (DeploymentGrade::Dev).
// Decision: Explicit env var (FEATURE_<NAME>=true/false) always takes priority.
// Decision: Struct-based for type safety; `is_enabled(&str)` for dynamic lookup.
// Decision: Two structs — FeatureFlags (API-visible) and InternalFeatureFlags (backend-only).
// Decision: Future extensibility: per-org/per-user flags, external providers (LaunchDarkly).
// Decision: No database storage needed yet — env vars + deployment grade suffice.

use serde::{Deserialize, Serialize};

use crate::deployment::DeploymentGrade;

/// Feature flags exposed via `GET /v1/feature-flags` and consumed by the frontend.
///
/// Currently backed by environment variables and deployment grade.
/// Future: per-org flags, per-user flags, external providers.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct FeatureFlags {
    /// Global chat (per-user singleton chat session). Experimental.
    pub global_chat: bool,
    /// In-app notifications (bell, toasts, notification SSE). Experimental.
    pub notifications: bool,
    /// MCP endpoint (POST /mcp — Everruns as an MCP server). Experimental.
    pub mcp_endpoint: bool,
    /// Evals (user-facing behavioral evals for agents). Experimental.
    pub evals: bool,
    /// App / channel scoped budgets and periodic budget resets (`5h`, `1d`, ...).
    /// Experimental.
    pub app_budgets: bool,
    /// Immutable agent versions, snapshots, forks, and app version binding.
    /// Experimental.
    pub agent_versions: bool,
    /// Realtime voice endpoints and microphone controls. Experimental.
    pub voice: bool,
    /// Channels-first app detail page and full-page channel forms. Experimental.
    #[serde(rename = "apps.detailV2")]
    pub apps_detail_v2: bool,
    /// Outbound agent delegation capabilities (`a2a_agent_delegation`, `agent_handoff`).
    /// Experimental: auto-enabled in dev, off in prod by default.
    /// When off, these capabilities are not registered and cannot be assigned to agents.
    pub agent_delegation: bool,
}

/// Metadata for an API-visible feature flag (org opt-in UI + catalog).
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct FeatureFlagDefinition {
    /// Stable flag key (matches `FeatureFlags` field / `is_enabled` name).
    pub name: &'static str,
    /// Human-readable title for settings UI.
    pub label: &'static str,
    /// Short description of what the flag gates.
    pub description: &'static str,
    /// When true, shown with experimental badges in the UI.
    pub experimental: bool,
}

/// All API-visible flags that organizations may opt into when the deployment allows them.
pub const API_FEATURE_FLAG_DEFINITIONS: &[FeatureFlagDefinition] = &[
    FeatureFlagDefinition {
        name: "global_chat",
        label: "Global chat",
        description: "Per-user singleton chat session in the sidebar.",
        experimental: true,
    },
    FeatureFlagDefinition {
        name: "notifications",
        label: "Notifications",
        description: "In-app notification bell, toasts, and notification SSE.",
        experimental: true,
    },
    FeatureFlagDefinition {
        name: "mcp_endpoint",
        label: "MCP server endpoint",
        description: "Expose Everruns as an MCP server (POST /mcp).",
        experimental: true,
    },
    FeatureFlagDefinition {
        name: "evals",
        label: "Evals",
        description: "Behavioral evals for agents.",
        experimental: true,
    },
    FeatureFlagDefinition {
        name: "app_budgets",
        label: "App budgets",
        description: "App and channel scoped budgets with periodic resets.",
        experimental: true,
    },
    FeatureFlagDefinition {
        name: "agent_versions",
        label: "Agent versions",
        description: "Immutable agent snapshots, forks, rollback, and app version binding.",
        experimental: true,
    },
    FeatureFlagDefinition {
        name: "voice",
        label: "Voice",
        description: "Realtime voice endpoints and microphone controls in chat.",
        experimental: true,
    },
    FeatureFlagDefinition {
        name: "apps.detailV2",
        label: "Apps detail v2",
        description: "Channels-first app detail page and full-page channel forms.",
        experimental: true,
    },
];

impl FeatureFlags {
    /// Effective flags for an organization: deployment/system gates AND explicit org opt-in.
    ///
    /// Org overrides default to disabled; a flag is on only when the deployment allows it
    /// and the org has opted in (`enabled: true` in storage).
    pub fn for_org(system: &Self, org_enabled: &std::collections::HashMap<String, bool>) -> Self {
        let opt_in = |name: &str, system_on: bool| -> bool {
            system_on && org_enabled.get(name).copied().unwrap_or(false)
        };
        Self {
            global_chat: opt_in("global_chat", system.global_chat),
            notifications: opt_in("notifications", system.notifications),
            mcp_endpoint: opt_in("mcp_endpoint", system.mcp_endpoint),
            evals: opt_in("evals", system.evals),
            app_budgets: opt_in("app_budgets", system.app_budgets),
            agent_versions: opt_in("agent_versions", system.agent_versions),
            voice: opt_in("voice", system.voice),
            apps_detail_v2: opt_in("apps.detailV2", system.apps_detail_v2),
            agent_delegation: opt_in("agent_delegation", system.agent_delegation),
        }
    }

    /// Compute feature flags from environment variables and deployment grade.
    pub fn from_env(grade: &DeploymentGrade) -> Self {
        Self {
            global_chat: experimental_flag("FEATURE_GLOBAL_CHAT", grade),
            notifications: experimental_flag("FEATURE_NOTIFICATIONS", grade),
            mcp_endpoint: experimental_flag("FEATURE_MCP_ENDPOINT", grade),
            evals: experimental_flag("FEATURE_EVALS", grade),
            app_budgets: experimental_flag("FEATURE_APP_BUDGETS", grade),
            agent_versions: experimental_flag("FEATURE_AGENT_VERSIONS", grade),
            voice: experimental_flag("FEATURE_VOICE", grade),
            apps_detail_v2: experimental_flag("FEATURE_APPS_DETAIL_V2", grade),
            agent_delegation: experimental_flag("FEATURE_AGENT_DELEGATION", grade),
        }
    }

    /// Resolve the current feature flags from env + the env-derived deployment grade.
    /// Convenience for callers that don't have a `FeatureFlags` instance handy.
    pub fn current() -> Self {
        Self::from_env(&DeploymentGrade::from_env())
    }

    /// Look up a flag by name (for dynamic/string-based access).
    pub fn is_enabled(&self, flag: &str) -> bool {
        match flag {
            "global_chat" => self.global_chat,
            "notifications" => self.notifications,
            "mcp_endpoint" => self.mcp_endpoint,
            "evals" => self.evals,
            "app_budgets" => self.app_budgets,
            "agent_versions" => self.agent_versions,
            "voice" => self.voice,
            "apps.detailV2" => self.apps_detail_v2,
            "agent_delegation" => self.agent_delegation,
            _ => false,
        }
    }

    /// All flags enabled (for testing).
    #[cfg(test)]
    pub fn all_enabled() -> Self {
        Self {
            global_chat: true,
            notifications: true,
            mcp_endpoint: true,
            evals: true,
            app_budgets: true,
            agent_versions: true,
            voice: true,
            apps_detail_v2: true,
            agent_delegation: true,
        }
    }
}

/// Backend-only feature flags. Not exposed via API or frontend.
///
/// Used for internal gating (capability registration, infrastructure behavior).
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct InternalFeatureFlags {
    /// Docker container capability. Disabled by default on all envs.
    /// Enable via `FEATURE_DOCKER_CAPABILITY=true`.
    pub docker_capability: bool,
    /// Self-hosted container sandbox capability and coding harness.
    /// Disabled by default on all envs.
    /// Enable via `FEATURE_CONTAINER_SANDBOX=true`, or via the legacy
    /// fallback `FEATURE_DOCKER_CAPABILITY=true` when
    /// `FEATURE_CONTAINER_SANDBOX` is unset.
    pub container_sandbox: bool,
    /// Managed session-owned sandbox capability and lifecycle orchestration.
    /// Experimental and disabled by default.
    pub session_sandbox: bool,
    /// Machine-payment capabilities (e.g. the Parallel paid search/extract/task
    /// capability). Gates registration of any capability that spends real money
    /// through `PaymentAuthority`. Disabled by default on all envs, including dev,
    /// because spend is irreversible. Enable via `FEATURE_MACHINE_PAYMENTS=true`.
    pub machine_payments: bool,
}

impl InternalFeatureFlags {
    /// Compute internal feature flags from environment variables.
    pub fn from_env() -> Self {
        let docker_capability = standard_flag("FEATURE_DOCKER_CAPABILITY", false);

        Self {
            docker_capability,
            container_sandbox: standard_flag("FEATURE_CONTAINER_SANDBOX", docker_capability),
            session_sandbox: standard_flag("FEATURE_SESSION_SANDBOX", false),
            machine_payments: standard_flag("FEATURE_MACHINE_PAYMENTS", false),
        }
    }

    /// Look up a flag by name (for dynamic/string-based access).
    pub fn is_enabled(&self, flag: &str) -> bool {
        match flag {
            "docker_capability" => self.docker_capability,
            "container_sandbox" => self.container_sandbox,
            "session_sandbox" => self.session_sandbox,
            "machine_payments" => self.machine_payments,
            _ => false,
        }
    }
}

/// Resolve an experimental flag.
///
/// Priority: explicit env var > experimental default (enabled in dev) > false.
fn experimental_flag(env_var: &str, grade: &DeploymentGrade) -> bool {
    if let Ok(val) = std::env::var(env_var) {
        return val == "true" || val == "1";
    }
    grade.experimental_features_enabled()
}

/// Resolve a standard (non-experimental) flag.
///
/// Priority: explicit env var > default.
fn standard_flag(env_var: &str, default: bool) -> bool {
    std::env::var(env_var)
        .map(|v| v == "true" || v == "1")
        .unwrap_or(default)
}

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

    // Env-var-mutating tests must not run in parallel.
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn lock_env() -> std::sync::MutexGuard<'static, ()> {
        ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Restore an env var to a previously captured value, or remove it if it was unset.
    fn restore_env(key: &str, prev: Option<String>) {
        match prev {
            Some(value) => unsafe { std::env::set_var(key, value) },
            None => unsafe { std::env::remove_var(key) },
        }
    }

    #[test]
    fn test_default_flags() {
        let flags = FeatureFlags::default();
        assert!(!flags.global_chat);
        assert!(!flags.notifications);
    }

    // SAFETY: env var tests must run single-threaded (--test-threads=1).
    // set_var/remove_var are unsafe in edition 2024 due to thread-safety.

    #[test]
    fn test_experimental_enabled_in_dev() {
        let _lock = lock_env();
        unsafe { std::env::remove_var("FEATURE_GLOBAL_CHAT") };
        unsafe { std::env::remove_var("FEATURE_EVALS") };
        let flags = FeatureFlags::from_env(&DeploymentGrade::Dev);
        assert!(flags.global_chat);
        assert!(flags.evals);
    }

    #[test]
    fn test_experimental_disabled_in_prod() {
        let _lock = lock_env();
        unsafe { std::env::remove_var("FEATURE_GLOBAL_CHAT") };
        unsafe { std::env::remove_var("FEATURE_EVALS") };
        let flags = FeatureFlags::from_env(&DeploymentGrade::Prod);
        assert!(!flags.global_chat);
        assert!(!flags.evals);
    }

    #[test]
    fn test_env_override_enables_in_prod() {
        let _lock = lock_env();
        unsafe { std::env::set_var("FEATURE_GLOBAL_CHAT", "true") };
        let flags = FeatureFlags::from_env(&DeploymentGrade::Prod);
        assert!(flags.global_chat);
        unsafe { std::env::remove_var("FEATURE_GLOBAL_CHAT") };
    }

    #[test]
    fn test_env_override_disables_in_dev() {
        let _lock = lock_env();
        unsafe { std::env::set_var("FEATURE_GLOBAL_CHAT", "false") };
        let flags = FeatureFlags::from_env(&DeploymentGrade::Dev);
        assert!(!flags.global_chat);
        unsafe { std::env::remove_var("FEATURE_GLOBAL_CHAT") };
    }

    #[test]
    fn test_is_enabled_dynamic() {
        let flags = FeatureFlags {
            global_chat: true,
            notifications: true,
            mcp_endpoint: true,
            evals: true,
            app_budgets: true,
            agent_versions: true,
            voice: true,
            apps_detail_v2: true,
            agent_delegation: true,
        };
        assert!(flags.is_enabled("global_chat"));
        assert!(flags.is_enabled("notifications"));
        assert!(flags.is_enabled("mcp_endpoint"));
        assert!(flags.is_enabled("evals"));
        assert!(flags.is_enabled("app_budgets"));
        assert!(flags.is_enabled("agent_versions"));
        assert!(flags.is_enabled("voice"));
        assert!(flags.is_enabled("apps.detailV2"));
        assert!(flags.is_enabled("agent_delegation"));
        assert!(!flags.is_enabled("nonexistent"));
    }

    #[test]
    fn test_serialization() {
        let flags = FeatureFlags {
            global_chat: true,
            notifications: true,
            mcp_endpoint: true,
            evals: true,
            app_budgets: true,
            agent_versions: true,
            voice: true,
            apps_detail_v2: true,
            agent_delegation: true,
        };
        let json = serde_json::to_string(&flags).unwrap();
        assert!(json.contains("\"global_chat\":true"));
        assert!(json.contains("\"notifications\":true"));
        assert!(json.contains("\"app_budgets\":true"));
        assert!(json.contains("\"agent_versions\":true"));
        assert!(json.contains("\"voice\":true"));
        assert!(json.contains("\"apps.detailV2\":true"));
        assert!(json.contains("\"agent_delegation\":true"));

        let parsed: FeatureFlags = serde_json::from_str(&json).unwrap();
        assert_eq!(flags, parsed);
    }

    #[test]
    fn test_agent_delegation_enabled_in_dev() {
        let _lock = lock_env();
        unsafe { std::env::remove_var("FEATURE_AGENT_DELEGATION") };
        let flags = FeatureFlags::from_env(&DeploymentGrade::Dev);
        assert!(flags.agent_delegation);
    }

    #[test]
    fn test_agent_delegation_disabled_in_prod() {
        let _lock = lock_env();
        unsafe { std::env::remove_var("FEATURE_AGENT_DELEGATION") };
        let flags = FeatureFlags::from_env(&DeploymentGrade::Prod);
        assert!(!flags.agent_delegation);
    }

    #[test]
    fn test_agent_delegation_env_override_in_prod() {
        let _lock = lock_env();
        unsafe { std::env::set_var("FEATURE_AGENT_DELEGATION", "true") };
        let flags = FeatureFlags::from_env(&DeploymentGrade::Prod);
        assert!(flags.agent_delegation);
        unsafe { std::env::remove_var("FEATURE_AGENT_DELEGATION") };
    }

    #[test]
    fn test_standard_flag() {
        let _lock = lock_env();
        unsafe { std::env::remove_var("FEATURE_TEST_STD") };
        assert!(!standard_flag("FEATURE_TEST_STD", false));
        assert!(standard_flag("FEATURE_TEST_STD", true));

        unsafe { std::env::set_var("FEATURE_TEST_STD", "1") };
        assert!(standard_flag("FEATURE_TEST_STD", false));
        unsafe { std::env::remove_var("FEATURE_TEST_STD") };
    }

    #[test]
    fn test_notifications_enabled_in_dev() {
        let _lock = lock_env();
        unsafe { std::env::remove_var("FEATURE_NOTIFICATIONS") };
        let flags = FeatureFlags::from_env(&DeploymentGrade::Dev);
        assert!(flags.notifications);
    }

    #[test]
    fn test_notifications_disabled_in_prod() {
        let _lock = lock_env();
        unsafe { std::env::remove_var("FEATURE_NOTIFICATIONS") };
        let flags = FeatureFlags::from_env(&DeploymentGrade::Prod);
        assert!(!flags.notifications);
    }

    #[test]
    fn test_for_org_requires_system_and_opt_in() {
        let system = FeatureFlags {
            global_chat: true,
            evals: true,
            ..FeatureFlags::default()
        };
        let mut org = std::collections::HashMap::new();
        org.insert("global_chat".to_string(), true);
        let effective = FeatureFlags::for_org(&system, &org);
        assert!(effective.global_chat);
        assert!(!effective.evals);

        let effective_none = FeatureFlags::for_org(&system, &std::collections::HashMap::new());
        assert!(!effective_none.global_chat);
    }

    #[test]
    fn test_for_org_cannot_enable_when_system_off() {
        let system = FeatureFlags::default();
        let mut org = std::collections::HashMap::new();
        org.insert("global_chat".to_string(), true);
        let effective = FeatureFlags::for_org(&system, &org);
        assert!(!effective.global_chat);
    }

    #[test]
    fn test_notifications_respects_env_override() {
        let _lock = lock_env();
        unsafe { std::env::set_var("FEATURE_NOTIFICATIONS", "true") };
        let flags = FeatureFlags::from_env(&DeploymentGrade::Prod);
        assert!(flags.notifications);
        unsafe { std::env::remove_var("FEATURE_NOTIFICATIONS") };
    }

    // =========================================================================
    // InternalFeatureFlags tests
    // =========================================================================

    #[test]
    fn test_internal_default_flags() {
        let flags = InternalFeatureFlags::default();
        assert!(!flags.docker_capability);
        assert!(!flags.container_sandbox);
        assert!(!flags.session_sandbox);
        assert!(!flags.machine_payments);
    }

    #[test]
    fn test_docker_capability_flag_disabled_by_default_in_dev() {
        let _lock = lock_env();
        unsafe { std::env::remove_var("FEATURE_DOCKER_CAPABILITY") };
        let flags = InternalFeatureFlags::from_env();
        assert!(
            !flags.docker_capability,
            "docker_capability should be disabled by default even in dev"
        );
    }

    #[test]
    fn test_docker_capability_flag_enabled_by_env_override() {
        let _lock = lock_env();
        unsafe { std::env::set_var("FEATURE_DOCKER_CAPABILITY", "true") };
        let flags = InternalFeatureFlags::from_env();
        assert!(flags.docker_capability);
        unsafe { std::env::remove_var("FEATURE_DOCKER_CAPABILITY") };
    }

    #[test]
    fn test_container_sandbox_flag_enabled_by_env_override() {
        let _lock = lock_env();
        unsafe { std::env::set_var("FEATURE_CONTAINER_SANDBOX", "true") };
        unsafe { std::env::remove_var("FEATURE_DOCKER_CAPABILITY") };
        let flags = InternalFeatureFlags::from_env();
        assert!(flags.container_sandbox);
        unsafe { std::env::remove_var("FEATURE_CONTAINER_SANDBOX") };
    }

    #[test]
    fn test_container_sandbox_flag_falls_back_to_legacy_docker_flag() {
        let _lock = lock_env();
        unsafe { std::env::remove_var("FEATURE_CONTAINER_SANDBOX") };
        unsafe { std::env::set_var("FEATURE_DOCKER_CAPABILITY", "true") };
        let flags = InternalFeatureFlags::from_env();
        assert!(flags.container_sandbox);
        unsafe { std::env::remove_var("FEATURE_DOCKER_CAPABILITY") };
    }

    #[test]
    fn test_internal_is_enabled_dynamic() {
        let flags = InternalFeatureFlags {
            docker_capability: true,
            container_sandbox: true,
            session_sandbox: true,
            machine_payments: true,
        };
        assert!(flags.is_enabled("docker_capability"));
        assert!(flags.is_enabled("container_sandbox"));
        assert!(flags.is_enabled("session_sandbox"));
        assert!(flags.is_enabled("machine_payments"));
        assert!(!flags.is_enabled("nonexistent"));
    }

    #[test]
    fn test_machine_payments_disabled_by_default() {
        let _lock = lock_env();
        let prev = std::env::var("FEATURE_MACHINE_PAYMENTS").ok();
        unsafe { std::env::remove_var("FEATURE_MACHINE_PAYMENTS") };
        let flags = InternalFeatureFlags::from_env();
        assert!(
            !flags.machine_payments,
            "machine_payments should be disabled by default on all envs"
        );
        restore_env("FEATURE_MACHINE_PAYMENTS", prev);
    }

    #[test]
    fn test_machine_payments_enabled_by_env_override() {
        let _lock = lock_env();
        let prev = std::env::var("FEATURE_MACHINE_PAYMENTS").ok();
        unsafe { std::env::set_var("FEATURE_MACHINE_PAYMENTS", "true") };
        let flags = InternalFeatureFlags::from_env();
        assert!(flags.machine_payments);
        restore_env("FEATURE_MACHINE_PAYMENTS", prev);
    }

    #[test]
    fn test_session_sandbox_flag_enabled_by_env_override() {
        let _lock = lock_env();
        unsafe { std::env::set_var("FEATURE_SESSION_SANDBOX", "true") };
        let flags = InternalFeatureFlags::from_env();
        assert!(flags.session_sandbox);
        unsafe { std::env::remove_var("FEATURE_SESSION_SANDBOX") };
    }
}