运行时 API
本页是插件可用的完整公开接口,取自 io.github.sadami3066.sora:plugin-api:2.0.2(包名 io.github.sadami3066.sora.plugin.api)。下文所有类型都由 SDK 声明;插件实现接口、调用工厂函数,绝不自行构造宿主拥有的模型。
可以整体导入包,也可以逐个导入声明:
import io.github.sadami3066.sora.plugin.api.*插件入口
宿主加载清单 entryClass 指定的类,并要求它具备公开的无参构造器。
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
}| 回调 | 宿主调用时机 | 需要做什么 |
|---|---|---|
availability(host) | 每次刷新 | 返回 available() 或 unavailable("原因");不可用会让插件进入 DEGRADED、停用技能并展示原因 |
onEnable / onDisable | 用户切换插件时,以及启动时对已启用插件 | 启动或停止插件工作;停用会先取消 host.scope,再调用 onDisable |
onUpgrade(host, fromVersion) | 新版本激活过程中、成为当前版本之前 | 迁移持久化状态;fromVersion 是当前正在使用的版本 |
skills(host) | 刷新时,插件已加载并启用 | 返回技能;宿主会把它们物化到智能体技能目录 |
promptSections(host) | 刷新时 | 追加系统提示词段落,按 priority 升序排列 |
contributions(host) | 内置贡献被物化时 | 返回全局工具与钩子 |
contributionsFor(host, session) | 每个会话绑定一次 | 返回会话级工具与钩子;返回默认钩子时继承全局钩子 |
ui(host) | 刷新时 | 返回插槽绑定、页面、输入框动作与工具结果渲染器 |
uninstall(host) | 用户删除插件之前 | 清理插件自身的外部副作用 |
close() | 停用、卸载、更新或进程退出时 | 释放资源;不要在之后启动异步工作 |
可用性辅助函数:
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() = available传给 contributionsFor 的会话句柄:
public interface PluginSessionInfo {
public val supportsChatDelivery: Boolean
public fun snapshot(): PluginSessionSnapshot?
}
public data class PluginSessionSnapshot(sessionId: String, file: String?, cwd: String)不要把 host、host.scope 或会话句柄缓存在插件字段中。重新启用的插件会被重新加载并获得新宿主;贡献在每次刷新物化一次,并在每个会话物化一次。
PluginHost
PluginHost 是插件唯一的入口。它暴露清单、目录、后台协程作用域、文本解析、36 个服务访问器与刷新触发器。
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()
}行为说明:
- 能力未声明的服务不会被注入,调用时抛出
PluginServiceUnavailable(IllegalStateException子类,带service与可选reason)。服务是可选的时候请捕获它。 - 已接线但当前不可用的服务通过自身字段(
available、enabled、permissionGranted、status等)报告,或返回 null/false,或抛出文档中写明的异常。 dataDir是插件私有的持久目录,升级后保留;assetsDir是已安装版本只读的 assets。scope会在停用、卸载、更新与进程退出时取消。长时间工作挂在它上面,并处理取消。requestContributionsRefresh()请求宿主重新物化工具、技能、提示词与 UI,并在安全点重建会话。它不返回句柄;忙碌会话会在本轮结束后更新。host.text(localized, *args)按应用语言解析LocalizedText,并应用String.format占位符。
宿主服务
以下签名就是精确的公开成员。数据类以其构造参数与默认值展示。线值类(PluginCapability、HostAccessLevel、PrivilegeLevel、MessageRole、JobStatus、GoalPhase、TimerTriggerKind 等)暴露 wire: String 属性,常量或工厂函数在伴生对象中;请从这些常量构造。
执行与文件
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() 在用户选择的执行层级(普通、ADB 或 Root)中运行,插件无法自行选择。exec 会记录超时与截断;stderr 会合并进 stdout,因此请检查 exitCode 与输出末尾。files() 的相对路径以 dataDir 为根;绝对路径遵循当前层级。
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 只读:exec 永远不会越过用户已授权的层级。AUTO 选择当前可用层级;在不可用时请求 ROOT 或 ADB 会返回失败。
智能体运行时
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() 没有列表方法:用 observe().first() 读取当前集合一次。
聊天、事件总线、日志、应用
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 = "")聊天的投递行为见下文「自定义消息与卡片」。
内容、网络与数据
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 与小程序
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? } }设备与系统
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)实验性组件:
@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() }后台与前台工作:
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): ForegroundServiceOptions屏幕与通知
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?)通知监听需要 permissions: ["notifications.listen"] 与 components.notificationListener。通知被停用时 notifyChecked 返回 null,notify 被静默忽略。没有显式动作时,点击通知会打开插件声明的第一个页面。
位置、联系人、短信、日历
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()): PluginCalendarEventDraft语音、网页、凭据、无障碍
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() 暴露用户真实的服务凭据与 MCP 凭据。只在执行用户请求时读取,绝不持久化、记录日志或转发。
UI 服务
UiService 负责宿主风格的交互与导航。完整行为与选择器模型见 UI 扩展。
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 承载插件面向全部会话或某个会话的工具与钩子。
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) 每个会话物化一次。在这里返回的钩子会覆盖插件的全局钩子。若返回的 Contributions 保留默认的 PluginHooks.None,宿主会回落到插件的全局钩子——因此新增会话工具不会静默禁用全局钩子。
工具
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| 成员 | 行为 |
|---|---|
name | 全局工具名,^[a-z][a-z0-9_]*$;不能与宿主保留名或其他插件冲突 |
label | 工具卡片标题 |
description | 原样传给模型的工具说明 |
parameters | 原样传给模型的 JSON Schema |
promptSnippet | 出现在系统提示词中的一行摘要 |
promptGuidelines | 给模型的使用规则 |
exposure | DIRECT(常驻,默认)或 DEFERRED(通过 tool_search 发现、通过 tool_execute 执行) |
execute | 挂起处理函数;异常会转成错误结果 |
PluginToolCall:
callId—— 用于日志与卡片关联的调用 id。args—— 模型传入的参数。sessionId—— 当前会话 id;没有活动会话时为空字符串。signal—— 取消信号;在阶段边界调用throwIfCancelled(),或用onCancel { }注册清理。partial(result)—— 向实时工具卡片推送中间结果;execute的返回值是最终结果。
结果:
textResult是给模型的纯文本;details是宿主侧元数据,供卡片使用,不进入模型上下文。richResult接受textBlock、imageBlock(图片会进入模型图片内容)与fileRefBlock(给模型增加一行文件信息,并在 UI 中显示文件行)。isError = true标记失败结果;业务错误请用它,不要抛异常。
技能与提示词段落
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): PromptSection技能 markdown 必须是完整的 SKILL.md,带 YAML frontmatter(name、description);PluginSkill.id 必须与 frontmatter 中的 name 一致。files 路径是技能目录内的相对路径,content 与 assetPath 互斥(assetPath 是包内的 assets/<path>)。技能 id 为 ^[a-z][a-z0-9_-]*$;插件必须处于启用状态(不报告不可用)才会出现。提示词段落 id 在同一插件内必须唯一;段落按 priority 升序排列。
提示词覆盖
@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 }声明 prompt 能力并实现 PromptOverridePlugin,即可替换智能体前言/规则或追加段落。多个插件之间,前言与规则由 priority 最高者决定;段落按优先级升序拼接。单个插件上限 32 KiB,所有插件合计 64 KiB;超限的贡献会被跳过并记录日志。宿主生成的工作区与环境段落不可覆盖。
钩子
每个钩子都是带默认空实现的 suspend 函数;只实现需要的部分,并从 contributions()(全局)或 contributionsFor()(会话级)返回。
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
}
}会话观察事件(21 个)按顺序串行派发,每个处理函数 5 秒超时;错误与超时会记录日志并继续派发:
| 回调 | 事件字段 |
|---|---|
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 |
系统事件(6 个)只派发给全局钩子,并需要对应门控:
| 回调 | 事件字段 | 门控 |
|---|---|---|
notificationReceived | notification、removed | notifications + components.notificationListener |
notificationAction | notificationId、actionId、payload | notifications |
backgroundTask | taskId、kind、firedAtMs | background + components.background 或 components.foregroundService |
shareReceived | text?、streams、title? | share + components.share |
deepLinkReceived | path、arguments | deeplink + components.deeplinks |
appLifecycle | foreground | app |
转换与拦截按插件注册顺序链式执行,每个处理函数 2 秒超时:
| 方法 | 输入 → 输出 | 失败策略 |
|---|---|---|
promptTransform | PromptRequest(sessionId, prompt) → 改写后的提示词 | fail-open:保留上一个值 |
context | PluginContextRequest(sessionId, cwd, providerId?, modelId?) → 注入系统提示词的文本 | fail-open:跳过;单插件 8 KiB,合计 32 KiB |
inputTransform | InputRequest(sessionId, text, imagePaths) → 通过 inputContinue(text, imagePaths) 或 inputHandled() 返回 InputDecision | fail-open:保留当前输入 |
beforeToolCall | ToolCallRequest(sessionId, callId, toolName, args) → toolContinue()、toolBlock(reason) 或 toolRewrite(args) | fail-closed:超时或异常会阻止调用 |
afterToolExecution | ToolExecutionResult(sessionId, callId, toolName, result) → resultKeep() 或 resultReplace(result) | 保留上一个结果 |
这些回调位于会话关键路径上,必须快速返回。不要在其中做网络或重 IO,也不要等待用户输入。取消必须向上传播:绝不吞掉 CancellationException。
宿主在运行开始时冻结钩子集合;运行期间启用或停用的插件从下一次运行开始生效。运行中途被停用的插件仍可能收到剩余事件,因此回调必须能容忍状态变化;资源清理放在 close() 或 onDisable()。
自定义消息与卡片
chat() 向会话写入消息,并可附带可渲染的卡片:
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",
),
),
)| 选项 | 行为 |
|---|---|
triggerTurn = true(默认) | 以 text 作为用户消息开启新一轮。会话忙碌时由 deliverAs 决定:STEER 打断,FOLLOW_UP 排队 |
triggerTurn = false | 只写入卡片消息,不开启新一轮 |
display | 先写入卡片(等价于 postCustomMessage),再开启新一轮 |
| 未知会话 | 抛出 IllegalArgumentException |
| 结果 | ChatSendResult.kind 为 STARTED、QUEUED 或 DISPLAYED |
用 customType 写入的卡片通过 chat.message:<customType> 插槽渲染,重新打开会话后也能恢复。
工具结果卡片
plugin-api 为插件工具支持三层工具结果。把这些键写入 details:
| 键 | 内容 |
|---|---|
sora.raw | 完整的上游输出,原样保留;追加到模型文本的「完整返回」段 |
sora.guidance | 给模型的简短下一步指引;追加到「用法」段 |
sora.card | { "customType": ..., "title": ..., "payload": ... };宿主会在模型文本中生成 present(...) 指令,并给卡片一个显示标题 |
sora.display | 由宿主写入;工具卡片的显示标题 |
这些常量位于 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(...) 会自动应用 Cards.deliver。如果自行实现 PluginTool,请在返回前调用一次 Cards.deliver(call.callId, result)。错误结果会丢弃卡片与 present 指令,只保留正文、完整返回与用法说明。不要自己写 present(...) 指令,也不要把卡片 id 放进 payload——payload 必须保持完整,卡片才能渲染。
文本、图标与插槽状态
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) 要求包含 default 键。assetIcon(path) 期望 asset:<包内路径>。插槽状态在 Compose 插槽内容中使用;见 UI 扩展。
能力与服务映射
每项能力、对应访问器(如有)以及服务返回的主要模型。未在清单中声明的服务不会被注入。
| 能力 | 访问器 | 主要类型 |
|---|---|---|
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 |
实验性 API
以下声明带 @PluginExperimentalApi(@RequiresOptIn,级别 WARNING):components()、credentials()、accessibility()、PromptOverridePlugin 及其使用的类型。在使用处或文件级显式选择加入:
@OptIn(PluginExperimentalApi::class)实验性声明在稳定前可能变化;转为稳定时只会移除注解。SDK 中的其他部分都遵循 API 级别兼容承诺。
限制
- 插件 id、版本、清单字段与包内容在安装时校验;非法包会以具体错误码拒绝。
- 插件不能在 Android 清单中注册 Activity、Service、Receiver 或权限;请使用宿主代理:
components()打开专用窗口与动态接收器,background()前台服务,components.notificationListener/accessibility/share/deeplinks接收系统事件。 - 没有资源:
res/与R不可用;使用 assets 与清单字段。 - 没有声明式 UI 节点:UI 是通过插槽、渲染器与页面实现的 Compose。
- 原生库不会被类加载器加载。
- 没有进程隔离:主线程、Compose 插槽或工具调用中的异常可能让应用退出。
- 不能提权:Root/ADB 命令只在用户选择的层级内运行。
- 已知缺口:
notifications().notify没有回执(需要回执用notifyChecked);requestContributionsRefresh()不返回句柄;jobs()没有list()。
