use crate::sdk::Fastshell;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, OnceLock};
static SDK_INSTANCE: OnceLock<Mutex<Fastshell>> = OnceLock::new();
fn sdk_handles() -> Option<(
Arc<Mutex<crate::bridge::Runtime>>,
Arc<AtomicBool>,
Arc<std::sync::atomic::AtomicU64>,
u64,
)> {
let sdk = get_sdk();
let guard = sdk.lock().unwrap_or_else(|e| e.into_inner());
if !guard.is_initialized() {
return None;
}
Some((
guard.runtime_ref(),
guard.cancel_handle(),
guard.deadline_handle(),
guard.command_timeout_ms(),
))
}
pub fn try_get_sdk_instance() -> Option<&'static Mutex<Fastshell>> {
SDK_INSTANCE.get()
}
fn get_sdk() -> &'static Mutex<Fastshell> {
SDK_INSTANCE.get_or_init(|| Mutex::new(Fastshell::new()))
}
#[cfg_attr(
not(all(target_os = "android", feature = "jni_direct")),
allow(dead_code)
)]
pub(crate) fn get_sdk_internal() -> &'static Mutex<Fastshell> {
SDK_INSTANCE.get_or_init(|| Mutex::new(Fastshell::new()))
}
fn result_to_json(result: &crate::sdk::types::CommandResult) -> String {
serde_json::json!({
"stdout": result.stdout,
"stderr": result.stderr,
"exit_code": result.exit_code,
})
.to_string()
}
fn error_to_json(msg: &str, code: i32) -> String {
serde_json::json!({
"stdout": "",
"stderr": msg,
"exit_code": code,
})
.to_string()
}
#[no_mangle]
#[allow(clippy::not_unsafe_ptr_arg_deref)]
pub extern "C" fn fastshell_free_string(ptr: *mut std::os::raw::c_char) {
if ptr.is_null() {
return;
}
unsafe {
let _ = std::ffi::CString::from_raw(ptr);
}
}
#[cfg(all(target_os = "android", feature = "jni_direct"))]
pub mod android {
use super::*;
use jni::objects::{JClass, JObject, JString};
use jni::sys::jstring;
use jni::JNIEnv;
use std::sync::OnceLock;
#[no_mangle]
pub extern "system" fn Java_com_fastshell_Sdk_nativeInit<'local>(
mut env: JNIEnv<'local>,
_class: JClass<'local>,
sandbox_path: JString<'local>,
) -> jstring {
let sandbox_path: String = match env.get_string(&sandbox_path) {
Ok(s) => s.into(),
Err(_) => {
let json = error_to_json("Invalid path argument", 1);
return env.new_string(json).unwrap().into_raw();
}
};
let mut sdk = get_sdk().lock().unwrap_or_else(|e| e.into_inner());
let config = crate::sdk::types::Config {
sandbox_path: sandbox_path.clone(),
python_enabled: true,
python_home: format!("{}/python", sandbox_path),
allow_subprocess: false,
network_ask_permission: false,
command_timeout_ms: 300_000,
..crate::sdk::types::Config::default()
};
let json = match sdk.init(config) {
Ok(()) => error_to_json("", 0),
Err(e) => error_to_json(&e, 1),
};
env.new_string(json).unwrap().into_raw()
}
#[no_mangle]
pub extern "system" fn Java_com_fastshell_Sdk_nativeExecute<'local>(
mut env: JNIEnv<'local>,
_class: JClass<'local>,
command: JString<'local>,
) -> jstring {
let command: String = match env.get_string(&command) {
Ok(s) => s.into(),
Err(_) => {
let json = error_to_json("Invalid command argument", 1);
return env.new_string(json).unwrap().into_raw();
}
};
let result = match sdk_handles() {
Some((rt, cancel, deadline, timeout)) => {
crate::sdk::execute_with_runtime(rt, cancel, deadline, timeout, &command)
}
None => crate::sdk::types::CommandResult::error(
"SDK not initialized. Call init() first.".to_string(),
),
};
let json = result_to_json(&result);
env.new_string(json).unwrap().into_raw()
}
#[no_mangle]
pub extern "system" fn Java_com_fastshell_Sdk_nativeGetCwd<'local>(
env: JNIEnv<'local>,
_class: JClass<'local>,
) -> jstring {
let cwd = match sdk_handles() {
Some((rt, _, _, _)) => crate::sdk::get_cwd_with_runtime(rt),
None => "/".to_string(),
};
env.new_string(cwd).unwrap().into_raw()
}
#[no_mangle]
pub extern "system" fn Java_com_fastshell_Sdk_nativeSetPermission<'local>(
mut env: JNIEnv<'local>,
_class: JClass<'local>,
resource: JString<'local>,
allowed: jni::sys::jboolean,
) {
let resource: String = match env.get_string(&resource) {
Ok(s) => s.into(),
Err(_) => return,
};
let sdk = get_sdk().lock().unwrap_or_else(|e| e.into_inner());
sdk.set_permission(&resource, allowed != 0);
}
#[no_mangle]
pub extern "system" fn Java_com_fastshell_Sdk_nativeCancelExecution<'local>(
_env: JNIEnv<'local>,
_class: JClass<'local>,
) {
let sdk = get_sdk().lock().unwrap_or_else(|e| e.into_inner());
sdk.cancel_execution();
}
#[no_mangle]
pub extern "system" fn Java_com_fastshell_Sdk_nativeRegisterStreamCallback<'local>(
env: JNIEnv<'local>,
_class: JClass<'local>,
callback: JObject<'local>,
) {
if callback.is_null() {
crate::python::clear_stream_callback();
return;
}
let vm = match env.get_java_vm() {
Ok(vm) => vm,
Err(_) => return,
};
let global_ref = match env.new_global_ref(callback) {
Ok(r) => r,
Err(_) => return,
};
static VM: OnceLock<jni::JavaVM> = OnceLock::new();
static CB: OnceLock<jni::objects::GlobalRef> = OnceLock::new();
if VM.set(vm).is_err() || CB.set(global_ref).is_err() {
return;
}
crate::python::register_stream_callback(Box::new(move |chunk: &str| {
let vm = match VM.get() {
Some(v) => v,
None => return,
};
let global_ref = match CB.get() {
Some(r) => r,
None => return,
};
let mut env = match vm.attach_current_thread() {
Ok(e) => e,
Err(_) => return,
};
let jstr = match env.new_string(chunk) {
Ok(s) => s,
Err(_) => return,
};
let _ = env.call_method(
&global_ref,
"onChunk",
"(Ljava/lang/String;)V",
&[jni::objects::JValue::Object(&jstr)],
);
}));
}
#[no_mangle]
pub extern "system" fn Java_com_fastshell_Sdk_nativeExecutePython<'local>(
mut env: JNIEnv<'local>,
_class: JClass<'local>,
code: JString<'local>,
) -> jstring {
let code: String = match env.get_string(&code) {
Ok(s) => s.into(),
Err(_) => {
let json = error_to_json("Invalid code argument", 1);
return env.new_string(json).unwrap().into_raw();
}
};
let result = match sdk_handles() {
Some((rt, _, _, _)) => crate::sdk::execute_python_with_runtime(rt, &code),
None => crate::sdk::types::CommandResult::error(
"SDK not initialized. Call init() first.".to_string(),
),
};
let json = result_to_json(&result);
env.new_string(json).unwrap().into_raw()
}
#[no_mangle]
pub extern "system" fn Java_com_fastshell_Sdk_nativeExecutePythonScript<'local>(
mut env: JNIEnv<'local>,
_class: JClass<'local>,
script_path: JString<'local>,
) -> jstring {
let script_path: String = match env.get_string(&script_path) {
Ok(s) => s.into(),
Err(_) => {
let json = error_to_json("Invalid script path", 1);
return env.new_string(json).unwrap().into_raw();
}
};
let result = match sdk_handles() {
Some((rt, _, _, _)) => crate::sdk::execute_python_script_with_runtime(rt, &script_path),
None => crate::sdk::types::CommandResult::error(
"SDK not initialized. Call init() first.".to_string(),
),
};
let json = result_to_json(&result);
env.new_string(json).unwrap().into_raw()
}
}
#[cfg(target_os = "ios")]
pub mod ios {
use super::*;
use std::os::raw::c_char;
fn to_c(s: String) -> *const c_char {
match std::ffi::CString::new(s) {
Ok(cs) => cs.into_raw(),
Err(_) => std::ffi::CString::new(
r#"{"stdout":"","stderr":"output contained NUL","exit_code":1}"#,
)
.expect("static JSON has no NUL")
.into_raw(),
}
}
fn guard(f: impl FnOnce() -> String) -> *const c_char {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
Ok(s) => to_c(s),
Err(_) => to_c(error_to_json("fastshell: internal panic", 1)),
}
}
#[no_mangle]
pub extern "C" fn fastshell_ios_init(
sandbox_path: *const std::os::raw::c_char,
) -> *const c_char {
guard(|| {
if sandbox_path.is_null() {
return error_to_json("null sandbox_path", 1);
}
let sandbox_path = unsafe {
std::ffi::CStr::from_ptr(sandbox_path)
.to_string_lossy()
.to_string()
};
let mut sdk = get_sdk().lock().unwrap_or_else(|e| e.into_inner());
let config = crate::sdk::types::Config {
sandbox_path: sandbox_path.clone(),
python_enabled: true,
python_home: format!("{}/python", sandbox_path),
allow_subprocess: false,
network_ask_permission: false,
command_timeout_ms: 300_000,
..crate::sdk::types::Config::default()
};
match sdk.init(config) {
Ok(()) => error_to_json("", 0),
Err(e) => error_to_json(&e, 1),
}
})
}
#[no_mangle]
pub extern "C" fn fastshell_ios_execute(command: *const std::os::raw::c_char) -> *const c_char {
guard(|| {
if command.is_null() {
return error_to_json("null command", 1);
}
let command = unsafe {
std::ffi::CStr::from_ptr(command)
.to_string_lossy()
.to_string()
};
let result = match sdk_handles() {
Some((rt, cancel, deadline, timeout)) => {
crate::sdk::execute_with_runtime(rt, cancel, deadline, timeout, &command)
}
None => crate::sdk::types::CommandResult::error(
"SDK not initialized. Call init() first.".to_string(),
),
};
result_to_json(&result)
})
}
#[no_mangle]
pub extern "C" fn fastshell_ios_set_permission(
resource: *const std::os::raw::c_char,
allowed: u8,
) {
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if resource.is_null() {
return;
}
let resource = unsafe {
std::ffi::CStr::from_ptr(resource)
.to_string_lossy()
.to_string()
};
let sdk = get_sdk().lock().unwrap_or_else(|e| e.into_inner());
sdk.set_permission(&resource, allowed != 0);
}));
}
#[no_mangle]
pub extern "C" fn fastshell_ios_cancel_execution() {
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let sdk = get_sdk().lock().unwrap_or_else(|e| e.into_inner());
sdk.cancel_execution();
}));
}
}
pub mod capi {
use super::*;
use std::os::raw::c_char;
fn cstr_to_string(ptr: *const c_char) -> Option<String> {
if ptr.is_null() {
return None;
}
Some(
unsafe { std::ffi::CStr::from_ptr(ptr) }
.to_string_lossy()
.to_string(),
)
}
fn into_c_string(s: String) -> *mut c_char {
match std::ffi::CString::new(s.clone()) {
Ok(cs) => cs.into_raw(),
Err(e) => {
let pos = e.nul_position();
let truncated = &s[..pos];
let json = serde_json::json!({
"stdout": truncated,
"stderr": format!("[fastshell: output truncated at byte {} due to NUL character]", pos),
"exit_code": 0,
"nul_truncated": true,
})
.to_string();
std::ffi::CString::new(json).unwrap().into_raw()
}
}
}
fn guard(f: impl FnOnce() -> String) -> *mut c_char {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
Ok(s) => into_c_string(s),
Err(_) => into_c_string(error_to_json("fastshell: internal panic", 1)),
}
}
#[no_mangle]
pub extern "C" fn fastshell_init(sandbox_path: *const c_char) -> *mut c_char {
guard(|| {
let sandbox_path = match cstr_to_string(sandbox_path) {
Some(s) => s,
None => return error_to_json("Invalid path argument", 1),
};
let mut sdk = get_sdk().lock().unwrap_or_else(|e| e.into_inner());
let config = crate::sdk::types::Config {
sandbox_path: sandbox_path.clone(),
python_enabled: std::env::var("FASTSHELL_DISABLE_PYTHON").is_err(),
python_home: format!("{}/python", sandbox_path),
allow_subprocess: false,
command_timeout_ms: 300_000,
..crate::sdk::types::Config::default()
};
match sdk.init(config) {
Ok(()) => error_to_json("", 0),
Err(e) => error_to_json(&e, 1),
}
})
}
fn install_global_device_plugin() {
let plugin = crate::sdk::device_callback::global_device_plugin();
let sdk = get_sdk().lock().unwrap_or_else(|e| e.into_inner());
match plugin {
Some(p) => sdk.register_plugin(p),
None => {
if let Ok(mut p) = sdk.plugin_ref.lock() {
*p = None;
}
}
}
}
#[no_mangle]
pub extern "C" fn fastshell_register_device_callback(
cb: Option<crate::sdk::device_callback::DeviceCallbackFn>,
) {
crate::sdk::device_callback::set_global_device_callback(cb);
install_global_device_plugin();
}
#[no_mangle]
pub extern "C" fn fastshell_register_device_callback_async(
cb: Option<crate::sdk::device_callback::DeviceCallbackAsyncFn>,
) {
crate::sdk::device_callback::set_global_device_callback_async(cb);
install_global_device_plugin();
}
#[no_mangle]
pub extern "C" fn fastshell_device_response(request_id: u64, json: *const c_char) {
crate::sdk::device_callback::host_send_result(request_id, json);
}
#[no_mangle]
pub extern "C" fn fastshell_execute(command: *const c_char) -> *mut c_char {
guard(|| {
let command = match cstr_to_string(command) {
Some(s) => s,
None => return error_to_json("Invalid command argument", 1),
};
match sdk_handles() {
Some((rt, cancel, deadline, timeout)) => result_to_json(
&crate::sdk::execute_with_runtime(rt, cancel, deadline, timeout, &command),
),
None => error_to_json("SDK not initialized. Call init() first.", 1),
}
})
}
#[no_mangle]
pub extern "C" fn fastshell_execute_python(code: *const c_char) -> *mut c_char {
guard(|| {
let code = match cstr_to_string(code) {
Some(s) => s,
None => return error_to_json("Invalid code argument", 1),
};
match sdk_handles() {
Some((rt, _, _, _)) => {
result_to_json(&crate::sdk::execute_python_with_runtime(rt, &code))
}
None => error_to_json("SDK not initialized. Call init() first.", 1),
}
})
}
#[no_mangle]
pub extern "C" fn fastshell_execute_python_script(script_path: *const c_char) -> *mut c_char {
guard(|| {
let script_path = match cstr_to_string(script_path) {
Some(s) => s,
None => return error_to_json("Invalid script path", 1),
};
match sdk_handles() {
Some((rt, _, _, _)) => result_to_json(
&crate::sdk::execute_python_script_with_runtime(rt, &script_path),
),
None => error_to_json("SDK not initialized. Call init() first.", 1),
}
})
}
#[no_mangle]
pub extern "C" fn fastshell_get_cwd() -> *mut c_char {
guard(|| match sdk_handles() {
Some((rt, _, _, _)) => crate::sdk::get_cwd_with_runtime(rt),
None => "/".to_string(),
})
}
#[no_mangle]
pub extern "C" fn fastshell_set_permission(resource: *const c_char, allowed: u8) {
let resource = match cstr_to_string(resource) {
Some(s) => s,
None => return,
};
let sdk = get_sdk().lock().unwrap_or_else(|e| e.into_inner());
sdk.set_permission(&resource, allowed != 0);
}
#[no_mangle]
pub extern "C" fn fastshell_cancel_execution() {
let sdk = get_sdk().lock().unwrap_or_else(|e| e.into_inner());
sdk.cancel_execution();
}
#[no_mangle]
pub extern "C" fn fastshell_execute_in(
dir: *const c_char,
command: *const c_char,
) -> *mut c_char {
guard(|| {
let dir = match cstr_to_string(dir) {
Some(s) => s,
None => return error_to_json("Invalid dir argument", 1),
};
let command = match cstr_to_string(command) {
Some(s) => s,
None => return error_to_json("Invalid command argument", 1),
};
match sdk_handles() {
Some((rt, cancel, deadline, timeout)) => {
result_to_json(&crate::sdk::execute_in_with_runtime(
rt, cancel, deadline, timeout, &dir, &command,
))
}
None => error_to_json("SDK not initialized. Call init() first.", 1),
}
})
}
#[no_mangle]
pub extern "C" fn fastshell_start_agent_server() -> *mut c_char {
let sdk = get_sdk().lock().unwrap_or_else(|e| e.into_inner());
match sdk.start_agent_server() {
Ok(()) => into_c_string(r#"{"ok":true}"#.to_string()),
Err(e) => into_c_string(serde_json::json!({"ok": false, "error": e}).to_string()),
}
}
#[no_mangle]
pub extern "C" fn fastshell_submit_task(
task_id: *const c_char,
task_json: *const c_char,
) -> *mut c_char {
let task_id = match cstr_to_string(task_id) {
Some(s) => s,
None => return into_c_string(error_to_json("Invalid task_id", 1)),
};
let task_json = match cstr_to_string(task_json) {
Some(s) => s,
None => return into_c_string(error_to_json("Invalid task_json", 1)),
};
let sdk = get_sdk().lock().unwrap_or_else(|e| e.into_inner());
match sdk.submit_task(&task_id, &task_json) {
Ok(()) => into_c_string(r#"{"ok":true}"#.to_string()),
Err(e) => into_c_string(serde_json::json!({"ok": false, "error": e}).to_string()),
}
}
pub type StreamCallback = extern "C" fn(*const c_char);
#[no_mangle]
pub extern "C" fn fastshell_register_stream_callback(cb: Option<StreamCallback>) {
match cb {
None => crate::python::clear_stream_callback(),
Some(f) => {
crate::python::register_stream_callback(Box::new(move |chunk: &str| {
if let Ok(cstr) = std::ffi::CString::new(chunk) {
f(cstr.as_ptr());
}
}));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::{CStr, CString};
fn take_json(ptr: *mut c_char) -> serde_json::Value {
assert!(!ptr.is_null(), "FFI returned null");
let s = unsafe { CStr::from_ptr(ptr) }.to_string_lossy().to_string();
fastshell_free_string(ptr);
serde_json::from_str(&s).unwrap_or_else(|_| panic!("not JSON: {s}"))
}
fn call_str(
f: extern "C" fn(*const c_char) -> *mut c_char,
arg: &str,
) -> serde_json::Value {
let c = CString::new(arg).unwrap();
take_json(f(c.as_ptr()))
}
static CB_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
extern "C" fn test_stream_cb(chunk: *const c_char) {
if !chunk.is_null() {
let _ = unsafe { CStr::from_ptr(chunk) }.to_string_lossy();
CB_HITS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
}
#[test]
fn capi_full_surface() {
let dir = std::env::temp_dir().join(format!("fastshell_capi_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let init = call_str(fastshell_init, dir.to_str().unwrap());
assert_eq!(init["exit_code"], 0, "init failed: {init}");
let echo = call_str(fastshell_execute, "echo hello_capi");
assert_eq!(echo["exit_code"], 0);
assert!(echo["stdout"].as_str().unwrap().contains("hello_capi"));
let cwd_ptr = fastshell_get_cwd();
let cwd = unsafe { CStr::from_ptr(cwd_ptr) }
.to_string_lossy()
.to_string();
fastshell_free_string(cwd_ptr);
assert!(!cwd.is_empty());
let res = CString::new("network:capi-roundtrip.internal").unwrap();
fastshell_set_permission(res.as_ptr(), 1);
fastshell_cancel_execution();
let bad = take_json(fastshell_execute(std::ptr::null()));
assert_ne!(bad["exit_code"], 0);
fastshell_register_stream_callback(Some(test_stream_cb));
fastshell_register_stream_callback(None);
let py = call_str(fastshell_execute_python, "print(6 * 7)");
{
let rt = crate::sdk::ffi::get_sdk_internal()
.lock()
.unwrap_or_else(|e| e.into_inner())
.runtime_ref();
let rt = rt.lock().unwrap_or_else(|e| e.into_inner());
if rt.python_available() {
assert_eq!(py["exit_code"], 0);
assert!(py["stdout"].as_str().unwrap().contains("42"));
}
}
fastshell_set_permission(std::ptr::null(), 0);
}
}
#[no_mangle]
pub extern "C" fn fastshell_get_features() -> *mut c_char {
let json = serde_json::json!({
"version": env!("CARGO_PKG_VERSION"),
"shell_features": [
"functions",
"aliases",
"brace_expansion",
"arithmetic_expansion",
"parameter_substitution",
"pipefail",
"errexit",
"xtrace",
"nounset",
"heredoc_expansion",
"here_string",
"process_substitution",
"recursive_glob",
"if_else",
"source_dot",
"eval",
"read",
"export_enhanced",
"cat_enhanced",
"echo_enhanced",
"cd_history",
"backslash_fix",
"comment_skip",
"word_splitting",
"killall_fix",
"nul_output_protection",
],
"builtin_commands": 200,
"jni_utf8_fixed": true,
})
.to_string();
into_c_string(json)
}
}