Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e95e17c3e |
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 240
|
||||
versionName = "2.0.40"
|
||||
versionCode = 241
|
||||
versionName = "2.0.41"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<!-- 通话时想在被叫/接听场景抢音频焦点用得上;多数机型不加也行 -->
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
|
||||
<!-- Android 11+ 用于判断 Termux 是否安装 -->
|
||||
<!-- Android 11+ 包可见性:不声明的话查不到别的 App,也就「打开手机 app」不了 -->
|
||||
<queries>
|
||||
<package android:name="com.termux" />
|
||||
<!-- 系统语音识别服务:不声明的话 Android 11+ 查不到可用引擎 -->
|
||||
@@ -28,6 +28,13 @@
|
||||
<intent>
|
||||
<action android:name="android.intent.action.TTS_SERVICE" />
|
||||
</intent>
|
||||
<!-- ★「打开手机 app」需要的:列出所有能启动的 App。
|
||||
Android 11 起不声明这条 queries,queryIntentActivities 只会返回空列表,
|
||||
表现是"已安装的 App 一个都找不到"。 -->
|
||||
<intent>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent>
|
||||
</queries>
|
||||
|
||||
<!-- 加速度计/陀螺仪等传感器不需要权限 -->
|
||||
@@ -55,5 +62,19 @@
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- ★★ 读手机通知(用户要求的工具)。
|
||||
Android **没有**"读取通知"的运行时权限 —— 唯一合法的路是让用户
|
||||
手动去「设置 → 通知 → 通知使用权」勾上本 App,系统才会把通知流过来。
|
||||
不声明这个 Service,权限开了也收不到任何东西。 -->
|
||||
<service
|
||||
android:name=".DoubaoNotificationListener"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name"
|
||||
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
|
||||
<intent-filter>
|
||||
<action android:name="android.service.notification.NotificationListenerService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
</application>
|
||||
</manifest>
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.app.Notification
|
||||
import android.os.Bundle
|
||||
import android.service.notification.NotificationListenerService
|
||||
import android.service.notification.StatusBarNotification
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* ★★ 读手机通知 —— 用户要求"加个读取手机通知的工具"。
|
||||
*
|
||||
* ## 为什么必须是个 Service
|
||||
*
|
||||
* Android **没有**"读取通知"的运行时权限。唯一合法的路是让用户手动去
|
||||
* 「设置 → 通知 → 通知使用权」里把这个 App 勾上,系统才会把通知流给我们。
|
||||
* 这个 Service 就是那个接收端 —— 不声明它,权限开了也收不到任何东西。
|
||||
*
|
||||
* ## 不落盘,只在内存里留最近的
|
||||
*
|
||||
* 通知是**高度隐私**的内容(验证码、私信、银行短信都在里面)。
|
||||
* 写进磁盘意味着卸载前一直躺在那儿,也可能被别的工具读到。
|
||||
* 只留内存,进程一死就没了 —— 用户要"读最近的通知"这个需求完全够用,
|
||||
* 而隐私面小得多。
|
||||
*
|
||||
* ★ 上限 [MAX_KEEP] 条:用户一天能收几百条通知,不限量会把内存吃满。
|
||||
*/
|
||||
class DoubaoNotificationListener : NotificationListenerService() {
|
||||
|
||||
override fun onListenerConnected() {
|
||||
super.onListenerConnected()
|
||||
connected = true
|
||||
Log.i(TAG, "通知使用权已连接")
|
||||
}
|
||||
|
||||
override fun onListenerDisconnected() {
|
||||
super.onListenerDisconnected()
|
||||
connected = false
|
||||
Log.i(TAG, "通知使用权已断开")
|
||||
}
|
||||
|
||||
override fun onNotificationPosted(sbn: StatusBarNotification?) {
|
||||
val n = sbn ?: return
|
||||
try {
|
||||
// ★ 跳过我们自己的通知(不然"AI 读通知"会把 App 自己的提示也读进去)
|
||||
if (n.packageName == packageName) return
|
||||
record(n, removed = false)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "记通知失败:${t.message}")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNotificationRemoved(sbn: StatusBarNotification?) {
|
||||
val n = sbn ?: return
|
||||
// ★ 只标成"已消失",**不删掉** —— 用户问"刚才那条验证码呢"的时候,
|
||||
// 通知早就被划掉了,删了就直接查不到了。
|
||||
try {
|
||||
val key = n.key ?: return
|
||||
items[key]?.let { it.removed = true; it.atRemoved = System.currentTimeMillis() }
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun record(n: StatusBarNotification, removed: Boolean) {
|
||||
val extras: Bundle = n.notification?.extras ?: Bundle()
|
||||
val title = extras.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
|
||||
val text = extras.getCharSequence(Notification.EXTRA_TEXT)?.toString().orEmpty()
|
||||
val big = extras.getCharSequence(Notification.EXTRA_BIG_TEXT)?.toString().orEmpty()
|
||||
val sub = extras.getCharSequence(Notification.EXTRA_SUB_TEXT)?.toString().orEmpty()
|
||||
|
||||
val item = Item(
|
||||
key = n.key ?: "${n.packageName}:${n.postTime}",
|
||||
pkg = n.packageName.orEmpty(),
|
||||
app = appLabel(n.packageName.orEmpty()),
|
||||
title = title,
|
||||
text = if (big.isNotBlank()) big else text,
|
||||
subText = sub,
|
||||
at = if (n.postTime > 0) n.postTime else System.currentTimeMillis(),
|
||||
removed = removed,
|
||||
atRemoved = 0L,
|
||||
)
|
||||
items[item.key] = item
|
||||
|
||||
// 超上限就丢最旧的。用 postTime 排(key 是字符串,排不了时间序)
|
||||
if (items.size > MAX_KEEP) {
|
||||
items.values.sortedBy { it.at }.take(items.size - MAX_KEEP).forEach { items.remove(it.key) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun appLabel(pkg: String): String = try {
|
||||
val pm = packageManager
|
||||
pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0)).toString()
|
||||
} catch (_: Throwable) {
|
||||
pkg
|
||||
}
|
||||
|
||||
data class Item(
|
||||
val key: String,
|
||||
val pkg: String,
|
||||
val app: String,
|
||||
val title: String,
|
||||
val text: String,
|
||||
val subText: String,
|
||||
val at: Long,
|
||||
var removed: Boolean,
|
||||
var atRemoved: Long,
|
||||
)
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DoubaoNotif"
|
||||
private const val MAX_KEEP = 200
|
||||
|
||||
/** 最近的通知(内存里,进程死了就没了 —— 见类注释里的隐私考虑) */
|
||||
private val items = ConcurrentHashMap<String, Item>()
|
||||
|
||||
/** 通知使用权连上了没有 */
|
||||
@Volatile
|
||||
var connected: Boolean = false
|
||||
|
||||
/**
|
||||
* 取最近的通知。
|
||||
*
|
||||
* @param limit 最多几条
|
||||
* @param onlyAlive 只要"还在通知栏上"的(默认 false = 包括已经被划掉的)
|
||||
* @param query 关键词过滤(标题/正文/App 名里含它)
|
||||
*/
|
||||
fun recent(limit: Int = 20, onlyAlive: Boolean = false, query: String = ""): JSONArray {
|
||||
var list = items.values.toList()
|
||||
if (onlyAlive) list = list.filter { !it.removed }
|
||||
if (query.isNotBlank()) {
|
||||
val q = query.lowercase()
|
||||
list = list.filter {
|
||||
it.title.lowercase().contains(q) ||
|
||||
it.text.lowercase().contains(q) ||
|
||||
it.app.lowercase().contains(q) ||
|
||||
it.pkg.lowercase().contains(q)
|
||||
}
|
||||
}
|
||||
val arr = JSONArray()
|
||||
list.sortedByDescending { it.at }.take(limit.coerceIn(1, MAX_KEEP)).forEach { it ->
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("app", it.app)
|
||||
.put("package", it.pkg)
|
||||
.put("title", it.title)
|
||||
.put("text", it.text)
|
||||
.put("subText", it.subText)
|
||||
.put("at", it.at)
|
||||
.put("removed", it.removed),
|
||||
)
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
fun count(): Int = items.size
|
||||
|
||||
fun clear() = items.clear()
|
||||
}
|
||||
}
|
||||
@@ -39,9 +39,17 @@ import java.util.concurrent.TimeUnit
|
||||
*/
|
||||
class NativeBridge(private val activity: Activity) {
|
||||
|
||||
/**
|
||||
* 一次最多列多少个 App。
|
||||
*
|
||||
* ★ 必须有上限:手机上有 100~300 个 App,全塞给模型光这一条就几千 token,
|
||||
* 而且它多半只需要"找那一个"。要全量就用 query 过滤。
|
||||
*/
|
||||
private val APP_LIST_MAX = 120
|
||||
|
||||
// ------------------------------------------------------------------ 设备能力
|
||||
|
||||
/** 统一入口:收一个 JSON 字符串,回一个 JSON 字符串 */
|
||||
/** 统一的入口:收一个 JSON 字符串,回一个 JSON 字符串 */
|
||||
@Suppress("unused")
|
||||
fun device(payloadJson: String): String {
|
||||
val req = try {
|
||||
@@ -86,6 +94,30 @@ class NativeBridge(private val activity: Activity) {
|
||||
"session_message" -> sessionMessage(req)
|
||||
// AI 写的界面里用户选了什么 → 排队送回模型(见 pushUiResult)
|
||||
"ui_result" -> pushUiResult(req)
|
||||
// ---- 操作手机:通知 / 打开 App / 音量 ----
|
||||
"notifications" -> notifications(req)
|
||||
"notification_access" -> JSONObject()
|
||||
.put("granted", PhoneOps.hasNotificationAccess(activity))
|
||||
.put("kept", DoubaoNotificationListener.count())
|
||||
"notification_settings" -> {
|
||||
// 带用户去开「通知使用权」—— Android 没有这个权限的运行时申请弹窗,
|
||||
// 只能跳到设置页让他自己勾
|
||||
activity.startActivity(PhoneOps.notificationAccessIntent())
|
||||
JSONObject().put("ok", true).put("opened", "通知使用权设置页")
|
||||
}
|
||||
"notification_clear" -> {
|
||||
DoubaoNotificationListener.clear()
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
"apps" -> appsList(req)
|
||||
"app_launch" -> appLaunch(req)
|
||||
"volume" -> JSONObject().put("state", PhoneOps.volumeState(activity))
|
||||
"volume_set" -> PhoneOps.setVolume(
|
||||
activity,
|
||||
req.optString("stream", "music"),
|
||||
req.optString("mode", "set"),
|
||||
req.optInt("value", 0),
|
||||
)
|
||||
else -> JSONObject().put("error", "未知 action:$action")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
@@ -378,6 +410,112 @@ class NativeBridge(private val activity: Activity) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 列 App。
|
||||
*
|
||||
* ★ 没传 query 就返回全部(截前 [APP_LIST_MAX] 个)——
|
||||
* 模型可以先看一眼有哪些 App,再决定开哪个。
|
||||
*/
|
||||
private fun appsList(req: JSONObject): JSONObject {
|
||||
val query = req.optString("query").trim()
|
||||
val all = PhoneOps.installedApps(activity)
|
||||
val out = JSONArray()
|
||||
if (query.isBlank()) {
|
||||
all.take(APP_LIST_MAX).forEach { (label, pkg, _) ->
|
||||
out.put(JSONObject().put("label", label).put("package", pkg))
|
||||
}
|
||||
return JSONObject().put("count", all.size).put("apps", out)
|
||||
}
|
||||
val q = query.lowercase()
|
||||
all.filter {
|
||||
it.first.lowercase().contains(q) || it.second.lowercase().contains(q)
|
||||
}.take(30).forEach { (label, pkg, _) ->
|
||||
out.put(JSONObject().put("label", label).put("package", pkg))
|
||||
}
|
||||
return JSONObject().put("count", all.size).put("matched", out.length()).put("apps", out)
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开一个 App。
|
||||
*
|
||||
* ★ 找不到时**明确报错并给出相近的名字** —— 让模型能自己改一个再来,
|
||||
* 而不是回一个干巴巴的"失败"(那样它只会反复重试同一个错名字)。
|
||||
*/
|
||||
private fun appLaunch(req: JSONObject): JSONObject {
|
||||
// 已经知道包名和 Activity(从上一步 app_list 拿到的)就直接开,省一次全表扫描
|
||||
val pkg = req.optString("package").trim()
|
||||
val cls = req.optString("activity").trim()
|
||||
if (pkg.isNotEmpty() && cls.isNotEmpty()) {
|
||||
val ok = PhoneOps.launchApp(activity, pkg, cls)
|
||||
return if (ok) {
|
||||
JSONObject().put("ok", true).put("package", pkg)
|
||||
} else {
|
||||
JSONObject().put("error", "启动 $pkg 失败(系统拒绝了,可能被停用)")
|
||||
}
|
||||
}
|
||||
|
||||
val name = req.optString("name").trim()
|
||||
if (name.isEmpty()) {
|
||||
return JSONObject().put("error", "至少要给 name(App 名字)或 package+activity")
|
||||
}
|
||||
val hit = PhoneOps.findApp(activity, name)
|
||||
?: run {
|
||||
// 给几个名字相近的当提示
|
||||
val q = name.lowercase()
|
||||
val near = PhoneOps.installedApps(activity)
|
||||
.filter { it.first.lowercase().contains(q.take(2)) }
|
||||
.take(5)
|
||||
.map { it.first }
|
||||
return JSONObject()
|
||||
.put("error", "没找到叫「$name」的 App")
|
||||
.put("hint", if (near.isEmpty()) {
|
||||
// ★ 这里写的 action 名必须和 tools/apps.py 里 enum 的一致。
|
||||
// 第一版写的 `app_list` —— 那个名字不存在,模型照着调会失败。
|
||||
"可以用 action=list 看看装了哪些 App"
|
||||
} else {
|
||||
"名字相近的有:" + near.joinToString("、") + "。换个名字再试"
|
||||
})
|
||||
}
|
||||
val ok = PhoneOps.launchApp(activity, hit.second, hit.third)
|
||||
return if (ok) {
|
||||
JSONObject().put("ok", true)
|
||||
.put("label", hit.first)
|
||||
.put("package", hit.second)
|
||||
} else {
|
||||
JSONObject().put("error", "找到「${hit.first}」但启动失败(系统拒绝了)")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读通知。
|
||||
*
|
||||
* ★ 权限没开时**返回明确错误**,不是空列表。
|
||||
* 返回空列表的话模型会说"最近没有通知" —— 那是**错的**
|
||||
* (明明有几条,只是我们读不到),用户会被误导。
|
||||
*/
|
||||
private fun notifications(req: JSONObject): JSONObject {
|
||||
if (!PhoneOps.hasNotificationAccess(activity)) {
|
||||
return JSONObject()
|
||||
.put("error", "没有「通知使用权」,读不到任何通知")
|
||||
.put("granted", false)
|
||||
.put(
|
||||
"hint",
|
||||
"这个权限安卓不给运行时申请,必须用户手动开:" +
|
||||
"设置 → 通知 → 通知使用权(或「通知读取权限」)→ 找到本 App 打开。" +
|
||||
"调用 action=notification_settings 可以直接跳到那个设置页。",
|
||||
)
|
||||
}
|
||||
val arr = DoubaoNotificationListener.recent(
|
||||
limit = req.optInt("limit", 20),
|
||||
onlyAlive = req.optBoolean("onlyAlive", false),
|
||||
query = req.optString("query"),
|
||||
)
|
||||
return JSONObject()
|
||||
.put("granted", true)
|
||||
.put("count", arr.length())
|
||||
.put("notifications", arr)
|
||||
}
|
||||
|
||||
private fun deviceInfo(): JSONObject {
|
||||
val stat = StatFs(Environment.getDataDirectory().path)
|
||||
val freeGb = stat.availableBytes / 1024.0 / 1024.0 / 1024.0
|
||||
|
||||
220
android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt
Normal file
220
android/app/src/main/java/com/doubao/lynxclone/PhoneOps.kt
Normal file
@@ -0,0 +1,220 @@
|
||||
package com.doubao.lynxclone
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.media.AudioManager
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* ★ 三个"操作手机"的能力:读通知 / 打开 App / 调音量。
|
||||
*
|
||||
* 抽成一个文件是因为它们同类(都是"AI 要动手机"),
|
||||
* 而且都要处理"权限没给"这一种失败 —— 收在一起比较好统一口径。
|
||||
*
|
||||
* ## 一律"如实报错",不假装成功
|
||||
*
|
||||
* 通知使用权没开、找不到那个 App、音量被系统锁住 —— 这些都会**明确返回错误**,
|
||||
* 而不是返回一个空列表或者一个看起来成功的值。
|
||||
* 模型拿到"权限没开"才会去告诉用户怎么开;拿到空列表它只会说
|
||||
* "最近没有通知",那是**错的**(明明有几条,只是我们读不到)。
|
||||
*/
|
||||
object PhoneOps {
|
||||
|
||||
private const val TAG = "DoubaoPhone"
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 一、通知 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/** 通知使用权开了没有 */
|
||||
fun hasNotificationAccess(ctx: Context): Boolean {
|
||||
val flat = Settings.Secure.getString(ctx.contentResolver, "enabled_notification_listeners")
|
||||
?: return false
|
||||
if (flat.isBlank()) return false
|
||||
val me = ComponentName(ctx, DoubaoNotificationListener::class.java)
|
||||
// enabled_notification_listeners 是 `pkg/cls:pkg/cls` 的形式,
|
||||
// 而且**不同 ROM 的大小写和简写不一样**,所以比对时统一转小写再找
|
||||
return flat.lowercase().split(':').any { entry ->
|
||||
val e = entry.trim()
|
||||
e == me.flattenToString().lowercase() ||
|
||||
e == me.flattenToShortString().lowercase() ||
|
||||
e.startsWith(me.packageName.lowercase() + "/")
|
||||
}
|
||||
}
|
||||
|
||||
/** 通知使用权的设置页(带用户去开) */
|
||||
fun notificationAccessIntent(): Intent =
|
||||
Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 二、打开 App */
|
||||
/* ==================================================================== */
|
||||
|
||||
/** 能启动的 App 列表(系统 + 用户装的) */
|
||||
fun installedApps(ctx: Context): List<Triple<String, String, String>> {
|
||||
val pm = ctx.packageManager
|
||||
val main = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
// ★ Android 11+ 必须先在 Manifest 的 <queries> 里声明 LAUNCHER intent,
|
||||
// 否则这里返回空列表(看着像"这台手机没有 App",很误导)
|
||||
val list = if (Build.VERSION.SDK_INT >= 33) {
|
||||
pm.queryIntentActivities(
|
||||
main,
|
||||
android.content.pm.PackageManager.ResolveInfoFlags.of(0L),
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
pm.queryIntentActivities(main, 0)
|
||||
}
|
||||
return list.mapNotNull { ri ->
|
||||
val pkg = ri.activityInfo?.packageName ?: return@mapNotNull null
|
||||
val cls = ri.activityInfo?.name ?: return@mapNotNull null
|
||||
val label = ri.loadLabel(pm).toString()
|
||||
Triple(label, pkg, cls)
|
||||
}.sortedBy { it.first }
|
||||
}
|
||||
|
||||
/** 模糊匹配一个 App;找不到返回 null */
|
||||
fun findApp(ctx: Context, query: String): Triple<String, String, String>? {
|
||||
val q = query.trim().lowercase()
|
||||
if (q.isEmpty()) return null
|
||||
val all = installedApps(ctx)
|
||||
// 优先级:包名完全相同 > 名字完全相同 > 名字以它开头 > 包含 > 包名包含
|
||||
return all.firstOrNull { it.second.lowercase() == q }
|
||||
?: all.firstOrNull { it.first.lowercase() == q }
|
||||
?: all.firstOrNull { it.first.lowercase().startsWith(q) }
|
||||
?: all.firstOrNull { it.first.lowercase().contains(q) }
|
||||
?: all.firstOrNull { it.second.lowercase().contains(q) }
|
||||
}
|
||||
|
||||
/** 启动一个 App */
|
||||
fun launchApp(ctx: Context, pkg: String, cls: String): Boolean = try {
|
||||
ctx.startActivity(
|
||||
Intent(Intent.ACTION_MAIN)
|
||||
.addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
.setComponent(ComponentName(pkg, cls))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED),
|
||||
)
|
||||
true
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "启动 $pkg/$cls 失败:${t.message}")
|
||||
false
|
||||
}
|
||||
|
||||
/* ==================================================================== */
|
||||
/* 三、音量 */
|
||||
/* ==================================================================== */
|
||||
|
||||
/**
|
||||
* 音量流。
|
||||
*
|
||||
* ★ 用**字符串名**而不是整数常量:模型要写 `music` / `ring` 这种可读的名字,
|
||||
* 让它记 `STREAM_MUSIC = 3` 既没必要也容易错。
|
||||
*/
|
||||
private fun streamOf(name: String): Int = when (name.trim().lowercase()) {
|
||||
"ring", "ringtone", "铃声" -> AudioManager.STREAM_RING
|
||||
"alarm", "闹钟" -> AudioManager.STREAM_ALARM
|
||||
"call", "voice_call", "通话" -> AudioManager.STREAM_VOICE_CALL
|
||||
"system", "系统" -> AudioManager.STREAM_SYSTEM
|
||||
"notification", "通知" -> AudioManager.STREAM_NOTIFICATION
|
||||
else -> AudioManager.STREAM_MUSIC // 默认媒体音量(最常用)
|
||||
}
|
||||
|
||||
private fun streamName(stream: Int): String = when (stream) {
|
||||
AudioManager.STREAM_RING -> "ring"
|
||||
AudioManager.STREAM_ALARM -> "alarm"
|
||||
AudioManager.STREAM_VOICE_CALL -> "call"
|
||||
AudioManager.STREAM_SYSTEM -> "system"
|
||||
AudioManager.STREAM_NOTIFICATION -> "notification"
|
||||
else -> "music"
|
||||
}
|
||||
|
||||
/**
|
||||
* 读所有音量流的当前值。
|
||||
*
|
||||
* ★ 同时给**原始值**和**百分比**:模型想"调到一半"用百分比直观,
|
||||
* 想"加一格"用原始值准。两个都给,它自己挑。
|
||||
*/
|
||||
fun volumeState(ctx: Context): JSONObject {
|
||||
val am = ctx.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val arr = JSONArray()
|
||||
val streams = listOf(
|
||||
AudioManager.STREAM_MUSIC, AudioManager.STREAM_RING, AudioManager.STREAM_ALARM,
|
||||
AudioManager.STREAM_VOICE_CALL, AudioManager.STREAM_SYSTEM,
|
||||
AudioManager.STREAM_NOTIFICATION,
|
||||
)
|
||||
for (s in streams) {
|
||||
val cur = am.getStreamVolume(s)
|
||||
val max = am.getStreamMaxVolume(s).coerceAtLeast(1)
|
||||
val pct = Math.round(cur * 100f / max)
|
||||
arr.put(
|
||||
JSONObject()
|
||||
.put("stream", streamName(s))
|
||||
.put("current", cur)
|
||||
.put("max", max)
|
||||
.put("percent", pct)
|
||||
.put("muted", cur == 0),
|
||||
)
|
||||
}
|
||||
return JSONObject().put("streams", arr)
|
||||
}
|
||||
|
||||
/**
|
||||
* 调音量。
|
||||
*
|
||||
* @param mode set=设成具体值 / up=加 / down=减 / mute=静音 / unmute=取消静音
|
||||
* @param value set 时的值,或 up/down 的步数(默认 1)
|
||||
*/
|
||||
fun setVolume(ctx: Context, streamArg: String, mode: String, value: Int): JSONObject {
|
||||
val am = ctx.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||
val stream = streamOf(streamArg)
|
||||
val max = am.getStreamMaxVolume(stream).coerceAtLeast(1)
|
||||
val before = am.getStreamVolume(stream)
|
||||
|
||||
val target: Int = when (mode.trim().lowercase()) {
|
||||
"mute" -> 0
|
||||
"unmute" -> {
|
||||
// 取消静音:恢复到"上次非零"不好拿,用 max 的一半,至少能听见
|
||||
if (before > 0) before else (max / 2).coerceAtLeast(1)
|
||||
}
|
||||
"up" -> (before + value.coerceAtLeast(1)).coerceAtMost(max)
|
||||
"down" -> (before - value.coerceAtLeast(1)).coerceAtLeast(0)
|
||||
else -> value.coerceIn(0, max)
|
||||
}
|
||||
|
||||
// ★ DND(勿扰)开着时系统会**拒绝**改铃声/通知音量 —— 静默失败。
|
||||
// 所以改完必须**回读**确认,不能假定成功。
|
||||
var err = ""
|
||||
try {
|
||||
am.setStreamVolume(stream, target, 0)
|
||||
} catch (t: Throwable) {
|
||||
err = "${t.javaClass.simpleName}: ${t.message}"
|
||||
}
|
||||
val after = am.getStreamVolume(stream)
|
||||
|
||||
val ok = if (err.isEmpty()) after == target else false
|
||||
val out = JSONObject()
|
||||
.put("stream", streamName(stream))
|
||||
.put("before", before)
|
||||
.put("requested", target)
|
||||
.put("current", after)
|
||||
.put("max", max)
|
||||
.put("percent", Math.round(after * 100f / max))
|
||||
.put("ok", ok)
|
||||
if (err.isNotEmpty()) out.put("error", err)
|
||||
if (!ok && err.isEmpty()) {
|
||||
// 回读和请求不一致 = 系统拦了(多半是勿扰模式)
|
||||
out.put(
|
||||
"error",
|
||||
"系统没有接受这次调整(可能开了勿扰模式,或该音量流被系统锁定)。" +
|
||||
"当前值仍是 $after。",
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
@@ -141,6 +141,22 @@ fun AppRoot(
|
||||
* `ask_user` 是阻塞的,用户必须先回答它;而「打开网页」是用户自己点的,
|
||||
* 他最想看的是网页,所以网页在最上面。
|
||||
*/
|
||||
// 「笔记」—— 用户要能查看 AI 替他记了什么
|
||||
AnimatedVisibility(
|
||||
visible = vm.notesOpen,
|
||||
enter = slideInVertically(tween(240)) { it / 6 } + fadeIn(tween(180)),
|
||||
exit = slideOutVertically(tween(200)) { it / 8 } + fadeOut(tween(150)),
|
||||
) {
|
||||
NotesScreen(
|
||||
notes = vm.notes,
|
||||
opening = vm.openingNote,
|
||||
onOpen = { vm.openNote(it) },
|
||||
onCloseNote = { vm.closeNote() },
|
||||
onDelete = { vm.deleteNote(it) },
|
||||
onBack = { vm.closeNotes() },
|
||||
)
|
||||
}
|
||||
|
||||
// 「AI 界面」列表(用户要求"AI 写的界面可以再点开")。
|
||||
// 排在 HTML 界面之下:点一个就从列表进到界面。
|
||||
AnimatedVisibility(
|
||||
@@ -243,6 +259,11 @@ private fun DrawerOverlay(vm: AppViewModel) {
|
||||
vm.drawerOpen = false
|
||||
vm.openAiScreenList()
|
||||
}
|
||||
// 「笔记」—— 用户要能查看 AI 替他记了什么
|
||||
DrawerItem(Icons.Filled.EditNote, "笔记") {
|
||||
vm.drawerOpen = false
|
||||
vm.openNotes()
|
||||
}
|
||||
DrawerItem(Icons.Filled.Layers, "技能·连接器") {
|
||||
vm.screen = Screen.Skills; vm.drawerOpen = false
|
||||
}
|
||||
|
||||
@@ -91,6 +91,70 @@ class AppViewModel(val client: KernelClient) : ViewModel() {
|
||||
var aiScreenListOpen by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/* -------------------- 笔记(用户要能查看)-------------------- */
|
||||
|
||||
/**
|
||||
* 笔记列表。
|
||||
*
|
||||
* ★ 用户的原话:"notes 用户要能查看" —— 以前笔记**只有 AI 能读写**,
|
||||
* 用户在界面上完全看不到:AI 说"我记下来了",他没法确认记了什么、
|
||||
* 记错没有。这类"AI 替你做事但你无法查看"的功能,用户不会信任。
|
||||
*/
|
||||
var notes by mutableStateOf<List<com.doubao.lynxclone.data.NoteItem>>(emptyList())
|
||||
private set
|
||||
|
||||
var notesOpen by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** 正在阅读的那条笔记(null = 在列表页) */
|
||||
var openingNote by mutableStateOf<com.doubao.lynxclone.data.NoteItem?>(null)
|
||||
private set
|
||||
|
||||
fun openNotes() {
|
||||
notesOpen = true
|
||||
openingNote = null
|
||||
refreshNotes()
|
||||
}
|
||||
|
||||
fun closeNotes() {
|
||||
notesOpen = false
|
||||
openingNote = null
|
||||
}
|
||||
|
||||
fun refreshNotes() {
|
||||
viewModelScope.launch {
|
||||
val list = runCatching {
|
||||
withContext(Dispatchers.IO) { client.notes() }
|
||||
}.getOrDefault(emptyList())
|
||||
notes = list
|
||||
}
|
||||
}
|
||||
|
||||
/** 点开一条:列表接口不带正文,这里再去读全文 */
|
||||
fun openNote(item: com.doubao.lynxclone.data.NoteItem) {
|
||||
viewModelScope.launch {
|
||||
val full = runCatching {
|
||||
withContext(Dispatchers.IO) { client.note(item.file) }
|
||||
}.getOrNull()
|
||||
openingNote = full ?: item
|
||||
}
|
||||
}
|
||||
|
||||
fun closeNote() {
|
||||
openingNote = null
|
||||
}
|
||||
|
||||
fun deleteNote(item: com.doubao.lynxclone.data.NoteItem) {
|
||||
viewModelScope.launch {
|
||||
val ok = withContext(Dispatchers.IO) {
|
||||
runCatching { client.deleteNote(item.file) }.isSuccess
|
||||
}
|
||||
openingNote = null
|
||||
refreshNotes()
|
||||
showHint(if (ok) "已删除「${item.title.ifBlank { item.file }}」" else "删除失败")
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开 AI 界面列表 / 直接重开某一个 */
|
||||
fun openAiScreenList() {
|
||||
aiScreenListOpen = true
|
||||
|
||||
258
android/app/src/main/java/com/doubao/lynxclone/ui/NotesScreen.kt
Normal file
258
android/app/src/main/java/com/doubao/lynxclone/ui/NotesScreen.kt
Normal file
@@ -0,0 +1,258 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.DeleteOutline
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.doubao.lynxclone.data.NoteItem
|
||||
|
||||
/**
|
||||
* ★★ 笔记列表 —— 用户要求"notes 用户要能查看"。
|
||||
*
|
||||
* ## 为什么需要它
|
||||
*
|
||||
* 笔记以前**只有 AI 能读写**(走 notes 工具),用户在界面上完全看不到。
|
||||
* 也就是说:AI 说"我记下来了",用户没有任何办法确认它记了什么、
|
||||
* 记错没有、或者删掉记错的。这类"AI 替你做事但你无法查看"的功能,
|
||||
* 用户是不会信任的。
|
||||
*
|
||||
* ## 按项目约定:独立全屏界面
|
||||
*
|
||||
* 列表要滚动(笔记会越攒越多),弹窗装不下。
|
||||
*/
|
||||
@Composable
|
||||
fun NotesScreen(
|
||||
notes: List<NoteItem>,
|
||||
opening: NoteItem?,
|
||||
onOpen: (NoteItem) -> Unit,
|
||||
onCloseNote: () -> Unit,
|
||||
onDelete: (NoteItem) -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
// 阅读某一条时,返回键先回到列表(而不是直接退出笔记页)——
|
||||
// 用户会觉得"我明明在笔记里,怎么一按就出去了"
|
||||
BackHandler(enabled = true) {
|
||||
if (opening != null) onCloseNote() else onBack()
|
||||
}
|
||||
|
||||
if (opening != null) {
|
||||
NoteDetail(note = opening, onBack = onCloseNote, onDelete = { onDelete(opening) })
|
||||
return
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader("笔记", onBack = onBack) {
|
||||
Text(
|
||||
if (notes.isEmpty()) "还没有" else "${notes.size} 条",
|
||||
fontSize = 13.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
|
||||
if (notes.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
"还没有笔记。\n让 AI「记一下」某件事,就会出现在这里。",
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 22.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
return@Column
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
item {
|
||||
Text(
|
||||
"AI 帮你记下来的东西都在这里。点开看全文。",
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
items(notes.size) { index ->
|
||||
val n = notes[index]
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.background(doubaoSurfaceAlt())
|
||||
.clickable { onOpen(n) }
|
||||
.padding(start = 14.dp, end = 6.dp, top = 12.dp, bottom = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
n.title.ifBlank { n.file },
|
||||
fontSize = 15.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = doubaoText(),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (n.preview.isNotBlank()) {
|
||||
Spacer(Modifier.height(3.dp))
|
||||
Text(
|
||||
n.preview,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 17.sp,
|
||||
color = doubaoTextDim(),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
listOf(formatNoteTime(n.at), formatNoteBytes(n.bytes))
|
||||
.filter { it.isNotBlank() }
|
||||
.joinToString(" · "),
|
||||
fontSize = 11.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
// 删除单独一个小按钮,别和"点开"挤在一起误触
|
||||
Box(
|
||||
Modifier
|
||||
.size(34.dp)
|
||||
.clip(CircleShape)
|
||||
.clickable { onDelete(n) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.DeleteOutline,
|
||||
"删除",
|
||||
tint = doubaoTextDim(),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(4.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 读某一条笔记的全文 */
|
||||
@Composable
|
||||
private fun NoteDetail(note: NoteItem, onBack: () -> Unit, onDelete: () -> Unit) {
|
||||
val clipboard = LocalClipboardManager.current
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(doubaoBg()),
|
||||
) {
|
||||
ScreenHeader(note.title.ifBlank { "笔记" }, onBack = onBack) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
Modifier.size(36.dp).clip(CircleShape).clickable {
|
||||
clipboard.setText(AnnotatedString(note.content))
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.ContentCopy, "复制", tint = doubaoTextSecondary(),
|
||||
modifier = Modifier.size(18.dp))
|
||||
}
|
||||
Box(
|
||||
Modifier.size(36.dp).clip(CircleShape).clickable { onDelete() },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(Icons.Filled.DeleteOutline, "删除", tint = doubaoTextSecondary(),
|
||||
modifier = Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 18.dp),
|
||||
) {
|
||||
Text(
|
||||
listOf(formatNoteTime(note.at), formatNoteBytes(note.bytes))
|
||||
.filter { it.isNotBlank() }
|
||||
.joinToString(" · "),
|
||||
fontSize = 12.sp,
|
||||
color = doubaoTextDim(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
// 正文可能是 markdown(notes 工具写的是 .md),所以按 markdown 渲染
|
||||
MarkdownText(
|
||||
markdown = note.content,
|
||||
color = doubaoText(),
|
||||
fontSize = 15,
|
||||
lineHeight = 24,
|
||||
)
|
||||
Spacer(Modifier.height(30.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ISO 时间 → 「今天 15:19」/「10-15 15:19」。
|
||||
*
|
||||
* ★ 解析失败就返回空串(界面上那一项直接不显示)——
|
||||
* **不要瞎猜**:用户手改过文件名的情况是有的,猜错会显示一个假时间。
|
||||
*/
|
||||
private fun formatNoteTime(iso: String): String {
|
||||
if (iso.isBlank()) return ""
|
||||
return try {
|
||||
val cleaned = iso.substringBefore('.').removeSuffix("Z")
|
||||
val dt = java.time.LocalDateTime.parse(cleaned)
|
||||
val today = java.time.LocalDate.now()
|
||||
val fmt = if (dt.toLocalDate() == today) {
|
||||
java.time.format.DateTimeFormatter.ofPattern("'今天' HH:mm")
|
||||
} else {
|
||||
java.time.format.DateTimeFormatter.ofPattern("MM-dd HH:mm")
|
||||
}
|
||||
dt.format(fmt)
|
||||
} catch (_: Throwable) {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
private fun formatNoteBytes(n: Int): String = when {
|
||||
n <= 0 -> ""
|
||||
n < 1024 -> "${n}B"
|
||||
n < 1024 * 1024 -> "${n / 1024}KB"
|
||||
else -> String.format(java.util.Locale.getDefault(), "%.1fMB", n / 1024.0 / 1024.0)
|
||||
}
|
||||
@@ -768,6 +768,30 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
})
|
||||
return True
|
||||
|
||||
# ---- 笔记(用户要能查看)----
|
||||
#
|
||||
# ★ 用户的原话:"notes 用户要能查看"。
|
||||
# 以前笔记只有 AI 能读写(走 notes 工具),用户看不到 ——
|
||||
# 而且路径算错落到了 App 外部私有目录,卸载还会被清掉。
|
||||
# 现在存 `<数据目录>/notes`,这几个接口让 App 列出来看。
|
||||
if pathname == '/api/notes' and method == 'GET':
|
||||
self.send_json(200, {'notes': store.list_notes()})
|
||||
return True
|
||||
|
||||
note_name = self._match_id(pathname, '/api/notes/')
|
||||
if note_name is not None:
|
||||
if method == 'GET':
|
||||
note = store.read_note(note_name)
|
||||
if note is None:
|
||||
self.send_json(404, {'error': '笔记不存在'})
|
||||
else:
|
||||
self.send_json(200, note)
|
||||
return True
|
||||
if method == 'DELETE':
|
||||
ok = store.delete_note(note_name)
|
||||
self.send_json(200 if ok else 404, {'ok': ok})
|
||||
return True
|
||||
|
||||
# ---- AI 弹过的界面(关掉之后还能再打开)----
|
||||
#
|
||||
# ★ 用户要求:"AI 写的界面可以再点开"。
|
||||
|
||||
@@ -36,6 +36,10 @@ BUNDLED_TOOL_FILES = [
|
||||
'end_conversation.py',
|
||||
# AI 主动往当前会话里发一条消息(带防死循环的闸,见 app.py /api/session-message)
|
||||
'send_message.py',
|
||||
# 操作手机:读通知 / 开 App / 调音量
|
||||
'notifications.py',
|
||||
'apps.py',
|
||||
'volume.py',
|
||||
'_mcp_python_example.py',
|
||||
]
|
||||
|
||||
|
||||
@@ -73,6 +73,15 @@ class Paths:
|
||||
# ★ AI 弹出来的那些 HTML 界面存这儿 —— 用户关掉之后还要能再打开
|
||||
# (用户明确要求:"AI 写的界面可以再点开")
|
||||
self.screens_dir = os.path.join(self.data_dir, 'screens')
|
||||
# ★ notes 工具的笔记存这儿("notes 用户要能查看")。
|
||||
#
|
||||
# 以前 notes.py 自己算路径:`工具文件/../data/notes` ——
|
||||
# 在安卓上会落到 **App 的外部私有目录**
|
||||
# (`/storage/emulated/0/Android/data/<包名>/files/data/notes`)。
|
||||
# 那个地方用户用文件管理器根本翻不到(Android 11+ 直接隐藏),
|
||||
# 而且**卸载 App 就一起删了**。
|
||||
# 放到 data_dir 下和别的数据一起,持久、位置统一、也能通过接口读出来给界面看。
|
||||
self.notes_dir = os.path.join(self.data_dir, 'notes')
|
||||
self.settings_file = os.path.join(self.data_dir, 'settings.json')
|
||||
self.conversations_file = os.path.join(self.data_dir, 'conversations.json')
|
||||
self.agents_file = os.path.join(self.data_dir, 'agents.json')
|
||||
@@ -93,7 +102,8 @@ class Paths:
|
||||
return os.path.abspath(candidates[-1])
|
||||
|
||||
def ensure_dirs(self) -> None:
|
||||
for folder in (self.data_dir, self.uploads_dir, self.tmp_dir, self.screens_dir):
|
||||
for folder in (self.data_dir, self.uploads_dir, self.tmp_dir, self.screens_dir,
|
||||
self.notes_dir):
|
||||
try:
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
except OSError as exc: # 安卓上外部存储没授权时会失败,不能让它把进程打死
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
@@ -540,6 +541,197 @@ def append_message(conv_id: str, role: str, content: str) -> dict:
|
||||
return msg
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 笔记(notes 工具写的,用户要能查看)
|
||||
# --------------------------------------------------------------------------- #
|
||||
#
|
||||
# ★ 用户的原话:"notes 用户要能查看"。
|
||||
# 以前笔记只有 AI 能读写(走 notes 工具),用户在界面上看不到。
|
||||
#
|
||||
# ★ 目录是 `<数据目录>/notes`(`paths.get().notes_dir`)——
|
||||
# 以前 notes.py 自己算 `工具文件/../data/notes`,在安卓上落到
|
||||
# **App 外部私有目录**(用户翻不到、卸载还会被清掉)。
|
||||
# 那些老文件由 notes.py 里的 `_migrate_once` 自动搬过来。
|
||||
#
|
||||
# ★ 文件名格式:`20261015-151925-标题.md`。时间戳前缀让排序天然按时间倒序。
|
||||
NOTE_SUFFIX = '.md'
|
||||
|
||||
|
||||
def _notes_dir() -> str:
|
||||
d = paths.get().notes_dir
|
||||
os.makedirs(d, exist_ok=True)
|
||||
# ★ 顺手把老位置的笔记搬过来。
|
||||
#
|
||||
# 以前迁移只在 `notes` 工具被调用时才跑(notes.py 的 ensure_dir)。
|
||||
# 问题是:用户装了新版之后**先打开「笔记」页面**(而不是先让 AI 写笔记),
|
||||
# 那时迁移还没跑,他看到的是**空列表** —— 以为笔记全丢了。
|
||||
# 放在这里,任何一次读笔记都会先保证迁移过。
|
||||
_migrate_legacy_notes(d)
|
||||
return d
|
||||
|
||||
|
||||
# 老位置:工具文件旁边的 `../data/notes`。
|
||||
# 在安卓上那会落到 App 的**外部**私有目录
|
||||
# (`/storage/emulated/0/Android/data/<包名>/files/data/notes`)——
|
||||
# 用户用文件管理器翻不到(Android 11+ 直接隐藏),卸载还会一起删掉。
|
||||
def _legacy_notes_dirs() -> list:
|
||||
dirs = []
|
||||
try:
|
||||
# 工具目录的上一级 + /data/notes
|
||||
tools_dir = paths.get().tools_dir
|
||||
if tools_dir:
|
||||
dirs.append(os.path.join(os.path.dirname(tools_dir), 'data', 'notes'))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return [d for d in dirs if d and os.path.abspath(d) != os.path.abspath(paths.get().notes_dir)]
|
||||
|
||||
|
||||
def _migrate_legacy_notes(target: str) -> None:
|
||||
"""
|
||||
把老位置的笔记搬到新位置(只做一次)。
|
||||
|
||||
★ 为什么必须搬:用户在老版本里记的笔记是**真实数据** ——
|
||||
换了目录之后文件还在老地方躺着,但 list/read 都看不到,
|
||||
表现就是"我记的笔记全没了"。这类"改路径把用户数据弄丢"的事最不该发生。
|
||||
"""
|
||||
marker = os.path.join(target, '.migrated')
|
||||
if os.path.exists(marker):
|
||||
return
|
||||
moved = 0
|
||||
for legacy in _legacy_notes_dirs():
|
||||
if not os.path.isdir(legacy):
|
||||
continue
|
||||
try:
|
||||
names = os.listdir(legacy)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
for name in names:
|
||||
if not name.endswith(NOTE_SUFFIX):
|
||||
continue
|
||||
dst = os.path.join(target, name)
|
||||
if os.path.exists(dst):
|
||||
continue # 不覆盖同名的(新位置已有)
|
||||
src = os.path.join(legacy, name)
|
||||
try:
|
||||
shutil.move(src, dst)
|
||||
moved += 1
|
||||
except Exception: # noqa: BLE001
|
||||
# 跨设备 move 可能失败,退回复制
|
||||
try:
|
||||
shutil.copy2(src, dst)
|
||||
os.remove(src)
|
||||
moved += 1
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
try:
|
||||
with open(marker, 'w', encoding='utf-8') as fh:
|
||||
fh.write('ok\n')
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
if moved:
|
||||
print(f'[notes] 已把 {moved} 条老笔记搬到新目录', file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
def _note_path(name: str):
|
||||
"""把文件名解析成绝对路径;不合法(穿越/非 .md)返回 None"""
|
||||
if not name or not name.endswith(NOTE_SUFFIX):
|
||||
return None
|
||||
# ★ 防目录穿越:文件名必须是纯文件名,不能带路径分隔符
|
||||
if '/' in name or '\\' in name or '..' in name:
|
||||
return None
|
||||
return os.path.join(_notes_dir(), name)
|
||||
|
||||
|
||||
def _note_title(path: str, fallback: str) -> str:
|
||||
"""标题取正文第一行的 `# 标题`;读不到就用文件名兜底"""
|
||||
try:
|
||||
with open(path, encoding='utf-8') as fh:
|
||||
first = fh.readline().strip().lstrip('#').strip()
|
||||
return first or fallback
|
||||
except Exception: # noqa: BLE001
|
||||
return fallback
|
||||
|
||||
|
||||
def _note_time(name: str) -> str:
|
||||
"""
|
||||
从文件名前缀 `20261015-151925` 解析出时间,转成 `2026-10-15T15:19:25`。
|
||||
|
||||
★ 解析不出来就返回空串(界面上不显示时间),**不要瞎猜** ——
|
||||
用户手改过文件名的情况是有的。
|
||||
"""
|
||||
m = re.match(r'^(\d{8})-(\d{6})-', name)
|
||||
if not m:
|
||||
return ''
|
||||
d, t = m.group(1), m.group(2)
|
||||
return f'{d[0:4]}-{d[4:6]}-{d[6:8]}T{t[0:2]}:{t[2:4]}:{t[4:6]}'
|
||||
|
||||
|
||||
def list_notes() -> list:
|
||||
"""列出所有笔记(按文件名倒序 = 按时间倒序)"""
|
||||
d = _notes_dir()
|
||||
try:
|
||||
names = sorted(os.listdir(d), reverse=True)
|
||||
except Exception: # noqa: BLE001
|
||||
return []
|
||||
out = []
|
||||
for name in names:
|
||||
if not name.endswith(NOTE_SUFFIX):
|
||||
continue
|
||||
full = os.path.join(d, name)
|
||||
try:
|
||||
size = os.path.getsize(full)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
# 预览 = 去掉标题行之后的头一段
|
||||
preview = ''
|
||||
try:
|
||||
with open(full, encoding='utf-8') as fh:
|
||||
body = fh.read()
|
||||
lines = [ln.strip() for ln in body.splitlines()]
|
||||
body_lines = [ln for ln in lines[1:] if ln]
|
||||
preview = ' '.join(body_lines)[:100]
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
out.append({
|
||||
'file': name,
|
||||
'title': _note_title(full, name),
|
||||
'bytes': size,
|
||||
'at': _note_time(name),
|
||||
'preview': preview,
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def read_note(name: str):
|
||||
"""读一条笔记;不存在返回 None"""
|
||||
path = _note_path(name)
|
||||
if not path or not os.path.isfile(path):
|
||||
return None
|
||||
try:
|
||||
with open(path, encoding='utf-8') as fh:
|
||||
text = fh.read()
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
return {
|
||||
'file': name,
|
||||
'title': _note_title(path, name),
|
||||
'at': _note_time(name),
|
||||
'content': text,
|
||||
'bytes': len(text.encode('utf-8')),
|
||||
}
|
||||
|
||||
|
||||
def delete_note(name: str) -> bool:
|
||||
path = _note_path(name)
|
||||
if not path or not os.path.isfile(path):
|
||||
return False
|
||||
try:
|
||||
os.remove(path)
|
||||
return True
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def get_conversation(conv_id: str):
|
||||
for conv in _load_conversations()['conversations']:
|
||||
if conv.get('id') == conv_id:
|
||||
|
||||
80
scripts/probe-notes-migrate.py
Normal file
80
scripts/probe-notes-migrate.py
Normal file
@@ -0,0 +1,80 @@
|
||||
"""查笔记迁移为什么没生效。"""
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
D = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=90):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
return json.loads(e.read().decode("utf-8", "replace"))
|
||||
|
||||
|
||||
probe = r'''
|
||||
import os, sys, json
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
TOOL = {"name": "probe_nt", "description": "x",
|
||||
"parameters": {"type": "object", "properties": {}}}
|
||||
def run(args):
|
||||
import notes
|
||||
out = {}
|
||||
out["notes_dir"] = notes.notes_dir()
|
||||
out["legacy_dir"] = notes._LEGACY_DIR
|
||||
out["same"] = os.path.abspath(notes.notes_dir()) == notes._LEGACY_DIR
|
||||
out["new_exists"] = os.path.isdir(notes.notes_dir())
|
||||
try:
|
||||
out["new_files"] = os.listdir(notes.notes_dir())
|
||||
except Exception as e:
|
||||
out["new_err"] = f"{type(e).__name__}: {e}"
|
||||
out["legacy_exists"] = os.path.isdir(notes._LEGACY_DIR)
|
||||
try:
|
||||
out["legacy_files"] = os.listdir(notes._LEGACY_DIR)
|
||||
except Exception as e:
|
||||
out["legacy_err"] = f"{type(e).__name__}: {e}"
|
||||
marker = os.path.join(notes.notes_dir(), ".migrated")
|
||||
out["marker_exists"] = os.path.exists(marker)
|
||||
# 手动跑一次迁移看报什么
|
||||
try:
|
||||
notes._migrate_once(notes.notes_dir())
|
||||
out["migrate_ran"] = True
|
||||
out["new_files_after"] = os.listdir(notes.notes_dir())
|
||||
except Exception as e:
|
||||
import traceback
|
||||
out["migrate_err"] = f"{type(e).__name__}: {e}"
|
||||
out["migrate_tb"] = traceback.format_exc()[-700:]
|
||||
# paths 里那个值
|
||||
try:
|
||||
import paths
|
||||
out["paths_notes_dir"] = paths.get().notes_dir
|
||||
except Exception as e:
|
||||
out["paths_err"] = f"{type(e).__name__}: {e}"
|
||||
return out
|
||||
'''
|
||||
|
||||
b64 = base64.b64encode(probe.encode("utf-8")).decode()
|
||||
w = ("import base64,os;"
|
||||
"open(os.path.join('%s','probe_nt.py'),'wb').write(base64.b64decode('%s'));"
|
||||
"print('ok')" % (D, b64))
|
||||
call("/api/tools/run", {"name": "python_run", "args": {"code": w, "timeout": 30}})
|
||||
time.sleep(1)
|
||||
call("/api/tools", None, "GET")
|
||||
r = call("/api/tools/run", {"name": "probe_nt", "args": {}})
|
||||
print(json.dumps((r or {}).get("result"), ensure_ascii=False, indent=1)[:1600])
|
||||
81
scripts/probe-notes-path.py
Normal file
81
scripts/probe-notes-path.py
Normal file
@@ -0,0 +1,81 @@
|
||||
"""查 notes 工具到底写到哪、能不能写。
|
||||
|
||||
★ 背景:用户要求"notes 用户要能查看"。
|
||||
notes.py 里的路径是 `工具文件/../data/notes` —— **相对工具自己算的**。
|
||||
安卓上工具在 `/storage/emulated/0/Android/data/<包名>/files/tools/`,
|
||||
于是笔记会落到 `.../files/data/notes`(**App 外部私有目录**,
|
||||
用户自己用文件管理器看不到,卸载还会被清掉)。
|
||||
先确认它到底写没写成功、写哪儿了。
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=90):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
return json.loads(e.read().decode("utf-8", "replace"))
|
||||
|
||||
|
||||
print("=== 1. 存一条笔记 ===")
|
||||
r = call("/api/tools/run", {
|
||||
"name": "notes",
|
||||
"args": {"action": "save", "title": "测试笔记", "content": "用户能查看吗?"},
|
||||
})
|
||||
print(" ", json.dumps(r, ensure_ascii=False)[:300])
|
||||
|
||||
print("\n=== 2. 列出来 ===")
|
||||
r = call("/api/tools/run", {"name": "notes", "args": {"action": "list"}})
|
||||
print(" ", json.dumps(r, ensure_ascii=False)[:400])
|
||||
|
||||
print("\n=== 3. 问内核:NOTES_DIR 究竟解析到哪个绝对路径 ===")
|
||||
probe = r'''
|
||||
import os, sys, json
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
TOOL = {"name": "probe_notes", "description": "x",
|
||||
"parameters": {"type": "object", "properties": {}}}
|
||||
def run(args):
|
||||
import notes
|
||||
out = {
|
||||
"NOTES_DIR_raw": notes.NOTES_DIR,
|
||||
"NOTES_DIR_abs": os.path.abspath(notes.NOTES_DIR),
|
||||
"exists": os.path.isdir(os.path.abspath(notes.NOTES_DIR)),
|
||||
"writable": os.access(os.path.abspath(notes.NOTES_DIR), os.W_OK),
|
||||
"tool_file": notes.__file__,
|
||||
}
|
||||
try:
|
||||
items = os.listdir(out["NOTES_DIR_abs"])
|
||||
out["files"] = items[:10]
|
||||
out["count"] = len(items)
|
||||
except Exception as e:
|
||||
out["listdir_error"] = f"{type(e).__name__}: {e}"
|
||||
return out
|
||||
'''
|
||||
import base64
|
||||
D = "/storage/emulated/0/Android/data/com.doubao.lynxclone/files/tools"
|
||||
b64 = base64.b64encode(probe.encode("utf-8")).decode()
|
||||
w = ("import base64,os;"
|
||||
"open(os.path.join('%s','probe_notes.py'),'wb').write(base64.b64decode('%s'));"
|
||||
"print('ok')" % (D, b64))
|
||||
call("/api/tools/run", {"name": "python_run", "args": {"code": w, "timeout": 30}})
|
||||
import time
|
||||
time.sleep(1)
|
||||
call("/api/tools", None, "GET")
|
||||
r = call("/api/tools/run", {"name": "probe_notes", "args": {}})
|
||||
print(" ", json.dumps((r or {}).get("result"), ensure_ascii=False, indent=1)[:900])
|
||||
153
scripts/probe-phone-ops.py
Normal file
153
scripts/probe-phone-ops.py
Normal file
@@ -0,0 +1,153 @@
|
||||
"""测三个"操作手机"的工具:读通知 / 开 App / 调音量。
|
||||
|
||||
★ 这三个都属于"会真的动手机"的能力,所以除了正常路径,
|
||||
重点测**失败路径**:权限没开、App 不存在、系统拒绝改音量。
|
||||
这些必须**如实报错**,不能假装成功,也不能返回一个看着正常的空结果。
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
URL = "http://127.0.0.1:15199"
|
||||
fails = []
|
||||
|
||||
|
||||
def call(path, payload=None, method="POST", timeout=90):
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
|
||||
req = urllib.request.Request(
|
||||
URL + path, data=data, method=method,
|
||||
headers={"Content-Type": "application/json; charset=utf-8"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
return json.loads(e.read().decode("utf-8", "replace"))
|
||||
|
||||
|
||||
def tool(name, args):
|
||||
"""跑一个工具。
|
||||
|
||||
★ 返回的是**顶层的 {ok, result} 或 {ok:false, error}**,
|
||||
不是只有 result —— 第一版测试脚本只看了 result,于是工具抛错时
|
||||
拿到空 dict,三条断言全红,看起来像"错误信息没给",
|
||||
其实信息给得挺全(在顶层 error 里)。
|
||||
测试脚本必须按**真实响应形状**取值。
|
||||
"""
|
||||
return call("/api/tools/run", {"name": name, "args": args})
|
||||
|
||||
|
||||
def tool_err(r):
|
||||
"""从工具响应里取错误文本(顶层 error 或 result.error)"""
|
||||
if not isinstance(r, dict):
|
||||
return ""
|
||||
if r.get("error"):
|
||||
return str(r["error"])
|
||||
return str((r.get("result") or {}).get("error") or "")
|
||||
|
||||
|
||||
def check(cond, label, detail=""):
|
||||
print(f" {'✓' if cond else '✗'} {label}" + (f" {detail}" if detail else ""))
|
||||
if not cond:
|
||||
fails.append(label)
|
||||
|
||||
|
||||
print("=== 0. 三个工具都被发现了吗 ===")
|
||||
tools = call("/api/tools", None, "GET")
|
||||
py = tools.get("python") or tools.get("tools") or []
|
||||
if isinstance(py, dict):
|
||||
py = py.get("python") or []
|
||||
names = [t.get("name") for t in py if isinstance(t, dict)]
|
||||
for n in ("notifications", "apps", "volume"):
|
||||
check(n in names, f"{n} 被内核发现")
|
||||
|
||||
print("\n=== 1. 音量:读 ===")
|
||||
r = tool("volume", {"action": "get"})
|
||||
res = (r or {}).get("result") or {}
|
||||
streams = res.get("streams") or []
|
||||
check(bool(streams), f"读出 {len(streams)} 个音量流")
|
||||
for s in streams[:3]:
|
||||
print(f" {s.get('stream')}: {s.get('percent')}% ({s.get('level')})")
|
||||
|
||||
print("\n=== 2. 音量:写(set 百分比 → 自动换算成档位)===")
|
||||
r = tool("volume", {"action": "set", "stream": "music", "mode": "set", "value": 40})
|
||||
res = (r or {}).get("result") or {}
|
||||
if res.get("error"):
|
||||
print(" (这台机器不让改媒体音量:", str(res["error"])[:80], ")")
|
||||
else:
|
||||
check(res.get("percent") is not None, f"设置后读到 {res.get('percent')}%")
|
||||
check(abs(int(res.get("percent") or 0) - 40) <= 10,
|
||||
"百分比落在 40% 附近(说明换算对了)",
|
||||
f"实际 {res.get('percent')}%")
|
||||
|
||||
print("\n=== 3. 音量:up / mute / unmute ===")
|
||||
r = tool("volume", {"action": "set", "stream": "music", "mode": "up"})
|
||||
u = (r or {}).get("result") or {}
|
||||
check(u.get("before") is not None and u.get("current") is not None,
|
||||
"up 有前后值", f"{u.get('before')} -> {u.get('current')}")
|
||||
r = tool("volume", {"action": "set", "stream": "music", "mode": "mute"})
|
||||
m = (r or {}).get("result") or {}
|
||||
check(m.get("current") == 0 or bool(str(m.get("error") or "")), "mute 生效或如实报错",
|
||||
f"current={m.get('current')} err={str(m.get('error'))[:40]}")
|
||||
r = tool("volume", {"action": "set", "stream": "music", "mode": "unmute"})
|
||||
n = (r or {}).get("result") or {}
|
||||
check(int(n.get("current") or 0) > 0 or bool(str(n.get("error") or "")),
|
||||
"unmute 恢复到非零", f"current={n.get('current')}")
|
||||
|
||||
print("\n=== 4. App:列出来 ===")
|
||||
r = tool("apps", {"action": "list"})
|
||||
res = (r or {}).get("result") or {}
|
||||
check((res.get("total_installed") or 0) > 0, f"装了 {res.get('total_installed')} 个 App")
|
||||
for a in (res.get("apps") or [])[:4]:
|
||||
print(f" {a.get('label')} ({a.get('package')})")
|
||||
|
||||
print("\n=== 5. App:找一个真实存在的 ===")
|
||||
r = tool("apps", {"action": "find", "name": "设置"})
|
||||
res = (r or {}).get("result") or {}
|
||||
found = res.get("apps") or []
|
||||
check(bool(found), f"找到 {len(found)} 个含「设置」的",
|
||||
(found[0].get("label") if found else ""))
|
||||
|
||||
print("\n=== 6. ★ App:找不到时要**如实报错并给相近的名字** ===")
|
||||
r = tool("apps", {"action": "open", "name": "这个App绝对不存在xyz"})
|
||||
check(r.get("ok") is False, "没有假装打开成功", f"ok={r.get('ok')}")
|
||||
err = tool_err(r)
|
||||
check("没找到" in err, "错误说清了'没找到'", err[:90])
|
||||
check("action=" in err, "错误里给了下一步(说了该调哪个 action)", err[:110])
|
||||
|
||||
print("\n=== 7. ★ 通知:权限没开时必须报错(不是空列表)===")
|
||||
r = tool("notifications", {"action": "access"})
|
||||
res = (r or {}).get("result") or {}
|
||||
granted = bool(res.get("granted"))
|
||||
print(f" 通知使用权:{'已开' if granted else '没开'}")
|
||||
if not granted:
|
||||
r2 = tool("notifications", {"action": "list"})
|
||||
check(r2.get("ok") is False, "没权限时**工具失败**(不是返回空列表)")
|
||||
err2 = tool_err(r2)
|
||||
check("通知使用权" in err2, "错误说清了是权限问题", err2[:80])
|
||||
check("设置" in err2 and "通知使用权" in err2, "错误里说了怎么开(设置路径)",
|
||||
err2[-90:])
|
||||
else:
|
||||
r2 = tool("notifications", {"action": "list"})
|
||||
res2 = (r2 or {}).get("result") or {}
|
||||
check("notifications" in res2, f"有权限 → 读到 {res2.get('count')} 条")
|
||||
|
||||
print("\n=== 8. 通知:open_settings 能跳设置页 ===")
|
||||
r = tool("notifications", {"action": "open_settings"})
|
||||
res = (r or {}).get("result") or {}
|
||||
check(bool(res.get("opened")) or bool(res.get("error")), "跳转设置页(或如实报错)",
|
||||
str(res)[:80])
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"❌ {len(fails)} 项不合格:")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
sys.exit(1)
|
||||
print("✅ 全部通过")
|
||||
@@ -18,7 +18,8 @@
|
||||
"b03b5b99dbd83587"
|
||||
],
|
||||
"notes.py": [
|
||||
"f2255c693b2401b5"
|
||||
"f2255c693b2401b5",
|
||||
"7da481daace71368"
|
||||
],
|
||||
"now.py": [
|
||||
"eb0c37b5afc1dd8b"
|
||||
@@ -47,5 +48,14 @@
|
||||
],
|
||||
"send_message.py": [
|
||||
"f133c98b6325f3ac"
|
||||
],
|
||||
"apps.py": [
|
||||
"7215ae7bc60f6f83"
|
||||
],
|
||||
"notifications.py": [
|
||||
"3e8ba8ae55b80019"
|
||||
],
|
||||
"volume.py": [
|
||||
"255939a9c89f51a2"
|
||||
]
|
||||
}
|
||||
|
||||
113
tools/apps.py
Normal file
113
tools/apps.py
Normal file
@@ -0,0 +1,113 @@
|
||||
"""打开手机上的 App。
|
||||
|
||||
## 两段式:先找、再开
|
||||
|
||||
`action=find` 按名字找(返回包名 + Activity)
|
||||
`action=open` 直接开。可以传 `name`(模糊匹配,一次搞定),
|
||||
也可以传 `package` + `activity`(从上一步 find 拿到的,更准)
|
||||
|
||||
★ 为什么 `open` 也支持只传 name:
|
||||
大多数情况模型就是想说"打开微信",让它先 find 再 open 是两次工具调用、
|
||||
多一轮往返。直接开,找不到时错误信息里**带上相近的名字**,
|
||||
它就能自己改一个再试 —— 比回一句干巴巴的"失败"有用得多。
|
||||
|
||||
## ★ 名字必须模糊匹配
|
||||
|
||||
用户说"打开抖音",但 App 列表里的名字可能是"抖音"、"抖音极速版"。
|
||||
模型说"打开微信",列表里是"WeChat"(有些 ROM 的英文名)。
|
||||
所以匹配顺序是:包名完全相同 → 名字完全相同 → 名字前缀 → 包含 → 包名包含。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
from _ui_bridge import call_device # noqa: E402
|
||||
|
||||
TOOL = {
|
||||
"name": "apps",
|
||||
"description": (
|
||||
"打开手机上的 App,或列出装了哪些 App。"
|
||||
"\n\n用法:"
|
||||
"\n· action=open(默认)—— 打开一个 App。传 name(名字,模糊匹配即可,"
|
||||
"比如「微信」「抖音」);或者传 package + activity(更准,从上一步 find 拿到的)。"
|
||||
"\n· action=find —— 按名字找,返回匹配到的 App(名字 + 包名)"
|
||||
"\n· action=list —— 列出装了的 App。传 query 过滤(不传就列一部分)"
|
||||
"\n\n★ 找不到时错误里会带相近的名字,照着改一个再试,别反复用同一个错名字。"
|
||||
"\n★ 打开 App 会让它**跑到前台盖住当前画面**,所以只在用户明确要求时才用。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["open", "find", "list"],
|
||||
"description": "要做的事,默认 open",
|
||||
},
|
||||
"name": {"type": "string", "description": "App 名字(模糊匹配),open/find 用"},
|
||||
"package": {"type": "string", "description": "包名,如 com.tencent.mm(更准)"},
|
||||
"activity": {"type": "string", "description": "Activity 全名,配合 package 用"},
|
||||
"query": {"type": "string", "description": "action=list 时的过滤词"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def run(args: dict) -> dict:
|
||||
action = str(args.get("action") or "open").strip().lower()
|
||||
|
||||
if action == "list":
|
||||
res = call_device({"action": "apps", "query": str(args.get("query") or "")})
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
if res.get("error"):
|
||||
raise RuntimeError(str(res["error"]))
|
||||
return {
|
||||
"total_installed": res.get("count", 0),
|
||||
"shown": len(res.get("apps") or []),
|
||||
"apps": res.get("apps") or [],
|
||||
}
|
||||
|
||||
if action == "find":
|
||||
name = str(args.get("name") or "").strip()
|
||||
if not name:
|
||||
raise ValueError("find 需要 name")
|
||||
# 列表接口支持过滤,直接用它
|
||||
res = call_device({"action": "apps", "query": name})
|
||||
if res.get("error"):
|
||||
raise RuntimeError(str(res["error"]))
|
||||
apps = res.get("apps") or []
|
||||
if not apps:
|
||||
return {"found": 0, "note": f"没有名字或包名含「{name}」的 App"}
|
||||
return {"found": len(apps), "apps": apps}
|
||||
|
||||
# open
|
||||
payload = {
|
||||
"action": "app_launch",
|
||||
"name": str(args.get("name") or "").strip(),
|
||||
"package": str(args.get("package") or "").strip(),
|
||||
"activity": str(args.get("activity") or "").strip(),
|
||||
}
|
||||
if not payload["name"] and not payload["package"]:
|
||||
raise ValueError("open 至少需要 name 或 package")
|
||||
|
||||
res = call_device(payload)
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
if res.get("error"):
|
||||
# ★ 把 hint(相近的名字)一起抛出去 —— 模型据此改一个再试,
|
||||
# 比只回"失败"有用得多
|
||||
hint = res.get("hint") or ""
|
||||
raise RuntimeError(f"{res['error']}。{hint}".strip())
|
||||
|
||||
return {
|
||||
"opened": True,
|
||||
"app": res.get("label") or payload["name"] or payload["package"],
|
||||
"package": res.get("package") or payload["package"],
|
||||
"note": "App 已经切到前台了。",
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
120
tools/notes.py
120
tools/notes.py
@@ -1,19 +1,106 @@
|
||||
"""笔记工具:把重要信息写进本地文件,或读回来。这就是最朴素的"记忆"。"""
|
||||
"""笔记工具:把重要信息写进本地文件,或读回来。这就是最朴素的"记忆"。
|
||||
|
||||
## ★ 笔记存哪儿(改过一次,很重要)
|
||||
|
||||
以前是 `工具文件/../data/notes` —— **相对工具自己算的**。
|
||||
在安卓上工具落在 `/storage/emulated/0/Android/data/<包名>/files/tools/`,
|
||||
于是笔记写到 `.../files/data/notes`:**App 的外部私有目录**。
|
||||
那个地方用户用文件管理器根本翻不到(Android 11+ 直接隐藏),
|
||||
而且**卸载 App 就一起删了**。
|
||||
|
||||
用户的原话是"notes 用户要能查看",所以现在:
|
||||
|
||||
1. 优先用内核给的路径(`paths.get().notes_dir` = `<数据目录>/notes`),
|
||||
和 conversations / screens 那些放一起,位置统一、持久
|
||||
2. **自动把老位置的文件搬过来**(只搬一次,搬完留个 `.migrated` 标记),
|
||||
不然用户以前记的笔记就"不见了"
|
||||
3. 电脑端没有内核的 paths 模块时,退回老算法(那边本来就是 repo 里的 tools/ 下)
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
|
||||
NOTES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data", "notes")
|
||||
# 老位置:工具文件旁边的 ../data/notes(安卓上会落到 App 外部私有目录)
|
||||
_LEGACY_DIR = os.path.abspath(
|
||||
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data", "notes")
|
||||
)
|
||||
|
||||
|
||||
def notes_dir() -> str:
|
||||
"""
|
||||
笔记目录。
|
||||
|
||||
★ 每次调用现算,不在模块顶层算成常量 —— 内核的 paths 是运行时初始化的,
|
||||
顶层算会拿到还没配置好的默认值(那个默认值在安卓上是相对路径)。
|
||||
"""
|
||||
try:
|
||||
import paths # noqa: PLC0415 - 电脑端没有这个模块
|
||||
|
||||
d = paths.get().notes_dir
|
||||
if d:
|
||||
return d
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return _LEGACY_DIR
|
||||
|
||||
|
||||
def _migrate_once(target: str) -> None:
|
||||
"""
|
||||
把老位置的笔记搬到新位置(只做一次)。
|
||||
|
||||
★ 为什么必须搬:用户在老版本里记的笔记是真实数据 ——
|
||||
换了目录之后那些文件还在老地方躺着,但 list/read 都看不到了,
|
||||
表现就是"我记的笔记全没了"。这类"改路径把用户数据弄丢"的事最不该发生。
|
||||
"""
|
||||
if os.path.abspath(target) == _LEGACY_DIR:
|
||||
return # 本来就是老位置(电脑端),不用搬
|
||||
marker = os.path.join(target, ".migrated")
|
||||
if os.path.exists(marker):
|
||||
return
|
||||
try:
|
||||
os.makedirs(target, exist_ok=True)
|
||||
if os.path.isdir(_LEGACY_DIR):
|
||||
moved = 0
|
||||
for name in os.listdir(_LEGACY_DIR):
|
||||
if not name.endswith(".md"):
|
||||
continue
|
||||
src = os.path.join(_LEGACY_DIR, name)
|
||||
dst = os.path.join(target, name)
|
||||
if os.path.exists(dst):
|
||||
continue # 不覆盖同名的(新位置已有)
|
||||
try:
|
||||
shutil.move(src, dst)
|
||||
moved += 1
|
||||
except Exception: # noqa: BLE001
|
||||
# 跨设备 move 可能失败,退回复制
|
||||
try:
|
||||
shutil.copy2(src, dst)
|
||||
os.remove(src)
|
||||
moved += 1
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
if moved:
|
||||
print(f'[notes] 已把 {moved} 条老笔记搬到新目录', file=sys.stderr, flush=True)
|
||||
with open(marker, "w", encoding="utf-8") as fh:
|
||||
fh.write("ok\n")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[notes] 迁移失败:{exc}', file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
TOOL = {
|
||||
"name": "notes",
|
||||
"description": "本地笔记:action=save 写笔记,action=list 列出全部,action=read 读某一条,action=search 关键词搜索。适合记录用户偏好、待办、结论。",
|
||||
"description": (
|
||||
"本地笔记:action=save 写笔记,action=list 列出全部,action=read 读某一条,"
|
||||
"action=search 关键词搜索。适合记录用户偏好、待办、结论。"
|
||||
"\n★ 用户能在 App 里「笔记」页面看到、也能删,所以别往里写不该让他看到的内部草稿。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -28,7 +115,10 @@ TOOL = {
|
||||
|
||||
|
||||
def ensure_dir():
|
||||
os.makedirs(NOTES_DIR, exist_ok=True)
|
||||
d = notes_dir()
|
||||
os.makedirs(d, exist_ok=True)
|
||||
_migrate_once(d)
|
||||
return d
|
||||
|
||||
|
||||
def slug(title):
|
||||
@@ -37,35 +127,37 @@ def slug(title):
|
||||
|
||||
|
||||
def run(args):
|
||||
ensure_dir()
|
||||
d = ensure_dir()
|
||||
action = str(args.get("action", "list")).lower()
|
||||
|
||||
if action == "save":
|
||||
title = str(args.get("title", "")).strip() or "未命名"
|
||||
content = str(args.get("content", ""))
|
||||
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||
path = os.path.join(NOTES_DIR, f"{stamp}-{slug(title)}.md")
|
||||
path = os.path.join(d, f"{stamp}-{slug(title)}.md")
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
fh.write(f"# {title}\n\n{content}\n")
|
||||
return {"saved": os.path.basename(path), "title": title, "chars": len(content)}
|
||||
|
||||
if action == "list":
|
||||
files = sorted(os.listdir(NOTES_DIR), reverse=True)
|
||||
files = sorted(os.listdir(d), reverse=True)
|
||||
items = []
|
||||
for name in files[:50]:
|
||||
full = os.path.join(NOTES_DIR, name)
|
||||
if not name.endswith(".md"):
|
||||
continue
|
||||
full = os.path.join(d, name)
|
||||
with open(full, encoding="utf-8") as fh:
|
||||
first = fh.readline().strip().lstrip("# ")
|
||||
items.append({"file": name, "title": first, "bytes": os.path.getsize(full)})
|
||||
return {"count": len(files), "notes": items}
|
||||
return {"count": len([f for f in files if f.endswith(".md")]), "notes": items}
|
||||
|
||||
if action == "read":
|
||||
name = str(args.get("title") or args.get("query") or "").strip()
|
||||
files = sorted(os.listdir(NOTES_DIR), reverse=True)
|
||||
files = [f for f in sorted(os.listdir(d), reverse=True) if f.endswith(".md")]
|
||||
hit = next((f for f in files if name and name in f), None)
|
||||
if not hit:
|
||||
return {"ok": False, "error": f"没找到匹配 {name} 的笔记"}
|
||||
with open(os.path.join(NOTES_DIR, hit), encoding="utf-8") as fh:
|
||||
with open(os.path.join(d, hit), encoding="utf-8") as fh:
|
||||
return {"file": hit, "content": fh.read()[:4000]}
|
||||
|
||||
if action == "search":
|
||||
@@ -73,8 +165,10 @@ def run(args):
|
||||
if not query:
|
||||
raise ValueError("search 需要 query")
|
||||
hits = []
|
||||
for name in sorted(os.listdir(NOTES_DIR), reverse=True):
|
||||
with open(os.path.join(NOTES_DIR, name), encoding="utf-8") as fh:
|
||||
for name in sorted(os.listdir(d), reverse=True):
|
||||
if not name.endswith(".md"):
|
||||
continue
|
||||
with open(os.path.join(d, name), encoding="utf-8") as fh:
|
||||
text = fh.read()
|
||||
if query in text:
|
||||
idx = text.index(query)
|
||||
|
||||
156
tools/notifications.py
Normal file
156
tools/notifications.py
Normal file
@@ -0,0 +1,156 @@
|
||||
"""读手机上的通知。
|
||||
|
||||
## 这是三个"动手机"的工具之一(另两个:开 App、调音量)
|
||||
|
||||
## ★ 隐私:读到的内容可能很敏感
|
||||
|
||||
通知里有验证码、银行短信、私信 —— 这是**整个 App 里最隐私的一类数据**。
|
||||
所以:
|
||||
|
||||
· 只在**内存**里留最近 200 条,不落盘(进程一死就没了)。
|
||||
写磁盘意味着卸载前一直躺着,也可能被别的工具读到。
|
||||
· 用户要在系统设置里**手动开"通知使用权"**才能读到。
|
||||
Android 没有这个权限的运行时申请弹窗 —— 这是唯一合法的路。
|
||||
· 读之前一定先查权限,没开就**明确报错**(见下)。
|
||||
|
||||
## ★ 权限没开时返回错误,不是空列表
|
||||
|
||||
返回空列表的话模型会说"你最近没有通知" —— 那是**错的**
|
||||
(明明有好几条,只是我们读不到)。用户会被误导,
|
||||
而且他不会想到"原来是要去开个权限"。
|
||||
|
||||
所以这里返回一个带 `hint` 的错误,模型就能照着告诉用户怎么开。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
from _ui_bridge import call_device # noqa: E402
|
||||
|
||||
TOOL = {
|
||||
"name": "notifications",
|
||||
"description": (
|
||||
"读手机上的通知(最近收到的、以及已经被划掉的)。"
|
||||
"\n\n用法:"
|
||||
"\n· action=list(默认)—— 列出最近的通知。"
|
||||
"query 可以按关键词过滤(标题/正文/App 名),limit 默认 20、最多 200。"
|
||||
"\n· action=alive —— 只看**还挂在通知栏上**的(已经被用户划掉的不算)"
|
||||
"\n· action=access —— 查有没有「通知使用权」"
|
||||
"\n· action=open_settings —— 跳到系统的通知使用权设置页,让用户去开"
|
||||
"\n· action=clear —— 把已经读到的记录清掉(内存里那份)"
|
||||
"\n\n★ 第一次用之前用户必须先手动开「通知使用权」(安卓不给运行时申请)。"
|
||||
"\n 没开的时候本工具会返回错误 + 怎么开的提示 —— 请照着念给用户,"
|
||||
"\n 别自己编步骤。开了之后才能读到东西。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["list", "alive", "access", "open_settings", "clear"],
|
||||
"description": "要做的事,默认 list",
|
||||
},
|
||||
"query": {"type": "string", "description": "按关键词过滤(可选)"},
|
||||
"limit": {"type": "number", "description": "最多几条,默认 20,最多 200"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def run(args: dict) -> dict:
|
||||
action = str(args.get("action") or "list").strip().lower()
|
||||
|
||||
if action == "open_settings":
|
||||
res = call_device({"action": "notification_settings"})
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
if res.get("error"):
|
||||
raise RuntimeError(str(res["error"]))
|
||||
return {
|
||||
"opened": True,
|
||||
"note": (
|
||||
"已经跳到系统的「通知使用权」设置页。"
|
||||
"请让用户在那里找到本 App 并打开开关 —— 开了之后我才能读到通知。"
|
||||
),
|
||||
}
|
||||
|
||||
if action == "access":
|
||||
res = call_device({"action": "notification_access"})
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
granted = bool(res.get("granted"))
|
||||
out = {"granted": granted, "kept": res.get("kept", 0)}
|
||||
if not granted:
|
||||
out["note"] = (
|
||||
"还没开「通知使用权」,读不到任何通知。"
|
||||
"让用户去 设置 → 通知 → 通知使用权 里打开本 App(我也可以调 "
|
||||
"action=open_settings 直接跳过去)。"
|
||||
)
|
||||
return out
|
||||
|
||||
if action == "clear":
|
||||
res = call_device({"action": "notification_clear"})
|
||||
if res.get("error"):
|
||||
raise RuntimeError(str(res["error"]))
|
||||
return {"cleared": True}
|
||||
|
||||
# list / alive
|
||||
payload = {
|
||||
"action": "notifications",
|
||||
"query": str(args.get("query") or ""),
|
||||
"onlyAlive": action == "alive",
|
||||
}
|
||||
try:
|
||||
limit = int(args.get("limit") or 20)
|
||||
except (TypeError, ValueError):
|
||||
limit = 20
|
||||
payload["limit"] = max(1, min(200, limit))
|
||||
|
||||
res = call_device(payload)
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
|
||||
# ★ 权限没开:把错误和"怎么开"一起抛回去。
|
||||
# 抛异常而不是返回空列表 —— 空列表会让模型说"你没有通知",那是错的。
|
||||
if res.get("error"):
|
||||
hint = res.get("hint") or ""
|
||||
raise RuntimeError(f"{res['error']}。{hint}".strip())
|
||||
|
||||
items = res.get("notifications") or []
|
||||
# 顺手整理成模型好读的形状:把时间戳变成"几分钟前"
|
||||
simplified = []
|
||||
import time
|
||||
now_ms = int(time.time() * 1000)
|
||||
for n in items:
|
||||
at = int(n.get("at") or 0)
|
||||
ago = ""
|
||||
if at:
|
||||
secs = max(0, (now_ms - at) // 1000)
|
||||
if secs < 60:
|
||||
ago = "刚刚"
|
||||
elif secs < 3600:
|
||||
ago = f"{secs // 60} 分钟前"
|
||||
elif secs < 86400:
|
||||
ago = f"{secs // 3600} 小时前"
|
||||
else:
|
||||
ago = f"{secs // 86400} 天前"
|
||||
simplified.append({
|
||||
"app": n.get("app") or n.get("package") or "",
|
||||
"title": n.get("title") or "",
|
||||
"text": n.get("text") or "",
|
||||
"ago": ago,
|
||||
# 已经被划掉的也留着 —— 用户问"刚才那条验证码呢"时它早就没了
|
||||
"gone": bool(n.get("removed")),
|
||||
})
|
||||
|
||||
return {
|
||||
"count": len(simplified),
|
||||
"only_alive": action == "alive",
|
||||
"notifications": simplified,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
147
tools/volume.py
Normal file
147
tools/volume.py
Normal file
@@ -0,0 +1,147 @@
|
||||
"""调手机音量。
|
||||
|
||||
## 六种音量流分开调
|
||||
|
||||
媒体(music) / 铃声(ring) / 闹钟(alarm) / 通话(call) / 系统(system) / 通知(notification)
|
||||
|
||||
安卓把它们**分开**的 —— "把声音调小"到底指哪个?媒体和铃声是两回事。
|
||||
所以这个工具要求指定 stream(默认 music,最常用那个)。
|
||||
|
||||
## ★ 改完必须回读确认
|
||||
|
||||
勿扰模式(DND)开着的时候,系统会**拒绝**改铃声/通知音量,而且**不报错** ——
|
||||
静默失败。所以这里改完立刻回读,不一致就如实说"系统没接受这次调整"。
|
||||
|
||||
不回读的话,模型会告诉用户"已经调好了",而用户发现根本没变 ——
|
||||
比直接说"没调成"糟得多。
|
||||
|
||||
## 两种表达方式都给
|
||||
|
||||
· 想"调到一半" → mode=set + value=50(按百分比)
|
||||
· 想"加一格" → mode=up(按原始档位)
|
||||
|
||||
value 在 set 时是百分比,在 up/down 时是步数 —— 这个区别写在参数说明里了,
|
||||
因为搞混的话"加 1"会变成"加到 1%"。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _protocol import serve # noqa: E402
|
||||
from _ui_bridge import call_device # noqa: E402
|
||||
|
||||
TOOL = {
|
||||
"name": "volume",
|
||||
"description": (
|
||||
"读或调手机音量。"
|
||||
"\n\n· action=get(默认)—— 读所有音量流的当前值"
|
||||
"\n· action=set —— 调整。用 stream 指定调哪个,mode 指定怎么调:"
|
||||
"\n stream: music(媒体,默认)/ ring(铃声)/ alarm(闹钟)/ "
|
||||
"call(通话)/ system / notification"
|
||||
"\n mode: set(设成某个值)/ up(加)/ down(减)/ mute(静音)/ unmute(取消静音)"
|
||||
"\n value: mode=set 时是**百分比 0-100**;mode=up/down 时是**档数**(默认 1)"
|
||||
"\n\n★ 安卓把媒体音量和铃声音量**分开**的 —— 用户说'把声音调小'时,"
|
||||
"\n 先想清楚他说的是哪个;拿不准就调 music 并说一句你调的是媒体音量。"
|
||||
"\n★ 勿扰模式开着时系统会拒绝改铃声/通知音量,这时候会明确告诉你没改成功。"
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["get", "set"],
|
||||
"description": "要做的事,默认 get",
|
||||
},
|
||||
"stream": {
|
||||
"type": "string",
|
||||
"enum": ["music", "ring", "alarm", "call", "system", "notification"],
|
||||
"description": "调哪个音量流,默认 music",
|
||||
},
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"enum": ["set", "up", "down", "mute", "unmute"],
|
||||
"description": "怎么调,默认 set",
|
||||
},
|
||||
"value": {
|
||||
"type": "number",
|
||||
"description": "mode=set 时是百分比(0-100);mode=up/down 时是档数(默认1)",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def run(args: dict) -> dict:
|
||||
action = str(args.get("action") or "get").strip().lower()
|
||||
|
||||
if action == "get":
|
||||
res = call_device({"action": "volume"})
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
state = res.get("state") or {}
|
||||
streams = state.get("streams") or []
|
||||
# 整理成模型好读的形状:一行一个流
|
||||
out = []
|
||||
for s in streams:
|
||||
out.append({
|
||||
"stream": s.get("stream"),
|
||||
"percent": s.get("percent"),
|
||||
"level": f"{s.get('current')}/{s.get('max')}",
|
||||
"muted": s.get("muted"),
|
||||
})
|
||||
return {"streams": out}
|
||||
|
||||
stream = str(args.get("stream") or "music").strip().lower()
|
||||
mode = str(args.get("mode") or "set").strip().lower()
|
||||
try:
|
||||
raw = args.get("value")
|
||||
value = int(raw) if raw is not None else 1
|
||||
except (TypeError, ValueError):
|
||||
value = 1
|
||||
|
||||
if mode in ("up", "down") and value <= 0:
|
||||
value = 1
|
||||
|
||||
# ★ set 时 value 是百分比,要先换算成档位 ——
|
||||
# 安卓的原始值是按流的 max 算的(媒体流通常 15 档,铃声 7 档),
|
||||
# 直接把 50 当原始值会撞到上限。
|
||||
requested = value
|
||||
if mode == "set":
|
||||
# 先读一遍拿到 max,再换算
|
||||
st = call_device({"action": "volume"})
|
||||
if st.get("error"):
|
||||
raise RuntimeError(str(st["error"]))
|
||||
streams = ((st.get("state") or {}).get("streams")) or []
|
||||
cur = next((s for s in streams if s.get("stream") == stream), None)
|
||||
mx = int((cur or {}).get("max") or 15)
|
||||
pct = max(0, min(100, value))
|
||||
requested = round(pct * mx / 100.0)
|
||||
|
||||
res = call_device({
|
||||
"action": "volume_set",
|
||||
"stream": stream,
|
||||
"mode": mode,
|
||||
"value": requested,
|
||||
})
|
||||
if res.get("unavailable"):
|
||||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||||
if res.get("error"):
|
||||
# ★ 系统拒绝(多半是勿扰)—— 如实抛出去,别假装成功
|
||||
raise RuntimeError(str(res["error"]))
|
||||
|
||||
out = {
|
||||
"stream": res.get("stream"),
|
||||
"before": res.get("before"),
|
||||
"current": res.get("current"),
|
||||
"max": res.get("max"),
|
||||
"percent": res.get("percent"),
|
||||
}
|
||||
if mode == "set":
|
||||
out["requested_percent"] = requested if mode != "set" else value
|
||||
out["note"] = f"「{res.get('stream')}」现在是 {res.get('percent')}%。"
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve(TOOL, run)
|
||||
Reference in New Issue
Block a user