octomind 0.25.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
// Copyright 2026 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.

// Command executor for /run commands using layers

use crate::config::Config;
use crate::session::chat::format_number;
use crate::session::chat::session::ChatSession;
use crate::session::{layers::layer_trait::Layer, layers::GenericLayer};
use anyhow::Result;
use colored::Colorize;

/// Execute a command layer without storing it in the session history
pub async fn execute_command_layer(
	command_name: &str,
	provided_input: &str,
	chat_session: &mut ChatSession,
	config: &Config,
	role: &str,
	operation_cancelled: tokio::sync::watch::Receiver<bool>,
) -> Result<String> {
	// Get role configuration to check for command layers
	let (_, _, _, commands_config, _) = config.get_role_config(role);

	// Find the command configuration
	let command_config = commands_config
		.and_then(|commands| commands.iter().find(|cmd| cmd.name == command_name))
		.ok_or_else(|| anyhow::anyhow!("Command '{}' not found in configuration", command_name))?;

	println!(
		"{} {}",
		"Executing command:".bright_cyan(),
		command_name.bright_yellow()
	);

	// Log the command execution
	if let Some(session_file) = &chat_session.session.session_file {
		let log_entry = serde_json::json!({
			"type": "COMMAND_EXEC",
			"timestamp": std::time::SystemTime::now()
			.duration_since(std::time::UNIX_EPOCH)
			.unwrap_or_default()
			.as_secs(),
			"command": command_name,
			"role": role,
			"config": {
			"model": command_config.get_effective_model(&chat_session.session.info.model),
			"temperature": command_config.temperature,
			"input_mode": format!("{:?}", command_config.input_mode),
			"mcp_enabled": !command_config.mcp.server_refs.is_empty()
		}
		});
		let _ = crate::session::append_to_session_file(
			session_file,
			&serde_json::to_string(&log_entry)?,
		);
	}

	// Create a generic layer with processed system prompt
	let mut processed_config = command_config.clone();
	// Process system prompt placeholders before creating layer
	// Use thread-local if set (ACP/WebSocket), otherwise process cwd
	if let Some(ref system_prompt) = processed_config.system_prompt {
		let current_dir = crate::mcp::get_thread_working_directory();
		let processed = crate::session::helper_functions::process_placeholders_async(
			system_prompt,
			&current_dir,
		)
		.await;
		processed_config.processed_system_prompt = Some(processed);
	}
	let command_layer = GenericLayer::new(processed_config);

	// Prepare the input according to the command's input_mode
	// CRITICAL FIX: Always use prepare_input to respect the input_mode setting
	// The input_mode determines what context the command should receive:
	// - "last": Get the last assistant response from session
	// - "all": Get all conversation context
	// - "summary": Get a summarized version
	let processed_input = match command_config.input_mode {
		crate::session::layers::layer_trait::InputMode::Last => {
			// For "Last" mode, always use prepare_input to get the last assistant response
			// If explicit input is provided, it will be combined with the last assistant context
			command_layer.prepare_input(provided_input, &chat_session.session)
		}
		crate::session::layers::layer_trait::InputMode::All => {
			// For "All" mode, use prepare_input to format the full conversation context
			command_layer.prepare_input(provided_input, &chat_session.session)
		}
		crate::session::layers::layer_trait::InputMode::Summary => {
			// For "Summary" mode, use prepare_input to generate a summary
			command_layer.prepare_input(provided_input, &chat_session.session)
		}
	};

	// Log the processed input
	if let Some(session_file) = &chat_session.session.session_file {
		let log_entry = serde_json::json!({
			"type": "COMMAND_INPUT",
			"timestamp": std::time::SystemTime::now()
			.duration_since(std::time::UNIX_EPOCH)
			.unwrap_or_default()
			.as_secs(),
			"command": command_name,
			"input_length": processed_input.len(),
			"input_mode": format!("{:?}", command_config.input_mode)
		});
		let _ = crate::session::append_to_session_file(
			session_file,
			&serde_json::to_string(&log_entry)?,
		);
	}

	// Execute the layer without affecting the session
	let result = command_layer
		.process(
			&processed_input,
			&chat_session.session,
			config,
			operation_cancelled,
		)
		.await?;

	// Log the command result
	if let Some(session_file) = &chat_session.session.session_file {
		let log_entry = serde_json::json!({
			"type": "COMMAND_RESULT",
			"timestamp": std::time::SystemTime::now()
			.duration_since(std::time::UNIX_EPOCH)
			.unwrap_or_default()
			.as_secs(),
			"command": command_name,
			"output_length": result.outputs.iter().map(|s| s.len()).sum::<usize>(),
			"usage": result.token_usage
		});
		let _ = crate::session::append_to_session_file(
			session_file,
			&serde_json::to_string(&log_entry)?,
		);
	}

	// Add command statistics to the session
	if let Some(usage) = &result.token_usage {
		let effective_model = command_config.get_effective_model(&chat_session.session.info.model);
		let cost = usage.cost.unwrap_or(0.0);

		// Add the stats to the session with a special prefix for commands
		chat_session.session.add_layer_stats(
			&format!("command:{command_name}"),
			&effective_model,
			usage.input_tokens,
			usage.output_tokens,
			cost,
		);

		// Save the session to persist the statistics
		let _ = chat_session.save();

		// Save the session to persist the statistics
		let _ = chat_session.save();

		// Display information about the command execution
		println!(
			"{} {} input, {} completion tokens",
			"Command usage:".bright_blue(),
			format_number(usage.input_tokens).bright_green(),
			format_number(usage.output_tokens).bright_green()
		);

		if cost > 0.0 {
			println!(
				"{} ${:.5}",
				"Command cost:".bright_blue(),
				cost.to_string().bright_magenta()
			);
		}
	}

	// Handle output_mode to determine how this command's output affects the session
	use crate::session::layers::layer_trait::OutputMode;
	match command_config.output_mode {
		OutputMode::None => {
			// Command output is returned but doesn't modify session (default behavior)
			println!(
				"{}",
				"Output mode: none (command output only)".bright_cyan()
			);
		}
		OutputMode::Append => {
			// Add command output as new assistant message to session
			println!(
				"{}",
				"Output mode: append (adding to session)".bright_cyan()
			);
			// Add all command outputs as messages with configured role
			for output_text in &result.outputs {
				chat_session
					.session
					.add_message(command_config.output_role.as_str(), output_text);
			}

			// Log the append operation for session restoration
			if let Some(session_file) = &chat_session.session.session_file {
				let log_entry = serde_json::json!({
					"type": "OUTPUT_MODE_APPEND",
					"timestamp": std::time::SystemTime::now()
						.duration_since(std::time::UNIX_EPOCH)
						.unwrap_or_default()
						.as_secs(),
					"command": command_name,
					"content_length": result.outputs.iter().map(|s| s.len()).sum::<usize>()
				});
				let _ = crate::session::append_to_session_file(
					session_file,
					&serde_json::to_string(&log_entry)?,
				);
			}

			// Save session to persist the new message
			let _ = chat_session.save();
		}
		OutputMode::Replace => {
			// Replace entire session with this command's output
			println!(
				"{}",
				"Output mode: replace (replacing session content)".bright_cyan()
			);

			// Log the replace operation for session restoration
			if let Some(session_file) = &chat_session.session.session_file {
				let log_entry = serde_json::json!({
					"type": "OUTPUT_MODE_REPLACE",
					"timestamp": std::time::SystemTime::now()
						.duration_since(std::time::UNIX_EPOCH)
						.unwrap_or_default()
						.as_secs(),
					"command": command_name,
					"previous_message_count": chat_session.session.messages.len(),
					"content_length": result.outputs.iter().map(|s| s.len()).sum::<usize>()
				});
				let _ = crate::session::append_to_session_file(
					session_file,
					&serde_json::to_string(&log_entry)?,
				);
			}

			// Find system message to preserve
			let system_message = chat_session
				.session
				.messages
				.iter()
				.find(|m| m.role == "system")
				.cloned();

			// Clear existing messages
			chat_session.session.messages.clear();

			// Build final message list following /truncate pattern
			let mut final_messages = Vec::new();

			// Add system message first
			if let Some(sys_msg) = system_message {
				final_messages.push(sys_msg);
			}
			// Add initial messages (welcome + instructions) using centralized function
			// Use thread-local if set (ACP/WebSocket), otherwise process cwd
			let current_dir = crate::mcp::get_thread_working_directory();
			if let Ok(initial_messages) =
				crate::session::chat::session::get_initial_messages(config, role, &current_dir)
					.await
			{
				final_messages.extend(initial_messages);
			}

			// Add all command outputs with configured role
			for output_text in &result.outputs {
				let output_msg = crate::session::Message {
					role: command_config.output_role.as_str().to_string(),
					content: output_text.clone(),
					timestamp: std::time::SystemTime::now()
						.duration_since(std::time::UNIX_EPOCH)
						.unwrap_or_default()
						.as_secs(),
					cached: false,
					tool_calls: None,
					tool_call_id: None,
					name: None,
					images: None,
					..Default::default()
				};
				final_messages.push(output_msg);
			}

			// Update session with final messages
			chat_session.session.messages = final_messages;

			// Save session to persist the replacement
			let _ = chat_session.save();
		}
		OutputMode::Last => {
			// Add only the last command output as assistant message to session
			println!(
				"{}",
				"Output mode: last (adding last response only to session)".bright_cyan()
			);

			// Add only the last output as message with configured role to session
			if let Some(last_output) = result.outputs.last() {
				chat_session
					.session
					.add_message(command_config.output_role.as_str(), last_output);
			}

			// Log the last append operation for session restoration
			if let Some(session_file) = &chat_session.session.session_file {
				let log_entry = serde_json::json!({
					"type": "OUTPUT_MODE_LAST",
					"timestamp": std::time::SystemTime::now()
						.duration_since(std::time::UNIX_EPOCH)
						.unwrap_or_default()
						.as_secs(),
					"command": command_name,
					"content_length": result.outputs.last().map(|s| s.len()).unwrap_or(0),
					"total_outputs": result.outputs.len()
				});
				let _ = crate::session::append_to_session_file(
					session_file,
					&serde_json::to_string(&log_entry)?,
				);
			}

			// Save session to persist the new message
			let _ = chat_session.save();
		}
		OutputMode::Restart => {
			// Replace entire session with only the last command output (fresh start)
			println!(
				"{}",
				"Output mode: restart (replacing session with last response only)".bright_cyan()
			);

			// Log the restart operation for session restoration
			if let Some(session_file) = &chat_session.session.session_file {
				let log_entry = serde_json::json!({
					"type": "OUTPUT_MODE_RESTART",
					"timestamp": std::time::SystemTime::now()
						.duration_since(std::time::UNIX_EPOCH)
						.unwrap_or_default()
						.as_secs(),
					"command": command_name,
					"previous_message_count": chat_session.session.messages.len(),
					"content_length": result.outputs.last().map(|s| s.len()).unwrap_or(0),
					"total_outputs": result.outputs.len()
				});
				let _ = crate::session::append_to_session_file(
					session_file,
					&serde_json::to_string(&log_entry)?,
				);
			}

			// Clear existing messages and replace with only the last command output
			chat_session.session.messages.clear();
			if let Some(last_output) = result.outputs.last() {
				chat_session
					.session
					.add_message(command_config.output_role.as_str(), last_output);
			}

			// Save session to persist the replacement
			let _ = chat_session.save();
		}
	}

	Ok(result.outputs.last().unwrap_or(&String::new()).clone())
}

/// List all available command layers for the current role
pub fn list_available_commands(config: &Config, role: &str) -> Vec<String> {
	let (_, _, _, commands_config, _) = config.get_role_config(role);

	commands_config
		.map(|commands| commands.iter().map(|cmd| cmd.name.clone()).collect())
		.unwrap_or_else(Vec::new)
}

/// Check if a command exists for the current role
pub fn command_exists(config: &Config, role: &str, command_name: &str) -> bool {
	let (_, _, _, commands_config, _) = config.get_role_config(role);

	commands_config
		.map(|commands| commands.iter().any(|cmd| cmd.name == command_name))
		.unwrap_or(false)
}

/// Get help text for command layers
pub fn get_command_help(config: &Config, role: &str) -> String {
	let (_, _, _, commands_config, _) = config.get_role_config(role);

	if let Some(commands) = commands_config {
		if commands.is_empty() {
			"No command layers configured.".to_string()
		} else {
			let mut help_text = String::from("Available command layers:\n");
			for command in commands {
				help_text.push_str(&format!(
					"  /run {} - {}\n",
					command.name, command.description
				));
			}
			help_text.push_str("\nUsage: /run <command_name>\nExample: /run reduce");
			help_text
		}
	} else {
		"No command layers configured.".to_string()
	}
}