Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
220 changes: 148 additions & 72 deletions PUBLICATION_MANIFEST.json

Large diffs are not rendered by default.

8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,16 @@ Availability depends on Android permissions, peer scopes, device roles, installe
| `protocol/schemas/` | JSON Schema contracts and synthetic examples |
| `skills/` | Agent workflow recipes |
| `docs/` | Selected public documentation and review evidence |
| `licenses/` | License texts for bundled third-party components |
| `.github/workflows/` | CI for the offline Go, Python and Android checks |

`PUBLICATION_MANIFEST.json` records SHA-256 hashes of the published file set (see [publishing](docs/publishing.md)).

## Offline checks

```sh
python -m pip install -r tools/requirements.txt
python tools/publication.py check
python tools/test_inbound.py
python tools/test_converse_sim.py
python -m unittest discover -s tools -p 'test_*.py'
Expand All @@ -58,7 +64,7 @@ go test ./...
go vet ./...
```

The conversation simulation uses real timing and takes several minutes. See [development](docs/development.md) for Android checks. `dry_call.py` and `judgement_eval.py` contact model services; device verification and SMS mesh scripts contact real phones. They are not offline tests.
CI runs the same checks, with `go test -race ./...` (needs CGo) and an Android job running `bash gradlew testDebugUnitTest lintDebug assembleDebug`. The conversation simulation uses real timing and takes several minutes. See [development](docs/development.md) for Android checks. `dry_call.py` and `judgement_eval.py` contact model services; device verification and SMS mesh scripts contact real phones. They are not offline tests.

## Publishing and contributing

Expand Down
2 changes: 1 addition & 1 deletion android-runtime/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ dependencies {

// Capability substrate (Apache-2.0). Consumed behind CapabilityAdapter.
// io.ktor is excluded from every droid-mcp artifact: droid-mcp-core pulls Ktor Netty at runtime scope
// and we never start its HttpTransport. Our own Ktor CIO deps above satisfy droid-mcp-core's compile refs.
// and we never start its HttpTransport. Our own Ktor Netty deps above satisfy droid-mcp-core's compile refs.
listOf(
"droid-mcp-core", "droid-mcp-sms", "droid-mcp-telephony", "droid-mcp-calllog", "droid-mcp-contacts",
"droid-mcp-device", "droid-mcp-network", "droid-mcp-apps", "droid-mcp-intent", "droid-mcp-location",
Expand Down
11 changes: 7 additions & 4 deletions android-runtime/app/src/debug/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@
xmlns:tools="http://schemas.android.com/tools">
<!-- The call-audio permissions moved to the main manifest (conversation mode ships in release). -->
<application>
<!-- Debug only: exported so `adb shell am broadcast` can drive approvals and pairing on an emulator. -->
<!-- Debug only: exported so `adb shell am broadcast` can drive approvals and pairing on an emulator.
android.permission.DUMP limits senders to the adb shell (and the system): an installed app cannot hold
it, so it cannot approve actions, release emergency stop, reset rate counters, allowlist a number or
enable LAN through these. Our own notification PendingIntents still arrive (same-app senders pass). -->
<receiver
android:name=".policy.ApprovalReceiver"
android:exported="true"
tools:replace="android:exported"
tools:ignore="ExportedReceiver" />
android:permission="android.permission.DUMP"
tools:replace="android:exported" />
<receiver
android:name=".core.DebugReceiver"
android:exported="true"
tools:ignore="ExportedReceiver" />
android:permission="android.permission.DUMP" />
</application>
</manifest>
5 changes: 4 additions & 1 deletion android-runtime/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@
<application
android:name=".RuntimeApp"
android:allowBackup="false"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
Expand Down Expand Up @@ -175,7 +177,8 @@
</intent-filter>
</receiver>

<!-- Debug builds re-declare this as exported (src/debug/AndroidManifest.xml) so adb can resolve approvals. -->
<!-- Not exported: only our own notification PendingIntents reach it. Debug builds re-declare it as exported
behind the DUMP permission (src/debug/AndroidManifest.xml) so adb, and no installed app, can resolve approvals. -->
<receiver
android:name=".policy.ApprovalReceiver"
android:exported="false" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
package dev.symbiosis.runtime

import android.app.Activity
import android.app.Application
import android.os.Bundle
import dev.symbiosis.runtime.capabilities.SelfProtection

class RuntimeApp : Application()
class RuntimeApp : Application() {
override fun onCreate() {
super.onCreate()
// Counts our started activities so screen control is refused while any of them is visible (SelfProtection).
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
override fun onActivityStarted(activity: Activity) { SelfProtection.startedActivities.incrementAndGet() }
override fun onActivityStopped(activity: Activity) { SelfProtection.startedActivities.updateAndGet { (it - 1).coerceAtLeast(0) } }
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
override fun onActivityResumed(activity: Activity) {}
override fun onActivityPaused(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
override fun onActivityDestroyed(activity: Activity) {}
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ fun interface AlarmSink { fun arm(atMs: Long?) }
*
* For each event, per workflow, in this order:
* 1. **Topic and scope.** The trigger's topic glob must match, and the owner's *current* principal must exist and be
* allowed to see the topic. Failing either is silent (no log line): a logged skip would tell the owner, one bit
* allowed to see the event (its topic, and for an event naming a `session_id`, that session must be the
* owner's: Principal.canSeeEvent). Failing either is silent (no log line): a logged skip would tell the owner, one bit
* at a time, which events on topics they cannot see matched their `where`.
* 2. **Loop guard (global).** Every run gets its own correlation id, carried by every step and by every event a
* step causes *that carries a correlation id at all*. An event whose correlation id belongs to ANY recent
Expand All @@ -62,6 +63,8 @@ fun interface AlarmSink { fun arm(atMs: Long?) }
* same for every workflow.
*
* @param principalFor the owner's CURRENT principal (null if revoked/expired).
* @param sessionOwner the peer owning a session named in an event payload (SessionManager.ownerOf). The default
* resolves nothing, so session events then trigger only the admin's workflows.
* @param gate false while the runtime is switched off in the app: triggers are ignored and due schedules are
* skipped to their next occurrence (`skipped:runtime_off`).
*/
Expand All @@ -76,6 +79,7 @@ class WorkflowEngine(
private val audit: (peerId: String?, corr: String, args: JsonObject, result: JsonObject?, ok: Boolean?) -> Unit = { _, _, _, _, _ -> },
private val gate: () -> Boolean = { true },
private val clock: () -> Long = Ids::now,
private val sessionOwner: (String) -> String? = { null },
) {
/** What a trigger came to. [Run] carries the job so callers (and tests) can await it. */
sealed class Decision {
Expand Down Expand Up @@ -135,7 +139,7 @@ class WorkflowEngine(
if (!TopicGlob.matches(t.topic, ev.topic)) continue
// Scope before anything observable: silent, and before where/cooldown/slot so nothing leaks or is consumed.
val owner = owners.getOrPut(wf.owner) { principalFor(wf.owner) } ?: continue
if (!owner.canSeeTopic(ev.topic)) continue
if (!owner.canSeeEvent(ev, sessionOwner)) continue
if (guarded) { out += skip(wf, "event:${ev.topic}", "loop_guard", ev, detail = "event caused by workflow run ${ev.correlation_id}"); continue }
val matched = try { t.where == null || Matcher.where(t.where, ev.payload) } catch (e: RegexTimeout) {
out += skip(wf, "event:${ev.topic}", "regex_timeout", ev, detail = e.message); continue
Expand Down Expand Up @@ -265,7 +269,7 @@ class WorkflowEngine(
// Re-read: the workflow may have been disabled, edited or deleted while this run waited.
val fresh = store.getById(wf.id)?.takeIf { it.enabled } ?: return@launch
val owner = principalFor(fresh.owner) ?: return@launch
if (p.second != null && !owner.canSeeTopic(p.second!!.topic)) return@launch
if (p.second != null && !owner.canSeeEvent(p.second!!, sessionOwner)) return@launch
fire(fresh, p.first, p.second)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ object CallAudioPlay {
Param("session_id", "string", "The call session (from telephony.place_call)", required = true),
Param("audio_base64", "string", "Base64-encoded WAV file, or raw 16-bit little-endian PCM", required = true),
Param("format", "string", "wav (default) or pcm", enum = listOf("wav", "pcm")),
Param("sample_rate", "integer", "Sample rate of raw PCM (ignored for wav, which carries its own)"),
Param("sample_rate", "integer", "Sample rate of raw PCM, 8000..48000 (default 16000; ignored for wav, which carries its own)"),
Param("gain", "number", "0..1 output level (default 1.0)"),
),
actionClass = ActionClass.COMMUNICATION, tier = 1,
Expand All @@ -46,7 +46,14 @@ object CallAudioPlay {
val b64 = args["audio_base64"]?.toString()?.takeIf { it.isNotBlank() }
?: return@Capability CapabilityResult.fail("invalid_params", "audio_base64 is required")
val format = (args["format"]?.toString() ?: "wav").lowercase()
val srcRate = (args["sample_rate"] as? Number)?.toInt() ?: TelephonyAudio.RATE
// Bounded: sample_rate 1 asked the resampler for 16 000 times the input (a multi-GB allocation), and a few
// hundred Hz meant hours of uplink audio.
val rawRate = args["sample_rate"]
val srcRate = when (rawRate) {
null -> TelephonyAudio.RATE
is Number -> rawRate.toDouble().takeIf { it == Math.floor(it) && it.toLong() in Wav.RATES.first..Wav.RATES.last }?.toInt()
else -> null
} ?: return@Capability CapabilityResult.fail("invalid_params", "sample_rate must be an integer between ${Wav.RATES.first} and ${Wav.RATES.last}")
val gain = ((args["gain"] as? Number)?.toDouble() ?: 1.0).coerceIn(0.0, 1.0)
if (!TelephonyAudio.hasPermission(context)) {
return@Capability CapabilityResult.fail("capability.unavailable", "MODIFY_AUDIO_ROUTING not granted")
Expand All @@ -62,6 +69,9 @@ object CallAudioPlay {
val pcm: ShortArray
val sourceRate: Int
if (format == "pcm") {
if (bytes.size / 2 > Wav.MAX_SECONDS.toLong() * srcRate) {
return@withContext CapabilityResult.fail("invalid_params", "audio longer than ${Wav.MAX_SECONDS} s")
}
val mono = ShortArray(bytes.size / 2)
for (i in mono.indices) {
mono[i] = ((bytes[i * 2].toInt() and 0xff) or (bytes[i * 2 + 1].toInt() shl 8)).toShort()
Expand All @@ -74,7 +84,7 @@ object CallAudioPlay {
try {
tmp.writeBytes(bytes)
val decoded = Wav.decodeMono16(tmp, TelephonyAudio.RATE)
?: return@withContext CapabilityResult.fail("invalid_params", "could not decode WAV (need 16-bit PCM)")
?: return@withContext CapabilityResult.fail("invalid_params", "could not decode WAV (need 16-bit PCM at ${Wav.RATES.first}..${Wav.RATES.last} Hz, at most ${Wav.MAX_SECONDS} s)")
pcm = decoded.pcm
sourceRate = decoded.sourceRate
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ class Capability(
val version: String = "0.1",
/** Argument key that names a contact/number target, checked against allow/deny lists. */
val targetArg: String? = null,
/**
* For a tool whose target is not an argument (notifications.reply names a notification key): the identities the
* call reaches (sender name, number), resolved from the args. An empty list means the target is unknown.
* Checked against the contact lists in place of [targetArg]; see PolicyEngine.evaluate.
*/
val targetResolver: ((Map<String, Any?>) -> List<String>)? = null,
val execute: suspend (args: Map<String, Any?>, ctx: CallContext) -> CapabilityResult,
) {
fun inputSchema(): JsonObject = kotlinx.serialization.json.buildJsonObject {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package dev.symbiosis.runtime.capabilities

import dev.symbiosis.runtime.events.Event
import dev.symbiosis.runtime.events.sessionIdOrNull
import dev.symbiosis.runtime.policy.ActionClass
import java.util.concurrent.ConcurrentHashMap

Expand Down Expand Up @@ -88,6 +90,22 @@ data class Principal(
fun canSeeTopic(topic: String): Boolean = isAdmin ||
(hasScope(Scopes.requiredScopeForTopic(topic)) && Scopes.requiredActionClassForTopic(topic) <= maxActionClass)

/**
* [canSeeTopic] plus session ownership. The one check every event delivery path uses: WebSocket push, replay (WS
* and events.replay), events.wait, workflow triggers and phone://events/recent. An event whose payload names a
* `session_id` (call.transcript, call.listening, session.state, a call's connected/ended...) belongs to that
* session: only its owning peer or the admin sees it, the rule /ws/sessions/{id} and telephony.get_session
* already enforce. A topic scope alone used to be enough, so any peer holding telephony.* could subscribe to
* call.* and read the live transcript of another peer's call. [sessionOwner] maps a session id to its owning
* peer; null (an unknown id, or a session with no owner) makes the event admin-only.
*/
fun canSeeEvent(ev: Event, sessionOwner: (String) -> String?): Boolean {
if (!canSeeTopic(ev.topic)) return false
if (isAdmin) return true
val sid = ev.sessionIdOrNull() ?: return true
return sessionOwner(sid) == peerId
}

/** Every namespace and data class reachable through [glob] must be authorized. */
fun canSubscribe(glob: String): Boolean = isAdmin ||
(Scopes.requiredActionClassForTopicGlob(glob) <= maxActionClass &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ object DroidMcpAdapter {
val permissions: List<String> = emptyList(),
val targetArg: String? = null,
val emits: List<String> = emptyList(),
/** See [Capability.targetResolver]: for tools whose target is not an argument. */
val targetResolver: ((Map<String, Any?>) -> List<String>)? = null,
)

private const val P_SMS_READ = "android.permission.READ_SMS"
Expand Down Expand Up @@ -66,7 +68,11 @@ object DroidMcpAdapter {
Meta("location.get_address", ActionClass.SENSITIVE_READ, permissions = listOf(P_LOC)) to "get_location_address",
// notifications (listener-backed)
Meta("notifications.list", ActionClass.SENSITIVE_READ, tier = 2) to "list_repliable_notifications",
Meta("notifications.reply", ActionClass.COMMUNICATION, tier = 2, rateClass = RateClass.SMS) to "reply_to_notification",
// EXTERNAL_COMMITMENT like messaging.send_sms: it sends a real message, so "Ask me first" and the contact lists
// apply. The lists see the notification's sender (notificationIdentities); a sender it cannot name is treated
// as not on the allowlist. Standard peers keep it: their ceiling is EXTERNAL_COMMITMENT.
Meta("notifications.reply", ActionClass.EXTERNAL_COMMITMENT, tier = 2, rateClass = RateClass.SMS,
targetResolver = { args -> notificationIdentities(args["key"]?.toString()) }) to "reply_to_notification",
Meta("notifications.dismiss", ActionClass.LOW_RISK, tier = 2) to "dismiss_notification",
Meta("notifications.invoke_action", ActionClass.DEVICE_MUTATION, tier = 2, rateClass = RateClass.MUTATION) to "invoke_notification_action",
// ui (accessibility-backed; passthrough, disabled by scope until a device has the service on)
Expand All @@ -80,7 +86,7 @@ object DroidMcpAdapter {
Meta("ui.press_global", ActionClass.DEVICE_MUTATION, tier = 2, rateClass = RateClass.MUTATION) to "global_action",
// Mapped 2026-09-26 from droid-mcp 0.10.1's AccessibilityTools (names and params read from the AAR's classes).
// Same class, tier and rate class as ui.tap_element on purpose: each is one screen action, so each counts one
// MUTATION slot like a tap. They do not widen docs/security.md §2.3a's accepted gap (screen control as a way
// MUTATION slot like a tap. They do not widen the accepted gap in docs/security.md#limits (screen control as a way
// round the text/call brakes): a long-press, scroll or find-and-tap reaches nothing a tap_element sequence
// could not already reach, at the same per-action cost. (lock_screen needs no mapping: it is already one of
// ui.press_global's actions.)
Expand Down Expand Up @@ -116,6 +122,7 @@ object DroidMcpAdapter {
readOnly = tool.annotations.readOnlyHint || meta.actionClass <= ActionClass.SENSITIVE_READ,
idempotent = tool.annotations.idempotentHint,
targetArg = meta.targetArg,
targetResolver = meta.targetResolver,
execute = { args, _ ->
val missing = meta.permissions.filter { context.checkSelfPermission(it) != android.content.pm.PackageManager.PERMISSION_GRANTED }
if (missing.isNotEmpty()) CapabilityResult.missingPermission(*missing.toTypedArray())
Expand All @@ -134,6 +141,27 @@ object DroidMcpAdapter {
)
}

/**
* Who a reply to notification [key] reaches, for the contact lists: the conversation title, the title (the
* sender's name, or their number when it is not a contact), and each other sender in a MessagingStyle thread by
* name and by number (a `tel:`/`sms:` person URI). Empty when the notification is unknown or names nobody.
*/
internal fun notificationIdentities(key: String?): List<String> {
if (key.isNullOrBlank()) return emptyList()
val n = io.droidmcp.notification.NotificationStore.findByKey(key)?.notification ?: return emptyList()
val out = linkedSetOf<String>()
n.extras?.getCharSequence(android.app.Notification.EXTRA_CONVERSATION_TITLE)?.toString()?.let(out::add)
n.extras?.getCharSequence(android.app.Notification.EXTRA_TITLE)?.toString()?.let(out::add)
runCatching { androidx.core.app.NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(n) }.getOrNull()?.let { style ->
// A message with no person is the device user's own; it names nobody the reply reaches.
for (p in style.messages.mapNotNull { it.person }) {
p.name?.toString()?.let(out::add)
p.uri?.let { u -> Regex("^(tel|sms|smsto):", RegexOption.IGNORE_CASE).find(u)?.let { out.add(u.substring(it.range.last + 1)) } }
}
}
return out.map { it.trim() }.filter { it.isNotEmpty() }.distinct()
}

/** droid-mcp reads loosely typed values but some tools cast; coerce JSON numbers to the declared type. */
private fun coerce(tool: McpTool, args: Map<String, Any?>): Map<String, Any> {
val types = tool.parameters.associate { it.name to it.type }
Expand Down
Loading
Loading