strike48-connector 0.3.9

Rust SDK for the Strike48 Connector 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
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
//! System Command Tool Connector
//!
//! This example pre-dates `ToolAdapter`; for new tool connectors see
//! `examples/calculator_tool.rs`. Kept as a reference because it builds the
//! registration `metadata["tool_schemas"]` payload directly.
//!
//! A TOOL connector that executes system commands on the host.
//! ⚠️ WARNING: This is for testing/development only. Running arbitrary
//! commands is a security risk in production environments.
//!
//! # Usage
//!
//! ```bash
//! TENANT_ID=non-prod STRIKE48_HOST=localhost:50061 cargo run --example system_command_tool
//! ```
//!
//! # Multi-Instance Deployment
//!
//! ```bash
//! INSTANCE_ID=cmd-1 CONNECTOR_NAME="Server 1" cargo run --example system_command_tool
//! INSTANCE_ID=cmd-2 CONNECTOR_NAME="Server 2" cargo run --example system_command_tool
//! ```
//!
//! # Tool Schema
//!
//! - `run_command`: Execute a shell command
//!   - `command`: The command to run (required)
//!   - `args`: Array of arguments (optional)
//!   - `working_dir`: Working directory (optional)
//!   - `timeout_secs`: Timeout in seconds (optional, default: 30)

use serde::Deserialize;
use std::collections::HashMap;
use std::process::Command;
use std::sync::Arc;
use strike48_connector::*;
#[cfg(unix)]
use tokio::signal::unix::{SignalKind, signal};

/// Tool schemas for registration
fn tool_schemas() -> serde_json::Value {
    serde_json::json!([
        {
            "name": "run_command",
            "description": "Execute a system command on the host. Returns stdout, stderr, and exit code.",
            "parameters": {
                "type": "object",
                "properties": {
                    "command": {
                        "type": "string",
                        "description": "The command to execute (e.g., 'ls', 'echo', 'cat')"
                    },
                    "args": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "Command arguments (e.g., ['-la', '/tmp'])"
                    },
                    "working_dir": {
                        "type": "string",
                        "description": "Working directory for the command (optional)"
                    },
                    "timeout_secs": {
                        "type": "integer",
                        "description": "Timeout in seconds (default: 30, max: 300)"
                    }
                },
                "required": ["command"]
            }
        },
        {
            "name": "get_env",
            "description": "Get the value of an environment variable",
            "parameters": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "description": "Environment variable name"
                    }
                },
                "required": ["name"]
            }
        },
        {
            "name": "list_directory",
            "description": "List contents of a directory",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Directory path to list (default: current directory)"
                    }
                },
                "required": []
            }
        },
        {
            "name": "read_file",
            "description": "Read contents of a text file (max 1MB)",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Path to the file to read"
                    },
                    "max_lines": {
                        "type": "integer",
                        "description": "Maximum number of lines to read (optional)"
                    }
                },
                "required": ["path"]
            }
        },
        {
            "name": "write_file",
            "description": "Write content to a file",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Path to the file to write"
                    },
                    "content": {
                        "type": "string",
                        "description": "Content to write to the file"
                    },
                    "append": {
                        "type": "boolean",
                        "description": "Append to file instead of overwriting (default: false)"
                    }
                },
                "required": ["path", "content"]
            }
        },
        {
            "name": "get_system_info",
            "description": "Get system information (hostname, OS, architecture, etc.)",
            "parameters": {
                "type": "object",
                "properties": {},
                "required": []
            }
        }
    ])
}

/// Request for run_command tool
#[derive(Debug, Deserialize)]
struct RunCommandRequest {
    command: String,
    #[serde(default)]
    args: Vec<String>,
    working_dir: Option<String>,
    #[allow(dead_code)]
    timeout_secs: Option<u64>,
}

/// System Command Connector
struct SystemCommandConnector;

impl SystemCommandConnector {
    fn run_command(&self, req: RunCommandRequest) -> serde_json::Value {
        // Note: timeout_secs is available but not implemented yet
        // Would need async command execution with tokio::time::timeout

        let mut cmd = Command::new(&req.command);
        cmd.args(&req.args);

        if let Some(ref dir) = req.working_dir {
            cmd.current_dir(dir);
        }

        // Execute command
        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();
                let exit_code = output.status.code().unwrap_or(-1);

                serde_json::json!({
                    "success": output.status.success(),
                    "exit_code": exit_code,
                    "stdout": stdout,
                    "stderr": stderr,
                    "command": req.command,
                    "args": req.args
                })
            }
            Err(e) => {
                serde_json::json!({
                    "success": false,
                    "error": e.to_string(),
                    "command": req.command,
                    "args": req.args
                })
            }
        }
    }

    fn get_env(&self, name: &str) -> serde_json::Value {
        match std::env::var(name) {
            Ok(value) => serde_json::json!({
                "success": true,
                "name": name,
                "value": value
            }),
            Err(_) => serde_json::json!({
                "success": false,
                "name": name,
                "error": "Environment variable not found"
            }),
        }
    }

    fn list_directory(&self, path: Option<&str>) -> serde_json::Value {
        let dir_path = path.unwrap_or(".");

        match std::fs::read_dir(dir_path) {
            Ok(entries) => {
                let items: Vec<serde_json::Value> = entries
                    .filter_map(|e| e.ok())
                    .map(|entry| {
                        let metadata = entry.metadata().ok();
                        serde_json::json!({
                            "name": entry.file_name().to_string_lossy(),
                            "is_dir": metadata.as_ref().map(|m| m.is_dir()).unwrap_or(false),
                            "is_file": metadata.as_ref().map(|m| m.is_file()).unwrap_or(false),
                            "size": metadata.as_ref().map(|m| m.len()).unwrap_or(0)
                        })
                    })
                    .collect();

                serde_json::json!({
                    "success": true,
                    "path": dir_path,
                    "entries": items,
                    "count": items.len()
                })
            }
            Err(e) => serde_json::json!({
                "success": false,
                "path": dir_path,
                "error": e.to_string()
            }),
        }
    }

    fn read_file(&self, path: &str, max_lines: Option<usize>) -> serde_json::Value {
        // Limit file size to 1MB
        const MAX_SIZE: u64 = 1024 * 1024;

        match std::fs::metadata(path) {
            Ok(meta) if meta.len() > MAX_SIZE => {
                return serde_json::json!({
                    "success": false,
                    "path": path,
                    "error": format!("File too large: {} bytes (max: {})", meta.len(), MAX_SIZE)
                });
            }
            Err(e) => {
                return serde_json::json!({
                    "success": false,
                    "path": path,
                    "error": e.to_string()
                });
            }
            _ => {}
        }

        match std::fs::read_to_string(path) {
            Ok(content) => {
                let final_content = if let Some(max) = max_lines {
                    content.lines().take(max).collect::<Vec<_>>().join("\n")
                } else {
                    content
                };

                serde_json::json!({
                    "success": true,
                    "path": path,
                    "content": final_content,
                    "lines": final_content.lines().count()
                })
            }
            Err(e) => serde_json::json!({
                "success": false,
                "path": path,
                "error": e.to_string()
            }),
        }
    }

    fn write_file(&self, path: &str, content: &str, append: bool) -> serde_json::Value {
        use std::io::Write;

        let result = if append {
            std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)
                .and_then(|mut f| f.write_all(content.as_bytes()))
        } else {
            std::fs::write(path, content)
        };

        match result {
            Ok(_) => serde_json::json!({
                "success": true,
                "path": path,
                "bytes_written": content.len(),
                "append": append
            }),
            Err(e) => serde_json::json!({
                "success": false,
                "path": path,
                "error": e.to_string()
            }),
        }
    }

    fn get_system_info(&self) -> serde_json::Value {
        serde_json::json!({
            "success": true,
            "hostname": hostname::get().ok().map(|h| h.to_string_lossy().to_string()),
            "os": std::env::consts::OS,
            "arch": std::env::consts::ARCH,
            "family": std::env::consts::FAMILY,
            "current_dir": std::env::current_dir().ok().map(|p| p.display().to_string()),
            "temp_dir": std::env::temp_dir().display().to_string(),
            "num_cpus": std::thread::available_parallelism().ok().map(|n| n.get())
        })
    }
}

impl BaseConnector for SystemCommandConnector {
    fn connector_type(&self) -> &str {
        "system-command-tool"
    }

    fn version(&self) -> &str {
        "1.0.0"
    }

    fn behavior(&self) -> ConnectorBehavior {
        ConnectorBehavior::Tool
    }

    fn metadata(&self) -> std::collections::HashMap<String, String> {
        let mut meta = HashMap::new();
        meta.insert("name".to_string(), "System Command Tool".to_string());
        meta.insert(
            "description".to_string(),
            "Execute system commands on the host".to_string(),
        );
        meta.insert("vendor".to_string(), "Strike48".to_string());
        meta.insert("icon".to_string(), "hero-command-line".to_string());
        meta.insert(
            "warning".to_string(),
            "Executes arbitrary commands - use in sandboxed environments only".to_string(),
        );

        // Tool schemas - REQUIRED for TOOL behavior
        meta.insert(
            "tool_schemas".to_string(),
            serde_json::to_string(&tool_schemas()).unwrap_or_default(),
        );
        meta.insert("tool_count".to_string(), "6".to_string());

        meta
    }

    fn execute(
        &self,
        request: serde_json::Value,
        _capability_id: Option<&str>,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<serde_json::Value>> + Send + '_>>
    {
        Box::pin(async move {
            // Extract tool name and parameters
            let tool = request
                .get("tool")
                .and_then(|v| v.as_str())
                .unwrap_or_default();

            let params = request
                .get("parameters")
                .or_else(|| request.get("args"))
                .cloned()
                .unwrap_or(serde_json::json!({}));

            let result = match tool {
                "run_command" => {
                    let req: RunCommandRequest = serde_json::from_value(params).map_err(|e| {
                        ConnectorError::InvalidConfig(format!("Invalid parameters: {e}"))
                    })?;
                    self.run_command(req)
                }

                "get_env" => {
                    let name = params.get("name").and_then(|v| v.as_str()).ok_or_else(|| {
                        ConnectorError::InvalidConfig("Missing 'name' parameter".to_string())
                    })?;
                    self.get_env(name)
                }

                "list_directory" => {
                    let path = params.get("path").and_then(|v| v.as_str());
                    self.list_directory(path)
                }

                "read_file" => {
                    let path = params.get("path").and_then(|v| v.as_str()).ok_or_else(|| {
                        ConnectorError::InvalidConfig("Missing 'path' parameter".to_string())
                    })?;
                    let max_lines = params
                        .get("max_lines")
                        .and_then(|v| v.as_u64())
                        .map(|n| n as usize);
                    self.read_file(path, max_lines)
                }

                "write_file" => {
                    let path = params.get("path").and_then(|v| v.as_str()).ok_or_else(|| {
                        ConnectorError::InvalidConfig("Missing 'path' parameter".to_string())
                    })?;
                    let content =
                        params
                            .get("content")
                            .and_then(|v| v.as_str())
                            .ok_or_else(|| {
                                ConnectorError::InvalidConfig(
                                    "Missing 'content' parameter".to_string(),
                                )
                            })?;
                    let append = params
                        .get("append")
                        .and_then(|v| v.as_bool())
                        .unwrap_or(false);
                    self.write_file(path, content, append)
                }

                "get_system_info" => self.get_system_info(),

                "" => {
                    return Err(ConnectorError::InvalidConfig(
                        "Missing 'tool' field in request".to_string(),
                    ));
                }

                _ => {
                    return Err(ConnectorError::InvalidConfig(format!(
                        "Unknown tool: {tool}"
                    )));
                }
            };

            Ok(serde_json::json!({
                "tool": tool,
                "result": result,
                "timestamp": chrono::Utc::now().to_rfc3339()
            }))
        })
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize logger
    init_logger();

    println!("=== System Command Tool ===");
    println!("⚠️  WARNING: This connector executes arbitrary system commands.");
    println!("⚠️  Only use in sandboxed/development environments!");
    println!();

    // Create connector configuration from environment
    // Uses from_env() to auto-detect transport from STRIKE48_HOST URL scheme (ws://, wss://, grpc://, grpcs://)
    let instance_id = std::env::var("INSTANCE_ID").unwrap_or_else(|_| {
        format!(
            "system-cmd-{}",
            chrono::Utc::now().timestamp_millis() % 10000
        )
    });

    // Build config - CONNECTOR_NAME sets display name for multi-instance routing
    let config = ConnectorConfig {
        connector_type: "system-command-tool".to_string(),
        instance_id: instance_id.clone(),
        version: "1.0.0".to_string(),
        max_concurrent_requests: 100,
        display_name: std::env::var("CONNECTOR_NAME").ok(),
        ..ConnectorConfig::from_env()
    };

    println!("Configuration:");
    println!("  Host: {}", config.host);
    println!("  Tenant ID: {}", config.tenant_id);
    println!("  Instance ID: {}", config.instance_id);
    if let Some(name) = &config.display_name {
        println!("  Display Name: {name}");
    }
    println!();
    println!("Available Tools:");
    println!("  - run_command: Execute a shell command");
    println!("  - get_env: Get environment variable value");
    println!("  - list_directory: List directory contents");
    println!("  - read_file: Read file contents (max 1MB)");
    println!("  - write_file: Write content to a file");
    println!("  - get_system_info: Get system information");
    println!();

    let connector = Arc::new(SystemCommandConnector);
    let runner = ConnectorRunner::new(config, connector);

    // Get shutdown handle BEFORE running - this avoids deadlock
    let shutdown_handle = runner.shutdown_handle();

    // Handle shutdown signals
    #[cfg(unix)]
    {
        let handle = shutdown_handle.clone();
        tokio::spawn(async move {
            let mut sigterm =
                signal(SignalKind::terminate()).expect("Failed to register SIGTERM handler");
            let mut sigint =
                signal(SignalKind::interrupt()).expect("Failed to register SIGINT handler");

            tokio::select! {
                _ = sigterm.recv() => {
                    println!("\nReceived SIGTERM, shutting down...");
                }
                _ = sigint.recv() => {
                    println!("\nReceived SIGINT, shutting down...");
                }
            }

            handle.shutdown();
        });
    }

    #[cfg(not(unix))]
    {
        let handle = shutdown_handle.clone();
        tokio::spawn(async move {
            tokio::signal::ctrl_c()
                .await
                .expect("Failed to register Ctrl+C handler");
            println!("\nReceived Ctrl+C, shutting down...");
            handle.shutdown();
        });
    }

    // Run the connector
    println!("Starting connector...");
    if let Err(e) = runner.run().await {
        eprintln!("Connector error: {e}");
        std::process::exit(1);
    }

    Ok(())
}