笔记用户可查看 + 三个操作手机的工具(通知/开App/音量)(v2.0.41)

用户三条需求:
  ① "notes 用户要能查看"
  ② "加个读取手机通知的工具"
  ③ "打开手机 app 和调整手机音量的工具"

## ① notes 用户能查看了

查下去发现不只是"没界面",还有两个真问题:

**问题一:笔记写到了用户看不到的地方。**
notes.py 自己算路径 `工具文件/../data/notes` —— 在安卓上落到
**App 的外部私有目录**(`/storage/emulated/0/Android/data/<包名>/files/data/notes`)。
那地方用户用文件管理器根本翻不到(Android 11+ 直接隐藏),
而且**卸载 App 就一起删了**。

**问题二:笔记只有 AI 能读写。**
AI 说"我记下来了",用户没有任何办法确认它记了什么、记错没有、删掉记错的。
这类"AI 替你做事但你无法查看"的功能,用户不会信任。

修法:
 · 路径改用内核的 `<数据目录>/notes`(和 conversations / screens 放一起)
 · **自动迁移老位置的笔记**(只搬一次,搬完留 `.migrated` 标记)——
   不搬的话用户以前记的笔记就"不见了",这类"改路径把用户数据弄丢"最不该发生
 · 迁移放在 `store._notes_dir()` 里,**任何一次读笔记都会先保证迁移过**。
   第一版只在 notes 工具被调用时才迁移,于是用户装完新版**先打开笔记页**
   会看到空列表 —— 以为笔记全丢了(实测踩到)
 · 新增 `/api/notes` 列表 / `GET /api/notes/<file>` 读 / `DELETE` 删
 · 界面:抽屉 →「笔记」→ 列表(标题 + 预览 + 时间)→ 点开看全文(markdown 渲染)、可复制、可删

## ② 读手机通知

★ Android **没有**"读取通知"的运行时权限 —— 唯一合法的路是让用户手动去
「设置 → 通知 → 通知使用权」勾上。所以加了个 `NotificationListenerService`。

几个刻意的决定:
 · **只在内存里留最近 200 条,不落盘**。通知里有验证码、银行短信、私信 ——
   是整个 App 最隐私的一类数据。写磁盘意味着卸载前一直躺着,也可能被别的工具读到。
 · **已划掉的也留着**(标 `gone:true`)。用户问"刚才那条验证码呢"时它早被划走了,
   删了就直接查不到。
 · **权限没开时返回错误,不是空列表**。返回空列表模型会说"你没有通知"——
   那是**错的**(明明有几条,只是我们读不到),用户会被误导。错误里带上
   "怎么开"的完整步骤,模型照着念就行。
 · `action=open_settings` 直接跳那个设置页(安卓不给申请弹窗,只能跳)。

## ③ 打开 App + 调音量

**打开 App**:两段式(`find` 找 / `open` 开),`open` 也支持只传名字。
 · Manifest 里加了 `<queries>` LAUNCHER intent —— Android 11+ 不声明这条,
   `queryIntentActivities` 只返回空列表,表现是"装了 8 个 App 一个都找不到"
 · 匹配顺序:包名完全相同 → 名字完全相同 → 前缀 → 包含 → 包名包含
 · 找不到时错误里**带上相近的名字**,模型能自己改一个再试

**调音量**:六种流分开(music/ring/alarm/call/system/notification)。
 · `mode=set` 的 value 是**百分比**,工具侧先读 max 再换算成档位 ——
   安卓原始值按流的 max 算(媒体通常 15 档、铃声 7 档),
   直接把 50 当原始值会撞上限
 · 改完**必须回读确认**:勿扰模式开着时系统会**拒绝**改铃声/通知音量而且**不报错**
   (静默失败)。不回读的话模型会告诉用户"调好了"而实际没变 —— 比说"没调成"糟得多

## 实测(Android 14 x86_64)

音量:读出 6 个流;set 40% → 实际 40%(换算对了);up 6→7;mute→0;unmute→7 ✓
App:列出 8 个;找到「设置」;不存在的名字 → 如实报错 + 指路 ✓
通知:`cmd notification post` 发一条 → 内核读到
      `{app:"Shell", title:"测试标题", text:"…12345", ago:"刚刚", gone:false}` ✓
笔记:老位置的文件被搬到新位置,界面显示 1 条、内容正确 ✓

## 顺带修的

 · `apps` 工具的"找不到"提示里写的是 `action=app_list` —— **那个 action 不存在**
   (实际叫 `list`),模型照着调会失败。改成 `action=list`。
 · 写测试脚本时踩到:工具抛错时响应是**顶层** `{ok:false, error}`,不是
   `{result:{error}}`。第一版脚本只看了 result,于是三条断言全红,
   看起来像"错误信息没给",其实给得挺全。测试脚本必须按真实响应形状取值。
This commit is contained in:
doubao
2026-10-15 15:38:00 +08:00
parent b1dd740b0d
commit 5e95e17c3e
20 changed files with 1966 additions and 19 deletions

View File

@@ -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
View 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)

View File

@@ -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
View 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
View 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)