Runtime API
This page is the complete public surface a plugin can use, taken from io.github.sadami3066.sora:plugin-api:2.0.2 (package io.github.sadami3066.sora.plugin.api). Every type below is declared in the SDK; plugins implement interfaces and call factory functions, and never construct host-owned models.
Import the whole package or individual declarations:
import io.github.sadami3066.sora.plugin.api.*Plugin entry point
The host loads the class named by entryClass in the manifest and requires a public no-arg constructor.
public interface SoraPlugin {
public suspend fun availability(host: PluginHost): PluginAvailability
public suspend fun uninstall(host: PluginHost): Unit = Unit
public suspend fun onEnable(host: PluginHost): Unit = Unit
public suspend fun onDisable(host: PluginHost): Unit = Unit
public suspend fun onUpgrade(host: PluginHost, fromVersion: String): Unit = Unit
public fun skills(host: PluginHost): List<PluginSkill> = emptyList()
public fun promptSections(host: PluginHost): List<PromptSection> = emptyList()
public fun contributions(host: PluginHost): Contributions = contributions()
public fun contributionsFor(host: PluginHost, session: PluginSessionInfo?): Contributions = contributions(host)
public fun ui(host: PluginHost): PluginUiContributions = PluginUiContributions.None
public suspend fun close(): Unit = Unit
}| Callback | When the host calls it | What to do |
|---|---|---|
availability(host) | On every refresh | Return available() or unavailable("reason"); unavailable puts the plugin in DEGRADED, withholds skills, and shows the reason |
onEnable / onDisable | When the user toggles the plugin, and at startup for enabled plugins | Start or stop plugin work; disabling cancels host.scope first, then calls onDisable |
onUpgrade(host, fromVersion) | While a new version is being activated, before it becomes current | Migrate persisted state; fromVersion is the version currently in use |
skills(host) | On refresh, while loaded and enabled | Return skills; the host materializes them into the agent skill directory |
promptSections(host) | On refresh | Append system-prompt sections, sorted by priority ascending |
contributions(host) | When built-in contributions are materialized | Return global tools and hooks |
contributionsFor(host, session) | Once per session binding | Return session tools and hooks; returning default hooks inherits the global hooks |
ui(host) | On refresh | Return slot bindings, pages, composer actions, and tool result renderers |
uninstall(host) | Before the user deletes the plugin | Clean up external side effects |
close() | On disable, uninstall, update, or process exit | Release resources; do not start asynchronous work |
Availability helpers:
public interface PluginAvailability {
public val available: Boolean
public val reason: String?
}
public fun available(): PluginAvailability
public fun unavailable(reason: String): PluginAvailability
public val PluginAvailability.isReady: Boolean get() = availableSession handle passed to contributionsFor:
public interface PluginSessionInfo {
public val supportsChatDelivery: Boolean
public fun snapshot(): PluginSessionSnapshot?
}
public data class PluginSessionSnapshot(sessionId: String, file: String?, cwd: String)Do not cache host, host.scope, or the session handle in plugin fields. A re-enabled plugin is loaded again and receives a new host; contributions are materialized once per refresh and once per session.
PluginHost
PluginHost is the plugin's only entry point. It exposes the manifest, directories, a scope for background work, text resolution, 36 service accessors, and a refresh trigger.
public interface PluginHost {
public val manifest: PluginManifest
public val context: Context
public val dataDir: File
public val assetsDir: File
public val scope: CoroutineScope
public fun text(source: LocalizedText, vararg args: Any): String
public fun linux(): LinuxService
public fun screen(): ScreenService
public fun notifications(): NotificationService
public fun secrets(): SecretService
public fun network(): NetworkService
public fun files(): FileService
public fun sessions(): SessionService
public fun jobs(): JobService
public fun timers(): TimerService
public fun goals(): GoalService
public fun miniapp(): MiniappService
public fun mcp(): McpService
public fun ui(): UiService
public fun images(): ImageService = throw PluginServiceUnavailable("images")
public fun app(): AppInfoService
public fun bus(): PluginBus
public fun logs(): LogService
public fun chat(): ChatService = throw PluginServiceUnavailable("chat")
public fun settings(): PluginSettingsService
public fun device(): DeviceService
public fun clipboard(): ClipboardService
public fun permissions(): PermissionService
public fun packages(): PackageService
public fun privilege(): PrivilegeService
public fun intents(): IntentsService
@PluginExperimentalApi
public fun components(): ComponentService
public fun background(): BackgroundService
public fun location(): LocationService
public fun contacts(): ContactsService
public fun sms(): SmsService
public fun calendar(): CalendarService
public fun media(): MediaService
public fun speech(): SpeechService
public fun web(): WebService
@PluginExperimentalApi
public fun credentials(): CredentialService
@PluginExperimentalApi
public fun accessibility(): AccessibilityServicePlugin
public fun requestContributionsRefresh()
}Behavior:
- A service whose capability is not declared is not injected; calling it throws
PluginServiceUnavailable(anIllegalStateExceptionwith aserviceand optionalreason). Catch it when a service is optional. - A wired but currently unusable service reports through its own fields (
available,enabled,permissionGranted,status, ...), returns null/false, or throws a documented exception. dataDiris the plugin's persistent private directory and survives upgrades;assetsDiris the read-only assets of the installed version.scopeis cancelled on disable, uninstall, update, and process exit. Put long-running work on it and handle cancellation.requestContributionsRefresh()asks the host to re-materialize tools, skills, prompts, and UI and to rebuild sessions at a safe point. It returns no handle; busy sessions update after the current round.host.text(localized, *args)resolves aLocalizedTextwith the app language and appliesString.formatplaceholders.
Host services
Signatures below are the exact public members. Data classes are shown with their constructor parameters and defaults. Wire value classes (PluginCapability, HostAccessLevel, PrivilegeLevel, MessageRole, JobStatus, GoalPhase, TimerTriggerKind, ScreenTarget is an enum, and the like) expose a wire: String property and constants or factories in their companion object; construct them from those constants.
Execution and files
public interface LinuxService {
public val available: Boolean
public suspend fun exec(command: String, cwd: String? = null, timeoutMs: Long = DEFAULT_TIMEOUT_MS): LinuxResult
public fun stream(command: String, cwd: String? = null): Flow<LinuxChunk>
public companion object { public const val DEFAULT_TIMEOUT_MS: Long = 15_000 }
}
public data class LinuxResult(
val exitCode: Int, val stdout: String, val stderr: String,
val timedOut: Boolean = false, val truncated: Boolean = false,
val fullOutputPath: String? = null,
)
public interface LinuxChunk { val kind: LinuxChunkKind; val text: String?; val exitCode: Int? }
public value class LinuxChunkKind { companion object { val STDOUT; val STDERR; val EXIT; val ALL; fun fromWire(value: String): LinuxChunkKind? } }
public interface FileService {
public val rootDir: String
public val workspaceDir: String?
public suspend fun list(path: String = ""): List<FileEntry>
public suspend fun readText(path: String): String
public suspend fun writeText(path: String, content: String, append: Boolean = false)
public suspend fun readBytes(path: String): ByteArray
public suspend fun writeBytes(path: String, bytes: ByteArray)
public suspend fun delete(path: String): Boolean
public suspend fun exists(path: String): Boolean
public suspend fun resolve(path: String): String
}
public data class FileEntry(path: String, name: String, directory: Boolean, size: Long = 0, modifiedAt: Long = 0)linux() runs inside the execution tier the user selected (normal, ADB, or root) and cannot choose it. exec records timeouts and truncation; stderr is merged into stdout, so check exitCode and the end of the output. Relative files() paths resolve against dataDir; absolute paths follow the current tier.
public interface PrivilegeService {
public val access: HostAccessLevel
public val root: RootState
public val adb: AdbState
public suspend fun probeRoot(): RootState
public suspend fun exec(command: String, level: PrivilegeLevel = PrivilegeLevel.AUTO, timeoutMs: Long = DEFAULT_TIMEOUT_MS): PrivilegeResult
public suspend fun install(apkPath: String, silent: Boolean = true): PackageInstallResult
public suspend fun uninstall(packageName: String): PackageInstallResult
public fun openAccessSettings(): Boolean
public fun openWirelessDebugging(): Boolean
public suspend fun startAdbPairing(): AdbPairingResult
public suspend fun submitAdbPairingCode(code: String): AdbPairingResult
public suspend fun connectAdb(): Boolean
public companion object { public const val DEFAULT_TIMEOUT_MS: Long = 30_000 }
}
public value class HostAccessLevel { companion object { val LOCAL; val ADB; val ROOT; val ALL; fun fromWire(value: String): HostAccessLevel? } }
public value class PrivilegeLevel { companion object { val AUTO; val ROOT; val ADB; val ALL; fun fromWire(value: String): PrivilegeLevel? } }
public data class RootState(status: String, granted: Boolean, error: String? = null)
public data class AdbState(paired: Boolean, connected: Boolean, busy: Boolean = false, host: String? = null, port: Int = 0, error: String? = null)
public data class PrivilegeResult(exitCode: Int, stdout: String, stderr: String, timedOut: Boolean = false, truncated: Boolean = false)
public data class AdbPairingResult(started: Boolean, paired: Boolean, error: String? = null)HostAccessLevel is read-only: exec never escalates above the tier the user authorized. AUTO picks the currently available tier; asking for ROOT or ADB when unavailable returns a failure.
Agent runtime
public interface SessionService {
public val active: SessionInfo?
public fun observe(): Flow<SessionInfo?>
public suspend fun list(): List<SessionInfo>
public suspend fun prompt(text: String, sessionId: String? = null): Boolean
public suspend fun history(sessionId: String, limit: Int = 50): List<PluginMessage>
public suspend fun stop(sessionId: String): Boolean
public suspend fun create(title: String? = null): SessionInfo?
public suspend fun rename(sessionId: String, title: String): Boolean
public suspend fun delete(sessionId: String): Boolean
public suspend fun open(sessionId: String): Boolean
public suspend fun archive(sessionId: String, archived: Boolean): Boolean
}
public data class SessionInfo(id: String, title: String? = null, cwd: String? = null, busy: Boolean = false)
public data class PluginMessage(id: String, role: MessageRole, text: String, timestampMs: Long, toolName: String? = null, images: List<String> = emptyList())
public value class MessageRole { companion object { val USER; val ASSISTANT; val TOOL; val SYSTEM; val ALL; fun fromWire(value: String): MessageRole? } }
public interface JobService {
public fun observe(): Flow<List<JobInfo>>
public suspend fun start(command: String, label: String, cwd: String? = null, sessionId: String? = null): String?
public suspend fun read(jobId: String): JobRead
public suspend fun kill(jobId: String): Boolean
}
public data class JobInfo(id: String, label: String, command: String, status: JobStatus, startedAt: Long, finishedAt: Long? = null, exitCode: Int? = null, outputBytes: Long = 0)
public data class JobRead(output: String, status: JobStatus, exitCode: Int? = null, dropped: Boolean = false)
public value class JobStatus { companion object { val RUNNING; val DONE; val FAILED; val KILLED; val INTERRUPTED; val ALL; fun fromWire(value: String): JobStatus? } }
public interface TimerService {
public suspend fun schedule(request: TimerRequest): TimerInfo?
public suspend fun list(): List<TimerInfo>
public suspend fun cancel(id: String): Boolean
}
public interface TimerRequest { val name: String; val prompt: String; val trigger: TimerTrigger; val sessionId: String?; val enabled: Boolean }
public fun timerRequest(name: String, prompt: String, trigger: TimerTrigger, sessionId: String? = null, enabled: Boolean = true): TimerRequest
public interface TimerTrigger { val kind: TimerTriggerKind; val epochMillis: Long?; val expression: String? }
public fun timerOnce(epochMillis: Long): TimerTrigger
public fun timerCron(expression: String): TimerTrigger
public value class TimerTriggerKind { companion object { val ONCE; val CRON; val ALL; fun fromWire(value: String): TimerTriggerKind? } }
public data class TimerInfo(id: String, name: String, prompt: String, trigger: TimerTrigger, sessionId: String? = null, enabled: Boolean = true, nextRunAt: Long? = null, lastError: String? = null)
public interface GoalService {
public fun observe(): Flow<List<GoalInfo>>
public suspend fun get(sessionId: String): GoalInfo?
public suspend fun create(sessionId: String, objective: String, maxRounds: Int? = null): GoalInfo?
public suspend fun edit(sessionId: String, objective: String): GoalInfo?
public suspend fun pause(sessionId: String): GoalInfo?
public suspend fun resume(sessionId: String): GoalInfo?
public suspend fun complete(sessionId: String): GoalInfo?
public suspend fun clear(sessionId: String)
}
public data class GoalInfo(id: String, sessionId: String, objective: String, phase: GoalPhase, roundsStarted: Int, maxRounds: Int, armed: Boolean = true, blockedReason: String? = null, createdAt: Long = 0, updatedAt: Long = 0)
public value class GoalPhase { companion object { val ACTIVE; val PAUSED; val BLOCKED; val COMPLETE; val ALL; fun fromWire(value: String): GoalPhase? } }jobs() has no list method: read the current set once with observe().first().
Chat, bus, logs, app
public interface ChatService {
public suspend fun postCustomMessage(sessionId: String, customType: String, payload: JsonObject, text: String = "", display: Boolean = true): Boolean
public suspend fun sendMessage(sessionId: String, text: String, options: ChatMessageOptions = chatMessageOptions()): ChatSendResult
public suspend fun sendMessageWithAttachments(sessionId: String, text: String, attachments: List<ChatAttachment>, options: ChatMessageOptions = chatMessageOptions()): ChatSendResult
}
public enum class ChatDelivery { STEER, FOLLOW_UP }
public interface ChatMessageOptions { val triggerTurn: Boolean; val deliverAs: ChatDelivery; val display: ChatDisplay? }
public fun chatMessageOptions(triggerTurn: Boolean = true, deliverAs: ChatDelivery = ChatDelivery.STEER, display: ChatDisplay? = null): ChatMessageOptions
public interface ChatDisplay { val customType: String; val payload: JsonObject; val text: String }
public fun chatDisplay(customType: String, payload: JsonObject = JsonObject(emptyMap()), text: String = ""): ChatDisplay
public interface ChatSendResult { val kind: ChatSendKind; val sessionId: String; val runId: String?; val delivery: ChatDelivery? }
public value class ChatSendKind { companion object { val STARTED; val QUEUED; val DISPLAYED; val ALL; fun fromWire(value: String): ChatSendKind? } }
public interface ChatAttachment { val path: String; val mimeType: String?; val name: String? }
public fun chatAttachment(path: String, mimeType: String? = null, name: String? = null): ChatAttachment
public interface PluginBus {
public fun publish(event: PluginBusEvent)
public fun subscribe(topic: String? = null): Flow<PluginBusEvent>
}
public interface PluginBusEvent { val topic: String; val publisher: String; val payload: JsonObject; val publishedAt: Long }
public fun pluginBusEvent(topic: String, payload: JsonObject = JsonObject(emptyMap()), publishedAt: Long = 0): PluginBusEvent
public interface LogService {
public fun log(level: PluginLogLevel, message: String, error: Throwable? = null)
public fun debug(message: String): Unit = log(PluginLogLevel.DEBUG, message)
public fun info(message: String): Unit = log(PluginLogLevel.INFO, message)
public fun warn(message: String, error: Throwable? = null): Unit = log(PluginLogLevel.WARN, message, error)
public fun error(message: String, error: Throwable? = null): Unit = log(PluginLogLevel.ERROR, message, error)
}
public enum class PluginLogLevel { DEBUG, INFO, WARN, ERROR }
public interface AppInfoService { public val info: AppInfo }
public data class AppInfo(versionName: String, versionCode: Long, pluginApiLevel: Int = PLUGIN_API_LEVEL, uiApiLevel: Int = HOST_UI_API_LEVEL, language: String = "zh", androidSdkInt: Int = 0, deviceModel: String = "", installationId: String = "")Chat delivery behavior is described under Custom messages and cards.
Content, network, and data
public interface NetworkService {
public suspend fun request(method: String, url: String, headers: Map<String, String> = emptyMap(), body: String? = null, timeoutMs: Long = DEFAULT_TIMEOUT_MS): NetworkResponse
public suspend fun download(url: String, targetPath: String, expectedSha256: String? = null, onProgress: ((Int?) -> Unit)? = null): DownloadResult
public companion object { public const val DEFAULT_TIMEOUT_MS: Long = 30_000 }
}
public suspend fun NetworkService.get(url: String, headers: Map<String, String> = emptyMap()): NetworkResponse
public suspend fun NetworkService.post(url: String, body: String, headers: Map<String, String> = emptyMap()): NetworkResponse
public data class NetworkResponse(statusCode: Int, body: String, headers: Map<String, String> = emptyMap(), contentType: String? = null, finalUrl: String? = null)
public data class DownloadResult(path: String, size: Long, sha256: String)
public interface SecretService {
public suspend fun get(key: String): String?
public suspend fun put(key: String, value: String)
public suspend fun remove(key: String)
public suspend fun clear()
}
public interface PluginSettingsService {
public suspend fun get(key: String): String?
public suspend fun put(key: String, value: String)
public suspend fun remove(key: String)
public suspend fun clear()
public suspend fun keys(): Set<String>
public suspend fun snapshot(): Map<String, String>
public suspend fun getJson(key: String): JsonObject?
public suspend fun putJson(key: String, value: JsonObject)
public fun observe(key: String? = null): Flow<Map<String, String>>
}
public interface ImageService {
public suspend fun load(url: String, maxEdgePx: Int = DEFAULT_MAX_EDGE_PX): RemoteImage?
public companion object { public const val DEFAULT_MAX_EDGE_PX: Int = 720 }
}
public data class RemoteImage(bitmap: ImageBitmap, width: Int, height: Int, contentType: String? = null, fromCache: Boolean = false)
public interface WebService {
public val available: Boolean
public suspend fun search(query: String, limit: Int = 8): List<PluginWebResult>
public suspend fun fetch(url: String, maxChars: Int = 20_000): PluginWebPage?
}
public data class PluginWebResult(title: String, url: String, snippet: String? = null)
public data class PluginWebPage(url: String, title: String?, text: String, truncated: Boolean = false)
public interface MediaService {
public suspend fun saveToDownloads(fileName: String, mimeType: String, bytes: ByteArray): String?
public suspend fun saveFileToDownloads(path: String, fileName: String? = null, mimeType: String? = null): String?
public suspend fun saveImageToGallery(fileName: String, mimeType: String, bytes: ByteArray): String?
public suspend fun scanFile(path: String): Boolean
public suspend fun open(path: String): Boolean
public suspend fun share(path: String, mimeType: String? = null): Boolean
public suspend fun preview(path: String): Boolean
public suspend fun readImage(path: String, maxSizePx: Int = 2_048): ByteArray?
public suspend fun thumbnail(path: String, maxSizePx: Int = 512): ByteArray?
public suspend fun importUri(uri: String, fileName: String? = null): String?
}MCP and mini apps
public interface McpService {
public suspend fun servers(): List<McpServer>
public suspend fun probe(name: String): McpProbe
public suspend fun tools(server: String): List<McpTool>
public suspend fun call(server: String, tool: String, arguments: JsonObject = JsonObject(emptyMap())): McpCallResult
public suspend fun callStructured(server: String, tool: String, arguments: JsonObject = JsonObject(emptyMap())): McpStructuredCallResult
}
public data class McpServer(name: String, url: String? = null, enabled: Boolean = true, status: McpServerStatus = McpServerStatus.UNKNOWN, toolCount: Int = 0)
public data class McpTool(name: String, description: String? = null, inputSchema: JsonObject = JsonObject(emptyMap()))
public data class McpProbe(status: McpServerStatus, toolCount: Int = 0, serverName: String? = null, error: String? = null)
public data class McpCallResult(blocks: List<ToolBlock> = emptyList(), isError: Boolean = false)
public value class McpServerStatus { companion object { val OK; val AUTH_REQUIRED; val FAILED; val UNKNOWN; val ALL; fun fromWire(value: String): McpServerStatus? } }
public interface McpStructuredCallResult { val blocks: List<ToolBlock>; val structuredContent: JsonElement?; val isError: Boolean }
public fun mcpStructuredCallResult(blocks: List<ToolBlock>, structuredContent: JsonElement?, isError: Boolean = false): McpStructuredCallResult
public interface MiniappService {
public suspend fun scan(): MiniappScan
public suspend fun load(id: String): MiniappEntry
public suspend fun create(request: MiniappCreateRequest): MiniappApp?
public suspend fun edit(id: String, instruction: String): MiniappRun
public suspend fun delete(id: String): Boolean
public suspend fun run(id: String, instruction: String): MiniappRun
}
public data class MiniappApp(id: String, name: String, description: String? = null, updatedAt: Long = 0)
public data class MiniappScan(apps: List<MiniappApp> = emptyList(), invalid: List<MiniappInvalid> = emptyList())
public data class MiniappInvalid(id: String, reason: String)
public interface MiniappEntry { val kind: MiniappEntryKind; val app: MiniappApp?; val manifest: JsonObject?; val id: String?; val reason: String? }
public fun miniappValid(app: MiniappApp, manifest: JsonObject = JsonObject(emptyMap())): MiniappEntry
public fun miniappInvalid(id: String, reason: String): MiniappEntry
public fun miniappMissing(): MiniappEntry
public interface MiniappCreateRequest { val name: String; val description: String; val prompt: String }
public fun miniappCreateRequest(name: String, description: String, prompt: String = ""): MiniappCreateRequest
public data class MiniappRun(appId: String, accepted: Boolean, error: String? = null)
public value class MiniappEntryKind { companion object { val VALID; val INVALID; val MISSING; val ALL; fun fromWire(value: String): MiniappEntryKind? } }Device and system
public interface DeviceService {
public val info: DeviceInfo
public val state: DeviceState
public fun observe(): Flow<DeviceState>
public fun vibrate(durationMs: Long = 200)
public fun openSettings(section: DeviceSettings): Boolean
}
public data class DeviceInfo(manufacturer: String, brand: String, model: String, device: String, product: String, hardware: String, androidRelease: String, sdkInt: Int, abis: List<String>, emulator: Boolean, language: String, timezone: String, screenWidthPx: Int, screenHeightPx: Int, density: Float, refreshRate: Float, totalMemoryBytes: Long, totalStorageBytes: Long, installationId: String)
public data class DeviceState(batteryPercent: Int, charging: Boolean, powerSave: Boolean, networkType: String, connected: Boolean, screenOn: Boolean, locked: Boolean, language: String, timezone: String, uptimeMs: Long, freeMemoryBytes: Long, freeStorageBytes: Long, hostAccess: HostAccessLevel)
public enum class DeviceSettings { APP, NOTIFICATIONS, ACCESSIBILITY, NOTIFICATION_LISTENER, OVERLAY, USAGE_STATS, BATTERY_OPTIMIZATION, INSTALL_PACKAGES, STORAGE, DEVELOPER, WIRELESS_DEBUGGING, LOCATION }
public interface ClipboardService {
public fun text(): String?
public fun setText(text: String)
public fun uri(): String?
public fun setUri(uri: String)
public fun has(): Boolean
public fun clear()
}
public interface PermissionService {
public fun granted(permission: String): Boolean
public suspend fun request(vararg permissions: String): Map<String, Boolean>
public fun special(access: PluginSpecialAccess): PluginAccessState
public fun openSettings(access: PluginSpecialAccess): Boolean
}
public value class PluginSpecialAccess { companion object { val NOTIFICATION_LISTENER; val ACCESSIBILITY; val OVERLAY; val USAGE_STATS; val BATTERY_OPTIMIZATION; val INSTALL_PACKAGES; val MANAGE_STORAGE; val ALL; fun fromWire(value: String): PluginSpecialAccess? } }
public data class PluginAccessState(granted: Boolean, available: Boolean = true, reason: String? = null)
public interface PackageService {
public suspend fun list(includeSystem: Boolean = false): List<PluginPackageInfo>
public suspend fun get(packageName: String): PluginPackageInfo?
public suspend fun install(apkPath: String, silent: Boolean = false): PackageInstallResult
public suspend fun uninstall(packageName: String, keepData: Boolean = false): PackageInstallResult
public fun launch(packageName: String): Boolean
public fun openAppInfo(packageName: String): Boolean
public suspend fun icon(packageName: String, sizePx: Int = 256): ByteArray?
}
public data class PluginPackageInfo(packageName: String, label: String, versionName: String, versionCode: Long, system: Boolean, enabled: Boolean, installedAtMs: Long = 0, updatedAtMs: Long = 0)
public data class PackageInstallResult(accepted: Boolean, pendingUserAction: Boolean = false, error: String? = null)
public interface IntentsService {
public fun startActivity(intent: Intent): Boolean
public suspend fun startActivityForResult(intent: Intent, timeoutMs: Long = DEFAULT_TIMEOUT_MS): PluginActivityResult
public fun sendBroadcast(intent: Intent): Boolean
public fun startService(intent: Intent): Boolean
public fun stopService(intent: Intent): Boolean
public fun canResolve(intent: Intent): Boolean
public suspend fun resolve(intent: Intent): ResolvedIntent?
public suspend fun queryActivities(intent: Intent): List<ResolvedIntent>
public companion object { public const val DEFAULT_TIMEOUT_MS: Long = 120_000 }
}
public data class PluginActivityResult(resultCode: Int, data: Intent?, cancelled: Boolean = false, timedOut: Boolean = false)
public data class ResolvedIntent(packageName: String, className: String?, label: String?, exported: Boolean)Experimental components:
@PluginExperimentalApi
public interface ComponentService {
public fun startActivity(options: PluginActivityOptions): Boolean
public fun registerReceiver(filter: IntentFilter): PluginReceiverHandle
}
public interface PluginActivityOptions { val pageId: String; val arguments: JsonObject; val newTask: Boolean }
public fun pluginActivityOptions(pageId: String, arguments: JsonObject = JsonObject(emptyMap()), newTask: Boolean = true): PluginActivityOptions
public interface PluginReceiverHandle { val id: String; fun events(): Flow<Intent>; fun close() }Background and foreground work:
public interface BackgroundService {
public suspend fun schedule(id: String, kind: PluginBackgroundKind, triggerAtMs: Long? = null, intervalMs: Long? = null, requiresNetwork: Boolean = false, requiresCharging: Boolean = false): Boolean
public suspend fun cancel(id: String): Boolean
public suspend fun tasks(): List<PluginBackgroundTaskInfo>
public fun startForeground(options: ForegroundServiceOptions): Boolean
public fun updateForeground(options: ForegroundServiceOptions): Boolean
public fun stopForeground(id: String): Boolean
public val batteryOptimizationIgnored: Boolean
public fun requestIgnoreBatteryOptimizations(): Boolean
public fun openBatteryOptimizationSettings(): Boolean
}
public value class PluginBackgroundKind { companion object { val ONCE; val PERIODIC; val EXACT; val BOOT; val ALL; fun fromWire(value: String): PluginBackgroundKind? } }
public data class PluginBackgroundTaskInfo(id: String, kind: String, nextRunAtMs: Long? = null, intervalMs: Long? = null, lastRunAtMs: Long? = null)
public interface ForegroundServiceOptions { val id: String; val title: String; val text: String; val ongoing: Boolean; val progress: Int? }
public fun foregroundServiceOptions(id: String, title: String, text: String, ongoing: Boolean = true, progress: Int? = null): ForegroundServiceOptionsScreen and notifications
public interface ScreenService {
public val status: ScreenStatus
public suspend fun startVirtual(): ScreenStatus
public suspend fun stopVirtual()
public suspend fun observe(target: ScreenTarget = ScreenTarget.VIRTUAL, packageName: String? = null): ScreenObservation
public suspend fun screenshot(target: ScreenTarget = ScreenTarget.VIRTUAL): ScreenScreenshot
public suspend fun apps(): List<ScreenApp>
public suspend fun launch(packageName: String, target: ScreenTarget = ScreenTarget.VIRTUAL): Boolean
public suspend fun tap(x: Int, y: Int, target: ScreenTarget = ScreenTarget.VIRTUAL): Boolean
public suspend fun tapNode(ref: String, target: ScreenTarget = ScreenTarget.VIRTUAL): Boolean
public suspend fun swipe(fromX: Int, fromY: Int, toX: Int, toY: Int, durationMs: Int = 300, target: ScreenTarget = ScreenTarget.VIRTUAL): Boolean
public suspend fun scroll(deltaY: Int, target: ScreenTarget = ScreenTarget.VIRTUAL): Boolean
public suspend fun type(text: String, target: ScreenTarget = ScreenTarget.VIRTUAL): Boolean
public suspend fun key(keyCode: String, target: ScreenTarget = ScreenTarget.VIRTUAL): Boolean
public suspend fun waitFor(text: String, timeoutMs: Long = DEFAULT_WAIT_TIMEOUT_MS, target: ScreenTarget = ScreenTarget.VIRTUAL): Boolean
public companion object { public const val DEFAULT_WAIT_TIMEOUT_MS: Long = 5_000 }
}
public enum class ScreenTarget { VIRTUAL, MAIN }
public data class ScreenStatus(virtual: ScreenCapability = ScreenCapability(), main: ScreenCapability = ScreenCapability())
public data class ScreenCapability(available: Boolean = false, accessibility: Boolean = false, screenshot: Boolean = false, input: Boolean = false)
public data class ScreenObservation(packageName: String? = null, windowTitle: String? = null, nodes: List<ScreenNode> = emptyList(), capturedAt: Long = 0)
public data class ScreenNode(ref: String, className: String? = null, text: String? = null, contentDescription: String? = null, bounds: ScreenBounds, clickable: Boolean = false, children: List<ScreenNode> = emptyList())
public data class ScreenBounds(left: Int, top: Int, right: Int, bottom: Int) { public val width: Int; public val height: Int }
public data class ScreenScreenshot(path: String, width: Int, height: Int, capturedAt: Long = 0)
public data class ScreenApp(packageName: String, label: String)
public interface NotificationService {
public val enabled: Boolean
public fun notify(notification: PluginNotification)
public fun notifyChecked(notification: PluginNotification): PluginNotificationHandle?
public fun updateProgress(id: String, progress: Int?, title: String? = null)
public fun cancel(id: String)
public val listenerGranted: Boolean
public suspend fun recent(limit: Int = 50): List<PluginNotificationRecord>
public fun received(): Flow<PluginNotificationRecord>
public fun removed(): Flow<String>
public suspend fun dismiss(key: String): Boolean
}
public enum class NotificationChannel { DEFAULT, PROGRESS, ALERT }
public interface PluginNotification {
val id: String; val title: String; val body: String; val channel: NotificationChannel; val progress: Int?; val ongoing: Boolean
val actions: List<PluginNotificationAction>; val payload: JsonObject
}
public fun pluginNotification(id: String, title: String, body: String, channel: NotificationChannel = NotificationChannel.DEFAULT, progress: Int? = null, ongoing: Boolean = false): PluginNotification
public fun pluginNotificationWithActions(id: String, title: String, body: String, channel: NotificationChannel = NotificationChannel.DEFAULT, progress: Int? = null, ongoing: Boolean = false, actions: List<PluginNotificationAction> = emptyList(), payload: JsonObject = JsonObject(emptyMap())): PluginNotification
public interface PluginNotificationAction { val id: String; val label: String }
public fun notificationAction(id: String, label: String): PluginNotificationAction
public data class PluginNotificationHandle(id: String, key: String)
public data class PluginNotificationRecord(key: String, packageName: String, appLabel: String?, title: String?, text: String?, bigText: String?, subText: String?, channelId: String?, category: String?, postedAtMs: Long, ongoing: Boolean, clearable: Boolean, progress: Int? = null, actions: List<PluginNotificationActionInfo> = emptyList())
public data class PluginNotificationActionInfo(id: String, title: String?)Notification listening requires permissions: ["notifications.listen"] plus components.notificationListener. notifyChecked returns null when notifications are disabled; notify is silently ignored. Tapping a notification without an explicit action opens the plugin's first declared page.
Location, contacts, SMS, calendar
public interface LocationService {
public val available: Boolean
public val permissionGranted: Boolean
public suspend fun lastKnown(): PluginLocation?
public suspend fun current(timeoutMs: Long = DEFAULT_TIMEOUT_MS): PluginLocation?
public fun updates(minIntervalMs: Long = 1_000, minDistanceM: Float = 0f): Flow<PluginLocation>
public suspend fun geocode(query: String, limit: Int = 5): List<PluginGeocode>
public suspend fun reverseGeocode(location: PluginLocation): PluginGeocode?
public companion object { public const val DEFAULT_TIMEOUT_MS: Long = 10_000 }
}
public data class PluginLocation(latitude: Double, longitude: Double, accuracyM: Float, provider: String, timeMs: Long, altitudeM: Double? = null, speedMps: Float? = null, bearingDeg: Float? = null)
public data class PluginGeocode(latitude: Double, longitude: Double, label: String? = null, country: String? = null, adminArea: String? = null, locality: String? = null)
public interface ContactsService {
public val permissionGranted: Boolean
public suspend fun list(limit: Int = 0): List<PluginContact>
public suspend fun search(query: String, limit: Int = 20): List<PluginContact>
public suspend fun get(id: String): PluginContact?
public suspend fun create(draft: PluginContactDraft): PluginContact?
public suspend fun update(id: String, draft: PluginContactDraft): PluginContact?
public suspend fun delete(id: String): Boolean
}
public data class PluginContact(id: String, displayName: String, phones: List<PluginContactField> = emptyList(), emails: List<PluginContactField> = emptyList(), organization: String? = null, note: String? = null, starred: Boolean = false)
public data class PluginContactField(value: String, label: String? = null, type: String? = null)
public interface PluginContactDraft { val displayName: String; val phones: List<String>; val emails: List<String>; val organization: String? }
public fun pluginContactDraft(displayName: String, phones: List<String> = emptyList(), emails: List<String> = emptyList(), organization: String? = null): PluginContactDraft
public interface SmsService {
public val available: Boolean
public val canRead: Boolean
public val canSend: Boolean
public suspend fun threads(limit: Int = 20): List<PluginSmsThread>
public suspend fun messages(threadId: String? = null, address: String? = null, limit: Int = 50): List<PluginSmsMessage>
public suspend fun send(address: String, text: String, subscriptionId: Int? = null): Boolean
public suspend fun markRead(threadId: String): Boolean
public suspend fun delete(threadId: String): Boolean
}
public data class PluginSmsThread(id: String, address: String, contactName: String? = null, snippet: String? = null, dateMs: Long = 0, unreadCount: Int = 0)
public data class PluginSmsMessage(id: String, threadId: String, address: String, body: String, dateMs: Long, incoming: Boolean, read: Boolean)
public interface CalendarService {
public val permissionGranted: Boolean
public suspend fun calendars(): List<PluginCalendar>
public suspend fun events(fromMs: Long, toMs: Long, calendarIds: List<String> = emptyList(), limit: Int = 200): List<PluginCalendarEvent>
public suspend fun get(eventId: String): PluginCalendarEvent?
public suspend fun create(draft: PluginCalendarEventDraft): PluginCalendarEvent?
public suspend fun update(eventId: String, draft: PluginCalendarEventDraft): PluginCalendarEvent?
public suspend fun delete(eventId: String): Boolean
}
public data class PluginCalendar(id: String, name: String, accountName: String? = null, displayName: String? = null, color: String? = null, visible: Boolean = true, primary: Boolean = false)
public data class PluginCalendarEvent(id: String, calendarId: String, title: String, startMs: Long, endMs: Long, allDay: Boolean, description: String? = null, location: String? = null, timeZone: String? = null, reminders: List<Int> = emptyList())
public interface PluginCalendarEventDraft { val title: String; val startMs: Long; val endMs: Long; val allDay: Boolean; val description: String?; val location: String?; val calendarId: String?; val timeZone: String?; val reminders: List<Int> }
public fun pluginCalendarEventDraft(title: String, startMs: Long, endMs: Long, allDay: Boolean = false, description: String? = null, location: String? = null, calendarId: String? = null, timeZone: String? = null, reminders: List<Int> = emptyList()): PluginCalendarEventDraftSpeech, web, credentials, accessibility
public interface SpeechService {
public val speakAvailable: Boolean
public val recognizeAvailable: Boolean
public suspend fun speak(text: String): Boolean
public fun stopSpeaking()
public fun speaking(): Flow<Boolean>
public suspend fun recognize(timeoutMs: Long = DEFAULT_TIMEOUT_MS): PluginSpeechResult
public fun openVoiceSettings(): Boolean
public companion object { public const val DEFAULT_TIMEOUT_MS: Long = 30_000 }
}
public data class PluginSpeechResult(text: String?, error: String? = null)
@PluginExperimentalApi
public interface CredentialService {
public fun providers(): List<PluginProviderCredential>
public fun provider(id: String): PluginProviderCredential?
public fun mcpTokens(): List<PluginMcpToken>
public fun mcpToken(server: String): PluginMcpToken?
public fun hostValues(): Map<String, String>
}
public data class PluginProviderCredential(id: String, name: String, baseUrl: String? = null, apiKey: String? = null, authKind: String? = null)
public data class PluginMcpToken(server: String, url: String? = null, accessToken: String? = null, refreshToken: String? = null, tokenType: String? = null, expiresAtMs: Long? = null)
@PluginExperimentalApi
public interface AccessibilityServicePlugin {
public val enabled: Boolean
public fun events(): Flow<PluginAccessibilityEvent>
public fun performGlobalAction(action: PluginGlobalAction): Boolean
}
public data class PluginAccessibilityEvent(eventType: Int, packageName: String?, className: String?, text: String?, contentDescription: String?, timeMs: Long)
public value class PluginGlobalAction { companion object { val BACK; val HOME; val RECENTS; val NOTIFICATIONS; val QUICK_SETTINGS; val POWER_DIALOG; val ALL; fun fromWire(value: String): PluginGlobalAction? } }credentials() exposes the user's real provider and MCP credentials. Read them only while performing a user request, never persist, log, or forward them.
UI service
UiService handles host-styled interaction and navigation. Full behavior and picker models are in UI Extensions.
public interface UiService {
public fun openUrl(url: String)
public fun share(request: ShareRequest)
public fun shareFiles(paths: List<String>, mimeType: String? = null)
public fun toast(message: String)
public fun openPage(pageId: String)
public fun openPageWithArguments(pageId: String, arguments: JsonObject, newTask: Boolean = false)
public fun openPageSheet(pageId: String, arguments: JsonObject = JsonObject(emptyMap()))
public fun closePage(result: JsonObject? = null)
public fun pageContext(): PluginPageContext?
public val isDark: Boolean
public suspend fun confirm(request: UiConfirmRequest): Boolean
public suspend fun prompt(request: UiPromptRequest): String?
public suspend fun choose(request: UiChooseRequest): String?
public suspend fun pickDate(request: UiDatePickRequest = uiDatePickRequest()): Long?
public suspend fun pickTime(request: UiTimePickRequest = uiTimePickRequest()): Int?
public suspend fun pickFiles(request: UiFilePickRequest = uiFilePickRequest()): List<PluginPickedFile>
public suspend fun pickImage(request: UiImagePickRequest = uiImagePickRequest()): PluginPickedFile?
public suspend fun scanQr(): String?
public suspend fun pickDirectory(): String?
public fun snackbar(message: String, actionLabel: String? = null, action: (() -> Unit)? = null)
}Contributions
Contributions carries the plugin's tools and hooks for the whole plugin or for one session.
public interface Contributions {
public val tools: List<PluginTool>
public val hooks: PluginHooks
}
public fun contributions(tools: List<PluginTool> = emptyList(), hooks: PluginHooks = PluginHooks.None): ContributionscontributionsFor(host, session) is materialized once per session. Hooks returned there override the plugin's global hooks. When the returned Contributions keeps the default PluginHooks.None, the host falls back to the plugin's global hooks — so adding session tools does not silently disable global hooks.
Tools
public enum class PluginToolExposure { DIRECT, DEFERRED }
public interface PluginTool {
public val name: String
public val label: String
public val description: String
public val parameters: JsonObject
public val promptSnippet: String?
public val promptGuidelines: List<String>
public val exposure: PluginToolExposure
public suspend fun execute(call: PluginToolCall): PluginToolResult
}
public fun pluginTool(
name: String,
description: String,
parameters: JsonObject,
label: String? = null,
promptSnippet: String? = null,
promptGuidelines: List<String> = emptyList(),
exposure: PluginToolExposure = PluginToolExposure.DIRECT,
execute: suspend (PluginToolCall) -> PluginToolResult,
): PluginTool
public interface PluginToolCall {
public val callId: String
public val args: JsonObject
public val signal: PluginRunSignal?
public val sessionId: String
public fun partial(result: PluginToolResult)
}
public interface PluginRunSignal {
public val cancelled: Boolean
public fun throwIfCancelled()
public fun onCancel(listener: () -> Unit): () -> Unit
public companion object { public val None: PluginRunSignal }
}
public interface PluginToolResult {
public val text: String?
public val blocks: List<ToolBlock>
public val details: JsonObject?
public val isError: Boolean
}
public fun textResult(text: String, details: JsonObject? = null, isError: Boolean = false): PluginToolResult
public fun richResult(blocks: List<ToolBlock>, details: JsonObject? = null, isError: Boolean = false): PluginToolResult
public interface ToolBlock
public interface TextBlock : ToolBlock { public val text: String }
public interface ImageBlock : ToolBlock { public val data: ByteArray; public val mimeType: String }
public interface FileRefBlock : ToolBlock { public val path: String; public val mimeType: String? }
public fun textBlock(text: String): ToolBlock
public fun imageBlock(data: ByteArray, mimeType: String): ToolBlock
public fun fileRefBlock(path: String, mimeType: String? = null): ToolBlock| Member | Behavior |
|---|---|
name | Global tool name, ^[a-z][a-z0-9_]*$; must not collide with host reserved names or another plugin |
label | Tool card title |
parameters | JSON Schema passed to the model as is |
promptSnippet | One-line summary shown in the system prompt |
promptGuidelines | Extra model rules for using the tool |
exposure | DIRECT (resident, default) or DEFERRED (discovered through tool_search, executed through tool_execute) |
execute | Suspend handler; exceptions become error results |
PluginToolCall:
callId— correlation id for logs and cards.args— model-provided arguments.sessionId— the active session id, or an empty string when there is no active session.signal— cancellation signal; callthrowIfCancelled()at stage boundaries or register cleanup withonCancel { }.partial(result)— stream an intermediate result to a live tool card; the return value ofexecuteis final.
Results:
textResultis plain text for the model;detailsis host-side metadata for cards, not model context.richResultacceptstextBlock,imageBlock(images enter model image content), andfileRefBlock(adds a file line for the model and a file row in the UI).isError = truemarks a failed result; use it instead of throwing for business errors.
Skills and prompt sections
public interface PluginSkill { val id: String; val markdown: String; val files: List<PluginSkillFile> }
public fun pluginSkill(id: String, markdown: String, files: List<PluginSkillFile> = emptyList()): PluginSkill
public interface PluginSkillFile { val path: String; val content: String?; val assetPath: String? }
public fun pluginSkillFile(path: String, content: String? = null, assetPath: String? = null): PluginSkillFile
public interface PromptSection { val id: String; val body: String; val priority: Int }
public fun promptSection(id: String, body: String, priority: Int = 0): PromptSectionSkill markdown must be a complete SKILL.md with YAML frontmatter (name, description); PluginSkill.id must match the frontmatter name. files paths are relative inside the skill directory, and content and assetPath are mutually exclusive (assetPath is assets/<path> inside the bundle). Skill ids are ^[a-z][a-z0-9_-]*$; they must be enabled (the plugin must not report unavailable) to appear. Prompt section ids must be unique within one plugin; sections are sorted by ascending priority.
Prompt override
@PluginExperimentalApi
public interface PromptOverride { val preamble: String?; val rules: String?; val sections: List<PromptSection>; val priority: Int }
@PluginExperimentalApi
public fun promptOverride(preamble: String? = null, rules: String? = null, sections: List<PromptSection> = emptyList(), priority: Int = 0): PromptOverride
@PluginExperimentalApi
public interface PromptOverridePlugin { public fun promptOverride(host: PluginHost): PromptOverride }Declare the prompt capability and implement PromptOverridePlugin to replace the agent preamble/rules or add sections. Among several plugins the highest priority wins for preamble and rules; sections are concatenated by ascending priority. A single plugin is limited to 32 KiB and all plugins to 64 KiB; oversized contributions are skipped and logged. The host-generated workspace and environment sections cannot be overridden.
Hooks
Every hook is a suspend function with a default empty implementation; implement only what you need and return the object from contributions() (global) or contributionsFor() (session).
public interface PluginHooks {
public suspend fun sessionStarted(event: SessionStartedEvent): Unit = Unit
public suspend fun sessionClosed(event: SessionClosedEvent): Unit = Unit
public suspend fun runStarted(event: RunStartedEvent): Unit = Unit
public suspend fun runFinished(event: RunFinishedEvent): Unit = Unit
public suspend fun turnStarted(event: TurnStartedEvent): Unit = Unit
public suspend fun turnFinished(event: TurnFinishedEvent): Unit = Unit
public suspend fun messageStarted(event: MessageStartedEvent): Unit = Unit
public suspend fun messageDelta(event: MessageDeltaEvent): Unit = Unit
public suspend fun messageFinished(event: MessageFinishedEvent): Unit = Unit
public suspend fun toolExecutionUpdate(event: ToolExecutionUpdateEvent): Unit = Unit
public suspend fun compactionStarted(event: CompactionStartedEvent): Unit = Unit
public suspend fun compactionFinished(event: CompactionFinishedEvent): Unit = Unit
public suspend fun compactionFailed(event: CompactionFailedEvent): Unit = Unit
public suspend fun modelChanged(event: ModelChangedEvent): Unit = Unit
public suspend fun thinkingLevelChanged(event: ThinkingLevelChangedEvent): Unit = Unit
public suspend fun retryScheduled(event: RetryScheduledEvent): Unit = Unit
public suspend fun retrySucceeded(event: RetrySucceededEvent): Unit = Unit
public suspend fun retryExhausted(event: RetryExhaustedEvent): Unit = Unit
public suspend fun mcpStatusChanged(event: McpStatusChangedEvent): Unit = Unit
public suspend fun mcpToolsChanged(event: McpToolsChangedEvent): Unit = Unit
public suspend fun busEvent(event: BusEventReceived): Unit = Unit
public suspend fun notificationReceived(event: NotificationReceivedEvent): Unit = Unit
public suspend fun notificationAction(event: NotificationActionEvent): Unit = Unit
public suspend fun backgroundTask(event: BackgroundTaskEvent): Unit = Unit
public suspend fun shareReceived(event: ShareReceivedEvent): Unit = Unit
public suspend fun deepLinkReceived(event: DeepLinkReceivedEvent): Unit = Unit
public suspend fun appLifecycle(event: AppLifecycleEvent): Unit = Unit
public suspend fun promptTransform(request: PromptRequest): String = request.prompt
public suspend fun context(request: PluginContextRequest): String? = null
public suspend fun inputTransform(request: InputRequest): InputDecision = inputContinue(request.text, request.imagePaths)
public suspend fun beforeToolCall(request: ToolCallRequest): ToolCallDecision = toolContinue()
public suspend fun afterToolExecution(request: ToolExecutionResult): ToolResultDecision = resultKeep()
public companion object {
public const val TRANSFORM_TIMEOUT_MS: Long = 2_000
public const val OBSERVE_TIMEOUT_MS: Long = 5_000
public val None: PluginHooks
}
}Session observation events (21), dispatched serially with a 5 s timeout each; errors and timeouts are logged and dispatch continues:
| Callback | Event fields |
|---|---|
sessionStarted | sessionId, title?, workspace? |
sessionClosed | sessionId |
runStarted | sessionId, runId |
runFinished | sessionId, runId, error?, succeeded |
turnStarted | sessionId, turnId |
turnFinished | sessionId, turnId, failed |
messageStarted | sessionId, messageId, role |
messageDelta | sessionId, messageId, delta |
messageFinished | sessionId, messageId, text? |
toolExecutionUpdate | sessionId, callId, toolName, phase, partial? |
compactionStarted | sessionId |
compactionFinished | sessionId, tokensBefore, tokensAfter |
compactionFailed | sessionId, error |
modelChanged | sessionId, model |
thinkingLevelChanged | sessionId, level |
retryScheduled | sessionId, attempt, delayMs, reason? |
retrySucceeded | sessionId, attempt |
retryExhausted | sessionId, attempts, error |
mcpStatusChanged | server, status |
mcpToolsChanged | server, tools |
busEvent | event |
System events (6) go only to global hooks and require the documented gate:
| Callback | Event fields | Gate |
|---|---|---|
notificationReceived | notification, removed | notifications + components.notificationListener |
notificationAction | notificationId, actionId, payload | notifications |
backgroundTask | taskId, kind, firedAtMs | background + components.background or components.foregroundService |
shareReceived | text?, streams, title? | share + components.share |
deepLinkReceived | path, arguments | deeplink + components.deeplinks |
appLifecycle | foreground | app |
Transforms and gates, chained in plugin registration order with a 2 s timeout each:
| Method | Input → output | Failure policy |
|---|---|---|
promptTransform | PromptRequest(sessionId, prompt) → rewritten prompt | fail-open: keep the previous value |
context | PluginContextRequest(sessionId, cwd, providerId?, modelId?) → text injected into the system prompt | fail-open: skipped; 8 KiB per plugin, 32 KiB total |
inputTransform | InputRequest(sessionId, text, imagePaths) → InputDecision via inputContinue(text, imagePaths) or inputHandled() | fail-open: keep the current input |
beforeToolCall | ToolCallRequest(sessionId, callId, toolName, args) → toolContinue(), toolBlock(reason), or toolRewrite(args) | fail-closed: timeout or exception blocks the call |
afterToolExecution | ToolExecutionResult(sessionId, callId, toolName, result) → resultKeep() or resultReplace(result) | keep the previous result |
These callbacks sit on the session critical path and must return quickly. Do not do network or heavy IO in them, and do not wait for user input. Cancellation must propagate: never swallow CancellationException.
The host freezes the hook set when a run starts; plugins enabled or disabled during the run affect the next run. A plugin disabled mid-run can still receive the remaining events, so callbacks must tolerate changed state; put cleanup in close() or onDisable().
Custom messages and cards
chat() writes messages into a session and can attach a renderable card:
val result = host.chat().sendMessage(
sessionId = call.sessionId,
text = "Sync finished, 12 files",
options = chatMessageOptions(
triggerTurn = false,
display = chatDisplay(
customType = "my.card",
payload = buildJsonObject { put("title", "Sync finished") },
text = "Card summary",
),
),
)| Option | Behavior |
|---|---|
triggerTurn = true (default) | Starts a new turn with text as the user message. When the session is busy, deliverAs decides: STEER interrupts, FOLLOW_UP queues |
triggerTurn = false | Writes the card message without starting a turn |
display | Writes the card first (equivalent to postCustomMessage) and then triggers the turn |
| Unknown session | Throws IllegalArgumentException |
| Result | ChatSendResult.kind is STARTED, QUEUED, or DISPLAYED |
Cards written with a customType render through the chat.message:<customType> slot and can be restored after reopening the session.
Tool result cards
plugin-api supports a three-layer tool result for plugin tools. Write these keys into details:
| Key | Contents |
|---|---|
sora.raw | Full upstream output, verbatim; appended to the model text under "Full return" |
sora.guidance | Short next-step guidance for the model; appended under "Usage" |
sora.card | { "customType": ..., "title": ..., "payload": ... }; the host adds a present(...) instruction to the model text and a display title to the card |
sora.display | Set by the host; display title for the tool card |
These constants live on Cards:
public object Cards {
public const val KEY: String = "sora.card"
public const val RAW_KEY: String = "sora.raw"
public const val GUIDANCE_KEY: String = "sora.guidance"
public const val DISPLAY_KEY: String = "sora.display"
public fun descriptor(customType: String?, title: String?, payload: JsonObject?): JsonObject
public fun instruction(callId: String, title: String?): String
public fun deliver(callId: String, result: PluginToolResult): PluginToolResult
}pluginTool(...) applies Cards.deliver automatically. If you implement PluginTool yourself, call Cards.deliver(call.callId, result) once before returning. For error results the card and the present instruction are dropped, keeping the body, the full return, and the guidance. Do not write the present(...) instruction yourself, and do not put card ids into the payload — payloads must stay complete so the card can render.
Text, icons, and slot states
public interface LocalizedText {
public val values: Map<String, String>
public fun resolve(language: String? = null): String?
public fun hasDefault(): Boolean
}
public fun localizedText(default: String, zh: String? = null, en: String? = null): LocalizedText
public fun localizedText(values: Map<String, String>): LocalizedText
public interface IconRef { public val asset: String }
public fun assetIcon(path: String): IconRef
public interface SlotState
public data object NoSlotState : SlotState
public interface ToolCardSlotState : SlotState { val callId: String; val toolName: String; val args: JsonObject; val result: PluginToolResult? }
public interface CustomMessageSlotState : SlotState { val messageId: String; val customType: String; val payload: JsonObject }localizedText(values) requires a default key. assetIcon(path) expects asset:<path inside the bundle>. Slot states are consumed in Compose slot content; see UI Extensions.
Capability to service mapping
Every capability, its accessor (if any), and the models its service returns. Services not declared in the manifest are not injected.
| Capability | Accessor | Main types |
|---|---|---|
linux | linux() | LinuxService, LinuxResult, LinuxChunk, LinuxChunkKind |
screen | screen() | ScreenService, ScreenStatus, ScreenObservation, ScreenNode, ScreenScreenshot, ScreenApp, ScreenTarget |
notifications | notifications() | NotificationService, PluginNotification, PluginNotificationRecord, PluginNotificationHandle |
secrets | secrets() | SecretService |
network | network() | NetworkService, NetworkResponse, DownloadResult |
files | files() | FileService, FileEntry |
sessions | sessions() | SessionService, SessionInfo, PluginMessage, MessageRole |
jobs | jobs() | JobService, JobInfo, JobRead, JobStatus |
timers | timers() | TimerService, TimerRequest, TimerTrigger, TimerInfo |
goals | goals() | GoalService, GoalInfo, GoalPhase |
miniapp | miniapp() | MiniappService, MiniappScan, MiniappEntry, MiniappRun |
mcp | mcp() | McpService, McpServer, McpTool, McpProbe, McpCallResult, McpStructuredCallResult |
ui | ui() | UiService, UiConfirmRequest, UiPromptRequest, UiChooseRequest, UiDatePickRequest, UiTimePickRequest, UiFilePickRequest, UiImagePickRequest, PluginPickedFile |
app | app() | AppInfoService, AppInfo |
bus | bus() | PluginBus, PluginBusEvent |
logs | logs() | LogService, PluginLogLevel |
chat | chat() | ChatService, ChatMessageOptions, ChatDisplay, ChatSendResult, ChatAttachment |
prompt | — | PromptOverridePlugin, PromptOverride |
settings | settings() | PluginSettingsService |
device | device() | DeviceService, DeviceInfo, DeviceState, DeviceSettings |
clipboard | clipboard() | ClipboardService |
permissions | permissions() | PermissionService, PluginSpecialAccess, PluginAccessState |
packages | packages() | PackageService, PluginPackageInfo, PackageInstallResult |
privilege | privilege() | PrivilegeService, PrivilegeLevel, RootState, AdbState, PrivilegeResult, AdbPairingResult |
intents | intents() | IntentsService, PluginActivityResult, ResolvedIntent |
components | components() | ComponentService, PluginActivityOptions, PluginReceiverHandle |
background | background() | BackgroundService, PluginBackgroundKind, PluginBackgroundTaskInfo, ForegroundServiceOptions |
location | location() | LocationService, PluginLocation, PluginGeocode |
contacts | contacts() | ContactsService, PluginContact, PluginContactField, PluginContactDraft |
sms | sms() | SmsService, PluginSmsThread, PluginSmsMessage |
calendar | calendar() | CalendarService, PluginCalendar, PluginCalendarEvent, PluginCalendarEventDraft |
media | media() | MediaService |
speech | speech() | SpeechService, PluginSpeechResult |
web | web() | WebService, PluginWebResult, PluginWebPage |
images | images() | ImageService, RemoteImage |
credentials | credentials() | CredentialService, PluginProviderCredential, PluginMcpToken |
accessibility | accessibility() | AccessibilityServicePlugin, PluginAccessibilityEvent, PluginGlobalAction |
share | — | ShareReceivedEvent, SharedStream |
deeplink | — | DeepLinkReceivedEvent |
Experimental API
These declarations are annotated @PluginExperimentalApi (@RequiresOptIn, level WARNING): components(), credentials(), accessibility(), PromptOverridePlugin, and the types they use. Opt in at the use site or file level:
@OptIn(PluginExperimentalApi::class)Experimental declarations may change before they become stable; graduating an API only removes the annotation. Everything else in the SDK follows the API level compatibility promise.
Limits
- Plugin ids, versions, manifest fields, and package contents are validated at install; invalid packages are rejected with a specific code.
- Plugins cannot register activities, services, receivers, or permissions in the Android manifest; use the host proxies:
components()for a dedicated window and dynamic receivers,background()for foreground services,components.notificationListener/accessibility/share/deeplinksfor system events. - No resources:
res/andRare unavailable; use assets and manifest fields. - No declarative UI nodes: UI is Compose through slots, renderers, and pages.
- Native libraries are not loaded by the classloader.
- No process isolation: an exception on the main thread, in a Compose slot, or during a tool call can take the app down.
- No privilege escalation: Root/ADB commands run only within the tier the user selected.
- Known gaps:
notifications().notifyhas no receipt (usenotifyChecked);requestContributionsRefresh()returns no handle;jobs()has nolist().
