fastshell 0.3.6

Lightweight Bash + Python runtime SDK for mobile AI agents
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
// Copyright (c) 2025 xiefujin <490021684@qq.com>
// Licensed under Apache-2.0, see LICENSE file for full license terms.

use crate::sdk::Fastshell;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, OnceLock};

static SDK_INSTANCE: OnceLock<Mutex<Fastshell>> = OnceLock::new();

/// Extract the runtime + cancel handles under a *short* lock.
///
/// The returned handles let the caller run a command **without** holding the
/// global `SDK_INSTANCE` mutex for its whole duration. This is what keeps a
/// long `git status`/`run_shell` from blocking `cancel_execution`,
/// `set_permission` and every other FFI call (previously all serialized behind
/// the execute lock — a hung command could not even be cancelled).
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(),
    ))
}

/// Returns a reference to the shared SDK instance if it has already been
/// initialized (e.g. by the host app via fastshell_init()). Returns None
/// if no SDK instance has been created yet.
///
/// This is the integration point for aacode-rs on mobile: the agent reuses
/// the App's fastshell instead of creating a second instance (which would
/// conflict on CPython initialization and VFS root paths).
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()))
}

// Used by the Android jni_direct module below; dead on other targets.
#[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]
// Standard C-ABI free contract: the pointer must come from a fastshell_*
// function (documented for hosts); marking it `unsafe` would not change the
// C caller's obligations.
#[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();
            }
        };

        // Run WITHOUT holding the global SDK lock (see `sdk_handles`).
        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;

    /// NUL-safe conversion of a result JSON into a C string. `CString::new`
    /// fails on an embedded NUL; a panic there would abort the whole app
    /// (Rust 1.81+ `extern "C"` unwind = abort).
    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(),
        }
    }

    /// Run an FFI body, converting a panic into an error JSON instead of
    /// letting it unwind across `extern "C"` (which aborts the process).
    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()
            };

            // Run WITHOUT holding the global SDK lock (see `sdk_handles`), so a
            // long command can never block cancel/permission/other FFI calls.
            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();
        }));
    }
}

// ═══════════════════════════════════════════════════════════
// Pure C ABI — compiled on ALL platforms.
//
// This is the entry point used by the NDK CMake bridge (fastshell_c,
// 方案 B): `libfastshell.a` exposes these `extern "C"` symbols, and a
// C JNI glue layer (jni_glue.c) forwards Java_* JNI calls to them. It
// is also usable by desktop/iOS C hosts.
//
// All functions returning `*mut c_char` allocate a NUL-terminated
// UTF-8 string that MUST be released with `fastshell_free_string`.
// ═══════════════════════════════════════════════════════════
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()
            }
        }
    }

    /// Run an FFI body, converting a panic into an error JSON instead of
    /// letting it unwind across `extern "C"` (which aborts the process).
    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),
            }
        })
    }

    /// Rebuild the global SDK instance's device plugin from the registered
    /// callbacks (async preferred). Shared by both sync/async registration.
    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;
                }
            }
        }
    }

    /// Registers (or clears with NULL) the host device-capability callback.
    /// The callback receives `(method, args_json)` and returns a malloc'd
    /// JSON string; fastshell frees it with `free()`. Call AFTER
    /// `fastshell_init` — the shell's device commands (`camera`, `record`,
    /// `location`, `sensor`, …) become functional once registered.
    #[no_mangle]
    pub extern "C" fn fastshell_register_device_callback(
        cb: Option<crate::sdk::device_callback::DeviceCallbackFn>,
    ) {
        // Store globally so per-task fastshell instances (aacode-rs) inherit it.
        crate::sdk::device_callback::set_global_device_callback(cb);
        install_global_device_plugin();
    }

    /// Registers (or clears with NULL) the **asynchronous** device callback
    /// (`fn(method, args_json, request_id)`). Preferred over the sync variant
    /// when both are set: the host returns immediately and later calls
    /// `fastshell_device_response(request_id, json)` with the result. This is
    /// the generic contract for every host (iOS / Android / desktop).
    #[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();
    }

    /// Host → fastshell result delivery for an async device request.
    /// `request_id` is the value passed to the async callback; `json` is a
    /// UTF-8 C string that this side copies (the host owns its allocation).
    #[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),
            };
            // Run WITHOUT holding the global SDK lock (see `sdk_handles`).
            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();
    }

    /// Executes `command` with `dir` as the working directory (restored
    /// afterwards). Concurrent-host safe: no `cd X && ...` prefix needed and
    /// the shared cwd is never left polluted.
    #[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),
            };
            // Run WITHOUT holding the global SDK lock (see `sdk_handles`).
            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),
            }
        })
    }

    /// Starts the agent server in a background Python thread.
    /// Returns JSON: {"ok": true} or {"ok": false, "error": "..."}
    #[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()),
        }
    }

    /// Submits a task to the running agent server.
    /// `task_id` is a short unique identifier.
    /// `task_json` is a JSON object with "task", "project_path", "session_id".
    /// Returns JSON: {"ok": true} or {"ok": false, "error": "..."}
    #[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()),
        }
    }

    /// C function pointer invoked for every stdout/stderr chunk produced
    /// by streaming Python execution. The `*const c_char` is a temporary
    /// NUL-terminated UTF-8 buffer valid only for the duration of the call;
    /// the callee must copy it if retention is needed.
    pub type StreamCallback = extern "C" fn(*const c_char);

    /// Registers (or, with a NULL pointer, clears) the stream callback.
    ///
    /// The C glue layer (jni_glue.c) passes a trampoline that forwards each
    /// chunk to the Java `onChunk(String)` method via JNI.
    #[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};

        // The C ABI drives a single process-global SDK instance, so every
        // assertion runs inside ONE serial test to avoid cross-test races.
        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);

            // init
            let init = call_str(fastshell_init, dir.to_str().unwrap());
            assert_eq!(init["exit_code"], 0, "init failed: {init}");

            // execute (shell)
            let echo = call_str(fastshell_execute, "echo hello_capi");
            assert_eq!(echo["exit_code"], 0);
            assert!(echo["stdout"].as_str().unwrap().contains("hello_capi"));

            // get_cwd
            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());

            // permission + cancel (must not panic). Unique resource name —
            // the permission table is process-global and example.com would
            // interfere with the sdk permission tests running in parallel.
            let res = CString::new("network:capi-roundtrip.internal").unwrap();
            fastshell_set_permission(res.as_ptr(), 1);
            fastshell_cancel_execution();

            // NULL-safety: passing null argument returns an error JSON, no crash
            let bad = take_json(fastshell_execute(std::ptr::null()));
            assert_ne!(bad["exit_code"], 0);

            // stream callback register / clear round-trip (no crash)
            fastshell_register_stream_callback(Some(test_stream_cb));
            fastshell_register_stream_callback(None);

            // execute_python — only assert output when a python engine exists
            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"));
                }
            }

            // set_permission with null resource must be a no-op, not a crash
            fastshell_set_permission(std::ptr::null(), 0);
        }
    }

    /// Returns a JSON object listing the shell features supported by this build.
    #[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)
    }
}