swarm-engine-core 0.1.6

Core types and orchestration for SwarmEngine
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
//! Environment - アクション実行環境の抽象化
//!
//! すべてのアクション実行を Environment 経由で行うことで、
//! Actions/Env の組み合わせを外部から注入可能にする。
//!
//! # 設計
//!
//! ```text
//! GenericWorker.execute_action()
//!//!     └── Extensions.get::<EnvironmentBox>()
//!//!             └── env.step(worker_id, action) → WorkResult
//! ```
//!
//! # 重要
//!
//! - `step()` が唯一のアクション実行メソッド
//! - `WorkResult::Done` で終了を通知
//! - 観察が必要な場合は `Action("Look")` を送り、`step()` で処理する
//!
//! # 使用例
//!
//! ```ignore
//! // デフォルト環境(Bash/Read/Write/Grep/Glob)
//! let orchestrator = OrchestratorBuilder::new()
//!     .environment(Box::new(DefaultEnvironment::new()))
//!     .build();
//!
//! // カスタム環境(迷路)
//! let orchestrator = OrchestratorBuilder::new()
//!     .environment(Box::new(MazeEnvironment::from_map(map)))
//!     .build();
//! ```

use crate::agent::WorkResult;
use crate::types::{Action, WorkerId};

// ============================================================================
// Environment Trait
// ============================================================================

/// アクション実行環境トレイト
///
/// すべてのアクション実行はこのトレイトを通じて行われる。
/// DefaultEnvironment(Bash/Read等)やカスタム環境(Maze等)を
/// 同じインターフェースで扱える。
///
/// # 設計原則
///
/// - `step()` がすべてのアクションを処理する唯一のメソッド
/// - `WorkResult::Done` で終了を通知
/// - 観察(Look等)も Action として `step()` 経由で実行
///
/// # 内部可変性
///
/// `step` メソッドは `&self` を受け取るため、内部状態を変更する必要がある
/// 環境(MazeEnvironment など)は `Mutex` や `RwLock` を使用すること。
pub trait Environment: Send + Sync {
    /// アクション実行
    ///
    /// すべてのアクション(移動、観察、待機等)をこのメソッドで処理する。
    ///
    /// # Arguments
    ///
    /// * `worker_id` - 実行する Worker の ID
    /// * `action` - 実行するアクション
    ///
    /// # Returns
    ///
    /// `WorkResult` - 実行結果を直接返す
    ///
    /// - `WorkResult::Acted` - 通常のアクション結果
    /// - `WorkResult::Done` - タスク完了
    /// - `WorkResult::env_success()` / `WorkResult::env_failure()` 等のヘルパーを使用
    ///
    /// # Example
    ///
    /// ```ignore
    /// // 移動アクション
    /// let action = Action::new("Move").with_arg("target", "north");
    /// let result = env.step(worker_id, &action);
    ///
    /// // 観察アクション
    /// let action = Action::new("Look");
    /// let result = env.step(worker_id, &action);
    /// // ActionResult.output に JSON データ
    /// ```
    fn step(&self, worker_id: WorkerId, action: &Action) -> WorkResult;

    /// 環境をリセット
    ///
    /// 評価システムが複数回実行する際に使用。
    fn reset(&self);

    /// 環境名
    fn name(&self) -> &str;
}

// ============================================================================
// EnvironmentBox (Type alias)
// ============================================================================

/// Environment の Box 型エイリアス
pub type EnvironmentBox = Box<dyn Environment>;

// ============================================================================
// DefaultEnvironment
// ============================================================================

use std::fs;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::Command;

/// デフォルト環境 - ファイル操作・シェルコマンド
///
/// 従来の GenericWorker がサポートしていたアクションを Environment 経由で提供。
///
/// # サポートするアクション
///
/// - `Bash`: シェルコマンド実行
/// - `Read`: ファイル読み込み
/// - `Write`: ファイル書き込み
/// - `Grep`: パターン検索(ファイル内)
/// - `Glob`: ファイル検索(パターンマッチ)
/// - `Answer`: 回答(成功扱い)
/// - `Continue`: 継続(成功扱い)
pub struct DefaultEnvironment {
    /// 作業ディレクトリ
    working_dir: PathBuf,
}

impl DefaultEnvironment {
    /// 新しい DefaultEnvironment を作成
    pub fn new() -> Self {
        Self {
            working_dir: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
        }
    }

    /// 作業ディレクトリを指定して作成
    pub fn with_working_dir(working_dir: impl Into<PathBuf>) -> Self {
        Self {
            working_dir: working_dir.into(),
        }
    }

    // ------------------------------------------------------------------------
    // Action Handlers
    // ------------------------------------------------------------------------

    fn handle_bash(&self, action: &Action) -> WorkResult {
        let command = action.params.target.as_deref().unwrap_or("");

        let mut cmd = Command::new("sh");
        cmd.arg("-c").arg(command);
        cmd.current_dir(&self.working_dir);

        match cmd.output() {
            Ok(output) => {
                let stdout = String::from_utf8_lossy(&output.stdout).to_string();
                let stderr = String::from_utf8_lossy(&output.stderr).to_string();

                if output.status.success() {
                    WorkResult::env_success_with_data("Command executed successfully", stdout)
                } else {
                    WorkResult::env_failure(format!(
                        "Exit code: {:?}\nstderr: {}",
                        output.status.code(),
                        stderr
                    ))
                }
            }
            Err(e) => WorkResult::env_failure(format!("Failed to execute: {}", e)),
        }
    }

    fn handle_read(&self, action: &Action) -> WorkResult {
        let path = action.params.target.as_deref().unwrap_or("");
        let full_path = self.resolve_path(path);

        match fs::read_to_string(&full_path) {
            Ok(content) => WorkResult::env_success_with_data("File read successfully", content),
            Err(e) => WorkResult::env_failure(format!("Failed to read {}: {}", path, e)),
        }
    }

    fn handle_write(&self, action: &Action) -> WorkResult {
        let path = action.params.target.as_deref().unwrap_or("");
        let content = action
            .params
            .args
            .get("content")
            .map(|s| s.as_str())
            .unwrap_or("");

        let full_path = self.resolve_path(path);

        // 親ディレクトリを作成
        if let Some(parent) = full_path.parent() {
            if !parent.exists() {
                if let Err(e) = fs::create_dir_all(parent) {
                    return WorkResult::env_failure(format!("Failed to create directory: {}", e));
                }
            }
        }

        match fs::write(&full_path, content) {
            Ok(()) => WorkResult::env_success(format!("Written to {}", path)),
            Err(e) => WorkResult::env_failure(format!("Failed to write {}: {}", path, e)),
        }
    }

    fn handle_grep(&self, action: &Action) -> WorkResult {
        // args["pattern"] または target からパターンを取得
        // target がファイルパスっぽくない場合はパターンとして扱う(後方互換性)
        let target_str = action.params.target.as_deref().unwrap_or("");
        let (pattern, search_path) = if let Some(p) = action.params.args.get("pattern") {
            let path = if target_str.is_empty() {
                "."
            } else {
                target_str
            };
            (p.as_str(), path)
        } else if !target_str.is_empty()
            && !target_str.contains('/')
            && !target_str.contains('\\')
            && !target_str.ends_with(".rs")
            && !target_str.ends_with(".txt")
            && !target_str.ends_with(".toml")
        {
            // target がパターンの場合(例: "fn main")
            // カレントディレクトリの全 .rs ファイルを検索
            (target_str, ".")
        } else {
            ("", target_str)
        };

        let full_path = self.resolve_path(search_path);

        // ディレクトリの場合は再帰検索
        if full_path.is_dir() {
            return self.grep_directory(&full_path, pattern);
        }

        let file = match fs::File::open(&full_path) {
            Ok(f) => f,
            Err(e) => {
                return WorkResult::env_failure(format!("Failed to open {}: {}", search_path, e))
            }
        };

        let reader = BufReader::new(file);
        let mut matches = Vec::new();

        for (line_num, line) in reader.lines().enumerate() {
            if let Ok(line) = line {
                if line.contains(pattern) {
                    matches.push(format!("{}:{}:{}", search_path, line_num + 1, line));
                }
            }
        }

        WorkResult::env_success_with_data(
            format!("Found {} matches", matches.len()),
            matches.join("\n"),
        )
    }

    /// ディレクトリを再帰的に grep
    fn grep_directory(&self, dir: &Path, pattern: &str) -> WorkResult {
        let mut matches = Vec::new();

        fn search_dir(dir: &Path, pattern: &str, matches: &mut Vec<String>) {
            if let Ok(entries) = fs::read_dir(dir) {
                for entry in entries.filter_map(|e| e.ok()) {
                    let path = entry.path();
                    if path.is_dir() {
                        // .git 等を除外
                        if let Some(name) = path.file_name() {
                            let name = name.to_string_lossy();
                            if !name.starts_with('.') && name != "target" && name != "node_modules"
                            {
                                search_dir(&path, pattern, matches);
                            }
                        }
                    } else if path.extension().map(|e| e == "rs").unwrap_or(false) {
                        if let Ok(content) = fs::read_to_string(&path) {
                            for (line_num, line) in content.lines().enumerate() {
                                if line.contains(pattern) {
                                    matches.push(format!(
                                        "{}:{}:{}",
                                        path.display(),
                                        line_num + 1,
                                        line
                                    ));
                                }
                            }
                        }
                    }
                }
            }
        }

        search_dir(dir, pattern, &mut matches);

        WorkResult::env_success_with_data(
            format!("Found {} matches", matches.len()),
            matches.join("\n"),
        )
    }

    fn handle_glob(&self, action: &Action) -> WorkResult {
        // args["pattern"] または target からパターンを取得
        // target が "*" を含む場合はパターンとして扱う(後方互換性)
        let target_str = action.params.target.as_deref().unwrap_or(".");
        let (pattern, search_dir) = if let Some(p) = action.params.args.get("pattern") {
            (p.as_str(), target_str)
        } else if target_str.contains('*') {
            // target がパターンの場合(例: "**/*.rs")
            (target_str, ".")
        } else {
            ("*", target_str)
        };
        let full_path = self.resolve_path(search_dir);

        // ** を含む場合は再帰検索
        if pattern.contains("**") {
            return self.glob_recursive(&full_path, pattern);
        }

        match fs::read_dir(&full_path) {
            Ok(entries) => {
                let files: Vec<String> = entries
                    .filter_map(|e| e.ok())
                    .filter(|e| {
                        if pattern == "*" {
                            return true;
                        }
                        if let Some(ext) = pattern.strip_prefix("*.") {
                            return e.path().extension().map(|x| x == ext).unwrap_or(false);
                        }
                        e.file_name().to_string_lossy().contains(pattern)
                    })
                    .map(|e| e.path().display().to_string())
                    .collect();

                WorkResult::env_success_with_data(
                    format!("Found {} files", files.len()),
                    files.join("\n"),
                )
            }
            Err(e) => WorkResult::env_failure(format!("Failed to read directory: {}", e)),
        }
    }

    /// 再帰的な glob 検索
    fn glob_recursive(&self, dir: &Path, pattern: &str) -> WorkResult {
        let mut files = Vec::new();

        // パターンから拡張子を抽出(例: **/*.rs -> rs)
        let ext = if pattern.contains("*.") {
            pattern.rsplit("*.").next()
        } else {
            None
        };

        fn collect_files(dir: &Path, ext: Option<&str>, files: &mut Vec<String>) {
            if let Ok(entries) = fs::read_dir(dir) {
                for entry in entries.filter_map(|e| e.ok()) {
                    let path = entry.path();
                    if path.is_dir() {
                        // 隠しディレクトリと特定のディレクトリを除外
                        if let Some(name) = path.file_name() {
                            let name = name.to_string_lossy();
                            if !name.starts_with('.') && name != "target" && name != "node_modules"
                            {
                                collect_files(&path, ext, files);
                            }
                        }
                    } else if let Some(ext) = ext {
                        if path.extension().map(|e| e == ext).unwrap_or(false) {
                            files.push(path.display().to_string());
                        }
                    } else {
                        files.push(path.display().to_string());
                    }
                }
            }
        }

        collect_files(dir, ext, &mut files);

        WorkResult::env_success_with_data(format!("Found {} files", files.len()), files.join("\n"))
    }

    fn handle_answer(&self, action: &Action) -> WorkResult {
        let answer = action.params.target.as_deref().unwrap_or("");
        WorkResult::done_success(format!("Answer: {}", answer))
    }

    fn handle_continue(&self, _action: &Action) -> WorkResult {
        WorkResult::env_success("Continuing...")
    }

    // ------------------------------------------------------------------------
    // Helpers
    // ------------------------------------------------------------------------

    fn resolve_path(&self, path: &str) -> PathBuf {
        let p = Path::new(path);
        if p.is_absolute() {
            p.to_path_buf()
        } else {
            self.working_dir.join(p)
        }
    }
}

impl Default for DefaultEnvironment {
    fn default() -> Self {
        Self::new()
    }
}

impl Environment for DefaultEnvironment {
    fn step(&self, _worker_id: WorkerId, action: &Action) -> WorkResult {
        match action.name.as_str() {
            "Bash" => self.handle_bash(action),
            "Read" => self.handle_read(action),
            "Write" => self.handle_write(action),
            "Grep" => self.handle_grep(action),
            "Glob" => self.handle_glob(action),
            "Answer" => self.handle_answer(action),
            "Continue" => self.handle_continue(action),
            _ => WorkResult::unsupported(&action.name),
        }
    }

    fn reset(&self) {
        // 状態なし
    }

    fn name(&self) -> &str {
        "DefaultEnvironment"
    }
}