package io.github.abrarul.modularai.plugin import android.content.Context import io.github.abrarul.modularai.bridge.TermuxBridge import org.json.JSONObject import java.io.File /** * Plugin layout: filesDir/plugins//plugin.json + entry script. * plugin.json: {"id","name","version","entry":"run.sh","permissions":["net","shell"],"hooks":["on_capture","on_model_loaded"]} * A plugin only runs hooks for permissions the user has explicitly granted. */ data class Plugin( val id: String, val name: String, val version: String, val entry: String, val permissions: Set, val hooks: Set, val dir: File ) class PluginHost(private val ctx: Context) { private val root = File(ctx.filesDir, "plugins").apply { mkdirs() } private val granted = ctx.getSharedPreferences("plugin_grants", Context.MODE_PRIVATE) fun installed(): List = root.listFiles()?.mapNotNull { load(it) } ?: emptyList() private fun load(d: File): Plugin? = try { val j = JSONObject(File(d, "plugin.json").readText()) fun set(k: String) = j.optJSONArray(k)?.let { a -> (0 until a.length()).map { a.getString(it) }.toSet() } ?: emptySet() Plugin(j.getString("id"), j.getString("name"), j.getString("version"), j.getString("entry"), set("permissions"), set("hooks"), d) } catch (_: Exception) { null } fun grant(id: String, perms: Set) = granted.edit().putStringSet(id, perms).apply() fun isGranted(p: Plugin) = granted.getStringSet(p.id, emptySet())!!.containsAll(p.permissions) fun remove(p: Plugin) { p.dir.deleteRecursively(); granted.edit().remove(p.id).apply() } /** Fires [event]; payload is passed as the first script argument. */ fun emit(event: String, payload: String = "") { installed().filter { event in it.hooks && isGranted(it) }.forEach { p -> // Entry paths must stay inside the plugin dir. val entry = File(p.dir, p.entry).canonicalFile if (!entry.path.startsWith(p.dir.canonicalPath)) return@forEach if ("shell" in p.permissions) { TermuxBridge.run(ctx, "sh '${entry.path}' '$event' \"\$1\"", arrayOf("_", payload)) } } } }