diff --git a/PUBLICATION_MANIFEST.json b/PUBLICATION_MANIFEST.json
index ac885f4..1ccf29c 100644
--- a/PUBLICATION_MANIFEST.json
+++ b/PUBLICATION_MANIFEST.json
@@ -21,7 +21,7 @@
},
{
"path": "README.md",
- "sha256": "5dd348ccc70cdd1fdc35801c94d3d65ebe2a83b60b5a322f94a2f59ce7129612"
+ "sha256": "49a7a471e426eb47110fa7b3a6a7c50956df0c2c5f79311e5947e00a0beca09b"
},
{
"path": "SECURITY.md",
@@ -37,7 +37,7 @@
},
{
"path": "android-runtime/app/build.gradle.kts",
- "sha256": "b14f9e5a978c45fb4abdf7bea2e0fc27bbdd03c24548cb1470e267c2832d7c8a"
+ "sha256": "7fb19ed5e17132d9f097c267f604cf3c24fc502c3e8289b1ea59e7bb8b485a44"
},
{
"path": "android-runtime/app/proguard-rules.pro",
@@ -45,11 +45,11 @@
},
{
"path": "android-runtime/app/src/debug/AndroidManifest.xml",
- "sha256": "a661a70394cd1eea73f06de43a01cb31c1783cb9df7e522143002c107e0997d1"
+ "sha256": "5c0f2c90f81bb32872f2941105f154388654df3b78f737ec35ab728a1eea7bec"
},
{
"path": "android-runtime/app/src/main/AndroidManifest.xml",
- "sha256": "9bc3851c056776d841aeb847a9b0bac2b1b4851466918f8d4550253df3692842"
+ "sha256": "375af9dd2b6e708f86da058af63e66d0d8fcf5d09265b50baef6a0154b0a21e5"
},
{
"path": "android-runtime/app/src/main/assets/smart-turn-v3.2-cpu.onnx",
@@ -65,7 +65,7 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/RuntimeApp.kt",
- "sha256": "ea9ae4a0f95f687b84c66349cb540a763fe5f730373e86e2069fcfde086622b6"
+ "sha256": "9072f7b72aef1327db440b0a62ea9e3bc45dec88735d7c520936383cd1086067"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/audit/AuditStore.kt",
@@ -105,7 +105,7 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/automation/WorkflowEngine.kt",
- "sha256": "f2a9b09e5666c189869c08eef8c6e7a9f8812d9f7a8e0f5e307313df7c0d8b24"
+ "sha256": "48cc357af0dbd749397b423f9759dad2cd81cd265167a086ca63c6c304e0fb4a"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/automation/WorkflowStore.kt",
@@ -125,7 +125,7 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/CallAudioPlay.kt",
- "sha256": "b137b0322e50e831b52a84734b35ac7de1a51bd1da0e17a835014d8488d131cd"
+ "sha256": "dfd26228fbb806bddfee6dbca940284f27aba1e09150bb6f578f4af2abc7edcf"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/CallSpeech.kt",
@@ -137,11 +137,11 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/Capability.kt",
- "sha256": "b61358271edde4b5f2b0fd1bf0ea767e4a78a527ff19051016686ef9876734f3"
+ "sha256": "1dafe5550c59bd5bd29a5c075bc297cb8656a78f4cf08c5622a8ca92268e5eae"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/CapabilityRegistry.kt",
- "sha256": "0ea798a2fecba7fcd66aadc46dc082673fc57ed048a0c1dd94875243e6941585"
+ "sha256": "72ab72c0e81e67624d6be1a8adc345b873d61db5c0bb9fd89e1eff391b4715cb"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/Clipboard.kt",
@@ -157,16 +157,20 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/DroidMcpAdapter.kt",
- "sha256": "1a4d0679c63e3fea1bf91dcdb384afc27f9948c0dd28dee6deb6d6c7090149de"
+ "sha256": "71eac7e9a72d3235fd1c6776c987323ae4059ead8af8ea8afd33c3407106ef48"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/NativeCapabilities.kt",
- "sha256": "5ef67d886f37f22e4353051fdd995d2fa9c0240c95397d1b859b194acbf542be"
+ "sha256": "064febfc3e830d98395bc230d0122cd6d92562f5ccc68d5dea0a55e6afa7a0fa"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/Notify.kt",
"sha256": "e62782d9b221315c1e096fbf2f2784db30c467a231c58fb61aeea9f2a59039e2"
},
+ {
+ "path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/SelfProtection.kt",
+ "sha256": "5236aac338fcecf6d9140ab700383df92f6c5b8f0cb1195551f48574c32c93dc"
+ },
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/SessionAccess.kt",
"sha256": "bdace4cbe2ac2b9998190d597f325604d0f5e73c439a648cb110e83c59870007"
@@ -177,7 +181,7 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/UiGestures.kt",
- "sha256": "0f275aebf6df3add4e45b83bba61ca04a76267a742ce352948716a0b1625cb01"
+ "sha256": "47ccdb274ea088a1a7ae7258d1828d43393e28594efe6ce222f423710c091019"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/core/BootReceiver.kt",
@@ -185,7 +189,7 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/core/DebugReceiver.kt",
- "sha256": "91a7dd3e2a15d15da316aa73bd4d805d1286478847c776878895cabac04718e1"
+ "sha256": "6bfd1f681df98bce842c47c6a649aa42a27a7c8f73d54a552abb53eda5fac748"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/core/Ids.kt",
@@ -197,7 +201,7 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/core/Runtime.kt",
- "sha256": "13118f5c5270ab97014f5df4daa90aad88f01aad8a32b647b28647bb32bcbf33"
+ "sha256": "c6936709d3d6820181240b2b2256bf8eb4543a595a2102d398160834649ea06d"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/core/RuntimeService.kt",
@@ -209,15 +213,15 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/Event.kt",
- "sha256": "67bd81cde78fa44582663120b5d628d8042bc28351c15f60f7b737eb8be8a70e"
+ "sha256": "9b01a691d6131287a1c54b4f1877ae58bce5f7e0365f98765ab4427d9b2820b2"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/EventBroker.kt",
- "sha256": "028eda14095a87f4b02f5d1fd3df82c18ca9f3ad50468cb10f6fef2e89d37356"
+ "sha256": "ff59f8194826c74e4eb64508d36336b1898f035d5779ec9b111f5601f6032a24"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/SubscriptionStore.kt",
- "sha256": "2ff0be0195ffc5ecc18aef2a9ac66ff96b2485c1d56d4b62eb04ab1f29efa187"
+ "sha256": "1c756ec9bcb724f202ede0172703613346af7b05eb777141678c947b50eff6b0"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/sources/CallStateSource.kt",
@@ -225,7 +229,7 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/sources/NotificationEventListener.kt",
- "sha256": "425a7a0e7851f1d3d7096048757429eb9ffbf22d9b6646c5c4759276fff2718a"
+ "sha256": "39e2cbf6175c44de6d77fb43f119bcebf14b58b78984e14ec022b2931ed4e624"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/sources/SmsReceiver.kt",
@@ -237,15 +241,19 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/ApprovalManager.kt",
- "sha256": "6c4fac12646ba40fa1dfe2d6619bb062a85ed7358caf9a686f6c253a8373da8b"
+ "sha256": "45c61b884970cc74a297391d8349d7fd428ccd9130a3dfa7a80b19601b4c36c5"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/ApprovalReceiver.kt",
- "sha256": "5326ab75c3ca22e0e0ad9aa480ef3bc9764b9e48a04e1b5357c0aa85580cdfda"
+ "sha256": "d8093df58c169c4f5a0b53bec4d20d77be1b8f104c0bb76e38eec9a2dac328a9"
+ },
+ {
+ "path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/ApprovalSummary.kt",
+ "sha256": "0d18fd00b2fa90e69a2da8bbecf4c3e1c76856bd18cfcc7318155b6c8f8740ff"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/PolicyEngine.kt",
- "sha256": "7c1e3758f3e42d46803af543a24dc7e36137a49f744e839272ed509fb09d34af"
+ "sha256": "bc120a2b01bea7e3514b5adc4beb2bf8b4411fb24e69b20c85661314cd9e2683"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/PolicyModel.kt",
@@ -257,11 +265,15 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/sessions/CallSession.kt",
- "sha256": "0f5adde4d47f9e887680d97dd52cb3f7b2ba40943f12747616f7116c6c636a9d"
+ "sha256": "34c377d177a77ba348f439887caaeda12924db56e6e41753db91d2d23a5f759f"
+ },
+ {
+ "path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/sessions/SessionFrameCursor.kt",
+ "sha256": "26d263718f9afe760a1dee88c3a5186a3eec6750c82338d9f63309dedb5c4ab6"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/sessions/SessionManager.kt",
- "sha256": "701ab091228f9f03c0fba11a22fda29b070cbef2cff6be8c7f41ebb2f45e28ba"
+ "sha256": "c6a0fd71d30ac893f5d9fe7960d12e04d49151677b5b04d1046959f6b42cad5a"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/storage/Db.kt",
@@ -269,7 +281,7 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/storage/SecureStore.kt",
- "sha256": "26f92b40cc46730f0d5cb1c5cd7b81d6d167129f6a6bd7a3ca6e24506f464d27"
+ "sha256": "f272178f4e644a9ab4deafdce0739de59396b1c2eb739d73d66fade0944885f0"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/CallConversation.kt",
@@ -289,7 +301,7 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/SymbiosisInCallService.kt",
- "sha256": "dcf66e4033c4e53494ba4ef9b032f708a464e0931f68ea5a7af9ac0dc06b8651"
+ "sha256": "51833dace2ba17a08f6b20797157cdcc5feda1651696b636c40cacfd583669fe"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/TelephonyAudio.kt",
@@ -297,11 +309,11 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/Tts.kt",
- "sha256": "0f0a2d51390fe4bb8ede7c8f27f1b6ef6a82831745a132da52b12f90e5629448"
+ "sha256": "1baeee4e910a245f234381771ef1c7ef3d060ad3709fccf2132fc96daf832e00"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/TurnDetector.kt",
- "sha256": "1f7aecea2abb8a9b6713c5d29d7358edc87dc506d6d6a3b24d683d74c52fdf7d"
+ "sha256": "b5909ad677d74fee2cca2ddae08a8e4908727b7c624fa2c3d43036fd0c4d398e"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/Vad.kt",
@@ -317,11 +329,11 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/transport/PeerStore.kt",
- "sha256": "c8982aba998e591a1de8e1d2d05dbae338969c8c9c0dd465ceb8d5056500564f"
+ "sha256": "a2ef6a0fb249055a1367266caf01cd25a03b3422f58044dc028f58c2d5ca1ce5"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/transport/Server.kt",
- "sha256": "5dcc640c370da67bc0dd24908583bbcef0405758dc044f4977fe866bec406616"
+ "sha256": "6b2f5acf8845f8b5b3b89afe613b99cdb4695548f89d9c363c6a94e70b8c6c2a"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/ui/DialActivity.kt",
@@ -333,7 +345,7 @@
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/ui/MainActivity.kt",
- "sha256": "0e028d30de86ccf9acce30c5ad9a75a6d2a5bc4fcc927070380daf53603e071d"
+ "sha256": "45e45a1c61e2de5dc1420b93a79169fd0d490d572c5aea95cfc6559e429d4ee1"
},
{
"path": "android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/ui/SymbiosisAccessibilityService.kt",
@@ -359,6 +371,14 @@
"path": "android-runtime/app/src/main/res/values/themes.xml",
"sha256": "5b926361b99415f010fb506b33c3d40fe9295a31a1e143cc82808dbb7fdb5dbb"
},
+ {
+ "path": "android-runtime/app/src/main/res/xml/backup_rules.xml",
+ "sha256": "fac12c4349aae802ce71668ebc6a8ea3e1fe513be7bf7859845dbb68307050cd"
+ },
+ {
+ "path": "android-runtime/app/src/main/res/xml/data_extraction_rules.xml",
+ "sha256": "293919259d83550c8426986697d9a4a1aa41a323c9047ad95f14d5245c59ebfe"
+ },
{
"path": "android-runtime/app/src/main/res/xml/network_security_config.xml",
"sha256": "95c969e33c85c533370a09551583da0e825aa9bc527fb5644f12150715e95ddb"
@@ -367,6 +387,10 @@
"path": "android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/AutomationTest.kt",
"sha256": "f5f1f26b9d05d055aaa30a8906f419dd8ad974e48e1588b5568d16676c7d6784"
},
+ {
+ "path": "android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/CallSessionGateTest.kt",
+ "sha256": "f8105da00b7c0a832dca3a080b39e39896a25a763722336c9cd694a1b0fa9084"
+ },
{
"path": "android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/ConversationAudioTest.kt",
"sha256": "f685826ef4f161b3a785593983e0535f67a70dc2a37294e6bf283a857f2c4114"
@@ -399,6 +423,18 @@
"path": "android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/ScopeGatingTest.kt",
"sha256": "4220dfd8a90be8a36660a7e2586bebe565b3b68b7b61602e0671cfa84495672d"
},
+ {
+ "path": "android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/SelfProtectionTest.kt",
+ "sha256": "eb15e27194e4d62bf15e2a686ad663e7d835b28ba4a0933b91f30a5b771d5d9e"
+ },
+ {
+ "path": "android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/SessionEventAccessTest.kt",
+ "sha256": "9f5caad102bc5b6dab234ec62ff8106310bf686f6b7849680ca7a1881ed95f5b"
+ },
+ {
+ "path": "android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/SessionFrameCursorTest.kt",
+ "sha256": "e9c6f0391d0d0dd3b1e0c303a8741116b82116f63eeb8e75aca3f1d2fd81cb6a"
+ },
{
"path": "android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/StatefulPathsTest.kt",
"sha256": "d9e0ff305955c0654e8acfbd87379759a518b23f60cf09419e17d496881fce4e"
@@ -407,17 +443,21 @@
"path": "android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/TopicAuthorityReviewTest.kt",
"sha256": "fa7ff7e872179ee7ef8380c914a529501bdc6be8dd47f543e70436dc02bdd8e5"
},
+ {
+ "path": "android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/WavParserTest.kt",
+ "sha256": "b1e07e980affea55930de74a9240b0ea085bbafa67d4cbb5df828c381c28feb4"
+ },
{
"path": "android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/WorkflowTest.kt",
"sha256": "2a092b2f620afb0335b05b2de3f9058b961b636d5541a0a53f8a1ea5bda43bc3"
},
{
"path": "android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/telephony/TurnDetectorTest.kt",
- "sha256": "6e55f11c30d4b8cf2590506d25c93af6ff90e35f4d3aa8743bea344725aae4f8"
+ "sha256": "fe025d01899dafa403b97665a671eb3b4bb652a0ba5199707d75df82b08cd808"
},
{
"path": "android-runtime/app/src/test/resources/README.md",
- "sha256": "acc6fdf14ab081210c24e842f4de60927a48220b545f799dcf622568523503f3"
+ "sha256": "b5c87ed8daea428850ddbc62759144a90134a56920872d096ed302982754964e"
},
{
"path": "android-runtime/app/src/test/resources/smartturn_golden.f32",
@@ -465,19 +505,19 @@
},
{
"path": "docs/architecture.md",
- "sha256": "5e7ee0264a4462576b96721737a9bfc972ce7ec0cfcbb1c50c920922841134b9"
+ "sha256": "42b953dbb34a86415f5b9b73f361d523264f9873c18fa61ccf5da830b8cf8cb7"
},
{
"path": "docs/automation.md",
- "sha256": "a6758a1e757a42bb58fd5b9a2da8345712fb0bc3f52bbfa557aed9e52e8bfac2"
+ "sha256": "2498b21bfebd129ca200cb2ea8469eab2939a6f45a2e827a22097304731e143d"
},
{
"path": "docs/conversation-mode.md",
- "sha256": "6c8d0b020ce7d6430d81b6d475b8f4b895a9a728141010b0a0dd871a4fc69e67"
+ "sha256": "0f8feacc86eedee7fa69844fc81bb8c2e37f835849103ef9577a22f7818cd359"
},
{
"path": "docs/development.md",
- "sha256": "2df5c9d915263d8644bcc1f4e816dc168bbcb8f05e768afa52b13a3c11295556"
+ "sha256": "2877955222d525bc3a2f4df15121fbb01bcc8d3933614faed111897a2d38b000"
},
{
"path": "docs/disclaimer.md",
@@ -485,11 +525,11 @@
},
{
"path": "docs/inbound.md",
- "sha256": "034545f6d36d2a25e6bfed74cb23784d958537d3ce376a9b633994b7db478ed4"
+ "sha256": "492206978608edea9be90121c0c49aa882a3cbc13c264bd7edb477a02bb13908"
},
{
"path": "docs/protocol.md",
- "sha256": "f781ac4c98a86233e70b7aa23fbd0e0c2ec208e30840ad21c14111da530c8e3a"
+ "sha256": "0c866dc7bf8c638d2523c4bd7e0a2590c8c6095ac865cfb5a5d25e0fa5cc56fc"
},
{
"path": "docs/publishing.md",
@@ -497,11 +537,11 @@
},
{
"path": "docs/review.md",
- "sha256": "f40068d15eedc3831892aea27217ccb06fcf6c2f86f76ad7c0f31c6bb5e51e3c"
+ "sha256": "557d75aca3646653b98ee2f709bd16b5e0420545f895a03bee725296efa2e8f6"
},
{
"path": "docs/security.md",
- "sha256": "91b044ec99ae5541a9e916cff314051960c2bc8b1ef7fa6b1887e875162e3f76"
+ "sha256": "90e3f7589dcd9be3f6823f0494001944b5d0646252c7034d2e3408ae6426d27b"
},
{
"path": "gateway/.gitignore",
@@ -509,7 +549,7 @@
},
{
"path": "gateway/README.md",
- "sha256": "14845f7a0019a2266c0886e20146d774a201ae890e85c5ac174b10004b9b67b6"
+ "sha256": "983edf8a559db8f49a449211a969678fefa3ea693386145c65d06734e10bd73c"
},
{
"path": "gateway/cmd/gateway/main.go",
@@ -521,7 +561,7 @@
},
{
"path": "gateway/config.example.yaml",
- "sha256": "e9d94d508f5775da3cd5265e6dab124ab067542c6818b3018d2c2f146de7f49d"
+ "sha256": "de448077cd13d323821ec5fb13c99ee67e528822194ebffd2dfb61143302f215"
},
{
"path": "gateway/go.mod",
@@ -533,16 +573,20 @@
},
{
"path": "gateway/internal/agent/agent.go",
- "sha256": "f23d6af5daef7ef7b39e2cdef0a380f8deae6f5b0399a2a9731ddce68cb48e7b"
+ "sha256": "d6dbca9681e312bd426c95c5f8be35b2f1300981e733268ff05dee4cb2e3d2f0"
},
{
"path": "gateway/internal/agent/agent_test.go",
- "sha256": "78438dc51ea0d169f2a704b12dad9a36cca43cbf0cfe83e150c2c5abaa8194a9"
+ "sha256": "1214e7e4e2c25c8a96f59f3646cb7a33a7e55b897de07dd75676cd427466cc1a"
},
{
"path": "gateway/internal/agent/stopreason_test.go",
"sha256": "db099021c8cfe0dac25788a553b3377675da3db9c39755e35e59cbc7d8f56b74"
},
+ {
+ "path": "gateway/internal/agent/tool_failure_test.go",
+ "sha256": "585d5637a70660557873bf3ed7f7a17784bdb91b57e883952a32ad2d8471cb35"
+ },
{
"path": "gateway/internal/canonicaljson/canonicaljson.go",
"sha256": "4fd4e30ff371b8cea3bd8a5119c5b62bc10a5cb3cb72bfdb7297569b92a57e13"
@@ -567,29 +611,41 @@
"path": "gateway/internal/config/thinking_test.go",
"sha256": "6e17361a6649da9ea6eb350246923ea2e817420a3798363eb97af2022098e64e"
},
+ {
+ "path": "gateway/internal/device/call_error_test.go",
+ "sha256": "83bb7980474072c7b29126cf09b0711217d597e54b01df1dd85d3b9a83b0d56a"
+ },
{
"path": "gateway/internal/device/canonical.go",
"sha256": "cbde9dddbfbe2f8312f5544420bb40b871d8986a0005cf323e0d03763dc85afe"
},
{
"path": "gateway/internal/device/events.go",
- "sha256": "462a4c7741973ca3c9633ae5bc7bbe4d9aaea139c2c0d44c8a9561f49b419a3c"
+ "sha256": "60e26bbc57ac69ddd9bac044ed25432e1595c5387997cbfc8162db83c886df56"
},
{
"path": "gateway/internal/device/events_concurrency_test.go",
"sha256": "5c8874d3e099f08f2b8a417ae52360437906fa6e085852d8ad6509f83ff1a497"
},
+ {
+ "path": "gateway/internal/device/events_fresh_test.go",
+ "sha256": "958e514e0f6a7edb767412f517c9c1f8d7ef5e8ad6f1de12e619619ea4d08fd7"
+ },
{
"path": "gateway/internal/device/events_recovery_test.go",
"sha256": "79696bd2b1e1a9e469147b85429538b3aeb859020e3b2957b96e45b033b23199"
},
+ {
+ "path": "gateway/internal/device/events_replay_failure_test.go",
+ "sha256": "c5d5dce9c1c1fefd086226b8c631d209c161b19c1b3fa9e3aab09cbb66feeb89"
+ },
{
"path": "gateway/internal/device/events_test.go",
"sha256": "c8b51a915fcd09dbd6af6368a53edb54b7c3055c1d3524515c2f1da063778b9f"
},
{
"path": "gateway/internal/device/mcp.go",
- "sha256": "8e84ce6abcec6431009496c4876cadcad702b1928ef71bd3a1909e31151f6c12"
+ "sha256": "136201703bb1c4093e14a30f9112df29c336d06458053f664df69d3540efeb0a"
},
{
"path": "gateway/internal/device/mcp_singleflight_test.go",
@@ -605,7 +661,7 @@
},
{
"path": "gateway/internal/device/response_validation_test.go",
- "sha256": "0ef2052f8a5ea6bbfb435afa76da501e14c884be67e3d419b0bf09dd90ef9e6d"
+ "sha256": "a510612ebb994229f1e7da1fa4ae810f4b21676ea0ad855d3e32b2dafb84c4b8"
},
{
"path": "gateway/internal/device/subscribe_denied_test.go",
@@ -629,7 +685,7 @@
},
{
"path": "gateway/internal/fakephone/fakephone.go",
- "sha256": "53ab3707daa090dd81a56a202c26e20b0a9346abd7d7ceaa6dce88d71483e8f9"
+ "sha256": "2be798cd9c87277014d0109c1388fae1eb407093a9ee8ab93de4f63f009bbcb4"
},
{
"path": "gateway/internal/mcpserver/concurrency_test.go",
@@ -653,7 +709,7 @@
},
{
"path": "gateway/internal/mcpserver/server.go",
- "sha256": "9e13ac4a51d3129f2585d72e8d2eff1494d0599368acfa2cb09651d4bc603c4c"
+ "sha256": "263044937df27aa31b98550ff116544a34225ded413311c211e7f192a5433f7c"
},
{
"path": "gateway/internal/mcpserver/server_test.go",
@@ -663,9 +719,13 @@
"path": "gateway/internal/mcpserver/shutdown_test.go",
"sha256": "189b32a69ba122f0d68f90f9732a70f6c606ce430767787bb838b2704c146088"
},
+ {
+ "path": "gateway/internal/mcpserver/transport_outcome_test.go",
+ "sha256": "462707412e6e88bc19c0a6c447e79703c5208ef04b68f790a44600b0bf8f113f"
+ },
{
"path": "gateway/internal/provider/anthropic.go",
- "sha256": "38f35a8d6d392a38633a56619358e783f812186cfe28a286a99d6d7e446f61ad"
+ "sha256": "5af2a4b44335211d72b7d14e41e8dab4fd114757b43fb9e2784014636fb67ce6"
},
{
"path": "gateway/internal/provider/anthropic_test.go",
@@ -689,7 +749,7 @@
},
{
"path": "gateway/internal/provider/gemini.go",
- "sha256": "a6518e322616ce9cddffefff531bd57bb24edb0eb7e0c05cc0920afd5e5e6764"
+ "sha256": "1920dcc52b3af4e96a8a1cf68f4e073aebd7fa670f842dc6553d91fc72419614"
},
{
"path": "gateway/internal/provider/gemini_test.go",
@@ -701,7 +761,7 @@
},
{
"path": "gateway/internal/provider/openai.go",
- "sha256": "0a84ff878396e598959536c1e52b0d2e2128ff917e171332eb704bad9530bfee"
+ "sha256": "629f45edaa6c70dbe62e5bc678be8c39ffd37760cfa455b8c8d5f41bcd35b216"
},
{
"path": "gateway/internal/provider/openai_baseurl_test.go",
@@ -713,7 +773,11 @@
},
{
"path": "gateway/internal/provider/provider.go",
- "sha256": "be2445a400f9540b59b5a6b9bd0a1573d4059d28dcd774c39d2cebd4ffa1d301"
+ "sha256": "49b96e57d9bf3a19da78c239396563ceb52da3c48a66fefccc9a4bf748c8f44f"
+ },
+ {
+ "path": "gateway/internal/provider/replay_fidelity_test.go",
+ "sha256": "2900945d2033044019eb3326a99692a5de672ad1b2adc2b5fadd81145c7ca5c6"
},
{
"path": "gateway/internal/provider/retryafter_test.go",
@@ -739,13 +803,25 @@
"path": "gateway/internal/store/mkdir_test.go",
"sha256": "686a45a9a10f5dfe1e6e459c1062ece8690146983cc2903c880f3ce3049a96ab"
},
+ {
+ "path": "gateway/internal/store/perm_unix.go",
+ "sha256": "4abece2516be0f91705f52580f39173a09b616ea5c492ca82b9a3e83b892f33a"
+ },
+ {
+ "path": "gateway/internal/store/perm_unix_test.go",
+ "sha256": "17601be2744c9275979dc60c831e626039fbb1790d6aadfd7443451dd9eb0e5c"
+ },
+ {
+ "path": "gateway/internal/store/perm_windows.go",
+ "sha256": "20eb7ac261cbda8750618a21533c9fa436ff5f0025cbf4954e02a61e950381e0"
+ },
{
"path": "gateway/internal/store/store.go",
- "sha256": "9a9dccc85537f14c60ece0710524dff51973a134212d578ed487db8256cf77ef"
+ "sha256": "9be9637ae066927d289938c3427139789331762eb4b825621f0024caf8bbcc21"
},
{
"path": "gateway/internal/store/store_test.go",
- "sha256": "89e04eff6b918c204884d17b2526c468710a66814ed3845bbaa5055388efa511"
+ "sha256": "2c52d473c08408bb1859d219aad29a3111bc8f021f72594cd06075e9642b235a"
},
{
"path": "licenses/droid-mcp-Apache-2.0.txt",
@@ -757,11 +833,11 @@
},
{
"path": "protocol/schemas/README.md",
- "sha256": "b2f5416765fb0171c75f8ac0ce7d1873f9a89b5251faf82edd61ae9707e00ae2"
+ "sha256": "9cb4fe7d6fe48e39a02c57d745ca97cb9d96e606b8c06deca0727ddbf7557214"
},
{
"path": "protocol/schemas/audit-entry.json",
- "sha256": "e090b5e56335769eb66e662f60e9f417d80c0f67813ef63fcb19f823972122da"
+ "sha256": "d48146050dc3d662896ee241dab9153f0ba25f39264e5457e5390405d104ac0d"
},
{
"path": "protocol/schemas/capability-manifest.json",
@@ -769,7 +845,7 @@
},
{
"path": "protocol/schemas/event.json",
- "sha256": "4bf2f5b628e4dd9277781d31978b007d08a8c5adac12cf5028f8cd4a1a2705e4"
+ "sha256": "e3c0b5f69c86787fe6252ee4396bac80991b323fb399f187b6106e657b2c0e8c"
},
{
"path": "protocol/schemas/events-ws-frames.json",
@@ -777,11 +853,11 @@
},
{
"path": "protocol/schemas/pair-request.json",
- "sha256": "c8589f7dd3a346b52586ebb27666abbc3f49aa9665b4ba69d1822fa0ac41ffa4"
+ "sha256": "2a5bef13a7c2ce2f3974b466b6290ede126d51b845ddf3f32783010a69b8f23f"
},
{
"path": "protocol/schemas/pair-response.json",
- "sha256": "5a48b107316c59278578fd34f06fc28f5a77593a1da706c961b5ab27e6548103"
+ "sha256": "50617989d065bb800e192e84dc1d36bf3096567613f8e428451b8548a3a6d69b"
},
{
"path": "protocol/schemas/policy.json",
@@ -789,7 +865,7 @@
},
{
"path": "protocol/schemas/session-frames.json",
- "sha256": "e5eb95325d8ef24ed511ced0ba362c0a627194836d6755788d4904a480d15021"
+ "sha256": "23610b75639ccd9a9d28e995be760d95423744f58a8a4a47a541b25a2c62a95b"
},
{
"path": "protocol/schemas/subscription.json",
@@ -797,11 +873,11 @@
},
{
"path": "protocol/schemas/tool-call-result.json",
- "sha256": "72968ebee6db46bcbc73a27bd06851c916eebf762bd43d4877354ff39c670f6d"
+ "sha256": "8dd05c3026ff79a7ad2c724315ef5854a0edbe07fe669f0bb21675db651fb43b"
},
{
"path": "protocol/schemas/trusted-peer.json",
- "sha256": "2e56119804d16931611fa92fdb3aa8923bd6cfab85bd5f5af7caa30e782e25de"
+ "sha256": "62fb90c044fc2ea3703bcdafed2f4916961a57c820616599c1c1a5a6d4ea75c1"
},
{
"path": "skills/README.md",
@@ -821,11 +897,11 @@
},
{
"path": "tools/converse.py",
- "sha256": "e559d768043a2ba014de9bca7b16ff81d8860d075cd83ff959ee5b87cce74eb3"
+ "sha256": "cb5b504eeaf56adfd212dcdfd091c8a8171620251eb812563621372fd3e66d9b"
},
{
"path": "tools/dry_call.py",
- "sha256": "e65f6395d71245418386a3ca35dcdf5faebe7d74285114693c746ab786641293"
+ "sha256": "8d96203614279f4c42f2b6f5b463dfb87818198fcea69d74ec8e538cd84e4a0f"
},
{
"path": "tools/generate_turn_fixture.py",
@@ -833,15 +909,15 @@
},
{
"path": "tools/inbound.py",
- "sha256": "7cf92fc2dfa281824913387f2b9a0d0ac714b25468d013c66e6ea884ab80ffd5"
+ "sha256": "ecbe8bf06b19c6825bc96964d4d38117b9dcab253a5de0dd77de7bcab5983934"
},
{
"path": "tools/judgement_eval.py",
- "sha256": "b4023093a48bdfb8df89391a891d6577c43414c322cafe1ef36d1ffb7e66d019"
+ "sha256": "2d3a68ab58550f41ac5e622c53bee926664e2a205d467f348130391077f216d5"
},
{
"path": "tools/privapp/build_module.py",
- "sha256": "fa6ebe0ce889e334684b45155a3437ff66a70a2d29c4e404666afb9671c0b342"
+ "sha256": "2ffbc0a840a8a6758f3f95984f233db62cae831773d75a7e88431647be1f9f44"
},
{
"path": "tools/privapp/module.prop",
@@ -865,11 +941,11 @@
},
{
"path": "tools/test_converse_sim.py",
- "sha256": "a15fa6d13c060d5c9ef99c19966713c8a7d3a7af5d77702abfbb14f1e68b3345"
+ "sha256": "4e2a02c88de6718ba197fb77240ec4ca8424d9a7ac1c5e39cbeb4b36b705c151"
},
{
"path": "tools/test_inbound.py",
- "sha256": "3f9f72d46fd3f804c34628721cef1f24f28cacbc7138fd979fc54df5713a8d78"
+ "sha256": "ce048d9d904dda884b3c6345a8d580512c49efebb6cda8ef8e9d17183e520e0d"
},
{
"path": "tools/test_publication.py",
@@ -877,7 +953,7 @@
},
{
"path": "tools/test_python_safety.py",
- "sha256": "ee2df6080db75c60e429dab72bc375ddf688986f06c70d1bdf2f03aeb50a9a14"
+ "sha256": "9686532fea5dcba6cab51b9e25742fc8d6758d444078660a1f94e0050be5c2b1"
},
{
"path": "tools/turn-fixture-requirements.txt",
@@ -885,6 +961,6 @@
},
{
"path": "tools/verify_device.py",
- "sha256": "5f686fbfd809cda9d1d574e7d5b8f9c82df3781b855e9b4a0af9cabe14fe078b"
+ "sha256": "d60767f985b363fa452c95826d683851e85b2955161bd72f5d0c96fd40760426"
}
]
diff --git a/README.md b/README.md
index ad24de5..166bdc6 100644
--- a/README.md
+++ b/README.md
@@ -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'
@@ -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
diff --git a/android-runtime/app/build.gradle.kts b/android-runtime/app/build.gradle.kts
index 1bc9e70..d942919 100644
--- a/android-runtime/app/build.gradle.kts
+++ b/android-runtime/app/build.gradle.kts
@@ -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",
diff --git a/android-runtime/app/src/debug/AndroidManifest.xml b/android-runtime/app/src/debug/AndroidManifest.xml
index 275c7fe..beea83e 100644
--- a/android-runtime/app/src/debug/AndroidManifest.xml
+++ b/android-runtime/app/src/debug/AndroidManifest.xml
@@ -3,15 +3,18 @@
xmlns:tools="http://schemas.android.com/tools">
-
+
+ android:permission="android.permission.DUMP"
+ tools:replace="android:exported" />
+ android:permission="android.permission.DUMP" />
diff --git a/android-runtime/app/src/main/AndroidManifest.xml b/android-runtime/app/src/main/AndroidManifest.xml
index 055a8d0..195fd69 100644
--- a/android-runtime/app/src/main/AndroidManifest.xml
+++ b/android-runtime/app/src/main/AndroidManifest.xml
@@ -54,6 +54,8 @@
-
+
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/RuntimeApp.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/RuntimeApp.kt
index 0544674..24537f7 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/RuntimeApp.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/RuntimeApp.kt
@@ -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) {}
+ })
+ }
+}
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/automation/WorkflowEngine.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/automation/WorkflowEngine.kt
index 2c70ab9..9c82276 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/automation/WorkflowEngine.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/automation/WorkflowEngine.kt
@@ -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
@@ -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`).
*/
@@ -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 {
@@ -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
@@ -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)
}
}
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/CallAudioPlay.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/CallAudioPlay.kt
index a81c31e..22dea67 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/CallAudioPlay.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/CallAudioPlay.kt
@@ -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,
@@ -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")
@@ -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()
@@ -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 {
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/Capability.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/Capability.kt
index d9f45bf..f4b410e 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/Capability.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/Capability.kt
@@ -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) -> List)? = null,
val execute: suspend (args: Map, ctx: CallContext) -> CapabilityResult,
) {
fun inputSchema(): JsonObject = kotlinx.serialization.json.buildJsonObject {
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/CapabilityRegistry.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/CapabilityRegistry.kt
index f7722a2..1567547 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/CapabilityRegistry.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/CapabilityRegistry.kt
@@ -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
@@ -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 &&
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/DroidMcpAdapter.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/DroidMcpAdapter.kt
index 00c7fcb..b22a03e 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/DroidMcpAdapter.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/DroidMcpAdapter.kt
@@ -20,6 +20,8 @@ object DroidMcpAdapter {
val permissions: List = emptyList(),
val targetArg: String? = null,
val emits: List = emptyList(),
+ /** See [Capability.targetResolver]: for tools whose target is not an argument. */
+ val targetResolver: ((Map) -> List)? = null,
)
private const val P_SMS_READ = "android.permission.READ_SMS"
@@ -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)
@@ -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.)
@@ -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())
@@ -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 {
+ if (key.isNullOrBlank()) return emptyList()
+ val n = io.droidmcp.notification.NotificationStore.findByKey(key)?.notification ?: return emptyList()
+ val out = linkedSetOf()
+ 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): Map {
val types = tool.parameters.associate { it.name to it.type }
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/NativeCapabilities.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/NativeCapabilities.kt
index 1b919c7..458ff25 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/NativeCapabilities.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/NativeCapabilities.kt
@@ -32,7 +32,7 @@ object NativeCapabilities {
Param("driver_managed", "boolean", "Cancel approval when the caller stops waiting; end the call if conversation mode does not start within 90 seconds (default false)"),
Param("audio_route", "string", "earpiece (default) or speaker", enum = listOf("earpiece", "speaker")),
),
- // An outbound call commits the user to the world: EXTERNAL_COMMITMENT, unattended by default (docs/security.md §2.3a) — rate limits and the denylist are the brakes, not an approval tap.
+ // An outbound call commits the user to the world: EXTERNAL_COMMITMENT, unattended by default (docs/security.md#configure-the-defaults-deliberately) — rate limits and the denylist are the brakes, not an approval tap.
actionClass = ActionClass.EXTERNAL_COMMITMENT, rateClass = RateClass.CALL,
requiredPermissions = listOf("android.permission.CALL_PHONE", "android.permission.READ_PHONE_STATE"),
emitsEvents = listOf(Topics.SESSION_STATE, Topics.CALL_CONNECTED, Topics.CALL_ENDED),
@@ -69,6 +69,7 @@ object NativeCapabilities {
else CapabilityResult.unavailable("TelecomManager.endCall refused on this device; the call must be ended from the dialer or by the far end")
} catch (e: SecurityException) { CapabilityResult.missingPermission("android.permission.${e.message}") }
catch (e: IllegalArgumentException) { CapabilityResult.fail("session.unknown", id) }
+ catch (e: IllegalStateException) { CapabilityResult.unavailable(UNIDENTIFIED_CALL) }
},
Capability(
name = "telephony.set_audio_route",
@@ -91,15 +92,16 @@ object NativeCapabilities {
params = listOf(Param("session_id", "string", "Session", required = true), Param("digits", "string", "Digits 0-9*#", required = true)),
actionClass = ActionClass.LOW_RISK,
) { args, ctx ->
- // Holder.active() is whatever call Telecom has up, not necessarily this session's: without the live-call
- // check, the owner of a stale session could key tones into the user's own call.
+ // Owned AND live, and then this session's own Telecom call: Holder.active(), which this used to use, was
+ // whatever call Telecom had up, so tones could go into the user's own call.
val access = SessionAccess.ownedActiveCall(sessions, args["session_id"]?.toString(), ctx)
if (access is SessionAccess.Access.Denied) return@Capability access.result
val id = (access as SessionAccess.Access.Ok).session.sessionId
val digits =args["digits"]?.toString()?.filter { it in "0123456789*#" } ?: ""
if (digits.isEmpty()) return@Capability CapabilityResult.fail("invalid_params", "digits must be 0-9, * or #")
- val call = dev.symbiosis.runtime.telephony.SymbiosisInCallService.Holder.active()
- ?: return@Capability CapabilityResult.unavailable("dtmf needs the default-dialer role (InCallService not bound)")
+ val call = calls.telecomCallFor(id) ?: return@Capability CapabilityResult.unavailable(
+ if (!dev.symbiosis.runtime.telephony.SymbiosisInCallService.Holder.bound) "dtmf needs the default-dialer role (InCallService not bound)" else UNIDENTIFIED_CALL,
+ )
for (d in digits) { call.playDtmfTone(d); kotlinx.coroutines.delay(160); call.stopDtmfTone(); kotlinx.coroutines.delay(90) }
sessions.emitFrame(id, sessions.get(id)?.correlationId, "dtmf.sent", kotlinx.serialization.json.buildJsonObject { put("digits", kotlinx.serialization.json.JsonPrimitive(digits)) })
CapabilityResult.ok(mapOf("session_id" to id, "digits" to digits))
@@ -125,6 +127,8 @@ object NativeCapabilities {
},
)
+ private const val UNIDENTIFIED_CALL = "this session's own call could not be identified (Telecom has not reported it, or another call may be up); refusing to act on a call that may be the user's"
+
/** Sessions are visible to their owning peer and to the admin; sessions without an owner are admin-only. */
private fun owns(s: dev.symbiosis.runtime.sessions.Session, ctx: CallContext): Boolean =
ctx.principal?.isAdmin == true || (s.peerId != null && s.peerId == ctx.peerId)
@@ -132,7 +136,8 @@ object NativeCapabilities {
private fun scopeError(glob: String) = CapabilityResult.fail("policy.denied", "topic '$glob' is outside this peer's scopes (needs ${dev.symbiosis.runtime.capabilities.Scopes.requiredScopesForTopicGlob(glob).joinToString(" and ")})")
- fun events(broker: EventBroker, subs: SubscriptionStore): List = listOf(
+ /** @param sessionOwner owner of a session named in an event payload ([SessionManager.ownerOf]), for [Principal.canSeeEvent]. */
+ fun events(broker: EventBroker, subs: SubscriptionStore, sessionOwner: (String) -> String?): List = listOf(
Capability(
name = "events.subscribe",
description = "Create a persistent subscription. Events are pushed on /ws/events and can be pulled with events.replay.",
@@ -190,7 +195,7 @@ object NativeCapabilities {
val sub = subs.get(peer, args["subscription_id"].toString()) ?: return@Capability CapabilityResult.fail("subscription.unknown")
val since = (args["since_id"] as? Number)?.toLong() ?: sub.ack_cursor
val principal = ctx.principal
- val r = subs.replay(sub, since, (args["limit"] as? Number)?.toInt() ?: 200) { ev -> principal?.canSeeTopic(ev.topic) == true }
+ val r = subs.replay(sub, since, (args["limit"] as? Number)?.toInt() ?: 200) { ev -> principal?.canSeeEvent(ev, sessionOwner) == true }
CapabilityResult.ok(
mapOf(
"events" to r.events.map { Json.toMap(Json.lenient.encodeToJsonElement(dev.symbiosis.runtime.events.Event.serializer(), it) as JsonObject) },
@@ -214,7 +219,7 @@ object NativeCapabilities {
val filter = parseFilter(args["filter"])
val timeout = ((args["timeout_ms"] as? Number)?.toLong() ?: 30_000L).coerceIn(100, 60_000)
val ev = withTimeoutOrNull(timeout) {
- broker.live.first { dev.symbiosis.runtime.events.TopicGlob.matches(glob, it.topic) && principal.canSeeTopic(it.topic) && filter.all { f -> f.matches(it.payload) } }
+ broker.live.first { dev.symbiosis.runtime.events.TopicGlob.matches(glob, it.topic) && principal.canSeeEvent(it, sessionOwner) && filter.all { f -> f.matches(it.payload) } }
}
if (ev == null) CapabilityResult.ok(mapOf("timed_out" to true))
else CapabilityResult.ok(mapOf("timed_out" to false, "event" to Json.toMap(Json.lenient.encodeToJsonElement(dev.symbiosis.runtime.events.Event.serializer(), ev) as JsonObject)))
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/SelfProtection.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/SelfProtection.kt
new file mode 100644
index 0000000..461a0ba
--- /dev/null
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/SelfProtection.kt
@@ -0,0 +1,83 @@
+package dev.symbiosis.runtime.capabilities
+
+import android.content.Context
+import dev.symbiosis.runtime.core.Ids
+import dev.symbiosis.runtime.ui.SymbiosisAccessibilityService
+import java.util.concurrent.atomic.AtomicInteger
+
+/**
+ * Keeps agents away from this app's own controls. The control panel shows the admin token, mints pairing codes,
+ * holds the safety switches and the Approve buttons, and the approval notifications carry Approve actions. A peer
+ * with screen control (`ui.*`) or `notifications.invoke_action` could otherwise drive all of that itself.
+ *
+ * Three layers, all checked at execution time in Runtime.executeAllowed (so direct calls, batch steps and late
+ * approvals alike):
+ * - every `ui.*` call is refused while one of our windows is on screen: one of our activities is started, or the
+ * accessibility service sees our package as the active window or anywhere in the interactive windows list;
+ * - `apps.launch`, `apps.open_deep_link` and `apps.send_intent` aimed at our own package are refused;
+ * - the notification tools refuse keys of notifications our own package posted.
+ * [ScreenControlWindow] is the fourth: an approval that arrives right after screen control is ignored.
+ */
+object SelfProtection {
+ const val CODE = "ui.self_protected"
+
+ /** Activities of this app that are currently started (visible, possibly behind a dialog or in split screen). */
+ val startedActivities = AtomicInteger(0)
+
+ /** Tools that act on a notification by its key. */
+ val NOTIFICATION_KEY_TOOLS = setOf("notifications.reply", "notifications.invoke_action", "notifications.dismiss")
+
+ /** Tools that open an app by package name. */
+ private val LAUNCH_TOOLS = setOf("apps.launch", "apps.open_deep_link", "apps.send_intent")
+
+ fun isScreenControl(name: String): Boolean = name.startsWith("ui.")
+
+ /** Calls that can press something on screen or in the shade; an approval right after one is not trusted. */
+ fun countsAsScreenControl(name: String): Boolean = isScreenControl(name) || name == "notifications.invoke_action"
+
+ /** The posting package from a StatusBarNotification key (`userId|package|id|tag|uid`), or null if malformed. */
+ fun notificationPackage(key: String?): String? = key?.split('|')?.getOrNull(1)?.takeIf { it.isNotBlank() }
+
+ /**
+ * The refusal for [name] with [args], or null when the call may run. [ownWindowShowing] is only consulted for
+ * screen-control tools, so the (main-thread-free but not free) window query runs only when it matters.
+ */
+ fun refusal(name: String, args: Map, ownPackage: String, ownWindowShowing: () -> Boolean): CapabilityResult? {
+ if (isScreenControl(name) && ownWindowShowing()) {
+ return CapabilityResult.fail(CODE, "screen control is refused while Android Agent Harness is on screen")
+ }
+ if (name in LAUNCH_TOOLS && args["package_name"]?.toString()?.trim() == ownPackage) {
+ return CapabilityResult.fail(CODE, "agents cannot open Android Agent Harness itself")
+ }
+ if (name in NOTIFICATION_KEY_TOOLS && notificationPackage(args["key"]?.toString()) == ownPackage) {
+ return CapabilityResult.fail(CODE, "notifications posted by Android Agent Harness are not available to agents")
+ }
+ return null
+ }
+
+ /** True when one of our windows is visible: a started activity, or our package in the accessibility window list. */
+ fun ownWindowShowing(context: Context): Boolean {
+ if (startedActivities.get() > 0) return true
+ val svc = SymbiosisAccessibilityService.current ?: return false
+ val own = context.packageName
+ if (runCatching { svc.rootInActiveWindow?.packageName?.toString() }.getOrNull() == own) return true
+ // flagRetrieveInteractiveWindows is set in droid-mcp's service config, so this covers split screen and overlays.
+ return runCatching { svc.windows.any { w -> w.root?.packageName?.toString() == own } }.getOrDefault(false)
+ }
+}
+
+/**
+ * When a peer last used screen control (any `ui.*` call or `notifications.invoke_action`), in one place. A tap on
+ * Approve within [WINDOW_MS] of that, in the app or in the notification shade, may be the agent's own tap and is
+ * ignored (Runtime.resolveApproval). Marked when such a call starts and again when it ends, so a long call
+ * (scroll_to_find, find_and_tap) is covered for its whole run plus the window.
+ */
+class ScreenControlWindow(private val clock: () -> Long = { Ids.now() }) {
+ @Volatile private var lastAt: Long = Long.MIN_VALUE
+
+ fun mark() { lastAt = clock() }
+
+ fun recentlyUsed(): Boolean = lastAt != Long.MIN_VALUE && clock() - lastAt < WINDOW_MS
+
+ companion object { const val WINDOW_MS = 10_000L }
+}
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/UiGestures.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/UiGestures.kt
index e594572..794e09b 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/UiGestures.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/capabilities/UiGestures.kt
@@ -31,7 +31,7 @@ object UiGestures {
Param("y", "number", "Screen Y in pixels", required = true),
Param("interval_ms", "integer", "Gap between the first tap's release and the second tap (default 100, 40-250)"),
),
- // Same class, tier and rate class as ui.tap_coordinates: one screen action (docs/security.md §2.3a).
+ // Same class, tier and rate class as ui.tap_coordinates: one screen action (docs/security.md#limits).
actionClass = ActionClass.DEVICE_MUTATION, tier = 2, rateClass = RateClass.MUTATION,
) { args, _ ->
val svc = SymbiosisAccessibilityService.current
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/core/DebugReceiver.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/core/DebugReceiver.kt
index 192161d..206a96d 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/core/DebugReceiver.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/core/DebugReceiver.kt
@@ -9,7 +9,8 @@ import dev.symbiosis.runtime.policy.ActionClass
/**
* DEBUG builds only (no-op in release): lets an emulator verification script drive flows that
- * normally need a tap on the screen.
+ * normally need a tap on the screen. Exported behind android.permission.DUMP (src/debug/AndroidManifest.xml),
+ * so only the adb shell can send these; an installed app cannot.
*
* adb shell am broadcast -n dev.symbiosis.runtime/.core.DebugReceiver -a dev.symbiosis.DEBUG_PAIR --es access standard|full
* → logs "SYMBIOSIS_PAIRING_CODE=XXXX-XXXX" (redeem it with POST /pair, exactly like a real agent)
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/core/Runtime.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/core/Runtime.kt
index a25cf9e..b639302 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/core/Runtime.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/core/Runtime.kt
@@ -14,6 +14,7 @@ import dev.symbiosis.runtime.capabilities.CapabilityResult
import dev.symbiosis.runtime.capabilities.DroidMcpAdapter
import dev.symbiosis.runtime.capabilities.NativeCapabilities
import dev.symbiosis.runtime.capabilities.Principal
+import dev.symbiosis.runtime.capabilities.SelfProtection
import dev.symbiosis.runtime.events.EventBroker
import dev.symbiosis.runtime.events.SubscriptionStore
import dev.symbiosis.runtime.events.Topics
@@ -99,6 +100,8 @@ class Runtime private constructor(private val context: Context) {
executor = automationExecutor,
// The owner's CURRENT principal: a revoked or expired peer's workflows do not run (and get disabled).
principalFor = { id -> principalOf(id) },
+ // A call's events (transcripts included) trigger only workflows whose owner owns that call.
+ sessionOwner = { id -> sessions.ownerOf(id) },
emergencyStopped = { policy.emergencyStop.value },
alarms = dev.symbiosis.runtime.automation.AndroidAlarms(context),
scope = scope,
@@ -125,6 +128,9 @@ class Runtime private constructor(private val context: Context) {
private var maintenanceJob: Job? = null
private val startedAt = Ids.now()
+ /** When a peer last used screen control; approvals right after it are ignored (see resolveApproval). */
+ val screenControl = dev.symbiosis.runtime.capabilities.ScreenControlWindow()
+
/** Idempotency keys currently executing, per peer, so a concurrent duplicate cannot run twice. */
private val inFlight = ConcurrentHashMap.newKeySet()
@@ -175,6 +181,7 @@ class Runtime private constructor(private val context: Context) {
}
}
peers.knownCapabilities = { registry.names() }
+ approvals.capabilityFor = { registry.get(it) }
registerCapabilities()
// After the hooks, so each is audited and announced as session.state like any other transition.
runCatching { calls.failStale("process_restart") }
@@ -256,7 +263,7 @@ class Runtime private constructor(private val context: Context) {
}
registry.registerAll(DroidMcpAdapter.adapt(context, droid))
registry.registerAll(NativeCapabilities.telephony(calls, sessions))
- registry.registerAll(NativeCapabilities.events(broker, subscriptions))
+ registry.registerAll(NativeCapabilities.events(broker, subscriptions) { sessions.ownerOf(it) })
registry.registerAll(NativeCapabilities.device(context) { status() })
// Conversation mode is part of the release surface (live-verified on the Pixel, Sept 2026).
registry.register(dev.symbiosis.runtime.capabilities.CallSpeech.speakCapability(context, broker, sessions))
@@ -426,12 +433,20 @@ class Runtime private constructor(private val context: Context) {
}
val missing = cap.requiredPermissions.filter { context.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
if (missing.isNotEmpty()) { policy.release(allow); return CapabilityResult.missingPermission(*missing.toTypedArray()) }
+ // Agents never operate this app's own screens or notifications (capabilities/SelfProtection.kt). Checked here,
+ // at execution time, so a batch step or a late approval is held to it as well as a direct call.
+ SelfProtection.refusal(cap.name, args, context.packageName) { SelfProtection.ownWindowShowing(context) }
+ ?.let { policy.release(allow); return it }
+ val screen = SelfProtection.countsAsScreenControl(cap.name)
+ if (screen) screenControl.mark()
return try {
withContext(Dispatchers.IO) { cap.execute(args, ctx.copy(principal = current)) }.also { if (!it.ok) policy.release(allow) }
} catch (t: Throwable) {
android.util.Log.e("Runtime", "capability ${cap.name} threw", t)
policy.release(allow)
CapabilityResult.fail("capability.failed", t.message ?: t.javaClass.simpleName)
+ } finally {
+ if (screen) screenControl.mark()
}
}
@@ -463,12 +478,37 @@ class Runtime private constructor(private val context: Context) {
}
}
- suspend fun resolveApproval(id: String, approved: Boolean, via: String) {
- val res = approvals.resolve(id, approved) ?: return
+ /**
+ * Apply an Approve/Deny tap. Returns null when it was applied, else why not: [APPROVAL_IGNORED_SCREEN_CONTROL]
+ * (left pending, try again shortly) or [APPROVAL_NOT_PENDING] (unknown, already resolved or expired).
+ */
+ suspend fun resolveApproval(id: String, approved: Boolean, via: String): String? {
+ // An approval right after a peer used screen control may be that peer tapping Approve itself (in this app or in
+ // the notification shade). Leave it pending and audit it. Denials always go through. The adb debug broadcast is
+ // exempt: only the shell (DUMP permission) can send it, never an agent's tap.
+ if (approved && via != "debug-broadcast" && screenControl.recentlyUsed()) {
+ val pa = approvals.get(id)
+ audit.append(AuditEntry(ts = Ids.now(), correlationId = pa?.correlationId, peerId = pa?.peerId, kind = AuditKind.APPROVAL, capability = pa?.capability, actionClass = pa?.actionClass?.name, result = JsonPrimitive("ignored"), args = buildJsonObject { put("pending_action_id", id); put("via", via) }, success = false, errorCode = APPROVAL_IGNORED_SCREEN_CONTROL))
+ return APPROVAL_IGNORED_SCREEN_CONTROL
+ }
+ val res = approvals.resolve(id, approved) ?: return APPROVAL_NOT_PENDING
val pa = res.action
audit.append(AuditEntry(ts = Ids.now(), correlationId = pa.correlationId, peerId = pa.peerId, kind = AuditKind.APPROVAL, capability = pa.capability, actionClass = pa.actionClass.name, result = JsonPrimitive(if (approved) "approved" else "denied"), args = buildJsonObject { put("pending_action_id", id); put("via", via); put("late", res.late) }, success = approved))
broker.emit(Topics.APPROVAL_RESOLVED, mapOf("pending_action_id" to id, "decision" to if (approved) "approved" else "denied", "capability" to pa.capability, "via" to via, "late" to res.late), pa.correlationId)
if (approved && res.late) executeApproved(pa)
+ return null
+ }
+
+ /**
+ * The app's "Rotate admin token" control. The old token stops authenticating at once (PeerStore reads the
+ * current one on every request); sockets and MCP sessions opened with it are closed, and the admin's pending
+ * approvals are cancelled so nothing queued under the old token can still run.
+ */
+ fun rotateAdminToken() {
+ secure.rotateAdminToken()
+ server?.closeSocketsFor(PeerStore.ADMIN_ID, "admin_token_rotated")
+ val cancelled = approvals.cancelPending(PeerStore.ADMIN_ID, "admin_token_rotated")
+ audit.append(AuditEntry(ts = Ids.now(), correlationId = null, peerId = PeerStore.ADMIN_ID, kind = AuditKind.ADMIN, capability = "admin_token_rotate", success = true, result = buildJsonObject { put("cancelled_pending", cancelled) }))
}
private fun toolResultJson(r: CapabilityResult, ctx: CallContext, durationMs: Long, auditId: Long? = null): JsonObject {
@@ -515,7 +555,7 @@ class Runtime private constructor(private val context: Context) {
"phone://policy" -> if (!principal.isAdmin) null else buildJsonObject { put("config", Json.lenient.encodeToJsonElement(dev.symbiosis.runtime.policy.PolicyConfig.serializer(), policy.config.value)); put("overrides", Json.toJson(policy.overrides().mapValues { it.value.name })); put("emergency_stop", policy.emergencyStop.value); put("observe_only", policy.observeOnly.value) }
"phone://sessions" -> JsonArray(sessions.recent(20).filter { principal.isAdmin || (it.peerId != null && it.peerId == principal.peerId) }.map { sessions.toJson(it) })
"phone://events/recent" -> if (!principal.isAdmin && !principal.canSubscribe("policy.x")) null
- else JsonArray(broker.recent(50).filter { principal.canSeeTopic(it.topic) }.map { Json.lenient.encodeToJsonElement(dev.symbiosis.runtime.events.Event.serializer(), it) })
+ else JsonArray(broker.recent(50).filter { principal.canSeeEvent(it) { id -> sessions.ownerOf(id) } }.map { Json.lenient.encodeToJsonElement(dev.symbiosis.runtime.events.Event.serializer(), it) })
"phone://audit/verify" -> if (!principal.isAdmin) null else {
val broken = audit.verifyChain(); val anchor = audit.anchor()
buildJsonObject { put("intact", broken == null); put("first_broken_id", broken); put("entries", audit.count()); put("verified_from_id", anchor?.firstKeptId); put("pruned_through", anchor?.createdAt) }
@@ -551,6 +591,9 @@ class Runtime private constructor(private val context: Context) {
)
companion object {
+ const val APPROVAL_IGNORED_SCREEN_CONTROL = "approval.ignored_screen_control"
+ const val APPROVAL_NOT_PENDING = "approval.not_pending"
+
/**
* Whether a stored outcome may be replayed for this call: null = replay it, else the refusal code.
* - A key is only a claim about WHICH call this is. Replay only if the stored outcome is for this very tool and
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/Event.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/Event.kt
index 00a08b6..4524adc 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/Event.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/Event.kt
@@ -2,6 +2,7 @@ package dev.symbiosis.runtime.events
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
@@ -19,6 +20,13 @@ data class Event(
val device_id: String? = null,
)
+/**
+ * The session this event is about (`payload.session_id`), or null when it names none. Visibility hangs on it
+ * (Principal.canSeeEvent): a session's events are its owner's.
+ */
+fun Event.sessionIdOrNull(): String? =
+ (payload["session_id"] as? JsonPrimitive)?.takeUnless { it is JsonNull }?.contentOrNull?.takeIf { it.isNotBlank() }
+
object Topics {
const val SMS_RECEIVED = "messaging.sms_received"
/** RCS chat messages surface only as the messaging app's notification; normalised to the SMS shape with transport=rcs. */
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/EventBroker.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/EventBroker.kt
index e84d4dd..98859b2 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/EventBroker.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/EventBroker.kt
@@ -48,9 +48,11 @@ class EventBroker(private val db: Db, private val deviceId: String) {
return ev
}
- fun lastId(): Long = db.readableDatabase.compileStatement("SELECT COALESCE(MAX(id), 0) FROM events").simpleQueryForLong()
- fun earliestId(): Long = db.readableDatabase.compileStatement("SELECT COALESCE(MIN(id), 0) FROM events").simpleQueryForLong()
- fun count(): Long = db.readableDatabase.compileStatement("SELECT COUNT(*) FROM events").simpleQueryForLong()
+ // Each statement is closed after use: these run per subscribe/replay/status call and leaked one native statement each.
+ fun lastId(): Long = scalar("SELECT COALESCE(MAX(id), 0) FROM events")
+ fun earliestId(): Long = scalar("SELECT COALESCE(MIN(id), 0) FROM events")
+ fun count(): Long = scalar("SELECT COUNT(*) FROM events")
+ private fun scalar(sql: String): Long = db.readableDatabase.compileStatement(sql).use { it.simpleQueryForLong() }
/** Events with id > sinceId, ascending, up to limit+1 so the caller can detect "more". */
fun after(sinceId: Long, limit: Int): List = db.readableDatabase.query(
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/SubscriptionStore.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/SubscriptionStore.kt
index b59f47a..db48fa2 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/SubscriptionStore.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/SubscriptionStore.kt
@@ -30,8 +30,13 @@ data class ReplayResult(val events: List, val nextSinceId: Long, val trun
class SubscriptionStore(private val db: Db, private val broker: EventBroker) {
private val filterSer = ListSerializer(FilterClause.serializer())
- /** Bumped on every create/delete so live fan-out caches can refresh cheaply. */
- @Volatile var version: Long = 0; private set
+ /**
+ * Bumped on every create/delete so live fan-out caches can refresh cheaply. Atomic: creates and deletes arrive on
+ * several threads (MCP requests, WebSocket frames, expiry pruning), and a lost `version++` left a socket serving a
+ * stale subscription list.
+ */
+ private val versionCounter = java.util.concurrent.atomic.AtomicLong(0)
+ val version: Long get() = versionCounter.get()
/** Called after a replay (WS or MCP tool) so a paused live push can resume for that subscription. */
var onReplayed: ((peerId: String, subscriptionId: String) -> Unit)? = null
@@ -67,12 +72,12 @@ class SubscriptionStore(private val db: Db, private val broker: EventBroker) {
put("expires_at", sub.expires_at); put("ack_cursor", sub.ack_cursor)
},
)
- version++
+ versionCounter.incrementAndGet()
return sub
}
- fun delete(peerId: String, id: String): Boolean = (db.writableDatabase.delete("subscriptions", "subscription_id = ? AND peer_id = ?", arrayOf(id, peerId)) > 0).also { if (it) version++ }
- fun deleteAllFor(peerId: String) = db.writableDatabase.delete("subscriptions", "peer_id = ?", arrayOf(peerId)).also { version++ }
+ fun delete(peerId: String, id: String): Boolean = (db.writableDatabase.delete("subscriptions", "subscription_id = ? AND peer_id = ?", arrayOf(id, peerId)) > 0).also { if (it) versionCounter.incrementAndGet() }
+ fun deleteAllFor(peerId: String) = db.writableDatabase.delete("subscriptions", "peer_id = ?", arrayOf(peerId)).also { versionCounter.incrementAndGet() }
fun get(peerId: String, id: String): Subscription? = db.readableDatabase.query("subscriptions", null, "subscription_id = ? AND peer_id = ?", arrayOf(id, peerId), null, null, null)
.use { c -> if (c.moveToFirst()) row(c) else null }?.takeUnless { it.expired() }
@@ -117,7 +122,7 @@ class SubscriptionStore(private val db: Db, private val broker: EventBroker) {
private fun pruneExpired() {
val n = db.writableDatabase.delete("subscriptions", "expires_at IS NOT NULL AND expires_at < ?", arrayOf(Ids.now().toString()))
- if (n > 0) version++
+ if (n > 0) versionCounter.incrementAndGet()
}
companion object { const val MAX_PER_PEER = 32 }
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/sources/NotificationEventListener.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/sources/NotificationEventListener.kt
index 795519e..f8629a3 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/sources/NotificationEventListener.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/events/sources/NotificationEventListener.kt
@@ -28,10 +28,19 @@ class NotificationEventListener : McpNotificationListenerServiceBase() {
super.onListenerDisconnected()
}
+ /**
+ * droid-mcp's base fills the store its notifications.* tools read (list, reply, invoke_action, dismiss) from this
+ * on connect and from [onNotificationPosted]. Our own notifications never enter it: the approval notification's
+ * Approve action is a PendingIntent, and invoke_action would let an agent fire it.
+ */
+ override fun getActiveNotifications(): Array? =
+ super.getActiveNotifications()?.filter { it.packageName != packageName }?.toTypedArray()
+
override fun onNotificationPosted(sbn: StatusBarNotification?) {
- super.onNotificationPosted(sbn)
sbn ?: return
- if (sbn.packageName == packageName) return // never loop on our own runtime/approval notifications
+ // Never stored for tools (see getActiveNotifications), and never looped back as our own events.
+ if (sbn.packageName == packageName) return
+ super.onNotificationPosted(sbn)
val n = sbn.notification
val extras = n.extras
val text = extras.getCharSequence(android.app.Notification.EXTRA_BIG_TEXT)?.toString() ?: extras.getCharSequence(android.app.Notification.EXTRA_TEXT)?.toString()
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/ApprovalManager.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/ApprovalManager.kt
index 4929fc9..c127571 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/ApprovalManager.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/ApprovalManager.kt
@@ -46,6 +46,9 @@ class ApprovalManager(private val context: Context, private val db: Db) {
private val waiters = ConcurrentHashMap>()
private val requestCodes = AtomicInteger(1000)
+ /** Capability lookup for the prompt's argument summary (set by Runtime; [ApprovalSummary] orders by it). */
+ @Volatile var capabilityFor: (String) -> dev.symbiosis.runtime.capabilities.Capability? = { null }
+
init { ensureChannel() }
/** True when approval notifications can actually be shown (API 33+ needs the runtime permission). */
@@ -202,15 +205,28 @@ class ApprovalManager(private val context: Context, private val db: Db) {
.putExtra(ApprovalReceiver.EXTRA_ID, pa.id).putExtra(ApprovalReceiver.EXTRA_DECISION, decision)
// Distinct request codes per PendingIntent: extras are not part of PendingIntent identity.
val pi = PendingIntent.getBroadcast(context, requestCodes.incrementAndGet(), i, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
- return Notification.Action.Builder(null, label, pi).build()
+ val b = Notification.Action.Builder(null, label, pi)
+ // Approve and Deny need the device unlocked first: a tap from the lock screen asks for the PIN.
+ if (Build.VERSION.SDK_INT >= 31) b.setAuthenticationRequired(true)
+ return b.build()
}
- val summary = pa.args.entries.take(3).joinToString(", ") { (k, v) -> "$k=${v.toString().take(40)}" }
+ // Target first, then the body, every value in full; undeclared args flagged (ApprovalSummary).
+ val lines = ApprovalSummary.lines(capabilityFor(pa.capability), pa.args)
+ val summary = ApprovalSummary.format(lines)
+ // The lock screen shows only this redacted version (VISIBILITY_PRIVATE below).
+ val redacted = Notification.Builder(context, CHANNEL)
+ .setSmallIcon(android.R.drawable.ic_dialog_alert)
+ .setContentTitle("Approval needed")
+ .setContentText("Unlock to review")
+ .build()
val n = Notification.Builder(context, CHANNEL)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentTitle("Approve ${pa.capability}?")
- .setContentText("$reason · $summary")
+ .setContentText("$reason · ${lines.firstOrNull()?.let { "${it.key}: ${it.value}" } ?: "no arguments"}")
.setStyle(Notification.BigTextStyle().bigText("${pa.actionClass} · $reason\n$summary\nExpires in ${(pa.expiresAt - Ids.now()) / 60000} min"))
.setCategory(Notification.CATEGORY_ALARM)
+ .setVisibility(Notification.VISIBILITY_PRIVATE)
+ .setPublicVersion(redacted)
.setAutoCancel(false)
.setOngoing(true)
.addAction(action("approve", "Approve"))
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/ApprovalReceiver.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/ApprovalReceiver.kt
index a3b2cf1..bb3162c 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/ApprovalReceiver.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/ApprovalReceiver.kt
@@ -13,7 +13,8 @@ import kotlinx.coroutines.launch
* Receives Approve/Deny from the approval notification. Not exported: only our own PendingIntents
* reach it. In DEBUG builds only, `adb shell am broadcast -n dev.symbiosis.runtime/.policy.ApprovalReceiver
* -a dev.symbiosis.DEBUG_RESOLVE --es id pa_xxx --es decision approve` is also accepted, so the
- * allow path can be exercised on an emulator without a human tapping the notification.
+ * allow path can be exercised on an emulator without a human tapping the notification. The debug export
+ * requires android.permission.DUMP, which the adb shell holds and installed apps cannot.
*/
class ApprovalReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/ApprovalSummary.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/ApprovalSummary.kt
new file mode 100644
index 0000000..d6e5fb5
--- /dev/null
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/ApprovalSummary.kt
@@ -0,0 +1,63 @@
+package dev.symbiosis.runtime.policy
+
+import dev.symbiosis.runtime.capabilities.Capability
+import dev.symbiosis.runtime.core.Json
+
+/**
+ * What an approval prompt shows: the arguments in an order the agent cannot choose. The target first (the
+ * capability's targetArg, or for a resolver-backed tool such as notifications.reply, who it reaches), then the
+ * message body, then the other declared params in declared order, each value in full. Arguments the capability
+ * does not declare follow, flagged as undeclared. Values are compact JSON with control and Unicode format
+ * characters escaped, so a value cannot draw a fake line (a newline and "to: ...") or reorder text (bidi controls).
+ *
+ * Undeclared arguments are shown rather than rejected: the passthrough droid-mcp tools receive the args map as is,
+ * and their declared parameter lists (read from the AAR) are what we show, but nothing here proves a tool reads
+ * no other key, so rejecting could break a working call while flagging cannot.
+ */
+object ApprovalSummary {
+ data class Line(val key: String, val value: String, val declared: Boolean)
+
+ /** Argument names treated as the message body, shown right after the target. */
+ val BODY_KEYS = listOf("body", "text", "message", "content")
+
+ const val RECIPIENT = "recipient"
+
+ fun lines(cap: Capability?, args: Map): List {
+ val declared = buildList {
+ cap?.targetArg?.let(::add)
+ cap?.params?.forEach { add(it.name) }
+ }.distinct()
+ val order = buildList {
+ cap?.targetArg?.let(::add)
+ BODY_KEYS.filter { it in declared }.forEach(::add)
+ addAll(declared)
+ }.distinct()
+ val out = mutableListOf()
+ cap?.targetResolver?.let { r ->
+ val who = runCatching { r(args) }.getOrDefault(emptyList()).filter { it.isNotBlank() }
+ out += Line(RECIPIENT, if (who.isEmpty()) "unknown" else who.joinToString(", ") { value(it) }, declared = true)
+ }
+ for (k in order) if (args.containsKey(k)) out += Line(k, value(args[k]), declared = true)
+ for (k in args.keys.filter { it !in declared }.sorted()) out += Line(escape(k), value(args[k]), declared = false)
+ return out
+ }
+
+ /** One line per argument, `key: value`, undeclared ones marked. */
+ fun format(lines: List): String = lines.joinToString("\n") { l ->
+ if (l.declared) "${l.key}: ${l.value}" else "${l.key} (undeclared): ${l.value}"
+ }
+
+ fun format(cap: Capability?, args: Map): String = format(lines(cap, args))
+
+ private fun value(v: Any?): String = escape(Json.canonical(Json.toJson(v)))
+
+ /** Escapes what [Json.canonical] leaves: C1 controls, line/paragraph separators and format characters (bidi). */
+ private fun escape(s: String): String = buildString {
+ for (c in s) {
+ val t = Character.getType(c)
+ val hidden = c.code < 0x20 || c.code in 0x7f..0x9f || t == Character.FORMAT.toInt() ||
+ t == Character.LINE_SEPARATOR.toInt() || t == Character.PARAGRAPH_SEPARATOR.toInt()
+ if (hidden) append(String.format("\\u%04x", c.code)) else append(c)
+ }
+ }
+}
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/PolicyEngine.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/PolicyEngine.kt
index f432b88..019aa7c 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/PolicyEngine.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/policy/PolicyEngine.kt
@@ -82,11 +82,17 @@ class PolicyEngine(private val db: Db, private val rateLimiter: RateLimiter) {
if (decision == PolicyDecision.DENY) return PolicyOutcome.Deny("policy.denied", "capability ${cap.name} is denied by policy")
if (cap.actionClass >= ActionClass.COMMUNICATION) {
- val target = cap.targetArg?.let { args[it]?.toString() }
- if (target != null) {
- val norm = normalizeNumber(target)
- if (cfg.contactDenylist.any { sameNumber(normalizeNumber(it), norm) }) return PolicyOutcome.Deny("policy.denied", "target is on the denylist")
- val allowlisted = cfg.contactAllowlist.any { sameNumber(normalizeNumber(it), norm) }
+ // A resolver names every identity the call reaches (a notification reply: sender name and number); an
+ // argument names one. Denied if ANY identity is on the denylist, allowlisted only if EVERY one is, so a group
+ // thread or a name the list does not hold still asks. An unresolvable target counts as not on the allowlist.
+ val resolved = cap.targetResolver?.let { r -> runCatching { r(args) }.getOrDefault(emptyList()).filter { it.isNotBlank() } }
+ val targets = resolved ?: cap.targetArg?.let { a -> args[a]?.toString()?.let { listOf(it) } }
+ if (resolved != null && resolved.isEmpty() && cfg.contactAllowlist.isNotEmpty() && decision == PolicyDecision.ALLOW) {
+ decision = PolicyDecision.APPROVE; approveReason = "target unknown, not on allowlist"
+ }
+ if (!targets.isNullOrEmpty()) {
+ if (targets.any { t -> cfg.contactDenylist.any { sameTarget(it, t) } }) return PolicyOutcome.Deny("policy.denied", "target is on the denylist")
+ val allowlisted = targets.all { t -> cfg.contactAllowlist.any { sameTarget(it, t) } }
if (cfg.contactAllowlist.isNotEmpty() && !allowlisted && decision == PolicyDecision.ALLOW) {
decision = PolicyDecision.APPROVE; approveReason = "target not on allowlist"
}
@@ -215,6 +221,17 @@ class PolicyEngine(private val db: Db, private val rateLimiter: RateLimiter) {
/** Compare complete normalized numbers; a shared national suffix does not make country codes equal. */
fun sameNumber(a: String, b: String): Boolean = normalizeNumber(a) == normalizeNumber(b)
+ /**
+ * A contact-list entry against a call's target. Numbers compare as [sameNumber]. When either side has no digits
+ * (a contact name, as a notification title gives it) they compare as trimmed, case-insensitive text instead:
+ * two different names both normalize to "" and must not count as the same number.
+ */
+ fun sameTarget(entry: String, target: String): Boolean {
+ val a = normalizeNumber(entry); val b = normalizeNumber(target)
+ if (a.isEmpty() || b.isEmpty()) return entry.isNotBlank() && entry.trim().equals(target.trim(), ignoreCase = true)
+ return a == b
+ }
+
fun normalizeNumber(raw: String): String {
val s = stripDialDecorations(raw)
val plus = s.startsWith("+")
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/sessions/CallSession.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/sessions/CallSession.kt
index 6c0f33f..775622b 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/sessions/CallSession.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/sessions/CallSession.kt
@@ -36,14 +36,33 @@ class CallSessions(
private var connectedAt: Long = 0
private var lastCallState: Int = TelephonyManager.CALL_STATE_IDLE
- fun currentSessionId(): String? = current.get()
+ /**
+ * Each session's own Telecom call, once identified ([onTelecomCallAdded]). end_call, DTMF, the dial watchdog,
+ * the driver lease and emergency stop act on this Call only. They used to act on `Holder.active()`, whatever call
+ * Telecom had up: with the agent's call still DIALING while the user was on a personal or VoIP call (the
+ * InCallService sees self-managed calls too), any of them could hang up the user's call.
+ */
+ private val telecomCalls = java.util.concurrent.ConcurrentHashMap()
+ /** The call placeCall just asked Telecom for, until Telecom reports it (or [CallBinding.WINDOW_MS] passes). */
+ private val placing = AtomicReference(null)
+ /**
+ * True when some other call existed when the live session dialed, or one has rung since. Only then can
+ * TelecomManager.endCall (which ends the foreground call, or rejects a ringing one) reach a call that is not ours.
+ */
+ @Volatile private var otherCall = false
+
+ /** The live call session, or null. Never [PLACEHOLDER]: that is a placeCall that has no session yet. */
+ fun currentSessionId(): String? = current.get()?.takeUnless { it == PLACEHOLDER }
/** Places a call; returns the session id or throws IllegalStateException with a machine-readable message. */
fun placeCall(target: String, displayName: String?, purpose: String?, audioRoute: String?, peerId: String?, correlationId: String, driverManaged: Boolean = false): Session {
if (context.checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) throw SecurityException("CALL_PHONE")
if (!E164.matches(target)) throw IllegalArgumentException("invalid_target")
// Single-call gate: claim the slot atomically before creating the session so concurrent requests cannot both dial.
+ // PLACEHOLDER is another request between claiming the slot and creating its session, so it is busy. It used to
+ // read as free (no session has that id), the CAS PLACEHOLDER -> PLACEHOLDER then succeeded, and both dialed.
val existingId = current.get()
+ if (existingId == PLACEHOLDER) throw IllegalStateException("call.busy:concurrent")
val existing = existingId?.let { sessions.get(it) }
if (existing != null && !existing.state.terminal) throw IllegalStateException("call.busy:${existing.sessionId}")
if (!current.compareAndSet(existingId, PLACEHOLDER)) throw IllegalStateException("call.busy:concurrent")
@@ -60,11 +79,16 @@ class CallSessions(
val tm = context.getSystemService(TelecomManager::class.java)
val uri = Uri.fromParts("tel", target, null)
+ // Both recorded before dialing: Telecom can report the new call (onTelecomCallAdded) before placeCall returns.
+ otherCall = runCatching { tm.isInCall }.getOrDefault(true)
+ val placed = CallBinding.Placed(session.sessionId, target, Ids.now())
+ placing.set(placed)
try {
tm.placeCall(uri, Bundle())
sessions.transition(session.sessionId, SessionState.DIALING, mapOf("number" to target))
} catch (t: Throwable) {
sessions.transition(session.sessionId, SessionState.FAILED, mapOf("reason" to (t.message ?: t.javaClass.simpleName)))
+ placing.compareAndSet(placed, null)
current.compareAndSet(session.sessionId, null)
throw IllegalStateException("call.failed:${t.message}")
}
@@ -85,10 +109,12 @@ class CallSessions(
/** Feed from the device-wide call state listener. */
fun onCallState(state: Int, number: String?) {
- val id = current.get() ?: return
+ val id = currentSessionId() ?: return
val s = sessions.get(id) ?: return
if (s.state.terminal) { current.compareAndSet(id, null); return }
when (state) {
+ // Ringing while ours is up is a second, incoming call: TelecomManager.endCall would now reject it.
+ TelephonyManager.CALL_STATE_RINGING -> otherCall = true
TelephonyManager.CALL_STATE_OFFHOOK -> {
// Without an InCallService there is no public signal separating "alerting" from "active":
// OFFHOOK is the earliest reliable "the network has the call" signal, so it maps to CONNECTED.
@@ -114,6 +140,7 @@ class CallSessions(
private fun finish(id: String, state: SessionState, reason: String) {
if (!finished.add(id)) return // IDLE callback and dial watchdog can both arrive; only the first finishes
timeoutJob?.cancel()
+ telecomCalls.remove(id)
val s = sessions.get(id) ?: return
val offhookMs = if (connectedAt > 0) Ids.now() - connectedAt else 0
sessions.transition(id, state, mapOf("reason" to reason, "offhook_ms" to offhookMs))
@@ -140,10 +167,13 @@ class CallSessions(
/*
* Takes the disconnect cause as a snapshot, not the Call: this runs on the runtime's call-events thread (the
* InCallService posts to it so finish()'s call-log wait never blocks the main thread), and by then Telecom
- * may have moved the Call on.
+ * may have moved the Call on. [sessionId] is the session bound to the Call that changed ([sessionFor]); the
+ * InCallService does not call this for other calls. It used to apply every call's state to the live session, so
+ * the user's own call disconnecting finished the agent's session.
*/
- fun onPreciseState(state: String, number: String?, disconnectCode: Int?, disconnectReason: String?) {
- val id = current.get() ?: return
+ fun onPreciseState(sessionId: String, state: String, number: String?, disconnectCode: Int?, disconnectReason: String?) {
+ val id = sessionId
+ if (current.get() != id) return
val s = sessions.get(id) ?: return
if (s.state.terminal) return
when (state) {
@@ -169,15 +199,25 @@ class CallSessions(
}
}
- /** Prefer Telecom's Call.disconnect() when we are the dialer; otherwise best-effort TelecomManager.endCall. */
+ /**
+ * Hang up this session's own call and nothing else. With our InCallService bound that is the session's Telecom
+ * Call ([telecomCallFor]). Without it the platform only has TelecomManager.endCall, which ends the FOREGROUND call
+ * (or rejects a ringing one): used only for the live session, and only when no other call existed at dial time
+ * and none has rung since ([otherCall]), so it cannot reach the user's call. Otherwise this throws
+ * IllegalStateException("call.unidentified") and touches no call.
+ */
fun endCall(id: String): Boolean {
val s = sessions.get(id) ?: throw IllegalArgumentException("session.unknown")
if (s.state.terminal) return true
- dev.symbiosis.runtime.telephony.SymbiosisInCallService.Holder.active()?.let { c ->
+ telecomCalls[id]?.let { c ->
sessions.transition(id, SessionState.ENDING)
c.disconnect()
return true
}
+ // Bound but not identified (Telecom has not reported our call yet, or its number did not match): every call
+ // Telecom has might be the user's. A call of ours reported after its session ended is hung up on arrival.
+ if (dev.symbiosis.runtime.telephony.SymbiosisInCallService.Holder.bound) throw IllegalStateException("call.unidentified")
+ if (id != currentSessionId() || otherCall) throw IllegalStateException("call.unidentified")
if (context.checkSelfPermission(Manifest.permission.ANSWER_PHONE_CALLS) != PackageManager.PERMISSION_GRANTED) throw SecurityException("ANSWER_PHONE_CALLS")
sessions.transition(id, SessionState.ENDING)
val tm = context.getSystemService(TelecomManager::class.java)
@@ -221,16 +261,39 @@ class CallSessions(
* and the dial watchdog all died with the process), so FAILED is the honest outcome. Returns the ids failed.
*/
fun failStale(reason: String = "process_restart"): List =
- sessions.active().filter { it.kind == "call" && !it.state.terminal && it.sessionId != current.get() }.mapNotNull { s ->
+ sessions.active().filter { it.kind == "call" && !it.state.terminal && it.sessionId != currentSessionId() }.mapNotNull { s ->
sessions.transition(s.sessionId, SessionState.FAILED, mapOf("reason" to reason)) ?: return@mapNotNull null
sessions.setSummary(s.sessionId, mapOf("outcome" to SessionState.FAILED.name, "reason" to reason, "target" to s.meta["target"]?.toString()?.trim('"')))
s.sessionId
}
fun endAll(reason: String) {
- current.get()?.let { id -> runCatching { endCall(id) }; finish(id, SessionState.CANCELLED, reason) }
+ currentSessionId()?.let { id -> runCatching { endCall(id) }; finish(id, SessionState.CANCELLED, reason) }
+ }
+
+ /**
+ * From the InCallService's onCallAdded (before it reports the call's first state): take [call] as the session's
+ * own if it is the one placeCall just dialed: outgoing, to the dialed number, within [CallBinding.WINDOW_MS].
+ * Returns the session it was bound to, or null. A match whose session already ended (dial watchdog, emergency
+ * stop, end_call before Telecom reported the call) is disconnected: it is ours, and nothing else would end it.
+ */
+ fun onTelecomCallAdded(call: android.telecom.Call, number: String?, outgoing: Boolean, now: Long = Ids.now()): String? {
+ val p = placing.get() ?: return null
+ if (!CallBinding.matches(p, number, outgoing, now) || !placing.compareAndSet(p, null)) return null
+ val s = sessions.get(p.sessionId)
+ if (s == null || s.state.terminal) { runCatching { call.disconnect() }; return null }
+ telecomCalls[p.sessionId] = call
+ return p.sessionId
}
+ /** The session [call] belongs to, or null for every call this runtime did not place (the user's own). */
+ fun sessionFor(call: android.telecom.Call): String? = telecomCalls.entries.firstOrNull { it.value === call }?.key
+
+ /** This session's own Telecom call, or null when it is not identified (or our InCallService is not bound). */
+ fun telecomCallFor(id: String): android.telecom.Call? = telecomCalls[id]
+
+ fun onTelecomCallRemoved(call: android.telecom.Call) { telecomCalls.entries.removeIf { it.value === call } }
+
private data class LogRow(val durationSec: Long, val type: String)
/** Most recent call-log row for the target within the last 10 minutes; the log is written shortly after IDLE. */
@@ -271,3 +334,29 @@ class CallSessions(
val E164 = Regex("^\\+?[0-9]{3,15}$")
}
}
+
+/** Which Telecom call a call session placed. Pure, so the rule is unit-testable. */
+object CallBinding {
+ /** A call this runtime just asked Telecom to place. */
+ data class Placed(val sessionId: String, val target: String, val placedAt: Long)
+
+ /** How long after placeCall Telecom may report the call and still be taken for ours. */
+ const val WINDOW_MS = 30_000L
+
+ /** Outgoing, to the number we dialed, reported within [WINDOW_MS] of dialing. */
+ fun matches(p: Placed, number: String?, outgoing: Boolean, addedAt: Long): Boolean =
+ outgoing && addedAt in p.placedAt..(p.placedAt + WINDOW_MS) && sameNumber(p.target, number)
+
+ /**
+ * Same digits, or with 7 or more digits one ending with the other: Telecom can report +15551234567 for a dialed
+ * 5551234567. Short numbers (service codes) must match exactly.
+ */
+ fun sameNumber(dialed: String, reported: String?): Boolean {
+ val a = dialed.filter(Char::isDigit)
+ val b = reported?.filter(Char::isDigit).orEmpty()
+ if (a.isEmpty() || b.isEmpty()) return false
+ if (a == b) return true
+ val (short, long) = if (a.length <= b.length) a to b else b to a
+ return short.length >= 7 && long.endsWith(short)
+ }
+}
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/sessions/SessionFrameCursor.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/sessions/SessionFrameCursor.kt
new file mode 100644
index 0000000..47197d1
--- /dev/null
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/sessions/SessionFrameCursor.kt
@@ -0,0 +1,87 @@
+package dev.symbiosis.runtime.sessions
+
+import dev.symbiosis.runtime.core.Ids
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.longOrNull
+import kotlinx.serialization.json.put
+
+/**
+ * What one /ws/sessions/{id} socket sends, in order, without duplicates and without silent holes.
+ *
+ * The socket subscribes to live frames FIRST and only then reads the persisted backlog ([backlog]); live frames that
+ * arrive meanwhile are de-duplicated by `seq` ([live]). Reading the backlog first, as the server used to, lost every
+ * frame emitted between the read and the subscription. Live frames come from a drop-oldest flow, so a slow socket
+ * can miss some: `seq` is contiguous per session, so a jump is a hole, and the hole is refilled from
+ * session_messages. Only when the refill would exceed one page does the socket send a `gap` frame instead
+ * (docs/protocol.md section 5.1); the client reconnects with `since_seq` to fetch it.
+ *
+ * Not thread-safe: one cursor per socket, driven from that socket's single writer coroutine.
+ *
+ * @param fetch persisted frames with seq > sinceSeq, ascending, at most `limit`, and whether more remain
+ * ([SessionManager.framesAfter]).
+ * @param headSeq the highest seq assigned on the session so far ([SessionManager.headSeq]).
+ */
+class SessionFrameCursor(
+ private val sessionId: String,
+ sinceSeq: Long,
+ private val fetch: (sinceSeq: Long, limit: Int) -> Pair, Boolean>,
+ private val headSeq: () -> Long,
+ private val page: Int = PAGE,
+ private val clock: () -> Long = Ids::now,
+) {
+ /** The highest seq this socket has accounted for: sent, or announced in a gap. */
+ var last: Long = sinceSeq.coerceAtLeast(0); private set
+
+ /** Persisted frames after the cursor (one page), then a `gap` covering the rest if more remain. */
+ fun backlog(): List {
+ val out = ArrayList()
+ // A since_seq beyond the head (a client's cursor from another session, or garbage) would otherwise make this
+ // socket skip every live frame until seq caught up with it.
+ headSeq().let { head -> if (last > head) last = head }
+ val (frames, more) = fetch(last, page)
+ for (f in frames) { val s = seqOf(f) ?: continue; if (s <= last) continue; out += f; last = s }
+ if (more) {
+ val head = headSeq()
+ if (head > last) { out += gap(last + 1, head); last = head }
+ }
+ return out
+ }
+
+ /** One live frame: nothing if already accounted for, else any refilled hole before it, then the frame. */
+ fun live(f: SessionFrame): List {
+ if (f.sessionId != sessionId || f.seq <= last) return emptyList()
+ val out = ArrayList()
+ if (f.seq > last + 1) {
+ // Frames last+1 .. f.seq-1 never reached this collector live: refill them from the store.
+ val (frames, more) = fetch(last, page)
+ var reachedLive = false
+ for (p in frames) {
+ val s = seqOf(p) ?: continue
+ if (s <= last) continue
+ if (s >= f.seq) { reachedLive = true; break }
+ out += p; last = s
+ }
+ if (!reachedLive && more && last < f.seq - 1) { out += gap(last + 1, f.seq - 1); last = f.seq - 1 }
+ }
+ out += f.toJson()
+ last = f.seq
+ return out
+ }
+
+ /**
+ * A `gap` frame: frames [from]..[to] were not sent on this socket. Its `seq` is the last frame delivered before
+ * the hole (from - 1), so a client that resumes from the highest seq it has seen re-fetches the hole.
+ */
+ private fun gap(from: Long, to: Long): JsonObject = buildJsonObject {
+ put("session_id", sessionId); put("seq", from - 1); put("ts", clock()); put("correlation_id", JsonPrimitive(null as String?))
+ put("type", "gap"); put("from_seq", from); put("to_seq", to)
+ put("hint", "reconnect with since_seq=${from - 1} to fetch the missing frames")
+ }
+
+ private fun seqOf(f: JsonObject): Long? = f["seq"]?.jsonPrimitive?.longOrNull
+
+ companion object { const val PAGE = 500 }
+}
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/sessions/SessionManager.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/sessions/SessionManager.kt
index de3f6ef..33bfd28 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/sessions/SessionManager.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/sessions/SessionManager.kt
@@ -46,9 +46,23 @@ data class SessionFrame(val sessionId: String, val seq: Long, val ts: Long, val
*/
class SessionManager(private val db: Db) {
private val seqs = ConcurrentHashMap()
- private val _frames = MutableSharedFlow(extraBufferCapacity = 512)
+ /**
+ * Live fan-out. DROP_OLDEST, not the default SUSPEND: with SUSPEND, one /ws/sessions socket that stopped reading
+ * filled the 512-frame buffer, `tryEmit` then failed, and the frame reached NO live socket, for every session.
+ * Now only the slow collector loses its oldest buffered frames. Every frame is persisted before it is published
+ * and `seq` is contiguous per session, so a socket sees the hole and refills it from session_messages
+ * ([SessionFrameCursor]).
+ */
+ private val _frames = MutableSharedFlow(extraBufferCapacity = 512, onBufferOverflow = kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST)
val frames: SharedFlow = _frames
+ /**
+ * session_id to owning peer id ("" for a session with no owner). The owner never changes after create, and
+ * session rows are never deleted (pruneFrames drops only their frames), so this is a cache of durable data: an
+ * ended session's events stay resolvable to their owner for as long as the journal keeps them.
+ */
+ private val owners = ConcurrentHashMap()
+
/** Hooks set by the runtime: audit + `session.state` events. */
var onTransition: ((Session, SessionState, SessionState) -> Unit)? = null
@@ -64,10 +78,20 @@ class SessionManager(private val db: Db) {
},
)
seqs[s.sessionId] = 0
+ owners[s.sessionId] = peerId ?: ""
emitFrame(s.sessionId, correlationId, "session.state", buildJsonObject { put("state", s.state.name); put("previous_state", JsonPrimitive(null as String?)); put("kind", kind) })
return s
}
+ /** The peer that owns session [id], or null when the session is unknown or has no owner (admin-only). */
+ fun ownerOf(id: String): String? {
+ val cached = owners[id] ?: get(id)?.let { s ->
+ if (owners.size >= MAX_CACHED_OWNERS) owners.clear()
+ (s.peerId ?: "").also { owners[id] = it }
+ }
+ return cached?.takeIf { it.isNotEmpty() }
+ }
+
fun get(id: String): Session? = db.readableDatabase.query("sessions", null, "session_id = ?", arrayOf(id), null, null, null).use { c -> if (c.moveToFirst()) row(c) else null }
fun active(): List = db.readableDatabase.query("sessions", null, "ended_at IS NULL", null, null, null, "created_at DESC").use { c ->
@@ -124,10 +148,13 @@ class SessionManager(private val db: Db) {
put("frame_json", Json.lenient.encodeToString(JsonObject.serializer(), f.toJson()))
},
)
- if (!_frames.tryEmit(f)) android.util.Log.w("SessionManager", "session frame buffer overflow: dropped live seq=$seq for $sessionId (persisted; clients replay with since_seq)")
+ _frames.tryEmit(f) // never fails with DROP_OLDEST; a collector that fell behind refills from session_messages
f
}
+ /** The highest seq assigned on [sessionId] so far (0 before its first frame). */
+ fun headSeq(sessionId: String): Long = synchronized(seqs) { seqs[sessionId] ?: lastSeq(sessionId) }
+
/** Frames after [sinceSeq]; `second` is true when more remain beyond [limit] (the caller should send a gap). */
fun framesAfter(sessionId: String, sinceSeq: Long, limit: Int = 500): Pair, Boolean> = db.readableDatabase.query(
"session_messages", arrayOf("frame_json"), "session_id = ? AND seq > ?", arrayOf(sessionId, sinceSeq.toString()), null, null, "seq ASC", (limit + 1).toString(),
@@ -150,6 +177,8 @@ class SessionManager(private val db: Db) {
put("meta", s.meta); put("summary", s.summary ?: JsonPrimitive(null as String?))
}
+ companion object { private const val MAX_CACHED_OWNERS = 10_000 }
+
private fun row(c: android.database.Cursor) = Session(
sessionId = c.getString(c.getColumnIndexOrThrow("session_id")),
kind = c.getString(c.getColumnIndexOrThrow("kind")),
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/storage/SecureStore.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/storage/SecureStore.kt
index 2dffb54..88a9378 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/storage/SecureStore.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/storage/SecureStore.kt
@@ -97,7 +97,11 @@ class SecureStore(context: Context) {
/** The admin bearer token. Created on first access. */
val adminToken: String get() = getOrCreate(K_ADMIN_TOKEN) { Ids.token() }
- fun rotateAdminToken(): String = Ids.token().also { prefs.edit().putString(K_ADMIN_TOKEN, it).apply() }
+ /**
+ * Replace the admin token (the app's "Rotate admin token" control, via Runtime.rotateAdminToken). Committed
+ * synchronously under the same lock as [getOrCreate], so the next authenticate() already sees the new value.
+ */
+ fun rotateAdminToken(): String = synchronized(this) { Ids.token().also { prefs.edit().putString(K_ADMIN_TOKEN, it).commit() } }
private companion object {
const val TAG = "SecureStore"
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/SymbiosisInCallService.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/SymbiosisInCallService.kt
index 5bcacdb..b278154 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/SymbiosisInCallService.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/SymbiosisInCallService.kt
@@ -15,14 +15,23 @@ import java.util.concurrent.ConcurrentHashMap
* the binding is what routes the full call audio to the app. Everything here is additive: the
* TelephonyCallback path keeps working when the service is not bound.
*
- * On a debug build with those privileged permissions granted, this promotes itself to a `microphone`
- * foreground service for the duration of a call so background capture is unrestricted (matches BCR).
+ * With RECORD_AUDIO granted, this promotes itself to a `microphone` foreground service for the duration of a call
+ * so background capture is unrestricted (matches BCR). This used to happen on debug builds only, a leftover from
+ * when the call-audio permissions lived in the debug manifest: conversation mode ships in release (the type and
+ * FOREGROUND_SERVICE_MICROPHONE are in the main manifest), and a release build with the screen off could not
+ * hear the far party.
*/
class SymbiosisInCallService : InCallService() {
override fun onCallAdded(call: Call) {
super.onCallAdded(call)
Holder.calls[call] = Unit
+ // Before the first state is reported: if this is the call a session just placed, bind it to that session so
+ // end/DTMF act on it and its states drive that session. Every other call (the user's own) stays unbound.
+ runCatching {
+ val d = call.details
+ Runtime.get(this).calls.onTelecomCallAdded(call, d.handle?.schemeSpecificPart, d.callDirection == Call.Details.DIRECTION_OUTGOING)
+ }.onFailure { android.util.Log.w("SymbiosisInCall", "call binding failed", it) }
call.registerCallback(callback)
emit(call, "added")
maybeStartMicForeground()
@@ -38,18 +47,19 @@ class SymbiosisInCallService : InCallService() {
call.unregisterCallback(callback)
Holder.calls.remove(call)
emit(call, "removed")
+ runCatching { Runtime.get(this).calls.onTelecomCallRemoved(call) }
if (Holder.calls.isEmpty()) stopMicForeground()
super.onCallRemoved(call)
}
private var micForeground = false
private fun maybeStartMicForeground() {
- if (micForeground || !dev.symbiosis.runtime.BuildConfig.DEBUG) return
+ if (micForeground) return
if (checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) != android.content.pm.PackageManager.PERMISSION_GRANTED) return
runCatching {
val nm = getSystemService(android.app.NotificationManager::class.java)
- nm.createNotificationChannel(android.app.NotificationChannel(FGS_CHANNEL, "Call audio research", android.app.NotificationManager.IMPORTANCE_LOW))
- val n = android.app.Notification.Builder(this, FGS_CHANNEL).setSmallIcon(android.R.drawable.ic_btn_speak_now).setContentTitle("Android Agent Harness call audio (research)").build()
+ nm.createNotificationChannel(android.app.NotificationChannel(FGS_CHANNEL, "Call audio", android.app.NotificationManager.IMPORTANCE_LOW))
+ val n = android.app.Notification.Builder(this, FGS_CHANNEL).setSmallIcon(android.R.drawable.ic_btn_speak_now).setContentTitle("Android Agent Harness call audio").build()
startForeground(FGS_ID, n, android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)
micForeground = true
}.onFailure { android.util.Log.w("SymbiosisInCall", "mic FGS start failed", it) }
@@ -93,6 +103,8 @@ class SymbiosisInCallService : InCallService() {
val causeCode = cause?.code
val causeReason = cause?.reason
val rt = runCatching { Runtime.get(this) }.getOrNull() ?: return
+ // The session this Call belongs to, or null: only a call bound in onCallAdded is ever attributed to a session.
+ val sessionId = rt.calls.sessionFor(call)
runCatching {
rt.callEvents.execute {
runCatching {
@@ -101,22 +113,24 @@ class SymbiosisInCallService : InCallService() {
mapOf(
"state" to state, "why" to why, "number" to number,
"direction" to if (incoming) "in" else "out",
- "session_id" to rt.calls.currentSessionId(),
+ "session_id" to sessionId,
"can_hold" to canHold, "can_mute" to canMute,
"disconnect_cause" to causeText,
),
)
- rt.calls.onPreciseState(state, number, causeCode, causeReason)
+ if (sessionId != null) rt.calls.onPreciseState(sessionId, state, number, causeCode, causeReason)
}.onFailure { android.util.Log.w("SymbiosisInCall", "precise state handling failed", it) }
}
}
}
- /** Static handle for capabilities: the live calls Telecom has handed us, or none when we are not the dialer. */
+ /**
+ * Static handle: the live calls Telecom has handed us, or none when we are not bound. These include the user's
+ * own calls; a capability acting on a session's call uses CallSessions.telecomCallFor, never a call picked from here.
+ */
object Holder {
val calls = ConcurrentHashMap()
@Volatile var audioState: CallAudioState? = null
- fun active(): Call? = calls.keys.firstOrNull { it.state == Call.STATE_ACTIVE } ?: calls.keys.firstOrNull { it.state != Call.STATE_DISCONNECTED }
fun ringing(): Call? = calls.keys.firstOrNull { it.state == Call.STATE_RINGING }
val bound: Boolean get() = instance != null
@Volatile var instance: SymbiosisInCallService? = null
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/Tts.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/Tts.kt
index 6fd18a4..1b70145 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/Tts.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/Tts.kt
@@ -92,30 +92,54 @@ object Tts {
}
}
-/** Minimal RIFF/WAVE reader — enough for what the TTS engine writes. */
+/** Minimal RIFF/WAVE reader: enough for what the TTS engine writes, and safe on what a caller sends (play_audio). */
object Wav {
data class Decoded(val pcm: ShortArray, val sourceRate: Int)
+ /** Sample rates accepted from a WAV header or a caller (raw PCM): telephony narrowband through 48 kHz. */
+ val RATES = 8_000..48_000
+
+ /**
+ * Longest audio accepted, after resampling. Bounds memory and how long one call can hold the uplink: a header
+ * claiming 1 Hz turned a small upload into an hours-long, gigabyte-sized resample.
+ */
+ const val MAX_SECONDS = 300
+
/** Decode to mono 16-bit and resample to [targetRate]. */
- fun decodeMono16(f: File, targetRate: Int): Decoded? = runCatching {
- val b = f.readBytes()
+ fun decodeMono16(f: File, targetRate: Int): Decoded? = runCatching { decodeMono16(f.readBytes(), targetRate) }.getOrNull()
+
+ /**
+ * [b] as mono 16-bit at [targetRate], or null if it is not a 16-bit PCM WAV with a rate in [RATES] and at most
+ * [MAX_SECONDS] long. Chunk sizes are unsigned 32-bit and are checked against the bytes actually present: read
+ * as a signed Int, a size of 0xFFFFFFF8 stepped the walk back to where it started and looped forever.
+ */
+ fun decodeMono16(b: ByteArray, targetRate: Int): Decoded? = runCatching {
if (b.size < 44) return null
- var i = 12
- var rate = targetRate; var channels = 1; var bits = 16
+ if (String(b, 0, 4, Charsets.US_ASCII) != "RIFF" || String(b, 8, 4, Charsets.US_ASCII) != "WAVE") return null
+ var i = 12L
+ var rate = -1; var channels = 0; var bits = 0
var dataOff = -1; var dataLen = 0
while (i + 8 <= b.size) {
- val id = String(b, i, 4, Charsets.US_ASCII)
- val size = le32(b, i + 4)
+ val at = i.toInt()
+ val id = String(b, at, 4, Charsets.US_ASCII)
+ val size = le32u(b, at + 4)
+ val remaining = b.size - (i + 8)
when (id) {
- "fmt " -> { channels = le16(b, i + 10); rate = le32(b, i + 12); bits = le16(b, i + 22) }
- "data" -> { dataOff = i + 8; dataLen = minOf(size, b.size - dataOff) }
+ "fmt " -> {
+ if (size < 16 || size > remaining) return null
+ channels = le16(b, at + 10); rate = le32(b, at + 12); bits = le16(b, at + 22)
+ }
+ // A streaming writer may leave the data size at 0xFFFFFFFF; what is present is what plays.
+ "data" -> { dataOff = at + 8; dataLen = minOf(size, remaining).toInt() }
+ else -> if (size > remaining) return null
}
if (dataOff >= 0) break
- i += 8 + size + (size and 1)
+ i += 8 + size + (size and 1) // Long: always advances, and past the end ends the walk
}
- if (dataOff < 0 || bits != 16 || channels < 1) return null
+ if (dataOff < 0 || bits != 16 || channels < 1 || rate !in RATES) return null
val frames = dataLen / 2 / channels
if (frames <= 0) return null
+ if (frames.toLong() > MAX_SECONDS.toLong() * rate) return null
val mono = ShortArray(frames)
for (n in 0 until frames) { // channel 0
val p = dataOff + n * 2 * channels
@@ -139,6 +163,8 @@ object Wav {
}
fun le16(b: ByteArray, i: Int) = (b[i].toInt() and 0xff) or ((b[i + 1].toInt() and 0xff) shl 8)
+ /** Unsigned little-endian 32-bit, for RIFF chunk sizes. */
+ fun le32u(b: ByteArray, i: Int): Long = le32(b, i).toLong() and 0xffff_ffffL
fun le32(b: ByteArray, i: Int) =
(b[i].toInt() and 0xff) or ((b[i + 1].toInt() and 0xff) shl 8) or
((b[i + 2].toInt() and 0xff) shl 16) or ((b[i + 3].toInt() and 0xff) shl 24)
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/TurnDetector.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/TurnDetector.kt
index d148f56..aecd8e4 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/TurnDetector.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/telephony/TurnDetector.kt
@@ -52,11 +52,16 @@ class TurnDetector private constructor(private val env: OrtEnvironment, private
const val WINDOW_SAMPLES = WINDOW_SECONDS * WhisperMel.SAMPLE_RATE
private const val INPUT = "input_features"
- fun fromBytes(model: ByteArray): TurnDetector {
+ /**
+ * [optimization] stays ALL_OPT on the phone. With it the QDQ int8 graph runs on fused integer kernels that
+ * ONNX Runtime picks per CPU, so x86 hosts without VNNI can differ from the reference; tests that compare
+ * against a fixed probability use NO_OPT, which executes the same graph as float math on every CPU.
+ */
+ fun fromBytes(model: ByteArray, optimization: OrtSession.SessionOptions.OptLevel = OrtSession.SessionOptions.OptLevel.ALL_OPT): TurnDetector {
val env = OrtEnvironment.getEnvironment()
val opts = OrtSession.SessionOptions().apply {
setIntraOpNumThreads(2)
- setOptimizationLevel(OrtSession.SessionOptions.OptLevel.ALL_OPT)
+ setOptimizationLevel(optimization)
}
return TurnDetector(env, env.createSession(model, opts))
}
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/transport/PeerStore.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/transport/PeerStore.kt
index 9d56b1f..e5a71c2 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/transport/PeerStore.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/transport/PeerStore.kt
@@ -67,9 +67,9 @@ class PeerStore(private val db: Db, private val secure: SecureStore) {
}
/**
- * What a "standard" agent gets: every read family, messaging and telephony (calls and texts still ask for the
- * user's tap unless the number is allowlisted), the screen, calendar, sensors, files. The ceiling is
- * EXTERNAL_COMMITMENT because place_call and send_sms live there; below that ceiling they are invisible
+ * What a "standard" agent gets: every read family, messaging and telephony (calls and texts run without a tap by
+ * default; "Ask me first" and the contact lists in PolicyConfig gate them), the screen, calendar, sensors, files. The ceiling is
+ * EXTERNAL_COMMITMENT because place_call, send_sms and notifications.reply live there; below that ceiling they are invisible
* (that is exactly what hid them from the first Hermes peer on 2026-09-18).
*/
fun mintStandardCode(): PairingCode = mintPairingCode(STANDARD_SCOPES, STANDARD_CEILING)
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/transport/Server.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/transport/Server.kt
index 86d8f32..4329cc4 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/transport/Server.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/transport/Server.kt
@@ -8,6 +8,7 @@ import dev.symbiosis.runtime.events.Event
import dev.symbiosis.runtime.events.FilterClause
import dev.symbiosis.runtime.events.Subscription
import dev.symbiosis.runtime.policy.ActionClass
+import dev.symbiosis.runtime.sessions.SessionFrameCursor
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.Application
@@ -47,6 +48,7 @@ import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ClosedReceiveChannelException
import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.flow.onSubscription
import kotlinx.coroutines.launch
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.json.JsonArray
@@ -92,6 +94,9 @@ class Server(private val runtime: Runtime, private val host: String, private val
private class SessionSocket(val peerId: String, val ws: DefaultWebSocketServerSession)
private val sessionSockets = ConcurrentHashMap()
+ /** Owner of a session named in an event payload, for [Principal.canSeeEvent]. */
+ private val sessionOwner: (String) -> String? = { runtime.sessions.ownerOf(it) }
+
init {
runtime.subscriptions.onReplayed = { peerId, subId -> eventSockets.values.filter { it.principal.peerId == peerId }.forEach { it.gaps.remove(subId) } }
}
@@ -259,10 +264,19 @@ class Server(private val runtime: Runtime, private val host: String, private val
// cannot leave a phantom socket behind (the driver lease would read it as the driver still being there).
try {
val since = call.request.queryParameters["since_seq"]?.toLongOrNull() ?: 0
- val (frames, more) = runtime.sessions.framesAfter(id, since)
- for (f in frames) send(Json.lenient.encodeToString(JsonElement.serializer(), f))
- if (more) send(Json.lenient.encodeToString(JsonElement.serializer(), buildJsonObject { put("session_id", id); put("type", "gap"); put("from_seq", (frames.lastOrNull()?.get("seq")?.jsonPrimitive?.longOrNull ?: since) + 1); put("hint", "reconnect with since_seq to continue") }))
- job = launch { runtime.sessions.frames.collect { f -> if (f.sessionId == id) runCatching { send(Json.lenient.encodeToString(JsonElement.serializer(), f.toJson())) } } }
+ // Subscribe to live frames BEFORE reading the backlog (onSubscription runs once the collector is
+ // registered), and let the cursor de-duplicate by seq: reading the backlog first lost every frame emitted
+ // in between. The cursor also refills frames this collector missed because it was slow (the flow drops a
+ // slow collector's oldest frames rather than stalling every socket) and sends `gap` when it cannot.
+ val cursor = SessionFrameCursor(id, since, { after, limit -> runtime.sessions.framesAfter(id, after, limit) }, { runtime.sessions.headSeq(id) })
+ suspend fun sendAll(frames: List) { for (f in frames) send(Json.lenient.encodeToString(JsonElement.serializer(), f)) }
+ job = launch {
+ runCatching {
+ runtime.sessions.frames
+ .onSubscription { sendAll(cursor.backlog()) }
+ .collect { f -> if (f.sessionId == id) sendAll(cursor.live(f)) }
+ }
+ }
for (frame in incoming) {
if (frame !is Frame.Text) continue
val msg = runCatching { Json.lenient.parseToJsonElement(frame.readText()) as JsonObject }.getOrNull() ?: continue
@@ -303,13 +317,15 @@ class Server(private val runtime: Runtime, private val host: String, private val
var encoded: JsonElement? = null
val version = runtime.subscriptions.version
for (sock in eventSockets.values) {
- if (!sock.principal.canSeeTopic(ev.topic)) continue
+ if (!sock.principal.canSeeEvent(ev, sessionOwner)) continue
if (sock.subsVersion != version) { sock.subs = runtime.subscriptions.listFor(sock.principal.peerId); sock.subsVersion = version }
for (sub in sock.subs) {
if (sub.delivery == "queue") continue // replay-only by contract (protocol.md §4.3)
if (sub.expired() || !sub.matches(ev)) continue
val sid = sub.subscription_id
- if (sock.gaps.containsKey(sid)) { sock.gaps[sid]!![1] = ev.id; continue } // paused until the client replays
+ // Paused until the client replays. One lookup: replay can remove the gap between a containsKey and a get.
+ val paused = sock.gaps[sid]
+ if (paused != null) { paused[1] = ev.id; continue }
if (encoded == null) encoded = Json.lenient.encodeToJsonElement(Event.serializer(), ev)
val frame = buildJsonObject { put("type", "event"); put("subscription_id", sid); put("event", encoded) }
if (!sock.outbound.trySend(frame).isSuccess) {
@@ -389,7 +405,7 @@ class Server(private val runtime: Runtime, private val host: String, private val
val sid = msg["subscription_id"]?.jsonPrimitive?.contentOrNull ?: return reply(err("invalid_params", "subscription_id is required"))
val sub = runtime.subscriptions.get(principal.peerId, sid) ?: return reply(err("subscription.unknown", sid))
val since = msg["since_id"]?.jsonPrimitive?.longOrNull ?: sub.ack_cursor
- val r = runtime.subscriptions.replay(sub, since, (msg["limit"]?.jsonPrimitive?.longOrNull ?: 200L).toInt()) { principal.canSeeTopic(it.topic) }
+ val r = runtime.subscriptions.replay(sub, since, (msg["limit"]?.jsonPrimitive?.longOrNull ?: 200L).toInt()) { principal.canSeeEvent(it, sessionOwner) }
sock.gaps.remove(sid) // live push resumes after a replay
reply(
buildJsonObject {
diff --git a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/ui/MainActivity.kt b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/ui/MainActivity.kt
index 27daffe..55b11e2 100644
--- a/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/ui/MainActivity.kt
+++ b/android-runtime/app/src/main/kotlin/dev/symbiosis/runtime/ui/MainActivity.kt
@@ -34,6 +34,8 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
+import androidx.compose.ui.semantics.isSensitiveData
+import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import dev.symbiosis.runtime.core.Runtime
@@ -67,6 +69,9 @@ class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
+ // The admin token, pairing codes and approvals are on this screen: no screenshots, screen recording or
+ // MediaProjection capture of it (ui.screenshot included), and it is blanked in Recents.
+ window.setFlags(android.view.WindowManager.LayoutParams.FLAG_SECURE, android.view.WindowManager.LayoutParams.FLAG_SECURE)
val runtime = Runtime.get(this)
if (RuntimeService.isEnabled(this)) RuntimeService.start(this)
if (intent?.getBooleanExtra(EXTRA_REQUEST_DIALER_ROLE, false) == true) requestDialerRole()
@@ -87,6 +92,9 @@ class MainActivity : ComponentActivity() {
dev.symbiosis.runtime.policy.PolicyDecision.APPROVE
var tick by remember { mutableStateOf(0) }
var showToken by remember { mutableStateOf(false) }
+ var tokenVersion by remember { androidx.compose.runtime.mutableIntStateOf(0) }
+ // API 34+: hidden from accessibility services that are not accessibility tools (our own ui.* service included).
+ val sensitive = Modifier.semantics { isSensitiveData = true }
var pairingCode by remember { mutableStateOf(null) }
var chainState by remember { mutableStateOf("not checked") }
val scope = androidx.compose.runtime.rememberCoroutineScope()
@@ -117,9 +125,17 @@ class MainActivity : ComponentActivity() {
}
Text("From a workstation: adb forward tcp:8765 tcp:8765, then POST http://127.0.0.1:8765/mcp", style = MaterialTheme.typography.bodySmall)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
- OutlinedButton(onClick = { showToken = !showToken }) { Text(if (showToken) "Hide admin token" else "Show admin token") }
+ OutlinedButton(modifier = sensitive, onClick = { showToken = !showToken }) { Text(if (showToken) "Hide admin token" else "Show admin token") }
+ // A leaked admin token is revoked by replacing it: the old one stops working and its connections close.
+ OutlinedButton(modifier = sensitive, onClick = {
+ scope.launch {
+ kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { runtime.rotateAdminToken() }
+ tokenVersion++
+ android.widget.Toast.makeText(this@MainActivity, "Admin token replaced. Clients using the old one are disconnected.", android.widget.Toast.LENGTH_LONG).show()
+ }
+ }) { Text("Rotate admin token") }
}
- if (showToken) Text(runtime.secure.adminToken, fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall)
+ if (showToken) Text(remember(tokenVersion) { runtime.secure.adminToken }, modifier = sensitive, fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodySmall)
HorizontalDivider()
var lan by remember { mutableStateOf(RuntimeService.isLanExposed(this@MainActivity)) }
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
@@ -133,15 +149,15 @@ class MainActivity : ComponentActivity() {
Section("Safety") {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text(if (estop) "EMERGENCY STOP engaged" else "Emergency stop")
- Switch(checked = estop, onCheckedChange = { runtime.policy.setEmergencyStop(it) })
+ Switch(checked = estop, modifier = sensitive, onCheckedChange = { runtime.policy.setEmergencyStop(it) })
}
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text("Observe-only (read tools only)")
- Switch(checked = observe, onCheckedChange = { runtime.policy.setObserveOnly(it) })
+ Switch(checked = observe, modifier = sensitive, onCheckedChange = { runtime.policy.setObserveOnly(it) })
}
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text("Ask me first: texts, calls, screen control")
- Switch(checked = asksFirst, onCheckedChange = { runtime.policy.setAsksFirst(it) })
+ Switch(checked = asksFirst, modifier = sensitive, onCheckedChange = { runtime.policy.setAsksFirst(it) })
}
Text(
if (asksFirst) "Each one waits for your Approve tap here or in a notification."
@@ -153,12 +169,12 @@ class MainActivity : ComponentActivity() {
Section("Pair an agent") {
Text("Mint a one-time code (5 min). The agent POSTs it to /pair and receives a scoped token.", style = MaterialTheme.typography.bodySmall)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
- Button(onClick = {
+ Button(modifier = sensitive, onClick = {
pairingCode = runtime.peers.mintStandardCode().code
}) { Text("Standard agent") }
- OutlinedButton(onClick = { pairingCode = runtime.peers.mintPairingCode(listOf("*"), ActionClass.DEVICE_MUTATION).code }) { Text("Full access") }
+ OutlinedButton(modifier = sensitive, onClick = { pairingCode = runtime.peers.mintPairingCode(listOf("*"), ActionClass.DEVICE_MUTATION).code }) { Text("Full access") }
}
- pairingCode?.let { Text(it, style = MaterialTheme.typography.headlineSmall, fontFamily = FontFamily.Monospace) }
+ pairingCode?.let { Text(it, modifier = sensitive, style = MaterialTheme.typography.headlineSmall, fontFamily = FontFamily.Monospace) }
}
Section("Permissions") {
@@ -174,10 +190,18 @@ class MainActivity : ComponentActivity() {
if (pending.isNotEmpty()) Section("Pending approvals (${pending.size})") {
pending.forEach { pa ->
- Text("${pa.capability} · ${pa.actionClass} · ${pa.args.entries.take(2).joinToString { (k, v) -> "$k=$v" }}", style = MaterialTheme.typography.bodySmall)
+ // Every argument in full, target and body first, undeclared ones flagged (policy/ApprovalSummary.kt).
+ Text("${pa.capability} · ${pa.actionClass}", modifier = sensitive, style = MaterialTheme.typography.bodyMedium)
+ Text(dev.symbiosis.runtime.policy.ApprovalSummary.format(runtime.registry.get(pa.capability), pa.args).ifEmpty { "no arguments" }, modifier = sensitive, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
- Button(onClick = { scope.launch { runtime.resolveApproval(pa.id, true, "ui"); tick++ } }) { Text("Approve") }
- OutlinedButton(onClick = { scope.launch { runtime.resolveApproval(pa.id, false, "ui"); tick++ } }) { Text("Deny") }
+ Button(modifier = sensitive, onClick = {
+ scope.launch {
+ val why = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { runtime.resolveApproval(pa.id, true, "ui") }
+ if (why == Runtime.APPROVAL_IGNORED_SCREEN_CONTROL) android.widget.Toast.makeText(this@MainActivity, "Not approved: an agent used screen control in the last 10 seconds. Tap Approve again shortly.", android.widget.Toast.LENGTH_LONG).show()
+ tick++
+ }
+ }) { Text("Approve") }
+ OutlinedButton(modifier = sensitive, onClick = { scope.launch { kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { runtime.resolveApproval(pa.id, false, "ui") }; tick++ } }) { Text("Deny") }
}
}
}
diff --git a/android-runtime/app/src/main/res/xml/backup_rules.xml b/android-runtime/app/src/main/res/xml/backup_rules.xml
new file mode 100644
index 0000000..cf56d69
--- /dev/null
+++ b/android-runtime/app/src/main/res/xml/backup_rules.xml
@@ -0,0 +1,14 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/android-runtime/app/src/main/res/xml/data_extraction_rules.xml b/android-runtime/app/src/main/res/xml/data_extraction_rules.xml
new file mode 100644
index 0000000..ed64ff4
--- /dev/null
+++ b/android-runtime/app/src/main/res/xml/data_extraction_rules.xml
@@ -0,0 +1,31 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/CallSessionGateTest.kt b/android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/CallSessionGateTest.kt
new file mode 100644
index 0000000..52fa531
--- /dev/null
+++ b/android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/CallSessionGateTest.kt
@@ -0,0 +1,130 @@
+package dev.symbiosis.runtime
+
+import android.Manifest
+import android.app.Application
+import android.telecom.TelecomManager
+import androidx.test.core.app.ApplicationProvider
+import dev.symbiosis.runtime.events.EventBroker
+import dev.symbiosis.runtime.sessions.CallBinding
+import dev.symbiosis.runtime.sessions.CallSessions
+import dev.symbiosis.runtime.sessions.SessionManager
+import dev.symbiosis.runtime.sessions.SessionState
+import dev.symbiosis.runtime.storage.Db
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.annotation.Config
+import java.util.concurrent.atomic.AtomicReference
+
+/** The single-call gate, and which Telecom call a session may act on. */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class CallSessionGateTest {
+ private lateinit var app: Application
+ private lateinit var db: Db
+ private lateinit var sessions: SessionManager
+ private lateinit var calls: CallSessions
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+
+ @Before fun setUp() {
+ app = ApplicationProvider.getApplicationContext()
+ app.deleteDatabase("symbiosis.db")
+ shadowOf(app).grantPermissions(Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ANSWER_PHONE_CALLS)
+ db = Db(app)
+ sessions = SessionManager(db)
+ calls = CallSessions(app, sessions, EventBroker(db, "dev_test"), scope)
+ }
+
+ @After fun tearDown() { scope.cancel() }
+
+ private fun telecom() = shadowOf(app.getSystemService(TelecomManager::class.java))
+ private fun place(target: String = "+15551234567") = calls.placeCall(target, null, null, null, "peer_a", "corr_test")
+
+ private fun busyCode(block: () -> Unit): String? = try { block(); null } catch (e: IllegalStateException) { e.message }
+
+ @Suppress("UNCHECKED_CAST")
+ private fun slot(): AtomicReference =
+ CallSessions::class.java.getDeclaredField("current").apply { isAccessible = true }.get(calls) as AtomicReference
+
+ @Test fun `a request that finds another one mid-placement is busy and does not dial`() {
+ // Request A has claimed the slot but not yet created its session: B used to read that as free and dial too.
+ slot().set("call_placing")
+ assertEquals("call.busy:concurrent", busyCode { place() })
+ assertTrue(telecom().allOutgoingCalls.isEmpty())
+ assertTrue(sessions.recent().isEmpty())
+ assertNull(calls.currentSessionId()) // the placeholder is never reported as a session
+ }
+
+ @Test fun `a second call while one is live is busy`() {
+ val first = place()
+ assertEquals("call.busy:${first.sessionId}", busyCode { place("+15559876543") })
+ assertEquals(1, telecom().allOutgoingCalls.size)
+ }
+
+ @Test fun `concurrent placements dial at most once`() {
+ val results = (1..8).map { i -> Thread { runCatching { place("+1555000000$i") } } }
+ results.forEach { it.start() }; results.forEach { it.join() }
+ assertEquals(1, telecom().allOutgoingCalls.size)
+ }
+
+ @Test fun `end_call without an identified call refuses when another call was up at dial time`() {
+ // No InCallService is bound under Robolectric, so the only way to hang up is TelecomManager.endCall, which ends
+ // the foreground call: with the user already on a call that may be theirs, so nothing is touched.
+ telecom().setIsInCall(true)
+ val s = place()
+ assertEquals("call.unidentified", busyCode { calls.endCall(s.sessionId) })
+ assertEquals(SessionState.DIALING, sessions.get(s.sessionId)!!.state)
+ }
+
+ @Test fun `end_call refuses a session that is not the live call`() {
+ val stale = sessions.create("call", "peer_a", "corr_old", emptyMap())
+ sessions.transition(stale.sessionId, SessionState.ACTIVE)
+ place()
+ assertEquals("call.unidentified", busyCode { calls.endCall(stale.sessionId) })
+ assertEquals(SessionState.ACTIVE, sessions.get(stale.sessionId)!!.state)
+ }
+
+ @Test fun `an incoming call while ours is up blocks the foreground-call fallback`() {
+ val s = place()
+ calls.onCallState(android.telephony.TelephonyManager.CALL_STATE_RINGING, "+15550001111")
+ assertEquals("call.unidentified", busyCode { calls.endCall(s.sessionId) })
+ }
+
+ @Test fun `end_call with no other call uses the platform fallback`() {
+ val s = place()
+ try { calls.endCall(s.sessionId) } catch (e: IllegalStateException) { fail("should not refuse: ${e.message}") }
+ assertEquals(SessionState.ENDING, sessions.get(s.sessionId)!!.state)
+ }
+
+ @Test fun `binding takes only our outgoing call to the dialed number, soon after dialing`() {
+ val p = CallBinding.Placed("call_1", "+15551234567", 1_000_000)
+ assertTrue(CallBinding.matches(p, "+15551234567", outgoing = true, addedAt = 1_000_100))
+ assertTrue(CallBinding.matches(p, "5551234567", outgoing = true, addedAt = 1_000_100)) // national form
+ assertTrue(CallBinding.matches(p, "+1 (555) 123-4567", outgoing = true, addedAt = 1_000_100))
+ assertFalse(CallBinding.matches(p, "+15551234567", outgoing = false, addedAt = 1_000_100)) // incoming
+ assertFalse(CallBinding.matches(p, "+15559999999", outgoing = true, addedAt = 1_000_100)) // the user's call
+ assertFalse(CallBinding.matches(p, null, outgoing = true, addedAt = 1_000_100))
+ assertFalse(CallBinding.matches(p, "+15551234567", outgoing = true, addedAt = 999_000)) // before we dialed
+ assertFalse(CallBinding.matches(p, "+15551234567", outgoing = true, addedAt = 1_000_000 + CallBinding.WINDOW_MS + 1))
+ // Short codes match exactly only: 911 must not match a number that merely ends in 911.
+ assertTrue(CallBinding.sameNumber("611", "611"))
+ assertFalse(CallBinding.sameNumber("611", "5555550611"))
+ }
+
+ @Test fun `no call is attributed to a session until Telecom reports it`() {
+ val s = place()
+ assertNull(calls.telecomCallFor(s.sessionId))
+ }
+}
diff --git a/android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/SelfProtectionTest.kt b/android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/SelfProtectionTest.kt
new file mode 100644
index 0000000..aa4e454
--- /dev/null
+++ b/android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/SelfProtectionTest.kt
@@ -0,0 +1,247 @@
+package dev.symbiosis.runtime
+
+import android.Manifest
+import android.app.Application
+import android.content.Context
+import android.os.Process
+import android.service.notification.StatusBarNotification
+import androidx.core.app.NotificationCompat
+import androidx.core.app.Person
+import androidx.test.core.app.ApplicationProvider
+import dev.symbiosis.runtime.capabilities.CallContext
+import dev.symbiosis.runtime.capabilities.Capability
+import dev.symbiosis.runtime.capabilities.CapabilityResult
+import dev.symbiosis.runtime.capabilities.DroidMcpAdapter
+import dev.symbiosis.runtime.capabilities.Param
+import dev.symbiosis.runtime.capabilities.ScreenControlWindow
+import dev.symbiosis.runtime.capabilities.SelfProtection
+import dev.symbiosis.runtime.core.Runtime
+import dev.symbiosis.runtime.policy.ActionClass
+import dev.symbiosis.runtime.policy.ApprovalSummary
+import dev.symbiosis.runtime.policy.PolicyEngine
+import dev.symbiosis.runtime.policy.PolicyOutcome
+import dev.symbiosis.runtime.policy.RateClass
+import dev.symbiosis.runtime.policy.RateLimiter
+import dev.symbiosis.runtime.transport.PeerStore
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.annotation.Config
+import java.util.concurrent.atomic.AtomicInteger
+
+/**
+ * The 2026-10 hardening: agents cannot drive this app's own screens or notifications, an approval right after
+ * screen control is ignored, the approval prompt orders arguments itself, notifications.reply obeys "Ask me first"
+ * and the contact lists, and the admin token can be rotated.
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class SelfProtectionTest {
+ private lateinit var app: Application
+ private lateinit var runtime: Runtime
+ private val own = "dev.symbiosis.runtime"
+
+ @Before fun setUp() {
+ app = ApplicationProvider.getApplicationContext()
+ app.deleteDatabase("symbiosis.db")
+ shadowOf(app).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)
+ SelfProtection.startedActivities.set(0)
+ runtime = Runtime::class.java.getDeclaredConstructor(Context::class.java).let { it.isAccessible = true; it.newInstance(app) }
+ }
+
+ @After fun tearDown() {
+ SelfProtection.startedActivities.set(0)
+ if (::runtime.isInitialized) { runtime.scope.cancel(); runtime.callEvents.shutdownNow(); runtime.db.close() }
+ }
+
+ private fun inert(name: String, cls: ActionClass, runs: AtomicInteger, params: List = emptyList()) =
+ Capability(name, "inert test", params, cls, rateClass = RateClass.MUTATION) { _, _ -> runs.incrementAndGet(); CapabilityResult.ok(mapOf("ran" to true)) }
+
+ private fun errorOf(body: kotlinx.serialization.json.JsonObject): String? =
+ body["structuredContent"]!!.jsonObject["error"]?.jsonPrimitive?.content
+
+ // ---- self protection ------------------------------------------------------------------------
+
+ @Test fun `screen control is refused only while our window shows`() {
+ assertEquals(SelfProtection.CODE, SelfProtection.refusal("ui.get_tree", emptyMap(), own) { true }?.errorCode)
+ assertEquals(SelfProtection.CODE, SelfProtection.refusal("ui.screenshot", emptyMap(), own) { true }?.errorCode)
+ assertEquals(SelfProtection.CODE, SelfProtection.refusal("ui.double_tap", emptyMap(), own) { true }?.errorCode)
+ assertNull(SelfProtection.refusal("ui.find_and_tap", emptyMap(), own) { false })
+ // The window query only runs for screen-control tools.
+ assertNull(SelfProtection.refusal("device.get_battery", emptyMap(), own) { error("must not query windows") })
+ }
+
+ @Test fun `apps cannot open us and notification tools cannot touch our notifications`() {
+ for (tool in listOf("apps.launch", "apps.open_deep_link", "apps.send_intent")) {
+ assertEquals(SelfProtection.CODE, SelfProtection.refusal(tool, mapOf("package_name" to own), own) { false }?.errorCode)
+ assertNull(SelfProtection.refusal(tool, mapOf("package_name" to "com.example.app"), own) { false })
+ }
+ val ourKey = "0|$own|1234|null|10123"
+ assertEquals(own, SelfProtection.notificationPackage(ourKey))
+ assertNull(SelfProtection.notificationPackage("garbage"))
+ for (tool in SelfProtection.NOTIFICATION_KEY_TOOLS) {
+ assertEquals(SelfProtection.CODE, SelfProtection.refusal(tool, mapOf("key" to ourKey), own) { false }?.errorCode)
+ assertNull(SelfProtection.refusal(tool, mapOf("key" to "0|com.google.android.apps.messaging|7|null|10200"), own) { false })
+ }
+ }
+
+ @Test fun `the pipeline refuses ui calls while one of our activities is started`() = runBlocking {
+ val admin = runtime.peers.adminPrincipal
+ val runs = AtomicInteger()
+ val cap = inert("ui.test_tap", ActionClass.DEVICE_MUTATION, runs)
+ SelfProtection.startedActivities.set(1)
+ val refused = runtime.invoke(admin, cap, emptyMap(), CallContext(admin.peerId, "self-1", principal = admin))
+ assertEquals(SelfProtection.CODE, errorOf(refused))
+ assertEquals(0, runs.get())
+ assertFalse("a refused call is not screen control", runtime.screenControl.recentlyUsed())
+
+ SelfProtection.startedActivities.set(0)
+ val ok = runtime.invoke(admin, cap, emptyMap(), CallContext(admin.peerId, "self-2", principal = admin))
+ assertNull(errorOf(ok))
+ assertEquals(1, runs.get())
+ assertTrue("an executed ui call opens the approval guard window", runtime.screenControl.recentlyUsed())
+ }
+
+ // ---- approvals after screen control -----------------------------------------------------------
+
+ @Test fun `screen control window lasts ten seconds from the last mark`() {
+ var now = 1_000_000L
+ val w = ScreenControlWindow { now }
+ assertFalse(w.recentlyUsed())
+ w.mark()
+ now += ScreenControlWindow.WINDOW_MS - 1
+ assertTrue(w.recentlyUsed())
+ now += 1
+ assertFalse(w.recentlyUsed())
+ w.mark()
+ assertTrue(w.recentlyUsed())
+ }
+
+ @Test fun `an approval right after screen control is ignored and left pending`() = runBlocking {
+ val (pa, _) = runtime.approvals.createAndAwait("messaging.send_sms", ActionClass.EXTERNAL_COMMITMENT, mapOf("to" to "+15125550100", "body" to "hi"), PeerStore.ADMIN_ID, "corr", 60_000, "test", waitMs = 0)
+ runtime.screenControl.mark()
+ assertEquals(Runtime.APPROVAL_IGNORED_SCREEN_CONTROL, runtime.resolveApproval(pa.id, true, "notification"))
+ assertEquals(Runtime.APPROVAL_IGNORED_SCREEN_CONTROL, runtime.resolveApproval(pa.id, true, "ui"))
+ assertEquals("pending", runtime.approvals.get(pa.id)!!.status)
+ val audited = runtime.audit.recent(20).any { it.errorCode == Runtime.APPROVAL_IGNORED_SCREEN_CONTROL }
+ assertTrue(audited)
+ // A denial is never ignored.
+ assertNull(runtime.resolveApproval(pa.id, false, "ui"))
+ assertEquals("denied", runtime.approvals.get(pa.id)!!.status)
+ }
+
+ // ---- approval summary --------------------------------------------------------------------------
+
+ @Test fun `approval summary puts target and body first in full and flags undeclared args`() {
+ val sms = Capability("messaging.send_sms", "", listOf(Param("to", "string", "", true), Param("body", "string", "", true)),
+ ActionClass.EXTERNAL_COMMITMENT, targetArg = "to") { _, _ -> CapabilityResult.ok(emptyMap()) }
+ val longBody = "Transfer approved, reference " + "x".repeat(200)
+ // Decoys first, as an agent would order them to fill a three-argument, 40-character preview.
+ val args = linkedMapOf("a_note" to "Hi mom, see you at 6", "b_note" to "nothing to see", "c" to "here", "body" to longBody, "to" to "+15125550199")
+ val lines = ApprovalSummary.lines(sms, args)
+ assertEquals(listOf("to", "body", "a_note", "b_note", "c"), lines.map { it.key })
+ assertEquals("\"+15125550199\"", lines[0].value)
+ assertTrue(lines[1].value.contains(longBody))
+ assertEquals(listOf(true, true, false, false, false), lines.map { it.declared })
+ assertTrue(ApprovalSummary.format(lines).contains("a_note (undeclared): "))
+
+ // A value cannot draw a fake line or hide behind bidi controls.
+ val text = ApprovalSummary.format(sms, mapOf("to" to "+15125550199", "body" to "ok\nto: +15125550100"))
+ assertEquals(2, text.lines().size)
+ assertFalse(text.contains(''))
+
+ // Unknown capability: everything is undeclared.
+ assertTrue(ApprovalSummary.lines(null, mapOf("x" to 1)).all { !it.declared })
+ // A resolver-backed tool shows who it reaches first.
+ val reply = Capability("notifications.reply", "", listOf(Param("key", "string", "", true), Param("text", "string", "", true)),
+ ActionClass.EXTERNAL_COMMITMENT, targetResolver = { listOf("Mom", "+15125550100") }) { _, _ -> CapabilityResult.ok(emptyMap()) }
+ val r = ApprovalSummary.lines(reply, mapOf("key" to "k", "text" to "hello"))
+ assertEquals(listOf(ApprovalSummary.RECIPIENT, "text", "key"), r.map { it.key })
+ assertEquals("\"Mom\", \"+15125550100\"", r[0].value)
+ }
+
+ // ---- notifications.reply under policy -----------------------------------------------------------
+
+ @Test fun `notifications reply is an external commitment that obeys contact lists`() {
+ val meta = DroidMcpAdapter.MAPPING.getValue("reply_to_notification")
+ assertEquals(ActionClass.EXTERNAL_COMMITMENT, meta.actionClass)
+ assertNotNull(meta.targetResolver)
+
+ var who = listOf("Mom", "+15125550100")
+ val reply = Capability("notifications.reply", "", emptyList(), ActionClass.EXTERNAL_COMMITMENT, rateClass = RateClass.SMS,
+ targetResolver = { who }) { _, _ -> CapabilityResult.ok(emptyMap()) }
+ val engine = PolicyEngine(runtime.db, RateLimiter(runtime.db))
+ val args = mapOf("key" to "0|com.google.android.apps.messaging|1|null|10200", "text" to "hi")
+
+ engine.setAsksFirst(true)
+ assertTrue("Ask me first covers it", engine.evaluate(reply, args) is PolicyOutcome.Approve)
+ engine.setAsksFirst(false)
+ assertTrue(engine.evaluate(reply, args) is PolicyOutcome.Allow)
+
+ engine.updateConfig(engine.config.value.copy(contactDenylist = listOf("5125550100")))
+ assertTrue("a denylisted sender number is denied", engine.evaluate(reply, args) is PolicyOutcome.Deny)
+ engine.updateConfig(engine.config.value.copy(contactDenylist = listOf("mom")))
+ assertTrue("a denylisted sender name is denied", engine.evaluate(reply, args) is PolicyOutcome.Deny)
+
+ engine.updateConfig(engine.config.value.copy(contactDenylist = emptyList(), contactAllowlist = listOf("+15125550100")))
+ assertTrue("only one of the identities is allowlisted", engine.evaluate(reply, args) is PolicyOutcome.Approve)
+ engine.updateConfig(engine.config.value.copy(contactAllowlist = listOf("+15125550100", "Mom")))
+ assertTrue(engine.evaluate(reply, args) is PolicyOutcome.Allow)
+ who = listOf("Dad")
+ assertTrue("a different name is not the same target", engine.evaluate(reply, args) is PolicyOutcome.Approve)
+ who = emptyList()
+ val unknown = engine.evaluate(reply, args)
+ assertTrue("an unresolvable sender is not on the allowlist", unknown is PolicyOutcome.Approve && unknown.reason.contains("unknown"))
+ engine.updateConfig(engine.config.value.copy(contactAllowlist = emptyList()))
+ assertTrue(engine.evaluate(reply, args) is PolicyOutcome.Allow)
+ assertFalse(PolicyEngine.sameTarget("Mom", "Dad"))
+ assertTrue(PolicyEngine.sameTarget("+1 (512) 555-0100", "5125550100"))
+ }
+
+ @Test fun `a notification's sender is resolved from the listener store`() {
+ val sender = Person.Builder().setName("Mom").setUri("tel:+15125550100").build()
+ val me = Person.Builder().setName("Me").build()
+ val n = NotificationCompat.Builder(app, "test")
+ .setSmallIcon(android.R.drawable.ic_dialog_info)
+ .setContentTitle("Mom")
+ .setStyle(NotificationCompat.MessagingStyle(me).addMessage("dinner?", 1L, sender))
+ .build()
+ @Suppress("DEPRECATION")
+ val sbn = StatusBarNotification("com.google.android.apps.messaging", "com.google.android.apps.messaging", 7, null, 10200, 0, 0, n, Process.myUserHandle(), 1L)
+ val store = io.droidmcp.notification.NotificationStore
+ store.javaClass.getDeclaredMethod("put\$droid_mcp_notification_listener_release", StatusBarNotification::class.java).invoke(store, sbn)
+ try {
+ val who = DroidMcpAdapter.notificationIdentities(sbn.key)
+ assertTrue(who.toString(), "Mom" in who && "+15125550100" in who)
+ assertTrue(DroidMcpAdapter.notificationIdentities("0|nope|1|null|1").isEmpty())
+ } finally {
+ store.javaClass.getDeclaredMethod("remove\$droid_mcp_notification_listener_release", String::class.java).invoke(store, sbn.key)
+ }
+ }
+
+ // ---- admin token rotation ----------------------------------------------------------------------
+
+ @Test fun `rotating the admin token revokes the old one and cancels its pending approvals`() = runBlocking {
+ val old = runtime.secure.adminToken
+ assertNotNull(runtime.peers.authenticate(old))
+ val (pa, _) = runtime.approvals.createAndAwait("messaging.send_sms", ActionClass.EXTERNAL_COMMITMENT, mapOf("to" to "+15125550100"), PeerStore.ADMIN_ID, "corr", 60_000, "test", waitMs = 0)
+ runtime.rotateAdminToken()
+ val new = runtime.secure.adminToken
+ assertTrue(old != new)
+ assertNull(runtime.peers.authenticate(old))
+ assertEquals(PeerStore.ADMIN_ID, runtime.peers.authenticate(new)?.peerId)
+ assertEquals("cancelled", runtime.approvals.get(pa.id)!!.status)
+ }
+}
diff --git a/android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/SessionEventAccessTest.kt b/android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/SessionEventAccessTest.kt
new file mode 100644
index 0000000..a51b2a9
--- /dev/null
+++ b/android-runtime/app/src/test/kotlin/dev/symbiosis/runtime/SessionEventAccessTest.kt
@@ -0,0 +1,166 @@
+package dev.symbiosis.runtime
+
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import dev.symbiosis.runtime.automation.AlarmSink
+import dev.symbiosis.runtime.automation.AutomationExecutor
+import dev.symbiosis.runtime.automation.StepDispatcher
+import dev.symbiosis.runtime.automation.WorkflowCapabilities
+import dev.symbiosis.runtime.automation.WorkflowEngine
+import dev.symbiosis.runtime.automation.WorkflowStore
+import dev.symbiosis.runtime.capabilities.CallContext
+import dev.symbiosis.runtime.capabilities.Capability
+import dev.symbiosis.runtime.capabilities.NativeCapabilities
+import dev.symbiosis.runtime.capabilities.Principal
+import dev.symbiosis.runtime.core.DispatchOutcome
+import dev.symbiosis.runtime.events.Event
+import dev.symbiosis.runtime.events.EventBroker
+import dev.symbiosis.runtime.events.SubscriptionStore
+import dev.symbiosis.runtime.events.Topics
+import dev.symbiosis.runtime.policy.ActionClass
+import dev.symbiosis.runtime.sessions.SessionManager
+import dev.symbiosis.runtime.storage.Db
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.async
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.runBlocking
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+
+/**
+ * Session-scoped events (a call's transcript, its state) reach only the peer that owns the session, on every
+ * delivery path. A telephony.* scope used to be enough to read another peer's live call transcript.
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class SessionEventAccessTest {
+ private lateinit var ctx: Context
+ private lateinit var db: Db
+ private lateinit var broker: EventBroker
+ private lateinit var sessions: SessionManager
+ private lateinit var subs: SubscriptionStore
+ private lateinit var events: Map
+
+ private val scopes = listOf("telephony.*", "events.*", "automation.*", "device.*")
+ private val alice = Principal("peer_alice", "alice", scopes, ActionClass.EXTERNAL_COMMITMENT)
+ private val bob = Principal("peer_bob", "bob", scopes, ActionClass.EXTERNAL_COMMITMENT)
+ private val admin = Principal("peer_admin", "admin", listOf("*"), ActionClass.DESTRUCTIVE)
+
+ @Before fun setUp() {
+ ctx = ApplicationProvider.getApplicationContext()
+ ctx.deleteDatabase("symbiosis.db")
+ db = Db(ctx)
+ broker = EventBroker(db, "dev_test")
+ sessions = SessionManager(db)
+ subs = SubscriptionStore(db, broker)
+ events = NativeCapabilities.events(broker, subs) { sessions.ownerOf(it) }.associateBy { it.name }
+ }
+
+ private fun transcript(sessionId: String?, text: String): Event =
+ broker.emit(Topics.CALL_TRANSCRIPT, mapOf("session_id" to sessionId, "text" to text, "final" to true, "turn_id" to 1))
+
+ private fun run(name: String, p: Principal, vararg args: Pair) = runBlocking {
+ events.getValue(name).execute(mapOf(*args), CallContext(p.peerId, "corr_test", principal = p))
+ }
+
+ @Test fun `only the session owner and the admin see a session's events`() {
+ val aliceCall = sessions.create("call", alice.peerId, "corr_a", emptyMap())
+ val ownerless = sessions.create("call", null, "corr_n", emptyMap())
+ val owner: (String) -> String? = { sessions.ownerOf(it) }
+ val ev = transcript(aliceCall.sessionId, "my card number is ...")
+ assertTrue(alice.canSeeEvent(ev, owner))
+ assertFalse(bob.canSeeEvent(ev, owner))
+ assertTrue(admin.canSeeEvent(ev, owner))
+ // Unknown and ownerless sessions are admin-only, like /ws/sessions/{id}.
+ assertFalse(alice.canSeeEvent(transcript("call_doesnotexist", "x"), owner))
+ assertFalse(alice.canSeeEvent(transcript(ownerless.sessionId, "x"), owner))
+ assertTrue(admin.canSeeEvent(transcript(ownerless.sessionId, "x"), owner))
+ // No session named: topic scope alone decides, as before.
+ assertTrue(bob.canSeeEvent(transcript(null, "x"), owner))
+ assertTrue(bob.canSeeEvent(broker.emit(Topics.CALL_RINGING, mapOf("number" to "+1555", "direction" to "in", "session_id" to null)), owner))
+ // Topic scope still applies first.
+ val noTelephony = Principal("peer_c", "c", listOf("events.*"), ActionClass.EXTERNAL_COMMITMENT)
+ assertFalse(noTelephony.canSeeEvent(transcript(null, "x"), owner))
+ }
+
+ @Test fun `an ended session's events stay owned after the owner cache is gone`() {
+ val s = sessions.create("call", alice.peerId, "corr_a", emptyMap())
+ sessions.transition(s.sessionId, dev.symbiosis.runtime.sessions.SessionState.ENDED)
+ val fresh = SessionManager(db) // a restarted process: nothing cached, ownership comes from the sessions table
+ assertEquals(alice.peerId, fresh.ownerOf(s.sessionId))
+ assertFalse(bob.canSeeEvent(transcript(s.sessionId, "x")) { fresh.ownerOf(it) })
+ }
+
+ @Test fun `replay drops another peer's call transcript`() {
+ val aliceCall = sessions.create("call", alice.peerId, "corr_a", emptyMap())
+ val bobCall = sessions.create("call", bob.peerId, "corr_b", emptyMap())
+ val sub = run("events.subscribe", bob, "topic_glob" to "call.*")
+ assertTrue(sub.ok)
+ transcript(aliceCall.sessionId, "alice's secret")
+ transcript(bobCall.sessionId, "bob's own")
+ val r = run("events.replay", bob, "subscription_id" to sub.data["subscription_id"], "since_id" to 0)
+ @Suppress("UNCHECKED_CAST")
+ val texts = (r.data["events"] as List