octomind 0.16.0

Session-based AI development assistant with conversational codebase interaction, multimodal vision support, built-in MCP tools, and multi-provider AI integration
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
// Copyright 2025 Muvon Un Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};

// Global environment tracker for source detection
static ENV_TRACKER: OnceLock<Mutex<env_source::EnvTracker>> = OnceLock::new();

/// Get global environment tracker instance
pub fn get_env_tracker() -> &'static Mutex<env_source::EnvTracker> {
	ENV_TRACKER.get_or_init(|| Mutex::new(env_source::EnvTracker::new()))
}

// Re-export all modules
pub mod env_source;
pub mod layers;
pub mod loading;
pub mod mcp;
pub mod migrations;
pub mod providers;
pub mod roles;
pub mod validation;

// Tests removed - strict configuration mode doesn't support Default implementations
// Tests should be rewritten to use complete config structures

// Re-export commonly used types
pub use layers::*;
pub use mcp::*;
pub use providers::*;
pub use roles::*;

// Agent configuration - removed, now uses LayerConfig directly

// Current config version - increment when making breaking changes
pub const CURRENT_CONFIG_VERSION: u32 = 1;

// Type alias to simplify the complex return type for get_role_config
type RoleConfigResult<'a> = (
	&'a RoleConfig,
	&'a RoleMcpConfig,
	Option<&'a Vec<crate::session::layers::LayerConfig>>,
	Option<&'a Vec<crate::session::layers::LayerConfig>>,
	&'a String,
);

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub enum LogLevel {
	#[serde(rename = "none")]
	None,
	#[serde(rename = "info")]
	Info,
	#[serde(rename = "debug")]
	Debug,
}

// REMOVED: Default implementation - LogLevel must be explicitly set in config

impl LogLevel {
	/// Check if info logging is enabled
	pub fn is_info_enabled(&self) -> bool {
		matches!(self, LogLevel::Info | LogLevel::Debug)
	}

	/// Check if debug logging is enabled
	pub fn is_debug_enabled(&self) -> bool {
		matches!(self, LogLevel::Debug)
	}
}

// REMOVED: All default functions - config must be complete and explicit

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AskConfig {
	/// System prompt for ask command
	pub system: String,
	/// Default temperature for ask command (0.0 to 1.0)
	pub temperature: f32,
	/// Default top_p for ask command (0.0 to 1.0)
	pub top_p: f32,
	/// Default top_k for ask command (1 to infinity)
	pub top_k: u32,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ShellConfig {
	/// System prompt for shell command
	pub system: String,
	/// Default temperature for shell command (0.0 to 1.0)
	pub temperature: f32,
	/// Default top_p for shell command (0.0 to 1.0)
	pub top_p: f32,
	/// Default top_k for shell command (1 to infinity)
	pub top_k: u32,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PromptConfig {
	/// Name of the prompt (used with /prompt command)
	pub name: String,
	/// The prompt template text
	pub prompt: String,
	/// Optional description for help display
	pub description: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Config {
	// Config version for future migrations (always first field)
	pub version: u32,

	// Root-level log level setting (takes precedence over role-specific)
	pub log_level: LogLevel,

	// Root-level model setting (used by all commands if specified)
	pub model: String,

	// Root-level max_tokens setting (used by all commands if specified)
	pub max_tokens: u32,

	// Custom instructions file name (relative to project root)
	pub custom_instructions_file_name: String,

	// Custom constraints file name (relative to project root)
	pub custom_constraints_file_name: String,

	// System-wide configuration settings (not role-specific)
	pub mcp_response_warning_threshold: usize,
	pub mcp_response_tokens_threshold: usize,
	pub max_session_tokens_threshold: usize,
	pub cache_tokens_threshold: u64,
	pub cache_timeout_seconds: u64,
	pub enable_markdown_rendering: bool,
	// Markdown theme for styling
	pub markdown_theme: String,
	// Session spending threshold in USD - if > 0, prompt user when exceeded
	pub max_session_spending_threshold: f64,
	// Request spending threshold in USD - if > 0, stop execution when exceeded during single request
	pub max_request_spending_threshold: f64,

	// Use long-term (1h) caching for system messages (strict: must be in config)
	pub use_long_system_cache: bool,

	// Maximum number of retries for API calls (can be overridden by --max-retries CLI flag)
	pub max_retries: u32,

	// Base timeout for exponential backoff retry logic (config-only, no CLI override)
	pub retry_timeout: u32,

	// Agent configurations - array of layer definitions (same structure as commands)
	#[serde(default)]
	pub agents: Vec<crate::session::layers::LayerConfig>,

	// REMOVED: Providers configuration - API keys now only from ENV variables for security

	// Role configurations - array format like layers
	pub roles: Vec<crate::config::roles::Role>,

	// Internal role lookup map (populated during loading)
	#[serde(skip)]
	pub role_map: HashMap<String, crate::config::roles::Role>,

	// Global MCP configuration (fallback for roles)
	#[serde(skip_serializing_if = "McpConfig::is_default_for_serialization")]
	pub mcp: McpConfig,

	// Global command configurations (fallback for roles) - array format consistent with layers
	pub commands: Option<Vec<crate::session::layers::LayerConfig>>,

	// Global layer configurations - array of layer definitions
	pub layers: Option<Vec<crate::session::layers::LayerConfig>>,

	// Ask command configuration
	pub ask: AskConfig,

	// Shell command configuration
	pub shell: ShellConfig,

	// Prompt template configurations
	pub prompts: Vec<PromptConfig>,

	// Legacy system prompt field for backward compatibility
	pub system: Option<String>,

	#[serde(skip)]
	config_path: Option<PathBuf>,
}

impl McpConfig {
	/// Check if this config should be skipped during serialization
	/// This helps avoid writing empty [mcp] sections when only internal servers exist
	pub fn is_default_for_serialization(&self) -> bool {
		self.servers.is_empty() && self.allowed_tools.is_empty()
	}

	/// Get all servers from the registry (for populating role configs)
	/// Now relies entirely on config - no more runtime injection
	pub fn get_all_servers(&self) -> Vec<McpServerConfig> {
		let mut result = Vec::new();

		// Add servers from loaded registry
		for server_config in &self.servers {
			let server = server_config.clone();
			// Name is already set in the server config
			result.push(server);
		}

		result
	}

	/// Create a config using server configurations
	pub fn with_servers(
		servers: std::collections::HashMap<String, McpServerConfig>,
		allowed_tools: Option<Vec<String>>,
	) -> Self {
		// Convert HashMap to Vec, ensuring names match keys
		let servers_vec: Vec<McpServerConfig> = servers
			.into_iter()
			.map(|(name, server)| {
				// Recreate server with correct name if it doesn't match
				match server {
					McpServerConfig::Builtin {
						timeout_seconds,
						tools,
						..
					} => McpServerConfig::Builtin {
						name,
						timeout_seconds,
						tools,
					},
					McpServerConfig::Http {
						connection,
						timeout_seconds,
						tools,
						..
					} => McpServerConfig::Http {
						name,
						connection,
						timeout_seconds,
						tools,
					},
					McpServerConfig::Stdin {
						command,
						args,
						timeout_seconds,
						tools,
						..
					} => McpServerConfig::Stdin {
						name,
						command,
						args,
						timeout_seconds,
						tools,
					},
				}
			})
			.collect();

		Self {
			servers: servers_vec,
			allowed_tools: allowed_tools.unwrap_or_default(),
		}
	}
}

impl Config {
	/// Get the effective model to use - uses root config model (now always required)
	pub fn get_effective_model(&self) -> String {
		// Model is now always required in config, no fallback needed
		self.model.clone()
	}

	/// Get the effective max_tokens to use - uses root config max_tokens (now always required)
	pub fn get_effective_max_tokens(&self) -> u32 {
		// Max tokens is now always required in config, no fallback needed
		self.max_tokens
	}

	/// Get server configuration by name from the config registry
	/// Now relies entirely on config - no more runtime injection
	pub fn get_server_config(&self, server_name: &str) -> Option<McpServerConfig> {
		// Get from loaded registry
		self.mcp
			.servers
			.iter()
			.find(|s| s.name() == server_name)
			.cloned()
	}

	/// Get enabled layers for a role with layer references
	/// This ensures layers are filtered by role layer_refs
	pub fn get_enabled_layers_for_role(
		&self,
		role: &str,
	) -> Vec<crate::session::layers::LayerConfig> {
		self.get_enabled_layers(role)
	}

	/// Get enabled servers for a role with runtime core server injection
	/// This ensures core servers are ALWAYS available regardless of config file state
	pub fn get_enabled_servers_for_role(
		&self,
		role_mcp_config: &RoleMcpConfig,
	) -> Vec<McpServerConfig> {
		// Use the updated RoleMcpConfig method that has runtime injection
		role_mcp_config.get_enabled_servers(&self.mcp.servers)
	}
	/// Get the global log level (system-wide setting)
	pub fn get_log_level(&self) -> LogLevel {
		self.log_level.clone()
	}

	/// Role-based configuration getters - these delegate to role configs
	/// Get enable layers setting for the specified role
	pub fn get_enable_layers(&self, role: &str) -> bool {
		let (role_config, _, _, _, _) = self.get_role_config(role);
		role_config.enable_layers
	}

	/// Get the model for the specified role
	pub fn get_model(&self, _role: &str) -> String {
		// All roles now use the system-wide model
		self.get_effective_model()
	}

	/// Get the max_tokens for the specified role
	pub fn get_max_tokens(&self, _role: &str) -> u32 {
		// All roles now use the system-wide max_tokens
		self.get_effective_max_tokens()
	}

	/// Get configuration for a specific role
	/// Returns: (role_config, role_mcp_config, layers, commands, system_prompt)
	pub fn get_role_config(&self, role: &str) -> RoleConfigResult<'_> {
		if let Some(role_config) = self.role_map.get(role) {
			(
				&role_config.config,
				&role_config.mcp,
				self.layers.as_ref(),
				self.commands.as_ref(),
				&role_config.config.system,
			)
		} else {
			// STRICT CONFIG: Unknown roles are not allowed - all roles must be explicitly defined
			panic!("CRITICAL CONFIG ERROR: Role '{role}' not found in config. All roles must be explicitly defined in config template.");
		}
	}

	/// Get a merged config for a specific role (for backward compatibility)
	/// This creates a new Config with role-specific settings merged into system-wide settings
	pub fn get_merged_config_for_role(&self, mode: &str) -> Config {
		let (_role_config, role_mcp_config, _role_layers_config, commands, system_prompt) =
			self.get_role_config(mode);

		let mut merged = self.clone();

		// CRITICAL FIX: Create a legacy McpConfig for backward compatibility with existing code
		// Use the new runtime injection method to ensure core servers are ALWAYS available
		let enabled_servers = self.get_enabled_servers_for_role(role_mcp_config);

		crate::log_debug!(
			"TRACE: Role '{}' server_refs: {:?}",
			mode,
			role_mcp_config.server_refs
		);
		crate::log_debug!(
			"TRACE: Found {} enabled servers for role",
			enabled_servers.len()
		);

		for server in &enabled_servers {
			crate::log_debug!("TRACE: Adding server '{}' to merged config", server.name());
		}

		merged.mcp = McpConfig {
			servers: enabled_servers, // Only role-enabled servers (with runtime injection)
			allowed_tools: role_mcp_config.allowed_tools.clone(),
		};

		// Role-specific layers (only enabled via layer_refs) - NOT USED ANYWHERE
		// Keep merged.layers as original registry for agent tools
		// let enabled_layers = self.get_enabled_layers_for_role(mode);

		merged.commands = commands.cloned();
		merged.system = Some(system_prompt.clone());

		merged
	}

	/// Get the role config struct for a specific role
	pub fn get_role_config_struct(&self, role: &str) -> &RoleConfig {
		let (role_config, _, _, _, _) = self.get_role_config(role);
		role_config
	}

	/// Get layer references for a specific role
	pub fn get_layer_refs(&self, role: &str) -> &Vec<String> {
		if let Some(role_config) = self.role_map.get(role) {
			&role_config.layer_refs
		} else {
			// Return empty vec for unknown roles
			static EMPTY_VEC: Vec<String> = Vec::new();
			&EMPTY_VEC
		}
	}

	/// Get enabled layers for a specific role (filters global layers by role layer_refs)
	/// STRICT CONFIG: All referenced layers MUST exist in config - no fallbacks
	pub fn get_enabled_layers(&self, role: &str) -> Vec<crate::session::layers::LayerConfig> {
		let layer_refs = self.get_layer_refs(role);
		if layer_refs.is_empty() {
			return Vec::new();
		}

		// STRICT CONFIG CHECK: layers registry must exist
		let all_layers = if let Some(layers) = &self.layers {
			layers
		} else {
			panic!("CRITICAL CONFIG ERROR: No layers defined in config but role '{role}' references layers: {layer_refs:?}. All layers must be explicitly defined in config.");
		};

		let mut result = Vec::new();
		for layer_name in layer_refs {
			// STRICT CONFIG CHECK: referenced layer must exist
			let layer_config = all_layers
				.iter()
				.find(|layer| layer.name == *layer_name)
				.cloned();

			if let Some(mut layer) = layer_config {
				// Auto-set the name from the registry key
				layer.name = layer_name.clone();
				result.push(layer);
			} else {
				// STRICT CONFIG: Missing layer is CRITICAL error
				panic!("CRITICAL CONFIG ERROR: Layer '{layer_name}' referenced by role '{role}' but not found in config layers registry. All referenced layers must be explicitly defined in config.");
			}
		}

		result
	}

	/// Build the internal role map from the roles array for fast lookup
	pub fn build_role_map(&mut self) {
		self.role_map.clear();
		for role in &self.roles {
			self.role_map.insert(role.name.clone(), role.clone());
		}
	}
}

// Logging macros for different log levels
// These macros automatically check the current log level and only print if appropriate

thread_local! {
	static CURRENT_CONFIG: RefCell<Option<Config>> = const { RefCell::new(None) };
}

/// Set the current config for the thread (to be used by logging macros)
pub fn set_thread_config(config: &Config) {
	CURRENT_CONFIG.with(|c| {
		*c.borrow_mut() = Some(config.clone());
	});
}

/// Get the current config for the thread
pub fn with_thread_config<F, R>(f: F) -> Option<R>
where
	F: FnOnce(&Config) -> R,
{
	CURRENT_CONFIG.with(|c| (*c.borrow()).as_ref().map(f))
}

/// Info logging macro with automatic cyan coloring
/// Shows info messages when log level is Info OR Debug
#[macro_export]
macro_rules! log_info {
	($fmt:expr) => {
		if let Some(should_log) = $crate::config::with_thread_config(|config| config.get_log_level().is_info_enabled()) {
		if should_log {
		use colored::Colorize;
		println!("{}", $fmt.cyan());
		}
		}
	};
	($fmt:expr, $($arg:expr),*) => {
		if let Some(should_log) = $crate::config::with_thread_config(|config| config.get_log_level().is_info_enabled()) {
		if should_log {
		use colored::Colorize;
	println!("{}", format!($fmt, $($arg),*).cyan());
	}
	}
	};
}

/// Debug logging macro with automatic bright blue coloring
#[macro_export]
macro_rules! log_debug {
	($fmt:expr) => {
		if let Some(should_log) = $crate::config::with_thread_config(|config| config.get_log_level().is_debug_enabled()) {
		if should_log {
		use colored::Colorize;
		println!("{}", $fmt.bright_blue());
		}
		}
	};
	($fmt:expr, $($arg:expr),*) => {
		if let Some(should_log) = $crate::config::with_thread_config(|config| config.get_log_level().is_debug_enabled()) {
		if should_log {
		use colored::Colorize;
	println!("{}", format!($fmt, $($arg),*).bright_blue());
	}
	}
	};
}

/// Error logging macro with automatic bright red coloring
/// Always visible regardless of log level (errors should always be shown)
#[macro_export]
macro_rules! log_error {
	($fmt:expr) => {{
		use colored::Colorize;
		eprintln!("{}", $fmt.bright_red());
		}};
	($fmt:expr, $($arg:expr),*) => {{
		use colored::Colorize;
		eprintln!("{}", format!($fmt, $($arg),*).bright_red());
		}};
}

/// Conditional logging - prints different messages based on log level
#[macro_export]
macro_rules! log_conditional {
	(debug: $debug_msg:expr, info: $info_msg:expr, none: $none_msg:expr) => {
		if let Some(level) = $crate::config::with_thread_config(|config| config.get_log_level()) {
			match level {
				$crate::config::LogLevel::Debug => println!("{}", $debug_msg),
				$crate::config::LogLevel::Info => println!("{}", $info_msg),
				$crate::config::LogLevel::None => println!("{}", $none_msg),
			}
		} else {
			// Fallback if no config is set
			println!("{}", $none_msg);
		}
	};
	(debug: $debug_msg:expr, default: $default_msg:expr) => {
		if let Some(should_debug) =
			$crate::config::with_thread_config(|config| config.get_log_level().is_debug_enabled())
		{
			if should_debug {
				println!("{}", $debug_msg);
			} else {
				println!("{}", $default_msg);
			}
		} else {
			// Fallback if no config is set
			println!("{}", $default_msg);
		}
	};
	(info: $info_msg:expr, default: $default_msg:expr) => {
		if let Some(should_info) =
			$crate::config::with_thread_config(|config| config.get_log_level().is_info_enabled())
		{
			if should_info {
				println!("{}", $info_msg);
			} else {
				println!("{}", $default_msg);
			}
		} else {
			// Fallback if no config is set
			println!("{}", $default_msg);
		}
	};
}